diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index f843c69a3..13d50b5e5 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -22,6 +22,7 @@ jobs: env: BF2_PYTHON_OUT: ${{ github.workspace }}/out/ci-python/${{ matrix.arch }} CMAKE_BUILD_PARALLEL_LEVEL: 2 + BF2_RELEASE_RUN: ${{ (github.event_name == 'release' || startsWith(github.ref, 'refs/tags/v')) && 'true' || 'false' }} defaults: run: shell: cmd @@ -39,7 +40,7 @@ jobs: run: | call Code\Build\vsdevcmd.cmd ${{ matrix.arch }} if errorlevel 1 exit /b 1 - cmake --preset msvc-${{ matrix.arch }} -B out/build/ci-${{ matrix.arch }} -DBF2_GAME_DIR:PATH="%GITHUB_WORKSPACE%/out/no-game-content" -DBF2_DICE_PY_LIB:FILEPATH="%BF2_PYTHON_OUT%/dice_py.lib" -DBF2_DICE_PY_DLL:FILEPATH="%BF2_PYTHON_OUT%/dice_py.dll" + cmake --preset msvc-${{ matrix.arch }} -B out/build/ci-${{ matrix.arch }} -DBF2_FRONTIER_DEFAULT_CONTINUE=ON -DBF2_GAME_DIR:PATH="%GITHUB_WORKSPACE%/out/no-game-content" -DBF2_DICE_PY_LIB:FILEPATH="%BF2_PYTHON_OUT%/dice_py.lib" -DBF2_DICE_PY_DLL:FILEPATH="%BF2_PYTHON_OUT%/dice_py.dll" - name: Run x86 engine and editor framework checks if: matrix.arch == 'x86' @@ -54,26 +55,121 @@ jobs: if errorlevel 1 exit /b 1 cmake --build out/build/ci-${{ matrix.arch }} --target ${{ matrix.server }} - # Keep the client/plugin and editor builds sequential within this checkout. - - name: Build the x86 AI library and client with plugins + - name: Build the x86 AI library if: matrix.arch == 'x86' run: | call Code\Build\vsdevcmd.cmd x86 if errorlevel 1 exit /b 1 - cmake --build out/build/ci-x86 --target bf2_aidll bf2_client + cmake --build out/build/ci-x86 --target bf2_aidll + + # [CHOSEN, not recovered] The x64 server depends on and stages the native AI library. + - name: Check the Windows x64 AI exports + if: matrix.arch == 'x64' + run: | + call Code\Build\vsdevcmd.cmd x64 + if errorlevel 1 exit /b 1 + dumpbin /exports out\build\ci-x64\bin_client\aidll.dll > out\build\ci-x64\aidll-exports.txt + if errorlevel 1 exit /b 1 + type out\build\ci-x64\aidll-exports.txt + python -c "import re; from pathlib import Path; text=Path('out/build/ci-x64/aidll-exports.txt').read_text(); names=re.findall(r'^\s+\d+\s+[0-9A-Fa-f]+\s+[0-9A-Fa-f]+\s+(\w+)(?:\s*=\s*\S+)?\s*$', text, re.M); assert sorted(names)==['deinitDll', 'initDll'], names" + if errorlevel 1 exit /b 1 + fc /b out\build\ci-x64\bin_client\aidll.dll out\build\ci-x64\bin_w64ded\aidll.dll + + # RendDX9.dll and TextureAtlasBuilder.dll, and so the client and the editor, build against the + # April 2005 DirectX SDK or, on hosted runners without it, the D3DX fallback (Code/Build/dxsdk.cmd). + # When neither is usable, other runs skip the client (and on x86 the editor) with a notice and leave + # them out of the packages. Release runs fail here instead: the Windows release package carries + # both clients and the editor, and a package without them is no release (docs/ci-releases.md). + - name: Locate the D3DX headers and import library + id: dxsdk + run: | + rem The same call renddx9.cmd and textureatlasbuilder.cmd make: the April 2005 SDK, or + rem without it the D3DX fallback (BF2_D3DX=auto, Code/Build/dxsdk.cmd). + call Code\Build\dxsdk.cmd ${{ matrix.arch }} fallback + if errorlevel 1 ( + if "%BF2_RELEASE_RUN%"=="true" ( + echo ::error title=No D3DX source::Neither the April 2005 DirectX SDK nor the D3DX fallback is usable; the Windows release package needs the ${{ matrix.arch == 'x86' && 'x86 client and editor' || 'x64 client' }}; see docs/ci-releases.md. + exit /b 1 + ) + echo ::notice title=No D3DX source::Neither the April 2005 DirectX SDK nor the D3DX fallback is usable; the ${{ matrix.arch == 'x86' && 'x86 client and editor are' || 'x64 client is' }} not built on this runner. + echo found=false>> "%GITHUB_OUTPUT%" + ) else ( + echo found=true>> "%GITHUB_OUTPUT%" + ) + exit /b 0 + + # Windows ships both clients: x86 (retail's PunkBuster, D3DX and OpenAL from the game folder) and + # x64 (no PunkBuster). Keep the client/plugin and editor builds sequential within this checkout. + - name: Build the ${{ matrix.arch }} client with plugins + if: steps.dxsdk.outputs.found == 'true' + run: | + call Code\Build\vsdevcmd.cmd ${{ matrix.arch }} + if errorlevel 1 exit /b 1 + cmake --build out/build/ci-${{ matrix.arch }} --target bf2_client + + # [CHOSEN, not recovered] OpenAL Soft as both clients' BF2OpenAL.dll, built from the release + # tarball pinned by URL and SHA-256 in Code/Build/build_openal_soft.py (docs/ci-releases.md). + # The cache key is the architecture and that script, so a new pin rebuilds. + - name: Restore the ${{ matrix.arch }} OpenAL Soft build + if: steps.dxsdk.outputs.found == 'true' + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: out/build/ci-${{ matrix.arch }}/openal-soft + key: openal-soft-${{ matrix.arch }}-${{ hashFiles('Code/Build/build_openal_soft.py') }} + + - name: Build OpenAL Soft for the ${{ matrix.arch }} client + if: steps.dxsdk.outputs.found == 'true' + run: | + call Code\Build\vsdevcmd.cmd ${{ matrix.arch }} + if errorlevel 1 exit /b 1 + python Code/Build/build_openal_soft.py --arch ${{ matrix.arch }} --stage-dir out/build/ci-${{ matrix.arch }}/openal-soft --work-dir out/openal-soft-work --client-dir out/build/ci-${{ matrix.arch }}/bin_client - name: Build the x86 editor with its plugins - if: matrix.arch == 'x86' + if: matrix.arch == 'x86' && steps.dxsdk.outputs.found == 'true' run: | call Code\Build\vsdevcmd.cmd x86 if errorlevel 1 exit /b 1 cmake --build out/build/ci-x86 --target bf2_editor + # The real import lists of the packaged client images (both architectures) and of the x86 editor, + # for the job log; no image may import NovintHFX.dll (the Falcon is archived, + # Code/Archive/NovintFalcon). Also the executables' embedded manifests: any requestedExecutionLevel + # disables UAC file virtualization (retail's BF2.exe has no manifest). Printed only, not changed. + - name: List the ${{ matrix.arch }} image imports and manifests + if: steps.dxsdk.outputs.found == 'true' + run: | + call Code\Build\vsdevcmd.cmd ${{ matrix.arch }} + if errorlevel 1 exit /b 1 + set "OUT=out\build\ci-${{ matrix.arch }}" + set "IMAGES="%OUT%\bin_client\BF2.exe" "%OUT%\bin_client\RendDX9.dll" "%OUT%\bin_client\TextureAtlasBuilder.dll" "%OUT%\bin_client\BF2OpenAL.dll"" + set "EXES="%OUT%\bin_client\BF2.exe"" + if "${{ matrix.arch }}"=="x86" set IMAGES=%IMAGES% "%OUT%\bin_editor\BF2Editor.exe" "%OUT%\bin_editor\RendDX9.dll" "%OUT%\bin_editor\TextureAtlasBuilder.dll" + if "${{ matrix.arch }}"=="x86" set EXES=%EXES% "%OUT%\bin_editor\BF2Editor.exe" + for %%I in (%IMAGES%) do ( + echo ===== imports: %%I + dumpbin /nologo /dependents /imports %%I > "%%~dpnxI.imports.txt" + if errorlevel 1 exit /b 1 + type "%%~dpnxI.imports.txt" + findstr /i /c:"NovintHFX" "%%~dpnxI.imports.txt" >nul && (echo ::error title=NovintHFX import::%%~nxI imports NovintHFX.dll& exit /b 1) + if /i "%%~nxI"=="BF2OpenAL.dll" findstr /i /c:"VCRUNTIME" /c:"MSVCP" /c:"api-ms-win-crt-" /c:"ucrtbase" "%%~dpnxI.imports.txt" >nul && (echo ::error title=OpenAL runtime::BF2OpenAL.dll imports the shared MSVC runtime& exit /b 1) + ) + for %%E in (%EXES%) do ( + echo ===== manifest: %%E + mt.exe -nologo "-inputresource:%%~fE;#1" -out:con + if errorlevel 1 echo no embedded manifest resource 1, or mt.exe could not read it + ) + exit /b 0 + # Future Windows signing belongs here, before packaging and checksums. # No signing credentials or signing step are configured yet. + - name: Check packaging fixtures + run: python Code/Tests/test_package_release.py + - name: Package Windows binaries - run: python Code/Build/package_release.py --platform windows-${{ matrix.arch }} --build-dir out/build/ci-${{ matrix.arch }} --output-dir out/packages --revision "%GITHUB_SHA%" --repository "%GITHUB_REPOSITORY%" + run: python Code/Build/package_release.py --platform windows-${{ matrix.arch }} --build-dir out/build/ci-${{ matrix.arch }} --output-dir out/packages --revision "%GITHUB_SHA%" --repository "%GITHUB_REPOSITORY%" ${{ steps.dxsdk.outputs.found != 'true' && (matrix.arch == 'x86' && '--omit client --omit editor' || '--omit client') || '' }} + # The per-role ZIPs (and, with a client, the pinned OpenAL Soft tarball) are CI artifacts; the + # windows-package job assembles the release package from both legs' artifacts. - name: Upload Windows packages uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: @@ -81,6 +177,7 @@ jobs: path: | out/packages/*.zip out/packages/*.sha256 + out/packages/*.tar.bz2 if-no-files-found: error compression-level: 0 retention-days: 14 @@ -99,6 +196,54 @@ jobs: if-no-files-found: ignore retention-days: 7 + # [CHOSEN, not recovered] The Windows release package, openbf2-windows.zip: both clients (x64\, x86\), + # the x86 dedicated server (server\) and the x86 editor (editor\), assembled from the two legs' + # per-role ZIPs after checking their checksums and build-info hashes (Code/Build/package_release.py + # --release windows). Release runs need every component; other runs package what was built, so CI + # stays green without D3DX, and the README and build-info.json name what is missing. + windows-package: + name: Windows package + needs: windows + runs-on: ubuntu-22.04 + timeout-minutes: 15 + env: + BF2_RELEASE_RUN: ${{ (github.event_name == 'release' || startsWith(github.ref, 'refs/tags/v')) && 'true' || 'false' }} + steps: + - name: Check out the event commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.sha }} + persist-credentials: false + + - name: Check packaging fixtures + run: python3 Code/Tests/test_package_release.py + + # One folder per artifact: both legs carry the same pinned OpenAL Soft tarball, and the + # packager checks that the copies are identical. + - name: Download the Windows per-role packages + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + pattern: packages-windows-* + path: out/packages + + - name: Assemble the Windows package + run: | + allow_missing=--allow-missing + if [ "$BF2_RELEASE_RUN" = true ]; then allow_missing=; fi + python3 Code/Build/package_release.py --release windows --packages-dir out/packages --output-dir out/release --revision "$GITHUB_SHA" --repository "$GITHUB_REPOSITORY" $allow_missing + + - name: Upload the Windows release package + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: release-windows + path: | + out/release/*.zip + out/release/*.sha256 + out/release/*.tar.bz2 + if-no-files-found: error + compression-level: 0 + retention-days: 14 + linux: name: Linux x64 runs-on: ubuntu-22.04 @@ -137,6 +282,21 @@ jobs: compression-level: 0 retention-days: 14 + # The Linux release package, openbf2-linux.zip: the same files in a platform-named archive. + - name: Assemble the Linux package + run: python3 Code/Build/package_release.py --release linux --packages-dir out/packages --output-dir out/release --revision "$GITHUB_SHA" --repository "$GITHUB_REPOSITORY" + + - name: Upload the Linux release package + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: release-linux + path: | + out/release/openbf2-linux.zip + out/release/openbf2-linux.zip.sha256 + if-no-files-found: error + compression-level: 0 + retention-days: 14 + - name: Upload Linux build diagnostics if: failure() uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 @@ -147,3 +307,271 @@ jobs: out/build/ci-linux-x64/CMakeFiles/CMake*.log if-no-files-found: ignore retention-days: 7 + + # [CHOSEN, not recovered] The macOS port: the renderer-on Metal client, the dedicated server and the + # AI library, one leg per architecture on the Apple-silicon runner, macos-15 (x86_64 is cross-compiled, as the + # local Intel builds cross-compile arm64). The client needs the native effect compiler, built here + # from pinned vkd3d-shader 2.1 and MojoShader sources with the repository's patches + # (tools/macos/nativefx/build.sh, tools/macos/vkd3d-patches). + # Release runs (a published release, or a v* tag) sign the binaries with the Developer ID from + # the protected `release` environment; every other run (pull requests, branch pushes, forks) + # stays ad-hoc and uses no secrets (docs/ci-releases.md). The per-architecture ZIPs are CI + # artifacts only and not notarized: releases ship the notarized disk image (macos-app). + macos: + name: macOS ${{ matrix.arch }} + runs-on: macos-15 + timeout-minutes: 150 + environment: ${{ (github.event_name == 'release' || startsWith(github.ref, 'refs/tags/v')) && 'release' || '' }} + strategy: + fail-fast: false + matrix: + arch: [arm64, x86_64] + env: + CMAKE_BUILD_PARALLEL_LEVEL: 3 + MACOSX_DEPLOYMENT_TARGET: "11.0" + BF2_RELEASE_SIGNING: ${{ (github.event_name == 'release' || startsWith(github.ref, 'refs/tags/v')) && 'true' || 'false' }} + steps: + - name: Check out the event commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.sha }} + persist-credentials: false + + - name: Install build dependencies + run: | + brew install flex bison mingw-w64 autoconf automake libtool pkgconf cpanminus vulkan-headers spirv-headers + # vkd3d's configure needs the Vulkan and SPIR-V headers; /opt/homebrew/include is not on the + # compiler's default search path on Apple silicon. + echo "CPPFLAGS=-I$(brew --prefix vulkan-headers)/include -I$(brew --prefix spirv-headers)/include" >> "$GITHUB_ENV" + # vkd3d's configure needs Perl's JSON module. + cpanm --notest --local-lib "$HOME/perl5" JSON + echo "PERL5LIB=$HOME/perl5/lib/perl5" >> "$GITHUB_ENV" + echo "$(brew --prefix flex)/bin" >> "$GITHUB_PATH" + echo "$(brew --prefix bison)/bin" >> "$GITHUB_PATH" + echo "WIDL=$(brew --prefix mingw-w64)/toolchain-x86_64/bin/x86_64-w64-mingw32-widl" >> "$GITHUB_ENV" + + - name: Fetch the native effect sources + run: | + git clone --depth 1 --branch vkd3d-2.1 https://gitlab.winehq.org/wine/vkd3d.git out/third_party/vkd3d + test "$(git -C out/third_party/vkd3d rev-parse HEAD)" = fb7f9ff3c1f8d972ee6f1b8c6a92caf6c8ba1e10 + (cd out/third_party/vkd3d && ./autogen.sh) + git clone https://github.com/icculus/mojoshader.git out/third_party/mojoshader + git -C out/third_party/mojoshader checkout --detach ad5dff84830c2863c841f4b1f4e3df78c705b383 + + - name: Build the native effect libraries + run: sh tools/macos/nativefx/build.sh ${{ matrix.arch }} + + - name: Configure + run: | + deps=nativefx + if [ "${{ matrix.arch }}" = arm64 ]; then deps=nativefx-arm64; fi + cmake --preset macos-x64 -B out/build/ci-macos-${{ matrix.arch }} \ + -DCMAKE_OSX_ARCHITECTURES=${{ matrix.arch }} -DBF2_MACOS_LINK_RENDDX9=ON \ + -DBF2_FRONTIER_DEFAULT_CONTINUE=ON \ + -DBF2_FX_NATIVE_DEPS="$GITHUB_WORKSPACE/out/build/$deps" \ + -DBF2_GAME_DIR:PATH="$GITHUB_WORKSPACE/out/no-game-content" + + - name: Build the client, the dedicated server and the AI library + run: cmake --build out/build/ci-macos-${{ matrix.arch }} --target bf2_client bf2 bf2_aidll + + - name: Check the architecture and the Python runtime + run: | + for image in bf2_client bf2 libdice_py.dylib libaidll.dylib; do + lipo out/build/ci-macos-${{ matrix.arch }}/bin_macos/$image -verify_arch ${{ matrix.arch }} + done + # The runner is arm64; the cross-compiled x86_64 images are not executed here. + if [ "${{ matrix.arch }}" = arm64 ]; then + cmake --build out/build/ci-macos-arm64 --target dice_py_check_run + fi + + # Release only, after every build step, so the keychain exists only for signing and packaging. + # No notary key here: this job notarizes nothing. + - name: Import the Developer ID certificate (release) + if: env.BF2_RELEASE_SIGNING == 'true' + env: + MACOS_CERT_P12: ${{ secrets.MACOS_CERT_P12 }} + MACOS_CERT_PASSWORD: ${{ secrets.MACOS_CERT_PASSWORD }} + run: bash tools/macos/ci/release-signing.sh import + + - name: Sign the macOS binaries (release) + if: env.BF2_RELEASE_SIGNING == 'true' + run: bash tools/macos/ci/release-signing.sh sign-standalone out/build/ci-macos-${{ matrix.arch }}/bin_macos + + - name: Package macOS binaries + run: | + signing=adhoc + if [ "$BF2_RELEASE_SIGNING" = true ]; then signing=developer-id; fi + python3 Code/Build/package_release.py --platform macos-${{ matrix.arch }} --build-dir out/build/ci-macos-${{ matrix.arch }} --output-dir out/packages --revision "$GITHUB_SHA" --repository "$GITHUB_REPOSITORY" --macos-signing "$signing" + + - name: Remove the signing keychain and key (release) + if: always() && env.BF2_RELEASE_SIGNING == 'true' + run: bash tools/macos/ci/release-signing.sh cleanup + + - name: Upload macOS packages + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: packages-macos-${{ matrix.arch }} + path: | + out/packages/*.zip + out/packages/*.sha256 + if-no-files-found: error + compression-level: 0 + retention-days: 14 + + - name: Upload macOS build diagnostics + if: failure() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: diagnostics-macos-${{ matrix.arch }} + path: | + out/build/ci-macos-${{ matrix.arch }}/CMakeFiles/CMakeConfigureLog.yaml + out/build/nativefx*/logs/*.log + if-no-files-found: ignore + retention-days: 7 + + # [CHOSEN, not recovered] The macOS app: the separate MIT setup app (kr4uzi/openbf2-setup, pinned + # below) with the universal client embedded, as a drag-and-drop disk image, openbf2-macos.dmg: the + # macOS release package. The two macOS legs are + # merged with lipo; the setup app's own release script builds, tests and verifies the image. Its + # contract for the client directory is docs/client-artifact.md in that repository. + # Release runs sign the app with the Developer ID (hardened runtime, timestamp, entitlements), + # sign, notarize and staple the disk image; other runs keep the setup script's ad-hoc signature. + macos-app: + name: macOS app (universal) + needs: macos + runs-on: macos-15 + timeout-minutes: 120 + environment: ${{ (github.event_name == 'release' || startsWith(github.ref, 'refs/tags/v')) && 'release' || '' }} + env: + SETUP_REPOSITORY: kr4uzi/openbf2-setup + SETUP_REVISION: fb6dc8fe8d7b81e41d0b737925891e92568cb61c # v0.3.1 + BF2_RELEASE_SIGNING: ${{ (github.event_name == 'release' || startsWith(github.ref, 'refs/tags/v')) && 'true' || 'false' }} + steps: + # The client entitlements, the signing helper and the packager (for the build-info); the app + # is built from the setup repository. + - name: Check out the signing files + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.sha }} + path: out/openbf2 + persist-credentials: false + sparse-checkout: | + Code/Build + tools/macos/ci + sparse-checkout-cone-mode: true + + - name: Download the macOS client packages + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + pattern: packages-macos-* + path: out/packages + merge-multiple: true + + - name: Merge the client legs into a universal client + working-directory: out + run: | + for arch in arm64 x86_64; do + (cd packages && shasum -a 256 -c "openbf2-macos-$arch-client.zip.sha256") + ditto -x -k "packages/openbf2-macos-$arch-client.zip" "legs/$arch" + done + mkdir client-universal + for item in bf2_client libdice_py.dylib libaidll.dylib; do + lipo -create "legs/arm64/openbf2-macos-arm64-client/$item" \ + "legs/x86_64/openbf2-macos-x86_64-client/$item" \ + -output "client-universal/$item" + lipo "client-universal/$item" -verify_arch arm64 x86_64 + done + chmod +x client-universal/bf2_client + + - name: Check out the setup app + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ env.SETUP_REPOSITORY }} + ref: ${{ env.SETUP_REVISION }} + path: out/openbf2-setup + persist-credentials: false + + # The setup app uses header-only Boost.Asio (1.86 or newer); find_package(Boost CONFIG) finds + # Homebrew's copy, nothing is compiled from Boost. + - name: Install the Boost headers + run: | + brew install boost + brew list --versions boost + + - name: Prepare the Rust toolchain + run: | + rustup target add aarch64-apple-darwin x86_64-apple-darwin + cargo fetch --locked --manifest-path out/openbf2-setup/core/rtp-bridge/Cargo.toml + + - name: Import the Developer ID certificate (release) + if: env.BF2_RELEASE_SIGNING == 'true' + env: + MACOS_CERT_P12: ${{ secrets.MACOS_CERT_P12 }} + MACOS_CERT_PASSWORD: ${{ secrets.MACOS_CERT_PASSWORD }} + NOTARY_KEY_P8: ${{ secrets.NOTARY_KEY_P8 }} + NOTARY_KEY_ID: ${{ secrets.NOTARY_KEY_ID }} + run: | + bash out/openbf2/tools/macos/ci/release-signing.sh import + bash out/openbf2/tools/macos/ci/release-signing.sh notary-key + + # SETUP_SIGN_IDENTITY unset means ad-hoc. In release runs the setup scripts sign with the + # imported identity, the hardened runtime, a timestamp and the two entitlements files. + - name: Build, test and package the app + run: | + if [ "$BF2_RELEASE_SIGNING" = true ]; then + export SETUP_SIGN_IDENTITY="$BF2_SIGN_IDENTITY" + export SETUP_ENTITLEMENTS_CLIENT="$GITHUB_WORKSPACE/out/openbf2/Code/Build/macos/bf2_client.entitlements" + export SETUP_ENTITLEMENTS_APP="$GITHUB_WORKSPACE/out/openbf2-setup/macos/OpenBF2.entitlements" + fi + bash out/openbf2-setup/macos/build-release.sh "$GITHUB_WORKSPACE/out/client-universal" "$GITHUB_WORKSPACE/out/packages-app/openbf2-macos.dmg" "$GITHUB_WORKSPACE/out/setup-build" + + - name: Sign, check and notarize the disk image (release) + if: env.BF2_RELEASE_SIGNING == 'true' + env: + NOTARY_KEY_ID: ${{ secrets.NOTARY_KEY_ID }} + NOTARY_ISSUER_ID: ${{ secrets.NOTARY_ISSUER_ID }} + run: | + dmg=out/packages-app/openbf2-macos.dmg + bash out/openbf2/tools/macos/ci/release-signing.sh verify-dmg "$dmg" + bash out/openbf2/tools/macos/ci/release-signing.sh sign-dmg "$dmg" + bash out/openbf2/tools/macos/ci/release-signing.sh notarize "$dmg" + bash out/openbf2/tools/macos/ci/release-signing.sh staple "$dmg" + + - name: Remove the signing keychain and key (release) + if: always() && env.BF2_RELEASE_SIGNING == 'true' + run: bash out/openbf2/tools/macos/ci/release-signing.sh cleanup + + # After stapling: the ticket changes the image, so the checksum is written last. + - name: Write the disk image checksum + working-directory: out/packages-app + run: | + rm -f openbf2-macos.dmg.sha256 + shasum -a 256 openbf2-macos.dmg > openbf2-macos.dmg.sha256 + + # The disk image cannot hold it (the setup build copies only the client's three files), so the + # build-info is a CI artifact beside the image: revision, setup app revision, the client's + # SHA-256s, the image's SHA-256 and the signing and notarization state. + - name: Write the disk image build-info + run: | + signing=adhoc + if [ "$BF2_RELEASE_SIGNING" = true ]; then signing=developer-id; fi + python3 out/openbf2/Code/Build/package_release.py --release macos --client-dir out/client-universal --dmg out/packages-app/openbf2-macos.dmg --setup-repository "$SETUP_REPOSITORY" --setup-revision "$SETUP_REVISION" --macos-signing "$signing" --output-dir out/build-info --revision "$GITHUB_SHA" --repository "$GITHUB_REPOSITORY" + + - name: Upload the macOS app + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: release-macos + path: | + out/packages-app/openbf2-macos.dmg + out/packages-app/openbf2-macos.dmg.sha256 + if-no-files-found: error + compression-level: 0 + retention-days: 14 + + - name: Upload the disk image build-info + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: build-info-macos + path: out/build-info/openbf2-macos.build-info.json + if-no-files-found: error + retention-days: 14 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b677210d6..8104d3bbb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,3 +21,6 @@ concurrency: jobs: build: uses: ./.github/workflows/build.yml + # A reusable workflow only receives the `release` environment's secrets when the caller + # passes secrets on; without this they resolve to empty strings. + secrets: inherit diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 63c78e6e1..8701d4e29 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -14,6 +14,9 @@ concurrency: jobs: build: uses: ./.github/workflows/build.yml + # A reusable workflow only receives the `release` environment's secrets when the caller + # passes secrets on; without this they resolve to empty strings. + secrets: inherit upload: name: Attach packages to the release @@ -23,10 +26,12 @@ jobs: permissions: contents: write steps: - - name: Download this run's packages + # Only the release-* artifacts: one package per platform. The per-role and per-architecture + # packages-* artifacts stay CI artifacts (docs/ci-releases.md). + - name: Download this run's release packages uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: - pattern: packages-* + pattern: release-* path: packages merge-multiple: true @@ -38,18 +43,37 @@ jobs: working-directory: packages shell: bash run: | - packages=( - openbf2-windows-x86-server-diagnostic - openbf2-windows-x86-client-diagnostic - openbf2-windows-x86-editor-diagnostic - openbf2-windows-x64-server - openbf2-linux-x64-server - ) + # Both Windows clients bundle OpenAL Soft (LGPL): the release carries the exact source. + shopt -s nullglob + sources=(openal-soft-*.tar.bz2) + shopt -u nullglob + test "${#sources[@]}" -eq 1 + files=(openbf2-macos.dmg openbf2-windows.zip openbf2-linux.zip "${sources[0]}") assets=() - for package in "${packages[@]}"; do - test -s "$package.zip" - test -s "$package.zip.sha256" - sha256sum --check "$package.zip.sha256" - assets+=("$package.zip" "$package.zip.sha256") + for file in "${files[@]}"; do + test -s "$file" + test -s "$file.sha256" + sha256sum --check "$file.sha256" + assets+=("$file" "$file.sha256") done + # Exactly these assets: nothing else may reach the release page. + expected=$(printf '%s\n' "${assets[@]}" | sort) + actual=$(ls -A | sort) + if [ "$expected" != "$actual" ]; then + echo "::error title=Unexpected release files::expected only: ${assets[*]}" + diff <(echo "$expected") <(echo "$actual") || true + exit 1 + fi + # build.yml fails release runs without D3DX; check the archive itself as well. + python3 - <<'EOF' + import json + import zipfile + + with zipfile.ZipFile("openbf2-windows.zip") as archive: + names = set(archive.namelist()) + info = json.loads(archive.read("openbf2-windows/build-info.json")) + for entry in ("x64/BF2.exe", "x86/BF2.exe", "server/bf2_w32ded.exe", "editor/BF2Editor.exe"): + assert "openbf2-windows/" + entry in names, "openbf2-windows.zip lacks " + entry + assert not info.get("omitted"), "openbf2-windows.zip omits " + ", ".join(info["omitted"]) + EOF gh release upload --repo "$GH_REPO" --clobber -- "$RELEASE_TAG" "${assets[@]}" diff --git a/.gitignore b/.gitignore index c77f458a2..3e44e4252 100644 --- a/.gitignore +++ b/.gitignore @@ -78,6 +78,7 @@ compile_commands.json !/Code/Build/bf2audio_diff/ !/Code/Build/bf2audio_smoke/ !/Code/Build/textureatlas_diff/ +!/Code/Build/macos/ !/Code/Build/bin/ /Code/Build/bin/** !/Code/Build/bin/README.md diff --git a/.run/bf2_client (game dir).run.xml b/.run/bf2_client (game dir).run.xml index 97e5a2de4..570273f29 100644 --- a/.run/bf2_client (game dir).run.xml +++ b/.run/bf2_client (game dir).run.xml @@ -1,7 +1,7 @@ - + - + \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md index e192106ca..7a8769ef0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,6 +4,27 @@ This is the canonical policy for every coding agent working in this repository. instruction files must import or point here instead of copying these rules. If guidance conflicts, the user's current request wins, followed by this file, then the subsystem documentation. +## Code Review Rules + +For code review and regression investigation, also read [docs/reviewing.md](docs/reviewing.md). +This file remains the canonical policy. Review alone does not authorize source changes; +explicit user authorization to implement fixes still applies. + +- **Report concrete regressions.** Review the PR diff and affected callers for memory/lifetime + errors, initialization and teardown failures, malformed-input handling, and broken builds. + Explain the reachable trigger and consequence; distinguish pre-existing defects from changes + introduced by the PR. Legacy style, raw pointers, lack of Asio, and opportunities to adopt + newer C++ are not defects by themselves. +- **Preserve the applicable compatibility contract.** Check ABI, protocols, serialized data, + and reconstructed behavior for each affected image and architecture. Respect the documented, + issue-backed native ABI and editor exceptions; do not restore retired compatibility adapters + or infer unknown signatures and layouts. State missing binary evidence and continue checks + that do not depend on it. +- **Account for parallel upstream work.** Where accessible, inspect relevant B2BF/OpenBF2 PRs + and branches at their current SHAs. Identify semantic conflicts and existing fixes with + evidence; upstream code is not automatically proof of correctness. State unavailable context + and continue the scoped review instead of assuming that another branch was checked. + ## Agent prerequisites and human ownership - Before implementing behavior as recovered engine code, the agent must have **IDA or Ghidra @@ -150,6 +171,42 @@ Use the repository's evidence vocabulary consistently: frontiers because `BF2Log` may not be initialized yet. If the signature/ABI is not known well enough to define a safe callable body, keep the symbol declaration-only and document the caller boundary instead of inventing a signature merely to add logging. + **Unimplemented-slot exception (owner decision 2026-11-02, libaidll reconstruction):** a + virtual slot that is `__cxa_pure_virtual` in every vtable of every class that has it, in + every inspected image, has no body anywhere. Reaching it in retail aborts with "pure virtual method + called". The same applies to a class member that no instruction reads or writes. Its name and + source-level type cannot be recovered, but its behaviour is fully determined. + - Such a slot or member may be declared with a `[CHOSEN, not recovered]` name, so that the + surrounding recovered code can be completed. + - The declaration must reproduce what the instructions prove: + - the slot position in both ELF vtables; + - the receiver and argument registers or stack slots each call site prepares; + - whether any caller reads a result (if none does, declare `void`; if a caller tests `eax`/`al`, + declare the narrowest integer type the test proves); + - for a member, the size and alignment implied by the neighbouring offsets in each image. + - Keep the slot pure (`= 0`); never give it a body. Every call site stays exactly as the listing + shows. + - Cite the vtable addresses and call-site addresses beside the declaration. + + This covers only slots and members with no body and no access. A slot that has an override + anywhere, or a member that is accessed anywhere, keeps the ordinary evidence rules. The matching + build (`MATCHING_BUILD_PLAN.md`) re-checks every such declaration at its call sites. + + **Unobservable-type exception (owner decision 2026-11-05, RendDX9 reconstruction):** a body may be + recovered with a `[CHOSEN, not recovered]` type or name when all of the following hold: + - no inspected image (retail PE, `_r`, editor, Linux ELF) has a caller that reaches it, or every + reachable path only ever sees empty data, so its behaviour is fully determined; + - the instructions of every image have been read and the body reproduces everything they prove + (reads, writes, offsets, call order, slot dispatch, return register); + - only a name or a type that no instruction can expose is missing. Examples: the element type of a + container that is never filled, or the name of a property pair that nothing calls. + + Mark each chosen piece `[CHOSEN, not recovered]` beside it, with the evidence (addresses in every + image, and why the choice cannot be observed). Prefer the choice the instructions point to, such as + float for an `st0` return. This replaces a [FRONTIER] stop only in that situation; a body that any + path reaches with real data keeps the ordinary evidence rules. First applied to: LightManager +0xBC/+0xC0 + (PE 0x1015C130/0x1015C140), GeometryTemplateManager +0x2C/+0x30 (PE 0x1015D940/0x1015D430) and + ObjectDrawer::flushDeferredGeometry (PE 0x100F8C00). - Test fixtures belong under `Code/Tests`, must be labeled as scaffolding, and may only model the specific condition the test needs. - When a production implementation lands, remove any Probe/harness override that would shadow it. @@ -191,8 +248,9 @@ Use the repository's evidence vocabulary consistently: sound it would have driven; each call site keeps its own hit count and is rate-limited, never silenced; NO value is fabricated, because every shipped call site discards the result, so continuing returns nothing at all; and the surrounding body is written as far as the evidence - honestly reaches, so the seam covers only the sound call. The shared implementation and the full - rule live in `Code/BF2/Core/SoundSeamFrontier.h`; it reports to stderr only, deliberately, because + honestly reaches, so the seam covers only the sound call. No sound seam remains (the shared + helper `Core/SoundSeamFrontier.h` was removed with its last caller); a future sound seam re-adds + that helper with this rule. It reports to stderr only, deliberately, because `Debug(DebugTypeError, ...)` aborts in this tree and `BF2Log` is not guaranteed to be up on the HUD paths that reach these seams. The cost is real and is the point: a sound retail would start or stop keeps doing whatever it was doing. This exception covers sound seams ONLY - every other diff --git a/CMakeLists.txt b/CMakeLists.txt index dd83553e6..045a2ad43 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8,31 +8,60 @@ if(POLICY CMP0141) endif() project(BF2Rebuilt LANGUAGES C CXX) +# [CHOSEN, not recovered] Header-selection preparation for the G2w forwarding backend. +option(BF2_GFX_SEAM "Compile the renderer against the D3D9/D3DX subset headers" OFF) +# [CHOSEN, not recovered] Release packaging (owner decision 2026-11-14): CI's release configure steps +# turn this ON so the plugin kit's frontier trap (Code/RendDX9Abi/Frontier.cpp) logs and continues +# when its env var is unset. OFF - dev builds and every gate - keeps the armed (abort) default. An +# explicit env value (continue / abort) wins in both. Reaches the .cmd image builds as the env var +# BF2_FRONTIER_DEFAULT_CONTINUE=ON|OFF (always passed, so a stray shell variable cannot flip it). +option(BF2_FRONTIER_DEFAULT_CONTINUE "Frontier trap defaults to continue (release packages)" OFF) +if(BF2_FRONTIER_DEFAULT_CONTINUE) + set(BF2_FRONTIER_DEFAULT_ENV "${CMAKE_COMMAND}" -E env BF2_FRONTIER_DEFAULT_CONTINUE=ON) +else() + set(BF2_FRONTIER_DEFAULT_ENV "${CMAKE_COMMAND}" -E env BF2_FRONTIER_DEFAULT_CONTINUE=OFF) +endif() +if(CMAKE_SYSTEM_NAME STREQUAL "Darwin") + # [CHOSEN, not recovered] The macOS client's Cocoa host is Objective-C++ (docs/macos-s2-4.md). + enable_language(OBJCXX) +endif() # ================================================================================================= # TOOLCHAINS (2026-09-29). Three configurations, one source tree: -# * MSVC x86 - the retail-fidelity reconstruction: bf2_w32ded.exe, /FORCE diagnostic link. +# * MSVC x86 - the retail-fidelity reconstruction: bf2_w32ded.exe, strict link. # * MSVC x64 - the native Windows dedicated port: bf2_w64ded.exe, strict link. # * GCC/Clang, Linux - the native Linux dedicated port: `bf2` + `libdice_py.so`. It is the x64 # x86-64 port's pointer-bearing layouts compiled by the platform family the ELF # oracle was built for. -# Everything Linux-specific in this file sits under BF2_BUILD_LINUX; the MSVC configurations are -# untouched by it. The Linux build is a native port (`[CHOSEN, not recovered]` layouts, like x64), -# not a reproduction of the shipped 32-bit ELF's object layouts. +# * AppleClang, macOS - the native macOS dedicated port: `bf2` + `libdice_py.dylib`, the Linux +# port's sources and layouts built for Darwin (docs/macos-port.md). +# Linux and macOS form the POSIX family (BF2_BUILD_POSIX); what they share sits under that switch, +# and only what genuinely differs sits under BF2_BUILD_LINUX or BF2_BUILD_MACOS. The MSVC +# configurations are untouched by any of them. Both POSIX builds are native ports +# (`[CHOSEN, not recovered]` layouts, like x64), not reproductions of the shipped 32-bit ELF's +# object layouts. The macOS configuration is an intentional port change requested by the project +# owner, `[CHOSEN, not recovered]` throughout. # ================================================================================================= set(BF2_BUILD_LINUX OFF) +set(BF2_BUILD_MACOS OFF) +set(BF2_BUILD_POSIX OFF) if(MSVC) # The two Windows configurations, selected by pointer width below. elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") set(BF2_BUILD_LINUX ON) + set(BF2_BUILD_POSIX ON) +elseif(CMAKE_SYSTEM_NAME STREQUAL "Darwin" AND CMAKE_CXX_COMPILER_ID MATCHES "Clang") + # [CHOSEN, not recovered] AppleClang (or upstream Clang) on macOS: the macos-x64 preset. + set(BF2_BUILD_MACOS ON) + set(BF2_BUILD_POSIX ON) else() message(FATAL_ERROR - "BF2Rebuilt builds with MSVC on Windows (msvc-x86 / msvc-x64 presets) or with GCC/Clang on " - "Linux x86-64 (linux-x64 preset). This toolchain is ${CMAKE_CXX_COMPILER_ID} on " - "${CMAKE_SYSTEM_NAME}.") + "BF2Rebuilt builds with MSVC on Windows (msvc-x86 / msvc-x64 presets), with GCC/Clang on " + "Linux x86-64 (linux-x64 preset) or with Clang on macOS (macos-x64 preset). This " + "toolchain is ${CMAKE_CXX_COMPILER_ID} on ${CMAKE_SYSTEM_NAME}.") endif() -if(CMAKE_SIZEOF_VOID_P EQUAL 4 AND NOT BF2_BUILD_LINUX) +if(CMAKE_SIZEOF_VOID_P EQUAL 4 AND NOT BF2_BUILD_POSIX) set(BF2_BUILD_X64 OFF) set(BF2_NATIVE_ARCH "x86") elseif(CMAKE_SIZEOF_VOID_P EQUAL 8) @@ -45,6 +74,11 @@ elseif(CMAKE_SIZEOF_VOID_P EQUAL 8) message(STATUS "Configuring the native Linux x86-64 dedicated-server port (bf2 + libdice_py.so). " "See docs/building.md for toolchain and runtime setup.") + elseif(BF2_BUILD_MACOS) + set(BF2_NATIVE_ARCH "macos-${CMAKE_SYSTEM_PROCESSOR}") + message(STATUS + "Configuring the native macOS ${CMAKE_SYSTEM_PROCESSOR} dedicated-server port " + "(bf2 + libdice_py.dylib). See docs/building.md and docs/macos-port.md.") else() set(BF2_NATIVE_ARCH "x64") message(STATUS @@ -54,7 +88,7 @@ elseif(CMAKE_SIZEOF_VOID_P EQUAL 8) else() message(FATAL_ERROR "BF2Rebuilt supports only MSVC x86 (retail-fidelity), MSVC x64 (native dedicated port) " - "and Linux x86-64 (native dedicated port) configurations; " + "and 64-bit Linux/macOS (native dedicated port) configurations; " "CMAKE_SIZEOF_VOID_P=${CMAKE_SIZEOF_VOID_P}.") endif() @@ -113,7 +147,10 @@ set(bf2_engine_sources) set(bf2_engine_headers) foreach(component_path IN LISTS bf2_component_paths) get_filename_component(component_name "${component_path}" NAME) - if(IS_DIRECTORY "${component_path}" AND NOT component_name STREQUAL "External") + # Memory is the recovered Memory.dll, its own image (bf2_memory, Code/BF2/Memory/CMakeLists.txt); + # the engine keeps its own memory:: stubs, so its units must not join the engine source list. + if(IS_DIRECTORY "${component_path}" AND NOT component_name STREQUAL "External" + AND NOT component_name STREQUAL "Memory") file(GLOB_RECURSE component_sources CONFIGURE_DEPENDS "${component_path}/*.cpp" @@ -129,6 +166,17 @@ foreach(component_path IN LISTS bf2_component_paths) endif() endforeach() list(SORT bf2_engine_sources) +# [CHOSEN, not recovered] The CPU effect library has its own image and source manifest. +list(REMOVE_ITEM bf2_engine_sources + "${BF2_ROOT}/Platform/Gfx/Effect/Cache.cpp" + "${BF2_ROOT}/Platform/Gfx/Effect/Runtime.cpp" + "${BF2_ROOT}/Platform/Gfx/Effect/D3DAsm.cpp" + "${BF2_ROOT}/Platform/Gfx/Effect/FxBuild.cpp" + "${BF2_ROOT}/Platform/Gfx/Effect/FxParser.cpp" + "${BF2_ROOT}/Platform/Gfx/Effect/FxStates.cpp" + "${BF2_ROOT}/Platform/Gfx/Effect/Native.cpp" + "${BF2_ROOT}/Platform/Gfx/Effect/NativeMojo.cpp" + "${BF2_ROOT}/Platform/Gfx/Effect/NativeVkd3d.cpp") list(SORT bf2_engine_headers) # These translation units belong to AIDLL_w32ded.dll, not bf2_w32ded.exe. The source tree is @@ -138,89 +186,16 @@ list(SORT bf2_engine_headers) # Its AIDLL-only half WAS SPLIT OUT on 2026-09-08 into AI/AIDLL/AI/Main/AISingletonServer.cpp, which # this list excludes - `AISingletonServer` exists only in libaidll.so. The side-DLL target that the # old note was waiting for is Code/Build/aidll.cmd plus bf2_aidll below. -set(bf2_aidll_only_sources +# AIDLL_w32ded.dll / libaidll owns every TU under AI/AIDLL except the shared singleton bridge +# (the same directory rule as Code/Build/build.cmd), plus three units outside it. This list is an +# exclusion set for the engine image only, so its order is irrelevant; the DLL's own link order is +# the explicit bf2_aidll_sources manifest below. +file(GLOB_RECURSE bf2_aidll_only_sources CONFIGURE_DEPENDS "${BF2_ROOT}/AI/AIDLL/*.cpp") +list(REMOVE_ITEM bf2_aidll_only_sources "${BF2_ROOT}/AI/AIDLL/AI/Main/CommonSingletonServer.cpp") +list(APPEND bf2_aidll_only_sources "${BF2_ROOT}/Core/DllModule.cpp" "${BF2_ROOT}/Core/DllGlobals.cpp" # the side-DLL image's globals TU - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/BotMain.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/BotNavigation.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/BotSquad.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/SensingAgent.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/CommunicationAgent.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/BotSenses.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIPlanInterpreter/BAPContext.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/InformationManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/Information.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/WeaponInfo.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/IPIArmament.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/IPIArmamentReal.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/IPICover.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/IPIMobile.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/IPIMobileReal.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/IPIMobileKnown.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/IPIUnit.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/InformationReal.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/WeaponInfoReal.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/IPIPhysicalReal.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIUtils/VehicleOccupancy.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/AIInformationGrid.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIUtils/DebugRendering/AIRenderUtil.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/WeaponInfoManager.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/BFInformationCourier.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/InformationFactory.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicMap/BFStrategicEnvironment.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicMap/BotSpawner.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/DrawPrimitives/DPManager.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/Main/AICollisionHandler.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/Main/AIEventCourier.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/Main/AIMineManager.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/Main/AIPlayerCourier.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/Main/BFPathfindingCourier.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/Material/Material.cpp" # libaidll materialId parser - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/Material/MaterialManager.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/NavMesh/MapProperties.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeManager.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTree.cpp" # libaidll only - chunk 04 - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeNode.cpp" # libaidll only - live polygon query - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.cpp" # libaidll only - chunk 04 - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNodeManager.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicMap/AerialHeightMap.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIPlanInterpreter/BAPEntries.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/SensingAgentPatterns.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/SquadManager.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/SquadCoordinator.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/SquadFormation.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/SquadMember.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIBotBehaviour/CustomCurve.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/BotMemory.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/BotSubObjects.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBotBehaviour/UrgencyMerger.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AIConsole.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIBotBehaviour/UrgeCurve.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNodeManager.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPositionManager.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicEntity/AILandingZoneManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObject.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicEntity/AIStrategicArea.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicEntity/SAWayPoint.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategic/SAI.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/Main/BotBehaviourManager.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/Main/CommunicationHub.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/Main/StrategyManager.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/Main/AIPathfinding.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/Main/IAIPathfinding.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/Main/UserOrderManager.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/Main/AIMain.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AIModule.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AIRandom.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/Main/AILODManager.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/Main/IBotManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AISettings.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AISingletonServer.cpp" # libaidll only - see the split, below - "${BF2_ROOT}/AI/AIDLL/AI/Main/BF2AI.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/BotManager.cpp" + "${BF2_ROOT}/Math/DoubleVec3.cpp" ) list(REMOVE_ITEM bf2_engine_sources ${bf2_aidll_only_sources}) @@ -246,6 +221,8 @@ list(REMOVE_ITEM bf2_engine_sources "${BF2_ROOT}/VoipServer/BF2VoipServerShell.c # carries the mirror list). Client-only REGIONS of shared TUs are not a manifest matter: they sit # under #if !DEDICATED, and bf2_set_image() below is what selects them per target. set(bf2_client_only_sources + "${BF2_ROOT}/Game/PunkBuster/PbClient.cpp" # BF2.exe 0x435900..0x436434; the ELF has only the server half + "${BF2_ROOT}/Game/GameLogic/PlayerVOHelp.cpp" # BF2.exe client tutorial owner; placement inferred "${BF2_ROOT}/Math/Mat4Inverse.cpp" # client PE inverse; explicitly reused by x86 bf2_aidll below "${BF2_ROOT}/Game/Main/BF2Window.cpp" # the game window (2026-09-02); its body is #if !DEDICATED as well "${BF2_ROOT}/Game/Main/BF2FrameInterpolator.cpp" # attested client-only TU; ctor recovered 2026-09-03 @@ -274,13 +251,18 @@ set(bf2_client_only_sources "${BF2_ROOT}/Menu/HudConsoleBindings.cpp" "${BF2_ROOT}/Menu/ProfileConsoleBindings.cpp" "${BF2_ROOT}/Menu/ClientUiFrontiers.cpp" - "${BF2_ROOT}/Game/Main/BF2ClientFrontiers.cpp" "${BF2_ROOT}/Game/LocalProfileManager.cpp" "${BF2_ROOT}/Game/LocalProfileManagerInit.cpp" "${BF2_ROOT}/Game/LocalProfileManagerOperations.cpp" "${BF2_ROOT}/Game/LocalProfileManagerSelection.cpp" "${BF2_ROOT}/Game/LocalProfileManagerDiscovery.cpp" "${BF2_ROOT}/Game/LocalProfileManagerFields.cpp" + "${BF2_ROOT}/Game/DistributedLightRenderer/DistributedLightRenderer.cpp" + "${BF2_ROOT}/Game/VoipClient/BF2VoipClient.cpp" # BF2.exe 0x4510F0..0x45235C + "${BF2_ROOT}/Game/VoipClient/VoipClient.cpp" # BF2.exe 0x736C30..0x737D4E + "${BF2_ROOT}/Game/VoipClient/VoipMixer.cpp" # BF2.exe 0x7356B0..0x736BA0 + "${BF2_ROOT}/Game/VoipClient/VoipMixerCoreAudio.cpp" # [PLATFORM] macOS backend; empty elsewhere + "${BF2_ROOT}/Game/VoipClient/VoipFakeDevice.cpp" # [CHOSEN] BF2_VOIP_CAPTURE=fake test device "${BF2_ROOT}/Game/LocalProfileManagerSuffix.cpp" "${BF2_ROOT}/Game/ProfileManager.cpp" # native online-profile lifetime/status owner "${BF2_ROOT}/Game/PasswordCodec.cpp" # inferred path; the profile password's CryptProtectData wrapper @@ -313,6 +295,7 @@ set(bf2_client_only_sources "${BF2_ROOT}/Menu/Bf2ButtonNode.cpp" "${BF2_ROOT}/Menu/Bf2NewListBoxNode.cpp" "${BF2_ROOT}/Menu/Bf2EditNode.cpp" + "${BF2_ROOT}/Menu/Bf2TileNode.cpp" "${BF2_ROOT}/Menu/Bf2MiniMenuMapNode.cpp" "${BF2_ROOT}/Menu/Bf2TransformListNode.cpp" "${BF2_ROOT}/External/BFMeme/SliderNode.cpp" @@ -345,6 +328,7 @@ set(bf2_client_only_sources "${BF2_ROOT}/Menu/BfNewListBoxNode.cpp" # recovered list-node storage; publication withheld "${BF2_ROOT}/Menu/BfListBoxData.cpp" # descriptor-attested shared chat/list data; node hooks open "${BF2_ROOT}/Menu/Ref2System.cpp" # recovered UI root construction; publication still gated + "${BF2_ROOT}/Menu/HudWidescreen.cpp" # issue #33: opt-in native vanilla HUD policy "${BF2_ROOT}/Menu/Font.cpp" "${BF2_ROOT}/Menu/DifFontMetadata.cpp" "${BF2_ROOT}/Menu/FontLoader.cpp" @@ -356,6 +340,7 @@ set(bf2_client_only_sources "${BF2_ROOT}/External/BFMeme/Event.cpp" "${BF2_ROOT}/External/BFMeme/Action.cpp" "${BF2_ROOT}/External/BFMeme/Function.cpp" + "${BF2_ROOT}/External/BFMeme/Tree.cpp" "${BF2_ROOT}/External/BFMeme/TypeDescriptor.cpp" "${BF2_ROOT}/External/BFMeme/NamedObjectRegistry.cpp" "${BF2_ROOT}/External/BFMeme/Data.cpp" @@ -410,7 +395,6 @@ set(bf2_client_only_sources "${BF2_ROOT}/IO/Input/KeyboardDevice.cpp" "${BF2_ROOT}/IO/Input/MouseDevice.cpp" "${BF2_ROOT}/IO/Input/GameControllerDevice.cpp" - "${BF2_ROOT}/IO/Input/FalconDevice.cpp" "${BF2_ROOT}/IO/Input/DX8InputDeviceManager.cpp" "${BF2_ROOT}/Sound/BfSound/MusicPlayer.cpp" # attested client-only TU (2026-09-02); body #if !DEDICATED as well "${BF2_ROOT}/Menu/MenuTeamManager.cpp" @@ -427,12 +411,13 @@ endif() # Game/Main/StatusMonitorImpl_win32.cpp and IO/File/Win32FileSystem.cpp, the ELF attests # IO/File/UnixFileSystem.cpp and StatusMonitorImpl_posix. The POSIX pair already compiles to an empty # TU under MSVC by its own guards; the Win32 pair is whole-file Win32 API with no guard, so it leaves -# the manifest on Linux instead. Same discipline as the AIDLL and client lists above. +# the manifest on Linux instead. Same discipline as the AIDLL and client lists above. macOS takes +# the POSIX pair as well ([CHOSEN, not recovered]: there was no retail macOS server). set(bf2_win32_only_sources "${BF2_ROOT}/IO/File/Win32FileSystem.cpp" "${BF2_ROOT}/Game/Main/StatusMonitorImpl_win32.cpp" ) -if(BF2_BUILD_LINUX) +if(BF2_BUILD_POSIX) list(REMOVE_ITEM bf2_engine_sources ${bf2_win32_only_sources}) endif() @@ -539,7 +524,12 @@ endfunction() # own portability layer selects its Linux branch from _LINUX (gsPlatform.h, "Linux: _LINUX + _UNIX"). function(bf2_configure_c_target target) if(MSVC) - target_compile_options("${target}" PRIVATE /W3 /wd4996) + # The SDK code stays as it ships. C5287: GameSpy compares two different enum types. On x64, + # C4244/C4267 are GameSpy's string, packet and buffer lengths (size_t, pointer differences) + # held in int or DWORD, and C4311/C4312 are buddy and block indices passed through a + # callback's void* user data and back (gpiBuddy.c, gpiProfile.c). Both round-trip losslessly at + # the sizes GameSpy handles, with the same 32-bit semantics as the x86 build. + target_compile_options("${target}" PRIVATE /W3 /wd4996 /wd5287 /wd4244 /wd4267 /wd4311 /wd4312) else() target_compile_options("${target}" PRIVATE -fno-strict-aliasing @@ -554,6 +544,9 @@ function(bf2_configure_c_target target) ) if(BF2_BUILD_LINUX) target_compile_definitions("${target}" PRIVATE _LINUX _GNU_SOURCE) + elseif(BF2_BUILD_MACOS) + # [CHOSEN, not recovered] The SDK's own Darwin branch ("MacOSX: _MACOSX + _UNIX"). + target_compile_definitions("${target}" PRIVATE _MACOSX) endif() endif() bf2_add_compile_debug_info("${target}") @@ -586,12 +579,18 @@ endfunction() # The embedded CPython's headers: Include/ plus the platform pyconfig.h directory. Windows uses the # vendored PC/pyconfig.h; Linux uses the configure-generated pyconfig.h vendored under -# External/python-embedded/linux/ (a chosen path - see that directory's README). +# External/python-embedded/linux/ (a chosen path - see that directory's README); macOS uses the +# Darwin configure output vendored under External/python-embedded/macos/ ([CHOSEN, not recovered]). if(BF2_BUILD_LINUX) set(BF2_PYTHON_INCLUDE_DIRS "${BF2_EXTERNAL_ROOT}/python-embedded/linux" "${BF2_EXTERNAL_ROOT}/python-embedded/py-src-2.3.4/Include" ) +elseif(BF2_BUILD_MACOS) + set(BF2_PYTHON_INCLUDE_DIRS + "${BF2_EXTERNAL_ROOT}/python-embedded/macos" + "${BF2_EXTERNAL_ROOT}/python-embedded/py-src-2.3.4/Include" + ) else() set(BF2_PYTHON_INCLUDE_DIRS "${BF2_EXTERNAL_ROOT}/python-embedded/py-src-2.3.4/Include" @@ -611,6 +610,12 @@ if(BF2_BUILD_LINUX) set(CURSES_NEED_NCURSES TRUE) set(CURSES_NEED_WIDE TRUE) find_package(Curses REQUIRED) +elseif(BF2_BUILD_MACOS) + # [CHOSEN, not recovered] The macOS SDK's system ncurses (libncurses.tbd) carries the same + # entry points; the SDK has no separate libncursesw, so the wide variant is not requested. + find_package(Threads REQUIRED) + set(CURSES_NEED_NCURSES TRUE) + find_package(Curses REQUIRED) endif() add_library(bf2_engine_objects OBJECT @@ -625,12 +630,19 @@ if(BF2_BUILD_X64 AND MSVC) # build failure. Explicit fixed-width wire conversions remain reviewable in source. target_compile_options(bf2_engine_objects PRIVATE /Gy /we4244 /we4267 /we4311 /we4312) endif() -if(BF2_BUILD_LINUX) +if(BF2_BUILD_POSIX) target_include_directories(bf2_engine_objects PRIVATE ${CURSES_INCLUDE_DIRS}) # The engine's own GameSpy-facing TUs (persistence, match-making, HTTP) include the SDK headers, - # whose platform switch is _LINUX (gsPlatform.h) - the same define bf2_configure_c_target gives - # the SDK's C objects. - target_compile_definitions(bf2_engine_objects PRIVATE _LINUX) + # whose platform switch is _LINUX or _MACOSX (gsPlatform.h) - the same define + # bf2_configure_c_target gives the SDK's C objects. BF2_PLATFORM_POSIX selects the engine's + # POSIX implementations (UnixFileSystem, the ncurses status monitor) on every POSIX family + # member, including macOS, whose compilers do not define __unix__. + target_compile_definitions(bf2_engine_objects PRIVATE BF2_PLATFORM_POSIX) + if(BF2_BUILD_LINUX) + target_compile_definitions(bf2_engine_objects PRIVATE _LINUX) + else() + target_compile_definitions(bf2_engine_objects PRIVATE _MACOSX) + endif() endif() # The client is a second compilation of the shared engine sources, not a relink of @@ -643,6 +655,16 @@ set(bf2_client_sources ) list(REMOVE_DUPLICATES bf2_client_sources) list(SORT bf2_client_sources) +if(BF2_BUILD_MACOS) + # [CHOSEN, not recovered] The macOS client replaces the DirectInput 8 devices with + # MacInputDeviceManager and the Mac*Device TUs (docs/macos-s2-4.md). The Linux and MSVC client + # manifests are unchanged. + list(REMOVE_ITEM bf2_client_sources + "${BF2_ROOT}/IO/Input/DX8InputDeviceManager.cpp" + "${BF2_ROOT}/IO/Input/KeyboardDevice.cpp" + "${BF2_ROOT}/IO/Input/MouseDevice.cpp" + "${BF2_ROOT}/IO/Input/GameControllerDevice.cpp") +endif() add_library(bf2_client_objects OBJECT EXCLUDE_FROM_ALL ${bf2_client_sources} ${bf2_engine_headers} @@ -654,14 +676,30 @@ bf2_set_platform_compat(bf2_client_objects) # same MSVC STL layout even when this CMake tree is configured as Debug; iterator debugging changes # container layout and cannot cross the image boundary. PluginAbi.h enforces the matching contract. target_compile_definitions(bf2_client_objects PRIVATE - BF2_PLUGIN_ABI_NATIVE=1 _ITERATOR_DEBUG_LEVEL=0 ) +# [CHOSEN, not recovered] The native x64 client (https://github.com/B2BF/OpenBF2/issues/7): a pointer +# truncated into a 32-bit integer fails the build, as in the plugin scripts' x64 mode. The editor's +# own objects and its second compilation of shared TUs take the same list. +set(BF2_CLIENT_X64_COMPILE_OPTIONS) +if(BF2_BUILD_X64 AND MSVC) + set(BF2_CLIENT_X64_COMPILE_OPTIONS /Gy /we4311 /we4312) +endif() +target_compile_options(bf2_client_objects PRIVATE ${BF2_CLIENT_X64_COMPILE_OPTIONS}) target_include_directories(bf2_client_objects PRIVATE ${BF2_PYTHON_INCLUDE_DIRS} "${BF2_EXTERNAL_ROOT}/zlib-1.2.3" "${BF2_EXTERNAL_ROOT}/zlib-1.2.3/contrib/minizip" ) +if(BF2_BUILD_MACOS) + # [CHOSEN, not recovered] The macOS client (docs/macos-port.md, "Client triage") compiles the + # shared engine sources with the platform switches the macOS server objects use: + # BF2_PLATFORM_POSIX selects the POSIX file system and status monitor, _MACOSX the GameSpy + # SDK's Darwin branch, BF2_STATIC_PLUGINS the statically linked plugin images + # (Code/StaticPlugins). The Linux and MSVC client objects are unchanged. + target_include_directories(bf2_client_objects PRIVATE ${CURSES_INCLUDE_DIRS}) + target_compile_definitions(bf2_client_objects PRIVATE BF2_PLATFORM_POSIX _MACOSX BF2_STATIC_PLUGINS=1) +endif() source_group(TREE "${BF2_ROOT}" PREFIX "BF2" FILES ${bf2_client_sources} ${bf2_engine_headers} @@ -830,6 +868,46 @@ source_group(TREE "${BF2_EXTERNAL_ROOT}/GameSpy" FILES ${bf2_gamespy_cdkeyc_sources} ) +# ================================================================================================= +# bf2_gamespy_voice_objects - GameSpy Voice 2 and its Speex 1.0.5 codec, statically linked in BF2.exe +# (the client voice client, Game/VoipClient). Stock upstream C, LINKED not reversed: the Voice2 core, +# the platform's hardware layer (DirectSound on Windows, as retail; the SDK's CoreAudio layer on macOS) +# and the custom-device file the test device builds on. Speex: only the libspeex files the narrowband +# and wideband codecs need - no SLOW_TRIG, no tools (External/speex-1.0.5/LOCAL_CHANGES.md). +# Client images only. +# ================================================================================================= +set(bf2_gamespy_voice_sources + "${BF2_EXTERNAL_ROOT}/GameSpy/Voice2/gvMain.c" + "${BF2_EXTERNAL_ROOT}/GameSpy/Voice2/gvSource.c" + "${BF2_EXTERNAL_ROOT}/GameSpy/Voice2/gvFrame.c" + "${BF2_EXTERNAL_ROOT}/GameSpy/Voice2/gvCodec.c" + "${BF2_EXTERNAL_ROOT}/GameSpy/Voice2/gvSpeex.c" + "${BF2_EXTERNAL_ROOT}/GameSpy/Voice2/gvDevice.c" + "${BF2_EXTERNAL_ROOT}/GameSpy/Voice2/gvUtil.c" + "${BF2_EXTERNAL_ROOT}/GameSpy/Voice2/gvCustomDevice.c" +) +if(WIN32) + list(APPEND bf2_gamespy_voice_sources "${BF2_EXTERNAL_ROOT}/GameSpy/Voice2/gvDirectSound.c") +elseif(APPLE) + list(APPEND bf2_gamespy_voice_sources "${BF2_EXTERNAL_ROOT}/GameSpy/Voice2/gvOSXAudio.c") +endif() +foreach(speex_unit bits cb_search exc_10_16_table exc_10_32_table exc_20_32_table exc_5_256_table + exc_5_64_table exc_8_128_table filters gain_table gain_table_lbr hexc_10_32_table hexc_table + high_lsp_tables lpc lsp lsp_tables_nb ltp misc modes nb_celp quant_lsp sb_celp speex_callbacks + vbr vq) + list(APPEND bf2_gamespy_voice_sources "${BF2_EXTERNAL_ROOT}/speex-1.0.5/libspeex/${speex_unit}.c") +endforeach() +# Client/test dependencies opt in; Linux dedicated builds have no Voice2 hardware backend. +add_library(bf2_gamespy_voice_objects OBJECT EXCLUDE_FROM_ALL ${bf2_gamespy_voice_sources}) +bf2_configure_c_target(bf2_gamespy_voice_objects) +target_include_directories(bf2_gamespy_voice_objects PRIVATE + "${BF2_EXTERNAL_ROOT}/speex-1.0.5/include" + "${BF2_EXTERNAL_ROOT}/speex-1.0.5/include/speex") # gvSpeex.c includes +source_group(TREE "${BF2_EXTERNAL_ROOT}" + PREFIX "External" + FILES ${bf2_gamespy_voice_sources} +) + # Client ProfileManager uses the stock presence SDK. Source set follows the # upstream gp/gptestc project, excluding its sample and already shared common TUs. set(bf2_gamespy_gp_sources @@ -899,9 +977,9 @@ set_target_properties(bf2_engine_objects bf2_zlib_objects bf2_tinyxml_objects # harness (bounded frames, object probes, RVA-printing fault handler) lives in Code/Build/bootmain.cpp # and is reached only through Code/Build/bootrun.cmd; it is deliberately NOT linked here. # -# âš  The x86 diagnostic target retains /FORCE: every unwritten function links at RVA 0 and faults -# when reached. The x64 target DOES NOT use /FORCE. It must not emit a runnable image until every -# compile, dependency, and strict-link requirement is satisfied. +# Both Windows executables link strictly: zero unresolved symbols were measured in +# the x86 companion with MSVC 14.44 and the matching dice_py.lib. +# Side-DLL link contracts and runtime frontiers remain independent of the executable's link. # # OUTPUT: /.exe. The default is inside that architecture's # build tree, NEVER the game folder: D:/B2BF Launcher/Battlefield2/bf2_w32ded.exe is the ORIGINAL @@ -930,6 +1008,14 @@ if(BF2_BUILD_LINUX) set(BF2_DEDICATED_DEFAULT_OUTPUT_DIR "${CMAKE_BINARY_DIR}/bin_linux") set(BF2_DICE_PY_DEFAULT_DIR "") set(BF2_DICE_PY_BUILD_HINT "libdice_py.so is a CMake target (dice_py) on Linux") +elseif(BF2_BUILD_MACOS) + # [CHOSEN, not recovered] The macOS port keeps the Linux names: `bf2` beside libdice_py.dylib, + # found through an @loader_path rpath. + set(BF2_DEDICATED_TARGET "bf2") + set(BF2_DEDICATED_OUTPUT_NAME "bf2") + set(BF2_DEDICATED_DEFAULT_OUTPUT_DIR "${CMAKE_BINARY_DIR}/bin_macos") + set(BF2_DICE_PY_DEFAULT_DIR "") + set(BF2_DICE_PY_BUILD_HINT "libdice_py.dylib is a CMake target (dice_py) on macOS") elseif(BF2_BUILD_X64) set(BF2_DEDICATED_TARGET "bf2_w64ded") set(BF2_DEDICATED_OUTPUT_NAME "bf2_w64ded") @@ -950,8 +1036,9 @@ else() endif() set(BF2_DEDICATED_OUTPUT_DIR "${BF2_DEDICATED_DEFAULT_OUTPUT_DIR}" CACHE PATH "Where ${BF2_DEDICATED_OUTPUT_NAME}.exe is written (never the retail game directory)") -if(BF2_BUILD_LINUX) - # libdice_py.so - the embedded CPython 2.3.4 as a shared library, built beside `bf2`. +if(BF2_BUILD_POSIX) + # libdice_py.so/.dylib - the embedded CPython 2.3.4 as a shared library, built beside `bf2`. + # One build description serves both POSIX ports; it selects the platform's pyconfig.h itself. set(BF2_DICE_PY_OUTPUT_DIR "${BF2_DEDICATED_OUTPUT_DIR}") if(EXISTS "${BF2_EXTERNAL_ROOT}/python-embedded/linux/CMakeLists.txt") add_subdirectory("${BF2_EXTERNAL_ROOT}/python-embedded/linux" "${CMAKE_BINARY_DIR}/dice_py") @@ -989,7 +1076,7 @@ set_target_properties("${BF2_DEDICATED_TARGET}" PROPERTIES PDB_OUTPUT_DIRECTORY "${BF2_DEDICATED_OUTPUT_DIR}" FOLDER "BF2" ) -if(BF2_BUILD_LINUX) +if(BF2_BUILD_POSIX) if(TARGET dice_py) target_link_libraries("${BF2_DEDICATED_TARGET}" PRIVATE dice_py) endif() @@ -1005,6 +1092,16 @@ else() "${BF2_DEDICATED_TARGET}: ${BF2_DICE_PY_LIB} is missing. " "${BF2_DICE_PY_BUILD_HINT}.") endif() +if(BF2_BUILD_X64 AND NOT BF2_BUILD_LINUX) + # [CHOSEN, not recovered] The native Windows x64 port links the voice-server module statically, + # like the Linux image (which adds the same sources above). The BF2VoipServer_w32ded.dll side + # image (bf2_voipserver, below) is x86-only: it is defined under NOT BF2_BUILD_X64 and its .def + # pins x86 decorated names. Without these sources the strict x64 link has no CBF2VoipServer + # definitions for VoipServerInternal. + target_sources("${BF2_DEDICATED_TARGET}" PRIVATE + ${bf2_voipserver_only_sources} + ) +endif() # dice_py IS A REAL DLL, so linking dice_py.lib is only half the job - the DLL has to be FOUND at # run time. Windows searches the executable's own directory before the working directory, and the # run target deliberately sets the working directory to the GAME folder, so the only place that @@ -1015,7 +1112,7 @@ endif() # copy_if_different so a rebuild does not touch the file when nothing changed. # NOTE: the guard is evaluated at CONFIGURE time, exactly like the .lib check below it. If the DLL # is built later by Code/Build/python/build_python.cmd, re-run CMake once so this rule appears. -if(BF2_BUILD_LINUX) +if(BF2_BUILD_POSIX) # Nothing to stage: the dice_py target writes libdice_py.so into BF2_DEDICATED_OUTPUT_DIR, and # the executable carries an $ORIGIN rpath (below) so the pair can be copied anywhere together. elseif(EXISTS "${BF2_DICE_PY_DLL}") @@ -1054,6 +1151,22 @@ if(BF2_BUILD_LINUX) -pthread "-Wl,-Map=${BF2_DEDICATED_OUTPUT_DIR}/${BF2_DEDICATED_OUTPUT_NAME}.map" ) +elseif(BF2_BUILD_MACOS) + # [CHOSEN, not recovered] The macOS counterparts of the Linux link contract above: libSystem + # supplies pthreads, dl and libm; ncurses comes from the SDK. libdice_py.dylib is resolved + # beside the executable through @loader_path, the Mach-O spelling of $ORIGIN. ld64 rejects + # undefined symbols by default, so this link is strict like the Linux one. There is no + # static-runtime option: libc++ is part of the OS on macOS. + target_link_libraries("${BF2_DEDICATED_TARGET}" PRIVATE + Threads::Threads ${CMAKE_DL_LIBS} ${CURSES_LIBRARIES}) + set_target_properties("${BF2_DEDICATED_TARGET}" PROPERTIES + BUILD_RPATH "@loader_path" + INSTALL_RPATH "@loader_path" + BUILD_WITH_INSTALL_RPATH TRUE + ) + target_link_options("${BF2_DEDICATED_TARGET}" PRIVATE + "-Wl,-map,${BF2_DEDICATED_OUTPUT_DIR}/${BF2_DEDICATED_OUTPUT_NAME}.map" + ) else() target_link_libraries("${BF2_DEDICATED_TARGET}" PRIVATE advapi32 user32 shell32 dbghelp ws2_32) target_link_options("${BF2_DEDICATED_TARGET}" PRIVATE @@ -1068,18 +1181,14 @@ target_link_options("${BF2_DEDICATED_TARGET}" PRIVATE "/MAP:${BF2_DEDICATED_OUTPUT_DIR}/${BF2_DEDICATED_OUTPUT_NAME}.map" /IGNORE:4006,4088,4098 ) -if(NOT BF2_BUILD_X64) - target_link_options("${BF2_DEDICATED_TARGET}" PRIVATE /FORCE) -else() +if(BF2_BUILD_X64) target_link_options("${BF2_DEDICATED_TARGET}" PRIVATE /OPT:REF /OPT:ICF /INCREMENTAL:NO) endif() -endif() # BF2_BUILD_LINUX / MSVC link contracts +endif() # BF2_BUILD_LINUX / BF2_BUILD_MACOS / MSVC link contracts # ================================================================================================= # bf2_aidll - THE BOT-AI SIDE-DLL IMAGE. -# The native-x64 profile is intentionally dedicated-only. Do not let it emit x64 binaries under -# the shipped x86 AIDLL/BF2 names; those ports require separate targets and ABI validation. -if(NOT BF2_BUILD_X64) +# Native 64-bit ports build the same manifest with their host ABI; they cannot load x86 AI. # # AIDLL_w32ded.dll is a THIRD server-side image built from this same tree: bf2_w32ded.exe loads it # through ai::AIConnection::init -> LoadLibraryBf -> the exported initDll, and reaches it afterwards @@ -1093,11 +1202,10 @@ if(NOT BF2_BUILD_X64) # below is therefore its own compilation, and it MIRRORS Code/Build/aidll.cmd. Keep the two lists # in step; aidll.cmd is the one the harness and every gate use. # -# EXCLUDE_FROM_ALL, and /FORCE for the same reason bf2_w32ded is: every unwritten function links at -# RVA 0 and faults BY NAME on the path that reaches it. The only unresolved symbol today is -# ai::informationManager, the InformationManager frontier BF2AI.cpp declares and chunk 02 fills. +# EXCLUDE_FROM_ALL; x86 Windows retains its diagnostic /FORCE link. Native 64-bit images link +# strictly. The executable's link does not establish the side-DLL's completeness. # -# OUTPUT: /AIDLL_w32ded.dll - the build tree's bin/, NEVER the game folder. +# x86 OUTPUT: /AIDLL_w32ded.dll - the build tree's bin/, NEVER the game folder. # "D:/B2BF Launcher/Battlefield2/AIDLL_w32ded.dll" is the REFERENCE binary. The server reaches the # rebuilt DLL through a RELATIVE `AIDLL` setting (LoadLibraryBf builds ".\\" + name against the # current directory); Code/Tests/aidll/run.py does exactly that and copies nothing. @@ -1105,109 +1213,99 @@ if(NOT BF2_BUILD_X64) set(BF2_AIDLL_OUTPUT_DIR "${CMAKE_BINARY_DIR}/bin" CACHE PATH "Where AIDLL_w32ded.dll is written (NOT the game folder - the original lives there)") -add_library(bf2_aidll SHARED EXCLUDE_FROM_ALL - # group 1 - the module entry point; engine code compiled into every side-DLL, never into the exe - "${BF2_ROOT}/Core/DllModule.cpp" - "${BF2_ROOT}/Core/DllGlobals.cpp" - # group 2 - the AIDLL-only AI translation units - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/BotMain.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/BotNavigation.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/BotSquad.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/SensingAgent.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/CommunicationAgent.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/BotSenses.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIPlanInterpreter/BAPContext.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/InformationManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/Information.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/WeaponInfo.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/IPIArmament.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/IPIArmamentReal.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/IPICover.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/IPIMobile.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/IPIMobileReal.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/IPIMobileKnown.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/IPIUnit.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/InformationReal.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/WeaponInfoReal.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/IPIPhysicalReal.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIUtils/VehicleOccupancy.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/AIInformationGrid.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIUtils/DebugRendering/AIRenderUtil.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/WeaponInfoManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/BFInformationCourier.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/InformationFactory.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicMap/BFStrategicEnvironment.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicMap/BotSpawner.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/DrawPrimitives/DPManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AICollisionHandler.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AIEventCourier.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AIMineManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AIPlayerCourier.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/BFPathfindingCourier.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/Material/Material.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/Material/MaterialManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/NavMesh/MapProperties.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTree.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeNode.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNodeManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicMap/AerialHeightMap.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIPlanInterpreter/BAPEntries.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/SensingAgentPatterns.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/SquadManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/SquadCoordinator.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/SquadFormation.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/SquadMember.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBotBehaviour/CustomCurve.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/BotMemory.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/BotSubObjects.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBotBehaviour/UrgencyMerger.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AIConsole.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBotBehaviour/UrgeCurve.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNodeManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPositionManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicEntity/AILandingZoneManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObject.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicEntity/AIStrategicArea.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicEntity/SAWayPoint.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategic/SAI.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/BotBehaviourManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/CommunicationHub.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/StrategyManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AIPathfinding.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/IAIPathfinding.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/UserOrderManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AIMain.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AIModule.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AIRandom.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AILODManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/IBotManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AISettings.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AISingletonServer.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/BF2AI.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/BotManager.cpp" - # group 3 - present in BOTH shipped images - "${BF2_ROOT}/AI/AIDLL/AI/Main/CommonSingletonServer.cpp" - # group 4 - engine translation units libaidll.so statically links, added as the strict link - # demands them (census/00_statically_linked_engine_code.tsv confirms each one is really there) - "${BF2_ROOT}/Core/ConsoleObjects.cpp" # 0x4865C0.. - registerConsoleObjects, AIModule::init - "${BF2_ROOT}/Core/ConsoleObjectBase.cpp" # the ConsoleClassN base - the ai.init binding - "${BF2_ROOT}/Math/Frustum.cpp" # a bot sees by frustum - BotSenses - "${BF2_ROOT}/Math/Mat4Inverse.cpp" # AIDLL PE body matches the recovered client PE body - "${BF2_ROOT}/AI/AIInterface/BFKnowledge/PlanePolygon.cpp" # physical-cover fallback dependency - "${BF2_ROOT}/Math/Plane3.cpp" # Frustum pulls Plane3::transform + intersect - "${BF2_ROOT}/Math/Vec3.cpp" # Vec3::getZero - BotMain's constructor - "${BF2_ROOT}/Core/Debug.cpp" # 0x487C30.. - Debug ctor/dtor, reached by checkPointer - "${BF2_ROOT}/Core/StringUtil.cpp" # 0x487AF0 - calcStringHashValueNoCase, for StringHashFunc - # Kept in step with Code/Build/aidll.cmd (2026-09-28): File.cpp joined that manifest on - # 2026-09-11 without this list; PlayerInput.cpp joins both for Input::setInput. - "${BF2_ROOT}/IO/File/File.cpp" # io::File - AerialHeightMap's file paths - "${BF2_ROOT}/IO/Input/PlayerInput.cpp" # 0x18F020 - setInput(float), the plan executor -) +# The AI side-DLL manifest, in link order (= static-initialisation order), shared with aidll.cmd. +set(bf2_aidll_manifest "${CMAKE_CURRENT_SOURCE_DIR}/Code/Build/aidll_sources.txt") +set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${bf2_aidll_manifest}") +file(STRINGS "${bf2_aidll_manifest}" bf2_aidll_manifest_lines) +set(bf2_aidll_sources) +foreach(bf2_aidll_line IN LISTS bf2_aidll_manifest_lines) + string(STRIP "${bf2_aidll_line}" bf2_aidll_line) + if(bf2_aidll_line AND NOT bf2_aidll_line MATCHES "^#") + list(APPEND bf2_aidll_sources "${BF2_ROOT}/${bf2_aidll_line}") + endif() +endforeach() +add_library(bf2_aidll SHARED EXCLUDE_FROM_ALL ${bf2_aidll_sources}) +if(BF2_BUILD_POSIX) + # [CHOSEN, not recovered] Native POSIX AI image (Linux libaidll.so, macOS libaidll.dylib; a + # native-port design, not retail); same host toolchain and STL ABI as bf2. Never substitute the + # retail 32-bit libaidll.so. + bf2_configure_cpp_target(bf2_aidll) + bf2_set_image(bf2_aidll 1) + bf2_set_platform_compat(bf2_aidll) + target_compile_definitions(bf2_aidll PRIVATE BF2_IMAGE_AIDLL=1 BF2_PLATFORM_POSIX) + target_include_directories(bf2_aidll PRIVATE ${BF2_PYTHON_INCLUDE_DIRS}) + target_link_libraries(bf2_aidll PRIVATE Threads::Threads ${CMAKE_DL_LIBS}) + set_target_properties(bf2_aidll PROPERTIES + OUTPUT_NAME aidll + LIBRARY_OUTPUT_DIRECTORY "${BF2_DEDICATED_OUTPUT_DIR}" + FOLDER "BF2") + # Keep module globals private, including names also defined by the engine. The only + # cross-image entry points are the existing ClassManager handshake exports. + if(BF2_BUILD_MACOS) + target_link_options(bf2_aidll PRIVATE + "-Wl,-exported_symbols_list,${CMAKE_CURRENT_SOURCE_DIR}/Code/AidllAbi/aidll-macos.exports") + set_property(TARGET bf2_aidll APPEND PROPERTY LINK_DEPENDS + "${CMAKE_CURRENT_SOURCE_DIR}/Code/AidllAbi/aidll-macos.exports") + else() + target_link_options(bf2_aidll PRIVATE + -Wl,--no-undefined + "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/Code/AidllAbi/aidll-posix.map") + set_property(TARGET bf2_aidll APPEND PROPERTY LINK_DEPENDS + "${CMAKE_CURRENT_SOURCE_DIR}/Code/AidllAbi/aidll-posix.map") + endif() + add_dependencies("${BF2_DEDICATED_TARGET}" bf2_aidll) + + # [CHOSEN, not recovered] Engine-free check of the real loader and export lookup. + add_executable(bf2_aidll_loader_check EXCLUDE_FROM_ALL + "${CMAKE_CURRENT_SOURCE_DIR}/Code/Tests/aidll/posix_loader.cpp" + "${BF2_ROOT}/Core/PluginDll.cpp") + bf2_configure_cpp_target(bf2_aidll_loader_check) + bf2_set_image(bf2_aidll_loader_check 1) + bf2_set_platform_compat(bf2_aidll_loader_check) + target_link_libraries(bf2_aidll_loader_check PRIVATE ${CMAKE_DL_LIBS}) + set_target_properties(bf2_aidll_loader_check PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${BF2_DEDICATED_OUTPUT_DIR}") + if(BF2_BUILD_MACOS) + set_target_properties(bf2_aidll_loader_check PROPERTIES BUILD_RPATH "@loader_path") + else() + set_target_properties(bf2_aidll_loader_check PROPERTIES BUILD_RPATH "\$ORIGIN") + endif() + add_dependencies(bf2_aidll_loader_check bf2_aidll) +elseif(BF2_BUILD_X64) + # [CHOSEN, not recovered] Windows x64 AI for the native client and dedicated server. + # https://github.com/kr4uzi/OpenBF2/issues/11. Keep the host's /MD, release STL layout, + # embedded debug information and pointer-truncation errors. The x64 link is strict. + bf2_configure_cpp_target(bf2_aidll) + bf2_set_image(bf2_aidll 1) + target_compile_definitions(bf2_aidll PRIVATE BF2_IMAGE_AIDLL=1 _ITERATOR_DEBUG_LEVEL=0) + target_compile_options(bf2_aidll PRIVATE ${BF2_CLIENT_X64_COMPILE_OPTIONS}) + target_include_directories(bf2_aidll PRIVATE ${BF2_PYTHON_INCLUDE_DIRS}) + set(bf2_aidll_x64_def "${CMAKE_CURRENT_SOURCE_DIR}/Code/AidllAbi/aidll-x64.def") + set_target_properties(bf2_aidll PROPERTIES + OUTPUT_NAME aidll + PREFIX "" + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin_client" + RUNTIME_OUTPUT_DIRECTORY_DEBUG "${CMAKE_BINARY_DIR}/bin_client" + RUNTIME_OUTPUT_DIRECTORY_RELEASE "${CMAKE_BINARY_DIR}/bin_client" + RUNTIME_OUTPUT_DIRECTORY_RECONSTRUCTION "${CMAKE_BINARY_DIR}/bin_client" + PDB_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin_client" + FOLDER "BF2") + target_link_libraries(bf2_aidll PRIVATE kernel32 user32 advapi32 ws2_32) + target_link_options(bf2_aidll PRIVATE + /DEBUG /OPT:REF /OPT:ICF /INCREMENTAL:NO /NODEFAULTLIB:python23.lib + "/DEF:${bf2_aidll_x64_def}" + "/MAP:${CMAKE_BINARY_DIR}/bin_client/aidll.map") + set_property(TARGET bf2_aidll APPEND PROPERTY LINK_DEPENDS "${bf2_aidll_x64_def}") + + # Stage on every server build, even if only the DLL changed since the last executable link. + add_custom_target(bf2_aidll_server_stage + COMMAND "${CMAKE_COMMAND}" -E make_directory "${BF2_DEDICATED_OUTPUT_DIR}" + COMMAND "${CMAKE_COMMAND}" -E copy_if_different + "$" "${BF2_DEDICATED_OUTPUT_DIR}/aidll.dll" + DEPENDS bf2_aidll + VERBATIM) + add_dependencies("${BF2_DEDICATED_TARGET}" bf2_aidll_server_stage) +else() set_target_properties(bf2_aidll PROPERTIES LINKER_LANGUAGE CXX OUTPUT_NAME AIDLL_w32ded @@ -1241,6 +1339,10 @@ target_link_options(bf2_aidll PRIVATE /IGNORE:4006,4088,4098 ) +endif() # POSIX / Windows AIDLL + +if(NOT BF2_BUILD_X64) + # ================================================================================================= # bf2_voipserver - THE VOICE-SERVER SIDE-DLL IMAGE. # @@ -1308,6 +1410,13 @@ if(TARGET bf2_voipserver) target_link_libraries("${BF2_DEDICATED_TARGET}" PRIVATE bf2_voipserver) endif() +# [CHOSEN, not recovered] Compatibility build alias: the production x86 server now links strictly. +# Like bf2_client_linkcheck, this emits only the production executable, not a second check image. +if(NOT BF2_BUILD_POSIX AND NOT BF2_BUILD_X64) + add_custom_target(bf2_w32ded_linkcheck DEPENDS bf2_w32ded) + set_property(TARGET bf2_w32ded_linkcheck PROPERTY FOLDER "BF2") +endif() + # ================================================================================================= # bf2_voipserver_client - THE CLIENT LISTEN-SERVER VOICE DLL. # @@ -1366,23 +1475,28 @@ set_target_properties(bf2_voipserver_standalone PROPERTIES bf2_configure_cpp_target(bf2_voipserver_standalone) bf2_set_image(bf2_voipserver_standalone 1) target_link_libraries(bf2_voipserver_standalone PRIVATE bf2_voipserver kernel32 user32 advapi32 ws2_32) +endif() # Windows x86 voice images + + +# The client and the editor build in both Windows configurations: x86, and the native x64 client +# ([CHOSEN, not recovered], https://github.com/B2BF/OpenBF2/issues/7). The x64 images keep the +# shipped file names (BF2.exe and its plugin DLLs, which BF2.exe loads by name) and are written only +# inside the x64 build tree. +if(NOT BF2_BUILD_POSIX) # ================================================================================================= -# bf2_client - THE CLIENT LINK-REACH IMAGE (2026-09-03). +# bf2_client - THE STRICTLY LINKED WINDOWS CLIENT. # -# This is a real /DDEDICATED=0 image. Modern link.exe does -# not enumerate unresolved symbols when /FORCE is active, so bf2_client_linkcheck below is the -# deliberately failing strict link whose diagnostics are the client work list. Both targets are -# EXCLUDE_FROM_ALL. Process startup constructs HUD, then stops before singleton registration (2026-09-05); -# this is not a runnable-client claim. RendDX9 now has a separately proven -# native registry/module ABI flavour, but its HWND/display-mode boundary and the exe-side -# BF2Render bridge are still open; SwiffPlayer's native AS host callbacks remain frontiers. Both plugin -# builds are staged beside this diagnostic host since 2026-09-08 (the bf2_client_plugins dependency below). +# This /DDEDICATED=0 image links without /FORCE on x86 and x64 when the matching +# dice_py import library is supplied (MSVC 14.44 checks, 2026-11-08). +# Four-way runs and the x64 movie check establish runtime reach; remaining engine +# frontiers still limit individual paths. The target stays EXCLUDE_FROM_ALL. +# Native plugins are staged beside the host by bf2_client_plugins below. # Output stays in this build tree and can never overwrite the retail BF2.exe used as # reverse-engineering evidence. # ================================================================================================= # Fixed inside this build tree on purpose: unlike the server's opt-in deployment directory, a -# diagnostic client target must never be redirected onto the retail BF2.exe (CMake clean would then +# client target must never be redirected onto the retail BF2.exe (CMake clean would then # own and could remove it). set(BF2_CLIENT_OUTPUT_DIR "${CMAKE_BINARY_DIR}/bin_client") @@ -1394,6 +1508,7 @@ add_executable(bf2_client EXCLUDE_FROM_ALL $ $ $ + $ ) set_target_properties(bf2_client PROPERTIES LINKER_LANGUAGE CXX @@ -1411,7 +1526,10 @@ set_target_properties(bf2_client PROPERTIES ) bf2_configure_cpp_target(bf2_client) bf2_set_image(bf2_client 0) -target_compile_definitions(bf2_client PRIVATE BF2_PLUGIN_ABI_NATIVE=1 _ITERATOR_DEBUG_LEVEL=0) +if(BF2_BUILD_X64) + add_dependencies(bf2_client bf2_aidll) +endif() +target_compile_definitions(bf2_client PRIVATE _ITERATOR_DEBUG_LEVEL=0) set_target_properties(bf2_client PROPERTIES VS_DEBUGGER_WORKING_DIRECTORY "${BF2_GAME_DIR}" VS_DEBUGGER_COMMAND_ARGUMENTS "+modPath mods/bf2 +fullscreen 0 +multi 1" @@ -1419,7 +1537,7 @@ set_target_properties(bf2_client PROPERTIES # Normal startup includes the movies; +restart remains an optional explicit skip. set(BF2_CLIENT_RUN_ARGS "+modPath;mods/bf2;+fullscreen;0;+multi;1" - CACHE STRING "Arguments for the diagnostic bf2_client_run target (a CMake ;-list).") + CACHE STRING "Arguments for the bf2_client_run target (a CMake ;-list).") add_custom_target(bf2_client_run COMMAND "$" ${BF2_CLIENT_RUN_ARGS} DEPENDS bf2_client @@ -1441,34 +1559,13 @@ if(EXISTS "${BF2_DICE_PY_DLL}") add_custom_command(TARGET bf2_client POST_BUILD COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${BF2_DICE_PY_DLL}" "${BF2_CLIENT_OUTPUT_DIR}/dice_py.dll" - COMMENT "Staging dice_py.dll beside the diagnostic BF2.exe" + COMMENT "Staging dice_py.dll beside BF2.exe" VERBATIM ) endif() -# The bounded Novint SDK surface contains no cross-compiler STL objects. Import -# names and the 32-byte ApplicationData carrier are read from the original client; -# the matching DLL supplies third-party bodies. -set(BF2_NOVINT_IMPORT_LIB "${CMAKE_BINARY_DIR}/novint_hfx/NovintHFX.lib") -add_custom_command(OUTPUT "${BF2_NOVINT_IMPORT_LIB}" - COMMAND "${CMAKE_COMMAND}" -E make_directory "${CMAKE_BINARY_DIR}/novint_hfx" - COMMAND "${CMAKE_AR}" /nologo /machine:x86 - "/def:${BF2_EXTERNAL_ROOT}/NovintHFX/NovintHFX.def" - "/out:${BF2_NOVINT_IMPORT_LIB}" - DEPENDS "${BF2_EXTERNAL_ROOT}/NovintHFX/NovintHFX.def" - VERBATIM -) -add_custom_target(bf2_novint_imports DEPENDS "${BF2_NOVINT_IMPORT_LIB}") -add_dependencies(bf2_client bf2_novint_imports) -target_link_libraries(bf2_client PRIVATE "${BF2_NOVINT_IMPORT_LIB}") -if(EXISTS "${BF2_GAME_DIR}/NovintHFX.dll") - add_custom_command(TARGET bf2_client POST_BUILD - COMMAND "${CMAKE_COMMAND}" -E copy_if_different - "${BF2_GAME_DIR}/NovintHFX.dll" "${BF2_CLIENT_OUTPUT_DIR}/NovintHFX.dll" - COMMENT "Staging the original Novint SDK companion beside the diagnostic BF2.exe" - VERBATIM - ) -endif() +# [CHOSEN, not recovered] The Novint Falcon is archived (Code/Archive/NovintFalcon, issue #17): no image +# imports or stages NovintHFX.dll. # [CHOSEN, not recovered] Build and stage one native client/plugin set: # https://github.com/B2BF/OpenBF2/issues/7. These DLLs target the rebuilt host only; @@ -1506,6 +1603,16 @@ endif() # # Rebuild and stage plugins on every client build. Their scripts do not emit full include # dependencies, so a glob over plugin sources would miss changes in shared engine headers. +# +# Each script takes the architecture as its flavour argument: `native` builds the x86 DLL into +# Code/Build/bin__native, `x64` the native x64 DLL into Code/Build/bin__x64. The x64 +# RendDX9.dll has no Bink import: it links the FFmpeg-based Bink stand-in (renddx9.cmd x64, +# Code/BF2/External/ffmpeg-bink/README.md); the x86 DLL imports binkw32.dll. +if(BF2_BUILD_X64) + set(BF2_PLUGIN_FLAVOUR x64) +else() + set(BF2_PLUGIN_FLAVOUR native) +endif() if(TRUE) # âš  EACH SCRIPT IS NAMED BY ITS FULL NATIVE PATH, not bare beside WORKING_DIRECTORY. cmd.exe # finds a bare script name only by searching the current directory, and that search is OFF @@ -1522,24 +1629,32 @@ if(TRUE) file(TO_NATIVE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/Code/Build/swiffplayer.cmd" BF2_SWIFFPLAYER_SCRIPT) file(TO_NATIVE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/Code/Build/textureatlasbuilder.cmd" BF2_TEXTUREATLAS_SCRIPT) add_custom_target(bf2_textureatlas_native - COMMAND cmd.exe /d /c "${BF2_TEXTUREATLAS_SCRIPT}" native + COMMAND cmd.exe /d /c "${BF2_TEXTUREATLAS_SCRIPT}" ${BF2_PLUGIN_FLAVOUR} WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/Code/Build" - COMMENT "Building the native TextureAtlasBuilder.dll (Code/Build/textureatlasbuilder.cmd native)" + COMMENT "Building the ${BF2_PLUGIN_FLAVOUR} TextureAtlasBuilder.dll (Code/Build/textureatlasbuilder.cmd ${BF2_PLUGIN_FLAVOUR})" VERBATIM ) set_property(TARGET bf2_textureatlas_native PROPERTY FOLDER "BF2") + # [CHOSEN, not recovered] G2w: BF2_GFX_SEAM=ON makes renddx9.cmd compile the renderer against the subset + # headers plus the generated forwarding backend (Platform/Gfx/D3D9Forward). + set(BF2_RENDDX9_SEAM_ENV) + if(BF2_GFX_SEAM) + set(BF2_RENDDX9_SEAM_ENV "${CMAKE_COMMAND}" -E env BF2_GFX_SEAM=ON) + endif() add_custom_target(bf2_renddx9_native - COMMAND cmd.exe /d /c "${BF2_RENDDX9_SCRIPT}" native + COMMAND ${BF2_FRONTIER_DEFAULT_ENV} ${BF2_RENDDX9_SEAM_ENV} cmd.exe /d /c "${BF2_RENDDX9_SCRIPT}" ${BF2_PLUGIN_FLAVOUR} WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/Code/Build" - COMMENT "Building the native RendDX9.dll (Code/Build/renddx9.cmd native)" + COMMENT "Building the ${BF2_PLUGIN_FLAVOUR} RendDX9.dll (Code/Build/renddx9.cmd ${BF2_PLUGIN_FLAVOUR})" VERBATIM ) set_property(TARGET bf2_renddx9_native PROPERTY FOLDER "BF2") - add_dependencies(bf2_renddx9_native bf2_textureatlas_native) + if(NOT BF2_GFX_SEAM) + add_dependencies(bf2_renddx9_native bf2_textureatlas_native) + endif() add_custom_target(bf2_swiffplayer_native - COMMAND cmd.exe /d /c "${BF2_SWIFFPLAYER_SCRIPT}" native + COMMAND ${BF2_FRONTIER_DEFAULT_ENV} cmd.exe /d /c "${BF2_SWIFFPLAYER_SCRIPT}" ${BF2_PLUGIN_FLAVOUR} WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/Code/Build" - COMMENT "Building the native SwiffPlayer.dll (Code/Build/swiffplayer.cmd native)" + COMMENT "Building the ${BF2_PLUGIN_FLAVOUR} SwiffPlayer.dll (Code/Build/swiffplayer.cmd ${BF2_PLUGIN_FLAVOUR})" VERBATIM ) set_property(TARGET bf2_swiffplayer_native PROPERTY FOLDER "BF2") @@ -1553,9 +1668,9 @@ if(TRUE) # ordering rule as the two above: after SwiffPlayer, never concurrently. file(TO_NATIVE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/Code/Build/bf2audio.cmd" BF2_BF2AUDIO_SCRIPT) add_custom_target(bf2_bf2audio_native - COMMAND cmd.exe /d /c "${BF2_BF2AUDIO_SCRIPT}" native + COMMAND ${BF2_FRONTIER_DEFAULT_ENV} cmd.exe /d /c "${BF2_BF2AUDIO_SCRIPT}" ${BF2_PLUGIN_FLAVOUR} WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/Code/Build" - COMMENT "Building the native BF2Audio.dll (Code/Build/bf2audio.cmd native)" + COMMENT "Building the ${BF2_PLUGIN_FLAVOUR} BF2Audio.dll (Code/Build/bf2audio.cmd ${BF2_PLUGIN_FLAVOUR})" VERBATIM ) set_property(TARGET bf2_bf2audio_native PROPERTY FOLDER "BF2") @@ -1565,26 +1680,26 @@ endif() set(BF2_PLUGIN_STAGE_SCRIPT "${CMAKE_CURRENT_SOURCE_DIR}/Code/Build/stage_plugin.cmake") add_custom_target(bf2_client_plugins COMMAND "${CMAKE_COMMAND}" - "-DBF2_PLUGIN_SRC=${CMAKE_CURRENT_SOURCE_DIR}/Code/Build/bin_renddx9_native/RendDX9.dll" + "-DBF2_PLUGIN_SRC=${CMAKE_CURRENT_SOURCE_DIR}/Code/Build/bin_renddx9_${BF2_PLUGIN_FLAVOUR}/RendDX9.dll" "-DBF2_PLUGIN_DST_DIR=${BF2_CLIENT_OUTPUT_DIR}" - "-DBF2_PLUGIN_HINT=build it with Code/Build/renddx9.cmd native" + "-DBF2_PLUGIN_HINT=build it with Code/Build/renddx9.cmd ${BF2_PLUGIN_FLAVOUR}" -P "${BF2_PLUGIN_STAGE_SCRIPT}" COMMAND "${CMAKE_COMMAND}" - "-DBF2_PLUGIN_SRC=${CMAKE_CURRENT_SOURCE_DIR}/Code/Build/bin_swiffplayer_native/SwiffPlayer.dll" + "-DBF2_PLUGIN_SRC=${CMAKE_CURRENT_SOURCE_DIR}/Code/Build/bin_swiffplayer_${BF2_PLUGIN_FLAVOUR}/SwiffPlayer.dll" "-DBF2_PLUGIN_DST_DIR=${BF2_CLIENT_OUTPUT_DIR}" - "-DBF2_PLUGIN_HINT=build it with Code/Build/swiffplayer.cmd native" + "-DBF2_PLUGIN_HINT=build it with Code/Build/swiffplayer.cmd ${BF2_PLUGIN_FLAVOUR}" -P "${BF2_PLUGIN_STAGE_SCRIPT}" COMMAND "${CMAKE_COMMAND}" - "-DBF2_PLUGIN_SRC=${CMAKE_CURRENT_SOURCE_DIR}/Code/Build/bin_bf2audio_native/BF2Audio.dll" + "-DBF2_PLUGIN_SRC=${CMAKE_CURRENT_SOURCE_DIR}/Code/Build/bin_bf2audio_${BF2_PLUGIN_FLAVOUR}/BF2Audio.dll" "-DBF2_PLUGIN_DST_DIR=${BF2_CLIENT_OUTPUT_DIR}" - "-DBF2_PLUGIN_HINT=build it with Code/Build/bf2audio.cmd native" + "-DBF2_PLUGIN_HINT=build it with Code/Build/bf2audio.cmd ${BF2_PLUGIN_FLAVOUR}" -P "${BF2_PLUGIN_STAGE_SCRIPT}" COMMAND "${CMAKE_COMMAND}" - "-DBF2_PLUGIN_SRC=${CMAKE_CURRENT_SOURCE_DIR}/Code/Build/bin_textureatlasbuilder_native/TextureAtlasBuilder.dll" + "-DBF2_PLUGIN_SRC=${CMAKE_CURRENT_SOURCE_DIR}/Code/Build/bin_textureatlasbuilder_${BF2_PLUGIN_FLAVOUR}/TextureAtlasBuilder.dll" "-DBF2_PLUGIN_DST_DIR=${BF2_CLIENT_OUTPUT_DIR}" - "-DBF2_PLUGIN_HINT=build it with Code/Build/textureatlasbuilder.cmd native" + "-DBF2_PLUGIN_HINT=build it with Code/Build/textureatlasbuilder.cmd ${BF2_PLUGIN_FLAVOUR}" -P "${BF2_PLUGIN_STAGE_SCRIPT}" - COMMENT "Staging the four native plugins beside the diagnostic BF2.exe" + COMMENT "Staging the four ${BF2_PLUGIN_FLAVOUR} plugins beside BF2.exe" VERBATIM ) # Ordering AND obligation: all four plugin builds complete before anything is copied. This @@ -1593,6 +1708,13 @@ add_custom_target(bf2_client_plugins # point where it hurts, which is a live debugging session. add_dependencies(bf2_client_plugins bf2_textureatlas_native bf2_renddx9_native bf2_swiffplayer_native bf2_bf2audio_native) add_dependencies(bf2_client bf2_client_plugins) +# The subsystem version that keeps the classic (pre-6.0) window frame; see the link options below. +# x64: 5.02, the lowest version link.exe accepts for an x64 image, on the same side of 6.0. +if(BF2_BUILD_X64) + set(BF2_CLIENT_SUBSYSTEM "/SUBSYSTEM:WINDOWS,5.02") +else() + set(BF2_CLIENT_SUBSYSTEM "/SUBSYSTEM:WINDOWS,5.01") +endif() # System imports present in the retail BF2.exe. target_link_libraries(bf2_client PRIVATE advapi32 crypt32 dbghelp dinput8 dsound dxguid gdi32 ole32 psapi shell32 user32 winmm ws2_32 @@ -1602,8 +1724,20 @@ target_link_libraries(bf2_client PRIVATE if(TARGET bf2_voipserver_client) target_link_libraries(bf2_client PRIVATE bf2_voipserver_client) endif() +# [CHOSEN, not recovered] x64 (issue #7): BF2VoipServer.dll is x86-only (its .def pins x86 decorated +# names), so the native x64 client links the voice-server module statically, as the x64 dedicated +# server and the macOS client do. Client image (/DDEDICATED=0), same sources as bf2_voipserver_client. +if(BF2_BUILD_X64) + add_library(bf2_voipserver_client_objects OBJECT EXCLUDE_FROM_ALL ${bf2_voipserver_only_sources}) + bf2_configure_cpp_target(bf2_voipserver_client_objects) + bf2_set_image(bf2_voipserver_client_objects 0) + bf2_set_platform_compat(bf2_voipserver_client_objects) + target_compile_definitions(bf2_voipserver_client_objects PRIVATE _ITERATOR_DEBUG_LEVEL=0) + target_compile_options(bf2_voipserver_client_objects PRIVATE ${BF2_CLIENT_X64_COMPILE_OPTIONS}) + set_property(TARGET bf2_voipserver_client_objects PROPERTY FOLDER "BF2") + target_sources(bf2_client PRIVATE $) +endif() target_link_options(bf2_client PRIVATE - /FORCE /INCREMENTAL:NO /DEBUG # âš  THE ",4.0" IS LOAD-BEARING, AND IT IS A FIDELITY SETTING, NOT A PREFERENCE. @@ -1626,7 +1760,7 @@ target_link_options(bf2_client PRIVATE # default subsystem version assumed" and silently falls back to 6.0, which is the bug. 5.01 is # the lowest value it accepts for x86. What governs the frame is the 6.0 boundary, so 5.01 and # retail's 4.0 behave identically here; the field itself still differs from the shipped image. - /SUBSYSTEM:WINDOWS,5.01 + "${BF2_CLIENT_SUBSYSTEM}" /NODEFAULTLIB:python23.lib "/MAP:${BF2_CLIENT_OUTPUT_DIR}/BF2.map" /IGNORE:4006,4088,4098 @@ -1634,56 +1768,454 @@ target_link_options(bf2_client PRIVATE set_property(TARGET bf2_client_objects PROPERTY FOLDER "BF2") -# Strict companion to bf2_client. This target is EXPECTED TO FAIL until every client external is -# recovered; the final LNK1120 count and the preceding symbol names are the measured whole-image -# work list (shared engine debt included, not a client-only delta). -# /FORCE:MULTIPLE tolerates the five known duplicate FileChangeManager constants without tolerating -# unresolveds. Keeping it separate lets bf2_client emit the RVA-0 PE used for map/import checks. -add_executable(bf2_client_linkcheck EXCLUDE_FROM_ALL - $ - $ - $ - $ - $ - $ - $ -) -set_target_properties(bf2_client_linkcheck PROPERTIES - LINKER_LANGUAGE CXX - WIN32_EXECUTABLE TRUE - OUTPUT_NAME BF2_linkcheck - RUNTIME_OUTPUT_DIRECTORY "${BF2_CLIENT_OUTPUT_DIR}" - RUNTIME_OUTPUT_DIRECTORY_DEBUG "${BF2_CLIENT_OUTPUT_DIR}" - RUNTIME_OUTPUT_DIRECTORY_RELEASE "${BF2_CLIENT_OUTPUT_DIR}" - RUNTIME_OUTPUT_DIRECTORY_RECONSTRUCTION "${BF2_CLIENT_OUTPUT_DIR}" - PDB_OUTPUT_DIRECTORY "${BF2_CLIENT_OUTPUT_DIR}" - PDB_OUTPUT_DIRECTORY_DEBUG "${BF2_CLIENT_OUTPUT_DIR}" - PDB_OUTPUT_DIRECTORY_RELEASE "${BF2_CLIENT_OUTPUT_DIR}" - PDB_OUTPUT_DIRECTORY_RECONSTRUCTION "${BF2_CLIENT_OUTPUT_DIR}" - FOLDER "BF2" -) -bf2_configure_cpp_target(bf2_client_linkcheck) -bf2_set_image(bf2_client_linkcheck 0) +# Compatibility build alias: bf2_client itself now performs the strict link. +add_custom_target(bf2_client_linkcheck DEPENDS bf2_client) +set_property(TARGET bf2_client_linkcheck PROPERTY FOLDER "BF2") -if(EXISTS "${BF2_DICE_PY_LIB}") - target_link_libraries(bf2_client_linkcheck PRIVATE "${BF2_DICE_PY_LIB}") -endif() -target_link_libraries(bf2_client_linkcheck PRIVATE - advapi32 crypt32 dbghelp dinput8 dsound dxguid gdi32 ole32 psapi shell32 user32 winmm ws2_32 -) -add_dependencies(bf2_client_linkcheck bf2_novint_imports) -target_link_libraries(bf2_client_linkcheck PRIVATE "${BF2_NOVINT_IMPORT_LIB}") -target_link_options(bf2_client_linkcheck PRIVATE - /FORCE:MULTIPLE - /INCREMENTAL:NO - /DEBUG - /SUBSYSTEM:WINDOWS - /NODEFAULTLIB:python23.lib -) - -# The BF2 Editor links the client object -# set above, so it lives in this Windows-x86-only block. Every editor target is EXCLUDE_FROM_ALL. +# The BF2 Editor links the client object set above, so it lives in this Windows client block +# (x86 and native x64). Every editor target is EXCLUDE_FROM_ALL. add_subdirectory(Code/Tools/BF2Editor) +endif() # NOT BF2_BUILD_POSIX (client and editor) + +# ================================================================================================= +# bf2_client on macOS - THE NATIVE macOS CLIENT IMAGE. [CHOSEN, not recovered] +# +# An owner-requested port change (macOSplan.md, package S2.0; docs/macos-port.md, "Client triage"). +# The client objects above are compiled with DEDICATED=0 and the macOS platform switches. The client +# plugin images are not shared libraries here: retail-DLL swapping is retired +# (https://github.com/B2BF/OpenBF2/issues/7), so RendDX9, SwiffPlayer and BF2Audio are static +# libraries, and Code/StaticPlugins/StaticPlugins.cpp answers the engine's LoadLibrary/GetProcAddress +# lookups for the ones linked in (BF2_STATIC_PLUGINS). RendDX9 is not linked by default; see +# BF2_MACOS_LINK_RENDDX9 below. Each library compiles its image's manifest +# from Code/Build/.cmd with that image's define; keep the lists in step with the scripts. +# Left out of every library: the Windows loader entry (RendDX9Abi/DllMain.cpp) and the engine TUs the +# host image already compiles (Math/*, Core/ConsoleObjectBase.cpp), because one image holds one copy. +# The RendDX9Abi kit (heap adapters, vc71 string, frontier log) is compiled once, in +# bf2_plugin_kit_static, for the same reason. The three plugin entry pairs are renamed per image so +# they can coexist in one link. TextureAtlasBuilder is embedded in the native renderer. +# +# The link is strict (ld64 rejects undefined symbols). It does not complete yet: the compile triage +# in docs/macos-port.md lists the blocked translation units by blocker class. +# ================================================================================================= +if(BF2_BUILD_MACOS) + set(BF2_RENDDX9_STATIC_SOURCES + "${CMAKE_CURRENT_SOURCE_DIR}/Code/RendDX9Abi/CrashReport.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Code/RendDX9Abi/EngineFile.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Code/RendDX9Abi/PluginEntry.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Code/RendDX9Abi/NativeConsoleObjects.cpp" + # [CHOSEN, not recovered] The binkw32 entry points on the vendored FFmpeg Bink decoders + # (bf2_ffmpeg_bink below; Code/BF2/External/ffmpeg-bink/README.md) and their AudioQueue sound output. + "${CMAKE_CURRENT_SOURCE_DIR}/Code/RendDX9Abi/BinkFFmpeg.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Code/RendDX9Abi/BinkAudioCoreAudio.cpp" + ) + # Code/Build/renddx9.cmd, STEP 2: SOURCES minus the kit, DllMain.cpp and the shared Math TUs, + # then CONSOLE_SOURCES minus Core/ConsoleObjectBase.cpp. + foreach(rel + RendDX9/BF2Render.cpp RendDX9/PostProductionFrameWork.cpp RendDX9/RendDX9Init.cpp + RendDX9/BufferManager.cpp RendDX9/QueryManager.cpp RendDX9/RendDX9Types.cpp + RendDX9/Texture.cpp RendDX9/TextureManager.cpp RendDX9/TextureAtlas/TextureAtlas.cpp + RendDX9/ResourceManager.cpp RendDX9/ResourceTracer.cpp RendDX9/VideoOptions.cpp + RendDX9/Effect.cpp RendDX9/DiceEffect.cpp + RendDX9/FXParameter.cpp RendDX9/ShaderManager.cpp RendDX9/StateManager.cpp + RendDX9/RendDX9Draw.cpp RendDX9/RenderQueues.cpp RendDX9/Ra/EffectManager.cpp + RendDX9/MovieRenderer.cpp + RendDX9/Ra/RaShaderPermutator.cpp RendDX9/Ra/RaShader.cpp RendDX9/Ra/RaVertexStreams.cpp + RendDX9/Ra/RaStreamDataEditable.cpp RendMisc/RendModule.cpp RendMisc/RenderView.cpp + RendMisc/EnvMapSystem/EnvMapManager.cpp RendMisc/EnvMapSystem/EnvMapObject.cpp + IO/Tokenizer.cpp Geom/ModuleGeom.cpp Geom/GeometryTemplateManager.cpp + Geom/MeshTemplate.cpp Geom/StaticMeshTemplate.cpp Geom/SkinnedMeshTemplate.cpp + Geom/SkinnedMesh.cpp Geom/BundledMeshTemplate.cpp Geom/BundledMeshMaterial.cpp + Geom/BundledMeshStateManager.cpp Geom/BundledMesh.cpp Geom/BundledMeshDraw.cpp + Geom/BundledMeshHeight.cpp Geom/StaticMesh.cpp Geom/StaticMeshLightmapGeneration.cpp + Geom/StaticMeshMaterial.cpp Geom/StaticMeshStateManager.cpp Geom/SkyDome.cpp + Geom/UndergrowthSystem.cpp Geom/UndergrowthSystemLoad.cpp + Geom/LightningManager.cpp Geom/WeatherManager.cpp Geom/Rain/RainManager.cpp + Geom/UndergrowthSystemRender.cpp Geom/Terrain.cpp Geom/QuadPatch.cpp + Geom/RaQuadPatchAdapter.cpp + Geom/SurroundingPatch.cpp Geom/TerrainDraw.cpp Geom/TerrainEditable.cpp + Geom/TerrainEditableGetSets.cpp Geom/QuadPatchEditable.cpp + Geom/SurroundingPatchEditable.cpp Geom/TerrainLightSampling.cpp + Geom/LightmapGeneration/LightmapGeneration.cpp + Geom/LightmapGeneration/MeshLightSampling.cpp Geom/ObjectDrawer.cpp + Geom/XpLightManager.cpp Geom/LightMerger.cpp Geom/LightGeometry.cpp Geom/MeshOptimizer.cpp + Geom/BundledMeshOptimizer.cpp Geom/StaticMeshOptimizer.cpp Geom/NametagManager.cpp Geom/NameTagRenderer.cpp + Geom/Overgrowth/OverGrowth.cpp Geom/Overgrowth/OverGrowthLoad.cpp + Geom/Overgrowth/OverGrowthCells.cpp Geom/Overgrowth/OverGrowthCellRender.cpp + Geom/Overgrowth/OverGrowthRender.cpp Geom/RoadCompiledRenderer.cpp + Geom/RoadCompiledTemplate.cpp Geom/RoadCompiled.cpp Geom/RoadTemplate.cpp + Geom/RoadEditableRenderer.cpp Geom/RoadEditable.cpp Geom/DecalSystem/DecalManager.cpp + Geom/DecalSystem/DecalShadowManager.cpp + Geom/DecalSystem/DecalObject.cpp Geom/DecalSystem/DecalTemplate.cpp + Geom/DecalSystem/DecalRenderer.cpp Geom/ParticleSystem/ParticleSystemManager.cpp + Geom/HemiMapManager/HemiMapManager.cpp Geom/ParticleSystem/ParticleSystemTemplate.cpp + Geom/ParticleSystem/ParticleSystemTemplateType1.cpp + Geom/ParticleSystem/MeshParticleMesh/MeshParticleMeshTemplate.cpp + Geom/ParticleSystem/MeshParticleMesh/MeshParticleMesh.cpp + Geom/ParticleSystem/TrailSystemTemplate.cpp + Geom/ParticleSystem/ParticleSystemTemplateType3.cpp + Geom/ParticleSystem/NSAParticleSystemTemplate.cpp Geom/StaticMeshRenderer.cpp + Geom/SkinnedMeshRenderer.cpp Geom/SwiffRender.cpp GeomMisc/ModuleGeomMisc.cpp + GeomMisc/FSQuadDrawer.cpp GeomMisc/DebugTextWriter.cpp GeomMisc/Debug.cpp + GeomMisc/DebugBoxMesh.cpp + GeomMisc/DebugCylinderMesh.cpp + GeomMisc/DebugSphereMesh.cpp + GeomMisc/DebugPlaneMesh.cpp + GeomMisc/DebugPolygonMesh.cpp + GeomMisc/DebugTorusMesh.cpp + GeomMisc/DebugXMesh.cpp + GeomMisc/DebugRenderer.cpp GeomMisc/DebugTextDrawer.cpp + GeomMisc/DebugCircleDrawer.cpp + GeomMisc/DebugLineDrawer.cpp + GeomMisc/FontSystem/FontSystem.cpp GeomMisc/FontSystem/SwiffFont.cpp + GeomMisc/OverlayTexture.cpp GeomMisc/DebugLineGraphD3d.cpp GeomMisc/PerlinNoise.cpp + GeomMisc/DebugBlockGraphD3D.cpp + GeomMisc/LoadingScreen/LoadingScreen.cpp + GeomMisc/SplineControlPoint.cpp GeomMisc/EditorSpline.cpp + GeomMisc/MenuRend/MemeTexture.cpp GeomMisc/MenuRend/FSMoviePlayer.cpp + GeomMisc/MenuRend/Video.cpp GeomMisc/MenuRend/QuadDrawer.cpp + GeomMisc/MenuRend/QuadOutputCache.cpp + Geom/LightManagerConsole.cpp Geom/HemiMapManager/HemiMapManagerConsole.cpp + Geom/SkyDomeConsole.cpp Geom/TerrainConsole.cpp RendDX9/RendererConsole.cpp + Geom/TerrainCullerConsole.cpp + Geom/NametagManagerConsole.cpp Geom/Overgrowth/OverGrowthConsole.cpp + Geom/UndergrowthSystemConsole.cpp Geom/DecalSystem/DecalManagerConsole.cpp + Geom/ObjectGeometryConsole.cpp Geom/LightmapGeneration/LightmapGenerationConsole.cpp + Geom/StaticMeshRendererConsole.cpp Geom/WeatherManagerConsole.cpp + Geom/HeightmapEventNode.cpp) + list(APPEND BF2_RENDDX9_STATIC_SOURCES "${BF2_ROOT}/${rel}") + endforeach() + + # Code/Build/swiffplayer.cmd, STEP 2, minus the kit and DllMain.cpp. + set(BF2_SWIFFPLAYER_STATIC_SOURCES + "${CMAKE_CURRENT_SOURCE_DIR}/Code/SwiffPlayerAbi/PluginEntry.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Code/SwiffPlayerAbi/SwiffMemory.cpp" + "${BF2_EXTERNAL_ROOT}/gameswf/SwiffPlayer/SwiffPlayer.cpp" + "${BF2_EXTERNAL_ROOT}/gameswf/SwiffPlayer/SwiffCrashLog.cpp" + "${BF2_EXTERNAL_ROOT}/gameswf/SwiffPlayer/SwiffPlayerModule.cpp" + ) + foreach(rel + base/config.cpp base/container.cpp base/file_util.cpp base/image.cpp + base/image_filters.cpp base/jpeg.cpp base/membuf.cpp base/tu_file.cpp base/tu_random.cpp + base/tu_timer.cpp base/tu_types.cpp base/utf8.cpp base/utility.cpp + gameswf/gameswf_action.cpp gameswf/gameswf_button.cpp gameswf/gameswf_dlist.cpp + gameswf/gameswf_font.cpp gameswf/gameswf_fontlib.cpp gameswf/gameswf_impl.cpp + gameswf/gameswf_log.cpp gameswf/gameswf_morph2.cpp + gameswf/gameswf_render.cpp gameswf/gameswf_shape.cpp gameswf/gameswf_sound.cpp + gameswf/gameswf_stream.cpp gameswf/gameswf_string.cpp gameswf/gameswf_styles.cpp + gameswf/gameswf_tesselate.cpp gameswf/gameswf_text.cpp + gameswf/gameswf_timers.cpp gameswf/gameswf_types.cpp gameswf/gameswf_xml.cpp) + list(APPEND BF2_SWIFFPLAYER_STATIC_SOURCES "${BF2_EXTERNAL_ROOT}/${rel}") + endforeach() + + # Code/Build/bf2audio.cmd, STEP 2, minus the kit. Win32System.cpp is that image's DllMain and + # its LoadLibrary wrappers; it stays in the list so the triage reports it (package S2.5). + set(BF2_BF2AUDIO_STATIC_SOURCES "${BF2_ROOT}/Sound/NullSound.cpp") + foreach(rel + Ambient.cpp BfOpenAL.cpp BfSoundEngine.cpp Music.cpp OpenALProvider.cpp + OpenALSample.cpp Reverb.cpp Sample.cpp Sound.cpp SoundDefaults.cpp SoundEvaluator.cpp + SoundFile.cpp SoundTrigger.cpp WavFileFormat.cpp Win32System.cpp) + list(APPEND BF2_BF2AUDIO_STATIC_SOURCES "${BF2_ROOT}/Sound/SoundEngine/${rel}") + endforeach() + set(BF2_VORBIS_STATIC_SOURCES + "${BF2_EXTERNAL_ROOT}/libogg-1.3.6/src/bitwise.c" + "${BF2_EXTERNAL_ROOT}/libogg-1.3.6/src/framing.c" + ) + foreach(name + analysis bitrate block codebook envelope floor0 floor1 info lookup lpc lsp mapping0 + mdct psy registry res0 sharedbook smallft synthesis vorbisfile window) + list(APPEND BF2_VORBIS_STATIC_SOURCES "${BF2_EXTERNAL_ROOT}/libvorbis-1.3.7/lib/${name}.c") + endforeach() + + # The settings every plugin library shares with the client objects. + function(bf2_configure_static_plugin target image_define) + bf2_configure_cpp_target("${target}") + bf2_set_image("${target}" 0) + bf2_set_platform_compat("${target}") + target_compile_definitions("${target}" PRIVATE + _ITERATOR_DEBUG_LEVEL=0 BF2_PLATFORM_POSIX _MACOSX + BF2_STATIC_PLUGINS=1 ${image_define}) + set_property(TARGET "${target}" PROPERTY FOLDER "BF2") + endfunction() + + # [CHOSEN, not recovered] Each statically linked plugin image keeps its own host-service globals + # (dice::hfe::classManager, settings, g_system, game and the rest that its PluginEntry.cpp + # defines and its initDll fills), as the DLL did. The host defines globals of the same names, + # often with other types. The image's static library is therefore prelinked into one + # relocatable object (ld -r) in which the symbols named in Code/StaticPlugins/ + # image-private-symbols.txt are bound to the image's own definitions and then made local; + # everything else keeps its linkage. See docs/macos-port.md, "Plugin globals". + # BF2Audio defines no host-service globals; its own null sound/template pair + # (Sound/SoundEngine/BfSoundEngine.cpp, created by getSoundEngine) is image-private in the + # same way and is listed in Code/StaticPlugins/bf2audio-private-symbols.txt. + set(BF2_STATIC_PLUGIN_PRIVATE_SYMBOLS + "${CMAKE_CURRENT_SOURCE_DIR}/Code/StaticPlugins/image-private-symbols.txt") + function(bf2_prelink_static_plugin consumer library symbols) + set(prelinked "${CMAKE_CURRENT_BINARY_DIR}/StaticPlugins/${library}_prelinked.o") + set(arch_flags "") + foreach(arch IN LISTS CMAKE_OSX_ARCHITECTURES) + list(APPEND arch_flags -arch "${arch}") + endforeach() + add_custom_command(OUTPUT "${prelinked}" + COMMAND "${CMAKE_COMMAND}" -E make_directory "${CMAKE_CURRENT_BINARY_DIR}/StaticPlugins" + COMMAND "${CMAKE_CXX_COMPILER}" ${arch_flags} -r -nostdlib -o "${prelinked}" + "-Wl,-force_load,$" + "-Wl,-unexported_symbols_list,${symbols}" + DEPENDS "${library}" "$" "${symbols}" + COMMENT "Prelinking ${library} with image-private host-service globals" + VERBATIM) + target_sources("${consumer}" PRIVATE "${prelinked}") + set_source_files_properties("${prelinked}" PROPERTIES EXTERNAL_OBJECT TRUE GENERATED TRUE) + endfunction() + + add_library(bf2_plugin_kit_static STATIC EXCLUDE_FROM_ALL + "${CMAKE_CURRENT_SOURCE_DIR}/Code/RendDX9Abi/BfMemory.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Code/RendDX9Abi/Frontier.cpp" + ) + bf2_configure_static_plugin(bf2_plugin_kit_static "") + if(BF2_FRONTIER_DEFAULT_CONTINUE) + target_compile_definitions(bf2_plugin_kit_static PRIVATE BF2_FRONTIER_DEFAULT_CONTINUE=1) + endif() + + add_library(bf2_renddx9_static STATIC EXCLUDE_FROM_ALL ${BF2_RENDDX9_STATIC_SOURCES}) + bf2_configure_static_plugin(bf2_renddx9_static BF2_IMAGE_RENDDX9) + # [CHOSEN, not recovered] Native factories/build/save use the renderer's Metal D3D9 seam. + set(BF2_TEXTURE_ATLAS_NATIVE_SOURCES + "${BF2_ROOT}/RendDX9/TextureAtlas/TextureAtlasBuilder/Packer.cpp" + "${BF2_ROOT}/RendDX9/TextureAtlas/TextureAtlasBuilder/TextureAtlas.cpp" + "${BF2_ROOT}/RendDX9/TextureAtlas/TextureAtlasBuilder/TextureAtlasConfiguration.cpp" + "${BF2_ROOT}/RendDX9/TextureAtlas/TextureAtlasBuilder/TextureAtlasD3D9.cpp" + "${BF2_ROOT}/RendDX9/TextureAtlas/TextureAtlasBuilder/TextureFormat.cpp" + ) + target_sources(bf2_renddx9_static PRIVATE ${BF2_TEXTURE_ATLAS_NATIVE_SOURCES}) + # The host manifests also list these paths; keep their builder image guard inactive. + set_source_files_properties(${BF2_TEXTURE_ATLAS_NATIVE_SOURCES} + PROPERTIES COMPILE_DEFINITIONS + "$<$,bf2_renddx9_static>:BF2_IMAGE_TEXTUREATLASBUILDER=1>") + # [CHOSEN, not recovered] One renderer-only prefix selects the subset without TU switches. + target_include_directories(bf2_renddx9_static BEFORE PRIVATE + "${BF2_ROOT}/Platform/Gfx/MacInclude" "${BF2_ROOT}/Platform/Gfx/Include") + target_sources(bf2_renddx9_static PRIVATE + "${BF2_ROOT}/Platform/Gfx/Metal/Frontiers.cpp" + "${BF2_ROOT}/Platform/Gfx/Metal/Effect.cpp" + "${BF2_ROOT}/Platform/Gfx/Metal/D3DXMath.cpp" + "${BF2_ROOT}/Platform/Gfx/Metal/D3DXGeometry.cpp" + "${BF2_ROOT}/Platform/Gfx/Metal/D3DXLine.cpp" + "${BF2_ROOT}/Platform/Gfx/Metal/D3DXPixels.cpp" + "${BF2_ROOT}/Platform/Gfx/Metal/D3DXImages.cpp" + "${BF2_ROOT}/Platform/Gfx/Metal/D3DXTextures.cpp" + "${BF2_ROOT}/Platform/Gfx/Metal/D3DXMesh.cpp" + "${BF2_ROOT}/Platform/Gfx/Metal/Device.cpp" + "${BF2_ROOT}/Platform/Gfx/Metal/FFVertex.cpp" + "${BF2_ROOT}/Platform/Gfx/Metal/MetalBridge.mm" + # zeux/meshoptimizer v1.3 (MIT, External/meshoptimizer/LICENSE.md): the stripifier behind + # the native D3DXConvertMeshSubsetToSingleStrip in D3DXMesh.cpp. + "${BF2_EXTERNAL_ROOT}/meshoptimizer/stripifier.cpp") + set_source_files_properties("${BF2_ROOT}/Platform/Gfx/Metal/MetalBridge.mm" + PROPERTIES COMPILE_OPTIONS "-fobjc-arc") + target_compile_options(bf2_renddx9_static PRIVATE + "$<$:-include${BF2_ROOT}/Platform/Gfx/MacSupport.h>") + target_compile_definitions(bf2_renddx9_static PRIVATE + initDll=bf2_renddx9_initDll deinitDll=bf2_renddx9_deinitDll) + + add_library(bf2_swiffplayer_static STATIC EXCLUDE_FROM_ALL ${BF2_SWIFFPLAYER_STATIC_SOURCES}) + bf2_configure_static_plugin(bf2_swiffplayer_static BF2_IMAGE_SWIFFPLAYER) + target_compile_definitions(bf2_swiffplayer_static PRIVATE + initDll=bf2_swiffplayer_initDll deinitDll=bf2_swiffplayer_deinitDll) + target_include_directories(bf2_swiffplayer_static PRIVATE + "${BF2_EXTERNAL_ROOT}" "${BF2_EXTERNAL_ROOT}/gameswf") + + # [CHOSEN, not recovered] Owner-approved Expat 1.95.0 substitute. The other + # xmltok .c files are included fragments, not separate translation units. + add_library(bf2_expat_static STATIC EXCLUDE_FROM_ALL + "${BF2_EXTERNAL_ROOT}/expat/xmlparse.c" + "${BF2_EXTERNAL_ROOT}/expat/xmltok.c" + "${BF2_EXTERNAL_ROOT}/expat/xmlrole.c") + bf2_configure_c_target(bf2_expat_static) + bf2_set_image(bf2_expat_static 0) + target_include_directories(bf2_expat_static PRIVATE "${BF2_EXTERNAL_ROOT}/expat") + set_property(TARGET bf2_expat_static PROPERTY FOLDER "BF2") + target_link_libraries(bf2_swiffplayer_static PUBLIC bf2_expat_static) + + add_library(bf2_vorbis_static STATIC EXCLUDE_FROM_ALL ${BF2_VORBIS_STATIC_SOURCES}) + bf2_configure_c_target(bf2_vorbis_static) + target_include_directories(bf2_vorbis_static PRIVATE + "${BF2_EXTERNAL_ROOT}/libogg-1.3.6/include" + "${BF2_EXTERNAL_ROOT}/libvorbis-1.3.7/include" + "${BF2_EXTERNAL_ROOT}/libvorbis-1.3.7/lib") + set_property(TARGET bf2_vorbis_static PROPERTY FOLDER "BF2") + + # [CHOSEN, not recovered] FFmpeg 7.1.1's Bink video/audio decoders, unmodified, over the + # OpenBF2 shim (Code/BF2/External/ffmpeg-bink/README.md; LGPL-2.1-or-later). This is the macOS + # build; Windows x64 compiles the same files in Code/Build/renddx9.cmd, Windows x86 keeps RAD's + # binkw32.dll. Built optimized in every configuration, as FFmpeg is. + set(BF2_FFMPEG_BINK_DIR "${BF2_EXTERNAL_ROOT}/ffmpeg-bink") + add_library(bf2_ffmpeg_bink STATIC EXCLUDE_FROM_ALL + "${BF2_FFMPEG_BINK_DIR}/libavcodec/bink.c" + "${BF2_FFMPEG_BINK_DIR}/libavcodec/binkdsp.c" + "${BF2_FFMPEG_BINK_DIR}/libavcodec/binkaudio.c" + "${BF2_FFMPEG_BINK_DIR}/libavcodec/wma_freqs.c" + "${BF2_FFMPEG_BINK_DIR}/shim/ffbink_shim.c") + target_include_directories(bf2_ffmpeg_bink PRIVATE "${BF2_FFMPEG_BINK_DIR}/shim") + set_target_properties(bf2_ffmpeg_bink PROPERTIES C_STANDARD 11 C_STANDARD_REQUIRED ON + C_EXTENSIONS ON) + target_compile_options(bf2_ffmpeg_bink PRIVATE -O2 -fno-strict-aliasing -fno-math-errno + -Wno-pointer-sign) + set_property(TARGET bf2_ffmpeg_bink PROPERTY FOLDER "BF2") + # [CHOSEN, not recovered] CPU check of the Bink port against reference frames/samples that + # the local ffmpeg CLI produces from the read-only game content (Code/BF2/External/ffmpeg-bink/README.md). + add_executable(bf2_bink_decode_test EXCLUDE_FROM_ALL + "${CMAKE_CURRENT_SOURCE_DIR}/Code/Tests/macos_bink_decode.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Code/RendDX9Abi/BinkFFmpeg.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Code/RendDX9Abi/BinkAudioCoreAudio.cpp") + target_compile_features(bf2_bink_decode_test PRIVATE cxx_std_17) + target_link_libraries(bf2_bink_decode_test PRIVATE bf2_ffmpeg_bink "-framework AudioToolbox") + # [TEMP] [CHOSEN, not recovered] The black-box Bink harness, port side: the same source the + # retail build runs against binkw32.dll (Code/Tests/movies, Code/BF2/External/ffmpeg-bink/README.md). + add_executable(bf2_bink_harness EXCLUDE_FROM_ALL + "${CMAKE_CURRENT_SOURCE_DIR}/Code/Tests/movies/bink_harness.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Code/RendDX9Abi/BinkFFmpeg.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Code/RendDX9Abi/BinkAudioCoreAudio.cpp") + target_compile_features(bf2_bink_harness PRIVATE cxx_std_17) + target_link_libraries(bf2_bink_harness PRIVATE bf2_ffmpeg_bink "-framework AudioToolbox") + + add_library(bf2_bf2audio_static STATIC EXCLUDE_FROM_ALL ${BF2_BF2AUDIO_STATIC_SOURCES}) + bf2_configure_static_plugin(bf2_bf2audio_static "BF2_IMAGE_BF2AUDIO") + target_include_directories(bf2_bf2audio_static PRIVATE + "${BF2_EXTERNAL_ROOT}/libogg-1.3.6/include" + "${BF2_EXTERNAL_ROOT}/libvorbis-1.3.7/include") + + # The client-image half of the macOS voice server, statically linked as the Linux server does. + add_library(bf2_voipserver_client_objects OBJECT EXCLUDE_FROM_ALL ${bf2_voipserver_only_sources}) + bf2_configure_cpp_target(bf2_voipserver_client_objects) + bf2_set_image(bf2_voipserver_client_objects 0) + bf2_set_platform_compat(bf2_voipserver_client_objects) + target_compile_definitions(bf2_voipserver_client_objects PRIVATE BF2_PLATFORM_POSIX _MACOSX) + set_property(TARGET bf2_voipserver_client_objects PROPERTY FOLDER "BF2") + + add_executable(bf2_client EXCLUDE_FROM_ALL + "${CMAKE_CURRENT_SOURCE_DIR}/Code/StaticPlugins/StaticPlugins.cpp" + $ + $ + $ + $ + $ + $ + $ + $ + $ + ) + bf2_configure_static_plugin(bf2_client "") + # bin_macos already holds the server `bf2`; APFS is case-insensitive, so the client cannot be + # `BF2` beside it. It shares the directory, and the @loader_path rpath, with libdice_py.dylib. + set_target_properties(bf2_client PROPERTIES + LINKER_LANGUAGE CXX + OUTPUT_NAME bf2_client + RUNTIME_OUTPUT_DIRECTORY "${BF2_DEDICATED_OUTPUT_DIR}" + BUILD_RPATH "@loader_path" + INSTALL_RPATH "@loader_path" + BUILD_WITH_INSTALL_RPATH TRUE + ) + if(TARGET dice_py) + target_link_libraries(bf2_client PRIVATE dice_py) + endif() + # [CHOSEN, not recovered] The renderer uses the G2 subset and G3 Metal device; + # unimplemented operations stop. OFF keeps the + # renderer-free client: StaticPlugins.cpp has no RendDX9 entry and BF2Render::init takes + # its shipped failure return. ON links the image for coordinator device-creation checks. + option(BF2_MACOS_LINK_RENDDX9 "Link the RendDX9 static library into the macOS client" OFF) + if(BF2_MACOS_LINK_RENDDX9) + bf2_prelink_static_plugin(bf2_client bf2_renddx9_static "${BF2_STATIC_PLUGIN_PRIVATE_SYMBOLS}") + target_compile_definitions(bf2_client PRIVATE BF2_STATIC_RENDDX9=1) + # [CHOSEN, not recovered] The renderer's Bink port (BinkFFmpeg.cpp) and its audio output. + target_link_libraries(bf2_client PRIVATE bf2_ffmpeg_bink "-framework AudioToolbox") + # [CHOSEN, not recovered] The G4 effect facade (Metal/Effect.cpp) runs the s2 CPU runtime. + target_link_libraries(bf2_client PRIVATE bf2_fx_runtime) + # [CHOSEN, not recovered] System JPEG decoding in the prelinked renderer image. + target_link_libraries(bf2_client PRIVATE "-framework ImageIO" "-framework CoreGraphics") + endif() + target_compile_definitions(bf2_client PRIVATE BF2_STATIC_SWIFFPLAYER=1 BF2_STATIC_BF2AUDIO=1) + bf2_prelink_static_plugin(bf2_client bf2_swiffplayer_static "${BF2_STATIC_PLUGIN_PRIVATE_SYMBOLS}") + bf2_prelink_static_plugin(bf2_client bf2_bf2audio_static + "${CMAKE_CURRENT_SOURCE_DIR}/Code/StaticPlugins/bf2audio-private-symbols.txt") + target_link_libraries(bf2_client PRIVATE + bf2_vorbis_static bf2_expat_static bf2_plugin_kit_static + Threads::Threads ${CMAKE_DL_LIBS} ${CURSES_LIBRARIES}) + target_link_options(bf2_client PRIVATE + "-Wl,-map,${BF2_DEDICATED_OUTPUT_DIR}/bf2_client.map") + + # [CHOSEN, not recovered] The Cocoa host and the GCController poller (package S2.4, + # docs/macos-s2-4.md): ARC Objective-C++ with the plain-C++ headers the engine includes. + set(BF2_MACOS_HOST_OBJCXX_SOURCES + "${BF2_ROOT}/Platform/macOS/CocoaHost.mm" + "${BF2_ROOT}/Platform/macOS/MacGamepad.mm" + "${BF2_ROOT}/Platform/macOS/MacRawMouse.mm" + "${BF2_ROOT}/Platform/macOS/MacInputScript.mm") # [TEMP] BF2_INPUT_SCRIPT + target_sources(bf2_client PRIVATE ${BF2_MACOS_HOST_OBJCXX_SOURCES}) + set_source_files_properties(${BF2_MACOS_HOST_OBJCXX_SOURCES} + PROPERTIES COMPILE_OPTIONS "-fobjc-arc") + target_link_libraries(bf2_client PRIVATE + "-framework AppKit" "-framework QuartzCore" "-framework Metal" + "-framework GameController" "-framework Carbon" "-framework IOKit") + # [CHOSEN, not recovered] BF2Audio's POSIX arm (Sound/SoundEngine/Win32System.cpp) queries the + # default output device through CoreAudio; OpenAL.framework itself is loaded at run time with + # dlopen, as the Win32 image loads OpenAL32.dll. MacSystem.cpp's alert uses CoreFoundation. + target_link_libraries(bf2_client PRIVATE "-framework CoreAudio" "-framework CoreFoundation") + # The SDK's CoreAudio voice layer (gvOSXAudio.c) converts sample rates with AudioConverter. + target_link_libraries(bf2_client PRIVATE "-framework AudioToolbox") + + # [CHOSEN, not recovered] Keep all static-image views in native ABI agreement. + # This also runs for renderer-OFF builds. The script caches successful probes + # against real target flags and transitive headers; a warm gate takes seconds. + find_package(Python3 COMPONENTS Interpreter REQUIRED) + set(CMAKE_EXPORT_COMPILE_COMMANDS ON) + add_executable(bf2_native_vtable_check EXCLUDE_FROM_ALL + "${CMAKE_CURRENT_SOURCE_DIR}/Code/Tests/macos_vtable_audit.cpp") + bf2_configure_cpp_target(bf2_native_vtable_check) + bf2_set_image(bf2_native_vtable_check 0) + target_compile_definitions(bf2_native_vtable_check PRIVATE BF2_STATIC_PLUGINS=1) + # [CHOSEN, not recovered] Pin captured BFMeme dispatch to native member encodings. + add_executable(bf2_meme_dispatch_check EXCLUDE_FROM_ALL + "${CMAKE_CURRENT_SOURCE_DIR}/Code/Tests/macos_meme_dispatch.cpp") + bf2_configure_cpp_target(bf2_meme_dispatch_check) + bf2_set_image(bf2_meme_dispatch_check 0) + # A cross build (an arm64-only tree on an Intel Mac) cannot execute the native checks: + # the static audit still gates the build with the target's own flags, and the linked + # checks ship in the M2 bundle (docs/macos-c-arm64-client.md). + set(BF2_VTABLE_CHECK_RUNNABLE ON) + if(CMAKE_OSX_ARCHITECTURES AND NOT CMAKE_HOST_SYSTEM_PROCESSOR IN_LIST CMAKE_OSX_ARCHITECTURES) + set(BF2_VTABLE_CHECK_RUNNABLE OFF) + endif() + if(BF2_VTABLE_CHECK_RUNNABLE) + set(BF2_VTABLE_CHECK_COMMAND COMMAND "$" + COMMAND "$") + else() + set(BF2_VTABLE_CHECK_COMMAND COMMAND "${CMAKE_COMMAND}" -E echo + "bf2_native_vtable_check and bf2_meme_dispatch_check are built for ${CMAKE_OSX_ARCHITECTURES} and run in the M2 bundle") + endif() + add_custom_target(bf2_vtable_audit ALL + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tools/macos/vtable_audit.py" + --build-dir "${CMAKE_BINARY_DIR}" + # AI behaviour system (S0): native vtable order against libaidll.so's + # (tools/macos/ai_behaviour_vtables.json); clang computes the slots, cached. + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tools/macos/ai_behaviour_vtables.py" + --build-dir "${CMAKE_BINARY_DIR}" + ${BF2_VTABLE_CHECK_COMMAND} + DEPENDS bf2_native_vtable_check bf2_meme_dispatch_check + COMMENT "Auditing native static-plugin vtables" + VERBATIM) + add_dependencies(bf2_client bf2_vtable_audit) + # [CHOSEN, not recovered] A game hosted from the client menu (the welcome page's instant + # battle, CREATE LOCAL) runs the server inside bf2_client, and BF2Engine names its AI image + # "aidll.dll" (BF2.exe 0x409CBD) - retail ships AIDLL.dll beside BF2.exe. The POSIX loader maps + # that to libaidll.dylib, found through the client's @loader_path rpath in bin_macos, where + # bf2_aidll is written. Without it AIConnection::init aborts (the shipped load-failure defect). + if(TARGET bf2_aidll) + add_dependencies(bf2_client bf2_aidll) + endif() + add_dependencies(bf2 bf2_vtable_audit) + add_dependencies(bf2_renddx9_static bf2_vtable_audit) + add_dependencies(bf2_swiffplayer_static bf2_vtable_audit) + add_dependencies(bf2_bf2audio_static bf2_vtable_audit) endif() # ================================================================================================= @@ -1750,8 +2282,464 @@ set_property(TARGET bf2_syntaxcheck PROPERTY FOLDER "Diagnostics") endif() include(CTest) + +# [TEMP] Issue #33: content-free policy checks, with no renderer or gameplay claim. +add_executable(bf2_hud_widescreen_check EXCLUDE_FROM_ALL + Code/Tests/hud_widescreen_policy.cpp + "${BF2_ROOT}/Menu/HudWidescreen.cpp") +bf2_configure_cpp_target(bf2_hud_widescreen_check) +bf2_set_platform_compat(bf2_hud_widescreen_check) +bf2_set_image(bf2_hud_widescreen_check 0) +if(BUILD_TESTING) + add_test(NAME bf2_hud_widescreen_check COMMAND bf2_hud_widescreen_check) +endif() + +if(BF2_BUILD_MACOS AND TARGET bf2_swiffplayer_static) + # [TEMP] [CHOSEN, not recovered] Content-free offline popup VM regression. + add_executable(bf2_swiff_offline_connect_popup_check EXCLUDE_FROM_ALL + Code/Tests/swiff_offline_connect_popup.cpp + Code/Tests/gameswf_xml/cocoa_host_unavailable.cpp) + bf2_configure_static_plugin(bf2_swiff_offline_connect_popup_check BF2_IMAGE_SWIFFPLAYER) + target_include_directories(bf2_swiff_offline_connect_popup_check PRIVATE + "${BF2_EXTERNAL_ROOT}" "${BF2_EXTERNAL_ROOT}/gameswf") + target_link_libraries(bf2_swiff_offline_connect_popup_check PRIVATE + bf2_swiffplayer_static bf2_plugin_kit_static) + + # [TEMP] [CHOSEN, not recovered] The __proto__ probe SWFs (tools/swf/proto_probe.py) in the + # native gameswf must show retail 1.50's squares (docs/tracks/game/swf-proto-retail-probe.md). + add_executable(bf2_swf_proto_probe_check EXCLUDE_FROM_ALL + Code/Tests/swf_proto_probe_runtime.cpp + Code/Tests/gameswf_xml/cocoa_host_unavailable.cpp) + bf2_configure_static_plugin(bf2_swf_proto_probe_check BF2_IMAGE_SWIFFPLAYER) + target_include_directories(bf2_swf_proto_probe_check PRIVATE + "${BF2_EXTERNAL_ROOT}" "${BF2_EXTERNAL_ROOT}/gameswf") + target_link_libraries(bf2_swf_proto_probe_check PRIVATE bf2_swiffplayer_static bf2_plugin_kit_static) + if(BUILD_TESTING) + find_package(Python3 COMPONENTS Interpreter QUIET) + if(Python3_Interpreter_FOUND) + add_test(NAME bf2_swf_proto_probe_generate + COMMAND "${Python3_EXECUTABLE}" -I "${CMAKE_CURRENT_SOURCE_DIR}/tools/swf/proto_probe.py" + swf --out "${CMAKE_CURRENT_BINARY_DIR}/swf-proto-probe") + add_test(NAME bf2_swf_proto_probe_check + COMMAND bf2_swf_proto_probe_check "${CMAKE_CURRENT_BINARY_DIR}/swf-proto-probe") + set_tests_properties(bf2_swf_proto_probe_check PROPERTIES DEPENDS bf2_swf_proto_probe_generate) + endif() + endif() + + # [TEMP] [CHOSEN, not recovered] Production gameswf XML/string/file fixture. + add_executable(bf2_gameswf_xml_check EXCLUDE_FROM_ALL + Code/Tests/gameswf_xml/xml_check.cpp + Code/Tests/gameswf_xml/cocoa_host_unavailable.cpp) + bf2_configure_static_plugin(bf2_gameswf_xml_check BF2_IMAGE_SWIFFPLAYER) + target_include_directories(bf2_gameswf_xml_check PRIVATE "${BF2_EXTERNAL_ROOT}") + target_link_libraries(bf2_gameswf_xml_check PRIVATE bf2_swiffplayer_static bf2_plugin_kit_static) + if(BUILD_TESTING) + add_test(NAME bf2_gameswf_xml_check COMMAND bf2_gameswf_xml_check + "${CMAKE_CURRENT_BINARY_DIR}/gameswf-xml-fixture.xml") + endif() +endif() + +# [TEMP] Behaviour fixture for the recovered slider bodies (Code/Tests/slider_node_behaviour.cpp, game +# frontier closure; Code/Tests/slider_node_behaviour.cmd is its Windows twin). The BFMeme families it +# never calls stay unresolved, as /FORCE:UNRESOLVED leaves them in the Windows fixtures. +if(APPLE) + add_executable(bf2_slider_node_check EXCLUDE_FROM_ALL + Code/Tests/slider_node_behaviour.cpp + "${BF2_ROOT}/External/BFMeme/SliderNode.cpp" + "${BF2_ROOT}/Menu/BfFixedSliderNode.cpp" + "${BF2_ROOT}/External/BFMeme/Node.cpp" + "${BF2_ROOT}/External/BFMeme/NodeState.cpp" + "${BF2_ROOT}/External/BFMeme/Object.cpp" + "${BF2_ROOT}/External/BFMeme/TypeDescriptor.cpp" + "${BF2_ROOT}/External/BFMeme/System.cpp" + "${BF2_ROOT}/External/BFMeme/Data.cpp" + "${BF2_ROOT}/External/BFMeme/NamedObjectRegistry.cpp" + "${BF2_ROOT}/External/BFMeme/Stream.cpp") + bf2_configure_cpp_target(bf2_slider_node_check) + bf2_set_platform_compat(bf2_slider_node_check) + bf2_set_image(bf2_slider_node_check 0) + target_link_options(bf2_slider_node_check PRIVATE "-Wl,-undefined,dynamic_lookup") + if(BUILD_TESTING) + add_test(NAME bf2_slider_node_check COMMAND bf2_slider_node_check) + endif() +endif() + +# [TEMP] [CHOSEN, not recovered] Receive-size limit of DataBlockManager (Code/Tests/datablock_cap_runtime.cpp): +# the actual DataBlockManager/DataBlockEvent/BitStream with a recording GameEventManager. +if(APPLE) + add_executable(bf2_datablock_cap_check EXCLUDE_FROM_ALL + Code/Tests/datablock_cap_runtime.cpp + "${BF2_ROOT}/Game/Common/DataBlockManager.cpp" + "${BF2_ROOT}/Game/GameEvents/DataBlockEvent.cpp" + "${BF2_ROOT}/Game/Common/GameEvent.cpp" + "${BF2_ROOT}/Core/EventManager.cpp" + "${BF2_ROOT}/IO/BitStream.cpp") + bf2_configure_cpp_target(bf2_datablock_cap_check) + bf2_set_platform_compat(bf2_datablock_cap_check) + bf2_set_image(bf2_datablock_cap_check 0) + if(BUILD_TESTING) + add_test(NAME bf2_datablock_cap_check COMMAND bf2_datablock_cap_check) + endif() +endif() + +# [TEMP] Cumulative fixture for game frontier-closure sites no normal session reaches +# (Code/Tests/game_frontier_check.cpp; docs/tracks/game/frontier-closure.md). Built on request; the +# families it never calls stay unresolved, as /FORCE:UNRESOLVED leaves them in the Windows fixtures. +if(APPLE) + add_executable(bf2_game_frontier_check EXCLUDE_FROM_ALL + Code/Tests/game_frontier_check.cpp + Code/Tests/game_frontier_x87_narrow.cpp + "${BF2_ROOT}/Game/LocalProfileManager.cpp" + "${BF2_ROOT}/Game/LocalProfileManagerDiscovery.cpp" + "${BF2_ROOT}/Game/LocalProfileManagerFields.cpp" + "${BF2_ROOT}/Game/LocalProfileManagerInit.cpp" + "${BF2_ROOT}/Game/LocalProfileManagerOperations.cpp" + "${BF2_ROOT}/Game/LocalProfileManagerSelection.cpp" + "${BF2_ROOT}/Game/LocalProfileManagerSuffix.cpp" + "${BF2_ROOT}/Physics/MaterialManager.cpp" + "${BF2_ROOT}/External/BFMeme/Node.cpp" + "${BF2_ROOT}/External/BFMeme/NodeState.cpp" + "${BF2_ROOT}/External/BFMeme/Object.cpp" + "${BF2_ROOT}/External/BFMeme/TypeDescriptor.cpp" + "${BF2_ROOT}/External/BFMeme/System.cpp" + "${BF2_ROOT}/External/BFMeme/NamedObjectRegistry.cpp" + "${BF2_ROOT}/External/BFMeme/Data.cpp" + "${BF2_ROOT}/Menu/BfEditNode.cpp" + "${BF2_ROOT}/Menu/Bf2EditNode.cpp" + "${BF2_ROOT}/Menu/BfNewListBoxNode.cpp" + "${BF2_ROOT}/Menu/BfListBoxData.cpp" + "${BF2_ROOT}/External/BFMeme/Action.cpp" + "${BF2_ROOT}/External/BFMeme/Tree.cpp" + "${BF2_ROOT}/External/BFMeme/Stream.cpp" + "${BF2_ROOT}/Menu/ProfileConsoleBindings.cpp" + "${BF2_ROOT}/Core/ConsoleObjectBase.cpp" + "${BF2_ROOT}/Game/DistributedLightRenderer/DistributedLightRenderer.cpp" + "${BF2_ROOT}/Game/Common/GameEvent.cpp" + "${BF2_ROOT}/Core/StringUtil.cpp" + "${BF2_ROOT}/AI/AIInterface/BFKnowledge/BFGame.cpp") + bf2_configure_cpp_target(bf2_game_frontier_check) + bf2_set_platform_compat(bf2_game_frontier_check) + bf2_set_image(bf2_game_frontier_check 0) + set_source_files_properties(Code/Tests/game_frontier_x87_narrow.cpp PROPERTIES + COMPILE_OPTIONS "-Wno-builtin-macro-redefined;-U__LDBL_MANT_DIG__;-D__LDBL_MANT_DIG__=53") + target_link_options(bf2_game_frontier_check PRIVATE "-Wl,-undefined,dynamic_lookup") + if(BUILD_TESTING) + add_test(NAME bf2_game_frontier_check COMMAND bf2_game_frontier_check) + endif() +endif() + +# [CHOSEN, not recovered] The frontier trap's default (Code/Tests/frontier_default_check.cpp): the kit's +# Frontier.cpp built as a dev image (default abort) and as a release image +# (BF2_FRONTIER_DEFAULT_CONTINUE=1, default continue); explicit env values win in both. +if(APPLE) + foreach(bf2_frontier_mode IN ITEMS abort continue) + set(bf2_frontier_target bf2_frontier_default_${bf2_frontier_mode}_check) + add_executable(${bf2_frontier_target} EXCLUDE_FROM_ALL + "${CMAKE_CURRENT_SOURCE_DIR}/Code/Tests/frontier_default_check.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Code/RendDX9Abi/Frontier.cpp") + if(bf2_frontier_mode STREQUAL "continue") + target_compile_definitions(${bf2_frontier_target} PRIVATE + BF2_FRONTIER_DEFAULT_CONTINUE=1 BF2_FRONTIER_CHECK_EXPECT_CONTINUE=1) + else() + target_compile_definitions(${bf2_frontier_target} PRIVATE BF2_FRONTIER_CHECK_EXPECT_CONTINUE=0) + endif() + if(BUILD_TESTING) + add_test(NAME ${bf2_frontier_target} COMMAND ${bf2_frontier_target}) + endif() + endforeach() +endif() + +# [TEMP] The voice client (Code/Tests/voip_client_runtime.cpp): VoipClient over loopback UDP and +# BF2VoipClient on fake game objects, with the synthetic capture device (no microphone, no permission +# prompt). The mixer (Code/Tests/voip_mixer_runtime.cpp) runs on its scripted WINMM table. +if(APPLE) + add_executable(bf2_voip_client_check EXCLUDE_FROM_ALL + Code/Tests/voip_client_runtime.cpp + "${BF2_ROOT}/Game/VoipClient/VoipClient.cpp" + "${BF2_ROOT}/Game/VoipClient/BF2VoipClient.cpp" + "${BF2_ROOT}/Game/VoipClient/VoipMixer.cpp" + "${BF2_ROOT}/Game/VoipClient/VoipFakeDevice.cpp" + $ + $) + bf2_configure_cpp_target(bf2_voip_client_check) + bf2_set_platform_compat(bf2_voip_client_check) + bf2_set_image(bf2_voip_client_check 0) + target_compile_definitions(bf2_voip_client_check PRIVATE BF2_PLATFORM_POSIX _MACOSX + BF2_VOIPMIXER_NO_PLATFORM_BACKEND=1) + target_link_options(bf2_voip_client_check PRIVATE "-Wl,-undefined,dynamic_lookup") + target_link_libraries(bf2_voip_client_check PRIVATE "-framework CoreAudio" "-framework AudioToolbox" + "-framework CoreFoundation" Threads::Threads) + if(BUILD_TESTING) + add_test(NAME bf2_voip_client_check COMMAND bf2_voip_client_check) + endif() + + # The retail x86 layout asserts of the voice client, compiled for the MSVC x86 ABI from the Mac + # (clang's i686-pc-windows-msvc target, stub STL headers); the real check is the Windows x86 build. + if(BUILD_TESTING AND CMAKE_CXX_COMPILER_ID MATCHES "Clang") + add_test(NAME bf2_voip_msvc_x86_layout + COMMAND "${CMAKE_CXX_COMPILER}" -target i686-pc-windows-msvc -fsyntax-only -std=c++14 -Wno-invalid-offsetof -Wno-unused-command-line-argument + -nostdinc -nostdinc++ -I "${CMAKE_CURRENT_SOURCE_DIR}/Code/Tests/msvc_x86_layout/include" + -D_M_IX86=600 "${CMAKE_CURRENT_SOURCE_DIR}/Code/Tests/msvc_x86_layout/msvc_x86_layout.cpp") + endif() + + add_executable(bf2_voip_mixer_check EXCLUDE_FROM_ALL + Code/Tests/voip_mixer_runtime.cpp + "${BF2_ROOT}/Game/VoipClient/VoipMixer.cpp") + bf2_configure_cpp_target(bf2_voip_mixer_check) + bf2_set_platform_compat(bf2_voip_mixer_check) + bf2_set_image(bf2_voip_mixer_check 0) + target_compile_definitions(bf2_voip_mixer_check PRIVATE BF2_VOIPMIXER_NO_PLATFORM_BACKEND=1) + if(BUILD_TESTING) + add_test(NAME bf2_voip_mixer_check COMMAND bf2_voip_mixer_check) + endif() +endif() + +# [TEMP] The PunkBuster glue objects at the 32-bit x86 ABI (Code/Tests/msvc_x86_layout/punkbuster_x86_layout.cpp). +if(BUILD_TESTING AND CMAKE_CXX_COMPILER_ID MATCHES "Clang") + foreach(pb_abi IN ITEMS msvc elf) + if(pb_abi STREQUAL "msvc") + set(pb_triple i686-pc-windows-msvc) + set(pb_define -D_M_IX86=600) + else() + set(pb_triple i386-pc-linux-gnu) + set(pb_define -D__i386__=1) + endif() + add_test(NAME bf2_punkbuster_${pb_abi}_x86_layout + COMMAND "${CMAKE_CXX_COMPILER}" -target ${pb_triple} -fsyntax-only -std=c++14 -Wno-invalid-offsetof -Wno-unused-command-line-argument -Wno-macro-redefined + -nostdinc -nostdinc++ -I "${CMAKE_CURRENT_SOURCE_DIR}/Code/Tests/msvc_x86_layout/include" + ${pb_define} "${CMAKE_CURRENT_SOURCE_DIR}/Code/Tests/msvc_x86_layout/punkbuster_x86_layout.cpp") + endforeach() +endif() + +# [TEMP] PunkBuster client glue and command hook (Code/Tests/punkbuster_client_runtime.cpp) against a +# fake pbcl.dll through the glue's library seam, fake PB_* functions and a fake server trap. Built on +# request; files only under a fresh temporary directory. +if(APPLE) + add_executable(bf2_punkbuster_client_check EXCLUDE_FROM_ALL + Code/Tests/punkbuster_client_runtime.cpp + "${BF2_ROOT}/Game/PunkBuster/PbClient.cpp" + "${BF2_ROOT}/Game/PunkBuster/PbCommandHook.cpp") + bf2_configure_cpp_target(bf2_punkbuster_client_check) + bf2_set_platform_compat(bf2_punkbuster_client_check) + bf2_set_image(bf2_punkbuster_client_check 0) + if(BUILD_TESTING) + add_test(NAME bf2_punkbuster_client_check COMMAND bf2_punkbuster_client_check) + endif() +endif() + +# [TEMP] The BF2-side PunkBuster functions (Code/Tests/punkbuster_game_runtime.cpp) against fake games, +# console, players, glue entry points and helpers, in the client and the dedicated image. Built on request. +if(APPLE) + add_executable(bf2_punkbuster_game_check EXCLUDE_FROM_ALL + Code/Tests/punkbuster_game_runtime.cpp + "${BF2_ROOT}/Game/PunkBuster/PbGame.cpp" + "${BF2_ROOT}/Game/Objects/IPlayer.cpp") + bf2_configure_cpp_target(bf2_punkbuster_game_check) + bf2_set_platform_compat(bf2_punkbuster_game_check) + bf2_set_image(bf2_punkbuster_game_check 0) + target_include_directories(bf2_punkbuster_game_check PRIVATE ${BF2_PYTHON_INCLUDE_DIRS}) + if(BUILD_TESTING) + add_test(NAME bf2_punkbuster_game_check COMMAND bf2_punkbuster_game_check) + endif() + add_executable(bf2_punkbuster_game_dedicated_check EXCLUDE_FROM_ALL + Code/Tests/punkbuster_game_runtime.cpp + "${BF2_ROOT}/Game/PunkBuster/PbGame.cpp" + "${BF2_ROOT}/Game/Objects/IPlayer.cpp") + bf2_configure_cpp_target(bf2_punkbuster_game_dedicated_check) + bf2_set_platform_compat(bf2_punkbuster_game_dedicated_check) + bf2_set_image(bf2_punkbuster_game_dedicated_check 1) + target_include_directories(bf2_punkbuster_game_dedicated_check PRIVATE ${BF2_PYTHON_INCLUDE_DIRS}) + if(BUILD_TESTING) + add_test(NAME bf2_punkbuster_game_dedicated_check COMMAND bf2_punkbuster_game_dedicated_check) + endif() +endif() + +# [TEMP] The PunkBuster server glue (Code/Tests/punkbuster_server_runtime.cpp) against a fake pbsv, +# fake PB_* functions and a scratch pb folder, in both images (the capture buffer's home differs). +# Built on request. +if(APPLE OR UNIX) + foreach(pbsv_image IN ITEMS dedicated client) + if(pbsv_image STREQUAL "dedicated") + set(pbsv_target bf2_punkbuster_server_check) + set(pbsv_define 1) + else() + set(pbsv_target bf2_punkbuster_server_client_check) + set(pbsv_define 0) + endif() + add_executable(${pbsv_target} EXCLUDE_FROM_ALL + Code/Tests/punkbuster_server_runtime.cpp + "${BF2_ROOT}/Game/PunkBuster/PbServer.cpp") + bf2_configure_cpp_target(${pbsv_target}) + bf2_set_platform_compat(${pbsv_target}) + bf2_set_image(${pbsv_target} ${pbsv_define}) + if(BUILD_TESTING) + add_test(NAME ${pbsv_target} COMMAND ${pbsv_target}) + endif() + endforeach() +endif() + +# [TEMP] Camera::handleUpdate and its shake/recoil helpers (Code/Tests/camera_shake_runtime.cpp): the real +# Camera.cpp against generated fakes; every other engine symbol it references becomes an aborting stub +# generated from the objects by tools/macos/link_stubs.py. Built on request. +if(APPLE) + find_package(Python3 COMPONENTS Interpreter REQUIRED) + add_library(bf2_camera_shake_objects OBJECT EXCLUDE_FROM_ALL + Code/Tests/camera_shake_runtime.cpp + "${BF2_ROOT}/Game/Objects/Base/Camera.cpp" + "${BF2_ROOT}/Game/Objects/IPlayer.cpp" + "${BF2_ROOT}/Scene/Object/ObjectPredicator.cpp") + bf2_configure_cpp_target(bf2_camera_shake_objects) + bf2_set_platform_compat(bf2_camera_shake_objects) + bf2_set_image(bf2_camera_shake_objects 0) + target_include_directories(bf2_camera_shake_objects PRIVATE ${BF2_PYTHON_INCLUDE_DIRS}) + set(bf2_camera_shake_stubs "${CMAKE_CURRENT_BINARY_DIR}/camera_shake_link_stubs.cpp") + add_custom_command(OUTPUT "${bf2_camera_shake_stubs}" + COMMAND "${Python3_EXECUTABLE}" -I "${CMAKE_CURRENT_SOURCE_DIR}/tools/macos/link_stubs.py" + "${bf2_camera_shake_stubs}" $ + DEPENDS bf2_camera_shake_objects $ + "${CMAKE_CURRENT_SOURCE_DIR}/tools/macos/link_stubs.py" + COMMAND_EXPAND_LISTS + COMMENT "Generating the camera shake check's link stubs") + add_executable(bf2_camera_shake_check EXCLUDE_FROM_ALL + $ "${bf2_camera_shake_stubs}") + bf2_configure_cpp_target(bf2_camera_shake_check) + bf2_set_platform_compat(bf2_camera_shake_check) + bf2_set_image(bf2_camera_shake_check 0) + if(BUILD_TESTING) + add_test(NAME bf2_camera_shake_check COMMAND bf2_camera_shake_check) + endif() +endif() + +# [TEMP] The Soldier's control-box profile switch (Code/Tests/soldier_haptic_profile_runtime.cpp, +# ledger N2 17a) against a generated fake HapticSettings and fake player-control templates. Built on request. +if(APPLE OR UNIX) + add_executable(bf2_soldier_haptic_profile_check EXCLUDE_FROM_ALL + Code/Tests/soldier_haptic_profile_runtime.cpp + "${BF2_ROOT}/Game/Objects/Game/SoldierHapticProfile.cpp" + "${BF2_ROOT}/Math/Vec3.cpp") + bf2_configure_cpp_target(bf2_soldier_haptic_profile_check) + bf2_set_platform_compat(bf2_soldier_haptic_profile_check) + bf2_set_image(bf2_soldier_haptic_profile_check 0) + if(BUILD_TESTING) + add_test(NAME bf2_soldier_haptic_profile_check COMMAND bf2_soldier_haptic_profile_check) + endif() +endif() + +# [TEMP] dice::hfe::Mutex recursion and exclusion (Code/Tests/mutex_runtime.cpp). Built on request. +if(APPLE OR UNIX) + add_executable(bf2_mutex_check EXCLUDE_FROM_ALL + Code/Tests/mutex_runtime.cpp + "${BF2_ROOT}/Core/Mutex.cpp") + bf2_configure_cpp_target(bf2_mutex_check) + bf2_set_platform_compat(bf2_mutex_check) + find_package(Threads REQUIRED) + target_link_libraries(bf2_mutex_check PRIVATE Threads::Threads) + if(BUILD_TESTING) + add_test(NAME bf2_mutex_check COMMAND bf2_mutex_check) + endif() +endif() + +# [TEMP] CBF2VoipServer::Shutdown under one dice::hfe::Mutex (Code/Tests/voip_server_shutdown_runtime.cpp): +# the relock through ReleaseAllInstances must not hang. Built on request; UDP port 55197 only. +if(APPLE) + add_executable(bf2_voip_server_shutdown_check EXCLUDE_FROM_ALL + Code/Tests/voip_server_shutdown_runtime.cpp + "${BF2_ROOT}/IO/Network/SocketManager.cpp" + "${BF2_ROOT}/IO/Network/NetworkLayer/Socket/UDPSocket.cpp" + "${BF2_ROOT}/VoipServer/VoipServer.cpp" + "${BF2_ROOT}/VoipServer/VoipServerInstance.cpp" + "${BF2_ROOT}/VoipServer/VoipDebug.cpp" + "${BF2_ROOT}/VoipServer/VoipRouter.cpp" + "${BF2_ROOT}/VoipServer/VoipClients.cpp" + "${BF2_ROOT}/VoipServer/VoipOutgoingChannels.cpp" + "${BF2_ROOT}/Core/Mutex.cpp" + "${BF2_ROOT}/Core/Timer.cpp" + "${BF2_ROOT}/Core/SystemInfo.cpp" + "${BF2_ROOT}/Core/StringUtil.cpp") + bf2_configure_cpp_target(bf2_voip_server_shutdown_check) + bf2_set_platform_compat(bf2_voip_server_shutdown_check) + bf2_set_image(bf2_voip_server_shutdown_check 1) + target_compile_definitions(bf2_voip_server_shutdown_check PRIVATE BF2_PLATFORM_POSIX _MACOSX) + # The challenge hash's MD5 (GameSpy md5c.c) is C; it builds without the C++ compatibility header. + add_library(bf2_voip_server_shutdown_md5 OBJECT EXCLUDE_FROM_ALL "${BF2_ROOT}/External/GameSpy/md5c.c") + target_sources(bf2_voip_server_shutdown_check PRIVATE $) + if(BUILD_TESTING) + add_test(NAME bf2_voip_server_shutdown_check COMMAND bf2_voip_server_shutdown_check) + endif() +endif() + +# [TEMP] Voice-server debug logs (Code/Tests/voip_debug_runtime.cpp, Windows twin +# voip_debug_runtime.cmd): HandlePacketDebugRoutingData, the routing dump and the voice trace, read +# back from the files they write. Built on request; the dedicated image (DEDICATED=1) as in the twin. +if(APPLE) + add_executable(bf2_voip_debug_check EXCLUDE_FROM_ALL + Code/Tests/voip_debug_runtime.cpp + "${BF2_ROOT}/VoipServer/VoipServerInstance.cpp" + "${BF2_ROOT}/VoipServer/VoipDebug.cpp" + "${BF2_ROOT}/VoipServer/VoipRouter.cpp" + "${BF2_ROOT}/VoipServer/VoipClients.cpp" + "${BF2_ROOT}/VoipServer/VoipOutgoingChannels.cpp" + "${BF2_ROOT}/Core/Timer.cpp" + "${BF2_ROOT}/Core/SystemInfo.cpp" + "${BF2_ROOT}/Core/StringUtil.cpp") + bf2_configure_cpp_target(bf2_voip_debug_check) + bf2_set_platform_compat(bf2_voip_debug_check) + bf2_set_image(bf2_voip_debug_check 1) + target_compile_definitions(bf2_voip_debug_check PRIVATE BF2_PLATFORM_POSIX _MACOSX) + target_link_options(bf2_voip_debug_check PRIVATE "-Wl,-undefined,dynamic_lookup") + if(BUILD_TESTING) + add_test(NAME bf2_voip_debug_check COMMAND bf2_voip_debug_check) + endif() +endif() + +# [TEMP] The online services' domain (Code/Tests/online_provider_runtime.cpp): the host names formed +# for the retail domain and for a +gamespy value, looked up by the linked GameSpy SDK and by +# the persistence classes. The fixture replaces the resolver, so no name leaves the process, and +# listens on the services' own loopback ports. Built on request; the client image (DEDICATED=0), +# which links every service. +if(APPLE) + add_executable(bf2_online_provider_check EXCLUDE_FROM_ALL + Code/Tests/online_provider_runtime.cpp + "${BF2_ROOT}/Game/MatchMaking/OnlineProvider.cpp" + "${BF2_ROOT}/Game/MatchMaking/OnlineProviderGameSpy.cpp" + "${BF2_ROOT}/Game/Persistence/HTTPRequest.cpp" + "${BF2_ROOT}/Game/Persistence/StatsManager.cpp" + "${BF2_ROOT}/Game/Persistence/PlayerStatsManager.cpp" + "${BF2_ROOT}/Core/StringUtil.cpp" + $ + $ + $) + bf2_configure_cpp_target(bf2_online_provider_check) + bf2_set_platform_compat(bf2_online_provider_check) + bf2_set_image(bf2_online_provider_check 0) + target_compile_definitions(bf2_online_provider_check PRIVATE BF2_PLATFORM_POSIX _MACOSX) + find_package(Threads REQUIRED) + target_link_libraries(bf2_online_provider_check PRIVATE Threads::Threads) + if(BUILD_TESTING) + add_test(NAME bf2_online_provider_check COMMAND bf2_online_provider_check) + endif() +endif() + +# bf2_memory - the rebuilt Memory.dll (Code/BF2/Memory). Built on request only (EXCLUDE_FROM_ALL) +# and linked into no game image (issue #7). Its tests join CTest when BF2_MEMORY_TESTS is ON. +add_subdirectory(Code/BF2/Memory) + +# [CHOSEN, not recovered] CPU-only effect pipeline for the macOS renderer facade. +if(BF2_BUILD_MACOS) + add_subdirectory(Code/BF2/Platform/Gfx/Effect) + add_subdirectory(Code/Tests/macos_gfx_forward) + # [CHOSEN, not recovered] Native effect compilation is mandatory; the effect subdirectory + # rejects missing dependencies at configure time. No developer oracle is invoked here. + if(TARGET bf2_renddx9_static) + target_compile_definitions(bf2_renddx9_static PRIVATE BF2_FX_NATIVE=1) + endif() + if(BF2_MACOS_LINK_RENDDX9 AND TARGET bf2_client AND TARGET bf2_renddx9_static) + target_link_libraries(bf2_client PRIVATE bf2_fx_native_compiler) + target_include_directories(bf2_renddx9_static PRIVATE "${BF2_ROOT}/Platform/Gfx/Effect") + endif() +endif() # The focused checks mirror Code/Tests/*.cmd, which are MSVC x86 gates; they are not part of the -# Linux port (its checks are the dice_py runtime check and the production run). +# Linux and macOS ports (their checks are the dice_py runtime check and the production run). if(BUILD_TESTING AND MSVC) function(bf2_add_check target) add_executable("${target}" EXCLUDE_FROM_ALL ${ARGN}) @@ -1818,6 +2806,9 @@ if(BUILD_TESTING AND MSVC) "${BF2_ROOT}/Game/Objects/Visual/LightSource.cpp" "${BF2_ROOT}/Game/Objects/Visual/LightSourceTemplate.cpp" "${BF2_ROOT}/Scene/Object/WorldObjTemplPortal/PortalManager.cpp" + "${BF2_ROOT}/Scene/Object/WorldObjTemplPortal/PortalPassing.cpp" + "${BF2_ROOT}/Scene/Object/WorldObjTemplPortal/Sector.cpp" + "${BF2_ROOT}/Scene/Object/WorldObjTemplPortal/PortalEvent.cpp" "${BF2_ROOT}/Scene/Object/Object.cpp" "${BF2_ROOT}/Scene/Object/ObjectPredicator.cpp" "${BF2_ROOT}/Scene/Object/ObjectUtil.cpp" @@ -1841,6 +2832,8 @@ if(BUILD_TESTING AND MSVC) "${BF2_ROOT}/Physics/StaticResponsePhysics.cpp" "${BF2_ROOT}/IO/Network/INetworkable.cpp" "${BF2_ROOT}/Math/LocalBoundingBox.cpp" + "${BF2_ROOT}/Math/Intersect.cpp" + "${BF2_ROOT}/IO/Stream/BoundingBox.cpp" "${BF2_ROOT}/Math/Frustum.cpp" "${BF2_ROOT}/Math/Mat4.cpp" "${BF2_ROOT}/Math/Plane3.cpp" @@ -1853,6 +2846,25 @@ if(BUILD_TESTING AND MSVC) target_compile_options(bf2_runtime_pair PRIVATE /Gy) target_link_options(bf2_runtime_pair PRIVATE /OPT:REF) + # [CHOSEN, not recovered] The client's Registry.dat (docs/registry-file.md): fake CD keys + # round-trip through CryptProtectData and the production reader, and through the dev script. + # A client image (DEDICATED=0), so it is not a bf2_add_check. + add_executable(bf2_registry_dat_check EXCLUDE_FROM_ALL + "${BF2_STUB_ROOT}/registry_dat_check.cpp" + "${BF2_ROOT}/Core/Registry.cpp" + ) + target_compile_features(bf2_registry_dat_check PRIVATE cxx_std_14) + target_compile_options(bf2_registry_dat_check PRIVATE /EHsc /O2 /permissive) + bf2_use_static_msvc_runtime(bf2_registry_dat_check) + bf2_set_image(bf2_registry_dat_check 0) + set_property(TARGET bf2_registry_dat_check PROPERTY FOLDER "Checks") + add_test(NAME bf2_registry_dat_check COMMAND $) + add_test(NAME bf2_registry_dat_script + COMMAND powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command + "& '${CMAKE_CURRENT_SOURCE_DIR}/tools/windows/new-registry-dat.ps1' -CdKey FAKE-SCRIPT-0000-1111 -Path '${CMAKE_BINARY_DIR}/registry_dat_script/Registry.dat'; if (-not $?) { exit 1 }; & '$' '${CMAKE_BINARY_DIR}/registry_dat_script/Registry.dat' FAKE-SCRIPT-0000-1111; exit $LASTEXITCODE" + ) + set_tests_properties(bf2_registry_dat_check bf2_registry_dat_script PROPERTIES RUN_SERIAL TRUE) + add_custom_target(bf2_run_checks COMMAND "${CMAKE_CTEST_COMMAND}" --output-on-failure -C $ DEPENDS @@ -1861,6 +2873,7 @@ if(BUILD_TESTING AND MSVC) bf2_bundle_template_core bf2_bundle_serialization bf2_runtime_pair + bf2_registry_dat_check WORKING_DIRECTORY "${CMAKE_BINARY_DIR}" USES_TERMINAL VERBATIM diff --git a/CMakePresets.json b/CMakePresets.json index e2b3267df..0a9bde771 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -55,6 +55,36 @@ "CMAKE_EXPORT_COMPILE_COMMANDS": "ON", "BUILD_TESTING": "OFF" } + }, + { + "name": "macos-x64", + "displayName": "BF2 native macOS dedicated port", + "description": "AppleClang on macOS: x86_64 build with Unix Makefiles. Needs the Command Line Tools and cmake.", + "generator": "Unix Makefiles", + "binaryDir": "${sourceDir}/out/build/${presetName}", + "condition": { + "type": "equals", + "lhs": "${hostSystemName}", + "rhs": "Darwin" + }, + "cacheVariables": { + "CMAKE_OSX_SYSROOT": "macosx", + "CMAKE_OSX_ARCHITECTURES": "x86_64", + "CMAKE_OSX_DEPLOYMENT_TARGET": "11.0", + "CMAKE_BUILD_TYPE": "RelWithDebInfo", + "CMAKE_EXPORT_COMPILE_COMMANDS": "ON", + "BUILD_TESTING": "OFF" + } + }, + { + "name": "macos-universal", + "inherits": "macos-x64", + "displayName": "BF2 native macOS universal port", + "description": "[CHOSEN, not recovered] AppleClang arm64 and x86_64 slices; arm64 runtime validation requires Apple silicon.", + "binaryDir": "${sourceDir}/out/build/${presetName}", + "cacheVariables": { + "CMAKE_OSX_ARCHITECTURES": "arm64;x86_64" + } } ], "buildPresets": [ @@ -90,6 +120,25 @@ "bf2", "dice_py_check" ] + }, + { + "name": "macos-x64", + "displayName": "Build bf2 and libdice_py.dylib", + "configurePreset": "macos-x64", + "targets": [ + "bf2", + "dice_py_check" + ] + }, + { + "name": "macos-universal", + "displayName": "Build universal server and runtime checks", + "configurePreset": "macos-universal", + "targets": [ + "bf2", + "dice_py_check", + "bf2_aidll_loader_check" + ] } ], "testPresets": [ diff --git a/Code/AidllAbi/aidll-macos.exports b/Code/AidllAbi/aidll-macos.exports new file mode 100644 index 000000000..35046f6f3 --- /dev/null +++ b/Code/AidllAbi/aidll-macos.exports @@ -0,0 +1,3 @@ +# [CHOSEN, not recovered] Native macOS AI image boundary; all other symbols are private. +_initDll +_deinitDll diff --git a/Code/AidllAbi/aidll-posix.map b/Code/AidllAbi/aidll-posix.map new file mode 100644 index 000000000..4d06b9dd2 --- /dev/null +++ b/Code/AidllAbi/aidll-posix.map @@ -0,0 +1,5 @@ +/* [CHOSEN, not recovered] Native POSIX AI image boundary; prevent host interposition. */ +{ + global: initDll; deinitDll; + local: *; +}; diff --git a/Code/AidllAbi/aidll-x64.def b/Code/AidllAbi/aidll-x64.def new file mode 100644 index 000000000..00cf6846a --- /dev/null +++ b/Code/AidllAbi/aidll-x64.def @@ -0,0 +1,6 @@ +; [CHOSEN, not recovered] Native Windows x64 AI entry points (kr4uzi/OpenBF2 issue #11). +; LoadLibraryBf resolves these names; retail x86 export ordinals are not an x64 contract. +; All other interaction uses the native ClassManager/singleton ABI shared with the host. +EXPORTS + deinitDll + initDll diff --git a/Code/Archive/NovintFalcon/External/NovintHFX/NovintHFX.def b/Code/Archive/NovintFalcon/External/NovintHFX/NovintHFX.def new file mode 100644 index 000000000..ab9a40271 --- /dev/null +++ b/Code/Archive/NovintFalcon/External/NovintHFX/NovintHFX.def @@ -0,0 +1,100 @@ +; Exact subset of the original BF2.exe import names, exported by stock NovintHFX.dll. +; Import library only: lib /nologo /machine:x86 /def:NovintHFX.def /out:/NovintHFX.lib +LIBRARY NovintHFX.dll +EXPORTS + Haptics DATA + ??0mouse_settings@ApplicationData@NovintHFX@@QAE@XZ + ?AttachApplication@HapticsSystem@NovintHFX@@QAE_NAAUApplicationData@2@@Z + ?RecountConnectedDevices@HapticsSystem@NovintHFX@@QAEXXZ + ?ConnectedDeviceCount@HapticsSystem@NovintHFX@@QBEHXZ + ?RunDevice@HapticsSystem@NovintHFX@@QAE_NPAPAVDevice@2@H@Z + ?StartMouse@HapticsSystem@NovintHFX@@QAEXPAVDevice@2@@Z + ?StopRunningDevice@HapticsSystem@NovintHFX@@QAE_NPAPAVDevice@2@@Z + ?InputUpdate@HapticsSystem@NovintHFX@@QAEHXZ + ?InputUpdate@Device@NovintHFX@@QAEXXZ + ?GetButtonData@Device@NovintHFX@@QBEXPAH00@Z + ?GetToolPosition@Device@NovintHFX@@QBEXQAN@Z + ??0ControlBoxEffectParams@NovintHFX@@QAE@XZ + ??1BaseEffectParams@NovintHFX@@UAE@XZ + ?CreateNewEffect@Stack@NovintHFX@@QAE_NPBDPAUIHapticEffectParam@@0PAPAVIHapticEffect@@@Z + ?CreateStandardEffect@BaseEffectParams@NovintHFX@@UAE_NPAVDevice@2@PBDPAPAVIHapticEffect@@@Z + ?CreateStandardEffect@BaseEffectParams@NovintHFX@@UAE_NPAVStack@2@PBDPAPAVIHapticEffect@@@Z + ?GetEffectStack@Device@NovintHFX@@QAEPAVStack@2@XZ + ?GetStaticInfoClass@ControlBoxEffectParams@NovintHFX@@UAEPAUParamsStaticClass@2@XZ + ?GetVar@ControlBoxEffectParams@NovintHFX@@UAE_NPBDAAH@Z + ?GetVar@ControlBoxEffectParams@NovintHFX@@UAE_NPBDAAM@Z + ?GetVar@ControlBoxEffectParams@NovintHFX@@UAE_NPBDAAN@Z + ?GetVar@ControlBoxEffectParams@NovintHFX@@UAE_NPBDAA_N@Z + ?GetVar@ControlBoxEffectParams@NovintHFX@@UAE_NPBDHAAH@Z + ?GetVar@ControlBoxEffectParams@NovintHFX@@UAE_NPBDHAAM@Z + ?GetVar@ControlBoxEffectParams@NovintHFX@@UAE_NPBDHAAN@Z + ?GetVar@ControlBoxEffectParams@NovintHFX@@UAE_NPBDHAA_N@Z + ?GetVar@ControlBoxEffectParams@NovintHFX@@UAE_NPBDHPAX@Z + ?GetVar@ControlBoxEffectParams@NovintHFX@@UAE_NPBDPAX@Z + ?GetVarType@ControlBoxEffectParams@NovintHFX@@UBEDPBDPAH@Z + ?RunSetCommand@BaseEffectParams@NovintHFX@@UAE_NPAD@Z + ?SetVar@BaseEffectParams@NovintHFX@@UAE_NPBD0@Z + ?SetVar@ControlBoxEffectParams@NovintHFX@@UAE_NPBDH@Z + ?SetVar@ControlBoxEffectParams@NovintHFX@@UAE_NPBDHH@Z + ?SetVar@ControlBoxEffectParams@NovintHFX@@UAE_NPBDHM@Z + ?SetVar@ControlBoxEffectParams@NovintHFX@@UAE_NPBDHN@Z + ?SetVar@ControlBoxEffectParams@NovintHFX@@UAE_NPBDHPAX@Z + ?SetVar@ControlBoxEffectParams@NovintHFX@@UAE_NPBDH_N@Z + ?SetVar@ControlBoxEffectParams@NovintHFX@@UAE_NPBDM@Z + ?SetVar@ControlBoxEffectParams@NovintHFX@@UAE_NPBDN@Z + ?SetVar@ControlBoxEffectParams@NovintHFX@@UAE_NPBDPAX@Z + ?SetVar@ControlBoxEffectParams@NovintHFX@@UAE_NPBD_N@Z + ?StandardEffectName@ControlBoxEffectParams@NovintHFX@@UBEPBDXZ + ??AVect3@NovintHFX@@QAEAANH@Z + ??0Vect3@NovintHFX@@QAE@ABN00@Z + ?GetStaticInfoClass@ConstantEffectParams@NovintHFX@@UAEPAUParamsStaticClass@2@XZ + ?GetVarType@ConstantEffectParams@NovintHFX@@UBEDPBDPAH@Z + ?GetVar@ConstantEffectParams@NovintHFX@@UAE_NPBDAAM@Z + ?GetVar@ConstantEffectParams@NovintHFX@@UAE_NPBDAAN@Z + ?GetVar@ConstantEffectParams@NovintHFX@@UAE_NPBDAA_N@Z + ?GetVar@ConstantEffectParams@NovintHFX@@UAE_NPBDAAH@Z + ?GetVar@ConstantEffectParams@NovintHFX@@UAE_NPBDPAX@Z + ?GetVar@ConstantEffectParams@NovintHFX@@UAE_NPBDHAAM@Z + ?GetVar@ConstantEffectParams@NovintHFX@@UAE_NPBDHAAN@Z + ?GetVar@ConstantEffectParams@NovintHFX@@UAE_NPBDHAA_N@Z + ?GetVar@ConstantEffectParams@NovintHFX@@UAE_NPBDHAAH@Z + ?GetVar@ConstantEffectParams@NovintHFX@@UAE_NPBDHPAX@Z + ?SetVar@ConstantEffectParams@NovintHFX@@UAE_NPBDN@Z + ?SetVar@ConstantEffectParams@NovintHFX@@UAE_NPBD_N@Z + ?SetVar@ConstantEffectParams@NovintHFX@@UAE_NPBDM@Z + ?SetVar@ConstantEffectParams@NovintHFX@@UAE_NPBDH@Z + ?SetVar@ConstantEffectParams@NovintHFX@@UAE_NPBDPAX@Z + ?SetVar@ConstantEffectParams@NovintHFX@@UAE_NPBDHN@Z + ?SetVar@ConstantEffectParams@NovintHFX@@UAE_NPBDH_N@Z + ?SetVar@ConstantEffectParams@NovintHFX@@UAE_NPBDHM@Z + ?SetVar@ConstantEffectParams@NovintHFX@@UAE_NPBDHH@Z + ?SetVar@ConstantEffectParams@NovintHFX@@UAE_NPBDHPAX@Z + ?StandardEffectName@ConstantEffectParams@NovintHFX@@UBEPBDXZ + ??0ConstantEffectParams@NovintHFX@@QAE@XZ + ??4Vect3@NovintHFX@@QAEAAU01@ABU01@@Z + ?GetStaticInfoClass@EnvelopeEffectParams@NovintHFX@@UAEPAUParamsStaticClass@2@XZ + ?GetVarType@EnvelopeEffectParams@NovintHFX@@UBEDPBDPAH@Z + ?GetVar@EnvelopeEffectParams@NovintHFX@@UAE_NPBDAAM@Z + ?GetVar@EnvelopeEffectParams@NovintHFX@@UAE_NPBDAAN@Z + ?GetVar@EnvelopeEffectParams@NovintHFX@@UAE_NPBDAA_N@Z + ?GetVar@EnvelopeEffectParams@NovintHFX@@UAE_NPBDAAH@Z + ?GetVar@EnvelopeEffectParams@NovintHFX@@UAE_NPBDPAX@Z + ?GetVar@EnvelopeEffectParams@NovintHFX@@UAE_NPBDHAAM@Z + ?GetVar@EnvelopeEffectParams@NovintHFX@@UAE_NPBDHAAN@Z + ?GetVar@EnvelopeEffectParams@NovintHFX@@UAE_NPBDHAA_N@Z + ?GetVar@EnvelopeEffectParams@NovintHFX@@UAE_NPBDHAAH@Z + ?GetVar@EnvelopeEffectParams@NovintHFX@@UAE_NPBDHPAX@Z + ?SetVar@EnvelopeEffectParams@NovintHFX@@UAE_NPBDN@Z + ?SetVar@EnvelopeEffectParams@NovintHFX@@UAE_NPBD_N@Z + ?SetVar@EnvelopeEffectParams@NovintHFX@@UAE_NPBDM@Z + ?SetVar@EnvelopeEffectParams@NovintHFX@@UAE_NPBDH@Z + ?SetVar@EnvelopeEffectParams@NovintHFX@@UAE_NPBDPAX@Z + ?SetVar@EnvelopeEffectParams@NovintHFX@@UAE_NPBDHN@Z + ?SetVar@EnvelopeEffectParams@NovintHFX@@UAE_NPBDH_N@Z + ?SetVar@EnvelopeEffectParams@NovintHFX@@UAE_NPBDHM@Z + ?SetVar@EnvelopeEffectParams@NovintHFX@@UAE_NPBDHH@Z + ?SetVar@EnvelopeEffectParams@NovintHFX@@UAE_NPBDHPAX@Z + ?StandardEffectName@EnvelopeEffectParams@NovintHFX@@UBEPBDXZ + ??0EnvelopeEffectParams@NovintHFX@@QAE@XZ + ??DVect3@NovintHFX@@QBE?AU01@ABN@Z + ?Normalize@Vect3@NovintHFX@@QBE?AU12@XZ diff --git a/Code/Archive/NovintFalcon/External/NovintHFX/NovintHFX.h b/Code/Archive/NovintFalcon/External/NovintHFX/NovintHFX.h new file mode 100644 index 000000000..68c830e48 --- /dev/null +++ b/Code/Archive/NovintFalcon/External/NovintHFX/NovintHFX.h @@ -0,0 +1,316 @@ +// [INFERRED] local ABI header; no Novint implementation is reconstructed here. +// Narrow declarations from BF2.exe's NovintHFX imports and its call-site layouts. +// See IO/Input/FALCON_DEVICE_STATUS.md. The matching stock DLL supplies all bodies. +#ifndef EXTERNAL_NOVINTHFX_ABI_H +#define EXTERNAL_NOVINTHFX_ABI_H +#include +#include +// [CHOSEN, not recovered] Test seam: the Mac fake-SDK check (Code/Tests/falcon_update_runtime.cpp) +// builds with BF2_NOVINT_FAKE_SDK and supplies every body; product images always import. +#if defined(BF2_NOVINT_FAKE_SDK) +#define NOVINTHFX_IMPORT +#else +#define NOVINTHFX_IMPORT __declspec(dllimport) +#endif +namespace NovintHFX { +class Stack; +class Device; +// Three doubles (24 bytes: BF2.exe 0x4A34BA builds one at ebp-0x54, the next local at ebp-0x3C). +// Only SDK members touch the components. [UNRESOLVED] member name. A struct: +// the SDK's own Vect3 imports mangle it U (??4Vect3@NovintHFX@@QAEAAU01@ABU01@@Z). +struct Vect3 { + NOVINTHFX_IMPORT Vect3(const double&, const double&, const double&); + NOVINTHFX_IMPORT double& operator[](int); + NOVINTHFX_IMPORT Vect3& operator=(const Vect3&); + NOVINTHFX_IMPORT Vect3 operator*(const double&) const; + NOVINTHFX_IMPORT Vect3 Normalize() const; +private: + double m_unresolved[3]; +}; +} +class IHapticEffect; + +// Effect parameter interface, global namespace (CreateNewEffect's PAUIHapticEffectParam@@). +// Slot order from BF2.exe's local ControlBoxEffectParams vtable 0x9116E0. MSVC groups overloads +// of one name at the first one's slot in reverse declaration order, so each group below is +// declared last slot first. +struct IHapticEffectParam { + virtual bool RunSetCommand(char*) = 0; // +0x00 + virtual const char* StandardEffectName() const = 0; // +0x04 + virtual bool SetVar(const char*, double) = 0; // +0x2C + virtual bool SetVar(const char*, bool) = 0; // +0x28 + virtual bool SetVar(const char*, float) = 0; // +0x24 + virtual bool SetVar(const char*, int) = 0; // +0x20 + virtual bool SetVar(const char*, void*) = 0; // +0x1C + virtual bool SetVar(const char*, int, double) = 0; // +0x18 + virtual bool SetVar(const char*, int, bool) = 0; // +0x14 + virtual bool SetVar(const char*, int, float) = 0; // +0x10 + virtual bool SetVar(const char*, int, int) = 0; // +0x0C + virtual bool SetVar(const char*, int, void*) = 0; // +0x08 + virtual bool GetVar(const char*, float&) = 0; // +0x54 + virtual bool GetVar(const char*, double&) = 0; // +0x50 + virtual bool GetVar(const char*, bool&) = 0; // +0x4C + virtual bool GetVar(const char*, int&) = 0; // +0x48 + virtual bool GetVar(const char*, void*) = 0; // +0x44 + virtual bool GetVar(const char*, int, float&) = 0; // +0x40 + virtual bool GetVar(const char*, int, double&) = 0; // +0x3C + virtual bool GetVar(const char*, int, bool&) = 0; // +0x38 + virtual bool GetVar(const char*, int, int&) = 0; // +0x34 + virtual bool GetVar(const char*, int, void*) = 0; // +0x30 + // +0x58..+0x94: header-inline typed forwarders (BF2.exe 0x5A42D0..0x5A43B0, 0x5D1600, + // 0x626BF0, 0x83C790), each a tail call of the slot named. [INFERRED] names: the bodies show + // only their targets. + virtual bool SetFloatVar(const char* n, float v) { return SetVar(n, v); } // +0x5C -> +0x24 + virtual bool SetFloatVar(const char* n, int i, float v) { return SetVar(n, i, v); } // +0x58 -> +0x10 + virtual bool SetDoubleVar(const char* n, double v) { return SetVar(n, v); } // +0x64 -> +0x2C + virtual bool SetDoubleVar(const char* n, int i, double v) { return SetVar(n, i, v); } // +0x60 -> +0x18 + virtual bool SetIntVar(const char* n, int v) { return SetVar(n, v); } // +0x6C -> +0x20 + virtual bool SetIntVar(const char* n, int i, int v) { return SetVar(n, i, v); } // +0x68 -> +0x0C + virtual bool SetBoolVar(const char* n, bool v) { return SetVar(n, v); } // +0x74 -> +0x28 + virtual bool SetBoolVar(const char* n, int i, bool v) { return SetVar(n, i, v); } // +0x70 -> +0x14 + virtual bool GetFloatVar(const char* n, float& v) { return GetVar(n, v); } // +0x7C -> +0x54 + virtual bool GetFloatVar(const char* n, int i, float& v) { return GetVar(n, i, v); } // +0x78 -> +0x40 + virtual bool GetDoubleVar(const char* n, double& v) { return GetVar(n, v); } // +0x84 -> +0x50 + virtual bool GetDoubleVar(const char* n, int i, double& v) { return GetVar(n, i, v); } // +0x80 -> +0x3C + virtual bool GetIntVar(const char* n, int& v) { return GetVar(n, v); } // +0x8C -> +0x48 + virtual bool GetIntVar(const char* n, int i, int& v) { return GetVar(n, i, v); } // +0x88 -> +0x34 + virtual bool GetBoolVar(const char* n, bool& v) { return GetVar(n, v); } // +0x94 -> +0x4C + virtual bool GetBoolVar(const char* n, int i, bool& v) { return GetVar(n, i, v); } // +0x90 -> +0x38 +}; + +// A running effect, owned by the device's effect stack (global namespace, PAPAVIHapticEffect@@). +// [UNRESOLVED] Only what BF2.exe 0x6A5835/0x6A5995/0x6A599D uses is declared; the haptic-effect +// sites (ledger N2) name the remaining slots. +class IHapticEffect { +public: + virtual void unresolvedSlot00() = 0; + virtual void unresolvedSlot04() = 0; + virtual void unresolvedSlot08() = 0; + virtual void unresolvedSlot0C() = 0; + virtual void unresolvedSlot10() = 0; + virtual void unresolvedSlot14() = 0; + virtual void unresolvedSlot18() = 0; + virtual void unresolvedSlot1C() = 0; + virtual void unresolvedSlot20() = 0; + virtual void unresolvedSlot24() = 0; + virtual void unresolvedSlot28() = 0; + virtual void unresolvedSlot2C() = 0; + virtual void unresolvedSlot30() = 0; + virtual void unresolvedSlot34() = 0; + virtual void unresolvedSlot38() = 0; + virtual void unresolvedSlot3C() = 0; + virtual void unresolvedSlot40() = 0; + virtual bool UpdateParams(IHapticEffectParam*) = 0; // +0x44 [INFERRED] name and result + virtual void unresolvedSlot48() = 0; + virtual void SetForce(const NovintHFX::Vect3&) = 0; // +0x4C [INFERRED] name and result; 0x4A34C3 + virtual void unresolvedSlot50() = 0; + // +0x54 [INFERRED] name and result: Soldier's CraftPhysics effects pass HapticSettings' + // PhysicsSOLDIERSmoothTime* here every tick (0x5AF322), the value also given as params +0x18. + virtual void SetSmoothTime(int) = 0; + unsigned char m_unresolved04[8]; + unsigned char m_stateFlags; // +0x0C; bit 0 [INFERRED] suspended, read and written inline +protected: + IHapticEffect(); // DLL-owned; created only by Stack::CreateNewEffect +}; + +namespace NovintHFX { +struct ParamsStaticClass; // [UNRESOLVED] opaque; returned by GetStaticInfoClass + +// Shared effect-parameter base. Its own virtuals follow the interface's (+0x98..+0xAC). +class BaseEffectParams : public IHapticEffectParam { +public: + NOVINTHFX_IMPORT bool RunSetCommand(char*) override; + NOVINTHFX_IMPORT virtual ~BaseEffectParams(); // +0x98 + NOVINTHFX_IMPORT virtual bool SetVar(const char*, const char*); // +0x9C + using IHapticEffectParam::SetVar; + virtual char GetVarType(const char*, int*) const = 0; // +0xA0 + virtual ParamsStaticClass* GetStaticInfoClass() = 0; // +0xA4 + NOVINTHFX_IMPORT virtual bool CreateStandardEffect(Device*, const char*, IHapticEffect**); // +0xAC + NOVINTHFX_IMPORT virtual bool CreateStandardEffect(Stack*, const char*, IHapticEffect**); // +0xA8 +protected: + BaseEffectParams(); // reached only through the derived SDK constructors +private: + alignas(4) unsigned char m_baseState[20]; // +0x04 [UNRESOLVED] SDK-owned +}; + +class ConstantEffectParams : public BaseEffectParams { +public: + // [INFERRED] throw(): BF2.exe's new-expression at 0x5A416E has no unwind state around the + // constructor call, so the compiler treated the construction as non-throwing. + NOVINTHFX_IMPORT ConstantEffectParams() throw(); + NOVINTHFX_IMPORT const char* StandardEffectName() const override; + NOVINTHFX_IMPORT bool SetVar(const char*, double) override; + NOVINTHFX_IMPORT bool SetVar(const char*, bool) override; + NOVINTHFX_IMPORT bool SetVar(const char*, float) override; + NOVINTHFX_IMPORT bool SetVar(const char*, int) override; + NOVINTHFX_IMPORT bool SetVar(const char*, void*) override; + NOVINTHFX_IMPORT bool SetVar(const char*, int, double) override; + NOVINTHFX_IMPORT bool SetVar(const char*, int, bool) override; + NOVINTHFX_IMPORT bool SetVar(const char*, int, float) override; + NOVINTHFX_IMPORT bool SetVar(const char*, int, int) override; + NOVINTHFX_IMPORT bool SetVar(const char*, int, void*) override; + using BaseEffectParams::SetVar; + NOVINTHFX_IMPORT bool GetVar(const char*, float&) override; + NOVINTHFX_IMPORT bool GetVar(const char*, double&) override; + NOVINTHFX_IMPORT bool GetVar(const char*, bool&) override; + NOVINTHFX_IMPORT bool GetVar(const char*, int&) override; + NOVINTHFX_IMPORT bool GetVar(const char*, void*) override; + NOVINTHFX_IMPORT bool GetVar(const char*, int, float&) override; + NOVINTHFX_IMPORT bool GetVar(const char*, int, double&) override; + NOVINTHFX_IMPORT bool GetVar(const char*, int, bool&) override; + NOVINTHFX_IMPORT bool GetVar(const char*, int, int&) override; + NOVINTHFX_IMPORT bool GetVar(const char*, int, void*) override; + NOVINTHFX_IMPORT char GetVarType(const char*, int*) const override; + NOVINTHFX_IMPORT ParamsStaticClass* GetStaticInfoClass() override; + int m_unresolved18; // +0x18 [UNRESOLVED] meaning; BF2.exe 0x5A418F writes 0x14 for "ShakeForce" + int m_unresolved1C; // +0x1C [UNRESOLVED] +}; + +class EnvelopeEffectParams : public BaseEffectParams { +public: + // [INFERRED] throw(): BF2.exe's new-expression at 0x5E65B4 has no unwind state around the + // constructor call, so the compiler treated the construction as non-throwing. + NOVINTHFX_IMPORT EnvelopeEffectParams() throw(); + NOVINTHFX_IMPORT const char* StandardEffectName() const override; + NOVINTHFX_IMPORT bool SetVar(const char*, double) override; + NOVINTHFX_IMPORT bool SetVar(const char*, bool) override; + NOVINTHFX_IMPORT bool SetVar(const char*, float) override; + NOVINTHFX_IMPORT bool SetVar(const char*, int) override; + NOVINTHFX_IMPORT bool SetVar(const char*, void*) override; + NOVINTHFX_IMPORT bool SetVar(const char*, int, double) override; + NOVINTHFX_IMPORT bool SetVar(const char*, int, bool) override; + NOVINTHFX_IMPORT bool SetVar(const char*, int, float) override; + NOVINTHFX_IMPORT bool SetVar(const char*, int, int) override; + NOVINTHFX_IMPORT bool SetVar(const char*, int, void*) override; + using BaseEffectParams::SetVar; + NOVINTHFX_IMPORT bool GetVar(const char*, float&) override; + NOVINTHFX_IMPORT bool GetVar(const char*, double&) override; + NOVINTHFX_IMPORT bool GetVar(const char*, bool&) override; + NOVINTHFX_IMPORT bool GetVar(const char*, int&) override; + NOVINTHFX_IMPORT bool GetVar(const char*, void*) override; + NOVINTHFX_IMPORT bool GetVar(const char*, int, float&) override; + NOVINTHFX_IMPORT bool GetVar(const char*, int, double&) override; + NOVINTHFX_IMPORT bool GetVar(const char*, int, bool&) override; + NOVINTHFX_IMPORT bool GetVar(const char*, int, int&) override; + NOVINTHFX_IMPORT bool GetVar(const char*, int, void*) override; + NOVINTHFX_IMPORT char GetVarType(const char*, int*) const override; + NOVINTHFX_IMPORT ParamsStaticClass* GetStaticInfoClass() override; + int m_unresolved18; // +0x18 [UNRESOLVED] meaning; BF2.exe 0x5E65C4 writes 0x64 for "Damage" + alignas(4) unsigned char m_unresolved1C[12]; // +0x1C [UNRESOLVED] + double m_force[3]; // +0x28 [INFERRED] name; BF2.exe 0x5E665C..0x5E667A write the scaled direction +}; + +// The control box BF2 builds in FalconDevice::updateCurrentState (BF2.exe 0x6A587F): 0x120 +// bytes, SDK constructor, every virtual imported except the interface's inline forwarders. +class ControlBoxEffectParams : public BaseEffectParams { +public: + // [INFERRED] throw(): BF2.exe's new-expression at 0x6A587F has no unwind state around the + // constructor call, so the compiler treated the construction as non-throwing. + NOVINTHFX_IMPORT ControlBoxEffectParams() throw(); + NOVINTHFX_IMPORT const char* StandardEffectName() const override; + NOVINTHFX_IMPORT bool SetVar(const char*, double) override; + NOVINTHFX_IMPORT bool SetVar(const char*, bool) override; + NOVINTHFX_IMPORT bool SetVar(const char*, float) override; + NOVINTHFX_IMPORT bool SetVar(const char*, int) override; + NOVINTHFX_IMPORT bool SetVar(const char*, void*) override; + NOVINTHFX_IMPORT bool SetVar(const char*, int, double) override; + NOVINTHFX_IMPORT bool SetVar(const char*, int, bool) override; + NOVINTHFX_IMPORT bool SetVar(const char*, int, float) override; + NOVINTHFX_IMPORT bool SetVar(const char*, int, int) override; + NOVINTHFX_IMPORT bool SetVar(const char*, int, void*) override; + using BaseEffectParams::SetVar; + NOVINTHFX_IMPORT bool GetVar(const char*, float&) override; + NOVINTHFX_IMPORT bool GetVar(const char*, double&) override; + NOVINTHFX_IMPORT bool GetVar(const char*, bool&) override; + NOVINTHFX_IMPORT bool GetVar(const char*, int&) override; + NOVINTHFX_IMPORT bool GetVar(const char*, void*) override; + NOVINTHFX_IMPORT bool GetVar(const char*, int, float&) override; + NOVINTHFX_IMPORT bool GetVar(const char*, int, double&) override; + NOVINTHFX_IMPORT bool GetVar(const char*, int, bool&) override; + NOVINTHFX_IMPORT bool GetVar(const char*, int, int&) override; + NOVINTHFX_IMPORT bool GetVar(const char*, int, void*) override; + NOVINTHFX_IMPORT char GetVarType(const char*, int*) const override; + NOVINTHFX_IMPORT ParamsStaticClass* GetStaticInfoClass() override; + // Written inline by BF2.exe 0x6A58E4..0x6A593E. [INFERRED] names: the lower and upper box + // walls and the spring stiffness on each side, per axis. + double m_lower[3]; // +0x18 + double m_upper[3]; // +0x30 + double m_unresolved48[6]; // +0x48 [UNRESOLVED] + double m_lowerStiffness[3]; // +0x78 + double m_upperStiffness[3]; // +0x90 + alignas(4) unsigned char m_unresolvedA8[0x6C]; // +0xA8 [UNRESOLVED] + int m_unresolved114; // +0x114; BF2 writes 3000 (ds:0x979010) [UNRESOLVED] meaning + alignas(4) unsigned char m_unresolved118[8]; // +0x118 [UNRESOLVED] +}; +} + +namespace NovintHFX { +struct ApplicationData { + struct mouse_settings { + NOVINTHFX_IMPORT mouse_settings(); + private: + // Opaque SDK state, 28-byte stack extent at BF2.exe 0x6A4EF0. + // Its own SDK constructor owns every field; no fabricated initialization. + alignas(4) unsigned char m_sdkState[28]; + }; + HWND window; // [INFERRED] name; HWND at byte 0, 0x6A4F23. + mouse_settings mouse; +}; +class Stack { +public: + NOVINTHFX_IMPORT bool CreateNewEffect(const char*, IHapticEffectParam*, const char*, IHapticEffect**); +#if defined(BF2_NOVINT_FAKE_SDK) +public: // [CHOSEN, not recovered] test seam: the fake SDK owns its instances +#else +private: +#endif + Stack(); // Opaque DLL-owned instance. +}; +class Device { +public: + NOVINTHFX_IMPORT void InputUpdate(); + NOVINTHFX_IMPORT void GetButtonData(int*, int*, int*) const; + NOVINTHFX_IMPORT void GetToolPosition(double* const) const; + NOVINTHFX_IMPORT Stack* GetEffectStack(); +#if defined(BF2_NOVINT_FAKE_SDK) +public: // [CHOSEN, not recovered] test seam: the fake SDK owns its instances +#else +private: +#endif + Device(); // Opaque DLL-owned instance; never allocate from this declaration. +}; +class HapticsSystem { +public: + NOVINTHFX_IMPORT bool AttachApplication(ApplicationData&); + NOVINTHFX_IMPORT void RecountConnectedDevices(); + NOVINTHFX_IMPORT int ConnectedDeviceCount() const; + NOVINTHFX_IMPORT bool RunDevice(Device**, int); + NOVINTHFX_IMPORT void StartMouse(Device*); + NOVINTHFX_IMPORT bool StopRunningDevice(Device**); + NOVINTHFX_IMPORT int InputUpdate(); +#if defined(BF2_NOVINT_FAKE_SDK) +public: // [CHOSEN, not recovered] test seam: the fake SDK defines Haptics +#else +private: +#endif + HapticsSystem(); // Opaque DLL-owned instance; never allocate or copy. +}; +} +// PE IAT 0x87F788: a single IAT load supplies this, i.e. the exported object's +// address. This is neither a pointer variable nor a callable Haptics() function. +extern "C" NOVINTHFX_IMPORT NovintHFX::HapticsSystem Haptics; +static_assert(sizeof(NovintHFX::ApplicationData::mouse_settings) == 28, "SDK ABI"); +#if defined(_M_IX86) +static_assert(sizeof(NovintHFX::ApplicationData) == 32, "x86 SDK ABI"); +static_assert(sizeof(NovintHFX::ControlBoxEffectParams) == 0x120, "BF2.exe 0x6A587F allocation"); +static_assert(offsetof(NovintHFX::ControlBoxEffectParams, m_lower) == 0x18, "x86 SDK ABI"); +static_assert(offsetof(NovintHFX::ControlBoxEffectParams, m_upper) == 0x30, "x86 SDK ABI"); +static_assert(offsetof(NovintHFX::ControlBoxEffectParams, m_lowerStiffness) == 0x78, "x86 SDK ABI"); +static_assert(offsetof(NovintHFX::ControlBoxEffectParams, m_upperStiffness) == 0x90, "x86 SDK ABI"); +static_assert(offsetof(NovintHFX::ControlBoxEffectParams, m_unresolved114) == 0x114, "x86 SDK ABI"); +static_assert(offsetof(IHapticEffect, m_stateFlags) == 0x0C, "x86 SDK ABI"); +static_assert(sizeof(NovintHFX::Vect3) == 24, "BF2.exe 0x4A34BA stack extent"); +#endif +// [CHOSEN, not recovered] x64 (https://github.com/B2BF/OpenBF2/issues/7): the SDK exists only as a +// 32-bit DLL, so an x64 image imports nothing from it; FalconDevice reports no device there. +#endif diff --git a/Code/Archive/NovintFalcon/Game/Objects/Game/SoldierHapticForces.cpp b/Code/Archive/NovintFalcon/Game/Objects/Game/SoldierHapticForces.cpp new file mode 100644 index 000000000..d134afb2b --- /dev/null +++ b/Code/Archive/NovintFalcon/Game/Objects/Game/SoldierHapticForces.cpp @@ -0,0 +1,80 @@ +// [CHOSEN, not recovered] Archived with the Novint Falcon (see README.md): the force inputs the Soldier +// and PlayerControlObject fed to the Falcon effects (ledger N2 17b). They were part of +// Game/Objects/Game/SoldierHapticProfile.cpp; the control-box profile switch stays there. +#include "SoldierHapticForces.h" +#if !DEDICATED +#include "../GenericFireArmTemplate.h" +#include "../Weapons/GenericFireArm.h" +#include "../../../IO/Input/FalconHaptics.h" +#include "../IObject.h" +#include "../IPlayer.h" +#include "../../../Math/Mat4.h" +#include "../../../Physics/IPhysicsNode.h" +#include "../ICameraObject.h" + +namespace dice { namespace hfe { namespace world { + +int HapticWeaponAccess::weaponType(IObject* weapon) +{ + return static_cast(weapon)->m_template->m_weaponType; +} + +void updateSoldierRecoilForce(IPlayer* occupant, IPlayer* localPlayer, float yawDelta, float pitchRecoil, + IObject* weapon) +{ + if (!occupant || occupant != localPlayer) + return; + int weaponType = -1; + if (yawDelta != 0.0f || pitchRecoil != 0.0f) + weaponType = HapticWeaponAccess::weaponType(weapon); + io::updateRecoilForce(yawDelta, pitchRecoil, weaponType); +} + +void updateSoldierCraftPhysics(IPlayer* occupant, IPlayer* localPlayer, IPlayer* player, const Vec3& velocity, + float dt) +{ + if (!occupant || occupant != localPlayer) + return; + const Mat4 inverse = player->getVehicle()->getInvAbsoluteTransformation(); // copied, as shipped + // 0x5A1710: v * M, accumulated on the x87 stack in this order. + const double vx = velocity.x, vy = velocity.y, vz = velocity.z; + Vec3 local; + local.x = static_cast(inverse.m[8] * vz + inverse.m[4] * vy + vx * inverse.m[0]); + local.y = static_cast(inverse.m[1] * vx + inverse.m[9] * vz + inverse.m[5] * vy); + local.z = static_cast(inverse.m[2] * vx + inverse.m[10] * vz + inverse.m[6] * vy); + io::updateSoldierCraftPhysicsForce(local, dt); +} + +namespace { +int s_hapticFrameMode = 3; // ds:0x974BF8, initialized 3; nothing writes it +// 0x5A1710: v * M, accumulated on the x87 stack in this order. +Vec3 rotateIntoFrame(const Vec3& v, const Mat4& m) +{ + const double vx = v.x, vy = v.y, vz = v.z; + Vec3 out; + out.x = static_cast(m.m[8] * vz + m.m[4] * vy + vx * m.m[0]); + out.y = static_cast(m.m[1] * vx + m.m[9] * vz + m.m[5] * vy); + out.z = static_cast(m.m[2] * vx + m.m[10] * vz + m.m[6] * vy); + return out; +} +} // namespace + +void updateVehicleCraftPhysics(IPhysicsNode* physics, IObject* vehicle, ICameraObject* camera, float dt, + int vehicleCategory) +{ + physics->getPositionalAcceleration(); // +0xA8 PE, dropped + Mat4 frame = Mat4::getIdentity(); + switch (s_hapticFrameMode) { // the jump table at 0x5FBE28 + case 0: frame = vehicle->getRelativeTransformation(); break; + case 1: frame = vehicle->getAbsoluteTransformation(); break; + case 2: frame = camera->getTransformation(0.0f); break; + case 3: frame = vehicle->getInvAbsoluteTransformation(); break; + case 4: frame = vehicle->getVisualAbsoluteTransformation(); break; + case 5: frame.setInverse(camera->getTransformation(0.0f)); break; + default: break; + } + io::updateVehicleCraftPhysicsForce(rotateIntoFrame(physics->getPositionalSpeed(), frame), dt, vehicleCategory); +} + +} } } +#endif diff --git a/Code/Archive/NovintFalcon/Game/Objects/Game/SoldierHapticForces.h b/Code/Archive/NovintFalcon/Game/Objects/Game/SoldierHapticForces.h new file mode 100644 index 000000000..2929eb5e3 --- /dev/null +++ b/Code/Archive/NovintFalcon/Game/Objects/Game/SoldierHapticForces.h @@ -0,0 +1,50 @@ +// [CHOSEN, not recovered] Archived with the Novint Falcon (see README.md): the force inputs that were +// declared in Game/Objects/Game/SoldierHapticProfile.h (ledger N2 17b). GenericFireArm declared +// `friend struct HapticWeaponAccess;` for weaponType. +#ifndef GAME_OBJECTS_GAME_SOLDIERHAPTICFORCES_H +#define GAME_OBJECTS_GAME_SOLDIERHAPTICFORCES_H +#include "../../../Core/BuildConfig.h" +#if !DEDICATED +#include "../../../Math/Vec3.h" +namespace dice { namespace hfe { namespace world { +class IPlayer; +class IObject; +class GenericFireArmTemplate; +class ICameraObject; +class IPhysicsNode; + +// Friend of GenericFireArm. weaponType is SoldierHapticProfile.cpp's read (0x5E0AC0); setTemplate is +// defined only by the check. +struct HapticWeaponAccess { + static int weaponType(IObject* weapon); + static void setTemplate(IObject* weapon, const GenericFireArmTemplate* weaponTemplate); +}; + +// Soldier::handlePlayerInput's "Recoil" decision (0x5AE352..0x5AE463, ledger N2 17b), with a device +// connected: only for the local occupant; the weapon's type (0x5E0AC0: the firearm's template +// weaponType, [INFERRED]) is read only when the yaw delta or the raw pitch recoil is non-zero, and +// the weapon is not checked, as shipped; then io::updateRecoilForce. [CHOSEN, not recovered] The +// caller looks up the weapon and the local player up front (both lookups have no effects). +void updateSoldierRecoilForce(IPlayer* occupant, IPlayer* localPlayer, float yawDelta, float pitchRecoil, + IObject* weapon); + +// Soldier::handlePlayerInput's "CraftPhysics" input (0x5AECF5..0x5AED72, ledger N2 17b), with a device +// connected: only for the local occupant; the physics node's linear integration velocity rotated into +// the frame of the controlling player's vehicle (v * getInvAbsoluteTransformation(), 0x5A1710), then +// io::updateSoldierCraftPhysicsForce. [CHOSEN, not recovered] The caller reads the velocity up front. +void updateSoldierCraftPhysics(IPlayer* occupant, IPlayer* localPlayer, IPlayer* player, const Vec3& velocity, + float dt); + +// PlayerControlObject::handleUpdate's "CraftPhysics" input (0x5FAC8C..0x5FADAE, ledger N2 17b), for the +// local occupant with a device and a root physics node: the node's positional acceleration is read and +// dropped, as shipped; the positional speed is rotated (0x5A1710) into the frame chosen by ds:0x974BF8 +// (initialized 3 and never written: 0 the vehicle's relative, 1 absolute, 3 inverse absolute, +// 4 visual absolute transformation, 2 the camera's getTransformation(0), 5 its orthonormal inverse); +// then io::updateVehicleCraftPhysicsForce with the vehicle category. [CHOSEN, not recovered] The caller +// reads the vehicle, the camera and the category up front (all without effects). +void updateVehicleCraftPhysics(IPhysicsNode* physics, IObject* vehicle, ICameraObject* camera, float dt, + int vehicleCategory); + +} } } +#endif +#endif diff --git a/Code/Archive/NovintFalcon/IO/Input/FalconDevice.cpp b/Code/Archive/NovintFalcon/IO/Input/FalconDevice.cpp new file mode 100644 index 000000000..796cda966 --- /dev/null +++ b/Code/Archive/NovintFalcon/IO/Input/FalconDevice.cpp @@ -0,0 +1,877 @@ +// Path [INFERRED]. Client PE recovery; symbolized ELF supplies names/signatures. +// [PLATFORM] ELF has no Novint imports and compiled-out init/update/device calls. +// BF2_NOVINT_FAKE_SDK builds the Windows body against the Mac check's fake SDK. +#include "FalconDevice.h" +#if !DEDICATED && !defined(_WIN32) && !defined(BF2_NOVINT_FAKE_SDK) +namespace dice { namespace hfe { namespace io { +// [CHOSEN, not recovered] Native POSIX clients have no Falcon (see FalconDevice.h); the menu's +// mouse-mode global and the control-box flag keep their shipped initial values. +int g_falconMouseMode = 1; // PE978FC4 +bool g_falconControlBoxDirty = true; // PE978FC8 +// [CHOSEN, not recovered] No Falcon effect is ever created here, so every target stays null and +// MainMenuLogic's zeroing finds nothing to call. +void zeroHapticForceTargets() {} +void updateShakeForce(world::IPlayerControlObject*, float, float, float, float) {} +bool hapticDeviceConnected() { return false; } +void updateRecoilForce(float, float, int) {} +void updateSoldierCraftPhysicsForce(const Vec3&, float) {} +void updateVehicleCraftPhysicsForce(const Vec3&, float, int) {} +void soldierRecoilPunch(int, bool, unsigned int, const float*, float, float, float, float) {} +void fireRecoilPunch(float, float, float) {} +void weaponRecoilPunch(int, const std::string&, float, float, float) {} +void kitRecoilPunch(int, const std::string&, float) {} +void updateDamageForce(world::IPlayer*, world::IPlayer*, const Mat4&, const Mat4&, float) {} +} +IHapticEffect* g_hapticForceTargets[6] = { 0, 0, 0, 0, 0, 0 }; // ds:0x9EBEC8.. (BF2ClientSeams.h) +} } +#elif !DEDICATED +#include "../../Core/Ids.h" +#include "../../Game/ControlSettings.h" +#include "../../Game/HapticSettings.h" +#include "../../Platform/X87Compat.h" +#include "../../Math/Vec3.h" +#include "../../Game/Objects/IObject.h" +#include "../../Game/Objects/IObjectTemplate.h" +#include "../../Scene/Object/ObjectTypes/Game/IPlayerControlObject.h" +#include +#include +#include +#include +#include +#include +#include +#include +// [CHOSEN, not recovered] x64 (https://github.com/B2BF/OpenBF2/issues/7): NovintHFX ships only as a +// 32-bit DLL. The x64 image never calls it: init() reports the device absent through the same +// `false` retail returns with no device connected, so m_device stays null and every device path +// below returns at its existing null test. No SDK symbol is referenced there: the frame update and the +// force zeroing compile to their no-device bodies. +#if defined(_M_IX86) || defined(BF2_NOVINT_FAKE_SDK) +#define BF2_FALCON_SDK 1 +#else +#define BF2_FALCON_SDK 0 +#endif +namespace dice { namespace hfe { +IHapticEffect* g_hapticForceTargets[6] = { 0, 0, 0, 0, 0, 0 }; // ds:0x9EBEC8.. (BF2ClientSeams.h) +extern IBase* g_controlSettings; // ds:0x98738C, Game/Main/BF2ClientSeams.h +extern IBase* g_hapticSettings; // ds:0x987394, Game/Main/BF2ClientSeams.h +namespace io { +extern IBase* inputDeviceManager; // PE 0x9FFCB0, singleton registration 0x698542 +extern IBase* controlMapManager; // PE 0x9FFCB4, Core/Globals.cpp +extern float inputSampleLatency; // PE 0xA07E4C, IO/Input/InputManager.cpp +NovintHFX::Device* g_falconDevice = 0; +int g_falconMouseMode = 1; // PE978FC4 +bool g_falconControlBoxDirty = true; // PE978FC8 +#if BF2_FALCON_SDK +namespace { +// Initialized data read only by updateCurrentState. [INFERRED] names. +double s_falconMouseGain = 1000.0; // ds:0x979018: mouse-mode position gain +short s_controlBoxForceValue = 3000; // ds:0x979010: control box +0x114 [UNRESOLVED] meaning +int s_smoothingWindow = 3; // ds:0x979020: samples between the delta's two ends +int s_smoothingCount = 0; // ds:0xA03948: samples queued in each delta history +IHapticEffect* s_controlBoxEffect = 0; // ds:0xA03944: created once, then updated in place + +// BF2.exe 0x6A589B..0x6A58A1 calls the imported ControlBoxEffectParams constructor and then stores +// its own vtable (0x9116E0), whose deleting destructor (0x5E2EA0) calls ~BaseEffectParams directly: +// the object is a BF2-side class derived from the SDK type with implicit members only. +// [INFERRED] name. +class FalconControlBoxParams : public NovintHFX::ControlBoxEffectParams {}; + +// Retail re-stores its own vtable after the SDK constructor: BF2.exe 0x5A4174 stores 0x8E7698, +// and 0x5E65BA stores 0x8ED440. As above, these BF2-side derived classes have implicit members only. +// [INFERRED] names. +class FalconConstantParams : public NovintHFX::ConstantEffectParams {}; +class FalconEnvelopeParams : public NovintHFX::EnvelopeEffectParams {}; + +// Retail indexes the returned Vec3 as a float array ([eax + 4*esi]). +float component(const Vec3& v, int axis) +{ + return axis == 0 ? v.x : axis == 1 ? v.y : v.z; +} +// The three position histories are function-local statics in retail (guards ds:0xA03988, bits +// 1/2/4; atexit 0x87A040/0x87A030/0x87A020). Dinkumware's pop_front ignores an empty deque. +void popFrontIfAny(std::deque& history) +{ + if (!history.empty()) history.pop_front(); +} +// One smoothing step at a full window: push, drop the oldest, and return the slope across it. +double windowDelta(std::deque& history, double value) +{ + history.push_back(value); + popFrontIfAny(history); + return (history.back() - history.front()) / static_cast(s_smoothingWindow * 2); +} +// Outside the dead zone the offset past its edge drives the axis at `scale`; inside it, the +// smoothed delta drives it at `deltaScale`. Each settings read is a fresh call, as in retail. +double axisValue(IHapticSettings* haptics, int axis, double position, double delta, + double scale, double deltaScale) +{ + if (component(haptics->getAimSensitivityLength(), axis) < position) + return (position - component(haptics->getAimSensitivityLength(), axis)) + * component(haptics->getTurnSensitivity(), axis) * scale; + if (-component(haptics->getAimSensitivityLength(), axis) > position) + return (component(haptics->getAimSensitivityLength(), axis) + position) + * component(haptics->getTurnSensitivity(), axis) * scale; + return delta * deltaScale; +} +} // namespace +#endif // BF2_FALCON_SDK: the frame update's state and helpers + +void zeroHapticForceTargets() +{ +#if !BF2_FALCON_SDK + // x64: no Falcon effect is ever created, so every target is null. +#else + const double x = 0.0, y = 0.0, z = 0.0; + NovintHFX::Vect3 zero(x, y, z); + static const int retailOrder[6] = { 2, 3, 4, 5, 0, 1 }; // 0x9EBF00..0x9EBF0C, then 0x9EBEC8/CC + for (int i = 0; i < 6; ++i) { + IHapticEffect* target = g_hapticForceTargets[retailOrder[i]]; + if (target) target->SetForce(zero); + } +#endif +} + +#if BF2_FALCON_SDK +namespace { +// BF2.exe 0x5A2790: the sign of a double, 0 for 0 and NaN. +double hapticSign(double value) +{ + if (value > 0.0) return 1.0; + if (value < 0.0) return -1.0; + return 0.0; +} +// BF2.exe 0x5A6280: the same for a float. +float hapticSignF(float value) +{ + if (value > 0.0f) return 1.0f; + if (value < 0.0f) return -1.0f; + return 0.0f; +} +} // namespace +#endif + +void updateShakeForce(world::IPlayerControlObject* pco, float explosionRoll, float speedRoll, + float closeVehiclePitch, float recoilY) +{ +#if !BF2_FALCON_SDK + (void) pco; (void) explosionRoll; (void) speedRoll; (void) closeVehiclePitch; (void) recoilY; +#else + if (!g_falconDevice) + return; + IHapticEffect*& vehicleShake = g_hapticForceTargets[0]; // ds:0x9EBEC8 + IHapticEffect*& soldierShake = g_hapticForceTargets[1]; // ds:0x9EBECC + if (vehicleShake && soldierShake) { + IHapticSettings* haptics = static_cast(g_hapticSettings); + float x = haptics->getExplosionShakeScale() * explosionRoll; + x = haptics->getSpeedShakeScale() * speedRoll + x; + x = haptics->getGeneralShakeScale() * closeVehiclePitch + x; + x = haptics->getUnresolved48C() * recoilY + x; + float shared = haptics->getExplosionShakeScale() * explosionRoll; + shared = haptics->getSpeedShakeScale() * speedRoll + shared; + shared = haptics->getGeneralShakeScale() * closeVehiclePitch + shared; + // Retail keeps this product on the x87 stack and stores the sum straight to a double; the + // product of two floats is exact in double. + const double y = static_cast(haptics->getUnresolved490()) * recoilY + shared; + const double xd = x, z = 0.0; + NovintHFX::Vect3 force(xd, y, z); + const float absX = static_cast(std::fabs(force[0])); + if (haptics->getForceCapX() < absX) + force[0] = hapticSign(force[0]) * haptics->getForceCapX(); + const float absY = static_cast(std::fabs(force[1])); + if (haptics->getForceCapY() < absY) + force[1] = hapticSign(force[1]) * haptics->getForceCapY(); + world::IObject* const occupied = static_cast(pco->queryInterface(world::IID_IObject)); + const bool soldier = occupied->getTemplate()->getClassID() == world::CID_SoldierTemplate; + (soldier ? soldierShake : vehicleShake)->SetForce(force); + return; + } + FalconConstantParams* params = new FalconConstantParams; + params->m_unresolved18 = 0x14; + g_falconDevice->GetEffectStack()->CreateNewEffect("CONSTANT", params, "ShakeForce", &vehicleShake); + g_falconDevice->GetEffectStack()->CreateNewEffect("CONSTANT", params, "ShakeForce", &soldierShake); + delete params; +#endif +} + +bool hapticDeviceConnected() +{ +#if !BF2_FALCON_SDK + return false; +#else + return g_falconDevice != 0; +#endif +} + +void updateRecoilForce(float yawDelta, float pitchRecoil, int weaponType) +{ +#if !BF2_FALCON_SDK + (void) yawDelta; (void) pitchRecoil; (void) weaponType; +#else + IHapticEffect*& recoil = g_hapticForceTargets[2]; // ds:0x9EBF00 + if (!recoil) { + FalconConstantParams* params = new FalconConstantParams; + params->m_unresolved18 = 10; + g_falconDevice->GetEffectStack()->CreateNewEffect("Constant", params, "Recoil", &recoil); + delete params; + } + const double x0 = 0.0, y0 = 0.0, z0 = 0.0; + NovintHFX::Vect3 force(x0, y0, z0); + if (yawDelta != 0.0f || pitchRecoil != 0.0f) { + IHapticSettings* haptics = static_cast(g_hapticSettings); + float yawScale, pitchScale; + switch (weaponType) { // the jump table at 0x5AF5DC + case 0: yawScale = haptics->getRecoilYawScaleRIFLE(); pitchScale = haptics->getRecoilPitchScaleRIFLE(); break; + case 1: yawScale = haptics->getRecoilYawScaleRIFLELAUNCHER(); pitchScale = haptics->getRecoilPitchScaleRIFLELAUNCHER(); break; + case 2: yawScale = haptics->getRecoilYawScaleCARBINE(); pitchScale = haptics->getRecoilPitchScaleCARBINE(); break; + case 3: yawScale = haptics->getRecoilYawScaleLMG(); pitchScale = haptics->getRecoilPitchScaleLMG(); break; + case 4: yawScale = haptics->getRecoilYawScaleSNIPER(); pitchScale = haptics->getRecoilPitchScaleSNIPER(); break; + case 5: yawScale = haptics->getRecoilYawScalePISTOL(); pitchScale = haptics->getRecoilPitchScalePISTOL(); break; + case 6: yawScale = haptics->getRecoilYawScaleLAUNCHER(); pitchScale = haptics->getRecoilPitchScaleLAUNCHER(); break; + case 7: yawScale = haptics->getRecoilYawScaleSMG(); pitchScale = haptics->getRecoilPitchScaleSMG(); break; + case 8: yawScale = haptics->getRecoilYawScaleSHOTGUN(); pitchScale = haptics->getRecoilPitchScaleSHOTGUN(); break; + case 9: yawScale = haptics->getRecoilYawScaleKNIFE(); pitchScale = haptics->getRecoilPitchScaleKNIFE(); break; + case 10: yawScale = haptics->getRecoilYawScaleDROP(); pitchScale = haptics->getRecoilPitchScaleDROP(); break; + case 11: yawScale = haptics->getRecoilYawScaleTHROWN(); pitchScale = haptics->getRecoilPitchScaleTHROWN(); break; + case 12: yawScale = haptics->getRecoilYawScaleDEFIB(); pitchScale = haptics->getRecoilPitchScaleDEFIB(); break; + default: yawScale = 0.0f; pitchScale = 0.0f; break; + } + float x = yawDelta; + if (haptics->getForceCapX() < static_cast(std::fabs(yawDelta))) + x = hapticSignF(yawDelta) * haptics->getForceCapX(); + float y = pitchRecoil; + if (haptics->getForceCapY() < static_cast(std::fabs(pitchRecoil))) + y = hapticSignF(pitchRecoil) * haptics->getForceCapY(); + // Retail multiplies on the x87 stack and stores doubles; float products are exact in double. + const double fx = static_cast(yawScale) * x; + const double fy = -(static_cast(pitchScale) * y); + force = NovintHFX::Vect3(fx, fy, z0); + } + recoil->SetForce(force); +#endif +} + +#if BF2_FALCON_SDK +namespace { +// One CraftPhysics effect: created once with params +0x18 = its smooth time. +void createCraftPhysicsEffect(IHapticEffect*& effect, const char* name, int smoothTime) +{ + if (effect) + return; + FalconConstantParams* params = new FalconConstantParams; + params->m_unresolved18 = smoothTime; + g_falconDevice->GetEffectStack()->CreateNewEffect("Constant", params, name, &effect); + delete params; +} +// An acceleration component capped by the force cap with its sign (0x5AF229..0x5AF2D4). +float capCraftPhysics(float value, float cap, IHapticSettings* haptics, float (IHapticSettings::*getCap)()) +{ + if (cap < static_cast(std::fabs(value))) + return hapticSignF(value) * (haptics->*getCap)(); + return value; +} +} // namespace +#endif + +#if BF2_FALCON_SDK +namespace { +// One HapticSettings physics block (SOLDIER, LAND, SEA, AIR, HELI share the layout, 0xC8 apart). +struct CraftPhysicsProfile { + Vec3 (IHapticSettings::*scale)(); + float (IHapticSettings::*x[3])(); // Low, Med, High + float (IHapticSettings::*y[3])(); + float (IHapticSettings::*z[3])(); + float (IHapticSettings::*transitionMed)(); + float (IHapticSettings::*transitionHigh)(); + int (IHapticSettings::*smoothX[3])(); + int (IHapticSettings::*smoothY[3])(); + int (IHapticSettings::*smoothZ[3])(); +}; +#define BF2_CRAFT_PROFILE(C) { &IHapticSettings::getPhysics##C##Scale, \ + { &IHapticSettings::getPhysics##C##ScaleXLow, &IHapticSettings::getPhysics##C##ScaleXMed, &IHapticSettings::getPhysics##C##ScaleXHigh }, \ + { &IHapticSettings::getPhysics##C##ScaleYLow, &IHapticSettings::getPhysics##C##ScaleYMed, &IHapticSettings::getPhysics##C##ScaleYHigh }, \ + { &IHapticSettings::getPhysics##C##ScaleZLow, &IHapticSettings::getPhysics##C##ScaleZMed, &IHapticSettings::getPhysics##C##ScaleZHigh }, \ + &IHapticSettings::getPhysics##C##TransitionValueMed, &IHapticSettings::getPhysics##C##TransitionValueHigh, \ + { &IHapticSettings::getPhysics##C##SmoothTimeXLow, &IHapticSettings::getPhysics##C##SmoothTimeXMed, &IHapticSettings::getPhysics##C##SmoothTimeXHigh }, \ + { &IHapticSettings::getPhysics##C##SmoothTimeYLow, &IHapticSettings::getPhysics##C##SmoothTimeYMed, &IHapticSettings::getPhysics##C##SmoothTimeYHigh }, \ + { &IHapticSettings::getPhysics##C##SmoothTimeZLow, &IHapticSettings::getPhysics##C##SmoothTimeZMed, &IHapticSettings::getPhysics##C##SmoothTimeZHigh } } +const CraftPhysicsProfile kSoldierProfile = BF2_CRAFT_PROFILE(SOLDIER); +const CraftPhysicsProfile kLandProfile = BF2_CRAFT_PROFILE(LAND); +const CraftPhysicsProfile kSeaProfile = BF2_CRAFT_PROFILE(SEA); +const CraftPhysicsProfile kAirProfile = BF2_CRAFT_PROFILE(AIR); +const CraftPhysicsProfile kHeliProfile = BF2_CRAFT_PROFILE(HELI); +#undef BF2_CRAFT_PROFILE + +// The CraftPhysics core shared by Soldier::handlePlayerInput (0x5AED77..0x5AF3F6) and +// PlayerControlObject::handleUpdate (0x5FADAE..0x5FBCD8). The soldier's block takes the Low smooth +// times in every band; the vehicle's takes the band's own. +void craftPhysicsForce(std::vector& velocities, std::vector& tickTimes, const Vec3& localVelocity, + float dt, const CraftPhysicsProfile& profile, bool smoothTimesByBand) +{ + Vec3 acceleration; + acceleration.x = acceleration.y = acceleration.z = 0.0f; + if (velocities.size() < 3) { + velocities.push_back(localVelocity); + tickTimes.push_back(dt); + } else { + velocities.erase(velocities.begin()); + velocities.push_back(localVelocity); + tickTimes.erase(tickTimes.begin()); + tickTimes.push_back(dt); + const float span = tickTimes[1] + tickTimes[2]; + const Vec3& oldest = velocities.front(); + const Vec3& newest = velocities.back(); + const float dx = oldest.x - newest.x, dy = oldest.y - newest.y, dz = oldest.z - newest.z; + // 0x5A6370 keeps 1 / span on the x87 stack for z and stores it rounded for x and y. + const double inverse = 1.0 / static_cast(span); + const float inverseRounded = static_cast(inverse); + acceleration.x = inverseRounded * dx; + acceleration.y = inverseRounded * dy; + acceleration.z = static_cast(inverse * dz); + } + const double ax = acceleration.x, ay = acceleration.y, az = acceleration.z; + const float length = static_cast(std::sqrt(ax * ax + ay * ay + az * az)); + + IHapticSettings* haptics = static_cast(g_hapticSettings); + int band; + if ((haptics->*profile.transitionMed)() > length) + band = 0; + else if ((haptics->*profile.transitionHigh)() > length) + band = 1; + else + band = 2; + const float sx = (haptics->*profile.x[band])() * (haptics->*profile.scale)().x; + const float sy = (haptics->*profile.y[band])() * (haptics->*profile.scale)().y; + const float sz = (haptics->*profile.z[band])() * (haptics->*profile.scale)().z; + const int smoothBand = smoothTimesByBand ? band : 0; + const int smoothX = (haptics->*profile.smoothX[smoothBand])(); + const int smoothY = (haptics->*profile.smoothY[smoothBand])(); + const int smoothZ = (haptics->*profile.smoothZ[smoothBand])(); + + IHapticEffect*& effectX = g_hapticForceTargets[3]; // ds:0x9EBF04 + IHapticEffect*& effectY = g_hapticForceTargets[4]; // ds:0x9EBF08 + IHapticEffect*& effectZ = g_hapticForceTargets[5]; // ds:0x9EBF0C + createCraftPhysicsEffect(effectX, "CraftPhysicsX", smoothX); + createCraftPhysicsEffect(effectY, "CraftPhysicsY", smoothY); + createCraftPhysicsEffect(effectZ, "CraftPhysicsZ", smoothZ); + + const double zero = 0.0; + NovintHFX::Vect3 force(zero, zero, zero); + const float cx = capCraftPhysics(acceleration.x, haptics->getForceCapX(), haptics, &IHapticSettings::getForceCapX); + const float cy = capCraftPhysics(acceleration.y, haptics->getForceCapY(), haptics, &IHapticSettings::getForceCapY); + const float cz = capCraftPhysics(acceleration.z, haptics->getForceCapZ(), haptics, &IHapticSettings::getForceCapZ); + // Retail multiplies on the x87 stack and stores doubles; float products are exact in double. + const double fx = -(static_cast(sx) * cx); + force = NovintHFX::Vect3(fx, zero, zero); + effectX->SetSmoothTime(smoothX); + effectX->SetForce(force); + const double fy = -(static_cast(sy) * cy); + force = NovintHFX::Vect3(zero, fy, zero); + effectY->SetSmoothTime(smoothY); + effectY->SetForce(force); + const double fz = static_cast(sz) * cz; + force = NovintHFX::Vect3(zero, zero, fz); + effectZ->SetSmoothTime(smoothZ); + effectZ->SetForce(force); +} +} // namespace +#endif + +void updateSoldierCraftPhysicsForce(const Vec3& localVelocity, float dt) +{ +#if !BF2_FALCON_SDK + (void) localVelocity; (void) dt; +#else + static std::vector velocities; // ds:0x9EC550 (guard bit 2 of ds:0x9EC560) + static std::vector tickTimes; // ds:0x9EC540 (guard bit 1) + craftPhysicsForce(velocities, tickTimes, localVelocity, dt, kSoldierProfile, false); +#endif +} + +void updateVehicleCraftPhysicsForce(const Vec3& localVelocity, float dt, int vehicleCategory) +{ +#if !BF2_FALCON_SDK + (void) localVelocity; (void) dt; (void) vehicleCategory; +#else + static std::vector velocities; // ds:0x9F06BC (guard bit 1 of ds:0x9F06CC) + static std::vector tickTimes; // ds:0x9F06AC (guard bit 2) + const CraftPhysicsProfile* profile; + switch (vehicleCategory) { // the jump table at 0x5FBE40 + case 1: profile = &kSeaProfile; break; + case 2: profile = &kAirProfile; break; + case 3: profile = &kHeliProfile; break; + default: profile = &kLandProfile; break; // 0 and every other value (0x5FB75C) + } + craftPhysicsForce(velocities, tickTimes, localVelocity, dt, *profile, true); +#endif +} + +void fireRecoilPunch(float punchTime, float punchScale, float fireStrength) +{ +#if !BF2_FALCON_SDK + (void) punchTime; (void) punchScale; (void) fireStrength; +#else + FalconEnvelopeParams* params = new FalconEnvelopeParams; + params->m_unresolved18 = static_cast(punchTime); // fistp with truncation + IHapticSettings* haptics = static_cast(g_hapticSettings); + const float strength = static_cast(std::fabs(fireStrength)); + if (haptics->getForceCapZ() < strength) + params->m_force[2] = static_cast(haptics->getForceCapZ()) * punchScale; + else + params->m_force[2] = static_cast(punchScale) * fireStrength; + g_falconDevice->GetEffectStack()->CreateNewEffect("Envelope", params, "RecoilPunch", 0); + delete params; +#endif +} + +void weaponRecoilPunch(int weaponType, const std::string& templateName, float cameraRecoilSpeed, + float cameraRecoilSize, float fireStrength) +{ +#if !BF2_FALCON_SDK + (void) weaponType; (void) templateName; (void) cameraRecoilSpeed; (void) cameraRecoilSize; (void) fireStrength; +#else + IHapticSettings* haptics = static_cast(g_hapticSettings); + float punchTime, punchScale; + switch (weaponType - 13) { // the jump table at 0x60A5C0 +#define BF2_V_RECOIL(n, type) \ + case n: \ + punchTime = haptics->getRecoilPunchTime##type(); \ + punchScale = haptics->getRecoilPunchScale##type(); \ + haptics->setUnresolved48C(haptics->getRecoilYawScale##type()); \ + haptics->setUnresolved490(haptics->getRecoilPitchScale##type()); \ + break; + BF2_V_RECOIL(0, V_LMG) + BF2_V_RECOIL(1, V_HMG) + BF2_V_RECOIL(2, V_HELIGUN) + BF2_V_RECOIL(3, V_AIRGUN) + BF2_V_RECOIL(4, V_MISSILE) + BF2_V_RECOIL(5, V_ARMORCANNON) + BF2_V_RECOIL(6, V_COAXIALGUN) +#undef BF2_V_RECOIL + default: { + std::string name(templateName); + for (std::size_t i = 0; i < name.size(); ++i) + name[i] = static_cast(std::tolower(name[i])); + if (name.find("firingport", 0, 10) != std::string::npos) { + punchTime = haptics->getRecoilPunchTimeRIFLE(); + punchScale = haptics->getRecoilPunchScaleRIFLE(); + haptics->setUnresolved48C(haptics->getRecoilYawScaleRIFLE()); + haptics->setUnresolved490(haptics->getRecoilPitchScaleRIFLE()); + } else { + punchTime = 1.0f; + punchScale = 0.0f; + haptics->setUnresolved48C(0.0f); + haptics->setUnresolved490(0.0f); + } + break; + } + } + punchScale = punchScale * cameraRecoilSize; + punchTime = punchTime * cameraRecoilSpeed; + fireRecoilPunch(punchTime, punchScale, fireStrength); +#endif +} + +void kitRecoilPunch(int weaponType, const std::string& templateName, float fireStrength) +{ +#if !BF2_FALCON_SDK + (void) weaponType; (void) templateName; (void) fireStrength; +#else + IHapticSettings* haptics = static_cast(g_hapticSettings); + float punchTime, punchScale; + switch (weaponType - 9) { // the jump table at 0x5E2E90 + case 0: punchTime = haptics->getRecoilPunchTimeKNIFE(); punchScale = haptics->getRecoilPunchScaleKNIFE(); break; + case 1: punchTime = haptics->getRecoilPunchTimeDROP(); punchScale = haptics->getRecoilPunchScaleDROP(); break; + case 2: punchTime = haptics->getRecoilPunchTimeTHROWN(); punchScale = haptics->getRecoilPunchScaleTHROWN(); break; + case 3: punchTime = haptics->getRecoilPunchTimeDEFIB(); punchScale = haptics->getRecoilPunchScaleDEFIB(); break; + default: { + std::string name(templateName); + for (std::size_t i = 0; i < name.size(); ++i) + name[i] = static_cast(std::tolower(name[i])); + if (name.find("kit", 0, 3) != std::string::npos || name.find("wrench", 0, 6) != std::string::npos) { + punchTime = haptics->getRecoilPunchTimeDROP(); + punchScale = haptics->getRecoilPunchScaleDROP(); + } else { + punchTime = 1.0f; + punchScale = 0.0f; + } + break; + } + } + fireRecoilPunch(punchTime, punchScale, fireStrength); +#endif +} + +void soldierRecoilPunch(int weaponType, bool hasRandomRecoilForce, unsigned int recoilSamples, const float* lastSample, + float forceUpValue, float forceUpVariation, float forceModifier, float fireStrength) +{ +#if !BF2_FALCON_SDK + (void) weaponType; (void) hasRandomRecoilForce; (void) recoilSamples; (void) lastSample; + (void) forceUpValue; (void) forceUpVariation; (void) forceModifier; (void) fireStrength; +#else + IHapticSettings* haptics = static_cast(g_hapticSettings); + float punchTime, punchScale; + switch (weaponType) { // the jump table at 0x60969C + case 0: punchTime = haptics->getRecoilPunchTimeRIFLE(); punchScale = haptics->getRecoilPunchScaleRIFLE(); break; + case 1: punchTime = haptics->getRecoilPunchTimeRIFLELAUNCHER(); punchScale = haptics->getRecoilPunchScaleRIFLELAUNCHER(); break; + case 2: punchTime = haptics->getRecoilPunchTimeCARBINE(); punchScale = haptics->getRecoilPunchScaleCARBINE(); break; + case 3: punchTime = haptics->getRecoilPunchTimeLMG(); punchScale = haptics->getRecoilPunchScaleLMG(); break; + case 4: punchTime = haptics->getRecoilPunchTimeSNIPER(); punchScale = haptics->getRecoilPunchScaleSNIPER(); break; + case 6: punchTime = haptics->getRecoilPunchTimeLAUNCHER(); punchScale = haptics->getRecoilPunchScaleLAUNCHER(); break; + case 7: punchTime = haptics->getRecoilPunchTimeSMG(); punchScale = haptics->getRecoilPunchScaleSMG(); break; + case 8: punchTime = haptics->getRecoilPunchTimeSHOTGUN(); punchScale = haptics->getRecoilPunchScaleSHOTGUN(); break; + case 9: punchTime = haptics->getRecoilPunchTimeKNIFE(); punchScale = haptics->getRecoilPunchScaleKNIFE(); break; + case 10: punchTime = haptics->getRecoilPunchTimeDROP(); punchScale = haptics->getRecoilPunchScaleDROP(); break; + case 11: punchTime = haptics->getRecoilPunchTimeTHROWN(); punchScale = haptics->getRecoilPunchScaleTHROWN(); break; + case 12: punchTime = haptics->getRecoilPunchTimeDEFIB(); punchScale = haptics->getRecoilPunchScaleDEFIB(); break; + default: punchTime = haptics->getRecoilPunchTimePISTOL(); punchScale = haptics->getRecoilPunchScalePISTOL(); break; + } + if (hasRandomRecoilForce) { + punchTime = static_cast(recoilSamples) * punchTime; + // x87: ((variation + value) * 0.5) * modifier * last, negated, times the scale; one rounding. + punchScale = static_cast(-(((static_cast(forceUpVariation) + forceUpValue) * 0.5) + * forceModifier * *lastSample) * punchScale); + } + fireRecoilPunch(punchTime, punchScale, fireStrength); +#endif +} + +void updateDamageForce(world::IPlayer* victim, world::IPlayer* localPlayer, const Mat4& lookAt, + const Mat4& ownerTransform, float damage) +{ +#if !BF2_FALCON_SDK + (void) victim; (void) localPlayer; (void) lookAt; (void) ownerTransform; (void) damage; +#else + // The forward row in the owner's frame, accumulated on the x87 stack in retail's order. + const double fx = lookAt.m[8], fy = lookAt.m[9], fz = lookAt.m[10]; + const Mat4& o = ownerTransform; + const float c = static_cast(fy * o.m[9] + fz * o.m[10] + fx * o.m[8]); + const float a = static_cast(fy * o.m[1] + fz * o.m[2] + fx * o.m[0]); + const float b = static_cast(fy * o.m[5] + fz * o.m[6] + fx * o.m[4]); + if (victim != localPlayer || !g_falconDevice) + return; + FalconEnvelopeParams* params = new FalconEnvelopeParams; + params->m_unresolved18 = 100; + IHapticSettings* haptics = static_cast(g_hapticSettings); + const double magnitude = static_cast(haptics->getDamageScale()) * damage * 0.5; + const double x = -static_cast(a), y = b, z = c; + NovintHFX::Vect3 force = NovintHFX::Vect3(x, y, z).Normalize() * magnitude; + params->m_force[0] = force[0]; + params->m_force[1] = force[1]; + params->m_force[2] = force[2]; + g_falconDevice->GetEffectStack()->CreateNewEffect("Envelope", params, "Damage", 0); + delete params; +#endif +} + +// PE 0x6A52A0. Consumes the samples update(0) queued that are older than the advanced sample +// clock: smoothed position deltas, the mouse or control-box mode, then the button state. +void FalconDevice::updateCurrentState(float dt) +{ +#if !BF2_FALCON_SDK + // x64: unreachable (update() returns while m_device is null, and it always is). + (void) dt; +#else + IControlMap* map = static_cast(controlMapManager)->getActive(); + m_axes[2] = 0.0; + m_axes[1] = 0.0; + m_axes[0] = 0.0; + m_previousButtons = m_buttons; + m_sampleTime += bf2x87::toIntTruncate(static_cast(dt) * 1000.0); + IHapticSettings* haptics = static_cast(g_hapticSettings); + while (!m_samples.empty()) { + FalconInputFormat& sample = m_samples.front(); + if (sample.time >= m_sampleTime) break; + inputSampleLatency = static_cast( + static_cast(static_cast(m_pollTime - sample.time)) + * static_cast(0.001f)); + const double x = sample.position[0]; + const double y = map && map->getInvertMouse() ? -sample.position[1] : sample.position[1]; + const double z = map && map->getInvertMouse() ? -sample.position[2] : sample.position[2]; + static std::deque historyX; + static std::deque historyY; + static std::deque historyZ; + double deltaX = 0.0, deltaY = 0.0, deltaZ = 0.0; + if (s_smoothingCount < s_smoothingWindow) { + historyX.push_back(x); + historyY.push_back(y); + historyZ.push_back(z); + ++s_smoothingCount; + } else if (s_smoothingCount == s_smoothingWindow) { + deltaX = windowDelta(historyX, x * component(haptics->getAimSensitivity(), 0)); + deltaY = windowDelta(historyY, y * component(haptics->getAimSensitivity(), 1)); + deltaZ = windowDelta(historyZ, z * component(haptics->getAimSensitivity(), 2)); + } else { + popFrontIfAny(historyX); + popFrontIfAny(historyY); + popFrontIfAny(historyZ); + --s_smoothingCount; + } + // While a binding is being captured the frame ends here: the sample stays queued and + // the axis scaling below is skipped (0x6A57CE -> 0x6A5C7B). + if (static_cast(g_controlSettings)->isMappingInput()) return; + if (g_falconMouseMode > 0 && isActive()) { + m_axes[0] = s_falconMouseGain * x; + m_axes[1] = -(s_falconMouseGain * y); + if (g_falconMouseMode == 1) { + m_haptics->StartMouse(m_device); + g_falconMouseMode = 2; + if (s_controlBoxEffect && !(s_controlBoxEffect->m_stateFlags & 1)) + s_controlBoxEffect->m_stateFlags |= 1; + } + } + if (g_falconMouseMode < 1 && isActive()) { + bool rebuild = false; + if (g_falconMouseMode == 0) { + g_falconMouseMode = -1; + rebuild = true; + } else if (g_falconControlBoxDirty) { + rebuild = true; + } + if (rebuild) { + g_falconControlBoxDirty = false; + FalconControlBoxParams* params = new FalconControlBoxParams; + for (int i = 0; i < 3; ++i) { + // The vertical walls sit 0.01 lower than the configured length. + const float lowerOffset = i == 2 ? 0.01f : 0.0f; + params->m_lower[i] = -static_cast(component(haptics->getControlBoxLength(), i)) + - static_cast(lowerOffset); + params->m_lowerStiffness[i] = component(haptics->getControlBoxStiffness(), i); + const float upperOffset = i == 2 ? 0.01f : 0.0f; + params->m_upper[i] = static_cast(component(haptics->getControlBoxLength(), i)) + - static_cast(upperOffset); + params->m_upperStiffness[i] = component(haptics->getControlBoxStiffness(), i); + } + params->m_unresolved114 = s_controlBoxForceValue; + if (!s_controlBoxEffect) + g_falconDevice->GetEffectStack()->CreateNewEffect("BOX", params, "ControlBox", + &s_controlBoxEffect); + s_controlBoxEffect->UpdateParams(params); + if (s_controlBoxEffect->m_stateFlags & 1) s_controlBoxEffect->m_stateFlags &= ~1; + delete params; + } + m_axes[0] = axisValue(haptics, 0, x, deltaX, 2000.0, 2500.0); + m_axes[1] = axisValue(haptics, 1, y, deltaY, -2000.0, -2500.0); + m_axes[2] = axisValue(haptics, 2, z, deltaZ, -2000.0, -2500.0); + } + int pressed, released; + m_device->GetButtonData(reinterpret_cast(&sample.buttons), &pressed, &released); + m_buttons = sample.buttons; + m_samples.pop_front(); + } + // Retail scales four doubles from +0x18; the fourth is the bytes of m_axisTravel[0..1]. + // The active map is not null-tested here. + for (int i = 0; i < 3; ++i) + m_axes[i] *= map->getAxisScale(static_cast(i)); + double fourth; + std::memcpy(&fourth, m_axisTravel, sizeof(fourth)); + fourth *= map->getAxisScale(static_cast(3)); + std::memcpy(m_axisTravel, &fourth, sizeof(fourth)); +#endif +} +namespace { +FalconInputFormat inputBuffer[1]; // PE 0xA03918, static polling buffer +const float lowerTravel[3] = { -0.0025f, -0.0025f, -0.001f }; +const float upperTravel[3] = { 0.0025f, 0.0025f, 0.001f }; +} +FalconDevice::FalconDevice() + : m_refCount(1), m_active(false), m_pollTime(0), +#if BF2_FALCON_SDK + m_haptics(&Haptics), +#else + m_haptics(0), +#endif + m_device(0) +{ +#if defined(_M_IX86) + static_assert(offsetof(FalconDevice, m_samples) == 0xE4, "x86 scalar prefix"); +#endif + static_assert(sizeof(FalconInputFormat) == 40, "x86 input sample alignment"); + m_field100 = 0; + g_falconDevice = 0; + m_buttons = 0; + m_previousButtons = 0; + for (int i = 0; i < 3; ++i) { + m_axisScale[i] = 1.0f; + m_axes[i] = 0.0; + m_invertAxis[i] = false; + m_axisTravel[i] = 0; + } + m_field0fc = false; + m_field0f0 = 0; + m_field0f4 = 0; + m_field0f8 = 0; +} +FalconDevice::~FalconDevice() +{ +#if BF2_FALCON_SDK + if (m_device) { + m_haptics->StopRunningDevice(&m_device); + m_haptics = 0; + g_falconDevice = 0; + m_device = 0; + } +#endif +} +void FalconDevice::addRef() { ++m_refCount; } +int FalconDevice::getRef() { return m_refCount; } +int FalconDevice::release() +{ + const int refs = --m_refCount; + if (!refs) delete this; + return refs; +} +void* FalconDevice::queryInterface(unsigned int iid) const +{ + return iid == IID_IBase || iid == IID_IInputDevice || iid == IID_IAdvancedInputDevice + ? const_cast(this) : 0; +} +InputDeviceTypes FalconDevice::getType() const { return IDTFalcon; } +bool FalconDevice::setCooperativeMode(InputDeviceMode mode) { m_mode = mode; return true; } +InputDeviceMode FalconDevice::getCooperativeMode() const { return m_mode; } +bool FalconDevice::activate() +{ + if (!m_device) return false; + if (!m_active) m_active = true; + return true; +} +bool FalconDevice::deActivate() +{ + // Retail intentionally does not clear m_active or stop the device here. + return m_device != 0; +} +bool FalconDevice::isActive() const { return m_device && m_active; } +int FalconDevice::getNumAxes() const { return m_numAxes; } +int FalconDevice::getNumButtons() const { return m_numButtons; } +float FalconDevice::readAxis(InputDeviceAxes axis, bool) const +{ + // The scaling argument and configured scale are ignored by this body. + return static_cast(m_invertAxis[axis] ? -m_axes[axis] : m_axes[axis]); +} +void FalconDevice::setInvertAxis(InputDeviceAxes axis, bool invert) +{ + if (axis <= m_numAxes) m_invertAxis[axis] = invert; +} +bool FalconDevice::getInvertAxis(InputDeviceAxes axis) const +{ + return axis <= m_numAxes ? m_invertAxis[axis] : false; +} +void FalconDevice::setAxisScale(InputDeviceAxes axis, float scale) +{ + if (axis <= m_numAxes) m_axisScale[axis] = scale; +} +float FalconDevice::getAxisScale(InputDeviceAxes axis) const +{ + return axis <= m_numAxes ? m_axisScale[axis] : 0.0f; +} +// These no-op/zero bodies are present in both binaries, not frontier substitutes. +void FalconDevice::setAxisAdd(InputDeviceAxes, float) {} +float FalconDevice::getAxisAdd(InputDeviceAxes) const { return 0.0f; } +bool FalconDevice::buttonDown(InputDeviceButtons button) const { return (m_buttons & button) != 0; } +bool FalconDevice::buttonPressed(InputDeviceButtons button) const +{ + return !(m_previousButtons & button) && (m_buttons & button); +} +bool FalconDevice::buttonReleased(InputDeviceButtons button) const +{ + return (m_previousButtons & button) && !(m_buttons & button); +} +float FalconDevice::buttonPressedSampleLatency(InputDeviceButtons button) const +{ + for (unsigned int i = 0; i < 32; ++i) + if (static_cast(button) & (1u << i)) return m_buttonLatency[i]; + return 0.0f; +} +bool FalconDevice::init() +{ + if (!inputDeviceManager) return false; +#if !BF2_FALCON_SDK + std::fprintf(stderr, "[x64] dice::hfe::io::FalconDevice::init: no 64-bit NovintHFX SDK; " + "the Falcon is reported as not connected\n"); + std::fflush(stderr); + return false; +#else + const HWND window = GetForegroundWindow(); + NovintHFX::ApplicationData application; + application.window = window; + bool active = false; + if (m_haptics->AttachApplication(application)) { + m_haptics->RecountConnectedDevices(); + if (m_haptics->ConnectedDeviceCount() < 1) return false; + active = m_haptics->RunDevice(&m_device, 0); + g_falconDevice = m_device; + m_haptics->StartMouse(m_device); + } + m_active = active; + m_numAxes = 3; + m_numButtons = 4; + // AttachApplication failure still returns true; zero devices returns false. + return true; +#endif +} +bool FalconDevice::getNextInput(InputDeviceAxes& axis, InputDeviceButtons& button, + InputDeviceKeys& key, bool& negative) +{ + if (!m_active) return false; + if (!m_device) return false; +#if BF2_FALCON_SDK + m_device->InputUpdate(); + int buttons, pressed, released; + m_device->GetButtonData(&buttons, &pressed, &released); + for (unsigned int i = 0; i < m_numButtons; ++i) { + if (static_cast(buttons) & (1u << i)) { + axis = static_cast(15); + button = static_cast(1u << i); + key = static_cast(0); + return true; // negative output deliberately untouched for buttons + } + } + double position[3]; + m_device->GetToolPosition(position); + for (int i = 0; i < m_numAxes; ++i) { + int& travel = m_axisTravel[i]; + if (lowerTravel[i] > position[i]) { + if (!travel) travel = 1; + else if (travel == 2) travel = 3; + } + if (upperTravel[i] < position[i]) { + if (!travel) { travel = 2; continue; } + if (travel == 1) travel = 3; + } + if (travel == 3) { + for (int j = 0; j < m_numAxes; ++j) m_axisTravel[j] = 0; + axis = static_cast(i); + button = static_cast(0); + key = static_cast(0); + negative = m_axes[i] < 0.0; + return true; + } + } +#endif + return false; +} +void FalconDevice::update(float dt) +{ + if (!m_active || !m_device) return; + if (dt > 0.0f) { + updateCurrentState(dt); + return; + } +#if BF2_FALCON_SDK + if (m_samples.size() > 256) m_samples.clear(); + m_haptics->InputUpdate(); + double position[3]; + m_device->GetToolPosition(position); + inputBuffer[0].position[0] = position[0]; + inputBuffer[0].position[1] = position[1]; + inputBuffer[0].position[2] = position[2]; + int pressed, released; + m_device->GetButtonData(reinterpret_cast(&inputBuffer[0].buttons), &pressed, &released); + inputBuffer[0].time = GetTickCount(); + m_sampleTime = m_pollTime; + m_pollTime = GetTickCount(); + for (unsigned int i = 0; i < 1; ++i) m_samples.push_back(inputBuffer[i]); +#endif +} +} } } +#endif diff --git a/Code/BF2/IO/Input/FalconDevice.h b/Code/Archive/NovintFalcon/IO/Input/FalconDevice.h similarity index 75% rename from Code/BF2/IO/Input/FalconDevice.h rename to Code/Archive/NovintFalcon/IO/Input/FalconDevice.h index eb39cc58f..d12383f6e 100644 --- a/Code/BF2/IO/Input/FalconDevice.h +++ b/Code/Archive/NovintFalcon/IO/Input/FalconDevice.h @@ -1,8 +1,21 @@ // Falcon input device. [INFERRED] Header placement. Preserve its 27-slot interface without a destructor slot. +// BF2_NOVINT_FAKE_SDK: the Mac fake-SDK check compiles the Windows class against fake SDK bodies. #ifndef IO_INPUT_FALCONDEVICE_H #define IO_INPUT_FALCONDEVICE_H #include "../../Core/BuildConfig.h" #if !DEDICATED +#include "FalconHaptics.h" // g_falconControlBoxDirty and the haptic-effect helpers (ledger N2) +class IHapticEffect; // NovintHFX.h (global namespace); the haptic force effects (BF2ClientSeams.h) +#if !defined(_WIN32) && !defined(BF2_NOVINT_FAKE_SDK) +// [CHOSEN, not recovered] Native POSIX clients: the Novint HFX SDK is a Windows-only DLL and no +// Falcon is ever present, so neither the SDK header nor FalconDevice exists there; the device +// manager reports IDFFalcon as not opened (MacInputDeviceManager). Only the menu's mouse-mode +// global, which the menu and HUD code write on every platform, is declared. See +// docs/macos-port.md, "Bink, Novint and VoIP capture (S2.8)". +namespace dice { namespace hfe { namespace io { +extern int g_falconMouseMode; // [INFERRED] name, PE978FC4 initialized1; HUD/updateCurrentState writers +} } } +#else #include "Input.h" #include "../../External/NovintHFX/NovintHFX.h" #include @@ -47,9 +60,8 @@ class FalconDevice : public IAdvancedInputDevice { float buttonPressedSampleLatency(InputDeviceButtons) const override; virtual bool init(); private: - // [FRONTIER] PE 0x6A52A0, ELF 0x8499C80; positive-dt frame update. - // Required HapticSettings/effect interfaces are not yet recovered. - void updateCurrentState(float); // [TEMP] diagnostic abort; falcon-state-diagnostic + // PE 0x6A52A0, ELF 0x8499C80 (whose sample loop is compiled out); positive-dt frame update. + void updateCurrentState(float); int m_refCount; // PE +04 unsigned int m_buttons; // +08 InputDeviceMode m_mode; // +0C; ctor leaves untouched @@ -71,5 +83,6 @@ class FalconDevice : public IAdvancedInputDevice { DWORD m_field100; // [UNRESOLVED] initialized zero }; } } } +#endif // _WIN32 #endif #endif diff --git a/Code/Archive/NovintFalcon/IO/Input/FalconHaptics.h b/Code/Archive/NovintFalcon/IO/Input/FalconHaptics.h new file mode 100644 index 000000000..9e6208c85 --- /dev/null +++ b/Code/Archive/NovintFalcon/IO/Input/FalconHaptics.h @@ -0,0 +1,96 @@ +// The game-facing half of the Falcon device (ledger N2): the control-box flag and the haptic-effect +// helpers the game code calls. [CHOSEN, not recovered] Split from FalconDevice.h so that game TUs do not +// see NovintHFX.h, which includes (its min/max macros broke Soldier.cpp's std::min/max on +// MSVC). The bodies are in FalconDevice.cpp; on POSIX clients and without a device they do nothing. +#ifndef IO_INPUT_FALCONHAPTICS_H +#define IO_INPUT_FALCONHAPTICS_H +#include "../../Core/BuildConfig.h" +#if !DEDICATED +#include "../../Math/Vec3.h" +#include "../../Math/Mat4.h" +#include +namespace dice { namespace hfe { namespace world { class IPlayerControlObject; class IPlayer; } } } +namespace dice { namespace hfe { namespace io { +// [INFERRED] name, PE978FC8 initialized true. updateCurrentState rebuilds the control-box effect +// from HapticSettings when it is set and clears it; the haptic-effect sites 0x5AB83A, 0x5AC90B and +// 0x5ADD98 (ledger N2) set it. +extern bool g_falconControlBoxDirty; +// MainMenuLogic::activate 0x4A3490..0x4A3535 (inline in retail): one NovintHFX::Vect3(0, 0, 0), then +// each non-null haptic force effect's +0x4C in retail's order 0x9EBF00, F04, F08, F0C, EC8, ECC. +// [CHOSEN, not recovered] Out of line here because MainMenuLogic builds on every platform and the +// SDK declarations are Windows-only. +void zeroHapticForceTargets(); +// Camera::handleUpdate's Novint block (BF2.exe 0x5A3F4F..0x5A41D7, ledger N2 17b), for the local +// occupant's camera. With a device: create the two CONSTANT "ShakeForce" effects (ds:0x9EBEC8/CC) once, +// then each frame set Vect3(x, y, 0) on the soldier's (CC) or the vehicle's (C8) from the camera's +// shake terms scaled by HapticSettings (+0x7DC explosion, +0x7E4 speed, +0x7D4 general on the +// close-vehicle pitch, +0x7C4 / +0x7CC on the recoil), each axis capped by the force cap with its sign. +// The soldier test is the occupied object's template class id (pco -> IID_IObject -> +0x14 -> +0x10). +// [CHOSEN, not recovered] Out of line here for the same reason as zeroHapticForceTargets. +void updateShakeForce(world::IPlayerControlObject* pco, float explosionRoll, float speedRoll, + float closeVehiclePitch, float recoilY); +// g_falconDevice != 0 (false on POSIX clients), for callers that build on every platform. +// [CHOSEN, not recovered] +bool hapticDeviceConnected(); +// Soldier::handlePlayerInput's "Recoil" block (BF2.exe 0x5AE335..0x5AE72B, ledger N2 17b), for the +// local occupant while a device is connected: create the Constant "Recoil" effect (ds:0x9EBF00) once +// (params +0x18 = 10), then set it every tick. Zero unless the yaw delta (recoil plus look) or the +// raw pitch recoil is non-zero; otherwise Vect3(yawScale * x, -(pitchScale * y), 0), where x and y are +// those two values capped by the force caps with their sign (0x5A6280) and the scales are +// HapticSettings' recoil yaw / pitch scales for the weapon type (0 RIFLE .. 12 DEFIB, else 0). +// [CHOSEN, not recovered] Out of line, as zeroHapticForceTargets. +void updateRecoilForce(float yawDelta, float pitchRecoil, int weaponType); +// Soldier::handlePlayerInput's "CraftPhysics" block (BF2.exe 0x5AECE8..0x5AF3F6, ledger N2 17b), after +// setRotationalSpeed, for the local occupant while a device is connected. The soldier's velocity in +// its vehicle's frame goes into static three-entry histories (velocities ds:0x9EC550, tick times +// ds:0x9EC540); once full, the acceleration is (oldest - newest) * (1 / (the last two tick times)), +// else zero. Its length against PhysicsSOLDIERTransitionValueMed / High picks the Low, Med or High +// scales (each times PhysicsSOLDIERScale's component). The three Constant effects "CraftPhysicsX/Y/Z" +// (ds:0x9EBF04/08/0C) are created once with params +0x18 = PhysicsSOLDIERSmoothTimeX/Y/ZLow (Low in +// every band, as shipped); each tick each gets SetSmoothTime(that value) and a force along its own +// axis: -(sx * ax), -(sy * ay), +(sz * az), each acceleration component first capped by the force cap +// with its sign. [CHOSEN, not recovered] Out of line, as zeroHapticForceTargets. +void updateSoldierCraftPhysicsForce(const Vec3& localVelocity, float dt); +// PlayerControlObject::handleUpdate's "CraftPhysics" block (BF2.exe 0x5FADAE..0x5FBCD8, ledger N2 17b): +// the same core with its own histories (ds:0x9F06BC velocities, ds:0x9F06AC tick times) and the +// HapticSettings block of the vehicle category (jump table 0x5FBE40: 1 SEA, 2 AIR, 3 HELI, LAND for 0 +// and every other value); unlike the soldier's, each band takes its own smooth times. +void updateVehicleCraftPhysicsForce(const Vec3& localVelocity, float dt, int vehicleCategory); +// SoldierBasedRecoilComp::postFire's "RecoilPunch" (BF2.exe 0x609353..0x609690, ledger N2 17b), for the +// local occupant while a device is connected: punch time and scale from HapticSettings by the soldier's +// active weapon type (jump table 0x60969C: 0 RIFLE .. 12 DEFIB, but 5 and every type above 12 share the +// default, PISTOL); with a random recoil force, time *= the recoil graph's sample count and +// scale = -(((variation + value) * 0.5) * forceModifier * lastSample) * scale; then fireRecoilPunch. +// The last sample is read unchecked, as shipped. +void soldierRecoilPunch(int weaponType, bool hasRandomRecoilForce, unsigned int recoilSamples, const float* lastSample, + float forceUpValue, float forceUpVariation, float forceModifier, float fireStrength); +// The shared tail of the RecoilPunch sites (0x6095EF..0x60968A, 0x60A451..0x60A4F8): an Envelope +// params object (+0x18 = the punch time truncated, m_force[2] = capZ * scale when the fire strength's +// magnitude is above the Z force cap, as shipped without its sign, else scale * fireStrength), the +// effect "RecoilPunch" created without keeping it, the params deleted. +void fireRecoilPunch(float punchTime, float punchScale, float fireStrength); +// WeaponBasedRecoilComp::postFire's "RecoilPunch" (BF2.exe 0x60A0E7..0x60A4F8, ledger N2 17b), for the +// local occupant while a device is connected: by the firing weapon's type, 13..19 (jump table 0x60A5C0: +// V_LMG, V_HMG, V_HELIGUN, V_AIRGUN, V_MISSILE, V_ARMORCANNON, V_COAXIALGUN) take that type's punch time +// and scale and set HapticSettings +0x48C / +0x490 (the recoil scales the ShakeForce block reads) to its +// recoil yaw / pitch scale; any other type takes RIFLE's four values when the lower-cased template name +// contains "firingport", else time 1, scale 0 and both set to 0. Then scale *= cameraRecoilSize, +// time *= cameraRecoilSpeed, and fireRecoilPunch. +void weaponRecoilPunch(int weaponType, const std::string& templateName, float cameraRecoilSpeed, + float cameraRecoilSize, float fireStrength); +// GenericFireArm::postFire's "RecoilPunch" for a weapon without a recoil component (BF2.exe +// 0x5E2A98..0x5E2CDA, the else of m_recoilComp->postFire; ledger N2 17b), when the weapon's player is +// the local player and a device is connected: weapon types 9..12 (jump table 0x5E2E90: KNIFE, DROP, +// THROWN, DEFIB) take that type's punch time and scale; any other type takes DROP's when the lower-cased +// template name contains "kit" or else "wrench", otherwise time 1 and scale 0; then fireRecoilPunch. +void kitRecoilPunch(int weaponType, const std::string& templateName, float fireStrength); +// GameLogicDamage::serverGiveDamage's "Damage" envelope (BF2.exe 0x5E6566..0x5E66A2, ledger N2 17b): +// for the local victim with a device, the look-at frame's forward row (lookAt +0x20) in the damaged +// owner's frame (dot products with its rows 0, 1, 2) gives Vect3(-a, b, c), normalized and scaled by +// HapticSettings' damage scale * damage * 0.5, into an Envelope params object (+0x18 = 100, +// m_force); the effect "Damage" created without keeping it. The victim test is pointer equality. +void updateDamageForce(world::IPlayer* victim, world::IPlayer* localPlayer, const Mat4& lookAt, + const Mat4& ownerTransform, float damage); +} } } +#endif // !DEDICATED +#endif diff --git a/Code/Archive/NovintFalcon/README.md b/Code/Archive/NovintFalcon/README.md new file mode 100644 index 000000000..312ea8337 --- /dev/null +++ b/Code/Archive/NovintFalcon/README.md @@ -0,0 +1,121 @@ +# Novint Falcon (archived) + +`[CHOSEN, not recovered]` This directory keeps the reconstructed Novint Falcon support. No +image builds it. The owner decided to drop Falcon support +([issue #17](https://github.com/kr4uzi/OpenBF2/issues/17)). The code is kept as a reference +here, not deleted. Windows later shipped the x86 client again, for PunkBuster. The Falcon +stays archived there too, and the x86 client could load the 32-bit DLL again if restored (see +"Restoring"). + +## What it was + +Retail `BF2.exe` drives a Novint Falcon, a 3-DOF haptic controller, through the vendor SDK +`NovintHFX.dll`. It imports that DLL statically, so retail needs the DLL even when no Falcon +is connected. The game uses it in two ways: + +- **As an input device.** `FalconDevice` is the `IDFFalcon` device of the DirectInput device + manager (`IAdvancedInputDevice`, 27 slots, no destructor slot). It polls position and + buttons, and in menus it moves the pointer (`g_falconMouseMode`). In game it holds a + "control box" spring effect, rebuilt from `HapticSettings` whenever + `g_falconControlBoxDirty` is set. +- **As force feedback.** About 140 game-side lines create and update HFX effects: the camera + `ShakeForce`, the soldier and vehicle `CraftPhysics`, the soldier `Recoil`, the weapon, + soldier and kit `RecoilPunch`, and the `Damage` envelope. They also zero the six persistent + effects on menu entry, death, the free camera and vehicle enter/exit. + +`HapticSettings` (`Haptic.con`, the menu's force-feedback page and the profile files) is +retail profile data and is **not** archived. It still loads, saves and applies as in retail. +The Soldier's control-box profile switch (`applyHapticProfile` and `hapticProfileForEntered` +in `Game/Objects/Game/SoldierHapticProfile.cpp`) also stays, because it writes +`HapticSettings`. + +`NovintHFX.dll` exists only as a 32-bit DLL. The native x64 client +([issue #7](https://github.com/B2BF/OpenBF2/issues/7)) could never load it. The macOS and +Linux clients never had a Falcon. + +## Retail addresses (BF2.exe 1.50) + +| Item | Address | +| --- | --- | +| `FalconDevice::~FalconDevice` | `0x6A50D0` | +| `FalconDevice::updateCurrentState` | `0x6A52A0` (ELF `0x8499C80`, sample loop compiled out) | +| `g_falconDevice` | `ds:0xA03940` | +| `g_falconMouseMode` (initialized 1) | `ds:0x978FC4` | +| `g_falconControlBoxDirty` (initialized true) | `ds:0x978FC8` | +| the six force effects `g_hapticForceTargets` | `ds:0x9EBEC8`, `0x9EBECC`, `0x9EBF00`, `0x9EBF04`, `0x9EBF08`, `0x9EBF0C` | +| control-box effect, sample buffer | `ds:0xA03944`, `ds:0xA03918` | +| `FalconControlBoxParams` vtable store after the SDK constructor | `0x6A58A1` (vtable `0x9116E0`) | +| `MainMenuLogic::activate` force zeroing | `0x4A3490..0x4A3535` | +| `Camera::handleUpdate` ShakeForce | `0x5A3F4F..0x5A41D7` | +| `Soldier` ctor / `onExit` / `onEnter` control-box switch | `0x5AC764..0x5AC90B`, `0x5AB5E6..0x5AB83A`, `0x5ACC99..0x5ADE14` | +| `Soldier::handlePlayerInput` Recoil / CraftPhysics | `0x5AE335..0x5AE72B`, `0x5AECE8..0x5AF3F6` | +| `PlayerControlObject::handleUpdate` CraftPhysics | `0x5FAC8C..0x5FBCDB` | +| `GenericFireArm::postFire` kit RecoilPunch | `0x5E2A98..0x5E2CDA` | +| `SoldierBasedRecoilComp::postFire` RecoilPunch | `0x609318..0x609690` | +| `WeaponBasedRecoilComp::postFire` RecoilPunch | `0x60A077..0x60A4FE` | +| `GameLogicDamage::serverGiveDamage` Damage envelope | `0x5E6566..0x5E66A2` | +| `GameLogic` kill tail force zeroing | `0x4ED60B..0x4ED6C2` | +| `FreeCamera::handlePlayerInput` force zeroing | `0x63EC73..0x63ED26` | +| `BF2Engine::renderMenu` mouse mode | `0x40BD44..0x40BD57` | + +More addresses are in the comments of the archived sources. + +## Contents + +The files keep their paths relative to `Code/BF2` (sources) and `Code/Tests` (checks). + +| File | Was | +| --- | --- | +| `IO/Input/FalconDevice.h`, `FalconDevice.cpp` | the device, the effect bodies and the globals | +| `IO/Input/FalconHaptics.h` | the game-facing effect helpers | +| `External/NovintHFX/NovintHFX.h`, `NovintHFX.def` | the SDK ABI header and the x86 import-library definition | +| `Game/Objects/Game/SoldierHapticForces.h`, `.cpp` | the force inputs of `SoldierHapticProfile` (`HapticWeaponAccess`, `updateSoldierRecoilForce`, `updateSoldierCraftPhysics`, `updateVehicleCraftPhysics`) | +| `Tests/falcon_update_runtime.cpp`, `Tests/novint_fake/windows.h` | `bf2_falcon_update_check` (Mac, fake SDK) | +| `Tests/falcon_device_runtime.cpp`, `.cmd` | the MSVC x86 check against the stock DLL | +| `Tests/falcon_vtable_restore.cmd` | the MSVC check of the local vtable stores after the SDK constructors | +| `Tests/msvc_x86_layout/novint_x86_layout.cpp`, `include/windows.h` | `bf2_novint_msvc_x86_layout` (clang, MSVC x86 ABI) | +| `Tests/soldier_haptic_profile_runtime.cpp` | `bf2_soldier_haptic_profile_check` as it was, with the force-input checks (the live check keeps the profile switch) | + +## What replaced it + +Each call site now does what retail does with `NovintHFX.dll` present and no Falcon +connected: `FalconDevice::init` fails, `g_falconDevice` stays null and every effect helper +returns at its null test. The globals were only read by `FalconDevice`, so their writes are +gone too. Each site has a comment that points here. + +| Site | Now | +| --- | --- | +| `IO/Input/DX8InputDeviceManager.cpp` `open` | `IDFFalcon` is never opened; its bit stays clear (as in `MacInputDeviceManager`) | +| `Menu/MainMenuLogic.cpp` `activate` | no mouse-mode write, no force zeroing | +| `Menu/BetweenRoundsLogic.cpp` `activate`, `Menu/BF2HudManagerInit.cpp`, `Menu/BF2HudManagerUpdate.cpp` `update`, `Game/Main/BF2Engine.cpp` `renderMenu` | no mouse-mode write | +| `Game/Objects/Game/Soldier.cpp` ctor, `onExit`, `onEnter` | `applyHapticProfile` only (no dirty flag, no zeroing) | +| `Game/Objects/Game/Soldier.cpp` `handlePlayerInput` (Recoil, CraftPhysics) | removed | +| `Game/Objects/Game/PlayerControlObject.cpp` `handleUpdate` (CraftPhysics) | removed | +| `Game/Objects/Base/Camera.cpp` `handleUpdate` (ShakeForce) | removed, as in the ELF | +| `Game/Objects/Base/FreeCamera.cpp` `handlePlayerInput` | no force zeroing | +| `Game/Objects/Weapons/GenericFireArm.cpp`, `RecoilComponents/SoldierBasedRecoilComp.cpp`, `WeaponBasedRecoilComp.cpp` `postFire` (RecoilPunch) | removed | +| `Game/GameLogic/GameLogicDamage.cpp` (Damage) | the look-at inputs are still computed, as in the ELF; no effect | +| `Game/GameLogic/GameLogic.cpp` kill tail | no force zeroing | +| `Game/Main/BF2ClientSeams.h` | no `g_hapticForceTargets` | +| `Code/Tests/camera_shake_runtime.cpp`, `hud_lifecycle_runtime.cpp`, `client_startup_runtime.cpp`, `input_dx8_module_runtime.cpp` and the DX8 input `.cmd` checks | no Falcon expectations, no `NovintHFX.lib` | +| `Game/Objects/Weapons/GenericFireArm.h` | no `HapticWeaponAccess` friend | + +The generic `IDFFalcon` lookups in `Menu/BF2HudManagerInput.cpp` (absolute pointer) and +`Game/Main/BF2FrameInterpolator.cpp` (camera interpolation) remain. They now always find no +device, which is the retail no-Falcon branch. The `IDFFalcon`/`IDTFalcon` enumerators, the +`CONTROLLER_IDFFalcon` control-settings name and the control-map token stay, because retail +control maps and profiles name them. + +No image imports `NovintHFX.dll`, and no build stages it (client and editor, x86 and x64). + +## Restoring + +1. Revert the commit "Archive the Novint Falcon integration" (`git revert`). Alternatively, + move the files above back to their original paths and add the call sites from the table. +2. On Windows x86, restore the import library and staging in the root `CMakeLists.txt` + (`bf2_novint_imports`, `lib /def:NovintHFX.def /machine:x86`, the `NovintHFX.dll` copy) and + in `Code/Tools/BF2Editor/CMakeLists.txt`. Add `FalconDevice.cpp` back to the client source + list, `Code/Build/build.cmd` and `Code/Tests/syntaxcheck.cmd`. +3. Only an x86 client can load the 32-bit DLL. For x64 or macOS, issue #17 describes the + way back: a 64-bit `NovintHFX` replacement on top of libnifalcon. It needs a working Falcon + to tune. diff --git a/Code/Tests/falcon_device_runtime.cmd b/Code/Archive/NovintFalcon/Tests/falcon_device_runtime.cmd similarity index 92% rename from Code/Tests/falcon_device_runtime.cmd rename to Code/Archive/NovintFalcon/Tests/falcon_device_runtime.cmd index 61a3f68ed..a3b836ac7 100644 --- a/Code/Tests/falcon_device_runtime.cmd +++ b/Code/Archive/NovintFalcon/Tests/falcon_device_runtime.cmd @@ -15,6 +15,7 @@ if errorlevel 1 exit /b 1 link /nologo /FORCE /OPT:REF /INCREMENTAL:NO /DEBUG /SUBSYSTEM:CONSOLE /OUT:"%BF2_BUILD_OUT%\falcon_device_runtime.exe" /PDB:"%BF2_BUILD_OUT%\falcon_device_runtime.pdb" "%BF2_BUILD_OUT%\FalconDevice.obj" "%BF2_BUILD_OUT%\fixture.obj" "%BF2_BUILD_OUT%\NovintHFX.lib" user32.lib if errorlevel 1 exit /b 1 rem Loader searches the unchanged original DLL directory through PATH; no original file is written. -set "PATH=D:\B2BF Launcher\Battlefield2;%PATH%" +if not defined BF2_GAME_DIR set "BF2_GAME_DIR=D:\B2BF Launcher\Battlefield2" +set "PATH=%BF2_GAME_DIR%;%PATH%" "%BF2_BUILD_OUT%\falcon_device_runtime.exe" exit /b %errorlevel% diff --git a/Code/Tests/falcon_device_runtime.cpp b/Code/Archive/NovintFalcon/Tests/falcon_device_runtime.cpp similarity index 86% rename from Code/Tests/falcon_device_runtime.cpp rename to Code/Archive/NovintFalcon/Tests/falcon_device_runtime.cpp index 0f40b5243..3cc72db46 100644 --- a/Code/Tests/falcon_device_runtime.cpp +++ b/Code/Archive/NovintFalcon/Tests/falcon_device_runtime.cpp @@ -11,7 +11,12 @@ #include #include #include -namespace dice { namespace hfe { namespace io { IBase* inputDeviceManager = 0; } } } +namespace dice { namespace hfe { +// The frame update's collaborators; this fixture never reaches it (no device, update returns first). +IBase* g_controlSettings = 0; +IBase* g_hapticSettings = 0; +namespace io { IBase* inputDeviceManager = 0; IBase* controlMapManager = 0; float inputSampleLatency = 0.0f; } +} } using namespace dice::hfe; using namespace dice::hfe::io; int main() @@ -63,8 +68,8 @@ int main() } check(!api->getInvertAxis(static_cast(4)) && api->getAxisScale(static_cast(4)) == 0, "greater-than-count rejection"); - api->setAxisAdd(IDA_X, 12); - check(api->getAxisAdd(IDA_X) == 0, "recovered axis-add no-op"); + api->setAxisAdd(IDAxis_0, 12); + check(api->getAxisAdd(IDAxis_0) == 0, "recovered axis-add no-op"); float x = 7, y = 9; api->peakXYAxis(x, y); check(x == 0 && y == 0, "inherited zero peak"); @@ -77,12 +82,12 @@ int main() device->m_buttonLatency[31] = 0.75f; check(api->buttonPressedSampleLatency(static_cast(0x80000001u)) == 0.25f, "lowest latency bit wins"); check(api->buttonPressedSampleLatency(static_cast(0x80000000u)) == 0.75f, "latency high bit"); - check(api->buttonPressedSampleLatency(IDB_NONE) == 0, "zero latency mask"); - InputDeviceAxes axis = IDA_Z; + check(api->buttonPressedSampleLatency(static_cast(0)) == 0, "zero latency mask"); + InputDeviceAxes axis = IDAxis_2; InputDeviceButtons button = static_cast(7); InputDeviceKeys key = static_cast(8); bool negative = true; - check(!api->getNextInput(axis, button, key, negative) && axis == IDA_Z && button == 7 && key == 8 && negative, + check(!api->getNextInput(axis, button, key, negative) && axis == IDAxis_2 && button == 7 && key == 8 && negative, "inactive mapping leaves outputs untouched"); device->m_active = true; check(!api->isActive() && !api->getNextInput(axis, button, key, negative), "null device second guard"); @@ -93,6 +98,8 @@ int main() api->addRef(); check(api->getRef() == 2 && api->release() == 1, "reference increment/decrement"); check(api->release() == 0, "real final release and destructor"); - std::printf("FalconDevice: %d checks, %d failures; native size %u\n", checks, failed, unsigned(sizeof(FalconDevice))); - return failed != 0; + std::printf("falcon device runtime %d/%d checks passed (native size %u)\n", checks - failed, checks, + unsigned(sizeof(FalconDevice))); + std::fflush(stdout); + return failed != 0 ? 1 : 0; } diff --git a/Code/Archive/NovintFalcon/Tests/falcon_update_runtime.cpp b/Code/Archive/NovintFalcon/Tests/falcon_update_runtime.cpp new file mode 100644 index 000000000..62029abe7 --- /dev/null +++ b/Code/Archive/NovintFalcon/Tests/falcon_update_runtime.cpp @@ -0,0 +1,1246 @@ +// [TEMP] [CHOSEN, not recovered] Mac fake-SDK check for FalconDevice::updateCurrentState +// (BF2.exe 0x6A52A0), built as bf2_falcon_update_check. The actual FalconDevice and HapticSettings +// run; the NovintHFX SDK, the Win32 clock, the active control map and ControlSettings are fakes +// that record what the device asks of them. No Falcon, DLL or Windows is involved. The Windows twin +// falcon_device_runtime.cmd links the stock NovintHFX.dll with no device connected. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#define private public +#include "../BF2/IO/Input/FalconDevice.h" +#undef private +#include "../BF2/Game/ControlSettings.h" +#include "../BF2/Game/HapticSettings.h" +#include "../BF2/Game/Main/BF2ClientSeams.h" +#include "../BF2/Core/ClassManager.h" +#include "../BF2/Core/EventManager.h" + +using namespace dice::hfe; +using namespace dice::hfe::io; + +static unsigned checks, failures; +static void check(bool value, const char* label) +{ + ++checks; + if (!value) { ++failures; std::printf("FAIL %s\n", label); } +} +static bool same(double a, double b) { return a == b || (std::isnan(a) && std::isnan(b)); } + +[[noreturn]] static void unsupported(const char* name) +{ + std::fprintf(stderr, "[TEMP] falcon_update check: %s is not modelled\n", name); + std::fflush(stderr); + std::abort(); +} + +// ---- Win32 clock ------------------------------------------------------------------------------- +static DWORD g_tick; +static int g_foregroundCalls; +extern "C" DWORD GetTickCount() { return g_tick; } +extern "C" HWND GetForegroundWindow() { ++g_foregroundCalls; return reinterpret_cast(0x1234); } + +// ---- fake NovintHFX SDK ------------------------------------------------------------------------ +namespace fake { +struct Log { std::vector calls; void add(const std::string& s) { calls.push_back(s); } + std::string joined() const { std::string r; for (auto& c : calls) r += c + ";"; return r; } + void clear() { calls.clear(); } }; +Log sdk; +double toolPosition[3]; +int buttonData; +int deviceCount = 1; +int liveParams; +struct Captured { double lower[3], upper[3], lowerStiffness[3], upperStiffness[3]; int value114; }; +std::vector updates; +const char* createType; +const char* createName; +} + +NovintHFX::ApplicationData::mouse_settings::mouse_settings() { std::memset(m_sdkState, 0, sizeof(m_sdkState)); } +NovintHFX::HapticsSystem::HapticsSystem() {} +static NovintHFX::Device g_deviceObject; +static NovintHFX::Stack* g_stack; +extern "C" NovintHFX::HapticsSystem Haptics; +NovintHFX::HapticsSystem Haptics; +bool NovintHFX::HapticsSystem::AttachApplication(ApplicationData& a) +{ fake::sdk.add(a.window == reinterpret_cast(0x1234) ? "attach foreground" : "attach other"); return true; } +void NovintHFX::HapticsSystem::RecountConnectedDevices() { fake::sdk.add("recount"); } +int NovintHFX::HapticsSystem::ConnectedDeviceCount() const { return fake::deviceCount; } +bool NovintHFX::HapticsSystem::RunDevice(Device** d, int index) +{ fake::sdk.add("run " + std::to_string(index)); *d = &g_deviceObject; return true; } +void NovintHFX::HapticsSystem::StartMouse(Device* d) { fake::sdk.add(d == &g_deviceObject ? "startMouse device" : "startMouse other"); } +bool NovintHFX::HapticsSystem::StopRunningDevice(Device** d) { fake::sdk.add("stop"); *d = 0; return true; } +int NovintHFX::HapticsSystem::InputUpdate() { fake::sdk.add("systemInput"); return 0; } +NovintHFX::Device::Device() {} +void NovintHFX::Device::InputUpdate() { fake::sdk.add("deviceInput"); } +void NovintHFX::Device::GetButtonData(int* down, int* pressed, int* released) const +{ fake::sdk.add("buttons"); *down = fake::buttonData; *pressed = 0; *released = 0; } +void NovintHFX::Device::GetToolPosition(double* const p) const +{ p[0] = fake::toolPosition[0]; p[1] = fake::toolPosition[1]; p[2] = fake::toolPosition[2]; } +NovintHFX::Stack* NovintHFX::Device::GetEffectStack() { fake::sdk.add("stack"); return g_stack; } +NovintHFX::Stack::Stack() {} + +namespace fake { int vect3Constructions; } +NovintHFX::Vect3::Vect3(const double& x, const double& y, const double& z) +{ ++fake::vect3Constructions; m_unresolved[0] = x; m_unresolved[1] = y; m_unresolved[2] = z; } +double& NovintHFX::Vect3::operator[](int i) { return m_unresolved[i]; } +NovintHFX::Vect3& NovintHFX::Vect3::operator=(const Vect3& other) +{ + for (int i = 0; i < 3; ++i) m_unresolved[i] = other.m_unresolved[i]; + return *this; +} +NovintHFX::Vect3 NovintHFX::Vect3::operator*(const double& scale) const +{ return Vect3(m_unresolved[0] * scale, m_unresolved[1] * scale, m_unresolved[2] * scale); } +NovintHFX::Vect3 NovintHFX::Vect3::Normalize() const +{ + const double length = std::sqrt(m_unresolved[0] * m_unresolved[0] + + m_unresolved[1] * m_unresolved[1] + m_unresolved[2] * m_unresolved[2]); + return length == 0.0 ? Vect3(0.0, 0.0, 0.0) : *this * (1.0 / length); +} + +namespace fake { double lastForce[3]; } +struct FakeEffect final : IHapticEffect { + int id = 0; + FakeEffect() { std::memset(m_unresolved04, 0, sizeof(m_unresolved04)); m_stateFlags = 0; } + explicit FakeEffect(int effectId) : FakeEffect() { id = effectId; } + void unresolvedSlot48() override { unsupported("effect slot 48"); } + void SetForce(const NovintHFX::Vect3& force) override + { + NovintHFX::Vect3& v = const_cast(force); + char line[96]; + std::snprintf(line, sizeof(line), "force %d %g %g %g", id, v[0], v[1], v[2]); + fake::sdk.add(line); + for (int i = 0; i < 3; ++i) fake::lastForce[i] = v[i]; + } + void unresolvedSlot50() override { unsupported("effect slot 50"); } + void SetSmoothTime(int value) override { fake::sdk.add("smooth " + std::to_string(id) + " " + std::to_string(value)); } + void unresolvedSlot00() override { unsupported("effect slot 00"); } + void unresolvedSlot04() override { unsupported("effect slot 04"); } + void unresolvedSlot08() override { unsupported("effect slot 08"); } + void unresolvedSlot0C() override { unsupported("effect slot 0C"); } + void unresolvedSlot10() override { unsupported("effect slot 10"); } + void unresolvedSlot14() override { unsupported("effect slot 14"); } + void unresolvedSlot18() override { unsupported("effect slot 18"); } + void unresolvedSlot1C() override { unsupported("effect slot 1C"); } + void unresolvedSlot20() override { unsupported("effect slot 20"); } + void unresolvedSlot24() override { unsupported("effect slot 24"); } + void unresolvedSlot28() override { unsupported("effect slot 28"); } + void unresolvedSlot2C() override { unsupported("effect slot 2C"); } + void unresolvedSlot30() override { unsupported("effect slot 30"); } + void unresolvedSlot34() override { unsupported("effect slot 34"); } + void unresolvedSlot38() override { unsupported("effect slot 38"); } + void unresolvedSlot3C() override { unsupported("effect slot 3C"); } + void unresolvedSlot40() override { unsupported("effect slot 40"); } + bool UpdateParams(IHapticEffectParam* p) override + { + auto* box = static_cast(p); + fake::Captured c; + for (int i = 0; i < 3; ++i) { + c.lower[i] = box->m_lower[i]; c.upper[i] = box->m_upper[i]; + c.lowerStiffness[i] = box->m_lowerStiffness[i]; c.upperStiffness[i] = box->m_upperStiffness[i]; + } + c.value114 = box->m_unresolved114; + fake::updates.push_back(c); + fake::sdk.add(std::string("update flags=") + std::to_string(m_stateFlags & 1)); + return true; + } +}; +IHapticEffect::IHapticEffect() {} +static FakeEffect g_effect; +namespace fake { int constantEffects; int constantParam18 = -1; std::string params18; } +bool NovintHFX::Stack::CreateNewEffect(const char* type, IHapticEffectParam* params, const char* name, IHapticEffect** out) +{ + fake::createType = type; fake::createName = name; + fake::sdk.add(std::string("create ") + type + " " + name); + if (std::string(type) == "CONSTANT" || std::string(type) == "Constant") { + // Each CONSTANT effect is its own object (ids 10, 11, ...); the params' +0x18 is recorded. + static FakeEffect constants[8] = { FakeEffect(10), FakeEffect(11), FakeEffect(12), FakeEffect(13), + FakeEffect(14), FakeEffect(15), FakeEffect(16), FakeEffect(17) }; + fake::constantParam18 = static_cast(params)->m_unresolved18; + fake::params18 += std::to_string(fake::constantParam18) + ","; + *out = &constants[fake::constantEffects++ % 8]; + return true; + } + if (std::string(type) == "Envelope") { + // Fire-and-forget: the out pointer is null; record what the effect would be built from. + auto* envelope = static_cast(params); + char line[160]; + std::snprintf(line, sizeof(line), "envelope %d %.17g %.17g %.17g%s", envelope->m_unresolved18, + envelope->m_force[0], envelope->m_force[1], envelope->m_force[2], out ? " out" : ""); + fake::sdk.add(line); + return true; + } + *out = &g_effect; + return true; +} +NovintHFX::BaseEffectParams::BaseEffectParams() { std::memset(m_baseState, 0, sizeof(m_baseState)); ++fake::liveParams; } +NovintHFX::BaseEffectParams::~BaseEffectParams() { --fake::liveParams; fake::sdk.add("params destroyed"); } +bool NovintHFX::BaseEffectParams::RunSetCommand(char*) { unsupported("RunSetCommand"); } +bool NovintHFX::BaseEffectParams::SetVar(const char*, const char*) { unsupported("SetVar(cc,cc)"); } +bool NovintHFX::BaseEffectParams::CreateStandardEffect(Device*, const char*, IHapticEffect**) { unsupported("CreateStandardEffect"); } +bool NovintHFX::BaseEffectParams::CreateStandardEffect(Stack*, const char*, IHapticEffect**) { unsupported("CreateStandardEffect"); } +NovintHFX::ControlBoxEffectParams::ControlBoxEffectParams() throw() +{ + // Poison every field so the check sees exactly what updateCurrentState writes. + for (int i = 0; i < 3; ++i) m_lower[i] = m_upper[i] = m_lowerStiffness[i] = m_upperStiffness[i] = -777.0; + m_unresolved114 = -1; + fake::sdk.add("params constructed"); +} +const char* NovintHFX::ControlBoxEffectParams::StandardEffectName() const { return "ControlBox"; } +#define FAKE_VAR(sig) bool NovintHFX::ControlBoxEffectParams::sig { unsupported(#sig); } +FAKE_VAR(SetVar(const char*, double)) FAKE_VAR(SetVar(const char*, bool)) FAKE_VAR(SetVar(const char*, float)) +FAKE_VAR(SetVar(const char*, int)) FAKE_VAR(SetVar(const char*, void*)) FAKE_VAR(SetVar(const char*, int, double)) +FAKE_VAR(SetVar(const char*, int, bool)) FAKE_VAR(SetVar(const char*, int, float)) FAKE_VAR(SetVar(const char*, int, int)) +FAKE_VAR(SetVar(const char*, int, void*)) FAKE_VAR(GetVar(const char*, float&)) FAKE_VAR(GetVar(const char*, double&)) +FAKE_VAR(GetVar(const char*, bool&)) FAKE_VAR(GetVar(const char*, int&)) FAKE_VAR(GetVar(const char*, void*)) +FAKE_VAR(GetVar(const char*, int, float&)) FAKE_VAR(GetVar(const char*, int, double&)) FAKE_VAR(GetVar(const char*, int, bool&)) +FAKE_VAR(GetVar(const char*, int, int&)) FAKE_VAR(GetVar(const char*, int, void*)) +#undef FAKE_VAR +char NovintHFX::ControlBoxEffectParams::GetVarType(const char*, int*) const { unsupported("GetVarType"); } +NovintHFX::ParamsStaticClass* NovintHFX::ControlBoxEffectParams::GetStaticInfoClass() { unsupported("GetStaticInfoClass"); } + +// [TEMP] [CHOSEN, not recovered] Unused effect fixture; SDK state is poisoned, not reconstructed. +NovintHFX::ConstantEffectParams::ConstantEffectParams() throw() +{ + m_unresolved18 = m_unresolved1C = -1; + fake::sdk.add("constant params constructed"); +} +const char* NovintHFX::ConstantEffectParams::StandardEffectName() const { return "Constant"; } +#define FAKE_VAR(sig) bool NovintHFX::ConstantEffectParams::sig { unsupported(#sig); } +FAKE_VAR(SetVar(const char*, double)) FAKE_VAR(SetVar(const char*, bool)) FAKE_VAR(SetVar(const char*, float)) +FAKE_VAR(SetVar(const char*, int)) FAKE_VAR(SetVar(const char*, void*)) FAKE_VAR(SetVar(const char*, int, double)) +FAKE_VAR(SetVar(const char*, int, bool)) FAKE_VAR(SetVar(const char*, int, float)) FAKE_VAR(SetVar(const char*, int, int)) +FAKE_VAR(SetVar(const char*, int, void*)) FAKE_VAR(GetVar(const char*, float&)) FAKE_VAR(GetVar(const char*, double&)) +FAKE_VAR(GetVar(const char*, bool&)) FAKE_VAR(GetVar(const char*, int&)) FAKE_VAR(GetVar(const char*, void*)) +FAKE_VAR(GetVar(const char*, int, float&)) FAKE_VAR(GetVar(const char*, int, double&)) FAKE_VAR(GetVar(const char*, int, bool&)) +FAKE_VAR(GetVar(const char*, int, int&)) FAKE_VAR(GetVar(const char*, int, void*)) +#undef FAKE_VAR +char NovintHFX::ConstantEffectParams::GetVarType(const char*, int*) const { unsupported("GetVarType"); } +NovintHFX::ParamsStaticClass* NovintHFX::ConstantEffectParams::GetStaticInfoClass() { unsupported("GetStaticInfoClass"); } + +// [TEMP] [CHOSEN, not recovered] Unused effect fixture; SDK state is poisoned, not reconstructed. +NovintHFX::EnvelopeEffectParams::EnvelopeEffectParams() throw() +{ + m_unresolved18 = -1; + std::memset(m_unresolved1C, 0xCC, sizeof(m_unresolved1C)); + for (int i = 0; i < 3; ++i) m_force[i] = -777.0; + fake::sdk.add("envelope params constructed"); +} +const char* NovintHFX::EnvelopeEffectParams::StandardEffectName() const { return "Envelope"; } +#define FAKE_VAR(sig) bool NovintHFX::EnvelopeEffectParams::sig { unsupported(#sig); } +FAKE_VAR(SetVar(const char*, double)) FAKE_VAR(SetVar(const char*, bool)) FAKE_VAR(SetVar(const char*, float)) +FAKE_VAR(SetVar(const char*, int)) FAKE_VAR(SetVar(const char*, void*)) FAKE_VAR(SetVar(const char*, int, double)) +FAKE_VAR(SetVar(const char*, int, bool)) FAKE_VAR(SetVar(const char*, int, float)) FAKE_VAR(SetVar(const char*, int, int)) +FAKE_VAR(SetVar(const char*, int, void*)) FAKE_VAR(GetVar(const char*, float&)) FAKE_VAR(GetVar(const char*, double&)) +FAKE_VAR(GetVar(const char*, bool&)) FAKE_VAR(GetVar(const char*, int&)) FAKE_VAR(GetVar(const char*, void*)) +FAKE_VAR(GetVar(const char*, int, float&)) FAKE_VAR(GetVar(const char*, int, double&)) FAKE_VAR(GetVar(const char*, int, bool&)) +FAKE_VAR(GetVar(const char*, int, int&)) FAKE_VAR(GetVar(const char*, int, void*)) +#undef FAKE_VAR +char NovintHFX::EnvelopeEffectParams::GetVarType(const char*, int*) const { unsupported("GetVarType"); } +NovintHFX::ParamsStaticClass* NovintHFX::EnvelopeEffectParams::GetStaticInfoClass() { unsupported("GetStaticInfoClass"); } + +// ---- engine globals and fakes ------------------------------------------------------------------ +namespace dice { namespace hfe { +ClassManager* classManager = nullptr; +EventManager* eventManager = nullptr; +hud::BF2HudManager* hudManager = nullptr; +IBase* g_controlSettings = nullptr; +IBase* g_hapticSettings = nullptr; +namespace io { +IBase* inputDeviceManager = nullptr; +IBase* controlMapManager = nullptr; +float inputSampleLatency = -1.0f; +} +} } + +struct FakeMap final : IControlMap { + bool invert = false; + float scale[4] = { 1.0f, 1.0f, 1.0f, 1.0f }; + int invertReads = 0, scaleReads = 0; + void addRef() override {} + int getRef() override { return 1; } + int release() override { return 1; } + void* queryInterface(unsigned int) const override { return 0; } + void setName(const std::string&) override { unsupported("setName"); } + const std::string& getName() const override { unsupported("getName"); } + int getID() const override { unsupported("getID"); } + void setID(int) override { unsupported("setID"); } + bool axisExists(int) const override { unsupported("axisExists"); } + bool triggerExists(int) const override { unsupported("triggerExists"); } + bool addAxisMapping(int, int, InputDeviceFlags, InputDeviceAxes, bool, bool) override { unsupported("addAxisMapping"); } + bool addAxisMapping(int, InputDeviceFlags, InputDeviceAxes, bool, bool) override { unsupported("addAxisMapping"); } + bool addAxisMapping(int, InputDeviceFlags, InputDeviceButtons, InputDeviceButtons, bool) override { unsupported("addAxisMapping"); } + bool addAxisMapping(int, InputDeviceFlags, InputDeviceKeys, InputDeviceKeys, bool) override { unsupported("addAxisMapping"); } + bool addAxisMapping(int, int, InputDeviceFlags, InputDevicePOVs, bool, bool, bool) override { unsupported("addAxisMapping"); } + bool addAxisMapping(int, InputDeviceFlags, InputDeviceButtons, InputDeviceFlags, InputDeviceKeys, bool) override { unsupported("addAxisMapping"); } + bool addAxisMapping(int, InputDeviceFlags, InputDeviceKeys, InputDeviceFlags, InputDeviceButtons, bool) override { unsupported("addAxisMapping"); } + bool addTriggerMapping(int, InputDeviceFlags, InputDeviceButtons, float, bool) override { unsupported("addTriggerMapping"); } + bool addTriggerMapping(int, InputDeviceFlags, InputDeviceKeys, float, bool) override { unsupported("addTriggerMapping"); } + bool addTriggerMapping(int, int, InputDeviceFlags, InputDeviceAxes, bool, float, float) override { unsupported("addTriggerMapping"); } + void removeMapping(unsigned int) override { unsupported("removeMapping"); } + void reset() override { unsupported("reset"); } + void reset(int, bool, bool, bool) override { unsupported("reset"); } + void setButtonRiseTime(float) override { unsupported("setButtonRiseTime"); } + void setButtonFallTime(float) override { unsupported("setButtonFallTime"); } + void setDoubleTapTime(float) override { unsupported("setDoubleTapTime"); } + float getAxisValue(int) const override { unsupported("getAxisValue"); } + bool isAxisValueAnalogue(int) const override { unsupported("isAxisValueAnalogue"); } + int getTriggerState(int) const override { unsupported("getTriggerState"); } + float getTriggerSampleLatency(int) const override { unsupported("getTriggerSampleLatency"); } + bool validate() override { unsupported("validate"); } + void update(float) override { unsupported("update"); } + void setInvertMouse(bool) override { unsupported("setInvertMouse"); } + bool getInvertMouse() override { ++invertReads; return invert; } + void setMouseSensitivity(float) override { unsupported("setMouseSensitivity"); } + float getMouseSensitivity() override { unsupported("getMouseSensitivity"); } + void setKeyboardSensitivity(float) override { unsupported("setKeyboardSensitivity"); } + float getKeyboardSensitivity() override { unsupported("getKeyboardSensitivity"); } + void setAxisScale(InputDeviceAxes, float) override { unsupported("setAxisScale"); } + float getAxisScale(InputDeviceAxes a) const override { ++const_cast(this)->scaleReads; return scale[a]; } + void setYawFactor(float) override { unsupported("setYawFactor"); } + void setPitchFactor(float) override { unsupported("setPitchFactor"); } + float getYawFactor() override { unsupported("getYawFactor"); } + float getPitchFactor() override { unsupported("getPitchFactor"); } + void save(std::ostream&, bool) override { unsupported("save"); } + void dump(bool) override { unsupported("dump"); } + bool findDuplicate(InputDeviceFlags&, InputDeviceAxes&, InputDeviceButtons&, InputDeviceKeys&, + DuplicateKeyVector&) override { unsupported("findDuplicate"); } + bool getInputMappedToMouseButton(bool, PlayerInputMap&) override { unsupported("getInputMappedToMouseButton"); } +}; + +struct FakeMaps final : IControlMapManager { + FakeMap map; + void addRef() override {} + int getRef() override { return 1; } + int release() override { return 1; } + void* queryInterface(unsigned int) const override { return 0; } + void update(float) override { unsupported("maps update"); } + IControlMap* create(const std::string&) override { unsupported("create"); } + IControlMap* getControlMap(const std::string&) const override { unsupported("getControlMap"); } + IControlMap* getControlMap(int) const override { unsupported("getControlMap"); } + void deleteControlMap(const std::string&) override { unsupported("deleteControlMap"); } + void deleteControlMap(int) override { unsupported("deleteControlMap"); } + void deleteControlMap(const IControlMap*) override { unsupported("deleteControlMap"); } + void setActive(const std::string&) override { unsupported("setActive"); } + void setActive(const IControlMap*) override { unsupported("setActive"); } + IControlMap* getActive() const override { return const_cast(&map); } + int mapNextInput(IControlMap*, int, bool, bool, bool, bool, std::string&) override { unsupported("mapNextInput"); } + float getRepeatRate(int, bool) override { unsupported("getRepeatRate"); } + void applyActive() override { unsupported("applyActive"); } +}; + +struct FakeControlSettings final : IControlSettings { + bool mapping = false; + void addRef() override {} + int getRef() override { return 1; } + int release() override { return 1; } + void* queryInterface(unsigned int) const override { return 0; } + std::string getFileName() override { unsupported("getFileName"); } + std::string getSettingsScript() override { unsupported("getSettingsScript"); } + bool restoreControlMaps() override { unsupported("restoreControlMaps"); } + void backupControlMaps() override { unsupported("backupControlMaps"); } + void backupControlMapsByName() override { unsupported("backupControlMapsByName"); } + bool setDefaults() override { unsupported("setDefaults"); } + void resetControlMaps() override { unsupported("resetControlMaps"); } + void updateInputDevices() override { unsupported("updateInputDevices"); } + int mapNextInput(int, bool, int, bool, bool) override { unsupported("mapNextInput"); } + bool selectControlMap(const std::string&) override { unsupported("selectControlMap"); } + bool getBindingDescription(io::IControlMap*, int, bool, bool, bool, std::string&, std::wstring&) override { unsupported("getBindingDescription"); } + std::string getActiveControlMapName() override { unsupported("getActiveControlMapName"); } + float getMouseSensitivity() override { unsupported("getMouseSensitivity"); } + void setMouseSensitivity(float) override { unsupported("setMouseSensitivity"); } + float getSlot48() override { unsupported("getSlot48"); } + void setSlot4C(float) override { unsupported("setSlot4C"); } + float getSlot50() override { unsupported("getSlot50"); } + void setSlot54(float) override { unsupported("setSlot54"); } + float getYawFactor() override { unsupported("getYawFactor"); } + void setYawFactor(float) override { unsupported("setYawFactor"); } + float getPitchFactor() override { unsupported("getPitchFactor"); } + void setPitchFactor(float) override { unsupported("setPitchFactor"); } + bool getInvertMouse() override { unsupported("getInvertMouse"); } + void setInvertMouse(bool) override { unsupported("setInvertMouse"); } + float getKeyboardSensitivity() override { unsupported("getKeyboardSensitivity"); } + void setKeyboardSensitivity(float) override { unsupported("setKeyboardSensitivity"); } + bool apply() override { unsupported("apply"); } + void deleteControlMapBackups() override { unsupported("deleteControlMapBackups"); } + void activateMouse() override { unsupported("activateMouse"); } + void deactivateMouse() override { unsupported("deactivateMouse"); } + bool isMappingInput() override { return mapping; } + void setMappingInput(bool) override { unsupported("setMappingInput"); } + std::string getMappedInputName() override { unsupported("getMappedInputName"); } +}; + +struct Nothing final : IBase { + void addRef() override {} + int getRef() override { return 1; } + int release() override { return 1; } + void* queryInterface(unsigned int) const override { return 0; } +}; + +// ---- helpers ----------------------------------------------------------------------------------- +static void poll(FalconDevice& d, DWORD tick, double x, double y, double z, int buttons) +{ + g_tick = tick; + fake::toolPosition[0] = x; fake::toolPosition[1] = y; fake::toolPosition[2] = z; + fake::buttonData = buttons; + d.update(0.0f); +} +static double fromFloat(float f) { return static_cast(f); } + +// ---- updateShakeForce's soldier test: the occupied object's template class id ------------------- +#include "../BF2/Core/Ids.h" +#include "../BF2/Game/Objects/IObject.h" +#include "../BF2/Game/Objects/IObjectTemplate.h" +#include "../BF2/Scene/Object/ObjectTypes/Game/IPlayerControlObject.h" +namespace { +using namespace dice::hfe::world; +[[noreturn]] void unexpected(const char* name) { unsupported(name); } +struct ShakeTemplate final : IObjectTemplate { + unsigned int classId = 0; + void addRef() override { unexpected("addRef"); } + int getRef() override { unexpected("getRef"); } + int release() override { unexpected("release"); } + void* queryInterface(unsigned int) const override { unexpected("IObjectTemplate::queryInterface"); } + unsigned int getClassID() const override { return classId; } + void templateInitialize() override { unexpected("IObjectTemplate::templateInitialize"); } + bool writeBinary(io::IStream*) const override { unexpected("IObjectTemplate::writeBinary"); } + bool readBinary(io::IStream*) override { unexpected("IObjectTemplate::readBinary"); } + void setName(const std::string&) override { unexpected("IObjectTemplate::setName"); } + const std::string& getName() const override { unexpected("IObjectTemplate::getName"); } + const std::string& getCreator() const override { unexpected("IObjectTemplate::getCreator"); } + void setCreator(const std::string&) override { unexpected("IObjectTemplate::setCreator"); } + const std::string& getModifiedByUser() const override { unexpected("IObjectTemplate::getModifiedByUser"); } + void setModifiedByUser(const std::string&) override { unexpected("IObjectTemplate::setModifiedByUser"); } + void setId(unsigned int) override { unexpected("IObjectTemplate::setId"); } + unsigned int getId() const override { unexpected("IObjectTemplate::getId"); } + unsigned int getFlags() const override { unexpected("IObjectTemplate::getFlags"); } + unsigned int updateFlags(unsigned int set, unsigned int clear) override { unexpected("IObjectTemplate::updateFlags"); } + void* queryImplementation(unsigned int classId) override { unexpected("IObjectTemplate::queryImplementation"); } + IObject* createObject() const override { unexpected("IObjectTemplate::createObject"); } + void setComponent(unsigned int classId, IBase* component) override { unexpected("IObjectTemplate::setComponent"); } + IObjectTemplateComponent* queryComponent(unsigned int) override { unexpected("IObjectTemplate::queryComponent"); } + IObjectTemplateComponent* getComponentFromClassID(unsigned int) const override { unexpected("IObjectTemplate::getComponentFromClassID"); } + void objectCreated(IObject*) override { unexpected("IObjectTemplate::objectCreated"); } + void objectDestroyed(IObject*) override { unexpected("IObjectTemplate::objectDestroyed"); } + void preCache() const override { unexpected("IObjectTemplate::preCache"); } + void setCullRadiusScale(float) override { unexpected("IObjectTemplate::setCullRadiusScale"); } + float getCullRadiusScale() const override { unexpected("IObjectTemplate::getCullRadiusScale"); } + void setPhysicsComponent(IObject*) const override { unexpected("IObjectTemplate::setPhysicsComponent"); } + void removePhysicsComponent(IObject*) const override { unexpected("IObjectTemplate::removePhysicsComponent"); } + void setPhysicsNodeComponent(IObject*) const override { unexpected("IObjectTemplate::setPhysicsNodeComponent"); } + void removePhysicsNodeComponent(IObject*) const override { unexpected("IObjectTemplate::removePhysicsNodeComponent"); } + void setResponsePhysicsComponent(IObject*) const override { unexpected("IObjectTemplate::setResponsePhysicsComponent"); } + void removeResponsePhysicsComponent(IObject*) const override { unexpected("IObjectTemplate::removeResponsePhysicsComponent"); } + void setNetworkableInfo(const std::string&) override { unexpected("IObjectTemplate::setNetworkableInfo"); } + const std::string& getNetworkableInfo() const override { unexpected("IObjectTemplate::getNetworkableInfo"); } + void setCollisionMesh(const std::string&) override { unexpected("IObjectTemplate::setCollisionMesh"); } + const std::string& getCollisionMesh() const override { unexpected("IObjectTemplate::getCollisionMesh"); } + const Vec3& getAnchor() const override { unexpected("IObjectTemplate::getAnchor"); } + void setAnchor(const Vec3&) override { unexpected("IObjectTemplate::setAnchor"); } + const Vec3& getAnchorOffset() const override { unexpected("IObjectTemplate::getAnchorOffset"); } + void setAnchorOffset(const Vec3&) override { unexpected("IObjectTemplate::setAnchorOffset"); } + Vec3 getAnchorPos() const override { unexpected("IObjectTemplate::getAnchorPos"); } + void setIsOvergrowth(bool) override { unexpected("IObjectTemplate::setIsOvergrowth"); } + bool getIsOvergrowth() const override { unexpected("IObjectTemplate::getIsOvergrowth"); } + std::vector >* getMaterialVector() override { unexpected("IObjectTemplate::getMaterialVector"); } + ComponentMap* getComponentMap() override { unexpected("IObjectTemplate::getComponentMap"); } + void setMaterial(int) override { unexpected("IObjectTemplate::setMaterial"); } + int getMaterial() const override { unexpected("IObjectTemplate::getMaterial"); } + void setSpecialMaterials(unsigned int) override { unexpected("IObjectTemplate::setSpecialMaterials"); } + unsigned int getSpecialMaterials() const override { unexpected("IObjectTemplate::getSpecialMaterials"); } +}; +struct ShakePco final : IPlayerControlObject { + IObject* occupied = 0; + void addRef() override { unexpected("addRef"); } + int getRef() override { unexpected("getRef"); } + int release() override { unexpected("release"); } + void* queryInterface(unsigned int iid) const override + { + if (iid != IID_IObject) unexpected("IPlayerControlObject::queryInterface(other)"); + return occupied; + } + IPlayer* getOccupingPlayer() const override { unexpected("IPlayerControlObject::getOccupingPlayer"); } + IObject* getOccupingObject() const override { unexpected("IPlayerControlObject::getOccupingObject"); } + bool isOccupied() const override { unexpected("IPlayerControlObject::isOccupied"); } + bool enter(IPlayer* player) override { unexpected("IPlayerControlObject::enter"); } + void exit() override { unexpected("IPlayerControlObject::exit"); } + void exitPlayer() override { unexpected("IPlayerControlObject::exitPlayer"); } + void onEnter(IObject*) override { unexpected("IPlayerControlObject::onEnter"); } + void onExit() override { unexpected("IPlayerControlObject::onExit"); } + int getPcoId() const override { unexpected("IPlayerControlObject::getPcoId"); } + void setPcoId(int id) override { unexpected("IPlayerControlObject::setPcoId"); } + std::map* getCameras() override { unexpected("IPlayerControlObject::getCameras"); } + std::map* getOwnCameras() override { unexpected("IPlayerControlObject::getOwnCameras"); } + void nextCamera() override { unexpected("IPlayerControlObject::nextCamera"); } + ICameraObject* getActiveCamera() override { unexpected("IPlayerControlObject::getActiveCamera"); } + void setActiveCamera(int) override { unexpected("IPlayerControlObject::setActiveCamera"); } + bool getExitPosition(Vec3& out) override { unexpected("IPlayerControlObject::getExitPosition"); } + bool getAltExitPosition(Vec3& out) override { unexpected("IPlayerControlObject::getAltExitPosition"); } + void addExternalCamera(ICameraObject* camera) override { unexpected("IPlayerControlObject::addExternalCamera"); } + void removeExternalCamera(ICameraObject* camera) override { unexpected("IPlayerControlObject::removeExternalCamera"); } + bool canSpawn(const Mat4& transform) override { unexpected("IPlayerControlObject::canSpawn"); } + std::map* getPcos() override { unexpected("IPlayerControlObject::getPcos"); } + const std::vector* getPcoPosId() override { unexpected("IPlayerControlObject::getPcoPosId"); } + void addWeapon(IObject* weapon) override { unexpected("IPlayerControlObject::addWeapon"); } + void* getWeapons() override { unexpected("IPlayerControlObject::getWeapons"); } + IObject* getActiveWeapon(int) const override { unexpected("IPlayerControlObject::getActiveWeapon"); } + void* getWeapons(int) override { unexpected("IPlayerControlObject::getWeapons"); } + void setActiveWeapon(IObject* weapon, int) override { unexpected("IPlayerControlObject::setActiveWeapon"); } + void toggleOnWeaponLock(IObject*) override { unexpected("IPlayerControlObject::toggleOnWeaponLock"); } + int getArtPos() override { unexpected("IPlayerControlObject::getArtPos"); } + bool checkSpecialToggle(io::PlayerInput input) override { unexpected("IPlayerControlObject::checkSpecialToggle"); } + bool checkSpecialToggleLastUpdate(io::PlayerInputMap map) override { unexpected("IPlayerControlObject::checkSpecialToggleLastUpdate"); } + void setTeam(int team) override { unexpected("IPlayerControlObject::setTeam"); } + void setDefaultTeam(int team) override { unexpected("IPlayerControlObject::setDefaultTeam"); } + int getDefaultTeam() override { unexpected("IPlayerControlObject::getDefaultTeam"); } + int getTeam() override { unexpected("IPlayerControlObject::getTeam"); } + float getTimeToLiveUnused() override { unexpected("IPlayerControlObject::getTimeToLiveUnused"); } + void setTimeToLiveUnused(float t) override { unexpected("IPlayerControlObject::setTimeToLiveUnused"); } + bool isAllowedToExit() override { unexpected("IPlayerControlObject::isAllowedToExit"); } + void addPlayerInputObject(IObject*) override { unexpected("IPlayerControlObject::addPlayerInputObject"); } + void removePlayerInputObject(IObject*) override { unexpected("IPlayerControlObject::removePlayerInputObject"); } + void setTimeSpawned(float t) override { unexpected("IPlayerControlObject::setTimeSpawned"); } + float getTimeSpawned() const override { unexpected("IPlayerControlObject::getTimeSpawned"); } + void setObjectSpawnerId(int id) override { unexpected("IPlayerControlObject::setObjectSpawnerId"); } + int getObjectSpawnerId() const override { unexpected("IPlayerControlObject::getObjectSpawnerId"); } + void setObjectSpawnerHolding(bool holding) override { unexpected("IPlayerControlObject::setObjectSpawnerHolding"); } + bool getObjectSpawnerHolding() const override { unexpected("IPlayerControlObject::getObjectSpawnerHolding"); } + const Vec3& getNameTagOffset() override { unexpected("IPlayerControlObject::getNameTagOffset"); } + const Vec3& getRidingWithOffset() override { unexpected("IPlayerControlObject::getRidingWithOffset"); } + float getRidingWithDistMod() override { unexpected("IPlayerControlObject::getRidingWithDistMod"); } + int getVehicleCameraShake() override { unexpected("IPlayerControlObject::getVehicleCameraShake"); } + float getVehicleFov() override { unexpected("IPlayerControlObject::getVehicleFov"); } + void addVehicleMod(VehicleMod mod) override { unexpected("IPlayerControlObject::addVehicleMod"); } + void removeVehicleMod(VehicleMod mod) override { unexpected("IPlayerControlObject::removeVehicleMod"); } + int getVehicleMod(VehicleMod mod) override { unexpected("IPlayerControlObject::getVehicleMod"); } + const std::string& getSoundFilter() const override { unexpected("IPlayerControlObject::getSoundFilter"); } + int getCockpitLod() override { unexpected("IPlayerControlObject::getCockpitLod"); } + int getCockpitSubGeom() override { unexpected("IPlayerControlObject::getCockpitSubGeom"); } + float getShakeFactor() const override { unexpected("IPlayerControlObject::getShakeFactor"); } + bool getIsSprinting() const override { unexpected("IPlayerControlObject::getIsSprinting"); } + void setIsSprinting(bool) override { unexpected("IPlayerControlObject::setIsSprinting"); } + float getSprintStamina() const override { unexpected("IPlayerControlObject::getSprintStamina"); } + void setSprintStamina(float) override { unexpected("IPlayerControlObject::setSprintStamina"); } + void setSprintStaminaDissipationFactor(float) override { unexpected("IPlayerControlObject::setSprintStaminaDissipationFactor"); } + float getSprintFactor() override { unexpected("IPlayerControlObject::getSprintFactor"); } + bool getIsUnderwater() const override { unexpected("IPlayerControlObject::getIsUnderwater"); } + float getNormalizedUnderwaterTime() const override { unexpected("IPlayerControlObject::getNormalizedUnderwaterTime"); } + void setDriverDecalObject(IObject*) override { unexpected("IPlayerControlObject::setDriverDecalObject"); } + IObject* getDriverDecalObject() const override { unexpected("IPlayerControlObject::getDriverDecalObject"); } + void addDriverDecalTransformation(const Mat4&) override { unexpected("IPlayerControlObject::addDriverDecalTransformation"); } + std::vector* getDriverDecalTransformations() const override { unexpected("IPlayerControlObject::getDriverDecalTransformations"); } + int getSpecialToggleWeaponInput() const override { unexpected("IPlayerControlObject::getSpecialToggleWeaponInput"); } + void setIsDucking(bool) override { unexpected("IPlayerControlObject::setIsDucking"); } + bool getIsDucking() override { unexpected("IPlayerControlObject::getIsDucking"); } + bool getAutoUseAbility() const override { unexpected("IPlayerControlObject::getAutoUseAbility"); } + bool applyCameraAnimation(const Mat4& in, Mat4& out) override { unexpected("IPlayerControlObject::applyCameraAnimation"); } + bool allowEnterOtherVehicle() override { unexpected("IPlayerControlObject::allowEnterOtherVehicle"); } + bool isChildSoldierActive() const override { unexpected("IPlayerControlObject::isChildSoldierActive"); } + bool getNeverDrawAs1p() const override { unexpected("IPlayerControlObject::getNeverDrawAs1p"); } + void removeChildVehicle(IObject*) override { unexpected("IPlayerControlObject::removeChildVehicle"); } + int getAmmoStatus() override { unexpected("IPlayerControlObject::getAmmoStatus"); } + void setAmmoStatus(int) override { unexpected("IPlayerControlObject::setAmmoStatus"); } + void onFirstGhost() override { unexpected("IPlayerControlObject::onFirstGhost"); } + void setGiveUnmannedInput(bool) override { unexpected("IPlayerControlObject::setGiveUnmannedInput"); } + void preHandlePlayerInput(io::PlayerInput& input, float dt) const override { unexpected("IPlayerControlObject::preHandlePlayerInput"); } +}; +// Never constructed: updateShakeForce reads only the template field (IObject::getTemplate, inline). +struct ObjectFields : IObject { + static void setTemplate(IObject* o, const IObjectTemplate* t) { static_cast(o)->m_template = t; } +}; +} // namespace + +int main() +{ + FakeMaps maps; + FakeControlSettings controls; + Nothing deviceManager; + io::controlMapManager = &maps; + io::inputDeviceManager = &deviceManager; + g_controlSettings = &controls; + HapticSettings* hapticOwner = new HapticSettings; + g_hapticSettings = static_cast(hapticOwner); + IHapticSettings* haptics = static_cast(g_hapticSettings); + haptics->setAimSensitivity(2.0f, 3.0f, 0.5f); + haptics->setAimSensitivityLength(0.25f, 0.5f, 0.125f); + haptics->setTurnSensitivity(4.0f, 0.75f, 1.5f); + haptics->setControlBoxLength(0.75f, 1.25f, 0.5f); + haptics->setControlBoxStiffness(100.0f, 200.0f, 300.0f); + static NovintHFX::Stack stackObject; + g_stack = &stackObject; + + FalconDevice* device = new FalconDevice; + device->m_sampleTime = 0; + check(device->init() && device->m_active && device->m_device == &g_deviceObject, "fake device runs"); + check(fake::sdk.joined() == "attach foreground;recount;run 0;startMouse device;", "init's SDK sequence"); + check(g_falconMouseMode == 1 && g_falconControlBoxDirty, "shipped initial modes"); + fake::sdk.clear(); + + // --- mouse mode: raw position, gain 1000, StartMouse once, the axis scaling ----------------- + poll(*device, 1000, 0.5, 0.25, -0.125, 0x5); // sample clock 0 -> poll time 1000 + poll(*device, 1010, 0.75, -0.5, 0.25, 0x2); + check(device->m_samples.size() == 2 && device->m_sampleTime == 1000 && device->m_pollTime == 1010, + "update(0) queues samples and lags the sample clock one poll"); + maps.map.scale[0] = 2.0f; maps.map.scale[1] = 0.5f; maps.map.scale[2] = 4.0f; maps.map.scale[3] = 1.0f; + device->m_buttons = 0x40; + fake::sdk.clear(); + device->update(0.0205f); // +20 ms (0.0205*1000 truncates) + check(device->m_sampleTime == 1020, "dt*1000 truncates into the sample clock"); + check(device->m_samples.empty(), "both samples older than the clock are consumed"); + check(device->m_previousButtons == 0x40 && device->m_buttons == 0x2, "buttons: previous frame kept, last sample wins"); + check(fake::sdk.joined() == "startMouse device;buttons;buttons;", "StartMouse once, before the first sample's button read"); + check(g_falconMouseMode == 2, "mode 1 becomes 2 after StartMouse"); + check(same(device->m_axes[0], 1000.0 * 0.75 * 2.0) && same(device->m_axes[1], -(1000.0 * -0.5) * 0.5) + && same(device->m_axes[2], 0.0), "mouse axes: gain, negated y, the map's scale; z stays zero"); + check(io::inputSampleLatency == 0.0f, "latency (poll time - sample time) * 0.001"); + check(maps.map.invertReads == 4, "getInvertMouse read twice per sample (y and z)"); + check(maps.map.scaleReads == 4, "four axis-scale reads (the fourth-axis defect)"); + + // --- latency of an older sample ------------------------------------------------------------ + poll(*device, 1100, 0.0, 0.0, 0.0, 0); + poll(*device, 1137, 0.0, 0.0, 0.0, 0); + device->m_samples.pop_back(); // keep only the 1100 sample, polled at 1137 + device->update(0.2f); + check(io::inputSampleLatency == static_cast(37.0 * static_cast(0.001f)), "latency 37 ms"); + + // --- control-box mode: rebuild on mode 0, params from HapticSettings, effect created once -- + maps.map.scale[0] = maps.map.scale[1] = maps.map.scale[2] = 1.0f; + g_falconMouseMode = 0; + g_effect.m_stateFlags = 0; + fake::sdk.clear(); + poll(*device, 2000, 0.1, 0.1, 0.1, 0); // inside every dead zone + fake::sdk.clear(); + device->update(1.0f); + check(g_falconMouseMode == -1 && !g_falconControlBoxDirty, "mode 0 becomes -1 and clears the flag"); + check(fake::sdk.joined() == "params constructed;stack;create BOX ControlBox;update flags=0;params destroyed;buttons;", + "rebuild: construct, create once, update, delete"); + check(fake::liveParams == 0, "params deleted through the virtual destructor"); + check(fake::updates.size() == 1, "one parameter update"); + const fake::Captured& c = fake::updates.back(); + check(same(c.lower[0], -fromFloat(0.75f)) && same(c.lower[1], -fromFloat(1.25f)) + && same(c.lower[2], -fromFloat(0.5f) - fromFloat(0.01f)), "lower walls: -length, z 0.01 lower"); + check(same(c.upper[0], fromFloat(0.75f)) && same(c.upper[1], fromFloat(1.25f)) + && same(c.upper[2], fromFloat(0.5f) - fromFloat(0.01f)), "upper walls: length, z 0.01 lower"); + check(c.lowerStiffness[0] == 100.0 && c.lowerStiffness[1] == 200.0 && c.lowerStiffness[2] == 300.0 + && c.upperStiffness[0] == 100.0 && c.upperStiffness[2] == 300.0, "stiffness both sides"); + check(c.value114 == 3000, "+0x114 = 3000"); + + // --- no rebuild without the flag; the flag forces one; the effect is not created again ----- + fake::sdk.clear(); + poll(*device, 2100, 0.1, 0.1, 0.1, 0); + fake::sdk.clear(); + device->update(1.0f); + check(fake::sdk.joined() == "buttons;", "no rebuild while mode -1 and clean"); + g_falconControlBoxDirty = true; + g_effect.m_stateFlags = 1; + poll(*device, 2200, 0.1, 0.1, 0.1, 0); + fake::sdk.clear(); + device->update(1.0f); + check(fake::sdk.joined() == "params constructed;update flags=1;params destroyed;buttons;", + "the flag rebuilds into the existing effect"); + check(g_effect.m_stateFlags == 0, "rebuild clears the suspended bit"); + + // --- back to mouse mode: StartMouse and the suspended bit ---------------------------------- + g_falconMouseMode = 1; + poll(*device, 2300, 0.1, 0.1, 0.1, 0); + fake::sdk.clear(); + device->update(1.0f); + check(fake::sdk.joined() == "startMouse device;buttons;" && g_effect.m_stateFlags == 1 && g_falconMouseMode == 2, + "entering mouse mode suspends the existing control-box effect"); + g_falconMouseMode = -1; + + // --- dead zones, turn sensitivity and the smoothed deltas ----------------------------------- + // The smoothing history is already full (count == window); feed positions and check the axes. + // Each delta is (newest - oldest) / (2 * window) over aim-scaled positions. + std::vector hx, hy, hz; // model of the three histories after the earlier samples + // Rebuild the model by replaying: earlier samples were (0.5,.25,-.125),(0.75,-.5,.25),(0,0,0), + // then (0.1,0.1,0.1) x4; the first three were pushed raw, the rest aim-scaled with a pop. + hx = { 0.5, 0.75, 0.0 }; hy = { 0.25, -0.5, 0.0 }; hz = { -0.125, 0.25, 0.0 }; + auto step = [](std::vector& h, double v) { h.push_back(v); h.erase(h.begin()); return (h.back() - h.front()) / 6.0; }; + for (int i = 0; i < 4; ++i) { step(hx, 0.1 * 2.0f); step(hy, 0.1 * 3.0f); step(hz, 0.1 * 0.5f); } + struct Case { double x, y, z; const char* label; }; + const Case cases[] = { + { 0.5, 0.75, 0.5, "beyond the upper dead-zone edge" }, + { -0.5, -0.75, -0.5, "beyond the lower dead-zone edge" }, + { 0.2, 0.25, 0.1, "inside the dead zone: smoothed delta" }, + { std::numeric_limits::quiet_NaN(), 0.0, 0.0, "NaN takes the delta path" }, + }; + for (const Case& k : cases) { + poll(*device, g_tick + 100, k.x, k.y, k.z, 0); + device->update(1.0f); + const double dX = step(hx, k.x * 2.0f), dY = step(hy, k.y * 3.0f), dZ = step(hz, k.z * 0.5f); + auto expect = [](double p, float dz, float turn, double scale, double delta, double deltaScale) { + if (dz < p) return (p - dz) * turn * scale; + if (-dz > p) return (dz + p) * turn * scale; + return delta * deltaScale; + }; + const double ex = expect(k.x, 0.25f, 4.0f, 2000.0, dX, 2500.0); + const double ey = expect(k.y, 0.5f, 0.75f, -2000.0, dY, -2500.0); + const double ez = expect(k.z, 0.125f, 1.5f, -2000.0, dZ, -2500.0); + check(same(device->m_axes[0], ex) && same(device->m_axes[1], ey) && same(device->m_axes[2], ez), k.label); + } + + // --- inverted mouse negates y and z before everything --------------------------------------- + maps.map.invert = true; + poll(*device, g_tick + 100, 0.5, 0.75, 0.5, 0); + device->update(1.0f); + { + const double dX = step(hx, 0.5 * 2.0f), dY = step(hy, -0.75 * 3.0f), dZ = step(hz, -0.5 * 0.5f); + (void) dX; (void) dY; (void) dZ; + check(same(device->m_axes[1], (-0.75 + 0.5f) * 0.75f * -2000.0) + && same(device->m_axes[2], (-0.5 + 0.125f) * 1.5f * -2000.0), "inverted y and z"); + } + maps.map.invert = false; + + // --- binding capture ends the frame early --------------------------------------------------- + controls.mapping = true; + device->m_buttons = 0x9; + maps.map.scale[0] = 3.0f; + poll(*device, g_tick + 100, 0.5, 0.5, 0.5, 0x4); + const int scaleReadsBefore = maps.map.scaleReads; + fake::sdk.clear(); + device->update(1.0f); + check(device->m_samples.size() == 1, "capture: the sample stays queued"); + check(device->m_buttons == 0x9 && device->m_previousButtons == 0x9, "capture: no button read"); + check(device->m_axes[0] == 0.0 && device->m_axes[1] == 0.0 && device->m_axes[2] == 0.0, "capture: axes zeroed only"); + check(maps.map.scaleReads == scaleReadsBefore && fake::sdk.calls.empty(), "capture: no scaling, no SDK call"); + controls.mapping = false; + device->m_samples.clear(); + maps.map.scale[0] = 1.0f; + + // --- the fourth-axis defect: m_axisTravel[0..1] scaled as a double --------------------------- + { + const double bits = 1.5; + std::memcpy(device->m_axisTravel, &bits, sizeof(bits)); + device->m_axisTravel[2] = 7; + maps.map.scale[3] = 2.0f; + device->update(1.0f); // empty queue: only the scaling runs + double after; + std::memcpy(&after, device->m_axisTravel, sizeof(after)); + check(after == 3.0 && device->m_axisTravel[2] == 7, "fourth scale lands on m_axisTravel[0..1] only"); + maps.map.scale[3] = 1.0f; + std::memset(device->m_axisTravel, 0, sizeof(device->m_axisTravel)); + } + + // --- empty queue: axes reset, scaling only ------------------------------------------------ + device->m_axes[0] = 5.0; + device->update(1.0f); + check(device->m_axes[0] == 0.0 && device->m_axes[1] == 0.0, "every frame starts from zero axes"); + + // --- MainMenuLogic's zeroing of the haptic force effects (0x4A3490..0x4A3535) --------------- + { + fake::sdk.clear(); + fake::vect3Constructions = 0; + io::zeroHapticForceTargets(); + check(fake::sdk.calls.empty() && fake::vect3Constructions == 1, "no effects: one zero vector, no call"); + static FakeEffect targets[6] = { FakeEffect(0), FakeEffect(1), FakeEffect(2), FakeEffect(3), FakeEffect(4), FakeEffect(5) }; + for (int i = 0; i < 6; ++i) g_hapticForceTargets[i] = &targets[i]; + g_hapticForceTargets[3] = 0; // ds:0x9EBF04 absent + fake::sdk.clear(); + fake::vect3Constructions = 0; + io::zeroHapticForceTargets(); + check(fake::sdk.joined() == "force 2 0 0 0;force 4 0 0 0;force 5 0 0 0;force 0 0 0 0;force 1 0 0 0;", + "zero force in retail order 0x9EBF00..0x9EBF0C, 0x9EBEC8, 0x9EBECC; nulls skipped"); + check(fake::vect3Constructions == 1, "one Vect3 shared by every call"); + for (int i = 0; i < 6; ++i) g_hapticForceTargets[i] = 0; + } + + // --- Camera::handleUpdate's Novint ShakeForce block (0x5A3F4F..0x5A41D7, ledger N2 17b) -------- + { + ShakeTemplate vehicleTemplate, soldierTemplate; + vehicleTemplate.classId = 1; + soldierTemplate.classId = CID_SoldierTemplate; + alignas(16) static unsigned char occupiedStorage[sizeof(IObject)]; + IObject* occupied = reinterpret_cast(occupiedStorage); + ObjectFields::setTemplate(occupied, &vehicleTemplate); + ShakePco pco; + pco.occupied = occupied; + haptics->setExplosionShakeScale(2.0f); + haptics->setSpeedShakeScale(3.0f); + haptics->setGeneralShakeScale(0.5f); + haptics->setUnresolved48C(0.25f); + haptics->setUnresolved490(0.75f); + haptics->setForceCapX(10.0f); + haptics->setForceCapY(10.0f); + + NovintHFX::Device* const saved = io::g_falconDevice; + io::g_falconDevice = 0; + fake::sdk.clear(); + io::updateShakeForce(&pco, 0.1f, 0.2f, 0.4f, 0.8f); + check(fake::sdk.calls.empty() && !g_hapticForceTargets[0], "shake force: no device, nothing"); + io::g_falconDevice = saved; + check(io::g_falconDevice != 0, "shake force: the fake device is the current one"); + + fake::sdk.clear(); + fake::constantEffects = 0; + io::updateShakeForce(&pco, 0.1f, 0.2f, 0.4f, 0.8f); + check(fake::sdk.joined() == "constant params constructed;stack;create CONSTANT ShakeForce;stack;create CONSTANT ShakeForce;params destroyed;", + "shake force: first call creates the two CONSTANT ShakeForce effects from one params, then deletes it"); + check(fake::constantParam18 == 0x14 && g_hapticForceTargets[0] && g_hapticForceTargets[1] + && g_hapticForceTargets[0] != g_hapticForceTargets[1], "shake force: params +0x18 = 20; two effects stored"); + + fake::sdk.clear(); + io::updateShakeForce(&pco, 0.1f, 0.2f, 0.4f, 0.8f); + // x = 2*0.1 + 3*0.2 + 0.5*0.4 + 0.25*0.8 = 1.2; y = 2*0.1 + 3*0.2 + 0.5*0.4 + 0.75*0.8 = 1.6 + check(fake::sdk.joined() == "force 10 1.2 1.6 0;", "shake force: the vehicle effect gets (x, y, 0) from the scaled terms"); + + ObjectFields::setTemplate(occupied, &soldierTemplate); + haptics->setForceCapX(1.0f); + haptics->setForceCapY(1.6f); + fake::sdk.clear(); + io::updateShakeForce(&pco, 0.1f, 0.2f, 0.4f, 0.8f); + check(fake::sdk.joined() == "force 11 1 1.6 0;", "shake force: the soldier effect; x capped at 1"); + { + // y = 1.000000x (float) + 0.75 * 0.8f in double: |y| rounds to 1.6f, the cap, so it is not + // above it and keeps its unrounded value (a clamp would store 1.6f itself). + const float shared = 2.0f * 0.1f + 3.0f * 0.2f + 0.5f * 0.4f; + const double expectedY = static_cast(0.75f) * 0.8f + shared; + check(static_cast(expectedY) == 1.6f && expectedY != static_cast(1.6f) + && fake::lastForce[1] == expectedY, "shake force: y equal to its cap at float precision is not clamped"); + } + haptics->setForceCapY(1.5f); + fake::sdk.clear(); + io::updateShakeForce(&pco, -0.1f, -0.2f, -0.4f, -0.8f); + check(fake::sdk.joined() == "force 11 -1 -1.5 0;", "shake force: both caps keep the sign"); + // At cap 0 a -0 term is not above it and keeps its sign; a clamp would store sign(-0) * 0 = +0. + haptics->setForceCapX(0.0f); + haptics->setForceCapY(0.0f); + fake::sdk.clear(); + io::updateShakeForce(&pco, -0.0f, -0.0f, -0.0f, -0.0f); + check(fake::sdk.joined() == "force 11 -0 -0 0;", "shake force: -0 at a zero cap is left alone"); + // A negative cap is below every |v|: a zero term becomes sign(0) * cap = 0 * -1 = -0. + haptics->setForceCapX(-1.0f); + haptics->setForceCapY(-1.0f); + fake::sdk.clear(); + io::updateShakeForce(&pco, 0.0f, 0.0f, 0.0f, 0.0f); + check(fake::sdk.joined() == "force 11 -0 -0 0;", "shake force: a negative cap clamps a zero term with sign 0"); + for (int i = 0; i < 6; ++i) g_hapticForceTargets[i] = 0; + } + + // --- Soldier::handlePlayerInput's Novint "Recoil" block (0x5AE335..0x5AE72B, ledger N2 17b) ----- + { + NovintHFX::Device* const saved = io::g_falconDevice; + io::g_falconDevice = 0; + check(!io::hapticDeviceConnected(), "recoil force: no device, not connected"); + io::g_falconDevice = saved; + check(io::hapticDeviceConnected(), "recoil force: the fake device is connected"); + + fake::sdk.clear(); + fake::constantEffects = 0; + fake::constantParam18 = -1; + io::updateRecoilForce(0.0f, 0.0f, 0); + check(fake::sdk.joined() == "constant params constructed;stack;create Constant Recoil;params destroyed;force 10 0 0 0;", + "recoil force: first call creates the Constant \"Recoil\" effect, then sets a zero force"); + check(fake::constantParam18 == 10 && g_hapticForceTargets[2], "recoil force: params +0x18 = 10, stored at 0x9EBF00"); + + // Distinct scales per weapon type: yaw (t + 1) / 4, pitch (t + 1) / 8. + typedef void (IHapticSettings::*Setter)(float); + const Setter yawSetters[13] = { + &IHapticSettings::setRecoilYawScaleRIFLE, &IHapticSettings::setRecoilYawScaleRIFLELAUNCHER, + &IHapticSettings::setRecoilYawScaleCARBINE, &IHapticSettings::setRecoilYawScaleLMG, + &IHapticSettings::setRecoilYawScaleSNIPER, &IHapticSettings::setRecoilYawScalePISTOL, + &IHapticSettings::setRecoilYawScaleLAUNCHER, &IHapticSettings::setRecoilYawScaleSMG, + &IHapticSettings::setRecoilYawScaleSHOTGUN, &IHapticSettings::setRecoilYawScaleKNIFE, + &IHapticSettings::setRecoilYawScaleDROP, &IHapticSettings::setRecoilYawScaleTHROWN, + &IHapticSettings::setRecoilYawScaleDEFIB }; + const Setter pitchSetters[13] = { + &IHapticSettings::setRecoilPitchScaleRIFLE, &IHapticSettings::setRecoilPitchScaleRIFLELAUNCHER, + &IHapticSettings::setRecoilPitchScaleCARBINE, &IHapticSettings::setRecoilPitchScaleLMG, + &IHapticSettings::setRecoilPitchScaleSNIPER, &IHapticSettings::setRecoilPitchScalePISTOL, + &IHapticSettings::setRecoilPitchScaleLAUNCHER, &IHapticSettings::setRecoilPitchScaleSMG, + &IHapticSettings::setRecoilPitchScaleSHOTGUN, &IHapticSettings::setRecoilPitchScaleKNIFE, + &IHapticSettings::setRecoilPitchScaleDROP, &IHapticSettings::setRecoilPitchScaleTHROWN, + &IHapticSettings::setRecoilPitchScaleDEFIB }; + for (int t = 0; t < 13; ++t) { + (haptics->*yawSetters[t])((t + 1) / 4.0f); + (haptics->*pitchSetters[t])((t + 1) / 8.0f); + } + haptics->setForceCapX(100.0f); + haptics->setForceCapY(100.0f); + + fake::sdk.clear(); + io::updateRecoilForce(0.0f, 0.0f, 3); + check(fake::sdk.joined() == "force 10 0 0 0;", "recoil force: created once; both zero gives a zero force"); + + bool everyType = true; + for (int t = 0; t < 13; ++t) { + fake::sdk.clear(); + io::updateRecoilForce(2.0f, 4.0f, t); + const double ex = (t + 1) / 4.0 * 2.0, ey = -((t + 1) / 8.0 * 4.0); + everyType = everyType && fake::sdk.calls.size() == 1 + && fake::lastForce[0] == ex && fake::lastForce[1] == ey && fake::lastForce[2] == 0.0; + } + check(everyType, "recoil force: weapon types 0..12 select their own yaw and (negated) pitch scale"); + fake::sdk.clear(); + io::updateRecoilForce(2.0f, 4.0f, 13); + io::updateRecoilForce(2.0f, 4.0f, -1); + check(fake::sdk.joined() == "force 10 0 -0 0;force 10 0 -0 0;", "recoil force: other weapon types scale by 0"); + + fake::sdk.clear(); + io::updateRecoilForce(0.5f, 0.0f, 0); // RIFLE: 0.25 / 0.125 + io::updateRecoilForce(0.0f, 0.5f, 0); + check(fake::sdk.joined() == "force 10 0.125 -0 0;force 10 0 -0.0625 0;", "recoil force: either value alone is enough"); + + haptics->setForceCapX(1.5f); + haptics->setForceCapY(3.0f); + fake::sdk.clear(); + io::updateRecoilForce(2.0f, 3.0f, 0); + io::updateRecoilForce(-2.0f, -4.0f, 0); + check(fake::sdk.joined() == "force 10 0.375 -0.375 0;force 10 -0.375 0.375 0;", + "recoil force: each value capped with its sign; equal to the cap stays"); + haptics->setForceCapX(-1.0f); + fake::sdk.clear(); + io::updateRecoilForce(0.0f, 1.0f, 0); + check(fake::sdk.joined() == "force 10 -0 -0.125 0;", "recoil force: a negative cap clamps a zero term with sign 0"); + // At cap 0 a -0 pitch is not above it and keeps its sign: -(0.125 * -0) = +0 (a clamp: -0). + haptics->setForceCapX(100.0f); + haptics->setForceCapY(0.0f); + fake::sdk.clear(); + io::updateRecoilForce(1.0f, -0.0f, 0); + check(fake::sdk.joined() == "force 10 0.25 0 0;", "recoil force: -0 pitch at a zero cap is left alone"); + for (int i = 0; i < 6; ++i) g_hapticForceTargets[i] = 0; + } + + // --- Soldier::handlePlayerInput's Novint "CraftPhysics" block (0x5AECE8..0x5AF3F6, ledger N2 17b) -- + { + haptics->setPhysicsSOLDIERScale(2.0f, 3.0f, 4.0f); + haptics->setPhysicsSOLDIERScaleXLow(0.5f); haptics->setPhysicsSOLDIERScaleYLow(0.25f); haptics->setPhysicsSOLDIERScaleZLow(0.125f); + haptics->setPhysicsSOLDIERScaleXMed(5.0f); haptics->setPhysicsSOLDIERScaleYMed(6.0f); haptics->setPhysicsSOLDIERScaleZMed(7.0f); + haptics->setPhysicsSOLDIERScaleXHigh(10.0f); haptics->setPhysicsSOLDIERScaleYHigh(20.0f); haptics->setPhysicsSOLDIERScaleZHigh(30.0f); + haptics->setPhysicsSOLDIERTransitionValueMed(1.0f); + haptics->setPhysicsSOLDIERTransitionValueHigh(10.0f); + haptics->setPhysicsSOLDIERSmoothTimeXLow(11); haptics->setPhysicsSOLDIERSmoothTimeYLow(12); haptics->setPhysicsSOLDIERSmoothTimeZLow(13); + haptics->setPhysicsSOLDIERSmoothTimeXMed(97); haptics->setPhysicsSOLDIERSmoothTimeYMed(97); haptics->setPhysicsSOLDIERSmoothTimeZMed(97); + haptics->setPhysicsSOLDIERSmoothTimeXHigh(98); haptics->setPhysicsSOLDIERSmoothTimeYHigh(98); haptics->setPhysicsSOLDIERSmoothTimeZHigh(98); + haptics->setForceCapX(1000.0f); haptics->setForceCapY(1000.0f); haptics->setForceCapZ(1000.0f); + auto v3 = [](float x, float y, float z) { Vec3 v; v.x = x; v.y = y; v.z = z; return v; }; + + fake::sdk.clear(); + fake::constantEffects = 0; + fake::params18.clear(); + io::updateSoldierCraftPhysicsForce(v3(0, 0, 0), 0.1f); + check(fake::sdk.joined() == + "constant params constructed;stack;create Constant CraftPhysicsX;params destroyed;" + "constant params constructed;stack;create Constant CraftPhysicsY;params destroyed;" + "constant params constructed;stack;create Constant CraftPhysicsZ;params destroyed;" + "smooth 10 11;force 10 -0 0 0;smooth 11 12;force 11 0 -0 0;smooth 12 13;force 12 0 0 0;", + "craft physics: the three Constant effects are created once, then each gets its smooth time and axis"); + check(fake::params18 == "11,12,13," && g_hapticForceTargets[3] && g_hapticForceTargets[4] && g_hapticForceTargets[5], + "craft physics: params +0x18 = the X/Y/Z Low smooth times; stored at 0x9EBF04/08/0C"); + fake::sdk.clear(); + io::updateSoldierCraftPhysicsForce(v3(1, 0, 0), 0.2f); + io::updateSoldierCraftPhysicsForce(v3(2, 0, 0), 0.25f); + const std::string zeroTick = "smooth 10 11;force 10 -0 0 0;smooth 11 12;force 11 0 -0 0;smooth 12 13;force 12 0 0 0;"; + check(fake::sdk.joined() == zeroTick + zeroTick, "craft physics: no acceleration until three samples are held"); + + // History (1,0,0) (2,0,0) (4,8,-2); span 0.25 + 0.25: a = (oldest - newest) * 2 = (-6, -16, 4), + // |a| = 17.5 >= 10: High scales (20, 60, 120); Low smooth times still. + fake::sdk.clear(); + io::updateSoldierCraftPhysicsForce(v3(4, 8, -2), 0.25f); + check(fake::sdk.joined() == "smooth 10 11;force 10 120 0 0;smooth 11 12;force 11 0 960 0;smooth 12 13;force 12 0 0 480;", + "craft physics: oldest minus newest over the last two tick times; High band; -x, -y, +z"); + // (2,0,0) (4,8,-2) (2.5,1,0): a = (-1, -2, 0), |a| = 2.24: Med scales (10, 18, 28). + fake::sdk.clear(); + io::updateSoldierCraftPhysicsForce(v3(2.5f, 1, 0), 0.25f); + check(fake::sdk.joined() == "smooth 10 11;force 10 10 0 0;smooth 11 12;force 11 0 36 0;smooth 12 13;force 12 0 0 0;", + "craft physics: Med band"); + // (4,8,-2) (2.5,1,0) (4,8.25,-2): a = (0, -0.5, 0), |a| = 0.5: Low scales (1, 0.75, 0.5). + fake::sdk.clear(); + io::updateSoldierCraftPhysicsForce(v3(4, 8.25f, -2), 0.25f); + check(fake::sdk.joined() == "smooth 10 11;force 10 -0 0 0;smooth 11 12;force 11 0 0.375 0;smooth 12 13;force 12 0 0 0;", + "craft physics: Low band"); + // (2.5,1,0) (4,8.25,-2) (2.5,1.5,0): a = (0, -1, 0), |a| = 1 = Med's value: Med. + fake::sdk.clear(); + io::updateSoldierCraftPhysicsForce(v3(2.5f, 1.5f, 0), 0.25f); + check(fake::sdk.joined() == "smooth 10 11;force 10 -0 0 0;smooth 11 12;force 11 0 18 0;smooth 12 13;force 12 0 0 0;", + "craft physics: a length equal to the Med value is Med"); + // (4,8.25,-2) (2.5,1.5,0) (0,0,10): a = (8, 16.5, -24), High; capped to (5, 10, -20) with sign. + haptics->setForceCapX(5.0f); haptics->setForceCapY(10.0f); haptics->setForceCapZ(20.0f); + fake::sdk.clear(); + io::updateSoldierCraftPhysicsForce(v3(0, 0, 10), 0.25f); + check(fake::sdk.joined() == "smooth 10 11;force 10 -100 0 0;smooth 11 12;force 11 0 -600 0;smooth 12 13;force 12 0 0 -2400;", + "craft physics: each acceleration component capped with its sign"); + // (2.5,1.5,0) (0,0,10) (2.5,-3.5,0): a = (0, 10, 0), |a| = 10 = High's value: High (60); y equal + // to its cap is kept. + fake::sdk.clear(); + io::updateSoldierCraftPhysicsForce(v3(2.5f, -3.5f, 0), 0.25f); + check(fake::sdk.joined() == "smooth 10 11;force 10 -0 0 0;smooth 11 12;force 11 0 -600 0;smooth 12 13;force 12 0 0 0;", + "craft physics: a length equal to the High value is High; a component equal to its cap is kept"); + // (0,0,9) (0,0,5) (0,0,0) over 0.05 + 0.1: 1 / 0.15 stays unrounded for z (0x5A6370), so + // a.z = 59.999996f, not the 60 a rounded reciprocal gives; High: z force 120 * a.z. + haptics->setForceCapX(1e6f); haptics->setForceCapY(1e6f); haptics->setForceCapZ(1e6f); + io::updateSoldierCraftPhysicsForce(v3(0, 0, 9), 0.25f); + io::updateSoldierCraftPhysicsForce(v3(0, 0, 5), 0.05f); + io::updateSoldierCraftPhysicsForce(v3(0, 0, 0), 0.1f); + const float span = 0.05f + 0.1f; + const float unrounded = static_cast((1.0 / span) * 9.0f); + check(unrounded != static_cast(1.0 / span) * 9.0f && fake::lastForce[2] == 120.0 * unrounded, + "craft physics: z uses the unrounded reciprocal of the span"); + // (0,0,5) (0,0,0) (0,0,4.8) over 0.1 + 0.25: a.z = 0.2 / 0.35, Low: z force 0.5 * a.z. + io::updateSoldierCraftPhysicsForce(v3(0, 0, 4.8f), 0.25f); + check(std::fabs(fake::lastForce[2] - 0.5 * (0.2 / 0.35)) < 1e-5, "craft physics: Low band z scale"); + // (0,-0,0) (0,0,4.8) (0,0,0): a.y = -0; at cap 0 it is not above it and keeps its sign, so + // the y force is -(0.75 * -0) = +0 (a clamp would store sign(-0) * 0 = +0, giving -0). + io::updateSoldierCraftPhysicsForce(v3(0, -0.0f, 0), 0.25f); + io::updateSoldierCraftPhysicsForce(v3(0, 0, 4.8f), 0.25f); + haptics->setForceCapY(0.0f); + fake::sdk.clear(); + io::updateSoldierCraftPhysicsForce(v3(0, 0, 0), 0.25f); + check(fake::sdk.joined() == "smooth 10 11;force 10 -0 0 0;smooth 11 12;force 11 0 0 0;smooth 12 13;force 12 0 0 0;", + "craft physics: -0 at a zero cap is left alone"); + for (int i = 0; i < 6; ++i) g_hapticForceTargets[i] = 0; + } + + // --- PlayerControlObject::handleUpdate's CraftPhysics (0x5FADAE..0x5FBCD8): categories, band smooth times -- + { + auto v3 = [](float x, float y, float z) { Vec3 v; v.x = x; v.y = y; v.z = z; return v; }; + // c = 0 LAND, 1 SEA, 2 AIR, 3 HELI: Z scale (c+1) / (c+1)*10 / (c+1)*100, smooth (c+1)*100 + 1..9. + haptics->setPhysicsLANDScale(1.0f, 1.0f, 1.0f); + haptics->setPhysicsLANDScaleXLow(1.0f); haptics->setPhysicsLANDScaleYLow(1.0f); haptics->setPhysicsLANDScaleZLow(1.0f); + haptics->setPhysicsLANDScaleXMed(1.0f); haptics->setPhysicsLANDScaleYMed(1.0f); haptics->setPhysicsLANDScaleZMed(10.0f); + haptics->setPhysicsLANDScaleXHigh(1.0f); haptics->setPhysicsLANDScaleYHigh(1.0f); haptics->setPhysicsLANDScaleZHigh(100.0f); + haptics->setPhysicsLANDTransitionValueMed(1.0f); haptics->setPhysicsLANDTransitionValueHigh(10.0f); + haptics->setPhysicsLANDSmoothTimeXLow(101); haptics->setPhysicsLANDSmoothTimeYLow(102); haptics->setPhysicsLANDSmoothTimeZLow(103); + haptics->setPhysicsLANDSmoothTimeXMed(104); haptics->setPhysicsLANDSmoothTimeYMed(105); haptics->setPhysicsLANDSmoothTimeZMed(106); + haptics->setPhysicsLANDSmoothTimeXHigh(107); haptics->setPhysicsLANDSmoothTimeYHigh(108); haptics->setPhysicsLANDSmoothTimeZHigh(109); + haptics->setPhysicsSEAScale(1.0f, 1.0f, 1.0f); + haptics->setPhysicsSEAScaleXLow(1.0f); haptics->setPhysicsSEAScaleYLow(1.0f); haptics->setPhysicsSEAScaleZLow(2.0f); + haptics->setPhysicsSEAScaleXMed(1.0f); haptics->setPhysicsSEAScaleYMed(1.0f); haptics->setPhysicsSEAScaleZMed(20.0f); + haptics->setPhysicsSEAScaleXHigh(1.0f); haptics->setPhysicsSEAScaleYHigh(1.0f); haptics->setPhysicsSEAScaleZHigh(200.0f); + haptics->setPhysicsSEATransitionValueMed(1.0f); haptics->setPhysicsSEATransitionValueHigh(10.0f); + haptics->setPhysicsSEASmoothTimeXLow(201); haptics->setPhysicsSEASmoothTimeYLow(202); haptics->setPhysicsSEASmoothTimeZLow(203); + haptics->setPhysicsSEASmoothTimeXMed(204); haptics->setPhysicsSEASmoothTimeYMed(205); haptics->setPhysicsSEASmoothTimeZMed(206); + haptics->setPhysicsSEASmoothTimeXHigh(207); haptics->setPhysicsSEASmoothTimeYHigh(208); haptics->setPhysicsSEASmoothTimeZHigh(209); + haptics->setPhysicsAIRScale(1.0f, 1.0f, 1.0f); + haptics->setPhysicsAIRScaleXLow(1.0f); haptics->setPhysicsAIRScaleYLow(1.0f); haptics->setPhysicsAIRScaleZLow(3.0f); + haptics->setPhysicsAIRScaleXMed(1.0f); haptics->setPhysicsAIRScaleYMed(1.0f); haptics->setPhysicsAIRScaleZMed(30.0f); + haptics->setPhysicsAIRScaleXHigh(1.0f); haptics->setPhysicsAIRScaleYHigh(1.0f); haptics->setPhysicsAIRScaleZHigh(300.0f); + haptics->setPhysicsAIRTransitionValueMed(1.0f); haptics->setPhysicsAIRTransitionValueHigh(10.0f); + haptics->setPhysicsAIRSmoothTimeXLow(301); haptics->setPhysicsAIRSmoothTimeYLow(302); haptics->setPhysicsAIRSmoothTimeZLow(303); + haptics->setPhysicsAIRSmoothTimeXMed(304); haptics->setPhysicsAIRSmoothTimeYMed(305); haptics->setPhysicsAIRSmoothTimeZMed(306); + haptics->setPhysicsAIRSmoothTimeXHigh(307); haptics->setPhysicsAIRSmoothTimeYHigh(308); haptics->setPhysicsAIRSmoothTimeZHigh(309); + haptics->setPhysicsHELIScale(1.0f, 1.0f, 1.0f); + haptics->setPhysicsHELIScaleXLow(1.0f); haptics->setPhysicsHELIScaleYLow(1.0f); haptics->setPhysicsHELIScaleZLow(4.0f); + haptics->setPhysicsHELIScaleXMed(1.0f); haptics->setPhysicsHELIScaleYMed(1.0f); haptics->setPhysicsHELIScaleZMed(40.0f); + haptics->setPhysicsHELIScaleXHigh(1.0f); haptics->setPhysicsHELIScaleYHigh(1.0f); haptics->setPhysicsHELIScaleZHigh(400.0f); + haptics->setPhysicsHELITransitionValueMed(1.0f); haptics->setPhysicsHELITransitionValueHigh(10.0f); + haptics->setPhysicsHELISmoothTimeXLow(401); haptics->setPhysicsHELISmoothTimeYLow(402); haptics->setPhysicsHELISmoothTimeZLow(403); + haptics->setPhysicsHELISmoothTimeXMed(404); haptics->setPhysicsHELISmoothTimeYMed(405); haptics->setPhysicsHELISmoothTimeZMed(406); + haptics->setPhysicsHELISmoothTimeXHigh(407); haptics->setPhysicsHELISmoothTimeYHigh(408); haptics->setPhysicsHELISmoothTimeZHigh(409); + haptics->setForceCapX(1e6f); haptics->setForceCapY(1e6f); haptics->setForceCapZ(1e6f); + for (int i = 0; i < 6; ++i) g_hapticForceTargets[i] = 0; + auto tick = [](int x, int y, int z, const char* fz) { + return "smooth 10 " + std::to_string(x) + ";force 10 -0 0 0;smooth 11 " + std::to_string(y) + + ";force 11 0 -0 0;smooth 12 " + std::to_string(z) + ";force 12 0 0 " + fz + ";"; + }; + fake::sdk.clear(); + fake::constantEffects = 0; + fake::params18.clear(); + io::updateVehicleCraftPhysicsForce(v3(0, 0, 0), 0.25f, 0); + check(fake::params18 == "101,102,103," && fake::sdk.calls.size() == 18 + && fake::sdk.calls[12] == "smooth 10 101" && fake::sdk.calls[17] == "force 12 0 0 0", + "vehicle craft physics: its own effects-creation pass; LAND's Low smooth times"); + fake::sdk.clear(); + io::updateVehicleCraftPhysicsForce(v3(0, 0, 0), 0.25f, 1); + io::updateVehicleCraftPhysicsForce(v3(0, 0, 0), 0.25f, 2); + check(fake::sdk.joined() == tick(201, 202, 203, "0") + tick(301, 302, 303, "0"), + "vehicle craft physics: SEA and AIR Low smooth times while the history fills"); + // (0,0,0) (0,0,0) (0,0,-1): a.z = 2, Med: AIR z scale 30, Med smooth times. + fake::sdk.clear(); + io::updateVehicleCraftPhysicsForce(v3(0, 0, -1), 0.25f, 2); + check(fake::sdk.joined() == tick(304, 305, 306, "60"), "vehicle craft physics: AIR, Med band and Med smooth times"); + fake::sdk.clear(); + io::updateVehicleCraftPhysicsForce(v3(0, 0, -1), 0.25f, 3); + check(fake::sdk.joined() == tick(404, 405, 406, "80"), "vehicle craft physics: HELI, Med"); + fake::sdk.clear(); + io::updateVehicleCraftPhysicsForce(v3(0, 0, -1), 0.25f, 1); + check(fake::sdk.joined() == tick(201, 202, 203, "0"), "vehicle craft physics: SEA, Low (no acceleration)"); + // (0,0,-1) (0,0,-1) (0,0,-11): a.z = 20, High; category 7 falls back to LAND. + fake::sdk.clear(); + io::updateVehicleCraftPhysicsForce(v3(0, 0, -11), 0.25f, 7); + check(fake::sdk.joined() == tick(107, 108, 109, "2000"), "vehicle craft physics: an unknown category is LAND; High band and High smooth times"); + for (int i = 0; i < 6; ++i) g_hapticForceTargets[i] = 0; + } + + // --- The RecoilPunch envelope (0x6095EF..0x60968A) and SoldierBasedRecoilComp's choice (0x609353..) -- + { + haptics->setForceCapZ(5.0f); + fake::sdk.clear(); + io::fireRecoilPunch(2.9f, 0.5f, 3.0f); + check(fake::sdk.joined() == "envelope params constructed;stack;create Envelope RecoilPunch;envelope 2 -777 -777 1.5;params destroyed;", + "recoil punch: Envelope params, time truncated, z = scale * strength below the cap, not kept, deleted"); + fake::sdk.clear(); + io::fireRecoilPunch(-2.9f, 0.5f, 10.0f); + io::fireRecoilPunch(1.0f, 0.5f, -10.0f); + io::fireRecoilPunch(1.0f, 0.5f, -5.0f); + std::string got; + for (const std::string& c : fake::sdk.calls) if (c.compare(0, 9, "envelope ") == 0 && c.compare(0, 15, "envelope params") != 0) got += c + ";"; + check(got == "envelope -2 -777 -777 2.5;envelope 1 -777 -777 2.5;envelope 1 -777 -777 -2.5;", + "recoil punch: truncation toward zero; above the Z cap z = cap * scale without the sign; equal stays"); + + // Punch time t+1, scale (t+1)*10 per HapticSettings type; PISTOL also takes 5, 13 and -1. + typedef void (IHapticSettings::*Setter)(float); + const Setter times[13] = { + &IHapticSettings::setRecoilPunchTimeRIFLE, &IHapticSettings::setRecoilPunchTimeRIFLELAUNCHER, + &IHapticSettings::setRecoilPunchTimeCARBINE, &IHapticSettings::setRecoilPunchTimeLMG, + &IHapticSettings::setRecoilPunchTimeSNIPER, &IHapticSettings::setRecoilPunchTimePISTOL, + &IHapticSettings::setRecoilPunchTimeLAUNCHER, &IHapticSettings::setRecoilPunchTimeSMG, + &IHapticSettings::setRecoilPunchTimeSHOTGUN, &IHapticSettings::setRecoilPunchTimeKNIFE, + &IHapticSettings::setRecoilPunchTimeDROP, &IHapticSettings::setRecoilPunchTimeTHROWN, + &IHapticSettings::setRecoilPunchTimeDEFIB }; + const Setter scales[13] = { + &IHapticSettings::setRecoilPunchScaleRIFLE, &IHapticSettings::setRecoilPunchScaleRIFLELAUNCHER, + &IHapticSettings::setRecoilPunchScaleCARBINE, &IHapticSettings::setRecoilPunchScaleLMG, + &IHapticSettings::setRecoilPunchScaleSNIPER, &IHapticSettings::setRecoilPunchScalePISTOL, + &IHapticSettings::setRecoilPunchScaleLAUNCHER, &IHapticSettings::setRecoilPunchScaleSMG, + &IHapticSettings::setRecoilPunchScaleSHOTGUN, &IHapticSettings::setRecoilPunchScaleKNIFE, + &IHapticSettings::setRecoilPunchScaleDROP, &IHapticSettings::setRecoilPunchScaleTHROWN, + &IHapticSettings::setRecoilPunchScaleDEFIB }; + for (int t = 0; t < 13; ++t) { (haptics->*times[t])(t + 1.0f); (haptics->*scales[t])((t + 1) * 10.0f); } + haptics->setForceCapZ(1e6f); + bool everyType = true; + for (int t = 0; t < 13; ++t) { + fake::sdk.clear(); + io::soldierRecoilPunch(t, false, 0, 0, 0.0f, 0.0f, 0.0f, 1.0f); + char want[96]; + std::snprintf(want, sizeof(want), "envelope %d -777 -777 %.17g", t + 1, (t + 1) * 10.0); + everyType = everyType && fake::sdk.calls.size() == 5 && fake::sdk.calls[3] == want; + } + check(everyType, "recoil punch: weapon types 0..12 select their own punch time and scale"); + fake::sdk.clear(); + io::soldierRecoilPunch(13, false, 0, 0, 0.0f, 0.0f, 0.0f, 1.0f); + io::soldierRecoilPunch(-1, false, 0, 0, 0.0f, 0.0f, 0.0f, 1.0f); + got.clear(); + for (const std::string& c : fake::sdk.calls) if (c.compare(0, 9, "envelope ") == 0 && c.compare(0, 15, "envelope params") != 0) got += c + ";"; + check(got == "envelope 6 -777 -777 60;envelope 6 -777 -777 60;", "recoil punch: other weapon types use PISTOL's"); + + // With a random recoil force: time *= 4 samples; scale = -(((3 + 1) * 0.5) * 2 * 0.5) * 10 = -20. + const float graph[4] = { 9.0f, 9.0f, 9.0f, 0.5f }; + fake::sdk.clear(); + io::soldierRecoilPunch(0, true, 4, &graph[3], 1.0f, 3.0f, 2.0f, 1.5f); + check(fake::sdk.calls.size() == 5 && fake::sdk.calls[3] == "envelope 4 -777 -777 -30", + "recoil punch: a random recoil force scales the time by the samples and the scale by the graph's last sample"); + } + + // --- WeaponBasedRecoilComp's RecoilPunch choice (0x60A0E7..0x60A4F8) ------------------------------ + { + typedef void (IHapticSettings::*Setter)(float); + struct V { Setter time, scale, yaw, pitch; }; + const V types[7] = { + { &IHapticSettings::setRecoilPunchTimeV_LMG, &IHapticSettings::setRecoilPunchScaleV_LMG, &IHapticSettings::setRecoilYawScaleV_LMG, &IHapticSettings::setRecoilPitchScaleV_LMG }, + { &IHapticSettings::setRecoilPunchTimeV_HMG, &IHapticSettings::setRecoilPunchScaleV_HMG, &IHapticSettings::setRecoilYawScaleV_HMG, &IHapticSettings::setRecoilPitchScaleV_HMG }, + { &IHapticSettings::setRecoilPunchTimeV_HELIGUN, &IHapticSettings::setRecoilPunchScaleV_HELIGUN, &IHapticSettings::setRecoilYawScaleV_HELIGUN, &IHapticSettings::setRecoilPitchScaleV_HELIGUN }, + { &IHapticSettings::setRecoilPunchTimeV_AIRGUN, &IHapticSettings::setRecoilPunchScaleV_AIRGUN, &IHapticSettings::setRecoilYawScaleV_AIRGUN, &IHapticSettings::setRecoilPitchScaleV_AIRGUN }, + { &IHapticSettings::setRecoilPunchTimeV_MISSILE, &IHapticSettings::setRecoilPunchScaleV_MISSILE, &IHapticSettings::setRecoilYawScaleV_MISSILE, &IHapticSettings::setRecoilPitchScaleV_MISSILE }, + { &IHapticSettings::setRecoilPunchTimeV_ARMORCANNON, &IHapticSettings::setRecoilPunchScaleV_ARMORCANNON, &IHapticSettings::setRecoilYawScaleV_ARMORCANNON, &IHapticSettings::setRecoilPitchScaleV_ARMORCANNON }, + { &IHapticSettings::setRecoilPunchTimeV_COAXIALGUN, &IHapticSettings::setRecoilPunchScaleV_COAXIALGUN, &IHapticSettings::setRecoilYawScaleV_COAXIALGUN, &IHapticSettings::setRecoilPitchScaleV_COAXIALGUN } }; + for (int k = 0; k < 7; ++k) { + (haptics->*types[k].time)(k + 1.0f); + (haptics->*types[k].scale)((k + 1) * 10.0f); + (haptics->*types[k].yaw)((k + 1) * 0.25f); + (haptics->*types[k].pitch)((k + 1) * 0.125f); + } + haptics->setRecoilPunchTimeRIFLE(3.0f); haptics->setRecoilPunchScaleRIFLE(7.0f); + haptics->setRecoilYawScaleRIFLE(0.75f); haptics->setRecoilPitchScaleRIFLE(0.375f); + haptics->setForceCapZ(1e6f); + auto envelope = [&]() { + for (const std::string& c : fake::sdk.calls) + if (c.compare(0, 9, "envelope ") == 0 && c.compare(0, 15, "envelope params") != 0) return c; + return std::string("(none)"); + }; + bool everyType = true; + for (int k = 0; k < 7; ++k) { + fake::sdk.clear(); + haptics->setUnresolved48C(-1.0f); haptics->setUnresolved490(-1.0f); + io::weaponRecoilPunch(13 + k, "tankgun", 2.0f, 0.5f, 1.0f); // time (k+1)*2, scale (k+1)*10*0.5 + char want[96]; + std::snprintf(want, sizeof(want), "envelope %d -777 -777 %.17g", (k + 1) * 2, (k + 1) * 5.0); + everyType = everyType && envelope() == want && haptics->getUnresolved48C() == (k + 1) * 0.25f + && haptics->getUnresolved490() == (k + 1) * 0.125f; + } + check(everyType, "weapon recoil punch: types 13..19 take their own time and scale and set +0x48C/+0x490"); + fake::sdk.clear(); + io::weaponRecoilPunch(4, "US_FiringPort_M16", 2.0f, 0.5f, 1.0f); + check(envelope() == "envelope 6 -777 -777 3.5" && haptics->getUnresolved48C() == 0.75f && haptics->getUnresolved490() == 0.375f, + "weapon recoil punch: another type named *firingport* (any case) takes RIFLE's four values"); + fake::sdk.clear(); + io::weaponRecoilPunch(20, "tankgun", 2.9f, 0.5f, 1.0f); + check(envelope() == "envelope 2 -777 -777 0" && haptics->getUnresolved48C() == 0.0f && haptics->getUnresolved490() == 0.0f, + "weapon recoil punch: otherwise time 1 (times the speed), scale 0, and both set to 0"); + fake::sdk.clear(); + io::weaponRecoilPunch(12, "firingpor", 1.0f, 1.0f, 1.0f); + check(envelope() == "envelope 1 -777 -777 0", "weapon recoil punch: types below 13 are not vehicle types"); + } + + // --- GenericFireArm::postFire's kit RecoilPunch (0x5E2A98..0x5E2CDA) ------------------------------- + { + haptics->setRecoilPunchTimeKNIFE(2.0f); haptics->setRecoilPunchScaleKNIFE(20.0f); + haptics->setRecoilPunchTimeDROP(3.0f); haptics->setRecoilPunchScaleDROP(30.0f); + haptics->setRecoilPunchTimeTHROWN(4.0f); haptics->setRecoilPunchScaleTHROWN(40.0f); + haptics->setRecoilPunchTimeDEFIB(5.0f); haptics->setRecoilPunchScaleDEFIB(50.0f); + haptics->setForceCapZ(1e6f); + auto envelopes = [&]() { + std::string r; + for (const std::string& c : fake::sdk.calls) + if (c.compare(0, 9, "envelope ") == 0 && c.compare(0, 15, "envelope params") != 0) r += c + ";"; + return r; + }; + fake::sdk.clear(); + for (int t = 9; t <= 12; ++t) io::kitRecoilPunch(t, "rifle", 1.0f); + check(envelopes() == "envelope 2 -777 -777 20;envelope 3 -777 -777 30;envelope 4 -777 -777 40;envelope 5 -777 -777 50;", + "kit recoil punch: types 9..12 take KNIFE, DROP, THROWN, DEFIB"); + fake::sdk.clear(); + io::kitRecoilPunch(0, "US_MedKit", 1.0f); + io::kitRecoilPunch(13, "ch_WRENCH_2", 1.0f); + io::kitRecoilPunch(8, "knife", 1.0f); + io::kitRecoilPunch(8, "ki", 2.0f); + check(envelopes() == "envelope 3 -777 -777 30;envelope 3 -777 -777 30;envelope 1 -777 -777 0;envelope 1 -777 -777 0;", + "kit recoil punch: other types named *kit* or *wrench* (any case) take DROP's, else time 1 and scale 0"); + } + + // --- GameLogicDamage::serverGiveDamage's "Damage" envelope (0x5E6566..0x5E66A2) --------------------- + { + Mat4 lookAt, owner; + for (int i = 0; i < 16; ++i) { lookAt.m[i] = 0.0f; owner.m[i] = 0.0f; } + lookAt.m[8] = 0.48f; lookAt.m[9] = 0.6f; lookAt.m[10] = 0.64f; // the forward row + owner.m[0] = owner.m[5] = owner.m[10] = owner.m[15] = 1.0f; + haptics->setDamageScale(2.0f); + world::IPlayer* const local = reinterpret_cast(0x1000); + world::IPlayer* const other = reinterpret_cast(0x2000); + fake::sdk.clear(); + io::updateDamageForce(other, local, lookAt, owner, 10.0f); + check(fake::sdk.calls.empty(), "damage: another victim, nothing"); + NovintHFX::Device* const saved = io::g_falconDevice; + io::g_falconDevice = 0; + io::updateDamageForce(local, local, lookAt, owner, 10.0f); + io::g_falconDevice = saved; + check(fake::sdk.calls.empty(), "damage: no device, nothing"); + io::updateDamageForce(local, local, lookAt, owner, 10.0f); + // identity owner: (a, b, c) = (0.48, 0.6, 0.64); direction (-0.48, 0.6, 0.64) * (2 * 10 * 0.5) + const NovintHFX::Vect3 expected = NovintHFX::Vect3(-static_cast(0.48f), static_cast(0.6f), static_cast(0.64f)).Normalize() * 10.0; + NovintHFX::Vect3& e = const_cast(expected); + char want[160]; + std::snprintf(want, sizeof(want), "envelope 100 %.17g %.17g %.17g", e[0], e[1], e[2]); + check(fake::sdk.joined() == std::string("envelope params constructed;stack;create Envelope Damage;") + want + ";params destroyed;", + "damage: Envelope params +0x18 = 100, the normalized (-a, b, c) times scale * damage * 0.5, not kept"); + // Rotated owner: rows (0,0,1) (1,0,0) (0,1,0): a = 0.64, b = 0.48, c = 0.6. + for (int i = 0; i < 16; ++i) owner.m[i] = 0.0f; + owner.m[2] = 1.0f; owner.m[4] = 1.0f; owner.m[9] = 1.0f; owner.m[15] = 1.0f; + fake::sdk.clear(); + io::updateDamageForce(local, local, lookAt, owner, 10.0f); + const NovintHFX::Vect3 rotated = NovintHFX::Vect3(-static_cast(0.64f), static_cast(0.48f), static_cast(0.6f)).Normalize() * 10.0; + NovintHFX::Vect3& r = const_cast(rotated); + std::snprintf(want, sizeof(want), "envelope 100 %.17g %.17g %.17g", r[0], r[1], r[2]); + check(fake::sdk.calls.size() == 5 && fake::sdk.calls[3] == want, "damage: the forward row dotted with the owner's rows 0, 1, 2"); + } + + device->release(); + std::printf("falcon update runtime %u/%u checks passed\n", checks - failures, checks); + return failures ? 1 : 0; +} diff --git a/Code/Archive/NovintFalcon/Tests/falcon_vtable_restore.cmd b/Code/Archive/NovintFalcon/Tests/falcon_vtable_restore.cmd new file mode 100644 index 000000000..6bf986b92 --- /dev/null +++ b/Code/Archive/NovintFalcon/Tests/falcon_vtable_restore.cmd @@ -0,0 +1,45 @@ +@echo off +setlocal +rem [TEMP] MSVC check (game-frontier batch 16 N1): the instruction right after the imported +rem NovintHFX::ControlBoxEffectParams constructor call must store FalconControlBoxParams' local +rem vtable, as BF2.exe does at 0x6A58A1 (mov dword ptr [esi], 0x9116E0). Compiles FalconDevice.cpp for x86 /O2, +rem disassembles FalconDevice::updateCurrentState and prints PASS or FAIL with the lines it saw. +rem N2 also checks all Constant/Envelope constructor calls for the immediate local-vtable store: +rem at least three Constant sites are required; Envelope sites are optional until used. +rem Writes only under BF2_BUILD_OUT; no DLL is loaded and nothing runs. +call "%~dp0..\Build\vsdevcmd.cmd" x86 +set "TASK_ROOT=%~dp0..\.." +if not defined BF2_BUILD_OUT set "BF2_BUILD_OUT=%~dp0..\Build\obj_falcon_vtable_restore" +if not exist "%BF2_BUILD_OUT%" mkdir "%BF2_BUILD_OUT%" +set "TASK_FLAGS=/nologo /O2 /EHsc /std:c++14 /permissive /MD /Gy /DDEDICATED=0 /DBF2_PLUGIN_ABI_NATIVE=1 /D_ITERATOR_DEBUG_LEVEL=0" +cl %TASK_FLAGS% /FI"%TASK_ROOT%\Code\BF2\Core\BuildConfig.h" /c "%TASK_ROOT%\Code\BF2\IO\Input\FalconDevice.cpp" /Fo"%BF2_BUILD_OUT%\FalconDevice.obj" >"%BF2_BUILD_OUT%\compile.log" 2>&1 +if errorlevel 1 (type "%BF2_BUILD_OUT%\compile.log" & echo FAIL: compile & exit /b 1) +dumpbin /nologo /disasm "%BF2_BUILD_OUT%\FalconDevice.obj" >"%BF2_BUILD_OUT%\disasm.txt" +if errorlevel 1 (echo FAIL: dumpbin & exit /b 1) +powershell -NoProfile -ExecutionPolicy Bypass -Command ^ + "$l = Get-Content -LiteralPath '%BF2_BUILD_OUT%\disasm.txt';" ^ + "$allPass = $true; $s = -1; for ($i = 0; $i -lt $l.Count; $i++) { if ($l[$i] -match '^\?updateCurrentState@FalconDevice@io@hfe@dice@@') { $s = $i; break } }" ^ + "if ($s -lt 0) { Write-Output 'FAIL: ControlBoxEffectParams: updateCurrentState not found in the disassembly'; $allPass = $false } else {" ^ + "$e = $l.Count; for ($i = $s + 1; $i -lt $l.Count; $i++) { if ($l[$i] -match '^\?\S+:$' -or $l[$i] -match '^_\S+:$') { $e = $i; break } }" ^ + "$c = -1; for ($i = $s; $i -lt $e; $i++) { if ($l[$i] -match '__imp_\?\?0ControlBoxEffectParams@NovintHFX@@QAE@XZ') { $c = $i; break } }" ^ + "if ($c -lt 0) { Write-Output 'FAIL: no call of the imported ControlBoxEffectParams constructor'; $allPass = $false } else {" ^ + "$hit = $null; if ($l[$c + 1] -match 'mov\s+dword ptr \[\w+\],(offset )?\?\?_7FalconControlBoxParams@') { $hit = $l[$c + 1] }" ^ + "Write-Output '--- after the constructor call:'; $l[$c..([Math]::Min($c + 8, $e - 1))] | Write-Output;" ^ + "if ($hit) { Write-Output ('PASS: FalconControlBoxParams vtable stored right after the imported constructor: ' + $hit.Trim()) }" ^ + "else { Write-Output 'FAIL: the instruction after the ControlBoxEffectParams constructor call is not the store of ??_7FalconControlBoxParams'; $allPass = $false } } }" ^ + "foreach ($rule in @(@{ Base = 'ConstantEffectParams'; Derived = 'FalconConstantParams'; Minimum = 3 }, @{ Base = 'EnvelopeEffectParams'; Derived = 'FalconEnvelopeParams'; Minimum = 0 })) {" ^ + "$callPattern = '\bcall\s+.*' + [regex]::Escape('__imp_??0' + $rule.Base + '@NovintHFX@@QAE@XZ');" ^ + "$storePattern = 'mov\s+dword ptr \[\w+\],(offset )?' + [regex]::Escape('??_7' + $rule.Derived + '@');" ^ + "$count = 0; $bad = 0; $function = '';" ^ + "for ($i = 0; $i -lt $l.Count; $i++) {" ^ + "if ($l[$i] -match '^(\?\S+):$') { $function = $Matches[1] }" ^ + "if ($l[$i] -notmatch $callPattern) { continue }; $count++;" ^ + "$next = ''; if ($i + 1 -lt $l.Count) { $next = $l[$i + 1] }" ^ + "Write-Output ($rule.Base + ' site in ' + $function + ':'); Write-Output $next;" ^ + "if ($next -notmatch $storePattern) { $bad++ } }" ^ + "if ($count -eq 0 -and $rule.Base -eq 'EnvelopeEffectParams') { Write-Output 'no EnvelopeEffectParams sites yet' }" ^ + "if ($count -ge $rule.Minimum -and $bad -eq 0) { Write-Output ('PASS: ' + $rule.Base + ': ' + $count + ' sites, all immediate vtable stores valid') }" ^ + "else { Write-Output ('FAIL: ' + $rule.Base + ': ' + $count + ' sites (minimum ' + $rule.Minimum + '), ' + $bad + ' invalid immediate vtable stores'); $allPass = $false } }" ^ + "if ($allPass) { Write-Output 'PASS: all Falcon vtable restore rules'; exit 0 }" ^ + "Write-Output 'FAIL: Falcon vtable restore rules'; exit 1" +exit /b %errorlevel% diff --git a/Code/Archive/NovintFalcon/Tests/msvc_x86_layout/include/windows.h b/Code/Archive/NovintFalcon/Tests/msvc_x86_layout/include/windows.h new file mode 100644 index 000000000..ba988f0e6 --- /dev/null +++ b/Code/Archive/NovintFalcon/Tests/msvc_x86_layout/include/windows.h @@ -0,0 +1,4 @@ +// [TEMP] Stub for the Mac-side MSVC x86 layout checks: the two Win32 names NovintHFX.h uses. +#pragma once +typedef unsigned long DWORD; +typedef struct HWND__* HWND; diff --git a/Code/Archive/NovintFalcon/Tests/msvc_x86_layout/novint_x86_layout.cpp b/Code/Archive/NovintFalcon/Tests/msvc_x86_layout/novint_x86_layout.cpp new file mode 100644 index 000000000..799e241ea --- /dev/null +++ b/Code/Archive/NovintFalcon/Tests/msvc_x86_layout/novint_x86_layout.cpp @@ -0,0 +1,14 @@ +// [TEMP] Compiles NovintHFX.h for the MSVC x86 ABI from the Mac (bf2_novint_msvc_x86_layout): the +// header's own static_asserts check ControlBoxEffectParams (0x120 bytes, BF2.exe 0x6A587F) and its +// inline-written fields, and IHapticEffect's +0x0C flags. The real check is the Windows x86 build. +#include "../../BF2/External/NovintHFX/NovintHFX.h" +static_assert(sizeof(IHapticEffectParam) == 4, "interface: one vfptr"); +static_assert(sizeof(NovintHFX::BaseEffectParams) == 0x18, "base: vfptr + 20 bytes of SDK state"); +static_assert(sizeof(NovintHFX::Vect3) == 24, "three doubles"); +static_assert(sizeof(NovintHFX::ConstantEffectParams) == 0x20, "constant effect: x86 SDK ABI"); +static_assert(offsetof(NovintHFX::ConstantEffectParams, m_unresolved18) == 0x18, "x86 SDK ABI"); +static_assert(offsetof(NovintHFX::ConstantEffectParams, m_unresolved1C) == 0x1C, "x86 SDK ABI"); +static_assert(sizeof(NovintHFX::EnvelopeEffectParams) == 0x40, "envelope effect: x86 SDK ABI"); +static_assert(offsetof(NovintHFX::EnvelopeEffectParams, m_unresolved18) == 0x18, "x86 SDK ABI"); +static_assert(offsetof(NovintHFX::EnvelopeEffectParams, m_unresolved1C) == 0x1C, "x86 SDK ABI"); +static_assert(offsetof(NovintHFX::EnvelopeEffectParams, m_force) == 0x28, "x86 SDK ABI"); diff --git a/Code/Archive/NovintFalcon/Tests/novint_fake/windows.h b/Code/Archive/NovintFalcon/Tests/novint_fake/windows.h new file mode 100644 index 000000000..8dad68c2d --- /dev/null +++ b/Code/Archive/NovintFalcon/Tests/novint_fake/windows.h @@ -0,0 +1,9 @@ +// [TEMP] [CHOSEN, not recovered] Mac fake-SDK check only (bf2_falcon_update_check): the four +// Win32 names FalconDevice.cpp and NovintHFX.h use. The check defines the two functions. +#ifndef BF2_TESTS_NOVINT_FAKE_WINDOWS_H +#define BF2_TESTS_NOVINT_FAKE_WINDOWS_H +typedef unsigned int DWORD; +typedef void* HWND; +extern "C" DWORD GetTickCount(); +extern "C" HWND GetForegroundWindow(); +#endif diff --git a/Code/Archive/NovintFalcon/Tests/soldier_haptic_profile_runtime.cpp b/Code/Archive/NovintFalcon/Tests/soldier_haptic_profile_runtime.cpp new file mode 100644 index 000000000..8b75e73c9 --- /dev/null +++ b/Code/Archive/NovintFalcon/Tests/soldier_haptic_profile_runtime.cpp @@ -0,0 +1,1276 @@ +// [TEMP] [CHOSEN, not recovered] The Soldier's Novint control-box profile switch +// (Game/Objects/Game/SoldierHapticProfile.cpp, ledger N2 17a) against a complete fake HapticSettings and +// fake player-control templates (CTest bf2_soldier_haptic_profile_check). The fakes are generated from +// their headers and fail loudly for every call the code under test must not make. +#include "../BF2/Game/Objects/Game/SoldierHapticProfile.h" +#include "../BF2/Game/HapticSettings.h" +#include "../BF2/Game/Objects/IPlayerControlObjectTemplate.h" +#include "../BF2/Game/Objects/GenericFireArmTemplate.h" +#include "../BF2/Game/Objects/Weapons/GenericFireArm.h" +#include "../BF2/IO/Input/FalconHaptics.h" +#include "../BF2/Game/Objects/IObject.h" +#include "../BF2/Game/Objects/IPlayer.h" +#include "../BF2/Math/Mat4.h" +#include "../BF2/Physics/IPhysicsNode.h" +#include +#include +#include +#include +#include +#include + +using namespace dice::hfe; +using namespace dice::hfe::world; + +static unsigned checks, failures; +static void check(bool value, const std::string& label) +{ + ++checks; + if (!value) { ++failures; std::printf("FAIL %s\n", label.c_str()); } +} +[[noreturn]] static void unexpected(const char* name) +{ + std::fprintf(stderr, "[TEMP] soldier_haptic_profile check: unexpected call %s\n", name); + std::fflush(stderr); + std::abort(); +} +static std::vector calls; +static Vec3 v3(float x, float y, float z) +{ + Vec3 v; + v.x = x; + v.y = y; + v.z = z; + return v; +} +static std::string fmt(float x, float y, float z) +{ + char b[64]; + std::snprintf(b, sizeof(b), "%g %g %g", x, y, z); + return b; +} + +namespace dice { namespace hfe { +struct FakeHapticSettings final : IHapticSettings { + void addRef() override { unexpected("addRef"); } + int getRef() override { unexpected("getRef"); } + int release() override { unexpected("release"); } + void* queryInterface(unsigned int) const override { unexpected("queryInterface"); } + std::string getFileName() override { unexpected("IHapticSettings::getFileName"); } + std::string getSettingsScript() override { unexpected("IHapticSettings::getSettingsScript"); } + bool apply() override { unexpected("IHapticSettings::apply"); } + void setDefaults() override { unexpected("IHapticSettings::setDefaults"); } + void setDefaultValues() override { unexpected("IHapticSettings::setDefaultValues"); } + void loadCurrentProfileFile() override { unexpected("IHapticSettings::loadCurrentProfileFile"); } + bool reloadCurrentProfileFile() override { unexpected("IHapticSettings::reloadCurrentProfileFile"); } + float getForceCapX() override { unexpected("IHapticSettings::getForceCapX"); } + void setForceCapX(float) override { unexpected("IHapticSettings::setForceCapX"); } + float getForceCapY() override { unexpected("IHapticSettings::getForceCapY"); } + void setForceCapY(float) override { unexpected("IHapticSettings::setForceCapY"); } + float getForceCapZ() override { unexpected("IHapticSettings::getForceCapZ"); } + void setForceCapZ(float) override { unexpected("IHapticSettings::setForceCapZ"); } + Vec3 getControlBoxLength() override { unexpected("IHapticSettings::getControlBoxLength"); } + Vec3 getControlBoxStiffness() override { unexpected("IHapticSettings::getControlBoxStiffness"); } + void setControlBoxLengthSOLDIER(float x, float y, float z) override { unexpected("IHapticSettings::setControlBoxLengthSOLDIER"); } + void setControlBoxStiffnessSOLDIER(float x, float y, float z) override { unexpected("IHapticSettings::setControlBoxStiffnessSOLDIER"); } + void setControlBoxLengthAIR(float x, float y, float z) override { unexpected("IHapticSettings::setControlBoxLengthAIR"); } + void setControlBoxStiffnessAIR(float x, float y, float z) override { unexpected("IHapticSettings::setControlBoxStiffnessAIR"); } + void setControlBoxLengthHELI(float x, float y, float z) override { unexpected("IHapticSettings::setControlBoxLengthHELI"); } + void setControlBoxStiffnessHELI(float x, float y, float z) override { unexpected("IHapticSettings::setControlBoxStiffnessHELI"); } + void setControlBoxLengthLAND(float x, float y, float z) override { unexpected("IHapticSettings::setControlBoxLengthLAND"); } + void setControlBoxStiffnessLAND(float x, float y, float z) override { unexpected("IHapticSettings::setControlBoxStiffnessLAND"); } + void setControlBoxLengthSEA(float x, float y, float z) override { unexpected("IHapticSettings::setControlBoxLengthSEA"); } + void setControlBoxStiffnessSEA(float x, float y, float z) override { unexpected("IHapticSettings::setControlBoxStiffnessSEA"); } + Vec3 getAimSensitivity() override { unexpected("IHapticSettings::getAimSensitivity"); } + Vec3 getAimSensitivityLength() override { unexpected("IHapticSettings::getAimSensitivityLength"); } + Vec3 getTurnSensitivity() override { unexpected("IHapticSettings::getTurnSensitivity"); } + void setAimSensitivitySOLDIER(float x, float y, float z) override { unexpected("IHapticSettings::setAimSensitivitySOLDIER"); } + void setAimSensitivityLengthSOLDIER(float x, float y, float z) override { unexpected("IHapticSettings::setAimSensitivityLengthSOLDIER"); } + void setTurnSensitivitySOLDIER(float x, float y, float z) override { unexpected("IHapticSettings::setTurnSensitivitySOLDIER"); } + void setAimSensitivityAIR(float x, float y, float z) override { unexpected("IHapticSettings::setAimSensitivityAIR"); } + void setAimSensitivityLengthAIR(float x, float y, float z) override { unexpected("IHapticSettings::setAimSensitivityLengthAIR"); } + void setTurnSensitivityAIR(float x, float y, float z) override { unexpected("IHapticSettings::setTurnSensitivityAIR"); } + void setAimSensitivityHELI(float x, float y, float z) override { unexpected("IHapticSettings::setAimSensitivityHELI"); } + void setAimSensitivityLengthHELI(float x, float y, float z) override { unexpected("IHapticSettings::setAimSensitivityLengthHELI"); } + void setTurnSensitivityHELI(float x, float y, float z) override { unexpected("IHapticSettings::setTurnSensitivityHELI"); } + void setAimSensitivityLAND(float x, float y, float z) override { unexpected("IHapticSettings::setAimSensitivityLAND"); } + void setAimSensitivityLengthLAND(float x, float y, float z) override { unexpected("IHapticSettings::setAimSensitivityLengthLAND"); } + void setTurnSensitivityLAND(float x, float y, float z) override { unexpected("IHapticSettings::setTurnSensitivityLAND"); } + void setAimSensitivitySEA(float x, float y, float z) override { unexpected("IHapticSettings::setAimSensitivitySEA"); } + void setAimSensitivityLengthSEA(float x, float y, float z) override { unexpected("IHapticSettings::setAimSensitivityLengthSEA"); } + void setTurnSensitivitySEA(float x, float y, float z) override { unexpected("IHapticSettings::setTurnSensitivitySEA"); } + Vec3 getPhysicsSOLDIERScale() override { unexpected("IHapticSettings::getPhysicsSOLDIERScale"); } + void setPhysicsSOLDIERScale(float x, float y, float z) override { unexpected("IHapticSettings::setPhysicsSOLDIERScale"); } + float getPhysicsSOLDIERScaleXLow() override { unexpected("IHapticSettings::getPhysicsSOLDIERScaleXLow"); } + void setPhysicsSOLDIERScaleXLow(float) override { unexpected("IHapticSettings::setPhysicsSOLDIERScaleXLow"); } + float getPhysicsSOLDIERScaleYLow() override { unexpected("IHapticSettings::getPhysicsSOLDIERScaleYLow"); } + void setPhysicsSOLDIERScaleYLow(float) override { unexpected("IHapticSettings::setPhysicsSOLDIERScaleYLow"); } + float getPhysicsSOLDIERScaleZLow() override { unexpected("IHapticSettings::getPhysicsSOLDIERScaleZLow"); } + void setPhysicsSOLDIERScaleZLow(float) override { unexpected("IHapticSettings::setPhysicsSOLDIERScaleZLow"); } + float getPhysicsSOLDIERScaleXMed() override { unexpected("IHapticSettings::getPhysicsSOLDIERScaleXMed"); } + void setPhysicsSOLDIERScaleXMed(float) override { unexpected("IHapticSettings::setPhysicsSOLDIERScaleXMed"); } + float getPhysicsSOLDIERScaleYMed() override { unexpected("IHapticSettings::getPhysicsSOLDIERScaleYMed"); } + void setPhysicsSOLDIERScaleYMed(float) override { unexpected("IHapticSettings::setPhysicsSOLDIERScaleYMed"); } + float getPhysicsSOLDIERScaleZMed() override { unexpected("IHapticSettings::getPhysicsSOLDIERScaleZMed"); } + void setPhysicsSOLDIERScaleZMed(float) override { unexpected("IHapticSettings::setPhysicsSOLDIERScaleZMed"); } + float getPhysicsSOLDIERScaleXHigh() override { unexpected("IHapticSettings::getPhysicsSOLDIERScaleXHigh"); } + void setPhysicsSOLDIERScaleXHigh(float) override { unexpected("IHapticSettings::setPhysicsSOLDIERScaleXHigh"); } + float getPhysicsSOLDIERScaleYHigh() override { unexpected("IHapticSettings::getPhysicsSOLDIERScaleYHigh"); } + void setPhysicsSOLDIERScaleYHigh(float) override { unexpected("IHapticSettings::setPhysicsSOLDIERScaleYHigh"); } + float getPhysicsSOLDIERScaleZHigh() override { unexpected("IHapticSettings::getPhysicsSOLDIERScaleZHigh"); } + void setPhysicsSOLDIERScaleZHigh(float) override { unexpected("IHapticSettings::setPhysicsSOLDIERScaleZHigh"); } + float getPhysicsSOLDIERTransitionValue(int level) override { unexpected("IHapticSettings::getPhysicsSOLDIERTransitionValue"); } + void setPhysicsSOLDIERTransitionValue(int level, float value) override { unexpected("IHapticSettings::setPhysicsSOLDIERTransitionValue"); } + float getPhysicsSOLDIERTransitionValueMed() override { unexpected("IHapticSettings::getPhysicsSOLDIERTransitionValueMed"); } + void setPhysicsSOLDIERTransitionValueMed(float) override { unexpected("IHapticSettings::setPhysicsSOLDIERTransitionValueMed"); } + float getPhysicsSOLDIERTransitionValueHigh() override { unexpected("IHapticSettings::getPhysicsSOLDIERTransitionValueHigh"); } + void setPhysicsSOLDIERTransitionValueHigh(float) override { unexpected("IHapticSettings::setPhysicsSOLDIERTransitionValueHigh"); } + int getPhysicsSOLDIERSmoothTimeX(int level) override { unexpected("IHapticSettings::getPhysicsSOLDIERSmoothTimeX"); } + void setPhysicsSOLDIERSmoothTimeX(int level, int value) override { unexpected("IHapticSettings::setPhysicsSOLDIERSmoothTimeX"); } + int getPhysicsSOLDIERSmoothTimeY(int level) override { unexpected("IHapticSettings::getPhysicsSOLDIERSmoothTimeY"); } + void setPhysicsSOLDIERSmoothTimeY(int level, int value) override { unexpected("IHapticSettings::setPhysicsSOLDIERSmoothTimeY"); } + int getPhysicsSOLDIERSmoothTimeZ(int level) override { unexpected("IHapticSettings::getPhysicsSOLDIERSmoothTimeZ"); } + void setPhysicsSOLDIERSmoothTimeZ(int level, int value) override { unexpected("IHapticSettings::setPhysicsSOLDIERSmoothTimeZ"); } + int getPhysicsSOLDIERSmoothTimeXLow() override { unexpected("IHapticSettings::getPhysicsSOLDIERSmoothTimeXLow"); } + void setPhysicsSOLDIERSmoothTimeXLow(int) override { unexpected("IHapticSettings::setPhysicsSOLDIERSmoothTimeXLow"); } + int getPhysicsSOLDIERSmoothTimeYLow() override { unexpected("IHapticSettings::getPhysicsSOLDIERSmoothTimeYLow"); } + void setPhysicsSOLDIERSmoothTimeYLow(int) override { unexpected("IHapticSettings::setPhysicsSOLDIERSmoothTimeYLow"); } + int getPhysicsSOLDIERSmoothTimeZLow() override { unexpected("IHapticSettings::getPhysicsSOLDIERSmoothTimeZLow"); } + void setPhysicsSOLDIERSmoothTimeZLow(int) override { unexpected("IHapticSettings::setPhysicsSOLDIERSmoothTimeZLow"); } + int getPhysicsSOLDIERSmoothTimeXMed() override { unexpected("IHapticSettings::getPhysicsSOLDIERSmoothTimeXMed"); } + void setPhysicsSOLDIERSmoothTimeXMed(int) override { unexpected("IHapticSettings::setPhysicsSOLDIERSmoothTimeXMed"); } + int getPhysicsSOLDIERSmoothTimeYMed() override { unexpected("IHapticSettings::getPhysicsSOLDIERSmoothTimeYMed"); } + void setPhysicsSOLDIERSmoothTimeYMed(int) override { unexpected("IHapticSettings::setPhysicsSOLDIERSmoothTimeYMed"); } + int getPhysicsSOLDIERSmoothTimeZMed() override { unexpected("IHapticSettings::getPhysicsSOLDIERSmoothTimeZMed"); } + void setPhysicsSOLDIERSmoothTimeZMed(int) override { unexpected("IHapticSettings::setPhysicsSOLDIERSmoothTimeZMed"); } + int getPhysicsSOLDIERSmoothTimeXHigh() override { unexpected("IHapticSettings::getPhysicsSOLDIERSmoothTimeXHigh"); } + void setPhysicsSOLDIERSmoothTimeXHigh(int) override { unexpected("IHapticSettings::setPhysicsSOLDIERSmoothTimeXHigh"); } + int getPhysicsSOLDIERSmoothTimeYHigh() override { unexpected("IHapticSettings::getPhysicsSOLDIERSmoothTimeYHigh"); } + void setPhysicsSOLDIERSmoothTimeYHigh(int) override { unexpected("IHapticSettings::setPhysicsSOLDIERSmoothTimeYHigh"); } + int getPhysicsSOLDIERSmoothTimeZHigh() override { unexpected("IHapticSettings::getPhysicsSOLDIERSmoothTimeZHigh"); } + void setPhysicsSOLDIERSmoothTimeZHigh(int) override { unexpected("IHapticSettings::setPhysicsSOLDIERSmoothTimeZHigh"); } + Vec3 getPhysicsLANDScale() override { unexpected("IHapticSettings::getPhysicsLANDScale"); } + void setPhysicsLANDScale(float x, float y, float z) override { unexpected("IHapticSettings::setPhysicsLANDScale"); } + float getPhysicsLANDScaleXLow() override { unexpected("IHapticSettings::getPhysicsLANDScaleXLow"); } + void setPhysicsLANDScaleXLow(float) override { unexpected("IHapticSettings::setPhysicsLANDScaleXLow"); } + float getPhysicsLANDScaleYLow() override { unexpected("IHapticSettings::getPhysicsLANDScaleYLow"); } + void setPhysicsLANDScaleYLow(float) override { unexpected("IHapticSettings::setPhysicsLANDScaleYLow"); } + float getPhysicsLANDScaleZLow() override { unexpected("IHapticSettings::getPhysicsLANDScaleZLow"); } + void setPhysicsLANDScaleZLow(float) override { unexpected("IHapticSettings::setPhysicsLANDScaleZLow"); } + float getPhysicsLANDScaleXMed() override { unexpected("IHapticSettings::getPhysicsLANDScaleXMed"); } + void setPhysicsLANDScaleXMed(float) override { unexpected("IHapticSettings::setPhysicsLANDScaleXMed"); } + float getPhysicsLANDScaleYMed() override { unexpected("IHapticSettings::getPhysicsLANDScaleYMed"); } + void setPhysicsLANDScaleYMed(float) override { unexpected("IHapticSettings::setPhysicsLANDScaleYMed"); } + float getPhysicsLANDScaleZMed() override { unexpected("IHapticSettings::getPhysicsLANDScaleZMed"); } + void setPhysicsLANDScaleZMed(float) override { unexpected("IHapticSettings::setPhysicsLANDScaleZMed"); } + float getPhysicsLANDScaleXHigh() override { unexpected("IHapticSettings::getPhysicsLANDScaleXHigh"); } + void setPhysicsLANDScaleXHigh(float) override { unexpected("IHapticSettings::setPhysicsLANDScaleXHigh"); } + float getPhysicsLANDScaleYHigh() override { unexpected("IHapticSettings::getPhysicsLANDScaleYHigh"); } + void setPhysicsLANDScaleYHigh(float) override { unexpected("IHapticSettings::setPhysicsLANDScaleYHigh"); } + float getPhysicsLANDScaleZHigh() override { unexpected("IHapticSettings::getPhysicsLANDScaleZHigh"); } + void setPhysicsLANDScaleZHigh(float) override { unexpected("IHapticSettings::setPhysicsLANDScaleZHigh"); } + float getPhysicsLANDTransitionValue(int level) override { unexpected("IHapticSettings::getPhysicsLANDTransitionValue"); } + void setPhysicsLANDTransitionValue(int level, float value) override { unexpected("IHapticSettings::setPhysicsLANDTransitionValue"); } + float getPhysicsLANDTransitionValueMed() override { unexpected("IHapticSettings::getPhysicsLANDTransitionValueMed"); } + void setPhysicsLANDTransitionValueMed(float) override { unexpected("IHapticSettings::setPhysicsLANDTransitionValueMed"); } + float getPhysicsLANDTransitionValueHigh() override { unexpected("IHapticSettings::getPhysicsLANDTransitionValueHigh"); } + void setPhysicsLANDTransitionValueHigh(float) override { unexpected("IHapticSettings::setPhysicsLANDTransitionValueHigh"); } + int getPhysicsLANDSmoothTimeX(int level) override { unexpected("IHapticSettings::getPhysicsLANDSmoothTimeX"); } + void setPhysicsLANDSmoothTimeX(int level, int value) override { unexpected("IHapticSettings::setPhysicsLANDSmoothTimeX"); } + int getPhysicsLANDSmoothTimeY(int level) override { unexpected("IHapticSettings::getPhysicsLANDSmoothTimeY"); } + void setPhysicsLANDSmoothTimeY(int level, int value) override { unexpected("IHapticSettings::setPhysicsLANDSmoothTimeY"); } + int getPhysicsLANDSmoothTimeZ(int level) override { unexpected("IHapticSettings::getPhysicsLANDSmoothTimeZ"); } + void setPhysicsLANDSmoothTimeZ(int level, int value) override { unexpected("IHapticSettings::setPhysicsLANDSmoothTimeZ"); } + int getPhysicsLANDSmoothTimeXLow() override { unexpected("IHapticSettings::getPhysicsLANDSmoothTimeXLow"); } + void setPhysicsLANDSmoothTimeXLow(int) override { unexpected("IHapticSettings::setPhysicsLANDSmoothTimeXLow"); } + int getPhysicsLANDSmoothTimeYLow() override { unexpected("IHapticSettings::getPhysicsLANDSmoothTimeYLow"); } + void setPhysicsLANDSmoothTimeYLow(int) override { unexpected("IHapticSettings::setPhysicsLANDSmoothTimeYLow"); } + int getPhysicsLANDSmoothTimeZLow() override { unexpected("IHapticSettings::getPhysicsLANDSmoothTimeZLow"); } + void setPhysicsLANDSmoothTimeZLow(int) override { unexpected("IHapticSettings::setPhysicsLANDSmoothTimeZLow"); } + int getPhysicsLANDSmoothTimeXMed() override { unexpected("IHapticSettings::getPhysicsLANDSmoothTimeXMed"); } + void setPhysicsLANDSmoothTimeXMed(int) override { unexpected("IHapticSettings::setPhysicsLANDSmoothTimeXMed"); } + int getPhysicsLANDSmoothTimeYMed() override { unexpected("IHapticSettings::getPhysicsLANDSmoothTimeYMed"); } + void setPhysicsLANDSmoothTimeYMed(int) override { unexpected("IHapticSettings::setPhysicsLANDSmoothTimeYMed"); } + int getPhysicsLANDSmoothTimeZMed() override { unexpected("IHapticSettings::getPhysicsLANDSmoothTimeZMed"); } + void setPhysicsLANDSmoothTimeZMed(int) override { unexpected("IHapticSettings::setPhysicsLANDSmoothTimeZMed"); } + int getPhysicsLANDSmoothTimeXHigh() override { unexpected("IHapticSettings::getPhysicsLANDSmoothTimeXHigh"); } + void setPhysicsLANDSmoothTimeXHigh(int) override { unexpected("IHapticSettings::setPhysicsLANDSmoothTimeXHigh"); } + int getPhysicsLANDSmoothTimeYHigh() override { unexpected("IHapticSettings::getPhysicsLANDSmoothTimeYHigh"); } + void setPhysicsLANDSmoothTimeYHigh(int) override { unexpected("IHapticSettings::setPhysicsLANDSmoothTimeYHigh"); } + int getPhysicsLANDSmoothTimeZHigh() override { unexpected("IHapticSettings::getPhysicsLANDSmoothTimeZHigh"); } + void setPhysicsLANDSmoothTimeZHigh(int) override { unexpected("IHapticSettings::setPhysicsLANDSmoothTimeZHigh"); } + Vec3 getPhysicsAIRScale() override { unexpected("IHapticSettings::getPhysicsAIRScale"); } + void setPhysicsAIRScale(float x, float y, float z) override { unexpected("IHapticSettings::setPhysicsAIRScale"); } + float getPhysicsAIRScaleXLow() override { unexpected("IHapticSettings::getPhysicsAIRScaleXLow"); } + void setPhysicsAIRScaleXLow(float) override { unexpected("IHapticSettings::setPhysicsAIRScaleXLow"); } + float getPhysicsAIRScaleYLow() override { unexpected("IHapticSettings::getPhysicsAIRScaleYLow"); } + void setPhysicsAIRScaleYLow(float) override { unexpected("IHapticSettings::setPhysicsAIRScaleYLow"); } + float getPhysicsAIRScaleZLow() override { unexpected("IHapticSettings::getPhysicsAIRScaleZLow"); } + void setPhysicsAIRScaleZLow(float) override { unexpected("IHapticSettings::setPhysicsAIRScaleZLow"); } + float getPhysicsAIRScaleXMed() override { unexpected("IHapticSettings::getPhysicsAIRScaleXMed"); } + void setPhysicsAIRScaleXMed(float) override { unexpected("IHapticSettings::setPhysicsAIRScaleXMed"); } + float getPhysicsAIRScaleYMed() override { unexpected("IHapticSettings::getPhysicsAIRScaleYMed"); } + void setPhysicsAIRScaleYMed(float) override { unexpected("IHapticSettings::setPhysicsAIRScaleYMed"); } + float getPhysicsAIRScaleZMed() override { unexpected("IHapticSettings::getPhysicsAIRScaleZMed"); } + void setPhysicsAIRScaleZMed(float) override { unexpected("IHapticSettings::setPhysicsAIRScaleZMed"); } + float getPhysicsAIRScaleXHigh() override { unexpected("IHapticSettings::getPhysicsAIRScaleXHigh"); } + void setPhysicsAIRScaleXHigh(float) override { unexpected("IHapticSettings::setPhysicsAIRScaleXHigh"); } + float getPhysicsAIRScaleYHigh() override { unexpected("IHapticSettings::getPhysicsAIRScaleYHigh"); } + void setPhysicsAIRScaleYHigh(float) override { unexpected("IHapticSettings::setPhysicsAIRScaleYHigh"); } + float getPhysicsAIRScaleZHigh() override { unexpected("IHapticSettings::getPhysicsAIRScaleZHigh"); } + void setPhysicsAIRScaleZHigh(float) override { unexpected("IHapticSettings::setPhysicsAIRScaleZHigh"); } + float getPhysicsAIRTransitionValue(int level) override { unexpected("IHapticSettings::getPhysicsAIRTransitionValue"); } + void setPhysicsAIRTransitionValue(int level, float value) override { unexpected("IHapticSettings::setPhysicsAIRTransitionValue"); } + float getPhysicsAIRTransitionValueMed() override { unexpected("IHapticSettings::getPhysicsAIRTransitionValueMed"); } + void setPhysicsAIRTransitionValueMed(float) override { unexpected("IHapticSettings::setPhysicsAIRTransitionValueMed"); } + float getPhysicsAIRTransitionValueHigh() override { unexpected("IHapticSettings::getPhysicsAIRTransitionValueHigh"); } + void setPhysicsAIRTransitionValueHigh(float) override { unexpected("IHapticSettings::setPhysicsAIRTransitionValueHigh"); } + int getPhysicsAIRSmoothTimeX(int level) override { unexpected("IHapticSettings::getPhysicsAIRSmoothTimeX"); } + void setPhysicsAIRSmoothTimeX(int level, int value) override { unexpected("IHapticSettings::setPhysicsAIRSmoothTimeX"); } + int getPhysicsAIRSmoothTimeY(int level) override { unexpected("IHapticSettings::getPhysicsAIRSmoothTimeY"); } + void setPhysicsAIRSmoothTimeY(int level, int value) override { unexpected("IHapticSettings::setPhysicsAIRSmoothTimeY"); } + int getPhysicsAIRSmoothTimeZ(int level) override { unexpected("IHapticSettings::getPhysicsAIRSmoothTimeZ"); } + void setPhysicsAIRSmoothTimeZ(int level, int value) override { unexpected("IHapticSettings::setPhysicsAIRSmoothTimeZ"); } + int getPhysicsAIRSmoothTimeXLow() override { unexpected("IHapticSettings::getPhysicsAIRSmoothTimeXLow"); } + void setPhysicsAIRSmoothTimeXLow(int) override { unexpected("IHapticSettings::setPhysicsAIRSmoothTimeXLow"); } + int getPhysicsAIRSmoothTimeYLow() override { unexpected("IHapticSettings::getPhysicsAIRSmoothTimeYLow"); } + void setPhysicsAIRSmoothTimeYLow(int) override { unexpected("IHapticSettings::setPhysicsAIRSmoothTimeYLow"); } + int getPhysicsAIRSmoothTimeZLow() override { unexpected("IHapticSettings::getPhysicsAIRSmoothTimeZLow"); } + void setPhysicsAIRSmoothTimeZLow(int) override { unexpected("IHapticSettings::setPhysicsAIRSmoothTimeZLow"); } + int getPhysicsAIRSmoothTimeXMed() override { unexpected("IHapticSettings::getPhysicsAIRSmoothTimeXMed"); } + void setPhysicsAIRSmoothTimeXMed(int) override { unexpected("IHapticSettings::setPhysicsAIRSmoothTimeXMed"); } + int getPhysicsAIRSmoothTimeYMed() override { unexpected("IHapticSettings::getPhysicsAIRSmoothTimeYMed"); } + void setPhysicsAIRSmoothTimeYMed(int) override { unexpected("IHapticSettings::setPhysicsAIRSmoothTimeYMed"); } + int getPhysicsAIRSmoothTimeZMed() override { unexpected("IHapticSettings::getPhysicsAIRSmoothTimeZMed"); } + void setPhysicsAIRSmoothTimeZMed(int) override { unexpected("IHapticSettings::setPhysicsAIRSmoothTimeZMed"); } + int getPhysicsAIRSmoothTimeXHigh() override { unexpected("IHapticSettings::getPhysicsAIRSmoothTimeXHigh"); } + void setPhysicsAIRSmoothTimeXHigh(int) override { unexpected("IHapticSettings::setPhysicsAIRSmoothTimeXHigh"); } + int getPhysicsAIRSmoothTimeYHigh() override { unexpected("IHapticSettings::getPhysicsAIRSmoothTimeYHigh"); } + void setPhysicsAIRSmoothTimeYHigh(int) override { unexpected("IHapticSettings::setPhysicsAIRSmoothTimeYHigh"); } + int getPhysicsAIRSmoothTimeZHigh() override { unexpected("IHapticSettings::getPhysicsAIRSmoothTimeZHigh"); } + void setPhysicsAIRSmoothTimeZHigh(int) override { unexpected("IHapticSettings::setPhysicsAIRSmoothTimeZHigh"); } + Vec3 getPhysicsHELIScale() override { unexpected("IHapticSettings::getPhysicsHELIScale"); } + void setPhysicsHELIScale(float x, float y, float z) override { unexpected("IHapticSettings::setPhysicsHELIScale"); } + float getPhysicsHELIScaleXLow() override { unexpected("IHapticSettings::getPhysicsHELIScaleXLow"); } + void setPhysicsHELIScaleXLow(float) override { unexpected("IHapticSettings::setPhysicsHELIScaleXLow"); } + float getPhysicsHELIScaleYLow() override { unexpected("IHapticSettings::getPhysicsHELIScaleYLow"); } + void setPhysicsHELIScaleYLow(float) override { unexpected("IHapticSettings::setPhysicsHELIScaleYLow"); } + float getPhysicsHELIScaleZLow() override { unexpected("IHapticSettings::getPhysicsHELIScaleZLow"); } + void setPhysicsHELIScaleZLow(float) override { unexpected("IHapticSettings::setPhysicsHELIScaleZLow"); } + float getPhysicsHELIScaleXMed() override { unexpected("IHapticSettings::getPhysicsHELIScaleXMed"); } + void setPhysicsHELIScaleXMed(float) override { unexpected("IHapticSettings::setPhysicsHELIScaleXMed"); } + float getPhysicsHELIScaleYMed() override { unexpected("IHapticSettings::getPhysicsHELIScaleYMed"); } + void setPhysicsHELIScaleYMed(float) override { unexpected("IHapticSettings::setPhysicsHELIScaleYMed"); } + float getPhysicsHELIScaleZMed() override { unexpected("IHapticSettings::getPhysicsHELIScaleZMed"); } + void setPhysicsHELIScaleZMed(float) override { unexpected("IHapticSettings::setPhysicsHELIScaleZMed"); } + float getPhysicsHELIScaleXHigh() override { unexpected("IHapticSettings::getPhysicsHELIScaleXHigh"); } + void setPhysicsHELIScaleXHigh(float) override { unexpected("IHapticSettings::setPhysicsHELIScaleXHigh"); } + float getPhysicsHELIScaleYHigh() override { unexpected("IHapticSettings::getPhysicsHELIScaleYHigh"); } + void setPhysicsHELIScaleYHigh(float) override { unexpected("IHapticSettings::setPhysicsHELIScaleYHigh"); } + float getPhysicsHELIScaleZHigh() override { unexpected("IHapticSettings::getPhysicsHELIScaleZHigh"); } + void setPhysicsHELIScaleZHigh(float) override { unexpected("IHapticSettings::setPhysicsHELIScaleZHigh"); } + float getPhysicsHELITransitionValue(int level) override { unexpected("IHapticSettings::getPhysicsHELITransitionValue"); } + void setPhysicsHELITransitionValue(int level, float value) override { unexpected("IHapticSettings::setPhysicsHELITransitionValue"); } + float getPhysicsHELITransitionValueMed() override { unexpected("IHapticSettings::getPhysicsHELITransitionValueMed"); } + void setPhysicsHELITransitionValueMed(float) override { unexpected("IHapticSettings::setPhysicsHELITransitionValueMed"); } + float getPhysicsHELITransitionValueHigh() override { unexpected("IHapticSettings::getPhysicsHELITransitionValueHigh"); } + void setPhysicsHELITransitionValueHigh(float) override { unexpected("IHapticSettings::setPhysicsHELITransitionValueHigh"); } + int getPhysicsHELISmoothTimeX(int level) override { unexpected("IHapticSettings::getPhysicsHELISmoothTimeX"); } + void setPhysicsHELISmoothTimeX(int level, int value) override { unexpected("IHapticSettings::setPhysicsHELISmoothTimeX"); } + int getPhysicsHELISmoothTimeY(int level) override { unexpected("IHapticSettings::getPhysicsHELISmoothTimeY"); } + void setPhysicsHELISmoothTimeY(int level, int value) override { unexpected("IHapticSettings::setPhysicsHELISmoothTimeY"); } + int getPhysicsHELISmoothTimeZ(int level) override { unexpected("IHapticSettings::getPhysicsHELISmoothTimeZ"); } + void setPhysicsHELISmoothTimeZ(int level, int value) override { unexpected("IHapticSettings::setPhysicsHELISmoothTimeZ"); } + int getPhysicsHELISmoothTimeXLow() override { unexpected("IHapticSettings::getPhysicsHELISmoothTimeXLow"); } + void setPhysicsHELISmoothTimeXLow(int) override { unexpected("IHapticSettings::setPhysicsHELISmoothTimeXLow"); } + int getPhysicsHELISmoothTimeYLow() override { unexpected("IHapticSettings::getPhysicsHELISmoothTimeYLow"); } + void setPhysicsHELISmoothTimeYLow(int) override { unexpected("IHapticSettings::setPhysicsHELISmoothTimeYLow"); } + int getPhysicsHELISmoothTimeZLow() override { unexpected("IHapticSettings::getPhysicsHELISmoothTimeZLow"); } + void setPhysicsHELISmoothTimeZLow(int) override { unexpected("IHapticSettings::setPhysicsHELISmoothTimeZLow"); } + int getPhysicsHELISmoothTimeXMed() override { unexpected("IHapticSettings::getPhysicsHELISmoothTimeXMed"); } + void setPhysicsHELISmoothTimeXMed(int) override { unexpected("IHapticSettings::setPhysicsHELISmoothTimeXMed"); } + int getPhysicsHELISmoothTimeYMed() override { unexpected("IHapticSettings::getPhysicsHELISmoothTimeYMed"); } + void setPhysicsHELISmoothTimeYMed(int) override { unexpected("IHapticSettings::setPhysicsHELISmoothTimeYMed"); } + int getPhysicsHELISmoothTimeZMed() override { unexpected("IHapticSettings::getPhysicsHELISmoothTimeZMed"); } + void setPhysicsHELISmoothTimeZMed(int) override { unexpected("IHapticSettings::setPhysicsHELISmoothTimeZMed"); } + int getPhysicsHELISmoothTimeXHigh() override { unexpected("IHapticSettings::getPhysicsHELISmoothTimeXHigh"); } + void setPhysicsHELISmoothTimeXHigh(int) override { unexpected("IHapticSettings::setPhysicsHELISmoothTimeXHigh"); } + int getPhysicsHELISmoothTimeYHigh() override { unexpected("IHapticSettings::getPhysicsHELISmoothTimeYHigh"); } + void setPhysicsHELISmoothTimeYHigh(int) override { unexpected("IHapticSettings::setPhysicsHELISmoothTimeYHigh"); } + int getPhysicsHELISmoothTimeZHigh() override { unexpected("IHapticSettings::getPhysicsHELISmoothTimeZHigh"); } + void setPhysicsHELISmoothTimeZHigh(int) override { unexpected("IHapticSettings::setPhysicsHELISmoothTimeZHigh"); } + Vec3 getPhysicsSEAScale() override { unexpected("IHapticSettings::getPhysicsSEAScale"); } + void setPhysicsSEAScale(float x, float y, float z) override { unexpected("IHapticSettings::setPhysicsSEAScale"); } + float getPhysicsSEAScaleXLow() override { unexpected("IHapticSettings::getPhysicsSEAScaleXLow"); } + void setPhysicsSEAScaleXLow(float) override { unexpected("IHapticSettings::setPhysicsSEAScaleXLow"); } + float getPhysicsSEAScaleYLow() override { unexpected("IHapticSettings::getPhysicsSEAScaleYLow"); } + void setPhysicsSEAScaleYLow(float) override { unexpected("IHapticSettings::setPhysicsSEAScaleYLow"); } + float getPhysicsSEAScaleZLow() override { unexpected("IHapticSettings::getPhysicsSEAScaleZLow"); } + void setPhysicsSEAScaleZLow(float) override { unexpected("IHapticSettings::setPhysicsSEAScaleZLow"); } + float getPhysicsSEAScaleXMed() override { unexpected("IHapticSettings::getPhysicsSEAScaleXMed"); } + void setPhysicsSEAScaleXMed(float) override { unexpected("IHapticSettings::setPhysicsSEAScaleXMed"); } + float getPhysicsSEAScaleYMed() override { unexpected("IHapticSettings::getPhysicsSEAScaleYMed"); } + void setPhysicsSEAScaleYMed(float) override { unexpected("IHapticSettings::setPhysicsSEAScaleYMed"); } + float getPhysicsSEAScaleZMed() override { unexpected("IHapticSettings::getPhysicsSEAScaleZMed"); } + void setPhysicsSEAScaleZMed(float) override { unexpected("IHapticSettings::setPhysicsSEAScaleZMed"); } + float getPhysicsSEAScaleXHigh() override { unexpected("IHapticSettings::getPhysicsSEAScaleXHigh"); } + void setPhysicsSEAScaleXHigh(float) override { unexpected("IHapticSettings::setPhysicsSEAScaleXHigh"); } + float getPhysicsSEAScaleYHigh() override { unexpected("IHapticSettings::getPhysicsSEAScaleYHigh"); } + void setPhysicsSEAScaleYHigh(float) override { unexpected("IHapticSettings::setPhysicsSEAScaleYHigh"); } + float getPhysicsSEAScaleZHigh() override { unexpected("IHapticSettings::getPhysicsSEAScaleZHigh"); } + void setPhysicsSEAScaleZHigh(float) override { unexpected("IHapticSettings::setPhysicsSEAScaleZHigh"); } + float getPhysicsSEATransitionValue(int level) override { unexpected("IHapticSettings::getPhysicsSEATransitionValue"); } + void setPhysicsSEATransitionValue(int level, float value) override { unexpected("IHapticSettings::setPhysicsSEATransitionValue"); } + float getPhysicsSEATransitionValueMed() override { unexpected("IHapticSettings::getPhysicsSEATransitionValueMed"); } + void setPhysicsSEATransitionValueMed(float) override { unexpected("IHapticSettings::setPhysicsSEATransitionValueMed"); } + float getPhysicsSEATransitionValueHigh() override { unexpected("IHapticSettings::getPhysicsSEATransitionValueHigh"); } + void setPhysicsSEATransitionValueHigh(float) override { unexpected("IHapticSettings::setPhysicsSEATransitionValueHigh"); } + int getPhysicsSEASmoothTimeX(int level) override { unexpected("IHapticSettings::getPhysicsSEASmoothTimeX"); } + void setPhysicsSEASmoothTimeX(int level, int value) override { unexpected("IHapticSettings::setPhysicsSEASmoothTimeX"); } + int getPhysicsSEASmoothTimeY(int level) override { unexpected("IHapticSettings::getPhysicsSEASmoothTimeY"); } + void setPhysicsSEASmoothTimeY(int level, int value) override { unexpected("IHapticSettings::setPhysicsSEASmoothTimeY"); } + int getPhysicsSEASmoothTimeZ(int level) override { unexpected("IHapticSettings::getPhysicsSEASmoothTimeZ"); } + void setPhysicsSEASmoothTimeZ(int level, int value) override { unexpected("IHapticSettings::setPhysicsSEASmoothTimeZ"); } + int getPhysicsSEASmoothTimeXLow() override { unexpected("IHapticSettings::getPhysicsSEASmoothTimeXLow"); } + void setPhysicsSEASmoothTimeXLow(int) override { unexpected("IHapticSettings::setPhysicsSEASmoothTimeXLow"); } + int getPhysicsSEASmoothTimeYLow() override { unexpected("IHapticSettings::getPhysicsSEASmoothTimeYLow"); } + void setPhysicsSEASmoothTimeYLow(int) override { unexpected("IHapticSettings::setPhysicsSEASmoothTimeYLow"); } + int getPhysicsSEASmoothTimeZLow() override { unexpected("IHapticSettings::getPhysicsSEASmoothTimeZLow"); } + void setPhysicsSEASmoothTimeZLow(int) override { unexpected("IHapticSettings::setPhysicsSEASmoothTimeZLow"); } + int getPhysicsSEASmoothTimeXMed() override { unexpected("IHapticSettings::getPhysicsSEASmoothTimeXMed"); } + void setPhysicsSEASmoothTimeXMed(int) override { unexpected("IHapticSettings::setPhysicsSEASmoothTimeXMed"); } + int getPhysicsSEASmoothTimeYMed() override { unexpected("IHapticSettings::getPhysicsSEASmoothTimeYMed"); } + void setPhysicsSEASmoothTimeYMed(int) override { unexpected("IHapticSettings::setPhysicsSEASmoothTimeYMed"); } + int getPhysicsSEASmoothTimeZMed() override { unexpected("IHapticSettings::getPhysicsSEASmoothTimeZMed"); } + void setPhysicsSEASmoothTimeZMed(int) override { unexpected("IHapticSettings::setPhysicsSEASmoothTimeZMed"); } + int getPhysicsSEASmoothTimeXHigh() override { unexpected("IHapticSettings::getPhysicsSEASmoothTimeXHigh"); } + void setPhysicsSEASmoothTimeXHigh(int) override { unexpected("IHapticSettings::setPhysicsSEASmoothTimeXHigh"); } + int getPhysicsSEASmoothTimeYHigh() override { unexpected("IHapticSettings::getPhysicsSEASmoothTimeYHigh"); } + void setPhysicsSEASmoothTimeYHigh(int) override { unexpected("IHapticSettings::setPhysicsSEASmoothTimeYHigh"); } + int getPhysicsSEASmoothTimeZHigh() override { unexpected("IHapticSettings::getPhysicsSEASmoothTimeZHigh"); } + void setPhysicsSEASmoothTimeZHigh(int) override { unexpected("IHapticSettings::setPhysicsSEASmoothTimeZHigh"); } + float getDamageScale() override { unexpected("IHapticSettings::getDamageScale"); } + void setDamageScale(float) override { unexpected("IHapticSettings::setDamageScale"); } + float getRecoilPunchScale(int weaponClass) override { unexpected("IHapticSettings::getRecoilPunchScale"); } + void setRecoilPunchScale(int weaponClass, float value) override { unexpected("IHapticSettings::setRecoilPunchScale"); } + float getRecoilPunchTime(int weaponClass) override { unexpected("IHapticSettings::getRecoilPunchTime"); } + void setRecoilPunchTime(int weaponClass, float value) override { unexpected("IHapticSettings::setRecoilPunchTime"); } + float getRecoilYawScale(int weaponClass) override { unexpected("IHapticSettings::getRecoilYawScale"); } + void setRecoilYawScale(int weaponClass, float value) override { unexpected("IHapticSettings::setRecoilYawScale"); } + float getRecoilPitchScale(int weaponClass) override { unexpected("IHapticSettings::getRecoilPitchScale"); } + void setRecoilPitchScale(int weaponClass, float value) override { unexpected("IHapticSettings::setRecoilPitchScale"); } + float getRecoilPunchScaleRIFLE() override { unexpected("IHapticSettings::getRecoilPunchScaleRIFLE"); } + void setRecoilPunchScaleRIFLE(float) override { unexpected("IHapticSettings::setRecoilPunchScaleRIFLE"); } + float getRecoilPunchTimeRIFLE() override { unexpected("IHapticSettings::getRecoilPunchTimeRIFLE"); } + void setRecoilPunchTimeRIFLE(float) override { unexpected("IHapticSettings::setRecoilPunchTimeRIFLE"); } + float getRecoilYawScaleRIFLE() override { unexpected("IHapticSettings::getRecoilYawScaleRIFLE"); } + void setRecoilYawScaleRIFLE(float) override { unexpected("IHapticSettings::setRecoilYawScaleRIFLE"); } + float getRecoilPitchScaleRIFLE() override { unexpected("IHapticSettings::getRecoilPitchScaleRIFLE"); } + void setRecoilPitchScaleRIFLE(float) override { unexpected("IHapticSettings::setRecoilPitchScaleRIFLE"); } + float getRecoilPunchScaleRIFLELAUNCHER() override { unexpected("IHapticSettings::getRecoilPunchScaleRIFLELAUNCHER"); } + void setRecoilPunchScaleRIFLELAUNCHER(float) override { unexpected("IHapticSettings::setRecoilPunchScaleRIFLELAUNCHER"); } + float getRecoilPunchTimeRIFLELAUNCHER() override { unexpected("IHapticSettings::getRecoilPunchTimeRIFLELAUNCHER"); } + void setRecoilPunchTimeRIFLELAUNCHER(float) override { unexpected("IHapticSettings::setRecoilPunchTimeRIFLELAUNCHER"); } + float getRecoilYawScaleRIFLELAUNCHER() override { unexpected("IHapticSettings::getRecoilYawScaleRIFLELAUNCHER"); } + void setRecoilYawScaleRIFLELAUNCHER(float) override { unexpected("IHapticSettings::setRecoilYawScaleRIFLELAUNCHER"); } + float getRecoilPitchScaleRIFLELAUNCHER() override { unexpected("IHapticSettings::getRecoilPitchScaleRIFLELAUNCHER"); } + void setRecoilPitchScaleRIFLELAUNCHER(float) override { unexpected("IHapticSettings::setRecoilPitchScaleRIFLELAUNCHER"); } + float getRecoilPunchScaleCARBINE() override { unexpected("IHapticSettings::getRecoilPunchScaleCARBINE"); } + void setRecoilPunchScaleCARBINE(float) override { unexpected("IHapticSettings::setRecoilPunchScaleCARBINE"); } + float getRecoilPunchTimeCARBINE() override { unexpected("IHapticSettings::getRecoilPunchTimeCARBINE"); } + void setRecoilPunchTimeCARBINE(float) override { unexpected("IHapticSettings::setRecoilPunchTimeCARBINE"); } + float getRecoilYawScaleCARBINE() override { unexpected("IHapticSettings::getRecoilYawScaleCARBINE"); } + void setRecoilYawScaleCARBINE(float) override { unexpected("IHapticSettings::setRecoilYawScaleCARBINE"); } + float getRecoilPitchScaleCARBINE() override { unexpected("IHapticSettings::getRecoilPitchScaleCARBINE"); } + void setRecoilPitchScaleCARBINE(float) override { unexpected("IHapticSettings::setRecoilPitchScaleCARBINE"); } + float getRecoilPunchScaleLMG() override { unexpected("IHapticSettings::getRecoilPunchScaleLMG"); } + void setRecoilPunchScaleLMG(float) override { unexpected("IHapticSettings::setRecoilPunchScaleLMG"); } + float getRecoilPunchTimeLMG() override { unexpected("IHapticSettings::getRecoilPunchTimeLMG"); } + void setRecoilPunchTimeLMG(float) override { unexpected("IHapticSettings::setRecoilPunchTimeLMG"); } + float getRecoilYawScaleLMG() override { unexpected("IHapticSettings::getRecoilYawScaleLMG"); } + void setRecoilYawScaleLMG(float) override { unexpected("IHapticSettings::setRecoilYawScaleLMG"); } + float getRecoilPitchScaleLMG() override { unexpected("IHapticSettings::getRecoilPitchScaleLMG"); } + void setRecoilPitchScaleLMG(float) override { unexpected("IHapticSettings::setRecoilPitchScaleLMG"); } + float getRecoilPunchScaleSNIPER() override { unexpected("IHapticSettings::getRecoilPunchScaleSNIPER"); } + void setRecoilPunchScaleSNIPER(float) override { unexpected("IHapticSettings::setRecoilPunchScaleSNIPER"); } + float getRecoilPunchTimeSNIPER() override { unexpected("IHapticSettings::getRecoilPunchTimeSNIPER"); } + void setRecoilPunchTimeSNIPER(float) override { unexpected("IHapticSettings::setRecoilPunchTimeSNIPER"); } + float getRecoilYawScaleSNIPER() override { unexpected("IHapticSettings::getRecoilYawScaleSNIPER"); } + void setRecoilYawScaleSNIPER(float) override { unexpected("IHapticSettings::setRecoilYawScaleSNIPER"); } + float getRecoilPitchScaleSNIPER() override { unexpected("IHapticSettings::getRecoilPitchScaleSNIPER"); } + void setRecoilPitchScaleSNIPER(float) override { unexpected("IHapticSettings::setRecoilPitchScaleSNIPER"); } + float getRecoilPunchScalePISTOL() override { unexpected("IHapticSettings::getRecoilPunchScalePISTOL"); } + void setRecoilPunchScalePISTOL(float) override { unexpected("IHapticSettings::setRecoilPunchScalePISTOL"); } + float getRecoilPunchTimePISTOL() override { unexpected("IHapticSettings::getRecoilPunchTimePISTOL"); } + void setRecoilPunchTimePISTOL(float) override { unexpected("IHapticSettings::setRecoilPunchTimePISTOL"); } + float getRecoilYawScalePISTOL() override { unexpected("IHapticSettings::getRecoilYawScalePISTOL"); } + void setRecoilYawScalePISTOL(float) override { unexpected("IHapticSettings::setRecoilYawScalePISTOL"); } + float getRecoilPitchScalePISTOL() override { unexpected("IHapticSettings::getRecoilPitchScalePISTOL"); } + void setRecoilPitchScalePISTOL(float) override { unexpected("IHapticSettings::setRecoilPitchScalePISTOL"); } + float getRecoilPunchScaleLAUNCHER() override { unexpected("IHapticSettings::getRecoilPunchScaleLAUNCHER"); } + void setRecoilPunchScaleLAUNCHER(float) override { unexpected("IHapticSettings::setRecoilPunchScaleLAUNCHER"); } + float getRecoilPunchTimeLAUNCHER() override { unexpected("IHapticSettings::getRecoilPunchTimeLAUNCHER"); } + void setRecoilPunchTimeLAUNCHER(float) override { unexpected("IHapticSettings::setRecoilPunchTimeLAUNCHER"); } + float getRecoilYawScaleLAUNCHER() override { unexpected("IHapticSettings::getRecoilYawScaleLAUNCHER"); } + void setRecoilYawScaleLAUNCHER(float) override { unexpected("IHapticSettings::setRecoilYawScaleLAUNCHER"); } + float getRecoilPitchScaleLAUNCHER() override { unexpected("IHapticSettings::getRecoilPitchScaleLAUNCHER"); } + void setRecoilPitchScaleLAUNCHER(float) override { unexpected("IHapticSettings::setRecoilPitchScaleLAUNCHER"); } + float getRecoilPunchScaleSMG() override { unexpected("IHapticSettings::getRecoilPunchScaleSMG"); } + void setRecoilPunchScaleSMG(float) override { unexpected("IHapticSettings::setRecoilPunchScaleSMG"); } + float getRecoilPunchTimeSMG() override { unexpected("IHapticSettings::getRecoilPunchTimeSMG"); } + void setRecoilPunchTimeSMG(float) override { unexpected("IHapticSettings::setRecoilPunchTimeSMG"); } + float getRecoilYawScaleSMG() override { unexpected("IHapticSettings::getRecoilYawScaleSMG"); } + void setRecoilYawScaleSMG(float) override { unexpected("IHapticSettings::setRecoilYawScaleSMG"); } + float getRecoilPitchScaleSMG() override { unexpected("IHapticSettings::getRecoilPitchScaleSMG"); } + void setRecoilPitchScaleSMG(float) override { unexpected("IHapticSettings::setRecoilPitchScaleSMG"); } + float getRecoilPunchScaleSHOTGUN() override { unexpected("IHapticSettings::getRecoilPunchScaleSHOTGUN"); } + void setRecoilPunchScaleSHOTGUN(float) override { unexpected("IHapticSettings::setRecoilPunchScaleSHOTGUN"); } + float getRecoilPunchTimeSHOTGUN() override { unexpected("IHapticSettings::getRecoilPunchTimeSHOTGUN"); } + void setRecoilPunchTimeSHOTGUN(float) override { unexpected("IHapticSettings::setRecoilPunchTimeSHOTGUN"); } + float getRecoilYawScaleSHOTGUN() override { unexpected("IHapticSettings::getRecoilYawScaleSHOTGUN"); } + void setRecoilYawScaleSHOTGUN(float) override { unexpected("IHapticSettings::setRecoilYawScaleSHOTGUN"); } + float getRecoilPitchScaleSHOTGUN() override { unexpected("IHapticSettings::getRecoilPitchScaleSHOTGUN"); } + void setRecoilPitchScaleSHOTGUN(float) override { unexpected("IHapticSettings::setRecoilPitchScaleSHOTGUN"); } + float getRecoilPunchScaleKNIFE() override { unexpected("IHapticSettings::getRecoilPunchScaleKNIFE"); } + void setRecoilPunchScaleKNIFE(float) override { unexpected("IHapticSettings::setRecoilPunchScaleKNIFE"); } + float getRecoilPunchTimeKNIFE() override { unexpected("IHapticSettings::getRecoilPunchTimeKNIFE"); } + void setRecoilPunchTimeKNIFE(float) override { unexpected("IHapticSettings::setRecoilPunchTimeKNIFE"); } + float getRecoilYawScaleKNIFE() override { unexpected("IHapticSettings::getRecoilYawScaleKNIFE"); } + void setRecoilYawScaleKNIFE(float) override { unexpected("IHapticSettings::setRecoilYawScaleKNIFE"); } + float getRecoilPitchScaleKNIFE() override { unexpected("IHapticSettings::getRecoilPitchScaleKNIFE"); } + void setRecoilPitchScaleKNIFE(float) override { unexpected("IHapticSettings::setRecoilPitchScaleKNIFE"); } + float getRecoilPunchScaleDEFIB() override { unexpected("IHapticSettings::getRecoilPunchScaleDEFIB"); } + void setRecoilPunchScaleDEFIB(float) override { unexpected("IHapticSettings::setRecoilPunchScaleDEFIB"); } + float getRecoilPunchTimeDEFIB() override { unexpected("IHapticSettings::getRecoilPunchTimeDEFIB"); } + void setRecoilPunchTimeDEFIB(float) override { unexpected("IHapticSettings::setRecoilPunchTimeDEFIB"); } + float getRecoilYawScaleDEFIB() override { unexpected("IHapticSettings::getRecoilYawScaleDEFIB"); } + void setRecoilYawScaleDEFIB(float) override { unexpected("IHapticSettings::setRecoilYawScaleDEFIB"); } + float getRecoilPitchScaleDEFIB() override { unexpected("IHapticSettings::getRecoilPitchScaleDEFIB"); } + void setRecoilPitchScaleDEFIB(float) override { unexpected("IHapticSettings::setRecoilPitchScaleDEFIB"); } + float getRecoilPunchScaleDROP() override { unexpected("IHapticSettings::getRecoilPunchScaleDROP"); } + void setRecoilPunchScaleDROP(float) override { unexpected("IHapticSettings::setRecoilPunchScaleDROP"); } + float getRecoilPunchTimeDROP() override { unexpected("IHapticSettings::getRecoilPunchTimeDROP"); } + void setRecoilPunchTimeDROP(float) override { unexpected("IHapticSettings::setRecoilPunchTimeDROP"); } + float getRecoilYawScaleDROP() override { unexpected("IHapticSettings::getRecoilYawScaleDROP"); } + void setRecoilYawScaleDROP(float) override { unexpected("IHapticSettings::setRecoilYawScaleDROP"); } + float getRecoilPitchScaleDROP() override { unexpected("IHapticSettings::getRecoilPitchScaleDROP"); } + void setRecoilPitchScaleDROP(float) override { unexpected("IHapticSettings::setRecoilPitchScaleDROP"); } + float getRecoilPunchScaleTHROWN() override { unexpected("IHapticSettings::getRecoilPunchScaleTHROWN"); } + void setRecoilPunchScaleTHROWN(float) override { unexpected("IHapticSettings::setRecoilPunchScaleTHROWN"); } + float getRecoilPunchTimeTHROWN() override { unexpected("IHapticSettings::getRecoilPunchTimeTHROWN"); } + void setRecoilPunchTimeTHROWN(float) override { unexpected("IHapticSettings::setRecoilPunchTimeTHROWN"); } + float getRecoilYawScaleTHROWN() override { unexpected("IHapticSettings::getRecoilYawScaleTHROWN"); } + void setRecoilYawScaleTHROWN(float) override { unexpected("IHapticSettings::setRecoilYawScaleTHROWN"); } + float getRecoilPitchScaleTHROWN() override { unexpected("IHapticSettings::getRecoilPitchScaleTHROWN"); } + void setRecoilPitchScaleTHROWN(float) override { unexpected("IHapticSettings::setRecoilPitchScaleTHROWN"); } + float getRecoilPunchScaleV_LMG() override { unexpected("IHapticSettings::getRecoilPunchScaleV_LMG"); } + void setRecoilPunchScaleV_LMG(float) override { unexpected("IHapticSettings::setRecoilPunchScaleV_LMG"); } + float getRecoilPunchTimeV_LMG() override { unexpected("IHapticSettings::getRecoilPunchTimeV_LMG"); } + void setRecoilPunchTimeV_LMG(float) override { unexpected("IHapticSettings::setRecoilPunchTimeV_LMG"); } + float getRecoilYawScaleV_LMG() override { unexpected("IHapticSettings::getRecoilYawScaleV_LMG"); } + void setRecoilYawScaleV_LMG(float) override { unexpected("IHapticSettings::setRecoilYawScaleV_LMG"); } + float getRecoilPitchScaleV_LMG() override { unexpected("IHapticSettings::getRecoilPitchScaleV_LMG"); } + void setRecoilPitchScaleV_LMG(float) override { unexpected("IHapticSettings::setRecoilPitchScaleV_LMG"); } + float getRecoilPunchScaleV_HMG() override { unexpected("IHapticSettings::getRecoilPunchScaleV_HMG"); } + void setRecoilPunchScaleV_HMG(float) override { unexpected("IHapticSettings::setRecoilPunchScaleV_HMG"); } + float getRecoilPunchTimeV_HMG() override { unexpected("IHapticSettings::getRecoilPunchTimeV_HMG"); } + void setRecoilPunchTimeV_HMG(float) override { unexpected("IHapticSettings::setRecoilPunchTimeV_HMG"); } + float getRecoilYawScaleV_HMG() override { unexpected("IHapticSettings::getRecoilYawScaleV_HMG"); } + void setRecoilYawScaleV_HMG(float) override { unexpected("IHapticSettings::setRecoilYawScaleV_HMG"); } + float getRecoilPitchScaleV_HMG() override { unexpected("IHapticSettings::getRecoilPitchScaleV_HMG"); } + void setRecoilPitchScaleV_HMG(float) override { unexpected("IHapticSettings::setRecoilPitchScaleV_HMG"); } + float getRecoilPunchScaleV_HELIGUN() override { unexpected("IHapticSettings::getRecoilPunchScaleV_HELIGUN"); } + void setRecoilPunchScaleV_HELIGUN(float) override { unexpected("IHapticSettings::setRecoilPunchScaleV_HELIGUN"); } + float getRecoilPunchTimeV_HELIGUN() override { unexpected("IHapticSettings::getRecoilPunchTimeV_HELIGUN"); } + void setRecoilPunchTimeV_HELIGUN(float) override { unexpected("IHapticSettings::setRecoilPunchTimeV_HELIGUN"); } + float getRecoilYawScaleV_HELIGUN() override { unexpected("IHapticSettings::getRecoilYawScaleV_HELIGUN"); } + void setRecoilYawScaleV_HELIGUN(float) override { unexpected("IHapticSettings::setRecoilYawScaleV_HELIGUN"); } + float getRecoilPitchScaleV_HELIGUN() override { unexpected("IHapticSettings::getRecoilPitchScaleV_HELIGUN"); } + void setRecoilPitchScaleV_HELIGUN(float) override { unexpected("IHapticSettings::setRecoilPitchScaleV_HELIGUN"); } + float getRecoilPunchScaleV_AIRGUN() override { unexpected("IHapticSettings::getRecoilPunchScaleV_AIRGUN"); } + void setRecoilPunchScaleV_AIRGUN(float) override { unexpected("IHapticSettings::setRecoilPunchScaleV_AIRGUN"); } + float getRecoilPunchTimeV_AIRGUN() override { unexpected("IHapticSettings::getRecoilPunchTimeV_AIRGUN"); } + void setRecoilPunchTimeV_AIRGUN(float) override { unexpected("IHapticSettings::setRecoilPunchTimeV_AIRGUN"); } + float getRecoilYawScaleV_AIRGUN() override { unexpected("IHapticSettings::getRecoilYawScaleV_AIRGUN"); } + void setRecoilYawScaleV_AIRGUN(float) override { unexpected("IHapticSettings::setRecoilYawScaleV_AIRGUN"); } + float getRecoilPitchScaleV_AIRGUN() override { unexpected("IHapticSettings::getRecoilPitchScaleV_AIRGUN"); } + void setRecoilPitchScaleV_AIRGUN(float) override { unexpected("IHapticSettings::setRecoilPitchScaleV_AIRGUN"); } + float getRecoilPunchScaleV_MISSILE() override { unexpected("IHapticSettings::getRecoilPunchScaleV_MISSILE"); } + void setRecoilPunchScaleV_MISSILE(float) override { unexpected("IHapticSettings::setRecoilPunchScaleV_MISSILE"); } + float getRecoilPunchTimeV_MISSILE() override { unexpected("IHapticSettings::getRecoilPunchTimeV_MISSILE"); } + void setRecoilPunchTimeV_MISSILE(float) override { unexpected("IHapticSettings::setRecoilPunchTimeV_MISSILE"); } + float getRecoilYawScaleV_MISSILE() override { unexpected("IHapticSettings::getRecoilYawScaleV_MISSILE"); } + void setRecoilYawScaleV_MISSILE(float) override { unexpected("IHapticSettings::setRecoilYawScaleV_MISSILE"); } + float getRecoilPitchScaleV_MISSILE() override { unexpected("IHapticSettings::getRecoilPitchScaleV_MISSILE"); } + void setRecoilPitchScaleV_MISSILE(float) override { unexpected("IHapticSettings::setRecoilPitchScaleV_MISSILE"); } + float getRecoilPunchScaleV_ARMORCANNON() override { unexpected("IHapticSettings::getRecoilPunchScaleV_ARMORCANNON"); } + void setRecoilPunchScaleV_ARMORCANNON(float) override { unexpected("IHapticSettings::setRecoilPunchScaleV_ARMORCANNON"); } + float getRecoilPunchTimeV_ARMORCANNON() override { unexpected("IHapticSettings::getRecoilPunchTimeV_ARMORCANNON"); } + void setRecoilPunchTimeV_ARMORCANNON(float) override { unexpected("IHapticSettings::setRecoilPunchTimeV_ARMORCANNON"); } + float getRecoilYawScaleV_ARMORCANNON() override { unexpected("IHapticSettings::getRecoilYawScaleV_ARMORCANNON"); } + void setRecoilYawScaleV_ARMORCANNON(float) override { unexpected("IHapticSettings::setRecoilYawScaleV_ARMORCANNON"); } + float getRecoilPitchScaleV_ARMORCANNON() override { unexpected("IHapticSettings::getRecoilPitchScaleV_ARMORCANNON"); } + void setRecoilPitchScaleV_ARMORCANNON(float) override { unexpected("IHapticSettings::setRecoilPitchScaleV_ARMORCANNON"); } + float getRecoilPunchScaleV_COAXIALGUN() override { unexpected("IHapticSettings::getRecoilPunchScaleV_COAXIALGUN"); } + void setRecoilPunchScaleV_COAXIALGUN(float) override { unexpected("IHapticSettings::setRecoilPunchScaleV_COAXIALGUN"); } + float getRecoilPunchTimeV_COAXIALGUN() override { unexpected("IHapticSettings::getRecoilPunchTimeV_COAXIALGUN"); } + void setRecoilPunchTimeV_COAXIALGUN(float) override { unexpected("IHapticSettings::setRecoilPunchTimeV_COAXIALGUN"); } + float getRecoilYawScaleV_COAXIALGUN() override { unexpected("IHapticSettings::getRecoilYawScaleV_COAXIALGUN"); } + void setRecoilYawScaleV_COAXIALGUN(float) override { unexpected("IHapticSettings::setRecoilYawScaleV_COAXIALGUN"); } + float getRecoilPitchScaleV_COAXIALGUN() override { unexpected("IHapticSettings::getRecoilPitchScaleV_COAXIALGUN"); } + void setRecoilPitchScaleV_COAXIALGUN(float) override { unexpected("IHapticSettings::setRecoilPitchScaleV_COAXIALGUN"); } + float getUnresolved48C() override { unexpected("IHapticSettings::getUnresolved48C"); } + void setUnresolved48C(float) override { unexpected("IHapticSettings::setUnresolved48C"); } + float getUnresolved490() override { unexpected("IHapticSettings::getUnresolved490"); } + void setUnresolved490(float) override { unexpected("IHapticSettings::setUnresolved490"); } + float getGeneralShakeScale() override { unexpected("IHapticSettings::getGeneralShakeScale"); } + void setGeneralShakeScale(float) override { unexpected("IHapticSettings::setGeneralShakeScale"); } + float getExplosionShakeScale() override { unexpected("IHapticSettings::getExplosionShakeScale"); } + void setExplosionShakeScale(float) override { unexpected("IHapticSettings::setExplosionShakeScale"); } + float getSpeedShakeScale() override { unexpected("IHapticSettings::getSpeedShakeScale"); } + void setSpeedShakeScale(float) override { unexpected("IHapticSettings::setSpeedShakeScale"); } + int getWeaponClass(const std::string& name) override { unexpected("IHapticSettings::getWeaponClass"); } + void addWeaponClassMap(const std::string& name, int weaponClass) override { unexpected("IHapticSettings::addWeaponClassMap"); } + Vec3 getControlBoxLengthSOLDIER() override { calls.push_back("getControlBoxLengthSOLDIER"); return v3(1.0f, 2.0f, 3.0f); } + Vec3 getControlBoxStiffnessSOLDIER() override { calls.push_back("getControlBoxStiffnessSOLDIER"); return v3(11.0f, 12.0f, 13.0f); } + Vec3 getAimSensitivitySOLDIER() override { calls.push_back("getAimSensitivitySOLDIER"); return v3(21.0f, 22.0f, 23.0f); } + Vec3 getAimSensitivityLengthSOLDIER() override { calls.push_back("getAimSensitivityLengthSOLDIER"); return v3(31.0f, 32.0f, 33.0f); } + Vec3 getTurnSensitivitySOLDIER() override { calls.push_back("getTurnSensitivitySOLDIER"); return v3(41.0f, 42.0f, 43.0f); } + Vec3 getControlBoxLengthAIR() override { calls.push_back("getControlBoxLengthAIR"); return v3(101.0f, 102.0f, 103.0f); } + Vec3 getControlBoxStiffnessAIR() override { calls.push_back("getControlBoxStiffnessAIR"); return v3(111.0f, 112.0f, 113.0f); } + Vec3 getAimSensitivityAIR() override { calls.push_back("getAimSensitivityAIR"); return v3(121.0f, 122.0f, 123.0f); } + Vec3 getAimSensitivityLengthAIR() override { calls.push_back("getAimSensitivityLengthAIR"); return v3(131.0f, 132.0f, 133.0f); } + Vec3 getTurnSensitivityAIR() override { calls.push_back("getTurnSensitivityAIR"); return v3(141.0f, 142.0f, 143.0f); } + Vec3 getControlBoxLengthHELI() override { calls.push_back("getControlBoxLengthHELI"); return v3(201.0f, 202.0f, 203.0f); } + Vec3 getControlBoxStiffnessHELI() override { calls.push_back("getControlBoxStiffnessHELI"); return v3(211.0f, 212.0f, 213.0f); } + Vec3 getAimSensitivityHELI() override { calls.push_back("getAimSensitivityHELI"); return v3(221.0f, 222.0f, 223.0f); } + Vec3 getAimSensitivityLengthHELI() override { calls.push_back("getAimSensitivityLengthHELI"); return v3(231.0f, 232.0f, 233.0f); } + Vec3 getTurnSensitivityHELI() override { calls.push_back("getTurnSensitivityHELI"); return v3(241.0f, 242.0f, 243.0f); } + Vec3 getControlBoxLengthLAND() override { calls.push_back("getControlBoxLengthLAND"); return v3(301.0f, 302.0f, 303.0f); } + Vec3 getControlBoxStiffnessLAND() override { calls.push_back("getControlBoxStiffnessLAND"); return v3(311.0f, 312.0f, 313.0f); } + Vec3 getAimSensitivityLAND() override { calls.push_back("getAimSensitivityLAND"); return v3(321.0f, 322.0f, 323.0f); } + Vec3 getAimSensitivityLengthLAND() override { calls.push_back("getAimSensitivityLengthLAND"); return v3(331.0f, 332.0f, 333.0f); } + Vec3 getTurnSensitivityLAND() override { calls.push_back("getTurnSensitivityLAND"); return v3(341.0f, 342.0f, 343.0f); } + Vec3 getControlBoxLengthSEA() override { calls.push_back("getControlBoxLengthSEA"); return v3(401.0f, 402.0f, 403.0f); } + Vec3 getControlBoxStiffnessSEA() override { calls.push_back("getControlBoxStiffnessSEA"); return v3(411.0f, 412.0f, 413.0f); } + Vec3 getAimSensitivitySEA() override { calls.push_back("getAimSensitivitySEA"); return v3(421.0f, 422.0f, 423.0f); } + Vec3 getAimSensitivityLengthSEA() override { calls.push_back("getAimSensitivityLengthSEA"); return v3(431.0f, 432.0f, 433.0f); } + Vec3 getTurnSensitivitySEA() override { calls.push_back("getTurnSensitivitySEA"); return v3(441.0f, 442.0f, 443.0f); } + void setControlBoxLength(float x, float y, float z) override { calls.push_back("setControlBoxLength " + fmt(x, y, z)); } + void setControlBoxStiffness(float x, float y, float z) override { calls.push_back("setControlBoxStiffness " + fmt(x, y, z)); } + void setAimSensitivity(float x, float y, float z) override { calls.push_back("setAimSensitivity " + fmt(x, y, z)); } + void setAimSensitivityLength(float x, float y, float z) override { calls.push_back("setAimSensitivityLength " + fmt(x, y, z)); } + void setTurnSensitivity(float x, float y, float z) override { calls.push_back("setTurnSensitivity " + fmt(x, y, z)); } +}; +namespace world { +struct FakeTemplate final : IPlayerControlObjectTemplate { + std::string name; + int vehicleType = 0, category = 0, controls = 0; + void addRef() override { unexpected("addRef"); } + int getRef() override { unexpected("getRef"); } + int release() override { unexpected("release"); } + void* queryInterface(unsigned int) const override { unexpected("queryInterface"); } + int getVehicleType() override { calls.push_back(name + ".type"); return vehicleType; } + int getVehicleCategory() const override { calls.push_back(name + ".category"); return category; } + int getControlsCategory() const override { calls.push_back(name + ".controls"); return controls; } + void setPcoId(int) override { unexpected("IPlayerControlObjectTemplate::setPcoId"); } + int getPcoId() override { unexpected("IPlayerControlObjectTemplate::getPcoId"); } + void setPcoFlags(int) override { unexpected("IPlayerControlObjectTemplate::setPcoFlags"); } + unsigned int getPcoFlags() const override { unexpected("IPlayerControlObjectTemplate::getPcoFlags"); } + void setVehicleCategory(VehicleCategory) override { unexpected("IPlayerControlObjectTemplate::setVehicleCategory"); } + void setControlsCategory(VehicleCategory) override { unexpected("IPlayerControlObjectTemplate::setControlsCategory"); } + void setVehicleType(VehicleType) override { unexpected("IPlayerControlObjectTemplate::setVehicleType"); } + void setToolTipType(ToolTipType) override { unexpected("IPlayerControlObjectTemplate::setToolTipType"); } + int getToolTipType() override { unexpected("IPlayerControlObjectTemplate::getToolTipType"); } + void setSoldierExitLocation(const Vec3&, const Vec3&) override { unexpected("IPlayerControlObjectTemplate::setSoldierExitLocation"); } + void setSoldierExitPosition(const Vec3&) override { unexpected("IPlayerControlObjectTemplate::setSoldierExitPosition"); } + Vec3 getSoldierExitPosition() override { unexpected("IPlayerControlObjectTemplate::getSoldierExitPosition"); } + void setSoldierExitRotation(const Vec3&) override { unexpected("IPlayerControlObjectTemplate::setSoldierExitRotation"); } + Vec3 getSoldierExitRotation() override { unexpected("IPlayerControlObjectTemplate::getSoldierExitRotation"); } + void setArtPos(bool) override { unexpected("IPlayerControlObjectTemplate::setArtPos"); } + bool getArtPos() override { unexpected("IPlayerControlObjectTemplate::getArtPos"); } + void setDirBarXScale(float) override { unexpected("IPlayerControlObjectTemplate::setDirBarXScale"); } + float getDirBarXScale() override { unexpected("IPlayerControlObjectTemplate::getDirBarXScale"); } + void setDirBarYScaleAbove(float) override { unexpected("IPlayerControlObjectTemplate::setDirBarYScaleAbove"); } + float getDirBarYScaleAbove() override { unexpected("IPlayerControlObjectTemplate::getDirBarYScaleAbove"); } + void setDirBarYScaleBelow(float) override { unexpected("IPlayerControlObjectTemplate::setDirBarYScaleBelow"); } + float getDirBarYScaleBelow() override { unexpected("IPlayerControlObjectTemplate::getDirBarYScaleBelow"); } + void setDirBarRotate(float) override { unexpected("IPlayerControlObjectTemplate::setDirBarRotate"); } + float getDirBarRotate() override { unexpected("IPlayerControlObjectTemplate::getDirBarRotate"); } + void setDirBarYScaleMin(float) override { unexpected("IPlayerControlObjectTemplate::setDirBarYScaleMin"); } + float getDirBarYScaleMin() override { unexpected("IPlayerControlObjectTemplate::getDirBarYScaleMin"); } + void setDirBarYScaleMax(float) override { unexpected("IPlayerControlObjectTemplate::setDirBarYScaleMax"); } + float getDirBarYScaleMax() override { unexpected("IPlayerControlObjectTemplate::getDirBarYScaleMax"); } + void setNameTagOffset(Vec3) override { unexpected("IPlayerControlObjectTemplate::setNameTagOffset"); } + const Vec3& getNameTagOffset() override { unexpected("IPlayerControlObjectTemplate::getNameTagOffset"); } + void setRidingWithOffset(Vec3) override { unexpected("IPlayerControlObjectTemplate::setRidingWithOffset"); } + const Vec3& getRidingWithOffset() override { unexpected("IPlayerControlObjectTemplate::getRidingWithOffset"); } + void setRidingWithDistMod(float) override { unexpected("IPlayerControlObjectTemplate::setRidingWithDistMod"); } + float getRidingWithDistMod() override { unexpected("IPlayerControlObjectTemplate::getRidingWithDistMod"); } + void setVehicleCameraShake(CameraShakeTriggers) override { unexpected("IPlayerControlObjectTemplate::setVehicleCameraShake"); } + int getVehicleCameraShake() override { unexpected("IPlayerControlObjectTemplate::getVehicleCameraShake"); } + void setVehicleFov(float) override { unexpected("IPlayerControlObjectTemplate::setVehicleFov"); } + float getVehicleFov() override { unexpected("IPlayerControlObjectTemplate::getVehicleFov"); } + void setSeatLeftRotationLimit(float) override { unexpected("IPlayerControlObjectTemplate::setSeatLeftRotationLimit"); } + float getSeatLeftRotationLimit() const override { unexpected("IPlayerControlObjectTemplate::getSeatLeftRotationLimit"); } + void setSeatRightRotationLimit(float) override { unexpected("IPlayerControlObjectTemplate::setSeatRightRotationLimit"); } + float getSeatRightRotationLimit() const override { unexpected("IPlayerControlObjectTemplate::getSeatRightRotationLimit"); } + void seatInformation(const std::string&, const Vec3&, const Vec3&) override { unexpected("IPlayerControlObjectTemplate::seatInformation"); } + void setSeatAnimationSystem(const std::string&) override { unexpected("IPlayerControlObjectTemplate::setSeatAnimationSystem"); } + const std::string& getSeatAnimationSystem() override { unexpected("IPlayerControlObjectTemplate::getSeatAnimationSystem"); } + void setSeatParent(const std::string&) override { unexpected("IPlayerControlObjectTemplate::setSeatParent"); } + const std::string& getSeatParent() const override { unexpected("IPlayerControlObjectTemplate::getSeatParent"); } + void setSeatPosition(const Vec3&) override { unexpected("IPlayerControlObjectTemplate::setSeatPosition"); } + const Vec3& getSeatPosition() const override { unexpected("IPlayerControlObjectTemplate::getSeatPosition"); } + void setSeatRotation(const Vec3&) override { unexpected("IPlayerControlObjectTemplate::setSeatRotation"); } + const Vec3& getSeatRotation() const override { unexpected("IPlayerControlObjectTemplate::getSeatRotation"); } + const Mat4& getSeatTransformation() const override { unexpected("IPlayerControlObjectTemplate::getSeatTransformation"); } + const std::string& getSoundFilter() const override { unexpected("IPlayerControlObjectTemplate::getSoundFilter"); } + void setSoundFilter(const std::string&) override { unexpected("IPlayerControlObjectTemplate::setSoundFilter"); } + float getListenerObstruction() const override { unexpected("IPlayerControlObjectTemplate::getListenerObstruction"); } + void setListenerObstruction(float) override { unexpected("IPlayerControlObjectTemplate::setListenerObstruction"); } + void setMaintainCameraOnExit(bool) override { unexpected("IPlayerControlObjectTemplate::setMaintainCameraOnExit"); } + bool getMaintainCameraOnExit() override { unexpected("IPlayerControlObjectTemplate::getMaintainCameraOnExit"); } + void setMaintainCameraOnEnter(bool) override { unexpected("IPlayerControlObjectTemplate::setMaintainCameraOnEnter"); } + bool getMaintainCameraOnEnter() override { unexpected("IPlayerControlObjectTemplate::getMaintainCameraOnEnter"); } + void setNeverDrawAs1p(bool) override { unexpected("IPlayerControlObjectTemplate::setNeverDrawAs1p"); } + bool getNeverDrawAs1p() const override { unexpected("IPlayerControlObjectTemplate::getNeverDrawAs1p"); } +}; +} } } + +static std::string joined() +{ + std::string r; + for (const std::string& c : calls) r += c + ";"; + return r; +} + +// ---- updateSoldierRecoilForce: io::updateRecoilForce is recorded ---- +void dice::hfe::world::HapticWeaponAccess::setTemplate(IObject* weapon, const GenericFireArmTemplate* weaponTemplate) +{ + static_cast(weapon)->m_template = weaponTemplate; +} +static std::vector recoilCalls; +namespace dice { namespace hfe { namespace io { +void updateRecoilForce(float yawDelta, float pitchRecoil, int weaponType) +{ + char b[96]; + std::snprintf(b, sizeof(b), "recoil %.3f %.3f %d", yawDelta, pitchRecoil, weaponType); + recoilCalls.push_back(b); +} +} } } +namespace dice { namespace hfe { namespace io { +void updateSoldierCraftPhysicsForce(const Vec3& v, float dt) +{ + char b[128]; + std::snprintf(b, sizeof(b), "craft %.6g %.6g %.6g %.3f", v.x, v.y, v.z, dt); + recoilCalls.push_back(b); +} +void updateVehicleCraftPhysicsForce(const Vec3& v, float dt, int category) +{ + char b[128]; + std::snprintf(b, sizeof(b), "vehicle craft %.6g %.6g %.6g %.3f %d", v.x, v.y, v.z, dt, category); + recoilCalls.push_back(b); +} +} } } +// ---- updateSoldierCraftPhysics: a controlling player whose vehicle has a fixed inverse transform ---- +namespace dice { namespace hfe { namespace world { +// IObject's out-of-line members (IObject.cpp brings the object manager); none is reached. +IObject::IObject() {} +IObject::~IObject() {} +IPhysicsNode::IPhysicsNode() {} +IPhysicsNode::~IPhysicsNode() {} +WeakPtr IObject::getWeakPtr() { unexpected("IObject::getWeakPtr"); } +void IObject::SetActiveLod(ObjectLodType) { unexpected("IObject::SetActiveLod"); } +void IObject::forceDestroy() { unexpected("IObject::forceDestroy"); } +std::string IObject::getArmorInfo() { unexpected("IObject::getArmorInfo"); } +void IObject::destroyObject() { unexpected("IObject::destroyObject"); } +void IObject::setObjectCacheID(unsigned int) { unexpected("IObject::setObjectCacheID"); } +void IObject::enableCachedObject() { unexpected("IObject::enableCachedObject"); } +void IObject::disableCachedObject() { unexpected("IObject::disableCachedObject"); } +void IObject::setGridCullerObject(CullerObject*) { unexpected("IObject::setGridCullerObject"); } +void IObject::setLatencyCullerObject(CullerObject*) { unexpected("IObject::setLatencyCullerObject"); } +void IObject::internal_assignNewObjectID() { unexpected("IObject::internal_assignNewObjectID"); } +void* IObject::getDecalObject() const { unexpected("IObject::getDecalObject"); } +io::INetworkable* IObject::getNetworkable() const { unexpected("IObject::getNetworkable"); } +int IObject::getGeometryPart() const { unexpected("IObject::getGeometryPart"); } +bool IObject::hasCollisionLod(int) const { unexpected("IObject::hasCollisionLod"); } +unsigned int IObject::getObjectCacheID() const { unexpected("IObject::getObjectCacheID"); } +CullerObject* IObject::getGridCullerObject() const { unexpected("IObject::getGridCullerObject"); } +CullerObject* IObject::getLatencyCullerObject() const { unexpected("IObject::getLatencyCullerObject"); } +bool IObject::isCreatedByLocalPlayer() const { unexpected("IObject::isCreatedByLocalPlayer"); } +} } } +namespace { +using namespace dice::hfe::world; +using dice::hfe::Mat4; +struct ShakeVehicle final : IObject { + Mat4 inverse; + void addRef() override { unexpected("addRef"); } + int getRef() override { unexpected("getRef"); } + int release() override { unexpected("release"); } + void* queryInterface(unsigned int) const override { unexpected("IObject::queryInterface"); } + const Mat4& getInvAbsoluteTransformation() const override { recoilCalls.push_back("vehicle.inverse"); return inverse; } + unsigned int getClassID() const override { unexpected("IObject::getClassID"); } + WeakPtr getWeakPtr() override { unexpected("IObject::getWeakPtr"); } + void init() override { unexpected("IObject::init"); } + void disableCachedObject() override { unexpected("IObject::disableCachedObject"); } + void enableCachedObject() override { unexpected("IObject::enableCachedObject"); } + unsigned int getObjectCacheID() const override { unexpected("IObject::getObjectCacheID"); } + void setObjectCacheID(unsigned int) override { unexpected("IObject::setObjectCacheID"); } + void destroy(bool force) override { unexpected("IObject::destroy"); } + void forceDestroy() override { unexpected("IObject::forceDestroy"); } + bool isObjectDestroyed() override { unexpected("IObject::isObjectDestroyed"); } + void setObjectInDestroyList(bool) override { unexpected("IObject::setObjectInDestroyList"); } + bool getObjectInDestroyList() const override { unexpected("IObject::getObjectInDestroyList"); } + void setGridCullerObject(CullerObject*) override { unexpected("IObject::setGridCullerObject"); } + CullerObject* getGridCullerObject() const override { unexpected("IObject::getGridCullerObject"); } + void setLatencyCullerObject(CullerObject*) override { unexpected("IObject::setLatencyCullerObject"); } + CullerObject* getLatencyCullerObject() const override { unexpected("IObject::getLatencyCullerObject"); } + bool setComponent(unsigned int classId, IBase*) override { unexpected("IObject::setComponent"); } + IBase* queryComponent(unsigned int classId, unsigned int iid) override { unexpected("IObject::queryComponent"); } + void updateFlags(unsigned int set, unsigned int clear) override { unexpected("IObject::updateFlags"); } + const std::string& getName() const override { unexpected("IObject::getName"); } + void setName(const std::string&) override { unexpected("IObject::setName"); } + const Vec3& getAbsolutePosition() const override { unexpected("IObject::getAbsolutePosition"); } + void setAbsolutePosition(const Vec3&) override { unexpected("IObject::setAbsolutePosition"); } + const Vec3& getAbsolutePositionSecondary() const override { unexpected("IObject::getAbsolutePositionSecondary"); } + void setAbsolutePositionSecondary(const Vec3&) override { unexpected("IObject::setAbsolutePositionSecondary"); } + const Vec3& getRotationSecondary() override { unexpected("IObject::getRotationSecondary"); } + void setRotationSecondary(const Vec3&) override { unexpected("IObject::setRotationSecondary"); } + const Mat4& getAbsoluteTransformation() const override { unexpected("IObject::getAbsoluteTransformation"); } + void setAbsoluteTransformation(const Mat4&) override { unexpected("IObject::setAbsoluteTransformation"); } + const Mat4& getVisualAbsoluteTransformation() const override { unexpected("IObject::getVisualAbsoluteTransformation"); } + float getVisualBoundingRadius() const override { unexpected("IObject::getVisualBoundingRadius"); } + float getPhysicBoundingRadius() const override { unexpected("IObject::getPhysicBoundingRadius"); } + float getBoundingRadiusModifier() const override { unexpected("IObject::getBoundingRadiusModifier"); } + LocalBoundingBox* getFullBoundingBox() override { unexpected("IObject::getFullBoundingBox"); } + LocalBoundingBox* getMineBoundingBox() override { unexpected("IObject::getMineBoundingBox"); } + void handleVisualUpdate(float, float) override { unexpected("IObject::handleVisualUpdate"); } + void handleFrameUpdate(float) override { unexpected("IObject::handleFrameUpdate"); } + void handleUpdate(float, unsigned int) override { unexpected("IObject::handleUpdate"); } + bool handleCollision(IObject*, const Vec3&, const Vec3&, const Vec3&, int, int, CollisionFaceInfo*, CollisionFaceInfo*) override { unexpected("IObject::handleCollision"); } + void updateGeometry() override { unexpected("IObject::updateGeometry"); } + int getUpdateFrequency() const override { unexpected("IObject::getUpdateFrequency"); } + UpdateFreqencyType getUpdateFrequencyType() const override { unexpected("IObject::getUpdateFrequencyType"); } + void setUpdateFrequencyType(UpdateFreqencyType) override { unexpected("IObject::setUpdateFrequencyType"); } + int getGeometryPart() const override { unexpected("IObject::getGeometryPart"); } + bool hasCollisionLod(int) const override { unexpected("IObject::hasCollisionLod"); } + int getMaterial() const override { unexpected("IObject::getMaterial"); } + void SetActiveLod(ObjectLodType) override { unexpected("IObject::SetActiveLod"); } + io::INetworkable* getNetworkable() const override { unexpected("IObject::getNetworkable"); } + void* getDecalObject() const override { unexpected("IObject::getDecalObject"); } + const Vec3& getRelativePosition() const override { unexpected("IObject::getRelativePosition"); } + void setRelativePosition(const Vec3&) override { unexpected("IObject::setRelativePosition"); } + const Mat4& getRelativeTransformation() const override { unexpected("IObject::getRelativeTransformation"); } + void setRelativeTransformation(const Mat4&) override { unexpected("IObject::setRelativeTransformation"); } + IObject* getChild() const override { unexpected("IObject::getChild"); } + void addChild(IObject*) override { unexpected("IObject::addChild"); } + void removeChild(IObject*) override { unexpected("IObject::removeChild"); } + void resetCachedRootParents() override { unexpected("IObject::resetCachedRootParents"); } + void handlePlayerInput(IPlayer*, const io::PlayerInput&, float, unsigned int) override { unexpected("IObject::handlePlayerInput"); } + void handleMessage(TemplateMessage, IPlayer*, bool) override { unexpected("IObject::handleMessage"); } + char getInputId() const override { unexpected("IObject::getInputId"); } + void setInputId(char) override { unexpected("IObject::setInputId"); } + char getChildId() const override { unexpected("IObject::getChildId"); } + void setChildId(char) override { unexpected("IObject::setChildId"); } + unsigned char getAlpha() override { unexpected("IObject::getAlpha"); } + unsigned char getLayer() override { unexpected("IObject::getLayer"); } + void setLayer(unsigned char) override { unexpected("IObject::setLayer"); } + unsigned char getGroup() override { unexpected("IObject::getGroup"); } + void setGroup(unsigned char) override { unexpected("IObject::setGroup"); } + void setIsOvergrowth(bool) override { unexpected("IObject::setIsOvergrowth"); } + bool getIsOvergrowth() override { unexpected("IObject::getIsOvergrowth"); } + void setNotInAI(bool) override { unexpected("IObject::setNotInAI"); } + bool getNotInAI() const override { unexpected("IObject::getNotInAI"); } + void setLightSourceMask(int) override { unexpected("IObject::setLightSourceMask"); } + int getLightSourceMask() const override { unexpected("IObject::getLightSourceMask"); } + bool getDisableChildren() override { unexpected("IObject::getDisableChildren"); } + void setDisableChildren(bool) override { unexpected("IObject::setDisableChildren"); } + std::string getArmorInfo() override { unexpected("IObject::getArmorInfo"); } + bool isCreatedByLocalPlayer() const override { unexpected("IObject::isCreatedByLocalPlayer"); } + void internal_assignNewObjectID() override { unexpected("IObject::internal_assignNewObjectID"); } + void destroyObject() override { unexpected("IObject::destroyObject"); } + void addSibling(IObject*) override { unexpected("IObject::addSibling"); } + void removeSibling(IObject*) override { unexpected("IObject::removeSibling"); } + void setParent(IObject*) override { unexpected("IObject::setParent"); } +}; +struct Controller final : IPlayer { + IObject* vehicle = 0; + void addRef() override { unexpected("addRef"); } + int getRef() override { unexpected("getRef"); } + int release() override { unexpected("release"); } + void* queryInterface(unsigned int) const override { unexpected("IPlayer::queryInterface"); } + IObject* getVehicle() const override { recoilCalls.push_back("player.vehicle"); return vehicle; } + unsigned int getClassID() const override { unexpected("IPlayer::getClassID"); } + WeakPtr getWeakPtr() override { unexpected("IPlayer::getWeakPtr"); } + void setName(const std::string& name) override { unexpected("IPlayer::setName"); } + const std::string& getName() const override { unexpected("IPlayer::getName"); } + void setFlags(const Flag32Bits& flags) override { unexpected("IPlayer::setFlags"); } + bool testFlags(const Flag32Bits& flags) const override { unexpected("IPlayer::testFlags"); } + void handleUpdate(float dt, unsigned int) override { unexpected("IPlayer::handleUpdate"); } + void handleFrameUpdate(float dt) override { unexpected("IPlayer::handleFrameUpdate"); } + UpdateFreqencyType getUpdateFrequencyType() const override { unexpected("IPlayer::getUpdateFrequencyType"); } + void setUpdateFrequencyType(UpdateFreqencyType type) override { unexpected("IPlayer::setUpdateFrequencyType"); } + void handleInput(io::PlayerInput& input, float dt, unsigned int) override { unexpected("IPlayer::handleInput"); } + void getAutoInput(io::PlayerInput& out, bool) override { unexpected("IPlayer::getAutoInput"); } + bool setVehicle(IObject* vehicle, int seat) override { unexpected("IPlayer::setVehicle"); } + int getInputId() const override { unexpected("IPlayer::getInputId"); } + int getId() const override { unexpected("IPlayer::getId"); } + void setIsRemote(bool remote) override { unexpected("IPlayer::setIsRemote"); } + bool getIsRemote() const override { unexpected("IPlayer::getIsRemote"); } + void setIsAIPlayer(bool ai) override { unexpected("IPlayer::setIsAIPlayer"); } + bool getIsAIPlayer() const override { unexpected("IPlayer::getIsAIPlayer"); } + void setIsAlive(bool alive) override { unexpected("IPlayer::setIsAlive"); } + bool getIsAlive() const override { unexpected("IPlayer::getIsAlive"); } + void setSuicide(bool) override { unexpected("IPlayer::setSuicide"); } + bool getSuicide() const override { unexpected("IPlayer::getSuicide"); } + bool getIsConnected() const override { unexpected("IPlayer::getIsConnected"); } + void setIsConnected(bool) override { unexpected("IPlayer::setIsConnected"); } + float getCrossHairFadeValue() const override { unexpected("IPlayer::getCrossHairFadeValue"); } + void setViewDistance(float) override { unexpected("IPlayer::setViewDistance"); } + float getViewDistance() const override { unexpected("IPlayer::getViewDistance"); } + void setFov(float fov, float time) override { unexpected("IPlayer::setFov"); } + float getFov() const override { unexpected("IPlayer::getFov"); } + float getEndFov() const override { unexpected("IPlayer::getEndFov"); } + ActionBuffer* getActionBuffer() override { unexpected("IPlayer::getActionBuffer"); } + void* getAIPlayerInput() const override { unexpected("IPlayer::getAIPlayerInput"); } + void setDefaultVehicle(IObject*) override { unexpected("IPlayer::setDefaultVehicle"); } + IObject* getDefaultVehicle() override { unexpected("IPlayer::getDefaultVehicle"); } + IObject* getFreeCamera() const override { unexpected("IPlayer::getFreeCamera"); } + void setFreeCameraEnabled(bool) override { unexpected("IPlayer::setFreeCameraEnabled"); } + bool getFreeCameraEnabled() const override { unexpected("IPlayer::getFreeCameraEnabled"); } + void toggleFreeCameraEnabled() override { unexpected("IPlayer::toggleFreeCameraEnabled"); } + void setOverheadCameraEnabled(bool) override { unexpected("IPlayer::setOverheadCameraEnabled"); } + bool getOverheadCameraEnabled() const override { unexpected("IPlayer::getOverheadCameraEnabled"); } + void setOverheadCameraTopDownView(bool) override { unexpected("IPlayer::setOverheadCameraTopDownView"); } + bool getOverheadCameraTopDownView() const override { unexpected("IPlayer::getOverheadCameraTopDownView"); } + void setCommanderCamOverhead(bool) override { unexpected("IPlayer::setCommanderCamOverhead"); } + bool getCommanderCamOverhead() const override { unexpected("IPlayer::getCommanderCamOverhead"); } + int getTickCount() const override { unexpected("IPlayer::getTickCount"); } + void addTick() override { unexpected("IPlayer::addTick"); } + void subTick() override { unexpected("IPlayer::subTick"); } + void resetTickCounter() override { unexpected("IPlayer::resetTickCounter"); } + float getTimeOutSideWorld() const override { unexpected("IPlayer::getTimeOutSideWorld"); } + void setTeam(int team, bool) override { unexpected("IPlayer::setTeam"); } + int getTeam() const override { unexpected("IPlayer::getTeam"); } + unsigned int getSpawnAtTick() const override { unexpected("IPlayer::getSpawnAtTick"); } + void setSpawnAtTick(unsigned int tick) override { unexpected("IPlayer::setSpawnAtTick"); } + float getTimeToSpawn() const override { unexpected("IPlayer::getTimeToSpawn"); } + float getManDownTimeLeft() const override { unexpected("IPlayer::getManDownTimeLeft"); } + void setIsManDown(bool) override { unexpected("IPlayer::setIsManDown"); } + bool getIsManDown() override { unexpected("IPlayer::getIsManDown"); } + unsigned int getManDownAtTick() override { unexpected("IPlayer::getManDownAtTick"); } + void setSquadId(unsigned int id) override { unexpected("IPlayer::setSquadId"); } + int getSquadId() const override { unexpected("IPlayer::getSquadId"); } + void setIsCommander(bool) override { unexpected("IPlayer::setIsCommander"); } + bool getIsCommander() const override { unexpected("IPlayer::getIsCommander"); } + void setUAVIsReady(bool) override { unexpected("IPlayer::setUAVIsReady"); } + bool getUAVIsReady() const override { unexpected("IPlayer::getUAVIsReady"); } + void setSatelliteIsReady(bool) override { unexpected("IPlayer::setSatelliteIsReady"); } + bool getSatelliteIsReady() const override { unexpected("IPlayer::getSatelliteIsReady"); } + void setLastTimeCommander(double t) override { unexpected("IPlayer::setLastTimeCommander"); } + double getLastTimeCommander() const override { unexpected("IPlayer::getLastTimeCommander"); } + void setCommanderReapplyWaitTime(double t) override { unexpected("IPlayer::setCommanderReapplyWaitTime"); } + double getCommanderReapplyWaitTime() const override { unexpected("IPlayer::getCommanderReapplyWaitTime"); } + void setIsSquadLeader(bool) override { unexpected("IPlayer::setIsSquadLeader"); } + bool getIsSquadLeader() const override { unexpected("IPlayer::getIsSquadLeader"); } + bool getIsGassed() override { unexpected("IPlayer::getIsGassed"); } + void setIsInsideCP(bool) override { unexpected("IPlayer::setIsInsideCP"); } + bool getIsInsideCP() override { unexpected("IPlayer::getIsInsideCP"); } + void setHasSimulatedFrame(bool) override { unexpected("IPlayer::setHasSimulatedFrame"); } + bool getHasSimulatedFrame() const override { unexpected("IPlayer::getHasSimulatedFrame"); } + void setSpawnGroup(int group) override { unexpected("IPlayer::setSpawnGroup"); } + int getSpawnGroup() const override { unexpected("IPlayer::getSpawnGroup"); } + void setInterpolationTime(unsigned int ms) override { unexpected("IPlayer::setInterpolationTime"); } + unsigned int getInterpolationTime() const override { unexpected("IPlayer::getInterpolationTime"); } + void setPing(unsigned int ping) override { unexpected("IPlayer::setPing"); } + unsigned int getPing() const override { unexpected("IPlayer::getPing"); } + void setKit(int kit) override { unexpected("IPlayer::setKit"); } + int getKit() const override { unexpected("IPlayer::getKit"); } + PlayerScoreData* getScoreData() override { unexpected("IPlayer::getScoreData"); } + void setFlagHolder(bool) override { unexpected("IPlayer::setFlagHolder"); } + bool getFlagHolder() const override { unexpected("IPlayer::getFlagHolder"); } + ICameraObject* getCamera() const override { unexpected("IPlayer::getCamera"); } + void setCamera(ICameraObject* camera) override { unexpected("IPlayer::setCamera"); } + bool hasFirstPersonView() const override { unexpected("IPlayer::hasFirstPersonView"); } + double getTimeConnected() const override { unexpected("IPlayer::getTimeConnected"); } + io::INetworkable* getNetworkable() override { unexpected("IPlayer::getNetworkable"); } + bool getStateSync(io::BitStream* stream, IObject* object) override { unexpected("IPlayer::getStateSync"); } + bool setStateSync(io::BitStream* stream, IObject* object, double) override { unexpected("IPlayer::setStateSync"); } + void reset() override { unexpected("IPlayer::reset"); } + void setFiringState(bool) override { unexpected("IPlayer::setFiringState"); } + bool getFiringState() const override { unexpected("IPlayer::getFiringState"); } + void setAltFiringState(bool) override { unexpected("IPlayer::setAltFiringState"); } + bool getAltFiringState() const override { unexpected("IPlayer::getAltFiringState"); } + void setFlareFiringState(bool) override { unexpected("IPlayer::setFlareFiringState"); } + bool getFlareFiringState() const override { unexpected("IPlayer::getFlareFiringState"); } + void setSprintState(bool) override { unexpected("IPlayer::setSprintState"); } + bool getSprintState() const override { unexpected("IPlayer::getSprintState"); } + void setSprintStateLastTick(bool) override { unexpected("IPlayer::setSprintStateLastTick"); } + bool getSprintStateLastTick() const override { unexpected("IPlayer::getSprintStateLastTick"); } + void setReloadState() override { unexpected("IPlayer::setReloadState"); } + bool getAndResetReloadState() override { unexpected("IPlayer::getAndResetReloadState"); } + void updateFiringState(unsigned int, IObject*) override { unexpected("IPlayer::updateFiringState"); } + void updateGhostFiringState() override { unexpected("IPlayer::updateGhostFiringState"); } + void setHitIndicator(bool) override { unexpected("IPlayer::setHitIndicator"); } + bool getHitIndicator() const override { unexpected("IPlayer::getHitIndicator"); } + float updateHitFromDirection(const Vec3& direction) override { unexpected("IPlayer::updateHitFromDirection"); } + float getHitFromDirection() const override { unexpected("IPlayer::getHitFromDirection"); } + void updateCameraShake(float amount) override { unexpected("IPlayer::updateCameraShake"); } + float getCameraShake() const override { unexpected("IPlayer::getCameraShake"); } + unsigned int getSquadInviteMask() const override { unexpected("IPlayer::getSquadInviteMask"); } + void setSquadInviteMask(unsigned int mask) override { unexpected("IPlayer::setSquadInviteMask"); } + bool getIsInvitedToSquad(int squad) const override { unexpected("IPlayer::getIsInvitedToSquad"); } + void setKitTimeStamp(double t) override { unexpected("IPlayer::setKitTimeStamp"); } + double getKitTimeStamp() const override { unexpected("IPlayer::getKitTimeStamp"); } + void setCurrentFiringButton(io::PlayerInputMap button) override { unexpected("IPlayer::setCurrentFiringButton"); } + io::PlayerInputMap getCurrentFiringButton() const override { unexpected("IPlayer::getCurrentFiringButton"); } + void setPersonalDecalTemplate(const IObjectTemplate* decal) override { unexpected("IPlayer::setPersonalDecalTemplate"); } + const IObjectTemplate* getPersonalDecalTemplate() const override { unexpected("IPlayer::getPersonalDecalTemplate"); } + void enableVOHelp(bool) override { unexpected("IPlayer::enableVOHelp"); } + void enableVOHelpMessage(int) override { unexpected("IPlayer::enableVOHelpMessage"); } + void disableVOHelpMessage(int) override { unexpected("IPlayer::disableVOHelpMessage"); } + bool getVOHelpMessagePlayed(int) override { unexpected("IPlayer::getVOHelpMessagePlayed"); } + void doAddTouchItem(IPlayer* other) override { unexpected("IPlayer::doAddTouchItem"); } + void setHealRepairedAtTick(unsigned int tick, bool giving, bool repairing) override { unexpected("IPlayer::setHealRepairedAtTick"); } + unsigned int getHealRepairedAtTick() const override { unexpected("IPlayer::getHealRepairedAtTick"); } + void setGaveAmmoAtTick(unsigned int tick, bool giving) override { unexpected("IPlayer::setGaveAmmoAtTick"); } + unsigned int getGaveAmmoAtTick() const override { unexpected("IPlayer::getGaveAmmoAtTick"); } + void setFailedExitAtTick(unsigned int tick) override { unexpected("IPlayer::setFailedExitAtTick"); } + unsigned int getFailedExitAtTick() const override { unexpected("IPlayer::getFailedExitAtTick"); } + bool getIsGivingAbility() const override { unexpected("IPlayer::getIsGivingAbility"); } + bool getIsRepairing() const override { unexpected("IPlayer::getIsRepairing"); } + bool getIsGivingReplenish() const override { unexpected("IPlayer::getIsGivingReplenish"); } + int getChosenUnlockLevel(int kit, int slot) const override { unexpected("IPlayer::getChosenUnlockLevel"); } + void setChosenUnlockLevel(int kit, int slot, int level) override { unexpected("IPlayer::setChosenUnlockLevel"); } + bool isUnlocked(int kit, int slot, int level) override { unexpected("IPlayer::isUnlocked"); } + int getUnlockLevel(int kit, int slot) override { unexpected("IPlayer::getUnlockLevel"); } + void setUnlocks(std::map* unlocks) override { unexpected("IPlayer::setUnlocks"); } + std::map* getUnlocks() override { unexpected("IPlayer::getUnlocks"); } + void setPeerAddress(const std::string& address) override { unexpected("IPlayer::setPeerAddress"); } + const std::string& getPeerAddress() const override { unexpected("IPlayer::getPeerAddress"); } + bool getVoipEnabled() override { unexpected("IPlayer::getVoipEnabled"); } + unsigned short getVoipSessionId() override { unexpected("IPlayer::getVoipSessionId"); } + void setVoipSessionId(unsigned short id) override { unexpected("IPlayer::setVoipSessionId"); } + bool getIsMuted() override { unexpected("IPlayer::getIsMuted"); } + bool getIsTalking() override { unexpected("IPlayer::getIsTalking"); } + double getLastTalkTime() override { unexpected("IPlayer::getLastTalkTime"); } + double getStopTalkingThreshold() override { unexpected("IPlayer::getStopTalkingThreshold"); } + void setIsMuted(bool) override { unexpected("IPlayer::setIsMuted"); } + void setIsTalking(bool) override { unexpected("IPlayer::setIsTalking"); } + void setVoipEnabled(bool) override { unexpected("IPlayer::setVoipEnabled"); } + void setVotingStatus(PlayerVotingStatus status) override { unexpected("IPlayer::setVotingStatus"); } + PlayerVotingStatus getVotingStatus() override { unexpected("IPlayer::getVotingStatus"); } + void setParticipateInVoting(bool) override { unexpected("IPlayer::setParticipateInVoting"); } + bool getParticipateInVoting() override { unexpected("IPlayer::getParticipateInVoting"); } + void setTargetOfVote(bool) override { unexpected("IPlayer::setTargetOfVote"); } + bool getTargetOfVote() override { unexpected("IPlayer::getTargetOfVote"); } + int getProfileId() override { unexpected("IPlayer::getProfileId"); } + void setProfileId(int id) override { unexpected("IPlayer::setProfileId"); } + void setBlurryVision(float, float, float) override { unexpected("IPlayer::setBlurryVision"); } + float getBlurValue() const override { unexpected("IPlayer::getBlurValue"); } + bool getIsNearGasCloud() const override { unexpected("IPlayer::getIsNearGasCloud"); } + bool getIsGasMaskOn() const override { unexpected("IPlayer::getIsGasMaskOn"); } + void setIsGasMaskOn(bool, bool) override { unexpected("IPlayer::setIsGasMaskOn"); } + void setGasMaskHudItem(bool) override { unexpected("IPlayer::setGasMaskHudItem"); } + float getPlayerGasMaskChangeTimer() const override { unexpected("IPlayer::getPlayerGasMaskChangeTimer"); } + float getPlayerNightVisionChangeTimer() const override { unexpected("IPlayer::getPlayerNightVisionChangeTimer"); } + bool getIsUnderwater() const override { unexpected("IPlayer::getIsUnderwater"); } + float getNormalizedNightVisionPower() override { unexpected("IPlayer::getNormalizedNightVisionPower"); } + void setNightVision(bool, bool) override { unexpected("IPlayer::setNightVision"); } + void rechargeNightVision() override { unexpected("IPlayer::rechargeNightVision"); } + void setVisualNightVision(bool) override { unexpected("IPlayer::setVisualNightVision"); } + bool getNightVision() const override { unexpected("IPlayer::getNightVision"); } + void disableFlashBangEffect() override { unexpected("IPlayer::disableFlashBangEffect"); } + void disableBlurryVision() override { unexpected("IPlayer::disableBlurryVision"); } + io::PlayerInput getPlayerInput() override { unexpected("IPlayer::getPlayerInput"); } + void resetOnDeath() override { unexpected("IPlayer::resetOnDeath"); } + bool isPlayerInNightMap() const override { unexpected("IPlayer::isPlayerInNightMap"); } + void setTracePlayerId(int id) override { unexpected("IPlayer::setTracePlayerId"); } + int getTracePlayerId() override { unexpected("IPlayer::getTracePlayerId"); } + void allocateFreeCamera() override { unexpected("IPlayer::allocateFreeCamera"); } + bool getIsThisASpam(bool) override { unexpected("IPlayer::getIsThisASpam"); } + void setRadioSpamFlagCount(int) override { unexpected("IPlayer::setRadioSpamFlagCount"); } + int getRadioSpamFlagCount() override { unexpected("IPlayer::getRadioSpamFlagCount"); } + void setRadioSpamBlockedFlagCount(int) override { unexpected("IPlayer::setRadioSpamBlockedFlagCount"); } + int getRadioSpamBlockedFlagCount() override { unexpected("IPlayer::getRadioSpamBlockedFlagCount"); } + void setRadioSpamFilterFlagTimer(float) override { unexpected("IPlayer::setRadioSpamFilterFlagTimer"); } + float getRadioSpamFilterFlagTimer() override { unexpected("IPlayer::getRadioSpamFilterFlagTimer"); } + void resetSpamFilter() override { unexpected("IPlayer::resetSpamFilter"); } + void getCloseMines(std::vector& out) const override { unexpected("IPlayer::getCloseMines"); } + bool getAutoReload() const override { unexpected("IPlayer::getAutoReload"); } + void setAutoReload(bool) override { unexpected("IPlayer::setAutoReload"); } + void updateClientSettings() override { unexpected("IPlayer::updateClientSettings"); } +}; +struct HapticPhysics final : IPhysicsNode { + Vec3 speed; + void addRef() override { unexpected("addRef"); } + int getRef() override { unexpected("getRef"); } + int release() override { unexpected("release"); } + void* queryInterface(unsigned int) const override { unexpected("IPhysicsNode::queryInterface"); } + const Vec3& getPositionalSpeed() const override { recoilCalls.push_back("physics.speed"); return speed; } + const Vec3& getPositionalAcceleration() const override { recoilCalls.push_back("physics.acceleration"); return speed; } + void setEnabled(bool) override { unexpected("IPhysicsNode::setEnabled"); } + bool getEnabled() const override { unexpected("IPhysicsNode::getEnabled"); } + void setIsDamaged(bool) override { unexpected("IPhysicsNode::setIsDamaged"); } + bool getIsDamaged() const override { unexpected("IPhysicsNode::getIsDamaged"); } + void setObject(IObject*) override { unexpected("IPhysicsNode::setObject"); } + IObject* getObject() const override { unexpected("IPhysicsNode::getObject"); } + void setParent(IPhysicsNode*) override { unexpected("IPhysicsNode::setParent"); } + IPhysicsNode* getParent() const override { unexpected("IPhysicsNode::getParent"); } + float getBoundingRadius() const override { unexpected("IPhysicsNode::getBoundingRadius"); } + const Mat4& getAbsoluteTransformation() const override { unexpected("IPhysicsNode::getAbsoluteTransformation"); } + void setAbsoluteTransformation(const Mat4&) override { unexpected("IPhysicsNode::setAbsoluteTransformation"); } + const Mat4& getRelativeTransformation() const override { unexpected("IPhysicsNode::getRelativeTransformation"); } + const Vec3& getAbsolutePosition() const override { unexpected("IPhysicsNode::getAbsolutePosition"); } + void setAbsolutePosition(const Vec3&) override { unexpected("IPhysicsNode::setAbsolutePosition"); } + const Mat4& getPrevTransformation() const override { unexpected("IPhysicsNode::getPrevTransformation"); } + void setPrevTransformation(const Mat4&) override { unexpected("IPhysicsNode::setPrevTransformation"); } + void setOldPosition(const Vec3&) override { unexpected("IPhysicsNode::setOldPosition"); } + const Vec3& getRelativePosition() const override { unexpected("IPhysicsNode::getRelativePosition"); } + const Vec3& getRotationalSpeed() const override { unexpected("IPhysicsNode::getRotationalSpeed"); } + void setPositionalSpeed(const Vec3&) override { unexpected("IPhysicsNode::setPositionalSpeed"); } + void setRotationalSpeed(const Vec3&) override { unexpected("IPhysicsNode::setRotationalSpeed"); } + void addPositionalSpeed(const Vec3&) override { unexpected("IPhysicsNode::addPositionalSpeed"); } + void addRotationalSpeed(const Vec3&) override { unexpected("IPhysicsNode::addRotationalSpeed"); } + void setPositionalAcceleration(const Vec3&) override { unexpected("IPhysicsNode::setPositionalAcceleration"); } + void setRotationalAcceleration(const Vec3&) override { unexpected("IPhysicsNode::setRotationalAcceleration"); } + void setPositionalFriction(const Vec3&) override { unexpected("IPhysicsNode::setPositionalFriction"); } + void setRotationalFriction(const Vec3&) override { unexpected("IPhysicsNode::setRotationalFriction"); } + void addSpeedAtAbsolutePosition(const Vec3&, const Vec3&) override { unexpected("IPhysicsNode::addSpeedAtAbsolutePosition"); } + void addSpeedAtRelativePosition(const Vec3&, const Vec3&) override { unexpected("IPhysicsNode::addSpeedAtRelativePosition"); } + void addAccelerationAtAbsolutePosition(const Vec3&, const Vec3&) override { unexpected("IPhysicsNode::addAccelerationAtAbsolutePosition"); } + void addAccelerationAtRelativePosition(const Vec3&, const Vec3&) override { unexpected("IPhysicsNode::addAccelerationAtRelativePosition"); } + void addFrictionAtAbsolutePosition(const Vec3&, const Vec3&) override { unexpected("IPhysicsNode::addFrictionAtAbsolutePosition"); } + void addPositionalAccelerationToRootParent(const Vec3&) override { unexpected("IPhysicsNode::addPositionalAccelerationToRootParent"); } + void addRotationalAccelerationAtAbsolutePosition(const Vec3&, const Vec3&) override { unexpected("IPhysicsNode::addRotationalAccelerationAtAbsolutePosition"); } + const Vec3& getTangentSpeed(const Vec3&) override { unexpected("IPhysicsNode::getTangentSpeed"); } + const Vec3& getTangentAcceleration(const Vec3&) override { unexpected("IPhysicsNode::getTangentAcceleration"); } + const Vec3& getRotationalAcceleration() const override { unexpected("IPhysicsNode::getRotationalAcceleration"); } + const Vec3& getPositionalFriction() const override { unexpected("IPhysicsNode::getPositionalFriction"); } + const Vec3& getRotationalFriction() const override { unexpected("IPhysicsNode::getRotationalFriction"); } + void updatePhysics(float dt) override { unexpected("IPhysicsNode::updatePhysics"); } + void setDrag(float) override { unexpected("IPhysicsNode::setDrag"); } + float getDrag() const override { unexpected("IPhysicsNode::getDrag"); } + void setDragOffset(const Vec3&) override { unexpected("IPhysicsNode::setDragOffset"); } + const Vec3& getDragOffset() const override { unexpected("IPhysicsNode::getDragOffset"); } + void setDragModifier(const Vec3&) override { unexpected("IPhysicsNode::setDragModifier"); } + const Vec3& getDragModifier() const override { unexpected("IPhysicsNode::getDragModifier"); } + void setMass(float) override { unexpected("IPhysicsNode::setMass"); } + float getMass() const override { unexpected("IPhysicsNode::getMass"); } + void setCenterOfMassOffset(const Vec3&) override { unexpected("IPhysicsNode::setCenterOfMassOffset"); } + const Vec3& getCenterOfMassOffset() const override { unexpected("IPhysicsNode::getCenterOfMassOffset"); } + void setCenterOfCollisionOffset(const Vec3&) override { unexpected("IPhysicsNode::setCenterOfCollisionOffset"); } + const Vec3& getCenterOfCollisionOffset() const override { unexpected("IPhysicsNode::getCenterOfCollisionOffset"); } + void setInertiaModifier(const Vec3&) override { unexpected("IPhysicsNode::setInertiaModifier"); } + const Vec3& getInertiaModifier() const override { unexpected("IPhysicsNode::getInertiaModifier"); } + void setGravityModifier(float) override { unexpected("IPhysicsNode::setGravityModifier"); } + float getGravityModifier() const override { unexpected("IPhysicsNode::getGravityModifier"); } + void setHasSeparatePhysicsUpdate(bool) override { unexpected("IPhysicsNode::setHasSeparatePhysicsUpdate"); } + bool getHasSeparatePhysicsUpdate() const override { unexpected("IPhysicsNode::getHasSeparatePhysicsUpdate"); } + void setUnderWater(float) override { unexpected("IPhysicsNode::setUnderWater"); } + float getUnderWater() const override { unexpected("IPhysicsNode::getUnderWater"); } + void setUnderwaterYComponent(float) override { unexpected("IPhysicsNode::setUnderwaterYComponent"); } + bool getIsTreadingWater() const override { unexpected("IPhysicsNode::getIsTreadingWater"); } + void reset(bool) override { unexpected("IPhysicsNode::reset"); } + bool getIsSleeping() const override { unexpected("IPhysicsNode::getIsSleeping"); } + void setIsSleeping() override { unexpected("IPhysicsNode::setIsSleeping"); } + void setSleepiness(int) override { unexpected("IPhysicsNode::setSleepiness"); } + int getSleepiness() const override { unexpected("IPhysicsNode::getSleepiness"); } + void setIsSleepier() override { unexpected("IPhysicsNode::setIsSleepier"); } + void setIsAwake() override { unexpected("IPhysicsNode::setIsAwake"); } + bool getIsMobile() const override { unexpected("IPhysicsNode::getIsMobile"); } + bool getIsPoint() const override { unexpected("IPhysicsNode::getIsPoint"); } + void initLatencyCompensation() override { unexpected("IPhysicsNode::initLatencyCompensation"); } + bool hasLatencyCompensation() override { unexpected("IPhysicsNode::hasLatencyCompensation"); } + void updateLatencyState() override { unexpected("IPhysicsNode::updateLatencyState"); } + const Mat4& getLatencyCompensatedTransformation(float, int*) override { unexpected("IPhysicsNode::getLatencyCompensatedTransformation"); } + const Vec3& getAbsolutePositionalSpeed() override { unexpected("IPhysicsNode::getAbsolutePositionalSpeed"); } + IPhysicsNode* getRootNode() override { unexpected("IPhysicsNode::getRootNode"); } + void setHandleCollisionSpeed(float) override { unexpected("IPhysicsNode::setHandleCollisionSpeed"); } + float getHandleCollisionSpeed() const override { unexpected("IPhysicsNode::getHandleCollisionSpeed"); } + const Vec3& getInverseInertia() override { unexpected("IPhysicsNode::getInverseInertia"); } + void addRelativeImpulse(const Vec3&, const Vec3&) override { unexpected("IPhysicsNode::addRelativeImpulse"); } + void setFloaterMod(float) override { unexpected("IPhysicsNode::setFloaterMod"); } + float getFloaterMod() const override { unexpected("IPhysicsNode::getFloaterMod"); } + const Vec3& getLinearIntegrationVelocity() const override { unexpected("IPhysicsNode::getLinearIntegrationVelocity"); } + void setLinearIntegrationVelocity(const Vec3&) override { unexpected("IPhysicsNode::setLinearIntegrationVelocity"); } + const Vec3& getAngularIntegrationVelocity() const override { unexpected("IPhysicsNode::getAngularIntegrationVelocity"); } + void setAngularIntegrationVelocity(const Vec3&) override { unexpected("IPhysicsNode::setAngularIntegrationVelocity"); } + void setTreeCollisionRadius(float) override { unexpected("IPhysicsNode::setTreeCollisionRadius"); } + float getTreeCollisionRadius() const override { unexpected("IPhysicsNode::getTreeCollisionRadius"); } + void postFrameUpdate() override { unexpected("IPhysicsNode::postFrameUpdate"); } + void setLocalLinearSpeed(const Vec3&) override { unexpected("IPhysicsNode::setLocalLinearSpeed"); } + const Vec3& getLocalLinearSpeed() const override { unexpected("IPhysicsNode::getLocalLinearSpeed"); } + void setLocalAngularSpeed(const Vec3&) override { unexpected("IPhysicsNode::setLocalAngularSpeed"); } + const Vec3& getLocalAngularSpeed() const override { unexpected("IPhysicsNode::getLocalAngularSpeed"); } + void setOtherCollisionLod(int) override { unexpected("IPhysicsNode::setOtherCollisionLod"); } + int getOtherCollisionLod() const override { unexpected("IPhysicsNode::getOtherCollisionLod"); } + bool getShouldGravityCompensateOnContact() const override { unexpected("IPhysicsNode::getShouldGravityCompensateOnContact"); } + void setHasContact(bool) override { unexpected("IPhysicsNode::setHasContact"); } + bool getHasContact() const override { unexpected("IPhysicsNode::getHasContact"); } + void setIsInAir(bool) override { unexpected("IPhysicsNode::setIsInAir"); } + bool getIsInAir() const override { unexpected("IPhysicsNode::getIsInAir"); } + void setSleepTimeout(int) override { unexpected("IPhysicsNode::setSleepTimeout"); } + void setIsPlatformPhysics(bool) override { unexpected("IPhysicsNode::setIsPlatformPhysics"); } + bool getIsPlatformPhysics() const override { unexpected("IPhysicsNode::getIsPlatformPhysics"); } +}; +} // namespace +static std::string recoilJoined() +{ + std::string r; + for (const std::string& c : recoilCalls) r += c + ";"; + return r; +} + +int main() +{ + std::setvbuf(stdout, nullptr, _IONBF, 0); + FakeHapticSettings settings; + // ---- applyHapticProfile: five copies, each getter called once per component ---- + const char* names[5] = { "SOLDIER", "AIR", "HELI", "LAND", "SEA" }; + const char* kinds[5] = { "ControlBoxLength", "ControlBoxStiffness", "AimSensitivity", "AimSensitivityLength", "TurnSensitivity" }; + const HapticProfile profiles[5] = { HapticProfileSoldier, HapticProfileAir, HapticProfileHeli, HapticProfileLand, HapticProfileSea }; + for (int p = 0; p < 5; ++p) { + calls.clear(); + applyHapticProfile(&settings, profiles[p]); + std::vector sets; + std::map gets; + for (const std::string& c : calls) { + if (c.compare(0, 3, "set") == 0) sets.push_back(c); + else ++gets[c]; + } + bool ok = sets.size() == 5 && gets.size() == 5 && calls.size() == 20; + for (int k = 0; k < 5 && ok; ++k) { + const int base = p * 100 + k * 10; + ok = sets[k] == std::string("set") + kinds[k] + " " + fmt(base + 1.0f, base + 2.0f, base + 3.0f) + && gets[std::string("get") + kinds[k] + names[p]] == 3; + } + // Each copy's three getter calls come right before its setter. + for (int k = 0; k < 5 && ok; ++k) + for (int g = 0; g < 3; ++g) ok = calls[k * 4 + g] == std::string("get") + kinds[k] + names[p]; + check(ok, std::string("profile ") + names[p] + ": the five copies from its own values, 3 getter calls each"); + } + + // ---- hapticProfileForEntered ---- + FakeTemplate entered, root; + entered.name = "entered"; + root.name = "root"; + const int soldierTypes[] = { 8, 9, 15, 19, 20, 24, 25 }; + for (int t : soldierTypes) { + entered.vehicleType = t; + root.category = 2; + calls.clear(); + check(hapticProfileForEntered(&entered, &root) == HapticProfileSoldier && joined() == "entered.type;", + "type " + std::to_string(t) + ": SOLDIER, nothing else read"); + } + entered.vehicleType = 26; + const struct { int category, controls; HapticProfile expected; const char* reads; } t26[] = { + { 2, 0, HapticProfileAir, "entered.type;entered.category;" }, + { 3, 1, HapticProfileHeli, "entered.type;entered.category;entered.controls;" }, + { 3, 0, HapticProfileSoldier, "entered.type;entered.category;entered.controls;" }, + { 0, 1, HapticProfileSoldier, "entered.type;entered.category;" }, + { 1, 1, HapticProfileSoldier, "entered.type;entered.category;" }, + { 7, 1, HapticProfileSoldier, "entered.type;entered.category;" }, + }; + for (const auto& c : t26) { + entered.category = c.category; + entered.controls = c.controls; + root.category = 0; + calls.clear(); + check(hapticProfileForEntered(&entered, &root) == c.expected && joined() == c.reads, + "type 26, category " + std::to_string(c.category) + ", controls " + std::to_string(c.controls)); + } + const int otherTypes[] = { -1, 0, 7, 10, 11, 12, 13, 14, 16, 17, 18, 21, 22, 23, 27, 100 }; + const struct { int category; HapticProfile expected; } byRoot[] = { + { 0, HapticProfileLand }, { 1, HapticProfileSea }, { 2, HapticProfileAir }, { 3, HapticProfileHeli }, + { 4, HapticProfileSoldier }, { -1, HapticProfileSoldier }, + }; + for (int t : otherTypes) { + bool ok = true; + for (const auto& r : byRoot) { + entered.vehicleType = t; + entered.category = 2; // never read for these types + root.category = r.category; + calls.clear(); + ok = ok && hapticProfileForEntered(&entered, &root) == r.expected && joined() == "entered.type;root.category;"; + } + check(ok, "type " + std::to_string(t) + ": the root's category (0 LAND, 1 SEA, 2 AIR, 3 HELI, else SOLDIER)"); + } + + // ---- updateSoldierRecoilForce (0x5AE352..0x5AE463) ---- + { + // Neither object is constructed: only the firearm's template pointer and the template's + // weaponType are read. + alignas(16) static unsigned char templateStorage[sizeof(GenericFireArmTemplate)]; + alignas(16) static unsigned char weaponStorage[sizeof(GenericFireArm)]; + GenericFireArmTemplate* weaponTemplate = reinterpret_cast(templateStorage); + GenericFireArm* weapon = reinterpret_cast(weaponStorage); + weaponTemplate->m_weaponType = 7; + HapticWeaponAccess::setTemplate(reinterpret_cast(weapon), weaponTemplate); + IPlayer* const local = reinterpret_cast(0x1000); + IPlayer* const other = reinterpret_cast(0x2000); + IObject* const asObject = reinterpret_cast(weapon); + + recoilCalls.clear(); + updateSoldierRecoilForce(0, local, 1.0f, 1.0f, asObject); + updateSoldierRecoilForce(other, local, 1.0f, 1.0f, asObject); + updateSoldierRecoilForce(0, 0, 1.0f, 1.0f, asObject); + check(recoilCalls.empty(), "recoil: no occupant, another occupant, or no local player: nothing"); + updateSoldierRecoilForce(local, local, 0.0f, 0.0f, 0); + updateSoldierRecoilForce(local, local, 0.0f, -0.0f, asObject); + check(recoilJoined() == "recoil 0.000 0.000 -1;recoil 0.000 -0.000 -1;", + "recoil: both zero: the weapon is not read (null is fine), even when there is one"); + recoilCalls.clear(); + updateSoldierRecoilForce(local, local, 0.5f, 0.0f, asObject); + updateSoldierRecoilForce(local, local, 0.0f, -0.25f, asObject); + weaponTemplate->m_weaponType = 12; + updateSoldierRecoilForce(local, local, -1.0f, 2.0f, asObject); + check(recoilJoined() == "recoil 0.500 0.000 7;recoil 0.000 -0.250 7;recoil -1.000 2.000 12;", + "recoil: either value non-zero reads the firearm template's weaponType; values passed through"); + } + + // ---- updateSoldierCraftPhysics (0x5AECF5..0x5AED72) ---- + { + ShakeVehicle vehicle; + // A rotation with distinct terms: rows (0,1,0) (-1,0,0) (0,0,1), plus a scale on z. + for (int i = 0; i < 16; ++i) vehicle.inverse.m[i] = 0.0f; + vehicle.inverse.m[1] = 1.0f; vehicle.inverse.m[4] = -1.0f; vehicle.inverse.m[10] = 2.0f; + vehicle.inverse.m[15] = 1.0f; // translation (m[12..14]) is ignored + vehicle.inverse.m[12] = 100.0f; vehicle.inverse.m[13] = 200.0f; vehicle.inverse.m[14] = 300.0f; + Controller controller; + controller.vehicle = &vehicle; + IPlayer* const local = reinterpret_cast(0x1000); + IPlayer* const other = reinterpret_cast(0x2000); + Vec3 velocity; + velocity.x = 3.0f; velocity.y = 5.0f; velocity.z = 7.0f; + + recoilCalls.clear(); + updateSoldierCraftPhysics(0, local, &controller, velocity, 0.02f); + updateSoldierCraftPhysics(other, local, &controller, velocity, 0.02f); + updateSoldierCraftPhysics(0, 0, &controller, velocity, 0.02f); + check(recoilCalls.empty(), "craft physics: no occupant or another occupant: nothing, the vehicle is not read"); + updateSoldierCraftPhysics(local, local, &controller, velocity, 0.02f); + // v * M: x = 3*m0 + 5*m4 + 7*m8 = -5; y = 3*m1 + 5*m5 + 7*m9 = 3; z = 3*m2 + 5*m6 + 7*m10 = 14 + check(recoilJoined() == "player.vehicle;vehicle.inverse;craft -5 3 14 0.020;", + "craft physics: the velocity in the controller's vehicle frame (v * inverse), and dt"); + } + + // ---- updateVehicleCraftPhysics (0x5FAC8C..0x5FADAE): mode 3, the vehicle's inverse transform ---- + { + ShakeVehicle vehicle; + for (int i = 0; i < 16; ++i) vehicle.inverse.m[i] = 0.0f; + vehicle.inverse.m[1] = 1.0f; vehicle.inverse.m[4] = -1.0f; vehicle.inverse.m[10] = 2.0f; + vehicle.inverse.m[15] = 1.0f; + vehicle.inverse.m[12] = 100.0f; vehicle.inverse.m[13] = 200.0f; vehicle.inverse.m[14] = 300.0f; + HapticPhysics physics; + physics.speed.x = 3.0f; physics.speed.y = 5.0f; physics.speed.z = 7.0f; + recoilCalls.clear(); + updateVehicleCraftPhysics(&physics, &vehicle, 0, 0.04f, 2); + check(recoilJoined() == "physics.acceleration;vehicle.inverse;physics.speed;vehicle craft -5 3 14 0.040 2;", + "vehicle craft physics: acceleration read and dropped, speed * the vehicle's inverse transform, dt, category"); + } + + std::printf("soldier haptic profile %u/%u checks passed\n", checks - failures, checks); + return failures ? 1 : 0; +} diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotMain.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/BotMain.cpp index fcca14ec8..ed47ec6c1 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotMain.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotMain.cpp @@ -1,6 +1,12 @@ // Bot implementation: owns its behavior, movement, sensing and communication state. // The manager schedules work through the Bot interface; unimplemented operations stop by name. +#include +#include +#include +#include +// Bot.cpp and BotMain.cpp are combined here; both original TUs only initialized iostreams. +// static init: ELF 0x185D60, 0x185DC0, 0x185DF0, 0x18DA90, 0x18DAF0, 0x18DB20 #include "BotMain.h" #include "BotOrder.h" #include "BotCallBack.h" @@ -12,16 +18,36 @@ #include "BotNavigation.h" #include "BotSquad.h" #include "../AIPlanInterpreter/BAPContext.h" +#include "../AIBotActionPlan/BotScript.h" +#include "../AIPlanInterpreter/PlanInterpreter.h" #include "SensingAgent.h" #include "CommunicationAgent.h" #include "BotSubObjects.h" -#include "../AIBotBehaviour/UrgencyMerger.h" +#include "../AIBotBehaviour/BotBehaviour.h" +#include "UrgencyMerger.h" #include "../AIUtils/checkPointer.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/Information.h" // updatePlayerAction: the equipment's mobile plug-in #include "../AIKnowledge/IPIMobile.h" #include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" #include "../../../../IO/Input/PlayerInput.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../Main/IBotManager.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "BotSenses.h" +#include "WaypointList.h" +#include "WPEmpty.h" +#include "WPAltitudeMoveTo.h" +#include "../AIBotBehaviourPattern/PlanGenerator.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/BFCollisionHandler.h" +#include "../../../AIInterface/BFKnowledge/SoldierPose.h" +#include "../../../../Core/Debug.h" #include // DBL_MAX - the two 'never happened' timestamps namespace dice { @@ -67,20 +93,18 @@ BotMain::BotMain(IAIPlayer* player, m_float32 = f; m_obedience = 1.0f; m_int40 = i; - m_ptr52 = 0; + m_inverseAttention = 0.0f; m_spawnToStrategicAreaId = -1; m_side = n; m_ptr72 = 0; m_float48 = 0.01f; - m_gap88[1] = 0; // +89 + m_badVehicle = false; // +89 m_memory = memory; - m_gap88[2] = 0; // +90 + m_vehicleChanged = false; // +90 m_inTransitionPhase = false; // +91 m_pad92 = 0; // +92 m_deactivated = false; // +93 - m_ptr100 = 0; - m_ptr104 = 0; - m_ptr108 = 0; + // +100..+108: the empty behaviour-queue vector. m_activePlan = 0; m_planLock = false; // +120 @@ -90,9 +114,7 @@ BotMain::BotMain(IAIPlayer* player, m_planInterpreter = interpreter; m_urgencyMerger = merger; m_urgencyGenerators = generators; - m_ptr160 = 0; - m_ptr164 = 0; - m_ptr168 = 0; + m_lookDir = Vec3::getZero(); // sub-object 1 of 6 m_fireCorrection = checkPointer(new FireCorrectionData()); @@ -109,46 +131,47 @@ BotMain::BotMain(IAIPlayer* player, m_ptr260 = 0; m_firingTarget = -1; m_requestedSoldierPose = 1; - m_int304 = -1; + m_poseTestTarget = -1; m_unresolvedCollision = -1; m_ptr252 = 0; // Use -DBL_MAX for uninitialized timestamps; magnitude sentinels use separate values. m_time276 = -DBL_MAX; - m_time288 = -DBL_MAX; + m_soldierPoseAlteredTime = -DBL_MAX; m_botStuck = false; - m_flag285 = false; + m_poseInputActive = false; for (int k = 0; k < 4; ++k) - m_flag300[k] = false; // +300..+303 + m_poseTestResults[k] = false; // +300..+303 m_airBorn = false; // +312 for (int k = 0; k < 3; ++k) - m_ptr316[k] = 0; // +316..+324 + m_spawnCoord[k] = 0; // +316..+324 m_deathCallBack = 0; // +328 m_spawnCallBack = 0; // +332 m_squadMember = 0; m_assignedAreas[0] = -1; m_assignedAreas[3] = -1; // +396 m_assignedAreas[2] = -1; // +392 - m_ptr400 = 0; + m_currentWaypoint[0] = 0.0f; m_assignedAreas[1] = -1; // +388 m_manDown = false; // +360 m_isFiring = false; // +372 m_fireAllowed = true; - m_ptr404 = 0; - m_ptr408 = 0; + m_currentWaypoint[1] = 0.0f; + m_currentWaypoint[2] = 0.0f; m_int412 = -1; m_stalledPlanTicks = 0; - for (int k = 0; k < 3; ++k) - m_ptr428[k] = 0; // +428..+436 + m_c4Explosives.position.x = 0.0f; // +428..+436 (three zero word stores) + m_c4Explosives.position.y = 0.0f; + m_c4Explosives.position.z = 0.0f; m_moveToStatus = 0; m_timeOfLastFailedStaticAttack = 0.0; m_timeOfLastFailedStaticSkyAttack = 0.0; m_avoidSide = 0; for (int k = 0; k < 3; ++k) (&m_wantsToSimulateArtillery)[k] = false; // +500..+502 - m_gap512[0] = 0; // +512 + m_avoidSideChanged = false; // +512 m_collidedObject = -1; - m_double516 = 0.0; + m_timeOfLastStateChange = 0.0; for (int k = 0; k < 3; ++k) m_collidedObjectPosition[k] = 0; // +528..+536 @@ -178,7 +201,7 @@ BotMain::BotMain(IAIPlayer* player, // this byte is set in the middle of the allocations, between SensingAgent and // CommunicationAgent, and it is -1 rather than 0. Reproduced in position. - m_gap64[0] = static_cast(-1); // +64 + m_mode = static_cast(-1); m_communication = checkPointer(new CommunicationAgent(this)); // Allocates matching urgency and behavior arrays, but clears only behavior pointers. @@ -196,15 +219,13 @@ BotMain::BotMain(IAIPlayer* player, recieveOrder(order); // dice's spelling m_waypoints = 0; - m_ptr84 = 0; + m_lastScout = 0.0f; m_player = player; if (player) setPlayerInput(); // zeroed A second time - see the block above. - m_ptr160 = 0; - m_ptr164 = 0; - m_ptr168 = 0; + m_lookDir = Vec3::getZero(); // sub-object 6 of 6, and it is the smallest thing here at four bytes m_bapContext = checkPointer(new BAPContext()); @@ -213,22 +234,53 @@ BotMain::BotMain(IAIPlayer* player, // sense every player, and the storage for that is committed at construction. m_sensedObjects.reserve(256); - m_c4Placed = false; // the constructor's last field store + m_c4Explosives.isPlaced = false; // the constructor's last field store reset(); } -// [CHOSEN, not recovered] Initial behavior count is zero until configured by the module. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding BotMain operation. +// ELF .bss 0x4CDFE8: zero until configured by the module. unsigned char BotMain::mu8NBehaviours = 0; -// ELF .bss / PE .data . Set by prepareBehaviourPool, not per bot. +// ELF .bss 0x4CDFEC. Set by prepareBehaviourPool, not per bot. float* BotMain::maBasicWeights = 0; -// [FRONTIER] Remaining bot lifecycle operations stop by name. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding BotMain operation. +// ELF 0x187A50 (D2). In order: the waypoint list (+124, deleting dtor), the behaviour and urgency +// arrays (delete[]), the memory (+76; the constructor's argument, deleted here), the death and +// spawn callbacks (deleting dtors), the BAP context, the player (IAIPlayer +0x78 +// removePlayerFromGame, then IAIPlayerFactory +0x18 destroy), navigation, squad, sensing and +// communication agents, +376 cleared, the fire correction (plain operator delete); then the +// members (+340 vector, +252 vector, the three lists, the behaviour queues) and Bot. BotMain::~BotMain() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::~BotMain"); + if (m_waypoints) + delete m_waypoints; + if (m_behaviours) + delete[] m_behaviours; + if (m_behaviourUrgencies) + delete[] m_behaviourUrgencies; + if (m_memory) + delete m_memory; + if (m_deathCallBack) + delete m_deathCallBack; + if (m_spawnCallBack) + delete m_spawnCallBack; + if (m_bapContext) + delete m_bapContext; + if (m_player) + { + m_player->removePlayerFromGame(); + static_cast(CommonSingletonServer::m_iaiPlayerFactory)->destroy(m_player); + } + if (m_navigation) + delete m_navigation; + if (m_squad) + delete m_squad; + if (m_sensingAgent) + delete m_sensingAgent; + if (m_communication) + delete m_communication; + m_squadMember = 0; + operator delete(m_fireCorrection); } // Releases each behavior's initialized state without deleting the behavior itself. @@ -237,11 +289,9 @@ void BotMain::uninitAllBehaviours() { for (int i = 0; i < mu8NBehaviours; ++i) { - if (m_behaviours[i]) - { - // Retail here is `m_behaviours[i]->something->uninit(this)` - see the block above. - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::uninitAllBehaviours (a behaviour is present)"); - } + // ELF 0x18A740: behaviour +0xC (the pattern), when set, vtable +0x10 unInit(this). + if (m_behaviours[i] && m_behaviours[i]->getPattern()) + m_behaviours[i]->getPattern()->unInit(this); } } @@ -251,16 +301,14 @@ void BotMain::reset() { m_double172 = 0.0; + // ELF 0x18B6A5 / 0x18B880: IAIPlayer +0x08 reset(). if (m_player) - { - // Retail calls IAIPlayer byte-slot +8 with no arguments. See the block above. - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::reset (IAIPlayer slot +8)"); - } + m_player->reset(); + // ELF 0x18B850: the plan's deleting destructor (BotScript slot +0x08). if (m_activePlan) { - // Retail destroys the plan through byte-slot +8. See the block above. - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::reset (active plan present)"); + delete m_activePlan; m_activePlan = 0; m_planInvalid = true; m_sensingAgent->setOverride(false); @@ -278,22 +326,22 @@ void BotMain::reset() m_stalledPlanTicks = 0; m_int200 = -1; - m_int304 = -1; + m_poseTestTarget = -1; m_avoidSide = 0; m_moveToStatus = 0; m_collidedObject = -1; - m_double364 = 0.0; + m_rearmTimer = 0.0; m_unresolvedCollision = -1; m_grenadeThrownTime[0] = 0.0; m_grenadeThrownTime[1] = 0.0; m_grenadeThrownTime[2] = 0.0; m_timeOfLastFailedStaticAttack = 0.0; m_timeOfLastFailedStaticSkyAttack = 0.0; - m_double516 = 0.0; + m_timeOfLastStateChange = 0.0; m_wantsToSimulateArtillery = false; m_isSimulatingArtillery = false; - m_flag502 = false; - m_gap512[0] = 0; + m_forcePose = false; + m_avoidSideChanged = false; m_collidedObjectPosition[0] = 0; m_collidedObjectPosition[1] = 0; m_collidedObjectPosition[2] = 0; @@ -312,7 +360,7 @@ void BotMain::reset() m_isGoingForFlag = false; m_useStaticAttack = false; // 9999.0, not the ctor's -DBL_MAX. See the block above. - m_time288 = -9999.0; + m_soldierPoseAlteredTime = -9999.0; m_timeOfLastFailedSplashDamageAttack = -9999.0; m_takeOffPosition[0] = 0.0f; m_takeOffPosition[1] = 0.0f; @@ -422,15 +470,44 @@ void BotMain::setTakingOrders(bool taking) { m_takingOrders = taking; } // The two plan-execution brackets. not vtable slots - `planExecution` at +0x010 is, but these // two are ordinary members, so whatever calls them does so on a `BotMain*` and not through `Bot`. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] + +// ELF 0x1891E0: only the movement axes are released before the plan runs. void BotMain::prePlanExecution() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::prePlanExecution"); + resetAllControls(true, false, false); } +// ELF 0x189220 (413 bytes). Soldiers only (equipment type flag 0x200000; no null guard on the +// information). One second after friends were last in the line of fire the avoid side is +// cleared; otherwise the bot strafes (PIYaw +-1) towards the avoid side while the navigation +// reports more than 0.5 of space there (+292 / +296), or switches the side when only the other +// side has space. void BotMain::postPlanExecution() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::postPlanExecution"); + Information* const equipment = informationManager->getInformation(getCurrentEquipment()); + if (!equipment->isOfType(ITSoldier)) + return; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + const double sinceFriendsInLine = now - getFriendsInLineOfFireTime(); + if (sinceFriendsInLine >= 1.0) + { + setAvoidSide(0); + return; + } + if (m_avoidSide == 1) + { + if (getBotNavigation()->getSpaceLeft() > 0.5f) + m_playerInput->setInput(io::PIYaw, -1.0f); + else if (getBotNavigation()->getSpaceRight() > 0.5f) + setAvoidSide(2); + } + else + { + if (getBotNavigation()->getSpaceRight() > 0.5f) + m_playerInput->setInput(io::PIYaw, 1.0f); + else if (getBotNavigation()->getSpaceLeft() > 0.5f) + setAvoidSide(1); + } } // Bot interface implementations, in virtual declaration order. @@ -448,16 +525,381 @@ BotLodLevel BotMain::getLodLevel() const return m_lodLevel; } -// +0x010 +// +0x010. ELF 0x188B90 (1611 bytes). Returns !m_planInvalid in %al; BotManager discards it. +// 1. Clears the change target, then copies a finished bot projectile's flight data from the +// collision handler into the fire correction data (slots +0x44 .. +0x58, +0x40 removes it). +// 2. An invalid plan is dropped (BotScript deleting destructor, vtable +8) and the sensing +// override released. Without a plan, the equipment unit's default behaviour (IAISettings +// +0x1C, or the man-down equipment type +0xA0) generates one (BotBehaviour +0x2C). +// 3. With a valid plan it runs between pre/postPlanExecution; a failure invalidates it. +// The sensing agent updates and runs its own plan with the override disallowed. +// 4. Non-soldiers release PIWeaponSelect9; a soldier falling faster than 1 m/s (speed.y <= -1) +// presses it (inlined Input::setInput: mapped bit 22 -> inputs[22] = 1). void BotMain::planExecution(const double& slice) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::planExecution"); + bool ok = true; + bool failed = false; + resetChangeTarget(); + + IBFCollisionHandler* const collision = + checkPointer(static_cast(CommonSingletonServer::m_iBFCollisionHandler)); + if (collision->botProjectilePassedPoint(m_botId)) + { + m_fireCorrection->m_projectilePrePoint = collision->botProjectilePrePoint(m_botId); + m_fireCorrection->m_projectilePostPoint = collision->botProjectilePostPoint(m_botId); + m_fireCorrection->m_projectileTargetPoint = collision->botProjectileTargetPoint(m_botId); + m_fireCorrection->m_projectileMaxHeight = collision->botProjectileMaxHeight(m_botId); + m_fireCorrection->m_flag5 = true; + m_fireCorrection->m_flag84 = true; + m_fireCorrection->m_flag85 = true; + collision->removeBotProjectile(m_botId); + } + + Information* const equipment = informationManager->getInformation(getCurrentEquipment()); + bool invalid; + bool havePlan = false; + if (m_planInvalid) + { + // ELF 0x188F80: the invalid plan is deleted (BotScript +8, deleting destructor). + if (m_activePlan) + { + delete m_activePlan; + m_activePlan = 0; + m_sensingAgent->setOverride(false); + } + } + else if (m_activePlan) + { + havePlan = true; + } + if (havePlan) + { + invalid = false; + } + else + { + IPIUnit* const unit = equipment ? equipment->getUnit() : 0; + BotBehaviour* behaviour = 0; + if (unit) + { + int type = unit->getEquipmentType(); + if (!m_manDown) + unit->setTime(); + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + if (getManDown()) + type = settings->getManDownEquipmentType(); + behaviour = settings->getDefaultBehaviour(type); + } + // ELF 0x188EFE: the default behaviour's pattern (+0xC) is forced initiated (PlanGenerator + // +0x14), then generatePlan (+0x2C) becomes the active plan; a plan is owned by the bot + // and marks the default plan. + if (behaviour) + { + behaviour->getPattern()->forceInitiated(this); + m_activePlan = behaviour->generatePlan(this); + if (m_activePlan) + { + m_activePlan->mpOwner = this; + m_hasDefaultPlan = true; + m_planInvalid = false; + } + } + invalid = m_planInvalid; + } + + if (!invalid) + { + prePlanExecution(); + // ELF 0x188D82: m_planInterpreter (+0x90) vtable +8 execute(plan, this, &ok, &failed); + // the result is ignored. The flag pair: -0x15A first, -0x159 second; the plan stays + // valid only when the first is set and the second clear. + m_planInterpreter->execute(m_activePlan, this, ok, failed); + postPlanExecution(); + m_planInvalid = failed || !ok; + if (m_planInvalid) + { + setPlanLock(false); + resetAllControls(true, true, true); + m_sensingAgent->clearPlanTargetInformation(); + } + m_sensingAgent->update(); + if (m_sensingAgent->getPlan()) + { + m_sensingAgent->disallowOverride(true); + m_sensingAgent->executePlan(); + m_sensingAgent->disallowOverride(false); + } + } + + // No null guard: the ELF reads the flag word of whatever the handle resolves to. + Information* const current = informationManager->getInformation(m_currentEquipment); + if (!current->isOfType(ITSoldier)) + { + m_playerInput->setInput(io::PIWeaponSelect9, 0.0f); + } + else if (IPIMobile* const mobile = equipment->getMobile()) + { + if (mobile->getSpeed().y <= -1.0f) + m_playerInput->setInput(io::PIWeaponSelect9, 1.0f); + } + pollRequestedSoldierPose(); + (void)slice; } // +0x014. Returns the count BotManager::actionDecisionMaking banks in BotInfo +32 (see BotMain.h). +// ELF 0x1893D0 (3134 bytes). Returns the number of behaviours whose urgency was refreshed. +// 1. A deactivated bot drops its plan and does nothing. +// 2. The inclinations decay; a changed vehicle runs updateBotVehicle and notifies the SAI +// (ISAI +0x40 setBotHasChangedEquipment); a vehicle the bot cannot use is reported. +// 3. Behaviour urgencies are refreshed queue by queue within the slice; once the slice is used +// up the remaining queues only age (each moves into the one before it). +// 4. The urgency merger picks the behaviour (hasChanged(bot, 0.87f, 1.15f) unless the plan is +// invalid), the memory records it, and its generated plan replaces the active one. int BotMain::decisionMaking(const double& slice) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::decisionMaking"); + std::list refreshed; + int count = 0; + if (m_deactivated) + { + // ELF 0x189401: the plan is deleted (BotScript +8, the deleting destructor), the plan + // marked invalid and the sensing override released. + if (m_activePlan) + { + delete m_activePlan; + m_activePlan = 0; + m_planInvalid = true; + m_sensingAgent->setOverride(false); + } + return 0; + } + + const int lastBehaviour = m_memory->m_int0; + stepMoveInclination(); + stepFireInclination(); + if (!m_checkVehicle) + { + IAIObject* const vehicle = m_player->getCurrentVehicle(); + if (!vehicle) + { + m_currentEquipment = static_cast(-1); + m_checkVehicle = true; + } + else + { + m_checkVehicle = vehicle->getInformation(m_side) != m_currentEquipment; + } + } + if (m_checkVehicle) + { + bool usable = false; + if (updateBotVehicle(&usable)) + { + if (m_activePlan) + { + delete m_activePlan; + m_activePlan = 0; + m_planInvalid = true; + m_sensingAgent->setOverride(false); + } + if (!usable || !informationManager->getInformation(m_currentEquipment)) + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIBot/BotMain.cpp", 749, "") << "Bot in bad vehicle!"; + m_badVehicle = true; + m_currentEquipment = static_cast(-1); + return 0; + } + updateBot(); + IAIMain::m_instance->getSAI(m_side)->setBotHasChangedEquipment(m_botId); + } + else if (m_badVehicle) + { + updateBot(); + m_navigation->reset(); + m_badVehicle = false; + IAIMain::m_instance->getSAI(m_side)->setBotHasChangedEquipment(m_botId); + } + m_checkVehicle = false; + } + + const IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); + const double start = timer->getUpdateTime(); + if (m_vehicleChanged) + { + m_planInvalid = true; + m_vehicleChanged = false; + } + if (m_planInvalid) + { + m_memory->m_int0 = -1; + m_memory->m_double16 = timer->getGameTime(); + } + + // Step 3 (ELF 0x189700..0x189B5E). While the slice lasts, queue i is consumed from the front: + // null behaviours are dropped, the others get their urgency refreshed (vtable +0x28, with + // `true`) when positive and move to `refreshed`. When start + slice <= now (getUpdateTime) + // the rest only age: from the current queue on (at least queue 1) every behaviour still gets + // calculateUrgency(this, false, urgency) when positive, then the queue's entries are + // appended to the queue before it and the queue is emptied. The urgency is the stored one, + // scaled (unless the plan is invalid or no behaviour was remembered) by + // BotMemory::modifyBehaviourUrgency(behaviour, game time) and the last behaviour's modifier + // row entry; the two loops multiply in different orders (kept). + unsigned int i = 0; + bool exhausted = false; + for (; i < m_behaviourQueues.size() && !exhausted; ++i) + { + std::list& queue = m_behaviourQueues[i]; + while (!queue.empty()) + { + const unsigned short index = queue.front(); + BotBehaviour* const behaviour = m_behaviours[index]; + if (!behaviour) + { + queue.erase(queue.begin()); + } + else + { + const float stored = m_behaviourUrgencies[index]; + float urgency = stored; + if (!m_planInvalid && lastBehaviour != -1) + { + const float modifier = m_memory->modifyBehaviourUrgency(behaviour, timer->getGameTime()); + urgency = modifier * m_behaviours[lastBehaviour]->getModifiers()[index] * stored; + } + if (0.0f < urgency) + { + ++count; + behaviour->calculateUrgency(this, true, urgency); + } + queue.erase(queue.begin()); + refreshed.push_back(index); + } + if (start + slice <= timer->getUpdateTime()) + { + if (i == 0) + i = 1; + exhausted = true; + break; + } + } + if (exhausted) + break; + } + + if (exhausted) + { + for (; i < m_behaviourQueues.size(); ++i) + { + std::list& queue = m_behaviourQueues[i]; + for (std::list::iterator it = queue.begin(); it != queue.end(); ) + { + const unsigned short index = *it; + BotBehaviour* const behaviour = m_behaviours[index]; + if (!behaviour) + { + it = queue.erase(it); + continue; + } + float urgency; + if (!m_planInvalid && lastBehaviour != -1) + { + const float modifier = m_memory->modifyBehaviourUrgency(behaviour, timer->getGameTime()); + urgency = modifier * m_behaviourUrgencies[index] * m_behaviours[lastBehaviour]->getModifiers()[index]; + } + else + { + urgency = m_behaviourUrgencies[index]; + } + if (0.0f < urgency) + behaviour->calculateUrgency(this, false, urgency); + ++it; + } + std::list& previous = m_behaviourQueues[i - 1]; + previous.insert(previous.end(), queue.begin(), queue.end()); + queue.erase(queue.begin(), queue.end()); + } + } + + // Step 4 (ELF 0x189BE0..). The merger picks the behaviour; the memory records it and the + // game time. An existing plan is handed to the chosen behaviour (+4), or deleted when the + // plan is invalid. A different behaviour clears the plan targets. The generated plan + // replaces the active one (the old one is owned back by the bot, deleted, and the controls + // reset); no plan marks the plan invalid. The refreshed behaviours go to the back of their + // queue group (BotBehaviour +5). + UrgencyGenerator* const merger = m_urgencyMerger; + if (m_planInvalid || merger->hasChanged(this, 0.87f, 1.15f)) + merger->updateActiveUrgency(this); + BotBehaviour* const chosen = static_cast(merger->getChosenGenerator()); + // Shipped defect: the selected behaviour is used without a null check. + m_memory->m_int0 = chosen->getIndex(); + m_memory->m_double16 = timer->getGameTime(); + if (m_activePlan) + { + if (!m_planInvalid) + { + m_activePlan->mpOwner = chosen; + } + else + { + delete m_activePlan; + m_activePlan = 0; + m_sensingAgent->setOverride(false); + } + } + if (lastBehaviour != static_cast(chosen->getIndex())) + m_sensingAgent->clearPlanTargetInformation(); + BotScript* const plan = chosen->generatePlan(this); + if (m_activePlan != plan) + { + if (m_activePlan) + { + m_activePlan->mpOwner = this; + delete m_activePlan; + m_activePlan = 0; + m_sensingAgent->setOverride(false); + } + resetAllControls(true, true, true); + } + m_activePlan = plan; + if (!plan) + { + m_planInvalid = true; + } + else + { + m_planInvalid = false; + m_hasDefaultPlan = false; + plan->mpOwner = this; + } + for (std::list::iterator it = refreshed.begin(); it != refreshed.end(); ++it) + { + std::list& queue = m_behaviourQueues[m_behaviours[*it]->getQueueGroup()]; + queue.insert(queue.end(), static_cast(*it)); + } + return count; +} + +// ELF 0x18C850: decays below 0.01 to zero, else by 0.8; the accumulated delta enters at 0.2. +void BotMain::stepMoveInclination() +{ + if (m_moveInclination <= 0.01f) + m_moveInclination = 0.0f; + else + m_moveInclination = m_moveInclination * 0.8f; + const float delta = m_moveInclinationDelta; + m_moveInclinationDelta = 0.0f; + m_moveInclination = delta * 0.2f + m_moveInclination; +} + +// ELF 0x18C920: the same on the fire pair. +void BotMain::stepFireInclination() +{ + if (m_fireInclination <= 0.01f) + m_fireInclination = 0.0f; + else + m_fireInclination = m_fireInclination * 0.8f; + const float delta = m_fireInclinationDelta; + m_fireInclinationDelta = 0.0f; + m_fireInclination = delta * 0.2f + m_fireInclination; } // +0x018 @@ -466,34 +908,165 @@ void BotMain::cheatExecution() // five bytes - A bare `ret`. The hook exists and does nothing. Reproduced. } + + // +0x01C +// ELF 0x18A1D0: forwards to the sensing agent's BotSenses (+192 -> +104). void BotMain::see(const double& dt) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::see"); + m_sensingAgent->getSenses()->see(dt); } // +0x020 +// ELF 0x18A210: forwards like see. void BotMain::updateSensing(const double& dt) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::updateSensing"); + m_sensingAgent->getSenses()->updateSensing(dt); } // +0x024 +// ELF 0x188AA0: tail of BotNavigation::update (+188). Its bool result is returned in %al +// and BotManager discards it, so the slot keeps its void declaration. void BotMain::updatePathfinding(bool& a, bool* b) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::updatePathfinding"); + m_navigation->update(a, b); } // +0x02C -void BotMain::updateBotVehicle(bool* out) -{ - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::updateBotVehicle"); +// ELF 0x18BCC0 (655 bytes). Returns false only when the bot already uses the vehicle's +// information for its side and is not man-down. Otherwise the manager takes the vehicle +// (IBotManager +0x2C), the old equipment's strength drops to 3/4 and the new one's rises by 4/3, +// and the bot restarts on it. *out tells whether there is a vehicle at all. +bool BotMain::updateBotVehicle(bool* out) +{ + IAIObject* const vehicle = m_player->getCurrentVehicle(); + getPlan(); + m_vehicleChanged = true; + m_planInvalid = true; + m_hasDefaultPlan = false; + if (!vehicle) + { + m_navigation->reset(); + setCurrentEquipment(static_cast(-1)); + if (out) + *out = false; + return true; + } + if (out) + *out = true; + const unsigned int handle = vehicle->getInformation(m_side); + if (handle != static_cast(-1) && getCurrentEquipment() == handle && !m_manDown) + return false; + IBotManager::instance->updateBotVehicle(this, vehicle); + m_airBorn = false; + Information* const previous = informationManager->getInformation(getCurrentEquipment()); + m_lastChangeTime = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + const unsigned int next = vehicle->getInformation(getSide()); + Information* const current = informationManager->getInformation(next); + if (previous) + previous->setStrength(previous->getStrength() * 0.75f); + if (!current) + { + setCurrentEquipment(static_cast(-1)); + return true; + } + m_sensingAgent->deletePlan(); + current->setStrength(current->getStrength() * 1.3333334f); + setCurrentEquipment(next); + setPlanLock(false); + m_navigation->reset(); + m_takeOffPosition[0] = 0.0f; + m_takeOffPosition[1] = 0.0f; + m_takeOffPosition[2] = 0.0f; + resetAllControls(true, true, true); + return true; } // +0x030 -void BotMain::updateBot() +// ELF 0x18BF50 (1488 bytes). (Re)builds the bot for its current equipment: the plan +// interpreter and the applicable behaviours for the equipment type (the man-down type while man +// down), the vehicle modifiers, then a fresh memory and a waypoint list - an empty one at the +// bot's position, or for flags & 0x10 (byte +4 of the information) a climb to 100 m above it. +// False without equipment or without its unit plug-in. +bool BotMain::updateBot() +{ + Information* const equipment = informationManager->getInformation(getCurrentEquipment()); + if (!equipment || !equipment->getUnit()) + return false; + UrgencyGenerator** const generators = getBehaviourUrgencyGenerators(); + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + const int type = m_manDown ? settings->getManDownEquipmentType() // slot +0xA0 + : equipment->getUnit()->getEquipmentType(); + setPlanInterpreter(static_cast(settings->getPlanInterpreter(type))); // +0x20 + const int count = settings->getNumberOfBehaviours(); // +0x0C + for (int i = 0; i < count; ++i) + { + BotBehaviour* behaviour = settings->getBehaviour(type, i); // +0x18 + if (behaviour) + { + if (!behaviour->isAplicable(equipment, this)) // BotBehaviour +0x30 + behaviour = 0; + if (behaviour) + behaviour->reset(this); // +0x24 + } + addBehaviour(behaviour, i); + generators[i] = behaviour; + if (behaviour && behaviour->getPattern()) + behaviour->getPattern()->unInit(this); // PlanGenerator +0x10 + } + m_ptr72 = settings->getVehicleMods(type); // +0x14 + calculateMods(); + getSelector()->updateActiveUrgency(this); // UrgencyGenerator +0x10 + getMemory()->reset(); + if (!equipment->isOfType(ITAir)) + { + // The image re-reads +0x8C (m_currentEquipment) inline here; no null guard. + Information* const self = informationManager->getInformation(m_currentEquipment); + setWaypoints(checkPointer(new WPEmpty(self->getPosition()))); + } + else + { + std::list path; + const Vec3& position = equipment->getPosition(); + Vec3 above; + above.x = position.x + 0.0f; + above.y = position.y + 100.0f; + above.z = position.z + 0.0f; + path.push_back(above); + setWaypoints(checkPointer(new WPAltitudeMoveTo(1.0f, 1.0f, 25.0f, 1, path))); + } + return true; +} + +// ELF 0x18AAD0. +UrgencyGenerator** BotMain::getBehaviourUrgencyGenerators() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::updateBot"); + return m_urgencyGenerators; +} + +// ELF 0x18AAC0. +UrgencyGenerator* BotMain::getSelector() +{ + return m_urgencyMerger; +} + +// ELF 0x18A540 (496 bytes). Grows the queue table to the behaviour's group (+5), queues its +// index (+4) when that slot was empty, and stores it in both the behaviour and generator tables. +void BotMain::addBehaviour(BotBehaviour* b, int i) +{ + if (b) + { + if (m_behaviourQueues.size() <= b->getQueueGroup()) + m_behaviourQueues.resize(static_cast(b->getQueueGroup()) + 1, std::list()); + if (m_behaviours[b->getIndex()] == 0) + { + std::list& queue = m_behaviourQueues[b->getQueueGroup()]; + // `insert(header, idx)`: the list's header node is end() in this STL - a push_back. + queue.insert(queue.end(), static_cast(b->getIndex())); + } + } + m_behaviours[i] = b; + m_urgencyGenerators[i] = b; } // +0x034 @@ -508,6 +1081,13 @@ float BotMain::getObedience() return m_obedience; } +// ELF 0x18ABA0: the int at +0x28 (the ctor's `i`). BBFireUnarmed::calculateUrgency converts the +// answer with cvtsi2ss, hence int. +int BotMain::getHarmlessThrsh() +{ + return m_int40; +} + // +0x03C float* BotMain::getCurrentOrders() { @@ -521,15 +1101,29 @@ WaypointList* BotMain::getWaypoints() } // +0x044 +// ELF 0x18A3D0: the previous list is destroyed through its deleting destructor (vtable +4) +// before the replacement is stored. void BotMain::setWaypoints(WaypointList* w) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::setWaypoints"); + if (m_waypoints) + delete m_waypoints; + m_waypoints = w; } // +0x04C -void BotMain::recieveOrder(BotOrder* order, std::list& targets) +// ELF 0x18A080 (272 bytes). As the one-argument order, with the target list copied in order and +// the modifiers always recalculated. +bool BotMain::recieveOrder(BotOrder* order, std::list& targets) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::recieveOrder"); + if (!m_takingOrders) + return false; + m_currentOrders = order->m_weights; + m_orderedBehaviour = static_cast(order->m_behaviour); + m_list128.clear(); + for (std::list::const_iterator it = targets.begin(); it != targets.end(); ++it) + m_list128.push_back(*it); + calculateMods(); + return true; } // +0x050 @@ -586,6 +1180,18 @@ bool BotMain::isTakingOrders() return m_takingOrders; } +// ELF 0x18A9F0: +0x58 = true. +void BotMain::setUpdateCurrentEquipment() +{ + m_checkVehicle = true; +} + +// ELF 0x18AA00: +0x58. +bool BotMain::getUpdateCurrentEquipment() +{ + return m_checkVehicle; +} + // +0x074 bool BotMain::isOrderedBehaviour(unsigned char behaviour) { @@ -593,15 +1199,48 @@ bool BotMain::isOrderedBehaviour(unsigned char behaviour) } // +0x078 +// ELF 0x18A450 (208 bytes). Only while taking orders, with ordered targets, for the ordered +// behaviour (BotBehaviour's index byte +4): whether `handle` is one of the targets. bool BotMain::isOrderedObject(unsigned int handle, BotBehaviour* b) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::isOrderedObject"); + if (!m_takingOrders || m_list128.empty()) + return false; + if (b->getIndex() != static_cast(m_orderedBehaviour)) + return false; + return std::find(m_list128.begin(), m_list128.end(), handle) != m_list128.end(); +} + +// ELF 0x18A780: +144. +PlanInterpreter* BotMain::getPlanInterpreter() +{ + return m_planInterpreter; +} + +// ELF 0x18A790: +144. +void BotMain::setPlanInterpreter(PlanInterpreter* p) +{ + m_planInterpreter = p; +} + +// ELF 0x18C7D0: +276. +void BotMain::setHadPrecisionTimeStamp(double time) +{ + m_time276 = time; } // +0x07C +// ELF 0x18C5E0 (432 bytes). A new target restarts the fire correction and drops the bot's +// tracked projectile. void BotMain::setFiringTarget(unsigned int handle) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::setFiringTarget"); + if (m_firingTarget == handle) + return; + m_firingTarget = handle; + m_firingTargetTime = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + m_fireCorrection->newTarget(handle); + m_fireCorrection->m_flag84 = false; + checkPointer(static_cast(CommonSingletonServer::m_iBFCollisionHandler)) + ->removeBotProjectile(m_botId); // slot +0x40 } // +0x080 @@ -623,21 +1262,23 @@ SensingAgent* BotMain::getSensingAgent() } // +0x08C +// ELF 0x18AA10: forwarded to the sensing agent. void BotMain::insertBehaviourInformation(float f, const Vec3& v, unsigned char c) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::insertBehaviourInformation"); + m_sensingAgent->insertBehaviourInformation(f, v, c); } // +0x090 -const std::vector& BotMain::getSensedObjects() const +// ELF 0x18AA60: BotSenses::getSensedObjects, the handle -> SensedObject* map at senses +112. +const std::map& BotMain::getSensedObjects() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::getSensedObjects"); + return m_sensingAgent->getSenses()->getSensedObjects(); } -// +0x094 -void* BotMain::getSensedObjectFromHandle(unsigned int handle) const +// +0x094. ELF 0x18A280: BotSenses::getSensedObjectFromHandle. +SensedObject* BotMain::getSensedObjectFromHandle(unsigned int handle) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::getSensedObjectFromHandle"); + return m_sensingAgent->getSenses()->getSensedObjectFromHandle(handle); } // +0x098 @@ -653,27 +1294,28 @@ unsigned int BotMain::getUnresolvedCollisionHandle() } // +0x0A0 -void* BotMain::getIncommingFire() +// ELF 0x18B0C0: `lea 0x54(senses)` - the fire-object list. +std::list >* BotMain::getIncommingFire() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::getIncommingFire"); + return m_sensingAgent->getSenses()->getIncommingFire(); } -// +0x0A4 +// +0x0A4. ELF 0x18B0E0: `flds 0x58(senses)`. float BotMain::getIncommingFireTotalStrength() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::getIncommingFireTotalStrength"); + return m_sensingAgent->getSenses()->getIncommingFireTotalStrength(); } -// +0x0A8 +// +0x0A8. ELF 0x18B100: `flds 0x5c(senses)`. float BotMain::getIncommingFireTotalStrengthAgainstSelf() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::getIncommingFireTotalStrengthAgainstSelf"); + return m_sensingAgent->getSenses()->getIncommingFireTotalStrengthAgainstSelf(); } -// +0x0AC +// +0x0AC. ELF 0x18B120: `flds 0x60(senses)`. float BotMain::getAttackerStrength() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::getAttackerStrength"); + return m_sensingAgent->getSenses()->getAttackerStrength(); } // +0x0B0 @@ -689,9 +1331,10 @@ int BotMain::getPlayerId() const } // +0x0B8 +// ELF 0x18A7D0: IAIPlayer::getInputId (+0x20), no null guard. int BotMain::getInputId() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::getInputId"); + return m_player->getInputId(); } // +0x0BC @@ -741,10 +1384,243 @@ void BotMain::updatePlayerAction(bool stalled) // the speed along the facing (clamped by minThrottle) or to zero; the second releases both look // axes; the third releases fire, alt-fire, the nine weapon and eight position selects, flares // crouch and lie (conditionally), use and reload. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -void BotMain::resetAllControls(bool, bool, bool) +// ELF 0x18ABB0 (1208 bytes). Every release writes 0.0f through Input::setInput(float). +// The soldier test is the equipment's type flag 0x200000; the vehicle throttle is +// -clamp(dot(speed, facing) * 0.5, -minThrottle, minThrottle) with minThrottle = 0.4f +// (ELF 0x4b6884). Flag 0x10 on the equipment skips the throttle; no null guard on that read. +void BotMain::resetAllControls(bool movement, bool look, bool actions) +{ + static float minThrottle = 0.4f; + Information* const equipment = informationManager->getInformation(m_currentEquipment); + const bool soldier = equipment && equipment->isOfType(ITSoldier); + if (movement) + { + m_playerInput->setInput(io::PISprint, 0.0f); + m_playerInput->setInput(io::PIYaw, 0.0f); + m_playerInput->setInput(io::PIPitch, 0.0f); + m_playerInput->setInput(io::PIRoll, 0.0f); + if (!equipment->isOfType(ITAir)) + { + IPIMobile* const mobile = equipment->getMobile(); + float throttle = 0.0f; + if (mobile && !soldier) + { + const Vec3 facing = equipment->getFaceing(); + const Vec3& speed = mobile->getSpeed(); + const float along = (speed.x * facing.x + speed.y * facing.y + speed.z * facing.z) * 0.5f; + // the ELF's fucomi/fcmovnbe order: a NaN product passes through unclamped. + float clamped; + if (-minThrottle > along) + clamped = -minThrottle; + else + clamped = along > minThrottle ? minThrottle : along; + throttle = -clamped; + } + m_playerInput->setInput(io::PIThrottle, throttle); + } + } + if (look) + { + m_playerInput->setInput(io::PIMouseLookX, 0.0f); + m_playerInput->setInput(io::PIMouseLookY, 0.0f); + } + if (actions) + { + m_playerInput->setInput(io::PIFire, 0.0f); + m_playerInput->setInput(io::PIAltFire, 0.0f); + for (int i = io::PIWeaponSelect1; i <= io::PIPositionSelect8; ++i) + m_playerInput->setInput(static_cast(i), 0.0f); + m_playerInput->setInput(io::PIFlareFire, 0.0f); + if (isDead() || !soldier) + { + m_playerInput->setInput(io::PICrouch, 0.0f); + m_playerInput->setInput(io::PILie, 0.0f); + } + m_playerInput->setInput(io::PIUse, 0.0f); + m_playerInput->setInput(io::PIReload, 0.0f); + } +} + +// ELF 0x18CAF0. +void BotMain::resetChangeTarget() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::resetAllControls"); + m_changeTarget = static_cast(-1); +} + +// ELF 0x18CE60. +void BotMain::clearTestResults() +{ + m_poseTestTarget = -1; + for (int k = 0; k < 4; ++k) + m_poseTestResults[k] = false; +} + +// ELF 0x18D660 (223 bytes). A pose is acceptable unless the firing target is an enemy; then +// the results of the last pose test count, if they were made against that target. +bool BotMain::checkPoseOk(bool& out, int pose) +{ + Information* const target = informationManager->getInformation(getFiringTarget()); + if (target && target->getSide() != getSide()) + { + if (m_poseTestTarget != static_cast(getFiringTarget())) + return false; + if (pose != SPCrouching) + { + out = m_poseTestResults[3]; + return m_poseTestResults[2]; + } + out = m_poseTestResults[1]; + return m_poseTestResults[0]; + } + return true; +} + +// ELF 0x18CEE0 (1856 bytes): drives PICrouch / PILie from the current pose (the equipment's +// SoldierPose) towards the requested one. Lying down toggles PILie against its current input +// value (inlined Input read: mapped bit 37 -> inputs[37]). An unknown requested pose reports +// "Internal error, unknown pose." (BotMain.cpp lines 2723 / 2760) and returns early. +void BotMain::pollRequestedSoldierPose() +{ + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + Information* const equipment = informationManager->getInformation(m_currentEquipment); + if (!equipment) + return; + + bool unused = false; + const int current = equipment->getSoldierPose(); + const int requested = m_requestedSoldierPose; + io::PlayerInput* const input = m_playerInput; + // Presses PILie unless it is already fully pressed. + struct Lie + { + static void toggle(io::PlayerInput* in) + { + const float value = ((in->mappingFlags >> io::PILie) & 1) ? in->inputs[io::PILie] : 0.0f; + in->setInput(io::PILie, value != 1.0f ? 1.0f : 0.0f); + } + }; + + bool release = false; // the LAB_19d067 arm: release both, input inactive + if (current == SPCrouching) + { + if (requested == SPCrouching) + { + input->setInput(io::PICrouch, 1.0f); + input->setInput(io::PILie, 0.0f); + m_poseInputActive = false; + } + else if (requested == SPStanding) + { + input->setInput(io::PILie, 0.0f); + input->setInput(io::PICrouch, 0.0f); + clearTestResults(); + m_poseInputActive = true; + } + else if (requested == SPLying) + { + if (checkPoseOk(unused, SPLying) || m_forcePose) + { + input->setInput(io::PICrouch, 0.0f); + Lie::toggle(input); + m_soldierPoseAlteredTime = now; + m_poseInputActive = true; + } + } + else if (requested == SPSwimming) + { + release = true; + } + else + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIBot/BotMain.cpp", 2723, "") << "Internal error, unknown pose."; + return; + } + } + else if (current == SPStanding) + { + if (requested == SPCrouching) + { + if (checkPoseOk(unused, SPCrouching) || m_forcePose) + { + input->setInput(io::PICrouch, 1.0f); + input->setInput(io::PILie, 0.0f); + m_poseInputActive = true; + } + } + else if (requested == SPStanding) + { + input->setInput(io::PICrouch, 0.0f); + input->setInput(io::PILie, 0.0f); + m_poseInputActive = false; + } + else if (requested == SPLying) + { + if (checkPoseOk(unused, SPLying) || m_forcePose) + { + input->setInput(io::PICrouch, 0.0f); + Lie::toggle(input); + m_soldierPoseAlteredTime = now; + m_poseInputActive = true; + } + } + else if (requested == SPSwimming) + { + release = true; + } + else + { + return; + } + } + else if (current == SPLying) + { + if (requested == SPCrouching) + { + if (checkPoseOk(unused, SPCrouching) || m_forcePose) + { + input->setInput(io::PICrouch, 1.0f); + input->setInput(io::PILie, 0.0f); + m_soldierPoseAlteredTime = now; + m_poseInputActive = true; + } + } + else if (requested == SPStanding) + { + input->setInput(io::PICrouch, 0.0f); + Lie::toggle(input); + clearTestResults(); + m_soldierPoseAlteredTime = now; + m_poseInputActive = true; + } + else if (requested == SPLying || requested == SPSwimming) + { + release = true; + } + else + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIBot/BotMain.cpp", 2760, "") << "Internal error, unknown pose."; + return; + } + } + else if (current == SPSwimming) + { + release = true; + } + else + { + m_requestedSoldierPose = SPStanding; + m_poseInputActive = false; + } + if (release) + { + input->setInput(io::PICrouch, 0.0f); + input->setInput(io::PILie, 0.0f); + m_poseInputActive = false; + } + + m_forcePose = false; + if (m_poseInputActive && equipment->isOfType(ITSoldier)) + input->setInput(io::PIFire, 0.0f); } // deactivated bots are dead without consulting the player. @@ -760,10 +1636,8 @@ bool BotMain::setSide(int side) Information* const equipment = informationManager->getInformation(m_currentEquipment); if (equipment) { - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - // IAIObject has no recovered typed interface yet. Retail calls its setSide at ELF - // +0x128 / PE +0x124 through Information's object (+0x20 ELF / +0x28 PE). - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::setSide (equipment IAIObject::setSide)"); + // ELF 0x18C9E0: `mov 0x20(info),%eax; call *0x128(vtbl)` - IAIObject::setSide. + equipment->getAIObject()->setSide(side); } m_side = side; m_player->setSide(side); @@ -771,9 +1645,10 @@ bool BotMain::setSide(int side) } // +0x0CC +// ELF 0x18CA80: IAIPlayer::setName (+0x7C). void BotMain::setName(const std::string& name) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::setName"); + m_player->setName(name); } // +0x0D0 @@ -825,15 +1700,25 @@ BotMemory* BotMain::getMemory() } // +0x0F0 +// ELF 0x18C990: IAIPlayer::getName (+0x18). const std::string& BotMain::getName() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::getName"); + return m_player->getName(); } // +0x0F4 +// ELF 0x18D960: a three-deep history; a repeated time is ignored, otherwise the older two +// shift down (+460 -> +468 -> +476). void BotMain::setTimeOfLastGrenadeThrown(double t) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::setTimeOfLastGrenadeThrown"); + const double last = m_grenadeThrownTime[0]; + if (t != last) + { + const double older = m_grenadeThrownTime[1]; + m_grenadeThrownTime[0] = t; + m_grenadeThrownTime[1] = last; + m_grenadeThrownTime[2] = older; + } } // +0x0F8 @@ -855,15 +1740,18 @@ int BotMain::getSpawnPoint() const } // +0x104 +// ELF 0x18B9E0: IAIPlayer::getSpawnKit (+0x44). int BotMain::getSpawnKit() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::getSpawnKit"); + return m_player->getSpawnKit(); } // +0x108 +// ELF 0x18BA00: spawn group (+0x40) then kit (+0x44). void BotMain::getSpawnTarget(int& a, int& b) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::getSpawnTarget"); + a = m_player->getSpawnGroup(); + b = m_player->getSpawnKit(); } // Keep fresh player/side/id reads @@ -895,9 +1783,19 @@ int BotMain::getSpawnToStrategicAreaId() } // +0x118 +// ELF 0x18BB80: true while the player is dead (and arms +313), then true exactly once on the +// first call that sees the player alive again. bool BotMain::isJustSpawned() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::isJustSpawned"); + if (!m_player->getIsAlive()) + { + m_spawnPending = true; + return true; + } + if (!m_spawnPending) + return false; + m_spawnPending = false; + return true; } // +0x11C @@ -978,33 +1876,51 @@ void BotMain::setBotStuck(bool b) } // +0x14C +// ELF 0x1888F0: the record with the game time and a 240 s life time (0x49CB3C). void BotMain::placeC4(int placementType, Vec3 v, AIStrategicObject* o) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::placeC4"); + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + m_c4Explosives.isPlaced = true; + m_c4Explosives.placementType = placementType; + m_c4Explosives.object = o; + m_c4Explosives.position = v; + m_c4Explosives.placedTime = now; + m_c4Explosives.lifeTime = 240.0; } // +0x150 +// ELF 0x1889C0. bool BotMain::isC4Placed() { - return m_c4Placed; + return m_c4Explosives.isPlaced; } // +0x154 +// ELF 0x188980: type and position stay. void BotMain::removeC4() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::removeC4"); + m_c4Explosives.isPlaced = false; + m_c4Explosives.object = 0; + m_c4Explosives.placedTime = 0.0; + m_c4Explosives.lifeTime = 0.0; } // +0x158 -void* BotMain::getC4() +// ELF 0x188880: a copy of +0x1A4..+0x1CB. +Bot::C4State BotMain::getC4() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::getC4"); + return m_c4Explosives; } // +0x15C +// ELF 0x1889D0: a placed charge past its life time is removed (virtual +0x154). void BotMain::updateC4() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::updateC4"); + if (!m_c4Explosives.isPlaced) + return; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (now > m_c4Explosives.placedTime + m_c4Explosives.lifeTime) + removeC4(); } // +0x160 @@ -1026,25 +1942,54 @@ void* BotMain::getDebugger() // +0x16C void BotMain::event_projectile(FireObject* f, unsigned int h) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::event_projectile"); + // ELF 0x18B1A0: forwards to the senses (+0xC0 -> +0x68). + m_sensingAgent->getSenses()->event_projectile(f, h); } // +0x170 +// ELF 0x18B1E0: a hit on the fire-correction target (+80) confirms the shot (+4, +5 set, +84 +// cleared); any other hit counts as a miss (Bot +0x174 event_shotMissed). void BotMain::event_shotHit(int i, world::IObject* o, const Vec3& v) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::event_shotHit"); + if (o == m_fireCorrection->m_shotTarget) + { + m_fireCorrection->m_flag4 = true; + m_fireCorrection->m_flag5 = true; + m_fireCorrection->m_flag84 = false; + return; + } + event_shotMissed(i, v); } // +0x174 +// ELF 0x18B230 (736 bytes). A miss of the correction shot (+0 the weapon) records where it went +// and the projectile's points from the collision handler, then drops the projectile. void BotMain::event_shotMissed(int i, const Vec3& v) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::event_shotMissed"); + FireCorrectionData* const correction = m_fireCorrection; + if (i != correction->m_weapon) + return; + correction->m_missedPosition = v; + m_fireCorrection->m_double72 = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + m_fireCorrection->m_flag4 = false; + m_fireCorrection->m_flag5 = true; + IBFCollisionHandler* const collision = + checkPointer(static_cast(CommonSingletonServer::m_iBFCollisionHandler)); + m_fireCorrection->m_projectilePrePoint = collision->botProjectilePrePoint(m_botId); // +0x4C + m_fireCorrection->m_projectilePostPoint = collision->botProjectilePostPoint(m_botId); // +0x50 + m_fireCorrection->m_projectileTargetPoint = collision->botProjectileTargetPoint(m_botId); // +0x54 + m_fireCorrection->m_projectileMaxHeight = collision->botProjectileMaxHeight(m_botId); // +0x58 + m_fireCorrection->m_flag5 = true; + m_fireCorrection->m_flag84 = true; + m_fireCorrection->m_flag85 = collision->botProjectilePassedPoint(m_botId); // +0x44 + collision->removeBotProjectile(m_botId); // +0x40 } // +0x178 void BotMain::event_heardObject(unsigned int h) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::event_heardObject"); + // ELF 0x18A190: forwards to the senses (+0xC0 -> +0x68). + m_sensingAgent->getSenses()->event_heardObject(h); } // +0x17C @@ -1084,9 +2029,19 @@ float BotMain::getFireInclination() } // +0x194 +// ELF 0x18CDC0. An unforced change waits while a pose input is held and for one second after +// the last pose change. void BotMain::requestSoldierPose(int pose, bool b) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::requestSoldierPose"); + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (pose != m_requestedSoldierPose) + { + if ((m_poseInputActive || now <= 1.0 + m_soldierPoseAlteredTime) && !b) + return; + m_requestedSoldierPose = pose; + } + if (b) + m_forcePose = true; } // +0x198 @@ -1096,15 +2051,29 @@ int BotMain::getRequestedSolderPose() } // +0x19C +// ELF 0x18D620. void BotMain::setPoseStatus(int pose, unsigned int h, bool a, bool b) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::setPoseStatus"); + m_poseTestTarget = static_cast(h); + if (pose == SPCrouching) + { + m_poseTestResults[0] = a; + m_poseTestResults[1] = b; + } + else + { + m_poseTestResults[2] = a; + m_poseTestResults[3] = b; + } } // +0x1A0 +// ELF 0x18D740: airborne when the equipment is ITAir or ITHelicopter (two single-bit tests, +// testb $0x10 then testb $0x20). void BotMain::event_airborn() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::event_airborn"); + Information* const equipment = informationManager->getInformation(m_currentEquipment); + m_airBorn = equipment && (equipment->isOfType(ITAir) || equipment->isOfType(ITHelicopter)); } // +0x1A4 @@ -1132,9 +2101,30 @@ bool BotMain::getManDown() const } // +0x1B4 +// ELF 0x18D7D0 (382 bytes). While not man-down, every REARM_PERIOD (6.0, double) of +// accumulated time increase each weapon of the armament is topped up by REARM_PERCENT (0.125f) +// for the bot's side. The weapon handles are copied first (a local vector). void BotMain::rearm(Information* i) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::rearm"); + static double REARM_PERIOD = 6.0; + static float REARM_PERCENT = 0.125f; + if (m_manDown) + return; + m_rearmTimer += static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease(); + if (m_rearmTimer > REARM_PERIOD) + { + IPIArmament* const armament = i->getArmament(); + const std::vector weapons = armament->getWeapons(); + for (std::vector::const_iterator it = weapons.begin(); it != weapons.end(); ++it) + { + if (*it == static_cast(-1)) + continue; + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(*it); + if (weapon) + armament->rearm(weapon, REARM_PERCENT, getSide()); + } + m_rearmTimer = 0.0; + } } // +0x1B8 @@ -1253,9 +2243,14 @@ void BotMain::setNewAssignedAreas(int a, int b) } // +0x204 +// ELF 0x18CCB0: the assigned areas equal their copies, `a` is the current waypoint's int, and an +// area is assigned at all. bool BotMain::hasSameAssignedAreas(int a) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::hasSameAssignedAreas"); + bool same = false; + if (m_assignedAreas[0] == m_assignedAreas[2] && m_assignedAreas[3] == m_assignedAreas[1] && a == m_int412) + same = m_assignedAreas[0] != -1; + return same; } // +0x208 @@ -1266,15 +2261,26 @@ void BotMain::copyAssignedAreas() } // +0x20C +// ELF 0x18CD40: the Vec3 at +400 and the int at +412. void BotMain::setCurrentWaypoint(Vec3 v, int i) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::setCurrentWaypoint"); + float* const waypoint = m_currentWaypoint; + waypoint[0] = v.x; + waypoint[1] = v.y; + waypoint[2] = v.z; + m_int412 = i; } // +0x210 -const Vec3& BotMain::getCurrentWaypoint() +// ELF 0x18CD90: the Vec3 at +400, by value. +Vec3 BotMain::getCurrentWaypoint() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::getCurrentWaypoint"); + const float* const waypoint = m_currentWaypoint; + Vec3 v; + v.x = waypoint[0]; + v.y = waypoint[1]; + v.z = waypoint[2]; + return v; } // +0x214 @@ -1334,9 +2340,20 @@ bool BotMain::getBotIsSimulatingArtillery() const } // +0x238 -void BotMain::setAvoidSide(int side) -{ - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::setAvoidSide"); +// ELF 0x18DA20 (112 bytes). Answers whether an earlier switch is still flagged and the side +// changes to another non-zero one; the flag (+512) is set by a switch between two non-zero +// sides and cleared by side 0. +bool BotMain::setAvoidSide(int side) +{ + bool result = false; + if (m_avoidSideChanged && side != m_avoidSide && side != 0) + result = true; + if (side == 0) + m_avoidSideChanged = false; + else if (m_avoidSide != side && m_avoidSide != 0) + m_avoidSideChanged = true; + m_avoidSide = side; + return result; } // +0x23C @@ -1352,9 +2369,18 @@ int BotMain::getMoveToStatus() const } // +0x244 +// ELF 0x18D9A0 (128 bytes). At most one status change per game-time stamp; a stamp ahead of the +// clock (after a time reset) is cleared first. void BotMain::setMoveToStatus(int status) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::setMoveToStatus"); + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (m_timeOfLastStateChange > now) + m_timeOfLastStateChange = 0.0; + if (now - m_timeOfLastStateChange > 0.0) + { + m_timeOfLastStateChange = now; + m_moveToStatus = status; + } } // +0x248 @@ -1370,9 +2396,12 @@ unsigned int BotMain::getCollidedObject() const } // +0x250 +// ELF 0x18EC60: +528. void BotMain::setCollidedObjectPosition(const Vec3& v) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::setCollidedObjectPosition"); + m_collidedObjectPosition[0] = v.x; + m_collidedObjectPosition[1] = v.y; + m_collidedObjectPosition[2] = v.z; } // +0x254 @@ -1444,9 +2473,12 @@ bool BotMain::getIsGoingForFlag() const } // +0x280 +// ELF 0x18CE90: within changeTime (0.8, double, ELF 0x4b6888) of the last pose change. bool BotMain::botInPoseTransition() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::botInPoseTransition"); + static double changeTime = 0.8; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + return now - m_soldierPoseAlteredTime < changeTime; } // +0x284 @@ -1474,9 +2506,12 @@ double BotMain::getTimeOfLastFailedSplashDamageAttack() const } // +0x294 +// ELF 0x18EE00: +576. void BotMain::setTakeOffPosition(const Vec3& v) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::setTakeOffPosition"); + m_takeOffPosition[0] = v.x; + m_takeOffPosition[1] = v.y; + m_takeOffPosition[2] = v.z; } // +0x298 @@ -1488,25 +2523,150 @@ const Vec3& BotMain::getTakeOffPosition() const // +0x29C void BotMain::setQuadSeen() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::setQuadSeen"); + // ELF 0x18A250: forwards to the sensing agent (+0xC0). + m_sensingAgent->setQuadSeen(); } // +0x2A0 bool BotMain::isAttacking(unsigned int handle, double& out) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::isAttacking"); + // ELF 0x18B140: forwards to the senses (+0xC0 -> +0x68). + return m_sensingAgent->getSenses()->isAttacking(handle, out); } // +0x2A4 +// ELF 0x18B510 (368 bytes). The correction shot timed out: drop the projectile. void BotMain::event_shotTimeOut(int i) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::event_shotTimeOut"); + IBFCollisionHandler* const collision = static_cast(CommonSingletonServer::m_iBFCollisionHandler); + if (i == m_fireCorrection->m_weapon) + checkPointer(collision)->removeBotProjectile(m_botId); // slot +0x40 } // +0x2A8 -void BotMain::event_firing(bool& b, int i, const Vec3& v) +// ELF 0x18C520 (192 bytes). Stamps the last-fire time (+172). A shot may carry a fire correction +// when the previous one was confirmed (+5) and none is pending (+84): it is booked (+5 cleared, +// +6 set, +72 = -1.0, the weapon and target stored); otherwise +6 is cleared. Both paths return +// the fire-correction record + 56 (the predicted target), re-reading the record pointer; +// AICollisionHandler::handleProjectileFire (0x382340) books it as the projectile's target point. +// [INFERRED] reference rather than pointer spelling. +const Vec3& BotMain::event_firing(bool& b, int i, const Vec3& v) +{ + m_double172 = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + FireCorrectionData* const correction = m_fireCorrection; + b = correction->m_flag5 && !correction->m_flag84; + if (!b) + { + correction->m_flag6 = false; + return m_fireCorrection->m_predictedTarget; + } + correction->m_flag5 = false; + correction->m_flag6 = true; + correction->m_double72 = -1.0f; + correction->m_weapon = i; + correction->m_firedTarget[0] = v.x; + correction->m_firedTarget[1] = v.y; + correction->m_firedTarget[2] = v.z; + return m_fireCorrection->m_predictedTarget; +} + +// ELF 0x18BBD0: `lea 0x13c(this)`. +const Vec3& BotMain::getSpawnCoord() const +{ + return *reinterpret_cast(m_spawnCoord); +} + +// ELF 0x18BBE0: a component copy into +316. BotManager::setBotIsAlive calls it on every spawn. +void BotMain::setSpawnCoord(const Vec3& v) +{ + m_spawnCoord[0] = v.x; + m_spawnCoord[1] = v.y; + m_spawnCoord[2] = v.z; +} + +// ELF 0x18C7B0: `fldl 0xac(this)` - the double at +172. +double BotMain::getTimeOfLastFire() const +{ + return m_double172; +} + +// ELF 0x18AB80: fst preserves the returned value in st(0). +float BotMain::setInvAttention(float value) +{ + m_inverseAttention = value; + return value; +} + +// ELF 0x18A360. +unsigned char BotMain::getMode() { return m_mode; } + +// ELF 0x18A520. +void BotMain::setMode(unsigned char mode) { m_mode = mode; } + +// ELF 0x18A390. +float BotMain::getLastScout() { return m_lastScout; } + +// ELF 0x18A6C0: does not delete the behaviour or remove its queued index. +void BotMain::removeBehaviour(BotBehaviour* behaviour) +{ + m_behaviours[behaviour->getIndex()] = 0; + m_urgencyGenerators[behaviour->getIndex()] = 0; +} + +// ELF 0x18A6F0. +BotBehaviour* BotMain::getActiveBehaviour() +{ + const int index = m_memory->m_int0; + return index == -1 ? 0 : m_behaviours[index]; +} + +// ELF 0x18AB40. +float BotMain::setObedience(float value) { return m_obedience = value; } + +// ELF 0x18AB50. +float BotMain::getAttention() { return m_float48; } + +// ELF 0x18AB60. +float BotMain::setAttention(float value) { return m_float48 = value; } + +// ELF 0x18AB70. +float BotMain::getInvAttention() { return m_inverseAttention; } + +// ELF 0x18AB90. +float BotMain::getMarksmanship() { return m_float32; } + +// ELF 0x18B070. +const Vec3& BotMain::getLookDir() { return m_lookDir; } + +// ELF 0x18B080. +void BotMain::setLookDir(const Vec3& direction) { m_lookDir = direction; } + +// ELF 0x18B180: borrowed attacker map owned by the sensing state. +void* BotMain::getAttackers() const { return &m_sensingAgent->getSenses()->m_map100; } + +// ELF 0x18B890. Shipped defect: this validation only reports an error. +bool BotMain::validateDataStructures() +{ + Debug(DebugTypeError, "AI/AIDLL/AI/AIBot/BotMain.cpp", 1764, "") + << "Doesn't work, didn't think it needed to."; + return true; +} + +// ELF 0x18C7C0. +double BotMain::getHadPrecisionTimeStamp() const { return m_time276; } + +// ELF 0x18C820. +void BotMain::clearMoveInclination() +{ + m_moveInclination = 0.0f; + m_moveInclinationDelta = 0.0f; +} + +// ELF 0x18C8F0. +void BotMain::clearFireInclination() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::event_firing"); + m_fireInclination = 0.0f; + m_fireInclinationDelta = 0.0f; } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotMain.h b/Code/BF2/AI/AIDLL/AI/AIBot/BotMain.h index 68e261a63..c565c90d1 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotMain.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotMain.h @@ -7,6 +7,8 @@ #include "../../../../Math/Vec3.h" #include +#include +#include #include #include @@ -37,38 +39,58 @@ class IBotDeathCallBack; class IBotSpawnCallBack; class Information; class PlanInterpreter; +class SensedObject; class SensingAgent; class SquadMember; class UrgencyGenerator; class WaypointList; +#if defined(BF2_PLATFORM_POSIX) +// [CHOSEN, not recovered] Match AISettingsInterfaces.h's forward declaration on Clang/GCC. +enum BotLodLevel : int { BotLodFull = 0, BotLodMedium = 1, BotLodLight = 2 }; +#else enum BotLodLevel { BotLodFull = 0, BotLodMedium = 1, BotLodLight = 2 }; // [CHOSEN] - see BotManager +#endif // Base interface used by the bot manager to schedule and query bots. // [RETIRE-WHEN: botmain-bases] Remove when the corresponding implementation is complete and validated. class Bot { public: + // The C4 record BotMain keeps at +0x1A4 and getC4 (ELF 0x188880, `ret $4`) returns by value: + // placeC4 (0x1888F0) and removeC4 (0x188980) write it. BBC4::calculateUrgency reads it. + // [INFERRED] type and field names; placement type stays an int (the enum's labels are not + // recovered; Bot::C4PlacementType is attested by the placeC4 mangling). + struct C4State + { + /* +0x00 */ bool isPlaced; // name: AIDLL_r assert "m_c4Explosives.isPlaced" (0x1014B2E0; PE +0x1D8) + /* +0x04 */ int placementType; + /* +0x08 */ Vec3 position; + /* +0x14 */ AIStrategicObject* object; + /* +0x18 */ double placedTime; // game time at placeC4 + /* +0x20 */ double lifeTime; // 240.0 (0x49CB3C) at placeC4; updateC4 removes after it + }; + virtual ~Bot(); // - one instruction each virtual void setLodLevel(BotLodLevel level) = 0; // +0x008 virtual BotLodLevel getLodLevel() const = 0; // +0x00C - virtual void planExecution(const double& slice) = 0; // +0x010 [FRONTIER] - virtual int decisionMaking(const double& slice) = 0; // +0x014 [FRONTIER] + virtual void planExecution(const double& slice) = 0; // +0x010 + virtual int decisionMaking(const double& slice) = 0; // +0x014 virtual void cheatExecution() = 0; // +0x018 - virtual void see(const double& dt) = 0; // +0x01C [FRONTIER] - virtual void updateSensing(const double& dt) = 0; // +0x020 [FRONTIER] - virtual void updatePathfinding(bool& a, bool* b) = 0; // +0x024 [FRONTIER] + virtual void see(const double& dt) = 0; // +0x01C + virtual void updateSensing(const double& dt) = 0; // +0x020 + virtual void updatePathfinding(bool& a, bool* b) = 0; // +0x024 virtual void reset() = 0; // +0x028 - virtual void updateBotVehicle(bool* out) = 0; // +0x02C [FRONTIER] - virtual void updateBot() = 0; // +0x030 [FRONTIER] + virtual bool updateBotVehicle(bool* out) = 0; // +0x02C + virtual bool updateBot() = 0; // +0x030 (ELF bool) virtual BotSquad* getBotSquad() const = 0; // +0x034 virtual float getObedience() = 0; // +0x038 virtual float* getCurrentOrders() = 0; // +0x03C order weights virtual WaypointList* getWaypoints() = 0; // +0x040 - virtual void setWaypoints(WaypointList* w) = 0; // +0x044 [FRONTIER] + virtual void setWaypoints(WaypointList* w) = 0; // +0x044 virtual bool recieveOrder(BotOrder* order) = 0; // +0x048 - virtual void recieveOrder(BotOrder* order, std::list& targets) = 0; // +0x04C [FRONTIER] + virtual bool recieveOrder(BotOrder* order, std::list& targets) = 0; // +0x04C (ELF answers 0/1) virtual std::list* getOrderList(unsigned char behaviour) = 0; // +0x050 virtual bool hasPlan() = 0; // +0x054 virtual bool hasDefaultPlan() const = 0; // +0x058 @@ -79,28 +101,28 @@ class Bot virtual void setPlanLock(bool b) = 0; // +0x06C virtual bool isTakingOrders() = 0; // +0x070 virtual bool isOrderedBehaviour(unsigned char behaviour) = 0; // +0x074 - virtual bool isOrderedObject(unsigned int handle, BotBehaviour* b) = 0; // +0x078 [FRONTIER] - virtual void setFiringTarget(unsigned int handle) = 0; // +0x07C [FRONTIER] + virtual bool isOrderedObject(unsigned int handle, BotBehaviour* b) = 0; // +0x078 + virtual void setFiringTarget(unsigned int handle) = 0; // +0x07C virtual unsigned int getFiringTarget() const = 0; // +0x080 virtual double getFiringTargetTime() const = 0; // +0x084 virtual SensingAgent* getSensingAgent() = 0; // +0x088 - virtual void insertBehaviourInformation(float f, const Vec3& v, unsigned char c) = 0; // +0x08C [FRONTIER] - virtual const std::vector& getSensedObjects() const = 0; // +0x090 [FRONTIER] - virtual void* getSensedObjectFromHandle(unsigned int handle) const = 0; // +0x094 [FRONTIER] + virtual void insertBehaviourInformation(float f, const Vec3& v, unsigned char c) = 0; // +0x08C + virtual const std::map& getSensedObjects() const = 0; // +0x090 + virtual SensedObject* getSensedObjectFromHandle(unsigned int handle) const = 0; // +0x094 virtual void setUnresolvedCollisionObject(unsigned int handle) = 0; // +0x098 virtual unsigned int getUnresolvedCollisionHandle() = 0; // +0x09C - virtual void* getIncommingFire() = 0; // +0x0A0 [FRONTIER] - virtual float getIncommingFireTotalStrength() = 0; // +0x0A4 [FRONTIER] - virtual float getIncommingFireTotalStrengthAgainstSelf() = 0; // +0x0A8 [FRONTIER] - virtual float getAttackerStrength() const = 0; // +0x0AC [FRONTIER] + virtual std::list >* getIncommingFire() = 0; // +0x0A0 + virtual float getIncommingFireTotalStrength() = 0; // +0x0A4 + virtual float getIncommingFireTotalStrengthAgainstSelf() = 0; // +0x0A8 + virtual float getAttackerStrength() const = 0; // +0x0AC virtual CommunicationAgent* getCommunicationAgent() = 0; // +0x0B0 virtual int getPlayerId() const = 0; // +0x0B4 - virtual int getInputId() = 0; // +0x0B8 [FRONTIER] + virtual int getInputId() = 0; // +0x0B8 virtual IAIPlayer* getPlayer() const = 0; // +0x0BC virtual void updatePlayerAction(bool stalled) = 0; // +0x0C0 virtual bool isDead() const = 0; // +0x0C4 - virtual bool setSide(int side) = 0; // +0x0C8 equipment arm [FRONTIER] - virtual void setName(const std::string& name) = 0; // +0x0CC [FRONTIER] + virtual bool setSide(int side) = 0; // +0x0C8 + virtual void setName(const std::string& name) = 0; // +0x0CC virtual bool isDeactivated() const = 0; // +0x0D0 virtual void setAsDeactivated(bool b) = 0; // +0x0D4 virtual unsigned int getCurrentEquipment() const = 0; // +0x0D8 @@ -109,17 +131,17 @@ class Bot virtual int getBotType() const; // +0x0E4 virtual unsigned int getBotId() const = 0; // +0x0E8 virtual BotMemory* getMemory() = 0; // +0x0EC - virtual const std::string& getName() const = 0; // +0x0F0 [FRONTIER] - virtual void setTimeOfLastGrenadeThrown(double t) = 0; // +0x0F4 [FRONTIER] + virtual const std::string& getName() const = 0; // +0x0F0 + virtual void setTimeOfLastGrenadeThrown(double t) = 0; // +0x0F4 virtual double getTimeOfGrenadeThrown(int i) const = 0; // +0x0F8 virtual BotNavigation* getBotNavigation() = 0; // +0x0FC virtual int getSpawnPoint() const = 0; // ELF +0x100 / PE +0xFC - virtual int getSpawnKit() const = 0; // +0x104 [FRONTIER] - virtual void getSpawnTarget(int& a, int& b) const = 0; // +0x108 [FRONTIER] + virtual int getSpawnKit() const = 0; // +0x104 + virtual void getSpawnTarget(int& a, int& b) const = 0; // +0x108 virtual void setSpawnTarget(int spawnGroup, int kit) = 0; // ELF +0x10C / PE +0x10C (overload order) virtual void setSpawnTarget(int strategicArea, int spawnGroup, int kit) = 0; // +0x110 virtual int getSpawnToStrategicAreaId() = 0; // +0x114 - virtual bool isJustSpawned() = 0; // +0x118 [FRONTIER] + virtual bool isJustSpawned() = 0; // +0x118 virtual IBotDeathCallBack* getDeathCallBack() const = 0; // +0x11C virtual void setDeathCallBack(IBotDeathCallBack* cb) = 0; // +0x120 virtual IBotSpawnCallBack* getSpawnCallBack() const = 0; // +0x124 @@ -132,33 +154,33 @@ class Bot virtual SquadMember* getSquadMember() = 0; // +0x140 virtual bool isBotStuck() = 0; // +0x144 virtual void setBotStuck(bool b) = 0; // +0x148 - virtual void placeC4(int placementType, Vec3 v, AIStrategicObject* o) = 0; // +0x14C [FRONTIER] + virtual void placeC4(int placementType, Vec3 v, AIStrategicObject* o) = 0; // +0x14C virtual bool isC4Placed() = 0; // +0x150 - virtual void removeC4() = 0; // +0x154 [FRONTIER] - virtual void* getC4() = 0; // +0x158 [FRONTIER] - virtual void updateC4() = 0; // +0x15C [FRONTIER] + virtual void removeC4() = 0; // +0x154 + virtual C4State getC4() = 0; // +0x158 + virtual void updateC4() = 0; // +0x15C virtual void enableBotScriptDebugger(bool /*enable*/) = 0; // +0x160 virtual void* getDebugger() = 0; // +0x164 virtual BAPContext* getScriptContext(); // +0x168 - virtual void event_projectile(FireObject* f, unsigned int h) = 0; // +0x16C [FRONTIER] - virtual void event_shotHit(int i, world::IObject* o, const Vec3& v) = 0; // +0x170 [FRONTIER] - virtual void event_shotMissed(int i, const Vec3& v) = 0; // +0x174 [FRONTIER] - virtual void event_heardObject(unsigned int h) = 0; // +0x178 [FRONTIER] + virtual void event_projectile(FireObject* f, unsigned int h) = 0; // +0x16C + virtual void event_shotHit(int i, world::IObject* o, const Vec3& v) = 0; // +0x170 + virtual void event_shotMissed(int i, const Vec3& v) = 0; // +0x174 + virtual void event_heardObject(unsigned int h) = 0; // +0x178 virtual bool isInTransitionPhase() const = 0; // +0x17C virtual void setIsInTransitionPhase(bool b) = 0; // +0x180 virtual void addToMoveInclination(float f) = 0; // +0x184 virtual void addToFireInclination(float f) = 0; // +0x188 virtual float getMoveInclination() = 0; // +0x18C virtual float getFireInclination() = 0; // +0x190 - virtual void requestSoldierPose(int pose, bool b) = 0; // +0x194 [FRONTIER] + virtual void requestSoldierPose(int pose, bool b) = 0; // +0x194 virtual int getRequestedSolderPose() = 0; // +0x198 - virtual void setPoseStatus(int pose, unsigned int h, bool a, bool b) = 0; // +0x19C [FRONTIER] - virtual void event_airborn() = 0; // +0x1A0 [FRONTIER] + virtual void setPoseStatus(int pose, unsigned int h, bool a, bool b) = 0; // +0x19C + virtual void event_airborn() = 0; // +0x1A0 virtual bool isAirBorn() const = 0; // +0x1A4 virtual void setLastChangeTime(double t) = 0; // +0x1A8 virtual void setManDown(bool b) = 0; // +0x1AC virtual bool getManDown() const = 0; // +0x1B0 - virtual void rearm(Information* i) = 0; // +0x1B4 [FRONTIER] + virtual void rearm(Information* i) = 0; // +0x1B4 virtual void setChangeTarget(unsigned int h) = 0; // +0x1B8 virtual unsigned int getChangeTarget() const = 0; // +0x1BC virtual void setRepairTarget(unsigned int h) = 0; // +0x1C0 @@ -173,6 +195,12 @@ class Bot // [INFERRED] friendship, like BotMain's below: BotManager::actionExecutePlan reads +4 inline // through a `Bot*` to press a climbing bot's inputs. friend class BotManager; + // [INFERRED] likewise: CommunicationAgent::shutOffHorn (ELF 0x1C53F0) reads +4 inline. + friend class CommunicationAgent; + // [INFERRED] likewise: SquadMember::update (ELF 0x1B1ED0) presses the weapon input via +4. + friend class SquadMember; + // [INFERRED] inline reader of +4 (no symbol): the BAP actions and entries read the bound input directly. + io::PlayerInput* getInput() const { return m_playerInput; } protected: // Base construction leaves both pointers uninitialized. Player input is borrowed and @@ -205,23 +233,23 @@ class BotMain : public Bot // [RETIRE-WHEN: botmain-bases] Remove when the corresponding implementation is complete and validated. virtual void setLodLevel(BotLodLevel level); // +0x008 virtual BotLodLevel getLodLevel() const; // +0x00C - virtual void planExecution(const double& slice); // +0x010 [FRONTIER] + virtual void planExecution(const double& slice); // +0x010 ELF 0x188B90 // [INFERRED] Returns an integer work count accumulated by BotManager. - virtual int decisionMaking(const double& slice); // +0x014 [FRONTIER] + virtual int decisionMaking(const double& slice); // +0x014 ELF 0x1893D0 virtual void cheatExecution(); // +0x018 - virtual void see(const double& dt); // +0x01C [FRONTIER] - virtual void updateSensing(const double& dt); // +0x020 [FRONTIER] - virtual void updatePathfinding(bool& a, bool* b); // +0x024 [FRONTIER] + virtual void see(const double& dt); // +0x01C + virtual void updateSensing(const double& dt); // +0x020 + virtual void updatePathfinding(bool& a, bool* b); // +0x024 virtual void reset(); // +0x028 - virtual void updateBotVehicle(bool* out); // +0x02C [FRONTIER] - virtual void updateBot(); // +0x030 [FRONTIER] + virtual bool updateBotVehicle(bool* out); // +0x02C + virtual bool updateBot(); // +0x030 ELF 0x18BF50 virtual BotSquad* getBotSquad() const; // +0x034 virtual float getObedience(); // +0x038 virtual float* getCurrentOrders(); // +0x03C order weights virtual WaypointList* getWaypoints(); // +0x040 - virtual void setWaypoints(WaypointList* w); // +0x044 [FRONTIER] + virtual void setWaypoints(WaypointList* w); // +0x044 virtual bool recieveOrder(BotOrder* order); // +0x048 - virtual void recieveOrder(BotOrder* order, std::list& targets); // +0x04C [FRONTIER] + virtual bool recieveOrder(BotOrder* order, std::list& targets); // +0x04C (ELF answers 0/1) virtual std::list* getOrderList(unsigned char behaviour); // +0x050 virtual bool hasPlan(); // +0x054 virtual bool hasDefaultPlan() const; // +0x058 @@ -232,28 +260,28 @@ class BotMain : public Bot virtual void setPlanLock(bool b); // +0x06C virtual bool isTakingOrders(); // +0x070 virtual bool isOrderedBehaviour(unsigned char behaviour); // +0x074 - virtual bool isOrderedObject(unsigned int handle, BotBehaviour* b); // +0x078 [FRONTIER] - virtual void setFiringTarget(unsigned int handle); // +0x07C [FRONTIER] + virtual bool isOrderedObject(unsigned int handle, BotBehaviour* b); // +0x078 + virtual void setFiringTarget(unsigned int handle); // +0x07C ELF 0x18C5E0 virtual unsigned int getFiringTarget() const; // +0x080 virtual double getFiringTargetTime() const; // +0x084 virtual SensingAgent* getSensingAgent(); // +0x088 - virtual void insertBehaviourInformation(float f, const Vec3& v, unsigned char c); // +0x08C [FRONTIER] - virtual const std::vector& getSensedObjects() const; // +0x090 [FRONTIER] - virtual void* getSensedObjectFromHandle(unsigned int handle) const; // +0x094 [FRONTIER] + virtual void insertBehaviourInformation(float f, const Vec3& v, unsigned char c); // +0x08C + virtual const std::map& getSensedObjects() const; // +0x090 + virtual SensedObject* getSensedObjectFromHandle(unsigned int handle) const; // +0x094 virtual void setUnresolvedCollisionObject(unsigned int handle); // +0x098 virtual unsigned int getUnresolvedCollisionHandle(); // +0x09C - virtual void* getIncommingFire(); // +0x0A0 [FRONTIER] - virtual float getIncommingFireTotalStrength(); // +0x0A4 [FRONTIER] - virtual float getIncommingFireTotalStrengthAgainstSelf(); // +0x0A8 [FRONTIER] - virtual float getAttackerStrength() const; // +0x0AC [FRONTIER] + virtual std::list >* getIncommingFire(); // +0x0A0 + virtual float getIncommingFireTotalStrength(); // +0x0A4 + virtual float getIncommingFireTotalStrengthAgainstSelf(); // +0x0A8 + virtual float getAttackerStrength() const; // +0x0AC virtual CommunicationAgent* getCommunicationAgent(); // +0x0B0 virtual int getPlayerId() const; // +0x0B4 - virtual int getInputId(); // +0x0B8 [FRONTIER] + virtual int getInputId(); // +0x0B8 virtual IAIPlayer* getPlayer() const; // +0x0BC virtual void updatePlayerAction(bool stalled); // +0x0C0 virtual bool isDead() const; // +0x0C4 - virtual bool setSide(int side); // +0x0C8 equipment arm [FRONTIER] - virtual void setName(const std::string& name); // +0x0CC [FRONTIER] + virtual bool setSide(int side); // +0x0C8 + virtual void setName(const std::string& name); // +0x0CC virtual bool isDeactivated() const; // +0x0D0 virtual void setAsDeactivated(bool b); // +0x0D4 virtual unsigned int getCurrentEquipment() const; // +0x0D8 @@ -262,17 +290,17 @@ class BotMain : public Bot virtual int getBotType() const; // +0x0E4 virtual unsigned int getBotId() const; // +0x0E8 virtual BotMemory* getMemory(); // +0x0EC - virtual const std::string& getName() const; // +0x0F0 [FRONTIER] - virtual void setTimeOfLastGrenadeThrown(double t); // +0x0F4 [FRONTIER] + virtual const std::string& getName() const; // +0x0F0 + virtual void setTimeOfLastGrenadeThrown(double t); // +0x0F4 virtual double getTimeOfGrenadeThrown(int i) const; // +0x0F8 virtual BotNavigation* getBotNavigation(); // +0x0FC virtual int getSpawnPoint() const; - virtual int getSpawnKit() const; // +0x104 [FRONTIER] - virtual void getSpawnTarget(int& a, int& b) const; // +0x108 [FRONTIER] + virtual int getSpawnKit() const; // +0x104 + virtual void getSpawnTarget(int& a, int& b) const; // +0x108 virtual void setSpawnTarget(int spawnGroup, int kit); virtual void setSpawnTarget(int strategicArea, int spawnGroup, int kit); // +0x110 virtual int getSpawnToStrategicAreaId(); // +0x114 - virtual bool isJustSpawned(); // +0x118 [FRONTIER] + virtual bool isJustSpawned(); // +0x118 virtual IBotDeathCallBack* getDeathCallBack() const; // +0x11C virtual void setDeathCallBack(IBotDeathCallBack* cb); // +0x120 virtual IBotSpawnCallBack* getSpawnCallBack() const; // +0x124 @@ -285,33 +313,33 @@ class BotMain : public Bot virtual SquadMember* getSquadMember(); // +0x140 virtual bool isBotStuck(); // +0x144 virtual void setBotStuck(bool b); // +0x148 - virtual void placeC4(int placementType, Vec3 v, AIStrategicObject* o); // +0x14C [FRONTIER] + virtual void placeC4(int placementType, Vec3 v, AIStrategicObject* o); // +0x14C virtual bool isC4Placed(); // +0x150 - virtual void removeC4(); // +0x154 [FRONTIER] - virtual void* getC4(); // +0x158 [FRONTIER] - virtual void updateC4(); // +0x15C [FRONTIER] + virtual void removeC4(); // +0x154 + virtual C4State getC4(); // +0x158 + virtual void updateC4(); // +0x15C virtual void enableBotScriptDebugger(bool /*enable*/); // +0x160 virtual void* getDebugger(); // +0x164 // Inherits Bot::getScriptContext; do not add a derived override for that slot. - virtual void event_projectile(FireObject* f, unsigned int h); // +0x16C [FRONTIER] - virtual void event_shotHit(int i, world::IObject* o, const Vec3& v); // +0x170 [FRONTIER] - virtual void event_shotMissed(int i, const Vec3& v); // +0x174 [FRONTIER] - virtual void event_heardObject(unsigned int h); // +0x178 [FRONTIER] + virtual void event_projectile(FireObject* f, unsigned int h); // +0x16C + virtual void event_shotHit(int i, world::IObject* o, const Vec3& v); // +0x170 + virtual void event_shotMissed(int i, const Vec3& v); // +0x174 + virtual void event_heardObject(unsigned int h); // +0x178 virtual bool isInTransitionPhase() const; // +0x17C virtual void setIsInTransitionPhase(bool b); // +0x180 virtual void addToMoveInclination(float f); // +0x184 virtual void addToFireInclination(float f); // +0x188 virtual float getMoveInclination(); // +0x18C virtual float getFireInclination(); // +0x190 - virtual void requestSoldierPose(int pose, bool b); // +0x194 [FRONTIER] + virtual void requestSoldierPose(int pose, bool b); // +0x194 virtual int getRequestedSolderPose(); // +0x198 - virtual void setPoseStatus(int pose, unsigned int h, bool a, bool b); // +0x19C [FRONTIER] - virtual void event_airborn(); // +0x1A0 [FRONTIER] + virtual void setPoseStatus(int pose, unsigned int h, bool a, bool b); // +0x19C + virtual void event_airborn(); // +0x1A0 virtual bool isAirBorn() const; // +0x1A4 virtual void setLastChangeTime(double t); // +0x1A8 virtual void setManDown(bool b); // +0x1AC virtual bool getManDown() const; // +0x1B0 - virtual void rearm(Information* i); // +0x1B4 [FRONTIER] + virtual void rearm(Information* i); // +0x1B4 virtual void setChangeTarget(unsigned int h); // +0x1B8 virtual unsigned int getChangeTarget() const; // +0x1BC virtual void setRepairTarget(unsigned int h); // +0x1C0 @@ -331,10 +359,10 @@ class BotMain : public Bot virtual void setMineTarget(unsigned int h); // +0x1F8 virtual unsigned int getMineTarget() const; // +0x1FC virtual void setNewAssignedAreas(int a, int b); // +0x200 - virtual bool hasSameAssignedAreas(int a); // +0x204 [FRONTIER] + virtual bool hasSameAssignedAreas(int a); // +0x204 virtual void copyAssignedAreas(); // +0x208 - virtual void setCurrentWaypoint(Vec3 v, int i); // +0x20C [FRONTIER] - virtual const Vec3& getCurrentWaypoint(); // +0x210 [FRONTIER] + virtual void setCurrentWaypoint(Vec3 v, int i); // +0x20C + virtual Vec3 getCurrentWaypoint(); // +0x210 by value (ELF sret) virtual void resetAssignedAreas(); // +0x214 virtual void setTimeOfLastFailedStaticSkyAttack(double t); // +0x218 virtual double getTimeOfLastFailedStaticSkyAttack() const; // +0x21C @@ -344,13 +372,13 @@ class BotMain : public Bot virtual bool getBotWantsToSimulateArtillery() const; // +0x22C virtual void setBotIsSimulatingArtillery(bool b); // +0x230 virtual bool getBotIsSimulatingArtillery() const; // +0x234 - virtual void setAvoidSide(int side); // +0x238 [FRONTIER] + virtual bool setAvoidSide(int side); // +0x238 (ELF answers 0/1) virtual int getAvoidSide() const; // +0x23C virtual int getMoveToStatus() const; // +0x240 - virtual void setMoveToStatus(int status); // +0x244 [FRONTIER] + virtual void setMoveToStatus(int status); // +0x244 virtual void setCollidedObject(unsigned int h); // +0x248 virtual unsigned int getCollidedObject() const; // +0x24C - virtual void setCollidedObjectPosition(const Vec3& v); // +0x250 [FRONTIER] + virtual void setCollidedObjectPosition(const Vec3& v); // +0x250 virtual const Vec3& getCollidedObjectPosition() const; // +0x254 virtual void setIgnoreObstacles(bool b); // +0x258 virtual bool getIgnoreObstacles() const; // +0x25C @@ -362,17 +390,17 @@ class BotMain : public Bot virtual double getLastCheckMoveToFinishedTime() const; // +0x274 virtual void setIsGoingForFlag(bool b); // +0x278 virtual bool getIsGoingForFlag() const; // +0x27C - virtual bool botInPoseTransition() const; // +0x280 [FRONTIER] + virtual bool botInPoseTransition() const; // +0x280 virtual void setUseStaticAttack(bool b); // +0x284 virtual bool getUseStaticAttack() const; // +0x288 virtual void setTimeOfLastFailedSplashDamageAttack(double t); // +0x28C virtual double getTimeOfLastFailedSplashDamageAttack() const; // +0x290 - virtual void setTakeOffPosition(const Vec3& v); // +0x294 [FRONTIER] + virtual void setTakeOffPosition(const Vec3& v); // +0x294 virtual const Vec3& getTakeOffPosition() const; // +0x298 - virtual void setQuadSeen(); // +0x29C [FRONTIER] - virtual bool isAttacking(unsigned int handle, double& out) const; // +0x2A0 [FRONTIER] - virtual void event_shotTimeOut(int i); // +0x2A4 [FRONTIER] - virtual void event_firing(bool& b, int i, const Vec3& v); // +0x2A8 [FRONTIER] + virtual void setQuadSeen(); // +0x29C + virtual bool isAttacking(unsigned int handle, double& out) const; // +0x2A0 + virtual void event_shotTimeOut(int i); // +0x2A4 + virtual const Vec3& event_firing(bool& b, int i, const Vec3& v); // +0x2A8 returns the record's +56 Vec3 // not in the vtable. Ordinary members; the vtable dump above is the authority on which // every name here is absent from all 171 slots. @@ -382,8 +410,12 @@ class BotMain : public Bot void removeBehaviour(BotBehaviour* b); void uninitAllBehaviours(); BotBehaviour* getActiveBehaviour(); - UrgencyGenerator** getBehaviourUrgencyGenerators(); + UrgencyGenerator** getBehaviourUrgencyGenerators(); // ELF 0x18AAD0: +152 + UrgencyGenerator* getSelector(); // ELF 0x18AAC0: +148 void calculateMods(); + unsigned char getMode(); + void setMode(unsigned char mode); + float getLastScout(); float* getBasicBehaviourMods(); float* getCurrentBehaviourMods(); // these two touch the class static, not A member. See the header. @@ -394,6 +426,11 @@ class BotMain : public Bot void setTakingOrders(bool b); PlanInterpreter* getPlanInterpreter(); void setPlanInterpreter(PlanInterpreter* p); + void setHadPrecisionTimeStamp(double time); // ELF 0x18C7D0: +276 + double getHadPrecisionTimeStamp() const; + // [INFERRED] inline reader (no symbol): +180 is read inline by BAPAAimAt::correctAim 0x1CDA3D and + // EntryMouseTurretAimAt 0x2B9A5C. Added by ai-w1-c-actions (requested from ai-bot). + FireCorrectionData* getFireCorrection() const { return m_fireCorrection; } double getTimeOfLastFire() const; void stepFireInclination(); // thunk void* getAttackers() const; @@ -401,17 +438,29 @@ class BotMain : public Bot // initialises. The old note that one of the two pairs was +576 is settled. const Vec3& getSpawnCoord() const; void setSpawnCoord(const Vec3& v); - void setObedience(float f); + const Vec3& getLookDir(); + void setLookDir(const Vec3& direction); + float setObedience(float f); float getAttention(); - void setAttention(float f); + float setAttention(float f); float getInvAttention(); - void setInvAttention(float f); + float setInvAttention(float f); // ELF 0x18AB80: stores and returns the supplied value float getMarksmanship(); // no setter - float getHarmlessThrsh(); // no setter, dice's spelling + int getHarmlessThrsh(); // ELF 0x18ABA0: +0x28 (cvtsi2ss at the caller); no setter, dice's spelling void setPlayer(IAIPlayer* p); void setPlayerInput(); - void resetAllControls(bool a, bool b, bool c); // [FRONTIER] - void validateDataStructures(); + void resetAllControls(bool a, bool b, bool c); + // Ask the next action to re-check the bot's vehicle (+0x58 m_checkVehicle). + void setUpdateCurrentEquipment(); // ELF 0x18A9F0 + bool getUpdateCurrentEquipment(); // ELF 0x18AA00 + void resetChangeTarget(); + void pollRequestedSoldierPose(); + bool checkPoseOk(bool& out, int pose); + void clearTestResults(); + void stepMoveInclination(); + void clearMoveInclination(); + void clearFireInclination(); + bool validateDataStructures(); // A class static, shared by every bot. See the header - the constructor reads it three times. static unsigned char mu8NBehaviours; static float* maBasicWeights; // ELF .bss @@ -419,6 +468,13 @@ class BotMain : public Bot private: // [INFERRED] friendship: addUnspawnedBot directly replaces +28 in both images. friend class BotManager; + // [INFERRED] friendship: SensingAgent::quadInFocus (ELF 0x1BDA60) reads +0x9C (m_player) inline. + friend class SensingAgent; + // [INFERRED] friendship: the WPBeachLanding constructors (ELF 0x1B8370, 0x1B8470) store their + // landing zone into +0xE8 (m_ptr232) through the Bot pointer. + friend class WPBeachLanding; + // ELF 0x1EEB90 reads the landing-zone pointer written by WPBeachLanding. + friend class BAPConObjectInLandingZone; // [CHOSEN] Names for fields whose original identifiers are unavailable. Offsets describe the retail x86 layout. /* 12 */ void* m_debugger; // = 0 getDebugger /* 16 */ BotLodLevel m_lodLevel; // = 0 get/setLodLevel @@ -431,26 +487,32 @@ class BotMain : public Bot /* 40 */ int m_int40; // ctor arg `i` [UNRESOLVED] /* 44 */ int m_side; // ctor arg `n` getSide /* 48 */ float m_float48; // = 0.01f [UNRESOLVED] a small threshold - /* 52 */ void* m_ptr52; // = 0 + /* 52 */ float m_inverseAttention; // = 0; get/setInvAttention /* 56 */ BotSquad* m_squad; // new(0xC) /* 60 */ int m_spawnToStrategicAreaId;// = -1 getSpawnToStrategicAreaId - /* 64 */ char m_gap64[4]; // +64 byte set to -1 [UNRESOLVED] + /* 64 */ unsigned char m_mode; // = 0xFF + /* 65 */ char m_pad65[3]; /* 68 */ float* m_currentOrders; // borrowed BotOrder weights, not the order object /* 72 */ float* m_ptr72; // = 0; per-behaviour modifiers in calculateMods /* 76 */ BotMemory* m_memory; // Borrowed; construction also initializes its first word and +16 double. /* 80 */ bool m_takingOrders; // isTakingOrders /* 81 */ char m_pad81[3]; - /* 84 */ void* m_ptr84; // = 0 - /* 88 */ char m_gap88[3]; // +89, +90 zeroed [UNRESOLVED] + /* 84 */ float m_lastScout; // = 0 + // decisionMaking (ELF 0x1893D0): +88 the equipment must be re-checked against the player's + // vehicle, +89 the last vehicle check failed ("Bot in bad vehicle!"), +90 updateBotVehicle + // asks for a fresh plan. The ctor zeroes +89/+90 only. [CHOSEN] names. + /* 88 */ bool m_checkVehicle; + /* 89 */ bool m_badVehicle; + /* 90 */ bool m_vehicleChanged; /* 91 */ bool m_inTransitionPhase; // isInTransitionPhase /* 92 */ char m_pad92; /* 93 */ bool m_deactivated; // isDeactivated /* 94 */ char m_pad94[2]; // Parallel per-behaviour arrays: scalar urgency values and behaviour pointers. /* 96 */ float* m_behaviourUrgencies; // new[] sized by mu8NBehaviours - one per behaviour - /* 100 */ void* m_ptr100; // = 0 - /* 104 */ void* m_ptr104; // = 0 - /* 108 */ void* m_ptr108; // = 0 + // Behaviour indices queued by urgency group (BotBehaviour +5); addBehaviour grows it and + // decisionMaking rotates it. ELF `std::vector >` (12 bytes). + /* 100 */ std::vector > m_behaviourQueues; // ctor: empty /* 112 */ BotBehaviour** m_behaviours; // new[] sized by mu8NBehaviours, zero-filled. // Owns the active BotScript. reset destroys it virtually and clears the pointer. /* 116 */ BotScript* m_activePlan; // Initially null; get/setPlan access it. @@ -468,9 +530,7 @@ class BotMain : public Bot /* 148 */ UrgencyGenerator* m_urgencyMerger; // ctor arg `merger` /* 152 */ UrgencyGenerator** m_urgencyGenerators;// ctor arg `generators` /* 156 */ IAIPlayer* m_player; // ctor arg; getPlayer reads it - /* 160 */ void* m_ptr160; // = 0 (written twice - before and after - /* 164 */ void* m_ptr164; // setPlayerInput; see the .cpp) - /* 168 */ void* m_ptr168; // = 0 + /* 160 */ Vec3 m_lookDir; // zeroed before and after setPlayerInput // reset clears this double before the other fields. /* 172 */ double m_double172; // reset: 0.0 /* 180 */ FireCorrectionData* m_fireCorrection; // new(0x80) @@ -491,7 +551,7 @@ class BotMain : public Bot /* 226 */ bool m_shouldWaitForRepairs; // reset: false /* 227 */ char m_pad227; /* 228 */ unsigned int m_mineTarget; // = -1 - /* 232 */ void* m_ptr232; // = 0 + /* 232 */ void* m_ptr232; // = 0; WPBeachLanding stores its AILandingZone* /* 236 */ float m_moveInclination; // = 0 /* 240 */ float m_fireInclination; // = 0 /* 244 */ float m_moveInclinationDelta; // = 1.0f addToMoveInclination accumulates here @@ -501,19 +561,28 @@ class BotMain : public Bot /* 260 */ void* m_ptr260; // = 0 /* 264 */ unsigned int m_firingTarget; // = -1 /* 268 */ double m_firingTargetTime; // getFiringTargetTime - /* 276 */ double m_time276; // = -DBL_MAX - "never happened" + /* 276 */ double m_time276; // = -DBL_MAX - "never happened"; setHadPrecisionTimeStamp /* 284 */ bool m_botStuck; // = false - /* 285 */ bool m_flag285; // = false + // pollRequestedSoldierPose (ELF 0x18CEE0): a pose input is held this tick; requestSoldierPose + // refuses an unforced change while it is set. [CHOSEN] name. + /* 285 */ bool m_poseInputActive; // = false /* 286 */ char m_pad286[2]; // Construction uses -DBL_MAX as the timestamp sentinel; reset uses -9999.0. - /* 288 */ double m_time288; // ctor: -DBL_MAX, reset: -9999.0 + // When pollRequestedSoldierPose last pressed lie/crouch; botInPoseTransition is 0.8 s after it. + /* 288 */ double m_soldierPoseAlteredTime; // ctor: -DBL_MAX, reset: -9999.0 // name: AIDLL_r assert 0x1014C060 (PE +0x148) /* 296 */ int m_requestedSoldierPose; // = 1 dice spells the getter "Solder" - /* 300 */ bool m_flag300[4]; // +300..+303, all false - /* 304 */ int m_int304; // = -1 + // setPoseStatus / checkPoseOk / clearTestResults: [0],[1] crouch, [2],[3] lie. + /* 300 */ bool m_poseTestResults[4]; // +300..+303, all false + // the firing target the pose tests were made against (setPoseStatus); -1 = none. + /* 304 */ int m_poseTestTarget; // = -1 /* 308 */ unsigned int m_unresolvedCollision; // = -1 /* 312 */ bool m_airBorn; // = false isAirBorn - /* 313 */ char m_pad313[3]; - /* 316 */ void* m_ptr316[3]; // +316..+324, all = 0 + // isJustSpawned (ELF 0x18BB80) sets this byte while the player is dead and clears it on the + // first alive call. [CHOSEN] name. + /* 313 */ bool m_spawnPending; + /* 314 */ char m_pad314[2]; + // get/setSpawnCoord (ELF 0x18BBD0 / 0x18BBE0) return and copy this Vec3. + /* 316 */ float m_spawnCoord[3]; // +316..+324, all = 0 /* 328 */ IBotDeathCallBack* m_deathCallBack; // = 0 /* 332 */ IBotSpawnCallBack* m_spawnCallBack; // = 0 /* 336 */ char m_gap336[4]; // [UNRESOLVED] @@ -523,7 +592,8 @@ class BotMain : public Bot /* 360 */ bool m_manDown; // get/setManDown /* 361 */ char m_pad361[3]; // A double, found by `reset`. The old 12-byte gap swallowed it. - /* 364 */ double m_double364; // reset: 0.0 + // rearm (ELF 0x18D7D0) accumulates the time increase here and rearms past 6 s. + /* 364 */ double m_rearmTimer; // reset: 0.0 /* 372 */ bool m_isFiring; // isFiring / setIsFiring /* 373 */ char m_pad373[3]; /* 376 */ SquadMember* m_squadMember; // = 0 @@ -531,18 +601,15 @@ class BotMain : public Bot /* 381 */ char m_pad381[3]; // four, and the second pair is A copy of the first - see copyAssignedAreas. /* 384 */ int m_assignedAreas[4]; // +384..+396, all = -1 - /* 400 */ void* m_ptr400; // = 0 - /* 404 */ void* m_ptr404; // = 0 - /* 408 */ void* m_ptr408; // = 0 - /* 412 */ int m_int412; // = -1 + /* 400 */ float m_currentWaypoint[3]; // = 0 (three zero stores); a Vec3 - set/getCurrentWaypoint + /* 412 */ int m_int412; // = -1; setCurrentWaypoint's int // [INFERRED] Consecutive plan-executor skips, cleared when execution resumes. // A signed comparison against 15 decides when a stalled bot stops coasting. /* 416 */ int m_stalledPlanTicks; // = 0 - /* 420 */ bool m_c4Placed; // = false - the ctor's last field store - /* 421 */ char m_pad421[7]; - /* 428 */ void* m_ptr428[3]; // +428..+436, all = 0 - /* 440 */ char m_gap440[20]; // [UNRESOLVED] + // +420..+459: placed (= false, the ctor's last field store), type, position (+428..+436, the + // ctor zeroes it), object, placed time, life time. + /* 420 */ C4State m_c4Explosives; // name: AIDLL_r asserts 0x1014B2E0, 0x1014D180 (PE +0x1D8) // Three grenade timestamps. getTimeOfGrenadeThrown requires an index in [0, 3); // it performs no bounds check and larger indices read adjacent attack timestamps. /* 460 */ double m_grenadeThrownTime[3]; // +460, +468, +476 @@ -550,12 +617,14 @@ class BotMain : public Bot /* 492 */ double m_timeOfLastFailedStaticSkyAttack; // = 0.0 /* 500 */ bool m_wantsToSimulateArtillery; // = false /* 501 */ bool m_isSimulatingArtillery; // = false - /* 502 */ bool m_flag502; // = false [UNRESOLVED] + // requestSoldierPose(pose, true) sets it; pollRequestedSoldierPose clears it every call. + /* 502 */ bool m_forcePose; // = false [UNRESOLVED] /* 503 */ char m_pad503; /* 504 */ int m_moveToStatus; // = 0 /* 508 */ int m_avoidSide; // = 0 - /* 512 */ char m_gap512[4]; // +512 byte = 0 - /* 516 */ double m_double516; // = 0.0 + /* 512 */ bool m_avoidSideChanged; // +512 byte = 0; setAvoidSide: switched between two non-zero sides [INFERRED] + /* 513 */ char m_pad513[3]; + /* 516 */ double m_timeOfLastStateChange; // = 0.0; setMoveToStatus: the game time of the last status change // name: AIDLL_r assert in setMoveToStatus 0x1014C250 (PE +0x238) /* 524 */ unsigned int m_collidedObject; // = -1 /* 528 */ float m_collidedObjectPosition[3]; // a Vec3 - getCollidedObjectPosition /* 540 */ bool m_ignoreObstacles; // = false @@ -567,10 +636,6 @@ class BotMain : public Bot /* 565 */ bool m_useStaticAttack; // = false /* 566 */ char m_pad566[2]; /* 568 */ double m_timeOfLastFailedSplashDamageAttack; // = -9999.0 - // The last field. `Vec3::getZero` is copied in component by component. `getLookDir` - // `setLookDir` and `getSpawnCoord` / `setSpawnCoord` have identical shapes - // so one of the two pairs is this field and the other is a Vec3 the ctor never initialises. - // [UNRESOLVED] which; reading either 56-byte setter settles it in one step. /* 576 */ float m_takeOffPosition[3]; // Vec3, = Vec3::getZero }; diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotMemory.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/BotMemory.cpp index d81aa9862..6df5267d8 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotMemory.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotMemory.cpp @@ -1,10 +1,13 @@ // [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining BotMemory operations. #include "BotMemory.h" -#include "../Main/AIDllFrontier.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x18F320, __tcf_0 0x18F380, _GLOBAL__I 0x18F3B0). +#include + +#include "../AIBotBehaviour/BotBehaviour.h" +#include "../AIBotBehaviour/UrgeCurve.h" namespace dice { namespace hfe { @@ -26,14 +29,26 @@ BotMemory::~BotMemory() { } +// ELF 0x18F2A0: the constructor's four stores again, in the image's order +// (+4 = -1, +0xC = 1, +8 = 1.0f from GOT-0x16598 -> 0x49CB2C 0x3F800000, +0 = -1). +// m_double16 is not touched. void BotMemory::reset() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMemory::reset"); + m_int4 = -1; + m_int12 = 1; + m_float8 = 1.0f; + m_int0 = -1; } -void BotMemory::modifyBehaviourUrgency(BotBehaviour*, double) +// ELF 0x18F2D0: for the remembered behaviour (index byte +4 == m_int0) the behaviour's urge +// curve (+0x20, vtable +8 calculate) is evaluated at (float)(time - m_double16) +// (`fldl 0x10(%ebp); fsubl 0x10(%ecx); fstps`); any other behaviour gets 1.0f +// (`flds -0x16598(%ebx)`, 0x49CB2C = 0x3F800000). +float BotMemory::modifyBehaviourUrgency(BotBehaviour* behaviour, double time) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMemory::modifyBehaviourUrgency"); + if (static_cast(behaviour->getIndex()) == m_int0) + return behaviour->getUrgeCurve()->calculate(static_cast(time - m_double16)); + return 1.0f; } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotMemory.h b/Code/BF2/AI/AIDLL/AI/AIBot/BotMemory.h index 1d1fe802d..78d2af29f 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotMemory.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotMemory.h @@ -16,9 +16,9 @@ class BotMemory BotMemory(); ~BotMemory(); - void reset(); // [FRONTIER] - // Adjusts the urgency assigned to behaviour by amount. - void modifyBehaviourUrgency(BotBehaviour* behaviour, double amount); // [FRONTIER] + void reset(); + // ELF 0x18F2D0 returns a float (x87 st0): the urgency factor for behaviour at time. + float modifyBehaviourUrgency(BotBehaviour* behaviour, double time); // Retail x86 field offsets. /* 0 */ int m_int0; // = -1 and BotMain writes it again from outside diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.cpp index 541cb8489..99f829c22 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.cpp @@ -1,36 +1,59 @@ -// [FRONTIER] Remaining methods stop by name until implemented. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining BotNavigation operations. - #include "BotNavigation.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x195420, __tcf_0 0x195480, _GLOBAL__I 0x1954B0). +#include + #include "BotMain.h" // getBotId / getCurrentEquipment - vtable +0xE8, +0xD8 #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" // IBFTimer::getGameTime -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/AIInformationGrid.h" +#include "../AIKnowledge/BFInformationEnvironment.h" #include "../AIUtils/checkPointer.h" #include "../Main/AIDllFrontier.h" +#include "../Main/IAIPathfinding.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIPathFinding/NavMesh/QuadTree.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" // IAIPlayer::isParachuting +#include "../../../../IO/Input/PlayerInput.h" +#include "../../../../Core/Debug.h" +#include namespace dice { namespace hfe { namespace ai { +namespace { + +// [CHOSEN, not recovered] the image's inlined sqrt of a squared length (with its sqrtf retry). +inline float length3(float x, float y, float z) +{ + return std::sqrt(x * x + y * y + z * z); +} + +} // namespace + // Creates navigation paths and initializes movement state for the supplied bot. BotNavigation::BotNavigation(BotMain* owner) : m_bot(owner) - , m_float4(2.0f) + , m_arriveDistance(2.0f) , m_float8(2.0f) - , m_int16(-1) - , m_int20(-1) - , m_int36(-1) - , m_flag40(false) + , m_startIsland(-1) + , m_startPolygon(-1) + , m_goalPolygon(-1) + , m_goalMaterial(0) // the two paths, in the order the binary builds them: the fine one first. - , m_polygonPath(checkPointer(new QTPath())) + , m_path(checkPointer(new QTPath())) , m_int76(-1) - , m_int116(0) + , m_currentPoint(0) , m_clusterPath(checkPointer(new ClusterNodePath())) , m_int128(-1) - , m_double144(0.0) - , m_double152(0.0) + , m_noProgressTimer(0.0) + , m_noThrottleTimer(0.0) , m_double160(0.0) , m_double168(0.0) // 9,999,999.0f - a distance sentinel, not a time and not a magnitude. See above. @@ -38,44 +61,56 @@ BotNavigation::BotNavigation(BotMain* owner) , m_flag192(false) , m_flag193(false) , m_flag195(false) - , m_int200(-1) - , m_int204(-1) - , m_int208(-1) - , m_int212(-1) - , m_int240(0) - , m_double268(0.0) - , m_flag276(false) + , m_currentPolygon(-1) + , m_vehicleIsland(-1) + , m_infantryPolygon(-1) + , m_infantryIsland(-1) + , m_skipTraceCount(0) + , m_grenadeTime(0.0) + , m_grenadeFlag(false) // Independent sentinel, initialized to -1.0. - , m_double300(-1.0) + , m_lastAngleDiffTest(-1.0) { for (int i = 0; i < 3; ++i) { - m_zero24[i] = 0; - m_zero44[i] = 0; - m_zero88[i] = 0; m_zero176[i] = 0; - m_zero216[i] = 0; - m_zero256[i] = 0; - } - m_pathOwner = 0; // +60 - a pointer, see BotNavigation.h - m_zero64 = 0; - m_zero308[0] = 0; - m_zero308[1] = 0; - for (int i = 0; i < 5; ++i) + } + m_tracePosition.x = 0.0f; + m_tracePosition.y = 0.0f; + m_tracePosition.z = 0.0f; + m_grenadePosition.x = 0.0f; m_grenadePosition.y = 0.0f; m_grenadePosition.z = 0.0f; + m_startPosition.x = 0.0f; m_startPosition.y = 0.0f; m_startPosition.z = 0.0f; + m_goal.x = 0.0f; m_goal.y = 0.0f; m_goal.z = 0.0f; + m_pathfinding = 0; // +60 + m_quadTree = 0; + m_largestAngleDiff = 0.0f; + m_pathLength = 0.0f; + for (int i = 0; i < 3; ++i) m_zero280[i] = 0; - for (int i = 0; i < 6; ++i) - m_zero320[i] = 0; + m_spaceLeft = 0; + m_spaceRight = 0; + m_searchStart.x = 0.0f; // +320..+340 + m_searchStart.y = 0.0f; + m_searchStart.z = 0.0f; + m_searchGoal.x = 0.0f; + m_searchGoal.y = 0.0f; + m_searchGoal.z = 0.0f; // the dead resize - see the block above. Written as what it is rather than dropped. - m_points.resize(0); + m_navigationPoints.resize(0); } -// [FRONTIER] Remaining navigation operations stop until implemented. // [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. +// ELF 0x18FF30: reset (releases the search resources), then the two owned paths; the set and the +// two vectors are members. BotNavigation::~BotNavigation() { - BF2_AI_FRONTIER("dice::hfe::ai::BotNavigation::~BotNavigation"); + reset(); + if (m_path) + delete m_path; + if (m_clusterPath) + delete m_clusterPath; } // Resets navigation, movement flags and progress timing. @@ -84,75 +119,72 @@ void BotNavigation::resetAll() reset(); m_int252 = 0; - m_flag276 = false; + m_grenadeFlag = false; // Not the constructor's 0.0 - see the block above. - m_double268 = -9999.0; - m_zero308[0] = 0; - m_double300 = -1.0; + m_grenadeTime = -9999.0; + m_largestAngleDiff = 0.0f; + m_lastAngleDiffTest = -1.0; clearProgress(); } -// Resets navigation state and returns path resources to their owners. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] Incomplete resource paths stop by name. -// [RETIRE-WHEN: aidll-02-skeleton] Implement and validate path release and progress reset. -// [RETIRE-WHEN: botmain-bases] Remove when the corresponding implementation is complete and validated. +// ELF 0x190A70. Releases both search slots, empties the paths and points, and re-reads the +// equipment's last valid positions. void BotNavigation::reset() { m_flag316 = false; - // giving the polygon path back. See the block above. - if (m_int76 != -1) + if (m_int76 != 0xFFFFFFFFu) { - // Retail: `m_pathOwner->release(&m_int76, m_bot->getBotId)`. The bot half is typed now; - // the object at +60 still has no class, so the slot cannot be. - BF2_AI_FRONTIER("dice::hfe::ai::BotNavigation::reset (a polygon path is reserved)"); - m_int76 = -1; + m_pathfinding->releaseResource(m_int76, m_bot->getBotId()); // slot +0x9C + m_int76 = 0xFFFFFFFFu; } - - // and the cluster path, through a different slot on the same object. - if (m_int128 != -1) + if (m_int128 != 0xFFFFFFFFu) { - BF2_AI_FRONTIER("dice::hfe::ai::BotNavigation::reset (a cluster path is reserved)"); - m_int128 = -1; + m_pathfinding->releaseClusterResource(m_int128, m_bot->getBotId()); // slot +0xA4 + m_int128 = 0xFFFFFFFFu; } // Reaching through both path objects - see the block above. - m_polygonPath->m_nodes.resize(0); - m_polygonPath->m_i0 = 0; - m_polygonPath->m_i20 = 0; + m_path->m_nodes.resize(0); + m_path->m_i0 = 0; + m_path->m_i20 = 0; m_clusterPath->m_nodes.resize(0); m_clusterPath->m_i0 = 0; m_int56 = 0; - m_points.resize(0); + m_navigationPoints.resize(0); - m_int240 = 0; - m_int116 = 0; + m_skipTraceCount = 0; + m_currentPoint = 0; m_double160 = 0.0; m_flag195 = false; m_flag193 = false; m_flag194 = false; m_double244 = 0.0; - // Resolves the bot's current equipment handle; skips equipment work when it has no object. - const unsigned int equipment = m_bot->getCurrentEquipment(); - Information* const info = informationManager->getPool()->get(equipment); + // the equipment's last valid positions (no mobile plug-in: unchanged) + Information* const info = informationManager->getPool()->get(m_bot->getCurrentEquipment()); if (info) { - // Retail: `IPIMobile* m = info->m_mobile56; if (m) { m_int80 = m->getVehicleNumber; - // const Vec* p = m->getLastValidPosition(m_int80); m_int200 = p[0]; ... }` - // `Information` and `IPIMobile` are both unrecovered - `Information` is a forward - // declaration behind the handle pool and `IPIMobile` is not in this tree at all. - BF2_AI_FRONTIER("dice::hfe::ai::BotNavigation::reset (the bot has equipment)"); + IPIMobile* const mobile = info->getMobile(); + if (mobile) + { + m_mapIndex = mobile->getVehicleNumber(); + const IPIMobile::ValidPos& vehicle = mobile->getLastValidPosition(m_mapIndex); + m_vehicleIsland = static_cast(vehicle.island); + m_currentPolygon = static_cast(vehicle.polygon); + m_infantryIsland = static_cast(mobile->getLastValidInfantryPos().island); + m_infantryPolygon = static_cast(mobile->getLastValidInfantryPos().polygon); + } } // The sentinel is the interesting one - see the block above. m_sentinel188 = 9999999.0f; - m_zero280[3] = 0; - m_zero280[4] = 0; + m_spaceLeft = 0; + m_spaceRight = 0; } // Clears progress counters and restarts the progress timer at the current game time. @@ -162,35 +194,1126 @@ void BotNavigation::clearProgress() m_zero176[0] = 0; // +176 // the one non-zero store. See the block above. - m_double144 = + m_noProgressTimer = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); m_double168 = 0.0; m_zero176[1] = 0; // +180 m_zero176[2] = 0; // +184 - m_double152 = 0.0; + m_noThrottleTimer = 0.0; m_flag192 = false; m_zero280[0] = 0; // +280 m_zero280[1] = 0; // +284 m_zero280[2] = 0; // +288 } -// [FRONTIER] Obstacle updates for living, standing bots are not implemented. -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -// Replace the stop when the corresponding navigation behavior is recovered. +namespace { + +// ELF 0x197560 (vtable 0x4b6c38): a primary object with a mobile plug-in (+0x38), or any +// information whose type flags carry bit 25 (`testb $0x2,0x7(info)`). +class MobileOrObstaclePredicate : public IAIInformationGridPredicate +{ +public: + virtual bool includeInformation(Information* information) const + { + return (information->isPrimary() && information->hasMobile()) + || information->isOfType(ITObstacle); + } +}; + +} // namespace + +// ELF 0x194B60 (399 bytes). The obstacle list is emptied, then filled from both grids (the +// bool argument 1, then 0) within 50 m of the equipment's position for the bot's side. +// No null guard on the equipment information. void BotNavigation::updateObstacles() { - BF2_AI_FRONTIER("dice::hfe::ai::BotNavigation::updateObstacles"); + m_obstacles.resize(0); + Information* const equipment = informationManager->getInformation(m_bot->getCurrentEquipment()); + const Vec3& position = equipment->getPosition(); + MobileOrObstaclePredicate predicate; + const IAIInformationEnvironment* const environment = + static_cast(AISingletonServer::m_iaiInformationEnvironment); + environment->getObjectsWithinRadius(m_obstacles, position, 50.0f, m_bot->getSide(), true, &predicate); + environment->getObjectsWithinRadius(m_obstacles, position, 50.0f, m_bot->getSide(), false, &predicate); + m_int252 = static_cast(m_obstacles.size()); } +// ELF 0x194E40. Empty in the shipped dedicated image. +void BotNavigation::drawPath() +{ +} + +// ELF 0x192160: active for three seconds of game time after +244. bool BotNavigation::isActive() { - BF2_AI_FRONTIER("dice::hfe::ai::BotNavigation::isActive"); + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + return now - m_double244 < 3.0; } +// ELF 0x192830 (123 bytes). void BotNavigation::updateOccationally() { - BF2_AI_FRONTIER("dice::hfe::ai::BotNavigation::updateOccationally"); + updateNavPoints(); + updateClosestDistance(); + if (m_int56 == 2) + { + if (hasIllegalPath()) + reset(); + else if (!checkProgress()) + m_flag192 = true; + } + if (m_updateSpaceLeftAndRight) + updateSpaceLeftAndRight(); +} + +// ELF 0x191320 (372 bytes). Without a path owner (+60), or in state 4, there is nothing to +// search. A pending point reset (+195) empties the points and requests a polygon search. +bool BotNavigation::update(bool& a, bool* b) +{ + if (m_pathfinding == 0) + return false; + m_flag316 = false; + if (m_int56 == 4) + return false; + a = false; + if (b) + *b = false; + if (m_flag195) + { + m_navigationPoints.resize(0); + m_currentPoint = 0; + m_polygonSearchPending = true; + m_flag195 = false; + } + if (m_useClusterSearch) + return doClusterSearch(a, b); + if (!m_polygonSearchPending) + return true; + return doPolygonSearch(a, b); +} + +// ELF 0x1901B0 (256 bytes). Finds the goal's polygon on the equipment's vehicle map, then starts +// the search; without equipment or a polygon nothing is started. +bool BotNavigation::initPathfinding(const Vec3& to, float arriveDistance, float b) +{ + Information* const info = informationManager->getInformation(m_bot->getCurrentEquipment()); + if (info) + { + const int equipmentType = info->getUnit()->getEquipmentType(); + const int vehicle = info->getMobile()->getVehicleNumber(); + unsigned int polygon; + unsigned int island; + if (IAIPathfinding::instance->getPolygon(to, vehicle, polygon, island, equipmentType)) // slot +0x44 + return initPathfinding(island, polygon, to, arriveDistance, b); + } + m_flag193 = false; + return false; +} + +// ELF 0x1902B0 (1744 bytes). The same goal on the same map and equipment keeps the current path +// (one point; the bot's polygon is the current point's; still on the path; or retrace). A new +// search needs the bot within 10 m of its last valid position and on the goal's island. +bool BotNavigation::initPathfinding(unsigned int island, unsigned int goalPolygon, const Vec3& to, + float arriveDistance, float b) +{ + Information* const info = informationManager->getInformation(m_bot->getCurrentEquipment()); + if (!info) + { + m_flag193 = false; + return false; + } + m_updateSpaceLeftAndRight = info->isOfType(ITSoldier); // byte +6 & 0x20 + if (m_pathfinding == 0) + m_pathfinding = IAIPathfinding::instance; + IPIMobile* const mobile = info->getMobile(); + const IPIMobile::ValidPos& valid = mobile->getLastValidPosition(); + + const bool sameGoal = std::fabs(to.x - m_goal.x) <= 1.1920929e-07f + && std::fabs(to.y - m_goal.y) <= 1.1920929e-07f + && std::fabs(to.z - m_goal.z) <= 1.1920929e-07f; + if (!sameGoal) + clearProgress(); + if (m_flag193 + && std::fabs(m_goal.x - to.x) <= 1.1920929e-07f + && std::fabs(m_goal.y - to.y) <= 1.1920929e-07f + && std::fabs(m_goal.z - to.z) <= 1.1920929e-07f + && m_mapIndex == mobile->getVehicleNumber() + && m_equipmentType == info->getUnit()->getEquipmentType()) + { + if (static_cast(m_int56) < 2) + return true; + if (!m_navigationPoints.empty() && m_navigationPoints[m_currentPoint].m_polygon == static_cast(valid.polygon)) + return true; + if (!m_navigationPoints.empty() && stillOnPath()) + return true; + if (m_navigationPoints.size() > 1) + { + retrace(); + return true; + } + } + + if (island != 0xFFFFFFFFu && goalPolygon != 0xFFFFFFFFu) + { + m_goalPolygon = static_cast(goalPolygon); + m_goal = to; + if (valid.island != 0xFFFFFFFFu && valid.polygon != 0xFFFFFFFFu) + { + const Vec3& position = info->getPosition(); // Information slot +0x30 + const float dx = position.x - valid.position.x; + const float dy = position.y - valid.position.y; + const float dz = position.z - valid.position.z; + if (dx * dx + dy * dy + dz * dz <= 100.0f) + { + if (island == valid.island) + { + m_polygonSearchPending = true; + m_useClusterSearch = true; + m_flag192 = false; + m_startIsland = static_cast(valid.island); + m_island = static_cast(valid.island); + m_startPolygon = static_cast(valid.polygon); + m_startPosition = valid.position; + m_arriveDistance = arriveDistance; + m_float8 = b; + m_float8Squared = b * b; + m_mapIndex = mobile->getVehicleNumber(); + const IPIMobile::ValidPos& vehicle = mobile->getLastValidPosition(m_mapIndex); + m_vehicleIsland = static_cast(vehicle.island); + m_currentPolygon = static_cast(vehicle.polygon); + m_infantryIsland = static_cast(mobile->getLastValidInfantryPos().island); + m_infantryPolygon = static_cast(mobile->getLastValidInfantryPos().polygon); + m_equipmentType = info->getUnit()->getEquipmentType(); + m_flag195 = false; + m_skipTraceCount = 0; + reset(); + m_flag193 = true; + m_radius = info->getPhysical()->getSmallestRadius(); // IPIPhysical slot +0x34 + m_pathfinding->getMaterial(m_mapIndex, island, static_cast(m_goalPolygon), + m_goalMaterial); // slot +0x5C + testDirectPath(); + void* const quadTree = m_pathfinding->getQuadTree(m_mapIndex, static_cast(m_startIsland)); + m_flag316 = true; + m_quadTree = static_cast(quadTree); // slot +0x64 + return true; + } + Debug(DebugTypeError, "AI/AIDLL/AI/AIBot/BotNavigation.cpp", 0xC4, "") + << "Bot " << m_bot->getName() << " is ordered to go to an island that it is not on (" + << island << " != " << valid.island << ")"; + m_flag193 = false; + return false; + } + } + } + m_flag193 = false; + m_flag192 = true; + return false; +} + +// ELF 0x1920A0 (192 bytes). Once the cluster path is used up and no search is pending, the last +// point follows the bot's last valid position on the path island. +void BotNavigation::updateLastPoint(Information* info) +{ + const ClusterNodePath* const cluster = m_clusterPath; + if (cluster->m_nodes.size() <= static_cast(cluster->m_i0) && !m_useClusterSearch + && !m_polygonSearchPending && static_cast(m_navigationPoints.size()) > 0) + { + const IPIMobile::ValidPos& valid = info->getMobile()->getLastValidPosition(m_mapIndex); + if (static_cast(m_island) == valid.island) + { + NavigationPoint& last = m_navigationPoints[m_navigationPoints.size() - 1]; + last.m_position = valid.position; + last.m_polygon = static_cast(valid.polygon); + } + } +} + +// ELF 0x1921B0. A parachuting bot is never stuck. +void BotNavigation::setIsStuck(bool stuck) +{ + if (m_bot->getPlayer()->isParachuting()) // Bot +0xBC, IAIPlayer +0x34 + m_flag192 = false; + else + m_flag192 = stuck; +} + +// ELF 0x192200 (1440 bytes). +bool BotNavigation::updatePath(Vec2& point, bool& arrived, bool& direct, float distance) +{ + static bool useSkipTrace = false; // ELF 0x4CE00E (.bss) + if (m_flag192) + return false; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + m_double244 = now; + if (!m_flag193) + return false; + arrived = false; + direct = false; + if (static_cast(m_int56) < 2) + m_double244 = 0.0; + if (m_useClusterSearch || m_flag195 || (m_polygonSearchPending && m_navigationPoints.size() <= m_currentPoint)) + { + direct = true; + return true; + } + + // a soldier firing at an enemy does not walk onto material 4 polygons + Information* const target = informationManager->getInformation(m_bot->getFiringTarget()); + if (!m_navigationPoints.empty() && m_updateSpaceLeftAndRight && m_bot->isFiring() && target) + { + if (target->getSide() != m_bot->getSide()) + { + const unsigned int polygon = m_navigationPoints.size() < 2 + ? static_cast(m_goalPolygon) + : static_cast(m_navigationPoints[m_currentPoint].m_polygon); + unsigned char material; + if (m_pathfinding->getMaterial(m_mapIndex, static_cast(m_island), polygon, material) + && material == 4) + { + direct = true; + m_double244 = 0.0; + return true; + } + } + } + + if (m_double168 == -666.0) + { + m_bot->getInput()->setInput(static_cast(9), 1.0f); // PIAction + m_double168 = now; + } + + if (checkArrivedAtPoint(distance)) + { + if (m_currentPoint == m_navigationPoints.size() - 1) + { + m_double244 = 0.0; + m_sentinel188 = 100000000.0f; + clearProgress(); + arrived = true; + } + else + { + ++m_currentPoint; + if (m_skipTraceCount > 0) + --m_skipTraceCount; + } + } + + ClusterNodePath* const cluster = m_clusterPath; + bool trim = true; + if (m_pathLength >= 30.0f && m_currentPoint + 10 < m_navigationPoints.size()) + { + const Polygon* const polygon = m_quadTree->getPolygon(static_cast(m_navigationPoints[m_currentPoint].m_polygon)); + if (static_cast(polygon->cluster) != static_cast(cluster->m_i0)) + { + const Polygon* const again = m_quadTree->getPolygon(static_cast(m_navigationPoints[m_currentPoint].m_polygon)); + unsigned short current = 0xFFFF; + if (cluster->m_i0 < static_cast(cluster->m_nodes.size())) + current = cluster->m_nodes[cluster->m_i0].first; + if (again->cluster != current) + trim = false; + } + } + if (trim && static_cast(cluster->m_i0) + 1 <= cluster->m_nodes.size() && !m_polygonSearchPending) + { + // keep at most ten points ahead and search the rest again + m_polygonSearchPending = true; + unsigned int keep = static_cast(m_navigationPoints.size()); + if (m_currentPoint + 10 < keep) + keep = m_currentPoint + 10; + m_navigationPoints.resize(keep, NavigationPoint()); + } + + if (!m_flag195) + { + if (m_int56 != 2 && (!m_polygonSearchPending || static_cast(m_int56) > 1)) + return false; + stillOnPath(); + if (!m_flag194) + { + m_double160 = now; + } + else + { + const float delay = m_updateSpaceLeftAndRight ? 2.0f : 0.5f; + if (static_cast(delay) < now - m_double160) + { + m_flag194 = false; + m_skipTraceCount = (useSkipTrace && m_updateSpaceLeftAndRight) ? 1 : 0; + retrace(); + } + } + } + vec3ToVec2XZ(m_navigationPoints[m_currentPoint].m_position, point); + return true; +} + +// ELF 0x193EC0 (512 bytes). On the path when the bot's last valid polygon is the previous or the +// current point's, or one behind; or within the next 20 points (which becomes the current one). +bool BotNavigation::stillOnPath() +{ + if (m_navigationPoints.size() < 2) + return false; + Information* const info = informationManager->getInformation(m_bot->getCurrentEquipment()); + const int polygon = static_cast(info->getMobile()->getLastValidPosition().polygon); + if (polygon == -1) + return false; + const unsigned int current = m_currentPoint; + if (current >= m_navigationPoints.size()) + return false; + const int previous = current != 0 ? m_navigationPoints[current - 1].m_polygon : -1; + if (polygon == previous || polygon == m_navigationPoints[current].m_polygon) + return true; + for (int i = static_cast(current); i >= 0; --i) + if (m_navigationPoints[i].m_polygon == polygon) + return true; + unsigned int ahead = static_cast(m_navigationPoints.size()) - current; + if (ahead > 0x14) + ahead = 0x14; + const unsigned int end = ahead + current; + for (unsigned int i = current; i < end; ++i) + { + if (m_navigationPoints[i].m_polygon == polygon) + { + m_currentPoint = i; + const int left = m_skipTraceCount - static_cast(i - current); + m_skipTraceCount = left > 0 ? left : 0; + return true; + } + } + return false; +} + +// ELF 0x1910C0 (608 bytes). Restarts from the bot's last valid position on the cluster path: +// at the bot's cluster, or at the first path cluster neighbouring it; otherwise a full reset. +void BotNavigation::retrace() +{ + ClusterNodePath* const cluster = m_clusterPath; + const unsigned int count = static_cast(cluster->m_nodes.size()); + if (count < 2) + { + m_flag195 = false; + reset(); + return; + } + cluster->m_i0 = 0; + m_navigationPoints.resize(0, NavigationPoint()); + Information* const info = informationManager->getInformation(m_bot->getCurrentEquipment()); + const IPIMobile::ValidPos& valid = info->getMobile()->getLastValidPosition(); + m_startIsland = static_cast(valid.island); + m_startPolygon = static_cast(valid.polygon); + m_startPosition = valid.position; + m_flag195 = true; + const short own = static_cast(m_pathfinding->getClusterOfPolygon( + m_mapIndex, static_cast(m_startIsland), valid.polygon)); // slot +0x7C + for (unsigned int i = 0; i < count - 1; ++i) + { + short node = -1; + if (m_clusterPath->m_i0 < static_cast(m_clusterPath->m_nodes.size())) + node = static_cast(m_clusterPath->m_nodes[m_clusterPath->m_i0].first); + if (own == node) + return; + ++m_clusterPath->m_i0; + } + m_clusterPath->m_i0 = 0; + for (unsigned int i = 0; i < count - 1; ++i) + { + unsigned short node = 0xFFFF; + if (m_clusterPath->m_i0 < static_cast(m_clusterPath->m_nodes.size())) + node = m_clusterPath->m_nodes[m_clusterPath->m_i0].first; + if (m_pathfinding->areNeighbouringClusters(m_mapIndex, static_cast(m_startIsland), + static_cast(own), node)) // slot +0x80 + return; + ++m_clusterPath->m_i0; + } + m_flag195 = false; + reset(); +} + +// ELF 0x190DA0 (800 bytes). A goal within 200 m (minDistSqr 40000) that a straight trace reaches +// becomes a one-point path. +void BotNavigation::testDirectPath() +{ + static float minDistSqr = 40000.0f; // ELF 0x4B6C24 (.data) + const float dx = m_goal.x - m_startPosition.x; + const float dy = m_goal.y - m_startPosition.y; + const float dz = m_goal.z - m_startPosition.z; + if (!(dx * dx + dy * dy + dz * dz < minDistSqr)) + return; + Information* const info = informationManager->getInformation(m_bot->getCurrentEquipment()); + if (!info || !info->getMobile()) + return; + Vec3 hit; + hit.x = 0.0f; hit.y = 0.0f; hit.z = 0.0f; + unsigned int polygon; + unsigned char material; + if (!m_pathfinding->trace(static_cast(m_startPolygon), static_cast(m_island), + m_mapIndex, m_startPosition, m_goal, hit, polygon, m_equipmentType, -1, 0.0f, 5, + &material)) // slot +0x8C + return; + const unsigned int index = static_cast(m_navigationPoints.size()); + m_navigationPoints.resize(index + 1, NavigationPoint()); + NavigationPoint& last = m_navigationPoints[index]; + last.m_position = m_goal; + last.m_polygon = static_cast(polygon); + last.edgePoint1 = m_goal; + last.m_pointC = m_goal; + m_goalPolygon = static_cast(polygon); + m_goalMaterial = material; + m_polygonSearchPending = false; + m_useClusterSearch = false; + m_currentPoint = 0; + m_int56 = 2; + updateClosestDistance(); +} + +// ELF 0x1949E0 (384 bytes). Within 3 m in height and the arrive distance in the plane: a soldier +// uses soldierMinDist; a vehicle max(+4, 1), at the last point max(radius - 1, that). +bool BotNavigation::checkArrivedAtPoint(float) +{ + static float soldierMinDist = 0.5f; // ELF 0x4B6C30 (.data) + // The image reads BotMain +0x8C (m_currentEquipment) inline; getCurrentEquipment returns it. + Information* const info = informationManager->getInformation(m_bot->getCurrentEquipment()); + const Vec3& position = info->getPosition(); + if (m_navigationPoints.empty()) + return false; + const NavigationPoint& p = m_navigationPoints[m_currentPoint]; + if (!(std::fabs(position.y - p.m_position.y) <= 3.0f)) + return false; + float distance = soldierMinDist; + if (!m_updateSpaceLeftAndRight) + { + distance = m_arriveDistance; + if (m_arriveDistance <= 1.0f) + distance = 1.0f; + } + float limit = distance; + if (!m_updateSpaceLeftAndRight && m_currentPoint == m_navigationPoints.size() - 1) + { + limit = m_radius - 1.0f; + if (limit <= distance) + limit = distance; + } + const float x = position.x - p.m_position.x; + const float z = position.z - p.m_position.z; + return z * z + x * x + 0.0f < limit * limit; +} + +// ELF 0x1940C0. +bool BotNavigation::getSecondPoint(Vec2& out) +{ + const unsigned int next = m_currentPoint + 1; + const bool exists = next < m_navigationPoints.size(); + if (exists) + vec3ToVec2XZ(m_navigationPoints[next].m_position, out); + return exists; +} + +// ELF 0x194120 (1408 bytes). Every 0.5 s: the largest absolute heading change between the bot's +// facing and the path legs within max(speed * timeStep, 3) metres ahead; cached in +308. +bool BotNavigation::getLargestAngleDiff(float& out) +{ + static float timeStep = 2.0f; // ELF 0x4B6C2C (.data) + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (!(now - m_lastAngleDiffTest >= 0.5)) + { + out = m_largestAngleDiff; + return true; + } + m_lastAngleDiffTest = now; + // The image reads BotMain +0x8C inline (no null guard). + Information* const info = informationManager->getInformation(m_bot->getCurrentEquipment()); + const Vec3& position = info->getPosition(); + unsigned int index = m_currentPoint; + const Vec3& first = m_navigationPoints[index].m_position; + float covered = length3(position.x - first.x, position.y - first.y, position.z - first.z); + Vec2 facing; + facing.x = 0.0f; facing.y = 0.0f; + const Vec3 faceing = info->getFaceing(); // Information slot +0x40 + vec3ToVec2XZ(faceing, facing); + out = 0.0f; + float range = info->getMobile()->getSpeedMagnitude() * timeStep; // IPIMobile slot +0x24 + if (range <= 3.0f) + range = 3.0f; + for (; covered < range && index < m_navigationPoints.size(); ++index) + { + Vec3 from; + if (index == 0) + from = info->getPosition(); + else + from = m_navigationPoints[index - 1].m_position; + const Vec3& to = m_navigationPoints[index].m_position; + covered = length3(from.x - to.x, from.y - to.y, from.z - to.z) + covered; + Vec3 leg; + leg.x = to.x - from.x; leg.y = to.y - from.y; leg.z = to.z - from.z; + Vec2 dir; + dir.x = 0.0f; dir.y = 0.0f; + vec3ToVec2XZ(leg, dir); + const float lengthSq = dir.x * dir.x + dir.y * dir.y; + if (std::fabs(lengthSq - 1.0f) >= 1.1920929e-07f) + { + if (std::fabs(lengthSq) < 1.4210855e-14f) + { + dir.x = 0.0f; dir.y = 0.0f; + } + else + { + const float inv = 1.0f / std::sqrt(lengthSq); + dir.x = dir.x * inv; dir.y = inv * dir.y; + } + } + const float diff = std::fabs(getSignedDiffAngleToDir(facing, dir)); + if (out < diff) + out = diff; + } + m_largestAngleDiff = out; + return true; +} + +// ELF 0x194E50 (192 bytes). The first point from the current one farther than `distance` from +// `from` in the plane; `out` keeps the last point looked at. +void BotNavigation::getFirstPointBeyondDist(const Vec2& from, float distance, Vec2& out) +{ + for (unsigned int i = m_currentPoint; i < m_navigationPoints.size(); ++i) + { + const Vec3& p = m_navigationPoints[i].m_position; + out.x = p.x; + out.y = p.z; + const float dx = from.x - p.x; + const float dz = from.y - p.z; + if (distance * distance < dz * dz + dx * dx) + return; + } +} + +// ELF 0x195280. The game-time query's result is discarded, as in the image. +void BotNavigation::setGrenadeWarning(const Vec3& position, double time, bool b) +{ + static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + m_grenadeTime = time; + m_grenadePosition = position; + m_grenadeFlag = b; +} + +// ELF 0x195310. +bool BotNavigation::getGrenadeWarning(Vec3& position, double& timeLeft) +{ + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + position = m_grenadePosition; + timeLeft = 2.8 - (now - m_grenadeTime); + return timeLeft > 0.0; +} + +// ELF 0x1914B0 (1535 bytes). A local (polygon) search for the next path segment: the first call +// acquires a search resource (none free: *blocked), turns on topology smoothing off the trace map, +// and allows the start's cluster, the next three clusters of the cluster path and the segment +// goal's cluster; the segment runs from the last point (or the start) to the cluster portal two +// steps ahead, or to the goal. Each call runs the search (IAIPathfinding +0x24): 1 is in progress +// (*finished = true, true); 2 found - the points are rebuilt and optimised, the goal appended when +// the segment ended there (and the cluster path emptied), the cluster step advanced; 3 / 4 failed. +bool BotNavigation::doPolygonSearch(bool& finished, bool* blocked) +{ + if (m_int76 == 0xFFFFFFFFu) + { + if (!m_pathfinding->acquireResource(m_int76, m_bot->getBotId())) + { + if (blocked) + *blocked = true; + return false; + } + if (m_mapIndex != m_pathfinding->getTraceMapIndex()) + m_pathfinding->setUsePathTopologySmoothing(m_int76, true); + if (m_navigationPoints.empty()) + { + m_searchStart = m_startPosition; + m_searchStartPolygon = static_cast(m_startPolygon); + } + else + { + const NavigationPoint& last = m_navigationPoints.back(); + m_searchStart = last.m_position; + m_searchStartPolygon = static_cast(last.m_polygon); + } + m_set132.clear(); + m_set132.insert(m_quadTree->getPolygon(m_searchStartPolygon)->cluster); + m_searchGoalIsFinal = false; + if (!m_clusterPath->getPoint(m_searchGoal, m_searchGoalPolygon, static_cast(m_clusterPath->m_i0 + 2))) + { + m_searchGoal = m_goal; + m_searchGoalIsFinal = true; + m_searchGoalPolygon = static_cast(m_goalPolygon); + } + for (int k = 0; k < 3; ++k) + { + const unsigned int index = static_cast(k + m_clusterPath->m_i0); + const unsigned int nodes = static_cast(m_clusterPath->m_nodes.size()); + if (nodes < index) + break; + const unsigned short cluster = + static_cast(index) < static_cast(nodes) ? m_clusterPath->m_nodes[index].first : 0xFFFF; + m_set132.insert(cluster); + } + m_set132.insert(m_quadTree->getPolygon(m_searchGoalPolygon)->cluster); + m_pathfinding->setAllowedClusters(m_int76, &m_set132); + } + m_int56 = m_pathfinding->localSearch(static_cast(m_int76), m_mapIndex, static_cast(m_startIsland), + m_searchStartPolygon, m_searchStart, m_searchGoalPolygon, m_searchGoal, + m_equipmentType, m_path); + if (m_int56 != 1) + { + m_pathfinding->releaseResource(m_int76, m_bot->getBotId()); + m_int76 = 0xFFFFFFFFu; + if (m_int56 == 2) + { + calculatePoints(); + if (m_searchGoalIsFinal) + { + const unsigned int n = static_cast(m_navigationPoints.size()); + m_navigationPoints.resize(n + 1, NavigationPoint()); + m_navigationPoints[n].m_position = m_goal; + m_navigationPoints[n].m_polygon = m_goalPolygon; + m_clusterPath->m_nodes.resize(0); + m_clusterPath->m_i0 = 0; + } + m_flag192 = false; + m_quadTree = static_cast( + m_pathfinding->getQuadTree(m_mapIndex, static_cast(m_path->m_island))); + optimizePoints(); + updateNavPoints(); + updateNavPoints(); + ++m_clusterPath->m_i0; + m_polygonSearchPending = false; + return true; + } + if (static_cast(m_int56 - 3) < 2) + return false; + } + finished = true; + return true; +} + +// ELF 0x191AB0 (315 bytes). The coarse (cluster) search: on success the polygon search takes +// over (+0x44 set, state 0); a failure (3 / 4) resets the navigation. +bool BotNavigation::doClusterSearch(bool& finished, bool* blocked) +{ + if (m_int128 == 0xFFFFFFFFu) + { + if (!m_pathfinding->acquireClusterResource(m_int128, m_bot->getBotId())) + { + if (blocked) + *blocked = true; + return false; + } + } + m_int56 = m_pathfinding->clusterSearch(static_cast(m_int128), m_mapIndex, static_cast(m_startIsland), + static_cast(m_startPolygon), m_startPosition, + static_cast(m_goalPolygon), m_goal, m_equipmentType, + m_clusterPath); + if (m_int56 != 1) + { + m_pathfinding->releaseClusterResource(m_int128, m_bot->getBotId()); + m_int128 = 0xFFFFFFFFu; + if (m_int56 == 2) + { + m_useClusterSearch = false; + m_polygonSearchPending = true; + m_int56 = 0; + return true; + } + if (static_cast(m_int56 - 3) < 2) + { + reset(); + return false; + } + } + finished = true; + return true; +} + +// ELF 0x194CF0: within the smallest radius of a non-soldier obstacle (+0x58) with a physical. +bool BotNavigation::pointWithinObstacleRadius(const Vec3& point) +{ + for (unsigned int i = 0; i < m_obstacles.size(); ++i) + { + Information* const info = informationManager->getInformation(m_obstacles[i]); + if (!info || info->isOfType(ITSoldier) || !info->getPhysical()) + continue; + const Vec3& p = info->getPosition(); + const float radius = info->getPhysical()->getSmallestRadius(); + if ((point.x - p.x) * (point.x - p.x) + (point.y - p.y) * (point.y - p.y) + (point.z - p.z) * (point.z - p.z) + < radius * radius) + return true; + } + return false; +} + +// ELF 0x1932A0. The local path's steps become navigation points, appended after the last point +// (or replacing all when the current point is past the end): each point's position and polygon +// from the step, and its portal edge (+0 / +0xC) from IAIPathfinding +0x70 getEdge(map, previous +// entered-from polygon, polygon, island), or the position twice for the first step. The path is +// emptied afterwards. +void BotNavigation::calculatePoints() +{ + m_path->m_i0 = 0; + QTPath* path = m_path; + const unsigned int island = static_cast(path->m_island); + const unsigned int steps = static_cast(path->m_nodes.size()); + const unsigned int count = static_cast(m_navigationPoints.size()); + unsigned int base = count - 1; + if (count <= m_currentPoint) + base = 0; + unsigned int size = 0; + if (static_cast(path->m_i0) <= steps + base) + size = steps + base - static_cast(path->m_i0); + int from = -1; + if (path->m_i0 < static_cast(steps)) + from = static_cast(path->m_nodes[path->m_i0].second); + int polygon = -1; + if (path->m_i0 < static_cast(path->m_nodes.size())) + polygon = static_cast(path->m_nodes[path->m_i0].first); + m_navigationPoints.resize(size, NavigationPoint()); + path = m_path; + unsigned int k = base; + while (static_cast(path->m_i0) < steps) + { + int entered = polygon; + NavigationPoint& point = m_navigationPoints[k]; + point.m_position = *path->getPosition(static_cast(path->m_i0)); + point.m_polygon = static_cast(m_path->getPolygon(static_cast(m_path->m_i0))); + if (from == -1) + { + point.edgePoint1 = *m_path->getPosition(static_cast(m_path->m_i0)); + point.m_pointC = *m_path->getPosition(static_cast(m_path->m_i0)); + } + else + { + m_pathfinding->getEdge(point.edgePoint1, point.m_pointC, m_mapIndex, static_cast(from), + static_cast(entered), island); + } + ++m_path->m_i0; + path = m_path; + int next = -1; + if (path->m_i0 < static_cast(path->m_nodes.size())) + next = static_cast(path->m_nodes[path->m_i0].second); + if (next != -1) + entered = next; + polygon = -1; + if (path->m_i0 < static_cast(path->m_nodes.size())) + polygon = static_cast(path->m_nodes[path->m_i0].first); + ++k; + from = entered; + } + path->m_nodes.resize(0); + path->m_i0 = 0; + path->m_i20 = 0.0f; +} + +// ELF 0x1937D0. Two passes pull each point (5 m or more from the bot) onto its portal edge where +// the line from the previous point (the bot first) to the next point crosses it, kept a margin +// (max(0.8 radius, 1), at most half the edge) from the edge's ends; a final pass places every +// point where that line crosses its edge, when it does within the edge. +void BotNavigation::optimizePoints() +{ + if (m_navigationPoints.empty()) + return; + Vec2 from; + from.x = 0.0f; + from.y = 0.0f; + // BotMain +0x8C read inline (here through the accessor). + Information* const info = informationManager->getInformation(m_bot->getCurrentEquipment()); + vec3ToVec2XZ(info->getPosition(), from); + for (int pass = 0; pass < 2; ++pass) + { + for (unsigned int i = 0; i < m_navigationPoints.size() - 1; ++i) + { + const Vec3& p = info->getPosition(); + const Vec3& at = m_navigationPoints[i].m_position; + const float dx = p.x - at.x; + const float dy = p.y - at.y; + const float dz = p.z - at.z; + if (25.0f <= dx * dx + dy * dy + dz * dz) + { + Vec2 next, a, b; + next.x = 0.0f; next.y = 0.0f; + a.x = 0.0f; a.y = 0.0f; + b.x = 0.0f; b.y = 0.0f; + vec3ToVec2XZ(m_navigationPoints[i + 1].m_position, next); + vec3ToVec2XZ(m_navigationPoints[i].edgePoint1, a); + vec3ToVec2XZ(m_navigationPoints[i].m_pointC, b); + float s; + float t; + if (lineIntersect(from, next, a, b, s, t)) + { + const float ex = b.x - a.x; + const float ey = b.y - a.y; + const float length = std::sqrt(ey * ey + ex * ex); + const float along = length * t; + const float half = length * 0.5f; + float margin = m_radius * 0.8f; + if (margin <= 1.0f) + margin = 1.0f; + if (half <= margin) + margin = half; + if (half <= along) + { + if (length - margin < along) + t = 1.0f - margin / length; + } + else if (along < margin) + { + t = margin / length; + } + NavigationPoint& point = m_navigationPoints[i]; + const float u = t <= 1.0f ? t : 1.0f; + point.m_position.x = point.edgePoint1.x + (point.m_pointC.x - point.edgePoint1.x) * u; + point.m_position.y = (point.m_pointC.y - point.edgePoint1.y) * u + point.edgePoint1.y; + point.m_position.z = (point.m_pointC.z - point.edgePoint1.z) * u + point.edgePoint1.z; + } + } + vec3ToVec2XZ(m_navigationPoints[i].m_position, from); + } + } + vec3ToVec2XZ(info->getPosition(), from); + for (unsigned int i = 0; i < m_navigationPoints.size() - 1; ++i) + { + Vec2 next, a, b; + next.x = 0.0f; next.y = 0.0f; + a.x = 0.0f; a.y = 0.0f; + b.x = 0.0f; b.y = 0.0f; + vec3ToVec2XZ(m_navigationPoints[i + 1].m_position, next); + vec3ToVec2XZ(m_navigationPoints[i].edgePoint1, a); + vec3ToVec2XZ(m_navigationPoints[i].m_pointC, b); + float s; + float t; + if (lineIntersect(from, next, a, b, s, t) && 0.0f <= t && t <= 1.0f) + { + NavigationPoint& point = m_navigationPoints[i]; + point.m_position.x = (point.m_pointC.x - point.edgePoint1.x) * t + point.edgePoint1.x; + point.m_position.y = (point.m_pointC.y - point.edgePoint1.y) * t + point.edgePoint1.y; + point.m_position.z = (point.m_pointC.z - point.edgePoint1.z) * t + point.edgePoint1.z; + } + vec3ToVec2XZ(m_navigationPoints[i].m_position, from); + } +} + +// ELF 0x192C00 (670 bytes). Following a path (state 2) from a valid position: unless +240 is set, +// when the current point is within 10 m (soldier) / 20 m, skip ahead while the next point is +// directly reachable (trace with clearance 0.5 / 0, 8 / 30, at most 1 / 4 points); otherwise a +// failed trace to the current point sets +194. minClearanceVehicle is a zero-initialised static +// (.bss 0x4CE010, no guard); minClearanceSoldier is 0.5 (0x4B6C28). +void BotNavigation::updateNavPoints() +{ + static float minClearanceSoldier = 0.5f; + static float minClearanceVehicle; + + Information* const info = informationManager->getInformation(m_bot->getCurrentEquipment()); + if (!info || !info->getMobile() || m_int56 != 2) + return; + if (info->getMobile()->getLastValidPosition().polygon == 0xFFFFFFFFu) + return; + Vec3 hit; + hit.x = 0.0f; + hit.y = 0.0f; + hit.z = 0.0f; + const Vec3& position = info->getPosition(); + const bool soldier = m_updateSpaceLeftAndRight; + const int steps = soldier ? 8 : 30; + const float range = soldier ? 10.0f : 20.0f; + bool advanced = false; + const float clearance = soldier ? minClearanceSoldier : minClearanceVehicle; + unsigned int polygon; + if (m_skipTraceCount == 0) + { + const Vec3& current = m_navigationPoints[m_currentPoint].m_position; + const float dx = position.x - current.x; + const float dy = position.y - current.y; + const float dz = position.z - current.z; + if (dz * dz + dx * dx + dy * dy < range * range) + { + for (int i = 0; i < (soldier ? 1 : 4); ++i) + { + if (m_navigationPoints.size() - 1 <= m_currentPoint + || !m_pathfinding->trace(this, false, m_navigationPoints[m_currentPoint + 1].m_position, hit, polygon, + m_equipmentType, steps, clearance, 5, 0)) + break; + ++m_currentPoint; + advanced = true; + } + if (advanced) + return; + } + } + if (!m_pathfinding->trace(this, false, m_navigationPoints[m_currentPoint].m_position, hit, polygon, m_equipmentType, -1, + 0.0f, 0, 0)) + m_flag194 = true; +} + +// ELF 0x1946A0 (824 bytes). +0xBC: the distance from the bot along the remaining points, plus +// the remaining cluster path (its points 1.. from the last navigation point); +0x138 the points +// part. No points: 0. ClusterNodePath::getPoint is indexed from 1, not from the current step, +// as in the image. +void BotNavigation::updateClosestDistance() +{ + if (m_navigationPoints.empty()) + { + m_sentinel188 = 0.0f; + return; + } + // The image reads BotMain +0x8C inline (no null guard). + Information* const info = informationManager->getInformation(m_bot->getCurrentEquipment()); + const Vec3& position = info->getPosition(); + const Vec3& current = m_navigationPoints[m_currentPoint].m_position; + float distance = length3(position.x - current.x, position.y - current.y, position.z - current.z); + unsigned int i = m_currentPoint + 1; + for (; i < m_navigationPoints.size(); ++i) + { + const Vec3& a = m_navigationPoints[i - 1].m_position; + const Vec3& b = m_navigationPoints[i].m_position; + distance = length3(a.x - b.x, a.y - b.y, a.z - b.z) + distance; + } + ClusterNodePath* const cluster = m_clusterPath; + m_pathLength = distance; + const unsigned int nodes = static_cast(cluster->m_nodes.size()); + if (static_cast(cluster->m_i0) < nodes) + { + const unsigned int remaining = nodes - static_cast(cluster->m_i0); + Vec3 previous = m_navigationPoints[i - 1].m_position; + for (unsigned int k = 1; k < remaining; ++k) + { + Vec3 point; + point.x = 0.0f; point.y = 0.0f; point.z = 0.0f; + unsigned int polygon; + m_clusterPath->getPoint(point, polygon, k); + distance = length3(previous.x - point.x, previous.y - point.y, previous.z - point.z) + distance; + previous = point; + } + } + m_sentinel188 = distance; +} + +// ELF 0x1927A0 (130 bytes): a point on a missing or non-walkable (material 0) polygon. +bool BotNavigation::hasIllegalPath() +{ + for (unsigned int i = 0; i < m_navigationPoints.size(); ++i) + { + const Polygon* const polygon = m_quadTree->getPolygon(static_cast(m_navigationPoints[i].m_polygon)); + if (!polygon || polygon->m_material == 0) + return true; + } + return false; +} + +namespace { + +// Bot +4 inputs read inline: an unmapped input reads 0 (`(mappingFlags >> i) & 1`). +float mappedInput(const io::PlayerInput* input, io::PlayerInputMap index) +{ + return ((input->mappingFlags >> static_cast(index)) & 1ULL) ? input->inputs[index] : 0.0f; +} + +float distanceSq(const float* a, const Vec3& b) +{ + return (a[0] - b.x) * (a[0] - b.x) + (a[1] - b.y) * (a[1] - b.y) + (a[2] - b.z) * (a[2] - b.z); +} + +} // namespace + +// ELF 0x191BF0 (1192 bytes). The action input is released one second after +168. While a path +// is followed (state 2): no move input (max of throttle, sprint, yaw within 0.1) for 0.1 s +// (soldier) / 0.5 s restamps +144 and is progress; otherwise the bot progresses when it got +// 2 m (soldier) / 4 m from +280 (restamped then) or when it stayed within that for less than +// 10 s / 20 s since +144. A soldier standing still (0.001) for 2 s, 3 s after +168, sets +168 +// to -666 (BotNavigation +0x1D0's action press, see updatePath). +bool BotNavigation::checkProgress() +{ + io::PlayerInput* const input = m_bot->getInput(); + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (1.0 < now - m_double168 && ((input->mappingFlags >> io::PIAction) & 1ULL)) + input->inputs[io::PIAction] = 0.0f; + if (m_navigationPoints.empty() || m_int56 != 2) + return true; + float move = mappedInput(input, io::PIThrottle); + const float sprint = mappedInput(input, io::PISprint); + if (move <= sprint) + move = sprint; + const float yaw = mappedInput(input, io::PIYaw); + if (move < yaw) + move = yaw; + const double still = m_updateSpaceLeftAndRight ? 0.1 : 0.5; + if (std::fabs(move) <= 0.1f) + { + if (still < now - m_noThrottleTimer) + { + m_noProgressTimer = now; + m_flag192 = false; + return true; + } + } + else + { + m_noThrottleTimer = now; + } + const float radius = m_updateSpaceLeftAndRight ? 2.0f : 4.0f; + Information* const info = informationManager->getInformation(m_bot->getCurrentEquipment()); + const Vec3& position = info->getPosition(); + if (distanceSq(m_zero280, position) <= radius * radius) + { + const float limit = m_updateSpaceLeftAndRight ? 10.0f : 20.0f; + const double since = m_noProgressTimer; + if (m_updateSpaceLeftAndRight && 2.0f < static_cast(now - since) && 3.0 < now - m_double168) + { + if (distanceSq(m_zero176, info->getPosition()) < 0.001f) + m_double168 = -666.0; + const Vec3& p = info->getPosition(); + m_zero176[0] = p.x; + m_zero176[1] = p.y; + m_zero176[2] = p.z; + } + return now - since < static_cast(limit); + } + m_zero280[0] = position.x; + m_zero280[1] = position.y; + m_zero280[2] = position.z; + m_noProgressTimer = now; + m_flag192 = false; + return true; +} + +// ELF 0x1928B0 (840 bytes). From the last valid position, a trace 2 m along the transformation's +// right axis (row 0) and one 2 m the other way (IAIPathfinding +0x90, trace(BotNavigation*, ...), +// map index 0, the equipment type, -1, 0, 5): +296 / +292 get the free distance, 2 when the trace +// reports true. +void BotNavigation::updateSpaceLeftAndRight() +{ + Information* const info = informationManager->getInformation(m_bot->getCurrentEquipment()); + if (!info || !info->getMobile() || m_int56 != 2) + return; + const IPIMobile::ValidPos& valid = info->getMobile()->getLastValidPosition(); + if (valid.polygon == 0xFFFFFFFFu) + return; + Vec3 hit; + hit.x = 0.0f; + hit.y = 0.0f; + hit.z = 0.0f; + const Mat4& transformation = info->getTransformation(); + unsigned int polygon; + Vec3 probe; + probe.x = transformation.m[0] * 2.0f + valid.position.x; + probe.y = transformation.m[1] * 2.0f + valid.position.y; + probe.z = transformation.m[2] * 2.0f + valid.position.z; + float space = 2.0f; + if (!m_pathfinding->trace(this, false, probe, hit, polygon, m_equipmentType, -1, 0.0f, 5, 0)) + space = length3(hit.x - valid.position.x, hit.y - valid.position.y, hit.z - valid.position.z); + m_spaceRight = space; + probe.x = probe.x - transformation.m[0] * 2.0f * 2.0f; + probe.y = probe.y - transformation.m[1] * 2.0f * 2.0f; + probe.z = probe.z - transformation.m[2] * 2.0f * 2.0f; + space = 2.0f; + if (!m_pathfinding->trace(this, false, probe, hit, polygon, m_equipmentType, -1, 0.0f, 5, 0)) + space = length3(hit.x - valid.position.x, hit.y - valid.position.y, hit.z - valid.position.z); + m_spaceLeft = space; } // Always returns true, leaving BotManager's final pathfinding sweep gated by isSearchActive. @@ -199,6 +1322,80 @@ bool BotNavigation::isRunning() return true; } +// ELF 0x194F10. The bot's equipment's last valid position for `mapIndex` (IPIMobile, unchecked +// lookups as in the image). A new map or a moved position (any coordinate more than +// 1.1920929e-07f away) is kept (+0xD8, +0xE4) and returned with its polygon / island; it also +// refreshes the vehicle pair (+0xC8, when it is the navigation's own map +0x50) and the infantry +// pair (+0xD0, for IAIPathfinding::getTraceMapIndex). Otherwise the kept position is returned +// with the stored pair of that map, or Debug line 0x630 "Should not be here!" (pair untouched). +void BotNavigation::getTraceData(int mapIndex, unsigned int& polygon, unsigned int& island, Vec3& position) +{ + Information* const info = informationManager->getInformation(m_bot->getCurrentEquipment()); + const IPIMobile::ValidPos& valid = info->getMobile()->getLastValidPosition(mapIndex); + if (m_traceMapIndex != mapIndex + || std::fabs(valid.position.x - m_tracePosition.x) > 1.1920929e-07f + || std::fabs(valid.position.y - m_tracePosition.y) > 1.1920929e-07f + || std::fabs(valid.position.z - m_tracePosition.z) > 1.1920929e-07f) + { + m_traceMapIndex = mapIndex; + m_tracePosition = valid.position; + position = valid.position; + polygon = valid.polygon; + island = valid.island; + if (m_mapIndex == mapIndex) + { + m_currentPolygon = static_cast(valid.polygon); + m_vehicleIsland = static_cast(valid.island); + } + if (mapIndex == IAIPathfinding::instance->getTraceMapIndex()) + { + m_infantryPolygon = static_cast(valid.polygon); + m_infantryIsland = static_cast(valid.island); + } + return; + } + position = m_tracePosition; + if (mapIndex == IAIPathfinding::instance->getTraceMapIndex()) + { + polygon = static_cast(m_infantryPolygon); + island = static_cast(m_infantryIsland); + } + else if (mapIndex == m_mapIndex) + { + polygon = static_cast(m_currentPolygon); + island = static_cast(m_vehicleIsland); + } + else + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIBot/BotNavigation.cpp", 0x630, "") << "Should not be here!"; + } +} + +// ELF 0x192EA0: append the old route's remaining interior points after recalculating the prefix. +void BotNavigation::mergeNavigationPoints() +{ + const std::vector previous(m_navigationPoints); + unsigned int index = m_currentPoint; + m_path->m_i0 = 0; + calculatePoints(); + // Shipped defect: an empty previous route underflows this unsigned bound. + for (; index < previous.size() - 1; ++index) + m_navigationPoints.push_back(previous[index]); + NavigationPoint last; + last.edgePoint1 = m_goal; + last.m_pointC = m_goal; + last.m_position = m_goal; + last.m_polygon = m_goalPolygon; + m_navigationPoints.push_back(last); +} + +// ELF 0x195390: appends to the caller's vector without clearing it. +void BotNavigation::getNavigationPoints(std::vector& points) const +{ + for (std::vector::const_iterator it = m_navigationPoints.begin(); it != m_navigationPoints.end(); ++it) + points.push_back(it->m_position); +} + } // namespace ai } // namespace hfe } // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.h b/Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.h index c9b6fd8c0..debeae782 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.h @@ -5,6 +5,7 @@ #include #include +#include #include "../Main/AIPathfindingSearchTypes.h" // QTPath, ClusterNodePath - both already written #include "../../../../Math/Vec3.h" // Vec2 and Vec3 both live here, and both are typedefs @@ -16,30 +17,37 @@ namespace ai { class BotMain; class Information; +class IAIPathfinding; +class QuadTree; class BotNavigation { public: explicit BotNavigation(BotMain* owner); - ~BotNavigation(); // [FRONTIER] + ~BotNavigation(); // ELF 0x18FF30 - // [FRONTIER] Navigation methods below remain incomplete unless implemented explicitly. - void update(bool& a, bool* b); + bool update(bool& a, bool* b); void updateOccationally(); // dice's spelling - "Occationally" - void updatePath(Vec2& a, bool& b, bool& c, float d); + // ELF 0x192200: the point to walk to; `arrived` at the last point, `direct` when the bot + // should not follow points (no path, retracing, or blocked by a hostile vehicle's material). + bool updatePath(Vec2& point, bool& arrived, bool& direct, float distance); void updateNavPoints(); void updateObstacles(); + void drawPath(); void updateLastPoint(Information* info); void updateSpaceLeftAndRight(); void updateClosestDistance(); - void initPathfinding(const Vec3& to, float a, float b); - void initPathfinding(unsigned int a, unsigned int b, const Vec3& to, float c, float d); - void doPolygonSearch(bool& a, bool* b); - void doClusterSearch(bool& a, bool* b); + // ELF 0x1901B0 / 0x1902B0: start a path search to `to`; false when none can be started. + bool initPathfinding(const Vec3& to, float arriveDistance, float b); + bool initPathfinding(unsigned int island, unsigned int goalPolygon, const Vec3& to, float arriveDistance, float b); + bool doPolygonSearch(bool& a, bool* b); + bool doClusterSearch(bool& a, bool* b); void calculatePoints(); + void mergeNavigationPoints(); + void getNavigationPoints(std::vector& points) const; void optimizePoints(); - bool testDirectPath(); + void testDirectPath(); // ELF 0x190DA0 (void: no eax on its exits) void retrace(); bool stillOnPath(); @@ -58,110 +66,180 @@ class BotNavigation bool isActive(); // returns true, unconditionally, in both images. bool isRunning(); - void checkProgress(); + int getMapIndex() const { return m_mapIndex; } + // [INFERRED] readers of fields the BAP actions read inline (ai-w1-c-actions request): + // +0x2C (BAPAMoveTo*), +0xBC, +0xC0, +0xCC (BAPAMoveToObjectFinding::initObjectFinding). + const Vec3& getGoal() const { return m_goal; } + float getTargetDistance() const { return m_sentinel188; } + bool getIsStuck() const { return m_flag192; } + unsigned int getLastValidIsland() const { return static_cast(m_vehicleIsland); } + // [INFERRED] reader of +0x58 (InfanteryControl / BBAvoid read begin/end inline). + const std::vector& getObstacles() const { return m_obstacles; } + float getSpaceLeft() const { return m_spaceLeft; } + float getSpaceRight() const { return m_spaceRight; } + bool checkProgress(); void clearProgress(); bool checkArrivedAtPoint(float distance); void setIsStuck(bool stuck); bool pointWithinObstacleRadius(const Vec3& point); void getFirstPointBeyondDist(const Vec2& from, float distance, Vec2& out); - void getSecondPoint(Vec2& out); - void getLargestAngleDiff(float& out); + bool getSecondPoint(Vec2& out); // ELF 0x1940C0 + bool getLargestAngleDiff(float& out); // ELF 0x194120 (always true) void getTraceData(int a, unsigned int& b, unsigned int& c, Vec3& d); - void getGrenadeWarning(Vec3& position, double& time); - void setGrenadeWarning(const Vec3& position, double time, bool b); + // ELF 0x195310: the warned position and the time left of 2.8 s; true while some is left. + bool getGrenadeWarning(Vec3& position, double& timeLeft); + // [INFERRED] reader of +0x114 (BBRandom / BBAvoid::calculateUrgency read it inline). + bool getGrenadeFlag() const { return m_grenadeFlag; } + void setGrenadeWarning(const Vec3& position, double time, bool b); // ELF 0x195280 void reset(); // - (one arm frontier) void resetAll(); - // attested as a nested type by the container instantiations, which spell - // `std::vector` in full. sizeof is 40, from - // the constructor's divide; the members are [UNRESOLVED] because nothing recovered so far builds - // one. Declared as a sized block rather than guessed at. + // attested as a nested type by the container instantiations. sizeof 40. testDirectPath + // (ELF 0x190DA0) writes all three Vec3 = the goal and +0x24 = trace's polygon; the walkers + // (updatePath, getSecondPoint, ...) read +0x18 and +0x24. The first two Vec3 are + // [UNRESOLVED] names. struct NavigationPoint { - // Initializes the index to -1 and clears the preceding 36 bytes. - // [UNRESOLVED] The contents of that byte range remain unknown. NavigationPoint() - : m_index36(-1) + : m_polygon(-1) { - for (int i = 0; i < 36; ++i) - m_bytes[i] = 0; + edgePoint1.x = 0.0f; edgePoint1.y = 0.0f; edgePoint1.z = 0.0f; + m_pointC.x = 0.0f; m_pointC.y = 0.0f; m_pointC.z = 0.0f; + m_position.x = 0.0f; m_position.y = 0.0f; m_position.z = 0.0f; } - char m_bytes[36]; // [UNRESOLVED] - int m_index36; // = -1 + /* +0x00 */ Vec3 edgePoint1; // name: AIDLL_r assert "m_navigationPoints[i].edgePoint1" 0x10149B20 (entry +0) + /* +0x0C */ Vec3 m_pointC; + /* +0x18 */ Vec3 m_position; + /* +0x24 */ int m_polygon; // = -1 }; private: + // ELF 0x22A429 reads the infantry polygon inline; reset writes it at 0x190D14. + friend class BBPAvoidCollision2d; /* 0 */ BotMain* m_bot; // the ctor argument, and the first store - /* 4 */ float m_float4; // = 2.0f [UNRESOLVED] + // initPathfinding's two floats (ELF 0x1902B0 stores +4 = a, +8 = b, +0xC = b * b); + // checkArrivedAtPoint arrives within max(+4, 1) for a vehicle. [INFERRED] names. + /* 4 */ float m_arriveDistance; // = 2.0f /* 8 */ float m_float8; // = 2.0f [UNRESOLVED] - /* 12 */ char m_gap12[4]; // [UNRESOLVED] - never written - /* 16 */ int m_int16; // = -1 - /* 20 */ int m_int20; // = -1 - /* 24 */ int m_zero24[3]; // +24..+32, all 0 - /* 36 */ int m_int36; // = -1 - /* 40 */ bool m_flag40; // = false + /* 12 */ float m_float8Squared; // initPathfinding: b * b + // initPathfinding / retrace: the bot's last valid position (IPIMobile::ValidPos fields). + /* 16 */ int m_startIsland; // = -1; ValidPos::island [INFERRED] name: AIDLL_r names +112 m_island (0x10149B20), so this one was renamed + /* 20 */ int m_startPolygon; // = -1 + /* 24 */ Vec3 m_startPosition; // all 0 + /* 36 */ int m_goalPolygon; // = -1 + // IAIPathfinding::getMaterial's answer for the goal polygon (initPathfinding) or trace's. + /* 40 */ unsigned char m_goalMaterial; // = 0 /* 41 */ char m_pad41[3]; - /* 44 */ int m_zero44[3]; // +44..+52, all 0 + /* 44 */ Vec3 m_goal; // all 0; initPathfinding's target + // path state: 0 reset, 2 path ready (testDirectPath), 4 (update stops). [INFERRED] /* 56 */ int m_int56; // not a gap - `reset` zeroes it - // Owns polygon and cluster path reservations, released through virtual slots +156 and - // +164 during reset. [UNRESOLVED] The interface type is not yet known. - /* 60 */ void* m_pathOwner; // = 0 - /* 64 */ int m_zero64; // = 0 - /* 68 */ char m_gap68[4]; // [UNRESOLVED] - never written - /* 72 */ QTPath* m_polygonPath; // new(0x18) - the fine path - /* 76 */ int m_int76; // = -1 - /* 80 */ char m_gap80[8]; // [UNRESOLVED] - never written - /* 88 */ int m_zero88[3]; // +88, +92, +96 + // IAIPathfinding::instance, set by initPathfinding; reset releases the two reservations + // through it (releaseResource +0x9C, releaseClusterResource +0xA4). + /* 60 */ IAIPathfinding* m_pathfinding; // = 0 + // IAIPathfinding::getQuadTree(map, island) (+0x64), set by initPathfinding. + /* 64 */ QuadTree* m_quadTree; // = 0 + // update (ELF 0x191320) sets it with the point reset and runs the polygon search while it + // is set. [CHOSEN] name. + /* 68 */ bool m_polygonSearchPending; + /* 69 */ char m_pad69[3]; + /* 72 */ QTPath* m_path; // new(0x18) - the fine path // name: AIDLL_r assert 0x10149B20 (PE +0x48) + // IAIPathfinding::acquireResource's polygon-search slot; -1 = none. + /* 76 */ unsigned int m_int76; // = -1 + // AIPathfinding::trace (ELF 0x3A81C0) reads +0x50 as the map index passed to getTraceData + // when it does not use the trace map. [INFERRED] name. + /* 80 */ int m_mapIndex; // never written by the constructor + // IPIUnit::getEquipmentType of the bot's equipment, set by initPathfinding. [INFERRED] name. + /* 84 */ int m_equipmentType; // never written by the constructor + // updateObstacles (ELF 0x194B60) clears and fills it through getObjectsWithinRadius, and + // stores its size at +252. + /* 88 */ std::vector m_obstacles; // the walkable result - see the header note. The constructor's dead resize targets this. - /* 100 */ std::vector m_points; - /* 112 */ char m_gap112[4]; // [UNRESOLVED] - never written - /* 116 */ int m_int116; // = 0 - /* 120 */ char m_gap120[4]; // [UNRESOLVED] - never written + /* 100 */ std::vector m_navigationPoints; // name: AIDLL_r assert 0x10149B20 (PE +0x68, 0x28-byte entries) + // the island the path was searched on (initPathfinding: the start island). + /* 112 */ int m_island; // never written by the constructor // name: AIDLL_r assert "m_island == m_path->getIsland()" 0x10149B20 (PE +0x78) + // index of the point being walked to. + /* 116 */ unsigned int m_currentPoint; // = 0 + // update: nonzero selects the cluster search. [CHOSEN] name. + /* 120 */ bool m_useClusterSearch; + /* 121 */ char m_pad121[3]; /* 124 */ ClusterNodePath* m_clusterPath; // new(0x1C) - the coarse path - /* 128 */ int m_int128; // = -1 + // the cluster-search slot (acquireClusterResource); -1 = none. + /* 128 */ unsigned int m_int128; // = -1 // `allocate(20)` with 0 / 0 / self / self is an `_Rb_tree` header at 16 + sizeof(value_type) // so the value type is four bytes - a set of pointers or handles. Which is [UNRESOLVED]; // `void*` holds the width and claims nothing. - /* 132 */ std::set m_set132; - /* 144 */ double m_double144; // = 0.0 - /* 152 */ double m_double152; // = 0.0 + /* 132 */ std::set m_set132; // doPolygonSearch: the clusters the local search may use (setAllowedClusters) + /* 144 */ double m_noProgressTimer; // = 0.0 // name: AIDLL_r assert in checkProgress 0x10145DD0 (PE +0x98) + /* 152 */ double m_noThrottleTimer; // = 0.0 // name: AIDLL_r assert in checkProgress 0x10145DD0 (PE +0xA0) /* 160 */ double m_double160; // = 0.0 /* 168 */ double m_double168; // = 0.0 - /* 176 */ int m_zero176[3]; // +176, +180, +184 + /* 176 */ float m_zero176[3]; // +176..+184; checkProgress: the soldier position at the last action-press check // is 9,999,999.0f - a "no distance yet" sentinel, and a third kind after the // DBL_MAX timestamps and -9999.0 magnitudes BotMain uses. Do not normalise them together. + // distance to the target (C's reader); reset 9999999.0f, updatePath's arrival 1e8f. /* 188 */ float m_sentinel188; // = 9999999.0f + // setIsStuck writes it (never while parachuting); initPathfinding sets it when no path can + // be started; updatePath does nothing while it is set. /* 192 */ bool m_flag192; // = false /* 193 */ bool m_flag193; // = false /* 194 */ bool m_flag194; // not padding - `reset` clears it /* 195 */ bool m_flag195; // = false /* 196 */ char m_gap196[4]; // [UNRESOLVED] - never written - /* 200 */ int m_int200; // = -1 - /* 204 */ int m_int204; // = -1 - /* 208 */ int m_int208; // = -1 - /* 212 */ int m_int212; // = -1 - /* 216 */ int m_zero216[3]; // +216, +220, +224 - /* 228 */ char m_gap228[12]; // [UNRESOLVED] - never written - /* 240 */ int m_int240; // = 0 + // the last valid positions (reset / initPathfinding): the vehicle's (getLastValidPosition of + // the vehicle number) and the infantry one (IPIMobile +8 / +0xC). + /* 200 */ int m_currentPolygon; // = -1 // name: AIDLL_r asserts 0x10146930, 0x1014AD10 (PE +0xD0) + /* 204 */ int m_vehicleIsland; // = -1 + /* 208 */ int m_infantryPolygon; // = -1 + /* 212 */ int m_infantryIsland; // = -1 + // getTraceData (ELF 0x194F10): the last traced valid position and its map index. The + // constructor zeroes the position (three word stores); the index is never initialised. + /* 216 */ Vec3 m_tracePosition; + /* 228 */ int m_traceMapIndex; + // IPIPhysical::getSmallestRadius of the equipment (initPathfinding). [INFERRED] name. + /* 232 */ float m_radius; + // initPathfinding: the equipment's type flags carry 0x200000 (byte +6 bit 0x20). The soldier + // arms test it (checkArrivedAtPoint's soldierMinDist, updatePath's 0.5 s retrace delay); + // updateOccationally (ELF 0x192830) calls updateSpaceLeftAndRight while it is set. + /* 236 */ bool m_updateSpaceLeftAndRight; + /* 237 */ char m_pad237[3]; + // updatePath: useSkipTrace && soldier before a retrace; stillOnPath counts it down. + /* 240 */ int m_skipTraceCount; // = 0 // name: AIDLL_r assert 0x101471C0 (PE +0xF8) + // updatePath's game time (isActive: three seconds). /* 244 */ double m_double244; // not a gap - `reset` zeroes it // resetAll clears this field. /* 252 */ int m_int252; // resetAll: 0 - /* 256 */ int m_zero256[3]; // +256, +260, +264 - /* 268 */ double m_double268; // = 0.0 - /* 276 */ bool m_flag276; // = false + // setGrenadeWarning (ELF 0x195280) writes all three; getGrenadeWarning answers 2.8 s from + // +268. [INFERRED] names. + /* 256 */ Vec3 m_grenadePosition; // all 0 + /* 268 */ double m_grenadeTime; // = 0.0; resetAll -9999.0 + /* 276 */ bool m_grenadeFlag; // = false; setGrenadeWarning's bool /* 277 */ char m_pad277[3]; - /* 280 */ int m_zero280[5]; // +280..+296 - /* 300 */ double m_double300; // Initially -1.0; independent of the distance sentinel. - /* 308 */ int m_zero308[2]; // +308, +312 + /* 280 */ float m_zero280[3]; // +280..+288; checkProgress: the position at the last progress + // BotMain::postPlanExecution (ELF 0x189220) strafes towards avoid side 1 while +292 > 0.5 + // and towards side 2 while +296 > 0.5; updateSpaceLeftAndRight writes them. [INFERRED] names. + /* 292 */ float m_spaceLeft; + /* 296 */ float m_spaceRight; + /* 300 */ double m_lastAngleDiffTest; // Initially -1.0; independent of the distance sentinel. // name: AIDLL_r assert 0x10147490 (PE +0x138) + // getLargestAngleDiff's cached answer (recomputed every 0.5 s, +300 the time). + /* 308 */ float m_largestAngleDiff; // = 0 + // updateClosestDistance: the walked-points length from the bot (updatePath re-checks the + // cluster path at 30 or more). [INFERRED] name. + /* 312 */ float m_pathLength; // = 0 // `reset`'s first statement clears the byte here. /* 316 */ bool m_flag316; // reset: false /* 317 */ char m_pad317[3]; - /* 320 */ int m_zero320[6]; // +320..+340 - /* 344 */ char m_gap344[12]; // +344..+355 - the ctor never reaches them [UNRESOLVED] + // doPolygonSearch's local search segment: from the last point (or the start) to the next + // cluster portal two steps ahead (or the goal). [INFERRED] names. + /* 320 */ Vec3 m_searchStart; // ctor: 0 + /* 332 */ Vec3 m_searchGoal; // ctor: 0 + /* 344 */ unsigned int m_searchStartPolygon; // never written by the ctor + /* 348 */ unsigned int m_searchGoalPolygon; + /* 352 */ bool m_searchGoalIsFinal; // the segment ends at the goal + /* 353 */ char m_pad353[3]; }; } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.cpp index fa52c41be..8331be476 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.cpp @@ -1,10 +1,38 @@ -// [FRONTIER] Remaining methods stop by name until implemented. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining BotSenses operations. - #include "BotSenses.h" #include "../AIUtils/checkPointer.h" #include "../Main/AIDllFrontier.h" +#include "../Main/CommonSingletonServer.h" +#include "BotMain.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../AIKnowledge/FireObject.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../Main/AIRandom.h" +#include "CommunicationAgent.h" +#include "SensedObject.h" +#include "SensingAgent.h" + +#include +#include +#include +#include +// static init: ELF 0x19E110, 0x19E200, 0x19E230: iostream Init and six cosine thresholds. + +#include "../../../AIInterface/BFKnowledge/AIAdapterTypes.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../../../../Core/Debug.h" +#include "../../../../Math/Mat4.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIUtils/DebugRendering/AIRenderUtil.h" +#include "../Main/IBotManager.h" namespace dice { namespace hfe { @@ -15,12 +43,12 @@ BotSenses::BotSenses(BotMain* owner) : m_bot(owner) // the camera. See the block above. , m_frustum(checkPointer(new Frustum())) - , m_double12(-1000000.0) - , m_int32(0) - , m_int36(0) - , m_int40(0) - , m_int88(0) - , m_int92(0) + , m_collectTime(-1000000.0) + , m_frustumStep(0) + , m_seeState(0) + , m_seeIndex(0) + , m_fireTotalStrength(0) + , m_fireTotalStrengthAgainstSelf(0) { // the constructor'S last statement - see the block above. The binary copies the list's head // pointer; in source that is the list's own end. The cursor at +80 is deliberately not here. @@ -31,11 +59,17 @@ BotSenses::BotSenses(BotMain* owner) // [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. void BotSenses::reset() { + // ELF 0x199D40: a record holding a contact (+0x64) releases it on its own information + // (slot 7, removeContact), then the record is deleted and its node erased. for (SensedObjectMap::iterator it = m_sensedObjects.begin(); it != m_sensedObjects.end(); ) { - // Retail here releases the object's `Information` through `informationManager` and then - // deletes `it->second`. See the block above for why this tree cannot write it yet. - BF2_AI_FRONTIER("dice::hfe::ai::BotSenses::reset (sensed objects present)"); + if (it->second->m_hasContact) + { + if (Information* const information = informationManager->getInformation(it->second->m_handle)) + information->removeContact(); + } + if (it->second) + delete it->second; m_sensedObjects.erase(it++); } m_sensedObjects.clear(); @@ -45,25 +79,26 @@ void BotSenses::reset() m_cursor60 = m_list56.end(); m_sortBuffer.clear(); - m_int40 = 0; - m_int36 = 0; - m_int32 = 0; - m_double12 = -1000000.0; + m_seeIndex = 0; + m_seeState = 0; + m_frustumStep = 0; + m_collectTime = -1000000.0; - m_set64.clear(); - m_list76.clear(); + m_hearingMemHelperSet.clear(); + m_hearingMemCheckQueue.clear(); // The constructor never did this; the cursor at +80 becomes valid here for the first time. - m_cursor80 = m_list76.end(); + m_cursor80 = m_hearingMemCheckQueue.end(); + // The fire list owns its objects; the attacker map below only borrows them. for (std::list::iterator it = m_list84.begin(); it != m_list84.end(); ++it) { - // Retail here is `delete it->first;`. See the block above. - BF2_AI_FRONTIER("dice::hfe::ai::BotSenses::reset (fire objects present)"); + if (it->first) + delete it->first; } m_list84.clear(); - m_int88 = 0; - m_int92 = 0; + m_fireTotalStrength = 0; + m_fireTotalStrengthAgainstSelf = 0; m_map100.clear(); } @@ -75,8 +110,1293 @@ BotSenses::~BotSenses() delete m_frustum; } -// [FRONTIER] Remaining sight, hearing and communication operations require implementation. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. +// ELF 0x19A040 (172 bytes). Hearing gets a tenth and the fire objects three tenths of the slice; +// seeing gets what is left of the deadline (start + slice - now). The ELF reads the update time +// (IBFTimer +0x10) three times; the middle read's result is discarded. +void BotSenses::updateSensing(const double& slice) +{ + const IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); + const double start = timer->getUpdateTime(); + const double total = slice; + const double hearing = total * 0.1; + updateHearing(hearing); + timer->getUpdateTime(); + const double fire = slice * 0.3; + updateFireObjects(fire); + const double seeing = (start + total) - timer->getUpdateTime(); + updateSeeing(seeing); +} + +// ELF 0x19D8A0: map find at +112, the mapped SensedObject* or null. +SensedObject* BotSenses::getSensedObjectFromHandle(unsigned int handle) const +{ + const SensedObjectMap::const_iterator it = m_sensedObjects.find(handle); + return it == m_sensedObjects.end() ? 0 : it->second; +} + +namespace { + +// ELF data 0x4B6CA0 (BotSenses.cpp's anonymous namespace): two rows (m_viewMode) of three +// {angle, threshold} pairs. see() takes the frustum angle from a row's first pair only, and the +// frustum-step threshold from pair m_frustumStep. The thresholds are initialized with cosf. +struct FrustumUpdateAngle +{ + float angle; + float threshold; +}; +FrustumUpdateAngle tweak_frustumUpdateAngle[2][3] = +{ + { { 1.7453293f, std::cos(0.436332315f) }, { 1.0471976f, std::cos(0.261799395f) }, + { 0.5235988f, std::cos(0.130899698f) } }, + { { 1.3089969f, std::cos(0.327249229f) }, { 0.7853982f, std::cos(0.196349546f) }, + { 0.2617994f, std::cos(0.065449849f) } }, +}; + +// The sort order of the candidate buffer (std::__unguarded_linear_insert ELF 0x19FED0): +// ascending squared distance. +struct InfoDistPred +{ + bool operator()(const std::pair& a, const std::pair& b) const + { + return a.first < b.first; + } +}; + +// ELF vtable 0x4B6CD0, predicate 0x1A0E30: which player-occupied objects a bot considers. +// Neutral objects within the view radius; never its own side; a dead physical object of type 21 +// is skipped; with `vehicleSight` the radius is also capped at 300 m (90000), otherwise a unit +// must also be within its own cull distance. +class SideFilter : public AIObjectPredicate +{ +public: + SideFilter(int side, const Vec3& position, float radiusSq, bool vehicleSight) + : m_side(side), m_position(position), m_radiusSq(radiusSq), m_vehicleSight(vehicleSight) + { + } + + virtual bool predicate(IAIObject* object) + { + const int side = object->getSide(); + if (side == 0) + return m_radiusSq > distanceSq(object); + if (side == m_side) + return false; + if (object->isOfType(static_cast(0x15))) + { + if (!object->isPhysical()) + return false; + if (0.0f >= object->getPhysical()->getHealth()) + return false; + } + const float distSq = distanceSq(object); + if (object->isUnit() && !m_vehicleSight) + { + if (!(m_radiusSq > distSq)) + return false; + return object->getUnit()->getCullDistanceSqr() > distSq; + } + if (!m_vehicleSight) + return m_radiusSq > distSq; + if (!(m_radiusSq > distSq)) + return false; + return 90000.0f > distSq; + } + +private: + float distanceSq(IAIObject* object) const + { + const Vec3& position = object->getPosition(); + const float dx = position.x - m_position.x; + const float dy = position.y - m_position.y; + const float dz = position.z - m_position.z; + return dx * dx + dy * dy + dz * dz; + } + + /* +0x04 */ int m_side; + /* +0x08 */ Vec3 m_position; + /* +0x14 */ float m_radiusSq; + /* +0x18 */ bool m_vehicleSight; +}; + +float distanceSqTo(const Vec3& own, IAIObject* object) +{ + const Vec3& position = object->getPosition(); + const float dx = own.x - position.x; + const float dy = own.y - position.y; + const float dz = own.z - position.z; + return dx * dx + dy * dy + dz * dz; +} + +} // namespace + +// ELF 0x198420 (6421 bytes). A time-sliced state machine over m_seeState: +// (3 -> 0) mark the camera's quadrants seen and step the frustum (m_frustumStep cycles 0, 1, 2 +// and drops to 0 once the camera has turned away from the last frustum direction); +// always rebuild the frustum from the camera (tweak angle, aspect 1, near 0.01, the player's +// view distance); +// 0 gather the player-occupied candidates (SideFilter), keep those in the frustum, close +// and in front (vehicle sight), or within three own radii, with their exposed +// occupiers, as (squared distance, handle); +// 1 sort them by distance; +// 2 for each not yet in the seen list, sample up to 1..10 sense points (bounding radius * +// 30 / distance) and cast a ray from the eye (camera position, y - 0.1); the first clear +// ray reports the object as seen to the bot and to every bot riding with it. +// Between the states the slice is checked against the update time. +void BotSenses::see(const double& slice) +{ + const IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); + const double start = timer->getUpdateTime(); + // As in the image, the equipment information is used without a null check. + Information* const equipment = informationManager->getInformation(m_bot->getCurrentEquipment()); + m_bot->getName(); + const Mat4& camera = *static_cast(m_bot->getPlayer()->getCameraTransformation()); + m_viewMode = equipment->isOfType(ITObstructedView); + if (m_seeState == 3) + { + m_bot->setQuadSeen(); + m_seeState = 0; + const Mat4& previous = m_frustum->m_transformation; + const float turn = camera.m[8] * previous.m[8] + camera.m[9] * previous.m[9] + + camera.m[10] * previous.m[10]; + if (m_frustumStep == 1) + m_frustumStep = 2; + else if (m_frustumStep == 0) + m_frustumStep = 1; + else + m_frustumStep = 0; + if (turn <= tweak_frustumUpdateAngle[m_viewMode][m_frustumStep].threshold) + m_frustumStep = 0; + } + IAIPlayer* const player = m_bot->getPlayer(); + player->getFieldOfView(); + const float viewDistance = player->getViewDistance(); + m_frustum->setPerspective(tweak_frustumUpdateAngle[m_viewMode][0].angle, 1.0f, 0.01f, viewDistance, camera); + + IAIObjectEnvironment* const environment = + static_cast(CommonSingletonServer::m_iaiObjectEnvironment); + switch (m_seeState) + { + case 0: + { + m_candidates.resize(0); + const int side = m_bot->getSide(); + bool vehicleSight = false; + if (equipment->isOfType(ITAir) || equipment->isOfType(ITHelicopter)) + vehicleSight = true; + SideFilter filter(side, equipment->getPosition(), viewDistance * viewDistance, vehicleSight); + const float ownRadius = equipment->getPhysical()->getRadius(); + environment->getWorldPlayerOccupiedObjects(m_candidates, &filter); + m_sortBuffer.resize(0); + const Vec3& own = equipment->getPosition(); + const float closeSq = static_cast(static_cast(ownRadius) * 3.0 * ownRadius * 3.0); + for (std::vector::iterator it = m_candidates.begin(); it != m_candidates.end(); ++it) + { + IAIObject* const object = *it; + Information* const information = informationManager->getInformation(object->getInformation(m_bot->getSide())); + const float radius = object->getBoundingRadius(); + bool take = m_frustum->inside(object->getPosition(), radius); + if (!take) + { + if (!equipment->isOfType(ITSoldier) + && (!information || information->isOfType(ITSoldier))) + { + take = vehicleSight && isCloseAndInFront(equipment, object); + } + else + { + const Vec3& position = object->getPosition(); + const float dx = position.x - own.x; + const float dy = position.y - own.y; + const float dz = position.z - own.z; + take = dx * dx + dy * dy + dz * dz <= closeSq; + } + } + if (!take) + continue; + { + const float distSq = distanceSqTo(own, object); + m_sortBuffer.push_back(std::make_pair(distSq, object->forceGetInformation(side, false))); + } + if (!object->isUnit()) + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIBot/BotSenses.cpp", 413, "") + << object->getName() << " has no unit."; + } + else + { + IAIObjectUnit* const unit = object->getUnit(); + if (unit->hasExposedSoldier() && unit->isOccupied()) + { + IAIObject* const occupier = unit->getOccupier(); + const float distSq = distanceSqTo(own, occupier); + m_sortBuffer.push_back(std::make_pair(distSq, occupier->forceGetInformation(side, false))); + } + } + int iterator; + for (IAIObject* secondary = object->getFirstSecondaryObject(iterator); secondary; + secondary = object->getSecondaryObject(iterator)) + { + IAIObjectUnit* const unit = secondary->getUnit(); + if (!unit || !unit->hasExposedSoldier() || !unit->isOccupied()) + continue; + IAIObject* const occupier = unit->getOccupier(); + if (!occupier) + continue; + const float distSq = distanceSqTo(own, occupier); + m_sortBuffer.push_back(std::make_pair(distSq, occupier->forceGetInformation(side, false))); + } + } + m_seeIndex = 0; + m_collectTime = timer->getGameTime(); + m_seeState = 1; + if (slice < timer->getUpdateTime() - start) + return; + } + // fall through + case 1: + equipment->getPosition(); + if (!m_sortBuffer.empty()) + std::sort(m_sortBuffer.begin(), m_sortBuffer.end(), InfoDistPred()); + m_seeState = 2; + if (slice < timer->getUpdateTime() - start) + return; + // fall through + case 2: + break; + case 3: + timer->getUpdateTime(); + return; + default: + return; + } + + const Vec3& own = equipment->getPosition(); + std::vector ignore; + ignore.push_back(equipment->getAIObject()->getPrimaryObject()); + ignore.push_back(0); + ignore.push_back(0); + const bool render = IBotManager::instance->getRenderBotSensing(); + AIRenderUtil* const renderUtil = render ? AIRenderUtil::m_instance : 0; + const int side = m_bot->getSide(); + double elapsed = timer->getUpdateTime() - start; + equipment->getPhysical()->getRadius(); + bool finished = true; + while (m_seeIndex < static_cast(m_sortBuffer.size())) + { + if (slice <= elapsed) + { + finished = false; + break; + } + const unsigned int handle = m_sortBuffer[m_seeIndex].second; + Information* const target = m_map44.find(handle) == m_map44.end() + ? informationManager->getInformation(handle) : 0; + if (target && target->isRootObject()) + { + IAIObject* const targetObject = target->getAIObject(); + Bot* const targetBot = IBotManager::instance->getBot(targetObject); + bool activeBot = false; + if (targetBot) + activeBot = 0 < static_cast(targetBot->getLodLevel()); + targetObject->getBoundingRadius(); + ignore[1] = targetObject; + // [CHOSEN, not recovered] The image stores the third ignored object even after an + // earlier target shrank the list to two (inside the capacity, past the size, so the + // ray test never sees it); the size test keeps that store out of a native vector. + IAIObject* rider = 0; + bool keepRider = false; + if (IPIUnit* const unit = target->getUnit()) + { + if (!target->isOfType(ITSoldier)) + { + if (unit->hasExposedSoldier()) + { + if (Information* const occupier = + informationManager->getInformation(unit->getOccupier(m_bot->getSide()))) + { + rider = occupier->getAIObject(); + keepRider = true; + } + } + } + else if (Information* const occupied = + informationManager->getInformation(unit->getOccupiedObject(m_bot->getSide()))) + { + if (occupied->getUnit() && occupied->getUnit()->hasExposedSoldier()) + { + rider = occupied->getAIObject(); + keepRider = true; + } + } + } + if (keepRider) + { + if (ignore.size() > 2) + ignore[2] = rider; + } + else + { + ignore.resize(2); + } + + Vec3 eye; + eye.x = camera.m[12]; + eye.y = camera.m[13] - 0.1f; + eye.z = camera.m[14]; + const Vec3& targetPosition = targetObject->getPosition(); + const float dx = own.x - targetPosition.x; + const float dy = own.y - targetPosition.y; + const float dz = own.z - targetPosition.z; + const float distance = std::sqrt(dx * dx + dy * dy + dz * dz); + // The image converts with fistp: 1e14 (and any value past INT_MAX) becomes INT_MIN, + // i.e. one sample after the clamp. [CHOSEN] spelled out for a native conversion. + const double ratio = 0.0f < distance + ? static_cast(targetObject->getBoundingRadius()) * 30.0 / distance : 1e14; + int samples = ratio >= 2147483648.0 || ratio <= -2147483649.0 ? INT_MIN : static_cast(ratio); + if (samples < 1) + samples = 1; + else if (10 < samples) + samples = 10; + unsigned int part = static_cast(-1); + const bool soldier = target->isOfType(ITSoldier); + for (int k = 0; k < samples; ++k) + { + Vec3 point; + point.x = 0.0f; + point.y = 0.0f; + point.z = 0.0f; + Vec3 normal = point; + if (!soldier && k == 0 && samples != 1) + point = targetObject->getPosition(); + else if (!soldier) + environment->pickRandomSensePosition(point, normal, eye, targetObject); + else + environment->pickSoldierRandomSensePosition(point, normal, targetObject, part); + bool hitFlag; + const bool blocked = + environment->collideLineWithWorld(eye, point, ignore, activeBot, 0.8f, true, hitFlag); + if (render) + renderUtil->addSensingLine(eye, point, side, !blocked); + if (blocked) + continue; + Information* self = equipment; + if (!equipment->isPrimary()) + self = informationManager->getInformation(equipment->getPrimaryObject(m_bot->getSide())); + if (Bot* const viewer = IBotManager::instance->getBot(self->getAIObject())) + viewer->getSensingAgent()->getSenses()->event_seenObject( + handle, normal, part, target, viewer == m_bot, hitFlag); + int iterator = -1; + for (Information* secondary = informationManager->getInformation( + self->getFirstSecondaryObject(iterator, m_bot->getSide())); + secondary; + secondary = informationManager->getInformation(self->getSecondaryObject(iterator, m_bot->getSide()))) + { + if (Bot* const viewer = IBotManager::instance->getBot(secondary->getAIObject())) + viewer->getSensingAgent()->getSenses()->event_seenObject( + handle, normal, part, target, viewer == m_bot, hitFlag); + } + break; + } + } + ++m_seeIndex; + elapsed = timer->getUpdateTime() - start; + } + if (finished) + { + m_seeState = 3; + m_seeIndex = 0; + } + if (slice < timer->getUpdateTime() - start) + return; + timer->getUpdateTime(); +} + +// ELF 0x19BE60 (1528 bytes). Nothing is heard within 1.5 s of the bot's own last shot. With +// equipment, the heard list (+76) is worked through once, front to back, within the slice: each +// record is popped; one whose information is gone or has neither mobile nor armament leaves the +// heard set (+64) and loses SENSE_HEARD (and is deleted unless it is also seen); a heard one +// refreshes its primary object and the primary's secondary objects (setTime(now, max(s, 0.1))); +// one unheard for more than 30 s is dropped the same way; the rest are requeued at the back. +void BotSenses::updateHearing(const double& slice) +{ + const IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); + const double now = timer->getGameTime(); + if (!(now - m_bot->getTimeOfLastFire() >= 1.5)) + return; + const double start = timer->getUpdateTime(); + const double budget = slice; + if (!informationManager->getInformation(m_bot->getCurrentEquipment())) + return; + const unsigned int count = static_cast(m_hearingMemCheckQueue.size()); + const int side = m_bot->getSide(); + for (unsigned int i = 0; i < count && timer->getUpdateTime() < static_cast(start + budget); ++i) + { + SensedObject* const object = m_hearingMemCheckQueue.front().second; + m_hearingMemCheckQueue.erase(m_hearingMemCheckQueue.begin()); + const unsigned int handle = object->m_handle; + Information* information = informationManager->getInformation(handle); + if (!information || (!information->getMobile() && !information->getArmament())) + { + m_hearingMemHelperSet.erase(handle); + const unsigned int flags = object->m_flags; + object->m_flags = flags & ~SensedObject::SENSE_HEARD; + if (!(flags & SensedObject::SENSE_SEEN)) + { + m_sensedObjects.erase(object->m_handle); + delete object; + } + continue; + } + const float strength = hear(handle, information); + if (0.0f < strength) + { + object->m_flags |= SensedObject::SENSE_HEARD_NOW; + object->m_lastSense = SensedObject::SENSE_HEARD_NOW; + object->m_lastSensedTime = now; + information = informationManager->getInformation(information->getPrimaryObject(side)); + float weight = 0.1f; + if (0.1f <= strength) + weight = strength; + if (information->setTime(timer->getGameTime(), weight)) + information->getAIObject()->addInformationToGrid(side); + int iterator = -1; + Information* secondary = + informationManager->getInformation(information->getFirstSecondaryObject(iterator, side)); + while (secondary) + { + float secondaryWeight = strength; + if (strength < 0.1f) + secondaryWeight = 0.1f; + secondary->setTime(timer->getGameTime(), secondaryWeight); + secondary = informationManager->getInformation(information->getSecondaryObject(iterator, side)); + } + } + else if (!(object->m_flags & SensedObject::SENSE_HEARD_NOW)) + { + if (30.0 < now - object->m_lastSensedTime) + { + m_hearingMemHelperSet.erase(handle); + const unsigned int flags = object->m_flags; + object->m_flags = flags & ~SensedObject::SENSE_HEARD; + if (!(flags & SensedObject::SENSE_SEEN)) + { + m_sensedObjects.erase(object->m_handle); + delete object; + } + continue; + } + } + else + { + object->m_flags &= ~SensedObject::SENSE_HEARD_NOW; + object->m_lastSensedTime = now; + } + m_hearingMemCheckQueue.push_back(TimedObject(now, object)); + } +} + +// ELF 0x19C460 (1232 bytes). The incoming-fire strengths (+88 over the six strength types, +92 +// against the equipment's own strength type), each shot weighted x10 when direct, over the fire +// list (+84). Shots younger than min(60 / max(n, 1), 5) s are recorded per shooter in the attacker +// map (+100) when newer than the one there; an older duplicate, or an old shot the map does not +// hold, is deleted. Then the attacker strength (+96) over the map, whose entries older than +// max(30 / max(size, 1), 15) s are erased (not deleted: the list owns them). The slice is unused. +void BotSenses::updateFireObjects(const double&) +{ + m_fireTotalStrength = 0.0f; + m_fireTotalStrengthAgainstSelf = 0.0f; + Information* const equipment = informationManager->getInformation(m_bot->getCurrentEquipment()); + IPIPhysical* physical = 0; + if (equipment) + physical = equipment->getPhysical(); + int ownStrengthType = 0; + if (physical) + ownStrengthType = physical->getStrengthType(); + const IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); + + float divisor = static_cast(static_cast(m_list84.size())); + if (divisor < 1.0f) + divisor = 1.0f; + float window = 60.0f / divisor; + if (5.0f < 60.0f / divisor) + window = 5.0f; + for (std::list::iterator it = m_list84.begin(); it != m_list84.end(); ) + { + FireObject* const fire = it->first; + float weight = 10.0f; + if (!fire->isDirect()) + weight = 1.0f; + for (int type = 0; type < 6; ++type) + m_fireTotalStrength = fire->getBattleStrength(type) * weight + m_fireTotalStrength; + if (physical) + m_fireTotalStrengthAgainstSelf = + fire->getBattleStrength(ownStrengthType) * weight + m_fireTotalStrengthAgainstSelf; + if (timer->getGameTime() - fire->getTime() <= static_cast(window)) + { + std::pair::iterator, bool> inserted = + m_map100.insert(std::make_pair(it->second, fire)); + if (inserted.second || inserted.first->second->getTime() < fire->getTime()) + { + inserted.first->second = fire; + } + else if (inserted.first->second != fire) + { + delete fire; + it = m_list84.erase(it); + continue; + } + ++it; + } + else + { + const std::map::iterator held = m_map100.find(it->second); + if (held != m_map100.end() && held->second == fire) + { + ++it; + continue; + } + delete fire; + it = m_list84.erase(it); + } + } + + m_attackerStrength = 0.0f; + float attackers = 1.0f; + if (1.0f <= static_cast(static_cast(m_map100.size()))) + attackers = static_cast(static_cast(m_map100.size())); + float memory = 30.0f / attackers; + if (30.0f / attackers <= 15.0f) + memory = 15.0f; + const double now = timer->getGameTime(); + for (std::map::iterator it = m_map100.begin(); it != m_map100.end(); ) + { + if (static_cast(memory) <= now - it->second->getTime()) + { + m_map100.erase(it++); + } + else + { + m_attackerStrength = it->second->getBattleStrength(ownStrengthType) + m_attackerStrength; + ++it; + } + } +} + +// ELF 0x19C930: `fldl 0x20(fire)` when found, else -1000.0f widened. +bool BotSenses::isAttacking(unsigned int handle, double& time) const +{ + const std::map::const_iterator it = m_map100.find(handle); + const bool found = it != m_map100.end(); + if (found) + time = it->second->getTime(); + else + time = -1000.0f; + return found; +} + +// ELF 0x19C9A0. The shot goes to the back of the fire list. When the shooter's information is of +// another side, its primary object is reported as seen (zero position, part -1, not direct, +// flag40 off) and the shooter's seen record - looked up by the shooter's handle, not the primary's +// - gets the attack time (+0x3C). +void BotSenses::event_projectile(FireObject* fire, unsigned int handle) +{ + m_list84.push_back(FireEntry(fire, handle)); + Information* information = informationManager->getInformation(handle); + if (!information) + return; + if (information->getSide() == m_bot->getSide()) + return; + const unsigned int primaryHandle = information->getPrimaryObject(m_bot->getSide()); + information = informationManager->getInformation(primaryHandle); + if (!information) + return; + Vec3 zero; + zero.x = 0.0f; + zero.y = 0.0f; + zero.z = 0.0f; + event_seenObject(primaryHandle, zero, static_cast(-1), information, false, true); + const std::map::iterator seen = m_map44.find(handle); + if (seen != m_map44.end()) + seen->second->second->m_lastAttackTime = + static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); +} + +// ELF 0x19CB60 (1803 bytes). The information's time is refreshed (setTime(now); a true result puts +// its object into the side's grid). A handle not in the seen list gets a record (a new one is +// SENSE_INDIRECT with +0x14 = now) that becomes SENSE_SEEN with both positions refreshed; a direct +// sighting clears INDIRECT and, once per record, books a contact (reporting a new enemy first when +// the information had none); an indirect one tells the sensing agent. It then joins the back of +// the seen list and the handle -> list-position map. A handle already in the list is only moved to +// the back when it was INDIRECT and this sighting is direct. +void BotSenses::event_seenObject(unsigned int handle, const Vec3& position, unsigned int part, + Information* information, bool direct, bool notFlag40) +{ + const int side = m_bot->getSide(); + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (information->setTime(now)) + information->getAIObject()->addInformationToGrid(side); + + const std::map::iterator listed = m_map44.find(handle); + if (listed == m_map44.end()) + { + SensedObject* object; + const SensedObjectMap::iterator known = m_sensedObjects.find(handle); + if (known == m_sensedObjects.end()) + { + object = checkPointer(new SensedObject(handle, true, information->getSide() != 0)); + object->m_flags |= SensedObject::SENSE_INDIRECT; + object->m_lastSense = SensedObject::SENSE_INDIRECT; + object->m_firstSeenTime = now; + m_sensedObjects.insert(std::make_pair(handle, object)); + } + else + { + object = known->second; + } + object->m_flags |= SensedObject::SENSE_SEEN; + object->m_lastSense = SensedObject::SENSE_SEEN; + object->m_lastPosition = information->getPosition(); + object->m_lastPositionTime = now; + object->m_lastSeenPosition = information->getPosition(); + object->m_lastSeenTime = now; + if (direct) + { + object->m_flags &= ~SensedObject::SENSE_INDIRECT; + if (!object->m_hasContact) + { + if (!information->hasContact()) + m_bot->getCommunicationAgent()->setSeenNewEnemy(information); + information->addContact(); + object->m_hasContact = true; + } + } + else + { + m_bot->getSensingAgent()->setSensedNewObject(); + } + if (!notFlag40) + { + object->m_flags |= SensedObject::SENSE_FLAG40; + object->m_lastSense = SensedObject::SENSE_FLAG40; + } + object->m_lastSensedTime = now; + object->m_seenPosition = position; + object->m_seenPart = part; + m_list56.push_back(TimedObject(now, object)); + m_map44[handle] = --m_list56.end(); + return; + } + + const TimedList::iterator entry = listed->second; + SensedObject* const object = entry->second; + if ((object->m_flags & SensedObject::SENSE_INDIRECT) && direct) + { + if (m_cursor60 == entry) + ++m_cursor60; + m_list56.erase(entry); + if (!object->m_hasContact) + { + information->addContact(); + object->m_hasContact = true; + } + object->m_seenPosition = position; + object->m_seenPart = part; + object->m_lastPosition = information->getPosition(); + object->m_lastPositionTime = now; + object->m_lastSeenPosition = information->getPosition(); + object->m_flags &= ~SensedObject::SENSE_INDIRECT; + object->m_lastSeenTime = now; + m_list56.push_back(TimedObject(now, object)); + listed->second = --m_list56.end(); + } +} + +// ELF 0x19D270 (1632 bytes). Needs the bot's equipment information and 1.5 s since its own last +// shot; the bot does not hear its own equipment, its own side, or - from a non-soldier equipment - +// a soldier (type flag 0x200000). When hear() > 0: a handle already in the heard set (+64) only +// refreshes its record and the primary object's time; a new one books the information into the +// side's grid, gets (or reuses) a record, refreshes the primary (grid on a true setTime) and +// joins the back of the heard list. A brand-new record tells the sensing agent. +void BotSenses::event_heardObject(unsigned int handle) +{ + Information* const equipment = informationManager->getInformation(m_bot->getCurrentEquipment()); + if (!equipment) + return; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (!(1.5 <= now - m_bot->getTimeOfLastFire())) + return; + if (handle == m_bot->getCurrentEquipment()) + return; + Information* const information = informationManager->getInformation(handle); + if (!information) + return; + if (information->getSide() == m_bot->getSide()) + return; + if (!equipment->isOfType(ITSoldier) && information->isOfType(ITSoldier)) + return; + const float strength = hear(handle, information); + if (!(0.0f < strength)) + return; + const int side = m_bot->getSide(); + const std::pair::iterator, bool> inserted = m_hearingMemHelperSet.insert(handle); + if (!inserted.second) + { + // The image does not check the find result. + SensedObject* const object = m_sensedObjects.find(handle)->second; + object->m_flags |= SensedObject::SENSE_HEARD; + object->m_lastSense = SensedObject::SENSE_HEARD; + object->m_lastPosition = information->getPosition(); + object->m_lastPositionTime = now; + object->m_lastSensedTime = now; + Information* const primary = informationManager->getInformation(information->getPrimaryObject(side)); + float weight = 0.1f; + if (0.1f <= strength) + weight = strength; + primary->setTime(now, weight); + return; + } + + const SensedObjectMap::iterator known = m_sensedObjects.find(handle); + information->getAIObject()->addInformationToGrid(information->getSide()); + SensedObject* object; + if (known == m_sensedObjects.end()) + { + object = checkPointer(new SensedObject(handle, false, information->getSide() != 0)); + m_sensedObjects.insert(std::make_pair(handle, object)); + m_bot->getSensingAgent()->setSensedNewObject(); + } + else + { + object = known->second; + object->m_flags |= SensedObject::SENSE_HEARD; + object->m_lastSense = SensedObject::SENSE_HEARD; + } + object->m_handle = handle; + object->m_flags |= SensedObject::SENSE_HEARD; + object->m_lastSense = SensedObject::SENSE_HEARD; + object->m_lastSensedTime = now; + object->m_lastPosition = information->getPosition(); + object->m_lastPositionTime = now; + Information* const primary = informationManager->getInformation(information->getPrimaryObject(side)); + float weight = 0.1f; + if (0.1f <= strength) + weight = strength; + if (primary->setTime(now, weight)) + primary->getAIObject()->addInformationToGrid(side); + m_hearingMemCheckQueue.push_back(TimedObject(now, object)); +} + +// ELF 0x19D8F0 (1152 bytes). Zero unless the bot has equipment, 1.5 s have passed since its own +// last shot, the object is alive (its physical plug-in's and its engine object's health > 0) and it +// has a mobile or an armament plug-in. The audible radius is the larger of the object's mobile +// sound radius (zeroed for a soldier in pose 2 or 3) and, within 5 s of a shot, its weapon's sound +// radius. Within that radius the hearing probability P interpolates the listener's mobile +// min..max by distance / the object's maximum sound radius (1 without a listener mobile); the +// object is heard (P returned) when a uniform draw exceeds (1 - max(speed / maxSpeed, 1)) * P. +// As in the image, the object's mobile is used for the maximum radius without a null check. +float BotSenses::hear(unsigned int, Information* information) +{ + Information* const equipment = informationManager->getInformation(m_bot->getCurrentEquipment()); + if (!equipment) + return 0.0f; + const IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); + const double now = timer->getGameTime(); + if (1.5 > now - m_bot->getTimeOfLastFire()) + return 0.0f; + if (IPIPhysical* const physical = information->getPhysical()) + { + if (0.0f >= physical->getHealth()) + return 0.0f; + } + IPIMobile* const mobile = information->getMobile(); + IPIArmament* const armament = information->getArmament(); + if (!armament && !mobile) + return 0.0f; + if (IAIObjectPhysical* const objectPhysical = information->getAIObject()->getPhysical()) + { + if (0.0f >= objectPhysical->getHealth()) + return 0.0f; + } + IPIMobile* const listener = equipment->getMobile(); + float mobileRadius; + if (mobile) + mobileRadius = mobile->getSoundSphereRadius(); + else + mobileRadius = 0.0f; + float weaponRadius = 0.0f; + if (armament) + { + if (WeaponInfo* const weapon = armament->getLastFiredWeapon()) + { + if (5.0 > now - weapon->getTimeOfFiring()) + weaponRadius = weapon->getSoundSphereRadius(); + } + } + if (information->isOfType(ITSoldier)) + { + const int pose = information->getSoldierPose(); + if (pose != 1 && !(pose < 1)) + { + if (pose <= 3) + mobileRadius = 0.0f; + } + } + float radius = weaponRadius; + if (weaponRadius <= mobileRadius) + radius = mobileRadius; + float moving; + if (listener) + { + moving = listener->getSpeedMagnitude() / listener->getMaxSpeed(); + if (moving <= 1.0f) + moving = 1.0f; + } + else + { + moving = 0.0f; + } + const Vec3& target = information->getAIObject()->getPosition(); + const Vec3& own = equipment->getPosition(); + const float dx = own.x - target.x; + const float dy = own.y - target.y; + const float dz = own.z - target.z; + const float distance = std::sqrt(dx * dx + dy * dy + dz * dz); + if (distance > radius) + return 0.0f; + const float fraction = distance / mobile->getSoundSphereRadiusMax(); + float probability; + if (listener) + probability = (1.0f - fraction) * listener->getHearingProbabilityMin() + + listener->getHearingProbabilityMax() * fraction; + else + probability = 1.0f; + const float threshold = (1.0f - moving) * probability; + const float draw = AIRandom::m_instance->nextFloat(); + return draw > threshold ? probability : 0.0f; +} + +// ELF 0x19DD70 (480 bytes). The information's primary object is looked up first (its contact is +// what a record releases). A listed handle leaves the seen list (the cursor at +60 resets to the +// end when it points at this record) and the position map, drops its contact and SENSE_SEEN, and +// is deleted unless it is also heard. +void BotSenses::forgetObject(unsigned int handle) +{ + Information* const information = informationManager->getInformation(handle); + if (!information) + return; + Information* const primary = + informationManager->getInformation(information->getPrimaryObject(m_bot->getSide())); + const std::map::iterator listed = m_map44.find(handle); + if (listed == m_map44.end()) + return; + SensedObject* const object = listed->second->second; + // [CHOSEN, not recovered] The image reads the cursor's element even at end() (its sentinel is a + // full node in that library); the end test keeps a native list's sentinel unread. + if (m_cursor60 != m_list56.end() && m_cursor60->second == object) + m_cursor60 = m_list56.end(); + m_list56.erase(listed->second); + m_map44.erase(listed); + if (object->m_hasContact) + { + primary->removeContact(); + object->m_hasContact = false; + } + const unsigned int flags = object->m_flags; + object->m_flags = flags & ~SensedObject::SENSE_SEEN; + if (!(flags & SensedObject::SENSE_HEARD)) + { + m_sensedObjects.erase(handle); + delete object; + } +} + +// ELF 0x19DF50 (352 bytes). `information`'s primary object's transformation (row 2 forward, +// row 3 position) is read before `object` is tested; `object`'s information for that side must +// be a primary one, within 200 m (squared < 40000) and in front (positive dot with forward). +bool BotSenses::isCloseAndInFront(Information* information, IAIObject* object) const +{ + Information* const primary = + informationManager->getInformation(information->getPrimaryObject(m_bot->getSide())); + if (!primary) + return false; + const Mat4& transformation = primary->getTransformation(); + if (!object) + return false; + Information* const other = informationManager->getInformation(object->getInformation(information->getSide())); + if (!other || !other->isPrimary()) + return false; + const Vec3& position = object->getPosition(); + const float dx = position.x - transformation.m[12]; + const float dy = position.y - transformation.m[13]; + const float dz = position.z - transformation.m[14]; + return dx * dx + dy * dy + dz * dz < 40000.0f + && 0.0f < dx * transformation.m[8] + dy * transformation.m[9] + dz * transformation.m[10]; +} + +namespace { + +// ELF 0x197650 (448 bytes). The centre of a soldier for the sight ray: its position plus a pose +// offset (lying: y - 0.7; standing and crouching: none). Any other pose logs "Unknown pose" +// (DebugTypeError, BotSenses.cpp line 207) and leaves `offset` as the caller set it. +void soldierHack_getSoldierCentre(Vec3& centre, Vec3& offset, Information* information) +{ + if (information->getSoldierPose() == SPLying) + { + offset.x = 0.0f; + offset.y = -0.7f; + offset.z = 0.0f; + } + else if (information->getSoldierPose() == SPCrouching || information->getSoldierPose() == SPStanding) + { + offset.x = 0.0f; + offset.y = 0.0f; + offset.z = 0.0f; + } + else + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIBot/BotSenses.cpp", 207, "") << "Unknown pose"; + } + const Vec3& position = information->getPosition(); + centre.x = offset.x + position.x; + centre.y = offset.y + position.y; + centre.z = offset.z + position.z; +} + +// The pose probe of updateSeeing (four inlined copies in the image): while the bot is changing +// pose (requested pose 2 or 3 differs from the equipment's current one), a second ray from where +// the eye will be tells the bot whether its firing target stays visible after the change. +// Crouching (2): y - 0.53 from standing, otherwise y + 0.38; lying (3): y - 0.91 from standing, +// otherwise y - 0.38. Reported through Bot +0x19C setPoseStatus(pose, handle, visible, hit). +void probePose(BotMain* bot, IAIObjectEnvironment* environment, const Vec3& eye, const Vec3& point, + const std::vector& ignore, bool activeBot, float width, SoldierPose pose, + int requested, unsigned int handle) +{ + Vec3 probe = eye; + if (requested == 2) + probe.y = pose == SPStanding ? eye.y - 0.53f : eye.y + 0.38f; + else if (requested == 3) + probe.y = eye.y - (pose == SPStanding ? 0.91f : 0.38f); + else + return; + bool hit; + const bool blocked = environment->collideLineWithWorld(probe, point, ignore, activeBot, width, true, hit); + bot->setPoseStatus(requested, handle, !blocked, hit); +} + +} // namespace + +// ELF 0x19A0F0 (7533 bytes). Reads the render flag (IBotManager +0x78), the update time and the +// game time, then works through the seen list (+56) from the cursor (+60, wrapping to the front) +// until the cursor is back where it started, the slice is spent or the list is empty. Per record: +// * dropped (seen bit cleared, deleted unless heard) when its information is gone, has no +// object, is not a root object, is on the bot's side or side 0, or is physically dead; +// * "in view" for a primary object or a soldier when it attacked the bot within 5 s, or the bot +// is a soldier and it is within 2r + 3 * own radius, or it is inside the frustum and within its +// unit's cull distance; or, with vehicle sight (equipment flag 0x10 / 0x20), close and in front; +// * in view, a ray (0.75) from the eye (camera row 3, y - 0.1) ignoring {own primary, target, +// rider}: an active bot target is sensed at its centre (soldier) or position; otherwise the +// stored sense point (+4) through the object matrix (non-soldier) or the stored body part +// (soldier, IAIObjectEnvironment +0x58); failing that, a fresh pick (+0x54 / +0x50); +// * visible: setTime, a contact booked when it was indirect, positions and times refreshed, +// flag 0x40 from the ray's hit output, and every other bot riding in the bot's primary object +// and its secondaries told (event_seenObject, indirect); +// * not visible: INDIRECT set (+0x14 = now) once; later the contact is released after 2 s, and +// the record forgotten after 60 s, or when the target is not primary, or after 5 s when the +// bot's equipment has no mobile, can engage it (anti-aircraft against flag 0x10), or the bot +// is going for a flag (Bot +0x27C). +// Kept records move to the back of the list (time = now) and re-register in the map (+44). +void BotSenses::updateSeeing(const double& slice) +{ + IBotManager* const botManager = IBotManager::instance; + IAIObjectEnvironment* const environment = + static_cast(CommonSingletonServer::m_iaiObjectEnvironment); + const bool render = botManager->getRenderBotSensing(); + AIRenderUtil* const renderUtil = render ? AIRenderUtil::m_instance : 0; + const IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); + const double start = timer->getUpdateTime(); + const double now = timer->getGameTime(); + if (m_list56.empty()) + return; + + // As in the image, the equipment information is used without a null check. + Information* const equipment = informationManager->getInformation(m_bot->getCurrentEquipment()); + const bool ownSoldier = equipment->isOfType(ITSoldier); + const float ownRadius3 = equipment->getPhysical()->getRadius() * 3.0f; + std::vector ignore; + ignore.push_back(equipment->getAIObject()->getPrimaryObject()); + ignore.push_back(0); + ignore.push_back(0); + const Mat4& camera = *static_cast(m_bot->getPlayer()->getCameraTransformation()); + Vec3 eye; + eye.x = camera.m[12]; + eye.y = camera.m[13] - 0.1f; + eye.z = camera.m[14]; + + // [CHOSEN, not recovered] The image stops when the cursor reaches the node it started on. A + // kept record is erased and re-inserted at the back, and the pool allocator hands the freed + // node straight back, so the start node survives that move; splice keeps the node the same + // way. When the start record is forgotten its node is gone, and the image's test then only + // matches if the pool reuses the node later; here the start is dropped and the slice or an + // empty list ends the pass. + const TimedList::iterator stop = m_cursor60; + bool stopValid = true; + double elapsed; + do + { + if (m_cursor60 == m_list56.end()) + m_cursor60 = m_list56.begin(); + const TimedList::iterator current = m_cursor60++; + SensedObject* const object = current->second; + const unsigned int handle = object->m_handle; + Information* const information = informationManager->getInformation(handle); + + bool drop = !information || !information->getAIObject() || !information->isRootObject() + || information->getSide() == m_bot->getSide() || information->getSide() == 0 + || (information->getPhysical() && information->getPhysical()->getHealth() <= 0.0f); + bool forget = false; + if (!drop) + { + IAIObject* const target = information->getAIObject(); + const bool primary = information->isPrimary(); + const bool soldier = information->isOfType(ITSoldier); + const float radius = target->getBoundingRadius(); + const Vec3& position = target->getPosition(); + const float dx = position.x - eye.x; + const float dy = position.y - eye.y; + const float dz = position.z - eye.z; + const float distSq = dz * dz + dy * dy + dx * dx; + bool inView = false; + if (primary || soldier) + { + inView = true; + if (5.0 < now - object->m_lastAttackTime) + { + const float close = radius + radius + ownRadius3; + if (!ownSoldier || close * close < distSq) + { + if (!m_frustum->inside(target->getPosition(), radius) + || (information->getUnit() && information->getUnit()->getCullDistanceSqr() < distSq)) + inView = false; + } + } + } + const bool vehicleSight = equipment->isOfType(ITAir) || equipment->isOfType(ITHelicopter); + const bool consider = inView || (vehicleSight && isCloseAndInFront(equipment, target)); + bool visible = consider; + Vec3 point; + point.x = 0.0f; + point.y = 0.0f; + point.z = 0.0f; + Vec3 sense = point; + Bot* const targetBot = IBotManager::instance->getBot(target); + bool activeBot = false; + if (targetBot) + activeBot = 0 < static_cast(targetBot->getLodLevel()); + unsigned int part = static_cast(-1); + bool hit = false; + + if (consider) + { + ignore[1] = target; + // The rider slot keeps the previous record's object when none is found here. + if (IPIUnit* const unit = information->getUnit()) + { + if (!soldier) + { + if (unit->hasExposedSoldier()) + { + if (Information* const occupier = + informationManager->getInformation(unit->getOccupier(m_bot->getSide()))) + ignore[2] = occupier->getAIObject(); + } + } + else if (Information* const occupied = + informationManager->getInformation(unit->getOccupiedObject(m_bot->getSide()))) + { + if (occupied->getUnit() && occupied->getUnit()->hasExposedSoldier()) + ignore[2] = occupied->getAIObject(); + } + } + + // First ray: an active bot target at its centre (soldier) or any target at its + // position (non-soldier); a soldier that is not an active bot gets no first ray. + if (soldier) + { + if (!activeBot) + { + visible = false; + } + else + { + soldierHack_getSoldierCentre(point, sense, information); + visible = !environment->collideLineWithWorld(eye, point, ignore, activeBot, 0.75f, true, hit); + const SoldierPose pose = equipment->getSoldierPose(); + const int requested = m_bot->getRequestedSolderPose(); + if (visible && pose != requested && pose != SPSwimming + && m_bot->getFiringTarget() == handle) + probePose(m_bot, environment, eye, point, ignore, activeBot, 0.75f, pose, requested, handle); + } + } + else + { + sense.x = 0.0f; + sense.y = 0.0f; + sense.z = 0.0f; + point = target->getPosition(); + visible = !environment->collideLineWithWorld(eye, point, ignore, activeBot, 0.75f, true, hit); + } + + // Second ray (not for an active bot): the stored sense point. + if (!visible && !activeBot) + { + if (!soldier) + { + sense = object->m_seenPosition; + const Mat4& matrix = target->getTransformation(); + point.x = matrix.m[8] * sense.z + matrix.m[0] * sense.x + matrix.m[4] * sense.y + matrix.m[12]; + point.y = matrix.m[1] * sense.x + matrix.m[5] * sense.y + matrix.m[9] * sense.z + matrix.m[13]; + point.z = sense.y * matrix.m[6] + matrix.m[2] * sense.x + sense.z * matrix.m[10] + matrix.m[14]; + visible = !environment->collideLineWithWorld(eye, point, ignore, false, 0.75f, true, hit); + } + else + { + const bool sensed = environment->getSoldierSensePosition(point, sense, target, object->m_seenPart); + part = object->m_seenPart; + if (sensed) + { + visible = !environment->collideLineWithWorld(eye, point, ignore, false, 0.75f, true, hit); + const SoldierPose pose = equipment->getSoldierPose(); + const int requested = m_bot->getRequestedSolderPose(); + if (visible && pose != requested && m_bot->getFiringTarget() == handle) + probePose(m_bot, environment, eye, point, ignore, false, 0.8f, pose, requested, handle); + } + } + } + + // Third ray (not for an active bot): a fresh sense point. + if (!visible && !activeBot) + { + if (soldier) + { + environment->pickSoldierRandomSensePosition(point, sense, target, part); + object->m_seenPart = part; + } + else + { + environment->pickRandomSensePosition(point, sense, eye, target); + } + visible = !environment->collideLineWithWorld(eye, point, ignore, false, 0.75f, true, hit); + const SoldierPose pose = equipment->getSoldierPose(); + const int requested = m_bot->getRequestedSolderPose(); + if (visible && requested != pose && m_bot->getFiringTarget() == handle) + probePose(m_bot, environment, eye, point, ignore, false, 0.8f, pose, requested, handle); + } + } + + if (visible) + { + information->setTime(now); + if (object->m_flags & SensedObject::SENSE_INDIRECT) + { + if (!object->m_hasContact) + { + information->addContact(); + object->m_hasContact = true; + } + object->m_flags &= ~SensedObject::SENSE_INDIRECT; + } + object->m_lastPosition = point; + object->m_lastPositionTime = now; + object->m_lastSeenPosition = point; + object->m_lastSeenTime = now; + object->m_seenPosition = sense; + if (!hit) + { + object->m_flags |= SensedObject::SENSE_FLAG40; + object->m_lastSense = SensedObject::SENSE_FLAG40; + } + else + { + object->m_flags &= ~SensedObject::SENSE_FLAG40; + } + + // Every other bot riding in this bot's primary object or its secondaries. + Information* self = equipment; + if (!equipment->isPrimary()) + self = informationManager->getInformation(equipment->getPrimaryObject(m_bot->getSide())); + const auto tellRider = [&](Bot* rider) + { + if (!rider || rider == m_bot) + return; + rider->getSensingAgent()->getSenses()->event_seenObject( + handle, object->m_seenPosition, part, information, false, hit); + if (botManager->getRenderBotSensing() && AIRenderUtil::m_instance) + AIRenderUtil::m_instance->addSensingLine(eye, sense, m_bot->getPlayer()->getSide(), visible); + }; + tellRider(IBotManager::instance->getBot(self->getAIObject())); + int iterator = -1; + for (Information* secondary = informationManager->getInformation( + self->getFirstSecondaryObject(iterator, m_bot->getSide())); + secondary; + secondary = informationManager->getInformation(self->getSecondaryObject(iterator, m_bot->getSide()))) + tellRider(IBotManager::instance->getBot(secondary->getAIObject())); + } + else if (!(object->m_flags & SensedObject::SENSE_INDIRECT)) + { + object->m_lastSense = SensedObject::SENSE_INDIRECT; + object->m_flags |= SensedObject::SENSE_INDIRECT; + object->m_firstSeenTime = now; // here: when it went out of sight + } + else + { + const double unseen = now - object->m_firstSeenTime; + Information* const lost = informationManager->getInformation(handle); + if (2.0 < unseen && object->m_hasContact) + { + object->m_hasContact = false; + lost->removeContact(); + int iterator = -1; + for (Information* secondary = informationManager->getInformation( + lost->getFirstSecondaryObject(iterator, m_bot->getSide())); + secondary; + secondary = informationManager->getInformation(lost->getSecondaryObject(iterator, m_bot->getSide()))) + secondary->removeContact(); + } + // As in the image, the equipment information is used without a null check. + Information* const own = informationManager->getInformation(m_bot->getCurrentEquipment()); + IPIArmament* const armament = own->getArmament(); + const bool canEngage = armament && lost->isOfType(ITAir) && 0 < armament->isAntiAircraft(); + if (60.0 < unseen || !primary || (!own->getMobile() && 5.0 < unseen) + || (canEngage && 5.0 < unseen) || (m_bot->getIsGoingForFlag() && 5.0 < unseen)) + forget = true; + } + if (render) + renderUtil->addSensingLine(eye, point, m_bot->getSide(), visible); + } + + if (drop || forget) + { + if (current == stop) + stopValid = false; + m_list56.erase(current); + m_map44.erase(handle); + const unsigned int flags = object->m_flags; + object->m_flags = flags & ~SensedObject::SENSE_SEEN; + if (!(flags & SensedObject::SENSE_HEARD)) + { + m_sensedObjects.erase(handle); + delete object; + } + } + else + { + current->first = now; + m_list56.splice(m_list56.end(), m_list56, current); + m_map44[handle] = --m_list56.end(); + } + elapsed = timer->getUpdateTime() - start; + } while ((!stopValid || m_cursor60 != stop) && elapsed < slice && !m_list56.empty()); +} } // namespace ai } // namespace hfe diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.h b/Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.h index dfb256b7d..894d289a0 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.h @@ -16,9 +16,9 @@ namespace hfe { namespace ai { class BotMain; -// The two things a bot's perception owns and deletes. Both are [FRONTIER] classes - `reset` and -// the destructor delete them through an inlined, non-virtual destructor, so neither can be written -// until the class itself is recovered. See the reset block in the .cpp. +class IAIObject; +class Information; +// The two things a bot's perception owns and deletes (AIBot/SensedObject.h, AIKnowledge/FireObject.h). class FireObject; class SensedObject; @@ -28,46 +28,85 @@ class BotSenses // (`operator new(0x94)` in SensingAgent's constructor). explicit BotSenses(BotMain* owner); ~BotSenses(); - void reset(); // - (two arms frontier) + void reset(); // ELF 0x199D40 // attested: an 11-byte body that returns `this + 112`. const std::map& getSensedObjects() const { return m_sensedObjects; } + typedef std::pair FireEntry; + + // ELF 0x198420 (6421 bytes). + void see(const double& slice); + // ELF 0x19a040: hearing, fire objects, then seeing with the remaining slice. + void updateSensing(const double& slice); + void updateHearing(const double& slice); // ELF 0x19be60 + void updateFireObjects(const double& slice); // ELF 0x19c460 + void updateSeeing(const double& slice); // ELF 0x19a0f0 + // ELF 0x19d8a0: the record for a handle, or null. + SensedObject* getSensedObjectFromHandle(unsigned int handle) const; + // ELF 0x19C930: the attacker map's fire time for a shooter, else -1000.0. + bool isAttacking(unsigned int handle, double& time) const; + // ELF 0x19C9A0: queue a reported shot; an enemy shooter's primary object counts as seen. + void event_projectile(FireObject* fire, unsigned int handle); + // ELF 0x19CB60: a seen object (handle, seen position, seen part, information, direct, flag40 off). + void event_seenObject(unsigned int handle, const Vec3& position, unsigned int part, + Information* information, bool direct, bool notFlag40); + // ELF 0x19D270: an engine sound event for a handle. + void event_heardObject(unsigned int handle); + // ELF 0x19D8F0: the hearing probability of an object, or 0 when not heard. + float hear(unsigned int handle, Information* information); + // ELF 0x19DD70: drop a handle from the seen list. + void forgetObject(unsigned int handle); + // ELF 0x19DF50: `object`'s primary information is within 200 m and in front of `information`'s + // primary object. + bool isCloseAndInFront(Information* information, IAIObject* object) const; + // ELF 0x18b0c0..0x18b120 (BotMain's forwarders read these fields inline). + std::list* getIncommingFire() { return &m_list84; } + float getIncommingFireTotalStrength() const { return m_fireTotalStrength; } + float getIncommingFireTotalStrengthAgainstSelf() const { return m_fireTotalStrengthAgainstSelf; } + float getAttackerStrength() const { return m_attackerStrength; } + private: + // BotMain::getAttackers (ELF 0x18B180) returns the map at +100 inline. + friend class BotMain; typedef std::pair TimedObject; // a time and a thing typedef std::list TimedList; - typedef std::pair FireEntry; typedef std::map SensedObjectMap; /* 0 */ BotMain* m_bot; // the ctor argument, and the first store /* 4 */ Frustum* m_frustum; // new(0x1E8) - . See the header block. - /* 8 */ char m_gap8[4]; // [UNRESOLVED] - never written, by anything read so far - /* 12 */ double m_double12; // = -1000000.0 a fifth kind of sentinel + // see (ELF 0x198420): 1 when the equipment is ITObstructedView (bit 22, AIDLL_r enum switch 0x100D3010); the + // row of tweak_frustumUpdateAngle used for the frustum. + /* 8 */ int m_viewMode; + /* 12 */ double m_collectTime; // = -1000000.0; see: the game time of the last candidate scan // the distance sort buffer - what `InfoDistPred` and `partial_sort` operate on. Held as a // member rather than a local, so the seeing path does not reallocate every tick. /* 20 */ std::vector > m_sortBuffer; - /* 32 */ int m_int32; // ctor: 0, reset: 0 - /* 36 */ int m_int36; // ctor: 0, reset: 0 - /* 40 */ int m_int40; // ctor: 0, reset: 0 + /* 32 */ int m_frustumStep; // ctor/reset 0; see cycles it 0 -> 1 -> 2 -> 0 + /* 36 */ int m_seeState; // ctor/reset 0; see: 0 scan, 1 sort, 2 test, 3 done + /* 40 */ int m_seeIndex; // ctor/reset 0; see: the next sort-buffer entry to test // handle -> position in the list at +56. See the header block. /* 44 */ std::map m_map44; /* 56 */ TimedList m_list56; // A cursor into the list above, seeded to end by the constructor's last statement. /* 60 */ TimedList::iterator m_cursor60; - /* 64 */ std::set m_set64; - /* 76 */ TimedList m_list76; + /* 64 */ std::set m_hearingMemHelperSet; // name: AIDLL_r assert 0x101D6BF0 (PE +0x50) + /* 76 */ TimedList m_hearingMemCheckQueue; // name: AIDLL_r assert 0x101D6BF0 (PE +0x5C) // A cursor into the list above - and unlike +60 the constructor leaves it default-constructed. // Only `reset` makes it valid. See the header block. /* 80 */ TimedList::iterator m_cursor80; /* 84 */ std::list m_list84; - /* 88 */ int m_int88; // ctor: 0, reset: 0 - /* 92 */ int m_int92; // ctor: 0, reset: 0 - /* 96 */ char m_gap96[4]; // [UNRESOLVED] - never written + // Floats: BotMain::getIncommingFireTotalStrength (ELF 0x18b0e0) and + // ...AgainstSelf (0x18b100) return `flds 0x58/0x5c(senses)`, getAttackerStrength (0x18b120) + // `flds 0x60`. The zero stores of ctor/reset are the same bits. + /* 88 */ float m_fireTotalStrength; // ctor: 0, reset: 0 + /* 92 */ float m_fireTotalStrengthAgainstSelf; // ctor: 0, reset: 0 + /* 96 */ float m_attackerStrength; // not written by ctor/reset /* 100 */ std::map m_map100; /* 112 */ SensedObjectMap m_sensedObjects; // the only two containers `reset` does not empty. Element width 4 and trivially destructible // (the destructor deallocates without a per-element loop); the element type is [INFERRED]. - /* 124 */ std::vector m_vector124; + /* 124 */ std::vector m_candidates; // see: getWorldPlayerOccupiedObjects' output /* 136 */ std::vector m_vector136; }; diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotSquad.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/BotSquad.cpp index 9a9b152d9..3559c4f79 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotSquad.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotSquad.cpp @@ -1,13 +1,19 @@ // [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. // [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining BotSquad operations. #include "BotSquad.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1A1930, __tcf_0 0x1A1990, _GLOBAL__I 0x1A19C0). +#include #include "BotMain.h" #include "../Main/AIDllFrontier.h" #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFSquad.h" +#include "../AIKnowledge/Information.h" +#include "SquadCoordinator.h" +#include "SquadManager.h" namespace dice { namespace hfe { @@ -59,84 +65,130 @@ bool BotSquad::joinSquad(int squad) return joined; } +namespace { + +IBFSquad* squadAdapter() +{ + return static_cast(CommonSingletonServer::m_iBFSquad); +} + +IAIObject* objectOf(Information* info) +{ + return info ? info->getAIObject() : 0; // Information +0x20 +} + +} // namespace + +// ELF 0x1A11B0: joins the side's next empty squad (the id is not stored; the engine's join event +// sets it). bool BotSquad::createSquad() { - BF2_AI_FRONTIER("dice::hfe::ai::BotSquad::createSquad"); + IAIPlayer* const player = m_bot->getPlayer(); + const int squad = squadAdapter()->getNextEmptySquad(m_bot->getSide()); + return squadAdapter()->joinSquad(squad, player); } +// ELF 0x1A1230. void BotSquad::exitSquad() { - BF2_AI_FRONTIER("dice::hfe::ai::BotSquad::exitSquad"); + IAIPlayer* const player = m_bot->getPlayer(); + squadAdapter()->exitSquad(m_squadId, player); } +// ELF 0x1A1280. bool BotSquad::isSquadLeader() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotSquad::isSquadLeader"); + IAIPlayer* const player = m_bot->getPlayer(); + return squadAdapter()->isSquadLeader(m_squadId, player); } +// ELF 0x1A12D0: the argument is not read. void BotSquad::applyAsSquadLeader(int) { - BF2_AI_FRONTIER("dice::hfe::ai::BotSquad::applyAsSquadLeader"); + IAIPlayer* const player = m_bot->getPlayer(); + squadAdapter()->assignAsSquadLeader(m_squadId, player); } +// ELF 0x1A1320: the argument is not read. void BotSquad::retireAsSquadLeader(int) { - BF2_AI_FRONTIER("dice::hfe::ai::BotSquad::retireAsSquadLeader"); + IAIPlayer* const player = m_bot->getPlayer(); + squadAdapter()->retireAsSquadLeader(m_squadId, player); +} + +// ELF 0x1A13F0 / 0x1A1460 / 0x1A14D0: (position, squad, side, the target's object or null). +void BotSquad::issueSquadAttackOrder(const Vec3& position, Information* info) +{ + IAIObject* const object = objectOf(info); + squadAdapter()->issueSquadAttackOrder(position, m_squadId, m_bot->getSide(), object); } -void BotSquad::issueSquadAttackOrder(const Vec3&, Information*) +void BotSquad::issueSquadMoveOrder(const Vec3& position, Information* info) { - BF2_AI_FRONTIER("dice::hfe::ai::BotSquad::issueSquadAttackOrder"); + IAIObject* const object = objectOf(info); + squadAdapter()->issueSquadMoveOrder(position, m_squadId, m_bot->getSide(), object); } -void BotSquad::issueSquadMoveOrder(const Vec3&, Information*) +void BotSquad::issueSquadDefendOrder(const Vec3& position, Information* info) { - BF2_AI_FRONTIER("dice::hfe::ai::BotSquad::issueSquadMoveOrder"); + IAIObject* const object = objectOf(info); + squadAdapter()->issueSquadDefendOrder(position, m_squadId, m_bot->getSide(), object); } -void BotSquad::issueSquadDefendOrder(const Vec3&, Information*) +namespace { + +// ELF 0x1A1540 / 0x1A1640 / 0x1A1740: the squad order's position (IBFSquad +0x54 getSquadOrder), +// the order type stored, and the squad's mission requested unless it is the same already. +void receiveSquadOrder(BotMain* bot, int squadId, BotSquad::OrderType& order, BotSquad::OrderType type) { - BF2_AI_FRONTIER("dice::hfe::ai::BotSquad::issueSquadDefendOrder"); + Vec3 position; + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; + squadAdapter()->getSquadOrder(bot->getSide(), squadId, position, 0); + order = type; + SquadCoordinator* const squad = SquadManager::m_instance->getSquadFromId(squadId, bot->getSide()); + if (!squad->isSameMission(order, position, 0)) + squad->requestMission(order, position, 0, false); } +} // namespace + void BotSquad::recieveAttackSquadOrder() { - BF2_AI_FRONTIER("dice::hfe::ai::BotSquad::recieveAttackSquadOrder"); + receiveSquadOrder(m_bot, m_squadId, m_order, OrderAttack); } void BotSquad::recieveDefendSquadOrder() { - BF2_AI_FRONTIER("dice::hfe::ai::BotSquad::recieveDefendSquadOrder"); + receiveSquadOrder(m_bot, m_squadId, m_order, OrderDefend); } void BotSquad::recieveMoveSquadOrder() { - BF2_AI_FRONTIER("dice::hfe::ai::BotSquad::recieveMoveSquadOrder"); -} - -void BotSquad::recieveAttackCommanderOrder() -{ - BF2_AI_FRONTIER("dice::hfe::ai::BotSquad::recieveAttackCommanderOrder"); + receiveSquadOrder(m_bot, m_squadId, m_order, OrderMove); } -void BotSquad::recieveDefendCommanderOrder() -{ - BF2_AI_FRONTIER("dice::hfe::ai::BotSquad::recieveDefendCommanderOrder"); -} +// ELF 0x1A18E0 / 0x1A18F0 / 0x1A1900: empty. +void BotSquad::recieveAttackCommanderOrder() {} +void BotSquad::recieveDefendCommanderOrder() {} +void BotSquad::recieveMoveCommanderOrder() {} -void BotSquad::recieveMoveCommanderOrder() -{ - BF2_AI_FRONTIER("dice::hfe::ai::BotSquad::recieveMoveCommanderOrder"); -} +// ELF 0x1A1910 / 0x1A1920: empty (a 0x148-byte frame and no code). +void BotSquad::acceptCommanderOrder() {} +void BotSquad::declineCommanderOrder() {} +// ELF 0x1A1840 / 0x1A1890. void BotSquad::acceptSquadOrder() { - BF2_AI_FRONTIER("dice::hfe::ai::BotSquad::acceptSquadOrder"); + IAIPlayer* const player = m_bot->getPlayer(); + squadAdapter()->acceptSquadOrder(m_squadId, player); } void BotSquad::declineSquadOrder() { - BF2_AI_FRONTIER("dice::hfe::ai::BotSquad::declineSquadOrder"); + IAIPlayer* const player = m_bot->getPlayer(); + squadAdapter()->declineSquadOrder(m_squadId, player); } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotSquad.h b/Code/BF2/AI/AIDLL/AI/AIBot/BotSquad.h index 574f008e4..7ed7cedb8 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotSquad.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotSquad.h @@ -38,7 +38,7 @@ class BotSquad bool hasMoveOrderOrder(); // dice's name bool hasNoOrder(); - // membership. joinSquad written; remaining methods are [FRONTIER]. + // membership bool joinSquad(int squad); bool createSquad(); void exitSquad(); @@ -58,9 +58,15 @@ class BotSquad void recieveAttackCommanderOrder(); void recieveDefendCommanderOrder(); void recieveMoveCommanderOrder(); + void acceptCommanderOrder(); + void declineCommanderOrder(); void acceptSquadOrder(); void declineSquadOrder(); + // [INFERRED] inline accessor: CommanderInterface's Bot overloads (ELF 0x3232D0..) read +4 + // directly. + int getSquadId() const { return m_squadId; } + private: /* 0 */ BotMain* m_bot; // the ctor argument /* 4 */ int m_squadId; // = 0; `joinSquad` sets it on success. `createSquad` does not diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotSubObjects.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/BotSubObjects.cpp index 755b8760a..aa00402ed 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotSubObjects.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotSubObjects.cpp @@ -2,6 +2,14 @@ #include "BotSubObjects.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1A2210, __tcf_0 0x1A2270, _GLOBAL__I 0x1A22A0). +#include + +#include "../Main/InformationManager.h" +#include "../AIKnowledge/Information.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" + namespace dice { namespace hfe { namespace ai { @@ -14,12 +22,31 @@ FireCorrectionData::FireCorrectionData() , m_flag84(false) { // +0..+3 and +68..+83 are deliberately untouched - see above. - for (int i = 0; i < 15; ++i) - m_zero8[i] = 0; - for (int i = 0; i < 9; ++i) - m_zero88[i] = 0; + for (int i = 0; i < 3; ++i) + m_firedTarget[i] = 0.0f; + Vec3* const zeroed[4] = { &m_missedPosition, &m_aimDirection, &m_vec44, &m_predictedTarget }; + for (int i = 0; i < 4; ++i) + zeroed[i]->x = zeroed[i]->y = zeroed[i]->z = 0.0f; + // +88..+120 zeroed: the three points. + Vec3* const points[3] = { &m_projectilePrePoint, &m_projectilePostPoint, &m_projectileTargetPoint }; + for (int i = 0; i < 3; ++i) + points[i]->x = points[i]->y = points[i]->z = 0.0f; } +// ELF 0x1A2170 (160 bytes). +void FireCorrectionData::newTarget(unsigned int handle) +{ + m_flag5 = true; + m_flag4 = true; + m_flag6 = true; + m_double72 = -1.0f; + Information* const information = informationManager->getInformation(handle); + m_vec44.x = 0.0f; m_vec44.y = 0.0f; m_vec44.z = 0.0f; + if (information) + m_shotTarget = information->getAIObject()->getObject(); // IAIObject slot +0x20 + else + m_shotTarget = 0; +} } // namespace ai } // namespace hfe diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotSubObjects.h b/Code/BF2/AI/AIDLL/AI/AIBot/BotSubObjects.h index a6c0a9b63..f91154556 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotSubObjects.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotSubObjects.h @@ -3,6 +3,8 @@ #ifndef AI_AIDLL_AI_AIBOT_BOTSUBOBJECTS_H #define AI_AIDLL_AI_AIBOT_BOTSUBOBJECTS_H +#include "../../../../Math/Vec3.h" + namespace dice { namespace hfe { namespace ai { @@ -14,18 +16,35 @@ class FireCorrectionData { public: FireCorrectionData(); // for the class + // ELF 0x1A2170: +4/+5/+6 set, +72 = -1.0, +44 zeroed, +80 = the target's world object. + void newTarget(unsigned int handle); -private: - /* 0 */ char m_gap0[4]; // [UNRESOLVED] - not initialised by the ctor + // BotMain::planExecution (ELF 0x188B90) writes these inline once the collision handler + // reports that the bot's projectile passed its point: the pre/post/target points and the + // maximum height from IBFCollisionHandler, then sets +5, +84 and +85. + /* 0 */ int m_weapon; // not initialised by the ctor; event_firing's int (the weapon) [INFERRED] /* 4 */ bool m_flag4; // = true - /* 5 */ bool m_flag5; // = true - /* 6 */ char m_pad6[2]; - /* 8 */ int m_zero8[15]; // +8..+64, all zeroed - /* 68 */ char m_gap68[16]; // [UNRESOLVED] - the ctor skips +68..+83 - /* 84 */ bool m_flag84; // = false - /* 85 */ char m_pad85[3]; - /* 88 */ int m_zero88[9]; // +88..+120, all zeroed - /* 124 */ char m_gap124[4]; // [UNRESOLVED] - 128 - 124 + /* 5 */ bool m_flag5; // = true; planExecution: true + /* 6 */ bool m_flag6; // not initialised by the ctor; event_firing: a correction shot is out + /* 7 */ char m_pad7[1]; + /* 8 */ float m_firedTarget[3]; // zeroed; event_firing's target (a Vec3) + // +20..+64 zeroed by the ctor. event_shotMissed (ELF 0x18B230) stores the miss at +0x14; + // newTarget (0x1A2170) zeroes +0x2C; EntryMouseTurretAimAt (0x2B9A5C) writes +0x20 (the aim + // direction) and +0x38 (the predicted target position). [INFERRED] names. + /* 20 */ Vec3 m_missedPosition; + /* 32 */ Vec3 m_aimDirection; + /* 44 */ Vec3 m_vec44; // [UNRESOLVED] name + /* 56 */ Vec3 m_predictedTarget; + /* 68 */ char m_gap68[4]; // [UNRESOLVED] - the ctor skips +68..+83 + /* 72 */ double m_double72; // event_firing / newTarget: -1.0; event_shotMissed: the miss time + /* 80 */ const void* m_shotTarget; // event_shotHit: a hit on this object confirms the shot [INFERRED] + /* 84 */ bool m_flag84; // = false; planExecution: true + /* 85 */ bool m_flag85; // planExecution: true + /* 86 */ char m_pad86[2]; + /* 88 */ Vec3 m_projectilePrePoint; // = 0 + /* 100 */ Vec3 m_projectilePostPoint; // = 0 + /* 112 */ Vec3 m_projectileTargetPoint; // = 0 + /* 124 */ float m_projectileMaxHeight; // not initialised by the ctor }; diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/CommunicationAgent.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/CommunicationAgent.cpp index d0a1add9b..2541bfb29 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/CommunicationAgent.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/CommunicationAgent.cpp @@ -1,12 +1,29 @@ // [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining CommunicationAgent operations. #include "CommunicationAgent.h" -#include "../Main/AIDllFrontier.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1C54D0, __tcf_0 0x1C5530, _GLOBAL__I 0x1C5560). +#include + +#include + +#include "BotMain.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../../../../IO/Input/PlayerInput.h" + +#include "../Main/IBotManager.h" #include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" #include "../Main/CommunicationHub.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" // IAIPlayer::getIsAIPlayer +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" // getPlayerFromId #include "../../../AIInterface/Module/BFConsole.h" // IBFModuleCourier, AIRadioMessageSettings namespace dice { @@ -46,6 +63,10 @@ CommunicationAgent::CommunicationAgent(BotMain* owner) reset(); } +CommunicationAgent::~CommunicationAgent() +{ +} + // Resets message state and acquires the shared communication hub. void CommunicationAgent::reset() { @@ -64,22 +85,380 @@ void CommunicationAgent::reset() while (!m_queue.empty()) m_queue.pop(); - m_double60 = 0.0; + m_lastPollTime = 0.0; m_int92 = -1; // This order is the binary's. - m_double104 = 0.0; + m_lastHornHonkTime = 0.0; m_double96 = 0.0; } -// [FRONTIER] Remaining message operations require implementation. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. - -// [FRONTIER] Services one bot's radio on the BotManager communication tick. -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -// Replace the stop when radio update behavior is recovered. +// ELF 0x1C4100: old messages are aged out every tick; the radio is polled once a second +// (a game time that went backwards restarts the interval). void CommunicationAgent::update() { - BF2_AI_FRONTIER("dice::hfe::ai::CommunicationAgent::update"); + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + clearOutOldMessages(now); + if (now < m_lastPollTime) + m_lastPollTime = now; + if (now - m_lastPollTime > 1.0) + { + m_lastPollTime = now; + pollForRadioMessage(now); + } +} + +// ELF 0x1C4190: the agent's own messages are queued first, then every due message is sent. +void CommunicationAgent::pollForRadioMessage(double now) +{ + sendCommunicationAgentMessages(now); + CAPrioMessage message; + while (peekRadioMessage(message) && !waitWithSendingMessage(message, now)) + { + postEvent(message); + dequeueRadioMessage(message); + } +} + +// ELF 0x1C4DD0 (396 bytes), all eighteen types: an expired send block is cleared, and the +// inbox (newest first) is cut at the first message older than the type's time to live. +void CommunicationAgent::clearOutOldMessages(double now) +{ + for (unsigned int type = 0; type < 18; ++type) + { + if (m_lastSentTime[type] < now) + m_lastSentTime[type] = 0.0; + std::list& inbox = m_receivedMessages[type]; + std::list::iterator it = inbox.begin(); + while (it != inbox.end() && now < it->m_time + m_receiveTimeToLive[type]) + ++it; + while (it != inbox.end()) + it = inbox.erase(it); + } +} + +// ELF 0x1C4F60: both checks use the bot's current equipment. +void CommunicationAgent::sendCommunicationAgentMessages(double) +{ + Information* const equipment = informationManager->getInformation(m_bot->getCurrentEquipment()); + sendCallForMedic(equipment); + shutOffHorn(equipment); +} + +// ELF 0x1C4FE0 (552 bytes). A wounded primary object (0 < health < 0.5 for strength type 0 +// else 0.75) calls for a medic - type 3 on channel 0 for infantry, type 4 on channel 6 +// otherwise - unless the bot is airborne, rides a fast (speed > 3) vehicle-flagged primary, or +// carries a weapon of type 1 or 3 with strength against its own type. The primary object's +// mobile plug-in is read before its null check (no guard in the ELF). +void CommunicationAgent::sendCallForMedic(Information* equipment) +{ + Information* const primary = + informationManager->getInformation(equipment->getPrimaryObject(m_bot->getSide())); + IPIMobile* const mobile = primary->getMobile(); + bool skip = false; + if (m_bot->isAirBorn() + || (primary && primary->isOfType(ITAir) && mobile + && mobile->getSpeedMagnitude() > 3.0f)) + skip = true; + if (!equipment->isPrimary() || skip) + return; + IPIPhysical* const physical = equipment->getPhysical(); + const float health = physical->getHealth(); + const int strengthType = physical->getStrengthType(); + const float threshold = strengthType == 0 ? 0.5f : 0.75f; + if (!(0.0f < health && health < threshold)) + return; + if (IPIArmament* const armament = equipment->getArmament()) + { + const std::vector& weapons = armament->getWeapons(); + for (unsigned int i = 0; i < weapons.size(); ++i) + { + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (weapon) + { + const int type = weapon->getWeaponType(); + if ((type == 1 || type == 3) && static_cast(weapon->getStrength(strengthType)) > 0.0f) + return; + } + } + } + if (strengthType == 0) + enqueueRadioMessage(static_cast(3), static_cast(0), 5, 0.0f, -1); + else + enqueueRadioMessage(static_cast(4), static_cast(6), 5, 0.0f, 0); +} + +// ELF 0x1C5460: the side (Bot +0xE0) is read first, then the information's object (+0x20) and the +// player (Bot +0xBC); the hub is +4. +void CommunicationAgent::setSeenNewEnemy(Information* enemy) +{ + const int side = m_bot->getSide(); + IAIObject* const object = enemy->getAIObject(); + m_hub->enemySpottedByAI(m_bot->getPlayer(), object, side); +} + +// ELF 0x1C44A0 (812 bytes). The record: the settings' modifier (+4), the sender, the game time, +// false, `flag`, the type (settings +0). A type-1 message drops the sender's first type-0 entry +// and everything after it; a type-0 message does the same in the type-1 list. In the message's +// own list an entry from the sender is refreshed (modifier, time, +16 false), else the record is +// appended. +void CommunicationAgent::receiveRadioMessage(const AIRadioMessageSettings& settings, int senderPlayerId, bool flag) +{ + int type; + std::memcpy(&type, settings.m_opaque0, sizeof(type)); // +0, opaque in BFConsole.h + AIRadioMessageInfo info; + info.m_modifier = settings.m_modifier; + info.m_senderPlayerId = senderPlayerId; + info.m_time = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + info.m_flag16 = false; + info.m_flag17 = flag; + info.m_int20 = type; + if (type == 1 || type == 0) + { + std::list& other = m_receivedMessages[type == 1 ? 0 : 1]; + for (std::list::iterator it = other.begin(); it != other.end(); ++it) + { + if (it->m_senderPlayerId == senderPlayerId) + { + while (it != other.end()) + it = other.erase(it); + break; + } + } + } + std::list& inbox = m_receivedMessages[type]; + for (std::list::iterator it = inbox.begin(); it != inbox.end(); ++it) + { + if (it->m_senderPlayerId == senderPlayerId) + { + it->m_modifier = settings.m_modifier; + it->m_flag16 = false; + it->m_time = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + return; + } + } + inbox.push_back(info); +} + +// ELF 0x1C53F0: horn-capable equipment (type flag 0x04000000) releases fire after 2 s. +void CommunicationAgent::shutOffHorn(Information* equipment) +{ + if (!equipment->isOfType(ITHasCarHorn)) + return; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (now - m_lastHornHonkTime > 2.0) + m_bot->m_playerInput->setInput(io::PIFire, 0.0f); +} + +// ELF 0x1C5210 (478 bytes). Nothing without a target, or when the target's player +// (Information::getPlayerId, IAIPlayerFactory +0x20) is unknown. The interval since the last horn +// (+104) must reach 20 s towards an AI player and 5 s towards a human. With horn-capable current +// equipment (type flag 0x04000000; the equipment information is not null-tested) the bot presses +// fire (PIFire 1.0); otherwise it radios type 11 on channel 6, priority 3, naming the target's +// player. The horn time is then renewed, and a target flagged 0x00200000 whose object is a bot +// (IBotManager +0x24) gets the time in its own agent (+96). +void CommunicationAgent::honkHorn(Information* target) +{ + if (!target) + return; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + const int targetPlayerId = target->getPlayerId(); + IAIPlayer* const player = static_cast(CommonSingletonServer::m_iaiPlayerFactory) + ->getPlayerFromId(target->getPlayerId()); + if (!player) + return; + const float interval = player->getIsAIPlayer() ? 20.0f : 5.0f; + if (interval > now - m_lastHornHonkTime) + return; + Information* const equipment = informationManager->getInformation(m_bot->getCurrentEquipment()); + if (equipment->isOfType(ITHasCarHorn)) + m_bot->m_playerInput->setInput(io::PIFire, 1.0f); + else + sendImmediately(static_cast(11), static_cast(6), 3, + targetPlayerId); + m_lastHornHonkTime = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (!target->isOfType(ITSoldier)) + return; + Bot* const horned = IBotManager::instance->getBot(target->getAIObject()); + if (!horned) + return; + const double time = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + horned->getCommunicationAgent()->m_double96 = time; +} + +// ELF 0x1C4A50: `0.0 > now - m_lastSentTime[type]`. +bool CommunicationAgent::getSentMessage(AIRadioMessageType type) const +{ + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + return 0.0f > now - m_lastSentTime[type]; +} + +// ELF 0x1C4AA0: IBFModuleCourier +0x1C for the voice, +0x18 for its settings (modifier at +4). +float CommunicationAgent::getModifierForMessageType(AIRadioMessageType type) const +{ + IBFModuleCourier* const courier = static_cast(CommonSingletonServer::m_iBFModuleCourier); + int voice; + if (!courier->getVoiceFromAiMessageType(type, voice)) + return 1.0f; + AIRadioMessageSettings settings; + courier->getAIMessageSettings(voice, settings); + return settings.m_modifier; +} + +// ELF 0x1C4C00: the queue top, by copy. +bool CommunicationAgent::peekRadioMessage(CAPrioMessage& out) const +{ + if (m_queue.empty()) + return false; + out = m_queue.top(); + return true; +} + +// ELF 0x1C4C50: copies the top, drops its type's pending entry (+20 map) and pops it. +bool CommunicationAgent::dequeueRadioMessage(CAPrioMessage& out) +{ + if (m_queue.empty()) + return false; + out = m_queue.top(); + m_map20.erase(m_map20.find(out.m_type)); + m_queue.pop(); + return true; +} + +// ELF 0x1C4D40: wait until the send time, and while the newest received message of the type is +// younger than its max send period. +bool CommunicationAgent::waitWithSendingMessage(CAPrioMessage& message, double now) +{ + if (message.m_sendTime > now) + return true; + const std::list& inbox = getReceivedMessages(message.m_type); + if (inbox.empty()) + return false; + const AIRadioMessageInfo& newest = inbox.front(); + return !(static_cast(m_maxSendPeriod[newest.m_int20]) <= now - newest.m_time); +} + +// ELF 0x1C4290 (514 bytes). Outside the type's send block (+48) one message per type is queued +// (the +20 map holds the pending type and its send time); the block is then renewed by the +// type's max send period. +void CommunicationAgent::enqueueRadioMessage(AIRadioMessageType type, AIRadioChannelType channel, + unsigned int priority, float delay, int c) +{ + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (!(m_lastSentTime[type] <= now)) + return; + CAPrioMessage message; + message.m_type = type; + message.m_channel = channel; + message.m_priority = static_cast(priority); + message.m_receiverPlayerId = c; + message.m_sendTime = now + static_cast(delay); + message.m_delay = delay; + if (m_map20.insert(std::make_pair(type, message.m_sendTime)).second) + m_queue.push(message); + m_lastSentTime[type] = now + static_cast(m_maxSendPeriod[type]); +} + +// ELF 0x1C4B10. The bot's player id (twice, as bytes), side and the message's last argument +// (byte); IBFModuleCourier +0x1C getVoiceFromAiMessageType must know the type, whose voice's low +// byte goes to the hub with channel message type 3. +void CommunicationAgent::postEvent(const CAPrioMessage& message) const +{ + const unsigned char sender = static_cast(m_bot->getPlayerId()); + const unsigned char player = static_cast(m_bot->getPlayerId()); + const unsigned char side = static_cast(m_bot->getSide()); + const unsigned char argument = static_cast(message.m_receiverPlayerId); + int voice; + if (!static_cast(CommonSingletonServer::m_iBFModuleCourier) + ->getVoiceFromAiMessageType(message.m_type, voice)) + return; + m_hub->filterAndSendAIRadioMessage(m_bot, sender, static_cast(3), message.m_channel, + message.m_type, static_cast(voice), player, side, argument); +} + +bool CommunicationAgent::getReceivedMessage(AIRadioMessageInfo& out, AIRadioMessageType type, + int senderPlayerId) const +{ + const std::list& messages = m_receivedMessages[type]; + for (std::list::const_iterator it = messages.begin(); it != messages.end(); ++it) + { + if (it->m_senderPlayerId == senderPlayerId) + { + out = *it; + return true; + } + } + return false; +} + +bool CommunicationAgent::receivedMessageExists(AIRadioMessageType type, int senderPlayerId) const +{ + const std::list& messages = m_receivedMessages[type]; + for (std::list::const_iterator it = messages.begin(); it != messages.end(); ++it) + { + if (senderPlayerId == -1 || it->m_senderPlayerId == senderPlayerId) + return true; + } + return false; +} + +bool CommunicationAgent::generalConfirmReceivedMessage(AIRadioMessageType type) +{ + bool confirmed = false; + std::list& messages = m_receivedMessages[type]; + for (std::list::iterator it = messages.begin(); it != messages.end(); ++it) + { + if (!it->m_flag16 && !it->m_flag17) + { + it->m_flag16 = true; + confirmed = true; + } + } + return confirmed; +} + +bool CommunicationAgent::confirmReceivedMessage(AIRadioMessageType type, int senderPlayerId) +{ + bool confirmed = false; + std::list& messages = m_receivedMessages[type]; + for (std::list::iterator it = messages.begin(); it != messages.end(); ++it) + { + if (it->m_senderPlayerId == senderPlayerId && !it->m_flag16 && !it->m_flag17) + { + it->m_flag16 = true; + confirmed = true; + } + } + return confirmed; +} + +// The search compares type (+20), sender (+4) and the time (+8, `fucompi`, unordered is unequal). +bool CommunicationAgent::confirmReceivedMessage(const AIRadioMessageInfo& info) +{ + std::list& messages = m_receivedMessages[info.m_int20]; + std::list::iterator it = messages.begin(); + for (; it != messages.end(); ++it) + { + if (it->m_int20 == info.m_int20 && it->m_senderPlayerId == info.m_senderPlayerId + && it->m_time == info.m_time) + break; + } + if (it == messages.end() || it->m_flag16 || it->m_flag17) + return false; + it->m_flag16 = true; + return true; +} + +void CommunicationAgent::sendImmediately(AIRadioMessageType type, AIRadioChannelType channel, + unsigned int priority, int c) +{ + CAPrioMessage message; + message.m_type = type; + message.m_channel = channel; + message.m_priority = static_cast(priority); + message.m_sendTime = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + message.m_receiverPlayerId = c; + message.m_delay = 0.0f; + postEvent(message); } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/CommunicationAgent.h b/Code/BF2/AI/AIDLL/AI/AIBot/CommunicationAgent.h index d50780f91..6003aaa56 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/CommunicationAgent.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/CommunicationAgent.h @@ -22,13 +22,33 @@ class Information; // enumerator name is recoverable from either binary. enum AIRadioChannelType : int; enum AIRadioMessageType : int; +struct AIRadioMessageSettings; // Radio-message record. [UNRESOLVED] Some fields are not yet identified. struct AIRadioMessageInfo { - /* 0 */ unsigned char m_opaque0[4]; // [UNRESOLVED] + // ELF 0x1C3260: 1.0f, -1, 0.0, false, false, 18. + AIRadioMessageInfo() + : m_modifier(1.0f), m_senderPlayerId(-1), m_time(0.0), m_flag16(false), m_flag17(false), m_int20(0x12) + { + } + + // ELF 0x1C3310 (C1; C2 0x1C32E0 is the same): member by member, out of line in the image. + AIRadioMessageInfo(const AIRadioMessageInfo& other) + : m_modifier(other.m_modifier), m_senderPlayerId(other.m_senderPlayerId), m_time(other.m_time), + m_flag16(other.m_flag16), m_flag17(other.m_flag17), m_int20(other.m_int20) + { + } + + // receiveRadioMessage (ELF 0x1C44A0) copies AIRadioMessageSettings +4 (the modifier) here. + /* 0 */ float m_modifier; /* 4 */ int m_senderPlayerId; - /* 8 */ unsigned char m_opaque8[16]; // [UNRESOLVED] + // clearOutOldMessages (ELF 0x1C4DD0) ages entries by this time; waitWithSendingMessage + // (0x1C4D40) indexes the max-send periods with the int at +20. + /* 8 */ double m_time; + /* 16 */ bool m_flag16; // [UNRESOLVED] false on receipt and on refresh + /* 17 */ bool m_flag17; // receiveRadioMessage's third argument + /* 20 */ int m_int20; // the message type (AIRadioMessageSettings +0); waitWithSendingMessage indexes by it }; class CommunicationAgent @@ -41,20 +61,67 @@ class CommunicationAgent // the largest value here is what the bot says next. bool operator<(const CAPrioMessage& rhs) const { return m_priority < rhs.m_priority; } - /* 0 */ unsigned char m_opaque0[8]; // [UNRESOLVED] - /* 8 */ int m_priority; - /* 12 */ unsigned char m_opaque12[16]; // [UNRESOLVED] + // 28 bytes: peek/dequeueRadioMessage (ELF 0x1C4C00 / 0x1C4C50) copy seven words. + /* 0 */ AIRadioMessageType m_type; // getReceivedMessages(m_type) in waitWithSendingMessage + // enqueueRadioMessage (ELF 0x1C4290) fills all seven words from its arguments. + /* 4 */ AIRadioChannelType m_channel; // postEvent's fifth hub argument + /* 8 */ int m_priority; // the unsigned argument + /* 12 */ int m_receiverPlayerId; // the last argument; postEvent passes its low byte // name: AIDLL_r assert "message.m_receiverPlayerId" 0x101640F0 (+0xC; channel AIRCPlayer = 8) + /* 16 */ double m_sendTime; // now + delay; not sent before this time + /* 24 */ float m_delay; }; explicit CommunicationAgent(BotMain* owner); - // The implicit destructor releases member containers; no custom cleanup is required. + // ELF 0x1C3CF0 (D1; D2 0x1C3B50): an empty body; the members are torn down by the compiler. + ~CommunicationAgent(); void reset(); - void update(); // - [FRONTIER] + void update(); + void pollForRadioMessage(double now); + void clearOutOldMessages(double now); + void sendCommunicationAgentMessages(double now); + void sendCallForMedic(Information* equipment); + void shutOffHorn(Information* equipment); + // ELF 0x1C5210: horns at `target` (or radios type 11 without a horn), at most every 20 s + // towards a bot and every 5 s towards a human. + void honkHorn(Information* target); + // ELF 0x1C4A50: true while the type's send block (+48) lies in the future. + bool getSentMessage(AIRadioMessageType type) const; + // ELF 0x1C4AA0: the type's AIRadioMessages.ai modifier, 1.0 without a voice. + float getModifierForMessageType(AIRadioMessageType type) const; + // ELF 0x1C5460: CommunicationHub::enemySpottedByAI(bot player, information's object, side). + void setSeenNewEnemy(Information* enemy); + // ELF 0x1C44A0: file a received message under its type (one entry per sender). + void receiveRadioMessage(const AIRadioMessageSettings& settings, int senderPlayerId, bool flag); + void enqueueRadioMessage(AIRadioMessageType type, AIRadioChannelType channel, unsigned int priority, + float delay, int c); + bool peekRadioMessage(CAPrioMessage& out) const; + bool dequeueRadioMessage(CAPrioMessage& out); + bool waitWithSendingMessage(CAPrioMessage& message, double now); + void postEvent(const CAPrioMessage& message) const; // ELF 0x1C4B10 // attested by a 7-byte body: `return m_receivedMessages.data + type;` const std::list& getReceivedMessages(AIRadioMessageType type) const { return m_receivedMessages[type]; } + // ELF 0x1C47F0: the first received message of `type` from senderPlayerId, copied out. + bool getReceivedMessage(AIRadioMessageInfo& out, AIRadioMessageType type, int senderPlayerId) const; + // ELF 0x1C4A00: any message of `type` from senderPlayerId (-1: from anyone). + bool receivedMessageExists(AIRadioMessageType type, int senderPlayerId) const; + // ELF 0x1C4850: marks every unconfirmed (+16, +17 clear) message of `type` confirmed (+16). + bool generalConfirmReceivedMessage(AIRadioMessageType type); + // ELF 0x1C4990: the same for the messages of one sender. + bool confirmReceivedMessage(AIRadioMessageType type, int senderPlayerId); + // ELF 0x1C48C0: the first message equal to `info` (type, sender, time) when unconfirmed. + bool confirmReceivedMessage(const AIRadioMessageInfo& info); + // ELF 0x1C4220: posts {type, channel, priority, c, now, 0.0f} without queueing. + void sendImmediately(AIRadioMessageType type, AIRadioChannelType channel, unsigned int priority, int c); + // [INFERRED] inline readers (D's waitForPickup reads +0x5C; F's BBAvoid reads +0x60). + // +0x60 is written by honkHorn on the bot it horns at. +0x5C is written by reset (-1) and by + // BBPChange::createPlan (0x23C474: the driver's player id when the driver is a bot, else 0xFF) + // through the inline setter below ([CHOSEN] name). + int getInt92() const { return m_int92; } + void setInt92(int value) { m_int92 = value; } + double getDouble96() const { return m_double96; } private: typedef std::priority_queue, @@ -72,13 +139,16 @@ class CommunicationAgent // Eighteen doubles, one per type, zeroed by `reset` and paired with the max-send-period cache // below. [INFERRED] that these are the per-type last-sent timestamps. /* 48 */ std::vector m_lastSentTime; - /* 60 */ double m_double60; // reset: 0.0 + // update (ELF 0x1C4100) polls the radio at most once a second from this time. + /* 60 */ double m_lastPollTime; // reset: 0.0 // the two cached columns of `AIRadioMessages.ai`. Filled once, in the constructor. /* 68 */ std::vector m_receiveTimeToLive; /* 80 */ std::vector m_maxSendPeriod; - /* 92 */ int m_int92; // reset: -1, this subsystem's null-index convention + /* 92 */ int m_int92; // reset: -1; BBPChange::createPlan (see above) + // the game time another bot last horned at this one (honkHorn); BBAvoid reads it. /* 96 */ double m_double96; // reset: 0.0 - /* 104 */ double m_double104; // reset: 0.0 + // shutOffHorn (ELF 0x1C53F0) releases the horn (PIFire) two seconds after this time. + /* 104 */ double m_lastHornHonkTime; // reset: 0.0 // name: AIDLL_r assert in honkHorn (0x10165630) }; } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/CoverDetection.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/CoverDetection.cpp new file mode 100644 index 000000000..e350ff01a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/CoverDetection.cpp @@ -0,0 +1,82 @@ +// The ELF FILE symbol attests CoverDetection.cpp; directory placement is [INFERRED]. + +#include +#include +// static init: ELF 0x1A20C0, 0x1A2120, 0x1A2150: iostream Init only. + +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../../../AIInterface/BFKnowledge/PlanePolygon.h" +#include "../../../../Math/BoundingBox.h" + +namespace dice { namespace hfe { namespace ai { + +// ELF 0x1A19E0. Shipped defect: output is read but never written. +float hasCoverObjects(Information* information, const Vec3& position, IPlanePolygon* polygon, + Vec3& output) +{ + const BoundingBox* const box = information->getPhysical()->getBoundingBox(); + const Vec3& objectPosition = information->getPosition(); + const Vec3 delta = {objectPosition.x - position.x, objectPosition.y - position.y, + objectPosition.z - position.z}; + Vec2 direction = {}; + Vec2 normal = {}; + vec3ToVec2XZ(delta, direction); + getNormal(direction, normal); + const float squared = normal.x * normal.x + normal.y * normal.y; + if (!(std::fabs(squared - 1.0f) < 1.1920928955078125e-7f)) + { + if (!(std::fabs(squared) < 1.4210854715202004e-14f)) + { + const float inverse = 1.0f / std::sqrt(squared); + normal.x *= inverse; + normal.y *= inverse; + } + else + { + normal.x = 0.0f; + normal.y = 0.0f; + } + } + const Vec3 maximum = box->getMax(); + const Vec3 maximumDelta = {maximum.x - position.x, maximum.y - position.y, maximum.z - position.z}; + Vec2 maximumXZ = {}; + vec3ToVec2XZ(maximumDelta, maximumXZ); + Vec2 high = maximumXZ; + Vec2 low = maximumXZ; + // [INFERRED] local packaging of the repeated inlined projection. + const auto projection = [&](const Vec2& point) + { + return (point.x * normal.x + point.y * normal.y) + / std::sqrt(point.x * point.x + point.y * point.y); + }; + float highest = projection(maximumXZ); + float lowest = highest; + const Vec3 minimum = box->getMin(); + const Vec3 minimumDelta = {minimum.x - position.x, minimum.y - position.y, minimum.z - position.z}; + Vec2 minimumXZ = {}; + vec3ToVec2XZ(minimumDelta, minimumXZ); + Vec2 corner = {maximumXZ.x, minimumXZ.y}; + float value = projection(corner); + if (value > highest) { highest = value; high = corner; } + else if (value < lowest) { lowest = value; low = corner; } + corner.x = minimumXZ.x; + value = projection(corner); + if (value > highest) { highest = value; high = corner; } + else if (value < lowest) { lowest = value; low = corner; } + corner.y = maximumXZ.y; + value = projection(corner); + if (value > highest) { high = corner; } + else if (value < lowest) { low = corner; } + Vec2 origin = {}; + Vec2 unused = {}; + vec3ToVec2XZ(position, origin); + vec3ToVec2XZ(output, unused); + unused.x -= origin.x; + unused.y -= origin.y; + if (polygon->intersects(high, origin)) + return polygon->intersects(low, origin) ? 1.0f : 0.25f; + return polygon->intersects(low, origin) ? 0.25f : 0.0f; +} + +} } } diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/RandomSquareMerger.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/RandomSquareMerger.cpp new file mode 100644 index 000000000..96d1316ba --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/RandomSquareMerger.cpp @@ -0,0 +1,64 @@ +// RandomSquareMerger. Recovered from libaidll.so 1.5.3153 (ia-32), 0x1A2480..0x1A279F. + +#include "RandomSquareMerger.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1A27A0, __tcf_0 0x1A2800, _GLOBAL__I 0x1A2830). +#include + +#include "../Main/AIRandom.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1A24D0 (C1; C2 0x1A2480): the base, then the vptr. +RandomSquareMerger::RandomSquareMerger(int count, float* weights, UrgencyGenerator** generators) + : UrgencyMerger(count, weights, generators) +{ +} + +// ELF 0x1A2560 (D1; D2 0x1A2520, D0 0x1A25A0): the base. +RandomSquareMerger::~RandomSquareMerger() +{ +} + +// ELF 0x1A25E0. Every generator updates; the squares of the updated urgencies are summed. A draw +// in [0, sum) then walks the generators, subtracting each one's active urgency (not squared); +// a generator whose share (active / sum) is above 0.01 becomes the chosen one (its own chosen +// generator, +0x20). The walk stops at the first generator after which the draw is no longer +// positive and a choice exists. Answers that generator's active urgency. Shipped defects: when +// the walk runs through, the index is the count (one past the array), and a null generator at +// the stop index is called; with no generators index 0 is used. +float RandomSquareMerger::updateActiveUrgency(Bot* bot) +{ + float total = 0.0f; + for (int i = 0; i < m_count; ++i) + { + if (m_generators[i]) + { + const float urgency = m_generators[i]->updateActiveUrgency(bot); // +0x10 + total = urgency * urgency + total; + } + } + float pick = static_cast(AIRandom::m_instance->next()) * 2.3283064e-10f * total; + mpMaxGenerator = 0; + int index = 0; + for (; index < m_count; ++index) + { + if (m_generators[index]) + { + const float active = m_generators[index]->getActiveUrgency(bot); // +0x0C + pick = pick - active; + if (active / total > 0.01f) + mpMaxGenerator = m_generators[index]->getChosenGenerator(); // +0x20 + } + if (pick <= 0.0f && mpMaxGenerator != 0) + break; + } + return m_generators[index]->getActiveUrgency(bot); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/RandomSquareMerger.h b/Code/BF2/AI/AIDLL/AI/AIBot/RandomSquareMerger.h new file mode 100644 index 000000000..7a7429d31 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/RandomSquareMerger.h @@ -0,0 +1,31 @@ +// An urgency merger that picks one of its generators at random, weighted by the squares of their +// active urgencies. +// Evidence: libaidll.so 1.5.3153 (ia-32). File RandomSquareMerger.cpp (FILE symbol; the AIBot +// directory is [INFERRED] from its neighbours, as the ledger files it); vtable 0x4B6D40: the +// destructors and updateActiveUrgency (+0x10) are its own, every other slot is UrgencyMerger's. +// Nothing in libaidll.so constructs one. + +#ifndef AI_AIDLL_AI_AIBOT_RANDOMSQUAREMERGER_H // [INFERRED] guard style +#define AI_AIDLL_AI_AIBOT_RANDOMSQUAREMERGER_H + +#include "UrgencyMerger.h" + +namespace dice { +namespace hfe { +namespace ai { + +class RandomSquareMerger : public UrgencyMerger +{ +public: + // As UrgencyMerger. + RandomSquareMerger(int count, float* weights, UrgencyGenerator** generators); + virtual ~RandomSquareMerger(); + + virtual float updateActiveUrgency(Bot* bot); // +0x10 +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOT_RANDOMSQUAREMERGER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SensedObject.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/SensedObject.cpp new file mode 100644 index 000000000..4f4cfe7f1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SensedObject.cpp @@ -0,0 +1,58 @@ +// One sensed-object record. Evidence: libaidll.so 1.5.3153 (ia-32), see SensedObject.h. + +#include "SensedObject.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1A29C0, __tcf_0 0x1A2A20, _GLOBAL__I 0x1A2A50). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1A2860 (C1; C2 0x1A28F0 is identical). The three Vec3 are zeroed, +0x3C gets -1000.0f +// (`flds 0x49CDC8; fstpl 0x3c`), +0x50 = 2, +0x54 / +0x5C = 0.0, +0x64 = 0. The flag word comes +// from the setne/incl/cmov chain: base = seen + 1, then +4 if sided, +8 and +16 if not seen. +SensedObject::SensedObject(unsigned int handle, bool seen, bool sided) + : m_handle(handle) +{ + m_seenPosition.x = 0.0f; + m_seenPosition.y = 0.0f; + m_seenPosition.z = 0.0f; + m_lastPosition.x = 0.0f; + m_lastPosition.y = 0.0f; + m_lastPosition.z = 0.0f; + m_lastSeenPosition.x = 0.0f; + m_lastSeenPosition.y = 0.0f; + m_lastSeenPosition.z = 0.0f; + m_lastAttackTime = -1000.0f; + unsigned int flags = seen ? SENSE_SEEN : SENSE_HEARD; + if (sided) + flags |= SENSE_SIDED; + if (!seen) + flags |= SENSE_INDIRECT; + if (!seen) + flags |= SENSE_HEARD_NOW; + m_lastSense = SENSE_SEEN; + m_lastSeenTime = 0.0f; + m_lastPositionTime = 0.0f; + m_flags = flags; + m_hasContact = false; +} + +// ELF 0x1A2980 (D1; D2 0x1A2990): `push ebp; mov ebp,esp; pop ebp; ret`. +SensedObject::~SensedObject() +{ +} + +// ELF 0x1A29A0: `mov $7,%eax; L: dec %eax; jns L` - eight passes, no body left. +void SensedObject::initStrengths() +{ + for (int i = 7; i >= 0; --i) + { + } +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SensedObject.h b/Code/BF2/AI/AIDLL/AI/AIBot/SensedObject.h new file mode 100644 index 000000000..9e84de0d1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SensedObject.h @@ -0,0 +1,69 @@ +// One thing a bot has seen or heard: BotSenses keeps one record per handle (the map at +112) and +// threads it through the seen list (+56) and the heard list (+76). +// Evidence: libaidll.so 1.5.3153 (ia-32). Attested file AIBot/SensedObject.cpp (FILE symbol +// beside 0x1A29C0); constructors 0x1A2860 / 0x1A28F0, destructors 0x1A2980 / 0x1A2990 (empty, +// not virtual: every owner deletes through `~SensedObject(); operator delete`), initStrengths +// 0x1A29A0. Size 0x68 (`operator new(0x68)` in BotSenses::event_seenObject / event_heardObject). + +#ifndef AI_AIDLL_AI_AIBOT_SENSEDOBJECT_H // [INFERRED] guard style +#define AI_AIDLL_AI_AIBOT_SENSEDOBJECT_H + +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +class SensedObject +{ +public: + // The flag word (+0x4C) and the "last sense" word (+0x50) share these values: every writer + // that sets a bit also stores the same value to +0x50. [INFERRED] names; the bits are attested. + enum SenseFlag + { + SENSE_HEARD = 0x01, // in the heard list; updateHearing / event_heardObject + SENSE_SEEN = 0x02, // in the seen list; event_seenObject sets, forgetObject clears + SENSE_SIDED = 0x04, // the constructor's third argument (the object's side != 0) + SENSE_INDIRECT = 0x08, // seen, but not directly yet (event_seenObject's `direct`) + SENSE_HEARD_NOW = 0x10, // heard during the last hearing pass + SENSE_FLAG40 = 0x40 // event_seenObject with its last argument false; meaning [UNRESOLVED] + }; + + // ELF 0x1A2860. The flag word is built as (seen ? SEEN : HEARD) | (sided ? SIDED : 0) and, for + // a heard record, INDIRECT | HEARD_NOW. +0x10, +0x14, +0x34 and +0x44 are not written here. + SensedObject(unsigned int handle, bool seen, bool sided); + ~SensedObject(); // ELF 0x1A2980: empty + + // ELF 0x1A29A0: a counted loop (8 passes) whose body the compiler removed; no caller in the image. + void initStrengths(); + + /* +0x00 */ unsigned int m_handle; + /* +0x04 */ Vec3 m_seenPosition; // event_seenObject's position argument + /* +0x10 */ unsigned int m_seenPart; // event_seenObject's third argument (-1 from event_projectile) + /* +0x14 */ double m_firstSeenTime; // event_seenObject, new record + /* +0x1C */ Vec3 m_lastPosition; // the information's position at the last sense + /* +0x28 */ Vec3 m_lastSeenPosition; // the information's position when last seen + /* +0x34 */ double m_lastSensedTime; // seen or heard + /* +0x3C */ double m_lastAttackTime; // ctor -1000.0; event_projectile: the game time + // +0x44/+0x48: the fire patterns' per-target state. Writers: BBPFireInfantery::createPlan sets + // both to 0 together with flag 0x20 (0x25CC43/0x25CC4D) and +0x48 = -100 when no weapon fits + // (0x25F36E); BBPFire2d::createPlan sets flag 0x20 and +0x48 = -100 (0x24AF3A). Readers: + // BBFire::calculateUrgency (0x208B58) and BBFireLargeBore::calculateUrgency (0x2118A8) skip the + // target when flag 0x20 is set and +0x48 < 0 (signed: js). BAPANotifyBot::execute (ELF 0x1DD800) + // adds its integer plan variable to +0x44 when its notification type is zero. + // AICollisionHandler::shooterUpdate (0x382B70) increments +0x48 for every confirmed hit. + // [CHOSEN, not recovered] names (ai-w1-e-fire, merged with D's m_unresolved44 use). + /* +0x44 */ int m_unresolved44; // [UNRESOLVED] notification accumulator meaning + /* +0x48 */ int m_fireRating; // < 0: no weapon can engage this target + /* +0x4C */ unsigned int m_flags; // SenseFlag bits + /* +0x50 */ int m_lastSense; // ctor 2; the SenseFlag value last set + /* +0x54 */ double m_lastSeenTime; // ctor 0 + /* +0x5C */ double m_lastPositionTime; // ctor 0; when +0x1C was written + /* +0x64 */ bool m_hasContact; // Information::addContact was called for this record +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOT_SENSEDOBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgent.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgent.cpp index eddc03f29..8eda2bc3f 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgent.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgent.cpp @@ -1,10 +1,17 @@ -// [FRONTIER] Remaining methods stop by name until implemented. // [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining SensingAgent operations. #include "SensingAgent.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1BF770, __tcf_0 0x1BF7D0, _GLOBAL__I 0x1BF800). +#include + +#include + #include "BotSenses.h" #include "../AIPlanInterpreter/BAPContext.h" +#include "../AIBotActionPlan/BAPStatement.h" +#include "../AIPlanInterpreter/PlanInterpreter.h" #include "SensingAgentPatterns.h" // ISensingAgentPattern::reset - the shared patterns #include "../Main/AIRandom.h" // the per-life reaction time #include "../Main/AISettingsInterfaces.h" @@ -12,7 +19,24 @@ #include "../../../AIInterface/BFKnowledge/BFTimer.h" // IBFTimer::getGameTime #include #include "../AIUtils/checkPointer.h" +#include "BotMain.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../../Math/Mat4.h" +#include #include "../Main/AIDllFrontier.h" +#include "../AIKnowledge/FireObject.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../../IO/Input/PlayerInput.h" +#include "../../../../Core/Debug.h" +#include "../AIBotActionPlan/BotScript.h" +#include "SensedObject.h" +#include "../DrawPrimitives/DPManager.h" +#include namespace dice { namespace hfe { @@ -23,15 +47,18 @@ SensingAgent::SensingAgent(BotMain* owner, unsigned char /*behaviourCount*/) : m_flag134(false) , m_plan(0) { - for (int i = 0; i < 6; ++i) - m_zero0[i] = 0; // +0..+20 - for (int i = 0; i < 3; ++i) - { - m_zero32[i] = 0; // +32, +36, +40 - m_zero64[i] = 0; // +64, +68, +72 - } - for (int i = 0; i < 5; ++i) - m_zero80[i] = 0; // +80..+96 + // +0..+20: the two focus vectors, empty. + m_focusPosition.x = 0.0f; // +32, +36, +40 + m_focusPosition.y = 0.0f; + m_focusPosition.z = 0.0f; + m_planDirection.x = 0.0f; // +64, +68, +72 + m_planDirection.y = 0.0f; + m_planDirection.z = 0.0f; + m_moveDirection.x = 0.0f; // +80..+96 zeroed + m_moveDirection.y = 0.0f; + m_sprintFocus.x = 0.0f; + m_sprintFocus.y = 0.0f; + m_sprintFocus.z = 0.0f; // the mechanism this agent steers. , and it takes the bot rather than the agent // so `BotSenses` answers to the bot directly and this object is a policy layer over it. @@ -48,24 +75,21 @@ SensingAgent::SensingAgent(BotMain* owner, unsigned char /*behaviourCount*/) reset(); } -// [FRONTIER] Remaining sensing-plan operations require implementation. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. - +// ELF 0x1BBB50: the senses (+0x68) and the BAP context (+0x90) are deleted; the plan is not. +// The vectors at +0, +0xC and +0x30 are destroyed as members. SensingAgent::~SensingAgent() { - BF2_AI_FRONTIER("dice::hfe::ai::SensingAgent::~SensingAgent"); + delete m_senses; + delete m_bapContext; } // Deletes the owned plan and marks planning state for refresh. -// [FRONTIER] Plan destruction stops until the required statement type is implemented. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. void SensingAgent::deletePlan() { if (m_plan) { - // Retail here is `delete m_plan;` - vtable byte-slot +8, the deleting destructor. See the - // block above for why this tree cannot write it yet. - BF2_AI_FRONTIER("dice::hfe::ai::SensingAgent::deletePlan (non-null plan)"); + // `delete m_plan;` - vtable byte-slot +8, the deleting destructor. + delete m_plan; m_plan = 0; } m_flag140 = true; @@ -75,7 +99,7 @@ void SensingAgent::deletePlan() void SensingAgent::clearPlanTargetInformation() { m_planTarget60 = 0; - m_planTarget76 = 0; + m_planWeight = 0.0f; } // Resets sensing state and draws a new reaction delay in [0.5, 1.0). @@ -104,11 +128,11 @@ void SensingAgent::reset() deletePlan(); m_int24 = -1; - m_int28 = 0; + m_focusWeight = 0.0f; m_flag44 = false; m_flag148 = true; - m_zero80[0] = 0; // +80 - m_zero80[1] = 0; // +84 + m_moveDirection.x = 0.0f; // +80 + m_moveDirection.y = 0.0f; // +84 // through the buffer, and the size is not touched. See the block above. for (unsigned q = 0; q <= 7; ++q) @@ -122,7 +146,7 @@ void SensingAgent::reset() m_double124 = 0.0; // Chooses a reaction time in [0.5, 1.0), preserving the arithmetic order. - m_reactionTime = 0.5f + AIRandom::m_instance->nextFloat() * (1.0f - 0.5f); + m_currentPeriod = 0.5f + AIRandom::m_instance->nextFloat() * (1.0f - 0.5f); m_senses->reset(); } @@ -140,6 +164,866 @@ void SensingAgent::setOverride(bool value) } } +namespace { + +// The inline Vec2 normalisation every caller below spells out: left alone within FLT_EPSILON of +// unit length, otherwise scaled by 1 / sqrt(length^2); `zeroIsFalse` reports a degenerate vector +// (computeQuadrantsFromPosition returns false there; quadInFocus zeroes it). +bool normaliseXZ(float& x, float& y, bool zeroIsFalse) +{ + const float lengthSq = y * y + x * x; + if (std::fabs(lengthSq - 1.0f) >= 1.1920929e-07f) + { + if (std::fabs(lengthSq) < 1.4210855e-14f) + { + if (zeroIsFalse) + return false; + x = 0.0f; + y = 0.0f; + return true; + } + const float inverse = 1.0f / std::sqrt(lengthSq); + x = x * inverse; + y = inverse * y; + } + return true; +} + +} // namespace + +// ELF 0x1BE110. The point is the camera's row 2 (forward) plus row 3 (position). +void SensingAgent::setQuadSeen() +{ + const Mat4& camera = *static_cast(m_bot->getPlayer()->getCameraTransformation()); + Vec3 ahead; + ahead.x = camera.m[8] + camera.m[12]; + ahead.y = camera.m[9] + camera.m[13]; + ahead.z = camera.m[10] + camera.m[14]; + int quadrants[2]; + if (!computeQuadrantsFromPosition(ahead, quadrants)) + return; + for (int i = 0; i < 2; ++i) + { + if (quadInFocus(quadrants[i])) + { + m_quadrantWeights[quadrants[i]] = 0.0f; + if (m_plan && m_flag148 && quadrants[i] == m_int24) + m_flag44 = true; + } + } +} + +// ELF 0x1BD860. The XZ offset from the camera position (row 3), normalised, is dotted with the +// diagonal axes (+-0.70710677) for the first quadrant and with the world axes for the second. +bool SensingAgent::computeQuadrantsFromPosition(const Vec3& position, int* quadrants) const +{ + const Mat4& camera = *static_cast(m_bot->getPlayer()->getCameraTransformation()); + float x = position.x - camera.m[12]; + float y = position.z - camera.m[14]; + if (!normaliseXZ(x, y, true)) + return false; + const float s = 0.70710677f; + const float b = y * -s + x * s; + if (0.0f <= x * s + y * s) + quadrants[0] = 0.0f <= b ? 1 : 0; + else + quadrants[0] = (b < 0.0f) + 2; + const float d = y * 0.0f + x * 1.0f; + if (0.0f <= x * 0.0f + y * 1.0f) + quadrants[1] = (d < 0.0f) * 3 + 4; + else + quadrants[1] = (d < 0.0f) + 5; + return true; +} + +// ELF 0x1BDA60. The camera is read through the bot's player field (+0x9C) directly. +bool SensingAgent::quadInFocus(int quadrant) const +{ + if (quadrant < 0) + return false; + const Mat4& camera = *static_cast(m_bot->m_player->getCameraTransformation()); + float x = camera.m[8]; + float y = camera.m[10]; + normaliseXZ(x, y, false); + Vec2 direction; + direction.x = 0.0f; + direction.y = 0.0f; + getQuadPosition(quadrant, direction); + return 0.9848f < x * direction.x + y * direction.y; +} + +// ELF 0x1BDBC0: an eight-way jump table; the default reports through Debug (type 6, line 770). +void SensingAgent::getQuadPosition(int quadrant, Vec2& position) const +{ + const float s = 0.70710677f; + switch (quadrant) + { + case 0: position.x = 0.0f; position.y = 1.0f; break; + case 1: position.x = 1.0f; position.y = 0.0f; break; + case 2: position.x = 0.0f; position.y = -1.0f; break; + case 3: position.x = -1.0f; position.y = 0.0f; break; + case 4: position.x = s; position.y = s; break; + case 5: position.x = s; position.y = -s; break; + case 6: position.x = -s; position.y = -s; break; + case 7: position.x = -s; position.y = s; break; + default: + Debug(DebugTypeError, __FILE__, __LINE__, "") << "Bad quadrant value " << quadrant; + break; + } +} + +// ELF 0x1BE0A0: also drops the stored override value. +void SensingAgent::disallowOverride(bool b) +{ + m_flag122 = false; + m_flag132 = b; +} + +// ELF 0x1BF230 (130 bytes). Both result flags start false here (BotMain's `ok` starts true); +// a failed or unfinished plan sets +140 and clears the plan targets. +void SensingAgent::executePlan() +{ + bool ok = false; + bool failed = false; + // ELF 0x1BF258: m_bot->getPlanInterpreter() vtable +8 execute(m_plan, m_bot, &ok, &failed). + m_bot->getPlanInterpreter()->execute(m_plan, m_bot, ok, failed); + m_flag140 = failed || !ok; + if (m_flag140) + clearPlanTargetInformation(); +} + +namespace { + +// Bot +4 is the bound PlayerInput; an unmapped input reads as zero (`(mappingFlags >> i) & 1`, +// e.g. checkForPlanInvalidation 0x1BD0F7 `shrdl $0x3` then `flds 0xc(%ecx)`). +float boundInput(const io::PlayerInput* input, io::PlayerInputMap index) +{ + return ((input->mappingFlags >> static_cast(index)) & 1ULL) ? input->inputs[index] + : 0.0f; +} + +// The inline Vec3 normalisation of createPlan: left alone within FLT_EPSILON of unit length, +// zeroed within FLT_EPSILON of zero (not FLT_EPSILON^2 as the Vec2 copies above). +void normalise3(Vec3& v) +{ + const float lengthSq = v.x * v.x + v.y * v.y + v.z * v.z; + if (std::fabs(lengthSq - 1.0f) >= 1.1920929e-07f) + { + if (std::fabs(lengthSq) >= 1.1920929e-07f) + { + const float inverse = 1.0f / std::sqrt(lengthSq); + v.x = v.x * inverse; + v.y = v.y * inverse; + v.z = inverse * v.z; + } + else + { + v.x = 0.0f; + v.y = 0.0f; + v.z = 0.0f; + } + } +} + +// The vehicle's forward (transformation row 2), turned about Y by the control info's camera DOF +// offset when it is positive (withinCamView 0x1BD5DA, createPlan): row vector times the rotation. +Vec3 cameraForward(BotMain* bot, Information* equipment) +{ + const float offset = equipment->getControlInfo()->getCameraRelativeDofRotationOffset(); + const Mat4& transformation = bot->getPlayer()->getCurrentVehicle()->getTransformation(); + Vec3 forward; + forward.x = transformation.m[8]; + forward.y = transformation.m[9]; + forward.z = transformation.m[10]; + if (0.0f < offset) + { + Mat4 rotation; + for (int i = 0; i < 16; ++i) + rotation.m[i] = 0.0f; + rotation.m[0] = 1.0f; + rotation.m[5] = 1.0f; + rotation.m[10] = 1.0f; + rotation.m[15] = 1.0f; + setRotateYDeg(rotation, offset * 57.295776f); + const Vec3 f = forward; + forward.x = f.z * rotation.m[8] + f.x * rotation.m[0] + f.y * rotation.m[4]; + forward.y = f.x * rotation.m[1] + f.y * rotation.m[5] + f.z * rotation.m[9]; + forward.z = f.x * rotation.m[2] + f.y * rotation.m[6] + f.z * rotation.m[10]; + } + return forward; +} + +// The angle between `direction` and the quadrant's unit direction (dot clamped to [-1, 1]); +// isForward / isBehind share it. +float angleToQuadrant(const SensingAgent* agent, int quadrant, const Vec2& direction) +{ + Vec2 q; + q.x = 0.0f; + q.y = 0.0f; + agent->getQuadPosition(quadrant, q); + float dot = direction.x * q.x + direction.y * q.y; + if (dot < -1.0f) + dot = -1.0f; + else if (dot > 1.0f) + dot = 1.0f; + return std::acos(dot); +} + +// AIRandom::nextFloat inline with a range: (hi - lo) * r + lo (calculateCurrentPeriod 0x1BE31F). +float randomBetween(float lo, float hi) +{ + return (hi - lo) * AIRandom::m_instance->nextFloat() + lo; +} + +// computeTargetQuadrant's random quadrant: floor(r * 2^-32 * 7 + 0.5) in x87 precision, through a +// float, truncated (0x1BCE7D..0x1BCEB1). +int randomQuadrant() +{ + const double r = static_cast(AIRandom::m_instance->next()); + const float rounded = static_cast( + std::floor(r * static_cast(2.3283064e-10f) * 7.0 + 0.5)); + return static_cast(rounded); +} + +} // namespace + +// ELF 0x1BBD30 (1130 bytes), static double waitTime = 2.0 (0x4B7448). +void SensingAgent::update() +{ + static double waitTime = 2.0; + + Information* const equipment = informationManager->getInformation(m_bot->m_currentEquipment); + if (!equipment) + return; + if (m_bot->getManDown()) + return; + ISensingAgentPattern* const pattern = + static_cast(CommonSingletonServer::m_iaiSettings) + ->getSensingAgentPattern(equipment->getUnit()->getEquipmentType()); + if (!pattern) + { + deletePlan(); + return; + } + if (m_flag122) + deletePlan(); + const double now = + static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + // An override (a plan aiming by itself) holds the sensing agent off for waitTime seconds. + if (m_flag122) + { + if (now - m_double124 > waitTime) + m_flag122 = false; + return; + } + if (now < m_double112) + m_double112 = now; + const double elapsed = now - m_double112; + + Information* const current = informationManager->getInformation(m_bot->getCurrentEquipment()); + bool turnedAway = false; + if (current->isOfType(ITSoldier) && m_flag133 + && !isForward(m_int24, m_moveDirection)) + turnedAway = true; + if (!(elapsed >= m_currentPeriod || m_flag120 || m_flag140 == true) && !turnedAway) + return; + if (turnedAway) + m_flag133 = false; + + const int pose = equipment->getSoldierPose(); + bool lookAlongMove = false; + if ((pose == 3 && !m_flag120) || pose == 4) + lookAlongMove = true; + if (!m_bot->isFireAllowed() || lookAlongMove) + { + Vec3 direction; + direction.x = m_moveDirection.x; + direction.y = current->getTransformation().m[9]; + direction.z = m_moveDirection.y; + createDirPlan(direction, pattern); + return; + } + + Vec2 direction; + direction.x = 0.0f; + direction.y = 0.0f; + if (!m_flag120) + updateQuadTimeUrgencies(direction, turnedAway); + QuadrantInformation quadrant; + quadrant.position.x = 0.0f; + quadrant.position.y = 0.0f; + quadrant.position.z = 0.0f; + Vec2 opposite; + opposite.x = -direction.x; + opposite.y = -direction.y; + calcTargetQuadFromObjects(&quadrant, opposite); + calculateCurrentPeriod(quadrant, current, direction); + if (m_flag120) + deletePlan(); + else + m_flag121 = false; + m_flag120 = false; + m_double112 = now; + checkForPlanInvalidation(quadrant, turnedAway); + if (m_flag140 == true) + createPlan(pattern, quadrant); + clearInformation(); +} + +// ELF 0x1BC1A0. A soldier looks away from its move direction (+0x50); in a vehicle the vehicle's +// backward XZ (transformation row 2, negated) is used. Quadrants the bot is not facing gain +// urgency over time (0.0125 per update; 0.05 ahead, 0.25 ahead when turned away); a primary +// mobile vehicle clears the quadrants behind it. +void SensingAgent::updateQuadTimeUrgencies(Vec2& direction, bool turnedAway) +{ + Information* const current = informationManager->getInformation(m_bot->getCurrentEquipment()); + if (!current->isOfType(ITSoldier)) + { + Information* const primary = + informationManager->getInformation(current->getPrimaryObject(m_bot->getSide())); + const Mat4& transformation = primary->getTransformation(); + direction.x = -transformation.m[8]; + direction.y = -transformation.m[10]; + } + else + { + Vec2 move = m_moveDirection; + if (move.x * move.x + move.y * move.y < 0.01f) + return; + direction.x = -move.x; + direction.y = -move.y; + } + bool clearBehind = false; + if (!current->isOfType(ITSoldier) && current->hasMobile() && current->isPrimary()) + clearBehind = true; + for (int q = 0; q < 8; ++q) + { + if (clearBehind && isBehind(q, direction)) + { + m_quadrantWeights[q] = 0.0f; + continue; + } + Vec2 ahead; + ahead.x = -direction.x; + ahead.y = -direction.y; + if (!isForward(q, ahead)) + m_quadrantWeights[q] = m_quadrantWeights[q] + 0.0125f; + else if (turnedAway) + m_quadrantWeights[q] = m_quadrantWeights[q] + 0.25f; + else + m_quadrantWeights[q] = m_quadrantWeights[q] + 0.05f; + } +} + +// ELF 0x1BC410. The direction argument is not read. +void SensingAgent::calcTargetQuadFromObjects(QuadrantInformation* info, const Vec2& /*direction*/) +{ + evaluateSensedObjects(); + evaluateFireObjects(); + std::pair > zero; + zero.first = 0.0f; + zero.second.first.x = 0.0f; + zero.second.first.y = 0.0f; + zero.second.first.z = 0.0f; + zero.second.second = 0; + QuadrantWeights weights(8, zero); // operator new(0xA0): 8 x 20 bytes + getQuadrantWeights(weights); + computeTargetQuadrant(weights, info); +} + +// ELF 0x1BC5B0. Every living sensed object is a candidate: seen directly 0.5; seen indirectly +// 0.25 when heard or a fire target (flag 0x20, BBPFireInfantery), else 0; not seen 0.3 when +// heard, + 0.25 for a fire target. The weight is scaled by the information's getSecurity(). +void SensingAgent::evaluateSensedObjects() +{ + FocusInformation empty; + empty.weight = 0.0f; + empty.position.x = 0.0f; + empty.position.y = 0.0f; + empty.position.z = 0.0f; + m_sensedFocus.resize(0, empty); // the image's resize: _M_fill_insert / erase + const std::map& sensed = m_senses->getSensedObjects(); + for (std::map::const_iterator it = sensed.begin(); + it != sensed.end(); ++it) + { + SensedObject* const object = it->second; + Information* const info = informationManager->getInformation(object->m_handle); + if (!info) + continue; + IPIPhysical* const physical = info->getPhysical(); + if (physical && !(0.0f < physical->getHealth())) + continue; + float weight = 0.0f; + const unsigned int flags = object->m_flags; + if ((flags & SensedObject::SENSE_SEEN) == 0) + { + if (flags & SensedObject::SENSE_HEARD) + weight = 0.3f; + if (flags & 0x20) + weight = weight + 0.25f; + } + else if (flags & SensedObject::SENSE_INDIRECT) + { + if ((flags & 0x20) || (flags & SensedObject::SENSE_HEARD)) + weight = weight + 0.25f; + } + else + { + weight = 0.5f; + } + FocusInformation focus; + focus.weight = weight * info->getSecurity(); + focus.position = info->getPosition(); + m_sensedFocus.push_back(focus); + } +} + +// ELF 0x1BC7E0. A friendly shot draws the eye to where it lands (FireObject +0x14), weight 0.5; +// an enemy shot to the shooter, 0.7 for 5 s, then 0.5, and books a re-plan once (+0x78 / +0x79). +void SensingAgent::evaluateFireObjects() +{ + FocusInformation empty; + empty.weight = 0.0f; + empty.position.x = 0.0f; + empty.position.y = 0.0f; + empty.position.z = 0.0f; + m_fireFocus.resize(0, empty); + const double now = + static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + std::list* const fire = m_senses->getIncommingFire(); + for (std::list::iterator it = fire->begin(); it != fire->end(); ++it) + { + Information* const info = informationManager->getInformation(it->second); + if (!info) + continue; + FireObject* const shot = it->first; + FocusInformation focus; + float weight; + if (info->getSide() == m_bot->getSide()) + { + focus.position = shot->getTarget(); + weight = 0.5f; + } + else + { + if (!m_flag121) + { + m_flag120 = true; + m_flag121 = true; + } + weight = 0.5f; + if (now - shot->getTime() < 5.0) + weight = 0.7f; + focus.position = info->getPosition(); + } + focus.weight = info->getSecurity() * weight; + m_fireFocus.push_back(focus); + } +} + +// ELF 0x1BCA90. Each candidate adds its weight and position to both of its quadrants; then the +// time urgencies (+0x30) are added and the positions averaged. +void SensingAgent::getQuadrantWeights(QuadrantWeights& weights) +{ + const std::vector* const lists[2] = { &m_sensedFocus, &m_fireFocus }; + for (int l = 0; l < 2; ++l) + { + for (std::vector::const_iterator it = lists[l]->begin(); + it != lists[l]->end(); ++it) + { + int quadrants[2]; + if (!computeQuadrantsFromPosition(it->position, quadrants)) + continue; + for (int k = 0; k < 2; ++k) + { + std::pair >& w = weights[quadrants[k]]; + w.first = it->weight + w.first; + w.second.first.x = it->position.x + w.second.first.x; + w.second.first.y = it->position.y + w.second.first.y; + w.second.first.z = it->position.z + w.second.first.z; + w.second.second = w.second.second + 1; + } + } + } + for (unsigned int q = 0; q < 8; ++q) + { + std::pair >& w = weights[q]; + w.first = m_quadrantWeights[q] + w.first; + if (w.second.second != 0) + { + const float inverse = 1.0f / static_cast(w.second.second); + w.second.first.x = w.second.first.x * inverse; + w.second.first.y = w.second.first.y * inverse; + w.second.first.z = inverse * w.second.first.z; + } + } +} + +// ELF 0x1BCD50. The heaviest feasible quadrant wins; with none, up to seven random tries for a +// feasible one, at weight 0.1 and no position. The getQuadPosition calls' results are unused. +void SensingAgent::computeTargetQuadrant(const QuadrantWeights& weights, QuadrantInformation* info) +{ + info->quadrant = -1; + info->weight = 0.0f; + float best = 0.0f; + int q = 0; + for (QuadrantWeights::const_iterator it = weights.begin(); it != weights.end(); ++it, ++q) + { + Vec2 unused; + unused.x = 0.0f; + unused.y = 0.0f; + getQuadPosition(q, unused); + if (best < it->first && targetFeasible(q)) + { + best = it->first; + info->weight = best; + info->quadrant = q; + info->position = it->second.first; + } + } + if (info->quadrant < 0) + { + unsigned int tries = 0; + info->quadrant = randomQuadrant(); + while (!targetFeasible(info->quadrant) && tries <= 5) + { + ++tries; + info->quadrant = randomQuadrant(); + Vec2 unused; + unused.x = 0.0f; + unused.y = 0.0f; + getQuadPosition(info->quadrant, unused); + } + info->weight = 0.1f; + info->position.x = 0.0f; + info->position.y = 0.0f; + info->position.z = 0.0f; + } +} + +// ELF 0x1BCFF0. Vehicles and borrowed armament never keep a sensing plan. Otherwise the plan goes +// when its focus is out of the camera's reach, a quadrant plan's quadrant changed, a target plan's +// target is still sensed (sic: `test %eax,%eax; je` keeps the plan only when the lookup is null), +// a pose-3 soldier throttles backwards, or `force`. +void SensingAgent::checkForPlanInvalidation(const QuadrantInformation& info, bool force) +{ + Information* const equipment = informationManager->getInformation(m_bot->m_currentEquipment); + bool vehicle = false; + if (equipment->isOfType(ITHelicopter) || equipment->isOfType(ITAir)) + vehicle = true; + if (equipment->getUnit()->mustBorrowArmament() || vehicle) + { + deletePlan(); + return; + } + bool invalid = false; + if (!targetFeasible(m_int24)) + invalid = true; + if (m_flag148) + { + if (info.quadrant != m_int24) + { + m_flag44 = false; + invalid = true; + } + } + else if (m_bot->getSensedObjectFromHandle(m_planTarget60)) + { + invalid = true; + } + if (equipment->getSoldierPose() == 3 && boundInput(m_bot->getInput(), io::PIThrottle) < 0.0f) + invalid = true; + if (force) + invalid = true; + if (m_plan && invalid) + deletePlan(); +} + +// ELF 0x1BD170. A quadrant is tested by its unit direction; quadrant < 0 means the plan target, +// whose world position's XZ is passed as is (not relative to the bot). +bool SensingAgent::targetFeasible(int quadrant) const +{ + Vec2 direction; + if (quadrant < 0) + { + Information* const target = informationManager->getInformation(m_planTarget60); + if (!target) + return false; + const Vec3& position = target->getPosition(); + direction.x = position.x; + direction.y = position.z; + } + else + { + direction.x = 0.0f; + direction.y = 0.0f; + getQuadPosition(quadrant, direction); + } + return withinCamView(direction); +} + +// ELF 0x1BD250: within 20 degrees (0.34906584 rad) of the quadrant. +bool SensingAgent::isForward(int quadrant, const Vec2& direction) const +{ + if (direction.y * direction.y + direction.x * direction.x < 0.01f || quadrant < 0) + return false; + return angleToQuadrant(this, quadrant, direction) < 0.34906584f; +} + +// ELF 0x1BD340: within 90 degrees of the quadrant. +bool SensingAgent::isBehind(int quadrant, const Vec2& direction) const +{ + if (direction.y * direction.y + direction.x * direction.x < 0.01f || quadrant < 0) + return false; + return angleToQuadrant(this, quadrant, direction) < 1.5707964f; +} + +// ELF 0x1BD430. The camera's XZ forward against `direction`: inside the control info's relative +// rotation limits (max on the left of the forward, min on the right); without limits always. +bool SensingAgent::withinCamView(const Vec2& direction) const +{ + Information* const equipment = informationManager->getInformation(m_bot->m_currentEquipment); + IPIControlInfo* const control = equipment->getControlInfo(); + const Vec3 forward3 = cameraForward(m_bot, equipment); + float x = forward3.x; + float y = forward3.z; + normaliseXZ(x, y, false); + float dot = y * direction.y + x * direction.x; + if (dot < -1.0f) + dot = -1.0f; + else if (dot > 1.0f) + dot = 1.0f; + const float angle = std::acos(dot); + const Vec3& maxRotation = control->getCameraRelativeMaxRotation(); + const Vec3& minRotation = control->getCameraRelativeMinRotation(); + if (maxRotation.x == 0.0f && minRotation.x == 0.0f) + return true; + if (y * direction.x - x * direction.y <= 0.0f) + return minRotation.x <= -angle; + return angle <= maxRotation.x; +} + +// ELF 0x1BE020: the plan target and the candidates' weights (positions are kept). +void SensingAgent::clearInformation() +{ + clearPlanTargetInformation(); + for (std::vector::iterator it = m_sensedFocus.begin(); it != m_sensedFocus.end(); ++it) + it->weight = 0.0f; + for (std::vector::iterator it = m_fireFocus.begin(); it != m_fireFocus.end(); ++it) + it->weight = 0.0f; +} + +// ELF 0x1BE250. The re-plan period (+0x98), drawn from a range: vehicle or borrowed armament +// [1, 1.5); no look direction [1.5, 2); standing still a soldier [3, 4), else [7, 10); moving +// with the focus ahead [7, 10), else a soldier [1.5, 2), a vehicle [5, 7). +void SensingAgent::calculateCurrentPeriod(const QuadrantInformation& info, Information* equipment, + const Vec2& direction) +{ + const io::PlayerInput* const input = m_bot->getInput(); + if (!equipment->getUnit()) + return; + if (equipment->getUnit()->mustBorrowArmament() || equipment->isOfType(ITHelicopter) || equipment->isOfType(ITAir)) + { + m_currentPeriod = randomBetween(1.0f, 1.5f); + return; + } + Vec2 look = direction; + if (!(0.01f <= look.y * look.y + look.x * look.x)) + { + m_currentPeriod = randomBetween(1.5f, 2.0f); + return; + } + const bool soldier = equipment->isOfType(ITSoldier); + if (boundInput(input, io::PIThrottle) < 0.01f && boundInput(input, io::PIYaw) < 0.01f) + { + m_currentPeriod = soldier ? randomBetween(3.0f, 4.0f) : randomBetween(7.0f, 10.0f); + return; + } + look.x = -look.x; + look.y = -look.y; + const bool forward = isForward(info.quadrant, look); + if (forward) + m_currentPeriod = randomBetween(7.0f, 10.0f); + else if (soldier) + m_currentPeriod = randomBetween(1.5f, 2.0f); + else + m_currentPeriod = randomBetween(5.0f, 7.0f); +} + +// ELF 0x1BE850. The previous plan is handed to the pattern first (+4 = pattern), which may reuse +// it. Vehicles and borrowed armament look along the (camera-turned) vehicle forward, a vehicle +// slightly down (-0.4 for flag 0x10, else -0.7). Otherwise the stronger of the plan direction +// (+0x4C weight, or any move) and the focus quadrant wins: a quadrant plan looks at the quadrant's +// mean position (or its direction at eye height), a direction / target plan at the plan's. +void SensingAgent::createPlan(ISensingAgentPattern* pattern, const QuadrantInformation& info) +{ + if (m_plan) + m_plan->mpOwner = pattern; + Information* const equipment = informationManager->getInformation(m_bot->m_currentEquipment); + bool vehicle = false; + if (equipment->isOfType(ITHelicopter) || equipment->isOfType(ITAir)) + vehicle = true; + if (equipment->getUnit()->mustBorrowArmament() || vehicle) + { + const Vec3 forward = cameraForward(m_bot, equipment); + if (vehicle) + { + Vec3 down; + down.x = forward.x; + down.y = equipment->isOfType(ITAir) ? -0.4f : -0.7f; + down.z = forward.z; + createDirPlan(down, pattern); + } + else + { + createDirPlan(forward, pattern); + } + m_flag133 = false; + return; + } + + if (0.01f <= m_moveDirection.y * m_moveDirection.y + m_moveDirection.x * m_moveDirection.x + || m_planWeight <= info.weight) + { + if (info.quadrant < 0) + { + Debug(DebugTypeError, __FILE__, __LINE__, "") << "Sensing agent plan has nothing to look at!"; + } + else + { + Vec3 direction; + const Mat4& transformation = equipment->getTransformation(); + if (info.position.y != 0.0f) + { + direction.x = info.position.x - transformation.m[12]; + direction.y = info.position.y - transformation.m[13]; + direction.z = info.position.z - transformation.m[14]; + } + else + { + Vec2 q; + q.x = 0.0f; + q.y = 0.0f; + getQuadPosition(info.quadrant, q); + direction.x = q.x; + direction.y = transformation.m[9]; + direction.z = q.y; + } + normalise3(direction); + m_int24 = info.quadrant; + m_focusWeight = info.weight; + m_plan = pattern->createPlan(this, m_bot, direction); + m_flag148 = true; + m_int24 = info.quadrant; + m_focusWeight = info.weight; + m_focusPosition = info.position; + m_flag133 = isForward(m_int24, m_moveDirection); + } + } + else + { + if (m_planTarget60 == m_bot->getCurrentEquipment()) + { + Vec3 direction = m_planDirection; + normalise3(direction); + m_plan = pattern->createPlan(this, m_bot, direction); + m_flag148 = false; + } + else + { + m_plan = pattern->createPlan(this, m_bot, m_planTarget60); + m_flag148 = false; + m_int24 = -1; + m_focusWeight = 0.0f; + } + m_flag133 = false; + } + if (m_plan) + m_plan->mpOwner = this; +} + +// ELF 0x1BF120: the previous plan's owner becomes the pattern, the new plan's this agent. +void SensingAgent::createDirPlan(const Vec3& direction, ISensingAgentPattern* pattern) +{ + if (m_plan) + m_plan->mpOwner = pattern; + m_plan = pattern->createPlan(this, m_bot, direction); + if (m_plan) + m_plan->mpOwner = this; +} + +// ELF 0x1BF180: IAISettings +0x8C getSensingAgentNullPattern, target handle 0. +void SensingAgent::createNullPlan() +{ + ISensingAgentPattern* const pattern = + static_cast(CommonSingletonServer::m_iaiSettings)->getSensingAgentNullPattern(); + if (m_plan) + m_plan->mpOwner = pattern; + m_plan = pattern->createPlan(this, m_bot, 0u); + if (m_plan) + m_plan->mpOwner = this; +} + +void SensingAgent::insertPlanDirectionInformation(float weight, const Vec3& direction, bool flag) +{ + m_planDirection = direction; + m_planTarget60 = m_bot->getCurrentEquipment(); + m_planWeight = weight; + m_flag120 = flag; +} + +// ELF 0x1BF2C0. Draws the selected quadrant/target, camera direction and soldier movement. +// The current-equipment and positive-weight target lookups are deliberately unchecked. +void SensingAgent::drawSensingAgentDebugStuff() +{ + Information* const equipment = informationManager->getInformation(m_bot->m_currentEquipment); + const Vec3& position = equipment->getPosition(); + if (m_int24 >= 0) + { + const float axial = 1.0f * 10.0f; + const float zero = 0.0f * 10.0f; + const float diagonal = 0.7071067690849304f * 10.0f; + const float negativeDiagonal = -0.7071067690849304f * 10.0f; + const Vec3 directions[8] = { + {zero, 3.0f, axial}, {axial, 3.0f, zero}, + {-zero, 3.0f, -axial}, {-axial, 3.0f, -zero}, + {diagonal, 3.0f, diagonal}, {diagonal, 3.0f, negativeDiagonal}, + {-diagonal, 3.0f, -diagonal}, {-diagonal, 3.0f, -negativeDiagonal} + }; + const Vec3 end = { position.x + directions[m_int24].x, + position.y + directions[m_int24].y, + position.z + directions[m_int24].z }; + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticLine(0.1f, 0xFF00, position, end, 0.1f); + } + else if (m_planWeight > 0.0f) + { + Information* const target = informationManager->getInformation(m_planTarget60); + const Vec3& end = target->getPosition(); + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticLine(0.1f, 0xF00F00, position, end, 0.1f); + } + + Information* const target = informationManager->getInformation(m_planTarget60); + if (target) + { + target->getPosition(); // The image discards this virtual result. + const Mat4& camera = *static_cast(m_bot->getPlayer()->getCameraTransformation()); + const Vec3 direction = { camera.m[8] * 3.0f, camera.m[9] * 3.0f, camera.m[10] * 3.0f }; + const Vec3 start = { camera.m[12], camera.m[13], camera.m[14] }; + const Vec3 end = { start.x + direction.x, start.y + direction.y, start.z + direction.z }; + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticLine(0.1f, 0xFFFF00, start, end, 0.1f); + } + if (equipment->isOfType(ITSoldier)) + { + const Vec3 direction = { m_moveDirection.x * 10.0f, 0.0f * 10.0f, m_moveDirection.y * 10.0f }; + const Vec3 end = { position.x + direction.x, position.y + direction.y, position.z + direction.z }; + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticLine(0.1f, 0x550000, position, end, 0.1f); + } +} + } // namespace ai } // namespace hfe } // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgent.h b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgent.h index ca26ba04a..277986c8b 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgent.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgent.h @@ -3,6 +3,7 @@ #ifndef AI_AIDLL_AI_AIBOT_SENSINGAGENT_H // [INFERRED] guard style #define AI_AIDLL_AI_AIBOT_SENSINGAGENT_H +#include #include #include "../../../../Math/Vec3.h" // Vec2 and Vec3 live here, and both are typedefs @@ -12,73 +13,164 @@ namespace hfe { namespace ai { class BAPContext; -// the plan'S base class. `SensingAgent` holds one `BAPStatement*` and nothing else about the -// statement tree; see the deletePlan block in the .cpp for how far the evidence goes. -class BAPStatement; +// The plan is a `BotScript*` (the patterns' createPlan returns one; deletePlan deletes it through +// the virtual destructor). class BotMain; class BotSenses; class Information; class ISensingAgentPattern; +class BotScript; class SensingAgent { + // [INFERRED] friendship: AIConsole::sensingAgentDebug ELF 0x396930 stores +0x86 at 0x396970. + friend class AIConsole; public: // The second parameter is in the ABI and is never read - see the header block. SensingAgent(BotMain* owner, unsigned char behaviourCount); - ~SensingAgent(); // [FRONTIER] + ~SensingAgent(); // ELF 0x1BBB50 + + // A focus candidate: one per sensed object (evaluateSensedObjects 0x1BC5B0) or incoming shot + // (evaluateFireObjects 0x1BC7E0); 16 bytes, the vector stride (`>> 4`). [INFERRED] member names. + struct FocusInformation + { + float weight; // +0 + Vec3 position; // +4 + }; + // The chosen focus quadrant: update keeps it on the stack (0x14 bytes used); computeTargetQuadrant + // fills it, createPlan / checkForPlanInvalidation / calculateCurrentPeriod read it. [INFERRED] names. + struct QuadrantInformation + { + int quadrant; // +0, -1 = none + float weight; // +4 + Vec3 position; // +8, the mean position of the quadrant's candidates + }; + // getQuadrantWeights' per-quadrant accumulator: weight, (position sum, candidate count). + typedef std::vector > > QuadrantWeights; - // [UNRESOLVED] Methods requiring unknown nested-type layouts remain undeclared. void reset(); // Called by `BotMain::reset` when a bot loses its active plan - losing a plan releases the // bot's aim override. void setOverride(bool); - void deletePlan(); // - (one arm frontier) + void deletePlan(); void clearPlanTargetInformation(); - // attested as a nested type by `std::vector`; its members are - // [UNRESOLVED] - nothing recovered so far constructs one. - struct FocusInformation; + void update(); // ELF 0x1BBD30 + void executePlan(); // ELF 0x1BF230 + void disallowOverride(bool b); // ELF 0x1BE0A0 + void updateQuadTimeUrgencies(Vec2& direction, bool turnedAway); // ELF 0x1BC1A0 + void calcTargetQuadFromObjects(QuadrantInformation* info, const Vec2& direction); // ELF 0x1BC410 + void evaluateSensedObjects(); // ELF 0x1BC5B0 + void evaluateFireObjects(); // ELF 0x1BC7E0 + void getQuadrantWeights(QuadrantWeights& weights); // ELF 0x1BCA90 + void computeTargetQuadrant(const QuadrantWeights& weights, QuadrantInformation* info); // ELF 0x1BCD50 + void checkForPlanInvalidation(const QuadrantInformation& info, bool force); // ELF 0x1BCFF0 + bool targetFeasible(int quadrant) const; // ELF 0x1BD170 + bool isForward(int quadrant, const Vec2& direction) const; // ELF 0x1BD250 + bool isBehind(int quadrant, const Vec2& direction) const; // ELF 0x1BD340 + bool withinCamView(const Vec2& direction) const; // ELF 0x1BD430 + void clearInformation(); // ELF 0x1BE020 + void calculateCurrentPeriod(const QuadrantInformation& info, Information* equipment, + const Vec2& direction); // ELF 0x1BE250 + void createPlan(ISensingAgentPattern* pattern, const QuadrantInformation& info); // ELF 0x1BE850 + void createDirPlan(const Vec3& direction, ISensingAgentPattern* pattern); // ELF 0x1BF120 + void createNullPlan(); // ELF 0x1BF180 + // ELF 0x1BE110: the quadrants one unit ahead of the camera that are in focus are marked seen + // (weight 0); seeing the plan's focus quadrant (+24) sets +44. + void setQuadSeen(); + // ELF 0x1BD860: the two quadrants (0..3 diagonal sectors, 4..7 axis sectors) of a position + // around the camera, in the XZ plane; false when the position is on the camera. + bool computeQuadrantsFromPosition(const Vec3& position, int* quadrants) const; + // ELF 0x1BDA60: the camera's XZ forward is within ~10 degrees (dot > 0.9848) of the quadrant. + bool quadInFocus(int quadrant) const; + // ELF 0x1BDBC0: the quadrant's unit XZ direction; anything else is reported. + void getQuadPosition(int quadrant, Vec2& position) const; + BotScript* getPlan() const { return m_plan; } // BotMain::planExecution reads +136 inline + // BotMain's sensing forwarders read +104 inline (ELF 0x18a1d0 `mov 0xc0(%eax),%eax; mov 0x68(%eax)`). + BotSenses* getSenses() const { return m_senses; } + // ELF 0x1BDF70: empty. + void insertBehaviourInformation(float, const Vec3&, unsigned char) {} + // ELF 0x1BDF80: empty. + void insertPlanTargetInformation(float, unsigned int, bool) {} + // ELF 0x1BDF90: a plan direction - +64 the direction, +60 the bot's current equipment, + // +76 the weight, and the sensed-new flag (+120) set to `flag`. + void insertPlanDirectionInformation(float weight, const Vec3& direction, bool flag); + void drawSensingAgentDebugStuff(); + // BotSenses::event_seenObject (indirect sighting) and event_heardObject (new record) store + // `movb $1, 0x78(agent)` inline. [INFERRED] name. + void setSensedNewObject() { m_flag120 = true; } + // EntryInfanteryMoveTo / MoveToObject (0x2B7CF7 `fstpl 0x7c(%eax)`) store 0.0 here inline, so the + // next update ends a pending override at once. [INFERRED] name. + void setOverrideTime(double time) { m_double124 = time; } + + // [INFERRED] inline accessors for the fields the BAP actions read and write in place + // (ai-w1-c-actions request; ELF 0x1D3F00, 0x1D5660). + const Vec2& getMoveDirection() const { return m_moveDirection; } + void setMoveDirection(const Vec2& direction) { m_moveDirection = direction; } + const Vec3& getSprintFocus() const { return m_sprintFocus; } + void setSprintFocus(const Vec3& point) { m_sprintFocus = point; } + unsigned int getSprintFocusTarget() const { return m_sprintFocusTarget; } + void setSprintFocusTarget(unsigned int handle) { m_sprintFocusTarget = handle; } private: - /* 0 */ int m_zero0[6]; // +0..+20, all 0 + // [INFERRED] friendship: the patterns' createPlan reads and clears +0x88 (the plan) and clears + // +0x90 (the BAP context) inline (e.g. SensingAgentNullPattern 0x1C1A93 / 0x1C1AD1). + friend class SensingAgentTurretPattern; + friend class SensingAgentMouseFreeLookPattern; + friend class SensingAgentSoldierPattern; + friend class SensingAgentNullPattern; + // the candidates of the last update; clearInformation zeroes their weights. Constructed empty. + /* 0 */ std::vector m_sensedFocus; // evaluateSensedObjects + /* 12 */ std::vector m_fireFocus; // evaluateFireObjects // neither is A gap - the constructor skips them and `reset` writes both. A field the // constructor misses is not necessarily unused; check the reset before calling it dead. - /* 24 */ int m_int24; // reset: -1 - /* 28 */ int m_int28; // reset: 0 - /* 32 */ int m_zero32[3]; // +32, +36, +40 - /* 44 */ bool m_flag44; // reset: false + // the focus quadrant of the current quadrant plan (createPlan 0x1BE850). [INFERRED] names. + /* 24 */ int m_int24; // reset: -1; the focus quadrant + /* 28 */ float m_focusWeight; // reset: 0 + /* 32 */ Vec3 m_focusPosition; // ctor: 0 + /* 44 */ bool m_flag44; // reset: false; the focus quadrant was looked at // the eight-quadrant weight ring - the constructor's only container, and the only thing it // sizes. Eight zeroed floats; see the header block. /* 48 */ std::vector m_quadrantWeights; // [INFERRED] Plan-target handle, cleared to zero and passed to BotMain when checking // plan invalidation; the neighboring words are also cleared. /* 60 */ unsigned int m_planTarget60; // clearPlanTargetInformation: 0 - /* 64 */ int m_zero64[3]; // +64, +68, +72 - /* 76 */ unsigned int m_planTarget76; // clearPlanTargetInformation: 0 - /* 80 */ int m_zero80[5]; // +80..+96 - /* 100 */ char m_gap100[4]; // [UNRESOLVED] - never written + // insertPlanDirectionInformation's direction and weight; createPlan compares the weight with + // the focus quadrant's and normalises the direction. + /* 64 */ Vec3 m_planDirection; // ctor: 0 + /* 76 */ float m_planWeight; // clearPlanTargetInformation: 0 + // BAPAMergeSoldierInputs::execute (ELF 0x1D3F00) reads +0x50/+0x54 as floats (a Vec2), + // +0x58..+0x60 as a Vec3 and compares +0x64 with -1 (a handle); BAPAMoveTo::setIsSprinting + // (0x1D5660) writes +0x58 / +0x64. [INFERRED] names. The constructor zeroes +80..+96; + // reset zeroes +80 / +84; +100 is never written by either. + /* 80 */ Vec2 m_moveDirection; + /* 88 */ Vec3 m_sprintFocus; + /* 100 */ unsigned int m_sprintFocusTarget; /* 104 */ BotSenses* m_senses; // new(0x94) - the mechanism this agent steers /* 108 */ BotMain* m_bot; // the ctor argument // the whole tail is `reset`'s, not the constructor's - see the note at +24. /* 112 */ double m_double112; // reset: the game time at reset - /* 120 */ bool m_flag120; // reset: false - /* 121 */ bool m_flag121; // reset: false - /* 122 */ bool m_flag122; // reset: false + /* 120 */ bool m_flag120; // reset: false; update re-plans at once while set + /* 121 */ bool m_flag121; // reset: false; evaluateFireObjects: enemy fire booked + /* 122 */ bool m_flag122; // reset: false; disallowOverride: false; the override /* 123 */ char m_pad123; /* 124 */ double m_double124; // reset: 0.0 - /* 132 */ bool m_flag132; // reset: false - /* 133 */ bool m_flag133; // reset: false + /* 132 */ bool m_flag132; // reset: false; disallowOverride(b) stores b + /* 133 */ bool m_flag133; // reset: false; createPlan: the focus is ahead of the move /* 134 */ bool m_flag134; // ctor: false /* 135 */ char m_pad135; // the plan itself - one owned statement, guarded everywhere it is touched. - /* 136 */ BAPStatement* m_plan; // ctor: 0 + /* 136 */ BotScript* m_plan; // ctor: 0 // Set true by `reset` and again by `deletePlan`, and nothing recovered so far reads it. // Meaning [UNRESOLVED]; the name stays neutral rather than guess at `m_planInvalid`. + // executePlan: set when the plan failed or did not finish (failed || !ok). /* 140 */ bool m_flag140; // reset: true, deletePlan: true /* 141 */ char m_pad141[3]; /* 144 */ BAPContext* m_bapContext; // new(4) - shared vocabulary with BotMain's own - /* 148 */ bool m_flag148; // reset: true + /* 148 */ bool m_flag148; // reset: true; createPlan: a quadrant (not target) plan /* 149 */ char m_pad149[3]; - /* 152 */ float m_reactionTime; // reset: a random float in [0.5, 1.0) - see the .cpp + // the time between two re-plans: reset a random float in [0.5, 1.0), calculateCurrentPeriod + // a random float in a range that depends on what the bot does. + /* 152 */ float m_currentPeriod; }; } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentMouseFreeLookPattern.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentMouseFreeLookPattern.cpp new file mode 100644 index 000000000..a631c0bd9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentMouseFreeLookPattern.cpp @@ -0,0 +1,86 @@ +// Source placement: AIDLL_r.dll __FILE__ "Code\BF2\AI\AIDLL\AI\AIBot\SensingAgentMouseFreeLookPattern.cpp" +// (asserts in 0x10136CD0 and 0x10137020, e.g. "lookDir vector empty!"). Split out of the former +// SensingAgentPatterns.cpp; the functions are unchanged. +#include "SensingAgentPatterns.h" +#include +// static init: ELF 0x1C1780, 0x1C17E0, 0x1C1810 (MouseFreeLook) + +#include "SensingAgentPatternPrologue.h" +#include "../AIBotActionPlan/BAPALookAtObject.h" +#include "../AIBotActionPlan/BAPALookInDir.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" + +namespace dice { +namespace hfe { +namespace ai { + +// The base owns the shared id field used by every pattern's getId/reset pair. +// Constructors and destructors perform no additional member initialization or cleanup. +// [INFERRED] placement: weak in the ELF, emitted right after this TU's static init (0x1C1830). +ISensingAgentPattern::~ISensingAgentPattern() +{ +} + +SensingAgentMouseFreeLookPattern::SensingAgentMouseFreeLookPattern() +{ +} + +SensingAgentMouseFreeLookPattern::~SensingAgentMouseFreeLookPattern() +{ +} + +int SensingAgentMouseFreeLookPattern::getId() const +{ + return m_id; +} + +void SensingAgentMouseFreeLookPattern::reset(int id) +{ + m_id = id; +} + +// ELF 0x1C0560: hold the mouse-look button and look in the direction, in parallel. +BotScript* SensingAgentMouseFreeLookPattern::createPlan(SensingAgent* agent, Bot* bot, const Vec3& direction) +{ + SENSING_PATTERN_KEEP_OR_DROP(agent); + BotScript* plan = 0; + if (IPIControlInfo* const control = currentControlInfo(bot)) + { + BAPATriggerContinously* const trigger = holdMouseLook(getId()); + const int id = getId(); + const unsigned long long controls = control->getLookControls(); + BAPALookInDir* const look = checkPointer( + new BAPALookInDir(direction, 0.08726646f, checkPointer(new BAPConFalse()), controls, id)); + BAPCombinerParallel* const parallel = checkPointer(new BAPCombinerParallel(getId(), -1, false)); + parallel->addStatement(trigger); + parallel->addStatement(look); + parallel->mpOwner = this; + plan = parallel; + } + return plan; +} + +// ELF 0x1C0E60: as above, looking at the object. +BotScript* SensingAgentMouseFreeLookPattern::createPlan(SensingAgent* agent, Bot* bot, unsigned int target) +{ + SENSING_PATTERN_KEEP_OR_DROP(agent); + BotScript* plan = 0; + if (IPIControlInfo* const control = currentControlInfo(bot)) + { + BAPATriggerContinously* const trigger = holdMouseLook(getId()); + const int id = getId(); + const unsigned long long controls = control->getLookControls(); + BAPALookAtObject* const look = checkPointer(new BAPALookAtObject( + bot, target, 0.08726646f, checkPointer(new BAPConFalse()), controls, id, 0, 0.0f)); + BAPCombinerParallel* const parallel = checkPointer(new BAPCombinerParallel(getId(), -1, false)); + parallel->addStatement(trigger); + parallel->addStatement(look); + parallel->mpOwner = this; + plan = parallel; + } + return plan; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentNullPattern.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentNullPattern.cpp new file mode 100644 index 000000000..06f0a4c48 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentNullPattern.cpp @@ -0,0 +1,55 @@ +// [INFERRED] Source placement and file name: the ELF gives the null pattern its own TU (own static +// init below, between the MouseFreeLook and Soldier TUs); AIDLL_r.dll has no assert in it, so no +// __FILE__ names it. Its three siblings are SensingAgentMouseFreeLookPattern.cpp, +// SensingAgentSoldierPattern.cpp and SensingAgentTurretPattern.cpp (AIDLL_r __FILE__). Split out of +// the former SensingAgentPatterns.cpp; the functions are unchanged. +#include "SensingAgentPatterns.h" +#include +// static init: ELF 0x1C1DD0, 0x1C1E30, 0x1C1E60 (Null) + +#include "SensingAgentPatternPrologue.h" +#include "../AIBotActionPlan/BAPAResetControls.h" + +namespace dice { +namespace hfe { +namespace ai { + +SensingAgentNullPattern::SensingAgentNullPattern() +{ +} + +SensingAgentNullPattern::~SensingAgentNullPattern() +{ +} + +int SensingAgentNullPattern::getId() const +{ + return m_id; +} + +void SensingAgentNullPattern::reset(int id) +{ + m_id = id; +} + +// ELF 0x1C1A70: BAPAResetControls(false, true, false, id) (0x1C bytes), owned by the pattern. +BotScript* SensingAgentNullPattern::createPlan(SensingAgent* agent, Bot* /*bot*/, const Vec3& /*direction*/) +{ + SENSING_PATTERN_KEEP_OR_DROP(agent); + BAPAResetControls* const reset = checkPointer(new BAPAResetControls(false, true, false, getId())); + reset->mpOwner = this; + return reset; +} + +// ELF 0x1C1C20: identical to the direction overload. +BotScript* SensingAgentNullPattern::createPlan(SensingAgent* agent, Bot* /*bot*/, unsigned int /*target*/) +{ + SENSING_PATTERN_KEEP_OR_DROP(agent); + BAPAResetControls* const reset = checkPointer(new BAPAResetControls(false, true, false, getId())); + reset->mpOwner = this; + return reset; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentPatternPrologue.h b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentPatternPrologue.h new file mode 100644 index 000000000..9608d8cfb --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentPatternPrologue.h @@ -0,0 +1,61 @@ +// [CHOSEN, not recovered] Private helpers shared by the sensing-agent pattern TUs +// (SensingAgentMouseFreeLookPattern.cpp, SensingAgentNullPattern.cpp, SensingAgentTurretPattern.cpp). +// The retail images expand them inline in each createPlan; this header only keeps one copy of the +// source after the split of the former SensingAgentPatterns.cpp. Include it from those .cpp files only. + +#ifndef AI_AIDLL_AI_AIBOT_SENSINGAGENTPATTERNPROLOGUE_H +#define AI_AIDLL_AI_AIBOT_SENSINGAGENTPATTERNPROLOGUE_H + +#include "SensingAgent.h" +#include "BotMain.h" +#include "../AIBotActionPlan/BAPATriggerContinously.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPStatement.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIUtils/checkPointer.h" + +// The patterns' shared prologue (inline in every createPlan but the soldier's, e.g. 0x1C2B10): the +// agent's plan is kept when this pattern built it (BAPStatement +0x10 == getId()); otherwise it is +// deleted and the agent's BAP context cleared. The function returns the kept plan or null. +#define SENSING_PATTERN_KEEP_OR_DROP(agent) \ + if (BotScript* const previous = (agent)->m_plan) \ + { \ + if (static_cast(previous)->getPatternId() == getId()) \ + return previous; \ + delete previous; \ + (agent)->m_plan = 0; \ + } \ + (agent)->m_bapContext->clear() + +namespace dice { +namespace hfe { +namespace ai { +namespace { + +// The bot's current equipment's control info, or null (Bot +0xD8, Information +0x30). +inline IPIControlInfo* currentControlInfo(Bot* bot) +{ + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + return equipment ? equipment->getControlInfo() : 0; +} + +// BAPATriggerContinously(PIMouseLook, true, false, false, mask 0x800, id, 0.0): the mouse-look +// button held for the plan's life (0x1C06F9..0x1C0727; 0x30 bytes). +inline BAPATriggerContinously* holdMouseLook(int id) +{ + BAPCondition* const third = checkPointer(new BAPConFalse()); + BAPCondition* const second = checkPointer(new BAPConFalse()); + BAPCondition* const first = checkPointer(new BAPConTrue()); + return checkPointer(new BAPATriggerContinously(io::PIMouseLook, first, second, third, 0x800ULL, id, 0.0)); +} + +} // namespace +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOT_SENSINGAGENTPATTERNPROLOGUE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentPatterns.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentPatterns.cpp deleted file mode 100644 index 8eeec45f9..000000000 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentPatterns.cpp +++ /dev/null @@ -1,144 +0,0 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining SensingAgentPatterns operations. - -#include "SensingAgentPatterns.h" - -#include "../Main/AIDllFrontier.h" - -namespace dice { -namespace hfe { -namespace ai { - -// The base owns the shared id field used by every pattern's getId/reset pair. -// Constructors and destructors perform no additional member initialization or cleanup. -ISensingAgentPattern::~ISensingAgentPattern() -{ -} - -SensingAgentTurretPattern::SensingAgentTurretPattern() -{ -} - -SensingAgentTurretPattern::~SensingAgentTurretPattern() -{ -} - -int SensingAgentTurretPattern::getId() const -{ - return m_id; -} - -void SensingAgentTurretPattern::reset(int id) -{ - m_id = id; -} - -SensingAgentMouseFreeLookPattern::SensingAgentMouseFreeLookPattern() -{ -} - -SensingAgentMouseFreeLookPattern::~SensingAgentMouseFreeLookPattern() -{ -} - -int SensingAgentMouseFreeLookPattern::getId() const -{ - return m_id; -} - -void SensingAgentMouseFreeLookPattern::reset(int id) -{ - m_id = id; -} - -SensingAgentSoldierPattern::SensingAgentSoldierPattern() -{ -} - -SensingAgentSoldierPattern::~SensingAgentSoldierPattern() -{ -} - -int SensingAgentSoldierPattern::getId() const -{ - return m_id; -} - -void SensingAgentSoldierPattern::reset(int id) -{ - m_id = id; -} - -SensingAgentNullPattern::SensingAgentNullPattern() -{ -} - -SensingAgentNullPattern::~SensingAgentNullPattern() -{ -} - -int SensingAgentNullPattern::getId() const -{ - return m_id; -} - -void SensingAgentNullPattern::reset(int id) -{ - m_id = id; -} - -// [FRONTIER] Pattern plan creation and soldier helpers require the look/aim plan runtime. -// [RETIRE-WHEN: aidll-02-skeleton] Replace each stop when its plan behavior is recovered. -void SensingAgentTurretPattern::createPlan(SensingAgent *, Bot *, const Vec3&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::SensingAgentTurretPattern::createPlan"); -} - -void SensingAgentTurretPattern::createPlan(SensingAgent *, Bot *, unsigned int) -{ - BF2_AI_FRONTIER("dice::hfe::ai::SensingAgentTurretPattern::createPlan"); -} - -void SensingAgentMouseFreeLookPattern::createPlan(SensingAgent *, Bot *, const Vec3&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::SensingAgentMouseFreeLookPattern::createPlan"); -} - -void SensingAgentMouseFreeLookPattern::createPlan(SensingAgent *, Bot *, unsigned int) -{ - BF2_AI_FRONTIER("dice::hfe::ai::SensingAgentMouseFreeLookPattern::createPlan"); -} - -void SensingAgentSoldierPattern::createPlan(SensingAgent *, Bot *, const Vec3&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::SensingAgentSoldierPattern::createPlan"); -} - -void SensingAgentSoldierPattern::createPlan(SensingAgent *, Bot *, unsigned int) -{ - BF2_AI_FRONTIER("dice::hfe::ai::SensingAgentSoldierPattern::createPlan"); -} - -void SensingAgentSoldierPattern::initPlan(SensingAgent *, Bot *, IPIControlInfo *&, BotScript *&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::SensingAgentSoldierPattern::initPlan"); -} - -void SensingAgentSoldierPattern::endPlan(BAPALook *, Bot *) -{ - BF2_AI_FRONTIER("dice::hfe::ai::SensingAgentSoldierPattern::endPlan"); -} - -// Null-pattern planning still requires an implementation; these overloads stop visibly. -void SensingAgentNullPattern::createPlan(SensingAgent *, Bot *, const Vec3&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::SensingAgentNullPattern::createPlan"); -} - -void SensingAgentNullPattern::createPlan(SensingAgent *, Bot *, unsigned int) -{ - BF2_AI_FRONTIER("dice::hfe::ai::SensingAgentNullPattern::createPlan"); -} - -} // namespace ai -} // namespace hfe -} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentPatterns.h b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentPatterns.h index 76ab6e007..c859d9e47 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentPatterns.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentPatterns.h @@ -1,6 +1,6 @@ -// [CHOSEN, not recovered] Grouped sensing-pattern declarations. -// Split into their individual translation units when their plan creation is implemented. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. +// The sensing agent's plan patterns (libaidll.so 0x1C0490..0x1C3250). [CHOSEN, not recovered]: the +// four classes stay grouped in one header. Each has its own source file, as in the retail images +// (AIDLL_r __FILE__: SensingAgentSoldier/Turret/MouseFreeLookPattern.cpp; SensingAgentNullPattern.cpp). #ifndef AI_AIDLL_AI_AIBOT_SENSINGAGENTPATTERNS_H #define AI_AIDLL_AI_AIBOT_SENSINGAGENTPATTERNS_H @@ -25,8 +25,8 @@ class ISensingAgentPattern // Preserve virtual order: reset precedes the other pattern operations. virtual void reset(int) = 0; // +0x08 - virtual void createPlan(SensingAgent *, Bot *, const Vec3&) = 0; // +0x0C - virtual void createPlan(SensingAgent *, Bot *, unsigned int) = 0; // +0x10 + virtual BotScript* createPlan(SensingAgent *, Bot *, const Vec3&) = 0; // +0x0C + virtual BotScript* createPlan(SensingAgent *, Bot *, unsigned int) = 0; // +0x10 virtual int getId() const = 0; // +0x14 // Uninitialised by construction - see the block above. @@ -42,8 +42,8 @@ class SensingAgentTurretPattern : public ISensingAgentPattern // Preserve virtual order: reset occupies the first slot. virtual void reset(int); - virtual void createPlan(SensingAgent *, Bot *, const Vec3&); - virtual void createPlan(SensingAgent *, Bot *, unsigned int); + virtual BotScript* createPlan(SensingAgent *, Bot *, const Vec3&); + virtual BotScript* createPlan(SensingAgent *, Bot *, unsigned int); virtual int getId() const; }; @@ -56,8 +56,8 @@ class SensingAgentMouseFreeLookPattern : public ISensingAgentPattern // Preserve virtual order: reset occupies the first slot. virtual void reset(int); - virtual void createPlan(SensingAgent *, Bot *, const Vec3&); - virtual void createPlan(SensingAgent *, Bot *, unsigned int); + virtual BotScript* createPlan(SensingAgent *, Bot *, const Vec3&); + virtual BotScript* createPlan(SensingAgent *, Bot *, unsigned int); virtual int getId() const; }; @@ -70,16 +70,18 @@ class SensingAgentSoldierPattern : public ISensingAgentPattern // Preserve virtual order: reset occupies the first slot. virtual void reset(int); - virtual void createPlan(SensingAgent *, Bot *, const Vec3&); - virtual void createPlan(SensingAgent *, Bot *, unsigned int); + virtual BotScript* createPlan(SensingAgent *, Bot *, const Vec3&); + virtual BotScript* createPlan(SensingAgent *, Bot *, unsigned int); virtual int getId() const; - // Non-virtual, and unique to this pattern: it brackets the plan it builds. - void initPlan(SensingAgent *, Bot *, IPIControlInfo *&, BotScript *&); - void endPlan(BAPALook *, Bot *); + // Unique to this pattern and virtual (vtable 0x4B7640 slots +0x18 / +0x1C): they bracket the + // plan it builds. initPlan (ELF 0x1C1F60) finds the control info; endPlan (0x1C2050) wraps the + // look in a parallel combiner with BAPAMergeSoldierInputs. + virtual bool initPlan(SensingAgent *, Bot *, IPIControlInfo *&, BotScript *&); + virtual BotScript* endPlan(BAPALook *, Bot *); }; -// The null object. Both createPlan overloads are and do nothing useful. +// The null object: both createPlan overloads build (or keep) a BAPAResetControls. class SensingAgentNullPattern : public ISensingAgentPattern { public: @@ -88,8 +90,8 @@ class SensingAgentNullPattern : public ISensingAgentPattern // Preserve virtual order: reset occupies the first slot. virtual void reset(int); - virtual void createPlan(SensingAgent *, Bot *, const Vec3&); - virtual void createPlan(SensingAgent *, Bot *, unsigned int); + virtual BotScript* createPlan(SensingAgent *, Bot *, const Vec3&); + virtual BotScript* createPlan(SensingAgent *, Bot *, unsigned int); virtual int getId() const; }; diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentSoldierPattern.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentSoldierPattern.cpp new file mode 100644 index 000000000..6f94764d6 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentSoldierPattern.cpp @@ -0,0 +1,114 @@ +// Source placement: AIDLL_r.dll __FILE__ "Code\BF2\AI\AIDLL\AI\AIBot\SensingAgentSoldierPattern.cpp" +// (asserts "No info" / "No control info" in 0x101368F0). Split out of the former +// SensingAgentPatterns.cpp; the functions are unchanged. +#include "SensingAgentPatterns.h" +#include +// static init: ELF 0x1C2980, 0x1C29E0, 0x1C2A10 (Soldier) + +#include "SensingAgent.h" +#include "BotMain.h" +#include "../AIBotActionPlan/BAPALookAtObject.h" +#include "../AIBotActionPlan/BAPALookInDir.h" +#include "../AIBotActionPlan/BAPAMergeSoldierInputs.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPStatement.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIUtils/checkPointer.h" + +namespace dice { +namespace hfe { +namespace ai { + +SensingAgentSoldierPattern::SensingAgentSoldierPattern() +{ +} + +SensingAgentSoldierPattern::~SensingAgentSoldierPattern() +{ +} + +int SensingAgentSoldierPattern::getId() const +{ + return m_id; +} + +void SensingAgentSoldierPattern::reset(int id) +{ + m_id = id; +} + +// ELF 0x1C1F60. Both createPlan overloads pass a null `plan`, so the reuse arm (the agent's plan +// kept when it is this pattern's: false; otherwise `plan` deleted and the agent's cleared) never +// runs from them. True with the current equipment's control info; otherwise `plan` = 0. +bool SensingAgentSoldierPattern::initPlan(SensingAgent* agent, Bot* bot, IPIControlInfo*& control, + BotScript*& plan) +{ + if (plan) + { + if (static_cast(agent->m_plan)->getPatternId() == getId()) + return false; + delete plan; + agent->m_plan = 0; + } + agent->m_bapContext->clear(); + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + if (equipment) + { + control = equipment->getControlInfo(); + if (control) + return true; + } + plan = 0; + return false; +} + +// ELF 0x1C2050: parallel(look, BAPAMergeSoldierInputs), owned by the pattern. +BotScript* SensingAgentSoldierPattern::endPlan(BAPALook* look, Bot* /*bot*/) +{ + BAPCombinerParallel* const parallel = checkPointer(new BAPCombinerParallel(getId(), -1, false)); + BAPAMergeSoldierInputs* const merge = checkPointer(new BAPAMergeSoldierInputs(getId())); + parallel->addStatement(look); + parallel->addStatement(merge); + parallel->mpOwner = this; + return parallel; +} + +// ELF 0x1C2310: look in the direction exactly (tolerance 0), never ending. +BotScript* SensingAgentSoldierPattern::createPlan(SensingAgent* agent, Bot* bot, const Vec3& direction) +{ + IPIControlInfo* control = 0; + BotScript* plan = 0; + if (initPlan(agent, bot, control, plan)) + { + const int id = getId(); + const unsigned long long controls = control->getLookControls(); + BAPALookInDir* const look = checkPointer( + new BAPALookInDir(direction, 0.0f, checkPointer(new BAPConFalse()), controls, id)); + plan = endPlan(look, bot); + } + return plan; +} + +// ELF 0x1C2640: look at the object (tolerance 0). +BotScript* SensingAgentSoldierPattern::createPlan(SensingAgent* agent, Bot* bot, unsigned int target) +{ + IPIControlInfo* control = 0; + BotScript* plan = 0; + if (initPlan(agent, bot, control, plan)) + { + const int id = getId(); + const unsigned long long controls = control->getLookControls(); + BAPALookAtObject* const look = checkPointer(new BAPALookAtObject( + bot, target, 0.0f, checkPointer(new BAPConFalse()), controls, id, 0, 0.0f)); + plan = endPlan(look, bot); + } + return plan; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentTurretPattern.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentTurretPattern.cpp new file mode 100644 index 000000000..19e9714f6 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentTurretPattern.cpp @@ -0,0 +1,70 @@ +// Source placement: AIDLL_r.dll __FILE__ "Code\BF2\AI\AIDLL\AI\AIBot\SensingAgentTurretPattern.cpp" +// (asserts "No info" / "No control info" in 0x10137390 and 0x10137570). Split out of the former +// SensingAgentPatterns.cpp; the functions are unchanged. +#include "SensingAgentPatterns.h" +#include +// static init: ELF 0x1C31A0, 0x1C3200, 0x1C3230 (Turret) + +#include "SensingAgentPatternPrologue.h" +#include "../AIBotActionPlan/BAPALookAtObject.h" +#include "../AIBotActionPlan/BAPALookInDir.h" + +namespace dice { +namespace hfe { +namespace ai { + +SensingAgentTurretPattern::SensingAgentTurretPattern() +{ +} + +SensingAgentTurretPattern::~SensingAgentTurretPattern() +{ +} + +int SensingAgentTurretPattern::getId() const +{ + return m_id; +} + +void SensingAgentTurretPattern::reset(int id) +{ + m_id = id; +} + +// ELF 0x1C2B10: look in the direction, 5 degrees (0.08726646 rad) tolerance, never ending. +BotScript* SensingAgentTurretPattern::createPlan(SensingAgent* agent, Bot* bot, const Vec3& direction) +{ + SENSING_PATTERN_KEEP_OR_DROP(agent); + BotScript* plan = 0; + if (IPIControlInfo* const control = currentControlInfo(bot)) + { + const int id = getId(); + const unsigned long long controls = control->getLookControls(); + BAPALookInDir* const look = checkPointer( + new BAPALookInDir(direction, 0.08726646f, checkPointer(new BAPConFalse()), controls, id)); + look->mpOwner = this; + plan = look; + } + return plan; +} + +// ELF 0x1C2E50: look at the object, as above. +BotScript* SensingAgentTurretPattern::createPlan(SensingAgent* agent, Bot* bot, unsigned int target) +{ + SENSING_PATTERN_KEEP_OR_DROP(agent); + BotScript* plan = 0; + if (IPIControlInfo* const control = currentControlInfo(bot)) + { + const int id = getId(); + const unsigned long long controls = control->getLookControls(); + BAPALookAtObject* const look = checkPointer(new BAPALookAtObject( + bot, target, 0.08726646f, checkPointer(new BAPConFalse()), controls, id, 0, 0.0f)); + look->mpOwner = this; + plan = look; + } + return plan; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.cpp index 5299a585d..8bc780420 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.cpp @@ -1,22 +1,48 @@ // [INFERRED] Source placement. // [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining SquadCoordinator operations. +#if defined(__APPLE__) +#include "../../../../Platform/X87Compat.h" // [CHOSEN, not recovered] +#endif #include "SquadCoordinator.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1A8DE0, __tcf_0 0x1A8E40, _GLOBAL__I 0x1A8E70). +#include + +#include +#include +#include + #include "SquadFormation.h" #include "SquadMember.h" #include "BotMain.h" +#include "BotSenses.h" +#include "SensingAgent.h" #include "CommunicationAgent.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../Main/AIDllFrontier.h" #include "../Main/AIMain.h" +#include "SquadManager.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/AIRandom.h" +#include "../Main/IAIPathfinding.h" #include "../AIStrategic/SAI.h" #include "../AIStrategicEntity/AIStrategicArea.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../Main/IBotManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" // IBFTimer::getGameTime #include "../../../AIInterface/BFKnowledge/BFSquad.h" #include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../../../../Math/Vec3.h" // rotateXZ, vec3ToVec2XZ namespace dice { namespace hfe { @@ -67,11 +93,18 @@ static bool maneuverMemberWithinRange(const Vec3& position, const Vec3& squadPos const long double dx = static_cast(static_cast(squadPosition.x) - position.x); const long double dy = static_cast(static_cast(squadPosition.y) - position.y); const long double dz = static_cast(static_cast(squadPosition.z) - position.z); +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + const bf2x87::Real dx = static_cast(squadPosition.x) - position.x; + const bf2x87::Real dy = static_cast(squadPosition.y) - position.y; + const bf2x87::Real dz = static_cast(squadPosition.z) - position.z; #else const long double dx = static_cast(squadPosition.x) - position.x; const long double dy = static_cast(squadPosition.y) - position.y; const long double dz = static_cast(squadPosition.z) - position.z; #endif +#endif #if defined(_WIN32) return (dx * dx + dy * dy) + dz * dz < 8100.0L; #else @@ -119,11 +152,22 @@ static bool shooterMovedAway(const Vec3& firePosition, const Vec3& position) #else #if defined(_WIN32) const long double dx = static_cast(static_cast(firePosition.x) - position.x); +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + const bf2x87::Real dx = static_cast(firePosition.x) - position.x; #else const long double dx = static_cast(firePosition.x) - position.x; #endif +#endif +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + const bf2x87::Real dy = static_cast(firePosition.y) - position.y; + const bf2x87::Real dz = static_cast(firePosition.z) - position.z; +#else const long double dy = static_cast(firePosition.y) - position.y; const long double dz = static_cast(firePosition.z) - position.z; +#endif #if defined(_WIN32) return (dz * dz + dy * dy) + dx * dx > 25.0L; #else @@ -169,10 +213,17 @@ static float leaderGotoDistanceSq(const Vec3& position, const Vec3& gotoPosition const long double dx = static_cast(static_cast(position.x) - gotoPosition.x); const long double dy = static_cast(static_cast(position.y) - gotoPosition.y); const long double dz = static_cast(static_cast(position.z) - gotoPosition.z); +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + const bf2x87::Real dx = static_cast(gotoPosition.x) - position.x; + const bf2x87::Real dy = static_cast(gotoPosition.y) - position.y; + const bf2x87::Real dz = static_cast(gotoPosition.z) - position.z; #else const long double dx = static_cast(gotoPosition.x) - position.x; const long double dy = static_cast(gotoPosition.y) - position.y; const long double dz = static_cast(gotoPosition.z) - position.z; +#endif #endif return static_cast((dx * dx + dy * dy) + dz * dz); #endif @@ -222,6 +273,13 @@ static bool insideControlPointRadius(const Vec3& controlPoint, const Vec3& posit const long double dy = static_cast(static_cast(controlPoint.y) - position.y); const long double dz = static_cast(static_cast(controlPoint.z) - position.z); return (dx * dx + dy * dy) + dz * dz < static_cast(radiusSq); +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + const bf2x87::Real dx = static_cast(position.x) - controlPoint.x; + const bf2x87::Real dy = static_cast(position.y) - controlPoint.y; + const bf2x87::Real dz = static_cast(position.z) - controlPoint.z; + return (dy * dy + dx * dx) + dz * dz < static_cast(radiusSq); #else const long double dx = static_cast(position.x) - controlPoint.x; const long double dy = static_cast(position.y) - controlPoint.y; @@ -229,6 +287,7 @@ static bool insideControlPointRadius(const Vec3& controlPoint, const Vec3& posit return (dy * dy + dx * dx) + dz * dz < static_cast(radiusSq); #endif #endif +#endif } // [INFERRED] @@ -237,7 +296,7 @@ static bool insideControlPointRadius(const Vec3& controlPoint, const Vec3& posit void SquadCoordinator::update(double time) { m_d124 = time; - if (m_i120 == 2 && !IAIMain::m_instance->getSAI(m_side + 1)->isPlayerCommander()) + if (m_missionStatus == 2 && !IAIMain::m_instance->getSAI(m_side + 1)->isPlayerCommander()) { if (m_i40 == 0) { @@ -387,9 +446,9 @@ void SquadCoordinator::updateNeedOrdersMessage(double time) return; static_cast(CommonSingletonServer::m_iBFSquad) ->requestNewCommanderOrder(m_squadIndex + 1, leader->getPlayer()); - CommunicationAgent* const radio = leader->getBot()->getCommunicationAgent(); - (void)radio; - BF2_AI_FRONTIER("dice::hfe::ai::SquadCoordinator::updateNeedOrdersMessage (CommunicationAgent::enqueueRadioMessage)"); + // ELF 0x1A3CB6: radio message 14 on channel 4, priority 3, delay 1 s. + leader->getBot()->getCommunicationAgent()->enqueueRadioMessage( + static_cast(14), static_cast(4), 3, 1.0f, 0); } } } @@ -430,7 +489,10 @@ void SquadCoordinator::updateIncomingMessages() return; m_formation->joinSquadLeader(); - BF2_AI_FRONTIER("dice::hfe::ai::SquadCoordinator::updateIncomingMessages (CommunicationAgent::enqueueRadioMessage)"); + // ELF 0x1A3760: the bot answers with radio message 6 (channel 3, priority 3, delay 2 s), and + // every member's path is invalidated. + radio->enqueueRadioMessage(static_cast(6), static_cast(3), 3, 2.0f, 0); + updateSquadPaths(); } // Returns whether a living, standing squad member is inside the assigned control point @@ -478,11 +540,11 @@ void SquadCoordinator::updateSquadManeuver() } break; case 1: - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - BF2_AI_FRONTIER("dice::hfe::ai::SquadCoordinator::updateSquadManeuver (squadManeuverAlternateFire)"); + squadManeuverAlternateFire(); + break; case 2: - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - BF2_AI_FRONTIER("dice::hfe::ai::SquadCoordinator::updateSquadManeuver (squadManeuverStaticFlank)"); + squadManeuverStaticFlank(); + break; } } @@ -512,8 +574,8 @@ int SquadCoordinator::chooseSquadManeuver() if (bot->isFiring()) { // No information-null guard exists in either image. - const unsigned int flags = information->getObjectTypeFlags(); - if (!(flags & 0x10u) && !(flags & 0x20u) && !(flags & 0x80u) && + if (!information->isOfType(ITAir) && !information->isOfType(ITHelicopter) && + !information->isOfType(ITNaval) && member->getPosition(position) && maneuverMemberWithinRange(position, m_v108)) ++firingMembers; @@ -522,15 +584,164 @@ int SquadCoordinator::chooseSquadManeuver() } if (firingMembers > 1) return 1; - if (m_i120 != 2) + if (m_missionStatus != 2) return 0; - Vec3 target = m_v28; - (void)target; - // The remaining terrain-altitude/distance/assignment policy is evidenced but - // not implemented here. Preserve its entry before any height call or flag store. - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - BF2_AI_FRONTIER("dice::hfe::ai::SquadCoordinator::chooseSquadManeuver (terrain altitude and flank policy)"); + // ELF 0x1A5741: the mission target (+28) at terrain height (IAITerrain +0x14), 50..173 m from the + // squad, a commander mission (+56) on an area this side holds (status 1): flank. A new flank + // (previous maneuver != 2) clears its two flags. + const float x = m_v28.x; + const float z = m_v28.z; + const float height = static_cast(CommonSingletonServer::m_iaiTerrain)->getTerrainAltitude(x, z); + const float dx = x - m_v108.x; + const float dy = height - m_v108.y; + const float dz = z - m_v108.z; + const float distanceSq = dx * dx + dy * dy + dz * dz; + if (distanceSq < 30000.0f && 2500.0f < distanceSq && m_b56 && m_strategicAreaAssignment + && static_cast(m_strategicAreaAssignment->getStatus(m_side + 1)) == 1) + { + if (m_i148 != 2) + { + m_b156 = false; + m_b157 = false; + } + return 2; + } + return 0; +} + +// ELF 0x1A4E90. Every 4 s (+124 the update time, +140 the next time): all bots may fire; the +// living bots firing on foot from a mobile primary within 90 m of the squad take turns in two +// halves (phase +152: 0 the first half holds fire 1.5 s, 1 a 1-3 s pause, 2 the second half +// 1.5 s, 3 a pause). A held bot only stops when it faces (dot > 0.85) its target more than 40 m away. +void SquadCoordinator::squadManeuverAlternateFire() +{ + if (!(m_d140 < m_d124)) + return; + m_d140 = m_d124 + 4.0f; + std::vector firing; + Vec3 position; + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; + for (unsigned int i = 0; i < m_squadMembers.size(); ++i) + { + if (m_squadMembers[i]->isBot()) + m_squadMembers[i]->getBot()->setAllowFire(true); + } + for (unsigned int i = 0; i < m_squadMembers.size(); ++i) + { + SquadMember* const member = m_squadMembers[i]; + if (!member->isBot() || !member->getPlayer()->getIsAlive()) + continue; + Bot* const bot = member->getBot(); + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + if (!bot->isFiring() || !equipment->isPrimary() || !equipment->hasMobile()) + continue; + if (equipment->isOfType(ITAir) || equipment->isOfType(ITHelicopter) || equipment->isOfType(ITNaval) || + !member->getPosition(position)) + continue; + const float dx = m_v108.x - position.x; + const float dy = m_v108.y - position.y; + const float dz = m_v108.z - position.z; + if (dx * dx + dy * dy + dz * dz < 8100.0f) + firing.push_back(member); + } + const unsigned int count = static_cast(firing.size()); + if (count < 2) + return; + unsigned int start = 0; + unsigned int end = 0; + switch (m_i152) + { + case 0: + end = count >> 1; + m_i152 = 1; + m_d140 = 1.5f + m_d124; + break; + case 1: + m_d140 = (1.0f + m_d124) + static_cast(AIRandom::m_instance->next()) * 2.3283064e-10f * 2.0; + ++m_i152; + break; + case 2: + end = count; + start = count >> 1; + m_i152 = 3; + m_d140 = 1.5f + m_d124; + break; + case 3: + m_d140 = (1.0f + m_d124) + static_cast(AIRandom::m_instance->next()) * 2.3283064e-10f * 2.0; + m_i152 = 0; + break; + default: + break; + } + for (unsigned int i = start; i < end; ++i) + { + SquadMember* const member = firing[i]; + Information* const target = informationManager->getInformation(member->getBot()->getFiringTarget()); + if (!target || !member->getPosition(position)) + continue; + const Vec3& t = target->getPosition(); + Vec3 direction; + direction.x = t.x - position.x; + direction.y = t.y - position.y; + direction.z = t.z - position.z; + const float lengthSq = direction.x * direction.x + direction.y * direction.y + direction.z * direction.z; + if (std::fabs(lengthSq - 1.0f) >= 1.1920929e-07f) + { + if (std::fabs(lengthSq) >= 1.1920929e-07f) + { + const float inverse = 1.0f / std::sqrt(lengthSq); + direction.x = direction.x * inverse; + direction.y = direction.y * inverse; + direction.z = inverse * direction.z; + } + else + { + direction.x = 0.0f; + direction.y = 0.0f; + direction.z = 0.0f; + } + } + const Vec3 facing = + informationManager->getInformation(member->getBot()->getCurrentEquipment())->getFaceing(); + if (0.85f < facing.z * direction.z + facing.x * direction.x + facing.y * direction.y) + { + const Vec3& again = target->getPosition(); + const float ex = again.x - position.x; + const float ey = again.y - position.y; + const float ez = again.z - position.z; + if (1600.0f < ex * ex + ey * ey + ez * ez) + firing[i]->getBot()->setAllowFire(false); + } + } +} + +// ELF 0x1A4060. All bots may fire. Once per mission (+157) on an area mission (+120 == 2) with a +// formed squad and an area, at 65 %: the flanking pair closest to the squad (into +160) when both +// are valid for the leader (slot 0) marks the flank (+156) and re-paths the leader. +void SquadCoordinator::squadManeuverStaticFlank() +{ + for (unsigned int i = 0; i < m_squadMembers.size(); ++i) + { + if (m_squadMembers[i]->isBot()) + m_squadMembers[i]->getBot()->setAllowFire(true); + } + if (m_b157 || m_missionStatus != 2) + return; + if (!m_formation->hasSquadMembers() || !m_strategicAreaAssignment) + return; + m_b157 = true; + if (!(AIRandom::m_instance->nextFloat() < 0.65f)) + return; + SquadMember* const leader = m_squadMembers[m_formation->getSquadMemberIndexAtSlot(0)]; + if (m_strategicAreaAssignment->getClosestFlankingPositions(m_v108, m_positions[0], m_positions[1]) + && isValidPosition(leader, m_positions[0]) && isValidPosition(leader, m_positions[1])) + { + m_b156 = true; + leader->setHavePath(false); + } } // [INFERRED] void return, as above. @@ -562,7 +773,7 @@ const Vec3& SquadCoordinator::getSquadGotoPos() // return enum spelling is unresolved, so int records the observed payload without new labels. int SquadCoordinator::getMissionStatus() { - return m_i120; + return m_missionStatus; } // The assignment is borrowed and nullable. @@ -571,8 +782,8 @@ bool SquadCoordinator::isSquadAssignedToArea(int areaIndex) return m_strategicAreaAssignment && m_strategicAreaAssignment->getIndex() == areaIndex; } -// Each qualifying -// live member needs an IAIObject information-handle query before any strength can be added. +// ELF 0x1A7FF0 (277 bytes): the sum of the members' unit strategic strengths of the type +// (IPIUnit +0xC), rounded by +0.5 and truncation. int SquadCoordinator::getStrategicStrength(StrategicStrengthType type) { float total = 0.0f; @@ -584,19 +795,347 @@ int SquadCoordinator::getStrategicStrength(StrategicStrengthType type) IAIObject* const vehicle = player->getCurrentVehicle(); if (!vehicle) continue; - - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - // Both ports next call vehicle's unknown slot (ELF +0xB8 / PE +0xB4), passing - // m_side + 1, then resolve its unsigned handle and sum unit strategic strengths[type]. - // ELF captures informationManager before that call; PE captures it afterwards for a - // nonzero low handle word. Stop before the untyped call; do not invent an owner ABI. - BF2_AI_FRONTIER("dice::hfe::ai::SquadCoordinator::getStrategicStrength (IAIObject information query)"); + Information* const info = informationManager->getInformation(vehicle->getInformation(m_side + 1)); + if (info && info->getUnit()) + total = total + info->getUnit()->getStrategicStrengths()[type]; } - // The shipped empty/filtered paths reach this rounding tail with the unchanged zero sum. - // Every possible contributor above still stops before its unrecovered object query. return static_cast(total + 0.5f); } +// ELF 0x1A7BC0. The order position of the strategic object closest to the squad position +// (+28), for the member's vehicle number, when the member has mobile unit information. +bool SquadCoordinator::getValidSaPos(SquadMember* member, Vec3& position) +{ + AIStrategicObject* const object = + AIStrategicObjectManager::getInstance()->getClosestObject(m_v28, m_side + 1); + bool valid = false; + if (member && object) + { + IAIObject* const vehicle = member->getPlayer()->getCurrentVehicle(); + if (vehicle) + { + Information* const info = informationManager->getInformation(vehicle->getInformation(m_side + 1)); + if (info && info->getUnit() && info->getMobile()) + { + position = object->getOrderPos(info->getMobile()->getVehicleNumber(), m_side + 1); + valid = true; + } + } + } + return valid; +} + +// ELF 0x1A7D30 (320 bytes). As the overload above, but the order position of the given area. +bool SquadCoordinator::getValidSaPos(SquadMember* member, AIStrategicArea* area, Vec3& position) +{ + bool valid = false; + if (member && area) + { + IAIObject* const vehicle = member->getPlayer()->getCurrentVehicle(); + if (vehicle) + { + Information* const info = informationManager->getInformation(vehicle->getInformation(m_side + 1)); + if (info && info->getUnit() && info->getMobile()) + { + position = area->getOrderPos(info->getMobile()->getVehicleNumber(), m_side + 1); + valid = true; + } + } + } + return valid; +} + +// ELF 0x1A6B60 (856 bytes). Whether `position` lies on the member's navigation mesh: the +// polygon under it (IAIPathfinding +0x44 getPolygon(position, vehicle number, polygon, island, +// equipment type)) must be valid for the vehicle (+0x30 isValidPosition(vehicle number, +// equipment type, position, island, true)). A member whose vehicle information has no mobile +// is tested with its soldier (IAIPlayer +0x4C) instead, and then the island must also be the +// one of the soldier's last valid position. As in the image, neither information is null-checked. +bool SquadCoordinator::isValidPosition(SquadMember* member, const Vec3& position) +{ + Information* const info = informationManager->getInformation( + member->getPlayer()->getCurrentVehicle()->getInformation(m_side + 1)); + IPIMobile* mobile = info->getMobile(); + unsigned int polygon; + unsigned int island; + if (mobile) + { + mobile->getLastValidPosition(); + const int equipment = info->getUnit()->getEquipmentType(); + if (!IAIPathfinding::instance->getPolygon(position, mobile->getVehicleNumber(), polygon, island, equipment)) + return false; + return IAIPathfinding::instance->isValidPosition( + mobile->getVehicleNumber(), info->getUnit()->getEquipmentType(), position, island, true); + } + Information* const soldier = informationManager->getInformation( + member->getPlayer()->getSoldier()->getInformation(m_side + 1)); + mobile = soldier->getMobile(); + const IPIMobile::ValidPos last = mobile->getLastValidPosition(); + const int equipment = soldier->getUnit()->getEquipmentType(); + if (!IAIPathfinding::instance->getPolygon(position, mobile->getVehicleNumber(), polygon, island, equipment)) + return false; + if (last.island == static_cast(-1) || island != last.island) + return false; + return IAIPathfinding::instance->isValidPosition( + mobile->getVehicleNumber(), soldier->getUnit()->getEquipmentType(), position, last.island, true); +} + +// ELF 0x1A3A40: the requested-mission record (+60..+95) by value. +SquadCoordinator::MissionRequest SquadCoordinator::getMissionRequest() +{ + MissionRequest request; + request.m_area = m_requestedArea; + request.m_position = m_v64; + request.m_type = m_i76; + request.m_object = m_requestedObject; + request.m_time = m_d84; + request.m_commander = m_b92; + return request; +} + +// ELF 0x1A4950: a repair request at `position`, unconfirmed, valid for 60 s of game time. +void SquadCoordinator::requestRepair(const Vec3& position) +{ + m_b172 = true; + m_v176 = position; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + m_b196 = false; + m_d188 = now + 60.0f; +} + +// ELF 0x1A6F30 (560 bytes). A squad order from a human squad leader (not `commander`) only moves +// the squad leader's goto position (+200) when it changed (componentwise beyond FLT_EPSILON) and +// the leader is not a bot: the roger-that flag is set, the paths invalidated and the formation +// leaves the leader. A commander order is taken when the side has a player commander, or when +// the squad has no mission and is not close to a non-owned target: the mission state (+120) +// becomes 1 (requested) until the update time + 10 s (+132), and the request record is filled. +void SquadCoordinator::requestMission(BotSquad::OrderType type, const Vec3& position, IAIObject* object, bool commander) +{ + SquadMember* const leader = getSquadLeader(); + if (!commander) + { + if (m_squadMembers.size() == 0) + return; + bool same = false; + if (std::fabs(position.x - m_v200.x) <= 1.1920929e-07f && std::fabs(position.y - m_v200.y) <= 1.1920929e-07f) + same = std::fabs(position.z - m_v200.z) <= 1.1920929e-07f; + if (same || leader->isBot()) + return; + m_b220 = true; + m_v200 = position; + updateSquadPaths(); + m_formation->leaveSquadLeader(); + return; + } + if ((!IAIMain::m_instance->getSAI(m_side + 1)->isPlayerCommander() && isSquadCloseToNonOwnedTarget()) + || m_missionStatus != 0) + { + if (!IAIMain::m_instance->getSAI(m_side + 1)->isPlayerCommander()) + return; + } + m_missionStatus = 1; + m_d132 = m_d124 + 10.0f; + m_v64 = position; + m_i76 = type; + m_requestedArea = 0; + m_requestedObject = object; + m_b92 = commander; +} + +// ELF 0x1A79C0 (480 bytes). `position` itself when valid, else up to eight random points in the +// square of half-size `radius` around it, on the terrain; the first valid one replaces it. +bool SquadCoordinator::getRandomValidPosition(SquadMember* member, Vec3& position, float radius) +{ + if (isValidPosition(member, position)) + return true; + IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + AIRandom* const random = AIRandom::m_instance; + Vec3 candidate; + candidate.x = 0.0f; + candidate.y = 0.0f; + candidate.z = 0.0f; + for (int attempt = 0; attempt <= 7; ++attempt) + { + // The image keeps each draw in x87 precision: u * 2^-32, doubled, times the radius. + const float lowX = position.x - radius; + candidate.x = static_cast(static_cast(random->next()) * 2.3283064e-10f * 2.0 * radius + lowX); + const float lowZ = position.z - radius; + candidate.z = static_cast(static_cast(random->next()) * 2.3283064e-10f * 2.0 * radius + lowZ); + candidate.y = terrain->getTerrainAltitude(candidate.x, candidate.z); + if (isValidPosition(member, candidate)) + { + position = candidate; + return true; + } + } + return false; +} + +// ELF 0x1A7160 (2016 bytes). Turns the requested mission (+60..) into the accepted one (+24..), +// for `member` (the squad leader, or the member itself when the leader is down). +// * The area assignment is cleared first. Without a player commander, an attack request whose +// closest strategic area has status 0 for this side unassigns the squad (false); the same order +// on the same area is already accepted (true - unreachable after the clear unless no area). +// * The closest area is taken when the goal lies inside it, or within the ignore-commander +// distance (IAISettings +0x08) plus the area's size of its centre on the terrain and the area's +// status is non-zero; the goal becomes the area's centre. +// * Without an area, a valid position within 30 m of the goal is taken instead; failing that a +// bot member declines (radio 7; as squad leader the engine's decline for the order type), and +// the squad is unassigned. +// * On acceptance: a human leader gets a commander message (attack 0 / defend 1, 3 s) when there +// is no player commander; a bot leader acknowledges (radio 6 with a player commander), issues the +// squad order and accepts the commander order for the member (attack 0x10, defend 0xF, move +// 0x11 on the radio), and every member's path is invalidated. +bool SquadCoordinator::acceptMission(SquadMember* member) +{ + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + bool accepted = false; + m_strategicAreaAssignment = 0; + AIStrategicArea* const closest = static_cast( + AIStrategicObjectManager::getInstance()->getClosestObject(m_v64, m_side + 1)); + if (!IAIMain::m_instance->getSAI(m_side + 1)->isPlayerCommander() && closest && m_i76 == 0 + && closest->m_status[m_side] == 0) + { + unAssignSquad(); + return false; + } + if (!IAIMain::m_instance->getSAI(m_side + 1)->isPlayerCommander() && m_i40 == m_i76 + && m_strategicAreaAssignment == closest) + return true; + + if (closest) + { + const Vec2& centre2 = closest->getPosition(m_side + 1); + const float cx = centre2.x; + const float cz = centre2.y; + Vec3 centre; + centre.x = cx; + centre.y = static_cast(CommonSingletonServer::m_iaiTerrain)->getTerrainAltitude(cx, cz); + centre.z = cz; + const float slack = static_cast(CommonSingletonServer::m_iaiSettings)->getIgnoreCommanderDistance(); + const float size = closest->m_size[m_side]; + bool take = closest->isInside(m_v64); + if (!take) + { + const float dx = m_v64.x - centre.x; + const float dy = m_v64.y - centre.y; + const float dz = m_v64.z - centre.z; + const float distance = std::sqrt(dx * dx + dy * dy + dz * dz); + take = !(static_cast(slack + size) <= distance) && closest->m_status[m_side] != 0; + } + if (take) + { + m_v64 = centre; + m_v28 = centre; + m_missionStatus = 2; + m_i40 = m_i76; + m_strategicAreaAssignment = closest; + m_i44 = m_requestedObject; + m_d48 = now; + m_b56 = m_b92; + accepted = true; + } + } + + if (!m_strategicAreaAssignment) + { + Vec3 position = m_v64; + if (getRandomValidPosition(member, position, 30.0f)) + { + m_v64 = position; + m_missionStatus = 2; + m_v28 = m_v64; + m_i40 = m_i76; + m_i44 = m_requestedObject; + m_b56 = m_b92; + m_d48 = now; + accepted = true; + } + else if (member->isBot()) + { + member->getBot()->getCommunicationAgent()->enqueueRadioMessage( + static_cast(7), static_cast(4), 3, 2.0f, 0); + if (member->isSquadLeader()) + { + IBFSquad* const engine = static_cast(CommonSingletonServer::m_iBFSquad); + if (m_i76 == 0) + engine->declineCommanderAttackOrder(m_squadIndex + 1, member->getPlayer()); + else if (m_i76 == 1) + engine->declineCommanderDefendOrder(m_squadIndex + 1, member->getPlayer()); + else if (m_i76 == 2) + engine->declineCommanderMoveOrder(m_squadIndex + 1, member->getPlayer()); + } + unAssignSquad(); + updateSquadPaths(); + } + } + if (!accepted) + return false; + + SquadMember* const leader = getSquadLeader(); + if (!leader->isBot()) + { + if (!IAIMain::m_instance->getSAI(m_side + 1)->isPlayerCommander() && (m_i40 == 0 || m_i40 == 1)) + SquadManager::m_instance->enqueueCommanderMessage( + m_side, m_squadIndex, static_cast(m_i40 == 0 ? 0 : 1), 3.0); + } + else + { + CommunicationAgent* const radio = leader->getBot()->getCommunicationAgent(); + if (IAIMain::m_instance->getSAI(m_side + 1)->isPlayerCommander()) + radio->enqueueRadioMessage(static_cast(6), static_cast(4), 3, 2.5f, 0); + IBFSquad* const engine = static_cast(CommonSingletonServer::m_iBFSquad); + int message = -1; + if (m_i40 == 0) + { + engine->issueSquadAttackOrder(m_v28, m_squadIndex + 1, m_side + 1, 0); + engine->acceptCommanderAttackOrder(m_squadIndex + 1, member->getPlayer()); + message = 0x10; + } + else if (m_i40 == 1) + { + engine->issueSquadDefendOrder(m_v28, m_squadIndex + 1, m_side + 1, 0); + engine->acceptCommanderDefendOrder(m_squadIndex + 1, member->getPlayer()); + message = 0xF; + } + else if (m_i40 == 2) + { + engine->issueSquadMoveOrder(m_v28, m_squadIndex + 1, m_side + 1, 0); + engine->acceptCommanderMoveOrder(m_squadIndex + 1, member->getPlayer()); + message = 0x11; + } + if (message != -1) + radio->enqueueRadioMessage(static_cast(message), static_cast(3), 3, 2.0f, 0); + } + for (unsigned int i = 0; i < m_squadMembers.size(); ++i) + m_squadMembers[i]->setHavePath(false); + return true; +} + +// ELF 0x1A4DC0 (208 bytes). Whether the navigation material under `position` for the member's +// vehicle (IAIPathfinding +0x58 getMaterial) is water (4); true without a vehicle. The vehicle +// information is not null-checked, and getMaterial's result is ignored. +bool SquadCoordinator::isPosOnWater(SquadMember* member, Vec3& position) +{ + IAIObject* const vehicle = member->getPlayer()->getCurrentVehicle(); + if (!vehicle) + return true; + Information* const info = informationManager->getInformation(vehicle->getInformation(m_side + 1)); + const int equipment = info->getUnit()->getEquipmentType(); + unsigned char material; + IAIPathfinding::instance->getMaterial(position, info->getMobile()->getVehicleNumber(), equipment, material); + return material == 4; +} + +// ELF 0x1A6B20: the accepted mission's goal (+28), only for a mission without a target object. +bool SquadCoordinator::getSquadMissionTargetPos(Vec3& position) +{ + if (m_i44) + return false; + position = m_v28; + return true; +} + // Stores side and squad identity before constructing the formation, which queries this coordinator. SquadCoordinator::SquadCoordinator(int side, int squadIndex) @@ -608,12 +1147,12 @@ SquadCoordinator::SquadCoordinator(int side, int squadIndex) , m_i40(4) , m_i44(0) , m_d48(-20.0) - , m_i60(0) + , m_requestedArea(0) , m_i76(4) - , m_i80(0) - , m_i96(-1) + , m_requestedObject(0) + , m_squadLeaderIndex(-1) , m_list104() - , m_i120(0) + , m_missionStatus(0) , m_d124(0.0) , m_d132(0.0) , m_d140(0.0) @@ -683,7 +1222,7 @@ void SquadCoordinator::getSquadPosition(Vec3& position) // used directly, including the absence of an empty-vector or negative-index guard. SquadMember* SquadCoordinator::getSquadLeader() { - return m_squadMembers[m_i96]; + return m_squadMembers[m_squadLeaderIndex]; } // Signed count consumed by the manager's comparisons. @@ -714,7 +1253,7 @@ void SquadCoordinator::unAssignSquad() m_strategicAreaAssignment = 0; m_i40 = 4; m_i44 = 0; - m_i120 = 0; + m_missionStatus = 0; } // Allocation is not checkPointer-wrapped. The human arm @@ -742,7 +1281,7 @@ void SquadCoordinator::addSquadMember(IAIPlayer* player) // change arm, but the single-member trailing-position reset still runs. void SquadCoordinator::updateSquadLeader() { - const int oldLeader = m_i96; + const int oldLeader = m_squadLeaderIndex; bool found = false; for (unsigned int i = 0; i < m_squadMembers.size(); ++i) { @@ -751,7 +1290,7 @@ void SquadCoordinator::updateSquadLeader() m_squadIndex + 1, m_squadMembers[i]->getPlayer())); if (m_squadMembers[i]->isSquadLeader()) { - m_i96 = static_cast(i); + m_squadLeaderIndex = static_cast(i); found = true; break; } @@ -759,13 +1298,18 @@ void SquadCoordinator::updateSquadLeader() if (!found) return; - if (oldLeader != m_i96 && oldLeader != -1 && !m_squadMembers.empty()) + if (oldLeader != m_squadLeaderIndex && oldLeader != -1 && !m_squadMembers.empty()) { - m_squadMembers[m_i96]->updateMemberPos(); - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - // Next: formation->joinSquadLeader, updateSquadPosition, updateSquadPaths - // then the human-leader/commander policy. Those movement bodies remain unrecovered. - BF2_AI_FRONTIER("dice::hfe::ai::SquadCoordinator::updateSquadLeader (SquadFormation::joinSquadLeader)"); + // ELF 0x1A5C66: a new leader - the formation rejoins it and the squad position and paths + // are refreshed; a human leader of a squad with more members leaves the AI commander's + // assignment (unless the side has a player commander). + m_squadMembers[m_squadLeaderIndex]->updateMemberPos(); + m_formation->joinSquadLeader(); + updateSquadPosition(); + updateSquadPaths(); + if (getSquadLeader() && !getSquadLeader()->isBot() && m_squadMembers.size() > 1 + && !IAIMain::m_instance->getSAI(m_side + 1)->isPlayerCommander()) + unAssignSquad(); } if (m_squadMembers.size() == 1) m_formation->resetTrailingPositions(); @@ -827,6 +1371,713 @@ void SquadCoordinator::resetNeedOrderMessageTimer(double now) m_needOrderMessageTimer = now; } +// ELF 0x1A3790: the per-round reset, store by store. The fire records are freed, the formation +// rejoins its leader and reassigns its slots, the need-orders timer restarts at the game time and +// every member resets its own state. +void SquadCoordinator::reset() +{ + m_strategicAreaAssignment = 0; + m_i40 = 4; + m_d48 = -20.0; + m_i44 = 0; + m_i76 = 4; + m_requestedArea = 0; + m_requestedObject = 0; + m_missionStatus = 0; + m_formation->joinSquadLeader(); + for (std::list::iterator it = m_list12.begin(); it != m_list12.end();) + { + ::operator delete(*it); + it = m_list12.erase(it); + } + m_formation->reassignSlots(); + m_v108.x = m_v108.y = m_v108.z = 0.0f; + m_i148 = 0; + m_i152 = 0; + m_d132 = 0.0; + m_d140 = 0.0; + m_b156 = false; + m_b157 = false; + m_b172 = false; + m_b196 = false; + m_v200.x = m_v200.y = m_v200.z = 0.0f; + resetNeedOrderMessageTimer(static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime()); + m_b220 = false; + for (unsigned int i = 0; i < m_squadMembers.size(); ++i) + m_squadMembers[i]->reset(); +} + +// ELF 0x1A64B0: frees and unlinks every fire record of the member's player (IAIPlayer +0x1C). +void SquadCoordinator::removeSquadMemberFire(SquadMember* member) +{ + const int playerId = member->getPlayer()->getId(); + for (std::list::iterator it = m_list12.begin(); it != m_list12.end();) + { + if ((*it)->m_playerId == playerId) + { + ::operator delete(*it); + it = m_list12.erase(it); + } + else + ++it; + } +} + +// ELF 0x1A82E0: the member leaves the fire records and, if it holds a slot, the formation; it is +// unlinked (not deleted - the caller owns it now), the remaining members are renumbered, the +// leader is re-elected and the slots are reassigned. +void SquadCoordinator::removeSquadMember(int index) +{ + SquadMember* const member = m_squadMembers[index]; + removeSquadMemberFire(member); + if (m_formation->isInFormation(member->getMemberIndex())) + m_formation->leaveFormation(member->getMemberIndex()); + m_squadMembers.erase(m_squadMembers.begin() + index); + for (unsigned int i = 0; i < m_squadMembers.size(); ++i) + m_squadMembers[i]->setMemberIndex(static_cast(i)); + updateSquadLeader(); + m_formation->reassignSlots(); +} + +// ELF 0x1A84F0: the first member with the same player id is removed by index; none, nothing. +void SquadCoordinator::removeSquadMember(SquadMember* member) +{ + for (unsigned int i = 0; i < m_squadMembers.size(); ++i) + { + if (member->getPlayerId() == m_squadMembers[i]->getPlayerId()) + { + removeSquadMember(static_cast(i)); + return; + } + } +} + +// ELF 0x1A6EC0: with an assigned area whose status for this squad's side is non-zero, true as +// soon as one member is close to that non-owned target. +bool SquadCoordinator::isSquadCloseToNonOwnedTarget() +{ + if (!m_strategicAreaAssignment || !m_strategicAreaAssignment->m_status[m_side]) + return false; + for (unsigned int i = 0; i < m_squadMembers.size(); ++i) + if (m_squadMembers[i]->isCloseToNonOwnedTarget()) + return true; + return false; +} + +// ELF 0x1A6B00: the mission state at +0x78 (m_missionStatus) equals 2. +bool SquadCoordinator::squadHasMission() +{ + return m_missionStatus == 2; +} + +// ELF 0x1A7FA0. +bool SquadCoordinator::isSquadAvailable() +{ + return m_missionStatus == 0; +} + +// ELF 0x1A7F60: the requested area's index (+0xF0). +bool SquadCoordinator::isSquadRequestedToArea(int areaIndex) +{ + bool requested = false; + if (m_requestedArea) + requested = areaIndex == m_requestedArea->getIndex(); + return requested; +} + +// ELF 0x1A3930: every member's request and record are freed, the list emptied, slots reassigned. +void SquadCoordinator::removeAll() +{ + for (unsigned int i = 0; i < m_squadMembers.size(); ++i) + { + SquadMember* const member = m_squadMembers[i]; + member->removeRequest(); + delete member; + } + m_squadMembers.resize(0); + m_formation->reassignSlots(); +} + +// ELF 0x1A83C0 (290 bytes). Like removeSquadMember, but the member record is destroyed and a +// bot's back-pointer cleared (Bot vtable +0x13C setSquadMember(0)). +void SquadCoordinator::destroySquadMember(int index) +{ + SquadMember* const member = m_squadMembers[index]; + removeSquadMemberFire(member); + member->removeRequest(); + if (m_formation->isInFormation(member->getMemberIndex())) + m_formation->leaveFormation(member->getMemberIndex()); + m_squadMembers.erase(m_squadMembers.begin() + index); + if (member->isBot()) + member->getBot()->setSquadMember(0); + delete member; + for (unsigned int i = 0; i < m_squadMembers.size(); ++i) + m_squadMembers[i]->setMemberIndex(i); + updateSquadLeader(); + m_formation->reassignSlots(); +} + +} // namespace ai +} // namespace hfe +} // namespace dice + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1A5D90, added by ai-w1-e-fire: a squad mate fired at `target`; every other bot of the +// squad sees the target's primary object (side + 1 = the image's `m_side + 1`) at the origin, +// part -1, neither direct nor flag 0x40. +void SquadCoordinator::shotsFired(int playerId, unsigned int target) +{ + const Vec3 origin = { 0.0f, 0.0f, 0.0f }; + Information* const information = informationManager->getInformation(target); + if (!information) + return; + const unsigned int primary = information->getPrimaryObject(m_side + 1); + Information* const primaryInformation = informationManager->getInformation(primary); + if (!primaryInformation) + return; + for (unsigned int i = 0; i < m_squadMembers.size(); ++i) + { + SquadMember* const member = m_squadMembers[i]; + if (!member || !member->isBot() || member->getPlayerId() == playerId) + continue; + member->getBot()->getSensingAgent()->getSenses()->event_seenObject( + primary, origin, static_cast(-1), primaryInformation, false, false); + } +} + +// ELF 0x1A86D0. +bool SquadCoordinator::isAnySquadMemberRespondingToRequest(unsigned int handle, int action) +{ + for (unsigned int i = 0; i < m_squadMembers.size(); ++i) + { + if (m_squadMembers[i]->isSameRequest(handle, action)) + return true; + } + return false; +} + +// ELF 0x1A8730 (1.7 KB). `target` is the squad member occupying the request's object (a hurt or +// downed player, a vehicle needing repair). Request actions as the callers pass them: 1 revive +// (BBRevive), 2 repair (BBBridgeRepair), 4 heal / supply (BBMedicAssist), 5 (any number may answer). +// * No occupant: 0 when someone of the side already answers; else 1, 0 beyond sqrt(20000) m of the +// squad position (+108), doubled when a human occupies the object. +// * Occupant in this squad: 0 for a revive of a living (health > 0.001) medic (kit 5) other than +// `member`; 0 for request 4 to a living engineer (kit 3); otherwise 0 when another member +// already has the request, x0.75 per such member for action 5. +// * Occupant in another squad: actions 1 / 2 / 4 within sqrt(1000) m of the squad position and with +// nobody answering: 0.5, or 0.1 when the occupant's squad has its own medic (5) / kit 4 / +// engineer (3); 0 otherwise; other actions 1. +// Finally doubled when the occupant is human. +float SquadCoordinator::requestResponseModifier(SquadMember* member, unsigned int handle, int action) +{ + SquadManager* const manager = SquadManager::m_instance; + float modifier = 1.0f; + bool skipRequests = false; + float distanceSq = 0.0f; + Vec3 position; + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; + SquadMember* const target = manager->getSquadMember(handle, m_side + 1); + bool zero = false; + if (!target) + { + if (manager->isAnySquadMemberRespondingToRequest(handle, action, m_side + 1)) + { + zero = true; + } + else + { + Information* const info = informationManager->getInformation(handle); + modifier = 1.0f; + if (info) + { + const Vec3& p = info->getPosition(); + if (20000.0f < (p.x - m_v108.x) * (p.x - m_v108.x) + (p.y - m_v108.y) * (p.y - m_v108.y) + + (p.z - m_v108.z) * (p.z - m_v108.z)) + modifier = 0.0f; + if (info->getUnit()) + { + const int occupant = info->getUnit()->getOccupyingPlayerId(m_side + 1); + if (occupant != -1 && IBotManager::instance->getBotFromPlayerId(occupant) == 0) + modifier = modifier + modifier; + } + } + } + } + else if (target->getSquadId() == member->getSquadId()) + { + if (target->getMemberIndex() != member->getMemberIndex() && action == 1) + { + // No null guard on the information (0x1A87F8). + IPIPhysical* const physical = informationManager->getInformation(handle)->getPhysical(); + if (physical && 0.001f < physical->getHealth() && target->getPlayer()->getSpawnKit() == 5) + zero = true; + } + if (!zero && action == 4 && target->getMemberIndex() != member->getMemberIndex()) + { + IPIPhysical* const physical = informationManager->getInformation(handle)->getPhysical(); + if (physical && 0.001f < physical->getHealth() && target->getPlayer()->getSpawnKit() == 3) + { + modifier = 0.0f; + skipRequests = true; + } + } + if (!zero && !skipRequests) + { + for (unsigned int i = 0; i < m_squadMembers.size(); ++i) + { + SquadMember* const other = m_squadMembers[i]; + if (member->getMemberIndex() != other->getMemberIndex() && other->isSameRequest(handle, action)) + { + if (action != 5) + { + zero = true; + break; + } + modifier = modifier * 0.75f; + } + } + } + } + else + { + const bool responding = manager->isAnySquadMemberRespondingToRequest(handle, action, m_side + 1); + if (target->getPosition(position)) + distanceSq = (position.z - m_v108.z) * (position.z - m_v108.z) + + (position.x - m_v108.x) * (position.x - m_v108.x) + + (position.y - m_v108.y) * (position.y - m_v108.y); + int kit = -1; + switch (action) + { + case 1: kit = 5; break; + case 2: kit = 4; break; + case 4: kit = 3; break; + default: break; + } + if (kit >= 0) + { + if (!responding && distanceSq < 1000.0f) + { + // No null guard on the squad (0x1A8958). + SquadCoordinator* const squad = manager->getSquadFromPlayer(target->getPlayerId(), m_side + 1); + modifier = squad->hasMemberWithKit(static_cast(kit)) ? 0.1f : 0.5f; + } + else + { + zero = true; + } + } + } + if (zero) + modifier = 0.0f; + if (target && !target->isBot()) + modifier = modifier + modifier; + return modifier; +} + +// ELF 0x1A69C0. +bool SquadCoordinator::isSameMission(BotSquad::OrderType type, const Vec3& position, IAIObject* object) +{ + if (m_i40 != static_cast(type) || m_i44 != object) + return false; + const float epsilon = 1.1920929e-07f; + if (epsilon < std::fabs(m_v28.x - position.x)) + return false; + if (epsilon < std::fabs(m_v28.y - position.y)) + return false; + return epsilon >= std::fabs(m_v28.z - position.z); +} + +// ELF 0x1A3270 (D1, 470 B; recovered on the client track). Each +// member drops its request and leaves the engine squad (IBFSquad +0x10, exitSquad with the +// 1-based squad number) before it is deleted - the member pointer is used before the null test, +// as shipped. Then the formation goes, then every fire record (plain operator delete, the node +// erased behind the iterator). The containers follow as members. +SquadCoordinator::~SquadCoordinator() +{ + for (unsigned int i = 0; i < m_squadMembers.size(); ++i) + { + SquadMember* const member = m_squadMembers[i]; + member->removeRequest(); + static_cast(CommonSingletonServer::m_iBFSquad)->exitSquad(m_squadIndex + 1, member->getPlayer()); + delete member; + } + delete m_formation; + std::list::iterator fire = m_list12.begin(); + while (fire != m_list12.end()) + { + delete *fire; + m_list12.erase(fire++); + } +} + +namespace { + +// [CHOSEN, not recovered] packaging: the engine's inline Vec2 / Vec3 normalise as the fire and +// flank bodies below spell it out (0x1A6040.., 0x1A4360..): left alone within FLT_EPSILON of unit +// length, zeroed below the threshold (Vec2: FLT_EPSILON^2, Vec3: FLT_EPSILON), else scaled by +// 1/sqrt. +void normalizeInline(Vec2& v) +{ + const float lsq = v.x * v.x + v.y * v.y; + if (std::fabs(lsq - 1.0f) < 1.1920929e-07f) + return; + if (std::fabs(lsq) < 1.4210855e-14f) + { + v.x = 0.0f; + v.y = 0.0f; + return; + } + const float inv = 1.0f / std::sqrt(lsq); + v.x = v.x * inv; + v.y = inv * v.y; +} + +void normalizeInline(Vec3& v) +{ + const float lsq = v.z * v.z + v.x * v.x + v.y * v.y; + if (std::fabs(lsq - 1.0f) < 1.1920929e-07f) + return; + if (std::fabs(lsq) < 1.1920929e-07f) + { + v.x = 0.0f; + v.y = 0.0f; + v.z = 0.0f; + return; + } + const float inv = 1.0f / std::sqrt(lsq); + v.x = v.x * inv; + v.y = v.y * inv; + v.z = inv * v.z; +} + +} // anonymous namespace + +// ELF 0x1A4250. No caller in libaidll.so. Every bot may fire. Once per mission (m_b157), with a +// mission (+0x78 == 2) and a formation leader slot: from the squad position (m_v108) towards the +// accepted mission position (m_v28, put on the terrain), with probability 0.3 (0.6 when the squad +// cannot see the target), the leader (slot 0) is given two flank points: the half-distance point +// of the direction turned by 0.781 rad (sign at random), then half the distance further along the +// direction; each is randomised within a quarter of the distance. When either fails the other +// side is tried; on success m_b156 is set and the leader re-paths. The leader's liveness is +// tested only after the null test. +void SquadCoordinator::squadManeuverDynamicFlank() +{ + for (unsigned int index = 0; index < m_squadMembers.size(); ++index) + { + SquadMember* const member = m_squadMembers[index]; + if (member->isBot()) + member->getBot()->setAllowFire(true); // +0x134 + } + if (m_b157 || m_missionStatus != 2 || !m_formation->hasSquadMembers()) + return; + m_b157 = true; + SquadMember* const leader = m_squadMembers[m_formation->getSquadMemberIndexAtSlot(0)]; + + Vec3 direction; + direction.x = m_v28.x - m_v108.x; + direction.y = m_v28.y - m_v108.y; + direction.z = m_v28.z - m_v108.z; + float distance = + std::sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z); + normalizeInline(direction); + + Vec3 target = m_v28; + Vec3 turned; + turned.x = 0.0f; + turned.y = 0.0f; + turned.z = 0.0f; + target.y = static_cast(CommonSingletonServer::m_iaiTerrain) + ->getTerrainAltitude(target.x, target.z); // +0x14 + float probability = 0.3f; + float angle = 0.781f; + if (!canSeePos(m_v108, target)) + probability = probability + probability; + if (!(AIRandom::m_instance->nextFloat() < probability) || leader == 0) + return; + if (!leader->getPlayer()->getIsAlive()) + return; + const float half = 0.5f; + if (half < AIRandom::m_instance->nextFloat()) + angle = -angle; + rotateXZ(direction, turned, angle); + m_positions[0].x = distance * turned.x * half + m_v108.x; + m_positions[0].y = distance * turned.y * half + m_v108.y; + m_positions[0].z = distance * turned.z * half + m_v108.z; + m_positions[1].x = distance * direction.x * half + m_positions[0].x; + m_positions[1].y = distance * direction.y * half + m_positions[0].y; + m_positions[1].z = half * distance * direction.z + m_positions[0].z; + const float radius = distance * 0.25f; + if (!getRandomValidFlankPos(leader, radius, m_positions[0]) + || !getRandomValidFlankPos(leader, radius, m_positions[1])) + { + angle = -angle; + rotateXZ(direction, turned, angle); + m_positions[0].x = distance * turned.x * half + m_v108.x; + m_positions[0].y = distance * turned.y * half + m_v108.y; + m_positions[0].z = distance * turned.z * half + m_v108.z; + m_positions[1].x = distance * direction.x * half + m_positions[0].x; + m_positions[1].y = distance * direction.y * half + m_positions[0].y; + m_positions[1].z = distance * direction.z * half + m_positions[0].z; + distance = distance * 0.25f; + if (!getRandomValidFlankPos(leader, distance, m_positions[0])) + return; + if (!getRandomValidFlankPos(leader, distance, m_positions[1])) + return; + } + m_b156 = true; + leader->setHavePath(false); +} + +// ELF 0x1A4A10. A line one metre above both points, ignoring the squad's vehicles +// (IAIObjectEnvironment +0x40, collideLineWithWorld(from, to, ignore, false, 0, true, hit)): +// visible when nothing is hit. +bool SquadCoordinator::canSeePos(const Vec3& from, const Vec3& to) +{ + Vec3 start = from; + start.y = from.y + 1.0f; + Vec3 end = to; + end.y = 1.0f + to.y; + std::vector ignore; + getSquadIgnoreList(ignore); + bool hit; + const bool collided = static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->collideLineWithWorld(start, end, ignore, false, 0.0f, true, hit); + return !collided; +} + +// ELF 0x1A4B10: the two flank points. +void SquadCoordinator::getFlankingCoords(std::vector& coords) +{ + coords = m_positions; +} + +// ELF 0x1A4B60. `position` put on the terrain is kept when it is valid for `member` and not on +// water - then `position` itself is NOT updated (its height stays as given). Otherwise up to ten +// random points in the square of half-side `radius` around it; the first good one is stored. +bool SquadCoordinator::getRandomValidFlankPos(SquadMember* member, float radius, Vec3& position) +{ + IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + bool found = true; + Vec3 candidate = position; + candidate.y = terrain->getTerrainAltitude(candidate.x, candidate.z); // +0x14 + if (!isValidPosition(member, candidate) || isPosOnWater(member, candidate)) + { + found = false; + for (int attempt = 0; attempt < 10; ++attempt) + { + const float lowX = position.x - radius; + const float drawX = AIRandom::m_instance->nextFloat() * radius; + candidate.x = drawX + drawX + lowX; + const float lowZ = position.z - radius; + const float drawZ = AIRandom::m_instance->nextFloat() * radius; + candidate.z = drawZ + drawZ + lowZ; + candidate.y = terrain->getTerrainAltitude(candidate.x, candidate.z); + if (isValidPosition(member, candidate) && !isPosOnWater(member, candidate)) + { + position = candidate; + return true; + } + } + } + return found; +} + +// ELF 0x1A5F00 (SquadManager::shotsFired). Nothing unless the shooter has a position. An existing +// record of the shooter is refreshed: when the shot's XZ direction turns away from the record's +// re-path direction (normalised dot below 0.1) that direction is replaced and the whole squad +// re-paths; then the latest direction and position, the expiry (now + 10 s) and the firing target +// (Bot +0x80 for a bot, else -1) are stored. Without a record a new one is appended with both +// directions and both positions from this shot, and the squad re-paths. +void SquadCoordinator::shotsFired(int playerId, const Vec3& direction) +{ + Vec3 position; + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + Vec2 shot; + shot.x = direction.x; + shot.y = direction.z; + int target = -1; + int index = 0; + Vec2 previous; + previous.x = 0.0f; + previous.y = 0.0f; + SquadMember* const shooter = getSquadMember(playerId, index); + if (!shooter->getPosition(position)) + return; + + std::list::iterator it = m_list12.begin(); + for (; it != m_list12.end(); ++it) + { + SquadMemberFire* const fire = *it; + if (playerId != fire->m_playerId) + continue; + vec3ToVec2XZ(fire->m_v20, previous); + normalizeInline(previous); + normalizeInline(shot); + if (shot.x * previous.x + shot.y * previous.y < 0.1f) + { + fire->m_v20 = direction; + for (unsigned int i = 0; i < m_squadMembers.size(); ++i) + m_squadMembers[i]->setHavePath(false); + m_formation->updateMovementFlag(true); + } + fire->m_v8 = direction; + fire->m_v40 = position; + fire->m_time = now + 10.0f; + if (shooter->isBot()) + target = static_cast(shooter->getBot()->getFiringTarget()); // +0x80 + fire->m_i64 = target; + break; + } + if (it != m_list12.end()) + return; + + if (shooter->isBot()) + target = static_cast(shooter->getBot()->getFiringTarget()); + SquadMemberFire* const fire = new SquadMemberFire; + fire->m_v8.x = fire->m_v8.y = fire->m_v8.z = 0.0f; + fire->m_v20.x = fire->m_v20.y = fire->m_v20.z = 0.0f; + fire->m_v40.x = fire->m_v40.y = fire->m_v40.z = 0.0f; + fire->m_position.x = fire->m_position.y = fire->m_position.z = 0.0f; + fire->m_v20 = direction; + fire->m_v8 = direction; + fire->m_playerId = playerId; + fire->m_member = getSquadMember(playerId, index); + fire->m_v40 = position; + fire->m_position = position; + fire->m_i64 = target; + fire->m_time = now + 10.0f; + m_list12.push_back(fire); + for (unsigned int i = 0; i < m_squadMembers.size(); ++i) + m_squadMembers[i]->setHavePath(false); + m_formation->updateMovementFlag(true); +} + +// ELF 0x1A6570: any fire record (the list is counted). +bool SquadCoordinator::anyFiring() +{ + return m_list12.size() != 0; +} + +// ELF 0x1A65B0: a fire record of `playerId`. +bool SquadCoordinator::isFiring(int playerId) +{ + for (std::list::iterator it = m_list12.begin(); it != m_list12.end(); ++it) + if (playerId == (*it)->m_playerId) + return true; + return false; +} + +// ELF 0x1A6610: distance output is written only when a nearer eligible shooter is found. +SquadMember* SquadCoordinator::getClosestFiringMember(SquadMember* member, float& distanceSquared) +{ + SquadMember* closest = 0; + Vec3 position = {}; + Vec3 candidatePosition = {}; + const int playerId = member->getPlayerId(); + float nearest = FLT_MAX; + if (!member->getPosition(position)) + return closest; + for (std::list::iterator it = m_list12.begin(); it != m_list12.end(); ++it) + { + SquadMemberFire* const fire = *it; + SquadMember* const candidate = fire->m_member; + if (candidate->getPlayerId() == playerId || !candidate->getPosition(candidatePosition) + || !candidate->getPlayer()->getIsAlive() + || !m_formation->isInFormation(candidate->getMemberIndex()) + || !member->canDamageTarget(static_cast(fire->m_i64))) + continue; + if (candidate->isSquadLeader() && m_formation->shouldLeaveSquadLeader()) + continue; + const float dx = position.x - candidatePosition.x; + const float dy = position.y - candidatePosition.y; + const float dz = position.z - candidatePosition.z; + const float squared = dx * dx + dy * dy + dz * dz; + if (nearest > squared) + { + nearest = squared; + closest = candidate; + distanceSquared = squared; + } + } + return closest; +} + +// ELF 0x1A6820: the member's latest shot direction, (1, 0, 0) without a record. +Vec3 SquadCoordinator::getFiringDir(SquadMember* member) +{ + Vec3 direction; + direction.y = 0.0f; + direction.z = 0.0f; + direction.x = 1.0f; + for (std::list::iterator it = m_list12.begin(); it != m_list12.end(); ++it) + { + SquadMemberFire* const fire = *it; + if (fire->m_playerId == member->getPlayerId()) + { + direction = fire->m_v8; + return direction; + } + } + return direction; +} + +// ELF 0x1A6A60. Compares the requested mission (+0x4C type, +0x50 object, +0x40 position), not +// the accepted one isSameMission reads. +bool SquadCoordinator::isSameRequest(BotSquad::OrderType type, const Vec3& position, IAIObject* object) +{ + bool same = false; + if (m_i76 == static_cast(type) && m_requestedObject == object) + { + const float epsilon = 1.1920929e-07f; + if (std::fabs(m_v64.x - position.x) <= epsilon && std::fabs(m_v64.y - position.y) <= epsilon) + same = std::fabs(m_v64.z - position.z) <= epsilon; + } + return same; +} + +// ELF 0x1A7940. +SquadMember* SquadCoordinator::getBotInSquad() +{ + for (unsigned int index = 0; index < m_squadMembers.size(); ++index) + if (m_squadMembers[index]->isBot()) + return m_squadMembers[index]; + return 0; +} + +// ELF 0x1A7E70: by value. +std::list SquadCoordinator::getListOfAreaNavPoints() +{ + return m_list104; +} + +// ELF 0x1A8580. +void SquadCoordinator::getSquadIgnoreList(std::vector& ignore) +{ + for (unsigned int index = 0; index < m_squadMembers.size(); ++index) + { + IAIObject* const vehicle = m_squadMembers[index]->getPlayer()->getCurrentVehicle(); // +0x54 + if (vehicle != 0) + ignore.push_back(vehicle); + } +} + +// ELF 0x1A8680. +bool SquadCoordinator::squadHasHumanPlayer() +{ + for (unsigned int index = 0; index < m_squadMembers.size(); ++index) + if (!m_squadMembers[index]->isBot()) + return true; + return false; +} + } // namespace ai } // namespace hfe } // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.h b/Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.h index d05604461..756d9c85b 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.h @@ -1,6 +1,4 @@ // Coordinates squad membership, leadership and its owned formation. -// [FRONTIER] Leader-change movement remains incomplete. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. // [INFERRED] Source placement. #ifndef AI_AIDLL_AI_AIBOT_SQUADCOORDINATOR_H // [INFERRED] guard style @@ -10,6 +8,7 @@ #include #include "../../../../Math/Vec3.h" +#include "BotSquad.h" // BotSquad::OrderType namespace dice { namespace hfe { @@ -20,29 +19,33 @@ class SquadFormation; class SquadMember; class IAIPlayer; class AIStrategicArea; +class AIStrategicObject; +class Bot; +class IAIObject; enum StrategicStrengthType : int; // Attested type name; enum labels remain unrecovered. class SquadCoordinator { public: // attested nested type name: `std::list` insert/erase/clear - // are instantiated. on the ELF (`shotsFired` allocates 0x44), four Vec3s zeroed by - // the allocation; the scalar members are written field by field. Roles come from shotsFired - // (, ), removeSquadMemberFire and updateShotsFired; names are [INFERRED]. - // Nothing in this tree allocates one yet, so the list stays empty on every exercised path. + // are instantiated. on the ELF (`shotsFired(int, const Vec3&)`, ELF 0x1A5F00, allocates 0x44), + // four Vec3s zeroed by the allocation; the scalar members are written field by field. Roles + // come from shotsFired, getFiringDir, removeSquadMemberFire and updateShotsFired; names are + // [INFERRED]. struct SquadMemberFire { /* +0x00 */ double m_time; // expiry: game time + 10 s, restamped on each shot - /* +0x08 */ Vec3 m_v8; // the shotsFired Vec3 argument [UNRESOLVED role] - /* +0x14 */ Vec3 m_v20; // seeded from it too; refreshed conditionally [UNRESOLVED] + /* +0x08 */ Vec3 m_v8; // the latest shot's direction; getFiringDir answers it + /* +0x14 */ Vec3 m_v20; // the direction at the last re-path (turns past dot 0.1) /* +0x20 */ int m_playerId; // the shotsFired int; the search/removal key /* +0x24 */ SquadMember* m_member; // getSquadMember(playerId, index), borrowed - /* +0x28 */ Vec3 m_v40; // shooter position at the latest shot [UNRESOLVED role] + /* +0x28 */ Vec3 m_v40; // shooter position at the latest shot /* +0x34 */ Vec3 m_position; // shooter position at the first shot; the 5 m anchor - /* +0x40 */ int m_i64; // 1, or the shooting bot's slot +0x80 answer [UNRESOLVED] + /* +0x40 */ int m_i64; // the shooting bot's firing target (Bot +0x80), else -1 }; SquadCoordinator(int side, int squadIndex); + ~SquadCoordinator(); // ELF 0x1A3270 (D1) void update(double time); // complete order void updateSquadPosition(); // complete @@ -52,7 +55,9 @@ class SquadCoordinator void updateIncomingMessages(); // radio-enqueue seam bool isSquadTakingFlag(); // complete void updateSquadManeuver(); // selected maneuver seams - int chooseSquadManeuver(); // integer payload, enum spelling unresolved + int chooseSquadManeuver(); // ELF 0x1A56A0: 0 none, 1 alternate fire, 2 static flank + void squadManeuverAlternateFire(); // ELF 0x1A4E90 + void squadManeuverStaticFlank(); // ELF 0x1A4060 void updateSquadPaths(); // complete invalidation loop int getSide(); int getMissionStatus(); // integer payload, enum spelling unresolved @@ -71,9 +76,79 @@ class SquadCoordinator SquadMember* getSquadMember(int index); SquadMember* getSquadMember(int playerId, int& index); bool hasMemberWithKit(KitType type); + // ELF 0x1A86D0: a member's pending request is (handle, action) (SquadMember::RequestAction). + bool isAnySquadMemberRespondingToRequest(unsigned int handle, int action); + // ELF 0x1A8730: how much `member` should answer the request (handle, action); see the .cpp. + float requestResponseModifier(SquadMember* member, unsigned int handle, int action); bool isSquadAssignedToAnyArea(); AIStrategicArea* getSquadStrategicAreaAssignment(); // borrowed void resetNeedOrderMessageTimer(double now); + void reset(); // ELF 0x1A3790 + void removeSquadMemberFire(SquadMember* member); // ELF 0x1A64B0 + bool isSquadCloseToNonOwnedTarget(); // ELF 0x1A6EC0 + bool squadHasMission(); // ELF 0x1A6B00: +0x78 == 2 + bool isSquadAvailable(); // ELF 0x1A7FA0: +0x78 == 0 + void removeAll(); // ELF 0x1A3930 + void destroySquadMember(int index); // ELF 0x1A83C0 + bool getValidSaPos(SquadMember* member, Vec3& position); // ELF 0x1A7BC0 + // [CHOSEN, not recovered] declaration placement; added by ai-w1-e-fire for + // BBPFireInfantery::createPlanInternal (coord/ai-requests.md 2026-11-01). ELF 0x1A5D90. + void shotsFired(int playerId, unsigned int target); + bool getValidSaPos(SquadMember* member, AIStrategicArea* area, Vec3& position); // ELF 0x1A7D30 + bool isValidPosition(SquadMember* member, const Vec3& position); // ELF 0x1A6B60 + // The requested-mission record (+60..+95), copied out by value by getMissionRequest. Its + // twin at +24..+59 is the accepted mission. [INFERRED] names. + struct MissionRequest + { + /* +0x00 */ AIStrategicArea* m_area; + /* +0x04 */ Vec3 m_position; + /* +0x10 */ int m_type; // BotSquad::OrderType, 4 = none + /* +0x14 */ IAIObject* m_object; + /* +0x18 */ double m_time; // requestMission: the update time + 10 s lives at +132 instead + /* +0x20 */ bool m_commander; // the order came from the commander + }; + MissionRequest getMissionRequest(); // ELF 0x1A3A40 + void requestRepair(const Vec3& position); // ELF 0x1A4950 + bool acceptMission(SquadMember* member); // ELF 0x1A7160 + bool isPosOnWater(SquadMember* member, Vec3& position); // ELF 0x1A4DC0 + bool getSquadMissionTargetPos(Vec3& position); // ELF 0x1A6B20 + bool getRandomValidPosition(SquadMember* member, Vec3& position, float radius); // ELF 0x1A79C0 + void requestMission(BotSquad::OrderType type, const Vec3& position, IAIObject* object, bool commander); // ELF 0x1A6F30 + // ELF 0x1A69C0: the accepted order (+40 type, +44 object, +28 position within FLT_EPSILON per axis). + bool isSameMission(BotSquad::OrderType type, const Vec3& position, IAIObject* object); + const Vec3& getSquadLeaderGotoPos() { return m_v200; } // ELF 0x1A7FE0: this + 0xC8 + int getSquadLeaderIndex() { return m_squadLeaderIndex; } // ELF 0x1A5D70: +0x60 + bool isRepairRequested() { return m_b172; } // ELF 0x1A49F0: movzbl +0xAC + Vec3& getRepairRequestPos() { return m_v176; } // ELF 0x1A4A00: this + 0xB0 + void setRogerThatPositionMessage(bool roger) { m_b220 = roger; } // ELF 0x1A39F0: +0xDC + bool getRogerThatPositionMessage() { return m_b220; } // ELF 0x1A3A10: +0xDC + bool isSquadRequestedToArea(int areaIndex); // ELF 0x1A7F60 + void removeSquadMember(int index); // ELF 0x1A82E0 + void removeSquadMember(SquadMember* member); // ELF 0x1A84F0 + + // Dynamic flanking (no caller in libaidll.so), its line-of-sight and position helpers. + void squadManeuverDynamicFlank(); // ELF 0x1A4250 + bool canSeePos(const Vec3& from, const Vec3& to); // ELF 0x1A4A10 + void getFlankingCoords(std::vector& coords); // ELF 0x1A4B10 + bool haveFlankingCoords() { return m_b156; } // ELF 0x1A4B50 + bool getRandomValidFlankPos(SquadMember* member, float radius, Vec3& position); // ELF 0x1A4B60 + int getSquadManeuver() { return m_i148; } // ELF 0x1A5690 + // Fire records: shotsFired(int, const Vec3&) is SquadManager::shotsFired's per-squad half. + void shotsFired(int playerId, const Vec3& direction); // ELF 0x1A5F00 + bool anyFiring(); // ELF 0x1A6570 + bool isFiring(int playerId); // ELF 0x1A65B0 + SquadMember* getClosestFiringMember(SquadMember* member, float& distanceSquared); + Vec3 getFiringDir(SquadMember* member); // ELF 0x1A6820 + // Repair confirmation (BBPBridgeRepair). + void confirmRepairRequested() { m_b196 = true; } // ELF 0x1A49D0 + bool haveConfirmedRepairRequest() { return m_b196; } // ELF 0x1A49E0 + // The requested (not the accepted) mission is (type, position within FLT_EPSILON, object). + bool isSameRequest(BotSquad::OrderType type, const Vec3& position, IAIObject* object); // ELF 0x1A6A60 + SquadMember* getBotInSquad(); // ELF 0x1A7940: the first bot member, or null + std::list getListOfAreaNavPoints(); // ELF 0x1A7E70: a copy + // Appends every member's current vehicle (IAIPlayer +0x54) that is not null. + void getSquadIgnoreList(std::vector& ignore); // ELF 0x1A8580 + bool squadHasHumanPlayer(); // ELF 0x1A8680: any member that is not a bot // layout, on the ELF, read store by store out of the constructor // The [UNRESOLVED] gaps hold position and claim nothing; the constructor never writes them. @@ -84,19 +159,26 @@ class SquadCoordinator /* +24 */ AIStrategicArea* m_strategicAreaAssignment; // [INFERRED] name; ELF +0x18 / PE +0x28, borrowed; initially null /* +28 */ Vec3 m_v28; // zeroed [UNRESOLVED] /* +40 */ int m_i40; // = 4 [UNRESOLVED] - /* +44 */ int m_i44; // = 0 [UNRESOLVED] - /* +48 */ double m_d48; // = -20.0 a "never happened" sentinel, not a time - /* +56 */ char m_gap56[4]; // never written by the constructor - /* +60 */ int m_i60; // = 0 [UNRESOLVED] + /* +44 */ IAIObject* m_i44; // = 0; acceptMission: the request's object. DICE: m_mission.target + // (AIDLL_r assert "m_mission.target == 0", 0x101BA880) + /* +48 */ double m_d48; // = -20.0 a "never happened" sentinel; acceptMission: the game time + /* +56 */ bool m_b56; // never written by the constructor; acceptMission: the request's commander flag + // isSquadRequestedToArea (ELF 0x1A7F60) compares the area index at +0xF0 of this pointer. + /* +60 */ AIStrategicArea* m_requestedArea; // = 0 [CHOSEN] name /* +64 */ Vec3 m_v64; // zeroed [UNRESOLVED] /* +76 */ int m_i76; // = 4 [UNRESOLVED] - the twin of m_i40 - /* +80 */ int m_i80; // = 0 [UNRESOLVED] - /* +84 */ char m_gap84[12]; // never written by the constructor - /* +96 */ int m_i96; // leader member index, initially -1 + /* +80 */ IAIObject* m_requestedObject; // = 0; requestMission's object [INFERRED] name + /* +84 */ double m_d84; // never written by the constructor; getMissionRequest copies it + /* +92 */ bool m_b92; // requestMission: the order came from the commander. DICE: + // m_missionRequest.isCommanderOrder (AIDLL_r assert, 0x101BA880) + /* +96 */ int m_squadLeaderIndex; // leader member index, initially -1. Name: AIDLL_r assert + // "m_squadLeaderIndex >= 0" in getSquadLeaderIndex (0x101B8910, PE +0x78) /* +100 */ SquadFormation* m_formation; // new SquadFormation(this) - /* +104 */ std::list m_list104; // header only; 4-byte element [UNRESOLVED] + /* +104 */ std::list m_list104; // the area nav points; getListOfAreaNavPoints copies it /* +108 */ Vec3 m_v108; // zeroed twice - once before the formation, once after - /* +120 */ int m_i120; // = 0 [UNRESOLVED] + // 0 = available (isSquadAvailable, ELF 0x1A7FA0), 2 = has a mission (squadHasMission). + /* +120 */ int m_missionStatus; // = 0. Name: AIDLL_r assert "m_missionStatus == MSOnMission" + // (getSquadMissionTargetPos 0x101B8B00 compares PE +0x98 with 2) /* +124 */ double m_d124; // = 0.0 [UNRESOLVED] /* +132 */ double m_d132; // = 0.0 [UNRESOLVED] /* +140 */ double m_d140; // = 0.0 [UNRESOLVED] @@ -111,9 +193,9 @@ class SquadCoordinator /* +176 */ Vec3 m_v176; // zeroed; getRepairRequestPos returns its address /* +188 */ double m_d188; // request deadline; the constructor never writes it /* +196 */ bool m_b196; // = false; haveConfirmedRepairRequest - /* +200 */ Vec3 m_v200; // zeroed twice, like m_v108 + /* +200 */ Vec3 m_v200; // zeroed twice, like m_v108; getSquadLeaderGotoPos /* +212 */ double m_needOrderMessageTimer; // = IBFTimer::getGameTime at construction - /* +220 */ bool m_b220; // = false [UNRESOLVED] + /* +220 */ bool m_b220; // = false; get/setRogerThatPositionMessage }; } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.cpp index a146ef12f..e7c017745 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.cpp @@ -1,16 +1,30 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining SquadFormation operations. +#if defined(__APPLE__) +#include "../../../../Platform/X87Compat.h" // [CHOSEN, not recovered] +#endif #include "SquadFormation.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1ACBB0, __tcf_0 0x1ACC10, _GLOBAL__I 0x1ACC40). +#include + +#include + #include #include "SquadCoordinator.h" #include "SquadMember.h" #include "../Main/AIDllFrontier.h" #include "../Main/CommonSingletonServer.h" +#include "../Main/AIRandom.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" #include "../../../AIInterface/BFKnowledge/AIPlayer.h" // IAIPlayer::getCurrentVehicle #include "../../../AIInterface/BFKnowledge/BFGame.h" // IAIGame::getMaxNumberOfSquadMembers #include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" namespace dice { namespace hfe { @@ -68,10 +82,17 @@ static bool formationLeaderWithinRange(const Vec3& leader, const Vec3& squad) notWithin: } return within; +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + const bf2x87::Real deltaX = static_cast(leader.x) - squad.x; + const bf2x87::Real deltaY = static_cast(leader.y) - squad.y; + const bf2x87::Real deltaZ = static_cast(leader.z) - squad.z; #else const long double deltaX = static_cast(leader.x) - squad.x; const long double deltaY = static_cast(leader.y) - squad.y; const long double deltaZ = static_cast(leader.z) - squad.z; +#endif #if defined(_WIN32) return (deltaZ * deltaZ + deltaY * deltaY) + deltaX * deltaX < 2500.0L; #else @@ -108,16 +129,28 @@ static bool trailPointIsSet(const Vec3& point) notSet: } return set; +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + const bf2x87::Real x = point.x; + const bf2x87::Real y = point.y; + const bf2x87::Real z = point.z; #else const long double x = point.x; const long double y = point.y; const long double z = point.z; +#endif #if defined(_WIN32) return (z * z + y * y) + x * x > static_cast(0.001f); +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + return (y * y + x * x) + z * z > static_cast(0.001f); #else return (y * y + x * x) + z * z > static_cast(0.001f); #endif #endif +#endif } // [INFERRED] local name. Squared distance between the anchor and the newest crumb, narrowed @@ -159,6 +192,13 @@ static float trailCrumbDistanceSq(const Vec3& anchor, const Vec3& crumb) const long double dy = static_cast(static_cast(anchor.y) - crumb.y); const long double dz = static_cast(static_cast(anchor.z) - crumb.z); return static_cast((dx * dx + dy * dy) + dz * dz); +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + const bf2x87::Real dx = static_cast(crumb.x) - anchor.x; + const bf2x87::Real dy = static_cast(crumb.y) - anchor.y; + const bf2x87::Real dz = static_cast(crumb.z) - anchor.z; + return static_cast((dy * dy + dx * dx) + dz * dz); #else const long double dx = static_cast(crumb.x) - anchor.x; const long double dy = static_cast(crumb.y) - anchor.y; @@ -166,6 +206,7 @@ static float trailCrumbDistanceSq(const Vec3& anchor, const Vec3& crumb) return static_cast((dy * dy + dx * dx) + dz * dz); #endif #endif +#endif } // [INFERRED] local name. A claimed member's squared distance to the anchor, stored as the sort @@ -200,11 +241,22 @@ static float trailMemberDistanceSq(const Vec3& position, const Vec3& anchor) #else #if defined(_WIN32) const long double dx = static_cast(static_cast(position.x) - anchor.x); +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + const bf2x87::Real dx = static_cast(position.x) - anchor.x; #else const long double dx = static_cast(position.x) - anchor.x; #endif +#endif +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + const bf2x87::Real dy = static_cast(position.y) - anchor.y; + const bf2x87::Real dz = static_cast(position.z) - anchor.z; +#else const long double dy = static_cast(position.y) - anchor.y; const long double dz = static_cast(position.z) - anchor.z; +#endif #if defined(_WIN32) return static_cast((dz * dz + dy * dy) + dx * dx); #else @@ -243,21 +295,37 @@ void SquadFormation::selectFormation() m_formation = FormationLine; } -// Updates the formation direction from its anchor member. An empty anchor returns immediately. -// [FRONTIER] The occupied-anchor path requires the remaining information queries. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding SquadFormation operation. +// ELF 0x1AB470: the anchor's (slot 0) vehicle speed (IAIPlayer +0x54 getCurrentVehicle, its +// information for side m_side + 1, Information +0x38 IPIMobile +0x1C getSpeed, copied) sets the +// forward vector when its squared length exceeds 0.25f (0x49CE84): vec3ToVec2XZ into m_forward, +// then the inlined Vec2 normalisation (left alone within 1.1920929e-07f (0x49CC7C) of unit length, +// zeroed below 1.4210855e-14f (0x49CCA4), else scaled by 1 / sqrt). An empty anchor returns. void SquadFormation::updateFormationForwardVector() { - Vec3 speed = {}; Slot* const anchor = m_slots[0]; - if (!anchor->m_occupied) + if (!anchor->hasSquadMemberAssigned) return; IAIPlayer* const player = m_coordinator->getSquadMember(anchor->m_memberIndex)->getPlayer(); IAIObject* const vehicle = player->getCurrentVehicle(); - (void)speed; - (void)vehicle; - BF2_AI_FRONTIER("dice::hfe::ai::SquadFormation::updateFormationForwardVector (IAIObject information query)"); + Information* const info = informationManager->getInformation(vehicle->getInformation(m_side + 1)); + const Vec3 speed = info->getMobile()->getSpeed(); + if (!(speed.x * speed.x + speed.y * speed.y + speed.z * speed.z > 0.25f)) + return; + + vec3ToVec2XZ(speed, m_forward); + const float lengthSq = m_forward.x * m_forward.x + m_forward.y * m_forward.y; + if (std::fabs(lengthSq - 1.0f) < 1.1920929e-07f) + return; + if (std::fabs(lengthSq) < 1.4210855e-14f) + { + m_forward.x = 0.0f; + m_forward.y = 0.0f; + return; + } + const float inverse = 1.0f / std::sqrt(lengthSq); + m_forward.y = m_forward.y * inverse; + m_forward.x = m_forward.x * inverse; } // Adds a trail position when the anchor moves more than six metres from the last position. @@ -271,7 +339,7 @@ void SquadFormation::updateTrailingPositions() m_trailingPosition = m_v72; return; } - if (!anchor->m_occupied) + if (!anchor->hasSquadMemberAssigned) return; const float distanceSq = trailCrumbDistanceSq(m_v72, m_trailingPosition); @@ -280,14 +348,14 @@ void SquadFormation::updateTrailingPositions() if (!(distanceSq > 36.0f)) return; - for (unsigned int index = m_maxSquadMembers - 1; index != 0; --index) + for (unsigned int index = m_numberOfSlots - 1; index != 0; --index) { // Two statements: both images reload the vector's storage after the byte store. - m_slotTargets[index].first = m_slotTargets[index - 1].first; - m_slotTargets[index].second = m_slotTargets[index - 1].second; + m_trailingPositions[index].first = m_trailingPositions[index - 1].first; + m_trailingPositions[index].second = m_trailingPositions[index - 1].second; } - m_slotTargets[0].first = true; - m_slotTargets[0].second = m_trailingPosition; + m_trailingPositions[0].first = true; + m_trailingPositions[0].second = m_trailingPosition; m_trailingPosition = m_v72; } @@ -297,10 +365,10 @@ void SquadFormation::updateTrailingSlots() std::list members; Vec3 position = {}; - for (unsigned int index = 0; index < m_maxSquadMembers; ++index) + for (unsigned int index = 0; index < m_numberOfSlots; ++index) { Slot* const slot = m_slots[index]; - if (slot->m_i20 != -1 && slot->m_occupied) + if (slot->m_i20 != -1 && slot->hasSquadMemberAssigned) { SquadMember* const member = m_coordinator->getSquadMember(slot->m_memberIndex); member->getPosition(position); @@ -315,7 +383,7 @@ void SquadFormation::updateTrailingSlots() members.sort(); Slot* slot = 0; - for (unsigned int index = 0; index < m_maxSquadMembers; ++index) + for (unsigned int index = 0; index < m_numberOfSlots; ++index) { slot = m_slots[index]; slot->m_i20 = -1; @@ -325,7 +393,7 @@ void SquadFormation::updateTrailingSlots() for (std::list::iterator it = members.begin(); it != members.end(); ++it) { SquadMember* const member = it->m_member; - for (unsigned int index = 1; index < m_maxSquadMembers; ++index) + for (unsigned int index = 1; index < m_numberOfSlots; ++index) { slot = m_slots[index]; if (slot->m_memberIndex == member->getMemberIndex()) @@ -356,6 +424,125 @@ void SquadFormation::joinSquadLeader() updateMovementFlag(true); } +// ELF 0x1AC550 (1248 bytes). The world position of `memberIndex`'s slot: the squad position plus +// the slot offset rotated by the forward vector (normalised when not unit length; the angle is +// acos(y), negated for x > 0). Slot 0 (the leader's) is always taken; another slot only when the +// position is valid for its member and not on water (its trailing fallback is then released), +// otherwise its trailing position - claiming the first free one, and failing that the mission +// target (only for a mission without an object) or the slot-0 member's position. Without a squad +// position the leader's position is used. +bool SquadFormation::getSlotWorldPos(int memberIndex, Vec3& position) +{ + bool found = true; + Vec3 squad = {}; + m_coordinator->getSquadPosition(squad); + if ((0.0f - squad.x) * (0.0f - squad.x) + (0.0f - squad.y) * (0.0f - squad.y) + + (0.0f - squad.z) * (0.0f - squad.z) < 0.001f) + { + found = false; + if (m_coordinator->getSquadLeader()->getPosition(position)) + found = true; + return found; + } + float fx = m_forward.x; + float fy = m_forward.y; + for (unsigned int i = 0; i < m_numberOfSlots; ++i) + { + Slot* const slot = m_slots[i]; + if (slot->m_memberIndex != memberIndex) + continue; + const Vec3 offset = slot->m_offset; + const float lengthSq = fx * fx + fy * fy; + if (1.1920929e-07f <= std::fabs(lengthSq - 1.0f)) + { + if (1.4210855e-14f <= std::fabs(lengthSq)) + { + const float inverse = 1.0f / std::sqrt(lengthSq); + fx = fx * inverse; + fy = inverse * fy; + } + else + { + fx = 0.0f; + fy = 0.0f; + } + } + float clamped = -1.0f; + if (-1.0f <= fy) + { + clamped = 1.0f; + if (fy <= 1.0f) + clamped = fy; + } + float angle = std::acos(clamped); + if (0.0f < fx) + angle = -angle; + const float s = std::sin(angle); + position.x = squad.x + (offset.x * fy - offset.z * s); + position.y = offset.y + squad.y; + position.z = squad.z + offset.x * s + offset.z * fy; + if (i == 0) + return true; + SquadMember* member = m_coordinator->getSquadMember(slot->m_memberIndex); + if (m_coordinator->isValidPosition(member, position) && !m_coordinator->isPosOnWater(member, position)) + { + slot->m_i20 = -1; + return true; + } + int trail = slot->m_i20; + if (trail == -1) + { + trail = getFirstFreeTrailingSlot(member); + if (trail == -1) + { + if (m_coordinator->squadHasMission()) + return m_coordinator->getSquadMissionTargetPos(position); + member = m_coordinator->getSquadMember(getSquadMemberIndexAtSlot(0)); + if (!member) + return false; + return member->getPosition(position); + } + slot->m_i20 = trail; + } + position = m_trailingPositions[trail].second; + return true; + } + return found; +} + +// ELF 0x1ACA30 (320 bytes). The first trailing position that is set, unclaimed by any slot and +// valid for `member`; -1 when none. (The image also computes, and drops, the distance to it.) +int SquadFormation::getFirstFreeTrailingSlot(SquadMember* member) +{ + for (unsigned int i = 0; i < m_numberOfSlots; ++i) + { + const bool assigned = isTrailPosAssigned(static_cast(i)); + const bool valid = m_coordinator->isValidPosition(member, m_trailingPositions[i].second); + if (m_trailingPositions[i].first && !assigned && valid) + return static_cast(i); + } + return -1; +} + +// ELF 0x1ACB70: whether any slot falls back to trailing position `trailIndex`. +bool SquadFormation::isTrailPosAssigned(int trailIndex) +{ + for (unsigned int i = 0; i < m_numberOfSlots; ++i) + { + if (m_slots[i]->m_i20 == trailIndex) + return true; + } + return false; +} + +// ELF 0x1AB640: the formation leaves the squad leader (+84 set, +85 cleared). +void SquadFormation::leaveSquadLeader() +{ + m_b85 = false; + m_b84 = true; + updateMovementFlag(true); +} + // [INFERRED] void result. No slot-vector, leader or member null guards exist. void SquadFormation::updateFormation() { @@ -368,10 +555,10 @@ void SquadFormation::updateFormation() m_coordinator->getSquadPosition(squadPosition); unsigned int leaderSlotIndex = 0; - for (; leaderSlotIndex < m_maxSquadMembers; ++leaderSlotIndex) + for (; leaderSlotIndex < m_numberOfSlots; ++leaderSlotIndex) { slot = m_slots[leaderSlotIndex]; - if (slot->m_occupied && slot->m_memberIndex == leaderIndex) + if (slot->hasSquadMemberAssigned && slot->m_memberIndex == leaderIndex) { leaderPresent = true; break; @@ -384,10 +571,10 @@ void SquadFormation::updateFormation() { if (leaderSlotIndex != 0) return; - for (unsigned int index = m_maxSquadMembers - 1; index > 0; --index) + for (unsigned int index = m_numberOfSlots - 1; index > 0; --index) { Slot* const other = m_slots[index]; - if (!other->m_occupied) + if (!other->hasSquadMemberAssigned) continue; const int otherIndex = other->m_memberIndex; const int oldIndex = slot->m_memberIndex; @@ -416,9 +603,9 @@ void SquadFormation::updateFormation() m_b85 = false; Slot* const zero = m_slots[0]; - const bool oldOccupied = zero->m_occupied; + const bool oldOccupied = zero->hasSquadMemberAssigned; const int oldIndex = zero->m_memberIndex; - zero->m_occupied = true; + zero->hasSquadMemberAssigned = true; zero->m_memberIndex = leaderIndex; zero->m_b24 = false; zero->m_i28 = 0.0f; @@ -426,7 +613,7 @@ void SquadFormation::updateFormation() // The old leader-slot pointer is reloaded after that callback. slot = m_slots[leaderSlotIndex]; - slot->m_occupied = oldOccupied; + slot->hasSquadMemberAssigned = oldOccupied; slot->m_memberIndex = oldIndex; slot->m_b24 = false; slot->m_i28 = 0.0f; @@ -437,17 +624,17 @@ void SquadFormation::updateFormation() } Slot* const zero = m_slots[0]; - if (!zero->m_occupied) + if (!zero->hasSquadMemberAssigned) return; if (m_coordinator->getSquadMember(zero->m_memberIndex)->isBot() == leaderIsBot) return; // Find the first occupied slot whose bot/human kind matches the captured leader. // The bound, vector and coordinator are fresh after each member callback. - for (unsigned int index = 1; index < m_maxSquadMembers; ++index) + for (unsigned int index = 1; index < m_numberOfSlots; ++index) { Slot* const other = m_slots[index]; - if (!other->m_occupied || + if (!other->hasSquadMemberAssigned || m_coordinator->getSquadMember(other->m_memberIndex)->isBot() != leaderIsBot) continue; const int oldIndex = zero->m_memberIndex; @@ -464,24 +651,67 @@ void SquadFormation::updateFormation() } } -// [INFERRED] void result. The first slot is deliberately excluded from this scan. +// ELF 0x1AAFC0. m_b36 (shouldSquadMoveOut) starts true; every occupied slot but the first is +// checked. A slot stops waiting (+0x18 = false, +0x1C = 0.0f) for the squad leader while the +// formation leaves it (m_b84), for a bot, for a member without a position, outside an estimated +// arrival of (150, 1500) (0x49CF9C / 0x49CF98), or when the member is no farther from the squad's +// goto position than the squad itself (both squared distances). Otherwise the squad waits +// (m_b36 = false): a waiting slot whose deadline (float)time has passed stops waiting (and the +// squad moves out unless another slot holds it); a slot without a deadline (< 0.01f, 0x49CB30) +// starts waiting until (float)time + 10 + 10 * random (0x49CC88; AIRandom inlined, 2^-32). void SquadFormation::updateWaitForSquadMembers(double time) { m_b36 = true; Vec3 memberPosition = {}; Vec3 squadPosition = {}; - (void)memberPosition; - (void)squadPosition; - (void)time; - for (unsigned int index = 1; index < m_maxSquadMembers; ++index) + for (unsigned int index = 1; index < m_numberOfSlots; ++index) { Slot* const slot = m_slots[index]; - if (slot->m_occupied) + if (!slot->hasSquadMemberAssigned) + continue; + + SquadMember* const member = m_coordinator->getSquadMember(slot->m_memberIndex); + bool wait = false; + if (!(m_b84 && slot->m_memberIndex == m_coordinator->getSquadLeaderIndex()) && !member->isBot()) + { + const float arrival = m_coordinator->getSquadMember(slot->m_memberIndex)->getEstimatedArrival(); + const bool hasPosition = member->getPosition(memberPosition); + m_coordinator->getSquadPosition(squadPosition); + if (hasPosition && 1500.0f > arrival && arrival > 150.0f) + { + const Vec3& goal = m_coordinator->getSquadGotoPos(); + const float mx = memberPosition.x - goal.x; + const float my = memberPosition.y - goal.y; + const float mz = memberPosition.z - goal.z; + const float memberDistanceSq = mx * mx + my * my + mz * mz; + const Vec3& goal2 = m_coordinator->getSquadGotoPos(); + const float sx = squadPosition.x - goal2.x; + const float sy = squadPosition.y - goal2.y; + const float sz = squadPosition.z - goal2.z; + wait = memberDistanceSq > sx * sx + sy * sy + sz * sz; + } + } + + if (!wait) + { + slot->m_b24 = false; + slot->m_i28 = 0.0f; + continue; + } + + if (slot->m_b24) { - // The real member lookup begins an occupied-slot timing policy with - // platform-specific time/RNG precision; no deadline or wait is invented. - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - BF2_AI_FRONTIER("dice::hfe::ai::SquadFormation::updateWaitForSquadMembers (occupied slot timing)"); + if (static_cast(time) > slot->m_i28) + slot->m_b24 = false; + else + m_b36 = false; + } + else if (0.01f > slot->m_i28) + { + m_b36 = false; + slot->m_b24 = true; + const double draw = static_cast(AIRandom::m_instance->next()) * 2.3283064e-10; + slot->m_i28 = static_cast(static_cast(static_cast(time)) + (draw * 10.0 + 10.0)); } } } @@ -531,9 +761,26 @@ static bool nearerFormationMember(const Vec3& position, const Vec3& destination, // x64 port has no x87 inline assembly; it is not validated as retail x86 here. #if defined(_WIN32) const long double dx = static_cast(static_cast(position.x) - destination.x); +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + const bf2x87::Real dx = static_cast(position.x) - destination.x; #else const long double dx = static_cast(position.x) - destination.x; #endif +#endif +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + const bf2x87::Real dy = static_cast(position.y) - destination.y; + const bf2x87::Real dz = static_cast(position.z) - destination.z; + const bf2x87::Real distance = (dy * dy + dx * dx) + dz * dz; + if (distance < minimum) + { + minimum = static_cast(distance); + return true; + } + return false; +#else const long double dy = static_cast(position.y) - destination.y; const long double dz = static_cast(position.z) - destination.z; const long double distance = (dy * dy + dx * dx) + dz * dz; @@ -544,13 +791,14 @@ static bool nearerFormationMember(const Vec3& position, const Vec3& destination, } return false; #endif +#endif } // Captured unsigned slot count, full signed member // comparison, no occupied/null/vector-size test. Even an empty slot's -1 can match. bool SquadFormation::isInFormation(int memberIndex) { - const unsigned int count = m_maxSquadMembers; + const unsigned int count = m_numberOfSlots; for (unsigned int i = 0; i < count; ++i) if (m_slots[i]->m_memberIndex == memberIndex) return true; @@ -562,7 +810,7 @@ bool SquadFormation::isInFormation(int memberIndex) void SquadFormation::resetSlot(int slotIndex) { Slot* const slot = m_slots[slotIndex]; - slot->m_occupied = false; + slot->hasSquadMemberAssigned = false; slot->m_memberIndex = -1; slot->m_i20 = -1; slot->m_b24 = false; @@ -576,7 +824,7 @@ void SquadFormation::resetSlot(int slotIndex) void SquadFormation::leaveFormation(int memberIndex) { unsigned int removed = 0; - for (; removed < m_maxSquadMembers; ++removed) + for (; removed < m_numberOfSlots; ++removed) { if (m_slots[removed]->m_memberIndex == memberIndex) { @@ -585,13 +833,13 @@ void SquadFormation::leaveFormation(int memberIndex) } } - if (removed < m_maxSquadMembers - 1 && m_slots[removed + 1]->m_occupied) + if (removed < m_numberOfSlots - 1 && m_slots[removed + 1]->hasSquadMemberAssigned) { - unsigned int last = m_maxSquadMembers - 1; + unsigned int last = m_numberOfSlots - 1; while (last > 0) { Slot* const lastSlot = m_slots[last]; - if (lastSlot->m_occupied) + if (lastSlot->hasSquadMemberAssigned) { if (removed == 0 && last > 1) { @@ -603,7 +851,7 @@ void SquadFormation::leaveFormation(int memberIndex) Slot* const slot = m_slots[candidate]; // Retail obtains the member even for an unoccupied candidate. SquadMember* const member = m_coordinator->getSquadMember(slot->m_memberIndex); - if (slot->m_occupied && !member->isSquadLeader() && member->isBot() && + if (slot->hasSquadMemberAssigned && !member->isSquadLeader() && member->isBot() && member->getPosition(position)) { const Vec3& destination = m_coordinator->getSquadGotoPos(); @@ -614,7 +862,7 @@ void SquadFormation::leaveFormation(int memberIndex) Slot* destination = m_slots[0]; Slot* source = m_slots[selected]; - destination->m_occupied = source->m_occupied; + destination->hasSquadMemberAssigned = source->hasSquadMemberAssigned; destination->m_b24 = source->m_b24; destination->m_offset = source->m_offset; destination->m_memberIndex = source->m_memberIndex; @@ -623,16 +871,16 @@ void SquadFormation::leaveFormation(int memberIndex) m_coordinator->getSquadMember(destination->m_memberIndex)->setHavePath(false); resetSlot(static_cast(selected)); - if (selected < m_maxSquadMembers - 1 && m_slots[selected + 1]->m_occupied) + if (selected < m_numberOfSlots - 1 && m_slots[selected + 1]->hasSquadMemberAssigned) { - unsigned int replacement = m_maxSquadMembers - 1; + unsigned int replacement = m_numberOfSlots - 1; while (replacement > 0) { source = m_slots[replacement]; - if (source->m_occupied) + if (source->hasSquadMemberAssigned) { destination = m_slots[selected]; - destination->m_occupied = source->m_occupied; + destination->hasSquadMemberAssigned = source->hasSquadMemberAssigned; destination->m_b24 = source->m_b24; destination->m_offset = source->m_offset; destination->m_memberIndex = source->m_memberIndex; @@ -654,7 +902,7 @@ void SquadFormation::leaveFormation(int memberIndex) const float oldValue = lastSlot->m_i28; resetSlot(static_cast(last)); Slot* const slot = m_slots[removed]; - slot->m_occupied = true; + slot->hasSquadMemberAssigned = true; slot->m_memberIndex = movedMember; slot->m_i20 = oldIndex; slot->m_b24 = oldFlag; @@ -675,9 +923,9 @@ void SquadFormation::leaveFormation(int memberIndex) // callbacks; occupied candidates only, with -1 and identical-slot results skipped. void SquadFormation::updateClosestSlots() { - for (unsigned int slot = 1; slot < m_maxSquadMembers; ++slot) + for (unsigned int slot = 1; slot < m_numberOfSlots; ++slot) { - if (m_slots[slot]->m_occupied) + if (m_slots[slot]->hasSquadMemberAssigned) { const int closest = getClosestSlotIndex(static_cast(slot)); if (closest != -1 && closest != static_cast(slot)) @@ -686,19 +934,33 @@ void SquadFormation::updateClosestSlots() } } -// The slot/member read precedes -// the first getSlotWorldPos call; no argument or null guard is added. +// ELF 0x1AAE70 (336 bytes). The occupied slot (1..) whose member stands closest to the world +// position of `slotIndex`'s slot; -1 when that position is unknown or no member qualifies. int SquadFormation::getClosestSlotIndex(int slotIndex) { int best = -1; float minimum = 3.402823466e+38F; Vec3 target = {}; Vec3 position = {}; - const int memberIndex = m_slots[slotIndex]->m_memberIndex; - (void)best; (void)minimum; (void)target; (void)position; (void)memberIndex; - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - // The bool getSlotWorldPos(int,Vec3&) movement/position chain remains unwritten. - BF2_AI_FRONTIER("dice::hfe::ai::SquadFormation::getClosestSlotIndex (getSlotWorldPos)"); + if (!getSlotWorldPos(m_slots[slotIndex]->m_memberIndex, target)) + return best; + for (unsigned int i = 1; i < m_numberOfSlots; ++i) + { + if (!m_slots[i]->hasSquadMemberAssigned) + continue; + if (!m_coordinator->getSquadMember(m_slots[i]->m_memberIndex)->getPosition(position)) + continue; + const float dx = target.x - position.x; + const float dy = target.y - position.y; + const float dz = target.z - position.z; + const float distanceSq = dx * dx + dy * dy + dz * dz; + if (minimum > distanceSq) + { + minimum = distanceSq; + best = static_cast(i); + } + } + return best; } // Keep the real allocation and captured pointers; @@ -726,11 +988,10 @@ SquadFormation::SquadFormation(SquadCoordinator* coordinator) : m_slots() , m_coordinator(coordinator) , m_formation(0) - , m_i48(0) - , m_f52(0.0f) + , m_forward() , m_i88(0) , m_d92(0.0) - , m_slotTargets() + , m_trailingPositions() , m_trailingPosition() { m_direction.x = 0.0f; @@ -746,10 +1007,10 @@ SquadFormation::SquadFormation(SquadCoordinator* coordinator) m_side = coordinator->getSide(); - m_maxSquadMembers = static_cast( + m_numberOfSlots = static_cast( static_cast(CommonSingletonServer::m_iaiGame)->getMaxNumberOfSquadMembers()); - for (unsigned int i = 0; i < m_maxSquadMembers; ++i) + for (unsigned int i = 0; i < m_numberOfSlots; ++i) { m_slots.push_back(new Slot()); @@ -757,7 +1018,7 @@ SquadFormation::SquadFormation(SquadCoordinator* coordinator) zero.x = 0.0f; zero.y = 0.0f; zero.z = 0.0f; - m_slotTargets.push_back(std::pair(false, zero)); + m_trailingPositions.push_back(std::pair(false, zero)); } // FLT_MAX, written as the bit pattern the binary stores. @@ -768,8 +1029,8 @@ SquadFormation::SquadFormation(SquadCoordinator* coordinator) setFormation(); m_b36 = false; - m_i48 = 0; - m_f52 = 1.0f; + m_forward.x = 0.0f; + m_forward.y = 1.0f; m_v60.x = 0.0f; m_v60.y = 0.0f; m_v60.z = 0.0f; @@ -793,12 +1054,12 @@ float SquadFormation::getFormationMaxSpeed() // even when the scan finds no free slot. PE inlines updateMovementFlag(true). void SquadFormation::joinFormation(int memberIndex) { - for (unsigned int i = 0; i < m_maxSquadMembers; ++i) + for (unsigned int i = 0; i < m_numberOfSlots; ++i) { Slot* const slot = m_slots[i]; - if (!slot->m_occupied) + if (!slot->hasSquadMemberAssigned) { - slot->m_occupied = true; + slot->hasSquadMemberAssigned = true; slot->m_memberIndex = memberIndex; slot->m_i20 = -1; slot->m_b24 = false; @@ -816,7 +1077,7 @@ void SquadFormation::joinFormation(int memberIndex) // when forced or when both strict thresholds pass. No empty-slot-vector guard. void SquadFormation::updateMovementFlag(bool force) { - if (!m_slots[0]->m_occupied) + if (!m_slots[0]->hasSquadMemberAssigned) return; m_b56 = false; @@ -841,16 +1102,11 @@ void SquadFormation::updateMovementFlag(bool force) } } -// Preserve both guards. -// The positioned-squad arm calls getSlotWorldPos(getSquadMemberIndexAtSlot(0), m_v72). -// Its navigation/position dependencies are not recovered here. -// [FRONTIER, narrow] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] +// Preserve both guards (inlined in the image): the positioned squad's slot-zero world position. void SquadFormation::updateSlotZeroPos() { - if (m_slots[0]->m_occupied && m_coordinator->squadHasPosition()) - { - BF2_AI_FRONTIER("dice::hfe::ai::SquadFormation::updateSlotZeroPos (getSlotWorldPos)"); - } + if (m_slots[0]->hasSquadMemberAssigned && m_coordinator->squadHasPosition()) + getSlotWorldPos(getSquadMemberIndexAtSlot(0), m_v72); } // Only the target-valid flags and slot indices are @@ -860,30 +1116,38 @@ void SquadFormation::resetTrailingPositions() updateSlotZeroPos(); m_trailingPosition = m_v72; - for (unsigned int i = 0; i < m_maxSquadMembers; ++i) + for (unsigned int i = 0; i < m_numberOfSlots; ++i) { - m_slotTargets[i].first = false; + m_trailingPositions[i].first = false; m_slots[i]->m_i20 = -1; } } -// Sets the formation speed from the slowest occupied slot, adjusted for crowding. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding SquadFormation operation. +// ELF 0x1AB310: the formation speed is the slowest occupied slot's vehicle speed, scaled by 0.9 +// (0x49CFA0) when more than one slot is occupied, 5.0f (0x49CDAC) when none is. Per occupied slot: +// getSquadMember(slot +4)->getPlayer()->getCurrentVehicle() (IAIPlayer +0x54), its information +// handle for side m_side + 1 (IAIObject +0xB8), the informationManager lookup (inlined: generation +// check, null on mismatch) and Information +0x38 IPIMobile::getMaxSpeed; `flds 0x28; fucompi` keeps +// the smaller value. The image dereferences the looked-up information unchecked. void SquadFormation::updateFormationMaxSpeed() { int occupied = 0; m_formationMaxSpeed = 3.402823466e+38F; - for (unsigned int i = 0; i < m_maxSquadMembers; ++i) + for (unsigned int i = 0; i < m_numberOfSlots; ++i) { Slot* const slot = m_slots[i]; - if (slot->m_occupied) + if (slot->hasSquadMemberAssigned) { ++occupied; - BF2_AI_FRONTIER("dice::hfe::ai::SquadFormation::updateFormationMaxSpeed" - " - the per-member IPIMobile::getMaxSpeed lookup"); + IAIObject* const vehicle = + m_coordinator->getSquadMember(slot->m_memberIndex)->getPlayer()->getCurrentVehicle(); + Information* const info = informationManager->getInformation(vehicle->getInformation(m_side + 1)); + const float speed = info->getMobile()->getMaxSpeed(); + if (m_formationMaxSpeed > speed) + m_formationMaxSpeed = speed; } } @@ -942,8 +1206,7 @@ void SquadFormation::setFormation() } } -// Places slot zero at the origin and alternates subsequent formation slots on either side. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. +// ELF 0x1AB830: slot zero at the origin, later slots alternate +/- direction.x on either side. void SquadFormation::setLineFormation() { const float spacing = 1.0f; @@ -952,7 +1215,7 @@ void SquadFormation::setLineFormation() float offset = 0.0f; int referenceSlot = 0; - for (unsigned int i = 0; i < m_maxSquadMembers; ++i) + for (unsigned int i = 0; i < m_numberOfSlots; ++i) { Slot* const slot = m_slots[i]; @@ -979,25 +1242,185 @@ void SquadFormation::setLineFormation() slot->m_offset.y = 0.0f; slot->m_offset.z = 0.0f; - if (slot->m_occupied) + // ELF 0x1AB920: an occupied slot is spread by both vehicles' radii, measured from its + // reference slot: offset = reference offset + offset * (3 * own radius + 3 * reference + // radius) (0x49CC90 = 3.0f; the image rounds the first product to float, keeps the x + // product's sum in x87 precision). + if (slot->hasSquadMemberAssigned) { - BF2_AI_FRONTIER("dice::hfe::ai::SquadFormation::setLineFormation" - " - the occupied-slot vehicle-radius spread"); + const float own = 3.0f * m_coordinator->getSquadMember(slot->m_memberIndex)->getVehicleRadius(); + Slot* const reference = m_slots[slot->m_referenceSlot]; + const float spread = 3.0f * m_coordinator->getSquadMember(reference->m_memberIndex)->getVehicleRadius() + own; + slot->m_offset.x = slot->m_offset.x * spread + reference->m_offset.x; + slot->m_offset.y = slot->m_offset.y * spread + reference->m_offset.y; + slot->m_offset.z = slot->m_offset.z * spread + reference->m_offset.z; } } } -// [FRONTIER] Wedge and echelon layouts selected by changeFormation remain unimplemented. -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -// Replace the stops when their layout behavior is recovered. +// ELF 0x1ABA10: the line's alternating walk, but the offset also steps 1.0f * direction.z +// along z on both sides (+x / -x); the image's Vec3 temporary keeps the last (x, z) between +// slots (slot 0 is the origin). Occupied slots are spread as in setLineFormation. void SquadFormation::setWedgeFormation() { - BF2_AI_FRONTIER("dice::hfe::ai::SquadFormation::setWedgeFormation"); + const float spacing = 1.0f; + + bool positiveSide = true; + Vec3 offset = {}; + int referenceSlot = 0; + + for (unsigned int i = 0; i < m_numberOfSlots; ++i) + { + Slot* const slot = m_slots[i]; + + if (i) + { + if (positiveSide) + { + offset.x = spacing * m_direction.x; + offset.z = spacing * m_direction.z; + slot->m_referenceSlot = referenceSlot; + positiveSide = false; + + if (i >= 3) + ++referenceSlot; + } + else + { + offset.x = -spacing * m_direction.x; + offset.z = spacing * m_direction.z; + slot->m_referenceSlot = referenceSlot++; + positiveSide = true; + } + } + + slot->m_offset = offset; + + if (slot->hasSquadMemberAssigned) + { + const float own = 3.0f * m_coordinator->getSquadMember(slot->m_memberIndex)->getVehicleRadius(); + Slot* const reference = m_slots[slot->m_referenceSlot]; + const float spread = 3.0f * m_coordinator->getSquadMember(reference->m_memberIndex)->getVehicleRadius() + own; + slot->m_offset.x = slot->m_offset.x * spread + reference->m_offset.x; + slot->m_offset.y = slot->m_offset.y * spread + reference->m_offset.y; + slot->m_offset.z = slot->m_offset.z * spread + reference->m_offset.z; + } + } } +// ELF 0x1ABBF0: as the wedge, with z mirrored per side: (+x, -z) then (-x, +z). void SquadFormation::setEchelonFormation() { - BF2_AI_FRONTIER("dice::hfe::ai::SquadFormation::setEchelonFormation"); + const float spacing = 1.0f; + + bool positiveSide = true; + Vec3 offset = {}; + int referenceSlot = 0; + + for (unsigned int i = 0; i < m_numberOfSlots; ++i) + { + Slot* const slot = m_slots[i]; + + if (i) + { + if (positiveSide) + { + offset.x = spacing * m_direction.x; + offset.z = -spacing * m_direction.z; + slot->m_referenceSlot = referenceSlot; + positiveSide = false; + + if (i >= 3) + ++referenceSlot; + } + else + { + offset.x = -spacing * m_direction.x; + offset.z = spacing * m_direction.z; + slot->m_referenceSlot = referenceSlot++; + positiveSide = true; + } + } + + slot->m_offset = offset; + + if (slot->hasSquadMemberAssigned) + { + const float own = 3.0f * m_coordinator->getSquadMember(slot->m_memberIndex)->getVehicleRadius(); + Slot* const reference = m_slots[slot->m_referenceSlot]; + const float spread = 3.0f * m_coordinator->getSquadMember(reference->m_memberIndex)->getVehicleRadius() + own; + slot->m_offset.x = slot->m_offset.x * spread + reference->m_offset.x; + slot->m_offset.y = slot->m_offset.y * spread + reference->m_offset.y; + slot->m_offset.z = slot->m_offset.z * spread + reference->m_offset.z; + } + } +} + +// ELF 0x1AC370: every slot is reset, then the first min(members, slots - 1) members that are +// allowed in formation take consecutive slots (occupied, their member index). When there are at +// least as many members as slots, the last slot is left free. +void SquadFormation::reassignSlots() +{ + for (unsigned int i = 0; i < m_numberOfSlots; ++i) + resetSlot(static_cast(i)); + unsigned int count = static_cast(m_coordinator->getNumberOfSquadMembers()); + if (count >= m_numberOfSlots) + count = m_numberOfSlots - 1; + unsigned int next = 0; + for (unsigned int i = 0; i < count; ++i) + { + SquadMember* const member = m_coordinator->getSquadMember(static_cast(i)); + if (!member->isAllowedInFormation()) + continue; + Slot* const slot = m_slots[next++]; + slot->hasSquadMemberAssigned = true; + slot->m_memberIndex = member->getMemberIndex(); + } +} + +// ELF 0x1A9E10 (D1, 240 B; recovered on the client track). Clears +// the coordinator back-pointer, deletes the first m_numberOfSlots slots (the bound is the +// member count fixed at construction, not the vector's size), then empties both vectors. +SquadFormation::~SquadFormation() +{ + m_coordinator = 0; + for (unsigned int i = 0; i < m_numberOfSlots; ++i) + delete m_slots[i]; + m_slots.erase(m_slots.begin(), m_slots.end()); + m_trailingPositions.erase(m_trailingPositions.begin(), m_trailingPositions.end()); +} + +// ELF 0x1A9FB0. Shipped defect: the gap-checking loop has no checks left in this image. +void SquadFormation::debugCheckNoFormationSlotGaps() +{ + unsigned int last = m_numberOfSlots - 1; + while (last && !m_slots[last]->hasSquadMemberAssigned) + --last; + if (last) + for (unsigned int index = 0; index <= last; ++index) {} +} + +// ELF 0x1AA7E0. +bool SquadFormation::hasFormationMoved() { return m_b56; } + +// ELF 0x1ABDE0. +void SquadFormation::changeFormation(Formations formation) +{ + m_formation = formation; + setFormation(); +} + +// ELF 0x1AC440: both ray endpoints are raised by one metre; the input vectors are untouched. +bool SquadFormation::haveLineOfSightBetween(Vec3& from, Vec3& to) +{ + std::vector ignore; + m_coordinator->getSquadIgnoreList(ignore); + IAIObjectEnvironment* const environment = + static_cast(CommonSingletonServer::m_iaiObjectEnvironment); + const Vec3 raisedFrom = {from.x, from.y + 1.0f, from.z}; + const Vec3 raisedTo = {to.x, to.y + 1.0f, to.z}; + bool hit; + return !environment->collideLineWithWorld(raisedFrom, raisedTo, ignore, false, 0.0f, true, hit); } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.h b/Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.h index bfe15fb34..6cdac329c 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.h @@ -15,6 +15,7 @@ namespace hfe { namespace ai { class SquadCoordinator; +class SquadMember; class SquadFormation { @@ -31,7 +32,7 @@ class SquadFormation explicit Slot(SwapTemporary) : m_offset() {} Slot() - : m_occupied(false) + : hasSquadMemberAssigned(false) , m_memberIndex(-1) , m_i20(-1) , m_b24(false) @@ -43,10 +44,10 @@ class SquadFormation m_offset.z = 0.0f; } - /* +0 */ bool m_occupied; // the flag every deep branch in this class is guarded by + /* +0 */ bool hasSquadMemberAssigned; // the flag every deep branch in this class is guarded by; name: AIDLL_r assert (0x101B4F00; +0) /* +4 */ int m_memberIndex; // = -1; indexes the coordinator's squad-member vector /* +8 */ Vec3 m_offset; // the position the formation setters compute - /* +20 */ int m_i20; // = -1 [UNRESOLVED] + /* +20 */ int m_i20; // = -1; the trailing position (m_trailingPositions) this slot falls back to /* +24 */ bool m_b24; // = false [UNRESOLVED] /* +28 */ float m_i28; // legacy inferred name; float proved by leaveFormation's x87 loads/stores /* +32 */ int m_referenceSlot; // the slot this one is measured from [INFERRED] @@ -63,28 +64,41 @@ class SquadFormation }; explicit SquadFormation(SquadCoordinator* coordinator); + ~SquadFormation(); // ELF 0x1A9E10 (D1) void update(double time); // complete scheduler void updateFormation(); // leader/anchor reassignment - void updateWaitForSquadMembers(double time); // occupied timing seam - void updateFormationForwardVector(); // occupied owner-query seam + void updateWaitForSquadMembers(double time); // ELF 0x1AAFC0 + void updateFormationForwardVector(); // ELF 0x1AB470 void updateTrailingPositions(); // complete void updateTrailingSlots(); // complete void selectFormation(); // / PE inlined at int getSquadMemberIndexAtSlot(int slotIndex); // no occupied test + // ELF 0x1AB6C0: the first slot is occupied (no empty-vector guard). + bool hasSquadMembers() { return m_slots[0]->hasSquadMemberAssigned; } + bool getSlotWorldPos(int memberIndex, Vec3& position); // ELF 0x1AC550 + int getFirstFreeTrailingSlot(SquadMember* member); // ELF 0x1ACA30 + bool isTrailPosAssigned(int trailIndex); // ELF 0x1ACB70 bool shouldLeaveSquadLeader(); // returns m_b84 void joinSquadLeader(); // (inlines the movement update) + void leaveSquadLeader(); // ELF 0x1AB640 float getFormationMaxSpeed(); + bool shouldSquadMoveOut() { return m_b36; } // ELF 0x1AB6F0: +0x24 void updateFormationMaxSpeed(); void setFormation(); + void changeFormation(Formations formation); + bool hasFormationMoved(); + bool haveLineOfSightBetween(Vec3& from, Vec3& to); + void debugCheckNoFormationSlotGaps(); void setLineFormation(); - void setWedgeFormation(); // [FRONTIER] - void setEchelonFormation(); // [FRONTIER] + void setWedgeFormation(); // ELF 0x1ABA10 + void setEchelonFormation(); // ELF 0x1ABBF0 void joinFormation(int memberIndex); bool isInFormation(int memberIndex); // ignores occupied flag void leaveFormation(int memberIndex); void resetSlot(int slotIndex); // inlined + void reassignSlots(); // ELF 0x1AC370 void updateClosestSlots(); int getClosestSlotIndex(int slotIndex); // world-position seam void swapSlots(int first, int second); // three payload fields only @@ -97,17 +111,14 @@ class SquadFormation /* +12 */ SquadCoordinator* m_coordinator; // the constructor's argument /* +16 */ int m_formation; // = 0 (line); `setFormation` switches on it /* +20 */ Vec3 m_direction; // set by `setFormation` per formation - /* +32 */ unsigned int m_maxSquadMembers; // = IAIGame::getMaxNumberOfSquadMembers + /* +32 */ unsigned int m_numberOfSlots; // = IAIGame::getMaxNumberOfSquadMembers // name: AIDLL_r assert 0x101B5980 (PE +0x24) /* +36 */ bool m_b36; // = false; shouldSquadMoveOut returns it /* +40 */ float m_formationMaxSpeed; // FLT_MAX, then 5.0f - see the header note /* +44 */ int m_side; // = the coordinator's side - // ELF +0x30 / PE +0x34 is one `Vec2` - the formation's XZ forward vector, born (0, 1). The - // Vec2 type is attested by the forward-vector update passing this address to - // `vec3ToVec2XZ(const Vec3&, Vec2&)`; getSlotWorldPos is the only other reader. The split - // below predates that evidence and stays until the occupied projection lands, so that the - // retyping and its first writer arrive together. - /* +48 */ int m_i48; // = 0 Vec2 x (0.0f bits) - /* +52 */ float m_f52; // = 1.0f Vec2 y + // ELF +0x30 / PE +0x34: the formation's XZ forward vector, born (0, 1). Attested as one Vec2 + // by the forward-vector update passing its address to `vec3ToVec2XZ(const Vec3&, Vec2&)`; + // getSlotWorldPos (ELF 0x1AC550) reads it as two floats. + /* +48 */ Vec2 m_forward; /* +56 */ bool m_b56; // = false; hasFormationMoved returns it /* +60 */ Vec3 m_v60; // zeroed; anchor position at the last movement stamp /* +72 */ Vec3 m_v72; // zeroed; slot-zero world position (updateSlotZeroPos) @@ -117,7 +128,7 @@ class SquadFormation /* +92 */ double m_d92; // = 0.0; next movement-stamp time (now + 0.2) // [INFERRED] Per-slot breadcrumb targets. Anchor movement beyond six metres shifts the // trail and inserts its previous position; construction sizes it to the slot count. - /* +100 */ std::vector > m_slotTargets; // (valid, crumb) per index + /* +100 */ std::vector > m_trailingPositions; // (valid, crumb) per index // name: AIDLL_r assert 0x101B7E20 (PE +0x68) /* +112 */ Vec3 m_trailingPosition; // [INFERRED name]; the newest crumb, seeded from m_v72 }; diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.cpp index b7fac1e72..a012ddc6e 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.cpp @@ -2,11 +2,23 @@ // [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining SquadManager operations. #include "SquadManager.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1B0FE0, __tcf_0 0x1B1040, _GLOBAL__I 0x1B1070). +#include +#include "../../../../Platform/X87Compat.h" // [CHOSEN, not recovered] #include "SquadCoordinator.h" // the constructor builds two per squad #include "BotMain.h" #include "BotSquad.h" +#include "SquadMember.h" #include "../Main/AIDllFrontier.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIUnit.h" #include "../Main/IBotManager.h" #include "../Main/AIMain.h" #include "../Main/CommonSingletonServer.h" @@ -19,6 +31,16 @@ #include "../../../AIInterface/BFKnowledge/BFTimer.h" #include "../../../../Core/SettingsRepostitory.h" #include "../../../../Core/StringUtil.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/Information.h" +#include "../Main/AIRandom.h" +#include "../Main/IAIPathfinding.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIStrategicEntity/AIStrategicArea.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include namespace dice { namespace hfe { @@ -29,12 +51,12 @@ namespace ai { int SquadManager::getSquadStrengths(int side, int areaIndex, StrategicStrengthType type) { int total = 0; - for (std::size_t index = 0; index < m_coordinators[side - 1].size(); ++index) + for (std::size_t index = 0; index < m_Squads[side - 1].size(); ++index) { - if (m_coordinators[side - 1][index]->getMissionStatus() == 2 && - m_coordinators[side - 1][index]->isSquadAssignedToArea(areaIndex)) + if (m_Squads[side - 1][index]->getMissionStatus() == 2 && + m_Squads[side - 1][index]->isSquadAssignedToArea(areaIndex)) { - total += m_coordinators[side - 1][index]->getStrategicStrength(type); + total += m_Squads[side - 1][index]->getStrategicStrength(type); } } return total; @@ -50,10 +72,10 @@ void SquadManager::update(double time) updateArtilleryStatus(time); updateCommanderMessages(); m_sideCursor = m_sideCursor == 0; - m_coordinators[m_sideCursor][m_squadCursor]->update(time); + m_Squads[m_sideCursor][m_squadCursor]->update(time); if (m_sideCursor == 1) { - if (static_cast(m_squadCursor) < m_coordinators[0].size() - 1) + if (static_cast(m_squadCursor) < m_Squads[0].size() - 1) m_squadCursor = static_cast(static_cast(m_squadCursor) + 1); else { @@ -69,15 +91,15 @@ void SquadManager::update(double time) // therefore runs two complete traversals. void SquadManager::updateArtilleryStatus(double time) { - SideBlock* blocks[2] = { &m_sideBlock0, &m_sideBlock1 }; + SideBlock* blocks[2] = { &m_artillery[0], &m_artillery[1] }; for (unsigned int block = 0; block < 2; ++block) { - if (blocks[block]->m_b0 && time > m_double156 + blocks[block]->m_artilleryStartTime) + if (blocks[block]->incomingArtillery && time > m_double156 + blocks[block]->m_artilleryStartTime) { - blocks[block]->m_b0 = false; + blocks[block]->incomingArtillery = false; for (unsigned int side = 0; side < 2; ++side) - for (unsigned int index = 0; index < m_coordinators[side].size(); ++index) - m_coordinators[side][index]->updateSquadPaths(); + for (unsigned int index = 0; index < m_Squads[side].size(); ++index) + m_Squads[side][index]->updateSquadPaths(); } } } @@ -144,6 +166,22 @@ void SquadManager::setPlayerOnValidPosition(IAIPlayer* player, bool valid, doubl m_playerValidPositions.insert(std::make_pair(id, time)); } +// ELF 0x1AE5B0 (listing). Whether a human (not getIsAIPlayer, +0x88) of `side` (getSide, +0x6C) +// is among the factory's players (IAIPlayerFactory +0x2C, copied); null entries are skipped. +// The manager itself is not read. +bool SquadManager::haveHumanPlayerOnOwnSide(int side) +{ + const std::vector players = + static_cast(CommonSingletonServer::m_iaiPlayerFactory)->getAllPlayers(); + for (std::vector::const_iterator i = players.begin(); i != players.end(); ++i) + { + IAIPlayer* const player = *i; + if (player && !player->getIsAIPlayer() && player->getSide() == side) + return true; + } + return false; +} + // Copy the borrowed factory // vector before callbacks. Preserve the repeated AI-player query even when the first one // returned true. A live, non-downed human with a vehicle next needs IAIObject::getInformation @@ -157,17 +195,27 @@ void SquadManager::updateHumanPlayers(double time) IAIPlayer* player = *i; if (!player) continue; - if (!player->getIsAIPlayer() && player->getIsAlive() && !player->isManDown()) + // ELF 0x1AE1D0: a human in an object with mobile information is on a valid position + // unless pathfinding rejects it (IAIPathfinding +0x2C, vehicle number, equipment type). + bool valid = true; + IAIObject* vehicle = 0; + if (!player->getIsAIPlayer() && player->getIsAlive() && !player->isManDown() + && (vehicle = player->getCurrentVehicle()) != 0) { - if (player->getCurrentVehicle()) + Information* const info = informationManager->getInformation(vehicle->getInformation(player->getSide())); + if (info) { - player->getSide(); - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - BF2_AI_FRONTIER("dice::hfe::ai::SquadManager::updateHumanPlayers (IAIObject::getInformation)"); + const Vec3 position = info->getPosition(); + if (IPIMobile* const mobile = info->getMobile()) + { + const int type = info->getUnit()->getEquipmentType(); + if (!IAIPathfinding::instance->isValidPosition(mobile->getVehicleNumber(), type, position, false)) + valid = false; + } } } if (!player->getIsAIPlayer()) - setPlayerOnValidPosition(player, true, time); + setPlayerOnValidPosition(player, valid, time); } for (std::map::iterator i = m_playerValidPositions.begin(); i != m_playerValidPositions.end(); ) @@ -183,7 +231,7 @@ void SquadManager::updateHumanPlayers(double time) // Creates a coordinator for each squad on each side, excluding squad zero. SquadManager::SquadManager() - : m_coordinators() + : m_Squads() // Default-initialize SideBlock: its three Vec3 values alone are zeroed. Value-initializing // the blocks would also zero timestamps/flags retail leaves untouched (full //PE reads). , m_commanderMessages() @@ -198,8 +246,8 @@ SquadManager::SquadManager() for (unsigned int i = 0; i < last; ++i) { - m_coordinators[0].push_back(new SquadCoordinator(0, static_cast(i))); - m_coordinators[1].push_back(new SquadCoordinator(1, static_cast(i))); + m_Squads[0].push_back(new SquadCoordinator(0, static_cast(i))); + m_Squads[1].push_back(new SquadCoordinator(1, static_cast(i))); } } @@ -210,8 +258,8 @@ SquadManager::SquadManager() m_float152 = 40.0f; m_sideCursor = 1; - m_sideBlock0.m_b0 = false; - m_sideBlock1.m_b0 = false; + m_artillery[0].incomingArtillery = false; + m_artillery[1].incomingArtillery = false; m_double156 = 25.0; @@ -253,7 +301,7 @@ void SquadManager::addSquadMember(int playerId, int side) const int maximum = static_cast(CommonSingletonServer::m_iaiGame) ->getMaxNumberOfSquadMembers(); int best = maximum; - std::vector& coordinators = m_coordinators[side]; + std::vector& coordinators = m_Squads[side]; for (unsigned int i = 0; i < coordinators.size(); ++i) { if (coordinators[i]->getNumberOfSquadMembers() <= best && @@ -276,11 +324,25 @@ void SquadManager::addSquadMember(int playerId, int side) best = selected->getNumberOfSquadMembers(); if (best >= splitAt) { - // The old member is fetched before removal. Its removal/formation reindexing - // engine exit/rejoin and subsequent deletion remain unrecovered as a chain. - selected->getSquadMember(best - 1); - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - BF2_AI_FRONTIER("dice::hfe::ai::SquadManager::addSquadMember (SquadCoordinator::removeSquadMember)"); + // ELF 0x1AF21A: the last member moves to the next (empty) squad: it is unlinked, + // the old squad re-elects its leader, the engine squad is left (IBFSquad +0x10 + // exitSquad), the member's player joins the next coordinator - a bot through its + // BotSquad, a human through IBFSquad +0x0C joinSquad - and the record is deleted. + // The new player then joins that next squad too. + SquadMember* const moved = selected->getSquadMember(best - 1); + selected->removeSquadMember(best - 1); + selected->updateSquadLeader(); + IBFSquad* const squads = static_cast(CommonSingletonServer::m_iBFSquad); + squads->exitSquad(selected->getSquadId() + 1, moved->getPlayer()); + selected = coordinators[selected->getSquadId() + 1]; + selected->addSquadMember(moved->getPlayer()); + if (moved->isBot()) + IBotManager::instance->getBotFromPlayerId(moved->getPlayerId())->getBotSquad() + ->joinSquad(selected->getSquadId() + 1); + else + squads->joinSquad(selected->getSquadId() + 1, moved->getPlayer()); + selected->updateSquadLeader(); + delete moved; } } @@ -304,14 +366,14 @@ void SquadManager::addSquadMember(int playerId, int side) // singleton or coordinator-null check here; the courier owns only the singleton guard. void SquadManager::newSquadLeader(int side, int squadId) { - m_coordinators[side - 1][squadId - 1]->updateSquadLeader(); + m_Squads[side - 1][squadId - 1]->updateSquadLeader(); } // Search this side in coordinator order and return the first // matching member. The coordinator's output index is intentionally not used by this caller. SquadMember* SquadManager::getSquadMember(int playerId, int side) { - std::vector& coordinators = m_coordinators[side - 1]; + std::vector& coordinators = m_Squads[side - 1]; for (unsigned int i = 0; i < coordinators.size(); ++i) { int memberIndex; @@ -327,7 +389,7 @@ SquadMember* SquadManager::getSquadMember(int playerId, int side) // The member index output is not consumed, and null coordinator entries are not guarded. SquadCoordinator* SquadManager::getSquadFromPlayer(int playerId, int side) { - std::vector& coordinators = m_coordinators[side - 1]; + std::vector& coordinators = m_Squads[side - 1]; for (unsigned int i = 0; i < coordinators.size(); ++i) { int memberIndex; @@ -337,6 +399,90 @@ SquadCoordinator* SquadManager::getSquadFromPlayer(int playerId, int side) return 0; } +// ELF 0x1AF6A0: the player's squad on side 1, else on side 2; returns the side searched last. +int SquadManager::getSquadFromPlayer(int playerId, SquadCoordinator*& squad) +{ + squad = getSquadFromPlayer(playerId, 1); + if (squad) + return 1; + squad = getSquadFromPlayer(playerId, 2); + return 2; +} + +// ELF 0x1AF720: one-based squad id and side, no range checks. +SquadCoordinator* SquadManager::getSquadFromId(int squadId, int side) +{ + return m_Squads[side - 1][squadId - 1]; +} + +// ELF 0x1AF860 (256 bytes). An order received by the player's squad: the order position comes +// from the engine (IBFSquad +0x50 getCommanderOrder for a commander order, +0x54 getSquadOrder +// for the squad leader's), then a repair order (type 3) becomes a repair request and anything +// else a mission request without a target object. +void SquadManager::setSquadReceivedOrder(BotSquad::OrderType type, int playerId, bool commander) +{ + SquadCoordinator* squad; + const int side = getSquadFromPlayer(playerId, squad); + if (!squad) + return; + Vec3 position; + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; + IBFSquad* const engine = static_cast(CommonSingletonServer::m_iBFSquad); + if (commander) + engine->getCommanderOrder(side, squad->getSquadId() + 1, position, 0); + else + engine->getSquadOrder(side, squad->getSquadId() + 1, position, 0); + if (type == 3) + squad->requestRepair(position); + else + squad->requestMission(type, position, 0, commander); +} + +// ELF 0x1AF960 (320 bytes). Without a player commander, a squad with a mission state whose request +// came from the (AI) commander gets that order again: attack (type 0) or defend, through the side's +// CommanderInterface, and a commander message (0 attack / 1 defend) due in 2 s. +void SquadManager::repeatOrder(int side, int squadId) +{ + ISAI* const sai = IAIMain::m_instance->getSAI(side); + SquadCoordinator* const squad = getSquadFromId(squadId, side); + if (!squad || sai->isPlayerCommander()) + return; + if (squad->getMissionStatus() == 0) + return; + const SquadCoordinator::MissionRequest request = squad->getMissionRequest(); + if (!request.m_commander) + return; + if (request.m_type == 0) + { + sai->getCommanderInterface()->giveAttackOrder(request.m_position, squad); + enqueueCommanderMessage(side - 1, squadId - 1, static_cast(0), 2.0f); + } + else + { + sai->getCommanderInterface()->giveDefendOrder(request.m_position, squad); + enqueueCommanderMessage(side - 1, squadId - 1, static_cast(1), 2.0f); + } +} + +// ELF 0x1AE970 (276 bytes). A message for the same (side index, squad index) already queued +// keeps its place; otherwise a new one (zeroed, 20 bytes) goes to the back. +void SquadManager::enqueueCommanderMessage(int sideIndex, int squadIndex, CommanderMessageType type, double delay) +{ + for (std::list::iterator it = m_commanderMessages.begin(); it != m_commanderMessages.end(); ++it) + { + if ((*it)->m_sideIndex == sideIndex && (*it)->m_squadIndex == squadIndex) + return; + } + CommanderMessage* const message = new CommanderMessage(); + message->m_dueTime = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime() + delay; + message->m_type = type; + message->m_sideIndex = sideIndex; + message->m_squadIndex = squadIndex; + m_commanderMessages.push_back(message); +} + // Squad zero is ignored. An existing member anywhere on the // side also returns immediately: a bot's engine join notification must not insert it twice. // On a miss, retain the unchecked coordinator/player lookups, add, then update the leader. @@ -347,13 +493,544 @@ void SquadManager::playerJoinsSquad(int playerId, int squadId, int side) if (getSquadMember(playerId, side)) return; - SquadCoordinator* coordinator = m_coordinators[side - 1][squadId - 1]; + SquadCoordinator* coordinator = m_Squads[side - 1][squadId - 1]; IAIPlayer* player = static_cast(CommonSingletonServer::m_iaiPlayerFactory) ->getPlayerFromId(playerId); coordinator->addSquadMember(player); coordinator->updateSquadLeader(); } +// ELF 0x1AF800: every coordinator of the one-based side drops its strategic-area assignment. +void SquadManager::unAssignSquads(int side) +{ + std::vector& coordinators = m_Squads[side - 1]; + for (unsigned int i = 0; i < coordinators.size(); ++i) + coordinators[i]->unAssignSquad(); +} + +// ELF 0x1AE100: both sides unassigned, queued commander messages and player positions cleared, +// the artillery flags of both side blocks and the update cursors reset, then every coordinator +// of side 0 and then side 1 resets. +// ELF 0x1ADD70 (D1, 467 B; recovered on the client track). Each +// side's coordinators are deleted (nonvirtual SquadCoordinator D1 + operator delete) and the +// vector emptied, then the commander messages and valid positions are cleared and the singleton +// pointer zeroed unconditionally. The members go afterwards in reverse declaration order. +SquadManager::~SquadManager() +{ + for (int side = 0; side < 2; ++side) + { + for (unsigned int i = 0; i < m_Squads[side].size(); ++i) + delete m_Squads[side][i]; + m_Squads[side].erase(m_Squads[side].begin(), m_Squads[side].end()); + } + clearCommanderMessages(); + clearPlayerValidPositions(); + m_instance = 0; +} + +void SquadManager::reset() +{ + unAssignSquads(1); + unAssignSquads(2); + clearCommanderMessages(); + clearPlayerValidPositions(); + m_artillery[0].incomingArtillery = false; + m_artillery[1].incomingArtillery = false; + m_squadCursor = 0; + m_sideCursor = 1; + for (int side = 0; side < 2; ++side) + for (unsigned int i = 0; i < m_Squads[side].size(); ++i) + m_Squads[side][i]->reset(); +} + +// ELF 0x1B0180: squad 0 (no squad) is ignored. Otherwise the player's member record is unlinked +// from coordinator [side - 1][squadId - 1], which re-elects its leader. The record itself is not +// deleted on this path, as shipped. +void SquadManager::playerRemovedFromSquad(int playerId, int squadId, int side) +{ + if (!squadId) + return; + SquadMember* const member = getSquadMember(playerId, side); + if (!member) + return; + SquadCoordinator* const coordinator = m_Squads[side - 1][squadId - 1]; + coordinator->removeSquadMember(member); + coordinator->updateSquadLeader(); +} + +// ELF 0x1AF750: the side's squads assigned to the area are released, except those already close to +// their non-owned target; answers how many were released. +int SquadManager::unAssignSquads(int areaIndex, int side) +{ + int released = 0; + std::vector& coordinators = m_Squads[side - 1]; + for (unsigned int i = 0; i < coordinators.size(); ++i) + { + if (coordinators[i]->isSquadCloseToNonOwnedTarget()) + continue; + if (coordinators[i]->isSquadAssignedToArea(areaIndex)) + { + coordinators[i]->unAssignSquad(); + ++released; + } + } + return released; +} + +// ELF 0x1B0610 (466 bytes). An enemy human whose valid position (m_playerValidPositions) is +// more than 60 s old and who sits in an object with information for its side is camping; its +// position's x and z are returned. +bool SquadManager::haveCampingHumans(int side, Vec2& position) +{ + const int enemy = side == 1 ? 2 : 1; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + IAIPlayerFactory* const factory = static_cast(CommonSingletonServer::m_iaiPlayerFactory); + for (std::map::iterator it = m_playerValidPositions.begin(); + it != m_playerValidPositions.end(); ++it) + { + IAIPlayer* const player = factory->getPlayerFromId(it->first); + if (!player || player->getSide() != enemy || !(it->second + 60.0 < now)) + continue; + IAIObject* const vehicle = player->getCurrentVehicle(); + if (!vehicle) + continue; + Information* const info = informationManager->getInformation(vehicle->getInformation(player->getSide())); + if (info) + { + const Vec3& p = info->getPosition(); + position.x = p.x; + position.y = p.z; + return true; + } + } + return false; +} + +// ELF 0x1AFD30. The nearest available squad with members whose strategic strength (type +// !attack) is positive; a squad requested to this very area counts only while its leader is a +// bot. strength receives twice the chosen squad's strength (0 if none). +SquadCoordinator* SquadManager::getClosestAvailableSquad(AIStrategicArea* area, const Vec3& position, + int side, bool attack, int& strength) +{ + SquadCoordinator* closest = 0; + float best = 3.4028235e+38f; + Vec3 squadPosition = { 0.0f, 0.0f, 0.0f }; + std::vector& coordinators = m_Squads[side - 1]; + strength = 0; + for (unsigned int i = 0; i < coordinators.size(); ++i) + { + SquadCoordinator* const squad = coordinators[i]; + if (!squad->isSquadAvailable() || squad->getNumberOfSquadMembers() <= 0) + continue; + if (squad->isSquadRequestedToArea(area->getIndex()) && !squad->getSquadLeader()->isBot()) + continue; + const int value = squad->getStrategicStrength(static_cast(!attack)) * 2; + if (value <= 0) + continue; + squad->getSquadPosition(squadPosition); + const float dx = position.x - squadPosition.x; + const float dy = position.y - squadPosition.y; + const float dz = position.z - squadPosition.z; + const float distance = dx * dx + dy * dy + dz * dz; + if (distance < best) + { + strength = value; + closest = squad; + best = distance; + } + } + return closest; +} + +// ELF 0x1AFAA0: distance to the nearest squad leader with a valid position (FLT_MAX's root +// when there is none). +float SquadManager::getDistanceToClosestSquad(const Vec3& position, int side) +{ + float best = 3.4028235e+38f; + Vec3 leader = { 0.0f, 0.0f, 0.0f }; + const std::vector& coordinators = m_Squads[side - 1]; + for (unsigned int i = 0; i < coordinators.size(); ++i) + { + SquadCoordinator* const squad = coordinators[i]; + if (squad->getNumberOfSquadMembers() <= 0) + continue; + if (squad->getSquadLeader()->getPosition(leader)) + { + const float dx = position.x - leader.x; + const float dy = position.y - leader.y; + const float dz = position.z - leader.z; + const float distance = dx * dx + dy * dy + dz * dz; + if (distance < best) + best = distance; + } + } + return std::sqrt(best); +} + +// ELF 0x1AEE60: the float at +0x98 (+152, m_float152, 40.0f at construction). +float SquadManager::getArtillerySafeDistance() +{ + return m_float152; +} + +// ELF 0x1B07F0 (427 bytes): is any player of the side within radius in an object that is a +// soldier (type flag 0x20) or not vehicle-flagged (0x10)? +bool SquadManager::friendliesCloseTo(Vec3 position, float radius, int side) +{ + std::vector ids; + bool found = false; + static_cast(CommonSingletonServer::m_iaiObjectEnvironment)->getWorldPlayerIds(ids); + IAIPlayerFactory* const factory = static_cast(CommonSingletonServer::m_iaiPlayerFactory); + for (std::vector::iterator it = ids.begin(); it != ids.end(); ++it) + { + IAIPlayer* const player = factory->getPlayerFromId(*it); + if (!player || player->getSide() != side) + continue; + IAIObject* const vehicle = player->getCurrentVehicle(); + if (!vehicle) + continue; + Information* const info = informationManager->getInformation(vehicle->getInformation(side)); + if (!info) + continue; + if (!info->isOfType(ITHelicopter) && info->isOfType(ITAir)) + continue; + const Vec3& p = info->getPosition(); + const float dx = p.x - position.x; + const float dy = p.y - position.y; + const float dz = p.z - position.z; + if (dx * dx + dy * dy + dz * dz < radius * radius) + { + found = true; + break; + } + } + return found; +} + +// ELF 0x1B09A0 (339 bytes). Marks the side's artillery warning with the time and impact point +// and a random delay in [d/2, d) for d = m_double156; both sides' flee positions become invalid. +// The sum is x87 extended in the ELF (fildll, fmuls, fmul, faddp); bf2x87::Real keeps that. +void SquadManager::incomingArtillery(Vec3 position, int side) +{ + SideBlock& block = side - 1 == 0 ? m_artillery[0] : m_artillery[1]; + SideBlock& other = side - 1 == 0 ? m_artillery[1] : m_artillery[0]; + const double half = 0.5 * m_double156; + block.incomingArtillery = true; + block.m_artilleryStartTime = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + block.m_artilleryPosition = position; + const unsigned int r = AIRandom::m_instance->next(); + block.m_validFlee0 = false; + block.m_validFlee1 = false; + const bf2x87::Real halfX = bf2x87::Real(half); + const bf2x87::Real delay = halfX + (bf2x87::Real(static_cast(r)) * bf2x87::Real(2.3283064e-10f)) * halfX; + block.m_artilleryDelay = static_cast(delay); + other.m_validFlee0 = false; + other.m_validFlee1 = false; +} + +// ELF 0x1B0B00 (574 bytes). Inside the safe distance (+152) of the side's own pending strike, +// or of the other side's strike once its delay has passed: sinceStart = now - start and +// artillerySide = the striking side. Otherwise -1.0 and 0. +bool SquadManager::isInArtilleryDangerZone(Vec3 position, int side, double& sinceStart, int& artillerySide) +{ + SideBlock& own = side - 1 == 0 ? m_artillery[0] : m_artillery[1]; + SideBlock& other = side - 1 == 0 ? m_artillery[1] : m_artillery[0]; + const int otherSide = side - 1 == 0 ? 2 : 1; + bool danger = false; + sinceStart = -1.0; + artillerySide = 0; + const bf2x87::Real now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + const float safe = m_float152 * m_float152; + const auto distanceSq = [&position](const SideBlock& block) { + const float dx = block.m_artilleryPosition.x - position.x; + const float dy = block.m_artilleryPosition.y - position.y; + const float dz = block.m_artilleryPosition.z - position.z; + return dx * dx + dy * dy + dz * dz; + }; + if (own.incomingArtillery && distanceSq(own) < safe) + { + danger = true; + sinceStart = static_cast(now - bf2x87::Real(own.m_artilleryStartTime)); + artillerySide = side; + } + else if (other.incomingArtillery && distanceSq(other) < safe + && bf2x87::Real(other.m_artilleryStartTime) + bf2x87::Real(other.m_artilleryDelay) < now) + { + danger = true; + sinceStart = static_cast(now - bf2x87::Real(other.m_artilleryStartTime)); + artillerySide = otherSide; + } + return danger; +} + +// ELF 0x1AFF20: the first coordinator of the side that holds the player drops it, tells the +// engine squad (IBFSquad::exitSquad, squad id + 1) and re-elects its leader. +void SquadManager::removeSquadMember(int playerId, int side) +{ + std::vector& coordinators = m_Squads[side - 1]; + for (unsigned int i = 0; i < coordinators.size(); ++i) + { + SquadCoordinator* const squad = coordinators[i]; + int index = 0; + SquadMember* const member = squad->getSquadMember(playerId, index); + if (!member) + continue; + squad->removeSquadMember(index); + IAIPlayer* const player = member->getPlayer(); + static_cast(CommonSingletonServer::m_iBFSquad)->exitSquad(squad->getSquadId() + 1, player); + squad->updateSquadLeader(); + return; + } +} + +// ELF 0x1AE000: both sides' squads are emptied, then every active bot is added again. +void SquadManager::removeAllSquads() +{ + for (unsigned int i = 0; i < m_Squads[0].size(); ++i) + m_Squads[0][i]->removeAll(); + for (unsigned int i = 0; i < m_Squads[1].size(); ++i) + m_Squads[1][i]->removeAll(); + IBotManager* const manager = IBotManager::instance; + if (!manager) + return; + const unsigned int count = manager->getBotCount(); + for (unsigned int i = 0; i < count; ++i) + { + Bot* const bot = manager->getBot(i); + if (!bot->isDeactivated()) + { + const int side = bot->getSide(); + addSquadMember(bot->getPlayerId(), side); + } + } +} + +// ELF 0x1B0010: removeSquadMember's search, but the coordinator destroys the member record. +void SquadManager::destroySquadMember(int playerId, int side) +{ + std::vector& coordinators = m_Squads[side - 1]; + for (unsigned int i = 0; i < coordinators.size(); ++i) + { + SquadCoordinator* const squad = coordinators[i]; + int index = 0; + SquadMember* const member = squad->getSquadMember(playerId, index); + if (!member) + continue; + IAIPlayer* const player = member->getPlayer(); + squad->destroySquadMember(index); + static_cast(CommonSingletonServer::m_iBFSquad)->exitSquad(squad->getSquadId() + 1, player); + squad->updateSquadLeader(); + return; + } +} + +// ELF 0x1AF600: the object's occupying player selects the squad. +SquadCoordinator* SquadManager::getSquadFromPlayer(unsigned int handle, int side) +{ + Information* const information = informationManager->getInformation(handle); + if (!information) + return 0; + IPIUnit* const unit = information->getUnit(); + if (!unit) + return 0; + const int playerId = unit->getOccupyingPlayerId(side); + return playerId == -1 ? 0 : getSquadFromPlayer(playerId, side); +} + +// ELF 0x1B0210: both lookups run even when the first player has no squad. +bool SquadManager::isInSameSquad(int firstPlayer, int secondPlayer, int side) +{ + SquadCoordinator* const first = getSquadFromPlayer(firstPlayer, side); + SquadCoordinator* const second = getSquadFromPlayer(secondPlayer, side); + if (!first || !second) + return false; + const int firstId = first->getSquadId(); + return firstId == second->getSquadId(); +} + +// ELF 0x1B02A0. +bool SquadManager::isInAnySquad(int playerId, int side) +{ + return getSquadFromPlayer(playerId, side) != 0; +} + +// ELF 0x1B0510: only a type-zero active weapon publishes a firing direction. +void SquadManager::shotsFired(int playerId, int side, const Vec3& direction) +{ + IAIPlayer* const player = static_cast(CommonSingletonServer::m_iaiPlayerFactory) + ->getPlayerFromId(playerId); + IAIObject* const vehicle = player->getCurrentVehicle(); + InformationManager* const manager = informationManager; + Information* const information = manager->getInformation(vehicle->getInformation(side)); + // Shipped defect: information is dereferenced without checking the pool lookup. + IPIArmament* const armament = information->getArmament(); + if (!armament) + return; + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation( + armament->getWeapon(armament->getActiveWeapon())); + if (weapon && weapon->getWeaponType() == 0) + { + SquadCoordinator* const squad = getSquadFromPlayer(playerId, side); + if (squad) + squad->shotsFired(playerId, direction); + } +} + +} // namespace ai +} // namespace hfe +} // namespace dice + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1B04B0, added by ai-w1-e-fire (createPlanInternal 0x2672BF reports every new fire plan): +// forwards to the shooter's squad, when he has one. +void SquadManager::shotsFired(int playerId, int side, unsigned int target) +{ + if (SquadCoordinator* const squad = getSquadFromPlayer(playerId, side)) + squad->shotsFired(playerId, target); +} + +// ELF 0x1AFBC0: over both sides' squads (stride 12), the positioned leader of a non-empty squad +// with the smallest squared distance (strictly smaller than FLT_MAX, then than the best so far). +SquadMember* SquadManager::getSquadLeaderClosestTo(const Vec3& position) +{ + float best = 3.4028235e+38f; + SquadMember* closest = 0; + Vec3 leaderPosition = {}; + for (unsigned int side = 0; side < 2; ++side) + { + std::vector& squads = m_Squads[side]; + for (unsigned int i = 0; i < squads.size(); ++i) + { + if (squads[i]->getNumberOfSquadMembers() <= 0) + continue; + SquadMember* const leader = squads[i]->getSquadLeader(); + if (!leader->getPosition(leaderPosition)) + continue; + const float dx = position.x - leaderPosition.x; + const float dy = position.y - leaderPosition.y; + const float dz = position.z - leaderPosition.z; + const float distanceSq = dx * dx + dy * dy + dz * dz; + if (distanceSq < best) + { + best = distanceSq; + closest = leader; + } + } + } + return closest; +} + +// ELF 0x1AF480. +SquadMember* SquadManager::getSquadMember(unsigned int handle, int side) +{ + Information* const info = informationManager->getInformation(handle); + if (info && info->getUnit()) + { + const int playerId = info->getUnit()->getOccupyingPlayerId(side); + if (playerId != -1) + return getSquadMember(playerId, side); + } + return 0; +} + +// ELF 0x1B0440. +bool SquadManager::isAnySquadMemberRespondingToRequest(unsigned int handle, int action, int side) +{ + const std::vector& squads = m_Squads[side - 1]; + for (unsigned int i = 0; i < squads.size(); ++i) + { + if (squads[i]->isAnySquadMemberRespondingToRequest(handle, action)) + return true; + } + return false; +} + +// ELF 0x1B0390. +float SquadManager::requestResponseModifier(SquadMember* member, unsigned int handle, int action, int side) +{ + float modifier = 0.0f; + SquadCoordinator* const squad = getSquadFromPlayer(member->getPlayerId(), side); + if (squad) + { + if (member->isSameRequest(handle, action)) + modifier = 1.0f; + else + modifier = squad->requestResponseModifier(member, handle, action); + } + return modifier; +} + +// ELF 0x1B0D40. +Vec3 SquadManager::getArtilleryTargetPos(int side) +{ + SideBlock* const blocks[2] = { &m_artillery[0], &m_artillery[1] }; + return blocks[side - 1]->m_artilleryPosition; +} + +namespace { + +// The member's current vehicle's information for its side, with a unit; null otherwise. +Information* fleeInformation(SquadMember* member, int side) +{ + IAIObject* const vehicle = member->getPlayer()->getCurrentVehicle(); + if (!vehicle) + return 0; + Information* const info = informationManager->getInformation(vehicle->getInformation(side)); + if (!info || !info->getUnit()) + return 0; + return info; +} + +} // namespace + +// ELF 0x1B0D80. +bool SquadManager::haveValidArtilleryFleePos(SquadMember* member, Vec3& position) +{ + const int side = member->getSide(); + SideBlock* const blocks[2] = { &m_artillery[0], &m_artillery[1] }; + SideBlock* const block = blocks[side - 1]; + Information* const info = fleeInformation(member, side); + if (!info) + return false; + if (!info->isOfType(ITSoldier)) + { + if (!block->m_validFlee1) + return false; + position = block->m_fleePos1; + } + else + { + if (!block->m_validFlee0) + return false; + position = block->m_fleePos0; + } + return true; +} + +// ELF 0x1B0EC0. +void SquadManager::setValidArtilleryFleePos(SquadMember* member, Vec3 position) +{ + const int side = member->getSide(); + SideBlock* const blocks[2] = { &m_artillery[0], &m_artillery[1] }; + SideBlock* const block = blocks[side - 1]; + Information* const info = fleeInformation(member, side); + if (!info) + return; + if (!info->isOfType(ITSoldier)) + { + block->m_validFlee1 = true; + block->m_fleePos1 = position; + } + else + { + block->m_validFlee0 = true; + block->m_fleePos0 = position; + } +} + } // namespace ai } // namespace hfe } // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.h b/Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.h index ebb791d87..aef25b6dd 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.h @@ -8,12 +8,14 @@ #include #include #include "../../../../Math/Vec3.h" +#include "BotSquad.h" // BotSquad::OrderType namespace dice { namespace hfe { namespace ai { class SquadCoordinator; // (`operator new(0xE0)`); held only by pointer here +class AIStrategicArea; class SquadMember; class IAIPlayer; // Attested enum name in both squad-strength ELF manglings. Enumerator names are not recovered. @@ -23,6 +25,7 @@ class SquadManager { public: SquadManager(); + ~SquadManager(); // ELF 0x1ADD70 (D1) // Direct AIMain scheduling call, double by value; neither image materializes a result. void update(double time); @@ -42,18 +45,61 @@ class SquadManager void newSquadLeader(int side, int squadId); void playerJoinsSquad(int playerId, int squadId, int side); SquadMember* getSquadMember(int playerId, int side); + // ELF 0x1AF480: the member occupying the object (IPIUnit::getOccupyingPlayerId(side)), or null. + SquadMember* getSquadMember(unsigned int handle, int side); + // ELF 0x1B0440: any squad of the side has a member with this pending request. + bool isAnySquadMemberRespondingToRequest(unsigned int handle, int action, int side); + // ELF 0x1B0390: 0 without a squad, 1 when `member` already has this request, else the squad's + // SquadCoordinator::requestResponseModifier. `action` is SquadMember::RequestAction. + float requestResponseModifier(SquadMember* member, unsigned int handle, int action, int side); + // [CHOSEN, not recovered] declaration placement; added by ai-w1-e-fire for + // BBPFireInfantery::createPlanInternal (coord/ai-requests.md 2026-11-01). ELF 0x1B04B0. + void shotsFired(int playerId, int side, unsigned int target); + void shotsFired(int playerId, int side, const Vec3& direction); SquadCoordinator* getSquadFromPlayer(int playerId, int side); + SquadCoordinator* getSquadFromPlayer(unsigned int handle, int side); + bool isInSameSquad(int firstPlayer, int secondPlayer, int side); + bool isInAnySquad(int playerId, int side); + int getSquadFromPlayer(int playerId, SquadCoordinator*& squad); // ELF 0x1AF6A0: the side found + SquadMember* getSquadLeaderClosestTo(const Vec3& position); // ELF 0x1AFBC0 + SquadCoordinator* getSquadFromId(int squadId, int side); // ELF 0x1AF720, unchecked + void setSquadReceivedOrder(BotSquad::OrderType type, int playerId, bool commander); // ELF 0x1AF860 + void repeatOrder(int side, int squadId); // ELF 0x1AF960 int getSquadStrengths(int side, int areaIndex, StrategicStrengthType type); // Clears messages and position records by erasing each container node individually. void clearCommanderMessages(); void clearPlayerValidPositions(); + void unAssignSquads(int side); // ELF 0x1AF800 + int unAssignSquads(int areaIndex, int side); // ELF 0x1AF750 + // Used by SAI::checkCommanderUseArtillery. getArtillerySafeDistance: ELF 0x1AEE60 (+0x98). + bool haveCampingHumans(int side, Vec2& position); // ELF 0x1B0610 + bool haveHumanPlayerOnOwnSide(int side); // ELF 0x1AE5B0 + float getArtillerySafeDistance(); // ELF 0x1AEE60 + float getDistanceToClosestSquad(const Vec3& position, int side); // ELF symbol; requested from ai-bot + SquadCoordinator* getClosestAvailableSquad(AIStrategicArea* area, const Vec3& position, int side, + bool attack, int& strength); // ELF symbol; requested from ai-bot + bool friendliesCloseTo(Vec3 position, float radius, int side); // ELF 0x1B07F0 + void removeAllSquads(); // ELF 0x1AE000 + void destroySquadMember(int playerId, int side); // ELF 0x1B0010 + void removeSquadMember(int playerId, int side); // ELF 0x1AFF20 + bool isInArtilleryDangerZone(Vec3 position, int side, double& sinceStart, int& artillerySide); // ELF 0x1B0B00 + Vec3 getArtilleryTargetPos(int side); // ELF 0x1B0D40 + // ELF 0x1B0D80 / 0x1B0EC0: the side's remembered flee position, one for soldiers, one for + // vehicles (the member's current vehicle's information flag 0x200000). + bool haveValidArtilleryFleePos(SquadMember* member, Vec3& position); + void setValidArtilleryFleePos(SquadMember* member, Vec3 position); + void incomingArtillery(Vec3 position, int side); // ELF 0x1B09A0 + void reset(); // ELF 0x1AE100 + void playerRemovedFromSquad(int playerId, int squadId, int side); // ELF 0x1B0180 static SquadManager* m_instance; // Queued commander message. Field and enumerator names are inferred. // Native dueTime offset/record size: ELF +0xC/20 bytes, PE +0x10/24 bytes. enum CommanderMessageType : int; + // ELF 0x1AE970: queued once per (side index, squad index), due after `delay` s of game time. + void enqueueCommanderMessage(int sideIndex, int squadIndex, CommanderMessageType type, double delay); class CommanderMessage { public: @@ -66,12 +112,12 @@ class SquadManager // Three Vec3 values, not containers: incomingArtillery // and setValidArtilleryFleePos store their scalar components. // [INFERRED] field names. ELF offsets below; PE offsets are 0,8,16,32,40,41,44,56. - // Only the three positions are zeroed here. The manager tail clears m_b0; both doubles + // Only the three positions are zeroed here. The manager tail clears incomingArtillery; both doubles // and the two validity flags remain unwritten by retail construction. class SideBlock { public: - /* +0 */ bool m_b0; + /* +0 */ bool incomingArtillery; // name: AIDLL_r assert (0x1012FC60) /* +4 */ double m_artilleryStartTime; /* +12 */ Vec3 m_artilleryPosition{}; /* +24 */ double m_artilleryDelay; @@ -84,13 +130,15 @@ class SquadManager private: // no vtable. The constructor stores no vptr on any path, so this class has no virtuals at // all - checked before writing, because a missing vptr shifts every offset below by four. - /* 0 */ std::vector m_coordinators[2]; // ELF stride 12 / PE stride 16 + /* 0 */ std::vector m_Squads[2]; // ELF stride 12 / PE stride 16 // name: AIDLL_r assert "m_Squads[side - 1]" 0x101320A0 (PE +0) /* 24 */ int m_squadCursor; // = 0; [INFERRED] name, update uses unsigned comparison /* 28 */ int m_sideCursor; // = 1; [INFERRED] name, update alternates zero/nonzero // Per-side state blocks, each 60 bytes in the original layout. Construction clears // the leading flag and the same nine words in each block. - /* 32 */ SideBlock m_sideBlock0; // +32..+91 - /* 92 */ SideBlock m_sideBlock1; // +92..+151 + // Two blocks, one per side: AIDLL_r asserts "m_artillery[side - 1].incomingArtillery" (0x1012FC60) + // and "m_artillery[theSide].incomingArtillery || m_artillery[otherSide].incomingArtillery" + // (0x1012FD90; PE stride 0x48, flag at +0x28 + index * 0x48). + /* 32 */ SideBlock m_artillery[2]; // +32..+91, +92..+151 /* 152 */ float m_float152; // = 40.0f (bit pattern ) /* 156 */ double m_double156; // = 25.0 // with a bare `operator delete` one at a time. diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.cpp index 7e60395ce..23aabc076 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.cpp @@ -1,7 +1,14 @@ // [INFERRED] Source placement. // [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining SquadMember operations. +#if defined(__APPLE__) +#include "../../../../Platform/X87Compat.h" // [CHOSEN, not recovered] +#endif #include "SquadMember.h" +#include +#include +// static init: ELF 0x1B56E0, 0x1B5740, 0x1B5770: iostream Init only. +#include "../AIStrategicEntity/AIStrategicArea.h" #include "../Main/AIDllFrontier.h" #include "../Main/IBotManager.h" @@ -9,7 +16,26 @@ #include "SquadCoordinator.h" #include "SquadFormation.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "SquadManager.h" +#include "WaypointList.h" +#include "../../../AIInterface/BFKnowledge/BFSquad.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" +#include "../Main/CommonSingletonServer.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" +#include "../AIStrategic/SAI.h" +#include "../Main/AIMain.h" +#include "CommunicationAgent.h" +#include "WPAltitudeMoveTo.h" +#include "WPMoveTo.h" +#include "../Main/AIRandom.h" +#include "../../../../IO/Input/PlayerInput.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" #include "../../../AIInterface/BFKnowledge/AIPlayer.h" namespace dice { @@ -34,9 +60,14 @@ static bool memberPathUpdateDue(double previous, double now) notDue: } return due; +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + return static_cast(now) > static_cast(previous) + 9.0L; #else return static_cast(now) > static_cast(previous) + 9.0L; #endif +#endif } // [PLATFORM] PE spills only dx, then sums (dz*dz+dx*dx)+dy*dy. ELF retains @@ -79,17 +110,33 @@ static bool memberPathDisplaced(const Vec3& previous, const Vec3& current) #else #if defined(_WIN32) const long double dx = static_cast(static_cast(previous.x) - current.x); +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + const bf2x87::Real dx = static_cast(previous.x) - current.x; #else const long double dx = static_cast(previous.x) - current.x; #endif +#endif +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + const bf2x87::Real dy = static_cast(previous.y) - current.y; + const bf2x87::Real dz = static_cast(previous.z) - current.z; +#else const long double dy = static_cast(previous.y) - current.y; const long double dz = static_cast(previous.z) - current.z; +#endif #if defined(_WIN32) return (dz * dz + dx * dx) + dy * dy > static_cast(0.01f); +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + return (dx * dx + dy * dy) + dz * dz > static_cast(0.01f); #else return (dx * dx + dy * dy) + dz * dz > static_cast(0.01f); #endif #endif +#endif } // Preserve the stores around the two virtual calls: publishing @@ -126,7 +173,7 @@ SquadMember::SquadMember(SquadCoordinator* squad, IAIPlayer* player, m_havePath = false; m_request = new RequestState(); m_request->m_action = 0; - m_int38 = 0; + m_assistMember = 0; m_position = {0.0f, 0.0f, 0.0f}; m_positionValid = false; m_flag49 = false; @@ -193,12 +240,22 @@ void SquadMember::update(double time) } else if (m_bot && getPosition(position)) { + // ELF 0x1B1ED0: WaypointList::getUrgency (vtable +8) at this position, no null + // guard. Below 0.5 the path is dropped; so it is when an unmoved member is more than + // 4 m from its path goal (+0x60). WaypointList* const waypoints = m_bot->getWaypoints(); - (void)waypoints; - // ELF +0x08 / PE +0x04 takes this position and the freshly read Bot. - // Its complete owner interface is not known. The time store is later. - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - BF2_AI_FRONTIER("dice::hfe::ai::SquadMember::update (WaypointList position query)"); + if (waypoints->getUrgency(position, m_bot) < 0.5f) + { + setHavePath(false); + } + else if (!m_moved) + { + const float dx = m_vector60.x - position.x; + const float dy = m_vector60.y - position.y; + const float dz = m_vector60.z - position.z; + if (dx * dx + dy * dy + dz * dz > 16.0f) + setHavePath(false); + } } m_time24 = time; } @@ -208,12 +265,14 @@ void SquadMember::update(double time) Vec3 position = {}; if (getPosition(position)) { - if (isMobile()) + double sinceArtillery = 0.0; + int artillerySide = 0; + if (isMobile() + && SquadManager::m_instance->isInArtilleryDangerZone(position, m_side + 1, sinceArtillery, artillerySide)) { - // The bool danger query and subsequent avoidArtillery body remain - // unrecovered, not replaced by a fabricated no-danger decision. - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - BF2_AI_FRONTIER("dice::hfe::ai::SquadMember::update (SquadManager::isInArtilleryDangerZone)"); + // A member that runs from artillery does nothing else this tick. + if (avoidArtillery(position, sinceArtillery, artillerySide)) + return; } else { @@ -234,13 +293,53 @@ void SquadMember::update(double time) const unsigned int handle = m_bot->getCurrentEquipment(); Information* const information = manager->getInformation(handle); #endif - if (information && (information->getObjectTypeFlags() & 0x200000u) && - information->hasArmament()) + IPIArmament* const armament = information ? information->getArmament() : 0; + if (information && information->isOfType(ITSoldier) && armament + && armament->getActiveWeapon() != -1) { - // The next call is the armament's selected-index query, ELF +0x14 - // PE +0x10. Keep the full missing owner/WeaponInfo chain explicit. - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - BF2_AI_FRONTIER("dice::hfe::ai::SquadMember::update (IPIArmament selected weapon)"); + // ELF 0x1B1ED0: a soldier who is not firing switches to weapon slot 2 (activation + // input, inlined Input::setInput(float) = 1) unless he should keep the active one: + // a medic (kit 5) with weapon type 1 at no more than 95 % health, an engineer + // (kit 3) with type 2 while his other ammunition is at most 90 % (product of + // current/max over the remaining weapons), or a non-type-1/2 weapon while firing. + WeaponInfo* const active = + WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + if (active) + { + IPIPhysical* const physical = information->getPhysical(); + bool keep = false; + if (m_player->getSpawnKit() == 5 && active->getWeaponType() == 1 + && !(physical->getHealth() > 0.95f)) + { + keep = true; + } + else + { + if (m_player->getSpawnKit() == 3 && active->getWeaponType() == 2) + { + const std::vector weapons = armament->getWeapons(); + float ratio = 1.0f; + for (unsigned int i = 0; i < weapons.size(); ++i) + { + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (weapon && weapon->getWeaponType() != 1 && weapon->getWeaponType() != 2 + && weapon->getAmmo() != -1 && weapon->getMaxAmmo() != 0) + { + ratio = (static_cast(weapon->getCurrentAmmo()) + / static_cast(weapon->getMaxAmmo())) * ratio; + } + } + keep = ratio <= 0.9f; + } + if (!keep && active->getWeaponType() != 1 && active->getWeaponType() != 2 + && m_bot->isFiring()) + keep = true; + } + WeaponInfo* const primary = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(2)); + if (primary && !keep && active != primary) + m_bot->m_playerInput->setInput( + static_cast(primary->getWeaponActivate()), 1.0f); + } } } @@ -255,16 +354,19 @@ void SquadMember::update(double time) } if (member) { - // The selected member goes to acceptMission before the engine's - // accept/decline courier. Neither response is fabricated here. - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - BF2_AI_FRONTIER("dice::hfe::ai::SquadMember::update (SquadCoordinator::acceptMission)"); + // ELF 0x1B20AB: the selected member goes to acceptMission, then this member's player + // accepts (IBFSquad +0x2C) or declines (+0x30) the squad order. + IBFSquad* const engine = static_cast(CommonSingletonServer::m_iBFSquad); + if (m_squad->acceptMission(member)) + engine->acceptSquadOrder(m_squadIndex + 1, m_player); + else + engine->declineSquadOrder(m_squadIndex + 1, m_player); } } // Formation remains the entry capture; member index is fresh after callbacks. const bool inFormation = formation->isInFormation(m_memberIndex); - m_int38 = 0; + m_assistMember = 0; if (inFormation) moveWithFormation(); else @@ -305,27 +407,41 @@ bool SquadMember::isMoving() return m_moved; } -// These are the complete refusal paths before vehicle information. -// The remaining body queries the vehicle at ELF +0xB8 / PE +0xB4 with m_side+1, checks its -// information/type/physical records, then compares the squad destination distance if assigned. -// IAIObject is still forward-only, so its slot signature must be recovered before crossing here. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] +// ELF 0x1B5380 (432 bytes). A live, not man-down member whose object is a soldier +// (type flag 0x200000) with unit and mobile information; on a mission to an assigned area it +// leaves the formation once within m_formationDistanceSq of the valid area position. bool SquadMember::isAllowedInFormation() { - if (!m_player->getIsAlive()) + bool allowed = false; + if (!m_player->getIsAlive() || m_player->isManDown()) return false; - if (m_player->isManDown()) - return false; - if (!m_player->getCurrentVehicle()) + IAIObject* const vehicle = m_player->getCurrentVehicle(); + if (!vehicle) return false; - - BF2_AI_FRONTIER("dice::hfe::ai::SquadMember::isAllowedInFormation (IAIObject information handle)"); + Information* const info = informationManager->getInformation(vehicle->getInformation(m_side + 1)); + if (info && info->getUnit() && info->isOfType(ITSoldier) && info->getMobile()) + { + allowed = true; + Vec3 goal = m_squad->getSquadGotoPos(); + Vec3 position = { 0.0f, 0.0f, 0.0f }; + if (m_squad->getMissionStatus() == 2 && m_squad->isSquadAssignedToAnyArea()) + { + m_squad->getValidSaPos(this, goal); + if (getPosition(position)) + { + const float dz = goal.z - position.z; + const float dx = goal.x - position.x; + const float dy = goal.y - position.y; + if (dz * dz + dx * dx + dy * dy < m_formationDistanceSq) + allowed = false; + } + } + } + return allowed; } -// The getter occurs before either flag is cleared. A null current -// vehicle leaves the prior position untouched. The nonnull arm needs the same unknown IAIObject -// slot, Information::getPrimaryObject(side+1), and the primary object's position/physics record. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] +// ELF 0x1B1A70 (371 bytes). The position is the primary object's (with physical information) +// for the member's side; it counts as moved beyond 0.1 m. void SquadMember::updateMemberPos() { IAIObject* const vehicle = m_player->getCurrentVehicle(); @@ -333,13 +449,24 @@ void SquadMember::updateMemberPos() m_moved = false; if (!vehicle) return; - - BF2_AI_FRONTIER("dice::hfe::ai::SquadMember::updateMemberPos (IAIObject information handle)"); + Information* const info = informationManager->getInformation(vehicle->getInformation(m_side + 1)); + Information* const primary = informationManager->getInformation(info->getPrimaryObject(m_side + 1)); + if (primary && primary->getUnit()) + { + const float oldY = m_position.y; + const float oldX = m_position.x; + const float oldZ = m_position.z; + m_position = primary->getPosition(); + m_positionValid = true; + const float dz = oldZ - m_position.z; + const float dx = oldX - m_position.x; + const float dy = oldY - m_position.y; + if (dz * dz + dx * dx + dy * dy > 0.01f) + m_moved = true; + } } -// Retain -// the vehicle before testing the freshly read player's alive/man-down state. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] +// ELF 0x1B5560 (188 bytes): a live member in an object with unit and mobile information. bool SquadMember::isMobile() { IAIObject* const vehicle = m_player->getCurrentVehicle(); @@ -349,27 +476,112 @@ bool SquadMember::isMobile() return false; if (m_player->isManDown()) return false; - - BF2_AI_FRONTIER("dice::hfe::ai::SquadMember::isMobile (IAIObject information handle)"); + Information* const info = informationManager->getInformation(vehicle->getInformation(m_side + 1)); + return info && info->getUnit() && info->getMobile(); } -// Position validity is deliberately ignored before the formation-world-position query. -// [INFERRED] void return: callers discard it and exits materialize no common value. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] +// ELF 0x1B3AC0 (864 bytes). The member's slot position (SquadFormation::getSlotWorldPos); with it, +// the maximum speed and the estimated arrival (squared distance / speed, as in the image) are +// refreshed from the vehicle's mobile information (no null checks). A bot member: within +// sqrt(10) of the slot it counts as arrived (+0x30; arriving clears the path flag). The slot-0 +// member leads: on a mission once the formation moves out, at the formation's speed, towards the +// goal (snapped to the area order position) unless it has a path or is within sqrt(8); otherwise +// only with a player commander and no path. Everyone else moves to the slot while +0x49 / +0x4A +// ask for it (+0x4A is consumed). void SquadMember::moveWithFormation() { SquadFormation* const formation = m_squad->getSquadFormation(); Vec3 position = {}; getPosition(position); Vec3 slotPosition = {}; - (void)formation; (void)slotPosition; - BF2_AI_FRONTIER("dice::hfe::ai::SquadMember::moveWithFormation (SquadFormation::getSlotWorldPos)"); + if (!formation->getSlotWorldPos(m_memberIndex, slotPosition)) + return; + const float dx = slotPosition.x - position.x; + const float dy = slotPosition.y - position.y; + const float dz = slotPosition.z - position.z; + const float distanceSq = dy * dy + dx * dx + dz * dz; + Information* const info = + informationManager->getInformation(m_player->getCurrentVehicle()->getInformation(m_side + 1)); + const float maxSpeed = info->getMobile()->getMaxSpeed(); + m_maxSpeed = maxSpeed; + m_estimatedArrival = static_cast(static_cast(distanceSq) / maxSpeed); + if (!m_bot) + return; + if (distanceSq <= 10.0f) + { + if (!m_flag30) + m_havePath = false; + m_flag30 = true; + } + else + { + m_flag30 = false; + } + if (formation->getSquadMemberIndexAtSlot(0) == m_memberIndex) + { + if (m_squad->getMissionStatus() == 2 && formation->shouldSquadMoveOut()) + { + m_maxSpeed = formation->getFormationMaxSpeed(); + Vec3 goal = m_squad->getSquadGotoPos(); + if (m_squad->isSquadAssignedToAnyArea()) + m_squad->getValidSaPos(this, goal); + if (m_havePath) + return; + const float gx = goal.x - position.x; + const float gy = goal.y - position.y; + const float gz = goal.z - position.z; + if (gz * gz + gx * gx + gy * gy <= 8.0f) + return; + } + else + { + if (m_havePath) + return; + if (!IAIMain::m_instance->getSAI(m_side + 1)->isPlayerCommander()) + return; + } + moveToGoalPos(info); + } + else if (m_flag49 || m_flag4A) + { + m_flag4A = false; + moveToSlotPos(slotPosition, info); + } } -// The no-bot and dead-player returns are shipped. The alive branch ignores position -// validity, copies the goal and queries the fresh player; no null vehicle guard follows. -// [INFERRED] void return, as above. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] +// ELF 0x1B3FF0 (592 bytes). A path to the slot: a one-goal WPMoveTo(0, 60, 2) on the ground, or a +// WPAltitudeMoveTo for aircraft as in moveToGoalPos - except that here the image samples the +// terrain at (x, y) of the slot, not (x, z). +void SquadMember::moveToSlotPos(const Vec3& position, Information* information) +{ + m_havePath = true; + m_vector60 = position; + if (!information->isOfType(ITAir)) + { + WPMoveTo::GoalList goals; + goals.push_back(std::make_pair(position, -1)); + m_bot->setWaypoints(new WPMoveTo(0.0f, 60.0f, 2, goals)); + return; + } + float altitude = 70.0f; + float radius = 30.0f; + if (information->isOfType(ITHelicopter)) + { + radius = 5.0f; + altitude = 20.0f; + } + std::list positions; + Vec3 raised = position; + raised.y = static_cast(CommonSingletonServer::m_iaiTerrain)->getTerrainAltitude(position.x, position.y) + + altitude; + positions.push_back(raised); + m_bot->setWaypoints(new WPAltitudeMoveTo(radius, radius, altitude, 2, positions)); +} + +// ELF 0x1B3E20 (464 bytes). A live bot member refreshes its maximum speed from its vehicle's +// mobile information (no null check on the information) and moves to the goal while it has no +// path: on a mission (status 2) when farther than sqrt(8) from the squad's goto position; +// otherwise only while its side's SAI has a player commander. void SquadMember::moveWithoutFormation() { if (!m_bot) @@ -380,16 +592,537 @@ void SquadMember::moveWithoutFormation() Vec3 position = {}; getPosition(position); const Vec3 goal = m_squad->getSquadGotoPos(); - IAIObject* const vehicle = m_player->getCurrentVehicle(); - (void)goal; (void)vehicle; - BF2_AI_FRONTIER("dice::hfe::ai::SquadMember::moveWithoutFormation (IAIObject information handle)"); + Information* const info = + informationManager->getInformation(m_player->getCurrentVehicle()->getInformation(m_side + 1)); + if (info->getMobile()) + m_maxSpeed = info->getMobile()->getMaxSpeed(); + if (m_squad->getMissionStatus() == 2) + { + if (m_havePath) + return; + const float dz = goal.z - position.z; + const float dx = goal.x - position.x; + const float dy = goal.y - position.y; + if (8.0f < dz * dz + dx * dx + dy * dy) + { + moveToGoalPos(info); + return; + } + } + else if (m_havePath) + { + return; + } + if (!IAIMain::m_instance->getSAI(m_side + 1)->isPlayerCommander()) + return; + moveToGoalPos(info); +} + +namespace { + +// The acknowledgement after a move order: a bot member tells the squad (radio message 6 when +// it moves, 7 when the position is unreachable; channel 3, priority 3, delay 2 s) once per +// order, as the coordinator's roger-that flag allows. +void acknowledgePosition(SquadMember* member, SquadCoordinator* squad, int message) +{ + if (!squad->getRogerThatPositionMessage() || !member->isBot()) + return; + member->getBot()->getCommunicationAgent()->enqueueRadioMessage( + static_cast(message), static_cast(3), 3, 2.0f, 0); + squad->setRogerThatPositionMessage(false); +} + +} // namespace + +// ELF 0x1B4240 (3802 bytes). Only for a mobile member of a squad on a mission (status 2). +// * Ground units (no type flag 0x10) follow the squad leader while the formation says so and the +// squad is not close to a non-owned target: to the leader's goto position, unless it lies in +// the assigned area; without an area directly, otherwise snapped to the order position of the +// strategic area containing it. A reachable goal becomes a one-goal WPMoveTo(0, 60, 2); +// an unreachable one is acknowledged with message 7 and falls through to the squad goal. +// * The squad goal: the goto position, snapped to the assigned area's order position. Aircraft +// (flag 0x10; helicopters 0x20 too) get a WPAltitudeMoveTo at terrain height + 70 (20) with +// radius 30 (5). Otherwise an unreachable goal is acknowledged with 7; a reachable one without +// an area becomes a WPMoveTo (set only when it differs from the current waypoints); with an +// area, the strategic route from the bot's current object to the area: no route gives a +// WPMoveTo as before (no acknowledgement), a route is handed to orderNormalBot, dropping its +// first object when the bot is closer to the goal than that object is. +// The ordered goal is kept at +0x60 (for a route: the area's height marker m_f148 as y). +void SquadMember::moveToGoalPos(Information* information) +{ + if (!information->getMobile()) + return; + if (m_squad->getMissionStatus() != 2) + return; + Vec3 goal = m_squad->getSquadGotoPos(); + AIStrategicArea* area = m_squad->getSquadStrategicAreaAssignment(); + const int side = m_side + 1; + + if (!information->isOfType(ITAir) + && m_squad->getSquadFormation()->shouldLeaveSquadLeader() + && !m_squad->isSquadCloseToNonOwnedTarget()) + { + goal = m_squad->getSquadLeaderGotoPos(); + bool follow = false; + if (!area) + { + follow = true; + } + else if (!area->isInside(goal)) + { + AIStrategicArea* const closest = static_cast( + AIStrategicObjectManager::getInstance()->getClosestObject(goal, side)); + if (closest && closest->isInside(goal)) + m_squad->getValidSaPos(this, closest, goal); + follow = true; + } + if (follow) + { + if (m_squad->isValidPosition(this, goal)) + { + m_havePath = true; + WPMoveTo::GoalList goals; + goals.push_back(std::make_pair(goal, -1)); + m_bot->setWaypoints(new WPMoveTo(0.0f, 60.0f, 2, goals)); + m_vector60 = goal; + acknowledgePosition(this, m_squad, 6); + return; + } + acknowledgePosition(this, m_squad, 7); + } + } + + goal = m_squad->getSquadGotoPos(); + if (m_squad->isSquadAssignedToAnyArea()) + m_squad->getValidSaPos(this, goal); + if (information->isOfType(ITAir)) + { + float altitude = 70.0f; + float radius = 30.0f; + if (information->isOfType(ITHelicopter)) + { + radius = 5.0f; + altitude = 20.0f; + } + std::list positions; + Vec3 raised = goal; + raised.y = static_cast(CommonSingletonServer::m_iaiTerrain)->getTerrainAltitude(goal.x, goal.z) + + altitude; + positions.push_back(raised); + m_bot->setWaypoints(new WPAltitudeMoveTo(radius, radius, altitude, 2, positions)); + m_vector60 = goal; + acknowledgePosition(this, m_squad, 6); + return; + } + if (!m_squad->isValidPosition(this, goal)) + { + acknowledgePosition(this, m_squad, 7); + return; + } + m_havePath = true; + WPMoveTo::GoalList goals; + if (!m_squad->isSquadAssignedToAnyArea()) + { + goals.push_back(std::make_pair(goal, -1)); + WPMoveTo* const waypoints = new WPMoveTo(0.0f, 60.0f, 2, goals); + if (!isSameWaypointList(m_bot->getWaypoints(), waypoints)) + { + m_bot->setWaypoints(waypoints); + m_vector60 = goal; + acknowledgePosition(this, m_squad, 6); + } + else + { + delete waypoints; + } + return; + } + + std::list route; + const int botId = static_cast(m_bot->getBotId()); + AIStrategicArea* const from = static_cast(AIStrategicObjectManager::getInstance()->getStrategicObject( + IAIMain::m_instance->getSAI(side)->getBotCurrentPos(botId))); + if (!m_squad->getSquadStrategicAreaAssignment()->getRouteList(side, from, route)) + { + goals.push_back(std::make_pair(goal, -1)); + WPMoveTo* const waypoints = new WPMoveTo(0.0f, 60.0f, 2, goals); + if (!isSameWaypointList(m_bot->getWaypoints(), waypoints)) + { + m_bot->setWaypoints(waypoints); + m_vector60 = goal; + } + else + { + delete waypoints; + } + return; + } + if (1 < route.size()) + { + Vec3 position = {}; + getPosition(position); + const float dx = goal.x - position.x; + const float dz = goal.z - position.z; + const Vec2& first = route.front()->getPosition(side); + const float fx = goal.x - first.x; + const float fz = goal.z - first.y; + if (dx * dx + dz * dz < fz * fz + fx * fx) + route.erase(route.begin()); + } + goal.y = m_squad->getSquadStrategicAreaAssignment()->m_f148; + m_vector60 = goal; + ISAI* const sai = IAIMain::m_instance->getSAI(side); + m_squad->getSquadStrategicAreaAssignment()->orderNormalBot(side, route, static_cast(m_bot->getBotId()), sai); + acknowledgePosition(this, m_squad, 6); +} + +// ELF 0x1B5120 (539 bytes). Only a current WPMoveTo (type word +0xC == 0) can match: both goal +// lists must have the same length and each pair of goals lie within 10 m (squared <= 100). +bool SquadMember::isSameWaypointList(WaypointList* current, WaypointList* candidate) +{ + if (static_cast(current)->m_int0C != 0) + return false; + std::list a; + std::list b; + static_cast(current)->getCoords(a); + static_cast(candidate)->getCoords(b); + if (a.empty() || b.empty()) + return false; + std::list::const_iterator i = a.begin(); + std::list::const_iterator j = b.begin(); + while (i != a.end()) + { + const float dx = j->x - i->x; + const float dy = j->y - i->y; + const float dz = j->z - i->z; + if (dx * dx + dy * dy + dz * dz > 100.0f) + return false; + ++i; + ++j; + if (i == a.end()) + return j == b.end(); + if (j == b.end()) + return false; + } + return false; } -// [FRONTIER] Returns the member's vehicle radius once the information query chain is implemented. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding SquadMember operation. +// ELF 0x1B3A10: IPIPhysical::getRadius of the member's object information; no null guards. float SquadMember::getVehicleRadius() { - BF2_AI_FRONTIER("dice::hfe::ai::SquadMember::getVehicleRadius"); + IAIObject* const vehicle = m_player->getCurrentVehicle(); + Information* const info = informationManager->getInformation(vehicle->getInformation(m_side + 1)); + return info->getPhysical()->getRadius(); +} + +// ELF 0x1B1930: the per-round state - the position flags (+0x48..+0x4B: invalid, 49/4A set, +// 4B clear), the path reconsideration time (+0x24) and the two Vec3s at +0x54/+0x60 zeroed. +void SquadMember::reset() +{ + m_positionValid = false; + m_flag49 = true; + m_flag4A = true; + m_flag4B = false; + m_time24 = 0.0; + m_vector54.x = m_vector54.y = m_vector54.z = 0.0f; + m_vector60.x = m_vector60.y = m_vector60.z = 0.0f; +} + +void SquadMember::setMemberIndex(int index) +{ + m_memberIndex = index; +} + +// ELF 0x1B1BF0: only with a mission, an area assignment whose status for this member's side is +// non-zero and a valid position: true when the squad's goto position lies inside the formation +// distance (squared distance below +0x4C). +bool SquadMember::isCloseToNonOwnedTarget() const +{ + if (!m_squad->squadHasMission()) + return false; + if (!m_squad->isSquadAssignedToAnyArea()) + return false; + if (!m_squad->getSquadStrategicAreaAssignment()->m_status[m_side]) + return false; + if (!m_positionValid) + return false; + const Vec3& target = m_squad->getSquadGotoPos(); + const double dx = static_cast(target.x) - m_position.x; + const double dy = static_cast(target.y) - m_position.y; + const double dz = static_cast(target.z) - m_position.z; + return m_formationDistanceSq > dx * dx + dy * dy + dz * dz; +} + +// ELF 0x1B1D10: status 1 uses the second threshold; other nonzero statuses use the first. +bool SquadMember::isCloseToNonOwnedTarget(float otherDistanceSq, float statusOneDistanceSq) const +{ + if (!m_squad->squadHasMission()) + return false; + if (!m_squad->isSquadAssignedToAnyArea()) + return false; + const int status = m_squad->getSquadStrategicAreaAssignment()->m_status[m_side]; + if (!status) + return false; + const float distanceSq = status == 1 ? statusOneDistanceSq : otherDistanceSq; + if (!m_positionValid) + return false; + Vec2 target = {0.0f, 0.0f}; + Vec2 position = {0.0f, 0.0f}; + vec3ToVec2XZ(m_squad->getSquadGotoPos(), target); + vec3ToVec2XZ(m_position, position); + const float dx = position.x - target.x; + const float dy = position.y - target.y; + return distanceSq > dx * dx + dy * dy; +} + +// ELF 0x1B2840 (1609 bytes). Already avoiding: true. Otherwise up to five candidates at the +// safe distance + 5 m from the artillery target, starting away from it through `position` and +// swinging round (the angle goes 0 -> +x, -(a) - x, 3a + x, ..., x in [0.6, 0.8)); a valid one, or +// else the side's remembered flee position, becomes a one-goal WPMoveTo (0, 60, flags 2) and the +// member avoids artillery (+0x31, +0x4B). A found candidate is remembered for the side. +bool SquadMember::avoidArtillery(Vec3 position, double /*sinceStart*/, int side) +{ + if (m_flag4B) + return true; + SquadManager* const manager = SquadManager::m_instance; + const Vec3 target = manager->getArtilleryTargetPos(side); + Vec3 away; + away.x = position.x - target.x; + away.y = position.y - target.y; + away.z = position.z - target.z; + const float safe = manager->getArtillerySafeDistance(); + const float lengthSq = away.z * away.z + away.x * away.x + away.y * away.y; + if (std::fabs(lengthSq - 1.0f) >= 1.1920929e-07f) + { + if (std::fabs(lengthSq) >= 1.1920929e-07f) + { + const float inverse = 1.0f / std::sqrt(lengthSq); + away.x = away.x * inverse; + away.y = away.y * inverse; + away.z = inverse * away.z; + } + else + { + away.x = 0.0f; + away.y = 0.0f; + away.z = 0.0f; + } + } + const float radius = safe + 5.0f; + Vec3 direction = away; + Vec3 candidate; + candidate.x = 0.0f; + candidate.y = 0.0f; + candidate.z = 0.0f; + float angle = 0.0f; + bool found = false; + for (int tries = 0; tries <= 4;) + { + candidate.x = radius * direction.x + target.x; + candidate.y = radius * direction.y + target.y; + candidate.z = radius * direction.z + target.z; + if (m_squad->isValidPosition(this, candidate)) + { + found = true; + break; + } + ++tries; + if (0.0f < angle) + angle = (angle - (angle + angle)) - (AIRandom::m_instance->nextFloat() * 0.2f + 0.6f); + else + angle = (angle + angle + angle) + (AIRandom::m_instance->nextFloat() * 0.2f + 0.6f); + rotateXZ(away, direction, angle); + } + if (!found && !manager->haveValidArtilleryFleePos(this, candidate)) + return false; + m_havePath = true; + m_flag4B = true; + std::list > goals; + goals.push_back(std::make_pair(candidate, -1)); + m_bot->setWaypoints(new WPMoveTo(0.0f, 60.0f, 2, goals)); + if (found) + manager->setValidArtilleryFleePos(this, candidate); + return true; +} + +// ELF 0x1B1E60: a killed member leaves its formation slot. +void SquadMember::squadMemberKilled() +{ + SquadFormation* const formation = m_squad->getSquadFormation(); + if (formation->isInFormation(m_memberIndex)) + formation->leaveFormation(m_memberIndex); +} + +// ELF 0x1B1990: frees the request record (operator delete); the pointer is left as is. +void SquadMember::removeRequest() +{ + ::operator delete(m_request); +} + +// ELF 0x1B3810: the member stands on its squad's assigned area's control point: it has a +// position, the area exists and its status for the member's side (+0x70 + 4 * (side + 1)) is +// non-zero, the area has a control point, the player is alive (IAIPlayer +0x24) and not man-down +// (+0x2C), and the squared distance is below radius^2 + 5 (0x49CDAC). +bool SquadMember::isTakingFlag() +{ + bool taking = false; + AIStrategicArea* const area = m_squad->getSquadStrategicAreaAssignment(); + Vec3 position = {}; + if (getPosition(position) && area && static_cast(area->getStatus(m_side + 1)) != 0) + { + Vec3 point = {}; + float radius; + if (area->getControlPointPosAndRadius(point, radius)) + { + radius = radius * radius; + if (m_player->getIsAlive() && !m_player->isManDown()) + { + const float dx = position.x - point.x; + const float dy = position.y - point.y; + const float dz = position.z - point.z; + if (dx * dx + dy * dy + dz * dz < radius + 5.0f) + taking = true; + } + } + } + return taking; +} + +// ELF 0x1B1E50. +void SquadMember::setForcePathUpdate(bool force) { m_flag4A = force; } + +// ELF 0x1B2EA0: the assisted member's equipment supplies the movement dimensions. +void SquadMember::moveToAssistSquadMember(SquadMember* member, const Vec3& position) +{ + if (m_havePath) + return; + IAIObject* const vehicle = member->getPlayer()->getCurrentVehicle(); + InformationManager* const manager = informationManager; + Information* const information = manager->getInformation(vehicle->getInformation(m_side + 1)); + moveToSlotPos(position, information); +} + +// ELF 0x1B2F40: ten attempts; failure returns the zero vector. +Vec3 SquadMember::getRandomAssistPos(SquadMember* member, const Vec3& position, const Vec3& direction) +{ + Vec3 result = {}; + const Vec2 normal = {direction.z, -direction.x}; + const float radius = member->getVehicleRadius(); + const float diameter = radius + radius; + const float selfRadius = getVehicleRadius(); + const float range = selfRadius + selfRadius + diameter; + Vec3 selfPosition = {}; + if (!getPosition(selfPosition)) + return result; + for (int attempt = 0; attempt < 10; ++attempt) + { + float angle = AIRandom::m_instance->nextFloat() * 0.785398006f + 0.436329991f; + Vec2 toward = {selfPosition.x - position.x, selfPosition.z - position.z}; + const float squared = toward.x * toward.x + toward.y * toward.y; + if (!(std::fabs(squared - 1.0f) < 1.1920928955078125e-7f)) + { + if (!(std::fabs(squared) < 1.4210854715202004e-14f)) + { + const float inverse = 1.0f / std::sqrt(squared); + toward.x *= inverse; + toward.y *= inverse; + } + else + { + toward.x = 0.0f; + toward.y = 0.0f; + } + } + if (toward.x * normal.x + toward.y * normal.y > 0.0f) + angle = -angle; + Vec3 rotated = {}; + rotateXZ(direction, rotated, angle); + const Vec3 base = {radius * rotated.x * 4.0f + position.x, + radius * rotated.y * 4.0f + position.y, + radius * rotated.z * 4.0f + position.z}; + const float random = AIRandom::m_instance->nextFloat(); + const Vec3 candidate = {rotated.x * random * range + base.x, + rotated.y * random * range + base.y, + random * rotated.z * range + base.z}; + if (m_squad->isValidPosition(this, candidate)) + return candidate; + } + return result; +} + +// ELF 0x1B3450: only a different shooter within 75 metres can be assisted. +SquadMember* SquadMember::getAssistFiringSquadMember(Vec3& position) +{ + Vec3 memberPosition = {}; + if (!m_squad->anyFiring() || m_squad->isFiring(m_playerId)) + return 0; + float distanceSquared; + SquadMember* const member = m_squad->getClosestFiringMember(this, distanceSquared); + if (!member || !(distanceSquared < 5625.0f)) + return 0; + if (m_assistMember != member) + m_havePath = false; + m_assistMember = member; + if (member->getPosition(memberPosition)) + { + const Vec3 direction = m_squad->getFiringDir(member); + position = getRandomAssistPos(member, memberPosition, direction); + if (!(position.x * position.x + position.y * position.y + position.z * position.z < 0.001f)) + return member; + } + m_assistMember = 0; + return 0; +} + +// ELF 0x1B35B0: missing data normally permits damage; man-down and insufficient strength refuse it. +bool SquadMember::canDamageTarget(unsigned int target) +{ + if (!m_bot || target == 0xFFFFFFFFu) + return true; + if (m_bot->getManDown()) + return false; + Information* const targetInformation = informationManager->getInformation(target); + if (!targetInformation) + return true; + Vec3 position = {}; + IPIPhysical* const targetPhysical = targetInformation->getPhysical(); + if (!targetPhysical || !getPosition(position)) + return true; + InformationManager* const manager = informationManager; + Information* const equipment = manager->getInformation(m_bot->getCurrentEquipment()); + if (!equipment) + return true; + IPIArmament* const armament = equipment->getArmament(); + if (!armament) + return true; + const std::vector& weapons = armament->getWeapons(); + const Vec3& targetPosition = targetInformation->getPosition(); + const float dx = m_position.x - targetPosition.x; + const float dy = m_position.y - targetPosition.y; + const float dz = m_position.z - targetPosition.z; + (void)std::sqrt(dx * dx + dy * dy + dz * dz); + float strength = 0.0f; + if (armament->isAntiAircraft() || !targetInformation->isOfType(ITAir)) + { + for (unsigned int i = 0; i < weapons.size(); ++i) + { + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (weapon && weapon->getWeaponType() == 0) + { + const float candidate = static_cast(weapon->getStrength(targetPhysical->getStrengthType())); + if (candidate > strength) + strength = candidate; + } + } + } + return strength > 0.1f; +} + +// ELF 0x1B39A0: action is written before the handle is re-read from the request. +void SquadMember::getCurrentRequestAction(RequestAction& action, unsigned int& handle) +{ + action = static_cast(m_request->m_action); + handle = m_request->m_handle; } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.h b/Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.h index c5e9582ff..2222f0d37 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.h @@ -14,6 +14,8 @@ namespace ai { class IAIPlayer; class Bot; class SquadCoordinator; +class Information; +class WaypointList; class SquadMember { @@ -26,21 +28,59 @@ class SquadMember SquadCoordinator* getSquad(); int getPlayerId(); bool isBot(); + float getEstimatedArrival() { return m_estimatedArrival; } // ELF 0x1B5550: flds +0x20 + bool isAtFormationSlot() { return m_flag30; } // ELF 0x1B5540: movzbl +0x30 + int getSide() { return m_side + 1; } // ELF 0x1B5680: +0x1C, incl + bool isTakingFlag(); // ELF 0x1B3810 Bot* getBot(); // borrowed int getMemberIndex(); + void setMemberIndex(int index); // ELF 0x1B56C0: +0x04 + bool isCloseToNonOwnedTarget() const; // ELF 0x1B1BF0 + bool isCloseToNonOwnedTarget(float, float) const; // ELF 0x1B1D10, squared horizontal thresholds void setIsSquadLeader(bool leader); bool isSquadLeader(); bool isMoving(); // returns m_moved + void setIsIdle(bool idle) { m_flag49 = idle; } // ELF 0x1B3950: +0x49 + bool getIsIdle() { return m_flag49; } // ELF 0x1B3960 + bool isAvoidingArtillery() { return m_flag4B; } // ELF 0x1B2E90: +0x4B void setHavePath(bool havePath); + void setForcePathUpdate(bool force); + void moveToAssistSquadMember(SquadMember* member, const Vec3& position); + Vec3 getRandomAssistPos(SquadMember* member, const Vec3& position, const Vec3& direction); + SquadMember* getAssistFiringSquadMember(Vec3& position); + bool canDamageTarget(unsigned int target); void update(double time); // bounded dependent calls void updateFormationStatus(); + void reset(); // ELF 0x1B1930 + void removeRequest(); // ELF 0x1B1990 + void squadMemberKilled(); // ELF 0x1B1E60 + bool avoidArtillery(Vec3 position, double sinceStart, int side); // ELF 0x1B2840 bool getPosition(Vec3& position); // copies even if invalid - bool isAllowedInFormation(); // nonnull vehicle [FRONTIER] - void updateMemberPos(); // nonnull vehicle [FRONTIER] - bool isMobile(); // owner query [FRONTIER] - void moveWithFormation(); // world-position [FRONTIER] - void moveWithoutFormation(); // alive owner query [FRONTIER] - float getVehicleRadius(); // [FRONTIER] + bool isAllowedInFormation(); // ELF 0x1B5380 + void updateMemberPos(); // ELF 0x1B1A70 + bool isMobile(); // ELF 0x1B5560 + void moveWithFormation(); // ELF 0x1B3AC0 + void moveToSlotPos(const Vec3& position, Information* information); // ELF 0x1B3FF0 + void moveWithoutFormation(); // ELF 0x1B3E20 + void moveToGoalPos(Information* information); // ELF 0x1B4240 + bool isSameWaypointList(WaypointList* current, WaypointList* candidate); // ELF 0x1B5120 + float getVehicleRadius(); + + // ELF 0x1B5620: +0x2C. + float getMaxSpeed() { return m_maxSpeed; } + // ELF 0x1B39C0: the request (+0x34) back to action 0, handle -1. + void clearRequestAction() { m_request->m_action = 0; m_request->m_handle = 0xFFFFFFFFu; } + // ELF 0x1B3980: the pending request (+0x34) becomes this action (+0) and handle (+4). The image + // takes the SquadMember::RequestAction enum; the tree keeps it as int like isSameRequest. + void setCurrentRequestAction(int action, unsigned int handle) + { m_request->m_action = action; m_request->m_handle = handle; } + enum RequestAction : int; + void getCurrentRequestAction(RequestAction& action, unsigned int& handle); + // ELF 0x1B39E0: the pending request (+0x34) has this handle (+4) and action (+0). + bool isSameRequest(unsigned int handle, int action) + { return m_request->m_handle == handle && m_request->m_action == action; } + // ELF 0x1B56B0: +0. + int getSquadId() const { return m_squadIndex; } // [INFERRED] carrier name. The two fields are attested by setCurrentRequestAction // its first parameter is the RequestAction enum, its second unsigned int. @@ -62,19 +102,19 @@ class SquadMember /* +0x20 */ float m_estimatedArrival; // getEstimatedArrival /* +0x24 */ double m_time24; // last path reconsideration time; initialized to zero /* +0x2C */ float m_maxSpeed; // getMaxSpeed - /* +0x30 */ bool m_flag30; // [UNRESOLVED] + /* +0x30 */ bool m_flag30; // moveWithFormation: within sqrt(10) of the slot [INFERRED] /* +0x31 */ bool m_havePath; /* +0x34 */ RequestState* m_request; - /* +0x38 */ int m_int38; // [UNRESOLVED] + /* +0x38 */ SquadMember* m_assistMember; // [INFERRED] member currently being assisted /* +0x3C */ Vec3 m_position; /* +0x48 */ bool m_positionValid; - /* +0x49 */ bool m_flag49; // [UNRESOLVED] + /* +0x49 */ bool m_flag49; // set/getIsIdle; moveWithFormation moves an idle member to its slot /* +0x4A */ bool m_flag4A; // setHavePath writes the inverse of its argument - /* +0x4B */ bool m_flag4B; // [UNRESOLVED] + /* +0x4B */ bool m_flag4B; // isAvoidingArtillery /* +0x4C */ float m_formationDistanceSq; // [INFERRED] name, starts at 900.0 /* +0x50 */ bool m_moved; /* +0x54 */ Vec3 m_vector54; // [UNRESOLVED] - /* +0x60 */ Vec3 m_vector60; // [UNRESOLVED] + /* +0x60 */ Vec3 m_vector60; // the last goal moveToGoalPos ordered [INFERRED] meaning }; #if defined(_MSC_VER) diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/UrgencyMerger.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/UrgencyMerger.cpp new file mode 100644 index 000000000..22a60fe25 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/UrgencyMerger.cpp @@ -0,0 +1,133 @@ +// Source placement: AIDLL_r.dll __FILE__ "Code\BF2\AI\AIDLL\AI\AIBot\UrgencyMerger.cpp" (assert "mpMaxGenerator != 0", 0x101F9180). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining UrgencyMerger operations. + +// static init: ELF 0x1B5CD0 (__tcf_0 0x1B5D30, _GLOBAL__I 0x1B5D60): 's Init object only. +#include + +#include "UrgencyMerger.h" + + +namespace dice { +namespace hfe { +namespace ai { + +// one instruction in the binary - the vptr store C++ emits on its own. The class owns nothing +// which is what makes it a pure interface rather than a partial implementation. +UrgencyGenerator::~UrgencyGenerator() +{ +} + +// Four stores after the vptr. `m_weights` is whatever the caller passed and BotManager passes +// null, so a merger from the bot pool has no weight array at all - whatever `getUrgency` does with +// that is the next thing to read, and it is not guessed at here. +UrgencyMerger::UrgencyMerger(int count, float* weights, UrgencyGenerator** generators) + : m_count(count) + , m_weights(weights) + , m_generators(generators) + , mpMaxGenerator(0) +{ +} + +// ELF 0x1B5930: only the vptr store; the generators belong to the caller. +UrgencyMerger::~UrgencyMerger() +{ +} + +// ELF 0x1B59B0. The chosen generator's urgency, 0 when none is chosen. +float UrgencyMerger::getUrgency(Bot* bot) +{ + if (mpMaxGenerator == 0) + return 0.0f; + return mpMaxGenerator->getUrgency(bot); +} + +// ELF 0x1B5A00. +float UrgencyMerger::getActiveUrgency(Bot* bot) +{ + if (mpMaxGenerator == 0) + return 0.0f; + return mpMaxGenerator->getActiveUrgency(bot); +} + +// ELF 0x1B5A40. Updates every generator; the strictly most urgent one's own chosen generator +// becomes this merger's. Returns that urgency (0 when none is positive). The weights are not read. +float UrgencyMerger::updateActiveUrgency(Bot* bot) +{ + float best = 0.0f; + mpMaxGenerator = 0; + for (int i = 0; i < m_count; ++i) + { + const float urgency = + m_generators[i] != 0 ? m_generators[i]->updateActiveUrgency(bot) : 0.0f; + if (urgency > best) + { + best = urgency; + mpMaxGenerator = m_generators[i]->getChosenGenerator(); + } + } + return best; +} + +// ELF 0x1B5AF0. True while every present generator reports a changed target (stops at the first +// that does not); true with no generators. +bool UrgencyMerger::hasChangedTarget(Bot* bot) +{ + bool changed = true; + for (int i = 0; i < m_count && changed; ++i) + { + if (m_generators[i] != 0) + changed = m_generators[i]->hasChangedTarget(bot); + } + return changed; +} + +// ELF 0x1B5B60. The same conjunction over quotientChanged. +bool UrgencyMerger::quotientChanged(Bot* bot, float lower, float upper) +{ + bool changed = true; + for (int i = 0; i < m_count && changed; ++i) + { + if (m_generators[i] != 0) + changed = m_generators[i]->quotientChanged(bot, lower, upper); + } + return changed; +} + +// ELF 0x1B5BE0. True as soon as one present generator's quotient or target changed. +bool UrgencyMerger::hasChanged(Bot* bot, float lower, float upper) +{ + bool changed = false; + for (int i = 0; i < m_count && !changed; ++i) + { + if (m_generators[i] != 0) + changed = m_generators[i]->quotientChanged(bot, lower, upper) || + m_generators[i]->hasChangedTarget(bot); + } + return changed; +} + +// ELF 0x1A2850. +UrgencyGenerator* UrgencyMerger::getChosenGenerator() +{ + return mpMaxGenerator; +} + +// ELF 0x1B5C80. Resets every present generator. +void UrgencyMerger::reset(Bot* bot) +{ + for (int i = 0; i < m_count; ++i) + { + if (m_generators[i] != 0) + m_generators[i]->reset(bot); + } +} + +// ELF 0x1B59F0. +int UrgencyMerger::getSize() +{ + return m_count; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/UrgencyMerger.h b/Code/BF2/AI/AIDLL/AI/AIBot/UrgencyMerger.h similarity index 72% rename from Code/BF2/AI/AIDLL/AI/AIBotBehaviour/UrgencyMerger.h rename to Code/BF2/AI/AIDLL/AI/AIBot/UrgencyMerger.h index d9f6dba58..b682364e4 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/UrgencyMerger.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/UrgencyMerger.h @@ -1,6 +1,5 @@ // Combines per-behavior urgency generators for a bot. -// [FRONTIER] Remaining merger behavior requires implementation. -// [INFERRED] Source placement. +// Header placement [INFERRED]: beside its .cpp, whose path AIDLL_r.dll confirms (AIBot/UrgencyMerger.cpp). #ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_URGENCYMERGER_H // [INFERRED] guard style #define AI_AIDLL_AI_AIBOTBEHAVIOUR_URGENCYMERGER_H @@ -11,7 +10,9 @@ namespace ai { class Bot; -// UrgencyGenerator - the abstract base. vtable off_4B6E88: , , then nine pure virtuals. +// UrgencyGenerator - the abstract base. vtable ELF 0x4B6E80: the two destructors, then eight pure +// virtuals (+0x08..+0x24). Slot +0x28 belongs to the subclasses: UrgencyMerger's getSize, a +// different pure virtual in BotBehaviour. // Its destructor body is one instruction - the vptr store C++ emits - so the class // owns nothing. It is an interface with a virtual destructor and no state. class UrgencyGenerator @@ -21,13 +22,12 @@ class UrgencyGenerator virtual float getUrgency(Bot* bot) = 0; // +0x08 virtual float getActiveUrgency(Bot* bot) = 0; // +0x0C - virtual void updateActiveUrgency(Bot* bot) = 0; // +0x10 + virtual float updateActiveUrgency(Bot* bot) = 0; // +0x10 virtual bool hasChangedTarget(Bot* bot) = 0; // +0x14 virtual bool quotientChanged(Bot* bot, float a, float b) = 0; // +0x18 virtual bool hasChanged(Bot* bot, float a, float b) = 0; // +0x1C virtual UrgencyGenerator* getChosenGenerator() = 0; // +0x20 virtual void reset(Bot* bot) = 0; // +0x24 - virtual int getSize() = 0; // +0x28 }; // UrgencyMerger - (`operator new(0x14)` in BotManager's loop). @@ -40,20 +40,21 @@ class UrgencyMerger : public UrgencyGenerator virtual float getUrgency(Bot* bot); virtual float getActiveUrgency(Bot* bot); - virtual void updateActiveUrgency(Bot* bot); + virtual float updateActiveUrgency(Bot* bot); virtual bool hasChangedTarget(Bot* bot); virtual bool quotientChanged(Bot* bot, float a, float b); virtual bool hasChanged(Bot* bot, float a, float b); virtual UrgencyGenerator* getChosenGenerator(); virtual void reset(Bot* bot); - virtual int getSize(); + virtual int getSize(); // +0x28, introduced here -private: +protected: + // RandomSquareMerger (AIBot/RandomSquareMerger.cpp) reads every field. /* 0 */ // vptr - off_4B6E48 /* 4 */ int m_count; // the generator count; getSize returns it /* 8 */ float* m_weights; // null from BotManager's pool /* 12 */ UrgencyGenerator** m_generators; - /* 16 */ void* m_chosen; // = 0 [INFERRED] from getChosenGenerator's offset + /* 16 */ UrgencyGenerator* mpMaxGenerator; // = 0; the winner of the last updateActiveUrgency // name: AIDLL_r assert "mpMaxGenerator != 0" (0x101F9180) }; } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeCloseTo.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeCloseTo.cpp new file mode 100644 index 000000000..07ee8b149 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeCloseTo.cpp @@ -0,0 +1,82 @@ +// A flight waypoint list that closes in on an object. Evidence: libaidll.so 1.5.3153 (ia-32), see +// WPAltitudeCloseTo.h. + +#include "WPAltitudeCloseTo.h" + +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1B60D0, __tcf_0 0x1B6130, _GLOBAL__I 0x1B6160). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1B5E40 (C1; C2 0x1B5DE0): the base fields (+8 = -1.0f), the arguments, then +0xC = 3. +WPAltitudeCloseTo::WPAltitudeCloseTo(unsigned int target, float radius, float second, float third) +{ + m_target = target; + m_radius = radius; + m_second = second; + m_int0C = 3; + m_third = third; +} + +// ELF 0x1B5EC0 (D1; D2 0x1B5EA0, D0 0x1B5EE0): the base vptr only. +WPAltitudeCloseTo::~WPAltitudeCloseTo() +{ +} + +// ELF 0x1B5F20. A missing target sets +5 and yields 0. Otherwise the waypoint is reached (+4 set, +// urgency 0) when radius^2 > dx^2 * dz^2 and position.y is below +0x18; every other case yields 1. +// The XZ test multiplies the squared components (`fmulp` at 0x1B5FEF) where a distance would add +// them; that shipped defect is kept. Unordered compares fall through to 1, as here. +// [PLATFORM] retail keeps the differences and products in x87 extended precision; native builds +// round each to float. +float WPAltitudeCloseTo::getUrgency(const Vec3& position, Bot*) +{ + if (m_wayPointError) + return 0.0f; + + // The image zeroes two Vec3 temporaries (the difference and a copy of it) before the lookup; + // only their components below are read. + Information* const target = informationManager->getInformation(m_target); + if (!target) + { + m_flag5 = true; + return 0.0f; + } + + const Vec3& targetPosition = target->getPosition(); + const Vec3 from = position; + const float dx = targetPosition.x - from.x; + const float dz = targetPosition.z - from.z; + if (m_radius * m_radius > dx * dx * (dz * dz) && m_second > from.y) + { + m_flag4 = true; + return 0.0f; + } + return 1.0f; +} + +// ELF 0x1B6040: the target's position, false when the handle is stale. +bool WPAltitudeCloseTo::getGoalPoint(Vec3& out) +{ + Information* const target = informationManager->getInformation(m_target); + if (!target) + return false; + out = target->getPosition(); + return true; +} + +// ELF 0x1B60C0: `flds 0x14(this)`. +float WPAltitudeCloseTo::getWayPointRadius() const +{ + return m_radius; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeCloseTo.h b/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeCloseTo.h new file mode 100644 index 000000000..319b25a0f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeCloseTo.h @@ -0,0 +1,39 @@ +// A flight waypoint list that closes in on an object at an altitude. +// Evidence: libaidll.so 1.5.3153 (ia-32). File WPAltitudeCloseTo.cpp (FILE symbol; the AIBot +// directory is [INFERRED] from its neighbours); vtable 0x4B6EE0; constructors 0x1B5DE0 / 0x1B5E40; +// destructors 0x1B5EA0 / 0x1B5EC0 / 0x1B5EE0; getUrgency 0x1B5F20; getGoalPoint 0x1B6040; +// getWayPointRadius 0x1B60C0; getId 0x1B6220. No call site in the image constructs it. + +#ifndef AI_AIDLL_AI_AIBOT_WPALTITUDECLOSETO_H // [INFERRED] guard style +#define AI_AIDLL_AI_AIBOT_WPALTITUDECLOSETO_H + +#include "WaypointList.h" + +namespace dice { +namespace hfe { +namespace ai { + +class WPAltitudeCloseTo : public WaypointList +{ +public: + // ELF 0x1B5E40: base fields (+8 = -1.0f), the arguments at +0x10..+0x1C, +0xC = 3. + WPAltitudeCloseTo(unsigned int target, float radius, float second, float third); + virtual ~WPAltitudeCloseTo(); + + virtual float getUrgency(const Vec3& position, Bot* bot); // ELF 0x1B5F20 + virtual bool getGoalPoint(Vec3& out); // ELF 0x1B6040: the target's position + virtual int getId() { return 5; } // ELF 0x1B6220 (weak) + virtual float getWayPointRadius() const; // ELF 0x1B60C0: +0x14 + + /* +0x0C */ int m_int0C; // ctor 3 [UNRESOLVED] meaning + /* +0x10 */ unsigned int m_target; // information handle (getGoalPoint) + /* +0x14 */ float m_radius; // getWayPointRadius; the arrival radius in getUrgency + /* +0x18 */ float m_second; // getUrgency: arrival needs position.y below it + /* +0x1C */ float m_third; // BBPGotoWaypoint3d: BAPAMoveTo3dObject's distance argument +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOT_WPALTITUDECLOSETO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeMoveTo.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeMoveTo.cpp new file mode 100644 index 000000000..a9dadc3b3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeMoveTo.cpp @@ -0,0 +1,111 @@ +// A flight waypoint list. Evidence: libaidll.so 1.5.3153 (ia-32), see WPAltitudeMoveTo.h. + +#include "WPAltitudeMoveTo.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1B6CC0, __tcf_0 0x1B6D20, _GLOBAL__I 0x1B6D50). +#include + +#include "BotMain.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1B6230 (C1; C2 0x1B6420): base fields, +8 = -1.0f, the arguments, +0x18 = 1e9f +// (0x4E6E6B28), the empty list, +0xC = 4, a clear and the copy. +WPAltitudeMoveTo::WPAltitudeMoveTo(float first, float second, float third, unsigned int flags, + std::list& positions) +{ + m_first = first; + m_second = second; + m_float18 = 1e9f; + m_third = third; + m_flags = flags; + m_int0C = 4; + m_positions.clear(); + for (std::list::iterator it = positions.begin(); it != positions.end(); ++it) + m_positions.push_back(*it); +} + +// ELF 0x1B6560: the list, then the base vptr. +WPAltitudeMoveTo::~WPAltitudeMoveTo() +{ +} + +// ELF 0x1B6690. f2 = m_first^2, s2 = m_second^2, d = distXZSqr(position, front), dy2 = the squared +// height difference to the front position. With several positions the front is dropped (+4 set) +// when f2 > d and s2 > dy2, or when d grew beyond the last stored distance (+0x18), which then +// takes d; the urgency is (d + dy2) / (f2 + s2) when f2 > d and dy2 > s2 (the height test is +// reversed against the drop test, as compiled), else 1. With one position nothing is dropped: the +// urgency is 0 inside 50 m (2500) for an airborne bot, else (d + dy2) / (f2 + s2) when f2 > d +// and s2 > dy2, else 1; that arm also formats the values into a stringstream that is never read +// (the image's dead debug output). No positions: +5 set, urgency 0. Unordered compares answer 1. +// [PLATFORM] retail keeps dy2 and the sums in x87 extended precision (dy2 is rounded to float only +// on the drop path). +float WPAltitudeMoveTo::getUrgency(const Vec3& position, Bot* bot) +{ + if (m_wayPointError) + return 0.0f; + if (m_positions.empty()) + { + m_flag5 = true; + return 0.0f; + } + + const float firstSqr = m_first * m_first; + const float secondSqr = m_second * m_second; + const float distanceSqr = distXZSqr(position, m_positions.front()); + const float dy = position.y - m_positions.front().y; + const float heightSqr = dy * dy; + if (m_positions.size() == 1) + { + float urgency; + if (2500.0f > distanceSqr && bot->isAirBorn()) + urgency = 0.0f; + else if (firstSqr > distanceSqr && secondSqr > heightSqr) + urgency = (distanceSqr + heightSqr) / (firstSqr + secondSqr); + else + urgency = 1.0f; + std::stringstream debug; + debug << "distLeftSquare: " << distanceSqr << ", MinDist: " << m_first << ", Urg: " << urgency; + return urgency; + } + + if ((firstSqr > distanceSqr && secondSqr > heightSqr) || distanceSqr > m_float18) + { + m_positions.erase(m_positions.begin()); + m_flag4 = true; + } + m_float18 = distanceSqr; + if (firstSqr > distanceSqr && heightSqr > secondSqr) + return (distanceSqr + heightSqr) / (firstSqr + secondSqr); + return 1.0f; +} + +// ELF 0x1B6C40: the first position when there is one. +bool WPAltitudeMoveTo::getGoalPoint(Vec3& out) +{ + const bool any = !m_positions.empty(); + if (any) + out = m_positions.front(); + return any; +} + +// ELF 0x1B6C80: `out = positions` (std::list::operator=). +void WPAltitudeMoveTo::getCoords(std::list& out) const +{ + out = m_positions; +} + +// ELF 0x1B6CB0: `flds 0x10(this)`. +float WPAltitudeMoveTo::getWayPointRadius() const +{ + return m_first; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeMoveTo.h b/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeMoveTo.h new file mode 100644 index 000000000..30c96f0ee --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeMoveTo.h @@ -0,0 +1,48 @@ +// A flight waypoint list: positions an air bot flies through at an altitude. +// Evidence: libaidll.so 1.5.3153 (ia-32). Attested file AIBot/WPAltitudeMoveTo.cpp (FILE symbol +// beside 0x1B6CC0); vtable 0x4B70A0; constructors 0x1B6230 / 0x1B6420; destructors 0x1B6560 / +// 0x1B65C0 / 0x1B6620; getUrgency 0x1B6690; getGoalPoint 0x1B6C40; getCoords 0x1B6C80; +// getWayPointRadius 0x1B6CB0; getId 0x1B6F90. Size 0x28 (`operator new(0x28)` in +// AIStrategicArea::orderAirBot, which passes (altitude, 120.0f, 50.0f, 2, path)). + +#ifndef AI_AIDLL_AI_AIBOT_WPALTITUDEMOVETO_H // [INFERRED] guard style +#define AI_AIDLL_AI_AIBOT_WPALTITUDEMOVETO_H + +#include + +#include "WaypointList.h" + +namespace dice { +namespace hfe { +namespace ai { + +class WPAltitudeMoveTo : public WaypointList +{ +public: + // ELF 0x1B6230. Note the list is taken by non-const reference (mangled `RSt4list`). + WPAltitudeMoveTo(float first, float second, float third, unsigned int flags, std::list& positions); + virtual ~WPAltitudeMoveTo(); + + virtual float getUrgency(const Vec3& position, Bot* bot); // ELF 0x1B6690 + virtual bool getGoalPoint(Vec3& out); // ELF 0x1B6C40: the first position + virtual int getId() { return 6; } // ELF 0x1B6F90 (weak) + virtual float getWayPointRadius() const; // ELF 0x1B6CB0: +0x10 + + void getCoords(std::list& out) const; // ELF 0x1B6C80: list assignment + + // [INFERRED] names; the stores are attested. + // +0x08: WaypointList::m_float8 (base constructor: -1.0f) + /* +0x0C */ int m_int0C; // ctor 4 + /* +0x10 */ float m_first; // the first argument; getWayPointRadius + /* +0x14 */ float m_second; + /* +0x18 */ float m_float18; // ctor 1e9f; getUrgency's last front distance + /* +0x1C */ float m_third; + /* +0x20 */ unsigned int m_flags; + /* +0x24 */ std::list m_positions; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOT_WPALTITUDEMOVETO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudePatrol.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudePatrol.cpp new file mode 100644 index 000000000..6a7c0a0a6 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudePatrol.cpp @@ -0,0 +1,82 @@ +// A flight patrol loop. Evidence: libaidll.so 1.5.3153 (ia-32), see WPAltitudePatrol.h. + +#include "WPAltitudePatrol.h" + +#include + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1B8220, __tcf_0 0x1B8280, _GLOBAL__I 0x1B82B0). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1B7E60 (C1; C2 0x1B7CB0): the base fields (+8 = -1.0f), the arguments, the empty list, +// +0xC = 5, a clear, then each position appended. +WPAltitudePatrol::WPAltitudePatrol(float first, float second, float third, unsigned int flags, + std::list& positions) +{ + m_first = first; + m_second = second; + m_third = third; + m_flags = flags; + m_int0C = 5; + m_positions.clear(); + for (std::list::iterator it = positions.begin(); it != positions.end(); ++it) + m_positions.insert(m_positions.end(), *it); +} + +// ELF 0x1B7FC0 (D1; D2 0x1B7F60, D0 0x1B8020): the list, then the base vptr. +WPAltitudePatrol::~WPAltitudePatrol() +{ +} + +// ELF 0x1B8090. The front position is reached when m_first^2 > dx^2 + dz^2 and |dy| < m_second +// (differences position - front); it is then re-inserted at the end before the front is erased +// and +4 is set. The urgency is 1 either way, 0 on a waypoint error. +// [PLATFORM] retail keeps the XZ sum in x87 extended precision and takes |dy| through SSE +// (`andnps` with the sign mask); native builds round each step to float. +float WPAltitudePatrol::getUrgency(const Vec3& position, Bot*) +{ + if (m_wayPointError) + return 0.0f; + + const float radiusSqr = m_first * m_first; + const float dx = position.x - m_positions.front().x; + const float dz = position.z - m_positions.front().z; + if (radiusSqr > dx * dx + dz * dz) + { + const float dy = std::fabs(position.y - m_positions.front().y); + if (m_second > dy) + { + m_positions.insert(m_positions.end(), m_positions.front()); + m_positions.erase(m_positions.begin()); + m_flag4 = true; + } + } + return 1.0f; +} + +// ELF 0x1B81A0: the front position (no empty check). +bool WPAltitudePatrol::getGoalPoint(Vec3& out) +{ + out = m_positions.front(); + return true; +} + +// ELF 0x1B81E0: list assignment. +void WPAltitudePatrol::getCoords(std::list& out) const +{ + out = m_positions; +} + +// ELF 0x1B8210: `flds 0x10(this)`. +float WPAltitudePatrol::getWayPointRadius() const +{ + return m_first; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudePatrol.h b/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudePatrol.h new file mode 100644 index 000000000..9533899d4 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudePatrol.h @@ -0,0 +1,46 @@ +// A flight waypoint list that patrols positions at an altitude. +// Evidence: libaidll.so 1.5.3153 (ia-32). File WPAltitudePatrol.cpp (FILE symbol; the AIBot +// directory is [INFERRED] from its neighbours); vtable 0x4B7260; constructors 0x1B7CB0 / 0x1B7E60; +// destructors 0x1B7F60 / 0x1B7FC0 / 0x1B8020; getUrgency 0x1B8090; getGoalPoint 0x1B81A0; +// getCoords 0x1B81E0; getWayPointRadius 0x1B8210; getId 0x1B82D0. Constructed only by +// AIConsole::botSetWaypoints_Patrol3d (0x3921D0, call at 0x3922B9). + +#ifndef AI_AIDLL_AI_AIBOT_WPALTITUDEPATROL_H // [INFERRED] guard style +#define AI_AIDLL_AI_AIBOT_WPALTITUDEPATROL_H + +#include + +#include "WaypointList.h" + +namespace dice { +namespace hfe { +namespace ai { + +class WPAltitudePatrol : public WaypointList +{ +public: + // ELF 0x1B7E60: base fields (+8 = -1.0f), the arguments at +0x10..+0x1C, the empty list, + // +0xC = 5, a clear and the copy. The list is taken by non-const reference (mangled `RSt4list`). + WPAltitudePatrol(float first, float second, float third, unsigned int flags, std::list& positions); + virtual ~WPAltitudePatrol(); + + virtual float getUrgency(const Vec3& position, Bot* bot); // ELF 0x1B8090 + virtual bool getGoalPoint(Vec3& out); // ELF 0x1B81A0: the first position + virtual int getId() { return 7; } // ELF 0x1B82D0 (weak) + virtual float getWayPointRadius() const; // ELF 0x1B8210 + + void getCoords(std::list& out) const; // ELF 0x1B81E0 + + /* +0x0C */ int m_int0C; // ctor 5 [UNRESOLVED] meaning + /* +0x10 */ float m_first; // getWayPointRadius; the XZ arrival radius + /* +0x14 */ float m_second; // getUrgency: the |dy| arrival tolerance + /* +0x18 */ float m_third; // BBPGotoWaypoint3d: BAPAMoveTo3d's distance argument + /* +0x1C */ unsigned int m_flags; + /* +0x20 */ std::list m_positions; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOT_WPALTITUDEPATROL_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPBeachLanding.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/WPBeachLanding.cpp new file mode 100644 index 000000000..ec62d6415 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPBeachLanding.cpp @@ -0,0 +1,95 @@ +// A boat waypoint list for beach landings. Evidence: libaidll.so 1.5.3153 (ia-32), see +// WPBeachLanding.h. + +#include "WPBeachLanding.h" + +#include "BotMain.h" +#include "../AIStrategicEntity/AILandingZone.h" +#include "../Main/AILandingZoneManager.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1B86C0, __tcf_0 0x1B8720, _GLOBAL__I 0x1B8750). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1B8370 (C1; C2 0x1B82E0): the base fields (+8 = -1.0f), the arguments, the zone by index, +// +0xC = 6, then the zone into BotMain +0xE8 through the Bot pointer. +WPBeachLanding::WPBeachLanding(int zoneIndex, float value, int map, int approachType, Bot* bot) +{ + m_map = map; + m_inside = false; + m_approachType = approachType; + m_value = value; + m_zone = AILandingZoneManager::m_instance->getAILandingZone(zoneIndex); + m_int0C = 6; + static_cast(bot)->m_ptr232 = m_zone; +} + +// ELF 0x1B8470 (C1; C2 0x1B8400): as above with the zone given. +WPBeachLanding::WPBeachLanding(AILandingZone* zone, float value, int map, int approachType, Bot* bot) +{ + m_map = map; + m_inside = false; + m_approachType = approachType; + m_zone = zone; + m_int0C = 6; + m_value = value; + static_cast(bot)->m_ptr232 = zone; +} + +void WPBeachLanding::storeLandingZone(Bot* bot, AILandingZone* zone) +{ + static_cast(bot)->m_ptr232 = zone; +} + +// ELF 0x1B8500 (D1; D2 0x1B84E0, D0 0x1B8520): the base vptr only. +WPBeachLanding::~WPBeachLanding() +{ +} + +// ELF 0x1B8560. Inside means a squared zone distance of exactly 0 (unordered is outside); outside, +// the distance is queried a second time for the store. +4 is set when inside changes. +float WPBeachLanding::getUrgency(const Vec3& position, Bot*) +{ + if (m_wayPointError) + return 0.0f; + + const bool wasInside = m_inside; + m_inside = m_zone->getDistanceSqr(position) == 0.0f; + m_distanceSqr = m_inside ? 0.0f : m_zone->getDistanceSqr(position); + m_flag4 = m_inside != wasInside; + return 1.0f; +} + +// ELF 0x1B8600: the beach position inside the zone, the approach position (10 m) outside it. +bool WPBeachLanding::getGoalPoint(Vec3& out) +{ + if (m_inside) + return m_zone->getBeachPosition(m_map, out); + return m_zone->getApproachPosition(m_map, m_approachType, out, 10.0f); +} + +// ELF 0x1B8670 +bool WPBeachLanding::insideZone() +{ + return m_inside; +} + +// ELF 0x1B8680: distance^2 >= the last squared zone distance; unordered is false. +bool WPBeachLanding::closeToZone(float distance) +{ + return distance * distance >= m_distanceSqr; +} + +// ELF 0x1B86A0: a constant 10. +float WPBeachLanding::getWayPointRadius() const +{ + return 10.0f; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPBeachLanding.h b/Code/BF2/AI/AIDLL/AI/AIBot/WPBeachLanding.h new file mode 100644 index 000000000..5d3f484fe --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPBeachLanding.h @@ -0,0 +1,57 @@ +// A boat waypoint list: approach a landing zone, then run onto its beach. +// Evidence: libaidll.so 1.5.3153 (ia-32). File WPBeachLanding.cpp (FILE symbol; the AIBot +// directory is [INFERRED] from its neighbours); vtable 0x4B72A0 (D1, D0, getUrgency, getGoalPoint, +// getId, then WaypointList's setWayPointError / getWayPointError, then getWayPointRadius). +// Constructors 0x1B82E0 / 0x1B8370 (zone index) and 0x1B8400 / 0x1B8470 (zone); destructors +// 0x1B84E0 / 0x1B8500 / 0x1B8520. No call site in the image constructs it, so the size is not +// attested; BBPGotoWaypointBoat::createPlan reads it through getId 3. + +#ifndef AI_AIDLL_AI_AIBOT_WPBEACHLANDING_H // [INFERRED] guard style +#define AI_AIDLL_AI_AIBOT_WPBEACHLANDING_H + +#include "WaypointList.h" + +namespace dice { +namespace hfe { +namespace ai { + +class AILandingZone; + +class WPBeachLanding : public WaypointList +{ +public: + // Both forms also store the zone into the bot (BotMain +0xE8). + WPBeachLanding(int zoneIndex, float value, int map, int approachType, Bot* bot); + WPBeachLanding(AILandingZone* zone, float value, int map, int approachType, Bot* bot); + virtual ~WPBeachLanding(); + + virtual float getUrgency(const Vec3& position, Bot* bot); // ELF 0x1B8560 + virtual bool getGoalPoint(Vec3& out); // ELF 0x1B8600 + virtual int getId() { return 3; } // ELF 0x1B8770 (weak) + virtual float getWayPointRadius() const; // ELF 0x1B86A0: 10 + + bool insideZone(); // ELF 0x1B8670 + bool closeToZone(float distance); // ELF 0x1B8680 + + // [CHOSEN, not recovered] packaging: the BotMain +0xE8 store both beach-landing waypoint + // lists' constructors make inline (WPMoveToBeachLanding 0x1BA42E too). It lives here because + // WPBeachLanding is BotMain's friend; [RETIRE-WHEN: wpmovetobeach-friend] BotMain.h also + // befriends WPMoveToBeachLanding, which then stores the zone itself. + static void storeLandingZone(Bot* bot, AILandingZone* zone); + + // [INFERRED] names; the stores are attested. + /* +0x0C */ int m_int0C; // ctor 6 [UNRESOLVED] meaning + /* +0x10 */ int m_map; // getBeachPosition / getApproachPosition first argument + /* +0x14 */ int m_approachType; // getApproachPosition second argument + /* +0x18 */ bool m_inside; // getUrgency: distance 0 to the zone + /* +0x1C */ float m_value; // ctor float argument; no reader in this TU + /* +0x20 */ float m_distanceSqr; // getUrgency; not initialised by the constructors + /* +0x24 */ int m_unknown24; // [UNRESOLVED] never stored or read in this TU + /* +0x28 */ AILandingZone* m_zone; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOT_WPBEACHLANDING_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPCloseTo.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/WPCloseTo.cpp new file mode 100644 index 000000000..5a528e104 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPCloseTo.cpp @@ -0,0 +1,151 @@ +// A waypoint list that closes in on one object. Evidence: libaidll.so 1.5.3153 (ia-32), see +// WPCloseTo.h. + +#include "WPCloseTo.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1B8F90, __tcf_0 0x1B8FF0, _GLOBAL__I 0x1B9020). +#include + +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../../../../Math/Mat4.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { +// Inlined in the constructor and getUrgency: without a physical plug-in the object's position, +// else the sphere's local offset rotated by the transformation (rows 0..2) plus the position. +Vec3 closeToPosition(Information* info) +{ + IPIPhysical* const physical = info->getPhysical(); + if (!physical) + return info->getPosition(); + const Mat4& m = info->getTransformation(); + const Vec3 offset = physical->getSphereLocalOffset(); + const float* const r = m.m; + Vec3 point; + point.x = r[8] * offset.z + r[0] * offset.x + r[4] * offset.y; + point.y = r[1] * offset.x + r[5] * offset.y + r[9] * offset.z; + point.z = offset.x * r[2] + offset.y * r[6] + offset.z * r[10]; + const Vec3& position = info->getPosition(); + point.x = position.x + point.x; + point.y = position.y + point.y; + point.z = position.z + point.z; + return point; +} +} // namespace + +// ELF 0x1B8780: the radius is at least 5.0f, and with a physical plug-in at least twice its +// smallest radius (x87 compare against 2r, stored as float). +WPCloseTo::WPCloseTo(unsigned int target, float radius) + : m_int12(2) + , m_target(target) + , m_radius(radius <= 5.0f ? 5.0f : radius) + , m_distanceSq(25.0f) +{ + m_flag4 = true; + m_flag5 = false; + m_wayPointError = false; + m_goal.x = 0.0f; + m_goal.y = 0.0f; + m_goal.z = 0.0f; + Information* const info = informationManager->getInformation(target); + if (!info) + return; + if (IPIPhysical* const physical = info->getPhysical()) + { + const float smallest = physical->getSmallestRadius(); + const float twice = smallest + smallest; + if (m_radius <= twice) + m_radius = twice; + } + m_goal = closeToPosition(info); +} + +WPCloseTo::~WPCloseTo() +{ +} + +// ELF 0x1B8BA0. 0 after a waypoint error, or (marking +5) when the object is gone. Otherwise the +// squared distance d from `position` to the object is kept (+0x18) and the urgency is +// min(1, d / (4 r^2)); inside r^2 the list is marked (+4) and the urgency is 0; outside, a goal +// that moved more than r (squared distances) is refreshed and the list marked. +float WPCloseTo::getUrgency(const Vec3& position, Bot*) +{ + if (m_wayPointError) + return 0.0f; + Information* const info = informationManager->getInformation(m_target); + if (!info) + { + m_flag5 = true; + return 0.0f; + } + const Vec3 point = closeToPosition(info); + const float dx = point.x - position.x; + const float dy = point.y - position.y; + const float dz = point.z - position.z; + const float distanceSq = dx * dx + dy * dy + dz * dz; + m_distanceSq = distanceSq; + const float radiusSq = m_radius * m_radius; + float urgency = distanceSq / (radiusSq * 4.0f); + if (1.0f < urgency) + urgency = 1.0f; + if (radiusSq <= distanceSq) + { + const float gx = m_goal.x - point.x; + const float gy = m_goal.y - point.y; + const float gz = m_goal.z - point.z; + if (radiusSq < gx * gx + gy * gy + gz * gz) + { + m_goal = point; + m_flag4 = true; + } + return urgency; + } + m_flag4 = true; + return 0.0f; +} + +// ELF 0x1B8F00: the goal while the object exists. +bool WPCloseTo::getGoalPoint(Vec3& out) +{ + if (!informationManager->getInformation(m_target)) + return false; + out = m_goal; + return true; +} + +// ELF 0x1B8E30. Without the object the speed stands. Without a mobile plug-in: 0 once the radius +// reaches the kept distance (+0x14 against +0x18 as stored), else the speed. With one: within +// that, at most the object's speed magnitude (IPIMobile +0x24); beyond twice the distance the +// speed stands; in between at most magnitude * 1.33 (0x49D240) * d / r. +float WPCloseTo::modifyMaxSpeed(float speed) +{ + Information* const info = informationManager->getInformation(m_target); + if (!info) + return speed; + IPIMobile* const mobile = info->getMobile(); + if (!mobile) + return m_radius < m_distanceSq ? speed : 0.0f; + float limit; + if (m_radius >= m_distanceSq) + { + limit = mobile->getSpeedMagnitude(); + } + else + { + if (m_radius < m_distanceSq + m_distanceSq) + return speed; + limit = mobile->getSpeedMagnitude() * 1.33f * m_distanceSq / m_radius; + } + return limit > speed ? speed : limit; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPCloseTo.h b/Code/BF2/AI/AIDLL/AI/AIBot/WPCloseTo.h new file mode 100644 index 000000000..7415b6856 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPCloseTo.h @@ -0,0 +1,42 @@ +// A waypoint list that closes in on one object (by information handle). Evidence: libaidll.so +// 1.5.3153 (ia-32): vtable 0x4B72E0 (D1, D0, getUrgency 0x1B8BA0, getGoalPoint 0x1B8F00, getId +// 0x1B9040 (weak, 0), WaypointList's error pair, getWayPointRadius 0x1B8F80); constructors +// 0x1B8780 / 0x1B8950; destructors 0x1B8B20 / 0x1B8B40 / 0x1B8B60; modifyMaxSpeed 0x1B8E30. + +#ifndef AI_AIDLL_AI_AIBOT_WPCLOSETO_H // [INFERRED] guard style +#define AI_AIDLL_AI_AIBOT_WPCLOSETO_H + +#include "WaypointList.h" + +namespace dice { +namespace hfe { +namespace ai { + +class WPCloseTo : public WaypointList +{ +public: + WPCloseTo(unsigned int target, float radius); // ELF 0x1B8780 + virtual ~WPCloseTo(); // ELF 0x1B8B20 + + virtual float getUrgency(const Vec3& position, Bot* bot); // ELF 0x1B8BA0 + virtual bool getGoalPoint(Vec3& out); // ELF 0x1B8F00 + virtual int getId() { return 0; } // ELF 0x1B9040 (weak) + virtual float getWayPointRadius() const { return m_radius; } // ELF 0x1B8F80: flds +0x14 + + float modifyMaxSpeed(float speed); // ELF 0x1B8E30 + unsigned int getTarget() const { return m_target; } // [INFERRED] reader of +0x10 + + // [INFERRED] names; the stores are attested (constructor 0x1B8780). + // +0x08: WaypointList::m_float8 (base constructor: -1.0f) + /* +0x0C */ unsigned int m_int12; // 2 [UNRESOLVED] (WPEmpty 1) + /* +0x10 */ unsigned int m_target; // the object's information handle + /* +0x14 */ float m_radius; // at least 5, at least twice the target's smallest radius + /* +0x18 */ float m_distanceSq; // 25.0f, then getUrgency's squared distance to the goal + /* +0x1C */ Vec3 m_goal; // the target's (sphere centre) position when last moved +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOT_WPCLOSETO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPEmpty.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/WPEmpty.cpp new file mode 100644 index 000000000..8e8641e92 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPEmpty.cpp @@ -0,0 +1,45 @@ +// The "no waypoints" list. Evidence: libaidll.so 1.5.3153 (ia-32), see WPEmpty.h. + +#include "WPEmpty.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1B9230, __tcf_0 0x1B9290, _GLOBAL__I 0x1B92C0). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1B9050. +WPEmpty::WPEmpty(const Vec3& position) + : m_int12(1) + , m_position(position) +{ + m_flag4 = true; + m_flag5 = false; + m_wayPointError = false; +} + +// ELF 0x1B9130. +WPEmpty::~WPEmpty() +{ +} + +// ELF 0x1B91B0: marks the list (+4) and follows the bot's position; urgency 0. +float WPEmpty::getUrgency(const Vec3& position, Bot*) +{ + m_flag4 = true; + m_position = position; + return 0.0f; +} + +// ELF 0x1B9200. +bool WPEmpty::getGoalPoint(Vec3& out) +{ + out = m_position; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPEmpty.h b/Code/BF2/AI/AIDLL/AI/AIBot/WPEmpty.h new file mode 100644 index 000000000..72b6a1cc2 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPEmpty.h @@ -0,0 +1,36 @@ +// The "no waypoints" list: holds one position (the bot's own at creation) and reports it as the +// goal. Evidence: libaidll.so 1.5.3153 (ia-32). Attested file AIBot/WPEmpty.cpp (FILE symbol +// beside 0x1B9230); vtable 0x4B7320 (D1, D0, getUrgency, getGoalPoint, getId; the rest are +// WaypointList's); constructors 0x1B9050 / 0x1B90C0; destructors 0x1B9130 / 0x1B9150 / 0x1B9170. +// Size 0x1C (`operator new(0x1c)` in BotMain::updateBot 0x18BF50). + +#ifndef AI_AIDLL_AI_AIBOT_WPEMPTY_H // [INFERRED] guard style +#define AI_AIDLL_AI_AIBOT_WPEMPTY_H + +#include "WaypointList.h" + +namespace dice { +namespace hfe { +namespace ai { + +class WPEmpty : public WaypointList +{ +public: + explicit WPEmpty(const Vec3& position); // ELF 0x1B9050 + virtual ~WPEmpty(); // ELF 0x1B9130 + + virtual float getUrgency(const Vec3& position, Bot* bot); // ELF 0x1B91B0 + virtual bool getGoalPoint(Vec3& out); // ELF 0x1B9200: always true + virtual int getId() { return 8; } // ELF 0x1B92E0 (weak) + + // [INFERRED] names; the stores are attested (constructor 0x1B9050). + // +0x08: WaypointList::m_float8 (base constructor: -1.0f) + /* +0x0C */ unsigned int m_int12; // 1 [UNRESOLVED] + /* +0x10 */ Vec3 m_position; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOT_WPEMPTY_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPMoveTo.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/WPMoveTo.cpp new file mode 100644 index 000000000..46d1b0255 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPMoveTo.cpp @@ -0,0 +1,203 @@ +// A walk-through waypoint list. Evidence: libaidll.so 1.5.3153 (ia-32), see WPMoveTo.h. + +#include "WPMoveTo.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1BA040, __tcf_0 0x1BA0A0, _GLOBAL__I 0x1BA0D0). +#include + +#include "../Main/AIDllFrontier.h" +#include "BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIStrategicEntity/AIStrategicArea.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1B96C0 (C1; C2 0x1B97E0). The base fields (+4 true, +5 / +6 false), then +8 = -1.0f, +// the clamp, +0x10..+0x18, the empty list, +0x20 = false, +0xC = 0, a clear, and the copy. +WPMoveTo::WPMoveTo(float radius, float stepRadius, unsigned int flags, const GoalList& goals) +{ + if (stepRadius <= 1.0f) + stepRadius = 1.0f; + m_radius = radius; + m_stepRadius = stepRadius; + m_flags = flags; + m_flag20 = false; + m_int0C = 0; + m_goals.clear(); + for (GoalList::const_iterator it = goals.begin(); it != goals.end(); ++it) + m_goals.push_back(*it); +} + +// ELF 0x1B92F0 (C1; C2 0x1B9530). As above with a clamp at 2.0; every position is paired with -1 +// and the last goal then takes `lastArea`. +WPMoveTo::WPMoveTo(float radius, float stepRadius, unsigned int flags, const std::list& positions, int lastArea) +{ + if (stepRadius <= 2.0f) + stepRadius = 2.0f; + m_radius = radius; + m_stepRadius = stepRadius; + m_flags = flags; + m_flag20 = false; + m_int0C = 0; + m_goals.clear(); + for (std::list::const_iterator it = positions.begin(); it != positions.end(); ++it) + m_goals.push_back(std::make_pair(*it, -1)); + if (!m_goals.empty()) + m_goals.back().second = lastArea; +} + +// ELF 0x1B9900: the list, then the base vptr. +WPMoveTo::~WPMoveTo() +{ +} + +// ELF 0x1B9A30 (1344 bytes). r is max(ceil(radius), the equipment's smallest radius) for the last +// goal; max(ceil(step radius), smallest radius) for an intermediate goal, or max(smallest radius, 10) +// for one without an area. d^2 is the squared distance from `position` to the front goal. +// * No goals: done (+5), 0. +// * The last goal within r: done (+5), +6 cleared, 0. Beyond r: clamp(d^2 / (1.5 r^2), 0.1, 1) times +// 2 for an area the side holds (status != 0), 0 inside an area it does not hold (d^2 = 0), else 1 +// with d^2 reduced by the side's area radius squared; without an area 1, or 0 when +6 is set. +// A set +6 moves the goal inside the area (randomizePos(side, 0.9)) and is cleared. +5 = d^2 < 1.5 r^2. +// * An intermediate goal is popped (+4 set, +6 cleared) within r, or beyond it when the bot is +// inside the goal's area, or with +6 set and no area; with +6 set outside the area it is moved +// instead. Always 1. +float WPMoveTo::getUrgency(const Vec3& position, Bot* bot) +{ + if (m_goals.empty()) + { + m_flag5 = true; + return 0.0f; + } + IPIPhysical* const physical = + informationManager->getInformation(bot->getCurrentEquipment())->getPhysical(); + const Vec3& goal = m_goals.front().first; + const float dx = goal.x - position.x; + const float dy = goal.y - position.y; + const float dz = goal.z - position.z; + float distanceSq = dz * dz + dy * dy + dx * dx; + + if (m_goals.size() == 1) + { + float radius = static_cast(std::ceil(static_cast(m_radius))); + const float smallest = physical->getSmallestRadius(); + if (radius < smallest) + radius = smallest; + const float radiusSq = radius * radius; + if (!(radiusSq <= distanceSq)) + { + m_flag5 = true; + m_wayPointError = false; + return 0.0f; + } + float factor; + AIStrategicArea* const area = + AIStrategicObjectManager::getInstance()->getStrategicArea(m_goals.front().second); + if (!area) + { + factor = m_wayPointError ? 0.0f : 1.0f; + } + else + { + const int side = bot->getSide(); + if (static_cast(area->getStatus(side)) == 0) + { + if (!area->isInside(position)) + { + // +0x98 + 4 * side: m_size[side]. + const float sideRadius = area->m_size[bot->getSide()]; + distanceSq = distanceSq - sideRadius * sideRadius; + factor = 1.0f; + } + else + { + factor = 0.0f; + distanceSq = 0.0f; + } + } + else + { + factor = 2.0f; + } + if (m_wayPointError) + { + area->randomizePos(bot->getSide(), 0.9f, m_goals.front().first); + m_wayPointError = false; + } + } + const float scaled = radiusSq * 1.5f; + float urgency = distanceSq / scaled; + m_flag5 = !(scaled <= distanceSq); + if (1.0f < urgency) + urgency = 1.0f; + if (!(0.1f <= urgency)) + urgency = 0.1f; + return urgency * factor; + } + + float radius = static_cast(std::ceil(static_cast(m_stepRadius))); + float smallest = physical->getSmallestRadius(); + if (radius < smallest) + radius = smallest; + if (m_goals.front().second == -1) + { + radius = physical->getSmallestRadius(); + if (radius <= 10.0f) + radius = 10.0f; + } + if (radius * radius <= distanceSq) + { + AIStrategicArea* const area = + AIStrategicObjectManager::getInstance()->getStrategicArea(m_goals.front().second); + if (!area) + { + if (!m_wayPointError) + return 1.0f; + } + else if (!area->isInside(position)) + { + if (!m_wayPointError) + return 1.0f; + area->randomizePos(bot->getSide(), 0.9f, m_goals.front().first); + m_wayPointError = false; + return 1.0f; + } + } + m_goals.erase(m_goals.begin()); + m_flag4 = true; + m_wayPointError = false; + return 1.0f; +} + +// ELF 0x1B9F70: the first goal's position when there is one. +bool WPMoveTo::getGoalPoint(Vec3& out) +{ + const bool any = !m_goals.empty(); + if (any) + out = m_goals.front().first; + return any; +} + +// ELF 0x1B9FB0: each goal position appended to `out`. +void WPMoveTo::getCoords(std::list& out) const +{ + for (GoalList::const_iterator it = m_goals.begin(); it != m_goals.end(); ++it) + out.push_back(it->first); +} + +// ELF 0x1BA030: `flds 0x10(this)`. +float WPMoveTo::getWayPointRadius() const +{ + return m_radius; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPMoveTo.h b/Code/BF2/AI/AIDLL/AI/AIBot/WPMoveTo.h new file mode 100644 index 000000000..72f65181d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPMoveTo.h @@ -0,0 +1,53 @@ +// A waypoint list of (position, strategic area id) goals a bot walks through in order. +// Evidence: libaidll.so 1.5.3153 (ia-32). Attested file AIBot/WPMoveTo.cpp (FILE symbol beside +// 0x1BA040); vtable 0x4B7360; constructors 0x1B92F0 / 0x1B9530 (Vec3 list + last area) and +// 0x1B96C0 / 0x1B97E0 (pair list); destructors 0x1B9900 / 0x1B9960 / 0x1B99C0; getUrgency +// 0x1B9A30; getGoalPoint 0x1B9F70; getCoords 0x1B9FB0; getWayPointRadius 0x1BA030; getId 0x1BA140. +// Size 0x24 (`operator new(0x24)` in AIStrategicArea::orderNormalBot). + +#ifndef AI_AIDLL_AI_AIBOT_WPMOVETO_H // [INFERRED] guard style +#define AI_AIDLL_AI_AIBOT_WPMOVETO_H + +#include +#include + +#include "WaypointList.h" + +namespace dice { +namespace hfe { +namespace ai { + +class WPMoveTo : public WaypointList +{ +public: + typedef std::list > GoalList; + + // ELF 0x1B96C0: the goals as given; the second distance is at least 1. + WPMoveTo(float radius, float stepRadius, unsigned int flags, const GoalList& goals); + // ELF 0x1B92F0: each position with area -1, the last one with `lastArea`; the second distance is + // at least 2. + WPMoveTo(float radius, float stepRadius, unsigned int flags, const std::list& positions, int lastArea); + virtual ~WPMoveTo(); + + virtual float getUrgency(const Vec3& position, Bot* bot); // ELF 0x1B9A30 + virtual bool getGoalPoint(Vec3& out); // ELF 0x1B9F70: the first goal + virtual int getId() { return 1; } // ELF 0x1BA140 (weak) + virtual float getWayPointRadius() const; // ELF 0x1BA030: +0x10 + + void getCoords(std::list& out) const; // ELF 0x1B9FB0: appends the positions + + // [INFERRED] names; the stores are attested. + // +0x08: WaypointList::m_float8 (base constructor: -1.0f) + /* +0x0C */ int m_int0C; // ctor 0 (WPAltitudeMoveTo writes 4) + /* +0x10 */ float m_radius; // the goal radius; getWayPointRadius + /* +0x14 */ float m_stepRadius; // the radius for intermediate goals + /* +0x18 */ unsigned int m_flags; // the third argument ([UNRESOLVED] meaning) + /* +0x1C */ GoalList m_goals; + /* +0x20 */ bool m_flag20; // ctor false +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOT_WPMOVETO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPMoveToBeachLanding.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/WPMoveToBeachLanding.cpp new file mode 100644 index 000000000..ab76ea47d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPMoveToBeachLanding.cpp @@ -0,0 +1,178 @@ +// A boat waypoint list for beach landings through waypoints. Evidence: libaidll.so 1.5.3153 +// (ia-32), see WPMoveToBeachLanding.h. + +#include "WPMoveToBeachLanding.h" + +#include + +#include "BotMain.h" +#include "WPBeachLanding.h" // storeLandingZone +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIStrategicEntity/AILandingZone.h" +#include "../Main/AILandingZoneManager.h" +#include "../AIStrategicEntity/AIStrategicArea.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1BAB80, __tcf_0 0x1BABE0, _GLOBAL__I 0x1BAC10). +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// The radius the constructors keep: the argument when above 5, else 5 (unordered gives 5). +float atLeastFive(float radius) +{ + return radius > 5.0f ? radius : 5.0f; +} + +} // anonymous namespace + +// ELF 0x1BA320 (C1; C2 0x1BA150): the base fields, the arguments, the zone by index, the +// waypoints copy-constructed, +0xC = 7, then the zone into BotMain +0xE8 through the Bot pointer. +WPMoveToBeachLanding::WPMoveToBeachLanding(int zoneIndex, float radius, int map, int approachType, + int value24, + std::list >& waypoints, Bot* bot) + : m_map(map) + , m_approachType(approachType) + , m_inside(false) + , m_radius(atLeastFive(radius)) + , m_int24(value24) + , m_zone(AILandingZoneManager::m_instance->getAILandingZone(zoneIndex)) + , m_waypoints(waypoints) +{ + m_int0C = 7; + WPBeachLanding::storeLandingZone(bot, m_zone); // BotMain +0xE8 +} + +// ELF 0x1BA560 (C1; C2 0x1BA450): as above with the zone given. +WPMoveToBeachLanding::WPMoveToBeachLanding(AILandingZone* zone, float radius, int map, + int approachType, int value24, + std::list >& waypoints, Bot* bot) + : m_map(map) + , m_approachType(approachType) + , m_inside(false) + , m_radius(atLeastFive(radius)) + , m_int24(value24) + , m_zone(zone) + , m_waypoints(waypoints) +{ + m_int0C = 7; + WPBeachLanding::storeLandingZone(bot, m_zone); // BotMain +0xE8 +} + +// ELF 0x1BA6D0 (D1; D2 0x1BA670, D0 0x1BA730): the waypoint list. +WPMoveToBeachLanding::~WPMoveToBeachLanding() +{ +} + +// ELF 0x1BA7A0. While waypoints remain, the first is dropped when reached - within the larger of +// the ceil'd radius and the bot's equipment's smallest radius (IPIPhysical +13), in XZ - or when +// the bot is inside its strategic area; dropping sets +4 and clears the error. A waypoint whose +// area does not exist is dropped only on a waypoint error; one whose area the bot is outside of +// is re-randomised within the area (0.9) on an error, which clears it. The equipment's record +// and physical plug-in are not null-tested. Without waypoints, the zone as WPBeachLanding but +// "inside" is a squared distance below 10. Always 1. +float WPMoveToBeachLanding::getUrgency(const Vec3& position, Bot* bot) +{ + if (!m_waypoints.empty()) + { + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); // +0xD8 + IPIPhysical* const physical = equipment->getPhysical(); + const float radius = static_cast(std::ceil(static_cast(m_radius))); + const float smallest = physical->getSmallestRadius(); + float reach = radius > smallest ? radius : smallest; + reach = reach * reach; + const std::pair& front = m_waypoints.front(); + const float dx = position.x - front.first.x; + const float dz = position.z - front.first.z; + if (reach > dx * dx + dz * dz) + { + m_waypoints.erase(m_waypoints.begin()); + m_flag4 = true; + m_wayPointError = false; + } + else + { + AIStrategicArea* const area = + AIStrategicObjectManager::getInstance()->getStrategicArea(front.second); + if (area) + { + if (area->isInside(position)) + { + m_waypoints.erase(m_waypoints.begin()); + m_flag4 = true; + m_wayPointError = false; + } + else if (m_wayPointError) + { + area->randomizePos(bot->getSide(), 0.9f, m_waypoints.front().first); // +0xE0 + m_wayPointError = false; + } + } + else if (m_wayPointError) + { + m_waypoints.erase(m_waypoints.begin()); + m_flag4 = true; + m_wayPointError = false; + } + } + } + if (!m_waypoints.empty()) + return 1.0f; + + const bool wasInside = m_inside; + m_inside = 10.0f > m_zone->getDistanceSqr(position); + m_flag4 = m_inside != wasInside; + m_distanceSqr = m_inside ? 0.0f : m_zone->getDistanceSqr(position); + return 1.0f; +} + +// ELF 0x1BAA20: the first waypoint while any remain; then the beach position inside the zone, +// the approach position (10 m) outside it. +bool WPMoveToBeachLanding::getGoalPoint(Vec3& out) +{ + if (!m_waypoints.empty()) + { + out = m_waypoints.front().first; + return true; + } + if (m_inside) + return m_zone->getBeachPosition(m_map, out); + return m_zone->getApproachPosition(m_map, m_approachType, out, 10.0f); +} + +// ELF 0x1BAAC0 +bool WPMoveToBeachLanding::insideZone() +{ + return m_inside; +} + +// ELF 0x1BAAD0: distance^2 >= the last squared zone distance; unordered is false. +bool WPMoveToBeachLanding::closeToZone(float distance) +{ + return distance * distance >= m_distanceSqr; +} + +// ELF 0x1BAAF0 +void WPMoveToBeachLanding::getCoords(std::list& out) const +{ + for (std::list >::const_iterator it = m_waypoints.begin(); + it != m_waypoints.end(); ++it) + out.push_back(it->first); +} + +// ELF 0x1BAB70: the constructor's radius. +float WPMoveToBeachLanding::getWayPointRadius() const +{ + return m_radius; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPMoveToBeachLanding.h b/Code/BF2/AI/AIDLL/AI/AIBot/WPMoveToBeachLanding.h new file mode 100644 index 000000000..546b14fe6 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPMoveToBeachLanding.h @@ -0,0 +1,61 @@ +// A boat waypoint list that first runs through a list of (position, strategic area) waypoints and +// then approaches a landing zone and its beach, as WPBeachLanding does. +// Evidence: libaidll.so 1.5.3153 (ia-32). File WPMoveToBeachLanding.cpp (FILE symbol; the AIBot +// directory is [INFERRED] from its neighbours); vtable 0x4B73A0 (D1, D0, getUrgency, +// getGoalPoint, getId, WaypointList's setWayPointError / getWayPointError, getWayPointRadius). +// Constructors 0x1BA150 / 0x1BA320 (zone index) and 0x1BA450 / 0x1BA560 (zone); destructors +// 0x1BA670 / 0x1BA6D0 / 0x1BA730. No call site in the image constructs it, so the size is not +// attested; getId answers 4. + +#ifndef AI_AIDLL_AI_AIBOT_WPMOVETOBEACHLANDING_H // [INFERRED] guard style +#define AI_AIDLL_AI_AIBOT_WPMOVETOBEACHLANDING_H + +#include +#include + +#include "WaypointList.h" + +namespace dice { +namespace hfe { +namespace ai { + +class AILandingZone; + +class WPMoveToBeachLanding : public WaypointList +{ +public: + // `waypoints` is copied: each a position and the index of the strategic area it lies in. The + // radius is `radius`, at least 5. Both forms also store the zone into the bot (BotMain +0xE8). + WPMoveToBeachLanding(int zoneIndex, float radius, int map, int approachType, int value24, + std::list >& waypoints, Bot* bot); + WPMoveToBeachLanding(AILandingZone* zone, float radius, int map, int approachType, int value24, + std::list >& waypoints, Bot* bot); + virtual ~WPMoveToBeachLanding(); + + virtual float getUrgency(const Vec3& position, Bot* bot); // ELF 0x1BA7A0 + virtual bool getGoalPoint(Vec3& out); // ELF 0x1BAA20 + virtual int getId() { return 4; } // ELF 0x1BAC30 (weak) + virtual float getWayPointRadius() const; // ELF 0x1BAB70 + + bool insideZone(); // ELF 0x1BAAC0 + bool closeToZone(float distance); // ELF 0x1BAAD0 + // Appends the remaining waypoint positions to `out`. + void getCoords(std::list& out) const; // ELF 0x1BAAF0 + + // [INFERRED] names; the stores are attested. + /* +0x0C */ int m_int0C; // ctor 7 [UNRESOLVED] meaning (WPBeachLanding: 6) + /* +0x10 */ int m_map; // getBeachPosition / getApproachPosition first argument + /* +0x14 */ int m_approachType; // getApproachPosition second argument + /* +0x18 */ bool m_inside; // getUrgency: squared zone distance below 10 + /* +0x1C */ float m_radius; // waypoint reach radius (ceil'd) and getWayPointRadius + /* +0x20 */ float m_distanceSqr; // getUrgency; not initialised by the constructors + /* +0x24 */ int m_int24; // ctor argument [UNRESOLVED]; no reader in this TU + /* +0x28 */ AILandingZone* m_zone; + /* +0x2C */ std::list > m_waypoints; // (position, strategic area index) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOT_WPMOVETOBEACHLANDING_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPPatrol.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/WPPatrol.cpp new file mode 100644 index 000000000..d4fa76218 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPPatrol.cpp @@ -0,0 +1,82 @@ +// A closed patrol loop. Evidence: libaidll.so 1.5.3153 (ia-32), see WPPatrol.h. + +#include "WPPatrol.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1BB370, __tcf_0 0x1BB3D0, _GLOBAL__I 0x1BB400). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1BAC40 (C2; C1 0x1BADF0). The base fields, +8 = -1.0f, the clamp, +0x10 / +0x14, the empty +// list, +0xC = 8, a clear, then each point appended. +WPPatrol::WPPatrol(float radius, unsigned int flags, std::list& points) +{ + if (radius <= 5.0f) + radius = 5.0f; + m_radius = radius; + m_flags = flags; + m_int0C = 8; + m_points.clear(); + for (std::list::iterator it = points.begin(); it != points.end(); ++it) + m_points.insert(m_points.end(), *it); +} + +// ELF 0x1BAEF0 (C2; C1 0x1BAFD0). As above, from a vector. +WPPatrol::WPPatrol(float radius, unsigned int flags, std::vector& points) +{ + if (radius <= 5.0f) + radius = 5.0f; + m_radius = radius; + m_flags = flags; + m_int0C = 8; + m_points.clear(); + for (std::vector::iterator it = points.begin(); it != points.end(); ++it) + m_points.insert(m_points.end(), *it); +} + +// ELF 0x1BB0B0 (D2; D1 0x1BB110, D0 0x1BB170): the list, then the base vptr. +WPPatrol::~WPPatrol() +{ +} + +// ELF 0x1BB1E0. The test is radius^2 > distXZSqr(position, front); the front point is re-inserted +// at the end before the front is erased. +float WPPatrol::getUrgency(const Vec3& position, Bot*) +{ + if (m_wayPointError) + return 0.0f; + const float radiusSqr = m_radius * m_radius; + if (radiusSqr > distXZSqr(position, m_points.front())) + { + m_points.insert(m_points.end(), m_points.front()); + m_points.erase(m_points.begin()); + m_flag4 = true; + } + return 1.0f; +} + +// ELF 0x1BB2F0. +bool WPPatrol::getGoalPoint(Vec3& out) +{ + out = m_points.front(); + return true; +} + +// ELF 0x1BB330: list assignment. +void WPPatrol::getCoords(std::list& out) const +{ + out = m_points; +} + +// ELF 0x1BB360. +float WPPatrol::getWayPointRadius() const +{ + return m_radius; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPPatrol.h b/Code/BF2/AI/AIDLL/AI/AIBot/WPPatrol.h new file mode 100644 index 000000000..9c870302d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPPatrol.h @@ -0,0 +1,53 @@ +// A closed patrol loop: the bot walks to the front point; once within the radius the point is moved +// to the back of the list, so the loop repeats forever. +// Evidence: libaidll.so 1.5.3153 (ia-32). Placement AIBot/WPPatrol.cpp [INFERRED] from the +// neighbouring WPMoveTo / WPMoveToBeachLanding TUs (the static-init symbol names the WPPatrol +// constructor); vtable 0x4B73E0 (D1, D0, getUrgency, getGoalPoint, getId, then WaypointList's +// setWayPointError / getWayPointError, then getWayPointRadius); constructors 0x1BAC40 / 0x1BADF0 +// (list) and 0x1BAEF0 / 0x1BAFD0 (vector); destructors 0x1BB0B0 / 0x1BB110 / 0x1BB170. +// Size 0x1C (`operator new(0x1c)` in PatrolPath::botIsAlive 0x350BF0). + +#ifndef AI_AIDLL_AI_AIBOT_WPPATROL_H // [INFERRED] guard style +#define AI_AIDLL_AI_AIBOT_WPPATROL_H + +#include +#include + +#include "WaypointList.h" + +namespace dice { +namespace hfe { +namespace ai { + +class WPPatrol : public WaypointList +{ +public: + // Both constructors clamp the radius to at least 5 and copy the points in order. + WPPatrol(float radius, unsigned int flags, std::list& points); + WPPatrol(float radius, unsigned int flags, std::vector& points); + virtual ~WPPatrol(); + + // 0 with the waypoint error set; otherwise 1, after cycling the front point to the back when + // `position` is within the radius of it (XZ plane) and marking the step (+4). + virtual float getUrgency(const Vec3& position, Bot* bot); + // The front point; always true (an empty list is not checked). + virtual bool getGoalPoint(Vec3& out); + virtual int getId() { return 2; } // ELF 0x1BB420 (weak) + virtual float getWayPointRadius() const; + + // Replaces `out` with the patrol points. + void getCoords(std::list& out) const; + + // [INFERRED] names, as in WPMoveTo; the stores are attested. + // +0x08: WaypointList::m_float8 (base constructor: -1.0f) + /* +0x0C */ int m_int0C; // ctor 8 [UNRESOLVED] meaning + /* +0x10 */ float m_radius; + /* +0x14 */ unsigned int m_flags; // the second argument (PatrolPath passes 5) [UNRESOLVED] meaning + /* +0x18 */ std::list m_points; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOT_WPPATROL_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WaypointList.h b/Code/BF2/AI/AIDLL/AI/AIBot/WaypointList.h new file mode 100644 index 000000000..123277c70 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WaypointList.h @@ -0,0 +1,54 @@ +// Abstract waypoint target a bot follows (WPMoveTo, WPEmpty, WPPatrol, ... derive from it). +// [INFERRED] Source placement; the class is inline in the ELF (weak symbols only). + +#ifndef AI_AIDLL_AI_AIBOT_WAYPOINTLIST_H // [INFERRED] guard style +#define AI_AIDLL_AI_AIBOT_WAYPOINTLIST_H + +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +class Bot; + +// vtable ELF 0x4b6f20: D1 0x1B6180 (vptr store only), D0 0x1B61A0, three pure slots (WPMoveTo +// 0x4b7360 names them getUrgency / getGoalPoint / getId), then the three accessors below. +// The base constructor is inlined into every subclass (WPEmpty::WPEmpty 0x1B9050 stores +// +4 = 1, +5 = 0, +6 = 0 before its own fields). +class WaypointList +{ +public: + WaypointList() + : m_flag4(true) + , m_flag5(false) + , m_wayPointError(false) + , m_float8(-1.0f) + { + } + virtual ~WaypointList() {} + + virtual float getUrgency(const Vec3& position, Bot* bot) = 0; // +0x08 [INFERRED] return type + virtual bool getGoalPoint(Vec3& out) = 0; // +0x0C bool: WPMoveTo 0x1B9F70 returns "not empty" + virtual int getId() = 0; // +0x10 WPMoveTo 1, WPEmpty 8 + // ELF 0x1B61E0 / 0x1B61F0: the byte at +6. + virtual void setWayPointError(bool error) { m_wayPointError = error; } // +0x14 + virtual bool getWayPointError() const { return m_wayPointError; } // +0x18 + // ELF 0x1B6200: the base radius is 0. + virtual float getWayPointRadius() const { return 0.0f; } // +0x1C + + // [UNRESOLVED] meaning of +4 and +5; SAI::updateBotPositions reads +5 inline. + /* 4 */ bool m_flag4; // base ctor: true + /* 5 */ bool m_flag5; // base ctor: false + /* 6 */ bool m_wayPointError; // base ctor: false + // Every subclass constructor stores -1.0f here before its own vptr store (the inlined base + // constructor); PatrolPath::botIsAlive stores the patrol speed. BBPGotoWaypoint3d::createPlan + // (0x27F7F6) reads it through the base pointer as the speed, the vehicle's maximum when < 0. + /* 8 */ float m_float8; // base ctor: -1.0f [INFERRED] meaning (speed override) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOT_WAYPOINTLIST_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/Aimer.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/Aimer.cpp new file mode 100644 index 000000000..328ba8c53 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/Aimer.cpp @@ -0,0 +1,487 @@ +// Ballistic aiming. Evidence: libaidll.so 1.5.3153 (ia-32), Aimer.cpp, 0x1C7120..0x1C8EA0 +// (see Aimer.h). Read from the Ghidra decompile and checked against objdump where Ghidra hides x87 +// precision (getFiringDirection's impact time is `double time + float t`, 0x1C8134..0x1C8143). + +#include "Aimer.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1C8EA0, __tcf_0 0x1C8F00, _GLOBAL__I 0x1C8F30). +#include + +#include +#include // _finite (MSVC) +#include + +#include "../../../../Core/PlatformCompat.h" // _finite elsewhere +#include "../../../../Math/Polynom.h" + +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x4B7724 (.data, file scope in Aimer.cpp): 0.95 pi, the elevation limit. dice's spelling. +static float WIERD_ANGLE_CONSTANT = 2.984513f; + +namespace { + +// [CHOSEN, not recovered] the image's inlined `x*x + y*y + z*z` sqrt (with its sqrtf retry when +// the x87 fsqrt yields NaN; the retry gives the same value). +inline float length3(float x, float y, float z) +{ + return std::sqrt(x * x + y * y + z * z); +} + +inline float timeStep() +{ + // IBFTimer slot +0xC (getTimeIncrease), narrowed to float as the image does. + return static_cast(static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease()); +} + +} // namespace + +// ELF 0x1C7120. +Aimer::Aimer() +{ + m_drag = 0.0f; + m_gravity = 0.0f; + m_speed = 1.0f; + m_nSamples = 0; + m_time = 0.0; + m_relativePos.x = 1.0f; m_relativePos.y = 0.0f; m_relativePos.z = 0.0f; + m_targetVelocity.x = 0.0f; m_targetVelocity.y = 0.0f; m_targetVelocity.z = 0.0f; + m_shooterVelocity.x = 0.0f; m_shooterVelocity.y = 0.0f; m_shooterVelocity.z = 0.0f; + m_relativeDir.x = 1.0f; m_relativeDir.y = 0.0f; m_relativeDir.z = 0.0f; + m_forward.x = 0.0f; m_forward.y = 0.0f; m_forward.z = 1.0f; + m_grenade = false; + m_angle = 666.0f; + m_flag69 = false; + m_angleStep = 0.0174533f; + // +0x04 and +0x58 are not written. +} + +// ELF 0x1C72A0. +Aimer::~Aimer() +{ +} + +// ELF 0x1C72C0. +bool Aimer::setTargetData(const Vec3& relativePos, const Vec3& targetVelocity, const Vec3& shooterVelocity, + const Mat4* transform, double time) +{ + m_nSamples = 1; + m_relativePos = relativePos; + m_relativeDir = relativePos; + const float lengthSq = m_relativeDir.x * m_relativeDir.x + m_relativeDir.y * m_relativeDir.y + + m_relativeDir.z * m_relativeDir.z; + if (std::fabs(lengthSq - 1.0f) >= 1.1920929e-07f) + { + if (std::fabs(lengthSq) < 1.1920929e-07f) + { + m_relativeDir.x = 0.0f; m_relativeDir.y = 0.0f; m_relativeDir.z = 0.0f; + } + else + { + const float inv = 1.0f / std::sqrt(lengthSq); + m_relativeDir.x *= inv; m_relativeDir.y *= inv; m_relativeDir.z *= inv; + } + } + m_targetVelocity = targetVelocity; + m_shooterVelocity = shooterVelocity; + m_forward.x = 0.0f; m_forward.y = 0.0f; m_forward.z = 1.0f; + m_time = time; + if (transform) + { + // (0, 0, 1) rotated by the transform's upper 3x3 (row vector times matrix). + const float* m = transform->m; + const float fx = m_forward.x, fy = m_forward.y, fz = m_forward.z; + m_forward.x = fx * m[0] + fy * m[4] + fz * m[8]; + m_forward.y = fx * m[1] + fy * m[5] + fz * m[9]; + m_forward.z = fx * m[2] + fy * m[6] + fz * m[10]; + } + return true; +} + +// ELF 0x1C74C0. The squared-speed drag applies when the INITIAL speed is above 200. +float Aimer::getImpactTime(float distance, float speed) +{ + const float dt = timeStep(); + float time = 0.0f; + float v = speed; + while (distance > 0.0f) + { + float dragTerm = v; + if (speed > 200.0f) + dragTerm = v * v; + float next = v - dragTerm * m_drag * dt; + if (next < 0.0f) + next = 0.0f; + const float step = (v + next) * 0.5f * dt; + if (step <= 0.0f || 1000.0f * step < distance) + return 1000.0f; + time += (distance < step) ? (distance / step) * dt : dt; + distance -= step; + v = next; + } + return time; +} + +// ELF 0x1C75D0. Trapezoidal integration in timer steps; the drag is linear in the velocity up to +// an initial speed of 200 and quadratic (current |v|) above. +void Aimer::getPredictedImpactPosition(Vec3 velocity, float time, Vec3& out) const +{ + const float speed = length3(velocity.x, velocity.y, velocity.z); + out.x = 0.0f; out.y = 0.0f; out.z = 0.0f; + if (speed == 0.0f) + return; + float dt = timeStep(); + for (; time > 0.0f; time -= dt) + { + if (time < dt) + dt = time; + float dx = 0.0f, dy = 0.0f, dz = 0.0f; + if (m_drag != 0.0f) + { + if (speed <= 200.0f) + { + dx = velocity.x * m_drag; dy = velocity.y * m_drag; dz = velocity.z * m_drag; + } + else + { + const float v = length3(velocity.x, velocity.y, velocity.z); + dx = velocity.x * v * m_drag; dy = velocity.y * v * m_drag; dz = v * velocity.z * m_drag; + } + dx *= dt; dy *= dt; dz *= dt; + } + const float nx = (velocity.x - dx) + dt * 0.0f; + const float ny = (velocity.y - dy) + m_gravity * dt; + const float nz = (velocity.z - dz) + dt * 0.0f; + out.x = (velocity.x + nx) * 0.5f * dt + out.x; + out.y = (velocity.y + ny) * 0.5f * dt + out.y; + out.z = (velocity.z + nz) * 0.5f * dt + out.z; + velocity.x = nx; velocity.y = ny; velocity.z = nz; + } +} + +// ELF 0x1C7970. Drag-free ballistic elevation: the larger root of the trajectory equation. +bool Aimer::getStaticFiringDirection(Vec3& direction, Vec3& target) const +{ + target = m_relativePos; + const float horizontal = std::sqrt(m_relativePos.x * m_relativePos.x + m_relativePos.z * m_relativePos.z); + const float g = -m_gravity; + const float speedSq = m_speed * m_speed; + const float b = -horizontal; + const float a = (horizontal * horizontal * g) / (speedSq + speedSq); + const float disc = b * b - a * 4.0f * (a + m_relativePos.y); + if (disc < 0.0f) + return false; + const float root = std::sqrt(disc); + const float first = std::atan((root - b) / (a + a)); + float angle = std::atan((-b - root) / (a + a)); + if (angle <= first) + angle = first; + const float c = std::cos(angle); + const float s = std::sin(angle); + direction.x = m_relativePos.x * (c / horizontal); + direction.y = s; + direction.z = (c / horizontal) * m_relativePos.z; + return true; +} + +// ELF 0x1C7B80. +bool Aimer::getTurnPointForGrenade(const Vec3& direction, Vec3& point, float& time) const +{ + const float up = direction.y; + if (up > 0.0f) + { + const float t = (up * m_speed) / -m_gravity; + time = t; + point.x = direction.x * t * m_speed; + point.z = direction.z * t * m_speed; + point.y = up * m_speed * 0.5f * t; + } + return up > 0.0f; +} + +// ELF 0x1C7C40. `accuracy` sets the iteration count (accuracy * 8 + 2); `highArc` starts from +// 3/8 pi (or halfway to 0.48 pi from the previous angle) and steps downwards. A zero speed (no +// projectile) aims 20 m above the target. The step (+0x64) is kept between calls; a search that +// did not bracket the target doubles it (at most 0.017) and fails once it is that large. +bool Aimer::getFiringDirection(double time, float accuracy, bool highArc, Vec3& direction, Vec3& target, + double* impactTime) +{ + const bool noSpeed = m_speed == 0.0f; + float relY = m_relativePos.y; + if (noSpeed) + relY += 20.0f; + const float distance = length3(m_relativePos.x, relY, m_relativePos.z); + const float closing = (m_speed - (m_targetVelocity.y * m_relativeDir.y + m_targetVelocity.x * m_relativeDir.x + + m_targetVelocity.z * m_relativeDir.z)) + + m_relativeDir.x * m_shooterVelocity.x + m_relativeDir.y * m_shooterVelocity.y + + m_relativeDir.z * m_shooterVelocity.z; + if (closing < 1.0f) + return false; + const float firstEstimate = distance / closing; + if (firstEstimate < 0.0f) + return false; + double impactAt = time + firstEstimate; + getPredictedTargetPosition(impactAt, target); + float horizontal = std::sqrt(target.z * target.z + target.x * target.x); + if (horizontal == 0.0f) + return false; + float height = target.y; + if (noSpeed) + height += 20.0f; + + float angle; + if (!highArc || m_angle >= 0.7853982f) + { + if (!noSpeed) + { + angle = m_angle; + if (angle != 666.0f) + goto haveAngle; + } + angle = std::atan2(height, horizontal); + } + else + { + angle = 1.1780972f; + } +haveAngle: + { + const float step = m_angleStep; + const float sign = step > 0.0f ? 1.0f : (step >= 0.0f ? 0.0f : -1.0f); + float magnitude = std::fabs(step); + if (magnitude < 0.0001f) + magnitude = 0.0001f; + m_angleStep = magnitude * sign; + } + if (highArc && !noSpeed) + { + angle = (angle + 1.5079645f) * 0.5f; + if (m_angleStep > 0.0f) + m_angleStep = -m_angleStep; + } + + bool converged = false; + int direction0 = 0; // first step direction: +1 up, -1 down + const float drag = m_drag; + const unsigned int iterations = static_cast(accuracy * 8.0f + 2.0f); + unsigned int iteration = 0; + unsigned int convergedCount = 0; + while (convergedCount < iterations) + { + // horizontal unit direction to the predicted target + float hx = target.x, hy = 0.0f, hz = target.z; + const float hSq = hx * hx + 0.0f + hz * hz; + if (std::fabs(hSq - 1.0f) >= 1.1920929e-07f) + { + if (std::fabs(hSq) < 1.1920929e-07f) + { + hx = 0.0f; hz = 0.0f; + } + else + { + const float inv = 1.0f / std::sqrt(hSq); + hy = inv * 0.0f; hx = target.x * inv; hz = inv * target.z; + } + } + float horizontalSpeed = m_shooterVelocity.z * hz + m_shooterVelocity.x * hx + m_shooterVelocity.y * hy + + std::cos(angle) * m_speed; + float verticalSpeed = std::sin(angle) * m_speed + m_shooterVelocity.y; + if (horizontalSpeed <= 0.1f) + return false; + float t = drag != 0.0f ? getImpactTime(horizontal, horizontalSpeed) : horizontal / horizontalSpeed; + if (t > 60.0f) + { + angle = std::atan2(height, horizontal); + m_angle = angle; + horizontalSpeed = m_shooterVelocity.z * hz + m_shooterVelocity.x * hx + m_shooterVelocity.y * hy + + std::cos(angle) * m_speed; + verticalSpeed = std::sin(angle) * m_speed + m_shooterVelocity.y; + getPredictedTargetPosition(time + firstEstimate, target); + const float h = std::sqrt(target.z * target.z + target.x * target.x); + t = drag != 0.0f ? getImpactTime(h, horizontalSpeed) : h / horizontalSpeed; + } + if (t > 100.0f) + return false; + Vec3 velocity; + velocity.x = horizontalSpeed; velocity.y = verticalSpeed; velocity.z = 0.0f; + Vec3 impact; + impact.x = 0.0f; impact.y = 0.0f; impact.z = 0.0f; + getPredictedImpactPosition(velocity, t, impact); + m_verticalExtreme = t * 0.5f; + impactAt = time + t; + getPredictedTargetPosition(impactAt, target); + horizontal = std::sqrt(target.z * target.z + target.x * target.x); + height = target.y; + if (noSpeed) + height += 20.0f; + if (m_grenade && !m_flag69) + height -= 1.3f; + if (!_finite(static_cast(horizontal)) || !_finite(static_cast(height))) + return false; + if (noSpeed) + { + converged = true; + break; + } + if (iteration == iterations - 1) + break; + if (height <= impact.y) + { + if (angle <= -WIERD_ANGLE_CONSTANT) + return false; + if (direction0 == 0) + direction0 = -1; + else if (direction0 > 0) + converged = true; + if (converged) + m_angleStep *= 0.5f; + const float next = angle - m_angleStep; + angle = -WIERD_ANGLE_CONSTANT; + if (-WIERD_ANGLE_CONSTANT <= next) + angle = next; + } + else + { + if (WIERD_ANGLE_CONSTANT <= angle) + return false; + if (direction0 == 0) + direction0 = 1; + else if (direction0 < 0) + converged = true; + if (converged) + m_angleStep *= 0.5f; + angle += m_angleStep; + if (WIERD_ANGLE_CONSTANT < angle) + angle = WIERD_ANGLE_CONSTANT; + } + ++iteration; + if (iteration > 0x400) + break; + if (converged) + ++convergedCount; + } + m_angle = angle; + if (!converged) + { + const float step = m_angleStep; + float doubled = step + step; + if (0.017f < step + step) + doubled = 0.017f; + m_angleStep = doubled; + if (std::fabs(step) >= 0.017f) + return false; + } + const float c = std::cos(angle) / horizontal; + direction.x = target.x * c; + direction.y = std::sin(angle); + direction.z = c * target.z; + const float len = length3(direction.x, direction.y, direction.z); + if (len < 0.95f) + return false; + const float inv = 1.0f / len; + direction.x *= inv; direction.y *= inv; direction.z = inv * direction.z; + if (impactTime) + *impactTime = impactAt; + return true; +} + +// ELF 0x1C8770. A grenade uses its fixed fuse time; a grenade without +0x69 aims 10% short. +void Aimer::getPredictedTargetPosition(double time, Vec3& out) const +{ + static float grenadeExplosionTime = 2.8f; // ELF 0x4B7728 (.data) + float dt = static_cast(time - m_time); + if (m_grenade) + dt = grenadeExplosionTime; + out.x = m_relativePos.x + m_targetVelocity.x * dt; + out.y = m_relativePos.y + m_targetVelocity.y * dt; + out.z = dt * m_targetVelocity.z + m_relativePos.z; + if (m_grenade && !m_flag69) + { + out.x -= m_relativePos.x * 0.1f; + out.y -= m_relativePos.y * 0.1f; + out.z -= m_relativePos.z * 0.1f; + } +} + +// ELF 0x1C8850. +bool Aimer::getImpactPosition(Vec3& out, const Vec3& direction, float time) const +{ + if (time > 100.0f) // 0x1C887A jbe: a NaN time integrates and returns true (0x1C88ED) + return false; + Vec3 velocity; + velocity.x = direction.x * m_speed + m_shooterVelocity.x; + velocity.y = direction.y * m_speed + m_shooterVelocity.y; + velocity.z = m_speed * direction.z + m_shooterVelocity.z; + getPredictedImpactPosition(velocity, time, out); + return true; +} + +// ELF 0x1C8900. Roots of a cubic in t built from the relative motion (the coefficients as the +// image computes them), then the root in [0, 100] whose impact lies closest to the target. +bool Aimer::getNearestImpactPoint(const Vec3& direction, Vec3& out, double& time) const +{ + std::vector roots; + const float vx = direction.x * m_speed + m_shooterVelocity.x; + const float vy = direction.y * m_speed + m_shooterVelocity.y; + const float vz = direction.z * m_speed + m_shooterVelocity.z; + const float k = 1.0f / (1.0f - m_drag); + const float ay = (vy * m_drag + m_gravity) * k; + const float ax = (vx * m_drag + 0.0f) * k; + const float az = k * (vz * m_drag + 0.0f); + const float rx = vx - m_targetVelocity.x; + const float ry = vy - m_targetVelocity.y; + const float rz = vz - m_targetVelocity.z; + const float c0 = -(rz * m_relativePos.z + m_relativePos.y * ry + m_relativePos.x * rx); + const float c1 = (rz * rz + rx * rx + ry * ry) + - (m_relativePos.x * ax + m_relativePos.y * ay + m_relativePos.z * az); + Polynom polynom(4); + polynom[0] = c0 + c0; + polynom[1] = c1 + c1; + polynom[2] = (rz * az + rx * ax + ry * ay) * 3.0f; + polynom[3] = az * az + ax * ax + ay * ay; + polynom.findRoots(roots); + if (roots.empty()) + return false; + float best = 3.4028235e+38f; + bool found = false; + for (unsigned int i = 0; i < roots.size(); ++i) + { + const float r = roots[i]; + if (0.0f <= r && r <= 100.0f) + { + Vec3 impact; + impact.x = 0.0f; impact.y = 0.0f; impact.z = 0.0f; + getImpactPosition(impact, direction, r); + const float t = roots[i]; + const float px = m_targetVelocity.x * t + m_relativePos.x; + const float py = m_targetVelocity.y * t + m_relativePos.y; + const float pz = t * m_targetVelocity.z + m_relativePos.z; + const float dx = px - impact.x, dy = py - impact.y, dz = pz - impact.z; + const float d2 = dx * dx + dy * dy + dz * dz; + if (d2 < best) + { + time = t; + out = impact; + found = true; + best = d2; + } + } + } + return found; +} + +// ELF 0x1C8E90. +double Aimer::getVerticalExtreme() const +{ + return m_verticalExtreme; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/Aimer.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/Aimer.h new file mode 100644 index 000000000..f4884e078 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/Aimer.h @@ -0,0 +1,78 @@ +// Ballistic aiming for one weapon at one target: given the shooter-relative target state and the +// projectile's speed, drag and gravity, finds the firing direction by iterating the elevation. +// Evidence: libaidll.so 1.5.3153 (ia-32). FILE symbol Aimer.cpp beside +// 0x1C8EA0, after CommunicationAgent.cpp; the directory is AIDLL_r.dll's __FILE__ +// "Code\BF2\AI\AIDLL\AI\AIBotActionPlan\Aimer.cpp" (the tree had inferred AIBot/); constructors 0x1C7120 / 0x1C71E0, destructors +// 0x1C72A0 / 0x1C72B0 (empty, not virtual). sizeof 0x6C: BAPAAimAt embeds it at +0xA4 and its next +// member is at +0x110 (BAPAAimAt::BAPAAimAt 0x1CD5E0). +// +// The fields are public: the aim actions write the projectile parameters in place before +// setTargetData (BAPAAimAtObject::getAimVec 0x1CEA00: +0 = drag, +4 = 1 / drag when the drag is +// not 0, +0xC = speed, +8 = physics gravity * the weapon's gravity modifier). Names are +// [INFERRED] from those uses unless noted. + +#ifndef AI_AIDLL_AI_AIBOT_AIMER_H // [INFERRED] guard style +#define AI_AIDLL_AI_AIBOT_AIMER_H + +#include "../../../../Math/Vec3.h" +#include "../../../../Math/Mat4.h" + +namespace dice { +namespace hfe { +namespace ai { + +class Aimer +{ +public: + Aimer(); // ELF 0x1C7120 + ~Aimer(); // ELF 0x1C72A0 (empty) + + // ELF 0x1C72C0. relativePos = target - shooter, targetVelocity, shooterVelocity, the shooter's + // transform (may be 0) and the time the data was sampled. Always returns true. + bool setTargetData(const Vec3& relativePos, const Vec3& targetVelocity, const Vec3& shooterVelocity, + const Mat4* transform, double time); + // ELF 0x1C74C0: time a projectile fired at `speed` needs to cover `distance` with drag. + float getImpactTime(float distance, float speed); + // ELF 0x1C75D0: integrates the projectile (drag, gravity) for `time`; `out` is the displacement. + void getPredictedImpactPosition(Vec3 velocity, float time, Vec3& out) const; + // ELF 0x1C7970: the analytic (drag-free) elevation for a static target. + bool getStaticFiringDirection(Vec3& direction, Vec3& target) const; + // ELF 0x1C7B80: apex of a throw in `direction`; false when the throw does not rise. + bool getTurnPointForGrenade(const Vec3& direction, Vec3& point, float& time) const; + // ELF 0x1C7C40: iterates the elevation until the trajectory meets the predicted target. + bool getFiringDirection(double time, float accuracy, bool highArc, Vec3& direction, Vec3& target, + double* impactTime); + // ELF 0x1C8770: the target relative position at `time`. + void getPredictedTargetPosition(double time, Vec3& out) const; + // ELF 0x1C8850: where a shot in `direction` is after `time` (false beyond 100 s). + bool getImpactPosition(Vec3& out, const Vec3& direction, float time) const; + // ELF 0x1C8900: closest approach of a shot in `direction` to the moving target. + bool getNearestImpactPoint(const Vec3& direction, Vec3& out, double& time) const; + // ELF 0x1C8E90: +0x58. + double getVerticalExtreme() const; + + /* +0x00 */ float m_drag; // ctor 0 + /* +0x04 */ float m_inverseDrag; // 1 / drag, written by the aim actions only + /* +0x08 */ float m_gravity; // ctor 0; y acceleration + /* +0x0C */ float m_speed; // ctor 1.0f; projectile speed (0 = no projectile) + /* +0x10 */ double m_time; // setTargetData's time + /* +0x18 */ Vec3 m_relativePos; // ctor (1, 0, 0) + /* +0x24 */ Vec3 m_relativeDir; // normalised m_relativePos; ctor (1, 0, 0) + /* +0x30 */ Vec3 m_targetVelocity; + /* +0x3C */ Vec3 m_shooterVelocity; + /* +0x48 */ Vec3 m_forward; // transform * (0, 0, 1); ctor (0, 0, 1) + /* +0x54 */ int m_nSamples; // ctor 0, setTargetData 1 // name: AIDLL_r asserts 0x101FE960, 0x101FFC20 (+0x54) + /* +0x58 */ double m_verticalExtreme; // half the last impact time (getFiringDirection) + /* +0x60 */ float m_angle; // last elevation; ctor 666.0f = none yet + /* +0x64 */ float m_angleStep; // ctor 0.0174533f (one degree) + /* +0x68 */ bool m_grenade; // ctor false; fixed fuse time in the prediction + /* +0x69 */ bool m_flag69; // [UNRESOLVED] name; ctor false; with m_grenade + // unset, the grenade aim point is pulled in + /* +0x6A */ char m_pad6A[2]; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOT_AIMER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt.cpp new file mode 100644 index 000000000..6f00113d8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt.cpp @@ -0,0 +1,99 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1CDA60 (__tcf_0 0x1CDAC0, _GLOBAL__I 0x1CDAF0): 's Init object only. +#include + +#include "BAPAAimAt.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/BotSubObjects.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1CD6E0 (C1; C2 0x1CD600). Vec3 members zeroed, the Aimer default-constructed, the ring +// cleared; +0x80..+0xA0 and +0x140/+0x144 are left alone. +BAPAAimAt::BAPAAimAt() +{ + m_offset.x = m_offset.y = m_offset.z = 0.0f; + for (int i = 0; i < 4; ++i) + m_vec20[i].x = m_vec20[i].y = m_vec20[i].z = 0.0f; + for (int i = 0; i < 4; ++i) + m_vec50[i].x = m_vec50[i].y = m_vec50[i].z = 0.0f; + m_pitchIndex = 0; + m_int148 = 0; + m_overrideValid = 0; + m_overrideAim = 0; + m_lastYawError = 0.0f; + for (int i = 0; i < 10; ++i) + m_pitchErrors[i] = 0.0f; +} + +// ELF 0x1CD8E0 (C1; C2 0x1CD7E0) +BAPAAimAt::BAPAAimAt(BAPVariable* overrideValid, BAPVariable* overrideAim) +{ + m_offset.x = m_offset.y = m_offset.z = 0.0f; + for (int i = 0; i < 4; ++i) + m_vec20[i].x = m_vec20[i].y = m_vec20[i].z = 0.0f; + for (int i = 0; i < 4; ++i) + m_vec50[i].x = m_vec50[i].y = m_vec50[i].z = 0.0f; + m_pitchIndex = 0; + m_lastYawError = 0.0f; + m_int148 = 0; + m_overrideValid = overrideValid; + m_overrideAim = overrideAim; + for (int i = 0; i < 10; ++i) + m_pitchErrors[i] = 0.0f; +} + +// ELF 0x1CDB40 (D1; D0 0x1CDBA0): the Aimer and the base only; the end condition belongs to the +// subclasses. +BAPAAimAt::~BAPAAimAt() +{ +} + +// ELF 0x1CD5C0: never executed directly (the plan interpreter's entry does the aiming). +bool BAPAAimAt::execute(Bot*, bool& ok, bool& done) +{ + ok = false; + done = true; + return false; +} + +// ELF 0x1CDB20 +BAPStatementType BAPAAimAt::getId() const +{ + return BAPSTAimAt; // 6 +} + +// ELF 0x1CDB30 +bool BAPAAimAt::hasDefault() +{ + return false; +} + +// ELF 0x1CD9E0: mean of the ten ring entries (x87 sum, then * 0.1). +float BAPAAimAt::getAveragePitchAngle() +{ + double sum = 0.0; + for (int i = 0; i < 10; ++i) + sum += m_pitchErrors[i]; + return static_cast(sum * static_cast(0.1f)); // fmuls: the float constant +} + +// ELF 0x1CDA20: `mov 0xb4(bot)` = BotMain::m_fireCorrection; zeroes its +0x2C Vec3 and returns it +// (`lea 0x2c(%edx), %eax`). The aim actions add it to the relative target position and subtract +// it from the prediction. +Vec3& BAPAAimAt::correctAim(Bot* bot) +{ + Vec3& correction = static_cast(bot)->getFireCorrection()->m_vec44; + correction.x = 0.0f; + correction.y = 0.0f; + correction.z = 0.0f; + return correction; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt.h new file mode 100644 index 000000000..bcd7efe45 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt.h @@ -0,0 +1,73 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMAT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMAT_H + +#include "../../../../Math/Vec3.h" +#include "BAPAction.h" +#include "BAPTypes.h" +#include "BAPVariable.h" +#include "Aimer.h" + +namespace dice { +namespace hfe { + +struct Mat4; +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B7780 (17 words), package C-actions. +// Layout from the constructors 0x1CD6E0 / 0x1CD8E0 and the subclasses (BAPAAimAtObject 0x1CE650, +// BAPAAimAtPoint 0x1CFE90); sizeof 0x154. Fields are public: B's EntryMouseTurretAimAt (0x2B9700) +// reads/writes +0xA0, +0x110, +0x114 and +0x13C inline. +class BAPAAimAt : public BAPAction +{ +public: + BAPAAimAt(); // 0x1CD6E0 + BAPAAimAt(BAPVariable*, BAPVariable*); // 0x1CD8E0 + virtual ~BAPAAimAt(); // 0x1CDB40 + + virtual bool execute(Bot*, bool&, bool&); // 0x1CD5C0, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1CDB20, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1CDB30, slot +0x14; from the base declaration + virtual int getAimAtType() = 0; // no body, slot +0x20; Object 1, Point 0 + virtual bool getAimVec(const Mat4&, const Vec3&, Vec3&, float, float, float, float, bool, Bot*) = 0; // no body, slot +0x24 + virtual bool getVectorToTarget(const Vec3&, Vec3&) const = 0; // no body, slot +0x28; ELF bool (EntryMouseTurretAimAt 0x2B9985 tests al) + virtual const Mat4* getAimerTransform() const = 0; // no body, slot +0x2C; `lea 0x174(this)` + virtual bool isAimingValid() const = 0; // no body, slot +0x30 + virtual bool getLastAimVec(Vec3&) const = 0; // no body, slot +0x34 + virtual bool getPredictedPosition(Vec3&) const = 0; // no body, slot +0x38 + virtual bool getImpactTime(double&) const = 0; // no body, slot +0x3C + virtual bool getImpactPosition(Vec3&, double) const = 0; // no body, slot +0x40; Aimer::getImpactPosition's bool + + float getAveragePitchAngle(); // 0x1CD9E0 + Vec3& correctAim(Bot*); // 0x1CDA20: zeroes and returns FireCorrectionData +0x2C + + /* +0x14 */ Vec3 m_offset; // = 0; the subclasses store their aim offset + /* +0x20 */ Vec3 m_vec20[4]; // = 0; [UNRESOLVED] not read by C's bodies + /* +0x50 */ Vec3 m_vec50[4]; // = 0; [UNRESOLVED] not read by C's bodies + /* +0x80 */ char m_gap80[0x18]; // [UNRESOLVED] not written by any constructor + /* +0x98 */ double m_double98; // subclasses: -5e9; [UNRESOLVED] not read by C's bodies + /* +0xA0 */ BAPCondition* m_endCondition; // owned by the subclasses (their destructors delete it) + /* +0xA4 */ Aimer m_aimer; + /* +0x110 */ float m_lastYawError; // = 0; EntryMouseTurretAimAt writes pi when idle + /* +0x114 */ float m_pitchErrors[10]; // = 0; ring, getAveragePitchAngle averages it + /* +0x13C */ int m_pitchIndex; // = 0; ring index + /* +0x140 */ int m_int140; // subclasses: 0; [UNRESOLVED] + /* +0x144 */ int m_unwritten144; // [UNRESOLVED] not written + /* +0x148 */ int m_int148; // = 0; [UNRESOLVED] + /* +0x14C */ BAPVariable* m_overrideValid; // with m_overrideAim: BAPAAimAtObject::getAimVec takes them + /* +0x150 */ BAPVariable* m_overrideAim; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMAT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt3d.cpp new file mode 100644 index 000000000..b4be9a034 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt3d.cpp @@ -0,0 +1,147 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. + +// static init: ELF 0x1CE1D0 (__tcf_0 0x1CE230, _GLOBAL__I 0x1CE260): 's Init object only. +#include + +#include "BAPAAimAt3d.h" + +#include "BAPActionInline.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// The weapon transform's third and fourth rows (+0xEC forward, +0xFC position), passed by address. +// [CHOSEN, not recovered] spelling of the image's `this + 0xEC` / `this + 0xFC`. +const Vec3& forwardOf(const Mat4& transform) +{ + return *reinterpret_cast(&transform.m[8]); +} + +const Vec3& positionOf(const Mat4& transform) +{ + return *reinterpret_cast(&transform.m[12]); +} + +void addTo(Vec3& v, const Vec3& add) +{ + v.x = add.x + v.x; + v.y = add.y + v.y; + v.z = add.z + v.z; +} + +} // namespace + +// ELF 0x1CDE70 (C1; C2 0x1CDC90). m_condition, m_impactTime and the subclass members are left +// to the subclass constructors, as compiled. +BAPAAimAt3d::BAPAAimAt3d() +{ + m_offset = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_vec24 = bapinline::vec3(1.0f, 0.0f, 0.0f); + m_vec30 = bapinline::vec3(0.0f, 0.0f, 1.0f); + m_vec3C = bapinline::vec3(0.0f, 1.0f, 0.0f); + for (int i = 0; i < 4; ++i) + m_vecs48[i] = bapinline::vec3(0.0f, 0.0f, 0.0f); + for (int i = 0; i < 4; ++i) + m_vecs78[i] = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_vecA8 = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_lastAimVec = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_predictedPosition = bapinline::vec3(0.0f, 0.0f, 0.0f); + for (int i = 0; i < 16; ++i) + m_aimerTransform.m[i] = 0.0f; + m_aimerTransform.m[0] = m_aimerTransform.m[5] = m_aimerTransform.m[10] = m_aimerTransform.m[15] = 1.0f; + m_aimVecValid = false; + m_int1C4 = 0; + for (int i = 0; i < 4; ++i) + m_floats1AC[i] = 0.0f; + m_vec1C8 = bapinline::vec3(0.0f, 0.0f, 1.0f); +} + +// ELF 0x1CE360 (weak; D0 0x1CE3C0): the Aimer member, then BAPStatement's destructor. +BAPAAimAt3d::~BAPAAimAt3d() +{ +} + +// ELF 0x1CDC70. Only an interpreter entry (EntryHeliAimAt, ...) can execute an aim: on its own +// the statement fails at once. +bool BAPAAimAt3d::execute(Bot*, bool& ok, bool& finished) +{ + ok = false; + finished = true; + return false; +} + +// ELF 0x1CE280 (weak) +BAPStatementType BAPAAimAt3d::getId() const +{ + return BAPSTAimAt; +} + +// ELF 0x1CE290 (weak) +bool BAPAAimAt3d::hasDefault() +{ + return false; +} + +// ELF 0x1CE2A0 (weak) +const Mat4& BAPAAimAt3d::getAimerTransform() const +{ + return m_aimerTransform; +} + +// ELF 0x1CE2B0 (weak) +bool BAPAAimAt3d::isAimVecValid() const +{ + return m_aimVecValid; +} + +// ELF 0x1CE2C0 (weak) +bool BAPAAimAt3d::getLastAimVec(Vec3& aimVec) +{ + aimVec = m_lastAimVec; + return m_aimVecValid; +} + +// ELF 0x1CE300 (weak) +bool BAPAAimAt3d::getPredictedPosition(Vec3& position) const +{ + position = m_predictedPosition; + return m_aimVecValid; +} + +// ELF 0x1CE340 (weak) +bool BAPAAimAt3d::getImpactTime(double& time) const +{ + time = m_impactTime; + return m_aimVecValid; +} + +// ELF 0x1CE050. The impact point `time` seconds after firing along the weapon's forward axis, in +// world space. +bool BAPAAimAt3d::getImpactPosition(Vec3& position, double time) const +{ + const bool result = m_aimer.getImpactPosition(position, forwardOf(m_aimerTransform), static_cast(time)); + addTo(position, positionOf(m_aimerTransform)); + return result; +} + +// ELF 0x1CE0D0. The point of the forward-axis trajectory nearest the target, in world space. +bool BAPAAimAt3d::getNearestImpactPosition(Vec3& position, double& time) const +{ + const bool result = m_aimer.getNearestImpactPoint(forwardOf(m_aimerTransform), position, time); + addTo(position, positionOf(m_aimerTransform)); + return result; +} + +// ELF 0x1CE150. The target's predicted position `time` seconds from now, in world space. +void BAPAAimAt3d::getPredictedPosition(double time, Vec3& position) const +{ + m_aimer.getPredictedTargetPosition(bapinline::gameTime() + time, position); + addTo(position, positionOf(m_aimerTransform)); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt3d.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt3d.h new file mode 100644 index 000000000..73bbbb5fc --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt3d.h @@ -0,0 +1,88 @@ +// Base of the 3d aim actions (aircraft and helicopter weapons): the plan statement the vehicle aim +// entries (EntryHeliAimAt, ...) execute. It keeps the aimer's ballistic state for the precision +// conditions (BAPCConPrecision3d, BAPCConBombPrecision3d). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMAT3D_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMAT3D_H + +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" +#include "Aimer.h" +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B7800 (19 words), package G-vehicles. Object size 0x1D4 (the subclasses add from +// +0x1D4). Member names are [INFERRED]; members only the entries use are [UNRESOLVED] by meaning +// and carry their constructed values. +class BAPAAimAt3d : public BAPAction +{ +public: + BAPAAimAt3d(); // 0x1CDE70 + virtual ~BAPAAimAt3d(); // 0x1CE360 (weak) + + virtual bool execute(Bot*, bool&, bool&); // 0x1CDC70, slot +0x00 + virtual BAPStatementType getId() const; // 0x1CE280, slot +0x10 (weak): AimAt + virtual bool hasDefault(); // 0x1CE290, slot +0x14 (weak): false + virtual int getAimAtType() = 0; // no body, slot +0x20: 1 object, 0 point + // Target position minus `from`; false when the target has no information. + virtual bool getVectorToTarget(const Vec3& from, Vec3& vector) const = 0; // no body, slot +0x24 + // Feeds the aimer with the weapon transform and velocities and solves the firing direction + // (Aimer::getFiringDirection); returns, and stores, whether it found one. + virtual bool getAimVec(const Mat4& transform, const Vec3& shooterVelocity, Vec3& direction, float accuracy, + float drag, float speed, float gravityScale, bool highArc) = 0; // no body, slot +0x28 + // The return types of the slots below follow their bodies (this + 0xCC, the +0x114 flag, the + // Aimer results); the skeleton's int/void were wrong. + virtual const Mat4& getAimerTransform() const; // 0x1CE2A0, slot +0x2C (weak); [INFERRED] reference + virtual bool isAimVecValid() const; // 0x1CE2B0, slot +0x30 (weak) + virtual bool getLastAimVec(Vec3&); // 0x1CE2C0, slot +0x34 (weak) + virtual bool getPredictedPosition(Vec3&) const; // 0x1CE300, slot +0x38 (weak) + virtual bool getImpactTime(double&) const; // 0x1CE340, slot +0x3C (weak) + virtual bool getImpactPosition(Vec3&, double) const; // 0x1CE050, slot +0x40 + virtual bool getNearestImpactPosition(Vec3&, double&) const; // 0x1CE0D0, slot +0x44 + virtual void getPredictedPosition(double, Vec3&) const; // 0x1CE150, slot +0x48 + +protected: + // [INFERRED] friendship: EntryHeliAimAt reads/writes +0x14/+0x24..+0x3C/+0xA8/+0x1A4..+0x1D0 inline (ELF 0x2B5420). + friend class EntryHeliAimAt; + // [INFERRED] friendship: EntryPlaneAimAt reads/writes +0x14/+0x24..+0x3C/+0xA8/+0x1A4..+0x1B8 inline (ELF 0x2BFC70). + friend class EntryPlaneAimAt; + /* +0x014 */ BAPCondition* m_condition; // the subclass constructors' condition; deleted by them + /* +0x018 */ Vec3 m_offset; // aim offset (subclass constructors) + /* +0x024 */ Vec3 m_vec24; // [INFERRED] equipment facing; EntryHeliAimAt + /* +0x030 */ Vec3 m_vec30; // [INFERRED] equipment right axis; EntryHeliAimAt + /* +0x03C */ Vec3 m_vec3C; // [INFERRED] equipment up axis; EntryHeliAimAt + /* +0x048 */ Vec3 m_vecs48[4]; // [UNRESOLVED] constructed zero + /* +0x078 */ Vec3 m_vecs78[4]; // [UNRESOLVED] constructed zero + /* +0x0A8 */ Vec3 m_vecA8; // [INFERRED] previous velocity sample; EntryHeliAimAt + /* +0x0B4 */ Vec3 m_lastAimVec; // getAimVec's direction + /* +0x0C0 */ Vec3 m_predictedPosition; // getFiringDirection's target, in world space + /* +0x0CC */ Mat4 m_aimerTransform; // the weapon transform of the last getAimVec; identity + /* +0x10C */ double m_impactTime; // getFiringDirection's impact time (not constructed) + /* +0x114 */ bool m_aimVecValid; // getAimVec's result + /* +0x118 */ Aimer m_aimer; + /* +0x184 */ char m_unknown184[0x18]; // [UNRESOLVED] not touched by the AimAt3d family + /* +0x19C */ double m_double19C; // [UNRESOLVED] subclass constructors: -5e9 + /* +0x1A4 */ float m_float1A4; // [UNRESOLVED] the subclass constructors' first float + /* +0x1A8 */ float m_float1A8; // [UNRESOLVED] their second float + /* +0x1AC */ float m_floats1AC[4]; // [INFERRED] yaw error, pitch error, unresolved, equipment height; EntryHeliAimAt + /* +0x1BC */ int m_int1BC; // [UNRESOLVED] subclass constructors: 0 + /* +0x1C0 */ int m_unknown1C0; // [UNRESOLVED] not constructed + /* +0x1C4 */ int m_int1C4; // [UNRESOLVED] constructed 0 (again by the subclasses) + /* +0x1C8 */ Vec3 m_vec1C8; // [INFERRED] previous steering direction; EntryHeliAimAt +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMAT3D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtObject.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtObject.cpp new file mode 100644 index 000000000..19ef27cb7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtObject.cpp @@ -0,0 +1,205 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1CF280 (__tcf_0 0x1CF2E0, _GLOBAL__I 0x1CF310): 's Init object only. +#include + +#include "BAPAAimAtObject.h" + +#include "BAPActionInline.h" +#include "BAPCondition.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SensedObject.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/Information.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFPhysics.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1CE650 (C1; C2 0x1CE3B0). The isPrimary/getPrimaryObject pairs on the bot's equipment and +// on the target are evaluated and their answers dropped, as in the image (neither information is +// null-checked there). +BAPAAimAtObject::BAPAAimAtObject(Bot* bot, unsigned int target, const Vec3& offset, BAPCondition* endCondition, + unsigned long long controls, int patternId, bool useCenter, + BAPVariable* overrideValid, BAPVariable* overrideAim) + : BAPAAimAt(overrideValid, overrideAim) +{ + m_bot = bot; + m_target = target; + m_lastAim = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_predicted = bapinline::vec3(0.0f, 0.0f, 0.0f); + for (int i = 0; i < 16; ++i) + m_aimerTransform.m[i] = 0.0f; + m_aimerTransform.m[15] = 1.0f; + m_aimerTransform.m[10] = 1.0f; + m_aimerTransform.m[5] = 1.0f; + m_aimerTransform.m[0] = 1.0f; + m_valid = false; + m_useCenter = useCenter; + + Information* self = bapinline::info(bot->getCurrentEquipment()); + if (!self->isPrimary()) + self->getPrimaryObject(bot->getSide()); + Information* info = bapinline::info(target); + if (!info->isPrimary()) + info->getPrimaryObject(bot->getSide()); + + m_offset = offset; + m_endCondition = endCondition; + endCondition->setOwner(this); + m_patternId = patternId; + m_int140 = 0; + m_controls = controls; + m_int148 = 0; + m_double98 = -5000000000.0; +} + +// ELF 0x1CE8F0 (D1; D0 0x1CE970): deletes the end condition (virtual destructor, slot +0x10). +BAPAAimAtObject::~BAPAAimAtObject() +{ + if (m_endCondition) + delete m_endCondition; +} + +// ELF 0x1CF330 +int BAPAAimAtObject::getAimAtType() +{ + return 1; +} + +// ELF 0x1CEA00. With both override variables set their values win. Otherwise the target point is +// the sensed hit point (Bot slot +0x94 getSensedObjectFromHandle, +0x04, through the target's +// transformation) or, when the target is not sensed and m_useCenter is set, its position; not +// sensed without m_useCenter, or no target information: false. The Aimer gets the drag, speed and +// scaled gravity, the target relative to the weapon origin (plus the offset and the bot's fire +// correction) and the target's velocity (its own mobile, else its primary object's). +bool BAPAAimAtObject::getAimVec(const Mat4& origin, const Vec3& ownSpeed, Vec3& dir, float accuracy, float drag, + float speed, float gravityModifier, bool highArc, Bot* bot) +{ + if (m_overrideValid && m_overrideAim) { + dir = m_overrideAim->m_value; + m_lastAim = dir; + m_valid = m_overrideValid->m_value; + return m_overrideValid->m_value; + } + + Vec3 rel = bapinline::vec3(0.0f, 0.0f, 0.0f); + const Vec3& correction = correctAim(bot); + Information* target = bapinline::info(m_target); + if (!target) + return false; + m_bot->getCurrentEquipment(); // answer dropped (0x1CEB5x) + m_aimerTransform = origin; + + m_aimer.m_drag = drag; + m_aimer.m_inverseDrag = drag != 0.0f ? 1.0f / drag : 0.0f; + m_aimer.m_speed = speed; + m_aimer.m_gravity = static_cast( + static_cast(static_cast(CommonSingletonServer::m_iaiPhysics)->getGravity()) * gravityModifier); + + Vec3 point; + SensedObject* sensed = m_bot->getSensedObjectFromHandle(m_target); + if (!sensed) { + if (!m_useCenter) + return false; + point = target->getPosition(); + } else { + const Mat4& t = target->getAIObject()->getTransformation(); + const Vec3& l = sensed->m_seenPosition; + point.x = t.m[0] * l.x + t.m[4] * l.y + t.m[8] * l.z + t.m[12]; // 0x1CECE8..0x1CED09 + point.y = t.m[1] * l.x + t.m[5] * l.y + t.m[9] * l.z + t.m[13]; + point.z = l.x * t.m[2] + l.y * t.m[6] + l.z * t.m[10] + t.m[14]; + } + + const float ox = m_aimerTransform.m[12]; + const float oy = m_aimerTransform.m[13]; + const float oz = m_aimerTransform.m[14]; + rel.x = (point.x - ox) + m_offset.x + correction.x; + rel.y = (point.y - oy) + m_offset.y + correction.y; + rel.z = (point.z - oz) + m_offset.z + correction.z; + + Vec3 velocity; + IPIMobile* mobile = target->getMobile(); + if (!mobile && !target->isPrimary()) { + Information* primary = bapinline::info(target->getPrimaryObject(m_bot->getSide())); + if (primary) + mobile = primary->getMobile(); + } + if (mobile) + velocity = mobile->getSpeed(); + else + velocity = bapinline::vec3(0.0f, 0.0f, 0.0f); + + m_aimer.setTargetData(rel, velocity, ownSpeed, &m_aimerTransform, bapinline::gameTime()); + m_valid = m_aimer.getFiringDirection(bapinline::gameTime(), accuracy, highArc, m_lastAim, m_predicted, + &m_impactTime); + // Back to world space; the correction comes off again. + m_predicted.x = (m_aimerTransform.m[12] + m_predicted.x) - correction.x; + m_predicted.y = (m_aimerTransform.m[13] + m_predicted.y) - correction.y; + m_predicted.z = (m_aimerTransform.m[14] + m_predicted.z) - correction.z; + dir = m_lastAim; + return m_valid; +} + +// ELF 0x1CF060: target position - from; false (out untouched) without the target information. +bool BAPAAimAtObject::getVectorToTarget(const Vec3& from, Vec3& out) const +{ + Information* target = bapinline::info(m_target); + if (target) + out = bapinline::sub(target->getPosition(), from); + return target != 0; +} + +// ELF 0x1CF1F0 +const Mat4* BAPAAimAtObject::getAimerTransform() const +{ + return &m_aimerTransform; +} + +// ELF 0x1CF130 +bool BAPAAimAtObject::isAimingValid() const +{ + return m_valid; +} + +// ELF 0x1CF140 +bool BAPAAimAtObject::getLastAimVec(Vec3& out) const +{ + if (m_valid) + out = m_lastAim; + return m_valid; +} + +// ELF 0x1CF180 +bool BAPAAimAtObject::getPredictedPosition(Vec3& out) const +{ + if (m_valid) + out = m_predicted; + return m_valid; +} + +// ELF 0x1CF1C0 +bool BAPAAimAtObject::getImpactTime(double& out) const +{ + if (m_valid) + out = m_impactTime; + return m_valid; +} + +// ELF 0x1CF200: the Aimer's impact position along the transform's row 2 (+0x194), made absolute. +bool BAPAAimAtObject::getImpactPosition(Vec3& out, double time) const +{ + Vec3 forward = bapinline::vec3(m_aimerTransform.m[8], m_aimerTransform.m[9], m_aimerTransform.m[10]); + const bool result = m_aimer.getImpactPosition(out, forward, static_cast(time)); + out.x = m_aimerTransform.m[12] + out.x; + out.y = m_aimerTransform.m[13] + out.y; + out.z = m_aimerTransform.m[14] + out.z; + return result; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtObject.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtObject.h new file mode 100644 index 000000000..1af38e483 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtObject.h @@ -0,0 +1,54 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMATOBJECT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMATOBJECT_H + +#include "../../../../Math/Vec3.h" +#include "BAPAAimAt.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +struct Mat4; +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B7860 (17 words), package C-actions. +class BAPAAimAtObject : public BAPAAimAt +{ +public: + BAPAAimAtObject(Bot*, unsigned int, const Vec3&, BAPCondition*, unsigned long long, int, bool, BAPVariable*, BAPVariable*); // 0x1CE650 + virtual ~BAPAAimAtObject(); // 0x1CE8F0 + + virtual int getAimAtType(); // 0x1CF330, slot +0x20; from the base declaration + virtual bool getAimVec(const Mat4&, const Vec3&, Vec3&, float, float, float, float, bool, Bot*); // 0x1CEA00, slot +0x24; from the base declaration + virtual bool getVectorToTarget(const Vec3&, Vec3&) const; // 0x1CF060, slot +0x28; from the base declaration + virtual const Mat4* getAimerTransform() const; // 0x1CF1F0, slot +0x2C; from the base declaration + virtual bool isAimingValid() const; // 0x1CF130, slot +0x30; from the base declaration + virtual bool getLastAimVec(Vec3&) const; // 0x1CF140, slot +0x34; from the base declaration + virtual bool getPredictedPosition(Vec3&) const; // 0x1CF180, slot +0x38; from the base declaration + virtual bool getImpactTime(double&) const; // 0x1CF1C0, slot +0x3C; from the base declaration + virtual bool getImpactPosition(Vec3&, double) const; // 0x1CF200, slot +0x40; from the base declaration + + /* +0x154 */ Bot* m_bot; + /* +0x158 */ unsigned int m_target; // information handle + /* +0x15C */ Vec3 m_lastAim; // getFiringDirection's direction + /* +0x168 */ Vec3 m_predicted; // getFiringDirection's target, made absolute + /* +0x174 */ Mat4 m_aimerTransform; // = identity; getAimVec copies the weapon's origin + /* +0x1B4 */ double m_impactTime; + /* +0x1BC */ bool m_valid; // = false; getFiringDirection's answer + /* +0x1BD */ bool m_useCenter; // ctor bool: no sensed hit point, aim at the position +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMATOBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtObject3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtObject3d.cpp new file mode 100644 index 000000000..051a0956d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtObject3d.cpp @@ -0,0 +1,119 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. + +// static init: ELF 0x1CFC90 (__tcf_0 0x1CFCF0, _GLOBAL__I 0x1CFD20): 's Init object only. +#include + +#include "BAPAAimAtObject3d.h" + +#include "../../../AIInterface/BFKnowledge/BFPhysics.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SensedObject.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/Information.h" +#include "BAPActionInline.h" +#include "BAPCondition.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1CF410 (C1; C2 0x1CF340). The condition's owner is set without a null test, as compiled. +BAPAAimAtObject3d::BAPAAimAtObject3d(Bot* bot, unsigned int target, const Vec3& offset, BAPCondition* condition, + unsigned long long controls, int patternId, float float1A4, float float1A8) +{ + m_bot = bot; + m_target = target; + m_float1A4 = float1A4; + m_float1A8 = float1A8; + m_offset = offset; + m_condition = condition; + condition->setOwner(this); + m_patternId = patternId; + m_int1BC = 0; + m_controls = controls; + m_int1C4 = 0; + m_double19C = static_cast(-5000000000.0f); +} + +// ELF 0x1CF560 (D1 0x1CF4E0, D0 0x1CF5E0) +BAPAAimAtObject3d::~BAPAAimAtObject3d() +{ + if (m_condition) + delete m_condition; +} + +// ELF 0x1CFD40 +int BAPAAimAtObject3d::getAimAtType() +{ + return 1; +} + +// ELF 0x1CFBC0 +bool BAPAAimAtObject3d::getVectorToTarget(const Vec3& from, Vec3& vector) const +{ + Information* const target = bapinline::info(m_target); + if (target) + vector = bapinline::sub(target->getPosition(), from); + return target != 0; +} + +// ELF 0x1CF660. Refuses a slow projectile (speed at most 0.1) from a nearly resting shooter. The +// target point is the bot's sensed point on the object, in the object's current transformation, +// or else the object's position; its velocity is the object's IPIMobile speed, or that of its +// primary object for the bot's side, or zero. +bool BAPAAimAtObject3d::getAimVec(const Mat4& transform, const Vec3& shooterVelocity, Vec3& direction, + float accuracy, float drag, float speed, float gravityScale, bool highArc) +{ + if (speed <= 0.1f && bapinline::lengthSqr(shooterVelocity) <= 0.01f) + return false; + Bot* const bot = m_bot; + const IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); + Information* const target = bapinline::info(m_target); + if (!target) + return false; + + m_aimerTransform = transform; + m_aimer.m_drag = drag; + m_aimer.m_inverseDrag = drag != 0.0f ? 1.0f / drag : 0.0f; + m_aimer.m_speed = speed; + m_aimer.m_gravity = static_cast(CommonSingletonServer::m_iaiPhysics)->getGravity() * gravityScale; + + Vec3 targetPosition = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (SensedObject* const sensed = bot->getSensedObjectFromHandle(m_target)) + { + const Mat4& t = target->getAIObject()->getTransformation(); + const Vec3& p = sensed->m_seenPosition; + targetPosition.x = t.m[0] * p.x + t.m[4] * p.y + t.m[8] * p.z + t.m[12]; + targetPosition.y = t.m[1] * p.x + t.m[5] * p.y + t.m[9] * p.z + t.m[13]; + targetPosition.z = t.m[2] * p.x + t.m[6] * p.y + t.m[10] * p.z + t.m[14]; + } + else + { + targetPosition = target->getPosition(); + } + const Vec3 relative = bapinline::sub(targetPosition, *reinterpret_cast(&m_aimerTransform.m[12])); + + Vec3 targetVelocity = bapinline::vec3(0.0f, 0.0f, 0.0f); + IPIMobile* mobile = target->getMobile(); + if (!mobile && !target->isPrimary()) + { + if (Information* const primary = bapinline::info(target->getPrimaryObject(m_bot->getSide()))) + mobile = primary->getMobile(); + } + if (mobile) + targetVelocity = mobile->getSpeed(); + + m_aimer.setTargetData(relative, targetVelocity, shooterVelocity, &transform, timer->getGameTime()); + m_aimVecValid = m_aimer.getFiringDirection(timer->getGameTime(), accuracy, highArc, direction, + m_predictedPosition, &m_impactTime); + m_lastAimVec = direction; + m_predictedPosition.x = m_aimerTransform.m[12] + m_predictedPosition.x; + m_predictedPosition.y = m_aimerTransform.m[13] + m_predictedPosition.y; + m_predictedPosition.z = m_aimerTransform.m[14] + m_predictedPosition.z; + return m_aimVecValid; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtObject3d.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtObject3d.h new file mode 100644 index 000000000..8d272f1b8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtObject3d.h @@ -0,0 +1,45 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMATOBJECT3D_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMATOBJECT3D_H + +#include "../../../../Math/Vec3.h" +#include "BAPAAimAt3d.h" + +namespace dice { +namespace hfe { + +struct Mat4; +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B7900 (19 words), package G-vehicles. +// Aims at an information object: its position, or the bot's sensed point on it, with its velocity +// (or its primary object's). +class BAPAAimAtObject3d : public BAPAAimAt3d +{ +public: + BAPAAimAtObject3d(Bot*, unsigned int, const Vec3&, BAPCondition*, unsigned long long, int, float, float); // 0x1CF410 + virtual ~BAPAAimAtObject3d(); // 0x1CF560 + + virtual int getAimAtType(); // 0x1CFD40, slot +0x20 + virtual bool getVectorToTarget(const Vec3&, Vec3&) const; // 0x1CFBC0, slot +0x24 + virtual bool getAimVec(const Mat4&, const Vec3&, Vec3&, float, float, float, float, bool); // 0x1CF660, slot +0x28 + +private: + // [INFERRED] friendship: EntryHeliAimAt reads +0x1D8 inline (ELF 0x2B5420). + friend class EntryHeliAimAt; + // [INFERRED] friendship: EntryPlaneAimAt reads +0x1D8 inline (ELF 0x2BFC70). + friend class EntryPlaneAimAt; + /* +0x1D4 */ Bot* m_bot; + /* +0x1D8 */ unsigned int m_target; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMATOBJECT3D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtPoint.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtPoint.cpp new file mode 100644 index 000000000..c9f583910 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtPoint.cpp @@ -0,0 +1,148 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1D06B0 (__tcf_0 0x1D0710, _GLOBAL__I 0x1D0740): 's Init object only. +#include + +#include "BAPAAimAtPoint.h" + +#include "BAPActionInline.h" +#include "BAPCondition.h" +#include "../AIBot/BotMain.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFPhysics.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1CFE90 (C1; C2 0x1CFC50) +BAPAAimAtPoint::BAPAAimAtPoint(Bot* bot, BAPVariable* point, const Vec3& offset, BAPCondition* endCondition, + unsigned long long controls, int patternId, BAPVariable* overrideValid, + BAPVariable* overrideAim) + : BAPAAimAt(overrideValid, overrideAim) +{ + m_point = point; + m_lastAim = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_bot = bot; + m_predicted = bapinline::vec3(0.0f, 0.0f, 0.0f); + for (int i = 0; i < 16; ++i) + m_aimerTransform.m[i] = 0.0f; + m_aimerTransform.m[15] = 1.0f; + m_aimerTransform.m[10] = 1.0f; + m_aimerTransform.m[5] = 1.0f; + m_aimerTransform.m[0] = 1.0f; + m_valid = false; + m_offset = offset; + m_endCondition = endCondition; + endCondition->setOwner(this); + m_patternId = patternId; + m_double98 = -5000000000.0; + m_controls = controls; + m_int140 = 0; + m_int148 = 0; +} + +// ELF 0x1D0050 (D1; D0 0x1D00D0): deletes the end condition. +BAPAAimAtPoint::~BAPAAimAtPoint() +{ + if (m_endCondition) + delete m_endCondition; +} + +// ELF 0x1D0760 +int BAPAAimAtPoint::getAimAtType() +{ + return 0; +} + +// ELF 0x1D0160. Like BAPAAimAtObject::getAimVec for the point variable, without the override +// variables, with a zero target velocity and the caller's origin matrix (not the copy) handed to +// setTargetData. The bot's equipment is read and dropped first, as in the image. +bool BAPAAimAtPoint::getAimVec(const Mat4& origin, const Vec3& ownSpeed, Vec3& dir, float accuracy, float drag, + float speed, float gravityModifier, bool highArc, Bot* bot) +{ + Vec3 rel = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_bot->getCurrentEquipment(); // answer dropped + const Vec3& correction = correctAim(bot); + m_aimerTransform = origin; + + m_aimer.m_drag = drag; + m_aimer.m_inverseDrag = drag == 0.0f ? 0.0f : 1.0f / drag; + m_aimer.m_speed = speed; + m_aimer.m_gravity = static_cast( + static_cast(static_cast(CommonSingletonServer::m_iaiPhysics)->getGravity()) * gravityModifier); + + const Vec3& p = m_point->m_value; + rel.x = (p.x - m_aimerTransform.m[12]) + m_offset.x + correction.x; + rel.y = (p.y - m_aimerTransform.m[13]) + m_offset.y + correction.y; + rel.z = (p.z - m_aimerTransform.m[14]) + m_offset.z + correction.z; + + const double now = bapinline::gameTime(); + const Vec3 velocity = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_aimer.setTargetData(rel, velocity, ownSpeed, &origin, now); + m_valid = m_aimer.getFiringDirection(bapinline::gameTime(), accuracy, highArc, m_lastAim, m_predicted, + &m_impactTime); + m_predicted.x = (m_aimerTransform.m[12] + m_predicted.x) - correction.x; + m_predicted.y = (m_aimerTransform.m[13] + m_predicted.y) - correction.y; + m_predicted.z = (m_aimerTransform.m[14] + m_predicted.z) - correction.z; + dir = m_lastAim; + return m_valid; +} + +// ELF 0x1D04E0: always true. +bool BAPAAimAtPoint::getVectorToTarget(const Vec3& from, Vec3& out) const +{ + out = bapinline::sub(m_point->m_value, from); + return true; +} + +// ELF 0x1D0620 +const Mat4* BAPAAimAtPoint::getAimerTransform() const +{ + return &m_aimerTransform; +} + +// ELF 0x1D0560 +bool BAPAAimAtPoint::isAimingValid() const +{ + return m_valid; +} + +// ELF 0x1D0570 +bool BAPAAimAtPoint::getLastAimVec(Vec3& out) const +{ + if (m_valid) + out = m_lastAim; + return m_valid; +} + +// ELF 0x1D05B0 +bool BAPAAimAtPoint::getPredictedPosition(Vec3& out) const +{ + if (m_valid) + out = m_predicted; + return m_valid; +} + +// ELF 0x1D05F0 +bool BAPAAimAtPoint::getImpactTime(double& out) const +{ + if (m_valid) + out = m_impactTime; + return m_valid; +} + +// ELF 0x1D0630: as BAPAAimAtObject::getImpactPosition. +bool BAPAAimAtPoint::getImpactPosition(Vec3& out, double time) const +{ + Vec3 forward = bapinline::vec3(m_aimerTransform.m[8], m_aimerTransform.m[9], m_aimerTransform.m[10]); + const bool result = m_aimer.getImpactPosition(out, forward, static_cast(time)); + out.x = m_aimerTransform.m[12] + out.x; + out.y = m_aimerTransform.m[13] + out.y; + out.z = m_aimerTransform.m[14] + out.z; + return result; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtPoint.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtPoint.h new file mode 100644 index 000000000..769ae5790 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtPoint.h @@ -0,0 +1,53 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMATPOINT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMATPOINT_H + +#include "../../../../Math/Vec3.h" +#include "BAPAAimAt.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +struct Mat4; +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B79A0 (17 words), package C-actions. +class BAPAAimAtPoint : public BAPAAimAt +{ +public: + BAPAAimAtPoint(Bot*, BAPVariable*, const Vec3&, BAPCondition*, unsigned long long, int, BAPVariable*, BAPVariable*); // 0x1CFE90 + virtual ~BAPAAimAtPoint(); // 0x1D0050 + + virtual int getAimAtType(); // 0x1D0760, slot +0x20; from the base declaration + virtual bool getAimVec(const Mat4&, const Vec3&, Vec3&, float, float, float, float, bool, Bot*); // 0x1D0160, slot +0x24; from the base declaration + virtual bool getVectorToTarget(const Vec3&, Vec3&) const; // 0x1D04E0, slot +0x28; from the base declaration + virtual const Mat4* getAimerTransform() const; // 0x1D0620, slot +0x2C; from the base declaration + virtual bool isAimingValid() const; // 0x1D0560, slot +0x30; from the base declaration + virtual bool getLastAimVec(Vec3&) const; // 0x1D0570, slot +0x34; from the base declaration + virtual bool getPredictedPosition(Vec3&) const; // 0x1D05B0, slot +0x38; from the base declaration + virtual bool getImpactTime(double&) const; // 0x1D05F0, slot +0x3C; from the base declaration + virtual bool getImpactPosition(Vec3&, double) const; // 0x1D0630, slot +0x40; from the base declaration + + /* +0x154 */ BAPVariable* m_point; + /* +0x158 */ Bot* m_bot; + /* +0x15C */ Vec3 m_lastAim; + /* +0x168 */ Vec3 m_predicted; + /* +0x174 */ Mat4 m_aimerTransform; // = identity + /* +0x1B4 */ double m_impactTime; + /* +0x1BC */ bool m_valid; // = false +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMATPOINT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtPoint3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtPoint3d.cpp new file mode 100644 index 000000000..41b38631d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtPoint3d.cpp @@ -0,0 +1,84 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. + +// static init: ELF 0x1D0D50 (__tcf_0 0x1D0DB0, _GLOBAL__I 0x1D0DE0): 's Init object only. +#include + +#include "BAPAAimAtPoint3d.h" + +#include "../../../AIInterface/BFKnowledge/BFPhysics.h" +#include "BAPActionInline.h" +#include "BAPCondition.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D0870 (C1; C2 0x1D0770). The condition's owner is set without a null test, as compiled. +BAPAAimAtPoint3d::BAPAAimAtPoint3d(Vec3& point, Vec3& offset, BAPCondition* condition, unsigned long long controls, + int patternId, float float1A4, float float1A8) +{ + m_point = bapinline::vec3(offset.x + point.x, offset.y + point.y, offset.z + point.z); + m_float1A4 = float1A4; + m_float1A8 = float1A8; + m_offset = offset; + m_condition = condition; + condition->setOwner(this); + m_patternId = patternId; + m_int1BC = 0; + m_controls = controls; + m_int1C4 = 0; + m_double19C = static_cast(-5000000000.0f); +} + +// ELF 0x1D09F0 (D1 0x1D0970, D0 0x1D0A70) +BAPAAimAtPoint3d::~BAPAAimAtPoint3d() +{ + if (m_condition) + delete m_condition; +} + +// ELF 0x1D0E00 +int BAPAAimAtPoint3d::getAimAtType() +{ + return 0; +} + +// ELF 0x1D0D00 +bool BAPAAimAtPoint3d::getVectorToTarget(const Vec3& from, Vec3& vector) const +{ + vector = bapinline::sub(m_point, from); + return true; +} + +// ELF 0x1D0AF0. A resting target: the relative position is the point (plus the offset once more) +// from the transformation's position; unlike the object aim, the transformation is not stored, so +// the predicted position is offset by the previous aim's weapon position. +bool BAPAAimAtPoint3d::getAimVec(const Mat4& transform, const Vec3& shooterVelocity, Vec3& direction, + float accuracy, float drag, float speed, float gravityScale, bool highArc) +{ + Vec3 relative = bapinline::vec3(0.0f, 0.0f, 0.0f); + const Vec3 targetVelocity = bapinline::vec3(0.0f, 0.0f, 0.0f); // stored, never read + (void)targetVelocity; + const IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); + m_aimer.m_drag = drag; + m_aimer.m_inverseDrag = drag != 0.0f ? 1.0f / drag : 0.0f; + m_aimer.m_speed = speed; + m_aimer.m_gravity = static_cast(CommonSingletonServer::m_iaiPhysics)->getGravity() * gravityScale; + + const Vec3 position = bapinline::vec3(transform.m[12], transform.m[13], transform.m[14]); + const Vec3 toPoint = bapinline::sub(m_point, position); + relative = bapinline::add(toPoint, m_offset); + const Vec3 resting = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_aimer.setTargetData(relative, resting, shooterVelocity, &transform, timer->getGameTime()); + m_aimVecValid = m_aimer.getFiringDirection(timer->getGameTime(), accuracy, highArc, m_lastAimVec, + m_predictedPosition, &m_impactTime); + direction = m_lastAimVec; + m_predictedPosition.x = m_aimerTransform.m[12] + m_predictedPosition.x; + m_predictedPosition.y = m_aimerTransform.m[13] + m_predictedPosition.y; + m_predictedPosition.z = m_aimerTransform.m[14] + m_predictedPosition.z; + return m_aimVecValid; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtPoint3d.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtPoint3d.h new file mode 100644 index 000000000..75c0d9ab3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtPoint3d.h @@ -0,0 +1,39 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMATPOINT3D_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMATPOINT3D_H + +#include "../../../../Math/Vec3.h" +#include "BAPAAimAt3d.h" + +namespace dice { +namespace hfe { + +struct Mat4; +namespace ai { + +class BAPCondition; + +// ELF: vtable 0x4B7A00 (19 words), package G-vehicles. +// Aims at a fixed point. The constructor adds the offset to the point and keeps it in m_offset, +// so getAimVec applies it twice, as shipped. +class BAPAAimAtPoint3d : public BAPAAimAt3d +{ +public: + BAPAAimAtPoint3d(Vec3&, Vec3&, BAPCondition*, unsigned long long, int, float, float); // 0x1D0870 + virtual ~BAPAAimAtPoint3d(); // 0x1D09F0 + + virtual int getAimAtType(); // 0x1D0E00, slot +0x20 + virtual bool getVectorToTarget(const Vec3&, Vec3&) const; // 0x1D0D00, slot +0x24 + virtual bool getAimVec(const Mat4&, const Vec3&, Vec3&, float, float, float, float, bool); // 0x1D0AF0, slot +0x28 + +private: + /* +0x1D4 */ Vec3 m_point; // the constructor's point plus offset +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMATPOINT3D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAChangeWeapon.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAChangeWeapon.cpp new file mode 100644 index 000000000..ecd6be91a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAChangeWeapon.cpp @@ -0,0 +1,87 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1D1450 (__tcf_0 0x1D14B0, _GLOBAL__I 0x1D14E0): 's Init object only. +#include + +#include "BAPAChangeWeapon.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D0F00 (C1): the weapon is resolved now; controls = the 64-bit `1 << getWeaponActivate()`. +// Neither the information nor the weapon is null-checked. +BAPAChangeWeapon::BAPAChangeWeapon(Bot* bot, int weaponIndex, int patternId) +{ + m_bot = bot; + m_weaponIndex = weaponIndex; + m_patternId = patternId; + IPIArmament* armament = bapinline::info(bot->getCurrentEquipment())->getArmament(); + m_weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(weaponIndex)); + m_controls = 1ULL << (static_cast(m_weapon->getWeaponActivate()) & 63u); +} + +// ELF 0x1D1030 (D0 0x1D1070) +BAPAChangeWeapon::~BAPAChangeWeapon() +{ +} + +// ELF 0x1D10C0. Soldiers: while another slot is active, release fire / alt fire / reload and +// press the activation input (ok, not failed); once it is active, release them all (done). +// Vehicles: press the activation input (Input::setInput inlined with its range check) and finish. +bool BAPAChangeWeapon::execute(Bot* bot, bool& ok, bool& failed) +{ + Information* info = bapinline::info(bot->getCurrentEquipment()); + if (!info) { + ok = false; + failed = true; + return true; + } + io::PlayerInput* input = bot->getInput(); + if (info->isOfType(ITSoldier)) { + if (info->getArmament()->getActiveWeapon() != m_weaponIndex) { + input->setInput(io::PIFire, 0.0f); + input->setInput(io::PIAltFire, 0.0f); + input->setInput(io::PIReload, 0.0f); + input->setInput(static_cast(m_weapon->getWeaponActivate()), 1.0f); + ok = true; + failed = false; + return true; + } + input->setInput(static_cast(m_weapon->getWeaponActivate()), 0.0f); + input->setInput(io::PIFire, 0.0f); + input->setInput(io::PIAltFire, 0.0f); + input->setInput(io::PIReload, 0.0f); + ok = true; + failed = true; + return true; + } + input->setInput(static_cast(m_weapon->getWeaponActivate()), 1.0f); + ok = true; + failed = true; + return true; +} + +// ELF 0x1D1430 +BAPStatementType BAPAChangeWeapon::getId() const +{ + return BAPSTChangeWeapon; // 28 +} + +// ELF 0x1D1440 +bool BAPAChangeWeapon::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAChangeWeapon.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAChangeWeapon.h new file mode 100644 index 000000000..79e48078d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAChangeWeapon.h @@ -0,0 +1,44 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPACHANGEWEAPON_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPACHANGEWEAPON_H + +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class WeaponInfo; + +// ELF: vtable 0x4B7AA0 (8 words), operator new 0x20, package C-actions. +// Selects a weapon slot of the bot's current vehicle/soldier by pressing its activation +// input (controls = 1 << that input). +class BAPAChangeWeapon : public BAPAction +{ +public: + BAPAChangeWeapon(Bot*, int, int); // 0x1D0F00 + virtual ~BAPAChangeWeapon(); // 0x1D1030 + + virtual bool execute(Bot*, bool&, bool&); // 0x1D10C0, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1D1430, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1D1440, slot +0x14; from the base declaration + +private: + /* +0x14 */ Bot* m_bot; + /* +0x18 */ int m_weaponIndex; // armament slot + /* +0x1C */ WeaponInfo* m_weapon; // resolved at construction +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPACHANGEWEAPON_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAComponentSoldierPose.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAComponentSoldierPose.cpp new file mode 100644 index 000000000..16268a6b1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAComponentSoldierPose.cpp @@ -0,0 +1,199 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1D1BE0 (__tcf_0 0x1D1C40, _GLOBAL__I 0x1D1C70): 's Init object only. +#include + +#include "BAPAComponentSoldierPose.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../Main/AIRandom.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D1620 (C1; C2 0x1D1500 region). The fire threshold gets the inline Mersenne-Twister +// draw: `t5 = t * 5` is stored as float, then `rnd * 2^-32 * t5 + t` in x87 precision +// (double here) and stored as float. +BAPAComponentSoldierPose::BAPAComponentSoldierPose(SoldierPose normal, SoldierPose incommingFire, + float fireObjectsThreshold, SoldierPose danger, + float controlThreshold, unsigned int object, + float timeDuration) +{ + m_normalPose = normal; + m_incommingFirePose = incommingFire; + const float t5 = fireObjectsThreshold * 5.0f; + const unsigned int r = AIRandom::m_instance->next(); + m_fireObjectsThreshold = static_cast(static_cast(r) * static_cast(2.3283064e-10f) * t5 + + fireObjectsThreshold); + m_dangerPose = danger; + m_currentPose = normal; + // The ordered comparisons leave a NaN unchanged. + float c = controlThreshold; + if (-1.0f > c) + c = -1.0f; + else if (c > 1.0f) + c = 1.0f; + m_controlThreshold = c; + m_timeDuration = timeDuration; + m_lastChangeTime = -static_cast(FLT_MAX); + m_object = object; +} + +// ELF 0x1D1760 (D1; D0 0x1D1780) +BAPAComponentSoldierPose::~BAPAComponentSoldierPose() +{ +} + +// ELF 0x1D17C0 +void BAPAComponentSoldierPose::setNormalPose(SoldierPose pose) +{ + m_normalPose = pose; +} + +// ELF 0x1D17D0 +void BAPAComponentSoldierPose::setIncommingFirePose(SoldierPose pose) +{ + m_incommingFirePose = pose; +} + +// ELF 0x1D17E0 +void BAPAComponentSoldierPose::setFireObjectsThreshold(float threshold) +{ + m_fireObjectsThreshold = threshold; +} + +// ELF 0x1D17F0 +void BAPAComponentSoldierPose::setDangerPose(SoldierPose pose) +{ + m_dangerPose = pose; +} + +// ELF 0x1D1800 +void BAPAComponentSoldierPose::setControlThreshold(float threshold) +{ + m_controlThreshold = threshold; +} + +// ELF 0x1D1810 +void BAPAComponentSoldierPose::setTimeDuration(float duration) +{ + m_timeDuration = duration; +} + +// Inline in both 0x1D1820 and 0x1D1940: `info->m_objectTypeFlags & 0x200000` (byte +6 bit 5), +// `m_iaiPlayerFactory->getPlayerFromId(info->getPlayerId())` (+0x20), `player->getSoldier()` +// (+0x4C) non-null, and `info->getSoldierPose() != SPStanding`. +bool BAPAComponentSoldierPose::objectForcesCrouch() const +{ + if (m_object == 0xFFFFFFFFu) + return false; + Information* info = bapinline::info(m_object); + if (!info || !info->isOfType(ITSoldier)) + return false; + IAIPlayer* player = static_cast(CommonSingletonServer::m_iaiPlayerFactory) + ->getPlayerFromId(info->getPlayerId()); + return player && player->getSoldier() && info->getSoldierPose() != SPStanding; +} + +// ELF 0x1D1820 +SoldierPose BAPAComponentSoldierPose::getNormalPose() +{ + if (objectForcesCrouch()) + return SPCrouching; + return m_normalPose; +} + +// ELF 0x1D18E0 +SoldierPose BAPAComponentSoldierPose::getIncommingFirePose() const +{ + return m_incommingFirePose; +} + +// ELF 0x1D18F0 +float BAPAComponentSoldierPose::getFireObjectsThreshold() const +{ + return m_fireObjectsThreshold; +} + +// ELF 0x1D1900 +SoldierPose BAPAComponentSoldierPose::getDangerPose() const +{ + return m_dangerPose; +} + +// ELF 0x1D1910 +float BAPAComponentSoldierPose::getControlThreshold() const +{ + return m_controlThreshold; +} + +// ELF 0x1D1920 +float BAPAComponentSoldierPose::getTimeDuration() const +{ + return m_timeDuration; +} + +// ELF 0x1D1930 +SoldierPose BAPAComponentSoldierPose::getCurrentPose() const +{ + return m_currentPose; +} + +// ELF 0x1D1940. Swimming wins; otherwise the pose is re-chosen at most every m_timeDuration: +// crouch next to a non-standing followed soldier; incoming fire above the threshold picks the +// incoming-fire pose, else control below the threshold picks the danger pose, else the normal +// pose; "lying" (3) needs kit 1 or 3, otherwise crouch. Then water: deeper than 0.4 stands, +// any water turns lying into crouching. +SoldierPose BAPAComponentSoldierPose::computeCurrentPose(float incommingFire, float control, double time, + Bot* bot, const Vec3& position) +{ + Information* self = bapinline::info(bot->getCurrentEquipment()); + if (!self) + return m_currentPose; + if (self->getSoldierPose() == SPSwimming) { + m_currentPose = SPSwimming; + return SPSwimming; + } + if (time - m_lastChangeTime < static_cast(m_timeDuration)) + return m_currentPose; + m_lastChangeTime = time; + if (objectForcesCrouch()) { + m_currentPose = SPCrouching; + return SPCrouching; + } + + SoldierPose pose; + if (incommingFire <= m_fireObjectsThreshold) + pose = (m_controlThreshold <= control) ? m_normalPose : m_dangerPose; + else + pose = m_incommingFirePose; + if (pose == SPLying && self->getKitType() != 1 && self->getKitType() != 3) + pose = SPCrouching; + m_currentPose = pose; + + IAITerrain* terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + const float water = terrain->getWaterLevel(position.x, position.z); + const float depth = water - terrain->getHeight(position.x, position.z); + if (0.4f < depth) { + m_currentPose = SPStanding; + return SPStanding; + } + if (0.0f < depth && m_currentPose == SPLying) { + m_currentPose = SPCrouching; + return SPCrouching; + } + return m_currentPose; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAComponentSoldierPose.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAComponentSoldierPose.h new file mode 100644 index 000000000..21f9591e8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAComponentSoldierPose.h @@ -0,0 +1,64 @@ +// Soldier-pose chooser shared by pose and move actions. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPACOMPONENTSOLDIERPOSE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPACOMPONENTSOLDIERPOSE_H + +#include "../../../../Math/Vec3.h" +#include "../../../AIInterface/BFKnowledge/SoldierPose.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B7AE0 (16 words), package C-actions. +// Soldier-pose chooser mixed into BAPAMoveTo and BAPASoldierPose (secondary base, size 0x2C). +// Setters return nothing (no eax write); the float getters return through x87. +class BAPAComponentSoldierPose +{ +public: + BAPAComponentSoldierPose(SoldierPose normal, SoldierPose incommingFire, float fireObjectsThreshold, + SoldierPose danger, float controlThreshold, unsigned int object, + float timeDuration); // 0x1D1620 + virtual ~BAPAComponentSoldierPose(); // 0x1D1760 + + virtual void setNormalPose(SoldierPose); // 0x1D17C0, slot +0x08 + virtual void setIncommingFirePose(SoldierPose); // 0x1D17D0, slot +0x0C + virtual void setFireObjectsThreshold(float); // 0x1D17E0, slot +0x10 + virtual void setDangerPose(SoldierPose); // 0x1D17F0, slot +0x14 + virtual void setControlThreshold(float); // 0x1D1800, slot +0x18 + virtual void setTimeDuration(float); // 0x1D1810, slot +0x1C + virtual SoldierPose getNormalPose(); // 0x1D1820, slot +0x20 + virtual SoldierPose getIncommingFirePose() const; // 0x1D18E0, slot +0x24 + virtual float getFireObjectsThreshold() const; // 0x1D18F0, slot +0x28 + virtual SoldierPose getDangerPose() const; // 0x1D1900, slot +0x2C + virtual float getControlThreshold() const; // 0x1D1910, slot +0x30 + virtual float getTimeDuration() const; // 0x1D1920, slot +0x34 + virtual SoldierPose getCurrentPose() const; // 0x1D1930, slot +0x38 + virtual SoldierPose computeCurrentPose(float incommingFire, float control, double time, Bot*, + const Vec3& position); // 0x1D1940, slot +0x3C + +private: + // True when m_object is a soldier-type information (flags bit 21) whose player has a soldier + // that is not standing: the inline test getNormalPose and computeCurrentPose both spell out. + bool objectForcesCrouch() const; + + /* +0x04 */ SoldierPose m_normalPose; + /* +0x08 */ SoldierPose m_incommingFirePose; + /* +0x0C */ float m_fireObjectsThreshold; // randomised: t + rnd * t * 5 + /* +0x10 */ SoldierPose m_dangerPose; + /* +0x14 */ SoldierPose m_currentPose; // = normal + /* +0x18 */ float m_controlThreshold; // clamped to [-1, 1] + /* +0x1C */ float m_timeDuration; + /* +0x20 */ double m_lastChangeTime; // = -FLT_MAX + /* +0x28 */ unsigned int m_object; // information handle, -1 = none + +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPACOMPONENTSOLDIERPOSE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPADebug.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPADebug.cpp new file mode 100644 index 000000000..141780932 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPADebug.cpp @@ -0,0 +1,61 @@ +// A completed debug marker whose integer value appears in plan dumps. + +// static init: ELF 0x1FB8F0 (__tcf_0 0x1FB950, _GLOBAL__I 0x1FB980): 's Init object only. +#include + +#include "BAPADebug.h" + +#include "../Main/IBotManager.h" +#include "../Main/AIStreamOperators.h" +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1FB6F0 (C1; C2 0x1FB6A0) +BAPADebug::BAPADebug(int value) : BAPAction(UninitializedPatternId()), m_value(value) +{ +} + +// ELF 0x1FB780 (D1; D2 0x1FB740, D0 0x1FB7C0) +BAPADebug::~BAPADebug() +{ +} + +// ELF 0x1FB810 +bool BAPADebug::execute(Bot*, bool& success, bool& finished) +{ + success = true; + finished = true; + return true; +} + +// ELF 0x1FB9A0 +unsigned long long BAPADebug::getControls() +{ + return m_controls; +} + +// ELF 0x1FB9B0 +BAPStatementType BAPADebug::getId() const +{ + return BAPSTDebug; +} + +// ELF 0x1FB9C0 +bool BAPADebug::hasDefault() +{ + return false; +} + +// ELF 0x1FB830 +void BAPADebug::streamSelf(std::ostream& out) const +{ + IBotManager::instance->tabulate(out); + out << getId() << "(" << m_value << ")" << std::endl; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPADebug.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPADebug.h new file mode 100644 index 000000000..8db452904 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPADebug.h @@ -0,0 +1,37 @@ +// A completed debug marker whose integer value appears in plan dumps. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPADEBUG_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPADEBUG_H + +#include +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4BA540 (8 words), package H-deferred. +class BAPADebug : public BAPAction +{ +public: + explicit BAPADebug(int); // 0x1FB6F0 + virtual ~BAPADebug(); // 0x1FB780 + + virtual bool execute(Bot*, bool&, bool&); // 0x1FB810, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1FB9A0, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1FB9B0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1FB9C0, slot +0x14; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1FB830, slot +0x1C; from the base declaration +private: + /* +0x14 */ int m_value; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPADEBUG_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAEvaluate.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAEvaluate.cpp new file mode 100644 index 000000000..82bdd7e8b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAEvaluate.cpp @@ -0,0 +1,47 @@ +// Expression statement; neither shipped image constructs an expression object. + +#include "BAPAEvaluate.h" + +#include "BAPExpression.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D1CF0 (C1; C2 0x1D1C90). +BAPAEvaluate::BAPAEvaluate(BAPExpression* expression) + : BAPStatement(UninitializedPatternId{}), m_expression(expression) +{ +} + +// ELF 0x1D1DB0 (D1; D2 0x1D1D50, D0 0x1D1E10). +BAPAEvaluate::~BAPAEvaluate() +{ + if (m_expression) + delete m_expression; +} + +// ELF 0x1D1E80 +bool BAPAEvaluate::execute(Bot*, bool& ok, bool& done) +{ + m_expression->unimplementedExpressionSlot2(); + ok = true; + done = true; + return true; +} + +// ELF 0x1D1EB0 +BAPStatementType BAPAEvaluate::getId() const +{ + return BAPSTEvaluate; +} + +// ELF 0x1D1EC0 +bool BAPAEvaluate::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAEvaluate.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAEvaluate.h new file mode 100644 index 000000000..39ab3f73e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAEvaluate.h @@ -0,0 +1,36 @@ +// Owns an expression, invokes its pure operation and finishes successfully. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAEVALUATE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAEVALUATE_H + +#include "BAPStatement.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPExpression; +class Bot; + +// ELF: vtable 0x4B7B40 (8 words), package H-deferred. +class BAPAEvaluate : public BAPStatement +{ +public: + explicit BAPAEvaluate(BAPExpression*); // 0x1D1CF0 + virtual ~BAPAEvaluate(); // 0x1D1DB0 + + virtual bool execute(Bot*, bool&, bool&); // 0x1D1E80, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1D1EB0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1D1EC0, slot +0x14; from the base declaration + +private: + /* +0x14 */ BAPExpression* m_expression; // owned; constructor leaves the inherited pattern id unwritten +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAEVALUATE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAEvaluateCondition.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAEvaluateCondition.cpp new file mode 100644 index 000000000..bdfe5cf2d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAEvaluateCondition.cpp @@ -0,0 +1,72 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1D2220 (__tcf_0 0x1D2280, _GLOBAL__I 0x1D22B0): 's Init object only. +#include + +#include "BAPAEvaluateCondition.h" + +#include "BAPActionInline.h" +#include "BAPCondition.h" +#include "../Main/IBotManager.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D1F40 (C1) +BAPAEvaluateCondition::BAPAEvaluateCondition(BAPCondition* condition, int patternId) +{ + m_condition = condition; + m_patternId = patternId; + condition->setOwner(this); +} + +// ELF 0x1D2020 (D0 0x1D2090): deletes the condition. +BAPAEvaluateCondition::~BAPAEvaluateCondition() +{ + if (m_condition) + delete m_condition; +} + +// ELF 0x1D2100 +bool BAPAEvaluateCondition::execute(Bot* bot, bool& ok, bool& failed) +{ + m_result = m_condition->evaluate(bot); + ok = true; + failed = true; + return true; +} + +// ELF 0x1D2140: no controls. +unsigned long long BAPAEvaluateCondition::getControls() +{ + return 0; +} + +// ELF 0x1D22D0 +BAPStatementType BAPAEvaluateCondition::getId() const +{ + return BAPSTEvaluateCondition; // 43 +} + +// ELF 0x1D2150 +bool BAPAEvaluateCondition::hasDefault() +{ + return true; +} + +// ELF 0x1D2160 +void BAPAEvaluateCondition::streamSelf(std::ostream& out) const +{ + IBotManager::instance->tabulate(out); + bapinline::streamType(out, getId()) << "("; + out << (m_result ? "[true]" : "[false]"); + out << *m_condition; + out << ")" << std::endl; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAEvaluateCondition.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAEvaluateCondition.h new file mode 100644 index 000000000..d2aea5c40 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAEvaluateCondition.h @@ -0,0 +1,45 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAEVALUATECONDITION_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAEVALUATECONDITION_H + +#include +#include "BAPStatement.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B7BC0 (8 words), operator new 0x1C, package C-actions. +// Evaluates a condition once and remembers the answer (+0x18, printed by streamSelf). +class BAPAEvaluateCondition : public BAPStatement +{ +public: + BAPAEvaluateCondition(BAPCondition*, int); // 0x1D1F40 + virtual ~BAPAEvaluateCondition(); // 0x1D2020 + + virtual bool execute(Bot*, bool&, bool&); // 0x1D2100, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1D2140, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1D22D0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1D2150, slot +0x14; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1D2160, slot +0x1C; from the base declaration + +private: + /* +0x14 */ BAPCondition* m_condition; // owned + /* +0x18 */ bool m_result; // not initialised by the ctor +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAEVALUATECONDITION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAForgetTarget.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAForgetTarget.cpp new file mode 100644 index 000000000..c97137fd1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAForgetTarget.cpp @@ -0,0 +1,50 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1D24C0 (__tcf_0 0x1D2520, _GLOBAL__I 0x1D2550): 's Init object only. +#include + +#include "BAPAForgetTarget.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/BotSenses.h" +#include "../AIBot/SensingAgent.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D2330 (C1) +BAPAForgetTarget::BAPAForgetTarget(unsigned int target) +{ + m_target = target; +} + +// ELF 0x1D23C0 (D0 0x1D2400) +BAPAForgetTarget::~BAPAForgetTarget() +{ +} + +// ELF 0x1D2450: `bot->getSensingAgent()->+0x68` (getSenses) ->forgetObject(target). +bool BAPAForgetTarget::execute(Bot* bot, bool& ok, bool& failed) +{ + bot->getSensingAgent()->getSenses()->forgetObject(m_target); + ok = true; + failed = true; + return true; +} + +// ELF 0x1D24A0 +BAPStatementType BAPAForgetTarget::getId() const +{ + return BAPSTForgetTarget; // 39 +} + +// ELF 0x1D24B0 +bool BAPAForgetTarget::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAForgetTarget.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAForgetTarget.h new file mode 100644 index 000000000..bfd50db16 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAForgetTarget.h @@ -0,0 +1,40 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAFORGETTARGET_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAFORGETTARGET_H + +#include "BAPStatement.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B7C40 (8 words), operator new 0x18, package C-actions. +// Makes the bot's senses forget one object (BotSenses::forgetObject). +class BAPAForgetTarget : public BAPStatement +{ +public: + explicit BAPAForgetTarget(unsigned int); // 0x1D2330 + virtual ~BAPAForgetTarget(); // 0x1D23C0 + + virtual bool execute(Bot*, bool&, bool&); // 0x1D2450, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1D24A0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1D24B0, slot +0x14; from the base declaration + +private: + /* +0x14 */ unsigned int m_target; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAFORGETTARGET_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAHonkHorn.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAHonkHorn.cpp new file mode 100644 index 000000000..e9d410f90 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAHonkHorn.cpp @@ -0,0 +1,52 @@ +// Requests a horn notification for one information handle; execution returns false as shipped. + +// static init: ELF 0x1D2780 (__tcf_0 0x1D27E0, _GLOBAL__I 0x1D2810): 's Init object only. +#include + +#include "BAPAHonkHorn.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/CommunicationAgent.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D25D0 (C1; C2 0x1D2570) +BAPAHonkHorn::BAPAHonkHorn(unsigned int object, int tag) : BAPAction(UninitializedPatternId()) +{ + m_patternId = tag; + m_object = object; +} + +// ELF 0x1D2670 (D1; D2 0x1D2630, D0 0x1D26B0) +BAPAHonkHorn::~BAPAHonkHorn() +{ +} + +// ELF 0x1D2700 +bool BAPAHonkHorn::execute(Bot* bot, bool& success, bool& finished) +{ + Information* object = bapinline::info(m_object); + bot->getCommunicationAgent()->honkHorn(object); + success = false; + finished = true; + return false; +} + +// ELF 0x1D2830 +BAPStatementType BAPAHonkHorn::getId() const +{ + return BAPSTHonkHorn; +} + +// ELF 0x1D2840 +bool BAPAHonkHorn::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAHonkHorn.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAHonkHorn.h new file mode 100644 index 000000000..c350899c4 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAHonkHorn.h @@ -0,0 +1,34 @@ +// Requests a horn notification for one information handle; execution returns false as shipped. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAHONKHORN_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAHONKHORN_H + +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B7C80 (8 words), operator new 0x18, package G-vehicles. +class BAPAHonkHorn : public BAPAction +{ +public: + BAPAHonkHorn(unsigned int, int); // 0x1D25D0 + virtual ~BAPAHonkHorn(); // 0x1D2670 + + virtual bool execute(Bot*, bool&, bool&); // 0x1D2700, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1D2830, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1D2840, slot +0x14; from the base declaration +private: + /* +0x14 */ unsigned int m_object; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAHONKHORN_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAIdle.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAIdle.cpp new file mode 100644 index 000000000..c75d75b15 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAIdle.cpp @@ -0,0 +1,63 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +#include "BAPAIdle.h" + +#include "BAPCondition.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D28C0 (C1; C2 0x1D2810 region): the condition's owner is set unconditionally. +BAPAIdle::BAPAIdle(BAPCondition* condition, unsigned long long controls, int patternId) +{ + m_condition = condition; + condition->setOwner(this); + m_patternId = patternId; + m_controls = controls; +} + +// ELF 0x1D2990 (D0 0x1D29F0): deletes the condition. +BAPAIdle::~BAPAIdle() +{ + if (m_condition) + delete m_condition; +} + +// ELF 0x1D2A60 +bool BAPAIdle::execute(Bot* bot, bool& ok, bool& failed) +{ + ok = true; + failed = m_condition->evaluate(bot); + return true; +} + +// ELF 0x1D2AA0 +unsigned long long BAPAIdle::getControls() +{ + return m_controls; +} + +// ELF 0x1D2B10 (weak) +BAPStatementType BAPAIdle::getId() const +{ + return BAPSTIdle; // 13 +} + +// ELF 0x1D2AB0 +bool BAPAIdle::hasDefault() +{ + return true; +} + +// ELF 0x1D2AC0: every level. +void BAPAIdle::debug(BotScriptDebugger::DebugLevel, std::string& text) +{ + text = "Idling..."; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAIdle.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAIdle.h new file mode 100644 index 000000000..d303f5a9a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAIdle.h @@ -0,0 +1,45 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAIDLE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAIDLE_H + +#include +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B7CC0 (8 words), package C-actions. +// Idles until the condition holds (ok = true, failed = condition). +class BAPAIdle : public BAPAction +{ +public: + BAPAIdle(BAPCondition*, unsigned long long, int); // 0x1D28C0 + virtual ~BAPAIdle(); // 0x1D2990 + + virtual bool execute(Bot*, bool&, bool&); // 0x1D2A60, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1D2AA0, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1D2B10, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1D2AB0, slot +0x14; from the base declaration + virtual void debug(BotScriptDebugger::DebugLevel, std::string&); // 0x1D2AC0, slot +0x18; from the base declaration + +private: + /* +0x14 */ BAPCondition* m_condition; // owned +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAIDLE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALook.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALook.cpp new file mode 100644 index 000000000..d09700c04 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALook.cpp @@ -0,0 +1,55 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1D2D10 (__tcf_0 0x1D2D70, _GLOBAL__I 0x1D2DA0): 's Init object only. +#include + +#include "BAPALook.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D2BA0 (C1; C2 0x1D2B20 identical). The inline BAPStatement base clears +0x04/+0x08 and +// counts `news`; then +0x14 = cond, +0x18 = speed, +0x1C..+0x2C = 0, +0x08 = controls, +0x10 = tag. +// The condition's owner is set by the derived constructors, not here. +BAPALook::BAPALook(float lookSpeed, BAPCondition* endCondition, unsigned long long controls, int tag) +{ + m_endCondition = endCondition; + m_lookSpeed = lookSpeed; + m_deviation = 0.0f; + m_lastControl = 0.0f; + m_cameraForward.x = 0.0f; + m_cameraForward.y = 0.0f; + m_cameraForward.z = 0.0f; + m_controls = controls; + m_patternId = tag; +} + +// ELF 0x1D2C60 (D1; D2 0x1D2C20, D0 0x1D2CA0): only the inline base destructor (`destroys`). +BAPALook::~BAPALook() +{ +} + +// ELF 0x1D2CF0: a look never runs by itself (the entries do the work): ok = false, failed = true. +bool BAPALook::execute(Bot*, bool& ok, bool& failed) +{ + ok = false; + failed = true; + return false; +} + +// ELF 0x1D2DC0 +BAPStatementType BAPALook::getId() const +{ + return BAPSTLookAt; // 23 +} + +// ELF 0x1D2DD0 +bool BAPALook::hasDefault() +{ + return false; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALook.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALook.h new file mode 100644 index 000000000..1748effc7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALook.h @@ -0,0 +1,50 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPALOOK_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPALOOK_H + +#include "../../../../Math/Vec3.h" +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B7D00 (9 words), package C-actions. Size 0x30 (derived data starts at +0x30). +// Look statement base: the infantry/turret look entries steer the camera towards +// getLookDirection() and keep their regulator state in the public fields below. +class BAPALook : public BAPAction +{ +public: + BAPALook(float, BAPCondition*, unsigned long long, int); // 0x1D2BA0 + virtual ~BAPALook(); // 0x1D2C60 + + virtual bool execute(Bot*, bool&, bool&); // 0x1D2CF0, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1D2DC0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1D2DD0, slot +0x14; from the base declaration + virtual Vec3 getLookDirection(bool&) = 0; // no body, slot +0x20; ELF sret (BAPALookInDir 0x1D3D40 `ret $4`) + + // Read and written inline by EntryMouseTurretLookAt::execute (0x2B9E90) and the other look + // entries, so public. [INFERRED] names from that use. + /* +0x14 */ BAPCondition* m_endCondition; // evaluated first by the entries: true ends the look. + // The derived classes own and delete it (base dtor does not). + /* +0x18 */ float m_lookSpeed; // the ctor's float; passed to mouseControlLookAtDirection + /* +0x1C */ float m_deviation; // = 0; regulator out/in (angle to target); entries store pi (0x40490FDB) when idle + /* +0x20 */ float m_lastControl; // = 0; regulator out/in (previous control value) + /* +0x24 */ Vec3 m_cameraForward; // = 0; entries copy camera matrix row 2 (+0x20) here +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPALOOK_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAhead.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAhead.cpp new file mode 100644 index 000000000..037b9940c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAhead.cpp @@ -0,0 +1,49 @@ +// Look statement that keeps the view along the vehicle's facing. Recovered from libaidll.so +// 1.5.3153 (ia-32); ELF addresses on every body. + +#include "BAPALookAhead.h" + +#include "BAPActionInline.h" +#include "BAPCondition.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1D3070, __tcf_0 0x1D30D0, _GLOBAL__I 0x1D3100). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D2E60 (C1; C2 0x1D2DE0): the base, the bot's current equipment at +0x30, then the end +// condition's owner (not null-checked). +BAPALookAhead::BAPALookAhead(Bot* bot, float lookSpeed, BAPCondition* endCondition, unsigned long long controls, + int tag) + : BAPALook(lookSpeed, endCondition, controls, tag) +{ + m_equipment = bot->getCurrentEquipment(); + m_endCondition->setOwner(this); +} + +// ELF 0x1D2F30 (D1; D2 0x1D2EE0, D0 0x1D2F80): deletes the end condition. +BAPALookAhead::~BAPALookAhead() +{ + if (m_endCondition) + delete m_endCondition; +} + +// ELF 0x1D2FE0: the equipment's facing; ok reports whether its information still exists, and a +// stale handle yields (0, 0, 0). +Vec3 BAPALookAhead::getLookDirection(bool& ok) +{ + Information* const equipment = bapinline::info(m_equipment); + ok = equipment != 0; + if (!ok) + return bapinline::vec3(0.0f, 0.0f, 0.0f); + return equipment->getFaceing(); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAhead.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAhead.h new file mode 100644 index 000000000..e6504868e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAhead.h @@ -0,0 +1,36 @@ +// Look statement along the facing of the bot's vehicle. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPALOOKAHEAD_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPALOOKAHEAD_H + +#include "../../../../Math/Vec3.h" +#include "BAPALook.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B7D40 (9 words), package G-vehicles. Looks along the facing of the bot's equipment +// at construction time. +class BAPALookAhead : public BAPALook +{ +public: + BAPALookAhead(Bot*, float, BAPCondition*, unsigned long long, int); // 0x1D2E60 + virtual ~BAPALookAhead(); // 0x1D2F30 + + virtual Vec3 getLookDirection(bool&); // 0x1D2FE0, slot +0x20; from the base declaration + + /* +0x30 */ unsigned int m_equipment; // the bot's current equipment handle at construction +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPALOOKAHEAD_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAtObject.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAtObject.cpp new file mode 100644 index 000000000..d0d0a2fce --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAtObject.cpp @@ -0,0 +1,65 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1D3580 (__tcf_0 0x1D35E0, _GLOBAL__I 0x1D3610): 's Init object only. +#include + +#include "BAPALookAtObject.h" + +#include "BAPActionInline.h" +#include "BAPCondition.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/Information.h" +#include "../Main/AIDllFrontier.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D31A0 (C1; C2 0x1D3120) +BAPALookAtObject::BAPALookAtObject(Bot* bot, unsigned int target, float lookSpeed, BAPCondition* endCondition, + unsigned long long controls, int tag, BAPVariable* targetPosition, + float heightOffset) + : BAPALook(lookSpeed, endCondition, controls, tag) +{ + m_bot = bot; + m_target = target; + m_targetPosition = targetPosition; + m_heightOffset = heightOffset; + m_endCondition->setOwner(this); +} + +// ELF 0x1D3270 (D1; D2 0x1D3220, D0 0x1D32C0): deletes the end condition. +BAPALookAtObject::~BAPALookAtObject() +{ + if (m_endCondition) + delete m_endCondition; +} + +// ELF 0x1D3320: from the camera position of the bot's current vehicle/soldier to the target +// (or the override variable's point), raised by m_heightOffset, normalised. No target +// information: ok = false and (1, 0, 0). +Vec3 BAPALookAtObject::getLookDirection(bool& ok) +{ + Information* self = bapinline::info(m_bot->getCurrentEquipment()); + Information* target = bapinline::info(m_target); + ok = target != 0; + if (!ok) + return bapinline::vec3(1.0f, 0.0f, 0.0f); + + // The camera transform is fetched before the target point (0x1D33D9; the bot's equipment + // information is not null-checked). Its row 3 (+0x30) is the camera position. + const Mat4& camera = self->getControlInfo()->getCameraTransformation(); + Vec3 p; + if (m_targetPosition) + p = m_targetPosition->m_value; + else + p = target->getPosition(); + Vec3 dir = bapinline::vec3(p.x - camera.m[12], (m_heightOffset + p.y) - camera.m[13], p.z - camera.m[14]); + bapinline::normalize(dir); + return dir; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAtObject.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAtObject.h new file mode 100644 index 000000000..7db18c041 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAtObject.h @@ -0,0 +1,42 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPALOOKATOBJECT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPALOOKATOBJECT_H + +#include "../../../../Math/Vec3.h" +#include "BAPALook.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B7DC0 (9 words), package C-actions. +class BAPALookAtObject : public BAPALook +{ +public: + BAPALookAtObject(Bot*, unsigned int, float, BAPCondition*, unsigned long long, int, BAPVariable*, float); // 0x1D31A0 + virtual ~BAPALookAtObject(); // 0x1D3270 + + virtual Vec3 getLookDirection(bool&); // 0x1D3320, slot +0x20; from the base declaration + +private: + /* +0x30 */ Bot* m_bot; + /* +0x34 */ unsigned int m_target; // information handle + /* +0x38 */ BAPVariable* m_targetPosition; // optional override of the target's position + /* +0x3C */ float m_heightOffset; // added to the target point's y +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPALOOKATOBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAtPoint.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAtPoint.cpp new file mode 100644 index 000000000..32da64221 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAtPoint.cpp @@ -0,0 +1,48 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1D39C0 (__tcf_0 0x1D3A20, _GLOBAL__I 0x1D3A50): 's Init object only. +#include + +#include "BAPALookAtPoint.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D36C0 (C1; C2 0x1D3630). Unlike the other looks it neither sets the condition's owner +// nor deletes the condition. +BAPALookAtPoint::BAPALookAtPoint(const Vec3& point, Bot* bot, float lookSpeed, BAPCondition* endCondition, + unsigned long long controls, int tag) + : BAPALook(lookSpeed, endCondition, controls, tag) +{ + m_point = point; + m_bot = bot; +} + +// ELF 0x1D3940 (D1; D2 0x1D38F0 region, D0 0x1D3990): base only. +BAPALookAtPoint::~BAPALookAtPoint() +{ +} + +// ELF 0x1D3750: from the bot's current vehicle/soldier position to the point, normalised; no +// information: ok = false and a zero vector. +Vec3 BAPALookAtPoint::getLookDirection(bool& ok) +{ + Information* self = bapinline::info(m_bot->getCurrentEquipment()); + if (!self) { + ok = false; + return bapinline::vec3(0.0f, 0.0f, 0.0f); + } + ok = true; + Vec3 dir = bapinline::sub(m_point, self->getPosition()); + bapinline::normalize(dir); + return dir; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAtPoint.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAtPoint.h new file mode 100644 index 000000000..9042808e6 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAtPoint.h @@ -0,0 +1,39 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPALOOKATPOINT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPALOOKATPOINT_H + +#include "../../../../Math/Vec3.h" +#include "BAPALook.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B7E00 (9 words), package C-actions. +class BAPALookAtPoint : public BAPALook +{ +public: + BAPALookAtPoint(const Vec3&, Bot*, float, BAPCondition*, unsigned long long, int); // 0x1D36C0 + virtual ~BAPALookAtPoint(); // 0x1D3940 + + virtual Vec3 getLookDirection(bool&); // 0x1D3750, slot +0x20; from the base declaration + +private: + /* +0x30 */ Vec3 m_point; + /* +0x3C */ Bot* m_bot; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPALOOKATPOINT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookInDir.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookInDir.cpp new file mode 100644 index 000000000..e08927448 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookInDir.cpp @@ -0,0 +1,40 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1D3C90 (__tcf_0 0x1D3CF0, _GLOBAL__I 0x1D3D20): 's Init object only. +#include + +#include "BAPALookInDir.h" + +#include "../AIBotActionPlan/BAPCondition.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D3B00 (C1; C2 0x1D3A70 identical): direction copied to +0x30, then the end condition's +// owner (+0x04) is pointed at this statement. +BAPALookInDir::BAPALookInDir(const Vec3& direction, float lookSpeed, BAPCondition* endCondition, + unsigned long long controls, int tag) + : BAPALook(lookSpeed, endCondition, controls, tag) +{ + m_direction = direction; + endCondition->setOwner(this); +} + +// ELF 0x1D3BE0 (D1; D2 0x1D3B90, D0 0x1D3C30): deletes the end condition (virtual D0, slot +0x10). +BAPALookInDir::~BAPALookInDir() +{ + if (m_endCondition) + delete m_endCondition; +} + +// ELF 0x1D3D40: always valid, the stored direction. +Vec3 BAPALookInDir::getLookDirection(bool& ok) +{ + ok = true; + return m_direction; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookInDir.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookInDir.h new file mode 100644 index 000000000..e0f972c16 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookInDir.h @@ -0,0 +1,37 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPALOOKINDIR_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPALOOKINDIR_H + +#include "../../../../Math/Vec3.h" +#include "BAPALook.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; + +// ELF: vtable 0x4B7E40 (9 words), package C-actions. +class BAPALookInDir : public BAPALook +{ +public: + BAPALookInDir(const Vec3&, float, BAPCondition*, unsigned long long, int); // 0x1D3B00 + virtual ~BAPALookInDir(); // 0x1D3BE0 + + virtual Vec3 getLookDirection(bool&); // 0x1D3D40, slot +0x20; from the base declaration + +private: + /* +0x30 */ Vec3 m_direction; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPALOOKINDIR_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMergeSoldierInputs.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMergeSoldierInputs.cpp new file mode 100644 index 000000000..230039410 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMergeSoldierInputs.cpp @@ -0,0 +1,192 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1D4BA0 (__tcf_0 0x1D4C00, _GLOBAL__I 0x1D4C30): 's Init object only. +#include + +#include "BAPAMergeSoldierInputs.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SensingAgent.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../AIPlanInterpreter/MouseControl.h" +#include "../Main/IBotManager.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../../Game/Objects/IObject.h" +#include "../../../../Game/Objects/ObjectLayoutAccess.h" +#include "../../../../Physics/IPhysicsNode.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// The function-static `lookAheadFrames` of execute (ELF .data 0x4B7EA4). +int lookAheadFrames = 3; + +float signedSqrtClamped(float v) +{ + const float sign = v <= 0.0f ? (0.0f <= v ? 0.0f : -1.0f) : 1.0f; + const float r = std::sqrt(std::fabs(v)) * sign; + if (r < -1.0f) + return -1.0f; + if (1.0f < r) + return 1.0f; + return r; +} + +} // namespace + +// ELF 0x1D3DD0 (C1; C2 0x1D3D40) +BAPAMergeSoldierInputs::BAPAMergeSoldierInputs(int patternId) +{ + m_lastYawError = 0.0f; + m_lastPitchError = 0.0f; + m_patternId = patternId; +} + +// ELF 0x1D3E70 (D1; D0 0x1D3EB0): base only. +BAPAMergeSoldierInputs::~BAPAMergeSoldierInputs() +{ +} + +// ELF 0x1D3F00. Turns the sensing agent's move direction (+0x50) into soldier inputs. +// Walking (no sprint input, not swimming): the direction is split onto the soldier's forward and +// right axes (XZ, normalised, turned ahead by the body's yaw rate over lookAheadFrames frames), +// each as a clamped signed square root, scaled by |throttle|; sprint released. +// Sprinting or swimming: the mouse turns the camera to the direction; throttle is pressed while +// the yaw error is small (< 5 deg) or the sprint focus (+0x58 point, or the +0x64 target's +// position) is at least 4 m away (1 m for a human-occupied vehicle within 3 m); sprint is kept +// while the error is below 40 deg and the focus is beyond that distance. A larger error releases +// the throttle input directly. Always ok and done. +bool BAPAMergeSoldierInputs::execute(Bot* bot, bool& ok, bool& done) +{ + io::PlayerInput* input = bot->getInput(); + SensingAgent* sensing = bot->getSensingAgent(); + const Vec2 move = sensing->getMoveDirection(); + Information* self = bapinline::info(bot->getCurrentEquipment()); // not null-checked + const Mat4& t = self->getTransformation(); + IPIControlInfo* controlInfo = self->getControlInfo(); + float pitchError = 0.0f; + float yawError = 0.0f; + const SoldierPose pose = self->getSoldierPose(); + const bool sprint = bapinline::mappedInput(input, io::PISprint) != 0.0f; + + io::PlayerInputMap lastInput; + float lastValue; + if (!sprint && pose != SPSwimming) { + Vec2 forward; + forward.x = 0.0f; + forward.y = 0.0f; + Vec2 right; + right.x = 0.0f; + right.y = 0.0f; + vec3ToVec2XZ(*reinterpret_cast(&t.m[8]), forward); + vec3ToVec2XZ(*reinterpret_cast(&t.m[0]), right); + bapinline::normalize(forward); + bapinline::normalize(right); + IAIObject* object = self->getAIObject(); + if (object) { + world::IPhysicsNode* node = static_cast( + world::object_detail::LayoutAccess::physicsNode(object->getObject())); + if (node) { + const float step = static_cast(lookAheadFrames) + * static_cast(bapinline::timeIncrease()); + const float rate = node->getRotationalSpeed().y * 0.017453292f; + if (rate != 0.0f) { + // A 2D rotation by -angle (rows (c, -s), (s, c)) applied as v' = (c*x + s*y, + // -s*x + c*y) to both axes (0x1D48B8..0x1D4AA0). + const float angle = rate * step; + const float c = std::cos(angle); + const float s = std::sin(angle); + const Vec2 f = forward; + forward.x = c * f.x + s * f.y; + forward.y = f.x * -s + f.y * c; + const Vec2 r = right; + right.y = -s * r.x + c * r.y; + right.x = s * r.y + c * r.x; + } + } + } + const float throttle = bapinline::mappedInput(input, io::PIThrottle); + const float f = signedSqrtClamped(forward.x * move.x + forward.y * move.y); + const float r = signedSqrtClamped(right.x * move.x + move.y * right.y); + input->setInput(io::PIThrottle, f * std::fabs(throttle)); + input->setInput(io::PIYaw, std::fabs(throttle) * r); + lastInput = io::PISprint; + lastValue = 0.0f; + } else { + Vec3 dir = bapinline::vec3(0.0f, 0.0f, 0.0f); + vec2ToVec3XZ(move, dir); + const Mat4& camera = *static_cast(bot->getPlayer()->getCameraTransformation()); + mouseControlLookAtDirection(bot, dir, camera, pitchError, m_lastPitchError, yawError, m_lastYawError, 0.0f, + controlInfo, input, 0.0f, 0.0f, 0.0f); + bool humanVehicle = false; + float focusDistSqr = 0.0f; + if (sprint) { + const Vec3 pos = bapinline::vec3(t.m[12], t.m[13], t.m[14]); + Vec3 focus = bapinline::vec3(0.0f, 0.0f, 0.0f); + const unsigned int handle = bot->getSensingAgent()->getSprintFocusTarget(); + Information* focusInfo = handle == 0xFFFFFFFFu ? 0 : bapinline::info(handle); + if (!focusInfo) { + const Vec3& p = bot->getSensingAgent()->getSprintFocus(); + focus.x = p.x; + focus.z = p.z; + } else { + focus = focusInfo->getPosition(); + humanVehicle = focusInfo->getAIObject() && !IBotManager::instance->getBot(focusInfo->getAIObject()) + && focusInfo->getUnit() && focusInfo->getUnit()->isOccupied(); + } + const float dx = pos.x - focus.x; + const float dz = pos.z - focus.z; + focusDistSqr = dx * dx + 0.0f + dz * dz; + } + const bool close = bot->getSensingAgent()->getSprintFocusTarget() != 0xFFFFFFFFu && focusDistSqr < 9.0f + && humanVehicle; + const float limit = close ? 1.0f : 16.0f; + if (limit <= focusDistSqr || close || std::fabs(yawError) <= 0.08726646f) { + if ((std::fabs(yawError) < 0.6981317f || close) && limit < focusDistSqr) { + if (sprint) + input->setInput(io::PISprint, 1.0f); + lastInput = io::PIThrottle; + lastValue = 1.0f; + } else { + input->setInput(io::PIThrottle, 1.0f); + lastInput = io::PISprint; + lastValue = 0.0f; + } + } else { + if ((input->mappingFlags >> 3) & 1ULL) + input->inputs[io::PIThrottle] = 0.0f; // Input::setInput inlined (0x1D4180) + lastInput = io::PISprint; + lastValue = 0.0f; + } + } + input->setInput(lastInput, lastValue); + m_lastPitchError = pitchError; + m_lastYawError = yawError; + ok = true; + done = true; + return true; +} + +// ELF 0x1D4C50 +BAPStatementType BAPAMergeSoldierInputs::getId() const +{ + return BAPSTMergeSoldierInputs; // 36 +} + +// ELF 0x1D4B90 +bool BAPAMergeSoldierInputs::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMergeSoldierInputs.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMergeSoldierInputs.h new file mode 100644 index 000000000..60a3e0d19 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMergeSoldierInputs.h @@ -0,0 +1,40 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMERGESOLDIERINPUTS_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMERGESOLDIERINPUTS_H + +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B7EC0 (8 words), operator new 0x1C, package C-actions. +class BAPAMergeSoldierInputs : public BAPAction +{ +public: + explicit BAPAMergeSoldierInputs(int); // 0x1D3DD0 + virtual ~BAPAMergeSoldierInputs(); // 0x1D3E70 + + virtual bool execute(Bot*, bool&, bool&); // 0x1D3F00, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1D4C50, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1D4B90, slot +0x14; from the base declaration + +private: + /* +0x14 */ float m_lastYawError; // = 0; mouseControlLookAtDirection's yaw in/out + /* +0x18 */ float m_lastPitchError; // = 0; its pitch in/out +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMERGESOLDIERINPUTS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveAwayFrom3dObject.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveAwayFrom3dObject.cpp new file mode 100644 index 000000000..2a1d78639 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveAwayFrom3dObject.cpp @@ -0,0 +1,92 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. + +// static init: ELF 0x1D5030 (__tcf_0 0x1D5090, _GLOBAL__I 0x1D50C0): 's Init object only. +#include + +#include "BAPAMoveAwayFrom3dObject.h" + +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/Information.h" +#include "BAPActionInline.h" +#include "BAPCondition.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D4D50 (C1; C2 0x1D4C60) +BAPAMoveAwayFrom3dObject::BAPAMoveAwayFrom3dObject(unsigned int object, float distance, BAPCondition* condition, + unsigned long long controls, int patternId) +{ + m_condition = condition; + m_point = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_object = object; + m_vec30 = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_distance = distance; + m_patternId = patternId; + m_controls = controls; + if (condition) + condition->setOwner(this); + if (Information* const info = bapinline::info(m_object)) + m_mobile = info->getMobile() != 0; + m_vec30 = bapinline::vec3(0.0f, 0.0f, 0.0f); +} + +// ELF 0x1D4EA0 (D1 0x1D4E40, D0 0x1D4F00) +BAPAMoveAwayFrom3dObject::~BAPAMoveAwayFrom3dObject() +{ + if (m_condition) + delete m_condition; +} + +// ELF 0x1D4F70. Only a vehicle move entry executes it: on its own it fails at once. +bool BAPAMoveAwayFrom3dObject::execute(Bot*, bool& ok, bool& finished) +{ + ok = false; + finished = true; + return false; +} + +// ELF 0x1D4F90. Without information the previous point is returned unchanged. +Vec3* BAPAMoveAwayFrom3dObject::getFirstPoint() +{ + if (Information* const info = bapinline::info(m_object)) + { + if (!m_mobile) + m_point = info->getPosition(); + else + info->getMobile()->getPositionEstimate(m_point); + } + return &m_point; +} + +// ELF 0x1D50E0 (weak) +unsigned long long BAPAMoveAwayFrom3dObject::getControls() +{ + return m_controls; +} + +// ELF 0x1D50F0 (weak) +BAPStatementType BAPAMoveAwayFrom3dObject::getId() const +{ + return BAPSTMoveAwayFromObject; +} + +// ELF 0x1D5100 (weak) +bool BAPAMoveAwayFrom3dObject::hasDefault() +{ + return false; +} + +// ELF 0x1D5110 (weak) +bool BAPAMoveAwayFrom3dObject::isFinished(Bot* bot) +{ + bool finished = false; + if (m_condition) + finished = m_condition->evaluate(bot); + return finished; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveAwayFrom3dObject.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveAwayFrom3dObject.h new file mode 100644 index 000000000..f598ce02f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveAwayFrom3dObject.h @@ -0,0 +1,51 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVEAWAYFROM3DOBJECT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVEAWAYFROM3DOBJECT_H + +#include "../../../../Math/Vec3.h" +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B7F00 (9 words), package G-vehicles. +// Flies away from an information object until the condition holds; the vehicle move entries +// execute it (on its own it fails) and read the object's point from getFirstPoint. +class BAPAMoveAwayFrom3dObject : public BAPAction +{ +public: + BAPAMoveAwayFrom3dObject(unsigned int, float, BAPCondition*, unsigned long long, int); // 0x1D4D50 + virtual ~BAPAMoveAwayFrom3dObject(); // 0x1D4EA0 + + virtual bool execute(Bot*, bool&, bool&); // 0x1D4F70, slot +0x00 + virtual unsigned long long getControls(); // 0x1D50E0, slot +0x0C + virtual BAPStatementType getId() const; // 0x1D50F0, slot +0x10 + virtual bool hasDefault(); // 0x1D5100, slot +0x14 + virtual bool isFinished(Bot*); // 0x1D5110, slot +0x20: the condition, false without one + + Vec3* getFirstPoint(); // 0x1D4F90; refreshes and returns this + 0x1C (was [INFERRED] int) + +private: + // [INFERRED] friendship: EntryHeliMoveAwayFromObject reads +0x14/+0x2C/+0x30 inline (ELF 0x2B6580). + friend class EntryHeliMoveAwayFromObject; + /* +0x14 */ unsigned int m_object; + /* +0x18 */ BAPCondition* m_condition; // deleted by the destructor + /* +0x1C */ Vec3 m_point; // getFirstPoint: the object's position or position estimate + /* +0x28 */ bool m_mobile; // the object had an IPIMobile at construction (else not set) + /* +0x2C */ float m_distance; // [INFERRED] name: callers pass 150 + /* +0x30 */ Vec3 m_vec30; // [INFERRED] previous velocity sample; EntryHeliMoveAwayFromObject +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVEAWAYFROM3DOBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo.cpp new file mode 100644 index 000000000..7f6e023e3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo.cpp @@ -0,0 +1,356 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1D6700 (__tcf_0 0x1D6760, _GLOBAL__I 0x1D6790): 's Init object only. +#include + +#include "BAPAMoveTo.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../AIPlanInterpreter/InfanteryControl.h" +#include "../Main/AIRandom.h" +#include "../AIBot/BotNavigation.h" +#include "../AIBot/SensingAgent.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// The constructor's fire threshold: `rnd * 2^-32 * 14 + 1` in x87 precision, stored as float. +float randomFireThreshold() +{ + const unsigned int r = AIRandom::m_instance->next(); + return static_cast(static_cast(r) * static_cast(2.3283064e-10f) * 14.0 + 1.0); +} + +inline float length2(float x, float y) +{ + return std::sqrt(x * x + y * y); +} + +} // namespace + +// ELF 0x1D5310 (C1; C2 0x1D5150). Pose chooser: stand, lie under incoming fire above a random +// threshold in [1, 15), crouch in danger, no control threshold, no object, 10 s between changes. +// Ends with BotMain::setMoveToStatus(0) (Bot vtable +0x244). +BAPAMoveTo::BAPAMoveTo(Bot* bot) + : BAPAction(UninitializedPatternId()), + BAPAComponentSoldierPose(SPStanding, SPLying, randomFireThreshold(), SPCrouching, 0.0f, 0xFFFFFFFFu, 10.0f) +{ + m_coordinate = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_isSprinting = false; + m_previousSpeed = 0.0f; + m_currentPoint.x = 0.0f; + m_currentPoint.y = 0.0f; + m_vec74.x = 0.0f; + m_vec74.y = 0.0f; + m_avoidPoint.x = 0.0f; + m_avoidPoint.y = 0.0f; + m_obstaclePosition.x = 0.0f; + m_obstaclePosition.y = 0.0f; + m_cachedDir.x = 0.0f; + m_cachedDir.y = 0.0f; + m_obstacle = 0xFFFFFFFFu; + m_nextDirTime = -1000.0; + m_previousHeading.y = 0.0f; + m_previousHeading.x = 1.0f; + static_cast(bot)->setMoveToStatus(0); +} + +// ELF 0x1D5550 (D1; D2 0x1D54D0, D0 0x1D55D0, thunk 0x1D67D0): deletes the end condition. +BAPAMoveTo::~BAPAMoveTo() +{ + if (m_endCondition) + delete m_endCondition; +} + +// ELF 0x1D5650 +unsigned long long BAPAMoveTo::getControls() +{ + return m_controls; +} + +// ELF 0x1D5710 +BAPStatementType BAPAMoveTo::getId() const +{ + return BAPSTMoveTo; // 7 +} + +// ELF 0x1D5720 +bool BAPAMoveTo::hasDefault() +{ + return false; +} + +// ELF 0x1D5700 +bool BAPAMoveTo::getIsSprinting() +{ + return m_isSprinting; +} + +// ELF 0x1D6880 +bool BAPAMoveTo::getIsMovingAway() +{ + return false; +} + +// ELF 0x1D6890 +Vec2& BAPAMoveTo::getCurrentPoint() +{ + return m_currentPoint; +} + +// ELF 0x1D68A0 +int BAPAMoveTo::update(Vec2&, bool&, bool&, float) +{ + return 0; +} + +// ELF 0x1D68B0: only the end condition. +bool BAPAMoveTo::isFinished(Bot* bot) +{ + bool finished = false; + if (m_endCondition) + finished = m_endCondition->evaluate(bot); + return finished; +} + +// ELF 0x1D68F0 +bool BAPAMoveTo::getSecondPoint(Vec2&) +{ + return false; +} + +// ELF 0x1D6900 +bool BAPAMoveTo::getLargestAngleDiff(float&) +{ + return false; +} + +// ELF 0x1D6910 +float BAPAMoveTo::getTargetDistance() +{ + return 0.0f; +} + +// ELF 0x1D6930 +unsigned int BAPAMoveTo::getObject() +{ + return 0xFFFFFFFFu; +} + +// ELF 0x1D5760: distance from the bot's current vehicle/soldier to the goal (x87 sum z, x, y). +float BAPAMoveTo::getSimpleTargetDistance(Bot* bot) +{ + return std::sqrt(BAPAMoveTo::getSimpleTargetDistanceSqr(bot)); // inline in the image (no virtual call) +} + +// ELF 0x1D5810 (the information is not null-checked) +float BAPAMoveTo::getSimpleTargetDistanceSqr(Bot* bot) +{ + const Vec3& p = bapinline::info(bot->getCurrentEquipment())->getPosition(); + const double dz = static_cast(p.z) - m_coordinate.z; + const double dx = static_cast(p.x) - m_coordinate.x; + const double dy = static_cast(p.y) - m_coordinate.y; + return static_cast(dz * dz + dx * dx + dy * dy); +} + +// ELF 0x1D6940 +bool BAPAMoveTo::isStuck() +{ + return false; +} + +// ELF 0x1D5660: sprinting looks at a point (target -1) or at an object (the point is zeroed). +void BAPAMoveTo::setIsSprinting(Bot* bot, bool sprinting, const Vec3& point, unsigned int target) +{ + m_isSprinting = sprinting; + if (!sprinting) + return; + if (target == 0xFFFFFFFFu) { + bot->getSensingAgent()->setSprintFocus(point); + } else { + bot->getSensingAgent()->setSprintFocusTarget(target); + bot->getSensingAgent()->setSprintFocus(bapinline::vec3(0.0f, 0.0f, 0.0f)); + } +} + +// ELF 0x1D5730 +Vec3& BAPAMoveTo::getCoordinate() +{ + return m_coordinate; +} + +// ELF 0x1D5740 +float BAPAMoveTo::getMaxSpeed() +{ + return m_maxSpeed; +} + +// ELF 0x1D5750 +float BAPAMoveTo::getMaxArriveSpeed() +{ + return m_maxArriveSpeed; +} + +// ELF 0x1D58B0. The XZ direction to walk towards `target`, normalised into `dir`, steering round +// one obstacle (m_obstacle) that updateInfantryMoveToPosWithObstacles picked. The answer is +// cached until m_nextDirTime (always "now", so every call recomputes). Returns true when the +// obstacle code took over (dir untouched) or the bot keeps walking straight past the obstacle. +bool BAPAMoveTo::getTargetDir(Bot* bot, Vec2 target, Vec2& dir, Information* targetInfo, bool flag) +{ + const double now = bapinline::gameTime(); + if (now < m_nextDirTime) { + dir = m_cachedDir; + return m_cachedResult; + } + m_cachedResult = true; + m_nextDirTime = now + 0.0; + + Vec2 pos; + pos.x = 0.0f; + pos.y = 0.0f; + vec3ToVec2XZ(bapinline::info(bot->getCurrentEquipment())->getPosition(), pos); + + if (usesPathfinding() + && (m_obstacle == 0xFFFFFFFFu || needsUpdate(m_avoidPoint, m_obstacle, m_obstacleRadius))) { + Vec2 ahead; + ahead.x = 0.0f; + ahead.y = 0.0f; + bot->getBotNavigation()->getFirstPointBeyondDist(pos, 10.0f, ahead); + if (updateInfantryMoveToPosWithObstacles(bot, ahead, m_coordinate, getObject(), m_avoidPoint, m_obstacle, + m_avoidDistance, m_obstaclePosition, m_obstacleRadius, m_avoiding, + targetInfo, flag)) + return true; + } + + dir.x = target.x - pos.x; + dir.y = target.y - pos.y; + const float distSqr = dir.y * dir.y + dir.x * dir.x; + float dist = std::sqrt(distSqr); + bool passing = false; + + Information* obstacle = bapinline::info(m_obstacle); + if (!obstacle) { + m_obstacle = 0xFFFFFFFFu; + } else { + const float toObsX = m_obstaclePosition.x - pos.x; + const float toObsY = m_obstaclePosition.y - pos.y; + const float fromObsX = pos.x - m_obstaclePosition.x; + const float fromObsY = pos.y - m_obstaclePosition.y; + unsigned int current = m_obstacle; + // -0xE8(%ebp): also the left side of the "(r + 1)^2" test below (0x1D6535), not the target + // distance (audit 2026-11-01). + const float obsDistSqr = fromObsY * fromObsY + fromObsX * fromObsX; + if ((m_obstacleRadius + 1.0f) * (m_obstacleRadius + 1.0f) < obsDistSqr) { + current = 0xFFFFFFFFu; + m_obstacle = 0xFFFFFFFFu; + } + bool isOwnTarget = false; + if (current != 0xFFFFFFFFu) { + unsigned int change = bot->getChangeTarget(); + Information* ci = bapinline::info(change); + if (ci && !ci->isPrimary()) + change = ci->getPrimaryObject(bot->getSide()); + unsigned int repair = bot->getRepairTarget(); + Information* ri = bapinline::info(repair); + if (ri && !ri->isPrimary()) + repair = ri->getPrimaryObject(bot->getSide()); + current = m_obstacle; + isOwnTarget = current == repair || current == change; + } + passing = isOwnTarget; + if (current != 0xFFFFFFFFu) { + if (!isOwnTarget && !m_avoiding) { + passing = toObsY * dir.y + toObsX * dir.x < 0.0f; + if (!passing && targetInfo && dist * dist <= toObsX * toObsX + toObsY * toObsY) + passing = true; + } + Vec2 obsPos; + obsPos.x = 0.0f; + obsPos.y = 0.0f; + vec3ToVec2XZ(obstacle->getPosition(), obsPos); + const float driftX = m_obstaclePosition.x - obsPos.x; + const float driftY = m_obstaclePosition.y - obsPos.y; + if (driftY * driftY + driftX * driftX < 0.25f) { + Vec2 goal; + goal.x = 0.0f; + goal.y = 0.0f; + vec3ToVec2XZ(m_coordinate, goal); + const float toGoalX = goal.x - pos.x; + const float toGoalY = goal.y - pos.y; + const float goalToObs = length2(obsPos.x - goal.x, obsPos.y - goal.y); + const float r = m_obstacleRadius; + const float reach = (r - goalToObs) + 0.8f; + const bool goalClose = toGoalY * toGoalY + toGoalX * toGoalX < reach * reach; + if ((m_avoiding && goalToObs <= r + && (goalClose || (m_avoidDistance < r && obsDistSqr <= (r + 1.0f) * (r + 1.0f)))) + || ((!passing || isOwnTarget) && goalToObs <= r && goalClose)) { + m_cachedDir = dir; + return true; + } + target = m_avoidPoint; + dir.x = target.x - pos.x; + dir.y = target.y - pos.y; + dist = length2(dir.x, dir.y); + } else { + m_obstacle = 0xFFFFFFFFu; + } + } + } + + if (getIsSprinting() && 1.1920929e-07f < std::fabs(target.y - 0.0f) + std::fabs(target.x - 0.0f)) + setIsSprinting(bot, true, bapinline::vec3(target.x, 0.0f, target.y), 0xFFFFFFFFu); + + bool straight = true; + if (m_obstacle != 0xFFFFFFFFu) { + if (dist < 0.3f) + m_obstacle = 0xFFFFFFFFu; + if (m_obstacle != 0xFFFFFFFFu && !passing && 0.5f < dist) { + straight = false; + Vec2 toAvoid; + toAvoid.x = m_avoidPoint.x - pos.x; + toAvoid.y = m_avoidPoint.y - pos.y; + bapinline::normalize(toAvoid); + Vec2 toObs; + toObs.x = m_obstaclePosition.x - pos.x; + toObs.y = m_obstaclePosition.y - pos.y; + bapinline::normalize(toObs); + if (toAvoid.y * toObs.y + toAvoid.x * toObs.x <= 0.05f) { + dir.x *= 1.0f / dist; + dir.y = (1.0f / dist) * dir.y; + } else { + // Step round the obstacle: from its centre through the point one unit towards the + // avoid point, out to m_avoidDistance. + Vec2 out; + out.x = (pos.x + toAvoid.x) - m_obstaclePosition.x; + out.y = (pos.y + toAvoid.y) - m_obstaclePosition.y; + bapinline::normalize(out); + dir.x = (out.x * m_avoidDistance + m_obstaclePosition.x) - pos.x; + dir.y = (m_avoidDistance * out.y + m_obstaclePosition.y) - pos.y; + bapinline::normalize(dir); + } + } + } + if (straight) { + if (0.001f < dist) { + dir.x *= 1.0f / dist; + dir.y = (1.0f / dist) * dir.y; + } else { + dir.x = 1.0f; + dir.y = 0.0f; + } + } + m_cachedDir = dir; + m_cachedResult = false; + return false; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo.h new file mode 100644 index 000000000..9c462a1c3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo.h @@ -0,0 +1,83 @@ +// Move statement base with soldier-pose and obstacle-avoidance state. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETO_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETO_H + +#include "../../../../Math/Vec3.h" +#include "BAPAComponentSoldierPose.h" +#include "BAPAction.h" +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class Information; + +// ELF: vtable 0x4B7F40 (40 words), package C-actions. +// Size 0xB4. Move statement base: the move entries call getTargetDir/update and read the public +// fields below inline. The BAPAComponentSoldierPose part sits at +0x14 (vtable 0x4B7FA8). +class BAPAMoveTo : public BAPAction, public BAPAComponentSoldierPose +{ +public: + explicit BAPAMoveTo(Bot*); // 0x1D5310 + virtual ~BAPAMoveTo(); // 0x1D5550 + + virtual unsigned long long getControls(); // 0x1D5650, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1D5710, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1D5720, slot +0x14; from the base declaration + virtual bool getIsSprinting(); // 0x1D5700, slot +0x20; [INFERRED] ELF bool + virtual bool getIsMovingAway(); // 0x1D6880, slot +0x24 + virtual Vec2& getCurrentPoint(); // 0x1D6890, slot +0x28 (+0x6C) + virtual int update(Vec2&, bool&, bool&, float); // 0x1D68A0, slot +0x2C; ELF bool (`al`), kept int: F's BAPAMoveToDirect overrides it as int + virtual bool isFinished(Bot*); // 0x1D68B0, slot +0x30 + virtual bool getSecondPoint(Vec2&); // 0x1D68F0, slot +0x34 + virtual bool getLargestAngleDiff(float&); // 0x1D6900, slot +0x38 + virtual float getTargetDistance(); // 0x1D6910, slot +0x3C + virtual unsigned int getObject(); // 0x1D6930, slot +0x40 (information handle, -1 = none) + virtual float getSimpleTargetDistance(Bot*); // 0x1D5760, slot +0x44 + virtual float getSimpleTargetDistanceSqr(Bot*); // 0x1D5810, slot +0x48 + virtual int usesPathfinding() = 0; // no body, slot +0x4C (ELF bool; kept int for F/H overrides) + virtual int withinDistance() = 0; // no body, slot +0x50 (ELF bool; kept int for F overrides) + virtual bool isStuck(); // 0x1D6940, slot +0x54 + + void setIsSprinting(Bot*, bool, const Vec3&, unsigned int); // 0x1D5660 + Vec3& getCoordinate(); // 0x1D5730 (+0x44) + float getMaxSpeed(); // 0x1D5740 + float getMaxArriveSpeed(); // 0x1D5750 + bool getTargetDir(Bot*, Vec2, Vec2&, Information*, bool); // 0x1D58B0 + + // Read and written inline by the move entries and the subclasses. [INFERRED] names. + /* +0x40 */ bool m_isSprinting; + /* +0x44 */ Vec3 m_coordinate; // the goal + /* +0x50 */ float m_maxSpeed; + /* +0x54 */ float m_maxArriveSpeed; + /* +0x58 */ BAPCondition* m_endCondition; // owned; isFinished evaluates it + /* +0x5C */ bool m_pathValid; // initPathfinding's answer (BAPAMoveToFinding) + // BoatControl::speedControl (ELF 0x2AA759, 0x2AA802..0x2AA814) reads/writes these samples. + /* +0x60 */ float m_previousSpeed; // = 0 + /* +0x64 */ Vec2 m_previousHeading; // = (1, 0) + /* +0x6C */ Vec2 m_currentPoint; // = 0; updatePath's next point + /* +0x74 */ Vec2 m_vec74; // = 0; [UNRESOLVED] + /* +0x7C */ int m_unwritten7C; // [UNRESOLVED] not written by the constructor + // Obstacle avoidance state of getTargetDir / updateInfantryMoveToPosWithObstacles. + /* +0x80 */ unsigned int m_obstacle; // information handle, -1 = none + /* +0x84 */ Vec2 m_avoidPoint; + /* +0x8C */ float m_obstacleRadius; + /* +0x90 */ float m_avoidDistance; + /* +0x94 */ Vec2 m_obstaclePosition; + /* +0x9C */ bool m_avoiding; + /* +0xA0 */ double m_nextDirTime; // = -1000.0 + /* +0xA8 */ Vec2 m_cachedDir; + /* +0xB0 */ bool m_cachedResult; + +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3d.cpp new file mode 100644 index 000000000..e531732b5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3d.cpp @@ -0,0 +1,126 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1D6F80 (__tcf_0 0x1D6FE0, _GLOBAL__I 0x1D7010): 's Init object only. +#include + +#include "BAPAMoveTo3d.h" + +#include "BAPActionInline.h" +#include "BAPCondition.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/Information.h" +#include "../../../../Math/Mat4.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { +Vec3 row(const Mat4& m, int r) +{ + return bapinline::vec3(m.m[r * 4], m.m[r * 4 + 1], m.m[r * 4 + 2]); +} +} // namespace + +// ELF 0x1D6B90 (C1; C2 0x1D6950). Store order of the image: +0x14 = 0, speeds, condition, point, +// +0x3C = 0, +0x4C/+0x58 = 0, +0x48 distance, the rest 0; then the bot's current equipment (no null +// test): +0x10 pattern id, condition +4 = this, +0x54 = getAltitude (vfn +0x38) of its +// IPIMobile::getSpeed (vfn +0x1C), +8 controls, +0x58/+0x64/+0x70 = transformation rows 2/1/0, +// +0x3C = 0 again. +BAPAMoveTo3d::BAPAMoveTo3d(Bot* bot, const Vec3& point, float maxSpeed, float maxArriveSpeed, + BAPCondition* breakCondition, unsigned long long controls, float distance, int patternId) +{ + m_vec14 = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_maxSpeed = maxSpeed; + m_maxArriveSpeed = maxArriveSpeed; + m_breakCondition = breakCondition; + m_point = point; + m_vec3C = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_int4C = 0; + m_distance = distance; + m_int50 = 0; + m_forward = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_up = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_right = bapinline::vec3(0.0f, 0.0f, 0.0f); + Information* equipment = bapinline::info(bot->getCurrentEquipment()); + m_patternId = patternId; + if (m_breakCondition) + m_breakCondition->setOwner(this); + m_altitude = equipment->getAltitude(equipment->getMobile()->getSpeed()); + m_controls = controls; + m_forward = row(equipment->getTransformation(), 2); + m_right = row(equipment->getTransformation(), 0); + m_up = row(equipment->getTransformation(), 1); + m_vec3C = bapinline::vec3(0.0f, 0.0f, 0.0f); +} + +// ELF 0x1D6E30 (D0 0x1D6E90): deletes the condition (vfn +0x10). +BAPAMoveTo3d::~BAPAMoveTo3d() +{ + if (m_breakCondition) + delete m_breakCondition; +} + +// ELF 0x1D6F00: the entry drives the move; executed directly it answers ok = false, finished = true. +bool BAPAMoveTo3d::execute(Bot*, bool& ok, bool& finished) +{ + ok = false; + finished = true; + return false; +} + +// ELF 0x1D6F20 +unsigned long long BAPAMoveTo3d::getControls() +{ + return m_controls; +} + +// ELF 0x1D7030 +BAPStatementType BAPAMoveTo3d::getId() const +{ + return BAPSTMoveTo; // 7 +} + +// ELF 0x1D6F30 +bool BAPAMoveTo3d::hasDefault() +{ + return false; +} + +// ELF 0x1D7040: the break condition's evaluate (vfn +0), false without one. +bool BAPAMoveTo3d::isFinished(Bot* bot) +{ + bool finished = false; + if (m_breakCondition) + finished = m_breakCondition->evaluate(bot); + return finished; +} + +// ELF 0x1D6F40 +float BAPAMoveTo3d::getMaxSpeed() +{ + return m_maxSpeed; +} + +// ELF 0x1D6F50 +float BAPAMoveTo3d::getMaxArriveSpeed() +{ + return m_maxArriveSpeed; +} + +// ELF 0x1D6F60 +BAPCondition* BAPAMoveTo3d::getBreakCondition() +{ + return m_breakCondition; +} + +// ELF 0x1D6F70 +Vec3* BAPAMoveTo3d::getFirstPoint() +{ + return &m_point; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3d.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3d.h new file mode 100644 index 000000000..d5b213107 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3d.h @@ -0,0 +1,64 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETO3D_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETO3D_H + +#include "../../../../Math/Vec3.h" +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B8080 (9 words), package F-infantry. +// 3d (air) move to a point, driven by its plan entry; execute itself answers false/finished. +// operator new 0x7C (BBPChange::createPlan). +class BAPAMoveTo3d : public BAPAction +{ +public: + BAPAMoveTo3d(Bot*, const Vec3&, float, float, BAPCondition*, unsigned long long, float, int); // 0x1D6B90 + virtual ~BAPAMoveTo3d(); // 0x1D6E30 + + virtual bool execute(Bot*, bool&, bool&); // 0x1D6F00, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1D6F20, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1D7030, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1D6F30, slot +0x14; from the base declaration + virtual bool isFinished(Bot*); // 0x1D7040, slot +0x20; [INFERRED] ELF int + + float getMaxSpeed(); // 0x1D6F40; x87 load of +0x20 + float getMaxArriveSpeed(); // 0x1D6F50; x87 load of +0x24 + BAPCondition* getBreakCondition(); // 0x1D6F60; returns +0x28 (was [INFERRED] int) + Vec3* getFirstPoint(); // 0x1D6F70; returns this + 0x2C (was [INFERRED] int) + +private: + // [INFERRED] friendship: EntryHeliMoveTo reads +0x3C/+0x48 inline (ELF 0x2B69B0). + friend class EntryHeliMoveTo; + // [INFERRED] friendship: EntryPlaneMoveTo reads/writes +0x48/+0x4C/+0x58..+0x78 inline (ELF 0x2C0C80). + friend class EntryPlaneMoveTo; + /* +0x14 */ Vec3 m_vec14; // = 0 [UNRESOLVED] + /* +0x20 */ float m_maxSpeed; + /* +0x24 */ float m_maxArriveSpeed; + /* +0x28 */ BAPCondition* m_breakCondition; // owned (deleted by the destructor), owner = this + /* +0x2C */ Vec3 m_point; // the goal + /* +0x38 */ int m_unwritten38; // not written by the constructor + /* +0x3C */ Vec3 m_vec3C; // [INFERRED] previous velocity sample; EntryHeliMoveTo + /* +0x48 */ float m_distance; // the constructor's 7th argument (createPlan: 25.0) + /* +0x4C */ float m_int4C; // [INFERRED] previous equipment height; EntryPlaneMoveTo + /* +0x50 */ int m_int50; // = 0 [UNRESOLVED] + /* +0x54 */ float m_altitude; // current equipment's getAltitude(its IPIMobile::getSpeed()) + /* +0x58 */ Vec3 m_forward; // current equipment's transformation row 2 + /* +0x64 */ Vec3 m_up; // row 1 + /* +0x70 */ Vec3 m_right; // row 0 +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETO3D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3dDirection.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3dDirection.cpp new file mode 100644 index 000000000..3b087da5d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3dDirection.cpp @@ -0,0 +1,107 @@ +// Three-dimensional direction move recovered from libaidll.so. +// static init: ELF 0x1D7900 (__tcf_0 0x1D7960, _GLOBAL__I 0x1D7990): 's Init object only. +#include +#include "BAPAMoveTo3dDirection.h" +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D71F0 (C1; C2 0x1D7080) +BAPAMoveTo3dDirection::BAPAMoveTo3dDirection(const Vec3& target, float maxSpeed, + float maxArriveSpeed, const Vec3& direction, BAPCondition* condition, + unsigned long long controls, float altitude, int patternId) + : BAPAction(UninitializedPatternId()), m_maxSpeed(maxSpeed), m_maxArriveSpeed(maxArriveSpeed), + m_altitude(altitude), m_vector24(bapinline::vec3(0.0f, 0.0f, 0.0f)), + m_target(target), m_direction(direction), m_forward(bapinline::vec3(0.0f, 0.0f, 0.0f)), + m_up(bapinline::vec3(0.0f, 0.0f, 0.0f)), m_right(bapinline::vec3(0.0f, 0.0f, 0.0f)), + m_endCondition(condition), m_vector70(bapinline::vec3(0.0f, 0.0f, 0.0f)), + m_vector7C(bapinline::vec3(0.0f, 0.0f, 0.0f)), m_state(0), m_initialize(false) +{ + m_patternId = patternId; + m_controls = controls; + if (condition) + condition->setOwner(this); + m_forward = bapinline::vec3(1.0f, 0.0f, 0.0f); + m_right = bapinline::vec3(0.0f, 0.0f, 1.0f); + m_up = bapinline::vec3(0.0f, 1.0f, 0.0f); + m_vector24 = bapinline::vec3(0.0f, 0.0f, 0.0f); +} + +// ELF 0x1D74A0 (C1; C2 0x1D7360) +BAPAMoveTo3dDirection::BAPAMoveTo3dDirection(float distance, float maxSpeed, + float maxArriveSpeed, BAPCondition* condition, unsigned long long controls, + float altitude, int patternId) + : BAPAction(UninitializedPatternId()), m_maxSpeed(maxSpeed), m_maxArriveSpeed(maxArriveSpeed), + m_altitude(altitude), m_vector24(bapinline::vec3(0.0f, 0.0f, 0.0f)), + m_target(bapinline::vec3(0.0f, 0.0f, 0.0f)), m_direction(bapinline::vec3(0.0f, 0.0f, 0.0f)), + m_forward(bapinline::vec3(0.0f, 0.0f, 0.0f)), m_up(bapinline::vec3(0.0f, 0.0f, 0.0f)), + m_right(bapinline::vec3(0.0f, 0.0f, 0.0f)), m_endCondition(condition), + m_vector70(bapinline::vec3(0.0f, 0.0f, 0.0f)), m_vector7C(bapinline::vec3(0.0f, 0.0f, 0.0f)), + m_state(0), m_distance(distance), m_initialize(true) +{ + m_patternId = patternId; + m_controls = controls; + if (condition) + condition->setOwner(this); + m_forward = bapinline::vec3(1.0f, 0.0f, 0.0f); + m_right = bapinline::vec3(0.0f, 0.0f, 1.0f); + m_up = bapinline::vec3(0.0f, 1.0f, 0.0f); +} + +// ELF 0x1D7640 (D1; D2 0x1D75E0, D0 0x1D76A0) +BAPAMoveTo3dDirection::~BAPAMoveTo3dDirection() +{ + delete m_endCondition; +} + +// ELF 0x1D7710 +bool BAPAMoveTo3dDirection::execute(Bot* bot, bool& success, bool& finished) +{ + success = false; + finished = true; + if (m_initialize) { + m_initialize = false; + Information* self = bapinline::info(bot->getCurrentEquipment()); + const Mat4& transform = self->getTransformation(); + m_target = bapinline::vec3(m_distance * transform.m[8] + transform.m[12], + m_distance * transform.m[9] + transform.m[13], + m_distance * transform.m[10] + transform.m[14]); + m_target.y = m_altitude; + Vec3 direction = bapinline::vec3(transform.m[8], 0.0f, transform.m[10]); + bapinline::normalize(direction); + m_direction = direction; + } + return false; +} + +// ELF 0x1D78E0 +unsigned long long BAPAMoveTo3dDirection::getControls() +{ + return m_controls; +} + +// ELF 0x1D79F0 +BAPStatementType BAPAMoveTo3dDirection::getId() const +{ + return BAPSTMoveToDirection; +} + +// ELF 0x1D78F0 +bool BAPAMoveTo3dDirection::hasDefault() +{ + return false; +} + +// ELF 0x1D79B0 +bool BAPAMoveTo3dDirection::isFinished(Bot* bot) +{ + return m_endCondition && m_endCondition->evaluate(bot); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3dDirection.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3dDirection.h new file mode 100644 index 000000000..4107b0bb5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3dDirection.h @@ -0,0 +1,54 @@ +// Three-dimensional direction move with optional first-execution target initialization. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETO3DDIRECTION_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETO3DDIRECTION_H + +#include "../../../../Math/Vec3.h" +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B80C0 (9 words), package H-deferred. +class BAPAMoveTo3dDirection : public BAPAction +{ +public: + BAPAMoveTo3dDirection(const Vec3&, float, float, const Vec3&, BAPCondition*, unsigned long long, float, int); // 0x1D71F0 + BAPAMoveTo3dDirection(float, float, float, BAPCondition*, unsigned long long, float, int); // 0x1D74A0 + virtual ~BAPAMoveTo3dDirection(); // 0x1D7640 + + virtual bool execute(Bot*, bool&, bool&); // 0x1D7710, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1D78E0, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1D79F0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1D78F0, slot +0x14; from the base declaration + virtual bool isFinished(Bot*); // 0x1D79B0, slot +0x20; [INFERRED] ELF int + // [INFERRED] names; plane-interpreter readers distinguish scalar and vector state. + /* +0x14 */ float m_maxSpeed; + /* +0x18 */ float m_maxArriveSpeed; + /* +0x1C */ float m_currentAltitude; // left uninitialized by both constructors + /* +0x20 */ float m_altitude; + /* +0x24 */ Vec3 m_vector24; // [INFERRED] previous velocity sample; EntryHeliMoveToDirection (ELF 0x2B6D30) + /* +0x30 */ Vec3 m_target; + /* +0x3C */ Vec3 m_direction; + /* +0x48 */ Vec3 m_forward; + /* +0x54 */ Vec3 m_up; + /* +0x60 */ Vec3 m_right; + /* +0x6C */ BAPCondition* m_endCondition; + /* +0x70 */ Vec3 m_vector70; + /* +0x7C */ Vec3 m_vector7C; + /* +0x88 */ int m_state; + /* +0x8C */ float m_distance; // first constructor leaves this uninitialized + /* +0x90 */ bool m_initialize; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETO3DDIRECTION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3dObject.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3dObject.cpp new file mode 100644 index 000000000..37b6b33a9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3dObject.cpp @@ -0,0 +1,109 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1D7EF0 (__tcf_0 0x1D7F50, _GLOBAL__I 0x1D7F80): 's Init object only. +#include + +#include "BAPAMoveTo3dObject.h" + +#include "BAPActionInline.h" +#include "BAPCondition.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/Information.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D7B80 (C1; C2 0x1D7A00). Zeroes +0x28..+0x7C and +0x84, stores the arguments, condition +// +4 = this, +0x80 = object has an IPIMobile (only when the information exists), then the three +// axes (+0x74 (1,0,0), +0x68 (0,0,1), +0x5C (0,1,0)) and +0x34 = 0. +BAPAMoveTo3dObject::BAPAMoveTo3dObject(unsigned int object, float f18, float maxSpeed, float maxArriveSpeed, + float distance, BAPCondition* breakCondition, unsigned long long controls, + int patternId) +{ + m_object = object; + m_float18 = f18; + m_maxSpeed = maxSpeed; + m_breakCondition = breakCondition; + m_point = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_maxArriveSpeed = maxArriveSpeed; + m_vec34 = bapinline::vec3(0.0f, 0.0f, 0.0f); + for (int i = 0; i < 4; ++i) + m_int40[i] = 0; + m_distance = distance; + m_up = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_forward = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_right = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_int84 = 0; + m_patternId = patternId; + m_controls = controls; + if (breakCondition) + breakCondition->setOwner(this); + Information* info = bapinline::info(m_object); + if (info) + m_objectMobile = info->getMobile() != 0; + m_right = bapinline::vec3(1.0f, 0.0f, 0.0f); + m_forward = bapinline::vec3(0.0f, 0.0f, 1.0f); + m_up = bapinline::vec3(0.0f, 1.0f, 0.0f); + m_vec34 = bapinline::vec3(0.0f, 0.0f, 0.0f); +} + +// ELF 0x1D7D60 (D0 0x1D7DC0): deletes the condition (vfn +0x10). +BAPAMoveTo3dObject::~BAPAMoveTo3dObject() +{ + if (m_breakCondition) + delete m_breakCondition; +} + +// ELF 0x1D7E30: as BAPAMoveTo3d::execute. +bool BAPAMoveTo3dObject::execute(Bot*, bool& ok, bool& finished) +{ + ok = false; + finished = true; + return false; +} + +// ELF 0x1D7FA0 +unsigned long long BAPAMoveTo3dObject::getControls() +{ + return m_controls; +} + +// ELF 0x1D7FB0 +BAPStatementType BAPAMoveTo3dObject::getId() const +{ + return BAPSTMoveToObject; // 9 +} + +// ELF 0x1D7FC0 +bool BAPAMoveTo3dObject::hasDefault() +{ + return false; +} + +// ELF 0x1D7FD0 +bool BAPAMoveTo3dObject::isFinished(Bot* bot) +{ + bool finished = false; + if (m_breakCondition) + finished = m_breakCondition->evaluate(bot); + return finished; +} + +// ELF 0x1D7E50: refresh +0x28 from the object (getPosition vfn +0x30, or with +0x80 the IPIMobile +// position estimate vfn +0x2C) when it still exists; return it. +Vec3* BAPAMoveTo3dObject::getFirstPoint() +{ + Information* info = bapinline::info(m_object); + if (info) { + if (!m_objectMobile) + m_point = info->getPosition(); + else + info->getMobile()->getPositionEstimate(m_point); + } + return &m_point; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3dObject.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3dObject.h new file mode 100644 index 000000000..9ec7a282d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3dObject.h @@ -0,0 +1,62 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETO3DOBJECT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETO3DOBJECT_H + +#include "../../../../Math/Vec3.h" +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B8100 (9 words), package F-infantry. +// 3d (air) move to an object, driven by its plan entry; execute itself answers false/finished. +// operator new 0x88 (BBPChange::createPlan). +class BAPAMoveTo3dObject : public BAPAction +{ +public: + BAPAMoveTo3dObject(unsigned int, float, float, float, float, BAPCondition*, unsigned long long, int); // 0x1D7B80 + virtual ~BAPAMoveTo3dObject(); // 0x1D7D60 + + virtual bool execute(Bot*, bool&, bool&); // 0x1D7E30, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1D7FA0, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1D7FB0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1D7FC0, slot +0x14; from the base declaration + virtual bool isFinished(Bot*); // 0x1D7FD0, slot +0x20; [INFERRED] ELF int + + Vec3* getFirstPoint(); // 0x1D7E50; refreshes and returns this + 0x28 (was [INFERRED] int) + +private: + // [INFERRED] friendship: EntryHeliMoveToObject reads +0x34/+0x50 inline (ELF 0x2B73E0). + friend class EntryHeliMoveToObject; + // [INFERRED] friendship: EntryPlaneMoveToObject reads/writes +0x14..+0x20/+0x40/+0x50/+0x5C..+0x84 inline (ELF 0x2C2AD0). + friend class EntryPlaneMoveToObject; + /* +0x14 */ unsigned int m_object; // information handle + /* +0x18 */ float m_float18; // createPlan: 0.5 [UNRESOLVED] + /* +0x1C */ float m_maxSpeed; + /* +0x20 */ float m_maxArriveSpeed; + /* +0x24 */ BAPCondition* m_breakCondition; // owned, owner = this + /* +0x28 */ Vec3 m_point; // getFirstPoint: the object's position or position estimate + /* +0x34 */ Vec3 m_vec34; // [INFERRED] previous velocity sample; EntryHeliMoveToObject + /* +0x40 */ float m_int40[4]; // [INFERRED] first element: previous speed magnitude; others [UNRESOLVED] + /* +0x50 */ float m_distance; // createPlan: 25.0 + /* +0x54 */ int m_unwritten54[2]; // not written by the constructor + /* +0x5C */ Vec3 m_up; // (0, 1, 0) + /* +0x68 */ Vec3 m_forward; // (0, 0, 1) + /* +0x74 */ Vec3 m_right; // (1, 0, 0) + /* +0x80 */ bool m_objectMobile; // the object has an IPIMobile (+0x38); only set when it exists + /* +0x84 */ float m_int84; // [INFERRED] previous equipment height; EntryPlaneMoveToObject +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETO3DOBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirect.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirect.cpp new file mode 100644 index 000000000..6bde413cf --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirect.cpp @@ -0,0 +1,62 @@ +// Direct move statement (no pathfinding). Recovered from libaidll.so 1.5.3153 (ia-32); ELF +// addresses on every body. + +#include "BAPAMoveToDirect.h" + +#include "BAPCondition.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1D8330, __tcf_0 0x1D8390, _GLOBAL__I 0x1D83C0). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D8110 (C1; C2 0x1D8010): the base, +0xB4 = (0, 0), the arguments, the end condition's +// owner when there is one, +0x60 = 0, +0x5C = true, the goal in XZ, then the controls. +BAPAMoveToDirect::BAPAMoveToDirect(Bot* bot, const Vec3& coordinate, float maxSpeed, float maxArriveSpeed, + BAPCondition* endCondition, unsigned long long controls, int patternId) + : BAPAMoveTo(bot) +{ + m_goal2d.x = 0.0f; + m_goal2d.y = 0.0f; + m_bot = bot; + m_patternId = patternId; + m_coordinate = coordinate; + m_maxSpeed = maxSpeed; + m_maxArriveSpeed = maxArriveSpeed; + m_endCondition = endCondition; + if (endCondition) + endCondition->setOwner(this); + m_previousSpeed = 0.0f; + m_pathValid = true; + vec3ToVec2XZ(coordinate, m_goal2d); + m_controls = controls; +} + +// ELF 0x1D8250 (D1; D2 0x1D8210, D0 0x1D8290, thunks 0x1D83E0 / 0x1D8400): base only. +BAPAMoveToDirect::~BAPAMoveToDirect() +{ +} + +// ELF 0x1D82E0: runs only through the move entries. +bool BAPAMoveToDirect::execute(Bot*, bool& ok, bool& failed) +{ + ok = false; + failed = true; + return false; +} + +// ELF 0x1D8300: always the goal; neither flag is raised. +int BAPAMoveToDirect::update(Vec2& point, bool& reached, bool& done, float) +{ + point = m_goal2d; + reached = false; + done = false; + return 1; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirect.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirect.h new file mode 100644 index 000000000..bcccaa652 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirect.h @@ -0,0 +1,40 @@ +// Move statement that steers straight at its goal. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETODIRECT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETODIRECT_H + +#include "../../../../Math/Vec3.h" +#include "BAPAMoveTo.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B8140 (40 words), package F-infantry. Steers straight at the goal without +// pathfinding; size 0xC0 (`operator new(0xc0)` in BBPGotoWaypointBoat::createPlan). +class BAPAMoveToDirect : public BAPAMoveTo +{ +public: + BAPAMoveToDirect(Bot*, const Vec3&, float, float, BAPCondition*, unsigned long long, int); // 0x1D8110 + virtual ~BAPAMoveToDirect(); // 0x1D8250 + + virtual bool execute(Bot*, bool&, bool&); // 0x1D82E0, slot +0x00; from the base declaration + virtual int update(Vec2&, bool&, bool&, float); // 0x1D8300, slot +0x2C; from the base declaration + virtual int usesPathfinding() { return 0; } // 0x1D8420 (weak), slot +0x4C + virtual int withinDistance() { return 0; } // 0x1D8430 (weak), slot +0x50 + + /* +0xB4 */ Vec2 m_goal2d; // the goal in XZ; update hands it out + /* +0xBC */ Bot* m_bot; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETODIRECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirection.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirection.cpp new file mode 100644 index 000000000..7d7e49c53 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirection.cpp @@ -0,0 +1,61 @@ +// Direction-move base recovered from libaidll.so. +// static init: ELF 0x1D8600 (__tcf_0 0x1D8660, _GLOBAL__I 0x1D8690): 's Init object only. +#include +#include "BAPAMoveToDirection.h" +#include "BAPCondition.h" +#include "BAPActionInline.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D8520 (C1; C2 0x1D8440) +BAPAMoveToDirection::BAPAMoveToDirection() + : BAPAction(UninitializedPatternId()), + BAPAComponentSoldierPose(SPStanding, SPLying, 1.0f, SPCrouching, 0.0f, 0xFFFFFFFFu, 5.0f), + m_point(bapinline::vec3(0.0f, 0.0f, 0.0f)), + m_direction(bapinline::vec3(0.0f, 0.0f, 0.0f)), + m_state68(bapinline::vec3(0.0f, 0.0f, 0.0f)) +{ +} + +// ELF 0x1D8740 (D1; D0 0x1D87D0) +BAPAMoveToDirection::~BAPAMoveToDirection() +{ +} + +// ELF 0x1D86B0 +unsigned long long BAPAMoveToDirection::getControls() +{ + return m_controls; +} + +// ELF 0x1D86C0 +BAPStatementType BAPAMoveToDirection::getId() const +{ + return BAPSTMoveToDirection; +} + +// ELF 0x1D86D0 +bool BAPAMoveToDirection::hasDefault() +{ + return false; +} + +// ELF 0x1D86E0: the Boolean reference is deliberately untouched. +int BAPAMoveToDirection::update(Vec2& point, bool&) +{ + point.x = m_point.x; + point.y = m_point.z; + return 1; +} + +// ELF 0x1D8700 +bool BAPAMoveToDirection::isFinished(Bot* bot) +{ + return m_endCondition && m_endCondition->evaluate(bot); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirection.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirection.h new file mode 100644 index 000000000..c3935816c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirection.h @@ -0,0 +1,55 @@ +// Direction-move state shared by the direct and finding variants; derived classes own its conditions. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETODIRECTION_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETODIRECTION_H + +#include "../../../../Math/Vec3.h" +#include "BAPAComponentSoldierPose.h" +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BAPCondition; + +// ELF: vtable 0x4B8200 (32 words). +class BAPAMoveToDirection : public BAPAction, public BAPAComponentSoldierPose +{ +public: + BAPAMoveToDirection(); // 0x1D8520 + virtual ~BAPAMoveToDirection(); // 0x1D8740 + + virtual unsigned long long getControls(); // 0x1D86B0, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1D86C0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1D86D0, slot +0x14; from the base declaration + virtual int update(Vec2&, bool&); // 0x1D86E0, slot +0x20; [INFERRED] ELF int + virtual bool isFinished(Bot*); // 0x1D8700, slot +0x24; [INFERRED] ELF int + // [CHOSEN, not recovered] Names and integer types under AGENTS.md's unimplemented-slot exception. + // Pure in base/Direct/Finding: ia-32 vtables 0x4B8200/0x4B82C0/0x4B8360, + // amd-64 0x614D80/0x614EE0/0x615000, primary slots 10/11 (+0x28/+0x2C; +0x50/+0x58). + // EntryBoatMoveToDirection calls 0x2B2DFA / amd-64 0x2FF5CA pass only this; + // dec eax compares the full 32-bit result with 1, so a byte/bool return is insufficient. + virtual int unimplementedDirectionSlot10() = 0; + // Calls 0x2B2E5C (also reached from 0x2B30D7) / amd-64 0x2FF78D/0x2FF7A9: + // stack this,int 1|2 / rdi=this,esi=1|2; no caller consumes the result. + virtual void unimplementedDirectionSlot11(int) = 0; + // [INFERRED] names; constructors and interpreter readers attest the member sequence. + /* +0x40 */ Vec3 m_point; + /* +0x4C */ float m_maxSpeed; + /* +0x50 */ float m_maxArriveSpeed; + /* +0x54 */ Vec3 m_direction; + /* +0x60 */ BAPCondition* m_endCondition; + /* +0x64 */ BAPCondition* m_condition64; + /* +0x68 */ Vec3 m_state68; // [INFERRED] previous signed speed, then XZ facing; EntryTankMoveToDirection (ELF 0x2C4800) + /* +0x74 */ bool m_flag74; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETODIRECTION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirectionDirect.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirectionDirect.cpp new file mode 100644 index 000000000..63116c3a6 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirectionDirect.cpp @@ -0,0 +1,67 @@ +// Direct direction move recovered from libaidll.so. +// static init: ELF 0x1D8E30 (__tcf_0 0x1D8E90, _GLOBAL__I 0x1D8EC0): 's Init object only. +#include +#include "BAPAMoveToDirectionDirect.h" +#include "BAPCondition.h" +#include "BAPActionInline.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D8A30 (C1; C2 0x1D8860) +BAPAMoveToDirectionDirect::BAPAMoveToDirectionDirect(Bot*, Vec3& point, Vec3& direction, + float maxSpeed, float maxArriveSpeed, BAPCondition* condition, BAPCondition* endCondition, + unsigned long long controls, int patternId) + : BAPAMoveToDirection() +{ + m_firstPoint.x = 0.0f; + m_firstPoint.y = 0.0f; + m_condition64 = condition; + condition->setOwner(this); + m_patternId = patternId; + m_point = point; + m_maxSpeed = maxSpeed; + m_maxArriveSpeed = maxArriveSpeed; + m_endCondition = endCondition; + if (endCondition) + endCondition->setOwner(this); + m_state68.x = 0.0f; + m_flag74 = true; + m_direction = direction; + bapinline::normalize(m_direction); + vec3ToVec2XZ(point, m_firstPoint); + m_controls = controls; +} + +// ELF 0x1D8CA0 (D1; D2 0x1D8C00, D0 0x1D8D40) +BAPAMoveToDirectionDirect::~BAPAMoveToDirectionDirect() +{ + delete m_endCondition; + delete m_condition64; +} + +// ELF 0x1D8DE0 +bool BAPAMoveToDirectionDirect::execute(Bot*, bool& success, bool& finished) +{ + success = false; + finished = true; + return false; +} + +// ELF 0x1D8E00 +Vec2* BAPAMoveToDirectionDirect::getFirstPoint() +{ + return &m_firstPoint; +} + +// ELF 0x1D8E10 +Vec2* BAPAMoveToDirectionDirect::getSecondPoint(bool& flag) +{ + flag = m_flag74; + return &m_firstPoint; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirectionDirect.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirectionDirect.h new file mode 100644 index 000000000..188a95347 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirectionDirect.h @@ -0,0 +1,36 @@ +// Direct direction move with two owned conditions. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETODIRECTIONDIRECT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETODIRECTIONDIRECT_H + +#include "../../../../Math/Vec3.h" +#include "BAPAMoveToDirection.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B82C0 (30 words), package H-deferred. +class BAPAMoveToDirectionDirect : public BAPAMoveToDirection +{ +public: + BAPAMoveToDirectionDirect(Bot*, Vec3&, Vec3&, float, float, BAPCondition*, BAPCondition*, unsigned long long, int); // 0x1D8A30 + virtual ~BAPAMoveToDirectionDirect(); // 0x1D8CA0 + + virtual bool execute(Bot*, bool&, bool&); // 0x1D8DE0, slot +0x00; from the base declaration + + Vec2* getFirstPoint(); // ELF 0x1D8E00; [INFERRED] pointer spelling; returns the member address + Vec2* getSecondPoint(bool&); // ELF 0x1D8E10; [INFERRED] pointer spelling + + /* +0x78 */ Vec2 m_firstPoint; // [INFERRED] name +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETODIRECTIONDIRECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirectionFinding.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirectionFinding.cpp new file mode 100644 index 000000000..03afb9709 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirectionFinding.cpp @@ -0,0 +1,74 @@ +// Finding direction move recovered from libaidll.so. +// static init: ELF 0x1D95F0 (__tcf_0 0x1D9650, _GLOBAL__I 0x1D9680): 's Init object only. +#include +#include "BAPAMoveToDirectionFinding.h" +#include "BAPCondition.h" +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIMobile.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D9170 (C1; C2 0x1D8F20) +BAPAMoveToDirectionFinding::BAPAMoveToDirectionFinding(Bot* bot, Vec3& point, Vec3& direction, + float maxSpeed, float maxArriveSpeed, BAPCondition* condition, BAPCondition* endCondition, + unsigned long long controls, int patternId) + : BAPAMoveToDirection() +{ + m_firstPoint.x = m_firstPoint.y = 0.0f; + m_secondPoint.x = m_secondPoint.y = 0.0f; + Vec2 position = {0.0f, 0.0f}; + Information* self = bapinline::info(bot->getCurrentEquipment()); + m_condition64 = condition; + condition->setOwner(this); + m_patternId = patternId; + m_point = point; + m_maxSpeed = maxSpeed; + m_maxArriveSpeed = maxArriveSpeed; + m_endCondition = endCondition; + if (endCondition) + endCondition->setOwner(this); + m_flag74 = true; + m_state68.x = 0.0f; + m_direction = direction; + bapinline::normalize(m_direction); + self->getMobile()->getVehicleNumber(); + // Shipped calls discard both results; neither stored path point is updated. + vec3ToVec2XZ(self->getPosition(), position); + m_controls = controls; +} + +// ELF 0x1D9460 (D1; D2 0x1D93C0, D0 0x1D9500) +BAPAMoveToDirectionFinding::~BAPAMoveToDirectionFinding() +{ + delete m_endCondition; + delete m_condition64; +} + +// ELF 0x1D95A0 +bool BAPAMoveToDirectionFinding::execute(Bot*, bool& success, bool& finished) +{ + success = false; + finished = true; + return false; +} + +// ELF 0x1D95C0 +Vec2* BAPAMoveToDirectionFinding::getFirstPoint() +{ + return &m_firstPoint; +} + +// ELF 0x1D95D0 +Vec2* BAPAMoveToDirectionFinding::getSecondPoint(bool& flag) +{ + flag = m_flag74; + return &m_secondPoint; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirectionFinding.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirectionFinding.h new file mode 100644 index 000000000..30ff2a0f5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirectionFinding.h @@ -0,0 +1,37 @@ +// Direction move retaining the shipped zero-valued path points. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETODIRECTIONFINDING_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETODIRECTIONFINDING_H + +#include "../../../../Math/Vec3.h" +#include "BAPAMoveToDirection.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B8360 (30 words), package H-deferred. +class BAPAMoveToDirectionFinding : public BAPAMoveToDirection +{ +public: + BAPAMoveToDirectionFinding(Bot*, Vec3&, Vec3&, float, float, BAPCondition*, BAPCondition*, unsigned long long, int); // 0x1D9170 + virtual ~BAPAMoveToDirectionFinding(); // 0x1D9460 + + virtual bool execute(Bot*, bool&, bool&); // 0x1D95A0, slot +0x00; from the base declaration + + Vec2* getFirstPoint(); // ELF 0x1D95C0; [INFERRED] pointer spelling + Vec2* getSecondPoint(bool&); // ELF 0x1D95D0; [INFERRED] pointer spelling + + /* +0x78 */ Vec2 m_firstPoint; // [INFERRED] names + /* +0x80 */ Vec2 m_secondPoint; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETODIRECTIONFINDING_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToFinding.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToFinding.cpp new file mode 100644 index 000000000..6338095e3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToFinding.cpp @@ -0,0 +1,231 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1DA4D0 (__tcf_0 0x1DA530, _GLOBAL__I 0x1DA560): 's Init object only. +#include + +#include "BAPAMoveToFinding.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotNavigation.h" +#include "../AIBot/SquadManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../Main/IAIPathfinding.h" +#include "../Main/IBotManager.h" +#include "../AIBot/SquadMember.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D9880 (C1; C2 0x1D96E0). The bot's getCurrentEquipment() result is discarded. +BAPAMoveToFinding::BAPAMoveToFinding(Bot* bot, const Vec3& coordinate, float maxSpeed, float maxArriveSpeed, + BAPCondition* endCondition, unsigned long long controls, int patternId, + float maxDistance, float minDistance) + : BAPAMoveTo(bot) +{ + m_flagD4 = false; + m_flagD5 = false; + m_intD8 = 1; + for (int i = 0; i < 8; ++i) + m_zeroB4[i] = 0; + m_bot = bot; + m_maxDistance = maxDistance; + m_minDistance = minDistance; + m_maxDistanceSqr = maxDistance * maxDistance; + m_minDistanceSqr = minDistance * minDistance; + m_pathDone = false; + bot->getCurrentEquipment(); + m_patternId = patternId; + m_coordinate = coordinate; + m_maxSpeed = maxSpeed; + m_maxArriveSpeed = maxArriveSpeed; + m_endCondition = endCondition; + if (endCondition) + endCondition->setOwner(this); + m_previousSpeed = 0.0f; + m_pathValid = true; + m_pathStarted = false; + m_controls = controls; + m_alternative.x = 0.0f; + m_alternative.y = 0.0f; +} + +// ELF 0x1D9A60 (D0 0x1D9AA0, thunk 0x1DA5A0): base only. +BAPAMoveToFinding::~BAPAMoveToFinding() +{ +} + +// ELF 0x1D9AF0: runs only through the move entries. +bool BAPAMoveToFinding::execute(Bot*, bool& ok, bool& failed) +{ + ok = false; + failed = true; + return false; +} + +// ELF 0x1DA420 +void BAPAMoveToFinding::streamSelf(std::ostream& out) const +{ + IBotManager::instance->tabulate(out); + out << "MoveToFinding(" << static_cast(m_minDistance) << ", " << static_cast(m_maxDistance) + << ")" << std::endl; +} + +// ELF 0x1D9B10. Next path point into `point`; `reached`/`done` as the entries expect (the float +// argument is not read). A bot that waits for repairs, or whose vehicle is in the air but not in +// water, stops (reached = false, done = true). Pathfinding restarts when the goal moved or the +// search is not running; inside the ring [min + 1] round the goal a valid ring point is searched +// in 0.5 rad steps. Finally artillery: a target point in a danger zone the bot is not in stops +// the move; a soldier in a danger zone whose squad member avoids artillery sprints. +int BAPAMoveToFinding::update(Vec2& point, bool& reached, bool& done, float) +{ + Information* self = bapinline::info(m_bot->getCurrentEquipment()); + if (static_cast(m_bot)->getShouldWaitForRepairs() + || (self->getPhysical()->isInAir() && !self->getPhysical()->isInWater())) { + reached = false; + done = true; + return 1; + } + + bool restart = !m_pathStarted; + if (!restart) { + BotNavigation* nav = m_bot->getBotNavigation(); + const Vec3& goal = nav->getGoal(); + const bool sameGoal = std::fabs(m_coordinate.x - goal.x) <= 1.1920929e-07f + && std::fabs(m_coordinate.y - goal.y) <= 1.1920929e-07f + && std::fabs(m_coordinate.z - goal.z) <= 1.1920929e-07f; + restart = !sameGoal || !m_bot->getBotNavigation()->isSearchActive(); + } + if (restart) { + m_pathStarted = true; + m_pathValid = m_bot->getBotNavigation()->initPathfinding(m_coordinate, 0.0f, m_maxDistance); + } + + bool result = false; + if (m_pathValid + && m_bot->getBotNavigation()->updatePath(m_currentPoint, m_pathDone, done, 0.0f)) { + result = true; + point = m_currentPoint; + reached = m_pathDone; + } + + const float distance = getSimpleTargetDistance(m_bot); + if (!(m_minDistance + 1.0f > distance) || !(m_minDistance > 1.0f)) { // 0x1D9C57 / 0x1D9C61 jbe + if (done) + goto finish; + if (isFinished(m_bot)) { + m_pathValid = true; + reached = true; + m_pathDone = true; + point = m_currentPoint; + result = true; + } + } else { + if (1.1920929e-07f < std::fabs(m_alternative.y - 0.0f) + std::fabs(m_alternative.x - 0.0f)) { + IPIMobile* mobile = self->getMobile(); + const int equipment = self->getUnit()->getEquipmentType(); + float angle = 0.0f; + bool valid; + do { + const float s = std::sin(angle); + const float c = std::cos(angle); + const float r = m_minDistance + 1.0f; + Vec3 p = bapinline::vec3(s * r + m_coordinate.x, r * 0.0f + m_coordinate.y, r * c + m_coordinate.z); + valid = IAIPathfinding::instance->isValidPosition(mobile->getVehicleNumber(), equipment, p, true); + if (valid) + vec3ToVec2XZ(p, m_alternative); + angle += 0.5f; + if (6.2831855f <= angle) { + if (!valid) + return 0; + break; + } + } while (!valid); + } + point = m_alternative; + } + + if (!done) { + const Vec3 target = bapinline::vec3(point.x, self->getPosition().y, point.y); + double sinceStart; + int artillerySide; + if (!self->isOfType(ITAir)) { + const int side = m_bot->getSide(); + if (SquadManager::m_instance->isInArtilleryDangerZone(target, side, sinceStart, artillerySide) + && !SquadManager::m_instance->isInArtilleryDangerZone(self->getPosition(), m_bot->getSide(), + sinceStart, artillerySide)) { + done = true; + goto finish; + } + } + if (self->isOfType(ITSoldier)) { + SquadMember* member; + if (SquadManager::m_instance->isInArtilleryDangerZone(self->getPosition(), m_bot->getSide(), sinceStart, + artillerySide) + && (member = m_bot->getSquadMember()) != 0 && member->isAvoidingArtillery()) + setIsSprinting(m_bot, true, target, 0xFFFFFFFFu); + } + } + +finish: + if (!result) + m_pathStarted = false; + return result; +} + +// ELF 0x1DA3B0: end condition or within distance; then BotNavigation::clearProgress. +bool BAPAMoveToFinding::isFinished(Bot* bot) +{ + if ((!m_endCondition || !m_endCondition->evaluate(bot)) && !withinDistance()) + return false; + bot->getBotNavigation()->clearProgress(); + return true; +} + +// ELF 0x1DA260 +bool BAPAMoveToFinding::getSecondPoint(Vec2& point) +{ + return m_bot->getBotNavigation()->getSecondPoint(point); +} + +// ELF 0x1DA2B0 +bool BAPAMoveToFinding::getLargestAngleDiff(float& angle) +{ + return m_bot->getBotNavigation()->getLargestAngleDiff(angle); +} + +// ELF 0x1DA300: BotNavigation +0xBC. +float BAPAMoveToFinding::getTargetDistance() +{ + return m_bot->getBotNavigation()->getTargetDistance(); +} + +// ELF 0x1DA5C0 +int BAPAMoveToFinding::usesPathfinding() +{ + return 1; +} + +// ELF 0x1DA360: min^2 <= d^2 <= max^2. +int BAPAMoveToFinding::withinDistance() +{ + const float d = getSimpleTargetDistanceSqr(m_bot); + return (d <= m_maxDistanceSqr && m_minDistanceSqr <= d) ? 1 : 0; +} + +// ELF 0x1DA330: BotNavigation +0xC0. +bool BAPAMoveToFinding::isStuck() +{ + return m_bot->getBotNavigation()->getIsStuck(); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToFinding.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToFinding.h new file mode 100644 index 000000000..67ddbc371 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToFinding.h @@ -0,0 +1,61 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETOFINDING_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETOFINDING_H + +#include +#include "../../../../Math/Vec3.h" +#include "BAPAMoveTo.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B8440 (40 words), package C-actions. +// Moves to a point with the bot's pathfinding (BotNavigation), finishing between the +// minimum and maximum distance. +class BAPAMoveToFinding : public BAPAMoveTo +{ +public: + BAPAMoveToFinding(Bot*, const Vec3&, float, float, BAPCondition*, unsigned long long, int, float, float); // 0x1D9880 + virtual ~BAPAMoveToFinding(); // 0x1D9A60 + + virtual bool execute(Bot*, bool&, bool&); // 0x1D9AF0, slot +0x00; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1DA420, slot +0x1C; from the base declaration + virtual int update(Vec2&, bool&, bool&, float); // 0x1D9B10, slot +0x2C; from the base declaration + virtual bool isFinished(Bot*); // 0x1DA3B0, slot +0x30; from the base declaration + virtual bool getSecondPoint(Vec2&); // 0x1DA260, slot +0x34; from the base declaration + virtual bool getLargestAngleDiff(float&); // 0x1DA2B0, slot +0x38; from the base declaration + virtual float getTargetDistance(); // 0x1DA300, slot +0x3C; from the base declaration + virtual int usesPathfinding(); // 0x1DA5C0, slot +0x4C; from the base declaration + virtual int withinDistance(); // 0x1DA360, slot +0x50; from the base declaration + virtual bool isStuck(); // 0x1DA330, slot +0x54; from the base declaration + +private: + /* +0xB4 */ int m_zeroB4[8]; // +0xB4..+0xD0 = 0; [UNRESOLVED] + /* +0xD4 */ bool m_flagD4; // = false; [UNRESOLVED] + /* +0xD5 */ bool m_flagD5; // = false; [UNRESOLVED] + /* +0xD8 */ int m_intD8; // = 1; [UNRESOLVED] + /* +0xDC */ Bot* m_bot; + /* +0xE0 */ float m_maxDistance; // last-but-one ctor float; initPathfinding's radius + /* +0xE4 */ float m_minDistance; // last ctor float + /* +0xE8 */ float m_maxDistanceSqr; + /* +0xEC */ float m_minDistanceSqr; + /* +0xF0 */ Vec2 m_alternative; // valid point on the ring round the goal + /* +0xF8 */ bool m_pathDone; // updatePath's flag + /* +0xF9 */ bool m_pathStarted; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETOFINDING_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObject.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObject.cpp new file mode 100644 index 000000000..5d9b558de --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObject.cpp @@ -0,0 +1,111 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1DAA60 (__tcf_0 0x1DAAC0, _GLOBAL__I 0x1DAAF0): 's Init object only. +#include + +#include "BAPAMoveToObject.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotNavigation.h" +#include "../AIKnowledge/Information.h" +#include "../Main/IBotManager.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1DA690 (C1; C2 0x1DA5D0) +BAPAMoveToObject::BAPAMoveToObject(Bot* bot, unsigned int object, float distance, float maxSpeed, + float maxArriveSpeed, BAPCondition* endCondition, + unsigned long long controls, int patternId) + : BAPAMoveTo(bot) +{ + m_object = object; + m_distance = distance; + m_distanceSqr = distance * distance; + m_maxSpeed = maxSpeed; + m_maxArriveSpeed = maxArriveSpeed; + m_controls = controls; + m_patternId = patternId; + m_endCondition = endCondition; + if (endCondition) + endCondition->setOwner(this); +} + +// ELF 0x1DAB50 (D0 0x1DABB0, thunk 0x1DAC00): base only. +BAPAMoveToObject::~BAPAMoveToObject() +{ +} + +// ELF 0x1DA7D0: runs only through the move entries. +bool BAPAMoveToObject::execute(Bot*, bool& ok, bool& failed) +{ + ok = false; + failed = true; + return false; +} + +// ELF 0x1DAB10 +unsigned long long BAPAMoveToObject::getControls() +{ + return m_controls; +} + +// ELF 0x1DAB20 +BAPStatementType BAPAMoveToObject::getId() const +{ + return BAPSTMoveToObject; // 9 +} + +// ELF 0x1DAB30 +bool BAPAMoveToObject::hasDefault() +{ + return false; +} + +// ELF 0x1DA9A0: the id is printed as a number here (this TU has no operator<< for the enum). +void BAPAMoveToObject::streamSelf(std::ostream& out) const +{ + IBotManager::instance->tabulate(out); + out << static_cast(getId()) << "(" << static_cast(m_distance) << ")" << std::endl; +} + +// ELF 0x1DA750: end condition or within m_distance; then BotNavigation::clearProgress. +bool BAPAMoveToObject::isFinished(Bot* bot) +{ + if ((!m_endCondition || !m_endCondition->evaluate(bot)) && m_distanceSqr <= getSimpleTargetDistanceSqr(bot)) + return false; + bot->getBotNavigation()->clearProgress(); + return true; +} + +// ELF 0x1DAB40 +unsigned int BAPAMoveToObject::getObject() +{ + return m_object; +} + +// ELF 0x1DA7F0 +float BAPAMoveToObject::getSimpleTargetDistance(Bot* bot) +{ + return std::sqrt(BAPAMoveToObject::getSimpleTargetDistanceSqr(bot)); // inline in the image (no virtual call) +} + +// ELF 0x1DA8E0: neither information is null-checked. +float BAPAMoveToObject::getSimpleTargetDistanceSqr(Bot* bot) +{ + const Vec3& a = bapinline::info(bot->getCurrentEquipment())->getPosition(); + const Vec3& b = bapinline::info(m_object)->getPosition(); + const double dz = static_cast(a.z) - b.z; + const double dx = static_cast(a.x) - b.x; + const double dy = static_cast(a.y) - b.y; + return static_cast(dz * dz + dx * dx + dy * dy); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObject.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObject.h new file mode 100644 index 000000000..26b98bfca --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObject.h @@ -0,0 +1,48 @@ +// Object-targeted move base; owns its optional end condition through BAPAMoveTo. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETOOBJECT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETOOBJECT_H + +#include +#include "BAPAMoveTo.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B8500 (40 words), package C-actions. +// Moves to an object until within m_distance (or the end condition holds). +class BAPAMoveToObject : public BAPAMoveTo +{ +public: + BAPAMoveToObject(Bot*, unsigned int, float, float, float, BAPCondition*, unsigned long long, int); // 0x1DA690 + virtual ~BAPAMoveToObject(); // 0x1DAB50 + + virtual bool execute(Bot*, bool&, bool&); // 0x1DA7D0, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1DAB10, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1DAB20, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1DAB30, slot +0x14; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1DA9A0, slot +0x1C; from the base declaration + virtual bool isFinished(Bot*); // 0x1DA750, slot +0x30; from the base declaration + virtual unsigned int getObject(); // 0x1DAB40, slot +0x40; from the base declaration + virtual float getSimpleTargetDistance(Bot*); // 0x1DA7F0, slot +0x44; from the base declaration + virtual float getSimpleTargetDistanceSqr(Bot*); // 0x1DA8E0, slot +0x48; from the base declaration + + + /* +0xB4 */ unsigned int m_object; // information handle + /* +0xB8 */ float m_distance; + /* +0xBC */ float m_distanceSqr; + /* +0xC0 */ bool m_pathValid2; // not written here; BAPAMoveToObjectFinding sets it (initPathfinding's answer); [UNRESOLVED] name + +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETOOBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectDirect.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectDirect.cpp new file mode 100644 index 000000000..05d0acb84 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectDirect.cpp @@ -0,0 +1,52 @@ +// Direct object-move point source recovered from libaidll.so. +// static init: ELF 0x1DAF30 (__tcf_0 0x1DAF90, _GLOBAL__I 0x1DAFC0): 's Init object only. +#include +#include "BAPAMoveToObjectDirect.h" +#include "BAPActionInline.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIMobile.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1DACE0 (C1; C2 0x1DAC20) +BAPAMoveToObjectDirect::BAPAMoveToObjectDirect(Bot* bot, unsigned int object, + float distance, float maxSpeed, float maxArriveSpeed, BAPCondition* endCondition, + unsigned long long controls, int patternId) + : BAPAMoveToObject(bot, object, distance, maxSpeed, maxArriveSpeed, endCondition, + controls, patternId) +{ + m_isMobile = bapinline::info(object)->getMobile() != 0; +} + +// ELF 0x1DADE0 (D1; D2 0x1DADA0, D0 0x1DAE20) +BAPAMoveToObjectDirect::~BAPAMoveToObjectDirect() +{ +} + +// ELF 0x1DAE70 +Vec2& BAPAMoveToObjectDirect::getCurrentPoint() +{ + Information* object = bapinline::info(m_object); + if (object) { + if (m_isMobile) { + Vec3 position = bapinline::vec3(0.0f, 0.0f, 0.0f); + object->getMobile()->getPositionEstimate(position); + vec3ToVec2XZ(position, m_currentPoint); + } else { + vec3ToVec2XZ(object->getPosition(), m_currentPoint); + } + } + return m_currentPoint; +} + +// ELF 0x1DB020 +int BAPAMoveToObjectDirect::usesPathfinding() +{ + return 0; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectDirect.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectDirect.h new file mode 100644 index 000000000..e9c0c9427 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectDirect.h @@ -0,0 +1,36 @@ +// Direct object-move point source; mobile availability is captured at construction. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETOOBJECTDIRECT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETOOBJECTDIRECT_H + +#include "BAPAMoveToObject.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B85C0 (40 words), package H-deferred. +class BAPAMoveToObjectDirect : public BAPAMoveToObject +{ +public: + BAPAMoveToObjectDirect(Bot*, unsigned int, float, float, float, BAPCondition*, unsigned long long, int); // 0x1DACE0 + virtual ~BAPAMoveToObjectDirect(); // 0x1DADE0 + + virtual Vec2& getCurrentPoint(); // 0x1DAE70, slot +0x28; from the base declaration + virtual int usesPathfinding(); // 0x1DB020, slot +0x4C; from the base declaration +private: + // [UNRESOLVED] Unaccessed bytes before the mobile flag. Both images leave the span unwritten; + // retain its extent without assigning a semantic member type (ia-32 +0xC1..+0xC7). + unsigned char m_unwrittenC1[7]; + /* +0xC8 */ bool m_isMobile; // [INFERRED] name; amd-64 +0xE8 +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETOOBJECTDIRECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectFinding.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectFinding.cpp new file mode 100644 index 000000000..50859d443 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectFinding.cpp @@ -0,0 +1,500 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1DD560 (__tcf_0 0x1DD5C0, _GLOBAL__I 0x1DD5F0): 's Init object only. +#include + +#include "BAPAMoveToObjectFinding.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotNavigation.h" +#include "../AIKnowledge/Information.h" +#include "../AIBot/SensedObject.h" +#include "../AIBot/SquadManager.h" +#include "../AIBot/SquadMember.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../Main/AIDllFrontier.h" +#include "../Main/IAIPathfinding.h" +#include "../Main/IBotManager.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1DB1A0 (C1; C2 0x1DB030) +BAPAMoveToObjectFinding::BAPAMoveToObjectFinding(Bot* bot, unsigned int object, float distance, float maxSpeed, + float maxArriveSpeed, BAPCondition* endCondition, + unsigned long long controls, int patternId, + BAPCondition* replanCondition, float minDistance, int index) + : BAPAMoveToObject(bot, object, distance, maxSpeed, maxArriveSpeed, endCondition, controls, patternId) +{ + m_flagE9 = false; + m_intEC = 1; + m_bot = bot; + for (int i = 0; i < 8; ++i) + m_zeroC8[i] = 0; + m_flagF8 = true; + m_replanCondition = replanCondition; + m_pathDone = false; + m_movingAway = false; + m_pathStarted = false; + m_minDistance = minDistance; + m_minDistanceSqr = minDistance * minDistance; + m_index = index; + m_lastInitTime = -1.0; + if (m_distance < minDistance) { + m_minDistance = m_distance; + m_minDistanceSqr = m_distanceSqr; + } + if (m_replanCondition) + m_replanCondition->setOwner(this); + m_flag107 = false; + m_pathValid2 = true; +} + +// ELF 0x1DC0C0 (D1; D0 0x1DC140, thunk 0x1DD630): deletes the replan condition. +BAPAMoveToObjectFinding::~BAPAMoveToObjectFinding() +{ + if (m_replanCondition) + delete m_replanCondition; +} + +// ELF 0x1DD430 +void BAPAMoveToObjectFinding::streamSelf(std::ostream& out) const +{ + IBotManager::instance->tabulate(out); + out << "MoveToObjectFinding"; + if (m_index != -1) + out << "[" << m_index << "]"; + out << "(" << static_cast(m_minDistance) << ", " << static_cast(m_distance) << ")" << std::endl; +} + +// ELF 0x1DD660 +bool BAPAMoveToObjectFinding::getIsMovingAway() +{ + return m_movingAway; +} + +namespace { + +bool sameVec3(const Vec3& a, const Vec3& b) +{ + return std::fabs(a.x - b.x) <= 1.1920929e-07f && std::fabs(a.y - b.y) <= 1.1920929e-07f + && std::fabs(a.z - b.z) <= 1.1920929e-07f; +} + +} // namespace + +// ELF 0x1DC1C0. Path to the object's last valid position. Fails (m_pathValid2 = false, 0) without +// the bot's or the object's information, the object's primary mobile, a valid position for the +// object, or (soldier, close in height) an active weapon; a bot without a valid position is +// marked stuck. A bot waiting for repairs or airborne out of water: reached = false, done, 1. +// Re-plans (initObjectFinding) when: the object is sensed only indirectly and its last valid +// position moved (once, m_flag107, and not while flanking with the path unfinished); the +// navigation goal is not m_coordinate; every second, when closer than m_minDistance and not +// flanking, or flanking with the target within m_minDistance of the goal and the path done, or +// with the path done, not within distance and the target moved; the search is not running +// (a fresh start: zero direction/origin, flag true); or every second when the re-plan condition +// holds (after it was false, or with the path done). Then updatePath (the float is passed on); +// a target point inside an artillery zone the bot is not in stops the move (done). A soldier +// chasing (not flanking) within 2 m of height sprints at the object while the path is shorter +// than its physical's radius + 25 (unless firing a weapon with range > 5 that is not type 4), +// otherwise stops sprinting; in an artillery zone with an avoiding squad member it sprints at +// the point. isFinished then completes the move. +int BAPAMoveToObjectFinding::update(Vec2& point, bool& reached, bool& done, float distance) +{ + BotMain* bot = static_cast(m_bot); + Information* self = bapinline::info(bot->getCurrentEquipment()); + if (!self || !m_pathValid2) { + m_pathValid2 = false; + return 0; + } + if (bot->getShouldWaitForRepairs() || (self->getPhysical()->isInAir() && !self->getPhysical()->isInWater())) { + reached = false; + done = true; + return 1; + } + Information* target = bapinline::info(m_object); + if (!target) { + m_pathValid2 = false; + return 0; + } + IPIMobile* mobile = self->getMobile(); + const IPIMobile::ValidPos& own = mobile->getLastValidPosition(mobile->getVehicleNumber()); + Information* primary = bapinline::info(target->getPrimaryObject(self->getSide())); + if (!primary || !primary->getMobile()) { + m_pathValid2 = false; + return 0; + } + const IPIMobile::ValidPos& goal = primary->getMobile()->getLastValidPosition(mobile->getVehicleNumber()); + if (own.polygon == 0xFFFFFFFFu) { + bot->getBotNavigation()->setIsStuck(true); + m_pathValid2 = false; + return 0; + } + if (goal.polygon == 0xFFFFFFFFu) { + m_pathValid2 = false; + return 0; + } + Vec3 dir = bapinline::sub(goal.position, own.position); + float dist = std::sqrt(dir.x * dir.x + dir.y * dir.y + dir.z * dir.z); + if (0.0001f < dist) { + const float inv = 1.0f / dist; + dir.x *= inv; + dir.y *= inv; + dir.z = inv * dir.z; + } + SensedObject* sensed = bot->getSensedObjectFromHandle(m_object); + const bool indirect = sensed ? (sensed->m_flags & 8u) != 0 : true; + if (!indirect) + m_flag107 = false; + const bool within = withinDistance() != 0; + const bool pathDone = m_pathDone; + const bool replanDue = 1.0 < bapinline::gameTime() - m_lastInitTime; + + // 0: no re-plan; 1: towards the target (dist, dir, own position, false); 2: fresh start. + int replan = 0; + bool checkNavigation = true; + if (indirect) { + if (!sameVec3(m_coordinate, goal.position) && !m_flag107 && !(m_movingAway && !pathDone)) { + m_flag107 = true; + replan = 1; + checkNavigation = false; + } + } + if (checkNavigation) { + bool searchCheck = true; + if (!sameVec3(m_coordinate, bot->getBotNavigation()->getGoal())) { + replan = 1; + searchCheck = false; + } else if (replanDue) { + if (m_movingAway || !(m_minDistance > dist)) { // 0x1DCCAB ja + if (m_movingAway) { + const Vec3 d = bapinline::sub(goal.position, m_coordinate); + if (d.x * d.x + d.y * d.y + d.z * d.z < m_minDistance * m_minDistance && pathDone) { + replan = 1; + searchCheck = false; + } + } + if (searchCheck && pathDone && !within && !sameVec3(m_coordinate, goal.position)) { + replan = 1; + searchCheck = false; + } + } else { + replan = 1; + searchCheck = false; + } + } + if (searchCheck) { + if (!m_pathStarted || !bot->getBotNavigation()->isSearchActive()) { + replan = 2; + } else if (replanDue && m_replanCondition && m_replanCondition->evaluate(m_bot)) { + if (!m_flagF8 || m_pathDone) { + m_flagF8 = true; + replan = 1; + } + } else { + m_flagF8 = false; + } + } + } + if (replan == 1) { + initObjectFinding(dist, dir, own.position, goal.island, goal.polygon, goal.position, false); + } else if (replan == 2) { + const Vec3 zero = bapinline::vec3(0.0f, 0.0f, 0.0f); + initObjectFinding(0.0f, zero, zero, goal.island, goal.polygon, goal.position, true); + } + + m_pathStarted = true; + if (!m_pathValid2) + return 0; + if (!m_movingAway) + bot->getBotNavigation()->updateLastPoint(primary); + const bool got = bot->getBotNavigation()->updatePath(m_currentPoint, m_pathDone, done, distance); + bool stopped = false; + const Vec3 target3 = bapinline::vec3(m_currentPoint.x, self->getPosition().y, m_currentPoint.y); + double sinceStart; + int artillerySide; + if (got) { + point = m_currentPoint; + reached = m_pathDone; + if (!self->isOfType(ITAir) + && SquadManager::m_instance->isInArtilleryDangerZone(target3, bot->getSide(), sinceStart, artillerySide) + && !SquadManager::m_instance->isInArtilleryDangerZone(self->getPosition(), bot->getSide(), sinceStart, + artillerySide)) { + done = true; + stopped = true; + } + } + if (!done) { + const bool soldier = self->isOfType(ITSoldier); + bool artilleryCheck = true; + if (!stopped && !m_movingAway && soldier + && std::fabs(target->getPosition().y - self->getPosition().y) < 2.0f) { + artilleryCheck = false; + const float pathLeft = bot->getBotNavigation()->getTargetDistance(); + IPIPhysical* physical = target->getPhysical(); + IPIArmament* armament = self->getArmament(); + if (!armament || armament->getActiveWeapon() == -1) { + m_pathValid2 = false; + return 0; + } + WeaponInfo* weapon = + WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + if (!weapon) { + m_pathValid2 = false; + return 0; + } + const Vec3 zero = bapinline::vec3(0.0f, 0.0f, 0.0f); + if ((!bot->isFiring() || !(weapon->getMaxRange() > 5.0f) || /* 0x1DCAB4 jbe */ weapon->getWeaponType() == 4) + && pathLeft < physical->getRadius() + 25.0f) + setIsSprinting(m_bot, true, zero, m_object); + else + setIsSprinting(m_bot, false, zero, 0xFFFFFFFFu); + } + if (artilleryCheck && soldier + && SquadManager::m_instance->isInArtilleryDangerZone(self->getPosition(), bot->getSide(), sinceStart, + artillerySide)) { + SquadMember* member = bot->getSquadMember(); + if (member && member->isAvoidingArtillery()) + setIsSprinting(m_bot, true, target3, 0xFFFFFFFFu); + } + if (!done && isFinished(m_bot)) { + m_pathValid2 = true; + reached = true; + m_pathDone = true; + point = m_currentPoint; + return 1; + } + } + if (!got) { + m_pathStarted = false; + return 0; + } + return 1; +} + +// ELF 0x1DD340: end condition, or (when moving away) path done and within distance, or +// (otherwise) within distance; then BotNavigation::clearProgress. +bool BAPAMoveToObjectFinding::isFinished(Bot* bot) +{ + bool ended = false; + if (m_endCondition && m_endCondition->evaluate(bot)) + ended = true; + bool finished; + if (!m_movingAway) + finished = ended || withinDistance(); + else + finished = ended || (m_pathDone && withinDistance()); + if (finished) + bot->getBotNavigation()->clearProgress(); + return finished; +} + +// ELF 0x1DD200 +bool BAPAMoveToObjectFinding::getLargestAngleDiff(float& angle) +{ + return m_bot->getBotNavigation()->getLargestAngleDiff(angle); +} + +// ELF 0x1DD1D0: BotNavigation +0xBC. +float BAPAMoveToObjectFinding::getTargetDistance() +{ + return m_bot->getBotNavigation()->getTargetDistance(); +} + +// ELF 0x1DD020 (same body as BAPAMoveToObject's) +float BAPAMoveToObjectFinding::getSimpleTargetDistance(Bot* bot) +{ + return std::sqrt(BAPAMoveToObjectFinding::getSimpleTargetDistanceSqr(bot)); +} + +// ELF 0x1DD110: neither information is null-checked. +float BAPAMoveToObjectFinding::getSimpleTargetDistanceSqr(Bot* bot) +{ + const Vec3& a = bapinline::info(bot->getCurrentEquipment())->getPosition(); + const Vec3& b = bapinline::info(m_object)->getPosition(); + const double dz = static_cast(a.z) - b.z; + const double dx = static_cast(a.x) - b.x; + const double dy = static_cast(a.y) - b.y; + return static_cast(dz * dz + dx * dx + dy * dy); +} + +// ELF 0x1DD650 +int BAPAMoveToObjectFinding::usesPathfinding() +{ + return 1; +} + +// ELF 0x1DD250: min^2 <= d^2 <= m_distance^2. +int BAPAMoveToObjectFinding::withinDistance() +{ + const float d = getSimpleTargetDistanceSqr(m_bot); + return (d <= m_distanceSqr && m_minDistanceSqr <= d) ? 1 : 0; +} + +// ELF 0x1DB310: the horizontal right of a direction, (z, y, -x) - written y, x, z in that order +// (`mov 4(%edx)->4(%ecx); mov 8(%edx)->(%ecx); xor $0x80000000 of (%edx) -> 8(%ecx)`). A global +// function of this TU (called through the PLT). +void getRight(const Vec3& direction, Vec3& right) +{ + right.y = direction.y; + right.x = direction.z; + right.z = -direction.x; +} + +// ELF 0x1DB360 (0xDE0 bytes). `distance` is the current distance to the object, `ownPosition` +// the bot's, `goal` the object's last valid position with its quad tree / polygon; the direction +// argument is unused. Both path flags cleared; no bot or object information: m_pathValid2 = +// false and nothing else. The arrive distance is 1.1 * the object's physical radius (FLT_MAX +// without one). Then: +// * at or beyond m_minDistance (0x1DB496 `fucompi; jbe`) or `fresh`: no sprint, straight at the +// goal with the caller's quad tree / polygon. +// * nearer: three flank offsets of length d = min((m_distance - m_minDistance) * 0.2, 10) + +// m_minDistance round the goal - a soldier moving faster than 1.5 m/s horizontally (the object's +// mobile, or its primary's; not null-checked): the side of its velocity facing the bot +// (0x1DBD7E `setae`: flipped when dot < 0), its opposite and the right of the unflipped side; +// a soldier otherwise: away from the goal towards the bot, then its right and left; anything +// else (a vehicle): along the object's transformation row 2, then right and left. Sprinting +// from the bot's position, each offset is traced (IAIPathfinding slot +0x90, 0x1DB82A) until +// one is clear; the goal is 98 % of the way to the clear trace end, or else to the blocked end +// farthest from the goal (zero / -1 if none is farther than 0), with the trace's polygon and +// BotNavigation +0xCC as the island; its height is then the terrain's (slot +0x14). +// Then BotNavigation::initPathfinding(island, polygon, goal, arrive, m_distance) and the time. +void BAPAMoveToObjectFinding::initObjectFinding(float distance, const Vec3&, const Vec3& ownPosition, + unsigned int quadTree, unsigned int polygon, const Vec3& goal, + bool fresh) +{ + m_movingAway = false; + m_pathDone = false; + Information* self = bapinline::info(m_bot->getCurrentEquipment()); + if (!self) { + m_pathValid2 = false; + return; + } + Information* target = bapinline::info(m_object); + if (!target) { + m_pathValid2 = false; + return; + } + IPIMobile* mobile = target->getMobile(); + if (!mobile && !target->isPrimary()) { + Information* primary = bapinline::info(target->getPrimaryObject(m_bot->getSide())); + if (primary) + mobile = primary->getMobile(); + } + float arrive = 3.4028235e+38f; + if (IPIPhysical* physical = target->getPhysical()) + arrive = physical->getRadius() * 1.1f; // fmuls by the float constant 0x3F8CCCCD + const int equipmentType = self->getUnit()->getEquipmentType(); + + if (!(m_minDistance > distance) || fresh) { // 0x1DB496 jbe + m_movingAway = false; + setIsSprinting(m_bot, false, bapinline::vec3(0.0f, 0.0f, 0.0f), 0xFFFFFFFFu); + m_coordinate = goal; + } else { + Vec3 offsets[3]; + for (int i = 0; i < 3; ++i) + offsets[i] = bapinline::vec3(0.0f, 0.0f, 0.0f); + const Vec3& speed = mobile->getSpeed(); + Vec3 flat = bapinline::vec3(speed.x, 0.0f, speed.z); + const float flatSpeed = std::sqrt(flat.x * flat.x + 0.0f * 0.0f + flat.z * flat.z); + const bool soldier = self->isOfType(ITSoldier); + if (!soldier || !(flatSpeed > 1.5f)) { // 0x1DB53E ja + float d = (m_distance - m_minDistance) * 0.2f; + if (10.0f < d) + d = 10.0f; + d = d + m_minDistance; + if (!soldier) { + const Mat4& t = self->getTransformation(); + offsets[0] = bapinline::vec3(t.m[8] * d, t.m[9] * d, d * t.m[10]); + } else { + Vec3 away = bapinline::sub(ownPosition, goal); + bapinline::normalize(away); + offsets[0] = bapinline::vec3(away.x * d, away.y * d, d * away.z); + } + getRight(offsets[0], offsets[1]); + offsets[2] = bapinline::vec3(-offsets[1].x, -offsets[1].y, -offsets[1].z); + } else { + const float inv = 1.0f / flatSpeed; + flat = bapinline::vec3(flat.x * inv, flat.y * inv, inv * flat.z); + Vec3 side = bapinline::vec3(0.0f, 0.0f, 0.0f); + getRight(flat, side); + const bool behind = !(bapinline::dot(bapinline::sub(ownPosition, goal), side) >= 0.0f); // 0x1DBD7A setae + if (behind) + side = bapinline::vec3(-side.x, -side.y, -side.z); + float d = (m_distance - m_minDistance) * 0.2f; + if (10.0f < d) + d = 10.0f; + d = d + m_minDistance; + offsets[0] = bapinline::vec3(side.x * d, side.y * d, d * side.z); + offsets[1] = bapinline::vec3(-offsets[0].x, -offsets[0].y, -offsets[0].z); + const Vec3 unflipped = behind ? offsets[1] : offsets[0]; + getRight(unflipped, offsets[2]); + } + + m_movingAway = true; + setIsSprinting(m_bot, true, self->getPosition(), 0xFFFFFFFFu); + BotNavigation* navigation = m_bot->getBotNavigation(); + float bestDistSqr = 0.0f; + unsigned int bestPolygon = 0xFFFFFFFFu; + Vec3 end = bapinline::vec3(0.0f, 0.0f, 0.0f); + Vec3 best = bapinline::vec3(0.0f, 0.0f, 0.0f); + unsigned int endPolygon; + bool clear; + int i = 0; + do { + const Vec3 candidate = bapinline::add(offsets[i], goal); + clear = IAIPathfinding::instance->trace(navigation, false, candidate, end, endPolygon, equipmentType, -1, + 0.0f, 0, 0); + if (!clear) { + const Vec3 back = bapinline::sub(goal, end); + const float distSqr = back.x * back.x + back.y * back.y + back.z * back.z; + if (bestDistSqr < distSqr) { + best = bapinline::vec3(goal.x + (end.x - goal.x) * 0.98f, goal.y + (end.y - goal.y) * 0.98f, + goal.z + (end.z - goal.z) * 0.98f); + bestPolygon = endPolygon; + bestDistSqr = distSqr; + } + } + ++i; + } while (!clear && i < 3); + quadTree = navigation->getLastValidIsland(); + if (!clear) { + m_coordinate = best; + polygon = bestPolygon; + } else { + m_coordinate = bapinline::vec3(goal.x + (end.x - goal.x) * 0.98f, goal.y + (end.y - goal.y) * 0.98f, + goal.z + (end.z - goal.z) * 0.98f); + polygon = endPolygon; + } + } + + m_previousSpeed = 0.0f; + m_flagEA = false; + if (m_movingAway) + m_coordinate.y = static_cast(CommonSingletonServer::m_iaiTerrain) + ->getTerrainAltitude(m_coordinate.x, m_coordinate.z); + m_pathValid2 = m_bot->getBotNavigation()->initPathfinding(quadTree, polygon, m_coordinate, arrive, m_distance); + m_lastInitTime = bapinline::gameTime(); +} + +// ELF 0x1DD2A0: the bot's current vehicle/soldier is within 1 m of the goal (not null-checked). +bool BAPAMoveToObjectFinding::isAtCoordinate() +{ + const Vec3& p = bapinline::info(m_bot->getCurrentEquipment())->getPosition(); + return bapinline::lengthSqr(bapinline::sub(p, m_coordinate)) < 1.0f; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectFinding.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectFinding.h new file mode 100644 index 000000000..a0921a06d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectFinding.h @@ -0,0 +1,67 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETOOBJECTFINDING_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETOOBJECTFINDING_H + +#include +#include "../../../../Math/Vec3.h" +#include "BAPAMoveToObject.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B86C0 (40 words), package C-actions. +// Moves to an object with pathfinding, re-planning towards the object's last valid position +// (initObjectFinding) and sprinting/flanking as needed. +class BAPAMoveToObjectFinding : public BAPAMoveToObject +{ +public: + BAPAMoveToObjectFinding(Bot*, unsigned int, float, float, float, BAPCondition*, unsigned long long, int, BAPCondition*, float, int); // 0x1DB1A0 + virtual ~BAPAMoveToObjectFinding(); // 0x1DC0C0 + + virtual void streamSelf(std::ostream&) const; // 0x1DD430, slot +0x1C; from the base declaration + virtual bool getIsMovingAway(); // 0x1DD660, slot +0x24; from the base declaration + virtual int update(Vec2&, bool&, bool&, float); // 0x1DC1C0, slot +0x2C; from the base declaration + virtual bool isFinished(Bot*); // 0x1DD340, slot +0x30; from the base declaration + virtual bool getLargestAngleDiff(float&); // 0x1DD200, slot +0x38; from the base declaration + virtual float getTargetDistance(); // 0x1DD1D0, slot +0x3C; from the base declaration + virtual float getSimpleTargetDistance(Bot*); // 0x1DD020, slot +0x44; from the base declaration + virtual float getSimpleTargetDistanceSqr(Bot*); // 0x1DD110, slot +0x48; from the base declaration + virtual int usesPathfinding(); // 0x1DD650, slot +0x4C; from the base declaration + virtual int withinDistance(); // 0x1DD250, slot +0x50; from the base declaration + + void initObjectFinding(float, const Vec3&, const Vec3&, unsigned int, unsigned int, const Vec3&, bool); // 0x1DB360; [INFERRED] ELF void + bool isAtCoordinate(); // 0x1DD2A0; [INFERRED] ELF bool + +private: + /* +0xC8 */ int m_zeroC8[8]; // +0xC8..+0xE4 = 0; [UNRESOLVED] + /* +0xE9 */ bool m_flagE9; // = false; [UNRESOLVED] + /* +0xEA */ bool m_flagEA; // initObjectFinding: false; [UNRESOLVED] + /* +0xEC */ int m_intEC; // = 1; [UNRESOLVED] + /* +0xF0 */ Bot* m_bot; + /* +0xF4 */ BAPCondition* m_replanCondition; // owned; update evaluates it on the replan timer; [INFERRED] name + /* +0xF8 */ bool m_flagF8; // = true; [UNRESOLVED] + /* +0xFC */ float m_minDistance; // clamped to m_distance + /* +0x100 */ float m_minDistanceSqr; + /* +0x104 */ bool m_pathDone; // updatePath's flag + /* +0x105 */ bool m_movingAway; // getIsMovingAway; set when initObjectFinding flanks + /* +0x106 */ bool m_pathStarted; + /* +0x107 */ bool m_flag107; // = false; [UNRESOLVED] + /* +0x108 */ int m_index; // the ctor's last int; printed as "[n]" unless -1 + /* +0x10C */ double m_lastInitTime; // = -1.0; game time of the last initObjectFinding +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETOOBJECTFINDING_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPANotifyBot.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPANotifyBot.cpp new file mode 100644 index 000000000..9aeebeff8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPANotifyBot.cpp @@ -0,0 +1,56 @@ +// Adds a plan-variable amount to a sensed object's notification word for type zero. + +// static init: ELF 0x1DD970 (__tcf_0 0x1DD9D0, _GLOBAL__I 0x1DDA00): 's Init object only. +#include + +#include "BAPANotifyBot.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SensedObject.h" +#include "../../../../Core/Debug.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1DD6D0 (C1; C2 0x1DD670) +BAPANotifyBot::BAPANotifyBot(Type type, BAPVariable* amount, BAPVariable* object) + : BAPAction(UninitializedPatternId()), m_type(type), m_amount(amount), m_object(object) +{ +} + +// ELF 0x1DD770 (D1; D2 0x1DD730, D0 0x1DD7B0) +BAPANotifyBot::~BAPANotifyBot() +{ +} + +// ELF 0x1DD800 +bool BAPANotifyBot::execute(Bot* bot, bool& success, bool& finished) +{ + if (m_type == 0) { + SensedObject* object = bot->getSensedObjectFromHandle(m_object->m_value); + if (object) + object->m_unresolved44 += m_amount->m_value; + } else { + Debug(DebugTypeError, "AI/AIDLL/AI/AIBotActionPlan/BAPANotifyBot.cpp", 45, "") << "Unkown type"; + } + success = true; + finished = true; + return true; +} + +// ELF 0x1DD950 +BAPStatementType BAPANotifyBot::getId() const +{ + return BAPSTNotifyBot; +} + +// ELF 0x1DD960 +bool BAPANotifyBot::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPANotifyBot.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPANotifyBot.h new file mode 100644 index 000000000..73668ed71 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPANotifyBot.h @@ -0,0 +1,38 @@ +// Adds a plan-variable amount to a sensed object's notification word for type zero. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPANOTIFYBOT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPANOTIFYBOT_H + +#include "BAPAction.h" +#include "BAPTypes.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B8780 (8 words), package G-vehicles. +class BAPANotifyBot : public BAPAction +{ +public: + enum Type : int; // [UNRESOLVED] enumerators + BAPANotifyBot(BAPANotifyBot::Type, BAPVariable*, BAPVariable*); // 0x1DD6D0 + virtual ~BAPANotifyBot(); // 0x1DD770 + + virtual bool execute(Bot*, bool&, bool&); // 0x1DD800, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1DD950, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1DD960, slot +0x14; from the base declaration +private: + /* +0x14 */ Type m_type; + /* +0x18 */ BAPVariable* m_amount; + /* +0x1C */ BAPVariable* m_object; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPANOTIFYBOT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAOverrideSensingAgent.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAOverrideSensingAgent.cpp new file mode 100644 index 000000000..1af78f9a0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAOverrideSensingAgent.cpp @@ -0,0 +1,49 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1DDBE0 (__tcf_0 0x1DDC40, _GLOBAL__I 0x1DDC70): 's Init object only. +#include + +#include "BAPAOverrideSensingAgent.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SensingAgent.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1DDA70 (C1; C2 0x1DDA20): the inline base only (+0x04, +0x08 = 0; +0x10 untouched). +BAPAOverrideSensingAgent::BAPAOverrideSensingAgent() +{ + m_controls = 0; +} + +// ELF 0x1DDB00 (D1; D2 0x1DDAC0, D0 0x1DDB40) +BAPAOverrideSensingAgent::~BAPAOverrideSensingAgent() +{ +} + +// ELF 0x1DDB90: hands the look to the plan (SensingAgent::setOverride(true)); done at once. +bool BAPAOverrideSensingAgent::execute(Bot* bot, bool& ok, bool& failed) +{ + bot->getSensingAgent()->setOverride(true); + ok = true; + failed = true; + return false; +} + +// ELF 0x1DDCA0 +BAPStatementType BAPAOverrideSensingAgent::getId() const +{ + return BAPSTOverrideSensingAgent; // 21 +} + +// ELF 0x1DDC90 +bool BAPAOverrideSensingAgent::hasDefault() +{ + return false; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAOverrideSensingAgent.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAOverrideSensingAgent.h new file mode 100644 index 000000000..054107346 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAOverrideSensingAgent.h @@ -0,0 +1,37 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAOVERRIDESENSINGAGENT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAOVERRIDESENSINGAGENT_H + +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B87C0 (8 words), operator new 0x14/0x2C, package C-actions. +// No data of its own (operator new 0x14: the BAPStatement base; the image leaves +0x10 unwritten, the shared base ctor zeroes it). +class BAPAOverrideSensingAgent : public BAPAction +{ +public: + BAPAOverrideSensingAgent(); // 0x1DDA70 + virtual ~BAPAOverrideSensingAgent(); // 0x1DDB00 + + virtual bool execute(Bot*, bool&, bool&); // 0x1DDB90, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1DDCA0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1DDC90, slot +0x14; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAOVERRIDESENSINGAGENT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAPhysicsEnable.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAPhysicsEnable.cpp new file mode 100644 index 000000000..e5e9db0ce --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAPhysicsEnable.cpp @@ -0,0 +1,62 @@ +// Enables or disables physics on the bot's primary equipment when its current state differs. + +// static init: ELF 0x1DDF20 (__tcf_0 0x1DDF80, _GLOBAL__I 0x1DDFB0): 's Init object only. +#include + +#include "BAPAPhysicsEnable.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1DDD00 (C1; C2 0x1DDCB0) +BAPAPhysicsEnable::BAPAPhysicsEnable(bool enable) + : BAPAction(UninitializedPatternId()), m_enable(enable) +{ +} + +// ELF 0x1DDD90 (D1; D2 0x1DDD50, D0 0x1DDDD0) +BAPAPhysicsEnable::~BAPAPhysicsEnable() +{ +} + +// ELF 0x1DDE20 +bool BAPAPhysicsEnable::execute(Bot* bot, bool& success, bool& finished) +{ + Information* self = bapinline::info(bot->getCurrentEquipment()); + if (self && self->isPrimary()) { + IAIObjectPhysical* physical = self->getAIObject()->getPhysical(); + if (m_enable) { + if (!physical->hasPhysicsEnabled()) + physical->enablePhysics(bot->getSide()); + } else { + if (physical->hasPhysicsEnabled()) + physical->disablePhysics(bot->getSide()); + } + } + finished = true; + success = true; + return true; +} + +// ELF 0x1DDFD0 +BAPStatementType BAPAPhysicsEnable::getId() const +{ + return BAPSTPhysicsEnable; +} + +// ELF 0x1DDFE0 +bool BAPAPhysicsEnable::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAPhysicsEnable.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAPhysicsEnable.h new file mode 100644 index 000000000..38dca7627 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAPhysicsEnable.h @@ -0,0 +1,34 @@ +// Enables or disables physics on the bot's primary equipment when its current state differs. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAPHYSICSENABLE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAPHYSICSENABLE_H + +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B8800 (8 words), package H-deferred. +class BAPAPhysicsEnable : public BAPAction +{ +public: + explicit BAPAPhysicsEnable(bool); // 0x1DDD00 + virtual ~BAPAPhysicsEnable(); // 0x1DDD90 + + virtual bool execute(Bot*, bool&, bool&); // 0x1DDE20, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1DDFD0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1DDFE0, slot +0x14; from the base declaration +private: + /* +0x14 */ bool m_enable; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAPHYSICSENABLE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAPlaceC4.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAPlaceC4.cpp new file mode 100644 index 000000000..e08e0303a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAPlaceC4.cpp @@ -0,0 +1,73 @@ +// C4 action: places or removes the bot's C4 (AI/AIDLL/AI/AIBotActionPlan/BAPAPlaceC4.cpp in the +// image). Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF +// address. +// +// static init: ELF 0x1DE280 (__tcf_0 0x1DE2E0, _GLOBAL__I 0x1DE310): the guard object only. + +#include "BAPAPlaceC4.h" + +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../../../../Math/Vec3.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1DE050 (C1; C2 0x1DDFF0): the inline BAPStatement constructor (+0x04, +0x08 zeroed), then +// +0x14 type, +0x18 target, +0x1C place. The image leaves +0x10 (pattern id) unwritten; the tree's +// BAPStatement() stores 0 there [CHOSEN, not recovered]. +BAPAPlaceC4::BAPAPlaceC4(int placementType, AIStrategicObject* target, bool place) +{ + m_placementType = placementType; + m_target = target; + m_place = place; +} + +// ELF 0x1DE0F0 (D1; D2 0x1DE0B0, D0 0x1DE130): base destructors only. +BAPAPlaceC4::~BAPAPlaceC4() +{ +} + +// ELF 0x1DE180: place: Bot +0x14C placeC4(type, position of the bot's equipment, target) unless +// +0x150 isC4Placed; remove: +0x154 removeC4 when placed. Both flags set, returns false. The +// equipment information is not null-checked, as compiled. +bool BAPAPlaceC4::execute(Bot* bot, bool& ok, bool& failed) +{ + if (m_place) + { + if (!bot->isC4Placed()) + { + // 0x1DE1D7 + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + const Vec3 position = info->getPosition(); + bot->placeC4(m_placementType, position, m_target); + } + } + else if (bot->isC4Placed()) + { + bot->removeC4(); // 0x1DE267 + } + ok = true; + failed = true; + return false; +} + +// ELF 0x1DE340 +BAPStatementType BAPAPlaceC4::getId() const +{ + return BAPSTPlaceC4; // 22 +} + +// ELF 0x1DE330 +bool BAPAPlaceC4::hasDefault() +{ + return false; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAPlaceC4.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAPlaceC4.h new file mode 100644 index 000000000..fd395dd97 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAPlaceC4.h @@ -0,0 +1,43 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAPLACEC4_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAPLACEC4_H + +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class AIStrategicObject; +class Bot; + +// ELF: vtable 0x4B8840 (8 words), operator new 0x20, package F-infantry. Places the bot's C4 at +// its position (place = true) or removes it, once, and finishes at once. +class BAPAPlaceC4 : public BAPAction +{ +public: + BAPAPlaceC4(int /* [UNRESOLVED] Bot::C4PlacementType */, AIStrategicObject*, bool); // 0x1DE050 + virtual ~BAPAPlaceC4(); // 0x1DE0F0 + + virtual bool execute(Bot*, bool&, bool&); // 0x1DE180, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1DE340, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1DE330, slot +0x14; from the base declaration + +private: + /* +0x14 */ int m_placementType; // Bot::C4PlacementType (kept int, see Bot::placeC4) + /* +0x18 */ AIStrategicObject* m_target; + /* +0x1C */ bool m_place; // true: place unless placed; false: remove if placed [INFERRED] name +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAPLACEC4_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAResetControls.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAResetControls.cpp new file mode 100644 index 000000000..e5d3d4c9d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAResetControls.cpp @@ -0,0 +1,104 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1DE790 (__tcf_0 0x1DE7F0, _GLOBAL__I 0x1DE820): 's Init object only. +#include + +#include "BAPAResetControls.h" + +#include "BAPActionInline.h" +#include "../Main/IBotManager.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1DE3D0 (C1; C2 0x1DE350): group form, no single input, controls = 0. +BAPAResetControls::BAPAResetControls(bool resetMove, bool resetLook, bool resetTrigger, int tag) +{ + m_resetMove = resetMove; + m_resetLook = resetLook; + m_input = static_cast(0); + m_resetTrigger = resetTrigger; + m_controls = 0; + m_patternId = tag; +} + +// ELF 0x1DE4D0 (C1; C2 0x1DE450): one input. `movl $1,%eax; shll %cl,%eax` then `sarl $31` into +// the high word: the 32-bit shift (count & 31) sign-extended to 64 bits, kept as in the image. +BAPAResetControls::BAPAResetControls(io::PlayerInputMap input, int tag) +{ + m_input = input; + m_resetMove = false; + m_resetLook = false; + m_resetTrigger = false; + m_patternId = tag; + const int bit = static_cast(1u << (static_cast(input) & 31u)); + m_controls = static_cast(static_cast(bit)); +} + +// ELF 0x1DE590 (D1; D2 0x1DE550, D0 0x1DE5D0) +BAPAResetControls::~BAPAResetControls() +{ +} + +// ELF 0x1DE660 +bool BAPAResetControls::execute(Bot*, bool& ok, bool& failed) +{ + ok = true; + failed = true; + return true; +} + +// ELF 0x1DE620 +unsigned long long BAPAResetControls::getControls() +{ + return m_controls; +} + +// ELF 0x1DE840 +BAPStatementType BAPAResetControls::getId() const +{ + return BAPSTResetControls; // 14 +} + +// ELF 0x1DE850 +bool BAPAResetControls::hasDefault() +{ + return false; +} + +// ELF 0x1DE680: "(" then the single input or the group labels, then ")" endl. +void BAPAResetControls::streamSelf(std::ostream& out) const +{ + IBotManager::instance->tabulate(out); + bapinline::streamType(out, getId()) << "("; + if (hasSingleInput()) { + bapinline::streamInput(out, getInput()); + } else { + if (m_resetMove) + out << "Move "; + if (m_resetLook) + out << "Look "; + if (m_resetTrigger) + out << "Trigger"; + } + out << ")" << std::endl; +} + +// ELF 0x1DE630: `(+0x0C | +0x08) != 0` +bool BAPAResetControls::hasSingleInput() const +{ + return m_controls != 0; +} + +// ELF 0x1DE650 +io::PlayerInputMap BAPAResetControls::getInput() const +{ + return m_input; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAResetControls.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAResetControls.h new file mode 100644 index 000000000..f07fb7355 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAResetControls.h @@ -0,0 +1,53 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPARESETCONTROLS_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPARESETCONTROLS_H + +#include +#include "../../../../IO/Input/Input.h" +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B88C0 (8 words), operator new 0x1C/0x20, package C-actions. +// Resets either one input (the PlayerInputMap form: controls = the sign-extended 32-bit +// `1 << input`) or whole groups (move / look / trigger; controls = 0). The work is done by +// EntryInfanteryResetControls; the statement's own execute just succeeds. +class BAPAResetControls : public BAPAction +{ +public: + BAPAResetControls(bool, bool, bool, int); // 0x1DE3D0 + BAPAResetControls(io::PlayerInputMap, int); // 0x1DE4D0 + virtual ~BAPAResetControls(); // 0x1DE590 + + virtual bool execute(Bot*, bool&, bool&); // 0x1DE660, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1DE620, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1DE840, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1DE850, slot +0x14; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1DE680, slot +0x1C; from the base declaration + + bool hasSingleInput() const; // 0x1DE630; [INFERRED] ELF bool, callers {'bool': 7} + io::PlayerInputMap getInput() const; // 0x1DE650 (+0x18) + + // Read inline by the reset entries, so public. [INFERRED] names from streamSelf's labels. + /* +0x14 */ bool m_resetMove; // "Move " + /* +0x15 */ bool m_resetLook; // "Look " + /* +0x16 */ bool m_resetTrigger; // "Trigger" + /* +0x18 */ io::PlayerInputMap m_input; // 0 in the group form +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPARESETCONTROLS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARevive.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARevive.cpp new file mode 100644 index 000000000..d6ed30fd5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARevive.cpp @@ -0,0 +1,73 @@ +// Revive action. Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries +// its ELF address. + +// static init: ELF 0x1DEB00 (__tcf_0 0x1DEB60, _GLOBAL__I 0x1DEB90): 's Init object only. +#include + +#include "BAPARevive.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../../../../IO/Input/Input.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1DE8B0 (C1; C2 0x1DE860): the inline BAPStatement constructor (+0x04, +0x08 zeroed, +// instance counter), +0x10 = pattern id, +0x14 = false. +BAPARevive::BAPARevive(int patternId) + : BAPStatement(patternId) +{ + m_firePressed = false; +} + +// ELF 0x1DE940 (D1; D2 0x1DE900, D0 0x1DE980): base destructors only. +BAPARevive::~BAPARevive() +{ +} + +// ELF 0x1DE9D0: requests the crouching pose (Bot +0x194 requestSoldierPose(2, true)). Once the +// bot's equipment is crouching, alternate executions press fire (written inline: the value 1 when +// the fire input is mapped) and release it through io::Input::setInput(PIFire, 0) with the second +// flag set. Always sets the first flag and returns true. The equipment information is not +// null-checked, as compiled. +bool BAPARevive::execute(Bot* bot, bool& ok, bool& finished) +{ + bot->requestSoldierPose(2, true); + if (bapinline::info(bot->getCurrentEquipment())->getSoldierPose() == SPCrouching) + { + if (!m_firePressed) + { + io::PlayerInput* const input = bot->getInput(); + if ((input->mappingFlags >> io::PIFire) & 1ULL) + input->inputs[io::PIFire] = 1.0f; + m_firePressed = true; + } + else + { + finished = true; + bot->getInput()->setInput(io::PIFire, 0.0f); + m_firePressed = false; + } + } + ok = true; + return true; +} + +// ELF 0x1DEAE0 +BAPStatementType BAPARevive::getId() const +{ + return BAPSTRevive; // 44 +} + +// ELF 0x1DEAF0 +bool BAPARevive::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARevive.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARevive.h new file mode 100644 index 000000000..96953c256 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARevive.h @@ -0,0 +1,36 @@ +// Revive action: crouches and presses fire once per two executions (the shock paddles). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAREVIVE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAREVIVE_H + +#include "BAPStatement.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B8940 (8 words), operator new 0x18/0x2C, package F-infantry. +class BAPARevive : public BAPStatement +{ +public: + explicit BAPARevive(int); // 0x1DE8B0 + virtual ~BAPARevive(); // 0x1DE940 + + virtual bool execute(Bot*, bool&, bool&); // 0x1DE9D0, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1DEAE0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1DEAF0, slot +0x14; from the base declaration + +private: + /* +0x14 */ bool m_firePressed; // [INFERRED] name: set by the execute that presses fire +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAREVIVE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARoll3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARoll3d.cpp new file mode 100644 index 000000000..51402da9f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARoll3d.cpp @@ -0,0 +1,95 @@ +// Roll-action state recovered from libaidll.so. +// static init: ELF 0x1DF350 (__tcf_0 0x1DF3B0, _GLOBAL__I 0x1DF3E0): 's Init object only. +#include +#include "BAPARoll3d.h" +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIMobile.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1DEEB0 (C1; C2 0x1DEBB0) +BAPARoll3d::BAPARoll3d(Bot* bot, int direction, float roll, float maxSpeed, + BAPCondition* condition, unsigned long long controls, float, int tag) + : BAPAction(UninitializedPatternId()) +{ + m_maxSpeed = maxSpeed; + m_roll = roll; + m_vector1C = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_float28 = 0.0f; + m_direction = direction; + m_forward = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_up = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_right = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_flatFacing = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_vector6C = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_vector78 = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_breakCondition = condition; + Information* self = bapinline::info(bot->getCurrentEquipment()); + Vec2 facing; + facing.x = 0.0f; + facing.y = 0.0f; + const Vec3 direction3 = self->getFaceing(); + vec3ToVec2XZ(direction3, facing); + bapinline::normalize(facing); + addVec2ToVec3XZ(facing, m_flatFacing); + const Mat4& first = self->getTransformation(); + m_vector78 = bapinline::vec3(first.m[4], first.m[5], first.m[6]); + const Mat4& second = self->getTransformation(); + m_vector6C = bapinline::vec3(second.m[4], second.m[5], second.m[6]); + m_patternId = tag; + m_breakCondition->setOwner(this); + m_initialAltitude = self->getAltitude(self->getMobile()->getSpeed()); + m_controls = controls; +} + +// ELF 0x1DF210 (D1; D2 0x1DF1A0, D0 0x1DF280) +BAPARoll3d::~BAPARoll3d() +{ + delete m_breakCondition; +} + +// ELF 0x1DF2F0 +bool BAPARoll3d::execute(Bot*, bool& success, bool& finished) +{ + success = false; + finished = true; + return false; +} + +// ELF 0x1DF310 +unsigned long long BAPARoll3d::getControls() +{ + return m_controls; +} + +// ELF 0x1DF400 +BAPStatementType BAPARoll3d::getId() const +{ + return BAPSTRoll3d; +} + +// ELF 0x1DF320 +bool BAPARoll3d::hasDefault() +{ + return false; +} + +// ELF 0x1DF330 +float BAPARoll3d::getMaxSpeed() +{ + return m_maxSpeed; +} + +// ELF 0x1DF340 +BAPCondition* BAPARoll3d::getBreakCondition() +{ + return m_breakCondition; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARoll3d.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARoll3d.h new file mode 100644 index 000000000..be5bc62ec --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARoll3d.h @@ -0,0 +1,54 @@ +// Roll state consumed by the plane interpreter; owns its required break condition. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAROLL3D_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAROLL3D_H + +#include "BAPAction.h" +#include "../../../../Math/Vec3.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B8980 (8 words), package H-deferred. +class BAPARoll3d : public BAPAction +{ +public: + BAPARoll3d(Bot*, int, float, float, BAPCondition*, unsigned long long, float, int); // 0x1DEEB0 + virtual ~BAPARoll3d(); // 0x1DF210 + + virtual bool execute(Bot*, bool&, bool&); // 0x1DF2F0, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1DF310, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1DF400, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1DF320, slot +0x14; from the base declaration + + float getMaxSpeed(); // 0x1DF330; [INFERRED] ELF float + BAPCondition* getBreakCondition(); // 0x1DF340 + // [INFERRED] names. The plane entry reads and updates these fields inline. + /* +0x14 */ float m_maxSpeed; + /* +0x18 */ float m_roll; + /* +0x1C */ Vec3 m_vector1C; + /* +0x28 */ float m_float28; + /* +0x2C */ float m_float2C; // shipped defect: constructor leaves this and +0x30 uninitialized + /* +0x30 */ float m_previousY; + /* +0x34 */ int m_direction; + /* +0x38 */ float m_initialAltitude; + /* +0x3C */ Vec3 m_forward; + /* +0x48 */ Vec3 m_up; + /* +0x54 */ Vec3 m_right; + /* +0x60 */ Vec3 m_flatFacing; + /* +0x6C */ Vec3 m_vector6C; + /* +0x78 */ Vec3 m_vector78; + /* +0x84 */ BAPCondition* m_breakCondition; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAROLL3D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARunOverObject.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARunOverObject.cpp new file mode 100644 index 000000000..fbc6acc71 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARunOverObject.cpp @@ -0,0 +1,138 @@ +// Recovered from libaidll.so 1.5.3153 (ia-32); objdump listings with Ghidra cross-checks, ELF +// addresses on every body. Static init: ELF 0x1DFB40 (the guard object only). + +#include "BAPARunOverObject.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIPlanInterpreter/CarControl.h" +#include "../Main/IAIPathfinding.h" +#include "../../../../Math/Vec3.h" + +#include +// static init: ELF 0x1DFB40 (__tcf_0 0x1DFBA0, _GLOBAL__I 0x1DFBD0): 's Init object only. +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1DF470 (C1; C2 0x1DF410). BAPStatement() (controls 0), then the members. +BAPARunOverObject::BAPARunOverObject(unsigned int object, unsigned long long controls, int patternId) +{ + m_object = object; + m_controls18 = controls; + m_patternId = patternId; +} + +// ELF 0x1DFBF0 (D1; D0 0x1DFC30): base only. +BAPARunOverObject::~BAPARunOverObject() +{ +} + +// ELF 0x1DF4D0 (listing; Ghidra cross-check). Without the bot's equipment it returns false and +// leaves ok = true, done = false. Without the target's information, or when IAIPathfinding +0x8C +// finds no clear line from the bot's last valid position to the target's (for the bot's vehicle +// number), it is done. Otherwise the intercept point is the target's position advanced by its +// velocity over the bot's travel time, refined once; the car steers at it with speed 50 through +// CarControl::controlTowardsDirection, the angle measured from the bot's normalised XZ facing. +// Shipped quirks kept: the target's mobile part is used unchecked, the bot's speed is not tested +// against zero, the trace's hit point is unused. +bool BAPARunOverObject::execute(Bot* bot, bool& ok, bool& done) +{ + ok = true; + done = false; + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + if (!equipment) + return false; + IPIMobile* const mobile = equipment->getMobile(); + IPIPhysical* const physical = equipment->getPhysical(); + Information* const target = informationManager->getInformation(m_object); + if (!target) + { + done = true; + return true; + } + IPIMobile* const targetMobile = target->getMobile(); + const IPIMobile::ValidPos& targetValid = targetMobile->getLastValidPosition(mobile->getVehicleNumber()); + const IPIMobile::ValidPos& ownValid = mobile->getLastValidPosition(); + Vec3 hit; + hit.x = 0.0f; + hit.y = 0.0f; + hit.z = 0.0f; + unsigned int polygon; + const int equipmentType = equipment->getUnit()->getEquipmentType(); + if (!IAIPathfinding::instance->trace(ownValid.polygon, ownValid.island, mobile->getVehicleNumber(), + ownValid.position, targetValid.position, hit, polygon, equipmentType, + -1, 0.0f, 5, 0)) + { + done = true; + return true; + } + + const Vec3& own = equipment->getPosition(); + const Vec3& at = target->getPosition(); + const float dx = at.x - own.x; + const float dy = at.y - own.y; + const float dz = at.z - own.z; + const float distance = std::sqrt(dx * dx + dy * dy + dz * dz); + const float speed = mobile->getSpeedMagnitude(); + const float time = distance / speed; + const Vec3& velocity = targetMobile->getSpeed(); + Vec3 predicted; + predicted.x = at.x + time * velocity.x; + predicted.y = at.y + time * velocity.y; + predicted.z = at.z + time * velocity.z; + const float px = predicted.x - own.x; + const float py = predicted.y - own.y; + const float pz = predicted.z - own.z; + const float refinedTime = std::sqrt(pz * pz + px * px + py * py) / speed; + const Vec3& velocity2 = targetMobile->getSpeed(); + Vec3 intercept; + intercept.x = refinedTime * velocity2.x + at.x; + intercept.y = refinedTime * velocity2.y + at.y; + intercept.z = refinedTime * velocity2.z + at.z; + Vec3 toIntercept; + toIntercept.x = intercept.x - own.x; + toIntercept.y = intercept.y - own.y; + toIntercept.z = intercept.z - own.z; + Vec2 direction; + direction.x = 0.0f; + direction.y = 0.0f; + vec3ToVec2XZ(toIntercept, direction); + + Vec2 normal; + normal.x = 0.0f; + normal.y = 0.0f; + Vec2 facing; + facing.x = 0.0f; + facing.y = 0.0f; + vec3ToVec2XZ(equipment->getFaceing(), facing); + bapinline::normalize(facing); + getNormal(facing, normal); + const float angle = getSignedDiffAngleToDirWithNormal(facing, normal, direction); + ok = CarControl::controlTowardsDirection(equipment, equipment->getControlInfo(), mobile, physical, bot->getInput(), + 50.0f, 1.0f, angle, 1.0f, 1.0f) != 0; + return true; +} + +// ELF 0x1DFB30 +BAPStatementType BAPARunOverObject::getId() const +{ + return BAPSTRunOverObject; +} + +// ELF 0x1DFB20 +bool BAPARunOverObject::hasDefault() +{ + return false; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARunOverObject.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARunOverObject.h new file mode 100644 index 000000000..cb0bc9e2e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARunOverObject.h @@ -0,0 +1,40 @@ +// Recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every declaration. +// Drives a car at an object's predicted position (BBPRunOverSoldier's plan). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPARUNOVEROBJECT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPARUNOVEROBJECT_H + +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B8A00 (8 words), package G-vehicles. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BAPARunOverObject : public BAPAction +{ +public: + BAPARunOverObject(unsigned int object, unsigned long long controls, int patternId); // 0x1DF470 (C2 0x1DF410) + virtual ~BAPARunOverObject(); // 0x1DFBF0 + + virtual bool execute(Bot*, bool&, bool&); // 0x1DF4D0, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1DFB30, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1DFB20, slot +0x14; from the base declaration + +private: + /* +0x14 */ unsigned int m_object; // information handle of the target + /* +0x18 */ unsigned long long m_controls18; // the constructor's controls; no reader. The base + // m_controls (+0x08) stays 0, so getControls + // (BAPStatement's, slot +0x0C) answers 0 [INFERRED name] +}; // operator new size 0x20 (BBPRunOverSoldier::createPlan) + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPARUNOVEROBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASendRadioMessage.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASendRadioMessage.cpp new file mode 100644 index 000000000..feea7da3c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASendRadioMessage.cpp @@ -0,0 +1,57 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1DFEB0 (__tcf_0 0x1DFF10, _GLOBAL__I 0x1DFF40): 's Init object only. +#include + +#include "BAPASendRadioMessage.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/CommunicationAgent.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1DFCF0 (C1; C2 0x1DFC80): +4/+8/+0xC = 0, then +0x14 type, +0x18 channel, +0x1C priority, +// +0x20 the last int, +0x24 the float, +0x10 the pattern id (the image's store order). +BAPASendRadioMessage::BAPASendRadioMessage(AIRadioMessageType type, AIRadioChannelType channel, + unsigned int priority, float delay, int patternId, int target) +{ + m_controls = 0; + m_type = type; + m_channel = channel; + m_priority = priority; + m_target = target; + m_delay = delay; + m_patternId = patternId; +} + +// ELF 0x1DFDA0 (D0 0x1DFDE0) +BAPASendRadioMessage::~BAPASendRadioMessage() +{ +} + +// ELF 0x1DFE30: getCommunicationAgent (Bot +0xB0)->enqueueRadioMessage(+0x14, +0x18, +0x1C, +0x24, +0x20). +bool BAPASendRadioMessage::execute(Bot* bot, bool& ok, bool& finished) +{ + bot->getCommunicationAgent()->enqueueRadioMessage(m_type, m_channel, m_priority, m_delay, m_target); + ok = true; + finished = true; + return true; +} + +// ELF 0x1DFF60 +BAPStatementType BAPASendRadioMessage::getId() const +{ + return BAPSTSendRadioMessage; // 37 +} + +// ELF 0x1DFEA0 +bool BAPASendRadioMessage::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASendRadioMessage.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASendRadioMessage.h new file mode 100644 index 000000000..1a94d0d18 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASendRadioMessage.h @@ -0,0 +1,41 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPASENDRADIOMESSAGE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPASENDRADIOMESSAGE_H + +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B8A40 (8 words), operator new 0x28, package F-infantry. +// Queues one radio message on the bot's CommunicationAgent (enqueueRadioMessage). +class BAPASendRadioMessage : public BAPAction +{ +public: + BAPASendRadioMessage(AIRadioMessageType, AIRadioChannelType, unsigned int, float, int, int); // 0x1DFCF0 + virtual ~BAPASendRadioMessage(); // 0x1DFDA0 + + virtual bool execute(Bot*, bool&, bool&); // 0x1DFE30, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1DFF60, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1DFEA0, slot +0x14; from the base declaration + +private: + /* +0x14 */ AIRadioMessageType m_type; + /* +0x18 */ AIRadioChannelType m_channel; + /* +0x1C */ unsigned int m_priority; + /* +0x20 */ int m_target; // the constructor's last int, enqueueRadioMessage's last argument + /* +0x24 */ float m_delay; // [INFERRED] name: enqueueRadioMessage's float +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPASENDRADIOMESSAGE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASense.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASense.cpp new file mode 100644 index 000000000..01d45f993 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASense.cpp @@ -0,0 +1,55 @@ +// Sensing statement with two required, owned conditions; direct execution refuses the action. + +#include "BAPASense.h" + +#include "BAPCondition.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1DFFE0 (C1; C2 0x1DFF70) +BAPASense::BAPASense(BAPCondition* first, BAPCondition* second, int tag) + : BAPAction(UninitializedPatternId()), m_firstCondition(first), m_secondCondition(second) +{ + m_firstCondition->setOwner(this); + m_secondCondition->setOwner(this); + m_patternId = tag; +} + +// ELF 0x1E00C0 (D1; D2 0x1E0050, D0 0x1E0130) +BAPASense::~BAPASense() +{ + delete m_firstCondition; + delete m_secondCondition; +} + +// ELF 0x1E01B0 +bool BAPASense::execute(Bot*, bool& success, bool& finished) +{ + success = false; + finished = true; + return false; +} + +// ELF 0x1E01D0 +unsigned long long BAPASense::getControls() +{ + return 0; +} + +// ELF 0x1E01E0 +BAPStatementType BAPASense::getId() const +{ + return BAPSTSense; +} + +// ELF 0x1E01F0 +bool BAPASense::hasDefault() +{ + return false; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASense.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASense.h new file mode 100644 index 000000000..729e7cb69 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASense.h @@ -0,0 +1,39 @@ +// Sensing statement with two required, owned conditions; direct execution refuses the action. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPASENSE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPASENSE_H + +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B8AC0 (8 words), package H-deferred. +class BAPASense : public BAPAction +{ +public: + BAPASense(BAPCondition*, BAPCondition*, int); // 0x1DFFE0 + virtual ~BAPASense(); // 0x1E00C0 + + virtual bool execute(Bot*, bool&, bool&); // 0x1E01B0, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1E01D0, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1E01E0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1E01F0, slot +0x14; from the base declaration +private: + // EntrySense reads these inline (ELF 0x2C3A5A / 0x2C3AA0). + friend class EntrySense; + /* +0x14 */ BAPCondition* m_firstCondition; + /* +0x18 */ BAPCondition* m_secondCondition; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPASENSE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASetSensingAgentFocus.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASetSensingAgentFocus.cpp new file mode 100644 index 000000000..34ff0a028 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASetSensingAgentFocus.cpp @@ -0,0 +1,71 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1E05A0 (__tcf_0 0x1E0600, _GLOBAL__I 0x1E0630): 's Init object only. +#include + +#include "BAPASetSensingAgentFocus.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SensingAgent.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E0280 (C1; C2 0x1E01F0 region): target form. +BAPASetSensingAgentFocus::BAPASetSensingAgentFocus(float weight, unsigned int target, int tag, bool flag) +{ + m_controls = 0; + m_direction.x = 0.0f; + m_direction.y = 0.0f; + m_direction.z = 0.0f; + m_patternId = tag; + m_weight = weight; + m_target = target; + m_isTarget = true; + m_flag = flag; +} + +// ELF 0x1E0390: direction form (+0x1C is left unwritten). +BAPASetSensingAgentFocus::BAPASetSensingAgentFocus(float weight, const Vec3& direction, int tag, bool flag) +{ + m_controls = 0; + m_patternId = tag; + m_weight = weight; + m_direction = direction; + m_isTarget = false; + m_flag = flag; +} + +// ELF 0x1E0460 (D1; D2 0x1E0420 region, D0 0x1E04A0) +BAPASetSensingAgentFocus::~BAPASetSensingAgentFocus() +{ +} + +// ELF 0x1E04F0 +bool BAPASetSensingAgentFocus::execute(Bot* bot, bool& ok, bool& failed) +{ + if (m_isTarget) + bot->getSensingAgent()->insertPlanTargetInformation(m_weight, m_target, m_flag); + else + bot->getSensingAgent()->insertPlanDirectionInformation(m_weight, m_direction, m_flag); + ok = true; + failed = true; + return true; +} + +// ELF 0x1E0650 +BAPStatementType BAPASetSensingAgentFocus::getId() const +{ + return BAPSTSetSensingAgentFocus; // 35 +} + +// ELF 0x1E0590 +bool BAPASetSensingAgentFocus::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASetSensingAgentFocus.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASetSensingAgentFocus.h new file mode 100644 index 000000000..8f1becf17 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASetSensingAgentFocus.h @@ -0,0 +1,46 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPASETSENSINGAGENTFOCUS_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPASETSENSINGAGENTFOCUS_H + +#include "../../../../Math/Vec3.h" +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B8B00 (8 words), operator new 0x30, package C-actions. +// Puts a focus target (object handle) or a focus direction into the bot's SensingAgent. +class BAPASetSensingAgentFocus : public BAPAction +{ +public: + BAPASetSensingAgentFocus(float, unsigned int, int, bool); // 0x1E0280 + BAPASetSensingAgentFocus(float, const Vec3&, int, bool); // 0x1E0390 + virtual ~BAPASetSensingAgentFocus(); // 0x1E0460 + + virtual bool execute(Bot*, bool&, bool&); // 0x1E04F0, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1E0650, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1E0590, slot +0x14; from the base declaration + +private: + /* +0x14 */ float m_weight; // the ctor's float, first argument of both insertPlan* calls; [INFERRED] name + /* +0x18 */ bool m_flag; // the ctor's bool, last argument of both calls; [UNRESOLVED] meaning + /* +0x1C */ unsigned int m_target; // information handle (target form) + /* +0x20 */ Vec3 m_direction; // = 0 in the target form + /* +0x2C */ bool m_isTarget; // true: target form, false: direction form +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPASETSENSINGAGENTFOCUS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASoldierPose.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASoldierPose.cpp new file mode 100644 index 000000000..28fa938d8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASoldierPose.cpp @@ -0,0 +1,115 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +#include "BAPASoldierPose.h" + +#include "BAPCondition.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { +// `+0x08 = 0; +0x0C = 0x60` in every constructor: (1 << PILie) | (1 << PICrouch). +const unsigned long long kSoldierPoseControls = 0x6000000000ULL; +} + +// ELF 0x1E0740 (C1): one pose for all three cases, fire threshold 2, control threshold 0, +// no object, 5 s between changes; no break condition. +BAPASoldierPose::BAPASoldierPose(SoldierPose pose, BAPCondition* run, int tag, bool flag) + : BAPAComponentSoldierPose(pose, pose, 2.0f, pose, 0.0f, 0xFFFFFFFFu, 5.0f) +{ + m_breakCondition = 0; + m_runCondition = run; + m_flag = flag; + run->setOwner(this); + m_controls = kSoldierPoseControls; + m_patternId = tag; +} + +// ELF 0x1E0900 (C1): as above with a followed object. +BAPASoldierPose::BAPASoldierPose(SoldierPose pose, BAPCondition* run, int tag, unsigned int object, bool flag) + : BAPAComponentSoldierPose(pose, pose, 2.0f, pose, 0.0f, object, 5.0f) +{ + m_breakCondition = 0; + m_runCondition = run; + m_flag = flag; + run->setOwner(this); + m_controls = kSoldierPoseControls; + m_patternId = tag; +} + +// ELF 0x1E0AD0 (C1): run and break conditions (both owners set unconditionally). +BAPASoldierPose::BAPASoldierPose(SoldierPose pose, BAPCondition* run, BAPCondition* brk, int tag, bool flag) + : BAPAComponentSoldierPose(pose, pose, 2.0f, pose, 0.0f, 0xFFFFFFFFu, 5.0f) +{ + m_runCondition = run; + m_breakCondition = brk; + m_flag = flag; + run->setOwner(this); + m_breakCondition->setOwner(this); + m_controls = kSoldierPoseControls; + m_patternId = tag; +} + +// ELF 0x1E0CC0 (C1): the full chooser; the int fire threshold is converted to float. +BAPASoldierPose::BAPASoldierPose(SoldierPose normal, SoldierPose incommingFire, int fireObjectsThreshold, + SoldierPose danger, float controlThreshold, BAPCondition* run, + BAPCondition* brk, int tag, bool flag) + : BAPAComponentSoldierPose(normal, incommingFire, static_cast(fireObjectsThreshold), danger, + controlThreshold, 0xFFFFFFFFu, 5.0f) +{ + m_runCondition = run; + m_breakCondition = brk; + m_flag = flag; + if (run) + run->setOwner(this); + if (m_breakCondition) + m_breakCondition->setOwner(this); + m_controls = kSoldierPoseControls; + m_patternId = tag; +} + +// ELF 0x1E0E50 (D1; D0 0x1E0EE0; thunk D0 0x1E1000 through the +0x14 base): deletes both conditions. +BAPASoldierPose::~BAPASoldierPose() +{ + if (m_runCondition) + delete m_runCondition; + if (m_breakCondition) + delete m_breakCondition; +} + +// ELF 0x1E0FA0: runs only through EntrySoldierPose. +bool BAPASoldierPose::execute(Bot*, bool& ok, bool& failed) +{ + ok = false; + failed = true; + return false; +} + +// ELF 0x1E0F80 +BAPStatementType BAPASoldierPose::getId() const +{ + return BAPSTSoldierPose; // 26 +} + +// ELF 0x1E0F90 +bool BAPASoldierPose::hasDefault() +{ + return false; +} + +// ELF 0x1E0FC0 +BAPCondition* BAPASoldierPose::getRunCondition() +{ + return m_runCondition; +} + +// ELF 0x1E0FD0 +BAPCondition* BAPASoldierPose::getBreakCondition() +{ + return m_breakCondition; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASoldierPose.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASoldierPose.h new file mode 100644 index 000000000..f3b67fc45 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASoldierPose.h @@ -0,0 +1,55 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPASOLDIERPOSE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPASOLDIERPOSE_H + +#include "../../../AIInterface/BFKnowledge/SoldierPose.h" +#include "BAPAComponentSoldierPose.h" +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B8B80 (26 words; the BAPAComponentSoldierPose part at +0x14 uses 0x4B8BB0), package C-actions. +// Size 0x4C. Holds a soldier pose while the run condition holds; EntrySoldierPose does the work. +// Controls = PILie | PICrouch (`+0x0C = 0x60`: bits 37, 38). +class BAPASoldierPose : public BAPAction, public BAPAComponentSoldierPose +{ +public: + BAPASoldierPose(SoldierPose, BAPCondition*, int, bool); // 0x1E0740 + BAPASoldierPose(SoldierPose, BAPCondition*, int, unsigned int, bool); // 0x1E0900 + BAPASoldierPose(SoldierPose, BAPCondition*, BAPCondition*, int, bool); // 0x1E0AD0 + BAPASoldierPose(SoldierPose, SoldierPose, int, SoldierPose, float, BAPCondition*, BAPCondition*, int, bool); // 0x1E0CC0 + virtual ~BAPASoldierPose(); // 0x1E0E50 + + virtual bool execute(Bot*, bool&, bool&); // 0x1E0FA0, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1E0F80, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1E0F90, slot +0x14; from the base declaration + + BAPCondition* getRunCondition(); // 0x1E0FC0 (+0x40) + BAPCondition* getBreakCondition(); // 0x1E0FD0 (+0x44) + // [INFERRED] inline (no symbol): EntrySoldierPose::execute 0x2C3DBF `movzbl 0x48(%ecx)` passes + // it to Bot::requestSoldierPose. + bool getFlag() const { return m_flag; } + +private: + /* +0x40 */ BAPCondition* m_runCondition; + /* +0x44 */ BAPCondition* m_breakCondition; // may be null + /* +0x48 */ bool m_flag; // the ctors' last bool; [UNRESOLVED] meaning +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPASOLDIERPOSE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATrigger.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATrigger.cpp new file mode 100644 index 000000000..36b395528 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATrigger.cpp @@ -0,0 +1,108 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1E1960 (__tcf_0 0x1E19C0, _GLOBAL__I 0x1E19F0): 's Init object only. +#include + +#include "BAPATrigger.h" + +#include "BAPActionInline.h" +#include "BAPCondition.h" +#include "../Main/IBotManager.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E10F0 (C1; C2 0x1E0FE0 region) +BAPATrigger::BAPATrigger(io::PlayerInputMap input, BAPCondition* start, BAPCondition* stop, + unsigned long long controls, int tag, double duration, bool flag) +{ + m_startCondition = start; + m_input = input; + m_started = false; + m_stopCondition = stop; + m_flag = flag; + if (start) + start->setOwner(this); + if (m_stopCondition) + m_stopCondition->setOwner(this); + m_patternId = tag; + m_controls = controls; + m_endTime = bapinline::gameTime() + duration; +} + +// ELF 0x1E1240 (D1; D0 0x1E12C0): deletes both conditions. +BAPATrigger::~BAPATrigger() +{ + if (m_startCondition) + delete m_startCondition; + if (m_stopCondition) + delete m_stopCondition; +} + +// ELF 0x1E1340: runs only through EntryTrigger. +bool BAPATrigger::execute(Bot*, bool& ok, bool& failed) +{ + ok = false; + failed = true; + return false; +} + +// ELF 0x1E1A10 +unsigned long long BAPATrigger::getControls() +{ + return m_controls; +} + +// ELF 0x1E1A20 +BAPStatementType BAPATrigger::getId() const +{ + return BAPSTTrigger; // 11 +} + +// ELF 0x1E1A30 +bool BAPATrigger::hasDefault() +{ + return false; +} + +// ELF 0x1E1360: any level but 0 writes "Pushed button with id ''". +void BAPATrigger::debug(BotScriptDebugger::DebugLevel level, std::string& text) +{ + if (level != 0) { + std::ostringstream os; + bapinline::streamInput(os << "Pushed button with id '", m_input) << "'"; + text = os.str(); + } +} + +// ELF 0x1E17A0 +void BAPATrigger::streamSelf(std::ostream& out) const +{ + IBotManager* bm = IBotManager::instance; + bm->tabulate(out); + bapinline::streamInput(bapinline::streamType(out, getId()) << "(", m_input) << ")" << std::endl; + bm->tabulate(out); + out << '[' << std::endl; + bm->increaseTabLevel(); + bm->tabulate(out); + out << "StartCondition: "; + if (m_startCondition) + bapinline::streamCondition(out, m_startCondition); + out << std::endl; + bm->tabulate(out); + out << "StopCondition: "; + if (m_stopCondition) + bapinline::streamCondition(out, m_stopCondition); + out << std::endl; + bm->decreaseTabLevel(); + bm->tabulate(out); + out << ']' << std::endl; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATrigger.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATrigger.h new file mode 100644 index 000000000..3dc84cd31 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATrigger.h @@ -0,0 +1,53 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPATRIGGER_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPATRIGGER_H + +#include +#include +#include "../../../../IO/Input/Input.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B8C80 (8 words), operator new 0x30, package C-actions. +// Presses one input; EntryTrigger does the work and reads the fields below inline (public). +class BAPATrigger : public BAPAction +{ +public: + BAPATrigger(io::PlayerInputMap, BAPCondition*, BAPCondition*, unsigned long long, int, double, bool); // 0x1E10F0 + virtual ~BAPATrigger(); // 0x1E1240 + + virtual bool execute(Bot*, bool&, bool&); // 0x1E1340, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1E1A10, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1E1A20, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1E1A30, slot +0x14; from the base declaration + virtual void debug(BotScriptDebugger::DebugLevel, std::string&); // 0x1E1360, slot +0x18; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1E17A0, slot +0x1C; from the base declaration + + // [INFERRED] names from streamSelf's labels. + /* +0x14 */ io::PlayerInputMap m_input; + /* +0x18 */ BAPCondition* m_startCondition; // "StartCondition: ", may be null + /* +0x1C */ BAPCondition* m_stopCondition; // "StopCondition: ", may be null + /* +0x20 */ bool m_started; // = false; [UNRESOLVED] name, written by the entry + /* +0x24 */ double m_endTime; // game time at construction + the ctor's double + /* +0x2C */ bool m_flag; // the ctor's last bool; [UNRESOLVED] meaning +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPATRIGGER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATriggerContinously.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATriggerContinously.cpp new file mode 100644 index 000000000..b76809807 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATriggerContinously.cpp @@ -0,0 +1,101 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1E1FE0 (__tcf_0 0x1E2040, _GLOBAL__I 0x1E2070): 's Init object only. +#include + +#include "BAPATriggerContinously.h" + +#include "BAPActionInline.h" +#include "BAPCondition.h" +#include "../Main/IBotManager.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E1B20 (C1; C2 0x1E1A40 identical) +BAPATriggerContinously::BAPATriggerContinously(io::PlayerInputMap input, BAPCondition* start, + BAPCondition* stop, BAPCondition* abort, + unsigned long long controls, int tag, double duration) +{ + m_startCondition = start; + m_input = input; + m_stopCondition = stop; + m_started = false; + m_abortCondition = abort; + start->setOwner(this); + if (m_stopCondition) + m_stopCondition->setOwner(this); + if (m_abortCondition) + m_abortCondition->setOwner(this); + m_patternId = tag; + m_controls = controls; + m_endTime = bapinline::gameTime() + duration; +} + +// ELF 0x1E1C90 (D1; D2 0x1E1C00, D0 0x1E1D20): deletes start, stop, abort (virtual D0). +BAPATriggerContinously::~BAPATriggerContinously() +{ + if (m_startCondition) + delete m_startCondition; + if (m_stopCondition) + delete m_stopCondition; + if (m_abortCondition) + delete m_abortCondition; +} + +// ELF 0x1E1DB0: runs only through EntryTriggerContinously. +bool BAPATriggerContinously::execute(Bot*, bool& ok, bool& failed) +{ + ok = false; + failed = true; + return false; +} + +// ELF 0x1E2090 +unsigned long long BAPATriggerContinously::getControls() +{ + return m_controls; +} + +// ELF 0x1E20A0 +BAPStatementType BAPATriggerContinously::getId() const +{ + return BAPSTTriggerContinously; // 12 +} + +// ELF 0x1E20B0 +bool BAPATriggerContinously::hasDefault() +{ + return false; +} + +// ELF 0x1E1DD0 +void BAPATriggerContinously::streamSelf(std::ostream& out) const +{ + IBotManager* bm = IBotManager::instance; + bm->tabulate(out); + bapinline::streamInput(bapinline::streamType(out, getId()) << "(", m_input) << ")" << std::endl; + bm->tabulate(out); + out << '[' << std::endl; + bm->increaseTabLevel(); + bm->tabulate(out); + bapinline::streamCondition(out << "StartCondition: ", m_startCondition) << std::endl; + if (m_stopCondition) { + bm->tabulate(out); + bapinline::streamCondition(out << "StopCondition: ", m_stopCondition) << std::endl; + } + if (m_abortCondition) { + bm->tabulate(out); + bapinline::streamCondition(out << "AbortCondition: ", m_abortCondition) << std::endl; + } + bm->decreaseTabLevel(); + bm->tabulate(out); + out << ']' << std::endl; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATriggerContinously.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATriggerContinously.h new file mode 100644 index 000000000..7ab2fc0ac --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATriggerContinously.h @@ -0,0 +1,51 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPATRIGGERCONTINOUSLY_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPATRIGGERCONTINOUSLY_H + +#include +#include "../../../../IO/Input/Input.h" +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B8D00 (8 words), package C-actions. +// Holds one input while the plan runs; EntryTriggerContinously does the work and reads the +// fields below inline (public). Size 0x30. +class BAPATriggerContinously : public BAPAction +{ +public: + BAPATriggerContinously(io::PlayerInputMap, BAPCondition*, BAPCondition*, BAPCondition*, unsigned long long, int, double); // 0x1E1B20 + virtual ~BAPATriggerContinously(); // 0x1E1C90 + + virtual bool execute(Bot*, bool&, bool&); // 0x1E1DB0, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1E2090, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1E20A0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1E20B0, slot +0x14; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1E1DD0, slot +0x1C; from the base declaration + + // [INFERRED] names from streamSelf's labels. + /* +0x14 */ io::PlayerInputMap m_input; + /* +0x18 */ BAPCondition* m_startCondition; // "StartCondition: ", required (owner set unconditionally) + /* +0x1C */ BAPCondition* m_stopCondition; // "StopCondition: ", may be null + /* +0x20 */ BAPCondition* m_abortCondition; // "AbortCondition: ", may be null + /* +0x24 */ bool m_started; // = false; [UNRESOLVED] name, written by the entry + /* +0x28 */ double m_endTime; // game time at construction + the ctor's double +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPATRIGGERCONTINOUSLY_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurn.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurn.cpp new file mode 100644 index 000000000..866ade64d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurn.cpp @@ -0,0 +1,50 @@ +// Turn statement base. Recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +#include "BAPATurn.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1E22B0, __tcf_0 0x1E2310, _GLOBAL__I 0x1E2340). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E2140 (C1; C2 0x1E20C0). The inline BAPStatement base clears +0x04/+0x08 and counts +// `news`; then +0x14 = cond, +0x18 = speed, +0x1C/+0x20 and +0x28..+0x30 = 0 (+0x24 is left), +// +0x08 = controls, +0x10 = tag. The condition's owner is set by the derived constructors. +BAPATurn::BAPATurn(float turnSpeed, BAPCondition* endCondition, unsigned long long controls, int tag) +{ + m_endCondition = endCondition; + m_turnSpeed = turnSpeed; + m_float1C = 0.0f; + m_float20 = 0.0f; + m_vec28.x = 0.0f; + m_vec28.y = 0.0f; + m_vec28.z = 0.0f; + m_controls = controls; + m_patternId = tag; +} + +// ELF 0x1E2200 (D1; D2 0x1E21C0, D0 0x1E2240): only the inline base destructor (`destroys`). +BAPATurn::~BAPATurn() +{ +} + +// ELF 0x1E2290: a turn never runs by itself (the entries do the work): ok = false, failed = true. +bool BAPATurn::execute(Bot*, bool& ok, bool& failed) +{ + ok = false; + failed = true; + return false; +} + +// ELF 0x1E2360 (weak) +BAPStatementType BAPATurn::getId() const +{ + return BAPSTTurn; // 24 +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurn.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurn.h new file mode 100644 index 000000000..819aed077 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurn.h @@ -0,0 +1,46 @@ +// Turn statement base: the vehicle turn entries steer towards getDirection(). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPATURN_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPATURN_H + +#include "../../../../Math/Vec3.h" +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B8D40 (9 words), package H-deferred. Size 0x34 (BAPATurnTowardsDirection's data +// starts at +0x34). +class BAPATurn : public BAPAction +{ +public: + BAPATurn(float, BAPCondition*, unsigned long long, int); // 0x1E2140 + virtual ~BAPATurn(); // 0x1E2200 + + virtual bool execute(Bot*, bool&, bool&); // 0x1E2290, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1E2360, slot +0x10; from the base declaration + virtual bool hasDefault() { return false; } // 0x1E2370 (weak), slot +0x14 + virtual Vec3 getDirection(bool&) = 0; // no body, slot +0x20; [INFERRED] from BAPATurnTowardsObject: ELF sret (returned through a hidden pointer) + + // [INFERRED] names; the constructor's stores are attested. The turn entries own the reads. + /* +0x14 */ BAPCondition* m_endCondition; // the derived classes own and delete it + /* +0x18 */ float m_turnSpeed; // the ctor's float + /* +0x1C */ float m_float1C; // = 0 [UNRESOLVED] + /* +0x20 */ float m_float20; // = 0 [UNRESOLVED] + /* +0x24 */ float m_unwritten24; // [UNRESOLVED] not written by the constructor + /* +0x28 */ Vec3 m_vec28; // = 0 [UNRESOLVED] +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPATURN_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurnTowardsDirection.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurnTowardsDirection.cpp new file mode 100644 index 000000000..81987c9af --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurnTowardsDirection.cpp @@ -0,0 +1,42 @@ +// Turn statement towards a fixed direction. Recovered from libaidll.so 1.5.3153 (ia-32); ELF +// addresses on every body. + +#include "BAPATurnTowardsDirection.h" + +#include "BAPCondition.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1E25D0, __tcf_0 0x1E2630, _GLOBAL__I 0x1E2660). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E2410 (C1; C2 0x1E2380): the base, the direction, then the end condition's owner (not +// null-checked). +BAPATurnTowardsDirection::BAPATurnTowardsDirection(const Vec3& direction, float turnSpeed, BAPCondition* endCondition, + unsigned long long controls, int tag) + : BAPATurn(turnSpeed, endCondition, controls, tag) +{ + m_direction = direction; + m_endCondition->setOwner(this); +} + +// ELF 0x1E24F0 (D1; D2 0x1E24A0, D0 0x1E2540): deletes the end condition. +BAPATurnTowardsDirection::~BAPATurnTowardsDirection() +{ + if (m_endCondition) + delete m_endCondition; +} + +// ELF 0x1E25A0: always valid. +Vec3 BAPATurnTowardsDirection::getDirection(bool& ok) +{ + ok = true; + return m_direction; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurnTowardsDirection.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurnTowardsDirection.h new file mode 100644 index 000000000..4027cd0b0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurnTowardsDirection.h @@ -0,0 +1,34 @@ +// Turn statement towards a fixed direction. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPATURNTOWARDSDIRECTION_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPATURNTOWARDSDIRECTION_H + +#include "../../../../Math/Vec3.h" +#include "BAPATurn.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; + +// ELF: vtable 0x4B8D80 (9 words), package H-deferred. +class BAPATurnTowardsDirection : public BAPATurn +{ +public: + BAPATurnTowardsDirection(const Vec3&, float, BAPCondition*, unsigned long long, int); // 0x1E2410 + virtual ~BAPATurnTowardsDirection(); // 0x1E24F0 + + virtual Vec3 getDirection(bool&); // 0x1E25A0, slot +0x20; from the base declaration + + /* +0x34 */ Vec3 m_direction; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPATURNTOWARDSDIRECTION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurnTowardsObject.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurnTowardsObject.cpp new file mode 100644 index 000000000..7f53496fc --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurnTowardsObject.cpp @@ -0,0 +1,61 @@ +// Turn statement towards an object. Recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on +// every body. + +#include "BAPATurnTowardsObject.h" + +#include "BAPActionInline.h" +#include "BAPCondition.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1E2B30, __tcf_0 0x1E2B90, _GLOBAL__I 0x1E2BC0). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E27C0 (C1; C2 0x1E2680): the base, the target at +0x38, the bot at +0x34. For the bot's +// equipment and then the target, a non-primary information asks for its primary object of the +// bot's side; both answers are discarded as compiled (neither information is null-checked). +// Finally the end condition's owner (not null-checked). +BAPATurnTowardsObject::BAPATurnTowardsObject(Bot* bot, unsigned int target, float turnSpeed, + BAPCondition* endCondition, unsigned long long controls, int tag) + : BAPATurn(turnSpeed, endCondition, controls, tag) +{ + m_target = target; + m_bot = bot; + Information* const self = bapinline::info(bot->getCurrentEquipment()); + if (!self->isPrimary()) + self->getPrimaryObject(bot->getSide()); // [UNRESOLVED] result unused in the image (0x1E28EC) + Information* const object = bapinline::info(target); + if (!object->isPrimary()) + object->getPrimaryObject(bot->getSide()); // [UNRESOLVED] result unused in the image (0x1E28CB) + m_endCondition->setOwner(this); +} + +// ELF 0x1E2950 (D1; D2 0x1E2900, D0 0x1E29A0): deletes the end condition. +BAPATurnTowardsObject::~BAPATurnTowardsObject() +{ + if (m_endCondition) + delete m_endCondition; +} + +// ELF 0x1E2A00: target position minus the bot's equipment position (not normalised; the +// equipment information is not null-checked). A stale target: ok = false and (1, 0, 0). +Vec3 BAPATurnTowardsObject::getDirection(bool& ok) +{ + Information* const target = bapinline::info(m_target); + ok = target != 0; + if (!ok) + return bapinline::vec3(1.0f, 0.0f, 0.0f); + const Vec3& selfPosition = bapinline::info(m_bot->getCurrentEquipment())->getPosition(); + const Vec3& targetPosition = target->getPosition(); + return bapinline::vec3(targetPosition.x - selfPosition.x, targetPosition.y - selfPosition.y, + targetPosition.z - selfPosition.z); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurnTowardsObject.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurnTowardsObject.h new file mode 100644 index 000000000..ac0227975 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurnTowardsObject.h @@ -0,0 +1,37 @@ +// Turn statement towards an object. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPATURNTOWARDSOBJECT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPATURNTOWARDSOBJECT_H + +#include "../../../../Math/Vec3.h" +#include "BAPATurn.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B8DC0 (9 words), package H-deferred. Size 0x3C (`operator new(0x3c)` in +// BBPFire2dDriver::createPlan). +class BAPATurnTowardsObject : public BAPATurn +{ +public: + BAPATurnTowardsObject(Bot*, unsigned int, float, BAPCondition*, unsigned long long, int); // 0x1E27C0 + virtual ~BAPATurnTowardsObject(); // 0x1E2950 + + virtual Vec3 getDirection(bool&); // 0x1E2A00, slot +0x20; from the base declaration + + /* +0x34 */ Bot* m_bot; + /* +0x38 */ unsigned int m_target; // information handle +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPATURNTOWARDSOBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAUpdateVehicle.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAUpdateVehicle.cpp new file mode 100644 index 000000000..3ad32c864 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAUpdateVehicle.cpp @@ -0,0 +1,56 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1E2DA0 (__tcf_0 0x1E2E00, _GLOBAL__I 0x1E2E30): 's Init object only. +#include + +#include "BAPAUpdateVehicle.h" + +#include "../AIBot/BotMain.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E2C30 (C1; C2 0x1E2BE0): +4/+8/+0xC = 0, +0x10 = the pattern id. +BAPAUpdateVehicle::BAPAUpdateVehicle(int patternId) + : BAPAction() +{ + m_controls = 0; + m_patternId = patternId; +} + +// ELF 0x1E2CC0 (D0 0x1E2D00): the inlined ~BAPStatement only. +BAPAUpdateVehicle::~BAPAUpdateVehicle() +{ +} + +// ELF 0x1E2D50: BotMain::setUpdateCurrentEquipment, then ok = finished = true. +bool BAPAUpdateVehicle::execute(Bot* bot, bool& ok, bool& finished) +{ + static_cast(bot)->setUpdateCurrentEquipment(); + ok = true; + finished = true; + return true; +} + +// ELF 0x1E2E50 +unsigned long long BAPAUpdateVehicle::getControls() +{ + return 0; +} + +// ELF 0x1E2E60 +BAPStatementType BAPAUpdateVehicle::getId() const +{ + return BAPSTUpdateVehicle; // 27 +} + +// ELF 0x1E2D90 +bool BAPAUpdateVehicle::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAUpdateVehicle.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAUpdateVehicle.h new file mode 100644 index 000000000..dc882ba18 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAUpdateVehicle.h @@ -0,0 +1,36 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAUPDATEVEHICLE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAUPDATEVEHICLE_H + +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B8E00 (8 words), operator new 0x14, package F-infantry. +// Asks the bot to re-read its current equipment (BotMain::setUpdateCurrentEquipment) after a change. +// The constructor argument is the creating pattern's id (BAPStatement +0x10). +class BAPAUpdateVehicle : public BAPAction +{ +public: + explicit BAPAUpdateVehicle(int); // 0x1E2C30 + virtual ~BAPAUpdateVehicle(); // 0x1E2CC0 + + virtual bool execute(Bot*, bool&, bool&); // 0x1E2D50, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1E2E50, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1E2E60, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1E2D90, slot +0x14; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAUPDATEVEHICLE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAUseFlareOnMissileLock.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAUseFlareOnMissileLock.cpp new file mode 100644 index 000000000..5cbd42016 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAUseFlareOnMissileLock.cpp @@ -0,0 +1,79 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1E3180 (__tcf_0 0x1E31E0, _GLOBAL__I 0x1E3210): 's Init object only. +#include + +#include "BAPAUseFlareOnMissileLock.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E2EE0 (C1) +BAPAUseFlareOnMissileLock::BAPAUseFlareOnMissileLock(Bot* bot, unsigned long long controls, int patternId) +{ + m_bot = bot; + m_controls = controls; + m_lockTime = -1.0; + m_locked = false; + m_patternId = patternId; +} + +// ELF 0x1E2F90 (D0 0x1E2FD0) +BAPAUseFlareOnMissileLock::~BAPAUseFlareOnMissileLock() +{ +} + +// ELF 0x1E3020. `time` is a function-static double (data 0x4B8E68 = 1.0). The flare input is +// written inline (mapped bit 47 -> inputs[47] = 1). The information is not null-checked. +bool BAPAUseFlareOnMissileLock::execute(Bot* bot, bool& ok, bool& failed) +{ + static double time = 1.0; + Information* info = bapinline::info(bot->getCurrentEquipment()); + IPIUnit* unit = info->getUnit(); + const int status = unit->getMissileLockStatus(); + const double now = bapinline::gameTime(); + bool locked = m_locked; + if (!locked && 0 < status) { + m_locked = true; + locked = true; + m_lockTime = now; + } + double wait = time; + if (!info->isOfType(ITAir)) + wait = 0.0; + if (locked && wait <= now - m_lockTime) { + io::PlayerInput* input = bot->getInput(); + if ((input->mappingFlags >> io::PIFlareFire) & 1ULL) + input->inputs[io::PIFlareFire] = 1.0f; + unit->setMissileLockStatus(0); + m_locked = false; + } + ok = true; + failed = true; + return true; +} + +// ELF 0x1E3160 +BAPStatementType BAPAUseFlareOnMissileLock::getId() const +{ + return BAPSTUseFlareOnMissileLock; // 40 +} + +// ELF 0x1E3170 +bool BAPAUseFlareOnMissileLock::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAUseFlareOnMissileLock.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAUseFlareOnMissileLock.h new file mode 100644 index 000000000..daa30166a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAUseFlareOnMissileLock.h @@ -0,0 +1,43 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAUSEFLAREONMISSILELOCK_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAUSEFLAREONMISSILELOCK_H + +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B8E80 (8 words), operator new 0x24, package C-actions. +// Fires flares (PIFlareFire) once a missile lock on the bot's vehicle has lasted the +// static delay (1 s for vehicles with type flag 0x10, else at once), then clears the lock status. +class BAPAUseFlareOnMissileLock : public BAPAction +{ +public: + BAPAUseFlareOnMissileLock(Bot*, unsigned long long, int); // 0x1E2EE0 + virtual ~BAPAUseFlareOnMissileLock(); // 0x1E2F90 + + virtual bool execute(Bot*, bool&, bool&); // 0x1E3020, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1E3160, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1E3170, slot +0x14; from the base declaration + +private: + /* +0x14 */ Bot* m_bot; + /* +0x18 */ double m_lockTime; // = -1.0 + /* +0x20 */ bool m_locked; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAUSEFLAREONMISSILELOCK_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAction.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAction.h new file mode 100644 index 000000000..1995b99d5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAction.h @@ -0,0 +1,37 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPACTION_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPACTION_H + +#include "BAPStatement.h" + +namespace dice { +namespace hfe { + +namespace ai { + + +// Action base. Vtable 0x4B8000; no members of its own (inline in the image). +// ELF: vtable 0x4B8000 (8 words), package S0-skeleton. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BAPAction : public BAPStatement +{ +public: + BAPAction() = default; + virtual ~BAPAction() {} // weak in the image (inline) + +protected: + // [CHOSEN, not recovered] forward the selector for BAPADebug's omitted pattern-id store + // (inline base construction in ELF 0x1FB6F0). + explicit BAPAction(UninitializedPatternId tag) : BAPStatement(tag) {} +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPACTION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPActionInline.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPActionInline.h new file mode 100644 index 000000000..2cfde386a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPActionInline.h @@ -0,0 +1,149 @@ +// [CHOSEN, not recovered] package C (ai-w1-c-actions): the inline helpers the BAP actions and +// conditions spell out in place. libaidll.so has no symbol for any of them; each one is the exact +// expansion seen in the bodies that cite it (ELF addresses there). Header-only, no build-list entry. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPACTIONINLINE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPACTIONINLINE_H + +#include "../../../../Math/Vec3.h" +#include "../../../../IO/Input/PlayerInput.h" +#include "../Main/InformationManager.h" +#include "BAPCondition.h" +#include "BAPTypes.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../AIUtils/IgnoreListPredicate.h" +#include "../Main/AIStreamOperators.h" + +#include +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +class BAPCondition; +class IAIObject; + +namespace bapinline { + +// informationManager->m_pool->get(handle): `h & 0xFFFF` one-based slot, `h >> 16` generation +// (e.g. BAPALookAtObject::getLookDirection 0x1D3320, BAPAMergeSoldierInputs::execute 0x1D3F00). +inline Information* info(unsigned int handle) +{ + return informationManager->getInformation(handle); +} + +// `(mappingFlags >> i) & 1 ? inputs[i] : 0.0f`: an unmapped input reads as zero +// (BAPAMergeSoldierInputs::execute 0x1D3FF0: bit 13 then +0x34; bit 3 then +0x0C). +inline float mappedInput(const io::PlayerInput* in, io::PlayerInputMap i) +{ + return ((in->mappingFlags >> static_cast(i)) & 1ULL) ? in->inputs[i] : 0.0f; +} + +inline Vec3 vec3(float x, float y, float z) +{ + Vec3 v; + v.x = x; + v.y = y; + v.z = z; + return v; +} + +inline Vec3 sub(const Vec3& a, const Vec3& b) { return vec3(a.x - b.x, a.y - b.y, a.z - b.z); } +inline Vec3 add(const Vec3& a, const Vec3& b) { return vec3(a.x + b.x, a.y + b.y, a.z + b.z); } +inline float dot(const Vec3& a, const Vec3& b) { return a.x * b.x + a.y * b.y + a.z * b.z; } +inline float lengthSqr(const Vec3& a) { return dot(a, a); } + +// The engine's inline Vec3 normalise: left alone within FLT_EPSILON of unit length, zeroed when +// the squared length is below FLT_EPSILON, else scaled by 1/sqrt (0x1D3495..0x1D351A). +inline void normalize(Vec3& v) +{ + const float lsq = lengthSqr(v); + if (std::fabs(1.0f - lsq) < 1.1920929e-07f) + return; + if (std::fabs(lsq) < 1.1920929e-07f) { + v = vec3(0.0f, 0.0f, 0.0f); + return; + } + const float inv = 1.0f / std::sqrt(lsq); + v.x *= inv; + v.y *= inv; + v.z *= inv; +} + +// The Vec2 variant: zeroed below FLT_EPSILON^2 (1.4210855e-14), BAPAMergeSoldierInputs 0x1D3F00. +inline void normalize(Vec2& v) +{ + const float lsq = v.x * v.x + v.y * v.y; + if (std::fabs(lsq - 1.0f) < 1.1920929e-07f) + return; + if (std::fabs(lsq) < 1.4210855e-14f) { + v.x = 0.0f; + v.y = 0.0f; + return; + } + const float inv = 1.0f / std::sqrt(lsq); + v.x *= inv; + v.y *= inv; +} + +// CommonSingletonServer::m_iBFTimer->vfn+0x08 / +0x0C (BAPATriggerContinously ctor 0x1E1BDF). +inline double gameTime() +{ + return static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); +} + +inline double timeIncrease() +{ + return static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease(); +} + +// operator<<(std::ostream&, const BAPCondition&) (ELF 0x1F80D0, A-core's BAPCondition.cpp). +inline std::ostream& streamCondition(std::ostream& out, const BAPCondition* condition) +{ + return out << *condition; +} + +// io::operator<<(std::ostream&, PlayerInputMap) (ELF 0x48D5A0, IO/Input/InputMapStream.cpp): the +// shipped libaidll.so carries its own copy, and so does bf2_aidll (aidll_sources.txt). +inline std::ostream& streamInput(std::ostream& out, io::PlayerInputMap input) +{ + return io::operator<<(out, input); +} + +// operator<<(std::ostream&, BAPStatementType) (ELF 0x3C7D90) and operator<<(std::ostream&, +// BAPConditionType) (0x3C7AE0), ai-main's Main/AIStreamOperators.cpp. +inline std::ostream& streamType(std::ostream& out, BAPStatementType type) +{ + return out << type; +} + +inline std::ostream& streamType(std::ostream& out, BAPConditionType type) +{ + return out << type; +} + +// `std::vector ignore; ignore.push_back(object); IgnoreListPredicate pred(ignore); +// m_iaiObjectEnvironment->collideLineWithWorld(from, to, &pred, &hit)` (slot +0x44), spelled out +// in BAPConSplashDamage::evaluate (push_back 0x1EA618, ctor 0x1EA627), BAPConOkToThrowGrenade:: +// evaluate (two traces; the second reuses the predicate after `ignore.resize(0); +// ignore.push_back(target)`, the same one-element list) and BAPWrapperAiming::getGroundLevelAtPos +// 0x1F8CF0. `hit` is the caller's zeroed output. +inline bool collideLineIgnoring(const Vec3& from, const Vec3& to, IAIObject* object, Vec3& hit) +{ + std::vector ignore; + ignore.push_back(object); + IgnoreListPredicate predicate(ignore); + return static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->collideLineWithWorld(from, to, &predicate, &hit); +} + +} // namespace bapinline +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPACTIONINLINE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPBoleanOp.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPBoleanOp.h new file mode 100644 index 000000000..8e5070277 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPBoleanOp.h @@ -0,0 +1,40 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPBOLEANOP_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPBOLEANOP_H + +#include +#include "BAPCondition.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; + +// Base of And/Or/Not. Vtable 0x4B9E60. Inline in the image: BAPConAnd() 0x1F3D30 stores the +// BAPBoleanOp vptr, +4 = 0 and builds the list before its own vptr; ~BAPConAnd 0x1F3E10 deletes the +// children under its own vptr, then clears and frees the list under BAPBoleanOp's. +// ELF: vtable 0x4B9E60 (6 words), package S0-skeleton (layout: A-core). +class BAPBoleanOp : public BAPCondition +{ +public: + BAPBoleanOp() {} + virtual ~BAPBoleanOp() {} // weak in the image (inline); the list destructor runs here + + virtual void addCondition(BAPCondition*) = 0; // no body, slot +0x14; ELF void (BAPConAnd 0x1F40A0) + +protected: + /* +0x08 */ std::list m_conditions; // owned: the derived destructors delete them +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPBOLEANOP_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConBombPrecision3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConBombPrecision3d.cpp new file mode 100644 index 000000000..f265198d2 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConBombPrecision3d.cpp @@ -0,0 +1,91 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// [PLATFORM] precision: the x87 build compares the squared miss distance in extended precision. + +// static init: ELF 0x1EB440 (__tcf_0 0x1EB4A0, _GLOBAL__I 0x1EB4D0): 's Init object only. +#include + +#include "BAPCConBombPrecision3d.h" + +#include +#include + +#include "../AIBot/BotMain.h" +#include "BAPAAimAt3d.h" +#include "BAPActionInline.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1EB110 (C1; C2 0x1EB0B0) +BAPCConBombPrecision3d::BAPCConBombPrecision3d(BAPAAimAt3d* aim, float precision, bool waitForClosest) +{ + m_precisionSq = std::max(0.01f, precision * precision); + m_aim = aim; + m_bestDistanceSq = FLT_MAX; + m_float14 = FLT_MAX; + m_waitForClosest = waitForClosest; +} + +// ELF 0x1EB4F0 (D0 0x1EB510): base only. +BAPCConBombPrecision3d::~BAPCConBombPrecision3d() +{ +} + +// ELF 0x1EB170. The aimer transform is fetched and not used; a failed closest approach keeps its +// best distance (unlike BAPCConPrecision3d), as compiled. +bool BAPCConBombPrecision3d::evaluate(Bot* bot) +{ + if (!m_aim->isAimVecValid()) + return false; + if (!bapinline::info(bot->getCurrentEquipment())) + return false; + double impactTime; + m_aim->getImpactTime(impactTime); + Vec3 aimVec = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_aim->getLastAimVec(aimVec); + m_aim->getAimerTransform(); + Vec3 predicted = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_aim->getPredictedPosition(predicted); + Vec3 impact = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (!m_aim->getImpactPosition(impact, impactTime - bapinline::gameTime())) + return false; + const float distanceSq = bapinline::lengthSqr(bapinline::sub(predicted, impact)); + + if (m_waitForClosest) + { + const float precisionSq = m_precisionSq; + if (!(precisionSq * 0.25f > distanceSq)) + { + const float best = m_bestDistanceSq; + if (best > 0.01 && best >= distanceSq) + { + m_bestDistanceSq = distanceSq; // still closing in + if (precisionSq >= distanceSq) + static_cast(bot)->setHadPrecisionTimeStamp(bapinline::gameTime()); + return false; + } + if (!(precisionSq >= best)) + return false; + static_cast(bot)->setHadPrecisionTimeStamp(bapinline::gameTime()); + m_bestDistanceSq = FLT_MAX; + return true; + } + } + else if (!(m_precisionSq >= distanceSq)) + { + return false; + } + static_cast(bot)->setHadPrecisionTimeStamp(bapinline::gameTime()); + return true; +} + +// ELF 0x1EB430 +BAPConditionType BAPCConBombPrecision3d::getConditionType() const +{ + return BAPCTBombPrecision3d; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConBombPrecision3d.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConBombPrecision3d.h new file mode 100644 index 000000000..7e1a9639b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConBombPrecision3d.h @@ -0,0 +1,42 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCCONBOMBPRECISION3D_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCCONBOMBPRECISION3D_H + +#include "BAPConnectedCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPAAimAt3d; +class Bot; + +// ELF: vtable 0x4B9510 (5 words), operator new 0x1C, package G-vehicles. +// BAPCConPrecision3d for bombs, without the angle test: the squared precision is at least 0.01; +// with waitForClosest a miss within half the precision answers at once. +class BAPCConBombPrecision3d : public BAPConnectedCondition +{ +public: + BAPCConBombPrecision3d(BAPAAimAt3d*, float, bool); // 0x1EB110 + virtual ~BAPCConBombPrecision3d(); // 0x1EB4F0 + + virtual bool evaluate(Bot*); // 0x1EB170, slot +0x00 + virtual BAPConditionType getConditionType() const; // 0x1EB430, slot +0x04 + +private: + /* +0x08 */ float m_precisionSq; + /* +0x0C */ BAPAAimAt3d* m_aim; + /* +0x10 */ float m_bestDistanceSq; // FLT_MAX: no approach yet + /* +0x14 */ float m_float14; // [UNRESOLVED] constructed FLT_MAX, never read + /* +0x18 */ bool m_waitForClosest; // [INFERRED] name +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCCONBOMBPRECISION3D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConLookDeviation.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConLookDeviation.cpp new file mode 100644 index 000000000..7c20610a1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConLookDeviation.cpp @@ -0,0 +1,94 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1EB990 (__tcf_0 0x1EB9F0, _GLOBAL__I 0x1EBA20): 's Init object only. +#include + +#include "BAPCConLookDeviation.h" + +#include "BAPALook.h" +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../../../../Math/Mat4.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1EB5D0 (C1) +BAPCConLookDeviation::BAPCConLookDeviation(BAPALook* look, float angle, bool flat) +{ + m_look = look; + m_flat = flat; + float a = 0.0f; + if (0.0f <= angle) { + a = angle; + if (3.1415927f < angle) + a = 3.1415927f; + } + m_cosLimit = std::cos(a); +} + +// ELF 0x1EB670 (D0 0x1EB690) +BAPCConLookDeviation::~BAPCConLookDeviation() +{ +} + +// ELF 0x1EB6D0: dot of the normalised look direction with camera row 2 (forward, +0x20) of +// IAIPlayer::getCameraTransformation (+0x8C) against the cosine limit; too short a direction or +// no player/information/look: false. +bool BAPCConLookDeviation::evaluate(Bot* bot) +{ + if (!bapinline::info(bot->getCurrentEquipment())) + return false; + bool valid; + Vec3 d = m_look->getLookDirection(valid); + if (!valid) + return false; + if (!m_flat) { + const float len = std::sqrt(d.z * d.z + d.y * d.y + d.x * d.x); + if (0.001f <= len) { + const float inv = 1.0f / len; + d.x *= inv; + d.y *= inv; + d.z = inv * d.z; + if (!bot->getPlayer()) + return false; + const Mat4& cam = *static_cast(bot->getPlayer()->getCameraTransformation()); + return m_cosLimit <= d.z * cam.m[10] + d.y * cam.m[9] + d.x * cam.m[8]; + } + return false; + } + d.y = 0.0f; + const float len = std::sqrt(d.z * d.z + d.x * d.x + 0.0f); + if (0.0001f <= len) { + const float inv = 1.0f / len; + d.x *= inv; + d.y *= inv; + d.z = inv * d.z; + if (!bot->getPlayer()) + return false; + const Mat4& cam = *static_cast(bot->getPlayer()->getCameraTransformation()); + const float fx = cam.m[8]; + const float fz = cam.m[10]; + const float flen = std::sqrt(fx * fx + 0.0f + fz * fz); + if (0.0001f <= flen) { + const float finv = 1.0f / flen; + return m_cosLimit <= fx * finv * d.x + 0.0f * finv * d.y + finv * fz * d.z; + } + } + return false; +} + +// ELF 0x1EB980 +BAPConditionType BAPCConLookDeviation::getConditionType() const +{ + return BAPCTLookDeviation; // 0 +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConLookDeviation.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConLookDeviation.h new file mode 100644 index 000000000..0e77757e1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConLookDeviation.h @@ -0,0 +1,43 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCCONLOOKDEVIATION_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCCONLOOKDEVIATION_H + +#include "BAPConnectedCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPALook; +class Bot; + +// ELF: vtable 0x4B9548 (5 words), operator new 0xC/0x14, package C-actions. +// True while the camera looks within an angle of the connected look's direction (3d, or XZ +// with the flag). Not owned: the look statement belongs to the plan. +class BAPCConLookDeviation : public BAPConnectedCondition +{ +public: + BAPCConLookDeviation(BAPALook*, float, bool); // 0x1EB5D0 + virtual ~BAPCConLookDeviation(); // 0x1EB670 + + virtual bool evaluate(Bot*); // 0x1EB6D0, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EB980, slot +0x04; from the base declaration + +private: + /* +0x08 */ float m_cosLimit; // cos(clamp(angle, 0, pi)) + /* +0x0C */ BAPALook* m_look; + /* +0x10 */ bool m_flat; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCCONLOOKDEVIATION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision.cpp new file mode 100644 index 000000000..9add832cf --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision.cpp @@ -0,0 +1,199 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1EC520 (__tcf_0 0x1EC580, _GLOBAL__I 0x1EC5B0): 's Init object only. +#include + +#include "BAPCConPrecision.h" + +#include "BAPAAimAt.h" +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// The function-static `negativeYLimitFactor` of BAPCConPrecision::evaluate (ELF .data 0x4B95A4). +const float negativeYLimitFactor = 0.1f; + +} // namespace + +// ELF 0x1EBAF0 (C1; C2 0x1EBA40): against an aim action. +BAPCConPrecision::BAPCConPrecision(unsigned int target, BAPAAimAt* aim, float precision, bool waitForBest, + bool limitPositiveY, bool noAngleCheck) +{ + m_target = target; + m_precisionSqr = 0.01f <= precision * precision ? precision * precision : 0.01f; + m_precision = 0.1f <= precision ? precision : 0.1f; + m_aim = aim; + m_bestDistanceSqr = FLT_MAX; + m_aimValid = 0; + m_aimDirection = 0; + m_waitForBest = waitForBest; + m_noAngleCheck = noAngleCheck; + m_limitPositiveY = limitPositiveY; + if (!noAngleCheck) + m_angleLimit = std::atan(m_precision / 50.0f); +} + +// ELF 0x1EBC50 (C1; C2 0x1EBBA0): against BAPWrapperAiming's output variables. +BAPCConPrecision::BAPCConPrecision(unsigned int target, BAPVariable* aimValid, BAPVariable* aimDirection, + BAPVariable* aimPoint, float precision, bool waitForBest, + bool limitPositiveY, bool noAngleCheck) +{ + m_target = target; + m_precisionSqr = 0.01f <= precision * precision ? precision * precision : 0.01f; + m_aim = 0; + m_bestDistanceSqr = FLT_MAX; + m_precision = 0.1f <= precision ? precision : 0.1f; + m_waitForBest = waitForBest; + m_aimValid = aimValid; + m_aimDirection = aimDirection; + m_aimPoint = aimPoint; + m_noAngleCheck = noAngleCheck; + m_limitPositiveY = limitPositiveY; + if (!noAngleCheck) + m_angleLimit = std::atan(m_precision / 50.0f); +} + +// ELF 0x1EBD20 (D1; D0 0x1EBD40): base only. +BAPCConPrecision::~BAPCConPrecision() +{ +} + +// ELF 0x1EBD80. True when the shot would hit within the precision. Without the target +// information: false. +// Aim action: needs a valid aim; an "aimer only" weapon pointing exactly along the last aim vector +// (dot >= 1 with the aimer transform's row 2) fires at once. Otherwise the miss is the distance +// between the predicted target position and the Aimer's impact position at the impact time; with +// m_waitForBest the condition waits while the miss still shrinks and fires on the first shot that +// is no better than the best so far (when that best was within the precision). Every positive +// answer stamps BotMain::setHadPrecisionTimeStamp(now); the "still improving" path stamps when +// within the precision but answers false (0x1EC41A..0x1EC43D). +// Variables: needs the valid flag; the miss is the angle between the weapon's projectile-origin +// row 2 and the aim direction (unless m_noAngleCheck), then the offset of that row from the aim +// direction scaled by the distance to the aim point: horizontally within the precision and +// vertically (signed square) within +-20% of it (the lower bound times negativeYLimitFactor, the +// upper one too when m_limitPositiveY). Vehicles close to a non-soldier target (|dy| < 5, < 15 m) +// and vehicles using static attacks skip the angle and vertical checks. +bool BAPCConPrecision::evaluate(Bot* bot) +{ + Information* target = bapinline::info(m_target); + if (!target) + return false; + Information* self = bapinline::info(bot->getCurrentEquipment()); + + if (!m_aimValid) { + if (!m_aim->isAimingValid()) + return false; + double impactTime; + m_aim->getImpactTime(impactTime); + Vec3 lastAim = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_aim->getLastAimVec(lastAim); + IPIArmament* armament = self->getArmament(); + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + if (weapon && weapon->useAimerOnly()) { + const Mat4* t = m_aim->getAimerTransform(); + if (1.0f <= t->m[10] * lastAim.z + t->m[8] * lastAim.x + t->m[9] * lastAim.y) { + static_cast(bot)->setHadPrecisionTimeStamp(bapinline::gameTime()); + return true; + } + } + Vec3 predicted = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_aim->getPredictedPosition(predicted); + Vec3 impact = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (!m_aim->getImpactPosition(impact, impactTime - bapinline::gameTime())) + return false; + const Vec3 miss = bapinline::sub(predicted, impact); + const float d = miss.z * miss.z + miss.x * miss.x + miss.y * miss.y; + if (!m_waitForBest) { + if (m_precisionSqr <= d) + return false; + static_cast(bot)->setHadPrecisionTimeStamp(bapinline::gameTime()); + return true; + } + const float best = m_bestDistanceSqr; + if (best <= 0.01f || best <= d) { + m_bestDistanceSqr = FLT_MAX; + if (m_precisionSqr < best) + return false; + static_cast(bot)->setHadPrecisionTimeStamp(bapinline::gameTime()); + return true; + } + m_bestDistanceSqr = d; + if (d <= m_precisionSqr) + static_cast(bot)->setHadPrecisionTimeStamp(bapinline::gameTime()); + return false; + } + + if (!m_aimValid->m_value) + return false; + Information* own = bapinline::info(bot->getCurrentEquipment()); // re-read; not null-checked + IPIArmament* armament = own->getArmament(); + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + if (!weapon) + return false; + const Vec3& point = m_aimPoint->m_value; + const Vec3& from = own->getPosition(); + const Vec3 toPoint = bapinline::sub(point, from); + float distance = std::sqrt(toPoint.x * toPoint.x + toPoint.y * toPoint.y + toPoint.z * toPoint.z); + bool closeVehicle = false; + if (5.0f <= std::fabs(point.y - from.y)) { + } else if (!target->isOfType(ITSoldier)) { + if (!own->isOfType(ITSoldier) && distance < 15.0f) + closeVehicle = true; + } + bool staticAttack = false; + if (!own->isOfType(ITSoldier)) + staticAttack = static_cast(bot)->getUseStaticAttack(); + + const Vec3 aim = m_aimDirection->m_value; + const Mat4& origin = weapon->getProjectileOrigin(); + const Vec3 forward = bapinline::vec3(origin.m[8], origin.m[9], origin.m[10]); + if (!m_noAngleCheck && !closeVehicle && !staticAttack) { + float c = forward.x * aim.x + forward.y * aim.y + forward.z * aim.z; + if (c < -1.0f) + c = -1.0f; + else if (1.0f < c) + c = 1.0f; + if (m_angleLimit <= std::acos(c)) + return false; + } + const float ox = (forward.x - aim.x) * distance; + const float oz = (forward.z - aim.z) * distance; + const float oy = (forward.y - aim.y) * distance; + const float sign = oy <= 0.0f ? (0.0f <= oy ? 0.0f : -1.0f) : 1.0f; + const float verticalSqr = oy * oy * sign; + float upper = m_precisionSqr * 0.2f; + const float lower = -upper; + if (m_limitPositiveY) + upper = upper * negativeYLimitFactor; + if (m_precisionSqr < ox * ox + oz * oz) + return false; + if (!closeVehicle && !staticAttack) { + if (upper < verticalSqr) + return false; + if (verticalSqr < lower * negativeYLimitFactor) + return false; + } + return true; +} + +// ELF 0x1EC510 +BAPConditionType BAPCConPrecision::getConditionType() const +{ + return BAPCTPrecision; // 1 +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision.h new file mode 100644 index 000000000..a2b18e964 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision.h @@ -0,0 +1,53 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCCONPRECISION_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCCONPRECISION_H + +#include "../../../../Math/Vec3.h" +#include "BAPConnectedCondition.h" +#include "BAPTypes.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPAAimAt; +class Bot; + +// ELF: vtable 0x4B95A8 (5 words), package C-actions. +class BAPCConPrecision : public BAPConnectedCondition +{ +public: + BAPCConPrecision(unsigned int, BAPAAimAt*, float, bool, bool, bool); // 0x1EBAF0 + BAPCConPrecision(unsigned int, BAPVariable*, BAPVariable*, BAPVariable*, float, bool, bool, bool); // 0x1EBC50 + virtual ~BAPCConPrecision(); // 0x1EBD20 + + virtual bool evaluate(Bot*); // 0x1EBD80, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EC510, slot +0x04; from the base declaration + +private: + /* +0x08 */ unsigned int m_target; // information handle (only null-checked) + /* +0x0C */ float m_precisionSqr; // max(precision^2, 0.01) + /* +0x10 */ float m_precision; // max(precision, 0.1) + /* +0x14 */ BAPAAimAt* m_aim; // first constructor; 0 with the variables + /* +0x18 */ float m_bestDistanceSqr; // = FLT_MAX; with m_waitForBest + /* +0x1C */ bool m_waitForBest; // fire when the miss stops shrinking + /* +0x20 */ BAPVariable* m_aimValid; // second constructor (BAPWrapperAiming's outputs) + /* +0x24 */ BAPVariable* m_aimDirection; + /* +0x28 */ BAPVariable* m_aimPoint; // not written by the first constructor + /* +0x2C */ bool m_limitPositiveY; // the upper vertical limit is scaled too + /* +0x2D */ bool m_noAngleCheck; + /* +0x30 */ float m_angleLimit; // atan(m_precision / 50) unless m_noAngleCheck +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCCONPRECISION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision3d.cpp new file mode 100644 index 000000000..421f2e487 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision3d.cpp @@ -0,0 +1,95 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// [PLATFORM] precision: the x87 build compares the squared miss distance in extended precision. + +// static init: ELF 0x1ECA30 (__tcf_0 0x1ECA90, _GLOBAL__I 0x1ECAC0): 's Init object only. +#include + +#include "BAPCConPrecision3d.h" + +#include +#include + +#include "../AIBot/BotMain.h" +#include "BAPAAimAt3d.h" +#include "BAPActionInline.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1EC650 (C1; C2 0x1EC5D0) +BAPCConPrecision3d::BAPCConPrecision3d(unsigned int object, BAPAAimAt3d* aim, float precision, bool waitForClosest) +{ + m_precision = precision; + m_object = object; + m_precisionSq = precision * precision; + m_aim = aim; + m_waitForClosest = waitForClosest; + m_bestDistanceSq = FLT_MAX; + m_maxAngle = std::atan(precision / 80.0f); +} + +// ELF 0x1EC6F0 (D1 0x1EC6D0, D0 0x1EC710): base only. +BAPCConPrecision3d::~BAPCConPrecision3d() +{ +} + +// ELF 0x1EC750. The bot's own information is looked up and not used, as compiled. +bool BAPCConPrecision3d::evaluate(Bot* bot) +{ + if (!m_aim->isAimVecValid()) + return false; + if (!bapinline::info(m_object)) + return false; + bot->getCurrentEquipment(); + double impactTime; + m_aim->getImpactTime(impactTime); + Vec3 aimVec = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_aim->getLastAimVec(aimVec); + const Mat4& transform = m_aim->getAimerTransform(); + float cosine = transform.m[8] * aimVec.x + transform.m[9] * aimVec.y + transform.m[10] * aimVec.z; + if (cosine < -1.0f) + cosine = -1.0f; + else if (cosine > 1.0f) + cosine = 1.0f; + if (std::acos(cosine) > m_maxAngle) + return false; + + Vec3 predicted = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_aim->getPredictedPosition(predicted); + Vec3 impact = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (!m_aim->getImpactPosition(impact, impactTime - bapinline::gameTime())) + return false; + const float distanceSq = bapinline::lengthSqr(bapinline::sub(predicted, impact)); + + if (!m_waitForClosest) + { + const bool hit = distanceSq <= m_precisionSq; + if (hit) + static_cast(bot)->setHadPrecisionTimeStamp(bapinline::gameTime()); + return hit; + } + const float best = m_bestDistanceSq; + if (best > 0.01f && best >= distanceSq) + { + m_bestDistanceSq = distanceSq; // still closing in + if (distanceSq <= m_precisionSq) + static_cast(bot)->setHadPrecisionTimeStamp(bapinline::gameTime()); + return false; + } + const bool hit = best <= m_precisionSq; + if (hit) + static_cast(bot)->setHadPrecisionTimeStamp(bapinline::gameTime()); + m_bestDistanceSq = FLT_MAX; + return hit; +} + +// ELF 0x1ECA20 +BAPConditionType BAPCConPrecision3d::getConditionType() const +{ + return BAPCTPrecision3d; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision3d.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision3d.h new file mode 100644 index 000000000..1ecfc0025 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision3d.h @@ -0,0 +1,46 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCCONPRECISION3D_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCCONPRECISION3D_H + +#include "BAPConnectedCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPAAimAt3d; +class Bot; + +// ELF: vtable 0x4B95D0 (5 words), operator new 0x24, package G-vehicles. +// True when the aim's trajectory passes within `precision` of the target's predicted position and +// the aim deviates from the weapon's forward axis by at most atan(precision / 80). With +// waitForClosest it holds fire while the miss distance still shrinks and answers once it grows. +// Each hit stamps BotMain::setHadPrecisionTimeStamp. +class BAPCConPrecision3d : public BAPConnectedCondition +{ +public: + BAPCConPrecision3d(unsigned int, BAPAAimAt3d*, float, bool); // 0x1EC650 + virtual ~BAPCConPrecision3d(); // 0x1EC6F0 + + virtual bool evaluate(Bot*); // 0x1EC750, slot +0x00 + virtual BAPConditionType getConditionType() const; // 0x1ECA20, slot +0x04 + +private: + /* +0x08 */ unsigned int m_object; // checked for information only + /* +0x0C */ float m_precisionSq; + /* +0x10 */ float m_precision; + /* +0x14 */ BAPAAimAt3d* m_aim; + /* +0x18 */ bool m_waitForClosest; // [INFERRED] name; callers pass !weapon->getBurst() + /* +0x1C */ float m_bestDistanceSq; // FLT_MAX: no approach yet + /* +0x20 */ float m_maxAngle; // atanf(precision / 80) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCCONPRECISION3D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombiner.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombiner.h new file mode 100644 index 000000000..ee8a2ff1b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombiner.h @@ -0,0 +1,53 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCOMBINER_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCOMBINER_H + +#include +#include "BAPStatement.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPStatement; + +// Base of the serial and parallel combiners. Vtable 0x4B9080. Inline in the image: every combiner +// constructor (BAPCombinerSerial(int, int) 0x1E6150, BAPCombinerParallel(int, int, bool) 0x1E4910) +// stores the BAPCombiner vptr, builds the statement list, then under its own vptr stores +// +0x18 = 0 and +0x1C = true (or the `bool` argument), then +0x10. The combiner destructors delete +// the children under their own vptr; the list is freed under BAPCombiner's (0x1E664C). +// ELF: vtable 0x4B9080 (9 words), package S0-skeleton (layout: A-core). +class BAPCombiner : public BAPStatement +{ + // [INFERRED] friendship: PrettyPrinter::prettyPrintScriptNode (libaidll ELF 0x1CAE60) reads the + // statement list, cursor and debug id inline. + friend class PrettyPrinter; +public: + virtual ~BAPCombiner() {} // weak in the image (inline); the list destructor runs here + + virtual unsigned long long getControls() = 0; // slot +0x0C: __cxa_pure_virtual in vtable 0x4B9080 (re-declared pure) + virtual void addStatement(BAPStatement*) = 0; // no body, slot +0x20; ELF void (BAPCombinerSerial 0x1E69A0) + +protected: + BAPCombiner(int patternId, bool waitForChild) + : BAPStatement(patternId), m_current(), m_waitForChild(waitForChild) {} + + /* +0x14 */ std::list m_statements; // owned children, in order + /* +0x18 */ std::list::iterator m_current; // = 0 in the constructors, then begin() + // +0x1C: true unless the (int, bool, ...) constructors pass false. Serial: advance only when the + // child reports finished (0x1E68E6); Parallel: copied into `finished` before the children run + // (0x1E57F0). [INFERRED] name. + /* +0x1C */ bool m_waitForChild; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCOMBINER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerParallel.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerParallel.cpp new file mode 100644 index 000000000..945ee7f5a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerParallel.cpp @@ -0,0 +1,168 @@ +// BAPCombinerParallel: recovered by package A-core from libaidll.so (TU BAPCombinerParallel.cpp, +// 0x1E4910..0x1E6150). Every body carries its ELF address. + +// static init: ELF 0x1E5C20 (__tcf_0 0x1E5C80, _GLOBAL__I 0x1E5CB0): 's Init object only. +#include + +#include "BAPCombinerParallel.h" + +#include "../AIBot/BotMain.h" +#include "../AIPlanInterpreter/PlanInterpreter.h" +#include "../Main/IBotManager.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E4910 (C2; C1 0x1E4AA0). The controls are zeroed again and the list cleared in the body. +BAPCombinerParallel::BAPCombinerParallel(int patternId, int debugId, bool neverFinish) + : BAPCombiner(patternId, true) + , m_debugId(debugId) + , m_neverFinish(neverFinish) +{ + m_controls = 0; + m_statements.clear(); +} + +// ELF 0x1E4B70 (C2; C1 0x1E4C50). +BAPCombinerParallel::BAPCombinerParallel(int patternId, bool waitForChild, int debugId, bool neverFinish) + : BAPCombiner(patternId, waitForChild) + , m_debugId(debugId) + , m_neverFinish(neverFinish) +{ + m_controls = 0; + m_statements.clear(); +} + +// ELF 0x1E4D30 (C2; C1 0x1E4F10). Takes ownership; the controls are the union of the children's. +BAPCombinerParallel::BAPCombinerParallel(std::list& statements, int patternId, int debugId, + bool neverFinish) + : BAPCombiner(patternId, true) + , m_debugId(debugId) + , m_neverFinish(neverFinish) +{ + m_controls = 0; + m_statements = statements; + for (std::list::iterator it = m_statements.begin(); it != m_statements.end(); ++it) + { + (*it)->mpOwner = this; + m_controls |= (*it)->getControls(); + m_isFinished.insert(m_isFinished.end(), false); + } +} + +// ELF 0x1E50F0 (C2; C1 0x1E52E0). +BAPCombinerParallel::BAPCombinerParallel(std::list& statements, int patternId, bool waitForChild, + int debugId, bool neverFinish) + : BAPCombiner(patternId, waitForChild) + , m_debugId(debugId) + , m_neverFinish(neverFinish) +{ + m_controls = 0; + m_statements = statements; + for (std::list::iterator it = m_statements.begin(); it != m_statements.end(); ++it) + { + (*it)->mpOwner = this; + m_controls |= (*it)->getControls(); + m_isFinished.insert(m_isFinished.end(), false); + } +} + +// ELF 0x1E54D0 (D2; D1 0x1E55C0, D0 0x1E56B0). Deletes the children (slot +8). +BAPCombinerParallel::~BAPCombinerParallel() +{ + for (std::list::iterator it = m_statements.begin(); it != m_statements.end(); ++it) + { + if (*it) + delete *it; + } +} + +// ELF 0x1E57B0 (108 instructions); the rules are in the header. Always returns 1. +bool BAPCombinerParallel::execute(Bot* bot, bool& ok, bool& finished) +{ + bool childFinished = false; + bool childOk = true; + finished = m_waitForChild; + ok = true; + + // BotMain::getPlanInterpreter (non-virtual, 0x18A780) on the Bot*, call at 0x1E57FF. + PlanInterpreter* interpreter = static_cast(bot)->getPlanInterpreter(); + std::list::iterator finishedFlag = m_isFinished.begin(); // never advanced (retail) + + for (m_current = m_statements.begin(); m_current != m_statements.end(); ++m_current) + { + (*m_current)->getControls(); // called, result unused (0x1E5858) + interpreter->execute(*m_current, bot, childOk, childFinished); + ok = ok && childOk; + if (m_waitForChild) + finished = finished && childFinished; + else + finished = finished || childFinished; + *finishedFlag = childFinished; + } + + if (m_neverFinish) + finished = false; + return true; +} + +// ELF 0x1E5940. +unsigned long long BAPCombinerParallel::getControls() +{ + return m_controls; +} + +// ELF 0x1E6140. +BAPStatementType BAPCombinerParallel::getId() const +{ + return BAPSTParallel; +} + +// ELF 0x1E5950. +bool BAPCombinerParallel::hasDefault() +{ + return true; +} + +// ELF 0x1E5A70. "Parallell" is the image's spelling. +void BAPCombinerParallel::streamSelf(std::ostream& os) const +{ + IBotManager::instance->tabulate(os); + os << "Parallell combiner"; + if (m_debugId != -1) + os << "(" << m_debugId << ")"; + os << std::endl; + + IBotManager::instance->tabulate(os); + os << '{' << std::endl; + IBotManager::instance->increaseTabLevel(); + for (std::list::const_iterator it = m_statements.begin(); it != m_statements.end(); ++it) + os << **it; + IBotManager::instance->decreaseTabLevel(); + IBotManager::instance->tabulate(os); + os << '}' << std::endl; +} + +// ELF 0x1E5960. A null statement is ignored. +void BAPCombinerParallel::addStatement(BAPStatement* statement) +{ + if (statement == 0) + return; + statement->mpOwner = this; + m_statements.insert(m_statements.end(), statement); + m_controls |= statement->getControls(); + m_isFinished.insert(m_isFinished.end(), false); +} + +// ELF 0x1E5A60. +const std::list& BAPCombinerParallel::getIsFinished() const +{ + return m_isFinished; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerParallel.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerParallel.h new file mode 100644 index 000000000..12a13400d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerParallel.h @@ -0,0 +1,63 @@ +// Recovered by package A-core (docs/macos-ai-behaviour-plan.md) from libaidll.so; the virtual order +// is checked by tools/macos/ai_behaviour_vtables.py. Every body carries its ELF address. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCOMBINERPARALLEL_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCOMBINERPARALLEL_H + +#include +#include +#include "BAPCombiner.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPStatement; +class Bot; + +// Runs all children every tick, in order. Completion rules (execute 0x1E57B0): +// * ok = true and finished = waitForChild before the loop; the children share one ok/finished +// pair that is not reset between them (child ok starts true, child finished false); +// * after each child: ok &= child ok; finished = waitForChild ? (finished && child finished) +// : (finished || child finished), i.e. all children finished, or any child finished; +// * neverFinish forces finished = false at the end. An empty combiner reports ok and +// finished = waitForChild (unless neverFinish). +// Each child's finished flag is stored into the FIRST element of m_isFinished only (the image never +// advances that iterator, 0x1E58CE). Each child's getControls() is called and discarded first. +// sizeof 0x2C. +// ELF: vtable 0x4B9040 (9 words), operator new 0x2C, package A-core. +class BAPCombinerParallel : public BAPCombiner +{ + // [INFERRED] friendship: PrettyPrinter::prettyPrintScriptNode (libaidll ELF 0x1CAE60) reads the + // statement list, cursor and debug id inline. + friend class PrettyPrinter; +public: + BAPCombinerParallel(int patternId, int debugId, bool neverFinish); // 0x1E4AA0 + BAPCombinerParallel(int patternId, bool waitForChild, int debugId, bool neverFinish); // 0x1E4C50 + BAPCombinerParallel(std::list& statements, int patternId, int debugId, bool neverFinish); // 0x1E4F10 + BAPCombinerParallel(std::list& statements, int patternId, bool waitForChild, int debugId, + bool neverFinish); // 0x1E52E0 + virtual ~BAPCombinerParallel(); // 0x1E55C0 + + virtual bool execute(Bot*, bool&, bool&); // 0x1E57B0, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1E5940, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1E6140, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1E5950, slot +0x14; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1E5A70, slot +0x1C; from the base declaration + virtual void addStatement(BAPStatement*); // 0x1E5960, slot +0x20; from the base declaration + + const std::list& getIsFinished() const; // 0x1E5A60: returns this + 0x20 + +private: + /* +0x20 */ std::list m_isFinished; // one false per child (addStatement / list constructors) + /* +0x24 */ int m_debugId; // second constructor int, -1 from the creators; streamSelf only [INFERRED] name + /* +0x28 */ bool m_neverFinish; // last constructor bool [INFERRED] name +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCOMBINERPARALLEL_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerSerial.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerSerial.cpp new file mode 100644 index 000000000..a2da06ffa --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerSerial.cpp @@ -0,0 +1,152 @@ +// BAPCombinerSerial: recovered by package A-core from libaidll.so (TU BAPCombinerSerial.cpp, +// 0x1E6150..0x1E6CF0). Every body carries its ELF address. + +// static init: ELF 0x1E6C30 (__tcf_0 0x1E6C90, _GLOBAL__I 0x1E6CC0): 's Init object only. +#include + +#include "BAPCombinerSerial.h" + +#include "../AIBot/BotMain.h" +#include "../AIPlanInterpreter/PlanInterpreter.h" +#include "../Main/IBotManager.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E6150 (C2; C1 0x1E6200). The body clears the (new, empty) list, then rewinds. +BAPCombinerSerial::BAPCombinerSerial(int patternId, int debugId) + : BAPCombiner(patternId, true) + , m_debugId(debugId) +{ + m_statements.clear(); + m_current = m_statements.begin(); +} + +// ELF 0x1E62B0 (C2; C1 0x1E6360). +BAPCombinerSerial::BAPCombinerSerial(int patternId, bool waitForChild, int debugId) + : BAPCombiner(patternId, waitForChild) + , m_debugId(debugId) +{ + m_statements.clear(); + m_current = m_statements.begin(); +} + +// ELF 0x1E6410 (C2; C1 0x1E6500). Copies the list and takes ownership of its statements. +BAPCombinerSerial::BAPCombinerSerial(std::list& statements, int patternId, int debugId) + : BAPCombiner(patternId, true) + , m_debugId(debugId) +{ + m_statements = statements; + m_current = m_statements.begin(); + for (std::list::iterator it = m_statements.begin(); it != m_statements.end(); ++it) + (*it)->mpOwner = this; +} + +// ELF 0x1E65F0 (D2; D1 0x1E66B0, D0 0x1E6770). Deletes the children (slot +8). +BAPCombinerSerial::~BAPCombinerSerial() +{ + for (std::list::iterator it = m_statements.begin(); it != m_statements.end(); ++it) + { + if (*it) + delete *it; + } +} + +// ELF 0x1E6840 (84 instructions). The child's own result is ignored; this always returns 1. +bool BAPCombinerSerial::execute(Bot* bot, bool& ok, bool& finished) +{ + if (m_current == m_statements.end()) + { + ok = true; + finished = true; + m_current = m_statements.begin(); + return true; + } + + // BotMain::getPlanInterpreter (non-virtual, 0x18A780) on the Bot*, call at 0x1E68BA. + static_cast(bot)->getPlanInterpreter()->execute(*m_current, bot, ok, finished); + + if (m_waitForChild) + { + if (!finished) + return true; + ++m_current; + if (m_current != m_statements.end()) + { + finished = false; + return true; + } + } + else + { + ++m_current; + if (!finished && m_current != m_statements.end()) + return true; + } + + finished = true; + m_current = m_statements.begin(); + return true; +} + +// ELF 0x1E6970: the current child's controls. Retail reads through m_current without an end() +// check (only an empty combiner can be at end() here, see execute). +unsigned long long BAPCombinerSerial::getControls() +{ + return (*m_current)->getControls(); +} + +// ELF 0x1E6CE0. +BAPStatementType BAPCombinerSerial::getId() const +{ + return BAPSTSerial; +} + +// ELF 0x1E6990. +bool BAPCombinerSerial::hasDefault() +{ + return true; +} + +// ELF 0x1E6A20. IBotManager::tabulate/increaseTabLevel/decreaseTabLevel are +0x88/+0x80/+0x84. +void BAPCombinerSerial::streamSelf(std::ostream& os) const +{ + IBotManager::instance->tabulate(os); + os << "Serial combiner"; + if (m_debugId != -1) + os << "(" << m_debugId << ")"; + os << std::endl; + + IBotManager::instance->tabulate(os); + os << '{' << std::endl; + IBotManager::instance->increaseTabLevel(); + for (std::list::const_iterator it = m_statements.begin(); it != m_statements.end(); ++it) + { + if (std::list::const_iterator(m_current) == it) + { + IBotManager::instance->tabulate(os); + os << "/*Active serial statement*/" << std::endl; + } + os << **it; + } + IBotManager::instance->decreaseTabLevel(); + IBotManager::instance->tabulate(os); + os << '}' << std::endl; +} + +// ELF 0x1E69A0. A null statement is ignored; adding rewinds. +void BAPCombinerSerial::addStatement(BAPStatement* statement) +{ + if (statement == 0) + return; + statement->mpOwner = this; + m_statements.insert(m_statements.end(), statement); + m_current = m_statements.begin(); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerSerial.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerSerial.h new file mode 100644 index 000000000..b21441078 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerSerial.h @@ -0,0 +1,56 @@ +// Recovered by package A-core (docs/macos-ai-behaviour-plan.md) from libaidll.so; the virtual order +// is checked by tools/macos/ai_behaviour_vtables.py. Every body carries its ELF address. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCOMBINERSERIAL_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCOMBINERSERIAL_H + +#include +#include +#include "BAPCombiner.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPStatement; +class Bot; + +// Runs its children one after the other. Completion rules (execute 0x1E6840): +// * empty list, or the current child is past the end: ok = finished = true, rewind, done; +// * waitForChild (default): the current child runs each tick; when it reports finished the +// combiner moves to the next one, and reports finished (and rewinds) after the last; +// * !waitForChild: every tick runs the current child once and moves on; a child that reports +// finished ends the whole sequence (finished stays true, rewind). +// `ok` is whatever the last child reported. sizeof 0x24. +// ELF: vtable 0x4B90E0 (9 words), operator new 0x24, package A-core. +class BAPCombinerSerial : public BAPCombiner +{ + // [INFERRED] friendship: PrettyPrinter::prettyPrintScriptNode (libaidll ELF 0x1CAE60) reads the + // statement list, cursor and debug id inline. + friend class PrettyPrinter; +public: + BAPCombinerSerial(int patternId, int debugId); // 0x1E6200 + BAPCombinerSerial(int patternId, bool waitForChild, int debugId); // 0x1E6360 + BAPCombinerSerial(std::list& statements, int patternId, int debugId); // 0x1E6500 + virtual ~BAPCombinerSerial(); // 0x1E66B0 + + virtual bool execute(Bot*, bool&, bool&); // 0x1E6840, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1E6970, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1E6CE0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1E6990, slot +0x14; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1E6A20, slot +0x1C; from the base declaration + virtual void addStatement(BAPStatement*); // 0x1E69A0, slot +0x20; from the base declaration + +private: + // +0x20: second constructor int; the creators pass -1. Only streamSelf reads it ("(n)" unless + // -1). [INFERRED] name. + /* +0x20 */ int m_debugId; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCOMBINERSERIAL_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAllowFire.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAllowFire.cpp new file mode 100644 index 000000000..0322214de --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAllowFire.cpp @@ -0,0 +1,44 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1E6E00 (__tcf_0 0x1E6E60, _GLOBAL__I 0x1E6E90): 's Init object only. +#include + +#include "BAPConAllowFire.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E6D20 (C1) +BAPConAllowFire::BAPConAllowFire() +{ +} + +// ELF 0x1E6D70 (D0 0x1E6D90): base only. +BAPConAllowFire::~BAPConAllowFire() +{ +} + +// ELF 0x1E6DD0 +bool BAPConAllowFire::evaluate(Bot* bot) +{ + return bot->isFireAllowed(); +} + +// ELF 0x1E6DF0 +BAPConditionType BAPConAllowFire::getConditionType() const +{ + return BAPCTAllowFire; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAllowFire.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAllowFire.h new file mode 100644 index 000000000..f2d8ffa96 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAllowFire.h @@ -0,0 +1,36 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONALLOWFIRE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONALLOWFIRE_H + +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9118 (5 words), operator new 0x8/0xC, package C-actions. +// Bot::isFireAllowed (+0x138). No data. +class BAPConAllowFire : public BAPCondition +{ +public: + BAPConAllowFire(); // 0x1E6D20 + virtual ~BAPConAllowFire(); // 0x1E6D70 + + virtual bool evaluate(Bot*); // 0x1E6DD0, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1E6DF0, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONALLOWFIRE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAnd.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAnd.cpp new file mode 100644 index 000000000..63598a9e2 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAnd.cpp @@ -0,0 +1,77 @@ +// BAPConAnd: recovered by package A-core from libaidll.so (TU without a FILE symbol, 0x1F3B10..0x1F41F0). +// Every body carries its ELF address. + +#include "BAPConAnd.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F3B10 (C2; C1 0x1F3C80). Copies the list and takes ownership of its conditions. +BAPConAnd::BAPConAnd(std::list& conditions) +{ + m_conditions = conditions; + for (std::list::iterator it = m_conditions.begin(); it != m_conditions.end(); ++it) + (*it)->mpOwner = this; +} + +// ELF 0x1F3D30 (C2; C1 0x1F3DA0). +BAPConAnd::BAPConAnd() +{ + m_conditions.clear(); +} + +// ELF 0x1F3E10 (D2; D1 and D0 follow). Deletes the conditions (slot +0x10); the list itself goes with +// BAPBoleanOp. +BAPConAnd::~BAPConAnd() +{ + for (std::list::iterator it = m_conditions.begin(); it != m_conditions.end(); ++it) + { + if (*it) + delete *it; + } +} + +// ELF 0x1F4030. +bool BAPConAnd::evaluate(Bot* bot) +{ + for (std::list::iterator it = m_conditions.begin(); it != m_conditions.end(); ++it) + { + if (!(*it)->evaluate(bot)) + return false; + } + return true; +} + +// ELF 0x1F40A0: no null check. +void BAPConAnd::addCondition(BAPCondition* condition) +{ + condition->mpOwner = this; + m_conditions.insert(m_conditions.end(), condition); +} + +// ELF 0x1F4110. +BAPConditionType BAPConAnd::getConditionType() const +{ + return BAPCTAnd; +} + +// ELF 0x1F4120: "(" c1 " && " c2 ... ")". +void BAPConAnd::streamSelf(std::ostream& os) const +{ + os << "("; + std::list::const_iterator it = m_conditions.begin(); + if (it != m_conditions.end()) + { + os << **it; + for (++it; it != m_conditions.end(); ++it) + os << " && " << **it; + } + os << ")"; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAnd.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAnd.h new file mode 100644 index 000000000..4df45f9e6 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAnd.h @@ -0,0 +1,40 @@ +// Recovered by package A-core (docs/macos-ai-behaviour-plan.md) from libaidll.so; the virtual order +// is checked by tools/macos/ai_behaviour_vtables.py. Every body carries its ELF address. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONAND_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONAND_H + +#include +#include +#include "BAPBoleanOp.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B9E40 (6 words), operator new 0x8/0xC, package A-core. +// True when every condition is (an empty And is true); stops at the first false. Owns its +// conditions (BAPBoleanOp::m_conditions). sizeof 0xC. +class BAPConAnd : public BAPBoleanOp +{ +public: + explicit BAPConAnd(std::list&); // 0x1F3C80 + BAPConAnd(); // 0x1F3DA0 + virtual ~BAPConAnd(); // 0x1F3EC0 + + virtual bool evaluate(Bot*); // 0x1F4030, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F4110, slot +0x04; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1F4120, slot +0x08; from the base declaration + virtual void addCondition(BAPCondition*); // 0x1F40A0, slot +0x14; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONAND_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConDistanceToProj.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConDistanceToProj.cpp new file mode 100644 index 000000000..d971ef32e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConDistanceToProj.cpp @@ -0,0 +1,51 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1E70C0 (__tcf_0 0x1E7120, _GLOBAL__I 0x1E7150): 's Init object only. +#include + +#include "BAPConDistanceToProj.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E6EF0 (C1) +BAPConDistanceToProj::BAPConDistanceToProj(IPIArmament* armament, float distance) +{ + m_distanceSqr = distance * distance; + m_armament = armament; +} + +// ELF 0x1E7050 (D0 0x1E7070) +BAPConDistanceToProj::~BAPConDistanceToProj() +{ +} + +// ELF 0x1E6F30: IPIArmament::getProjectilePosition (+0x38); the information is not null-checked. +bool BAPConDistanceToProj::evaluate(Bot* bot) +{ + Vec3 p = bapinline::vec3(0.0f, 0.0f, 0.0f); + bool result = false; + if (m_armament->getProjectilePosition(p)) { + const Vec3& self = bapinline::info(bot->getCurrentEquipment())->getPosition(); + result = (p.z - self.z) * (p.z - self.z) + (p.x - self.x) * (p.x - self.x) + (p.y - self.y) * (p.y - self.y) + < m_distanceSqr; + } + return result; +} + +// ELF 0x1E70B0 +BAPConditionType BAPConDistanceToProj::getConditionType() const +{ + return BAPCTDistanceToProj; // 15 +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConDistanceToProj.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConDistanceToProj.h new file mode 100644 index 000000000..5dc2955ca --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConDistanceToProj.h @@ -0,0 +1,42 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONDISTANCETOPROJ_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONDISTANCETOPROJ_H + +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class IPIArmament; + +// ELF: vtable 0x4B9168 (5 words), operator new 0x10, package C-actions. +// The armament's live projectile is closer than the distance to the bot's current +// vehicle/soldier; no projectile: false. +class BAPConDistanceToProj : public BAPCondition +{ +public: + BAPConDistanceToProj(IPIArmament*, float); // 0x1E6EF0 + virtual ~BAPConDistanceToProj(); // 0x1E7050 + + virtual bool evaluate(Bot*); // 0x1E6F30, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1E70B0, slot +0x04; from the base declaration + +private: + /* +0x08 */ IPIArmament* m_armament; + /* +0x0C */ float m_distanceSqr; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONDISTANCETOPROJ_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConEndOfPath.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConEndOfPath.cpp new file mode 100644 index 000000000..1b03a1a9f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConEndOfPath.cpp @@ -0,0 +1,31 @@ +// End-of-path condition from libaidll.so. The shipped evaluator always returns false. + +// static init: ELF 0x1E7180 (__tcf_0 0x1E71E0, _GLOBAL__I 0x1E7210): 's Init object only. +#include + +#include "BAPConEndOfPath.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E7230 (D1; D0 0x1E7250): base destruction only. +BAPConEndOfPath::~BAPConEndOfPath() +{ +} + +// ELF 0x1E7170 +bool BAPConEndOfPath::evaluate(Bot*) +{ + return false; +} + +// ELF 0x1E7290 +BAPConditionType BAPConEndOfPath::getConditionType() const +{ + return BAPCTEndOfPath; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConEndOfPath.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConEndOfPath.h new file mode 100644 index 000000000..5d4880ec7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConEndOfPath.h @@ -0,0 +1,30 @@ +// End-of-path condition. The retail evaluator is an unconditional false. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONENDOFPATH_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONENDOFPATH_H + +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9190 (5 words), package H-deferred. +class BAPConEndOfPath : public BAPCondition +{ +public: + virtual ~BAPConEndOfPath(); // 0x1E7230 + + virtual bool evaluate(Bot*); // 0x1E7170, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1E7290, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONENDOFPATH_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConFalse.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConFalse.cpp new file mode 100644 index 000000000..1e5a52da2 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConFalse.cpp @@ -0,0 +1,34 @@ +// BAPConFalse: recovered by ai-main from libaidll.so (0x1C1920..0x1C1990; S0 skeleton file). +// Every body carries its ELF address. + +#include "BAPConFalse.h" + +#include "../../../../Math/Vec3.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1C1940 (D1, D0 0x1C1960): only the vtable store of the (empty) BAPCondition base +// (GOT -0x1550 + 8); nothing of its own. +BAPConFalse::~BAPConFalse() +{ +} + +// ELF 0x1C1920: `xorl %eax, %eax; ret`. +bool BAPConFalse::evaluate(Bot*) +{ + return false; +} + +// ELF 0x1C1930: `movl $0x6, %eax; ret` (6 = BAPCTFalse). +BAPConditionType BAPConFalse::getConditionType() const +{ + return BAPCTFalse; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConFalse.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConFalse.h new file mode 100644 index 000000000..6ef0e7744 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConFalse.h @@ -0,0 +1,35 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONFALSE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONFALSE_H + +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B74E0 (5 words), package S0-skeleton. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BAPConFalse : public BAPCondition +{ +public: + virtual ~BAPConFalse(); // 0x1C1940 + + virtual bool evaluate(Bot*); // 0x1C1920, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1C1930, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONFALSE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConInsideBattleZone.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConInsideBattleZone.cpp new file mode 100644 index 000000000..c40251ba5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConInsideBattleZone.cpp @@ -0,0 +1,41 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. + +// static init: ELF 0x1E7360 (__tcf_0 0x1E73C0, _GLOBAL__I 0x1E73F0): 's Init object only. +#include + +#include "BAPConInsideBattleZone.h" + +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" +#include "../AIBot/BotMain.h" +#include "../Main/CommonSingletonServer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E72D0 (C1; C2 0x1E72A0) +BAPConInsideBattleZone::BAPConInsideBattleZone(float distance) +{ + m_distance = distance; +} + +// ELF 0x1E7410 (D0 0x1E7430): base only. +BAPConInsideBattleZone::~BAPConInsideBattleZone() +{ +} + +// ELF 0x1E7300 +bool BAPConInsideBattleZone::evaluate(Bot* bot) +{ + return static_cast(CommonSingletonServer::m_iaiTerrain)->isInsideCombatArea(bot->getPlayer()); +} + +// ELF 0x1E7350 +BAPConditionType BAPConInsideBattleZone::getConditionType() const +{ + return BAPCTInsideBattleZone; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConInsideBattleZone.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConInsideBattleZone.h new file mode 100644 index 000000000..26f2ce85d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConInsideBattleZone.h @@ -0,0 +1,37 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONINSIDEBATTLEZONE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONINSIDEBATTLEZONE_H + +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B91B8 (5 words), operator new 0xC/0x7C, package G-vehicles. +// True while the bot's player is inside the combat area (IAITerrain::isInsideCombatArea). The +// constructor's distance is stored but not read. +class BAPConInsideBattleZone : public BAPCondition +{ +public: + explicit BAPConInsideBattleZone(float); // 0x1E72D0 + virtual ~BAPConInsideBattleZone(); // 0x1E7410 + + virtual bool evaluate(Bot*); // 0x1E7300, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1E7350, slot +0x04; from the base declaration + +private: + /* +0x08 */ float m_distance; // [INFERRED] name: callers pass 150 and 200 +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONINSIDEBATTLEZONE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIsSprinting.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIsSprinting.cpp new file mode 100644 index 000000000..318031708 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIsSprinting.cpp @@ -0,0 +1,44 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1E75D0 (__tcf_0 0x1E7630, _GLOBAL__I 0x1E7660): 's Init object only. +#include + +#include "BAPConIsSprinting.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E74A0 (C1) +BAPConIsSprinting::BAPConIsSprinting() +{ +} + +// ELF 0x1E74F0 (D0 0x1E7510): base only. +BAPConIsSprinting::~BAPConIsSprinting() +{ +} + +// ELF 0x1E7550 +bool BAPConIsSprinting::evaluate(Bot* bot) +{ + return bapinline::mappedInput(bot->getInput(), io::PISprint) != 0.0f; +} + +// ELF 0x1E75C0 +BAPConditionType BAPConIsSprinting::getConditionType() const +{ + return BAPCTIsSprinting; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIsSprinting.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIsSprinting.h new file mode 100644 index 000000000..8ed675135 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIsSprinting.h @@ -0,0 +1,36 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONISSPRINTING_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONISSPRINTING_H + +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9208 (5 words), operator new 0x8/0xC, package C-actions. +// The bot presses sprint: the mapped PISprint input (bit 13, +0x34) is not 0. No data. +class BAPConIsSprinting : public BAPCondition +{ +public: + BAPConIsSprinting(); // 0x1E74A0 + virtual ~BAPConIsSprinting(); // 0x1E74F0 + + virtual bool evaluate(Bot*); // 0x1E7550, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1E75C0, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONISSPRINTING_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIsTriggered.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIsTriggered.cpp new file mode 100644 index 000000000..0e1694eb9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIsTriggered.cpp @@ -0,0 +1,38 @@ +// Tests the borrowed trigger action's started flag. + +// static init: ELF 0x1E7780 (__tcf_0 0x1E77E0, _GLOBAL__I 0x1E7810): 's Init object only. +#include + +#include "BAPConIsTriggered.h" + +#include "BAPATrigger.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E76B0 (C1; C2 0x1E7680) +BAPConIsTriggered::BAPConIsTriggered(BAPATrigger* trigger) : m_trigger(trigger) +{ +} + +// ELF 0x1E7710 (D1; D2 0x1E76F0, D0 0x1E7730) +BAPConIsTriggered::~BAPConIsTriggered() +{ +} + +// ELF 0x1E76E0 +bool BAPConIsTriggered::evaluate(Bot*) +{ + return m_trigger->m_started; +} + +// ELF 0x1E7770 +BAPConditionType BAPConIsTriggered::getConditionType() const +{ + return BAPCTIsTriggered; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIsTriggered.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIsTriggered.h new file mode 100644 index 000000000..20ad58393 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIsTriggered.h @@ -0,0 +1,35 @@ +// Tests the borrowed trigger action's started flag. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONISTRIGGERED_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONISTRIGGERED_H + +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPATrigger; +class Bot; + +// ELF: vtable 0x4B9268 (5 words), package H-deferred. +class BAPConIsTriggered : public BAPCondition +{ +public: + explicit BAPConIsTriggered(BAPATrigger*); // 0x1E76B0 + virtual ~BAPConIsTriggered(); // 0x1E7710 + + virtual bool evaluate(Bot*); // 0x1E76E0, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1E7770, slot +0x04; from the base declaration + +private: + /* +0x08 */ BAPATrigger* m_trigger; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONISTRIGGERED_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIteration.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIteration.cpp new file mode 100644 index 000000000..916313858 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIteration.cpp @@ -0,0 +1,35 @@ +// BAPConIteration: recovered by package A-core from libaidll.so (TU without a FILE symbol, +// 0x1E7830..0x1E7940). Every body carries its ELF address. + +#include "BAPConIteration.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E7830 (C2; C1 0x1E7860). +BAPConIteration::BAPConIteration(int count) + : m_count(count) +{ +} + +// ELF 0x1E7890 (D2; D1 0x1E78B0, D0 0x1E78D0): the vptr store only. +BAPConIteration::~BAPConIteration() +{ +} + +// ELF 0x1E7910. +bool BAPConIteration::evaluate(Bot*) +{ + return --m_count <= 0; +} + +// ELF 0x1E7930. +BAPConditionType BAPConIteration::getConditionType() const +{ + return BAPCTIteration; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIteration.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIteration.h new file mode 100644 index 000000000..2c04f916e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIteration.h @@ -0,0 +1,36 @@ +// Recovered by package A-core (docs/macos-ai-behaviour-plan.md) from libaidll.so; the virtual order +// is checked by tools/macos/ai_behaviour_vtables.py. Every body carries its ELF address. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONITERATION_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONITERATION_H + +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9290 (5 words), package A-core. +// True on the n-th evaluate and on every later one (counts down, no reset). sizeof 0xC. +class BAPConIteration : public BAPCondition +{ +public: + explicit BAPConIteration(int); // 0x1E7860 + virtual ~BAPConIteration(); // 0x1E78B0 + + virtual bool evaluate(Bot*); // 0x1E7910, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1E7930, slot +0x04; from the base declaration + +private: + /* +0x08 */ int m_count; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONITERATION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConLineOfFire.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConLineOfFire.cpp new file mode 100644 index 000000000..102356882 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConLineOfFire.cpp @@ -0,0 +1,68 @@ +// Fixed-point line-of-fire condition recovered from libaidll.so. +// static init: ELF 0x1E7EE0 (__tcf_0 0x1E7F40, _GLOBAL__I 0x1E7F70): 's Init object only. +#include +#include "BAPConLineOfFire.h" +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../../Core/Debug.h" +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E79B0 (C1; C2 0x1E7940) +BAPConLineOfFire::BAPConLineOfFire(const Vec3& target, bool flag) + : m_target(target), m_useCamera(true), m_flag15(flag) +{ +} + +// ELF 0x1E7A90 (C1; C2 0x1E7A20) +BAPConLineOfFire::BAPConLineOfFire(const Vec3& target, bool flag, SoldierPose pose) + : m_target(target), m_useCamera(false), m_flag15(flag), m_pose(pose) +{ +} + +// ELF 0x1E7B20 (D1; D2 0x1E7B00, D0 0x1E7B40) +BAPConLineOfFire::~BAPConLineOfFire() +{ +} + +// ELF 0x1E7B80 +bool BAPConLineOfFire::evaluate(Bot* bot) +{ + Information* self = bapinline::info(bot->getCurrentEquipment()); + if (!self) + return false; + Vec3 from = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (m_useCamera) { + const Mat4& camera = *static_cast(bot->getPlayer()->getCameraTransformation()); + from = bapinline::vec3(camera.m[12], camera.m[13], camera.m[14]); + } else { + const Vec3 local = self->getAIObject()->getSoldierPoseCameraPosition(m_pose); + const Mat4& transform = self->getTransformation(); + from.x = local.x * transform.m[0] + local.y * transform.m[4] + local.z * transform.m[8] + transform.m[12]; + from.y = local.x * transform.m[1] + local.y * transform.m[5] + local.z * transform.m[9] + transform.m[13]; + from.z = local.x * transform.m[2] + local.y * transform.m[6] + local.z * transform.m[10] + transform.m[14]; + } + std::vector ignore; + ignore.push_back(self->getAIObject()); + Debug(DebugTypeError, "AI/AIDLL/AI/AIBotActionPlan/BAPConLineOfFire.cpp", 58, "") + << "Does not work with transparancy."; + bool hit; + return !static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->collideLineWithWorld(from, m_target, ignore, bot->getLodLevel() != 0, 0.75f, false, hit); +} + +// ELF 0x1E7ED0 +BAPConditionType BAPConLineOfFire::getConditionType() const +{ + return BAPCTLineOfFire; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConLineOfFire.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConLineOfFire.h new file mode 100644 index 000000000..056c6352a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConLineOfFire.h @@ -0,0 +1,39 @@ +// Tests the line from the bot's camera (or the selected soldier pose) to a fixed point. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONLINEOFFIRE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONLINEOFFIRE_H + +#include "../../../../Math/Vec3.h" +#include "../../../AIInterface/BFKnowledge/SoldierPose.h" +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B92B8 (5 words), operator new 0x1C, package H-deferred. +class BAPConLineOfFire : public BAPCondition +{ +public: + BAPConLineOfFire(const Vec3&, bool); // 0x1E79B0 + BAPConLineOfFire(const Vec3&, bool, SoldierPose); // 0x1E7A90 + virtual ~BAPConLineOfFire(); // 0x1E7B20 + + virtual bool evaluate(Bot*); // 0x1E7B80, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1E7ED0, slot +0x04; from the base declaration +private: + /* +0x08 */ Vec3 m_target; + /* +0x14 */ bool m_useCamera; + /* +0x15 */ bool m_flag15; // [UNRESOLVED] constructor flag; never read by the shipped evaluator + /* +0x18 */ SoldierPose m_pose; // initialized only by the pose-taking constructor +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONLINEOFFIRE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConNot.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConNot.cpp new file mode 100644 index 000000000..40dd66e8d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConNot.cpp @@ -0,0 +1,72 @@ +// BAPConNot: recovered by package A-core from libaidll.so (TU without a FILE symbol, +// 0x1F4580..0x1F4D30). Every body carries its ELF address. + +#include "BAPConNot.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F4580 (C2; C1 0x1F46E0). No null check. +BAPConNot::BAPConNot(BAPCondition* condition) +{ + condition->mpOwner = this; + m_conditions.insert(m_conditions.end(), condition); +} + +// ELF 0x1F4780 (C2; C1 0x1F4850). Only the list's front is taken (owner set, appended). +BAPConNot::BAPConNot(std::list& conditions) +{ + m_conditions.clear(); + conditions.front()->mpOwner = this; + m_conditions.insert(m_conditions.end(), conditions.front()); +} + +// ELF 0x1F4920 (C2; C1 0x1F4990). +BAPConNot::BAPConNot() +{ + m_conditions.clear(); +} + +// ELF 0x1F4A00 (D2; D1 0x1F4AB0, D0 0x1F4B60). Deletes the conditions (slot +0x10). +BAPConNot::~BAPConNot() +{ + for (std::list::iterator it = m_conditions.begin(); it != m_conditions.end(); ++it) + { + if (*it) + delete *it; + } +} + +// ELF 0x1F4C20: front() without an empty check (retail). +bool BAPConNot::evaluate(Bot* bot) +{ + return !m_conditions.front()->evaluate(bot); +} + +// ELF 0x1F4C50: ignored once a condition is present. +void BAPConNot::addCondition(BAPCondition* condition) +{ + if (!m_conditions.empty()) + return; + condition->mpOwner = this; + m_conditions.insert(m_conditions.end(), condition); +} + +// ELF 0x1F4CC0. +BAPConditionType BAPConNot::getConditionType() const +{ + return BAPCTNot; +} + +// ELF 0x1F4CD0. +void BAPConNot::streamSelf(std::ostream& os) const +{ + os << "NOT(" << *m_conditions.front() << ")"; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConNot.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConNot.h new file mode 100644 index 000000000..600cf9e56 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConNot.h @@ -0,0 +1,42 @@ +// Recovered by package A-core (docs/macos-ai-behaviour-plan.md) from libaidll.so; the virtual order +// is checked by tools/macos/ai_behaviour_vtables.py. Every body carries its ELF address. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONNOT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONNOT_H + +#include +#include +#include "BAPBoleanOp.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B9EA0 (6 words), operator new 0xC/0x20/0x2C, package A-core. +// Negates the first condition of the list (evaluate reads front() without an empty check, as +// the image does). addCondition only accepts the first one; the list constructor takes only the +// list's front. Owns its condition. sizeof 0xC. +class BAPConNot : public BAPBoleanOp +{ +public: + explicit BAPConNot(BAPCondition*); // 0x1F46E0 + explicit BAPConNot(std::list&); // 0x1F4850 + BAPConNot(); // 0x1F4990 + virtual ~BAPConNot(); // 0x1F4AB0 + + virtual bool evaluate(Bot*); // 0x1F4C20, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F4CC0, slot +0x04; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1F4CD0, slot +0x08; from the base declaration + virtual void addCondition(BAPCondition*); // 0x1F4C50, slot +0x14; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONNOT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObject.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObject.h new file mode 100644 index 000000000..024608cd8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObject.h @@ -0,0 +1,31 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECT_H + +#include "BAPCondition.h" + +namespace dice { +namespace hfe { + +namespace ai { + + +// ELF: package C-actions. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BAPConObject : public BAPCondition +{ +public: + // Inline in the image (no symbol); every subclass ctor stores the object handle at +0x08. + /* +0x08 */ unsigned int m_object; // information handle of the tested object +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectBehind.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectBehind.cpp new file mode 100644 index 000000000..2a8162096 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectBehind.cpp @@ -0,0 +1,93 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1ECFC0 (__tcf_0 0x1ED020, _GLOBAL__I 0x1ED050): 's Init object only. +#include + +#include "BAPConObjectBehind.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/Information.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1ECB20 (C1; C2 0x1ECAE0): +4 = 0, +8 handle, +0xC threshold, +0x10 flag. +BAPConObjectBehind::BAPConObjectBehind(unsigned int object, float threshold, bool useEstimate) +{ + setOwner(0); + m_object = object; + m_threshold = threshold; + m_useEstimate = useEstimate; +} + +// ELF 0x1ECB80 (D0 0x1ECBA0) +BAPConObjectBehind::~BAPConObjectBehind() +{ +} + +// ELF 0x1ECBE0. Object position (XZ): the IPIMobile (+0x38) position estimate (vfn +0x2C) when +// +0x10 is set and the object has one, else getPosition (vfn +0x30). Bot position: the current +// equipment's getPosition (no null test in the image). Forward: transformation (vfn +0x3C) row 2 +// (+0x20) in XZ, normalised in place; direction object->bot normalised by the same inline +// (1.1920929e-07 / 1.4210855e-14 thresholds). 0x1ECEA2 `flds 0xc(%eax)`, `fucompi`, `setae`: +// threshold >= dot. +bool BAPConObjectBehind::evaluate(Bot* bot) +{ + Information* object = bapinline::info(m_object); + if (!object) + return true; + Information* equipment = bapinline::info(bot->getCurrentEquipment()); + + Vec2 objectPosition; + objectPosition.x = 0.0f; + objectPosition.y = 0.0f; + IPIMobile* mobile = object->getMobile(); + if (!m_useEstimate || !mobile) { + vec3ToVec2XZ(object->getPosition(), objectPosition); + } else { + Vec3 estimate; + estimate.x = 0.0f; + estimate.y = 0.0f; + estimate.z = 0.0f; + mobile->getPositionEstimate(estimate); + vec3ToVec2XZ(estimate, objectPosition); + } + + Vec2 botPosition; + botPosition.x = 0.0f; + botPosition.y = 0.0f; + vec3ToVec2XZ(equipment->getPosition(), botPosition); + + Vec2 forward; + forward.x = 0.0f; + forward.y = 0.0f; + const Mat4& transformation = object->getTransformation(); + Vec3 row2; + row2.x = transformation.m[8]; + row2.y = transformation.m[9]; + row2.z = transformation.m[10]; + vec3ToVec2XZ(row2, forward); + bapinline::normalize(forward); + + Vec2 direction; + direction.x = botPosition.x - objectPosition.x; + direction.y = botPosition.y - objectPosition.y; + bapinline::normalize(direction); + + return direction.x * forward.x + direction.y * forward.y <= m_threshold; +} + +// ELF 0x1ECFB0 +BAPConditionType BAPConObjectBehind::getConditionType() const +{ + return BAPCTObjectBehind; // 17 +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectBehind.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectBehind.h new file mode 100644 index 000000000..b804d6585 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectBehind.h @@ -0,0 +1,37 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTBEHIND_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTBEHIND_H + +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B95F8 (5 words), operator new 0x14, package F-infantry. +// True when the bot's equipment is behind the object: the XZ direction object->bot dotted with the +// object's forward axis (transformation row 2) is at most the threshold. True when the object is gone. +class BAPConObjectBehind : public BAPConObject +{ +public: + BAPConObjectBehind(unsigned int, float, bool); // 0x1ECB20 + virtual ~BAPConObjectBehind(); // 0x1ECB80 + + virtual bool evaluate(Bot*); // 0x1ECBE0, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1ECFB0, slot +0x04; from the base declaration +private: + /* +0x0C */ float m_threshold; // compared with the dot product (createPlan passes -0.95 / -0.8) + /* +0x10 */ bool m_useEstimate; // use the object's IPIMobile position estimate when it has one +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTBEHIND_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectDistance.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectDistance.cpp new file mode 100644 index 000000000..6bcec400e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectDistance.cpp @@ -0,0 +1,132 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1ED840 (__tcf_0 0x1ED8A0, _GLOBAL__I 0x1ED8D0): 's Init object only. +#include + +#include "BAPConObjectDistance.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/Information.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1ED0D0 (C1): max distance only. +BAPConObjectDistance::BAPConObjectDistance(unsigned int object, float maxDistance, bool estimate, bool flat, + bool outside) +{ + m_object = object; + m_minDistanceSqr = 0.0f; + m_estimate = estimate; + m_flat = flat; + m_lastDistanceSqr = 0.0f; + m_maxDistanceSqr = maxDistance * maxDistance; + m_outside = outside; +} + +// ELF 0x1ED190 (C1) +BAPConObjectDistance::BAPConObjectDistance(unsigned int object, float minDistance, float maxDistance, bool estimate, + bool flat) +{ + m_object = object; + m_estimate = estimate; + m_outside = false; + m_maxDistanceSqr = maxDistance * maxDistance; + m_flat = flat; + m_minDistanceSqr = minDistance * minDistance; + m_lastDistanceSqr = 0.0f; +} + +// ELF 0x1ED210 (D0 0x1ED230) +BAPConObjectDistance::~BAPConObjectDistance() +{ +} + +// ELF 0x1ED270 (the bot's information is not null-checked) +bool BAPConObjectDistance::evaluate(Bot* bot) +{ + Information* object = bapinline::info(m_object); + if (!object) + return true; + Information* self = bapinline::info(bot->getCurrentEquipment()); + float a, b; // the two partial sums the image adds last + if (!m_estimate) { + if (!m_flat) { + const Vec3& s = self->getPosition(); + const Vec3& o = object->getPosition(); + const float dx = o.x - s.x; + const float dy = o.y - s.y; + const float dz = o.z - s.z; + b = dz * dz; + a = dx * dx + dy * dy; + } else { + const float sx = self->getPosition().x; + const float sz = self->getPosition().z; + const float ox = object->getPosition().x; + const float oz = object->getPosition().z; + b = (ox - sx) * (ox - sx); + a = (oz - sz) * (oz - sz); + } + } else { + Vec3 p = bapinline::vec3(0.0f, 0.0f, 0.0f); + IPIMobile* mobile = object->getMobile(); + if (!mobile) + p = object->getPosition(); + else + mobile->getPositionEstimate(p); + const Vec3& s = self->getPosition(); + if (!m_flat) { + const float dx = p.x - s.x; + const float dy = p.y - s.y; + const float dz = p.z - s.z; + b = dz * dz; + a = dx * dx + dy * dy; + } else { + const float dx = p.x - s.x; + const float dz = p.z - s.z; + b = dx * dx; + a = dz * dz; + } + } + const float d = a + b; + m_lastDistanceSqr = d; + if (!m_outside) + return m_minDistanceSqr <= d && d <= m_maxDistanceSqr; + return m_maxDistanceSqr < d; +} + +// ELF 0x1ED640 +BAPConditionType BAPConObjectDistance::getConditionType() const +{ + return BAPCTObjectDistance; // 18 +} + +// ELF 0x1ED650 +void BAPConObjectDistance::streamSelf(std::ostream& out) const +{ + if (!m_outside) { + out << "ObjectDistance(" << static_cast(std::sqrt(m_minDistanceSqr)) << " <= ["; + if (m_lastDistanceSqr == 0.0f) + out << "not calculated"; + else + out << static_cast(std::sqrt(m_lastDistanceSqr)); + out << "] <= " << static_cast(std::sqrt(m_maxDistanceSqr)) << ")"; + } else { + out << "ObjectDistance["; + if (m_lastDistanceSqr == 0.0f) + out << "not calculated"; + else + out << static_cast(std::sqrt(m_lastDistanceSqr)); + out << "] > " << static_cast(std::sqrt(m_maxDistanceSqr)); + } +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectDistance.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectDistance.h new file mode 100644 index 000000000..8206d6ed1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectDistance.h @@ -0,0 +1,48 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTDISTANCE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTDISTANCE_H + +#include +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9620 (5 words), operator new 0x1C, package C-actions. +// min^2 <= d^2 <= max^2 (or d^2 > max^2 with the outside flag) between the bot's current +// vehicle/soldier and an object (3d or XZ; optionally its estimated position). No object: true. +class BAPConObjectDistance : public BAPConObject +{ +public: + BAPConObjectDistance(unsigned int, float, bool, bool, bool); // 0x1ED0D0 + BAPConObjectDistance(unsigned int, float, float, bool, bool); // 0x1ED190 + virtual ~BAPConObjectDistance(); // 0x1ED210 + + virtual bool evaluate(Bot*); // 0x1ED270, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1ED640, slot +0x04; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1ED650, slot +0x08; from the base declaration + +private: + /* +0x0C */ float m_minDistanceSqr; + /* +0x10 */ float m_maxDistanceSqr; + /* +0x14 */ bool m_estimate; // IPIMobile::getPositionEstimate (+0x2C) instead of the position + /* +0x15 */ bool m_flat; // XZ only + /* +0x16 */ bool m_outside; // "d > max" form + /* +0x18 */ float m_lastDistanceSqr; // = 0 ("not calculated") +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTDISTANCE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectDistanceToPoint.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectDistanceToPoint.cpp new file mode 100644 index 000000000..452690e23 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectDistanceToPoint.cpp @@ -0,0 +1,91 @@ +// Object-to-point distance condition recovered from libaidll.so. +// static init: ELF 0x1EDF10 (__tcf_0 0x1EDF70, _GLOBAL__I 0x1EDFA0): 's Init object only. +#include +#include "BAPConObjectDistanceToPoint.h" +#include "BAPActionInline.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIMobile.h" +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1ED980 (C1; C2 0x1ED8F0) +BAPConObjectDistanceToPoint::BAPConObjectDistanceToPoint(const Vec3& point, unsigned int object, + float maxDistance, bool estimate, bool flat) + : m_minDistanceSqr(0.0f), m_maxDistanceSqr(maxDistance * maxDistance), + m_estimate(estimate), m_flat(flat), m_point(point), m_lastDistanceSqr(0.0f) +{ + m_object = object; +} + +// ELF 0x1EDAA0 (C1; C2 0x1EDA10) +BAPConObjectDistanceToPoint::BAPConObjectDistanceToPoint(const Vec3& point, unsigned int object, + float minDistance, float maxDistance, + bool estimate, bool flat) + : m_minDistanceSqr(minDistance * minDistance), m_maxDistanceSqr(maxDistance * maxDistance), + m_estimate(estimate), m_flat(flat), m_point(point), m_lastDistanceSqr(0.0f) +{ + m_object = object; +} + +// ELF 0x1EDB50 (D1; D2 0x1EDB30, D0 0x1EDB70) +BAPConObjectDistanceToPoint::~BAPConObjectDistanceToPoint() +{ +} + +// ELF 0x1EDBB0 +bool BAPConObjectDistanceToPoint::evaluate(Bot*) +{ + Information* object = bapinline::info(m_object); + if (!object) + return true; + float distanceSqr; + if (m_estimate) { + IPIMobile* mobile = object->getMobile(); + Vec3 position = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (mobile) + mobile->getPositionEstimate(position); + else + position = object->getPosition(); + if (m_flat) + distanceSqr = distXZSqr(position, m_point); + else { + const Vec3 delta = bapinline::sub(position, m_point); + distanceSqr = delta.x * delta.x + delta.y * delta.y + delta.z * delta.z; + } + } else if (m_flat) { + distanceSqr = distXZSqr(object->getPosition(), m_point); + } else { + const Vec3 delta = bapinline::sub(object->getPosition(), m_point); + distanceSqr = delta.x * delta.x + delta.y * delta.y + delta.z * delta.z; + } + m_lastDistanceSqr = distanceSqr; + return m_minDistanceSqr <= distanceSqr && distanceSqr <= m_maxDistanceSqr; +} + +// ELF 0x1EDF00 +BAPConditionType BAPConObjectDistanceToPoint::getConditionType() const +{ + return BAPCTObjectDistanceToPoint; +} + +// ELF 0x1EDD80 +void BAPConObjectDistanceToPoint::streamSelf(std::ostream& out) const +{ + out << "PointDistance["; + if (m_lastDistanceSqr == 0.0f) + out << "not calculated"; + else + out << static_cast(std::sqrt(m_lastDistanceSqr)); + out << "] < " << static_cast(std::sqrt(m_maxDistanceSqr)); + if (m_minDistanceSqr != 0.0f) + out << " && PointDistance[" << static_cast(std::sqrt(m_lastDistanceSqr)) + << "] > " << static_cast(std::sqrt(m_minDistanceSqr)); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectDistanceToPoint.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectDistanceToPoint.h new file mode 100644 index 000000000..34addbb93 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectDistanceToPoint.h @@ -0,0 +1,42 @@ +// Tests an object's distance from a fixed point; missing information satisfies the condition. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTDISTANCETOPOINT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTDISTANCETOPOINT_H + +#include +#include "../../../../Math/Vec3.h" +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9648 (5 words), package H-deferred. +class BAPConObjectDistanceToPoint : public BAPConObject +{ +public: + BAPConObjectDistanceToPoint(const Vec3&, unsigned int, float, bool, bool); // 0x1ED980 + BAPConObjectDistanceToPoint(const Vec3&, unsigned int, float, float, bool, bool); // 0x1EDAA0 + virtual ~BAPConObjectDistanceToPoint(); // 0x1EDB50 + + virtual bool evaluate(Bot*); // 0x1EDBB0, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EDF00, slot +0x04; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1EDD80, slot +0x08; from the base declaration +private: + /* +0x0C */ float m_minDistanceSqr; + /* +0x10 */ float m_maxDistanceSqr; + /* +0x14 */ bool m_estimate; + /* +0x15 */ bool m_flat; + /* +0x18 */ Vec3 m_point; + /* +0x24 */ float m_lastDistanceSqr; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTDISTANCETOPOINT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectEnemyOccupied.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectEnemyOccupied.cpp new file mode 100644 index 000000000..27f713f1f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectEnemyOccupied.cpp @@ -0,0 +1,49 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1EE160 (__tcf_0 0x1EE1C0, _GLOBAL__I 0x1EE1F0): 's Init object only. +#include + +#include "BAPConObjectEnemyOccupied.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../AIUtils/VehicleOccupancy.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1EDFF0 (C1; C2 0x1EDFC0): +4 = 0, +8 = the handle. +BAPConObjectEnemyOccupied::BAPConObjectEnemyOccupied(unsigned int object) +{ + setOwner(0); + m_object = object; +} + +// ELF 0x1EE0F0 (D0 0x1EE110) +BAPConObjectEnemyOccupied::~BAPConObjectEnemyOccupied() +{ +} + +// ELF 0x1EE020: vehicleOccupied(handle, bot side) (Bot +0xE0), then the information's side +// (vfn +0x44, Information::getSide) against the bot's side again. +bool BAPConObjectEnemyOccupied::evaluate(Bot* bot) +{ + if (!vehicleOccupied(m_object, bot->getSide())) + return false; + Information* info = bapinline::info(m_object); + if (!info) + return false; + return info->getSide() != bot->getSide(); +} + +// ELF 0x1EE150 +BAPConditionType BAPConObjectEnemyOccupied::getConditionType() const +{ + return BAPCTObjectEnemyOccupied; // 20 +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectEnemyOccupied.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectEnemyOccupied.h new file mode 100644 index 000000000..bb387c9ac --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectEnemyOccupied.h @@ -0,0 +1,33 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTENEMYOCCUPIED_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTENEMYOCCUPIED_H + +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9670 (5 words), operator new 0xC, package F-infantry. +// True when vehicleOccupied(object, bot side) and the object's side differs from the bot's. +class BAPConObjectEnemyOccupied : public BAPConObject +{ +public: + explicit BAPConObjectEnemyOccupied(unsigned int); // 0x1EDFF0 + virtual ~BAPConObjectEnemyOccupied(); // 0x1EE0F0 + + virtual bool evaluate(Bot*); // 0x1EE020, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EE150, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTENEMYOCCUPIED_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectExists.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectExists.cpp new file mode 100644 index 000000000..4bb14e841 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectExists.cpp @@ -0,0 +1,39 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. + +// static init: ELF 0x1EE350 (__tcf_0 0x1EE3B0, _GLOBAL__I 0x1EE3E0): 's Init object only. +#include + +#include "BAPConObjectExists.h" + +#include "BAPActionInline.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1EE240 (C1; C2 0x1EE210) +BAPConObjectExists::BAPConObjectExists(unsigned int object) +{ + m_object = object; +} + +// ELF 0x1EE2E0 (C1 0x1EE2C0, D0 0x1EE300): base only. +BAPConObjectExists::~BAPConObjectExists() +{ +} + +// ELF 0x1EE270 +bool BAPConObjectExists::evaluate(Bot*) +{ + return bapinline::info(m_object) != 0; +} + +// ELF 0x1EE340 +BAPConditionType BAPConObjectExists::getConditionType() const +{ + return BAPCTObjectExists; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectExists.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectExists.h new file mode 100644 index 000000000..525f2a6e2 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectExists.h @@ -0,0 +1,33 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTEXISTS_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTEXISTS_H + +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9698 (5 words), operator new 0xC, package F-infantry. +// True while the object has information. +class BAPConObjectExists : public BAPConObject +{ +public: + explicit BAPConObjectExists(unsigned int); // 0x1EE240 + virtual ~BAPConObjectExists(); // 0x1EE2E0 + + virtual bool evaluate(Bot*); // 0x1EE270, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EE340, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTEXISTS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectHealth.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectHealth.cpp new file mode 100644 index 000000000..9a972a6db --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectHealth.cpp @@ -0,0 +1,57 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1EE5E0 (__tcf_0 0x1EE640, _GLOBAL__I 0x1EE670): 's Init object only. +#include + +#include "BAPConObjectHealth.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1EE440 (C1) +BAPConObjectHealth::BAPConObjectHealth(unsigned int object, float health) +{ + m_object = object; + m_health = health; +} + +// ELF 0x1EE4A0 (D0 0x1EE4C0): base only. +BAPConObjectHealth::~BAPConObjectHealth() +{ +} + +// ELF 0x1EE500 +bool BAPConObjectHealth::evaluate(Bot*) +{ + Information* info = bapinline::info(m_object); + bool result = false; + if (info) + result = info->getPhysical()->getHealth() <= m_health; + return result; +} + +// ELF 0x1EE580 +BAPConditionType BAPConObjectHealth::getConditionType() const +{ + return BAPCTObjectHealth; +} + +// ELF 0x1EE590 +void BAPConObjectHealth::streamSelf(std::ostream& out) const +{ + out << "ObjectHealth <= " << static_cast(m_health); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectHealth.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectHealth.h new file mode 100644 index 000000000..51f66c79c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectHealth.h @@ -0,0 +1,41 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTHEALTH_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTHEALTH_H + +#include +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B96C0 (5 words), operator new 0xC/0x10, package C-actions. +// The object's health (IPIPhysical::getHealth) is at most the limit; no information: false. +class BAPConObjectHealth : public BAPConObject +{ +public: + BAPConObjectHealth(unsigned int, float); // 0x1EE440 + virtual ~BAPConObjectHealth(); // 0x1EE4A0 + + virtual bool evaluate(Bot*); // 0x1EE500, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EE580, slot +0x04; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1EE590, slot +0x08; from the base declaration + +private: + /* +0x0C */ float m_health; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTHEALTH_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInFront.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInFront.cpp new file mode 100644 index 000000000..35bfc4243 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInFront.cpp @@ -0,0 +1,59 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// [PLATFORM] precision: the x87 build adds the scaled forward axis to the position in extended +// precision before rounding the point. + +// static init: ELF 0x1EE9E0 (__tcf_0 0x1EEA40, _GLOBAL__I 0x1EEA70): 's Init object only. +#include + +#include "BAPConObjectInFront.h" + +#include "../../../../Math/Mat4.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "BAPActionInline.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1EE6D0 (C1; C2 0x1EE690) +BAPConObjectInFront::BAPConObjectInFront(unsigned int object, float distance, float minDot) +{ + m_object = object; + m_distance = distance; + m_minDot = minDot; +} + +// ELF 0x1EE730 (D1 0x1EE710, D0 0x1EE750): base only. +BAPConObjectInFront::~BAPConObjectInFront() +{ +} + +// ELF 0x1EE790. No information on the object or the bot's vehicle: false. +bool BAPConObjectInFront::evaluate(Bot* bot) +{ + Information* const target = bapinline::info(m_object); + if (!target) + return false; + Information* const self = bapinline::info(bot->getCurrentEquipment()); + if (!self) + return false; + const Mat4& transformation = self->getTransformation(); + const Vec3 forward = bapinline::vec3(transformation.m[8], transformation.m[9], transformation.m[10]); + const Vec3& position = self->getPosition(); + const Vec3 ahead = bapinline::vec3(forward.x * m_distance, forward.y * m_distance, forward.z * m_distance); + const Vec3 front = bapinline::add(ahead, position); + Vec3 direction = bapinline::sub(target->getPosition(), front); + bapinline::normalize(direction); + return bapinline::dot(forward, direction) > m_minDot; +} + +// ELF 0x1EE9D0 +BAPConditionType BAPConObjectInFront::getConditionType() const +{ + return BAPCTObjectInFront; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInFront.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInFront.h new file mode 100644 index 000000000..33ce20d85 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInFront.h @@ -0,0 +1,38 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTINFRONT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTINFRONT_H + +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B96E8 (5 words), operator new 0x14, package F-infantry. +// True when the direction from a point `distance` ahead of the bot's vehicle to the object deviates +// from the vehicle's forward axis by a cosine above `minDot`. +class BAPConObjectInFront : public BAPConObject +{ +public: + BAPConObjectInFront(unsigned int, float, float); // 0x1EE6D0 + virtual ~BAPConObjectInFront(); // 0x1EE730 + + virtual bool evaluate(Bot*); // 0x1EE790, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EE9D0, slot +0x04; from the base declaration + +private: + /* +0x0C */ float m_distance; // [INFERRED] names + /* +0x10 */ float m_minDot; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTINFRONT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInLandingZone.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInLandingZone.cpp new file mode 100644 index 000000000..39fcf1823 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInLandingZone.cpp @@ -0,0 +1,46 @@ +// Tests whether the object is inside the bot's assigned landing zone. + +// static init: ELF 0x1EEC20 (__tcf_0 0x1EEC80, _GLOBAL__I 0x1EECB0): 's Init object only. +#include + +#include "BAPConObjectInLandingZone.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../AIStrategicEntity/AILandingZone.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1EEAD0 (C1; C2 0x1EEA90) +BAPConObjectInLandingZone::BAPConObjectInLandingZone(unsigned int object) +{ + m_object = object; +} + +// ELF 0x1EEB30 (D1; D2 0x1EEB10, D0 0x1EEB50) +BAPConObjectInLandingZone::~BAPConObjectInLandingZone() +{ +} + +// ELF 0x1EEB90 +bool BAPConObjectInLandingZone::evaluate(Bot* bot) +{ + Information* object = bapinline::info(m_object); + if (!object || !static_cast(bot)->m_ptr232) + return false; + const Vec3& position = object->getPosition(); + return static_cast(static_cast(bot)->m_ptr232)->isInZone(position); +} + +// ELF 0x1EECD0 +BAPConditionType BAPConObjectInLandingZone::getConditionType() const +{ + return BAPCTObjectInLandingZone; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInLandingZone.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInLandingZone.h new file mode 100644 index 000000000..a0f8cfaed --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInLandingZone.h @@ -0,0 +1,31 @@ +// Tests whether the object is inside the bot's assigned landing zone. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTINLANDINGZONE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTINLANDINGZONE_H + +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9710 (5 words), package H-deferred. +class BAPConObjectInLandingZone : public BAPConObject +{ +public: + explicit BAPConObjectInLandingZone(unsigned int); // 0x1EEAD0 + virtual ~BAPConObjectInLandingZone(); // 0x1EEB30 + + virtual bool evaluate(Bot*); // 0x1EEB90, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EECD0, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTINLANDINGZONE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInsideFrustum.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInsideFrustum.cpp new file mode 100644 index 000000000..f1176528b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInsideFrustum.cpp @@ -0,0 +1,65 @@ +// Camera-frustum condition recovered from libaidll.so. +// static init: ELF 0x1EF010 (__tcf_0 0x1EF070, _GLOBAL__I 0x1EF0A0): 's Init object only. +#include +#include "BAPConObjectInsideFrustum.h" +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1EED40 (C1; C2 0x1EECE0) +BAPConObjectInsideFrustum::BAPConObjectInsideFrustum(unsigned int object, TransformType type) + : m_transformType(type), m_frustum(), m_initialize(true) +{ + m_object = object; +} + +// ELF 0x1EEDC0 (D1; D2 0x1EEDA0, D0 0x1EEDE0) +BAPConObjectInsideFrustum::~BAPConObjectInsideFrustum() +{ +} + +// ELF 0x1EEE20 +bool BAPConObjectInsideFrustum::evaluate(Bot* bot) +{ + if (!bot) + return false; + Information* object = bapinline::info(m_object); + if (!object) + return false; + Information* self = bapinline::info(bot->getCurrentEquipment()); + if (!self || m_transformType != 0) + return false; + if (m_initialize) { + m_initialize = false; + const float farDistance = bot->getPlayer()->getViewDistance(); + if (self->isOfType(ITObstructedView)) { + const Mat4& camera = *static_cast(bot->getPlayer()->getCameraTransformation()); + m_frustum.setPerspective(1.570796371f, 1.0f, 0.01f, farDistance, camera); + } else { + const Mat4& camera = *static_cast(bot->getPlayer()->getCameraTransformation()); + m_frustum.setPerspective(2.094395161f, 1.0f, 0.01f, farDistance, camera); + } + } + IPIPhysical* physical = object->getPhysical(); + if (physical) { + const float radius = physical->getRadius(); + return m_frustum.inside(object->getPosition(), radius); + } + return m_frustum.inside(object->getPosition(), 1.0f); +} + +// ELF 0x1EF000 +BAPConditionType BAPConObjectInsideFrustum::getConditionType() const +{ + return BAPCTObjectInsideFrustum; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInsideFrustum.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInsideFrustum.h new file mode 100644 index 000000000..cb2327d78 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInsideFrustum.h @@ -0,0 +1,37 @@ +// Object visibility against a camera frustum initialized on the first eligible evaluation. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTINSIDEFRUSTUM_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTINSIDEFRUSTUM_H + +#include "BAPConObject.h" +#include "../../../../Math/Frustum.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9738 (5 words), package H-deferred. +class BAPConObjectInsideFrustum : public BAPConObject +{ +public: + enum TransformType : int; // [UNRESOLVED] enumerators + BAPConObjectInsideFrustum(unsigned int, BAPConObjectInsideFrustum::TransformType); // 0x1EED40 + virtual ~BAPConObjectInsideFrustum(); // 0x1EEDC0 + + virtual bool evaluate(Bot*); // 0x1EEE20, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EF000, slot +0x04; from the base declaration +private: + /* +0x00C */ TransformType m_transformType; + /* +0x010 */ Frustum m_frustum; + /* +0x1F8 */ bool m_initialize; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTINSIDEFRUSTUM_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectLineOfFire.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectLineOfFire.cpp new file mode 100644 index 000000000..c93b0a4cf --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectLineOfFire.cpp @@ -0,0 +1,164 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1EF940 (__tcf_0 0x1EF9A0, _GLOBAL__I 0x1EF9D0): 's Init object only. +#include + +#include "BAPConObjectLineOfFire.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SensedObject.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// Function statics of hasFriendlySoldiersInLineOfFire (ELF .data 0x4B9784 / 0x4B9788 / 0x4B978C). +const float allowedDistanceShort = 0.5f; +const float allowedDistanceFar = 1.5f; +const float minDistForSideStep = 5.0f; + +} // namespace + +// ELF 0x1EF100 (C1; C2 0x1EF0C0) +BAPConObjectLineOfFire::BAPConObjectLineOfFire(unsigned int object, bool flag) +{ + m_anyPose = true; + m_object = object; + m_flag0D = flag; +} + +// ELF 0x1EF180 (C1; C2 0x1EF140) +BAPConObjectLineOfFire::BAPConObjectLineOfFire(unsigned int object, bool flag, SoldierPose pose) +{ + m_anyPose = false; + m_object = object; + m_flag0D = flag; + m_pose = pose; +} + +// ELF 0x1EF8D0 (D1; D0 0x1EF8F0): base only. +BAPConObjectLineOfFire::~BAPConObjectLineOfFire() +{ +} + +// ELF 0x1EF1C0. True when the bot senses the target directly (record without flag 8); a weapon +// that cannot fire through transparent objects also needs flag 0x40 on the record. A soldier +// additionally needs no friendly soldier in the line of fire. No information for the bot or the +// target: false. +bool BAPConObjectLineOfFire::evaluate(Bot* bot) +{ + Information* self = bapinline::info(bot->getCurrentEquipment()); + Information* target = bapinline::info(m_object); + if (!self || !target) + return false; + SensedObject* sensed = bot->getSensedObjectFromHandle(m_object); + bool result = sensed && !(sensed->m_flags & 8u); + IPIArmament* armament = self->getArmament(); + if (armament && armament->getActiveWeapon() != -1) { + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + if (weapon && sensed && !weapon->getFiresThroughTransparent()) { + const bool clear = !(sensed->m_flags & 8u) && !(sensed->m_flags & 0x40u); + result = result && !clear; + } + } + if (result && self->isOfType(ITSoldier)) + result = !hasFriendlySoldiersInLineOfFire(bot, self, target); + return result; +} + +// ELF 0x1EF360. Friendly soldiers (same side, not the bot, not the target) between the weapon's +// projectile origin and the target, within a corridor widening from allowedDistanceShort at the +// muzzle to allowedDistanceFar at 50 m (support kit (spawn kit 1) with a range above 100 m and a +// weapon zoom other than 0x40: allowedDistanceShort throughout). A friend closer than +// minDistForSideStep in the bot's facing (XZ dot > 0.9) stamps BotMain::setFriendsInLineOfFireTime +// (now) and answers at once; otherwise the stamp is cleared (0.0) after the scan. The bot's weapon +// is not null-checked. +bool BAPConObjectLineOfFire::hasFriendlySoldiersInLineOfFire(Bot* bot, Information* self, Information* target) +{ + BotMain* main = static_cast(bot); + IPIArmament* armament = self->getArmament(); + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + const Mat4& origin = weapon->getProjectileOrigin(); + const Vec3& tp = target->getPosition(); + Vec3 dir = bapinline::vec3(tp.x - origin.m[12], tp.y - origin.m[13], tp.z - origin.m[14]); + const float distance = std::sqrt(dir.z * dir.z + dir.x * dir.x + dir.y * dir.y); + if (0.0001f < distance) { + const float inv = 1.0f / distance; + dir.x *= inv; + dir.y *= inv; + dir.z = inv * dir.z; + } + + bool found = false; + const std::vector& players = + static_cast(CommonSingletonServer::m_iaiPlayerFactory)->getAllPlayers(); + for (unsigned int i = 0; i < players.size(); ++i) { + IAIPlayer* player = players[i]; + if (!player || player->getSide() != bot->getSide()) + continue; + IAIObject* vehicle = player->getCurrentVehicle(); + if (!vehicle) + continue; + Information* info = bapinline::info(vehicle->getInformation(bot->getSide())); + if (info == self || info == target || !info || !info->isOfType(ITSoldier)) + continue; + const Vec3& p = info->getPosition(); + const Vec3 rel = bapinline::vec3(p.x - origin.m[12], p.y - origin.m[13], p.z - origin.m[14]); + const float along = dir.z * rel.z + dir.y * rel.y + dir.x * rel.x; + if (distance < along) + continue; + const Vec3 perp = bapinline::vec3(rel.x - dir.x * along, rel.y - along * dir.y, rel.z - dir.z * along); + const float allowed = (along / 50.0f) * (allowedDistanceFar - allowedDistanceShort) + allowedDistanceShort; + float limit = allowed; + if (weapon->getWeaponZoom() != 0x40 && bot->getSpawnKit() == 1) { + limit = allowedDistanceShort; + if (weapon->getMaxRange() <= 100.0f) + limit = allowed; + } + if (!(perp.z * perp.z + perp.y * perp.y + perp.x * perp.x < limit * limit)) + continue; + found = true; + if (!(along < minDistForSideStep)) + continue; + Vec2 dir2; + dir2.x = 0.0f; + dir2.y = 0.0f; + vec3ToVec2XZ(dir, dir2); + bapinline::normalize(dir2); + const Vec3 facing = self->getFaceing(); + Vec2 face2; + face2.x = 0.0f; + face2.y = 0.0f; + vec3ToVec2XZ(facing, face2); + if (0.9f < dir2.x * face2.x + dir2.y * face2.y) { + main->setFriendsInLineOfFireTime(bapinline::gameTime()); + return true; + } + } + main->setFriendsInLineOfFireTime(0.0); + return found; +} + +// ELF 0x1EF930 +BAPConditionType BAPConObjectLineOfFire::getConditionType() const +{ + return BAPCTObjectLineOfFire; // 26 +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectLineOfFire.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectLineOfFire.h new file mode 100644 index 000000000..ac53f4c86 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectLineOfFire.h @@ -0,0 +1,45 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTLINEOFFIRE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTLINEOFFIRE_H + +#include "../../../AIInterface/BFKnowledge/SoldierPose.h" +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class Information; + +// ELF: vtable 0x4B9790 (5 words), operator new 0x10/0x14, package C-actions. +class BAPConObjectLineOfFire : public BAPConObject +{ +public: + BAPConObjectLineOfFire(unsigned int, bool); // 0x1EF100 + BAPConObjectLineOfFire(unsigned int, bool, SoldierPose); // 0x1EF180 + virtual ~BAPConObjectLineOfFire(); // 0x1EF8D0 + + virtual bool evaluate(Bot*); // 0x1EF1C0, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EF930, slot +0x04; from the base declaration + + bool hasFriendlySoldiersInLineOfFire(Bot*, Information*, Information*); // 0x1EF360; ELF bool + +private: + /* +0x0C */ bool m_anyPose; // first constructor: true; second: false + /* +0x0D */ bool m_flag0D; // constructor bool; [UNRESOLVED] not read by evaluate + /* +0x10 */ SoldierPose m_pose; // second constructor only; [UNRESOLVED] not read by evaluate +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTLINEOFFIRE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectManDown.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectManDown.cpp new file mode 100644 index 000000000..e04df7f88 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectManDown.cpp @@ -0,0 +1,43 @@ +// Condition: the object is man down. Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); +// every body carries its ELF address. + +#include "BAPConObjectManDown.h" + +#include "BAPActionInline.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/Information.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1EFA20 (C1; C2 0x1EF9F0): +0x04 = 0 by the base, +0x08 = the object handle. +BAPConObjectManDown::BAPConObjectManDown(unsigned int object) +{ + m_object = object; +} + +// ELF 0x1EFA70 (D1; D2 0x1EFA50, D0 0x1EFA90): base only. +BAPConObjectManDown::~BAPConObjectManDown() +{ +} + +// ELF 0x1EFAD0: the object's physical plug-in getManDown (+0x5C); false without information. +bool BAPConObjectManDown::evaluate(Bot*) +{ + Information* info = bapinline::info(m_object); + bool result = false; + if (info) + result = info->getPhysical()->getManDown(); + return result; +} + +// ELF 0x1EFB40 +BAPConditionType BAPConObjectManDown::getConditionType() const +{ + return BAPCTObjectManDown; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectManDown.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectManDown.h new file mode 100644 index 000000000..202faaad2 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectManDown.h @@ -0,0 +1,31 @@ +// Condition: the object is man down. Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTMANDOWN_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTMANDOWN_H + +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B97B8 (5 words), operator new 0xC, package F-infantry. +class BAPConObjectManDown : public BAPConObject +{ +public: + explicit BAPConObjectManDown(unsigned int); // 0x1EFA20 + virtual ~BAPConObjectManDown(); // 0x1EFA70 + + virtual bool evaluate(Bot*); // 0x1EFAD0, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EFB40, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTMANDOWN_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectMoved.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectMoved.cpp new file mode 100644 index 000000000..415d4622c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectMoved.cpp @@ -0,0 +1,48 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1EFD00 (__tcf_0 0x1EFD60, _GLOBAL__I 0x1EFD90): 's Init object only. +#include + +#include "BAPConObjectMoved.h" + +#include "BAPActionInline.h" +#include "../AIKnowledge/Information.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1EFBA0 (C1; C2 0x1EFB50 region) +BAPConObjectMoved::BAPConObjectMoved(unsigned int object, float distance) +{ + setOwner(0); + m_object = object; + m_lastPosition = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_distanceSqr = distance * distance; +} + +// ELF 0x1EFDB0 (D0 0x1EFDD0) +BAPConObjectMoved::~BAPConObjectMoved() +{ +} + +// ELF 0x1EFBF0 +bool BAPConObjectMoved::evaluate(Bot*) +{ + Information* info = bapinline::info(m_object); + if (info && m_distanceSqr < bapinline::lengthSqr(bapinline::sub(info->getPosition(), m_lastPosition))) { + m_lastPosition = info->getPosition(); + return true; + } + return false; +} + +// ELF 0x1EFCF0 +BAPConditionType BAPConObjectMoved::getConditionType() const +{ + return BAPCTObjectMoved; // 28 +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectMoved.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectMoved.h new file mode 100644 index 000000000..58723f6a7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectMoved.h @@ -0,0 +1,42 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTMOVED_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTMOVED_H + +#include "../../../../Math/Vec3.h" +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B97E0 (5 words), operator new 0x1C/0x114, package C-actions. +// True once the object has moved more than the distance since the last true answer +// (the reference point starts at the origin). +class BAPConObjectMoved : public BAPConObject +{ +public: + BAPConObjectMoved(unsigned int, float); // 0x1EFBA0 + virtual ~BAPConObjectMoved(); // 0x1EFDB0 + + virtual bool evaluate(Bot*); // 0x1EFBF0, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EFCF0, slot +0x04; from the base declaration + +private: + /* +0x0C */ Vec3 m_lastPosition; // = 0; updated on every true answer + /* +0x18 */ float m_distanceSqr; // the ctor's distance squared +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTMOVED_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectOccupied.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectOccupied.cpp new file mode 100644 index 000000000..942f7d39b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectOccupied.cpp @@ -0,0 +1,45 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1EFF70 (__tcf_0 0x1EFFD0, _GLOBAL__I 0x1F0000): 's Init object only. +#include + +#include "BAPConObjectOccupied.h" + +#include "BAPActionInline.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1EFE40 (C1; C2 0x1EFE10): +4 = 0, +8 = the handle. +BAPConObjectOccupied::BAPConObjectOccupied(unsigned int object) +{ + setOwner(0); + m_object = object; +} + +// ELF 0x1EFF00 (D0 0x1EFF20): only the base vtable store. +BAPConObjectOccupied::~BAPConObjectOccupied() +{ +} + +// ELF 0x1EFE70: false without the information or its unit plug-in (+0x40). +bool BAPConObjectOccupied::evaluate(Bot*) +{ + Information* info = bapinline::info(m_object); + if (info && info->getUnit()) + return info->getUnit()->isOccupied(); + return false; +} + +// ELF 0x1EFF60 +BAPConditionType BAPConObjectOccupied::getConditionType() const +{ + return BAPCTObjectOccupied; // 29 +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectOccupied.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectOccupied.h new file mode 100644 index 000000000..dda5fc82c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectOccupied.h @@ -0,0 +1,33 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTOCCUPIED_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTOCCUPIED_H + +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9848 (5 words), operator new 0xC, package F-infantry. +// True when the object's unit plug-in reports it occupied (IPIUnit::isOccupied). +class BAPConObjectOccupied : public BAPConObject +{ +public: + explicit BAPConObjectOccupied(unsigned int); // 0x1EFE40 + virtual ~BAPConObjectOccupied(); // 0x1EFF00 + + virtual bool evaluate(Bot*); // 0x1EFE70, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EFF60, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTOCCUPIED_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectSpeed.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectSpeed.cpp new file mode 100644 index 000000000..fe8984a7b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectSpeed.cpp @@ -0,0 +1,47 @@ +// Tests whether the object's speed is strictly below a fixed threshold. + +// static init: ELF 0x1F01B0 (__tcf_0 0x1F0210, _GLOBAL__I 0x1F0240): 's Init object only. +#include + +#include "BAPConObjectSpeed.h" + +#include "BAPActionInline.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIMobile.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F0060 (C1; C2 0x1F0020) +BAPConObjectSpeed::BAPConObjectSpeed(unsigned int object, float speed) : m_speed(speed) +{ + m_object = object; +} + +// ELF 0x1F00C0 (D1; D2 0x1F00A0, D0 0x1F00E0) +BAPConObjectSpeed::~BAPConObjectSpeed() +{ +} + +// ELF 0x1F0120 +bool BAPConObjectSpeed::evaluate(Bot*) +{ + Information* object = bapinline::info(m_object); + if (!object) + return false; + IPIMobile* mobile = object->getMobile(); + if (!mobile) + return true; + return mobile->getSpeedMagnitude() < m_speed; +} + +// ELF 0x1F01A0 +BAPConditionType BAPConObjectSpeed::getConditionType() const +{ + return BAPCTObjectSpeed; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectSpeed.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectSpeed.h new file mode 100644 index 000000000..8cab01ec2 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectSpeed.h @@ -0,0 +1,33 @@ +// Tests whether the object's speed is strictly below a fixed threshold. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTSPEED_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTSPEED_H + +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9870 (5 words), package H-deferred. +class BAPConObjectSpeed : public BAPConObject +{ +public: + BAPConObjectSpeed(unsigned int, float); // 0x1F0060 + virtual ~BAPConObjectSpeed(); // 0x1F00C0 + + virtual bool evaluate(Bot*); // 0x1F0120, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F01A0, slot +0x04; from the base declaration +private: + /* +0x0C */ float m_speed; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTSPEED_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectTouchingLand.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectTouchingLand.cpp new file mode 100644 index 000000000..e11310217 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectTouchingLand.cpp @@ -0,0 +1,47 @@ +// Tests the inverse of the object's physical in-air state. + +// static init: ELF 0x1F03E0 (__tcf_0 0x1F0440, _GLOBAL__I 0x1F0470): 's Init object only. +#include + +#include "BAPConObjectTouchingLand.h" + +#include "BAPActionInline.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIPhysical.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F02A0 (C1; C2 0x1F0260) +BAPConObjectTouchingLand::BAPConObjectTouchingLand(unsigned int object) +{ + m_object = object; +} + +// ELF 0x1F0300 (D1; D2 0x1F02E0, D0 0x1F0320) +BAPConObjectTouchingLand::~BAPConObjectTouchingLand() +{ +} + +// ELF 0x1F0360 +bool BAPConObjectTouchingLand::evaluate(Bot*) +{ + Information* object = bapinline::info(m_object); + if (!object) + return false; + IPIPhysical* physical = object->getPhysical(); + if (!physical) + return false; + return !physical->isInAir(); +} + +// ELF 0x1F0490 +BAPConditionType BAPConObjectTouchingLand::getConditionType() const +{ + return BAPCTObjectTouchingLand; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectTouchingLand.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectTouchingLand.h new file mode 100644 index 000000000..f6f87d126 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectTouchingLand.h @@ -0,0 +1,31 @@ +// Tests the inverse of the object's physical in-air state. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTTOUCHINGLAND_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTTOUCHINGLAND_H + +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9898 (5 words), package H-deferred. +class BAPConObjectTouchingLand : public BAPConObject +{ +public: + explicit BAPConObjectTouchingLand(unsigned int); // 0x1F02A0 + virtual ~BAPConObjectTouchingLand(); // 0x1F0300 + + virtual bool evaluate(Bot*); // 0x1F0360, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F0490, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTTOUCHINGLAND_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidAiming.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidAiming.cpp new file mode 100644 index 000000000..66237bc3b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidAiming.cpp @@ -0,0 +1,152 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1F0D70 (__tcf_0 0x1F0DD0, _GLOBAL__I 0x1F0E00): 's Init object only. +#include + +#include "BAPConObjectValidAiming.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SensedObject.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFPhysics.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F0510 (C1; C2 0x1F0480): the bot's own equipment shoots. +BAPConObjectValidAiming::BAPConObjectValidAiming(unsigned int object, BAPVariable* aimValid, + BAPVariable* aimDirection, bool trackStaticAttack) +{ + m_shooter = 0xFFFFFFFFu; + m_object = object; + m_aimValid = aimValid; + m_aimDirection = aimDirection; + m_trackStaticAttack = trackStaticAttack; +} + +// ELF 0x1F05F0 (C1; C2 0x1F0580) +BAPConObjectValidAiming::BAPConObjectValidAiming(unsigned int object, unsigned int shooter, BAPVariable* aimValid, + BAPVariable* aimDirection, bool trackStaticAttack) +{ + m_object = object; + m_shooter = shooter; + m_aimValid = aimValid; + m_aimDirection = aimDirection; + m_trackStaticAttack = trackStaticAttack; +} + +// ELF 0x1F0E20 (D1; D0 0x1F0E70): the Aimer and the base only. +BAPConObjectValidAiming::~BAPConObjectValidAiming() +{ +} + +// ELF 0x1F0660. The aim must be solvable (internalAiming) and the camera must be able to turn to +// the direction (IPIControlInfo::validateCameraDirection on m_shooter's, or the bot's, control +// info; not null-checked). Retail quirk: with the Aimer path internalAiming leaves `dir` at zero, +// so the camera check sees (0, 0, 0). With m_trackStaticAttack a failed check stamps the failed +// static attack time and clears both artillery flags (unless the aim failed too and the last +// failed sky attack is at most 2.5 s old: false without stamping), or, while the bot wants to +// simulate artillery, the failed sky attack time. +bool BAPConObjectValidAiming::evaluate(Bot* bot) +{ + Vec3 dir = bapinline::vec3(0.0f, 0.0f, 0.0f); + const bool aimed = internalAiming(bot, dir); + bool valid = false; + if (aimed) { + const unsigned int handle = m_shooter == 0xFFFFFFFFu ? bot->getCurrentEquipment() : m_shooter; + valid = bapinline::info(handle)->getControlInfo()->validateCameraDirection(dir); + } + if (m_trackStaticAttack) { + BotMain* main = static_cast(bot); + const double now = bapinline::gameTime(); + if (!main->getBotWantsToSimulateArtillery()) { + if (!valid) { + if (!aimed && now - main->getTimeOfLastFailedStaticSkyAttack() <= 2.5) + return false; + main->setTimeOfLastFailedStaticAttack(now); + main->setBotWantsToSimulateArtillery(false); + main->setBotIsSimulatingArtillery(false); + } + } else if (!valid) { + main->setTimeOfLastFailedStaticSkyAttack(now); + } + } + return valid; +} + +// ELF 0x1F07E0. With both variables: dir = the direction variable, answer = the valid variable. +// Otherwise solves the Aimer for the active weapon of the bot's current vehicle/soldier against +// the target (its position when not sensed or sensed indirectly (flag 8), else the sensed hit +// point), relative to the weapon's absolute transformation, 0.1 s ahead; `dir` is not written +// (the solution goes to a local). No information, control info, armament, weapon or target: false. +bool BAPConObjectValidAiming::internalAiming(Bot* bot, Vec3& dir) +{ + if (m_aimValid && m_aimDirection) { + dir = m_aimDirection->m_value; + return m_aimValid->m_value; + } + Information* self = bapinline::info(bot->getCurrentEquipment()); + if (!self || !self->getControlInfo() || !self->getArmament()) + return false; + IPIArmament* armament = self->getArmament(); + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + if (!weapon) + return false; + Information* target = bapinline::info(m_object); + if (!target) + return false; + IPIMobile* ownMobile = bapinline::info(self->getPrimaryObject(bot->getSide()))->getMobile(); // not null-checked + + const float drag = weapon->getDrag(); + m_aimer.m_drag = drag; + m_aimer.m_inverseDrag = drag != 0.0f ? 1.0f / drag : 0.0f; + m_aimer.m_speed = weapon->getExitVelocity(); + const float gravityModifier = weapon->getGravityModifier(); + m_aimer.m_gravity = static_cast( + static_cast(static_cast(CommonSingletonServer::m_iaiPhysics)->getGravity()) * gravityModifier); + + SensedObject* sensed = bot->getSensedObjectFromHandle(m_object); + Vec3 point; + if (!sensed || (sensed->m_flags & 8u)) { + point = target->getPosition(); + } else { + const Mat4& t = target->getTransformation(); + const Vec3& l = sensed->m_seenPosition; + point.x = t.m[8] * l.z + t.m[0] * l.x + t.m[4] * l.y + t.m[12]; + point.y = t.m[1] * l.x + t.m[5] * l.y + t.m[9] * l.z + t.m[13]; + point.z = l.x * t.m[2] + l.y * t.m[6] + l.z * t.m[10] + t.m[14]; + } + IPIMobile* targetMobile = bapinline::info(target->getPrimaryObject(bot->getSide()))->getMobile(); // not null-checked + const Mat4& weaponTransform = weapon->getAbsoluteTransformation(); + const Vec3 rel = bapinline::vec3(point.x - weaponTransform.m[12], point.y - weaponTransform.m[13], + point.z - weaponTransform.m[14]); + Vec3 targetVelocity = bapinline::vec3(0.0f, 0.0f, 0.0f); + Vec3 ownVelocity = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (ownMobile) + ownVelocity = ownMobile->getSpeed(); + if (targetMobile) + targetVelocity = targetMobile->getSpeed(); + m_aimer.setTargetData(rel, targetVelocity, ownVelocity, &weapon->getAbsoluteTransformation(), bapinline::gameTime()); + Vec3 solution = bapinline::vec3(0.0f, 0.0f, 0.0f); + Vec3 solutionTarget = bapinline::vec3(0.0f, 0.0f, 0.0f); + const bool indirect = weapon->getIndirect(); + return m_aimer.getFiringDirection(bapinline::gameTime() + 0.1, 0.5f, indirect, solution, solutionTarget, 0); +} + +// ELF 0x1F0D60 +BAPConditionType BAPConObjectValidAiming::getConditionType() const +{ + return BAPCTObjectValidAiming; // 32 +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidAiming.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidAiming.h new file mode 100644 index 000000000..2b9891a05 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidAiming.h @@ -0,0 +1,47 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTVALIDAIMING_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTVALIDAIMING_H + +#include "../../../../Math/Vec3.h" +#include "BAPConObject.h" +#include "BAPTypes.h" +#include "BAPVariable.h" +#include "Aimer.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B98E8 (5 words), operator new 0x10/0x2C/0x88, package C-actions. +class BAPConObjectValidAiming : public BAPConObject +{ +public: + BAPConObjectValidAiming(unsigned int, BAPVariable*, BAPVariable*, bool); // 0x1F0510 + BAPConObjectValidAiming(unsigned int, unsigned int, BAPVariable*, BAPVariable*, bool); // 0x1F05F0 + virtual ~BAPConObjectValidAiming(); // 0x1F0E20 + + virtual bool evaluate(Bot*); // 0x1F0660, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F0D60, slot +0x04; from the base declaration + + bool internalAiming(Bot*, Vec3&); // 0x1F07E0; ELF bool + + /* +0x0C */ unsigned int m_shooter; // information handle; -1: the bot's equipment + /* +0x10 */ Aimer m_aimer; + /* +0x7C */ BAPVariable* m_aimValid; // with m_aimDirection: taken as the answer + /* +0x80 */ BAPVariable* m_aimDirection; + /* +0x84 */ bool m_trackStaticAttack; // stamp the failed static (sky) attack times +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTVALIDAIMING_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidPitchAiming.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidPitchAiming.cpp new file mode 100644 index 000000000..e9e6c44d5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidPitchAiming.cpp @@ -0,0 +1,58 @@ +// Aiming condition restricted to the camera's pitch range. Recovered from libaidll.so 1.5.3153 +// (ia-32); ELF addresses on every body. + +#include "BAPConObjectValidPitchAiming.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/Information.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1F1110, __tcf_0 0x1F1170, _GLOBAL__I 0x1F11A0). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F0F20 (C1; C2 0x1F0EC0): the bot's own equipment shoots; no static-attack tracking. +BAPConObjectValidPitchAiming::BAPConObjectValidPitchAiming(unsigned int object, BAPVariable* aimValid, + BAPVariable* aimDirection) + : BAPConObjectValidAiming(object, aimValid, aimDirection, false) +{ +} + +// ELF 0x1F0FE0 (C1; C2 0x1F0F80) +BAPConObjectValidPitchAiming::BAPConObjectValidPitchAiming(unsigned int object, unsigned int shooter, BAPVariable* aimValid, + BAPVariable* aimDirection) + : BAPConObjectValidAiming(object, shooter, aimValid, aimDirection, false) +{ +} + +// ELF 0x1F11C0 (weak D1; D0 0x1F1210): the Aimer and the base only. +BAPConObjectValidPitchAiming::~BAPConObjectValidPitchAiming() +{ +} + +// ELF 0x1F1040. The aim must be solvable (internalAiming) and the camera must be able to turn +// to the direction in pitch (IPIControlInfo::validateCameraDirectionPitch on m_shooter's, or the +// bot's, control info; the information is not null-checked). +bool BAPConObjectValidPitchAiming::evaluate(Bot* bot) +{ + Vec3 dir = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (!internalAiming(bot, dir)) + return false; + const unsigned int handle = m_shooter == 0xFFFFFFFFu ? bot->getCurrentEquipment() : m_shooter; + return bapinline::info(handle)->getControlInfo()->validateCameraDirectionPitch(dir); +} + +// ELF 0x1F1100 +BAPConditionType BAPConObjectValidPitchAiming::getConditionType() const +{ + return BAPCTObjectValidAiming; // 32, as the base +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidPitchAiming.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidPitchAiming.h new file mode 100644 index 000000000..1af48e09d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidPitchAiming.h @@ -0,0 +1,37 @@ +// Aiming condition restricted to the camera's pitch range. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTVALIDPITCHAIMING_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTVALIDPITCHAIMING_H + +#include "../../../../Math/Vec3.h" +#include "BAPConObjectValidAiming.h" +#include "BAPTypes.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9948 (5 words), operator new 0x88, package H-deferred. +// No members of its own. +class BAPConObjectValidPitchAiming : public BAPConObjectValidAiming +{ +public: + BAPConObjectValidPitchAiming(unsigned int, BAPVariable*, BAPVariable*); // 0x1F0F20 + BAPConObjectValidPitchAiming(unsigned int, unsigned int, BAPVariable*, BAPVariable*); // 0x1F0FE0 + virtual ~BAPConObjectValidPitchAiming(); // 0x1F11C0 + + virtual bool evaluate(Bot*); // 0x1F1040, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F1100, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTVALIDPITCHAIMING_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidPosition.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidPosition.cpp new file mode 100644 index 000000000..12a91c63c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidPosition.cpp @@ -0,0 +1,57 @@ +// Tests the object's position against the selected vehicle and equipment navigation constraints. + +// static init: ELF 0x1F1520 (__tcf_0 0x1F1580, _GLOBAL__I 0x1F15B0): 's Init object only. +#include + +#include "BAPConObjectValidPosition.h" + +#include "BAPActionInline.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../Main/IAIPathfinding.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F12F0 (C1; C2 0x1F1260) +BAPConObjectValidPosition::BAPConObjectValidPosition(unsigned int object) +{ + m_object = object; + Information* information = bapinline::info(object); + m_vehicle = information->getMobile()->getVehicleNumber(); + m_equipment = information->getUnit()->getEquipmentType(); +} + +// ELF 0x1F13C0 (C1; C2 0x1F1380) +BAPConObjectValidPosition::BAPConObjectValidPosition(unsigned int object, int vehicle, int equipment) + : m_vehicle(vehicle), m_equipment(equipment) +{ + m_object = object; +} + +// ELF 0x1F1420 (D1; D2 0x1F1400, D0 0x1F1440) +BAPConObjectValidPosition::~BAPConObjectValidPosition() +{ +} + +// ELF 0x1F1480 +bool BAPConObjectValidPosition::evaluate(Bot*) +{ + Information* object = bapinline::info(m_object); + if (!object) + return true; + const Vec3& position = object->getPosition(); + return IAIPathfinding::instance->isValidPosition(m_vehicle, m_equipment, position, true); +} + +// ELF 0x1F15D0 +BAPConditionType BAPConObjectValidPosition::getConditionType() const +{ + return BAPCTObjectValidPosition; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidPosition.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidPosition.h new file mode 100644 index 000000000..5a0cf598d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidPosition.h @@ -0,0 +1,35 @@ +// Tests the object's position against the selected vehicle and equipment navigation constraints. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTVALIDPOSITION_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTVALIDPOSITION_H + +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B99A8 (5 words), package H-deferred. +class BAPConObjectValidPosition : public BAPConObject +{ +public: + explicit BAPConObjectValidPosition(unsigned int); // 0x1F12F0 + BAPConObjectValidPosition(unsigned int, int, int); // 0x1F13C0 + virtual ~BAPConObjectValidPosition(); // 0x1F1420 + + virtual bool evaluate(Bot*); // 0x1F1480, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F15D0, slot +0x04; from the base declaration +private: + /* +0x0C */ int m_vehicle; + /* +0x10 */ int m_equipment; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTVALIDPOSITION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidYawAiming.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidYawAiming.cpp new file mode 100644 index 000000000..7adb2fa08 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidYawAiming.cpp @@ -0,0 +1,58 @@ +// Aiming condition restricted to the camera's yaw range. Recovered from libaidll.so 1.5.3153 +// (ia-32); ELF addresses on every body. + +#include "BAPConObjectValidYawAiming.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/Information.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1F1830, __tcf_0 0x1F1890, _GLOBAL__I 0x1F18C0). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F1640 (C1; C2 0x1F15E0): the bot's own equipment shoots; no static-attack tracking. +BAPConObjectValidYawAiming::BAPConObjectValidYawAiming(unsigned int object, BAPVariable* aimValid, + BAPVariable* aimDirection) + : BAPConObjectValidAiming(object, aimValid, aimDirection, false) +{ +} + +// ELF 0x1F1700 (C1; C2 0x1F16A0) +BAPConObjectValidYawAiming::BAPConObjectValidYawAiming(unsigned int object, unsigned int shooter, BAPVariable* aimValid, + BAPVariable* aimDirection) + : BAPConObjectValidAiming(object, shooter, aimValid, aimDirection, false) +{ +} + +// ELF 0x1F18E0 (weak D1; D0 0x1F1930): the Aimer and the base only. +BAPConObjectValidYawAiming::~BAPConObjectValidYawAiming() +{ +} + +// ELF 0x1F1760. The aim must be solvable (internalAiming) and the camera must be able to turn +// to the direction in yaw (IPIControlInfo::validateCameraDirectionYaw on m_shooter's, or the +// bot's, control info; the information is not null-checked). +bool BAPConObjectValidYawAiming::evaluate(Bot* bot) +{ + Vec3 dir = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (!internalAiming(bot, dir)) + return false; + const unsigned int handle = m_shooter == 0xFFFFFFFFu ? bot->getCurrentEquipment() : m_shooter; + return bapinline::info(handle)->getControlInfo()->validateCameraDirectionYaw(dir); +} + +// ELF 0x1F1820 +BAPConditionType BAPConObjectValidYawAiming::getConditionType() const +{ + return BAPCTObjectValidAiming; // 32, as the base +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidYawAiming.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidYawAiming.h new file mode 100644 index 000000000..d7e06c1f3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidYawAiming.h @@ -0,0 +1,37 @@ +// Aiming condition restricted to the camera's yaw range. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTVALIDYAWAIMING_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTVALIDYAWAIMING_H + +#include "../../../../Math/Vec3.h" +#include "BAPConObjectValidAiming.h" +#include "BAPTypes.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9A08 (5 words), operator new 0x88, package H-deferred. +// No members of its own. +class BAPConObjectValidYawAiming : public BAPConObjectValidAiming +{ +public: + BAPConObjectValidYawAiming(unsigned int, BAPVariable*, BAPVariable*); // 0x1F1640 + BAPConObjectValidYawAiming(unsigned int, unsigned int, BAPVariable*, BAPVariable*); // 0x1F1700 + virtual ~BAPConObjectValidYawAiming(); // 0x1F18E0 + + virtual bool evaluate(Bot*); // 0x1F1760, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F1820, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTVALIDYAWAIMING_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectVisible.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectVisible.cpp new file mode 100644 index 000000000..03c163b32 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectVisible.cpp @@ -0,0 +1,48 @@ +// Tests the sensed object's visible flag while excluding indirect sensing. + +// static init: ELF 0x1F1B40 (__tcf_0 0x1F1BA0, _GLOBAL__I 0x1F1BD0): 's Init object only. +#include + +#include "BAPConObjectVisible.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SensedObject.h" +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F19B0 (C1; C2 0x1F1980) +BAPConObjectVisible::BAPConObjectVisible(unsigned int object) +{ + m_object = object; +} + +// ELF 0x1F1A00 (D1; D2 0x1F19E0, D0 0x1F1A20) +BAPConObjectVisible::~BAPConObjectVisible() +{ +} + +// ELF 0x1F1A60 +bool BAPConObjectVisible::evaluate(Bot* bot) +{ + SensedObject* object = bot->getSensedObjectFromHandle(m_object); + return (object->m_flags & 2u) != 0 && (object->m_flags & 8u) == 0; +} + +// ELF 0x1F1AA0 +BAPConditionType BAPConObjectVisible::getConditionType() const +{ + return BAPCTObjectVisible; +} + +// ELF 0x1F1AB0 +void BAPConObjectVisible::operator<<(std::ostream& out) +{ + out << static_cast(getConditionType()) << "(" << m_object << ")"; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectVisible.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectVisible.h new file mode 100644 index 000000000..811727523 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectVisible.h @@ -0,0 +1,33 @@ +// Tests the sensed object's visible flag while excluding indirect sensing. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTVISIBLE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTVISIBLE_H + +#include +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9A40 (6 words), operator new 0xC, package H-deferred. +class BAPConObjectVisible : public BAPConObject +{ +public: + explicit BAPConObjectVisible(unsigned int); // 0x1F19B0 + virtual ~BAPConObjectVisible(); // 0x1F1A00 + + virtual bool evaluate(Bot*); // 0x1F1A60, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F1AA0, slot +0x04; from the base declaration + virtual void operator<<(std::ostream&); // 0x1F1AB0, slot +0x14; [INFERRED] ELF void +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTVISIBLE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOkToThrowGrenade.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOkToThrowGrenade.cpp new file mode 100644 index 000000000..89e3e44ab --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOkToThrowGrenade.cpp @@ -0,0 +1,134 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1E88E0 (__tcf_0 0x1E8940, _GLOBAL__I 0x1E8970): 's Init object only. +#include + +#include "BAPConOkToThrowGrenade.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" +#include "../../../AIInterface/BFKnowledge/BFPhysics.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E7FF0 (C1; C2 0x1E7F90) +BAPConOkToThrowGrenade::BAPConOkToThrowGrenade(unsigned int object, BAPVariable* targetPoint, + BAPVariable* throwDirection) +{ + m_object = object; + m_targetPoint = targetPoint; + m_throwDirection = throwDirection; +} + +// ELF 0x1E8990 (D1; D0 0x1E89E0): the Aimer and the base only. +BAPConOkToThrowGrenade::~BAPConOkToThrowGrenade() +{ +} + +// ELF 0x1E8050. A soldier waits 10 s after a failed static attack; no friendly soldier may stand +// within 7 m of the target point (|dy| < 2.5). The throw is traced from the projectile origin to +// the apex (Aimer::getTurnPointForGrenade, only while the bot simulates artillery; otherwise three +// units along the throw direction), ignoring the bot's object; without a hit on that leg, from the +// apex to the target point, ignoring the target's object (no hit there: ok). A hit 3.5 m or more +// from the target point fails and stamps the failed static (sky) attack time. The bot's +// information and weapon are not null-checked; without the target information: false. +bool BAPConOkToThrowGrenade::evaluate(Bot* bot) +{ + BotMain* main = static_cast(bot); + Information* self = bapinline::info(bot->getCurrentEquipment()); + IPIArmament* armament = self->getArmament(); + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + Information* target = bapinline::info(m_object); + if (!target) + return false; + const double now = bapinline::gameTime(); + if (now - main->getTimeOfLastFailedStaticAttack() < 10.0 && self->isOfType(ITSoldier)) + return false; + + const std::vector& players = + static_cast(CommonSingletonServer::m_iaiPlayerFactory)->getAllPlayers(); + for (unsigned int i = 0; i < players.size(); ++i) { + IAIPlayer* player = players[i]; + if (!player || player->getSide() != bot->getSide()) + continue; + IAIObject* vehicle = player->getCurrentVehicle(); + if (!vehicle) + continue; + Information* info = bapinline::info(vehicle->getInformation(bot->getSide())); + if (info && info->isOfType(ITSoldier) + && std::fabs(info->getPosition().y - m_targetPoint->m_value.y) < 2.5f) { + const Vec3 d = bapinline::sub(m_targetPoint->m_value, info->getPosition()); + if (d.x * d.x + d.y * d.y + d.z * d.z < 49.0f) + return false; + } + } + + bot->getSensedObjectFromHandle(m_object); // answer dropped (0x1E8340) + const float drag = weapon->getDrag(); + m_aimer.m_drag = drag; + m_aimer.m_inverseDrag = drag != 0.0f ? 1.0f / drag : 0.0f; + m_aimer.m_speed = weapon->getExitVelocity(); + const float gravityModifier = weapon->getGravityModifier(); + m_aimer.m_gravity = static_cast( + static_cast(static_cast(CommonSingletonServer::m_iaiPhysics)->getGravity()) * gravityModifier); + const Mat4& origin = weapon->getProjectileOrigin(); + + float apexTime = 0.0f; + Vec3 apex = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (!main->getBotWantsToSimulateArtillery() + || !m_aimer.getTurnPointForGrenade(m_throwDirection->m_value, apex, apexTime)) { + const Vec3& d = m_throwDirection->m_value; + apex = bapinline::vec3(d.x * 3.0f, d.y * 3.0f, d.z * 3.0f); + } else { + apex.y = static_cast((static_cast(weapon->getExitVelocity()) * m_throwDirection->m_value.y * apexTime + + apex.y) * 0.5); + } + const Vec3 from = bapinline::vec3(origin.m[12], origin.m[13], origin.m[14]); + apex = bapinline::vec3(origin.m[12] + apex.x, origin.m[13] + apex.y, origin.m[14] + apex.z); + + Vec3 hit = bapinline::vec3(0.0f, 0.0f, 0.0f); + bool ok = true; + if (bapinline::collideLineIgnoring(from, apex, self->getAIObject(), hit)) { + ok = false; + } else if (bapinline::collideLineIgnoring(apex, m_targetPoint->m_value, target->getAIObject(), hit)) { + ok = false; + } + if (!ok) { + const Vec3 miss = bapinline::sub(m_targetPoint->m_value, hit); + if (12.25f <= miss.x * miss.x + miss.y * miss.y + miss.z * miss.z) { + if (!main->getBotWantsToSimulateArtillery()) { + main->setTimeOfLastFailedStaticAttack(now); + } else { + main->setTimeOfLastFailedStaticSkyAttack(now); + main->setBotIsSimulatingArtillery(false); + } + return false; + } + } + if (main->getBotWantsToSimulateArtillery() && !weapon->getIsThrown()) + main->setBotIsSimulatingArtillery(true); + return true; +} + +// ELF 0x1E88D0 +BAPConditionType BAPConOkToThrowGrenade::getConditionType() const +{ + return BAPCTOkToThrowGrenade; // 56 +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOkToThrowGrenade.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOkToThrowGrenade.h new file mode 100644 index 000000000..e2e14e725 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOkToThrowGrenade.h @@ -0,0 +1,43 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOKTOTHROWGRENADE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOKTOTHROWGRENADE_H + +#include "../../../../Math/Vec3.h" +#include "BAPConObject.h" +#include "BAPTypes.h" +#include "BAPVariable.h" +#include "Aimer.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9308 (5 words), operator new 0x80, package C-actions. +class BAPConOkToThrowGrenade : public BAPConObject +{ +public: + BAPConOkToThrowGrenade(unsigned int, BAPVariable*, BAPVariable*); // 0x1E7FF0 + virtual ~BAPConOkToThrowGrenade(); // 0x1E8990 + + virtual bool evaluate(Bot*); // 0x1E8050, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1E88D0, slot +0x04; from the base declaration + +private: + /* +0x0C */ Aimer m_aimer; // drag/speed/gravity set by evaluate + /* +0x78 */ BAPVariable* m_targetPoint; + /* +0x7C */ BAPVariable* m_throwDirection; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOKTOTHROWGRENADE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOpLessThan.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOpLessThan.h new file mode 100644 index 000000000..361f9d8be --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOpLessThan.h @@ -0,0 +1,62 @@ +// Comparison condition template; only is instantiated (vtable 0x4BBC38, inline in the +// image, emitted in BBPFire2d.cpp). getConditionType 0x24B7E0 returns 55. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOPLESSTHAN_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOPLESSTHAN_H + +#include + +#include "BAPCondition.h" +#include "BAPExpression.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { +namespace ai { + +template +class BAPConOpLessThan : public BAPCondition +{ +public: + // [CHOSEN, not recovered] Constructor spelling for the inline construction at + // ELF 0x246A44..0x246A7E: both optional expressions null, followed by the value pointers. + BAPConOpLessThan(BAPVariable* left, BAPVariable* right) + : m_leftExpression(0), m_left(left), m_rightExpression(0), m_right(right) {} + + // ELF 0x24B790 (). + virtual bool evaluate(Bot*) + { + if (m_leftExpression) + m_leftExpression->unimplementedExpressionSlot2(); + if (m_rightExpression) + m_rightExpression->unimplementedExpressionSlot2(); + return m_left->m_value < m_right->m_value; + } + virtual BAPConditionType getConditionType() const { return BAPCTOpLessThan; } // 0x24B7E0 + // ELF 0x24B7F0 (): streams the cached values without invoking the expressions. + virtual void streamSelf(std::ostream& out) const + { + out << m_left->m_value << " < " << m_right->m_value; + } + // ELF 0x24B850 (D1; D0 0x24B8B0). + virtual ~BAPConOpLessThan() + { + if (m_leftExpression) + delete m_leftExpression; + if (m_rightExpression) + delete m_rightExpression; + } + +private: + // [INFERRED] Operand names; expressions are owned, variables belong to the context. + /* +0x08 */ BAPExpression* m_leftExpression; + /* +0x0C */ BAPVariable* m_left; + /* +0x10 */ BAPExpression* m_rightExpression; + /* +0x14 */ BAPVariable* m_right; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOPLESSTHAN_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOr.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOr.cpp new file mode 100644 index 000000000..dce54867a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOr.cpp @@ -0,0 +1,77 @@ +// BAPConOr: recovered by package A-core from libaidll.so (TU without a FILE symbol, 0x1F4D30..0x1F5410). +// Every body carries its ELF address. + +#include "BAPConOr.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F4D30 (C2; C1 0x1F4EA0). Copies the list and takes ownership of its conditions. +BAPConOr::BAPConOr(std::list& conditions) +{ + m_conditions = conditions; + for (std::list::iterator it = m_conditions.begin(); it != m_conditions.end(); ++it) + (*it)->mpOwner = this; +} + +// ELF 0x1F4F50 (C2; C1 0x1F4FC0). +BAPConOr::BAPConOr() +{ + m_conditions.clear(); +} + +// ELF 0x1F5030 (D2; D1 and D0 follow). Deletes the conditions (slot +0x10); the list itself goes with +// BAPBoleanOp. +BAPConOr::~BAPConOr() +{ + for (std::list::iterator it = m_conditions.begin(); it != m_conditions.end(); ++it) + { + if (*it) + delete *it; + } +} + +// ELF 0x1F5250. +bool BAPConOr::evaluate(Bot* bot) +{ + for (std::list::iterator it = m_conditions.begin(); it != m_conditions.end(); ++it) + { + if ((*it)->evaluate(bot)) + return true; + } + return false; +} + +// ELF 0x1F52C0: no null check. +void BAPConOr::addCondition(BAPCondition* condition) +{ + condition->mpOwner = this; + m_conditions.insert(m_conditions.end(), condition); +} + +// ELF 0x1F5330. +BAPConditionType BAPConOr::getConditionType() const +{ + return BAPCTOr; +} + +// ELF 0x1F5340: "(" c1 " || " c2 ... ")". +void BAPConOr::streamSelf(std::ostream& os) const +{ + os << "("; + std::list::const_iterator it = m_conditions.begin(); + if (it != m_conditions.end()) + { + os << **it; + for (++it; it != m_conditions.end(); ++it) + os << " || " << **it; + } + os << ")"; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOr.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOr.h new file mode 100644 index 000000000..3159667e0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOr.h @@ -0,0 +1,40 @@ +// Recovered by package A-core (docs/macos-ai-behaviour-plan.md) from libaidll.so; the virtual order +// is checked by tools/macos/ai_behaviour_vtables.py. Every body carries its ELF address. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOR_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOR_H + +#include +#include +#include "BAPBoleanOp.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B9EE0 (6 words), operator new 0xC, package A-core. +// True when any condition is (an empty Or is false); stops at the first true. Owns its +// conditions (BAPBoleanOp::m_conditions). sizeof 0xC. +class BAPConOr : public BAPBoleanOp +{ +public: + explicit BAPConOr(std::list&); // 0x1F4EA0 + BAPConOr(); // 0x1F4FC0 + virtual ~BAPConOr(); // 0x1F50E0 + + virtual bool evaluate(Bot*); // 0x1F5250, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F5330, slot +0x04; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1F5340, slot +0x08; from the base declaration + virtual void addCondition(BAPCondition*); // 0x1F52C0, slot +0x14; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOR_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointAt.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointAt.cpp new file mode 100644 index 000000000..84ac2171c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointAt.cpp @@ -0,0 +1,51 @@ +// Compares the bot's forward direction with a normalized object-position-plus-offset vector. + +// static init: ELF 0x1E8DA0 (__tcf_0 0x1E8E00, _GLOBAL__I 0x1E8E30): 's Init object only. +#include + +#include "BAPConPointAt.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E8AA0 (C1; C2 0x1E8A30) +BAPConPointAt::BAPConPointAt(unsigned int object, Vec3& offset, float angle) + : m_object(object), m_cosAngle(std::cos(angle)), m_offset(offset) +{ +} + +// ELF 0x1E8B30 (D1; D2 0x1E8B10, D0 0x1E8B50) +BAPConPointAt::~BAPConPointAt() +{ +} + +// ELF 0x1E8B90 +bool BAPConPointAt::evaluate(Bot* bot) +{ + Information* object = bapinline::info(m_object); + if (!object) + return true; + // shipped defect: the bot's position is never subtracted from this world-space point. + Vec3 direction = bapinline::add(object->getPosition(), m_offset); + bapinline::normalize(direction); + Information* self = bapinline::info(bot->getCurrentEquipment()); + const Mat4& transform = self->getTransformation(); + const Vec3 forward = bapinline::vec3(transform.m[8], transform.m[9], transform.m[10]); + return bapinline::dot(direction, forward) >= m_cosAngle; +} + +// ELF 0x1E8D90 +BAPConditionType BAPConPointAt::getConditionType() const +{ + return BAPCTPointAt; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointAt.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointAt.h new file mode 100644 index 000000000..2311deff9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointAt.h @@ -0,0 +1,36 @@ +// Compares the bot's forward direction with a normalized object-position-plus-offset vector. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONPOINTAT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONPOINTAT_H + +#include "../../../../Math/Vec3.h" +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9340 (5 words), package H-deferred. +class BAPConPointAt : public BAPCondition +{ +public: + BAPConPointAt(unsigned int, Vec3&, float); // 0x1E8AA0 + virtual ~BAPConPointAt(); // 0x1E8B30 + + virtual bool evaluate(Bot*); // 0x1E8B90, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1E8D90, slot +0x04; from the base declaration +private: + /* +0x08 */ unsigned int m_object; + /* +0x0C */ float m_cosAngle; + /* +0x10 */ Vec3 m_offset; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONPOINTAT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointDistance.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointDistance.cpp new file mode 100644 index 000000000..04ef73b4c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointDistance.cpp @@ -0,0 +1,86 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1E9400 (__tcf_0 0x1E9460, _GLOBAL__I 0x1E9490): 's Init object only. +#include + +#include "BAPConPointDistance.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E8ED0 (C1) +BAPConPointDistance::BAPConPointDistance(const Vec3& point, float maxDistance, bool flat) +{ + m_minDistanceSqr = 0.0f; + m_lastDistanceSqr = 0.0f; + m_2d = flat; + m_point = point; + m_maxDistanceSqr = maxDistance * maxDistance; +} + +// ELF 0x1E8FD0 (C1) +BAPConPointDistance::BAPConPointDistance(const Vec3& point, float minDistance, float maxDistance, bool flat) +{ + m_2d = flat; + m_lastDistanceSqr = 0.0f; + m_point = point; + m_maxDistanceSqr = maxDistance * maxDistance; + m_minDistanceSqr = minDistance * minDistance; +} + +// ELF 0x1E9070 (D0 0x1E9090) +BAPConPointDistance::~BAPConPointDistance() +{ +} + +// ELF 0x1E90D0 (the information is not null-checked) +bool BAPConPointDistance::evaluate(Bot* bot) +{ + Information* self = bapinline::info(bot->getCurrentEquipment()); + float a, b; + if (!m_2d) { + const Vec3& p = self->getPosition(); + b = (m_point.z - p.z) * (m_point.z - p.z); + a = (m_point.x - p.x) * (m_point.x - p.x) + (m_point.y - p.y) * (m_point.y - p.y); + } else { + const float px = self->getPosition().x; + const float dz = m_point.z - self->getPosition().z; + a = (m_point.x - px) * (m_point.x - px); + b = dz * dz; + } + const float d = a + b; + m_lastDistanceSqr = d; + return m_minDistanceSqr <= d && d <= m_maxDistanceSqr; +} + +// ELF 0x1E9270 +BAPConditionType BAPConPointDistance::getConditionType() const +{ + return BAPCTPointDistance; // 12 +} + +// ELF 0x1E9280 (the label says "ObjectDistance" in the image) +void BAPConPointDistance::streamSelf(std::ostream& out) const +{ + out << "ObjectDistance["; + if (m_lastDistanceSqr == 0.0f) + out << "not calculated"; + else + out << static_cast(std::sqrt(m_lastDistanceSqr)); + out << "] < " << static_cast(std::sqrt(m_maxDistanceSqr)); + if (m_minDistanceSqr != 0.0f) + out << " && ObjectDistance[" << static_cast(std::sqrt(m_lastDistanceSqr)) << "] > " + << static_cast(std::sqrt(m_minDistanceSqr)); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointDistance.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointDistance.h new file mode 100644 index 000000000..be6adcccd --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointDistance.h @@ -0,0 +1,48 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONPOINTDISTANCE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONPOINTDISTANCE_H + +#include +#include "../../../../Math/Vec3.h" +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9368 (5 words), operator new 0x24, package C-actions. +// min^2 <= d^2 <= max^2 from the bot's current vehicle/soldier to a point (3d, or XZ +// with the flag); the last d^2 is kept for streamSelf. +class BAPConPointDistance : public BAPCondition +{ +public: + BAPConPointDistance(const Vec3&, float, bool); // 0x1E8ED0 + BAPConPointDistance(const Vec3&, float, float, bool); // 0x1E8FD0 + virtual ~BAPConPointDistance(); // 0x1E9070 + + virtual bool evaluate(Bot*); // 0x1E90D0, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1E9270, slot +0x04; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1E9280, slot +0x08; from the base declaration + +private: + /* +0x08 */ float m_minDistanceSqr; // = 0 in the one-distance form + /* +0x0C */ float m_maxDistanceSqr; + /* +0x10 */ bool m_2d; + /* +0x14 */ float m_lastDistanceSqr; // = 0 ("not calculated") + /* +0x18 */ Vec3 m_point; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONPOINTDISTANCE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointInFront.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointInFront.cpp new file mode 100644 index 000000000..ce58ca058 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointInFront.cpp @@ -0,0 +1,56 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// [PLATFORM] precision: the x87 build adds the scaled forward axis to the position in extended +// precision before rounding the point. + +// static init: ELF 0x1E9830 (__tcf_0 0x1E9890, _GLOBAL__I 0x1E98C0): 's Init object only. +#include + +#include "BAPConPointInFront.h" + +#include "../../../../Math/Mat4.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "BAPActionInline.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E9520 (C1; C2 0x1E94B0) +BAPConPointInFront::BAPConPointInFront(const Vec3& point, float distance, float minDot) +{ + m_distance = distance; + m_minDot = minDot; + m_point = point; +} + +// ELF 0x1E95B0 (D1 0x1E9590, D0 0x1E95D0): base only. +BAPConPointInFront::~BAPConPointInFront() +{ +} + +// ELF 0x1E9610. No information on the bot's vehicle: false. +bool BAPConPointInFront::evaluate(Bot* bot) +{ + Information* const self = bapinline::info(bot->getCurrentEquipment()); + if (!self) + return false; + const Mat4& transformation = self->getTransformation(); + const Vec3 forward = bapinline::vec3(transformation.m[8], transformation.m[9], transformation.m[10]); + const Vec3& position = self->getPosition(); + const Vec3 ahead = bapinline::vec3(forward.x * m_distance, forward.y * m_distance, forward.z * m_distance); + const Vec3 front = bapinline::add(position, ahead); + Vec3 direction = bapinline::sub(m_point, front); + bapinline::normalize(direction); + return bapinline::dot(forward, direction) > m_minDot; +} + +// ELF 0x1E9820: ObjectInFront, as shipped. +BAPConditionType BAPConPointInFront::getConditionType() const +{ + return BAPCTObjectInFront; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointInFront.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointInFront.h new file mode 100644 index 000000000..bcc6a7bff --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointInFront.h @@ -0,0 +1,39 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONPOINTINFRONT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONPOINTINFRONT_H + +#include "../../../../Math/Vec3.h" +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9390 (5 words), operator new 0x1C, package G-vehicles. +// BAPConObjectInFront for a fixed point. getConditionType answers ObjectInFront (23), as shipped. +class BAPConPointInFront : public BAPCondition +{ +public: + BAPConPointInFront(const Vec3&, float, float); // 0x1E9520 + virtual ~BAPConPointInFront(); // 0x1E95B0 + + virtual bool evaluate(Bot*); // 0x1E9610, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1E9820, slot +0x04; from the base declaration + +private: + /* +0x08 */ float m_distance; // [INFERRED] names + /* +0x0C */ float m_minDot; + /* +0x10 */ Vec3 m_point; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONPOINTINFRONT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPosition.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPosition.cpp new file mode 100644 index 000000000..78f79f549 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPosition.cpp @@ -0,0 +1,69 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1E9CD0 (__tcf_0 0x1E9D30, _GLOBAL__I 0x1E9D60): 's Init object only. +#include + +#include "BAPConPosition.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E9950 (C1): `new Vec3(point)` (operator new 0xC) at +0x08. +BAPConPosition::BAPConPosition(const Vec3& point, float radius) +{ + setOwner(0); + Vec3* p = new Vec3(point); + m_point = &p->x; + m_is3d = true; + m_radiusSqr = radius * radius; +} + +// ELF 0x1E9A30 (C1): `new Vec2(point)` (operator new 8). +BAPConPosition::BAPConPosition(const Vec2& point, float radius) +{ + setOwner(0); + Vec2* p = new Vec2(point); + m_point = &p->x; + m_is3d = false; + m_radiusSqr = radius * radius; +} + +// ELF 0x1E9AF0 (D0 0x1E9B40): plain operator delete of the point. +BAPConPosition::~BAPConPosition() +{ + ::operator delete(m_point); +} + +// ELF 0x1E9B90: 3d `<=`, 2d (x, z against the Vec2) strict `<`. +bool BAPConPosition::evaluate(Bot* bot) +{ + Information* info = bapinline::info(bot->getCurrentEquipment()); + if (!info) + return true; + if (!m_is3d) { + const Vec3& pos = info->getPosition(); + const float dx = pos.x - m_point[0]; + const float dz = pos.z - m_point[1]; + return dz * dz + dx * dx < m_radiusSqr; + } + const Vec3& pos = info->getPosition(); + const float dx = pos.x - m_point[0]; + const float dy = pos.y - m_point[1]; + const float dz = pos.z - m_point[2]; + return dx * dx + dy * dy + dz * dz <= m_radiusSqr; +} + +// ELF 0x1E9CC0 +BAPConditionType BAPConPosition::getConditionType() const +{ + return BAPCTPosition; // 37 +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPosition.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPosition.h new file mode 100644 index 000000000..17d679060 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPosition.h @@ -0,0 +1,44 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONPOSITION_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONPOSITION_H + +#include "../../../../Math/Vec3.h" +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B93B8 (5 words), operator new 0x8/0x14, package C-actions. +// True while the bot's current vehicle/soldier is within the radius of a point (3d form) or +// of an XZ point (2d form, strictly inside). No information: true. +class BAPConPosition : public BAPCondition +{ +public: + BAPConPosition(const Vec3&, float); // 0x1E9950 + BAPConPosition(const Vec2&, float); // 0x1E9A30 + virtual ~BAPConPosition(); // 0x1E9AF0 + + virtual bool evaluate(Bot*); // 0x1E9B90, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1E9CC0, slot +0x04; from the base declaration + +private: + /* +0x08 */ float* m_point; // new float[3] (Vec3 form) or new float[2] (Vec2 form): a heap Vec3 / Vec2 + /* +0x0C */ float m_radiusSqr; + /* +0x10 */ bool m_is3d; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONPOSITION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSharedCondition.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSharedCondition.cpp new file mode 100644 index 000000000..a87f2fff7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSharedCondition.cpp @@ -0,0 +1,74 @@ +// BAPConSharedCondition: recovered by package A-core from libaidll.so (TU without a FILE symbol, +// 0x1E9D80..0x1EA280). Every body carries its ELF address. + +#include "BAPConSharedCondition.h" + +#include "../AIUtils/checkPointer.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E9D80 (C2; C1 0x1E9DF0). The cell is unchecked `operator new(8)`; no null check on the +// condition. +BAPConSharedCondition::BAPConSharedCondition(BAPCondition* condition) +{ + m_shared = new SharedValue; + m_shared->value = false; + m_shared->references = 1; + m_condition = condition; + condition->mpOwner = this; +} + +// ELF 0x1E9E60 (C2; C1 0x1E9EA0): shares the cell, owns no condition. +BAPConSharedCondition::BAPConSharedCondition(const BAPConSharedCondition& other) + : BAPCondition() + , m_shared(other.m_shared) + , m_condition(0) +{ + ++m_shared->references; +} + +// ELF 0x1E9EE0 (D2; D1 0x1E9F50, D0 0x1E9FC0). +BAPConSharedCondition::~BAPConSharedCondition() +{ + if (m_condition) + delete m_condition; + if (--m_shared->references == 0) + delete m_shared; +} + +// ELF 0x1EA040. +BAPConSharedCondition* BAPConSharedCondition::getNewSharedCondition() const +{ + return checkPointer(new BAPConSharedCondition(*this)); +} + +// ELF 0x1EA190: only the original evaluates; every holder returns the cell. +bool BAPConSharedCondition::evaluate(Bot* bot) +{ + if (m_condition) + m_shared->value = m_condition->evaluate(bot); + return m_shared->value; +} + +// ELF 0x1EA1D0. +BAPConditionType BAPConSharedCondition::getConditionType() const +{ + return BAPCTSharedCondition; +} + +// ELF 0x1EA1E0: "[" condition "][" cell address "]"; a copy prints "[][" address "]". +void BAPConSharedCondition::streamSelf(std::ostream& os) const +{ + if (m_condition) + os << "[" << *m_condition << "][" << static_cast(m_shared) << "]"; + else + os << "[" << "][" << static_cast(m_shared) << "]"; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSharedCondition.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSharedCondition.h new file mode 100644 index 000000000..049b237ce --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSharedCondition.h @@ -0,0 +1,52 @@ +// Recovered by package A-core (docs/macos-ai-behaviour-plan.md) from libaidll.so; the virtual order +// is checked by tools/macos/ai_behaviour_vtables.py. Every body carries its ELF address. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONSHAREDCONDITION_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONSHAREDCONDITION_H + +#include +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B93E0 (5 words), operator new 0x8/0x10, package A-core. +// A condition evaluated once and read by several plan nodes: the original (built with the wrapped +// condition) evaluates it and stores the result in a shared, reference-counted cell; copies +// (getNewSharedCondition) only read the cell. sizeof 0x10. +class BAPConSharedCondition : public BAPCondition +{ +public: + explicit BAPConSharedCondition(BAPCondition*); // 0x1E9DF0 + explicit BAPConSharedCondition(const BAPConSharedCondition&); // 0x1E9EA0 + virtual ~BAPConSharedCondition(); // 0x1E9F50 + + virtual bool evaluate(Bot*); // 0x1EA190, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EA1D0, slot +0x04; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1EA1E0, slot +0x08; from the base declaration + + BAPConSharedCondition* getNewSharedCondition() const; // 0x1EA040: checkPointer(new copy) + +private: + // `operator new(8)` in the constructor 0x1E9D80: {false, 1}. + struct SharedValue + { + bool value; + int references; + }; + + /* +0x08 */ SharedValue* m_shared; + /* +0x0C */ BAPCondition* m_condition; // owned; 0 in copies +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONSHAREDCONDITION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSplashDamage.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSplashDamage.cpp new file mode 100644 index 000000000..e46febe86 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSplashDamage.cpp @@ -0,0 +1,115 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1EA970 (__tcf_0 0x1EA9D0, _GLOBAL__I 0x1EAA00): 's Init object only. +#include + +#include "BAPConSplashDamage.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SensedObject.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" +#include "../../../AIInterface/BFKnowledge/BFPhysics.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1EA2F0 (C1; C2 0x1EA280) +BAPConSplashDamage::BAPConSplashDamage(unsigned int object, BAPVariable* targetPoint, + BAPVariable* variable7C, float radius) +{ + m_object = object; + m_targetPoint = targetPoint; + m_variable7C = variable7C; + m_radiusSqr = radius * radius; +} + +// ELF 0x1EAA20 (D1; D0 0x1EAA70): the Aimer and the base only. +BAPConSplashDamage::~BAPConSplashDamage() +{ +} + +// ELF 0x1EA360. Casts the shot along the weapon's projectile-origin row 2 out to the target's last +// seen position + 5 m, ignoring the bot's own object. True when it hits within the radius of the +// target point and no soldier of the bot's side stands within the radius of the hit (|dy| < 2.5). +// Without the target information or its sensed record: false. Every other false answer stamps +// BotMain::setTimeOfLastFailedSplashDamageAttack(now). The bot's information and its weapon are +// not null-checked. +bool BAPConSplashDamage::evaluate(Bot* bot) +{ + Information* self = bapinline::info(bot->getCurrentEquipment()); + IPIArmament* armament = self->getArmament(); + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + if (!bapinline::info(m_object)) + return false; + SensedObject* sensed = bot->getSensedObjectFromHandle(m_object); + if (!sensed) + return false; + + const float drag = weapon->getDrag(); + m_aimer.m_drag = drag; + m_aimer.m_inverseDrag = drag != 0.0f ? 1.0f / drag : 0.0f; + m_aimer.m_speed = weapon->getExitVelocity(); + const float gravityModifier = weapon->getGravityModifier(); + m_aimer.m_gravity = static_cast( + static_cast(static_cast(CommonSingletonServer::m_iaiPhysics)->getGravity()) * gravityModifier); + + const Mat4& origin = weapon->getProjectileOrigin(); + const Vec3 from = bapinline::vec3(origin.m[12], origin.m[13], origin.m[14]); + const Vec3 d = bapinline::sub(sensed->m_lastSeenPosition, from); + const float reach = std::sqrt(d.z * d.z + d.x * d.x + d.y * d.y) + 5.0f; + const Vec3 to = bapinline::vec3(origin.m[8] * reach + origin.m[12], origin.m[9] * reach + origin.m[13], + reach * origin.m[10] + origin.m[14]); + Vec3 hit = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (bapinline::collideLineIgnoring(from, to, self->getAIObject(), hit)) { + const std::vector& players = + static_cast(CommonSingletonServer::m_iaiPlayerFactory)->getAllPlayers(); + bool friendlyInSplash = false; + for (unsigned int i = 0; i < players.size() && !friendlyInSplash; ++i) { + IAIPlayer* player = players[i]; + if (!player || player->getSide() != bot->getSide()) + continue; + IAIObject* vehicle = player->getCurrentVehicle(); + if (!vehicle) + continue; + Information* info = bapinline::info(vehicle->getInformation(bot->getSide())); + if (info && info->isOfType(ITSoldier) && std::fabs(info->getPosition().y - hit.y) < 2.5f) { + const Vec3& p = info->getPosition(); + if ((hit.z - p.z) * (hit.z - p.z) + (hit.x - p.x) * (hit.x - p.x) + (hit.y - p.y) * (hit.y - p.y) + < m_radiusSqr) + friendlyInSplash = true; + } + } + if (!friendlyInSplash) { + const Vec3& t = m_targetPoint->m_value; + const float dx = t.x - hit.x; + const float dy = t.y - hit.y; + const float dz = t.z - hit.z; + if (dx * dx + dy * dy + dz * dz < m_radiusSqr) + return true; + } + } + static_cast(bot)->setTimeOfLastFailedSplashDamageAttack(bapinline::gameTime()); + return false; +} + +// ELF 0x1EA960 +BAPConditionType BAPConSplashDamage::getConditionType() const +{ + return BAPCTSplashDamage; // 57 +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSplashDamage.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSplashDamage.h new file mode 100644 index 000000000..57c9d216b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSplashDamage.h @@ -0,0 +1,44 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONSPLASHDAMAGE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONSPLASHDAMAGE_H + +#include "../../../../Math/Vec3.h" +#include "BAPConObject.h" +#include "BAPTypes.h" +#include "BAPVariable.h" +#include "Aimer.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9448 (5 words), operator new 0x84, package C-actions. +class BAPConSplashDamage : public BAPConObject +{ +public: + BAPConSplashDamage(unsigned int, BAPVariable*, BAPVariable*, float); // 0x1EA2F0 + virtual ~BAPConSplashDamage(); // 0x1EAA20 + + virtual bool evaluate(Bot*); // 0x1EA360, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EA960, slot +0x04; from the base declaration + +private: + /* +0x0C */ Aimer m_aimer; // only its drag/speed/gravity are set (evaluate) + /* +0x78 */ BAPVariable* m_targetPoint; // the impact must land within the radius of it + /* +0x7C */ BAPVariable* m_variable7C; // [UNRESOLVED] stored, not read by evaluate + /* +0x80 */ float m_radiusSqr; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONSPLASHDAMAGE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConStrategicObjectStatus.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConStrategicObjectStatus.cpp new file mode 100644 index 000000000..ff8a2a6b1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConStrategicObjectStatus.cpp @@ -0,0 +1,49 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1EAC00 (__tcf_0 0x1EAC60, _GLOBAL__I 0x1EAC90): 's Init object only. +#include + +#include "BAPConStrategicObjectStatus.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../AIStrategicEntity/AIStrategicObject.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1EAB00 (C1) +BAPConStrategicObjectStatus::BAPConStrategicObjectStatus(AIStrategicObject* object, int side, bool zero) +{ + m_object = object; + m_side = side; + m_zero = zero; +} + +// ELF 0x1EAB90 (D0 0x1EABB0): base only. +BAPConStrategicObjectStatus::~BAPConStrategicObjectStatus() +{ +} + +// ELF 0x1EAB40: `object->+0x70 + 4 * side` (AIStrategicObject::getStatus(side), 1-based side). +bool BAPConStrategicObjectStatus::evaluate(Bot*) +{ + const int status = static_cast(m_object->getStatus(m_side)); + return m_zero ? status == 0 : status != 0; +} + +// ELF 0x1EABF0 +BAPConditionType BAPConStrategicObjectStatus::getConditionType() const +{ + return BAPCTStrategicObjectStatus; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConStrategicObjectStatus.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConStrategicObjectStatus.h new file mode 100644 index 000000000..53767b5c3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConStrategicObjectStatus.h @@ -0,0 +1,42 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONSTRATEGICOBJECTSTATUS_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONSTRATEGICOBJECTSTATUS_H + +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class AIStrategicObject; +class Bot; + +// ELF: vtable 0x4B9470 (5 words), operator new 0x14, package C-actions. +// A strategic object's status for one side is non-zero (or, with the flag, zero). +class BAPConStrategicObjectStatus : public BAPCondition +{ +public: + BAPConStrategicObjectStatus(AIStrategicObject*, int, bool); // 0x1EAB00 + virtual ~BAPConStrategicObjectStatus(); // 0x1EAB90 + + virtual bool evaluate(Bot*); // 0x1EAB40, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EABF0, slot +0x04; from the base declaration + +private: + /* +0x08 */ AIStrategicObject* m_object; + /* +0x0C */ int m_side; // 1-based + /* +0x10 */ bool m_zero; // true: "status is 0", false: "status is not 0" +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONSTRATEGICOBJECTSTATUS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTime.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTime.cpp new file mode 100644 index 000000000..736933d15 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTime.cpp @@ -0,0 +1,53 @@ +// BAPConTime: recovered by package A-core from libaidll.so (TU without a FILE symbol, +// 0x1EACB0..0x1EAEF0). Every body carries its ELF address. + +#include "BAPConTime.h" + +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1EACB0 (C2; C1 0x1EAD50). The deadline is a double: -1.0f widened, or now + duration. +BAPConTime::BAPConTime(double duration, bool flag19, bool armed, bool fireFirst) +{ + if (fireFirst) + m_deadline = -1.0f; + else + m_deadline = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime() + duration; + m_duration = duration; + m_armed = armed || fireFirst; + m_flag19 = flag19; +} + +// ELF 0x1EADF0 (D2/D1; D0 0x1EAE30): the vptr store only. +BAPConTime::~BAPConTime() +{ +} + +// ELF 0x1EAE70. `now < deadline` is the image's jb after fucomip (unordered: true -> not yet). +bool BAPConTime::evaluate(Bot*) +{ + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (!m_armed) + { + m_armed = true; + m_deadline = now + m_duration; + } + if (now < m_deadline) + return false; + m_armed = false; + return true; +} + +// ELF 0x1EAEE0. +BAPConditionType BAPConTime::getConditionType() const +{ + return BAPCTTime; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTime.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTime.h new file mode 100644 index 000000000..d64cf47d0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTime.h @@ -0,0 +1,43 @@ +// Recovered by package A-core (docs/macos-ai-behaviour-plan.md) from libaidll.so; the virtual order +// is checked by tools/macos/ai_behaviour_vtables.py. Every body carries its ELF address. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONTIME_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONTIME_H + +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9498 (5 words), operator new 0x18/0x1C, package A-core. +// True once the game time (IBFTimer::getGameTime, CommonSingletonServer::m_iBFTimer) reaches the +// deadline; then it re-arms: the next evaluate sets deadline = now + duration. sizeof 0x1C +// (`operator new(0x1C)`; 0x18 at other sites rounds the 0x1A of fields). +class BAPConTime : public BAPCondition +{ +public: + // fireFirst: the first evaluate is already true (deadline -1). armed (or fireFirst): the deadline + // counts from construction; otherwise from the first evaluate. + BAPConTime(double duration, bool flag19, bool armed, bool fireFirst); // 0x1EAD50 + virtual ~BAPConTime(); // 0x1EAE10 + + virtual bool evaluate(Bot*); // 0x1EAE70, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EAEE0, slot +0x04; from the base declaration + +private: + /* +0x08 */ double m_deadline; + /* +0x10 */ double m_duration; + /* +0x18 */ bool m_armed; // [INFERRED] name + /* +0x19 */ bool m_flag19; // first bool argument; no recovered function reads it [UNRESOLVED] meaning +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONTIME_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTotalAmmo.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTotalAmmo.cpp new file mode 100644 index 000000000..e1fd78607 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTotalAmmo.cpp @@ -0,0 +1,63 @@ +// Condition: the object's ammunition, as the product of the fill fractions of its weapons, is at +// most a threshold. Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body +// carries its ELF address. + +#include "BAPConTotalAmmo.h" + +#include "BAPActionInline.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F1C30 (C1; C2 0x1F1BF0): +0x04 = 0 by the base, +0x08 = the object, +0x0C = threshold. +BAPConTotalAmmo::BAPConTotalAmmo(unsigned int object, float threshold) +{ + m_object = object; + m_threshold = threshold; +} + +// ELF 0x1F1E50 (D1; D2 0x1F1E30, D0 0x1F1E70): base only. +BAPConTotalAmmo::~BAPConTotalAmmo() +{ +} + +// ELF 0x1F1C70: false without information. Otherwise the object's weapon list is copied and every +// weapon that exists, is neither of type 1 nor 2, whose WeaponInfo slot +0x10 (getAmmo) is not -1 +// and whose maximum ammunition is not 0 multiplies the total (1 at first) by +// getCurrentAmmo / getMaxAmmo. True when the total is at most the threshold. +bool BAPConTotalAmmo::evaluate(Bot*) +{ + float total = 1.0f; + std::vector weapons; + Information* info = bapinline::info(m_object); + if (!info) + return false; + weapons = info->getArmament()->getWeapons(); + for (unsigned int i = 0; i < weapons.size(); ++i) + { + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (!weapon || weapon->getWeaponType() == 1 || weapon->getWeaponType() == 2 || weapon->getAmmo() == -1 + || weapon->getMaxAmmo() == 0) + continue; + const float current = static_cast(weapon->getCurrentAmmo()); + total *= current / static_cast(weapon->getMaxAmmo()); + } + return m_threshold >= total; +} + +// ELF 0x1F1EB0 +BAPConditionType BAPConTotalAmmo::getConditionType() const +{ + return BAPCTTotalAmmo; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTotalAmmo.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTotalAmmo.h new file mode 100644 index 000000000..44469d6fe --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTotalAmmo.h @@ -0,0 +1,34 @@ +// Condition: the product of the object's ammunition fractions is at most a threshold. Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONTOTALAMMO_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONTOTALAMMO_H + +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9AA8 (5 words), operator new 0x10, package F-infantry. +class BAPConTotalAmmo : public BAPConObject +{ +public: + BAPConTotalAmmo(unsigned int, float); // 0x1F1C30 + virtual ~BAPConTotalAmmo(); // 0x1F1E50 + + virtual bool evaluate(Bot*); // 0x1F1C70, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F1EB0, slot +0x04; from the base declaration + +private: + /* +0x0C */ float m_threshold; // the constructor's float +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONTOTALAMMO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTriggerableActive.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTriggerableActive.cpp new file mode 100644 index 000000000..edf49a8e1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTriggerableActive.cpp @@ -0,0 +1,39 @@ +// Reads the borrowed triggerable's active-state byte without a null guard. + +// static init: ELF 0x1EB000 (__tcf_0 0x1EB060, _GLOBAL__I 0x1EB090): 's Init object only. +#include + +#include "BAPConTriggerableActive.h" + +#include "../../../../Game/Objects/Game/Triggerable.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1EAF20 (C1; C2 0x1EAEF0) +BAPConTriggerableActive::BAPConTriggerableActive(world::Triggerable* triggerable) + : m_triggerable(triggerable) +{ +} + +// ELF 0x1EAF90 (D1; D2 0x1EAF70, D0 0x1EAFB0) +BAPConTriggerableActive::~BAPConTriggerableActive() +{ +} + +// ELF 0x1EAF50 +bool BAPConTriggerableActive::evaluate(Bot*) +{ + return m_triggerable->m_bool16C; +} + +// ELF 0x1EAFF0 +BAPConditionType BAPConTriggerableActive::getConditionType() const +{ + return BAPCTTriggerableActive; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTriggerableActive.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTriggerableActive.h new file mode 100644 index 000000000..c4a6bad89 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTriggerableActive.h @@ -0,0 +1,34 @@ +// Reads the borrowed triggerable's active-state byte without a null guard. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONTRIGGERABLEACTIVE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONTRIGGERABLEACTIVE_H + +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace world { class Triggerable; } +namespace ai { + +class Bot; + +// ELF: vtable 0x4B94E8 (5 words), operator new 0xC/0x2C, package F-infantry. +class BAPConTriggerableActive : public BAPCondition +{ +public: + explicit BAPConTriggerableActive(world::Triggerable*); // 0x1EAF20 + virtual ~BAPConTriggerableActive(); // 0x1EAF90 + + virtual bool evaluate(Bot*); // 0x1EAF50, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EAFF0, slot +0x04; from the base declaration +private: + /* +0x08 */ world::Triggerable* m_triggerable; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONTRIGGERABLEACTIVE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTrue.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTrue.cpp new file mode 100644 index 000000000..c290298a1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTrue.cpp @@ -0,0 +1,34 @@ +// BAPConTrue: recovered by ai-main from libaidll.so (0x1C18A0..0x1C1910; S0 skeleton file). +// Every body carries its ELF address. + +#include "BAPConTrue.h" + +#include "../../../../Math/Vec3.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1C18C0 (D1, D0 0x1C18E0): only the vtable store of the (empty) BAPCondition base +// (GOT -0x1550 + 8); nothing of its own. +BAPConTrue::~BAPConTrue() +{ +} + +// ELF 0x1C18A0: `movl $0x1, %eax; ret`. +bool BAPConTrue::evaluate(Bot*) +{ + return true; +} + +// ELF 0x1C18B0: `movl $0x28, %eax; ret` (40 = BAPCTTrue). +BAPConditionType BAPConTrue::getConditionType() const +{ + return BAPCTTrue; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTrue.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTrue.h new file mode 100644 index 000000000..198a92486 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTrue.h @@ -0,0 +1,35 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONTRUE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONTRUE_H + +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B7500 (5 words), package S0-skeleton. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BAPConTrue : public BAPCondition +{ +public: + virtual ~BAPConTrue(); // 0x1C18C0 + + virtual bool evaluate(Bot*); // 0x1C18A0, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1C18B0, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONTRUE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeapon.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeapon.h new file mode 100644 index 000000000..65ab83840 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeapon.h @@ -0,0 +1,34 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPON_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPON_H + +#include "BAPCondition.h" + +namespace dice { +namespace hfe { + +namespace ai { + + +// ELF: package C-actions. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class WeaponInfo; +template class BAPVariable; + +class BAPConWeapon : public BAPCondition +{ +public: + // Inline in the image (no symbol); every subclass ctor stores the weapon variable at +0x08. + /* +0x08 */ BAPVariable* m_weapon; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPON_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponDetonatorIsActive.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponDetonatorIsActive.cpp new file mode 100644 index 000000000..e1da9d18e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponDetonatorIsActive.cpp @@ -0,0 +1,51 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1F2260 (__tcf_0 0x1F22C0, _GLOBAL__I 0x1F22F0): 's Init object only. +#include + +#include "BAPConWeaponDetonatorIsActive.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F20E0 (C1) +BAPConWeaponDetonatorIsActive::BAPConWeaponDetonatorIsActive(BAPVariable* weapon) +{ + m_weapon = weapon; +} + +// ELF 0x1F2130 (D0 0x1F2150): base only. +BAPConWeaponDetonatorIsActive::~BAPConWeaponDetonatorIsActive() +{ +} + +// ELF 0x1F2190 +bool BAPConWeaponDetonatorIsActive::evaluate(Bot* bot) +{ + IPIArmament* armament = bapinline::info(bot->getCurrentEquipment())->getArmament(); + armament->getWeapon(armament->getActiveWeapon()); + WeaponInfo* active = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + bool result = false; + if (m_weapon->m_value == active) + result = m_weapon->m_value->getWeaponState() == 1; + return result; +} + +// ELF 0x1F2250 +BAPConditionType BAPConWeaponDetonatorIsActive::getConditionType() const +{ + return BAPCTWeaponDetonatorIsActive; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponDetonatorIsActive.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponDetonatorIsActive.h new file mode 100644 index 000000000..3409fac87 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponDetonatorIsActive.h @@ -0,0 +1,38 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONDETONATORISACTIVE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONDETONATORISACTIVE_H + +#include "BAPConWeapon.h" +#include "BAPTypes.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class WeaponInfo; + +// ELF: vtable 0x4B9B08 (5 words), operator new 0xC, package C-actions. +// The variable's weapon is the active one and its weapon state is 1. +class BAPConWeaponDetonatorIsActive : public BAPConWeapon +{ +public: + explicit BAPConWeaponDetonatorIsActive(BAPVariable*); // 0x1F20E0 + virtual ~BAPConWeaponDetonatorIsActive(); // 0x1F2130 + + virtual bool evaluate(Bot*); // 0x1F2190, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F2250, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONDETONATORISACTIVE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHasLockOnTarget.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHasLockOnTarget.cpp new file mode 100644 index 000000000..00a0573a6 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHasLockOnTarget.cpp @@ -0,0 +1,51 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1F24B0 (__tcf_0 0x1F2510, _GLOBAL__I 0x1F2540): 's Init object only. +#include + +#include "BAPConWeaponHasLockOnTarget.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F2350 (C1) +BAPConWeaponHasLockOnTarget::BAPConWeaponHasLockOnTarget(BAPVariable* weapon, unsigned int unused) +{ + m_weapon = weapon; + m_target = unused; +} + +// ELF 0x1F23B0 (D0 0x1F23D0): base only. +BAPConWeaponHasLockOnTarget::~BAPConWeaponHasLockOnTarget() +{ +} + +// ELF 0x1F2410: `getLockedTarget()->getInformation(bot->getSide())` (IAIObject +0xB8) resolves. +bool BAPConWeaponHasLockOnTarget::evaluate(Bot* bot) +{ + IAIObject* target = m_weapon->m_value->getLockedTarget(); + bool result = false; + if (target) + result = bapinline::info(target->getInformation(bot->getSide())) != 0; + return result; +} + +// ELF 0x1F24A0 +BAPConditionType BAPConWeaponHasLockOnTarget::getConditionType() const +{ + return BAPCTWeaponHasLockOnTarget; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHasLockOnTarget.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHasLockOnTarget.h new file mode 100644 index 000000000..cc4276493 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHasLockOnTarget.h @@ -0,0 +1,41 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONHASLOCKONTARGET_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONHASLOCKONTARGET_H + +#include "BAPConWeapon.h" +#include "BAPTypes.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class WeaponInfo; + +// ELF: vtable 0x4B9B68 (5 words), operator new 0xC/0x10, package C-actions. +// The weapon has locked a target whose information for the bot's side exists. +class BAPConWeaponHasLockOnTarget : public BAPConWeapon +{ +public: + BAPConWeaponHasLockOnTarget(BAPVariable*, unsigned int); // 0x1F2350 + virtual ~BAPConWeaponHasLockOnTarget(); // 0x1F23B0 + + virtual bool evaluate(Bot*); // 0x1F2410, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F24A0, slot +0x04; from the base declaration + +private: + /* +0x0C */ unsigned int m_target; // the ctor's second argument; evaluate does not read it // name: AIDLL_r assert in the constructor 0x101CE300 (+0xC) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONHASLOCKONTARGET_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHeat.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHeat.cpp new file mode 100644 index 000000000..c651f73b2 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHeat.cpp @@ -0,0 +1,62 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +#include "BAPConWeaponHeat.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F25A0 (C1): one limit for both. +BAPConWeaponHeat::BAPConWeaponHeat(BAPVariable* weapon, float limit) +{ + m_overheat = limit; + m_cooled = limit; + m_weapon = weapon; + m_overheated = false; +} + +// ELF 0x1F2620 (C1) +BAPConWeaponHeat::BAPConWeaponHeat(BAPVariable* weapon, float overheat, float cooled) +{ + m_weapon = weapon; + m_overheat = overheat; + m_overheated = false; + m_cooled = cooled; +} + +// ELF 0x1F2680 (D0 0x1F26A0) +BAPConWeaponHeat::~BAPConWeaponHeat() +{ +} + +// ELF 0x1F26E0: WeaponInfo::getHeat (+0x24). +bool BAPConWeaponHeat::evaluate(Bot*) +{ + if (!m_overheated) { + if (m_overheat <= m_weapon->m_value->getHeat()) { + m_overheated = true; + return false; + } + } else { + if (m_cooled < m_weapon->m_value->getHeat()) + return false; + m_overheated = false; + } + return true; +} + +// ELF 0x1F2750 +BAPConditionType BAPConWeaponHeat::getConditionType() const +{ + return BAPCTWeaponHeat; // 46 +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHeat.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHeat.h new file mode 100644 index 000000000..795d26681 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHeat.h @@ -0,0 +1,45 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONHEAT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONHEAT_H + +#include "BAPConWeapon.h" +#include "BAPTypes.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class WeaponInfo; + +// ELF: vtable 0x4B9BC8 (5 words), operator new 0x18, package C-actions. +// Heat hysteresis: false once the heat reaches the upper limit, true again once it +// falls to the lower limit. +class BAPConWeaponHeat : public BAPConWeapon +{ +public: + BAPConWeaponHeat(BAPVariable*, float); // 0x1F25A0 + BAPConWeaponHeat(BAPVariable*, float, float); // 0x1F2620 + virtual ~BAPConWeaponHeat(); // 0x1F2680 + + virtual bool evaluate(Bot*); // 0x1F26E0, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F2750, slot +0x04; from the base declaration + +private: + /* +0x0C */ float m_overheat; // becomes "overheated" at heat >= this + /* +0x10 */ float m_cooled; // and recovers at heat <= this + /* +0x14 */ bool m_overheated; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONHEAT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsActive.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsActive.cpp new file mode 100644 index 000000000..5f9ee8e4c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsActive.cpp @@ -0,0 +1,50 @@ +// Condition: the plan's weapon variable holds the bot's active weapon. Recovered from libaidll.so +// (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. + +// static init: ELF 0x1F2900 (__tcf_0 0x1F2960, _GLOBAL__I 0x1F2990): 's Init object only. +#include + +#include "BAPConWeaponIsActive.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F2790 (C1; C2 0x1F2760): +0x04 = 0 by the base, +0x08 = the weapon variable. +BAPConWeaponIsActive::BAPConWeaponIsActive(BAPVariable* weapon) +{ + m_weapon = weapon; +} + +// ELF 0x1F27E0 (D1; D2 0x1F27C0, D0 0x1F2800): base only. +BAPConWeaponIsActive::~BAPConWeaponIsActive() +{ +} + +// ELF 0x1F2840: true when the variable's weapon is the WeaponInfo of the active weapon of the +// bot's current equipment. The equipment information is not null-checked, and the active weapon +// handle is fetched once without use before the compared fetch; as compiled. +bool BAPConWeaponIsActive::evaluate(Bot* bot) +{ + IPIArmament* armament = bapinline::info(bot->getCurrentEquipment())->getArmament(); + armament->getWeapon(armament->getActiveWeapon()); + WeaponInfo* active = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + return m_weapon->m_value == active; +} + +// ELF 0x1F28F0 +BAPConditionType BAPConWeaponIsActive::getConditionType() const +{ + return BAPCTWeaponIsActive; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsActive.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsActive.h new file mode 100644 index 000000000..e571822e7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsActive.h @@ -0,0 +1,33 @@ +// Condition: the plan weapon variable holds the active weapon. Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONISACTIVE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONISACTIVE_H + +#include "BAPConWeapon.h" +#include "BAPTypes.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class WeaponInfo; + +// ELF: vtable 0x4B9C28 (5 words), operator new 0x8/0xC, package F-infantry. +class BAPConWeaponIsActive : public BAPConWeapon +{ +public: + explicit BAPConWeaponIsActive(BAPVariable*); // 0x1F2790 + virtual ~BAPConWeaponIsActive(); // 0x1F27E0 + + virtual bool evaluate(Bot*); // 0x1F2840, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F28F0, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONISACTIVE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsZoomed.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsZoomed.cpp new file mode 100644 index 000000000..0aa557f1f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsZoomed.cpp @@ -0,0 +1,51 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1F2B50 (__tcf_0 0x1F2BB0, _GLOBAL__I 0x1F2BE0): 's Init object only. +#include + +#include "BAPConWeaponIsZoomed.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F29E0 (C1) +BAPConWeaponIsZoomed::BAPConWeaponIsZoomed() +{ + setOwner(0); +} + +// ELF 0x1F2A30 (D0 0x1F2A50) +BAPConWeaponIsZoomed::~BAPConWeaponIsZoomed() +{ +} + +// ELF 0x1F2A90: the active weapon of the bot's current vehicle/soldier. The image calls +// getWeapon(getActiveWeapon()) twice and drops the first result; both calls are kept. The +// information and its armament are not null-checked. +bool BAPConWeaponIsZoomed::evaluate(Bot* bot) +{ + Information* info = bapinline::info(bot->getCurrentEquipment()); + IPIArmament* armament = info->getArmament(); + armament->getWeapon(armament->getActiveWeapon()); + const unsigned int weapon = armament->getWeapon(armament->getActiveWeapon()); + WeaponInfo* weaponInfo = WeaponInfoManager::m_instance->getInformation(weapon); + return weaponInfo ? weaponInfo->isZoomed() : false; +} + +// ELF 0x1F2B40 +BAPConditionType BAPConWeaponIsZoomed::getConditionType() const +{ + return BAPCTWeaponIsZoomed; // 52 +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsZoomed.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsZoomed.h new file mode 100644 index 000000000..caf0dd286 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsZoomed.h @@ -0,0 +1,36 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONISZOOMED_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONISZOOMED_H + +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9C88 (5 words), operator new 0x8/0xC, package C-actions. +// No data (operator new 8). +class BAPConWeaponIsZoomed : public BAPCondition +{ +public: + BAPConWeaponIsZoomed(); // 0x1F29E0 + virtual ~BAPConWeaponIsZoomed(); // 0x1F2A30 + + virtual bool evaluate(Bot*); // 0x1F2A90, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F2B40, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONISZOOMED_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponMagAmmo.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponMagAmmo.cpp new file mode 100644 index 000000000..be4d80ba9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponMagAmmo.cpp @@ -0,0 +1,61 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +#include "BAPConWeaponMagAmmo.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F2C40 (C1) +BAPConWeaponMagAmmo::BAPConWeaponMagAmmo(BAPVariable* weapon, BAPVariable* count, bool notEqual) +{ + m_weapon = weapon; + m_notEqual = notEqual; + m_count = count; +} + +// ELF 0x1F2D80 (D0 0x1F2DA0) +BAPConWeaponMagAmmo::~BAPConWeaponMagAmmo() +{ +} + +// ELF 0x1F2C80. Default form: no mags left counts as true, otherwise shots in mag <= n. The +// flag form: no mags: n != 0; negative mags: false; else shots in mag != n. Every getter call of +// the image is kept. +bool BAPConWeaponMagAmmo::evaluate(Bot*) +{ + WeaponInfo* weapon = m_weapon->m_value; + if (!m_notEqual) { + bool result = false; + if (weapon->getNumberOfMags() >= 0) { + result = true; + if (weapon->getNumberOfMags() != 0) { + result = false; + if (weapon->getShotsInMag(0) >= 0) + result = weapon->getShotsInMag(0) <= m_count->m_value; + } + } + return result; + } + if (weapon->getNumberOfMags() == 0) + return m_count->m_value != 0; + if (weapon->getNumberOfMags() < 0) + return false; + return weapon->getShotsInMag(0) != m_count->m_value; +} + +// ELF 0x1F2DE0 +BAPConditionType BAPConWeaponMagAmmo::getConditionType() const +{ + return BAPCTWeaponMagAmmo; // 41 +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponMagAmmo.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponMagAmmo.h new file mode 100644 index 000000000..f79a6a6dd --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponMagAmmo.h @@ -0,0 +1,42 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONMAGAMMO_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONMAGAMMO_H + +#include "BAPConWeapon.h" +#include "BAPTypes.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class WeaponInfo; + +// ELF: vtable 0x4B9CE8 (5 words), operator new 0x14, package C-actions. +// Magazine test against an int variable (getNumberOfMags +0x18, getShotsInMag(0) +0x0C). +class BAPConWeaponMagAmmo : public BAPConWeapon +{ +public: + BAPConWeaponMagAmmo(BAPVariable*, BAPVariable*, bool); // 0x1F2C40 + virtual ~BAPConWeaponMagAmmo(); // 0x1F2D80 + + virtual bool evaluate(Bot*); // 0x1F2C80, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F2DE0, slot +0x04; from the base declaration + +private: + /* +0x0C */ bool m_notEqual; // the ctor's bool: "shots in mag != n" form; [INFERRED] name + /* +0x10 */ BAPVariable* m_count; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONMAGAMMO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponReadyToFire.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponReadyToFire.cpp new file mode 100644 index 000000000..9813518d0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponReadyToFire.cpp @@ -0,0 +1,52 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1F2F90 (__tcf_0 0x1F2FF0, _GLOBAL__I 0x1F3020): 's Init object only. +#include + +#include "BAPConWeaponReadyToFire.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F2E20 (C1) +BAPConWeaponReadyToFire::BAPConWeaponReadyToFire(BAPVariable* weapon) +{ + m_weapon = weapon; +} + +// ELF 0x1F2E70 (D0 0x1F2E90): base only. +BAPConWeaponReadyToFire::~BAPConWeaponReadyToFire() +{ +} + +// ELF 0x1F2ED0 (getWeapon(getActiveWeapon()) is called twice, the first result dropped). +bool BAPConWeaponReadyToFire::evaluate(Bot* bot) +{ + IPIArmament* armament = bapinline::info(bot->getCurrentEquipment())->getArmament(); + armament->getWeapon(armament->getActiveWeapon()); + WeaponInfo* active = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + bool result = false; + WeaponInfo* weapon = m_weapon->m_value; + if (weapon == active) + result = weapon->isReadyToFire(); + return result; +} + +// ELF 0x1F2F80 +BAPConditionType BAPConWeaponReadyToFire::getConditionType() const +{ + return BAPCTWeaponReadyToFire; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponReadyToFire.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponReadyToFire.h new file mode 100644 index 000000000..6cb0e8d32 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponReadyToFire.h @@ -0,0 +1,38 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONREADYTOFIRE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONREADYTOFIRE_H + +#include "BAPConWeapon.h" +#include "BAPTypes.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class WeaponInfo; + +// ELF: vtable 0x4B9D48 (5 words), operator new 0xC, package C-actions. +// The variable's weapon is the active one of the bot's current vehicle/soldier and is ready to fire. +class BAPConWeaponReadyToFire : public BAPConWeapon +{ +public: + explicit BAPConWeaponReadyToFire(BAPVariable*); // 0x1F2E20 + virtual ~BAPConWeaponReadyToFire(); // 0x1F2E70 + + virtual bool evaluate(Bot*); // 0x1F2ED0, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F2F80, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONREADYTOFIRE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTargetReachable.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTargetReachable.cpp new file mode 100644 index 000000000..5de808512 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTargetReachable.cpp @@ -0,0 +1,98 @@ +// Weapon-target reachability recovered from libaidll.so. +// static init: ELF 0x1F3910 (__tcf_0 0x1F3970, _GLOBAL__I 0x1F39A0): 's Init object only. +#include +#include "BAPConWeaponTargetReachable.h" +#include "BAPActionInline.h" +#include "Aimer.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../../../AIInterface/BFKnowledge/BFPhysics.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F30B0 (C1; C2 0x1F3040) +BAPConWeaponTargetReachable::BAPConWeaponTargetReachable(BAPVariable* position, + BAPVariable* weapon, BAPVariable* target) + : m_target(target), m_position(position) +{ + m_weapon = weapon; + m_aimer = new Aimer; +} + +// ELF 0x1F3180 (D1; D2 0x1F3120, D0 0x1F31E0) +BAPConWeaponTargetReachable::~BAPConWeaponTargetReachable() +{ + delete m_aimer; +} + +// ELF 0x1F3250 +bool BAPConWeaponTargetReachable::evaluate(Bot* bot) +{ + static Vec3 zero = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (!m_weapon || !m_weapon->m_value) + return false; + WeaponInfo* weapon = m_weapon->m_value; + Information* target = bapinline::info(m_target->m_value); + if (!target) + return false; + Information* self = bapinline::info(bot->getCurrentEquipment()); + if (!self) + return false; + IPIMobile* mobile = target->getMobile(); + Vec3 targetPosition = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (mobile) + mobile->getPositionEstimate(targetPosition); + else + targetPosition = target->getPosition(); + Vec3 relative = bapinline::sub(targetPosition, self->getPosition()); + if (!bot->getSensedObjectFromHandle(m_target->m_value)) + return false; + const bool thrown = weapon->getIsThrown(); + weapon->getExplosionRadius(); + const Mat4& origin = weapon->getProjectileOrigin(); + m_aimer->m_speed = weapon->getExitVelocity(); + m_aimer->m_drag = weapon->getDrag(); + m_aimer->m_inverseDrag = m_aimer->m_drag != 0.0f ? 1.0f / m_aimer->m_drag : 0.0f; + const float gravity = static_cast(CommonSingletonServer::m_iaiPhysics)->getGravity(); + m_aimer->m_gravity = weapon->getGravityModifier() * gravity; + if (thrown) { + Vec3 direction = bapinline::vec3(0.0f, 0.0f, 0.0f); + const double time = bapinline::gameTime(); + relative = bapinline::sub(targetPosition, self->getPosition()); + Vec3 shooterVelocity = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_aimer->setTargetData(relative, zero, shooterVelocity, &origin, time); + Vec3 aimPoint = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (!m_aimer->getFiringDirection(time, 0.5f, true, direction, aimPoint, 0)) + return false; + bapinline::normalize(direction); + const float speed = weapon->getExitVelocity(); + direction.x *= speed; + direction.y *= speed; + direction.z *= speed; + const double extreme = m_aimer->getVerticalExtreme(); + const Vec3& position = self->getPosition(); + const float travelTime = static_cast(extreme); + Vec3 trajectory = bapinline::vec3(direction.x * travelTime + position.x, + direction.y * travelTime + position.y, direction.z * travelTime + position.z); + const float acceleration = static_cast(CommonSingletonServer::m_iaiPhysics)->getGravity(); + trajectory.y += acceleration * static_cast(extreme * extreme * 0.5); + (void)trajectory; + } + // shipped defect: the calculated trajectory is discarded and the output is the shooter's position. + m_position->m_value = self->getPosition(); + return true; +} + +// ELF 0x1F3900 +BAPConditionType BAPConWeaponTargetReachable::getConditionType() const +{ + return BAPCTWeaponTargetReachable; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTargetReachable.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTargetReachable.h new file mode 100644 index 000000000..08eaee3e3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTargetReachable.h @@ -0,0 +1,39 @@ +// Weapon/target reachability condition with an owned ballistic aimer and a position output. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONTARGETREACHABLE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONTARGETREACHABLE_H + +#include "../../../../Math/Vec3.h" +#include "BAPConWeapon.h" +#include "BAPTypes.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class Aimer; +class WeaponInfo; + +// ELF: vtable 0x4B9DA8 (5 words), package H-deferred. +class BAPConWeaponTargetReachable : public BAPConWeapon +{ +public: + BAPConWeaponTargetReachable(BAPVariable*, BAPVariable*, BAPVariable*); // 0x1F30B0 + virtual ~BAPConWeaponTargetReachable(); // 0x1F3180 + + virtual bool evaluate(Bot*); // 0x1F3250, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F3900, slot +0x04; from the base declaration +private: + /* +0x0C */ BAPVariable* m_target; + /* +0x10 */ BAPVariable* m_position; + /* +0x14 */ Aimer* m_aimer; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONTARGETREACHABLE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTotalAmmo.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTotalAmmo.cpp new file mode 100644 index 000000000..69b9bc997 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTotalAmmo.cpp @@ -0,0 +1,40 @@ +// Compares current weapon ammunition with a plan variable using != or <=. + +#include "BAPConWeaponTotalAmmo.h" + +#include "../AIKnowledge/WeaponInfo.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F3A00 (C1; C2 0x1F39C0) +BAPConWeaponTotalAmmo::BAPConWeaponTotalAmmo(BAPVariable* weapon, + BAPVariable* ammo, bool notEqual) : m_notEqual(notEqual), m_ammo(ammo) +{ + m_weapon = weapon; +} + +// ELF 0x1F3AA0 (D1; D2 0x1F3A80, D0 0x1F3AC0) +BAPConWeaponTotalAmmo::~BAPConWeaponTotalAmmo() +{ +} + +// ELF 0x1F3A40 +bool BAPConWeaponTotalAmmo::evaluate(Bot*) +{ + const int ammo = m_weapon->m_value->getCurrentAmmo(); + if (m_notEqual) + return ammo != m_ammo->m_value; + return ammo <= m_ammo->m_value; +} + +// ELF 0x1F3B00 +BAPConditionType BAPConWeaponTotalAmmo::getConditionType() const +{ + return BAPCTWeaponTotalAmmo; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTotalAmmo.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTotalAmmo.h new file mode 100644 index 000000000..c97033643 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTotalAmmo.h @@ -0,0 +1,36 @@ +// Compares current weapon ammunition with a plan variable using != or <=. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONTOTALAMMO_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONTOTALAMMO_H + +#include "BAPConWeapon.h" +#include "BAPTypes.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class WeaponInfo; + +// ELF: vtable 0x4B9E08 (5 words), package H-deferred. +class BAPConWeaponTotalAmmo : public BAPConWeapon +{ +public: + BAPConWeaponTotalAmmo(BAPVariable*, BAPVariable*, bool); // 0x1F3A00 + virtual ~BAPConWeaponTotalAmmo(); // 0x1F3AA0 + + virtual bool evaluate(Bot*); // 0x1F3A40, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F3B00, slot +0x04; from the base declaration +private: + /* +0x0C */ bool m_notEqual; + /* +0x10 */ BAPVariable* m_ammo; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONTOTALAMMO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCondition.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCondition.cpp new file mode 100644 index 000000000..5a9893979 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCondition.cpp @@ -0,0 +1,38 @@ +// BAPCondition: recovered by package A-core from libaidll.so (TU BAPCondition.cpp, 0x1F8090..0x1F8210). +// Every body carries its ELF address. + +// static init: ELF 0x1F8100 (__tcf_0 0x1F8160, _GLOBAL__I 0x1F8190): 's Init object only. +#include + +#include "BAPCondition.h" +#include "../Main/AIStreamOperators.h" + + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F81F0 (D1; D0 0x1F81B0): the vptr store only. +BAPCondition::~BAPCondition() +{ +} + +// ELF 0x1F8090: os << getConditionType() (slot +4) with operator<<(ostream&, BAPConditionType) +// 0x3C7AE0 (Main/AIStreamOperators.cpp). No endl. Only plan dumps reach it. +void BAPCondition::streamSelf(std::ostream& os) const +{ + os << getConditionType(); +} + +// ELF 0x1F80D0. +std::ostream& operator<<(std::ostream& os, const BAPCondition& condition) +{ + condition.streamSelf(os); + return os; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCondition.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCondition.h new file mode 100644 index 000000000..bd797a00e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCondition.h @@ -0,0 +1,52 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONDITION_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONDITION_H + +#include +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// Condition base. Vtable 0x4BA1C8: evaluate, getConditionType, streamSelf, D1, D0. +// ELF: vtable 0x4BA1C8 (5 words), package A-core. +class BAPCondition +{ +public: + BAPCondition() : mpOwner(0) {} // inline in the image (BAPConAnd() 0x1F3D30 stores +4 = 0) + + virtual bool evaluate(Bot*) = 0; // no body, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const = 0; // no body, slot +0x04; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1F8090, slot +0x08; from the base declaration + virtual ~BAPCondition(); // 0x1F81F0 slots +0x0C/+0x10 + + // [INFERRED] inline (no symbol): statement constructors store themselves at +0x04 of their + // conditions (BAPALookAtObject 0x1D318B, BAPALookInDir 0x1D3AEB). + void setOwner(void* owner) { mpOwner = owner; } + +protected: + // The owner: BAPFlowCEnd's constructor (0x1E3293) stores the owning statement here, + // BAPBoleanOp::addCondition (BAPConAnd 0x1F40CC) and the list constructors the owning condition. + // Mixed pointee types, so untyped. [INFERRED] name; public like BotScript::mpOwner, because + // statements of other packages store it inline. [CHOSEN] visibility. +public: + /* +0x04 */ void* mpOwner; // name: AIDLL_r asserts 0x101B21C0, 0x101B1340 (+4) +}; + +// ELF 0x1F80D0: condition.streamSelf(os) (slot +8); returns os. +std::ostream& operator<<(std::ostream& os, const BAPCondition& condition); + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONDITION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConnectedCondition.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConnectedCondition.h new file mode 100644 index 000000000..70e4cc004 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConnectedCondition.h @@ -0,0 +1,29 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONNECTEDCONDITION_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONNECTEDCONDITION_H + +#include "BAPCondition.h" + +namespace dice { +namespace hfe { + +namespace ai { + + +// ELF: package C-actions. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BAPConnectedCondition : public BAPCondition +{ +public: +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONNECTEDCONDITION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPExpression.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPExpression.h new file mode 100644 index 000000000..7268ab7aa --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPExpression.h @@ -0,0 +1,31 @@ +// Abstract expression interface used by the otherwise unconstructed expression paths. +// [INFERRED] Header placement beside BAPAEvaluate, whose constructor names this type. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPEXPRESSION_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPEXPRESSION_H + +namespace dice { +namespace hfe { +namespace ai { + +class BAPExpression +{ +public: + // Deletion calls ia-32 +0x04 at ELF 0x1D1E09/0x24B89D/0x24B8A7; + // amd-64 +0x08 at 0x23E32E/0x2A9870/0x2A985E establish the destructor pair. + // Neither image emits a BAPExpression constructor, destructor, vtable or descendant RTTI. + // Declaration only: there is no attested destructor body to implement. + virtual ~BAPExpression(); + + // [CHOSEN, not recovered] Name and void return under the unimplemented-slot exception. + // No vtable exists in either ELF. Calls at ia-32 0x1D1E91/0x24B7CD/0x24B7D7 + // (+0x08), amd-64 0x23E1DB/0x2A97D0/0x2A97C0 (+0x10), pass only this + // (stack / rdi) and discard the result. No expression instance is constructed. + virtual void unimplementedExpressionSlot2() = 0; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCEnd.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCEnd.cpp new file mode 100644 index 000000000..e8d8a8699 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCEnd.cpp @@ -0,0 +1,96 @@ +// BAPFlowCEnd: recovered by package A-core from libaidll.so (TU without a FILE symbol, beside +// BAPFlowCIf.cpp; 0x1E3230..0x1E3550). Every body carries its ELF address. + +#include "BAPFlowCEnd.h" + +#include "BAPCondition.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E3230 (C2; C1 0x1E32A0). +BAPFlowCEnd::BAPFlowCEnd(int patternId, BAPFlowCEnd::EndType type, BAPCondition* condition) + : BAPFlowControl(patternId) + , m_condition(condition) + , m_type(type) +{ + if (condition) + condition->mpOwner = this; +} + +// ELF 0x1E3310 (D2; D1 0x1E3380, D0 0x1E33F0). The condition's deleting destructor is slot +0x10. +BAPFlowCEnd::~BAPFlowCEnd() +{ + if (m_condition) + delete m_condition; +} + +// ELF 0x1E3460; the table is in the header. +bool BAPFlowCEnd::execute(Bot* bot, bool& ok, bool& finished) +{ + switch (static_cast(m_type)) + { + case 0: + if (m_condition == 0 || m_condition->evaluate(bot)) + { + finished = true; + ok = false; + } + else + { + finished = false; + ok = true; + } + break; + case 1: + if (m_condition == 0) + { + finished = true; + ok = false; + } + else + { + finished = m_condition->evaluate(bot); + ok = true; + } + break; + case 2: + if (m_condition == 0) + { + finished = false; + ok = false; + } + else + { + finished = !m_condition->evaluate(bot); + ok = true; + } + break; + default: + break; + } + return true; +} + +// ELF 0x1E3520. +unsigned long long BAPFlowCEnd::getControls() +{ + return 0; +} + +// ELF 0x1E3540. +BAPStatementType BAPFlowCEnd::getId() const +{ + return BAPSTPlanEnd; +} + +// ELF 0x1E3530. +bool BAPFlowCEnd::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCEnd.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCEnd.h new file mode 100644 index 000000000..56e25a0a3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCEnd.h @@ -0,0 +1,46 @@ +// Recovered by package A-core (docs/macos-ai-behaviour-plan.md) from libaidll.so; the virtual order +// is checked by tools/macos/ai_behaviour_vtables.py. Every body carries its ELF address. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPFLOWCEND_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPFLOWCEND_H + +#include "BAPFlowControl.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// Plan end (execute 0x1E3460), by EndType (ok, finished): +// 0: condition true -> (false, true), false -> (true, false); no condition -> (false, true); +// 1: (true, condition); no condition -> (false, true); +// 2: (true, !condition); no condition -> (false, false); +// other values: neither flag is written. Always returns 1. +// The condition is owned. sizeof 0x1C. +// ELF: vtable 0x4B8EC0 (8 words), operator new 0x1C, package A-core. +class BAPFlowCEnd : public BAPFlowControl +{ +public: + enum EndType : int; // [UNRESOLVED] enumerators: values 0, 1, 2 are handled (see above) + BAPFlowCEnd(int patternId, BAPFlowCEnd::EndType type, BAPCondition* condition); // 0x1E32A0 + virtual ~BAPFlowCEnd(); // 0x1E3380 + + virtual bool execute(Bot*, bool&, bool&); // 0x1E3460, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1E3520, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1E3540, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1E3530, slot +0x14; from the base declaration + +private: + /* +0x14 */ BAPCondition* m_condition; // may be 0 + /* +0x18 */ EndType m_type; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPFLOWCEND_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCIf.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCIf.cpp new file mode 100644 index 000000000..e8d15adb9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCIf.cpp @@ -0,0 +1,196 @@ +// BAPFlowCIf: recovered by package A-core from libaidll.so (TU BAPFlowCIf.cpp, 0x1E3550..0x1E3F80). +// Every body carries its ELF address. + +// static init: ELF 0x1E3E20 (__tcf_0 0x1E3E80, _GLOBAL__I 0x1E3EB0): 's Init object only. +#include + +#include "BAPFlowCIf.h" +#include +#include "../Main/IBotManager.h" +#include "../Main/AIStreamOperators.h" + +#include "BAPCondition.h" +#include "../AIBot/BotMain.h" +#include "../AIPlanInterpreter/PlanInterpreter.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E3550 (C2; C1 0x1E35F0). The condition's owner is set unconditionally, the branches' only +// when present. +BAPFlowCIf::BAPFlowCIf(BAPCondition* condition, BAPStatement* trueStatement, BAPStatement* falseStatement, + int patternId, bool reevaluate, bool keepElse) + : BAPFlowControl(patternId) + , m_condition(condition) + , m_trueStatement(trueStatement) + , m_falseStatement(falseStatement) + , m_activeStatement(0) + , m_activeStatementDebug(0) + , m_reevaluate(reevaluate) + , m_keepElse(keepElse) +{ + condition->mpOwner = this; + if (m_trueStatement) + m_trueStatement->mpOwner = this; + if (m_falseStatement) + m_falseStatement->mpOwner = this; +} + +// ELF 0x1E3690 (D2; D1 0x1E3720, D0 0x1E37B0). +BAPFlowCIf::~BAPFlowCIf() +{ + if (m_condition) + delete m_condition; + if (m_trueStatement) + delete m_trueStatement; + if (m_falseStatement) + delete m_falseStatement; +} + +// ELF 0x1E3850 (77 instructions); the rules are in the header. Always returns 1. +bool BAPFlowCIf::execute(Bot* bot, bool& ok, bool& finished) +{ + bool test; + if (!m_reevaluate) + test = (m_activeStatement == 0); + else if (m_keepElse && m_activeStatement == m_falseStatement) + test = (m_activeStatement == 0); + else + test = true; + + if (test) + { + m_activeStatement = m_condition->evaluate(bot) ? m_trueStatement : m_falseStatement; + m_activeStatementDebug = m_activeStatement; + if (m_activeStatement == 0) + { + ok = true; + finished = true; + return true; + } + } + + // BotMain::getPlanInterpreter (non-virtual, 0x18A780) on the Bot*, call at 0x1E38EA. + static_cast(bot)->getPlanInterpreter()->execute(m_activeStatement, bot, ok, finished); + if (finished) + m_activeStatement = 0; + return true; +} + +// ELF 0x1E3950: the union of both branches' controls. +unsigned long long BAPFlowCIf::getControls() +{ + unsigned long long controls = 0; + if (m_trueStatement) + controls = m_trueStatement->getControls(); + if (m_falseStatement) + controls |= m_falseStatement->getControls(); + return controls; +} + +// ELF 0x1E3F70 (emitted after the TU's initialiser). +BAPStatementType BAPFlowCIf::getId() const +{ + return BAPSTIf; +} + +// ELF 0x1E39B0. +bool BAPFlowCIf::hasDefault() +{ + return true; +} + +// ELF 0x1E3A10. +void BAPFlowCIf::debug(BotScriptDebugger::DebugLevel, std::string& text) +{ + if (m_activeStatementDebug == 0) + { + text = "If, now about to test condition..."; + return; + } + const std::string branch(m_activeStatementDebug == m_trueStatement ? "Then" : "Else"); + std::string line = "If, currently executing " + branch; + line.append(" block..."); + text = line; +} + +// ELF 0x1E3B60 (192 instructions). With +0x28 set, a tabulated "/*Force update*/" line first +// ("/*Force update, but freeze false-statement*/" with +0x29). Then tabulate, os << getId() << "(", +// "[true]"/"[false]" when a branch is active (+0x20 == +0x18 picks "[true]"), *condition when set, +// ")" endl; '{', the true branch one tab level deeper when set, '}'; and for a false branch +// (+0x1C) "else", '{', the branch one level deeper, '}', each on its own tabulated line. +void BAPFlowCIf::streamSelf(std::ostream& os) const +{ + IBotManager* const manager = IBotManager::instance; + if (m_reevaluate) + { + manager->tabulate(os); + os << (m_keepElse ? "/*Force update, but freeze false-statement*/" : "/*Force update*/") << std::endl; + } + manager->tabulate(os); + os << getId() << "("; + if (m_activeStatement) + os << (m_activeStatement == m_trueStatement ? "[true]" : "[false]"); + if (m_condition) + os << *m_condition; + os << ")" << std::endl; + manager->tabulate(os); + os << '{' << std::endl; + if (m_trueStatement) + { + manager->increaseTabLevel(); + os << *m_trueStatement; + manager->decreaseTabLevel(); + } + manager->tabulate(os); + os << '}' << std::endl; + if (m_falseStatement) + { + manager->tabulate(os); + os << "else" << std::endl; + manager->tabulate(os); + os << '{' << std::endl; + manager->increaseTabLevel(); + os << *m_falseStatement; + manager->decreaseTabLevel(); + manager->tabulate(os); + os << '}' << std::endl; + } +} + +// ELF 0x1E39C0. +BAPCondition* BAPFlowCIf::getCondition() const +{ + return m_condition; +} + +// ELF 0x1E39D0. +BAPStatement* BAPFlowCIf::getTrueStatement() const +{ + return m_trueStatement; +} + +// ELF 0x1E39E0. +BAPStatement* BAPFlowCIf::getFalseStatement() const +{ + return m_falseStatement; +} + +// ELF 0x1E39F0. +BAPStatement* BAPFlowCIf::getActiveStatement() const +{ + return m_activeStatement; +} + +// ELF 0x1E3A00. +BAPStatement* BAPFlowCIf::getActiveStatementDebug() const +{ + return m_activeStatementDebug; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCIf.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCIf.h new file mode 100644 index 000000000..96ca2500b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCIf.h @@ -0,0 +1,63 @@ +// Recovered by package A-core (docs/macos-ai-behaviour-plan.md) from libaidll.so; the virtual order +// is checked by tools/macos/ai_behaviour_vtables.py. Every body carries its ELF address. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPFLOWCIF_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPFLOWCIF_H + +#include +#include +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "BAPFlowControl.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class BAPStatement; +class Bot; + +// If (execute 0x1E3850). Without reevaluate the condition is tested once, the chosen branch then +// runs until it reports finished, after which the next tick tests again. With reevaluate the +// condition is tested every tick (the branch may switch), except that with keepElse a running +// else-branch is kept until it finishes. A missing branch: ok = finished = true. The branch's +// finished drops it (the next tick tests again). Both branches and the condition are owned. +// sizeof 0x2C. +// ELF: vtable 0x4B8F40 (8 words), operator new 0x2C, package A-core. +class BAPFlowCIf : public BAPFlowControl +{ +public: + BAPFlowCIf(BAPCondition* condition, BAPStatement* trueStatement, BAPStatement* falseStatement, int patternId, + bool reevaluate, bool keepElse); // 0x1E35F0 + virtual ~BAPFlowCIf(); // 0x1E3720 + + virtual bool execute(Bot*, bool&, bool&); // 0x1E3850, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1E3950, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1E3F70, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1E39B0, slot +0x14; from the base declaration + virtual void debug(BotScriptDebugger::DebugLevel, std::string&); // 0x1E3A10, slot +0x18; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1E3B60, slot +0x1C; from the base declaration + + BAPCondition* getCondition() const; // 0x1E39C0: +0x14 + BAPStatement* getTrueStatement() const; // 0x1E39D0: +0x18 + BAPStatement* getFalseStatement() const; // 0x1E39E0: +0x1C + BAPStatement* getActiveStatement() const; // 0x1E39F0: +0x20 + BAPStatement* getActiveStatementDebug() const; // 0x1E3A00: +0x24 + +private: + /* +0x14 */ BAPCondition* m_condition; + /* +0x18 */ BAPStatement* m_trueStatement; + /* +0x1C */ BAPStatement* m_falseStatement; + /* +0x20 */ BAPStatement* m_activeStatement; // 0 = test the condition next tick + /* +0x24 */ BAPStatement* m_activeStatementDebug; // last chosen branch, kept for debug()/streamSelf + /* +0x28 */ bool m_reevaluate; // [INFERRED] name + /* +0x29 */ bool m_keepElse; // [INFERRED] name +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPFLOWCIF_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWait.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWait.cpp new file mode 100644 index 000000000..f4b082422 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWait.cpp @@ -0,0 +1,55 @@ +// BAPFlowCWait: recovered by package A-core from libaidll.so (TU without a FILE symbol, beside +// BAPFlowCIf.cpp; 0x1E3F80..0x1E4200). Every body carries its ELF address. + +#include "BAPFlowCWait.h" + +#include "BAPCondition.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E3F80 (C2; C1 0x1E3FF0). The condition's owner is set unconditionally. +BAPFlowCWait::BAPFlowCWait(BAPCondition* condition, int patternId) + : BAPFlowControl(patternId) + , m_condition(condition) +{ + condition->mpOwner = this; +} + +// ELF 0x1E4060 (D2; D1 0x1E40C0, D0 0x1E4120). +BAPFlowCWait::~BAPFlowCWait() +{ + if (m_condition) + delete m_condition; +} + +// ELF 0x1E4190. +bool BAPFlowCWait::execute(Bot* bot, bool& ok, bool& finished) +{ + finished = m_condition->evaluate(bot); + ok = true; + return true; +} + +// ELF 0x1E41D0. +unsigned long long BAPFlowCWait::getControls() +{ + return 0; +} + +// ELF 0x1E41F0. +BAPStatementType BAPFlowCWait::getId() const +{ + return BAPSTWait; +} + +// ELF 0x1E41E0. +bool BAPFlowCWait::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWait.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWait.h new file mode 100644 index 000000000..3021bb9e2 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWait.h @@ -0,0 +1,39 @@ +// Recovered by package A-core (docs/macos-ai-behaviour-plan.md) from libaidll.so; the virtual order +// is checked by tools/macos/ai_behaviour_vtables.py. Every body carries its ELF address. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPFLOWCWAIT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPFLOWCWAIT_H + +#include "BAPFlowControl.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// Wait (execute 0x1E4190): ok = true, finished = condition. The condition is owned. sizeof 0x18. +// ELF: vtable 0x4B8F80 (8 words), package A-core. +class BAPFlowCWait : public BAPFlowControl +{ +public: + BAPFlowCWait(BAPCondition* condition, int patternId); // 0x1E3FF0 + virtual ~BAPFlowCWait(); // 0x1E40C0 + + virtual bool execute(Bot*, bool&, bool&); // 0x1E4190, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1E41D0, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1E41F0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1E41E0, slot +0x14; from the base declaration + +private: + /* +0x14 */ BAPCondition* m_condition; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPFLOWCWAIT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWhile.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWhile.cpp new file mode 100644 index 000000000..4f5c88449 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWhile.cpp @@ -0,0 +1,155 @@ +// BAPFlowCWhile: recovered by package A-core from libaidll.so (TU BAPFlowCWhile.cpp, +// 0x1E4200..0x1E4910). Every body carries its ELF address. + +// static init: ELF 0x1E4850 (__tcf_0 0x1E48B0, _GLOBAL__I 0x1E48E0): 's Init object only. +#include + +#include "BAPFlowCWhile.h" +#include +#include "../Main/IBotManager.h" +#include "../Main/AIStreamOperators.h" + +#include "BAPCondition.h" +#include "../AIBot/BotMain.h" +#include "../AIPlanInterpreter/PlanInterpreter.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E4200 (C2; C1 0x1E4280). The condition's owner is set unconditionally, the body's only +// when present. +BAPFlowCWhile::BAPFlowCWhile(BAPCondition* condition, BAPStatement* loopStatement, int patternId) + : BAPFlowControl(patternId) + , m_condition(condition) + , m_loopStatement(loopStatement) + , m_break(false) + , m_testCondition(true) + , m_testOnFinish(true) +{ + condition->mpOwner = this; + if (m_loopStatement) + m_loopStatement->mpOwner = this; +} + +// ELF 0x1E4300 (C2; C1 0x1E4390). +BAPFlowCWhile::BAPFlowCWhile(BAPCondition* condition, BAPStatement* loopStatement, bool testOnFinish, + int patternId) + : BAPFlowControl(patternId) + , m_condition(condition) + , m_loopStatement(loopStatement) + , m_break(false) + , m_testCondition(true) + , m_testOnFinish(testOnFinish) +{ + condition->mpOwner = this; + if (m_loopStatement) + m_loopStatement->mpOwner = this; +} + +// ELF 0x1E4420 (D2; D1 0x1E4490, D0 0x1E4500). +BAPFlowCWhile::~BAPFlowCWhile() +{ + if (m_condition) + delete m_condition; + if (m_loopStatement) + delete m_loopStatement; +} + +// ELF 0x1E4580 (82 instructions); the rules are in the header. Always returns 1. +bool BAPFlowCWhile::execute(Bot* bot, bool& ok, bool& finished) +{ + if (m_loopStatement == 0) + { + ok = true; + m_break = false; + finished = !m_condition->evaluate(bot); + return true; + } + + if (m_break) + { + ok = true; + finished = true; + m_break = false; + return true; + } + + if (m_testCondition && !m_condition->evaluate(bot)) + { + ok = true; + finished = true; + return true; + } + + // BotMain::getPlanInterpreter (non-virtual, 0x18A780) on the Bot*, call at 0x1E4616. + static_cast(bot)->getPlanInterpreter()->execute(m_loopStatement, bot, ok, finished); + if (m_testOnFinish) + m_testCondition = finished; + else + m_testCondition = true; + finished = false; + return true; +} + +// ELF 0x1E4690. +unsigned long long BAPFlowCWhile::getControls() +{ + if (m_loopStatement == 0) + return 0; + return m_loopStatement->getControls(); +} + +// ELF 0x1E4900 (emitted after the TU's initialiser). +BAPStatementType BAPFlowCWhile::getId() const +{ + return BAPSTWhile; +} + +// ELF 0x1E46C0. +bool BAPFlowCWhile::hasDefault() +{ + return true; +} + +// ELF 0x1E4700 (97 instructions): tabulate, os << getId() << "(" << *condition << ")" << endl (the +// condition is not null-checked), then '{', the body one tab level deeper when there is one +// (+0x18, 0x1E47CA), and '}', each on its own tabulated line. +void BAPFlowCWhile::streamSelf(std::ostream& os) const +{ + IBotManager* const manager = IBotManager::instance; + manager->tabulate(os); + os << getId() << "(" << *m_condition << ")" << std::endl; + manager->tabulate(os); + os << '{' << std::endl; + if (m_loopStatement) + { + manager->increaseTabLevel(); + os << *m_loopStatement; + manager->decreaseTabLevel(); + } + manager->tabulate(os); + os << '}' << std::endl; +} + +// ELF 0x1E46D0. +void BAPFlowCWhile::breakLoop() +{ + m_break = true; +} + +// ELF 0x1E46E0. +BAPCondition* BAPFlowCWhile::getCondition() +{ + return m_condition; +} + +// ELF 0x1E46F0. +BAPStatement* BAPFlowCWhile::getLoopStatement() +{ + return m_loopStatement; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWhile.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWhile.h new file mode 100644 index 000000000..9054bb261 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWhile.h @@ -0,0 +1,55 @@ +// Recovered by package A-core (docs/macos-ai-behaviour-plan.md) from libaidll.so; the virtual order +// is checked by tools/macos/ai_behaviour_vtables.py. Every body carries its ELF address. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPFLOWCWHILE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPFLOWCWHILE_H + +#include +#include "BAPFlowControl.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class BAPStatement; +class Bot; + +// While (execute 0x1E4580). Without a loop statement it reports ok and finished = !condition. +// Otherwise: breakLoop() ends it on the next tick (ok, finished); the condition is tested only +// when m_testCondition is set (always, or with testOnFinish only after the body reported +// finished) and a false condition ends it (ok, finished); else the body runs and the while itself +// reports not finished. Condition and body are owned. sizeof 0x20. +// ELF: vtable 0x4B9000 (8 words), operator new 0x8/0x20, package A-core. +class BAPFlowCWhile : public BAPFlowControl +{ +public: + BAPFlowCWhile(BAPCondition* condition, BAPStatement* loopStatement, int patternId); // 0x1E4280 + BAPFlowCWhile(BAPCondition* condition, BAPStatement* loopStatement, bool testOnFinish, int patternId); // 0x1E4390 + virtual ~BAPFlowCWhile(); // 0x1E4490 + + virtual bool execute(Bot*, bool&, bool&); // 0x1E4580, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1E4690, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1E4900, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1E46C0, slot +0x14; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1E4700, slot +0x1C; from the base declaration + + void breakLoop(); // 0x1E46D0: +0x1C = 1 + BAPCondition* getCondition(); // 0x1E46E0: +0x14 + BAPStatement* getLoopStatement(); // 0x1E46F0: +0x18 + +private: + /* +0x14 */ BAPCondition* m_condition; + /* +0x18 */ BAPStatement* m_loopStatement; + /* +0x1C */ bool m_break; // = false + /* +0x1D */ bool m_testCondition; // = true [INFERRED] name + /* +0x1E */ bool m_testOnFinish; // = true, or the bool argument [INFERRED] name +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPFLOWCWHILE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowControl.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowControl.h new file mode 100644 index 000000000..64917c3eb --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowControl.h @@ -0,0 +1,29 @@ +// Recovered by package A-core (docs/macos-ai-behaviour-plan.md) from libaidll.so; the virtual order +// is checked by tools/macos/ai_behaviour_vtables.py. Every body carries its ELF address. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPFLOWCONTROL_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPFLOWCONTROL_H + +#include "BAPStatement.h" + +namespace dice { +namespace hfe { + +namespace ai { + + +// Base of If/While/Wait/End: typeinfo only in the image (no vtable, no data; the derived +// constructors go straight from the BAPStatement vptr to their own). +// ELF: package A-core. +class BAPFlowControl : public BAPStatement +{ +protected: + BAPFlowControl() {} + explicit BAPFlowControl(int patternId) : BAPStatement(patternId) {} +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPFLOWCONTROL_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPICChangeVehicle.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPICChangeVehicle.cpp new file mode 100644 index 000000000..8702d7f63 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPICChangeVehicle.cpp @@ -0,0 +1,48 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1F8540 (__tcf_0 0x1F85A0, _GLOBAL__I 0x1F85D0): 's Init object only. +#include + +#include "BAPICChangeVehicle.h" + +#include "../AIBot/BotMain.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F8490 (C1; C2 0x1F8440): +4/+8/+0xC = 0, +0x14 = the handle (+0x10 is not written). +BAPICChangeVehicle::BAPICChangeVehicle(unsigned int target) +{ + m_target = target; +} + +// ELF 0x1F85F0 (D0 0x1F8630): the inlined ~BAPStatement only. +BAPICChangeVehicle::~BAPICChangeVehicle() +{ +} + +// ELF 0x1F84E0: Bot vfn +0x1B8 (setChangeTarget) with +0x14; ok = finished = true. +bool BAPICChangeVehicle::execute(Bot* bot, bool& ok, bool& finished) +{ + bot->setChangeTarget(m_target); + ok = true; + finished = true; + return true; +} + +// ELF 0x1F8520 +BAPStatementType BAPICChangeVehicle::getId() const +{ + return BAPSTICChangeVehicle; // 29 +} + +// ELF 0x1F8530 +bool BAPICChangeVehicle::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPICChangeVehicle.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPICChangeVehicle.h new file mode 100644 index 000000000..93353e994 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPICChangeVehicle.h @@ -0,0 +1,37 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPICCHANGEVEHICLE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPICCHANGEVEHICLE_H + +#include "BAPInterruptControl.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4BA280 (8 words), operator new 0x18, package F-infantry. +// Interrupt control: hands the vehicle/seat handle to the bot (Bot::setChangeTarget, +0x1B8). +class BAPICChangeVehicle : public BAPInterruptControl +{ +public: + explicit BAPICChangeVehicle(unsigned int); // 0x1F8490 + virtual ~BAPICChangeVehicle(); // 0x1F85F0 + + virtual bool execute(Bot*, bool&, bool&); // 0x1F84E0, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1F8520, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1F8530, slot +0x14; from the base declaration + +private: + /* +0x14 */ unsigned int m_target; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPICCHANGEVEHICLE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPICTurnLock.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPICTurnLock.cpp new file mode 100644 index 000000000..0a488a2c0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPICTurnLock.cpp @@ -0,0 +1,48 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1F8850 (__tcf_0 0x1F88B0, _GLOBAL__I 0x1F88E0): 's Init object only. +#include + +#include "BAPICTurnLock.h" + +#include "../AIBot/BotMain.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F86D0 (C1): base only, +0x10 untouched in the image (the shared base ctor zeroes it). +BAPICTurnLock::BAPICTurnLock(bool lock) +{ + m_lock = lock; +} + +// ELF 0x1F8760 (D0 0x1F87A0) +BAPICTurnLock::~BAPICTurnLock() +{ +} + +// ELF 0x1F87F0 +bool BAPICTurnLock::execute(Bot* bot, bool& ok, bool& failed) +{ + bot->setPlanLock(m_lock); + ok = true; + failed = true; + return true; +} + +// ELF 0x1F8830 +BAPStatementType BAPICTurnLock::getId() const +{ + return BAPSTICTurnLock; // 31 +} + +// ELF 0x1F8840 +bool BAPICTurnLock::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPICTurnLock.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPICTurnLock.h new file mode 100644 index 000000000..e4412b4df --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPICTurnLock.h @@ -0,0 +1,40 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPICTURNLOCK_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPICTURNLOCK_H + +#include "BAPInterruptControl.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4BA2C0 (8 words), operator new 0x18, package C-actions. +// Sets the bot's plan lock (Bot::setPlanLock, +0x6C). +class BAPICTurnLock : public BAPInterruptControl +{ +public: + explicit BAPICTurnLock(bool); // 0x1F86D0 + virtual ~BAPICTurnLock(); // 0x1F8760 + + virtual bool execute(Bot*, bool&, bool&); // 0x1F87F0, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1F8830, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1F8840, slot +0x14; from the base declaration + +private: + /* +0x14 */ bool m_lock; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPICTURNLOCK_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWChange.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWChange.cpp new file mode 100644 index 000000000..d9846d1b7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWChange.cpp @@ -0,0 +1,92 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1F6920 (__tcf_0 0x1F6980, _GLOBAL__I 0x1F69B0): 's Init object only. +#include + +#include "BAPIWChange.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/CommunicationAgent.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../Main/IBotManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F5A80 (C1; C2 0x1F59E0): BAPInfoWrapper(statement, patternId), +0x18 handle, +0x1C player id, +// then Information::bookVehicle(player id) on the handle's information (no null test), child +4 = this. +BAPIWChange::BAPIWChange(unsigned int target, BAPStatement* statement, int patternId, int playerId) + : BAPInfoWrapper(statement, patternId) +{ + m_target = target; + m_playerId = playerId; + bapinline::info(target)->bookVehicle(playerId); + m_statement->mpOwner = this; +} + +// ELF 0x1F5FC0 (D1; D2 0x1F5B20, D0 0x1F6470). Cancels the booking; then, when the plan's bot +// (IBotManager::getBotFromPlayerId, +0x1C, no null test) now sits in the target: "requested" when the +// target's primary or one of its secondary seats has a player (getPlayerId >= 0) who sent message +// type 1 (receivedMessageExists) and the bot's primary is that primary; "seatsFree" starts as +// "the bot is not in the primary seat, the primary's unit is occupied, same primary" and stays set +// while no secondary seat is booked. The seat loop leaves as soon as requested && !seatsFree. +// Afterwards: seatsFree -> enqueueRadioMessage(11, 7, 3, 1.0f, -1), else requested -> (8, 7, 3, 1.0f, -1). +// Finally the child is deleted (vfn +8) and the base destructor runs. +BAPIWChange::~BAPIWChange() +{ + Information* target = bapinline::info(m_target); + if (target && target->isBooked()) + target->cancelBookVehicle(); + + Bot* bot = IBotManager::instance->getBotFromPlayerId(m_playerId); + CommunicationAgent* communication = bot->getCommunicationAgent(); + Information* equipment = bapinline::info(bot->getCurrentEquipment()); + if (target && equipment && m_target == bot->getCurrentEquipment()) { + bool requested = false; + Information* primary = bapinline::info(target->getPrimaryObject(bot->getSide())); + Information* equipmentPrimary = bapinline::info(equipment->getPrimaryObject(bot->getSide())); + int playerId = primary->getPlayerId(); + if (playerId >= 0 && communication->receivedMessageExists(static_cast(1), playerId) + && equipmentPrimary == primary) + requested = true; + bool seatsFree = false; + if (!equipment->isPrimary() && primary->getUnit()->isOccupied() && equipmentPrimary == primary) + seatsFree = true; + + int iterator; + Information* seat = bapinline::info(primary->getFirstSecondaryObject(iterator, bot->getSide())); + while (seat) { + playerId = seat->getPlayerId(); + if (playerId >= 0 && communication->receivedMessageExists(static_cast(1), playerId) + && equipmentPrimary == primary) + requested = true; + seatsFree = seatsFree && !seat->isBooked(); + if (requested && !seatsFree) + break; + seat = bapinline::info(primary->getSecondaryObject(iterator, bot->getSide())); + } + + if (seatsFree) + communication->enqueueRadioMessage(static_cast(11), static_cast(7), + 3, 1.0f, -1); + else if (requested) + communication->enqueueRadioMessage(static_cast(8), static_cast(7), + 3, 1.0f, -1); + } + + if (m_statement) + delete m_statement; +} + +// ELF 0x1F69D0: "Change" in infoTypes. +int BAPIWChange::getInfoType() const +{ + return 8; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWChange.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWChange.h new file mode 100644 index 000000000..18538e421 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWChange.h @@ -0,0 +1,38 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWCHANGE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWCHANGE_H + +#include "BAPInfoWrapper.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPStatement; + +// ELF: vtable 0x4B9FE0 (9 words), package F-infantry. +// Info wrapper of type "Change" (8): books the target vehicle/seat for the player while the plan +// lives; the destructor cancels the booking and radios the pickup result (messages 11 / 8). +class BAPIWChange : public BAPInfoWrapper +{ +public: + BAPIWChange(unsigned int, BAPStatement*, int, int); // 0x1F5A80 + virtual ~BAPIWChange(); // 0x1F5FC0 + + virtual int getInfoType() const; // 0x1F69D0, slot +0x20; from the base declaration + + unsigned int getTarget() const { return m_target; } // [CHOSEN] inline reader: BBPChange::createPlan reads +0x18 + +private: + /* +0x18 */ unsigned int m_target; // vehicle/seat information handle + /* +0x1C */ int m_playerId; // Bot::getPlayerId of the plan's bot +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWCHANGE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWDefuseMines.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWDefuseMines.cpp new file mode 100644 index 000000000..2035c011d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWDefuseMines.cpp @@ -0,0 +1,39 @@ +// Owns a mine-defusing plan and brackets its lifetime with the bot's firing/mine-target state. + +// static init: ELF 0x1F6C90 (__tcf_0 0x1F6CF0, _GLOBAL__I 0x1F6D20): 's Init object only. +#include + +#include "BAPIWDefuseMines.h" + +#include "../AIBot/BotMain.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F6A70 (C1; C2 0x1F69E0) +BAPIWDefuseMines::BAPIWDefuseMines(Bot* bot, unsigned int mine, BAPStatement* statement, int tag) + : BAPInfoWrapper(statement, tag), m_mine(mine), m_bot(bot) +{ + m_statement->setParent(this); + bot->setIsFiring(true); + static_cast(m_bot)->setMineTarget(mine); +} + +// ELF 0x1F6B80 (D1; D2 0x1F6B00, D0 0x1F6C00) +BAPIWDefuseMines::~BAPIWDefuseMines() +{ + delete m_statement; + m_bot->setIsFiring(false); + static_cast(m_bot)->setMineTarget(0xFFFFFFFFu); +} + +// ELF 0x1F6D40 +int BAPIWDefuseMines::getInfoType() const +{ + return 1; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWDefuseMines.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWDefuseMines.h new file mode 100644 index 000000000..7c1f6309d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWDefuseMines.h @@ -0,0 +1,35 @@ +// Owns a mine-defusing plan and brackets its lifetime with the bot's firing/mine-target state. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWDEFUSEMINES_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWDEFUSEMINES_H + +#include "BAPInfoWrapper.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPStatement; +class Bot; + +// ELF: vtable 0x4BA020 (9 words), operator new 0x20, package F-infantry. +class BAPIWDefuseMines : public BAPInfoWrapper +{ +public: + BAPIWDefuseMines(Bot*, unsigned int, BAPStatement*, int); // 0x1F6A70 + virtual ~BAPIWDefuseMines(); // 0x1F6B80 + + virtual int getInfoType() const; // 0x1F6D40, slot +0x20; from the base declaration +private: + // [INFERRED] friendship for the inline mine reader in createPlan (ELF 0x243FB0). + friend class BBPDefuseMines; + /* +0x18 */ unsigned int m_mine; + /* +0x1C */ Bot* m_bot; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWDEFUSEMINES_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWFire.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWFire.cpp new file mode 100644 index 000000000..8d0726cf0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWFire.cpp @@ -0,0 +1,67 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1F72F0 (__tcf_0 0x1F7350, _GLOBAL__I 0x1F7380): 's Init object only. +#include + +#include "BAPIWFire.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../Main/IBotManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F6E20 (C1): Bot::setIsFiring(true) (+0x12C), setFiringTarget(target) (+0x7C), and +// BotMain::getUseStaticAttack (+0x288) is remembered. +BAPIWFire::BAPIWFire(Bot* bot, unsigned int target, bool flag24, bool flag25, int int1C, int int20, + BAPStatement* statement, int patternId) + : BAPInfoWrapper(statement, patternId) +{ + m_target = target; + m_int1C = int1C; + m_int20 = int20; + m_flag24 = flag24; + m_int28 = -1; + m_flag25 = flag25; + m_bot = bot; + m_statement->mpOwner = this; + bot->setIsFiring(true); + bot->setFiringTarget(target); + m_useStaticAttack = static_cast(bot)->getUseStaticAttack(); +} + +// ELF 0x1F7040 (D1; D0 0x1F7190): deletes the child, then resets the bot (+0x12C, +0x1D0, +// +0x230, +0x1C0, +0x278, +0x7C) and clears the target player's bot "engineer target" flag (+0x1E8). +BAPIWFire::~BAPIWFire() +{ + if (m_statement) + delete m_statement; + BotMain* bot = static_cast(m_bot); + bot->setIsFiring(false); + bot->setBridgeRepairTarget(0xFFFFFFFFu); + bot->setBotIsSimulatingArtillery(false); + bot->setRepairTarget(0xFFFFFFFFu); + bot->setIsGoingForFlag(false); + bot->setFiringTarget(0xFFFFFFFFu); + if (m_target != 0xFFFFFFFFu) { + Information* info = bapinline::info(m_target); + if (info) { + Bot* other = IBotManager::instance->getBotFromPlayerId(info->getPlayerId()); + if (other) + static_cast(other)->setIsEngineerTarget(false); + } + } +} + +// ELF 0x1F73A0: "Fire" +int BAPIWFire::getInfoType() const +{ + return 0; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWFire.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWFire.h new file mode 100644 index 000000000..f5fd5160b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWFire.h @@ -0,0 +1,59 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWFIRE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWFIRE_H + +#include "BAPInfoWrapper.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPStatement; +class Bot; + +// ELF: vtable 0x4BA060 (9 words), operator new 0x34, package C-actions. +// Fire info wrapper: marks the bot firing at the target for its lifetime and clears the +// bot's fire/repair/engineer state when the plan ends. +class BAPIWFire : public BAPInfoWrapper +{ +public: + BAPIWFire(Bot*, unsigned int, bool, bool, int, int, BAPStatement*, int); // 0x1F6E20 + virtual ~BAPIWFire(); // 0x1F7040 + + virtual int getInfoType() const; // 0x1F73A0, slot +0x20; from the base declaration + +public: + // [CHOSEN, not recovered] getters added by ai-w1-e-fire for BBPFireInfantery (inline in the image, + // createPlan 0x25F541..0x25F5D8); mapped onto the owner's (C) field names. + unsigned int getTarget() const { return m_target; } + int getWeapon() const { return m_int1C; } + bool getFlagA() const { return m_flag24; } + bool getUseStaticAttack() const { return m_useStaticAttack; } + // [CHOSEN, not recovered] accessors for BBPFire2dDriver::createPlan (0x24C100), which reads + // +0x25 and +0x28 and stores +0x28 inline (0x250D6C, 0x250D79, 0x24D4FC). + bool getFlagB() const { return m_flag25; } + int getInt28() const { return m_int28; } + void setInt28(int value) { m_int28 = value; } + +private: + /* +0x18 */ unsigned int m_target; + /* +0x1C */ int m_int1C; // ctor's first int (the weapon, per BBPFireInfantery); [UNRESOLVED] + /* +0x20 */ int m_int20; // ctor's second int; [UNRESOLVED] + /* +0x24 */ bool m_flag24; // ctor's first bool; [UNRESOLVED] + /* +0x25 */ bool m_flag25; // ctor's second bool; [UNRESOLVED] + /* +0x28 */ int m_int28; // = -1; [UNRESOLVED] + /* +0x2C */ Bot* m_bot; + /* +0x30 */ bool m_useStaticAttack; // BotMain::getUseStaticAttack at construction +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWFIRE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWIdle.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWIdle.cpp new file mode 100644 index 000000000..c4c4ce640 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWIdle.cpp @@ -0,0 +1,44 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1F76E0 (__tcf_0 0x1F7740, _GLOBAL__I 0x1F7770): 's Init object only. +#include + +#include "BAPIWIdle.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F7480 (C1; C2 0x1F7310 region) +BAPIWIdle::BAPIWIdle(const Vec3& position, BAPStatement* statement, int tag, Bot* bot) + : BAPInfoWrapper(statement, tag) +{ + m_position = position; + m_bot = bot; + if (bot && bot->getSquadMember()) + m_bot->getSquadMember()->setIsIdle(true); + m_statement->mpOwner = this; +} + +// ELF 0x1F75D0 (D1; D2 0x1F7510 region, D0 0x1F7650): clears the idle flag, deletes the child +// (virtual D0, slot +8). +BAPIWIdle::~BAPIWIdle() +{ + if (m_bot && m_bot->getSquadMember()) + m_bot->getSquadMember()->setIsIdle(false); + if (m_statement) + delete m_statement; +} + +// ELF 0x1F7790: "Idle" +int BAPIWIdle::getInfoType() const +{ + return 4; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWIdle.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWIdle.h new file mode 100644 index 000000000..593789c40 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWIdle.h @@ -0,0 +1,40 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWIDLE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWIDLE_H + +#include "../../../../Math/Vec3.h" +#include "BAPInfoWrapper.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPStatement; +class Bot; + +// ELF: vtable 0x4BA0A0 (9 words), operator new 0x28, package C-actions. +// Idle info wrapper: marks the bot's squad member idle for its lifetime. +class BAPIWIdle : public BAPInfoWrapper +{ +public: + BAPIWIdle(const Vec3&, BAPStatement*, int, Bot*); // 0x1F7480 + virtual ~BAPIWIdle(); // 0x1F75D0 + + virtual int getInfoType() const; // 0x1F7790, slot +0x20; from the base declaration + +private: + /* +0x18 */ Vec3 m_position; + /* +0x24 */ Bot* m_bot; // may be null +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWIDLE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWMoveTo.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWMoveTo.cpp new file mode 100644 index 000000000..13ab3abdb --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWMoveTo.cpp @@ -0,0 +1,35 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1F79A0 (__tcf_0 0x1F7A00, _GLOBAL__I 0x1F7A30): 's Init object only. +#include + +#include "BAPIWMoveTo.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F7820 (C1; C2 0x1F77A0 region) +BAPIWMoveTo::BAPIWMoveTo(const Vec3& position, BAPStatement* statement, int tag) + : BAPInfoWrapper(statement, tag) +{ + m_position = position; + m_statement->mpOwner = this; +} + +// ELF 0x1F78F0 (D0 0x1F7940): deletes the child. +BAPIWMoveTo::~BAPIWMoveTo() +{ + if (m_statement) + delete m_statement; +} + +// ELF 0x1F7A50: "MoveTo" +int BAPIWMoveTo::getInfoType() const +{ + return 2; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWMoveTo.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWMoveTo.h new file mode 100644 index 000000000..e453a9fd9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWMoveTo.h @@ -0,0 +1,42 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWMOVETO_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWMOVETO_H + +#include "../../../../Math/Vec3.h" +#include "BAPInfoWrapper.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPStatement; + +// ELF: vtable 0x4BA0E0 (9 words), operator new 0x24, package C-actions. +// MoveTo info wrapper; owns its child. +class BAPIWMoveTo : public BAPInfoWrapper +{ +public: + BAPIWMoveTo(const Vec3&, BAPStatement*, int); // 0x1F7820 + virtual ~BAPIWMoveTo(); // 0x1F78F0 + + virtual int getInfoType() const; // 0x1F7A50, slot +0x20; from the base declaration + + // [INFERRED] inline (no symbol): BBPGotoWaypointSoldier::createPlan 0x285E2F `fsubrs 0x18(%eax)` + // (and 0x2864F0) compares it with the new goal to keep the plan. + const Vec3& getPosition() const { return m_position; } + +private: + /* +0x18 */ Vec3 m_position; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWMOVETO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWRoam.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWRoam.cpp new file mode 100644 index 000000000..ad664551f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWRoam.cpp @@ -0,0 +1,31 @@ +// Owns a roaming plan and retains its object handle. + +#include "BAPIWRoam.h" + + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F7AC0 (C1; C2 0x1F7A60) +BAPIWRoam::BAPIWRoam(unsigned int object, BAPStatement* statement, int tag) + : BAPInfoWrapper(statement, tag), m_object(object) +{ + m_statement->setParent(this); +} + +// ELF 0x1F7B70 (D1; D2 0x1F7B20, D0 0x1F7BC0) +BAPIWRoam::~BAPIWRoam() +{ + delete m_statement; +} + +// ELF 0x1F7C20 +int BAPIWRoam::getInfoType() const +{ + return 5; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWRoam.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWRoam.h new file mode 100644 index 000000000..20a5a80d0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWRoam.h @@ -0,0 +1,33 @@ +// Owns a roaming plan and retains its object handle. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWROAM_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWROAM_H + +#include "BAPInfoWrapper.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPStatement; + +// ELF: vtable 0x4BA120 (9 words), operator new 0x1C, package H-deferred. +class BAPIWRoam : public BAPInfoWrapper +{ +public: + BAPIWRoam(unsigned int, BAPStatement*, int); // 0x1F7AC0 + virtual ~BAPIWRoam(); // 0x1F7B70 + + virtual int getInfoType() const; // 0x1F7C20, slot +0x20; from the base declaration +private: + // [INFERRED] friendship for createPlan's inline target reader (ELF 0x29BFD1). + friend class BBPRoam3d; + /* +0x18 */ unsigned int m_object; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWROAM_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWTakeCover.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWTakeCover.cpp new file mode 100644 index 000000000..2210cf1f6 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWTakeCover.cpp @@ -0,0 +1,47 @@ +// Owns a take-cover plan and stores either a fixed point or an object's initial position. + +// static init: ELF 0x1F7FD0 (__tcf_0 0x1F8030, _GLOBAL__I 0x1F8060): 's Init object only. +#include + +#include "BAPIWTakeCover.h" + +#include "BAPActionInline.h" +#include "../AIKnowledge/Information.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F7CB0 (C1; C2 0x1F7C30) +BAPIWTakeCover::BAPIWTakeCover(const Vec3& position, BAPStatement* statement, int tag) + : BAPInfoWrapper(statement, tag), m_position(position), m_useObject(false) +{ + m_statement->setParent(this); +} + +// ELF 0x1F7E00 (C1; C2 0x1F7D30) +BAPIWTakeCover::BAPIWTakeCover(unsigned int object, BAPStatement* statement, int tag) + : BAPInfoWrapper(statement, tag), m_position(bapinline::vec3(0.0f, 0.0f, 0.0f)), + m_object(object), m_useObject(true) +{ + Information* information = bapinline::info(object); + if (information) + m_position = information->getPosition(); + m_statement->setParent(this); +} + +// ELF 0x1F7F20 (D1; D2 0x1F7ED0, D0 0x1F7F70) +BAPIWTakeCover::~BAPIWTakeCover() +{ + delete m_statement; +} + +// ELF 0x1F8080 +int BAPIWTakeCover::getInfoType() const +{ + return 7; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWTakeCover.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWTakeCover.h new file mode 100644 index 000000000..a845be3f3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWTakeCover.h @@ -0,0 +1,40 @@ +// Owns a take-cover plan and stores either a fixed point or an object's initial position. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWTAKECOVER_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWTAKECOVER_H + +#include "../../../../Math/Vec3.h" +#include "BAPInfoWrapper.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPStatement; + +// ELF: vtable 0x4BA160 (9 words), operator new 0x2C, package H-deferred. +class BAPIWTakeCover : public BAPInfoWrapper +{ +public: + BAPIWTakeCover(const Vec3&, BAPStatement*, int); // 0x1F7CB0 + BAPIWTakeCover(unsigned int, BAPStatement*, int); // 0x1F7E00 + virtual ~BAPIWTakeCover(); // 0x1F7F20 + + virtual int getInfoType() const; // 0x1F8080, slot +0x20; from the base declaration +private: + // [INFERRED] friendship for the inline +0x18/+0x24/+0x28 readers in BBPTakeCover::createPlan + // (ELF 0x29F98C, 0x29F9E3, 0x29FA73, 0x29FAE7, 0x29FB4F). + friend class BBPTakeCover; + // The infantry pattern repeats the same readers (ELF 0x2A664D, 0x2A669E, 0x2A6724). + friend class BBPTakeCoverInfantry; + /* +0x18 */ Vec3 m_position; + /* +0x24 */ unsigned int m_object; // initialized only by the object-taking constructor + /* +0x28 */ bool m_useObject; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWTAKECOVER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPInfoWrapper.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPInfoWrapper.cpp new file mode 100644 index 000000000..875ef2489 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPInfoWrapper.cpp @@ -0,0 +1,85 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1F5740 (__tcf_0 0x1F58D0, __tcf_1 0x1F5900, _GLOBAL__I 0x1F5970): 's Init object, then dice::hfe::ai::infoTypes. +#include + +#include "BAPInfoWrapper.h" + +#include "BAPActionInline.h" +#include "../AIPlanInterpreter/PlanInterpreter.h" +#include "../Main/IBotManager.h" +#include "../AIBot/BotMain.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x4CE220, built by the TU's static initialiser 0x1F5740 (destroyed by __tcf_1 0x1F5900). +std::string infoTypes[10] = { "Fire", "DefuseMines", "MoveTo", "Avoid", "Idle", "Roam", "Scout", + "TakeCover", "Change", "Default" }; + +// ELF 0x1F5470 (C1; C2 0x1F5410). The child's parent is set by the subclasses, not here. +BAPInfoWrapper::BAPInfoWrapper(BAPStatement* statement, int tag) +{ + m_controls = 0; + m_patternId = tag; + m_statement = statement; +} + +// ELF 0x1F5510 (D1; D2 0x1F54D0, D0 0x1F5550): base only, the child is not deleted here. +BAPInfoWrapper::~BAPInfoWrapper() +{ +} + +// ELF 0x1F55A0: `bot->getPlanInterpreter()->execute(child, bot, ok, failed)` (slot +8). +bool BAPInfoWrapper::execute(Bot* bot, bool& ok, bool& failed) +{ + PlanInterpreter* interpreter = static_cast(bot)->getPlanInterpreter(); + return interpreter->execute(m_statement, bot, ok, failed); +} + +// ELF 0x1F5990: the child's controls. +unsigned long long BAPInfoWrapper::getControls() +{ + return m_statement->getControls(); +} + +// ELF 0x1F59B0 +BAPStatementType BAPInfoWrapper::getId() const +{ + return BAPSTInfoWrapper; // 15 +} + +// ELF 0x1F59C0 +bool BAPInfoWrapper::hasDefault() +{ + return true; +} + +// ELF 0x1F5600 +void BAPInfoWrapper::streamSelf(std::ostream& out) const +{ + IBotManager::instance->tabulate(out); + const int type = getInfoType(); + out << "InfoWrapper(" << infoTypes[type] << ")" << std::endl; + IBotManager::instance->tabulate(out); + out << '{' << std::endl; + IBotManager::instance->increaseTabLevel(); + if (m_statement) + out << *m_statement; // operator<<(std::ostream&, const BAPStatement&) 0x1F82D0 + IBotManager::instance->decreaseTabLevel(); + IBotManager::instance->tabulate(out); + out << '}' << std::endl; +} + +// ELF 0x1F59D0: "Default" +int BAPInfoWrapper::getInfoType() const +{ + return 9; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPInfoWrapper.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPInfoWrapper.h new file mode 100644 index 000000000..38fdf6fc9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPInfoWrapper.h @@ -0,0 +1,51 @@ +// Runs a child statement through the bot's interpreter and supplies a plan information type. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPINFOWRAPPER_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPINFOWRAPPER_H + +#include +#include +#include "BAPStatement.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPStatement; +class Bot; + +// BSS 0x4CE220: "Fire", "DefuseMines", "MoveTo", "Avoid", "Idle", "Roam", "Scout", "TakeCover", +// "Change", "Default" (static initialiser 0x1F5740), indexed by getInfoType(). +extern std::string infoTypes[10]; + +// ELF: vtable 0x4B9F60 (9 words), package C-actions. +// Wraps one statement and tags it with an information type (getInfoType, an index into +// infoTypes); runs the child through the bot's plan interpreter. +class BAPInfoWrapper : public BAPStatement +{ +public: + BAPInfoWrapper(BAPStatement*, int); // 0x1F5470 + virtual ~BAPInfoWrapper(); // 0x1F5510 + + virtual bool execute(Bot*, bool&, bool&); // 0x1F55A0, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1F5990, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1F59B0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1F59C0, slot +0x14; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1F5600, slot +0x1C; from the base declaration + virtual int getInfoType() const; // 0x1F59D0, slot +0x20; [INFERRED] ELF int + + // [CHOSEN, not recovered] added by ai-w1-e-fire for BBPFireInfantery: inline in the image + // (createPlan reads +0x10, BAPStatement::m_patternId). + int getGeneratorId() const { return m_patternId; } + + /* +0x14 */ BAPStatement* m_statement; // the wrapped child; deleted by the subclasses' destructors + +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPINFOWRAPPER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPInterruptControl.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPInterruptControl.h new file mode 100644 index 000000000..774434105 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPInterruptControl.h @@ -0,0 +1,29 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPINTERRUPTCONTROL_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPINTERRUPTCONTROL_H + +#include "BAPStatement.h" + +namespace dice { +namespace hfe { + +namespace ai { + + +// ELF: package C-actions. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BAPInterruptControl : public BAPStatement +{ +public: +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPINTERRUPTCONTROL_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPStatement.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPStatement.cpp new file mode 100644 index 000000000..0c995fc33 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPStatement.cpp @@ -0,0 +1,47 @@ +// BAPStatement: recovered by package A-core from libaidll.so (TU BAPStatement.cpp, 0x1F8210..0x1F8440; +// getControls is weak at 0x1CDB10). Every body carries its ELF address. + +// static init: ELF 0x1F8300 (__tcf_0 0x1F8360, _GLOBAL__I 0x1F8390): 's Init object only. +#include + +#include "BAPStatement.h" +#include "../Main/IBotManager.h" +#include "../Main/AIStreamOperators.h" + + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +int BAPStatement::news = 0; +int BAPStatement::destroys = 0; + +// ~BAPStatement (0x1F83B0) and getControls (0x1CDB10) are weak in the image: inline in the header. + +// ELF 0x1F8210. +void BAPStatement::debug(BotScriptDebugger::DebugLevel, std::string& text) +{ + text = "Standard debug."; +} + +// ELF 0x1F8260: IBotManager::instance->tabulate(os) (+0x88), then os << getId() (slot +0x10) +// << endl with operator<<(ostream&, BAPStatementType) 0x3C7D90 (Main/AIStreamOperators.cpp). +void BAPStatement::streamSelf(std::ostream& os) const +{ + IBotManager::instance->tabulate(os); + os << getId() << std::endl; +} + +// ELF 0x1F82D0. +std::ostream& operator<<(std::ostream& os, const BAPStatement& statement) +{ + statement.streamSelf(os); + return os; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPStatement.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPStatement.h new file mode 100644 index 000000000..c9a467dc5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPStatement.h @@ -0,0 +1,77 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPSTATEMENT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPSTATEMENT_H + +#include +#include +#include "BotScript.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + + +// Plan statement base. Vtable 0x4BA240. Layout from BAPFlowCEnd(int, EndType, BAPCondition*) 0x1E3230, +// BAPCombinerSerial(int, int) 0x1E6150, BAPFlowCIf 0x1E3550 and BAPAIdle(BAPCondition*, u64, int) 0x1D2850: +// every constructor stores vptr, +4 = 0, +8/+0xC = 0, increments `news`, then its own vptr, and stores +// its trailing `int` constructor argument at +0x10. That argument is the creating pattern's id +// (BBPAvoidCollision2d::createPlan passes its +8, SensingAgentMouseFreeLookPattern its getId()). +// ELF: vtable 0x4BA240 (8 words), package A-core. +class BAPStatement : public BotScript +{ +public: + virtual ~BAPStatement() { ++destroys; } // 0x1F83B0, weak in the image (inline): every derived dtor inlines it + + virtual unsigned long long getControls() { return m_controls; } // 0x1CDB10 (weak), slot +0x0C + virtual BAPStatementType getId() const = 0; // no body, slot +0x10; from the base declaration + virtual bool hasDefault() = 0; // no body, slot +0x14; from the base declaration + virtual void debug(BotScriptDebugger::DebugLevel, std::string&); // 0x1F8210, slot +0x18; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1F8260, slot +0x1C; from the base declaration + + // [INFERRED] inline (no symbol): wrappers and combiners store themselves at +0x04 of their + // child statements (BAPIWIdle 0x1F7480, BAPIWMoveTo 0x1F7820). Same as writing mpOwner. + void setParent(void* parent) { mpOwner = parent; } + + // [INFERRED] inline (no symbol): patterns compare the current plan's +0x10 with their own id to + // keep it (BBPIdleInfantery::createPlan 0x28F718, BBPGotoWaypointSoldier::createPlan 0x2847DF). + int getPatternId() const { return m_patternId; } + +public: + static int news; // BSS 0x4CE268; every BAPStatement constructor increments it + static int destroys; // BSS 0x4CE26C; ~BAPStatement 0x1F83B0 increments it + +protected: + // [CHOSEN, not recovered] overload selector for the inline base construction in BAPWrapperFinished + // (ELF 0x1F9F00) and BAPWrapperWeapon (0x1FB050): neither stores a pattern id. + struct UninitializedPatternId {}; + explicit BAPStatement(UninitializedPatternId) : m_controls(0) { ++news; } + + // The image's BAPStatement constructor is inline (no symbol). Derived constructors either pass + // the trailing int (and the controls mask, when they take one) here or assign the fields; the + // store order inside one constructor is not observable. [CHOSEN] the two signatures. + BAPStatement() : m_controls(0), m_patternId(0) { ++news; } + explicit BAPStatement(int patternId, unsigned long long controls = 0) + : m_controls(controls), m_patternId(patternId) { ++news; } + + // +0x04 is BotScript::mpOwner (the parent node or the behaviour). + /* +0x08 */ unsigned long long m_controls; // = 0; getControls 0x1CDB10 returns it; actions store their + // `unsigned long long` constructor argument (BAPAIdle 0x1D28B2) + /* +0x10 */ int m_patternId; // trailing constructor `int`: the creating pattern's id [INFERRED] name +}; + +// ELF 0x1F82D0: statement.streamSelf(os) (slot +0x1C); returns os. +std::ostream& operator<<(std::ostream& os, const BAPStatement& statement); + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPSTATEMENT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPTypes.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPTypes.h new file mode 100644 index 000000000..09848dbdc --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPTypes.h @@ -0,0 +1,144 @@ +// Plan-system enums shared by the action, condition, behaviour and interpreter classes. +// [INFERRED] file placement and enumerator spellings where noted; values are attested. +// S0 skeleton (docs/macos-ai-behaviour-plan.md). Owner: package A-core. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPTYPES_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPTYPES_H + +namespace dice { +namespace hfe { +namespace ai { + +// Statement type: BAPStatement::getId. Values from every getId body; names from the 44 BAPST* +// strings the .ai files use (aiSettings.activateDefaultInterpreter). Same `: int` spelling as the +// forward declarations in Main/AIConsole.h and Main/AISettingsInterfaces.h. +// operator<<(ostream&, BAPStatementType) is libaidll.so 0x3C7D90 (a 45-case jump table). +enum BAPStatementType : int +{ + BAPSTParallel = 0, // BAPCombinerParallel + BAPSTSerial = 1, // BAPCombinerSerial + BAPSTPlanEnd = 2, // BAPFlowCEnd + BAPSTIf = 3, // BAPFlowCIf + BAPSTWait = 4, // BAPFlowCWait + BAPSTWhile = 5, // BAPFlowCWhile + BAPSTAimAt = 6, // BAPAAimAt, BAPAAimAt3d + BAPSTMoveTo = 7, // BAPAMoveTo, BAPAMoveTo3d + BAPSTMoveToDirection = 8, // BAPAMoveToDirection, BAPAMoveTo3dDirection + BAPSTMoveToObject = 9, // BAPAMoveToObject, BAPAMoveTo3dObject + BAPSTMoveAwayFromObject = 10, // BAPAMoveAwayFrom3dObject + BAPSTTrigger = 11, + BAPSTTriggerContinously = 12, + BAPSTIdle = 13, + BAPSTResetControls = 14, + BAPSTInfoWrapper = 15, + BAPSTAimingWrapper = 16, + BAPSTFinishedWrapper = 17, + BAPSTWeaponWrapper = 18, + BAPSTLookAtWrapper = 19, + BAPSTSense = 20, + BAPSTOverrideSensingAgent = 21, + BAPSTPlaceC4 = 22, + BAPSTLookAt = 23, // BAPALook + BAPSTTurn = 24, + BAPSTRoll3d = 25, + BAPSTSoldierPose = 26, + BAPSTUpdateVehicle = 27, + BAPSTChangeWeapon = 28, + BAPSTICChangeVehicle = 29, + // 30: no class returns it and the stream operator prints nothing for it. [UNRESOLVED] + BAPSTICTurnLock = 31, + BAPSTEvaluate = 32, + BAPSTNotifyBot = 33, + BAPSTPhysicsEnable = 34, + BAPSTSetSensingAgentFocus = 35, + BAPSTMergeSoldierInputs = 36, + BAPSTSendRadioMessage = 37, + BAPSTDebug = 38, + BAPSTForgetTarget = 39, + BAPSTUseFlareOnMissileLock = 40, + BAPSTRunOverObject = 41, + BAPSTHonkHorn = 42, + BAPSTEvaluateCondition = 43, + BAPSTRevive = 44 +}; + +// Condition type: BAPCondition::getConditionType. Values from the getConditionType bodies and +// operator<<(ostream&, BAPConditionType) 0x3C7AE0 (59 cases; its strings in the comments). +// [INFERRED] enumerator names (BAPCT + class stem). Retail quirks kept by the classes, not here: +// BAPConPointInFront returns 23 (ObjectInFront), ValidPitchAiming/ValidYawAiming return 32. +enum BAPConditionType : int +{ + BAPCTLookDeviation = 0, + BAPCTPrecision = 1, + BAPCTPrecision3d = 2, + BAPCTBombPrecision3d = 3, + BAPCTAnd = 4, + BAPCTEndOfPath = 5, + BAPCTFalse = 6, // "false" + BAPCTGeneric1Arg = 7, // "Generic1Arg"; no class returns it + BAPCTGeneric2Arg = 8, // "Generic2Arg"; no class returns it + BAPCTInsideBattleZone = 9, + BAPCTIteration = 10, + BAPCTLineOfFire = 11, + BAPCTPointDistance = 12, + BAPCTPointInFront = 13, + BAPCTNot = 14, + BAPCTDistanceToProj = 15, + BAPCTStrategicObjectStatus = 16, + BAPCTObjectBehind = 17, + BAPCTObjectDistance = 18, + BAPCTObjectDistanceToPoint = 19, + BAPCTObjectEnemyOccupied = 20, + BAPCTObjectExists = 21, + BAPCTObjectHealth = 22, + BAPCTObjectInFront = 23, + BAPCTObjectInLandingZone = 24, + BAPCTObjectInsideFrustum = 25, + BAPCTObjectLineOfFire = 26, + BAPCTObjectManDown = 27, + BAPCTObjectMoved = 28, + BAPCTObjectOccupied = 29, + BAPCTObjectSpeed = 30, + BAPCTObjectTouchingLand = 31, // "ObjectTouchingGround" + BAPCTObjectValidAiming = 32, + BAPCTObjectValidPosition = 33, + BAPCTObjectVisible = 34, + BAPCTOr = 35, + BAPCTPointAt = 36, + BAPCTPosition = 37, + BAPCTSharedCondition = 38, + BAPCTTime = 39, + BAPCTTrue = 40, // "true" + BAPCTWeaponMagAmmo = 41, + BAPCTWeaponTotalAmmo = 42, + BAPCTTotalAmmo = 43, // "TotalWeaponAmmo" + BAPCTWeaponReadyToFire = 44, + BAPCTWeaponTargetReachable = 45, + BAPCTWeaponHeat = 46, + BAPCTWeaponHasLockOnTarget = 47, + // 48: no class returns it and the stream operator prints nothing for it. [UNRESOLVED] + BAPCTIsTriggered = 49, + BAPCTAllowFire = 50, // "Allow fire" + BAPCTIsSprinting = 51, // "Sprinting" + BAPCTWeaponIsZoomed = 52, // "Zoomed" + BAPCTWeaponDetonatorIsActive = 53, // "Detonator active" + BAPCTWeaponIsActive = 54, // "Weapon active" + BAPCTOpLessThan = 55, // BAPConOpLessThan + BAPCTOkToThrowGrenade = 56, // "Ok to throw grenade" + BAPCTSplashDamage = 57, // "Splash damage" + BAPCTTriggerableActive = 58 // "Triggerable Active" +}; + +// Free enums seen only in mangled parameter lists. [UNRESOLVED] enumerators; the same `: int` +// forward declarations already used by Main/ and AIBot/. BotLodLevel is defined in AIBot/BotMain.h +// (operator<< 0x3C78B0 prints BLLNone/BLLLight/BLLFull/BLLMedium). +enum BotLodLevel : int; +enum AIRadioMessageType : int; +enum AIRadioChannelType : int; +enum AvoidSide : int; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPTYPES_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPVariable.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPVariable.h new file mode 100644 index 000000000..a7fd9a6c3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPVariable.h @@ -0,0 +1,35 @@ +// Typed plan variable owned by a BAPContext (inline template in the image). +// Layout from the inlined constructions in BBPFireInfantery::createPlanInternal (0x2650F0): +// new 0x10 for and 0x18 for ; each new variable is pushed onto the context's +// std::list. Instantiated for bool, int, unsigned int, float, Vec3 and +// WeaponInfo* (vtables 0x4BBD38, 0x4BBC68, 0x4BBC28, 0x4BBC58, 0x4BBD28, 0x4BB908). +// S0 skeleton (docs/macos-ai-behaviour-plan.md). Owner: package A-core. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPVARIABLE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPVARIABLE_H + +#include "../AIPlanInterpreter/BAPContext.h" + +namespace dice { +namespace hfe { +namespace ai { + +template +class BAPVariable : public BotScriptVariable +{ +public: + // [INFERRED] parameter order: the inlined stores are +4 = a pointer the caller keeps in a + // register (dereferenced before), +8 = the initial value, then the trailing word = 0. + BAPVariable(void* owner, const T& value) : m_owner(owner), m_value(value), m_tail(0) {} + virtual ~BAPVariable() {} // D1/D0 only: vptr store and BotScriptVariable + + /* +0x04 */ void* m_owner; // [UNRESOLVED] type and name + /* +0x08 */ T m_value; // bool: false, Vec3: (0, 1, 0) at the construction above + /* after */ int m_tail; // = 0; +0x0C for bool, +0x14 for Vec3 [UNRESOLVED] meaning +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPVARIABLE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperAiming.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperAiming.cpp new file mode 100644 index 000000000..9ce7c7b33 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperAiming.cpp @@ -0,0 +1,251 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1F9D20 (__tcf_0 0x1F9D80, _GLOBAL__I 0x1F9DB0): 's Init object only. +#include + +#include "BAPWrapperAiming.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SensedObject.h" +#include "../AIBot/SensingAgent.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../Main/AIDllFrontier.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFPhysics.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// The sensed hit point (SensedObject +0x04) through the target's transformation (Information slot +// +0x3C), spelled out in place three times in execute. +Vec3 sensedWorldPoint(Information* target, const SensedObject* sensed) +{ + const Mat4& t = target->getTransformation(); + const Vec3& l = sensed->m_seenPosition; + return bapinline::vec3(t.m[8] * l.z + t.m[0] * l.x + t.m[4] * l.y + t.m[12], + t.m[1] * l.x + t.m[5] * l.y + t.m[9] * l.z + t.m[13], + l.x * t.m[2] + l.y * t.m[6] + l.z * t.m[10] + t.m[14]); +} + +} // namespace + +// ELF 0x1F8C30 (C1; C2 0x1F8B70). Note the argument order: aim direction, valid flag, aim point. +BAPWrapperAiming::BAPWrapperAiming(BAPVariable* aimDirection, BAPVariable* aimValid, + BAPVariable* aimPoint, unsigned int shooter, unsigned int target, + bool continuous) +{ + m_aimDirection = aimDirection; + m_aimPoint = aimPoint; + m_aimValid = aimValid; + m_shooter = shooter; + m_target = target; + m_continuous = continuous; + m_groundQuery.x = m_groundQuery.y = m_groundQuery.z = 0.0f; + m_groundLevel = 0.0f; +} + +// ELF 0x1F9DD0 (D1; D0 0x1F9E30): the Aimer and the base only. +BAPWrapperAiming::~BAPWrapperAiming() +{ +} + +// ELF 0x1F8CF0. The ground under `pos`: a line from pos down 2 m against the world, ignoring the +// target's object; the answer is cached for the last position (FLT_EPSILON per component). No +// target information: false; no hit: false (cache untouched). +bool BAPWrapperAiming::getGroundLevelAtPos(Bot*, const Vec3& pos, float& level) +{ + Information* target = bapinline::info(m_target); + if (!target) + return false; + if (std::fabs(m_groundQuery.x - pos.x) > 1.1920929e-07f || std::fabs(m_groundQuery.y - pos.y) > 1.1920929e-07f + || std::fabs(m_groundQuery.z - pos.z) > 1.1920929e-07f) { + // pos - (0, 2, 0) (the image subtracts 0.0 from x and z). + const Vec3 below = bapinline::vec3(pos.x - 0.0f, pos.y - 2.0f, pos.z - 0.0f); + Vec3 hit = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (!bapinline::collideLineIgnoring(pos, below, target->getAIObject(), hit)) + return false; + level = hit.y; + m_groundQuery = pos; + m_groundLevel = level; + return true; + } + level = m_groundLevel; + return true; +} + +// ELF 0x1F8F40. Aims the weapon of m_shooter at m_target: overrides the sensing agent, sets up +// the Aimer from the active weapon (drag, exit velocity, scaled gravity, thrown), picks the aim +// point from the sensed record and solves for the firing direction. Explosive unguided weapons +// against a target that is out of sight use its last seen position (on the ground) or, for a +// "static" shot (BotMain::setBotWantsToSimulateArtillery(true), Aimer::getStaticFiringDirection), +// its last known position led by its velocity. Out: m_aimDirection, m_aimPoint, m_aimValid; ok; +// done unless m_continuous. Missing information, control info, armament or weapon: ok = false, +// done. +bool BAPWrapperAiming::execute(Bot* bot, bool& ok, bool& done) +{ + bot->getSensingAgent()->setOverride(true); + Information* self = bapinline::info(m_shooter); + if (!self || !self->getControlInfo() || !self->getArmament()) { + ok = false; + done = true; + return true; + } + IPIArmament* armament = self->getArmament(); + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + if (!weapon) { + ok = false; + done = true; + return true; + } + Information* target = bapinline::info(m_target); + if (!target) { + ok = false; + done = true; + return true; + } + // Neither primary information is null-checked in the image. + IPIMobile* targetMobile = bapinline::info(target->getPrimaryObject(bot->getSide()))->getMobile(); + IPIMobile* ownMobile = bapinline::info(self->getPrimaryObject(bot->getSide()))->getMobile(); + + const float drag = weapon->getDrag(); + m_aimer.m_drag = drag; + m_aimer.m_inverseDrag = drag != 0.0f ? 1.0f / drag : 0.0f; + m_aimer.m_speed = weapon->getExitVelocity(); + const float gravityModifier = weapon->getGravityModifier(); + m_aimer.m_gravity = static_cast( + static_cast(static_cast(CommonSingletonServer::m_iaiPhysics)->getGravity()) * gravityModifier); + m_aimer.m_grenade = weapon->getIsThrown(); + const double now = bapinline::gameTime(); + + // Soldier against soldier: short-range weapons aim 0.2 lower, others 0.3 lower at a standing + // target. + float yOffset = 0.0f; + if (self->isOfType(ITSoldier) && target->isOfType(ITSoldier)) { + if (weapon->getMaxRange() < 10.0f) + yOffset = -0.2f; + else if (target->getSoldierPose() == SPStanding) + yOffset = -0.3f; + } + + SensedObject* sensed = bot->getSensedObjectFromHandle(m_target); + if (!sensed) + return true; // ok/done untouched (0x1F91EA) + + Vec3 point = sensedWorldPoint(target, sensed); + const double now2 = bapinline::gameTime(); + const Vec3& from = self->getPosition(); + const float dy = point.y - from.y; + Vec3 toTarget = bapinline::vec3(point.x - from.x, dy, point.z - from.z); + const float len = std::sqrt(toTarget.x * toTarget.x + toTarget.y * toTarget.y + toTarget.z * toTarget.z); + if (len != 0.0f) { + const float inv = 1.0f / len; + toTarget.x *= inv; + toTarget.y *= inv; + toTarget.z = inv * toTarget.z; + } + + const bool explosive = weapon->getExplosionRadius() != 0.0f && weapon->getWeaponGuidanceType() == 0; + const bool explosiveShot = explosive && !weapon->getIsThrown(); + const bool vehicleAtSoldier = !self->isOfType(ITSoldier) + && target->isOfType(ITSoldier) && explosiveShot; + const bool highAbove = bot->getSpawnKit() != 1 && !weapon->getIsThrown() && 30.0f < dy; + const bool indirect = (sensed->m_flags & 2u) && ((sensed->m_flags & 8u) || vehicleAtSoldier || highAbove) + && explosive; + const double lastFailed = static_cast(bot)->getTimeOfLastFailedStaticSkyAttack(); + const bool staticShot = indirect && lastFailed <= sensed->m_lastPositionTime && !vehicleAtSoldier + && (!explosiveShot || 10.0f < dy || 0.6f < toTarget.y); + m_aimer.m_flag69 = indirect && !staticShot; + + if (staticShot) { + if (targetMobile) { + double sinceSeen = 999999.0; + if (sensed->m_flags & 2u) + sinceSeen = now2 - sensed->m_lastSeenTime; + point = 5.0 <= sinceSeen ? sensed->m_lastSeenPosition : sensed->m_lastPosition; + double lead = now - sensed->m_lastPositionTime; + if (1.0 < lead) { + const double scaled = (lead - 1.0) * 0.05 + 1.0; // static `factor` = 0.05 (0x4BA328) + const float limit = + 8.0f <= static_cast(now2 - bot->getTimeOfGrenadeThrown(0)) ? 2.0f : 0.5f; + lead = limit; + if (scaled < static_cast(limit)) + lead = scaled; + } + const Vec3& v = targetMobile->getSpeed(); + const float s = static_cast(lead); + point.x = v.x * s + point.x; + point.y = v.y * s + point.y; + point.z = s * v.z + point.z; + } else { + point = sensedWorldPoint(target, sensed); + } + } else if (indirect) { + point = sensed->m_lastSeenPosition; + float level; + if (getGroundLevelAtPos(bot, point, level)) + point.y = level; + } else if (!(sensed->m_flags & 2u) || (sensed->m_flags & 8u)) { + point.y = yOffset + point.y; + } else { + point = sensedWorldPoint(target, sensed); + point.y = point.y + yOffset; + } + + if (explosive && !weapon->getIsThrown() && !indirect && target->isOfType(ITSoldier)) + point.y = static_cast(CommonSingletonServer::m_iaiTerrain)->getHeight(point.x, point.z); + if (m_aimPoint) + m_aimPoint->m_value = point; + + const Mat4& origin = weapon->getProjectileOrigin(); + const Vec3 rel = bapinline::vec3(point.x - origin.m[12], point.y - origin.m[13], point.z - origin.m[14]); + Vec3 targetVelocity = bapinline::vec3(0.0f, 0.0f, 0.0f); + Vec3 ownVelocity = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (ownMobile) + ownVelocity = ownMobile->getSpeed(); + if (targetMobile && !indirect) + targetVelocity = targetMobile->getSpeed(); + m_aimer.setTargetData(rel, targetVelocity, ownVelocity, &origin, now); + + Vec3 direction = bapinline::vec3(0.0f, 0.0f, 0.0f); + Vec3 aimTarget = bapinline::vec3(0.0f, 0.0f, 0.0f); + bool valid; + if (staticShot) { + static_cast(bot)->setBotWantsToSimulateArtillery(true); + valid = m_aimer.getStaticFiringDirection(direction, aimTarget); + } else { + static_cast(bot)->setBotWantsToSimulateArtillery(false); + valid = m_aimer.getFiringDirection(now, 0.5f, weapon->getIndirect(), direction, aimTarget, 0); + } + done = !m_continuous; + ok = true; + m_aimDirection->m_value = direction; + m_aimValid->m_value = valid; + return true; +} + +// ELF 0x1F9D00 +BAPStatementType BAPWrapperAiming::getId() const +{ + return BAPSTAimingWrapper; // 16 +} + +// ELF 0x1F9D10 +bool BAPWrapperAiming::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperAiming.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperAiming.h new file mode 100644 index 000000000..573d7fb66 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperAiming.h @@ -0,0 +1,52 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPWRAPPERAIMING_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPWRAPPERAIMING_H + +#include "../../../../Math/Vec3.h" +#include "BAPStatement.h" +#include "BAPTypes.h" +#include "BAPVariable.h" +#include "Aimer.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4BA340 (8 words), operator new 0xA8, package C-actions. +class BAPWrapperAiming : public BAPStatement +{ +public: + BAPWrapperAiming(BAPVariable*, BAPVariable*, BAPVariable*, unsigned int, unsigned int, bool); // 0x1F8C30 + virtual ~BAPWrapperAiming(); // 0x1F9DD0 + + virtual bool execute(Bot*, bool&, bool&); // 0x1F8F40, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1F9D00, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1F9D10, slot +0x14; from the base declaration + + bool getGroundLevelAtPos(Bot*, const Vec3&, float&); // 0x1F8CF0; ELF bool (`testb %al` in execute) + +private: + /* +0x14 */ Aimer m_aimer; + /* +0x80 */ BAPVariable* m_aimDirection; // out: the firing direction + /* +0x84 */ BAPVariable* m_aimPoint; // out (may be 0): the point aimed at + /* +0x88 */ BAPVariable* m_aimValid; // out: the Aimer's answer + /* +0x8C */ unsigned int m_shooter; // information handle: the bot's vehicle/soldier + /* +0x90 */ unsigned int m_target; // information handle + /* +0x94 */ bool m_continuous; // set: never done + /* +0x98 */ Vec3 m_groundQuery; // = 0; getGroundLevelAtPos' last position + /* +0xA4 */ float m_groundLevel; // = 0; its answer +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPWRAPPERAIMING_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperFinished.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperFinished.cpp new file mode 100644 index 000000000..7de304d22 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperFinished.cpp @@ -0,0 +1,71 @@ +// Owns a child statement and overrides its finished result after interpreter execution. + +// static init: ELF 0x1FA260 (__tcf_0 0x1FA2C0, _GLOBAL__I 0x1FA2F0): 's Init object only. +#include + +#include "BAPWrapperFinished.h" + +#include "../AIBot/BotMain.h" +#include "../AIPlanInterpreter/PlanInterpreter.h" +#include "../Main/IBotManager.h" +#include "../Main/AIStreamOperators.h" +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F9F00 (C1; C2 0x1F9E90) +BAPWrapperFinished::BAPWrapperFinished(BAPStatement* statement, bool finished) + : BAPStatement(UninitializedPatternId()), m_statement(statement), m_finished(finished) +{ + if (m_statement) + m_statement->setParent(this); +} + +// ELF 0x1F9FE0 (D1; D2 0x1F9F70, D0 0x1FA050) +BAPWrapperFinished::~BAPWrapperFinished() +{ + delete m_statement; +} + +// ELF 0x1FA0C0 +bool BAPWrapperFinished::execute(Bot* bot, bool& success, bool& finished) +{ + if (m_statement) + static_cast(bot)->getPlanInterpreter()->execute(m_statement, bot, success, finished); + finished = m_finished; + return true; +} + +// ELF 0x1FA130 +BAPStatementType BAPWrapperFinished::getId() const +{ + return BAPSTFinishedWrapper; +} + +// ELF 0x1FA140 +bool BAPWrapperFinished::hasDefault() +{ + return true; +} + +// ELF 0x1FA150 +void BAPWrapperFinished::streamSelf(std::ostream& out) const +{ + IBotManager::instance->tabulate(out); + out << getId() << std::endl; + IBotManager::instance->tabulate(out); + out << '{' << std::endl; + if (m_statement) { + IBotManager::instance->increaseTabLevel(); + out << *m_statement; + IBotManager::instance->decreaseTabLevel(); + } + IBotManager::instance->tabulate(out); + out << '}' << std::endl; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperFinished.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperFinished.h new file mode 100644 index 000000000..309657673 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperFinished.h @@ -0,0 +1,38 @@ +// Owns a child statement and overrides its finished result after interpreter execution. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPWRAPPERFINISHED_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPWRAPPERFINISHED_H + +#include +#include "BAPStatement.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPStatement; +class Bot; + +// ELF: vtable 0x4BA3C0 (8 words), package H-deferred. +class BAPWrapperFinished : public BAPStatement +{ +public: + BAPWrapperFinished(BAPStatement*, bool); // 0x1F9F00 + virtual ~BAPWrapperFinished(); // 0x1F9FE0 + + virtual bool execute(Bot*, bool&, bool&); // 0x1FA0C0, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1FA130, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1FA140, slot +0x14; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1FA150, slot +0x1C; from the base declaration +private: + /* +0x14 */ BAPStatement* m_statement; + /* +0x18 */ bool m_finished; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPWRAPPERFINISHED_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperLookAt.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperLookAt.cpp new file mode 100644 index 000000000..194102138 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperLookAt.cpp @@ -0,0 +1,156 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1FADB0 (__tcf_0 0x1FAE10, _GLOBAL__I 0x1FAE40): 's Init object only. +#include + +#include "BAPWrapperLookAt.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SensedObject.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../Main/AIDllFrontier.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1FA390 (C1; C2 0x1FA2D0): look at an object. +BAPWrapperLookAt::BAPWrapperLookAt(unsigned int target, BAPVariable* lookPoint, bool continuous, bool lead, + BAPVariable* lookDirection, BAPVariable* valid) +{ + m_target = target; + m_lookPoint = lookPoint; + m_lookDirection = lookDirection; + m_valid = valid; + m_point.x = m_point.y = m_point.z = 0.0f; + m_continuous = continuous; + m_lead = lead; +} + +// ELF 0x1FA4B0 (C1; C2 0x1FA410): look at a fixed point. +BAPWrapperLookAt::BAPWrapperLookAt(const Vec3& point, BAPVariable* lookPoint, bool continuous, + BAPVariable* lookDirection, BAPVariable* valid) +{ + m_target = 0xFFFFFFFFu; + m_lookPoint = lookPoint; + m_lookDirection = lookDirection; + m_valid = valid; + m_point = point; + m_lead = false; + m_continuous = continuous; +} + +// ELF 0x1FAE60 (D1; D0 0x1FAEA0): base only. +BAPWrapperLookAt::~BAPWrapperLookAt() +{ +} + +// ELF 0x1FA550. Fixed point: the point, ok, done unless continuous (the direction variable is not +// written). Object: unknown information: ok = false, done. Otherwise ok, done unless continuous, +// valid = true, and when the bot senses it: the sensed hit point in world space (or, with m_lead, +// that point led by the target's velocity over the projectile's flight time from the camera, +// raised by 5% of the distance for soldiers) into m_lookPoint and the normalised direction from +// the bot into m_lookDirection. The bot's information is not null-checked. +bool BAPWrapperLookAt::execute(Bot* bot, bool& ok, bool& done) +{ + Information* self = bapinline::info(bot->getCurrentEquipment()); + if (m_target == 0xFFFFFFFFu) { + ok = true; + done = !m_continuous; + m_lookPoint->m_value = m_point; + return true; + } + Information* target = bapinline::info(m_target); + if (!target) { + ok = false; + done = true; + return true; + } + ok = true; + done = !m_continuous; + if (m_valid) + m_valid->m_value = true; + SensedObject* sensed = bot->getSensedObjectFromHandle(m_target); + if (!sensed) + return true; + + const Mat4& t = target->getTransformation(); + const Vec3& l = sensed->m_seenPosition; + const Vec3 point = bapinline::vec3(t.m[8] * l.z + t.m[0] * l.x + t.m[4] * l.y + t.m[12], + t.m[1] * l.x + t.m[5] * l.y + t.m[9] * l.z + t.m[13], + l.y * t.m[6] + l.x * t.m[2] + l.z * t.m[10] + t.m[14]); + Vec3 dir; + if (!m_lead) { + m_lookPoint->m_value = point; + if (!m_lookDirection) + return true; + dir = bapinline::sub(point, self->getPosition()); + bapinline::normalize(dir); + } else { + IPIMobile* targetMobile = target->getMobile(); + IPIArmament* armament = self->getArmament(); + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + const Mat4& origin = weapon->getProjectileOrigin(); + Vec3 projSpeed = bapinline::vec3(0.0f, 0.0f, 0.0f); + const bool haveSpeed = armament->getProjectileSpeed(projSpeed); + Vec3 projPos = bapinline::vec3(0.0f, 0.0f, 0.0f); + armament->getProjectilePosition(projPos); + const float speedLen = std::sqrt(projSpeed.z * projSpeed.z + projSpeed.y * projSpeed.y + projSpeed.x * projSpeed.x); + const Vec3 from = (speedLen == 0.0f || !haveSpeed) ? bapinline::vec3(origin.m[12], origin.m[13], origin.m[14]) + : projPos; + Vec3 rel = bapinline::sub(point, from); + const Mat4* camera = &self->getControlInfo()->getCameraTransformation(); + Vec3 targetVelocity = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (targetMobile) + targetVelocity = targetMobile->getSpeed(); + if (std::sqrt(projSpeed.z * projSpeed.z + projSpeed.y * projSpeed.y + projSpeed.x * projSpeed.x) == 0.0f) { + projSpeed.x = camera->m[8] * 20.0f; + projSpeed.y = camera->m[9] * 20.0f; + projSpeed.z = camera->m[10] * 20.0f; + } + const float closing = std::sqrt((projSpeed.z - targetVelocity.z) * (projSpeed.z - targetVelocity.z) + + (projSpeed.x - targetVelocity.x) * (projSpeed.x - targetVelocity.x) + + (projSpeed.y - targetVelocity.y) * (projSpeed.y - targetVelocity.y)); + const float distance = std::sqrt(rel.z * rel.z + rel.y * rel.y + rel.x * rel.x); + const float flight = distance / closing; + if (flight < 2.5f) { + rel.x = targetVelocity.x * flight + rel.x; + rel.z = targetVelocity.z * flight + rel.z; + rel.y = rel.y + 0.0f; + } + camera = &self->getControlInfo()->getCameraTransformation(); + if (self->isOfType(ITSoldier)) + rel.y = distance * 0.05f + rel.y; + m_lookPoint->m_value = bapinline::vec3(rel.x + camera->m[12], rel.y + camera->m[13], rel.z + camera->m[14]); + if (!m_lookDirection) + return true; + dir = bapinline::sub(m_lookPoint->m_value, self->getPosition()); + bapinline::normalize(dir); + } + m_lookDirection->m_value = dir; + return true; +} + +// ELF 0x1FAD90 +BAPStatementType BAPWrapperLookAt::getId() const +{ + return BAPSTLookAtWrapper; // 19 +} + +// ELF 0x1FADA0 +bool BAPWrapperLookAt::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperLookAt.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperLookAt.h new file mode 100644 index 000000000..abda262c8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperLookAt.h @@ -0,0 +1,48 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPWRAPPERLOOKAT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPWRAPPERLOOKAT_H + +#include "../../../../Math/Vec3.h" +#include "BAPStatement.h" +#include "BAPTypes.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4BA440 (8 words), operator new 0x34, package C-actions. +class BAPWrapperLookAt : public BAPStatement +{ +public: + BAPWrapperLookAt(unsigned int, BAPVariable*, bool, bool, BAPVariable*, BAPVariable*); // 0x1FA390 + BAPWrapperLookAt(const Vec3&, BAPVariable*, bool, BAPVariable*, BAPVariable*); // 0x1FA4B0 + virtual ~BAPWrapperLookAt(); // 0x1FAE60 + + virtual bool execute(Bot*, bool&, bool&); // 0x1FA550, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1FAD90, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1FADA0, slot +0x14; from the base declaration + +private: + /* +0x14 */ unsigned int m_target; // information handle; -1: look at m_point + /* +0x18 */ BAPVariable* m_lookPoint; // out: the point looked at + /* +0x1C */ BAPVariable* m_lookDirection; // out (may be 0): normalised, from the bot + /* +0x20 */ BAPVariable* m_valid; // out (may be 0): set when the target is known + /* +0x24 */ Vec3 m_point; // the point constructor's; = 0 otherwise + /* +0x30 */ bool m_continuous; // set: never done + /* +0x31 */ bool m_lead; // lead the target with the projectile's flight time +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPWRAPPERLOOKAT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperWeapon.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperWeapon.cpp new file mode 100644 index 000000000..6e009fd2d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperWeapon.cpp @@ -0,0 +1,66 @@ +// Weapon-value wrapper recovered from libaidll.so. +#include "BAPWrapperWeapon.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../../../../Core/Debug.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1FB050 (C1; C2 0x1FAEF0) +BAPWrapperWeapon::BAPWrapperWeapon(ValueId id, BAPVariable* value, + BAPVariable* weapon, bool repeat) + : BAPStatement(UninitializedPatternId()), m_valueId(id), m_integer(value), + m_weapon(weapon), m_repeat(repeat) +{ + if (m_valueId != 0) + Debug(DebugTypeError, "AI/AIDLL/AI/AIBotActionPlan/BAPWrapperWeapon.cpp", 28, "") + << "Unknown integer valueId"; +} + +// ELF 0x1FB310 (C1; C2 0x1FB1B0) +BAPWrapperWeapon::BAPWrapperWeapon(ValueId id, BAPVariable* value, + BAPVariable* weapon, bool repeat) + : BAPStatement(UninitializedPatternId()), m_valueId(id), m_float(value), + m_weapon(weapon), m_repeat(repeat) +{ + if (m_valueId != 1) + Debug(DebugTypeError, "AI/AIDLL/AI/AIBotActionPlan/BAPWrapperWeapon.cpp", 50, "") + << "Unknown float valueId"; +} + +// ELF 0x1FB610 (D1; D0 0x1FB650) +BAPWrapperWeapon::~BAPWrapperWeapon() +{ +} + +// ELF 0x1FB470 +bool BAPWrapperWeapon::execute(Bot*, bool& success, bool& finished) +{ + if (m_valueId == 0) + m_integer->m_value = m_weapon->m_value->getShotsInMag(0); + else if (m_valueId == 1) + m_float->m_value = m_weapon->m_value->getHeat(); + else + Debug(DebugTypeError, "AI/AIDLL/AI/AIBotActionPlan/BAPWrapperWeapon.cpp", 68, "") + << "Unknown valueId"; + success = true; + finished = !m_repeat; + return true; +} + +// ELF 0x1FB5F0 +BAPStatementType BAPWrapperWeapon::getId() const +{ + return BAPSTWeaponWrapper; +} + +// ELF 0x1FB600 +bool BAPWrapperWeapon::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperWeapon.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperWeapon.h new file mode 100644 index 000000000..6a978333f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperWeapon.h @@ -0,0 +1,42 @@ +// Copies magazine ammunition or heat from a borrowed weapon into a plan variable. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPWRAPPERWEAPON_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPWRAPPERWEAPON_H + +#include "BAPStatement.h" +#include "BAPTypes.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class WeaponInfo; + +// ELF: vtable 0x4BA4C0 (8 words), operator new 0x28, package G-vehicles. +class BAPWrapperWeapon : public BAPStatement +{ +public: + enum ValueId : int; // [UNRESOLVED] enumerators + BAPWrapperWeapon(BAPWrapperWeapon::ValueId, BAPVariable*, BAPVariable*, bool); // 0x1FB050 + BAPWrapperWeapon(BAPWrapperWeapon::ValueId, BAPVariable*, BAPVariable*, bool); // 0x1FB310 + virtual ~BAPWrapperWeapon(); // 0x1FB610 + + virtual bool execute(Bot*, bool&, bool&); // 0x1FB470, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1FB5F0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1FB600, slot +0x14; from the base declaration +private: + /* +0x14 */ ValueId m_valueId; + /* +0x18 */ BAPVariable* m_integer; + /* +0x1C */ BAPVariable* m_float; + /* +0x20 */ BAPVariable* m_weapon; + /* +0x24 */ bool m_repeat; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPWRAPPERWEAPON_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BotScript.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BotScript.h new file mode 100644 index 000000000..2e6513bc6 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BotScript.h @@ -0,0 +1,48 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Header placement: AIDLL_r.dll __FILE__ "Code/BF2//AI/AIDLL/AI/AIBotActionPlan/BotScript.h" (assert "0 == mpOwner"). +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_BOTSCRIPT_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_BOTSCRIPT_H + + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// Root of every plan node. Vtable 0x4B77D8: execute (pure), D1, D0. Inline in the image. +// ELF: vtable 0x4B77D8 (3 words), package S0-skeleton (layout: A-core). +// +// execute(bot, ok, finished) protocol, as every recovered caller and node uses it: +// ok the node ran (BAPInterpreter::execute 0x2A99D0 sets it true and finished false for a +// bot that has just spawned, and false/true when no entry may interpret the statement); +// finished the node is done; a parent combiner advances or resets on it (BAPCombinerSerial +// 0x1E6840, BAPFlowCIf 0x1E3850 drop their active child when it is set). +// The return value is 1 in every recovered node; BAPInterpreter forwards its callee's. +class BotScript +{ +public: + BotScript() : mpOwner(0) {} // inline in the image: every BAPStatement constructor stores +4 = 0 + + virtual bool execute(Bot*, bool& ok, bool& finished) = 0; // no body, slot +0x00; from the base declaration + virtual ~BotScript() {} // weak in the image (inline) slots +0x04/+0x08 + + // +0x04: who owns the node. Written through BotScript* by BotBehaviour::generatePlan 0x225C30 + // (the plan root: the behaviour, and the previous plan: the behaviour), by BotMain, and through + // BAPStatement by the combiners (child +4 = parent combiner, 0x1E64D6) and BAPFlowCIf (branches + // +4 = the If, 0x1E35CD). Mixed pointee types, so untyped. [INFERRED] name; public because the + // image writes it inline from several classes. [CHOSEN] visibility. + /* +0x04 */ void* mpOwner; // name: AIDLL_r asserts 0x100EEA60, 0x1014B0C0 (+4) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_BOTSCRIPT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBAvoid.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBAvoid.cpp new file mode 100644 index 000000000..984882d0e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBAvoid.cpp @@ -0,0 +1,407 @@ +// Avoid behaviour (infantry "Avoid" slot of aibehaviours.ai): a soldier scans the obstacles its +// navigation collected, predicts collisions with the moving non-soldier objects and hands the most +// urgent one to its BBPAvoidCollision pattern; a vehicle about to be bailed from is fled at urgency +// 100 per object, and a grenade warning or gas forces urgency 1000. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see +// docs/macos-ai-behaviour-plan.md. + +// static init: ELF 0x1FD0B0 (__tcf_0 0x1FD110, _GLOBAL__I 0x1FD140): 's Init object only. +#include + +#include "BBAvoid.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/BotMemory.h" +#include "../AIBot/BotNavigation.h" +#include "../AIBot/CommunicationAgent.h" +#include "../AIBotBehaviourPattern/BBPAvoidCollision.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../Main/AIDllFrontier.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IBotManager.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../../Game/Objects/IPlayer.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// The sphere centre of an information in world space: the local sphere offset turned by the +// rotation rows of the transformation (row vector times matrix: x uses m[0], m[4], m[8]), plus the +// position. Inlined twice in calculateUrgency (0x1FBE28 for the bot, 0x1FC5DB per obstacle); the +// calls run getTransformation (slot +0x3C), getSphereLocalOffset (IPIPhysical +0x30), getPosition +// (+0x30) in that order. +Vec3 sphereCentre(Information* information, IPIPhysical* physical) +{ + const Mat4& transformation = information->getTransformation(); + const Vec3 offset = physical->getSphereLocalOffset(); + const float* m = transformation.m; + Vec3 rotated; + rotated.x = offset.x * m[0] + offset.y * m[4] + offset.z * m[8]; + rotated.y = offset.x * m[1] + offset.y * m[5] + offset.z * m[9]; + rotated.z = offset.x * m[2] + offset.y * m[6] + offset.z * m[10]; + const Vec3& origin = information->getPosition(); + Vec3 centre; + centre.x = rotated.x + origin.x; + centre.y = rotated.y + origin.y; + centre.z = rotated.z + origin.z; + return centre; +} + +inline float dot(const Vec3& a, const Vec3& b) +{ + return a.x * b.x + a.y * b.y + a.z * b.z; +} + +} // namespace + +// ELF 0x1FB9D0 (C2) / 0x1FBA90 (C1). The base gets getMaxNBots (IAISettings slot 0); a second +// getMaxNBots sizes the +0x08 target array (plain operator new[], no checkPointer block here), and +// every bot starts with urgency 0.0f (rodata 0x49CB34) and target 0xFFFFFFFF (`movl $0xffffffff`). +BBAvoid::BBAvoid(unsigned char index, unsigned char queue, BBPAvoidCollision* pattern, UrgeCurve* curve, + float* modifiers) + : BotBehaviour(modifiers, curve, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_targets = new unsigned int[count]; + for (int i = 0; i < count; ++i) + { + m_urgency[i] = 0.0f; + m_targets[i] = 0xFFFFFFFFu; + } +} + +// ELF 0x1FBB50 (D2) / 0x1FBBA0 (D1) / 0x1FBBF0 (D0): delete[] +0x08 when set, then the base. +BBAvoid::~BBAvoid() +{ + if (m_targets) + delete[] m_targets; +} + +// ELF 0x1FBC40 (1,201 insns). +// Not updating: clears the changed flag and keeps the urgency while the pattern runs, else unInits. +// Updating: only a soldier (Information::isOfType(ITSoldier), byte +6 bit 5; AIDLL_r names bit 21 +// ITSoldier in its enum switch 0x100D3010 and asserts "!targetPrimaryInfo->isOfType(ITSoldier)") with a mobile plug-in gets past the first +// tests. Retail quirks kept: two `!isSoldier` blocks can never run (the flag was tested earlier; the +// image reloads the same stack byte); the bot's own Information is used without a null check; so is +// the chosen target's Information before insertBehaviourInformation. +float BBAvoid::calculateUrgency(Bot* bot, bool update, float modifier) +{ + BBPAvoidCollision* const pattern = static_cast(m_pattern); + unsigned int* const targets = m_targets; + + if (!update) + { + // 0x1FBC6A: flags = 0; isInitiated (pattern slot +0x0C) keeps the stored urgency. + m_targetChanged[bot->getBotId()] = false; + if (pattern->isInitiated(bot)) + return m_urgency[bot->getBotId()]; + pattern->unInit(bot); + m_urgency[bot->getBotId()] = 0.0f; + return 0.0f; + } + + // ELF 0x4BA5A4 (d, 0x3F19999A): calculateUrgency(Bot*, bool, float)::radiusTweak. + static float radiusTweak = 0.6f; + + // 0x1FBD00: five Vec3 locals (-0x28, -0x38, -0x48, -0x58, -0x68) start at 0.0f. + Vec3 position = { 0.0f, 0.0f, 0.0f }; + Vec3 speed = { 0.0f, 0.0f, 0.0f }; + Vec3 toObstacle = { 0.0f, 0.0f, 0.0f }; + Vec3 relativeSpeed = { 0.0f, 0.0f, 0.0f }; + Vec3 collisionPoint = { 0.0f, 0.0f, 0.0f }; + + const unsigned int previousTarget = targets[bot->getBotId()]; + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + unsigned int selfPrimary; + if (self->isPrimary()) + selfPrimary = bot->getCurrentEquipment(); + else + selfPrimary = self->getPrimaryObject(bot->getSide()); + self->getName(); // 0x1FBDC1: called, result unused + + float maxUrgency = 0.0f; // -0x208 + float total = 0.0f; // -0x200 + IPIMobile* const mobile = self->getMobile(); + if (!mobile) + { + m_urgency[bot->getBotId()] = total; + return total; + } + const bool isSoldier = self->isOfType(ITSoldier); // testb $0x20, 0x6(info) + if (!isSoldier) + { + m_urgency[bot->getBotId()] = total; + return total; + } + + IPIPhysical* const physical = self->getPhysical(); + position = sphereCentre(self, physical); + const float radius = physical->getSmallestRadius(); // IPIPhysical +0x34 + speed = mobile->getSpeed(); // IPIMobile +0x1C + const float speedMagnitude = std::sqrt(dot(speed, speed)); + // 0x1FBF7E: unreachable (isSoldier is true here); getUnresolvedCollisionHandle is Bot +0x9C. + if (!isSoldier && (3.0f > speedMagnitude || bot->getUnresolvedCollisionHandle() != 0xFFFFFFFFu)) + { + m_urgency[bot->getBotId()] = 0.0f; + return 0.0f; + } + + float lookAhead = mobile->getAvoidCollisionLookAhead(); + if (self->getAIObject()) + { + if (self->getSoldierPose() == SPLying) + lookAhead += lookAhead; // 0x1FCD75: fadd %st(0), %st + else if (self->getSoldierPose() == SPCrouching) + lookAhead *= 1.5f; // rodata 0x49CDC0 + } + // 0x1FC013: (flags & 0x10) != 0, plus 2; collisionPredicted never reads it. + const int predictMode = (self->isOfType(ITAir)) + 2; + + unsigned int changeTarget = bot->getChangeTarget(); + Information* const changeInformation = informationManager->getInformation(changeTarget); + if (changeInformation && !changeInformation->isPrimary()) + changeTarget = changeInformation->getPrimaryObject(bot->getSide()); + unsigned int repairTarget = bot->getRepairTarget(); + Information* const repairInformation = informationManager->getInformation(repairTarget); + if (repairInformation && !repairInformation->isPrimary()) + repairTarget = repairInformation->getPrimaryObject(bot->getSide()); + + // 0x1FC0DF: the obstacle handles are BotNavigation +0x58 (std::vector, filled by + // updateObstacles); the count is taken once before the loop, the data pointer on every pass. + // ELF 0x1FC0DF: getBotNavigation (slot +0xFC), then `lea 0x58(%eax)`. + const std::vector& obstacles = bot->getBotNavigation()->getObstacles(); + + const unsigned int obstacleCount = static_cast(obstacles.size()); + for (unsigned int i = 0; i < obstacleCount; ++i) + { + const unsigned int handle = obstacles[i]; + Information* const obstacle = informationManager->getInformation(handle); + if (!obstacle) + continue; + IPIMobile* const obstacleMobile = obstacle->getMobile(); + if (obstacle->getObjectSpawnerHolding() + && obstacle->getObjectSpawner(bot->getSide()) == bot->getCurrentEquipment()) + continue; + unsigned int obstaclePrimary = handle; + if (!obstacle->isPrimary()) + obstaclePrimary = obstacle->getPrimaryObject(bot->getSide()); + IPIPhysical* const obstaclePhysical = obstacle->getPhysical(); + if (!obstaclePhysical || selfPrimary == obstaclePrimary || handle == repairTarget || handle == changeTarget + || handle == bot->getWantedRepairTarget() || obstacle->isOfType(ITSoldier)) + continue; + + // 0x1FC5DB: obstacle sphere centre minus own centre. + const Vec3 obstacleCentre = sphereCentre(obstacle, obstaclePhysical); + toObstacle.x = obstacleCentre.x - position.x; + toObstacle.y = obstacleCentre.y - position.y; + toObstacle.z = obstacleCentre.z - position.z; + // 0x1FC737: unreachable (isSoldier): an obstacle behind a moving non-soldier is ignored. + if (!isSoldier && 0.0f > dot(toObstacle, speed)) + continue; + + Vec3 obstacleSpeed = { 0.0f, 0.0f, 0.0f }; // -0x178 + if (obstacleMobile) + obstacleSpeed = obstacleMobile->getSpeed(); + relativeSpeed.x = obstacleSpeed.x - speed.x; + relativeSpeed.y = obstacleSpeed.y - speed.y; + relativeSpeed.z = obstacleSpeed.z - speed.z; + const float relativeSpeedSq = dot(relativeSpeed, relativeSpeed); // -0x254 + float radii = radius + obstaclePhysical->getSmallestRadius(); + if (isSoldier) + radii *= radiusTweak; // fmuls 0x74E0(%ebx) + const float obstacleHealth = obstaclePhysical->getHealth(); // IPIPhysical +0x14 + const float bailValue = IBotManager::instance->getVehicleBailValue(); // +0x68 + + IPIArmament* const armament = self->getArmament(); + WeaponInfo* activeWeapon = 0; + if (armament && armament->getActiveWeapon() != -1) + activeWeapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + + // 0x1FC8B1: flee a vehicle whose health is under the bail value, or one with type flag + // 0x02000000 (byte +7 bit 1), unless the active weapon is of type 4. [INFERRED] name `flee`. + bool flee = false; + if (isSoldier) + { + if (bailValue > obstacleHealth || obstacle->isOfType(ITObstacle)) + { + if (!activeWeapon || activeWeapon->getWeaponType() != 4) + flee = true; + } + } + if (isSoldier && !flee && 4.0f > dot(obstacleSpeed, obstacleSpeed)) + continue; + + const float distance = std::sqrt(dot(toObstacle, toObstacle)); // -0x268 + // 0x1FC978: max(r, min(r + 4.0f, 10.0f)) with two getSmallestRadius calls (fcmovnbe, fcmovbe). + const float smallestRadius = obstaclePhysical->getSmallestRadius(); + float fleeDistance = obstaclePhysical->getSmallestRadius() + 4.0f; + if (fleeDistance > 10.0f) + fleeDistance = 10.0f; + if (fleeDistance <= smallestRadius) + fleeDistance = smallestRadius; + + if (flee) + { + if (fleeDistance > distance) + { + maxUrgency = 100.0f; // rodata 0x49CB5C + total += maxUrgency; + float strength = (fleeDistance - distance) / 5.0f + 0.5f; + if (strength <= 1.0f) + strength = 1.0f; + targets[bot->getBotId()] = handle; + Vec3 zeroPoint = { 0.0f, 0.0f, 0.0f }; // -0x168 + Vec3 zeroSpeed = { 0.0f, 0.0f, 0.0f }; // -0x158 + pattern->init(bot, zeroPoint, handle, zeroSpeed, strength); + } + continue; + } + + float timeToCollision = 0.0f; // -0x1EC; [CHOSEN] initialised, the image leaves it to collisionPredicted + const float predicted = collisionPredicted(toObstacle, relativeSpeed, predictMode, lookAhead, radii, + collisionPoint, timeToCollision); + if (!(predicted > 0.0f)) + continue; + // 0x1FCB3C: the image squares 3.0f at run time (flds 3; fmul %st(0), %st). + const float minRelativeSpeed = 3.0f; + if (relativeSpeedSq < minRelativeSpeed * minRelativeSpeed) + continue; + float divisor; + if (1.1920929e-07f > timeToCollision) // rodata 0x49CC7C (FLT_EPSILON) + divisor = 1.0f; + else + divisor = std::sqrt(dot(toObstacle, toObstacle)); + const float mass = obstacle->getPhysical()->getMass(); // IPIPhysical +0x4C + const float value = mass * std::sqrt(dot(relativeSpeed, relativeSpeed)) / divisor * predicted; + total += value; + if (value > maxUrgency) + { + maxUrgency = value; + targets[bot->getBotId()] = handle; + pattern->init(bot, collisionPoint, handle, relativeSpeed, timeToCollision); + } + } + + Vec3 grenadePosition = { 0.0f, 0.0f, 0.0f }; // -0x1E8 + if (isSoldier && total == 0.0f) + { + // 0x1FC577: BotNavigation::getGrenadeWarning (0x195310) answers `seta`: the warning time is + // still inside the limit at rodata 0x49CCB8 (PLT 0x17E9E0, called at 0x1FC59C, `test al`). + double grenadeTime = 0.0; + const bool grenadeWarning = bot->getBotNavigation()->getGrenadeWarning(grenadePosition, grenadeTime); + if (grenadeWarning) + { + Vec3 zero = { 0.0f, 0.0f, 0.0f }; // -0x1D8, passed twice + pattern->init(bot, zero, 0xFFFFFFFFu, zero, 0.0f); + m_urgency[bot->getBotId()] = 1000.0f; // rodata 0x49CF48 + return 1000.0f; + } + } + (void)grenadePosition; + + // 0x1FC26D: IAIPlayer +0x0C getPlayer, then world::IPlayer +0x2B8 getBlurValue, +0x140 getIsGassed. + world::IPlayer* const player = bot->getPlayer()->getPlayer(); + if (player->getBlurValue() > 0.0f && player->getIsGassed()) + { + Vec3 zero = { 0.0f, 0.0f, 0.0f }; + pattern->init(bot, zero, 0xFFFFFFFFu, zero, 0.0f); + m_urgency[bot->getBotId()] = 1000.0f; + return 1000.0f; + } + + if (total == 0.0f) + { + // 0x1FC2B6: the changed flag takes isInitiated, then unInit and urgency 0. + const bool initiated = pattern->isInitiated(bot); + m_targetChanged[bot->getBotId()] = initiated; + pattern->unInit(bot); + m_urgency[bot->getBotId()] = 0.0f; + return 0.0f; + } + + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders()) + total *= bot->getMemory()->m_float8; + if (self->isOfType(ITSoldier)) + { + // 0x1FC456: IBFTimer +0x08 minus the double at CommunicationAgent +0x60 (fsubl 0x60(%eax)), + // compared with 5.0f (rodata 0x49CDAC); a recent time doubles the total. + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + CommunicationAgent* const communication = bot->getCommunicationAgent(); + const double since = communication->getDouble96(); + if (now - since < 5.0f) + total += total; + } + + m_urgency[bot->getBotId()] = modifier * total; + m_targetChanged[bot->getBotId()] = previousTarget != targets[bot->getBotId()]; + // 0x1FC3DF: no null check on the target's Information (retail). + Information* const target = informationManager->getInformation(targets[bot->getBotId()]); + bot->insertBehaviourInformation(0.5f, target->getPosition(), m_index); // Bot +0x8C, rodata 0x49CB44 + return m_urgency[bot->getBotId()]; +} + +// ELF 0x1FCDF0. Closest approach of the relative motion: position `relative` (obstacle minus self), +// velocity `velocity`. Below a relative speed of 0.001 (double, rodata 0x49F4A0, squared at run +// time) there is no collision. `closestTime` is the time of closest approach; a closest distance +// inside sqrt(1.5) * radius gives the entry time t - sqrt(|d^2 - 1.5 r^2|) / |v|, written to `time`; +// inside [0, lookAhead] the entry point goes to `point` and the answer is 1.0f, else 0.0f. +float BBAvoid::collisionPredicted(Vec3& relative, Vec3& velocity, int, float lookAhead, float radius, Vec3& point, + float& time) +{ + const float radiusSq = radius * radius * 1.5f; // 0x1FCE13: stored back into the argument slot + const float speedSq = velocity.x * velocity.x + velocity.y * velocity.y + velocity.z * velocity.z; + const double minSpeed = 0.001; + if (speedSq < minSpeed * minSpeed) + return 0.0f; + const float speed = std::sqrt(speedSq); + const float inverse = 1.0f / speed; + Vec3 direction; + direction.x = velocity.x * inverse; + direction.y = velocity.y * inverse; + direction.z = velocity.z * inverse; + Vec3 back; + back.x = -relative.x; + back.y = -relative.y; + back.z = -relative.z; + const float closestTime = (direction.x * back.x + direction.y * back.y + direction.z * back.z) / speed; + if (0.0f > closestTime) + return 0.0f; + Vec3 closest; + closest.x = relative.x + velocity.x * closestTime; + closest.y = relative.y + velocity.y * closestTime; + closest.z = relative.z + velocity.z * closestTime; + const float closestSq = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + if (closestSq >= radiusSq) + return 0.0f; + const float entryTime = closestTime - std::sqrt(std::fabs(closestSq - radiusSq)) / speed; + time = entryTime; + if (entryTime > lookAhead || 0.0f > entryTime) + return 0.0f; + point.x = velocity.x * entryTime + relative.x; + point.y = velocity.y * entryTime + relative.y; + point.z = velocity.z * entryTime + relative.z; + return 1.0f; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBAvoid.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBAvoid.h new file mode 100644 index 000000000..83ee45ea1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBAvoid.h @@ -0,0 +1,43 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBAVOID_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBAVOID_H + +#include "../../../../Math/Vec3.h" +#include "BotBehaviour.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BBPAvoidCollision; +class Bot; +class UrgeCurve; + +// ELF: vtable 0x4BA5C0 (13 words), operator new 0x24, package F-infantry. +// No members of its own: operator new 0x24 is sizeof(BotBehaviour). The base +0x08 array holds the +// handle of the obstacle each bot avoids (unsigned int per bot, 0xFFFFFFFF = none); +0x0C is the +// BBPAvoidCollision pattern. +class BBAvoid : public BotBehaviour +{ +public: + BBAvoid(unsigned char, unsigned char, BBPAvoidCollision*, UrgeCurve*, float*); // 0x1FBA90 + virtual ~BBAvoid(); // 0x1FBBA0 + + virtual float calculateUrgency(Bot*, bool, float); // 0x1FBC40, slot +0x28; from the base declaration + + // float: the only caller (calculateUrgency 0x1FCB21) stores st(0) with fstps and compares it + // against 0.0f; every exit loads 0.0f or 1.0f. The int argument is never read. + float collisionPredicted(Vec3&, Vec3&, int, float, float, Vec3&, float&); // 0x1FCDF0 +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBAVOID_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBBridgeRepair.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBBridgeRepair.cpp new file mode 100644 index 000000000..179bf870a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBBridgeRepair.cpp @@ -0,0 +1,342 @@ +// Bridge-repair behaviour (infantry "BridgeRepair" slot of aibehaviours.ai): an engineer (spawn kit 4) +// picks the closest destroyed bridge segment and a valid standing point at one of its two ends. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see +// docs/macos-ai-behaviour-plan.md. + +// static init: ELF 0x1FED10 (__tcf_0 0x1FED70, _GLOBAL__I 0x1FEDA0): 's Init object only. +#include + +#include "../AIBot/SquadManager.h" // requestResponseModifier (ai-bot) +#include "BBBridgeRepair.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadCoordinator.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotBehaviourPattern/BBPBridgeRepair.h" +#include "../AIBotBehaviourPattern/PlanGenerator.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AIDllFrontier.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/SoldierPose.h" +#include "../../../../Math/Vec3.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// Narrow stops for callees that the tree does not declare (or declares with a different +// signature). Each is a one-line swap once the owner declares the method. + +// ai-bot: _ZN4dice3hfe2ai16SquadCoordinator17isRepairRequestedEv (ELF 0x1A49F0, PLT 0x17BB30); +// call: squad->isRepairRequested(). SquadCoordinator.h names the member (+172 m_b172) only. +bool squadIsRepairRequested(SquadCoordinator* squad) +{ + return squad->isRepairRequested(); +} + +// ai-bot: _ZN4dice3hfe2ai16SquadCoordinator19getRepairRequestPosEv (ELF 0x1A4A00, PLT 0x17DB10); +// call: squad->getRepairRequestPos(); the caller reads three floats through the returned address (+176). +const Vec3& squadGetRepairRequestPos(SquadCoordinator* squad) +{ + return squad->getRepairRequestPos(); +} + +// ai-bot: _ZN4dice3hfe2ai12SquadManager23requestResponseModifierEPNS1_11SquadMemberEjNS3_13RequestActionEi +// (ELF 0x1B0390, PLT 0x17A880); call: SquadManager::m_instance->requestResponseModifier( +// bot->getSquadMember(), segmentHandle, SquadMember::RequestAction(2), bot->getSide()); float in ST0. +float squadManagerRequestResponseModifier(SquadMember* member, unsigned int handle, int action, int side) +{ + return SquadManager::m_instance->requestResponseModifier(member, handle, action, side); +} + +// ai-strategic: _ZN4dice3hfe2ai24AIStrategicObjectManager32getClosestDestroyedBridgeSegmentENS0_4Vec3EbiRS3_Rf +// (ELF 0x349ED0, PLT 0x185180): the image returns the segment's IAIObject pointer, and this caller +// calls slot +0xD0 (IAIObject::getHandle) on it. +IAIObject* strategicClosestDestroyedBridgeSegment(AIStrategicObjectManager* manager, Vec3 position, + bool repairRequested, int side, Vec3& direction, + float& distance) +{ + return manager->getClosestDestroyedBridgeSegment(position, repairRequested, side, direction, distance); +} + +inline float lengthSquared(float x, float y, float z) +{ + return x * x + y * y + z * z; +} + +} // namespace + +// ELF 0x1FD180 (C2) / 0x1FD6C0 (C1). The base gets getMaxNBots (IAISettings slot 0); the empty +// vector at +0x24 is zeroed; three getNBattleStrengths-sized (slot +0x34) arrays go to +0x30/+0x34/ +// +0x38 (checkPointer'd, not initialised) before the index/queue/pattern stores; a getMaxNBots +// array goes to +0x08 and every base urgency (+0x10) is set to 0.0f (rodata 0x49CB34). +BBBridgeRepair::BBBridgeRepair(unsigned char index, unsigned char queue, PlanGenerator* pattern, UrgeCurve* curve, + float* modifiers) + : BotBehaviour(modifiers, curve, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_unknown30 = checkPointer(new int[static_cast(CommonSingletonServer::m_iaiSettings)->getNBattleStrengths()]); + m_unknown34 = checkPointer(new int[static_cast(CommonSingletonServer::m_iaiSettings)->getNBattleStrengths()]); + m_unknown38 = checkPointer(new int[static_cast(CommonSingletonServer::m_iaiSettings)->getNBattleStrengths()]); + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_targets = checkPointer(new unsigned int[count]); + for (int i = 0; i < count; ++i) + m_urgency[i] = 0.0f; +} + +// ELF 0x1FDC00 (D2) / 0x1FDCB0 (D1) / 0x1FDD60 (D0): delete[] +0x08, +0x30, +0x34, +0x38 when set, +// then the vector at +0x24 (default_alloc deallocate) and the base. +BBBridgeRepair::~BBBridgeRepair() +{ + if (m_targets) + delete[] m_targets; + if (m_unknown30) + delete[] m_unknown30; + if (m_unknown34) + delete[] m_unknown34; + if (m_unknown38) + delete[] m_unknown38; +} + +// ELF 0x1FE2E0. +float BBBridgeRepair::calculateUrgency(Bot* bot, bool update, float urgencyScale) +{ + unsigned int* const segmentHandles = m_targets; + PlanGenerator* const pattern = m_pattern; + + if (!update) + { + // 0x1FE304..0x1FE460: keep the current choice while its segment Information exists. + if (informationManager->getInformation(segmentHandles[bot->getBotId()])) + { + m_targetChanged[bot->getBotId()] = false; + if (!pattern->isInitiated(bot)) // PlanGenerator slot +0x0C + m_urgency[bot->getBotId()] = 0.0f; + } + else + { + // 0x1FE3C7: fucompi against 0.0f, setp|setne (unordered counts as changed). + m_targetChanged[bot->getBotId()] = m_urgency[bot->getBotId()] != 0.0f; + m_urgency[bot->getBotId()] = 0.0f; + pattern->unInit(bot); // PlanGenerator slot +0x10 + } + return m_urgency[bot->getBotId()]; + } + + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); // Bot +0xD8 + const unsigned int botId = bot->getBotId(); + const Vec3 botPosition = info->getPosition(); // Information slot +0x30 + int weaponIndex = -1; + // 0x1FE4EF: retail quirk, getNBattleStrengths (IAISettings +0x34) is called and its result dropped. + static_cast(CommonSingletonServer::m_iaiSettings)->getNBattleStrengths(); + + // 0x1FE508: virtual isApplicable (slot +0x34); then the soldier (0x200000) or 0x40 type flag. + if (isApplicable(info, bot) && + (info->isOfType(ITSoldier) || info->isOfType(ITGround))) + { + if (info->isOfType(ITSoldier) && info->getSoldierPose() == SPSwimming) + { + // 0x1FEBF0 + m_targetChanged[botId] = true; + pattern->unInit(bot); + m_urgency[botId] = 0.0f; + return 0.0f; + } + + // 0x1FE54B: the soldier's own Information (side from Bot +0xE0 first), its weapon list + // copied, and the index of the first weapon of type 1 (-1 when none). + const int side = bot->getSide(); + Information* const soldierInfo = + informationManager->getInformation(bot->getPlayer()->getSoldier()->getInformation(side)); + std::vector weapons = soldierInfo->getArmament()->getWeapons(); + for (unsigned int i = 0; i < weapons.size(); ++i) + { + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (weapon && weapon->getWeaponType() == 1) + { + weaponIndex = i; + break; + } + } + + SquadMember* const member = bot->getSquadMember(); // Bot +0x140 + SquadCoordinator* const squad = member->getSquad(); + const bool repairRequested = squadIsRepairRequested(squad); + Vec3 direction = {0.0f, 0.0f, 0.0f}; + bool nearRequest = false; + Vec3 standPosition = {0.0f, 0.0f, 0.0f}; + Vec3 segmentEnd = {0.0f, 0.0f, 0.0f}; + float distance; + const int segmentSide = bot->getSide(); + IAIObject* const segment = strategicClosestDestroyedBridgeSegment( + AIStrategicObjectManager::getInstance(), info->getPosition(), repairRequested, segmentSide, direction, + distance); + + // 0x1FE784: continue only when |direction|^2 > 0.01f (rodata 0x49CB30; ja). + if (segment && lengthSquared(direction.x, direction.y, direction.z) > 0.01f) + { + const unsigned int segmentHandle = segment->getHandle(1); // IAIObject +0xD0 + // 0x1FE85F: retail quirk, a stale handle dereferences a null Information. + const Vec3 segmentPosition = informationManager->getInformation(segmentHandle)->getPosition(); + if (repairRequested) + { + const Vec3& requestPosition = squadGetRepairRequestPos(squad); + // 0x1FEBAE: rodata 0x49CF6C 2500.0f. + if (lengthSquared(requestPosition.x - segmentPosition.x, requestPosition.y - segmentPosition.y, + requestPosition.z - segmentPosition.z) < 2500.0f) + nearRequest = true; + } + // 0x1FE889: fcmove picks 10000.0f (rodata 0x49F4C0) near a request, else 2500.0f; + // jbe fails when limit <= distance (and when unordered). + const float limit = nearRequest ? 10000.0f : 2500.0f; + if (distance < limit && segmentHandle != 0xFFFFFFFFu) + { + standPosition = segmentPosition; + if (getBridgeCoordinate(segmentHandle, direction, bot, botPosition, standPosition, segmentEnd)) + { + // 0x1FE985: fmuls rodata 0x49CC8C 20.0f. + m_urgency[botId] = urgencyScale * 20.0f; + m_targetChanged[botId] = segmentHandles[botId] != segmentHandle; + segmentHandles[botId] = segmentHandle; + static_cast(pattern)->init(segmentHandles[botId], weaponIndex, direction, bot, + nearRequest, standPosition, segmentEnd); + float* const urgency = m_urgency; + const int responseSide = bot->getSide(); + urgency[botId] = squadManagerRequestResponseModifier(bot->getSquadMember(), segmentHandle, 2, + responseSide) * + urgency[botId]; + if (nearRequest) + m_urgency[botId] *= 2.0f; // 0x1FEAF0: fadd %st(0),%st + return m_urgency[bot->getBotId()]; + } + } + } + + // 0x1FE78E (the copied weapon list is freed after this) + m_urgency[botId] = 0.0f; + m_targetChanged[botId] = segmentHandles[botId] != 0xFFFFFFFFu; + segmentHandles[botId] = 0xFFFFFFFFu; + pattern->unInit(bot); + return 0.0f; + } + + // 0x1FEC3B + m_urgency[botId] = 0.0f; + m_targetChanged[botId] = segmentHandles[botId] != 0xFFFFFFFFu; + segmentHandles[botId] = 0xFFFFFFFFu; + pattern->unInit(bot); + return 0.0f; +} + +// ELF 0x1FECB0: bot->getPlayer() (+0xBC) alive (+0x24), not getManDown (+0x1B0), and the +// player's getSpawnKit (+0x44) == 4. +bool BBBridgeRepair::isApplicable(Information*, Bot* bot) +{ + if (!bot->getPlayer()->getIsAlive()) + return false; + if (bot->getManDown()) + return false; + return bot->getPlayer()->getSpawnKit() == 4; +} + +// ELF 0x1FDE20: the two candidate ends of the segment are bridgePosition +/- direction * radius +// (segment Information's IPIPhysical::getRadius, slot +0x2C; a stale handle dereferences null, retail +// quirk). Each end is raised by 1.5f (rodata 0x49CDC0) and stepped along its direction up to ten +// times until the squad accepts it; the end closer to botPosition wins. bridgePosition receives the +// stand point, segmentEnd the unraised end. +bool BBBridgeRepair::getBridgeCoordinate(unsigned int segmentHandle, Vec3 direction, Bot* bot, Vec3 botPosition, + Vec3& bridgePosition, Vec3& segmentEnd) +{ + bot->getBotId(); // 0x1FDE5E: result unused (retail quirk) + const Vec3 forward = direction; + const Vec3 backward = {-forward.x, -forward.y, -forward.z}; // xorl $0x80000000 per component + const float radius = informationManager->getInformation(segmentHandle)->getPhysical()->getRadius(); + + Vec3 forwardEnd = {forward.x * radius + bridgePosition.x, forward.y * radius + bridgePosition.y, + forward.z * radius + bridgePosition.z}; + Vec3 backwardEnd = {backward.x * radius + bridgePosition.x, backward.y * radius + bridgePosition.y, + backward.z * radius + bridgePosition.z}; + const Vec3 forwardStart = forwardEnd; + const Vec3 backwardStart = backwardEnd; + + SquadMember* const member = bot->getSquadMember(); // Bot +0x140 + SquadCoordinator* const squad = member->getSquad(); + forwardEnd.y += 1.5f; + backwardEnd.y += 1.5f; + + bool forwardValid = false; + int tries = 0; + do + { + if (squad->isValidPosition(member, forwardEnd)) + forwardValid = true; + else + { + ++tries; + forwardEnd.x = forward.x + forwardEnd.x; + forwardEnd.y = forward.y + forwardEnd.y; + forwardEnd.z = forward.z + forwardEnd.z; + } + } + while (tries < 10 && !forwardValid); // 0x1FDFFB: cmpl $9; jg + + bool backwardValid = false; + tries = 0; + do + { + if (squad->isValidPosition(member, backwardEnd)) + backwardValid = true; + else + { + ++tries; + backwardEnd.x = backward.x + backwardEnd.x; + backwardEnd.y = backward.y + backwardEnd.y; + backwardEnd.z = backward.z + backwardEnd.z; + } + } + while (tries < 10 && !backwardValid); + + if (forwardValid) + { + // 0x1FE073: with both valid, the backward end wins when its squared distance to + // botPosition is <= the forward one (fucompi; jbe at 0x1FE154) [INFERRED operand order, + // read from the Ghidra decompile]. + if (backwardValid && + lengthSquared(backwardEnd.x - botPosition.x, backwardEnd.y - botPosition.y, backwardEnd.z - botPosition.z) <= + lengthSquared(forwardEnd.x - botPosition.x, forwardEnd.y - botPosition.y, + forwardEnd.z - botPosition.z)) + { + bridgePosition = backwardEnd; + segmentEnd = backwardStart; + return true; + } + bridgePosition = forwardEnd; + segmentEnd = forwardStart; + return true; + } + if (!backwardValid) + return false; + bridgePosition = backwardEnd; + segmentEnd = backwardStart; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBBridgeRepair.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBBridgeRepair.h new file mode 100644 index 000000000..13009c316 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBBridgeRepair.h @@ -0,0 +1,53 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBBRIDGEREPAIR_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBBRIDGEREPAIR_H + +#include "../../../../Math/Vec3.h" +#include "BotBehaviour.h" + +#include + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class Information; +class PlanGenerator; +class UrgeCurve; + +// ELF: vtable 0x4BA660 (14 words), operator new 0x3C, package F-infantry. +class BBBridgeRepair : public BotBehaviour +{ +public: + BBBridgeRepair(unsigned char, unsigned char, PlanGenerator*, UrgeCurve*, float*); // 0x1FD6C0 + virtual ~BBBridgeRepair(); // 0x1FDCB0 + + virtual float calculateUrgency(Bot*, bool, float); // 0x1FE2E0, slot +0x28; from the base declaration + virtual bool isApplicable(Information*, Bot*); // 0x1FECB0, slot +0x34; bool: 1 only for alive, not man-down, spawn kit 4 + + // ELF 0x1FDE20: bool, returns the movb $1/$0 flag in %al; the only caller tests %al. + bool getBridgeCoordinate(unsigned int, Vec3, Bot*, Vec3, Vec3&, Vec3&); + + // Base m_targets (+0x08) is unsigned int[getMaxNBots]: the bridge segment Information handle + // each bot repairs (-1 when none; calculateUrgency 0x1FE2E0). + +private: + // Constructor 0x1FD180/0x1FD6C0, destructor 0x1FDC00/0x1FDCB0/0x1FDD60. + /* +0x24 */ std::vector m_unknown24; // empty; freed as 4-byte elements; no F reader [UNRESOLVED] + /* +0x30 */ int* m_unknown30; // new [getNBattleStrengths] (IAISettings +0x34), uninitialised; no TU reader [UNRESOLVED] element type + /* +0x34 */ int* m_unknown34; // likewise [UNRESOLVED] + /* +0x38 */ int* m_unknown38; // likewise [UNRESOLVED] +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBBRIDGEREPAIR_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBC4.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBC4.cpp new file mode 100644 index 000000000..62057be0d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBC4.cpp @@ -0,0 +1,156 @@ +// C4 behaviour (infantry "c4" slot of aibehaviours.ai): a bot carrying a C4 kit with charges left +// either blows its placed charge (urgency 100) or places one at an owned control point (500). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see +// docs/macos-ai-behaviour-plan.md. + +// static init: ELF 0x1FF760 (__tcf_0 0x1FF7C0, _GLOBAL__I 0x1FF7F0): 's Init object only. +#include + +#include "BBC4.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadManager.h" +#include "../AIBotBehaviourPattern/BBPC4.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../AIStrategic/SAI.h" +#include "../AIStrategicEntity/AIStrategicObject.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AIDllFrontier.h" +#include "../Main/AIMain.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1FEDC0 (C2) / 0x1FEFB0 (C1): base with getMaxNBots, index/queue/pattern, then +// +0x08 = checkPointer(new[getMaxNBots]) and every base urgency = 0.0f (rodata 0x49CB34). +BBC4::BBC4(unsigned char index, unsigned char queue, PlanGenerator* pattern, UrgeCurve* curve, float* modifiers) + : BotBehaviour(modifiers, curve, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_targets = checkPointer(new unsigned int[count]); + for (int i = 0; i < count; ++i) + m_urgency[i] = 0.0f; +} + +// ELF 0x1FF1A0 (D2) / 0x1FF1F0 (D1) / 0x1FF240 (D0) +BBC4::~BBC4() +{ + if (m_targets) + delete[] m_targets; +} + +// ELF 0x1FF290 (249 insns). +float BBC4::calculateUrgency(Bot* bot, bool active, float) +{ + if (!active) + { + // 0x1FF2B9: `cmpb $0,0x10(%ebp); jne` - an inactive call only clears the slot. + m_urgency[bot->getBotId()] = 0.0f; + return m_urgency[bot->getBotId()]; + } + + // 0x1FF2F5: the bot's current equipment through the information pool (inlined lookup). + Information* info = informationManager->getInformation(bot->getCurrentEquipment()); + float urgency = 0.0f; // -0x168 + bool placed = false; // -0x169 + AIStrategicObject* object = 0; // -0x160 + SAI* sai = IAIMain::m_instance->getSAI(bot->getSide()); // IAIMain +0x3C + + // 0x1FF36E: `testb $0x20,0x6(%esi)` - type flag 0x200000 of the equipment, then the + // behaviour's own isApplicable (slot +0x34). + if (info && info->isOfType(ITSoldier) && isApplicable(info, bot)) + { + // 0x1FF41E: the first weapon of type 4 (C4); w keeps the last lookup when none matches. + std::vector& weapons = info->getArmament()->getWeapons(); + WeaponInfo* weapon = 0; + for (unsigned int i = 0; i < weapons.size(); ++i) + { + weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (weapon && weapon->getWeaponType() == 4) + break; + } + + // 0x1FF4A4: Bot::getC4 (+0x158) by value (sret, BotMain 0x188880). + const Bot::C4State c4 = bot->getC4(); + const Vec3 position = info->getPosition(); // slot +0x30, copied + + if (c4.isPlaced) + { + object = c4.object; + if (c4.placementType == 0) + { + // 0x1FF505: a hostile takeover of the area the charge lies in, then no friendly + // within 15 m (rodata 0x49CDC4) of the charge: blow it. + AIStrategicObject* takeover = 0; + Vec2 takeoverPosition = { 0.0f, 0.0f }; + if (sai->hostileTakeoveInProgress(takeover, takeoverPosition) && c4.object + && c4.object->getIndex() == takeover->getIndex()) + { + if (!SquadManager::m_instance->friendliesCloseTo(c4.position, 15.0f, bot->getSide())) + { + urgency = 100.0f; // rodata 0x49CB5C + placed = true; + } + } + } + } + else + { + // 0x1FF5F0: charges left (WeaponInfo slot +0x14) and inside an owned control point + // (10 m, rodata 0x49CC88): place one, urgency 500 (rodata 0x49F500, cmovne). + placed = false; + if (weapon->getCurrentAmmo() > 0) + { + if (sai->isPosInsideOwnedControlPoint(object, position, 10.0f)) + urgency = 500.0f; + } + } + } + + // 0x1FF378: `flds 0.001; flds urgency; fxch; fucompi; jbe init` - init unless urgency < 0.001. + if (urgency < 0.001f) + m_pattern->unInit(bot); + else + static_cast(m_pattern)->init(bot, placed, object); + + m_urgency[bot->getBotId()] = urgency; + return m_urgency[bot->getBotId()]; +} + +// ELF 0x1FF690: alive, not man down, and an armament holding a type-4 weapon with ammo. +bool BBC4::isApplicable(Information* info, Bot* bot) +{ + IPIArmament* armament = info->getArmament(); // +0x2C, read first + if (!bot->getPlayer()->getIsAlive()) + return false; + if (bot->getManDown()) + return false; + if (!armament) + return false; + + std::vector& weapons = armament->getWeapons(); + for (unsigned int i = 0; i < weapons.size(); ++i) + { + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (weapon && weapon->getWeaponType() == 4 && weapon->getCurrentAmmo() > 0) + return true; + } + return false; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBC4.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBC4.h new file mode 100644 index 000000000..348c880ef --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBC4.h @@ -0,0 +1,38 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBC4_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBC4_H + +#include "BotBehaviour.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class Information; +class PlanGenerator; +class UrgeCurve; + +// ELF: vtable 0x4BA700 (14 words), operator new 0x24, package F-infantry. +// No members of its own: 0x24 is sizeof(BotBehaviour). +class BBC4 : public BotBehaviour +{ +public: + BBC4(unsigned char, unsigned char, PlanGenerator*, UrgeCurve*, float*); // 0x1FEFB0 + virtual ~BBC4(); // 0x1FF1F0 + + virtual float calculateUrgency(Bot*, bool, float); // 0x1FF290, slot +0x28; from the base declaration + virtual bool isApplicable(Information*, Bot*); // 0x1FF690, slot +0x34; bool: 0/1 in %edx -> %eax +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBC4_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBCallForMedic.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBCallForMedic.cpp new file mode 100644 index 000000000..1ae4c2557 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBCallForMedic.cpp @@ -0,0 +1,147 @@ +// Calls for a nearby medic according to travel time and remaining man-down time. + +// static init: ELF 0x1FFEA0 (__tcf_0 0x1FFF00, _GLOBAL__I 0x1FFF30): 's Init object only. +#include + +#include "BBCallForMedic.h" + +#include "../AIUtils/CustomCurve.h" +#include "../AIBot/BotMain.h" +#include "../AIBotBehaviourPattern/BBPCallForMedic.h" +#include "../AIKnowledge/AIInformationGrid.h" +#include "../AIKnowledge/BFInformationEnvironment.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../../Math/Vec3.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// Same-side objects carrying a weapon of type 1 or 3. No virtual destructor in the shipped table. +// [INFERRED] Source placement with its only caller; the weak body follows this TU's initializer. +class MedicatePredicate : public IAIInformationGridPredicate +{ +public: + explicit MedicatePredicate(int side) : m_side(side) {} + + // ELF 0x1FFF50 + virtual bool includeInformation(Information* information) const + { + IPIArmament* armament = information->getArmament(); + if (!armament) + return false; + const std::vector& weapons = armament->getWeapons(); + bool found = false; + for (unsigned int i = 0; i < weapons.size(); ++i) + { + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (weapon) + { + const int type = weapon->getWeaponType(); + found = false; + if (type == 3 || type == 1) + { + found = true; + break; + } + } + } + return information->getSide() == m_side && found; + } + +private: + /* +0x04 */ int m_side; +}; + +// ELF 0x1FF810 (C2), 0x1FF8E0 (C1) +BBCallForMedic::BBCallForMedic(unsigned char index, unsigned char queue, BBPCallForMedic* pattern, + UrgeCurve* curve, float* modifiers) + : BotBehaviour(modifiers, curve, + static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_targets = new unsigned int[count]; + for (int i = 0; i < count; ++i) + { + m_urgency[i] = 0.0f; + m_targetChanged[i] = false; + m_targets[i] = 0xFFFFFFFFu; + } +} + +// ELF 0x1FF9B0 (D2), 0x1FFA00 (D1), 0x1FFA50 (D0) +BBCallForMedic::~BBCallForMedic() +{ + if (m_targets) + delete[] m_targets; +} + +// ELF 0x1FFAA0 +float BBCallForMedic::calculateUrgency(Bot* bot, bool evaluate, float) +{ + if (!evaluate) + { + if (m_pattern->isInitiated(bot) && + informationManager->getInformation(m_targets[bot->getBotId()])) + return m_urgency[bot->getBotId()]; + m_pattern->unInit(bot); + m_urgency[bot->getBotId()] = 0.0f; + return 0.0f; + } + std::vector medics; + Information* equipment = informationManager->getInformation(bot->getCurrentEquipment()); + const Vec3& position = equipment->getPosition(); + const int side = bot->getSide(); + MedicatePredicate predicate(side); + static_cast(AISingletonServer::m_iaiInformationEnvironment) + ->getObjectsWithinRadius(medics, position, 50.0f, side, true, &predicate); + float nearestDistance = 50.0f; + m_targets[bot->getBotId()] = 0xFFFFFFFFu; + for (std::vector::const_iterator i = medics.begin(); i != medics.end(); ++i) + { + Information* medic = informationManager->getInformation(*i); + const Vec3& medicPosition = medic->getPosition(); + const Vec3 delta = {position.x - medicPosition.x, position.y - medicPosition.y, + position.z - medicPosition.z}; + const float distance = std::sqrt(delta.x * delta.x + delta.y * delta.y + delta.z * delta.z); + if (distance < nearestDistance) + { + nearestDistance = distance; + m_targets[bot->getBotId()] = *i; + } + } + static_cast(m_pattern)->init(bot); + Information* medic = informationManager->getInformation(m_targets[bot->getBotId()]); + IPIPhysical* physical = equipment->getPhysical(); + if (medic && physical->getManDownTimeLeft() > 0.0f) + { + const float speed = medic->getMobile()->getMaxSpeed(); + const float travelTime = nearestDistance / speed; + float ratio = travelTime / physical->getManDownTimeLeft(); + if (ratio > 1.0f) + ratio = 1.0f; + const unsigned int index = bot->getBotId(); + m_urgency[index] = 1.0f - SCurve::calculate(ratio); + } + else + m_urgency[bot->getBotId()] = 0.0f; + return m_urgency[bot->getBotId()]; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBCallForMedic.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBCallForMedic.h new file mode 100644 index 000000000..0f4121d57 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBCallForMedic.h @@ -0,0 +1,31 @@ +// Urgency for a medic call while a nearby friendly medic can reach the bot before man-down expires. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBCALLFORMEDIC_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBCALLFORMEDIC_H + +#include "BotBehaviour.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BBPCallForMedic; +class Bot; +class UrgeCurve; + +// ELF: vtable 0x4BA7A0 (13 words), operator new 0x24, package H-deferred. +class BBCallForMedic : public BotBehaviour +{ +public: + BBCallForMedic(unsigned char, unsigned char, BBPCallForMedic*, UrgeCurve*, float*); // 0x1FF8E0 + virtual ~BBCallForMedic(); // 0x1FFA00 + + virtual float calculateUrgency(Bot*, bool, float); // 0x1FFAA0, slot +0x28; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBCALLFORMEDIC_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChange.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChange.cpp new file mode 100644 index 000000000..890b095fe --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChange.cpp @@ -0,0 +1,899 @@ +// Change behaviour: rates the bot's current vehicle (and its seats), getting out on foot, and every +// nearby vehicle and seat (calculateVehicleUrgency), then initialises the BBPChange pattern with the best +// one. Radio requests (message types 0 and 1) and the human player calling for a pick-up weigh in. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see +// docs/macos-ai-behaviour-plan.md. Information flag bits (InformationType, AIDLL_r enum switch +// 0x100D3010): 0x10 ITAir (the air-vehicle tests: altitude, runway), 0x20 ITHelicopter, 0x40 ITGround, +// 0x80 ITNaval, 0x8000 ITMobile, 0x200000 ITSoldier. + +// static init: ELF 0x2038C0 (__tcf_0 0x203920, _GLOBAL__I 0x203950): 's Init object only. +#include + +#include "BBChange.h" +#include "VehicleUrgencyCalculator.h" + +#include "UrgeCurve.h" +#include "../AIUtils/CustomCurve.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotMemory.h" +#include "../AIBot/CommunicationAgent.h" +#include "../AIBot/SquadCoordinator.h" +#include "../AIBot/SquadManager.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotBehaviourPattern/BBPChange.h" +#include "../AIBotBehaviourPattern/PlanGenerator.h" +#include "../AIKnowledge/AIInformationGrid.h" +#include "../AIKnowledge/BFInformationEnvironment.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIStrategicEntity/AIStrategicArea.h" +#include "../AIPathFinding/AerialHeightMap/AerialHeightMap.h" +#include "../AIStrategicMap/BFStrategicEnvironment.h" +#include "../AIUtils/VehicleOccupancy.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AIDllFrontier.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IBotManager.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../../Math/Frustum.h" +#include "../../../../Math/LocalBoundingBox.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +#include +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// ELF 0x203970 (W, this TU): the frustum query filter of runwayClear. +0x04 / +0x08 are the two +// informations runwayClear was given; vtable _ZTVN4dice3hfe2ai56_GLOBAL__N_AI_AIDLL_AI_AIBotBehaviour_ +// BBChange.cppI8HLwd25RunwayObstructedPredicateE. +class RunwayObstructedPredicate : public IAIInformationGridPredicate +{ +public: + RunwayObstructedPredicate(Information* vehicle, Information* other) : m_vehicle(vehicle), m_other(other) {} + + // Neither of the two; flag 0x8000 set, 0x200000 and 0x80 clear. + virtual bool includeInformation(Information* information) const + { + if (information == m_vehicle || information == m_other) + return false; + if (!information->isOfType(ITMobile)) + return false; + if (information->isOfType(ITSoldier)) + return false; + if (information->isOfType(ITNaval)) + return false; + return true; + } + +private: + /* +0x04 */ Information* m_vehicle; + /* +0x08 */ Information* m_other; +}; + +// [CHOSEN, not recovered] helper: the image inlines this check at five sites (radio message types 0 +// and 1): the sender of the list's first message, if that player exists, is human (IAIPlayer slot +// +0x88 false), alive (+0x24) and not man-down (+0x2C). +IAIPlayer* liveHumanSender(const std::list& messages) +{ + IAIPlayer* player = static_cast(CommonSingletonServer::m_iaiPlayerFactory) + ->getPlayerFromId(messages.front().m_senderPlayerId); + if (!player || player->getIsAIPlayer() || !player->getIsAlive() || player->isManDown()) + return 0; + return player; +} + +} // namespace + +// ELF 0x200000 (C2) / 0x200240 (C1). The base gets getMaxNBots (IAISettings slot 0); +0x24/+0x30 empty +// vectors, +0x3C/+0x40 = 0; then index, queue, pattern; +0x08 = checkPointer(new unsigned int[getMaxNBots]) +// and, per bot, urgency (+0x10) = 0.0f (rodata 0x49CB34) and +0x08 = 0xFFFFFFFF. +BBChange::BBChange(unsigned char index, unsigned char queue, PlanGenerator* pattern, UrgeCurve* curve, + float* modifiers) + : BotBehaviour(modifiers, curve, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()), + m_vehicles(), m_runwayObstacles(), m_unknown3C(0), m_unknown40(0) +{ + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_targets = checkPointer(new unsigned int[count]); + for (int i = 0; i < count; ++i) + { + m_urgency[i] = 0.0f; + m_targets[i] = 0xFFFFFFFFu; + } +} + +// ELF 0x200480 (D2) / 0x200530 (D1) / 0x2005E0 (D0): delete[] +0x08, delete +0x3C, delete +0x40 (each +// when set, slot +4), then the vectors (+0x30, +0x24) and the base. +BBChange::~BBChange() +{ + if (m_targets) + delete[] m_targets; + if (m_unknown3C) + delete m_unknown3C; + if (m_unknown40) + delete m_unknown40; +} + +// ELF 0x200770. Ghidra decompile + asm (the locals carry their ELF frame offsets). +float BBChange::calculateUrgency(Bot* bot, bool evaluate, float scale) +{ + unsigned int* const targets = m_targets; + PlanGenerator* const pattern = m_pattern; + + // The fire/move inclinations (Bot +0x190 / +0x18C) split into shares that sum to 1. + float fireShare = 0.0f; // -0x1B4 + float moveShare = 0.0f; // -0x1B8 + int side = bot->getSide(); // -0x1A4 (passed by reference to isMannedByEnemy) + const unsigned int botId = bot->getBotId(); // -0x1BC + bot->getSquadMember(); // ELF 0x2007DC: result unused + const float fire = bot->getFireInclination(); + const float move = bot->getMoveInclination(); + if (move > 0.0f) + { + if (fire > 0.0f) + { + fireShare = fire / (fire + move); + moveShare = move / (fire + move); + } + else + { + moveShare = 1.0f; + } + } + else if (fire > 0.0f) + { + fireShare = 1.0f; + } + else + { + fireShare = 0.5f; // ELF 0x202E03: fsts + fstps of rodata 0x49CB44 + moveShare = 0.5f; + } + + IAIStrategicEnvironment* const strategic = + static_cast(AISingletonServer::m_iaiStrategicEnvironment); + CommunicationAgent* const comm = bot->getCommunicationAgent(); // -0x1C0 + const float* const enemyTypes = strategic->getEnemyTypes(bot); // slot +0x0C, -0x1C4 + const float* const enemyStrengths = strategic->getEnemyStrengths(bot); // slot +0x08, -0x1C8 + + if (!evaluate) + { + // ---- ELF 0x200889: only re-check the bot's current choice. + const unsigned int equipment = bot->getCurrentEquipment(); + const unsigned int soldier = bot->getPlayer()->getSoldier()->getInformation(side); + const bool onFoot = soldier == equipment; // -0x1CD + + if (!onFoot && isBailAllowed(bot)) + { + Information* equipmentInfo = informationManager->getInformation(equipment); // -0x1D4 + float current = calculateVehicleUrgency(bot, equipmentInfo, enemyStrengths, enemyTypes, false, + equipmentInfo, fireShare, moveShare, side) * 2.5f; + if (!equipmentInfo->isPrimary()) + current *= modifyForDriver( + informationManager->getInformation(equipmentInfo->getPrimaryObject(side)), false); + const float getOut = calculateVehicleUrgency(bot, informationManager->getInformation(soldier), + enemyStrengths, enemyTypes, false, equipmentInfo, + fireShare, moveShare, side) * 0.2f; + if (current > getOut) + { + // ELF 0x200A27: keep the current target while it is free and the pattern runs. + Information* target = informationManager->getInformation(targets[botId]); + if (target) + { + if (!target->getUnit()->isOccupied()) + { + if (pattern->isInitiated(bot)) + { + m_targetChanged[botId] = false; + m_urgency[botId] = checkBookings(bot); + return m_urgency[botId]; + } + } + m_targetChanged[botId] = true; // ELF 0x200A80: overwritten at once below (retail) + } + } + else + { + // ELF 0x200B51: get out - the soldier itself is the target. + m_targetChanged[botId] = targets[botId] != soldier; + targets[botId] = soldier; + static_cast(m_pattern)->init(soldier, false, false, bot); + const float ratio = current != 0.0f ? getOut * 0.5f / current : getOut * 0.5f; + m_urgency[botId] = DecleiningSlopeCurve::calculate(ratio) * (scale * 4.0f); + m_urgency[botId] = checkBookings(bot); + return m_urgency[botId]; + } + } + else + { + // ELF 0x200CC0 + Information* target = informationManager->getInformation(targets[botId]); + if (onFoot && target) + { + if (target->getUnit() && !target->getUnit()->isOccupied() && pattern->isInitiated(bot)) + { + m_targetChanged[botId] = false; + m_urgency[botId] = checkBookings(bot); + // ELF 0x200D88: no null test of the equipment information (retail). + Information* equipmentInfo = informationManager->getInformation(equipment); + if (equipmentInfo->isOfType(ITSoldier)) + { + const std::list& calls = + comm->getReceivedMessages(static_cast(1)); + if (!calls.empty() && isCallingVehicle(targets[botId], calls, side)) + static_cast(m_pattern)->setGetInConfirm(true, bot); + } + m_urgency[botId] = checkBookings(bot); + return m_urgency[botId]; + } + m_targetChanged[botId] = true; // ELF 0x200A80 + } + } + + // ELF 0x200A93: drop the choice. + m_targetChanged[botId] = pattern->isInitiated(bot); + targets[botId] = 0xFFFFFFFFu; + pattern->unInit(bot); + m_urgency[botId] = 0.0f; + return 0.0f; + } + + // ---- ELF 0x200E68: full evaluation. + float currentUrgency = 0.0f; // -0x1EC: the current vehicle/seat's own urgency + int seatIterator = 0; // -0x19C, shared by every secondary-object walk below + Vec3 entryPos; // -0x148 + Vec3 bestEntryPos; // -0x138 + entryPos.x = entryPos.y = entryPos.z = -666.0f; // rodata 0x49CC98 + bestEntryPos.x = bestEntryPos.y = bestEntryPos.z = -666.0f; + SquadManager* const squadManager = SquadManager::m_instance; + float orderModifier = 0.0f; // -0x1F4 + bool wasCalled = false; // -0x1F9: the chosen vehicle answered a radio call + bool chooseSoldier = false; // -0x1FA: getting out won + + const unsigned int equipment = bot->getCurrentEquipment(); // -0x1D8 + Information* equipmentInfo = informationManager->getInformation(equipment); // -0x208, no null test + Vec3& pos = equipmentInfo->getPosition(); // -0x20C + IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); // -0x210 + const bool isAir = equipmentInfo->isOfType(ITSoldier); // -0x1FB + bool inArtillery = false; // -0x211 + double artillerySinceStart = 0.0; // -0x198 + int artillerySide = -1; // -0x190 + if (!equipmentInfo->isOfType(ITAir)) + { + // ELF 0x202D27 + if (squadManager->isInArtilleryDangerZone(pos, bot->getSide(), artillerySinceStart, artillerySide) + && artillerySinceStart > 4.0f) + inArtillery = true; + } + + if (!isAir && !isBailAllowed(bot)) + { + // ELF 0x202D10 -> 0x200AB4 + m_targetChanged[botId] = pattern->isInitiated(bot); + targets[botId] = 0xFFFFFFFFu; + pattern->unInit(bot); + m_urgency[botId] = 0.0f; + return 0.0f; + } + + // ELF 0x200FB2: the current vehicle's primary object and its seats. + const unsigned int primary = equipmentInfo->getPrimaryObject(side); + Information* primaryInfo = informationManager->getInformation(primary); // -0x218 + Information* primaryInfoAgain = informationManager->getInformation(equipmentInfo->getPrimaryObject(side)); // -0x21C + unsigned int bestHandle = primary; // -0x1DC + float candidate; // -0x1E4 + int vehicleNumber; // -0x200 + if (equipment == primary) + { + // ELF 0x202C23 + candidate = 2.0f * calculateVehicleUrgency(bot, primaryInfo, enemyStrengths, enemyTypes, false, + equipmentInfo, fireShare, moveShare, side); // fadd st,st + currentUrgency = candidate; + if (0.0f > currentUrgency) + currentUrgency = 0.0f; + vehicleNumber = -1; + if (primaryInfo->getMobile()) + { + vehicleNumber = primaryInfo->getMobile()->getVehicleNumber(); + primaryInfo->getUnit()->getEquipmentType(); // ELF 0x202CEA: result unused + } + } + else + { + candidate = 2.0f * calculateVehicleUrgency(bot, primaryInfo, enemyStrengths, enemyTypes, true, + equipmentInfo, fireShare, moveShare, side); + vehicleNumber = -1; + } + + float radioStrength; // -0x1F8 + bool upsideDown; // -0x212 + if (!isAir && isUpsideDown(primaryInfo, terrain, 0.7071f)) // rodata 0x49F580 + { + candidate = 0.0f; + upsideDown = true; + radioStrength = 1.0f; + if (primaryInfo->isOfType(ITAir) && !primaryInfo->getPhysical()->isInAir()) + { + // ELF 0x202BB9: a grounded air vehicle counts as upright again. + radioStrength = getRadioStrength(primaryInfo, bot); + upsideDown = false; + candidate *= radioStrength; + } + } + else + { + radioStrength = getRadioStrength(primaryInfo, bot); // ELF 0x202BE0 + upsideDown = false; + candidate *= radioStrength; + } + + float best = candidate; // -0x1E8 + Information* bestInfo = primaryInfo; // -0x1E0 + if (!upsideDown) + { + // ELF 0x2028A7: the current vehicle's seats. + unsigned int seatHandle = bestInfo->getFirstSecondaryObject(seatIterator, side); + Information* seat = informationManager->getInformation(seatHandle); // -0x220 + const float driverModifier = modifyForDriver(primaryInfo, primary == equipment); // -0x1F0 + while (seat) + { + if (seatHandle == equipment) + { + // ELF 0x202AE4 + candidate = 2.0f * calculateVehicleUrgency(bot, seat, enemyStrengths, enemyTypes, false, + equipmentInfo, fireShare, moveShare, side) + * driverModifier * radioStrength; + currentUrgency = candidate; + if (0.0f > currentUrgency) + currentUrgency = 0.0f; + } + else + { + candidate = calculateVehicleUrgency(bot, seat, enemyStrengths, enemyTypes, true, + equipmentInfo, fireShare, moveShare, side) + * driverModifier * radioStrength; + } + // ELF 0x202A80: an idle flag-taking squad member prefers an unarmed (+0x2C) vehicle's seats. + if (!isAir && bot->getSquadMember()->isTakingFlag() && bot->getSquadMember()->getIsIdle() + && !primaryInfo->hasArmament()) + candidate *= 5.0f; + if (candidate > best) + { + bestHandle = seatHandle; + bestInfo = seat; + bestEntryPos = entryPos; + best = candidate; + } + seatHandle = primaryInfo->getSecondaryObject(seatIterator, side); + seat = informationManager->getInformation(seatHandle); + } + } + + // ELF 0x201175: getting out, against the radio message type 0 list. + const unsigned int soldier = bot->getPlayer()->getSoldier()->getInformation(side); + const std::list& requests = comm->getReceivedMessages(static_cast(0)); // -0x224 + bool requestValid = false; // -0x225 + if (!requests.empty() && liveHumanSender(requests)) + requestValid = true; + if (soldier != equipment) + { + Information* soldierInfo = informationManager->getInformation(soldier); // -0x22C + candidate = calculateVehicleUrgency(bot, soldierInfo, enemyStrengths, enemyTypes, false, + equipmentInfo, fireShare, moveShare, side) * 0.2f; + if (!requests.empty() && requestValid && !equipmentInfo->isOfType(ITSoldier)) + candidate = 100.0f * requests.front().m_modifier * candidate; + if (!requests.empty() && requestValid && equipmentInfo->isOfType(ITAir)) + candidate = 10000.0f; // rodata 0x49F4C0 + if (inArtillery) + candidate = 10000.0f; + if (bot->isBotStuck() && soldierInfo) + { + bot->setBotStuck(false); + candidate = 10000.0f; + } + AIStrategicArea* area = bot->getSquadMember()->getSquad()->getSquadStrategicAreaAssignment(); + if (area) + { + // ELF 0x201388: getOrderPos (slot +0x14) for 0 and 1; a height step over 3 checks avoidance. + const Vec3 orderPos0 = area->getOrderPos(0, bot->getSide()); + const Vec3 orderPos1 = area->getOrderPos(1, bot->getSide()); + if (std::fabs(orderPos0.y - orderPos1.y) > 3.0f) + { + if (closeAndShouldAvoidVehicles(primaryInfoAgain, primaryInfoAgain->getSide(), bot)) + candidate = 10000.0f; + } + } + if (0.001f > currentUrgency) // rodata 0x49CC94 + candidate = 10000.0f; + soldierInfo->getMobile()->getVehicleNumber(); // ELF 0x201448: results unused + soldierInfo->getUnit()->getEquipmentType(); + if (candidate > best) + { + chooseSoldier = true; + best = candidate; + bestHandle = soldier; + bestInfo = soldierInfo; + } + } + + // ELF 0x20149A: an ordered "change" with an empty order list uses the memory's modifier (+0x08). + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && bot->getOrderList(m_index)->empty()) + orderModifier = bot->getMemory()->m_float8; + else + orderModifier = 1.0f; + + // ELF 0x2014C7: a human (radio message type 1) asks for the vehicle the bot's target belongs to. + bool requestedByHuman = false; // -0x22D + unsigned int requestedPrimary = 0xFFFFFFFFu; // -0x234 + Information* currentTarget = informationManager->getInformation(targets[botId]); + if (currentTarget) + { + requestedPrimary = currentTarget->getPrimaryObject(side); + const std::list& calls = comm->getReceivedMessages(static_cast(1)); + if (!calls.empty() && equipmentInfo->isOfType(ITSoldier)) + { + IAIPlayer* caller = liveHumanSender(calls); + if (caller && caller->getCurrentVehicle()->getPrimaryObject()->getInformation(side) == requestedPrimary) + requestedByHuman = true; + } + } + + unsigned int callingHandle = 0xFFFFFFFFu; // -0x238: the last scanned vehicle's caller state (retail) + if (!chooseSoldier && (requests.empty() || !requestValid) && !equipmentInfo->isOfType(ITAir) + && !inArtillery && !bot->getSquadMember()->isCloseToNonOwnedTarget()) + { + // ---- ELF 0x201AF9: every vehicle around. + m_vehicles.resize(0); + // ELF 0x201B6B: slot +0x14 returns the search radius in st0 (stored at -0x23C). + const float searchRadius = + static_cast(AISingletonServer::m_iaiInformationEnvironment) + ->getHardware(m_vehicles, pos, bot); + bool reachable = false; // -0x241: not reset per vehicle (retail) + const std::list& calls = comm->getReceivedMessages(static_cast(1)); // -0x24C + const float searchRadiusSq = searchRadius * searchRadius; // -0x23C + Information* equipmentInfoAgain = informationManager->getInformation(bot->getCurrentEquipment()); // -0x250 + + for (std::vector::iterator it = m_vehicles.begin(); it != m_vehicles.end(); ++it) + { + callingHandle = 0xFFFFFFFFu; + unsigned int handle = *it; // -0x1A8 (passed by reference to isMannedByEnemy) + if (!calls.empty() && equipmentInfo->isOfType(ITSoldier) + && isCallingVehicle(*it, calls, side)) + callingHandle = *it; + + Information* vehicle = informationManager->getInformation(handle); // -0x254 + if (!vehicle || vehicle == primaryInfoAgain || vehicle->isOfType(ITSoldier)) + continue; + if (requestedByHuman && handle != requestedPrimary) + continue; + if (vehicle->isOfType(ITNaval)) + { + // ELF 0x201CF2: only the vehicle the calling human sits in, airborne and in water. + if (calls.empty()) + continue; + IAIPlayer* caller = liveHumanSender(calls); + if (!caller) + continue; + const unsigned int callerVehicle = + caller->getCurrentVehicle()->getPrimaryObject()->getInformation(side); + Information* callerVehicleInfo = informationManager->getInformation(callerVehicle); + if (handle != callerVehicle || !callerVehicleInfo || !callerVehicleInfo->getPhysical()) + continue; + IPIPhysical* physical = callerVehicleInfo->getPhysical(); + if (!physical->isInAir() || !physical->isInWater()) + continue; + } + if (!vehicle->getAIObject()->getIsAllowedByBots()) + continue; + if (isMannedByEnemy(handle, vehicle, side)) + continue; + + Vec3& vehiclePos = vehicle->getPosition(); // -0x258 + IPIMobile* mobile = vehicle->getMobile(); // -0x248 + if (mobile && !vehicle->isOfType(ITAir)) + { + // ELF 0x202570: no valid navmesh position - only the calling human's vehicle. + const IPIMobile::ValidPos lastValid = mobile->getLastValidPosition(); + if (lastValid.island == 0xFFFFFFFFu) + { + if (calls.empty()) + continue; + IAIPlayer* caller = liveHumanSender(calls); + if (!caller) + continue; + const unsigned int callerPrimary = + caller->getCurrentVehicle()->getPrimaryObject()->getInformation(side); + const unsigned int callerVehicle = caller->getCurrentVehicle()->getInformation(side); + if (handle != callerPrimary || handle != callerVehicle) + continue; + } + } + if (mobile && !vehicle->isOfType(ITAir) && !vehicle->isOfType(ITSoldier) + && isUpsideDown(vehicle, terrain, 0.7071f)) + continue; + + // ELF 0x201E9A: distance falloff, 1 at the bot down to 0 beyond the search radius. + IPIUnit* unit = vehicle->getUnit(); + Vec3 delta; + delta.x = vehiclePos.x - pos.x; + delta.y = vehiclePos.y - pos.y; + delta.z = vehiclePos.z - pos.z; + const float distSq = delta.z * delta.z + delta.y * delta.y + delta.x * delta.x; // -0x240 + float falloff = (searchRadiusSq - distSq * 0.8f) / searchRadiusSq; + if (0.5f <= falloff) + falloff = 0.5f; + float distanceFactor = 0.0f; // -0x25C + if (0.0f <= falloff + 0.5f) + distanceFactor = falloff + 0.5f; + + if (vehicleNumber == -1) + { + reachable = true; // ELF 0x202530 + } + else if (unit) + { + if (unit->useNoPathfindingToGetToObject() || !vehicle->getMobile()) + { + reachable = true; // ELF 0x2024FE + entryPos = unit->getEntryPositionOfNonMobile(); + } + else + { + // ELF 0x201FA9: vehicle number 0, not vehicleNumber (retail). + const IPIMobile::ValidPos& valid = mobile->getLastValidPosition(0); + if (vehicle->getPhysical()) + { + const float radius = vehicle->getPhysical()->getRadius(); + if (equipmentInfoAgain->getPhysical()) + { + const float ownRadius = equipmentInfoAgain->getPhysical()->getRadius(); + Vec3 gap; + gap.x = vehiclePos.x - valid.position.x; + gap.y = vehiclePos.y - valid.position.y; + gap.z = vehiclePos.z - valid.position.z; + reachable = gap.x * gap.x + gap.y * gap.y + gap.z * gap.z + < (radius + ownRadius) * (radius + ownRadius); + } + } + } + } + bool usable; + if (!vehicle->getMobile() || vehicle->isOfType(ITAir)) + usable = true; + else + usable = reachable; + if (!usable || !reachable) + continue; + + // ELF 0x2020CB: the vehicle's primary seat. + radioStrength = getRadioStrength(vehicle, bot); + float urgency = calculateVehicleUrgency(bot, vehicle, enemyStrengths, enemyTypes, true, + equipmentInfo, fireShare, moveShare, side) + * distanceFactor * radioStrength; + candidate = urgency; + if (requestedByHuman) + candidate = urgency * 5.0f; + // ELF 0x2024AD: no null test of the physical plug-in here (the seat loop has one). + if (isAir && 400.0f > distSq && 0.25f > equipmentInfo->getPhysical()->getHealth()) + candidate *= 50.0f; + if (callingHandle != 0xFFFFFFFFu) + candidate *= calls.front().m_modifier; + if (candidate > best) + { + if (!vehicle->isOfType(ITAir) || vehicle->isOfType(ITHelicopter) || runwayClear(vehicle, equipmentInfo, side)) + { + bestHandle = handle; + wasCalled = callingHandle != 0xFFFFFFFFu; + best = candidate; + bestEntryPos = entryPos; + bestInfo = vehicle; + } + } + + // ELF 0x20222D: its seats. + unsigned int seatHandle = vehicle->getFirstSecondaryObject(seatIterator, side); + Information* seat = informationManager->getInformation(seatHandle); + const float driverModifier = modifyForDriver(vehicle, false); // -0x1F0 + while (seat) + { + urgency = calculateVehicleUrgency(bot, seat, enemyStrengths, enemyTypes, true, equipmentInfo, + fireShare, moveShare, side) + * radioStrength * distanceFactor * driverModifier; + candidate = urgency; + if (requestedByHuman) + candidate = urgency * 5.0f; + else if (isAir && 400.0f > distSq && equipmentInfo->getPhysical() + && 0.25f > equipmentInfo->getPhysical()->getHealth()) + candidate = candidate * 50.0f; + if (callingHandle != 0xFFFFFFFFu) + candidate *= calls.front().m_modifier; + if (candidate > best) + { + bestHandle = seatHandle; + wasCalled = callingHandle != 0xFFFFFFFFu; + bestEntryPos = entryPos; + best = candidate; + bestInfo = seat; + } + seatHandle = vehicle->getSecondaryObject(seatIterator, side); + seat = informationManager->getInformation(seatHandle); + } + } + } + + // ---- ELF 0x2015B0: commit the choice. + if (bestHandle == equipment) + { + // ELF 0x201A50: nothing better than staying - refuse a caller and drop the choice. + if (isAir && callingHandle != 0xFFFFFFFFu) + denyGetIn(equipmentInfo, callingHandle, comm); + m_targetChanged[botId] = pattern->isInitiated(bot); + targets[botId] = 0xFFFFFFFFu; + pattern->unInit(bot); + m_urgency[botId] = 0.0f; + return 0.0f; + } + + const bool samePrimary = bestInfo->getPrimaryObject(side) == equipmentInfo->getPrimaryObject(side); // -0x25D + m_targetChanged[botId] = targets[botId] != bestHandle; + targets[botId] = bestHandle; + if (isAir && callingHandle != 0xFFFFFFFFu && !botChoiceInVehicle(targets[botId], callingHandle, side)) + denyGetIn(equipmentInfo, callingHandle, comm); + static_cast(m_pattern)->init(bestHandle, bestEntryPos, samePrimary, wasCalled, bot); + + // ELF 0x2016B2: the 1.0f (rodata 0x49CB2C) is a separate factor of the scale in the image. + const float unitFactor = 1.0f; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + const float ratio = currentUrgency != 0.0f ? best * 0.5f / currentUrgency : best * 0.5f; + m_urgency[botId] = DecleiningSlopeCurve::calculate(ratio) * (unitFactor * scale * 4.0f) * orderModifier; + const double sincePossessed = now - equipmentInfo->getUnit()->getLastPlayerPossesionTime(); // fstpl + if (15.0f > sincePossessed) + m_urgency[botId] *= 6.0f; + + if (chooseSoldier) + { + // ELF 0x201930: bailing out of a damaged vehicle says so on the radio. + Information* current = informationManager->getInformation(bot->getCurrentEquipment()); + if (current) + { + if (IPIPhysical* physical = current->getPhysical()) + { + const float health = physical->getHealth(); + if (IBotManager::instance->getVehicleBailValue() + 0.1f >= health) + comm->sendImmediately(static_cast(0), + static_cast(7), 10, 0); + } + m_urgency[botId] *= 5.0f; + } + } + if (isAir) + { + // ELF 0x201843 + const Vec3& bestPos = bestInfo->getPosition(); + Vec3 delta; + delta.x = bestPos.x - pos.x; + delta.y = bestPos.y - pos.y; + delta.z = bestPos.z - pos.z; + if (delta.x * delta.x + delta.y * delta.y + delta.z * delta.z < 400.0f && equipmentInfo->getPhysical() + && equipmentInfo->getPhysical()->getHealth() < 0.25f) + m_urgency[botId] *= 5.0f; + } + + // ELF 0x2017AC: no null test of the target information (retail). + Information* target = informationManager->getInformation(targets[bot->getBotId()]); + bot->insertBehaviourInformation(0.5f, target->getPosition(), m_index); + m_urgency[botId] = checkBookings(bot); + return m_urgency[botId]; +} + +// ELF 0x2006A0: a positive urgency drops to 0 while the chosen vehicle is booked by someone else +// (Bot::getPlayerId, slot +0xB4). +float BBChange::checkBookings(Bot* bot) +{ + const unsigned int botId = bot->getBotId(); + float urgency = m_urgency[botId]; + Information* target = informationManager->getInformation(m_targets[botId]); + if (target && target->isBooked() && !target->isBookedBy(bot->getPlayerId())) + { + if (m_urgency[botId] > 0.0f) // fcmovnbe against rodata 0x49CB34 + urgency = 0.0f; + } + return urgency; +} + +// ELF 0x202E20: a driver seat recently given up by a player (less than 15 s, rodata 0x49CDC4) keeps +// 1.0f; otherwise by flag 0x80 -> 1.0f, 0x40 -> 0.77f (rodata 0x49F58C), 0x10 -> 0.5f, else 1.0f. +float BBChange::modifyForDriver(Information* vehicle, bool current) +{ + if (!vehicle) + return 1.0f; + IPIUnit* unit = vehicle->getUnit(); + // ELF 0x202E54: the time is taken before the unit's null test (retail order). + const double sincePossessed = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime() + - vehicle->getUnit()->getLastPlayerPossesionTime(); + if (!unit) + return 1.0f; + if (!current && unit->isOccupied()) + return 1.0f; + if (!vehicle->getMobile()) + return 1.0f; + if (15.0f > sincePossessed) + return 1.0f; + if (vehicle->isOfType(ITNaval)) + return 1.0f; + if (vehicle->isOfType(ITGround)) + return 0.77f; + if (vehicle->isOfType(ITAir)) + return 0.5f; + return 1.0f; +} + +// ELF 0x202F00: an orthographic frustum along the aircraft's flattened forward axis (box size x/y +// times 1.2, rodata 0x49F590; near z * -0.6, rodata 0x49CFA4; far z * 12, rodata 0x49F594) must hold +// no obstacle (RunwayObstructedPredicate) for the given side. +bool BBChange::runwayClear(Information* aircraft, Information* other, int side) const +{ + LocalBoundingBox* box = const_cast(aircraft->getPhysical()->getLocalBoundingBox()); + const float sizeX = box->getSize().x; + const float sizeZ = box->getSize().z; + const float sizeY = box->getSize().y; + aircraft->getPosition(); // ELF 0x202F6F: slot +0x30, result unused + + // ELF 0x202F7D: the matrix is zeroed (16 x 0.0f) before the copy, then row 2's y is cleared and the + // rows are re-orthonormalised: row 1 receives the third axis, rows 2 and 0 are rewritten. + Mat4 transform; + for (int i = 0; i < 16; ++i) + transform.m[i] = 0.0f; + transform = aircraft->getTransformation(); + transform.m[9] = 0.0f; + reinterpret_cast(&transform.m[4])->makeOrthonormalBasis(*reinterpret_cast(&transform.m[8]), + *reinterpret_cast(&transform.m[0])); + + const float widthScale = 1.2f; + const float farScale = 12.0f; + Frustum frustum; + frustum.setOrtho(sizeX * widthScale, sizeY * widthScale, sizeZ * -0.6f, sizeZ * farScale, transform); + + m_runwayObstacles.resize(0); + RunwayObstructedPredicate predicate(aircraft, other); + static_cast(AISingletonServer::m_iaiInformationEnvironment) + ->getObjectsWithinFrustum(m_runwayObstacles, frustum, side, true, &predicate); + return m_runwayObstacles.size() == 0; +} + +// ELF 0x203210: 1.0f for flag 0x200000, else 1.0f squared (fmul st,st of rodata 0x49CB2C). +float BBChange::getRadioStrength(Information* vehicle, Bot*) const +{ + const float strength = 1.0f; + if (vehicle->isOfType(ITSoldier)) + return strength; + return strength * strength; +} + +// ELF 0x203240: a vehicle of another side (Information slot +0x44) that is occupied for our side. +bool BBChange::isMannedByEnemy(unsigned int& handle, Information* vehicle, int& side) const +{ + bool manned = false; + if (vehicle->getSide() != side && vehicleOccupied(handle, side)) + manned = true; + return manned; +} + +// ELF 0x2032A0: the transformation's m[5] (row 1, y; +0x14) below 0.01f (rodata 0x49CB30). The terrain +// and the threshold argument are not read. +bool BBChange::isUpsideDown(Information* vehicle, IAITerrain*, float) const +{ + return 0.01f > vehicle->getTransformation().m[5]; +} + +// ELF 0x2032E0: always true while the bot has its soldier information, except an air vehicle (flag +// 0x10) that is primary and between 2 and 12 (rodata 0x49CC74 / 0x49F594) above the aerial height map. +bool BBChange::isBailAllowed(Bot* bot) const +{ + Information* equipment = informationManager->getInformation(bot->getCurrentEquipment()); + Information* soldier = + informationManager->getInformation(bot->getPlayer()->getSoldier()->getInformation(bot->getSide())); + if (!soldier) + return false; + if (equipment->isPrimary()) + { + // ELF 0x2033D3: the position and two unused queries, then the altitude test. + const Vec3& position = equipment->getPosition(); + equipment->getUnit()->useNoPathfindingToGetToObject(); + equipment->isPrimary(); + if (equipment->isOfType(ITAir)) + { + const float altitude = AerialHeightMap::m_instance->getAltitude(position); + if (altitude > 2.0f && 12.0f > altitude) + return false; + } + } + // ELF 0x2033A1: both outcomes of the remaining tests answer true (retail). + if (equipment->getMobile()) + return true; + if (equipment->isPrimary()) + return true; + return true; +} + +// ELF 0x203460: a not-yet-handled (m_flag16) message whose sender owns the vehicle or one of its seats +// (IAIObject slot +0x148, inlined Information::getPlayerId). False when the vehicle is manned by an enemy. +bool BBChange::isCallingVehicle(unsigned int handle, const std::list& messages, int side) const +{ + Information* vehicle = informationManager->getInformation(handle); + int seatIterator = 0; + if (isMannedByEnemy(handle, vehicle, side)) + return false; + for (std::list::const_iterator it = messages.begin(); it != messages.end(); ++it) + { + if (it->m_flag16) + continue; + if (vehicle->getAIObject()->getPlayerId() == it->m_senderPlayerId) + return true; + Information* seat = informationManager->getInformation(vehicle->getFirstSecondaryObject(seatIterator, side)); + while (seat) + { + if (seat->getAIObject()->getPlayerId() == it->m_senderPlayerId) + return true; + seat = informationManager->getInformation(vehicle->getSecondaryObject(seatIterator, side)); + } + } + return false; +} + +// ELF 0x203610: after a confirmed get-in request (message type 1), a caller closer than 15 (225 squared, +// rodata 0x49CF4C) hears message 7 on channel 6, priority 3, delay 1.0f, -1. +void BBChange::denyGetIn(Information* vehicle, unsigned int caller, CommunicationAgent* comm) const +{ + if (!comm->generalConfirmReceivedMessage(static_cast(1))) + return; + // ELF 0x20366C: no null test of the caller's information (retail). + const Vec3 callerPos = informationManager->getInformation(caller)->getPosition(); + const Vec3 vehiclePos = vehicle->getPosition(); + Vec3 delta; + delta.x = vehiclePos.x - callerPos.x; + delta.y = vehiclePos.y - callerPos.y; + delta.z = vehiclePos.z - callerPos.z; + if (delta.x * delta.x + delta.y * delta.y + delta.z * delta.z < 225.0f) + comm->enqueueRadioMessage(static_cast(7), static_cast(6), 3, 1.0f, -1); +} + +// ELF 0x203740: true when the bot's target is the calling vehicle's primary object or one of its seats. +bool BBChange::botChoiceInVehicle(unsigned int target, unsigned int caller, int side) const +{ + Information* callerPrimary = + informationManager->getInformation(informationManager->getInformation(caller)->getPrimaryObject(side)); + if (callerPrimary == informationManager->getInformation(target)) + return true; + int seatIterator; // ELF -0x10: not initialised (getFirstSecondaryObject sets it) + unsigned int seatHandle = callerPrimary->getFirstSecondaryObject(seatIterator, side); + Information* seat = informationManager->getInformation(seatHandle); + while (seat) + { + if (seatHandle == target) + return true; + seatHandle = callerPrimary->getSecondaryObject(seatIterator, side); + seat = informationManager->getInformation(seatHandle); + } + return false; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChange.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChange.h new file mode 100644 index 000000000..185ae61fe --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChange.h @@ -0,0 +1,63 @@ +// Change behaviour (the "Change" slot of aibehaviours.ai): picks the vehicle or seat a bot should get +// into (or back out of) and hands it to the BBPChange pattern. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see +// docs/macos-ai-behaviour-plan.md. Virtual functions are in ELF vtable slot order (vtable check). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBCHANGE_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBCHANGE_H + +#include +#include +#include "BotBehaviour.h" + +namespace dice { +namespace hfe { + +namespace ai { + +struct AIRadioMessageInfo; +class Bot; +class CommunicationAgent; +class IAITerrain; +class Information; +class PlanGenerator; +class UrgeCurve; + +// ELF: vtable 0x4BA860 (13 words), operator new 0x44, package F-infantry. +class BBChange : public BotBehaviour +{ +public: + BBChange(unsigned char, unsigned char, PlanGenerator*, UrgeCurve*, float*); // 0x200240 + virtual ~BBChange(); // 0x200530 + + virtual float calculateUrgency(Bot*, bool, float); // 0x200770, slot +0x28; from the base declaration + + float checkBookings(Bot*); // 0x2006A0; float in st0 (flds of the urgency slot) + float modifyForDriver(Information*, bool); // 0x202E20; float in st0 (1.0f / 0.77f / 0.5f) + bool runwayClear(Information*, Information*, int) const; // 0x202F00; bool: sete + movzbl + float getRadioStrength(Information*, Bot*) const; // 0x203210; float in st0 + bool isMannedByEnemy(unsigned int&, Information*, int&) const; // 0x203240; bool byte + bool isUpsideDown(Information*, IAITerrain*, float) const; // 0x2032A0; bool: seta + movzbl + bool isBailAllowed(Bot*) const; // 0x2032E0; 0/1 in eax, both callers test %al + bool isCallingVehicle(unsigned int, const std::list&, int) const; // 0x203460; 0/1, callers test %al + void denyGetIn(Information*, unsigned int, CommunicationAgent*) const; // 0x203610; ELF void + bool botChoiceInVehicle(unsigned int, unsigned int, int) const; // 0x203740; 0/1, the caller tests %al + +private: + // The constructors zero +0x24..+0x40 and the destructors free them (ELF 0x200480 / 0x200530 / 0x2005E0). + // The base +0x08 (m_targets) is the per-bot chosen vehicle or seat (unsigned int[bot], -1 = none). + /* +0x24 */ std::vector m_vehicles; // calculateUrgency: the getHardware list + // runwayClear (a const member) resizes and refills it: [INFERRED] mutable. + /* +0x30 */ mutable std::vector m_runwayObstacles; + // [UNRESOLVED] Nothing in this TU writes these except the constructors' 0; every destructor deletes + // them through vtable slot +4 (the deleting destructor), +0x3C first. The pointee type is + // [CHOSEN, not recovered]: UrgeCurve, a polymorphic type whose delete compiles to the same call. + /* +0x3C */ UrgeCurve* m_unknown3C; + /* +0x40 */ UrgeCurve* m_unknown40; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBCHANGE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeLandingCraft.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeLandingCraft.cpp new file mode 100644 index 000000000..bb740e5db --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeLandingCraft.cpp @@ -0,0 +1,291 @@ +// Landing-craft seat selection and disembark urgency, recovered from libaidll.so. + +// static init: ELF 0x204EA0 (__tcf_0 0x204F00, _GLOBAL__I 0x204F30): 's Init object only. +#include + +#include "BBChangeLandingCraft.h" + +#include "../AIUtils/CustomCurve.h" +#include "VehicleUrgencyCalculator.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotMemory.h" +#include "../AIBot/CommunicationAgent.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotBehaviourPattern/BBPChange.h" +#include "../AIBotBehaviourPattern/BBPChangeLandingCraft.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIStrategicMap/BFStrategicEnvironment.h" +#include "../Main/IBotManager.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../../../../Math/Vec3.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2039C0 (C2) / 0x203A80 (C1); vtable GOT -0xDE0. The BBAvoid shape: the base gets getMaxNBots +// (IAISettings slot 0); a second getMaxNBots sizes the +0x08 target array (plain operator new[]), +// and every bot starts with urgency 0.0f (rodata 0x49CB34) and target 0xFFFFFFFF. +BBChangeLandingCraft::BBChangeLandingCraft(unsigned char index, unsigned char queue, PlanGenerator* pattern, + UrgeCurve* curve, float* modifiers) + : BotBehaviour(modifiers, curve, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_targets = new unsigned int[count]; + for (int i = 0; i < count; ++i) + { + m_urgency[i] = 0.0f; + m_targets[i] = 0xFFFFFFFFu; + } +} + +// ELF 0x203B40 (D2) / 0x203B90 (D1) / 0x203BE0 (D0): delete[] +0x08 when set, then ~BotBehaviour. +BBChangeLandingCraft::~BBChangeLandingCraft() +{ + if (m_targets) + delete[] m_targets; +} + +// ELF 0x203DD0 +float BBChangeLandingCraft::calculateUrgency(Bot* bot, bool evaluate, float) +{ + if (!evaluate) + { + m_urgency[bot->getBotId()] = 0.0f; + const bool initiated = m_pattern->isInitiated(bot); + m_targetChanged[bot->getBotId()] = initiated; + m_pattern->unInit(bot); + const float urgency = checkLandingCraftBookings(bot); + m_urgency[bot->getBotId()] = urgency; + return m_urgency[bot->getBotId()]; + } + std::list unusedObjects; + float fireShare; + float moveShare; + if (bot->getMoveInclination() > 0.0f) + { + if (bot->getFireInclination() > 0.0f) + { + const float fire = bot->getFireInclination(); + const float sum = bot->getMoveInclination() + fire; + fireShare = bot->getFireInclination() / sum; + moveShare = bot->getMoveInclination() / sum; + } + else { fireShare = 0.0f; moveShare = 1.0f; } + } + else if (bot->getFireInclination() > 0.0f) + { fireShare = 1.0f; moveShare = 0.0f; } + else { fireShare = 0.5f; moveShare = 0.5f; } + + const int side = bot->getSide(); + unsigned int bestHandle = bot->getCurrentEquipment(); + Information* current = informationManager->getInformation(bestHandle); + float orderFactor = 1.0f; + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() + && bot->getOrderList(m_index)->empty()) + orderFactor = bot->getMemory()->m_float8; + IAIStrategicEnvironment* strategic = static_cast(AISingletonServer::m_iaiStrategicEnvironment); + const float* types = strategic->getEnemyTypes(bot); + const float* strengths = strategic->getEnemyStrengths(bot); + Information* primary = informationManager->getInformation(current->getPrimaryObject(side)); + IPIMobile* primaryMobile = primary ? primary->getMobile() : 0; + float primaryFactor = 1.0f; + float currentFactor = 1.0f; + const float secondaryFactor = 0.25f; + if (current->isPrimary()) + primary = current; + else if (!primary->getUnit()->isOccupied() && !current->isOfType(ITNaval)) + { + primaryFactor = current->isOfType(ITAir) ? 1.5f : 1.0f; + currentFactor = 0.25f; + } + const bool currentIsPrimary = current == primary; + int iterator = primary->getFirstSecondaryObjectIterator(); + unsigned int handle = current->getPrimaryObject(side); + IPIUnit* primaryUnit = primary->getUnit(); + bool invalidPosition = false; + float best = 0.0f; + float currentUrgency = 0.0f; + Information* candidate = primary; + if (candidate) + { + do + { + const bool isCurrent = current == candidate; + float urgency = calculateVehicleUrgency(bot, candidate, strengths, types, !isCurrent, + current, fireShare, moveShare, side); + urgency *= isCurrent ? currentFactor : (candidate->isPrimary() ? primaryFactor : secondaryFactor); + urgency *= orderFactor; + if (candidate == primary && !primaryUnit->isOccupied() && primaryMobile) + { + const IPIMobile::ValidPos valid = primaryMobile->getLastValidPosition(); + if (valid.island == 0xFFFFFFFFu) + { urgency = 0.0f; invalidPosition = true; } + else urgency += 100.0f; + } + if (isCurrent) + currentUrgency = urgency; + if (urgency > best) + { best = urgency; bestHandle = handle; } + handle = primary->getSecondaryObject(iterator, side); + candidate = informationManager->getInformation(handle); + } while (candidate && !invalidPosition); + } + + bool disembark = false; + const bool air = primary->isOfType(ITAir); + const Vec3& position = current->getPosition(); + bool canDisembark = false; + if (air) + { + SquadMember* member = bot->getSquadMember(); + if (member && currentIsPrimary) + { + const bool close = member->isCloseToNonOwnedTarget(10000.0f, 22500.0f); + const bool alone = isOnlyPrimaryInVehicle(current, side); + if (alone) + canDisembark = member->isCloseToNonOwnedTarget(625.0f, 10000.0f); + else if (close) + { + CommunicationAgent* communication = bot->getCommunicationAgent(); + if (!communication->getSentMessage(static_cast(0))) + communication->enqueueRadioMessage(static_cast(0), + static_cast(7), 10, 0.0f, -1); + } + } + } + else if (IPIPhysical* physical = primary->getPhysical()) + { + Vec3 contact = {0.0f, 0.0f, 0.0f}; + canDisembark = !physical->isInWater() || physical->isTouchingTerrain(contact); + } + if (canDisembark) + { + IPIMobile* mobile = primary->getMobile(); + canDisembark = air || mobile->getSpeedMagnitude() < 2.0f; + const int playerSide = bot->getSide(); + bot->getPlayer()->getSoldier()->getInformation(playerSide); + if (canDisembark) + { + if (air) + disembark = true; + else + { + const Vec3& valid = mobile->getLastValidInfantryPos().position; + const float dx = valid.x - position.x; + const float dy = valid.y - position.y; + const float dz = valid.z - position.z; + disembark = 16.0f > dx * dx + dy * dy + dz * dz; + } + } + } + if (!air && !primary->isOfType(ITSoldier)) + { + Vec3 normal = {0.0f, 0.0f, 0.0f}; + IAITerrain* terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + terrain->getWaterLevel(position.x, position.z); + terrain->getHeight(position.x, position.z); + terrain->getNormal(position.x, position.z, normal); + } + const std::list& messages = bot->getCommunicationAgent()->getReceivedMessages(static_cast(0)); + if (air && !messages.empty()) + disembark = true; + if (current->getPhysical()) + { + const float health = current->getPhysical()->getHealth(); + if (IBotManager::instance->getVehicleBailValue() + 0.1f >= health) + { + disembark = true; + bot->getCommunicationAgent()->sendImmediately(static_cast(0), + static_cast(7), 10, 0); + } + } + if (disembark || invalidPosition) + { + const int playerSide = bot->getSide(); + bestHandle = bot->getPlayer()->getSoldier()->getInformation(playerSide); + const unsigned int botId = bot->getBotId(); + m_targetChanged[botId] = m_targets[bot->getBotId()] != 0xFFFFFFFFu; + m_targets[bot->getBotId()] = 0xFFFFFFFFu; + if (air) + static_cast(m_pattern)->init(bestHandle, false, false, bot); + else + static_cast(m_pattern)->init(bestHandle, false, bot); + primary->getAIObject()->getPhysical(); // ELF 0x2044FC: result discarded. + static_cast(bot)->resetAllControls(true, true, true); + m_urgency[bot->getBotId()] = 4.0f; + } + else if (bestHandle == bot->getCurrentEquipment()) + { + const bool initiated = m_pattern->isInitiated(bot); + m_targetChanged[bot->getBotId()] = initiated; + m_pattern->unInit(bot); + m_targets[bot->getBotId()] = 0xFFFFFFFFu; + m_urgency[bot->getBotId()] = 0.0f; + } + else + { + const unsigned int botId = bot->getBotId(); + m_targetChanged[botId] = m_targets[bot->getBotId()] != bestHandle; + m_targets[bot->getBotId()] = bestHandle; + if (air) + static_cast(m_pattern)->init(bestHandle, true, false, bot); + else + static_cast(m_pattern)->init(bestHandle, true, bot); + const unsigned int urgencyId = bot->getBotId(); + const float ratio = currentUrgency > 0.0f ? (best * 0.5f) / currentUrgency : best * 0.5f; + m_urgency[urgencyId] = DecleiningSlopeCurve::calculate(ratio) * 4.0f; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + const double sincePossessed = now - current->getUnit()->getLastPlayerPossesionTime(); + if (15.0f > sincePossessed) + m_urgency[bot->getBotId()] *= 6.0f; + } + const float urgency = checkLandingCraftBookings(bot); + m_urgency[bot->getBotId()] = urgency; + return m_urgency[bot->getBotId()]; +} + +// ELF 0x203C30 +float BBChangeLandingCraft::checkLandingCraftBookings(Bot* bot) +{ + const unsigned int id = bot->getBotId(); + float urgency = m_urgency[id]; + Information* target = informationManager->getInformation(m_targets[id]); + if (target && target->isBooked() && !target->isBookedBy(bot->getPlayerId())) + if (m_urgency[id] > 0.0f) + urgency = 0.0f; + return urgency; +} + +// ELF 0x203D00 +bool BBChangeLandingCraft::isOnlyPrimaryInVehicle(Information* primary, int side) +{ + int iterator; + Information* seat = informationManager->getInformation(primary->getFirstSecondaryObject(iterator, side)); + while (seat) + { + if (seat->getUnit() && seat->getUnit()->isOccupied()) + return false; + seat = informationManager->getInformation(primary->getSecondaryObject(iterator, side)); + } + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeLandingCraft.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeLandingCraft.h new file mode 100644 index 000000000..70f82508f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeLandingCraft.h @@ -0,0 +1,35 @@ +// Landing-craft seat selection and disembark urgency. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBCHANGELANDINGCRAFT_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBCHANGELANDINGCRAFT_H + +#include "BotBehaviour.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class Information; +class PlanGenerator; +class UrgeCurve; + +// ELF: vtable 0x4BA920 (13 words), operator new 0x24, package G-vehicles. +class BBChangeLandingCraft : public BotBehaviour +{ +public: + BBChangeLandingCraft(unsigned char, unsigned char, PlanGenerator*, UrgeCurve*, float*); // 0x203A80 + virtual ~BBChangeLandingCraft(); // 0x203B90 + + virtual float calculateUrgency(Bot*, bool, float); // 0x203DD0, slot +0x28; from the base declaration + + float checkLandingCraftBookings(Bot*); // 0x203C30 + bool isOnlyPrimaryInVehicle(Information*, int); // 0x203D00 +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBCHANGELANDINGCRAFT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeTeleport.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeTeleport.cpp new file mode 100644 index 000000000..56780e70c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeTeleport.cpp @@ -0,0 +1,217 @@ +// Rates teleporting between the current vehicle's seats and initializes its change pattern. + +// static init: ELF 0x205D70 (__tcf_0 0x205DD0, _GLOBAL__I 0x205E00): 's Init object only. +#include + +#include "BBChangeTeleport.h" + +#include "VehicleUrgencyCalculator.h" +#include "../AIUtils/CustomCurve.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotMemory.h" +#include "../AIBotBehaviourPattern/BBPChangeTeleport.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIStrategicMap/BFStrategicEnvironment.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x204F50 (C2) / 0x205010 (C1); vtable GOT -0x1624. The BBAvoid shape: the base gets getMaxNBots +// (IAISettings slot 0); a second getMaxNBots sizes the +0x08 target array (plain operator new[]), +// and every bot starts with urgency 0.0f (rodata 0x49CB34) and target 0xFFFFFFFF. +BBChangeTeleport::BBChangeTeleport(unsigned char index, unsigned char queue, PlanGenerator* pattern, + UrgeCurve* curve, float* modifiers) + : BotBehaviour(modifiers, curve, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_targets = new unsigned int[count]; + for (int i = 0; i < count; ++i) + { + m_urgency[i] = 0.0f; + m_targets[i] = 0xFFFFFFFFu; + } +} + +// ELF 0x2050D0 (D2) / 0x205120 (D1) / 0x205170 (D0): delete[] +0x08 when set, then ~BotBehaviour. +BBChangeTeleport::~BBChangeTeleport() +{ + if (m_targets) + delete[] m_targets; +} + +// ELF 0x2051C0 +float BBChangeTeleport::calculateUrgency(Bot* bot, bool evaluate, float) +{ + if (!evaluate) + { + m_urgency[bot->getBotId()] = 0.0f; + const bool initiated = m_pattern->isInitiated(bot); + m_targetChanged[bot->getBotId()] = initiated; + m_pattern->unInit(bot); + return m_urgency[bot->getBotId()]; + } + std::list unused; + float fireShare; + float moveShare; + if (bot->getMoveInclination() > 0.0f) + { + if (bot->getFireInclination() > 0.0f) + { + const float fire = bot->getFireInclination(); + const float sum = bot->getMoveInclination() + fire; + fireShare = bot->getFireInclination() / sum; + moveShare = bot->getMoveInclination() / sum; + } + else + { + fireShare = 0.0f; + moveShare = 1.0f; + } + } + else if (bot->getFireInclination() > 0.0f) + { + fireShare = 1.0f; + moveShare = 0.0f; + } + else + fireShare = moveShare = 0.5f; + + const int side = bot->getSide(); + Information* equipment = informationManager->getInformation(bot->getCurrentEquipment()); + equipment->getPrimaryObject(side); + float orderModifier = 1.0f; + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && bot->getOrderList(m_index)->empty()) + orderModifier = bot->getMemory()->m_float8; + IAIStrategicEnvironment* strategic = + static_cast(AISingletonServer::m_iaiStrategicEnvironment); + const float* types = strategic->getEnemyTypes(bot); + const float* strengths = strategic->getEnemyStrengths(bot); + unsigned int bestHandle = bot->getCurrentEquipment(); + float currentModifier; + float secondaryModifier; + float primaryModifier; + if (equipment->isPrimary()) + { + currentModifier = 1.0f; + secondaryModifier = 0.5f; + primaryModifier = 1.0f; + } + else + { + Information* primary = informationManager->getInformation(equipment->getPrimaryObject(side)); + if (primary->getUnit()->isOccupied()) + { + currentModifier = 1.0f; + secondaryModifier = primaryModifier = 0.5f; + } + else + { + if (equipment->isOfType(ITNaval)) + { + currentModifier = 0.5f; + secondaryModifier = 0.65f; + primaryModifier = 1.0f; + } + else if (equipment->isOfType(ITGround)) + { + currentModifier = 0.5f; + secondaryModifier = 0.7f; + primaryModifier = 1.0f; + } + else if (equipment->isOfType(ITAir)) + { + currentModifier = secondaryModifier = 0.5f; + primaryModifier = 1.5f; + } + else + currentModifier = secondaryModifier = primaryModifier = 1.0f; + } + } + bool isPrimary = equipment->isPrimary(); + Information* primary = equipment; + if (!isPrimary) + { + bestHandle = equipment->getPrimaryObject(side); + primary = informationManager->getInformation(bestHandle); + } + float current = calculateVehicleUrgency(bot, primary, strengths, types, !isPrimary, + equipment, fireShare, moveShare, side); + current *= isPrimary ? currentModifier : primaryModifier; + float best = current; + if (!isPrimary) + { + best *= orderModifier; + current = 0.0f; + } + int iterator; + unsigned int handle = primary->getFirstSecondaryObject(iterator, side); + Information* seat = informationManager->getInformation(handle); + while (seat) + { + const bool other = equipment != seat; + // shipped defect: each secondary is rated using the primary information record. + float candidate = calculateVehicleUrgency(bot, primary, strengths, types, other, + equipment, fireShare, moveShare, side); + candidate *= other ? secondaryModifier : currentModifier; + if (other) + candidate *= orderModifier; + else + current = candidate; + if (candidate > best) + { + best = candidate; + bestHandle = handle; + } + handle = primary->getSecondaryObject(iterator, side); + seat = informationManager->getInformation(handle); + } + if (bestHandle == bot->getCurrentEquipment() && fireShare < 0.05f && bot->getLodLevel() != 0) + { + const unsigned int changedIndex = bot->getBotId(); + m_targetChanged[changedIndex] = m_targets[bot->getBotId()] != 0xFFFFFFFFu; + m_targets[bot->getBotId()] = 0xFFFFFFFFu; + static_cast(m_pattern)->init(bestHandle, false, bot); + m_urgency[bot->getBotId()] = 2.0f; + } + else if (bestHandle == bot->getCurrentEquipment()) + { + const bool initiated = m_pattern->isInitiated(bot); + m_targetChanged[bot->getBotId()] = initiated; + m_pattern->unInit(bot); + m_targets[bot->getBotId()] = 0xFFFFFFFFu; + m_urgency[bot->getBotId()] = 0.0f; + } + else + { + const unsigned int changedIndex = bot->getBotId(); + m_targetChanged[changedIndex] = m_targets[bot->getBotId()] != bestHandle; + m_targets[bot->getBotId()] = bestHandle; + static_cast(m_pattern)->init(bestHandle, true, bot); + const unsigned int urgencyIndex = bot->getBotId(); + const float ratio = current > 0.0f ? (best * 0.5f) / current : best * 0.5f; + m_urgency[urgencyIndex] = DecleiningSlopeCurve::calculate(ratio) * 4.0f; + } + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + const double elapsed = now - equipment->getUnit()->getLastPlayerPossesionTime(); + if (elapsed < 15.0f) + { + const unsigned int index = bot->getBotId(); + m_urgency[index] = 6.0f * m_urgency[index]; + } + return m_urgency[bot->getBotId()]; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeTeleport.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeTeleport.h new file mode 100644 index 000000000..c94f3ee08 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeTeleport.h @@ -0,0 +1,31 @@ +// Urgency for changing seats through the teleport change pattern. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBCHANGETELEPORT_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBCHANGETELEPORT_H + +#include "BotBehaviour.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class PlanGenerator; +class UrgeCurve; + +// ELF: vtable 0x4BA9C0 (13 words), operator new 0x24, package G-vehicles. +class BBChangeTeleport : public BotBehaviour +{ +public: + BBChangeTeleport(unsigned char, unsigned char, PlanGenerator*, UrgeCurve*, float*); // 0x205010 + virtual ~BBChangeTeleport(); // 0x205120 + + virtual float calculateUrgency(Bot*, bool, float); // 0x2051C0, slot +0x28; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBCHANGETELEPORT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBDefuseMines.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBDefuseMines.cpp new file mode 100644 index 000000000..e5516cc0b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBDefuseMines.cpp @@ -0,0 +1,260 @@ +// Defuse-mines behaviour (infantry "DefuseMines" slot of aibehaviours.ai): an engineer (spawn kit 4) +// without a mine target looks for the closest hostile mine whose pathfinding position is reachable +// within 35 m. Recovered from libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see +// docs/macos-ai-behaviour-plan.md. + +// static init: ELF 0x207370 (__tcf_0 0x2073D0, _GLOBAL__I 0x207400): 's Init object only. +#include + +#include "BBDefuseMines.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotBehaviourPattern/BBPDefuseMines.h" +#include "../AIBotBehaviourPattern/PlanGenerator.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../AIUtils/checkPointer.h" +#include "../AIKnowledge/AIMineManager.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IAIPathfinding.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/BFGame.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/SoldierPose.h" +#include "../../../../Math/Vec3.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +inline float lengthSquared(float x, float y, float z) +{ + return x * x + y * y + z * z; +} + +} // namespace + +// ELF 0x205E20 (C2) / 0x206280 (C1). The base gets getMaxNBots (IAISettings slot 0); the empty +// vector at +0x24 is zeroed; +0x30 is new [getNBattleStrengths] (slot +0x34) and +0x34 new +// [getMaxNBots], both checkPointer'd, before the index/queue/pattern stores; +0x08 is new +// [getMaxNBots]; then every base urgency (+0x10) is 0.0f (rodata 0x49CB34) and every mine target -1. +BBDefuseMines::BBDefuseMines(unsigned char index, unsigned char queue, PlanGenerator* pattern, UrgeCurve* curve, + float* modifiers) + : BotBehaviour(modifiers, curve, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_unknown30 = checkPointer(new int[static_cast(CommonSingletonServer::m_iaiSettings)->getNBattleStrengths()]); + m_mineTarget = checkPointer(new unsigned int[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_targets = checkPointer(new unsigned int[count]); + for (int i = 0; i < count; ++i) + { + m_urgency[i] = 0.0f; + m_mineTarget[i] = 0xFFFFFFFFu; + } +} + +// ELF 0x2066E0 (D2) / 0x206780 (D1) / 0x206820 (D0): delete[] +0x08, +0x30, +0x34 when set, then the +// vector at +0x24 (default_alloc deallocate) and the base. +BBDefuseMines::~BBDefuseMines() +{ + if (m_targets) + delete[] m_targets; + if (m_unknown30) + delete[] m_unknown30; + if (m_mineTarget) + delete[] m_mineTarget; +} + +// ELF 0x2068C0. Bot slots +0x1F8 setMineTarget / +0x1FC getMineTarget are virtual calls in the image, +// but the Bot interface in AIBot/BotMain.h ends at +0x1DC; [CHOSEN, not recovered] the calls go +// through BotMain (the only Bot implementation, same slots) until ai-bot extends Bot. +float BBDefuseMines::calculateUrgency(Bot* bot, bool update, float urgencyScale) +{ + PlanGenerator* const pattern = m_pattern; + + if (!update) + { + // 0x2068E4..0x206A11: keep the current choice while a mine target is set. + if (m_mineTarget[bot->getBotId()] != 0xFFFFFFFFu) + { + m_targetChanged[bot->getBotId()] = false; + if (!pattern->isInitiated(bot)) // PlanGenerator slot +0x0C + m_urgency[bot->getBotId()] = 0.0f; + } + else + { + // 0x206980: fucompi against 0.0f, setp|setne (unordered counts as changed). + m_targetChanged[bot->getBotId()] = m_urgency[bot->getBotId()] != 0.0f; + m_urgency[bot->getBotId()] = 0.0f; + pattern->unInit(bot); // PlanGenerator slot +0x10 + } + return m_urgency[bot->getBotId()]; + } + + float baseUrgency = 0.0f; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); // Bot +0xD8 + unsigned int mineTarget = 0xFFFFFFFFu; + const unsigned int botId = bot->getBotId(); + const Vec3 botPosition = info->getPosition(); // Information slot +0x30 + int weaponIndex = -1; + // 0x206AAB: retail quirk, getNBattleStrengths (IAISettings +0x34) is called and its result dropped. + static_cast(CommonSingletonServer::m_iaiSettings)->getNBattleStrengths(); + + // 0x206AC4: virtual isApplicable (slot +0x34); then the soldier (0x200000) or 0x40 type flag. + if (isApplicable(info, bot) && + (info->isOfType(ITSoldier) || info->isOfType(ITGround))) + { + if (info->isOfType(ITSoldier) && info->getSoldierPose() == SPSwimming) + { + // 0x207255 + m_targetChanged[botId] = true; + pattern->unInit(bot); + m_urgency[botId] = 0.0f; + return 0.0f; + } + + // 0x206B01: a bot that already has a mine target (Bot +0x1FC) keeps its urgency. + if (static_cast(bot)->getMineTarget() != 0xFFFFFFFFu) + return m_urgency[botId]; + + // 0x206B29: the soldier's own Information (side from Bot +0xE0 first), its weapon list + // copied, and the index of the first weapon of type 1 (-1 when none). + const int side = bot->getSide(); + Information* const soldierInfo = + informationManager->getInformation(bot->getPlayer()->getSoldier()->getInformation(side)); + std::vector weapons = soldierInfo->getArmament()->getWeapons(); + for (unsigned int i = 0; i < weapons.size(); ++i) + { + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (weapon && weapon->getWeaponType() == 1) + { + weaponIndex = i; + break; + } + } + + IPIMobile* const mobile = soldierInfo->getMobile(); // +0x38, read once before the loop + SquadMember* const member = bot->getSquadMember(); // Bot +0x140 + std::vector ignoredMines; + Vec3 minePosition = {0.0f, 0.0f, 0.0f}; + Vec3 mineNormal = {0.0f, 0.0f, 0.0f}; + Vec3 targetPosition = {0.0f, 0.0f, 0.0f}; + bool done = false; + bool found = false; + int tries = 0; + while (!done) + { + // 0x206CF6: cmpl $0x64; jg -- at most 100 queries. + if (++tries > 100) + break; + + bool mineFlag; // [UNRESOLVED] meaning; its negation is passed as the MineType + unsigned int mineId; + // IAIGame slot +0x18 (declared int; the caller tests %al only, 0x206D91). + if (!static_cast(static_cast(CommonSingletonServer::m_iaiGame) + ->getClosestHostileMine(member->getPlayer(), botPosition, mineFlag, + minePosition, mineNormal, mineId, + ignoredMines))) + { + done = true; + continue; + } + + found = false; + unsigned int quadTree; + unsigned int polygon; + // ELF 0x206DDB calls the const-reference getter (0x2E1720), then copies its Vec3. + minePosition = static_cast(CommonSingletonServer::m_iAIMineManager) + ->getPathfindingPositionOfMine(mineId, static_cast(!mineFlag), + quadTree, polygon); + if (quadTree != 0xFFFFFFFFu && polygon != 0xFFFFFFFFu) + { + targetPosition = minePosition; + // 0x206E2A: fucompi |normal.y| against 0.5f (rodata 0x49CB44); jbe pulls the target + // back 0.8f (rodata 0x49CB64) along the normal, also when unordered. + if (!(std::fabs(mineNormal.y) > 0.5f)) + { + targetPosition.x = minePosition.x - mineNormal.x * 0.8f; + targetPosition.y = minePosition.y - mineNormal.y * 0.8f; + targetPosition.z = minePosition.z - mineNormal.z * 0.8f; + } + // IAIPathfinding slot +0x2C; getEquipmentType (Information +0x40 unit, reread each + // pass) is evaluated before getVehicleNumber. + const int equipmentType = soldierInfo->getUnit()->getEquipmentType(); + const int vehicleNumber = mobile->getVehicleNumber(); + if (IAIPathfinding::instance->isValidPosition(vehicleNumber, equipmentType, targetPosition, false)) + { + // 0x206F0B: rodata 0x49F6A4 1225.0f (35 m squared); 42.0f is rodata 0x49F6A8. + if (lengthSquared(targetPosition.x - botPosition.x, targetPosition.y - botPosition.y, + targetPosition.z - botPosition.z) < 1225.0f) + { + baseUrgency = 42.0f; + found = true; + mineTarget = mineId; + done = true; + continue; + } + } + } + ignoredMines.push_back(mineId); + } + + if (found) + { + // 0x206F81: flds base; fmuls urgencyScale. + m_urgency[botId] = baseUrgency * urgencyScale; + m_targetChanged[botId] = m_mineTarget[botId] != mineTarget; + m_mineTarget[botId] = mineTarget; + static_cast(pattern)->init(mineTarget, weaponIndex, bot, minePosition, targetPosition); + if (m_urgency[botId] == 0.0f) + static_cast(bot)->setMineTarget(0xFFFFFFFFu); // Bot +0x1F8 + return m_urgency[bot->getBotId()]; + } + + // 0x207105 + m_urgency[botId] = 0.0f; + m_targetChanged[botId] = m_mineTarget[botId] != mineTarget; + pattern->unInit(bot); + m_mineTarget[botId] = mineTarget; + static_cast(bot)->setMineTarget(0xFFFFFFFFu); + return 0.0f; + } + + // 0x207294 + m_urgency[botId] = 0.0f; + m_targetChanged[botId] = m_mineTarget[botId] != 0xFFFFFFFFu; + m_mineTarget[botId] = 0xFFFFFFFFu; + pattern->unInit(bot); + static_cast(bot)->setMineTarget(0xFFFFFFFFu); + return 0.0f; +} + +// ELF 0x207310: bot->getPlayer() (+0xBC) alive (+0x24), not getManDown (+0x1B0), and the +// player's getSpawnKit (+0x44) == 4. +bool BBDefuseMines::isApplicable(Information*, Bot* bot) +{ + if (!bot->getPlayer()->getIsAlive()) + return false; + if (bot->getManDown()) + return false; + return bot->getPlayer()->getSpawnKit() == 4; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBDefuseMines.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBDefuseMines.h new file mode 100644 index 000000000..52099896b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBDefuseMines.h @@ -0,0 +1,47 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBDEFUSEMINES_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBDEFUSEMINES_H + +#include "BotBehaviour.h" + +#include + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class Information; +class PlanGenerator; +class UrgeCurve; + +// ELF: vtable 0x4BAA60 (14 words), operator new 0x38, package F-infantry. +class BBDefuseMines : public BotBehaviour +{ +public: + BBDefuseMines(unsigned char, unsigned char, PlanGenerator*, UrgeCurve*, float*); // 0x206280 + virtual ~BBDefuseMines(); // 0x206780 + + virtual float calculateUrgency(Bot*, bool, float); // 0x2068C0, slot +0x28; from the base declaration + virtual bool isApplicable(Information*, Bot*); // 0x207310, slot +0x34; bool: 1 only for alive, not man-down, spawn kit 4 + + // Base m_targets (+0x08) is new unsigned int[getMaxNBots], uninitialised; no reader in this TU. + +private: + // Constructor 0x205E20/0x206280, destructor 0x2066E0/0x206780/0x206820. + /* +0x24 */ std::vector m_unknown24; // empty; freed as 4-byte elements; no F reader [UNRESOLVED] + /* +0x30 */ int* m_unknown30; // new [getNBattleStrengths] (IAISettings +0x34), uninitialised [UNRESOLVED] + /* +0x34 */ unsigned int* m_mineTarget; // new [getMaxNBots], each -1: the mine id each bot defuses [INFERRED] name +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBDEFUSEMINES_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire.cpp new file mode 100644 index 000000000..bfece1b02 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire.cpp @@ -0,0 +1,1036 @@ +// Fire behaviour base (AI/AIDLL/AI/AIBotBehaviour/BBFire.cpp in the image). Recovered from +// libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. Package D. + +// static init: ELF 0x20B720 (__tcf_0 0x20B780, _GLOBAL__I 0x20B7B0): 's Init object only. +#include + +#include "BBFire.h" + +#include "../AIUtils/CustomCurve.h" +#include "../AIBot/BotMain.h" +#include "../AIBotBehaviourPattern/BBPFire.h" +#include "../AIBot/BotMemory.h" +#include "../AIBot/SensedObject.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../AIStrategic/SAI.h" +#include "../AIStrategicEntity/AIStrategicArea.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" +#include "../AIUtils/checkPointer.h" +#include "../AIUtils/VehicleOccupancy.h" +#include "../Main/AIMain.h" +#include "../Main/AIRandom.h" +#include "../Main/IAIPathfinding.h" +#include "../Main/IBotManager.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../Main/AIDllFrontier.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../AIBot/BotNavigation.h" +#include "../AIStrategicEntity/AIStrategicObject.h" +#include "../../../AIInterface/BFKnowledge/IWeapon.h" +#include "../../../../IO/Input/PlayerInput.h" +#include "../../../../Math/Mat4.h" + +#include +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +IAISettings* settings() +{ + return static_cast(CommonSingletonServer::m_iaiSettings); +} + +// [INFERRED] the inline reader of io::Input: a mapped input's value, else 0. chooseWeapon +// (0x20B278) tests the 64-bit mapping mask and reads the value directly. +float mappedInput(const io::PlayerInput* input, io::PlayerInputMap index) +{ + return ((input->mappingFlags >> index) & 1) ? input->inputs[index] : 0.0f; +} + +} // namespace + +// ELF 0x2079B0 +BBFire::BBFire(unsigned char index, unsigned char queue, BBPFire* pattern, UrgeCurve* curve, float* modifiers) + : BotBehaviour(modifiers, curve, settings()->getMaxNBots()) + , m_double28(0.0) +{ + m_index = index; + m_queue = queue; + m_pattern = pattern; + + const int bots = settings()->getMaxNBots(); + m_targets = checkPointer(new unsigned int[bots]); + m_unknown24 = checkPointer(new unsigned int[bots]); + for (int i = 0; i < bots; ++i) + { + m_urgency[i] = 0.0f; + m_unknown24[i] = static_cast(-1); + m_targets[i] = static_cast(-1); + } + pattern->setUrgencyGenerator(this); + m_curve = new CustomCurve(&CustomCurve::modifiedSoftStepFunc, 0.0f, 1.0f, 0.03f); +} + +// ELF 0x207E80 +BBFire::~BBFire() +{ + if (m_targets) + delete[] m_targets; + if (m_unknown24) + delete[] m_unknown24; + if (m_curve) + delete m_curve; +} + +// ELF 0x208040 (listing block by block; Ghidra pseudo-code cross-check). Scores every sensed, +// hostile, living object as a target and keeps the best one in the per-bot target array +// (BotBehaviour +0x08), its weapon index in m_unknown24, and hands both to the pattern through +// initializeGenerator. Without a target the behaviour is un-initialised and its urgency is 0. +// +// A candidate's score is the summed strength of it and its secondary objects (the own battle +// strength against it, its information strength and its battle strength against the own +// strength type, times its armour class value, the order factor and the area factor), times +// the range factor, the best weapon's strength, the indirect-sense age factor, the approach +// factor, the attack factor, the area factor, a CustomCurve of an AIRandom draw and the +// weapon's range quality, and * 0.33 when the summed strength is at most the harmless +// threshold. The current target is kept while it scores more than 1 / 1.2 of the best. +// The weapon-score array, the up vector and several dead Vec3 temporaries are as compiled. +float BBFire::calculateUrgency(Bot* bot, bool recalculate, float modifier) +{ + static bool checkOpportunist = false; // .bss; nothing in the image writes it + static float enemyStrengthTweak = 2.0f; // .data + + PlanGenerator* const pattern = m_pattern; + unsigned int* const targets = m_targets; + + if (!recalculate) + { + if (!pattern->isInitiated(bot)) + { + m_targetChanged[bot->getBotId()] = false; + return m_urgency[bot->getBotId()] = 0.0f; + } + if (!informationManager->getInformation(targets[bot->getBotId()])) + { + m_targetChanged[bot->getBotId()] = true; + pattern->unInit(bot); + return m_urgency[bot->getBotId()] = 0.0f; + } + m_targetChanged[bot->getBotId()] = false; + bot->addToFireInclination(m_urgency[bot->getBotId()]); + return m_urgency[bot->getBotId()]; + } + + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + float areaFactor = 0.5f; + const float* const armourClassValues = settings()->getArmourClassValues(); + + // 0x20821A: once a minute, forget the feedback of objects that no longer exist. + if (now - m_double28 > 60.0) + { + std::map::iterator it = m_feedback.begin(); + while (it != m_feedback.end()) + { + if (informationManager->getInformation(it->first)) + { + ++it; + continue; + } + delete it->second; + m_feedback.erase(it++); + } + m_double28 = now; + } + + const int side = bot->getSide(); + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + const Vec3& position = equipment->getPosition(); + if (!equipment->isOfType(ITNaval) && !equipment->isOfType(ITAir) && equipment->isOfType(ITSoldier)) + { + // 0x209FE0: a passenger seat whose soldier pose is 4 does not fire. + if (equipment->isPrimary() && equipment->getSoldierPose() == 4) + { + m_targetChanged[bot->getBotId()] = true; + pattern->unInit(bot); + return m_urgency[bot->getBotId()] = 0.0f; + } + } + + IPIUnit* const unit = equipment->getUnit(); + const int equipmentType = unit->getEquipmentType(); // called before the null test (retail) + IPIArmament* const armament = equipment->getArmament(); + IPIPhysical* const physical = equipment->getPhysical(); + IPIControlInfo* const controlInfo = equipment->getControlInfo(); + if (!unit || !physical || !armament || !controlInfo) + { + m_targetChanged[bot->getBotId()] = true; + pattern->unInit(bot); + return m_urgency[bot->getBotId()] = 0.0f; + } + + IPIMobile* const mobile = equipment->getMobile(); + const bool exposedSoldier = unit->hasExposedSoldier(); + const int strengthType = physical->getStrengthType(); + int soldierStrengthType = 0; + if (exposedSoldier) + { + // 0x209F74: the exposed soldier's own strength type. Retail quirk: no null test. + Information* const soldier = + informationManager->getInformation(bot->getPlayer()->getSoldier()->getInformation(side)); + soldierStrengthType = soldier->getPhysical()->getStrengthType(); + } + + const float zero = 0.0f; // -0x19C: never written again + unsigned int countedOrders = 0; // -0x1A4 + WeaponInfo* bestWeaponInfo = 0; // -0x204 + const unsigned int currentTarget = targets[bot->getBotId()]; + bot->getBotId(); // called, result unused + bool keepCurrentTarget = false; // -0x1A9: the current target scored again + + const int orderedArea = IAIMain::m_instance->getSAI(side)->getBotOrderedPos(bot->getBotId()); + AIStrategicArea* const area = + static_cast(AIStrategicObjectManager::getInstance()->getStrategicObject(orderedArea)); + if (area && !area->isInside(position)) + areaFactor = 0.85f; + + Vec3 unused; // -0x158: zeroed, never read + unused.x = zero; + unused.y = zero; + unused.z = zero; + (void)unused; + equipment->getTransformation(); // 0x2084A6: called, result unused here + float bestDistance = zero; // -0x208 + m_unknown24[bot->getBotId()] = static_cast(-1); + + float currentTargetScore = zero; // -0x1B0 + float bestScore = zero; // -0x198 + const std::map& sensed = bot->getSensedObjects(); + for (std::map::const_iterator it = sensed.begin(); it != sensed.end(); ++it) + { + SensedObject* const object = it->second; + if (!(object->m_flags & SensedObject::SENSE_SEEN) || !(object->m_flags & SensedObject::SENSE_SIDED)) + continue; + Information* const info = informationManager->getInformation(object->m_handle); + if (!info) + continue; + if (info->getSide() == side || info->getSide() == 0) + continue; + IPIUnit* const targetUnit = info->getUnit(); + IPIPhysical* const targetPhysical = info->getPhysical(); + if (!targetPhysical) + continue; + if (info->isOfType(ITLowPriority) || info->isOfType(ITVegetation) || info->isOfType(ITNoTemperature)) + continue; + if (0.0f >= targetPhysical->getHealth()) // 0x208B46 jae: a NaN health is kept + continue; + if ((object->m_flags & 0x20) && object->m_fireRating < 0) + continue; + + // 0x208B63: recent fire feedback on this object needs some movement to engage again. + BBPFeedback* const feedback = getBBPFeedback(object->m_handle); + if (now - feedback->m_time < 20.0) + { + float speed = 0.0f; + if (mobile) + speed = mobile->getSpeedMagnitude(); + if (info->getMobile()) + speed = speed + info->getMobile()->getSpeedMagnitude(); + if (speed < 2.0f) + continue; + static_cast(bot)->setHadPrecisionTimeStamp(now); + } + + // 0x208BDD: an object attacking the bot weighs up to 1.5 (3x for a human soldier), fading + // to 1.0 over 30 seconds. + float attackFactor; // -0x1B4 + double attackTime; + if (static_cast(bot)->isAttacking(object->m_handle, attackTime)) + { + const float age = static_cast(now - attackTime); + float ramp = age / 30.0f; + if (0.0f > ramp) + ramp = 0.0f; + else if (ramp > 1.0f) + ramp = 1.0f; + attackFactor = 1.5f - ramp * 0.5f; + if (!IBotManager::instance->getBotFromPlayerId(info->getPlayerId()) + && info->isOfType(ITSoldier)) + attackFactor = attackFactor * 3.0f; + } + else + { + attackFactor = 1.0f; + } + + Vec3 targetPosition; // -0x168 + targetPosition.x = zero; + targetPosition.y = zero; + targetPosition.z = zero; + IPIMobile* const targetMobile = info->getMobile(); + if (targetMobile) + targetMobile->getPositionEstimate(targetPosition); + else + targetPosition = info->getPosition(); + Vec3 direction; // -0x148 + direction.x = targetPosition.x - position.x; + direction.y = targetPosition.y - position.y; + direction.z = targetPosition.z - position.z; + float distance = std::sqrt(direction.x * direction.x + direction.y * direction.y + + direction.z * direction.z); + if (distance > 0.0001f) + { + const float inverse = 1.0f / distance; + direction.x = direction.x * inverse; + direction.y = direction.y * inverse; + direction.z = inverse * direction.z; + } + float indirectFactor = 1.0f; // -0x224 + if (1.0f > distance) + distance = 1.0f; + + if (object->m_flags & SensedObject::SENSE_INDIRECT) + { + // 0x208D65: an object not seen directly must stand on ground the bot's vehicle can use. + if (!mobile) + continue; + IAIPathfinding* const pathfinding = IAIPathfinding::instance; + if (!targetMobile) + continue; + const IPIMobile::ValidPos& valid = targetMobile->getLastValidPosition(mobile->getVehicleNumber()); + if (valid.polygon == static_cast(-1)) + continue; + if (targetUnit->getEquipmentType() != equipmentType) + { + unsigned char material; + pathfinding->getMaterial(mobile->getVehicleNumber(), valid.island, valid.polygon, material); + if (!settings()->isValidMaterial(equipmentType, material)) + continue; + } + const float age = static_cast(now - object->m_firstSeenTime); + indirectFactor = 1.0f / (age * 0.05f + 1.5f); + } + else if (!mobile) + { + // 0x209D64: a static weapon needs the seen part inside its camera's range of directions. + Vec3 cameraBase; + cameraBase.x = zero; + cameraBase.y = zero; + cameraBase.z = zero; + controlInfo->getCameraBasePos(cameraBase); + Vec3 seen; + seen.x = zero; + seen.y = zero; + seen.z = zero; + const Mat4& transformation = info->getTransformation(); + const Vec3& local = object->m_seenPosition; + // 0x209DC3..0x209DEC: ((m4*y + m0*x) + m8*z) + m12. + seen.x = transformation.m[4] * local.y + transformation.m[0] * local.x + + transformation.m[8] * local.z + transformation.m[12]; + seen.y = transformation.m[1] * local.x + transformation.m[5] * local.y + + transformation.m[9] * local.z + transformation.m[13]; + seen.z = local.x * transformation.m[2] + local.y * transformation.m[6] + + local.z * transformation.m[10] + transformation.m[14]; + if (!equipment->isOfType(ITAir) || equipment->isOfType(ITHelicopter)) + { + if (!controlInfo->validateCameraDirectionByPos(seen)) + continue; + } + } + + // 0x208E82: the strongest usable weapon against the target's strength type, and the + // longest range of all weapons. + float bestWeaponScore = 0.0f; // -0x238 + int bestWeapon = -1; // -0x234 + float maxRange = 0.0f; // -0x230 + float weaponScores[8]; // -0x138 + std::vector& weapons = armament->getWeapons(); + int i; + for (i = 0; static_cast(i) < weapons.size(); ++i) + { + if (!WeaponInfoManager::m_instance->getInformation(weapons[i])) + { + weaponScores[i] = 0.0f; + continue; + } + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + const int weaponType = weapon->getWeaponType(); + if (weaponType != 0 && weaponType != 4 && weaponType != 3) + { + weaponScores[i] = 0.0f; + continue; + } + if (weaponType == 4 && targetMobile) + { + // Retail: the skipped weapon's score is left unwritten. + const Vec3 faceing = equipment->getFaceing(); + const Vec3& speed = targetMobile->getSpeed(); + if (std::fabs(speed.y * faceing.y + speed.x * faceing.x + speed.z * faceing.z) > 4.0f) + continue; + } + int ammo = weapon->getAmmo(); + if (ammo == -1) + ammo = 0x10000; + if (ammo > 0) + weaponScores[i] = static_cast(weapon->getStrength(targetPhysical->getStrengthType())); + else + weaponScores[i] = 0.0f; + if (i == armament->getActiveWeapon()) + weaponScores[i] = weaponScores[i] * 1.03f; + if (weaponScores[i] > bestWeaponScore) + { + bestWeapon = i; + bestWeaponScore = weaponScores[i]; + bestWeaponInfo = weapon; + } + if (weapon->getMaxRange() > maxRange) + maxRange = weapon->getMaxRange(); + } + if (bestWeaponScore == 0.0f) + continue; + for (; i < 8; ++i) + weaponScores[i] = 0.0f; + + Vec3 targetSpeed; // -0x118 + targetSpeed.x = 0.0f; + targetSpeed.y = 0.0f; + targetSpeed.z = 0.0f; + if (targetMobile) + targetSpeed = targetMobile->getSpeed(); + const float targetSpeedMagnitude = std::sqrt(targetSpeed.x * targetSpeed.x + targetSpeed.y * targetSpeed.y + + targetSpeed.z * targetSpeed.z); + + float targetAreaFactor = areaFactor; // -0x1A0 + if (mobile && !equipment->isOfType(ITAir) && area && !area->isInside(targetPosition)) + targetAreaFactor = targetAreaFactor * 0.85f; + + // 0x209247: the approach factor (-0x258). + float approachFactor; + bool closing = true; // falls through to the closing-speed estimate below + if (info->isOfType(ITAir)) + { + // 0x209C55: an aircraft target. + const int antiAircraft = armament->isAntiAircraft(); + if (!antiAircraft) + { + if (info->getAltitude() > 5.0f) + continue; + if (distance > maxRange * 0.5f || targetSpeedMagnitude > 5.0f) // 0x209D15 ja, 0x209D21 jbe + { + approachFactor = 0.0f; + closing = false; + } + } + else + { + if (checkOpportunist && antiAircraft == 2) + { + const Mat4& transformation = equipment->getTransformation(); + if (direction.y * transformation.m[5] + direction.x * transformation.m[4] + + direction.z * transformation.m[6] + > 0.5f) + continue; + } + if (maxRange * 0.9f > distance) // 0x209C8D jbe + { + approachFactor = 1.0f; + closing = false; + } + } + } + if (closing) + { + if (!targetMobile || !(distance > maxRange)) + { + approachFactor = 1.0f; + targetAreaFactor = 0.5f; + } + else + { + // 0x20927A: out of range; how fast the target can close in or cross. + float ownMaxSpeed = 0.0f; + Vec3 ownSpeed; // -0x108 + ownSpeed.x = 0.0f; + ownSpeed.y = 0.0f; + ownSpeed.z = 0.0f; + if (mobile) + { + ownMaxSpeed = mobile->getMaxSpeed(); + ownSpeed = mobile->getSpeed(); + } + if (targetMobile->getMaxSpeed() - ownMaxSpeed > 5.0f) + { + Vec3 up; // -0xD8 + up.x = 0.0f; + up.y = 1.0f; + up.z = 0.0f; + Vec3 across; // -0xF8: up x direction + across.x = up.y * direction.z - up.z * direction.y; + across.y = up.z * direction.x - up.x * direction.z; + across.z = up.x * direction.y - up.y * direction.x; + const Vec3& speed = targetMobile->getSpeed(); + float towards = (direction.x * speed.x + direction.y * speed.y + direction.z * speed.z) + - (direction.x * ownSpeed.x + direction.y * ownSpeed.y + direction.z * ownSpeed.z); + float sideways = (across.x * speed.x + across.y * speed.y + across.z * speed.z) + - (ownSpeed.x * across.x + ownSpeed.y * across.y + ownSpeed.z * across.z); + if (0.0f > towards) // 0x209BB4 fcmovbe keeps a NaN + towards = 0.0f; + if (0.0f > sideways) + sideways = 0.0f; + const float speedMagnitude = std::sqrt(speed.x * speed.x + speed.y * speed.y + speed.z * speed.z); + approachFactor = 0.25f / (towards + towards + up.y + (sideways + sideways) + + speedMagnitude * 0.5f); + } + else + { + approachFactor = 0.25f; + } + } + } + + if (distance > maxRange) + { + // 0x209325: out of range; the bot must be able to drive to the target in 5 seconds. + if (!targetMobile || !mobile) + continue; + const IPIMobile::ValidPos& valid = targetMobile->getLastValidPosition(mobile->getVehicleNumber()); + if (valid.polygon == static_cast(-1)) + continue; + IAIPathfinding* const pathfinding = IAIPathfinding::instance; + if (targetUnit->getEquipmentType() != equipmentType) + { + unsigned char material; + pathfinding->getMaterial(mobile->getVehicleNumber(), valid.island, valid.polygon, material); + if (!settings()->isValidMaterial(equipmentType, material)) + continue; + } + if (distance - maxRange > mobile->getMaxSpeed() * 5.0f) + continue; + } + + // 0x209461: the strength of the object and its secondary objects (seats). + if (!info->getUnit() || !vehicleOccupied(object->m_handle, side)) + continue; + float strengthSum = 0.0f; // -0x278 + float score = 0.0f; // -0x194 + unsigned int partHandle = object->m_handle; + Information* part = info; + int secondary = info->getFirstSecondaryObjectIterator(); + const int targetStrengthType = info->getPhysical()->getStrengthType(); + do + { + IPIUnit* partUnit = part->getUnit(); + const unsigned int occupied = partUnit->getOccupiedObject(side); + if (occupied != static_cast(-1)) + { + Information* const occupier = informationManager->getInformation(occupied); + if (occupier) + partUnit = occupier->getUnit(); + } + strengthSum = strengthSum + partUnit->getBattleStrengths()[strengthType]; + bool ordered = false; + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() + && bot->getOrderList(m_index)->size() > countedOrders) + { + if (bot->getOrderList(m_index)->end() + != std::find(bot->getOrderList(m_index)->begin(), bot->getOrderList(m_index)->end(), + partHandle)) + ordered = true; + } + float orderFactor; + if (ordered) + { + ++countedOrders; + orderFactor = bot->getMemory()->m_float8; + } + else + { + orderFactor = 1.0f; + } + float strength; + if (!exposedSoldier) + strength = partUnit->getBattleStrengths()[strengthType]; + else + strength = std::max(partUnit->getBattleStrengths()[strengthType], + partUnit->getBattleStrengths()[soldierStrengthType]); + if (!info->isOfType(ITSoldier)) + strength = strength * enemyStrengthTweak; + score = (strength + part->getStrength() + unit->getBattleStrengths()[targetStrengthType]) + * armourClassValues[targetStrengthType] * orderFactor * targetAreaFactor + + score; + partHandle = info->getSecondaryObject(secondary, side); + part = informationManager->getInformation(partHandle); + } + while (part); + + // 0x209667 + float rangeFactor = 1.0f - distance / (maxRange * 1.2f); + if (!(rangeFactor > 0.0f)) + rangeFactor = 0.0f; + score = rangeFactor * bestWeaponScore * indirectFactor * approachFactor * attackFactor * targetAreaFactor + * score; + const float weaponMaxRange = bestWeaponInfo->getMaxRange(); + const float weaponMinRange = bestWeaponInfo->getMinRange(); + const float rangeQuality = ((weaponMaxRange - weaponMinRange) * 0.1f + weaponMinRange) / distance; + score = m_curve->calculate(AIRandom::m_instance->nextFloat(), true) * score * rangeQuality; + if (strengthSum <= static_cast(static_cast(bot)->getHarmlessThrsh())) + score = score * 0.33f; + if (!info->getUnit()) + continue; + if (currentTarget == it->first) + { + currentTargetScore = score; + keepCurrentTarget = true; + } + if (score > bestScore) + { + bestScore = score; + targets[bot->getBotId()] = it->first; + m_unknown24[bot->getBotId()] = bestWeapon; + bestDistance = distance; + } + } + + float scale = 1.0f; // -0x298 + if (bestScore > 0.0f) + { + if (keepCurrentTarget) + currentTargetScore = currentTargetScore * 1.2f; + if (keepCurrentTarget && currentTargetScore > bestScore) + { + if (targets[bot->getBotId()] != currentTarget) + { + // 0x20877F: stay with the current target; its distance replaces the best one. + targets[bot->getBotId()] = currentTarget; + Information* const target = informationManager->getInformation(currentTarget); + const Vec3& from = equipment->getPosition(); + const Vec3& to = target->getPosition(); + const float dx = to.x - from.x; + const float dy = to.y - from.y; + const float dz = to.z - from.z; + bestDistance = std::sqrt(dx * dx + dy * dy + dz * dz); + } + } + else + { + bot->getBotId(); // called, result unused + keepCurrentTarget = false; + } + const int weapon = chooseWeapon(bot, targets[bot->getBotId()], bestDistance); + if (weapon != -1) + m_unknown24[bot->getBotId()] = weapon; + initializeGenerator(static_cast(bot), m_unknown24[bot->getBotId()], false, false); + + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && bot->getOrderList(m_index)->empty()) + bestScore = bestScore * bot->getMemory()->m_float8; + m_targetChanged[bot->getBotId()] = !keepCurrentTarget; + scale = scale * modifier; + m_urgency[bot->getBotId()] = DecleiningSlopeCurve::calculate(bestScore + bestScore) * scale; + bot->addToFireInclination(m_urgency[bot->getBotId()]); + return m_urgency[bot->getBotId()]; + } + + // 0x2088A8. -0x19C is never written after its 0.0, so the second branch (0x208936) is dead + // code in the image; it is kept as compiled. + m_targetChanged[bot->getBotId()] = !keepCurrentTarget; + float indirectScore = zero; + if (!(indirectScore > 0.0f)) + { + pattern->unInit(bot); + m_urgency[bot->getBotId()] = 0.0f; + targets[bot->getBotId()] = static_cast(-1); + return 0.0f; + } + targets[bot->getBotId()] = static_cast(-1); + initializeGenerator(static_cast(bot), -1, false, false); + const float weighted = scale * indirectScore; + indirectScore = indirectScore + indirectScore; + m_urgency[bot->getBotId()] = DecleiningSlopeCurve::calculate(indirectScore + indirectScore) * weighted; + bot->addToFireInclination(m_urgency[bot->getBotId()]); + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && bot->getOrderList(m_index)->empty()) + m_urgency[bot->getBotId()] = m_urgency[bot->getBotId()] * bot->getMemory()->m_float8; + return m_urgency[bot->getBotId()]; +} + +// ELF 0x20A090 +void BBFire::initializeGenerator(BotMain* bot, int mode, bool a, bool b) +{ + unsigned int* const targets = m_targets; + bot->setFiringTarget(targets[bot->getBotId()]); + static_cast(m_pattern)->init(bot, targets[bot->getBotId()], mode, a, b); +} + +// ELF 0x20A120 +void BBFire::initializeGenerator(unsigned int target, const Vec3& position, BotMain* bot, int mode) +{ + bot->setFiringTarget(target); + static_cast(m_pattern)->init(bot, target, position, mode); +} + +// ELF 0x20A180 +BBFire::BBPFeedback* BBFire::getBBPFeedback(unsigned int target) +{ + std::map::iterator it = m_feedback.find(target); + if (it != m_feedback.end()) + return it->second; + BBPFeedback* const feedback = checkPointer(new BBPFeedback); + m_feedback.insert(std::make_pair(target, feedback)); + return feedback; +} + +// ELF 0x20A350 (listing block by block; Ghidra pseudo-code cross-check). The index of the +// bot's weapon that scores best against the target at `distance`, or -1. A weapon scores its +// strength against the target's strength type, scaled down outside its range band and by 0.33 +// with an empty magazine. Against a soldier the bot may pick a close-quarters weapon +// (spawn-kit dependent slot 0 or 5) and returns it at once when the pathfinding trace to the +// target's last valid position succeeds; a splash-damage weapon may be chosen for a static +// attack (score * 100, setUseStaticAttack(true)) when the target is in its band, not recently +// failed and not near the flag the bot is going for. setUseStaticAttack(false) comes first. +int BBFire::chooseWeapon(Bot* bot, unsigned int target, float distance) +{ + static bool allowMultipleC4 = false; // .bss; nothing in the image writes it + + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + const bool ownIsSoldier = equipment->isOfType(ITSoldier); + IPIArmament* const armament = equipment->getArmament(); + static_cast(bot)->setUseStaticAttack(false); + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + int bestWeapon = -1; + float bestScore = 0.0f; + + Information* const targetInfo = informationManager->getInformation(target); + if (!targetInfo) + return -1; + const bool targetIsSoldier = targetInfo->isOfType(ITSoldier); + IPIPhysical* const targetPhysical = targetInfo->getPhysical(); + IPIMobile* const targetMobile = targetInfo->getMobile(); + if (!targetPhysical) + return -1; + + // 0x20A478: the bot's active weapon. closeQuartersActive: a soldier holding the slot the + // close-quarters weapon of its kit sits in; ownMagazineEmpty: the active magazine is empty. + bool closeQuartersActive = false; // -0x199 + bool ownMagazineEmpty = false; // -0x19A + IPIArmament* const ownArmament = equipment->getArmament(); + if (ownArmament && ownArmament->getActiveWeapon() != -1) + { + const int active = ownArmament->getActiveWeapon(); + WeaponInfo* const activeInfo = WeaponInfoManager::m_instance->getInformation(ownArmament->getWeapon(active)); + if (!activeInfo) + return -1; + IWeapon* const activeWeapon = activeInfo->getWeapon(); + if (ownIsSoldier + && ((bot->getSpawnKit() != 5 && active == 0) || (bot->getSpawnKit() == 5 && active == 5))) + closeQuartersActive = true; + ownMagazineEmpty = false; + if (activeWeapon->getAmmoInMag(0) == 0 && !closeQuartersActive) + ownMagazineEmpty = true; + } + + // 0x20A511: the target's active weapon and whether its magazine is empty. + bool targetMagazineEmpty = false; // -0x19B + WeaponInfo* targetWeapon = 0; + IPIArmament* const targetArmament = targetInfo->getArmament(); + if (targetArmament && targetArmament->getActiveWeapon() != -1) + { + targetWeapon = WeaponInfoManager::m_instance->getInformation( + targetArmament->getWeapon(targetArmament->getActiveWeapon())); + if (targetWeapon) + targetMagazineEmpty = targetWeapon->getWeapon()->getAmmoInMag(0) == 0; + } + + // 0x20A57D: whether the target fights the bot: a bot whose firing target is this bot's + // player, or a human who attacked the bot (any recorded attack: within 9995 seconds). + bool targetEngagesBot = false; // -0x19C + Bot* const targetBot = IBotManager::instance->getBotFromPlayerId(targetInfo->getPlayerId()); + if (!targetBot) + { + if (targetWeapon) + { + double attackTime; + static_cast(bot)->isAttacking(target, attackTime); + targetEngagesBot = now - attackTime < 9995.0; + } + } + else + { + Information* const firingTarget = informationManager->getInformation(targetBot->getFiringTarget()); + if (firingTarget && firingTarget->getPlayerId() == bot->getPlayerId()) + targetEngagesBot = true; + } + bool soldierAgainstSoldier = false; // -0x19D + if (targetIsSoldier && ownIsSoldier) + soldierAgainstSoldier = true; + const bool targetIsHuman = !IBotManager::instance->getBotFromPlayerId(targetInfo->getPlayerId()); // -0x19E + SensedObject* const sensed = bot->getSensedObjectFromHandle(target); + + std::vector& weapons = armament->getWeapons(); + for (unsigned int i = 0; i < weapons.size(); ++i) + { + if (!WeaponInfoManager::m_instance->getInformation(weapons[i])) + continue; + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + const int weaponType = weapon->getWeaponType(); + if (weaponType != 0 && weaponType != 4 && weaponType != 3) + continue; + + bool closeQuarters = false; // -0x1B1 + bool meleeAttack = false; // -0x1B2 + bool splash = false; // -0x1C8: a vehicle's explosive weapon against a soldier + if (!ownIsSoldier && targetInfo->isOfType(ITSoldier)) + { + if (weapon->getWeaponGuidanceType() == 0 && weapon->getExplosionRadius() != 0.0f) + splash = true; + } + if (!weapon->getFiresThroughTransparent() && !(sensed->m_flags & SensedObject::SENSE_INDIRECT) + && !(sensed->m_flags & SensedObject::SENSE_FLAG40)) + continue; + if (ownIsSoldier + && ((bot->getSpawnKit() != 5 && i == 0) || (bot->getSpawnKit() == 5 && i == 5))) + closeQuarters = true; + if (targetInfo->getArmament() && targetInfo->getArmament()->getActiveWeapon() == 0) + closeQuarters = false; + if (weaponType == 4) + { + // 0x20B520: C4 once, and not against a target moving across the bot's facing. + if (bot->isC4Placed() && !allowMultipleC4) + continue; + if (targetMobile) + { + const Vec3 faceing = equipment->getFaceing(); + const Vec3& speed = targetMobile->getSpeed(); + if (std::fabs(speed.y * faceing.y + speed.x * faceing.x + speed.z * faceing.z) > 4.0f) + continue; + } + } + + if (closeQuarters && ownIsSoldier && targetInfo->getMobile() && equipment->getMobile()) + { + // 0x20B41F: no close quarters with a target off its last valid position or inside + // an obstacle radius; that also ends soldierAgainstSoldier for the later weapons. + const IPIMobile::ValidPos& valid = + targetInfo->getMobile()->getLastValidPosition(equipment->getMobile()->getVehicleNumber()); + const Vec3& targetPosition = targetInfo->getPosition(); + Vec3 offset; + offset.x = 0.0f; + offset.y = 0.0f; + offset.z = 0.0f; + offset.x = targetPosition.x - valid.position.x; + offset.y = targetPosition.y - valid.position.y; + offset.z = targetPosition.z - valid.position.z; + if (offset.x * offset.x + offset.y * offset.y + offset.z * offset.z > 1.0f + || bot->getBotNavigation()->pointWithinObstacleRadius(targetInfo->getPosition())) + { + soldierAgainstSoldier = false; + continue; + } + } + + // 0x20A810 + bool closeAndActive = false; // -0x1D1 + if (closeQuartersActive && 10.0f > distance) + closeAndActive = true; + const float stamina = targetMobile ? targetMobile->getSprintStamina() : 0.0f; + if ((stamina > 0.5f || (closeAndActive && stamina > 0.0f)) && closeQuarters + && (targetMagazineEmpty || closeAndActive) && (ownMagazineEmpty || closeQuartersActive) + && soldierAgainstSoldier && targetIsHuman && 20.0f > distance + && (targetEngagesBot || closeQuartersActive)) + meleeAttack = true; + + int ammo = weapon->getAmmo(); + bool staticAttack = false; // -0x1D2 + if (ammo == -1) + ammo = 0x10000; + if (!(ammo > 0) && weaponType != 3 && !meleeAttack) + continue; + float score = static_cast(weapon->getStrength(targetPhysical->getStrengthType())); + if (score == 0.0f) + continue; + if (ownIsSoldier && targetIsSoldier && score != 0.0f && 3.0f > distance && closeQuarters) + meleeAttack = true; + + if (meleeAttack) + { + // 0x20B300: take the close-quarters weapon when the target's last valid position + // can be reached. + const IPIMobile::ValidPos& valid = + targetInfo->getMobile()->getLastValidPosition(equipment->getMobile()->getVehicleNumber()); + IAIPathfinding* const pathfinding = IAIPathfinding::instance; + Vec3 end; + end.x = 0.0f; + end.y = 0.0f; + end.z = 0.0f; + unsigned int polygon; + const int equipmentType = equipment->getUnit()->getEquipmentType(); + if (pathfinding->trace(bot->getBotNavigation(), false, valid.position, end, polygon, equipmentType, -1, + 0.0f, 0, 0)) + return static_cast(i); + } + + if ((ownIsSoldier || splash) && targetInfo->isOfType(ITSoldier) + && weapon->getWeaponGuidanceType() == 0 && weapon->getExplosionRadius() != 0.0f) + { + // 0x20ABCC: splash damage, unless the bot or the target is at the flag the bot goes for. + bool goingForFlag = static_cast(bot)->getIsGoingForFlag(); // -0x1D9 + bool targetNearFlag = false; // -0x1DA + if (!splash) + { + AIStrategicObject* const closest = AIStrategicObjectManager::getInstance()->getClosestObject( + equipment->getPosition(), bot->getSide(), false); + Vec3 orderPosition; + orderPosition.x = 0.0f; + orderPosition.y = 0.0f; + orderPosition.z = 0.0f; + if (closest) + { + orderPosition = closest->getOrderPos(equipment->getMobile()->getVehicleNumber(), bot->getSide()); + float radius = closest->m_size[bot->getSide()]; + Vec3 flag; + flag.x = 0.0f; + flag.y = 0.0f; + flag.z = 0.0f; + vec2ToVec3XZ(closest->getPosition(bot->getSide()), flag); + radius = radius * radius; + flag.y = orderPosition.y; + Vec3 offset; + offset.x = flag.x - orderPosition.x; + offset.y = flag.y - orderPosition.y; + offset.z = flag.z - orderPosition.z; + if (offset.x * offset.x + offset.y * offset.y + offset.z * offset.z < radius) + { + const float nearRadius = 40.0f; + if (closest->getStatus(bot->getSide()) != 0) + { + const Vec3& position = equipment->getPosition(); + offset.x = position.x - orderPosition.x; + offset.y = position.y - orderPosition.y; + offset.z = position.z - orderPosition.z; + if (offset.x * offset.x + offset.y * offset.y + offset.z * offset.z + < nearRadius * nearRadius) + { + const io::PlayerInput* const input = bot->getInput(); + if (mappedInput(input, io::PIThrottle) != 0.0f || mappedInput(input, io::PIYaw) != 0.0f + || mappedInput(input, io::PISprint) != 0.0f) + goingForFlag = true; + } + } + } + const Vec3& targetPosition = targetInfo->getPosition(); + offset.x = flag.x - targetPosition.x; + offset.y = flag.y - targetPosition.y; + offset.z = flag.z - targetPosition.z; + if (offset.x * offset.x + offset.y * offset.y + offset.z * offset.z < radius) + targetNearFlag = true; + } + } + if ((!goingForFlag && !targetNearFlag) || splash) + { + // 0x20AC13: the target in the weapon's band, not just failed, seen within the + // window, and no grenade thrown in the last 10 seconds. + const float heightDifference = targetInfo->getPosition().y - equipment->getPosition().y; + float minRange = weapon->getMinRange(); + if (!splash) + { + minRange = 5.0f; + if (!(heightDifference > 3.0f)) + minRange = 10.0f; + } + float maxRange = weapon->getMaxRange(); + if (heightDifference > 5.0f && !weapon->getIsThrown()) + maxRange = heightDifference * 1.25f + maxRange; + if (static_cast(bot)->getBotWantsToSimulateArtillery()) + { + minRange = minRange - 1.0f; + maxRange = 1.0f + maxRange; + } + bool aboveTarget = false; // -0x208 + if (bot->getSpawnKit() != 1 && !weapon->getIsThrown() && heightDifference > 30.0f) + aboveTarget = true; + aboveTarget = aboveTarget || splash; + double seenWindow = 10.0; + if (splash) + seenWindow = 5.0; + int grenades = 1; + if (!weapon->getIsThrown()) + { + if (weapon->getBurst()) + grenades = 3; + } + const double sinceSeen = now - sensed->m_lastSeenTime; + const double sinceGrenade = now - bot->getTimeOfGrenadeThrown(grenades - 1); + const bool staticFailed = + now - static_cast(bot)->getTimeOfLastFailedStaticAttack() < 10.0; + bool recentlyFailed = + now - static_cast(bot)->getTimeOfLastFailedSplashDamageAttack() < 5.0; + const bool inBand = distance >= minRange && maxRange >= distance; + if (!splash) + recentlyFailed = staticFailed; + if (inBand && !recentlyFailed && (sensed->m_flags & SensedObject::SENSE_SEEN) + && ((sensed->m_flags & SensedObject::SENSE_INDIRECT) || aboveTarget) && seenWindow > sinceSeen + && (sinceGrenade > 10.0 || splash)) + { + staticAttack = true; + score = score * 100.0f; + static_cast(bot)->setUseStaticAttack(true); + } + } + } + + // 0x20A9E1: an empty magazine that reloads slowly is nearly worthless. + IWeapon* const iweapon = weapon->getWeapon(); + if (iweapon->getAmmoInMag(0) == 0 && weapon->getReloadTime() > 1.9f && weapon->hasAutoReload()) + { + static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); // result unused + if (iweapon->getWeaponGuidingSystem() == 0) + score = 0.1f; + else if (!iweapon->getProjectile()) + score = 0.1f; + } + const float maxRange = weapon->getMaxRange(); + const float minRange = weapon->getMinRange(); + if (!staticAttack) + { + if (minRange > distance) + { + float shortfall = (minRange - distance) / 5.0f; + if (shortfall > 1.0f) + shortfall = 1.0f; + score = ((1.0f - 0.9f) - shortfall * 0.09f) * score; + } + else if (distance > maxRange) + { + float excess = (distance - maxRange) / 5.0f; + if (excess > 1.0f) + excess = 1.0f; + score = (1.0f - excess * 0.9f) * score; + } + } + if (iweapon->getAmmoInMag(0) == 0) + score = score * 0.33f; + if (score > bestScore) + { + bestScore = score; + bestWeapon = static_cast(i); + } + } + return bestWeapon; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire.h new file mode 100644 index 000000000..2e09c5750 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire.h @@ -0,0 +1,58 @@ +// Fire behaviour base: urgency of engaging the bot's chosen target, weapon choice, and the target +// handed to the fire pattern (BBPFire) through initializeGenerator. +// Recovered from libaidll.so (Linux 1.5.3153); every body carries its ELF address. Package D. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIRE_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIRE_H + +#include "../../../../Math/Vec3.h" +#include "BotBehaviour.h" + +#include + +namespace dice { +namespace hfe { + +namespace ai { + +class BBPFire; +class Bot; +class BotMain; +class CustomCurve; +class UrgeCurve; + +// ELF: vtable 0x4BAB00 (15 words), operator new 0x40, package D-behaviours. +class BBFire : public BotBehaviour +{ +public: + // Per-target feedback from the fire pattern, kept by target handle (new(8) in getBBPFeedback). + struct BBPFeedback + { + BBPFeedback() : m_time(-10000.0) {} + /* +0 */ double m_time; // [UNRESOLVED] meaning; -10000 = never + }; + + BBFire(unsigned char index, unsigned char queue, BBPFire* pattern, UrgeCurve* curve, float* modifiers); // 0x2079B0 + virtual ~BBFire(); // 0x207E80 + + virtual float calculateUrgency(Bot*, bool, float); // 0x208040, slot +0x28 + // Hands the bot's current target (BotBehaviour +0x08 [botId]) to the pattern and to the bot. + virtual void initializeGenerator(BotMain*, int, bool, bool); // 0x20A090, slot +0x34 + virtual void initializeGenerator(unsigned int target, const Vec3& position, BotMain*, int); // 0x20A120, slot +0x38 + + BBPFeedback* getBBPFeedback(unsigned int target); // 0x20A180: find, or insert a new one + int chooseWeapon(Bot*, unsigned int, float); // 0x20A350; [INFERRED] ELF int, callers {'int': 1} + +protected: + /* +0x24 */ unsigned int* m_unknown24; // per bot slot, constructed -1 [UNRESOLVED] meaning + /* +0x28 */ double m_double28; // constructed 0.0 [UNRESOLVED] meaning + /* +0x30 */ std::map m_feedback; // never freed (retail leak) + /* +0x3C */ CustomCurve* m_curve; // CustomCurve(modifiedSoftStepFunc, 0, 1, 0.03) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIRE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire3d.cpp new file mode 100644 index 000000000..a692ef3a3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire3d.cpp @@ -0,0 +1,539 @@ +// Aircraft fire behaviour, recovered from the symbolized Linux 1.50 libaidll.so. + +// static init: ELF 0x20E060 (__tcf_0 0x20E0C0, _GLOBAL__I 0x20E0F0): 's Init object only. +#include + +#include "BBFire3d.h" + +#include "../AIUtils/CustomCurve.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotMemory.h" +#include "../AIBot/SensedObject.h" +#include "../AIBotBehaviourPattern/BBPFire.h" +#include "../AIKnowledge/BFInformationEnvironment.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../AIStrategic/SAI.h" +#include "../AIStrategicEntity/AIStrategicArea.h" +#include "../AIStrategicEntity/AIStrategicObject.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" +#include "../AIUtils/VehicleOccupancy.h" +#include "../Main/AIMain.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IBotManager.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +#include +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x20BB00 (C2) / 0x20BCF0 (C1); vtable GOT -0x964. The base gets getMaxNBots; +0x28 = 0.0 +// (fld of the 0.0f constant, fstpl), the empty map at +0x30 (a 0x18-byte header node); a second +// getMaxNBots sizes the +0x08 and +0x24 arrays (plain operator new[], no checkPointer); every bot +// starts with urgency 0.0f and both slots -1; the pattern gets this behaviour as its urgency +// generator. Unlike BBFire, no CustomCurve. +BBFire3d::BBFire3d(unsigned char index, unsigned char queue, BBPFire* pattern, UrgeCurve* curve, + float* modifiers) + : BotBehaviour(modifiers, curve, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) + , m_double28(0.0) +{ + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int bots = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_targets = new unsigned int[bots]; + m_unknown24 = new unsigned int[bots]; + for (int i = 0; i < bots; ++i) + { + m_urgency[i] = 0.0f; + m_unknown24[i] = static_cast(-1); + m_targets[i] = static_cast(-1); + } + pattern->setUrgencyGenerator(this); +} + +// ELF 0x20BE30 (D2) / 0x20BEF0 (D1) / 0x20BFB0 (D0): delete[] +0x08, then +0x24 (each when set), +// then the map's destructor (_M_erase of the nodes; the BBPFeedback objects are not deleted) and +// ~BotBehaviour. +BBFire3d::~BBFire3d() +{ + if (m_targets) + delete[] m_targets; + if (m_unknown24) + delete[] m_unknown24; +} + +// ELF 0x20C070 +float BBFire3d::calculateUrgency(Bot* bot, bool recalculate, float modifier) +{ + if (!recalculate) + { + if (!m_pattern->isInitiated(bot)) + { + m_targetChanged[bot->getBotId()] = false; + return m_urgency[bot->getBotId()] = 0.0f; + } + if (!informationManager->getInformation(m_targets[bot->getBotId()])) + { + m_targetChanged[bot->getBotId()] = true; + m_pattern->unInit(bot); + return m_urgency[bot->getBotId()] = 0.0f; + } + m_targetChanged[bot->getBotId()] = false; + bot->addToFireInclination(m_urgency[bot->getBotId()]); + return m_urgency[bot->getBotId()]; + } + + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (now - m_double28 > 60.0) + { + std::map::iterator it = m_feedback.begin(); + while (it != m_feedback.end()) + { + if (informationManager->getInformation(it->first)) + ++it; + else + { + delete it->second; + m_feedback.erase(it++); + } + } + m_double28 = now; + } + + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + IPIUnit* const unit = equipment->getUnit(); + IPIPhysical* const physical = equipment->getPhysical(); + IPIArmament* const armament = equipment->getArmament(); + IPIMobile* const mobile = equipment->getMobile(); + IPIControlInfo* const controls = equipment->getControlInfo(); + const unsigned long long aimControls = controls->getAimControls(); + const unsigned long long driveControls = controls->getDriveControls(); + if ((aimControls & driveControls) && !bot->isAirBorn()) + { + m_pattern->unInit(bot); + m_urgency[bot->getBotId()] = 0.0f; + m_targets[bot->getBotId()] = static_cast(-1); + return 0.0f; + } + + const int strengthType = physical->getStrengthType(); + float indirectScore = 0.0f; // never updated in the shipped body + float bestScore = 0.0f; + float currentScore = 0.0f; + unsigned int countedOrders = 0; + int bestWeapon = -1; + const int side = bot->getSide(); + const unsigned int currentTarget = m_targets[bot->getBotId()]; + const int currentWeapon = m_unknown24[bot->getBotId()]; + bool keepCurrent = false; + std::vector unusedObjects; + unusedObjects.push_back(equipment->getAIObject()); + unusedObjects.push_back(0); + + const Vec3& position = equipment->getPosition(); + const unsigned int botId = bot->getBotId(); + const int orderedArea = IAIMain::m_instance->getSAI(side)->getBotOrderedPos(botId); + AIStrategicObject* const area = AIStrategicObjectManager::getInstance()->getStrategicObject(orderedArea); + const float areaFactor = area ? (static_cast(area)->isInside(position) ? 1.0f : 0.75f) : 1.0f; + equipment->getTransformation(); // result unused + Vec3 indirectPosition; + indirectPosition.x = indirectPosition.y = indirectPosition.z = 0.0f; + + const std::map& sensed = bot->getSensedObjects(); + for (std::map::const_iterator it = sensed.begin(); it != sensed.end(); ++it) + { + SensedObject* const object = it->second; + if (!(object->m_flags & 2) && !(object->m_flags & 4)) + continue; + Information* const info = informationManager->getInformation(object->m_handle); + if (!info) + continue; + Bot* const other = IBotManager::instance->getBotFromPlayerId(info->getPlayerId()); + if (other && info->isOfType(ITAir)) + { + Information* const otherTarget = informationManager->getInformation(other->getFiringTarget()); + if (otherTarget && otherTarget->getPlayerId() == bot->getPlayerId()) + continue; + } + if (20.0 > now - getBBPFeedback(object->m_handle)->m_time) + continue; + int weapon = -1; + const double seenTime = (object->m_flags & 8) ? object->m_firstSeenTime : 0.0; + const float score = updateUrgencyWithTarget(object->m_handle, info, seenTime, now, weapon, + static_cast(bot), position, equipment, armament, mobile, unit, strengthType, + areaFactor, area, countedOrders); + if (currentTarget == object->m_handle) + { + keepCurrent = true; + currentScore = score; + } + if (score > bestScore) + { + bestScore = score; + m_targets[bot->getBotId()] = object->m_handle; + bestWeapon = weapon; + } + } + + if (!keepCurrent) + { + std::vector enemies; + static_cast(AISingletonServer::m_iaiInformationEnvironment) + ->getEnemyObjects(enemies, bot, -1.0f); + for (std::vector::const_iterator it = enemies.begin(); it != enemies.end(); ++it) + { + if (20.0 > now - getBBPFeedback(*it)->m_time) + continue; + Information* const info = informationManager->getInformation(*it); + if (!info) + continue; + Bot* const other = IBotManager::instance->getBotFromPlayerId(info->getPlayerId()); + if (other && info->isOfType(ITAir)) + { + Information* const otherTarget = informationManager->getInformation(other->getFiringTarget()); + if (otherTarget && otherTarget->getPlayerId() == bot->getPlayerId()) + continue; + } + int weapon = -1; + const float score = updateUrgencyWithTarget(*it, info, 0.0, now, weapon, + static_cast(bot), position, equipment, armament, mobile, unit, strengthType, + areaFactor, area, countedOrders); + if (currentTarget == *it) + { + keepCurrent = true; + currentScore = score; + } + if (score > bestScore) + { + bestScore = score; + m_targets[bot->getBotId()] = *it; + bestWeapon = weapon; + } + } + } + + float scale = 1.0f; + // The point-target branch survives in ia-32, but its handle remains -1. + const unsigned int indirectTarget = static_cast(-1); + if (indirectTarget != static_cast(-1)) + { + m_urgency[bot->getBotId()] = 5.0f; + m_targets[bot->getBotId()] = static_cast(-1); + initializeGenerator(indirectTarget, indirectPosition, static_cast(bot), + m_unknown24[bot->getBotId()]); + return m_urgency[bot->getBotId()]; + } + if (bestScore > 0.0f) + { + if (keepCurrent) + currentScore = currentScore * 1.2f; + if (keepCurrent && currentScore > bestScore && currentWeapon == bestWeapon) + { + // Shipped quirk: restore the target, but keep the best candidate's score. + m_targets[bot->getBotId()] = currentTarget; + m_unknown24[bot->getBotId()] = bestWeapon; + } + else + { + bot->getBotId(); // result unused + m_unknown24[bot->getBotId()] = bestWeapon; + keepCurrent = false; + } + initializeGenerator(static_cast(bot), bestWeapon, false, false); + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && bot->getOrderList(m_index)->empty()) + bestScore = bestScore * bot->getMemory()->m_float8; + m_targetChanged[bot->getBotId()] = !keepCurrent; + scale = scale * modifier; + m_urgency[bot->getBotId()] = DecleiningSlopeCurve::calculate(bestScore + bestScore) * scale; + bot->addToFireInclination(m_urgency[bot->getBotId()]); + return m_urgency[bot->getBotId()]; + } + + m_targetChanged[bot->getBotId()] = !keepCurrent; + if (!(indirectScore > 0.0f)) + { + m_pattern->unInit(bot); + m_urgency[bot->getBotId()] = 0.0f; + m_targets[bot->getBotId()] = static_cast(-1); + return 0.0f; + } + m_targets[bot->getBotId()] = static_cast(-1); + initializeGenerator(static_cast(bot), -1, false, false); + const float weighted = scale * indirectScore; + indirectScore = indirectScore + indirectScore; + m_urgency[bot->getBotId()] = DecleiningSlopeCurve::calculate(indirectScore + indirectScore) * weighted; + bot->addToFireInclination(m_urgency[bot->getBotId()]); + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && bot->getOrderList(m_index)->empty()) + m_urgency[bot->getBotId()] = m_urgency[bot->getBotId()] * bot->getMemory()->m_float8; + return m_urgency[bot->getBotId()]; +} + +// ELF 0x20D0A0 +void BBFire3d::initializeGenerator(BotMain* bot, int weapon, bool a, bool b) +{ + bot->setFiringTarget(m_targets[bot->getBotId()]); + static_cast(m_pattern)->init(bot, m_targets[bot->getBotId()], weapon, a, b); +} + +// ELF 0x20D130 +void BBFire3d::initializeGenerator(unsigned int target, const Vec3& position, BotMain* bot, int weapon) +{ + bot->setFiringTarget(target); + static_cast(m_pattern)->init(bot, target, position, weapon); +} + +// ELF 0x20D190 +BBFire3d::BBPFeedback* BBFire3d::getBBPFeedback(unsigned int target) +{ + std::map::iterator it = m_feedback.find(target); + if (it != m_feedback.end()) + return it->second; + BBPFeedback* const feedback = new BBPFeedback; + feedback->m_time = -10000.0; + m_feedback.insert(std::make_pair(target, feedback)); + return feedback; +} + +// ELF 0x20D230 +float BBFire3d::updateUrgencyWithTarget(unsigned int target, Information* info, double seenTime, + double now, int& bestWeapon, BotMain* bot, const Vec3& position, Information* equipment, + IPIArmament* armament, IPIMobile* mobile, IPIUnit* unit, int strengthType, float areaFactor, + AIStrategicObject* area, unsigned int& countedOrders) +{ + if (!info || info->getSide() == bot->getSide()) + return 0.0f; + Information* const primary = informationManager->getInformation(info->getPrimaryObject(bot->getSide())); + IPIPhysical* const physical = info->getPhysical(); + if (!physical || info->isOfType(ITLowPriority) || info->isOfType(ITVegetation) + || info->isOfType(ITNoTemperature) || 0.0f >= physical->getHealth()) + return 0.0f; + + float attackFactor = 1.0f; + double attackTime; + if (bot->isAttacking(target, attackTime)) + { + float ramp = static_cast(now - attackTime) / 30.0f; + if (0.0f > ramp) + ramp = 0.0f; + else if (ramp > 1.0f) + ramp = 1.0f; + attackFactor = 1.5f - ramp * 0.5f; + } + + IPIMobile* const targetMobile = primary->getMobile(); + Vec3 targetPosition; + targetPosition.x = targetPosition.y = targetPosition.z = 0.0f; + if (targetMobile) + targetMobile->getPositionEstimate(targetPosition); + else + targetPosition = primary->getPosition(); + Vec3 direction; + direction.x = targetPosition.x - position.x; + direction.y = targetPosition.y - position.y; + direction.z = targetPosition.z - position.z; + float distance = std::sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z); + if (0.5f > distance) + distance = 0.5f; + if (distance > 0.00001f) + { + const float reciprocal = 1.0f / distance; + direction.x = direction.x * reciprocal; + direction.y = direction.y * reciprocal; + direction.z = direction.z * reciprocal; + } + + float weaponScores[8]; // shipped body has no upper bound on the weapon count + float bestStrength = 0.0f; + float maxRange = 0.0f; + const std::vector& weapons = armament->getWeapons(); + unsigned int i = 0; + for (; i < weapons.size(); ++i) + { + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (!weapon) + { + weaponScores[i] = 0.0f; + continue; + } + const float strength = static_cast(weapon->getStrength(physical->getStrengthType())); + int ammo = weapon->getAmmo(); + if (ammo == -1) + ammo = 0x10000; + weaponScores[i] = ammo > 0 ? strength : 0.0f; + if (weaponScores[i] > bestStrength) + { + bestWeapon = i; + bestStrength = weaponScores[i]; + } + if (weapon->getMaxRange() > maxRange) + maxRange = weapon->getMaxRange(); + } + if (bestStrength == 0.0f) + return 0.0f; + for (; i < 8; ++i) + weaponScores[i] = 0.0f; + + float ageFactor = 1.0f; + if (seenTime > 0.0) + { + const float age = static_cast(now - seenTime); + ageFactor = 1.0f / (age * 0.05f + 1.0f); + } + Vec3 targetSpeed; + targetSpeed.x = targetSpeed.y = targetSpeed.z = 0.0f; + if (targetMobile) + targetSpeed = targetMobile->getSpeed(); + const float speed = std::sqrt(targetSpeed.x * targetSpeed.x + targetSpeed.y * targetSpeed.y + + targetSpeed.z * targetSpeed.z); + + bool calculateApproach = true; + float approachFactor = 1.0f; + if (primary->isOfType(ITAir)) + { + if (armament->isAntiAircraft() == 0) + { + if (primary->getAltitude() > 5.0f) + return 0.0f; + if (distance > maxRange * 0.5f || speed > 15.0f) + { + approachFactor = 0.0f; + calculateApproach = false; + } + } + else if (!equipment->isOfType(ITAir) && maxRange * 0.9f > distance) + { + calculateApproach = false; + } + } + if (calculateApproach && targetMobile) + { + if (distance > maxRange) + { + float maxSpeed = 0.0f; + Vec3 ownSpeed; + ownSpeed.x = ownSpeed.y = ownSpeed.z = 0.0f; + if (mobile) + { + maxSpeed = mobile->getMaxSpeed(); + ownSpeed = mobile->getSpeed(); + } + if (targetMobile->getMaxSpeed() - maxSpeed > 5.0f) + { + Vec3 lateral; + lateral.x = direction.z - direction.y * 0.0f; + lateral.y = direction.x * 0.0f - direction.z * 0.0f; + lateral.z = direction.y * 0.0f - direction.x; + const Vec3& velocity = targetMobile->getSpeed(); + float radial = (direction.x * velocity.x + direction.y * velocity.y + direction.z * velocity.z) + - (direction.x * ownSpeed.x + direction.y * ownSpeed.y + direction.z * ownSpeed.z); + if (0.0f > radial) + radial = 0.0f; + float transverse = (lateral.x * velocity.x + lateral.y * velocity.y + lateral.z * velocity.z) + - (lateral.x * ownSpeed.x + lateral.y * ownSpeed.y + lateral.z * ownSpeed.z); + if (0.0f > transverse) + transverse = 0.0f; + const float targetSpeedMagnitude = std::sqrt(velocity.x * velocity.x + velocity.y * velocity.y + + velocity.z * velocity.z); + approachFactor = 0.25f / (radial * 2.0f + 1.0f + transverse * 2.0f + + targetSpeedMagnitude * 0.5f); + } + else + approachFactor = 0.25f; + } + else + { + const Vec3& velocity = targetMobile->getSpeed(); + approachFactor = 1.0f / (std::sqrt(velocity.x * velocity.x + velocity.y * velocity.y + + velocity.z * velocity.z) * 0.5f + 1.0f); + } + } + + float targetAreaFactor = areaFactor; + if (mobile && !equipment->isOfType(ITAir) && area + && !static_cast(area)->isInside(targetPosition)) + targetAreaFactor = targetAreaFactor * 0.75f; + if (!info->getUnit() || !vehicleOccupied(target, bot->getSide())) + return 0.0f; + + float strengthSum = 0.0f; + float score = 0.0f; + unsigned int partHandle = target; + int secondary = info->getFirstSecondaryObjectIterator(); + const int targetStrengthType = info->getPhysical()->getStrengthType(); + const float* const armourValues = static_cast(CommonSingletonServer::m_iaiSettings)->getArmourClassValues(); + Information* part = info; + do + { + IPIUnit* const partUnit = part->getUnit(); + strengthSum = strengthSum + partUnit->getBattleStrengths()[strengthType]; + float orderFactor = 1.0f; + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() + && countedOrders < bot->getOrderList(m_index)->size()) + { + std::list::iterator end = bot->getOrderList(m_index)->end(); + std::list::iterator begin = bot->getOrderList(m_index)->begin(); + std::list::iterator searchEnd = bot->getOrderList(m_index)->end(); + std::list::iterator found = std::find(begin, searchEnd, partHandle); + if (found != end) + { + ++countedOrders; + orderFactor = bot->getMemory()->m_float8; + } + } + score = (partUnit->getBattleStrengths()[strengthType] + part->getStrength() + + unit->getBattleStrengths()[targetStrengthType]) * armourValues[targetStrengthType] + * orderFactor * targetAreaFactor + score; + partHandle = info->getSecondaryObject(secondary, bot->getSide()); + part = informationManager->getInformation(partHandle); + } + while (part); + + float rangeFactor; + if (primary->isOfType(ITAir)) + { + rangeFactor = 1.0f - distance / (maxRange * 1.5f); + if (!(rangeFactor > 0.0f)) + rangeFactor = 0.0f; + if (armament->isAntiAircraft()) + score = score + score; + } + else + { + float fraction = distance / (maxRange * 3.0f); + if (fraction > 1.0f) + fraction = 1.0f; + rangeFactor = 1.0f - fraction; + } + const Mat4& transformation = equipment->getTransformation(); + float facing = direction.x * transformation.m[8] + direction.y * transformation.m[9] + + direction.z * transformation.m[10] + 1.0f; + if (!(facing > 0.5f)) + facing = 0.5f; + rangeFactor = facing * 0.5f * rangeFactor; + rangeFactor = bestStrength * rangeFactor; + rangeFactor = rangeFactor * ageFactor; + rangeFactor = rangeFactor * approachFactor; + score = rangeFactor * attackFactor * score; + if (strengthSum <= static_cast(bot->getHarmlessThrsh())) + score = score * 0.01f; + return score; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire3d.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire3d.h new file mode 100644 index 000000000..f99edb204 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire3d.h @@ -0,0 +1,56 @@ +// Aircraft fire behaviour. Scores sensed and spatial-query targets and initializes BBPFire. +// Recovered from the symbolized Linux 1.50 libaidll.so; offsets refer to the ia-32 image. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIRE3D_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIRE3D_H + +#include "../../../../Math/Vec3.h" +#include "BotBehaviour.h" + +#include + +namespace dice { +namespace hfe { + +namespace ai { + +class AIStrategicObject; +class BBPFire; +class Bot; +class BotMain; +class IPIArmament; +class IPIMobile; +class IPIUnit; +class Information; +class UrgeCurve; + +// ELF: vtable 0x4BABA0 (13 words), operator new 0x3C, package G-vehicles. +class BBFire3d : public BotBehaviour +{ +public: + struct BBPFeedback + { + // ELF 0x20D190 initializes the sole double to -10000.0. + double m_time; + }; + BBFire3d(unsigned char, unsigned char, BBPFire*, UrgeCurve*, float*); // 0x20BCF0 + virtual ~BBFire3d(); // 0x20BEF0 + + virtual float calculateUrgency(Bot*, bool, float); // 0x20C070, slot +0x28; from the base declaration + + void initializeGenerator(BotMain*, int, bool, bool); // 0x20D0A0 + void initializeGenerator(unsigned int, const Vec3&, BotMain*, int); // 0x20D130 + BBPFeedback* getBBPFeedback(unsigned int); // 0x20D190: find or allocate a feedback record + float updateUrgencyWithTarget(unsigned int, Information*, double, double, int&, BotMain*, const Vec3&, Information*, IPIArmament*, IPIMobile*, IPIUnit*, int, float, AIStrategicObject*, unsigned int&); // 0x20D230 + + // Fields from the constructor 0x20BCF0 and destructor 0x20BEF0 (operator new 0x3C). + /* +0x24 */ unsigned int* m_unknown24; // per-bot weapon index; initialized to -1 + /* +0x28 */ double m_double28; // last feedback cleanup time; initialized to 0.0 + /* +0x30 */ std::map m_feedback; // target -> feedback; the destructor only frees the nodes [INFERRED] name +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIRE3D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireArtilleryDriver.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireArtilleryDriver.cpp new file mode 100644 index 000000000..6ba2d65b3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireArtilleryDriver.cpp @@ -0,0 +1,80 @@ +// Artillery driver fire behaviour, recovered from the symbolized Linux 1.50 libaidll.so. + +// static init: ELF 0x20F070 (__tcf_0 0x20F0D0, _GLOBAL__I 0x20F100): 's Init object only. +#include + +#include "BBFireArtilleryDriver.h" + +#include "BBFireLargeBore.h" +#include "BBFireUnarmed.h" +#include "../AIBot/BotMain.h" +#include "../AIBotBehaviourPattern/BBPFire.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x20E3F0 (C2), 0x20E870 (C1) +BBFireArtilleryDriver::BBFireArtilleryDriver(unsigned char index, unsigned char queue, BBPFire* pattern, + UrgeCurve* curve, float* modifiers) + : BotBehaviour(modifiers, curve, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_unarmed = checkPointer(new BBFireUnarmed(index, queue)); + m_gunner = checkPointer(new BBFireLargeBore(index, queue, pattern, curve, modifiers, false)); + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int bots = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_targets = checkPointer(new unsigned int[bots]); + for (int i = 0; i < bots; ++i) + { + m_urgency[i] = 0.0f; + m_targets[i] = static_cast(-1); + } + pattern->setUrgencyGenerator(this); +} + +// ELF 0x20ECF0 (D2), 0x20ED70 (D1), 0x20EDF0 (D0) +BBFireArtilleryDriver::~BBFireArtilleryDriver() +{ + if (m_targets) + delete[] m_targets; + if (m_unarmed) + delete m_unarmed; + if (m_gunner) + delete m_gunner; + // Shipped defect: the gunner and this behaviour both own the same pattern through their bases. +} + +// ELF 0x20EE70 +float BBFireArtilleryDriver::calculateUrgency(Bot* bot, bool recalculate, float modifier) +{ + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + int secondary; + Information* const gunner = informationManager->getInformation(equipment->getFirstSecondaryObject(secondary, bot->getSide())); + // Shipped defect: neither the secondary object nor its unit is checked for null. + if (gunner->getUnit()->isOccupied()) + { + const float urgency = m_gunner->calculateUrgency(bot, recalculate, modifier, gunner, equipment->getMobile()); + m_urgency[bot->getBotId()] = urgency; + const bool changed = m_gunner->hasChangedTarget(bot); + m_targetChanged[bot->getBotId()] = changed; + } + else + { + m_targetChanged[bot->getBotId()] = false; + const float urgency = m_unarmed->calculateUrgency(bot, recalculate, modifier); + m_urgency[bot->getBotId()] = urgency; + } + return m_urgency[bot->getBotId()]; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireArtilleryDriver.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireArtilleryDriver.h new file mode 100644 index 000000000..e1d3727dc --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireArtilleryDriver.h @@ -0,0 +1,38 @@ +// Artillery driver fire behaviour: delegates to the occupied gun seat or the unarmed behaviour. +// Recovered from the symbolized Linux 1.50 libaidll.so; offsets refer to the ia-32 image. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIREARTILLERYDRIVER_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIREARTILLERYDRIVER_H + +#include "BotBehaviour.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BBPFire; +class BBFireLargeBore; +class BBFireUnarmed; +class Bot; +class UrgeCurve; + +// ELF: vtable 0x4BAC40 (13 words), operator new 0x2C, package H-deferred. +class BBFireArtilleryDriver : public BotBehaviour +{ +public: + BBFireArtilleryDriver(unsigned char, unsigned char, BBPFire*, UrgeCurve*, float*); // 0x20E870 + virtual ~BBFireArtilleryDriver(); // 0x20ED70 + + virtual float calculateUrgency(Bot*, bool, float); // 0x20EE70, slot +0x28; from the base declaration + +private: + /* +0x24 */ BBFireUnarmed* m_unarmed; + /* +0x28 */ BBFireLargeBore* m_gunner; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIREARTILLERYDRIVER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireInfantery.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireInfantery.cpp new file mode 100644 index 000000000..725a92fe2 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireInfantery.cpp @@ -0,0 +1,36 @@ +// Fire behaviour of infantry (AI/AIDLL/AI/AIBotBehaviour/BBFireInfantery.cpp in the image). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. + +// static init: ELF 0x20F310 (__tcf_0 0x20F370, _GLOBAL__I 0x20F3A0): 's Init object only. +#include + +#include "BBFireInfantery.h" + +#include "../AIBotBehaviourPattern/BBPFireInfantery.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x20F190 +BBFireInfantery::BBFireInfantery(unsigned char index, unsigned char queue, BBPFireInfantery* pattern, + UrgeCurve* curve, float* modifiers) + : BBFire(index, queue, pattern, curve, modifiers) + , m_infantryPattern(pattern) +{ +} + +// ELF 0x20F240 +BBFireInfantery::~BBFireInfantery() +{ +} + +// ELF 0x20F2C0: forwards to BBFire's. +void BBFireInfantery::initializeGenerator(BotMain* bot, int i, bool a, bool b) +{ + BBFire::initializeGenerator(bot, i, a, b); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireInfantery.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireInfantery.h new file mode 100644 index 000000000..acf718dd6 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireInfantery.h @@ -0,0 +1,38 @@ +// Fire behaviour of infantry: BBFire with the infantry fire pattern (BBPFireInfantery, package E). +// Recovered from libaidll.so (Linux 1.5.3153); every body carries its ELF address. Package D. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIREINFANTERY_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIREINFANTERY_H + +#include "BBFire.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BBPFireInfantery; +class BotMain; +class UrgeCurve; + +// ELF: vtable 0x4BACA0 (15 words), operator new 0x44, package D-behaviours. +class BBFireInfantery : public BBFire +{ +public: + BBFireInfantery(unsigned char index, unsigned char queue, BBPFireInfantery* pattern, UrgeCurve* curve, + float* modifiers); // 0x20F190 + virtual ~BBFireInfantery(); // 0x20F240 + + virtual void initializeGenerator(BotMain*, int, bool, bool); // 0x20F2C0, slot +0x34 + +private: + // The constructor's pattern argument again, typed (BBFire keeps it as the generic pattern at +0x0C). + /* +0x40 */ BBPFireInfantery* m_infantryPattern; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIREINFANTERY_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireLargeBore.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireLargeBore.cpp new file mode 100644 index 000000000..65ce5fd4e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireLargeBore.cpp @@ -0,0 +1,672 @@ +// Large-bore fire behaviour, recovered from the symbolized Linux 1.50 libaidll.so. + +// static init: ELF 0x212EA0 (__tcf_0 0x212F00, _GLOBAL__I 0x212F30): 's Init object only. +#include + +#include "BBFireLargeBore.h" + +#include "../AIUtils/CustomCurve.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotMemory.h" +#include "../AIBot/SensedObject.h" +#include "../AIBotBehaviourPattern/BBPFire.h" +#include "../AIBotBehaviourPattern/BBPFire2d.h" +#include "../AIKnowledge/BFInformationEnvironment.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../AIStrategic/SAI.h" +#include "../AIStrategicEntity/AIStrategicArea.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" +#include "../AIUtils/VehicleOccupancy.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AIMain.h" +#include "../Main/IAIPathfinding.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +#include +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x20F3C0 (C2) / 0x20F7E0 (C1); vtable GOT -0x1514. As BBFire3d's, plus the bool at +0x3C, +// and both per-bot arrays go through the inlined checkPointer: +0x08 targets, then +0x24; every bot +// starts with urgency 0.0f and both slots -1; the pattern gets this behaviour as its urgency +// generator. +BBFireLargeBore::BBFireLargeBore(unsigned char index, unsigned char queue, BBPFire* pattern, + UrgeCurve* curve, float* modifiers, bool flag) + : BotBehaviour(modifiers, curve, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) + , m_double28(0.0) +{ + m_flag3C = flag; + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int bots = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_targets = checkPointer(new unsigned int[bots]); + m_unknown24 = checkPointer(new unsigned int[bots]); + for (int i = 0; i < bots; ++i) + { + m_urgency[i] = 0.0f; + m_unknown24[i] = static_cast(-1); + m_targets[i] = static_cast(-1); + } + pattern->setUrgencyGenerator(this); +} + +// ELF 0x20FB80 (D2) / 0x20FC40 (D1) / 0x20FD00 (D0): delete[] +0x08, then +0x24 (each when set), +// then the map's destructor (nodes only) and ~BotBehaviour. +BBFireLargeBore::~BBFireLargeBore() +{ + if (m_targets) + delete[] m_targets; + if (m_unknown24) + delete[] m_unknown24; +} + +// ELF 0x20FDC0 +float BBFireLargeBore::calculateUrgency(Bot* bot, bool recalculate, float modifier) +{ + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + return calculateUrgency(bot, recalculate, modifier, equipment, equipment->getMobile()); +} + +// ELF 0x212BE0 +void BBFireLargeBore::initializeGenerator(BotMain* bot, int weapon, bool a, bool b, bool spatial) +{ + bot->setFiringTarget(m_targets[bot->getBotId()]); + BBPFire* const pattern = static_cast(m_pattern); + if (pattern->getImplementationType() == 2) + static_cast(m_pattern)->init(bot, m_targets[bot->getBotId()], weapon, a, b, spatial); + else + pattern->init(bot, m_targets[bot->getBotId()], weapon, a, b); +} + +// ELF 0x20FE50 +float BBFireLargeBore::calculateUrgency(Bot* bot, bool recalculate, float modifier, + Information* equipment, IPIMobile* mobile) +{ + if (!recalculate) + { + if (!m_pattern->isInitiated(bot)) + { + m_targetChanged[bot->getBotId()] = false; + return m_urgency[bot->getBotId()] = 0.0f; + } + if (!informationManager->getInformation(m_targets[bot->getBotId()])) + { + m_targetChanged[bot->getBotId()] = true; + m_pattern->unInit(bot); + return m_urgency[bot->getBotId()] = 0.0f; + } + m_targetChanged[bot->getBotId()] = false; + bot->addToFireInclination(m_urgency[bot->getBotId()]); + return m_urgency[bot->getBotId()]; + } + + bool bestSpatial = false; + bool secondarySpatial = false; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + const float* const armourValues = static_cast(CommonSingletonServer::m_iaiSettings)->getArmourClassValues(); + const int equipmentType = equipment->getUnit()->getEquipmentType(); + if (now - m_double28 > 60.0) + { + std::map::iterator it = m_feedback.begin(); + while (it != m_feedback.end()) + { + if (informationManager->getInformation(it->first)) + ++it; + else + { + delete it->second; + m_feedback.erase(it++); + } + } + m_double28 = now; + } + + IPIUnit* const unit = equipment->getUnit(); + IPIControlInfo* const controls = equipment->getControlInfo(); + IPIPhysical* const physical = equipment->getPhysical(); + IPIArmament* armament; + if (m_flag3C) + { + int secondary; + Information* const gunner = informationManager->getInformation( + equipment->getFirstSecondaryObject(secondary, bot->getSide())); + armament = gunner->getArmament(); // shipped: no secondary-object null guard + } + else + armament = equipment->getArmament(); + const int strengthType = physical->getStrengthType(); + const Vec3 position = equipment->getPosition(); + float deadScore = 0.0f; // never written again in the image + float bestScore = 0.0f; + float secondaryScore = 0.0f; + float currentScore = 0.0f; + int bestWeapon = -1; + int secondaryWeapon = -1; + unsigned int secondaryTarget = static_cast(-1); + unsigned int countedOrders = 0; + WeaponInfo* selectedWeaponInfo = 0; + const int side = bot->getSide(); + const unsigned int currentTarget = m_targets[bot->getBotId()]; + const unsigned int currentWeapon = m_unknown24[bot->getBotId()]; + bool keepCurrent = false; + IAIPathfinding* const pathfinding = IAIPathfinding::instance; + const unsigned int botId = bot->getBotId(); + const int orderedArea = IAIMain::m_instance->getSAI(side)->getBotOrderedPos(botId); + AIStrategicArea* const area = static_cast( + AIStrategicObjectManager::getInstance()->getStrategicObject(orderedArea)); + const float areaFactor = area ? (area->isInside(position) ? 1.0f : 0.75f) : 1.0f; + IAIObjectEnvironment* const environment = static_cast(CommonSingletonServer::m_iaiObjectEnvironment); + + // [INFERRED] local helper names for repeated inline expansions in this body. + // ELF 0x212AA2 / 0x211830: attacking-target bonus, fading from 1.5 to 1 over 30 seconds. + const auto attackFactorFor = [&](unsigned int handle) -> float + { + double attackTime; + if (!static_cast(bot)->isAttacking(handle, attackTime)) + return 1.0f; + float ramp = static_cast(now - attackTime) / 30.0f; + if (0.0f > ramp) + ramp = 0.0f; + else if (ramp > 1.0f) + ramp = 1.0f; + return 1.5f - ramp * 0.5f; + }; + + // ELF 0x211CE0..0x211E25 / 0x212588..0x21289E, and 0x210CCD..0x210E1E / + // 0x211318..0x211632: moving-target and anti-aircraft weights. + const auto approachFactorFor = [&](Information* info, IPIMobile* targetMobile, + const Vec3& direction, float distance, float maxRange, + bool sensed) -> float + { + Vec3 targetSpeed; + targetSpeed.x = targetSpeed.y = targetSpeed.z = 0.0f; + if (targetMobile) + targetSpeed = targetMobile->getSpeed(); + const float speed = std::sqrt(targetSpeed.x * targetSpeed.x + targetSpeed.y * targetSpeed.y + + targetSpeed.z * targetSpeed.z); + if (!equipment->isOfType(ITAir) && info->isOfType(ITAir)) + { + if (armament->isAntiAircraft() == 0) + { + if (distance > maxRange * 0.5f || speed > 15.0f) + return 0.0f; + } + else if (maxRange * 0.9f > distance) + return 1.0f; + } + if (!targetMobile) + return 1.0f; + if (!(distance > maxRange)) + { + const Vec3& velocity = targetMobile->getSpeed(); + return 1.0f / (std::sqrt(velocity.x * velocity.x + velocity.y * velocity.y + + velocity.z * velocity.z) * 0.5f + 1.0f); + } + float maxSpeed = 0.0f; + Vec3 ownSpeed; + ownSpeed.x = ownSpeed.y = ownSpeed.z = 0.0f; + if (mobile) + { + maxSpeed = mobile->getMaxSpeed(); + ownSpeed = mobile->getSpeed(); + } + if (!(targetMobile->getMaxSpeed() - maxSpeed > 5.0f)) + return 0.25f; + Vec3 lateral; + lateral.x = direction.z - direction.y * 0.0f; + lateral.y = direction.x * 0.0f - direction.z * 0.0f; + lateral.z = direction.y * 0.0f - direction.x; + const Vec3& velocity = targetMobile->getSpeed(); + float radial = (direction.x * velocity.x + direction.y * velocity.y + direction.z * velocity.z) + - (direction.x * ownSpeed.x + direction.y * ownSpeed.y + direction.z * ownSpeed.z); + if (0.0f > radial) + radial = 0.0f; + float transverse = (lateral.x * velocity.x + lateral.y * velocity.y + lateral.z * velocity.z) + - (lateral.x * ownSpeed.x + lateral.y * ownSpeed.y + lateral.z * ownSpeed.z); + if (0.0f > transverse) + transverse = 0.0f; + const float magnitude = std::sqrt(velocity.x * velocity.x + velocity.y * velocity.y + velocity.z * velocity.z); + const float relative = sensed ? transverse * 2.0f + radial * 2.0f + 1.0f + : radial * 2.0f + 1.0f + transverse * 2.0f; + return 0.25f / (relative + magnitude * 0.5f); + }; + + // ELF 0x211F0F..0x212063 and 0x210F05..0x21106E: target plus secondary-seat strengths. + const auto strengthsFor = [&](Information* info, unsigned int target, float targetAreaFactor, + float& strengthSum) -> float + { + float score = 0.0f; + strengthSum = 0.0f; + unsigned int partHandle = target; + int secondary = info->getFirstSecondaryObjectIterator(); + const int targetStrengthType = info->getPhysical()->getStrengthType(); + Information* part = info; + do + { + IPIUnit* const partUnit = part->getUnit(); + strengthSum = strengthSum + partUnit->getBattleStrengths()[strengthType]; + bool ordered = false; + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() + && countedOrders < bot->getOrderList(m_index)->size()) + { + const std::list::iterator end = bot->getOrderList(m_index)->end(); + const std::list::iterator begin = bot->getOrderList(m_index)->begin(); + const std::list::iterator searchEnd = bot->getOrderList(m_index)->end(); + ordered = std::find(begin, searchEnd, partHandle) != end; + } + float orderFactor = 1.0f; + if (ordered) + { + ++countedOrders; + orderFactor = bot->getMemory()->m_float8; + } + score = (partUnit->getBattleStrengths()[strengthType] + part->getStrength() + + unit->getBattleStrengths()[targetStrengthType]) * armourValues[targetStrengthType] + * orderFactor * targetAreaFactor + score; + partHandle = info->getSecondaryObject(secondary, side); + part = informationManager->getInformation(partHandle); + } + while (part); + return score; + }; + + const std::map& sensed = bot->getSensedObjects(); + for (std::map::const_iterator it = sensed.begin(); it != sensed.end(); ++it) + { + SensedObject* const object = it->second; + Information* const info = informationManager->getInformation(it->first); + if (!info || info->getSide() == side) + continue; + IPIPhysical* const targetPhysical = info->getPhysical(); + if (!targetPhysical || info->isOfType(ITLowPriority) || info->isOfType(ITVegetation) + || info->isOfType(ITNoTemperature) || 0.0f >= targetPhysical->getHealth()) + continue; + if ((object->m_flags & 0x20) && object->m_fireRating < 0) + continue; + if (20.0 > now - getBBPFeedback(object->m_handle)->m_time) + continue; + const float attackFactor = attackFactorFor(object->m_handle); + IPIMobile* const targetMobile = info->getMobile(); + Vec3 targetPosition; + targetPosition.x = targetPosition.y = targetPosition.z = 0.0f; + if (targetMobile) + targetMobile->getPositionEstimate(targetPosition); + else + targetPosition = info->getPosition(); + Vec3 direction; + direction.x = targetPosition.x - position.x; + direction.y = targetPosition.y - position.y; + direction.z = targetPosition.z - position.z; + float distance = std::sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z); + if (0.5f > distance) + distance = 0.5f; + const float inverse = 1.0f / distance; + direction.x = direction.x * inverse; + direction.y = direction.y * inverse; + direction.z = direction.z * inverse; + + int weaponIndex = -1; + float maxRange = 0.0f; + float bestStrength = 0.0f; + float weaponScores[8]; // shipped: no bound on the weapon count + const std::vector& weapons = armament->getWeapons(); + unsigned int i = 0; + for (; i < weapons.size(); ++i) + { + if (!WeaponInfoManager::m_instance->getInformation(weapons[i])) + { + weaponScores[i] = 0.0f; + continue; + } + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + int ammo = weapon->getAmmo(); + if (ammo == -1) + ammo = 0x10000; + if (ammo > 0) + { + float strength = static_cast(weapon->getStrength(targetPhysical->getStrengthType())); + if (!(weapon->getMaxRange() >= distance)) + strength = strength * 0.25f; + weaponScores[i] = strength; + } + else + weaponScores[i] = 0.0f; + if (weapon->getMinRange() > distance) + weaponScores[i] = 0.0f; + if (weaponScores[i] > bestStrength) + { + weaponIndex = i; + bestStrength = weaponScores[i]; + selectedWeaponInfo = weapon; + } + if (weapon->getMaxRange() > maxRange) + maxRange = weapon->getMaxRange(); + } + if (bestStrength == 0.0f) + continue; + for (; i < 8; ++i) + weaponScores[i] = 0.0f; + + float ageFactor = 1.0f; + if (object->m_flags & 8) + { + const float age = static_cast(now - object->m_firstSeenTime); + ageFactor = 1.0f / (age * 0.05f + 1.0f); + } + else if (!mobile) + { + Vec3 unusedCameraPosition; + unusedCameraPosition.x = unusedCameraPosition.y = unusedCameraPosition.z = 0.0f; + controls->getCameraBasePos(unusedCameraPosition); + const Mat4& transform = info->getTransformation(); + const Vec3& local = object->m_seenPosition; + Vec3 point; + point.x = local.x * transform.m[0] + local.y * transform.m[4] + local.z * transform.m[8] + transform.m[12]; + point.y = local.x * transform.m[1] + local.y * transform.m[5] + local.z * transform.m[9] + transform.m[13]; + point.z = local.x * transform.m[2] + local.y * transform.m[6] + local.z * transform.m[10] + transform.m[14]; + const Vec3& weaponPosition = selectedWeaponInfo->getPosition(); + Vec3 aim; + aim.x = point.x - weaponPosition.x; + aim.y = point.y - weaponPosition.y; + aim.z = point.z - weaponPosition.z; + if (!controls->validateCameraDirectionYaw(aim)) + continue; + } + + const float approachFactor = approachFactorFor(info, targetMobile, direction, distance, maxRange, true); + if (distance > maxRange * 0.89f) + { + if (!mobile) + continue; + const Vec3& target = info->getPosition(); + const int vehicle = mobile->getVehicleNumber(); + if (pathfinding->isValidPosition(vehicle, equipmentType, target, true)) + continue; + } + else if (!mobile) + { + Vec3 from; + from.x = from.y = from.z = 0.0f; + Vec3 to; + to.x = to.y = to.z = 0.0f; + const Mat4* const camera = static_cast(bot->getPlayer()->getCameraTransformation()); + from.x = camera->m[12]; + from.y = camera->m[13]; + from.z = camera->m[14]; + std::vector ignored; + ignored.push_back(equipment->getAIObject()); + ignored.push_back(info->getAIObject()); + const Mat4& transform = info->getTransformation(); + const Vec3& local = object->m_seenPosition; + to.x = local.x * transform.m[0] + local.y * transform.m[4] + local.z * transform.m[8] + transform.m[12]; + to.y = local.x * transform.m[1] + local.y * transform.m[5] + local.z * transform.m[9] + transform.m[13]; + to.z = local.x * transform.m[2] + local.y * transform.m[6] + local.z * transform.m[10] + transform.m[14]; + if (targetMobile) + { + Vec3 estimate; + estimate.x = estimate.y = estimate.z = 0.0f; + targetMobile->getPositionEstimate(now, estimate); + const Vec3& currentPosition = info->getPosition(); + to.x = (estimate.x - currentPosition.x) + to.x; + to.y = (estimate.y - currentPosition.y) + to.y; + to.z = (estimate.z - currentPosition.z) + to.z; + } + bool hit; + if (environment->collideLineWithWorld(from, to, ignored, false, 0.7f, false, hit)) + continue; + } + float targetAreaFactor = areaFactor; + if (mobile && area && !area->isInside(targetPosition)) + targetAreaFactor = targetAreaFactor * 0.75f; + if (!info->getUnit() || !vehicleOccupied(object->m_handle, side)) + continue; + float strengthSum; + float score = strengthsFor(info, object->m_handle, targetAreaFactor, strengthSum); + float fraction = (distance * 1.5f) / maxRange; + if (!(fraction > 0.1f)) + fraction = 0.1f; + if (fraction > 1.0f) + fraction = 1.0f; + score = (1.0f - fraction) * bestStrength * ageFactor * approachFactor * attackFactor * score; + if (strengthSum <= static_cast(static_cast(bot)->getHarmlessThrsh())) + score = score * 0.33f; + if (info->getUnit() && score > secondaryScore) + { + secondaryScore = score; + secondaryTarget = it->first; + secondaryWeapon = weaponIndex; + } + } + + if (armament->isAntiAircraft() == 0) + { + std::vector enemies; + static_cast(AISingletonServer::m_iaiInformationEnvironment) + ->getEnemyObjects(enemies, bot, 850.0f); + for (std::vector::const_iterator it = enemies.begin(); it != enemies.end(); ++it) + { + Information* const info = informationManager->getInformation(*it); + if (!info || info->getSide() == side) + continue; + IPIPhysical* const targetPhysical = info->getPhysical(); + if (!targetPhysical || info->isOfType(ITLowPriority) || info->isOfType(ITVegetation) + || info->isOfType(ITNoTemperature) || 0.0f >= targetPhysical->getHealth()) + continue; + if (20.0 > now - getBBPFeedback(*it)->m_time) + continue; + const float attackFactor = attackFactorFor(*it); + if (!mobile) + { + Vec3 cameraPosition; + cameraPosition.x = cameraPosition.y = cameraPosition.z = 0.0f; + controls->getCameraBasePos(cameraPosition); + const Vec3& target = info->getPosition(); + Vec3 aim; + aim.x = target.x - cameraPosition.x; + aim.y = target.y - cameraPosition.y; + aim.z = target.z - cameraPosition.z; + const float lengthSquared = aim.x * aim.x + aim.y * aim.y + aim.z * aim.z; + if (!(std::fabs(lengthSquared - 1.0f) < 1.19209290e-7f)) + { + if (std::fabs(lengthSquared) < 1.19209290e-7f) + aim.x = aim.y = aim.z = 0.0f; + else + { + const float reciprocal = 1.0f / std::sqrt(lengthSquared); + aim.x = aim.x * reciprocal; + aim.y = aim.y * reciprocal; + aim.z = aim.z * reciprocal; + } + } + if (!controls->validateCameraDirectionYaw(aim)) + continue; + } + IPIMobile* const targetMobile = info->getMobile(); + Vec3 targetPosition; + targetPosition.x = targetPosition.y = targetPosition.z = 0.0f; + if (targetMobile) + targetMobile->getPositionEstimate(targetPosition); + else + targetPosition = info->getPosition(); + Vec3 direction; + direction.x = targetPosition.x - position.x; + direction.y = targetPosition.y - position.y; + direction.z = targetPosition.z - position.z; + float distance = std::sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z); + if (0.5f > distance) + distance = 0.5f; + const float inverse = 1.0f / distance; + direction.x = direction.x * inverse; + direction.y = direction.y * inverse; + direction.z = direction.z * inverse; + int weaponIndex = -1; + float maxRange = 0.0f; + float bestStrength = 0.0f; + float weaponScores[8]; // shipped: no upper bound on weapons.size() + const std::vector& weapons = armament->getWeapons(); + unsigned int i = 0; + for (; i < weapons.size(); ++i) + { + if (!WeaponInfoManager::m_instance->getInformation(weapons[i])) + { + weaponScores[i] = 0.0f; + continue; + } + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + const float strength = static_cast(weapon->getStrength(targetPhysical->getStrengthType())); + int ammo = weapon->getAmmo(); + if (ammo == -1) + ammo = 0x10000; + weaponScores[i] = ammo > 0 ? strength / (10.0f / static_cast(ammo) + 1.0f) : 0.0f; + if (weaponScores[i] > bestStrength) + { + bestStrength = weaponScores[i]; + weaponIndex = i; + } + if (weapon->getMaxRange() > maxRange) + maxRange = weapon->getMaxRange(); + } + if (bestStrength == 0.0f) + continue; + for (; i < 8; ++i) + weaponScores[i] = 0.0f; + const float approachFactor = approachFactorFor(info, targetMobile, direction, distance, maxRange, false); + if (distance > maxRange * 0.89f) + { + if (!mobile) + continue; + const Vec3& target = info->getPosition(); + const int vehicle = mobile->getVehicleNumber(); + if (pathfinding->isValidPosition(vehicle, equipmentType, target, true)) + continue; + } + float targetAreaFactor = areaFactor; + if (mobile && area && !area->isInside(targetPosition)) + targetAreaFactor = targetAreaFactor * 0.75f; + if (!info->getUnit() || !vehicleOccupied(*it, side)) + continue; + float strengthSum; + float score = strengthsFor(info, *it, targetAreaFactor, strengthSum); + float fraction = distance / (maxRange * 1.5f); + if (!(fraction > 0.1f)) + fraction = 0.1f; + if (fraction > 1.0f) + fraction = 1.0f; + score = (1.0f - fraction) * bestStrength * approachFactor * attackFactor * 0.75f * score; + if (!(strengthSum > static_cast(static_cast(bot)->getHarmlessThrsh()))) + { + if (score > secondaryScore) + { + secondaryScore = score; + secondaryWeapon = weaponIndex; + secondaryTarget = *it; + secondarySpatial = true; + } + } + else + { + if (currentTarget == *it) + { + currentScore = score; + keepCurrent = true; + } + if (score > bestScore) + { + bestScore = score; + m_targets[bot->getBotId()] = *it; + bestWeapon = weaponIndex; + bestSpatial = true; + } + } + } + } + + float scale = 1.0f; + if (bestScore > 0.0f) + { + if (keepCurrent) + currentScore = currentScore * 1.2f; + if (keepCurrent && currentScore > bestScore) + { + m_targets[bot->getBotId()] = currentTarget; + m_unknown24[bot->getBotId()] = currentWeapon; + } + else + { + bot->getBotId(); // result unused + // Shipped defect: load the previous slot instead of storing the newly selected weapon. + bestWeapon = m_unknown24[bot->getBotId()]; + keepCurrent = false; + } + initializeGenerator(static_cast(bot), bestWeapon, false, false, bestSpatial); + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && bot->getOrderList(m_index)->empty()) + bestScore = bestScore * bot->getMemory()->m_float8; + m_targetChanged[bot->getBotId()] = !keepCurrent; + scale = scale * modifier; + m_urgency[bot->getBotId()] = DecleiningSlopeCurve::calculate(bestScore + bestScore) * scale; + bot->addToFireInclination(m_urgency[bot->getBotId()]); + return m_urgency[bot->getBotId()]; + } + + m_targetChanged[bot->getBotId()] = !keepCurrent; + if (secondaryScore > 0.0f) + { + m_targets[bot->getBotId()] = secondaryTarget; + initializeGenerator(static_cast(bot), secondaryWeapon, false, false, secondarySpatial); + } + else if (deadScore > 0.0f) + { + m_targets[bot->getBotId()] = static_cast(-1); + initializeGenerator(static_cast(bot), -1, true, true, false); + } + else + { + m_pattern->unInit(bot); + m_urgency[bot->getBotId()] = 0.0f; + m_targets[bot->getBotId()] = static_cast(-1); + return 0.0f; + } + // Shipped quirk: the secondary/dead-score path omits the caller's modifier. + const float weighted = scale * (secondaryScore > 0.0f ? secondaryScore : deadScore); + secondaryScore = secondaryScore + deadScore; + m_urgency[bot->getBotId()] = DecleiningSlopeCurve::calculate(secondaryScore + secondaryScore) * weighted; + bot->addToFireInclination(m_urgency[bot->getBotId()]); + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && bot->getOrderList(m_index)->empty()) + m_urgency[bot->getBotId()] = m_urgency[bot->getBotId()] * bot->getMemory()->m_float8; + return m_urgency[bot->getBotId()]; +} + +// ELF 0x212CD0 +BBFireLargeBore::BBPFeedback* BBFireLargeBore::getBBPFeedback(unsigned int target) +{ + std::map::iterator it = m_feedback.find(target); + if (it != m_feedback.end()) + return it->second; + BBPFeedback* const feedback = checkPointer(new BBPFeedback); + feedback->m_time = -10000.0; + m_feedback.insert(std::make_pair(target, feedback)); + return feedback; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireLargeBore.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireLargeBore.h new file mode 100644 index 000000000..87edbf03a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireLargeBore.h @@ -0,0 +1,51 @@ +// Large-bore fire behaviour, including driver-controlled and stationary guns. +// Recovered from the symbolized Linux 1.50 libaidll.so; offsets refer to the ia-32 image. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIRELARGEBORE_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIRELARGEBORE_H + +#include "BotBehaviour.h" + +#include + +namespace dice { +namespace hfe { + +namespace ai { + +class BBPFire; +class Bot; +class BotMain; +class IPIMobile; +class Information; +class UrgeCurve; + +// ELF: vtable 0x4BAD40 (14 words), operator new 0x40, package G-vehicles. +class BBFireLargeBore : public BotBehaviour +{ +public: + struct BBPFeedback + { + double m_time; // ELF 0x212CD0: sole member, initialized to -10000.0 + }; + BBFireLargeBore(unsigned char, unsigned char, BBPFire*, UrgeCurve*, float*, bool); // 0x20F7E0 + virtual ~BBFireLargeBore(); // 0x20FC40 + + virtual float calculateUrgency(Bot*, bool, float); // 0x20FDC0, slot +0x28; from the base declaration + virtual void initializeGenerator(BotMain*, int, bool, bool, bool); // 0x212BE0, slot +0x34; [INFERRED] ELF void + + float calculateUrgency(Bot*, bool, float, Information*, IPIMobile*); // 0x20FE50; [INFERRED] ELF float, callers {'float': 1} + BBPFeedback* getBBPFeedback(unsigned int); // 0x212CD0 + + // Fields from the constructor 0x20F7E0 and destructor 0x20FC40 (operator new 0x40). + /* +0x24 */ unsigned int* m_unknown24; // per-bot weapon slot; initialized to -1 + /* +0x28 */ double m_double28; // last feedback cleanup time; initialized to 0.0 + /* +0x30 */ std::map m_feedback; // the destructor only frees the nodes [INFERRED] name + /* +0x3C */ bool m_flag3C; // use the first secondary object's armament +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIRELARGEBORE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireUnarmed.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireUnarmed.cpp new file mode 100644 index 000000000..3b585531c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireUnarmed.cpp @@ -0,0 +1,299 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +// static init: ELF 0x214A60 (__tcf_0 0x214AC0, _GLOBAL__I 0x214AF0): 's Init object only. +#include + +#include "BBFireUnarmed.h" + +#include "../Main/AIDllFrontier.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../AIUtils/checkPointer.h" +#include "../../../../Math/Vec3.h" +#include "../AIUtils/CustomCurve.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotMemory.h" +#include "../AIBot/SensedObject.h" +#include "../AIKnowledge/FireObject.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIStrategic/SAI.h" +#include "../AIStrategicEntity/AIStrategicArea.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" +#include "../AIUtils/VehicleOccupancy.h" +#include "../Main/AIMain.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" + +#include +#include +#include +#include +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x213230 (C2) / 0x213570 (C1); vtable GOT -0x1158. BotBehaviour(null modifiers, null +// curve, getMaxNBots); +0x24 = checkPointer(new float[n]), then the +0x08 targets = +// checkPointer(new unsigned int[n]) (operator new 0x28), no pattern (+0x0C = 0); every bot +// starts with urgency and +0x24 at 0.0f and target -1. +BBFireUnarmed::BBFireUnarmed(unsigned char index, unsigned char queue) + : BotBehaviour(0, 0, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_index = index; + m_queue = queue; + const int bots = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_value24 = checkPointer(new float[bots]); + m_targets = checkPointer(new unsigned int[bots]); + m_pattern = 0; + for (int i = 0; i < bots; ++i) + { + m_urgency[i] = 0.0f; + m_value24[i] = 0.0f; + m_targets[i] = static_cast(-1); + } +} + +// ELF 0x2138B0 (D2) / 0x213910 (D1) / 0x213970 (D0): delete[] +0x08, then +0x24 (each when set), +// then ~BotBehaviour. +BBFireUnarmed::~BBFireUnarmed() +{ + if (m_targets) + delete[] m_targets; + if (m_value24) + delete[] m_value24; +} + +// ELF 0x2139E0 (Ghidra; listing for the constants and the return). Always returns 0.0; the +// urgency goes to +0x24 and to the bot's fire inclination (+0x188). +// Without `evaluate`: a target that no longer resolves marks the change and clears +0x24; +// otherwise the stored +0x24 is fed to the fire inclination again. +// With it: every sided sensed object of another side with a physical part, alive, not of the +// three excluded type bits (0x20000 / 0x100000 / 0x800000) and within 250 (distance floored at +// 0.5) of the equipment's position is weighed when it has a unit and its vehicle is occupied +// for this side: over it and its secondary objects, (battle strength against the own strength +// type + the information's strength) * armour class of its strength type * the order factor +// (the memory's +0x08 while the object is in the bot's order list, counted at most once per order) +// * the area factor (0.75 outside the ordered area, again 0.75 when a mobile bot's target is +// outside it), then * time factor (1 / (age * 0.05 + 1) for indirect senses) / max(0.1, +// distance * 1.5 * 0.2), and * 0.33 when the summed strength is at most the harmless threshold. +// The best becomes the target, unless the current target scored and stays within 1.2 of it. +// A two-entry ignore list (the equipment's AI object, null) is built and never used, and the +// normalised direction is computed and dropped, as compiled. +float BBFireUnarmed::calculateUrgency(Bot* bot, bool evaluate, float modifier) +{ + if (!evaluate) + { + Information* const target = informationManager->getInformation(m_targets[bot->getBotId()]); + if (!target) + { + m_targetChanged[bot->getBotId()] = true; + m_value24[bot->getBotId()] = 0.0f; + return 0.0f; + } + m_targetChanged[bot->getBotId()] = false; + bot->addToFireInclination(m_value24[bot->getBotId()]); + return 0.0f; + } + + const float* const armourClass = + static_cast(CommonSingletonServer::m_iaiSettings)->getArmourClassValues(); // +0x94 + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* const ownMobile = equipment->getMobile(); + const int ownStrengthType = equipment->getPhysical()->getStrengthType(); + const Vec3 position = equipment->getPosition(); + float currentTargetScore = 0.0f; + unsigned int countedOrders = 0; + const int side = bot->getSide(); + const unsigned int currentTarget = m_targets[bot->getBotId()]; + bool currentTargetScored = false; + std::vector ignore; + ignore.push_back(equipment->getAIObject()); + ignore.push_back(0); + + const unsigned int botId = bot->getBotId(); + const int orderedArea = IAIMain::m_instance->getSAI(side)->getBotOrderedPos(botId); + AIStrategicArea* const area = + static_cast(AIStrategicObjectManager::getInstance()->getStrategicObject(orderedArea)); + float areaFactor; + if (!area) + areaFactor = 1.0f; + else + areaFactor = area->isInside(position) ? 1.0f : 0.75f; + + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + float bestScore = currentTargetScore; + const std::map& sensed = bot->getSensedObjects(); + for (std::map::const_iterator it = sensed.begin(); it != sensed.end(); ++it) + { + SensedObject* const object = it->second; + if (!(object->m_flags & SensedObject::SENSE_SIDED)) + continue; + Information* const info = informationManager->getInformation(object->m_handle); + if (!info || info->getSide() == side || !info->getPhysical()) + continue; + if (info->isOfType(ITLowPriority) || info->isOfType(ITVegetation) || info->isOfType(ITNoTemperature)) + continue; + if (!(info->getPhysical()->getHealth() > 0.0f)) + continue; + + Vec3 targetPosition; + targetPosition.x = 0.0f; + targetPosition.y = 0.0f; + targetPosition.z = 0.0f; + if (info->getMobile()) + info->getMobile()->getPositionEstimate(targetPosition); + else + targetPosition = info->getPosition(); + Vec3 direction; + direction.x = targetPosition.x - position.x; + direction.y = targetPosition.y - position.y; + direction.z = targetPosition.z - position.z; + float distance = std::sqrt(direction.z * direction.z + direction.x * direction.x + + direction.y * direction.y); + if (!(0.5f <= distance)) + distance = 0.5f; + if (distance > 250.0f) + continue; + + float timeFactor = 1.0f; + const float inverse = 1.0f / distance; + direction.x = direction.x * inverse; + direction.y = direction.y * inverse; + direction.z = inverse * direction.z; + (void)direction; + if (object->m_flags & SensedObject::SENSE_INDIRECT) + { + const float age = static_cast(now - object->m_firstSeenTime); + timeFactor = 1.0f / (age * 0.05f + 1.0f); + } + + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() + && bot->getOrderList(m_index)->size() > countedOrders) + { + if (bot->getOrderList(m_index)->end() + != std::find(bot->getOrderList(m_index)->begin(), bot->getOrderList(m_index)->end(), + object->m_handle)) + ++countedOrders; + } + + float targetAreaFactor = areaFactor; + if (ownMobile && area && !area->isInside(targetPosition)) + targetAreaFactor = areaFactor * 0.75f; + + if (!info->getUnit() || !vehicleOccupied(object->m_handle, side)) + continue; + + float strengthSum = 0.0f; + const unsigned int handle = object->m_handle; + int secondary = info->getFirstSecondaryObjectIterator(); + const int targetStrengthType = info->getPhysical()->getStrengthType(); + Information* part = info; + float score = strengthSum; + do + { + IPIUnit* const unit = part->getUnit(); + strengthSum = strengthSum + unit->getBattleStrengths()[ownStrengthType]; + bool ordered = false; + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() + && bot->getOrderList(m_index)->size() > countedOrders) + { + if (bot->getOrderList(m_index)->end() + != std::find(bot->getOrderList(m_index)->begin(), bot->getOrderList(m_index)->end(), + handle)) + ordered = true; + } + float orderFactor; + if (ordered) + { + ++countedOrders; + orderFactor = bot->getMemory()->m_float8; + } + else + { + orderFactor = 1.0f; + } + score = (unit->getBattleStrengths()[ownStrengthType] + part->getStrength()) + * armourClass[targetStrengthType] * orderFactor * targetAreaFactor + + score; + part = informationManager->getInformation(info->getSecondaryObject(secondary, side)); + } + while (part); + + float distanceFactor = distance * 1.5f * 0.2f; + if (distanceFactor <= 0.1f) + distanceFactor = 0.1f; + score = score * (timeFactor / distanceFactor); + if (strengthSum <= static_cast(static_cast(bot)->getHarmlessThrsh())) + score = score * 0.33f; + if (info->getUnit()) + { + if (currentTarget == object->m_handle) + { + currentTargetScore = score; + currentTargetScored = true; + } + if (bestScore < score) + { + bestScore = score; + m_targets[bot->getBotId()] = object->m_handle; + } + } + } + + if (bestScore <= 0.0f) + { + m_targetChanged[bot->getBotId()] = !currentTargetScored; + m_value24[bot->getBotId()] = 0.0f; + m_value24[bot->getBotId()] += getIncomingFireUrgency(static_cast(bot)); + bot->addToFireInclination(m_value24[bot->getBotId()]); + return 0.0f; + } + + if (!currentTargetScored || currentTargetScore * 1.2f <= bestScore) + { + bot->getBotId(); // called, result unused + currentTargetScored = false; + } + else + { + m_targets[bot->getBotId()] = currentTarget; + } + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && bot->getOrderList(m_index)->empty()) + bestScore = bestScore * bot->getMemory()->m_float8; + m_targetChanged[bot->getBotId()] = !currentTargetScored; + m_value24[bot->getBotId()] = DecleiningSlopeCurve::calculate(bestScore + bestScore) * (modifier * 1.0f); + m_value24[bot->getBotId()] += getIncomingFireUrgency(static_cast(bot)); + bot->addToFireInclination(m_value24[bot->getBotId()]); + return 0.0f; +} + +// ELF 0x214800 (Ghidra). Ten times the strongest incoming fire against the equipment's strength +// type, over a copy of the bot's incoming-fire list (the type asked for once per entry). +float BBFireUnarmed::getIncomingFireUrgency(BotMain* bot) +{ + float strongest = 0.0f; + const std::list > incoming = *bot->getIncommingFire(); // +0xA0 + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + IPIPhysical* const physical = equipment->getPhysical(); + for (std::list >::const_iterator it = incoming.begin(); + it != incoming.end(); ++it) + { + const float strength = it->first->getBattleStrength(physical->getStrengthType()); + strongest = (strength <= strongest) ? strongest : strength; + } + return strongest * 10.0f; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireUnarmed.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireUnarmed.h new file mode 100644 index 000000000..31826114a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireUnarmed.h @@ -0,0 +1,39 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIREUNARMED_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIREUNARMED_H + +#include "BotBehaviour.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotMain; + +// ELF: vtable 0x4BADE0 (13 words), operator new 0x28, package G-vehicles. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BBFireUnarmed : public BotBehaviour +{ +public: + BBFireUnarmed(unsigned char, unsigned char); // 0x213570 + virtual ~BBFireUnarmed(); // 0x213910 + + virtual float calculateUrgency(Bot*, bool, float); // 0x2139E0, slot +0x28; from the base declaration + + float getIncomingFireUrgency(BotMain*); // 0x214800; [INFERRED] ELF float, callers {'float': 2} + + /* +0x24 */ float* m_value24; // per bot, 0.0f; calculateUrgency stores a float there (fsts 0x213AD9) [UNRESOLVED] meaning +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIREUNARMED_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBIdle.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBIdle.cpp new file mode 100644 index 000000000..5c20c30e5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBIdle.cpp @@ -0,0 +1,336 @@ +// Idle behaviour (AI/AIDLL/AI/AIBotBehaviour/BBIdle.cpp in the image). Recovered from libaidll.so +// (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. Package D. +// Radio message and channel numbers are kept as the image's integers: the enumerator names of +// AIRadioMessageType/AIRadioChannelType are not recoverable from either binary ([UNRESOLVED]). + +// static init: ELF 0x215C30 (__tcf_0 0x215C90, _GLOBAL__I 0x215CC0): 's Init object only. +#include + +#include "BBIdle.h" + +#include "BBPendingCalls.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/CommunicationAgent.h" +#include "../AIBotBehaviourPattern/BBPIdle.h" +#include "../AIBotBehaviourPattern/BBPIdle2d.h" +#include "../AIBotBehaviourPattern/BBPIdle3d.h" +#include "../AIBotBehaviourPattern/BBPIdleInfantery.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../Main/AIDllFrontier.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IBotManager.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../../Math/Mat4.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +IAISettings* settings() +{ + return static_cast(CommonSingletonServer::m_iaiSettings); +} + +// Object-type tests use Information::isOfType (InformationType bits; AIDLL_r enum switch 0x100D3010): +// ITAir and ITHelicopter select the larger pickup radius; ITSoldier marks a soldier (a requester on +// foot, whose "vehicle" is the soldier itself); the bot's own equipment must not be one to give a lift. + +// The sender id that means "anyone" in a pickup request; a real one makes the request personal. +const int kAnySender = 0xFF; + +} // namespace + +// ELF 0x214C10 +BBIdle::BBIdle(unsigned char index, unsigned char queue, BBPIdle* pattern, UrgeCurve* curve, float* modifiers) + : BotBehaviour(modifiers, curve, settings()->getMaxNBots()) +{ + m_index = index; + m_queue = queue; + m_pattern = pattern; + + const int bots = settings()->getMaxNBots(); + m_waitStartTime = new double[bots]; + m_waitingForPickup = new bool[bots]; + m_healthAtWaitStart = new float[bots]; + for (int i = 0; i < bots; ++i) + { + m_urgency[i] = 1.0f; + m_targetChanged[i] = false; + m_waitStartTime[i] = 0.0; + m_waitingForPickup[i] = false; + m_healthAtWaitStart[i] = 0.0f; + } + m_targets = 0; +} + +// ELF 0x214D90 +BBIdle::~BBIdle() +{ + if (m_waitStartTime) + delete[] m_waitStartTime; + if (m_waitingForPickup) + delete[] m_waitingForPickup; + if (m_healthAtWaitStart) + delete[] m_healthAtWaitStart; +} + +// ELF 0x215BA0. Retail quirk: it resets every bot slot, not only the bot it is given, and it does +// not call BotBehaviour::reset. +void BBIdle::reset(Bot*) +{ + const int bots = settings()->getMaxNBots(); + for (int i = 0; i < bots; ++i) + { + m_urgency[i] = 1.0f; + m_targetChanged[i] = false; + m_waitStartTime[i] = 0.0; + m_waitingForPickup[i] = false; + m_healthAtWaitStart[i] = 0.0f; + } + m_targets = 0; +} + +// ELF 0x214E90 +float BBIdle::calculateUrgency(Bot* bot, bool, float modifier) +{ + BBPIdle* const pattern = static_cast(m_pattern); + const unsigned int equipment = bot->getCurrentEquipment(); + Information* const info = informationManager->getInformation(equipment); + info->getPrimaryObject(bot->getSide()); // 0x214F1D: called, result unused + IPIMobile* const mobile = info->getMobile(); + + bool active = false; + float urgency = modifier; + int pickupPlayerId = -1; + + if (info->isPrimary() && !info->isOfType(ITSoldier) && mobile) + { + bool moving = false; + if (bot->isAirBorn()) + moving = true; + else if (info->isOfType(ITAir) && mobile->getSpeedMagnitude() > 3.0f) + moving = true; + + IPIPhysical* const physical = info->getPhysical(); + bool damaged = false; + if (physical && physical->getHealth() < 0.9f) + damaged = true; + + bool waitForRepairs = false; + if (!moving && damaged) + { + BotMain* const main = static_cast(bot); + if (main->getIsRepaired() || main->getIsEngineerTarget()) + waitForRepairs = true; + } + static_cast(bot)->setShouldWaitForRepairs(waitForRepairs); + + if (!waitForRepairs) + { + // 0x215581: a repair that ended with a real gain is acknowledged once. + if (m_healthAtWaitStart[bot->getBotId()] > 0.0f && physical) + { + const float gained = physical->getHealth() - m_healthAtWaitStart[bot->getBotId()]; + if (gained > 0.25f) + { + bot->getCommunicationAgent()->enqueueRadioMessage(static_cast(8), + static_cast(6), 3, 1.0f, + -1); + m_healthAtWaitStart[bot->getBotId()] = 0.0f; + } + } + } + + const std::list& messages = + bot->getCommunicationAgent()->getReceivedMessages(static_cast(11)); + bool hadMessages = false; + if (waitForRepairs) + { + double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (m_waitingForPickup[bot->getBotId()] == true || m_waitStartTime[bot->getBotId()] == 0.0) + { + m_waitStartTime[bot->getBotId()] = now; + m_healthAtWaitStart[bot->getBotId()] = physical->getHealth(); + } + now = now - m_waitStartTime[bot->getBotId()]; + if (now > 3.0) + static_cast(bot)->setIsRepaired(false); + if (!messages.empty()) + hadMessages = true; + m_waitingForPickup[bot->getBotId()] = false; + urgency = modifier * 60.0f; + active = true; + } + else + { + waitForPickup(bot, equipment, info, pattern, moving, modifier, urgency, pickupPlayerId, active); + } + + // 0x21515F: answer the senders of message 11 that are in the bot's own vehicle. + if (!messages.empty() + && bbpending::generalConfirmReceivedMessage(bot->getCommunicationAgent(), + static_cast(11)) + && pickupPlayerId != kAnySender) + { + for (std::list::const_iterator it = messages.begin(); it != messages.end(); ++it) + { + IAIPlayer* const player = + static_cast(CommonSingletonServer::m_iaiPlayerFactory) + ->getPlayerFromId(it->m_senderPlayerId); + if (!player) + continue; + IAIObject* const vehicle = player->getCurrentVehicle(); + if (!vehicle) + continue; + Information* const vehicleInfo = informationManager->getInformation(vehicle->getHandle(bot->getSide())); + if (!vehicleInfo) + continue; + Information* const ownPrimary = + informationManager->getInformation(info->getPrimaryObject(bot->getSide())); + Information* const senderPrimary = + informationManager->getInformation(vehicleInfo->getPrimaryObject(bot->getSide())); + if (senderPrimary != ownPrimary) + continue; + if (!hadMessages) + { + bot->getCommunicationAgent()->enqueueRadioMessage(static_cast(6), + static_cast(7), 3, 1.0f, + -1); + active = false; + } + else + { + bot->getCommunicationAgent()->enqueueRadioMessage(static_cast(7), + static_cast(7), 3, 1.0f, + -1); + } + } + } + } + + // 0x215170 + if (!active) + { + static_cast(bot)->setIsRepaired(false); + static_cast(bot)->setShouldWaitForRepairs(false); + m_waitStartTime[bot->getBotId()] = 0.0; + m_waitingForPickup[bot->getBotId()] = false; + m_healthAtWaitStart[bot->getBotId()] = 0.0f; + urgency = modifier; + } + + m_urgency[bot->getBotId()] = urgency; + if (pattern->getType() == 1) + static_cast(pattern)->init(bot, pickupPlayerId); + else if (pattern->getType() == 2) + static_cast(pattern)->init(50.0f, bot, pickupPlayerId); + else if (pattern->getType() == 3) + static_cast(pattern)->init(bot); + return urgency; +} + +// ELF 0x2156C0. Walks the bot's received pickup offers (message 2) and accepts the first that +// fits: a carrier vehicle close enough to the bot's own (primary) object. +void BBIdle::waitForPickup(Bot* bot, unsigned int equipment, Information* equipmentInfo, BBPIdle* pattern, + bool moving, float modifier, float& urgency, int& pickupPlayerId, bool& active) +{ + const std::list& messages = + bot->getCommunicationAgent()->getReceivedMessages(static_cast(2)); + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + + for (std::list::const_iterator it = messages.begin(); it != messages.end(); ++it) + { + Bot* const sender = IBotManager::instance->getBotFromPlayerId(it->m_senderPlayerId); + Information* const primary = + informationManager->getInformation(equipmentInfo->getPrimaryObject(bot->getSide())); + const int primaryPlayerId = primary->getAIObject()->getPlayerId(); + CommunicationAgent* const senderAgent = sender ? sender->getCommunicationAgent() : 0; + const bool fromAnyone = it->m_senderPlayerId == kAnySender; + + if (pickupPlayerId >= 0 && !fromAnyone) + continue; + if (equipmentInfo->isOfType(ITSoldier)) + continue; + // 0x21584E: `cmpl 0x5C(agent), primaryPlayerId` (CommunicationAgent +0x5C). + if (senderAgent && bbpending::communicationAgentInt92(senderAgent) != primaryPlayerId) + continue; + + IAIPlayer* const player = + static_cast(CommonSingletonServer::m_iaiPlayerFactory)->getPlayerFromId(it->m_senderPlayerId); + if (!player) + continue; + IAIObject* const vehicle = player->getCurrentVehicle(); + if (!vehicle) + continue; + Information* const vehicleInfo = informationManager->getInformation(vehicle->getHandle(bot->getSide())); + if (!vehicleInfo) + continue; + if (!vehicleInfo->isOfType(ITSoldier)) + continue; + + float maxDistanceSqr; + if (equipmentInfo->isOfType(ITHelicopter) || equipmentInfo->isOfType(ITAir) || fromAnyone) + maxDistanceSqr = 2500.0f; + else + maxDistanceSqr = 625.0f; + + // Information slot +0x3C (getTransformation); the translation row is m[12..14]. + const Mat4& own = primary->getTransformation(); + const Mat4& carrier = vehicleInfo->getTransformation(); + Vec3 delta; + delta.x = own.m[12] - carrier.m[12]; + delta.y = own.m[13] - carrier.m[13]; + delta.z = own.m[14] - carrier.m[14]; + const float distanceSqr = delta.x * delta.x + delta.y * delta.y + delta.z * delta.z; + + bool decline; + if (fromAnyone) + decline = !pattern->freePosition(equipment, bot->getSide()) || distanceSqr > maxDistanceSqr || moving; + else + decline = distanceSqr > maxDistanceSqr || moving; + if (decline) + { + // 0x21598F + if (!bbpending::confirmReceivedMessage(bot->getCommunicationAgent(), *it)) + continue; + bot->getCommunicationAgent()->enqueueRadioMessage(static_cast(7), + static_cast(6), 3, 1.0f, -1); + return; + } + + // 0x215A00 + if (!m_waitingForPickup[bot->getBotId()] || m_waitStartTime[bot->getBotId()] == 0.0) + m_waitStartTime[bot->getBotId()] = now; + const double waited = now - m_waitStartTime[bot->getBotId()]; + if (!vehicleInfo->isOfType(ITSoldier) || primary != equipmentInfo) + continue; + if (!equipmentInfo->getMobile() || equipmentInfo->isOfType(ITSoldier) || moving) + continue; + if (!(waited < 10.0)) + continue; + if (pickupPlayerId >= 0 && !fromAnyone) + continue; + + urgency = modifier * it->m_modifier; + active = true; + pickupPlayerId = it->m_senderPlayerId; + m_waitingForPickup[bot->getBotId()] = true; + if (pickupPlayerId == kAnySender) + return; + } +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBIdle.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBIdle.h new file mode 100644 index 000000000..318e654e4 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBIdle.h @@ -0,0 +1,45 @@ +// Idle behaviour: the fallback every vehicle type gets (aibehaviours.ai `setVehicleDefaultBehaviour`). +// Its urgency is the modifier, raised while a bot waits for repairs or for a pickup it was offered. +// Recovered from libaidll.so (Linux 1.5.3153); every body carries its ELF address. Package D. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBIDLE_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBIDLE_H + +#include "BotBehaviour.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BBPIdle; +class Bot; +class Information; +class UrgeCurve; + +// ELF: vtable 0x4BAE80 (13 words), operator new 0x30, package D-behaviours. +class BBIdle : public BotBehaviour +{ +public: + BBIdle(unsigned char index, unsigned char queue, BBPIdle* pattern, UrgeCurve* curve, float* modifiers); // 0x214C10 + virtual ~BBIdle(); // 0x214D90 + + virtual void reset(Bot*); // 0x215BA0, slot +0x24 + virtual float calculateUrgency(Bot*, bool, float); // 0x214E90, slot +0x28 + + void waitForPickup(Bot* bot, unsigned int equipment, Information* equipmentInfo, BBPIdle* pattern, + bool moving, float modifier, float& urgency, int& pickupPlayerId, bool& active); // 0x2156C0 + +private: + // The three per-bot arrays (one entry per bot slot, IAISettings::getMaxNBots), from the constructor. + /* +0x24 */ double* m_waitStartTime; // 0.0 = not waiting; the game time the current wait began + /* +0x28 */ bool* m_waitingForPickup; // set when a pickup offer was accepted (waitForPickup) + /* +0x2C */ float* m_healthAtWaitStart; // vehicle health when a repair wait began; 0 = none +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBIDLE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMedicAssist.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMedicAssist.cpp new file mode 100644 index 000000000..92fd6c3c0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMedicAssist.cpp @@ -0,0 +1,739 @@ +// Medic/support assist behaviour (infantry "MedicAssist" slot of aibehaviours.ai). A medic +// (IAIPlayer::getSpawnKit 5) heals and an engineer (kit 4) repairs the friendly unit with the best +// strength / (curve(1 - health) * distance) score; a support soldier (kit 3) hands out ammunition +// (calculateGiveAmmoUrgency). The chosen target goes to the pattern through BBPMedicAssist::init. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see +// docs/macos-ai-behaviour-plan.md. +// +// Float constants (rodata): 0x49CB34 0.0f, 0x49CB2C 1.0f, 0x49F818 75.0f, 0x49CB54 0.75f, +// 0x49F81C 0.99f, 0x49F580 0.7071f, 0x49CB5C 100.0f, 0x49CCA8 50.0f, 0x49CC88 10.0f, +// 0x49CDC0 1.5f, 0x49CC90 3.0f, 0x49CC84 4.0f, 0x49F820 0.49f, 0x49F824 0.74f, 0x49CF6C 2500.0f, +// 0x49F828 0.9 (double, fldl). + +// static init: ELF 0x219240 (__tcf_0 0x2192A0, _GLOBAL__I 0x2192D0): 's Init object only. +#include + +#include "../AIBot/SquadManager.h" // requestResponseModifier (ai-bot) +#include "BBMedicAssist.h" + +#include "../AIUtils/CustomCurve.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotMemory.h" +#include "../AIBot/CommunicationAgent.h" +#include "../AIBot/SquadCoordinator.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotBehaviourPattern/BBPMedicAssist.h" +#include "../AIBotBehaviourPattern/PlanGenerator.h" +#include "../AIKnowledge/BFInformationEnvironment.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AIDllFrontier.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IBotManager.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +#include +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// Narrow stops for callees the tree does not declare yet (owner ai-bot). Each is a one-line swap +// to the real call once the owner declares it. + +// ELF 0x1C47F0 _ZNK4dice3hfe2ai18CommunicationAgent18getReceivedMessageERNS1_18AIRadioMessageInfoENS1_18AIRadioMessageTypeEi +// (PLT 0x185930). Swap to: return agent->getReceivedMessage(info, type, playerId); +bool communicationAgentGetReceivedMessage(const CommunicationAgent* agent, AIRadioMessageInfo& info, + AIRadioMessageType type, int playerId) +{ + return agent->getReceivedMessage(info, type, playerId); +} + +// ELF 0x1C4A00 _ZN4dice3hfe2ai18CommunicationAgent21receivedMessageExistsENS1_18AIRadioMessageTypeEi +// (PLT 0x17E1F0). Swap to: return agent->receivedMessageExists(type, playerId); +bool communicationAgentReceivedMessageExists(CommunicationAgent* agent, AIRadioMessageType type, + int playerId) +{ + return agent->receivedMessageExists(type, playerId); +} + +// ELF _ZN4dice3hfe2ai12SquadManager23requestResponseModifierEPNS1_11SquadMemberEjNS3_13RequestActionEi +// (PLT 0x17A880): float SquadManager::requestResponseModifier(SquadMember*, unsigned int target, +// SquadManager::RequestAction, int side), called on SquadManager::m_instance; the x87 result is +// multiplied into the urgency. Swap to: +// return SquadManager::m_instance->requestResponseModifier(member, target, +// static_cast(action), side); +float squadManagerRequestResponseModifier(SquadMember* member, unsigned int target, int action, int side) +{ + return SquadManager::m_instance->requestResponseModifier(member, target, action, side); +} + +const unsigned int kNoTarget = 0xFFFFFFFFu; + +inline IAIPlayer* playerFromId(int id) +{ + return static_cast(CommonSingletonServer::m_iaiPlayerFactory)->getPlayerFromId(id); +} + +// The inlined Vec3 subtraction followed by the x87 length (fsqrt, sqrtf on NaN). +inline float distance(const Vec3& a, const Vec3& b) +{ + const float dx = b.x - a.x; + const float dy = b.y - a.y; + const float dz = b.z - a.z; + return std::sqrt(dx * dx + dy * dy + dz * dz); +} + +inline float distanceSqr(const Vec3& a, const Vec3& b) +{ + const float dx = b.x - a.x; + const float dy = b.y - a.y; + const float dz = b.z - a.z; + return dx * dx + dy * dy + dz * dz; +} + +} // namespace + +// ELF 0x215CE0 (C2) / 0x216220 (C1). The base gets getMaxNBots (IAISettings slot 0); the +// vector at +0x24 is zeroed (three words); +0x30/+0x34/+0x38 are new[getNBattleStrengths] +// (slot +0x34, called once per array, each checkPointer'd); then index/queue/pattern; +0x08 is +// new[getMaxNBots] (not initialised) and every base urgency is 0.0f (rodata 0x49CB34). +BBMedicAssist::BBMedicAssist(unsigned char index, unsigned char queue, PlanGenerator* pattern, UrgeCurve* curve, + float* modifiers) + : BotBehaviour(modifiers, curve, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + IAISettings* settings = static_cast(CommonSingletonServer::m_iaiSettings); + m_bestWeaponIndex = checkPointer(new int[settings->getNBattleStrengths()]); + m_bestWeaponRange = checkPointer(new float[settings->getNBattleStrengths()]); + m_bestWeaponStrength = checkPointer(new int[settings->getNBattleStrengths()]); + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int count = settings->getMaxNBots(); + m_targets = checkPointer(new unsigned int[count]); // per-bot chosen target handle + for (int i = 0; i < count; ++i) + m_urgency[i] = 0.0f; +} + +// ELF 0x216760 (D2) / 0x216810 (D1) / 0x2168C0 (D0): delete[] +0x08, +0x30, +0x34, +0x38 when +// set, then the vector's storage, then the base. +BBMedicAssist::~BBMedicAssist() +{ + if (m_targets) + delete[] m_targets; + if (m_bestWeaponIndex) + delete[] m_bestWeaponIndex; + if (m_bestWeaponRange) + delete[] m_bestWeaponRange; + if (m_bestWeaponStrength) + delete[] m_bestWeaponStrength; +} + +// ELF 0x216980. Primary object of `info` for `side`, then its secondary objects: the first unit +// that is occupied by a player whom IAIPlayerFactory::getPlayerFromId (+0x20) knows and whose +// getIsAIPlayer (+0x88) is false answers true. +bool BBMedicAssist::isHumanInTarget(Information* info, int side) +{ + bool human = false; + if (info) + { + Information* primary = informationManager->getInformation(info->getPrimaryObject(side)); + if (primary) + { + IPIUnit* unit = primary->getUnit(); + if (unit && unit->isOccupied()) + { + IAIPlayer* player = playerFromId(unit->getOccupyingPlayerId(side)); + if (player && !player->getIsAIPlayer()) + return true; + } + int iterator; + for (Information* secondary = + informationManager->getInformation(primary->getFirstSecondaryObject(iterator, side)); + secondary; + secondary = informationManager->getInformation(primary->getSecondaryObject(iterator, side))) + { + unit = secondary->getUnit(); + if (unit && unit->isOccupied()) + { + IAIPlayer* player = playerFromId(unit->getOccupyingPlayerId(side)); + if (player && !player->getIsAIPlayer()) + { + human = true; + break; + } + } + } + } + } + return human; +} + +// ELF 0x216B40. +float BBMedicAssist::calculateUrgency(Bot* bot, bool recalculate, float urgencyScale) +{ + unsigned int* targets = m_targets; + PlanGenerator* pattern = m_pattern; + + if (!recalculate) + { + // Keep the current target while it is still on the bot's side (Information slot +0x44 + // getSide vs Bot +0xE0); a pattern that is no longer initiated (+0x0C) drops the urgency. + Information* target = informationManager->getInformation(targets[bot->getBotId()]); + if (target && target->getSide() == bot->getSide()) + { + m_targetChanged[bot->getBotId()] = false; + if (!pattern->isInitiated(bot)) + m_urgency[bot->getBotId()] = 0.0f; + } + else + { + m_targetChanged[bot->getBotId()] = m_urgency[bot->getBotId()] != 0.0f; + m_urgency[bot->getBotId()] = 0.0f; + pattern->unInit(bot); + } + return m_urgency[bot->getBotId()]; + } + + // ELF 0x216CE9: cmpl $0x3 on IAIPlayer::getSpawnKit (+0x44) - support soldiers hand out ammo. + if (bot->getPlayer()->getSpawnKit() == 3) + return calculateGiveAmmoUrgency(bot, urgencyScale); + + const int nStrengths = static_cast(CommonSingletonServer::m_iaiSettings)->getNBattleStrengths(); + int bestPlayerId = -1; // -0x198 + int bestWeaponIndex = -1; // -0x194 + Vec3 normal = {0.0f, 0.0f, 0.0f}; + const int kit = bot->getPlayer()->getSpawnKit(); + Information* self = informationManager->getInformation(bot->getCurrentEquipment()); + const Vec3& selfPosition = self->getPosition(); // retail: no null check + + for (int i = 0; i < nStrengths; ++i) + { + m_bestWeaponIndex[i] = -1; + m_bestWeaponStrength[i] = 0; + } + + IPIArmament* armament = self->getArmament(); + IPIMobile* selfMobile = self->getMobile(); + int vehicleNumber = -2; + if (selfMobile) + { + vehicleNumber = selfMobile->getVehicleNumber(); + self->getUnit()->getEquipmentType(); // ELF 0x216E1A: result unused + } + + // The bot's own healing/repair weapons (WeaponInfo::getWeaponType 1): per strength type the + // strongest one, its index and its max range. + std::vector weapons = armament->getWeapons(); + for (unsigned int w = 0; w < weapons.size(); ++w) + { + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(weapons[w]); + if (!weapon || weapon->getWeaponType() != 1) + continue; + for (int i = 0; i < nStrengths; ++i) + { + if (weapon->getStrength(i) > m_bestWeaponStrength[i]) + { + m_bestWeaponIndex[i] = static_cast(w); + m_bestWeaponStrength[i] = weapon->getStrength(i); + m_bestWeaponRange[i] = weapon->getMaxRange(); + } + } + } + + float bestScore = 0.0f; + // ELF -0x188: the same stack slot is the new size of the resize below and the counter of + // ordered targets met in the loop. [INFERRED] one source variable. + unsigned int orderedCount = 0; + // ELF 0x216FA5..0x216FC9 / 0x217E18: size > 0 -> erase(begin, end), else + // _M_fill_insert(end, 0, 0): the inlined vector::resize(0). + m_friendlies.resize(orderedCount); + // IAIInformationEnvironment slot +0x0C: getFriendlyAndNeutralUnits(out, position, bot, 75.0f). + static_cast(AISingletonServer::m_iaiInformationEnvironment) + ->getFriendlyAndNeutralUnits(m_friendlies, selfPosition, bot, 75.0f); + + unsigned int bestTarget = kNoTarget; // -0x1BC + CommunicationAgent* agent = bot->getCommunicationAgent(); + const std::list& medicCalls = agent->getReceivedMessages(static_cast(3)); + const std::list& repairCalls = agent->getReceivedMessages(static_cast(4)); + bool canAnswerMedicCall = !medicCalls.empty(); + bool canAnswerRepairCall = !repairCalls.empty(); + if (bot->isAirBorn()) + { + canAnswerMedicCall = false; + canAnswerRepairCall = false; + } + // ELF 0x21708D: a 1.0f local that multiplies every score (fmuls -0x1A0). + const float scoreModifier = 1.0f; + + // Squad queries whose results are not used (ELF 0x2170C5..0x21710C). + Vec3 squadPosition = {0.0f, 0.0f, 0.0f}; + SquadCoordinator* squad = bot->getSquadMember()->getSquad(); + squad->getSquadPosition(squadPosition); + Vec3 squadGotoPosition = squad->getSquadGotoPos(); + (void)squadGotoPosition; + squad->getSquadLeader(); + + float bestDistance = 100.0f; + bool bestIsHuman = false; // -0x1DA + bool bestHasNoBot = false; // -0x1DB: set by any 3x candidate, not only the best (retail) + + for (std::vector::iterator it = m_friendlies.begin(); it != m_friendlies.end(); ++it) + { + float healthThreshold = 0.75f; + bool isHuman = false; + Information* info = informationManager->getInformation(*it); + if (!info || !info->getPhysical()) + continue; + // A firing medic does not treat itself. + if (info == self && bot->getPlayer()->getSpawnKit() == 5 && bot->isFiring()) + continue; + // Object-type flag 0x80 (testb $-0x80, +0x04): only when a human is in it. + if (info->isOfType(ITNaval) && !isHumanInTarget(info, bot->getSide())) + continue; + if (info == self && bot->getPlayer()->getSpawnKit() == 5 && armament->getActiveWeapon() != -1) + { + // A medic holding its healing weapon (type 1) skips itself. + WeaponInfo* active = + WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + if (active && active->getWeaponType() == 1) + continue; + } + + IPIPhysical* physical = info->getPhysical(); + const int strengthType = physical->getStrengthType(); + if (physical->getManDown()) + continue; + if (isHumanInTarget(info, bot->getSide())) + { + healthThreshold = 0.99f; + isHuman = true; + } + if (m_bestWeaponIndex[strengthType] == -1) + continue; + + const float health = physical->getHealth(); + int occupant = -1; + if (info->getUnit()) + occupant = info->getUnit()->getOccupyingPlayerId(info->getSide()); + + AIRadioMessageInfo medicCall; + bool medicCalled = false; + if (canAnswerMedicCall) + medicCalled = communicationAgentGetReceivedMessage(agent, medicCall, static_cast(3), + occupant); + // Retail: repairCall is never filled, so its sender stays -1 (the constructor's value). + AIRadioMessageInfo repairCall; + bool repairCalled = false; + if (canAnswerRepairCall) + repairCalled = vehicleRequestsEngineer(info, info->getSide(), agent); + if (!repairCalled && bot->getPlayer()->getSpawnKit() == 4 && + bot->getSquadMember()->isCloseToNonOwnedTarget()) + continue; + + // ucomiss: needs treatment (0 < health < threshold) or a call for it. + if (!(healthThreshold > health && health > 0.0f) && !medicCalled && !repairCalled) + continue; + if (health > healthThreshold) + continue; + + // Only units standing on ground flatter than 45 degrees (terrain normal . object up row). + const Vec3& position = info->getPosition(); + static_cast(CommonSingletonServer::m_iaiTerrain)->getNormal(position.x, position.z, normal); + const Mat4& transformation = info->getTransformation(); + if (normal.x * transformation.m[4] + normal.y * transformation.m[5] + normal.z * transformation.m[6] < + 0.7071f) + continue; + + IPIUnit* unit = info->getUnit(); + if (unit->getAlwaysTargetSoldier()) + continue; + if (distance(selfPosition, position) > m_bestWeaponRange[strengthType]) + { + if (!selfMobile) + continue; + if (!unit->useNoPathfindingToGetToObject() && info->getMobile()) + { + // Retail: skips the target when the bot's last valid position is within range. + const Vec3& lastValid = selfMobile->getLastValidPosition(vehicleNumber).position; + const float range = m_bestWeaponRange[strengthType]; + if (distanceSqr(lastValid, position) < range * range) + continue; + } + } + const float targetDistance = info == self ? 1.0f : distance(selfPosition, position); + + float strength; + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && + orderedCount < bot->getOrderList(m_index)->size() && + std::find(bot->getOrderList(m_index)->begin(), bot->getOrderList(m_index)->end(), *it) != + bot->getOrderList(m_index)->end()) + { + ++orderedCount; + strength = info->getStrength() * bot->getMemory()->m_float8; + } + else + { + strength = info->getStrength(); + } + + // fdivp (AT&T: st(1) = st(0) / st(1)): strength / (curve(1 - health) * distance). + float score = strength / (DecleiningSlopeCurve::calculate(1.0f - health) * targetDistance); + if ((medicCalled && medicCall.m_senderPlayerId == occupant && kit == 5) || + (repairCalled && repairCall.m_senderPlayerId == occupant && kit == 4)) + { + // IBotManager slot +0x1C: a caller without a bot (a human) triples the score. + if (IBotManager::instance->getBotFromPlayerId(occupant)) + { + score = score * 1.5f; + } + else + { + score = score * 3.0f; + bestHasNoBot = true; + } + } + if (score * scoreModifier > bestScore) + { + bestIsHuman = isHuman; + bestDistance = targetDistance; + bestWeaponIndex = m_bestWeaponIndex[strengthType]; + bestScore = score * scoreModifier; + bestTarget = *it; + bestPlayerId = occupant; + } + } + + const unsigned int id = bot->getBotId(); + if (bestTarget == kNoTarget) + { + m_urgency[id] = 0.0f; + m_targetChanged[id] = targets[id] != kNoTarget; + targets[id] = kNoTarget; + pattern->unInit(bot); + return 0.0f; + } + + // An ordered behaviour with an empty order list scales the score by BotMemory +0x08. + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && bot->getOrderList(m_index)->empty()) + bestScore = bestScore * bot->getMemory()->m_float8; + + if (bestIsHuman && bestHasNoBot && bestDistance < 50.0f) + { + m_urgency[id] = 100.0f; + } + else if (bestIsHuman) + { + m_urgency[id] = DecleiningSlopeCurve::calculate(bestScore) * 10.0f * urgencyScale; + } + else + { + // fadd %st(0), %st: curve + curve. + const float curve = DecleiningSlopeCurve::calculate(bestScore); + m_urgency[id] = (curve + curve) * urgencyScale; + } + + m_targetChanged[id] = targets[id] != bestTarget; + targets[id] = bestTarget; + static_cast(m_pattern)->init(targets[id], bestWeaponIndex, bestPlayerId, bot); + + if (kit == 5) + { + // RequestAction 1 (ELF 0x217452 movl $0x1). + m_urgency[id] = squadManagerRequestResponseModifier(bot->getSquadMember(), bestTarget, 1, bot->getSide()) * + m_urgency[id]; + } + else if (kit == 4) + { + // RequestAction 2 (ELF 0x2173A2 movl $0x2); Bot +0x1C8 setWantedRepairTarget. + m_urgency[id] = squadManagerRequestResponseModifier(bot->getSquadMember(), bestTarget, 2, bot->getSide()) * + m_urgency[id]; + bot->setWantedRepairTarget(m_urgency[id] == 0.0f ? kNoTarget : bestTarget); + } + return m_urgency[bot->getBotId()]; +} + +// ELF 0x217E70. A bot that is man down never applies; otherwise the information's armament must +// hold a weapon of type 1 (heal/repair) or 2 (ammo): `decl; cmpl $0x1; jbe`. +bool BBMedicAssist::isAplicable(Information* info, Bot* bot) +{ + IPIArmament* armament = info->getArmament(); + if (bot->getManDown() || !armament) + return false; + std::vector& weapons = armament->getWeapons(); + for (unsigned int i = 0; i < weapons.size(); ++i) + { + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (weapon && static_cast(weapon->getWeaponType() - 1) <= 1) + return true; + } + return false; +} + +// ELF 0x217F10. A repair request (message type 4) from the information's player, or from the +// player of any of its secondary objects for `side`. +bool BBMedicAssist::vehicleRequestsEngineer(Information* info, int side, CommunicationAgent* agent) const +{ + if (info && communicationAgentReceivedMessageExists(agent, static_cast(4), info->getPlayerId())) + return true; + // Retail: also reached with a null info (getFirstSecondaryObject is called on it). + int iterator; + for (Information* secondary = informationManager->getInformation(info->getFirstSecondaryObject(iterator, side)); + secondary; secondary = informationManager->getInformation(info->getSecondaryObject(iterator, side))) + { + if (communicationAgentReceivedMessageExists(agent, static_cast(4), + secondary->getPlayerId())) + return true; + } + return false; +} + +// ELF 0x218020. The support soldier's version of calculateUrgency: weapon type 2 (ammo), friendly +// units low on ammunition, message type 10, SCurve of the ammo ratio, RequestAction 4. +float BBMedicAssist::calculateGiveAmmoUrgency(Bot* bot, float urgencyScale) +{ + unsigned int* targets = m_targets; + PlanGenerator* pattern = m_pattern; + + const int nStrengths = static_cast(CommonSingletonServer::m_iaiSettings)->getNBattleStrengths(); + IAITerrain* terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + int bestPlayerId = -1; // -0x190 + int bestWeaponIndex = -1; // -0x18C + Vec3 normal = {0.0f, 0.0f, 0.0f}; + Information* self = informationManager->getInformation(bot->getCurrentEquipment()); + const Vec3& selfPosition = self->getPosition(); // retail: no null check + + for (int i = 0; i < nStrengths; ++i) + { + m_bestWeaponIndex[i] = -1; + m_bestWeaponStrength[i] = 0; + } + + IPIArmament* armament = self->getArmament(); + IPIMobile* selfMobile = self->getMobile(); + int vehicleNumber = -2; + if (selfMobile) + { + vehicleNumber = selfMobile->getVehicleNumber(); + self->getUnit()->getEquipmentType(); // ELF 0x21815A: result unused + } + + // The bot's own ammo weapons (type 2). + std::vector weapons = armament->getWeapons(); + for (unsigned int w = 0; w < weapons.size(); ++w) + { + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(weapons[w]); + if (!weapon || weapon->getWeaponType() != 2) + continue; + for (int i = 0; i < nStrengths; ++i) + { + if (weapon->getStrength(i) > m_bestWeaponStrength[i]) + { + m_bestWeaponIndex[i] = static_cast(w); + m_bestWeaponStrength[i] = weapon->getStrength(i); + m_bestWeaponRange[i] = weapon->getMaxRange(); + } + } + } + + float bestScore = 0.0f; + unsigned int orderedCount = 0; // same slot as the resize size, see calculateUrgency + m_friendlies.resize(orderedCount); + // IAIInformationEnvironment slot +0x08: getFriendlyUnits(out, position, bot, 75.0f). + static_cast(AISingletonServer::m_iaiInformationEnvironment) + ->getFriendlyUnits(m_friendlies, selfPosition, bot, 75.0f); + + const float scoreModifier = 1.0f; // ELF 0x218340 (-0x198) + unsigned int bestTarget = kNoTarget; // -0x1B4 + CommunicationAgent* agent = bot->getCommunicationAgent(); + bool canAnswerAmmoCall = !agent->getReceivedMessages(static_cast(10)).empty(); + if (canAnswerAmmoCall && bot->isAirBorn()) + canAnswerAmmoCall = false; + + std::vector targetWeapons; + Vec3 squadPosition = {0.0f, 0.0f, 0.0f}; + SquadMember* member = bot->getSquadMember(); + member->getSquad()->getSquadPosition(squadPosition); + Vec3 squadGotoPosition = member->getSquad()->getSquadGotoPos(); + (void)squadGotoPosition; + Vec3 memberPosition = {0.0f, 0.0f, 0.0f}; + + for (std::vector::iterator it = m_friendlies.begin(); it != m_friendlies.end(); ++it) + { + float ammoThreshold = 0.49f; + Information* info = informationManager->getInformation(*it); + if (!info || !info->getPhysical()) + continue; + + IPIUnit* occupiedUnit = info->getUnit(); + if (occupiedUnit && occupiedUnit->isOccupied()) + { + // An occupied unit: skipped when an AI player is in it. + IAIPlayer* player = playerFromId(occupiedUnit->getOccupyingPlayerId(info->getSide())); + if (player && player->getIsAIPlayer()) + continue; + } + else if (member->getPosition(memberPosition) && + distanceSqr(memberPosition, info->getPosition()) > 2500.0f) + { + // An empty unit more than 50 m from the bot's own squad-member position. + continue; + } + + if (info == self && bot->getPlayer()->getSpawnKit() == 3 && armament->getActiveWeapon() != -1) + { + // A support soldier holding its ammo weapon (type 2) skips itself. + WeaponInfo* active = + WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + if (active && active->getWeaponType() == 2) + continue; + } + + IPIPhysical* physical = info->getPhysical(); + if (physical->getManDown()) + continue; + const int strengthType = physical->getStrengthType(); + if (m_bestWeaponIndex[strengthType] == -1) + continue; + + // The ammo ratio over the target's weapons except heal/repair (1) and ammo (2) ones, with + // getAmmo (+0x10) != -1 and getMaxAmmo != 0. Needs ammo when a weapon has more magazines + // (+0x18 getNumberOfMags) than int(getCurrentAmmo (+0x14) / getMaxAmmoInMag) + 1. + targetWeapons = info->getArmament()->getWeapons(); + float ammoRatio = 1.0f; + bool needsAmmo = false; + // Retail: the bound is the bot's own weapon count (-0x168/-0x164), the index goes into + // the target's copy (-0x158). + for (unsigned int w = 0; w < weapons.size(); ++w) + { + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(targetWeapons[w]); + if (!weapon || weapon->getWeaponType() == 1 || weapon->getWeaponType() == 2 || weapon->getAmmo() == -1 || + weapon->getMaxAmmo() == 0) + continue; + const float currentAmmo = static_cast(weapon->getCurrentAmmo()); + ammoRatio = currentAmmo / static_cast(weapon->getMaxAmmo()) * ammoRatio; + const int mags = weapon->getNumberOfMags(); + const float fullMags = currentAmmo / static_cast(weapon->getMaxAmmoInMag()); // fstps, cvttss2si + if (static_cast(fullMags) + 1 < mags) + needsAmmo = true; + } + if (!needsAmmo) + continue; + + int occupant = -1; + if (info->getUnit()) + occupant = info->getUnit()->getOccupyingPlayerId(info->getSide()); + AIRadioMessageInfo ammoCall; + bool ammoCalled = false; + if (canAnswerAmmoCall) + ammoCalled = communicationAgentGetReceivedMessage(agent, ammoCall, static_cast(10), + occupant); + if (isHumanInTarget(info, bot->getSide())) + ammoThreshold = 0.74f; // cmovnel of the bit pattern + + if (!(ammoThreshold > ammoRatio && ammoRatio > 0.0f)) + { + if (!ammoCalled) + continue; + if (!(ammoRatio < 0.9)) // fldl 0x49F828: double compare + continue; + } + + const Vec3& position = info->getPosition(); + terrain->getNormal(position.x, position.z, normal); + const Mat4& transformation = info->getTransformation(); + if (normal.x * transformation.m[4] + normal.y * transformation.m[5] + normal.z * transformation.m[6] < + 0.7071f) + continue; + + IPIUnit* unit = info->getUnit(); + if (unit->getAlwaysTargetSoldier()) + continue; + if (distance(selfPosition, position) > m_bestWeaponRange[strengthType]) + { + if (!selfMobile) + continue; + if (!unit->useNoPathfindingToGetToObject() && info->getMobile()) + { + const Vec3& lastValid = selfMobile->getLastValidPosition(vehicleNumber).position; + const float range = m_bestWeaponRange[strengthType]; + if (distanceSqr(lastValid, position) < range * range) + continue; + } + } + const float targetDistance = info == self ? 1.0f : distance(selfPosition, position); + + float strength; + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && + orderedCount < bot->getOrderList(m_index)->size() && + std::find(bot->getOrderList(m_index)->begin(), bot->getOrderList(m_index)->end(), *it) != + bot->getOrderList(m_index)->end()) + { + ++orderedCount; + strength = info->getStrength() * bot->getMemory()->m_float8; + } + else + { + strength = info->getStrength(); + } + + float score = strength / (SCurve::calculate(ammoRatio) * targetDistance); + if (ammoCalled) + { + // Looked up by the message's sender (-0x114), not the occupant. + if (IBotManager::instance->getBotFromPlayerId(ammoCall.m_senderPlayerId)) + score = score * 1.5f; + else + score = score * 3.0f; + } + if (score * scoreModifier > bestScore) + { + bestWeaponIndex = m_bestWeaponIndex[strengthType]; + bestScore = score * scoreModifier; + bestTarget = *it; + bestPlayerId = occupant; + } + } + + if (bestTarget == kNoTarget) + { + m_urgency[bot->getBotId()] = 0.0f; + m_targetChanged[bot->getBotId()] = targets[bot->getBotId()] != kNoTarget; + targets[bot->getBotId()] = kNoTarget; + pattern->unInit(bot); + return 0.0f; + } + + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && bot->getOrderList(m_index)->empty()) + bestScore = bestScore * bot->getMemory()->m_float8; + + m_urgency[bot->getBotId()] = DecleiningSlopeCurve::calculate(bestScore) * 4.0f * urgencyScale; + m_targetChanged[bot->getBotId()] = targets[bot->getBotId()] != bestTarget; + targets[bot->getBotId()] = bestTarget; + static_cast(m_pattern)->init(targets[bot->getBotId()], bestWeaponIndex, bestPlayerId, bot); + // RequestAction 4 (ELF 0x218680 movl $0x4). + const unsigned int id = bot->getBotId(); + m_urgency[id] = squadManagerRequestResponseModifier(bot->getSquadMember(), bestTarget, 4, bot->getSide()) * + m_urgency[id]; + return m_urgency[bot->getBotId()]; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMedicAssist.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMedicAssist.h new file mode 100644 index 000000000..7e5bd9a2c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMedicAssist.h @@ -0,0 +1,58 @@ +// Medic/support assist behaviour (infantry): a medic (kit 5) or engineer (kit 4) picks the most +// urgent friendly unit near it to heal or repair; a support soldier (kit 3) instead looks for a +// friendly unit that needs ammunition (calculateGiveAmmoUrgency). Recovered from libaidll.so +// (Linux 1.5.3153, ia-32); F-urgency package, see docs/macos-ai-behaviour-plan.md. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBMEDICASSIST_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBMEDICASSIST_H + +#include "BotBehaviour.h" + +#include + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class CommunicationAgent; +class Information; +class PlanGenerator; +class UrgeCurve; + +// ELF: vtable 0x4BAF20 (13 words), operator new 0x3C, package F-infantry. +class BBMedicAssist : public BotBehaviour +{ +public: + BBMedicAssist(unsigned char, unsigned char, PlanGenerator*, UrgeCurve*, float*); // 0x216220 + virtual ~BBMedicAssist(); // 0x216810 + + virtual float calculateUrgency(Bot*, bool, float); // 0x216B40, slot +0x28; from the base declaration + virtual bool isAplicable(Information*, Bot*); // 0x217E70, slot +0x30; bool: 0/1 in %edx + + // ELF bool (movzbl of a 0/1 local); true when a human (non-AI) player occupies the + // information's primary object or one of its secondary objects for that side. + bool isHumanInTarget(Information*, int); // 0x216980 + // ELF returns 0/1 in %eax (movl $0x1, %edx); every caller tests the low byte, so bool. + bool vehicleRequestsEngineer(Information*, int, CommunicationAgent*) const; // 0x217F10 + // ELF float: both returns leave the urgency on the x87 stack (flds). + float calculateGiveAmmoUrgency(Bot*, float); // 0x218020 + +private: + // The friendly units of the last calculation, filled by IAIInformationEnvironment + // getFriendlyAndNeutralUnits / getFriendlyUnits (75 m around the bot). + /* +0x24 */ std::vector m_friendlies; + // Three per-battle-strength-type arrays (new[IAISettings::getNBattleStrengths]); for each + // strength type the bot's own healing/repair (weapon type 1) or ammo (type 2) weapon with the + // highest strength against it: its index in IPIArmament::getWeapons, its max range, its strength. + /* +0x30 */ int* m_bestWeaponIndex; // -1 = none + /* +0x34 */ float* m_bestWeaponRange; // WeaponInfo::getMaxRange + /* +0x38 */ int* m_bestWeaponStrength; // WeaponInfo::getStrength(type) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBMEDICASSIST_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveTo.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveTo.cpp new file mode 100644 index 000000000..cf6b0726b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveTo.cpp @@ -0,0 +1,126 @@ +// MoveTo behaviour (AI/AIDLL/AI/AIBotBehaviour/BBMoveTo.cpp in the image). Recovered from +// libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. Package D. + +// static init: ELF 0x219960 (__tcf_0 0x2199C0, _GLOBAL__I 0x2199F0): 's Init object only. +#include + +#include "BBMoveTo.h" + +#include "BBPendingCalls.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotMemory.h" +#include "../AIBot/SquadCoordinator.h" +#include "../AIBot/SquadFormation.h" +#include "../AIBot/SquadManager.h" +#include "../AIBot/SquadMember.h" +#include "../AIBot/WaypointList.h" +#include "../AIBotBehaviourPattern/BBPGotoWaypoint.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../Main/AIDllFrontier.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +IAISettings* settings() +{ + return static_cast(CommonSingletonServer::m_iaiSettings); +} + +} // namespace + +// ELF 0x2193A0 +BBMoveTo::BBMoveTo(unsigned char index, unsigned char queue, BBPGotoWaypoint* pattern, UrgeCurve* curve, + float* modifiers) + : BotBehaviour(modifiers, curve, settings()->getMaxNBots()) +{ + m_index = index; + m_queue = queue; + m_targets = 0; + m_pattern = pattern; + + const int bots = settings()->getMaxNBots(); + for (int i = 0; i < bots; ++i) + m_urgency[i] = 0.0f; +} + +// ELF 0x219490 +BBMoveTo::~BBMoveTo() +{ +} + +// ELF 0x219510 +float BBMoveTo::calculateUrgency(Bot* bot, bool recalculate, float modifier) +{ + BBPGotoWaypoint* const pattern = static_cast(m_pattern); + + // A squad member that holds its formation slot does not move until the squad moves out. + SquadMember* const member = bot->getSquadMember(); + if (bbpending::isAtFormationSlot(member) + && !member->getSquad()->getSquadFormation()->shouldSquadMoveOut()) + { + return m_urgency[bot->getBotId()] = 0.0f; + } + + if (!recalculate) + { + m_targetChanged[bot->getBotId()] = false; + if (!pattern->isInitiated(bot)) + m_urgency[bot->getBotId()] = 0.0f; + bot->addToMoveInclination(m_urgency[bot->getBotId()]); + return m_urgency[bot->getBotId()]; + } + + float factor = 1.0f; + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders()) + { + const float weight = bot->getMemory()->m_float8; + m_urgency[bot->getBotId()] = weight * bot->getWaypoints()->getUrgency(equipment->getPosition(), bot); + } + else + { + m_urgency[bot->getBotId()] = bot->getWaypoints()->getUrgency(equipment->getPosition(), bot); + } + + const int side = bot->getSide(); + Vec3 position = equipment->getPosition(); + double sinceStart; + int artillerySide; + if (SquadManager::m_instance->isInArtilleryDangerZone(position, side, sinceStart, artillerySide)) + { + SquadMember* const avoiding = bot->getSquadMember(); + if (avoiding && avoiding->isAvoidingArtillery()) + m_urgency[bot->getBotId()] = 1000.0f; + } + + factor = factor * modifier; + m_urgency[bot->getBotId()] = factor * m_urgency[bot->getBotId()]; + if (m_urgency[bot->getBotId()] <= 0.0f) + { + m_targetChanged[bot->getBotId()] = pattern->isInitiated(bot); + pattern->unInit(bot); + m_urgency[bot->getBotId()] = 0.0f; + return 0.0f; + } + + m_targetChanged[bot->getBotId()] = bot->getWaypoints()->m_flag4; + pattern->init(bot); + bot->addToMoveInclination(m_urgency[bot->getBotId()]); + + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; + if (bot->getWaypoints()->getGoalPoint(position)) + bot->insertBehaviourInformation(0.5f, position, m_index); + return m_urgency[bot->getBotId()]; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveTo.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveTo.h new file mode 100644 index 000000000..679881d3f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveTo.h @@ -0,0 +1,33 @@ +// MoveTo behaviour: follow the bot's waypoint list; the urgency comes from the waypoints. +// Recovered from libaidll.so (Linux 1.5.3153); every body carries its ELF address. Package D. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBMOVETO_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBMOVETO_H + +#include "BotBehaviour.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BBPGotoWaypoint; +class Bot; +class UrgeCurve; + +// ELF: vtable 0x4BAF80 (13 words), operator new 0x24, package D-behaviours. No members of its own. +class BBMoveTo : public BotBehaviour +{ +public: + BBMoveTo(unsigned char index, unsigned char queue, BBPGotoWaypoint* pattern, UrgeCurve* curve, float* modifiers); // 0x2193A0 + virtual ~BBMoveTo(); // 0x219490 + + virtual float calculateUrgency(Bot*, bool, float); // 0x219510, slot +0x28 +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBMOVETO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveToFixed.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveToFixed.cpp new file mode 100644 index 000000000..3bbfb682d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveToFixed.cpp @@ -0,0 +1,99 @@ +// Fixed move-to behaviour (AI/AIDLL/AI/AIBotBehaviour/BBMoveToFixed.cpp in the image). Recovered +// from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. + +// static init: ELF 0x21A1A0 (__tcf_0 0x21A200, _GLOBAL__I 0x21A230): 's Init object only. +#include + +#include "BBMoveToFixed.h" + +#include "../Main/AIDllFrontier.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../AIUtils/checkPointer.h" +#include "../../../../Math/Vec3.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotMemory.h" +#include "../AIBot/WaypointList.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../Main/AIMain.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x219A10 (C2) / 0x219C20 (C1); vtable GOT -0x1190. BotBehaviour(null modifiers, null curve, +// getMaxNBots); no targets and no pattern (+0x08 = +0x0C = 0); +0x24 = checkPointer(new +// float[getMaxNBots()]) (operator new 0x28); every bot starts with urgency and +0x24 at 0.0f. +BBMoveToFixed::BBMoveToFixed(unsigned char index, unsigned char queue) + : BotBehaviour(0, 0, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_index = index; + m_targets = 0; + m_pattern = 0; + m_queue = queue; + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_value24 = checkPointer(new float[count]); + for (int i = 0; i < count; ++i) + { + m_urgency[i] = 0.0f; + m_value24[i] = 0.0f; + } +} + +// ELF 0x219E30 (D2) / 0x219E80 (D1) / 0x219ED0 (D0): delete[] +0x24 when set, then ~BotBehaviour. +BBMoveToFixed::~BBMoveToFixed() +{ + if (m_value24) + delete[] m_value24; +} + +// ELF 0x219F20 (Ghidra; listing cross-check). Always returns 0.0; the urgency goes to +0x24 and to +// the bot's move inclination. With `recalculate` it is the waypoint list's urgency at the +// equipment's position (times the memory's +0x08 for an ordered behaviour); while positive, the +// target-changed flag follows the list's +0x04 flag and the list's goal point is reported to the +// sensing agent with weight 0.5. The SAI of the bot's side is fetched and not used, and a zero +// Vec3 is built and never read, as compiled. +float BBMoveToFixed::calculateUrgency(Bot* bot, bool recalculate, float) +{ + if (!recalculate) + { + m_targetChanged[bot->getBotId()] = false; + bot->addToMoveInclination(m_value24[bot->getBotId()]); + return 0.0f; + } + + Vec3 unused; + unused.x = 0.0f; + unused.y = 0.0f; + unused.z = 0.0f; + (void)unused; + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + IAIMain::m_instance->getSAI(bot->getSide()); // result unused + const Vec3& position = equipment->getPosition(); + m_value24[bot->getBotId()] = bot->getWaypoints()->getUrgency(position, bot); + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders()) + m_value24[bot->getBotId()] = m_value24[bot->getBotId()] * bot->getMemory()->m_float8; + if (0.0f < m_value24[bot->getBotId()]) + { + m_targetChanged[bot->getBotId()] = bot->getWaypoints()->m_flag4; + bot->addToMoveInclination(m_value24[bot->getBotId()]); + Vec3 goal; + goal.x = 0.0f; + goal.y = 0.0f; + goal.z = 0.0f; + if (bot->getWaypoints()->getGoalPoint(goal)) + bot->insertBehaviourInformation(0.5f, goal, m_index); + } + else + { + m_targetChanged[bot->getBotId()] = false; + } + return 0.0f; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveToFixed.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveToFixed.h new file mode 100644 index 000000000..50fdc0b0e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveToFixed.h @@ -0,0 +1,36 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBMOVETOFIXED_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBMOVETOFIXED_H + +#include "BotBehaviour.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4BAFE0 (13 words), operator new 0x28, package G-vehicles. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BBMoveToFixed : public BotBehaviour +{ +public: + BBMoveToFixed(unsigned char, unsigned char); // 0x219C20 + virtual ~BBMoveToFixed(); // 0x219E80 + + virtual float calculateUrgency(Bot*, bool, float); // 0x219F20, slot +0x28; from the base declaration + + /* +0x24 */ float* m_value24; // per bot, 0.0f; calculateUrgency stores and compares it [UNRESOLVED] meaning +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBMOVETOFIXED_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBPendingCalls.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBPendingCalls.h new file mode 100644 index 000000000..06203d62c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBPendingCalls.h @@ -0,0 +1,68 @@ +// [TEMP] [CHOSEN, not recovered] package D's stand-ins (since ai-bot eeb9049 they forward to the +// recovered callees; call sites may call them directly and this file go) for calls whose callee is not declared in +// this tree yet. Each wrapper names the image's call (ELF address of the callee) and stops by name, +// so D's recovered bodies stay complete and read like the image; when the owner's declaration +// lands, the wrapper body becomes the real call (or the call site calls it directly). +// [RETIRE-WHEN: ai-w1-d-pending-calls] every callee below is declared and linked (coord/ai-requests.md). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBPENDINGCALLS_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBPENDINGCALLS_H + +#include "../AIBotActionPlan/BAPStatement.h" +#include "../Main/AIDllFrontier.h" +#include "../AIBot/CommunicationAgent.h" +#include "../AIBot/SquadMember.h" +#include "../AIBot/WPCloseTo.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +class BotScript; +class CommunicationAgent; +class SquadMember; +class WaypointList; +struct AIRadioMessageInfo; +enum AIRadioMessageType : int; + +namespace bbpending { + +// --- ai-bot ------------------------------------------------------------------------------- +inline bool isAtFormationSlot(SquadMember* member) // SquadMember::isAtFormationSlot 0x1B5540 +{ + return member->isAtFormationSlot(); +} + + +// WPCloseTo +0x10: the handle of the object to close in on (getId() 0), read inline by +// BBPGotoWaypointSoldier::createPlan 0x284EEC. WPCloseTo is not declared in this tree. +inline unsigned int closeToTarget(WaypointList* waypoints) +{ + return static_cast(waypoints)->getTarget(); +} + +// CommunicationAgent::generalConfirmReceivedMessage(AIRadioMessageType) +inline bool generalConfirmReceivedMessage(CommunicationAgent* agent, AIRadioMessageType type) +{ + return agent->generalConfirmReceivedMessage(type); +} + +// CommunicationAgent::confirmReceivedMessage(const AIRadioMessageInfo&) +inline bool confirmReceivedMessage(CommunicationAgent* agent, const AIRadioMessageInfo& info) +{ + return agent->confirmReceivedMessage(info); +} + +// CommunicationAgent +0x5C (m_int92, private), read inline by BBIdle::waitForPickup 0x21584E. +inline int communicationAgentInt92(CommunicationAgent* agent) +{ + return agent->getInt92(); +} + +} // namespace bbpending +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBPENDINGCALLS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRandom.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRandom.cpp new file mode 100644 index 000000000..0fb7a74ee --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRandom.cpp @@ -0,0 +1,191 @@ +// Random behaviour (infantry "Random" slot of aibehaviours.ai). Despite the name it reacts to a +// grenade warning: once BotNavigation reports one, the behaviour wins with urgency 1000 until +// 5 s after the grenade's time has passed. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see +// docs/macos-ai-behaviour-plan.md. + +#include "BBRandom.h" + +// static init: ELF 0x21AB30, 0x21AC40, 0x21AC70 (iostream Init, then the local color table). +#include + +#include "../AIBot/BotMain.h" +#include "../AIBotBehaviourPattern/BBPRandom.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIUtils/checkPointer.h" +#include "../AIBot/BotNavigation.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" + +#include +#include +#include + +namespace dice { +namespace hfe { +namespace world { +namespace { + +// [CHOSEN, not recovered] Type, component names and constructor spelling for the +// three-float elements stored by ELF 0x21AB30. No original type name is attested. +struct DebugMeshMaterialColor +{ + float r, g, b; + + DebugMeshMaterialColor(float red, float green, float blue) : r(red), g(green), b(blue) {} +}; + +static_assert(sizeof(DebugMeshMaterialColor) == 12, "color element stride"); +static_assert(offsetof(DebugMeshMaterialColor, r) == 0 && + offsetof(DebugMeshMaterialColor, g) == 4 && + offsetof(DebugMeshMaterialColor, b) == 8, "color component offsets"); +static_assert(std::is_trivially_destructible::value, + "the color table has no registered teardown"); + +} // anonymous namespace + +// ELF 0x4CE300, local symbol, ten elements. __tcf_0 destroys only iostream Init. +// [CHOSEN, not recovered] Retain the unreferenced retail object with modern compilers. +#if defined(__GNUC__) +__attribute__((used)) +#endif +static DebugMeshMaterialColor debugMeshMaterialColors[10] = { + {0.66f, 0.66f, 0.185f}, + {0.185f, 0.66f, 0.185f}, + {0.185f, 0.185f, 0.66f}, + {0.185f, 0.66f, 0.66f}, + {0.66f, 0.185f, 0.185f}, + {0.66f, 0.66f, 0.66f}, + {0.66f, 0.185f, 0.66f}, + {0.185f, 0.185f, 0.185f}, + {1.0f, 1.0f, 1.0f}, + {0.0f, 0.0f, 0.0f} +}; +static_assert(sizeof(debugMeshMaterialColors) == 0x78, "local color table extent"); + +} // namespace world +namespace ai { + +// ELF 0x21A250 (C2) / 0x21A470 (C1). +BBRandom::BBRandom(unsigned char index, unsigned char queue, PlanGenerator* pattern, UrgeCurve* curve, + float* modifiers) + : BotBehaviour(modifiers, curve, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_grenadePosition.x = 0.0f; // 0x21A2BF: rodata 0x49CB34 into +0x38/+0x3C/+0x40 + m_grenadePosition.y = 0.0f; + m_grenadePosition.z = 0.0f; + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_targets = checkPointer(new unsigned int[count]); + for (int i = 0; i < count; ++i) + m_urgency[i] = 0.0f; + m_grenadeWarning = false; // 0x21A341 + m_warningTime = 0.0; // 0x21A345: fstl / fstpl of the same 0.0f + m_grenadeTime = 0.0; +} + +// ELF 0x21A690 (D2) / 0x21A6E0 (D1) / 0x21A730 (D0) +BBRandom::~BBRandom() +{ + if (m_targets) + delete[] m_targets; +} + +// ELF 0x21A780 (261 insns). +float BBRandom::calculateUrgency(Bot* bot, bool active, float) +{ + PlanGenerator* pattern = m_pattern; + if (!active) + { + // 0x21AA90: an initiated pattern keeps the stored urgency; otherwise uninit and 0. + if (pattern->isInitiated(bot)) + return m_urgency[bot->getBotId()]; + pattern->unInit(bot); + return m_urgency[bot->getBotId()] = 0.0f; // `fsts` - the stored value is returned + } + + float urgency = 0.0f; + Vec3 grenadePosition; // -0x28, zeroed + grenadePosition.x = 0.0f; + grenadePosition.y = 0.0f; + grenadePosition.z = 0.0f; + + if (!m_grenadeWarning) + { + // 0x21A7CC: BotNavigation::getGrenadeWarning(Vec3&, double&) returns bool (`testb %al`), + // then BotNavigation's bool at +0x114 (m_flag276) must be set too. + // 0x21A7E8 call, 0x21A87B `cmpb $0x0, 0x114(%eax)` on a second getBotNavigation. + double grenadeTime; // -0x60 + if (bot->getBotNavigation()->getGrenadeWarning(grenadePosition, grenadeTime) + && bot->getBotNavigation()->getGrenadeFlag()) + { + m_grenadeWarning = true; + m_warningTime = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + m_grenadeTime = grenadeTime; + m_grenadePosition = grenadePosition; + } + } + else + { + // 0x21A8C8: `fldl +0x30; faddl +0x28; fucomi; jbe` - nothing until the grenade's time has + // passed; 5 s (rodata 0x49CDAC, a float) after it the warning is dropped, but this tick + // still answers it. + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + const double end = m_grenadeTime + m_warningTime; + if (now > end) + { + if (now > end + 5.0f) + m_grenadeWarning = false; + + // 0x21A8FF: ignore the bot's own equipment object (no null check in the image) and + // trace from one metre above it to the grenade; the result is not used (retail). + std::vector ignore; + Information* info = informationManager->getInformation(bot->getCurrentEquipment()); + ignore.push_back(info->getAIObject()); + IAIObjectEnvironment* environment = + static_cast(CommonSingletonServer::m_iaiObjectEnvironment); + const Vec3& position = info->getPosition(); + Vec3 up; + up.x = 0.0f; + up.y = 1.0f; + up.z = 0.0f; + Vec3 from; + from.x = position.x + up.x; + from.y = position.y + up.y; + from.z = position.z + up.z; + bool hit; // -0x65 + environment->collideLineWithWorld(from, m_grenadePosition, ignore, false, 0.7f, false, hit); // slot +0x40 + + static_cast(m_pattern)->init(bot); + m_urgency[bot->getBotId()] = 1000.0f; // rodata 0x49CF48 + return 1000.0f; // the local, not a reload (0x21AA42) + } + } + + // 0x21A7F1: `flds 0.001; flds urgency; fxch; fucompi; jbe init` - init unless below 0.001. + if (urgency < 0.001f) + pattern->unInit(bot); + else + static_cast(m_pattern)->init(bot); + m_urgency[bot->getBotId()] = urgency; + return m_urgency[bot->getBotId()]; +} + +// ELF 0x21AAF0: alive bots answer getManDown (+0x1B0). +bool BBRandom::isApplicable(Information*, Bot* bot) +{ + if (!bot->getPlayer()->getIsAlive()) + return false; + return bot->getManDown(); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRandom.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRandom.h new file mode 100644 index 000000000..f827b93e1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRandom.h @@ -0,0 +1,48 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBRANDOM_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBRANDOM_H + +#include "BotBehaviour.h" + +#include "../../../../Math/Vec3.h" // Vec3 is a typedef; never forward-declare + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class Information; +class PlanGenerator; +class UrgeCurve; + +// ELF: vtable 0x4BB080 (14 words), operator new 0x44, package F-infantry. +class BBRandom : public BotBehaviour +{ +public: + BBRandom(unsigned char, unsigned char, PlanGenerator*, UrgeCurve*, float*); // 0x21A470 + virtual ~BBRandom(); // 0x21A6E0 + + virtual float calculateUrgency(Bot*, bool, float); // 0x21A780, slot +0x28; from the base declaration + virtual bool isApplicable(Information*, Bot*); // 0x21AAF0, slot +0x34; bool: getManDown or 0 + +private: + // Constructor 0x21A250: +0x24 = false, +0x28/+0x30 = 0.0, +0x38 = (0,0,0). One grenade + // warning is kept for the whole behaviour object, not per bot (retail; the object is shared + // by every bot of the vehicle type). [INFERRED] names. + /* +0x24 */ bool m_grenadeWarning; + /* +0x28 */ double m_warningTime; // IBFTimer::getGameTime when the warning was taken + /* +0x30 */ double m_grenadeTime; // BotNavigation::getGrenadeWarning's time + /* +0x38 */ Vec3 m_grenadePosition; // BotNavigation::getGrenadeWarning's position +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBRANDOM_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRevive.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRevive.cpp new file mode 100644 index 000000000..183e879ba --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRevive.cpp @@ -0,0 +1,302 @@ +// Revive behaviour (infantry "Revive" slot of aibehaviours.ai): a bot carrying a revive weapon +// (WeaponInfo type 3) looks for man-down friendly soldiers within 40 m and picks the one it can +// reach soonest relative to the man-down time left; ordered targets and human players weigh more. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see +// docs/macos-ai-behaviour-plan.md. + +// static init: ELF 0x21C8A0 (__tcf_0 0x21C900, _GLOBAL__I 0x21C930): 's Init object only. +#include + +#include "../AIBot/SquadManager.h" // requestResponseModifier (ai-bot) +#include "BBRevive.h" + +#include "../AIUtils/CustomCurve.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotMemory.h" +#include "../AIBotBehaviourPattern/BBPRevive.h" +#include "../AIKnowledge/BFInformationEnvironment.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AIDllFrontier.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" +#include "../../../../Math/Vec3.h" + +#include +#include +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x21AC90 (C2) / 0x21B220 (C1). Base with getMaxNBots; the vector is empty; then +0x30, +0x34, +// +0x38 = checkPointer(new[getNBattleStrengths]) (IAISettings +0x34, called once per array); the +// index, queue and pattern; +0x08 = checkPointer(new unsigned int[getMaxNBots]) (not initialised); +// every bot starts with urgency 0.0f (rodata 0x49CB34) and changed flag false. +BBRevive::BBRevive(unsigned char index, unsigned char queue, BBPRevive* pattern, UrgeCurve* curve, float* modifiers) + : BotBehaviour(modifiers, curve, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()), + m_friendlyUnits() +{ + m_bestWeapon = checkPointer(new int[static_cast(CommonSingletonServer::m_iaiSettings)->getNBattleStrengths()]); + m_rangeSq = checkPointer(new float[static_cast(CommonSingletonServer::m_iaiSettings)->getNBattleStrengths()]); + m_bestStrength = checkPointer(new int[static_cast(CommonSingletonServer::m_iaiSettings)->getNBattleStrengths()]); + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_targets = checkPointer(new unsigned int[count]); + for (int i = 0; i < count; ++i) + { + m_urgency[i] = 0.0f; + m_targetChanged[i] = false; + } +} + +// ELF 0x21B7B0 (D2) / 0x21B860 (D1) / 0x21B910 (D0): delete[] +0x08, +0x30, +0x34, +0x38 when set, +// the vector, then the base. +BBRevive::~BBRevive() +{ + if (m_targets) + delete[] m_targets; + if (m_bestWeapon) + delete[] m_bestWeapon; + if (m_rangeSq) + delete[] m_rangeSq; + if (m_bestStrength) + delete[] m_bestStrength; +} + +// ELF 0x21B9D0 (958 insns). +// Not updating: a target still on the bot's side keeps the urgency while the pattern runs; +// otherwise the changed flag records a non-zero urgency, which drops to 0, and the pattern unInits. +// Updating: candidates are man-down soldiers (type flag 0x200000) with physical and mobile +// plug-ins, not swimming and not under more than 0.75 of water, whose strength type the bot has a +// revive weapon for and whose man-down time left is at least 0.001. Retail: the bot's own +// Information and its armament are used without a null check. +float BBRevive::calculateUrgency(Bot* bot, bool update, float modifier) +{ + BBPRevive* const pattern = static_cast(m_pattern); + unsigned int* const targets = m_targets; + + if (!update) + { + // 0x21B9FA: Information slot +0x44 (getSide) against Bot +0xE0. + Information* const target = informationManager->getInformation(targets[bot->getBotId()]); + if (target && target->getSide() == bot->getSide()) + { + m_targetChanged[bot->getBotId()] = false; + if (!pattern->isInitiated(bot)) + m_urgency[bot->getBotId()] = 0.0f; + } + else + { + m_targetChanged[bot->getBotId()] = m_urgency[bot->getBotId()] != 0.0f; + m_urgency[bot->getBotId()] = 0.0f; + pattern->unInit(bot); + } + return m_urgency[bot->getBotId()]; + } + + const int strengthCount = static_cast(CommonSingletonServer::m_iaiSettings)->getNBattleStrengths(); + for (int i = 0; i < strengthCount; ++i) + { + m_bestWeapon[i] = -1; + m_bestStrength[i] = 0; + } + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + IPIArmament* const armament = self->getArmament(); + const Vec3& position = self->getPosition(); + // 0x21BC15: the inlined resize(0) (erase when non-empty, _M_fill_insert of 0 elements else). + m_friendlyUnits.resize(0); + static_cast(AISingletonServer::m_iaiInformationEnvironment) + ->getFriendlyUnits(m_friendlyUnits, position, bot, 40.0f); // slot +0x08, rodata 0x49CFD4 + if (m_friendlyUnits.empty()) + { + m_targetChanged[bot->getBotId()] = m_urgency[bot->getBotId()] != 0.0f; + m_urgency[bot->getBotId()] = 0.0f; + pattern->unInit(bot); + return 0.0f; + } + + // 0x21BC7F: a copy of the weapon list (allocate + memmove), freed on every exit. + const std::vector weapons = armament->getWeapons(); + const int kit = bot->getPlayer()->getSpawnKit(); // IAIPlayer +0x44 + for (unsigned int i = 0; i < weapons.size(); ++i) + { + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (!weapon || weapon->getWeaponType() != 3) + continue; + for (int s = 0; s < strengthCount; ++s) + { + if (weapon->getStrength(s) > m_bestStrength[s]) + { + m_bestWeapon[s] = static_cast(i); + m_bestStrength[s] = weapon->getStrength(s); + const float range = weapon->getMaxRange(); + m_rangeSq[s] = range * range; + } + } + } + + float bestScore = 0.0f; // -0x1A0 + unsigned int orderedCount = 0; // -0x1A4 + int bestWeapon = -1; // -0x1A8 + unsigned int bestTarget = 0xFFFFFFFFu; // -0x1AC + const float maxSpeed = self->getMobile()->getMaxSpeed(); + float bestDistance = 100.0f; // -0x1B4, rodata 0x49CB5C + + for (std::vector::iterator it = m_friendlyUnits.begin(); it != m_friendlyUnits.end(); ++it) + { + Information* const unit = informationManager->getInformation(*it); + if (!unit) + continue; + IPIPhysical* const physical = unit->getPhysical(); + if (!physical || unit == self || !unit->hasMobile() || !unit->isOfType(ITSoldier)) + continue; + if (!physical->getManDown()) // IPIPhysical +0x5C + continue; + if (unit->getSoldierPose() == SPSwimming) + continue; + // 0x21C30D: IAITerrain +0x30 getWaterLevel and +0x08 getHeight at the unit's x, z. + const Vec3& unitPosition = unit->getPosition(); + IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + const float waterLevel = terrain->getWaterLevel(unitPosition.x, unitPosition.z); + const float height = terrain->getHeight(unitPosition.x, unitPosition.z); + if (waterLevel + 0.5f > unitPosition.y && waterLevel - height > 0.75f) // rodata 0x49CB44, 0x49CB54 + continue; + const int strengthType = physical->getStrengthType(); // IPIPhysical +0x44 + if (m_bestWeapon[strengthType] == -1) + continue; + const float timeLeft = physical->getManDownTimeLeft(); // IPIPhysical +0x54 + if (0.001f > timeLeft) // rodata 0x49CC94 + continue; + + Vec3 offset; + offset.x = unitPosition.x - position.x; + offset.y = unitPosition.y - position.y; + offset.z = unitPosition.z - position.z; + const float distance = std::sqrt(offset.x * offset.x + offset.y * offset.y + offset.z * offset.z); + float score = distance / maxSpeed / timeLeft; + if (score > 1.0f) + score = 1.0f; + score = 1.0f - score; + + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders()) + { + // 0x21C5D0: the old std::list::size walk, then std::find over the order list; each + // further one-time order match multiplies by BotMemory +0x08. + if (bot->getOrderList(m_index)->size() > orderedCount) + { + const std::list::iterator end = bot->getOrderList(m_index)->end(); + if (std::find(bot->getOrderList(m_index)->begin(), bot->getOrderList(m_index)->end(), *it) != end) + { + ++orderedCount; + score *= bot->getMemory()->m_float8; + } + } + } + + IPIUnit* const unitPlugIn = unit->getUnit(); + if (unitPlugIn && unitPlugIn->isOccupied()) + { + // IAIPlayerFactory +0x20 getPlayerFromId, IAIPlayer +0x88 getIsAIPlayer: humans weigh x10. + IAIPlayer* const occupant = static_cast(CommonSingletonServer::m_iaiPlayerFactory) + ->getPlayerFromId(unitPlugIn->getOccupyingPlayerId(unit->getSide())); + if (occupant && !occupant->getIsAIPlayer()) + score *= 10.0f; // rodata 0x49CC88 + } + if (score > bestScore) + { + bestDistance = distance; + bestScore = score; + bestWeapon = m_bestWeapon[strengthType]; + bestTarget = *it; + } + } + + if (bestTarget == 0xFFFFFFFFu) + { + m_urgency[bot->getBotId()] = 0.0f; + m_targetChanged[bot->getBotId()] = targets[bot->getBotId()] != 0xFFFFFFFFu; + targets[bot->getBotId()] = 0xFFFFFFFFu; + pattern->unInit(bot); + return 0.0f; + } + + Information* const target = informationManager->getInformation(bestTarget); + bool humanTarget = false; + if (target && target->getUnit() && target->getUnit()->isOccupied()) + { + IAIPlayer* const occupant = static_cast(CommonSingletonServer::m_iaiPlayerFactory) + ->getPlayerFromId(target->getUnit()->getOccupyingPlayerId(target->getSide())); + if (occupant && !occupant->getIsAIPlayer()) + humanTarget = true; + } + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && bot->getOrderList(m_index)->empty()) + bestScore *= bot->getMemory()->m_float8; + + // 0x21BF7C: a human closer than 50 m gets 100.0f flat (no modifier); otherwise the declining + // slope of the best score, x5 for a human and x2 (fadd %st(0), %st) for a bot, times the modifier. + float urgency; + if (humanTarget) + { + if (50.0f > bestDistance) // rodata 0x49CCA8 + urgency = 100.0f; + else + urgency = DecleiningSlopeCurve::calculate(bestScore) * 5.0f * modifier; + } + else + { + const float slope = DecleiningSlopeCurve::calculate(bestScore); + urgency = (slope + slope) * modifier; + } + m_urgency[bot->getBotId()] = urgency; + m_targetChanged[bot->getBotId()] = targets[bot->getBotId()] != bestTarget; + targets[bot->getBotId()] = bestTarget; + pattern->init(targets[bot->getBotId()], bestWeapon, bot); + + if (kit == 5) + { + // 0x21C0BC: m_urgency[id] = SquadManager::requestResponseModifier(SquadManager::m_instance, + // bot->getSquadMember() (Bot +0x140), bestTarget, RequestAction 1, bot->getSide()) * m_urgency[id] + // (x87 result, fmuls of the stored urgency). + m_urgency[bot->getBotId()] = SquadManager::m_instance->requestResponseModifier( + bot->getSquadMember(), bestTarget, 1, bot->getSide()) + * m_urgency[bot->getBotId()]; + } + return m_urgency[bot->getBotId()]; +} + +// ELF 0x21C810: true when the information's armament (+0x2C) lists a weapon of type 3; the list +// (IPIArmament +0x20 getWeapons) is re-measured on every pass. +bool BBRevive::isAplicable(Information* information, Bot*) +{ + IPIArmament* const armament = information->getArmament(); + if (armament) + { + std::vector& weapons = armament->getWeapons(); + for (unsigned int i = 0; i < weapons.size(); ++i) + { + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (weapon && weapon->getWeaponType() == 3) + return true; + } + } + return false; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRevive.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRevive.h new file mode 100644 index 000000000..ad4067dd0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRevive.h @@ -0,0 +1,50 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBREVIVE_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBREVIVE_H + +#include "BotBehaviour.h" + +#include + +namespace dice { +namespace hfe { + +namespace ai { + +class BBPRevive; +class Bot; +class Information; +class UrgeCurve; + +// ELF: vtable 0x4BB120 (13 words), operator new 0x3C, package F-infantry. +// The base +0x08 array holds the handle of the man-down soldier each bot goes to revive +// (unsigned int per bot, 0xFFFFFFFF = none); +0x0C is the BBPRevive pattern. +class BBRevive : public BotBehaviour +{ +public: + BBRevive(unsigned char, unsigned char, BBPRevive*, UrgeCurve*, float*); // 0x21B220 + virtual ~BBRevive(); // 0x21B860 + + virtual float calculateUrgency(Bot*, bool, float); // 0x21B9D0, slot +0x28; from the base declaration + virtual bool isAplicable(Information*, Bot*); // 0x21C810, slot +0x30; bool: `movl $0x1` / `xorl` into %eax + +private: + // Constructor 0x21B220: the vector is constructed empty before the vptr store; the three + // arrays are new[getNBattleStrengths] (IAISettings +0x34), checkPointer'd. calculateUrgency + // refills them per update from the bot's revive weapons (WeaponInfo type 3). + /* +0x24 */ std::vector m_friendlyUnits; // getFriendlyUnits result, radius 40 [INFERRED] name + /* +0x30 */ int* m_bestWeapon; // per strength type: index into the weapon list, -1 = none + /* +0x34 */ float* m_rangeSq; // per strength type: that weapon's getMaxRange squared (not read here) + /* +0x38 */ int* m_bestStrength; // per strength type: that weapon's getStrength +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBREVIVE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRunOverSoldier.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRunOverSoldier.cpp new file mode 100644 index 000000000..9e210bca5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRunOverSoldier.cpp @@ -0,0 +1,157 @@ +// Run-over behaviour (AI/AIDLL/AI/AIBotBehaviour/BBRunOverSoldier.cpp in the image). Recovered from +// libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. + +// static init: ELF 0x21D3B0 (__tcf_0 0x21D410, _GLOBAL__I 0x21D440): 's Init object only. +#include + +#include "BBRunOverSoldier.h" + +#include "../Main/AIDllFrontier.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../AIUtils/checkPointer.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SensedObject.h" +#include "../AIBotBehaviourPattern/BBPRunOverSoldier.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../Main/IAIPathfinding.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" + +#include +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x21C950 (C2) / 0x21CB40 (C1); vtable GOT -0xA20. The base gets getMaxNBots; a second +// getMaxNBots sizes the +0x08 target array (not initialised) through the inlined checkPointer +// (Debug type 6, line 46); every bot starts with urgency 0.0f. +BBRunOverSoldier::BBRunOverSoldier(unsigned char index, unsigned char queue, PlanGenerator* pattern, + UrgeCurve* curve, float* modifiers) + : BotBehaviour(modifiers, curve, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_targets = checkPointer(new unsigned int[count]); + for (int i = 0; i < count; ++i) + m_urgency[i] = 0.0f; +} + +// ELF 0x21CD30 (D2) / 0x21CD80 (D1) / 0x21CDD0 (D0): delete[] +0x08 when set, then ~BotBehaviour. +BBRunOverSoldier::~BBRunOverSoldier() +{ + if (m_targets) + delete[] m_targets; +} + +// ELF 0x21CE20 (Ghidra; listing for the trace arguments and the constants). A bot whose vehicle +// moves at least minSpeed runs over the first living enemy soldier it sees directly that lies +// ahead (direction against the transformation's third row at least minDot) within maxDistance +// (distance floored at 1) and that the pathfinding trace from the vehicle's last valid +// position reaches: urgency 65, target in +0x08. The pattern is initialised with the stored +// target even when none was found this time. +float BBRunOverSoldier::calculateUrgency(Bot* bot, bool recalculate, float) +{ + static float minSpeed = 10.0f; // .data + static float minDot = 0.85f; // .data + static float maxDistance = 50.0f; // .data + + if (!recalculate) + { + m_urgency[bot->getBotId()] = 0.0f; + return m_urgency[bot->getBotId()]; + } + + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + m_urgency[bot->getBotId()] = 0.0f; + const int equipmentType = equipment->getUnit()->getEquipmentType(); + IPIMobile* const mobile = equipment->getMobile(); + if (!(minSpeed <= mobile->getSpeedMagnitude())) + { + m_urgency[bot->getBotId()] = 0.0f; + return m_urgency[bot->getBotId()]; + } + + const Vec3& position = equipment->getPosition(); + const std::map& sensed = bot->getSensedObjects(); + for (std::map::const_iterator it = sensed.begin(); it != sensed.end(); ++it) + { + const unsigned int flags = it->second->m_flags; + if (!(flags & SensedObject::SENSE_SEEN) || !(flags & SensedObject::SENSE_SIDED) + || (flags & SensedObject::SENSE_INDIRECT)) + continue; + Information* const info = informationManager->getInformation(it->second->m_handle); + if (!info || !info->isOfType(ITSoldier)) + continue; + if (info->getSide() == bot->getSide() || info->getSide() == 0) + continue; + IPIPhysical* const physical = info->getPhysical(); + IPIMobile* const targetMobile = info->getMobile(); + if (!physical || !(physical->getHealth() > 0.0f) || !targetMobile) + continue; + const Vec3& targetPosition = info->getPosition(); + Vec3 direction; + direction.x = targetPosition.x - position.x; + direction.y = targetPosition.y - position.y; + direction.z = targetPosition.z - position.z; + const float length = std::sqrt(direction.x * direction.x + direction.y * direction.y + + direction.z * direction.z); + if (!(length > 0.0001f)) + continue; + const float inverse = 1.0f / length; + direction.x = direction.x * inverse; + float distance = 1.0f; + if (1.0f <= length) + distance = length; + direction.y = direction.y * inverse; + direction.z = inverse * direction.z; + const Mat4& transformation = equipment->getTransformation(); + if (minDot > transformation.m[10] * direction.z + transformation.m[8] * direction.x + + transformation.m[9] * direction.y) + continue; + if (distance > maxDistance) + continue; + const IPIMobile::ValidPos& targetValid = targetMobile->getLastValidPosition(mobile->getVehicleNumber()); + if (targetValid.island == static_cast(-1) || targetValid.polygon == static_cast(-1)) + continue; + const IPIMobile::ValidPos& valid = mobile->getLastValidPosition(); + IAIPathfinding* const pathfinding = IAIPathfinding::instance; + Vec3 end; + end.x = 0.0f; + end.y = 0.0f; + end.z = 0.0f; + unsigned int endPolygon; + if (pathfinding->trace(valid.polygon, valid.island, mobile->getVehicleNumber(), valid.position, + targetValid.position, end, endPolygon, equipmentType, -1, 0.0f, 5, 0)) + { + m_targets[bot->getBotId()] = it->first; + m_urgency[bot->getBotId()] = 65.0f; + break; + } + } + static_cast(m_pattern)->init(bot, m_targets[bot->getBotId()]); + return m_urgency[bot->getBotId()]; +} + +// ELF 0x21D360 (Ghidra). Applicable while the bot's player is alive and not man down. +bool BBRunOverSoldier::isApplicable(Information*, Bot* bot) +{ + bool applicable = false; + if (bot->getPlayer()->getIsAlive()) + applicable = !bot->getManDown(); + return applicable; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRunOverSoldier.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRunOverSoldier.h new file mode 100644 index 000000000..9f3495c16 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRunOverSoldier.h @@ -0,0 +1,38 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBRUNOVERSOLDIER_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBRUNOVERSOLDIER_H + +#include "BotBehaviour.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class Information; +class PlanGenerator; +class UrgeCurve; + +// ELF: vtable 0x4BB1C0 (14 words), operator new 0x24, package G-vehicles. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BBRunOverSoldier : public BotBehaviour +{ +public: + BBRunOverSoldier(unsigned char, unsigned char, PlanGenerator*, UrgeCurve*, float*); // 0x21CB40 + virtual ~BBRunOverSoldier(); // 0x21CD80 + + virtual float calculateUrgency(Bot*, bool, float); // 0x21CE20, slot +0x28; from the base declaration + virtual bool isApplicable(Information*, Bot*); // 0x21D360, slot +0x34; [INFERRED] ELF int +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBRUNOVERSOLDIER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBSuicide.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBSuicide.cpp new file mode 100644 index 000000000..3bf75b45a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBSuicide.cpp @@ -0,0 +1,57 @@ +// Suicide urgency is the remaining fraction of the current equipment's man-down interval. + +// static init: ELF 0x21D740 (__tcf_0 0x21D7A0, _GLOBAL__I 0x21D7D0): 's Init object only. +#include + +#include "BBSuicide.h" + +#include "../AIBot/BotMain.h" +#include "../AIBotBehaviourPattern/BBPSuicide.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x21D460 (C2), 0x21D510 (C1) +BBSuicide::BBSuicide(unsigned char index, unsigned char queue, BBPSuicide* pattern, + UrgeCurve* curve, float* modifiers) + : BotBehaviour(modifiers, curve, + static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + for (int i = 0; i < count; ++i) + { + m_urgency[i] = 0.0f; + m_targetChanged[i] = false; + } +} + +// ELF 0x21D5C0 (D2), 0x21D600 (D1), 0x21D640 (D0) +BBSuicide::~BBSuicide() +{ +} + +// ELF 0x21D680 +float BBSuicide::calculateUrgency(Bot* bot, bool, float) +{ + Information* equipment = informationManager->getInformation(bot->getCurrentEquipment()); + IPIPhysical* physical = equipment->getPhysical(); + const unsigned int index = bot->getBotId(); + const float remaining = physical->getManDownTimeLeft(); + const float maximum = physical->getMaxManDownTime(); + m_urgency[index] = remaining / maximum; + static_cast(m_pattern)->init(bot); + return m_urgency[bot->getBotId()]; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBSuicide.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBSuicide.h new file mode 100644 index 000000000..2aeb2019b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBSuicide.h @@ -0,0 +1,31 @@ +// Man-down suicide urgency and pattern initialization. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBSUICIDE_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBSUICIDE_H + +#include "BotBehaviour.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BBPSuicide; +class Bot; +class UrgeCurve; + +// ELF: vtable 0x4BB220 (13 words), operator new 0x24, package H-deferred. +class BBSuicide : public BotBehaviour +{ +public: + BBSuicide(unsigned char, unsigned char, BBPSuicide*, UrgeCurve*, float*); // 0x21D510 + virtual ~BBSuicide(); // 0x21D600 + + virtual float calculateUrgency(Bot*, bool, float); // 0x21D680, slot +0x28; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBSUICIDE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover.cpp new file mode 100644 index 000000000..9c8a232aa --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover.cpp @@ -0,0 +1,387 @@ +// Cover urgency from directional threat strengths and reachable cover geometry. + +// static init: ELF 0x2204C0 (__tcf_0 0x220520, _GLOBAL__I 0x220550): 's Init object only. +#include + +#include "BBTakeCover.h" + +#include "../AIUtils/CustomCurve.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotMemory.h" +#include "../AIBotBehaviourPattern/BBPTakeCover.h" +#include "../AIKnowledge/BFInformationEnvironment.h" +#include "../AIKnowledge/DangerObject.h" +#include "../AIKnowledge/IPICover.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIPlanInterpreter/VehicleControlInline.h" +#include "../AIUtils/VehicleOccupancy.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IAIPathfinding.h" +#include "../../../../Math/LocalBoundingBox.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x21D7F0 (C2), 0x21DC00 (C1) +BBTakeCover::BBTakeCover(unsigned char index, unsigned char queue, PlanGenerator* pattern, + UrgeCurve* curve, float* modifiers) + : BotBehaviour(modifiers, curve, + static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_dangers = checkPointer(new DangerObject*[m_count]); + m_index = index; + m_queue = queue; + m_pattern = pattern; + m_targets = checkPointer(new unsigned int[m_count]); + // shipped defect: the first danger-pointer array is overwritten and leaked. + m_dangers = checkPointer(new DangerObject*[m_count]); + for (int i = 0; i < m_count; ++i) + { + m_targets[i] = 0xFFFFFFFFu; + m_urgency[i] = 0.0f; + m_dangers[i] = 0; + } +} + +// ELF 0x21E010 (D2), 0x21E090 (D1), 0x21E110 (D0) +BBTakeCover::~BBTakeCover() +{ + // DangerObject has no destructor slot; the shipped bodies deallocate these trivial wrappers. + for (int i = 0; i < m_count; ++i) + ::operator delete(m_dangers[i]); + if (m_targets) + delete[] m_targets; + if (m_dangers) + delete[] m_dangers; +} + +// ELF 0x220440 +void BBTakeCover::reset(Bot* bot) +{ + BotBehaviour::reset(bot); + if (m_dangers[bot->getBotId()]) + ::operator delete(m_dangers[bot->getBotId()]); + m_dangers[bot->getBotId()] = 0; +} + +// ELF 0x21E190 +float BBTakeCover::calculateUrgency(Bot* bot, bool evaluate, float scale) +{ + if (!evaluate) + { + m_targetChanged[bot->getBotId()] = false; + if (m_pattern->isInitiated(bot)) + return m_urgency[bot->getBotId()]; + m_urgency[bot->getBotId()] = 0.0f; + return 0.0f; + } + + // [INFERRED] local packaging of the repeated inlined pattern-clear block. + const auto clearPattern = [&]() + { + if (m_pattern->isInitiated(bot)) + { + m_targetChanged[bot->getBotId()] = true; + m_pattern->unInit(bot); + } + // shipped defect: this overwrites the changed-target flag just set above. + m_targetChanged[bot->getBotId()] = false; + m_urgency[bot->getBotId()] = 0.0f; + }; + + const int side = bot->getSide(); + Information* self = informationManager->getInformation(bot->getCurrentEquipment()); + IPIPhysical* physical = self->getPhysical(); + IPIMobile* mobile = self->getMobile(); + const int equipmentType = self->getUnit()->getEquipmentType(); + const auto& sensed = bot->getSensedObjects(); + const auto* incoming = bot->getIncommingFire(); + if (sensed.empty() && incoming->empty()) + { + clearPattern(); + return 0.0f; + } + + float total = 0.0f; + float sums[8] = {}; + float maxima[8] = {}; + DangerObject* dangers[8] = {}; + const Vec3 axisX = {1.0f, 0.0f, 0.0f}; + const Vec3 axisZ = {0.0f, 0.0f, 1.0f}; + const Vec3 diagonalA = {0.70710677f, 0.0f, -0.70710677f}; + const Vec3 diagonalB = {0.70710677f, 0.0f, 0.70710677f}; + const Vec3 position = self->getPosition(); + const int strengthType = physical->getStrengthType(); + const auto dot = [](const Vec3& a, const Vec3& b) + { + return a.x * b.x + a.y * b.y + a.z * b.z; + }; + const auto quadrants = [&](const Vec3& delta, int& first, int& second) + { + const float x = dot(axisX, delta); + const float z = dot(axisZ, delta); + first = !(z < 0.0f) ? int(!(x < 0.0f)) : 2 + int(x < 0.0f); + const float a = dot(diagonalA, delta); + const float b = dot(diagonalB, delta); + second = !(b < 0.0f) ? 4 + int(!(a < 0.0f)) : 6 + int(a < 0.0f); + }; + for (const auto& entry : *incoming) + { + FireObject* fire = entry.first; + const Vec3& origin = fire->getOrigin(); + const Vec3 delta = {origin.x - position.x, origin.y - position.y, origin.z - position.z}; + int first, second; + quadrants(delta, first, second); + float strength = fire->getBattleStrength(strengthType); + if (!fire->isDirect()) + strength *= 0.8f; + sums[first] += strength; + sums[second] += strength; + total += strength; + if (strength > maxima[first]) + { + maxima[first] = strength; + if (!dangers[first]) + dangers[first] = checkPointer(new FireDanger(fire)); + else + static_cast(dangers[first])->m_fire = fire; + } + if (strength > maxima[second]) + { + // shipped defect: the second quadrant's maximum is never updated for fire. + if (!dangers[second]) + dangers[second] = checkPointer(new FireDanger(fire)); + else + static_cast(dangers[second])->m_fire = fire; + } + } + + Information* ownSector = informationManager->getInformation(mobile->getSector()); + unsigned int matchedOrders = 0; + const auto weightOrder = [&](unsigned int handle, float& rating) + { + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && + matchedOrders < bot->getOrderList(m_index)->size()) + { + const auto end = bot->getOrderList(m_index)->end(); + const auto begin = bot->getOrderList(m_index)->begin(); + const auto last = bot->getOrderList(m_index)->end(); + if (end != std::find(begin, last, handle)) + { + ++matchedOrders; + rating *= bot->getMemory()->m_float8; + } + } + }; + for (const auto& entry : sensed) + { + Information* target = informationManager->getInformation(entry.first); + if (!target || target->getSide() != 0 || !vehicleOccupied(entry.first, side) || !target->getUnit()) + continue; + const Vec3& at = target->getPosition(); + const Vec3 delta = {at.x - position.x, at.y - position.y, at.z - position.z}; + int first, second; + quadrants(delta, first, second); + float distance = vehiclecontrol::distanceVec3(position, target->getPosition()); + distance = distance > 5.0f ? distance : 5.0f; + IPIMobile* targetMobile = target->getMobile(); + if (targetMobile && ownSector) + { + Information* targetSector = informationManager->getInformation(targetMobile->getSector()); + if (targetSector && ownSector->getAIObject() == targetSector->getAIObject()) + distance *= 0.5f; + } + int iterator = target->getFirstSecondaryObjectIterator(); + unsigned int next = target->getSecondaryObject(iterator, side); + Information* seat = target; + float rating; + do + { + // shipped defects: overwrite rather than accumulate, skip the first secondary seat, + // and match the next seat's handle against orders while rating the current seat. + rating = seat->getUnit()->getBattleStrengths()[strengthType] / distance; + weightOrder(next, rating); + next = target->getSecondaryObject(iterator, side); + seat = informationManager->getInformation(next); + } while (seat); + sums[first] += rating; + sums[second] += rating; + total += rating; + const auto setInformationDanger = [&](int quadrant) + { + if (rating > maxima[quadrant]) + { + maxima[quadrant] = rating; + if (dangers[quadrant] && dangers[quadrant]->isInformation()) + static_cast(dangers[quadrant])->m_information = entry.first; + else + { + ::operator delete(dangers[quadrant]); + dangers[quadrant] = checkPointer(new InfoDanger(entry.first)); + } + } + }; + setInformationDanger(first); + setInformationDanger(second); + } + + Vec3 coverPosition = {}; + DangerObject* previous = 0; + if (total > 0.0f) + { + IAIPathfinding* pathfinding = IAIPathfinding::instance; + previous = m_dangers[bot->getBotId()]; + m_dangers[bot->getBotId()] = 0; + float bestQuadrant = 0.0f; + for (int i = 0; i < 8; ++i) + { + if (sums[i] > bestQuadrant) + { + bestQuadrant = sums[i]; + ::operator delete(m_dangers[bot->getBotId()]); + m_dangers[bot->getBotId()] = dangers[i]; + } + else + ::operator delete(dangers[i]); + } + if (!m_dangers[bot->getBotId()]) + { + clearPattern(); + if (previous) + ::operator delete(previous); + m_urgency[bot->getBotId()] = 0.0f; + return 0.0f; + } + Information* threatSector = 0; + DangerObject* danger = m_dangers[bot->getBotId()]; + if (danger->isInformation()) + { + Information* threat = informationManager->getInformation(static_cast(danger)->m_information); + if (threat && threat->getMobile()) + threatSector = informationManager->getInformation(threat->getMobile()->getSector()); + } + Vec3 threatPosition = {}; + if (!m_dangers[bot->getBotId()]->getPosition(threatPosition)) + { + clearPattern(); + if (previous) + ::operator delete(previous); + m_urgency[bot->getBotId()] = 0.0f; + return 0.0f; + } + + float multiplier = 1.0f; + float bestCover = 0.0f; + LocalBoundingBox* bounds = const_cast(physical->getLocalBoundingBox()); + const float sizeX = bounds->getSize().x; + const float sizeZ = bounds->getSize().z; + const float width = sizeZ > sizeX ? sizeZ : sizeX; + const float height = bounds->getSize().y; + std::vector covers; + static_cast(AISingletonServer::m_iaiInformationEnvironment)->getCover(*bot, covers); + for (unsigned int handle : covers) + { + Information* cover = informationManager->getInformation(handle); + if (!cover) + continue; + IPIPhysical* coverPhysical = cover->getPhysical(); + IPICover* plugin = cover->getCover(); + if (!coverPhysical || !plugin || + (threatSector && threatSector->getAIObject() == cover->getAIObject())) + continue; + const Vec3 at = cover->getPosition(); + Vec3 direction = {at.x - threatPosition.x, at.y - threatPosition.y, at.z - threatPosition.z}; + vehiclecontrol::normalizeVec3(direction); + const Vec3 start = vehiclecontrol::alongFrom(at, direction, coverPhysical->getRadius() * 0.75f); + const Vec3 end = vehiclecontrol::alongFrom(at, direction, coverPhysical->getRadius() * 3.0f); + Vec3 valid = {}; + unsigned int polygon, island; + if (!pathfinding->findClosestValidPolygon(polygon, island, valid, mobile->getVehicleNumber(), + start, end, 10, equipmentType)) + continue; + LocalBoundingBox* coverBounds = const_cast(coverPhysical->getLocalBoundingBox()); + const float coverX = coverBounds->getSize().x; + const float coverZ = coverBounds->getSize().z; + const float coverWidth = coverZ > coverX ? coverZ : coverX; + const float coverHeight = coverBounds->getSize().y; + float widthFactor = (coverWidth / width) * 0.2f; + float heightFactor = (coverHeight / height) * 0.5f; + if (widthFactor < 0.0f) widthFactor = 0.0f; + if (heightFactor < 0.0f) heightFactor = 0.0f; + if (widthFactor > 1.0f) widthFactor = 1.0f; + if (heightFactor > 1.0f) heightFactor = 1.0f; + const float factor = widthFactor * 0.25f + heightFactor * 0.75f; + float denominator = vehiclecontrol::distanceVec3(cover->getPosition(), position) * factor; + if (plugin->getPortalCount()) + denominator *= 0.1f; + float rating = plugin->getCoverValue() / denominator; + weightOrder(handle, rating); + if (rating > bestCover) + { + bestCover = rating; + m_targets[bot->getBotId()] = handle; + coverPosition = valid; + multiplier *= 1.3f; + } + else if (rating > 0.0f) + multiplier *= (rating / bestCover) * 0.3f + 1.0f; + } + total = bestCover > 0.0f ? total * multiplier : 0.0f; + } + + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && bot->getOrderList(m_index)->empty()) + total *= bot->getMemory()->m_float8; + // The final x87 comparison takes the positive arm for unordered values as well. + if (!(total <= 0.0f)) + { + const unsigned int coverHandle = m_targets[bot->getBotId()]; + if (m_dangers[bot->getBotId()]) + { + const unsigned int changedIndex = bot->getBotId(); + m_targetChanged[changedIndex] = previous != m_dangers[bot->getBotId()]; + m_urgency[bot->getBotId()] = 0.0f; + if (previous) + ::operator delete(previous); + BBPTakeCover* pattern = static_cast(m_pattern); + DangerObject* danger = m_dangers[bot->getBotId()]; + Vec3 threatPosition = {}; + danger->getPosition(threatPosition); + if (danger->isInformation()) + pattern->init(bot, static_cast(danger)->m_information, coverPosition, coverHandle); + else + pattern->init(bot, threatPosition, coverPosition, coverHandle); + float distance = vehiclecontrol::distanceVec3(threatPosition, self->getPosition()); + distance = (distance > 10.0f ? distance : 10.0f) * 0.1f; + const unsigned int urgencyIndex = bot->getBotId(); + float* urgency = m_urgency; + const float strengthCurve = DecleiningSlopeCurve::calculate(total); + const float distanceCurve = SCurve::calculate(distance); + const float result = (distanceCurve * strengthCurve - 0.19f) * 1.0f * scale; + urgency[urgencyIndex] = result; + return result; + } + bot->getBotId(); + m_targetChanged[bot->getBotId()] = false; + m_pattern->unInit(bot); + m_urgency[bot->getBotId()] = 0.0f; + return 0.0f; + } + clearPattern(); + if (previous) + ::operator delete(previous); + m_urgency[bot->getBotId()] = 0.0f; + return 0.0f; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover.h new file mode 100644 index 000000000..352ac1655 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover.h @@ -0,0 +1,38 @@ +// Rates cover against incoming shots and sensed occupied vehicles, retaining one threat per bot. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBTAKECOVER_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBTAKECOVER_H + +#include "BotBehaviour.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class PlanGenerator; +class UrgeCurve; +class DangerObject; + +// ELF: vtable 0x4BB2C0 (13 words), operator new 0x2C, package H-deferred. +class BBTakeCover : public BotBehaviour +{ +public: + BBTakeCover(unsigned char, unsigned char, PlanGenerator*, UrgeCurve*, float*); // 0x21DC00 + virtual ~BBTakeCover(); // 0x21E090 + + virtual void reset(Bot*); // 0x220440, slot +0x24; from the base declaration + virtual float calculateUrgency(Bot*, bool, float); // 0x21E190, slot +0x28; from the base declaration + +private: + // [INFERRED] names; both constructors and reset/destruction establish these owned arrays. + /* +0x24 */ int m_count; + /* +0x28 */ DangerObject** m_dangers; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBTAKECOVER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover3d.cpp new file mode 100644 index 000000000..f46c8062b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover3d.cpp @@ -0,0 +1,81 @@ +// Aircraft cover urgency from missile-lock status. + +// static init: ELF 0x220BC0 (__tcf_0 0x220C20, _GLOBAL__I 0x220C50): 's Init object only. +#include + +#include "BBTakeCover3d.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/BotMemory.h" +#include "../AIBotBehaviourPattern/BBPTakeCover3d.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x220750 (C2), 0x220810 (C1) +BBTakeCover3d::BBTakeCover3d(unsigned char index, unsigned char queue, PlanGenerator* pattern, + UrgeCurve* curve, float* modifiers) + : BotBehaviour(modifiers, curve, + static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + // The allocated target elements are left uninitialized by the shipped constructor. + m_targets = new unsigned int[count]; + for (int i = 0; i < count; ++i) + m_urgency[i] = 0.0f; +} + +// ELF 0x2208D0 (D2), 0x220920 (D1), 0x220970 (D0) +BBTakeCover3d::~BBTakeCover3d() +{ + if (m_targets) + delete[] m_targets; +} + +// ELF 0x2209C0 +float BBTakeCover3d::calculateUrgency(Bot* bot, bool, float scale) +{ + Information* equipment = informationManager->getInformation(bot->getCurrentEquipment()); + float urgency = 0.0f; + switch (equipment->getUnit()->getMissileLockStatus()) + { + case 1: + case 2: + urgency = 0.0f; + break; + case 3: + urgency = 20.0f; + break; + default: + break; + } + if (urgency > 0.0f) + { + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && bot->getOrderList(m_index)->empty()) + urgency *= bot->getMemory()->m_float8; + m_urgency[bot->getBotId()] = urgency * scale; + m_targetChanged[bot->getBotId()] = false; + static_cast(m_pattern)->init(bot); + return m_urgency[bot->getBotId()]; + } + m_pattern->unInit(bot); + if (m_pattern->isInitiated(bot)) + m_targetChanged[bot->getBotId()] = true; + else + m_targetChanged[bot->getBotId()] = false; + m_urgency[bot->getBotId()] = 0.0f; + return 0.0f; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover3d.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover3d.h new file mode 100644 index 000000000..a69fe803d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover3d.h @@ -0,0 +1,31 @@ +// Aircraft cover urgency and initialization of its evasion pattern. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBTAKECOVER3D_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBTAKECOVER3D_H + +#include "BotBehaviour.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class PlanGenerator; +class UrgeCurve; + +// ELF: vtable 0x4BB3E0 (13 words), operator new 0x24, package H-deferred. +class BBTakeCover3d : public BotBehaviour +{ +public: + BBTakeCover3d(unsigned char, unsigned char, PlanGenerator*, UrgeCurve*, float*); // 0x220810 + virtual ~BBTakeCover3d(); // 0x220920 + + virtual float calculateUrgency(Bot*, bool, float); // 0x2209C0, slot +0x28; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBTAKECOVER3D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCoverInfantry.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCoverInfantry.cpp new file mode 100644 index 000000000..8ef138536 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCoverInfantry.cpp @@ -0,0 +1,543 @@ +// Infantry cover selection and per-quadrant threat bookkeeping. + +#include "BBTakeCoverInfantry.h" +#include "../AIUtils/CustomCurve.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotMemory.h" +#include "../AIBot/SensedObject.h" +#include "../AIBotBehaviourPattern/BBPTakeCoverInfantry.h" +#include "../AIKnowledge/BFInformationEnvironment.h" +#include "../AIKnowledge/DangerObject.h" +#include "../AIKnowledge/IPICover.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIPlanInterpreter/VehicleControlInline.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/AIMain.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IAIPathfinding.h" +#include "../AIStrategic/SAI.h" +#include "../AIStrategicEntity/AIStrategicArea.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" +#include "../AIStrategicEntity/CoverPosition/CoverPositionManager.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../../../../Math/BoundingBox.h" +#include "../../../../Math/LocalBoundingBox.h" +#include "../../../../Core/Debug.h" + +#include "../../../../Math/Vec3.h" + +#include +#include +#include +#include +// static init: ELF 0x2247B0, 0x2248A0, 0x2248D0: iostream Init and four direction vectors. + +namespace dice { +namespace hfe { +namespace ai { +namespace { +const Vec3 north = {0.0f, 0.0f, 1.0f}; +const Vec3 east = {1.0f, 0.0f, 0.0f}; +const Vec3 northEast = {0.707106769f, 0.0f, 0.707106769f}; +const Vec3 southEast = {0.707106769f, 0.0f, -0.707106769f}; + +// ELF 0x220C70. +void computeQuadrants(int& first, int& second, const Vec3& position, const Vec3& target) +{ + const Vec3 delta = {target.x - position.x, target.y - position.y, target.z - position.z}; + const float ne = delta.x * northEast.x + delta.y * northEast.y + delta.z * northEast.z; + const float se = delta.x * southEast.x + delta.y * southEast.y + delta.z * southEast.z; + first = ne < 0.0f ? (se < 0.0f ? 3 : 1) : (!(se < 0.0f) ? 2 : 0); + second = delta.z < 0.0f ? (!(delta.x < 0.0f) ? 6 : 5) : (delta.x < 0.0f ? 7 : 4); +} + +// ELF 0x220D80: the direction is not normalized here. +int closestQuadFromDirection(Vec3 direction) +{ + direction.y = 0.0f; + const Vec3 candidates[] = {north, {0.0f, 0.0f, -1.0f}, east, {-1.0f, 0.0f, 0.0f}, + northEast, {-0.707106769f, 0.0f, -0.707106769f}, + southEast, {-0.707106769f, 0.0f, 0.707106769f}}; + for (int i = 0; i < 8; ++i) + if (direction.x * candidates[i].x + direction.y * candidates[i].y + + direction.z * candidates[i].z >= 0.906307817f) + return i; + return -1; +} + +// ELF 0x220F70. +Vec3 getQuadRecommendedLookDirection(Information* information, int quadrant) +{ + Vec3 direction = {}; + switch (quadrant) + { + case 0: direction = {-1.0f, 0.0f, 0.0f}; break; + case 1: direction = {1.0f, 0.0f, 0.0f}; break; + case 2: direction = {0.0f, 0.0f, 1.0f}; break; + case 3: direction = {0.0f, 0.0f, -1.0f}; break; + case 4: direction = {-0.707106769f, 0.0f, 0.707106769f}; break; + case 5: direction = {0.707106769f, 0.0f, -0.707106769f}; break; + case 6: direction = {0.707106769f, 0.0f, 0.707106769f}; break; + case 7: direction = {-0.707106769f, 0.0f, -0.707106769f}; break; + default: return direction; + } + const Mat4& transform = information->getTransformation(); + const Vec3 up = {transform.m[4], transform.m[5], transform.m[6]}; + const Vec3 result = {up.y * direction.z - up.z * direction.y, + up.z * direction.x - up.x * direction.z, + up.x * direction.y - up.y * direction.x}; + return result; +} + +// ELF 0x221090. A threatening neighbour still returns the current area's position. +bool getDangerPositionFromSAI(Bot* bot, Vec2& position) +{ + ISAI* const sai = IAIMain::m_instance->getSAI(bot->getSide()); + const int current = sai->getBotCurrentPos(static_cast(bot->getBotId())); + AIStrategicObject* const object = AIStrategicObjectManager::getInstance()->getStrategicObject(current); + if (!object || object->getType() != 0) + return false; + AIStrategicArea* const area = static_cast(object); + const int status = static_cast(area->getStatus(bot->getSide())); + if (status == 1 || status == 2) + { + position = area->getPosition(bot->getSide()); + return true; + } + if (status != 0) + return false; + for (auto it = area->m_neighbouringObjects.begin(); it != area->m_neighbouringObjects.end(); ++it) + { + AIStrategicObject* const neighbour = *it; + if (neighbour && neighbour->getType() == 0) + { + const int neighbourStatus = static_cast(neighbour->getStatus(bot->getSide())); + if (neighbourStatus == 1 || neighbourStatus == 2) + { + // shipped defect: this is the current area, not the threatening neighbour. + position = area->getPosition(bot->getSide()); + return true; + } + } + } + return false; +} + +// [INFERRED] local packaging of repeated inline clamps; unordered input is retained. +float clampCoverWeight(float value) +{ + if (value < 0.0f) return 0.0f; + if (value > 1.0f) return 1.0f; + return value; +} +} // namespace + +// ELF 0x221230 (C2), 0x2218F0 (C1). +BBTakeCoverInfantry::BBTakeCoverInfantry(unsigned char index, unsigned char queue, PlanGenerator* pattern, + UrgeCurve* curve, float* modifiers) + : BotBehaviour(modifiers, curve, + static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_dangers = checkPointer(new DangerObject*[ + static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); + m_index = index; + m_queue = queue; + m_pattern = pattern; + m_targets = checkPointer(new unsigned int[m_count]); + // shipped defect: the first pointer array is overwritten and leaked. + m_dangers = checkPointer(new DangerObject*[m_count]); + m_fireDangers = checkPointer(new FireDanger[m_count]); + m_infoDangers = checkPointer(new InfoDanger[m_count]); + for (int i = 0; i < m_count; ++i) + { + m_targets[i] = 0xFFFFFFFFu; + m_urgency[i] = 0.0f; + m_dangers[i] = 0; + } +} + +// ELF 0x221FB0 (D2), 0x2220A0 (D1), 0x222190 (D0). +BBTakeCoverInfantry::~BBTakeCoverInfantry() +{ + // shipped defect: selected pointers can point inside the separately owned wrapper arrays. + for (int i = 0; i < m_count; ++i) + ::operator delete(m_dangers[i]); + if (m_targets) delete[] m_targets; + if (m_dangers) delete[] m_dangers; + if (m_fireDangers) delete[] m_fireDangers; + if (m_infoDangers) delete[] m_infoDangers; +} + +// ELF 0x222340 +float BBTakeCoverInfantry::calculateUrgency(Bot* bot, bool evaluate, float /*scale*/) +{ + if (!evaluate) + { + m_targetChanged[bot->getBotId()] = false; + if (m_pattern->isInitiated(bot)) + return m_urgency[bot->getBotId()]; + m_urgency[bot->getBotId()] = 0.0f; + return 0.0f; + } + const int side = bot->getSide(); + const unsigned int id = bot->getBotId(); + InformationManager* const manager = informationManager; + Information* const self = manager->getInformation(bot->getCurrentEquipment()); + IPIPhysical* const physical = self->getPhysical(); + InformationManager* const sectorManager = informationManager; + Information* const sector = sectorManager->getInformation(self->getMobile()->getSector()); + FireDanger fireDangers[8]; + InfoDanger infoDangers[8]; + DangerObject* dangers[8] = {}; + float sums[8] = {}, maxima[8] = {}; + float total = 0.0f; + unsigned int matchedOrders = 0; + const Vec3 selfPosition = self->getPosition(); + const int strengthType = physical->getStrengthType(); + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + const auto* incoming = bot->getIncommingFire(); + m_lastIncomingFireTime = 0.0; + for (auto it = incoming->begin(); it != incoming->end(); ++it) + { + FireObject* const fire = it->first; + int first, second; + computeQuadrants(first, second, selfPosition, fire->getOrigin()); + const float distance = vehiclecontrol::distanceVec3(selfPosition, fire->getTarget()); + const float divisor = distance <= 0.0f ? 0.1f : distance; + const float attenuation = clampCoverWeight(4.0f / divisor); + float strength = fire->getBattleStrength(strengthType) * attenuation * 15.0f; + m_lastIncomingFireTime = fire->getTime(); + if (fire->isDirect()) strength += strength; + sums[first] += strength; + sums[second] += strength; + total += strength; + if (strength > maxima[first]) + { + maxima[first] = strength; + if (!dangers[first]) dangers[first] = &fireDangers[first]; + static_cast(dangers[first])->m_fire = fire; + } + if (strength > maxima[second]) + { + // shipped defect: the second quadrant's maximum is not updated for fire. + if (!dangers[second]) dangers[second] = &fireDangers[second]; + static_cast(dangers[second])->m_fire = fire; + } + } + // [INFERRED] local packaging of the repeated order-list search. + const auto weightOrder = [&](unsigned int handle, float& strength) + { + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() + && matchedOrders < bot->getOrderList(m_index)->size()) + { + const auto comparisonEnd = bot->getOrderList(m_index)->end(); + const auto begin = bot->getOrderList(m_index)->begin(); + const auto searchEnd = bot->getOrderList(m_index)->end(); + if (std::find(begin, searchEnd, handle) != comparisonEnd) + { + ++matchedOrders; + strength *= bot->getMemory()->m_float8; + } + } + }; + const auto& sensed = bot->getSensedObjects(); + for (auto it = sensed.begin(); it != sensed.end(); ++it) + { + SensedObject* const sensedObject = it->second; + const unsigned int handle = sensedObject->m_handle; + Information* const information = informationManager->getInformation(handle); + if (!information || information->getSide() != 0 || !information->getUnit() + || !information->getUnit()->isOccupied()) + continue; + IPIUnit* const unit = information->getUnit(); + WeaponInfo* weapon = 0; + if (information->getArmament()) weapon = information->getArmament()->getLastFiredWeapon(); + int first, second; + computeQuadrants(first, second, selfPosition, information->getPosition()); + const float measured = vehiclecontrol::distanceVec3(selfPosition, information->getPosition()); + const float distance = measured > 2.0f ? measured : 2.0f; + float strength = 0.0f; + if (sensedObject->m_flags & 2) + { + int iterator = information->getFirstSecondaryObjectIterator(); + unsigned int secondary = information->getSecondaryObject(iterator, side); + Information* current = information; + do + { + const float battleStrength = current->getUnit()->getBattleStrengths()[strengthType]; + float part = battleStrength * battleStrength / distance; + // The first contribution is the primary's but uses the first secondary's handle. + weightOrder(secondary, part); + strength += part; + secondary = information->getSecondaryObject(iterator, side); + current = informationManager->getInformation(secondary); + } while (current); + if (sensedObject->m_flags & 8) + { + const double age = now - sensedObject->m_firstSeenTime; + const float fraction = static_cast((age < 30.0 ? age : 30.0) / 30.0); + strength *= (1.0f - fraction) * 0.5f + 0.5f; + } + } + else if (sensedObject->m_flags & 1) + strength = information->getSecurity() * unit->getBattleStrengths()[strengthType] / distance; + if ((sensedObject->m_flags & 3) && weapon) + { + if (distance >= weapon->getMaxRange()) continue; + strength *= 1.0f - SCurve::calculate(distance / weapon->getMaxRange()); + } + if (bot->isOrderedObject(handle, this)) + { + ++matchedOrders; + strength *= bot->getMemory()->m_float8; + } + // shipped defect: both additions target the first quadrant. + sums[first] += strength; + sums[first] += strength; + total += strength; + const int quadrants[] = {first, second}; + for (int q : quadrants) + if (strength > maxima[q]) + { + maxima[q] = strength; + if (!dangers[q] || !dangers[q]->isInformation()) dangers[q] = &infoDangers[q]; + static_cast(dangers[q])->m_information = handle; + } + } + bool changed = true; + unsigned int cover = 0xFFFFFFFFu; + Vec3 coverPosition = {}; + float projection = 0.0f, multiplier; + if (total > 0.0f) + { + DangerObject* strongest = 0; + float maximum = 0.0f; + for (int q = 0; q < 8; ++q) + if (sums[q] > maximum) { maximum = sums[q]; strongest = dangers[q]; } + if (!strongest) { unInit(bot); return 0.0f; } + if (m_dangers[id]) changed = !(*m_dangers[id] == *strongest); + if (strongest->isInformation()) + { + m_dangers[id] = &m_infoDangers[id]; + m_infoDangers[id].m_information = static_cast(strongest)->m_information; + } + else + { + m_dangers[id] = &m_fireDangers[id]; + m_fireDangers[id].m_fire = static_cast(strongest)->m_fire; + } + Information* threat = 0; + DangerObject* const danger = m_dangers[id]; + if (danger->isInformation()) + { + Information* const information = informationManager->getInformation( + static_cast(danger)->m_information); + if (information && information->getMobile()) + threat = informationManager->getInformation(information->getMobile()->getSector()); + } + Vec3 threatPosition = {}; + if (!m_dangers[id]->getPosition(threatPosition) + || !getCoverObject(bot, threatPosition, threat, false, cover, coverPosition, projection, multiplier, false)) + { unInit(bot); return 0.0f; } + } + if (total <= 0.0f) { unInit(bot); return 0.0f; } + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && bot->getOrderList(m_index)->empty()) + total *= bot->getMemory()->m_float8; + m_targetChanged[id] = changed || cover == 0xFFFFFFFFu || cover != m_targets[id]; + m_targets[id] = cover; + DangerObject* const danger = m_dangers[id]; + if (danger->isInformation()) + { + Information* const information = informationManager->getInformation( + static_cast(danger)->m_information); + std::vector ignore; + ignore.push_back(self->getAIObject()); + ignore.push_back(information->getAIObject()); + const bool coarse = bot->getLodLevel() != BotLodFull; + const Vec3& to = information->getPosition(); + const Vec3& from = self->getPosition(); + bool hit; + if (static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->collideLineWithWorld(from, to, ignore, coarse, 1.0f, true, hit)) + { m_urgency[id] = 0.0f; return 0.0f; } + } + if (m_targetChanged[id]) + { + BBPTakeCoverInfantry* const pattern = static_cast(m_pattern); + Vec3 unused = {}; + danger->getPosition(unused); + if (danger->isInformation()) + pattern->init(bot, static_cast(danger)->m_information, coverPosition, m_targets[id]); + else + { + Vec3 threatPosition = {}; + danger->getPosition(threatPosition); + pattern->init(bot, threatPosition, coverPosition, m_targets[id]); + } + m_urgency[id] = total; + if (sector) m_urgency[id] *= 0.5f; + } + else + { + const float x = self->getPosition().x; + const float z = self->getPosition().z; + const float dx = coverPosition.x - x; + const float dz = coverPosition.z - z; + if (dx * dx + dz * dz < 4.0f) + m_urgency[id] = 0.0f; + else + { + const float age = static_cast(now - m_lastIncomingFireTime); + m_urgency[id] *= clampCoverWeight(5.0f / age); + } + } + if (m_urgency[id] < 0.2f) m_urgency[id] = 0.0f; + return m_urgency[id]; +} + +// ELF 0x222290 +void BBTakeCoverInfantry::unInit(Bot* bot) +{ + if (m_pattern->isInitiated(bot)) + { + m_targetChanged[bot->getBotId()] = true; + m_pattern->unInit(bot); + } + // shipped defect: the changed flag just set above is immediately cleared again. + m_targetChanged[bot->getBotId()] = false; + m_urgency[bot->getBotId()] = 0.0f; + m_dangers[bot->getBotId()] = 0; +} + +// ELF 0x223920 +bool BBTakeCoverInfantry::getCoverObject(Bot* bot, const Vec3& threatPosition, Information* threat, + bool unrestricted, unsigned int& cover, Vec3& position, + float& projection, float& multiplier, bool restrictToArea) +{ + InformationManager* const manager = informationManager; + Information* const self = manager->getInformation(bot->getCurrentEquipment()); + IPIMobile* const mobile = self->getMobile(); + LocalBoundingBox* const selfBox = const_cast(self->getPhysical()->getLocalBoundingBox()); + const float selfX = selfBox->getSize().x; + const float selfZ = selfBox->getSize().z; + const float selfWidth = selfZ > selfX ? selfZ : selfX; + const float selfHeight = selfBox->getSize().y; + ISAI* const sai = IAIMain::m_instance->getSAI(bot->getSide()); + AIStrategicObjectManager* const strategic = AIStrategicObjectManager::getInstance(); + AIStrategicObject* const ordered = strategic->getStrategicObject( + sai->getBotOrderedPos(static_cast(bot->getBotId()))); + multiplier = 1.0f; + cover = 0xFFFFFFFFu; + Vec2 coverPosition = {}, from = {}, to = {}; + vec3ToVec2XZ(self->getPosition(), from); + vec3ToVec2XZ(threatPosition, to); + if (CoverPositionManager::m_instance->getClosestAttackCoverPosition(from, to, 30.0f, -1.0f, coverPosition)) + { + vec2ToVec3XZ(coverPosition, position); + cover = 0; + return true; + } + std::vector candidates; + static_cast(AISingletonServer::m_iaiInformationEnvironment) + ->getCover(*bot, candidates); + float best = 0.0f; + for (auto it = candidates.begin(); it != candidates.end(); ++it) + { + Information* const candidate = informationManager->getInformation(*it); + // shipped defect: getName is called before the null check. + candidate->getName(); + if (!candidate || !candidate->getPhysical() || !candidate->getCover()) + continue; + IPIPhysical* const physical = candidate->getPhysical(); + IPICover* const coverInfo = candidate->getCover(); + if (threat && threat->getAIObject() == candidate->getAIObject()) + continue; + const Vec3 candidatePosition = candidate->getPosition(); + const Vec3& selfFirst = self->getPosition(); + const Vec3 towardThreat = {threatPosition.x - selfFirst.x, threatPosition.y - selfFirst.y, + threatPosition.z - selfFirst.z}; + const Vec3& selfSecond = self->getPosition(); + const Vec3 towardCover = {candidatePosition.x - selfSecond.x, candidatePosition.y - selfSecond.y, + candidatePosition.z - selfSecond.z}; + const float threatDistance = std::sqrt(towardThreat.x * towardThreat.x + towardThreat.y * towardThreat.y + + towardThreat.z * towardThreat.z); + const float coverDistance = std::sqrt(towardCover.x * towardCover.x + towardCover.y * towardCover.y + + towardCover.z * towardCover.z); + const float dot = towardThreat.x * towardCover.x + towardThreat.y * towardCover.y + + towardThreat.z * towardCover.z; + if (!unrestricted && dot / coverDistance > threatDistance * 0.5f) + continue; + Vec3 goal = {}; + if (coverInfo->getPortalCount()) + Debug(DebugTypeError, "AI/AIDLL/AI/AIBotBehaviour/BBTakeCoverInfantry.cpp", 1087, "") + << "What portals? They have been removed for BF2."; + coverInfo->getPortalCount(); + Vec3 away = {candidatePosition.x - threatPosition.x, candidatePosition.y - threatPosition.y, + candidatePosition.z - threatPosition.z}; + vehiclecontrol::normalizeVec3(away); + const float nearRadius = physical->getRadius() * 0.75f; + const Vec3 near = vehiclecontrol::alongFrom(candidatePosition, away, nearRadius); + const float farRadius = physical->getRadius() * 2.0f; + const Vec3 far = vehiclecontrol::alongFrom(candidatePosition, away, farRadius); + const int equipmentType = self->getUnit()->getEquipmentType(); + const int vehicle = mobile->getVehicleNumber(); + unsigned int island, polygon; + if (!IAIPathfinding::instance->findClosestValidPolygon(island, polygon, goal, vehicle, + near, far, 10, equipmentType)) + continue; + LocalBoundingBox* const box = const_cast(physical->getLocalBoundingBox()); + const float boxX = box->getSize().x; + const float boxZ = box->getSize().z; + const float width = boxZ > boxX ? boxZ : boxX; + const float height = box->getSize().y; + const float horizontal = clampCoverWeight(width / selfWidth * 0.2f); + const float vertical = clampCoverWeight(height / selfHeight * 0.5f); + const float sizeRating = horizontal * 0.25f + vertical * 0.75f; + float overlap = 1.0f; + if (restrictToArea && ordered) + { + AIStrategicArea* const area = static_cast(ordered); + Vec2 unused = {}; + const Vec2 centre = area->getPosition(bot->getSide()); + const Vec2 maximum = getBoxMaxCorner(area->m_centre, centre, unused); + BoundingBox worldBox = {}; + worldBox.initWithLocalBoundingBox(*box); + worldBox.transform(candidate->getTransformation()); + const Vec3 minimum3 = worldBox.getMin(); + const Vec3 maximum3 = worldBox.getMax(); + const Vec2 minimum2 = {minimum3.x, minimum3.z}; + const Vec2 maximum2 = {maximum3.x, maximum3.z}; + Vec2 intersectionMin = {}, intersectionMax = {}; + overlap = ::dice::hfe::getBoxIntersections(area->m_centre, maximum, minimum2, maximum2, + intersectionMin, intersectionMax) ? 1.0f : 0.0f; + } + const Vec3& selfThird = self->getPosition(); + const Vec3& candidateAgain = candidate->getPosition(); + const float distance = vehiclecontrol::distanceVec3(candidateAgain, selfThird); + float rating = coverInfo->getCoverValue() * sizeRating / distance * overlap; + if (bot->isOrderedObject(*it, this)) + rating *= bot->getMemory()->m_float8; + if (rating > best) + { + best = rating; + cover = *it; + position = goal; + projection = dot; + multiplier *= 1.3f; + } + else if (rating > 0.0f) + multiplier *= rating / best * 0.3f + 1.0f; + } + return cover != 0xFFFFFFFFu; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCoverInfantry.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCoverInfantry.h new file mode 100644 index 000000000..c0fa1fb17 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCoverInfantry.h @@ -0,0 +1,47 @@ +// Rates infantry cover against incoming shots and sensed occupied objects. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBTAKECOVERINFANTRY_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBTAKECOVERINFANTRY_H + +#include "../../../../Math/Vec3.h" +#include "BotBehaviour.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class Information; +class PlanGenerator; +class UrgeCurve; +class DangerObject; +class FireDanger; +class InfoDanger; + +// ELF: vtable 0x4BB480 (13 words), operator new 0x3C, package H-deferred. +class BBTakeCoverInfantry : public BotBehaviour +{ +public: + BBTakeCoverInfantry(unsigned char, unsigned char, PlanGenerator*, UrgeCurve*, float*); // 0x2218F0 + virtual ~BBTakeCoverInfantry(); // 0x2220A0 + + virtual float calculateUrgency(Bot*, bool, float); // 0x222340, slot +0x28; from the base declaration + + void unInit(Bot*); // 0x222290; [INFERRED] ELF void + bool getCoverObject(Bot*, const Vec3&, Information*, bool, unsigned int&, Vec3&, float&, float&, bool); // 0x223920; [INFERRED] ELF int, callers {'bool': 1} + +private: + // [INFERRED] names; constructors and urgency bookkeeping establish the array types. + /* +0x24 */ int m_count; + /* +0x28 */ DangerObject** m_dangers; + /* +0x2C */ FireDanger* m_fireDangers; + /* +0x30 */ InfoDanger* m_infoDangers; + /* +0x34 */ double m_lastIncomingFireTime; // shared by all bots, not initialized by construction +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBTAKECOVERINFANTRY_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTriggerable.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTriggerable.cpp new file mode 100644 index 000000000..21fc47db8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTriggerable.cpp @@ -0,0 +1,121 @@ +// Triggerable behaviour (infantry "Triggerable" slot of aibehaviours.ai): a man-down bot is the +// only one it applies to; its urgency is always 0 here, so it is never chosen by urgency alone. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see +// docs/macos-ai-behaviour-plan.md. + +#include "BBTriggerable.h" + +// static init: ELF 0x224F30, 0x2250A0, 0x2250D0, 0x225140 (iostream Init, colors, triggerables). +#include + +#include "../AIBot/BotMain.h" +#include "../AIBotBehaviourPattern/PlanGenerator.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace world { +namespace { + +// [CHOSEN, not recovered] Type, component names and constructor spelling for the +// three-float elements stored by ELF 0x224F30. No original type name is attested. +struct DebugMeshMaterialColor +{ + float r, g, b; + + DebugMeshMaterialColor(float red, float green, float blue) : r(red), g(green), b(blue) {} +}; + +static_assert(sizeof(DebugMeshMaterialColor) == 12, "color element stride"); +static_assert(offsetof(DebugMeshMaterialColor, r) == 0 && + offsetof(DebugMeshMaterialColor, g) == 4 && + offsetof(DebugMeshMaterialColor, b) == 8, "color component offsets"); +static_assert(std::is_trivially_destructible::value, + "the color table has no registered teardown"); + +} // anonymous namespace + +// ELF 0x4CE3E0, a separate local table. __tcf_1 destroys only the triggerables map. +// [CHOSEN, not recovered] Retain the unreferenced retail object with modern compilers. +#if defined(__GNUC__) +__attribute__((used)) +#endif +static DebugMeshMaterialColor debugMeshMaterialColors[10] = { + {0.66f, 0.66f, 0.185f}, + {0.185f, 0.66f, 0.185f}, + {0.185f, 0.185f, 0.66f}, + {0.185f, 0.66f, 0.66f}, + {0.66f, 0.185f, 0.185f}, + {0.66f, 0.66f, 0.66f}, + {0.66f, 0.185f, 0.66f}, + {0.185f, 0.185f, 0.185f}, + {1.0f, 1.0f, 1.0f}, + {0.0f, 0.0f, 0.0f} +}; +static_assert(sizeof(debugMeshMaterialColors) == 0x78, "local color table extent"); + +} // namespace world +namespace ai { + +// ELF 0x224F30 constructs this map after the colors; __tcf_1 ELF 0x2250D0 destroys +// its nodes and sentinel, without deleting the stored Triggerable pointers. +std::map BBTriggerable::m_triggerables; + +// ELF 0x2248F0 (C2) / 0x224AF0 (C1). The base gets getMaxNBots (IAISettings slot 0) as its +// per-bot count, then a second getMaxNBots sizes the +0x08 array (checkPointer'd, not +// initialised) and every base urgency (+0x10) is set to 0.0f (rodata 0x49CB34). +BBTriggerable::BBTriggerable(unsigned char index, unsigned char queue, PlanGenerator* pattern, UrgeCurve* curve, + float* modifiers) + : BotBehaviour(modifiers, curve, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_targets = checkPointer(new unsigned int[count]); + for (int i = 0; i < count; ++i) + m_urgency[i] = 0.0f; + m_unknown24 = 0; +} + +// ELF 0x224CF0 (D2) / 0x224D40 (D1) / 0x224D90 (D0): delete[] +0x08 when set, then the base. +BBTriggerable::~BBTriggerable() +{ + if (m_targets) + delete[] m_targets; +} + +// ELF 0x224DE0: m_urgency[bot->getBotId()] = 0.0f, return it (flds of the same slot). +float BBTriggerable::calculateUrgency(Bot* bot, bool, float) +{ + m_urgency[bot->getBotId()] = 0.0f; + return m_urgency[bot->getBotId()]; +} + +// ELF 0x224E40: bot->getPlayer() (+0xBC) ->getIsAlive() (+0x24); alive bots answer getManDown (+0x1B0). +bool BBTriggerable::isApplicable(Information*, Bot* bot) +{ + if (!bot->getPlayer()->getIsAlive()) + return false; + return bot->getManDown(); +} + +// ELF 0x224E80: drops the bot's entry from m_triggerables (find + erase), then the pattern +// (+0x0C) unInit(bot) through PlanGenerator slot +0x10. +void BBTriggerable::unInitialise(Bot* bot) +{ + std::map::iterator it = m_triggerables.find(bot->getBotId()); + if (it != m_triggerables.end()) + m_triggerables.erase(it); + m_pattern->unInit(bot); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTriggerable.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTriggerable.h new file mode 100644 index 000000000..fc2863290 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTriggerable.h @@ -0,0 +1,50 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBTRIGGERABLE_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBTRIGGERABLE_H + +#include "BotBehaviour.h" + +#include + +namespace dice { +namespace hfe { + +namespace world { class Triggerable; } + +namespace ai { + +class Bot; +class Information; +class PlanGenerator; +class UrgeCurve; + +// ELF: vtable 0x4BB520 (14 words), operator new 0x28, package F-infantry. +class BBTriggerable : public BotBehaviour +{ +public: + BBTriggerable(unsigned char, unsigned char, PlanGenerator*, UrgeCurve*, float*); // 0x224AF0 + virtual ~BBTriggerable(); // 0x224D40 + + virtual float calculateUrgency(Bot*, bool, float); // 0x224DE0, slot +0x28; from the base declaration + virtual bool isApplicable(Information*, Bot*); // 0x224E40, slot +0x34; bool: returns Bot::getManDown or 0 + + void unInitialise(Bot*); // 0x224E80; ELF void (no result register is set) + + // The triggerable each bot works on, keyed by Bot::getBotId (ELF 0x4CE3C0, B; static + // initialiser 0x225140 is _GLOBAL__I__ZN4dice3hfe2ai13BBTriggerable14m_triggerablesE). + static std::map m_triggerables; + +private: + /* +0x24 */ unsigned int m_unknown24; // = 0 in the constructor; no other F.1 reader [UNRESOLVED] +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBTRIGGERABLE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.cpp new file mode 100644 index 000000000..06122c76e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.cpp @@ -0,0 +1,170 @@ +// BotBehaviour: recovered by package A-core from libaidll.so (TU BotBehaviour.cpp, 0x225250..0x2260D0; +// the two weak members sit at 0x1FD160). Every body carries its ELF address. + +// static init: ELF 0x226040 (__tcf_0 0x2260A0, _GLOBAL__I 0x2260D0): 's Init object only. +#include + +#include "BotBehaviour.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SensingAgent.h" +#include "../AIBotBehaviourPattern/PlanGenerator.h" +#include "../AIBotActionPlan/BotScript.h" +#include "../AIUtils/checkPointer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x225250 (C2; C1 0x225610). Three checkPointer'd arrays, then the init loop. The urgency array +// is not initialised here; reset() and the derived calculateUrgency write it. +BotBehaviour::BotBehaviour(float* modifiers, UrgeCurve* urgeCurve, int count) + : m_targets(0) + , m_pattern(0) +{ + m_urgency = checkPointer(new float[count]); + m_modifiers = modifiers; + m_targetChanged = checkPointer(new bool[count]); + m_activeUrgency = checkPointer(new float[count]); + m_urgeCurve = urgeCurve; + for (int i = 0; i < count; ++i) + { + m_activeUrgency[i] = 1e-5f; // rodata 0x49D588 + m_targetChanged[i] = true; + } +} + +// ELF 0x2259D0 (C2; C1 0x225A20). No arrays. +BotBehaviour::BotBehaviour(float* modifiers, UrgeCurve* urgeCurve) + : m_targets(0) + , m_pattern(0) + , m_urgency(0) + , m_modifiers(modifiers) + , m_targetChanged(0) + , m_activeUrgency(0) + , m_urgeCurve(urgeCurve) +{ +} + +// ELF 0x225A70 (D2; D1 0x225B00, D0 0x225B90). The pattern is owned (deleting destructor, slot +4); +// the modifier row, the curve and m_targets are not freed here. +BotBehaviour::~BotBehaviour() +{ + delete[] m_urgency; + delete[] m_targetChanged; + delete[] m_activeUrgency; + delete m_pattern; +} + +// ELF 0x225D70. +float BotBehaviour::getUrgency(Bot* bot) +{ + return m_urgency[bot->getBotId()]; +} + +// ELF 0x225DA0. +float BotBehaviour::getActiveUrgency(Bot* bot) +{ + return m_activeUrgency[bot->getBotId()]; +} + +// ELF 0x225DD0: the current urgency becomes the active one and is returned (fsts). +float BotBehaviour::updateActiveUrgency(Bot* bot) +{ + return m_activeUrgency[bot->getBotId()] = m_urgency[bot->getBotId()]; +} + +// ELF 0x225E20. +bool BotBehaviour::hasChangedTarget(Bot* bot) +{ + return m_targetChanged[bot->getBotId()]; +} + +// ELF 0x225E50. With no active urgency: changed when the new one is positive. With a zero new +// urgency: changed. Otherwise the ratio new/active (`fdivp %st,%st(1)` = de f1, st(1) = st(0)/st(1) +// with st(0) = urgency) must lie inside [low, high]. The comparisons are the unordered-false +// forms of the image (ja / jbe after fucomip). +bool BotBehaviour::quotientChanged(Bot* bot, float low, float high) +{ + if (m_activeUrgency[bot->getBotId()] == 0.0f) + return m_urgency[bot->getBotId()] > 0.0f; + + if (m_urgency[bot->getBotId()] == 0.0f) + return true; + + const float quotient = m_urgency[bot->getBotId()] / m_activeUrgency[bot->getBotId()]; + return low > quotient || quotient > high; +} + +// ELF 0x225F30: both through the vtable (+0x14, +0x18). +bool BotBehaviour::hasChanged(Bot* bot, float low, float high) +{ + return hasChangedTarget(bot) && quotientChanged(bot, low, high); +} + +// ELF 0x1FD160 (weak). +UrgencyGenerator* BotBehaviour::getChosenGenerator() +{ + return this; +} + +// ELF 0x225F90. Note the 1e-4f here against the constructor's 1e-5f (rodata 0x49D578 / 0x49D588). +void BotBehaviour::reset(Bot* bot) +{ + if (m_pattern) + m_pattern->unInit(bot); + m_urgency[bot->getBotId()] = 0.0f; + m_activeUrgency[bot->getBotId()] = 1e-4f; + m_targetChanged[bot->getBotId()] = true; + if (m_targets) + m_targets[bot->getBotId()] = 0xFFFFFFFFu; +} + +// ELF 0x225C30 (105 instructions). +// * A locked plan (Bot +0x68) is kept: the current plan (+0x60) is returned. +// * An initiated pattern builds a new plan. The old plan is first re-owned by the pattern, the new +// one by this behaviour; when a different old plan exists it is re-owned by this behaviour too +// and the sensing agent is told something new was sensed (SensingAgent +0x78 = 1). +// The new plan is returned (the caller replaces and frees the old one). +// * A pattern that is not initiated: the current plan is deleted (slot +8), the plan is cleared +// (+0x64) and 0 is returned. +BotScript* BotBehaviour::generatePlan(Bot* bot) +{ + if (bot->getPlanLock()) + return bot->getPlan(); + + if (!m_pattern->isInitiated(bot)) + { + if (bot->getPlan() != 0) + { + delete bot->getPlan(); + bot->setPlan(0); + } + return 0; + } + + if (bot->getPlan() != 0) + bot->getPlan()->mpOwner = m_pattern; + + BotScript* plan = m_pattern->createPlan(bot); + if (plan != 0) + { + plan->mpOwner = this; + if (bot->getPlan() != 0 && bot->getPlan() != plan) + { + bot->getPlan()->mpOwner = this; + bot->getSensingAgent()->setSensedNewObject(); + } + } + return plan; +} + +// ELF 0x1FD170 (weak). +bool BotBehaviour::isAplicable(Information*, Bot*) +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.h new file mode 100644 index 000000000..133a91324 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.h @@ -0,0 +1,80 @@ +// Behaviour base: per-bot urgency bookkeeping and plan generation through the behaviour's pattern. +// Recovered by package A-core (docs/macos-ai-behaviour-plan.md) from libaidll.so; the virtual order +// is checked by tools/macos/ai_behaviour_vtables.py. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BOTBEHAVIOUR_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BOTBEHAVIOUR_H + +#include "../AIBot/UrgencyMerger.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; +class PlanGenerator; +class Information; +class UrgeCurve; +class UrgencyGenerator; + +// Behaviour base. Vtable 0x4BB580 (13 words). One object per vehicle type and behaviour (built at +// map load by BotBehaviourManager), shared by every bot of that vehicle: the per-bot state is in +// arrays indexed by Bot::getBotId() (+0xE8). +// ELF: vtable 0x4BB580 (13 words), package A-core. +class BotBehaviour : public UrgencyGenerator +{ +public: + BotBehaviour(float*, UrgeCurve*, int); // 0x225610 + BotBehaviour(float*, UrgeCurve*); // 0x225A20 + virtual ~BotBehaviour(); // 0x225B00 + + virtual float getUrgency(Bot*); // 0x225D70, slot +0x08; from the base declaration + virtual float getActiveUrgency(Bot*); // 0x225DA0, slot +0x0C; from the base declaration + virtual float updateActiveUrgency(Bot*); // 0x225DD0, slot +0x10; from the base declaration + virtual bool hasChangedTarget(Bot*); // 0x225E20, slot +0x14; from the base declaration + virtual bool quotientChanged(Bot*, float, float); // 0x225E50, slot +0x18; from the base declaration + virtual bool hasChanged(Bot*, float, float); // 0x225F30, slot +0x1C; from the base declaration + virtual UrgencyGenerator* getChosenGenerator(); // 0x1FD160, slot +0x20; from the base declaration + virtual void reset(Bot*); // 0x225F90, slot +0x24; from the base declaration + virtual float calculateUrgency(Bot*, bool, float) = 0; // no body, slot +0x28; from the base declaration + virtual BotScript* generatePlan(Bot*); // 0x225C30, slot +0x2C; from the base declaration + virtual bool isAplicable(Information*, Bot*); // 0x1FD170, slot +0x30; from the base declaration + + // BotMain::decisionMaking (0x1893D0) reads +4, +5 and +0x14 inline; the image has no accessor. + // [CHOSEN, not recovered] inline getters so AIBot needs no friend access. + unsigned char getIndex() const { return m_index; } + unsigned char getQueueGroup() const { return m_queue; } + float* getModifiers() const { return m_modifiers; } + // [INFERRED] inline reader of +0x0C for BotMain::updateBot (ELF 0x18BF50 reads it inline). + PlanGenerator* getPattern() const { return m_pattern; } + // [INFERRED] inline reader of +0x20 for BotMemory::modifyBehaviourUrgency (ELF 0x18F2F8 reads it inline). + UrgeCurve* getUrgeCurve() const { return m_urgeCurve; } + +protected: + // BotBehaviour(float*, UrgeCurve*, int count) 0x225250: +8 = +0xC = 0, the three arrays of + // `count` (checkPointer each), activeUrgency[i] = 1e-5f, targetChanged[i] = true; urgency[] is + // left uninitialised. BotBehaviour(float*, UrgeCurve*) 0x2259D0: all three arrays 0. + // +0x04/+0x05 are bytes the BB* constructors store (behaviour index, queue group) [INFERRED]. + /* +0x04 */ unsigned char m_index; + /* +0x05 */ unsigned char m_queue; + // +0x08: per-bot handle array that only some behaviours allocate (BBTriggerable); reset 0x22601E + // writes 0xFFFFFFFF when present. [INFERRED] name and element type. + /* +0x08 */ unsigned int* m_targets; + // +0x0C: the behaviour's pattern (BBCreateFunction passes `new BBP(id)`), owned: the + // destructor deletes it (0x225AC6). generatePlan calls isInitiated (+0xC) and createPlan (+8), + // reset calls unInit (+0x10). + /* +0x0C */ PlanGenerator* m_pattern; + /* +0x10 */ float* m_urgency; // [bot]: getUrgency 0x225D70 + /* +0x14 */ float* m_modifiers; // constructor argument 1 (the behaviour-modifier row), not owned + /* +0x18 */ bool* m_targetChanged; // [bot]: hasChangedTarget 0x225E20 returns it [INFERRED] name + /* +0x1C */ float* m_activeUrgency; // [bot]: updateActiveUrgency 0x225DD0 copies urgency into it + /* +0x20 */ UrgeCurve* m_urgeCurve; // constructor argument 2, not owned +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BOTBEHAVIOUR_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/CustomCurve.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/CustomCurve.h deleted file mode 100644 index b33ed43e5..000000000 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/CustomCurve.h +++ /dev/null @@ -1,48 +0,0 @@ -// Samples a supplied curve function into a table for later evaluation. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. -// [INFERRED] Source placement. - -#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_CUSTOMCURVE_H // [INFERRED] guard style -#define AI_AIDLL_AI_AIBOTBEHAVIOUR_CUSTOMCURVE_H - -namespace dice { -namespace hfe { -namespace ai { - -// Static curve table with no per-instance state. Construction initializes the shared -// table and destruction releases it. -class SCurve -{ -public: - SCurve(); // - calls init, nothing else - ~SCurve(); - static void init(); - static float calculate(float x); // - the only one with a NaN guard - static float* curveValues; -}; - -class JCurve -{ -public: - JCurve(); - ~JCurve(); - static void init(); - static float calculate(float x); // - extrapolates above 1 - static float* curveValues; -}; - -class DecleiningSlopeCurve // dice's spelling -{ -public: - DecleiningSlopeCurve(); - ~DecleiningSlopeCurve(); - static void init(); - static float calculate(float x); - static float* curveValues; -}; - -} // namespace ai -} // namespace hfe -} // namespace dice - -#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_CUSTOMCURVE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/UrgeCurve.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/UrgeCurve.cpp index 443ab2095..028364e51 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/UrgeCurve.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/UrgeCurve.cpp @@ -1,6 +1,10 @@ // [INFERRED] Source placement. #include "UrgeCurve.h" +#include +// Original UCLinear.cpp and UCXInverse.cpp are combined here; both only initialized iostreams. +// static init: ELF 0x226350, 0x2263B0, 0x2263E0 +// static init: ELF 0x226530, 0x226590, 0x2265C0 #include // std::max - see the argument-order note in the header diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/UrgencyMerger.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/UrgencyMerger.cpp deleted file mode 100644 index 50b9a8cc3..000000000 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/UrgencyMerger.cpp +++ /dev/null @@ -1,86 +0,0 @@ -// [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining UrgencyMerger operations. - -#include "UrgencyMerger.h" - -#include "../Main/AIDllFrontier.h" - -namespace dice { -namespace hfe { -namespace ai { - -// one instruction in the binary - the vptr store C++ emits on its own. The class owns nothing -// which is what makes it a pure interface rather than a partial implementation. -UrgencyGenerator::~UrgencyGenerator() -{ -} - -// Four stores after the vptr. `m_weights` is whatever the caller passed and BotManager passes -// null, so a merger from the bot pool has no weight array at all - whatever `getUrgency` does with -// that is the next thing to read, and it is not guessed at here. -UrgencyMerger::UrgencyMerger(int count, float* weights, UrgencyGenerator** generators) - : m_count(count) - , m_weights(weights) - , m_generators(generators) - , m_chosen(0) -{ -} - -UrgencyMerger::~UrgencyMerger() -{ - BF2_AI_FRONTIER("dice::hfe::ai::UrgencyMerger::~UrgencyMerger"); -} - -// [FRONTIER] Bot-specific urgency and modifier operations remain unimplemented. -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -// Replace each stop when the corresponding merger behavior is recovered. - -float UrgencyMerger::getUrgency(Bot*) -{ - BF2_AI_FRONTIER("dice::hfe::ai::UrgencyMerger::getUrgency"); -} - -float UrgencyMerger::getActiveUrgency(Bot*) -{ - BF2_AI_FRONTIER("dice::hfe::ai::UrgencyMerger::getActiveUrgency"); -} - -void UrgencyMerger::updateActiveUrgency(Bot*) -{ - BF2_AI_FRONTIER("dice::hfe::ai::UrgencyMerger::updateActiveUrgency"); -} - -bool UrgencyMerger::hasChangedTarget(Bot*) -{ - BF2_AI_FRONTIER("dice::hfe::ai::UrgencyMerger::hasChangedTarget"); -} - -bool UrgencyMerger::quotientChanged(Bot*, float, float) -{ - BF2_AI_FRONTIER("dice::hfe::ai::UrgencyMerger::quotientChanged"); -} - -bool UrgencyMerger::hasChanged(Bot*, float, float) -{ - BF2_AI_FRONTIER("dice::hfe::ai::UrgencyMerger::hasChanged"); -} - -UrgencyGenerator* UrgencyMerger::getChosenGenerator() -{ - BF2_AI_FRONTIER("dice::hfe::ai::UrgencyMerger::getChosenGenerator"); -} - -void UrgencyMerger::reset(Bot*) -{ - BF2_AI_FRONTIER("dice::hfe::ai::UrgencyMerger::reset"); -} - -int UrgencyMerger::getSize() -{ - BF2_AI_FRONTIER("dice::hfe::ai::UrgencyMerger::getSize"); -} - -} // namespace ai -} // namespace hfe -} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/VehicleUrgencyCalculator.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/VehicleUrgencyCalculator.cpp new file mode 100644 index 000000000..dad79df7b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/VehicleUrgencyCalculator.cpp @@ -0,0 +1,679 @@ +// VehicleUrgencyCalculator: libaidll.so TU VehicleUrgencyCalculator.cpp (0x2265E0..0x228EF0), the +// vehicle scoring behind BBChange (which vehicle / seat a bot should take). Recovered by ai-bot +// (coordinator assignment 2026-11-01) from the ELF bodies; the strength rows are IPIUnit +8 +// (getBattleStrengths), indexed by the IPIPhysical strength type (vtable +0x44). + +// static init: ELF 0x228E60 (__tcf_0 0x228EC0, _GLOBAL__I 0x228EF0): 's Init object only. +#include + +#include "VehicleUrgencyCalculator.h" + +#include +#include +#include +#include +#include + +#include "../AIBot/BotMain.h" +#include "../AIBot/SensedObject.h" +#include "../AIBot/SquadCoordinator.h" +#include "../AIBot/SquadMember.h" +#include "../AIKnowledge/BFInformationEnvironment.h" +#include "../AIKnowledge/FireObject.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../AIStrategic/SAI.h" +#include "../AIStrategicEntity/AIStrategicArea.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" +#include "../Main/AIMain.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IBotManager.h" +#include "../../../AIInterface/BFKnowledge/AIObjectUnit.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/BFGame.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +const int kMaxStrengths = 64; // [CHOSEN] stack row size (the image's frame holds 15 / 83 floats) + +Information* infoOf(unsigned int handle) +{ + return informationManager->getInformation(handle); +} + +int strengthCount() +{ + return static_cast(CommonSingletonServer::m_iaiSettings)->getNBattleStrengths(); +} + +// The bot's soldier's information for `side` (Bot +0xBC getPlayer, IAIPlayer +0x4C getSoldier, +// IAIObject +0xB8 getInformation). +Information* soldierInfo(Bot* bot, int side) +{ + return infoOf(bot->getPlayer()->getSoldier()->getInformation(side)); +} + +// The inline Vec3 normalisation: unchanged within FLT_EPSILON of unit length; false (left as is) +// within FLT_EPSILON of zero, where the image skips the camera test. +bool normalise(Vec3& v) +{ + const float lengthSq = v.x * v.x + v.y * v.y + v.z * v.z; + if (std::fabs(lengthSq - 1.0f) < 1.1920929e-07f) + return true; + if (std::fabs(lengthSq) < 1.1920929e-07f) + return false; + const float inverse = 1.0f / std::sqrt(lengthSq); + v.x = v.x * inverse; + v.y = v.y * inverse; + v.z = inverse * v.z; + return true; +} + +// The armament's weapon range envelope: max of the maximum ranges (from 50), min of the minimum +// ranges (from 0.1); `guided` when any weapon has a guidance type. +void weaponRanges(IPIArmament* armament, float& maxRange, float& minRange, bool* guided) +{ + std::vector& weapons = armament->getWeapons(); + for (unsigned int i = 0; i < weapons.size(); ++i) + { + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (!weapon) + continue; + if (guided && weapon->getWeaponGuidanceType() != 0) + *guided = true; + const float maxR = weapon->getMaxRange(); + const float minR = weapon->getMinRange(); + if (maxRange < maxR) + maxRange = maxR; + if (minR < minRange) + minRange = minR; + } +} + +// The occupied seats' fire strength added to `strengths`: 0.4 of the primary object's row when it +// is occupied, plus `share` (0.4; 0.9 for an unarmed primary) of every occupied secondary's row. +// Inline in calculateVehicleFireUrgency and calculateFireStrength. +void addSeatStrengths(float* strengths, int n, Information* vehicle, int side, bool flag, + Information* current) +{ + Information* primary; + float share = 0.4f; + if (!vehicle->isPrimary()) + { + primary = infoOf(vehicle->getPrimaryObject(side)); + IPIUnit* const unit = primary->getUnit(); + if ((primary != current || !flag) && unit->isOccupied()) + { + for (int i = 0; i < n; ++i) + strengths[i] = unit->getBattleStrengths()[i] * 0.4f + strengths[i]; + } + } + else + { + primary = vehicle; + if (!vehicle->hasArmament()) + share = 0.9f; + } + int iterator; + Information* secondary = infoOf(primary->getFirstSecondaryObject(iterator, side)); + while (secondary) + { + if (secondary != vehicle) + { + IPIUnit* const unit = secondary->getUnit(); + if ((secondary != current || !flag) && unit->isOccupied()) + { + for (int i = 0; i < n; ++i) + strengths[i] = share * unit->getBattleStrengths()[i] + strengths[i]; + } + } + secondary = infoOf(primary->getSecondaryObject(iterator, side)); + } +} + +bool closeAndShouldAvoidVehiclesImpl(Information* vehicle, int side, Bot* bot); + +// [CHOSEN, not recovered] No GNU unused attribute: these external helpers also compile on MSVC. +// ELF 0x226C90 (no caller in the image): sum over six components of a*b (b where a is 0), x0.25. +float sqrDistance(const float* a, const float* b) +{ + float sum = 0.0f; + for (int i = 0; i < 6; ++i) + sum = sum + (a[i] != 0.0f ? a[i] * b[i] : b[i]); + return sum * 0.25f; +} + +// ELF 0x226CF0 (no caller in the image): 1 / the (larger, when `both`) strength, capped at 10. +float vulnerability(const float* strengths, int type, bool both, int other) +{ + float s = strengths[type]; + if (both && !(strengths[other] <= strengths[type])) + s = strengths[other]; + if (s == 0.0f) + return 10.0f; + const float inverse = 1.0f / s; + return 10.0f < inverse ? 10.0f : inverse; +} + +// ELF 0x226D60 (no caller in the image): the squared strongest seat strength against an enemy +// type with weight > 0, minus the enemy's strength against the vehicle (and its exposed soldier). +float calculateVehicleFireUrgency(Bot* bot, Information* vehicle, + const float* enemyStrengths, const float* weights, + int, bool flag, Information* current, int side) +{ + const int n = strengthCount(); + IPIUnit* const unit = vehicle->getUnit(); + const int ownType = vehicle->getPhysical()->getStrengthType(); + const bool exposed = unit->hasExposedSoldier(); + if (closeAndShouldAvoidVehiclesImpl(vehicle, side, bot)) + return 0.0f; + int soldierType = 0; + if (exposed) + soldierType = soldierInfo(bot, side)->getPhysical()->getStrengthType(); + const bool usable = vehicle != current || !flag; + float strengths[kMaxStrengths]; + for (int i = 0; i < n; ++i) + strengths[i] = usable ? unit->getBattleStrengths()[i] : 0.0f; + addSeatStrengths(strengths, n, vehicle, side, flag, current); + float best = 0.0f; + for (int i = 0; i < n; ++i) + { + if (0.0f < weights[i]) + { + const float sq = strengths[i] * strengths[i]; + if (best < sq) + best = sq; + } + } + if (!exposed) + return best - enemyStrengths[ownType]; + const float threat = enemyStrengths[soldierType] <= enemyStrengths[ownType] ? enemyStrengths[ownType] + : enemyStrengths[soldierType]; + return best - threat; +} + +// ELF 0x227150. Vehicles the bot should avoid are worth nothing. A primary mobile vehicle: max +// speed x5. A seat of a mobile primary: an empty primary is worth x4 faded over the 15 s after a +// player of this side last possessed it (0 otherwise); a primary a bot drives x2.5 when that bot +// is ordered elsewhere than this one (SAI +0xB8 getBotOrderedPos), else x4. +float calculateVehicleMoveUrgency(Information* vehicle, int side, Bot* bot, bool flag, Information* current) +{ + if (closeAndShouldAvoidVehiclesImpl(vehicle, side, bot)) + return 0.0f; + const unsigned int botId = bot->getBotId(); + if (!vehicle->isPrimary()) + { + Information* const primary = infoOf(vehicle->getPrimaryObject(side)); + IPIMobile* const mobile = primary->getMobile(); + if (mobile && (primary != current || !flag)) + { + IPIUnit* const unit = primary->getUnit(); + if (!unit->isOccupied()) + { + float urgency = 0.0f; + if (primary->getSide() == side) + { + const double now = + static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + const double since = now - unit->getLastPlayerPossesionTime(); + if (since < 15.0) + urgency = (1.0f - static_cast(since / 15.0)) * (mobile->getMaxSpeed() * 4.0f); + } + return urgency; + } + Bot* const driver = IBotManager::instance->getBot(primary->getAIObject()); + SAI* const sai = IAIMain::m_instance->getSAI(side); + if (driver) + { + const int mine = sai->getBotOrderedPos(botId); + if (mine != sai->getBotOrderedPos(driver->getBotId())) + return mobile->getMaxSpeed() * 2.5f; + } + return mobile->getMaxSpeed() * 4.0f; + } + } + else if (vehicle->getMobile()) + { + return vehicle->getMobile()->getMaxSpeed() * 5.0f; + } + return 0.0f; +} + +// ELF 0x2273B0 (1814 instructions). The fire value of taking `vehicle`: +// * a static emplacement without guided or anti-aircraft weapons is worth nothing beyond 12 m / 2 m +// of height of the current equipment; +// * with sensed objects: the best sided target (static: within weapon range, not an indirect sighting +// younger than 20 s) the seat out-guns the current equipment against, s^2 minus the target's +// strength against the vehicle; x4 unless the vehicle should be avoided; no target engaged in a +// driven vehicle falls back to the raw value; +// * nothing sensed, undriven: the best enemy object in weapon range (validity test as above); no +// enemy at all: 0 unless no neighbouring area of the bot's ordered area is in camera reach; +// * the raw value (fallback): the best weighted row strength minus the threat. +float calculateFireStrength(Bot* bot, Information* vehicle, int side, const float* enemyStrengths, + const float* weights, bool flag, Information* current) +{ + const std::map& sensed = bot->getSensedObjects(); + const int n = strengthCount(); + float fireThreat = 0.0f; + bool engaged = false; + const Vec3& position = vehicle->getPosition(); + float maxRange = 50.0f; + IPIUnit* const unit = vehicle->getUnit(); + float minRange = 0.1f; + IPIPhysical* const physical = vehicle->getPhysical(); + IPIControlInfo* const control = vehicle->getControlInfo(); + IPIArmament* armament = vehicle->getArmament(); + + bool skipProximity = false; + if (armament) + { + const int antiAircraft = armament->isAntiAircraft(); + bool guided = false; + weaponRanges(armament, maxRange, minRange, &guided); + skipProximity = guided || antiAircraft == 1; + } + if (!skipProximity && vehicle->isPrimary() && !vehicle->hasMobile()) + { + const Vec3& here = current->getPosition(); + const float dx = position.x - here.x; + const float dy = position.y - here.y; + const float dz = position.z - here.z; + if (144.0f < dx * dx + dy * dy + dz * dz + || 2.0f < std::fabs(current->getPosition().y - position.y)) + return 0.0f; + } + + const bool usable = vehicle != current || !flag; + IPIMobile* driven; // -0x1D8: the mobile of the vehicle / a manned primary + bool noMobile; // -0x1F1 + if (!vehicle->isPrimary()) + { + Information* const primary = infoOf(vehicle->getPrimaryObject(bot->getSide())); + if (!primary->getUnit() || current == primary || !primary->getUnit()->isOccupied()) + { + noMobile = true; + driven = 0; + } + else + { + driven = primary->getMobile(); + noMobile = false; + } + } + else + { + driven = vehicle->getMobile(); + noMobile = driven == 0; + } + const int ownType = physical->getStrengthType(); + const bool exposed = unit->hasExposedSoldier(); + int soldierType = 0; + if (exposed) + soldierType = soldierInfo(bot, side)->getPhysical()->getStrengthType(); + + // A seat that must borrow the soldier's weapons scores with the soldier's row and ranges. + IAIObject* const object = vehicle->getAIObject(); + IPIUnit* strengthUnit = unit; + if (usable && object->getUnit()->mustBorrowArmament(object)) + { + Information* const soldier = soldierInfo(bot, side); + maxRange = 50.0f; + strengthUnit = soldier->getUnit(); + minRange = 0.1f; + armament = soldier->getArmament(); + if (armament) + weaponRanges(armament, maxRange, minRange, 0); + } + float strengths[kMaxStrengths]; + for (int i = 0; i < n; ++i) + strengths[i] = usable ? strengthUnit->getBattleStrengths()[i] : 0.0f; + addSeatStrengths(strengths, n, vehicle, side, flag, current); + + if (sensed.empty()) + { + if (driven == 0) + { + float reach = 0.0f; + if (!armament && !object->getUnit()->mustBorrowArmament(object)) + return 0.0f; + if (!armament) + armament = soldierInfo(bot, side)->getArmament(); + const std::vector weapons = armament->getWeapons(); + for (unsigned int i = 0; i < weapons.size(); ++i) + { + if (weapons[i] == 0xFFFFFFFFu) + continue; + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (!weapon) + continue; + const float r = weapon->getMaxRange(); + if (reach < r) + reach = r; + } + std::vector objects; + static_cast(AISingletonServer::m_iaiInformationEnvironment) + ->getEnemyObjects(objects, bot, reach); + float value = 0.0f; + float best = 0.0f; + if (!objects.empty()) + { + for (unsigned int k = 0; k < objects.size(); ++k) + { + Information* const target = infoOf(objects[k]); + if (!target) + continue; + const Vec3& p = target->getPosition(); + const float dx = p.x - position.x; + const float dy = p.y - position.y; + const float dz = p.z - position.z; + const float distance = std::sqrt(dx * dx + dy * dy + dz * dz); + if (!(distance <= maxRange && minRange <= distance)) + continue; + IPIUnit* const targetUnit = target->getUnit(); + IPIPhysical* const targetPhysical = + target->isPrimary() ? target->getPhysical() + : infoOf(target->getPrimaryObject(side))->getPhysical(); + if (!targetUnit || !targetPhysical) + continue; + bool valid = false; + Vec3 direction; + direction.x = target->getPosition().x - position.x; + direction.y = target->getPosition().y - position.y; + direction.z = target->getPosition().z - position.z; + if (normalise(direction) && control->validateCameraDirection(direction)) + valid = true; + // 0x227D1D..0x227D5E: the same row entry compared with itself - taken unless NaN. + const float s = strengths[targetPhysical->getStrengthType()]; + if ((valid && s > strengths[targetPhysical->getStrengthType()]) + || s == strengths[targetPhysical->getStrengthType()]) + { + const float* const theirs = targetUnit->getBattleStrengths(); + if (!exposed) + value = s * s - theirs[ownType]; + else + value = s * s - (theirs[soldierType] <= theirs[ownType] ? theirs[ownType] + : theirs[soldierType]); + } + if (best < value) + best = value; + } + return best; + } + // No enemy in reach: the bot's ordered area (SAI +0xB8; looked up with -1 only when the + // current one, +0xB4, is -1 too). + SAI* const sai = IAIMain::m_instance->getSAI(side); + const int ordered = sai->getBotOrderedPos(bot->getBotId()); + if (ordered != -1 || sai->getBotCurrentPos(bot->getBotId()) == -1) + { + AIStrategicObject* const area = AIStrategicObjectManager::getInstance()->getStrategicObject(ordered); + if (area) + { + const Vec2 from = area->getPosition(side); + const std::vector& neighbours = + static_cast(area)->m_neighbours; // +0x11C + for (unsigned int k = 0; k < neighbours.size(); ++k) + { + AIStrategicObject* const neighbour = neighbours[k]; + if (static_cast(neighbour->getStatus(side)) == 0) + continue; + const Vec2& to = neighbour->getPosition(side); + Vec2 offset; + offset.x = to.x - from.x; + offset.y = to.y - from.y; + Vec3 direction; + direction.x = 0.0f; + direction.y = 0.0f; + direction.z = 0.0f; + vec2ToVec3XZ(offset, direction); + if (normalise(direction) && control->validateCameraDirection(direction)) + noMobile = false; + } + } + } + if (!noMobile) + return 0.0f; + } + } + else + { + bool valid = true; + float best = 0.0f; + IPIUnit* const currentUnit = current->getUnit(); + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + for (std::map::const_iterator it = sensed.begin(); it != sensed.end(); ++it) + { + Information* const target = infoOf(it->first); + const SensedObject* const record = it->second; + if (!target || (record->m_flags & SensedObject::SENSE_SIDED) == 0) + continue; + if (!vehicle->hasMobile() && armament) + { + const Vec3& p = target->getPosition(); + const float dx = p.x - position.x; + const float dy = p.y - position.y; + const float dz = p.z - position.z; + const float distance = std::sqrt(dx * dx + dy * dy + dz * dz); + if (maxRange < distance || distance < minRange + || ((record->m_flags & SensedObject::SENSE_INDIRECT) && now < record->m_firstSeenTime + 20.0)) + continue; + } + IPIUnit* const targetUnit = target->getUnit(); + IPIPhysical* const targetPhysical = + target->isPrimary() ? target->getPhysical() : infoOf(target->getPrimaryObject(side))->getPhysical(); + if (!targetUnit || !targetPhysical) + continue; + if (driven == 0) + { + valid = false; + Vec3 direction; + direction.x = target->getPosition().x - position.x; + direction.y = target->getPosition().y - position.y; + direction.z = target->getPosition().z - position.z; + if (normalise(direction) && control->validateCameraDirection(direction)) + { + noMobile = false; + valid = true; + } + } + const int type = targetPhysical->getStrengthType(); + const float s = strengths[type]; + float value = 0.0f; + if (valid && currentUnit->getBattleStrengths()[type] <= unit->getBattleStrengths()[type]) + { + engaged = true; + const float* const theirs = targetUnit->getBattleStrengths(); + if (!exposed) + value = s * s - theirs[ownType]; + else + value = s * s - (theirs[soldierType] <= theirs[ownType] ? theirs[ownType] : theirs[soldierType]); + } + if (value <= best) + value = best; + best = value; + } + + // The strongest incoming fire against the vehicle's type, over a copy of the list (the image's + // sensed-object find and the two side reads per entry have no effect). + const std::list > fire = *bot->getIncommingFire(); + for (std::list >::const_iterator it = fire.begin(); it != fire.end(); ++it) + { + const float strength = it->first->getBattleStrength(ownType); + if (fireThreat < strength) + fireThreat = strength; + } + if (driven != 0 || !noMobile) + { + if (!(!engaged && driven != 0)) + { + if (!closeAndShouldAvoidVehiclesImpl(vehicle, side, bot)) + return best * 4.0f; + return 0.0f; + } + // not engaged in a driven vehicle: the raw value below + } + else + { + return 0.0f; + } + } + + // The raw fire value: the best weighted strength (x6 for weights <= 0.5, else x3 x weight; a + // running maximum) against an enemy type with weight > 0, minus the threat to the vehicle. + if ((!vehicle->isPrimary() || vehicle->hasMobile()) && !closeAndShouldAvoidVehiclesImpl(vehicle, side, bot)) + { + float best = 0.0f; + float running = 0.0f; + for (int i = 0; i < n; ++i) + { + const float w = weights[i]; + float v = w <= 0.5f ? strengths[i] * 6.0f : strengths[i] * 3.0f * w; + if (v <= running) + v = running; + if (0.0f < w && best < v) + best = v; + running = v; + } + if (best <= 0.0f) + return running; + float threat; + if (!exposed) + threat = fireThreat + enemyStrengths[ownType]; + else + threat = (enemyStrengths[soldierType] <= enemyStrengths[ownType] ? enemyStrengths[ownType] + : enemyStrengths[soldierType]) + + fireThreat; + return best - threat; + } + return 0.0f; +} + +// ELF 0x2265E0. A ground vehicle (primary not a soldier, not flags 0x10 / 0x20) while the bot's +// squad holds a takeable area whose order position is outside its control point radius: avoided +// when the bot already uses it (same primary) within 25 m of the order position (unless the bot +// is in an armed primary and the side's SAI has owned control points, +0x74), or when the vehicle +// or the squad is within 70 m of the control point. +bool closeAndShouldAvoidVehiclesImpl(Information* vehicle, int side, Bot* bot) +{ + bool avoid = false; + Information* const primary = infoOf(vehicle->getPrimaryObject(side)); + if (primary->isOfType(ITSoldier) || primary->isOfType(ITAir) || primary->isOfType(ITHelicopter)) + return false; + IPIMobile* const mobile = primary->getMobile(); + AIStrategicArea* const area = bot->getSquadMember()->getSquad()->getSquadStrategicAreaAssignment(); + if (!area || !area->isAreaTakeable() || !mobile) + return false; + if (!area->isOrderPosOutsideCpRadius(mobile->getVehicleNumber(), side)) + return false; + Vec3 squad; + squad.x = 0.0f; + squad.y = 0.0f; + squad.z = 0.0f; + if (!bot->getSquadMember()->getPosition(squad)) + return false; + Information* const equipment = infoOf(bot->getCurrentEquipment()); + if (equipment->getPrimaryObject(side) == primary->getPrimaryObject(side)) + { + const Vec3 order = area->getOrderPos(mobile->getVehicleNumber(), side); + const float dx = squad.x - order.x; + const float dy = squad.y - order.y; + const float dz = squad.z - order.z; + if (dx * dx + dy * dy + dz * dz < 625.0f) + { + avoid = true; + if (equipment->isPrimary() && equipment->hasArmament() + && IAIMain::m_instance->getSAI(side)->haveAnyOwnedCps(side)) + avoid = false; + } + } + else + { + Vec3 centre; + centre.x = 0.0f; + centre.y = 0.0f; + centre.z = 0.0f; + float radius = 1.0f; + bool active; + static_cast(CommonSingletonServer::m_iaiGame) + ->getControlPointInfo(area->m_controlPointId, centre, radius, active); + const Vec3& p = primary->getPosition(); + if ((p.z - centre.z) * (p.z - centre.z) + (p.x - centre.x) * (p.x - centre.x) + + (p.y - centre.y) * (p.y - centre.y) < 4900.0f + || (centre.x - squad.x) * (centre.x - squad.x) + (centre.y - squad.y) * (centre.y - squad.y) + + (centre.z - squad.z) * (centre.z - squad.z) < 4900.0f) + avoid = true; + } + return avoid; +} + +} // namespace + +// ELF 0x2265E0. +bool closeAndShouldAvoidVehicles(Information* vehicle, int side, Bot* bot) +{ + return closeAndShouldAvoidVehiclesImpl(vehicle, side, bot); +} + +// ELF 0x2269E0 (static double allowedTimeDiff = 15.0 at 0x4BB688). Nothing for a vehicle booked by +// another player, more than 8 m above ground (unless flag 0x10 or the current one), occupied (with +// `flag`) or not team-locked to the side. Otherwise fire + move value (+ 4 x the strength when +// above 0.01), scaled by health when it is at least the bail value (x0.3 for the current primary; +// soldiers always), and faded over 15 s after the side last possessed it. The two floats are unread. +float calculateVehicleUrgency(Bot* bot, Information* vehicle, const float* strengths, const float* weights, + bool flag, Information* current, float, float, int side) +{ + static double allowedTimeDiff = 15.0; + + IPIPhysical* const physical = vehicle->getPhysical(); + IPIUnit* const unit = vehicle->getUnit(); + if (vehicle->isBooked() && !vehicle->isBookedBy(bot->getPlayerId())) + return 0.0f; + if (vehicle != current && !vehicle->isOfType(ITAir)) + { + if (8.0f < static_cast(CommonSingletonServer::m_iaiTerrain) + ->getAltitude(vehicle->getPosition())) + return 0.0f; + } + if ((flag && unit->isOccupied()) || !unit->isTeamLocked(side)) + return 0.0f; + const float fire = calculateFireStrength(bot, vehicle, side, strengths, weights, flag, current); + const float move = calculateVehicleMoveUrgency(vehicle, side, bot, flag, current); + float urgency = move + fire; + if (0.01f < urgency) + urgency = vehicle->getStrength() * 4.0f + urgency; + const float health = physical->getHealth(); + float bail = IBotManager::instance->getVehicleBailValue(); + if (!vehicle->isOfType(ITSoldier) && vehicle->isPrimary() + && vehicle->getHandle() == current->getHandle()) + bail = bail * 0.3f; + if (!(bail <= health) && !vehicle->isOfType(ITSoldier)) + return 0.0f; + urgency = urgency * health; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (vehicle->getSide() == side) + { + const double since = now - unit->getLastPlayerPossesionTime(); + if (since < allowedTimeDiff) + urgency = static_cast(1.0 / allowedTimeDiff * since) * urgency; + } + return urgency; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/VehicleUrgencyCalculator.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/VehicleUrgencyCalculator.h new file mode 100644 index 000000000..39c7a743a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/VehicleUrgencyCalculator.h @@ -0,0 +1,28 @@ +// Vehicle urgency helpers shared by the change/enter-vehicle behaviours (BBChange). Package A-core +// (docs/macos-ai-behaviour-plan.md); TU VehicleUrgencyCalculator.cpp, libaidll.so 0x2265E0..0x228EF0. +// The image has no header symbol; the free functions are in namespace dice::hfe::ai. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_VEHICLEURGENCYCALCULATOR_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_VEHICLEURGENCYCALCULATOR_H + +namespace dice { +namespace hfe { +namespace ai { + +class Bot; +class Information; + +// ELF 0x2265E0 (318 instructions; returns `al`). +bool closeAndShouldAvoidVehicles(Information* vehicle, int side, Bot* bot); + +// ELF 0x2269E0 (175 instructions; x87 float return). Callers: BBChange (9 sites, 0x20096F..0x202C7C). +// The two `const float*` are per-weapon-class rows indexed by IAISettings slot +0x34 counts; +// [UNRESOLVED] parameter names. +float calculateVehicleUrgency(Bot* bot, Information* vehicle, const float* strengths, const float* weights, + bool flag, Information* current, float a, float b, int side); + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_VEHICLEURGENCYCALCULATOR_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision.cpp new file mode 100644 index 000000000..f61ceee82 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision.cpp @@ -0,0 +1,46 @@ +// Base of the avoid-collision patterns (BBPAvoidCollisionInfantery, BBPAvoidCollision2d, 3d): the +// per-bot arrays their init (slot +0x18) fills from BBAvoid's calculateUrgency. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see +// docs/macos-ai-behaviour-plan.md. + +// static init: ELF 0x2297F0 (__tcf_0 0x229850, _GLOBAL__I 0x229880): 's Init object only. +#include + +#include "BBPAvoidCollision.h" + +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x229090 (C2) / 0x229440 (C1). One getMaxNBots (IAISettings slot 0) sizes all three arrays: +// +0x0C new[n] of 4 bytes, +0x10 new[n * 12] with every Vec3 zeroed (rodata 0x49CB34) before the +// check, +0x14 new[n] of 4 bytes; each is checkPointer'd. +0x08 is left to the subclasses. +BBPAvoidCollision::BBPAvoidCollision() + : BBPPattern() +{ + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_obstacle = checkPointer(new unsigned int[count]); + m_relativeSpeed = checkPointer(new Vec3[count]()); + m_value = checkPointer(new float[count]); +} + +// ELF 0x228F10 (D2) / 0x228F90 (D1) / 0x229010 (D0): delete[] +0x0C, +0x10, +0x14 when set, then +// ~BBPPattern. +BBPAvoidCollision::~BBPAvoidCollision() +{ + if (m_obstacle) + delete[] m_obstacle; + if (m_relativeSpeed) + delete[] m_relativeSpeed; + if (m_value) + delete[] m_value; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision.h new file mode 100644 index 000000000..8214154a9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision.h @@ -0,0 +1,43 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPAVOIDCOLLISION_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPAVOIDCOLLISION_H + +#include "../../../../Math/Vec3.h" +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4BB6A0 (7 words), package F-infantry. sizeof 0x18 (BBPAvoidCollisionInfantery's +// own members start at +0x18). The per-bot arrays are what init (slot +0x18) stores; BBAvoid's +// calculateUrgency passes (bot, collision point, obstacle handle, relative speed, time to +// collision) or zero vectors and a flee strength. +class BBPAvoidCollision : public BBPPattern +{ +public: + BBPAvoidCollision(); // 0x229440 + virtual ~BBPAvoidCollision(); // 0x228F90 + + virtual void init(Bot*, Vec3&, unsigned int, Vec3&, float) = 0; // no body, slot +0x18; void: BBPAvoidCollisionInfantery::init 0x22C870 sets no result register + +protected: + /* +0x08 */ int m_id; // not written here; the concrete constructors store their argument + /* +0x0C */ unsigned int* m_obstacle; // per bot: init's handle [INFERRED] name + /* +0x10 */ Vec3* m_relativeSpeed; // per bot, zeroed: init's second Vec3 [INFERRED] name + /* +0x14 */ float* m_value; // per bot: init's float (time to collision or flee strength) [INFERRED] name +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPAVOIDCOLLISION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision2d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision2d.cpp new file mode 100644 index 000000000..ba6079a9d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision2d.cpp @@ -0,0 +1,192 @@ +// Vehicle collision-avoidance plans, recovered from libaidll.so. + +// static init: ELF 0x22AFD0 (__tcf_0 0x22B030, _GLOBAL__I 0x22B060): 's Init object only. +#include + +#include "BBPAvoidCollision2d.h" + +#include "../AIUtils/checkPointer.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotNavigation.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPAHonkHorn.h" +#include "../AIBotActionPlan/BAPAMoveToDirect.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConOr.h" +#include "../AIBotActionPlan/BAPConPosition.h" +#include "../AIBotActionPlan/BAPConTime.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIPlanInterpreter/VehicleControlInline.h" +#include "../Main/IAIPathfinding.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../../Math/Vec3.h" +#include "../../../../Math/Mat4.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x229AD0: BBPAvoidCollision(), the vtable store (GOT -0xF48 + 8), the argument at +0x08, +// then `new Vec2[getMaxNBots()]` (IAISettings slot 0; 8 bytes each, both words zeroed from the +// 0.0f constant) through the inlined checkPointer (Debug type 6, line 46) into +0x1C. The same +// body as BBPAvoidCollisionInfantery's. +BBPAvoidCollision2d::BBPAvoidCollision2d(int id) + : BBPAvoidCollision() +{ + m_id = id; + m_pointXZ = checkPointer(new Vec2[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]()); +} + +// ELF 0x229C70 (D2) / 0x229CC0 (D1) / 0x229D10 (D0): delete[] +0x1C when set, then +// ~BBPAvoidCollision. +BBPAvoidCollision2d::~BBPAvoidCollision2d() +{ + if (m_pointXZ) + delete[] m_pointXZ; +} + +// ELF 0x229E20 +BotScript* BBPAvoidCollision2d::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) + { + BotScript* previous = bot->getPlan(); + if (previous) + delete previous; + bot->setPlan(0); + } + return 0; + } + if (bot->getPlan()) + { + BotScript* previous = bot->getPlan(); + if (previous) + delete previous; + bot->setPlan(0); + } + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + const unsigned int obstacleHandle = m_obstacle[bot->getBotId()]; + Information* obstacle = informationManager->getInformation(obstacleHandle); + if (!obstacle) + return 0; + IPIMobile* obstacleMobile = obstacle->getMobile(); + if (!obstacleMobile) + return 0; + const float time = m_value[bot->getBotId()]; + const Vec2 collisionPoint = m_pointXZ[bot->getBotId()]; + const Vec3 relativeSpeed = m_relativeSpeed[bot->getBotId()]; + (void)collisionPoint; + (void)relativeSpeed; + Information* self = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* mobile = self->getMobile(); + IPIControlInfo* controls = self->getControlInfo(); + const Vec3& position = self->getPosition(); + const Vec2 ownXZ = {position.x, position.z}; + const Vec3& obstaclePosition = obstacle->getPosition(); + const Vec2 obstacleXZ = {obstaclePosition.x, obstaclePosition.z}; + Vec2 velocity; + velocity.x = mobile->getSpeed().x; + velocity.y = mobile->getSpeed().z; + if (velocity.x * velocity.x + velocity.y * velocity.y == 0.0f) + { + velocity.x = self->getTransformation().m[8]; + velocity.y = self->getTransformation().m[10]; + } + Vec2 obstacleVelocity; + obstacleVelocity.x = obstacleMobile->getSpeed().x; + obstacleVelocity.y = obstacleMobile->getSpeed().z; + const float obstacleSpeed = std::sqrt(obstacleVelocity.x * obstacleVelocity.x + + obstacleVelocity.y * obstacleVelocity.y); + Vec2 unusedDirection = obstacleVelocity; + if (obstacleSpeed > 0.0001f) + { + const float inverse = 1.0f / obstacleSpeed; + unusedDirection.x *= inverse; + unusedDirection.y *= inverse; + } + (void)unusedDirection; + Vec2 direction = velocity; + vehiclecontrol::normalizeVec2(direction); + const float dx = obstacleXZ.x - ownXZ.x; + const float dy = obstacleXZ.y - ownXZ.y; + const float ahead = velocity.x * dx + velocity.y * dy; + const float across = direction.y * dx - direction.x * dy; + const float side = obstacleSpeed > 5.0f ? (ahead > 0.0f ? 1.0f : -1.0f) + : (across < 0.0f ? 1.0f : -1.0f); + const float ownRadius = self->getPhysical()->getRadius(); + const float obstacleRadius = obstacle->getPhysical()->getRadius(); + const Mat4& transformation = self->getTransformation(); + const Vec3 offset = {side * transformation.m[0], side * transformation.m[1], side * transformation.m[2]}; + const float radius = ownRadius + obstacleRadius; + Vec3 target = {radius * offset.x + obstaclePosition.x, + radius * offset.y + obstaclePosition.y, + radius * offset.z + obstaclePosition.z}; + BotNavigation* navigation = bot->getBotNavigation(); + Vec3 hit = {0.0f, 0.0f, 0.0f}; + if (navigation->m_infantryPolygon == -1) + return 0; + unsigned int polygon; + const int equipmentType = self->getUnit()->getEquipmentType(); + if (IAIPathfinding::instance->trace(navigation, true, target, hit, polygon, + equipmentType, -1, 0.0f, 0, 0)) + target = hit; + else + { + const Mat4& fallback = self->getTransformation(); + target = Vec3{0.1f + fallback.m[12], fallback.m[13] + 0.0f, fallback.m[14] + 0.0f}; + } + bot->getSquadMember()->clearRequestAction(); + BAPConOr* stop = checkPointer(new BAPConOr()); + stop->addCondition(checkPointer(new BAPConTime(static_cast(time * 1.5f), false, false, false))); + stop->addCondition(checkPointer(new BAPConPosition(target, 1.0f))); + const unsigned long long driveControls = controls->getDriveControls(); + const float arriveSpeed = mobile->getMaxSpeed(); + const float speed = mobile->getMaxSpeed(); + BAPAMoveToDirect* move = checkPointer(new BAPAMoveToDirect(bot, target, speed, arriveSpeed, stop, driveControls, m_id)); + BAPAHonkHorn* horn = 0; + if (self->isOfType(ITHasCarHorn)) + { + const int obstacleSide = obstacle->getSide(); + const int ownSide = self->getSide(); + if (obstacleSide == ownSide && obstacle->getUnit()->isOccupied()) + horn = checkPointer(new BAPAHonkHorn(obstacleHandle, m_id)); + } + BAPCombinerSerial* serial = checkPointer(new BAPCombinerSerial(m_id, -1)); + if (horn) + serial->addStatement(horn); + serial->addStatement(move); + serial->mpOwner = this; + return serial; +} + +// ELF 0x229D60 +void BBPAvoidCollision2d::init(Bot* bot, Vec3& point, unsigned int obstacle, Vec3& relativeSpeed, float time) +{ + m_initiated[bot->getBotId()] = true; + vec3ToVec2XZ(point, m_pointXZ[bot->getBotId()]); + m_obstacle[bot->getBotId()] = obstacle; + m_relativeSpeed[bot->getBotId()] = relativeSpeed; + m_value[bot->getBotId()] = time; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision2d.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision2d.h new file mode 100644 index 000000000..6de3e2456 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision2d.h @@ -0,0 +1,36 @@ +// Vehicle collision-avoidance plan generator. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPAVOIDCOLLISION2D_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPAVOIDCOLLISION2D_H + +#include "../../../../Math/Vec3.h" +#include "BBPAvoidCollision.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BB720 (7 words), operator new 0x20, package G-vehicles. +class BBPAvoidCollision2d : public BBPAvoidCollision +{ +public: + explicit BBPAvoidCollision2d(int); // 0x229AD0 + virtual ~BBPAvoidCollision2d(); // 0x229CC0 + + virtual BotScript* createPlan(Bot*); // 0x229E20, slot +0x08; from the base declaration + virtual void init(Bot*, Vec3&, unsigned int, Vec3&, float); // 0x229D60, slot +0x18; from the base declaration + + // Same layout as BBPAvoidCollisionInfantery (operator new 0x20 in both create arms). + /* +0x18 */ unsigned char m_unwritten18[4]; // not written by the constructor [UNRESOLVED] + /* +0x1C */ Vec2* m_pointXZ; // per bot, zeroed [INFERRED] name, as in the infantry pattern +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPAVOIDCOLLISION2D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision3d.cpp new file mode 100644 index 000000000..3b39fbe59 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision3d.cpp @@ -0,0 +1,183 @@ +// Collision-avoidance pattern of aircraft (AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision3d.cpp +// in the image). Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its +// ELF address. createPlan was read from the Intel-syntax listing (fsubrp operand order) and checked +// against the Ghidra pseudocode, which misnames the altitude calls (+0x34) as getMaxSpeed. + +// static init: ELF 0x22C390 (__tcf_0 0x22C3F0, _GLOBAL__I 0x22C420): 's Init object only. +#include + +#include "BBPAvoidCollision3d.h" + +#include "../../../../Math/Vec3.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPActionInline.h" +#include "../AIBotActionPlan/BAPAMoveTo3d.h" +#include "../AIBotActionPlan/BAPConOr.h" +#include "../AIBotActionPlan/BAPConPosition.h" +#include "../AIBotActionPlan/BAPConTime.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x22B220: BBPAvoidCollision(), the vtable store, the argument at +0x08, then +// `new Vec3[getMaxNBots()]` (IAISettings slot 0; every component stored from the 0.0f constant) +// through the inlined checkPointer into +0x1C. +BBPAvoidCollision3d::BBPAvoidCollision3d(int id) + : BBPAvoidCollision() +{ + m_id = id; + m_collisionPoint = + checkPointer(new Vec3[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]()); +} + +// ELF 0x22B410 (D2 0x22B3C0, D0 0x22B460): delete[] +0x1C when set, then ~BBPAvoidCollision. +BBPAvoidCollision3d::~BBPAvoidCollision3d() +{ + if (m_collisionPoint) + delete[] m_collisionPoint; +} + +// ELF 0x22B4B0. Stores the arguments per bot, in this order. +void BBPAvoidCollision3d::init(Bot* bot, Vec3& collisionPoint, unsigned int obstacle, Vec3& relativeSpeed, + float value) +{ + m_initiated[bot->getBotId()] = true; + m_collisionPoint[bot->getBotId()] = collisionPoint; + m_obstacle[bot->getBotId()] = obstacle; + m_relativeSpeed[bot->getBotId()] = relativeSpeed; + m_value[bot->getBotId()] = value; +} + +// ELF 0x22B570. Always rebuilds: a single BAPAMoveTo3d to a point 45 degrees left or right of the +// own XZ speed (whichever side the obstacle is not on, judged by the own speed's normal), at the +// own altitude plus twice the stored value when above the obstacle and minus it otherwise, until +// 1.1 times the value has passed or the point is within 5 m. The speed is the own maximum, reduced +// to 30 % unless the obstacle lies behind both 45-degree directions. Neither information is +// null-checked, nor the obstacle's mobile plug-in, as compiled. +// The first test compares |dot(own speed normal, obstacle heading)| - pi/2 with 20 degrees; a dot +// product of unit vectors can never pass it, so the left turn without the obstacle test is dead +// code in practice, kept as compiled. The statement list is constructed and destroyed unused. +// [PLATFORM] precision: the x87 build keeps the rotated components, the dot products and the +// normalization factor in extended precision; the float expressions below round them. +BotScript* BBPAvoidCollision3d::createPlan(Bot* bot) +{ + std::list statements; + std::list conditions; + bool behindBoth = false; + + if (!m_initiated[bot->getBotId()]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } + return 0; + } + + bot->getSquadMember()->clearRequestAction(); + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* const mobile = self->getMobile(); + Information* const obstacle = informationManager->getInformation(m_obstacle[bot->getBotId()]); + + Vec2 selfXZ; + vec3ToVec2XZ(self->getPosition(), selfXZ); + Vec2 obstacleXZ; + vec3ToVec2XZ(obstacle->getPosition(), obstacleXZ); + Vec2 speed; + vec3ToVec2XZ(mobile->getSpeed(), speed); + Vec2 obstacleSpeed; + vec3ToVec2XZ(obstacle->getMobile()->getSpeed(), obstacleSpeed); + Vec2 obstacleHeading = obstacleSpeed; + bapinline::normalize(obstacleHeading); // inlined Vec2 normalization + + Vec2 left; + left.x = speed.x * 0.7071f - speed.y * 0.7071f; + left.y = speed.x * 0.7071f + speed.y * 0.7071f; + Vec2 right; + right.x = speed.x * 0.7071f + speed.y * 0.7071f; + right.y = speed.y * 0.7071f - 0.7071f * speed.x; + + Vec2 normal; + getNormal(speed, normal); + Vec2 destinationXZ = selfXZ; + if (std::fabs(normal.x * obstacleHeading.x + normal.y * obstacleHeading.y) - 1.5708f > 0.349066f) + { + destinationXZ.x += left.x; + destinationXZ.y += left.y; + } + else + { + Vec2 toObstacle; + toObstacle.x = obstacleXZ.x - selfXZ.x; + toObstacle.y = obstacleXZ.y - selfXZ.y; + if (toObstacle.x * left.x + toObstacle.y * left.y <= 0.0f + && toObstacle.x * right.x + toObstacle.y * right.y <= 0.0f) + behindBoth = true; + if (normal.x * toObstacle.x + normal.y * toObstacle.y > 0.0f) + { + destinationXZ.x += left.x; + destinationXZ.y += left.y; + } + else + { + destinationXZ.x += right.x; + destinationXZ.y += right.y; + } + } + + const unsigned long long controls = self->getControlInfo()->getDriveControls(); + float maxSpeed = mobile->getMaxSpeed(); + Vec3 destination; + vec2ToVec3XZ(destinationXZ, destination); + const float altitude = self->getAltitude(); + if (altitude > obstacle->getAltitude()) + destination.y = m_value[bot->getBotId()] + m_value[bot->getBotId()] + altitude; + else + destination.y = altitude - (m_value[bot->getBotId()] + m_value[bot->getBotId()]); + + // The product is formed in extended precision and stored as the double argument; a float + // times float product is exact in double. + BAPConTime* const timeout = checkPointer(new BAPConTime( + static_cast(1.1f) * m_value[bot->getBotId()], false, false, false)); + BAPConPosition* const reached = checkPointer(new BAPConPosition(destination, 5.0f)); + conditions.push_back(timeout); + conditions.push_back(reached); + BAPConOr* const stop = checkPointer(new BAPConOr(conditions)); + if (!behindBoth) + maxSpeed *= 0.3f; + BAPAMoveTo3d* const move = + checkPointer(new BAPAMoveTo3d(bot, destination, maxSpeed, maxSpeed, stop, controls, 30.0f, m_id)); + move->setParent(this); // +0x04 (BotScript::mpOwner) + return move; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision3d.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision3d.h new file mode 100644 index 000000000..bae60e535 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision3d.h @@ -0,0 +1,39 @@ +// Collision-avoidance pattern of aircraft (3d navigation): steers 45 degrees off the own course, +// away from the obstacle, and climbs or dives by twice the time to collision. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPAVOIDCOLLISION3D_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPAVOIDCOLLISION3D_H + +#include "../../../../Math/Vec3.h" +#include "BBPAvoidCollision.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BB7A0 (7 words), operator new 0x20, package H-deferred. +class BBPAvoidCollision3d : public BBPAvoidCollision +{ +public: + explicit BBPAvoidCollision3d(int); // 0x22B220 + virtual ~BBPAvoidCollision3d(); // 0x22B410 + + virtual BotScript* createPlan(Bot*); // 0x22B570, slot +0x08; from the base declaration + virtual void init(Bot*, Vec3&, unsigned int, Vec3&, float); // 0x22B4B0, slot +0x18; from the base declaration + + // Same layout as BBPAvoidCollision2d, with a Vec3 per bot at +0x1C. + /* +0x18 */ unsigned char m_unwritten18[4]; // not written by the constructor [UNRESOLVED] + /* +0x1C */ Vec3* m_collisionPoint; // per bot, zeroed: init's first Vec3 [INFERRED] name +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPAVOIDCOLLISION3D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollisionInfantery.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollisionInfantery.cpp new file mode 100644 index 000000000..7a2eb5938 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollisionInfantery.cpp @@ -0,0 +1,264 @@ +// Infantry avoid-collision pattern (AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollisionInfantery.cpp +// in the image): init keeps the collision point (XZ), the obstacle, the relative speed and the time +// or strength per bot; createPlan sprints the bot to a free point away from the obstacle, a tear-gas +// cloud or a grenade. Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries +// its ELF address. +// +// static init: ELF 0x22E420 (__tcf_0 0x22E480, _GLOBAL__I 0x22E4B0): the guard object only. + +#include "BBPAvoidCollisionInfantery.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/BotNavigation.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPActionInline.h" +#include "../AIBotActionPlan/BAPAMergeSoldierInputs.h" +#include "../AIBotActionPlan/BAPAMoveToDirect.h" +#include "../AIBotActionPlan/BAPAOverrideSensingAgent.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConOr.h" +#include "../AIBotActionPlan/BAPConPosition.h" +#include "../AIBotActionPlan/BAPConTime.h" +#include "../AIBotActionPlan/BAPICTurnLock.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AIRandom.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IAIPathfinding.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../../Game/GameLogic/Player.h" +#include "../../../../Game/Objects/IPlayer.h" +#include "../../../../Math/Vec3.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x22C440 (C2) / 0x22C5E0 (C1): BBPAvoidCollision(), +0x08 = the argument, +0x1C = +// checkPointer(new Vec2[getMaxNBots]) with every Vec2 zeroed (rodata 0x49CB34) before the check. +BBPAvoidCollisionInfantery::BBPAvoidCollisionInfantery(int id) + : BBPAvoidCollision() +{ + m_id = id; + m_pointXZ = checkPointer(new Vec2[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]()); +} + +// ELF 0x22C780 (D2) / 0x22C7D0 (D1) / 0x22C820 (D0): delete[] +0x1C when set, then +// ~BBPAvoidCollision. +BBPAvoidCollisionInfantery::~BBPAvoidCollisionInfantery() +{ + if (m_pointXZ) + delete[] m_pointXZ; +} + +// ELF 0x22C930 (listing; Ghidra loses the stack after the sret calls). Builds +// serial { turn lock on, +// parallel { override sensing agent, +// sprint (BAPAMoveToDirect) to the flee point until BAPConOr(time, within 2 m), +// merge soldier inputs }, +// turn lock off } +// The danger is the obstacle's position (XZ) or, without obstacle information, the tear-gas +// position of the bot's engine Player plus (1, 1, 1) with a 5 s flee time, else the grenade warning +// (none: 0). Without an obstacle handle, or with a zero collision point, the flee point is a trace +// 15 m (with an obstacle handle 10 m) straight away from the danger, then to a random side, then the +// other side (the last result is used whatever the trace answers); otherwise one trace sideways of the +// obstacle's velocity (its facing when it stands still), on the side away from it. The time is the +// flee time without an obstacle handle (rounded to float), else init's value. As compiled: the +// current plan is always dropped, the bot's equipment information is not null-checked, the obstacle's +// mobile plug-in is not null-checked, and a pattern that is not initiated returns 0 untouched. +BotScript* BBPAvoidCollisionInfantery::createPlan(Bot* bot) +{ + Vec2 ownXZ; + ownXZ.x = ownXZ.y = 0.0f; + Vec2 dangerXZ; + dangerXZ.x = dangerXZ.y = 0.0f; + Vec2 destinationXZ; + destinationXZ.x = destinationXZ.y = 0.0f; + + world::IPlayer* const player = bot->getPlayer()->getPlayer(); // 0x22C97C, before the test + if (!m_initiated[bot->getBotId()]) + return 0; // 0x22E412 + + bot->getSquadMember()->clearRequestAction(); + if (bot->getPlan()) + { + // 0x22E3E1 + delete bot->getPlan(); + bot->setPlan(0); + } + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); // 0x22E3C6 + bot->getScriptContext()->clear(); + + const bool noObstacle = m_obstacle[bot->getBotId()] == 0xFFFFFFFFu; + Information* const obstacle = informationManager->getInformation(m_obstacle[bot->getBotId()]); + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* const mobile = info->getMobile(); // 0x22CAA0: unchecked + const Vec3& position = info->getPosition(); + vec3ToVec2XZ(position, ownXZ); + + double fleeTime = 0.0; + Vec3 destination; // -0x1A8: the danger position first, then the trace's flee point + if (!obstacle) + { + // 0x22E2A3 + destination.x = destination.y = destination.z = 0.0f; + if (player->getIsGassed()) + { + fleeTime = 5.0; + Vec3 one; + one.x = one.y = one.z = 1.0f; + const Vec3 gas = static_cast(player)->getTearGasPosition(); // raw +0x2E8 in the image + destination = bapinline::add(gas, one); + } + else if (!bot->getBotNavigation()->getGrenadeWarning(destination, fleeTime)) + { + return 0; // 0x22E3AA + } + vec3ToVec2XZ(destination, dangerXZ); + } + else + { + vec3ToVec2XZ(obstacle->getPosition(), dangerXZ); // 0x22CAE6 + } + + // 0x22CB0F + const float distance = noObstacle ? 15.0f : 10.0f; + info->getMobile()->getVehicleNumber(); // result discarded + const unsigned long long driveControls = info->getControlInfo()->getDriveControls(); + destination.x = destination.y = destination.z = 0.0f; + IAIPathfinding* const pathfinding = IAIPathfinding::instance; + const float maxSpeed = mobile->getMaxSpeed(); + const float side = AIRandom::m_instance->next() * 2.3283064e-10f > 0.5f ? 1.0f : -1.0f; + const int equipmentType = info->getUnit()->getEquipmentType(); + + bool atZeroPoint = false; + if (!noObstacle) + { + // 0x22E200: the collision point compared with zero. + Vec2 zero; + zero.x = zero.y = 0.0f; + const Vec2& point = m_pointXZ[bot->getBotId()]; + if (std::fabs(point.x - zero.x) + std::fabs(point.y - zero.y) <= 1.1920929e-07f) + atZeroPoint = true; + } + + Vec3 target; + target.x = target.y = target.z = 0.0f; + unsigned int polygon; + if (atZeroPoint || noObstacle) + { + // 0x22CC76: straight away from the danger, else to one side, else the other. + Vec2 toDanger; + toDanger.x = dangerXZ.x - ownXZ.x; + toDanger.y = dangerXZ.y - ownXZ.y; + bapinline::normalize(toDanger); + Vec2 sideways; + sideways.x = distance * toDanger.y; + sideways.y = distance * -toDanger.x; + Vec2 offset; + offset.x = distance * -toDanger.x; + offset.y = -toDanger.y * distance; + + target = position; + addVec2ToVec3XZ(offset, target); + if (!pathfinding->trace(bot->getBotNavigation(), false, target, destination, polygon, equipmentType, -1, 0.0f, 0, 0)) + { + // 0x22DC20 + offset.x = side * sideways.x; + offset.y = side * sideways.y; + target = position; + addVec2ToVec3XZ(offset, target); + if (!pathfinding->trace(bot->getBotNavigation(), false, target, destination, polygon, equipmentType, -1, 0.0f, 0, 0)) + { + // 0x22DCEC + offset.x = sideways.x * -side; + offset.y = -side * sideways.y; + target = position; + addVec2ToVec3XZ(offset, target); + pathfinding->trace(bot->getBotNavigation(), false, target, destination, polygon, equipmentType, -1, 0.0f, 0, 0); + } + } + } + else + { + // 0x22DE00: sideways of the obstacle's motion, on the side away from the obstacle. + Vec3 velocity = obstacle->getMobile()->getSpeed(); + const Vec3& zero = Vec3::getZero(); + if (std::fabs(velocity.x - zero.x) <= 1.1920929e-07f && std::fabs(velocity.y - zero.y) <= 1.1920929e-07f + && std::fabs(velocity.z - zero.z) <= 1.1920929e-07f) + velocity = obstacle->getFaceing(); // 0x22E1B4 + const Vec3& obstaclePosition = obstacle->getPosition(); + const Vec3 own = position; + Vec3 away; + away.x = own.x - obstaclePosition.x; + away.y = 0.0f; + away.z = own.z - obstaclePosition.z; + Vec3 offset; + offset.x = velocity.z; + offset.y = 0.0f; + offset.z = -velocity.x; + bapinline::normalize(offset); + offset.x = distance * offset.x; + offset.y = distance * offset.y; + offset.z = distance * offset.z; + if (bapinline::dot(offset, away) > 0.0f) + target = bapinline::add(position, offset); + else + target = bapinline::sub(position, offset); // 0x22E107 + pathfinding->trace(bot->getBotNavigation(), false, target, destination, polygon, equipmentType, -1, 0.0f, 0, 0); + } + + // 0x22CE58 + BAPConTime* time; + if (noObstacle) + time = checkPointer(new BAPConTime(static_cast(fleeTime), false, false, false)); + else + time = checkPointer(new BAPConTime(m_value[bot->getBotId()], false, false, false)); // 0x22DAD0 + vec3ToVec2XZ(destination, destinationXZ); + BAPConPosition* const reached = checkPointer(new BAPConPosition(destinationXZ, 2.0f)); + BAPConOr* const done = checkPointer(new BAPConOr()); + done->addCondition(time); + done->addCondition(reached); + BAPAMoveToDirect* const move = + checkPointer(new BAPAMoveToDirect(bot, destination, maxSpeed, maxSpeed, done, driveControls, m_id)); + move->setIsSprinting(bot, true, destination, 0xFFFFFFFFu); + + BAPCombinerSerial* const serial = checkPointer(new BAPCombinerSerial(m_id, -1)); + serial->addStatement(checkPointer(new BAPICTurnLock(true))); + BAPCombinerParallel* const parallel = checkPointer(new BAPCombinerParallel(m_id, true, -1, false)); + parallel->addStatement(checkPointer(new BAPAOverrideSensingAgent())); + parallel->addStatement(move); + parallel->addStatement(checkPointer(new BAPAMergeSoldierInputs(m_id))); + serial->addStatement(parallel); + serial->addStatement(checkPointer(new BAPICTurnLock(false))); + serial->setParent(this); // +0x04 (BotScript::mpOwner) + return serial; +} + +// ELF 0x22C870 (64 insns; reached from BBAvoid::calculateUrgency through slot +0x18): +// m_initiated[id] = true, vec3ToVec2XZ(point, +0x1C[id]), +0x0C[id] = handle, +0x10[id] = speed +// (three-word copy), +0x14[id] = value. +void BBPAvoidCollisionInfantery::init(Bot* bot, Vec3& point, unsigned int obstacle, Vec3& relativeSpeed, float value) +{ + m_initiated[bot->getBotId()] = true; + vec3ToVec2XZ(point, m_pointXZ[bot->getBotId()]); + m_obstacle[bot->getBotId()] = obstacle; + m_relativeSpeed[bot->getBotId()] = relativeSpeed; + m_value[bot->getBotId()] = value; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollisionInfantery.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollisionInfantery.h new file mode 100644 index 000000000..d113d3d94 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollisionInfantery.h @@ -0,0 +1,41 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPAVOIDCOLLISIONINFANTERY_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPAVOIDCOLLISIONINFANTERY_H + +#include "../../../../Math/Vec3.h" +#include "BBPAvoidCollision.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BB820 (7 words), operator new 0x20, package F-infantry. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BBPAvoidCollisionInfantery : public BBPAvoidCollision +{ +public: + explicit BBPAvoidCollisionInfantery(int); // 0x22C5E0 + virtual ~BBPAvoidCollisionInfantery(); // 0x22C7D0 + + virtual BotScript* createPlan(Bot*); // 0x22C930, slot +0x08; from the base declaration + virtual void init(Bot*, Vec3&, unsigned int, Vec3&, float); // 0x22C870, slot +0x18; from the base declaration + +private: + /* +0x18 */ unsigned char m_unwritten18[4]; // not written by the constructor or init [UNRESOLVED] + /* +0x1C */ Vec2* m_pointXZ; // per bot, zeroed: init's first Vec3 projected to XZ [INFERRED] name +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPAVOIDCOLLISIONINFANTERY_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPBridgeRepair.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPBridgeRepair.cpp new file mode 100644 index 000000000..d9fcaf7e7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPBridgeRepair.cpp @@ -0,0 +1,225 @@ +// Bridge-repair pattern: per-bot plan parameters that BBBridgeRepair::calculateUrgency stores through +// init. Recovered from libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see +// docs/macos-ai-behaviour-plan.md. + +// static init: ELF 0x232140 (__tcf_0 0x2321A0, _GLOBAL__I 0x2321D0): 's Init object only. +#include + +#include "BBPBridgeRepair.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/CommunicationAgent.h" +#include "../AIBot/SensingAgent.h" +#include "../AIBot/SquadCoordinator.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPALookAtObject.h" +#include "../AIBotActionPlan/BAPAMoveToDirect.h" +#include "../AIBotActionPlan/BAPAMoveToFinding.h" +#include "../AIBotActionPlan/BAPAOverrideSensingAgent.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPASoldierPose.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPATriggerContinously.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConPosition.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPFlowCWhile.h" +#include "../AIBotActionPlan/BAPICChangeVehicle.h" +#include "../AIBotActionPlan/BAPIWFire.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x22E4D0 (C2) / 0x22EC30 (C1): BBPPattern(), the argument to +0x08, six getMaxNBots-sized +// arrays (each checkPointer'd; the Vec3 ones run the zeroing Vec3 constructor loop, rodata +// 0x49CB34 0.0f, reproduced here by value-initialisation), then for each bot (getMaxNBots re-read +// per pass) segment and weapon index -1 and the near-request flag false. +BBPBridgeRepair::BBPBridgeRepair(int value) + : BBPPattern() +{ + m_unknown8 = value; + m_segment = checkPointer(new unsigned int[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); + m_weaponIndex = checkPointer(new int[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); + m_direction = checkPointer(new Vec3[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]()); + m_nearRequest = checkPointer(new bool[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); + m_standPosition = checkPointer(new Vec3[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]()); + m_segmentEnd = checkPointer(new Vec3[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]()); + for (int i = 0; i < static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); ++i) + { + m_segment[i] = 0xFFFFFFFFu; + m_weaponIndex[i] = -1; + m_nearRequest[i] = false; + } +} + +// ELF 0x22F390 (D2) / 0x22F450 (D1) / 0x22F510 (D0): delete[] +0x0C..+0x20 in order when set, then +// the base. +BBPBridgeRepair::~BBPBridgeRepair() +{ + if (m_segment) + delete[] m_segment; + if (m_weaponIndex) + delete[] m_weaponIndex; + if (m_direction) + delete[] m_direction; + if (m_nearRequest) + delete[] m_nearRequest; + if (m_standPosition) + delete[] m_standPosition; + if (m_segmentEnd) + delete[] m_segmentEnd; +} + +// ELF 0x22F6E0 +BotScript* BBPBridgeRepair::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) { + delete bot->getPlan(); + bot->setPlan(0); + } + return 0; + } + + bot->getPlayer()->getSpawnKit(); + bot->getCommunicationAgent(); + if (bot->hasPlan() && static_cast(bot->getPlan())->getPatternId() == m_unknown8 + && static_cast(bot->getPlan())->getId() == BAPSTInfoWrapper + && static_cast(bot->getPlan())->getInfoType() == 0 + && static_cast(bot->getPlan())->getTarget() == m_segment[bot->getBotId()]) + return bot->getPlan(); + + const unsigned int segment = m_segment[bot->getBotId()]; + bot->getSquadMember()->clearRequestAction(); + bot->getSensingAgent()->clearPlanTargetInformation(); + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + if (bot->getPlan()) { + delete bot->getPlan(); + bot->setPlan(0); + } + bot->getScriptContext()->clear(); + + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + Information* const target = informationManager->getInformation(m_segment[bot->getBotId()]); + if (!self || !self->getUnit() || !target) + return 0; + bot->setBridgeRepairTarget(segment); + IPIMobile* const mobile = self->getMobile(); + IPIControlInfo* const controls = self->getControlInfo(); + const int weaponIndex = m_weaponIndex[bot->getBotId()]; + if (weaponIndex == -1) { + self->getAIObject()->update(); + return 0; + } + + const int side = bot->getSide(); + const unsigned int soldierHandle = bot->getPlayer()->getSoldier()->getInformation(side); + Information* const soldier = informationManager->getInformation(soldierHandle); + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(soldier->getArmament()->getWeapon(weaponIndex)); + BAPCombinerSerial* const root = checkPointer(new BAPCombinerSerial(m_unknown8, -1)); + BAPCombinerSerial* const sequence = checkPointer(new BAPCombinerSerial(m_unknown8, -1)); + sequence->addStatement(checkPointer(new BAPAResetControls(true, true, true, m_unknown8))); + BAPStatement* last; + if (!self->isOfType(ITSoldier)) { + BAPCombinerSerial* const leave = checkPointer(new BAPCombinerSerial(m_unknown8, -1)); + BAPConFalse* const stop = checkPointer(new BAPConFalse()); + BAPConTrue* const start = checkPointer(new BAPConTrue()); + leave->addStatement(checkPointer(new BAPATrigger(static_cast(10), start, stop, + 0x400ULL, m_unknown8, 0.0, false))); + leave->addStatement(checkPointer(new BAPICChangeVehicle(soldierHandle))); + last = leave; + } else { + if (m_nearRequest[bot->getBotId()] && !bot->getSquadMember()->getSquad()->haveConfirmedRepairRequest()) { + bot->getSquadMember()->getSquad()->confirmRepairRequested(); + bot->getCommunicationAgent()->enqueueRadioMessage(static_cast(6), + static_cast(3), 3, 2.0f, 0); + } + const Vec3 standPosition = m_standPosition[bot->getBotId()]; + const Vec3 segmentEnd = m_segmentEnd[bot->getBotId()]; + const unsigned long long drive = controls->getDriveControls(); + const float arriveSpeed = mobile->getMaxSpeed(); + const float speed = mobile->getMaxSpeed(); + sequence->addStatement(checkPointer(new BAPAMoveToFinding(bot, standPosition, speed, arriveSpeed, + 0, drive, m_unknown8, 0.0f, 0.0f))); + + // shipped defect: input masks shift a signed 32-bit one, then sign-extend to 64 bits. + const unsigned int activateBit = 1u << (weapon->getWeaponActivate() & 31); + const unsigned long long activateMask = static_cast(static_cast(static_cast(activateBit))); + BAPConFalse* const stop = checkPointer(new BAPConFalse()); + BAPConTrue* const start = checkPointer(new BAPConTrue()); + sequence->addStatement(checkPointer(new BAPATrigger(static_cast(weapon->getWeaponActivate()), + start, stop, activateMask, m_unknown8, 0.0, false))); + const unsigned long long directControls = self->getControlInfo()->getDriveControls(); + const Vec2 endXZ = {segmentEnd.x, segmentEnd.z}; + BAPConPosition* const atEnd = checkPointer(new BAPConPosition(endXZ, 1.0f)); + const float directArriveSpeed = mobile->getMaxSpeed(); + const float directSpeed = mobile->getMaxSpeed(); + sequence->addStatement(checkPointer(new BAPAMoveToDirect(bot, segmentEnd, directSpeed, directArriveSpeed, + atEnd, directControls, m_unknown8))); + sequence->addStatement(checkPointer(new BAPAResetControls(true, false, false, m_unknown8))); + BAPCombinerParallel* const repair = checkPointer(new BAPCombinerParallel(m_unknown8, -1, false)); + repair->addStatement(checkPointer(new BAPASoldierPose(static_cast(2), + checkPointer(new BAPConTrue()), m_unknown8, true))); + repair->addStatement(checkPointer(new BAPAOverrideSensingAgent())); + const unsigned long long lookControls = self->getControlInfo()->getLookControls(); + repair->addStatement(checkPointer(new BAPALookAtObject(bot, segment, 0.0f, checkPointer(new BAPConFalse()), + lookControls, m_unknown8, 0, 0.0f))); + const unsigned int fireBit = 1u << (weapon->getWeaponFire() & 31); + const unsigned long long fireMask = static_cast(static_cast(static_cast(fireBit))); + BAPConFalse* const abort = checkPointer(new BAPConFalse()); + BAPConFalse* const fireStop = checkPointer(new BAPConFalse()); + BAPConTrue* const fireStart = checkPointer(new BAPConTrue()); + repair->addStatement(checkPointer(new BAPATriggerContinously(static_cast(weapon->getWeaponFire()), + fireStart, fireStop, abort, fireMask, m_unknown8, 0.0))); + last = checkPointer(new BAPFlowCWhile(checkPointer(new BAPConTrue()), repair, true, m_unknown8)); + } + sequence->addStatement(last); + root->addStatement(sequence); + const unsigned int requestHandle = target->getHandle(); + bot->getSquadMember()->setCurrentRequestAction(2, requestHandle); + BAPIWFire* const wrapper = checkPointer(new BAPIWFire(bot, m_segment[bot->getBotId()], true, false, + weaponIndex, -1, root, m_unknown8)); + wrapper->mpOwner = this; + static_cast(bot)->resetAllControls(true, true, true); + return wrapper; +} + +// ELF 0x22F5E0: marks the bot initiated (BBPPattern +0x04) and stores the parameters; getBotId is +// called once per store. +void BBPBridgeRepair::init(unsigned int segment, int weaponIndex, Vec3 direction, Bot* bot, bool nearRequest, + Vec3 standPosition, Vec3 segmentEnd) +{ + m_initiated[bot->getBotId()] = true; + m_segment[bot->getBotId()] = segment; + m_weaponIndex[bot->getBotId()] = weaponIndex; + m_direction[bot->getBotId()] = direction; + m_nearRequest[bot->getBotId()] = nearRequest; + m_standPosition[bot->getBotId()] = standPosition; + m_segmentEnd[bot->getBotId()] = segmentEnd; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPBridgeRepair.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPBridgeRepair.h new file mode 100644 index 000000000..ce3a75de7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPBridgeRepair.h @@ -0,0 +1,45 @@ +// Bridge-repair plan parameters and generation, recovered from libaidll.so (Linux 1.5, ia-32). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPBRIDGEREPAIR_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPBRIDGEREPAIR_H + +#include "../../../../Math/Vec3.h" +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BB8A0 (6 words), operator new 0x24, package F-infantry. +class BBPBridgeRepair : public BBPPattern +{ +public: + explicit BBPBridgeRepair(int); // 0x22EC30 + virtual ~BBPBridgeRepair(); // 0x22F450 + + virtual BotScript* createPlan(Bot*); // 0x22F6E0, slot +0x08; from the base declaration + + // 0x22F5E0: void (stores only, %eax is left as the last getBotId result). + void init(unsigned int, int, Vec3, Bot*, bool, Vec3, Vec3); + +private: + // Constructor 0x22E4D0/0x22EC30, destructor 0x22F390/0x22F450/0x22F510; per-bot arrays are + // new [getMaxNBots] (IAISettings slot 0); init 0x22F5E0 writes them by Bot::getBotId. + /* +0x08 */ int m_unknown8; // pattern id carried by the generated plan + /* +0x0C */ unsigned int* m_segment; // -1; bridge segment Information handle [INFERRED] name + /* +0x10 */ int* m_weaponIndex; // -1; first weapon of type 1 [INFERRED] name + /* +0x14 */ Vec3* m_direction; // zeroed (Vec3 array constructor loop) + /* +0x18 */ bool* m_nearRequest; // false; segment within 50 m of the squad repair request + /* +0x1C */ Vec3* m_standPosition; // zeroed + /* +0x20 */ Vec3* m_segmentEnd; // zeroed +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPBRIDGEREPAIR_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPC4.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPC4.cpp new file mode 100644 index 000000000..230012c6e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPC4.cpp @@ -0,0 +1,171 @@ +// C4 pattern: places or detonates the bot's C4 (AI/AIDLL/AI/AIBotBehaviourPattern/BBPC4.cpp in the +// image). Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF +// address. +// +// static init: ELF 0x235010 (__tcf_0 0x235070, _GLOBAL__I 0x2350A0): the guard object only. + +#include "BBPC4.h" + +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAIdle.h" +#include "../AIBotActionPlan/BAPAPlaceC4.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConNot.h" +#include "../AIBotActionPlan/BAPConTime.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPConWeaponDetonatorIsActive.h" +#include "../AIBotActionPlan/BAPFlowCIf.h" +#include "../AIBotActionPlan/BAPIWFire.h" +#include "../AIBotActionPlan/BAPVariable.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +void dropPlan(Bot* bot) +{ + delete bot->getPlan(); + bot->setPlan(0); +} + +// One weapon key as the image builds it inline every time: a trigger of the key that starts at +// once (BAPConTrue) and never stops by condition (BAPConFalse), with the key's control bit +// (1 << key, sign-extended from int) and no repeat time. The key is read twice, for the controls +// and for the input map (right-to-left argument order: the controls' read comes first). +BAPATrigger* newKeyTrigger(const WeaponInfo* weapon, int (WeaponInfo::*key)() const, int patternId, bool flag) +{ + return checkPointer(new BAPATrigger(static_cast((weapon->*key)()), + checkPointer(new BAPConTrue()), checkPointer(new BAPConFalse()), + static_cast(1u << (weapon->*key)()), patternId, 0.0, flag)); +} + +} // namespace + +// ELF 0x2321F0 (C2) / 0x232370 (C1): BBPPattern(), +0x08 = id, +0x0C = checkPointer(new[getMaxNBots]). +BBPC4::BBPC4(int id) + : BBPPattern() +{ + m_id = id; + m_perBot = checkPointer(new unsigned int[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); +} + +// ELF 0x2324F0 (D2) / 0x232540 (D1) / 0x232590 (D0): delete[] +0x0C when set, then ~BBPPattern. +BBPC4::~BBPC4() +{ + if (m_perBot) + delete[] m_perBot; +} + +// ELF 0x232620 (listing). Builds, under a BAPIWFire(bot, -1, true, false, 4, -1, ..) wrapper, +// serial { reset controls, trigger(activate key of the C4 slot 4 weapon), +// if (detonator [not] active) trigger(alt-fire key), idle 0.7 s, trigger(fire key), +// [trigger(activate key of the slot 2 weapon)], place C4 (type 0, target) } +// m_placed (init's bool) selects the variant: placed: the alt-fire key when the detonator is NOT +// active and BAPAPlaceC4(.., false); not placed: when it IS active and BAPAPlaceC4(.., true). +// The script context is cleared first, also when the current plan of this pattern is kept, and the +// equipment handle is read once without use; as compiled. Returns 0 without equipment, unit, mobile +// or a slot 4 weapon. The bot's controls are reset after the plan is built. +BotScript* BBPC4::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + // 0x234F98 + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) + dropPlan(bot); + return 0; + } + + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + BAPContext* const context = bot->getScriptContext(); + context->clear(); + bot->getCurrentEquipment(); // 0x232692, result unused + + if (bot->hasPlan() && static_cast(bot->getPlan())->getPatternId() == m_id) + return bot->getPlan(); // 0x234F73 + if (bot->getPlan()) + dropPlan(bot); // 0x234F48 + + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + if (!equipment || !equipment->getUnit() || !equipment->getMobile()) + return 0; + IPIArmament* const armament = equipment->getArmament(); + WeaponInfo* const c4 = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(4)); // 0x23274B + if (!c4) + return 0; + + BAPATrigger* const activate = newKeyTrigger(c4, &WeaponInfo::getWeaponActivate, m_id, false); // 0x232880 + BAPCombinerSerial* const serial = checkPointer(new BAPCombinerSerial(m_id, -1)); + serial->addStatement(checkPointer(new BAPAResetControls(true, true, true, m_id))); + serial->addStatement(checkPointer(activate)); // checkPointer'd a second time (0x232945) + + // 0x23296B: the plan variable of the C4 weapon (inline BAPVariable, then list insert at begin). + BAPVariable* const weaponVariable = checkPointer(new BAPVariable(context, c4)); + context->addVariable(weaponVariable); + + BAPFlowCIf* detonate; + BAPAPlaceC4* place; + if (m_placed) + { + // 0x232A02 + detonate = checkPointer(new BAPFlowCIf( + checkPointer(new BAPConNot(checkPointer(new BAPConWeaponDetonatorIsActive(weaponVariable)))), + newKeyTrigger(c4, &WeaponInfo::getWeaponAltFire, m_id, true), 0, m_id, true, false)); + place = checkPointer(new BAPAPlaceC4(0, m_target, false)); + } + else + { + // 0x2340D0 + detonate = checkPointer(new BAPFlowCIf(checkPointer(new BAPConWeaponDetonatorIsActive(weaponVariable)), + newKeyTrigger(c4, &WeaponInfo::getWeaponAltFire, m_id, true), 0, m_id, true, + false)); + place = checkPointer(new BAPAPlaceC4(0, m_target, true)); + } + // 0x232C55 + serial->addStatement(detonate); + serial->addStatement(checkPointer(new BAPAIdle(checkPointer(new BAPConTime(0.7f, false, false, false)), 0ULL, m_id))); + serial->addStatement(newKeyTrigger(c4, &WeaponInfo::getWeaponFire, m_id, true)); + serial->addStatement(place); + + WeaponInfo* const other = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(2)); // 0x232E9E + if (other) + serial->addStatement(newKeyTrigger(other, &WeaponInfo::getWeaponActivate, m_id, false)); + + // 0x232FE2 + BAPIWFire* const root = checkPointer(new BAPIWFire(bot, 0xFFFFFFFFu, true, false, 4, -1, serial, m_id)); + root->setParent(this); // +0x04 (BotScript::mpOwner) + static_cast(bot)->resetAllControls(true, true, true); + return root; +} + +// ELF 0x2325E0: m_initiated[bot->getBotId()] = true (BBPPattern +0x04), then +0x10/+0x14. +void BBPC4::init(Bot* bot, bool placed, AIStrategicObject* target) +{ + m_initiated[bot->getBotId()] = true; + m_placed = placed; + m_target = target; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPC4.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPC4.h new file mode 100644 index 000000000..2e5c3fa1c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPC4.h @@ -0,0 +1,43 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPC4_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPC4_H + +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class AIStrategicObject; +class Bot; +class BotScript; + +// ELF: vtable 0x4BB920 (6 words), operator new 0x18, package F-infantry. +class BBPC4 : public BBPPattern +{ +public: + explicit BBPC4(int); // 0x232370 + virtual ~BBPC4(); // 0x232540 + + virtual BotScript* createPlan(Bot*); // 0x232620, slot +0x08; from the base declaration + + void init(Bot*, bool, AIStrategicObject*); // 0x2325E0; void [INFERRED]: %eax is left holding the bool argument, no caller reads it + +private: + /* +0x08 */ int m_id; // constructor argument [INFERRED] name (the pattern id) + /* +0x0C */ unsigned int* m_perBot; // new[getMaxNBots], checkPointer'd, never filled here [UNRESOLVED] use + /* +0x10 */ bool m_placed; // init's bool: BBC4 passes "own C4 is placed and the area is taken" [INFERRED] + /* +0x14 */ AIStrategicObject* m_target; // init's object +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPC4_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPCallForMedic.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPCallForMedic.cpp new file mode 100644 index 000000000..2b6f2994c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPCallForMedic.cpp @@ -0,0 +1,74 @@ +// Medic-request radio pattern, recovered from libaidll.so (Linux 1.5, ia-32). + +// static init: ELF 0x235730 (__tcf_0 0x235790, _GLOBAL__I 0x2357C0): 's Init object only. +#include + +#include "BBPCallForMedic.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPASendRadioMessage.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../../../../Math/Vec3.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2352E0 (C2), 0x235320 (C1). +BBPCallForMedic::BBPCallForMedic(int patternId) + : m_patternId(patternId) +{ +} + +// ELF 0x235360 (D2), 0x2353A0 (D1), 0x2353E0 (D0). +BBPCallForMedic::~BBPCallForMedic() +{ +} + +// ELF 0x235450 +BotScript* BBPCallForMedic::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) { + delete bot->getPlan(); + bot->setPlan(0); + } + return 0; + } + bot->getCurrentEquipment(); + if (!bot->hasPlan()) { + if (bot->getPlan()) { + delete bot->getPlan(); + bot->setPlan(0); + } + } else if (static_cast(bot->getPlan())->getPatternId() == m_patternId) { + return bot->getPlan(); + } + // shipped defect: a valid plan of another pattern is not deleted here. + bot->getSquadMember()->clearRequestAction(); + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + BAPASendRadioMessage* const plan = checkPointer(new BAPASendRadioMessage(static_cast(3), + static_cast(0), 5, 0.0f, m_patternId, -1)); + plan->mpOwner = this; + return plan; +} + +// ELF 0x235420 +void BBPCallForMedic::init(Bot* bot) +{ + m_initiated[bot->getBotId()] = true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPCallForMedic.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPCallForMedic.h new file mode 100644 index 000000000..f28b4c590 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPCallForMedic.h @@ -0,0 +1,35 @@ +// Medic-request radio pattern, recovered from libaidll.so (Linux 1.5, ia-32). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPCALLFORMEDIC_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPCALLFORMEDIC_H + +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BB980 (6 words), operator new 0xC, package H-deferred. +class BBPCallForMedic : public BBPPattern +{ +public: + explicit BBPCallForMedic(int); // 0x235320 + virtual ~BBPCallForMedic(); // 0x2353A0 + + virtual BotScript* createPlan(Bot*); // 0x235450, slot +0x08; from the base declaration + + void init(Bot*); // 0x235420; [INFERRED] ELF void + +private: + /* +0x08 */ int m_patternId; // [INFERRED] name: id passed to the generated radio statement +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPCALLFORMEDIC_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChange.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChange.cpp new file mode 100644 index 000000000..df6cfcba0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChange.cpp @@ -0,0 +1,538 @@ +// Change pattern: per-bot target vehicle/seat, entry position and get-in flags. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see +// docs/macos-ai-behaviour-plan.md. + +// static init: ELF 0x23DC90 (__tcf_0 0x23DCF0, _GLOBAL__I 0x23DD20): 's Init object only. +#include + +#include "BBPChange.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/CommunicationAgent.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPAMoveTo3d.h" +#include "../AIBotActionPlan/BAPAMoveTo3dObject.h" +#include "../AIBotActionPlan/BAPASendRadioMessage.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConPosition.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPICTurnLock.h" +#include "../Main/IAIPathfinding.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../../Math/Mat4.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPAUpdateVehicle.h" +#include "../AIBotActionPlan/BAPAUseFlareOnMissileLock.h" +#include "../AIBotActionPlan/BAPAMoveToFinding.h" +#include "../AIBotActionPlan/BAPAMoveToObjectFinding.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConAnd.h" +#include "../AIBotActionPlan/BAPConNot.h" +#include "../AIBotActionPlan/BAPConObjectBehind.h" +#include "../AIBotActionPlan/BAPConObjectDistance.h" +#include "../AIBotActionPlan/BAPConObjectEnemyOccupied.h" +#include "../AIBotActionPlan/BAPConObjectMoved.h" +#include "../AIBotActionPlan/BAPConObjectOccupied.h" +#include "../AIBotActionPlan/BAPConOr.h" +#include "../AIBotActionPlan/BAPFlowCIf.h" +#include "../AIBotActionPlan/BAPFlowCWhile.h" +#include "../AIBotActionPlan/BAPICChangeVehicle.h" +#include "../AIBotActionPlan/BAPIWChange.h" +#include "../AIBotActionPlan/BAPStatement.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../Main/IBotManager.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../../Math/Vec3.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2357E0 (C2) / 0x235CB0 (C1). After the BBPPattern base, four getMaxNBots-sized arrays, each +// checkPointer'd (the inlined "AI::Allocation failed" Debug blocks): +0x10 Vec3 (the new[] loop stores +// 0.0f, rodata 0x49CB34, into all three floats before the null test), +0x14 and +0x18 bool (left +// uninitialised), then +0x08 = the argument and +0x0C unsigned int (uninitialised). +BBPChange::BBPChange(int value) +{ + m_noPathfindingPos = checkPointer( + new Vec3[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]()); + m_sameVehicle = checkPointer(new bool[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); + m_getInConfirm = checkPointer(new bool[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); + m_patternId = value; + m_targets = checkPointer(new unsigned int[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); +} + +// ELF 0x236180 (D2) / 0x236210 (D1) / 0x2362A0 (D0): delete[] +0x0C, +0x14, +0x10, +0x18 (each when +// set), then the BBPPattern base. +BBPChange::~BBPChange() +{ + if (m_targets) + delete[] m_targets; + if (m_sameVehicle) + delete[] m_sameVehicle; + if (m_noPathfindingPos) + delete[] m_noPathfindingPos; + if (m_getInConfirm) + delete[] m_getInConfirm; +} + +namespace { + +// The plan-reset idiom of createPlan (debugger slot +0x164 -> clear vfn +0xC; plan slot +0x60, deleted +// through vfn +8, then setPlan(0) slot +0x64; script context slot +0x168 -> BAPContext::clear). The +// image inlines it three times with two different orders; the callers keep their order. +void clearDebugger(Bot* bot) +{ + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); +} + +void deletePlan(Bot* bot) +{ + if (bot->getPlan()) { + delete bot->getPlan(); + bot->setPlan(0); + } +} + +// Radius of an information's physical plug-in (+0x3C, IPIPhysical::getRadius vfn +0x2C); a seat that is +// not the primary object uses its primary's (getPrimaryObject(bot side), no null test in the image). +float radiusOf(Information* info, Bot* bot) +{ + if (info->isPrimary()) + return info->getPhysical()->getRadius(); + return informationManager->getInformation(info->getPrimaryObject(bot->getSide()))->getPhysical()->getRadius(); +} + +} // namespace + +// ELF 0x236A20. +BotScript* BBPChange::createPlan(Bot* bot) +{ + const unsigned int botId = bot->getBotId(); // esi + CommunicationAgent* const communication = bot->getCommunicationAgent(); // -0x180 + if (!m_initiated[bot->getBotId()]) { + // 0x23DC07: debugger, context, plan. + clearDebugger(bot); + bot->getScriptContext()->clear(); + deletePlan(bot); + return 0; + } + + // 0x236A8A..0x236AC5, -0x181 / -0x182: keep the running plan when it is this pattern's + // (BAPStatement +0x10) and wraps the same target (BAPIWChange +0x18). + bool otherPattern = false; + if (!bot->getPlan() || static_cast(bot->getPlan())->getPatternId() != m_patternId) + otherPattern = true; + bool otherTarget = false; + if (otherPattern || static_cast(bot->getPlan())->getTarget() != m_targets[botId]) + otherTarget = true; + if (!otherTarget) { + if (m_getInConfirm[botId] && communication->generalConfirmReceivedMessage(static_cast(1))) + communication->enqueueRadioMessage(static_cast(6), static_cast(6), 3, + 1.0f, -1); + return bot->getPlan(); + } + + static_cast(bot)->resetAllControls(true, true, true); + // -0x188 current equipment, -0x18C its IPIMobile, -0x190 its IPIPhysical, -0x198/-0x194 its drive + // controls. The image reads +0x38/+0x3C/+0x30 before the null test at 0x236CEE. + Information* const current = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* const mobile = current->getMobile(); + const unsigned long long driveControls = current->getControlInfo()->getDriveControls(); + // -0x19C target (the vehicle/seat), -0x1A0 its IPIUnit. + Information* const target = informationManager->getInformation(m_targets[bot->getBotId()]); + if (!target) { + // 0x23DB20: debugger, plan, context. + clearDebugger(bot); + deletePlan(bot); + bot->getScriptContext()->clear(); + return 0; + } + IPIUnit* const targetUnit = target->getUnit(); + // -0x1A8 = target radius (-0x1A4) + current radius (-0x1AC), float adds (0x236C98). + const float targetRadius = radiusOf(target, bot); + const float currentRadius = radiusOf(current, bot); + float radiusSum = targetRadius + currentRadius; + + // 0x236CAF: debugger, plan, context. + clearDebugger(bot); + deletePlan(bot); + bot->getScriptContext()->clear(); + if (!current) + return 0; + bot->getSquadMember()->clearRequestAction(); + + BAPStatement* plan; // the node the tail wraps + if (!current->isOfType(ITSoldier)) { + // 0x236D12 `testb $0x20, 0x6(%esi)`: the bot sits in a vehicle or stationary weapon. + BAPCombinerSerial* const sequence = checkPointer(new BAPCombinerSerial(m_patternId, -1)); // -0x1B0 + // Getting out to the bot's own soldier: confirm a pending type-0 message with 6 on channel 7. + if (m_targets[bot->getBotId()] == bot->getPlayer()->getSoldier()->getInformation(bot->getSide()) + && communication->generalConfirmReceivedMessage(static_cast(0))) + sequence->addStatement(checkPointer(new BAPASendRadioMessage( + static_cast(6), static_cast(7), 3, 1.0f, m_patternId, -1))); + + if (m_sameVehicle[bot->getBotId()]) { + // 0x23A260: another seat of the same vehicle: press its select key, then hand over the target. + BAPCombinerSerial* const seatChange = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + const int patternId = m_patternId; + const unsigned long long controls = 1ULL << targetUnit->getSelectKey(); // 64-bit shift (0x23A2CA) + BAPConFalse* const stop = checkPointer(new BAPConFalse()); + BAPConTrue* const start = checkPointer(new BAPConTrue()); + seatChange->addStatement(checkPointer(new BAPATrigger(targetUnit->getSelectKey(), start, stop, controls, + patternId, 0.0, false))); + seatChange->addStatement(checkPointer(new BAPICChangeVehicle(m_targets[bot->getBotId()]))); + sequence->addStatement(seatChange); + plan = sequence; + } else if (!current->getMobile()) { + // 0x236DEB: a stationary weapon: press enter/exit (input 10, controls 0x400). + BAPCombinerSerial* const leave = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + const int patternId = m_patternId; + BAPConFalse* const stop = checkPointer(new BAPConFalse()); + BAPConTrue* const start = checkPointer(new BAPConTrue()); + leave->addStatement(checkPointer(new BAPATrigger(static_cast(10), start, stop, 0x400ULL, + patternId, 0.0, false))); + leave->addStatement(checkPointer(new BAPICChangeVehicle(m_targets[bot->getBotId()]))); + sequence->addStatement(leave); + plan = sequence; + } else { + // 0x237822: drive (or fly) to the target first. -0x1A8 becomes radiusSum * 1.2 + 50. + radiusSum = radiusSum * 1.2f + 50.0f; + Vec2 targetXZ; + targetXZ.x = target->getPosition().x; + targetXZ.y = target->getPosition().z; + BAPConPosition* arrived = checkPointer(new BAPConPosition(targetXZ, radiusSum)); // -0x26C + + bool toEntryPosition = false; // -0x276 / -0x275 + if (targetUnit->useNoPathfindingToGetToObject() || !target->hasMobile()) + toEntryPosition = true; + if (toEntryPosition && !target->isPrimary()) + toEntryPosition = + !informationManager->getInformation(target->getPrimaryObject(bot->getSide()))->hasMobile(); + + BAPAction* move; + if (toEntryPosition) { + if (!current->isOfType(ITAir)) { + // 0x239CF0 + BAPConAnd* const arrivedBehind = checkPointer(new BAPConAnd()); + arrivedBehind->addCondition(arrived); + arrivedBehind->addCondition( + checkPointer(new BAPConObjectBehind(m_targets[bot->getBotId()], -0.95f, false))); + const int patternId = m_patternId; + const float arriveSpeed = mobile->getMaxSpeed() * 0.75f; + const float speed = mobile->getMaxSpeed(); + move = checkPointer(new BAPAMoveToFinding(bot, m_noPathfindingPos[bot->getBotId()], speed, arriveSpeed, + arrivedBehind, driveControls, patternId, 0.0f, 0.0f)); + } else { + // 0x239B40: flag 0x10 (air): 3d move to the target's position. + const int patternId = m_patternId; + const float arriveSpeed = mobile->getMaxSpeed() * 0.75f; + const float speed = mobile->getMaxSpeed(); + move = checkPointer(new BAPAMoveTo3d(bot, target->getPosition(), speed, arriveSpeed, arrived, + driveControls, 25.0f, patternId)); + } + } else if (!current->isOfType(ITAir)) { + bool aroundAircraft = false; + Vec3 position; + if (target->isOfType(ITAir) && !target->isOfType(ITHelicopter)) { + // 0x239064: the target is an aircraft (0x10 without 0x20): a navigable point behind + // or beside it. + position = target->getPosition(); + const int equipmentType = current->getUnit()->getEquipmentType(); + const int vehicleNumber = current->getMobile()->getVehicleNumber(); + aroundAircraft = getPosAroundAircraft(target, vehicleNumber, equipmentType, position); + } + if (aroundAircraft) { + // 0x2390EF: radius = the current equipment's own radius (-0x1AC); the first + // BAPConPosition is not freed. + Vec2 positionXZ; + positionXZ.x = position.x; + positionXZ.y = position.z; + arrived = checkPointer(new BAPConPosition(positionXZ, currentRadius)); + const int patternId = m_patternId; + const float arriveSpeed = mobile->getMaxSpeed() * 0.5f; + const float speed = mobile->getMaxSpeed(); + move = checkPointer(new BAPAMoveToFinding(bot, position, speed, arriveSpeed, arrived, driveControls, + patternId, 0.0f, 0.0f)); + } else { + // 0x23791C / 0x2393C0 + BAPConAnd* const repath = checkPointer(new BAPConAnd()); + repath->addCondition( + checkPointer(new BAPConObjectDistance(m_targets[bot->getBotId()], 20.0f, true, false, false))); + repath->addCondition(checkPointer(new BAPConObjectMoved(m_targets[bot->getBotId()], 10.0f))); + const int patternId = m_patternId; + const float arriveSpeed = 0.5f * mobile->getMaxSpeed(); + const float speed = mobile->getMaxSpeed(); + move = checkPointer(new BAPAMoveToObjectFinding(bot, m_targets[bot->getBotId()], 0.5f, speed, + arriveSpeed, arrived, driveControls, patternId, + repath, 0.0f, -1)); + } + } else { + // 0x239950: flying: 3d move to the object. + const int patternId = m_patternId; + const float arriveSpeed = 0.5f * mobile->getMaxSpeed(); + const float speed = mobile->getMaxSpeed(); + move = checkPointer(new BAPAMoveTo3dObject(m_targets[bot->getBotId()], 0.5f, speed, arriveSpeed, 25.0f, + arrived, driveControls, patternId)); + } + sequence->addStatement(move); + + // 0x237B2A: then press exit/enter (input 10, controls 0x400) unless an enemy took the target. + BAPAUpdateVehicle* const update = checkPointer(new BAPAUpdateVehicle(m_patternId)); + BAPConObjectEnemyOccupied* const enemy = + checkPointer(new BAPConObjectEnemyOccupied(m_targets[bot->getBotId()])); + const int patternId = m_patternId; + BAPConTrue* const start = checkPointer(new BAPConTrue()); + BAPATrigger* const enter = checkPointer(new BAPATrigger(static_cast(10), start, enemy, + 0x400ULL, patternId, 0.0, false)); + // 0x237C66: getting out to the soldier from the primary seat of a ground vehicle whose health + // (IPIPhysical vfn +0x14) is below IBotManager::getVehicleBailValue: also press input 0x2F + // (controls bit 47). + if (target->isOfType(ITSoldier) && current->isPrimary() + && !current->isOfType(ITAir) && !current->isOfType(ITHelicopter)) { + if (current->getPhysical()->getHealth() < IBotManager::instance->getVehicleBailValue()) { + const int bailPatternId = m_patternId; + BAPConFalse* const bailStop = checkPointer(new BAPConFalse()); + BAPConTrue* const bailStart = checkPointer(new BAPConTrue()); + sequence->addStatement(checkPointer(new BAPATrigger(static_cast(0x2F), bailStart, + bailStop, 0x800000000000ULL, bailPatternId, 0.0, + false))); + } + } + sequence->addStatement(checkPointer(new BAPICTurnLock(true))); + sequence->addStatement(enter); + sequence->addStatement(update); + sequence->addStatement(checkPointer(new BAPICTurnLock(false))); + + BAPCombinerParallel* const withChange = checkPointer(new BAPCombinerParallel(m_patternId, -1, false)); + withChange->addStatement(checkPointer(new BAPICChangeVehicle(m_targets[bot->getBotId()]))); + withChange->addStatement(sequence); + plan = withChange; + } + } else { + // 0x23AF40: on foot, walk to the target and get in. + BAPCombinerParallel* const approach = // -0x3A8 + checkPointer(new BAPCombinerParallel(m_patternId, false, -1, false)); + + // -0x3AE / -0x3AD: walk straight to the stored entry position when the target's unit wants no + // pathfinding or the target cannot move; a seat counts as movable when its primary is. + bool toEntryPosition = false; + if (targetUnit->useNoPathfindingToGetToObject() || !target->hasMobile()) + toEntryPosition = true; + if (toEntryPosition && !target->isPrimary()) + toEntryPosition = !informationManager->getInformation(target->getPrimaryObject(bot->getSide()))->hasMobile(); + + BAPAction* move; + if (toEntryPosition) { + // 0x23D384 + BAPConObjectOccupied* const occupied = checkPointer(new BAPConObjectOccupied(m_targets[bot->getBotId()])); + BAPConObjectEnemyOccupied* const enemy = + checkPointer(new BAPConObjectEnemyOccupied(m_targets[bot->getBotId()])); + BAPConOr* const taken = checkPointer(new BAPConOr()); + taken->addCondition(occupied); + taken->addCondition(enemy); + const int patternId = m_patternId; + const float arriveSpeed = mobile->getMaxSpeed() * 0.75f; + const float speed = mobile->getMaxSpeed(); + move = checkPointer(new BAPAMoveToFinding(bot, m_noPathfindingPos[bot->getBotId()], speed, arriveSpeed, taken, + driveControls, patternId, 0.5f, 0.0f)); + } else { + // 0x23AFEB + BAPConObjectOccupied* const occupied = checkPointer(new BAPConObjectOccupied(m_targets[bot->getBotId()])); + BAPConObjectEnemyOccupied* const enemy = + checkPointer(new BAPConObjectEnemyOccupied(m_targets[bot->getBotId()])); + BAPConOr* const taken = checkPointer(new BAPConOr()); // -0x3C4 + taken->addCondition(occupied); + taken->addCondition(enemy); + BAPConAnd* const repath = checkPointer(new BAPConAnd()); // -0x3CC + repath->addCondition(checkPointer(new BAPConObjectDistance(m_targets[bot->getBotId()], 10.0f, true, false, false))); + repath->addCondition(checkPointer(new BAPConObjectMoved(m_targets[bot->getBotId()], 5.0f))); + const int patternId = m_patternId; + const float arriveSpeed = mobile->getMaxSpeed() * 0.5f; + const float speed = mobile->getMaxSpeed(); + move = checkPointer(new BAPAMoveToObjectFinding(bot, m_targets[bot->getBotId()], 0.0f, speed, arriveSpeed, + taken, driveControls, patternId, repath, 0.0f, -1)); + } + approach->addStatement(move); + + // 0x23B2E3: press the enter key (input 10, controls 0x400) once within reach (radius sum + 1), + // and, for objects entered without pathfinding, from behind (dot <= -0.8). + BAPConObjectDistance* const reach = // -0x41C + checkPointer(new BAPConObjectDistance(m_targets[bot->getBotId()], radiusSum + 1.0f, false, false, false)); + BAPCondition* enterCondition = reach; + if (targetUnit->useNoPathfindingToGetToObject()) { + BAPConAnd* const both = checkPointer(new BAPConAnd()); // -0x424 + both->addCondition(reach); + both->addCondition(checkPointer(new BAPConObjectBehind(m_targets[bot->getBotId()], -0.8f, false))); + enterCondition = both; + } + BAPATrigger* const enter = checkPointer(new BAPATrigger( // -0x434 + static_cast(10), enterCondition, 0, 0x400ULL, m_patternId, 0.0, false)); + BAPAUpdateVehicle* const update = checkPointer(new BAPAUpdateVehicle(m_patternId)); // -0x43C + approach->addStatement(enter); + + BAPCombinerSerial* const sequence = checkPointer(new BAPCombinerSerial(m_patternId, -1)); // -0x444 + // -0x449 / -0x44A: messages of type 1 / 0 waiting (std::list not empty). + const bool type1Waiting = !communication->getReceivedMessages(static_cast(1)).empty(); + const bool type0Waiting = !communication->getReceivedMessages(static_cast(0)).empty(); + // -0x450 the target's primary, -0x454 its IAIObject (read before the null test), -0x458 its bot. + Information* const primary = informationManager->getInformation(target->getPrimaryObject(bot->getSide())); + // shipped defect: the primary is dereferenced before its null test, and the distance + // calculation below runs only for a null primary. + IAIObject* const primaryObject = primary->getAIObject(); + Bot* const primaryBot = IBotManager::instance->getBot(primaryObject); + float primaryDistanceSqr = 0.0f; + if (!primary) { + const Mat4& primaryTransform = primary->getTransformation(); + const Mat4& currentTransform = current->getTransformation(); + const Vec3 delta = {primaryTransform.m[12] - currentTransform.m[12], + primaryTransform.m[13] - currentTransform.m[13], + primaryTransform.m[14] - currentTransform.m[14]}; + primaryDistanceSqr = delta.x * delta.x + delta.y * delta.y + delta.z * delta.z; + } + // 0x23B558: ask the driver for a ride when the bot walks into a manned vehicle's seat. + if (!m_sameVehicle[bot->getBotId()] && current->isOfType(ITSoldier) + && primaryObject->getPlayerId() >= 0 && primary && primary->hasMobile() && primaryDistanceSqr < 400.0f + && !type1Waiting && !type0Waiting) { + BAPConObjectOccupied* const driverIn = checkPointer(new BAPConObjectOccupied(primary->getHandle())); // -0x464 + BAPASendRadioMessage* const ask = checkPointer(new BAPASendRadioMessage( // -0x46C + static_cast(2), static_cast(6), 3, 0.0f, m_patternId, + primaryObject->getPlayerId())); + BAPFlowCIf* const askIfManned = checkPointer(new BAPFlowCIf(driverIn, ask, 0, m_patternId, false, false)); + sequence->addStatement(askIfManned); + // 0x23C453: CommunicationAgent +0x5C = the driver's player id (IAIObject +0x148) when the + // driver is a bot, else 0xFF. + if (primaryBot) + communication->setInt92(primaryObject->getPlayerId()); + else + communication->setInt92(0xFF); + } + + // 0x23B57D: loop the approach until the target is occupied, then re-read the equipment. + BAPFlowCWhile* const untilInside = checkPointer(new BAPFlowCWhile( // -0x47C + checkPointer(new BAPConNot(checkPointer(new BAPConObjectOccupied(m_targets[bot->getBotId()])))), approach, + false, m_patternId)); + sequence->addStatement(untilInside); + sequence->addStatement(update); + + BAPCombinerParallel* const withChange = checkPointer(new BAPCombinerParallel(m_patternId, -1, false)); // -0x498 + withChange->addStatement(checkPointer(new BAPICChangeVehicle(m_targets[bot->getBotId()]))); + withChange->addStatement(sequence); + + BAPCombinerSerial* const root = checkPointer(new BAPCombinerSerial(m_patternId, -1)); // -0x4A8 + if (m_getInConfirm[bot->getBotId()] + && communication->generalConfirmReceivedMessage(static_cast(1))) + root->addStatement(checkPointer(new BAPASendRadioMessage( + static_cast(6), static_cast(6), 2, 1.0f, m_patternId, -1))); + root->addStatement(withChange); + plan = root; + } + + // Shared tail (inlined after every branch, 0x23B7B3 here): in a vehicle, run the plan beside + // BAPAUseFlareOnMissileLock (controls bit 47); wrap it in BAPIWChange (books the target), owner = this + // (0x2370E0). + BAPStatement* wrapped = plan; + if (!current->isOfType(ITSoldier)) { + BAPCombinerParallel* const flares = checkPointer(new BAPCombinerParallel(m_patternId, true, -1, false)); + flares->addStatement(checkPointer(new BAPAUseFlareOnMissileLock(bot, 0x800000000000ULL, m_patternId))); + flares->addStatement(plan); + wrapped = flares; + } + const int playerId = bot->getPlayerId(); + BAPIWChange* const wrapper = + checkPointer(new BAPIWChange(m_targets[bot->getBotId()], wrapped, m_patternId, playerId)); + wrapper->mpOwner = this; + return wrapper; +} + +// ELF 0x236340: five getBotId (Bot slot +0xE8) calls, one per store: initiated (+0x04) = true, +// +0x14 = the first bool, +0x0C = handle, +0x10 = position (three floats), +0x18 = the second bool. +void BBPChange::init(unsigned int handle, const Vec3& position, bool sameVehicle, bool getInConfirm, Bot* bot) +{ + m_initiated[bot->getBotId()] = true; + m_sameVehicle[bot->getBotId()] = sameVehicle; + m_targets[bot->getBotId()] = handle; + m_noPathfindingPos[bot->getBotId()] = position; + m_getInConfirm[bot->getBotId()] = getInConfirm; +} + +// ELF 0x2363F0: as above without the position. +void BBPChange::init(unsigned int handle, bool sameVehicle, bool getInConfirm, Bot* bot) +{ + m_initiated[bot->getBotId()] = true; + m_sameVehicle[bot->getBotId()] = sameVehicle; + m_targets[bot->getBotId()] = handle; + m_getInConfirm[bot->getBotId()] = getInConfirm; +} + +// ELF 0x236470: +0x18[getBotId] = confirm. +void BBPChange::setGetInConfirm(bool confirm, Bot* bot) +{ + m_getInConfirm[bot->getBotId()] = confirm; +} + +// ELF 0x2364A0: IAIPathfinding::findClosestValidPolygon (vfn +0x94) on map `map` from `from` towards +// `to` with 10 as the search argument and `type` last; the found point (zero-initialised) goes to `out` +// in XZ whatever the answer. The Vec3 arguments arrive by invisible reference (GCC 3.3 class by value). +bool BBPChange::findValidNavPosToAir(int map, int type, Vec3 from, Vec3 to, Vec2& out) +{ + Vec3 found; + found.x = 0.0f; + found.y = 0.0f; + found.z = 0.0f; + unsigned int island; + unsigned int polygon; + const bool valid = static_cast(IAIPathfinding::instance) + ->findClosestValidPolygon(polygon, island, found, map, from, to, 10, type); + vec3ToVec2XZ(found, out); + return valid; +} + +// ELF 0x236540: three candidate segments around the aircraft, r = its IPIPhysical radius (vfn +0x2C), +// p = transformation row 3, f = row 2, s = row 0: behind (p - 2r f -> p - 3r f), right (p + r s -> +// p + 3r s), left (p - r s -> p - 3r s). The first valid one is written to `position` in XZ (y kept). +bool BBPChange::getPosAroundAircraft(Information* aircraft, int map, int type, Vec3& position) +{ + const Mat4& m = aircraft->getTransformation(); + const float r = aircraft->getPhysical()->getRadius(); + const Vec3 p = {m.m[12], m.m[13], m.m[14]}; + Vec2 found; + found.x = 0.0f; + found.y = 0.0f; + + Vec3 f = {m.m[8], m.m[9], m.m[10]}; + Vec3 to = {p.x - f.x * 3.0f * r, p.y - f.y * 3.0f * r, p.z - f.z * 3.0f * r}; + Vec3 from = {p.x - f.x * 2.0f * r, p.y - f.y * 2.0f * r, p.z - f.z * 2.0f * r}; + if (!findValidNavPosToAir(map, type, from, to, found)) { + const Vec3 s = {m.m[0], m.m[1], m.m[2]}; + to = {s.x * 3.0f * r + p.x, s.y * 3.0f * r + p.y, s.z * 3.0f * r + p.z}; + from = {p.x + s.x * r, p.y + s.y * r, p.z + s.z * r}; + if (!findValidNavPosToAir(map, type, from, to, found)) { + const Vec3 s2 = {m.m[0], m.m[1], m.m[2]}; + to = {p.x - s2.x * 3.0f * r, p.y - s2.y * 3.0f * r, p.z - s2.z * 3.0f * r}; + from = {p.x - s2.x * r, p.y - s2.y * r, p.z - s2.z * r}; + if (!findValidNavPosToAir(map, type, from, to, found)) + return false; + } + } + vec2ToVec3XZ(found, position); + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChange.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChange.h new file mode 100644 index 000000000..c155b88f1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChange.h @@ -0,0 +1,49 @@ +// Change pattern: per-bot target vehicle/seat, entry position and get-in flags that BBChange's urgency +// fills (init / setGetInConfirm) and createPlan consumes. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see +// docs/macos-ai-behaviour-plan.md. Virtual functions are in ELF vtable slot order (vtable check). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPCHANGE_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPCHANGE_H + +#include "../../../../Math/Vec3.h" +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; +class Information; + +// ELF: vtable 0x4BBA00 (6 words), operator new 0x1C, package F-infantry. +class BBPChange : public BBPPattern +{ +public: + explicit BBPChange(int); // 0x235CB0 + virtual ~BBPChange(); // 0x236210 + + virtual BotScript* createPlan(Bot*); // 0x236A20, slot +0x08; from the base declaration + + void init(unsigned int, const Vec3&, bool, bool, Bot*); // 0x236340; ELF void (no result register) + void init(unsigned int, bool, bool, Bot*); // 0x2363F0; ELF void + void setGetInConfirm(bool, Bot*); // 0x236470; ELF void + bool findValidNavPosToAir(int, int, Vec3, Vec3, Vec2&); // 0x2364A0; [INFERRED] ELF bool, callers {'bool': 2} + bool getPosAroundAircraft(Information*, int, int, Vec3&); // 0x236540; [INFERRED] ELF int, callers {'bool': 1} + +private: + // Every array is new[]'d with IAISettings::getMaxNBots (slot 0) entries and indexed by Bot::getBotId. + /* +0x08 */ int m_patternId; // the constructor argument: the pattern id the plan nodes carry + /* +0x0C */ unsigned int* m_targets; // init: the vehicle/seat handle + /* +0x10 */ Vec3* m_noPathfindingPos; // value-initialised (0,0,0); init(handle, pos, ...) only // name: AIDLL_r assert 0x100FB800 (+0x10) + /* +0x14 */ bool* m_sameVehicle; // [INFERRED] name: init's first bool, BBChange passes "same primary object" + /* +0x18 */ bool* m_getInConfirm; // init's second bool and setGetInConfirm (named after the setter) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPCHANGE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeLandingCraft.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeLandingCraft.cpp new file mode 100644 index 000000000..5a814eddd --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeLandingCraft.cpp @@ -0,0 +1,133 @@ +// Seat-change pattern for landing craft (AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeLandingCraft.cpp in +// the image). Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its +// ELF address. createPlan was checked against the listing for the trigger arguments. + +// static init: ELF 0x23F620 (__tcf_0 0x23F680, _GLOBAL__I 0x23F6B0): 's Init object only. +#include + +#include "BBPChangeLandingCraft.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPICChangeVehicle.h" +#include "../AIBotActionPlan/BAPIWChange.h" +#include "../AIBotActionPlan/BAPStatement.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x23DFD0: BBPPattern(), the vtable store (GOT -0x280 + 8), `new bool[getMaxNBots()]` into +// +0x10, the argument at +0x08, then `new unsigned int[getMaxNBots()]` into +0x0C (both not +// initialised, each through the inlined checkPointer; operator new 0x14). The image's order. +BBPChangeLandingCraft::BBPChangeLandingCraft(int id) +{ + m_sameVehicle = checkPointer(new bool[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); + m_patternId = id; + m_target = checkPointer(new unsigned int[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); +} + +// ELF 0x23E260 (D2) / 0x23E2C0 (D1) / 0x23E320 (D0): delete[] +0x0C, then +0x10 (each when set), then +// ~BBPPattern. +BBPChangeLandingCraft::~BBPChangeLandingCraft() +{ + if (m_target) + delete[] m_target; + if (m_sameVehicle) + delete[] m_sameVehicle; +} + +// ELF 0x23E400. Keeps a BAPIWChange of this pattern for the same target; otherwise drops the plan +// and builds `IWChange(target, serial(trigger, change vehicle))`: the trigger presses the target +// seat's select key when init named a seat of the same vehicle, else enter/exit (input 10, controls +// 0x400). The target's information is not null-checked before its unit is read; without own +// equipment information nothing is built. +BotScript* BBPChangeLandingCraft::createPlan(Bot* bot) +{ + const unsigned int botId = bot->getBotId(); + if (!m_initiated[bot->getBotId()]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } + return 0; + } + + bool otherPattern = false; + if (!bot->getPlan() || static_cast(bot->getPlan())->getPatternId() != m_patternId) + otherPattern = true; + bool otherTarget = false; + if (otherPattern || static_cast(bot->getPlan())->getTarget() != m_target[botId]) + otherTarget = true; + if (!otherTarget) + return bot->getPlan(); + + bot->getSquadMember()->clearRequestAction(); + Information* const current = informationManager->getInformation(bot->getCurrentEquipment()); + Information* const target = informationManager->getInformation(m_target[bot->getBotId()]); + IPIUnit* const targetUnit = target->getUnit(); + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } + bot->getScriptContext()->clear(); + if (!current) + return 0; + + BAPCombinerSerial* const sequence = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + if (m_sameVehicle[bot->getBotId()]) + { + const int patternId = m_patternId; + const unsigned long long controls = 1ULL << targetUnit->getSelectKey(); // 64-bit shift (0x23E618) + BAPConFalse* const stop = checkPointer(new BAPConFalse()); + BAPConTrue* const start = checkPointer(new BAPConTrue()); + sequence->addStatement(checkPointer(new BAPATrigger(targetUnit->getSelectKey(), start, stop, controls, + patternId, 0.0, false))); + } + else + { + const int patternId = m_patternId; + BAPConFalse* const stop = checkPointer(new BAPConFalse()); + BAPConTrue* const start = checkPointer(new BAPConTrue()); + sequence->addStatement(checkPointer(new BAPATrigger(static_cast(10), start, stop, + 0x400ULL, patternId, 0.0, false))); + } + sequence->addStatement(checkPointer(new BAPICChangeVehicle(m_target[bot->getBotId()]))); + const int playerId = bot->getPlayerId(); + BAPIWChange* const wrapper = + checkPointer(new BAPIWChange(m_target[bot->getBotId()], sequence, m_patternId, playerId)); + wrapper->setParent(this); // +0x04 (BotScript::mpOwner) + return wrapper; +} + +// ELF 0x23E390: three getBotId calls, one per store. +void BBPChangeLandingCraft::init(unsigned int target, bool sameVehicle, Bot* bot) +{ + m_initiated[bot->getBotId()] = true; + m_sameVehicle[bot->getBotId()] = sameVehicle; + m_target[bot->getBotId()] = target; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeLandingCraft.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeLandingCraft.h new file mode 100644 index 000000000..528163645 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeLandingCraft.h @@ -0,0 +1,38 @@ +// Seat-change pattern for landing craft: moves the bot to another seat or out of the vehicle. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPCHANGELANDINGCRAFT_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPCHANGELANDINGCRAFT_H + +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BBA80 (6 words), operator new 0x14, package G-vehicles. +class BBPChangeLandingCraft : public BBPPattern +{ +public: + explicit BBPChangeLandingCraft(int); // 0x23DFD0 + virtual ~BBPChangeLandingCraft(); // 0x23E2C0 + + virtual BotScript* createPlan(Bot*); // 0x23E400, slot +0x08; from the base declaration + + void init(unsigned int target, bool sameVehicle, Bot*); // 0x23E390; ELF void (no return value materialized) + + /* +0x08 */ int m_patternId; // the constructor argument + /* +0x0C */ unsigned int* m_target; // per bot: init's handle [INFERRED] name + /* +0x10 */ bool* m_sameVehicle; // per bot: init's bool [INFERRED] name (as BBPChange's) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPCHANGELANDINGCRAFT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeTeleport.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeTeleport.cpp new file mode 100644 index 000000000..f095ed8b1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeTeleport.cpp @@ -0,0 +1,125 @@ +// Teleport and same-vehicle seat-change plans, recovered from libaidll.so (Linux 1.5, ia-32). + +// static init: ELF 0x240ED0 (__tcf_0 0x240F30, _GLOBAL__I 0x240F60): 's Init object only. +#include + +#include "BBPChangeTeleport.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConTime.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPFlowCWait.h" +#include "../AIBotActionPlan/BAPICChangeVehicle.h" +#include "../AIBotActionPlan/BAPIWChange.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIStrategic/SAI.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AIMain.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../../Math/Vec3.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x23F960: BBPPattern(), the vtable store (GOT -0xFC0 + 8), `new bool[getMaxNBots()]` into +// +0x10, the argument at +0x08, then `new unsigned int[getMaxNBots()]` into +0x0C (both not +// initialised, each through the inlined checkPointer; operator new 0x14). The image's order. +BBPChangeTeleport::BBPChangeTeleport(int id) +{ + m_sameVehicle = checkPointer(new bool[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); + m_patternId = id; + m_target = checkPointer(new unsigned int[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); +} + +// ELF 0x23FBF0 (D2) / 0x23FC50 (D1) / 0x23FCB0 (D0): delete[] +0x0C, then +0x10 (each when set), then +// ~BBPPattern. +BBPChangeTeleport::~BBPChangeTeleport() +{ + if (m_target) + delete[] m_target; + if (m_sameVehicle) + delete[] m_sameVehicle; +} + +// ELF 0x23FD90 +BotScript* BBPChangeTeleport::createPlan(Bot* bot) +{ + const unsigned int botId = bot->getBotId(); + if (!m_initiated[bot->getBotId()]) { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) { + delete bot->getPlan(); + bot->setPlan(0); + } + return 0; + } + const bool otherPattern = !bot->getPlan() + || static_cast(bot->getPlan())->getPatternId() != m_patternId; + const bool otherTarget = otherPattern + || static_cast(bot->getPlan())->getTarget() != m_target[botId]; + if (!otherTarget) + return bot->getPlan(); + + bot->getSquadMember()->clearRequestAction(); + Information* const current = informationManager->getInformation(bot->getCurrentEquipment()); + Information* const target = informationManager->getInformation(m_target[bot->getBotId()]); + IPIUnit* const targetUnit = target->getUnit(); + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + if (bot->getPlan()) { + delete bot->getPlan(); + bot->setPlan(0); + } + bot->getScriptContext()->clear(); + if (!current) + return 0; + + bot->setChangeTarget(m_target[bot->getBotId()]); + BAPCombinerParallel* plan; + if (m_sameVehicle[bot->getBotId()]) { + plan = checkPointer(new BAPCombinerParallel(m_patternId, -1, false)); + plan->addStatement(checkPointer(new BAPICChangeVehicle(m_target[bot->getBotId()]))); + const unsigned long long controls = 1ULL << targetUnit->getSelectKey(); + BAPConFalse* const stop = checkPointer(new BAPConFalse()); + BAPConTrue* const start = checkPointer(new BAPConTrue()); + plan->addStatement(checkPointer(new BAPATrigger(targetUnit->getSelectKey(), start, stop, controls, + m_patternId, 0.0, false))); + } else { + const unsigned int teleporter = bot->getBotId(); + IAIMain::m_instance->getSAI(bot->getSide())->registerTeleporter(teleporter); + plan = checkPointer(new BAPCombinerParallel(m_patternId, -1, false)); + plan->addStatement(checkPointer(new BAPICChangeVehicle(m_target[bot->getBotId()]))); + plan->addStatement(checkPointer(new BAPFlowCWait(checkPointer(new BAPConTime(2.0, false, false, false)), + m_patternId))); + } + const int playerId = bot->getPlayerId(); + BAPIWChange* const wrapper = checkPointer(new BAPIWChange(m_target[bot->getBotId()], plan, m_patternId, playerId)); + wrapper->mpOwner = this; + return wrapper; +} + +// ELF 0x23FD20 +void BBPChangeTeleport::init(unsigned int target, bool sameVehicle, Bot* bot) +{ + m_initiated[bot->getBotId()] = true; + m_sameVehicle[bot->getBotId()] = sameVehicle; + m_target[bot->getBotId()] = target; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeTeleport.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeTeleport.h new file mode 100644 index 000000000..f033a2864 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeTeleport.h @@ -0,0 +1,36 @@ +// Teleport and same-vehicle seat-change pattern, recovered from libaidll.so (Linux 1.5, ia-32). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPCHANGETELEPORT_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPCHANGETELEPORT_H + +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BBB00 (6 words), operator new 0x14, package G-vehicles. +class BBPChangeTeleport : public BBPPattern +{ +public: + explicit BBPChangeTeleport(int); // 0x23F960 + virtual ~BBPChangeTeleport(); // 0x23FC50 + + virtual BotScript* createPlan(Bot*); // 0x23FD90, slot +0x08; from the base declaration + + void init(unsigned int, bool, Bot*); // 0x23FD20; [INFERRED] ELF void + + /* +0x08 */ int m_patternId; // the constructor argument + /* +0x0C */ unsigned int* m_target; // per bot: init's handle [INFERRED] name + /* +0x10 */ bool* m_sameVehicle; // per bot: init's bool [INFERRED] name (as BBPChange's) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPCHANGETELEPORT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPDefuseMines.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPDefuseMines.cpp new file mode 100644 index 000000000..39e65dafc --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPDefuseMines.cpp @@ -0,0 +1,205 @@ +// Defuse-mines pattern: per-bot plan parameters that BBDefuseMines::calculateUrgency stores through +// init. Recovered from libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see +// docs/macos-ai-behaviour-plan.md. + +// static init: ELF 0x244060 (__tcf_0 0x2440C0, _GLOBAL__I 0x2440F0): 's Init object only. +#include + +#include "BBPDefuseMines.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SensingAgent.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPALookAtPoint.h" +#include "../AIBotActionPlan/BAPAMoveToFinding.h" +#include "../AIBotActionPlan/BAPAOverrideSensingAgent.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPASoldierPose.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPATriggerContinously.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPFlowCWhile.h" +#include "../AIBotActionPlan/BAPICChangeVehicle.h" +#include "../AIBotActionPlan/BAPIWDefuseMines.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x240F80 (C2) / 0x2414A0 (C1): BBPPattern(), the argument to +0x08, four getMaxNBots-sized +// arrays (each checkPointer'd; the Vec3 ones run the zeroing Vec3 constructor loop, rodata +// 0x49CB34 0.0f, reproduced here by value-initialisation), then for each bot (getMaxNBots re-read +// per pass) mine and weapon index -1. +BBPDefuseMines::BBPDefuseMines(int value) + : BBPPattern() +{ + m_unknown8 = value; + m_mine = checkPointer(new unsigned int[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); + m_weaponIndex = checkPointer(new int[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); + m_minePosition = checkPointer(new Vec3[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]()); + m_targetPosition = checkPointer(new Vec3[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]()); + for (int i = 0; i < static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); ++i) + { + m_mine[i] = 0xFFFFFFFFu; + m_weaponIndex[i] = -1; + } +} + +// ELF 0x2419C0 (D2) / 0x241A50 (D1) / 0x241AE0 (D0): delete[] +0x0C..+0x18 in order when set, then +// the base. +BBPDefuseMines::~BBPDefuseMines() +{ + if (m_mine) + delete[] m_mine; + if (m_weaponIndex) + delete[] m_weaponIndex; + if (m_minePosition) + delete[] m_minePosition; + if (m_targetPosition) + delete[] m_targetPosition; +} + +// ELF 0x241C00 +BotScript* BBPDefuseMines::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) + { + BotScript* previous = bot->getPlan(); + if (previous) + delete previous; + bot->setPlan(0); + } + return 0; + } + bot->getPlayer()->getSpawnKit(); + bot->getCommunicationAgent(); + if (bot->hasPlan() + && static_cast(bot->getPlan())->getPatternId() == m_unknown8 + && static_cast(bot->getPlan())->getId() == BAPSTInfoWrapper + && static_cast(bot->getPlan())->getInfoType() == 1) + { + const unsigned int previousMine = static_cast(bot->getPlan())->m_mine; + if (previousMine == m_mine[bot->getBotId()]) + return bot->getPlan(); + } + const unsigned int mine = m_mine[bot->getBotId()]; + bot->getSquadMember()->clearRequestAction(); + bot->getSensingAgent()->clearPlanTargetInformation(); + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + if (bot->getPlan()) + { + BotScript* previous = bot->getPlan(); + if (previous) + delete previous; + bot->setPlan(0); + } + bot->getScriptContext()->clear(); + Information* self = informationManager->getInformation(bot->getCurrentEquipment()); + if (!self || !self->getUnit() || mine == 0) + return 0; + IPIMobile* mobile = self->getMobile(); + IPIControlInfo* controls = self->getControlInfo(); + const int weaponIndex = m_weaponIndex[bot->getBotId()]; + if (weaponIndex == -1) + { + self->getAIObject()->update(); + return 0; + } + const int side = bot->getSide(); + const unsigned int soldierHandle = bot->getPlayer()->getSoldier()->getInformation(side); + Information* soldier = informationManager->getInformation(soldierHandle); + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(soldier->getArmament()->getWeapon(weaponIndex)); + BAPCombinerSerial* root = checkPointer(new BAPCombinerSerial(m_unknown8, -1)); + BAPCombinerSerial* sequence = checkPointer(new BAPCombinerSerial(m_unknown8, -1)); + sequence->addStatement(checkPointer(new BAPAResetControls(true, true, true, m_unknown8))); + if (!self->isOfType(ITSoldier)) + { + BAPCombinerParallel* leave = checkPointer(new BAPCombinerParallel(m_unknown8, -1, false)); + leave->addStatement(checkPointer(new BAPICChangeVehicle(soldierHandle))); + BAPConFalse* stop = checkPointer(new BAPConFalse()); + BAPConTrue* start = checkPointer(new BAPConTrue()); + leave->addStatement(checkPointer(new BAPATrigger(static_cast(10), start, stop, + 0x400ULL, m_unknown8, 0.0, false))); + sequence->addStatement(leave); + } + else + { + const unsigned long long driveControls = controls->getDriveControls(); + const float arriveSpeed = mobile->getMaxSpeed(); + const float speed = mobile->getMaxSpeed(); + const Vec3& destination = m_targetPosition[bot->getBotId()]; + sequence->addStatement(checkPointer(new BAPAMoveToFinding(bot, destination, speed, arriveSpeed, + 0, driveControls, m_unknown8, 0.0f, 0.0f))); + // shipped defect: a signed 32-bit input mask is sign-extended to 64 bits. + const unsigned int activateBit = 1u << (weapon->getWeaponActivate() & 31); + const unsigned long long activateMask = static_cast(static_cast(static_cast(activateBit))); + BAPConFalse* activateStop = checkPointer(new BAPConFalse()); + BAPConTrue* activateStart = checkPointer(new BAPConTrue()); + const io::PlayerInputMap activate = static_cast(weapon->getWeaponActivate()); + sequence->addStatement(checkPointer(new BAPATrigger(activate, activateStart, activateStop, + activateMask, m_unknown8, 0.0, false))); + BAPCombinerParallel* defuse = checkPointer(new BAPCombinerParallel(m_unknown8, -1, false)); + defuse->addStatement(checkPointer(new BAPASoldierPose(SPCrouching, checkPointer(new BAPConTrue()), + m_unknown8, true))); + defuse->addStatement(checkPointer(new BAPAOverrideSensingAgent())); + const unsigned long long lookControls = self->getControlInfo()->getLookControls(); + BAPConFalse* lookCondition = checkPointer(new BAPConFalse()); + const Vec3& minePosition = m_minePosition[bot->getBotId()]; + defuse->addStatement(checkPointer(new BAPALookAtPoint(minePosition, bot, 0.0f, lookCondition, + lookControls, m_unknown8))); + const unsigned int fireBit = 1u << (weapon->getWeaponFire() & 31); + const unsigned long long fireMask = static_cast(static_cast(static_cast(fireBit))); + BAPConFalse* abort = checkPointer(new BAPConFalse()); + BAPConFalse* fireStop = checkPointer(new BAPConFalse()); + BAPConTrue* fireStart = checkPointer(new BAPConTrue()); + const io::PlayerInputMap fire = static_cast(weapon->getWeaponFire()); + defuse->addStatement(checkPointer(new BAPATriggerContinously(fire, fireStart, fireStop, abort, + fireMask, m_unknown8, 0.0))); + sequence->addStatement(checkPointer(new BAPFlowCWhile(checkPointer(new BAPConTrue()), defuse, true, m_unknown8))); + } + root->addStatement(sequence); + const unsigned int target = m_mine[bot->getBotId()]; + BAPIWDefuseMines* wrapper = checkPointer(new BAPIWDefuseMines(bot, target, root, m_unknown8)); + wrapper->mpOwner = this; + static_cast(bot)->resetAllControls(true, true, true); + return wrapper; +} + +// ELF 0x241B80: one getBotId; marks the bot initiated (BBPPattern +0x04) and stores the parameters. +void BBPDefuseMines::init(unsigned int mine, int weaponIndex, Bot* bot, Vec3 minePosition, Vec3 targetPosition) +{ + const unsigned int botId = bot->getBotId(); + m_initiated[botId] = true; + m_mine[botId] = mine; + m_weaponIndex[botId] = weaponIndex; + m_minePosition[botId] = minePosition; + m_targetPosition[botId] = targetPosition; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPDefuseMines.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPDefuseMines.h new file mode 100644 index 000000000..9f5ad7411 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPDefuseMines.h @@ -0,0 +1,43 @@ +// Per-bot mine, tool and movement parameters for defusing plans. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPDEFUSEMINES_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPDEFUSEMINES_H + +#include "../../../../Math/Vec3.h" +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BBB80 (6 words), operator new 0x1C, package F-infantry. +class BBPDefuseMines : public BBPPattern +{ +public: + explicit BBPDefuseMines(int); // 0x2414A0 + virtual ~BBPDefuseMines(); // 0x241A50 + + virtual BotScript* createPlan(Bot*); // 0x241C00, slot +0x08; from the base declaration + + // 0x241B80: void (stores only). + void init(unsigned int, int, Bot*, Vec3, Vec3); + +private: + // Constructor 0x240F80/0x2414A0, destructor 0x2419C0/0x241A50/0x241AE0; per-bot arrays are + // new [getMaxNBots] (IAISettings slot 0); init 0x241B80 writes them by Bot::getBotId. + /* +0x08 */ int m_unknown8; // creating pattern id + /* +0x0C */ unsigned int* m_mine; // -1; mine id [INFERRED] name + /* +0x10 */ int* m_weaponIndex; // -1; first weapon of type 1 [INFERRED] name + /* +0x14 */ Vec3* m_minePosition; // zeroed (Vec3 array constructor loop) + /* +0x18 */ Vec3* m_targetPosition; // zeroed +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPDEFUSEMINES_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire.cpp new file mode 100644 index 000000000..08eceaeb4 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire.cpp @@ -0,0 +1,68 @@ +// Fire pattern base (AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire.cpp in the image). Recovered from +// libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. Package D. + +// static init: ELF 0x244F10 (__tcf_0 0x244F70, _GLOBAL__I 0x244FA0): 's Init object only. +#include + +#include "BBPFire.h" + +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +IAISettings* settings() +{ + return static_cast(CommonSingletonServer::m_iaiSettings); +} + +} // namespace + +// ELF 0x244910. m_patternId, m_flag20 and m_urgencyGenerator are left to the concrete constructor +// and BBFire's constructor (setUrgencyGenerator). +BBPFire::BBPFire() +{ + m_targets = checkPointer(new unsigned int[settings()->getMaxNBots()]); + m_targetChanged = checkPointer(new bool[settings()->getMaxNBots()]); + m_weapons = checkPointer(new int[settings()->getMaxNBots()]); + m_positionArgs = checkPointer(new unsigned int[settings()->getMaxNBots()]); + // [CHOSEN, not recovered] value-initialisation stands in for the image's zeroing Vec3 + // constructor loop (0x244A4B: three zero stores per element); Math::Vec3 is a POD here. + m_targetPositions = checkPointer(new Vec3[settings()->getMaxNBots()]()); +} + +// ELF 0x2441C0 +BBPFire::~BBPFire() +{ + if (m_targets) + delete[] m_targets; + if (m_targetChanged) + delete[] m_targetChanged; + if (m_weapons) + delete[] m_weapons; + if (m_positionArgs) + delete[] m_positionArgs; + if (m_targetPositions) + delete[] m_targetPositions; +} + +// ELF 0x244FC0 +int BBPFire::getImplementationType() +{ + return 0; +} + +// ELF 0x244F00 +void BBPFire::setUrgencyGenerator(BotBehaviour* behaviour) +{ + m_urgencyGenerator = behaviour; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire.h new file mode 100644 index 000000000..8444e6aa9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire.h @@ -0,0 +1,55 @@ +// Fire pattern base: the per-bot target state every fire pattern shares, set by BBFire's +// initializeGenerator through the two init overloads. +// Recovered from libaidll.so (Linux 1.5.3153); every body carries its ELF address. Package D. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPFIRE_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPFIRE_H + +#include "../../../../Math/Vec3.h" +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotBehaviour; + +// ELF: vtable 0x4BBBC0 (9 words), package D-behaviours. Abstract; the concrete patterns +// (BBPFireInfantery 0x34 bytes) start their own members at +0x28. +class BBPFire : public BBPPattern +{ +public: + BBPFire(); // 0x244910 + virtual ~BBPFire(); // 0x2441C0 + + // BBPFireInfantery::init (0x25C480) stores into the arrays below; see the member comments. + virtual void init(Bot*, unsigned int target, int weapon, bool, bool) = 0; // slot +0x18 + virtual void init(Bot*, unsigned int target, const Vec3& position, int weapon) = 0; // slot +0x1C + virtual int getImplementationType(); // 0x244FC0, slot +0x20: 0 + + void setUrgencyGenerator(BotBehaviour* behaviour); // 0x244F00 + +protected: + // Per bot slot (IAISettings::getMaxNBots), allocated by the constructor and not initialised there. + // Names as agreed with package E (coord/ai-requests.md). + /* +0x08 */ int m_patternId; // written by the concrete constructors (their int argument); + // compared with BAPStatement +0x10 of the current plan + /* +0x0C */ unsigned int* m_targets; // the firing target handle + /* +0x10 */ bool* m_targetChanged; // init: the handle differs from the previous one + /* +0x14 */ int* m_weapons; // init's int argument (the chosen weapon) + /* +0x18 */ unsigned int* m_positionArgs; // init(Vec3) overload: its handle argument + /* +0x1C */ Vec3* m_targetPositions; // init(Vec3) overload: the position; constructed zero + /* +0x20 */ bool m_flag20; // [UNRESOLVED] not written by BBPFire; E's createPlan reads it + /* +0x21 */ bool m_flag21; // [UNRESOLVED] init(Bot*, unsigned, int, bool, bool)'s second bool + // (BBPFire3d::init 0x2513C0); not read by BBPFire3d + /* +0x24 */ BotBehaviour* m_urgencyGenerator;// the owning BBFire (setUrgencyGenerator) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPFIRE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2d.cpp new file mode 100644 index 000000000..e0a3d3c7d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2d.cpp @@ -0,0 +1,464 @@ +// Ground-vehicle firing plans, including the shipped pointer test and inverted heat branch. + +// static init: ELF 0x24B620 (__tcf_0 0x24B680, _GLOBAL__I 0x24B6B0): 's Init object only. +#include + +#include "BBPFire2d.h" + +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IAIPathfinding.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotSenses.h" +#include "../AIBot/SensedObject.h" +#include "../AIBot/SensingAgent.h" +#include "../AIBot/SquadManager.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPAAimAtObject.h" +#include "../AIBotActionPlan/BAPAChangeWeapon.h" +#include "../AIBotActionPlan/BAPALookAtObject.h" +#include "../AIBotActionPlan/BAPAMoveToFinding.h" +#include "../AIBotActionPlan/BAPAMoveToObjectFinding.h" +#include "../AIBotActionPlan/BAPANotifyBot.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPATriggerContinously.h" +#include "../AIBotActionPlan/BAPCConPrecision.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConAnd.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConNot.h" +#include "../AIBotActionPlan/BAPConObjectDistance.h" +#include "../AIBotActionPlan/BAPConObjectHealth.h" +#include "../AIBotActionPlan/BAPConObjectMoved.h" +#include "../AIBotActionPlan/BAPConOpLessThan.h" +#include "../AIBotActionPlan/BAPConOr.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPConWeaponHeat.h" +#include "../AIBotActionPlan/BAPConWeaponMagAmmo.h" +#include "../AIBotActionPlan/BAPFlowCIf.h" +#include "../AIBotActionPlan/BAPFlowCWhile.h" +#include "../AIBotActionPlan/BAPIWFire.h" +#include "../AIBotActionPlan/BAPWrapperWeapon.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../../Core/Debug.h" +#include "../../../../Math/LocalBoundingBox.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" +#include "WeaponChoice.h" + +#include +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// [CHOSEN, not recovered] Local factoring of the image's inline variable, cleanup, +// distance, input-mask and repeated reload-trigger operations; these helper names have no symbols. + +// Inline construction and context-list insertion in ELF 0x245B58 and subsequent allocations. +template +BAPVariable* newVariable(BAPContext* context, const T& value) +{ + BAPVariable* const variable = checkPointer(new BAPVariable(context, value)); + context->addVariable(variable); + return variable; +} + +void dropPlan(Bot* bot) +{ + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } +} + +float distanceBetween(const Vec3& a, const Vec3& b) +{ + const float x = a.x - b.x; + const float y = a.y - b.y; + const float z = a.z - b.z; + return std::sqrt(x * x + y * y + z * z); +} + +// ELF 0x246B53 / 0x24769E: 32-bit shl, then sign extension to the 64-bit mask. +unsigned long long inputMask(int input) +{ + const int mask = static_cast(1u << (static_cast(input) & 31u)); + return static_cast(static_cast(mask)); +} + +// The identical reload triggers at ELF 0x245F18 and 0x248FC8. +BAPATrigger* reloadTrigger(int patternId) +{ + return checkPointer(new BAPATrigger(static_cast(32), + checkPointer(new BAPConTrue()), checkPointer(new BAPConFalse()), + 0x100000000ULL, patternId, 0.0, false)); +} + +} // namespace + +// ELF 0x245140: BBPFire(), the vtable store (GOT -0x178 + 8), the argument at +0x08, then +// `new bool[getMaxNBots()]` (IAISettings slot 0, not initialised) through the inlined checkPointer +// into +0x28 (operator new 0x2C). +BBPFire2d::BBPFire2d(int patternId) + : BBPFire() +{ + m_patternId = patternId; + m_perBotFlag = checkPointer(new bool[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); +} + +// ELF 0x2452B0 (D2) / 0x245300 (D1) / 0x245350 (D0): delete[] +0x28 when set, then ~BBPFire. +BBPFire2d::~BBPFire2d() +{ + if (m_perBotFlag) + delete[] m_perBotFlag; +} + +// ELF 0x245650 +BotScript* BBPFire2d::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + dropPlan(bot); + return 0; + } + static_cast(bot)->resetAllControls(true, false, true); + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + Information* const targetInfo = informationManager->getInformation(m_targets[bot->getBotId()]); + if (!targetInfo) + return 0; + IAIObjectEnvironment* const environment = + static_cast(CommonSingletonServer::m_iaiObjectEnvironment); + IPIPhysical* const physical = targetInfo->getPhysical(); + IPIArmament* const armament = self->getArmament(); + IPIMobile* const mobile = self->getMobile(); + IPIControlInfo* const controls = self->getControlInfo(); + const unsigned long long driveControls = controls->getDriveControls(); + const unsigned long long aimControls = controls->getAimControls(); + const bool separateControls = (driveControls & aimControls) == 0; + SensedObject* const sensed = bot->getSensedObjectFromHandle(m_targets[bot->getBotId()]); + LocalBoundingBox* const bounds = const_cast(physical->getLocalBoundingBox()); + const int strength = physical->getStrengthType(); + const Vec3& selfPosition = self->getPosition(); + const Vec3& targetPosition = targetInfo->getPosition(); + const float distance = distanceBetween(selfPosition, targetPosition); + const unsigned int botId = bot->getBotId(); + const std::vector& weapons = armament->getWeapons(); + const int weapon = choseWeapon(weapons, m_weapons[botId], distance, strength, false, false, false, false); + if (weapon == -1) + { + self->getAIObject()->update(); + return 0; + } + WeaponInfo* const weaponInfo = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(weapon)); + armament->setActiveWeapon(weapon, bot->getSide()); + // Three inline size getters are evaluated even though their values are discarded. + (void)bounds->getSize().x; + (void)bounds->getSize().y; + (void)bounds->getSize().z; + const Vec3& currentSelfPosition = self->getPosition(); + const Vec3& currentTargetPosition = targetInfo->getPosition(); + const float targetDistance = distanceBetween(currentSelfPosition, currentTargetPosition); + const float maxRange = weaponInfo->getMaxRange(); + int lineOfFire; + if (targetDistance > static_cast(maxRange) * 0.95) + lineOfFire = mobile ? 0 : 3; + else if (sensed && !(sensed->m_flags & SensedObject::SENSE_INDIRECT)) + lineOfFire = 1; + else + { + Vec3 aimPoint = {0.0f, 0.0f, 0.0f}; + if (sensed) + { + const Mat4& m = targetInfo->getTransformation(); + const Vec3& p = sensed->m_seenPosition; + aimPoint.x = m.m[0] * p.x + m.m[4] * p.y + m.m[8] * p.z + m.m[12]; + aimPoint.y = m.m[1] * p.x + m.m[5] * p.y + m.m[9] * p.z + m.m[13]; + aimPoint.z = m.m[2] * p.x + m.m[6] * p.y + m.m[10] * p.z + m.m[14]; + } + else + aimPoint = targetInfo->getPosition(); + std::vector excluded; + excluded.push_back(self->getAIObject()); + excluded.push_back(targetInfo->getAIObject()); + lineOfFire = environment->hasIndirectLineOfFire(weaponInfo->getWeapon(), weaponInfo->getPosition(), aimPoint, excluded) + ? 2 : (mobile ? 0 : 3); + } + if (bot->hasPlan() && static_cast(bot->getPlan())->getPatternId() == m_patternId + && static_cast(bot->getPlan())->getId() == BAPSTInfoWrapper + && static_cast(bot->getPlan())->getInfoType() == 0) + { + BAPIWFire* const existing = static_cast(bot->getPlan()); + if (existing->getTarget() == m_targets[bot->getBotId()] && existing->getInt28() == lineOfFire) + return bot->getPlan(); + } + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + dropPlan(bot); + bot->getSquadMember()->clearRequestAction(); + BAPContext* const context = bot->getScriptContext(); + context->clear(); + BAPVariable* const weaponVariable = newVariable(context, weaponInfo); + BAPVariable* const targetVariable = newVariable(context, m_targets[bot->getBotId()]); + BAPStatement* statement = 0; + if (lineOfFire == 3) + { + SensedObject* blocked = bot->getSensedObjectFromHandle(m_targets[bot->getBotId()]); + if (!blocked) + { + const unsigned int primary = targetInfo->getPrimaryObject(targetInfo->getSide()); + Information* const primaryInfo = informationManager->getInformation(primary); + if (primaryInfo) + { + const Vec3 zero = {0.0f, 0.0f, 0.0f}; + bot->getSensingAgent()->getSenses()->event_seenObject(primary, zero, static_cast(-1), + primaryInfo, false, false); + blocked = bot->getSensedObjectFromHandle(primary); + } + } + // shipped defect: no guard if the primary information/sensed record is absent. + blocked->m_flags |= 0x20; + blocked->m_fireRating = -100; + blocked->m_lastSense = 0x20; + return 0; + } + if (lineOfFire == 0) + { + IAIPathfinding* const pathfinding = IAIPathfinding::instance; + BAPCombinerParallel* const approach = checkPointer(new BAPCombinerParallel(m_patternId, -1, false)); + const int equipment = self->getUnit()->getEquipmentType(); + BAPStatement* movement; + if (pathfinding->isValidPosition(mobile->getVehicleNumber(), equipment, targetInfo->getPosition(), true)) + { + BAPConAnd* const close = checkPointer(new BAPConAnd()); + close->addCondition(checkPointer(new BAPConObjectDistance(m_targets[bot->getBotId()], 50.0f, true, true, false))); + close->addCondition(checkPointer(new BAPConObjectMoved(m_targets[bot->getBotId()], 10.0f))); + const unsigned long long drive = controls->getDriveControls(); + const float arriveSpeed = mobile->getMaxSpeed(); + const float speed = mobile->getMaxSpeed(); + const float approachDistance = targetDistance * 0.75f; + const float rangeLimit = weaponInfo->getMaxRange() * 0.95f; + movement = checkPointer(new BAPAMoveToObjectFinding(bot, m_targets[bot->getBotId()], + rangeLimit > approachDistance ? approachDistance : rangeLimit, speed, arriveSpeed, 0, + drive, m_patternId, close, 0.0f, -1)); + } + else + { + Vec3 goal = {0.0f, 0.0f, 0.0f}; + unsigned int polygon, island; + const Vec3& from = self->getPosition(); + const Vec3& to = targetInfo->getPosition(); + pathfinding->findClosestValidPolygon(polygon, island, goal, mobile->getVehicleNumber(), to, from, 10, equipment); + const float maximum = weaponInfo->getMaxRange(); + const float minimum = weaponInfo->getMinRange(); + const float band = (maximum - minimum) * 0.1f; + const float stoppingDistance = weaponInfo->getMinRange() + band; + const unsigned long long drive = controls->getDriveControls(); + const float arriveSpeed = mobile->getMaxSpeed(); + const float speed = mobile->getMaxSpeed(); + movement = checkPointer(new BAPAMoveToFinding(bot, goal, speed, arriveSpeed, 0, + drive, m_patternId, stoppingDistance, 0.0f)); + } + BAPALookAtObject* const look = checkPointer(new BAPALookAtObject(bot, m_targets[bot->getBotId()], 0.034906585f, + checkPointer(new BAPConFalse()), controls->getLookControls(), m_patternId, 0, 0.0f)); + approach->addStatement(movement); + approach->addStatement(look); + statement = approach; + } + else if (lineOfFire == 1 || lineOfFire == 2) + { + BAPCombinerSerial* const sequence = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + if (weaponInfo->getWeaponActivate() != 64) + sequence->addStatement(checkPointer(new BAPAChangeWeapon(bot, weapon, m_patternId))); + BAPConWeaponMagAmmo* const empty = checkPointer(new BAPConWeaponMagAmmo(weaponVariable, newVariable(context, 0), false)); + BAPATrigger* const reload = reloadTrigger(m_patternId); + sequence->addStatement(checkPointer(new BAPFlowCIf(empty, reload, 0, m_patternId, false, false))); + BAPVariable* const unused = newVariable(context, 0); + (void)unused; + BAPConNot* alive; + { + std::list lost; + lost.push_back(checkPointer(new BAPConObjectHealth(m_targets[bot->getBotId()], 0.0f))); + lost.push_back(checkPointer(new BAPConWeaponMagAmmo(weaponVariable, newVariable(context, 0), false))); + BAPConOr* const any = checkPointer(new BAPConOr(lost)); + std::list wrapped; + wrapped.push_back(any); + alive = checkPointer(new BAPConNot(wrapped)); + } + BAPCombinerSerial* const repeat = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + if (!weaponInfo->hasAutoReload()) + { + BAPConWeaponMagAmmo* const noAmmo = checkPointer(new BAPConWeaponMagAmmo(weaponVariable, newVariable(context, 0), false)); + BAPATrigger* const trigger = reloadTrigger(m_patternId); + repeat->addStatement(checkPointer(new BAPFlowCWhile(noAmmo, trigger, m_patternId))); + } + // shipped defect: this cooling branch is selected when hasHeat() is false. + if (!weaponInfo->hasHeat()) + { + BAPConWeaponHeat* const hot = checkPointer(new BAPConWeaponHeat(weaponVariable, 0.8f)); + BAPConWeaponHeat* const cooled = checkPointer(new BAPConWeaponHeat(weaponVariable, 0.7f)); + BAPCombinerSerial* const cool = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + BAPAResetControls* const reset = checkPointer(new BAPAResetControls(false, false, true, m_patternId)); + BAPALookAtObject* const look = checkPointer(new BAPALookAtObject(bot, m_targets[bot->getBotId()], 0.1f, + cooled, controls->getLookControls(), m_patternId, 0, 0.0f)); + cool->addStatement(look); + cool->addStatement(reset); + repeat->addStatement(checkPointer(new BAPFlowCIf(hot, cool, 0, m_patternId, false, false))); + } + BAPVariable* const ammo = newVariable(context, 0); + repeat->addStatement(checkPointer(new BAPWrapperWeapon(static_cast(0), ammo, weaponVariable, false))); + BAPCombinerParallel* const firing = checkPointer(new BAPCombinerParallel(m_patternId, false, -1, false)); + const Vec3 zero = {0.0f, 0.0f, 0.0f}; + // shipped defect: tests the allocated array pointer, not this bot's flag. + BAPAAimAtObject* const aim = checkPointer(new BAPAAimAtObject(bot, m_targets[bot->getBotId()], zero, + checkPointer(new BAPConFalse()), controls->getAimControls(), m_patternId, m_perBotFlag != 0, 0, 0)); + firing->addStatement(aim); + BAPVariable* const heat = newVariable(context, 0.0f); + firing->addStatement(checkPointer(new BAPWrapperWeapon(static_cast(1), heat, weaponVariable, true))); + LocalBoundingBox* const box = const_cast(physical->getLocalBoundingBox()); + const Vec3& selfPositionNow = self->getPosition(); + const Vec3& targetPositionNow = targetInfo->getPosition(); + const float rangeDistance = distanceBetween(selfPositionNow, targetPositionNow); + const float minimum = weaponInfo->getMinRange(); + const float maximum = weaponInfo->getMaxRange(); + const float rangeMinimum = weaponInfo->getMinRange(); + const float fraction = (rangeDistance - minimum) / (maximum - rangeMinimum); + const float precisionScale = (1.0f - fraction) * 0.1f + fraction * 5.0f; + float precisionFactor; + float minimumPrecision; + if (targetInfo->isOfType(ITAir)) + { + precisionFactor = 0.8f; + minimumPrecision = 0.5f; + } + else if (m_perBotFlag) + { + precisionFactor = 2.5f; + minimumPrecision = 10.0f; + } + else + { + precisionFactor = 1.5f; + minimumPrecision = 5.0f; + } + const float xSize = box->getSize().x; + const float ySize = box->getSize().y; + const float zSize = box->getSize().z; + const float yz = zSize > ySize ? zSize : ySize; + const float size = yz > xSize ? yz : xSize; + const float scaled = size * precisionFactor; + const float precision = scaled > minimumPrecision ? scaled : minimumPrecision; + BAPCConPrecision* const accurate = checkPointer(new BAPCConPrecision(m_targets[bot->getBotId()], aim, + precision * precisionScale, !weaponInfo->getBurst(), false, false)); + BAPConOr* stopFiring; + { + std::list stop; + stop.push_back(checkPointer(new BAPConWeaponMagAmmo(weaponVariable, ammo, true))); + stop.push_back(checkPointer(new BAPConOpLessThan(newVariable(context, 0.5f), heat))); + stopFiring = checkPointer(new BAPConOr(stop)); + } + BAPStatement* fire; + if (weaponInfo->getBurst()) + { + const unsigned long long mask = inputMask(weaponInfo->getWeaponFire()); + fire = checkPointer(new BAPATriggerContinously(static_cast(weaponInfo->getWeaponFire()), accurate, 0, + stopFiring, mask, m_patternId, 0.0)); + } + else + { + const unsigned long long mask = inputMask(weaponInfo->getWeaponFire()); + BAPConFalse* const end = checkPointer(new BAPConFalse()); + BAPATrigger* const trigger = checkPointer(new BAPATrigger(static_cast(weaponInfo->getWeaponFire()), accurate, + end, mask, m_patternId, 0.0, false)); + std::list conditions; + conditions.push_back(stopFiring); + BAPConNot* const keepFiring = checkPointer(new BAPConNot(conditions)); + fire = checkPointer(new BAPFlowCWhile(keepFiring, trigger, m_patternId)); + } + firing->addStatement(fire); + repeat->addStatement(firing); + repeat->addStatement(checkPointer(new BAPANotifyBot(static_cast(0), + newVariable(context, 1), targetVariable))); + sequence->addStatement(checkPointer(new BAPFlowCWhile(alive, repeat, m_patternId))); + BAPCombiner* root; + if (separateControls) + root = checkPointer(new BAPCombinerParallel(m_patternId, -1, false)); + else + root = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + root->addStatement(checkPointer(new BAPAResetControls(true, false, false, m_patternId))); + root->addStatement(sequence); + statement = root; + } + BAPIWFire* const plan = checkPointer(new BAPIWFire(bot, m_targets[bot->getBotId()], m_flag20, false, + weapon, -1, statement, m_patternId)); + plan->setInt28(lineOfFire); + plan->setParent(this); + const unsigned int firingBotId = bot->getBotId(); + const unsigned int* const targets = m_targets; + const int side = bot->getSide(); + const int player = bot->getPlayerId(); + SquadManager::m_instance->shotsFired(player, side, targets[firingBotId]); + return plan; +} + +// ELF 0x2453A0 +void BBPFire2d::init(Bot* bot, unsigned int target, int weapon, bool flag20, bool flag21) +{ + init(bot, target, weapon, flag20, flag21, false); +} + +// ELF 0x2454A0 +void BBPFire2d::init(Bot* bot, unsigned int positionArg, const Vec3& position, int weapon) +{ + Debug(DebugTypeError, "AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2d.cpp", 0x8D, "") + << "LaserGuided missiles unsuported by artillry."; + m_initiated[bot->getBotId()] = true; + m_targets[bot->getBotId()] = static_cast(-1); + m_weapons[bot->getBotId()] = weapon; + m_positionArgs[bot->getBotId()] = positionArg; + m_targetPositions[bot->getBotId()] = position; +} + +// ELF 0x24B6D0 +int BBPFire2d::getImplementationType() +{ + return 2; +} + +// ELF 0x245400 +void BBPFire2d::init(Bot* bot, unsigned int target, int weapon, bool flag20, bool flag21, bool perBotFlag) +{ + m_initiated[bot->getBotId()] = true; + m_targets[bot->getBotId()] = target; + m_perBotFlag[bot->getBotId()] = perBotFlag; + m_weapons[bot->getBotId()] = weapon; + m_flag20 = flag20; + m_flag21 = flag21; + m_positionArgs[bot->getBotId()] = static_cast(-1); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2d.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2d.h new file mode 100644 index 000000000..6052017b7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2d.h @@ -0,0 +1,38 @@ +// Builds approach and firing plans for ground-vehicle weapons. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPFIRE2D_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPFIRE2D_H + +#include "../../../../Math/Vec3.h" +#include "BBPFire.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BBC80 (9 words), operator new 0x2C, package G-vehicles. +class BBPFire2d : public BBPFire +{ +public: + explicit BBPFire2d(int); // 0x245140 + virtual ~BBPFire2d(); // 0x245300 + + virtual BotScript* createPlan(Bot*); // 0x245650, slot +0x08; from the base declaration + virtual void init(Bot*, unsigned int, int, bool, bool); // 0x2453A0, slot +0x18; from the base declaration + virtual void init(Bot*, unsigned int, const Vec3&, int); // 0x2454A0, slot +0x1C; from the base declaration + virtual int getImplementationType(); // 0x24B6D0, slot +0x20; from the base declaration + + void init(Bot*, unsigned int, int, bool, bool, bool); // 0x245400; [INFERRED] ELF void + + /* +0x28 */ bool* m_perBotFlag; // per bot: the last bool of init 0x245400 [INFERRED] name +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPFIRE2D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2dDriver.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2dDriver.cpp new file mode 100644 index 000000000..419fc42c0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2dDriver.cpp @@ -0,0 +1,464 @@ +// Fire pattern of artillery drivers and other ground vehicles that aim with their own turret +// (AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2dDriver.cpp in the image, the init(Vec3) __FILE__). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// createPlan was rebuilt from the listing block by block: Ghidra drops the bool arguments of the +// condition and flow constructors, passes the findClosestValidPolygon out-values by value and +// shows the while loop's swapped arguments as constants; GCC evaluates the constructor arguments +// right to left, which fixes the source order of the nested allocations below. +// [PLATFORM] precision: the x87 build keeps the distance sums, the circle radius and the +// approach-distance products in extended precision before rounding; the float expressions below +// round each step. + +#include "BBPFire2dDriver.h" + +#include +#include +#include + +#include "../../../../Core/Debug.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SensedObject.h" +#include "../AIBot/SquadManager.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPActionInline.h" +#include "../AIBotActionPlan/BAPAMoveToFinding.h" +#include "../AIBotActionPlan/BAPAMoveToObjectFinding.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPATurnTowardsObject.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPConAnd.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConNot.h" +#include "../AIBotActionPlan/BAPConObjectDistance.h" +#include "../AIBotActionPlan/BAPConObjectHealth.h" +#include "../AIBotActionPlan/BAPConObjectMoved.h" +#include "../AIBotActionPlan/BAPConObjectOccupied.h" +#include "../AIBotActionPlan/BAPConObjectValidAiming.h" +#include "../AIBotActionPlan/BAPConObjectValidPitchAiming.h" +#include "../AIBotActionPlan/BAPConObjectValidYawAiming.h" +#include "../AIBotActionPlan/BAPConOr.h" +#include "../AIBotActionPlan/BAPFlowCIf.h" +#include "../AIBotActionPlan/BAPFlowCWhile.h" +#include "../AIBotActionPlan/BAPIWFire.h" +#include "../AIBotActionPlan/BAPInfoWrapper.h" +#include "../AIBotActionPlan/BAPVariable.h" +#include "../AIBotActionPlan/BAPWrapperAiming.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/TraceUtils.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IAIPathfinding.h" +#include "WeaponChoice.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x251060, __tcf_0 0x2510C0, _GLOBAL__I 0x2510F0). +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +IAISettings* settings() +{ + return static_cast(CommonSingletonServer::m_iaiSettings); +} + +IAIObjectEnvironment* objectEnvironment() +{ + return static_cast(CommonSingletonServer::m_iaiObjectEnvironment); +} + +void dropPlan(Bot* bot) +{ + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } +} + +// The image's inlined plan-variable construction: `checkPointer(new BAPVariable(context, value))` +// followed by `std::list::insert(context->begin(), &variable)`. +template +BAPVariable* newVariable(BAPContext* context, const T& value) +{ + BAPVariable* const variable = checkPointer(new BAPVariable(context, value)); + context->addVariable(variable); + return variable; +} + +// |to - from| from the extended-precision sum, as the image computes both target distances. +float distanceBetween(const Vec3& from, const Vec3& to) +{ + const float dx = to.x - from.x; + const float dy = to.y - from.y; + const float dz = to.z - from.z; + return std::sqrt(dx * dx + dy * dy + dz * dz); +} + +// The approach move both the direct and the aiming branch build when there is no line of fire or +// the target is out of reach (0x24CC23..0x24CEE3 and 0x250310..0x2505CA, 0x24EB30.., 0x250A10..). +// A valid target position gets an object-finding move that ends near (50 m) or when the target +// moved 10 m; otherwise the closest valid polygon towards the target is approached up to a tenth +// of the weapon's range band. The findClosestValidPolygon answer is discarded as compiled. +BAPStatement* newApproach(Bot* bot, unsigned int target, unsigned int currentTarget, Information* self, + Information* targetInfo, IPIMobile* mobile, IPIControlInfo* controlInfo, + WeaponInfo* weaponInfo, int equipmentType, float targetDistance, int patternId) +{ + IAIPathfinding* const pathfinding = IAIPathfinding::instance; + if (pathfinding->isValidPosition(mobile->getVehicleNumber(), equipmentType, targetInfo->getPosition(), true)) + { + BAPConAnd* const close = checkPointer(new BAPConAnd()); + close->addCondition(checkPointer(new BAPConObjectDistance(currentTarget, 50.0f, true, true, false))); + close->addCondition(checkPointer(new BAPConObjectMoved(currentTarget, 10.0f))); + // min(range * 0.95, distance * 0.75); unordered keeps the range term (`fcmovnbe`). + const float rangeLimit = weaponInfo->getMaxRange() * 0.95f; + const float approach = targetDistance * 0.75f; + return checkPointer(new BAPAMoveToObjectFinding(bot, target, rangeLimit > approach ? approach : rangeLimit, + mobile->getMaxSpeed(), mobile->getMaxSpeed(), + checkPointer(new BAPConFalse()), + controlInfo->getDriveControls(), patternId, close, 0.0f, -1)); + } + + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + Vec3 unused; // zeroed beside the goal and never read + unused.x = unused.y = unused.z = 0.0f; + (void)unused; + unsigned int island; + unsigned int polygon; + pathfinding->findClosestValidPolygon(polygon, island, goal, mobile->getVehicleNumber(), targetInfo->getPosition(), + self->getPosition(), 10, equipmentType); + return checkPointer(new BAPAMoveToFinding( + bot, goal, mobile->getMaxSpeed(), mobile->getMaxSpeed(), 0, controlInfo->getDriveControls(), patternId, + weaponInfo->getMinRange() + (weaponInfo->getMaxRange() - weaponInfo->getMinRange()) * 0.1f, 0.0f)); +} + +} // namespace + +// ELF 0x24BBF0 (C1; C2 0x24BA80): BBPFire(), the vtable store, the argument at +0x08, then one +// flag per bot slot (IAISettings::getMaxNBots), not initialised. +BBPFire2dDriver::BBPFire2dDriver(int patternId) + : BBPFire() +{ + m_patternId = patternId; + m_flags28 = checkPointer(new bool[settings()->getMaxNBots()]); +} + +// ELF 0x24BDB0 (D1; D2 0x24BD60, D0 0x24BE00): the flag array, then BBPFire's destructor. +BBPFire2dDriver::~BBPFire2dDriver() +{ + if (m_flags28) + delete[] m_flags28; +} + +// ELF 0x24C100. An uninitiated pattern clears the debugger and drops the plan (the context is left) +// and builds nothing. Otherwise the controls are reset (true, false, true), a weapon is chosen +// for the distance and the target's strength type (none: the own object's update, no plan), and +// the line of fire is classified: 1 when the target is sensed directly, else 2 or 0 from the +// indirect line-of-fire test against the sensed part (or the target's position). A fire plan of +// this pattern built for the same target, classification and closeness is kept. Otherwise the +// plan is rebuilt as IWFire over +// 0: an approach move (newApproach); +// too close (inside the minimum range + 0.5 m): a move to the best point found by tracing a +// circle of 2 * minimum range + 5 m around the target, 15 degree steps alternating to both +// sides of the bearing away from the target, ended once outside the minimum range + 1 m; +// else: parallel(aiming wrapper, if(within minimum range + 0.5 m: nothing, +// else if(out of 0.9 * range or no valid aim: approach move, else fire loop))), +// the fire loop being while(alive and occupied and not within the minimum range + 0.5 m: reset +// controls), behind a yaw check that turns towards the target first for a turnable vehicle. +// Shipped quirks kept: the target information, its physical, the armament and the equipment are +// not null-checked; the target's local bounding box is fetched and dropped; two plan variables +// (weapon, target) are created and never used; the while loop gets (m_patternId != 0, 0) for +// (testOnFinish, patternId); the turn takes the raw drive-turn input as its control mask. +BotScript* BBPFire2dDriver::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + dropPlan(bot); + return 0; + } + + static_cast(bot)->resetAllControls(true, false, true); + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + const unsigned int target = m_targets[bot->getBotId()]; + Information* const targetInfo = informationManager->getInformation(target); + IAIObjectEnvironment* const environment = objectEnvironment(); + Vec2 targetPosition2d; // converted and never read + targetPosition2d.x = targetPosition2d.y = 0.0f; + Vec2 selfPosition2d; + selfPosition2d.x = selfPosition2d.y = 0.0f; + IPIPhysical* const targetPhysical = targetInfo->getPhysical(); + vec3ToVec2XZ(targetInfo->getPosition(), targetPosition2d); + vec3ToVec2XZ(self->getPosition(), selfPosition2d); + IPIMobile* const mobile = self->getMobile(); + IPIControlInfo* const controlInfo = self->getControlInfo(); + int armamentIterator; + IPIArmament* const armament = + informationManager->getInformation(self->getFirstSecondaryObject(armamentIterator, bot->getSide()))->getArmament(); + const int strengthType = targetPhysical->getStrengthType(); + const float distance = distanceBetween(self->getPosition(), targetInfo->getPosition()); + const int weapon = choseWeapon(armament->getWeapons(), m_weapons[bot->getBotId()], distance, strengthType, false, + false, false, false); + if (weapon == -1) + { + self->getAIObject()->update(); + return 0; + } + + WeaponInfo* const weaponInfo = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(weapon)); + const float targetDistance = distanceBetween(self->getPosition(), targetInfo->getPosition()); + const bool tooClose = weaponInfo->getMinRange() + 0.5f > targetDistance; + SensedObject* const sensed = bot->getSensedObjectFromHandle(m_targets[bot->getBotId()]); + targetPhysical->getLocalBoundingBox(); // [UNRESOLVED] result unused in the image (0x24C57D) + + int lineOfFire; + if (sensed && !(sensed->m_flags & 8)) + lineOfFire = 1; + else + { + Vec3 aimPoint; + aimPoint.x = aimPoint.y = aimPoint.z = 0.0f; + if (sensed) + { + // The sensed part's offset in the target's frame, in world space (0x250DC0). + const Mat4& transform = targetInfo->getTransformation(); + const Vec3& part = sensed->m_seenPosition; + aimPoint.x = transform.m[0] * part.x + transform.m[4] * part.y + transform.m[8] * part.z + transform.m[12]; + aimPoint.y = transform.m[1] * part.x + transform.m[5] * part.y + transform.m[9] * part.z + transform.m[13]; + aimPoint.z = part.x * transform.m[2] + part.y * transform.m[6] + part.z * transform.m[10] + transform.m[14]; + } + else + aimPoint = targetInfo->getPosition(); + std::vector excluded; + excluded.push_back(self->getAIObject()); + excluded.push_back(targetInfo->getAIObject()); + lineOfFire = environment->hasIndirectLineOfFire(weaponInfo->getWeapon(), weaponInfo->getPosition(), aimPoint, + excluded) + ? 2 + : 0; + } + + if (bot->hasPlan() && static_cast(bot->getPlan())->getGeneratorId() == m_patternId + && static_cast(bot->getPlan())->getId() == BAPSTInfoWrapper + && static_cast(bot->getPlan())->getInfoType() == 0 + && static_cast(bot->getPlan())->getTarget() == m_targets[bot->getBotId()] + && static_cast(bot->getPlan())->getInt28() == lineOfFire + && static_cast(bot->getPlan())->getFlagB() == tooClose) + return bot->getPlan(); + + bot->getSquadMember()->clearRequestAction(); + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + dropPlan(bot); + BAPContext* const context = bot->getScriptContext(); + context->clear(); + const int equipmentType = self->getUnit()->getEquipmentType(); + + BAPStatement* statement; + if (lineOfFire == 0) + { + statement = newApproach(bot, target, m_targets[bot->getBotId()], self, targetInfo, mobile, controlInfo, + weaponInfo, equipmentType, targetDistance, m_patternId); + } + else if (tooClose) + { + float angle = 0.0f; + float bestDistanceSqr = 0.0f; + Vec2 best = selfPosition2d; + const float minRange = weaponInfo->getMinRange(); + const float radius = minRange + minRange + 5.0f; + const float limitSqr = (radius - 1.0f) * (radius - 1.0f); + const Vec3& targetPosition = targetInfo->getPosition(); + const Vec3& selfPosition = self->getPosition(); + Vec3 away = bapinline::vec3(selfPosition.x - targetPosition.x, selfPosition.y - targetPosition.y, + selfPosition.z - targetPosition.z); + if (bapinline::lengthSqr(away) > 0.1f) + bapinline::normalize(away); + else + away = bapinline::vec3(1.0f, 0.0f, 0.0f); + while (bestDistanceSqr <= limitSqr && angle <= 1.5707964f) + { + Vec3 point = bapinline::vec3(0.0f, 0.0f, 0.0f); + const bool reached = TraceUtils::tracePointOnCircle(away, targetInfo->getPosition(), self->getPosition(), + mobile->getVehicleNumber(), angle, radius, point); + angle = -angle; + if (angle >= 0.0f) + angle += 0.2617994f; // 15 degrees (0x3E860A92) + if (reached) + { + const Vec3& centre = targetInfo->getPosition(); + const float dx = centre.x - point.x; + const float dy = centre.y - point.y; + const float dz = centre.z - point.z; + const float distanceSqr = dx * dx + dy * dy + dz * dz; + if (distanceSqr > bestDistanceSqr) + { + bestDistanceSqr = distanceSqr; + vec3ToVec2XZ(point, best); + } + } + } + + Vec3 goal = bapinline::vec3(0.0f, 0.0f, 0.0f); + BAPConObjectDistance* const inside = + checkPointer(new BAPConObjectDistance(target, weaponInfo->getMinRange() + 1.0f, true, false, false)); + BAPConNot* const outside = checkPointer(new BAPConNot()); + outside->addCondition(inside); + vec2ToVec3XZ(best, goal); + statement = checkPointer(new BAPAMoveToFinding(bot, goal, mobile->getMaxSpeed(), mobile->getMaxSpeed(), outside, + controlInfo->getDriveControls(), m_patternId, 0.0f, 0.0f)); + } + else + { + const bool turnable = mobile->isTurnable(); + int secondaryIterator; + const unsigned int secondary = self->getFirstSecondaryObject(secondaryIterator, self->getSide()); + newVariable(context, weaponInfo); // never read + newVariable(context, target); // never read + BAPVariable* const aimValid = newVariable(context, false); + BAPVariable* const aimDirection = newVariable(context, bapinline::vec3(0.0f, 1.0f, 0.0f)); + BAPVariable* const aimPosition = newVariable(context, bapinline::vec3(0.0f, 1.0f, 0.0f)); + + BAPCombinerParallel* const parallel = checkPointer(new BAPCombinerParallel(m_patternId, -1, false)); + parallel->addStatement( + checkPointer(new BAPWrapperAiming(aimDirection, aimValid, aimPosition, secondary, target, false))); + + // Reposition when out of 0.9 * range or without a valid aim. + BAPConOr* const reposition = checkPointer(new BAPConOr()); + { + BAPConObjectDistance* const inRange = + checkPointer(new BAPConObjectDistance(target, weaponInfo->getMaxRange() * 0.9f, true, false, false)); + BAPConNot* const outOfRange = checkPointer(new BAPConNot()); + outOfRange->addCondition(inRange); + reposition->addCondition(outOfRange); + } + if (turnable) + { + BAPConObjectValidPitchAiming* const pitch = + checkPointer(new BAPConObjectValidPitchAiming(target, secondary, aimValid, aimDirection)); + BAPConNot* const noPitch = checkPointer(new BAPConNot()); + noPitch->addCondition(pitch); + reposition->addCondition(noPitch); + } + else + { + BAPConObjectValidAiming* const aim = + checkPointer(new BAPConObjectValidAiming(target, secondary, aimValid, aimDirection, false)); + BAPConNot* const noAim = checkPointer(new BAPConNot()); + noAim->addCondition(aim); + reposition->addCondition(noAim); + } + + BAPStatement* const approach = newApproach(bot, target, m_targets[bot->getBotId()], self, targetInfo, mobile, + controlInfo, weaponInfo, equipmentType, targetDistance, m_patternId); + + BAPConAnd* keepFiring; + { + std::list lost; + lost.push_back(checkPointer(new BAPConObjectHealth(target, 0.0f))); + BAPConObjectOccupied* const occupied = checkPointer(new BAPConObjectOccupied(secondary)); + BAPConNot* const empty = checkPointer(new BAPConNot()); + empty->addCondition(occupied); + lost.push_back(empty); + BAPConOr* const lostTarget = checkPointer(new BAPConOr(lost)); + std::list wrapped; + wrapped.push_back(lostTarget); + BAPConNot* const alive = checkPointer(new BAPConNot(wrapped)); + BAPConObjectDistance* const inside = + checkPointer(new BAPConObjectDistance(target, weaponInfo->getMinRange() + 0.5f, true, false, false)); + BAPConNot* const outside = checkPointer(new BAPConNot()); + outside->addCondition(inside); + keepFiring = checkPointer(new BAPConAnd()); + keepFiring->addCondition(outside); + keepFiring->addCondition(alive); + } + BAPAResetControls* const reset = checkPointer(new BAPAResetControls(true, true, true, m_patternId)); + // The image passes (m_patternId != 0, 0) for (testOnFinish, patternId) (0x24D2CF): kept. + BAPFlowCWhile* const fireLoop = checkPointer(new BAPFlowCWhile(keepFiring, reset, m_patternId != 0, 0)); + BAPStatement* fire = fireLoop; + if (turnable) + { + BAPConObjectValidYawAiming* const yaw = + checkPointer(new BAPConObjectValidYawAiming(target, secondary, aimValid, aimDirection)); + // The drive-turn input itself, zero-extended, is the control mask (0x24D958). + BAPATurnTowardsObject* const turn = checkPointer(new BAPATurnTowardsObject( + bot, target, 0.08726646f, checkPointer(new BAPConFalse()), // 5 degrees (0x3DB2B8C2) + static_cast(static_cast(controlInfo->getDriveTurnControl())), + m_patternId)); + fire = checkPointer(new BAPFlowCIf(yaw, fireLoop, turn, m_patternId, true, false)); + } + BAPFlowCIf* const engage = checkPointer(new BAPFlowCIf(reposition, approach, fire, m_patternId, true, false)); + BAPConObjectDistance* const inside = + checkPointer(new BAPConObjectDistance(target, weaponInfo->getMinRange() + 0.5f, true, false, false)); + parallel->addStatement(checkPointer(new BAPFlowCIf(inside, 0, engage, m_patternId, true, false))); + statement = parallel; + } + + BAPIWFire* const plan = checkPointer(new BAPIWFire(bot, m_targets[bot->getBotId()], m_flag20, tooClose, weapon, -1, + statement, m_patternId)); + plan->setInt28(lineOfFire); + plan->setParent(this); // +0x04 (BotScript::mpOwner) + SquadManager::m_instance->shotsFired(bot->getPlayerId(), bot->getSide(), m_targets[bot->getBotId()]); + return plan; +} + +// ELF 0x24BE50: the six-argument form with the last flag false. +void BBPFire2dDriver::init(Bot* bot, unsigned int target, int weapon, bool flag20, bool flag21) +{ + init(bot, target, weapon, flag20, flag21, false); +} + +// ELF 0x24BF50. The Debug error is the image's (it aborts in this tree); the arguments are then +// stored like BBPFire3d's overload. +void BBPFire2dDriver::init(Bot* bot, unsigned int positionArg, const Vec3& position, int weapon) +{ + Debug(DebugTypeError, "AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2dDriver.cpp", 0x93, "") + << "LaserGuided missiles unsuported by artillry drivers."; + m_initiated[bot->getBotId()] = true; + m_targets[bot->getBotId()] = static_cast(-1); + m_weapons[bot->getBotId()] = weapon; + m_positionArgs[bot->getBotId()] = positionArg; + m_targetPositions[bot->getBotId()] = position; +} + +// ELF 0x251110 (weak) +int BBPFire2dDriver::getImplementationType() +{ + return 3; +} + +// ELF 0x24BEB0 +void BBPFire2dDriver::init(Bot* bot, unsigned int target, int weapon, bool flag20, bool flag21, bool flag28) +{ + m_initiated[bot->getBotId()] = true; + m_targets[bot->getBotId()] = target; + m_flags28[bot->getBotId()] = flag28; + m_weapons[bot->getBotId()] = weapon; + m_flag20 = flag20; + m_flag21 = flag21; + m_positionArgs[bot->getBotId()] = static_cast(-1); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2dDriver.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2dDriver.h new file mode 100644 index 000000000..828a4ac81 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2dDriver.h @@ -0,0 +1,42 @@ +// Fire pattern of artillery drivers and other ground vehicles aiming with their own turret. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPFIRE2DDRIVER_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPFIRE2DDRIVER_H + +#include "../../../../Math/Vec3.h" +#include "BBPFire.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BBD60 (9 words), operator new 0x2C, package H-deferred. +class BBPFire2dDriver : public BBPFire +{ +public: + explicit BBPFire2dDriver(int); // 0x24BBF0 + virtual ~BBPFire2dDriver(); // 0x24BDB0 + + virtual BotScript* createPlan(Bot*); // 0x24C100, slot +0x08; from the base declaration + virtual void init(Bot*, unsigned int, int, bool, bool); // 0x24BE50, slot +0x18; from the base declaration + virtual void init(Bot*, unsigned int, const Vec3&, int); // 0x24BF50, slot +0x1C; from the base declaration + virtual int getImplementationType(); // 0x251110, slot +0x20; from the base declaration + + void init(Bot*, unsigned int, int, bool, bool, bool); // 0x24BEB0; [INFERRED] ELF void + + // One flag per bot slot, allocated (not initialised) by the constructor; init's sixth + // argument. [UNRESOLVED] meaning: createPlan does not read it. + /* +0x28 */ bool* m_flags28; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPFIRE2DDRIVER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire3d.cpp new file mode 100644 index 000000000..38271410f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire3d.cpp @@ -0,0 +1,532 @@ +// Fire pattern of aircraft (AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire3d.cpp in the image). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Ghidra pseudocode was checked against the listing for constructor overloads, constant arguments +// and statement order (it drops the bool arguments of the combiner constructors and misreads the +// last turn lock of mode 1). +// [PLATFORM] precision: the x87 build keeps the radius sum and the bounding-box sum in extended +// precision before doubling or dividing; the float expressions below round them first. + +// static init: ELF 0x25B970 (__tcf_0 0x25B9D0, _GLOBAL__I 0x25BA00): 's Init object only. +#include + +#include "BBPFire3d.h" + +#include "../../../../Math/LocalBoundingBox.h" +#include "../../../../Math/Vec3.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadManager.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPAAimAtObject3d.h" +#include "../AIBotActionPlan/BAPAAimAtPoint3d.h" +#include "../AIBotActionPlan/BAPAChangeWeapon.h" +#include "../AIBotActionPlan/BAPAMoveTo3d.h" +#include "../AIBotActionPlan/BAPAMoveTo3dObject.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPATriggerContinously.h" +#include "../AIBotActionPlan/BAPAUseFlareOnMissileLock.h" +#include "../AIBotActionPlan/BAPCConBombPrecision3d.h" +#include "../AIBotActionPlan/BAPCConPrecision3d.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConAnd.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConInsideBattleZone.h" +#include "../AIBotActionPlan/BAPConNot.h" +#include "../AIBotActionPlan/BAPConObjectDistance.h" +#include "../AIBotActionPlan/BAPConObjectExists.h" +#include "../AIBotActionPlan/BAPConObjectHealth.h" +#include "../AIBotActionPlan/BAPConObjectInFront.h" +#include "../AIBotActionPlan/BAPConObjectLineOfFire.h" +#include "../AIBotActionPlan/BAPConObjectOccupied.h" +#include "../AIBotActionPlan/BAPConPointDistance.h" +#include "../AIBotActionPlan/BAPConPointInFront.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPConWeaponHasLockOnTarget.h" +#include "../AIBotActionPlan/BAPConWeaponHeat.h" +#include "../AIBotActionPlan/BAPConWeaponMagAmmo.h" +#include "../AIBotActionPlan/BAPFlowCIf.h" +#include "../AIBotActionPlan/BAPFlowCWhile.h" +#include "../AIBotActionPlan/BAPICTurnLock.h" +#include "../AIBotActionPlan/BAPIWFire.h" +#include "../AIBotActionPlan/BAPInfoWrapper.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIBotActionPlan/BAPVariable.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IBotManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// The image's inlined plan-variable construction: `checkPointer(new BAPVariable(context, value))` +// followed by `std::list::insert(context->begin(), &variable)`. +template +BAPVariable* newVariable(BAPContext* context, const T& value) +{ + BAPVariable* const variable = checkPointer(new BAPVariable(context, value)); + context->addVariable(variable); + return variable; +} + +// `1 << input` sign-extended to the 64-bit control mask (`movl %eax,%edx; sarl $0x1f,%edx`). +unsigned long long inputMask(int input) +{ + return static_cast(static_cast(static_cast(1u << input))); +} + +IAITerrain* terrain() +{ + return static_cast(CommonSingletonServer::m_iaiTerrain); +} + +void dropPlan(Bot* bot) +{ + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } +} + +// "The target is still worth attacking": And{ Exists(target), [Occupied(target)], Not(Health(target, 0)), +// [WeaponHeat(weapon) < heat] }, the loop condition of createPlanInternal's three arms. +BAPConAnd* newTargetAlive(BAPContext* context, unsigned int target, IPIUnit* targetUnit, WeaponInfo* weapon, + float heat) +{ + BAPConAnd* const alive = checkPointer(new BAPConAnd()); + alive->addCondition(checkPointer(new BAPConObjectExists(target))); + if (targetUnit && targetUnit->isOccupied()) + alive->addCondition(new BAPConObjectOccupied(target)); // no checkPointer in the image + alive->addCondition(checkPointer(new BAPConNot(checkPointer(new BAPConObjectHealth(target, 0.0f))))); + if (weapon->hasHeat()) + alive->addCondition(checkPointer(new BAPConWeaponHeat(newVariable(context, weapon), heat))); + return alive; +} + +} // namespace + +// ELF 0x2512C0: BBPFire(), the vtable store, then the argument at +0x08. +BBPFire3d::BBPFire3d(int patternId) + : BBPFire() +{ + m_patternId = patternId; +} + +// ELF 0x251340 (D0 0x251380): the vtable store, then BBPFire's destructor; nothing of its own. +BBPFire3d::~BBPFire3d() +{ +} + +// ELF 0x2514E0. Keeps a fire plan of this pattern built for the same target, flag and weapon; +// otherwise drops the plan and builds `IWFire(serial([change weapon], parallel(reset controls, +// flares on missile lock, attack)))`. The attack comes from createPlanLaserGuided when the target +// is no object but a designated point, otherwise from createPlanInternal with the FireData mode +// chosen from the own vehicle and the target. Without a usable target, or with no weapon chosen, +// no plan is built (with no weapon the own object's update is called first, as compiled). +BotScript* BBPFire3d::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + dropPlan(bot); + return 0; + } + + static_cast(bot)->resetAllControls(false, true, true); + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + if (bot->hasPlan() && static_cast(bot->getPlan())->getGeneratorId() == m_patternId + && static_cast(bot->getPlan())->getId() == BAPSTInfoWrapper + && static_cast(bot->getPlan())->getInfoType() == 0 + && static_cast(bot->getPlan())->getTarget() == m_targets[bot->getBotId()] + && m_flag20 == static_cast(bot->getPlan())->getFlagA() + && static_cast(bot->getPlan())->getWeapon() == m_weapons[bot->getBotId()]) + return bot->getPlan(); + + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + dropPlan(bot); + bot->getScriptContext()->clear(); + + const unsigned int target = m_targets[bot->getBotId()]; + Information* const targetInfo = informationManager->getInformation(target); + FireData data; + data.m_position.x = data.m_position.y = data.m_position.z = 0.0f; + WeaponInfo* const weapon = + WeaponInfoManager::m_instance->getInformation(self->getArmament()->getWeapon(m_weapons[bot->getBotId()])); + + BAPStatement* attack; + if (!targetInfo) + { + if (m_positionArgs[bot->getBotId()] == static_cast(-1)) + return 0; + attack = createPlanLaserGuided(bot, data); + } + else + { + IPIPhysical* const targetPhysical = targetInfo->getPhysical(); + IPIControlInfo* const controlInfo = self->getControlInfo(); + IPIPhysical* const selfPhysical = self->getPhysical(); + if (!targetPhysical || !controlInfo || !selfPhysical) + return 0; + IPIMobile* const targetMobile = targetInfo->getMobile(); + LocalBoundingBox* const box = const_cast(targetPhysical->getLocalBoundingBox()); + if (m_weapons[bot->getBotId()] == -1) + { + self->getAIObject()->update(); + return 0; + } + bot->getSquadMember()->clearRequestAction(); + const float selfRadius = selfPhysical->getRadius(); + const float radius = targetMobile ? targetPhysical->getRadius() + selfRadius : selfRadius + 0.0f; + data.m_approachRadius = radius + radius; + const bool indirect = weapon->getIndirect(); + const bool flag40 = targetInfo->isOfType(ITGround); + if (!self->getMobile()) + { + data.m_mode = 3; + } + else if (!flag40) + { + data.m_mode = 0; + data.m_precision = weapon->getAllowedDeviation(); + } + else if (!indirect) + { + data.m_mode = 1; + data.m_precision = weapon->getAllowedDeviation(); + } + else + { + data.m_mode = 2; + const float size = (box->getSize().x + box->getSize().y + box->getSize().z) / 3.0f; + data.m_precision = size > 10.0f ? size : 10.0f; // 0x251FD4 fcmovbe: NaN gives 10 + } + attack = createPlanInternal(bot, data); + } + + BAPCombinerParallel* const parallel = checkPointer(new BAPCombinerParallel(m_patternId, true, -1, false)); + parallel->addStatement(checkPointer(new BAPAResetControls(true, true, true, m_patternId))); + parallel->addStatement(new BAPAUseFlareOnMissileLock(bot, 0x800000000000ULL, m_patternId)); // no checkPointer + parallel->addStatement(attack); + BAPCombinerSerial* const serial = checkPointer(new BAPCombinerSerial(m_patternId, true, -1)); + if (m_weapons[bot->getBotId()] != -1 && weapon->getWeaponActivate() != 0x40) + serial->addStatement(checkPointer(new BAPAChangeWeapon(bot, m_weapons[bot->getBotId()], m_patternId))); + serial->addStatement(parallel); + BAPIWFire* const plan = checkPointer( + new BAPIWFire(bot, target, m_flag20, false, m_weapons[bot->getBotId()], -1, serial, m_patternId)); + plan->setParent(this); // +0x04 (BotScript::mpOwner) + SquadManager::m_instance->shotsFired(bot->getPlayerId(), bot->getSide(), m_targets[bot->getBotId()]); + return plan; +} + +// ELF 0x2513C0 +void BBPFire3d::init(Bot* bot, unsigned int target, int weapon, bool flag20, bool flag21) +{ + m_initiated[bot->getBotId()] = true; + m_targets[bot->getBotId()] = target; + m_positionArgs[bot->getBotId()] = static_cast(-1); + m_weapons[bot->getBotId()] = weapon; + m_flag20 = flag20; + m_flag21 = flag21; +} + +// ELF 0x251440 +void BBPFire3d::init(Bot* bot, unsigned int positionArg, const Vec3& position, int weapon) +{ + m_initiated[bot->getBotId()] = true; + m_targets[bot->getBotId()] = static_cast(-1); + m_weapons[bot->getBotId()] = weapon; + m_positionArgs[bot->getBotId()] = positionArg; + m_targetPositions[bot->getBotId()] = position; +} + +// ELF 0x25BA20 +int BBPFire3d::getImplementationType() +{ + return 4; +} + +// ELF 0x252260 (listing; the switch is `cmpl $1/2/3` at 0x252447). Modes 1 and 2 (the target has +// type flag 0x40) and mode 0 loop while the target is alive and, for a weapon with heat, not too +// hot: inside the battle zone (150) the bot attacks when the target is in range (mode 0: and in the +// line of fire; modes 1/2: and in front) and otherwise approaches it; outside it flies back to the +// map centre at 200 m. Modes 1 and 2 wrap the loop in a serial with a trailing turn unlock and lock +// turning during the attack. Mode 3 (no IPIMobile of its own) is the plain attack. +BAPStatement* BBPFire3d::createPlanInternal(Bot* bot, BBPFire3d::FireData& data) +{ + BAPContext* const context = bot->getScriptContext(); + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + IPIControlInfo* const controlInfo = self->getControlInfo(); + IPIArmament* const armament = self->getArmament(); + IPIMobile* const mobile = self->getMobile(); + WeaponInfo* const weapon = + WeaponInfoManager::m_instance->getInformation(armament->getWeapon(m_weapons[bot->getBotId()])); + if (m_weapons[bot->getBotId()] != -1) + armament->setActiveWeapon(m_weapons[bot->getBotId()], bot->getSide()); + + const unsigned int target = m_targets[bot->getBotId()]; + Information* const targetInfo = informationManager->getInformation(target); // no null test + IPIUnit* const targetUnit = targetInfo->getUnit(); + const float worldSizeX = static_cast(terrain()->getWorldSizeX()); + const float worldSizeZ = static_cast(terrain()->getWorldSizeZ()); + bool targetIsLodBot = false; + if (Bot* const targetBot = IBotManager::instance->getBot(targetInfo->getAIObject())) + targetIsLodBot = targetBot->getLodLevel() > 0; + + switch (data.m_mode) + { + case 1: + case 2: + { + // 0x255A14 (mode 1) and 0x252490 (mode 2) differ only in the order of the range + // conditions and in the approach (200 / 350) and return (200 / 300) distances. + const bool bomb = data.m_mode == 2; + BAPCombinerSerial* const root = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + BAPConAnd* const alive = newTargetAlive(context, target, targetUnit, weapon, 0.8f); + BAPConInsideBattleZone* const inside = checkPointer(new BAPConInsideBattleZone(150.0f)); + BAPConAnd* const inRange = checkPointer(new BAPConAnd()); + BAPConObjectInFront* const inFront = checkPointer(new BAPConObjectInFront(target, 10.0f, 0.0f)); + BAPConObjectDistance* const distance = + checkPointer(new BAPConObjectDistance(target, 0.9f, weapon->getMaxRange(), false, false)); + if (bomb) + { + inRange->addCondition(distance); + inRange->addCondition(inFront); + } + else + { + inRange->addCondition(inFront); + inRange->addCondition(distance); + } + BAPCombinerParallel* const attackBlock = checkPointer(new BAPCombinerParallel(m_patternId, -1, false)); + BAPICTurnLock* const lock = checkPointer(new BAPICTurnLock(true)); + BAPStatement* const attack = createMobileLessAttackPlan(bot, data); + attackBlock->addStatement(lock); + attackBlock->addStatement(attack); + BAPCombinerParallel* const approachBlock = checkPointer(new BAPCombinerParallel(m_patternId, -1, false)); + BAPICTurnLock* const unlock = checkPointer(new BAPICTurnLock(false)); + BAPCombinerSerial* const approach = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + approach->addStatement(checkPointer(new BAPAMoveTo3dObject( + target, data.m_approachRadius, mobile->getMaxSpeed(), mobile->getMaxSpeed(), bomb ? 350.0f : 200.0f, + checkPointer(new BAPConFalse()), controlInfo->getDriveControls(), m_patternId))); + approachBlock->addStatement(unlock); + approachBlock->addStatement(approach); + BAPFlowCIf* const engage = + checkPointer(new BAPFlowCIf(inRange, attackBlock, approachBlock, m_patternId, true, false)); + const Vec3 centre = { worldSizeX * 0.5f, 200.0f, worldSizeZ * 0.5f }; + BAPAMoveTo3d* const back = checkPointer(new BAPAMoveTo3d( + bot, centre, mobile->getMaxSpeed(), mobile->getMaxSpeed(), checkPointer(new BAPConInsideBattleZone(200.0f)), + controlInfo->getDriveControls(), bomb ? 300.0f : 200.0f, m_patternId)); + BAPFlowCIf* const zone = checkPointer(new BAPFlowCIf(inside, engage, back, m_patternId, true, false)); + BAPFlowCWhile* const loop = checkPointer(new BAPFlowCWhile(alive, zone, m_patternId)); + BAPICTurnLock* const release = checkPointer(new BAPICTurnLock(false)); + root->addStatement(loop); + root->addStatement(release); + return root; + } + case 0: + { + // 0x254214 + BAPConAnd* const alive = newTargetAlive(context, target, targetUnit, weapon, 0.5f); + BAPConInsideBattleZone* const inside = checkPointer(new BAPConInsideBattleZone(150.0f)); + BAPConAnd* const inRange = checkPointer(new BAPConAnd()); + inRange->addCondition(checkPointer(new BAPConObjectDistance(target, 0.9f, weapon->getMaxRange(), false, false))); + inRange->addCondition(checkPointer(new BAPConObjectLineOfFire(target, targetIsLodBot))); + BAPStatement* const attack = createMobileLessAttackPlan(bot, data); + BAPConAnd* const stopApproach = checkPointer(new BAPConAnd()); + BAPConObjectDistance* const distance = + checkPointer(new BAPConObjectDistance(target, 0.8f, weapon->getMaxRange(), false, false)); + BAPConObjectLineOfFire* const lineOfFire = checkPointer(new BAPConObjectLineOfFire(target, targetIsLodBot)); + stopApproach->addCondition(distance); + stopApproach->addCondition(lineOfFire); + BAPAMoveTo3dObject* const approach = checkPointer(new BAPAMoveTo3dObject( + target, data.m_approachRadius, mobile->getMaxSpeed(), mobile->getMaxSpeed() * 0.5f, 50.0f, stopApproach, + controlInfo->getDriveControls(), m_patternId)); + BAPFlowCIf* const engage = checkPointer(new BAPFlowCIf(inRange, attack, approach, m_patternId, false, false)); + const Vec3 centre = { worldSizeX * 0.5f, 200.0f, worldSizeZ * 0.5f }; + BAPAMoveTo3d* const back = checkPointer(new BAPAMoveTo3d( + bot, centre, mobile->getMaxSpeed(), mobile->getMaxSpeed(), checkPointer(new BAPConInsideBattleZone(200.0f)), + controlInfo->getDriveControls(), 200.0f, m_patternId)); + BAPFlowCIf* const zone = checkPointer(new BAPFlowCIf(inside, engage, back, m_patternId, true, false)); + return checkPointer(new BAPFlowCWhile(alive, zone, m_patternId)); + } + case 3: + return createMobileLessAttackPlan(bot, data); // 0x25246A + default: + return 0; + } +} + +// ELF 0x2577D0. The attack itself: serial(arm the weapon, [reload when the magazine is empty], +// parallel(aim, trigger)). Arming is a reset of the controls, plus pressing the weapon's activation +// input unless it is 0x40. The aim is at the target object, or at FireData::m_position when there +// is no target. The trigger fires while the aim precision holds (modes 0, 1 and 3 also need the +// weapon's range; mode 3 a missile lock for guidance type 1; mode 2 uses the bomb precision); +// burst weapons hold the trigger continuously. +BAPStatement* BBPFire3d::createMobileLessAttackPlan(Bot* bot, BBPFire3d::FireData& data) +{ + BAPContext* const context = bot->getScriptContext(); + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + IPIArmament* const armament = self->getArmament(); + IPIControlInfo* const controlInfo = self->getControlInfo(); + WeaponInfo* const weapon = + WeaponInfoManager::m_instance->getInformation(armament->getWeapon(m_weapons[bot->getBotId()])); + const unsigned int target = m_targets[bot->getBotId()]; + BAPCombinerSerial* const root = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + + BAPStatement* arm; + if (weapon->getWeaponActivate() == 0x40) + { + arm = checkPointer(new BAPAResetControls(false, true, true, m_patternId)); + } + else + { + BAPCombinerParallel* const block = checkPointer(new BAPCombinerParallel(m_patternId, -1, false)); + BAPAResetControls* const reset = checkPointer(new BAPAResetControls(false, true, true, m_patternId)); + BAPATrigger* const activate = checkPointer(new BAPATrigger( + static_cast(weapon->getWeaponActivate()), checkPointer(new BAPConTrue()), + checkPointer(new BAPConFalse()), inputMask(weapon->getWeaponActivate()), m_patternId, 0.0, false)); + block->addStatement(reset); + block->addStatement(activate); + arm = block; + } + root->addStatement(arm); + + if (!weapon->hasAutoReload()) + { + BAPVariable* const ammo = newVariable(context, 0); + BAPVariable* const weaponVariable = newVariable(context, weapon); + BAPConWeaponMagAmmo* const empty = checkPointer(new BAPConWeaponMagAmmo(weaponVariable, ammo, false)); + // Input 0x20 with the mask constant 0x100000000 (bit 32). + BAPATrigger* const reload = checkPointer(new BAPATrigger( + static_cast(0x20), checkPointer(new BAPConTrue()), checkPointer(new BAPConFalse()), + 0x100000000ULL, m_patternId, 0.0, false)); + root->addStatement(checkPointer(new BAPFlowCIf(empty, reload, 0, m_patternId, false, false))); + } + + BAPCombinerParallel* const fire = checkPointer(new BAPCombinerParallel(m_patternId, -1, false)); + BAPAAimAt3d* aim; + if (target == static_cast(-1)) + { + Vec3 offset = { 0.0f, 0.0f, 0.0f }; + aim = checkPointer(new BAPAAimAtPoint3d(data.m_position, offset, checkPointer(new BAPConFalse()), + controlInfo->getAimControls(), m_patternId, 50.0f, 350.0f)); + } + else + { + const Vec3 offset = { 0.0f, 0.0f, 0.0f }; + aim = checkPointer(new BAPAAimAtObject3d(bot, target, offset, checkPointer(new BAPConFalse()), + controlInfo->getAimControls(), m_patternId, + data.m_mode != 1 ? 40.0f : 50.0f, 350.0f)); + } + + BAPConAnd* const ready = checkPointer(new BAPConAnd()); + BAPCondition* precision = 0; + if (data.m_mode == 1) + { + ready->addCondition(checkPointer(new BAPConObjectDistance(target, weapon->getMaxRange(), false, false, false))); + precision = checkPointer(new BAPCConPrecision3d(target, aim, data.m_precision, !weapon->getBurst())); + } + else if (data.m_mode == 2) + { + precision = checkPointer(new BAPCConBombPrecision3d(aim, data.m_precision, true)); + } + else if (data.m_mode == 0 || data.m_mode == 3) + { + ready->addCondition(checkPointer(new BAPConObjectDistance(target, weapon->getMaxRange(), false, false, false))); + if (weapon->getWeaponGuidanceType() == 1) + precision = checkPointer(new BAPConWeaponHasLockOnTarget(newVariable(context, weapon), target)); + else + precision = checkPointer(new BAPCConPrecision3d(target, aim, data.m_precision, !weapon->getBurst())); + } + ready->addCondition(precision); // a null condition for any other mode, as compiled + + BAPStatement* trigger; + if (!weapon->getBurst()) + trigger = checkPointer(new BAPATrigger(static_cast(weapon->getWeaponFire()), ready, + checkPointer(new BAPConFalse()), inputMask(weapon->getWeaponFire()), + m_patternId, 0.0, true)); + else + trigger = checkPointer(new BAPATriggerContinously(static_cast(weapon->getWeaponFire()), + ready, 0, checkPointer(new BAPConFalse()), + inputMask(weapon->getWeaponFire()), m_patternId, 0.0)); + fire->addStatement(aim); + fire->addStatement(trigger); + root->addStatement(fire); + return root; +} + +// ELF 0x25A260. Attack on a designated point (init's Vec3 overload): mode 2 with radius 20 and +// precision 40 at the stored position; the weapon is told its target (the handle argument). +// Inside the battle zone (150) the bot attacks when the point is in range and in front, otherwise +// flies to it at 50 m; outside it returns to the map centre at 300 m. +BAPStatement* BBPFire3d::createPlanLaserGuided(Bot* bot, BBPFire3d::FireData& data) +{ + data.m_mode = 2; + data.m_approachRadius = 20.0f; + data.m_precision = 40.0f; + data.m_position = m_targetPositions[bot->getBotId()]; + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* const mobile = self->getMobile(); + IPIArmament* const armament = self->getArmament(); + IPIControlInfo* const controlInfo = self->getControlInfo(); + WeaponInfo* const weapon = + WeaponInfoManager::m_instance->getInformation(armament->getWeapon(m_weapons[bot->getBotId()])); + weapon->setTarget(m_positionArgs[bot->getBotId()]); + + BAPCombinerSerial* const root = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + BAPConInsideBattleZone* const inside = checkPointer(new BAPConInsideBattleZone(150.0f)); + BAPConAnd* const inRange = checkPointer(new BAPConAnd()); + BAPConPointInFront* const inFront = checkPointer(new BAPConPointInFront(data.m_position, 10.0f, 0.0f)); + BAPConPointDistance* const distance = + checkPointer(new BAPConPointDistance(data.m_position, 0.9f, weapon->getMaxRange(), false)); + inRange->addCondition(distance); + inRange->addCondition(inFront); + BAPCombinerParallel* const attackBlock = checkPointer(new BAPCombinerParallel(m_patternId, -1, false)); + BAPICTurnLock* const lock = checkPointer(new BAPICTurnLock(true)); + BAPStatement* const attack = createMobileLessAttackPlan(bot, data); + attackBlock->addStatement(lock); + attackBlock->addStatement(attack); + BAPCombinerParallel* const approachBlock = checkPointer(new BAPCombinerParallel(m_patternId, -1, false)); + BAPICTurnLock* const unlock = checkPointer(new BAPICTurnLock(false)); + BAPCombinerSerial* const approach = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + approach->addStatement(checkPointer(new BAPAMoveTo3d(bot, data.m_position, mobile->getMaxSpeed(), + mobile->getMaxSpeed(), checkPointer(new BAPConFalse()), + controlInfo->getDriveControls(), 50.0f, m_patternId))); + approachBlock->addStatement(unlock); + approachBlock->addStatement(approach); + BAPFlowCIf* const engage = + checkPointer(new BAPFlowCIf(inRange, attackBlock, approachBlock, m_patternId, true, false)); + const float worldSizeX = static_cast(terrain()->getWorldSizeX()); + const float worldSizeZ = static_cast(terrain()->getWorldSizeZ()); + const Vec3 centre = { worldSizeX * 0.5f, 200.0f, worldSizeZ * 0.5f }; + BAPAMoveTo3d* const back = checkPointer(new BAPAMoveTo3d( + bot, centre, mobile->getMaxSpeed(), mobile->getMaxSpeed(), checkPointer(new BAPConInsideBattleZone(200.0f)), + controlInfo->getDriveControls(), 300.0f, m_patternId)); + BAPFlowCIf* const zone = checkPointer(new BAPFlowCIf(inside, engage, back, m_patternId, true, false)); + BAPICTurnLock* const release = checkPointer(new BAPICTurnLock(false)); + root->addStatement(zone); + root->addStatement(release); + return root; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire3d.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire3d.h new file mode 100644 index 000000000..110ee939e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire3d.h @@ -0,0 +1,58 @@ +// Fire pattern of aircraft (3d navigation): attack runs against a target object or a laser-designated +// point, built by createPlan from the target and the chosen weapon. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPFIRE3D_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPFIRE3D_H + +#include "../../../../Math/Vec3.h" +#include "BBPFire.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +class BAPStatement; + +// ELF: vtable 0x4BBE00 (9 words), operator new 0x28 (nothing beyond BBPFire), package G-vehicles. +class BBPFire3d : public BBPFire +{ +public: + // The attack parameters createPlan hands to the plan builders; a stack object of createPlan + // (no constructor in the image). Names are [INFERRED] from createPlan (0x2514E0). + struct FireData + { + /* +0x00 */ int m_unused00; // [UNRESOLVED] neither written nor read by BBPFire3d + // 0: target without object type flag 0x40; 1: flag 0x40, direct weapon; 2: flag 0x40, + // indirect weapon, or a laser-designated point; 3: the own vehicle has no IPIMobile. + /* +0x04 */ int m_mode; + /* +0x08 */ float m_approachRadius; // twice the own (plus the moving target's) physical radius + /* +0x0C */ float m_precision; // weapon deviation, or the target's mean box size (at least 10) + /* +0x10 */ Vec3 m_position; // zero, or the laser-designated point + }; + + explicit BBPFire3d(int); // 0x2512C0 + virtual ~BBPFire3d(); // 0x251340 + + virtual BotScript* createPlan(Bot*); // 0x2514E0, slot +0x08 + virtual void init(Bot*, unsigned int, int, bool, bool); // 0x2513C0, slot +0x18 + virtual void init(Bot*, unsigned int, const Vec3&, int); // 0x251440, slot +0x1C + virtual int getImplementationType(); // 0x25BA20, slot +0x20: 4 + + // The three builders return the statement createPlan puts into its parallel block + // (`movl %eax,-0x18c(%ebp)` after each call, 0x2517CC). + BAPStatement* createPlanInternal(Bot*, BBPFire3d::FireData&); // 0x252260 + BAPStatement* createMobileLessAttackPlan(Bot*, BBPFire3d::FireData&); // 0x2577D0 + BAPStatement* createPlanLaserGuided(Bot*, BBPFire3d::FireData&); // 0x25A260 +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPFIRE3D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFireInfantery.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFireInfantery.cpp new file mode 100644 index 000000000..b89ca80ab --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFireInfantery.cpp @@ -0,0 +1,2161 @@ +// Infantry fire pattern: chooses how a soldier bot engages its target (direct weapon, indirect +// weapon from here or from a firing position) and builds the matching action plan. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, with symbols); every body carries its ELF +// address. x87 code was read with the AT&T fsub(r)p/fdiv(r)p operand swap in mind. Package E +// (docs/macos-ai-behaviour-plan.md). + +// static init: ELF 0x27BA40 (__tcf_0 0x27BAA0, _GLOBAL__I 0x27BAD0): 's Init object only. +#include + +#include "BBPFireInfantery.h" + +#include +#include +#include + +#include "../../../../Core/Debug.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SensedObject.h" +#include "../AIBot/SquadCoordinator.h" +#include "../AIBot/SquadManager.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPAAimAt.h" +#include "../AIBotActionPlan/BAPAAimAtPoint.h" +#include "../AIBotActionPlan/BAPALook.h" +#include "../AIBotActionPlan/BAPALookAtPoint.h" +#include "../AIBotActionPlan/BAPATriggerContinously.h" +#include "../AIBotActionPlan/BAPCConLookDeviation.h" +#include "../AIBotActionPlan/BAPCConPrecision.h" +#include "../AIBotActionPlan/BAPConAllowFire.h" +#include "../AIBotActionPlan/BAPConDistanceToProj.h" +#include "../AIBotActionPlan/BAPConOkToThrowGrenade.h" +#include "../AIBotActionPlan/BAPConSplashDamage.h" +#include "../AIBotActionPlan/BAPConWeaponHasLockOnTarget.h" +#include "../AIBotActionPlan/BAPConWeaponHeat.h" +#include "../AIBotActionPlan/BAPConWeaponIsZoomed.h" +#include "../AIBotActionPlan/BAPAAimAtObject.h" +#include "../AIBotActionPlan/BAPAChangeWeapon.h" +#include "../AIBotActionPlan/BAPAEvaluateCondition.h" +#include "../AIBotActionPlan/BAPAForgetTarget.h" +#include "../AIBotActionPlan/BAPAIdle.h" +#include "../AIBotActionPlan/BAPALookAtObject.h" +#include "../AIBotActionPlan/BAPAMergeSoldierInputs.h" +#include "../AIBotActionPlan/BAPAMoveToFinding.h" +#include "../AIBotActionPlan/BAPAMoveToObjectFinding.h" +#include "../AIBotActionPlan/BAPAOverrideSensingAgent.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPASoldierPose.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPAUseFlareOnMissileLock.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConAnd.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConIsSprinting.h" +#include "../AIBotActionPlan/BAPConNot.h" +#include "../AIBotActionPlan/BAPConObjectDistance.h" +#include "../AIBotActionPlan/BAPConObjectHealth.h" +#include "../AIBotActionPlan/BAPConObjectLineOfFire.h" +#include "../AIBotActionPlan/BAPConObjectMoved.h" +#include "../AIBotActionPlan/BAPConObjectValidAiming.h" +#include "../AIBotActionPlan/BAPConOr.h" +#include "../AIBotActionPlan/BAPConPointDistance.h" +#include "../AIBotActionPlan/BAPConPosition.h" +#include "../AIBotActionPlan/BAPConSharedCondition.h" +#include "../AIBotActionPlan/BAPConStrategicObjectStatus.h" +#include "../AIBotActionPlan/BAPConTime.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPConWeaponDetonatorIsActive.h" +#include "../AIBotActionPlan/BAPConWeaponMagAmmo.h" +#include "../AIBotActionPlan/BAPConWeaponReadyToFire.h" +#include "../AIBotActionPlan/BAPFlowCEnd.h" +#include "../AIBotActionPlan/BAPFlowCIf.h" +#include "../AIBotActionPlan/BAPFlowCWhile.h" +#include "../AIBotActionPlan/BAPICTurnLock.h" +#include "../AIBotActionPlan/BAPWrapperAiming.h" +#include "../AIBotActionPlan/BAPWrapperLookAt.h" +#include "../AIBotActionPlan/BAPIWFire.h" +#include "../AIBotActionPlan/BAPInfoWrapper.h" +#include "../AIBotBehaviour/BBFire.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIStrategicEntity/AIStrategicArea.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../AIUtils/TraceUtils.h" +#include "../Main/AIRandom.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IAIPathfinding.h" +#include "../Main/IBotManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +double gameTime() +{ + return static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); +} + +int maxBots() +{ + return static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); +} + +// [INFERRED] helper shape: the image inlines AIRandom's tempering and computes +// `r * 2.3283064e-10 * scale + offset` at every site (createPlan 0x25E382, 0x25DF17, ...). +float randomFloat(float scale, float offset) +{ + return AIRandom::m_instance->nextFloat() * scale + offset; +} + +IAIObjectEnvironment* objectEnvironment() +{ + return static_cast(CommonSingletonServer::m_iaiObjectEnvironment); +} + +// ELF 0x25C5F0. Finds a firing position for an indirect weapon: 10 m short of the target, then +// moved along the line towards (too far) or away from (too close) the target so that the +// weapon's minimum range plus 3 m fits, snapped to the navmesh. Returns false (no position) when +// the 10-m point is already inside [minRange, maxRange]; outBase is written in every case. +bool getIndirectWeaponCloseToFiringPositions(Vec3& outPosition, Vec3& outBase, Information* self, + IPIMobile* mobile, int equipmentType, WeaponInfo* weapon, + Information* target, const Vec3& targetPosition) +{ + const Vec3& selfPosition = self->getPosition(); + Vec3 aim = targetPosition; + Vec3 dir = { aim.x - selfPosition.x, aim.y - selfPosition.y, aim.z - selfPosition.z }; + float distance = std::sqrt(dir.x * dir.x + dir.y * dir.y + dir.z * dir.z); + if (distance > 0.0001f) + { + const float inv = 1.0f / distance; + dir.x *= inv; + dir.y *= inv; + dir.z *= inv; + } + distance -= 10.0f; + const Vec3 step = { dir.x * 10.0f, dir.y * 10.0f, dir.z * 10.0f }; + aim.x -= step.x; + aim.y -= step.y; + aim.z -= step.z; + outBase = aim; + + unsigned int polygon; + unsigned int cluster; + Vec3 position; + if (!(weapon->getMinRange() > distance)) // 0x25C705 jbe: NaN takes this arm + { + if (!(distance > weapon->getMaxRange())) // 0x25C7F0 jbe: NaN returns false + return false; + + // Too far: walk towards the target. + const Vec3& from = self->getPosition(); + const float move = (distance + 3.0f) - weapon->getMinRange(); + position.x = dir.x * move + from.x; + position.y = dir.y * move + from.y; + position.z = move * dir.z + from.z; + } + else + { + // Too close: back away from the target. + const Vec3& from = self->getPosition(); + const float move = (weapon->getMinRange() + 3.0f) - distance; + const Vec3 offset = { dir.x * move, dir.y * move, move * dir.z }; + position.x = from.x - offset.x; + position.y = from.y - offset.y; + position.z = from.z - offset.z; + } + const Vec3& reference = target->getPosition(); + const int vehicleNumber = mobile->getVehicleNumber(); + IAIPathfinding::instance->findClosestValidPolygon(polygon, cluster, outPosition, vehicleNumber, position, + reference, 10, equipmentType); + return true; +} + +// ELF 0x25C8E0: `xorl %eax,%eax; ret` - aiming failures are never detected in this build. +bool detectAimingFailure(BotMain*) +{ + return false; +} + +// The image's "drop the plan" sequence (createPlan 0x25C8F0 head and 0x25D769). +void dropPlan(Bot* bot) +{ + if (bot->getPlan()) + { + BotScript* const plan = bot->getPlan(); + delete plan; + bot->setPlan(0); + } +} + +// Phase 3 (firing) is over when the target is dead or the magazine is empty (m_shots == -1), or +// when the burst is fired; a finished decision goes to the front of the history +// (createPlan 0x25E93D..0x25E906, three copies in the image). +bool burstFinished(BBPFireInfantery::Data& data, const BBPFireInfantery::FiringState* state, + IPIPhysical* targetPhysical, WeaponInfo* weapon, IAIPlayer* player) +{ + if (state->m_shots == -1) + { + if (targetPhysical->getHealth() <= 0.0f || weapon->getAmmo() == 0) + { + data.m_history.push_front(data.m_decision); + return true; + } + return false; + } + if (state->m_shots <= player->getNumShotsFired(weapon->getWeapon()) - data.m_shotsAtPhaseStart + || weapon->getAmmo() == 0) + { + data.m_history.push_front(data.m_decision); + return true; + } + return false; +} + +} // namespace + +// ELF 0x25BAA0 +BBPFireInfantery::FiringState::FiringState() + : m_target(static_cast(-1)) + , m_weapon(-1) + , m_shots(-1) + , m_bool0C(false) + , m_bool14(false) + , m_backOff(false) + , m_independentAim(false) + , m_hasFiringPosition(false) + , m_bool24(false) + , m_bool25(false) + , m_bool26(false) + , m_arrivalRadius(0.0f) +{ + m_position.x = m_position.y = m_position.z = 0.0f; + m_firingPosition.x = m_firingPosition.y = m_firingPosition.z = 0.0f; +} + +// ELF 0x25BC60 +BBPFireInfantery::Data::Data() + : m_decision(FireDecisionNone) + , m_history() + , m_phase(0) + , m_lockStartTime(0.0) + , m_lockDuration(10.0) + , m_int4C(-1) + , m_int50(-1) +{ + m_vec24.x = m_vec24.y = m_vec24.z = 0.0f; + m_phaseTargetPosition.x = m_phaseTargetPosition.y = m_phaseTargetPosition.z = 0.0f; + m_firePosition.x = m_firePosition.y = m_firePosition.z = 0.0f; +} + +// ELF 0x25BFE0 +BBPFireInfantery::BBPFireInfantery(int patternId) + : BBPFire() +{ + m_patternId = patternId; + m_firingStates = checkPointer(new FiringState[maxBots()]); + m_data = checkPointer(new Data[maxBots()]); +} + +// ELF 0x25C350 +BBPFireInfantery::~BBPFireInfantery() +{ + delete[] m_firingStates; + delete[] m_data; +} + +// ELF 0x27BC00 +int BBPFireInfantery::getImplementationType() +{ + return 5; +} + +// ELF 0x25C480. Both bools are unused. +void BBPFireInfantery::init(Bot* bot, unsigned int target, int weapon, bool, bool) +{ + const unsigned int id = bot->getBotId(); + m_targetChanged[id] = target != m_targets[id]; + m_targets[id] = target; + m_weapons[id] = weapon; + if (!m_initiated[id]) + { + Data& data = m_data[id]; + data.m_decision = Data::FireDecisionNone; + data.m_phase = 0; + data.m_lockStartTime = 0.0; + data.m_lockDuration = 10.0; + m_firingStates[id].m_target = static_cast(-1); + } + m_initiated[id] = true; +} + +// ELF 0x25C530 +void BBPFireInfantery::init(Bot* bot, unsigned int positionArg, const Vec3& position, int weapon) +{ + const unsigned int id = bot->getBotId(); + m_initiated[id] = true; + m_targets[id] = static_cast(-1); + m_weapons[id] = weapon; + m_positionArgs[id] = positionArg; + m_targetPositions[id] = position; + Data& data = m_data[id]; + data.m_decision = Data::FireDecisionNone; + data.m_phase = 0; + data.m_lockStartTime = 0.0; + data.m_lockDuration = 10.0; + m_firingStates[id].m_target = static_cast(-1); +} + +// ELF 0x25C8F0 (2,906 instructions; Ghidra pseudocode cross-checked against the listing at the +// jump tables 0x4A00C4 / 0x4A00DC, the isFireAllowed sites 0x25D7FC / 0x25D60E and the range +// checks 0x25D830..0x25DA1E). Keeps the current plan while it is this pattern's fire plan for the +// same target, weapon and static-attack mode; otherwise re-evaluates the per-bot decision (Data), +// fills the bot's FiringState and asks createPlanInternal for the plan. Returns 0 and drops the +// current plan while a new decision is pending. +BotScript* BBPFireInfantery::createPlan(Bot* bot) +{ + const unsigned int id = bot->getBotId(); + FiringState* const state = &m_firingStates[id]; + Data& data = m_data[id]; + + if (!m_initiated[id]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + dropPlan(bot); + return 0; + } + + BBFire* const urgencyGenerator = static_cast(m_urgencyGenerator); + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + IPIArmament* const armament = self->getArmament(); + IPIPhysical* const selfPhysical = self->getPhysical(); + IPIControlInfo* const controlInfo = self->getControlInfo(); + IAIPlayer* const player = bot->getPlayer(); + if (!armament || !selfPhysical || !controlInfo || !player) + { + m_initiated[id] = false; + return bot->getPlan(); + } + + const int equipmentType = self->getUnit()->getEquipmentType(); + const Vec3& selfPosition = self->getPosition(); + IPIMobile* const selfMobile = self->getMobile(); + bool independentAim = false; + if (selfMobile) + { + independentAim = (controlInfo->getDriveControls() & controlInfo->getAimControls()) == 0; + selfMobile->getSector(); // [UNRESOLVED] result unused in the image (0x25CA96) + } + + bool freshPlan = false; + if (!bot->hasPlan() || static_cast(bot->getPlan())->getGeneratorId() != m_patternId + || static_cast(CommonSingletonServer::m_iaiSettings)->getBotSkill() < 0.3f) + freshPlan = true; + m_freshPlan = freshPlan; + + // Keep the current plan while nothing it was built from has changed (0x25F541..0x25F5D8). + int previousWeapon = -1; + if (bot->hasPlan()) + { + if (static_cast(bot->getPlan())->getGeneratorId() == m_patternId + && static_cast(bot->getPlan())->getId() == BAPSTInfoWrapper + && static_cast(bot->getPlan())->getInfoType() == 0 + && static_cast(bot->getPlan())->getTarget() == m_targets[bot->getBotId()] + && m_flag20 == static_cast(bot->getPlan())->getFlagA()) + { + previousWeapon = static_cast(bot->getPlan())->getWeapon(); + if (previousWeapon == m_weapons[bot->getBotId()] + && static_cast(bot->getPlan())->getUseStaticAttack() + == static_cast(bot)->getUseStaticAttack()) + return bot->getPlan(); + } + } + + unsigned int target = m_targets[id]; + Information* targetInfo = informationManager->getInformation(target); + IPIUnit* const targetUnit = targetInfo ? targetInfo->getUnit() : 0; + Information* vehicleInfo = 0; + SensedObject* sensed = 0; + if (targetUnit && targetUnit->getAlwaysTargetSoldier()) + { + // Aim at the soldier in the vehicle instead, when this bot senses him. + Information* const occupant = + informationManager->getInformation(targetUnit->getOccupiedObject(bot->getSide())); + if (occupant) + { + sensed = bot->getSensedObjectFromHandle(targetUnit->getOccupiedObject(bot->getSide())); + if (sensed) + { + target = targetUnit->getOccupiedObject(bot->getSide()); + vehicleInfo = targetInfo; + targetInfo = occupant; + } + } + } + IPIPhysical* const targetPhysical = targetInfo ? targetInfo->getPhysical() : 0; + if (!sensed) + sensed = bot->getSensedObjectFromHandle(target); + if (!targetInfo || !targetPhysical || !sensed) + { + m_initiated[id] = false; + return bot->getPlan(); + } + + bool targetIsLodBot = false; + if (Bot* const targetBot = IBotManager::instance->getBot(targetInfo->getAIObject())) + targetIsLodBot = targetBot->getLodLevel() > 0; + + const Vec3 targetPosition = targetInfo->getPosition(); + if (IPIMobile* const targetMobile = targetInfo->getMobile()) + targetMobile->getSector(); // [UNRESOLVED] result unused in the image (0x25CC3D) + + if (!(sensed->m_flags & 0x20)) + { + sensed->m_fireRating = 0; + sensed->m_unresolved44 = 0; + sensed->m_flags |= 0x20; + sensed->m_lastSense = 0x20; + } + + std::vector excluded; + excluded.push_back(self->getAIObject()); + excluded.push_back(targetInfo->getAIObject()); + if (vehicleInfo) + excluded.push_back(vehicleInfo->getAIObject()); + + const Vec3 toTarget = { targetPosition.x - selfPosition.x, targetPosition.y - selfPosition.y, + targetPosition.z - selfPosition.z }; + const float targetDistance = + std::sqrt(toTarget.x * toTarget.x + toTarget.y * toTarget.y + toTarget.z * toTarget.z); + Vec3 direction = { targetPosition.x - selfPosition.x, targetPosition.y - selfPosition.y, + targetPosition.z - selfPosition.z }; + const float directionLength = + std::sqrt(direction.z * direction.z + direction.x * direction.x + direction.y * direction.y); + if (directionLength > 0.0001f) + { + const float inv = 1.0f / directionLength; + direction.x *= inv; + direction.y *= inv; + direction.z *= inv; + } + + const int weapon = m_weapons[id]; + WeaponInfo* directWeapon = 0; + WeaponInfo* indirectWeapon = 0; + WeaponInfo* previousWeaponInfo = 0; + if (weapon != -1) + { + // The image looks the same weapon up twice (0x25CEF6 / 0x25CF28). + directWeapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(weapon)); + indirectWeapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(weapon)); + } + if (previousWeapon != -1) + previousWeaponInfo = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(previousWeapon)); + + if (weapon == -1) + { + sensed->m_fireRating = -100; + return bot->getPlan(); + } + + // The sensed part's offset in the target's frame, in world space. + const Mat4& targetTransform = targetInfo->getTransformation(); + const Vec3& part = sensed->m_seenPosition; + const Vec3 aimPoint = { + targetTransform.m[8] * part.z + targetTransform.m[0] * part.x + targetTransform.m[4] * part.y + + targetTransform.m[12], + targetTransform.m[1] * part.x + targetTransform.m[5] * part.y + targetTransform.m[9] * part.z + + targetTransform.m[13], + part.x * targetTransform.m[2] + part.y * targetTransform.m[6] + part.z * targetTransform.m[10] + + targetTransform.m[14] + }; + // The camera position (translation row) is copied to the stack and never read (0x25D029). + const float* const camera = static_cast(bot->getPlayer()->getCameraTransformation()); + const Vec3 cameraPosition = { camera[12], camera[13], camera[14] }; + (void)cameraPosition; + + const double now = gameTime(); + if (state->m_target != target || now - data.m_lastUpdateTime > 5.0) + { + data.m_decision = Data::FireDecisionNone; + data.m_history.clear(); + data.m_int4C = -1; + data.m_int50 = -1; + data.m_lockStartTime = 0.0; + data.m_lockDuration = 0.0; + } + + float firingPositionDistance = 0.0f; // XZ distance to the state's position + if (state->m_hasFiringPosition) + { + const float dx = state->m_position.x - selfPosition.x; + const float dz = state->m_position.z - selfPosition.z; + firingPositionDistance = std::sqrt(dz * dz + dx * dx); + } + + // 1. Is the current decision finished or invalid? (jump table 0x4A00C4: 0, 1, 2, 4, 5; 3 and + // anything above 5 report and keep the decision) + bool redecide = false; + bool reset = false; // the image's `decision = phase = 0` tail at 0x25E924 + switch (data.m_decision) + { + case Data::FireDecisionNone: + redecide = true; + reset = true; + break; + + case Data::FireDecision1: + case Data::FireDecision2: + { + WeaponInfo* const current = data.m_decision == Data::FireDecision1 ? directWeapon : indirectWeapon; + if (!current) + { + redecide = false; + reset = true; + break; + } + const int phase = data.m_phase; + if (phase == 0) + { + redecide = false; + } + else if (data.m_decision == Data::FireDecision1 && phase == 2 && self->getMobile()) + { + if (!previousWeaponInfo) + redecide = true; + else if (state->m_bool14) + redecide = previousWeaponInfo->getMinRange() + 1.0f < targetDistance; + else + { + redecide = true; + reset = true; + } + } + else if (phase == 1 && self->getMobile()) + { + if (!previousWeaponInfo) + redecide = true; + else if (state->m_bool14) + redecide = previousWeaponInfo->getMinRange() < targetDistance + && targetDistance < previousWeaponInfo->getMaxRange(); + else if (state->m_hasFiringPosition) + { + const float dx = targetPosition.x - data.m_phaseTargetPosition.x; + const float dy = targetPosition.y - data.m_phaseTargetPosition.y; + const float dz = targetPosition.z - data.m_phaseTargetPosition.z; + if (std::sqrt(dz * dz + dx * dx + dy * dy) > 10.0f) + { + redecide = true; + reset = true; + } + else + { + redecide = firingPositionDistance < state->m_arrivalRadius + || (previousWeaponInfo->getMinRange() < targetDistance + && targetDistance < previousWeaponInfo->getMaxRange()); + } + } + } + else if (phase == 3) + { + if (!previousWeaponInfo || !current) + { + redecide = true; + reset = true; + break; + } + const bool aimingFailed = detectAimingFailure(static_cast(bot)); + bool inRange = false; + if ((self->getMobile() || previousWeaponInfo->getMinRange() < targetDistance) + && targetDistance < previousWeaponInfo->getMaxRange()) + inRange = true; + if (aimingFailed) + { + urgencyGenerator->getBBPFeedback(target)->m_time = gameTime(); + redecide = true; + reset = true; + break; + } + redecide = true; + if (inRange) + redecide = burstFinished(data, state, targetPhysical, previousWeaponInfo, player); + reset = redecide; + } + break; + } + + case Data::FireDecision4: + { + if (!indirectWeapon) + { + redecide = false; + reset = true; + break; + } + const int phase = data.m_phase; + if (phase == 0) + redecide = false; + else if (phase == 1 && self->getMobile()) + redecide = firingPositionDistance < state->m_arrivalRadius; + else if (phase == 3) + { + redecide = true; + if (previousWeaponInfo) + { + if (detectAimingFailure(static_cast(bot))) + urgencyGenerator->getBBPFeedback(target)->m_time = gameTime(); + else + redecide = burstFinished(data, state, targetPhysical, previousWeaponInfo, player); + } + reset = redecide; + } + break; + } + + case Data::FireDecision5: + if (data.m_phase == 0 && !self->getMobile()) + redecide = false; + else if (data.m_phase == 1) + { + redecide = firingPositionDistance < state->m_arrivalRadius; + if (redecide) + data.m_history.push_front(data.m_decision); + reset = redecide; + } + break; + + default: + Debug(DebugTypeError, "AI/AIDLL/AI/AIBotBehaviourPattern/BBPFireInfantery.cpp", 0x417, "") + << "I don't belive we should be here!"; + break; + } + if (reset) + { + data.m_decision = Data::FireDecisionNone; + data.m_phase = 0; + } + + // 2. Draw the next decision. This always runs; it replaces the current decision only when a + // candidate wins its draw or none is set. + while (static_cast(data.m_history.size()) > 8.0f) + data.m_history.erase(--data.m_history.end()); + int counts[8]; + for (int i = 0; i < 8; ++i) + counts[i] = 0; + for (std::list::iterator it = data.m_history.begin(); it != data.m_history.end(); ++it) + ++counts[*it]; + + const int candidates[7] = { 1, 2, 3, 4, 7, 6, 5 }; + const float weight = self->getMobile() ? 1.0f : 0.0f; + const float weights[7] = { 1.0f, 1.0f, 1.0f, weight, weight, weight, weight }; // stored, never read + (void)weights; + + const bool locked = gameTime() - data.m_lockStartTime < data.m_lockDuration; + const int decision = data.m_decision; + const bool moving = (decision == 5 || decision == 7 || decision == 6) && self->getMobile(); + const int indirectCount = counts[2] + counts[3] + counts[4]; + bool lastWasIndirect = false; + if (indirectCount > 0 + && (data.m_history.front() == 2 || data.m_history.front() == 3 || data.m_history.front() == 4)) + lastWasIndirect = true; + const bool fewIndirect = indirectCount < 2 && !lastWasIndirect; + + bool chosen = false; + int choice = 0; + for (int i = 0; i < 7 && !chosen; ++i) + { + const int candidate = candidates[i]; + if (candidate == 0) + break; + if (candidate == 2) + { + if (!indirectWeapon || locked || (!moving && decision != 0) || (!fewIndirect && directWeapon)) + continue; + bool clear = false; + if (targetIsLodBot) + clear = true; + else if (objectEnvironment()->hasIndirectLineOfFire(indirectWeapon->getWeapon(), + indirectWeapon->getPosition(), aimPoint, excluded)) + clear = true; + const float chance = clear ? 0.5f : 0.05f; + if (!choice) + choice = candidate; + if (randomFloat(1.0f, 0.0f) < chance) + { + choice = candidate; + chosen = true; + } + } + else if (candidate == 1) + { + if (!directWeapon || decision == 1) + continue; + float chance = 1.0f; + if (counts[1] > 0 && static_cast(counts[1]) * 0.1f > 1e-05f) + chance = 1.0f / (static_cast(counts[1]) * 0.1f); + if (moving) + chance /= 5.0f; + if (static_cast(decision - 2) < 3 && data.m_phase == 3) + chance = 0.0f; + if (!choice) + choice = candidate; + if (randomFloat(1.0f, 0.0f) < chance) + { + choice = candidate; + chosen = true; + } + } + else if (candidate == 4) + { + if (!indirectWeapon || locked || !(moving || decision == 0) || !(fewIndirect || !directWeapon)) + continue; + const Vec3 shortPoint = { targetPosition.x - direction.x * 5.0f, targetPosition.y - direction.y * 5.0f, + targetPosition.z - direction.z * 5.0f }; + if (!targetIsLodBot + && !objectEnvironment()->hasIndirectLineOfFire(indirectWeapon->getWeapon(), + indirectWeapon->getPosition(), shortPoint, excluded)) + continue; + if (!choice) + choice = candidate; + if (randomFloat(1.0f, 0.0f) < 0.5f) + { + choice = candidate; + chosen = true; + } + } + } + if (chosen || data.m_decision == Data::FireDecisionNone) + { + data.m_decision = static_cast(choice); + data.m_phase = 0; + redecide = true; + } + data.m_lastUpdateTime = gameTime(); + + // 3. Fill the next firing state from the current one (jump table 0x4A00DC: 0, 1, 2, 4, 5). + FiringState next = *state; + next.m_target = target; + next.m_position = selfPosition; + switch (data.m_decision) + { + case Data::FireDecisionNone: + next.m_hasFiringPosition = false; + next.m_bool25 = false; + next.m_weapon = -1; + break; + + case Data::FireDecision1: + { + int phase = data.m_phase; + bool startBurst = false; + if (phase == 0) + { + redecide = true; + if (self->getMobile()) + { + next.m_bool26 = false; + next.m_shots = 0; + next.m_bool25 = true; + next.m_bool14 = true; + next.m_backOff = false; + next.m_independentAim = independentAim; + next.m_hasFiringPosition = false; + next.m_bool24 = true; + data.m_phase = 1; + data.m_phaseTargetPosition = targetPosition; + next.m_weapon = weapon; + phase = 1; + } + else + startBurst = true; + } + if (phase == 1 || startBurst) + { + if (redecide) + { + // 0x25DAD9: start a burst of 2..4 shots, or 1..min(magazine, 10) for burst weapons. + next.m_weapon = weapon; + if (!directWeapon->getBurst()) + { + const float draw = randomFloat(1.0f, 0.0f); + next.m_shots = static_cast(3.0f * draw + 2.0f); + } + else + { + const float magazine = static_cast(directWeapon->getMaxAmmoInMag()); + float limit = 10.0f; + if (1.0f <= magazine && magazine < 10.0f) + limit = magazine; + const float range = limit - 1.0f; + const float draw = randomFloat(1.0f, 0.0f); + next.m_shots = static_cast(draw * range + 1.0f); + } + next.m_bool26 = false; + next.m_bool25 = true; + next.m_bool14 = self->getMobile() != 0; + next.m_backOff = false; + next.m_independentAim = independentAim; + next.m_hasFiringPosition = false; + data.m_phase = 3; + data.m_phaseTargetPosition = targetPosition; + data.m_shotsAtPhaseStart = player->getNumShotsFired(directWeapon->getWeapon()); + data.m_phaseStartTime = gameTime(); + redecide = false; + } + phase = 3; + } + bool backOffCheck = phase == 2; + if (phase == 3) + { + // 0x25D7F4 (the image tests isFireAllowed here and again at 0x25D60E). + next.m_int10 = bot->isFireAllowed() ? next.m_int10 : 1; + if (!redecide) + next.m_backOff = false; + else + data.m_phase = 0; + backOffCheck = true; + } + if (backOffCheck) + { + // 0x25D830: inside the weapon's minimum range - back off. + const float minRange = directWeapon->getMinRange(); + bool handled = false; + if (selfMobile) + { + const float dx = targetPosition.x - selfPosition.x; + const float dy = targetPosition.y - selfPosition.y; + const float dz = targetPosition.z - selfPosition.z; + if (dx * dx + dy * dy + dz * dz < (minRange + 1.0f) * (minRange + 1.0f)) // 0x25D89D..0x25D8C2 + { + const float minRange2 = directWeapon->getMinRange(); + bool keepPosition = false; + if (data.m_phase == 2) + { + const float fx = targetPosition.x - state->m_firingPosition.x; + const float fy = targetPosition.y - state->m_firingPosition.y; + const float fz = targetPosition.z - state->m_firingPosition.z; + // A squared distance against an unsquared bound, as in the image (0x25D9C2). + keepPosition = fx * fx + fy * fy + fz * fz > (minRange2 + minRange2 + 5.0f) * 0.75f; + } + if (keepPosition) + { + data.m_firePosition = state->m_position; + next.m_position = state->m_position; + } + else + { + next.m_position.x = 1.0f; + next.m_position.y = 0.0f; + next.m_position.z = 1.0f; + data.m_firePosition = next.m_position; + next.m_backOff = true; + data.m_phase = 2; + } + redecide = false; + handled = true; + } + } + if (!handled && data.m_phase == 2) + { + data.m_phase = 0; + next.m_backOff = false; + redecide = true; + } + } + break; + } + + case Data::FireDecision2: + case Data::FireDecision4: + { + const bool fromPosition = data.m_decision == Data::FireDecision4; + int phase = data.m_phase; + bool start = false; + if (phase == 0) + { + redecide = true; + if (self->getMobile()) + { + next.m_bool26 = false; + next.m_shots = 0; + next.m_bool25 = false; + next.m_weapon = weapon; + if (fromPosition) + { + next.m_bool14 = false; + next.m_independentAim = false; + const bool found = getIndirectWeaponCloseToFiringPositions( + next.m_position, next.m_firingPosition, self, selfMobile, equipmentType, indirectWeapon, + targetInfo, targetPosition); + next.m_hasFiringPosition = found; + next.m_bool24 = false; + redecide = !found; + } + else + { + next.m_independentAim = independentAim; + next.m_bool24 = true; + } + data.m_phase = 1; + data.m_phaseTargetPosition = targetPosition; + phase = 1; + } + else + start = true; + } + if ((phase == 1 && redecide) || start) + { + // 0x25DDF6 / 0x25E063: start firing, then lock indirect fire for 5..10 s. + next.m_bool26 = fromPosition; + next.m_bool25 = false; + next.m_shots = 1; + if (fromPosition) + { + next.m_bool14 = false; + next.m_independentAim = false; + } + else + { + next.m_bool14 = self->getMobile() != 0; + next.m_independentAim = independentAim; + next.m_hasFiringPosition = false; + } + data.m_phase = 3; + data.m_phaseTargetPosition = targetPosition; + next.m_weapon = weapon; + data.m_shotsAtPhaseStart = player->getNumShotsFired(indirectWeapon->getWeapon()); + data.m_lockStartTime = gameTime(); + data.m_lockDuration = static_cast(randomFloat(5.0f, 5.0f)); + data.m_phaseStartTime = gameTime(); + redecide = false; + } + else if (phase == 3 && redecide) + data.m_phase = 0; + break; + } + + case Data::FireDecision5: + if (data.m_phase == 0) + { + redecide = true; + if (self->getMobile()) + { + Vec2 unused = { 0.0f, 0.0f }; // computed and never read in the image (0x25E1F0) + vec3ToVec2XZ(targetInfo->getPosition(), unused); + next.m_bool26 = false; + next.m_shots = 0; + next.m_independentAim = independentAim; + next.m_bool14 = true; + next.m_hasFiringPosition = false; + next.m_bool25 = true; + next.m_bool24 = false; + data.m_phase = 1; + data.m_phaseTargetPosition = targetPosition; + redecide = false; + next.m_weapon = weapon; + } + else + data.m_phase = 0; + } + else if (data.m_phase == 1 && redecide) + data.m_phase = 0; + break; + + default: + break; + } + + // 0x25D606 + next.m_int10 = bot->isFireAllowed() ? next.m_int10 : 1; + if (!redecide) + { + bot->getSquadMember()->clearRequestAction(); + next.m_arrivalRadius = selfPhysical->getRadius() + 2.0f; + m_firingStates[id] = next; + return createPlanInternal(bot, targetIsLodBot); + } + dropPlan(bot); + return 0; +} + +namespace { + +// The image's inlined plan-variable construction: `checkPointer(new BAPVariable(context, value))` +// followed by `std::list::insert(context->begin(), &variable)`. +template +BAPVariable* newVariable(BAPContext* context, const T& value) +{ + BAPVariable* const variable = checkPointer(new BAPVariable(context, value)); + context->addVariable(variable); + return variable; +} + +// Component-wise comparison with Vec3::getZero() at FLT_EPSILON, as inlined (0x276E3A, 0x267A0B). +bool isZero(const Vec3& v) +{ + const Vec3& zero = Vec3::getZero(); + return std::fabs(v.x - zero.x) <= 1.1920929e-07f && std::fabs(v.y - zero.y) <= 1.1920929e-07f + && std::fabs(v.z - zero.z) <= 1.1920929e-07f; +} + +// The inlined normalisation (0x2653F0..): a unit vector is kept, a near-zero one becomes zero. +void normalize(Vec3& v) +{ + const float lengthSq = v.x * v.x + v.y * v.y + v.z * v.z; + if (std::fabs(lengthSq - 1.0f) < 1.1920929e-07f) + return; + if (std::fabs(lengthSq) < 1.1920929e-07f) + { + v.x = v.y = v.z = 0.0f; + return; + } + const float inv = 1.0f / std::sqrt(lengthSq); + v.x *= inv; + v.y *= inv; + v.z *= inv; +} + +// `1 << input` sign-extended to the 64-bit control mask (`movl %eax,%edx; sarl $0x1f,%edx`). +unsigned long long inputMask(int input) +{ + return static_cast(static_cast(static_cast(1u << input))); +} + +// Every branch starts its parallel block with the sensing-agent override; bots whose own +// object has type flag 0x200000 only override while not sprinting. +BAPStatement* newOverrideSensingAgent(bool selfFlag200000, int patternId) +{ + if (selfFlag200000) + return checkPointer(new BAPFlowCIf(checkPointer(new BAPConNot(checkPointer(new BAPConIsSprinting()))), + checkPointer(new BAPAOverrideSensingAgent()), 0, patternId, true, false)); + return checkPointer(new BAPAOverrideSensingAgent()); +} + +// "Fire while the target lives": And{ Not(ObjectHealth(target, 0)) }. +BAPCondition* newTargetAlive(unsigned int target) +{ + BAPConAnd* const alive = checkPointer(new BAPConAnd()); + alive->addCondition(checkPointer(new BAPConNot(checkPointer(new BAPConObjectHealth(target, 0.0f))))); + return alive; +} + +float atLeast(float value, float minimum) +{ + return value <= minimum ? minimum : value; +} + +} // namespace + +// ELF 0x2650F0 (18,046 instructions). Builds the fire plan for the FiringState createPlan filled: +// a serial root { change weapon, parallel(reset controls, sensing override, the branch's block) } +// wrapped in a BAPIWFire. Branches (FiringState flags): +// m_bool14 && m_independentAim move and fire (infantry; 0x265B1A) recovered +// m_bool14 && !independent && weapon type 4 place and detonate (0x26B5xx) recovered +// m_bool14 && !independent, other weapons move then fire (0x271F4A) recovered +// !m_bool14 && m_hasFiringPosition go to the firing position, fire recovered +// otherwise / no mobile fire from here (0x2709A0) recovered +BotScript* BBPFireInfantery::createPlanInternal(Bot* bot, bool targetIsLodBot) +{ + const unsigned int id = bot->getBotId(); + FiringState* const state = &m_firingStates[id]; + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + BAPContext* const context = bot->getScriptContext(); + context->clear(); + static_cast(bot)->setHadPrecisionTimeStamp(gameTime()); + dropPlan(bot); + + const unsigned int self = bot->getCurrentEquipment(); + Information* const selfInfo = informationManager->getInformation(self); + IPIArmament* const armament = selfInfo->getArmament(); + IPIPhysical* const selfPhysical = selfInfo->getPhysical(); + IPIControlInfo* const controlInfo = selfInfo->getControlInfo(); + if (!armament || !selfPhysical || !controlInfo) + return 0; + IPIMobile* const selfMobile = selfInfo->getMobile(); + if (selfMobile) + selfMobile->isTurnable(); // result unused in the image (0x265258) + controlInfo->getDriveControls(); // results unused in the image (0x265266 / 0x265272) + controlInfo->getAimControls(); + const Vec3& selfPosition = selfInfo->getPosition(); + + const unsigned int target = state->m_target; + Information* const targetInfo = informationManager->getInformation(target); + if (!targetInfo) + return 0; + IPIPhysical* const targetPhysical = targetInfo->getPhysical(); + if (!targetPhysical) + return 0; + + WeaponInfo* weaponInfo = 0; + if (m_weapons[bot->getBotId()] != -1) + { + weaponInfo = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(m_weapons[bot->getBotId()])); + armament->setActiveWeapon(m_weapons[bot->getBotId()], bot->getSide()); + } + + // The target, or its primary object, can move. + bool targetMobile = targetInfo->getMobile() != 0; + if (!targetMobile && !targetInfo->isPrimary()) + targetMobile = informationManager->getInformation(targetInfo->getPrimaryObject(bot->getSide()))->getMobile() != 0; + + // A reachable spot 30 m from the target on the bot's side (0x265300..0x2653D1). + bool pathFound = true; + Vec3 movePosition = { 0.0f, 0.0f, 0.0f }; + if (selfMobile && !targetMobile) + { + const Vec3& from = targetInfo->getPosition(); + const Vec3& own = selfInfo->getPosition(); + Vec3 direction = { own.x - from.x, own.y - from.y, own.z - from.z }; + normalize(direction); + const Vec3 point = { direction.x * 30.0f + from.x, direction.y * 30.0f + from.y, direction.z * 30.0f + from.z }; + const int equipmentType = selfInfo->getUnit()->getEquipmentType(); + unsigned int polygon; + unsigned int cluster; + pathFound = IAIPathfinding::instance->findClosestValidPolygon(polygon, cluster, movePosition, + selfMobile->getVehicleNumber(), from, point, + 10, equipmentType); + } + + const int guidance = weaponInfo->getWeaponGuidanceType(); + if (guidance != 0 && selfInfo->isOfType(ITSoldier)) + return createGuidedPlanInternalInfantry(bot, targetIsLodBot, movePosition); // 0x2779B1 + + // The plan variables (0x26543B..0x265819), shared by the wrappers and the fire plans. + BAPVariable* const weaponVariable = newVariable(context, weaponInfo); + BAPVariable* const targetVariable = newVariable(context, target); + BAPVariable* const aimValidVariable = newVariable(context, false); + const Vec3 up = { 0.0f, 1.0f, 0.0f }; + const Vec3 zero = { 0.0f, 0.0f, 0.0f }; + BAPVariable* const aimVariable = newVariable(context, up); + BAPVariable* const aimOffsetVariable = newVariable(context, zero); + BAPVariable* const lookVariable = newVariable(context, zero); + + BAPCombinerSerial* const root = checkPointer(new BAPCombinerSerial(m_patternId, 0)); + if (m_weapons[bot->getBotId()] != -1 && weaponInfo->getWeaponActivate() != 0x40) + root->addStatement(checkPointer(new BAPAChangeWeapon(bot, m_weapons[bot->getBotId()], m_patternId))); + BAPCombinerParallel* const block = checkPointer(new BAPCombinerParallel(m_patternId, true, -1, false)); + root->addStatement(block); + block->addStatement(checkPointer(new BAPAResetControls(true, true, true, m_patternId))); + + const bool placedExplosive = weaponInfo->getWeaponType() == 4; + const int antiAircraft = armament->isAntiAircraft(); + const bool targetFlag10 = targetInfo->isOfType(ITAir); + const bool noMove = targetFlag10 && antiAircraft == 1; // -0x246 + bool fireFromHere = (targetFlag10 && antiAircraft == 2) || !pathFound; // -0x247 + if (weaponInfo->getMaxRange() < 10.0f) + fireFromHere = false; + + // The squad's strategic-area position, when the squad has a mission (0x277055). + SquadMember* const squadMember = bot->getSquadMember(); + bool squadPositionValid = false; + Vec3 squadPosition = { 0.0f, 0.0f, 0.0f }; + if (squadMember && squadMember->getSquad() && squadMember->getSquad()->squadHasMission() + && squadMember->getSquad()->getValidSaPos(squadMember, squadPosition)) + squadPositionValid = true; + + const bool selfFlag = selfInfo->isOfType(ITSoldier); // -0x249 + const bool targetFlag = targetInfo->isOfType(ITSoldier); // -0x24A + const bool targetIsBot = IBotManager::instance->getBotFromPlayerId(targetInfo->getPlayerId()) != 0; + + BAPStatement* branch = 0; // added to the parallel block at 0x2671C0 + bool stationary = false; // 0x2709A0 + if (!fireFromHere && m_targetChanged[id]) + { + if (!selfMobile) + stationary = true; + else if (squadPositionValid && !isZero(squadPosition)) + { + // 0x276E2B: fire from here when the squad position lies behind the bot, away from a + // target beyond 30 m (50 m unless either side has type flag 0x200000). + const Vec3 toSquad = { squadPosition.x - selfPosition.x, squadPosition.y - selfPosition.y, + squadPosition.z - selfPosition.z }; + const Vec3& targetPosition = targetInfo->getPosition(); + const Vec3 toTarget = { targetPosition.x - selfPosition.x, targetPosition.y - selfPosition.y, + targetPosition.z - selfPosition.z }; + const float range = (selfFlag || targetFlag) ? 30.0f : 50.0f; + if (range * range < toTarget.z * toTarget.z + toTarget.y * toTarget.y + toTarget.x * toTarget.x + && toTarget.z * toSquad.z + toTarget.x * toSquad.x + toTarget.y * toSquad.y < 0.0f) + fireFromHere = true; + } + } + + // 0x265AF0 + if (!stationary && !selfMobile) + stationary = true; + if (!stationary && state->m_bool14 && state->m_independentAim) + { + // ---- Move and fire (0x265B1A..0x2671BB) ---- + if (!fireFromHere) + { + if (IPIMobile* const targetMover = targetInfo->getMobile()) + { + const IPIMobile::ValidPos& valid = targetMover->getLastValidPosition(selfMobile->getVehicleNumber()); + if (valid.island == static_cast(-1) || valid.polygon == static_cast(-1)) + fireFromHere = true; + } + if (!fireFromHere && targetIsBot && targetFlag) + fireFromHere = true; + } + const bool splash = weaponInfo->getExplosionRadius() != 0.0f && guidance == 0; + const bool staticAttack = static_cast(bot)->getUseStaticAttack() && splash && targetFlag; + block->addStatement(newOverrideSensingAgent(selfFlag, m_patternId)); + + BAPConSharedCondition* const lineOfFire = + staticAttack ? checkPointer(new BAPConSharedCondition(checkPointer(new BAPConTrue()))) + : checkPointer(new BAPConSharedCondition(checkPointer(new BAPConObjectLineOfFire(target, targetIsLodBot)))); + + // A control point close to the bot: fire at any range while it is not ours (0x265D8A). + BAPConSharedCondition* controlPointCondition = 0; + AIStrategicObject* const object = + AIStrategicObjectManager::getInstance()->getClosestObject(selfPosition, bot->getSide(), false); + Vec3 controlPoint = { 0.0f, 0.0f, 0.0f }; + if (object && !noMove && !fireFromHere + && static_cast(object)->m_controlPointId != static_cast(-1)) + { + const int equipmentType = selfInfo->getUnit()->getEquipmentType(); + const int vehicleNumber = selfMobile->getVehicleNumber(); + static_cast(object)->getControlpointPos(object, bot->getSide(), vehicleNumber, + equipmentType, selfPosition, controlPoint); + const float radius = object->m_size[bot->getSide()]; + Vec3 objectPosition = { 0.0f, 0.0f, 0.0f }; + vec2ToVec3XZ(object->getPosition(bot->getSide()), objectPosition); + objectPosition.y = controlPoint.y; + const Vec3 offset = { objectPosition.x - controlPoint.x, objectPosition.y - controlPoint.y, + objectPosition.z - controlPoint.z }; + if (offset.x * offset.x + offset.y * offset.y + offset.z * offset.z < radius * radius) + { + // 0x26A7A5 also computes controlPoint - selfPosition into a slot it never reads. + BAPConAnd* const near = checkPointer(new BAPConAnd()); + near->addCondition(checkPointer(new BAPConStrategicObjectStatus(object, bot->getSide(), false))); + near->addCondition(checkPointer(new BAPConPointDistance(controlPoint, 40.0f, true))); + controlPointCondition = checkPointer(new BAPConSharedCondition(near)); + } + } + + BAPConAnd* const fireCondition = checkPointer(new BAPConAnd()); + fireCondition->addCondition(lineOfFire->getNewSharedCondition()); + if (!controlPointCondition) + fireCondition->addCondition(checkPointer(new BAPConObjectDistance( + target, weaponInfo->getMinRange(), weaponInfo->getMaxRange(), true, false))); + else + { + BAPConOr* const inRange = checkPointer(new BAPConOr()); + inRange->addCondition(checkPointer(new BAPConObjectDistance( + target, weaponInfo->getMinRange(), weaponInfo->getMaxRange(), true, false))); + inRange->addCondition(controlPointCondition->getNewSharedCondition()); + fireCondition->addCondition(inRange); + } + BAPConSharedCondition* const validAiming = checkPointer(new BAPConSharedCondition(checkPointer( + new BAPConObjectValidAiming(target, self, aimValidVariable, aimVariable, staticAttack)))); + + BAPStatement* fireOrAim; + if (guidance == 0) + { + BAPStatement* const firePlan = createFirePlan(bot, state, weaponVariable, targetVariable, aimValidVariable, + aimVariable, aimOffsetVariable, lookVariable, weaponInfo, + selfInfo, controlInfo, targetInfo, targetPhysical, WGSNone); + const Vec3 noOffset = { 0.0f, 0.0f, 0.0f }; + BAPAAimAtObject* const aim = checkPointer(new BAPAAimAtObject( + bot, target, noOffset, checkPointer(new BAPConFalse()), controlInfo->getAimControls(), m_patternId, + false, aimValidVariable, aimVariable)); + fireOrAim = checkPointer(new BAPFlowCIf(fireCondition, firePlan, aim, m_patternId, true, false)); + } + else + { + BAPStatement* const firePlan = createFirePlanGuided(bot, state, weaponVariable, targetVariable, lookVariable, + weaponInfo, selfInfo, controlInfo, targetInfo, + targetPhysical, static_cast(guidance)); + BAPALookAtObject* const look = checkPointer(new BAPALookAtObject( + bot, target, 0.0f, checkPointer(new BAPConFalse()), controlInfo->getLookControls(), m_patternId, + lookVariable, 0.0f)); + fireOrAim = checkPointer(new BAPFlowCIf(fireCondition, firePlan, look, m_patternId, true, false)); + } + + BAPCombinerParallel* const engage = checkPointer(new BAPCombinerParallel(m_patternId, 4, false)); + engage->addStatement(checkPointer(new BAPAEvaluateCondition(lineOfFire, m_patternId))); + engage->addStatement(checkPointer(new BAPAEvaluateCondition(validAiming, m_patternId))); + if (guidance == 0) + engage->addStatement(checkPointer(new BAPWrapperAiming(aimVariable, aimValidVariable, aimOffsetVariable, + self, target, true))); + else + engage->addStatement(checkPointer(new BAPWrapperLookAt(target, lookVariable, true, guidance == 3, + aimVariable, aimValidVariable))); + + // Movement while engaging (0x2664xx..0x266Fxx). + BAPStatement* movement = 0; + if (selfMobile && !noMove && !fireFromHere) + { + // No line of fire: walk to within 1.1 x minimum range (>= 15 m), forget the target, end. + BAPStatement* away; + if (targetMobile) + away = checkPointer(new BAPAMoveToObjectFinding( + bot, state->m_target, 0.0f, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.5f, 0, + controlInfo->getDriveControls(), m_patternId, 0, atLeast(weaponInfo->getMinRange() * 1.1f, 15.0f), 3)); + else + away = checkPointer(new BAPAMoveToFinding( + bot, movePosition, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.75f, 0, + controlInfo->getDriveControls(), m_patternId, 0.0f, atLeast(weaponInfo->getMinRange() * 1.1f, 15.0f))); + BAPCombinerSerial* const lost = checkPointer(new BAPCombinerSerial(m_patternId, 300)); + lost->addStatement(away); + lost->addStatement(checkPointer(new BAPAForgetTarget(state->m_target))); + lost->addStatement(checkPointer(new BAPFlowCEnd(m_patternId, static_cast(0), 0))); + + // Aim valid: close in while beyond half the maximum range or inside 1.05 x minimum (>= 18 m). + BAPConOr* const approachCondition = checkPointer(new BAPConOr()); + approachCondition->addCondition(checkPointer(new BAPConObjectDistance(target, weaponInfo->getMaxRange() * 0.5f, true, false, true))); + approachCondition->addCondition(checkPointer(new BAPConObjectDistance(target, atLeast(weaponInfo->getMinRange() * 1.05f, 18.0f), true, false, false))); + BAPStatement* approachMove; + if (targetMobile) + approachMove = checkPointer(new BAPAMoveToObjectFinding( + bot, state->m_target, weaponInfo->getMaxRange() * 0.35f, selfMobile->getMaxSpeed(), + selfMobile->getMaxSpeed() * 0.5f, 0, controlInfo->getDriveControls(), m_patternId, 0, + atLeast(weaponInfo->getMinRange() * 1.1f, 15.0f), 4)); + else + approachMove = checkPointer(new BAPAMoveToFinding( + bot, movePosition, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.75f, 0, + controlInfo->getDriveControls(), m_patternId, weaponInfo->getMaxRange() * 0.35f, + atLeast(weaponInfo->getMinRange() * 1.05f, 15.0f))); + BAPFlowCIf* const approach = checkPointer(new BAPFlowCIf(approachCondition, approachMove, 0, m_patternId, false, false)); + + // Aim not valid: reposition, near (beyond max(minimum, 15) + 5 m) or far. + BAPConObjectDistance* const beyond = checkPointer(new BAPConObjectDistance( + target, atLeast(weaponInfo->getMinRange(), 15.0f) + 5.0f, true, false, true)); + BAPStatement* nearMove; + BAPStatement* farMove; + if (targetMobile) + { + nearMove = checkPointer(new BAPAMoveToObjectFinding( + bot, state->m_target, atLeast(weaponInfo->getMinRange() * 1.1f, 10.0f), selfMobile->getMaxSpeed(), + selfMobile->getMaxSpeed() * 0.5f, 0, controlInfo->getDriveControls(), m_patternId, 0, 0.0f, 5)); + BAPConAnd* const moved = checkPointer(new BAPConAnd()); + moved->addCondition(checkPointer(new BAPConObjectDistance(m_targets[bot->getBotId()], 50.0f, true, true, false))); + moved->addCondition(checkPointer(new BAPConObjectMoved(m_targets[bot->getBotId()], 5.0f))); + farMove = checkPointer(new BAPAMoveToObjectFinding( + bot, state->m_target, weaponInfo->getMaxRange() * 0.7f, selfMobile->getMaxSpeed(), + selfMobile->getMaxSpeed() * 0.5f, 0, controlInfo->getDriveControls(), m_patternId, moved, + atLeast(weaponInfo->getMinRange() * 2.2f, 30.0f), 6)); + } + else + { + nearMove = checkPointer(new BAPAMoveToFinding( + bot, movePosition, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.75f, 0, + controlInfo->getDriveControls(), m_patternId, atLeast(weaponInfo->getMinRange() * 1.1f, 10.0f), 0.0f)); + farMove = checkPointer(new BAPAMoveToFinding( + bot, movePosition, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.75f, 0, + controlInfo->getDriveControls(), m_patternId, weaponInfo->getMaxRange() * 0.7f, + atLeast(weaponInfo->getMinRange() * 2.2f, 30.0f))); + } + BAPFlowCIf* const reposition = checkPointer(new BAPFlowCIf(beyond, nearMove, farMove, m_patternId, false, false)); + BAPFlowCIf* const aimed = checkPointer(new BAPFlowCIf( + checkPointer(new BAPConNot(validAiming->getNewSharedCondition())), reposition, approach, m_patternId, + false, false)); + movement = checkPointer(new BAPFlowCIf(checkPointer(new BAPConNot(lineOfFire->getNewSharedCondition())), + lost, aimed, m_patternId, true, false)); + } + if (!controlPointCondition) + { + if (movement) + engage->addStatement(movement); + else if (fireFromHere && squadPositionValid && !isZero(squadPosition)) + { + static_cast(bot)->setIsGoingForFlag(true); // 0x267A42 + engage->addStatement(checkPointer(new BAPAMoveToFinding( + bot, squadPosition, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.75f, 0, + controlInfo->getDriveControls(), m_patternId, 0.0f, 0.0f))); + } + } + else + { + BAPAMoveToFinding* const toControlPoint = checkPointer(new BAPAMoveToFinding( + bot, controlPoint, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.75f, 0, + controlInfo->getDriveControls(), m_patternId, 0.0f, 0.0f)); + engage->addStatement(checkPointer(new BAPFlowCIf(controlPointCondition, toControlPoint, movement, + m_patternId, false, false))); + } + engage->addStatement(fireOrAim); + + branch = checkPointer(new BAPFlowCWhile(newTargetAlive(target), engage, false, m_patternId)); + if (!selfFlag) + block->addStatement(checkPointer(new BAPAUseFlareOnMissileLock(bot, 0x800000000000ULL, m_patternId))); + } + else if (!stationary && state->m_bool14 && placedExplosive) + { + // ---- Place and detonate (weapon type 4; 0x26B5xx..) ---- + block->addStatement(checkPointer(new BAPFlowCIf( + checkPointer(new BAPConNot(checkPointer(new BAPConIsSprinting()))), + checkPointer(new BAPAOverrideSensingAgent()), 0, m_patternId, true, false))); + BAPCombinerParallel* const engage = checkPointer(new BAPCombinerParallel(m_patternId, 4, false)); + branch = checkPointer(new BAPFlowCWhile(newTargetAlive(target), engage, false, m_patternId)); + const Vec3 noOffset = { 0.0f, 0.0f, 0.0f }; + engage->addStatement(checkPointer(new BAPAAimAtObject(bot, target, noOffset, checkPointer(new BAPConFalse()), + controlInfo->getAimControls(), m_patternId, false, 0, 0))); + BAPCombinerSerial* const steps = checkPointer(new BAPCombinerSerial(m_patternId, 1)); + const float contact = targetPhysical->getSmallestRadius() + selfPhysical->getSmallestRadius(); + + // 1. Walk up to the target. + BAPStatement* walkUp; + if (targetMobile) + { + steps->addStatement(checkPointer(new BAPAMoveToObjectFinding( + bot, state->m_target, contact, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.5f, 0, + controlInfo->getDriveControls(), m_patternId, 0, 0.0f, 1))); + BAPAMoveToObjectFinding* const follow = checkPointer(new BAPAMoveToObjectFinding( + bot, state->m_target, 0.0f, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.5f, 0, + controlInfo->getDriveControls(), m_patternId, 0, 0.0f, 3)); + walkUp = checkPointer(new BAPFlowCWhile( + checkPointer(new BAPConNot(checkPointer(new BAPConTime(0.20000000298023224, false, false, false)))), + follow, false, m_patternId)); + } + else + walkUp = checkPointer(new BAPAMoveToFinding( + bot, movePosition, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.75f, 0, + controlInfo->getDriveControls(), m_patternId, 0.0f, 0.0f)); + steps->addStatement(walkUp); + + // 2. Place: alternate fire while the detonator is active, then fire, then lock turning. + const int altFire = weaponInfo->getWeaponAltFire(); + steps->addStatement(checkPointer(new BAPFlowCWhile( + checkPointer(new BAPConWeaponDetonatorIsActive(weaponVariable)), + checkPointer(new BAPATrigger(static_cast(altFire), checkPointer(new BAPConTrue()), + checkPointer(new BAPConFalse()), inputMask(altFire), m_patternId, 0.0, true)), + false, m_patternId))); + const int fire = weaponInfo->getWeaponFire(); + steps->addStatement(checkPointer(new BAPATrigger(static_cast(fire), checkPointer(new BAPConTrue()), + checkPointer(new BAPConFalse()), inputMask(fire), m_patternId, 0.0, true))); + steps->addStatement(checkPointer(new BAPICTurnLock(true))); + + // 3. Keep close until the weapon is ready again, then back off 30 m. + BAPStatement* stay; + if (targetMobile) + stay = checkPointer(new BAPAMoveToObjectFinding( + bot, state->m_target, 0.0f, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.5f, 0, + controlInfo->getDriveControls(), m_patternId, 0, 0.0f, 2)); + else + stay = checkPointer(new BAPAMoveToFinding( + bot, movePosition, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.75f, 0, + controlInfo->getDriveControls(), m_patternId, 0.0f, 0.0f)); + steps->addStatement(checkPointer(new BAPFlowCWhile( + checkPointer(new BAPConNot(checkPointer(new BAPConWeaponReadyToFire(weaponVariable)))), stay, false, m_patternId))); + BAPStatement* backOff; + if (targetMobile) + backOff = checkPointer(new BAPAMoveToObjectFinding( + bot, state->m_target, 30.0f, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.5f, 0, + controlInfo->getDriveControls(), m_patternId, 0, contact + 9.0f, 2)); + else + backOff = checkPointer(new BAPAMoveToFinding( + bot, movePosition, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.75f, 0, + controlInfo->getDriveControls(), m_patternId, 30.0f, contact + 9.0f)); + steps->addStatement(backOff); + + // 4. Crouch (pose 2) and detonate: alternate fire until the detonator is active, wait 0.7 s, fire. + BAPCombinerParallel* const detonate = checkPointer(new BAPCombinerParallel(m_patternId, -1, false)); + detonate->addStatement(checkPointer(new BAPASoldierPose(SPCrouching, checkPointer(new BAPConTrue()), m_patternId, true))); + BAPFlowCWhile* const arm = checkPointer(new BAPFlowCWhile( + checkPointer(new BAPConNot(checkPointer(new BAPConWeaponDetonatorIsActive(weaponVariable)))), + checkPointer(new BAPATrigger(static_cast(altFire), checkPointer(new BAPConTrue()), + checkPointer(new BAPConFalse()), inputMask(altFire), m_patternId, 0.0, false)), + false, m_patternId)); + BAPCombinerSerial* const sequence = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + sequence->addStatement(arm); + sequence->addStatement(checkPointer(new BAPAIdle( + checkPointer(new BAPConTime(0.699999988079071, false, false, false)), 0, m_patternId))); + sequence->addStatement(checkPointer(new BAPATrigger( + static_cast(fire), checkPointer(new BAPConWeaponDetonatorIsActive(weaponVariable)), + checkPointer(new BAPConFalse()), inputMask(fire), m_patternId, 0.0, false))); + detonate->addStatement(sequence); + steps->addStatement(detonate); + steps->addStatement(checkPointer(new BAPICTurnLock(false))); + engage->addStatement(steps); + engage->addStatement(checkPointer(new BAPAMergeSoldierInputs(m_patternId))); + } + else if (!stationary && state->m_bool14) + { + // ---- Move then fire, drive and aim controls overlapping (0x271F4A..0x272B1F, with the + // out-of-line blocks 0x273020.., 0x273C3A..0x27422C, 0x2754D0, 0x2759CA, 0x275C5A, 0x275DC0, + // 0x2762A1, 0x2763B1, 0x276504, 0x276D76..0x276E26) ---- + const bool splash = weaponInfo->getExplosionRadius() != 0.0f && guidance == 0; // -0x5D5 + SensedObject* const sensed = bot->getSensedObjectFromHandle(target); + bool targetAbove = false; // -0x5D6 + if (bot->getSpawnKit() != 1 && !weaponInfo->getIsThrown()) + { + if (30.0f < targetInfo->getPosition().y - selfInfo->getPosition().y) + targetAbove = true; + } + bool grenadeChecks = false; // -0x5D7 (no splash-at-target term, unlike createFirePlan) + if (static_cast(bot)->getUseStaticAttack() && splash && targetFlag + && ((sensed->m_flags & 8) || targetAbove)) + grenadeChecks = true; + + // Ranges: a target more than 5 m above adds 1.25 x the height to the maximum (not for + // thrown weapons, only beyond 10 m); thrown weapons in static attack keep 5 m minimum. + const float dy = targetInfo->getPosition().y - selfInfo->getPosition().y; // -0x5DC + float heightBonus = 0.0f; // -0x5E0 + if (dy > 5.0f && weaponInfo->getMaxRange() > 10.0f && !weaponInfo->getIsThrown()) + heightBonus = dy * 1.25f; + const float maxRange = weaponInfo->getMaxRange() + heightBonus; // -0x5E4 + float minRange = weaponInfo->getMinRange(); // -0x5E8 + if (dy > 3.0f && grenadeChecks && weaponInfo->getIsThrown()) + minRange = 5.0f; // 0x276D8C cmovne + block->addStatement(newOverrideSensingAgent(selfFlag, m_patternId)); + + // The fire condition: the shared "can hit" And (valid aiming when the bot will fire, + // line of fire unless grenade checks), then the range (or a control point nearby). + BAPConAnd* const fireCondition = checkPointer(new BAPConAnd()); // -0x604 + BAPConAnd* const canHit = checkPointer(new BAPConAnd()); + if (m_weapons[bot->getBotId()] != -1 && state->m_shots != 0 && guidance == 0) + canHit->addCondition(checkPointer(new BAPConObjectValidAiming(target, self, aimValidVariable, aimVariable, + grenadeChecks))); // 0x276504 + if (!grenadeChecks) + canHit->addCondition(checkPointer(new BAPConObjectLineOfFire(target, targetIsLodBot))); // 0x2763B1 + BAPConSharedCondition* const canHitShared = checkPointer(new BAPConSharedCondition(canHit)); // -0x61C + fireCondition->addCondition(canHitShared->getNewSharedCondition()); + + BAPConSharedCondition* controlPointCondition = 0; // -0x620 + AIStrategicObject* const object = + AIStrategicObjectManager::getInstance()->getClosestObject(selfPosition, bot->getSide(), false); + Vec3 controlPoint = { 0.0f, 0.0f, 0.0f }; + if ((!selfFlag || weaponInfo->getMaxRange() > 5.0f) && object && !fireFromHere + && static_cast(object)->m_controlPointId != static_cast(-1)) + { + const int equipmentType = selfInfo->getUnit()->getEquipmentType(); + const int vehicleNumber = selfMobile->getVehicleNumber(); + static_cast(object)->getControlpointPos(object, bot->getSide(), vehicleNumber, + equipmentType, selfPosition, controlPoint); + const float radius = object->m_size[bot->getSide()]; + Vec3 objectPosition = { 0.0f, 0.0f, 0.0f }; + vec2ToVec3XZ(object->getPosition(bot->getSide()), objectPosition); + objectPosition.y = controlPoint.y; + const Vec3 offset = { objectPosition.x - controlPoint.x, objectPosition.y - controlPoint.y, + objectPosition.z - controlPoint.z }; + if (offset.x * offset.x + offset.y * offset.y + offset.z * offset.z < radius * radius) + { + // 0x275DC0 also computes controlPoint - selfPosition into a slot it never reads. + BAPConAnd* const near = checkPointer(new BAPConAnd()); + near->addCondition(checkPointer(new BAPConStrategicObjectStatus(object, bot->getSide(), false))); + near->addCondition(checkPointer(new BAPConPointDistance(controlPoint, 40.0f, true))); + controlPointCondition = checkPointer(new BAPConSharedCondition(near)); + } + } + if (!grenadeChecks) + { + if (!controlPointCondition) + fireCondition->addCondition(checkPointer(new BAPConObjectDistance( + target, minRange * 0.9f, maxRange * 1.1f, true, false))); // 0x275C5A + else + { + BAPConOr* const inRange = checkPointer(new BAPConOr()); + inRange->addCondition(checkPointer(new BAPConObjectDistance( + target, minRange * 0.9f, maxRange * 1.1f, true, false))); + inRange->addCondition(controlPointCondition->getNewSharedCondition()); + fireCondition->addCondition(inRange); + } + } + + // Fire (createFirePlan with the weapon's guidance) or keep aiming (0x272573..0x2726B6). + BAPStatement* firePlan = 0; // -0x654 + if (m_weapons[bot->getBotId()] != -1 && state->m_shots != 0) + firePlan = createFirePlan(bot, state, weaponVariable, targetVariable, aimValidVariable, aimVariable, + aimOffsetVariable, lookVariable, weaponInfo, selfInfo, controlInfo, targetInfo, + targetPhysical, static_cast(guidance)); // 0x275A5C + const Vec3 noOffset = { 0.0f, 0.0f, 0.0f }; + BAPAAimAtObject* const aim = checkPointer(new BAPAAimAtObject( + bot, target, noOffset, checkPointer(new BAPConFalse()), controlInfo->getAimControls(), m_patternId, false, + aimValidVariable, aimVariable)); + BAPFlowCIf* const fireOrAim = checkPointer(new BAPFlowCIf(fireCondition, firePlan, aim, m_patternId, true, false)); + + BAPCombinerParallel* const engage = checkPointer(new BAPCombinerParallel(m_patternId, 4, false)); // -0x674 + if (guidance == 0) + engage->addStatement(checkPointer(new BAPWrapperAiming(aimVariable, aimValidVariable, aimOffsetVariable, + self, target, true))); + else + engage->addStatement(checkPointer(new BAPWrapperLookAt(target, lookVariable, true, guidance == 3, + aimVariable, aimValidVariable))); // 0x2754D0 + + // Movement (0x273C3A..0x27422C): no line of fire or fire not allowed -> walk up to + // 1.1 x minimum range, forget the target, end; otherwise keep the distance at + // min + (max - min) x optimal range (randomised 0.8..1.2 beyond 10 m). + BAPStatement* movement = 0; // -0x680 + if (selfMobile && !fireFromHere) + { + BAPConOr* const noFire = checkPointer(new BAPConOr()); // -0x684 + if (!grenadeChecks) + noFire->addCondition(checkPointer(new BAPConNot(canHitShared->getNewSharedCondition()))); + else + noFire->addCondition(checkPointer(new BAPConFalse())); // 0x2751C0 + noFire->addCondition(checkPointer(new BAPConNot(checkPointer(new BAPConAllowFire())))); + + BAPStatement* away; + if (targetMobile) // -0x695, recomputed as before + away = checkPointer(new BAPAMoveToObjectFinding( + bot, state->m_target, 0.0f, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.5f, 0, + controlInfo->getDriveControls(), m_patternId, 0, minRange * 1.1f, 7)); + else + away = checkPointer(new BAPAMoveToFinding( + bot, movePosition, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.75f, 0, + controlInfo->getDriveControls(), m_patternId, 0.5f, minRange * 1.1f)); // 0x274CD7 + BAPCombinerSerial* const lost = checkPointer(new BAPCombinerSerial(m_patternId, 300)); // -0x6B4 + lost->addStatement(away); + lost->addStatement(checkPointer(new BAPAForgetTarget(state->m_target))); + lost->addStatement(checkPointer(new BAPFlowCEnd(m_patternId, static_cast(0), 0))); + + float optimal = weaponInfo->getOptimalRangePercentage() * 0.01f; // -0x6C4 + if (weaponInfo->getMaxRange() > 10.0f) + optimal = (randomFloat(0.4f, 0.0f) + 0.8f) * optimal; + float desired = (maxRange - minRange) * optimal + minRange; // -0x6CC + if (grenadeChecks && !weaponInfo->getIsThrown()) + { + const float height = targetInfo->getPosition().y - selfInfo->getPosition().y; + if (height > 0.0f) + desired += height * 0.25f; // 0x2748D6 + } + BAPStatement* keep; // -0x6D0 + if (targetMobile) + keep = checkPointer(new BAPAMoveToObjectFinding( + bot, state->m_target, desired, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.5f, 0, + controlInfo->getDriveControls(), m_patternId, 0, minRange * 1.1f, 8)); + else + keep = checkPointer(new BAPAMoveToFinding( + bot, movePosition, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.75f, 0, + controlInfo->getDriveControls(), m_patternId, desired, minRange * 1.1f)); // 0x2746D1 + BAPConObjectDistance* const inBand = checkPointer(new BAPConObjectDistance( + target, minRange, desired * 1.1f, true, false)); + BAPFlowCIf* const approach = checkPointer(new BAPFlowCIf(checkPointer(new BAPConNot(inBand)), keep, 0, + m_patternId, false, false)); + movement = checkPointer(new BAPFlowCIf(noFire, lost, approach, m_patternId, true, true)); + } + + // Reload once the magazine is empty (0x2727A5; no auto-reload check here). + BAPConWeaponMagAmmo* const empty = checkPointer(new BAPConWeaponMagAmmo( + weaponVariable, newVariable(context, 0), false)); + BAPATrigger* const reload = checkPointer(new BAPATrigger( + static_cast(0x20), checkPointer(new BAPConTrue()), checkPointer(new BAPConFalse()), + 0x100000000ULL, m_patternId, 0.0, false)); + engage->addStatement(checkPointer(new BAPFlowCIf(empty, reload, 0, m_patternId, true, false))); + engage->addStatement(checkPointer(new BAPAEvaluateCondition(canHitShared, m_patternId))); + + if (controlPointCondition && !fireFromHere) + { + BAPAMoveToFinding* const toControlPoint = checkPointer(new BAPAMoveToFinding( + bot, controlPoint, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.75f, 0, + controlInfo->getDriveControls(), m_patternId, 0.0f, 0.0f)); // 0x27329B + engage->addStatement(checkPointer(new BAPFlowCIf(controlPointCondition, toControlPoint, movement, + m_patternId, false, false))); + } + else if (movement) + engage->addStatement(movement); + else if (fireFromHere && squadPositionValid && !isZero(squadPosition)) + { + static_cast(bot)->setIsGoingForFlag(true); // 0x2730D8 + engage->addStatement(checkPointer(new BAPAMoveToFinding( + bot, squadPosition, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.75f, 0, + controlInfo->getDriveControls(), m_patternId, 0.0f, 0.0f))); + } + engage->addStatement(fireOrAim); + if (selfFlag) + engage->addStatement(checkPointer(new BAPAMergeSoldierInputs(m_patternId))); // 0x272EE2 + + branch = checkPointer(new BAPFlowCWhile(newTargetAlive(target), engage, false, m_patternId)); // 0x272B18 + } + else if (!stationary && state->m_hasFiringPosition) + { + // ---- Go to the firing position, then fire (0x26FBxx..0x26FF9x) ---- + block->addStatement(newOverrideSensingAgent(selfFlag, m_patternId)); + const Vec2 firingPosition = { state->m_position.x, state->m_position.z }; + BAPConPosition* const arrived = checkPointer(new BAPConPosition(firingPosition, state->m_arrivalRadius * 0.5f)); + block->addStatement(checkPointer(new BAPAMoveToFinding( + bot, state->m_position, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.5f, arrived, + selfInfo->getControlInfo()->getDriveControls(), m_patternId, 0.0f, 0.0f))); + if (m_weapons[bot->getBotId()] != -1 && state->m_shots != 0) + { + BAPCombinerParallel* const fireBlock = checkPointer(new BAPCombinerParallel(m_patternId, 6, false)); + if (guidance == 0) + fireBlock->addStatement(checkPointer(new BAPWrapperAiming(aimVariable, aimValidVariable, aimOffsetVariable, + self, target, true))); + else + fireBlock->addStatement(checkPointer(new BAPWrapperLookAt(target, lookVariable, true, guidance == 3, + aimVariable, aimValidVariable))); + if (guidance == 0) + fireBlock->addStatement(createFirePlan(bot, state, weaponVariable, targetVariable, aimValidVariable, aimVariable, + aimOffsetVariable, lookVariable, weaponInfo, selfInfo, controlInfo, + targetInfo, targetPhysical, WGSNone)); + else + fireBlock->addStatement(createFirePlanGuided(bot, state, weaponVariable, targetVariable, lookVariable, + weaponInfo, selfInfo, controlInfo, targetInfo, targetPhysical, + static_cast(guidance))); + branch = fireBlock; + } + } + else + stationary = true; + + if (stationary) + { + // ---- Fire from here (0x2709A0..0x270D26) ---- + if (m_weapons[bot->getBotId()] == -1 || state->m_shots == 0) + return 0; // the variables and the statements built so far are not released (as in the image) + block->addStatement(newOverrideSensingAgent(selfFlag, m_patternId)); + BAPCombinerParallel* const fireBlock = checkPointer(new BAPCombinerParallel(m_patternId, 7, false)); + if (!weaponInfo->hasAutoReload() && weaponInfo->getNumberOfMags() != 1) + { + // Reload (input 0x20) once the magazine is empty. + BAPConWeaponMagAmmo* const empty = checkPointer(new BAPConWeaponMagAmmo( + weaponVariable, newVariable(context, 0), false)); + BAPATrigger* const reload = checkPointer(new BAPATrigger( + static_cast(0x20), checkPointer(new BAPConTrue()), checkPointer(new BAPConFalse()), + 0x100000000ULL, m_patternId, 0.0, false)); + fireBlock->addStatement(checkPointer(new BAPFlowCIf(empty, reload, 0, m_patternId, true, false))); + } + BAPStatement* firePlan; + if (guidance == 0) + { + fireBlock->addStatement(checkPointer(new BAPWrapperAiming(aimVariable, aimValidVariable, aimOffsetVariable, + self, target, true))); + firePlan = createFirePlan(bot, state, weaponVariable, targetVariable, aimValidVariable, aimVariable, + aimOffsetVariable, lookVariable, weaponInfo, selfInfo, controlInfo, targetInfo, + targetPhysical, WGSNone); + } + else + { + fireBlock->addStatement(checkPointer(new BAPWrapperLookAt(target, lookVariable, true, guidance == 3, + aimVariable, aimValidVariable))); + firePlan = createFirePlanGuided(bot, state, weaponVariable, targetVariable, lookVariable, weaponInfo, selfInfo, + controlInfo, targetInfo, targetPhysical, + static_cast(guidance)); + } + fireBlock->addStatement(checkPointer(new BAPFlowCIf( + checkPointer(new BAPConObjectValidAiming(target, self, aimValidVariable, aimVariable, false)), firePlan, 0, + m_patternId, true, false))); + branch = fireBlock; + } + + // 0x2671C0 / 0x2671C3 + if (branch) + block->addStatement(branch); + int weapon = -1; + if (weaponInfo) + weapon = m_weapons[bot->getBotId()]; + BAPIWFire* const plan = checkPointer(new BAPIWFire(bot, target, m_flag20, state->m_backOff, weapon, -1, root, m_patternId)); + plan->setParent(this); + SquadManager::m_instance->shotsFired(bot->getPlayerId(), bot->getSide(), m_targets[bot->getBotId()]); + return plan; +} + +// ELF 0x25F740 (5,526 instructions; returns the BAPIWFire). The plan for a guided weapon of a bot +// whose object has type flag 0x200000 (createPlanInternal 0x2779B1): look at the target, fire the +// guided plan while the line of fire and the range (or a control point nearby) hold, keep within +// 0.5 x max .. min range, reload when empty and no own projectile is within 1000 m. +BotScript* BBPFireInfantery::createGuidedPlanInternalInfantry(Bot* bot, bool targetIsLodBot, const Vec3& movePosition) +{ + const unsigned int id = bot->getBotId(); + FiringState* const state = &m_firingStates[id]; + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + BAPContext* const context = bot->getScriptContext(); + context->clear(); + static_cast(bot)->setHadPrecisionTimeStamp(gameTime()); + dropPlan(bot); + + Information* const selfInfo = informationManager->getInformation(bot->getCurrentEquipment()); + IPIArmament* const armament = selfInfo->getArmament(); + IPIControlInfo* const controlInfo = selfInfo->getControlInfo(); + if (!armament || !selfInfo->getPhysical() || !controlInfo) + return 0; + IPIMobile* const selfMobile = selfInfo->getMobile(); + if (selfMobile) + selfMobile->isTurnable(); // result unused in the image + controlInfo->getDriveControls(); // results unused in the image + controlInfo->getAimControls(); + const Vec3& selfPosition = selfInfo->getPosition(); + + const unsigned int target = state->m_target; + Information* const targetInfo = informationManager->getInformation(target); + if (!targetInfo) + return 0; + IPIPhysical* const targetPhysical = targetInfo->getPhysical(); + if (!targetPhysical) + return 0; + + // No -1 check on the weapon index here (createPlanInternal made it). + const int weapon = m_weapons[bot->getBotId()]; + WeaponInfo* const weaponInfo = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(weapon)); + armament->setActiveWeapon(weapon, bot->getSide()); + + BAPVariable* const weaponVariable = newVariable(context, weaponInfo); + BAPVariable* const targetVariable = newVariable(context, target); + BAPVariable* const aimValidVariable = newVariable(context, false); + const Vec3 up = { 0.0f, 1.0f, 0.0f }; + const Vec3 zero = { 0.0f, 0.0f, 0.0f }; + BAPVariable* const aimVariable = newVariable(context, up); + BAPVariable* const lookVariable = newVariable(context, zero); + + BAPCombinerSerial* const root = checkPointer(new BAPCombinerSerial(m_patternId, 0)); + if (weaponInfo->getWeaponActivate() != 0x40) + root->addStatement(checkPointer(new BAPAChangeWeapon(bot, weapon, m_patternId))); + BAPCombinerParallel* const block = checkPointer(new BAPCombinerParallel(m_patternId, true, -1, false)); + root->addStatement(block); + const bool selfFlag = selfInfo->isOfType(ITSoldier); + block->addStatement(newOverrideSensingAgent(selfFlag, m_patternId)); // before the reset here + block->addStatement(checkPointer(new BAPAResetControls(true, true, true, m_patternId))); + if (!selfFlag) + block->addStatement(checkPointer(new BAPAUseFlareOnMissileLock(bot, 0x800000000000ULL, m_patternId))); + const int guidance = weaponInfo->getWeaponGuidanceType(); + + // A control point close to the bot (no fire-from-here / no-move checks in this function). + BAPConSharedCondition* controlPointCondition = 0; // -0x220 + AIStrategicObject* const object = + AIStrategicObjectManager::getInstance()->getClosestObject(selfPosition, bot->getSide(), false); + Vec3 controlPoint = { 0.0f, 0.0f, 0.0f }; + if (object && static_cast(object)->m_controlPointId != static_cast(-1)) + { + // The image reads the vehicle number of a null mobile here as well (non-virtual field read). + const int equipmentType = selfInfo->getUnit()->getEquipmentType(); + const int vehicleNumber = selfMobile->getVehicleNumber(); + static_cast(object)->getControlpointPos(object, bot->getSide(), vehicleNumber, + equipmentType, selfPosition, controlPoint); + const float radius = object->m_size[bot->getSide()]; + Vec3 objectPosition = { 0.0f, 0.0f, 0.0f }; + vec2ToVec3XZ(object->getPosition(bot->getSide()), objectPosition); + objectPosition.y = controlPoint.y; + const Vec3 offset = { objectPosition.x - controlPoint.x, objectPosition.y - controlPoint.y, + objectPosition.z - controlPoint.z }; + if (offset.x * offset.x + offset.y * offset.y + offset.z * offset.z < radius * radius) + { + // The image also computes controlPoint - selfPosition into a slot it never reads. + BAPConAnd* const near = checkPointer(new BAPConAnd()); + near->addCondition(checkPointer(new BAPConStrategicObjectStatus(object, bot->getSide(), false))); // 0x263FCF + near->addCondition(checkPointer(new BAPConPointDistance(controlPoint, 40.0f, true))); + controlPointCondition = checkPointer(new BAPConSharedCondition(near)); + } + } + + BAPConSharedCondition* const lineOfFire = + checkPointer(new BAPConSharedCondition(checkPointer(new BAPConObjectLineOfFire(target, targetIsLodBot)))); + BAPConAnd* const fireCondition = checkPointer(new BAPConAnd()); + fireCondition->addCondition(lineOfFire->getNewSharedCondition()); + if (!controlPointCondition) + fireCondition->addCondition(checkPointer(new BAPConObjectDistance( + target, weaponInfo->getMinRange() * 0.9f, weaponInfo->getMaxRange() * 1.1f, true, false))); + else + { + BAPConOr* const inRange = checkPointer(new BAPConOr()); + inRange->addCondition(checkPointer(new BAPConObjectDistance( + target, weaponInfo->getMinRange() * 0.9f, weaponInfo->getMaxRange() * 1.1f, true, false))); + inRange->addCondition(controlPointCondition->getNewSharedCondition()); + fireCondition->addCondition(inRange); + } + + BAPStatement* firePlan = 0; // -0x268 + if (m_weapons[bot->getBotId()] != -1 && state->m_shots != 0) + firePlan = createFirePlanGuided(bot, state, weaponVariable, targetVariable, lookVariable, weaponInfo, selfInfo, + controlInfo, targetInfo, targetPhysical, + static_cast(guidance)); // 0x2638FA + BAPALookAtObject* const look = checkPointer(new BAPALookAtObject( + bot, target, 0.0f, checkPointer(new BAPConFalse()), controlInfo->getLookControls(), m_patternId, + lookVariable, 0.0f)); + BAPFlowCIf* const fireOrLook = checkPointer(new BAPFlowCIf(fireCondition, firePlan, look, m_patternId, true, false)); + + BAPCombinerParallel* const engage = checkPointer(new BAPCombinerParallel(m_patternId, 4, false)); + engage->addStatement(checkPointer(new BAPAEvaluateCondition(lineOfFire, m_patternId))); + engage->addStatement(checkPointer(new BAPWrapperLookAt(target, lookVariable, true, guidance == 3, aimVariable, + aimValidVariable))); + + // Movement (0x260456..0x260B3F): no line of fire or fire not allowed -> walk to 1.1 x minimum + // range, forget the target, end; else close in to 0.85 x max while beyond 0.5 x max or inside min. + BAPStatement* movement = 0; // -0x294 + if (selfMobile) + { + BAPConOr* const noFire = checkPointer(new BAPConOr()); + noFire->addCondition(checkPointer(new BAPConNot(lineOfFire->getNewSharedCondition()))); + noFire->addCondition(checkPointer(new BAPConNot(checkPointer(new BAPConAllowFire())))); + bool targetMobile = targetInfo->getMobile() != 0; + if (!targetMobile && !targetInfo->isPrimary()) + targetMobile = informationManager->getInformation(targetInfo->getPrimaryObject(bot->getSide()))->getMobile() != 0; + BAPStatement* away; + if (targetMobile) + away = checkPointer(new BAPAMoveToObjectFinding( + bot, state->m_target, 0.0f, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.5f, 0, + controlInfo->getDriveControls(), m_patternId, 0, weaponInfo->getMinRange() * 1.1f, 1)); + else + away = checkPointer(new BAPAMoveToFinding( + bot, movePosition, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.75f, 0, + controlInfo->getDriveControls(), m_patternId, 0.5f, weaponInfo->getMinRange() * 1.1f)); + BAPCombinerSerial* const lost = checkPointer(new BAPCombinerSerial(m_patternId, 300)); + lost->addStatement(away); + lost->addStatement(checkPointer(new BAPAForgetTarget(state->m_target))); + lost->addStatement(checkPointer(new BAPFlowCEnd(m_patternId, static_cast(0), 0))); + + BAPConOr* const approachCondition = checkPointer(new BAPConOr()); + approachCondition->addCondition(checkPointer(new BAPConObjectDistance(target, weaponInfo->getMaxRange() * 0.5f, true, false, true))); + approachCondition->addCondition(checkPointer(new BAPConObjectDistance(target, weaponInfo->getMinRange(), true, false, false))); + BAPStatement* approachMove; + if (targetMobile) + approachMove = checkPointer(new BAPAMoveToObjectFinding( + bot, state->m_target, weaponInfo->getMaxRange() * 0.85f, selfMobile->getMaxSpeed(), + selfMobile->getMaxSpeed() * 0.5f, 0, controlInfo->getDriveControls(), m_patternId, + checkPointer(new BAPConFalse()), atLeast(weaponInfo->getMinRange() * 1.1f, 15.0f), 2)); + else + approachMove = checkPointer(new BAPAMoveToFinding( + bot, movePosition, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.75f, 0, + controlInfo->getDriveControls(), m_patternId, weaponInfo->getMaxRange() * 0.85f, + atLeast(weaponInfo->getMinRange() * 1.1f, 15.0f))); + BAPFlowCIf* const approach = checkPointer(new BAPFlowCIf(approachCondition, approachMove, 0, m_patternId, false, false)); + movement = checkPointer(new BAPFlowCIf(noFire, lost, approach, m_patternId, true, false)); // 0x260B3F + } + + // Reload: empty magazine and no own projectile within 1000 m (0x260B52..0x260DE4). + BAPConAnd* const reloadCondition = checkPointer(new BAPConAnd()); + reloadCondition->addCondition(checkPointer(new BAPConWeaponMagAmmo(weaponVariable, newVariable(context, 0), false))); + reloadCondition->addCondition(checkPointer(new BAPConNot(checkPointer(new BAPConDistanceToProj(armament, 1000.0f))))); + BAPATrigger* const reload = checkPointer(new BAPATrigger( + static_cast(0x20), checkPointer(new BAPConTrue()), checkPointer(new BAPConFalse()), + 0x100000000ULL, m_patternId, 0.0, false)); + engage->addStatement(checkPointer(new BAPFlowCIf(reloadCondition, reload, 0, m_patternId, true, false))); + if (controlPointCondition) + { + BAPAMoveToFinding* const toControlPoint = checkPointer(new BAPAMoveToFinding( + bot, controlPoint, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.75f, 0, + controlInfo->getDriveControls(), m_patternId, 0.0f, 0.0f)); + movement = checkPointer(new BAPFlowCIf(controlPointCondition, toControlPoint, movement, m_patternId, false, false)); + } + engage->addStatement(movement); // null is ignored + engage->addStatement(fireOrLook); + if (selfFlag) + engage->addStatement(checkPointer(new BAPAMergeSoldierInputs(m_patternId))); + block->addStatement(checkPointer(new BAPFlowCWhile(newTargetAlive(target), engage, false, m_patternId))); + + int planWeapon = -1; + if (weaponInfo) + planWeapon = m_weapons[bot->getBotId()]; + BAPIWFire* const plan = checkPointer(new BAPIWFire(bot, target, m_flag20, state->m_backOff, planWeapon, -1, root, m_patternId)); + plan->setParent(this); + return plan; // no SquadManager::shotsFired here (unlike createPlanInternal) +} + +// ELF 0x277CF0 (1,941 instructions). The firing part of a plan: aim at the target (or at the +// firing position's point for indirect fire, FiringState::m_bool26), pull the trigger while the +// precision condition (and, for splash weapons in static attack, the grenade checks) hold, and +// zoom first when the weapon has a zoom input. +BAPStatement* BBPFireInfantery::createFirePlan(Bot* bot, BBPFireInfantery::FiringState* state, + BAPVariable* weaponVariable, BAPVariable*, + BAPVariable* aimValidVariable, BAPVariable* aimVariable, + BAPVariable* aimOffsetVariable, BAPVariable*, + WeaponInfo* weaponInfo, Information* selfInfo, IPIControlInfo* controlInfo, + Information* targetInfo, IPIPhysical*, WeaponGuidingSystem guidance) +{ + BAPContext* const context = bot->getScriptContext(); + const unsigned int target = state->m_target; + + // A sniper (spawn kit 1) with a zoomed long-range weapon (-0x179). + bool sniping = false; + if (weaponInfo->getWeaponZoom() != 0x40 && bot->getSpawnKit() == 1 && weaponInfo->getMaxRange() > 100.0f) + sniping = true; + bool splash = false; // -0x17A + if (weaponInfo->getExplosionRadius() != 0.0f && guidance == 0) + splash = true; + SensedObject* const sensed = bot->getSensedObjectFromHandle(target); + const bool selfFlag = selfInfo->isOfType(ITSoldier); + const bool targetFlag = targetInfo->isOfType(ITSoldier); + bool splashAtTarget = false; // -0x198 + if (!selfFlag && targetFlag && guidance == 0 && weaponInfo->getExplosionRadius() != 0.0f) + splashAtTarget = true; + bool targetAbove = false; + if (bot->getSpawnKit() != 1 && !weaponInfo->getIsThrown()) + { + const Vec3& targetPosition = targetInfo->getPosition(); + const Vec3& selfPosition = selfInfo->getPosition(); + if (30.0f < targetPosition.y - selfPosition.y) + targetAbove = true; + } + bool grenadeChecks = false; // -0x1AA + if (static_cast(bot)->getUseStaticAttack() && splash && targetFlag + && ((sensed->m_flags & 8) || splashAtTarget || targetAbove)) + grenadeChecks = true; + + BAPCombinerParallel* const plan = checkPointer(new BAPCombinerParallel(m_patternId, false, 0xE, false)); + BAPAAimAt* aim; + if (!state->m_bool26) + { + const Vec3 noOffset = { 0.0f, 0.0f, 0.0f }; + aim = checkPointer(new BAPAAimAtObject(bot, target, noOffset, checkPointer(new BAPConFalse()), + controlInfo->getAimControls(), m_patternId, false, aimValidVariable, + aimVariable)); + } + else + { + BAPVariable* const point = newVariable(context, state->m_firingPosition); + const Vec3 noOffset = { 0.0f, 0.0f, 0.0f }; + aim = checkPointer(new BAPAAimAtPoint(bot, point, noOffset, checkPointer(new BAPConFalse()), + controlInfo->getAimControls(), m_patternId, aimValidVariable, aimVariable)); + } + plan->addStatement(aim); + + float deviation = weaponInfo->getAllowedDeviation(); + if (splash && targetFlag && !selfFlag) + deviation = 1.0f; // 0x2780B1 cmove + BAPCondition* precision; + if (!aimValidVariable) + precision = checkPointer(new BAPCConPrecision(target, aim, deviation, !weaponInfo->getBurst(), sniping, + weaponInfo->getMaxRange() < 5.0f)); + else + precision = checkPointer(new BAPCConPrecision(target, aimValidVariable, aimVariable, aimOffsetVariable, deviation, + !weaponInfo->getBurst(), sniping, weaponInfo->getMaxRange() < 5.0f)); + BAPConAnd* const fireCondition = checkPointer(new BAPConAnd()); + if (weaponInfo->usesHeat()) + fireCondition->addCondition(checkPointer(new BAPConSharedCondition( + checkPointer(new BAPConWeaponHeat(weaponVariable, 0.8f, 0.5f))))); // 0x278F50 + if (grenadeChecks && splashAtTarget) + { + // 0x278E03: the precision condition, then the splash-damage check (3.5 m). + fireCondition->addCondition(precision); + fireCondition->addCondition(checkPointer(new BAPConSplashDamage(target, aimOffsetVariable, aimVariable, 3.5f))); + } + else + { + if (grenadeChecks) + fireCondition->addCondition(checkPointer(new BAPConOkToThrowGrenade(target, aimOffsetVariable, aimVariable))); + fireCondition->addCondition(precision); + } + + // A fresh plan waits (1.5 + U[0,1)) x (1 - skill) s before the first shot (0x278C50). + float delay = 0.0f; + if (m_freshPlan && weaponInfo->getMaxRange() > 10.0f) + { + const float wait = randomFloat(1.0f, 0.0f) + 1.5f; + delay = (1.0f - static_cast(CommonSingletonServer::m_iaiSettings)->getBotSkill()) * wait; + } + BAPStatement* trigger; + const int fire = weaponInfo->getWeaponFire(); + if (!weaponInfo->getBurst()) + trigger = checkPointer(new BAPATrigger(static_cast(fire), fireCondition, 0, inputMask(fire), + m_patternId, delay, true)); + else + trigger = checkPointer(new BAPATriggerContinously(static_cast(fire), fireCondition, 0, 0, + inputMask(fire), m_patternId, delay)); + if (weaponInfo->getWeaponZoom() != 0x40) + { + const int zoom = weaponInfo->getWeaponZoom(); + BAPATrigger* const zoomIn = checkPointer(new BAPATrigger( + static_cast(zoom), checkPointer(new BAPConTrue()), checkPointer(new BAPConFalse()), + inputMask(zoom), m_patternId, 0.0, false)); + plan->addStatement(checkPointer(new BAPFlowCIf(checkPointer(new BAPConNot(checkPointer(new BAPConWeaponIsZoomed()))), + zoomIn, 0, m_patternId, true, false))); + } + plan->addStatement(trigger); + return plan; +} + +// ELF 0x279B40 (1,735 instructions). The firing part for guided weapons: look at the target (or +// at the init(Vec3) position when the target is unknown) and fire once nothing in the Or holds: +// an empty magazine, no lock (heat-seeking and laser-guided), or a look deviation above 5 deg +// (laser-guided; the function-static `degrees`, 5.0 in .data 0x4BBE64) or 3 deg (otherwise). +BAPStatement* BBPFireInfantery::createFirePlanGuided(Bot* bot, const BBPFireInfantery::FiringState* state, + BAPVariable* weaponVariable, BAPVariable*, + BAPVariable* lookVariable, WeaponInfo* weaponInfo, + Information*, IPIControlInfo* controlInfo, Information* targetInfo, + IPIPhysical*, WeaponGuidingSystem guidance) +{ + static float degrees = 5.0f; + BAPContext* const context = bot->getScriptContext(); + const unsigned int target = state->m_target; + BAPCombinerParallel* const plan = checkPointer(new BAPCombinerParallel(m_patternId, false, 0xE, false)); + BAPALook* look; + if (targetInfo) + look = checkPointer(new BAPALookAtObject(bot, target, 0.0f, checkPointer(new BAPConFalse()), + controlInfo->getLookControls(), m_patternId, lookVariable, 0.0f)); + else + look = checkPointer(new BAPALookAtPoint(m_targetPositions[bot->getBotId()], bot, 0.00872664619f, + checkPointer(new BAPConFalse()), controlInfo->getLookControls(), + m_patternId)); // 0x27B345 + plan->addStatement(look); + + BAPConOr* const holdFire = checkPointer(new BAPConOr()); + holdFire->addCondition(checkPointer(new BAPConWeaponMagAmmo(weaponVariable, newVariable(context, 0), false))); + if (static_cast(guidance) - 1u < 2u) + holdFire->addCondition(checkPointer(new BAPConNot(checkPointer(new BAPConWeaponHasLockOnTarget(weaponVariable, target))))); + if (guidance == WGSLaserGuided) + holdFire->addCondition(checkPointer(new BAPConNot(checkPointer(new BAPCConLookDeviation(look, degrees * 0.017453292f, false))))); + else + holdFire->addCondition(checkPointer(new BAPConNot(checkPointer(new BAPCConLookDeviation(look, 0.052359879f, false))))); + + const int fire = weaponInfo->getWeaponFire(); + BAPATrigger* const trigger = checkPointer(new BAPATrigger(static_cast(fire), checkPointer(new BAPConTrue()), + holdFire, inputMask(fire), m_patternId, 0.0, true)); + if (weaponInfo->getWeaponZoom() != 0x40) + { + const int zoom = weaponInfo->getWeaponZoom(); + BAPATrigger* const zoomIn = checkPointer(new BAPATrigger( + static_cast(zoom), checkPointer(new BAPConTrue()), checkPointer(new BAPConFalse()), + inputMask(zoom), m_patternId, 0.0, false)); + plan->addStatement(checkPointer(new BAPFlowCIf(checkPointer(new BAPConNot(checkPointer(new BAPConWeaponIsZoomed()))), + zoomIn, 0, m_patternId, true, false))); + } + plan->addStatement(trigger); + return plan; +} + +// ELF 0x27B6F0. Tries alternating angles on a circle and keeps the furthest valid trace endpoint. +void BBPFireInfantery::calculateAwayPosition(const Vec3& from, const Vec3& centre, int map, Vec3& out, float radius) +{ + const float requiredDistanceSqr = (radius - 1.0f) * (radius - 1.0f); + Vec3 best = from; + Vec3 candidate = {0.0f, 0.0f, 0.0f}; + Vec3 direction = {from.x - centre.x, 0.0f, from.z - centre.z}; + const float directionLengthSqr = direction.x * direction.x + direction.y * direction.y + direction.z * direction.z; + if (directionLengthSqr > 0.1f) { + if (std::fabs(directionLengthSqr - 1.0f) >= 1.1920929e-7f) { + if (std::fabs(directionLengthSqr) >= 1.1920929e-7f) { + const float inverseLength = 1.0f / std::sqrt(directionLengthSqr); + direction.x *= inverseLength; + direction.y *= inverseLength; + direction.z *= inverseLength; + } else { + direction = {0.0f, 0.0f, 0.0f}; + } + } + } else { + direction = {1.0f, 0.0f, 0.0f}; + } + + float bestDistanceSqr = 0.0f; + float angle = 0.0f; + while (bestDistanceSqr <= requiredDistanceSqr && angle <= 1.570796371f) { + const bool valid = TraceUtils::tracePointOnCircle(direction, centre, from, map, angle, radius, candidate); + angle = -angle; + if (angle >= 0.0f) + angle += 0.261799395f; + if (valid) { + const Vec3 delta = {centre.x - candidate.x, centre.y - candidate.y, centre.z - candidate.z}; + const float distanceSqr = delta.x * delta.x + delta.y * delta.y + delta.z * delta.z; + if (distanceSqr > bestDistanceSqr) { + best = candidate; + bestDistanceSqr = distanceSqr; + } + } + } + out = best; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFireInfantery.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFireInfantery.h new file mode 100644 index 000000000..7421c0bc1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFireInfantery.h @@ -0,0 +1,120 @@ +// Infantry fire-plan generation, recovered from libaidll.so (Linux 1.5, ia-32). +// Virtual order is checked by tools/macos/ai_behaviour_vtables.py. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPFIREINFANTERY_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPFIREINFANTERY_H + +#include + +#include "../../../../Math/Vec3.h" +#include "../../../AIInterface/BFKnowledge/WeaponTemplate.h" +#include "../AIBotActionPlan/BAPVariable.h" +#include "BBPFire.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPStatement; +class Bot; +class BotScript; +class IPIControlInfo; +class IPIPhysical; +class Information; +class WeaponInfo; + +// ELF: vtable 0x4BBE80 (9 words), operator new 0x34, package E-fire-pattern. +// Layout (x86 ELF): BBPFire up to +0x28, then the per-bot arrays below and one bool (ctor 0x25BFE0). +class BBPFireInfantery : public BBPFire +{ +public: + // Per-bot fire-decision record, 0x5C bytes in the image (new[] with a count cookie, ctor 0x25BC60). + // Names are [INFERRED] from BBPFireInfantery::createPlan (0x25C8F0); offsets are the ELF's. + class Data + { + public: + // The decision createPlan picks among its seven candidates; the image stores and compares + // the values 0..7 (`m_decision`, the history list's element). [INFERRED] numeric names: + // createPlan's candidate order is 1, 2, 3, 4, 7, 6, 5 and it handles 1, 2, 4 and 5. + enum FireDecision + { + FireDecisionNone = 0, + FireDecision1 = 1, // the direct weapon (checks its min/max range) + FireDecision2 = 2, // the indirect weapon from here (hasIndirectLineOfFire to the aim point) + FireDecision3 = 3, + FireDecision4 = 4, // the indirect weapon from a firing position (getIndirectWeaponCloseToFiringPositions) + FireDecision5 = 5, + FireDecision6 = 6, + FireDecision7 = 7 + }; + + Data(); // 0x25BC60 + + /* +0x00 */ double m_lastUpdateTime; // createPlan: game time of the last decision pass (not set by the ctor) + /* +0x08 */ FireDecision m_decision; // ctor 0 + /* +0x0C */ std::list m_history; // newest first, trimmed to 8 entries + /* +0x10 */ int m_phase; // ctor 0; 0 start, 1 approach, 2 back off, 3 firing + /* +0x14 */ double m_lockStartTime; // ctor 0.0 + /* +0x1C */ double m_lockDuration; // ctor 10.0; indirect fire: 5..10 s random + /* +0x24 */ Vec3 m_vec24; // ctor 0; [UNRESOLVED] not used by createPlan + /* +0x30 */ Vec3 m_phaseTargetPosition; // ctor 0; the target's position when the phase began + /* +0x3C */ Vec3 m_firePosition; // ctor 0 + /* +0x48 */ int m_shotsAtPhaseStart; // IAIPlayer::getNumShotsFired when phase 3 began (not set by the ctor) + /* +0x4C */ int m_int4C; // ctor -1; [UNRESOLVED] createPlan only resets it + /* +0x50 */ int m_int50; // ctor -1; [UNRESOLVED] createPlan only resets it + /* +0x54 */ double m_phaseStartTime; // game time when phase 3 began (not set by the ctor) + }; + + // The firing parameters createPlan hands to createPlanInternal, 0x38 bytes (ctor 0x25BAA0). + // Names are [INFERRED] from createPlan; offsets are the ELF's. + class FiringState + { + public: + FiringState(); // 0x25BAA0 + + /* +0x00 */ unsigned int m_target; // ctor -1 + /* +0x04 */ int m_weapon; // ctor -1; the BBPFire weapon index + /* +0x08 */ int m_shots; // ctor -1; -1 = until the target dies or the magazine is empty + /* +0x0C */ bool m_bool0C; // ctor false; carried over unchanged by createPlan + /* +0x10 */ int m_int10; // not set by the ctor; createPlan forces 1 while fire is not allowed + /* +0x14 */ bool m_bool14; // ctor false + /* +0x15 */ bool m_backOff; // ctor false; set with Data::m_phase 2 + /* +0x16 */ bool m_independentAim; // ctor false; drive and aim controls do not overlap + /* +0x17 */ bool m_hasFiringPosition; // ctor false + /* +0x18 */ Vec3 m_position; // ctor 0 + /* +0x24 */ bool m_bool24; // ctor false + /* +0x25 */ bool m_bool25; // ctor false + /* +0x26 */ bool m_bool26; // ctor false + /* +0x28 */ Vec3 m_firingPosition; // ctor 0 + /* +0x34 */ float m_arrivalRadius; // ctor 0; createPlan: own physical radius + 2 + }; + + explicit BBPFireInfantery(int); // 0x25BFE0 + virtual ~BBPFireInfantery(); // 0x25C350 + + virtual BotScript* createPlan(Bot*); // 0x25C8F0, slot +0x08; from the base declaration + virtual void init(Bot*, unsigned int, int, bool, bool); // 0x25C480, slot +0x18; from the base declaration + virtual void init(Bot*, unsigned int, const Vec3&, int); // 0x25C530, slot +0x1C; from the base declaration + virtual int getImplementationType(); // 0x27BC00, slot +0x20; from the base declaration + + // createPlanInternal returns its result as the plan (0x2779B1, then `jmp 0x2672D0`, the common return with %eax). + BotScript* createGuidedPlanInternalInfantry(Bot*, bool, const Vec3&); // 0x25F740 + // createPlan returns its result as the plan (`movl %eax,%esi` after the call at 0x25D734). + BotScript* createPlanInternal(Bot*, bool); // 0x2650F0 + // Both fire-plan builders return the statement createPlanInternal adds to a combiner or an If. + BAPStatement* createFirePlan(Bot*, BBPFireInfantery::FiringState*, BAPVariable*, BAPVariable*, BAPVariable*, BAPVariable*, BAPVariable*, BAPVariable*, WeaponInfo*, Information*, IPIControlInfo*, Information*, IPIPhysical*, WeaponGuidingSystem); // 0x277CF0 + BAPStatement* createFirePlanGuided(Bot*, const BBPFireInfantery::FiringState*, BAPVariable*, BAPVariable*, BAPVariable*, WeaponInfo*, Information*, IPIControlInfo*, Information*, IPIPhysical*, WeaponGuidingSystem); // 0x279B40 + void calculateAwayPosition(const Vec3&, const Vec3&, int, Vec3&, float); // 0x27B6F0 + +protected: + /* +0x28 */ FiringState* m_firingStates; // new FiringState[maxBots] + /* +0x2C */ Data* m_data; // new Data[maxBots] + /* +0x30 */ bool m_freshPlan; // createPlan: no plan of this pattern yet, or bot skill < 0.3 [INFERRED] name +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPFIREINFANTERY_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoint.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoint.h new file mode 100644 index 000000000..de96cc198 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoint.h @@ -0,0 +1,33 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPGOTOWAYPOINT_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPGOTOWAYPOINT_H + +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4BBF40 (7 words), package S0-skeleton. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BBPGotoWaypoint : public BBPPattern +{ +public: + virtual ~BBPGotoWaypoint() {} // weak in the image (inline) + + virtual void init(Bot*) = 0; // no body, slot +0x18; [INFERRED] from BBPGotoWaypoint3d: ELF void +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPGOTOWAYPOINT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints2d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints2d.cpp new file mode 100644 index 000000000..4e877749d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints2d.cpp @@ -0,0 +1,320 @@ +// Waypoint pattern of ground vehicles (AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints2d.cpp in the +// image; class BBPGotoWaypoint2d). Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); +// every body carries its ELF address. +// +// static init: ELF 0x27F440 (__tcf_0 0x27F4A0, _GLOBAL__I 0x27F4D0): the guard object only. + +#include "BBPGotoWaypoints2d.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBot/WaypointList.h" +#include "../AIBot/WPCloseTo.h" +#include "../AIBotActionPlan/BAPAMoveToFinding.h" +#include "../AIBotActionPlan/BAPAMoveToObjectFinding.h" +#include "../AIBotActionPlan/BAPASetSensingAgentFocus.h" +#include "../AIBotActionPlan/BAPAUseFlareOnMissileLock.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConObjectMoved.h" +#include "../AIBotActionPlan/BAPInfoWrapper.h" +#include "../AIBotActionPlan/BAPIWMoveTo.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../../../../Math/Vec3.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// Waypoint list ids (WaypointList::getId, slot +0x10): WPCloseTo 0, WPMoveTo 1, WPPatrol 2. +const int kWaypointCloseTo = 0; +const int kWaypointMoveTo = 1; +const int kWaypointPatrol = 2; + +// BAPInfoWrapper::getInfoType of a BAPIWMoveTo. +const int kInfoTypeMoveTo = 2; + +void clearScript(Bot* bot) +{ + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); +} + +void dropPlan(Bot* bot) +{ + delete bot->getPlan(); + bot->setPlan(0); +} + +// The larger of the waypoint radius and the approach range; unordered gives the range +// (fcmovbe 0x27C84C). +float approachDistance(float wayPointRadius, float range) +{ + return wayPointRadius > range ? wayPointRadius : range; +} + +// The serial body every arm starts with: the sensing focus (0.5) towards the goal. Every arm of +// createPlan builds it inline in this order (serial, focus, add). +BAPCombinerSerial* beginRoute(Information* equipment, const Vec3& goal, int patternId) +{ + BAPCombinerSerial* const serial = checkPointer(new BAPCombinerSerial(patternId, -1)); + Vec3 look; + look.x = look.y = look.z = 0.0f; + const Vec3& position = equipment->getPosition(); + look.x = goal.x - position.x; + look.y = goal.y - position.y; + look.z = goal.z - position.z; + BAPASetSensingAgentFocus* const focus = checkPointer(new BAPASetSensingAgentFocus(0.5f, look, patternId, false)); + serial->addStatement(focus); + return serial; +} + +// The common tail of every arm: parallel(use flares on missile lock, serial) inside a BAPIWMoveTo at +// the goal. The flare action is not checkPointer'd (no null test in any arm). +BotScript* finishRoute(Bot* bot, BAPCombinerSerial* serial, const Vec3& goal, int patternId, void* owner) +{ + BAPCombinerParallel* const parallel = checkPointer(new BAPCombinerParallel(patternId, true, -1, false)); + parallel->addStatement(new BAPAUseFlareOnMissileLock(bot, 0x800000000000ULL, patternId)); + parallel->addStatement(serial); + BAPIWMoveTo* const root = checkPointer(new BAPIWMoveTo(goal, parallel, patternId)); + root->setParent(owner); // +0x04 (BotScript::mpOwner) + return root; +} + +} // namespace + +// ELF 0x27BC50: BBPPattern(), the vtable store (GOT -0x2FC + 8), then the argument at +0x08. +BBPGotoWaypoint2d::BBPGotoWaypoint2d(int id) + : m_patternId(id) +{ +} + +// ELF 0x27F4F0 (D0 0x27F530): nothing of its own; the BBPGotoWaypoint vtable store and +// BBPPattern's destructor. +BBPGotoWaypoint2d::~BBPGotoWaypoint2d() +{ +} + +// ELF 0x27BCC0 (listing). Drives the vehicle along its waypoint list: +// BAPIWMoveTo(goal, parallel { BAPAUseFlareOnMissileLock, serial { BAPASetSensingAgentFocus(0.5, +// goal - position), BAPAMoveToFinding or BAPAMoveToObjectFinding } }) +// WPPatrol moves with the full waypoint radius, WPMoveTo with half of it; WPCloseTo approaches the +// object until it moved (BAPConObjectMoved). An existing plan of this pattern is rebuilt only once +// the waypoints changed; a WPPatrol or WPCloseTo plan is then kept while its goal is farther than +// 4 * the squad member's max speed from the new goal (the reverse of the soldier pattern's test), +// and the WPPatrol test reads the x components twice; both as shipped. +BotScript* BBPGotoWaypoint2d::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + // 0x27F3FE + clearScript(bot); + if (bot->getPlan()) + dropPlan(bot); + return 0; + } + + const float maxSpeed = bot->getSquadMember()->getMaxSpeed(); // 0x27BD0F + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + IPIControlInfo* const controlInfo = equipment->getControlInfo(); // 0x27BD5B, read before the plan test + + if (bot->hasPlan() && static_cast(bot->getPlan())->getPatternId() == m_patternId) + { + // 0x27D7A3: the current plan is ours. Keep it unless the waypoints changed. + if (!bot->getWaypoints()->m_flag4 || bot->getWaypoints()->getWayPointError()) + return bot->getPlan(); + bot->getWaypoints()->m_flag4 = false; + + if (static_cast(bot->getPlan())->getInfoType() == kInfoTypeMoveTo) + { + WaypointList* const waypoints = bot->getWaypoints(); + const unsigned long long controls = controlInfo->getDriveControls(); + float range = equipment->getPhysical()->getRadius() * 4.0f; + const int id = waypoints->getId(); + if (id == kWaypointMoveTo) + { + // 0x27EB97: always rebuilt. + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + Vec2 goal2d; + goal2d.x = goal2d.y = 0.0f; + if (!waypoints->getGoalPoint(goal)) + return 0; + vec3ToVec2XZ(goal, goal2d); + dropPlan(bot); + clearScript(bot); + BAPCombinerSerial* const serial = beginRoute(equipment, goal, m_patternId); + BAPAMoveToFinding* const move = checkPointer(new BAPAMoveToFinding( + bot, goal, maxSpeed, maxSpeed, 0, controls, m_patternId, waypoints->getWayPointRadius() * 0.5f, + 0.0f)); + serial->addStatement(move); + return finishRoute(bot, serial, goal, m_patternId, this); + } + if (id < kWaypointMoveTo) + { + if (id != kWaypointCloseTo) + { + // 0x27D860 + if (bot->getPlan()) + dropPlan(bot); + return 0; + } + // 0x27E12D + Vec3 target; + target.x = target.y = target.z = 0.0f; + Information* const targetInfo = + informationManager->getInformation(static_cast(waypoints)->getTarget()); + if (!targetInfo) + { + dropPlan(bot); + return 0; + } + target = targetInfo->getPosition(); + const Vec3& current = static_cast(bot->getPlan())->getPosition(); + Vec3 delta; + delta.x = delta.y = delta.z = 0.0f; + delta.x = target.x - current.x; + delta.y = target.y - current.y; + delta.z = target.z - current.z; + const float keep = maxSpeed * 4.0f; + if (delta.x * delta.x + delta.y * delta.y + delta.z * delta.z > keep * keep) // 0x27E248 + return bot->getPlan(); + dropPlan(bot); + clearScript(bot); + if (targetInfo->getPhysical()) + range = targetInfo->getPhysical()->getRadius() + range; + BAPCombinerSerial* const serial = beginRoute(equipment, target, m_patternId); + // The end condition is built inside the argument list, after the action's allocation. + BAPAMoveToObjectFinding* const move = checkPointer(new BAPAMoveToObjectFinding( + bot, static_cast(waypoints)->getTarget(), range, maxSpeed, maxSpeed, 0, controls, + m_patternId, + checkPointer(new BAPConObjectMoved(static_cast(waypoints)->getTarget(), range)), + 0.0f, -1)); + serial->addStatement(move); + return finishRoute(bot, serial, target, m_patternId, this); + } + if (id != kWaypointPatrol) + { + // 0x27D860 + if (bot->getPlan()) + dropPlan(bot); + return 0; + } + // 0x27D89B + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + Vec2 goal2d; + goal2d.x = goal2d.y = 0.0f; + if (!waypoints->getGoalPoint(goal)) + return 0; + vec3ToVec2XZ(goal, goal2d); + const float dx = static_cast(bot->getPlan())->getPosition().x - goal2d.x; + const float dx2 = static_cast(bot->getPlan())->getPosition().x - goal2d.x; // sic: x again + const float keep = 4.0f * maxSpeed; + if (dx * dx + dx2 * dx2 > keep * keep) // 0x27D960 + return bot->getPlan(); + dropPlan(bot); + clearScript(bot); + BAPCombinerSerial* const serial = beginRoute(equipment, goal, m_patternId); + BAPAMoveToFinding* const move = checkPointer(new BAPAMoveToFinding( + bot, goal, maxSpeed, maxSpeed, 0, controls, m_patternId, waypoints->getWayPointRadius(), 0.0f)); + serial->addStatement(move); + return finishRoute(bot, serial, goal, m_patternId, this); + } + // 0x27D778: another wrapper; build a new plan. + dropPlan(bot); + } + else if (bot->getPlan()) + { + dropPlan(bot); + } + + // 0x27BD94 + clearScript(bot); + if (bot->getWaypoints()->getWayPointError()) + return 0; + WaypointList* const waypoints = bot->getWaypoints(); + const unsigned long long controls = controlInfo->getDriveControls(); + float range = equipment->getPhysical()->getRadius() * 4.0f; + bot->getWaypoints()->m_flag4 = false; // 0x27BE2A + bot->getSquadMember()->clearRequestAction(); + + const int id = waypoints->getId(); + if (id == kWaypointMoveTo) + { + // 0x27CF80: the goal point is asked for twice, as compiled. + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + Vec2 goal2d; + goal2d.x = goal2d.y = 0.0f; + if (!waypoints->getGoalPoint(goal)) + return 0; + if (!waypoints->getGoalPoint(goal)) + return 0; + BAPCombinerSerial* const serial = beginRoute(equipment, goal, m_patternId); + vec3ToVec2XZ(goal, goal2d); + BAPAMoveToFinding* const move = checkPointer(new BAPAMoveToFinding( + bot, goal, maxSpeed, maxSpeed, 0, controls, m_patternId, waypoints->getWayPointRadius() * 0.5f, 0.0f)); + serial->addStatement(move); + return finishRoute(bot, serial, goal, m_patternId, this); + } + if (id < kWaypointMoveTo) + { + if (id != kWaypointCloseTo) + return 0; + // 0x27C62D + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + Information* const targetInfo = + informationManager->getInformation(static_cast(waypoints)->getTarget()); + if (!targetInfo) + return 0; + goal = targetInfo->getPosition(); + if (targetInfo->getPhysical()) + range = targetInfo->getPhysical()->getRadius() + range; + BAPCombinerSerial* const serial = beginRoute(equipment, goal, m_patternId); + // The end condition is built inside the argument list, after the action's allocation. + BAPAMoveToObjectFinding* const move = checkPointer(new BAPAMoveToObjectFinding( + bot, static_cast(waypoints)->getTarget(), + approachDistance(waypoints->getWayPointRadius(), range), maxSpeed, maxSpeed, 0, controls, m_patternId, + checkPointer(new BAPConObjectMoved(static_cast(waypoints)->getTarget(), range)), 0.0f, -1)); + serial->addStatement(move); + return finishRoute(bot, serial, goal, m_patternId, this); + } + if (id != kWaypointPatrol) + return 0; + // 0x27BE72 + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + Vec2 goal2d; + goal2d.x = goal2d.y = 0.0f; + if (!waypoints->getGoalPoint(goal)) + return 0; + BAPCombinerSerial* const serial = beginRoute(equipment, goal, m_patternId); + vec3ToVec2XZ(goal, goal2d); + BAPAMoveToFinding* const move = checkPointer(new BAPAMoveToFinding( + bot, goal, maxSpeed, maxSpeed, 0, controls, m_patternId, waypoints->getWayPointRadius(), 0.0f)); + serial->addStatement(move); + return finishRoute(bot, serial, goal, m_patternId, this); +} + +// ELF 0x27BC90: marks the bot's slot of the initiated array (+0x04). +void BBPGotoWaypoint2d::init(Bot* bot) +{ + m_initiated[bot->getBotId()] = true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints2d.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints2d.h new file mode 100644 index 000000000..029fa11f7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints2d.h @@ -0,0 +1,38 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPGOTOWAYPOINTS2D_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPGOTOWAYPOINTS2D_H + +#include "BBPGotoWaypoint.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BBF00 (7 words), operator new 0xC, package G-vehicles. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BBPGotoWaypoint2d : public BBPGotoWaypoint +{ +public: + explicit BBPGotoWaypoint2d(int); // 0x27BC50 + virtual ~BBPGotoWaypoint2d(); // 0x27F4F0 + + virtual BotScript* createPlan(Bot*); // 0x27BCC0, slot +0x08; from the base declaration + virtual void init(Bot*); // 0x27BC90, slot +0x18; from the base declaration + + /* +0x08 */ int m_patternId; // the constructor argument (operator new 0xC) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPGOTOWAYPOINTS2D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints3d.cpp new file mode 100644 index 000000000..6574bf826 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints3d.cpp @@ -0,0 +1,179 @@ +// Waypoint-following pattern of aircraft (AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints3d.cpp in +// the image). Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its +// ELF address. createPlan was checked against the listing for constructor arguments and the +// waypoint fields each arm reads. + +// static init: ELF 0x280C40 (__tcf_0 0x280CA0, _GLOBAL__I 0x280CD0): 's Init object only. +#include + +#include "BBPGotoWaypoints3d.h" + +#include "../../../../Math/Vec3.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBot/WPAltitudeCloseTo.h" +#include "../AIBot/WPAltitudeMoveTo.h" +#include "../AIBot/WPAltitudePatrol.h" +#include "../AIBot/WaypointList.h" +#include "../AIBotActionPlan/BAPAMoveTo3d.h" +#include "../AIBotActionPlan/BAPAMoveTo3dObject.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPAUseFlareOnMissileLock.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConPosition.h" +#include "../AIBotActionPlan/BAPStatement.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +void dropPlan(Bot* bot) +{ + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } +} + +// `parallel(reset controls, flares on missile lock)`, the head every arm of createPlan builds. +BAPCombinerParallel* newFlightPlan(Bot* bot, int patternId) +{ + BAPCombinerParallel* const plan = checkPointer(new BAPCombinerParallel(patternId, true, -1, false)); + plan->addStatement(checkPointer(new BAPAResetControls(true, true, true, patternId))); + // No checkPointer on this allocation in the image. + plan->addStatement(new BAPAUseFlareOnMissileLock(bot, 0x800000000000ULL, patternId)); + return plan; +} + +} // namespace + +// ELF 0x27F630 (C2 0x27F5F0): BBPPattern(), the vtable store, then the argument at +0x08. +BBPGotoWaypoint3d::BBPGotoWaypoint3d(int id) + : m_patternId(id) +{ +} + +// ELF 0x280CF0 (weak; D0 0x280D30): the BBPGotoWaypoint vtable store and BBPPattern's destructor. +BBPGotoWaypoint3d::~BBPGotoWaypoint3d() +{ +} + +// ELF 0x27F6A0. Keeps a plan of this pattern unless the waypoints were renewed (their +4 flag, +// cleared here, drops the plan); a plan of another pattern that hasPlan reports is not deleted, +// as compiled. Builds `parallel(reset controls, flares on missile lock, move)` for the flight +// waypoint lists: WPAltitudeCloseTo (5) follows the target object, WPAltitudeMoveTo (6) and +// WPAltitudePatrol (7) fly to the goal point, each with the list's distance argument. The speed is +// the list's +8 value, or the vehicle's maximum when it is negative; the arrival radius is four +// times the own physical radius (plus the target's, or 2 m for an equipment with type flag 0x20 +// on a WPAltitudeMoveTo). Any other list, like an uninitiated pattern, clears the debugger, the +// context and the plan and builds nothing. The equipment information is not null-checked. +BotScript* BBPGotoWaypoint3d::createPlan(Bot* bot) +{ + if (m_initiated[bot->getBotId()]) + { + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + if (bot->hasPlan()) + { + if (bot->getWaypoints()->m_flag4) + { + bot->getWaypoints()->m_flag4 = false; + dropPlan(bot); + } + else if (static_cast(bot->getPlan())->getPatternId() == m_patternId) + return bot->getPlan(); + } + else + dropPlan(bot); + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + + IPIMobile* const mobile = self->getMobile(); + WaypointList* const waypoints = bot->getWaypoints(); + const unsigned long long controls = self->getControlInfo()->getDriveControls(); + float radius = self->getPhysical()->getRadius() * 4.0f; + const float maxSpeed = mobile->getMaxSpeed(); + const float waypointSpeed = bot->getWaypoints()->m_float8; + const float speed = waypointSpeed < 0.0f ? maxSpeed : waypointSpeed; // NaN keeps the list's value + bot->getSquadMember()->clearRequestAction(); + + switch (waypoints->getId()) + { + case 5: + { + WPAltitudeCloseTo* const closeTo = static_cast(waypoints); + Information* const target = informationManager->getInformation(closeTo->m_target); + if (!target) + return 0; + BAPCombinerParallel* const plan = newFlightPlan(bot, m_patternId); + if (target->getPhysical()) + radius = target->getPhysical()->getRadius() + radius; + plan->addStatement(checkPointer(new BAPAMoveTo3dObject(closeTo->m_target, radius, speed, speed, + closeTo->m_third, checkPointer(new BAPConFalse()), + controls, m_patternId))); + plan->setParent(this); // +0x04 (BotScript::mpOwner) + return plan; + } + case 6: + { + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + if (!waypoints->getGoalPoint(goal)) + return 0; + BAPCombinerParallel* const plan = newFlightPlan(bot, m_patternId); + BAPConPosition* const reached = self->isOfType(ITHelicopter) + ? checkPointer(new BAPConPosition(goal, 2.0f)) + : checkPointer(new BAPConPosition(goal, radius)); + plan->addStatement(checkPointer(new BAPAMoveTo3d(bot, goal, speed, speed, reached, controls, + static_cast(waypoints)->m_third, + m_patternId))); + plan->setParent(this); + return plan; + } + case 7: + { + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + if (!waypoints->getGoalPoint(goal)) + return 0; + BAPCombinerParallel* const plan = newFlightPlan(bot, m_patternId); + BAPConPosition* const reached = checkPointer(new BAPConPosition(goal, radius)); + plan->addStatement(checkPointer(new BAPAMoveTo3d(bot, goal, speed, speed, reached, controls, + static_cast(waypoints)->m_third, + m_patternId))); + plan->setParent(this); + return plan; + } + default: + break; + } + } + + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + dropPlan(bot); + return 0; +} + +// ELF 0x27F670 +void BBPGotoWaypoint3d::init(Bot* bot) +{ + m_initiated[bot->getBotId()] = true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints3d.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints3d.h new file mode 100644 index 000000000..643c5783a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints3d.h @@ -0,0 +1,35 @@ +// Waypoint-following pattern of aircraft (3d navigation): flies the bot's flight waypoint list. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPGOTOWAYPOINTS3D_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPGOTOWAYPOINTS3D_H + +#include "BBPGotoWaypoint.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BBFC0 (7 words), operator new 0xC, package G-vehicles. +class BBPGotoWaypoint3d : public BBPGotoWaypoint +{ +public: + explicit BBPGotoWaypoint3d(int); // 0x27F630 + virtual ~BBPGotoWaypoint3d(); // 0x280CF0 + + virtual BotScript* createPlan(Bot*); // 0x27F6A0, slot +0x08; from the base declaration + virtual void init(Bot*); // 0x27F670, slot +0x18; from the base declaration + + /* +0x08 */ int m_patternId; // the constructor argument (operator new 0xC) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPGOTOWAYPOINTS3D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsBoat.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsBoat.cpp new file mode 100644 index 000000000..f45faafe4 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsBoat.cpp @@ -0,0 +1,287 @@ +// Waypoint-following pattern of boats (AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsBoat.cpp in +// the image). Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its +// ELF address. createPlan was checked against the listing for constructor arguments (bools and +// the 64-bit masks), allocation order and the waypoint fields each arm reads. + +#include "BBPGotoWaypointsBoat.h" + +#include "../../../../IO/Input/Input.h" +#include "../../../../Math/Vec3.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBot/WPBeachLanding.h" +#include "../AIBot/WPCloseTo.h" +#include "../AIBot/WaypointList.h" +#include "../AIBotActionPlan/BAPALookAhead.h" +#include "../AIBotActionPlan/BAPAMoveToDirect.h" +#include "../AIBotActionPlan/BAPAMoveToFinding.h" +#include "../AIBotActionPlan/BAPAMoveToObjectFinding.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPATriggerContinously.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConObjectMoved.h" +#include "../AIBotActionPlan/BAPConPosition.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPFlowCWhile.h" +#include "../AIBotActionPlan/BAPIWMoveTo.h" +#include "../AIBotActionPlan/BAPStatement.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIStrategicEntity/AILandingZone.h" +#include "../AIUtils/checkPointer.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x284510, __tcf_0 0x284570, _GLOBAL__I 0x2845A0). +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// [CHOSEN, not recovered] packaging: the image repeats these blocks inline in each arm. + +void dropPlan(Bot* bot) +{ + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } +} + +void clearScript(Bot* bot) +{ + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); +} + +// The look-ahead built when the vehicle looks with another control than it steers with: 5 degrees +// per update (0x3DB2B8C2), a never-ending condition, the look controls. +BAPALookAhead* newLookAhead(Bot* bot, Information* self, int patternId) +{ + return checkPointer(new BAPALookAhead(bot, 0.08726646f, checkPointer(new BAPConFalse()), + self->getControlInfo()->getLookControls(), patternId)); +} + +} // namespace + +// ELF 0x280DB0 (C1; C2 0x280D70): BBPPattern(), the vtable store (GOT -0xC5C + 8), then the argument +// at +0x08. +BBPGotoWaypointBoat::BBPGotoWaypointBoat(int id) + : m_patternId(id) +{ +} + +// ELF 0x280E30 (D1; D2 0x280DF0, D0 0x280E70): nothing of its own; the BBPGotoWaypoint vtable store +// and BBPPattern's destructor. +BBPGotoWaypointBoat::~BBPGotoWaypointBoat() +{ +} + +// ELF 0x280EE0. An uninitiated pattern clears the debugger and the context, drops the plan and +// builds nothing. A plan of this pattern is kept unless the waypoints were renewed (their +4 flag, +// cleared here); otherwise the plan is dropped, and a waypoint error builds nothing. The plan is a +// BAPIWMoveTo over the waypoint list's goal: +// 0 WPCloseTo: object-finding move to the target, ended when the target moved by the radius; +// 1 WPMoveTo: finding move to the goal point; +// 2 WPPatrol: serial(parallel(finding move ended at the goal in XZ), reset controls); +// 3/4 beach landing: outside the zone as 1; inside, serial(while(true, parallel(direct move, +// pitch held continuously))) towards the zone's box centre. +// Every move except 0 gets a parallel look-ahead when the look control differs from the drive turn +// control. The arrival radius is four times the own physical radius (plus the target's in arm 0); +// the speed is the list's +8 value, or the vehicle's maximum when it is negative. The equipment +// information is not null-checked; any other list id returns null without clearing. +BotScript* BBPGotoWaypointBoat::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + clearScript(bot); + dropPlan(bot); + return 0; + } + + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + IPIControlInfo* const controlInfo = self->getControlInfo(); + const bool lookSeparately = controlInfo->getLookHorizontalControl() != controlInfo->getDriveTurnControl(); + if (bot->hasPlan() && static_cast(bot->getPlan())->getPatternId() == m_patternId + && !bot->getWaypoints()->m_flag4) + return bot->getPlan(); + + bot->getWaypoints()->m_flag4 = false; + dropPlan(bot); + clearScript(bot); + if (bot->getWaypoints()->getWayPointError()) + return 0; + + IPIMobile* const mobile = self->getMobile(); + WaypointList* const waypoints = bot->getWaypoints(); + const unsigned long long controls = self->getControlInfo()->getDriveControls(); + float radius = self->getPhysical()->getRadius() * 4.0f; + const float maxSpeed = mobile->getMaxSpeed(); + const float waypointSpeed = bot->getWaypoints()->m_float8; + const float speed = waypointSpeed < 0.0f ? maxSpeed : waypointSpeed; // NaN keeps the list's value + bot->getSquadMember()->clearRequestAction(); + + switch (waypoints->getId()) + { + case 0: + { + WPCloseTo* const closeTo = static_cast(waypoints); + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + Information* const target = informationManager->getInformation(closeTo->m_target); + if (!target) + return 0; + goal = target->getPosition(); + if (target->getPhysical()) + radius = target->getPhysical()->getRadius() + radius; + BAPConFalse* const never = checkPointer(new BAPConFalse()); + const float listRadius = waypoints->getWayPointRadius(); + const float distance = listRadius > radius ? listRadius : radius; // unordered: radius + BAPAMoveToObjectFinding* const move = checkPointer(new BAPAMoveToObjectFinding( + bot, closeTo->m_target, distance, speed, speed, never, controls, m_patternId, + checkPointer(new BAPConObjectMoved(closeTo->m_target, radius)), 0.0f, -1)); + BAPIWMoveTo* const plan = checkPointer(new BAPIWMoveTo(goal, move, m_patternId)); + plan->setParent(this); + return plan; + } + case 1: + { + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + Vec2 goal2d; + goal2d.x = goal2d.y = 0.0f; + BAPALookAhead* look = 0; + if (!waypoints->getGoalPoint(goal)) + return 0; + vec3ToVec2XZ(goal, goal2d); // not read in this arm + if (lookSeparately) + look = newLookAhead(bot, self, m_patternId); + BAPAMoveToFinding* const move = checkPointer(new BAPAMoveToFinding( + bot, goal, speed, speed, 0, controls, m_patternId, waypoints->getWayPointRadius(), 0.0f)); + BAPIWMoveTo* plan; + if (lookSeparately) + { + BAPCombinerParallel* const both = checkPointer(new BAPCombinerParallel(m_patternId, false, -1, false)); + both->addStatement(move); + both->addStatement(look); + plan = checkPointer(new BAPIWMoveTo(goal, both, m_patternId)); + } + else + plan = checkPointer(new BAPIWMoveTo(goal, move, m_patternId)); + plan->setParent(this); + return plan; + } + case 2: + { + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + Vec2 goal2d; + goal2d.x = goal2d.y = 0.0f; + if (!waypoints->getGoalPoint(goal)) + return 0; + vec3ToVec2XZ(goal, goal2d); + BAPCombinerSerial* const steps = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + BAPCombinerParallel* const both = checkPointer(new BAPCombinerParallel(m_patternId, false, -1, false)); + // The list radius is read once for the move's distance and once more for the arrival test. + const float listRadius = waypoints->getWayPointRadius(); + const float arrivalListRadius = waypoints->getWayPointRadius(); + const float arrival = arrivalListRadius > radius ? arrivalListRadius : radius; // unordered: radius + BAPAMoveToFinding* const move = checkPointer(new BAPAMoveToFinding( + bot, goal, speed, speed, checkPointer(new BAPConPosition(goal2d, arrival)), controls, m_patternId, + listRadius, 0.0f)); + both->addStatement(move); + if (lookSeparately) + both->addStatement(newLookAhead(bot, self, m_patternId)); + steps->addStatement(both); + steps->addStatement(checkPointer(new BAPAResetControls(true, true, true, m_patternId))); + BAPIWMoveTo* const plan = checkPointer(new BAPIWMoveTo(goal, steps, m_patternId)); + plan->setParent(this); + return plan; + } + case 3: + case 4: + { + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + Vec2 goal2d; + goal2d.x = goal2d.y = 0.0f; + BAPALookAhead* look = 0; + // The goal point is asked twice; the second answer is the one used. + if (!waypoints->getGoalPoint(goal)) + return 0; + if (!waypoints->getGoalPoint(goal)) + return 0; + vec3ToVec2XZ(goal, goal2d); // not read in this arm + WPBeachLanding* const landing = static_cast(waypoints); + if (landing->insideZone()) + { + BAPCombinerSerial* const steps = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + BAPCombinerParallel* const both = checkPointer(new BAPCombinerParallel(m_patternId, false, -1, false)); + both->addStatement(checkPointer(new BAPAMoveToDirect(bot, goal, speed, speed, + checkPointer(new BAPConFalse()), controls, + m_patternId))); + if (lookSeparately) + both->addStatement(newLookAhead(bot, self, m_patternId)); + // Pitch (input 1, mask bit 1) held for as long as the loop runs. + both->addStatement(checkPointer(new BAPATriggerContinously( + io::PIPitch, checkPointer(new BAPConTrue()), checkPointer(new BAPConFalse()), + checkPointer(new BAPConFalse()), 2ULL, m_patternId, 0.0))); + steps->addStatement(checkPointer(new BAPFlowCWhile(checkPointer(new BAPConTrue()), both, false, + m_patternId))); + + Vec3 centre3d; + centre3d.x = centre3d.y = centre3d.z = 0.0f; + Vec2 centre2d; + centre2d.x = centre2d.y = 0.0f; + Vec2 centre; + centre.x = centre.y = 0.0f; + getBoxCentre(landing->m_zone->getMinCorner(), centre, landing->m_zone->getMaxCorner()); + centre2d = centre; + vec2ToVec3XZ(centre2d, centre3d); + BAPIWMoveTo* const plan = checkPointer(new BAPIWMoveTo(centre3d, steps, m_patternId)); + plan->setParent(this); + return plan; + } + + if (lookSeparately) + look = newLookAhead(bot, self, m_patternId); + BAPAMoveToFinding* const move = checkPointer(new BAPAMoveToFinding( + bot, goal, speed, speed, 0, controls, m_patternId, waypoints->getWayPointRadius(), 0.0f)); + BAPIWMoveTo* plan; + if (lookSeparately) + { + BAPCombinerParallel* const both = checkPointer(new BAPCombinerParallel(m_patternId, false, -1, false)); + both->addStatement(move); + both->addStatement(look); + plan = checkPointer(new BAPIWMoveTo(goal, both, m_patternId)); + } + else + plan = checkPointer(new BAPIWMoveTo(goal, move, m_patternId)); + plan->setParent(this); + return plan; + } + default: + return 0; + } +} + +// ELF 0x280EB0 +void BBPGotoWaypointBoat::init(Bot* bot) +{ + m_initiated[bot->getBotId()] = true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsBoat.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsBoat.h new file mode 100644 index 000000000..745950664 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsBoat.h @@ -0,0 +1,36 @@ +// Waypoint-following pattern of boats: follows the bot's waypoint list, including beach landings. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPGOTOWAYPOINTSBOAT_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPGOTOWAYPOINTSBOAT_H + +#include "BBPGotoWaypoint.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BC040 (7 words), operator new 0xC, package G-vehicles. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BBPGotoWaypointBoat : public BBPGotoWaypoint +{ +public: + explicit BBPGotoWaypointBoat(int); // 0x280DB0 + virtual ~BBPGotoWaypointBoat(); // 0x280E30 + + virtual BotScript* createPlan(Bot*); // 0x280EE0, slot +0x08; from the base declaration + virtual void init(Bot*); // 0x280EB0, slot +0x18; from the base declaration + + /* +0x08 */ int m_patternId; // the constructor argument (operator new 0xC) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPGOTOWAYPOINTSBOAT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsInfantery.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsInfantery.cpp new file mode 100644 index 000000000..f6588f2ec --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsInfantery.cpp @@ -0,0 +1,261 @@ +// Waypoint pattern of infantry (AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsInfantery.cpp in +// the image; class BBPGotoWaypointSoldier). Recovered from libaidll.so (Linux 1.5.3153, ia-32, +// symbols); every body carries its ELF address. Package D. + +// static init: ELF 0x287410 (__tcf_0 0x287470, _GLOBAL__I 0x2874A0): 's Init object only. +#include + +#include "BBPGotoWaypointsInfantery.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBot/WaypointList.h" +#include "../AIBotActionPlan/BAPAMoveToFinding.h" +#include "../AIBotActionPlan/BAPAMoveToObjectFinding.h" +#include "../AIBotActionPlan/BAPASetSensingAgentFocus.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConObjectMoved.h" +#include "../AIBotActionPlan/BAPInfoWrapper.h" +#include "../AIBotActionPlan/BAPIWMoveTo.h" +#include "../AIBotBehaviour/BBPendingCalls.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AIDllFrontier.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// Waypoint list ids (WaypointList::getId, slot +0x10): WPCloseTo 0, WPMoveTo 1, WPPatrol 2. +const int kWaypointCloseTo = 0; +const int kWaypointMoveTo = 1; +const int kWaypointPatrol = 2; + +// BAPInfoWrapper::getInfoType of a BAPIWMoveTo. +const int kInfoTypeMoveTo = 2; + +void clearScript(Bot* bot) +{ + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); +} + +void dropPlan(Bot* bot) +{ + delete bot->getPlan(); + bot->setPlan(0); +} + +} // namespace + +// ELF 0x284600 +BBPGotoWaypointSoldier::BBPGotoWaypointSoldier(int id) + : m_patternId(id) +{ +} + +// ELF 0x284680 +BBPGotoWaypointSoldier::~BBPGotoWaypointSoldier() +{ +} + +// ELF 0x284730. Moves the soldier along its waypoint list: for a point goal (WPMoveTo, WPPatrol) +// BAPIWMoveTo(goal, serial { BAPASetSensingAgentFocus(0.5, goal - position), BAPAMoveToFinding }) +// and for an object goal (WPCloseTo) the same with BAPAMoveToObjectFinding, which ends when the +// object moved (BAPConObjectMoved). A current plan of this pattern is kept while its goal is +// within 4 * the squad member's max speed of the new goal (the patrol and object cases; a WPMoveTo +// plan is always rebuilt once the list changed). +BotScript* BBPGotoWaypointSoldier::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + clearScript(bot); + if (bot->getPlan()) + dropPlan(bot); + return 0; + } + + const float maxSpeed = bot->getSquadMember()->getMaxSpeed(); // 0x28477F + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + + if (bot->hasPlan() && static_cast(bot->getPlan())->getPatternId() == m_patternId) + { + // 0x285CA3: the current plan is ours. Keep it unless the waypoints changed. + if (!bot->getWaypoints()->m_flag4 || bot->getWaypoints()->getWayPointError()) + return bot->getPlan(); + bot->getWaypoints()->m_flag4 = false; + + if (static_cast(bot->getPlan())->getInfoType() == kInfoTypeMoveTo) + { + WaypointList* const waypoints = bot->getWaypoints(); + const unsigned long long controls = + equipment->getControlInfo()->getDriveControls(); + float range = equipment->getPhysical()->getRadius() * 4.0f; + const int id = waypoints->getId(); + if (id == kWaypointPatrol || id == kWaypointMoveTo) + { + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + Vec2 goal2d; + goal2d.x = goal2d.y = 0.0f; + if (!waypoints->getGoalPoint(goal)) + return 0; + vec3ToVec2XZ(goal, goal2d); + if (id == kWaypointPatrol) + { + // 0x285E21: keep the plan while its goal is close (XZ) to the new one. + const Vec3& current = static_cast(bot->getPlan())->getPosition(); + const float dx = current.x - goal.x; + const float dz = current.z - goal.z; + const float keep = 4.0f * maxSpeed; + if (keep * keep >= dx * dx + dz * dz) + return bot->getPlan(); + } + dropPlan(bot); + clearScript(bot); + return buildMoveTo(bot, equipment, goal, maxSpeed, controls, waypoints->getWayPointRadius()); + } + if (id == kWaypointCloseTo) + { + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + const unsigned int target = bbpending::closeToTarget(waypoints); + Information* const targetInfo = informationManager->getInformation(target); + if (!targetInfo) + { + dropPlan(bot); + return 0; + } + goal = targetInfo->getPosition(); + // 0x2864EB: keep the plan while its goal is close (3d) to the object. + const Vec3& current = static_cast(bot->getPlan())->getPosition(); + Vec3 delta; + delta.x = goal.x - current.x; + delta.y = goal.y - current.y; + delta.z = goal.z - current.z; + const float keep = maxSpeed * 4.0f; + if (keep * keep >= delta.x * delta.x + delta.y * delta.y + delta.z * delta.z) + return bot->getPlan(); + dropPlan(bot); + clearScript(bot); + if (targetInfo->getPhysical()) + range = targetInfo->getPhysical()->getRadius() + range; + return buildMoveToObject(bot, equipment, waypoints, target, goal, range, maxSpeed, controls); + } + // 0x285D70 + if (bot->getPlan()) + dropPlan(bot); + return 0; + } + // 0x285C78: another wrapper; build a new plan. + if (bot->getPlan()) + dropPlan(bot); + } + else if (bot->getPlan()) + { + dropPlan(bot); + } + + // 0x2847F8 + clearScript(bot); + if (bot->getWaypoints()->getWayPointError()) + return 0; + WaypointList* const waypoints = bot->getWaypoints(); + const unsigned long long controls = equipment->getControlInfo()->getDriveControls(); // 0x284848 +0x30, 0x28484E + float range = equipment->getPhysical()->getRadius() * 4.0f; + bot->getSquadMember()->clearRequestAction(); // 0x28488A + + const int id = waypoints->getId(); + if (id == kWaypointPatrol || id == kWaypointMoveTo) + { + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + Vec2 goal2d; + goal2d.x = goal2d.y = 0.0f; + if (!waypoints->getGoalPoint(goal)) + return 0; + vec3ToVec2XZ(goal, goal2d); + return buildMoveTo(bot, equipment, goal, maxSpeed, controls, waypoints->getWayPointRadius()); + } + if (id == kWaypointCloseTo) + { + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + const unsigned int target = bbpending::closeToTarget(waypoints); + Information* const targetInfo = informationManager->getInformation(target); + if (!targetInfo) + return 0; + goal = targetInfo->getPosition(); + if (targetInfo->getPhysical()) + range = targetInfo->getPhysical()->getRadius() + range; + return buildMoveToObject(bot, equipment, waypoints, target, goal, range, maxSpeed, controls); + } + return 0; +} + +// The point-goal plan, built identically by the WPMoveTo and WPPatrol arms (0x2848C0, 0x285660, +// 0x285DAB, 0x286D45). +BotScript* BBPGotoWaypointSoldier::buildMoveTo(Bot* bot, Information* equipment, const Vec3& goal, float maxSpeed, + unsigned long long controls, float wayPointRadius) +{ + BAPAMoveToFinding* const move = checkPointer( + new BAPAMoveToFinding(bot, goal, maxSpeed, maxSpeed, 0, controls, m_patternId, wayPointRadius, 0.0f)); + BAPCombinerSerial* const serial = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + Vec3 look; + const Vec3& position = equipment->getPosition(); + look.x = goal.x - position.x; + look.y = goal.y - position.y; + look.z = goal.z - position.z; + BAPASetSensingAgentFocus* const focus = + checkPointer(new BAPASetSensingAgentFocus(0.5f, look, m_patternId, false)); + serial->addStatement(focus); + serial->addStatement(move); + BAPIWMoveTo* const root = checkPointer(new BAPIWMoveTo(goal, serial, m_patternId)); + root->setParent(this); // +0x04 (BotScript::mpOwner) + return root; +} + +// The object-goal plan of the WPCloseTo arm (0x284EC0, 0x286470): the approach distance is the +// larger of the waypoint radius and `range` (4 * own radius + the object's radius). +BotScript* BBPGotoWaypointSoldier::buildMoveToObject(Bot* bot, Information* equipment, WaypointList* waypoints, + unsigned int target, const Vec3& goal, float range, + float maxSpeed, unsigned long long controls) +{ + BAPConObjectMoved* const moved = checkPointer(new BAPConObjectMoved(target, range)); + const float wayPointRadius = waypoints->getWayPointRadius(); + const float distance = !(wayPointRadius > range) ? range : wayPointRadius; // fcmovbe 0x284FEA (unordered: range) + BAPAMoveToObjectFinding* const move = checkPointer(new BAPAMoveToObjectFinding( + bot, target, distance, maxSpeed, maxSpeed, 0, controls, m_patternId, moved, 0.0f, -1)); + BAPCombinerSerial* const serial = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + Vec3 look; + const Vec3& position = equipment->getPosition(); + look.x = goal.x - position.x; + look.y = goal.y - position.y; + look.z = goal.z - position.z; + BAPASetSensingAgentFocus* const focus = + checkPointer(new BAPASetSensingAgentFocus(0.5f, look, m_patternId, false)); + serial->addStatement(focus); + serial->addStatement(move); + BAPIWMoveTo* const root = checkPointer(new BAPIWMoveTo(goal, serial, m_patternId)); + root->setParent(this); // +0x04 (BotScript::mpOwner) + return root; +} + +// ELF 0x284700 +void BBPGotoWaypointSoldier::init(Bot* bot) +{ + m_initiated[bot->getBotId()] = true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsInfantery.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsInfantery.h new file mode 100644 index 000000000..9d0b5cfe5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsInfantery.h @@ -0,0 +1,46 @@ +// Waypoint-following pattern of infantry (class BBPGotoWaypointSoldier in BBPGotoWaypointsInfantery.cpp; +// aibehaviours.ai names it BBPGotoWaypointInfantery). +// Recovered from libaidll.so (Linux 1.5.3153); every body carries its ELF address. Package D. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPGOTOWAYPOINTSINFANTERY_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPGOTOWAYPOINTSINFANTERY_H + +#include "../../../../Math/Vec3.h" +#include "BBPGotoWaypoint.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; +class Information; +class WaypointList; + +// ELF: vtable 0x4BC0C0 (7 words), operator new 0xC, package D-behaviours. +class BBPGotoWaypointSoldier : public BBPGotoWaypoint +{ +public: + explicit BBPGotoWaypointSoldier(int id); // 0x284600 + virtual ~BBPGotoWaypointSoldier(); // 0x284680 + + virtual BotScript* createPlan(Bot*); // 0x284730, slot +0x08 + virtual void init(Bot*); // 0x284700, slot +0x18 + +private: + // [CHOSEN, not recovered] helpers for the plan the image builds inline in four arms. + BotScript* buildMoveTo(Bot*, Information* equipment, const Vec3& goal, float maxSpeed, + unsigned long long controls, float wayPointRadius); + BotScript* buildMoveToObject(Bot*, Information* equipment, WaypointList*, unsigned int target, const Vec3& goal, + float range, float maxSpeed, unsigned long long controls); + + /* +0x08 */ int m_patternId; // the constructor argument +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPGOTOWAYPOINTSINFANTERY_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPHeliFire3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPHeliFire3d.cpp new file mode 100644 index 000000000..c3bc4ab32 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPHeliFire3d.cpp @@ -0,0 +1,427 @@ +// Fire pattern of helicopters (AI/AIDLL/AI/AIBotBehaviourPattern/BBPHeliFire3d.cpp in the image). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// The builders were written from the listing block by block; Ghidra drops the bool constructor +// arguments and shows createPlanInternal's mode 0/1 arm once for both modes. +// [PLATFORM] precision: the x87 build keeps the radius sum, the bounding-box sums, the fire-rate +// scale and the 60 / shots quotient in extended precision before rounding or converting them; the +// float expressions below round them first. + +// static init: ELF 0x28C0E0 (__tcf_0 0x28C140, _GLOBAL__I 0x28C170): 's Init object only. +#include + +#include "BBPHeliFire3d.h" + +#include + +#include "../../../../Core/Debug.h" +#include "../../../../Math/LocalBoundingBox.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPAAimAtObject3d.h" +#include "../AIBotActionPlan/BAPAMoveAwayFrom3dObject.h" +#include "../AIBotActionPlan/BAPAMoveTo3dObject.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPATriggerContinously.h" +#include "../AIBotActionPlan/BAPAUseFlareOnMissileLock.h" +#include "../AIBotActionPlan/BAPCConBombPrecision3d.h" +#include "../AIBotActionPlan/BAPCConPrecision3d.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConAnd.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConInsideBattleZone.h" +#include "../AIBotActionPlan/BAPConNot.h" +#include "../AIBotActionPlan/BAPConObjectDistance.h" +#include "../AIBotActionPlan/BAPConObjectExists.h" +#include "../AIBotActionPlan/BAPConObjectHealth.h" +#include "../AIBotActionPlan/BAPConObjectInFront.h" +#include "../AIBotActionPlan/BAPConObjectLineOfFire.h" +#include "../AIBotActionPlan/BAPConObjectOccupied.h" +#include "../AIBotActionPlan/BAPConTime.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPConWeaponHeat.h" +#include "../AIBotActionPlan/BAPFlowCIf.h" +#include "../AIBotActionPlan/BAPFlowCWhile.h" +#include "../AIBotActionPlan/BAPIWFire.h" +#include "../AIBotActionPlan/BAPInfoWrapper.h" +#include "../AIBotActionPlan/BAPVariable.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IBotManager.h" +#include "WeaponChoice.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// The image's inlined plan-variable construction: `checkPointer(new BAPVariable(context, value))` +// followed by `std::list::insert(context->begin(), &variable)`. +template +BAPVariable* newVariable(BAPContext* context, const T& value) +{ + BAPVariable* const variable = checkPointer(new BAPVariable(context, value)); + context->addVariable(variable); + return variable; +} + +// `1 << input` sign-extended to the 64-bit control mask (`movl %eax,%edx; sarl $0x1f,%edx`). +unsigned long long inputMask(int input) +{ + return static_cast(static_cast(static_cast(1u << input))); +} + +IAITerrain* terrain() +{ + return static_cast(CommonSingletonServer::m_iaiTerrain); +} + +// [CHOSEN, not recovered] spelling of the image's inlined row copy (three loads at 4 * row floats). +Vec3 row(const Mat4& transformation, int index) +{ + const Vec3 result = { transformation.m[index * 4], transformation.m[index * 4 + 1], + transformation.m[index * 4 + 2] }; + return result; +} + +void dropPlan(Bot* bot) +{ + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } +} + +} // namespace + +// ELF 0x287500: BBPFire(), the vtable store (GOT -0x1308 + 8), then the argument at +0x08 +// (operator new 0x28: nothing beyond BBPFire). +BBPHeliFire3d::BBPHeliFire3d(int patternId) + : BBPFire() +{ + m_patternId = patternId; +} + +// ELF 0x287580 (D0 0x2875C0): the vtable store, then BBPFire's destructor; nothing of its own. +BBPHeliFire3d::~BBPHeliFire3d() +{ +} + +// ELF 0x287830. Keeps a fire plan of this pattern built for the same target and flag; otherwise +// drops the plan, chooses the strongest weapon with ammunition against the target's strength type +// regardless of range (7: every weapon class), and builds `IWFire(createPlanInternal)`. The mode +// comes from the own vehicle and the target, the precision from the target's bounding box (mode 0: +// 0.8 of the largest extent, at least 0.5; mode 1: the extent sum, at least 5; mode 2: the mean +// extent, at least 10). Without a usable target no plan is built; with no weapon the own object's +// update is called first, as compiled. +BotScript* BBPHeliFire3d::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + dropPlan(bot); + return 0; + } + + static_cast(bot)->resetAllControls(false, true, true); + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + if (bot->hasPlan() && static_cast(bot->getPlan())->getGeneratorId() == m_patternId + && static_cast(bot->getPlan())->getId() == BAPSTInfoWrapper + && static_cast(bot->getPlan())->getInfoType() == 0 + && static_cast(bot->getPlan())->getTarget() == m_targets[bot->getBotId()] + && m_flag20 == static_cast(bot->getPlan())->getFlagA()) + return bot->getPlan(); + + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + dropPlan(bot); + bot->getScriptContext()->clear(); + + const unsigned int target = m_targets[bot->getBotId()]; + Information* const targetInfo = informationManager->getInformation(target); + if (!targetInfo) + return 0; + IPIArmament* const armament = self->getArmament(); + IPIPhysical* const selfPhysical = self->getPhysical(); + IPIControlInfo* const controlInfo = self->getControlInfo(); + IPIPhysical* const targetPhysical = targetInfo->getPhysical(); + if (!armament || !targetPhysical || !controlInfo || !selfPhysical) + return 0; + IPIMobile* const targetMobile = targetInfo->getMobile(); + LocalBoundingBox* const box = const_cast(targetPhysical->getLocalBoundingBox()); + FireData data; + data.m_weapon = choseWeaponDistanceIndependent(m_weapons[bot->getBotId()], targetPhysical->getStrengthType(), + armament->getWeapons(), 7); + if (data.m_weapon == -1) + { + self->getAIObject()->update(); + return 0; + } + + const float selfRadius = selfPhysical->getRadius(); + const float radius = targetMobile ? targetPhysical->getRadius() + selfRadius : selfRadius + 0.0f; + data.m_approachRadius = radius + radius; + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(data.m_weapon)); + const Vec3 weaponPosition = row(weapon->getAbsoluteTransformation(), 3); // stored, never read + (void)weaponPosition; + data.m_weaponDirection = row(weapon->getAbsoluteTransformation(), 2); + data.m_position = row(self->getTransformation(), 3); + data.m_direction = row(self->getTransformation(), 2); + const bool indirect = weapon->getIndirect(); + const bool flag40 = targetInfo->isOfType(ITGround); + bot->getSquadMember()->clearRequestAction(); + if (!self->getMobile()) + { + data.m_mode = 3; + } + else + { + float limit; + float precision; + if (!flag40) + { + limit = 0.5f; + data.m_mode = 0; + precision = std::max(box->getSize().x, std::max(box->getSize().y, box->getSize().z)) * 0.8f; + } + else if (!indirect) + { + limit = 5.0f; + data.m_mode = 1; + precision = box->getSize().x + box->getSize().y + box->getSize().z; + } + else + { + limit = 10.0f; + data.m_mode = 2; + precision = (box->getSize().x + box->getSize().y + box->getSize().z) / 3.0f; + } + data.m_precision = std::max(limit, precision); + } + + BAPIWFire* const plan = checkPointer(new BAPIWFire(bot, target, m_flag20, false, data.m_weapon, -1, + createPlanInternal(bot, data), m_patternId)); + plan->setParent(this); // +0x04 (BotScript::mpOwner) + return plan; +} + +// ELF 0x287600 +void BBPHeliFire3d::init(Bot* bot, unsigned int target, int weapon, bool flag20, bool flag21) +{ + m_initiated[bot->getBotId()] = true; + m_targets[bot->getBotId()] = target; + m_weapons[bot->getBotId()] = weapon; + m_flag20 = flag20; + m_flag21 = flag21; + m_positionArgs[bot->getBotId()] = static_cast(-1); +} + +// ELF 0x287680. Helicopters have no laser-guided attack: the image reports it (an Error-type +// Debug, which aborts in this tree) and then stores the arguments like BBPFire3d's overload. +void BBPHeliFire3d::init(Bot* bot, unsigned int positionArg, const Vec3& position, int weapon) +{ + Debug(DebugTypeError, "AI/AIDLL/AI/AIBotBehaviourPattern/BBPHeliFire3d.cpp", 0x7D, "") + << "LaserGuided missiles unsuported by helicopters."; + m_initiated[bot->getBotId()] = true; + m_targets[bot->getBotId()] = static_cast(-1); + m_weapons[bot->getBotId()] = weapon; + m_positionArgs[bot->getBotId()] = positionArg; + m_targetPositions[bot->getBotId()] = position; +} + +// ELF 0x28C190 +int BBPHeliFire3d::getImplementationType() +{ + return 4; +} + +// ELF 0x288130 (listing; the switch is at 0x2882B4). Modes 0 and 1 loop while the target is +// alive and, for a weapon with heat, not too hot: inside the battle zone (150) the helicopter +// attacks when the target is in the line of fire, in range (20 m to the weapon's range) and in +// front, and otherwise backs away and re-approaches it twice; outside it closes in on the target at +// 25 m. Controls are reset and flares answer missile locks throughout. Mode 3 (no IPIMobile of its +// own) is the plain attack; mode 2 builds nothing, as compiled. +BAPStatement* BBPHeliFire3d::createPlanInternal(Bot* bot, BBPHeliFire3d::FireData& data) +{ + static float dotLimit = 0.5f; // 0x4BC124 + static float minHeight = 25.0f; // 0x4BC128 + + BAPContext* const context = bot->getScriptContext(); + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + IPIControlInfo* const controlInfo = self->getControlInfo(); + IPIArmament* const armament = self->getArmament(); + IPIMobile* const mobile = self->getMobile(); + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(data.m_weapon)); + if (data.m_weapon != -1) + armament->setActiveWeapon(data.m_weapon, bot->getSide()); + + const unsigned int target = m_targets[bot->getBotId()]; + Information* const targetInfo = informationManager->getInformation(target); // no null test + IPIUnit* const targetUnit = targetInfo->getUnit(); + const float worldSizeX = static_cast(terrain()->getWorldSizeX()); // not read + const float worldSizeZ = static_cast(terrain()->getWorldSizeZ()); // not read + (void)worldSizeX; + (void)worldSizeZ; + if (Bot* const targetBot = IBotManager::instance->getBot(targetInfo->getAIObject())) + (void)targetBot->getLodLevel(); // called, result not used + + switch (data.m_mode) + { + case 0: + case 1: + { + BAPCombinerSerial* const root = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + BAPConAnd* const alive = checkPointer(new BAPConAnd()); + alive->addCondition(checkPointer(new BAPConObjectExists(target))); + if (targetUnit && targetUnit->isOccupied()) + alive->addCondition(new BAPConObjectOccupied(target)); // no checkPointer in the image + alive->addCondition(checkPointer(new BAPConNot(checkPointer(new BAPConObjectHealth(target, 0.0f))))); + if (weapon->hasHeat()) + alive->addCondition(checkPointer(new BAPConWeaponHeat(newVariable(context, weapon), 0.8f))); + + BAPConInsideBattleZone* const inside = checkPointer(new BAPConInsideBattleZone(150.0f)); + BAPConAnd* const inRange = checkPointer(new BAPConAnd()); + BAPConObjectLineOfFire* const lineOfFire = checkPointer(new BAPConObjectLineOfFire(target, false)); + BAPConObjectDistance* const distance = + checkPointer(new BAPConObjectDistance(target, 20.0f, weapon->getMaxRange(), false, true)); + inRange->addCondition(lineOfFire); + inRange->addCondition(distance); + inRange->addCondition(checkPointer(new BAPConObjectInFront(target, 0.0f, dotLimit))); + + BAPCombinerParallel* const attackBlock = checkPointer(new BAPCombinerParallel(m_patternId, -1, false)); + attackBlock->addStatement(createMobileLessAttackPlan(bot, data)); + + BAPCombinerSerial* const evade = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + BAPAMoveAwayFrom3dObject* const away1 = checkPointer(new BAPAMoveAwayFrom3dObject( + target, 150.0f, checkPointer(new BAPConFalse()), controlInfo->getDriveControls(), m_patternId)); + BAPAMoveTo3dObject* const return1 = checkPointer(new BAPAMoveTo3dObject( + target, data.m_approachRadius, mobile->getMaxSpeed(), mobile->getMaxSpeed(), minHeight, + checkPointer(new BAPConObjectDistance(target, 30.0f, true, true, false)), controlInfo->getDriveControls(), + m_patternId)); + BAPAMoveAwayFrom3dObject* const away2 = checkPointer(new BAPAMoveAwayFrom3dObject( + target, 150.0f, checkPointer(new BAPConFalse()), controlInfo->getDriveControls(), m_patternId)); + BAPAMoveTo3dObject* const return2 = checkPointer(new BAPAMoveTo3dObject( + target, data.m_approachRadius, mobile->getMaxSpeed(), mobile->getMaxSpeed(), minHeight, + checkPointer(new BAPConObjectDistance(target, 30.0f, true, true, false)), controlInfo->getDriveControls(), + m_patternId)); + evade->addStatement(away1); + evade->addStatement(return1); + evade->addStatement(away2); + evade->addStatement(return2); + + BAPFlowCIf* const engage = checkPointer(new BAPFlowCIf(inRange, attackBlock, evade, m_patternId, true, false)); + BAPAMoveTo3dObject* const approach = checkPointer(new BAPAMoveTo3dObject( + target, data.m_approachRadius, mobile->getMaxSpeed(), mobile->getMaxSpeed(), 25.0f, + checkPointer(new BAPConObjectDistance(target, 30.0f, true, true, false)), controlInfo->getDriveControls(), + m_patternId)); + BAPFlowCIf* const zone = checkPointer(new BAPFlowCIf(inside, engage, approach, m_patternId, true, false)); + + BAPCombinerParallel* const body = checkPointer(new BAPCombinerParallel(m_patternId, true, -1, false)); + body->addStatement(checkPointer(new BAPAResetControls(true, true, true, m_patternId))); + body->addStatement(new BAPAUseFlareOnMissileLock(bot, 0x800000000000ULL, m_patternId)); // no checkPointer + body->addStatement(zone); + root->addStatement(checkPointer(new BAPFlowCWhile(alive, body, m_patternId))); + return root; + } + case 3: + return createMobileLessAttackPlan(bot, data); // 0x2882D0 + default: + return 0; + } +} + +// ELF 0x28A7B0. The attack itself: serial([press the weapon's activation input unless it is 0x40], +// parallel(aim at the target, trigger)). The trigger fires while the precision holds (modes 0, 1 +// and 3 also need the weapon's range; mode 2 uses the bomb precision) and, for a weapon with a fire +// rate, at most at 1.5 times that rate scaled down by the bot skill; burst weapons hold the +// trigger continuously. +BAPStatement* BBPHeliFire3d::createMobileLessAttackPlan(Bot* bot, BBPHeliFire3d::FireData& data) +{ + bot->getScriptContext(); // called, result not used + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + IPIControlInfo* const controlInfo = self->getControlInfo(); + WeaponInfo* const weapon = + WeaponInfoManager::m_instance->getInformation(self->getArmament()->getWeapon(data.m_weapon)); + int shots = static_cast(weapon->getFireRate() * 1.5f); + const unsigned int target = m_targets[bot->getBotId()]; + BAPCombinerSerial* const root = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + const Vec3 offset = { 0.0f, 0.0f, 0.0f }; + + if (weapon->getWeaponActivate() != 0x40) + root->addStatement(checkPointer(new BAPATrigger( + static_cast(weapon->getWeaponActivate()), checkPointer(new BAPConTrue()), + checkPointer(new BAPConFalse()), inputMask(weapon->getWeaponActivate()), m_patternId, 0.0, false))); + + BAPCombinerParallel* const fire = checkPointer(new BAPCombinerParallel(m_patternId, -1, false)); + BAPAAimAtObject3d* const aim = + checkPointer(new BAPAAimAtObject3d(bot, target, offset, checkPointer(new BAPConFalse()), + controlInfo->getAimControls(), m_patternId, 40.0f, 0.0f)); + BAPConAnd* const ready = checkPointer(new BAPConAnd()); + BAPCondition* precision = 0; + if (data.m_mode == 1) + { + BAPConObjectDistance* const inRange = + checkPointer(new BAPConObjectDistance(target, weapon->getMaxRange(), false, false, false)); + precision = checkPointer(new BAPCConPrecision3d(target, aim, weapon->getAllowedDeviation(), false)); + ready->addCondition(inRange); + } + else if (data.m_mode == 2) + { + precision = checkPointer(new BAPCConBombPrecision3d(aim, data.m_precision, true)); + } + else if (data.m_mode == 0 || data.m_mode == 3) + { + BAPConObjectDistance* const inRange = + checkPointer(new BAPConObjectDistance(target, weapon->getMaxRange(), false, false, false)); + precision = checkPointer( + new BAPCConPrecision3d(target, aim, weapon->getAllowedDeviation(), !weapon->getBurst())); + ready->addCondition(inRange); + } + if (shots != 0) + { + const float skill = static_cast(CommonSingletonServer::m_iaiSettings)->getBotSkill(); + shots = static_cast(shots * (1.0f - (1.0f - skill) * 0.8f)); + ready->addCondition(checkPointer(new BAPConTime(60.0f / shots, false, false, true))); + } + ready->addCondition(precision); // a null condition for any other mode, as compiled + + BAPStatement* trigger; + if (!weapon->getBurst()) + trigger = checkPointer(new BAPATrigger(static_cast(weapon->getWeaponFire()), ready, + checkPointer(new BAPConFalse()), inputMask(weapon->getWeaponFire()), + m_patternId, 0.0, true)); + else + trigger = checkPointer(new BAPATriggerContinously(static_cast(weapon->getWeaponFire()), + ready, 0, checkPointer(new BAPConFalse()), + inputMask(weapon->getWeaponFire()), m_patternId, 0.0)); + fire->addStatement(aim); + fire->addStatement(trigger); + root->addStatement(fire); + return root; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPHeliFire3d.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPHeliFire3d.h new file mode 100644 index 000000000..030ae8d23 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPHeliFire3d.h @@ -0,0 +1,62 @@ +// Fire pattern of helicopters: hover attacks against a target object, built by createPlan from the +// target and a weapon chosen independently of the distance. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPHELIFIRE3D_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPHELIFIRE3D_H + +#include "../../../../Math/Vec3.h" +#include "BBPFire.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +class BAPStatement; + +// ELF: vtable 0x4BC140 (9 words), operator new 0x28 (nothing beyond BBPFire), package G-vehicles. +class BBPHeliFire3d : public BBPFire +{ +public: + // The attack parameters createPlan hands to the plan builders; a stack object of createPlan + // (0x3C bytes at -0x158, no constructor in the image). Names are [INFERRED] from createPlan (0x287830). + struct FireData + { + /* +0x00 */ int m_weapon; // armament index from choseWeaponDistanceIndependent + // 0: target without object type flag 0x40; 1: flag 0x40, direct weapon; 2: flag 0x40, + // indirect weapon (createPlanInternal builds nothing for it); 3: no IPIMobile of its own. + /* +0x04 */ int m_mode; + /* +0x08 */ float m_approachRadius; // twice the own (plus the moving target's) physical radius + /* +0x0C */ float m_precision; // from the target's bounding box; not set in mode 3 + // Written by createPlan, read by neither builder. + /* +0x10 */ Vec3 m_weaponDirection; // third row of the weapon's absolute transformation + /* +0x1C */ float m_unused1C; // [UNRESOLVED] never accessed + /* +0x20 */ Vec3 m_position; // fourth row of the own transformation + /* +0x2C */ float m_unused2C; // [UNRESOLVED] never accessed + /* +0x30 */ Vec3 m_direction; // third row of the own transformation + }; + + explicit BBPHeliFire3d(int); // 0x287500 + virtual ~BBPHeliFire3d(); // 0x287580 + + virtual BotScript* createPlan(Bot*); // 0x287830, slot +0x08 + virtual void init(Bot*, unsigned int, int, bool, bool); // 0x287600, slot +0x18 + virtual void init(Bot*, unsigned int, const Vec3&, int); // 0x287680, slot +0x1C: refuses (Debug Error) + virtual int getImplementationType(); // 0x28C190, slot +0x20: 4 + + // createPlan hands createPlanInternal's statement to the BAPIWFire constructor; createPlanInternal + // returns createMobileLessAttackPlan's root for mode 3 and puts it into a parallel otherwise. + BAPStatement* createPlanInternal(Bot*, BBPHeliFire3d::FireData&); // 0x288130 + BAPStatement* createMobileLessAttackPlan(Bot*, BBPHeliFire3d::FireData&); // 0x28A7B0 +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPHELIFIRE3D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle.cpp new file mode 100644 index 000000000..019ff1b2e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle.cpp @@ -0,0 +1,82 @@ +// Idle pattern base (AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle.cpp in the image). Recovered from +// libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. Package D. + +// static init: ELF 0x28C620 (__tcf_0 0x28C680, _GLOBAL__I 0x28C6B0): 's Init object only. +#include + +#include "BBPIdle.h" + +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIUnit.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x28C1E0 +BBPIdle::BBPIdle(int id) + : m_patternId(id) +{ +} + +// ELF 0x28C260 +BBPIdle::~BBPIdle() +{ +} + +// ELF 0x28C6D0 +int BBPIdle::getType() +{ + return 0; +} + +// ELF 0x28C2E0. Retail quirk: the primary-object lookup is not null-checked. +bool BBPIdle::freePosition(unsigned int equipment, int side) +{ + Information* info = informationManager->getInformation(equipment); + if (!info) + return false; + if (!info->isPrimary()) + info = informationManager->getInformation(info->getPrimaryObject(side)); + + if (!info->getUnit()) + return false; + if (!info->getUnit()->isOccupied()) + return true; + + int iterator; + for (Information* seat = informationManager->getInformation(info->getFirstSecondaryObject(iterator, side)); seat; + seat = informationManager->getInformation(info->getSecondaryObject(iterator, side))) + { + if (seat->getUnit() && !seat->getUnit()->isOccupied()) + return true; + } + return false; +} + +// ELF 0x28C480. Same walk as freePosition, testing Information::isBooked. +bool BBPIdle::anyBookedPositions(unsigned int equipment, int side) +{ + Information* info = informationManager->getInformation(equipment); + if (!info) + return false; + if (!info->isPrimary()) + info = informationManager->getInformation(info->getPrimaryObject(side)); + + if (info->isBooked()) + return true; + + int iterator; + for (Information* seat = informationManager->getInformation(info->getFirstSecondaryObject(iterator, side)); seat; + seat = informationManager->getInformation(info->getSecondaryObject(iterator, side))) + { + if (seat->isBooked()) + return true; + } + return false; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle.h new file mode 100644 index 000000000..33cc9f2a5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle.h @@ -0,0 +1,39 @@ +// Idle pattern base: the pattern id and the pickup-seat queries the idle patterns share. +// Recovered from libaidll.so (Linux 1.5.3153); every body carries its ELF address. Package D. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPIDLE_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPIDLE_H + +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +// ELF: vtable 0x4BC1C0 (7 words), package D-behaviours. +class BBPIdle : public BBPPattern +{ +public: + explicit BBPIdle(int id); // 0x28C1E0 + virtual ~BBPIdle(); // 0x28C260 + + // 0 for the base; BBPIdle2d 1, BBPIdle3d 2, BBPIdleInfantery 3 (BBIdle::calculateUrgency switches on it). + virtual int getType(); // 0x28C6D0, slot +0x18 + + // True when the equipment's primary object, or one of its secondary objects (seats), has an + // unoccupied unit. + bool freePosition(unsigned int equipment, int side); // 0x28C2E0 + // True when the primary object or one of its secondary objects is booked. + bool anyBookedPositions(unsigned int equipment, int side); // 0x28C480 + +protected: + /* +0x08 */ int m_patternId; // the constructor argument (the BBCreateFunction's pattern id) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPIDLE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle2d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle2d.cpp new file mode 100644 index 000000000..c5dbb096d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle2d.cpp @@ -0,0 +1,183 @@ +// Idle pattern of ground vehicles (AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle2d.cpp in the image). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. + +// static init: ELF 0x28D950 (__tcf_0 0x28D9B0, _GLOBAL__I 0x28D9E0): 's Init object only. +#include + +#include "BBPIdle2d.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/BotNavigation.h" +#include "../AIBot/CommunicationAgent.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPASendRadioMessage.h" +#include "../AIBotActionPlan/BAPAUseFlareOnMissileLock.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPFlowCWhile.h" +#include "../AIBotActionPlan/BAPIWIdle.h" +#include "../AIBotActionPlan/BAPStatement.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../../Math/Mat4.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AIDllFrontier.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +IAISettings* settings() +{ + return static_cast(CommonSingletonServer::m_iaiSettings); +} + +} // namespace + +// ELF 0x28C880 +BBPIdle2d::BBPIdle2d(int id) + : BBPIdle(id) +{ + m_pickupPlayerId = checkPointer(new int[settings()->getMaxNBots()]); + for (int i = 0; i < settings()->getMaxNBots(); ++i) + m_pickupPlayerId[i] = -1; +} + +// ELF 0x28CA70 +BBPIdle2d::~BBPIdle2d() +{ + if (m_pickupPlayerId) + delete[] m_pickupPlayerId; +} + +// ELF 0x28CB60 (listing). The plan is `parallel(use flares on missile lock, serial(...))` inside a +// BAPIWIdle at the equipment's position; the serial's first statement is `while (true) reset +// controls`. A vehicle waiting for a passenger (a pickup player id >= 0 on equipment whose primary +// object lacks the 0x200000 type flag) first queues a pickup radio message (BAPASendRadioMessage +// 6/6/2, 1.0) when the passenger's vehicle is within 40 m (1600 squared) of the primary object, the +// position is free (not asked for id 255), the equipment is primary and the passenger's request +// (type 2) is confirmed. An existing plan of this pattern is kept; for a waiting vehicle it also +// re-enqueues the radio message (6/6/3, 1.0) after a confirmed request. A plan of another pattern +// that hasPlan reports is not deleted here, as compiled. Builds the plan and clears the +// navigation progress. +BotScript* BBPIdle2d::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } + return 0; + } + + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + if (bot->hasPlan()) + { + if (static_cast(bot->getPlan())->getPatternId() == m_patternId) + { + const int pickupPlayerId = m_pickupPlayerId[bot->getBotId()]; + if (pickupPlayerId >= 0 && !equipment->isOfType(ITSoldier) + && bot->getCommunicationAgent()->confirmReceivedMessage(static_cast(2), + pickupPlayerId)) + { + bot->getCommunicationAgent()->enqueueRadioMessage(static_cast(6), + static_cast(6), 3, 1.0f, -1); + } + return bot->getPlan(); + } + } + else if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } + + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + bot->getSquadMember()->clearRequestAction(); + + BAPCombinerSerial* const serial = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + Information* const primary = informationManager->getInformation(equipment->getPrimaryObject(bot->getSide())); + const int pickupPlayerId = m_pickupPlayerId[bot->getBotId()]; + const bool anyPosition = pickupPlayerId == 0xFF; + if (pickupPlayerId >= 0 && !primary->isOfType(ITSoldier)) + { + IAIPlayer* const passenger = + static_cast(CommonSingletonServer::m_iaiPlayerFactory)->getPlayerFromId(pickupPlayerId); + IAIObject* const passengerVehicle = passenger ? passenger->getCurrentVehicle() : 0; // +0x54 + if (passengerVehicle) + { + const unsigned int equipmentHandle = bot->getCurrentEquipment(); + Information* const passengerInfo = + informationManager->getInformation(passengerVehicle->getHandle(bot->getSide())); // +0xD0 + if (passengerInfo) + { + const Mat4& own = primary->getTransformation(); // +0x3C + const Mat4& other = passengerInfo->getTransformation(); + const float dx = own.m[12] - other.m[12]; + const float dy = own.m[13] - other.m[13]; + const float dz = own.m[14] - other.m[14]; + const float distanceSqr = dx * dx + dy * dy + dz * dz; + if ((anyPosition || freePosition(equipmentHandle, bot->getSide())) + && 1600.0f > distanceSqr + && equipment->isPrimary() + && bot->getCommunicationAgent()->confirmReceivedMessage(static_cast(2), + pickupPlayerId)) + { + BAPASendRadioMessage* const message = checkPointer(new BAPASendRadioMessage( + static_cast(6), static_cast(6), 2, 1.0f, + m_patternId, -1)); + serial->addStatement(message); + } + } + } + } + + BAPFlowCWhile* const loop = checkPointer(new BAPFlowCWhile( + checkPointer(new BAPConTrue()), checkPointer(new BAPAResetControls(true, true, true, m_patternId)), + m_patternId)); + serial->addStatement(loop); + BAPCombinerParallel* const parallel = checkPointer(new BAPCombinerParallel(m_patternId, true, -1, false)); + BAPAUseFlareOnMissileLock* const flares = + checkPointer(new BAPAUseFlareOnMissileLock(bot, 0x800000000000ULL, m_patternId)); + parallel->addStatement(flares); + parallel->addStatement(serial); + BAPIWIdle* const idle = checkPointer(new BAPIWIdle(equipment->getPosition(), parallel, m_patternId, bot)); + idle->setParent(this); // +0x04 (BotScript::mpOwner) + bot->getBotNavigation()->clearProgress(); + return idle; +} + +// ELF 0x28DA00 +int BBPIdle2d::getType() +{ + return 1; +} + +// ELF 0x28CB10 +void BBPIdle2d::init(Bot* bot, int pickupPlayerId) +{ + m_initiated[bot->getBotId()] = true; + m_pickupPlayerId[bot->getBotId()] = pickupPlayerId; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle2d.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle2d.h new file mode 100644 index 000000000..60e5cb7c3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle2d.h @@ -0,0 +1,38 @@ +// Idle pattern of ground vehicles (2d navigation): waits, optionally for a passenger to pick up. +// Recovered from libaidll.so (Linux 1.5.3153); every body carries its ELF address. Package D. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPIDLE2D_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPIDLE2D_H + +#include "BBPIdle.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BC240 (7 words), operator new 0x10, package D-behaviours. +class BBPIdle2d : public BBPIdle +{ +public: + explicit BBPIdle2d(int id); // 0x28C880 + virtual ~BBPIdle2d(); // 0x28CA70 + + virtual BotScript* createPlan(Bot*); // 0x28CB60, slot +0x08 + virtual int getType(); // 0x28DA00, slot +0x18: 1 + + void init(Bot*, int pickupPlayerId); // 0x28CB10 + +protected: + /* +0x0C */ int* m_pickupPlayerId; // per bot slot, -1 = none (BBIdle::calculateUrgency passes it) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPIDLE2D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle3d.cpp new file mode 100644 index 000000000..9d880b7da --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle3d.cpp @@ -0,0 +1,237 @@ +// Idle pattern of aircraft (AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle3d.cpp in the image). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. + +// static init: ELF 0x28F420 (__tcf_0 0x28F480, _GLOBAL__I 0x28F4B0): 's Init object only. +#include + +#include "BBPIdle3d.h" + +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotNavigation.h" +#include "../AIBot/CommunicationAgent.h" +#include "../AIBot/SquadMember.h" +#include "../AIBot/WaypointList.h" +#include "../AIBotActionPlan/BAPActionInline.h" +#include "../AIBotActionPlan/BAPAMoveTo3d.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPASendRadioMessage.h" +#include "../AIBotActionPlan/BAPAUseFlareOnMissileLock.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPIWIdle.h" +#include "../AIBotActionPlan/BAPInfoWrapper.h" +#include "../AIBotActionPlan/BAPStatement.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIPathFinding/AerialHeightMap/AerialHeightMap.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +IAISettings* settings() +{ + return static_cast(CommonSingletonServer::m_iaiSettings); +} + +} // namespace + +// ELF 0x28DCF0 +BBPIdle3d::BBPIdle3d(int id) + : BBPIdle(id) +{ + m_pickupPlayerId = checkPointer(new int[settings()->getMaxNBots()]); + const int bots = settings()->getMaxNBots(); + m_altitude = checkPointer(new float[bots]); + for (int i = 0; i < bots; ++i) + { + m_altitude[i] = 100.0f; + m_pickupPlayerId[i] = -1; + } +} + +// ELF 0x28E020. Retail quirk: m_altitude is not released. +BBPIdle3d::~BBPIdle3d() +{ + if (m_pickupPlayerId) + delete[] m_pickupPlayerId; +} + +// ELF 0x28E120 (listing). The plan is a BAPIWIdle at the equipment's position around +// `serial(reset controls (no aim reset), [pickup radio message], parallel(reset controls, flares on +// missile lock, [move]))`. The bot counts as airborne when the bot reports it, or when the primary +// object has type flag 0x10 and the equipment moves faster than 3 m/s; an airborne bot gets the +// move: 500 m ahead along the flattened heading plus the right axis when the primary object lacks +// type flag 0x20 or has an armament, otherwise to the waypoint goal (or stays) at the aerial +// height map altitude plus 45 m. The pickup message (6/6/2, 1.0) is queued as in BBPIdle2d, but +// only when not airborne. An existing idle plan of this pattern is kept, re-enqueueing the radio +// message (6/6/3, 1.0) for a confirmed request when not airborne. The per-bot altitude that init +// stores (+0x0C) is not read here. The equipment and primary informations are not null-checked, +// as compiled. +// [PLATFORM] precision: the x87 build keeps the heading-plus-right sum and its product with 500 in +// extended precision before adding the position; the float expressions below round each step. +BotScript* BBPIdle3d::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } + return 0; + } + + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* const mobile = equipment->getMobile(); + Information* const primary = informationManager->getInformation(equipment->getPrimaryObject(bot->getSide())); + bool airborne = false; + if (bot->isAirBorn() || (primary->isOfType(ITAir) && mobile->getSpeedMagnitude() > 3.0f)) + airborne = true; + + if (bot->hasPlan() && static_cast(bot->getPlan())->getPatternId() == m_patternId + && static_cast(bot->getPlan())->getInfoType() == 4) + { + const int pickupPlayerId = m_pickupPlayerId[bot->getBotId()]; + if (pickupPlayerId >= 0 && !airborne + && bot->getCommunicationAgent()->confirmReceivedMessage(static_cast(2), + pickupPlayerId)) + { + bot->getCommunicationAgent()->enqueueRadioMessage(static_cast(6), + static_cast(6), 3, 1.0f, -1); + } + return bot->getPlan(); + } + + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + bot->getSquadMember()->clearRequestAction(); + + const unsigned long long controls = equipment->getControlInfo()->getDriveControls(); + const float maxSpeed = mobile->getMaxSpeed(); + BAPAResetControls* const reset = checkPointer(new BAPAResetControls(false, true, true, m_patternId)); + BAPCombinerSerial* const serial = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + serial->addStatement(reset); + + const int pickupPlayerId = m_pickupPlayerId[bot->getBotId()]; + const bool anyPosition = pickupPlayerId == 0xFF; + if (pickupPlayerId >= 0 && !primary->isOfType(ITSoldier)) + { + IAIPlayer* const passenger = + static_cast(CommonSingletonServer::m_iaiPlayerFactory)->getPlayerFromId(pickupPlayerId); + IAIObject* const passengerVehicle = passenger ? passenger->getCurrentVehicle() : 0; // +0x54 + if (passengerVehicle) + { + const unsigned int equipmentHandle = bot->getCurrentEquipment(); + Information* const passengerInfo = + informationManager->getInformation(passengerVehicle->getHandle(bot->getSide())); // +0xD0 + if (passengerInfo) + { + const Mat4& own = primary->getTransformation(); // +0x3C + const Mat4& other = passengerInfo->getTransformation(); + const float dx = own.m[12] - other.m[12]; + const float dy = own.m[13] - other.m[13]; + const float dz = own.m[14] - other.m[14]; + const float distanceSqr = dx * dx + dy * dy + dz * dz; + if ((anyPosition || freePosition(equipmentHandle, bot->getSide())) + && 1600.0f > distanceSqr + && equipment->isPrimary() + && !airborne + && bot->getCommunicationAgent()->confirmReceivedMessage(static_cast(2), + pickupPlayerId)) + { + BAPASendRadioMessage* const message = checkPointer(new BAPASendRadioMessage( + static_cast(6), static_cast(6), 2, 1.0f, + m_patternId, -1)); + serial->addStatement(message); + } + } + } + } + + BAPCombinerParallel* const parallel = checkPointer(new BAPCombinerParallel(m_patternId, true, -1, false)); + parallel->addStatement(checkPointer(new BAPAResetControls(true, true, true, m_patternId))); + // No checkPointer on this allocation in the image. + parallel->addStatement(new BAPAUseFlareOnMissileLock(bot, 0x800000000000ULL, m_patternId)); + if (airborne) + { + Vec3 destination = equipment->getPosition(); // +0x30 + if (!primary->isOfType(ITHelicopter) || primary->getArmament()) + { + const Mat4& heading = equipment->getTransformation(); // +0x3C + Vec3 direction; + direction.x = heading.m[8]; + direction.y = 0.0f; + direction.z = heading.m[10]; + bapinline::normalize(direction); + const Mat4& axes = equipment->getTransformation(); + direction.x = axes.m[0] + direction.x; + direction.y = axes.m[1] + direction.y; + direction.z = axes.m[2] + direction.z; + direction.y = 0.0f; + destination.x = direction.x * 500.0f + destination.x; + destination.y = direction.y * 500.0f + destination.y; + destination.z = direction.z * 500.0f + destination.z; + } + else + { + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + if (bot->getWaypoints()->getGoalPoint(goal)) + destination = goal; + destination.y = AerialHeightMap::m_instance->getAltitude(equipment->getPosition()) + 45.0f; + } + BAPAMoveTo3d* const move = checkPointer(new BAPAMoveTo3d(bot, destination, maxSpeed, maxSpeed, + checkPointer(new BAPConFalse()), controls, 25.0f, + m_patternId)); + parallel->addStatement(move); + } + serial->addStatement(parallel); + + BAPIWIdle* const idle = checkPointer(new BAPIWIdle(equipment->getPosition(), serial, m_patternId, bot)); + idle->setParent(this); // +0x04 (BotScript::mpOwner) + bot->getBotNavigation()->clearProgress(); + return idle; +} + +// ELF 0x28F4D0 +int BBPIdle3d::getType() +{ + return 2; +} + +// ELF 0x28E0C0 +void BBPIdle3d::init(float altitude, Bot* bot, int pickupPlayerId) +{ + m_altitude[bot->getBotId()] = altitude; + m_initiated[bot->getBotId()] = true; + m_pickupPlayerId[bot->getBotId()] = pickupPlayerId; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle3d.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle3d.h new file mode 100644 index 000000000..b6cf9becb --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle3d.h @@ -0,0 +1,39 @@ +// Idle pattern of aircraft (3d navigation): circles at an altitude, optionally waiting for a pickup. +// Recovered from libaidll.so (Linux 1.5.3153); every body carries its ELF address. Package D. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPIDLE3D_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPIDLE3D_H + +#include "BBPIdle.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BC2C0 (7 words), operator new 0x14, package D-behaviours. +class BBPIdle3d : public BBPIdle +{ +public: + explicit BBPIdle3d(int id); // 0x28DCF0 + virtual ~BBPIdle3d(); // 0x28E020 + + virtual BotScript* createPlan(Bot*); // 0x28E120, slot +0x08 + virtual int getType(); // 0x28F4D0, slot +0x18: 2 + + void init(float altitude, Bot*, int pickupPlayerId); // 0x28E0C0 + +protected: + /* +0x0C */ float* m_altitude; // per bot slot, constructed 100.0f + /* +0x10 */ int* m_pickupPlayerId; // per bot slot, -1 = none +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPIDLE3D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdleInfantery.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdleInfantery.cpp new file mode 100644 index 000000000..7cdf896e7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdleInfantery.cpp @@ -0,0 +1,158 @@ +// Idle pattern of infantry (AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdleInfantery.cpp in the image). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. + +// static init: ELF 0x290960 (__tcf_0 0x2909C0, _GLOBAL__I 0x2909F0): 's Init object only. +#include + +#include "BBPIdleInfantery.h" + +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPStatement.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPASoldierPose.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConNot.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPConWeaponIsZoomed.h" +#include "../AIBotActionPlan/BAPFlowCIf.h" +#include "../AIBotActionPlan/BAPFlowCWhile.h" +#include "../AIBotActionPlan/BAPIWIdle.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIStrategicEntity/AIStrategicObject.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AIDllFrontier.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x28F520 +BBPIdleInfantery::BBPIdleInfantery(int id) + : BBPIdle(id) +{ +} + +// ELF 0x28F5A0 +BBPIdleInfantery::~BBPIdleInfantery() +{ +} + +// ELF 0x28F650. Stand still with reset controls; near a strategic object, also unzoom a zoomed +// weapon (BAPATrigger on the zoom input while not zoomed) and, for 0x200000-flagged equipment, +// take soldier pose 2. The plan root is a BAPIWIdle around `while (true) parallel`. +BotScript* BBPIdleInfantery::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } + return 0; + } + + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + if (bot->hasPlan() && static_cast(bot->getPlan())->getPatternId() == m_patternId) + return bot->getPlan(); + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } + + bot->getSquadMember()->clearRequestAction(); // SquadMember::clearRequestAction + + BAPCombinerParallel* const parallel = checkPointer(new BAPCombinerParallel(m_patternId, false, 99, false)); + BAPAResetControls* const resetControls = checkPointer(new BAPAResetControls(true, true, true, m_patternId)); + parallel->addStatement(resetControls); + + const Vec3& position = equipment->getPosition(); + AIStrategicObject* const closest = + AIStrategicObjectManager::getInstance()->getClosestObject(position, bot->getSide(), false); + if (closest) + { + float radius = closest->m_size[bot->getSide()]; + Vec3 centre; + centre.x = 0.0f; + centre.y = 0.0f; + centre.z = 0.0f; + vec2ToVec3XZ(closest->getPosition(bot->getSide()), centre); + centre.y = position.y; + Vec3 delta; + delta.x = centre.x - position.x; + delta.y = centre.y - position.y; + delta.z = centre.z - position.z; + const float distanceSqr = delta.x * delta.x + delta.y * delta.y + delta.z * delta.z; + radius = radius + 2.0f; + if (radius * radius > distanceSqr) + { + IPIArmament* const armament = equipment->getArmament(); + if (armament && armament->getActiveWeapon() != -1) + { + WeaponInfo* const weapon = + WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + if (weapon && weapon->getWeaponZoom() != 0x40) + { + // Right-to-left argument evaluation in the image: the controls mask and both + // conditions are built before the input is read again. + const int patternId = m_patternId; + const unsigned long long controls = static_cast(static_cast(1u << weapon->getWeaponZoom())); + BAPConFalse* const stop = checkPointer(new BAPConFalse()); + BAPConTrue* const start = checkPointer(new BAPConTrue()); + BAPATrigger* const unzoom = checkPointer(new BAPATrigger( + static_cast(weapon->getWeaponZoom()), start, stop, controls, patternId, + 0.0, false)); + BAPConNot* const notZoomed = checkPointer(new BAPConNot(checkPointer(new BAPConWeaponIsZoomed()))); + BAPFlowCIf* const ifNotZoomed = + checkPointer(new BAPFlowCIf(notZoomed, unzoom, 0, m_patternId, true, false)); + parallel->addStatement(ifNotZoomed); + } + } + if (equipment->isOfType(ITSoldier)) + { + BAPASoldierPose* const pose = checkPointer( + new BAPASoldierPose(static_cast(2), checkPointer(new BAPConTrue()), m_patternId, true)); + parallel->addStatement(pose); + } + } + } + + BAPFlowCWhile* const loop = checkPointer(new BAPFlowCWhile(checkPointer(new BAPConTrue()), parallel, m_patternId)); + BAPIWIdle* const idle = checkPointer(new BAPIWIdle(equipment->getPosition(), loop, m_patternId, bot)); + idle->setParent(this); // +0x04 (BotScript::mpOwner) + return idle; +} + +// ELF 0x290A10 +int BBPIdleInfantery::getType() +{ + return 3; +} + +// ELF 0x28F620 +void BBPIdleInfantery::init(Bot* bot) +{ + m_initiated[bot->getBotId()] = true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdleInfantery.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdleInfantery.h new file mode 100644 index 000000000..414081635 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdleInfantery.h @@ -0,0 +1,35 @@ +// Idle pattern of infantry: what a soldier does while nothing more urgent is chosen. +// Recovered from libaidll.so (Linux 1.5.3153); every body carries its ELF address. Package D. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPIDLEINFANTERY_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPIDLEINFANTERY_H + +#include "BBPIdle.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BC340 (7 words), operator new 0xC, package D-behaviours. No members of its own. +class BBPIdleInfantery : public BBPIdle +{ +public: + explicit BBPIdleInfantery(int id); // 0x28F520 + virtual ~BBPIdleInfantery(); // 0x28F5A0 + + virtual BotScript* createPlan(Bot*); // 0x28F650, slot +0x08 + virtual int getType(); // 0x290A10, slot +0x18: 3 + + void init(Bot*); // 0x28F620 +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPIDLEINFANTERY_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPMedicAssist.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPMedicAssist.cpp new file mode 100644 index 000000000..3c83adc95 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPMedicAssist.cpp @@ -0,0 +1,498 @@ +// Medic/engineer/support assist pattern: heal, repair or resupply a unit. Recovered from +// libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// +// static init: ELF 0x296E20 (__tcf_0 0x296E80, _GLOBAL__I 0x296EB0): the guard object only. + +#include "BBPMedicAssist.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/CommunicationAgent.h" +#include "../AIBot/SensingAgent.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPALookAtObject.h" +#include "../AIBotActionPlan/BAPAMergeSoldierInputs.h" +#include "../AIBotActionPlan/BAPAMoveToFinding.h" +#include "../AIBotActionPlan/BAPAMoveToObjectFinding.h" +#include "../AIBotActionPlan/BAPAOverrideSensingAgent.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPASendRadioMessage.h" +#include "../AIBotActionPlan/BAPASoldierPose.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPATriggerContinously.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConAnd.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConNot.h" +#include "../AIBotActionPlan/BAPConObjectDistance.h" +#include "../AIBotActionPlan/BAPConObjectExists.h" +#include "../AIBotActionPlan/BAPConObjectHealth.h" +#include "../AIBotActionPlan/BAPConObjectInFront.h" +#include "../AIBotActionPlan/BAPConTime.h" +#include "../AIBotActionPlan/BAPConTotalAmmo.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPConWeaponIsActive.h" +#include "../AIBotActionPlan/BAPFlowCIf.h" +#include "../AIBotActionPlan/BAPFlowCWhile.h" +#include "../AIBotActionPlan/BAPIWFire.h" +#include "../AIBotActionPlan/BAPInfoWrapper.h" +#include "../AIBotActionPlan/BAPVariable.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../Main/IBotManager.h" +#include "WeaponChoice.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x290A20 (C2) / 0x290DE0 (C1): BBPPattern(), +0x08 = argument, then +0x0C/+0x10/+0x14 = +// new[getMaxNBots] (IAISettings slot 0, checkPointer'd) and every slot -1; the loop re-reads +// getMaxNBots on each iteration. +BBPMedicAssist::BBPMedicAssist(int value) + : BBPPattern() +{ + m_id = value; + IAISettings* settings = static_cast(CommonSingletonServer::m_iaiSettings); + m_target = checkPointer(new unsigned int[settings->getMaxNBots()]); + m_weaponIndex = checkPointer(new int[settings->getMaxNBots()]); + m_targetPlayerId = checkPointer(new int[settings->getMaxNBots()]); + for (int i = 0; i < static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); ++i) + { + m_target[i] = 0xFFFFFFFFu; + m_weaponIndex[i] = -1; + m_targetPlayerId[i] = -1; + } +} + +// ELF 0x2911A0 (D2) / 0x291220 (D1) / 0x2912A0 (D0): delete[] +0x0C, +0x10, +0x14 when set, +// then the base. +BBPMedicAssist::~BBPMedicAssist() +{ + if (m_target) + delete[] m_target; + if (m_weaponIndex) + delete[] m_weaponIndex; + if (m_targetPlayerId) + delete[] m_targetPlayerId; +} + +namespace { + +void dropPlan(Bot* bot) +{ + delete bot->getPlan(); + bot->setPlan(0); +} + +// One weapon key as the image builds it inline: a trigger of the key that starts at once +// (BAPConTrue) and never stops by condition (BAPConFalse), with the key's control bit +// (1 << key, sign-extended from int) and no repeat time. +BAPATrigger* newKeyTrigger(const WeaponInfo* weapon, int (WeaponInfo::*key)() const, int patternId, bool flag) +{ + return checkPointer(new BAPATrigger(static_cast((weapon->*key)()), + checkPointer(new BAPConTrue()), checkPointer(new BAPConFalse()), + static_cast(1u << (weapon->*key)()), patternId, 0.0, flag)); +} + +// The image's inlined plan-variable construction: `checkPointer(new BAPVariable(context, value))` +// followed by the list insert at the context's begin. +template +BAPVariable* newVariable(BAPContext* context, const T& value) +{ + BAPVariable* const variable = checkPointer(new BAPVariable(context, value)); + context->addVariable(variable); + return variable; +} + +// The radio message type a kit confirms for a treatment request: medic 3, engineer 4, support 10; +// 0 for any other kit (no confirmation). +int requestMessageType(int kit) +{ + if (kit == 5) + return 3; + if (kit == 4) + return 4; + if (kit == 3) + return 10; + return 0; +} + +// The inlined Vec3 subtraction followed by the x87 length (fsqrt, sqrtf on NaN). +float distance(const Vec3& a, const Vec3& b) +{ + const float dx = b.x - a.x; + const float dy = b.y - a.y; + const float dz = b.z - a.z; + return std::sqrt(dx * dx + dy * dy + dz * dz); +} + +} // namespace + +// ELF 0x291550 (listing; Ghidra drops the BAPATrigger/BAPASoldierPose bool arguments, merges the +// 64-bit control masks and loses the unused weapon-2 trigger). The medic (kit 5), engineer (kit 4) +// and support (kit 3) treatment plan: heal, repair or resupply the unit m_target[bot]. +// +// The current plan is kept when it is this pattern's BAPIWFire on the same target; the request is +// then confirmed on the radio (enqueue 6/6/3) when the requester accepts. Otherwise the request +// action and the plan target are cleared, the plan dropped and a new one built: +// self (equipment == target): serial { parallel { reset controls, pose (stand/lie/crouch), +// trigger(activate key, true) } } +// other: serial { [radio 6/6/2 when the requester confirms], reset controls, +// while (target exists && health <= 0.99 / 0.75 (ammo <= 0.95 / 0.75 for support; the higher +// value when a human occupies the target)) parallel { reset controls, override sensing, +// move (to the own unit's entry position when the target cannot be reached by pathfinding, +// else to the target), look at target, pose, if (within half the replenish radius plus both +// radii) treat, merge soldier inputs } } +// treat: parallel { trigger(activate key), while (true) { override sensing, look at target, +// if (in front) hold fire while the weapon is active } (vehicles only) }, preceded by 0.5 s +// of closing in with pathfinding when the target is a reachable vehicle. +// Shipped quirks kept: the primary object of a non-primary target is not null-checked; the +// override-sensing action of the treat block, an int plan variable and a trigger of the slot 2 +// weapon's activate key are built and never used (leaked) when not added; the plan context is +// cleared after the plan is dropped; the radio statement is placed before the reset. +BotScript* BBPMedicAssist::createPlan(Bot* bot) +{ + // .bss 0x4CE4D0: no writer in the image, so the look offset is always 0. + static float yOffset; + + if (!m_initiated[bot->getBotId()]) + { + // 0x296DA0 + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) + dropPlan(bot); + return 0; + } + + const int kit = bot->getPlayer()->getSpawnKit(); + CommunicationAgent* const communication = bot->getCommunicationAgent(); + if (bot->hasPlan() && static_cast(bot->getPlan())->getPatternId() == m_id + && static_cast(bot->getPlan())->getId() == BAPSTInfoWrapper + && static_cast(bot->getPlan())->getInfoType() == 0 + && static_cast(bot->getPlan())->getTarget() == m_target[bot->getBotId()]) + { + // 0x296C68 + const int requester = m_targetPlayerId[bot->getBotId()]; + if (requester >= 0) + { + const int type = requestMessageType(kit); + if (type != 0 && communication->confirmReceivedMessage(static_cast(type), requester)) + bot->getCommunicationAgent()->enqueueRadioMessage(static_cast(6), + static_cast(6), 3, 1.0f, -1); + } + return bot->getPlan(); + } + + bot->getBotId(); // 0x2915EC, result unused + bot->getSquadMember()->clearRequestAction(); + bot->getSensingAgent()->clearPlanTargetInformation(); + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + if (bot->getPlan()) + dropPlan(bot); + bot->getScriptContext()->clear(); + + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + Information* const target = informationManager->getInformation(m_target[bot->getBotId()]); + if (!equipment || !equipment->getUnit()) + return 0; + IPIMobile* const mobile = equipment->getMobile(); + if (!mobile || !target) + return 0; + IPIArmament* const armament = equipment->getArmament(); + IPIControlInfo* const controlInfo = equipment->getControlInfo(); + IPIPhysical* const physical = equipment->getPhysical(); + IPIPhysical* const targetPhysical = target->getPhysical(); + + // 0x291753: the support kit picks among type-2 weapons, the others among type-1 weapons. + int weaponIndex; + if (bot->getPlayer()->getSpawnKit() == 3) + { + const int strengthType = targetPhysical->getStrengthType(); + const float range = distance(equipment->getPosition(), target->getPosition()); + weaponIndex = choseWeapon(armament->getWeapons(), m_weaponIndex[bot->getBotId()], range, strengthType, false, + false, false, true); + } + else + { + const int strengthType = targetPhysical->getStrengthType(); + const float range = distance(equipment->getPosition(), target->getPosition()); + weaponIndex = choseWeapon(armament->getWeapons(), m_weaponIndex[bot->getBotId()], range, strengthType, false, + true, false, false); + } + if (weaponIndex == -1) + { + equipment->getAIObject()->update(); // 0x296A89 + return 0; + } + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(weaponIndex)); + + BAPCombinerSerial* const serial = checkPointer(new BAPCombinerSerial(m_id, -1)); + // 0x291942 / 0x291956: IPIPhysical slot +0x34, getSmallestRadius, on both (not getRadius +0x2C). + float radii = physical->getSmallestRadius(); + radii = radii + targetPhysical->getSmallestRadius(); + + bool targetVacant; + if (equipment == target) + { + // 0x295FDF: treating itself. + BAPCombinerParallel* const self = checkPointer(new BAPCombinerParallel(m_id, -1, false)); + self->addStatement(checkPointer(new BAPAResetControls(true, true, true, m_id))); + self->addStatement(checkPointer(new BAPASoldierPose(SPStanding, SPLying, 3, SPCrouching, 0.0f, + checkPointer(new BAPConTrue()), + checkPointer(new BAPConFalse()), m_id, true))); + self->addStatement(newKeyTrigger(weapon, &WeaponInfo::getWeaponActivate, m_id, true)); + serial->addStatement(self); + targetVacant = false; + } + else + { + const bool targetIsSoldier = targetPhysical->getStrengthType() == 0; // -0x1C9 + const float reach = weapon->getReplenishRadius() * 0.5f + radii; // -0x1D0 + IPIUnit* const targetUnit = target->getUnit(); + // -0x1D1: approach the own unit's entry position instead of the target. + bool toEntry = true; + if (targetUnit) + { + bool noPathfinding = false; + if (targetUnit->useNoPathfindingToGetToObject() || !target->getMobile()) + noPathfinding = true; + toEntry = noPathfinding; + } + if (toEntry && !target->isPrimary()) + toEntry = !informationManager->getInformation(target->getPrimaryObject(bot->getSide()))->getMobile(); // 0x295F7F + + // 0x291A13 + BAPContext* const context = bot->getScriptContext(); + BAPVariable* const weaponVariable = newVariable(context, weapon); + newVariable(bot->getScriptContext(), 0); // 0x291AE6, never read + + BAPConAnd* const treating = checkPointer(new BAPConAnd()); + treating->addCondition(checkPointer(new BAPConObjectExists(m_target[bot->getBotId()]))); + BAPCondition* needed; + if (kit == 3) + { + // 0x295956 + if (humanPlayerInTarget(target, bot->getSide())) + needed = checkPointer(new BAPConTotalAmmo(m_target[bot->getBotId()], 0.95f)); + else + needed = checkPointer(new BAPConTotalAmmo(m_target[bot->getBotId()], 0.75f)); + } + else if (humanPlayerInTarget(target, bot->getSide())) + { + needed = checkPointer(new BAPConObjectHealth(m_target[bot->getBotId()], 0.99f)); + } + else + { + needed = checkPointer(new BAPConObjectHealth(m_target[bot->getBotId()], 0.75f)); // 0x295820 + } + treating->addCondition(needed); + + BAPCombinerParallel* const parallel = checkPointer(new BAPCombinerParallel(m_id, -1, false)); + parallel->addStatement(checkPointer(new BAPAResetControls(true, true, true, m_id))); + parallel->addStatement(checkPointer(new BAPAOverrideSensingAgent())); + if (toEntry) + { + // 0x2952B1 + const Vec3 entry = equipment->getUnit()->getEntryPositionOfNonMobile(); + parallel->addStatement(checkPointer(new BAPAMoveToFinding(bot, entry, mobile->getMaxSpeed(), mobile->getMaxSpeed(), + 0, controlInfo->getDriveControls(), m_id, 0.5f, + 0.0f))); + } + else + { + parallel->addStatement(checkPointer(new BAPAMoveToObjectFinding( + bot, m_target[bot->getBotId()], radii, mobile->getMaxSpeed(), mobile->getMaxSpeed(), 0, + controlInfo->getDriveControls(), m_id, 0, 0.0f, -1))); + } + parallel->addStatement(checkPointer(new BAPALookAtObject(bot, m_target[bot->getBotId()], 0.0f, + checkPointer(new BAPConFalse()), + equipment->getControlInfo()->getLookControls(), m_id, 0, + yOffset))); + BAPASoldierPose* pose; + if (target->isOfType(ITSoldier) && (kit == 5 || kit == 3)) + pose = checkPointer(new BAPASoldierPose(SPStanding, checkPointer(new BAPConTrue()), m_id, + m_target[bot->getBotId()], true)); // 0x294D90 + else + pose = checkPointer(new BAPASoldierPose(SPStanding, checkPointer(new BAPConTrue()), m_id, true)); + parallel->addStatement(pose); + + BAPConAnd* const inReach = checkPointer(new BAPConAnd()); + inReach->addCondition(checkPointer(new BAPConObjectDistance(m_target[bot->getBotId()], reach, false, false, false))); + BAPCombinerParallel* const treat = checkPointer(new BAPCombinerParallel(m_id, -1, false)); + treat->addStatement(newKeyTrigger(weapon, &WeaponInfo::getWeaponActivate, m_id, false)); + BAPAOverrideSensingAgent* const overrideSensing = checkPointer(new BAPAOverrideSensingAgent()); + BAPCombinerParallel* const aim = checkPointer(new BAPCombinerParallel(m_id, -1, false)); + if (!targetIsSoldier) + { + // 0x293B22 + aim->addStatement(overrideSensing); + aim->addStatement(checkPointer(new BAPALookAtObject(bot, m_target[bot->getBotId()], 0.0f, + checkPointer(new BAPConFalse()), + equipment->getControlInfo()->getLookControls(), m_id, 0, + yOffset))); + BAPATriggerContinously* const fire = checkPointer(new BAPATriggerContinously( + static_cast(weapon->getWeaponFire()), + checkPointer(new BAPConWeaponIsActive(weaponVariable)), checkPointer(new BAPConFalse()), + checkPointer(new BAPConFalse()), static_cast(1u << weapon->getWeaponFire()), m_id, 0.0)); + aim->addStatement(checkPointer(new BAPFlowCIf( + checkPointer(new BAPConObjectInFront(m_target[bot->getBotId()], 0.0f, 0.1f)), fire, 0, m_id, true, false))); + } + treat->addStatement(checkPointer(new BAPFlowCWhile(checkPointer(new BAPConTrue()), aim, true, m_id))); + + WeaponInfo* const other = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(2)); // 0x2923C1 + if (other) + newKeyTrigger(other, &WeaponInfo::getWeaponActivate, m_id, false); // built, never added + + // 0x292513: confirm the requester's radio request. + const int requester = m_targetPlayerId[bot->getBotId()]; + if (requester >= 0 && requestMessageType(kit) != 0) + { + bool confirmed; + if (kit == 4) + { + // 0x293670 + confirmed = communication->confirmReceivedMessage(static_cast(4), requester); + Bot* const requesterBot = IBotManager::instance->getBotFromPlayerId(requester); + if (requesterBot) + static_cast(requesterBot)->setIsEngineerTarget(true); + } + else + { + confirmed = communication->confirmReceivedMessage(static_cast(requestMessageType(kit)), + requester); + } + if (confirmed) + serial->addStatement(checkPointer(new BAPASendRadioMessage(static_cast(6), + static_cast(6), 2, 1.0f, + m_id, -1))); + } + + // 0x292558 + BAPFlowCIf* approach; + if (targetIsSoldier || toEntry) + { + approach = checkPointer(new BAPFlowCIf(inReach, treat, 0, m_id, true, false)); + } + else + { + // 0x292D47: a vehicle reachable by pathfinding: half a second of closing in first. + BAPCombinerSerial* const sequence = checkPointer(new BAPCombinerSerial(m_id, 1)); + BAPAMoveToObjectFinding* const close = checkPointer(new BAPAMoveToObjectFinding( + bot, m_target[bot->getBotId()], 0.0f, mobile->getMaxSpeed(), mobile->getMaxSpeed(), 0, + controlInfo->getDriveControls(), m_id, 0, 0.0f, -1)); + BAPConTime* const time = checkPointer(new BAPConTime(0.5, false, false, false)); + sequence->addStatement(checkPointer(new BAPFlowCWhile(checkPointer(new BAPConNot(time)), close, false, m_id))); + sequence->addStatement(treat); + approach = checkPointer(new BAPFlowCIf(inReach, sequence, 0, m_id, true, false)); + } + parallel->addStatement(approach); + parallel->addStatement(checkPointer(new BAPAMergeSoldierInputs(m_id))); + BAPFlowCWhile* const loop = checkPointer(new BAPFlowCWhile(treating, parallel, false, m_id)); + serial->addStatement(checkPointer(new BAPAResetControls(true, true, true, m_id))); + serial->addStatement(loop); + targetVacant = false; + if (targetUnit) + targetVacant = !targetUnit->isOccupied(); + } + + // 0x292732: the squad request this bot now answers. + if (bot->getPlayer()->getSpawnKit() == 5) + { + const unsigned int handle = target->getHandle(); + bot->getSquadMember()->setCurrentRequestAction(1, handle); + } + else if (bot->getPlayer()->getSpawnKit() == 4) + { + bot->setRepairTarget(m_target[bot->getBotId()]); + const unsigned int handle = target->getHandle(); + bot->getSquadMember()->setCurrentRequestAction(2, handle); + } + else if (bot->getPlayer()->getSpawnKit() == 3) + { + const unsigned int handle = target->getHandle(); + bot->getSquadMember()->setCurrentRequestAction(4, handle); + } + + // 0x29278F + BAPIWFire* const root = checkPointer( + new BAPIWFire(bot, m_target[bot->getBotId()], targetVacant, false, weaponIndex, -1, serial, m_id)); + root->setParent(this); // +0x04 (BotScript::mpOwner) + static_cast(bot)->resetAllControls(true, true, true); + return root; +} + +// ELF 0x291320: m_initiated (+0x04) [botId] = true, then the three per-bot slots, each indexed by +// a fresh Bot::getBotId (+0xE8). +void BBPMedicAssist::init(unsigned int target, int weaponIndex, int targetPlayerId, Bot* bot) +{ + m_initiated[bot->getBotId()] = true; + m_target[bot->getBotId()] = target; + m_weaponIndex[bot->getBotId()] = weaponIndex; + m_targetPlayerId[bot->getBotId()] = targetPlayerId; +} + +// ELF 0x291390: instruction for instruction BBMedicAssist::isHumanInTarget (0x216980) - the +// primary object of `info` for `side`, then its secondary objects; true at the first unit occupied +// by a known non-AI player (IAIPlayerFactory +0x20 getPlayerFromId, IAIPlayer +0x88 getIsAIPlayer). +bool BBPMedicAssist::humanPlayerInTarget(Information* info, int side) +{ + bool human = false; + if (info) + { + Information* primary = informationManager->getInformation(info->getPrimaryObject(side)); + if (primary) + { + IPIUnit* unit = primary->getUnit(); + if (unit && unit->isOccupied()) + { + IAIPlayer* player = static_cast(CommonSingletonServer::m_iaiPlayerFactory)->getPlayerFromId(unit->getOccupyingPlayerId(side)); + if (player && !player->getIsAIPlayer()) + return true; + } + int iterator; + for (Information* secondary = + informationManager->getInformation(primary->getFirstSecondaryObject(iterator, side)); + secondary; + secondary = informationManager->getInformation(primary->getSecondaryObject(iterator, side))) + { + unit = secondary->getUnit(); + if (unit && unit->isOccupied()) + { + IAIPlayer* player = static_cast(CommonSingletonServer::m_iaiPlayerFactory)->getPlayerFromId(unit->getOccupyingPlayerId(side)); + if (player && !player->getIsAIPlayer()) + { + human = true; + break; + } + } + } + } + } + return human; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPMedicAssist.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPMedicAssist.h new file mode 100644 index 000000000..7b956dc9c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPMedicAssist.h @@ -0,0 +1,45 @@ +// Medic/support assist pattern: BBMedicAssist hands it the chosen target, the weapon index to use +// and the target's player per bot (init); createPlan builds the plan from them. Recovered from +// libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see docs/macos-ai-behaviour-plan.md. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPMEDICASSIST_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPMEDICASSIST_H + +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; +class Information; + +// ELF: vtable 0x4BC3C0 (6 words), operator new 0x18, package F-infantry. +class BBPMedicAssist : public BBPPattern +{ +public: + explicit BBPMedicAssist(int); // 0x290DE0 + virtual ~BBPMedicAssist(); // 0x291220 + + virtual BotScript* createPlan(Bot*); // 0x291550, slot +0x08; from the base declaration + + // ELF void: no result register is set (0x291320..0x291389). + void init(unsigned int, int, int, Bot*); // 0x291320 + // ELF bool (movzbl of a 0/1 local); the same body as BBMedicAssist::isHumanInTarget. + bool humanPlayerInTarget(Information*, int); // 0x291390 + +private: + /* +0x08 */ int m_id; // pattern id: createPlan tags every statement with it + // Per bot (new[IAISettings::getMaxNBots], each -1), written by init. + /* +0x0C */ unsigned int* m_target; // information handle of the unit to treat + /* +0x10 */ int* m_weaponIndex; // index into the bot's IPIArmament::getWeapons + /* +0x14 */ int* m_targetPlayerId; // occupying player of the target, -1 if none +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPMEDICASSIST_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPPattern.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPPattern.cpp new file mode 100644 index 000000000..e346a5642 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPPattern.cpp @@ -0,0 +1,53 @@ +// BBPPattern: recovered by package A-core from libaidll.so (TU BBPPattern.cpp, 0x296ED0..0x297380; the +// three weak members at 0x2298A0). Every body carries its ELF address. + +// static init: ELF 0x2972F0 (__tcf_0 0x297350, _GLOBAL__I 0x297380): 's Init object only. +#include + +#include "BBPPattern.h" + +#include "../AIBot/BotMain.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x296FD0 (C2; C1 0x297160). The flag array has one entry per possible bot. +BBPPattern::BBPPattern() +{ + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_initiated = checkPointer(new bool[count]); + for (int i = 0; i < count; ++i) + m_initiated[i] = false; +} + +// ELF 0x296ED0 (D2; D1 0x296F20, D0 0x296F70). +BBPPattern::~BBPPattern() +{ + delete[] m_initiated; +} + +// ELF 0x2298D0 (weak). +bool BBPPattern::isInitiated(Bot* bot) +{ + return m_initiated[bot->getBotId()]; +} + +// ELF 0x2298A0 (weak). +void BBPPattern::unInit(Bot* bot) +{ + m_initiated[bot->getBotId()] = false; +} + +// ELF 0x229900 (weak). +void BBPPattern::forceInitiated(Bot* bot) +{ + m_initiated[bot->getBotId()] = true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPPattern.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPPattern.h new file mode 100644 index 000000000..f0558e106 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPPattern.h @@ -0,0 +1,41 @@ +// Behaviour-pattern base: the per-bot "initiated" flags every pattern keeps. Recovered by package +// A-core (docs/macos-ai-behaviour-plan.md) from libaidll.so; the virtual order is checked by +// tools/macos/ai_behaviour_vtables.py. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPPATTERN_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPPATTERN_H + +#include "PlanGenerator.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// Behaviour-pattern base. Vtable 0x4BC400. +// ELF: vtable 0x4BC400 (6 words), package A-core. +class BBPPattern : public PlanGenerator +{ +public: + BBPPattern(); // 0x297160 + virtual ~BBPPattern(); // 0x296F20 + + // The three are weak in the image (inline in the header, emitted beside BBPAvoidCollision2d); + // defined out of line in BBPPattern.cpp so this header needs no Bot definition. [CHOSEN] + virtual bool isInitiated(Bot*); // 0x2298D0, slot +0x0C; from the base declaration + virtual void unInit(Bot*); // 0x2298A0, slot +0x10; from the base declaration + virtual void forceInitiated(Bot*); // 0x229900, slot +0x14; from the base declaration + +protected: + // BBPPattern() 0x296FD0: checkPointer(new bool[IAISettings::getMaxNBots()]), all false; indexed by + // Bot::getBotId(). Freed by the destructor 0x296ED0. + /* +0x04 */ bool* m_initiated; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPPATTERN_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRandom.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRandom.cpp new file mode 100644 index 000000000..d2c1d08dd --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRandom.cpp @@ -0,0 +1,143 @@ +// Random pattern (BBRandom: the grenade-warning reaction). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32). + +// static init: ELF 0x2989B0 (__tcf_0 0x298A10, _GLOBAL__I 0x298A40): 's Init object only. +#include + +#include "BBPRandom.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPASoldierPose.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPFlowCWhile.h" +#include "../AIBotActionPlan/BAPIWIdle.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../../Core/Random.h" +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { +// [CHOSEN, not recovered] Local packaging of Random's inlined arithmetic at ELF 0x2979A4..0x297B64. +std::uint32_t randomStage(std::uint32_t seed, int factor) +{ + const std::int32_t low = static_cast((seed & 0xffffu) * factor); + const std::int32_t high = (static_cast(seed) >> 16) * factor + (low >> 16); + const std::uint32_t combined = (static_cast(low) & 0xffffu) + + ((static_cast(high) & 0x7fffu) << 16) + + static_cast(high >> 15); + const std::uint32_t reduced = combined - 0x7fffffffu; + return static_cast(reduced) < 0 ? combined : reduced; +} + +float randomDraw() +{ + Rand.m_seed = randomStage(randomStage(Rand.m_seed, 24112), 26143); + const std::int32_t raw = (static_cast(Rand.m_seed) >> 7) | 1; + return static_cast(raw + 1) * 5.9604644775390625e-8f; +} +} + +// ELF 0x297400 (C2) / 0x297580 (C1): BBPPattern(), +0x08 = id, +0x0C = checkPointer(new[getMaxNBots]). +BBPRandom::BBPRandom(int id) + : BBPPattern() +{ + m_id = id; + m_perBot = checkPointer(new unsigned int[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); +} + +// ELF 0x297700 (D2) / 0x297750 (D1) / 0x2977A0 (D0): delete[] +0x0C when set, then ~BBPPattern. +BBPRandom::~BBPRandom() +{ + if (m_perBot) + delete[] m_perBot; +} + +// ELF 0x297840 +BotScript* BBPRandom::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) + { + BotScript* previous = bot->getPlan(); + if (previous) + delete previous; + bot->setPlan(0); + } + return 0; + } + bot->getSquadMember()->clearRequestAction(); + Information* self = informationManager->getInformation(bot->getCurrentEquipment()); + if (!bot->hasPlan()) + { + if (bot->getPlan()) + { + BotScript* previous = bot->getPlan(); + if (previous) + delete previous; + bot->setPlan(0); + } + } + else if (static_cast(bot->getPlan())->getPatternId() == m_id) + return bot->getPlan(); + + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getSquadMember()->clearRequestAction(); + // shipped defect: an active plan with a different pattern id is not deleted here. + bot->getScriptContext()->clear(); + BAPCombinerParallel* parallel = checkPointer(new BAPCombinerParallel(m_id, -1, false)); + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + const float first = randomDraw(); + const float second = randomDraw(); + const float third = randomDraw(); + m_initTime = now; + const SoldierPose pose = first > second ? SPCrouching : SPLying; + parallel->addStatement(checkPointer(new BAPASoldierPose(pose, checkPointer(new BAPConTrue()), m_id, false))); + Information* weaponOwner = informationManager->getInformation(bot->getCurrentEquipment()); + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(weaponOwner->getArmament()->getWeapon(1)); + if (weapon && third > 0.7f) + { + const unsigned int mask = 1u << (static_cast(weapon->getWeaponFire()) & 31u); + const unsigned long long controls = static_cast(static_cast(static_cast(mask))); + BAPConFalse* stop = checkPointer(new BAPConFalse()); + BAPConTrue* start = checkPointer(new BAPConTrue()); + const io::PlayerInputMap input = static_cast(weapon->getWeaponFire()); + parallel->addStatement(checkPointer(new BAPATrigger(input, start, stop, controls, m_id, 0.0, true))); + } + BAPFlowCWhile* loop = checkPointer(new BAPFlowCWhile(checkPointer(new BAPConTrue()), parallel, true, m_id)); + BAPIWIdle* wrapper = checkPointer(new BAPIWIdle(self->getPosition(), loop, m_id, bot)); + wrapper->mpOwner = this; + return wrapper; +} + +// ELF 0x2977F0: m_initiated[bot->getBotId()] = true; +0x14 = IBFTimer slot +0x08 (getGameTime). +void BBPRandom::init(Bot* bot) +{ + m_initiated[bot->getBotId()] = true; + m_initTime = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRandom.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRandom.h new file mode 100644 index 000000000..29b231608 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRandom.h @@ -0,0 +1,38 @@ +// Random grenade-warning reaction, recovered from libaidll.so. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPRANDOM_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPRANDOM_H + +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BC4A0 (6 words), operator new 0x1C, package F-infantry. +class BBPRandom : public BBPPattern +{ +public: + explicit BBPRandom(int); // 0x297580 + virtual ~BBPRandom(); // 0x297750 + + virtual BotScript* createPlan(Bot*); // 0x297840, slot +0x08; from the base declaration + + void init(Bot*); // 0x2977F0; void (fstpl is the last instruction before the epilogue) + +private: + /* +0x08 */ int m_id; // constructor argument [INFERRED] name + /* +0x0C */ unsigned int* m_perBot; // new[getMaxNBots], checkPointer'd [UNRESOLVED] use + /* +0x10 */ unsigned char m_unwritten10[4]; // not written by the constructor or init + /* +0x14 */ double m_initTime; // init: IBFTimer::getGameTime [INFERRED] name +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPRANDOM_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRevive.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRevive.cpp new file mode 100644 index 000000000..9639cc768 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRevive.cpp @@ -0,0 +1,215 @@ +// Revive pattern: init keeps the man-down soldier and the revive weapon per bot; createPlan builds +// the revive script. Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body +// carries its ELF address. +// +// static init: ELF 0x29B200 (__tcf_0 0x29B260, _GLOBAL__I 0x29B290): the guard object only. + +#include "BBPRevive.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPALookAtObject.h" +#include "../AIBotActionPlan/BAPAMergeSoldierInputs.h" +#include "../AIBotActionPlan/BAPAMoveToObjectFinding.h" +#include "../AIBotActionPlan/BAPAOverrideSensingAgent.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPARevive.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConAnd.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConObjectDistance.h" +#include "../AIBotActionPlan/BAPConObjectExists.h" +#include "../AIBotActionPlan/BAPConObjectManDown.h" +#include "../AIBotActionPlan/BAPConObjectMoved.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPFlowCIf.h" +#include "../AIBotActionPlan/BAPFlowCWhile.h" +#include "../AIBotActionPlan/BAPIWFire.h" +#include "../AIBotActionPlan/BAPInfoWrapper.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "WeaponChoice.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x298A60 (C2) / 0x298CF0 (C1): BBPPattern(), +0x08 = the argument, +0x0C and +0x10 = +// checkPointer(new[getMaxNBots]) of 4 bytes each (not initialised). +BBPRevive::BBPRevive(int id) + : BBPPattern() +{ + m_id = id; + m_target = checkPointer(new unsigned int[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); + m_weapon = checkPointer(new int[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); +} + +// ELF 0x298F80 (D2) / 0x298FE0 (D1) / 0x299040 (D0): delete[] +0x0C, +0x10 when set, then ~BBPPattern. +BBPRevive::~BBPRevive() +{ + if (m_target) + delete[] m_target; + if (m_weapon) + delete[] m_weapon; +} + +namespace { + +void dropPlan(Bot* bot) +{ + delete bot->getPlan(); + bot->setPlan(0); +} + +// The inlined Vec3 subtraction followed by the x87 length (fsqrt, sqrtf on NaN). +float distance(const Vec3& a, const Vec3& b) +{ + const float dx = b.x - a.x; + const float dy = b.y - a.y; + const float dz = b.z - a.z; + return std::sqrt(dx * dx + dy * dy + dz * dz); +} + +} // namespace + +// ELF 0x299110 (listing; Ghidra cross-check). Revives the man-down soldier m_target[bot] with the +// shock paddles: +// serial { reset controls (true, false, true) when the weapon's activate key is 64, else +// trigger(activate key), +// while (target exists && man down) parallel { reset controls, override sensing, +// look at target, if (within 1.6 m) revive else move to the target with pathfinding +// (re-planned when within 10 m and the target moved 0.2 m), merge soldier inputs } } +// under BAPIWFire(bot, target, true, false, weapon, -1, ..). The current plan is kept when it is +// this pattern's BAPIWFire on the same target. The medic kit answers the squad request (action 1 +// with the target handle). Returns 0 without equipment, unit, mobile, target or a type-3 weapon +// (then the equipment's object is updated). +BotScript* BBPRevive::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + // 0x29B182 + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) + dropPlan(bot); + return 0; + } + + if (bot->hasPlan() && static_cast(bot->getPlan())->getPatternId() == m_id + && static_cast(bot->getPlan())->getId() == BAPSTInfoWrapper + && static_cast(bot->getPlan())->getInfoType() == 0 + && static_cast(bot->getPlan())->getTarget() == m_target[bot->getBotId()]) + return bot->getPlan(); // 0x29B11C + + bot->getSquadMember()->clearRequestAction(); + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + if (bot->getPlan()) + dropPlan(bot); + bot->getScriptContext()->clear(); + + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + Information* const target = informationManager->getInformation(m_target[bot->getBotId()]); + if (!equipment || !equipment->getUnit()) + return 0; + IPIMobile* const mobile = equipment->getMobile(); + if (!mobile || !target) + return 0; + IPIArmament* const armament = equipment->getArmament(); + IPIControlInfo* const controlInfo = equipment->getControlInfo(); + + const int strengthType = target->getPhysical()->getStrengthType(); + const float range = distance(equipment->getPosition(), target->getPosition()); + const int weaponIndex = choseWeapon(armament->getWeapons(), m_weapon[bot->getBotId()], range, strengthType, false, + false, true, false); + if (weaponIndex == -1) + { + equipment->getAIObject()->update(); // 0x29B08D + return 0; + } + bot->setReviveTarget(m_target[bot->getBotId()]); + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(weaponIndex)); + + BAPCombinerSerial* const serial = checkPointer(new BAPCombinerSerial(m_id, -1)); + BAPStatement* select; + if (weapon->getWeaponActivate() == 64) + select = checkPointer(new BAPAResetControls(true, false, true, m_id)); // 0x29AE90 + else + select = checkPointer(new BAPATrigger(static_cast(weapon->getWeaponActivate()), + checkPointer(new BAPConTrue()), checkPointer(new BAPConFalse()), + static_cast(1u << weapon->getWeaponActivate()), m_id, 0.0, false)); + serial->addStatement(select); + + // 0x2995B9: the revive distance, stored as a float local and scaled at run time. + const float reviveDistance = 0.4f; + BAPConObjectDistance* const close = checkPointer( + new BAPConObjectDistance(m_target[bot->getBotId()], reviveDistance * 4.0f, false, true, false)); + BAPConAnd* const replan = checkPointer(new BAPConAnd()); + replan->addCondition(checkPointer(new BAPConObjectDistance(m_target[bot->getBotId()], 10.0f, true, true, false))); + replan->addCondition(checkPointer(new BAPConObjectMoved(m_target[bot->getBotId()], reviveDistance * 0.5f))); + BAPAMoveToObjectFinding* const move = checkPointer(new BAPAMoveToObjectFinding( + bot, m_target[bot->getBotId()], 0.0f, mobile->getMaxSpeed(), mobile->getMaxSpeed(), 0, + controlInfo->getDriveControls(), m_id, replan, 0.0f, -1)); + BAPFlowCIf* const revive = checkPointer(new BAPFlowCIf(close, checkPointer(new BAPARevive(m_id)), move, m_id, true, false)); + + BAPConAnd* const down = checkPointer(new BAPConAnd()); + BAPConObjectExists* const exists = checkPointer(new BAPConObjectExists(m_target[bot->getBotId()])); + BAPConObjectManDown* const manDown = checkPointer(new BAPConObjectManDown(m_target[bot->getBotId()])); + down->addCondition(exists); + down->addCondition(manDown); + + BAPCombinerParallel* const parallel = checkPointer(new BAPCombinerParallel(m_id, -1, false)); + parallel->addStatement(checkPointer(new BAPAResetControls(true, true, true, m_id))); + parallel->addStatement(checkPointer(new BAPAOverrideSensingAgent())); + parallel->addStatement(checkPointer(new BAPALookAtObject(bot, m_target[bot->getBotId()], 0.0f, + checkPointer(new BAPConFalse()), + equipment->getControlInfo()->getLookControls(), m_id, 0, + 0.0f))); + parallel->addStatement(revive); + parallel->addStatement(checkPointer(new BAPAMergeSoldierInputs(m_id))); + serial->addStatement(checkPointer(new BAPFlowCWhile(down, parallel, false, m_id))); + + if (bot->getPlayer()->getSpawnKit() == 5) + { + // 0x299E4D + const unsigned int handle = m_target[bot->getBotId()]; + bot->getSquadMember()->setCurrentRequestAction(1, handle); + } + + BAPIWFire* const root = checkPointer( + new BAPIWFire(bot, m_target[bot->getBotId()], true, false, weaponIndex, -1, serial, m_id)); + root->setParent(this); // +0x04 (BotScript::mpOwner) + static_cast(bot)->resetAllControls(true, true, true); + return root; +} + +// ELF 0x2990B0: m_initiated[id] = true; +0x0C[id] = target; +0x10[id] = weapon. +void BBPRevive::init(unsigned int target, int weapon, Bot* bot) +{ + m_initiated[bot->getBotId()] = true; + m_target[bot->getBotId()] = target; + m_weapon[bot->getBotId()] = weapon; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRevive.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRevive.h new file mode 100644 index 000000000..5e7229208 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRevive.h @@ -0,0 +1,42 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPREVIVE_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPREVIVE_H + +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BC520 (6 words), operator new 0x14, package F-infantry. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BBPRevive : public BBPPattern +{ +public: + explicit BBPRevive(int); // 0x298CF0 + virtual ~BBPRevive(); // 0x298FE0 + + virtual BotScript* createPlan(Bot*); // 0x299110, slot +0x08; from the base declaration + + void init(unsigned int, int, Bot*); // 0x2990B0; void (no result register is set) + +private: + /* +0x08 */ int m_id; // constructor argument [INFERRED] name + /* +0x0C */ unsigned int* m_target; // per bot: init's handle (BBRevive's chosen man-down soldier) + /* +0x10 */ int* m_weapon; // per bot: init's weapon index (BBRevive's m_bestWeapon entry) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPREVIVE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam.cpp new file mode 100644 index 000000000..036d26d9c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam.cpp @@ -0,0 +1,39 @@ +// Shared roaming pattern state, recovered from libaidll.so (Linux 1.5, ia-32). + +// static init: ELF 0x29B4A0 (__tcf_0 0x29B500, _GLOBAL__I 0x29B530): 's Init object only. +#include + +#include "BBPRoam.h" + +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../../Math/Vec3.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x29B3A0 (C2), 0x29B420 (C1). +BBPRoam::BBPRoam() +{ + m_positions = new Vec3[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()](); +} + +// ELF 0x29B2B0 (D2), 0x29B300 (D1), 0x29B350 (D0). +BBPRoam::~BBPRoam() +{ + if (m_positions) + delete[] m_positions; +} + +// ELF 0x29B550 +int BBPRoam::getRoamType() +{ + return 0; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam.h new file mode 100644 index 000000000..f057bd5f8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam.h @@ -0,0 +1,34 @@ +// Shared roaming pattern state, recovered from libaidll.so (Linux 1.5, ia-32). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPROAM_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPROAM_H + +#include "BBPPattern.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { + +namespace ai { + + +// ELF: vtable 0x4BC560 (7 words), package H-deferred. +class BBPRoam : public BBPPattern +{ +public: + BBPRoam(); // 0x29B420 + virtual ~BBPRoam(); // 0x29B300 + + virtual int getRoamType(); // 0x29B550, slot +0x18; [INFERRED] ELF int + +protected: + // [INFERRED] member names from the constructors and concrete init methods. + /* +0x08 */ int m_patternId; // set by concrete pattern constructors + /* +0x0C */ Vec3* m_positions; // per-bot positions, initially zero +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPROAM_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam2d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam2d.cpp new file mode 100644 index 000000000..ee420a012 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam2d.cpp @@ -0,0 +1,80 @@ +// Ground roaming pattern, recovered from libaidll.so (Linux 1.5, ia-32). + +// static init: ELF 0x29B9A0 (__tcf_0 0x29BA00, _GLOBAL__I 0x29BA30): 's Init object only. +#include + +#include "BBPRoam2d.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPAMoveToFinding.h" +#include "../AIBotActionPlan/BAPConPosition.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../../../../Math/Vec3.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x29B560 (C2), 0x29B5A0 (C1). +BBPRoam2d::BBPRoam2d(int patternId) +{ + m_patternId = patternId; +} + +// ELF 0x29B5E0 (D2), 0x29B620 (D1), 0x29B660 (D0). +BBPRoam2d::~BBPRoam2d() +{ +} + +// ELF 0x29B700 +BotScript* BBPRoam2d::createPlan(Bot* bot) +{ + const bool initiated = m_initiated[bot->getBotId()]; + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (!initiated) + return 0; + + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + if (bot->getPlan()) { + delete bot->getPlan(); + bot->setPlan(0); + } + bot->getSquadMember()->clearRequestAction(); + IPIMobile* const mobile = self->getMobile(); + const unsigned long long controls = self->getControlInfo()->getDriveControls(); + const float radius = self->getPhysical()->getRadius() * 4.0f; + const float speed = mobile->getMaxSpeed(); + BAPConPosition* const arrived = new BAPConPosition(m_positions[bot->getBotId()], radius); + BAPAMoveToFinding* const plan = new BAPAMoveToFinding(bot, m_positions[bot->getBotId()], speed, speed, + arrived, controls, m_patternId, 0.0f, 0.0f); + plan->mpOwner = this; + return plan; +} + +// ELF 0x29BA50 +int BBPRoam2d::getRoamType() +{ + return 1; +} + +// ELF 0x29B6A0 +void BBPRoam2d::init(Bot* bot, const Vec3& position) +{ + m_initiated[bot->getBotId()] = true; + m_positions[bot->getBotId()] = position; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam2d.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam2d.h new file mode 100644 index 000000000..99b8f20fc --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam2d.h @@ -0,0 +1,34 @@ +// Ground roaming pattern, recovered from libaidll.so (Linux 1.5, ia-32). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPROAM2D_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPROAM2D_H + +#include "../../../../Math/Vec3.h" +#include "BBPRoam.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BC5E0 (7 words), package H-deferred. +class BBPRoam2d : public BBPRoam +{ +public: + explicit BBPRoam2d(int); // 0x29B5A0 + virtual ~BBPRoam2d(); // 0x29B620 + + virtual BotScript* createPlan(Bot*); // 0x29B700, slot +0x08; from the base declaration + virtual int getRoamType(); // 0x29BA50, slot +0x18; from the base declaration + + void init(Bot*, const Vec3&); // 0x29B6A0; [INFERRED] ELF void +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPROAM2D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam3d.cpp new file mode 100644 index 000000000..04a250b5e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam3d.cpp @@ -0,0 +1,110 @@ +// Airborne roaming recovered from libaidll.so. + +// static init: ELF 0x29C090 (__tcf_0 0x29C0F0, _GLOBAL__I 0x29C120): 's Init object only. +#include + +#include "BBPRoam3d.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPAMoveTo3dObject.h" +#include "../AIBotActionPlan/BAPConObjectVisible.h" +#include "../AIBotActionPlan/BAPIWRoam.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x29BAC0 (C1; C2 0x29BA60) +BBPRoam3d::BBPRoam3d(int patternId) +{ + m_patternId = patternId; + m_objects = new unsigned int[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]; +} + +// ELF 0x29BB70 (D1; D2 0x29BB20, D0 0x29BBC0) +BBPRoam3d::~BBPRoam3d() +{ + if (m_objects) + delete[] m_objects; +} + +// ELF 0x29BC60 +BotScript* BBPRoam3d::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) + { + BotScript* previous = bot->getPlan(); + if (previous) + delete previous; + bot->setPlan(0); + } + return 0; + } + Information* self = informationManager->getInformation(bot->getCurrentEquipment()); + if (bot->hasPlan() + && static_cast(bot->getPlan())->getPatternId() == m_patternId + && static_cast(bot->getPlan())->getId() == BAPSTInfoWrapper + && static_cast(bot->getPlan())->getInfoType() == 5) + { + const unsigned int previousObject = static_cast(bot->getPlan())->m_object; + if (previousObject == m_objects[bot->getBotId()]) + return bot->getPlan(); + } + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + // shipped defect: a replaced plan is not deleted or cleared here. + bot->getScriptContext()->clear(); + Information* target = informationManager->getInformation(m_objects[bot->getBotId()]); + if (!target) + return 0; + bot->getSquadMember()->clearRequestAction(); + IPIMobile* mobile = self->getMobile(); + const float ownRadius = self->getPhysical()->getRadius(); + float radius = 0.0f; + // shipped defect: the Boolean mobile flag is added to our radius only for this zero test. + if (ownRadius + static_cast(target->getMobile() != 0) != 0.0f) + radius = target->getPhysical()->getRadius(); + radius += radius; + BAPConObjectVisible* visible = new BAPConObjectVisible(m_objects[bot->getBotId()]); + const unsigned long long driveControls = self->getControlInfo()->getDriveControls(); + const float arriveSpeed = mobile->getMaxSpeed() * 0.5f; + const float speed = mobile->getMaxSpeed(); + const unsigned int object = m_objects[bot->getBotId()]; + BAPAMoveTo3dObject* move = new BAPAMoveTo3dObject(object, radius, speed, arriveSpeed, 50.0f, + visible, driveControls, m_patternId); + BAPIWRoam* wrapper = new BAPIWRoam(m_objects[bot->getBotId()], move, m_patternId); + wrapper->mpOwner = this; + return wrapper; +} + +// ELF 0x29C140 +int BBPRoam3d::getRoamType() +{ + return 2; +} + +// ELF 0x29BC10 +void BBPRoam3d::init(unsigned int object, Bot* bot) +{ + m_objects[bot->getBotId()] = object; + m_initiated[bot->getBotId()] = true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam3d.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam3d.h new file mode 100644 index 000000000..6b4ed3146 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam3d.h @@ -0,0 +1,36 @@ +// Airborne roaming toward a per-bot information handle. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPROAM3D_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPROAM3D_H + +#include "BBPRoam.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BC660 (7 words), package H-deferred. +class BBPRoam3d : public BBPRoam +{ +public: + explicit BBPRoam3d(int); // 0x29BAC0 + virtual ~BBPRoam3d(); // 0x29BB70 + + virtual BotScript* createPlan(Bot*); // 0x29BC60, slot +0x08; from the base declaration + virtual int getRoamType(); // 0x29C140, slot +0x18; from the base declaration + + void init(unsigned int, Bot*); // 0x29BC10; [INFERRED] ELF void + +private: + /* +0x10 */ unsigned int* m_objects; // [INFERRED] name; uninitialized per-bot handles +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPROAM3D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRunOverSoldier.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRunOverSoldier.cpp new file mode 100644 index 000000000..df478d229 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRunOverSoldier.cpp @@ -0,0 +1,107 @@ +// Recovered from libaidll.so 1.5.3153 (ia-32); objdump listings with Ghidra cross-checks, ELF +// addresses on every body. Static init: ELF 0x29CAE0 (the guard object only). + +#include "BBPRunOverSoldier.h" + +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPARunOverObject.h" +#include "../AIBotActionPlan/BAPIWFire.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +// static init: ELF 0x29CAE0 (__tcf_0 0x29CB40, _GLOBAL__I 0x29CB70): 's Init object only. + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x29C2D0: BBPPattern(), the vtable store (GOT -0x7CC + 8), the argument at +0x08, then +// `new unsigned int[getMaxNBots()]` (not initialised) through the inlined checkPointer into +0x0C +// (operator new 0x10). +BBPRunOverSoldier::BBPRunOverSoldier(int id) + : m_patternId(id) +{ + m_target = checkPointer(new unsigned int[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); +} + +// ELF 0x29C450 (D2) / 0x29C4A0 (D1) / 0x29C4F0 (D0): delete[] +0x0C when set, then ~BBPPattern. +BBPRunOverSoldier::~BBPRunOverSoldier() +{ + if (m_target) + delete[] m_target; +} + +namespace { + +// The image's "drop the plan" sequence (0x29C9F6): the plan's deleting destructor, then +// Bot +0x64 setPlan(0). +void dropPlan(Bot* bot) +{ + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } +} + +} // namespace + +// ELF 0x29C580 (listing; Ghidra cross-check). Without init for this bot: clear the debugger and +// the script context, drop the plan, no plan. Otherwise the current plan is kept while it is this +// pattern's fire wrapper (getId 15, info type 0) on the same target; else it is dropped and, when +// the bot's equipment has a unit and a mobile part, the plan is BAPIWFire(bot, target, true, +// false, 4, -1, BAPARunOverObject(target, drive controls, id), id) owned by this pattern, with +// every control reset. The equipment's control part is not null-tested (as shipped). +BotScript* BBPRunOverSoldier::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + dropPlan(bot); + return 0; + } + + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + bot->getCurrentEquipment(); // 0x29C60D, result unused + if (bot->hasPlan() && static_cast(bot->getPlan())->getPatternId() == m_patternId + && static_cast(bot->getPlan())->getId() == BAPSTInfoWrapper + && static_cast(bot->getPlan())->getInfoType() == 0 + && static_cast(bot->getPlan())->getTarget() == m_target[bot->getBotId()]) + return bot->getPlan(); + dropPlan(bot); + + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + if (!equipment || !equipment->getUnit() || !equipment->getMobile()) + return 0; + IPIControlInfo* const controlInfo = equipment->getControlInfo(); + BAPARunOverObject* const runOver = checkPointer( + new BAPARunOverObject(m_target[bot->getBotId()], controlInfo->getDriveControls(), m_patternId)); + BAPIWFire* const root = checkPointer( + new BAPIWFire(bot, m_target[bot->getBotId()], true, false, 4, -1, runOver, m_patternId)); + root->setParent(this); // +0x04 (BotScript::mpOwner) + static_cast(bot)->resetAllControls(true, true, true); + return root; +} + +// ELF 0x29C540: marks the bot initiated and stores its target. +void BBPRunOverSoldier::init(Bot* bot, unsigned int target) +{ + const unsigned int id = bot->getBotId(); + m_initiated[id] = true; + m_target[id] = target; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRunOverSoldier.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRunOverSoldier.h new file mode 100644 index 000000000..84757b248 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRunOverSoldier.h @@ -0,0 +1,37 @@ +// Recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every declaration. +// Vehicle pattern: run over a soldier with a car (BAPARunOverObject under a fire wrapper). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPRUNOVERSOLDIER_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPRUNOVERSOLDIER_H + +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BC6E0 (6 words), operator new 0x10, package G-vehicles. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BBPRunOverSoldier : public BBPPattern +{ +public: + explicit BBPRunOverSoldier(int); // 0x29C2D0 + virtual ~BBPRunOverSoldier(); // 0x29C4A0 + + virtual BotScript* createPlan(Bot*); // 0x29C580, slot +0x08; from the base declaration + + void init(Bot*, unsigned int target); // 0x29C540; ELF void (no eax write) + + /* +0x08 */ int m_patternId; // the constructor argument + /* +0x0C */ unsigned int* m_target; // per bot: init's handle (init also sets m_initiated) [INFERRED] name +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPRUNOVERSOLDIER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPSuicide.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPSuicide.cpp new file mode 100644 index 000000000..ddd66df76 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPSuicide.cpp @@ -0,0 +1,82 @@ +// Suicide input pattern, recovered from libaidll.so (Linux 1.5, ia-32). + +// static init: ELF 0x29D240 (__tcf_0 0x29D2A0, _GLOBAL__I 0x29D2D0): 's Init object only. +#include + +#include "BBPSuicide.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../../../../Math/Vec3.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x29CB90 (C2), 0x29CBD0 (C1). +BBPSuicide::BBPSuicide(int patternId) + : BBPPattern(), m_patternId(patternId) +{ +} + +// ELF 0x29CC10 (D2), 0x29CC50 (D1), 0x29CC90 (D0). +BBPSuicide::~BBPSuicide() +{ +} + +// ELF 0x29CD00 +BotScript* BBPSuicide::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) { + delete bot->getPlan(); + bot->setPlan(0); + } + return 0; + } + + bot->getSquadMember()->clearRequestAction(); + bot->getCurrentEquipment(); + if (!bot->hasPlan()) { + if (bot->getPlan()) { + delete bot->getPlan(); + bot->setPlan(0); + } + } else if (static_cast(bot->getPlan())->getPatternId() == m_patternId) { + return bot->getPlan(); + } + // shipped defect: a valid plan of another pattern is not deleted here. + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getSquadMember()->clearRequestAction(); + bot->getScriptContext()->clear(); + + BAPConFalse* const stop = checkPointer(new BAPConFalse()); + BAPConTrue* const start = checkPointer(new BAPConTrue()); + // shipped defect: the signed input-31 mask is widened with every upper bit set. + BAPATrigger* const plan = checkPointer(new BAPATrigger(static_cast(31), start, stop, + 0xFFFFFFFF80000000ULL, m_patternId, 0.0, false)); + plan->mpOwner = this; + return plan; +} + +// ELF 0x29CCD0 +void BBPSuicide::init(Bot* bot) +{ + m_initiated[bot->getBotId()] = true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPSuicide.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPSuicide.h new file mode 100644 index 000000000..e1f58c2fa --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPSuicide.h @@ -0,0 +1,36 @@ +// Suicide input pattern, recovered from libaidll.so (Linux 1.5, ia-32). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPSUICIDE_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPSUICIDE_H + +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BC760 (6 words), operator new 0xC, package H-deferred. +class BBPSuicide : public BBPPattern +{ +public: + explicit BBPSuicide(int); // 0x29CBD0 + virtual ~BBPSuicide(); // 0x29CC50 + + virtual BotScript* createPlan(Bot*); // 0x29CD00, slot +0x08; from the base declaration + + void init(Bot*); // 0x29CCD0; [INFERRED] ELF void + +private: + // [INFERRED] member name from the constructor and generated trigger. + /* +0x08 */ int m_patternId; // constructor argument carried by the trigger +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPSUICIDE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover.cpp new file mode 100644 index 000000000..c4aa8958e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover.cpp @@ -0,0 +1,252 @@ +// Cover-plan construction recovered from libaidll.so. + +// static init: ELF 0x29FC30 (__tcf_0 0x29FC90, _GLOBAL__I 0x29FCC0): 's Init object only. +#include + +#include "BBPTakeCover.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPALookAtObject.h" +#include "../AIBotActionPlan/BAPALookInDir.h" +#include "../AIBotActionPlan/BAPAMoveToFinding.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConAnd.h" +#include "../AIBotActionPlan/BAPConEndOfPath.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConPosition.h" +#include "../AIBotActionPlan/BAPIWTakeCover.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IAIPathfinding.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x29D910 (C1; C2 0x29D2F0) +BBPTakeCover::BBPTakeCover(int patternId) +{ + const unsigned int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_patternId = patternId; + m_coverObjects = checkPointer(new unsigned int[count]); + m_coverPositions = checkPointer(new Vec3[count]()); + m_threatPositions = checkPointer(new Vec3[count]()); + m_threatObjects = checkPointer(new unsigned int[count]); + m_useObjects = checkPointer(new bool[count]); +} + +// ELF 0x29DFD0 (D1; D2 0x29DF30, D0 0x29E070) +BBPTakeCover::~BBPTakeCover() +{ + if (m_coverObjects) + delete[] m_coverObjects; + if (m_coverPositions) + delete[] m_coverPositions; + if (m_threatPositions) + delete[] m_threatPositions; + // shipped defect: m_threatObjects is leaked, and m_useObjects is deleted twice. + if (m_useObjects) + delete[] m_useObjects; + if (m_useObjects) + delete[] m_useObjects; +} + +// ELF 0x29E330 +BotScript* BBPTakeCover::createPlan(Bot* bot) +{ + if (!isInitiated(bot)) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) + { + BotScript* previous = bot->getPlan(); + if (previous) + delete previous; + bot->setPlan(0); + } + return 0; + } + + const unsigned int coverObject = m_coverObjects[bot->getBotId()]; + const bool useObject = m_useObjects[bot->getBotId()]; + const Vec3 coverPosition = m_coverPositions[bot->getBotId()]; + Vec3 threatPosition = {}; + if (bot->hasPlan()) + { + BAPStatement* previous = static_cast(bot->getPlan()); + if (previous->getPatternId() == m_patternId && previous->getId() == BAPSTInfoWrapper) + { + BAPIWTakeCover* wrapper = static_cast(previous); + if (wrapper->getInfoType() == 7) + { + if (useObject) + { + if (wrapper->m_useObject) + { + Information* target = informationManager->getInformation(m_threatObjects[bot->getBotId()]); + Information* oldTarget = informationManager->getInformation(wrapper->m_object); + if (target && oldTarget && target->getAIObject() == oldTarget->getAIObject()) + { + const Vec3& position = oldTarget->getPosition(); + const Vec3 difference = {wrapper->m_position.x - position.x, + wrapper->m_position.y - position.y, + wrapper->m_position.z - position.z}; + if (difference.x * difference.x + difference.y * difference.y + + difference.z * difference.z < 1.0f) + return wrapper; + } + } + } + else if (!wrapper->m_useObject) + { + const Vec3& position = m_threatPositions[bot->getBotId()]; + const Vec3 difference = {wrapper->m_position.x - position.x, + wrapper->m_position.y - position.y, + wrapper->m_position.z - position.z}; + if (difference.x * difference.x + difference.y * difference.y + + difference.z * difference.z < 9.0f) + return wrapper; + } + } + } + } + if (bot->getPlan()) + { + BotScript* previous = bot->getPlan(); + if (previous) + delete previous; + bot->setPlan(0); + } + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + Information* self = informationManager->getInformation(bot->getCurrentEquipment()); + if (!self) + return 0; + IPIControlInfo* controls = self->getControlInfo(); + if (!controls) + return 0; + IPIMobile* mobile = self->getMobile(); + if (!mobile) + return 0; + Information* cover = informationManager->getInformation(coverObject); + if (!cover || !cover->getPhysical()) + return 0; + if (useObject) + { + Information* target = informationManager->getInformation(m_threatObjects[bot->getBotId()]); + if (!target) + return 0; + threatPosition = target->getPosition(); + } + else + threatPosition = m_threatPositions[bot->getBotId()]; + + bot->getSquadMember()->clearRequestAction(); + const Vec2 goal = {}; + Vec3 sensePosition = {}; + Vec3 senseNormal = {}; + Vec3 hint = {}; + static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->pickRandomSensePosition(sensePosition, senseNormal, hint, cover->getAIObject()); + Vec3 tracePosition = {}; + unsigned int polygon; + const int equipmentType = self->getUnit()->getEquipmentType(); + const int vehicleNumber = mobile->getVehicleNumber(); + IAIPathfinding::instance->trace(vehicleNumber, sensePosition, coverPosition, tracePosition, polygon, + equipmentType, -1, 0.0f, 0, 0); + const float maximumSpeed = mobile->getMaxSpeed(); + const float radius = maximumSpeed < 4.0f ? 4.0f : maximumSpeed * 0.5f; + BAPCombinerSerial* root = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + BAPAResetControls* reset = checkPointer(new BAPAResetControls(true, false, false, m_patternId)); + BAPCombinerParallel* parallel = checkPointer(new BAPCombinerParallel(m_patternId, false, -1, false)); + BAPConAnd* endCondition = checkPointer(new BAPConAnd()); + BAPConEndOfPath* endOfPath = checkPointer(new BAPConEndOfPath()); + BAPConPosition* atPosition = checkPointer(new BAPConPosition(goal, radius)); + endCondition->addCondition(endOfPath); + endCondition->addCondition(atPosition); + const unsigned long long driveControls = controls->getDriveControls(); + const float arriveSpeed = mobile->getMaxSpeed(); + const float speed = mobile->getMaxSpeed(); + // shipped defect: the trace output is discarded; the separate XZ goal remains (0, 0). + const Vec3 destination = {goal.x, 0.0f, goal.y}; + BAPAMoveToFinding* move = checkPointer(new BAPAMoveToFinding(bot, destination, speed, arriveSpeed, + endCondition, driveControls, m_patternId, 0.0f, 0.0f)); + BAPStatement* look; + if (useObject) + { + const unsigned long long lookControls = controls->getLookControls(); + BAPConFalse* condition = checkPointer(new BAPConFalse()); + const unsigned int target = m_threatObjects[bot->getBotId()]; + look = checkPointer(new BAPALookAtObject(bot, target, 0.314f, condition, lookControls, m_patternId, 0, 0.0f)); + } + else + { + const unsigned long long lookControls = controls->getLookControls(); + BAPConFalse* condition = checkPointer(new BAPConFalse()); + const Vec3& position = self->getPosition(); + const Vec3 direction = {threatPosition.x - position.x, threatPosition.y - position.y, + threatPosition.z - position.z}; + look = checkPointer(new BAPALookInDir(direction, 0.314f, condition, lookControls, m_patternId)); + } + parallel->addStatement(move); + parallel->addStatement(look); + root->addStatement(reset); + root->addStatement(parallel); + BAPIWTakeCover* wrapper; + if (useObject) + { + const unsigned int target = m_threatObjects[bot->getBotId()]; + wrapper = checkPointer(new BAPIWTakeCover(target, root, m_patternId)); + } + else + wrapper = checkPointer(new BAPIWTakeCover(threatPosition, root, m_patternId)); + wrapper->mpOwner = this; + return wrapper; +} + +// ELF 0x29E120 +void BBPTakeCover::init(Bot* bot, const Vec3& threat, const Vec3& position, unsigned int cover) +{ + m_coverObjects[bot->getBotId()] = cover; + m_coverPositions[bot->getBotId()] = position; + m_threatPositions[bot->getBotId()] = threat; + m_useObjects[bot->getBotId()] = false; + m_initiated[bot->getBotId()] = true; +} + +// ELF 0x29E1E0 +void BBPTakeCover::init(Bot* bot, unsigned int threat, const Vec3& position, unsigned int cover) +{ + m_coverObjects[bot->getBotId()] = cover; + m_coverPositions[bot->getBotId()] = position; + m_threatObjects[bot->getBotId()] = threat; + m_useObjects[bot->getBotId()] = true; + Information* target = informationManager->getInformation(m_threatObjects[bot->getBotId()]); + if (target) + { + Vec3& destination = m_threatPositions[bot->getBotId()]; + destination = target->getPosition(); + m_initiated[bot->getBotId()] = true; + } + else + m_initiated[bot->getBotId()] = false; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover.h new file mode 100644 index 000000000..e1f3332d4 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover.h @@ -0,0 +1,43 @@ +// Per-bot cover positions and fixed-point/object threat targets. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPTAKECOVER_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPTAKECOVER_H + +#include "../../../../Math/Vec3.h" +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BC7E0 (6 words), operator new 0x20, package H-deferred. +class BBPTakeCover : public BBPPattern +{ +public: + explicit BBPTakeCover(int); // 0x29D910 + virtual ~BBPTakeCover(); // 0x29DFD0 + + virtual BotScript* createPlan(Bot*); // 0x29E330, slot +0x08; from the base declaration + + void init(Bot*, const Vec3&, const Vec3&, unsigned int); // 0x29E120; [INFERRED] ELF void + void init(Bot*, unsigned int, const Vec3&, unsigned int); // 0x29E1E0; [INFERRED] ELF void + +private: + // [INFERRED] names; constructor and init stores establish the ia-32 layout. + /* +0x08 */ int m_patternId; + /* +0x0C */ unsigned int* m_coverObjects; + /* +0x10 */ Vec3* m_coverPositions; + /* +0x14 */ Vec3* m_threatPositions; + /* +0x18 */ unsigned int* m_threatObjects; + /* +0x1C */ bool* m_useObjects; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPTAKECOVER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover3d.cpp new file mode 100644 index 000000000..3c3ebbf1e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover3d.cpp @@ -0,0 +1,116 @@ +// Take-cover pattern of aircraft (AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover3d.cpp in the image). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// createPlan was checked against the listing for constructor arguments (Ghidra merges the trigger's +// 64-bit mask and drops the bool arguments). + +// static init: ELF 0x2A0A40 (__tcf_0 0x2A0AA0, _GLOBAL__I 0x2A0AD0): 's Init object only. +#include + +#include "BBPTakeCover3d.h" + +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPAMoveTo3d.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConTime.h" +#include "../AIBotActionPlan/BAPStatement.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x29FD20: BBPPattern(), the vtable store, then the argument at +0x08. +BBPTakeCover3d::BBPTakeCover3d(int patternId) + : BBPPattern() +{ + m_patternId = patternId; +} + +// ELF 0x29FDA0 (D0 0x29FDE0): the vtable store, then BBPPattern's destructor; nothing of its own. +BBPTakeCover3d::~BBPTakeCover3d() +{ +} + +// ELF 0x29FE20 +void BBPTakeCover3d::init(Bot* bot) +{ + m_initiated[bot->getBotId()] = true; +} + +// ELF 0x29FE50. Keeps a plan of this pattern; otherwise drops the plan and builds +// `parallel(reset controls, trigger input 47 for 2 s, move to 500 m along the own heading)`. +// The own equipment's information is not null-checked before its mobile and control-info +// plug-ins are read, as compiled. +// [PLATFORM] precision: the x87 build adds the extended product heading * 500 to the position; +// the float expression below rounds the product first. +BotScript* BBPTakeCover3d::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } + return 0; + } + + if (bot->hasPlan() && static_cast(bot->getPlan())->getPatternId() == m_patternId) + return bot->getPlan(); + + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + bot->getSquadMember()->clearRequestAction(); + + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* const mobile = self->getMobile(); + IPIControlInfo* const controlInfo = self->getControlInfo(); + + BAPCombinerParallel* const plan = checkPointer(new BAPCombinerParallel(m_patternId, true, -1, false)); + plan->addStatement(checkPointer(new BAPAResetControls(true, true, true, m_patternId))); + plan->addStatement(checkPointer(new BAPATrigger(static_cast(0x2F), + checkPointer(new BAPConTime(2.0f, false, true, true)), + checkPointer(new BAPConFalse()), 0x800000000000ULL, + m_patternId, 0.0f, false))); + + const Vec3& position = self->getPosition(); // +0x30 + const Mat4& transformation = self->getTransformation(); // +0x3C + Vec3 offset; + offset.x = transformation.m[8] * 500.0f; + offset.y = transformation.m[9] * 500.0f; + offset.z = 500.0f * transformation.m[10]; + Vec3 destination; + destination.x = offset.x + position.x; + destination.y = offset.y + position.y; + destination.z = offset.z + position.z; + plan->addStatement(checkPointer(new BAPAMoveTo3d(bot, destination, mobile->getMaxSpeed(), mobile->getMaxSpeed(), + checkPointer(new BAPConFalse()), + controlInfo->getDriveControls(), 30.0f, m_patternId))); + plan->setParent(this); // +0x04 (BotScript::mpOwner) + return plan; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover3d.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover3d.h new file mode 100644 index 000000000..e957d49d7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover3d.h @@ -0,0 +1,38 @@ +// Take-cover pattern of aircraft (3d navigation): flies 500 m straight ahead while pressing input 47. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPTAKECOVER3D_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPTAKECOVER3D_H + +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BC860 (6 words), package H-deferred. BotBehaviourManager's create function +// (0x3D7F80) allocates 0x18 bytes; no body of this class touches +0x0C..+0x17. [UNRESOLVED] +class BBPTakeCover3d : public BBPPattern +{ +public: + explicit BBPTakeCover3d(int); // 0x29FD20 + virtual ~BBPTakeCover3d(); // 0x29FDA0 + + virtual BotScript* createPlan(Bot*); // 0x29FE50, slot +0x08; from the base declaration + + void init(Bot*); // 0x29FE20; ELF void (no return value materialized) + +protected: + /* +0x08 */ int m_patternId; // the constructor argument +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPTAKECOVER3D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCoverInfantry.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCoverInfantry.cpp new file mode 100644 index 000000000..d66089a96 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCoverInfantry.cpp @@ -0,0 +1,392 @@ +// Infantry cover-plan construction recovered from libaidll.so. + +// static init: ELF 0x2A68C0 (__tcf_0 0x2A6920, _GLOBAL__I 0x2A6950): 's Init object only. +#include + +#include "BBPTakeCoverInfantry.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPActionInline.h" +#include "../AIBotActionPlan/BAPAMoveToFinding.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPASetSensingAgentFocus.h" +#include "../AIBotActionPlan/BAPASoldierPose.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConAnd.h" +#include "../AIBotActionPlan/BAPConEndOfPath.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConLineOfFire.h" +#include "../AIBotActionPlan/BAPConObjectLineOfFire.h" +#include "../AIBotActionPlan/BAPConOr.h" +#include "../AIBotActionPlan/BAPConPosition.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPFlowCIf.h" +#include "../AIBotActionPlan/BAPIWTakeCover.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPICover.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IAIPathfinding.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../../../../Math/Mat4.h" +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// [CHOSEN, not recovered] Packaging of the inline transforms in ELF 0x2A1B50. +Vec3 transformPoint(const Mat4& m, const Vec3& point) +{ + const Vec3 result = {point.x * m.m[0] + point.y * m.m[4] + point.z * m.m[8] + m.m[12], + point.x * m.m[1] + point.y * m.m[5] + point.z * m.m[9] + m.m[13], + point.x * m.m[2] + point.y * m.m[6] + point.z * m.m[10] + m.m[14]}; + return result; +} + +Vec3 transformDirection(const Mat4& m, const Vec3& direction) +{ + const Vec3 result = {direction.x * m.m[0] + direction.y * m.m[4] + direction.z * m.m[8], + direction.x * m.m[1] + direction.y * m.m[5] + direction.z * m.m[9], + direction.x * m.m[2] + direction.y * m.m[6] + direction.z * m.m[10]}; + return result; +} + +} // namespace + +// ELF 0x2A1110 (C1; C2 0x2A0AF0) +BBPTakeCoverInfantry::BBPTakeCoverInfantry(int patternId) +{ + const unsigned int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_patternId = patternId; + m_coverObjects = checkPointer(new unsigned int[count]); + m_coverPositions = checkPointer(new Vec3[count]()); + m_threatPositions = checkPointer(new Vec3[count]()); + m_threatObjects = checkPointer(new unsigned int[count]); + m_useObjects = checkPointer(new bool[count]); +} + +// ELF 0x2A17E0 (D1; D2 0x2A1730, D0 0x2A1890) +BBPTakeCoverInfantry::~BBPTakeCoverInfantry() +{ + if (m_coverObjects) + delete[] m_coverObjects; + if (m_coverPositions) + delete[] m_coverPositions; + if (m_threatPositions) + delete[] m_threatPositions; + if (m_threatObjects) + delete[] m_threatObjects; + if (m_useObjects) + delete[] m_useObjects; +} + +// ELF 0x2A1B50 +BotScript* BBPTakeCoverInfantry::createPlan(Bot* bot) +{ + if (!isInitiated(bot)) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) + { + BotScript* previous = bot->getPlan(); + if (previous) + delete previous; + bot->setPlan(0); + } + return 0; + } + IAIPathfinding* pathfinding = IAIPathfinding::instance; + const unsigned int coverObject = m_coverObjects[bot->getBotId()]; + const bool useObject = m_useObjects[bot->getBotId()]; + const Vec3 coverPosition = m_coverPositions[bot->getBotId()]; + Vec3 threatPosition = {}; + if (bot->hasPlan()) + { + BAPStatement* previous = static_cast(bot->getPlan()); + if (previous->getPatternId() == m_patternId && previous->getId() == BAPSTInfoWrapper) + { + BAPIWTakeCover* wrapper = static_cast(previous); + if (wrapper->getInfoType() == 7) + { + if (useObject) + { + if (wrapper->m_useObject) + { + Information* target = informationManager->getInformation(m_threatObjects[bot->getBotId()]); + Information* oldTarget = informationManager->getInformation(wrapper->m_object); + if (target && oldTarget && target->getAIObject() == oldTarget->getAIObject()) + { + const Vec3 difference = bapinline::sub(wrapper->m_position, oldTarget->getPosition()); + if (bapinline::lengthSqr(difference) < 1.0f) + return wrapper; + } + } + } + else if (!wrapper->m_useObject) + { + const Vec3 difference = bapinline::sub(wrapper->m_position, m_threatPositions[bot->getBotId()]); + if (bapinline::lengthSqr(difference) < 9.0f) + return wrapper; + } + } + } + } + if (bot->getPlan()) + { + BotScript* previous = bot->getPlan(); + if (previous) + delete previous; + bot->setPlan(0); + } + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + bot->getSquadMember()->clearRequestAction(); + Information* self = informationManager->getInformation(bot->getCurrentEquipment()); + if (!self) + return 0; + IPIControlInfo* controls = self->getControlInfo(); + if (!controls) + return 0; + IPIMobile* mobile = self->getMobile(); + if (!mobile) + return 0; + Information* cover = informationManager->getInformation(coverObject); + IPICover* coverInfo = 0; + if (cover) + { + if (!cover->getPhysical()) + return 0; + coverInfo = cover->getCover(); + if (!coverInfo) + return 0; + } + if (useObject) + { + Information* target = informationManager->getInformation(m_threatObjects[bot->getBotId()]); + if (!target) + return 0; + threatPosition = target->getPosition(); + } + else + threatPosition = m_threatPositions[bot->getBotId()]; + + BAPCombinerSerial* root; + if (!cover) + { + Vec3 direction = bapinline::sub(threatPosition, self->getPosition()); + const Vec3 destination = coverPosition; + root = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + BAPASetSensingAgentFocus* focus; + if (!m_useObjects[bot->getBotId()]) + { + bapinline::normalize(direction); + focus = checkPointer(new BAPASetSensingAgentFocus(0.5f, direction, m_patternId, false)); + } + else + { + const unsigned int target = m_threatObjects[bot->getBotId()]; + focus = checkPointer(new BAPASetSensingAgentFocus(0.5f, target, m_patternId, false)); + } + const unsigned long long driveControls = controls->getDriveControls(); + BAPConPosition* atPosition = checkPointer(new BAPConPosition(destination, 4.0f)); + const float arriveSpeed = mobile->getMaxSpeed(); + const float speed = mobile->getMaxSpeed() + 1.0f; + BAPAMoveToFinding* move = checkPointer(new BAPAMoveToFinding(bot, destination, speed, arriveSpeed, + atPosition, driveControls, m_patternId, 0.0f, 0.0f)); + BAPAResetControls* reset = checkPointer(new BAPAResetControls(true, false, false, m_patternId)); + BAPASoldierPose* lie = checkPointer(new BAPASoldierPose(SPLying, checkPointer(new BAPConTrue()), m_patternId, false)); + root->addStatement(move); + root->addStatement(reset); + root->addStatement(lie); + root->addStatement(focus); + } + else + { + Vec2 goal = {}; + const int equipmentType = self->getUnit()->getEquipmentType(); + if (coverInfo->getPortalCount() == 0) + { + Vec3 sensePosition = {}; + Vec3 senseNormal = {}; + Vec3 hint = {}; + static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->pickRandomSensePosition(sensePosition, senseNormal, hint, cover->getAIObject()); + Vec3 tracePosition = {}; + unsigned int polygon; + const int vehicleNumber = mobile->getVehicleNumber(); + pathfinding->trace(vehicleNumber, coverPosition, sensePosition, tracePosition, polygon, + equipmentType, -1, 0.0f, 0, 0); + vec3ToVec2XZ(tracePosition, goal); + } + else + { + const Mat4& world = cover->getTransformation(); + Mat4 inverse; + inverse.setInverse(world); + const Vec3 localThreat = transformPoint(inverse, threatPosition); + unsigned int selected = 0; + float bestDot = -FLT_MAX; + unsigned int portal; + for (portal = 0; portal < coverInfo->getPortalCount(); ++portal) + { + Vec3 direction = bapinline::sub(localThreat, coverInfo->getPortalCenter(portal)); + bapinline::normalize(direction); + const float dot = bapinline::dot(direction, coverInfo->getPortalNormal(portal)); + if (dot > bestDot) + { + selected = portal; + bestDot = dot; + } + } + const Vec3& centre = coverInfo->getPortalCenter(selected); + const Vec3& normal = coverInfo->getPortalNormal(selected); + const Vec3 worldCentre = transformPoint(world, centre); + const Vec3 worldNormal = transformDirection(world, normal); + const Vec3 offset = {worldNormal.x * -2.0f, worldNormal.y * -2.0f, worldNormal.z * -2.0f}; + Vec3 closest = {}; + unsigned int polygon; + unsigned int island; + const int vehicleNumber = mobile->getVehicleNumber(); + if (pathfinding->findClosestValidPolygon(polygon, island, closest, vehicleNumber, + worldCentre, offset, 10, equipmentType)) + { + const Vec3 tangent = {worldNormal.z, 0.0f, -worldNormal.x}; + const float side = bapinline::dot(tangent, threatPosition) - bapinline::dot(tangent, worldCentre); + const Vec3 step = {tangent.x * 2.0f, tangent.y * 2.0f, tangent.z * 2.0f}; + // shipped defect: the extent query uses the exhausted loop index, not `selected`. + const float extent = side > 0.0f ? coverInfo->getPortalXZExtentR(portal) + : coverInfo->getPortalXZExtentL(portal); + const Vec3 from = {step.x * extent + worldCentre.x, step.y * extent + worldCentre.y, + step.z * extent + worldCentre.z}; + Vec3 tracePosition = {}; + unsigned int tracePolygon; + const int traceVehicle = mobile->getVehicleNumber(); + pathfinding->trace(traceVehicle, from, closest, tracePosition, tracePolygon, + equipmentType, -1, 0.0f, 0, 0); + vec3ToVec2XZ(tracePosition, goal); + } + } + const float maximumSpeed = mobile->getMaxSpeed(); + const float radius = maximumSpeed < 4.0f ? 4.0f : maximumSpeed * 0.5f; + (void)std::sqrt(bapinline::lengthSqr(bapinline::sub(threatPosition, self->getPosition()))); + root = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + BAPASetSensingAgentFocus* focus; + if (!m_useObjects[bot->getBotId()]) + { + Vec3 direction = bapinline::sub(threatPosition, self->getPosition()); + bapinline::normalize(direction); + focus = checkPointer(new BAPASetSensingAgentFocus(0.5f, direction, m_patternId, false)); + } + else + { + const unsigned int target = m_threatObjects[bot->getBotId()]; + focus = checkPointer(new BAPASetSensingAgentFocus(0.5f, target, m_patternId, false)); + } + root->addStatement(focus); + BAPAResetControls* reset = checkPointer(new BAPAResetControls(true, false, true, m_patternId)); + BAPCombinerParallel* moving = checkPointer(new BAPCombinerParallel(m_patternId, false, -1, false)); + BAPConFalse* poseBreak = checkPointer(new BAPConFalse()); + BAPConTrue* poseRun = checkPointer(new BAPConTrue()); + BAPASoldierPose* pose = checkPointer(new BAPASoldierPose(SPStanding, SPLying, 5, SPCrouching, + 0.0f, poseRun, poseBreak, m_patternId, false)); + BAPConOr* endCondition = checkPointer(new BAPConOr()); + BAPConFalse* never = new BAPConFalse(); + BAPConAnd* arrived = checkPointer(new BAPConAnd()); + BAPConEndOfPath* endOfPath = checkPointer(new BAPConEndOfPath()); + BAPConPosition* atPosition = checkPointer(new BAPConPosition(goal, radius)); + arrived->addCondition(endOfPath); + arrived->addCondition(atPosition); + endCondition->addCondition(never); + endCondition->addCondition(arrived); + const unsigned long long driveControls = controls->getDriveControls(); + const float arriveSpeed = mobile->getMaxSpeed(); + const float speed = mobile->getMaxSpeed(); + const Vec3 destination = {goal.x, 0.0f, goal.y}; + BAPAMoveToFinding* move = checkPointer(new BAPAMoveToFinding(bot, destination, speed, arriveSpeed, + endCondition, driveControls, m_patternId, 0.0f, 0.0f)); + moving->addStatement(pose); + moving->addStatement(move); + BAPCombinerParallel* posing = checkPointer(new BAPCombinerParallel(m_patternId, false, -1, false)); + unsigned int target = 0; + BAPCondition* standingLine; + if (useObject) + { + target = m_threatObjects[bot->getBotId()]; + standingLine = checkPointer(new BAPConObjectLineOfFire(target, false, SPStanding)); + } + else + standingLine = checkPointer(new BAPConLineOfFire(threatPosition, false, SPStanding)); + BAPASoldierPose* stand = checkPointer(new BAPASoldierPose(SPStanding, checkPointer(new BAPConTrue()), m_patternId, false)); + BAPCondition* crouchingLine; + if (useObject) + crouchingLine = checkPointer(new BAPConObjectLineOfFire(target, false, SPCrouching)); + else + crouchingLine = checkPointer(new BAPConLineOfFire(threatPosition, false, SPCrouching)); + BAPASoldierPose* crouch = checkPointer(new BAPASoldierPose(SPCrouching, checkPointer(new BAPConTrue()), m_patternId, false)); + BAPASoldierPose* lie = checkPointer(new BAPASoldierPose(SPLying, checkPointer(new BAPConTrue()), m_patternId, false)); + BAPFlowCIf* lowerPose = checkPointer(new BAPFlowCIf(crouchingLine, lie, crouch, m_patternId, false, false)); + BAPFlowCIf* selectPose = checkPointer(new BAPFlowCIf(standingLine, lowerPose, stand, m_patternId, false, false)); + posing->addStatement(selectPose); + root->addStatement(reset); + root->addStatement(moving); + root->addStatement(posing); + } + BAPIWTakeCover* wrapper; + if (useObject) + { + const unsigned int target = m_threatObjects[bot->getBotId()]; + wrapper = checkPointer(new BAPIWTakeCover(target, root, m_patternId)); + } + else + wrapper = checkPointer(new BAPIWTakeCover(threatPosition, root, m_patternId)); + wrapper->mpOwner = this; + return wrapper; +} + +// ELF 0x2A1940 +void BBPTakeCoverInfantry::init(Bot* bot, const Vec3& threat, const Vec3& position, unsigned int cover) +{ + m_coverObjects[bot->getBotId()] = cover; + m_coverPositions[bot->getBotId()] = position; + m_threatPositions[bot->getBotId()] = threat; + m_useObjects[bot->getBotId()] = false; + m_initiated[bot->getBotId()] = true; +} + +// ELF 0x2A1A00 +void BBPTakeCoverInfantry::init(Bot* bot, unsigned int threat, const Vec3& position, unsigned int cover) +{ + m_coverObjects[bot->getBotId()] = cover; + m_coverPositions[bot->getBotId()] = position; + m_threatObjects[bot->getBotId()] = threat; + m_useObjects[bot->getBotId()] = true; + Information* target = informationManager->getInformation(m_threatObjects[bot->getBotId()]); + if (target) + { + Vec3& destination = m_threatPositions[bot->getBotId()]; + destination = target->getPosition(); + m_initiated[bot->getBotId()] = true; + } + else + m_initiated[bot->getBotId()] = false; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCoverInfantry.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCoverInfantry.h new file mode 100644 index 000000000..e4db79302 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCoverInfantry.h @@ -0,0 +1,43 @@ +// Infantry cover planning with optional cover-object portals and stance selection. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPTAKECOVERINFANTRY_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPTAKECOVERINFANTRY_H + +#include "../../../../Math/Vec3.h" +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BC8E0 (6 words), operator new 0x20, package H-deferred. +class BBPTakeCoverInfantry : public BBPPattern +{ +public: + explicit BBPTakeCoverInfantry(int); // 0x2A1110 + virtual ~BBPTakeCoverInfantry(); // 0x2A17E0 + + virtual BotScript* createPlan(Bot*); // 0x2A1B50, slot +0x08; from the base declaration + + void init(Bot*, const Vec3&, const Vec3&, unsigned int); // 0x2A1940; [INFERRED] ELF void + void init(Bot*, unsigned int, const Vec3&, unsigned int); // 0x2A1A00; [INFERRED] ELF void + +private: + // [INFERRED] names; constructor and init stores establish the ia-32 layout. + /* +0x08 */ int m_patternId; + /* +0x0C */ unsigned int* m_coverObjects; + /* +0x10 */ Vec3* m_coverPositions; + /* +0x14 */ Vec3* m_threatPositions; + /* +0x18 */ unsigned int* m_threatObjects; + /* +0x1C */ bool* m_useObjects; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPTAKECOVERINFANTRY_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTriggerable.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTriggerable.cpp new file mode 100644 index 000000000..010148cce --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTriggerable.cpp @@ -0,0 +1,127 @@ +// Triggerable pattern (man-down bots and world triggerables). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32). + +// static init: ELF 0x2A7F80 (__tcf_0 0x2A7FE0, _GLOBAL__I 0x2A8010): 's Init object only. +#include + +#include "BBPTriggerable.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPAMoveToFinding.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConNot.h" +#include "../AIBotActionPlan/BAPConTriggerableActive.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPFlowCIf.h" +#include "../AIBotActionPlan/BAPFlowCWhile.h" +#include "../AIBotActionPlan/BAPIWIdle.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIPlanInterpreter/VehicleControlInline.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../../Game/Objects/Game/Triggerable.h" +#include "../../../../Game/Objects/TemplateLeaves.h" +#include "../../../../Math/Mat4.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2A6970 (C2) / 0x2A6AF0 (C1): BBPPattern(), +0x08 = id, +0x0C = checkPointer(new[getMaxNBots]); +0x14 = 0 (0x2A69D3, stored before +0x0C). +BBPTriggerable::BBPTriggerable(int id) + : BBPPattern() +{ + m_id = id; + m_triggerable = 0; + m_perBot = checkPointer(new unsigned int[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); +} + +// ELF 0x2A6C70 (D2) / 0x2A6CC0 (D1) / 0x2A6D10 (D0): delete[] +0x0C when set, then ~BBPPattern. +BBPTriggerable::~BBPTriggerable() +{ + if (m_perBot) + delete[] m_perBot; +} + +// ELF 0x2A6DA0: retain this pattern's existing plan, otherwise approach the triggerable and +// repeatedly trigger it while it is inactive. The inactive-pattern path destroys the old plan. +BotScript* BBPTriggerable::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } + return 0; + } + + bot->getSquadMember()->clearRequestAction(); + bot->getCurrentEquipment(); + if (bot->hasPlan()) + { + if (static_cast(bot->getPlan())->getPatternId() == m_id) + return bot->getPlan(); + } + else if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } + + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getSquadMember()->clearRequestAction(); + bot->getScriptContext()->clear(); + BAPCombinerParallel* const parallel = checkPointer(new BAPCombinerParallel(m_id, -1, false)); + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + const unsigned long long controls = equipment->getControlInfo()->getDriveControls(); + // Shipped defect: this condition is constructed and leaked; the movement receives null. + new BAPConFalse(); + const float radius = 0.6f * m_triggerable->m_template->m_radius; + const Mat4& transform = m_triggerable->getAbsoluteTransformation(); + Vec3 direction = { transform.m[8], transform.m[9], transform.m[10] }; + vehiclecontrol::normalizeVec3(direction); + const Vec3& position = m_triggerable->getAbsolutePosition(); + const Vec3 goal = { direction.x * 2.0f + position.x, direction.y * 2.0f + position.y, + direction.z * 2.0f + position.z }; + parallel->addStatement(checkPointer(new BAPAMoveToFinding(bot, goal, 5.0f, 5.0f, 0, + controls, m_id, radius, 0.0f))); + + BAPConFalse* const stop = checkPointer(new BAPConFalse()); + BAPConTrue* const start = checkPointer(new BAPConTrue()); + BAPATrigger* const trigger = checkPointer(new BAPATrigger(static_cast(10), + start, stop, 0x400ULL, m_id, 0.0, false)); + BAPConTriggerableActive* const active = checkPointer(new BAPConTriggerableActive(m_triggerable)); + BAPConNot* const inactive = checkPointer(new BAPConNot(active)); + parallel->addStatement(checkPointer(new BAPFlowCIf(inactive, trigger, 0, m_id, true, false))); + BAPConTrue* const repeat = checkPointer(new BAPConTrue()); + BAPFlowCWhile* const loop = checkPointer(new BAPFlowCWhile(repeat, parallel, true, m_id)); + BAPIWIdle* const plan = checkPointer(new BAPIWIdle(equipment->getPosition(), loop, m_id, bot)); + plan->mpOwner = this; + return plan; +} + +// ELF 0x2A6D60: bot->invalidatePlan() (+0x5C), m_initiated[bot->getBotId()] = true, +0x14. +void BBPTriggerable::init(Bot* bot, world::Triggerable* triggerable) +{ + bot->invalidatePlan(); + m_initiated[bot->getBotId()] = true; + m_triggerable = triggerable; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTriggerable.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTriggerable.h new file mode 100644 index 000000000..366094209 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTriggerable.h @@ -0,0 +1,43 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPTRIGGERABLE_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPTRIGGERABLE_H + +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace world { class Triggerable; } +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BC960 (6 words), operator new 0x18, package F-infantry. +class BBPTriggerable : public BBPPattern +{ +public: + explicit BBPTriggerable(int); // 0x2A6AF0 + virtual ~BBPTriggerable(); // 0x2A6CC0 + + virtual BotScript* createPlan(Bot*); // 0x2A6DA0, slot +0x08; from the base declaration + + void init(Bot*, world::Triggerable*); // 0x2A6D60; void [INFERRED]: no caller in the image reads %eax + +private: + /* +0x08 */ int m_id; // constructor argument [INFERRED] name + /* +0x0C */ unsigned int* m_perBot; // new[getMaxNBots], checkPointer'd [UNRESOLVED] use + /* +0x10 */ unsigned char m_unwritten10[4]; // not written by the constructor or init + /* +0x14 */ world::Triggerable* m_triggerable; // = 0; init's argument +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPTRIGGERABLE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/PlanGenerator.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/PlanGenerator.h new file mode 100644 index 000000000..eee1836c0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/PlanGenerator.h @@ -0,0 +1,37 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_PLANGENERATOR_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_PLANGENERATOR_H + + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// Pattern interface. Vtable 0x4BC420: D1, D0, four pure slots. Inline in the image. +// ELF: vtable 0x4BC420 (6 words), package S0-skeleton. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class PlanGenerator +{ +public: + virtual ~PlanGenerator() {} // weak in the image (inline) + + virtual BotScript* createPlan(Bot*) = 0; // no body, slot +0x08; from the base declaration + virtual bool isInitiated(Bot*) = 0; // no body, slot +0x0C; from the base declaration + virtual void unInit(Bot*) = 0; // no body, slot +0x10; [INFERRED] from BBPGotoWaypoint: ELF void + virtual void forceInitiated(Bot*) = 0; // no body, slot +0x14; [INFERRED] from BBPGotoWaypoint: ELF void +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_PLANGENERATOR_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/WeaponChoice.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/WeaponChoice.cpp new file mode 100644 index 000000000..ee2c68e68 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/WeaponChoice.cpp @@ -0,0 +1,105 @@ +// Weapon selection helpers shared by the fire patterns. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// [INFERRED] file name (see WeaponChoice.h). + +#include "WeaponChoice.h" + +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2A8030 +int choseWeapon(const std::vector& weapons, int current, float distance, int strengthType, + bool noIndirect, bool type1, bool type3, bool type2) +{ + int best = -1; + int bestStrength = 0; + bool inRange = false; + for (unsigned int i = 0; i < weapons.size(); ++i) + { + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (!weapon) + continue; + if ((weapon->getWeaponType() == 3) != type3) + continue; + if ((weapon->getWeaponType() == 1) != type1) + continue; + if ((weapon->getWeaponType() == 2) != type2) + continue; + if (noIndirect && weapon->getIndirect()) + continue; + if (weapon->getAmmo() == 0 && !type2 && !type1 && !type3) + continue; + if (weapon->getStrength(strengthType) <= 0) + continue; + if (weapon->getMaxRange() > distance && weapon->getMinRange() < distance) + { + if (inRange && weapon->getStrength(strengthType) < bestStrength) + continue; + inRange = true; + best = i; + bestStrength = weapon->getStrength(strengthType); + if (best == current) + bestStrength *= 3; + } + else if (!inRange && weapon->getStrength(strengthType) > bestStrength) + { + best = i; + bestStrength = weapon->getStrength(strengthType); + if (best == current) + bestStrength *= 3; + } + } + return best; +} + +// ELF 0x2A8220 +int choseWeaponDistanceIndependent(int current, int strengthType, const std::vector& weapons, + unsigned int allowed) +{ + int best = -1; + int bestStrength = 0; + for (int i = 0; i < static_cast(weapons.size()); ++i) + { + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (!weapon) + continue; + if (!(allowed & 4) && weapon->getWeaponType() == 1) + continue; + if (!(allowed & 2) && weapon->getIndirect()) + continue; + if (!(allowed & 1) && !weapon->getIndirect()) + continue; + if (weapon->getAmmo() == 0 || weapon->getStrength(strengthType) <= 0) + continue; + int strength = weapon->getStrength(strengthType); + if (current == i) + strength *= 3; + if (strength > bestStrength) + { + bestStrength = strength; + best = i; + } + } + return best; +} + +// ELF 0x2A8330 +int soldier_choseThrownWeapon(const std::vector& weapons, int, float distance, int strengthType) +{ + for (unsigned int i = 0; i < weapons.size(); ++i) + { + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (weapon && weapon->getIsThrown() && weapon->getAmmo() != 0 && weapon->getStrength(strengthType) > 0 + && !(weapon->getMinRange() > distance)) + return i; + } + return -1; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/WeaponChoice.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/WeaponChoice.h new file mode 100644 index 000000000..e10063f1a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/WeaponChoice.h @@ -0,0 +1,39 @@ +// Weapon selection helpers shared by the fire patterns. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// [INFERRED] file name: the three functions form a translation unit without a static initialiser +// that links between BBPTriggerable.cpp and AIPlanInterpreter/BAPDebugger.cpp; no __FILE__ string +// names it. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_WEAPONCHOICE_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_WEAPONCHOICE_H + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// Picks the strongest weapon (WeaponInfo::getStrength(strengthType)) among `weapons` (handles) +// whose type matches the three type flags exactly (type 1, 3, 2), with ammunition unless one of +// the type flags is set, and not indirect when `noIndirect`. A weapon whose range brackets +// `distance` beats every weapon out of range; the `current` index counts triple. Returns the +// index into `weapons`, or -1. +int choseWeapon(const std::vector& weapons, int current, float distance, int strengthType, + bool noIndirect, bool type1, bool type3, bool type2); // 0x2A8030 + +// Picks the strongest weapon with ammunition regardless of range. `allowed` bit 0 admits direct +// weapons, bit 1 indirect weapons, bit 2 weapons of type 1; the `current` index counts triple. +// Returns the index into `weapons`, or -1. +int choseWeaponDistanceIndependent(int current, int strengthType, const std::vector& weapons, + unsigned int allowed); // 0x2A8220 + +// The first thrown weapon with ammunition and strength whose minimum range is at most +// `distance`; the int argument is not read. Returns the index into `weapons`, or -1. +int soldier_choseThrownWeapon(const std::vector& weapons, int, float distance, + int strengthType); // 0x2A8330 + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_WEAPONCHOICE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/AIInformationGrid.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/AIInformationGrid.cpp index 8d1a41c48..3eaffd26f 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/AIInformationGrid.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/AIInformationGrid.cpp @@ -1,9 +1,13 @@ #include "AIInformationGrid.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2D74C0, __tcf_0 0x2D7520, _GLOBAL__I 0x2D7550). +#include + #include "Information.h" #include "IPIPhysical.h" -#include "InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIUtils/checkPointer.h" // and, through it, Core/Debug.h #include "../../../../Math/Frustum.h" @@ -24,15 +28,15 @@ AIInformationGrid::AIInformationGrid(int side, int dimX, int dimZ, Vec2 min, Vec , m_dimZ(dimZ) , m_min(min) , m_max(max) - , m_cells(0) + , m_grid(0) { - m_cells = checkPointer(new Cell[m_dimX * m_dimZ + 1]); + m_grid = checkPointer(new Cell[m_dimX * m_dimZ + 1]); } // The records the map still points at are not deleted - defect 2. AIInformationGrid::~AIInformationGrid() { - delete[] m_cells; + delete[] m_grid; } // On an id it already holds this updates rather than declining, which makes it @@ -222,7 +226,7 @@ void AIInformationGrid::getInformationWithinCircle(std::vector& ou { for (int x = minX; x <= maxX; ++x) { - Cell& cell = m_cells[x + m_dimX * y]; + Cell& cell = m_grid[x + m_dimX * y]; for (Cell::iterator it = cell.begin(); it != cell.end(); ++it) { InfoInfo* const info = it->m_info; @@ -287,7 +291,7 @@ void AIInformationGrid::getInformationWithinFrustum(std::vector& o { for (int x = minX; x <= maxX; ++x) { - Cell& cell = m_cells[x + m_dimX * y]; + Cell& cell = m_grid[x + m_dimX * y]; for (Cell::iterator it = cell.begin(); it != cell.end(); ++it) { InfoInfo* const info = it->m_info; @@ -342,7 +346,7 @@ void AIInformationGrid::getInformationWithinRectangle(std::vector& { for (int x = minX; x <= maxX; ++x) { - Cell& cell = m_cells[x + m_dimX * y]; + Cell& cell = m_grid[x + m_dimX * y]; for (Cell::iterator it = cell.begin(); it != cell.end(); ++it) { InfoInfo* const info = it->m_info; @@ -467,7 +471,7 @@ void AIInformationGrid::updateElementInCells(unsigned int id, const InfoInfo& ol for (int x = oldMinX; x <= oldMaxX; ++x) { const int cell = x + m_dimX * y; - m_cells[cell].erase(findCellElement(cell, id)); + m_grid[cell].erase(findCellElement(cell, id)); } } @@ -479,7 +483,7 @@ void AIInformationGrid::updateElementInCells(unsigned int id, const InfoInfo& ol { for (int x = newMinX; x <= newMaxX; ++x) { - Cell& cell = m_cells[x + m_dimX * y]; + Cell& cell = m_grid[x + m_dimX * y]; cell.insert(cell.begin(), element); } } @@ -507,7 +511,7 @@ void AIInformationGrid::addElementToCells(unsigned int id, InfoInfo* info) { for (int x = minX; x <= maxX; ++x) { - Cell& cell = m_cells[x + m_dimX * y]; + Cell& cell = m_grid[x + m_dimX * y]; cell.insert(cell.begin(), element); } } @@ -533,7 +537,7 @@ void AIInformationGrid::removeElementFromCells(unsigned int id, InfoInfo* info) for (int x = minX; x <= maxX; ++x) { const int cell = x + m_dimX * y; - m_cells[cell].erase(findCellElement(cell, id)); + m_grid[cell].erase(findCellElement(cell, id)); } } } @@ -542,7 +546,7 @@ void AIInformationGrid::removeElementFromCells(unsigned int id, InfoInfo* info) AIInformationGrid::Cell::iterator AIInformationGrid::findCellElement(int cell, unsigned int id) const { - Cell& list = m_cells[cell]; + Cell& list = m_grid[cell]; Cell::iterator it = list.begin(); while (it != list.end()) diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/AIInformationGrid.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/AIInformationGrid.h index 8a1bb625b..22aa7b578 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/AIInformationGrid.h +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/AIInformationGrid.h @@ -131,7 +131,7 @@ class AIInformationGrid : public IAIInformationGrid // [UNRESOLVED] Four-byte member left uninitialized and unread by the implemented methods. /* +0x20 */ int m_unwritten20; - /* +0x24 */ Cell* m_cells; // `new Cell[m_dimX * m_dimZ + 1]` - see the header block + /* +0x24 */ Cell* m_grid; // `new Cell[m_dimX * m_dimZ + 1]` - see the header block // name: AIDLL_r assert 0x101FAC00 (+0x24) /* +0x28 */ InfoMap m_infos; // id -> record; in this libstdc++ /* +0x34 */ mutable std::vector m_visited; // the scratchpad; `mutable` is required // because three `const` queries fill it diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIMineManager.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/AIMineManager.cpp similarity index 87% rename from Code/BF2/AI/AIDLL/AI/Main/AIMineManager.cpp rename to Code/BF2/AI/AIDLL/AI/AIKnowledge/AIMineManager.cpp index d942456f1..52b330c22 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIMineManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/AIMineManager.cpp @@ -1,4 +1,6 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining AIMineManager operations. +// Source placement: AIDLL_r.dll __FILE__ "Code\BF2\AI\AIDLL\AI\AIKnowledge\AIMineManager.cpp" (asserts in 0x100B3B60 / 0x100B3C60). +// static init: ELF 0x2E17C0 (__tcf_0 0x2E1820, _GLOBAL__I 0x2E1850): 's Init object only. +#include #include "AIMineManager.h" @@ -8,10 +10,9 @@ #include "../../../../Core/ClassManager.h" #include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" // IAIObjectEnvironment::isAsleep #include "../../../AIInterface/BFKnowledge/BFTimer.h" // IBFTimer::getGameTime -// AIDllFrontier.h is no longer included - this file has no frontier body left. -#include "AIRandom.h" -#include "CommonSingletonServer.h" -#include "IAIPathfinding.h" +#include "../Main/AIRandom.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IAIPathfinding.h" namespace dice { namespace hfe { @@ -34,6 +35,7 @@ inline const Vec3& translationOf(const Mat4& m) } // anonymous namespace // IAIMineManager +// ELF 0x2E9700 / 0x2E97A0 IAIMineManager::IAIMineManager() { // the guard reads the roster static, not the registry. Reproduced. @@ -41,6 +43,7 @@ IAIMineManager::IAIMineManager() classManager->registerSimpleSingleton("IAIMineManager", this); } +// ELF 0x2E9840 / 0x2E98D0 / 0x2E9960 IAIMineManager::~IAIMineManager() { if (CommonSingletonServer::m_iAIMineManager == this) @@ -48,12 +51,14 @@ IAIMineManager::~IAIMineManager() } // Polygon counter records default to zero and support memberwise copying. +// ELF 0x2DEDD0 / 0x2DEDF0 AIMineManager::PolygonData::PolygonData() : m_mines(0) , m_otherMines(0) { } +// ELF 0x2DEE10 / 0x2DEE30 AIMineManager::PolygonData::PolygonData(const PolygonData& other) : m_mines(other.m_mines) , m_otherMines(other.m_otherMines) @@ -61,6 +66,7 @@ AIMineManager::PolygonData::PolygonData(const PolygonData& other) } // Creates an empty mine record with invalid ID, quad-tree and polygon sentinels. +// ELF 0x2DE2C0 / 0x2DE420 AIMineManager::MineInfo::MineInfo() : m_id(-1) , m_mineType(0) @@ -84,6 +90,7 @@ AIMineManager::MineInfo::MineInfo() } // Creates a circular mine record. mineAtRest() must fill its quad-tree and polygon indices before use. +// ELF 0x2DE4D0 / 0x2DE610 AIMineManager::MineInfo::MineInfo(unsigned int id, MineType type, const Mat4& transform, float radius) : m_id(static_cast(id)) @@ -105,6 +112,7 @@ AIMineManager::MineInfo::MineInfo(unsigned int id, MineType type, const Mat4& tr // Builds an anti-personnel mine from its triangular footprint. Leaves the quad-tree id, // polygon id, and radius uninitialized; the anti-personnel path does not read radius. +// ELF 0x2DE750 / 0x2DE8B0 AIMineManager::MineInfo::MineInfo(unsigned int id, MineType type, const Mat4& transform, const Vec3& corner1, const Vec3& corner2) : m_id(static_cast(id)) @@ -119,37 +127,55 @@ AIMineManager::MineInfo::MineInfo(unsigned int id, MineType type, const Mat4& tr m_corner2 = corner2; } +// ELF 0x2DEA10 / 0x2DEBF0 +AIMineManager::MineInfo::MineInfo(const MineInfo& other) + : m_id(other.m_id) + , m_mineType(other.m_mineType) + , m_quadTree(other.m_quadTree) + , m_polygon(other.m_polygon) + , m_polygons(other.m_polygons) + , m_radius(other.m_radius) +{ + for (int i = 0; i < 16; ++i) + m_transform.m[i] = 0.0f; + m_transform = other.m_transform; + m_corner1 = other.m_corner1; + m_corner2 = other.m_corner2; +} + // Initializes mine tracking with one outer-vector entry for each of the two sides. +// ELF 0x2DEE50 / 0x2DF140 AIMineManager::AIMineManager() : m_nextUpdateTime(-1000000000.0) , m_int60(-1) - , m_int72(0) - , m_int76(0) - , m_int80(0) + , m_missingMinePosition{0.0f, 0.0f, 0.0f} , m_flag84(false) { // Leaves m_gap64 uninitialized. Creates entries for anti-personnel and anti-tank mines; // init later sizes each type's map dimension. m_minedPolygons.resize(2); - m_polygonData.resize(2); + m_minesInPolygon.resize(2); } // The binary tears down exactly the four containers, in reverse declaration order - the settling // map, the resting map, then the two nested vectors - and touches none of the six trailing scalars. // That is what proves +72..+83 are three plain ints rather than another vector, and it is all a C++ // destructor does on its own, so the body is empty. +// ELF 0x2DF430 / 0x2DF6D0 / 0x2DF970 AIMineManager::~AIMineManager() { } // Sizes navigation-island tracking for the given mine type. The type must be valid. +// ELF 0x2DFC10 void AIMineManager::init(MineType type, unsigned int islandCount) { m_minedPolygons[type].resize(islandCount); - m_polygonData[type].resize(islandCount); + m_minesInPolygon[type].resize(islandCount); } // Resets scheduling and scalar state while retaining both mine maps and polygon indices. +// ELF 0x2DFDE0 void AIMineManager::reset() { m_int60 = -1; @@ -159,30 +185,33 @@ void AIMineManager::reset() // Returns a reference to the indexed polygon set. Both indices must be valid; a later // init that grows the inner vector can invalidate the reference. -const std::set& AIMineManager::getMinedPolygons(MineType type, unsigned int map) +// ELF 0x2E16F0 +const std::set& AIMineManager::getMinedPolygons(MineType type, unsigned int map) const { return m_minedPolygons[type][map]; } -// Writes the latest recorded quad tree and polygon for the mine, or -1 to both outputs when absent. -void AIMineManager::getPathfindingPositionOfMine(unsigned int mineId, MineType /*type*/, - unsigned int& quadTree, unsigned int& polygon) +// Returns the latest recorded mine position and writes its quad tree and polygon; absent mines return the zero fallback. +// ELF 0x2E1720 +const Vec3& AIMineManager::getPathfindingPositionOfMine(unsigned int mineId, MineType /*type*/, + unsigned int& quadTree, unsigned int& polygon) const { const std::map >::const_iterator i = m_mines.find(mineId); if (i == m_mines.end()) { quadTree = 0xFFFFFFFFu; polygon = 0xFFFFFFFFu; - return; + return m_missingMinePosition; } - const MineInfo& info = i->second.back(); - quadTree = info.m_quadTree; - polygon = info.m_polygon; + quadTree = i->second.back().m_quadTree; + polygon = i->second.back().m_polygon; + return translationOf(i->second.back().m_transform); } // Processes pending mine state at two updates per second. // The deadline test is strict: an update runs only when now is greater than m_nextUpdateTime. +// ELF 0x2E0390 void AIMineManager::update() { IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); @@ -211,6 +240,7 @@ void AIMineManager::update() } // Registers a resting mine as a pathfinding hazard and updates affected polygon counts. +// ELF 0x2E08B0 void AIMineManager::mineAtRest(const MineInfo& info) { MineInfo local(info); @@ -302,6 +332,7 @@ void AIMineManager::mineAtRest(const MineInfo& info) // Probes seven positions along the mine's facing axis, from zero through six metres. // Stops when both polygon and quad-tree ids are valid; returns the final seed otherwise, // which may still be the invalid handle. +// ELF 0x2E04D0 unsigned int AIMineManager::findSeedPolygonForAPMine(MineInfo& info) { unsigned int seed = 0xFFFFFFFFu; @@ -326,6 +357,7 @@ unsigned int AIMineManager::findSeedPolygonForAPMine(MineInfo& info) } // Tries up to fifteen random positions around the mine to find a seed polygon. +// ELF 0x2E05C0 unsigned int AIMineManager::findSeedPolygonForATMine(MineInfo& info) { AIRandom* const random = AIRandom::m_instance; @@ -355,10 +387,11 @@ unsigned int AIMineManager::findSeedPolygonForATMine(MineInfo& info) } // Adds a mine to a polygon's counters. Material changes occur on an existing counter's zero-to-one transition. +// ELF 0x2E1090 void AIMineManager::addNewMineToPolygon(MineType type, unsigned int quadTree, unsigned int polygon) { const std::pair::iterator, bool> result = - m_polygonData[type][quadTree].insert(std::make_pair(polygon, PolygonData())); + m_minesInPolygon[type][quadTree].insert(std::make_pair(polygon, PolygonData())); if (result.second) { @@ -372,11 +405,12 @@ void AIMineManager::addNewMineToPolygon(MineType type, unsigned int quadTree, un ++result.first->second.m_mines; } +// ELF 0x2E11D0 void AIMineManager::addNewOtherMineToPolygon(MineType type, unsigned int quadTree, unsigned int polygon) { const std::pair::iterator, bool> result = - m_polygonData[type][quadTree].insert(std::make_pair(polygon, PolygonData())); + m_minesInPolygon[type][quadTree].insert(std::make_pair(polygon, PolygonData())); if (result.second) { @@ -391,10 +425,11 @@ void AIMineManager::addNewOtherMineToPolygon(MineType type, unsigned int quadTre } // Removes a mine from an existing polygon entry. The caller must ensure the entry exists. -void AIMineManager::removeMineFromPolygon(MineType type, unsigned int quadTree, +// ELF 0x2E14B0 +void AIMineManager::removeMineFromPolygon(MineType type, unsigned int island, unsigned int polygon) { - std::map& polygons = m_polygonData[type][quadTree]; + std::map& polygons = m_minesInPolygon[type][island]; // No end check - see above. const std::map::iterator i = polygons.find(polygon); @@ -403,14 +438,15 @@ void AIMineManager::removeMineFromPolygon(MineType type, unsigned int quadTree, if (i->second.m_mines == 0 && i->second.m_otherMines == 0) { polygons.erase(i); - m_minedPolygons[type][quadTree].erase(polygon); + m_minedPolygons[type][island].erase(polygon); } } -void AIMineManager::removeOtherMineFromPolygon(MineType type, unsigned int quadTree, +// ELF 0x2E15D0 +void AIMineManager::removeOtherMineFromPolygon(MineType type, unsigned int island, unsigned int polygon) { - std::map& polygons = m_polygonData[type][quadTree]; + std::map& polygons = m_minesInPolygon[type][island]; const std::map::iterator i = polygons.find(polygon); --i->second.m_otherMines; @@ -418,11 +454,12 @@ void AIMineManager::removeOtherMineFromPolygon(MineType type, unsigned int quadT if (i->second.m_otherMines == 0 && i->second.m_mines == 0) { polygons.erase(i); - m_minedPolygons[type][quadTree].erase(polygon); + m_minedPolygons[type][island].erase(polygon); } } // Queues a newly placed mine for later processing; it does not update navigation polygons immediately. +// ELF 0x2DFF00 void AIMineManager::minePlaced(MineType type, unsigned int id, const Mat4& transform, float radius) { if (type == 1) @@ -455,6 +492,7 @@ void AIMineManager::minePlaced(MineType type, unsigned int id, const Mat4& trans // Removes settling mines first. If absent there, removes a resting mine and releases // its polygon counters. An id must not exist in both maps. +// ELF 0x2DFE10 void AIMineManager::mineRemoved(unsigned int id) { const std::map::iterator settling = m_settlingMines.find(id); @@ -471,6 +509,7 @@ void AIMineManager::mineRemoved(unsigned int id) } // Releases all polygon registrations for a mine and erases its entry. +// ELF 0x2E1310 void AIMineManager::removeMine(std::map >::iterator& entry) { int index = 0; diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIMineManager.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/AIMineManager.h similarity index 87% rename from Code/BF2/AI/AIDLL/AI/Main/AIMineManager.h rename to Code/BF2/AI/AIDLL/AI/AIKnowledge/AIMineManager.h index 58c63215a..4b09023f5 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIMineManager.h +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/AIMineManager.h @@ -1,6 +1,5 @@ // Tracks mines by side and updates navigation hazards when mines settle or disappear. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. -// [INFERRED] Source placement. +// Header placement [INFERRED]: beside its .cpp, whose path AIDLL_r.dll confirms (AIKnowledge/AIMineManager.cpp: asserts in 0x100B3B60 / 0x100B3C60). #ifndef AI_AIDLL_AI_MAIN_AIMINEMANAGER_H #define AI_AIDLL_AI_MAIN_AIMINEMANAGER_H @@ -11,7 +10,7 @@ #include #include -#include "AIDllTypes.h" +#include "../Main/AIDllTypes.h" namespace dice { namespace hfe { @@ -35,8 +34,9 @@ class IAIMineManager // Mine notifications do not return a result. virtual void mineRemoved(unsigned int) = 0; virtual void minePlaced(MineType, unsigned int, const Mat4&, float) = 0; - virtual const std::set& getMinedPolygons(MineType, unsigned int) = 0; - virtual void getPathfindingPositionOfMine(unsigned int, MineType, unsigned int&, unsigned int&) = 0; + virtual const std::set& getMinedPolygons(MineType, unsigned int) const = 0; + // Returns a borrowed position and writes its navigation indices; unknown mines yield two -1 indices. + virtual const Vec3& getPathfindingPositionOfMine(unsigned int, MineType, unsigned int&, unsigned int&) const = 0; }; // Mine tracking and polygon counters. Offsets describe the original 88-byte ELF object; @@ -59,6 +59,7 @@ class AIMineManager : public IAIMineManager struct MineInfo { MineInfo(); + MineInfo(const MineInfo& other); // The anti-tank form: a radius, i.e. a circular danger area. , MineInfo(unsigned int, MineType, const Mat4&, float); @@ -91,8 +92,8 @@ class AIMineManager : public IAIMineManager virtual void update(); virtual void mineRemoved(unsigned int); virtual void minePlaced(MineType, unsigned int, const Mat4&, float); - virtual const std::set& getMinedPolygons(MineType, unsigned int); - virtual void getPathfindingPositionOfMine(unsigned int, MineType, unsigned int&, unsigned int&); + virtual const std::set& getMinedPolygons(MineType, unsigned int) const; + virtual const Vec3& getPathfindingPositionOfMine(unsigned int, MineType, unsigned int&, unsigned int&) const; private: // The secondary counter tracks projections of mines onto another navigation map. @@ -117,16 +118,14 @@ class AIMineManager : public IAIMineManager // Indexed by mine type, then quad-tree island. init() sizes the island dimension. /* 12 */ std::vector > > m_minedPolygons; - /* 24 */ std::vector > > m_polygonData; + /* 24 */ std::vector > > m_minesInPolygon; // name: AIDLL_r assert 0x100B3B60 (PE +0x20) /* 36 */ std::map > m_mines; // at rest; node = /* 48 */ std::map m_settlingMines; // still moving; node = 132 /* 60 */ int m_int60; // = -1 [UNRESOLVED]; reset sets it to -1 as well /* 64 */ char m_gap64[8]; // the constructor never writes these eight bytes - /* 72 */ int m_int72; // = 0 [UNRESOLVED] - /* 76 */ int m_int76; // = 0 [UNRESOLVED] - /* 80 */ int m_int80; // = 0 [UNRESOLVED] + /* 72 */ Vec3 m_missingMinePosition; // Zero fallback returned by getPathfindingPositionOfMine; name [INFERRED]. /* 84 */ bool m_flag84; // = false [UNRESOLVED]; reset clears it as well }; diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationCourier.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationCourier.cpp index 853ff3d33..523a87a62 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationCourier.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationCourier.cpp @@ -2,16 +2,20 @@ #include "BFInformationCourier.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2E6040, __tcf_0 0x2E60A0, _GLOBAL__I 0x2E60D0). +#include + #include #include #include #include "Information.h" -#include "InformationManager.h" +#include "../Main/InformationManager.h" #include "IPIMobile.h" #include "WeaponInfo.h" -#include "WeaponInfoManager.h" -#include "../AIStrategicMap/AerialHeightMap.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../AIPathFinding/AerialHeightMap/AerialHeightMap.h" #include "../../../../Core/ClassManager.h" #include "../Main/CommonSingletonServer.h" #include "../Main/IAIPathfinding.h" @@ -57,7 +61,7 @@ BFInformationCourier::BFInformationCourier() for (int i = 0; i < 3; ++i) { m_saved[i].polygon = 0xFFFFFFFFu; - m_saved[i].quadTree = 0xFFFFFFFFu; + m_saved[i].island = 0xFFFFFFFFu; m_saved[i].position.x = 0.0f; m_saved[i].position.y = 0.0f; m_saved[i].position.z = 0.0f; @@ -251,13 +255,13 @@ void BFInformationCourier::updateCurrentPolygon(IAIObject* object) IPIMobile::ValidPos infantryPosition; infantryPosition.polygon = static_cast(-1); - infantryPosition.quadTree = static_cast(-1); + infantryPosition.island = static_cast(-1); infantryPosition.position.x = 0.0f; infantryPosition.position.y = 0.0f; infantryPosition.position.z = 0.0f; if (pathfinding->getPolygon( - position, traceMapIndex, infantryPosition.polygon, infantryPosition.quadTree, - mobile->m_lastValidInfantryPos.polygon, mobile->m_lastValidInfantryPos.quadTree, + position, traceMapIndex, infantryPosition.polygon, infantryPosition.island, + mobile->m_lastValidInfantryPos.polygon, mobile->m_lastValidInfantryPos.island, equipmentType)) { infantryPosition.position = position; @@ -270,13 +274,13 @@ void BFInformationCourier::updateCurrentPolygon(IAIObject* object) : mobile->m_lastValidVehiclePosB; IPIMobile::ValidPos vehiclePosition; vehiclePosition.polygon = static_cast(-1); - vehiclePosition.quadTree = static_cast(-1); + vehiclePosition.island = static_cast(-1); vehiclePosition.position.x = 0.0f; vehiclePosition.position.y = 0.0f; vehiclePosition.position.z = 0.0f; if (pathfinding->getPolygon( - position, traceMapIndex == 0, vehiclePosition.polygon, vehiclePosition.quadTree, - previousVehiclePosition.polygon, previousVehiclePosition.quadTree, equipmentType)) + position, traceMapIndex == 0, vehiclePosition.polygon, vehiclePosition.island, + previousVehiclePosition.polygon, previousVehiclePosition.island, equipmentType)) { vehiclePosition.position = position; mobile->setLastValidVehiclePos(vehiclePosition); diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.cpp index a88ad027a..d42e42c43 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.cpp @@ -1,11 +1,17 @@ -// [FRONTIER] Remaining methods stop by name until implemented. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining BFInformationEnvironment operations. - #include "BFInformationEnvironment.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2E7AD0, __tcf_0 0x2E7B30, _GLOBAL__I 0x2E7B60). +#include + #include #include "AIInformationGrid.h" // the grids the constructor builds +#include "Information.h" // removeAllContacts +#include "../Main/InformationManager.h" // the information pool +#include "IPIMobile.h" // getCover's search radius +#include "../AIBot/BotMain.h" // Bot +0xD8 / +0xE0 +#include "../AIUtils/VehicleOccupancy.h" // InfoEnemyPredicate #include "../AIUtils/checkPointer.h" // inlined four times by the constructor #include "../../../../Core/ClassManager.h" #include "../../../../Core/SmartItf.h" // the classManager global @@ -94,51 +100,231 @@ BFInformationEnvironment::BFInformationEnvironment() } } -// [FRONTIER] Unimplemented environment queries and modifiers stop by name. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. - +// ELF 0x2E6C30. Deletes every grid of the second vector, then of the first (null slots skipped, +// the end re-read after each delete); the vectors free themselves. BFInformationEnvironment::~BFInformationEnvironment() { - BF2_AI_FRONTIER("dice::hfe::ai::BFInformationEnvironment::~BFInformationEnvironment"); + for (std::vector::iterator i = m_gridsB.begin(); i != m_gridsB.end(); ++i) + { + if (*i != 0) + delete *i; + } + for (std::vector::iterator i = m_gridsA.begin(); i != m_gridsA.end(); ++i) + { + if (*i != 0) + delete *i; + } } -void BFInformationEnvironment::getFriendlyUnits(std::vector&, const Vec3&, Bot*, float) const +namespace { + +// The query predicates of this TU (anonymous in retail: vtables ELF 0x4BE548..0x4BE5A8, bodies +// 0x2E7E80..0x2E8040, all weak). +4 is each one's single field. + +// Units of one side. +class InfoSideUnitPredicate : public IAIInformationGridPredicate +{ +public: + explicit InfoSideUnitPredicate(int side) : m_side(side) {} + // ELF 0x2E7F20. The side first, then the unit plug-in. + virtual bool includeInformation(Information* information) const + { + return information->getSide() == m_side && information->getUnit() != 0; + } + int m_side; +}; + +// Units of one side or of side 0. +class InfoSideAndNeutralUnitPredicate : public IAIInformationGridPredicate +{ +public: + explicit InfoSideAndNeutralUnitPredicate(int side) : m_side(side) {} + // ELF 0x2E7F70. The unit plug-in first; getSide is called a second time for the 0 test. + virtual bool includeInformation(Information* information) const + { + if (information->getUnit() == 0) + return false; + return information->getSide() == m_side || information->getSide() == 0; + } + int m_side; +}; + +// Any unit. +class InfoUnitPredicate : public IAIInformationGridPredicate { - BF2_AI_FRONTIER("dice::hfe::ai::BFInformationEnvironment::getFriendlyUnits"); +public: + // ELF 0x2E7F00. + virtual bool includeInformation(Information* information) const + { + return information->getUnit() != 0; + } +}; + +// Everything but one record. +class InfoCullSelfPredicate : public IAIInformationGridPredicate +{ +public: + explicit InfoCullSelfPredicate(Information* self) : m_self(self) {} + // ELF 0x2E8020. + virtual bool includeInformation(Information* information) const + { + return m_self != information; + } + Information* m_self; +}; + +// Both of two predicates, the first first. +class CompositeInfoPredicate : public IAIInformationGridPredicate +{ +public: + CompositeInfoPredicate(IAIInformationGridPredicate* first, IAIInformationGridPredicate* second) + : m_first(first), m_second(second) + { + } + // ELF 0x2E7FC0. + virtual bool includeInformation(Information* information) const + { + return m_first->includeInformation(information) && m_second->includeInformation(information); + } + IAIInformationGridPredicate* m_first; // +4 + IAIInformationGridPredicate* m_second; // +8 +}; + +// Cover objects of one side or of side 0. ITStructure accepts any side; ITAir and ITNaval reject. +// Bit names: InformationType (AIDLL_r 0x100D3010); AIDLL_r's version of this predicate (0x101A83C0) +// asserts "Object has no cover plugin but is of type ITCover" on the ITCover bit. +class InfoCoverPredicate : public IAIInformationGridPredicate +{ +public: + explicit InfoCoverPredicate(int side) : m_side(side) {} + // ELF 0x2E7E80. + virtual bool includeInformation(Information* information) const + { + if (!information->isOfType(ITCover) || information->getCover() == 0) + return false; + if (information->isOfType(ITStructure)) + return true; + const int side = information->getSide(); + const bool sideOk = m_side == side || side == 0; + return sideOk && !information->isOfType(ITAir) + && !information->isOfType(ITNaval); + } + int m_side; +}; + +// Units of another side, when vehicleOccupied says the record counts for that side. +class InfoEnemyPredicate : public IAIInformationGridPredicate +{ +public: + explicit InfoEnemyPredicate(int side) : m_side(side) {} + // ELF 0x2E8040. + virtual bool includeInformation(Information* information) const + { + if (information->getUnit() == 0 || m_side == information->getSide()) + return false; + return vehicleOccupied(information->getHandle(), m_side); + } + int m_side; +}; + +// The bot's own record through Bot +0xD8 (getCurrentEquipment). +Information* informationOf(const Bot* bot) +{ + return informationManager->getInformation(bot->getCurrentEquipment()); } -void BFInformationEnvironment::getFriendlyAndNeutralUnits(std::vector&, const Vec3&, Bot*, float) const +} // anonymous namespace + +// ELF 0x2E6F40. `out` is cleared after the lookup; a bot without a record gets nothing. The +// bot's side is read twice (predicate, then the query's side argument). +void BFInformationEnvironment::getFriendlyUnits(std::vector& out, + const Vec3& position, Bot* bot, float radius) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFInformationEnvironment::getFriendlyAndNeutralUnits"); + Information* const self = informationOf(bot); + out.erase(out.begin(), out.end()); + if (self == 0) + return; + InfoSideUnitPredicate keep(bot->getSide()); + getObjectsWithinRadius(out, position, radius, bot->getSide(), true, &keep); } -void BFInformationEnvironment::getCover(const Bot&, std::vector&) const +// ELF 0x2E7030. As getFriendlyUnits, side-0 units included. +void BFInformationEnvironment::getFriendlyAndNeutralUnits(std::vector& out, + const Vec3& position, Bot* bot, + float radius) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFInformationEnvironment::getCover"); + Information* const self = informationOf(bot); + out.erase(out.begin(), out.end()); + if (self == 0) + return; + InfoSideAndNeutralUnitPredicate keep(bot->getSide()); + getObjectsWithinRadius(out, position, radius, bot->getSide(), true, &keep); } -void BFInformationEnvironment::getHardware(std::vector&, const Vec3&, Bot*) const +// ELF 0x2E7120. Both grids (`which` true, then false) within the bot's mobile plug-in's cover +// search radius; `out` is appended to. Retail reads the record's mobile plug-in without testing +// the record for null. +void BFInformationEnvironment::getCover(const Bot& bot, std::vector& out) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFInformationEnvironment::getHardware"); + Information* const self = informationOf(&bot); + IPIMobile* const mobile = self->getMobile(); + if (mobile == 0) + return; + const float radius = mobile->getCoverSearchRadius(); + InfoCoverPredicate keep(bot.getSide()); + getObjectsWithinRadius(out, radius, bot, true, &keep); + getObjectsWithinRadius(out, radius, bot, false, &keep); } -void BFInformationEnvironment::getHardware(std::vector&, const Vec3&, float, int, Information*) const +// ELF 0x2E7220. Units within 75 m except the bot's own record; 0 (and nothing) without a record. +float BFInformationEnvironment::getHardware(std::vector& out, const Vec3& position, + Bot* bot) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFInformationEnvironment::getHardware (Information*)"); + Information* const self = informationOf(bot); + if (self == 0) + return 0.0f; + return getHardware(out, position, 75.0f, bot->getSide(), self); } -void BFInformationEnvironment::getEnemyObjects(std::vector&, Bot*, float) const +// ELF 0x2E72C0. Units within `radius` (minus `self` when given), side `side` and side 0 of the +// first grid; answers the radius. +float BFInformationEnvironment::getHardware(std::vector& out, const Vec3& position, + float radius, int side, Information* self) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFInformationEnvironment::getEnemyObjects"); + InfoUnitPredicate units; + InfoCullSelfPredicate notSelf(self); + CompositeInfoPredicate both(&units, ¬Self); + IAIInformationGridPredicate* const keep = + self != 0 ? static_cast(&both) : &units; + getObjectsWithinRadius(out, position, radius, side, true, keep); + return radius; } -void BFInformationEnvironment::getObjectsWithinRadius(std::vector&, float, const Bot&, - bool, IAIInformationGridPredicate*) const +// ELF 0x2E7360. A negative radius means 600 m when the bot's record has object flag 0x10 and +// 75 m otherwise (retail does not test the record for null there). +void BFInformationEnvironment::getEnemyObjects(std::vector& out, Bot* bot, + float radius) const +{ + Information* const self = informationOf(bot); + if (radius < 0.0f) + radius = self->isOfType(ITAir) ? 600.0f : 75.0f; + InfoEnemyPredicate keep(bot->getSide()); + getObjectsWithinRadius(out, radius, *bot, true, &keep); +} + +// ELF 0x2E7430. Around the bot's record position, for its side; nothing without a record. +void BFInformationEnvironment::getObjectsWithinRadius(std::vector& out, float radius, + const Bot& bot, bool which, + IAIInformationGridPredicate* keep) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFInformationEnvironment::getObjectsWithinRadius (Bot&)"); + Information* const self = informationOf(&bot); + if (self == 0) + return; + const int side = bot.getSide(); + getObjectsWithinRadius(out, self->getPosition(), radius, side, which, keep); } -// flatten XZ, then delegate +// ELF 0x2E74F0: flatten XZ, then delegate // virtually to the Vec2 overload (ELF +0x28 / PE +0x1C). void BFInformationEnvironment::getObjectsWithinRadius(std::vector& out, const Vec3& position, float radius, @@ -152,7 +338,7 @@ void BFInformationEnvironment::getObjectsWithinRadius(std::vector& getObjectsWithinRadius(out, flat, radius, side, which, keep); } -// Query side zero first +// ELF 0x2E7570. Query side zero first // then look up the requested side after that callback. Both calls remain when // side is zero. The grid query is const; output is appended to, never cleared. void BFInformationEnvironment::getObjectsWithinRadius(std::vector& out, @@ -176,10 +362,14 @@ void BFInformationEnvironment::getObjectsWithinRectangle(std::vectorgetInformationWithinRectangle(out, min, max, keep); } -void BFInformationEnvironment::getObjectsWithinFrustum(std::vector&, const Frustum&, - int, bool, IAIInformationGridPredicate*) const +// ELF 0x2E76E0. Side 0 first, then `side` (side 0 twice when asked for it), as the radius and +// rectangle queries. +void BFInformationEnvironment::getObjectsWithinFrustum(std::vector& out, + const Frustum& frustum, int side, bool which, + IAIInformationGridPredicate* keep) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFInformationEnvironment::getObjectsWithinFrustum"); + getInformationGrid(0, which)->getInformationWithinFrustum(out, frustum, keep); + getInformationGrid(side, which)->getInformationWithinFrustum(out, frustum, keep); } void BFInformationEnvironment::getAllInformation(std::vector& out, int side, bool which, @@ -213,24 +403,35 @@ void BFInformationEnvironment::addAndUpdatePosition(int side, bool which, unsign getInformationGrid(side, which)->addAndUpdatePosition(handle); } -void BFInformationEnvironment::updatePosition(int, bool, unsigned int) +// ELF 0x2E78E0: the grid's +5 updatePosition (ELF +0x14). The ELF zero-extends the grid's bool +// into its own result; every caller in both images drops it, so the declared void stays. +void BFInformationEnvironment::updatePosition(int side, bool which, unsigned int handle) { - BF2_AI_FRONTIER("dice::hfe::ai::BFInformationEnvironment::updatePosition"); + getInformationGrid(side, which)->updatePosition(handle); } -void BFInformationEnvironment::removeInfo(int, bool, unsigned int) +// ELF 0x2E7930: the information's +8 removeAllContacts first, then the grid's +3 removeInfo +// (ELF +0x0C). The handle is resolved through the information pool inline; a stale handle +// yields null and the shipped call dereferences it unguarded. +void BFInformationEnvironment::removeInfo(int side, bool which, unsigned int handle) { - BF2_AI_FRONTIER("dice::hfe::ai::BFInformationEnvironment::removeInfo"); + informationManager->getInformation(handle)->removeAllContacts(); + getInformationGrid(side, which)->removeInfo(handle); } -void BFInformationEnvironment::safeRemoveInfo(int, bool, unsigned int) +// ELF 0x2E79C0: as removeInfo, but through the grid's +4 safeRemoveInfo (ELF +0x10) with a null +// removal predicate. The grid's bool is not used. +void BFInformationEnvironment::safeRemoveInfo(int side, bool which, unsigned int handle) { - BF2_AI_FRONTIER("dice::hfe::ai::BFInformationEnvironment::safeRemoveInfo"); + informationManager->getInformation(handle)->removeAllContacts(); + getInformationGrid(side, which)->safeRemoveInfo(handle, nullptr); } -void BFInformationEnvironment::destroyRemoveInfo(int, bool, unsigned int) +// ELF 0x2E7A50: the grid's +4 safeRemoveInfo with a null predicate, without touching the +// information's contacts. +void BFInformationEnvironment::destroyRemoveInfo(int side, bool which, unsigned int handle) { - BF2_AI_FRONTIER("dice::hfe::ai::BFInformationEnvironment::destroyRemoveInfo"); + getInformationGrid(side, which)->safeRemoveInfo(handle, nullptr); } // Selects one of two grid sets by which, then indexes it by side. diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.h index 6acb4277e..a1427947b 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.h +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.h @@ -31,8 +31,9 @@ class IAIInformationEnvironment virtual void getFriendlyUnits(std::vector&, const Vec3&, Bot*, float) const = 0; virtual void getFriendlyAndNeutralUnits(std::vector&, const Vec3&, Bot*, float) const = 0; virtual void getCover(const Bot&, std::vector&) const = 0; - virtual void getHardware(std::vector&, const Vec3&, Bot*) const = 0; - virtual void getHardware(std::vector&, const Vec3&, float, int, Information*) const = 0; + // Both return the search radius in st0 (ELF 0x2E7220 / 0x2E72C0), not void. + virtual float getHardware(std::vector&, const Vec3&, Bot*) const = 0; + virtual float getHardware(std::vector&, const Vec3&, float, int, Information*) const = 0; virtual void getEnemyObjects(std::vector&, Bot*, float) const = 0; virtual void getObjectsWithinRadius(std::vector&, float, const Bot&, bool, IAIInformationGridPredicate*) const = 0; @@ -73,14 +74,14 @@ class BFInformationEnvironment : public IAIInformationEnvironment, { public: BFInformationEnvironment(); // - , complete - virtual ~BFInformationEnvironment(); // [FRONTIER] + virtual ~BFInformationEnvironment(); // ELF 0x2E6C30 // IAIInformationEnvironment. All-information, Vec3/Vec2 radius and rectangle wrappers written. virtual void getFriendlyUnits(std::vector&, const Vec3&, Bot*, float) const; virtual void getFriendlyAndNeutralUnits(std::vector&, const Vec3&, Bot*, float) const; virtual void getCover(const Bot&, std::vector&) const; - virtual void getHardware(std::vector&, const Vec3&, Bot*) const; - virtual void getHardware(std::vector&, const Vec3&, float, int, Information*) const; + virtual float getHardware(std::vector&, const Vec3&, Bot*) const; + virtual float getHardware(std::vector&, const Vec3&, float, int, Information*) const; virtual void getEnemyObjects(std::vector&, Bot*, float) const; virtual void getObjectsWithinRadius(std::vector&, float, const Bot&, bool, IAIInformationGridPredicate*) const; @@ -99,7 +100,7 @@ class BFInformationEnvironment : public IAIInformationEnvironment, virtual void getAllInformation(std::vector&, int, bool, IAIInformationGridPredicate*, IAIInformationGridPredicate*); - // IAIInformationEnvironmentModifiers. All [FRONTIER]. + // IAIInformationEnvironmentModifiers. virtual void addInfo(int, bool, unsigned int); virtual void addAndUpdatePosition(int, bool, unsigned int); virtual void updatePosition(int, bool, unsigned int); diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/DangerObject.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/DangerObject.cpp new file mode 100644 index 000000000..f33df19a8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/DangerObject.cpp @@ -0,0 +1,4 @@ +// The methods are weak inline bodies in the image; the standalone TU initializes iostream only. +// static init: ELF 0x2D7FE0 (__tcf_0 0x2D8040, _GLOBAL__I 0x2D8070). +#include "DangerObject.h" +#include diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/DangerObject.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/DangerObject.h new file mode 100644 index 000000000..cb72a5d31 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/DangerObject.h @@ -0,0 +1,95 @@ +// Identity and position of a threat used by the cover behaviours. +// Source placement: the image's initializer names AI/AIDLL/AI/AIKnowledge/DangerObject.cpp. +#ifndef AI_AIDLL_AI_AIKNOWLEDGE_DANGEROBJECT_H +#define AI_AIDLL_AI_AIKNOWLEDGE_DANGEROBJECT_H + +#include "FireObject.h" +#include "Information.h" +#include "../Main/InformationManager.h" + +namespace dice { namespace hfe { namespace ai { + +// The shipped tables contain five virtual slots and no virtual destructor. Objects are borrowed +// threat identities; their FireObject/Information pointees are never owned. +class DangerObject +{ +public: + virtual bool isFireObject() const = 0; + virtual bool isInformation() const = 0; + virtual bool getPosition(Vec3& position) = 0; + // [INFERRED] void* for the untyped identity pointer compared by operator==. + virtual void* getPointer() const = 0; + + // ELF 0x2206C0 + virtual bool operator==(const DangerObject& other) const + { + if (isInformation() && !other.isInformation()) + return false; + if (isFireObject() && !other.isFireObject()) + return false; + if (!getPointer()) + return false; + void* pointer = getPointer(); + return pointer == other.getPointer(); + } +}; + +class FireDanger : public DangerObject +{ +public: + // [INFERRED] Inline construction: the cover bodies store null or their borrowed shot pointer. + FireDanger() : m_fire(0) {} + explicit FireDanger(FireObject* fire) : m_fire(fire) {} + + // ELF 0x220570 + virtual bool isFireObject() const { return true; } + // ELF 0x220580 + virtual bool isInformation() const { return false; } + // ELF 0x220610 + virtual bool getPosition(Vec3& position) + { + if (!m_fire) + return false; + position = m_fire->getOrigin(); + return true; + } + // ELF 0x220590 + virtual void* getPointer() const { return m_fire; } + + /* +0x04 */ FireObject* m_fire; +}; + +class InfoDanger : public DangerObject +{ +public: + // [INFERRED] Inline construction: the cover bodies store -1 or an information handle. + InfoDanger() : m_information(0xFFFFFFFFu) {} + explicit InfoDanger(unsigned int information) : m_information(information) {} + + // ELF 0x2205A0 + virtual bool isFireObject() const { return false; } + // ELF 0x2205B0 + virtual bool isInformation() const { return true; } + // ELF 0x220640 + virtual bool getPosition(Vec3& position) + { + Information* information = informationManager->getInformation(m_information); + if (!information) + return false; + position = information->getPosition(); + return true; + } + // ELF 0x2205C0 + virtual void* getPointer() const + { + if (m_information == 0xFFFFFFFFu) + return 0; + return informationManager->getInformation(m_information); + } + + /* +0x04 */ unsigned int m_information; +}; + +} } } + +#endif diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/FireObject.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/FireObject.cpp new file mode 100644 index 000000000..ea87beacb --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/FireObject.cpp @@ -0,0 +1,98 @@ +// A reported shot. Evidence: libaidll.so 1.5.3153 (ia-32), see FireObject.h. + +#include "FireObject.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2D8710, __tcf_0 0x2D8770, _GLOBAL__I 0x2D87A0). +#include + +#include + +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2D8090 (C1; C2 0x2D8280 is identical). Field stores first, then the strength count from +// IAISettings +0x34 (getNBattleStrengths), the checked array and the copy loop. +FireObject::FireObject(Vec3 origin, Vec3 target, float* strengths, bool direct, double time, float decay) +{ + m_direct = direct; + m_origin = origin; + m_target = target; + m_time = time; + m_decay = decay; + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + const int count = settings->getNBattleStrengths(); + m_strengths = checkPointer(new float[count]); + for (int i = 0; i < count; ++i) + m_strengths[i] = strengths[i]; +} + +// ELF 0x2D8470: `if (+4) operator delete[](+4)`. +FireObject::~FireObject() +{ + if (m_strengths) + delete[] m_strengths; +} + +// ELF 0x2D84D0. The shot's XZ direction: getVec2NormalFromVec3XZ(target - origin), then the inline +// Vec2 normalisation (left alone within FLT_EPSILON of unit length, zeroed below FLT_EPSILON^2, +// else scaled by 1 / sqrt). The offset of `position` from the origin, projected to XZ, dotted with +// that normal is the distance from the line. +bool FireObject::isWithinRadius(const Vec3& position, float radius) +{ + Vec3 direction; + direction.x = m_target.x - m_origin.x; + direction.y = m_target.y - m_origin.y; + direction.z = m_target.z - m_origin.z; + Vec2 normal; + normal.x = 0.0f; + normal.y = 0.0f; + getVec2NormalFromVec3XZ(direction, normal); + const float lengthSq = normal.x * normal.x + normal.y * normal.y; + if (std::fabs(1.0f - lengthSq) >= 1.1920929e-07f) + { + if (std::fabs(lengthSq) >= 1.4210855e-14f) + { + const float inverse = 1.0f / std::sqrt(lengthSq); + normal.x = normal.x * inverse; + normal.y = inverse * normal.y; + } + else + { + normal.x = 0.0f; + normal.y = 0.0f; + } + } + Vec3 offset; + offset.x = position.x - m_origin.x; + offset.y = position.y - m_origin.y; + offset.z = position.z - m_origin.z; + Vec2 offsetXZ; + offsetXZ.x = 0.0f; + offsetXZ.y = 0.0f; + vec3ToVec2XZ(offset, offsetXZ); + float distance = offsetXZ.x * normal.x + offsetXZ.y * normal.y; + if (distance < 0.0f) + distance = -distance; + return distance <= radius; +} + +// ELF 0x2D86B0: `flds (+4)[type]`; IBFTimer +8 (getGameTime) - +0x20, rounded to float, times +// +0x28, plus 1.0; divide. +float FireObject::getBattleStrength(int type) +{ + const float* const strengths = m_strengths; + const IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); + const float age = static_cast(timer->getGameTime() - m_time); + return strengths[type] / (age * m_decay + 1.0f); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/FireObject.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/FireObject.h new file mode 100644 index 000000000..a22539f2b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/FireObject.h @@ -0,0 +1,50 @@ +// A shot a bot was told about: where it came from, where it went, its per-type battle strengths +// and when it was fired. BotSenses keeps them in its incoming-fire list (+84) and, per shooter, +// in its attacker map (+100); BotMain::event_projectile hands them over. +// Evidence: libaidll.so 1.5.3153 (ia-32). Attested file AIKnowledge/FireObject.cpp (FILE symbol +// beside 0x2D8710, between DangerObject.cpp and Information.cpp); constructors 0x2D8090 / +// 0x2D8280, destructors 0x2D8470 / 0x2D84A0 (not virtual), isWithinRadius 0x2D84D0, +// getBattleStrength 0x2D86B0. Size 0x2C (ia-32). + +#ifndef AI_AIDLL_AI_AIKNOWLEDGE_FIREOBJECT_H // [INFERRED] guard style +#define AI_AIDLL_AI_AIKNOWLEDGE_FIREOBJECT_H + +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +class FireObject +{ +public: + // ELF 0x2D8090. Copies IAISettings::getNBattleStrengths() floats from `strengths` into an owned + // array (checkPointer(new float[n])). + FireObject(Vec3 origin, Vec3 target, float* strengths, bool direct, double time, float decay); + ~FireObject(); // ELF 0x2D8470: delete[] the strengths + + // ELF 0x2D84D0: |distance of `position` from the shot's XZ line| <= radius. + bool isWithinRadius(const Vec3& position, float radius); + // ELF 0x2D86B0: strengths[type] / ((float)(now - time) * decay + 1). + float getBattleStrength(int type); + + bool isDirect() const { return m_direct; } // [INFERRED] inline reader (BotSenses reads +0) + double getTime() const { return m_time; } // [INFERRED] inline reader (BotSenses reads +0x20) + // [INFERRED] inline reader: FireDanger::getPosition copies +0x08..+0x10 (ELF 0x220623). + const Vec3& getOrigin() const { return m_origin; } + const Vec3& getTarget() const { return m_target; } // [INFERRED] inline reader (SensingAgent::evaluateFireObjects reads +0x14) + +private: + /* +0x00 */ bool m_direct; // updateFireObjects weights a direct shot x10 + /* +0x04 */ float* m_strengths; // new float[getNBattleStrengths()] + /* +0x08 */ Vec3 m_origin; + /* +0x14 */ Vec3 m_target; + /* +0x20 */ double m_time; + /* +0x28 */ float m_decay; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIKNOWLEDGE_FIREOBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmament.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmament.cpp index c88b85a17..916bc4640 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmament.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmament.cpp @@ -1,10 +1,14 @@ #include "IPIArmament.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2EC6C0, __tcf_0 0x2EC720, _GLOBAL__I 0x2EC750). +#include + #include "Information.h" #include "InformationFactory.h" #include "WeaponInfo.h" -#include "WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" #include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentDummy.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentDummy.cpp new file mode 100644 index 000000000..4e3b73c1d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentDummy.cpp @@ -0,0 +1,64 @@ +// IPIArmamentDummy. Recovered from libaidll.so 1.5.3153 (ia-32), 0x2EC850..0x2ECD44; the +// inline slots are in IPIArmamentDummy.h. + +#include "IPIArmamentDummy.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2ECC70, __tcf_0 0x2ECCD0, _GLOBAL__I 0x2ECD00). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2EC850 / 0x2EC950. The base gets no information. The member is zeroed (the shipped Mat4 +// member construction) and then copied. +IPIArmamentDummy::IPIArmamentDummy(Mat4& transformation) + : IPIArmament(0) +{ + for (int i = 0; i < 16; ++i) + m_transformation.m[i] = 0.0f; + m_transformation = transformation; +} + +// ELF 0x2ECA50 / 0x2ECAB0 / 0x2ECB10: nothing of its own; the base frees the weapon list. +IPIArmamentDummy::~IPIArmamentDummy() +{ +} + +// ELF 0x2ECB80: the transformation's third row; always true. +bool IPIArmamentDummy::getDirection(Bot* /*bot*/, Vec3& direction) +{ + direction.x = m_transformation.m[8]; + direction.y = m_transformation.m[9]; + direction.z = m_transformation.m[10]; + return true; +} + +// ELF 0x2ECBB0. Despite the name it STORES the given matrix into the member (the argument is +// only read); always true. Shipped behaviour. +bool IPIArmamentDummy::getTransformation(Bot* /*bot*/, Mat4& transformation) +{ + m_transformation = transformation; + return true; +} + +// ELF 0x2ECC40: empty. +void IPIArmamentDummy::setTime() +{ +} + +// ELF 0x2ECC50: empty. +void IPIArmamentDummy::setTime(float /*time*/) +{ +} + +// ELF 0x2ECC60: never anti-aircraft. +int IPIArmamentDummy::isAntiAircraft() const +{ + return 0; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentDummy.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentDummy.h new file mode 100644 index 000000000..ab71c7d84 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentDummy.h @@ -0,0 +1,46 @@ +// Placeholder armament plug-in that is not backed by an engine object: it keeps one weapon +// transformation of its own and has no weapons. getWeapon / getWeapons (+7 / +8) stay pure, so +// the class is abstract; nothing in libaidll.so constructs it or derives from it. +// Evidence: libaidll.so 1.5.3153 (ia-32) 0x2EC850..0x2ECD44, vtable 0x4BEA40 (16 slots); +// FILE symbol IPIArmamentDummy.cpp. + +#ifndef AI_AIDLL_AI_AIKNOWLEDGE_IPIARMAMENTDUMMY_H +#define AI_AIDLL_AI_AIKNOWLEDGE_IPIARMAMENTDUMMY_H + +#include "IPIArmament.h" +#include "../../../../Math/Mat4.h" + +namespace dice { +namespace hfe { +namespace ai { + +class Bot; + +class IPIArmamentDummy : public IPIArmament +{ +public: + // No information; the weapon transformation starts as `transformation`. + explicit IPIArmamentDummy(Mat4& transformation); + virtual ~IPIArmamentDummy(); + + virtual void setTime(); // +3 + virtual void setActiveWeapon(int, int) {} // +6 ELF 0x2ECD20 + virtual int isAntiAircraft() const; // +11 + virtual void updateWeapons() {} // +12 ELF 0x2ECD40 + virtual void rearm(WeaponInfo*, float, int) {} // +13 ELF 0x2ECD30 + + // Non-virtual. Both answer true for any bot. + bool getDirection(Bot* bot, Vec3& direction); + bool getTransformation(Bot* bot, Mat4& transformation); + void setTime(float time); + +protected: + // ELF layout; sizeof 0x58. + /* +0x18 */ Mat4 m_transformation; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIKNOWLEDGE_IPIARMAMENTDUMMY_H diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentKnown.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentKnown.cpp new file mode 100644 index 000000000..5095ebbfe --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentKnown.cpp @@ -0,0 +1,84 @@ +// IPIArmamentKnown. Recovered from libaidll.so 1.5.3153 (ia-32), 0x2ECD50..0x2ED14E; vtable +// 0x4BEAE0 (17 slots: IPIArmament's 16 plus updateWeaponsInternal()). + +#include "IPIArmamentKnown.h" + +#include "WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// 0x2ECD50: marks the records stale, then builds them at once (both calls direct). +IPIArmamentKnown::IPIArmamentKnown(Information* information) + : IPIArmament(information) +{ + m_activeWeapon = 0; // [CHOSEN] + IPIArmamentKnown::updateWeapons(); + IPIArmamentKnown::updateWeaponsInternal(); +} + +// 0x2ECDF0: frees every weapon record (no -1 test, as in IPIArmament::updateWeaponsInternal), +// then the base releases the vector. +IPIArmamentKnown::~IPIArmamentKnown() +{ + for (std::vector::iterator it = m_weapons.begin(); it != m_weapons.end(); ++it) + WeaponInfoManager::m_instance->freeInformation(*it); +} + +// 0x2ED0C0: rebuilds stale records, then lets every existing record refresh itself. +void IPIArmamentKnown::setTime(double /*time*/) +{ + if (m_weaponsStale) + updateWeaponsInternal(); // +16 + for (unsigned int i = 0; i < m_weapons.size(); ++i) + { + if (m_weapons[i] == static_cast(-1)) + continue; + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(m_weapons[i]); + if (weapon) + weapon->update(); // +2 + } +} + +// 0x2ECFE0 (unchecked index). +unsigned int IPIArmamentKnown::getWeapon(int index) +{ + if (m_weaponsStale) + updateWeaponsInternal(); // +16 + return m_weapons[index]; +} + +// 0x2ED010. +std::vector& IPIArmamentKnown::getWeapons() +{ + if (m_weaponsStale) + updateWeaponsInternal(); // +16 + return m_weapons; +} + +// 0x2ED040. +int IPIArmamentKnown::getActiveWeapon() +{ + if (m_weaponsStale) + updateWeaponsInternal(); // +16 + return m_activeWeapon; +} + +// 0x2ED070. +void IPIArmamentKnown::updateWeapons() +{ + m_weaponsStale = true; +} + +// 0x2ED080: the base rebuild with known (not real) weapon records. +void IPIArmamentKnown::updateWeaponsInternal() +{ + IPIArmament::updateWeaponsInternal(false); + m_weaponsStale = false; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentKnown.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentKnown.h new file mode 100644 index 000000000..8b96eb554 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentKnown.h @@ -0,0 +1,40 @@ +// Armament information about an object of another side: the weapon records are rebuilt lazily +// (after updateWeapons marks them stale) and refreshed on every setTime. +// [INFERRED] Source placement beside IPIArmamentReal. +#ifndef AI_AIDLL_AI_AIKNOWLEDGE_IPIARMAMENTKNOWN_H +#define AI_AIDLL_AI_AIKNOWLEDGE_IPIARMAMENTKNOWN_H + +#include "IPIArmament.h" + +namespace dice { +namespace hfe { +namespace ai { + +class IPIArmamentKnown : public IPIArmament +{ +public: + explicit IPIArmamentKnown(Information* information); + virtual ~IPIArmamentKnown(); + + virtual void setTime(double time); // +4 + virtual unsigned int getWeapon(int index); // +7 + virtual std::vector& getWeapons(); // +8 + virtual void updateWeapons(); // +12 - marks stale + // +16, the class's own slot: rebuilds the weapon records as known ones. + virtual void updateWeaponsInternal(); + + // Non-virtual; the vtable keeps IPIArmament::getActiveWeapon (+5). + int getActiveWeapon(); + +private: + /* +0x18 */ bool m_weaponsStale; // [INFERRED] name + // Read by getActiveWeapon, written by no audited body (retail reads it uninitialised). + // [CHOSEN, not recovered] zeroed by the constructor here. + /* +0x1C */ int m_activeWeapon; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIKNOWLEDGE_IPIARMAMENTKNOWN_H diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIControlInfo.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIControlInfo.cpp new file mode 100644 index 000000000..29b732953 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIControlInfo.cpp @@ -0,0 +1,333 @@ +// IPIControlInfo forwarders. Recovered from libaidll.so 1.5.3153 0x2ED380..0x2EDD50: every +// function is the same 0x30-byte shape, +// mov 0x8(%ebp),%eax; mov 0x4(%eax),%eax; mov 0x20(%eax),%eax; call *0x88(vtbl); +// [push the one reference argument]; call *slot(vtbl); [movzbl %al for the bool ones] +// so the return value (eax, edx:eax for the 64-bit masks, st0 for floats) passes through. + +#include "IPIControlInfo.h" + +#include "Information.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// Information +0x20 (the owning AI object), then IAIObject +0x88. +inline IAIObjectControlInfo* controlInfoOf(Information* information) +{ + return information->getAIObject()->getControlInfo(); +} + +} // anonymous namespace + +// ELF 0x2ED380: plug-in slot +0x18. +unsigned long long IPIControlInfo::getDriveControls() +{ + return controlInfoOf(m_information)->getDriveControls(); +} + +// ELF 0x2ED3B0: plug-in slot +0x24. +unsigned long long IPIControlInfo::getAimControls() +{ + return controlInfoOf(m_information)->getAimControls(); +} + +// ELF 0x2ED3E0: plug-in slot +0x30. +unsigned long long IPIControlInfo::getLookControls() +{ + return controlInfoOf(m_information)->getLookControls(); +} + +// ELF 0x2ED410: plug-in slot +0x3C. +float IPIControlInfo::getThrottleSensitivity() +{ + return controlInfoOf(m_information)->getThrottleSensitivity(); +} + +// ELF 0x2ED440: plug-in slot +0x40. +float IPIControlInfo::getPitchSensitivity() +{ + return controlInfoOf(m_information)->getPitchSensitivity(); +} + +// ELF 0x2ED470: plug-in slot +0x7C. +float IPIControlInfo::getLookHorizontalSensitivity() +{ + return controlInfoOf(m_information)->getLookHorizontalSensitivity(); +} + +// ELF 0x2ED4A0: plug-in slot +0x78. +float IPIControlInfo::getLookVerticalSensitivity() +{ + return controlInfoOf(m_information)->getLookVerticalSensitivity(); +} + +// ELF 0x2ED4D0: plug-in slot +0x44. +float IPIControlInfo::getRollSensitivity() +{ + return controlInfoOf(m_information)->getRollSensitivity(); +} + +// ELF 0x2ED500: plug-in slot +0x48. +float IPIControlInfo::getYawSensitivity() +{ + return controlInfoOf(m_information)->getYawSensitivity(); +} + +// ELF 0x2ED530: plug-in slot +0x4C. +float IPIControlInfo::getProportionalConstant() +{ + return controlInfoOf(m_information)->getProportionalConstant(); +} + +// ELF 0x2ED560: plug-in slot +0x50. +float IPIControlInfo::getDerivativeConstant() +{ + return controlInfoOf(m_information)->getDerivativeConstant(); +} + +// ELF 0x2ED590: plug-in slot +0x54. +float IPIControlInfo::getAngleSpeedConstant() +{ + return controlInfoOf(m_information)->getAngleSpeedConstant(); +} + +// ELF 0x2ED5C0: plug-in slot +0x58. +float IPIControlInfo::getThrottleLookAhead() +{ + return controlInfoOf(m_information)->getThrottleLookAhead(); +} + +// ELF 0x2ED5F0: plug-in slot +0x5C. +float IPIControlInfo::getPitchLookAhead() +{ + return controlInfoOf(m_information)->getPitchLookAhead(); +} + +// ELF 0x2ED620: plug-in slot +0x84. +float IPIControlInfo::getLookHorizontalLookAhead() +{ + return controlInfoOf(m_information)->getLookHorizontalLookAhead(); +} + +// ELF 0x2ED650: plug-in slot +0x80. +float IPIControlInfo::getLookVerticalLookAhead() +{ + return controlInfoOf(m_information)->getLookVerticalLookAhead(); +} + +// ELF 0x2ED680: plug-in slot +0x60. +float IPIControlInfo::getRollLookAhead() +{ + return controlInfoOf(m_information)->getRollLookAhead(); +} + +// ELF 0x2ED6B0: plug-in slot +0x64. +float IPIControlInfo::getYawLookAhead() +{ + return controlInfoOf(m_information)->getYawLookAhead(); +} + +// ELF 0x2ED6E0: plug-in slot +0x68. +float IPIControlInfo::getThrottleScale() +{ + return controlInfoOf(m_information)->getThrottleScale(); +} + +// ELF 0x2ED710: plug-in slot +0x6C. +float IPIControlInfo::getPitchScale() +{ + return controlInfoOf(m_information)->getPitchScale(); +} + +// ELF 0x2ED740: plug-in slot +0x8C. +float IPIControlInfo::getLookHorizontalScale() +{ + return controlInfoOf(m_information)->getLookHorizontalScale(); +} + +// ELF 0x2ED770: plug-in slot +0x88. +float IPIControlInfo::getLookVerticalScale() +{ + return controlInfoOf(m_information)->getLookVerticalScale(); +} + +// ELF 0x2ED7A0: plug-in slot +0x70. +float IPIControlInfo::getRollScale() +{ + return controlInfoOf(m_information)->getRollScale(); +} + +// ELF 0x2ED7D0: plug-in slot +0x74. +float IPIControlInfo::getYawScale() +{ + return controlInfoOf(m_information)->getYawScale(); +} + +// ELF 0x2ED800: plug-in slot +0x1C. +io::PlayerInputMap IPIControlInfo::getDriveThrottleControl() +{ + return controlInfoOf(m_information)->getDriveThrottleControl(); +} + +// ELF 0x2ED830: plug-in slot +0x20. +io::PlayerInputMap IPIControlInfo::getDriveTurnControl() +{ + return controlInfoOf(m_information)->getDriveTurnControl(); +} + +// ELF 0x2ED860: plug-in slot +0x28. +io::PlayerInputMap IPIControlInfo::getAimVerticalControl() +{ + return controlInfoOf(m_information)->getAimVerticalControl(); +} + +// ELF 0x2ED890: plug-in slot +0x2C. +io::PlayerInputMap IPIControlInfo::getAimHorizontalControl() +{ + return controlInfoOf(m_information)->getAimHorizontalControl(); +} + +// ELF 0x2ED8C0: plug-in slot +0x34. +io::PlayerInputMap IPIControlInfo::getLookVerticalControl() +{ + return controlInfoOf(m_information)->getLookVerticalControl(); +} + +// ELF 0x2ED8F0: plug-in slot +0x38. +io::PlayerInputMap IPIControlInfo::getLookHorizontalControl() +{ + return controlInfoOf(m_information)->getLookHorizontalControl(); +} + +// ELF 0x2ED920: plug-in slot +0x90. +float IPIControlInfo::getMaxSpeedBumpinessFallOff() +{ + return controlInfoOf(m_information)->getMaxSpeedBumpinessFallOff(); +} + +// ELF 0x2ED950: plug-in slot +0x94. +float IPIControlInfo::getCameraRelativeDofRotationOffset() const +{ + return controlInfoOf(m_information)->getCameraRelativeDofRotationOffset(); +} + +// ELF 0x2ED980: plug-in slot +0x98. +const Vec3& IPIControlInfo::getCameraRelativeMinRotation() const +{ + return controlInfoOf(m_information)->getCameraRelativeMinRotation(); +} + +// ELF 0x2ED9B0: plug-in slot +0x9C. +const Vec3& IPIControlInfo::getCameraRelativeMaxRotation() const +{ + return controlInfoOf(m_information)->getCameraRelativeMaxRotation(); +} + +// ELF 0x2ED9E0: plug-in slot +0xA0. +void IPIControlInfo::getCameraRelativeRotation(Vec3& out) const +{ + controlInfoOf(m_information)->getCameraRelativeRotation(out); +} + +// ELF 0x2EDA10: plug-in slot +0xA4. +const Mat4& IPIControlInfo::getCameraTransformation() const +{ + return controlInfoOf(m_information)->getCameraTransformation(); +} + +// ELF 0x2EDA40: plug-in slot +0xA8. +void IPIControlInfo::getCameraBaseTransformation(Mat4& out) const +{ + controlInfoOf(m_information)->getCameraBaseTransformation(out); +} + +// ELF 0x2EDA70: plug-in slot +0xAC. +void IPIControlInfo::getCameraBaseRight(Vec3& out) const +{ + controlInfoOf(m_information)->getCameraBaseRight(out); +} + +// ELF 0x2EDAA0: plug-in slot +0xB0. +void IPIControlInfo::getCameraBaseUp(Vec3& out) const +{ + controlInfoOf(m_information)->getCameraBaseUp(out); +} + +// ELF 0x2EDAD0: plug-in slot +0xB4. +void IPIControlInfo::getCameraBaseDof(Vec3& out) const +{ + controlInfoOf(m_information)->getCameraBaseDof(out); +} + +// ELF 0x2EDB00: plug-in slot +0xB8. +void IPIControlInfo::getCameraBasePos(Vec3& out) const +{ + controlInfoOf(m_information)->getCameraBasePos(out); +} + +// ELF 0x2EDB30: plug-in slot +0xBC. +bool IPIControlInfo::validateCameraDirection(const Vec3& direction) const +{ + return controlInfoOf(m_information)->validateCameraDirection(direction); +} + +// ELF 0x2EDB70: plug-in slot +0xC0. +bool IPIControlInfo::validateCameraDirectionYaw(const Vec3& direction) const +{ + return controlInfoOf(m_information)->validateCameraDirectionYaw(direction); +} + +// ELF 0x2EDBB0: plug-in slot +0xC4. +bool IPIControlInfo::validateCameraDirectionPitch(const Vec3& direction) const +{ + return controlInfoOf(m_information)->validateCameraDirectionPitch(direction); +} + +// ELF 0x2EDBF0: plug-in slot +0xC8. +bool IPIControlInfo::validateCameraDirectionByPos(const Vec3& position) const +{ + return controlInfoOf(m_information)->validateCameraDirectionByPos(position); +} + +// ELF 0x2EDC30: plug-in slot +0xCC. +float IPIControlInfo::getMaxClimbAngle() +{ + return controlInfoOf(m_information)->getMaxClimbAngle(); +} + +// ELF 0x2EDC60: plug-in slot +0xD0. +float IPIControlInfo::getMaxRollAngle() +{ + return controlInfoOf(m_information)->getMaxRollAngle(); +} + +// ELF 0x2EDC90: plug-in slot +0xD4. +io::PlayerInputMap IPIControlInfo::getDriveRollControl() +{ + return controlInfoOf(m_information)->getDriveRollControl(); +} + +// ELF 0x2EDCC0: plug-in slot +0xD8. +io::PlayerInputMap IPIControlInfo::getDrivePitchControl() +{ + return controlInfoOf(m_information)->getDrivePitchControl(); +} + +// ELF 0x2EDCF0: plug-in slot +0xDC. +io::PlayerInputMap IPIControlInfo::getAimThrottleControl() +{ + return controlInfoOf(m_information)->getAimThrottleControl(); +} + +// ELF 0x2EDD20: plug-in slot +0xE0. +io::PlayerInputMap IPIControlInfo::getAimRollControl() +{ + return controlInfoOf(m_information)->getAimRollControl(); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIControlInfo.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIControlInfo.h index 817f38cd4..1bf3be2e2 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIControlInfo.h +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIControlInfo.h @@ -1,10 +1,14 @@ -// Control information plug-in; adds no virtual methods to InformationPlugIn. -// [INFERRED] Source placement. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding IPIControlInfo operation. +// Control information plug-in: the AI-side view of an object's control template (input maps, +// regulator constants, camera limits). Every accessor reads through to the engine object. +// ELF: vtable 0x4B7450; the 51 non-virtual forwarders 0x2ED380..0x2EDD50 sit between +// IPIArmamentDummy.cpp and IPICover.cpp (no FILE symbol: no static initialiser), hence +// IPIControlInfo.cpp. #ifndef AI_AIDLL_AI_AIKNOWLEDGE_IPICONTROLINFO_H #define AI_AIDLL_AI_AIKNOWLEDGE_IPICONTROLINFO_H #include "InformationPlugIn.h" +#include "Information.h" // callers rely on it (E, mac-metal bd97c30) +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" // io::PlayerInputMap, Vec3, Mat4 namespace dice { namespace hfe { namespace ai { @@ -21,6 +25,62 @@ class IPIControlInfo : public InformationPlugIn // through to the engine object on every call, so there is nothing to refresh. virtual void setTime() {} virtual void setTime(double /*time*/) {} + + // Non-virtual forwarders, out of line in the image. Each body is + // `m_information(+4)->m_object(+0x20)->getControlInfo()(IAIObject +0x88)->slot()`, the + // arguments passed through unchanged (IAIObjectControlInfo slot named on the right). + // Constness follows the mangled names: only the camera block is const. + unsigned long long getDriveControls(); // ELF 0x2ED380 -> slot +0x18 + unsigned long long getAimControls(); // ELF 0x2ED3B0 -> slot +0x24 + unsigned long long getLookControls(); // ELF 0x2ED3E0 -> slot +0x30 + float getThrottleSensitivity(); // ELF 0x2ED410 -> slot +0x3C + float getPitchSensitivity(); // ELF 0x2ED440 -> slot +0x40 + float getLookHorizontalSensitivity(); // ELF 0x2ED470 -> slot +0x7C + float getLookVerticalSensitivity(); // ELF 0x2ED4A0 -> slot +0x78 + float getRollSensitivity(); // ELF 0x2ED4D0 -> slot +0x44 + float getYawSensitivity(); // ELF 0x2ED500 -> slot +0x48 + float getProportionalConstant(); // ELF 0x2ED530 -> slot +0x4C + float getDerivativeConstant(); // ELF 0x2ED560 -> slot +0x50 + float getAngleSpeedConstant(); // ELF 0x2ED590 -> slot +0x54 + float getThrottleLookAhead(); // ELF 0x2ED5C0 -> slot +0x58 + float getPitchLookAhead(); // ELF 0x2ED5F0 -> slot +0x5C + float getLookHorizontalLookAhead(); // ELF 0x2ED620 -> slot +0x84 + float getLookVerticalLookAhead(); // ELF 0x2ED650 -> slot +0x80 + float getRollLookAhead(); // ELF 0x2ED680 -> slot +0x60 + float getYawLookAhead(); // ELF 0x2ED6B0 -> slot +0x64 + float getThrottleScale(); // ELF 0x2ED6E0 -> slot +0x68 + float getPitchScale(); // ELF 0x2ED710 -> slot +0x6C + float getLookHorizontalScale(); // ELF 0x2ED740 -> slot +0x8C + float getLookVerticalScale(); // ELF 0x2ED770 -> slot +0x88 + float getRollScale(); // ELF 0x2ED7A0 -> slot +0x70 + float getYawScale(); // ELF 0x2ED7D0 -> slot +0x74 + io::PlayerInputMap getDriveThrottleControl(); // ELF 0x2ED800 -> slot +0x1C + io::PlayerInputMap getDriveTurnControl(); // ELF 0x2ED830 -> slot +0x20 + io::PlayerInputMap getAimVerticalControl(); // ELF 0x2ED860 -> slot +0x28 + io::PlayerInputMap getAimHorizontalControl(); // ELF 0x2ED890 -> slot +0x2C + io::PlayerInputMap getLookVerticalControl(); // ELF 0x2ED8C0 -> slot +0x34 + io::PlayerInputMap getLookHorizontalControl(); // ELF 0x2ED8F0 -> slot +0x38 + float getMaxSpeedBumpinessFallOff(); // ELF 0x2ED920 -> slot +0x90 + float getCameraRelativeDofRotationOffset() const; // ELF 0x2ED950 -> slot +0x94 + const Vec3& getCameraRelativeMinRotation() const; // ELF 0x2ED980 -> slot +0x98 + const Vec3& getCameraRelativeMaxRotation() const; // ELF 0x2ED9B0 -> slot +0x9C + void getCameraRelativeRotation(Vec3& out) const; // ELF 0x2ED9E0 -> slot +0xA0 + const Mat4& getCameraTransformation() const; // ELF 0x2EDA10 -> slot +0xA4 + void getCameraBaseTransformation(Mat4& out) const; // ELF 0x2EDA40 -> slot +0xA8 + void getCameraBaseRight(Vec3& out) const; // ELF 0x2EDA70 -> slot +0xAC + void getCameraBaseUp(Vec3& out) const; // ELF 0x2EDAA0 -> slot +0xB0 + void getCameraBaseDof(Vec3& out) const; // ELF 0x2EDAD0 -> slot +0xB4 + void getCameraBasePos(Vec3& out) const; // ELF 0x2EDB00 -> slot +0xB8 + bool validateCameraDirection(const Vec3& direction) const; // ELF 0x2EDB30 -> slot +0xBC + bool validateCameraDirectionYaw(const Vec3& direction) const; // ELF 0x2EDB70 -> slot +0xC0 + bool validateCameraDirectionPitch(const Vec3& direction) const; // ELF 0x2EDBB0 -> slot +0xC4 + bool validateCameraDirectionByPos(const Vec3& position) const; // ELF 0x2EDBF0 -> slot +0xC8 + float getMaxClimbAngle(); // ELF 0x2EDC30 -> slot +0xCC + float getMaxRollAngle(); // ELF 0x2EDC60 -> slot +0xD0 + io::PlayerInputMap getDriveRollControl(); // ELF 0x2EDC90 -> slot +0xD4 + io::PlayerInputMap getDrivePitchControl(); // ELF 0x2EDCC0 -> slot +0xD8 + io::PlayerInputMap getAimThrottleControl(); // ELF 0x2EDCF0 -> slot +0xDC + io::PlayerInputMap getAimRollControl(); // ELF 0x2EDD20 -> slot +0xE0 }; } } } diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPICover.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPICover.cpp index db04b4f29..c70b7f821 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPICover.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPICover.cpp @@ -2,6 +2,10 @@ #include "IPICover.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2EE3F0, __tcf_0 0x2EE450, _GLOBAL__I 0x2EE480). +#include + #include "Information.h" #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobile.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobile.cpp index 3f2e45312..5a081a3f7 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobile.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobile.cpp @@ -3,6 +3,10 @@ #include "IPIMobile.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2EEAF0, __tcf_0 0x2EEB50, _GLOBAL__I 0x2EEB80). +#include + #include "Information.h" #include "../Main/CommonSingletonServer.h" #include "../Main/IAIPathfinding.h" @@ -19,7 +23,7 @@ namespace { void clearValidPos(IPIMobile::ValidPos& position) { position.polygon = static_cast(-1); - position.quadTree = static_cast(-1); + position.island = static_cast(-1); position.position.x = 0.0f; position.position.y = 0.0f; position.position.z = 0.0f; @@ -133,7 +137,7 @@ void IPIMobile::setLastValidVehiclePosInternal(const ValidPos& position) { unsigned char material; // Retail ignores getMaterial's result and may inspect this uninitialized. IAIPathfinding::instance->getMaterial(IAIPathfinding::instance->getTraceMapIndex() == 0, - position.quadTree, position.polygon, material); + position.island, position.polygon, material); switch (material) { case 3: diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobile.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobile.h index 9aefdcb60..5ce679acf 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobile.h +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobile.h @@ -21,7 +21,7 @@ class IPIMobile : public InformationPlugIn struct ValidPos { unsigned int polygon; - unsigned int quadTree; + unsigned int island; // name: AIDLL_r assert "oldVehicleVP.island != invalidIslandId" (0x100CDD00; +4) Vec3 position; }; @@ -57,6 +57,11 @@ class IPIMobile : public InformationPlugIn float getAvoidCollisionLookAhead() const; float getSprintStamina() const; + // [INFERRED] inline reader of +0x08: BFPathfindingCourier::getLastValidSquadleaderPosition + // (ELF 0x2E83BD) reads `mobile+8 != -1` and copies +0x10..+0x18 without a call; also + // BotNavigation::reset / initPathfinding (ELF 0x190A70 / 0x1902B0) read the infantry + // polygon and island (+0x08 / +0x0C) directly. + const ValidPos& getLastValidInfantryPos() const { return m_lastValidInfantryPos; } const ValidPos& getLastValidPosition() const; const ValidPos& getLastValidPosition(int vehicleNumber) const; void setLastValidInfantryPosInternal(const ValidPos& position); diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileDummy.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileDummy.cpp new file mode 100644 index 000000000..1aacf4d74 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileDummy.cpp @@ -0,0 +1,81 @@ +// IPIMobileDummy. Recovered from libaidll.so 1.5.3153 (ia-32), 0x2EEBA0..0x2EEFCE; the inline +// slots are in IPIMobileDummy.h. + +#include "IPIMobileDummy.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2EEE80, __tcf_0 0x2EEEE0, _GLOBAL__I 0x2EEF10). +#include + +#include "Information.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +double gameTime() +{ + return static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); +} + +} // anonymous namespace + +// ELF 0x2EEBA0 / 0x2EEC30: the speed is copied, the rotational speed zeroed, then the (empty) +// polygon update. +IPIMobileDummy::IPIMobileDummy(Information* information, Vec3& speed) + : IPIMobile(information), m_speed(speed) +{ + m_rotationalSpeed.x = 0.0f; + m_rotationalSpeed.y = 0.0f; + m_rotationalSpeed.z = 0.0f; + updateCurrentPolygon(); +} + +// ELF 0x2EECC0 / 0x2EECE0 / 0x2EED00: nothing of its own. +IPIMobileDummy::~IPIMobileDummy() +{ +} + +// ELF 0x2EED40: never a valid position; `position` is untouched. +bool IPIMobileDummy::getValidPosition(Vec3& /*position*/) +{ + return false; +} + +// ELF 0x2EED50: the information's position (Information +12). +void IPIMobileDummy::getPositionEstimate(Vec3& position) +{ + position = m_information->getPosition(); +} + +// ELF 0x2EED90: the information's position, moved by the speed (through +7) over the time from +// now to `time`. +void IPIMobileDummy::getPositionEstimate(double time, Vec3& position) +{ + position = m_information->getPosition(); + const float dt = static_cast(time - gameTime()); + const Vec3& speed = getSpeed(); + position.x += speed.x * dt; + position.y += speed.y * dt; + position.z += speed.z * dt; +} + +// ELF 0x2EEE30: setTime(double) through the vtable with the game time. +void IPIMobileDummy::setTime() +{ + setTime(gameTime()); +} + +// ELF 0x2EEE70. Empty; the image keeps a 0x148-byte frame and no code (the body's locals were +// compiled out). +void IPIMobileDummy::updateCurrentPolygon() +{ +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileDummy.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileDummy.h new file mode 100644 index 000000000..aeb3e58e9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileDummy.h @@ -0,0 +1,54 @@ +// Placeholder mobile plug-in that is not backed by an engine object: it keeps a fixed speed and a +// zero rotational speed and estimates positions from its information's position. The sound, +// sector, portal and valid-position slots (+10, +13..+16) stay pure, so the class is abstract; +// nothing in libaidll.so constructs it or derives from it. +// Evidence: libaidll.so 1.5.3153 (ia-32) 0x2EEBA0..0x2EEFCE, vtable 0x4BED00 (18 slots); +// FILE symbol IPIMobileDummy.cpp. + +#ifndef AI_AIDLL_AI_AIKNOWLEDGE_IPIMOBILEDUMMY_H +#define AI_AIDLL_AI_AIKNOWLEDGE_IPIMOBILEDUMMY_H + +#include + +#include "IPIMobile.h" + +namespace dice { +namespace hfe { +namespace ai { + +class IPIMobileDummy : public IPIMobile +{ +public: + // The plug-in of `information`, moving at `speed`. + IPIMobileDummy(Information* information, Vec3& speed); + virtual ~IPIMobileDummy(); + + virtual void setTime(); // +3 + virtual void setTime(double) {} // +4 ELF 0x2EEF50 + virtual void setHasContact() {} // +5 ELF 0x2EEF30 + virtual void setLostContact() {} // +6 ELF 0x2EEF40 + virtual const Vec3& getSpeed() { return m_speed; } // +7 ELF 0x2EEF60 + virtual const Vec3& getRotationalSpeed() { return m_rotationalSpeed; } // +8 ELF 0x2EEF70 + virtual float getSpeedMagnitude() // +9 ELF 0x2EEF80 + { + return std::sqrt(m_speed.x * m_speed.x + m_speed.y * m_speed.y + m_speed.z * m_speed.z); + } + virtual void getPositionEstimate(Vec3& position); // +11 + virtual void getPositionEstimate(double time, Vec3& position); // +12 + // +17, new in this class. [INFERRED] bool: the body materializes 0 and has no caller. + virtual bool getValidPosition(Vec3& position); + + // Non-virtual; empty in the image. + void updateCurrentPolygon(); + +protected: + // ELF layout; sizeof 0x60. + /* +0x48 */ Vec3 m_speed; + /* +0x54 */ Vec3 m_rotationalSpeed; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIKNOWLEDGE_IPIMOBILEDUMMY_H diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileKnown.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileKnown.cpp index 22e42b3e6..df3a5d694 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileKnown.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileKnown.cpp @@ -1,11 +1,18 @@ // so and AIDLL_w32ded.dll . +#if defined(__APPLE__) +#include "../../../../Platform/X87Compat.h" // [CHOSEN, not recovered] +#endif #include "IPIMobileKnown.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2EF6C0, __tcf_0 0x2EF720, _GLOBAL__I 0x2EF750). +#include + #include #include "Information.h" -#include "InformationManager.h" +#include "../Main/InformationManager.h" #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" #include "../../../AIInterface/BFKnowledge/IAIObject.h" @@ -111,6 +118,7 @@ void IPIMobileKnown::getPositionEstimate(Vec3& position) position); } +// ELF 0x2EF4B0. void IPIMobileKnown::getPositionEstimate(double time, Vec3& position) { #if defined(_MSC_VER) @@ -124,6 +132,24 @@ void IPIMobileKnown::getPositionEstimate(double time, Vec3& position) position.x = scaledX; position.y = scaledY; position.z = scaledZ; +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + // [PLATFORM] ELF rounds age before security and retains one x87-wide scale for X/Y/Z. + const float age = static_cast(m_time - time); + const float security = m_information->getSecurity(time); + const bf2x87::Real wideScale = + static_cast(security) * static_cast(age); + const float scaledX = + static_cast(static_cast(m_speed.x) * wideScale); + const float scaledY = + static_cast(static_cast(m_speed.y) * wideScale); + const float scaledZ = + static_cast(static_cast(m_speed.z) * wideScale); + // ELF materializes its temporary Vec3 in Z, X, Y store order. + position.z = scaledZ; + position.x = scaledX; + position.y = scaledY; #else // [PLATFORM] ELF rounds age before security and retains one x87-wide scale for X/Y/Z. const float age = static_cast(m_time - time); @@ -140,6 +166,7 @@ void IPIMobileKnown::getPositionEstimate(double time, Vec3& position) position.z = scaledZ; position.x = scaledX; position.y = scaledY; +#endif #endif const Vec3& knownPosition = m_information->getPosition(); position.x += knownPosition.x; diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileReal.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileReal.cpp index b9be8dafd..efdde7946 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileReal.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileReal.cpp @@ -1,7 +1,14 @@ // so and AIDLL_w32ded.dll . +#if defined(__APPLE__) +#include "../../../../Platform/X87Compat.h" // [CHOSEN, not recovered] +#endif #include "IPIMobileReal.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2EFB80, __tcf_0 0x2EFBE0, _GLOBAL__I 0x2EFC10). +#include + #include #include "Information.h" @@ -66,6 +73,7 @@ void IPIMobileReal::getPositionEstimate(Vec3& position) position = m_information->getPosition(); } +// ELF 0x2EF900. The information's position moved by the speed over (time - now). void IPIMobileReal::getPositionEstimate(double time, Vec3& position) { position = m_information->getPosition(); @@ -81,6 +89,21 @@ void IPIMobileReal::getPositionEstimate(double time, Vec3& position) position.x = static_cast(scaledX + static_cast(position.x)); position.y = static_cast(static_cast(scaledY) + position.y); position.z = static_cast(static_cast(scaledZ) + position.z); +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + // [PLATFORM] ELF calls the timer first and rounds the delta before calling speed. + const float difference = static_cast( + time - static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime()); + const Vec3& speed = getSpeed(); + const bf2x87::Real scaledX = static_cast(speed.x) * difference; + const float scaledY = + static_cast(static_cast(speed.y) * difference); + const float scaledZ = + static_cast(static_cast(speed.z) * difference); + position.x = static_cast(scaledX + static_cast(position.x)); + position.y = static_cast(static_cast(scaledY) + position.y); + position.z = static_cast(static_cast(scaledZ) + position.z); #else // [PLATFORM] ELF calls the timer first and rounds the delta before calling speed. const float difference = static_cast( @@ -95,6 +118,7 @@ void IPIMobileReal::getPositionEstimate(double time, Vec3& position) position.y = static_cast(static_cast(scaledY) + position.y); position.z = static_cast(static_cast(scaledZ) + position.z); #endif +#endif } unsigned int IPIMobileReal::getSector() const diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysical.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysical.h index 37bdb0c12..5c534b0ab 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysical.h +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysical.h @@ -40,7 +40,9 @@ class IPIPhysical : public InformationPlugIn virtual Vec3 getSphereLocalOffset() const = 0; // +12 by value (corrected) virtual float getSmallestRadius() const = 0; // +13 - virtual void getSubSpheres2d(std::vector&) const = 0; // +14 + // float: IPIPhysicalReal/Known (ELF 0x2F0CA0 / 0x2F05F0) leave the engine call's x87 result + // as theirs (no pop), and IPIPhysicalDummy (ELF 0x2F0000) loads 0.0f. + virtual float getSubSpheres2d(std::vector&) const = 0; // +14 float (corrected) virtual float getArmour(Vec3&) = 0; // +15 virtual float getBestArmour() = 0; // +16 virtual int getStrengthType() = 0; // +17 diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalDummy.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalDummy.cpp new file mode 100644 index 000000000..fc1542c69 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalDummy.cpp @@ -0,0 +1,93 @@ +// IPIPhysicalDummy. Recovered from libaidll.so 1.5.3153 (ia-32), 0x2EFC50..0x2F018B; the inline +// slots are in IPIPhysicalDummy.h. + +#include "IPIPhysicalDummy.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2EFF40, __tcf_0 0x2EFFA0, _GLOBAL__I 0x2EFFD0). +#include +#include + +#include "Information.h" +#include "../AIUtils/CustomCurve.h" // SCurve::calculate (static) +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" // IBFTimer::getGameTime +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" // IAIObject, IAIObjectPhysical + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2EFC50 / 0x2EFCC0: the arguments in order; m_mod, m_inAir and m_inWater are not written. +IPIPhysicalDummy::IPIPhysicalDummy(Information* information, float health, + BoundingBox* boundingBox, LocalBoundingBox* localBoundingBox, + float radius, float armour, float bestArmour, + int strengthType, float volume, float mass, + bool touchingTerrain, int material) +{ + m_information = information; + m_health = health; + m_boundingBox = boundingBox; + m_localBoundingBox = localBoundingBox; + m_radius = radius; + m_armour = armour; + m_bestArmour = bestArmour; + m_strengthType = strengthType; + m_volume = volume; + m_mass = mass; + m_touchingTerrain = touchingTerrain; + m_material = material; +} + +// ELF 0x2EFD30 / 0x2EFD80 / 0x2EFDD0: deletes the bounding box, then the local bounding box +// (scalar deallocation, no visible destructor call; BoundingBox is incomplete here, as in +// IPICover). +IPIPhysicalDummy::~IPIPhysicalDummy() +{ + ::operator delete(m_boundingBox); + delete m_localBoundingBox; +} + +// ELF 0x2EFE30: setTime(double) through the vtable with the game time. +void IPIPhysicalDummy::setTime() +{ + setTime(static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime()); +} + +// ELF 0x2EFE70. Ignores the time. Takes the health from the information's ENGINE object +// (IAIObject +0x94 physical; the dummy record's object is not tested) when its maximum health is +// positive, else zero, and sets the modifier to 0.5 + 0.5 * SCurve(health), as +// IPIPhysicalReal::setTime does. ELF comparison: a NaN maximum selects zero (PE not compared). +void IPIPhysicalDummy::setTime(double /*time*/) +{ + IAIObjectPhysical* const physical = m_information->getAIObject()->getPhysical(); // +0x94 + if (physical->getMaxHealth() > 0.0f) // +0x1C + m_health = physical->getHealth(); // +0x18 + else + m_health = 0.0f; + const float half = 0.5f; + m_mod = half; + m_mod = SCurve::calculate(m_health) * half + m_mod; +} + +// ELF 0x2EFEF0: the engine object's maximum health (IAIObjectPhysical +0x1C). +float IPIPhysicalDummy::getMaxHealth() +{ + return m_information->getAIObject()->getPhysical()->getMaxHealth(); +} + +// ELF 0x2EFF20. +int IPIPhysicalDummy::getMaterial() const +{ + return m_material; +} + +// ELF 0x2EFF30. Empty; the image keeps a 0x148-byte frame and no code (the body's locals were +// compiled out). +void IPIPhysicalDummy::setHealth(float /*health*/) +{ +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalDummy.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalDummy.h new file mode 100644 index 000000000..576cbc3f9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalDummy.h @@ -0,0 +1,86 @@ +// Placeholder physical plug-in that answers from values given at construction. It owns the +// bounding box and local bounding box it is given. The man-down slots (+21..+23) stay pure, so +// the class is abstract; nothing in libaidll.so constructs it or derives from it. +// Evidence: libaidll.so 1.5.3153 (ia-32) 0x2EFC50..0x2F018B, vtable 0x4BEEE0 (27 slots); +// FILE symbol IPIPhysicalDummy.cpp. + +#ifndef AI_AIDLL_AI_AIKNOWLEDGE_IPIPHYSICALDUMMY_H +#define AI_AIDLL_AI_AIKNOWLEDGE_IPIPHYSICALDUMMY_H + +#include "IPIPhysical.h" +#include "../../../../Math/LocalBoundingBox.h" + +namespace dice { +namespace hfe { +namespace ai { + +class IPIPhysicalDummy : public IPIPhysical +{ +public: + // Takes ownership of `boundingBox` and `localBoundingBox`. The modifier and the in-air and + // in-water flags are left as allocated. + IPIPhysicalDummy(Information* information, float health, BoundingBox* boundingBox, + LocalBoundingBox* localBoundingBox, float radius, float armour, + float bestArmour, int strengthType, float volume, float mass, + bool touchingTerrain, int material); + virtual ~IPIPhysicalDummy(); + + virtual void setTime(); // +3 + virtual void setTime(double time); // +4 + virtual float getHealth() const { return m_health; } // +5 ELF 0x2F0020 + virtual void setHealth(float health); // +6 + virtual float getMaxHealth(); // +7 + virtual float getMod() { return m_mod; } // +8 ELF 0x2F0030 + virtual BoundingBox* getBoundingBox() { return m_boundingBox; } // +9 ELF 0x2F0040 + virtual const LocalBoundingBox* getLocalBoundingBox() // +10 ELF 0x2F0050 + { + return m_localBoundingBox; + } + virtual float getRadius() { return m_radius; } // +11 ELF 0x2F0060 + virtual Vec3 getSphereLocalOffset() const // +12 ELF 0x2F0070 + { + if (m_localBoundingBox->m_derivedDataDirty) + m_localBoundingBox->calcRadius(); + return m_localBoundingBox->m_centre; + } + virtual float getSmallestRadius() const // +13 ELF 0x2F00D0 + { + if (m_localBoundingBox->m_derivedDataDirty) + m_localBoundingBox->calcRadius(); + return m_localBoundingBox->m_radiusFromCentre; + } + virtual float getSubSpheres2d(std::vector&) const { return 0.0f; } // +14 ELF 0x2F0000 + virtual float getArmour(Vec3&) { return m_armour; } // +15 ELF 0x2F0110 + virtual float getBestArmour() { return m_bestArmour; } // +16 ELF 0x2F0120 + virtual int getStrengthType() { return m_strengthType; } // +17 ELF 0x2F0130 + virtual float getVolume() { return m_volume; } // +18 ELF 0x2F0140 + virtual float getMass() { return m_mass; } // +19 ELF 0x2F0150 + virtual int getMaterial() const; // +20 + // +21..+23 (getManDownTimeLeft, getMaxManDownTime, getManDown) stay pure. + virtual bool isTouchingTerrain(Vec3&) const { return m_touchingTerrain; } // +24 ELF 0x2F0160 + virtual bool isInAir() const { return m_inAir; } // +25 ELF 0x2F0170 + virtual bool isInWater() const { return m_inWater; } // +26 ELF 0x2F0180 + +protected: + // ELF layout; sizeof 0x38. + /* +0x08 */ float m_mod; // set by setTime(double) + /* +0x0C */ float m_health; + /* +0x10 */ BoundingBox* m_boundingBox; // owned + /* +0x14 */ LocalBoundingBox* m_localBoundingBox; // owned + /* +0x18 */ float m_radius; + /* +0x1C */ float m_armour; + /* +0x20 */ float m_bestArmour; + /* +0x24 */ int m_strengthType; + /* +0x28 */ float m_volume; + /* +0x2C */ float m_mass; + /* +0x30 */ bool m_touchingTerrain; + /* +0x31 */ bool m_inAir; // no writer in the image + /* +0x32 */ bool m_inWater; // no writer in the image + /* +0x34 */ int m_material; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIKNOWLEDGE_IPIPHYSICALDUMMY_H diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalKnown.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalKnown.cpp new file mode 100644 index 000000000..4d2c99405 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalKnown.cpp @@ -0,0 +1,187 @@ +// IPIPhysicalKnown. Recovered from libaidll.so 1.5.3153 (ia-32), 0x2F0190..0x2F07CB; vtable +// 0x4BEFC0 (same 27 slots as IPIPhysicalReal's). The forwarders use the same IAIObjectPhysical +// slots as IPIPhysicalReal's. + +#include "IPIPhysicalKnown.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2F0690, __tcf_0 0x2F06F0, _GLOBAL__I 0x2F0720). +#include + +#include "Information.h" +#include "../AIUtils/CustomCurve.h" // SCurve::calculate (static) +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" // IAIObject, IAIObjectPhysical + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +IAIObjectPhysical* physicalOf(Information* information) +{ + return information->getAIObject()->getPhysical(); // +0x94 +} + +} // anonymous namespace + +// 0x2F0190: flags false, terrain position zero; health and modifier stay as allocated. +IPIPhysicalKnown::IPIPhysicalKnown(Information* information) +{ + m_information = information; + m_touchingTerrain = false; + m_terrainPosition.x = 0.0f; + m_terrainPosition.y = 0.0f; + m_terrainPosition.z = 0.0f; + m_inAir = false; + m_inWater = false; + m_manDown = false; +} + +IPIPhysicalKnown::~IPIPhysicalKnown() +{ +} + +// 0x2F02B0. +void IPIPhysicalKnown::setTime() +{ + setTime(static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime()); +} + +// 0x2F02F0. Caches man-down, the absolute health (zero unless the maximum is positive; a NaN +// maximum gives zero, the ELF comparison), the modifier 0.5 + 0.5 * SCurve(health) and the +// terrain/air/water state. +void IPIPhysicalKnown::setTime(double /*time*/) +{ + IAIObjectPhysical* const physical = physicalOf(m_information); + m_manDown = physical->getManDown(); // +0x68 + if (physical->getMaxHealth() > 0.0f) // +0x1C + m_health = physical->getHealth(); // +0x18 + else + m_health = 0.0f; + const float half = 0.5f; + m_mod = half; + m_mod = SCurve::calculate(m_health) * half + m_mod; + m_touchingTerrain = physical->isTouchingTerrain(m_terrainPosition); // +0x50 + m_inAir = physical->isInAir(); // +0x54 + m_inWater = physical->isInWater(); // +0x58 +} + +float IPIPhysicalKnown::getHealth() const +{ + return m_health; +} + +void IPIPhysicalKnown::setHealth(float health) +{ + m_health = health; +} + +float IPIPhysicalKnown::getMaxHealth() +{ + return physicalOf(m_information)->getMaxHealth(); // +0x1C +} + +float IPIPhysicalKnown::getMod() +{ + return m_mod; +} + +BoundingBox* IPIPhysicalKnown::getBoundingBox() +{ + return physicalOf(m_information)->getCurrentBoundingBox(); // +0x34 +} + +const LocalBoundingBox* IPIPhysicalKnown::getLocalBoundingBox() +{ + return physicalOf(m_information)->getLocalBoundingBox(); // +0x30 +} + +float IPIPhysicalKnown::getRadius() +{ + return physicalOf(m_information)->getRadius(); // +0x3C +} + +Vec3 IPIPhysicalKnown::getSphereLocalOffset() const +{ + return physicalOf(m_information)->getSphereLocalOffset(); // +0x40 +} + +float IPIPhysicalKnown::getSmallestRadius() const +{ + return physicalOf(m_information)->getSmallestRadius(); // +0x44 +} + +// ELF 0x2F05F0: forwards, returning the engine plug-in's answer. +float IPIPhysicalKnown::getSubSpheres2d(std::vector& out) const +{ + return physicalOf(m_information)->getSubSpheres2d(out); // +0x48 +} + +float IPIPhysicalKnown::getArmour(Vec3& direction) +{ + return physicalOf(m_information)->getArmour(direction); // +0x28 +} + +float IPIPhysicalKnown::getBestArmour() +{ + return physicalOf(m_information)->getBestArmour(); // +0x2C +} + +int IPIPhysicalKnown::getStrengthType() +{ + return physicalOf(m_information)->getStrType(); // +0x4C +} + +float IPIPhysicalKnown::getVolume() +{ + return physicalOf(m_information)->getVolume(); // +0x24 +} + +float IPIPhysicalKnown::getMass() +{ + return physicalOf(m_information)->getMass(); // +0x20 +} + +int IPIPhysicalKnown::getMaterial() const +{ + return physicalOf(m_information)->getMaterial(); // +0x5C +} + +float IPIPhysicalKnown::getManDownTimeLeft() const +{ + return physicalOf(m_information)->getManDownTimeLeft(); // +0x60 +} + +float IPIPhysicalKnown::getMaxManDownTime() const +{ + return physicalOf(m_information)->getMaxManDownTime(); // +0x64 +} + +bool IPIPhysicalKnown::getManDown() const +{ + return m_manDown; +} + +// 0x2F0770: the cached terrain position and flag. +bool IPIPhysicalKnown::isTouchingTerrain(Vec3& position) const +{ + position = m_terrainPosition; + return m_touchingTerrain; +} + +bool IPIPhysicalKnown::isInAir() const +{ + return m_inAir; +} + +bool IPIPhysicalKnown::isInWater() const +{ + return m_inWater; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalKnown.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalKnown.h new file mode 100644 index 000000000..5a67b79a4 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalKnown.h @@ -0,0 +1,60 @@ +// Physical information about an object of another side. Health, modifier and the terrain/air/ +// water/man-down flags are cached at each setTime; the shape and armour queries forward to the +// engine object's physical plug-in. Health is cached as the absolute value (InformationReal's +// counterpart answers a fraction). The constructor leaves health and modifier unset. +// [INFERRED] Source placement beside IPIPhysicalReal. +#ifndef AI_AIDLL_AI_AIKNOWLEDGE_IPIPHYSICALKNOWN_H +#define AI_AIDLL_AI_AIKNOWLEDGE_IPIPHYSICALKNOWN_H + +#include "IPIPhysical.h" + +namespace dice { +namespace hfe { +namespace ai { + +class IPIPhysicalKnown : public IPIPhysical +{ +public: + explicit IPIPhysicalKnown(Information* information); + virtual ~IPIPhysicalKnown(); + + virtual void setTime(); // +3 - now + virtual void setTime(double time); // +4 + virtual float getHealth() const; // +5 - cached + virtual void setHealth(float health); // +6 - stores + virtual float getMaxHealth(); // +7 + virtual float getMod(); // +8 - cached + virtual BoundingBox* getBoundingBox(); // +9 + virtual const LocalBoundingBox* getLocalBoundingBox(); // +10 + virtual float getRadius(); // +11 + virtual Vec3 getSphereLocalOffset() const; // +12 + virtual float getSmallestRadius() const; // +13 + virtual float getSubSpheres2d(std::vector& out) const; // +14 + virtual float getArmour(Vec3& direction); // +15 + virtual float getBestArmour(); // +16 + virtual int getStrengthType(); // +17 + virtual float getVolume(); // +18 + virtual float getMass(); // +19 + virtual int getMaterial() const; // +20 + virtual float getManDownTimeLeft() const; // +21 + virtual float getMaxManDownTime() const; // +22 + virtual bool getManDown() const; // +23 - cached + virtual bool isTouchingTerrain(Vec3& position) const; // +24 - cached + virtual bool isInAir() const; // +25 - cached + virtual bool isInWater() const; // +26 - cached + +private: + /* +0x08 */ float m_mod; // not initialised by the constructor + /* +0x0C */ float m_health; // not initialised by the constructor + /* +0x10 */ bool m_touchingTerrain; + /* +0x14 */ Vec3 m_terrainPosition; + /* +0x20 */ bool m_inAir; + /* +0x21 */ bool m_inWater; + /* +0x22 */ bool m_manDown; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIKNOWLEDGE_IPIPHYSICALKNOWN_H diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalReal.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalReal.cpp index bc9a7eb78..78ca16b34 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalReal.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalReal.cpp @@ -1,8 +1,12 @@ #include "IPIPhysicalReal.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2F0D60, __tcf_0 0x2F0DC0, _GLOBAL__I 0x2F0DF0). +#include + #include "Information.h" -#include "../AIBotBehaviour/CustomCurve.h" // SCurve::calculate (static) +#include "../AIUtils/CustomCurve.h" // SCurve::calculate (static) #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" // IBFTimer::getGameTime #include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" // IAIObject, IAIObjectPhysical @@ -104,9 +108,10 @@ float IPIPhysicalReal::getSmallestRadius() const return m_information->getAIObject()->getPhysical()->getSmallestRadius(); // +0x44 } -void IPIPhysicalReal::getSubSpheres2d(std::vector& out) const +// ELF 0x2F0CA0: forwards, returning the engine plug-in's answer. +float IPIPhysicalReal::getSubSpheres2d(std::vector& out) const { - m_information->getAIObject()->getPhysical()->getSubSpheres2d(out); // +0x48 + return m_information->getAIObject()->getPhysical()->getSubSpheres2d(out); // +0x48 } float IPIPhysicalReal::getArmour(Vec3& direction) diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalReal.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalReal.h index 4b0b72cb4..52c8ccfbf 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalReal.h +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalReal.h @@ -29,7 +29,7 @@ class IPIPhysicalReal : public IPIPhysical virtual float getRadius(); // +11 virtual Vec3 getSphereLocalOffset() const; // +12 virtual float getSmallestRadius() const; // +13 - virtual void getSubSpheres2d(std::vector& out) const; // +14 + virtual float getSubSpheres2d(std::vector& out) const; // +14 virtual float getArmour(Vec3& direction); // +15 virtual float getBestArmour(); // +16 virtual int getStrengthType(); // +17 diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIUnit.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIUnit.cpp index de3480d97..a78a0443f 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIUnit.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIUnit.cpp @@ -3,12 +3,16 @@ // Retail deliberately omits null and bounds guards in these paths. #include "IPIUnit.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2F1CC0, __tcf_0 0x2F1D20, _GLOBAL__I 0x2F1D50). +#include + #include "Information.h" #include "IPIArmament.h" #include "IPIPhysical.h" #include "WeaponInfo.h" -#include "WeaponInfoManager.h" -#include "../AIBotBehaviour/CustomCurve.h" // SCurve::calculate (static) +#include "../AIUtils/WeaponInfoManager.h" +#include "../AIUtils/CustomCurve.h" // SCurve::calculate (static) #include "../AIUtils/checkPointer.h" #include "../Main/AISettingsInterfaces.h" #include "../Main/CommonSingletonServer.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/Information.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/Information.cpp index 961210f43..0039931e2 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/Information.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/Information.cpp @@ -1,13 +1,17 @@ // [INFERRED] Source placement. #include "Information.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2D9460, __tcf_0 0x2D94C0, _GLOBAL__I 0x2D94F0). +#include + #include "IPIArmament.h" #include "IPIControlInfo.h" #include "IPICover.h" #include "IPIMobile.h" #include "IPIPhysical.h" #include "IPIUnit.h" -#include "InformationManager.h" +#include "../Main/InformationManager.h" #include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" // IAIObject, IAIObjectMobile namespace dice { namespace hfe { namespace ai { @@ -15,7 +19,7 @@ namespace dice { namespace hfe { namespace ai { // the time, the owner, not booked, no plug-in. The // +0x04..+0x14 prefix is not touched here (the subclass constructors write it). Information::Information(IAIObject* object, double time) - : m_time(time), m_object(object), m_booked(false), m_bookingPlayerId(-1), + : m_time(time), m_object(object), m_isBooked(false), m_bookingPlayerId(-1), m_armament(0), m_controlInfo(0), m_cover(0), m_mobile(0), m_physical(0), m_unit(0) { } @@ -259,7 +263,7 @@ int Information::getBookingPlayerId() bool Information::isBooked() { - return m_booked; + return m_isBooked; } // Compares the id alone - a cancelled booking (-1) is "booked by" player -1. @@ -270,13 +274,13 @@ bool Information::isBookedBy(int playerId) void Information::bookVehicle(int playerId) { - m_booked = true; + m_isBooked = true; m_bookingPlayerId = playerId; } void Information::cancelBookVehicle() { - m_booked = false; + m_isBooked = false; m_bookingPlayerId = -1; } diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/Information.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/Information.h index 0d25ae78e..a7f10d1af 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/Information.h +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/Information.h @@ -11,6 +11,7 @@ #include "../../../../Math/Vec3.h" #include "../../../AIInterface/BFKnowledge/SoldierPose.h" +#include "../../../AIInterface/BFKnowledge/InformationType.h" namespace dice { namespace hfe { @@ -107,27 +108,41 @@ class Information IPIPhysical* getPhysical() const { return m_physical; } IPIUnit* getUnit() const { return m_unit; } unsigned int getObjectTypeFlags() const { return m_objectTypeFlags; } + // DICE's name and form: AIDLL_r.dll (BoosterPack2 debug build) asserts + // "!targetPrimaryInfo->isOfType(ITSoldier)" (BBPChange.cpp, 0x100FD302) and inlines it as + // `(types >> n) & 1` (shr 0x15 / test 1); "Object has no cover plugin but is of type ITCover" + // (BFInformationEnvironment.cpp, 0x101A8419) tests bit 14. Bit n is InformationType n + // (AIDLL_r's enum-to-string switch 0x100D3010, jump table 0x100D32EC: 0 ITProduction .. 26 + // ITHasCarHorn). Both retail images expand it inline as a single-bit test. + bool isOfType(InformationType type) const { return ((m_objectTypeFlags >> type) & 1) != 0; } float getStrength() const { return m_strength; } + // BotMain::updateBotVehicle (ELF 0x18BCC0) scales +0x10 inline (x0.75 / x1.3333334). + void setStrength(float strength) { m_strength = strength; } + // [INFERRED] name; SAIMap::updateInformation (ELF 0x3641F0) copies +0x14 into +0x10 inline. + float getBasicTemp() const { return m_basicTemp; } bool hasMobile() const { return m_mobile != nullptr; } IPIMobile* getMobile() const { return m_mobile; } + // [INFERRED] inline reader of +0x34 (InfoCoverPredicate 0x2E7E80 reads it without a call). + IPICover* getCover() const { return m_cover; } IAIObject* getAIObject() const { return m_object; } bool hasArmament() const { return m_armament != nullptr; } // [INFERRED] source-level inline accessor. Both retail images read the same +0x2C member in // InformationFactory::updateInformationPlugin before the virtual updateWeapons call. IPIArmament* getArmament() const { return m_armament; } + IPIControlInfo* getControlInfo() const { return m_controlInfo; } protected: /* +0x00 */ // vptr // Offsets describe ELF. PE members are four bytes higher through +0x18 and eight higher // from the first double onward because of alignment. Original sizes: ELF 68, PE 80 bytes. - /* +0x04 */ unsigned int m_objectTypeFlags; // [INFERRED] name; InformationReal: the template's types + /* +0x04 */ unsigned int m_objectTypeFlags; // [INFERRED] name; InformationReal: the template's types (InformationType bits, see isOfType) /* +0x08 */ float m_allowedTimeDiff; // [INFERRED] name; InformationReal's constructor /* +0x0C */ unsigned char m_unwritten0C[4]; // not written by InformationReal /* +0x10 */ float m_strength; // [INFERRED] name; InformationReal: the template's basicTemp /* +0x14 */ float m_basicTemp; // [INFERRED] name; InformationReal: basicTemp again /* +0x18 */ double m_time; // the constructor's time /* +0x20 */ IAIObject* m_object; // the constructor's owner - /* +0x24 */ bool m_booked; // constructed false; bookVehicle / cancelBookVehicle + /* +0x24 */ bool m_isBooked; // constructed false; bookVehicle / cancelBookVehicle // name: AIDLL_r asserts "m_isBooked != false" / "== false" (0x10161E70) /* +0x28 */ int m_bookingPlayerId; // constructed -1 /* +0x2C */ IPIArmament* m_armament; // type 4 /* +0x30 */ IPIControlInfo* m_controlInfo; // type 5 diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationDummy.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationDummy.cpp new file mode 100644 index 000000000..529bab53a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationDummy.cpp @@ -0,0 +1,136 @@ +// InformationDummy. Recovered from libaidll.so 1.5.3153 (ia-32), 0x2D9520..0x2D9F3C; the +// inline slots are in InformationDummy.h. + +#include "InformationDummy.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2D9D20, __tcf_0 0x2D9D80, _GLOBAL__I 0x2D9DB0). +#include + +#include + +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +IAITerrain* terrain() +{ + return static_cast(CommonSingletonServer::m_iaiTerrain); +} + +} // anonymous namespace + +// ELF 0x2D9520 / 0x2D9680. No owner, time -1. The transformation member is zeroed (the shipped +// Mat4 member construction) and then copied; the name is assigned after the side and types. +InformationDummy::InformationDummy(Vec3& position, Mat4& transformation, int side, + unsigned int types) + : Information(0, -1.0), m_position(position) +{ + for (int i = 0; i < 16; ++i) + m_transformation.m[i] = 0.0f; + m_transformation = transformation; + m_objectTypeFlags = types; + m_side = side; + m_name = "DummyInformation"; +} + +// ELF 0x2D97E0 / 0x2D98E0. Zeroed, set to identity, then the three rows are overwritten with +// (0,0,1), (0,1,0), (1,0,0) and the translation with the position. The name stays empty. +InformationDummy::InformationDummy(Vec3& position, int side, unsigned int types) + : Information(0, -1.0), m_position(position) +{ + for (int i = 0; i < 16; ++i) + m_transformation.m[i] = 0.0f; + m_transformation.m[0] = 1.0f; + m_transformation.m[5] = 1.0f; + m_transformation.m[10] = 1.0f; + m_transformation.m[15] = 1.0f; + + m_transformation.m[0] = 0.0f; + m_transformation.m[1] = 0.0f; + m_transformation.m[2] = 1.0f; + m_transformation.m[4] = 0.0f; + m_transformation.m[5] = 1.0f; + m_transformation.m[6] = 0.0f; + m_transformation.m[8] = 1.0f; + m_transformation.m[9] = 0.0f; + m_transformation.m[10] = 0.0f; + m_transformation.m[12] = m_position.x; + m_transformation.m[13] = m_position.y; + m_transformation.m[14] = m_position.z; + m_objectTypeFlags = types; + m_side = side; +} + +// ELF 0x2D99E0 / 0x2D9A50 / 0x2D9AC0: the name, then the base (which destroys the plug-ins). +InformationDummy::~InformationDummy() +{ +} + +// ELF 0x2D9CE0: the terrain's altitude at the position (IAITerrain +0xC). +float InformationDummy::getAltitude() +{ + return terrain()->getAltitude(m_position); +} + +// ELF 0x2D9B30. The lowest terrain altitude sampled along `direction` in sixth steps: the start, +// then from the second step on (the first step is added twice, as InformationReal does with its +// tenth steps). A direction no longer than one step samples only the start. +float InformationDummy::getAltitude(const Vec3& direction) +{ + Vec3 probe; + probe.x = 0.0f; + probe.y = 0.0f; + probe.z = 0.0f; + Vec3 step; + step.x = 0.0f; + step.y = 0.0f; + step.z = 0.0f; + const float length = + std::sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z); + probe = m_position; + float lowest = terrain()->getAltitude(probe); + + const float scale = 1.0f / 6.0f; + step.x = direction.x * scale; + step.y = direction.y * scale; + step.z = direction.z * scale; + const float stepLength = length / 6.0f; + probe.x += step.x; + probe.y += step.y; + probe.z += step.z; + float travelled = stepLength; + while (length > travelled) + { + probe.x += step.x; + probe.y += step.y; + probe.z += step.z; + const float altitude = terrain()->getAltitude(probe); + travelled += stepLength; + lowest = altitude > lowest ? lowest : altitude; + } + return lowest; +} + +// ELF 0x2D9CA0: no secondary objects; the iterator is reset to -1. +unsigned int InformationDummy::getSecondaryObject(int& iterator, int /*side*/) +{ + iterator = -1; + return 0xFFFFFFFFu; +} + +// ELF 0x2D9CC0: as getSecondaryObject. +unsigned int InformationDummy::getFirstSecondaryObject(int& iterator, int /*side*/) +{ + iterator = -1; + return 0xFFFFFFFFu; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationDummy.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationDummy.h new file mode 100644 index 000000000..cd3633eb1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationDummy.h @@ -0,0 +1,77 @@ +// Placeholder information record that is not backed by an engine object: it answers from its own +// position, transformation, side and name, and owns its plug-ins through Information. The +// contact slots (+6..+9) stay pure, so the class is abstract; nothing in libaidll.so constructs +// it or derives from it. +// Evidence: libaidll.so 1.5.3153 (ia-32) 0x2D9520..0x2D9F3C, vtable 0x4BDF80 (29 slots); +// FILE symbol InformationDummy.cpp. + +#ifndef AI_AIDLL_AI_AIKNOWLEDGE_INFORMATIONDUMMY_H +#define AI_AIDLL_AI_AIKNOWLEDGE_INFORMATIONDUMMY_H + +#include + +#include "Information.h" +#include "../../../../Math/Mat4.h" + +namespace dice { +namespace hfe { +namespace ai { + +class InformationDummy : public Information +{ +public: + // A dummy at `position` with `transformation`, of `side`, carrying the object types `types`; + // named "DummyInformation". + InformationDummy(Vec3& position, Mat4& transformation, int side, unsigned int types); + // A dummy at `position` with a fixed orientation (rows (0,0,1), (0,1,0), (1,0,0)) and an + // empty name. + InformationDummy(Vec3& position, int side, unsigned int types); + virtual ~InformationDummy(); + + virtual int getInformationSort() { return 2; } // +2 ELF 0x2D9DD0 + virtual bool setTime(double) { return false; } // +3 ELF 0x2D9E40 + virtual bool setTime(double, float) { return false; } // +4 ELF 0x2D9E50 + virtual double getTimeStamp() const { return 0.0f; } // +5 ELF 0x2D9E10 + // +6..+9 (addContact, removeContact, removeAllContacts, hasContact) stay pure. + virtual float getSecurity(double) { return 1.0f; } // +10 ELF 0x2D9E60 + virtual float getSecurity() { return 1.0f; } // +11 ELF 0x2D9E80 + virtual Vec3& getPosition() { return m_position; } // +12 ELF 0x2D9E30 + virtual float getAltitude(); // +13 + virtual float getAltitude(const Vec3& direction); // +14 + virtual Mat4& getTransformation() { return m_transformation; } // +15 ELF 0x2D9EA0 + virtual Vec3 getFaceing() // +16 ELF 0x2D9EB0 the third row + { + Vec3 facing; + facing.x = m_transformation.m[8]; + facing.y = m_transformation.m[9]; + facing.z = m_transformation.m[10]; + return facing; + } + virtual int getSide() const { return m_side; } // +17 ELF 0x2D9ED0 + + // New virtual slots. They hide Information's non-virtual forwarders of the same names. + virtual const std::string& getName() const { return m_name; } // +18 ELF 0x2D9F20 + virtual const std::string& getAIName() const { return m_name; } // +19 ELF 0x2D9F30 + virtual const std::string& getObjectTypeName() const { return m_name; } // +20 ELF 0x2D9EE0 + virtual unsigned int getHandle() const { return 0xFFFFFFFFu; } // +21 ELF 0x2D9DE0 + virtual bool isPrimary() const { return true; } // +22 ELF 0x2D9EF0 + virtual unsigned int getPrimaryObject(int) { return 0xFFFFFFFFu; } // +23 ELF 0x2D9F00 + virtual unsigned int getSecondaryObject(int& iterator, int side); // +24 + virtual unsigned int getFirstSecondaryObject(int& iterator, int side); // +25 + virtual int getFirstSecondaryObjectIterator() const { return -1; } // +26 ELF 0x2D9F10 + virtual bool getObjectSpawnerHolding() const { return false; } // +27 ELF 0x2D9DF0 + virtual unsigned int getObjectSpawner(int) const { return 0xFFFFFFFFu; } // +28 ELF 0x2D9E00 + +protected: + // ELF layout; sizeof 0x98. + /* +0x44 */ Vec3 m_position; + /* +0x50 */ Mat4 m_transformation; + /* +0x90 */ int m_side; + /* +0x94 */ std::string m_name; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIKNOWLEDGE_INFORMATIONDUMMY_H diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationFactory.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationFactory.cpp index 25ac28bbc..5f401abe3 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationFactory.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationFactory.cpp @@ -2,20 +2,28 @@ #include "InformationFactory.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2DB350, __tcf_0 0x2DB3B0, _GLOBAL__I 0x2DB3E0). +#include + #include #include "Information.h" -#include "InformationManager.h" +#include "../Main/InformationManager.h" +#include "InformationKnown.h" #include "InformationReal.h" +#include "IPIArmamentKnown.h" #include "IPIArmamentReal.h" #include "IPIControlInfo.h" #include "IPICover.h" #include "IPIMobileKnown.h" #include "IPIMobileReal.h" +#include "IPIPhysicalKnown.h" #include "IPIPhysicalReal.h" #include "IPIUnit.h" +#include "WeaponInfoKnown.h" #include "WeaponInfoReal.h" -#include "WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../AIUtils/checkPointer.h" #include "../../../../Core/ClassManager.h" #include "../../../../Core/Ids.h" // IID_IBase @@ -94,13 +102,16 @@ unsigned int InformationFactory::requestInformationReal(unsigned int handle, IAI } // The same with an InformationKnown -// (ELF , PE ; , / , `(object, types, time -// degeneration, basicTemp, allowedTimeDiff, side)`), registered through the same vtable slot. -// [FRONTIER] InformationKnown is not written. -unsigned int InformationFactory::requestInformationKnown(unsigned int, IAIObject*, unsigned int, - double, float, float, float, int) const +// (ELF 0x2DA1B0: `(object, types, time, degeneration, basicTemp, allowedTimeDiff, ownerSide)` +// passed through in order), registered through the same vtable slot. +unsigned int InformationFactory::requestInformationKnown(unsigned int handle, IAIObject* object, + unsigned int types, double time, + float degeneration, float basicTemp, + float allowedTimeDiff, int ownerSide) const { - BF2_AI_FRONTIER("dice::hfe::ai::InformationFactory::requestInformationKnown [InformationKnown]"); + return registerInformation(handle, checkPointer(new InformationKnown( + object, types, time, degeneration, basicTemp, + allowedTimeDiff, ownerSide))); } // the plug-in halves @@ -127,7 +138,8 @@ bool InformationFactory::requestInformationPlugin(unsigned int sourceHandle, target->setArmament(checkPointer(new IPIArmamentReal(source))); return true; } - BF2_AI_FRONTIER("dice::hfe::ai::InformationFactory::requestInformationPlugin [IPIArmamentKnown]"); + target->setArmament(checkPointer(new IPIArmamentKnown(source))); + return true; case 1: // control info - , built inline in both images, the same for real and known target->setControlInfo(checkPointer(new IPIControlInfo(source))); @@ -150,7 +162,8 @@ bool InformationFactory::requestInformationPlugin(unsigned int sourceHandle, target->setPhysical(checkPointer(new IPIPhysicalReal(source))); return true; } - BF2_AI_FRONTIER("dice::hfe::ai::InformationFactory::requestInformationPlugin [IPIPhysicalKnown]"); + target->setPhysical(checkPointer(new IPIPhysicalKnown(source))); + return true; case 5: // unit - IPIUnit , the same for real and known; `real` is ignored target->setUnit(checkPointer(new IPIUnit(source))); @@ -179,13 +192,13 @@ bool InformationFactory::updateInformationPlugin(unsigned int handle, int type) // A WeaponInfoReal for the owning // side, else a WeaponInfoKnown (ELF / PE ), each built on the IWeapon and registered through -// the vtable (registerWeapon, ELF +0x3C / PE +0x38). The Real arm is written; Known remains named. +// the vtable (registerWeapon, ELF +0x3C / PE +0x38). unsigned int InformationFactory::requestWeaponInfo(unsigned int handle, IWeapon* weapon, bool real) const { if (real) return registerWeapon(handle, checkPointer(new WeaponInfoReal(weapon))); - BF2_AI_FRONTIER("dice::hfe::ai::InformationFactory::requestWeaponInfo [WeaponInfoKnown]"); + return registerWeapon(handle, checkPointer(new WeaponInfoKnown(weapon))); } // lookups diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationKnown.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationKnown.cpp new file mode 100644 index 000000000..66d19c6f4 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationKnown.cpp @@ -0,0 +1,367 @@ +// InformationKnown. Recovered from libaidll.so 1.5.3153 (ia-32), 0x2DB4B0..0x2DC5F5 +// (Ghidra + 0x10000); vtable 0x4BE100 has the same 18 slots as InformationReal's. + +#include "InformationKnown.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2DC4D0, __tcf_0 0x2DC530, _GLOBAL__I 0x2DC560). +#include + +#include + +#include "BFInformationEnvironment.h" // IAIInformationEnvironmentModifiers +#include "IPIMobile.h" +#include "IPIPhysical.h" +#include "IPIUnit.h" +#include "../Main/InformationManager.h" +#include "../AIUtils/CustomCurve.h" // SCurve::calculate (static) +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +IAITerrain* terrain() +{ + return static_cast(CommonSingletonServer::m_iaiTerrain); +} + +double gameTime() +{ + return static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); +} + +} // anonymous namespace + +// 0x2DB4B0. The base time is -1 (never updated); the last update is the given time. The cached +// position starts at zero and the transformation at identity, then both take the object's +// current values; the object's side is cached, contact count 0. +InformationKnown::InformationKnown(IAIObject* object, unsigned int types, double time, + float degeneration, float basicTemp, float allowedTimeDiff, + int ownerSide) + : Information(object, -1.0) +{ + m_lastUpdate = time; + m_degeneration = degeneration; + m_lastPosition.x = 0.0f; + m_lastPosition.y = 0.0f; + m_lastPosition.z = 0.0f; + for (int i = 0; i < 16; ++i) + m_lastTransformation.m[i] = 0.0f; + m_lastTransformation.m[0] = 1.0f; + m_lastTransformation.m[5] = 1.0f; + m_lastTransformation.m[10] = 1.0f; + m_lastTransformation.m[15] = 1.0f; + m_ownerSide = ownerSide; + m_contacts = 0; + m_allowedTimeDiff = allowedTimeDiff; + m_strength = basicTemp; + m_basicTemp = basicTemp; + m_objectTypeFlags = types; + m_side = m_object->getSide(); // +0x12C + storeLastSeen(); +} + +// 0x2DB7F0 / 0x2DB870: the base destroys the plug-ins. +InformationKnown::~InformationKnown() +{ +} + +void InformationKnown::storeLastSeen() +{ + m_lastPosition = m_object->getPosition(); // +0xD4 + m_lastTransformation = m_object->getTransformation(); // +0xDC +} + +// 0x2DC580: a known information is sort 1. +int InformationKnown::getInformationSort() +{ + return 1; +} + +// 0x2DB9B0: setTime(double) through the vtable with the game time. +bool InformationKnown::setTime() +{ + return setTime(gameTime()); // +3 +} + +// 0x2DBA00. Updates are throttled: unless the time is past the last full update plus the +// allowed difference, only the timestamp moves and the answer is false. Otherwise: without +// contact the last-seen state is refreshed and the mobile plug-in is told contact was lost; +// the mobile plug-in gets the time; a primary object passes the time to its secondary +// objects' information (looked up for this record's side); the side is re-read; a unit +// recomputes its strength from the physical plug-in's health (the physical plug-in is not +// null-tested here, unlike InformationReal); all plug-ins get the time; then a primary object +// re-registers its position with the information environment for the owning side. +bool InformationKnown::setTime(double time) +{ + if (!(time > m_time + m_allowedTimeDiff)) + { + m_lastUpdate = time; + return false; + } + if (!m_contacts) + { + storeLastSeen(); + if (m_mobile) + m_mobile->setLostContact(); // +6 + } + if (m_mobile) + m_mobile->setTime(time); // +4 + if (isPrimary()) + { + int iterator = -1; + const int side = getSide(); // +17 + Information* secondary = + informationManager->getInformation(getFirstSecondaryObject(iterator, side)); + while (secondary) + { + secondary->setTime(time); // +3 + secondary = informationManager->getInformation(getSecondaryObject(iterator, side)); + } + } + m_side = m_object->getSide(); // +0x12C + if (m_unit) + { + m_physical->setTime(time); // +4 + m_unit->calculateStrMod(m_physical->getHealth()); // +5 + } + setTimeOnPlugIns(time); + m_time = time; + if (isPrimary()) + { + const unsigned int handle = m_object->getInformation(m_ownerSide); // +0xB8 + static_cast( + CommonSingletonServer::m_iaiInformationEnvironmentModifiers) + ->addAndUpdatePosition(m_ownerSide, m_unit != 0, handle); // +0xC + } + m_lastUpdate = time; + return true; +} + +// 0x2DBD20. Raises the record's security to `security` (clamped to [0,1]) if it is lower: +// a full update first, then the timestamp is backdated so getSecurity answers about that +// value, and setTime(double) runs again with the base time reset (its answer is returned). +// Retail backdates by 1 / (security * degeneration), not by the SCurve inverse. A clamped +// security of exactly zero cannot pass the test (security is never below 0) - the branch that +// stores 0.0 as the timestamp is kept as written. +bool InformationKnown::setTime(double time, float security) +{ + float target = 0.0f; + if (!(0.0f > security)) + { + target = security; + if (security > 1.0f) + target = 1.0f; + } + if (!(getSecurity() < target)) // +11 + return false; + setTime(time); // +3 + if (target == 0.0f) + { + m_lastUpdate = target; + return true; + } + const double backdated = time - 1.0 / (static_cast(target) * m_degeneration); + m_time = -1.0; + return setTime(backdated); // +3 +} + +// 0x2DC5D0. +double InformationKnown::getTimeStamp() const +{ + return m_lastUpdate; +} + +// 0x2DBDE0. Counts the contact, tells the mobile plug-in, and passes the contact on to a +// primary object's secondary objects. +void InformationKnown::addContact() +{ + ++m_contacts; + if (m_mobile) + m_mobile->setHasContact(); // +5 + if (!isPrimary()) + return; + int iterator = -1; + const int side = getSide(); // +17 + Information* secondary = + informationManager->getInformation(getFirstSecondaryObject(iterator, side)); + while (secondary) + { + secondary->addContact(); // +6 + secondary = informationManager->getInformation(getSecondaryObject(iterator, side)); + } +} + +// 0x2DBEF0. When the last contact goes, the last-seen state is frozen and the mobile plug-in +// told; a primary object passes the removal on to its secondary objects either way. +void InformationKnown::removeContact() +{ + if (m_contacts > 0) + { + if (--m_contacts == 0) + { + storeLastSeen(); + if (m_mobile) + m_mobile->setLostContact(); // +6 + } + } + if (!isPrimary()) + return; + int iterator = -1; + const int side = getSide(); // +17 + Information* secondary = + informationManager->getInformation(getFirstSecondaryObject(iterator, side)); + while (secondary) + { + secondary->removeContact(); // +7 + secondary = informationManager->getInformation(getSecondaryObject(iterator, side)); + } +} + +// 0x2DC0D0. As removeContact, dropping every contact at once. +void InformationKnown::removeAllContacts() +{ + if (m_contacts > 0) + { + m_contacts = 0; + storeLastSeen(); + if (m_mobile) + m_mobile->setLostContact(); // +6 + } + if (!isPrimary()) + return; + int iterator = -1; + const int side = getSide(); // +17 + Information* secondary = + informationManager->getInformation(getFirstSecondaryObject(iterator, side)); + while (secondary) + { + secondary->removeAllContacts(); // +8 + secondary = informationManager->getInformation(getSecondaryObject(iterator, side)); + } +} + +// 0x2DC5E0. +bool InformationKnown::hasContact() const +{ + return m_contacts > 0; +} + +// 0x2DB970: one minus the SCurve of the age over the degeneration. +float InformationKnown::getSecurity(double time) +{ + const float age = static_cast(time - m_lastUpdate); + return 1.0f - SCurve::calculate(age / m_degeneration); +} + +// 0x2DB910: full while in contact, else the decay at the current game time. +float InformationKnown::getSecurity() +{ + if (m_contacts > 0) + return 1.0f; + return getSecurity(gameTime()); // +10 +} + +// 0x2DB8B0: live while in contact, else the last seen position. +Vec3& InformationKnown::getPosition() +{ + if (m_contacts) + return const_cast(m_object->getPosition()); // +0xD4 + return m_lastPosition; +} + +// 0x2DC470: the terrain's altitude (IAITerrain +0xC) at getPosition's answer, inlined. +float InformationKnown::getAltitude() +{ + if (m_contacts) + return terrain()->getAltitude(m_object->getPosition()); + return terrain()->getAltitude(m_lastPosition); +} + +// 0x2DC2B0. The lowest terrain altitude along `direction` from the current position, in +// tenth steps; like InformationReal's the first tenth step is skipped, but the samples come +// from IAITerrain::getAltitude, not the aerial height map. +float InformationKnown::getAltitude(const Vec3& direction) +{ + const float length = std::sqrt(direction.x * direction.x + direction.y * direction.y + + direction.z * direction.z); + Vec3 probe; + if (m_contacts) + probe = m_object->getPosition(); + else + probe = m_lastPosition; + float lowest = terrain()->getAltitude(probe); + + const double tenth = 1.0f / 10.0f; + const float stepX = static_cast(direction.x * tenth); + const float stepY = static_cast(direction.y * tenth); + const float stepZ = static_cast(direction.z * tenth); + const double firstStep = length / 10.0f; + const float step = static_cast(firstStep); + float travelled = step; + probe.x = static_cast(direction.x * tenth + probe.x); + probe.y = static_cast(direction.y * tenth + probe.y); + probe.z = static_cast(direction.z * tenth + probe.z); + if (length > firstStep) + { + double next; + do + { + probe.x = stepX + probe.x; + probe.y = stepY + probe.y; + probe.z = stepZ + probe.z; + const float altitude = terrain()->getAltitude(probe); + if (!(altitude > lowest)) + lowest = altitude; + next = static_cast(travelled) + step; + travelled = static_cast(next); + } + while (length > next); + } + return lowest; +} + +// 0x2DB8E0: live while in contact, else the last seen transformation. +Mat4& InformationKnown::getTransformation() +{ + if (m_contacts) + return const_cast(m_object->getTransformation()); // +0xDC + return m_lastTransformation; +} + +// 0x2DC590: the stored transformation's third row, even while in contact. +Vec3 InformationKnown::getFaceing() +{ + Vec3 facing; + facing.x = m_lastTransformation.m[8]; + facing.y = m_lastTransformation.m[9]; + facing.z = m_lastTransformation.m[10]; + return facing; +} + +// 0x2DC5C0. +int InformationKnown::getSide() const +{ + return m_side; +} + +// 0x2DC440 / 0x2DC450. +int InformationKnown::getOwnerSide() +{ + return m_ownerSide; +} + +void InformationKnown::setOwnerSide(int side) +{ + m_ownerSide = side; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationKnown.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationKnown.h new file mode 100644 index 000000000..7305a9cf9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationKnown.h @@ -0,0 +1,66 @@ +// Sensed information about an object of another side. While the owning side has contact, the +// position and transformation are read live from the engine object; when the last contact goes, +// they are frozen at the last seen values and the record's security decays with time. +// Owns its attached plug-ins (through Information). +// [INFERRED] Source placement beside InformationReal. + +#ifndef AI_AIDLL_AI_AIKNOWLEDGE_INFORMATIONKNOWN_H +#define AI_AIDLL_AI_AIKNOWLEDGE_INFORMATIONKNOWN_H + +#include "Information.h" +#include "../../../../Math/Mat4.h" + +namespace dice { +namespace hfe { +namespace ai { + +class InformationKnown : public Information +{ +public: + // `degeneration` scales the security decay, `basicTemp` and `allowedTimeDiff` fill the base + // prefix as in InformationReal, `ownerSide` is the side that knows the object. + InformationKnown(IAIObject* object, unsigned int types, double time, float degeneration, + float basicTemp, float allowedTimeDiff, int ownerSide); + virtual ~InformationKnown(); + + virtual int getInformationSort(); // +2 - 1 + virtual bool setTime(double time); // +3 + virtual bool setTime(double time, float security); // +4 + virtual double getTimeStamp() const; // +5 - the last update + virtual void addContact(); // +6 + virtual void removeContact(); // +7 + virtual void removeAllContacts(); // +8 + virtual bool hasContact() const; // +9 + virtual float getSecurity(double time); // +10 + virtual float getSecurity(); // +11 + virtual Vec3& getPosition(); // +12 + virtual float getAltitude(); // +13 + virtual float getAltitude(const Vec3& direction); // +14 + virtual Mat4& getTransformation(); // +15 + virtual Vec3 getFaceing(); // +16 + virtual int getSide() const; // +17 - the cached side + + // Non-virtual: updates to the current game time. + bool setTime(); + int getOwnerSide(); + void setOwnerSide(int side); + +private: + // [INFERRED] helper: the same inline copy appears in the constructor, setTime and both + // contact removals. + void storeLastSeen(); + + /* +0x44 */ double m_lastUpdate; // [INFERRED] name; getTimeStamp + /* +0x4C */ float m_degeneration; // [INFERRED] name; divides the age in getSecurity + /* +0x50 */ Vec3 m_lastPosition; // [INFERRED] name + /* +0x5C */ Mat4 m_lastTransformation; // [INFERRED] name + /* +0x9C */ int m_side; // the object's side (IAIObject +0x12C) + /* +0xA0 */ int m_ownerSide; + /* +0xA4 */ int m_contacts; // [INFERRED] name; add/removeContact +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIKNOWLEDGE_INFORMATIONKNOWN_H diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationReal.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationReal.cpp index da15b9569..c393f139c 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationReal.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationReal.cpp @@ -1,12 +1,16 @@ #include "InformationReal.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2DCB90, __tcf_0 0x2DCBF0, _GLOBAL__I 0x2DCC20). +#include + #include #include "IPIPhysical.h" #include "IPIUnit.h" -#include "InformationManager.h" -#include "../AIStrategicMap/AerialHeightMap.h" +#include "../Main/InformationManager.h" +#include "../AIPathFinding/AerialHeightMap/AerialHeightMap.h" #include "../Main/CommonSingletonServer.h" #include "../../../../Math/Mat4.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" // IBFTimer::getGameTime diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfo.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfo.cpp index 01da6c24c..d7808322e 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfo.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfo.cpp @@ -1,6 +1,10 @@ #include "WeaponInfo.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2DD370, __tcf_0 0x2DD3D0, _GLOBAL__I 0x2DD400). +#include + namespace dice { namespace hfe { namespace ai { WeaponInfo::WeaponInfo(IWeapon* weapon) diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfo.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfo.h index cde20e73f..52f6a1e8d 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfo.h +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfo.h @@ -70,6 +70,12 @@ class WeaponInfo IAIObject* getLockedTarget() const; const std::string& getName() const; +public: + // [CHOSEN, not recovered] added by ai-w1-e-fire (coord/ai-requests.md): the image reads +0x04 + // inline (BBPFireInfantery::createPlan passes it to IAIPlayer::getNumShotsFired and + // IAIObjectEnvironment::hasIndirectLineOfFire). + IWeapon* getWeapon() const { return m_weapon; } + protected: friend class IPIArmament; // retail IPIArmament::rearm reads both fields directly /* +0x04 */ IWeapon* m_weapon; diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoKnown.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoKnown.cpp new file mode 100644 index 000000000..88534c376 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoKnown.cpp @@ -0,0 +1,116 @@ +// WeaponInfoKnown. Recovered from libaidll.so 1.5.3153 (ia-32), 0x2DD420..0x2DDAB7; vtable +// 0x4BE2E0 (same 13 slots as WeaponInfoReal's). + +#include "WeaponInfoKnown.h" + +#include "../AIUtils/CustomCurve.h" // SCurve::calculate (static) +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" + +namespace dice { namespace hfe { namespace ai { + +namespace { + +double gameTime() +{ + return static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); +} + +} // anonymous namespace + +// [INFERRED] helper: the constructor and update read the same five values in this order. +void WeaponInfoKnown::sample() +{ + m_ammo = m_weapon->getAmmo(); // +0xB8 + m_currentAmmo = m_weapon->getCurrentAmmo(); // +0xBC + m_readyToFire = m_weapon->isReadyToFire(); // +0x100 + m_heat = m_weapon->getHeat(); // +0xF4 + m_timeOfFiring = m_weapon->getTimeOfFiring(); // +0xE8 +} + +// 0x2DD420: samples the weapon now, then the shots of each magazine (the magazine count is +// re-read every iteration). +WeaponInfoKnown::WeaponInfoKnown(IWeapon* weapon) + : WeaponInfo(weapon), m_mags() +{ + sample(); + m_timeStamp = gameTime(); + for (int i = 0; i < m_weapon->getNumberOfMags(); ++i) // +0xCC + m_mags.push_back(m_weapon->getAmmoInMag(i)); // +0xC0 +} + +WeaponInfoKnown::~WeaponInfoKnown() +{ +} + +// 0x2DD7B0: re-samples when more than a second has passed since the last sample. Always true. +bool WeaponInfoKnown::update() +{ + const double now = gameTime(); + if (now > m_timeStamp + 1.0f) + { + sample(); + m_timeStamp = now; + m_mags.resize(0); + for (int i = 0; i < m_weapon->getNumberOfMags(); ++i) // +0xCC + m_mags.push_back(m_weapon->getAmmoInMag(i)); // +0xC0 + } + return true; +} + +// 0x2DD990 (unchecked index). +int WeaponInfoKnown::getShotsInMag(int mag) +{ + return m_mags[mag]; +} + +int WeaponInfoKnown::getAmmo() const +{ + return m_ammo; +} + +int WeaponInfoKnown::getCurrentAmmo() const +{ + return m_currentAmmo; +} + +// 0x2DD9D0: the number of sampled magazines. +int WeaponInfoKnown::getNumberOfMags() const +{ + return static_cast(m_mags.size()); +} + +bool WeaponInfoKnown::isReadyToFire() const +{ + return m_readyToFire; +} + +double WeaponInfoKnown::getTimeOfFiring() const +{ + return m_timeOfFiring; +} + +float WeaponInfoKnown::getHeat() const +{ + return m_heat; +} + +// 0x2DDA20: live. +bool WeaponInfoKnown::usesHeat() const +{ + return m_weapon->usesHeat(); // +0xFC +} + +// 0x2DDA40: the decay at the current game time. +float WeaponInfoKnown::getSecurity() const +{ + return getSecurity(gameTime()); // +12 +} + +// 0x2DDA80: one minus the SCurve of a fifth of the sample's age. +float WeaponInfoKnown::getSecurity(double time) const +{ + return 1.0f - SCurve::calculate(static_cast((time - m_timeStamp) * 0.2)); +} + +} } } diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoKnown.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoKnown.h new file mode 100644 index 000000000..72aa555b2 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoKnown.h @@ -0,0 +1,46 @@ +// Weapon information about another side's weapon: ammunition, magazines, readiness, heat and +// firing time are sampled from the engine weapon at most once per second; the record's security +// decays with the age of that sample. +// [INFERRED] Source placement beside WeaponInfoReal. +#ifndef AI_AIDLL_AI_AIKNOWLEDGE_WEAPONINFOKNOWN_H +#define AI_AIDLL_AI_AIKNOWLEDGE_WEAPONINFOKNOWN_H + +#include + +#include "WeaponInfo.h" + +namespace dice { namespace hfe { namespace ai { + +class WeaponInfoKnown : public WeaponInfo +{ +public: + explicit WeaponInfoKnown(IWeapon* weapon); + virtual ~WeaponInfoKnown(); + + virtual bool update(); + virtual int getShotsInMag(int mag); + virtual int getAmmo() const; + virtual int getCurrentAmmo() const; + virtual int getNumberOfMags() const; + virtual bool isReadyToFire() const; + virtual double getTimeOfFiring() const; + virtual float getHeat() const; + virtual bool usesHeat() const; + virtual float getSecurity() const; + virtual float getSecurity(double time) const; + +private: + void sample(); + + /* +0x0C */ std::vector m_mags; // name: AIDLL_r assert 0x1016CB30 (PE +0xC) + /* +0x18 */ int m_ammo; + /* +0x1C */ int m_currentAmmo; + /* +0x20 */ bool m_readyToFire; + /* +0x24 */ float m_heat; + /* +0x28 */ double m_timeOfFiring; + /* +0x30 */ double m_timeStamp; // name: AIDLL_r assert 0x1016CD60 (PE +0x38) +}; + +} } } + +#endif // AI_AIDLL_AI_AIKNOWLEDGE_WEAPONINFOKNOWN_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/AerialHeightMap/AerialHeightMap.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/AerialHeightMap/AerialHeightMap.cpp new file mode 100644 index 000000000..6d4d05292 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/AerialHeightMap/AerialHeightMap.cpp @@ -0,0 +1,210 @@ +// Cached ground heights for aerial navigation. Evidence: libaidll.so (ia-32) 0x3133B0..0x313D09. + +#include "AerialHeightMap.h" + +#include +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x313C40, __tcf_0 0x313CA0, _GLOBAL__I 0x313CD0). +#include + +#include "../../Main/CommonSingletonServer.h" +#include "../../../../AIInterface/BFKnowledge/AIAdapterTypes.h" // AIObjectPredicate +#include "../../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" // IAIObjectEnvironment::getMaxHeight +#include "../../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../../AIInterface/BFKnowledge/BFGame.h" // IAIGame::getLevelPath +#include "../../../../AIInterface/BFKnowledge/BFTerrain.h" // IAITerrain, the world bounds +#include "../../../../../IO/File/File.h" + +namespace dice { +namespace hfe { +namespace ai { + +AerialHeightMap* AerialHeightMap::m_instance = 0; + +// Filters vehicles out of the height probe: accepts every object that is not mobile. Inline in +// the image (weak ELF 0x313CF0, emitted with this TU), so declared here; its vtable has the one +// predicate slot and no destructor. Placement: AIDLL_r.dll __FILE__ +// "Code\BF2\AI\AIDLL\AI\AIPathFinding\AerialHeightMap\AerialHeightMap.cpp" (0x1007D0E0). +class AIObjectPredicateNoVehicles : public AIObjectPredicate +{ +public: + virtual bool predicate(IAIObject* object) + { + return !object->isMobile(); + } +}; + +namespace { + +// The cache's name, spelled dice's way in both directions. "AerialHeighMap" is missing a 't' and +// that is not a transcription slip - the reader and the writer share the literal, so a rebuilt +// server that corrects the spelling stops finding the file a shipped level ships with. +const char* const kHeightMapSuffix = "/AIPathFinding/AerialHeighMap.ahm"; + +} // namespace + +// ELF 0x3133B0 (C2; C1 0x3133F0). Starts with cell size 16, zero origin, and no height buffer. +// Construction unconditionally replaces the singleton. +AerialHeightMap::AerialHeightMap() + : m_cellSize(16.0f) + , m_heights(0) +{ + m_origin.x = 0.0f; + m_origin.y = 0.0f; + + // m_width and m_height deliberately not initialised - the binary steps over both. See the + // header; `m_width` is genuinely read before anything is guaranteed to have written it. + m_instance = this; +} + +// ELF 0x313430 (D2; D1 0x313470). It nulls the static unconditionally, without testing `== this`, so destroying a displaced +// instance clears the pointer to the live one. Reproduced. +AerialHeightMap::~AerialHeightMap() +{ + delete[] m_heights; + m_instance = 0; +} + +// Samples height above ground. Grid lookup requires a position inside the configured bounds. +// An unloaded map returns the missing-height sentinel 9999. +// ELF 0x313960. +float AerialHeightMap::getAltitude(const Vec3& position) +{ + return position.y - getGroundHeight(position); +} + +// ELF 0x3139A0. +float AerialHeightMap::getGroundHeight(const Vec3& position) +{ + return getGroundHeight(position.x, position.z); +} + +// ELF 0x3139E0. +float AerialHeightMap::getGroundHeight(float x, float z) +{ + if (!m_heights) + return 9999.0f; + + const int column = static_cast((x - m_origin.x) / m_cellSize); + const int row = static_cast((z - m_origin.y) / m_cellSize); + + return static_cast(m_heights[column + m_width * row]); +} + +// ELF 0x313650. Loads the level's cached height grid. Missing cache data leaves the map empty. +void AerialHeightMap::readHeightMapFromFile() +{ + const std::string levelPath = + static_cast(CommonSingletonServer::m_iaiGame)->getLevelPath(); + + io::File file; + + std::string path(levelPath); + path.append(kHeightMapSuffix); + + if (!file.open(path, io::FILEMODE_READ, static_cast(0), 0)) + return; + + file.read(m_cellSize); + file.read(m_width); + file.read(m_height); + file.read(m_origin); + + if (!m_heights) + m_heights = new unsigned short[m_width * m_height]; + + file.read(m_heights, 2 * m_width * m_height); + file.close(); +} + +// ELF 0x3134B0. The exact mirror of the reader, field for field and in the same order. It shares the reader's +// silence on failure, and it writes the array unconditionally - a save on an object whose +// `m_heights` is still null passes a null pointer and a zero size to `File::write`. +void AerialHeightMap::saveHeightMapToFile() +{ + const std::string levelPath = + static_cast(CommonSingletonServer::m_iaiGame)->getLevelPath(); + + io::File file; + + std::string path(levelPath); + path.append(kHeightMapSuffix); + + if (file.open(path, static_cast(0), io::FILEACCESS_1, 0)) + { + file.write(m_cellSize); + file.write(m_width); + file.write(m_height); + file.write(m_origin); + file.write(m_heights, 2 * m_width * m_height); + file.close(); + } +} + +// ELF 0x313810. Builds the aerial height grid from terrain bounds and saves it to the level cache. +void AerialHeightMap::createHeightMap(int samplesPerAxis) +{ + IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + + m_width = static_cast(static_cast(terrain->getWorldSizeX()) / m_cellSize); + m_height = static_cast(static_cast(terrain->getWorldSizeZ()) / m_cellSize); + + m_origin.x = static_cast(terrain->getWorldMinX()); + m_origin.y = static_cast(terrain->getWorldMinZ()); + + if (m_heights) + delete[] m_heights; + + m_heights = new unsigned short[m_width * m_height]; + + for (int z = 0; z < m_height; ++z) + for (int x = 0; x < m_width; ++x) + m_heights[x + m_width * z] = computeHeightAt(x, z, samplesPerAxis); + + saveHeightMapToFile(); +} + +// ELF 0x313A60. The highest of samplesPerAxis^2 probes spread over the cell (at the centres of a +// regular sub-grid): each probe takes IAIObjectEnvironment::getMaxHeight on a vertical line from +// y = 9999 down to y = -9999 (the lower end one metre further along x), ignoring vehicles, and +// then the higher of that and the water level. The probe result is not reset between probes, so a +// query that does not write it keeps the previous probe's height; the first starts at -9999. The +// result is truncated to 16 bits. +unsigned short AerialHeightMap::computeHeightAt(int cellX, int cellZ, int samplesPerAxis) +{ + const float cellOriginX = static_cast(cellX) * m_cellSize + m_origin.x; + const float cellOriginZ = static_cast(cellZ) * m_cellSize + m_origin.y; + const float top = 9999.0f; + AIObjectPredicateNoVehicles noVehicles; + float height = -9999.0f; + float highest = -9999.0f; + const float step = m_cellSize / static_cast(samplesPerAxis); + for (int row = 0; row < samplesPerAxis; ++row) + { + const float baseY = 0.0f; + const float offsetZ = (static_cast(row) + 0.5f) * step; + for (int column = 0; column < samplesPerAxis; ++column) + { + Vec3 from; + from.x = (static_cast(column) + 0.5f) * step + cellOriginX; + from.y = baseY + top; + from.z = offsetZ + cellOriginZ; + Vec3 to; + to.x = from.x + 1.0f; + to.y = -9999.0f; + to.z = from.z; + static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->getMaxHeight(from, to, &noVehicles, height); + const float probe = height; + const float water = static_cast(CommonSingletonServer::m_iaiTerrain) + ->getWaterLevel(from.x, from.z); + height = std::max(probe, water); + highest = std::max(highest, height); + } + } + return static_cast(static_cast(highest)); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/AerialHeightMap.h b/Code/BF2/AI/AIDLL/AI/AIPathFinding/AerialHeightMap/AerialHeightMap.h similarity index 82% rename from Code/BF2/AI/AIDLL/AI/AIStrategicMap/AerialHeightMap.h rename to Code/BF2/AI/AIDLL/AI/AIPathFinding/AerialHeightMap/AerialHeightMap.h index 721291c9e..add12cf70 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/AerialHeightMap.h +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/AerialHeightMap/AerialHeightMap.h @@ -1,13 +1,12 @@ // Cached ground heights for aerial navigation. Sampling requires in-range coordinates. // An empty map reports the missing-height sentinel 9999. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. -// [INFERRED] Source placement. +// Header placement [INFERRED]: beside its .cpp, whose path AIDLL_r.dll confirms (AIPathFinding/AerialHeightMap/AerialHeightMap.cpp: singleton assert in 0x1007D0E0). #ifndef AI_AIDLL_AI_AISTRATEGICMAP_AERIALHEIGHTMAP_H #define AI_AIDLL_AI_AISTRATEGICMAP_AERIALHEIGHTMAP_H -#include "../Main/AIDllTypes.h" // Vec3 -#include "../../../../Math/Vec3.h" // Vec2 lives here too, and both are typedefs - never +#include "../../Main/AIDllTypes.h" // Vec3 +#include "../../../../../Math/Vec3.h" // Vec2 lives here too, and both are typedefs - never // forward-declare either one; see AILandingZoneManager.h. namespace dice { @@ -24,11 +23,10 @@ class AerialHeightMap float getGroundHeight(const Vec3&); float getGroundHeight(float, float); - void createHeightMap(int samplesPerAxis); + void createHeightMap(int samplesPerAxis = 4); // ConsoleClass161 passes 4 without an argument // Returns the sampled height as an unsigned 16-bit integer for height-map storage. unsigned short computeHeightAt(int cellX, int cellZ, int samplesPerAxis); - // [FRONTIER] void saveHeightMapToFile(); void readHeightMapFromFile(); diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/Cluster.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/Cluster.cpp new file mode 100644 index 000000000..a4bf4b87e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/Cluster.cpp @@ -0,0 +1,39 @@ +// The cluster record's out-of-line members. + +#include "Cluster.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x313DC0, __tcf_0 0x313E20, _GLOBAL__I 0x313E50). +#include + +#include "../../../../../IO/File/File.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x313D10 (C2; C1 0x313D20). Leaves every field unset; ClusterGraph::readFromFile overwrites +// the array it constructs. +Cluster::Cluster() +{ +} + +// ELF 0x313D30 (D2; D1 0x313D40). +Cluster::~Cluster() +{ +} + +// ELF 0x313D50. Reads one cluster's polygon list of a GTS file into `polygons` (count first, then +// the indices) and records where it starts in the graph's list (`first`) and how long it is. +void Cluster::readGTSDataFromFile(unsigned int* polygons, unsigned int& count, unsigned int first, + io::File& file) +{ + file.read(count); + file.read(polygons, count * sizeof(unsigned int)); + m_firstPolygon = first; + m_numberOfPolygons = count; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/Cluster.h b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/Cluster.h index 25490f301..4ba6ac4a7 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/Cluster.h +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/Cluster.h @@ -7,18 +7,28 @@ namespace dice { namespace hfe { + +namespace io { class File; } + namespace ai { class Cluster { public: - Cluster() {} // empty - ~Cluster() {} // empty + Cluster(); + ~Cluster(); + + // Reads the cluster's polygon list of a GTS file; see the definition. + void readGTSDataFromFile(unsigned int* polygons, unsigned int& count, unsigned int first, + io::File& file); - /* +0x00 */ unsigned char m_unread00[8]; // [UNRESOLVED] - see the note above + /* +0x00 */ unsigned int m_firstPolygon; // [INFERRED] name: into ClusterGraph::m_clusterPolygons + /* +0x04 */ unsigned int m_numberOfPolygons; // [INFERRED] name: resetTempMemberSizes copies it /* +0x08 */ unsigned short m_firstPortal; // getClusterPortal's base /* +0x0A */ unsigned short m_numberOfPortals; // getClusterPortal's stride - /* +0x0C */ unsigned char m_unread0C[4]; // index 2 (+0x0E): map-part walkability state + /* +0x0C */ unsigned short m_firstPortalCost; // [INFERRED] name: getCostBetweenClustersPortals' base + /* +0x0E */ unsigned char m_walkable; // [INFERRED] name: map-part walkability state + /* +0x0F */ unsigned char m_unread0F; }; typedef char ClusterIsTheFileRecord[sizeof(Cluster) == 16 ? 1 : -1]; diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.cpp index 94c200770..178d3d575 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.cpp @@ -1,43 +1,803 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining ClusterGraph operations. - #include "ClusterGraph.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x31DAE0, __tcf_0 0x31DB40, _GLOBAL__I 0x31DB70). +#include +#include +#include // drawCluster +#include +#include + +#include "../NavMesh/QuadTree.h" +#include "../NavMesh/GTSDataOptimiser.h" +#include "../Material/MaterialManager.h" +#include "../../Main/AISettingsInterfaces.h" #include "../../AIUtils/checkPointer.h" +#include "../../Main/CommonSingletonServer.h" +#include "../../DrawPrimitives/DPManager.h" // IDPStaticCreator +#include "../../Main/AIPathfinding.h" // getPortalCost, isValidClusterType +#include "../../Main/IAIPathfinding.h" #include "../../../../../IO/File/File.h" namespace dice { namespace hfe { namespace ai { -// Zeroes the six fields at +0x00..+0x14 and the three at +0x24..+0x2C; the two sets +// ELF 0x314380. +void ClusterGraph::readGTSDataFromFile(QuadTree* tree, io::File& file) +{ + clean(); + file.read(m_numberOfClusters); + m_clusters = checkPointer(new Cluster[m_numberOfClusters]); + m_clusterPolygons = checkPointer(new unsigned int[tree->m_numberOfPolygons]); + for (unsigned short i = 0; i < m_numberOfClusters; ++i) + { + Cluster& cluster = m_clusters[i]; + unsigned int count; + cluster.readGTSDataFromFile(m_clusterPolygons + m_polygonCount, + count, m_polygonCount, file); + const unsigned int first = cluster.m_firstPolygon; + const unsigned int size = cluster.m_numberOfPolygons; + for (unsigned int j = 0; j < size; ++j) + { + const unsigned int id = m_clusterPolygons[first + j]; + Polygon* polygon = tree->getPolygon(id); + DoublePolygon* doublePolygon = tree->getPolygonDouble(id); + polygon->cluster = i; + doublePolygon->m_cluster = i; + } + m_polygonCount += count; + } +} + +// ELF 0x315160. The radius argument is unused in the shipped body. +void ClusterGraph::createPortals(int map, QuadTree* tree, float) +{ + std::list > costTypes; + AIPathfinding* const pathfinding = static_cast(IAIPathfinding::instance); + for (unsigned short type = 0; pathfinding->isValidClusterType(map, type); ++type) + costTypes.push_back(std::make_pair(type, + pathfinding->getEquipmentTypeFromClusterCostType(map, type))); + PortalBuildMap portals; + for (unsigned short i = 0; i < m_numberOfClusters; ++i) + { + const Cluster& cluster = m_clusters[i]; + ClusterEdges edges; + VertexClusterEdges vertices; + buildClusterEdges(cluster, i, tree, vertices, edges); + buildPortalsFromClusterEdges(i, tree, vertices, edges, portals); + } + if (portals.empty()) + { + m_numberOfPortals = 0; + for (unsigned short i = 0; i < m_numberOfClusters; ++i) + { + m_clusters[i].m_firstPortal = 0; + m_clusters[i].m_numberOfPortals = 0; + } + return; + } + for (PortalBuildMap::const_iterator i = portals.begin(); i != portals.end(); ++i) + m_numberOfPortals += static_cast(i->second.size()); + m_numberOfPortals *= static_cast(costTypes.size()); + m_portals = checkPointer(new ClusterPortal[m_numberOfPortals]); + unsigned short portalIndex = 0; + for (unsigned short i = 0; i < m_numberOfClusters; ++i) + { + Cluster& cluster = m_clusters[i]; + cluster.m_firstPortal = portalIndex; + PortalBuildMap::const_iterator found = portals.find(i); + if (found == portals.end()) + { + cluster.m_numberOfPortals = 0; + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.cpp", 468, "") + << static_cast(i) << " is a lost cluster!"; + continue; + } + for (std::list >::const_iterator type = costTypes.begin(); + type != costTypes.end(); ++type) + { + MaterialManager* materials = static_cast(CommonSingletonServer::m_iaiSettings) + ->getVehicleMaterialManager(type->second); + cluster.m_numberOfPortals = static_cast(found->second.size()); + for (std::list::const_iterator p = found->second.begin(); + p != found->second.end(); ++p, ++portalIndex) + { + unsigned int polygon; + ClusterPortal& portal = m_portals[portalIndex]; + if (!calculateMiddleVertex(i, *p, tree, portalIndex, materials, portal.m_position, polygon)) + { + float bestDistance = FLT_MAX; + bool success = false; + bool checkMaterial = true; + const Cluster& neighbour = m_clusters[p->neighbour]; + for (int pass = 0; pass < 2; ++pass) + { + for (int side = 0; side < 2; ++side) + { + const Cluster& candidateCluster = side == 0 ? cluster : neighbour; + const unsigned int first = candidateCluster.m_firstPolygon; + const unsigned int count = candidateCluster.m_numberOfPolygons; + for (unsigned int j = 0; j < count; ++j) + { + const unsigned int id = m_clusterPolygons[first + j]; + const Polygon* candidate = tree->getPolygon(id); + if (!candidate->m_material || + (checkMaterial && !materials->isValidMaterial(candidate->m_material))) + continue; + const Vec3& a = tree->m_vertices[p->firstVertex]; + const Vec3& b = tree->m_vertices[p->secondVertex]; + Vec3 midpoint; + midpoint.x = (b.x + a.x) * 0.5f; + midpoint.y = (b.y + a.y) * 0.5f; + midpoint.z = (b.z + a.z) * 0.5f; + Vec3 centre = {}; + tree->getCentreOfPolygon(centre, id); + // shipped defect: compares against the changing output position, not centre. + const float dx = midpoint.x - portal.m_position.x; + const float dy = midpoint.y - portal.m_position.y; + const float dz = midpoint.z - portal.m_position.z; + const float distance = dx * dx + dy * dy + dz * dz; + if (bestDistance > distance) + { + portal.m_position = centre; + bestDistance = distance; + success = true; + polygon = id; + } + } + } + checkMaterial = false; + if (success) break; + } + if (!success) + { + portal.m_neighbourCluster = 0xFFFF; + portal.m_position.x = portal.m_position.y = portal.m_position.z = 0.0f; + portal.m_polygon = 0xFFFFFFFF; + continue; + } + } + portal.m_neighbourCluster = p->neighbour; + portal.m_polygon = polygon; + } + } + } +} + +// ELF 0x315DE0. +void ClusterGraph::buildClusterEdges(const Cluster& cluster, unsigned short clusterId, + QuadTree* tree, VertexClusterEdges& vertices, ClusterEdges& edges) +{ + const unsigned int first = cluster.m_firstPolygon; + const unsigned int count = cluster.m_numberOfPolygons; + for (unsigned int j = 0; j < count; ++j) + { + const unsigned int id = m_clusterPolygons[first + j]; + const Polygon* polygon = tree->getPolygon(id); + for (unsigned char edge = 0; edge < polygon->vertexCount; ++edge) + { + const unsigned int neighbourId = tree->getNeighbourOfPolygon(id, edge); + const Polygon* neighbour = tree->getPolygon(neighbourId); + if (!neighbour || neighbour->cluster == polygon->cluster) continue; + const unsigned int a = tree->getVertexIndexForPolygon(id, edge); + const unsigned int b = tree->getVertexIndexForPolygon(id, + static_cast((edge + 1) % polygon->vertexCount)); + for (int endpoint = 0; endpoint < 2; ++endpoint) + { + const unsigned int vertex = endpoint == 0 ? a : b; + VertexClusterEdges::iterator found = vertices.find(vertex); + if (found == vertices.end()) + { + std::map clusters; + clusters.insert(std::make_pair(neighbour->cluster, 1U)); + vertices.insert(std::make_pair(vertex, clusters)); + } + else + { + std::map::iterator entry = found->second.find(neighbour->cluster); + if (entry == found->second.end()) + found->second.insert(std::make_pair(neighbour->cluster, 1U)); + else if (++entry->second > 2) + { + printClusterInfo(clusterId, tree, false); + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.cpp", + endpoint == 0 ? 510 : 539, "") << "Bailing out!"; + } + } + } + ClusterEdges::iterator found = edges.find(neighbour->cluster); + const std::pair edgePair(a, b); + if (found == edges.end()) + { + std::list > list; + list.push_back(edgePair); + edges.insert(std::make_pair(neighbour->cluster, list)); + } + else + found->second.push_back(edgePair); + } + } +} + +// ELF 0x316EC0. +void ClusterGraph::buildPortalsFromClusterEdges(unsigned short cluster, QuadTree* tree, + const VertexClusterEdges& vertices, const ClusterEdges& edges, PortalBuildMap& output) +{ + typedef std::pair Edge; + std::list portals; + for (ClusterEdges::const_iterator group = edges.begin(); group != edges.end(); ++group) + { + std::list starts; + for (std::list::const_iterator e = group->second.begin(); e != group->second.end(); ++e) + { + VertexClusterEdges::const_iterator a = vertices.find(e->first); + VertexClusterEdges::const_iterator b = vertices.find(e->second); + std::map::const_iterator ac = a->second.find(group->first); + std::map::const_iterator bc = b->second.find(group->first); + if (ac->second == 1 || bc->second == 1) starts.push_back(*e); + } + std::set visitedEdges; + if (starts.empty()) + { + // shipped defect: takes the first group, even when processing a later group. + const ClusterEdges::const_iterator first = edges.begin(); + ClusterPortalBuildInfo portal; + portal.firstVertex = first->second.begin()->first; + portal.secondVertex = first->second.begin()->first; + portal.neighbour = first->first; + portals.push_back(portal); + output.insert(std::make_pair(cluster, portals)); + continue; + } + for (std::list::const_iterator start = starts.begin(); start != starts.end(); ++start) + { + if (visitedEdges.find(*start) != visitedEdges.end()) continue; + if (visitedEdges.find(Edge(start->second, start->first)) != visitedEdges.end()) continue; + VertexClusterEdges::const_iterator a = vertices.find(start->first); + VertexClusterEdges::const_iterator b = vertices.find(start->second); + std::map::const_iterator ac = a->second.find(group->first); + std::map::const_iterator bc = b->second.find(group->first); + unsigned int first; + unsigned int current; + unsigned int last = 0xFFFFFFFF; + bool complete = false; + if (ac->second == 1) + { + first = start->first; + current = start->second; + if (bc->second == 1) { last = start->second; complete = true; } + } + else { first = start->second; current = start->first; } + std::set visited; + visited.insert(first); + visited.insert(current); + while (!complete) + { + bool progressed = false; + for (std::list::const_iterator e = group->second.begin(); e != group->second.end(); ++e) + { + VertexClusterEdges::const_iterator va = vertices.find(e->first); + VertexClusterEdges::const_iterator vb = vertices.find(e->second); + std::map::const_iterator ea = va->second.find(group->first); + std::map::const_iterator eb = vb->second.find(group->first); + if (visited.find(e->first) != visited.end() && visited.find(e->second) != visited.end()) continue; + unsigned int next; + unsigned int degree; + if (e->first == current) { next = e->second; degree = eb->second; } + else if (e->second == current) { next = e->first; degree = ea->second; } + else continue; + if (degree == 1) + { + last = next; + visitedEdges.insert(*start); + visitedEdges.insert(Edge(current, last)); + complete = true; + } + else + { + current = next; + visited.insert(current); + progressed = true; + } + break; + } + if (complete) break; + if (progressed) continue; + for (VertexClusterEdges::const_iterator v = vertices.begin(); v != vertices.end(); ++v) + for (std::map::const_iterator c = v->second.begin(); c != v->second.end(); ++c) {} + printClusterInfo(cluster, tree, false); + printClusterInfo(group->first, tree, false); + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.cpp", 756, "") << "Bailing out!"; + break; + } + if (complete) + { + ClusterPortalBuildInfo portal; + portal.firstVertex = first < last ? first : last; + portal.secondVertex = first < last ? last : first; + portal.neighbour = group->first; + portals.push_back(portal); + } + } + } + if (!portals.empty() && portals.size()) output.insert(std::make_pair(cluster, portals)); + else + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.cpp", 782, "") + << "Could not find any portals for cluster: " << static_cast(cluster); +} + +// ELF 0x318270. The portal index argument is unused. +bool ClusterGraph::calculateMiddleVertex(unsigned short cluster, const ClusterPortalBuildInfo& info, + QuadTree* tree, unsigned short, MaterialManager* materials, Vec3& point, unsigned int& polygon) const +{ + const Vec3& a = tree->m_vertices[info.firstVertex]; + const Vec3& b = tree->m_vertices[info.secondVertex]; + point.x = (b.x + a.x) * 0.5f; + point.y = (b.y + a.y) * 0.5f; + point.z = (b.z + a.z) * 0.5f; + const bool found = tree->findPolygon(point, polygon, materials, 100.0f); + const Polygon* result = tree->getPolygon(polygon); + if (found) + { + const bool valid = materials->isValidMaterial(result->m_material); + const bool rightCluster = result->cluster == cluster || result->cluster == info.neighbour; + if (valid && rightCluster) return true; + } + Vec3 direction; + direction.x = -(b.z - a.z); + direction.y = b.y - a.y; + direction.z = b.x - a.x; + const float lengthSquared = direction.x * direction.x + direction.y * direction.y + direction.z * direction.z; + if (!(FLT_EPSILON > std::fabs(1.0f - lengthSquared))) + { + if (!(FLT_EPSILON > std::fabs(lengthSquared))) + { + const float scale = 1.0f / std::sqrt(lengthSquared); + direction.x *= scale; direction.y *= scale; direction.z *= scale; + } + else direction.x = direction.y = direction.z = 0.0f; + } + const Vec3 origin = point; + for (unsigned int side = 0; side <= 1; ++side) + { + float distance = 0.1f; + for (int step = 0; step <= 999; ++step) + { + point.x = direction.x * distance + origin.x; + point.y = direction.y * distance + origin.y; + point.z = direction.z * distance + origin.z; + if (tree->findPolygon(point, polygon, materials, 100.0f)) + { + result = tree->getPolygon(polygon); + const bool valid = materials->isValidMaterial(result->m_material); + const bool rightCluster = result->cluster == cluster || result->cluster == info.neighbour; + if (valid && rightCluster) return true; + } + distance += 0.1f; + } + direction.x = -direction.x; direction.y = -direction.y; direction.z = -direction.z; + } + return false; +} + +// ELF 0x318610. Only polygon ranges are rebuilt; other Cluster fields remain uninitialised. +void ClusterGraph::adjustPolygonsInClusters() +{ + Cluster* adjusted = checkPointer(new Cluster[m_numberOfClusters]); + unsigned int first = 0; + for (unsigned int i = 0; i < m_numberOfClusters; ++i) + { + const Cluster& old = m_clusters[i]; + const unsigned int count = old.m_numberOfPolygons; + const unsigned int oldFirst = old.m_firstPolygon; + adjusted[i].m_numberOfPolygons = count; + for (unsigned int j = 0; j < count; ++j) + if (m_set18.find(m_clusterPolygons[oldFirst + j]) != m_set18.end()) + --adjusted[i].m_numberOfPolygons; + adjusted[i].m_firstPolygon = first; + first += adjusted[i].m_numberOfPolygons; + } + delete[] m_clusters; + m_clusters = adjusted; +} + +// ELF 0x318910. +void ClusterGraph::movePolygonBetweenClusters(unsigned short source, unsigned short destination, + unsigned int polygon) +{ + Cluster* adjusted = checkPointer(new Cluster[m_numberOfClusters]); + unsigned int* polygons = checkPointer(new unsigned int[m_polygonCount]); + for (unsigned int i = 0; i < m_numberOfClusters; ++i) + { + if (i == source) adjusted[i].m_numberOfPolygons = m_clusters[i].m_numberOfPolygons - 1; + else if (i == destination) adjusted[i].m_numberOfPolygons = m_clusters[destination].m_numberOfPolygons + 1; + else adjusted[i].m_numberOfPolygons = m_clusters[i].m_numberOfPolygons; + } + for (unsigned int i = 0; i < m_polygonCount; ++i) + { + // shipped defect: skipped entries leave holes; insertion also skips the old destination entry. + if (m_clusterPolygons[i] == polygon) continue; + if (m_clusterPolygons[i] == m_clusterPolygons[m_clusters[destination].m_firstPolygon]) + polygons[i++] = polygon; + polygons[i] = m_clusterPolygons[i]; + } + unsigned int first = 0; + for (unsigned int i = 0; i < m_numberOfClusters; ++i) + { + adjusted[i].m_firstPolygon = first; + first += adjusted[i].m_numberOfPolygons; + } + delete[] m_clusters; + m_clusters = adjusted; + delete[] m_clusterPolygons; + m_clusterPolygons = polygons; +} + +// ELF 0x318D30. +void ClusterGraph::addPolygonsToNewCluster(const std::set& selected, + std::list& mesh) +{ + Cluster* adjusted = checkPointer(new Cluster[m_numberOfClusters + 1]); + unsigned int* polygons = checkPointer(new unsigned int[m_polygonCount]); + for (unsigned int i = 0; i < m_numberOfClusters; ++i) + adjusted[i].m_numberOfPolygons = m_clusters[i].m_numberOfPolygons; + unsigned int write = 0; + for (unsigned int i = 0; i < m_numberOfClusters; ++i) + { + const unsigned int first = m_clusters[i].m_firstPolygon; + const unsigned int count = m_clusters[i].m_numberOfPolygons; + for (unsigned int j = 0; j < count; ++j) + { + const unsigned int id = m_clusterPolygons[first + j]; + if (selected.find(id) == selected.end()) polygons[write++] = id; + else --adjusted[i].m_numberOfPolygons; + } + } + unsigned int first = 0; + for (unsigned int i = 0; i < m_numberOfClusters; ++i) + { + adjusted[i].m_firstPolygon = first; + first += adjusted[i].m_numberOfPolygons; + } + adjusted[m_numberOfClusters].m_numberOfPolygons = static_cast(selected.size()); + // shipped defect: the empty-graph case reads the preceding record. + adjusted[m_numberOfClusters].m_firstPolygon = + adjusted[m_numberOfClusters - 1].m_firstPolygon + adjusted[m_numberOfClusters - 1].m_numberOfPolygons; + first = adjusted[m_numberOfClusters].m_firstPolygon; + const unsigned int count = adjusted[m_numberOfClusters].m_numberOfPolygons; + std::set::const_iterator id = selected.begin(); + for (unsigned int j = 0; j < count; ++j, ++id) polygons[first + j] = *id; + for (std::list::iterator p = mesh.begin(); p != mesh.end(); ++p) + if (selected.find((*p)->m_index) != selected.end()) + (*p)->m_cluster = static_cast(m_numberOfClusters); + ++m_numberOfClusters; + delete[] m_clusters; + m_clusters = adjusted; + delete[] m_clusterPolygons; + m_clusterPolygons = polygons; +} + +// ELF 0x319330. +void ClusterGraph::updateClustersAfterOptimisation(const DynamicPolygonMap& dynamicPolygons, + std::list& mesh, ClusterPolygonMap& clusters) +{ + adjustPolygonsInClusters(); + setPolygonIndices(clusters); + moveDynamicObjectPolygonsToSeparateClusters(mesh, dynamicPolygons, clusters); + clearEmptyClusters(mesh); + setPolygonIndices(clusters); + fixClusterGraphConnectivity(mesh, false); + m_set18.clear(); +} + +// ELF 0x319400. +void ClusterGraph::clearEmptyClusters(std::list& mesh) +{ + std::list empty; + unsigned int count = m_numberOfClusters; + for (unsigned short i = 0; i < m_numberOfClusters; ++i) + if (!m_clusters[i].m_numberOfPolygons) { empty.push_back(i); --count; } + if (empty.empty() || !empty.size()) return; + while (!empty.empty() && empty.size()) + { + const unsigned short removed = *empty.begin(); + for (std::list::iterator p = mesh.begin(); p != mesh.end(); ++p) + if ((*p)->m_cluster > removed) --(*p)->m_cluster; + empty.erase(empty.begin()); + for (std::list::iterator i = empty.begin(); i != empty.end(); ++i) --*i; + } + Cluster* adjusted = checkPointer(new Cluster[count]); + unsigned int write = 0; + for (unsigned short i = 0; i < m_numberOfClusters; ++i) + if (m_clusters[i].m_numberOfPolygons) + { + adjusted[write].m_numberOfPolygons = m_clusters[i].m_numberOfPolygons; + adjusted[write].m_firstPolygon = m_clusters[i].m_firstPolygon; + ++write; + } + m_numberOfClusters = count; + delete[] m_clusters; + m_clusters = adjusted; +} + +// ELF 0x319870. +void ClusterGraph::splitClustersCutByDeepWater(const std::list& mesh) +{ + bool split; + do + { + std::set checked; + split = false; + for (std::list::const_iterator p = mesh.begin(); p != mesh.end(); ++p) + { + OptPolygon* seed = *p; + if (checked.find(seed) != checked.end()) continue; + std::set connected; + floodFillPolygonsInCluster(seed, connected, true); + if (connected.empty()) continue; + std::set invalid; + getAllDeepWaterAndInvalidPolygonsInCluster(seed->m_cluster, mesh, invalid); + if (connected.size() + invalid.size() == m_clusters[seed->m_cluster].m_numberOfPolygons) + { + checked.insert(connected.begin(), connected.end()); + continue; + } + split = true; + std::set other; + for (std::list::const_iterator q = mesh.begin(); q != mesh.end(); ++q) + if ((*q)->m_cluster == seed->m_cluster && connected.find(*q) == connected.end()) + other.insert(*q); + Cluster* adjusted = checkPointer(new Cluster[m_numberOfClusters + 1]); + unsigned int first = 0; + for (unsigned short i = 0; i < m_numberOfClusters; ++i) + { + if (i == seed->m_cluster) + { + // shipped defect: decrements once regardless of the size of other; leaves the range unset. + adjusted[i].m_numberOfPolygons = m_clusters[i].m_numberOfPolygons - 1; + for (std::set::iterator q = other.begin(); q != other.end(); ++q) + (*q)->m_cluster = static_cast(m_numberOfClusters); + } + else adjusted[i].m_firstPolygon = first; + // shipped defect: other counts and the new record were never initialised. + first += adjusted[i].m_numberOfPolygons; + } + delete[] m_clusters; + ++m_numberOfClusters; + m_clusters = adjusted; + break; + } + } while (split); +} + +// ELF 0x31A020. +void ClusterGraph::moveDynamicObjectPolygonsToSeparateClusters(const std::list& mesh, + const DynamicPolygonMap& dynamicPolygons, ClusterPolygonMap& clusters) +{ + typedef std::map > ObjectPolygons; + ObjectPolygons objects; + for (DynamicPolygonMap::const_iterator p = dynamicPolygons.begin(); p != dynamicPolygons.end(); ++p) + { + ObjectPolygons::iterator object = objects.find(p->second.first); + if (object == objects.end()) + { + std::vector polygons; + polygons.push_back(p->first); + objects.insert(std::make_pair(p->second.first, polygons)); + } + else object->second.push_back(p->first); + } + const int objectCount = static_cast(objects.size()); + if (!objectCount) return; + Cluster* adjusted = checkPointer(new Cluster[m_numberOfClusters + objectCount]); + for (unsigned int i = 0; i < m_numberOfClusters; ++i) + { + adjusted[i].m_walkable = 1; + adjusted[i].m_numberOfPolygons = m_clusters[i].m_numberOfPolygons; + } + unsigned int newCluster = m_numberOfClusters; + for (ObjectPolygons::const_iterator object = objects.begin(); object != objects.end(); ++object) + { + const DynamicPolygonMap::const_iterator first = dynamicPolygons.find(object->second[0]); + adjusted[newCluster].m_numberOfPolygons = static_cast(object->second.size()); + adjusted[newCluster].m_walkable = first->second.second; + std::list empty; + clusters.insert(std::make_pair(static_cast(newCluster), empty)); + for (std::list::const_iterator p = mesh.begin(); p != mesh.end(); ++p) + { + OptPolygon* polygon = *p; + for (std::vector::const_iterator id = object->second.begin(); id != object->second.end(); ++id) + { + if (*id != polygon->m_index) continue; + --adjusted[polygon->m_cluster].m_numberOfPolygons; + ClusterPolygonMap::iterator old = clusters.find(polygon->m_cluster); + std::list::iterator entry = old->second.begin(); + while (entry != old->second.end()) + { + if (*entry == *id) + { + std::list::iterator removed = entry++; + old->second.erase(removed); + clusters.find(static_cast(newCluster))->second.push_back(*id); + } + else ++entry; + } + polygon->m_cluster = static_cast(newCluster); + } + } + ++newCluster; + } + m_numberOfClusters += objectCount; + unsigned int first = 0; + for (unsigned int i = 0; i < m_numberOfClusters; ++i) + { + adjusted[i].m_firstPolygon = first; + first += adjusted[i].m_numberOfPolygons; + } + delete[] m_clusters; + m_clusters = adjusted; +} + +// ELF 0x31AC20. +void ClusterGraph::fixClusterGraphConnectivity(std::list& mesh, bool reportOnly) +{ + std::set checked; + if (m_numberOfClusters == 1 && m_clusters[0].m_numberOfPolygons == 1) return; + for (;;) + { + bool fixed = true; + for (std::list::iterator p = mesh.begin(); p != mesh.end(); ++p) + { + OptPolygon* polygon = *p; + if (checked.find(polygon->m_cluster) != checked.end()) continue; + std::set connected; + if (validateClusterConnectivityFromPolygon(polygon->m_cluster, polygon, + m_clusters[polygon->m_cluster].m_numberOfPolygons, connected, true)) + { + checked.insert(polygon->m_cluster); + continue; + } + if (reportOnly) + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.cpp", 1294, "") + << "Non connected cluster " << static_cast(polygon->m_cluster) + << ". Found " << static_cast(connected.size()) + << " polygons, should be " << static_cast(m_clusters[polygon->m_cluster].m_numberOfPolygons) + << " polygons"; + return; + } + unsigned int unconnected = 0xFFFFFFFF; + const Cluster& cluster = m_clusters[polygon->m_cluster]; + const unsigned int first = cluster.m_firstPolygon; + const unsigned int count = cluster.m_numberOfPolygons; + for (unsigned int j = 0; j < count; ++j) + if (connected.find(m_clusterPolygons[first + j]) == connected.end()) + { + unconnected = m_clusterPolygons[first + j]; + break; + } + OptPolygon* seed = 0; + for (std::list::iterator q = mesh.begin(); q != mesh.end(); ++q) + if ((*q)->m_index == unconnected) { seed = *q; break; } + std::set selected; + selected.insert(unconnected); + for (unsigned int edge = 0; edge < seed->m_numberOfVertices; ++edge) + { + OptPolygon* neighbour = seed->m_neighbours[edge]; + if (neighbour && neighbour->m_cluster == seed->m_cluster) + recurseFloodFill(neighbour, seed, selected); + } + addPolygonsToNewCluster(selected, mesh); + fixed = false; + break; + } + if (fixed) return; + } +} + +// ELF 0x31B3F0. +void ClusterGraph::floodFillPolygonsInCluster(OptPolygon* polygon, std::set& filled, + bool filter) const +{ + if (filled.find(polygon) != filled.end()) return; + // shipped defect: with filter true the material must simultaneously equal zero and four. + if (filter && polygon->m_material != 0) return; + if (polygon->m_material != 4) return; + filled.insert(polygon); + for (unsigned int edge = 0; edge < polygon->m_numberOfVertices; ++edge) + { + OptPolygon* neighbour = polygon->m_neighbours[edge]; + if (neighbour && neighbour->m_cluster == polygon->m_cluster) + floodFillPolygonsInCluster(neighbour, filled, filter); + } +} + +// ELF 0x31B510. +void ClusterGraph::getAllDeepWaterAndInvalidPolygonsInCluster(unsigned short cluster, + const std::list& mesh, std::set& polygons) const +{ + for (std::list::const_iterator p = mesh.begin(); p != mesh.end(); ++p) + if ((*p)->m_cluster == cluster && ((*p)->m_material == 0 || (*p)->m_material == 4)) + polygons.insert(*p); +} + +// ELF 0x31B5B0. +void ClusterGraph::setPolygonIndices(const ClusterPolygonMap& clusters) +{ + m_polygonCount = 0; + for (ClusterPolygonMap::const_iterator i = clusters.begin(); i != clusters.end(); ++i) + m_polygonCount += static_cast(i->second.size()); + unsigned int* polygons = checkPointer(new unsigned int[m_polygonCount]); + unsigned int write = 0; + for (ClusterPolygonMap::const_iterator i = clusters.begin(); i != clusters.end(); ++i) + for (std::list::const_iterator p = i->second.begin(); p != i->second.end(); ++p) + polygons[write++] = *p; + delete[] m_clusterPolygons; + m_clusterPolygons = polygons; +} + +// ELF 0x31BC80. +void ClusterGraph::recurseFloodFill(OptPolygon* polygon, OptPolygon* origin, + std::set& filled) const +{ + if (polygon == origin) return; + if (filled.find(polygon->m_index) != filled.end()) return; + filled.insert(polygon->m_index); + for (unsigned int edge = 0; edge < polygon->m_numberOfVertices; ++edge) + { + OptPolygon* neighbour = polygon->m_neighbours[edge]; + if (neighbour && neighbour->m_cluster == origin->m_cluster) + recurseFloodFill(neighbour, origin, filled); + } +} + +// ELF 0x31BD70. The cluster argument is unused. +bool ClusterGraph::validateClusterConnectivityFromPolygon(unsigned short, OptPolygon* polygon, + unsigned int count, std::set& filled, bool all) const +{ + if (all) filled.insert(polygon->m_index); + for (unsigned int edge = 0; edge < polygon->m_numberOfVertices; ++edge) + { + OptPolygon* neighbour = polygon->m_neighbours[edge]; + if (neighbour && neighbour->m_cluster == polygon->m_cluster) + { + recurseFloodFill(neighbour, polygon, filled); + if (!all) break; + } + } + return filled.size() == count; +} + +// ELF 0x313E70 (C2; C1 0x314010). Zeroes the six fields at +0x00..+0x14 and the three at +0x24..+0x2C; the two sets // construct empty (their sentinel allocations are the only calls). is bigger only because the // SGI node allocator is inlined into it - same source, two inlining decisions. ClusterGraph::ClusterGraph() : m_clusterPolygons(0) - , m_numberOfClusterPolygons(0) + , m_polygonCount(0) , m_clusters(0) , m_numberOfClusters(0) , m_numberOfPortals(0) , m_portals(0) - , m_array24(0) + , m_tempMemberSizes(0) , m_numberOfPortalCosts(0) , m_portalCosts(0) { } -// clean, then the two sets in reverse declaration order. +// ELF 0x3140F0 (D2; D1 0x3141D0). clean, then the two sets in reverse declaration order. ClusterGraph::~ClusterGraph() { clean(); } -// Releases arrays and clears counts, but leaves four freed pointers unchanged. +// ELF 0x3142B0. Releases arrays and clears counts, but leaves four freed pointers unchanged. // Do not clean twice without repopulating those pointers; readFromFile assigns them // immediately after cleanup. Only the pointer at +0x24 is cleared. void ClusterGraph::clean() { delete[] m_clusterPolygons; - m_numberOfClusterPolygons = 0; + m_polygonCount = 0; delete[] m_clusters; m_numberOfClusters = 0; @@ -45,14 +805,14 @@ void ClusterGraph::clean() delete[] m_portals; m_numberOfPortals = 0; - delete[] m_array24; - m_array24 = 0; + delete[] m_tempMemberSizes; + m_tempMemberSizes = 0; delete[] m_portalCosts; m_numberOfPortalCosts = 0; } -// Loads a version-5 cluster graph. Unsupported versions leave the existing graph unchanged. +// ELF 0x314830. Loads a version-5 cluster graph. Unsupported versions leave the existing graph unchanged. void ClusterGraph::readFromFile(io::File& file) { int version = 0; @@ -66,9 +826,9 @@ void ClusterGraph::readFromFile(io::File& file) m_clusters = checkPointer(new Cluster[m_numberOfClusters]); file.read(m_clusters, sizeof(Cluster) * m_numberOfClusters); - file.read(m_numberOfClusterPolygons); - m_clusterPolygons = checkPointer(new unsigned int[m_numberOfClusterPolygons]); - file.read(m_clusterPolygons, sizeof(unsigned int) * m_numberOfClusterPolygons); + file.read(m_polygonCount); + m_clusterPolygons = checkPointer(new unsigned int[m_polygonCount]); + file.read(m_clusterPolygons, sizeof(unsigned int) * m_polygonCount); file.read(m_numberOfPortals); if (m_numberOfPortals) @@ -94,6 +854,466 @@ void ClusterGraph::readFromFile(io::File& file) } } +// ELF 0x314E10. An out-of-range polygon dereferences null, as in retail. +unsigned short ClusterGraph::getClusterId(QuadTree* quadTree, unsigned int polygon) const +{ + return quadTree->getPolygon(polygon)->cluster; +} + +// ELF 0x31DA70. True when one of the cluster's portals leads to `neighbour`. +bool ClusterGraph::areNeighbours(unsigned short cluster, unsigned short neighbour) const +{ + const Cluster& record = m_clusters[cluster]; + for (unsigned short i = 0; i < record.m_numberOfPortals; ++i) + { + if (m_portals[record.m_firstPortal + i].m_neighbourCluster == neighbour) + return true; + } + return false; +} + +// ELF 0x314E50. +ClusterPortal* ClusterGraph::getClusterPortal(unsigned short cluster, unsigned short costType, + unsigned short index) const +{ + const Cluster& record = m_clusters[cluster]; + return &m_portals[record.m_firstPortal + costType * record.m_numberOfPortals + index]; +} + +// ELF 0x314EA0. The index of the cluster's first portal into `neighbour`, or 0xFFFF. The +// cost-type offset plus index is truncated to 16 bits before the base is added, as in retail. +unsigned short ClusterGraph::getPortalForNeighbour(unsigned short cluster, + unsigned short costType, + unsigned short neighbour) const +{ + if (cluster == 0xFFFF) + return 0xFFFF; + const Cluster& record = m_clusters[cluster]; + for (unsigned short i = 0; i < record.m_numberOfPortals; ++i) + { + const unsigned short offset = + static_cast(costType * record.m_numberOfPortals + i); + if (m_portals[record.m_firstPortal + offset].m_neighbourCluster == neighbour) + return i; + } + return 0xFFFF; +} + +// ELF 0x314F30. The neighbour cluster's index of the same portal: the same polygon key and a +// position within 0.1 (squared distance under 0.01). +unsigned short ClusterGraph::getCorrespongingPortalInNeighbour(ClusterPortal* portal, + unsigned short costType) const +{ + const unsigned short neighbour = portal->m_neighbourCluster; + if (neighbour == 0xFFFF) + return 0xFFFF; + const Cluster& record = m_clusters[neighbour]; + for (unsigned short i = 0; i < record.m_numberOfPortals; ++i) + { + const ClusterPortal& candidate = + m_portals[record.m_firstPortal + costType * record.m_numberOfPortals + i]; + if (candidate.m_polygon != portal->m_polygon) + continue; + const float dx = candidate.m_position.x - portal->m_position.x; + const float dy = candidate.m_position.y - portal->m_position.y; + const float dz = candidate.m_position.z - portal->m_position.z; + if (0.01f > dx * dx + dy * dy + dz * dz) + return i; + } + return 0xFFFF; +} + +// ELF 0x31CEE0. Portal-to-portal costs are a triangular table per cluster and cost type: the pair +// (lo, hi) is entry T(n) - T(n - lo) + (hi - lo) after the cluster's base, T(k) = k(k - 1) / 2, +// read one before that position. Every intermediate is truncated to 16 bits as in retail. +float ClusterGraph::getCostBetweenClustersPortals(unsigned short cluster, unsigned short first, + unsigned short second, + unsigned short costType) const +{ + const Cluster& record = m_clusters[cluster]; + const unsigned short lo = first < second ? first : second; + const unsigned short hi = first < second ? second : first; + const int count = record.m_numberOfPortals; + const unsigned short pairs = static_cast(count * (count - 1) / 2); + const int remaining = static_cast(count - lo); + const unsigned short tail = static_cast(remaining * (remaining - 1) / 2); + const unsigned short within = static_cast( + pairs - tail + static_cast(hi - lo)); + const int index = record.m_firstPortalCost + pairs * costType + within; + return m_portalCosts[index - 1]; +} + +// ELF 0x315050. Appends the cluster's portals of one cost type; an unknown cluster adds none. +void ClusterGraph::getClusterPortals(unsigned short cluster, unsigned short costType, + std::list& portals) const +{ + if (cluster >= m_numberOfClusters) + return; + const Cluster& record = m_clusters[cluster]; + for (unsigned short i = 0; i < record.m_numberOfPortals; ++i) + portals.push_back( + &m_portals[record.m_firstPortal + costType * record.m_numberOfPortals + i]); +} + +// ELF 0x31CF90. Like getPortalForNeighbour, without the 0xFFFF guard or the 16-bit truncation. +unsigned short ClusterGraph::findClusterPortalWithNeighbour(unsigned short cluster, + unsigned short costType, + unsigned short neighbour) const +{ + const Cluster& record = m_clusters[cluster]; + for (unsigned short i = 0; i < record.m_numberOfPortals; ++i) + { + if (m_portals[record.m_firstPortal + costType * record.m_numberOfPortals + i] + .m_neighbourCluster == neighbour) + return i; + } + return 0xFFFF; +} + +// ELF 0x31CE30. Mirrors getCostBetweenClustersPortals: the smaller portal index first, the +// same 16-bit truncations, and the store at index - 1. +void ClusterGraph::setCostBetweenClustersPortals(unsigned short cluster, unsigned short first, + unsigned short second, unsigned short costType, + float cost) +{ + const Cluster& record = m_clusters[cluster]; + const unsigned short lo = first < second ? first : second; + const unsigned short hi = first < second ? second : first; + const int count = record.m_numberOfPortals; + const unsigned short pairs = static_cast(count * (count - 1) / 2); + const int remaining = static_cast(count - lo); + const unsigned short tail = static_cast(remaining * (remaining - 1) / 2); + const unsigned short within = static_cast( + pairs - tail + static_cast(hi - lo)); + const int index = record.m_firstPortalCost + pairs * costType + within; + m_portalCosts[index - 1] = cost; +} + +// ELF 0x31CA80. One step of the incremental portal-cost update of `cluster`: `state` is +// (first portal, second portal, cost type), starting at (0, 1, 0) when the caller has no search +// resource yet (one is acquired for owner 1234; none free -> false). The step restricts the +// search to the cluster and both portals' neighbour clusters (m_set30) and asks +// AIPathfinding::getPortalCost; while that search runs the answer is false. A finished pair is +// stored, the resource is released and re-acquired, and the state advances: next cost type, +// then next second portal (cost type 0), then next first portal (second = first + 1). True once +// the first portal passes the last one. Retail also constructs and frees an unused local +// std::vector (4-byte elements; -0x3C..-0x34) and has an unused static `clusterUpdate`. +bool ClusterGraph::updatePortalCosts(unsigned int& resource, + triple& state, + int map, unsigned int island, unsigned short cluster) +{ + AIPathfinding* const pathfinding = static_cast(IAIPathfinding::instance); + const Cluster& record = m_clusters[cluster]; + const unsigned short numberOfPortals = record.m_numberOfPortals; + const unsigned int firstPortal = record.m_firstPortal; + + if (resource == 0xFFFFFFFFu) + { + state.first = 0; + state.second = 1; + state.third = 0; + pathfinding->acquireResource(resource, 1234); + if (resource == 0xFFFFFFFFu) + return false; + } + + const ClusterPortal* const from = &m_portals[state.first + firstPortal]; + const ClusterPortal* const to = &m_portals[state.second + firstPortal]; + m_set30.clear(); + m_set30.insert(cluster); + m_set30.insert(from->m_neighbourCluster); + m_set30.insert(to->m_neighbourCluster); + + float cost; + if (!pathfinding->getPortalCost(cost, resource, map, island, state.third, from->m_position, + from->m_polygon, to->m_position, to->m_polygon, m_set30)) + return false; + + pathfinding->releaseResource(resource, 1234); + setCostBetweenClustersPortals(cluster, state.first, state.second, state.third, cost); + ++state.third; + if (!pathfinding->isValidClusterType(map, state.third)) + { + state.third = 0; + ++state.second; + if (state.second >= numberOfPortals) + { + const unsigned short previous = state.first; + ++state.first; + if (state.first >= numberOfPortals) + return true; + state.second = static_cast(previous + 2); + } + } + pathfinding->acquireResource(resource, 1234); + return false; +} + +// ELF 0x314740. Writes the version-5 record readFromFile reads; empty portal and cost arrays are +// written as their zero count alone. +void ClusterGraph::saveToFile(io::File& file) const +{ + file.write(5); + file.write(m_numberOfClusters); + file.write(m_clusters, sizeof(Cluster) * m_numberOfClusters); + file.write(m_polygonCount); + file.write(m_clusterPolygons, sizeof(unsigned int) * m_polygonCount); + file.write(m_numberOfPortals); + if (m_numberOfPortals) + file.write(m_portals, sizeof(ClusterPortal) * m_numberOfPortals); + file.write(m_numberOfPortalCosts); + if (m_numberOfPortalCosts) + file.write(m_portalCosts, sizeof(float) * m_numberOfPortalCosts); +} + +// ELF 0x31C2E0. Rebuilds the whole portal-to-portal cost table: for every cluster (its base is +// the running table size) and every valid cluster cost type, one blocking search per portal pair +// (i < j), restricted to the cluster and both portals' neighbour clusters. The old table is freed +// first; its count is only rewritten at the end. Retail also keeps a per-cluster +// std::list > whose iterator is stepped once per appended cost and never read, +// and a final pass that recomputes each pair's distance and stored cost without using either. +void ClusterGraph::calculatePortalCosts(int map, unsigned int island) +{ + AIPathfinding* const pathfinding = static_cast(IAIPathfinding::instance); + delete[] m_portalCosts; + + std::vector portalCosts; + std::vector costs; + for (unsigned int cluster = 0; cluster < m_numberOfClusters; ++cluster) + { + std::list > unusedCosts; + Cluster& record = m_clusters[cluster]; + const unsigned short count = record.m_numberOfPortals; + record.m_firstPortalCost = static_cast(portalCosts.size()); + unsigned int first = record.m_firstPortal; + for (unsigned int costType = 0; pathfinding->isValidClusterType(map, costType); + ++costType, first += count) + { + for (unsigned short i = 0; i < count; ++i) + { + const ClusterPortal* const from = &m_portals[first + i]; + for (unsigned short j = static_cast(i + 1); j < count; ++j) + { + const ClusterPortal* const to = &m_portals[first + j]; + std::set allowedClusters; + allowedClusters.insert(static_cast(cluster)); + allowedClusters.insert(from->m_neighbourCluster); + allowedClusters.insert(to->m_neighbourCluster); + costs.resize(0); + pathfinding->getPortalCost(costs, static_cast(costType), map, + island, to->m_position, to->m_polygon, + from->m_position, from->m_polygon, + allowedClusters); + std::list >::iterator unused = unusedCosts.begin(); + for (std::vector::iterator cost = costs.begin(); cost != costs.end(); + ++cost, ++unused) + portalCosts.push_back(*cost); + } + } + } + } + + m_portalCosts = new float[portalCosts.size()]; + m_numberOfPortalCosts = static_cast(portalCosts.size()); + for (unsigned int i = 0; i < portalCosts.size(); ++i) + m_portalCosts[i] = portalCosts[i]; + + for (unsigned int cluster = 0; cluster < m_numberOfClusters; ++cluster) + { + const Cluster& record = m_clusters[cluster]; + const unsigned short count = record.m_numberOfPortals; + const unsigned int first = record.m_firstPortal; + for (unsigned short i = 0; i < count; ++i) + { + for (unsigned short j = static_cast(i + 1); j < count; ++j) + { + for (unsigned int costType = 0; pathfinding->isValidClusterType(map, costType); + ++costType) + { + const Vec3 a = m_portals[first + i + costType * count].m_position; + const Vec3 b = m_portals[first + j + costType * count].m_position; + const float dx = a.x - b.x; + const float dy = a.y - b.y; + const float dz = a.z - b.z; + const float distance = std::sqrt(dx * dx + dy * dy + dz * dz); + const float cost = getCostBetweenClustersPortals( + static_cast(cluster), i, j, + static_cast(costType)); + (void)distance; + (void)cost; + } + } + } + } +} + +// ELF 0x31B7F0. Snapshots every cluster's polygon count into a new array (the previous one is +// not freed). +void ClusterGraph::resetTempMemberSizes() +{ + m_tempMemberSizes = checkPointer(new unsigned int[m_numberOfClusters]); + for (unsigned int cluster = 0; cluster < m_numberOfClusters; ++cluster) + m_tempMemberSizes[cluster] = m_clusters[cluster].m_numberOfPolygons; +} + +// ELF 0x31B970. False as soon as the cluster's polygons border more than one other (assigned) +// cluster. +bool ClusterGraph::allNeighboursOfClusterInSameCluster(QuadTree* quadTree, + unsigned short cluster) const +{ + const Cluster& record = m_clusters[cluster]; + const unsigned int first = record.m_firstPolygon; + const unsigned int count = record.m_numberOfPolygons; + std::set neighbours; + for (unsigned int i = 0; i < count; ++i) + { + const unsigned int polygon = m_clusterPolygons[first + i]; + const Polygon* const candidate = quadTree->getPolygon(polygon); + for (unsigned char edge = 0; edge < candidate->vertexCount; ++edge) + { + const Polygon* const neighbour + = quadTree->getPolygon(quadTree->getNeighbourOfPolygon(polygon, edge)); + if (neighbour && neighbour->cluster != cluster && neighbour->cluster != 0xFFFF) + { + neighbours.insert(neighbour->cluster); + if (neighbours.size() > 1) + return false; + } + } + } + return true; +} + +// ELF 0x31BB90. A cluster of more than one polygon holds when every polygon has a neighbour in +// the same cluster. +bool ClusterGraph::checkClusterCondition(QuadTree* quadTree, unsigned short cluster) const +{ + const Cluster& record = m_clusters[cluster]; + const unsigned int first = record.m_firstPolygon; + const unsigned int count = record.m_numberOfPolygons; + if (count == 1) + return true; + + for (unsigned int i = 0; i < count; ++i) + { + const unsigned int polygon = m_clusterPolygons[first + i]; + const Polygon* const candidate = quadTree->getPolygon(polygon); + unsigned char edge = 0; + for (; edge < candidate->vertexCount; ++edge) + { + const Polygon* const neighbour + = quadTree->getPolygon(quadTree->getNeighbourOfPolygon(polygon, edge)); + if (neighbour && neighbour->cluster == cluster) + break; + } + if (edge >= candidate->vertexCount) + return false; + } + return true; +} + +// ELF 0x31BE50. Reports (printClusterInfo, then an error) every cluster whose member list holds a +// polygon assigned elsewhere; always true. +bool ClusterGraph::validateClusterGraphConnectivity(QuadTree* quadTree, bool verbose) +{ + for (unsigned short cluster = 0; cluster < m_numberOfClusters; ++cluster) + { + const Cluster& record = m_clusters[cluster]; + const unsigned int first = record.m_firstPolygon; + const unsigned int count = record.m_numberOfPolygons; + unsigned int members = 0; + for (unsigned int i = 0; i < count; ++i) + { + if (quadTree->getPolygon(m_clusterPolygons[first + i])->cluster == cluster) + ++members; + } + if (members != count) + { + printClusterInfo(cluster, quadTree, verbose); + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.cpp", 1578, "") + << "Bailing out in validateClusterGraphConnectivity()!"; + } + } + return true; +} + +// ELF 0x31C080. Reports the cluster id; the walk over its polygons reads each corner index and +// neighbour without printing them. +void ClusterGraph::printClusterInfo(unsigned short cluster, QuadTree* quadTree, bool) const +{ + if (cluster >= m_numberOfClusters) + return; + + const Cluster& record = m_clusters[cluster]; + const unsigned int first = record.m_firstPolygon; + const unsigned int count = record.m_numberOfPolygons; + // operator<<(int): the listing carries its inlined oct/hex test. + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.cpp", 1596, "") + << "Cluster info for cluster " << static_cast(cluster); + + for (unsigned int i = 0; i < count; ++i) + { + const unsigned int polygon = m_clusterPolygons[first + i]; + const Polygon* const candidate = quadTree->getPolygon(polygon); + for (unsigned char edge = 0; edge < candidate->vertexCount; ++edge) + { + quadTree->getVertexIndexForPolygon(polygon, edge); + quadTree->getPolygon(quadTree->getNeighbourOfPolygon(polygon, edge)); + } + } +} + +// ELF 0x31D000. Debug view of one cluster and cost type (30 s): its id above the first portal, +// a red circle per portal, and per portal pair a line and the stored cost at its midpoint. The +// first portal is read even for a cluster without portals. +void ClusterGraph::drawCluster(unsigned short cluster, int costType) const +{ + Vec3 up; + up.x = 0.0f; + up.y = 1.0f; + up.z = 0.0f; + const Cluster& record = m_clusters[cluster]; + IDPStaticCreator* const creator + = static_cast(CommonSingletonServer::m_iDPStaticCreator); + const unsigned short count = record.m_numberOfPortals; + const unsigned int first = record.m_firstPortal + costType * count; + const ClusterPortal* const firstPortal = &m_portals[first]; + + { + std::stringstream text; + text << cluster; + Vec3 position; + position.x = up.x + firstPortal->m_position.x; + position.y = up.y + firstPortal->m_position.y; + position.z = up.z + firstPortal->m_position.z; + creator->createStatic3dText(30.0f, 0x5588u, position, text.str(), 0, + static_cast(0), + static_cast(0)); + } + + for (unsigned short i = 0; i < count; ++i) + { + const ClusterPortal* const portal = &m_portals[first + i]; + creator->createStaticCircle(30.0f, 0xFFFF0000u, portal->m_position, 0.5f, up, false, 10); + for (unsigned short j = static_cast(i + 1); j < count; ++j) + { + const ClusterPortal* const other = &m_portals[first + j]; + creator->createStaticLine(30.0f, 0xAAAA0000u, portal->m_position, other->m_position, + 0.25f); + Vec3 middle; + middle.x = (portal->m_position.x + other->m_position.x) * 0.5f; + middle.y = (portal->m_position.y + other->m_position.y) * 0.5f; + middle.z = (portal->m_position.z + other->m_position.z) * 0.5f; + std::stringstream text; + text << getCostBetweenClustersPortals(cluster, i, j, + static_cast(costType)); + creator->createStatic3dText(30.0f, 0x88u, middle, text.str(), 0, + static_cast(0), + static_cast(0)); + } + } +} + } // namespace ai } // namespace hfe } // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.h b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.h index 6cf66e128..06d8d667e 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.h +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.h @@ -1,13 +1,15 @@ -// Navigation cluster graph with file loading and cleanup. -// [FRONTIER] Remaining graph queries and mesh generation require implementation. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. +// Navigation cluster graph with GTS construction, optimisation fix-ups and portal queries. #ifndef AI_AIDLL_AI_AIPATHFINDING_CLUSTER_CLUSTERGRAPH_H #define AI_AIDLL_AI_AIPATHFINDING_CLUSTER_CLUSTERGRAPH_H +#include #include +#include +#include #include "../../Main/AIDllTypes.h" // Vec3 +#include "../../Main/IAIPathfinding.h" // ai::triple #include "Cluster.h" namespace dice { @@ -18,6 +20,8 @@ namespace io { class File; } namespace ai { class QuadTree; +class OptPolygon; +class MaterialManager; // Portal record used by the cluster graph and its serialized format. class ClusterPortal @@ -25,8 +29,10 @@ class ClusterPortal public: ClusterPortal() { m_position.x = 0.0f; m_position.y = 0.0f; m_position.z = 0.0f; } - /* +0x00 */ Vec3 m_position; // [INFERRED] name - /* +0x0C */ unsigned char m_unread0C[8]; // [UNRESOLVED] - see the note above + /* +0x00 */ Vec3 m_position; // [INFERRED] name + /* +0x0C */ unsigned short m_neighbourCluster; // [INFERRED] name; areNeighbours compares it + /* +0x0E */ unsigned char m_unread0E[2]; // [UNRESOLVED] - see the note above + /* +0x10 */ unsigned int m_polygon; // [INFERRED] name: ClusterNodePath::getPoint hands it out }; typedef char ClusterPortalIsTheFileRecord[sizeof(ClusterPortal) == 20 ? 1 : -1]; @@ -34,27 +40,98 @@ typedef char ClusterPortalIsTheFileRecord[sizeof(ClusterPortal) == 20 ? 1 : -1]; class ClusterGraph { public: + struct ClusterPortalBuildInfo + { + // Field names are inferred from the portal builder; ia-32 offsets are 0, 4 and 8. + unsigned int firstVertex; + unsigned int secondVertex; + unsigned short neighbour; + }; + typedef std::map > VertexClusterEdges; + typedef std::map > > ClusterEdges; + typedef std::map > PortalBuildMap; + typedef std::map > DynamicPolygonMap; + typedef std::map > ClusterPolygonMap; + ClusterGraph(); ~ClusterGraph(); void clean(); void readFromFile(io::File& file); + void readGTSDataFromFile(QuadTree* quadTree, io::File& file); + void createPortals(int map, QuadTree* quadTree, float radius); + void buildClusterEdges(const Cluster&, unsigned short, QuadTree*, VertexClusterEdges&, ClusterEdges&); + void buildPortalsFromClusterEdges(unsigned short, QuadTree*, const VertexClusterEdges&, + const ClusterEdges&, PortalBuildMap&); + bool calculateMiddleVertex(unsigned short, const ClusterPortalBuildInfo&, QuadTree*, + unsigned short, MaterialManager*, Vec3&, unsigned int&) const; + void adjustPolygonsInClusters(); + void movePolygonBetweenClusters(unsigned short, unsigned short, unsigned int); + void addPolygonsToNewCluster(const std::set&, std::list&); + void updateClustersAfterOptimisation(const DynamicPolygonMap&, std::list&, ClusterPolygonMap&); + void clearEmptyClusters(std::list&); + void splitClustersCutByDeepWater(const std::list&); + void moveDynamicObjectPolygonsToSeparateClusters(const std::list&, + const DynamicPolygonMap&, ClusterPolygonMap&); + void fixClusterGraphConnectivity(std::list&, bool); + void floodFillPolygonsInCluster(OptPolygon*, std::set&, bool) const; + void getAllDeepWaterAndInvalidPolygonsInCluster(unsigned short, const std::list&, + std::set&) const; + void setPolygonIndices(const ClusterPolygonMap&); + void recurseFloodFill(OptPolygon*, OptPolygon*, std::set&) const; + bool validateClusterConnectivityFromPolygon(unsigned short, OptPolygon*, unsigned int, + std::set&, bool) const; + void saveToFile(io::File& file) const; + // Recomputes every portal-to-portal cost of the map's island with blocking searches. + void calculatePortalCosts(int map, unsigned int island); + void resetTempMemberSizes(); + bool allNeighboursOfClusterInSameCluster(QuadTree* quadTree, unsigned short cluster) const; + bool checkClusterCondition(QuadTree* quadTree, unsigned short cluster) const; + bool validateClusterGraphConnectivity(QuadTree* quadTree, bool verbose); + void printClusterInfo(unsigned short cluster, QuadTree* quadTree, bool verbose) const; + void drawCluster(unsigned short cluster, int costType) const; // [CHOSEN name] Returns the stored cluster count used by QuadTreeManager. unsigned int getNumberOfClusters() const { return m_numberOfClusters; } + unsigned short getClusterId(QuadTree* quadTree, unsigned int polygon) const; + bool areNeighbours(unsigned short cluster, unsigned short neighbour) const; + // Portal queries. A cluster's portals are stored once per cost type: portal `index` of cost + // type `costType` is m_portals[first + costType * count + index]. + ClusterPortal* getClusterPortal(unsigned short cluster, unsigned short costType, + unsigned short index) const; + unsigned short getPortalForNeighbour(unsigned short cluster, unsigned short costType, + unsigned short neighbour) const; + unsigned short getCorrespongingPortalInNeighbour(ClusterPortal* portal, + unsigned short costType) const; + float getCostBetweenClustersPortals(unsigned short cluster, unsigned short first, + unsigned short second, unsigned short costType) const; + void getClusterPortals(unsigned short cluster, unsigned short costType, + std::list& portals) const; + unsigned short findClusterPortalWithNeighbour(unsigned short cluster, unsigned short costType, + unsigned short neighbour) const; + // ELF 0x31CE30. The setter twin of getCostBetweenClustersPortals (same pair index). + void setCostBetweenClustersPortals(unsigned short cluster, unsigned short first, + unsigned short second, unsigned short costType, float cost); + bool updatePortalCosts(unsigned int& resource, triple& portal, + int map, unsigned int island, unsigned short costType); + private: + friend class GTSDataOptimiser; + friend class ClusterNodeManager; friend class QuadTree; + friend class QuadTreeManager; /* +0x00 */ unsigned int* m_clusterPolygons; // [INFERRED] polygon indices grouped by cluster - /* +0x04 */ unsigned int m_numberOfClusterPolygons; // (Dalian Infantry: 18,512, every polygon once) + /* +0x04 */ unsigned int m_polygonCount; // (Dalian Infantry: 18,512, every polygon once) // name: AIDLL_r assert 0x10179F30 (+4) /* +0x08 */ Cluster* m_clusters; // getClusterPortal /* +0x0C */ unsigned int m_numberOfClusters; // loadQuadTrees' empty walk bound /* +0x10 */ unsigned int m_numberOfPortals; /* +0x14 */ ClusterPortal* m_portals; // getClusterPortal - /* +0x18 */ std::set m_set18; // [UNRESOLVED] roles for both sets and - /* +0x24 */ unsigned char* m_array24; // the +0x24 array: only the GTS - // generation path (not written) fills - // them; clean frees and nulls +0x24 + /* +0x18 */ std::set m_set18; // [INFERRED] removed polygon indices + /* +0x24 */ unsigned int* m_tempMemberSizes; // [INFERRED] name: resetTempMemberSizes + // fills it with every cluster's polygon + // count; clean frees and nulls it /* +0x28 */ unsigned int m_numberOfPortalCosts; // float: the PE allocates it through its own checkPointer instantiation (, not the // uint one at the +0x00 list uses), and the shipped values are plainly floats diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNode.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNode.cpp new file mode 100644 index 000000000..bf37c5fb0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNode.cpp @@ -0,0 +1,67 @@ +// The cluster A* node's out-of-line members. [INFERRED] file name: the image keeps them in their +// own translation unit (own static initialisation) between ClusterGraph's and +// ClusterNodeManager's. + +#include "ClusterNodeManager.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x31FBB0, __tcf_0 0x31FC10, _GLOBAL__I 0x31FC40). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x31F9B0 (C2; C1 0x31FA00). +ClusterNode::ClusterNode(unsigned short cluster, unsigned int depth) + : m_next(0) + , m_prev(0) + , m_parent(0) + , m_g(0.0f) + , m_f(0.0f) + , m_key(cluster) + , m_portal(0xFFFF) + , m_depth(static_cast(depth)) +{ +} + +// ELF 0x31FA50 (C2; C1 0x31FAA0). +ClusterNode::ClusterNode(const ClusterNode& other) + : m_next(0) + , m_prev(0) + , m_parent(0) + , m_g(0.0f) + , m_f(0.0f) + , m_key(other.m_key) + , m_portal(other.m_portal) + , m_depth(0) +{ +} + +// ELF 0x31FAF0 (D2; D1 0x31FB00): empty. +ClusterNode::~ClusterNode() +{ +} + +// ELF 0x31FB10. +ClusterNode* ClusterNode::expandFirst(ClusterNodeManager* manager, nodeStatus::Status& status, + unsigned short& portal) +{ + portal = 0; + ClusterNode* const neighbour = manager->getNeighbourOfNode(this, portal, status); + ++portal; + return neighbour; +} + +// ELF 0x31FB60. +ClusterNode* ClusterNode::expand(ClusterNodeManager* manager, nodeStatus::Status& status, + unsigned short& portal) +{ + ClusterNode* const neighbour = manager->getNeighbourOfNode(this, portal, status); + ++portal; + return neighbour; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.cpp index 22f14ce44..d664f9116 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.cpp @@ -2,44 +2,469 @@ #include "ClusterNodeManager.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x3215F0, __tcf_0 0x321650, _GLOBAL__I 0x321680). +#include + +#include + +#include "ClusterGraph.h" +#include "../NavMesh/QuadTree.h" #include "../../AIUtils/checkPointer.h" -#include "../../Main/AIDllFrontier.h" +#include "../../Main/IAIPathfinding.h" +#include "../../../../../Core/Debug.h" namespace dice { namespace hfe { namespace ai { -// Initializes empty node lists and a 313-bucket hash linked to this manager. +namespace { + +// ELF 0x31FC60. Reports a node that is its own ancestor within ten generations. The result is +// discarded by both retail callers. +bool checkHeritage(ClusterNode* node) +{ + int generation = 0; + for (ClusterNode* ancestor = node->m_parent; ancestor != 0; ancestor = ancestor->m_parent) + { + if (ancestor == node) + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.cpp", 38, "") + << "Circular heritage for " << static_cast(ancestor->m_key); + return false; + } + ++generation; + if (generation > 9) + break; + } + return true; +} + +} // namespace + +// ClusterNodeManager +// ELF 0x31FDD0 (C2; C1 0x320010). Positions zeroed, empty pools, a 313-bucket status hash linked to this manager. ClusterNodeManager::ClusterNodeManager() : m_quadTree(0) , m_clusterGraph(0) - , m_i8(0) - , m_i12(0) - , m_i16(0) - , m_i20(0) - , m_i24(0) - , m_i28(0) - , m_i32(0) - , m_i36(0) - , m_i40(0) + , m_goal(0) + , m_freeNodes(0) + , m_nodeCacheSize(0) , m_freeOCData(0) - , m_i48(0) + , m_ocCacheSize(0) , m_ocDataHash(checkPointer(new Hash(kOCDataBuckets))) - , m_i56(0) - , m_i60(0) - , m_i64(0) - , m_i68(0) + , m_costType(0) { + m_start.x = 0.0f; + m_start.y = 0.0f; + m_start.z = 0.0f; + m_goalPosition.x = 0.0f; + m_goalPosition.y = 0.0f; + m_goalPosition.z = 0.0f; m_ocDataHash->m_nodeManager = this; } -// [FRONTIER] Cleanup of the hash, buckets, and OCData chain remains unimplemented. -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -// Replace the stop when ordered node-manager teardown is recovered. +// ELF 0x3201E0 (D2; D1 0x320370). Frees the node pool, the record pool, every hashed record and its node, the hash +// and the goal copy. Retail reads each hashed record's chain link after deleting it; the link is +// read first here ([CHOSEN], the same walk without the use after free). ClusterNodeManager::~ClusterNodeManager() { - BF2_AI_FRONTIER("dice::hfe::ai::ClusterNodeManager::~ClusterNodeManager"); + while (m_freeNodes != 0) + { + ClusterNode* const node = m_freeNodes; + m_freeNodes = node->m_next; + delete node; + --m_nodeCacheSize; + } + + while (m_freeOCData != 0) + { + OCData* const data = m_freeOCData; + m_freeOCData = data->m_next; + delete data; + --m_ocCacheSize; + } + + Hash* const hash = m_ocDataHash; + Hash::iterator it = hash->begin(); + while (it != hash->end()) + { + OCData* const data = it.m_node; + OCData* const next = data->m_next; + if (data->m_node != 0) + delete data->m_node; + delete data; + --m_ocCacheSize; + --m_nodeCacheSize; + it.m_node = next; + if (it.m_node == 0) + { + it.m_bucket = it.m_bucket->m_nextUsed; + if (it.m_bucket != 0) + it.m_node = it.m_bucket->m_head; + } + } + if (hash != 0) + { + if (hash->m_buckets != 0) + delete[] hash->m_buckets; + delete hash; + } + + if (m_goal != 0) + { + delete m_goal; + --m_nodeCacheSize; + } +} + +// ELF 0x320500. +void ClusterNodeManager::setQuadTree(QuadTree* quadTree) +{ + m_quadTree = quadTree; +} + +// ELF 0x320510. +void ClusterNodeManager::setClusterGraph(ClusterGraph* clusterGraph) +{ + m_clusterGraph = clusterGraph; +} + +// ELF 0x320520. Keeps a private copy of the goal's cluster and portal and recycles `node`. +void ClusterNodeManager::setGoal(ClusterNode* node) +{ + if (m_goal == 0) + m_goal = getNewNode(node); + else + { + m_goal->m_key = node->m_key; + m_goal->m_portal = node->m_portal; + } + recycleNode(node); +} + +// ELF 0x320590. A probe record is built first; an existing record is marked open and the probe +// recycled, otherwise the probe itself is hashed as the node's open record. +void ClusterNodeManager::setNodeOpen(ClusterNode* node) +{ + OCData* const probe = getNewOCData(); + probe->m_open = true; + probe->m_node = node; + probe->m_closed = false; + + OCData* const existing = m_ocDataHash->get(probe); + if (existing != 0) + { + recycleOCData(probe); + existing->m_open = true; + return; + } + m_ocDataHash->insert(probe); +} + +// ELF 0x3206B0. The record must exist: retail writes through the lookup unchecked. +void ClusterNodeManager::setNodeClosed(ClusterNode* node) +{ + OCData* const probe = getNewOCData(); + probe->m_open = true; + probe->m_closed = false; + probe->m_node = node; + OCData* const existing = m_ocDataHash->get(probe); + recycleOCData(probe); + existing->m_open = false; + existing->m_closed = true; +} + +// ELF 0x320730. The neighbour cluster behind the first usable portal at or after `portal`. A portal +// is usable when the best route to its neighbour cluster costs something non-negative, does not +// start from the portal this node was entered through, and is not an earlier portal (so each +// neighbour is reached once, through its cheapest portal). The new node enters the neighbour +// through the matching portal there; unseen neighbours are costed (the goal only flagged). +ClusterNode* ClusterNodeManager::getNeighbourOfNode(ClusterNode* node, unsigned short& portal, + nodeStatus::Status& status) +{ + const Cluster& cluster = m_clusterGraph->m_clusters[node->m_key]; + unsigned short neighbourPortal = 0xFFFF; + unsigned short bestPortal; + if (portal >= cluster.m_numberOfPortals) + { + status = nodeStatus::kInvalid; + return 0; + } + + float cost = findBestPortalAndCost(bestPortal, neighbourPortal, node, node->m_portal, portal, + node->m_key); + for (;;) + { + if (cluster.m_numberOfPortals <= portal) + { + status = nodeStatus::kInvalid; + return 0; + } + if (cost >= 0.0f && neighbourPortal != 0xFFFF && node->m_portal != portal && + bestPortal >= portal) + break; + ++portal; + cost = findBestPortalAndCost(bestPortal, neighbourPortal, node, node->m_portal, portal, + node->m_key); + } + + const ClusterPortal* const exit = m_clusterGraph->getClusterPortal( + node->m_key, static_cast(m_costType), bestPortal); + ClusterNode* const neighbour = getNewNode(exit->m_neighbourCluster, node, node->m_depth + 1); + + OCData* const probe = getNewOCData(); + probe->m_open = true; + probe->m_closed = false; + probe->m_node = neighbour; + OCData* const existing = m_ocDataHash->get(probe); + if (existing != 0) + { + if (existing->m_open) + status = nodeStatus::kOpen; + else if (existing->m_closed) + status = nodeStatus::kClosed; + else + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.cpp", 233, "") + << "This case should not exists!"; + status = nodeStatus::kInvalid; + } + recycleOCData(probe); + return neighbour; + } + + checkHeritage(neighbour); + neighbour->m_portal = neighbourPortal; + if (neighbour->m_key == m_goal->m_key) + status = nodeStatus::kGoal; + else + { + status = nodeStatus::kUnvisited; + neighbour->m_g = cost; + neighbour->m_f = calculateHeuristicCost(cost, neighbourPortal, neighbour); + } + recycleOCData(probe); + return neighbour; +} + +// ELF 0x320B10. A recycled node keeps its costs, links and entry portal except the parent. +ClusterNode* ClusterNodeManager::getNewNode(unsigned short cluster, ClusterNode* parent, + unsigned int depth) +{ + ClusterNode* node = m_freeNodes; + if (node != 0) + { + node->m_key = cluster; + node->m_depth = static_cast(depth); + m_freeNodes = m_freeNodes->m_next; + } + else + { + node = new ClusterNode(cluster, depth); + ++m_nodeCacheSize; + } + node->m_parent = parent; + return node; +} + +// ELF 0x320B90. A recycled node is assigned every field of `source`; a new one is copy +// constructed, which keeps only the cluster and the entry portal. +ClusterNode* ClusterNodeManager::getNewNode(ClusterNode* source) +{ + ClusterNode* node = m_freeNodes; + if (node != 0) + { + m_freeNodes = node->m_next; + *node = *source; + } + else + { + node = new ClusterNode(*source); + ++m_nodeCacheSize; + } + return node; +} + +// ELF 0x320C30. Returns every hashed record's node to the pool, unhashes and recycles the records, +// then the goal copy. +void ClusterNodeManager::reset() +{ + Hash::iterator it = m_ocDataHash->begin(); + while (it != m_ocDataHash->end()) + { + OCData* const data = it.m_node; + recycleNode(data->m_node); + ++it; + m_ocDataHash->remove(data); + recycleOCData(data); + } + + if (m_goal != 0) + { + recycleNode(m_goal); + m_goal = 0; + } +} + +// ELF 0x320DE0: empty. +void ClusterNodeManager::returnReset() +{ +} + +// ELF 0x320DF0. Re-costs `existing` as reached from `parent` through the portal between them; +// taken only when strictly cheaper. Refused at the depth limit and for the start node. +bool ClusterNodeManager::updateNode(ClusterNode* parent, ClusterNode* existing, + unsigned int maxDepth) +{ + const int depth = parent->m_depth + 1; + if (maxDepth == static_cast(depth) || existing->m_parent == 0) + return false; + + const unsigned short costType = static_cast(m_costType); + const unsigned short portal = + m_clusterGraph->findClusterPortalWithNeighbour(parent->m_key, costType, existing->m_key); + unsigned short bestPortal; + unsigned short neighbourPortal; + const float cost = findBestPortalAndCost(bestPortal, neighbourPortal, parent, + parent->m_portal, portal, parent->m_key); + if (0.0f > cost) + return false; + + const float f = calculateHeuristicCost(cost, neighbourPortal, existing); + if (f >= existing->m_f) + return false; + + existing->m_portal = + m_clusterGraph->getPortalForNeighbour(existing->m_key, costType, parent->m_key); + existing->m_parent = parent; + checkHeritage(existing); + existing->m_g = cost; + existing->m_f = f; + existing->m_depth = depth; + existing->m_portal = neighbourPortal; + return true; +} + +// ELF 0x320F30. The accumulated cost of leaving `node` through `portal`: from the start position +// for the start node, otherwise the cluster's portal-to-portal table (-1 when negative). +float ClusterNodeManager::calculateCost(ClusterNode* node, unsigned short portal) const +{ + if (node == 0) + return 0.0f; + + const unsigned short costType = static_cast(m_costType); + if (node->m_portal != 0xFFFF) + { + const float step = m_clusterGraph->getCostBetweenClustersPortals(node->m_key, + node->m_portal, portal, + costType); + if (0.0f > step) + return -1.0f; + return step + node->m_g; + } + + const ClusterPortal* const exit = m_clusterGraph->getClusterPortal(node->m_key, costType, portal); + const float dx = exit->m_position.x - m_start.x; + const float dy = exit->m_position.y - m_start.y; + const float dz = exit->m_position.z - m_start.z; + return std::sqrt(dx * dx + dy * dy + dz * dz) + node->m_g; +} + +// ELF 0x321060. g plus the straight distance from the node's entry point to the goal position. +float ClusterNodeManager::calculateHeuristicCost(float cost, unsigned short portal, + ClusterNode* node) const +{ + const Vec3* const entry = getEntryPoint(portal, node); + const float dx = m_goalPosition.x - entry->x; + const float dy = m_goalPosition.y - entry->y; + const float dz = m_goalPosition.z - entry->z; + return cost + std::sqrt(dx * dx + dy * dy + dz * dz); +} + +// ELF 0x321110. Appends (cluster, entry portal) from the start to `goal`. The path's nodes are not +// cleared first; no cost is stored. +void ClusterNodeManager::buildPath(ClusterNodePath& path, ClusterNode* goal) +{ + m_pathNodes.resize(0); + for (ClusterNode* node = goal; node != 0; node = node->m_parent) + m_pathNodes.push_back(node); + + for (int i = static_cast(m_pathNodes.size()) - 1; i >= 0; --i) + path.m_nodes.push_back(std::make_pair(m_pathNodes[i]->m_key, m_pathNodes[i]->m_portal)); +} + +// ELF 0x321280. checkPointer guards the allocation (checkPointer.h line 46). +ClusterNodeManager::OCData* ClusterNodeManager::getNewOCData() +{ + if (m_freeOCData != 0) + { + OCData* const data = m_freeOCData; + m_freeOCData = data->m_next; + return data; + } + + ++m_ocCacheSize; + OCData* const data = new OCData; + data->m_open = true; + data->m_closed = false; + data->m_node = 0; + data->m_next = 0; + return checkPointer(data); +} + +// ELF 0x3213F0. +void ClusterNodeManager::recycleOCData(OCData* data) +{ + data->m_next = m_freeOCData; + m_freeOCData = data; +} + +// ELF 0x321410. The start position for a node without a parent, else the portal's position. +const Vec3* ClusterNodeManager::getEntryPoint(unsigned short portal, ClusterNode* node) const +{ + if (node->m_parent == 0) + return &m_start; + return &m_clusterGraph + ->getClusterPortal(node->m_key, static_cast(m_costType), portal) + ->m_position; +} + +// ELF 0x321470. Among the cluster's portals into the same neighbour as `portal`, the cheapest +// non-negative calculateCost; its index goes to `bestPortal` and the neighbour's matching portal +// to `neighbourPortal` (0xFFFF when none). -1 when the neighbour is not a valid, walkable +// cluster or nothing qualifies. `entryPortal` is not read. +float ClusterNodeManager::findBestPortalAndCost(unsigned short& bestPortal, + unsigned short& neighbourPortal, + ClusterNode* node, unsigned short, + unsigned short portal, + unsigned short cluster) const +{ + const Cluster& record = m_clusterGraph->m_clusters[cluster]; + const unsigned short costType = static_cast(m_costType); + const unsigned int neighbour = + m_clusterGraph->getClusterPortal(cluster, costType, portal)->m_neighbourCluster; + if (neighbour >= m_clusterGraph->m_numberOfClusters || + m_clusterGraph->m_clusters[neighbour].m_walkable == 0) + return -1.0f; + + float best = 1e9f; + neighbourPortal = 0xFFFF; + for (unsigned short i = 0; i < record.m_numberOfPortals; ++i) + { + ClusterPortal* const candidate = m_clusterGraph->getClusterPortal(cluster, costType, i); + if (candidate->m_neighbourCluster != neighbour) + continue; + const float cost = calculateCost(node, i); + if (best > cost && cost >= 0.0f) + { + bestPortal = i; + neighbourPortal = m_clusterGraph->getCorrespongingPortalInNeighbour(candidate, costType); + best = cost; + } + } + return neighbourPortal == 0xFFFF ? -1.0f : best; } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.h b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.h index 0f8dbf2e7..010361ba7 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.h +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.h @@ -1,57 +1,120 @@ -// Node pool for cluster-graph A* searches, including an intrusive free list for open/closed records. -// returnReset is intentionally empty. -// [FRONTIER] Remaining search operations require implementation. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the node-pool lifecycle and search operations. +// Cluster-graph A* search nodes and their manager: node and open/closed-record pools, portal +// expansion, costs and path building. Placement of ClusterNode and ClusterNodePath's methods in +// this file is [INFERRED]: their functions sit beside the manager's in the ELF. #ifndef AI_AIDLL_AI_AIPATHFINDING_CLUSTER_CLUSTERNODEMANAGER_H // [INFERRED] guard style #define AI_AIDLL_AI_AIPATHFINDING_CLUSTER_CLUSTERNODEMANAGER_H -#include "../../Main/AIPathfindingSearchTypes.h" // Hash +#include + +#include "../../Main/AIPathfindingSearchTypes.h" // Hash, nodeStatus namespace dice { namespace hfe { namespace ai { class ClusterGraph; +class ClusterNodeManager; class QuadTree; -class ClusterNode; + +// One A* node: a cluster entered through one of its portals. 28 bytes (operator new(0x1C)). +class ClusterNode +{ +public: + ClusterNode(unsigned short cluster, unsigned int depth); + // Copies the cluster and the entry portal; links, costs and depth start cleared. + ClusterNode(const ClusterNode& other); + ~ClusterNode(); + + // Portal iteration for AStarResource::update: expandFirst starts at portal 0. Both advance + // `portal` past the one they report. + ClusterNode* expandFirst(ClusterNodeManager* manager, nodeStatus::Status& status, + unsigned short& portal); + ClusterNode* expand(ClusterNodeManager* manager, nodeStatus::Status& status, + unsigned short& portal); + + /* +0x00 */ ClusterNode* m_next; // hash chain / free-list link + /* +0x04 */ ClusterNode* m_prev; + /* +0x08 */ ClusterNode* m_parent; + /* +0x0C */ float m_g; + /* +0x10 */ float m_f; + /* +0x14 */ unsigned short m_key; // the cluster + /* +0x16 */ unsigned short m_portal; // entry portal index in this cluster; 0xFFFF for the start + /* +0x18 */ int m_depth; +}; class ClusterNodeManager { public: - // The open/closed record. Its only recovered field is the free-list link at +8, which - // `recycleOCData` writes, so the type stays incomplete here rather than guessing a size. - // Attested as a nested type by the mangled names of `getNewOCData`, `recycleOCData` and - // `HashIterator`. - class OCData; + // The open/closed record of one cluster node, kept in a hash keyed by the node's cluster. + // 16 bytes; +12 is not written on allocation. Names [INFERRED]; the nested type is attested by + // the mangled names of getNewOCData, recycleOCData and HashIterator. + class OCData + { + public: + /* +0 */ bool m_open; + /* +1 */ bool m_closed; + /* +4 */ ClusterNode* m_node; + /* +8 */ OCData* m_next; // hash chain / free-list link + /* +12 */ OCData* m_prev; + }; // the same prime the cluster search resource'S two hashes use. A literal in the binary. enum { kOCDataBuckets = 313 }; ClusterNodeManager(); - ~ClusterNodeManager(); // , [FRONTIER] + ~ClusterNodeManager(); + + void setQuadTree(QuadTree* quadTree); + void setClusterGraph(ClusterGraph* clusterGraph); + void setGoal(ClusterNode* node); + void setNodeOpen(ClusterNode* node); + void setNodeClosed(ClusterNode* node); + ClusterNode* getNeighbourOfNode(ClusterNode* node, unsigned short& portal, + nodeStatus::Status& status); + ClusterNode* getNewNode(unsigned short cluster, ClusterNode* parent, unsigned int depth); + ClusterNode* getNewNode(ClusterNode* source); + void reset(); + void returnReset(); + bool updateNode(ClusterNode* parent, ClusterNode* existing, unsigned int maxDepth); + float calculateCost(ClusterNode* node, unsigned short portal) const; + float calculateHeuristicCost(float cost, unsigned short portal, ClusterNode* node) const; + void buildPath(ClusterNodePath& path, ClusterNode* goal); + OCData* getNewOCData(); + void recycleOCData(OCData* data); + const Vec3* getEntryPoint(unsigned short portal, ClusterNode* node) const; + float findBestPortalAndCost(unsigned short& bestPortal, unsigned short& neighbourPortal, + ClusterNode* node, unsigned short entryPortal, + unsigned short portal, unsigned short cluster) const; + + // [INFERRED] Inlined in every retail user: returns a node to the free list. + void recycleNode(ClusterNode* node) + { + node->m_next = m_freeNodes; + m_freeNodes = node; + } - // layout, on the ELF, read store by store out of the constructor + // layout, on the ELF /* +0 */ QuadTree* m_quadTree; // = 0; `setQuadTree` writes it /* +4 */ ClusterGraph* m_clusterGraph; // = 0; `setClusterGraph` writes it - /* +8 */ int m_i8; // = 0 [UNRESOLVED] - /* +12 */ int m_i12; // = 0 [UNRESOLVED] - /* +16 */ int m_i16; // = 0 [UNRESOLVED] - /* +20 */ int m_i20; // = 0 [UNRESOLVED] - /* +24 */ int m_i24; // = 0 [UNRESOLVED] - /* +28 */ int m_i28; // = 0 [UNRESOLVED] - /* +32 */ int m_i32; // = 0 [UNRESOLVED] - /* +36 */ int m_i36; // = 0 [UNRESOLVED] - /* +40 */ int m_i40; // = 0 [UNRESOLVED] + /* +8 */ Vec3 m_start; // the search's start position + /* +20 */ Vec3 m_goalPosition; // the search's goal position + /* +32 */ ClusterNode* m_goal; // = 0; setGoal's copy of the goal node + /* +36 */ ClusterNode* m_freeNodes; // = 0 + /* +40 */ int m_nodeCacheSize; // = 0 // name: AIDLL_r assert 0x1018FDD0 (PE +0x28) /* +44 */ OCData* m_freeOCData; // = 0 the intrusive free list `recycleOCData` pushes to - /* +48 */ int m_i48; // = 0 [UNRESOLVED] + /* +48 */ int m_ocCacheSize; // = 0 // name: AIDLL_r assert 0x1018FDD0 (PE +0x30) /* +52 */ Hash* m_ocDataHash; // new Hash(313), then ->this - /* +56 */ int m_i56; // = 0 [UNRESOLVED] - /* +60 */ int m_i60; // = 0 [UNRESOLVED] - /* +64 */ int m_i64; // = 0 [UNRESOLVED] - /* +68 */ int m_i68; // = 0 [UNRESOLVED] + /* +56 */ std::vector m_pathNodes; // buildPath's goal-to-start scratch list + /* +68 */ int m_costType; // the vehicle's cluster cost type; read as 16 bits }; +// The status records hash by their node's cluster. +inline int hashKeyOf(const ClusterNodeManager::OCData* data) +{ + return static_cast(data->m_node->m_key); +} + } // namespace ai } // namespace hfe } // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodePath.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodePath.cpp new file mode 100644 index 000000000..0b2f41f4d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodePath.cpp @@ -0,0 +1,66 @@ +// The cluster path result's out-of-line members. [INFERRED] file name: the image keeps them in +// their own translation unit (own static initialisation) after ClusterNodeManager's. + +#include "ClusterNodeManager.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x322170, __tcf_0 0x3221D0, _GLOBAL__I 0x322200). +#include + +#include "ClusterGraph.h" +#include "../../Main/IAIPathfinding.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x321E90 (C2; C1 0x321EC0). Only the step index and the node vector are set; map, cost +// type and island are left to setVehicle and clusterSearch. +ClusterNodePath::ClusterNodePath() + : m_i0(0) +{ +} + +// ELF 0x321EF0 (D2; D1 0x321F50). +ClusterNodePath::~ClusterNodePath() +{ +} + +// ELF 0x321FB0. +void ClusterNodePath::setVehicle(int map, int vehicleId) +{ + m_map = map; + m_costType = IAIPathfinding::instance->getClusterCostType(m_map, vehicleId); +} + +// ELF 0x322000. +bool ClusterNodePath::getPoint(Vec3& position, unsigned int& polygon, unsigned int index) const +{ + if (index >= m_nodes.size() || m_nodes[index].second == 0xFFFF) + return false; + ClusterGraph* const graph = + static_cast(IAIPathfinding::instance->getClusterGraph(m_map, m_island)); + const ClusterPortal* const portal = graph->getClusterPortal( + m_nodes[index].first, static_cast(m_costType), m_nodes[index].second); + position = portal->m_position; + polygon = portal->m_polygon; + return true; +} + +// ELF 0x3220D0. +const Vec3& ClusterNodePath::getPoint(unsigned int index) const +{ + const unsigned int step = m_i0 + index; + if (step >= m_nodes.size() || m_nodes[step].second == 0xFFFF) + return Vec3::getZero(); + ClusterGraph* const graph = + static_cast(IAIPathfinding::instance->getClusterGraph(m_map, m_island)); + return graph + ->getClusterPortal(m_nodes[step].first, static_cast(m_costType), + m_nodes[step].second) + ->m_position; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Material/Material.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Material/Material.cpp index 18e3bf616..0b35ba88c 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Material/Material.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Material/Material.cpp @@ -2,6 +2,10 @@ #include "Material.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x3227D0, __tcf_0 0x322830, _GLOBAL__I 0x322860). +#include + #include "../../../../../Core/Debug.h" #include "../../../../../Core/StringUtil.h" @@ -12,6 +16,7 @@ namespace dice { namespace hfe { namespace ai { +// ELF 0x322220. std::istream& operator>>(std::istream& stream, materialId& material) { std::string token; @@ -37,9 +42,9 @@ std::istream& operator>>(std::istream& stream, materialId& material) material = 9; else { - // Both ports report this exact source line and abort through DebugTypeError. There is no + // The image reports source line 66 and aborts through DebugTypeError. There is no // fallback assignment for an unknown token. - Debug(DebugTypeError, __FILE__, __LINE__, "") + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/Material/Material.cpp", 66, "") << token << " is not recognised as a proper materialId."; } diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Material/MaterialManager.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Material/MaterialManager.cpp index fd9ea642e..3ce216e13 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Material/MaterialManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Material/MaterialManager.cpp @@ -1,16 +1,21 @@ #include "MaterialManager.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x322E90, __tcf_0 0x322EF0, _GLOBAL__I 0x322F20). +#include + #include "../../AIUtils/checkPointer.h" namespace dice { namespace hfe { namespace ai { -// Initializes the navigation material table and its default traversal costs. +// ELF 0x322880 (C2; C1 0x322AF0). Nine materials at cost 1, then Invalid -1 and both danger +// objects 1000. MaterialManager::MaterialManager() { - for (unsigned int i = 0; i <= 8u; ++i) + for (unsigned char i = 0; i < 9; ++i) { MaterialContainer* const container = new MaterialContainer(); checkPointer(container); @@ -22,7 +27,7 @@ MaterialManager::MaterialManager() setMaterialCost(7, 1000.0f); } -// Deletes each owned material-cost record. +// ELF 0x322D60 (D2; D1 0x322DC0). Deletes each owned material-cost record. MaterialManager::~MaterialManager() { for (std::vector::iterator i = m_materials.begin(); @@ -32,16 +37,19 @@ MaterialManager::~MaterialManager() // A material is walkable when its cost compares >= 0; material zero starts at -1. // All accessors require a valid material index. +// ELF 0x322E60. bool MaterialManager::isValidMaterial(unsigned char material) const { return m_materials[material]->m_cost >= 0.0f; } +// ELF 0x322E20. void MaterialManager::setMaterialCost(unsigned char material, float cost) { m_materials[material]->m_cost = cost; } +// ELF 0x322E40. float MaterialManager::getMaterialCost(unsigned char material) const { return m_materials[material]->m_cost; diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.cpp new file mode 100644 index 000000000..8ba17cb1a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.cpp @@ -0,0 +1,1167 @@ +// ELF FILE symbol GTSDataOptimiser.cpp; OptPolygon methods occur in this translation unit. +#include "GTSDataOptimiser.h" +#include "QuadTree.h" +#include "../Cluster/ClusterGraph.h" +#include "../../AIUtils/checkPointer.h" +#include "../../../../../IO/File/File.h" +#include +#include +#include +// ELF static init 0x2FC5A0, __tcf_0 0x2FC600, _GLOBAL__I 0x2FC630: ios_base::Init lifetime. +#include + +namespace dice { namespace hfe { namespace ai { + +namespace { +// Inlined vector operations in the optimiser bodies; the helper names are inferred. +DoubleVec3 difference(const DoubleVec3& a, const DoubleVec3& b) +{ + DoubleVec3 result = { a.x - b.x, a.y - b.y, a.z - b.z }; + return result; +} +double scalarProduct(const DoubleVec3& a, const DoubleVec3& b) +{ + return a.x * b.x + a.y * b.y + a.z * b.z; +} +DoubleVec3 vectorProduct(const DoubleVec3& a, const DoubleVec3& b) +{ + DoubleVec3 result = { a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, + a.x * b.y - a.y * b.x }; + return result; +} +void normaliseDouble(DoubleVec3& vector) +{ + const double lengthSquared = scalarProduct(vector, vector); + if (static_cast(FLT_EPSILON) > std::fabs(1.0 - lengthSquared)) return; + if (!(static_cast(FLT_EPSILON) > std::fabs(lengthSquared))) + { + const double scale = 1.0 / std::sqrt(lengthSquared); + vector.x *= scale; vector.y *= scale; vector.z *= scale; + } + else vector.x = vector.y = vector.z = 0.0; +} +int wrappedIndex(int index, int count) +{ + // shipped defect: a negative multiple produces count rather than zero. + return index < 0 ? count + index % count : index % count; +} +float normalAngle(const DoubleVec3& a, const DoubleVec3& b) +{ + float dot = static_cast(scalarProduct(a, b)); + if (dot < -1.0f) dot = -1.0f; + else if (dot > 1.0f) dot = 1.0f; + return std::acos(dot); +} +} + +// ELF 0x2F2390 (C2), 0x2F2490 (C1). +GTSDataOptimiser::GTSDataOptimiser(ClusterGraph* graph) : m_current(), m_clusterGraph(graph) {} + +// ELF 0x2F24E0 (D2), 0x2F2550 (D1). +GTSDataOptimiser::~GTSDataOptimiser() +{ + for (std::list::iterator i = m_polygons.begin(); i != m_polygons.end(); ++i) + destroyPolygon(*i); +} + +// ELF 0x2F3EB0. +void GTSDataOptimiser::destroyPolygon(OptPolygon* polygon) { delete polygon; } + +// ELF 0x2F62F0. Shipped code dereferences begin without checking for an empty list. +OptPolygon* GTSDataOptimiser::initPolygonIteration() +{ + m_current = m_polygons.begin(); + return *m_current; +} + +// ELF 0x2F6310. +OptPolygon* GTSDataOptimiser::getNextPolygon() +{ + ++m_current; + return m_current == m_polygons.end() ? 0 : *m_current; +} + +// ELF 0x2F6340. +unsigned int GTSDataOptimiser::getNumberOfVertices() const +{ + unsigned int count = 0; + for (std::list::const_iterator i = m_polygons.begin(); i != m_polygons.end(); ++i) + count += (*i)->m_numberOfVertices; + return count; +} + +// ELF 0x2F25C0 (C2), 0x2F25F0 (C1). m_index is left uninitialized. +OptPolygon::OptPolygon() : m_numberOfVertices(0), m_vertices(0), m_neighbours(0), + m_material(0), m_originalMaterial(0), m_normal(0), m_cluster(0) {} + +// ELF 0x2F2620 (D2), 0x2F2650 (D1). +OptPolygon::~OptPolygon() { deleteMembers(); } + +// ELF 0x2F2680. Only the cached normal pointer is nulled after freeing. +void OptPolygon::deleteMembers() +{ + delete m_normal; + m_normal = 0; + delete[] m_vertices; + delete[] m_neighbours; +} + +// ELF 0x2F2F30. +const DoubleVec3* OptPolygon::getNormal() const +{ + if (!m_normal) + calculateNormal(); + return m_normal; +} + +// ELF 0x2F26E0. Calculates and caches a polygon normal from its vertex fan. +void OptPolygon::calculateNormal() const +{ + const DoubleVec3 origin = m_vertices[0]; + const DoubleVec3 firstEdge = difference(m_vertices[1], origin); + DoubleVec3 secondEdge = difference(m_vertices[2], origin); + m_normal = checkPointer(new DoubleVec3(vectorProduct(firstEdge, secondEdge))); + DoubleVec3 firstUnit = firstEdge; + normaliseDouble(firstUnit); + DoubleVec3 secondUnit = secondEdge; + normaliseDouble(secondUnit); + float dot = static_cast(scalarProduct(secondUnit, firstUnit)); + float angle = std::fabs(std::fabs(dot) - 1.0f); + int corner = 2; + while (static_cast(0.01f) > scalarProduct(*m_normal, *m_normal) || 0.01f > angle) + { + if (corner >= m_numberOfVertices - 1) break; + ++corner; + secondEdge = difference(m_vertices[corner], origin); + *m_normal = vectorProduct(firstEdge, secondEdge); + secondUnit = secondEdge; + normaliseDouble(secondUnit); + dot = static_cast(scalarProduct(secondUnit, firstUnit)); + // shipped defect: subsequent fan triangles omit the outer absolute value. + angle = std::fabs(dot) - 1.0f; + } + normaliseDouble(*m_normal); +} + +// ELF 0x2F2F70. +unsigned char OptPolygon::findFirstNeighbourIndex(OptPolygon* neighbour) const +{ + for (int edge = 0; edge < m_numberOfVertices; ++edge) + if (m_neighbours[edge] == neighbour) return static_cast(edge); + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.cpp", 103, "") + << "Couldn't find first neighbour index in " << static_cast(this) + << " of " << static_cast(neighbour); + return 0xFF; +} + +// ELF 0x2F30F0. +void OptPolygon::changeVertex(const DoubleVec3& oldVertex, const DoubleVec3& newVertex) +{ + for (int corner = 0; corner < m_numberOfVertices; ++corner) + { + const DoubleVec3 delta = difference(oldVertex, m_vertices[corner]); + if (!(scalarProduct(delta, delta) > DBL_EPSILON)) + { + delete m_normal; + m_normal = 0; + m_vertices[corner] = newVertex; + return; + } + } +} + +// ELF 0x2F3210. +void OptPolygon::changeNeighbour(const DoubleVec3& vertex, OptPolygon* oldNeighbour, + OptPolygon* newNeighbour) +{ + for (int corner = 0; corner < m_numberOfVertices; ++corner) + { + const DoubleVec3 delta = difference(vertex, m_vertices[corner]); + if (!(scalarProduct(delta, delta) > DBL_EPSILON)) + { + const int previous = corner - 1; + const int edge = previous < 0 ? m_numberOfVertices + previous % m_numberOfVertices + : previous % m_numberOfVertices; + if (m_neighbours[edge] == oldNeighbour) + { + m_neighbours[edge] = newNeighbour; + return; + } + } + } + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.cpp", 138, "") + << "Couldn't change neighbour in " << static_cast(this) + << " from " << static_cast(oldNeighbour) + << " to " << static_cast(newNeighbour); +} + +// ELF 0x2F36E0. Appends the polygon's XZ coordinates and diagnostic pointer to the file. +void OptPolygon::printPolygon(io::File& file, int id) const +{ + file.seek(static_cast(2), 0); + std::stringstream text; + const unsigned int count = m_numberOfVertices; + text << static_cast(count) << " " << id << std::endl; + text << static_cast(this) << std::endl; + for (unsigned int corner = 0; corner < count; ++corner) + text << m_vertices[corner].x << " " << m_vertices[corner].z << std::endl; + file.write(text.str()); +} + +// ELF 0x2F3C40. +bool OptPolygon::checkForDuplicateVertices() const +{ + const unsigned int count = m_numberOfVertices; + for (unsigned int first = 0; first < count; ++first) + for (unsigned int second = first + 1; second < count; ++second) + { + const DoubleVec3 delta = difference(m_vertices[second], m_vertices[first]); + if (DBL_EPSILON > scalarProduct(delta, delta)) return true; + } + return false; +} + +// ELF 0x2F3450. +void GTSDataOptimiser::removeVerticesAndRebuildPolygon(const VertexRemovalMap& removals) +{ + for (VertexRemovalMap::const_iterator i = removals.begin(); i != removals.end(); ++i) + { + OptPolygon* polygon = i->first; + const unsigned char oldCount = polygon->m_numberOfVertices; + const unsigned char count = static_cast(oldCount - i->second.size()); + DoubleVec3* vertices = new DoubleVec3[count](); + OptPolygon** neighbours = new OptPolygon*[count]; + unsigned char output = 0; + for (unsigned char corner = 0; corner < oldCount; ++corner) + { + bool remove = false; + for (std::vector::const_iterator v = i->second.begin(); + v != i->second.end(); ++v) + { + const DoubleVec3 delta = difference(polygon->m_vertices[corner], **v); + if (DBL_EPSILON > scalarProduct(delta, delta)) { remove = true; break; } + } + if (!remove) + { + vertices[output] = polygon->m_vertices[corner]; + neighbours[output++] = polygon->m_neighbours[corner]; + } + } + polygon->deleteMembers(); + polygon->m_numberOfVertices = count; + polygon->m_vertices = vertices; + delete polygon->m_normal; + polygon->m_normal = 0; + polygon->m_neighbours = neighbours; + } +} + +// ELF 0x2F3D60. +OptPolygon* GTSDataOptimiser::createPolygon() const { return checkPointer(new OptPolygon); } + +// ELF 0x2F3EF0. Only the two-to-one pass is enabled in the shipped optimiser. +void GTSDataOptimiser::optimise(const std::vector& parts) +{ + m_clusterGraph->resetTempMemberSizes(); + std::set removed; + while (twoToOneMerge(removed)) {} + delete[] m_clusterGraph->m_tempMemberSizes; + m_clusterGraph->m_tempMemberSizes = 0; + setPolygonIndices(parts); +} + +// ELF 0x2F5340. +void GTSDataOptimiser::setPolygonIndices(const std::vector& parts) +{ + ClusterGraph::ClusterPolygonMap clusters; + const std::set& removed = m_clusterGraph->m_set18; + std::map oldParts; + unsigned int part = 0; + for (std::vector::const_iterator p = parts.begin(); p != parts.end(); ++p, ++part) + for (std::vector::const_iterator i = (*p)->m_polygons.begin(); + i != (*p)->m_polygons.end(); ++i) + oldParts.insert(std::make_pair(*i, part)); + ClusterGraph::DynamicPolygonMap newParts; + unsigned int index = 0; + for (std::list::iterator i = m_polygons.begin(); i != m_polygons.end(); ++i, ++index) + { + OptPolygon* polygon = *i; + if (removed.find(polygon->m_index) == removed.end()) + { + for (unsigned short cluster = 0; cluster < m_clusterGraph->m_numberOfClusters; ++cluster) + if (polygon->m_cluster == cluster) + { + ClusterGraph::ClusterPolygonMap::iterator entry = clusters.find(cluster); + if (entry == clusters.end()) + { + std::list indices; + indices.insert(indices.end(), index); + clusters.insert(std::make_pair(cluster, indices)); + } + else entry->second.insert(entry->second.end(), index); + } + } + else + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.cpp", 623, "") + << "We shouldn't come here!"; + std::map::iterator entry = oldParts.find(polygon->m_index); + if (entry != oldParts.end()) + newParts.insert(std::make_pair(index, + std::make_pair(entry->second, parts[entry->second]->m_initiallyWalkable))); + polygon->m_index = index; + } + m_clusterGraph->updateClustersAfterOptimisation(newParts, m_polygons, clusters); +} + +// ELF 0x2F5D20. Dropping a previous list does not destroy its polygons, as shipped. +void GTSDataOptimiser::buildOptMeshFromTriangles(DoublePolygon* triangles, DoubleVec3* vertices, + unsigned int* vertexIndices, unsigned int* neighbourIndices, unsigned int count, QuadTree* tree) +{ + m_polygons.resize(0, static_cast(0)); + std::vector polygons; + std::set dynamic; + for (std::vector::const_iterator p = tree->m_destroyableMapParts.begin(); + p != tree->m_destroyableMapParts.end(); ++p) + { + const std::vector indices = (*p)->m_polygons; + for (std::vector::const_iterator i = indices.begin(); i != indices.end(); ++i) + dynamic.insert(*i); + } + for (unsigned int i = 0; i < count; ++i) + { + OptPolygon* polygon = createPolygon(); + polygon->m_numberOfVertices = triangles[i].m_numberOfVertices; + polygon->m_vertices = new DoubleVec3[polygon->m_numberOfVertices](); + delete polygon->m_normal; + polygon->m_normal = 0; + polygon->m_neighbours = new OptPolygon*[polygon->m_numberOfVertices]; + polygon->m_originalMaterial = triangles[i].m_material; + polygon->m_material = dynamic.find(i) == dynamic.end() ? triangles[i].m_material : 8; + if (polygon->m_normal) *polygon->m_normal = triangles[i].m_normal; + else polygon->m_normal = new DoubleVec3(triangles[i].m_normal); + polygon->m_index = i; + polygon->m_cluster = triangles[i].m_cluster; + for (unsigned int corner = 0; corner < triangles[i].m_numberOfVertices; ++corner) + { + polygon->m_vertices[corner] = vertices[vertexIndices[triangles[i].m_firstIndex + corner]]; + delete polygon->m_normal; + polygon->m_normal = 0; + } + m_polygons.insert(m_polygons.end(), polygon); + polygons.push_back(polygon); + } + unsigned int i = 0; + for (std::list::iterator p = m_polygons.begin(); p != m_polygons.end(); ++p, ++i) + for (unsigned int corner = 0; corner < triangles[i].m_numberOfVertices; ++corner) + { + const unsigned int neighbour = neighbourIndices[triangles[i].m_firstIndex + corner]; + (*p)->m_neighbours[corner] = neighbour == ~0u ? 0 : polygons[neighbour]; + } +} + +// ELF 0x2FB170. The two counters are diagnostic inputs unused by the shipped body. +void GTSDataOptimiser::cleanPolygon(OptPolygon* polygon, unsigned int, unsigned int) +{ + std::list vertices; + std::list neighbours; + VertexRemovalMap removals; + const unsigned char count = polygon->m_numberOfVertices; + unsigned char next = 1; + unsigned char previous = static_cast(count - 1); + for (unsigned char corner = 0; corner < count; ++corner) + { + OptPolygon* neighbour = polygon->m_neighbours[corner]; + bool remove = false; + if (neighbour == polygon->m_neighbours[previous] && + (!neighbour || neighbour->m_numberOfVertices > 3)) + { + DoubleVec3 forward = difference(polygon->m_vertices[next], polygon->m_vertices[corner]); + normaliseDouble(forward); + DoubleVec3 backward = difference(polygon->m_vertices[previous], polygon->m_vertices[corner]); + normaliseDouble(backward); + remove = static_cast(0.01f) > scalarProduct(backward, forward) + 1.0; + } + if (remove) + { + if (neighbour) + { + VertexRemovalMap::iterator entry = removals.find(neighbour); + if (entry == removals.end()) + { + std::vector indices; + indices.push_back(&polygon->m_vertices[corner]); + removals.insert(std::make_pair(neighbour, indices)); + } + else entry->second.push_back(&polygon->m_vertices[corner]); + } + // shipped defect: previous advances only when a vertex is retained. + } + else + { + vertices.insert(vertices.end(), polygon->m_vertices[corner]); + neighbours.insert(neighbours.end(), polygon->m_neighbours[corner]); + previous = static_cast(previous + 1) % count; + } + next = static_cast(next + 1) % count; + } + removeVerticesAndRebuildPolygon(removals); + polygon->deleteMembers(); + polygon->m_numberOfVertices = static_cast(vertices.size()); + polygon->m_neighbours = new OptPolygon*[polygon->m_numberOfVertices]; + polygon->m_vertices = new DoubleVec3[polygon->m_numberOfVertices](); + delete polygon->m_normal; + polygon->m_normal = 0; + unsigned int corner = 0; + std::list::const_iterator n = neighbours.begin(); + for (std::list::const_iterator v = vertices.begin(); v != vertices.end(); ++v, ++n, ++corner) + { + polygon->m_vertices[corner] = *v; + delete polygon->m_normal; + polygon->m_normal = 0; + polygon->m_neighbours[corner] = *n; + } +} + +// ELF 0x2F6380. +bool GTSDataOptimiser::twoToOneMerge(std::set& removed) +{ + std::set created; + static unsigned int callTimes = 0; + ++callTimes; + bool merged = false; + unsigned int ordinal = 0; + for (std::list::iterator p = m_polygons.begin(); p != m_polygons.end(); ++p) + { + ++ordinal; + OptPolygon* polygon = *p; + OptPolygon* output = 0; + if (removed.find(polygon) != removed.end()) continue; + const int count = polygon->m_numberOfVertices; + for (int edge = 0; edge < count; ++edge) + { + OptPolygon* neighbour = polygon->m_neighbours[edge]; + if (!neighbour || neighbour->m_material != polygon->m_material || + neighbour->m_material == 8 || polygon->m_material == 8) continue; + const DoubleVec3* neighbourNormal = neighbour->getNormal(); + const DoubleVec3* polygonNormal = polygon->getNormal(); + if (normalAngle(*polygonNormal, *neighbourNormal) > 0.08726646f) continue; + if (polygon->m_neighbours[wrappedIndex(edge - 1, count)] == neighbour) continue; + if (created.find(neighbour) != created.end()) continue; + if (removed.find(neighbour) != removed.end()) + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.cpp", 955, "") + << "Neighbour " << static_cast(neighbour) << " has previously been removed!"; + const int otherCount = neighbour->m_numberOfVertices; + DoubleVec2 backward = {}; + getVectorToXZDouble(polygon->m_vertices[edge], + polygon->m_vertices[wrappedIndex(edge - 1, count)], backward); + int firstOther = otherCount - 1; + for (; firstOther >= 0; --firstOther) + if (neighbour->m_neighbours[firstOther] != polygon && + neighbour->m_neighbours[wrappedIndex(firstOther - 1, otherCount)] == polygon) + break; + DoubleVec2 normal = {}; + DoubleVec3 vertex = neighbour->m_vertices[firstOther]; + getVectorToXZDouble(vertex, neighbour->m_vertices[wrappedIndex(firstOther + 1, otherCount)], normal); + getNormalDouble(normal, normal); + if (normal.x * backward.x + normal.y * backward.y < 0.0) continue; + DoubleVec2 forward = {}; + int last = edge; + int lastOther = firstOther; + do + { + last = wrappedIndex(last + 1, count); + lastOther = wrappedIndex(lastOther - 1, otherCount); + } while (polygon->m_neighbours[last] == neighbour); + getVectorToXZDouble(polygon->m_vertices[last], + polygon->m_vertices[wrappedIndex(last + 1, count)], forward); + normal = DoubleVec2{}; + vertex = neighbour->m_vertices[lastOther]; + getVectorToXZDouble(neighbour->m_vertices[wrappedIndex(lastOther - 1, otherCount)], vertex, normal); + getNormalDouble(normal, normal); + if (normal.x * forward.x + normal.y * forward.y < 0.0) continue; + + OptPolygon* retained = neighbour; + OptPolygon* discarded = polygon; + unsigned short retainedCluster = neighbour->m_cluster; + unsigned short discardedCluster = polygon->m_cluster; + unsigned int remaining = m_clusterGraph->m_tempMemberSizes[discardedCluster]; + const unsigned int otherSize = m_clusterGraph->m_tempMemberSizes[retainedCluster]; + if (remaining <= otherSize) + { + retained = polygon; + discarded = neighbour; + retainedCluster = polygon->m_cluster; + discardedCluster = neighbour->m_cluster; + remaining = otherSize; + } + --remaining; + if (retainedCluster != discardedCluster && remaining > 1) + { + std::set visited; + if (!m_clusterGraph->validateClusterConnectivityFromPolygon(discardedCluster, discarded, + remaining, visited, false)) + { + visited.clear(); + continue; + } + } + output = createPolygon(); + output->m_index = retained->m_index; + output->m_cluster = retainedCluster; + m_clusterGraph->m_set18.insert(discarded->m_index); + m_clusterGraph->m_tempMemberSizes[discardedCluster] = remaining; + std::list vertices; + std::list neighbours; + for (int corner = firstOther; corner != lastOther; corner = wrappedIndex(corner + 1, otherCount)) + { + vertices.insert(vertices.end(), &neighbour->m_vertices[corner]); + OptPolygon* next = neighbour->m_neighbours[corner]; + if (next) + { + next->changeNeighbour(neighbour->m_vertices[corner], neighbour, output); + neighbour->changeNeighbour(neighbour->m_vertices[(corner + 1) % neighbour->m_numberOfVertices], next, 0); + } + neighbours.insert(neighbours.end(), next); + } + for (int corner = 0; corner < neighbour->m_numberOfVertices; ++corner) + if (neighbour->m_neighbours[corner]) + neighbour->m_neighbours[corner]->changeNeighbour(neighbour->m_vertices[corner], neighbour, 0); + for (int corner = last; corner != edge; corner = wrappedIndex(corner + 1, count)) + { + vertices.insert(vertices.end(), &polygon->m_vertices[corner]); + OptPolygon* next = polygon->m_neighbours[corner]; + if (next) + { + next->changeNeighbour(polygon->m_vertices[corner], polygon, output); + polygon->changeNeighbour(polygon->m_vertices[(corner + 1) % polygon->m_numberOfVertices], next, 0); + } + neighbours.insert(neighbours.end(), next); + } + for (int corner = 0; corner < polygon->m_numberOfVertices; ++corner) + if (polygon->m_neighbours[corner]) + polygon->m_neighbours[corner]->changeNeighbour(polygon->m_vertices[corner], polygon, 0); + output->m_numberOfVertices = static_cast(vertices.size()); + output->m_neighbours = new OptPolygon*[output->m_numberOfVertices]; + output->m_vertices = new DoubleVec3[output->m_numberOfVertices](); + delete output->m_normal; + output->m_normal = 0; + int corner = 0; + std::list::const_iterator n = neighbours.begin(); + for (std::list::const_iterator v = vertices.begin(); v != vertices.end(); ++v, ++n, ++corner) + { + output->m_vertices[corner] = **v; + delete output->m_normal; + output->m_normal = 0; + output->m_neighbours[corner] = *n; + } + output->m_material = polygon->m_material; + output->m_originalMaterial = polygon->m_originalMaterial; + cleanPolygon(output, ordinal, callTimes); + removed.insert(neighbour); + removed.insert(polygon); + created.insert(output); + merged = true; + break; + } + } + for (std::list::iterator p = m_polygons.begin(); p != m_polygons.end();) + { + if (removed.find(*p) == removed.end()) { ++p; continue; } + OptPolygon* polygon = *p; + m_polygons.erase(p++); + destroyPolygon(polygon); + } + removed.clear(); + for (std::set::const_iterator p = created.begin(); p != created.end(); ++p) + m_polygons.insert(m_polygons.end(), *p); + return merged; +} + +// ELF 0x2F4000. Retail dead code: every polygon is treated as a triangle without checking its size. +void GTSDataOptimiser::removeTooThinTriangles() +{ + std::set removed; + const double minimumSquared = 0.0025000000000000005; + for (std::list::iterator p = m_polygons.begin(); p != m_polygons.end(); ++p) + { + OptPolygon* polygon = *p; + if (removed.find(polygon) != removed.end()) continue; + double shortest = DBL_MAX; + bool shortEdge = false; + unsigned char edge = 0; + OptPolygon* neighbour = 0; + for (unsigned char i = 0; i <= 2; ++i) + { + const DoubleVec3 delta = difference(polygon->m_vertices[i], polygon->m_vertices[(i + 1) % 3]); + const double lengthSquared = scalarProduct(delta, delta); + if (minimumSquared > lengthSquared && shortest > lengthSquared) + { + shortEdge = true; + neighbour = polygon->m_neighbours[i]; + edge = i; + shortest = lengthSquared; + } + } + if (shortEdge) + { + for (unsigned char i = 0; i <= 2; ++i) + { + if (i == edge) + { + const unsigned char first = (edge + 1) % 3; + const unsigned char second = (edge + 2) % 3; + OptPolygon* a = polygon->m_neighbours[first]; + OptPolygon* b = polygon->m_neighbours[second]; + if (a) a->changeNeighbour(polygon->m_vertices[first], polygon, b); + if (b) b->changeNeighbour(polygon->m_vertices[second], polygon, a); + } + if (neighbour && neighbour->m_neighbours[i] == polygon) + { + const unsigned char first = (i + 1) % 3; + const unsigned char second = (i + 2) % 3; + OptPolygon* a = neighbour->m_neighbours[first]; + OptPolygon* b = neighbour->m_neighbours[second]; + if (a) a->changeNeighbour(neighbour->m_vertices[first], neighbour, b); + if (b) b->changeNeighbour(neighbour->m_vertices[second], neighbour, a); + } + } + const DoubleVec3 oldVertex = polygon->m_vertices[edge]; + const DoubleVec3 newVertex = polygon->m_vertices[(edge + 1) % 3]; + for (std::list::iterator i = m_polygons.begin(); i != m_polygons.end(); ++i) + if (removed.find(*i) == removed.end()) (*i)->changeVertex(oldVertex, newVertex); + removed.insert(polygon); + if (neighbour) removed.insert(neighbour); + } + else + { + unsigned char longestEdge = 0; + double longest = 0.0; + for (unsigned char i = 0; i <= 2; ++i) + { + const DoubleVec3 delta = difference(polygon->m_vertices[(i + 1) % 3], polygon->m_vertices[i % 3]); + const double lengthSquared = scalarProduct(delta, delta); + if (lengthSquared > longest) { longest = lengthSquared; longestEdge = i; } + } + const unsigned char end = (longestEdge + 1) % 3; + const unsigned char opposite = (longestEdge + 2) % 3; + const DoubleVec3* a = &polygon->m_vertices[longestEdge]; + const DoubleVec3* b = &polygon->m_vertices[end]; + DoubleVec3 direction = difference(*b, *a); + normaliseDouble(direction); + const DoubleVec3 toOpposite = difference(polygon->m_vertices[opposite], *a); + const double projection = scalarProduct(direction, toOpposite); + if (!(minimumSquared > scalarProduct(toOpposite, toOpposite) - projection * projection)) continue; + OptPolygon* before = polygon->m_neighbours[opposite]; + OptPolygon* across = polygon->m_neighbours[longestEdge]; + OptPolygon* after = polygon->m_neighbours[end]; + OptPolygon* split[2] = {}; + const DoubleVec3 midpoint = { (b->x + a->x) * 0.5, (b->y + a->y) * 0.5, (b->z + a->z) * 0.5 }; + if (across) + { + split[0] = createPolygon(); + split[1] = createPolygon(); + for (unsigned char half = 0; half <= 1; ++half) + { + OptPolygon* output = split[half]; + output->m_numberOfVertices = 3; + output->m_vertices = new DoubleVec3[output->m_numberOfVertices](); + delete output->m_normal; + output->m_normal = 0; + output->m_neighbours = new OptPolygon*[output->m_numberOfVertices]; + // shipped defect: material stays at its constructor value of zero. + output->m_originalMaterial = across->m_material; + const DoubleVec3* normal = across->getNormal(); + if (output->m_normal) *output->m_normal = *normal; + else output->m_normal = new DoubleVec3(*normal); + output->m_index = static_cast(m_polygons.size()); + output->m_cluster = across->m_cluster; + for (unsigned char i = 0; i <= 2; ++i) + { + const DoubleVec3 delta = difference(across->m_vertices[i], half == 0 ? *b : *a); + output->m_vertices[i] = DBL_EPSILON > scalarProduct(delta, delta) ? midpoint : across->m_vertices[i]; + delete output->m_normal; + output->m_normal = 0; + } + for (unsigned char i = 0; i <= 2; ++i) + { + const DoubleVec3 current = difference(output->m_vertices[i], midpoint); + const DoubleVec3 next = difference(output->m_vertices[(i + 1) % 3], midpoint); + if (half == 0) + { + if (DBL_EPSILON > scalarProduct(next, next)) output->m_neighbours[i] = split[1]; + else if (DBL_EPSILON > scalarProduct(current, current)) output->m_neighbours[i] = before; + else + { + output->m_neighbours[i] = across->m_neighbours[i]; + if (output->m_neighbours[i]) + output->m_neighbours[i]->changeNeighbour(across->m_vertices[i], across, output); + } + } + else + { + if (DBL_EPSILON > scalarProduct(current, current)) output->m_neighbours[i] = split[0]; + else if (DBL_EPSILON > scalarProduct(next, next)) output->m_neighbours[i] = after; + else + { + output->m_neighbours[i] = across->m_neighbours[i]; + if (output->m_neighbours[i]) + output->m_neighbours[i]->changeNeighbour(across->m_vertices[i], across, output); + } + } + } + m_polygons.insert(m_polygons.end(), split[half]); + } + ++m_clusterGraph->m_tempMemberSizes[across->m_cluster]; + removed.insert(across); + } + if (before) before->changeNeighbour(polygon->m_vertices[opposite], polygon, split[0]); + if (after) after->changeNeighbour(polygon->m_vertices[end], polygon, split[1]); + const DoubleVec3 oldVertex = polygon->m_vertices[opposite]; + for (std::list::iterator i = m_polygons.begin(); i != m_polygons.end(); ++i) + if (removed.find(*i) == removed.end()) (*i)->changeVertex(oldVertex, midpoint); + removed.insert(polygon); + } + } + for (std::list::iterator i = m_polygons.begin(); i != m_polygons.end();) + { + if (removed.find(*i) == removed.end()) { ++i; continue; } + OptPolygon* polygon = *i; + m_clusterGraph->m_set18.insert(polygon->m_index); + --m_clusterGraph->m_tempMemberSizes[polygon->m_cluster]; + m_polygons.erase(i++); + destroyPolygon(polygon); + } +} + +// ELF 0x2F7650. Retail dead code; cluster membership and original material are not repaired here. +bool GTSDataOptimiser::threeToTwoMerge() +{ + // Names of these inlined list/array operations are inferred. + const auto append = [](OptPolygon* source, int corner, OptPolygon* output, + std::list& vertices, std::list& neighbours) + { + vertices.insert(vertices.end(), source->m_vertices[corner]); + OptPolygon* neighbour = source->m_neighbours[corner]; + if (neighbour) neighbour->changeNeighbour(source->m_vertices[corner], source, output); + neighbours.insert(neighbours.end(), neighbour); + }; + const auto range = [&append](OptPolygon* source, int start, int end, OptPolygon* output, + std::list& vertices, std::list& neighbours) + { + for (int i = start; i != end; i = wrappedIndex(i + 1, source->m_numberOfVertices)) + append(source, i, output, vertices, neighbours); + }; + const auto install = [](OptPolygon* output, const std::list& vertices, + const std::list& neighbours, unsigned char material) + { + const int count = static_cast(vertices.size()); + DoubleVec3* v = new DoubleVec3[count](); + OptPolygon** n = new OptPolygon*[count]; + std::list::const_iterator vi = vertices.begin(); + std::list::const_iterator ni = neighbours.begin(); + for (int i = 0; i < count; ++i, ++vi, ++ni) { v[i] = *vi; n[i] = *ni; } + output->m_numberOfVertices = static_cast(count); + output->m_vertices = v; + delete output->m_normal; + output->m_normal = 0; + output->m_neighbours = n; + output->m_material = material; + }; + const auto splitExternal = [](OptPolygon* polygon, OptPolygon* target, OptPolygon* first, + OptPolygon* second, const DoubleVec3& intersection, bool wrap) + { + const int count = polygon->m_numberOfVertices; + DoubleVec3* vertices = new DoubleVec3[count + 1](); + OptPolygon** neighbours = new OptPolygon*[count + 1]; + int corner = 0; + if (wrap && polygon->m_neighbours[count - 1] == target && polygon->m_neighbours[0] == target) + { + for (; corner < count - 1; ++corner) + { + vertices[corner] = polygon->m_vertices[corner]; + neighbours[corner] = polygon->m_neighbours[corner]; + } + } + else + { + for (; polygon->m_neighbours[corner] != target; ++corner) + { + vertices[corner] = polygon->m_vertices[corner]; + neighbours[corner] = polygon->m_neighbours[corner]; + } + } + vertices[corner] = polygon->m_vertices[corner]; + neighbours[corner] = first; + ++corner; + vertices[corner] = intersection; + neighbours[corner] = second; + for (; corner < count; ++corner) + { + vertices[corner + 1] = polygon->m_vertices[corner]; + neighbours[corner + 1] = polygon->m_neighbours[corner]; + } + polygon->deleteMembers(); + if (wrap) + { + polygon->m_vertices = vertices; + polygon->m_numberOfVertices = static_cast(count + 1); + } + else + { + polygon->m_numberOfVertices = static_cast(count + 1); + polygon->m_vertices = vertices; + } + delete polygon->m_normal; + polygon->m_normal = 0; + polygon->m_neighbours = neighbours; + }; + const auto replaceAll = [](OptPolygon* polygon, OptPolygon* old, OptPolygon* replacement) + { + if (polygon) + for (int i = 0; i < polygon->m_numberOfVertices; ++i) + if (polygon->m_neighbours[i] == old) polygon->m_neighbours[i] = replacement; + }; + const auto eraseInputs = [this](OptPolygon* a, OptPolygon* b, OptPolygon* c, bool stopAtThree) + { + int count = 0; + for (std::list::iterator i = m_polygons.begin(); + i != m_polygons.end() && (!stopAtThree || count < 3);) + { + if (*i == a || *i == b || *i == c) + { + ++count; + destroyPolygon(*i); + m_polygons.erase(i++); + } + else ++i; + } + }; + const auto sign = [](double value) { return value > 0.0 ? 1.0 : value < 0.0 ? -1.0 : 0.0; }; + for (std::list::iterator p = m_polygons.begin(); p != m_polygons.end(); ++p) + { + OptPolygon* polygon = *p; + const unsigned char material = polygon->m_material; + const int count = polygon->m_numberOfVertices; + if (count <= 3) continue; + for (int edge = 0; edge < count; ++edge) + { + OptPolygon* neighbour = polygon->m_neighbours[edge]; + if (!neighbour) continue; + OptPolygon* third = polygon->m_neighbours[wrappedIndex(edge + 1, count)]; + if (neighbour == third) continue; + OptPolygon* previous = polygon->m_neighbours[wrappedIndex(edge - 1, count)]; + if (neighbour == previous || neighbour->m_numberOfVertices <= 3) continue; + const int otherCount = neighbour->m_numberOfVertices; + int otherEdge = 0; + for (; otherEdge < otherCount; ++otherEdge) + if (neighbour->m_neighbours[otherEdge] == polygon) break; + if (!third || neighbour->m_neighbours[wrappedIndex(otherEdge - 1, otherCount)] != third) + { + third = previous; + if (!third || neighbour->m_neighbours[wrappedIndex(otherEdge + 1, otherCount)] != third) continue; + } + if (neighbour->m_material != polygon->m_material || third->m_material != polygon->m_material) continue; + const DoubleVec3* normal = polygon->getNormal(); + const DoubleVec3* otherNormal = neighbour->getNormal(); + const DoubleVec3* thirdNormal = third->getNormal(); + if (normalAngle(*otherNormal, *normal) > 0.08726646f) continue; + // shipped defect: the second angle compares the neighbour's normal with itself. + if (normalAngle(*otherNormal, *otherNormal) > 0.08726646f) continue; + if (normalAngle(*otherNormal, *thirdNormal) > 0.08726646f) continue; + const int thirdCount = third->m_numberOfVertices; + int thirdEdge = 0; + bool swap = false; + for (; thirdEdge < thirdCount; ++thirdEdge) + { + if (third->m_neighbours[thirdEdge] == polygon) + { + if (thirdEdge <= 0 && third->m_neighbours[thirdCount - 1] == neighbour) + { thirdEdge = thirdCount - 1; swap = true; } + break; + } + if (third->m_neighbours[thirdEdge] == neighbour) + { + swap = true; + if (thirdEdge <= 0 && third->m_neighbours[thirdCount - 1] == polygon) + { thirdEdge = thirdCount - 1; swap = false; } + break; + } + } + OptPolygon* a = swap ? neighbour : polygon; + OptPolygon* b = swap ? polygon : neighbour; + const int ac = swap ? otherCount : count; + const int bc = swap ? count : otherCount; + const int ai = wrappedIndex((swap ? otherEdge : edge) + 1, ac); + const int bi = swap ? edge : otherEdge; + const int aBegin = wrappedIndex(ai + 1, ac); + const int aEnd = wrappedIndex(ai - 1, ac); + const int bBegin = wrappedIndex(bi + 1, bc); + const int bEnd = wrappedIndex(bi - 1, bc); + const int cBegin = wrappedIndex(thirdEdge + 2, thirdCount); + DoubleVec2 vector = {}, perpendicular = {}; + getVectorToXZDouble(a->m_vertices[aBegin], a->m_vertices[wrappedIndex(ai + 2, ac)], vector); + getVectorToXZDouble(third->m_vertices[wrappedIndex(thirdEdge - 1, thirdCount)], + third->m_vertices[thirdEdge], perpendicular); + getNormalDouble(perpendicular, perpendicular); + if (perpendicular.x * vector.x + perpendicular.y * vector.y > 0.0) continue; + vector = DoubleVec2{}; + getVectorToXZDouble(b->m_vertices[wrappedIndex(bi - 2, bc)], b->m_vertices[bEnd], vector); + perpendicular = DoubleVec2{}; + getVectorToXZDouble(third->m_vertices[cBegin], + third->m_vertices[wrappedIndex(thirdEdge + 3, thirdCount)], perpendicular); + getNormalDouble(perpendicular, perpendicular); + if (perpendicular.x * vector.x + perpendicular.y * vector.y < 0.0) continue; + vector = DoubleVec2{}; + getVectorToXZDouble(b->m_vertices[bBegin], b->m_vertices[wrappedIndex(bi + 2, bc)], vector); + perpendicular = DoubleVec2{}; + getVectorToXZDouble(a->m_vertices[aEnd], a->m_vertices[wrappedIndex(ai - 2, ac)], perpendicular); + getNormalDouble(perpendicular, perpendicular); + if (perpendicular.x * vector.x + perpendicular.y * vector.y <= 0.0) + { + OptPolygon* output = createPolygon(); + std::list vertices; + std::list neighbours; + range(a, aBegin, aEnd, output, vertices, neighbours); + range(b, bBegin, bEnd, output, vertices, neighbours); + range(third, cBegin, thirdEdge, output, vertices, neighbours); + eraseInputs(a, b, third, false); + install(output, vertices, neighbours, material); + m_polygons.insert(m_polygons.end(), output); + return true; + } + DoubleVec3 intersection = {}; + const DoubleVec3* lineEnd = &a->m_vertices[aEnd]; + const DoubleVec3* lineStart = &a->m_vertices[wrappedIndex(ai - 2, ac)]; + perpendicular = DoubleVec2{}; + getVectorToXZDouble(*lineStart, *lineEnd, perpendicular); + getNormalDouble(perpendicular, perpendicular); + vector = DoubleVec2{}; + getVectorToXZDouble(a->m_vertices[ai], *lineEnd, vector); + if (perpendicular.x * vector.x + perpendicular.y * vector.y != 0.0) + for (int cut = wrappedIndex(bi + 2, bc); cut != bEnd; cut = wrappedIndex(cut + 1, bc)) + { + const int next = wrappedIndex(cut + 1, bc); + DoubleVec2 currentSide = {}, nextSide = {}; + getVectorToXZDouble(*lineEnd, b->m_vertices[cut], currentSide); + const double firstSide = currentSide.x * perpendicular.x + currentSide.y * perpendicular.y; + getVectorToXZDouble(*lineEnd, b->m_vertices[next], nextSide); + const double secondSide = nextSide.x * perpendicular.x + nextSide.y * perpendicular.y; + if (sign(firstSide) == sign(secondSide) || secondSide == 0.0) continue; + lineIntersect(b->m_vertices[cut], b->m_vertices[next], *lineStart, *lineEnd, intersection); + const DoubleVec3 delta = difference(b->m_vertices[cut], intersection); + const bool split = !(static_cast(0.1f) > scalarProduct(delta, delta)); + if (!split) intersection = b->m_vertices[cut]; + OptPolygon* first = createPolygon(); + OptPolygon* second = createPolygon(); + { + std::list vertices; + std::list neighbours; + range(a, aBegin, aEnd, first, vertices, neighbours); + vertices.insert(vertices.end(), a->m_vertices[aEnd]); + neighbours.insert(neighbours.end(), second); + if (split) + { + vertices.insert(vertices.end(), intersection); + neighbours.insert(neighbours.end(), b->m_neighbours[cut]); + } + else append(b, cut, first, vertices, neighbours); + range(b, next, bEnd, first, vertices, neighbours); + range(third, cBegin, thirdEdge, first, vertices, neighbours); + install(first, vertices, neighbours, material); + } + { + std::list vertices; + std::list neighbours; + range(b, bBegin, cut, second, vertices, neighbours); + if (split) + { + append(b, cut, second, vertices, neighbours); + vertices.insert(vertices.end(), intersection); + neighbours.insert(neighbours.end(), first); + } + else + { + vertices.insert(vertices.end(), b->m_vertices[cut]); + neighbours.insert(neighbours.end(), first); + } + install(second, vertices, neighbours, material); + } + if (split && b->m_neighbours[cut]) + splitExternal(b->m_neighbours[cut], second, first, second, intersection, false); + eraseInputs(a, b, third, false); + m_polygons.insert(m_polygons.end(), first); + m_polygons.insert(m_polygons.end(), second); + return true; + } + lineEnd = &b->m_vertices[bBegin]; + lineStart = &b->m_vertices[wrappedIndex(bi + 2, bc)]; + perpendicular = DoubleVec2{}; + getVectorToXZDouble(*lineStart, *lineEnd, perpendicular); + getNormalDouble(perpendicular, perpendicular); + vector = DoubleVec2{}; + getVectorToXZDouble(b->m_vertices[bi], *lineEnd, vector); + if (perpendicular.x * vector.x + perpendicular.y * vector.y == 0.0) continue; + for (int cut = aBegin; cut != wrappedIndex(ai - 2, ac); cut = wrappedIndex(cut + 1, ac)) + { + const int next = wrappedIndex(cut + 1, ac); + DoubleVec2 currentSide = {}, nextSide = {}; + getVectorToXZDouble(*lineEnd, a->m_vertices[cut], currentSide); + const double firstSide = currentSide.x * perpendicular.x + currentSide.y * perpendicular.y; + getVectorToXZDouble(*lineEnd, a->m_vertices[next], nextSide); + const double secondSide = nextSide.x * perpendicular.x + nextSide.y * perpendicular.y; + if (sign(firstSide) == sign(secondSide) || secondSide == 0.0) continue; + lineIntersect(a->m_vertices[cut], a->m_vertices[next], *lineStart, *lineEnd, intersection); + const DoubleVec3 delta = difference(a->m_vertices[cut], intersection); + const bool split = !(static_cast(0.1f) > scalarProduct(delta, delta)); + if (!split) intersection = a->m_vertices[cut]; + OptPolygon* first = createPolygon(); + OptPolygon* second = createPolygon(); + { + std::list vertices; + std::list neighbours; + range(a, aBegin, next, first, vertices, neighbours); + if (split) + { + vertices.insert(vertices.end(), intersection); + neighbours.insert(neighbours.end(), second); + } + else + { + replaceAll(a->m_neighbours[wrappedIndex(next - 1, ac)], a, first); + neighbours.back() = second; + } + range(b, bBegin, bEnd, first, vertices, neighbours); + range(third, cBegin, wrappedIndex(thirdEdge, thirdCount), first, vertices, neighbours); + install(first, vertices, neighbours, material); + } + { + std::list vertices; + std::list neighbours; + range(a, next, aEnd, second, vertices, neighbours); + vertices.insert(vertices.end(), a->m_vertices[aEnd]); + neighbours.insert(neighbours.end(), first); + OptPolygon* neighbour = a->m_neighbours[cut]; + if (split) + { + vertices.insert(vertices.end(), intersection); + replaceAll(neighbour, a, second); + } + else + { + vertices.insert(vertices.end(), a->m_vertices[cut]); + if (neighbour) neighbour->changeNeighbour(a->m_vertices[cut], a, second); + } + neighbours.insert(neighbours.end(), neighbour); + install(second, vertices, neighbours, material); + } + if (split && a->m_neighbours[cut]) + splitExternal(a->m_neighbours[cut], first, second, first, intersection, true); + eraseInputs(a, b, third, true); + m_polygons.insert(m_polygons.end(), first); + m_polygons.insert(m_polygons.end(), second); + return true; + } + } + } + return false; +} + +// ELF 0x2FBBA0. +DoubleVec2& GTSDataOptimiser::getVectorToXZDouble(const DoubleVec3& from, const DoubleVec3& to, + DoubleVec2& result) +{ + result.x = to.x - from.x; + result.y = to.z - from.z; + return result; +} + +// ELF 0x2FBBC0. Preserve the read before either write for aliased input/output. +DoubleVec2& GTSDataOptimiser::getNormalDouble(const DoubleVec2& vector, DoubleVec2& result) +{ + const double negativeX = -vector.x; + result.x = vector.y; + result.y = negativeX; + return result; +} + +// ELF 0x2FBBE0. +bool GTSDataOptimiser::lineIntersect(const DoubleVec3& a, const DoubleVec3& b, + const DoubleVec3& c, const DoubleVec3& d, DoubleVec3& result) +{ + const DoubleVec3 first = difference(b, a); + DoubleVec3 firstUnit = first; + normaliseDouble(firstUnit); + const DoubleVec3 second = difference(d, c); + DoubleVec3 secondUnit = second; + normaliseDouble(secondUnit); + if (static_cast(0.001f) > std::fabs(std::fabs(scalarProduct(firstUnit, secondUnit)) - 1.0)) + return false; + const DoubleVec3 origin = a; + const DoubleVec3 separation = difference(c, a); + const DoubleVec3 cross = vectorProduct(first, second); + const DoubleVec3 numerator = vectorProduct(separation, second); + const double denominator = scalarProduct(cross, cross); + if (denominator != 0.0) + { + const double scale = scalarProduct(cross, numerator) / denominator; + const DoubleVec3 displacement = { first.x * scale, first.y * scale, first.z * scale }; + result = displacement; + // shipped defect: output aliasing a adds the displacement to itself. + result.x = displacement.x + a.x; + result.y = displacement.y + a.y; + result.z = displacement.z + a.z; + return true; + } + if (scalarProduct(numerator, numerator) == 0.0) { result = origin; return true; } + return false; +} + +// ELF 0x2FC080. Tests whether first occurs in second's neighbour array. +bool GTSDataOptimiser::isNeighbourOfPolygon(OptPolygon* first, OptPolygon* second) const +{ + const unsigned char count = second->m_numberOfVertices; + for (unsigned char edge = 0; edge < count; ++edge) + if (second->m_neighbours[edge] == first) return true; + return false; +} + +// ELF 0x2FC0C0. +void GTSDataOptimiser::validateNeighbours(OptPolygon* polygon) const +{ + unsigned char count = polygon->m_numberOfVertices; + for (unsigned int edge = 0; edge < count; ++edge) + { + OptPolygon* neighbour = polygon->m_neighbours[edge]; + if (!neighbour) continue; + bool found = false; + const DoubleVec3& vertex = polygon->m_vertices[edge]; + for (unsigned int corner = 0; corner < neighbour->m_numberOfVertices; ++corner) + { + const DoubleVec3 delta = difference(vertex, neighbour->m_vertices[corner]); + if (DBL_EPSILON > scalarProduct(delta, delta)) { found = true; break; } + } + if (!found) + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.cpp", 2429, "") + << "Couldn't find common neighbour vertex for polygon " << static_cast(polygon); + count = polygon->m_numberOfVertices; + } + } +} + +// ELF 0x2FC320. +void GTSDataOptimiser::validateNeighbourRelations(const std::set& removed) +{ + for (OptPolygon* polygon = initPolygonIteration(); polygon; polygon = getNextPolygon()) + { + if (removed.find(polygon) != removed.end()) continue; + validateNeighbours(polygon); + const unsigned char count = polygon->m_numberOfVertices; + for (unsigned char edge = 0; edge < count; ++edge) + if (removed.find(polygon->m_neighbours[edge]) != removed.end()) + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.cpp", 2455, "") + << "Reference to removed polygon!"; + } +} + +} } } diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.h b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.h new file mode 100644 index 000000000..8b357e509 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.h @@ -0,0 +1,81 @@ +// Navigation mesh optimisation records. +#ifndef AI_AIDLL_GTS_DATA_OPTIMISER_H +#define AI_AIDLL_GTS_DATA_OPTIMISER_H + +#include +#include +#include +#include +#include "../../../../../Math/DoubleVec3.h" + +namespace dice { namespace hfe { +// Two-double record used by the optimiser's projected edge operations; member names [INFERRED]. +struct DoubleVec2 { double x, y; }; +namespace io { class File; } +namespace ai { + +class ClusterGraph; +class QuadTree; +class DoublePolygon; +class DestroyableMapPart; + +class OptPolygon +{ +public: + OptPolygon(); + ~OptPolygon(); + void deleteMembers(); + void calculateNormal() const; + const DoubleVec3* getNormal() const; + unsigned char findFirstNeighbourIndex(OptPolygon*) const; + void changeVertex(const DoubleVec3&, const DoubleVec3&); + void changeNeighbour(const DoubleVec3&, OptPolygon*, OptPolygon*); + void printPolygon(io::File&, int) const; + bool checkForDuplicateVertices() const; + + // Field names are inferred from the optimiser and QuadTree readers; offsets are ia-32. + /* +0x00 */ unsigned char m_numberOfVertices; + /* +0x04 */ DoubleVec3* m_vertices; + /* +0x08 */ OptPolygon** m_neighbours; + /* +0x0C */ unsigned char m_material; + /* +0x0D */ unsigned char m_originalMaterial; + /* +0x10 */ mutable DoubleVec3* m_normal; + /* +0x14 */ unsigned int m_index; + /* +0x18 */ unsigned short m_cluster; +}; + +class GTSDataOptimiser +{ +public: + explicit GTSDataOptimiser(ClusterGraph* graph); + ~GTSDataOptimiser(); + void destroyPolygon(OptPolygon* polygon); + void buildOptMeshFromTriangles(DoublePolygon*, DoubleVec3*, unsigned int*, unsigned int*, + unsigned int, QuadTree*); + void optimise(const std::vector&); + OptPolygon* initPolygonIteration(); + OptPolygon* getNextPolygon(); + unsigned int getNumberOfVertices() const; + typedef std::map > VertexRemovalMap; + void removeVerticesAndRebuildPolygon(const VertexRemovalMap&); + OptPolygon* createPolygon() const; + void removeTooThinTriangles(); + void setPolygonIndices(const std::vector&); + bool twoToOneMerge(std::set&); + bool threeToTwoMerge(); + void cleanPolygon(OptPolygon*, unsigned int, unsigned int); + DoubleVec2& getVectorToXZDouble(const DoubleVec3&, const DoubleVec3&, DoubleVec2&); + DoubleVec2& getNormalDouble(const DoubleVec2&, DoubleVec2&); + bool lineIntersect(const DoubleVec3&, const DoubleVec3&, const DoubleVec3&, + const DoubleVec3&, DoubleVec3&); + bool isNeighbourOfPolygon(OptPolygon*, OptPolygon*) const; + void validateNeighbours(OptPolygon*) const; + void validateNeighbourRelations(const std::set&); + + /* +0x00 */ std::list m_polygons; + /* +0x04 */ std::list::iterator m_current; + /* +0x08 */ ClusterGraph* m_clusterGraph; // name: AIDLL_r assert 0x101F74E0 (PE +0x10) +}; + +} } } +#endif diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/MapProperties.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/MapProperties.cpp index 839dd7f44..21771d8dd 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/MapProperties.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/MapProperties.cpp @@ -1,13 +1,16 @@ #include "MapProperties.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2FE200, __tcf_0 0x2FE260, _GLOBAL__I 0x2FE290). +#include #include namespace dice { namespace hfe { namespace ai { -// Initializes map traversal properties and their default limits. +// ELF 0x2FDE80 (C2; C1 0x2FDFA0). Initializes map traversal properties and their default limits. MapProperties::MapProperties() : m_maxSlopeCos(0.0f) , m_radius(0.0f) @@ -16,19 +19,19 @@ MapProperties::MapProperties() { } -// The whole body is the set's own teardown, which a C++ destructor does on its own. Empty here. +// ELF 0x2FE020 (D2; D1 0x2FE090). The whole body is the set's own teardown, which a C++ destructor does on its own. Empty here. MapProperties::~MapProperties() { } -// Tests only the Y component against the slope cosine. Requires a unit surface normal +// ELF 0x2FE100. Tests only the Y component against the slope cosine. Requires a unit surface normal // for slope semantics; the material argument is ignored. bool MapProperties::isValidGroundMesh(const Vec3& normal, unsigned char /*material*/) const { return m_maxSlopeCos <= normal.y; } -// Stores maximum slope as a cosine. The getter clamps it to [-1, 1] before acosf +// ELF 0x2FE130 / 0x2FE160. Stores maximum slope as a cosine. The getter clamps it to [-1, 1] before acosf // and returns the resulting angle in radians. void MapProperties::setMaxSlope(float radians) { @@ -46,27 +49,31 @@ float MapProperties::getMaxSlope() const return acosf(cosine); } +// ELF 0x2FE1B0. void MapProperties::setHeadClearance(float clearance) { m_headClearance = clearance; } +// ELF 0x2FE1C0. float MapProperties::getHeadClearance() const { return m_headClearance; } +// ELF 0x2FE1D0. void MapProperties::setRadius(float radius) { m_radius = radius; } +// ELF 0x2FE1E0. float MapProperties::getRadius() const { return m_radius; } -// no matching getter ships - see the header. +// ELF 0x2FE1F0. No matching getter ships - see the header. void MapProperties::setAllowedHeightDiff(float diff) { m_allowedHeightDiff = diff; diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/MeshImporterExporter.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/MeshImporterExporter.cpp new file mode 100644 index 000000000..855065245 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/MeshImporterExporter.cpp @@ -0,0 +1,59 @@ +// [INFERRED] Source placement from the translation unit's static initializer symbol. +#include "MeshImporterExporter.h" + +// static init: ELF 0x2FE770, __tcf_0 0x2FE7D0, _GLOBAL__I 0x2FE800. +#include + +#include "../../Main/CommonSingletonServer.h" +#include "../../../../AIInterface/BFKnowledge/BFGame.h" +#include "../../../../../IO/File/File.h" + +namespace dice { namespace hfe { namespace ai { + +// ELF 0x2FE320. +bool MeshImporterExporter::exportMesh(const std::vector& vertices, + const std::vector>& edges, + const std::list>& faces, + const std::string& name) +{ + const std::string levelPath = + static_cast(CommonSingletonServer::m_iaiGame)->getLevelPath(); + io::File file; + if (!file.open(levelPath + "/GTSData/Meshes/" + name + ".gts", + static_cast(0), static_cast(1), 0)) + return false; + + file.write(static_cast(vertices.size())); + file.write(static_cast(edges.size())); + file.write(static_cast(faces.size())); + + for (std::vector::const_iterator it = vertices.begin(); it != vertices.end(); ++it) + file.write(0); + for (std::vector::const_iterator it = vertices.begin(); it != vertices.end(); ++it) + { + file.write(static_cast(it->x)); + file.write(static_cast(it->y)); + file.write(static_cast(it->z)); + } + + for (std::vector>::const_iterator it = edges.begin(); it != edges.end(); ++it) + file.write(0); + for (std::vector>::const_iterator it = edges.begin(); it != edges.end(); ++it) + { + file.write(it->first); + file.write(it->second); + } + + for (std::list>::const_iterator it = faces.begin(); it != faces.end(); ++it) + file.write(0); + for (std::list>::const_iterator it = faces.begin(); it != faces.end(); ++it) + { + file.write(it->first); + file.write(it->second); + file.write(it->third); + } + file.close(); + return true; +} + +} } } diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/MeshImporterExporter.h b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/MeshImporterExporter.h new file mode 100644 index 000000000..79178228f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/MeshImporterExporter.h @@ -0,0 +1,26 @@ +// GTS mesh serialization. [INFERRED] Source placement. +#ifndef AI_AIDLL_AI_AIPATHFINDING_NAVMESH_MESHIMPORTEREXPORTER_H +#define AI_AIDLL_AI_AIPATHFINDING_NAVMESH_MESHIMPORTEREXPORTER_H + +#include "../../Main/IAIPathfinding.h" +#include +#include +#include +#include + +namespace dice { namespace hfe { namespace ai { + +class MeshImporterExporter +{ +public: + // Writes a binary GTS mesh beneath the current level's GTSData/Meshes directory. + // Returns false if opening fails; individual write results are discarded. + static bool exportMesh(const std::vector& vertices, + const std::vector>& edges, + const std::list>& faces, + const std::string& name); +}; + +} } } + +#endif diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTPath.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTPath.cpp new file mode 100644 index 000000000..e8b828a25 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTPath.cpp @@ -0,0 +1,30 @@ +// The local path result's out-of-line members. [INFERRED] file name: the image keeps them in their +// own translation unit (own static initialisation) between MeshImporterExporter's and +// QTSearchNode's. + +#include "../../Main/AIPathfindingSearchTypes.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2FE9F0, __tcf_0 0x2FEA50, _GLOBAL__I 0x2FEA80). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2FE870 (C2; C1 0x2FE8C0). No step yet, no island, zero cost. +QTPath::QTPath() + : m_i0(0) + , m_island(-1) + , m_i20(0.0f) +{ +} + +// ELF 0x2FE910 (D2; D1 0x2FE980). +QTPath::~QTPath() +{ +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNode.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNode.cpp new file mode 100644 index 000000000..ce49c5c0b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNode.cpp @@ -0,0 +1,71 @@ +// The local (nav-mesh) A* node's out-of-line members. [INFERRED] file name: the image keeps them +// in their own translation unit (own static initialisation) between QTPath's and +// QTSearchNodeManager's. + +#include "QTSearchNodeManager.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2FED20, __tcf_0 0x2FED80, _GLOBAL__I 0x2FEDB0). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2FEAA0 (C2; C1 0x2FEB00). +QTSearchNode::QTSearchNode(unsigned int polygon, unsigned int depth) + : m_next(0) + , m_prev(0) + , m_parent(0) + , m_expandedFrom(0) + , m_key(polygon) + , m_g(0.0f) + , m_f(0.0f) + , m_depth(static_cast(depth)) +{ + m_position.x = 0.0f; + m_position.y = 0.0f; + m_position.z = 0.0f; +} + +// ELF 0x2FEB60 (C2; C1 0x2FEBE0). +QTSearchNode::QTSearchNode(const QTSearchNode& other) + : m_next(0) + , m_prev(0) + , m_parent(0) + , m_expandedFrom(0) + , m_key(other.m_key) + , m_g(0.0f) + , m_f(0.0f) + , m_depth(0) + , m_position(other.m_position) +{ +} + +// ELF 0x2FEC60 (D2; D1 0x2FEC70): empty. +QTSearchNode::~QTSearchNode() +{ +} + +// ELF 0x2FEC80. +QTSearchNode* QTSearchNode::expandFirst(QTSearchNodeManager* manager, nodeStatus::Status& status, + unsigned short& edge) +{ + edge = 0; + QTSearchNode* const neighbour = manager->getNeighbourOfNode(this, edge, status); + ++edge; + return neighbour; +} + +// ELF 0x2FECD0. +QTSearchNode* QTSearchNode::expand(QTSearchNodeManager* manager, nodeStatus::Status& status, + unsigned short& edge) +{ + QTSearchNode* const neighbour = manager->getNeighbourOfNode(this, edge, status); + ++edge; + return neighbour; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNodeManager.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNodeManager.cpp index 08e7ad29e..a3ca45749 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNodeManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNodeManager.cpp @@ -2,57 +2,532 @@ #include "QTSearchNodeManager.h" -#include "../../Main/AIDllFrontier.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x300590, __tcf_0 0x3005F0, _GLOBAL__I 0x300620). +#include + +#include + +#include "QuadTree.h" +#include "../Material/MaterialManager.h" +#include "../../../../../Core/Debug.h" namespace dice { namespace hfe { namespace ai { -// Constructors share initialization except for the optional quad-tree pointer. -// Keep both overloads; observed stores do not establish member declaration order. +namespace { + +// ELF 0x2FEDD0. False when the node is its own m_expandedFrom ancestor within ten generations. +// Nothing in the image calls it. +bool checkNodeHeritage(QTSearchNode* node) +{ + int generation = 0; + for (QTSearchNode* ancestor = node->m_expandedFrom; ancestor != 0 && generation < 10; + ancestor = ancestor->m_expandedFrom, ++generation) + { + if (ancestor == node) + return false; + } + return true; +} +} // namespace + +// QTSearchNodeManager + +// ELF 0x2FEE00 (C2; C1 0x2FEEC0) and 0x2FEF80 (C2; C1 0x2FF040). Constructors share +// initialization except for the optional quad-tree pointer. +// Keep both overloads; observed stores do not establish member declaration order. QTSearchNodeManager::QTSearchNodeManager() : m_quadTree(0) - , m_i4(0) + , m_goal(0) , m_nodeCache(0) - , m_i12(0) - , m_i16(0) - , m_i20(0) + , m_numberOfNodes(0) + , m_freeEntries(0) + , m_usedBuckets(0) , m_table(new CacheEntry[kCacheEntries]) - , m_i28(0) - , m_i32(0) - , m_i36(0) - , m_i40(0) - , m_i44(0) - , m_b48(false) - , m_i52(0) + , m_additionalGoals(0) + , m_allowedClusters(0) + , m_usePathTopologySmoothing(false) + , m_materials(0) { } QTSearchNodeManager::QTSearchNodeManager(QuadTree* quadTree) : m_quadTree(quadTree) - , m_i4(0) + , m_goal(0) , m_nodeCache(0) - , m_i12(0) - , m_i16(0) - , m_i20(0) + , m_numberOfNodes(0) + , m_freeEntries(0) + , m_usedBuckets(0) , m_table(new CacheEntry[kCacheEntries]) - , m_i28(0) - , m_i32(0) - , m_i36(0) - , m_i40(0) - , m_i44(0) - , m_b48(false) - , m_i52(0) + , m_additionalGoals(0) + , m_allowedClusters(0) + , m_usePathTopologySmoothing(false) + , m_materials(0) { } -// [FRONTIER] Node-manager table and cache-chain teardown remains unimplemented. -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -// Replace the stop when all owned-resource cleanup is recovered. +// ELF 0x2FF100 (D2; D1 0x2FF290). Frees the node pool, every bucket's status records and the nodes they hold, the +// recycled records, the table and the goal copy. QTSearchNodeManager::~QTSearchNodeManager() { - BF2_AI_FRONTIER("dice::hfe::ai::QTSearchNodeManager::~QTSearchNodeManager"); + while (m_nodeCache != 0) + { + QTSearchNode* const node = m_nodeCache; + m_nodeCache = node->m_next; + delete node; + --m_numberOfNodes; + } + + for (unsigned int i = 0; i < kCacheEntries; ++i) + { + StatusEntry* entry = m_table[i].m_head; + while (entry != 0) + { + StatusEntry* const next = entry->m_next; + if (entry->m_node != 0) + delete entry->m_node; + delete entry; + entry = next; + } + } + + while (m_freeEntries != 0) + { + StatusEntry* const entry = m_freeEntries; + m_freeEntries = entry->m_next; + delete entry; + } + + if (m_table != 0) + delete[] m_table; + + if (m_goal != 0) + { + delete m_goal; + --m_numberOfNodes; + } +} + +// ELF 0x2FF420. +void QTSearchNodeManager::setQuadTree(QuadTree* quadTree) +{ + m_quadTree = quadTree; +} + +// ELF 0x2FF430. Keeps a private copy of the goal's polygon and position and recycles `node`. +void QTSearchNodeManager::setGoal(QTSearchNode* node) +{ + if (m_goal == 0) + m_goal = getNewNode(node); + else + m_goal->m_key = node->m_key; + m_goal->m_position = node->m_position; + recycleNode(node); +} + +// ELF 0x2FF4C0. Finds or creates the polygon's status record and marks it open. A recycled record +// keeps its old closed flag; a new one starts not closed. +void QTSearchNodeManager::setNodeOpen(QTSearchNode* node) +{ + const int key = static_cast(node->m_key); + int index = key % kCacheEntries; + if (key < 0) + index += kCacheEntries; + CacheEntry& bucket = m_table[index]; + + for (StatusEntry* entry = bucket.m_head; entry != 0; entry = entry->m_next) + { + if (entry->m_node->m_key == node->m_key) + { + entry->m_open = true; + return; + } + } + + StatusEntry* entry = m_freeEntries; + if (entry != 0) + { + m_freeEntries = entry->m_next; + entry->m_open = true; + entry->m_node = node; + } + else + { + entry = new StatusEntry; + entry->m_open = true; + entry->m_closed = false; + entry->m_node = node; + } + + entry->m_next = bucket.m_head; + if (bucket.m_head == 0) + { + bucket.m_nextUsed = m_usedBuckets; + m_usedBuckets = &bucket; + } + bucket.m_head = entry; +} + +// ELF 0x2FF5A0. The record must exist: retail writes through the search result unchecked. +void QTSearchNodeManager::setNodeClosed(QTSearchNode* node) +{ + const int key = static_cast(node->m_key); + int index = key % kCacheEntries; + if (key < 0) + index += kCacheEntries; + + StatusEntry* entry = m_table[index].m_head; + while (entry != 0 && entry->m_node->m_key != node->m_key) + entry = entry->m_next; + entry->m_open = false; + entry->m_closed = true; +} + +// ELF 0x2FF610. The neighbour across the first bordered edge at or after `edge` (which is left on +// that edge), as a new node one step deeper, with what is known about it in `status`. Impassable +// material, a cluster outside the allowed set and an exhausted polygon report kInvalid; the last +// returns null, the others the node. Unseen neighbours are costed: the entry point is the crossed +// edge's midpoint and, for the goal or an additional goal, f is the exact remaining cost. +QTSearchNode* QTSearchNodeManager::getNeighbourOfNode(QTSearchNode* node, unsigned short& edge, + nodeStatus::Status& status) +{ + unsigned int neighbourPolygon = + m_quadTree->getNeighbourOfPolygon(node->m_key, static_cast(edge)); + while (neighbourPolygon == 0xFFFFFFFFu) + { + ++edge; + if (edge >= m_quadTree->getPolygon(node->m_key)->vertexCount) + { + status = nodeStatus::kInvalid; + return 0; + } + neighbourPolygon = + m_quadTree->getNeighbourOfPolygon(node->m_key, static_cast(edge)); + } + + QTSearchNode* const neighbour = getNewNode(neighbourPolygon, node, node->m_depth + 1); + + const int key = static_cast(neighbour->m_key); + int index = key % kCacheEntries; + if (key < 0) + index += kCacheEntries; + StatusEntry* entry = m_table[index].m_head; + while (entry != 0 && entry->m_node->m_key != neighbour->m_key) + entry = entry->m_next; + + const Polygon* const polygon = m_quadTree->getPolygon(neighbourPolygon); + if (0.0f > m_materials->getMaterialCost(polygon->m_material)) + { + status = nodeStatus::kInvalid; + return neighbour; + } + + if (m_allowedClusters != 0 && m_allowedClusters->find(polygon->cluster) == m_allowedClusters->end()) + { + status = nodeStatus::kInvalid; + return neighbour; + } + + if (entry != 0) + { + if (entry->m_open) + { + status = nodeStatus::kOpen; + return neighbour; + } + if (entry->m_closed) + { + status = nodeStatus::kClosed; + return neighbour; + } + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNodeManager.cpp", 289, "") + << "This case should not exists!"; + status = nodeStatus::kInvalid; + return neighbour; + } + + Vec3 entryPoint; + entryPoint.x = 0.0f; + entryPoint.y = 0.0f; + entryPoint.z = 0.0f; + calculateEntryPoint(entryPoint, edge, node); + neighbour->m_position = entryPoint; + neighbour->m_g = calculateCost(node, neighbour, neighbour->m_position); + + if (neighbour->m_key == m_goal->m_key || + (m_additionalGoals != 0 && + m_additionalGoals->find(neighbourPolygon) != m_additionalGoals->end())) + { + neighbour->m_f = calculateCostBetweenPolygons(node->m_key, entryPoint, neighbourPolygon, + m_goal->m_position) + + neighbour->m_g; + status = nodeStatus::kGoal; + return neighbour; + } + + neighbour->m_f = calculateHeuristicCost(neighbour->m_g, entryPoint); + status = nodeStatus::kUnvisited; + return neighbour; +} + +// ELF 0x2FFA70. A recycled node keeps its costs, position and links except the two parents. +QTSearchNode* QTSearchNodeManager::getNewNode(unsigned int polygon, QTSearchNode* parent, + unsigned int depth) +{ + QTSearchNode* node = m_nodeCache; + if (node != 0) + { + node->m_key = polygon; + node->m_depth = static_cast(depth); + m_nodeCache = m_nodeCache->m_next; + } + else + { + node = new QTSearchNode(polygon, depth); + ++m_numberOfNodes; + } + node->m_parent = parent; + node->m_expandedFrom = parent; + return node; +} + +// ELF 0x2FFAF0. A recycled node is assigned every field of `source`; a new one is copy +// constructed, which keeps only the key and the position. +QTSearchNode* QTSearchNodeManager::getNewNode(QTSearchNode* source) +{ + QTSearchNode* node = m_nodeCache; + if (node != 0) + { + m_nodeCache = node->m_next; + *node = *source; + } + else + { + node = new QTSearchNode(*source); + ++m_numberOfNodes; + } + return node; +} + +// ELF 0x2FFBA0. Returns every status record's node to the pool and the records to their free list, +// one bucket chain at a time, then the goal copy, and drops the allowed-cluster set. +void QTSearchNodeManager::reset() +{ + while (m_usedBuckets != 0) + { + StatusEntry* const first = m_usedBuckets->m_head; + StatusEntry* entry = first; + while (entry->m_next != 0) + { + recycleNode(entry->m_node); + entry = entry->m_next; + } + recycleNode(entry->m_node); + entry->m_next = m_freeEntries; + m_freeEntries = first; + + m_usedBuckets->m_head = 0; + m_usedBuckets = m_usedBuckets->m_nextUsed; + } + + if (m_goal != 0) + { + recycleNode(m_goal); + m_goal = 0; + } + m_allowedClusters = 0; +} + +// ELF 0x2FFC20. +void QTSearchNodeManager::returnReset() +{ + m_usePathTopologySmoothing = false; + m_additionalGoals = 0; +} + +// ELF 0x2FFC40. Re-costs `existing` as reached from `parent` (through the edge between them). The +// route is taken only when it is cheaper by more than half a unit; it then becomes the node's +// parent chain. Refused at the depth limit, for the parent's own predecessor and for a node +// without a parent (the start). +bool QTSearchNodeManager::updateNode(QTSearchNode* parent, QTSearchNode* existing, + unsigned int maxDepth) +{ + const int depth = parent->m_depth + 1; + if (maxDepth == static_cast(depth) || parent->m_expandedFrom == existing || + existing->m_parent == 0) + return false; + + Vec3 entryPoint; + entryPoint.x = 0.0f; + entryPoint.y = 0.0f; + entryPoint.z = 0.0f; + unsigned char edge; + m_quadTree->getNeighbourIndexForPolygon(edge, parent->m_key, existing->m_key); + + QTSearchNode* from = parent; + if (!checkIfNodeHasAdequateSize(existing, edge)) + { + from = parent->m_parent; + if (from == 0) + return false; + } + + calculateEntryPoint(entryPoint, edge, parent); + const float g = calculateCost(from, existing, entryPoint); + const float f = calculateHeuristicCost(g, entryPoint); + if (f + 0.5f >= existing->m_f) + return false; + + existing->m_expandedFrom = parent; + existing->m_position = entryPoint; + existing->m_f = f; + existing->m_g = g; + existing->m_parent = from; + existing->m_depth = depth; + return true; +} + +// ELF 0x2FFDA0. Accumulated cost: the step cost plus `from`'s g when the step cost is positive +// (an impassable -1 is returned as is). No predecessor costs nothing. +float QTSearchNodeManager::calculateCost(QTSearchNode* from, QTSearchNode* to, + const Vec3& entry) const +{ + if (from == 0) + return 0.0f; + float cost = calculateCostBetweenPolygons(from->m_key, from->m_position, to->m_key, entry); + if (cost > 0.0f) + cost += from->m_g; + return cost; +} + +// ELF 0x2FFE20. The straight distance weighted by the material cost of the polygon left; -1 for +// impassable material. With topology smoothing, steps of at least 0.25 also weigh the slope of the +// polygon left and the change of normal between the two polygons. +float QTSearchNodeManager::calculateCostBetweenPolygons(unsigned int fromPolygon, + const Vec3& from, + unsigned int toPolygon, + const Vec3& to) const +{ + float cost = m_materials->getMaterialCost(m_quadTree->getMaterialOfPolygon(fromPolygon)); + if (cost < 0.0f) + return -1.0f; + + const float dx = to.x - from.x; + const float dy = to.y - from.y; + const float dz = to.z - from.z; + const float distance = std::sqrt(dx * dx + dy * dy + dz * dz); + if (!m_usePathTopologySmoothing) + return distance * cost; + + float extra = 0.0f; + if (distance >= 0.25f) + { + const Vec3* const fromNormal = m_quadTree->getNormalOfPolygon(fromPolygon); + const Vec3* const toNormal = m_quadTree->getNormalOfPolygon(toPolygon); + const float turn = + toNormal->x * fromNormal->x + toNormal->y * fromNormal->y + toNormal->z * fromNormal->z; + const float upright = m_quadTree->getNormalOfPolygon(fromPolygon)->y; + + float slope = upright * 5.0f - 4.0f; + if (!(slope > 0.0f)) + slope = 0.0f; + float bend = turn * 5.0f - 4.0f; + if (!(bend > 0.0f)) + bend = 0.0f; + const float slopeFactor = 4.0f - slope * slope * 3.0f; + const float bendTerm = 2.0f - bend * bend; + extra = bendTerm * bendTerm; + cost = slopeFactor * slopeFactor * cost; + } + return cost * distance + extra; +} + +// ELF 0x300060. g plus the straight distance to the goal's position. +float QTSearchNodeManager::calculateHeuristicCost(float cost, const Vec3& position) const +{ + const float dx = m_goal->m_position.x - position.x; + const float dy = m_goal->m_position.y - position.y; + const float dz = m_goal->m_position.z - position.z; + return cost + std::sqrt(dx * dx + dy * dy + dz * dz); +} + +// ELF 0x300100. Appends the chain from the start to `goal` (at most 201 nodes walked back from the +// goal) and the goal's f cost. Each step records its polygon, the polygon it was entered from +// (UINT_MAX for the start) and its entry point. The path's nodes are not cleared first. +void QTSearchNodeManager::buildPath(QTPath& path, QTSearchNode* goal) +{ + m_pathNodes.resize(0); + + QTSearchNode* node = goal; + int count = 0; + while (node != 0) + { + ++count; + m_pathNodes.push_back(node); + node = node->m_parent; + if (count > 200) + break; + } + + for (int i = static_cast(m_pathNodes.size()) - 1; i >= 0; --i) + { + const unsigned int polygon = m_pathNodes[i]->m_key; + const unsigned int enteredFrom = m_pathNodes[i]->m_expandedFrom != 0 + ? m_pathNodes[i]->m_expandedFrom->m_key + : 0xFFFFFFFFu; + path.m_nodes.push_back(make_triple(polygon, enteredFrom, m_pathNodes[i]->m_position)); + } + path.m_i20 = goal->m_f; +} + +// ELF 0x300310. Sums the step costs from the path's current index. The loop runs size - 1 steps +// from there regardless of that start, so a non-zero start reads past the end (a null position); +// retail behaviour. +float QTSearchNodeManager::calculateCostOfPath(const QTPath& path) const +{ + float total = 0.0f; + const unsigned int steps = static_cast(path.m_nodes.size()); + unsigned int polygon = path.getPolygon(path.m_i0); + const Vec3* position = path.getPosition(path.m_i0); + for (unsigned int i = 1; i < steps; ++i) + { + const Vec3* const nextPosition = path.getPosition(path.m_i0 + i); + const unsigned int nextPolygon = path.getPolygon(path.m_i0 + i); + total += calculateCostBetweenPolygons(polygon, *position, nextPolygon, *nextPosition); + polygon = path.getPolygon(path.m_i0 + i); + position = path.getPosition(path.m_i0 + i); + } + return total; +} + +// ELF 0x3004B0. The midpoint of the polygon edge from corner `edge` to the next (wrapping). +void QTSearchNodeManager::calculateEntryPoint(Vec3& entry, unsigned short edge, QTSearchNode* node) +{ + const Vec3* const first = + m_quadTree->getVertexForPolygon(node->m_key, static_cast(edge)); + const Vec3* const second = m_quadTree->getSafeVertexForPolygon( + node->m_key, static_cast(static_cast(edge) + 1)); + entry.x = (second->x + first->x) * 0.5f; + entry.y = (second->y + first->y) * 0.5f; + entry.z = (second->z + first->z) * 0.5f; +} + +// ELF 0x300560. +int QTSearchNodeManager::getSizeOfNodeCache() const +{ + int size = 0; + for (QTSearchNode* node = m_nodeCache; node != 0; node = node->m_next) + ++size; + return size; +} + +// ELF 0x300580: always true in the shipped build. +bool QTSearchNodeManager::checkIfNodeHasAdequateSize(QTSearchNode*, unsigned char) const +{ + return true; } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNodeManager.h b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNodeManager.h index 290e79627..0e5404fa1 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNodeManager.h +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNodeManager.h @@ -1,35 +1,77 @@ -// Node pool for navigation-mesh A* searches. Spare nodes form an intrusive free list. -// [UNRESOLVED] Meaning of the separate 1031-entry table. -// [FRONTIER] Remaining search operations require implementation. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the node-pool lifecycle and search operations. - +// Navigation-mesh A* search nodes and their manager: node pool, per-polygon open/closed status, +// neighbour expansion, costs and path building. +// Placement of QTSearchNode in this file is [INFERRED]: its functions sit beside the manager's in +// the ELF and the anonymous `checkNodeHeritage` helper is between them. #ifndef AI_AIDLL_AI_AIPATHFINDING_NAVMESH_QTSEARCHNODEMANAGER_H // [INFERRED] guard style #define AI_AIDLL_AI_AIPATHFINDING_NAVMESH_QTSEARCHNODEMANAGER_H +#include +#include + +#include "../../Main/AIPathfindingSearchTypes.h" // QTPath, nodeStatus + namespace dice { namespace hfe { namespace ai { +class MaterialManager; class QuadTree; -class QTSearchNode; +class QTSearchNodeManager; + +// One A* node: a polygon reached through a polygon edge. 44 bytes on the ELF (operator new(0x2C)). +class QTSearchNode +{ +public: + QTSearchNode(unsigned int polygon, unsigned int depth); + // Copies only the key and the position; links, costs and depth start cleared. + QTSearchNode(const QTSearchNode& other); + ~QTSearchNode(); + + // Neighbour iteration for AStarResource::update: expandFirst starts at edge 0. Both advance + // `edge` past the edge they report. + QTSearchNode* expandFirst(QTSearchNodeManager* manager, nodeStatus::Status& status, + unsigned short& edge); + QTSearchNode* expand(QTSearchNodeManager* manager, nodeStatus::Status& status, + unsigned short& edge); + + /* +0x00 */ QTSearchNode* m_next; // hash chain / free-list link + /* +0x04 */ QTSearchNode* m_prev; // hash chain back link + /* +0x08 */ QTSearchNode* m_parent; // the node the path continues from + /* +0x0C */ QTSearchNode* m_expandedFrom; // [INFERRED] name: the node whose edge gave m_position + /* +0x10 */ unsigned int m_key; // the polygon + /* +0x14 */ float m_g; // cost from the start + /* +0x18 */ float m_f; // g plus the heuristic + /* +0x1C */ int m_depth; // steps from the start + /* +0x20 */ Vec3 m_position; // entry point: the midpoint of the crossed edge +}; class QTSearchNodeManager { public: - // The eight-byte record of the table at +24. `operator new[]` is called without an array cookie - // so the element is trivially destructible; the constructor zeroes both of its words. Name and - // field names [INFERRED] - see the header note, the identity is [UNRESOLVED]. + // One per-polygon status record, chained per bucket. 12 bytes (operator new(0xC)). Names + // [INFERRED]. + struct StatusEntry + { + bool m_open; + bool m_closed; + QTSearchNode* m_node; + StatusEntry* m_next; + }; + + // The eight-byte record of the table at +24: a link in the used-bucket list and the bucket's + // entry chain. `operator new[]` is called without an array cookie; the constructor zeroes + // both words. Names [INFERRED]. class CacheEntry { public: CacheEntry() - : m_w0(0) - , m_w1(0) + : m_nextUsed(0) + , m_head(0) { } - int m_w0; - int m_w1; + CacheEntry* m_nextUsed; + StatusEntry* m_head; }; // the same prime the search resource'S two hashes use. Written out as a literal in the binary. @@ -37,23 +79,51 @@ class QTSearchNodeManager QTSearchNodeManager(); explicit QTSearchNodeManager(QuadTree* quadTree); - ~QTSearchNodeManager(); // , [FRONTIER] + ~QTSearchNodeManager(); + + void setQuadTree(QuadTree* quadTree); + void setGoal(QTSearchNode* node); + void setNodeOpen(QTSearchNode* node); + void setNodeClosed(QTSearchNode* node); + QTSearchNode* getNeighbourOfNode(QTSearchNode* node, unsigned short& edge, + nodeStatus::Status& status); + QTSearchNode* getNewNode(unsigned int polygon, QTSearchNode* parent, unsigned int depth); + QTSearchNode* getNewNode(QTSearchNode* source); + void reset(); + // Clears the per-search additional goals and the smoothing flag. + void returnReset(); + bool updateNode(QTSearchNode* parent, QTSearchNode* existing, unsigned int maxDepth); + float calculateCost(QTSearchNode* from, QTSearchNode* to, const Vec3& entry) const; + float calculateCostBetweenPolygons(unsigned int fromPolygon, const Vec3& from, + unsigned int toPolygon, const Vec3& to) const; + float calculateHeuristicCost(float cost, const Vec3& position) const; + void buildPath(QTPath& path, QTSearchNode* goal); + float calculateCostOfPath(const QTPath& path) const; + void calculateEntryPoint(Vec3& entry, unsigned short edge, QTSearchNode* node); + int getSizeOfNodeCache() const; + bool checkIfNodeHasAdequateSize(QTSearchNode* node, unsigned char edge) const; + + // [INFERRED] Inlined in every retail user: returns a node to the free list. + void recycleNode(QTSearchNode* node) + { + node->m_next = m_nodeCache; + m_nodeCache = node; + } // layout, on the ELF, read store by store out of the constructor /* +0 */ QuadTree* m_quadTree; // the one argument the second constructor takes - /* +4 */ int m_i4; // = 0 [UNRESOLVED] + /* +4 */ QTSearchNode* m_goal; // = 0; setGoal's copy of the goal node /* +8 */ QTSearchNode* m_nodeCache; // = 0 the intrusive free list `getSizeOfNodeCache` walks - /* +12 */ int m_i12; // = 0 [UNRESOLVED] - /* +16 */ int m_i16; // = 0 [UNRESOLVED] - /* +20 */ int m_i20; // = 0 [UNRESOLVED] + /* +12 */ int m_numberOfNodes; // = 0; nodes allocated and not yet deleted + /* +16 */ StatusEntry* m_freeEntries;// = 0; recycled status records + /* +20 */ CacheEntry* m_usedBuckets; // = 0; buckets holding status records /* +24 */ CacheEntry* m_table; // new CacheEntry[kCacheEntries] - /* +28 */ int m_i28; // = 0 [UNRESOLVED] - /* +32 */ int m_i32; // = 0 [UNRESOLVED] - /* +36 */ int m_i36; // = 0 [UNRESOLVED] - /* +40 */ int m_i40; // = 0 `returnReset` clears this one and m_b48 - /* +44 */ int m_i44; // = 0 [UNRESOLVED] - /* +48 */ bool m_b48; // = false also cleared by `returnReset` - /* +52 */ int m_i52; // = 0 [UNRESOLVED] + /* +28 */ std::vector m_pathNodes; // buildPath's goal-to-start scratch list + // Per-search options set through AIPathfinding; the two sets are borrowed, not owned. + /* +40 */ const std::set* m_additionalGoals; // = 0; returnReset clears it + /* +44 */ const std::set* m_allowedClusters; // = 0; reset clears it + /* +48 */ bool m_usePathTopologySmoothing; // = false; returnReset clears it + /* +52 */ MaterialManager* m_materials; // = 0; the searching vehicle's material costs }; } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTree.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTree.cpp index 96052edd7..d6aa1747f 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTree.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTree.cpp @@ -1,13 +1,23 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining QuadTree operations. +// Navigation quad-tree queries, GTS import, construction and destroyable-map-part state. #include "QuadTree.h" +#include "GTSDataOptimiser.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x309940, __tcf_0 0x3099A0, _GLOBAL__I 0x3099D0). +#include +#include +#include +#include // drawPolygonIds #include "../Cluster/ClusterGraph.h" #include "../Material/MaterialManager.h" #include "../../AIUtils/checkPointer.h" // and, through it, Core/Debug.h #include "../../DrawPrimitives/DPManager.h" // IDPManager::deleteMesh #include "../../Main/CommonSingletonServer.h" +#include "../../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" #include "../../../../../IO/File/File.h" +#include "../../../../../Math/Vec3.h" // vec3ToVec2XZ, lineIntersect, pointWithinPolygon2d #include "../../../../../Math/Mat4.h" #include "../../../../../Math/Plane3.h" @@ -15,14 +25,402 @@ namespace dice { namespace hfe { namespace ai { -// Initializes the island, bounds, array pointers, selected counts, timing values, and -// debug mesh. Size and node/vertex-index/neighbor counts remain unset until clean, +namespace { + +// ELF 0x300ED0. +void setAllMaterialsToGround(unsigned int count, Polygon* polygons) +{ + for (unsigned int i = 0; i < count; ++i) + polygons[i].m_material = 1; +} + +// [INFERRED] Helper name/grouping for the inlined normalisation at ELF 0x30255B, +// 0x3037BC and 0x303869. Both precisions use the single-precision epsilon. +template +void normalizeGTSNormal(Vector& normal, Scalar) +{ + const Scalar squared = normal.x * normal.x + normal.y * normal.y + normal.z * normal.z; + const Scalar epsilon = 1.1920928955078125e-7f; + if (std::fabs(squared - Scalar(1)) < epsilon) + return; + if (std::fabs(squared) < epsilon) + { + normal.x = 0; + normal.y = 0; + normal.z = 0; + return; + } + const Scalar inverse = Scalar(1) / std::sqrt(squared); + normal.y *= inverse; + normal.z *= inverse; + normal.x *= inverse; +} + +} // namespace + +// ELF 0x3031C0. Retains double vertices and normals for the subsequent optimiser. +void QuadTree::readGTSDataFromFileDoubles(io::File& file) +{ + clean(); + file.read(m_vertexCount); + file.read(m_numberOfPolygons); + m_vertexIndexCount = m_numberOfPolygons * 3; + m_numberOfNeighbours = m_numberOfPolygons * 3; + file.read(m_double8C); + file.read(m_double94); + file.read(m_double9C); + file.read(m_doubleA4); + const double xSize = m_double9C - m_double8C; + const double zSize = m_doubleA4 - m_double94; + m_doubleAC = zSize > xSize ? zSize : xSize; + m_polygons = checkPointer(new Polygon[m_numberOfPolygons]); + m_array88 = checkPointer(new DoublePolygon[m_numberOfPolygons]); + m_array84 = checkPointer(new DoubleVec3[m_vertexCount]()); + m_vertexIndices = checkPointer(new unsigned int[m_vertexIndexCount]); + m_neighbours = checkPointer(new unsigned int[m_numberOfNeighbours]); + file.read(m_array84, m_vertexCount * 24); + file.read(m_vertexIndices, m_vertexIndexCount * 4); + std::vector polygons; + DoubleVec3* normals = checkPointer(new DoubleVec3[m_numberOfPolygons]()); + file.read(normals, m_numberOfPolygons * 24); + unsigned char* materials = checkPointer(new unsigned char[m_numberOfPolygons]); + file.read(materials, m_numberOfPolygons); + IAIObjectEnvironment* environment = static_cast( + CommonSingletonServer::m_iaiObjectEnvironment); + environment->initAiCombatAreas(); + for (unsigned int p = 0; p < m_numberOfPolygons; ++p) + { + polygons.push_back(p); + m_array88[p].m_numberOfVertices = 3; + m_array88[p].m_firstIndex = p * 3; + m_polygons[p].vertexCount = 3; + m_polygons[p].vertexOffset = p * 3; + const DoubleVec3& av = m_array84[m_vertexIndices[p * 3]]; + const DoubleVec3& bv = m_array84[m_vertexIndices[p * 3 + 1]]; + const DoubleVec3& cv = m_array84[m_vertexIndices[p * 3 + 2]]; + const Vec3 a = {static_cast(av.x), static_cast(av.y), static_cast(av.z)}; + const Vec3 b = {static_cast(bv.x), static_cast(bv.y), static_cast(bv.z)}; + const Vec3 c = {static_cast(cv.x), static_cast(cv.y), static_cast(cv.z)}; + if (environment->isAiPositionInsideCombatArea(a) && + environment->isAiPositionInsideCombatArea(b) && + environment->isAiPositionInsideCombatArea(c)) + { + m_array88[p].m_material = static_cast(materials[p] + 1); + m_polygons[p].m_material = static_cast(materials[p] + 1); + } + else + { + m_array88[p].m_material = 0; + m_polygons[p].m_material = 0; + } + m_array88[p].m_normal = normals[p]; + normalizeGTSNormal(m_array88[p].m_normal, double()); + m_polygons[p].m_normal = Vec3{static_cast(normals[p].x), + static_cast(normals[p].y), static_cast(normals[p].z)}; + normalizeGTSNormal(m_polygons[p].m_normal, float()); + } + delete[] normals; + delete[] materials; + file.read(m_neighbours, m_numberOfNeighbours * 4); +} + +// ELF 0x302130. The single-precision reader constructs the tree immediately. +void QuadTree::readGTSDataFromFile(io::File& file) +{ + clean(); + file.read(m_vertexCount); + file.read(m_numberOfPolygons); + m_vertexIndexCount = m_numberOfPolygons * 3; + m_numberOfNeighbours = m_numberOfPolygons * 3; + file.read(m_min); + file.read(m_max); + const float xSize = m_max.x - m_min.x; + const float zSize = m_max.y - m_min.y; + m_size = zSize > xSize ? zSize : xSize; + m_polygons = checkPointer(new Polygon[m_numberOfPolygons]); + m_vertices = checkPointer(new Vec3[m_vertexCount]()); + m_vertexIndices = checkPointer(new unsigned int[m_vertexIndexCount]); + m_neighbours = checkPointer(new unsigned int[m_numberOfNeighbours]); + file.read(m_vertices, m_vertexCount * 12); + file.read(m_vertexIndices, m_vertexIndexCount * 4); + std::vector polygons; + Vec3* normals = checkPointer(new Vec3[m_numberOfPolygons]()); + file.read(normals, m_numberOfPolygons * 12); + unsigned char* materials = checkPointer(new unsigned char[m_numberOfPolygons]); + file.read(materials, m_numberOfPolygons); + IAIObjectEnvironment* environment = static_cast( + CommonSingletonServer::m_iaiObjectEnvironment); + environment->initAiCombatAreas(); + for (unsigned int p = 0; p < m_numberOfPolygons; ++p) + { + polygons.push_back(p); + m_polygons[p].vertexCount = 3; + m_polygons[p].vertexOffset = p * 3; + if (environment->isAiPositionInsideCombatArea(m_vertices[m_vertexIndices[p * 3]]) && + environment->isAiPositionInsideCombatArea(m_vertices[m_vertexIndices[p * 3 + 1]]) && + environment->isAiPositionInsideCombatArea(m_vertices[m_vertexIndices[p * 3 + 2]])) + m_polygons[p].m_material = static_cast(materials[p] + 1); + else + m_polygons[p].m_material = 0; + m_polygons[p].m_normal = normals[p]; + normalizeGTSNormal(m_polygons[p].m_normal, float()); + } + delete[] normals; + delete[] materials; + file.read(m_neighbours, m_numberOfNeighbours * 4); + buildQuadTree(polygons); +} + +// ELF 0x304160. +void QuadTree::optimiseGTSData(ClusterGraph* graph) +{ + validateNeighbourRelations(); + GTSDataOptimiser* optimiser = checkPointer(new GTSDataOptimiser(graph)); + optimiser->buildOptMeshFromTriangles(m_array88, m_array84, m_vertexIndices, m_neighbours, + m_numberOfPolygons, this); + optimiser->optimise(m_destroyableMapParts); + clean(); + buildQuadTreeMeshFromOptMesh(optimiser); + delete optimiser; +} + +// ELF 0x304B80; the same construction is inlined into ELF 0x302661..0x302869. +void QuadTree::buildQuadTree(const std::vector& polygons) +{ + m_nodes = checkPointer(new QuadTreeNode[0x1555A]); + m_numberOfNodes = 0; + m_nodes->create(this, m_numberOfNodes, m_min, m_size, 0, polygons, m_numberOfPolygons); + QuadTreeNode* nodes = checkPointer(new QuadTreeNode[m_numberOfNodes]); + for (unsigned int i = 0; i < m_numberOfNodes; ++i) + nodes[i] = m_nodes[i]; + delete[] m_nodes; + m_nodes = nodes; + m_numberOfNodePolygons = static_cast(m_vector18.size()); + m_nodePolygons = checkPointer(new unsigned int[m_numberOfNodePolygons]); + for (unsigned int i = 0; i < m_numberOfNodePolygons; ++i) + m_nodePolygons[i] = m_vector18[i]; + m_vector18.erase(m_vector18.begin(), m_vector18.end()); +} + +// ELF 0x3069C0. +DoublePolygon* QuadTree::getPolygonDouble(unsigned int polygon) const +{ + return polygon < m_numberOfPolygons ? m_array88 + polygon : 0; +} + +// ELF 0x304350. The optimiser owns the source polygons; this tree receives independent arrays. +void QuadTree::buildQuadTreeMeshFromOptMesh(GTSDataOptimiser* optimiser) +{ + m_numberOfPolygons = static_cast(optimiser->m_polygons.size()); + m_vertexCount = optimiser->getNumberOfVertices(); + m_vertexIndexCount = m_vertexCount; + m_numberOfNeighbours = m_vertexCount; + m_min.x = static_cast(m_double8C); + m_min.y = static_cast(m_double94); + m_max.x = static_cast(m_double9C); + m_max.y = static_cast(m_doubleA4); + const float xSize = m_max.x - m_min.x; + const float zSize = m_max.y - m_min.y; + m_size = zSize > xSize ? zSize : xSize; + delete[] m_polygons; + m_polygons = checkPointer(new Polygon[m_numberOfPolygons]); + delete[] m_vertices; + m_vertices = checkPointer(new Vec3[m_vertexCount]()); + delete[] m_vertexIndices; + m_vertexIndices = checkPointer(new unsigned int[m_vertexIndexCount]); + delete[] m_neighbours; + m_neighbours = checkPointer(new unsigned int[m_numberOfNeighbours]); + std::vector polygons; + unsigned int polygon = 0; + unsigned int first = 0; + for (OptPolygon* p = optimiser->initPolygonIteration(); p; p = optimiser->getNextPolygon()) + { + if (p->m_material != 0) + p->m_material = p->m_originalMaterial; + polygons.push_back(polygon); + m_polygons[polygon].vertexCount = p->m_numberOfVertices; + m_polygons[polygon].vertexOffset = first; + m_polygons[polygon].m_material = p->m_material; + const DoubleVec3* normal = p->getNormal(); + m_polygons[polygon].m_normal = Vec3{static_cast(normal->x), + static_cast(normal->y), static_cast(normal->z)}; + m_polygons[polygon].cluster = p->m_cluster; + const unsigned char count = p->m_numberOfVertices; + for (unsigned char corner = 0; corner < count; ++corner) + { + const unsigned int index = first + corner; + const DoubleVec3& vertex = p->m_vertices[corner]; + m_vertices[index] = Vec3{static_cast(vertex.x), + static_cast(vertex.y), static_cast(vertex.z)}; + m_vertexIndices[index] = index; + m_neighbours[index] = p->m_neighbours[corner] ? + p->m_neighbours[corner]->m_index : 0xFFFFFFFFu; + } + ++polygon; + first += count; + } + removeDuplicateVerticesFromOptMesh(); + buildQuadTree(polygons); +} + +// ELF 0x305060. A duplicate points forward to another original vertex; follow the whole chain. +void QuadTree::removeDuplicateVerticesFromOptMesh() +{ + std::vector > mapping( + m_vertexIndexCount, std::make_pair(false, 0u)); + unsigned int count = 0; + buildQuadTreesForDuplicateVertices(mapping, count); + Vec3* vertices = checkPointer(new Vec3[count]()); + for (unsigned int i = 0; i < m_vertexIndexCount; ++i) + { + if (mapping[i].first) + { + vertices[mapping[i].second] = m_vertices[i]; + m_vertexIndices[i] = mapping[i].second; + } + else + { + unsigned int source = i; + while (!mapping[source].first) + source = mapping[source].second; + m_vertexIndices[i] = mapping[source].second; + } + } + delete[] m_vertices; + m_vertices = vertices; + m_vertexCount = count; +} + +// ELF 0x305360. +void QuadTree::buildQuadTreesForDuplicateVertices( + std::vector >& mapping, unsigned int& nextVertex) +{ + std::vector vertices[4]; + std::vector indices[4]; + std::vector > bounds; + initialDivideQuadsAndTestForDuplicateVertices(vertices, indices, bounds); + for (unsigned int i = 0; i < 4; ++i) + recurseQuadTreeForDuplicateVertices(vertices[i], indices[i], bounds[i], 0, + mapping, nextVertex); +} + +namespace { + +// [INFERRED] Name/grouping for the identical inlined subdivision in ELF 0x30556D..0x3057FC +// and 0x305A6A..0x305CF2. The four pairs are appended, without clearing the output. +void appendDuplicateVertexQuadrants(const Vec2& minimum, const Vec2& maximum, + std::vector >& bounds) +{ + Vec2 a = minimum; + Vec2 b = {(minimum.x + maximum.x) * 0.5f, (minimum.y + maximum.y) * 0.5f}; + bounds.push_back(std::make_pair(a, b)); + a = Vec2{minimum.x, (minimum.y + maximum.y) * 0.5f}; + b = Vec2{(minimum.x + maximum.x) * 0.5f, maximum.y}; + bounds.push_back(std::make_pair(a, b)); + a = Vec2{(minimum.x + maximum.x) * 0.5f, (minimum.y + maximum.y) * 0.5f}; + b = maximum; + bounds.push_back(std::make_pair(a, b)); + a = Vec2{(minimum.x + maximum.x) * 0.5f, minimum.y}; + b = Vec2{maximum.x, (minimum.y + maximum.y) * 0.5f}; + bounds.push_back(std::make_pair(a, b)); +} + +} // namespace + +// ELF 0x305550. Inclusive edges choose the first matching quadrant, with no overlap margin. +void QuadTree::initialDivideQuadsAndTestForDuplicateVertices(std::vector* vertices, + std::vector* indices, std::vector >& bounds) +{ + appendDuplicateVertexQuadrants(m_min, m_max, bounds); + for (unsigned int i = 0; i < m_vertexCount; ++i) + { + Vec3* vertex = m_vertices + i; + for (unsigned int q = 0; q < 4; ++q) + { + if (bounds[q].first.x <= vertex->x && bounds[q].first.y <= vertex->z && + vertex->x <= bounds[q].second.x && vertex->z <= bounds[q].second.y) + { + vertices[q].push_back(vertex); + indices[q].push_back(m_vertexIndices[i]); + break; + } + } + } +} + +// ELF 0x305A50. +void QuadTree::divideQuadsAndTestForDuplicateVertices(const Vec2& minimum, const Vec2& maximum, + const std::vector& inputVertices, const std::vector& inputIndices, + std::vector* vertices, std::vector* indices, + std::vector >& bounds) +{ + appendDuplicateVertexQuadrants(minimum, maximum, bounds); + for (unsigned int i = 0; i < inputVertices.size(); ++i) + { + for (unsigned int q = 0; q < 4; ++q) + { + Vec3* vertex = inputVertices[i]; + if (bounds[q].first.x <= vertex->x && bounds[q].first.y <= vertex->z && + vertex->x <= bounds[q].second.x && vertex->z <= bounds[q].second.y) + { + vertices[q].push_back(vertex); + indices[q].push_back(inputIndices[i]); + break; + } + } + } +} + +// ELF 0x305FA0. Subdivision stops at depth four or nine vertices, then compares forward pairs. +void QuadTree::recurseQuadTreeForDuplicateVertices(const std::vector& vertices, + const std::vector& indices, const std::pair& boundary, + unsigned int depth, std::vector >& mapping, + unsigned int& nextVertex) +{ + const unsigned int count = static_cast(vertices.size()); + if (depth != 4 && count > 9) + { + std::vector children[4]; + std::vector childIndices[4]; + std::vector > bounds; + divideQuadsAndTestForDuplicateVertices(boundary.first, boundary.second, vertices, + indices, children, childIndices, bounds); + for (unsigned int q = 0; q < 4; ++q) + recurseQuadTreeForDuplicateVertices(children[q], childIndices[q], bounds[q], + depth + 1, mapping, nextVertex); + return; + } + for (unsigned int i = 0; i < count; ++i) + { + bool duplicate = false; + for (unsigned int j = i + 1; j < count; ++j) + { + const Vec3 difference = {vertices[i]->x - vertices[j]->x, + vertices[i]->y - vertices[j]->y, vertices[i]->z - vertices[j]->z}; + if (difference.x * difference.x + difference.y * difference.y + + difference.z * difference.z < 1.1920928955078125e-7f) + { + mapping[indices[i]] = std::make_pair(false, indices[j]); + duplicate = true; + break; + } + } + if (!duplicate) + { + mapping[indices[i]] = std::make_pair(true, nextVertex); + ++nextVertex; + } + } +} + +// ELF 0x300EF0 (C2; C1 0x301010). Initializes the island, bounds, array pointers, selected +// counts, timing values, and debug mesh. Size and node/vertex-index/neighbor counts remain unset until clean, // which readFromFile calls before loading. QuadTree::QuadTree(unsigned int island) : m_island(island) , m_numberOfPolygons(0) , m_numberOfNodePolygons(0) - , m_numberOfVertices(0) + , m_vertexCount(0) , m_nodes(0) , m_polygons(0) , m_nodePolygons(0) @@ -42,17 +440,17 @@ QuadTree::QuadTree(unsigned int island) m_max.x = 0.0f; m_max.y = 0.0f; - // m_size, m_numberOfNodes, m_numberOfVertexIndices and m_numberOfNeighbours deliberately not + // m_size, m_numberOfNodes, m_vertexIndexCount and m_numberOfNeighbours deliberately not // initialised - both binaries step over them. } -// clean, then the five vectors in reverse declaration order. +// ELF 0x301130 (D2; D1 0x301230). clean, then the five vectors in reverse declaration order. QuadTree::~QuadTree() { clean(); } -// Releases mesh arrays, resets their counts and pointers, and removes debug drawing. +// ELF 0x301330. Releases mesh arrays, resets their counts and pointers, and removes debug drawing. void QuadTree::clean() { delete[] m_nodes; @@ -65,8 +463,8 @@ void QuadTree::clean() m_numberOfNodes = 0; m_numberOfPolygons = 0; m_numberOfNodePolygons = 0; - m_numberOfVertices = 0; - m_numberOfVertexIndices = 0; + m_vertexCount = 0; + m_vertexIndexCount = 0; m_numberOfNeighbours = 0; m_nodes = 0; m_polygons = 0; @@ -87,7 +485,7 @@ void QuadTree::clean() undraw(); } -// Reads a version-3 navigation tree. Unsupported versions leave the existing tree unchanged. +// ELF 0x3016C0. Reads a version-3 navigation tree. Unsupported versions leave the existing tree unchanged. void QuadTree::readFromFile(io::File& file) { int version = 0; @@ -124,20 +522,20 @@ void QuadTree::readFromFile(io::File& file) m_nodePolygons = checkPointer(new unsigned int[m_numberOfNodePolygons]); file.read(m_nodePolygons, sizeof(unsigned int) * m_numberOfNodePolygons); - file.read(m_numberOfVertices); - m_vertices = checkPointer(new Vec3[m_numberOfVertices]()); - file.read(m_vertices, sizeof(Vec3) * m_numberOfVertices); + file.read(m_vertexCount); + m_vertices = checkPointer(new Vec3[m_vertexCount]()); + file.read(m_vertices, sizeof(Vec3) * m_vertexCount); - file.read(m_numberOfVertexIndices); - m_vertexIndices = checkPointer(new unsigned int[m_numberOfVertexIndices]); - file.read(m_vertexIndices, sizeof(unsigned int) * m_numberOfVertexIndices); + file.read(m_vertexIndexCount); + m_vertexIndices = checkPointer(new unsigned int[m_vertexIndexCount]); + file.read(m_vertexIndices, sizeof(unsigned int) * m_vertexIndexCount); file.read(m_numberOfNeighbours); m_neighbours = checkPointer(new unsigned int[m_numberOfNeighbours]); file.read(m_neighbours, sizeof(unsigned int) * m_numberOfNeighbours); } -// Finds a polygon for a position. Empty trees and points outside the island bounds return false. +// ELF 0x306350. Finds a polygon for a position. Empty trees and points outside the island bounds return false. bool QuadTree::findPolygon(const Vec3& position, unsigned int& polygon, MaterialManager* materials, float allowedHeightDiff) const { @@ -152,6 +550,7 @@ bool QuadTree::findPolygon(const Vec3& position, unsigned int& polygon, allowedHeightDiff); } +// ELF 0x306630. bool QuadTree::pointWithinPolygonEdges(Polygon* polygon, const Vec3& point) const { Vec2 point2; @@ -160,7 +559,7 @@ bool QuadTree::pointWithinPolygonEdges(Polygon* polygon, const Vec3& point) cons vec3ToVec2XZ(point, point2); unsigned char edge = 0; - if (polygon->m_numberOfVertices == 0) + if (polygon->vertexCount == 0) return true; do @@ -168,14 +567,14 @@ bool QuadTree::pointWithinPolygonEdges(Polygon* polygon, const Vec3& point) cons Vec2 first; first.x = 0.0f; first.y = 0.0f; - vec3ToVec2XZ(m_vertices[m_vertexIndices[polygon->m_firstIndex + edge]], first); + vec3ToVec2XZ(m_vertices[m_vertexIndices[polygon->vertexOffset + edge]], first); Vec2 second; second.x = 0.0f; second.y = 0.0f; const unsigned char next = static_cast( - (edge + 1) % polygon->m_numberOfVertices); - vec3ToVec2XZ(m_vertices[m_vertexIndices[polygon->m_firstIndex + next]], second); + (edge + 1) % polygon->vertexCount); + vec3ToVec2XZ(m_vertices[m_vertexIndices[polygon->vertexOffset + next]], second); if ((second.y - first.y) * (point2.x - first.x) + (point2.y - first.y) * -(second.x - first.x) < -0.001f) @@ -183,15 +582,16 @@ bool QuadTree::pointWithinPolygonEdges(Polygon* polygon, const Vec3& point) cons ++edge; } - while (edge < polygon->m_numberOfVertices); + while (edge < polygon->vertexCount); return true; } +// ELF 0x3064B0. bool QuadTree::withinPolygon(Polygon* polygon, const Vec3& point, float& distanceSquared, float allowedHeightDiff) const { - const Vec3& first = m_vertices[m_vertexIndices[polygon->m_firstIndex]]; + const Vec3& first = m_vertices[m_vertexIndices[polygon->vertexOffset]]; Plane3 plane; plane.normal = polygon->m_normal; @@ -217,13 +617,14 @@ bool QuadTree::withinPolygon(Polygon* polygon, const Vec3& point, float& distanc const float dx = point.x - intersection.x; const float dy = point.y - intersection.y; const float dz = point.z - intersection.z; - distanceSquared = dz * dz + dy * dy + dx * dx; + distanceSquared = dy * dy + dx * dx + dz * dz; // the listing's summation order static const float maxDistanceAbove = 1.0f; const float limit = point.y > intersection.y ? allowedHeightDiff : maxDistanceAbove; - return distanceSquared <= limit * limit; + return !(distanceSquared > limit * limit); // setbe 0x306619: unordered counts as inside } +// ELF 0x308100. bool QuadTree::isPointInPolygon(const Vec3& point, unsigned int polygon, float allowedHeightDiff, MaterialManager* materials) const { @@ -237,30 +638,489 @@ bool QuadTree::isPointInPolygon(const Vec3& point, unsigned int polygon, float a return withinPolygon(candidate, point, distanceSquared, allowedHeightDiff); } +// ELF 0x307780. void QuadTree::getVerticiesOfPolygon(std::vector& vertices, unsigned int polygon) const { Polygon* const candidate = &m_polygons[polygon]; unsigned char corner = 0; - if (candidate->m_numberOfVertices == 0) + if (candidate->vertexCount == 0) return; do { - vertices.push_back(&m_vertices[m_vertexIndices[candidate->m_firstIndex + corner]]); + vertices.push_back(&m_vertices[m_vertexIndices[candidate->vertexOffset + corner]]); ++corner; } - while (corner < candidate->m_numberOfVertices); + while (corner < candidate->vertexCount); } -// Retail directly indexes the polygon array; there is no bounds or +// ELF 0x3081A0. Retail directly indexes the polygon array; there is no bounds or // null guard between the caller-supplied polygon id and the material byte. unsigned char QuadTree::getMaterialOfPolygon(unsigned int polygon) const { return m_polygons[polygon].m_material; } +// ELF 0x3081C0. Unchecked, like the getter. +void QuadTree::setMaterialOfPolygon(unsigned int polygon, unsigned char material) +{ + m_polygons[polygon].m_material = material; +} + +// Polygon topology accessors. Each polygon's corners and neighbours share one run of indices +// starting at vertexOffset: corner i is m_vertices[m_vertexIndices[first + i]], and the polygon +// across the edge from corner i to corner i + 1 is m_neighbours[first + i] (UINT_MAX on a border). +// None of these checks the polygon id; the "safe" variants only wrap the corner index. + +// ELF 0x3069A0. The only bounds-checked lookup: null past the last polygon. +Polygon* QuadTree::getPolygon(unsigned int polygon) const +{ + if (polygon >= m_numberOfPolygons) + return 0; + return &m_polygons[polygon]; +} + +// ELF 0x3068B0. UINT_MAX when the edge index is not below the polygon's corner count. +unsigned int QuadTree::getNeighbourOfPolygon(unsigned int polygon, unsigned char edge) const +{ + const Polygon* const record = &m_polygons[polygon]; + if (edge >= record->vertexCount) + return 0xFFFFFFFFu; + return m_neighbours[record->vertexOffset + edge]; +} + +// ELF 0x306F80. The start polygon is appended unconditionally (no sentinel or duplicate test, +// unlike the internal walk), then each neighbour is walked in edge order. +void QuadTree::getPolygonsInRadius(std::list& polygons, unsigned int polygon, + const Vec3& centre, float radius) const +{ + polygons.insert(polygons.end(), polygon); + const Polygon* const record = &m_polygons[polygon]; + for (unsigned char edge = 0; edge < record->vertexCount; ++edge) + getPolygonsInRadiusInternal(polygons, m_neighbours[record->vertexOffset + edge], centre, + radius); +} + +// ELF 0x307030. A polygon is taken when corner 0, or the corner `previous` of any pass, is +// strictly closer than the radius, or when the centre projects onto the edge previous -> i +// (0 <= t <= length) at a perpendicular distance within the radius. Retail quirks kept: +// `previous` only advances when the projection lands on the edge (a degenerate edge, length +// <= 1e-8, or an off-edge projection keeps the old corner), and corner 0 is read before the +// corner count is tested. A taken polygon is appended and its neighbours walked in edge order. +void QuadTree::getPolygonsInRadiusInternal(std::list& polygons, + unsigned int polygon, const Vec3& centre, + float radius) const +{ + if (polygon == 0xFFFFFFFFu) + return; + if (std::find(polygons.begin(), polygons.end(), polygon) != polygons.end()) + return; + + const float radiusSqr = radius * radius; + const Polygon* const record = &m_polygons[polygon]; + unsigned char previous = static_cast(record->vertexCount - 1); + + const Vec3& first = m_vertices[m_vertexIndices[record->vertexOffset]]; + float dx = centre.x - first.x; + float dy = centre.y - first.y; + float dz = centre.z - first.z; + bool touches = radiusSqr > dx * dx + dy * dy + dz * dz; + + if (!touches) + { + for (unsigned char i = 0; i < record->vertexCount; ++i) + { + const Vec3& a = m_vertices[m_vertexIndices[record->vertexOffset + i]]; + const Vec3& b = m_vertices[m_vertexIndices[record->vertexOffset + previous]]; + + dx = centre.x - b.x; + dy = centre.y - b.y; + dz = centre.z - b.z; + if (radiusSqr > dx * dx + dy * dy + dz * dz) + { + touches = true; + break; + } + + float ex = b.x - a.x; + float ey = b.y - a.y; + float ez = b.z - a.z; + const float length = std::sqrt(ex * ex + ey * ey + ez * ez); + if (length > 1e-08f) + { + const float inverse = 1.0f / length; + ex *= inverse; + ey *= inverse; + ez *= inverse; + const float wx = centre.x - a.x; + const float wy = centre.y - a.y; + const float wz = centre.z - a.z; + const float t = ex * wx + ey * wy + ez * wz; + if (!(0.0f > t) && !(t > length)) + { + if (radiusSqr >= (wx * wx + wy * wy + wz * wz) - t * t) + { + touches = true; + break; + } + previous = i; + } + } + } + if (!touches) + return; + } + + polygons.insert(polygons.end(), polygon); + for (unsigned char edge = 0; edge < record->vertexCount; ++edge) + getPolygonsInRadiusInternal(polygons, m_neighbours[record->vertexOffset + edge], centre, + radius); +} + +// ELF 0x3069E0. Same shape as getPolygonsInRadius. +void QuadTree::getPolygonsInTriangle(std::list& polygons, unsigned int polygon, + const Vec3& a, const Vec3& b, const Vec3& c) const +{ + polygons.insert(polygons.end(), polygon); + const Polygon* const record = &m_polygons[polygon]; + for (unsigned char edge = 0; edge < record->vertexCount; ++edge) + getPolygonsInTriangleInternal(polygons, m_neighbours[record->vertexOffset + edge], a, b, c); +} + +// ELF 0x306AA0. A polygon is taken when corner 0, or the corner `previous` of a pass, lies in the +// triangle (pointWithinPolygon2d, XZ), or when the edge current -> previous crosses a triangle +// edge (lineIntersect with both parameters in [0, 1]). Any tested corner more than 2 m above +// or below the triangle's first vertex rejects the whole polygon (corner 0 after its inside +// test, the others before theirs). `previous` advances on every pass here. +void QuadTree::getPolygonsInTriangleInternal(std::list& polygons, + unsigned int polygon, const Vec3& a, const Vec3& b, + const Vec3& c) const +{ + Vec3 triangle[3]; + triangle[0] = a; + triangle[1] = b; + triangle[2] = c; + if (polygon == 0xFFFFFFFFu) + return; + if (std::find(polygons.begin(), polygons.end(), polygon) != polygons.end()) + return; + + const Polygon* const record = &m_polygons[polygon]; + unsigned char previous = static_cast(record->vertexCount - 1); + const Vec3& first = m_vertices[m_vertexIndices[record->vertexOffset]]; + bool touches = pointWithinPolygon2d(first, triangle, 3); + if (std::fabs(first.y - a.y) > 2.0f) + return; + + Vec2 triangle2d[3]; + for (int i = 0; i < 3; ++i) + { + triangle2d[i].x = 0.0f; // retail Vec2 constructors + triangle2d[i].y = 0.0f; + } + vec3ToVec2XZ(a, triangle2d[0]); + vec3ToVec2XZ(b, triangle2d[1]); + vec3ToVec2XZ(c, triangle2d[2]); + + if (!touches) + { + for (unsigned char i = 0; i < record->vertexCount; ++i) + { + const Vec3& current = m_vertices[m_vertexIndices[record->vertexOffset + i]]; + const Vec3& corner = m_vertices[m_vertexIndices[record->vertexOffset + previous]]; + if (std::fabs(corner.y - a.y) > 2.0f) + return; + if (pointWithinPolygon2d(corner, triangle, 3)) + { + touches = true; + break; + } + + Vec2 from = { 0.0f, 0.0f }; + Vec2 to = { 0.0f, 0.0f }; + vec3ToVec2XZ(current, from); + vec3ToVec2XZ(corner, to); + for (int j = 0; j < 3; ++j) + { + float t; + float s; + if (lineIntersect(from, to, triangle2d[j], triangle2d[(j + 1) % 3], t, s) + && t >= 0.0f && t <= 1.0f && s >= 0.0f && s <= 1.0f) + { + touches = true; + break; + } + } + if (touches) + break; + previous = i; + } + if (!touches) + return; + } + + polygons.insert(polygons.end(), polygon); + for (unsigned char edge = 0; edge < record->vertexCount; ++edge) + getPolygonsInTriangleInternal(polygons, m_neighbours[record->vertexOffset + edge], a, b, c); +} + +// ELF 0x3068F0. +bool QuadTree::isNeighbourOfPolygon(unsigned int polygon, unsigned int neighbour) const +{ + const Polygon* const record = &m_polygons[polygon]; + for (unsigned char edge = 0; edge < record->vertexCount; ++edge) + { + if (m_neighbours[record->vertexOffset + edge] == neighbour) + return true; + } + return false; +} + +// ELF 0x306950. The edge index wraps modulo the corner count. +unsigned int QuadTree::getSafeNeighbourOfPolygon(unsigned int polygon, unsigned char edge) const +{ + const Polygon* const record = &m_polygons[polygon]; + return m_neighbours[record->vertexOffset + edge % record->vertexCount]; +} + +// ELF 0x307530. +const Vec3* QuadTree::getVertexForPolygon(unsigned int polygon, unsigned char corner) const +{ + return &m_vertices[m_vertexIndices[m_polygons[polygon].vertexOffset + corner]]; +} + +// ELF 0x307560. +bool QuadTree::isVertexOfPolygon(unsigned int polygon, unsigned int vertex) const +{ + const Polygon* const record = &m_polygons[polygon]; + for (unsigned char corner = 0; corner < record->vertexCount; ++corner) + { + if (m_vertexIndices[record->vertexOffset + corner] == vertex) + return true; + } + return false; +} + +// ELF 0x3075C0. The corner index wraps modulo the corner count. +const Vec3* QuadTree::getSafeVertexForPolygon(unsigned int polygon, unsigned char corner) const +{ + const Polygon* const record = &m_polygons[polygon]; + return &m_vertices[m_vertexIndices[record->vertexOffset + corner % record->vertexCount]]; +} + +// ELF 0x307610. +unsigned int QuadTree::getVertexIndexForPolygon(unsigned int polygon, unsigned char corner) const +{ + return m_vertexIndices[m_polygons[polygon].vertexOffset + corner]; +} + +// ELF 0x307640. The corner index wraps modulo the corner count. +unsigned int QuadTree::getSafeVertexIndexForPolygon(unsigned int polygon, + unsigned char corner) const +{ + const Polygon* const record = &m_polygons[polygon]; + return m_vertexIndices[record->vertexOffset + corner % record->vertexCount]; +} + +// ELF 0x307680. The corner average. A polygon without corners divides by zero, as in retail. +void QuadTree::getCentreOfPolygon(Vec3& centre, unsigned int polygon) const +{ + const Polygon* const record = &m_polygons[polygon]; + centre.x = 0.0f; + centre.y = 0.0f; + centre.z = 0.0f; + for (unsigned char corner = 0; corner < record->vertexCount; ++corner) + { + const Vec3& vertex = m_vertices[m_vertexIndices[record->vertexOffset + corner]]; + centre.x += vertex.x; + centre.y += vertex.y; + centre.z += vertex.z; + } + const float inverse = 1.0f / static_cast(record->vertexCount); + centre.x *= inverse; + centre.y *= inverse; + centre.z *= inverse; +} + +// ELF 0x307760. +const Vec3* QuadTree::getNormalOfPolygon(unsigned int polygon) const +{ + return &m_polygons[polygon].m_normal; +} + +// ELF 0x307F90. Finds the edge of `polygon` that borders `neighbour`. Retail tests edge 0 before +// comparing against the corner count, so a polygon without corners still reads its first entry. +bool QuadTree::getNeighbourIndexForPolygon(unsigned char& edge, unsigned int polygon, + unsigned int neighbour) const +{ + const Polygon* const record = &m_polygons[polygon]; + edge = 0; + if (m_neighbours[record->vertexOffset] == neighbour) + return true; + for (;;) + { + ++edge; + if (edge >= record->vertexCount) + return false; + if (m_neighbours[record->vertexOffset + edge] == neighbour) + return true; + } +} + +// ELF 0x307830. Walks the polygon's edges (skipping the one shared with `previousPolygon`) and +// intersects the XZ ray origin + t * (direction.x, 0, direction.z) with each. The first edge hit +// with t >= 0 inside the edge wins; within 0.001 of a corner the edge only counts when the ray +// leaves through it (its 2D normal faces against the ray). Otherwise the smallest near miss under +// `minInvalid` is used. The result lies on the ray in XZ; its height follows `direction.y` over +// the XZ distance. `edge` is left on the hit edge (or past the last one). For a direct hit +// `edgeClearance` receives the distance to the nearer edge end. +bool QuadTree::getLineIntersectionOnEdgeInPolygon(Vec3& intersection, unsigned int polygon, + unsigned char& edge, + unsigned int previousPolygon, + const Vec3& origin, const Vec3& direction, + float* edgeClearance, float*) const +{ + static float minInvalid = 0.001f; + + Vec2 start; + start.x = 0.0f; + start.y = 0.0f; + Vec2 corner; + corner.x = 0.0f; + corner.y = 0.0f; + Vec2 nextCorner; + nextCorner.x = 0.0f; + nextCorner.y = 0.0f; + Vec2 end; + end.x = 0.0f; + end.y = 0.0f; + Vec2 hit; + hit.x = 0.0f; + hit.y = 0.0f; + vec3ToVec2XZ(origin, start); + + float bestMiss = 99999.0f; + float bestT = 0.0f; + Vec2 bestEnd; + bestEnd.x = 0.0f; + bestEnd.y = 0.0f; + + const Polygon* const record = &m_polygons[polygon]; + edge = 0; + if (record->vertexCount != 0) + { + do + { + if (previousPolygon == 0xFFFFFFFFu || + m_neighbours[record->vertexOffset + edge] != previousPolygon) + { + vec3ToVec2XZ(m_vertices[m_vertexIndices[record->vertexOffset + edge]], corner); + vec3ToVec2XZ(m_vertices[m_vertexIndices[record->vertexOffset + + (edge + 1) % record->vertexCount]], + nextCorner); + + const float scale = 1.0f; + Vec3 flat; + flat.x = direction.x * scale; + flat.y = 0.0f * scale; + flat.z = direction.z * scale; + Vec3 ahead; + ahead.x = origin.x + flat.x; + ahead.y = origin.y + flat.y; + ahead.z = origin.z + flat.z; + vec3ToVec2XZ(ahead, end); + + float t; + float s; + if (lineIntersect(start, end, corner, nextCorner, t, s)) + { + bool onEdge = false; + if (t >= 0.0f && s >= 0.0f && 1.0f >= s) + { + if (0.001f >= s || !(s < 0.999f)) + { + Vec2 heading; + heading.x = 0.0f; + heading.y = 0.0f; + vec3ToVec2XZ(direction, heading); + Vec2 side; + side.x = nextCorner.x - corner.x; + side.y = nextCorner.y - corner.y; + Vec2 normal; + normal.x = 0.0f; + normal.y = 0.0f; + getNormal(side, normal); + onEdge = !(normal.x * heading.x + normal.y * heading.y >= 0.0f); + } + else + onEdge = true; + + if (onEdge) + { + Vec2 point; + point.x = start.x * (1.0f - t) + end.x * t; + point.y = start.y * (1.0f - t) + end.y * t; + vec2ToVec3XZ(point, intersection); + vec3ToVec2XZ(intersection, hit); + const float hx = hit.x - start.x; + const float hy = hit.y - start.y; + intersection.y = + std::sqrt(hx * hx + hy * hy) * direction.y + origin.y; + if (edgeClearance != 0) + { + const float ex = corner.x - nextCorner.x; + const float ey = corner.y - nextCorner.y; + const float length = std::sqrt(ex * ex + ey * ey); + const float nearer = (1.0f - s) > s ? s : 1.0f - s; + *edgeClearance = nearer * length; + } + return true; + } + } + else + { + // How far outside the ray (t < 0) or the edge (s outside [0, 1]). + const float behind = 0.0f > t ? std::fabs(t) : 9999.0f; + float miss; + if (0.0f > s && behind > -s) + miss = -s; + else if (s > 1.0f) + miss = behind > s - 1.0f ? s - 1.0f : behind; + else + miss = behind; + + if (minInvalid > miss && bestMiss > miss) + { + bestMiss = miss; + bestT = t; + bestEnd = end; + } + } + } + } + ++edge; + } + while (record->vertexCount > edge); + } + + if (!(minInvalid > bestMiss)) + return false; + + Vec2 point; + point.x = start.x * (1.0f - bestT) + bestEnd.x * bestT; + point.y = start.y * (1.0f - bestT) + bestEnd.y * bestT; + vec2ToVec3XZ(point, intersection); + vec3ToVec2XZ(intersection, hit); + const float hx = hit.x - start.x; + const float hy = hit.y - start.y; + intersection.y = std::sqrt(hx * hx + hy * hy) * direction.y + origin.y; + return true; +} + // Tracks polygons affected by destroyable map parts and restores their original materials. + +// ELF 0x308EE0. void QuadTree::getPolygonsWithinBoundary(const Vec3& minimum, const Vec3& maximum, const Mat4& transformation, std::vector& polygons) const @@ -271,9 +1131,9 @@ void QuadTree::getPolygonsWithinBoundary(const Vec3& minimum, const Vec3& maximu for (unsigned int polygonId = 0; polygonId < m_numberOfPolygons; ++polygonId) { const Polygon& polygon = m_polygons[polygonId]; - for (unsigned int corner = 0; corner < polygon.m_numberOfVertices; ++corner) + for (unsigned int corner = 0; corner < polygon.vertexCount; ++corner) { - const Vec3& vertex = m_vertices[m_vertexIndices[polygon.m_firstIndex + corner]]; + const Vec3& vertex = m_vertices[m_vertexIndices[polygon.vertexOffset + corner]]; Vec3 local; local.x = inverse.m[0] * vertex.x + inverse.m[4] * vertex.y @@ -294,6 +1154,7 @@ void QuadTree::getPolygonsWithinBoundary(const Vec3& minimum, const Vec3& maximu } } +// ELF 0x3093B0. void QuadTree::getPolygonsWithinBoundaryDoubles(const Vec3& minimum, const Vec3& maximum, const Mat4& transformation, std::vector& polygons) const @@ -304,9 +1165,9 @@ void QuadTree::getPolygonsWithinBoundaryDoubles(const Vec3& minimum, const Vec3& for (unsigned int polygonId = 0; polygonId < m_numberOfPolygons; ++polygonId) { const Polygon& polygon = m_polygons[polygonId]; - for (unsigned int corner = 0; corner < polygon.m_numberOfVertices; ++corner) + for (unsigned int corner = 0; corner < polygon.vertexCount; ++corner) { - const DoubleVec3& vertex = m_array84[m_vertexIndices[polygon.m_firstIndex + corner]]; + const DoubleVec3& vertex = m_array84[m_vertexIndices[polygon.vertexOffset + corner]]; Vec3 local; local.x = static_cast(inverse.m[0] * vertex.x + inverse.m[4] * vertex.y @@ -327,7 +1188,8 @@ void QuadTree::getPolygonsWithinBoundaryDoubles(const Vec3& minimum, const Vec3& } } -void QuadTree::initializeDestroyableMapPart(int mapPartId, bool initiallyWalkable, +// ELF 0x308860. +void QuadTree::initializeDestroyableMapPart(int pathfindingMapId, bool initiallyWalkable, const Vec3& minimum, const Vec3& maximum, const Mat4& transformation, ClusterGraph* graph, bool useDoubles) @@ -368,15 +1230,16 @@ void QuadTree::initializeDestroyableMapPart(int mapPartId, bool initiallyWalkabl m_destroyableMapParts.push_back(part); part->m_initiallyWalkable = initiallyWalkable; if (!initiallyWalkable && !useDoubles) - restoreMapPart(mapPartId, graph); + restoreMapPart(pathfindingMapId, graph); part->m_destroyed = false; } -void QuadTree::destroyMapPart(int mapPartId, ClusterGraph* graph) +// ELF 0x308C60. +void QuadTree::destroyMapPart(int pathfindingMapId, ClusterGraph* graph) { if (!m_destroyableMapParts.empty()) { - DestroyableMapPart* const part = m_destroyableMapParts[mapPartId]; + DestroyableMapPart* const part = m_destroyableMapParts[pathfindingMapId]; if (part && !part->m_destroyed) { for (unsigned int i = 0; i < part->m_polygons.size(); ++i) @@ -388,7 +1251,7 @@ void QuadTree::destroyMapPart(int mapPartId, ClusterGraph* graph) if (graph && !part->m_polygons.empty()) { const unsigned int first = part->m_polygons[0]; - graph->m_clusters[m_polygons[first].m_cluster].m_unread0C[2] + graph->m_clusters[m_polygons[first].cluster].m_walkable = static_cast(!part->m_initiallyWalkable); } part->m_destroyed = true; @@ -396,11 +1259,12 @@ void QuadTree::destroyMapPart(int mapPartId, ClusterGraph* graph) } } -void QuadTree::restoreMapPart(int mapPartId, ClusterGraph* graph) +// ELF 0x308D20. +void QuadTree::restoreMapPart(int pathfindingMapId, ClusterGraph* graph) { - if (mapPartId != -1) + if (pathfindingMapId != -1) { - DestroyableMapPart* const part = m_destroyableMapParts[mapPartId]; + DestroyableMapPart* const part = m_destroyableMapParts[pathfindingMapId]; if (part) { for (unsigned int i = 0; i < part->m_polygons.size(); ++i) @@ -412,7 +1276,7 @@ void QuadTree::restoreMapPart(int mapPartId, ClusterGraph* graph) if (graph && !part->m_polygons.empty()) { const unsigned int first = part->m_polygons[0]; - graph->m_clusters[m_polygons[first].m_cluster].m_unread0C[2] + graph->m_clusters[m_polygons[first].cluster].m_walkable = static_cast(part->m_initiallyWalkable); } part->m_destroyed = false; @@ -420,11 +1284,12 @@ void QuadTree::restoreMapPart(int mapPartId, ClusterGraph* graph) } } -void QuadTree::resetOriginalMaterialOfDestroyableMapPart(int mapPartId, ClusterGraph* graph) +// ELF 0x308E30. +void QuadTree::resetOriginalMaterialOfDestroyableMapPart(int pathfindingMapId, ClusterGraph* graph) { - if (mapPartId != -1) + if (pathfindingMapId != -1) { - DestroyableMapPart* const part = m_destroyableMapParts[mapPartId]; + DestroyableMapPart* const part = m_destroyableMapParts[pathfindingMapId]; if (part) { for (unsigned int i = 0; i < part->m_polygons.size(); ++i) @@ -433,7 +1298,7 @@ void QuadTree::resetOriginalMaterialOfDestroyableMapPart(int mapPartId, ClusterG if (graph && !part->m_polygons.empty()) { const unsigned int first = part->m_polygons[0]; - graph->m_clusters[m_polygons[first].m_cluster].m_unread0C[2] + graph->m_clusters[m_polygons[first].cluster].m_walkable = static_cast(part->m_initiallyWalkable); } part->m_destroyed = false; @@ -441,13 +1306,157 @@ void QuadTree::resetOriginalMaterialOfDestroyableMapPart(int mapPartId, ClusterG } } +// ELF 0x308DC0. void QuadTree::resetDestroyableMapParts(ClusterGraph* graph) { for (unsigned int mapPartId = 0; mapPartId < m_destroyableMapParts.size(); ++mapPartId) restoreMapPart(mapPartId, graph); } -// QuadTree::undraw - , (const); inlined into the PE's clean. +// ELF 0x301550. Writes the version-3 record readFromFile reads: bounds, size, then each array +// behind its count. +void QuadTree::saveToFile(io::File& file) +{ + file.write(3); + file.write(&m_min, sizeof(m_min)); + file.write(&m_max, sizeof(m_max)); + file.write(m_size); + + file.write(m_numberOfNodes); + file.write(m_nodes, sizeof(QuadTreeNode) * m_numberOfNodes); + file.write(m_numberOfPolygons); + file.write(m_polygons, sizeof(Polygon) * m_numberOfPolygons); + file.write(m_numberOfNodePolygons); + file.write(m_nodePolygons, sizeof(unsigned int) * m_numberOfNodePolygons); + file.write(m_vertexCount); + file.write(m_vertices, sizeof(Vec3) * m_vertexCount); + file.write(m_vertexIndexCount); + file.write(m_vertexIndices, sizeof(unsigned int) * m_vertexIndexCount); + file.write(m_numberOfNeighbours); + file.write(m_neighbours, sizeof(unsigned int) * m_numberOfNeighbours); +} + +// ELF 0x306400. The debug walk of findPolygon: the same empty-tree and bounds gates (written as +// inclusive acceptance tests here), then the root node's printPolygonsInNode. +void QuadTree::printPolygonsInNode(const Vec3& position, unsigned int& polygon, + MaterialManager* materials, float allowedHeightDiff) const +{ + if (!m_nodes) + return; + + if (m_min.x <= position.x && position.x <= m_max.x + && m_min.y <= position.z && position.z <= m_max.y) + m_nodes[0].printPolygonsInNode(this, m_min, m_size, position, polygon, materials, + allowedHeightDiff); +} + +// ELF 0x306790. One static line per edge (red, 0.3 wide). With `height` both ends are drawn at +// that height instead of the vertices' own. +void QuadTree::drawPolygon(unsigned int polygon, float* height, float time) +{ + const Polygon* const candidate = &m_polygons[polygon]; + unsigned char corner = 0; + if (candidate->vertexCount == 0) + return; + + do + { + Vec3 start = m_vertices[m_vertexIndices[candidate->vertexOffset + corner]]; + const unsigned char next = static_cast( + (corner + 1) % candidate->vertexCount); + Vec3 end = m_vertices[m_vertexIndices[candidate->vertexOffset + next]]; + if (height) + { + end.y = *height; + start.y = end.y; + } + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticLine(time, 0xFF0000u, start, end, 0.3f); + ++corner; + } + while (corner < candidate->vertexCount); +} + +// ELF 0x3068A0. Empty in the shipped image. +void QuadTree::drawPolygonEdge(unsigned int, unsigned char) const +{ +} + +// ELF 0x308010. The corner average, accumulated through getVertexForPolygon. A polygon without +// corners divides by zero, as in retail. +Vec3 QuadTree::getPolygonMidPoint(unsigned int polygon) +{ + Vec3 midPoint; + midPoint.x = 0.0f; + midPoint.y = 0.0f; + midPoint.z = 0.0f; + + const Polygon* const candidate = &m_polygons[polygon]; + for (unsigned char corner = 0; corner < candidate->vertexCount; ++corner) + { + const Vec3* const vertex = getVertexForPolygon(polygon, corner); + midPoint.x += vertex->x; + midPoint.y += vertex->y; + midPoint.z += vertex->z; + } + + const float scale = 1.0f / static_cast(candidate->vertexCount); + midPoint.x *= scale; + midPoint.y *= scale; + midPoint.z *= scale; + return midPoint; +} + +// ELF 0x3081E0. Replaces the debug mesh with one static mesh of every polygon (60 s). Unlike +// undraw, neither manager is null-tested. +void QuadTree::draw() const +{ + IDPStaticCreator* const creator + = static_cast(CommonSingletonServer::m_iDPStaticCreator); + static_cast(CommonSingletonServer::m_iDPManager)->deleteMesh(m_debugMesh); + // DPStaticMesh is not defined in this tree; the image stores the returned pointer unadjusted + // as the DrawPrimitive handle. [CHOSEN, not recovered] cast. + m_debugMesh = reinterpret_cast( + creator->createStaticMesh(60.0f, 0, m_polygons, m_vertices, m_vertexIndices, + static_cast(m_numberOfPolygons), true)); +} + +// ELF 0x3082B0. Each polygon's id as 3D text (white, 30 s) 2 m above its centre. +void QuadTree::drawPolygonIds() const +{ + IDPStaticCreator* const creator + = static_cast(CommonSingletonServer::m_iDPStaticCreator); + for (unsigned long polygon = 0; polygon < m_numberOfPolygons; ++polygon) + { + Vec3 centre; + centre.x = 0.0f; + centre.y = 0.0f; + centre.z = 0.0f; + getCentreOfPolygon(centre, polygon); + centre.y += 2.0f; + + std::stringstream text; + text << polygon; + creator->createStatic3dText(30.0f, 0xFFFFFFFFu, centre, text.str(), 0, + static_cast(0), + static_cast(0)); + } +} + +// ELF 0x3098F0. Walks every polygon's edges and checks nothing: the shipped body is the empty +// loop nest. +void QuadTree::validateNeighbourRelations() const +{ + for (unsigned int polygon = 0; polygon < m_numberOfPolygons; ++polygon) + { + const Polygon& candidate = m_polygons[polygon]; + for (unsigned char edge = 0; edge < candidate.vertexCount; ++edge) + { + } + } +} + +// ELF 0x308270. Inlined into the PE's clean. // Hands the debug mesh to IDPManager::deleteMesh (ELF slot +0x50, PE +0x4C) when the draw-primitive // manager exists; deleteMesh takes the handle by reference. The bool it answers is discarded. void QuadTree::undraw() const diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTree.h b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTree.h index 23a96f250..d52be58ed 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTree.h +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTree.h @@ -1,13 +1,15 @@ // Navigation quad tree with file loading, polygon lookup and destroyable-map-part state. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. #ifndef AI_AIDLL_AI_AIPATHFINDING_NAVMESH_QUADTREE_H #define AI_AIDLL_AI_AIPATHFINDING_NAVMESH_QUADTREE_H +#include #include +#include #include "../../Main/AIDllTypes.h" // Vec2, Vec3, DrawPrimitive #include "QuadTreeNode.h" +#include "../../../../../Math/DoubleVec3.h" namespace dice { namespace hfe { @@ -17,6 +19,7 @@ namespace io { class File; } namespace ai { class ClusterGraph; +class GTSDataOptimiser; class MaterialManager; // Polygon - one navigation-mesh polygon, 20 bytes on disk and in memory. The array is constructed @@ -29,10 +32,10 @@ class Polygon public: Polygon() { m_normal.x = 0.0f; m_normal.y = 0.0f; m_normal.z = 0.0f; } - /* +0x00 */ unsigned char m_numberOfVertices; // bounds every corner / edge index (0x3068B0, 0x307560) + /* +0x00 */ unsigned char vertexCount; // bounds every corner / edge index (0x3068B0, 0x307560) // name: AIDLL_r assert "p.vertexCount" 0x101871C0 (+0) /* +0x01 */ unsigned char m_material; // get/setMaterialOfPolygon (0x3081A0 / 0x3081C0) - /* +0x02 */ unsigned short m_cluster; // ClusterGraph::getClusterId (0x314E10) - /* +0x04 */ unsigned int m_firstIndex; // into m_vertexIndices and m_neighbours + /* +0x02 */ unsigned short cluster; // ClusterGraph::getClusterId (0x314E10) // name: AIDLL_r assert "p->cluster == cId" (0x10175A40; +2) + /* +0x04 */ unsigned int vertexOffset; // into m_vertexIndices and m_neighbours // name: AIDLL_r assert "p.vertexOffset" 0x101871C0 (+4) /* +0x08 */ Vec3 m_normal; // getNormalOfPolygon returns its address (0x307760) }; @@ -51,16 +54,19 @@ class DestroyableMapPart bool m_destroyed; // [INFERRED] name }; -// [INFERRED] source name. readGTSDataFromFileDoubles allocates exactly 24 bytes per element and -// getPolygonsWithinBoundaryDoubles reads three consecutive doubles from each one. -struct DoubleVec3 +// Double-precision GTS polygon: ELF 0x303316 allocates 32 bytes per element. +class DoublePolygon { - double x; - double y; - double z; +public: + DoublePolygon() : m_normal() {} + /* +0x00 */ unsigned char m_numberOfVertices; + /* +0x01 */ unsigned char m_material; + /* +0x02 */ unsigned short m_cluster; + /* +0x04 */ unsigned int m_firstIndex; + /* +0x08 */ DoubleVec3 m_normal; }; -typedef char DoubleVec3IsTheFileRecord[sizeof(DoubleVec3) == 24 ? 1 : -1]; +typedef char DoublePolygonIsTheFileRecord[sizeof(DoublePolygon) == 32 ? 1 : -1]; class QuadTree { @@ -69,13 +75,67 @@ class QuadTree ~QuadTree(); void clean(); + void saveToFile(io::File& file); void readFromFile(io::File& file); + void readGTSDataFromFileDoubles(io::File& file); + void readGTSDataFromFile(io::File& file); + void optimiseGTSData(ClusterGraph* graph); + void buildQuadTreeMeshFromOptMesh(GTSDataOptimiser* optimiser); + void buildQuadTree(const std::vector& polygons); + void removeDuplicateVerticesFromOptMesh(); + void buildQuadTreesForDuplicateVertices(std::vector >&, + unsigned int&); + void initialDivideQuadsAndTestForDuplicateVertices(std::vector*, + std::vector*, std::vector >&); + void divideQuadsAndTestForDuplicateVertices(const Vec2&, const Vec2&, + const std::vector&, const std::vector&, + std::vector*, std::vector*, std::vector >&); + void recurseQuadTreeForDuplicateVertices(const std::vector&, + const std::vector&, const std::pair&, unsigned int, + std::vector >&, unsigned int&); + void draw() const; void undraw() const; + void drawPolygonIds() const; + void drawPolygon(unsigned int polygon, float* height, float time); + void drawPolygonEdge(unsigned int polygon, unsigned char edge) const; + void validateNeighbourRelations() const; bool findPolygon(const Vec3&, unsigned int&, MaterialManager*, float) const; + void printPolygonsInNode(const Vec3&, unsigned int&, MaterialManager*, float) const; + Vec3 getPolygonMidPoint(unsigned int polygon); bool isPointInPolygon(const Vec3&, unsigned int, float, MaterialManager*) const; void getVerticiesOfPolygon(std::vector&, unsigned int) const; unsigned char getMaterialOfPolygon(unsigned int polygon) const; + void setMaterialOfPolygon(unsigned int polygon, unsigned char material); + + // ClusterGraph's GTS importer writes cluster ids through both returned pointers. + Polygon* getPolygon(unsigned int polygon) const; + DoublePolygon* getPolygonDouble(unsigned int polygon) const; + unsigned int getNeighbourOfPolygon(unsigned int polygon, unsigned char edge) const; + bool isNeighbourOfPolygon(unsigned int polygon, unsigned int neighbour) const; + unsigned int getSafeNeighbourOfPolygon(unsigned int polygon, unsigned char edge) const; + const Vec3* getVertexForPolygon(unsigned int polygon, unsigned char corner) const; + bool isVertexOfPolygon(unsigned int polygon, unsigned int vertex) const; + const Vec3* getSafeVertexForPolygon(unsigned int polygon, unsigned char corner) const; + unsigned int getVertexIndexForPolygon(unsigned int polygon, unsigned char corner) const; + unsigned int getSafeVertexIndexForPolygon(unsigned int polygon, unsigned char corner) const; + void getCentreOfPolygon(Vec3& centre, unsigned int polygon) const; + const Vec3* getNormalOfPolygon(unsigned int polygon) const; + bool getNeighbourIndexForPolygon(unsigned char& edge, unsigned int polygon, + unsigned int neighbour) const; + // Where the XZ ray from `origin` along `direction` leaves the polygon; see the definition. + bool getLineIntersectionOnEdgeInPolygon(Vec3& intersection, unsigned int polygon, + unsigned char& edge, unsigned int previousPolygon, + const Vec3& origin, const Vec3& direction, + float* edgeClearance, float*) const; + + // Flood fills from `polygon` over neighbours: the start polygon always, then every polygon a + // vertex or edge of which lies within the radius (XYZ) / that overlaps the triangle (XZ, with + // a 2 m height window); see the definitions. + void getPolygonsInRadius(std::list& polygons, unsigned int polygon, + const Vec3& centre, float radius) const; + void getPolygonsInTriangle(std::list& polygons, unsigned int polygon, + const Vec3& a, const Vec3& b, const Vec3& c) const; void initializeDestroyableMapPart(int, bool, const Vec3&, const Vec3&, const Mat4&, ClusterGraph*, bool); @@ -85,8 +145,15 @@ class QuadTree void resetOriginalMaterialOfDestroyableMapPart(int, ClusterGraph*); private: + friend class GTSDataOptimiser; friend class QuadTreeNode; + friend class QuadTreeManager; + friend class ClusterGraph; + void getPolygonsInRadiusInternal(std::list& polygons, unsigned int polygon, + const Vec3& centre, float radius) const; + void getPolygonsInTriangleInternal(std::list& polygons, unsigned int polygon, + const Vec3& a, const Vec3& b, const Vec3& c) const; bool withinPolygon(Polygon*, const Vec3&, float&, float) const; bool pointWithinPolygonEdges(Polygon*, const Vec3&) const; void getPolygonsWithinBoundary(const Vec3&, const Vec3&, const Mat4&, @@ -95,14 +162,17 @@ class QuadTree std::vector&) const; // Left-hand offsets are the ELF's (sizeof 196; `operator new(0xC4)` in loadQuadTrees). - // [UNRESOLVED] roles for the four vectors, the two byte arrays and the four doubles: only the - // GTS generation path (not written) fills them; the constructor empties them, clean() frees the - // arrays and the destructor the vectors. + // [UNRESOLVED] roles of the scratch vectors except m_vector18, which accumulates leaf + // polygon ids during tree construction. The doubles store min X/Z, max X/Z and extent; + // GTS-only arrays hold double vertices and polygons. clean frees these arrays. /* +0x00 */ std::vector m_vector00; // 12-byte elements, trivial destructor /* +0x0C */ std::vector m_vector0C; /* +0x18 */ std::vector m_vector18; /* +0x24 */ std::vector m_vector24; - /* +0x30 */ unsigned char m_unwritten30[12]; // no constructor, clean or destructor touches it + // Set by QuadTreeManager::loadGTSData; construction and clean leave these untouched. + /* +0x30 */ int m_minPolygonsInLeaf; // [INFERRED] names from the map setup parameters + /* +0x34 */ int m_maxDepthInTree; + /* +0x38 */ int m_gtsBuildValue; // [INFERRED] name; maximum-depth stop applies only at or above this depth /* +0x3C */ Vec2 m_min; // [INFERRED] the island's bounds - Dalian Infantry /* +0x44 */ Vec2 m_max; // (-351.75, -466.75) .. (382.65, 340.53) /* +0x4C */ float m_size; // [INFERRED] the root square's edge - 807.28 there, the larger extent @@ -110,8 +180,8 @@ class QuadTree /* +0x54 */ unsigned int m_numberOfNodes; /* +0x58 */ unsigned int m_numberOfPolygons; // getPolygon's bound (0x3069A0) /* +0x5C */ unsigned int m_numberOfNodePolygons; - /* +0x60 */ unsigned int m_numberOfVertices; - /* +0x64 */ unsigned int m_numberOfVertexIndices; + /* +0x60 */ unsigned int m_vertexCount; // name: AIDLL_r assert 0x1018C4A0 (PE +0x70) + /* +0x64 */ unsigned int m_vertexIndexCount; // name: AIDLL_r assert 0x1018CF30 (PE +0x74) /* +0x68 */ unsigned int m_numberOfNeighbours; /* +0x6C */ QuadTreeNode* m_nodes; /* +0x70 */ Polygon* m_polygons; @@ -120,7 +190,7 @@ class QuadTree /* +0x7C */ unsigned int* m_vertexIndices; /* +0x80 */ unsigned int* m_neighbours; /* +0x84 */ DoubleVec3* m_array84; // GTS-only double-precision vertex array - /* +0x88 */ unsigned char* m_array88; + /* +0x88 */ DoublePolygon* m_array88; /* +0x8C */ double m_double8C; /* +0x94 */ double m_double94; /* +0x9C */ double m_double9C; diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeManager.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeManager.cpp index f1f020e39..306b9e203 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeManager.cpp @@ -1,51 +1,86 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining QuadTreeManager operations. +// Navigation island ownership, GTS import orchestration and navigation debug meshes. #include "QuadTreeManager.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x310FA0, __tcf_0 0x311000, _GLOBAL__I 0x311030). +#include + #include // std::abort - the ELF's island trap +#include +#include +#include +#include #include "QuadTree.h" #include "../Cluster/ClusterGraph.h" #include "../../AIUtils/checkPointer.h" -#include "../../Main/AIDllFrontier.h" +#include "../../Main/AIRandom.h" +#include "../../Main/AISettingsInterfaces.h" #include "../../Main/CommonSingletonServer.h" +#include "../../DrawPrimitives/DPManager.h" // IDPManager, IDPStaticCreator #include "../../../../AIInterface/BFKnowledge/BFGame.h" // IAIGame::getLevelPath +#include "../../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" #include "../../../../../IO/File/File.h" namespace dice { namespace hfe { namespace ai { -// Initializes an empty quad-tree collection and its island metadata. +// ELF 0x30CACB, 0x30E669, 0x30F9AC, 0x310375: inlined constructor. +QuadTreeManager::DebugMesh::DebugMesh() + : m_numberOfVertices(0), m_numberOfPolygons(0), m_numberOfIndices(0) +{ + // shipped defect: the pointers, including the drawing handle, remain uninitialized. +} + +// ELF 0x30D126..0x30D1FF (inlined); amd-64 ELF 0x3580F0 attests lockSize's name. +void QuadTreeManager::DebugMesh::lockSize() +{ + m_firstIndices = checkPointer(new unsigned int[m_numberOfPolygons]); + m_vertexCounts = checkPointer(new unsigned int[m_numberOfPolygons]); + m_vertices = checkPointer(new Vec3[m_numberOfVertices]()); + m_indices = checkPointer(new unsigned int[m_numberOfIndices]); + m_materials = checkPointer(new unsigned char[m_numberOfPolygons]); + m_colours = checkPointer(new unsigned int[m_numberOfPolygons]); +} + +// ELF 0x30A4A0 (C2; C1 0x30A5F0). Initializes an empty quad-tree collection and its island +// metadata. QuadTreeManager::QuadTreeManager() { - // m_numberOfIslands deliberately not initialised - the binary steps over it. + // m_treeCount deliberately not initialised - the binary steps over it. } -// [FRONTIER] Manager destruction requires the remaining quad-tree and debug-mesh cleanup. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding QuadTreeManager operation. +// ELF 0x30DD40 (D2; D1 0x30DE30; first recovered on the client track): +// destroyQuadTrees, unloadDebugMeshes, unloadDebugClusterMeshes, then the four lists and the +// island vector go as members. QuadTreeManager::~QuadTreeManager() { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::~QuadTreeManager"); + destroyQuadTrees(); + unloadDebugMeshes(); + unloadDebugClusterMeshes(); } -// Returns the selected island or cluster graph. The caller must supply a valid island index. +// ELF 0x30E530 / 0x30E550. Returns the selected island or cluster graph. The caller must supply +// a valid island index. QuadTree* QuadTreeManager::getIsland(unsigned int island) const { - return m_islands[island].first; + return m_quadTrees[island].first; } ClusterGraph* QuadTreeManager::getClusterGraph(unsigned int island) const { - return m_islands[island].second; + return m_quadTrees[island].second; } +// ELF 0x310F80. unsigned int QuadTreeManager::getNumberOfIslands() const { - return static_cast(m_islands.size()); + return static_cast(m_quadTrees.size()); } -// Deletes both halves of every island's pair (each `delete` null-tests for itself), then +// ELF 0x30E240. Deletes both halves of every island's pair (each `delete` null-tests for itself), then // `resize(0)` - the shape in both images: g++ 3.x's size test with erase / zero-length // _M_fill_insert, and MSVC's size test with an erase that only moves `end` back. Not clear: the // vector keeps its capacity in both. Called first by loadQuadTrees, so a reload frees the old @@ -53,33 +88,33 @@ unsigned int QuadTreeManager::getNumberOfIslands() const // with no islands at all. void QuadTreeManager::destroyQuadTrees() { - for (std::vector >::iterator it = m_islands.begin(); - it != m_islands.end(); ++it) + for (std::vector >::iterator it = m_quadTrees.begin(); + it != m_quadTrees.end(); ++it) { delete it->first; delete it->second; } - m_islands.resize(0); + m_quadTrees.resize(0); } -// Deletes the matching quad tree while retaining its island entry and nulling its pointer. +// ELF 0x30A690. Deletes the matching quad tree while retaining its island entry and nulling its pointer. void QuadTreeManager::destroyQuadTree(QuadTree* quadTree) { - std::vector >::iterator it = m_islands.begin(); - for (; it != m_islands.end(); ++it) + std::vector >::iterator it = m_quadTrees.begin(); + for (; it != m_quadTrees.end(); ++it) { if (it->first == quadTree) break; } - if (it != m_islands.end()) + if (it != m_quadTrees.end()) { delete it->first; it->first = 0; } } -// Loads navigation meshes for a map into the managed quad trees. +// ELF 0x30ABA0. Loads navigation meshes for a map into the managed quad trees. void QuadTreeManager::loadQuadTrees(const std::string& name) { destroyQuadTrees(); @@ -97,8 +132,8 @@ void QuadTreeManager::loadQuadTrees(const std::string& name) static_cast(0), 0)) return; - quadTreeFile.read(m_numberOfIslands); - if (m_numberOfIslands > 1) + quadTreeFile.read(m_treeCount); + if (m_treeCount > 1) { // [PLATFORM] ELF: signed `cmp edi, 1 / jg` at 0x30AF0A, `call abort` at 0x30B385. PE: signed // `cmp [ebx], 2 / jl` at , `int 3` at - which falls through into the @@ -110,7 +145,7 @@ void QuadTreeManager::loadQuadTrees(const std::string& name) #endif } - for (unsigned int island = 0; island < static_cast(m_numberOfIslands); ++island) + for (unsigned int island = 0; island < static_cast(m_treeCount); ++island) { QuadTree* const quadTree = checkPointer(new QuadTree(island)); quadTree->readFromFile(quadTreeFile); @@ -118,13 +153,13 @@ void QuadTreeManager::loadQuadTrees(const std::string& name) ClusterGraph* const clusterGraph = checkPointer(new ClusterGraph); clusterGraph->readFromFile(clusterFile); - m_islands.push_back(std::make_pair(quadTree, clusterGraph)); + m_quadTrees.push_back(std::make_pair(quadTree, clusterGraph)); } - for (unsigned int island = 0; island < static_cast(m_numberOfIslands); ++island) + for (unsigned int island = 0; island < static_cast(m_treeCount); ++island) { for (unsigned short cluster = 0; - cluster < m_islands[island].second->getNumberOfClusters(); + cluster < m_quadTrees[island].second->getNumberOfClusters(); ++cluster) { } @@ -134,94 +169,619 @@ void QuadTreeManager::loadQuadTrees(const std::string& name) quadTreeFile.close(); } -// [FRONTIER] Remaining operations require quad-tree, cluster-graph, GTS or debug-mesh support. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. -void QuadTreeManager::saveQuadTrees(const std::string&) +// ELF 0x30A700. Writes /AIPathFinding/.qtr and .clb: the island count (also stored in +// m_treeCount) to the tree file, then each island's tree and graph. Nothing is written +// unless both files open. +void QuadTreeManager::saveQuadTrees(const std::string& name) { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::saveQuadTrees"); + const std::string levelPath = + static_cast(CommonSingletonServer::m_iaiGame)->getLevelPath(); + + io::File quadTreeFile; + if (!quadTreeFile.open(levelPath + "/AIPathFinding/" + name + ".qtr", + static_cast(0), io::FILEACCESS_1, 0)) + return; + + io::File clusterFile; + if (!clusterFile.open(levelPath + "/AIPathFinding/" + name + ".clb", + static_cast(0), io::FILEACCESS_1, 0)) + return; + + m_treeCount = static_cast(m_quadTrees.size()); + quadTreeFile.write(m_treeCount); + for (std::vector >::iterator it = m_quadTrees.begin(); + it != m_quadTrees.end(); ++it) + { + it->first->saveToFile(quadTreeFile); + it->second->saveToFile(clusterFile); + } + + quadTreeFile.close(); + clusterFile.close(); } -void QuadTreeManager::loadGTSData(const std::string&, int, int, int, float) +// ELF 0x30B390. Imports and optimises each island before publishing it and computing its costs. +bool QuadTreeManager::loadGTSData(const std::string& name, int maxDepth, int minPolygons, + int map, float radius) { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::loadGTSData"); + destroyQuadTrees(); + const std::string levelPath = + static_cast(CommonSingletonServer::m_iaiGame)->getLevelPath(); + io::File treeFile; + if (!treeFile.open(levelPath + "/GTSData/Output/" + name + ".qti", + io::FILEMODE_READ, static_cast(0), 0)) + return false; + io::File clusterFile; + if (!clusterFile.open(levelPath + "/GTSData/Output/" + name + ".cls", + io::FILEMODE_READ, static_cast(0), 0)) + return false; + unsigned int count; + treeFile.read(count); + if (count == 0) + return false; + + std::vector objects; + static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->getAllDestroyableObjects(objects); + unsigned int island = 0; + do + { + QuadTree* tree = checkPointer(new QuadTree(island)); + tree->m_gtsBuildValue = 1; + tree->m_maxDepthInTree = maxDepth; + tree->m_minPolygonsInLeaf = minPolygons; + tree->readGTSDataFromFileDoubles(treeFile); + for (std::vector::const_iterator i = objects.begin(); + i != objects.end(); ++i) + { + // shipped defect: every object is assigned the same map-part id. + tree->initializeDestroyableMapPart(map, i->initiallyWalkable, i->min, i->max, + i->transform, 0, true); + } + ClusterGraph* graph = checkPointer(new ClusterGraph); + graph->readGTSDataFromFile(tree, clusterFile); + graph->validateClusterGraphConnectivity(tree, true); + tree->optimiseGTSData(graph); + graph->validateClusterGraphConnectivity(tree, false); + graph->createPortals(map, tree, radius); + m_quadTrees.push_back(std::make_pair(tree, graph)); + graph->calculatePortalCosts(map, island); + ++island; + } while (--count != 0); + treeFile.close(); + clusterFile.close(); + return island != 0; } -void QuadTreeManager::recalculatePortalCosts(int) +// ELF 0x30BDA0. Rebuilds every island's portal cost table (island index in vector order). +void QuadTreeManager::recalculatePortalCosts(int map) { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::recalculatePortalCosts"); + unsigned int island = 0; + for (std::vector >::iterator it = m_quadTrees.begin(); + it != m_quadTrees.end(); ++it, ++island) + it->second->calculatePortalCosts(map, island); } -void QuadTreeManager::draw() +// ELF 0x30BE00. Re-creates each debug mesh's static mesh (1e9 s); neither manager is null-tested. +// DPStaticMesh is not defined in this tree; the image stores the returned pointer unadjusted as +// the DrawPrimitive handle. [CHOSEN, not recovered] cast. +void QuadTreeManager::draw() const { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::draw"); + for (std::list::const_iterator it = m_debugMeshes.begin(); + it != m_debugMeshes.end(); ++it) + { + DebugMesh* const mesh = *it; + static_cast(CommonSingletonServer::m_iDPManager)->deleteMesh(mesh->m_mesh); + mesh->m_mesh = 0; + mesh->m_mesh = reinterpret_cast( + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticMesh(1.0e9f, mesh->m_colours, 0, mesh->m_vertices, + mesh->m_indices, mesh->m_numberOfPolygons, true)); + } } -void QuadTreeManager::undraw() +// ELF 0x30BEB0. +void QuadTreeManager::undraw() const { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::undraw"); + for (std::list::const_iterator it = m_debugMeshes.begin(); + it != m_debugMeshes.end(); ++it) + { + DebugMesh* const mesh = *it; + static_cast(CommonSingletonServer::m_iDPManager)->deleteMesh(mesh->m_mesh); + mesh->m_mesh = 0; + } } +// ELF 0x30BF20. draw on the cluster meshes. void QuadTreeManager::drawCluster() { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::drawCluster"); + for (std::list::iterator it = m_debugClusterMeshes.begin(); + it != m_debugClusterMeshes.end(); ++it) + { + DebugMesh* const mesh = *it; + static_cast(CommonSingletonServer::m_iDPManager)->deleteMesh(mesh->m_mesh); + mesh->m_mesh = 0; + mesh->m_mesh = reinterpret_cast( + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticMesh(1.0e9f, mesh->m_colours, 0, mesh->m_vertices, + mesh->m_indices, mesh->m_numberOfPolygons, true)); + } } -void QuadTreeManager::undrawCluster() +// ELF 0x30BFE0. +void QuadTreeManager::undrawCluster() const { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::undrawCluster"); + for (std::list::const_iterator it = m_debugClusterMeshes.begin(); + it != m_debugClusterMeshes.end(); ++it) + { + DebugMesh* const mesh = *it; + static_cast(CommonSingletonServer::m_iDPManager)->deleteMesh(mesh->m_mesh); + mesh->m_mesh = 0; + } } -void QuadTreeManager::drawClusterNeighbourIndices(const Vec3&) +// ELF 0x30C050. The first drawing handle is a circle; the remaining handles are portal labels. +void QuadTreeManager::drawClusterNeighbourIndices(const Vec3& point) { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::drawClusterNeighbourIndices"); + std::list::iterator i = m_drawn.begin(); + if (i != m_drawn.end()) + { + static_cast(CommonSingletonServer::m_iDPManager)->deleteCircle(*i); + i = m_drawn.erase(i); + } + while (i != m_drawn.end()) + { + static_cast(CommonSingletonServer::m_iDPManager)->delete3dText(*i); + i = m_drawn.erase(i); + } + const Vec3 up = {0.0f, 1.0f, 0.0f}; + const Vec3 raised = {point.x + 0.0f, point.y + 1.0f, point.z + 0.0f}; + m_drawn.push_back(reinterpret_cast( + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticCircle(60.0f, 0xFFFFFFu, raised, 0.5f, up, false, 255))); + + const unsigned int islands = static_cast(m_quadTrees.size()); + for (unsigned int island = 0; island < islands; ++island) + { + QuadTree* tree = m_quadTrees[island].first; + ClusterGraph* graph = m_quadTrees[island].second; + MaterialManager* materials = + static_cast(CommonSingletonServer::m_iaiSettings) + ->getVehicleMaterialManager(1); + unsigned int polygon = 0xFFFFFFFFu; + if (!tree->findPolygon(point, polygon, materials, 100.0f)) + continue; + const unsigned short cluster = graph->getClusterId(tree, polygon); + if (cluster == 0xFFFFu) + return; + std::list portals; + graph->getClusterPortals(cluster, 0, portals); + for (std::list::const_iterator p = portals.begin(); + p != portals.end(); ++p) + { + std::stringstream text; + if ((*p)->m_neighbourCluster == 0xFFFFu) + text << "Inv"; + else + text << static_cast((*p)->m_neighbourCluster); + Vec3 position = (*p)->m_position; + // Preserve the x87 expression's precision until the final float store. + const long double random = static_cast(AIRandom::m_instance->next()) * + 2.3283064365386962890625e-10f; + position.y = static_cast((3.0L - 1.0L) * random + 1.0L + position.y); + m_drawn.push_back( + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStatic3dText(60.0f, 0xFFFFFFu, position, text.str(), 0, + static_cast(0), + static_cast(0))); + } + } } +// ELF 0x30E570. Deduplicates vertices within each island and splits at 0x5555 polygons. void QuadTreeManager::buildDebugMeshes(const std::string&) { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::buildDebugMeshes"); + unloadDebugMeshes(); + std::list indices; + std::map vertexMap; + std::list vertices; + std::list materials; + std::vector counts; + const unsigned int islands = static_cast(m_quadTrees.size()); + DebugMesh* mesh = checkPointer(new DebugMesh); + int polygons = 0; + unsigned int nextVertex = 0; + for (unsigned int island = 0; island < islands; ++island) + { + QuadTree* tree = m_quadTrees[island].first; + const unsigned int polygonCount = tree->m_numberOfPolygons; + vertexMap.clear(); + for (unsigned int polygon = 0; polygon < polygonCount; ++polygon) + { + const Polygon* p = tree->getPolygon(polygon); + counts.push_back(p->vertexCount); + materials.push_back(p->m_material); + for (unsigned char corner = 0; corner < p->vertexCount; ++corner) + { + const unsigned int index = tree->m_vertexIndices[p->vertexOffset + corner]; + std::map::iterator v = vertexMap.find(index); + if (v == vertexMap.end()) + { + vertexMap.insert(std::make_pair(index, nextVertex)); + indices.push_back(nextVertex); + vertices.push_back(tree->m_vertices[index]); + ++nextVertex; + } + else + indices.push_back(v->second); + } + ++polygons; + if ((island == islands - 1 && polygon == polygonCount - 1) || polygons == 0x5555) + { + mesh->m_numberOfPolygons = polygons; + mesh->m_numberOfVertices = static_cast(vertices.size()); + mesh->m_numberOfIndices = static_cast(indices.size()); + mesh->lockSize(); + std::copy(vertices.begin(), vertices.end(), mesh->m_vertices); + std::copy(indices.begin(), indices.end(), mesh->m_indices); + std::copy(materials.begin(), materials.end(), mesh->m_materials); + IAIObjectEnvironment* environment = static_cast( + CommonSingletonServer::m_iaiObjectEnvironment); + environment->initAiCombatAreas(); + for (int p = 0; p < mesh->m_numberOfPolygons; ++p) + { + mesh->m_vertexCounts[p] = counts[p]; + mesh->m_firstIndices[p] = p > 0 ? + mesh->m_firstIndices[p - 1] + counts[p - 1] : 0; + bool outside = false; + for (unsigned int corner = 0; corner < counts[p]; ++corner) + { + if (!environment->isAiPositionInsideCombatArea(mesh->m_vertices[ + mesh->m_indices[mesh->m_firstIndices[p] + corner]])) + { + outside = true; + break; + } + } + if (outside) + mesh->m_colours[p] = 0; + else + { + unsigned int base; + switch (mesh->m_materials[p]) + { + case 1: base = 0x80C000u; break; + case 2: base = 0xE00000u; break; + case 3: base = 0xE0E000u; break; + case 4: base = 0x6020E0u; break; + default: base = 0xE00000u; break; + } + mesh->m_colours[p] = (AIRandom::m_instance->next() & 0x1F1F1F1Fu) + base; + } + } + m_debugMeshes.push_back(mesh); + if (polygons == 0x5555) + { + mesh = checkPointer(new DebugMesh); + polygons = 0; + nextVertex = 0; + vertices.resize(0, Vec3()); + indices.resize(0, 0); + vertexMap.clear(); + materials.resize(0, 0); + counts.resize(0); + } + } + } + } + // shipped defect: an unused mesh leaks for empty input or an exact final chunk. + triangulateDebugMeshes(m_debugMeshes); } +// ELF 0x30C9B0. Clusters share a base colour; each polygon consumes another random value. void QuadTreeManager::buildDebugClusterMeshes(const std::string&) { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::buildDebugClusterMeshes"); + unloadDebugClusterMeshes(); + const unsigned int islands = static_cast(m_quadTrees.size()); + int polygons = 0; + std::list indices; + std::list vertices; + std::map vertexMap; + std::vector counts; + std::list materials; + std::list colours; + unsigned int clusterTag = 1; + DebugMesh* mesh = checkPointer(new DebugMesh); + unsigned int nextVertex = 0; + for (unsigned int island = 0; island < islands; ++island) + { + QuadTree* tree = m_quadTrees[island].first; + ClusterGraph* graph = m_quadTrees[island].second; + const unsigned int clusterCount = graph->m_numberOfClusters; + vertexMap.clear(); + for (unsigned short cluster = 0; cluster < clusterCount; ++cluster) + { + const unsigned int first = graph->m_clusters[cluster].m_firstPolygon; + const unsigned int count = graph->m_clusters[cluster].m_numberOfPolygons; + unsigned int base = graph->m_clusters[cluster].m_walkable ? + AIRandom::m_instance->next() & 0xFFFFFFu : 0xFF0000u; + for (unsigned int polygon = 0; polygon < count; ++polygon) + { + const Polygon* p = tree->getPolygon(graph->m_clusterPolygons[first + polygon]); + ++polygons; + counts.push_back(p->vertexCount); + materials.push_back(static_cast(clusterTag)); + base &= 0xE0E0E0E0u; + colours.push_back((AIRandom::m_instance->next() & 0x1F1F1F1Fu) + base); + for (unsigned char corner = 0; corner < p->vertexCount; ++corner) + { + const unsigned int index = tree->m_vertexIndices[p->vertexOffset + corner]; + std::map::iterator v = vertexMap.find(index); + if (v == vertexMap.end()) + { + vertexMap.insert(std::make_pair(index, nextVertex)); + indices.push_back(nextVertex); + vertices.push_back(tree->m_vertices[index]); + ++nextVertex; + } + else + indices.push_back(v->second); + } + if ((island == islands - 1 && cluster == clusterCount - 1 && + polygon == count - 1) || polygons == 0x5555) + { + mesh->m_numberOfPolygons = polygons; + mesh->m_numberOfVertices = static_cast(vertices.size()); + mesh->m_numberOfIndices = static_cast(indices.size()); + mesh->lockSize(); + std::copy(vertices.begin(), vertices.end(), mesh->m_vertices); + std::copy(indices.begin(), indices.end(), mesh->m_indices); + std::copy(materials.begin(), materials.end(), mesh->m_materials); + std::list::const_iterator colour = colours.begin(); + for (int p = 0; p < mesh->m_numberOfPolygons; ++p, ++colour) + { + mesh->m_vertexCounts[p] = counts[p]; + mesh->m_firstIndices[p] = p > 0 ? + mesh->m_firstIndices[p - 1] + counts[p - 1] : 0; + mesh->m_colours[p] = *colour; + } + m_debugClusterMeshes.push_back(mesh); + if (polygons == 0x5555) + { + mesh = checkPointer(new DebugMesh); + nextVertex = 0; + polygons = 0; + vertices.resize(0, Vec3()); + indices.resize(0, 0); + vertexMap.clear(); + materials.resize(0, 0); + counts.resize(0); + colours.resize(0, 0); + } + } + } + ++clusterTag; + } + } + // shipped defect: an unused mesh leaks for empty input or an exact final chunk. + triangulateDebugMeshes(m_debugClusterMeshes); } -void QuadTreeManager::loadGTSDebugMeshes(const std::string&) +// ELF 0x30F630. GTS debug triangles use different material colours from the quad-tree meshes. +void QuadTreeManager::loadGTSDebugMeshes(const std::string& name) { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::loadGTSDebugMeshes"); + unloadDebugMeshes(); + const std::string levelPath = + static_cast(CommonSingletonServer::m_iaiGame)->getLevelPath(); + io::File file; + if (!file.open(levelPath + "/GTSData/Output/" + name + ".vbf", + io::FILEMODE_READ, static_cast(0), 0)) + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeManager.cpp", 938, "") + << "Could not find file " << levelPath << "/GTSData/Output/" << name << ".vbf"; + return; + } + int count; + file.read(count); + IAIObjectEnvironment* environment = static_cast( + CommonSingletonServer::m_iaiObjectEnvironment); + environment->initAiCombatAreas(); + for (int island = 0; island < count; ++island) + { + DebugMesh* mesh = checkPointer(new DebugMesh); + file.read(mesh->m_numberOfVertices); + file.read(mesh->m_numberOfPolygons); + mesh->m_numberOfIndices = mesh->m_numberOfPolygons * 3; + mesh->lockSize(); + file.read(mesh->m_vertices, mesh->m_numberOfVertices * 12); + file.read(mesh->m_indices, mesh->m_numberOfPolygons * 12); + file.read(mesh->m_materials, mesh->m_numberOfPolygons); + for (int polygon = 0; polygon < mesh->m_numberOfPolygons; ++polygon) + { + mesh->m_firstIndices[polygon] = polygon * 3; + mesh->m_vertexCounts[polygon] = 3; + if (!environment->isAiPositionInsideCombatArea( + mesh->m_vertices[mesh->m_indices[polygon * 3]]) || + !environment->isAiPositionInsideCombatArea( + mesh->m_vertices[mesh->m_indices[polygon * 3 + 1]]) || + !environment->isAiPositionInsideCombatArea( + mesh->m_vertices[mesh->m_indices[polygon * 3 + 2]])) + mesh->m_colours[polygon] = 0; + else + { + unsigned int base; + switch (static_cast(mesh->m_materials[polygon]) + 1) + { + case 1: base = 0x80C000u; break; + case 3: base = 0x80C0u; break; + case 4: base = 0x40A0u; break; + default: base = 0xE00000u; break; + } + mesh->m_colours[polygon] = (AIRandom::m_instance->next() & 0x1F1F1F1Fu) + base; + } + } + m_debugMeshes.push_back(mesh); + } + file.close(); } +// ELF 0x310150. Erases every mesh node first, then releases the mesh's static mesh (IDPManager +// +0x50), frees its six arrays and the mesh; finally resize(0). void QuadTreeManager::unloadDebugMeshes() { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::unloadDebugMeshes"); + std::list::iterator it = m_debugMeshes.begin(); + while (it != m_debugMeshes.end()) + { + DebugMesh* const mesh = *it; + it = m_debugMeshes.erase(it); + if (mesh) + { + static_cast(CommonSingletonServer::m_iDPManager)->deleteMesh(mesh->m_mesh); + mesh->m_mesh = 0; + delete[] mesh->m_firstIndices; + delete[] mesh->m_vertexCounts; + delete[] mesh->m_vertices; + delete[] mesh->m_indices; + delete[] mesh->m_materials; + delete[] mesh->m_colours; + delete mesh; + } + } + m_debugMeshes.resize(0, 0); } +// ELF 0x30DBD0: the same sequence on the cluster-mesh list. void QuadTreeManager::unloadDebugClusterMeshes() { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::unloadDebugClusterMeshes"); + std::list::iterator it = m_debugClusterMeshes.begin(); + while (it != m_debugClusterMeshes.end()) + { + DebugMesh* const mesh = *it; + it = m_debugClusterMeshes.erase(it); + if (mesh) + { + static_cast(CommonSingletonServer::m_iDPManager)->deleteMesh(mesh->m_mesh); + mesh->m_mesh = 0; + delete[] mesh->m_firstIndices; + delete[] mesh->m_vertexCounts; + delete[] mesh->m_vertices; + delete[] mesh->m_indices; + delete[] mesh->m_materials; + delete[] mesh->m_colours; + delete mesh; + } + } + m_debugClusterMeshes.resize(0, 0); } -void QuadTreeManager::triangulateDebugMeshes(std::list&) +// ELF 0x3102C0. Replaces each polygon mesh with triangle fans, retaining sorted vertex order. +void QuadTreeManager::triangulateDebugMeshes(std::list& meshes) { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::triangulateDebugMeshes"); + std::vector triangles; + for (std::list::const_iterator i = meshes.begin(); i != meshes.end(); ++i) + { + DebugMesh* source = *i; + int first = 0; + while (first < source->m_numberOfPolygons) + { + DebugMesh* mesh = checkPointer(new DebugMesh); + std::set vertices; + int polygonCount = 0; + int indexCount = 0; + int end = first; + int prospectiveCount = static_cast(source->m_vertexCounts[end] - 2); + while (prospectiveCount <= 0x5555 && end < source->m_numberOfPolygons) + { + polygonCount = prospectiveCount; + indexCount += source->m_vertexCounts[end] * 3 - 6; + ++end; + // shipped defect: the lookahead reads past the final polygon's count. + prospectiveCount = static_cast(source->m_vertexCounts[end] - 2) + polygonCount; + } + for (int polygon = first; polygon < end; ++polygon) + for (unsigned int corner = 0; corner < source->m_vertexCounts[polygon]; ++corner) + vertices.insert(source->m_indices[source->m_firstIndices[polygon] + corner]); + + mesh->m_numberOfVertices = static_cast(vertices.size()); + mesh->m_numberOfPolygons = polygonCount; + mesh->m_numberOfIndices = indexCount; + mesh->lockSize(); + std::map vertexMap; + unsigned int nextVertex = 0; + for (std::set::const_iterator v = vertices.begin(); v != vertices.end(); ++v) + { + mesh->m_vertices[nextVertex] = source->m_vertices[*v]; + vertexMap.insert(std::make_pair(*v, nextVertex)); + ++nextVertex; + } + unsigned int triangle = 0; + unsigned int index = 0; + unsigned int firstIndex = 0; + for (int polygon = first; polygon < end; ++polygon) + { + const std::map::const_iterator v = vertexMap.find( + source->m_indices[source->m_firstIndices[polygon]]); + for (unsigned int corner = 1; corner < source->m_vertexCounts[polygon] - 1; ++corner) + { + mesh->m_indices[index++] = v->second; + mesh->m_indices[index++] = vertexMap.find( + source->m_indices[source->m_firstIndices[polygon] + corner])->second; + mesh->m_indices[index++] = vertexMap.find( + source->m_indices[source->m_firstIndices[polygon] + corner + 1])->second; + mesh->m_firstIndices[triangle] = firstIndex; + mesh->m_vertexCounts[triangle] = 3; + mesh->m_materials[triangle] = source->m_materials[polygon]; + mesh->m_colours[triangle] = source->m_colours[polygon]; + ++triangle; + firstIndex += 3; + } + } + first = end; + triangles.push_back(mesh); + // shipped defect: a polygon exceeding the chunk limit makes no forward progress. + } + } + + std::list::iterator i = meshes.begin(); + while (i != meshes.end()) + { + DebugMesh* mesh = *i; + i = meshes.erase(i); + if (mesh) + { + static_cast(CommonSingletonServer::m_iDPManager)->deleteMesh(mesh->m_mesh); + mesh->m_mesh = 0; + delete[] mesh->m_firstIndices; + delete[] mesh->m_vertexCounts; + delete[] mesh->m_vertices; + delete[] mesh->m_indices; + delete[] mesh->m_materials; + delete[] mesh->m_colours; + delete mesh; + } + } + meshes.resize(0, 0); + for (std::vector::const_iterator mesh = triangles.begin(); + mesh != triangles.end(); ++mesh) + meshes.push_back(*mesh); } -// Visit islands in vector order and return the first +// ELF 0x30DF20. Visit islands in vector order and return the first // whose tree finds a polygon. The polygon output is whatever that tree wrote; a total miss leaves it // untouched and returns UINT_MAX. unsigned int QuadTreeManager::findPolygon(const Vec3& point, unsigned int& polygon, MaterialManager* materials, float allowedHeightDiff) { - for (unsigned int island = 0; island < m_islands.size(); ++island) + for (unsigned int island = 0; island < m_quadTrees.size(); ++island) { - if (m_islands[island].first->findPolygon(point, polygon, materials, allowedHeightDiff)) + if (m_quadTrees[island].first->findPolygon(point, polygon, materials, allowedHeightDiff)) return island; } return 0xFFFFFFFFu; } -// Reuse a known polygon/island only when neither is the +// ELF 0x30DFA0. Reuse a known polygon/island only when neither is the // sentinel and the point still belongs to it; otherwise run the full scan. The island is deliberately // not bounds-checked before indexing the vector. unsigned int QuadTreeManager::findPolygon(const Vec3& point, unsigned int& polygon, @@ -229,7 +789,7 @@ unsigned int QuadTreeManager::findPolygon(const Vec3& point, unsigned int& polyg MaterialManager* materials, float allowedHeightDiff) { if (knownIsland == 0xFFFFFFFFu || knownPolygon == 0xFFFFFFFFu - || !m_islands[knownIsland].first->isPointInPolygon( + || !m_quadTrees[knownIsland].first->isPointInPolygon( point, knownPolygon, allowedHeightDiff, materials)) return findPolygon(point, polygon, materials, allowedHeightDiff); @@ -237,74 +797,91 @@ unsigned int QuadTreeManager::findPolygon(const Vec3& point, unsigned int& polyg return knownIsland; } -void QuadTreeManager::printPolygonsInNode(const Vec3&, unsigned int&, MaterialManager*, float) const +// ELF 0x30E080. Every island's debug walk, re-reading the vector size each pass. +void QuadTreeManager::printPolygonsInNode(const Vec3& point, unsigned int& polygon, + MaterialManager* materials, float allowedHeightDiff) { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::printPolygonsInNode"); + for (unsigned int island = 0; island < m_quadTrees.size(); ++island) + m_quadTrees[island].first->printPolygonsInNode(point, polygon, materials, + allowedHeightDiff); } -unsigned short QuadTreeManager::getCluster(unsigned int, unsigned int) const +// ELF 0x30E0F0. +unsigned short QuadTreeManager::getCluster(unsigned int island, unsigned int polygon) const { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::getCluster"); + return m_quadTrees[island].second->getClusterId(m_quadTrees[island].first, polygon); } -void QuadTreeManager::getClusterPortals(unsigned int, unsigned short, unsigned short, - std::list&) const +// ELF 0x30E140. +void QuadTreeManager::getClusterPortals(unsigned int island, unsigned short cluster, + unsigned short costType, + std::list& portals) const { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::getClusterPortals"); + m_quadTrees[island].second->getClusterPortals(cluster, costType, portals); } -void QuadTreeManager::getPolygonsInRadius(std::list&, unsigned int, unsigned int, - const Vec3&, float) const +// ELF 0x30E190. The island's tree only; no bounds check. +void QuadTreeManager::getPolygonsInRadius(std::list& polygons, unsigned int island, + unsigned int polygon, const Vec3& centre, + float radius) const { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::getPolygonsInRadius"); + m_quadTrees[island].first->getPolygonsInRadius(polygons, polygon, centre, radius); } -void QuadTreeManager::getPolygonsInTriangle(std::list&, unsigned int, unsigned int, - const Vec3&, const Vec3&, const Vec3&) const +// ELF 0x30E1E0. +void QuadTreeManager::getPolygonsInTriangle(std::list& polygons, unsigned int island, + unsigned int polygon, const Vec3& a, const Vec3& b, + const Vec3& c) const { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::getPolygonsInTriangle"); + m_quadTrees[island].first->getPolygonsInTriangle(polygons, polygon, a, b, c); } -// Forward to every island in ascending order, re-reading the vector +// ELF 0x30E320. Forward to every island in ascending order, re-reading the vector // size on each pass. Runtime map parts use the ordinary float-vertex path (`useDoubles=false`). void QuadTreeManager::initializeDestroyableMapPart(int mapPartId, bool initiallyWalkable, const Vec3& minimum, const Vec3& maximum, const Mat4& transformation) { - for (unsigned int island = 0; island < m_islands.size(); ++island) - m_islands[island].first->initializeDestroyableMapPart( + for (unsigned int island = 0; island < m_quadTrees.size(); ++island) + m_quadTrees[island].first->initializeDestroyableMapPart( mapPartId, initiallyWalkable, minimum, maximum, transformation, - m_islands[island].second, false); + m_quadTrees[island].second, false); } +// ELF 0x30E3C0. void QuadTreeManager::destroyMapPart(int mapPartId) { - for (unsigned int island = 0; island < m_islands.size(); ++island) - m_islands[island].first->destroyMapPart(mapPartId, m_islands[island].second); + for (unsigned int island = 0; island < m_quadTrees.size(); ++island) + m_quadTrees[island].first->destroyMapPart(mapPartId, m_quadTrees[island].second); } +// ELF 0x30E420. void QuadTreeManager::restoreMapPart(int mapPartId) { - for (unsigned int island = 0; island < m_islands.size(); ++island) - m_islands[island].first->restoreMapPart(mapPartId, m_islands[island].second); + for (unsigned int island = 0; island < m_quadTrees.size(); ++island) + m_quadTrees[island].first->restoreMapPart(mapPartId, m_quadTrees[island].second); } +// ELF 0x30E480. void QuadTreeManager::resetOriginalMaterialOfDestroyableMapPart(int mapPartId) { - for (unsigned int island = 0; island < m_islands.size(); ++island) - m_islands[island].first->resetOriginalMaterialOfDestroyableMapPart( - mapPartId, m_islands[island].second); + for (unsigned int island = 0; island < m_quadTrees.size(); ++island) + m_quadTrees[island].first->resetOriginalMaterialOfDestroyableMapPart( + mapPartId, m_quadTrees[island].second); } +// ELF 0x30E4E0. void QuadTreeManager::resetDestroyableMapParts() { - for (unsigned int island = 0; island < m_islands.size(); ++island) - m_islands[island].first->resetDestroyableMapParts(m_islands[island].second); + for (unsigned int island = 0; island < m_quadTrees.size(); ++island) + m_quadTrees[island].first->resetDestroyableMapParts(m_quadTrees[island].second); } -void QuadTreeManager::validateNeighbourRelations() +// ELF 0x310F30. +void QuadTreeManager::validateNeighbourRelations() const { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::validateNeighbourRelations"); + for (unsigned int island = 0; island < m_quadTrees.size(); ++island) + m_quadTrees[island].first->validateNeighbourRelations(); } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeManager.h b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeManager.h index 066df3774..05f816713 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeManager.h +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeManager.h @@ -1,5 +1,4 @@ // Owns navigation quad trees and loads their per-map data. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. #ifndef AI_AIDLL_AI_AIPATHFINDING_NAVMESH_QUADTREEMANAGER_H #define AI_AIDLL_AI_AIPATHFINDING_NAVMESH_QUADTREEMANAGER_H @@ -23,9 +22,26 @@ class QuadTree; class QuadTreeManager { public: - // Opaque nested debug mesh, referenced by pointer here. Teardown must release six - // arrays at original offsets +12..+32 and its primitive handle at +36. - class DebugMesh; + // One debug mesh: up to 0x5555 polygons of the islands in one static mesh. 40 bytes on the + // ELF (operator new(0x28)), no virtual members. Field names [INFERRED] from buildDebugMeshes, + // which allocates and fills every array, and draw, which hands them to createStaticMesh. + class DebugMesh + { + public: + DebugMesh(); + void lockSize(); + + /* +0x00 */ int m_numberOfVertices; + /* +0x04 */ int m_numberOfPolygons; + /* +0x08 */ int m_numberOfIndices; + /* +0x0C */ unsigned int* m_firstIndices; // per polygon: where its indices start + /* +0x10 */ unsigned int* m_vertexCounts; // per polygon + /* +0x14 */ Vec3* m_vertices; + /* +0x18 */ unsigned int* m_indices; + /* +0x1C */ unsigned char* m_materials; // per polygon + /* +0x20 */ unsigned int* m_colours; // per polygon, the mesh's colour argument + /* +0x24 */ DrawPrimitive* m_mesh; // the static mesh handle while drawn + }; QuadTreeManager(); ~QuadTreeManager(); @@ -40,12 +56,12 @@ class QuadTreeManager void destroyQuadTrees(); void saveQuadTrees(const std::string&); void loadQuadTrees(const std::string&); - void loadGTSData(const std::string&, int, int, int, float); + bool loadGTSData(const std::string&, int, int, int, float); void recalculatePortalCosts(int); - void draw(); - void undraw(); + void draw() const; + void undraw() const; void drawCluster(); - void undrawCluster(); + void undrawCluster() const; void drawClusterNeighbourIndices(const Vec3&); void buildDebugMeshes(const std::string&); void buildDebugClusterMeshes(const std::string&); @@ -58,7 +74,7 @@ class QuadTreeManager unsigned int findPolygon(const Vec3&, unsigned int&, MaterialManager*, float); unsigned int findPolygon(const Vec3&, unsigned int&, unsigned int, unsigned int, MaterialManager*, float); - void printPolygonsInNode(const Vec3&, unsigned int&, MaterialManager *, float) const; + void printPolygonsInNode(const Vec3&, unsigned int&, MaterialManager *, float); unsigned short getCluster(unsigned int, unsigned int) const; void getClusterPortals(unsigned int, unsigned short, unsigned short, std::list&) const; void getPolygonsInRadius(std::list&, unsigned int, unsigned int, const Vec3&, float) const; @@ -68,15 +84,15 @@ class QuadTreeManager void restoreMapPart(int); void resetOriginalMaterialOfDestroyableMapPart(int); void resetDestroyableMapParts(); - void validateNeighbourRelations(); + void validateNeighbourRelations() const; // Offsets describe the original 32-byte ELF object; STL layouts vary by compiler. // One quad-tree/cluster-graph pointer pair per island; each original x86 pair is eight bytes. - /* +0 */ std::vector > m_islands; + /* +0 */ std::vector > m_quadTrees; // name: AIDLL_r asserts 0x10170D30, 0x10173C10 (PE +0, 8-byte entries) // Island count stored in the file, initialized by load or save. Runtime count queries - // use m_islands.size() instead; construction leaves this field unset. - /* +12 */ int m_numberOfIslands; + // use m_quadTrees.size() instead; construction leaves this field unset. + /* +12 */ int m_treeCount; // name: AIDLL_r assert 0x10173C10 (PE +0x10) /* +16 */ std::list m_debugMeshes; // node 12 /* +20 */ std::list m_debugClusterMeshes; // node 12 /* +24 */ std::list > m_drawnPairs; // node 16 [INFERRED] diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeNode.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeNode.cpp index 6fd190343..826089b4a 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeNode.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeNode.cpp @@ -1,16 +1,178 @@ -// [INFERRED] Source placement. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining QuadTreeNode operations. +// Navigation quad-tree node construction and polygon lookup. #include "QuadTreeNode.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x313300, __tcf_0 0x313360, _GLOBAL__I 0x313390). +#include + #include "QuadTree.h" #include "../Material/MaterialManager.h" +#include "../../../../../Math/Vec3.h" namespace dice { namespace hfe { namespace ai { -// A branch selects exactly one quadrant. Child index zero means absent; non-zero indices address +// ELF 0x312900. Retail iterates to the end and ignores the requested value. +void checkVector(const std::vector& values, unsigned int) +{ + for (std::vector::const_iterator i = values.begin(); i != values.end(); ++i) {} +} + +// ELF 0x312930. Reserves a branch before its children; empty children consume no node. +bool QuadTreeNode::create(QuadTree* tree, unsigned int& nodeCount, const Vec2& minimum, + float size, int depth, const std::vector& polygons, int count) +{ + static int maxPolygonCount = 20; // Original .data 0x4BF158. + bool leaf = depth == tree->m_maxDepthInTree; + std::vector children[4]; + if (depth < tree->m_gtsBuildValue) + leaf = false; + if (!leaf) + leaf = count <= tree->m_minPolygonsInLeaf; + int counts[4]; + if (!leaf) + { + const float half = size * 0.5f; + Vec2 childMinimum = minimum; + counts[0] = countPolygonsInside(polygons, tree, childMinimum, half, children[0]); + childMinimum.y += half; + counts[1] = countPolygonsInside(polygons, tree, childMinimum, half, children[1]); + childMinimum.x += half; + childMinimum.y -= half; + counts[2] = countPolygonsInside(polygons, tree, childMinimum, half, children[2]); + childMinimum.y += half; + counts[3] = countPolygonsInside(polygons, tree, childMinimum, half, children[3]); + if (static_cast(count) / + static_cast(counts[0] + counts[1] + counts[2] + counts[3]) < 0.5f && + count < maxPolygonCount) + leaf = true; + } + if (leaf) + { + if (count == 0) + return false; + ++nodeCount; + m_isLeaf = 1; + // shipped defect: the count narrows to a byte, while all supplied polygons are copied. + m_polygonCount = static_cast(count); + m_firstPolygon = static_cast(tree->m_vector18.size()); + for (int i = 0; i < count; ++i) + tree->m_vector18.push_back(polygons[i]); + return true; + } + + ++nodeCount; + const float half = size * 0.5f; + m_children[0] = nodeCount; + if (!tree->m_nodes[nodeCount].create(tree, nodeCount, minimum, half, depth + 1, + children[0], counts[0])) + m_children[0] = 0; + Vec2 childMinimum = {minimum.x, minimum.y + half}; + m_children[1] = nodeCount; + if (!tree->m_nodes[nodeCount].create(tree, nodeCount, childMinimum, half, depth + 1, + children[1], counts[1])) + m_children[1] = 0; + childMinimum.x += half; + childMinimum.y -= half; + m_children[2] = nodeCount; + if (!tree->m_nodes[nodeCount].create(tree, nodeCount, childMinimum, half, depth + 1, + children[2], counts[2])) + m_children[2] = 0; + childMinimum.y += half; + m_children[3] = nodeCount; + if (!tree->m_nodes[nodeCount].create(tree, nodeCount, childMinimum, half, depth + 1, + children[3], counts[3])) + m_children[3] = 0; + return true; +} + +// ELF 0x312850. Appends matches and returns the full resulting vector size. +int QuadTreeNode::countPolygonsInside(const std::vector& polygons, QuadTree* tree, + const Vec2& minimum, float size, std::vector& output) +{ + for (std::vector::const_iterator p = polygons.begin(); p != polygons.end(); ++p) + if (polygonInside(minimum, size, tree, *p)) + output.push_back(*p); + return static_cast(output.size()); +} + +// ELF 0x312480. Tests polygon vertices, square corners, then all projected edge pairs. +bool QuadTreeNode::polygonInside(const Vec2& minimum, float size, QuadTree* tree, + unsigned int polygon) +{ + const Vec3 square[4] = {{minimum.x, 0.0f, minimum.y}, + {minimum.x + size, 0.0f, minimum.y}, + {minimum.x + size, 0.0f, minimum.y + size}, + {minimum.x, 0.0f, minimum.y + size}}; + const Polygon* p = tree->m_polygons + polygon; + const int count = p->vertexCount; + for (int corner = 0; corner < count; ++corner) + { + const Vec3* v = tree->getVertexForPolygon(polygon, static_cast(corner)); + if (minimum.x <= v->x && v->x <= minimum.x + size && + minimum.y <= v->z && v->z <= minimum.y + size) + return true; + } + for (int corner = 0; corner < 4; ++corner) + { + bool inside = true; + for (int edge = 0; edge < count && inside; ++edge) + { + const Vec3* a = tree->getVertexForPolygon(polygon, static_cast(edge)); + const Vec3* b = tree->getSafeVertexForPolygon(polygon, + static_cast(edge + 1)); + const Vec3 direction = {b->x - a->x, 0.0f, b->z - a->z}; + const Vec3 offset = {square[corner].x - a->x, 0.0f, square[corner].z - a->z}; + const Vec3 cross = {0.0f * direction.z - offset.z * 0.0f, + offset.z * direction.x - direction.z * offset.x, + offset.x * 0.0f - direction.x * 0.0f}; + inside = cross.x * p->m_normal.x + cross.y * p->m_normal.y + + cross.z * p->m_normal.z < 0.0f; + } + if (inside) + return true; + } + for (int edge = 0; edge < count; ++edge) + { + Vec3 a = *tree->getVertexForPolygon(polygon, static_cast(edge)); + const Vec3* next = tree->getSafeVertexForPolygon(polygon, + static_cast(edge + 1)); + Vec3 b = {next->x, 0.0f, next->z}; + a.y = 0.0f; + for (int side = 0; side < 4; ++side) + if (lineSegmentIntersect(a, b, square[side], square[(side + 1) % 4])) + return true; + } + return false; +} + +// ELF 0x312420 (C2; C1 0x312440). The children are left unset. +QuadTreeNode::QuadTreeNode() + : m_isLeaf(0) + , m_polygonCount(0) + , m_firstPolygon(0) +{ +} + +// ELF 0x312460 (D2; D1 0x312470). +QuadTreeNode::~QuadTreeNode() +{ +} + +// ELF 0x3132C0. +QuadTreeNode& QuadTreeNode::operator=(const QuadTreeNode& other) +{ + for (int i = 0; i < 4; ++i) + m_children[i] = other.m_children[i]; + m_isLeaf = other.m_isLeaf; + m_polygonCount = other.m_polygonCount; + m_firstPolygon = other.m_firstPolygon; + return *this; +} + +// ELF 0x312DD0. A branch selects exactly one quadrant. Child index zero means absent; non-zero indices address // QuadTree::m_nodes directly. Equality belongs to the positive-X / positive-Z halves. // A leaf examines its byte-counted slice of m_nodePolygons. It rejects downward/vertical polygon // normals and negative material costs, then keeps the candidate with the smallest squared vertical @@ -97,6 +259,68 @@ bool QuadTreeNode::findPolygon(const QuadTree* tree, const Vec2& minimum, float return true; } +// ELF 0x313080. Descends like findPolygon (child index zero ends the walk); a leaf only reads +// each corner of its polygons through getVertexForPolygon. The child's minimum is the parent's +// plus a 0 / half offset per axis (the zero offsets are real additions in the listing), except +// for the first quadrant, which passes the parent's. +void QuadTreeNode::printPolygonsInNode(const QuadTree* tree, const Vec2& minimum, float size, + const Vec3& point, unsigned int& polygon, + MaterialManager* materials, float allowedHeightDiff) const +{ + if (m_isLeaf) + { + const unsigned char count = m_polygonCount; + for (int i = 0; i < count; ++i) + { + const unsigned int candidate = tree->m_nodePolygons[m_firstPolygon + i]; + const Polygon& candidatePolygon = tree->m_polygons[candidate]; + for (int corner = 0; corner < candidatePolygon.vertexCount; ++corner) + tree->getVertexForPolygon(candidate, static_cast(corner)); + } + return; + } + + const float half = size * 0.5f; + Vec2 childMinimum; + const Vec2* next = &childMinimum; + unsigned int child; + + if (minimum.x + half > point.x) + { + if (minimum.y + half > point.z) + { + child = m_children[0]; + next = &minimum; + } + else + { + child = m_children[1]; + childMinimum.x = minimum.x + 0.0f; + childMinimum.y = minimum.y + half; + } + } + else + { + childMinimum.x = minimum.x + half; + if (minimum.y + half > point.z) + { + child = m_children[2]; + childMinimum.y = minimum.y + 0.0f; + } + else + { + child = m_children[3]; + childMinimum.y = minimum.y + half; + } + } + + if (!child) + return; + + tree->m_nodes[child].printPolygonsInNode(tree, *next, half, point, polygon, materials, + allowedHeightDiff); +} + } // namespace ai } // namespace hfe } // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeNode.h b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeNode.h index f2f80187d..340e5f466 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeNode.h +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeNode.h @@ -1,12 +1,11 @@ // Navigation quad-tree node. File loading initializes its stored data. -// [FRONTIER] Generation and debug queries remain incomplete. -// [INFERRED] Source placement. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining QuadTreeNode operations. +// Generation subdivides the navigation polygons during QuadTree::buildQuadTree. #ifndef AI_AIDLL_AI_AIPATHFINDING_NAVMESH_QUADTREENODE_H #define AI_AIDLL_AI_AIPATHFINDING_NAVMESH_QUADTREENODE_H #include "../../Main/AIDllTypes.h" +#include namespace dice { namespace hfe { @@ -18,11 +17,24 @@ class QuadTree; class QuadTreeNode { public: - QuadTreeNode() : m_isLeaf(0), m_polygonCount(0), m_firstPolygon(0) {} - ~QuadTreeNode() {} // empty + QuadTreeNode(); + ~QuadTreeNode(); + + // Copies the children, the leaf flag, the count and the first index; the two bytes at +0x12 + // are not copied. + QuadTreeNode& operator=(const QuadTreeNode& other); + bool create(QuadTree*, unsigned int&, const Vec2&, float, int, + const std::vector&, int); + bool polygonInside(const Vec2&, float, QuadTree*, unsigned int); + int countPolygonsInside(const std::vector&, QuadTree*, const Vec2&, float, + std::vector&); bool findPolygon(const QuadTree*, const Vec2&, float, const Vec3&, unsigned int&, MaterialManager*, float) const; + // The debug twin of findPolygon: descends the same way and reads every corner of the leaf's + // polygons without printing or returning anything. + void printPolygonsInNode(const QuadTree*, const Vec2&, float, const Vec3&, unsigned int&, + MaterialManager*, float) const; // A branch stores four node-array indices, with zero meaning "no child". A leaf instead uses // the byte count and first index to address QuadTree::m_nodePolygons. The two bytes at +0x12 diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPContext.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPContext.h index 2484ce080..afdf47960 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPContext.h +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPContext.h @@ -24,6 +24,12 @@ class BAPContext ~BAPContext(); // - , and it leaks; see above void clear(); + // [CHOSEN, not recovered] added by ai-w1-e-fire (coord/ai-requests.md 2026-11-01); the owner may + // rename it. Every plan variable the fire patterns create is put at the front of the list: + // BBPFireInfantery::createPlanInternal calls `std::list::insert(begin(), &v)` + // right after each inlined BAPVariable construction (0x2654C6, 0x265547, ... 0x27127A). + void addVariable(BotScriptVariable* variable) { m_variables.insert(m_variables.begin(), variable); } + private: /* 0 */ std::list m_variables; // the whole object }; diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPDebugger.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPDebugger.cpp new file mode 100644 index 000000000..dc8799369 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPDebugger.cpp @@ -0,0 +1,159 @@ +// Bot-script debugger: per-statement debug levels for two debug places and a statement stack. +// Evidence: libaidll.so (ia-32) 0x2A83E0..0x2A90DF and 0x2A95D0. Placement attested by the __FILE__ +// string "AI/AIDLL/AI/AIPlanInterpreter/BAPDebugger.cpp". + +// static init: ELF 0x2A9030 (__tcf_0 0x2A9090, _GLOBAL__I 0x2A90C0): 's Init object only. +#include + +#include "BAPDebugger.h" + +#include +#include + +#include "../../../../Core/Debug.h" +#include "../AIBotActionPlan/BAPStatement.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2A8560 (C1; C2 0x2A83E0). +BAPDebugger::BAPDebugger() + : m_debugLevel(static_cast(3)) +{ +} + +// ELF 0x2A8720 (D1; D2 0x2A8620, D0 0x2A8820). The members are destroyed in reverse order. +BAPDebugger::~BAPDebugger() +{ +} + +// ELF 0x2A8930. Place 0 uses the first map, place 1 the second; any other place does nothing. +void BAPDebugger::debug(BotScriptDebugger::DebugLevel level, BotScript* script, + BotScriptDebugger::DebugPlace place, int value) +{ + switch (place) + { + case 0: + internalDebug(level, script, value, m_placeZeroStatements); + break; + case 1: + internalDebug(level, script, value, m_placeOneStatements); + break; + default: + break; + } +} + +// ELF 0x2A8C90. +void BAPDebugger::clear() +{ + clearDebugStatement(); + clearStack(); +} + +// ELF 0x2A95D0. +int BAPDebugger::getImplementation() +{ + return 1; +} + +// ELF 0x2A89B0. Same place dispatch as debug(). +void BAPDebugger::addDebugStatement(BotScriptDebugger::DebugLevel level, BAPStatement* statement, + BotScriptDebugger::DebugPlace place, int value) +{ + switch (place) + { + case 0: + internalAddStatement(level, statement, value, m_placeZeroStatements); + break; + case 1: + internalAddStatement(level, statement, value, m_placeOneStatements); + break; + default: + break; + } +} + +// ELF 0x2A8A30. +void BAPDebugger::clearDebugStatement() +{ + m_placeZeroStatements.clear(); + m_placeOneStatements.clear(); +} + +// ELF 0x2A8AE0. +void BAPDebugger::pushStatement(BAPStatement* statement) +{ + m_stack.insert(m_stack.begin(), statement); +} + +// ELF 0x2A8B30. Answers 0 on an empty stack (counted with size()). When the back is not the +// statement, it is searched from the front; the search result is dereferenced even when it is +// end() (shipped defect). On a match the back is popped, not the matching element (shipped). +int BAPDebugger::popStatement(BAPStatement* statement) +{ + if (m_stack.size() == 0) + return 0; + if (m_stack.back() != statement) + { + if (*std::find(m_stack.begin(), m_stack.end(), statement) != statement) + return 0; + } + m_stack.pop_back(); + return 1; +} + +// ELF 0x2A8C70. +void BAPDebugger::setDebugLevel(BotScriptDebugger::DebugLevel level) +{ + m_debugLevel = level; +} + +// ELF 0x2A8C80. +int BAPDebugger::getDebugLevel() +{ + return m_debugLevel; +} + +// ELF 0x2A8CD0. +void BAPDebugger::clearStack() +{ + m_stack.clear(); +} + +// ELF 0x2A8D00. A registered statement whose value filter is -1 or matches prints itself at the +// lowest of the requested, registered and debugger levels; level 2 output goes to the error log. +void BAPDebugger::internalDebug(BotScriptDebugger::DebugLevel level, BotScript* script, int value, + std::map >& statements) +{ + std::string text; + BAPStatement* statement = static_cast(script); + StatementMap::iterator found = statements.find(statement); + if (found == statements.end()) + return; + if (found->second.second != -1 && found->second.second != value) + return; + BotScriptDebugger::DebugLevel effective = level; + if (found->second.first <= level) + effective = found->second.first; + if (effective > m_debugLevel) + effective = m_debugLevel; + statement->debug(effective, text); + if (effective == 2) + Debug(DebugTypeError, "AI/AIDLL/AI/AIPlanInterpreter/BAPDebugger.cpp", 248, "") << text; +} + +// ELF 0x2A8F00. Registers a statement once; an existing entry is left unchanged. +void BAPDebugger::internalAddStatement(BotScriptDebugger::DebugLevel level, BAPStatement* statement, + int value, + std::map >& statements) +{ + if (statements.find(statement) != statements.end()) + return; + statements[statement] = std::make_pair(level, value); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPDebugger.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPDebugger.h new file mode 100644 index 000000000..5d71bd237 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPDebugger.h @@ -0,0 +1,58 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_BAPDEBUGGER_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_BAPDEBUGGER_H + +#include +#include +#include +#include "BotScriptDebugger.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPStatement; +class BotScript; + +// ELF: vtable 0x4BC9C8 (5 words), package H-deferred. +// sizeof == 0x24 on ia-32. Data members from the constructor (0x2A83E0) and the bodies below; +// names [INFERRED]. +class BAPDebugger : public BotScriptDebugger +{ +public: + BAPDebugger(); // 0x2A8560 + virtual ~BAPDebugger(); // 0x2A8720 + + virtual void debug(BotScriptDebugger::DebugLevel, BotScript*, BotScriptDebugger::DebugPlace, int); // 0x2A8930, slot +0x08; from the base declaration + virtual void clear(); // 0x2A8C90, slot +0x0C; from the base declaration + virtual int getImplementation(); // 0x2A95D0, slot +0x10; from the base declaration + + void addDebugStatement(BotScriptDebugger::DebugLevel, BAPStatement*, BotScriptDebugger::DebugPlace, int); // 0x2A89B0; [INFERRED] ELF void + void clearDebugStatement(); // 0x2A8A30; [INFERRED] ELF void + void pushStatement(BAPStatement*); // 0x2A8AE0; [INFERRED] ELF void + int popStatement(BAPStatement*); // 0x2A8B30; [INFERRED] ELF int + void setDebugLevel(BotScriptDebugger::DebugLevel); // 0x2A8C70; [INFERRED] void: only stores (no callers) + int getDebugLevel(); // 0x2A8C80; [INFERRED] ELF int + void clearStack(); // 0x2A8CD0; [INFERRED] ELF void + void internalDebug(BotScriptDebugger::DebugLevel, BotScript*, int, std::map >&); // 0x2A8D00; [INFERRED] ELF void + void internalAddStatement(BotScriptDebugger::DebugLevel, BAPStatement*, int, std::map >&); // 0x2A8F00; [INFERRED] ELF void + +private: + typedef std::map > StatementMap; + /* +0x04 */ StatementMap m_placeZeroStatements; // DebugPlace 0 + /* +0x10 */ StatementMap m_placeOneStatements; // DebugPlace 1 + /* +0x1C */ std::list m_stack; // pushStatement prepends, popStatement pops the back + /* +0x20 */ BotScriptDebugger::DebugLevel m_debugLevel; // = 3 +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_BAPDEBUGGER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPEntries.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPEntries.cpp deleted file mode 100644 index e8963a53a..000000000 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPEntries.cpp +++ /dev/null @@ -1,826 +0,0 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining BAPEntries operations. - -#include "BAPEntries.h" - -#include "../Main/AIDllFrontier.h" - -namespace dice { -namespace hfe { -namespace ai { - -// Action-plan primitives return their statement type for registry dispatch. - -// Empty body; see BAPEntry.h. -BAPEntry::~BAPEntry() -{ -} - -EntryTankMoveTo::EntryTankMoveTo() -{ -} - -EntryTankMoveTo::~EntryTankMoveTo() -{ -} - -int EntryTankMoveTo::getTargetId() -{ - return 7; -} - -bool EntryTankMoveTo::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryTankMoveTo::execute"); -} - - -EntryTankMoveToObject::EntryTankMoveToObject() -{ -} - -EntryTankMoveToObject::~EntryTankMoveToObject() -{ -} - -int EntryTankMoveToObject::getTargetId() -{ - return 9; -} - -bool EntryTankMoveToObject::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryTankMoveToObject::execute"); -} - - -EntryTankMoveToDirection::EntryTankMoveToDirection() -{ -} - -EntryTankMoveToDirection::~EntryTankMoveToDirection() -{ -} - -int EntryTankMoveToDirection::getTargetId() -{ - return 8; -} - -bool EntryTankMoveToDirection::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryTankMoveToDirection::execute"); -} - - -EntryTankResetControls::EntryTankResetControls() -{ -} - -EntryTankResetControls::~EntryTankResetControls() -{ -} - -int EntryTankResetControls::getTargetId() -{ - return 14; -} - -bool EntryTankResetControls::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryTankResetControls::execute"); -} - - -EntryTankTurnTo::EntryTankTurnTo() -{ -} - -EntryTankTurnTo::~EntryTankTurnTo() -{ -} - -int EntryTankTurnTo::getTargetId() -{ - return 24; -} - -bool EntryTankTurnTo::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryTankTurnTo::execute"); -} - -void EntryTankTurnTo::getCentreOfFacingSide(const Vec2&, const Vec2&, const Vec2&, - const Vec2&, Vec2&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryTankTurnTo::getCentreOfFacingSide"); -} - - -EntryCarMoveTo::EntryCarMoveTo() -{ -} - -EntryCarMoveTo::~EntryCarMoveTo() -{ -} - -int EntryCarMoveTo::getTargetId() -{ - return 7; -} - -bool EntryCarMoveTo::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryCarMoveTo::execute"); -} - - -EntryCarMoveToDirection::EntryCarMoveToDirection() -{ -} - -EntryCarMoveToDirection::~EntryCarMoveToDirection() -{ -} - -int EntryCarMoveToDirection::getTargetId() -{ - return 8; -} - -// A retail stub - see the block above. , and all it does is succeed. -bool EntryCarMoveToDirection::execute(BotScript *, Bot *, bool&, bool&) -{ - return true; -} - - -EntryCarMoveToObject::EntryCarMoveToObject() -{ -} - -EntryCarMoveToObject::~EntryCarMoveToObject() -{ -} - -int EntryCarMoveToObject::getTargetId() -{ - return 9; -} - -bool EntryCarMoveToObject::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryCarMoveToObject::execute"); -} - - -EntryCarResetControls::EntryCarResetControls() -{ -} - -EntryCarResetControls::~EntryCarResetControls() -{ -} - -int EntryCarResetControls::getTargetId() -{ - return 14; -} - -bool EntryCarResetControls::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryCarResetControls::execute"); -} - - -EntryPlaneMoveTo::EntryPlaneMoveTo() -{ -} - -EntryPlaneMoveTo::~EntryPlaneMoveTo() -{ -} - -int EntryPlaneMoveTo::getTargetId() -{ - return 7; -} - -bool EntryPlaneMoveTo::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryPlaneMoveTo::execute"); -} - - -EntryPlaneMoveToDirection::EntryPlaneMoveToDirection() -{ -} - -EntryPlaneMoveToDirection::~EntryPlaneMoveToDirection() -{ -} - -int EntryPlaneMoveToDirection::getTargetId() -{ - return 8; -} - -bool EntryPlaneMoveToDirection::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryPlaneMoveToDirection::execute"); -} - - -EntryPlaneMoveToObject::EntryPlaneMoveToObject() -{ -} - -EntryPlaneMoveToObject::~EntryPlaneMoveToObject() -{ -} - -int EntryPlaneMoveToObject::getTargetId() -{ - return 9; -} - -bool EntryPlaneMoveToObject::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryPlaneMoveToObject::execute"); -} - - -EntryPlaneAimAt::EntryPlaneAimAt() -{ -} - -EntryPlaneAimAt::~EntryPlaneAimAt() -{ -} - -int EntryPlaneAimAt::getTargetId() -{ - return 6; -} - -bool EntryPlaneAimAt::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryPlaneAimAt::execute"); -} - - -EntryPlaneResetControls::EntryPlaneResetControls() -{ -} - -EntryPlaneResetControls::~EntryPlaneResetControls() -{ -} - -int EntryPlaneResetControls::getTargetId() -{ - return 14; -} - -bool EntryPlaneResetControls::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryPlaneResetControls::execute"); -} - - -EntryBoatMoveTo::EntryBoatMoveTo() -{ -} - -EntryBoatMoveTo::~EntryBoatMoveTo() -{ -} - -int EntryBoatMoveTo::getTargetId() -{ - return 7; -} - -bool EntryBoatMoveTo::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryBoatMoveTo::execute"); -} - - -EntryBoatMoveToObject::EntryBoatMoveToObject() -{ -} - -EntryBoatMoveToObject::~EntryBoatMoveToObject() -{ -} - -int EntryBoatMoveToObject::getTargetId() -{ - return 9; -} - -bool EntryBoatMoveToObject::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryBoatMoveToObject::execute"); -} - - -EntryBoatMoveToDirection::EntryBoatMoveToDirection() -{ -} - -EntryBoatMoveToDirection::~EntryBoatMoveToDirection() -{ -} - -int EntryBoatMoveToDirection::getTargetId() -{ - return 8; -} - -bool EntryBoatMoveToDirection::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryBoatMoveToDirection::execute"); -} - - -EntryBoatResetControls::EntryBoatResetControls() -{ -} - -EntryBoatResetControls::~EntryBoatResetControls() -{ -} - -int EntryBoatResetControls::getTargetId() -{ - return 14; -} - -bool EntryBoatResetControls::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryBoatResetControls::execute"); -} - - -EntryInfanteryMoveTo::EntryInfanteryMoveTo() -{ -} - -EntryInfanteryMoveTo::~EntryInfanteryMoveTo() -{ -} - -int EntryInfanteryMoveTo::getTargetId() -{ - return 7; -} - -bool EntryInfanteryMoveTo::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryInfanteryMoveTo::execute"); -} - - -EntryInfanteryMoveToObject::EntryInfanteryMoveToObject() -{ -} - -EntryInfanteryMoveToObject::~EntryInfanteryMoveToObject() -{ -} - -int EntryInfanteryMoveToObject::getTargetId() -{ - return 9; -} - -bool EntryInfanteryMoveToObject::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryInfanteryMoveToObject::execute"); -} - - -EntryInfanteryMoveToDirection::EntryInfanteryMoveToDirection() -{ -} - -EntryInfanteryMoveToDirection::~EntryInfanteryMoveToDirection() -{ -} - -int EntryInfanteryMoveToDirection::getTargetId() -{ - return 8; -} - -// A retail stub - see the block above. , and all it does is succeed. -bool EntryInfanteryMoveToDirection::execute(BotScript *, Bot *, bool&, bool&) -{ - return true; -} - - -EntryInfanteryResetControls::EntryInfanteryResetControls() -{ -} - -EntryInfanteryResetControls::~EntryInfanteryResetControls() -{ -} - -int EntryInfanteryResetControls::getTargetId() -{ - return 14; -} - -bool EntryInfanteryResetControls::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryInfanteryResetControls::execute"); -} - - -EntryTrigger::EntryTrigger() -{ -} - -EntryTrigger::~EntryTrigger() -{ -} - -int EntryTrigger::getTargetId() -{ - return 11; -} - -bool EntryTrigger::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryTrigger::execute"); -} - - -EntryTriggerContinously::EntryTriggerContinously() -{ -} - -EntryTriggerContinously::~EntryTriggerContinously() -{ -} - -int EntryTriggerContinously::getTargetId() -{ - return 12; -} - -bool EntryTriggerContinously::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryTriggerContinously::execute"); -} - - -EntryKeyTurretAimAt::EntryKeyTurretAimAt() -{ -} - -EntryKeyTurretAimAt::~EntryKeyTurretAimAt() -{ -} - -int EntryKeyTurretAimAt::getTargetId() -{ - return 6; -} - -bool EntryKeyTurretAimAt::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryKeyTurretAimAt::execute"); -} - - -EntryMouseTurretAimAt::EntryMouseTurretAimAt() -{ -} - -EntryMouseTurretAimAt::~EntryMouseTurretAimAt() -{ -} - -int EntryMouseTurretAimAt::getTargetId() -{ - return 6; -} - -bool EntryMouseTurretAimAt::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryMouseTurretAimAt::execute"); -} - - -EntryMouseTurretLookAt::EntryMouseTurretLookAt() -{ -} - -EntryMouseTurretLookAt::~EntryMouseTurretLookAt() -{ -} - -int EntryMouseTurretLookAt::getTargetId() -{ - return 23; -} - -bool EntryMouseTurretLookAt::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryMouseTurretLookAt::execute"); -} - - -EntrySense::EntrySense() -{ -} - -EntrySense::~EntrySense() -{ -} - -int EntrySense::getTargetId() -{ - return 20; -} - -bool EntrySense::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntrySense::execute"); -} - - -EntrySoldierPose::EntrySoldierPose() -{ -} - -EntrySoldierPose::~EntrySoldierPose() -{ -} - -int EntrySoldierPose::getTargetId() -{ - return 26; -} - -bool EntrySoldierPose::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntrySoldierPose::execute"); -} - - -EntryMoveToMedium::EntryMoveToMedium() -{ -} - -EntryMoveToMedium::~EntryMoveToMedium() -{ -} - -int EntryMoveToMedium::getTargetId() -{ - return 7; -} - -bool EntryMoveToMedium::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryMoveToMedium::execute"); -} - - -EntryMoveToMediumBoat::EntryMoveToMediumBoat() -{ -} - -EntryMoveToMediumBoat::~EntryMoveToMediumBoat() -{ -} - -int EntryMoveToMediumBoat::getTargetId() -{ - return 7; -} - -bool EntryMoveToMediumBoat::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryMoveToMediumBoat::execute"); -} - - -EntryMoveToMediumSoldier::EntryMoveToMediumSoldier() -{ -} - -EntryMoveToMediumSoldier::~EntryMoveToMediumSoldier() -{ -} - -int EntryMoveToMediumSoldier::getTargetId() -{ - return 7; -} - -bool EntryMoveToMediumSoldier::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryMoveToMediumSoldier::execute"); -} - - -EntryMoveToObjectMedium::EntryMoveToObjectMedium() -{ -} - -EntryMoveToObjectMedium::~EntryMoveToObjectMedium() -{ -} - -int EntryMoveToObjectMedium::getTargetId() -{ - return 9; -} - -bool EntryMoveToObjectMedium::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryMoveToObjectMedium::execute"); -} - - -EntryMoveToObjectMediumBoat::EntryMoveToObjectMediumBoat() -{ -} - -EntryMoveToObjectMediumBoat::~EntryMoveToObjectMediumBoat() -{ -} - -int EntryMoveToObjectMediumBoat::getTargetId() -{ - return 9; -} - -bool EntryMoveToObjectMediumBoat::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryMoveToObjectMediumBoat::execute"); -} - - -EntryMoveToObjectMediumSoldier::EntryMoveToObjectMediumSoldier() -{ -} - -EntryMoveToObjectMediumSoldier::~EntryMoveToObjectMediumSoldier() -{ -} - -int EntryMoveToObjectMediumSoldier::getTargetId() -{ - return 9; -} - -bool EntryMoveToObjectMediumSoldier::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryMoveToObjectMediumSoldier::execute"); -} - - -EntryInfoWrapper::EntryInfoWrapper() -{ -} - -EntryInfoWrapper::~EntryInfoWrapper() -{ -} - -int EntryInfoWrapper::getTargetId() -{ - return 15; -} - -bool EntryInfoWrapper::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryInfoWrapper::execute"); -} - - -EntryHeliMoveTo::EntryHeliMoveTo() -{ -} - -EntryHeliMoveTo::~EntryHeliMoveTo() -{ -} - -int EntryHeliMoveTo::getTargetId() -{ - return 7; -} - -bool EntryHeliMoveTo::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryHeliMoveTo::execute"); -} - - -EntryHeliMoveToDirection::EntryHeliMoveToDirection() -{ -} - -EntryHeliMoveToDirection::~EntryHeliMoveToDirection() -{ -} - -int EntryHeliMoveToDirection::getTargetId() -{ - return 8; -} - -bool EntryHeliMoveToDirection::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryHeliMoveToDirection::execute"); -} - - -EntryHeliMoveToObject::EntryHeliMoveToObject() -{ -} - -EntryHeliMoveToObject::~EntryHeliMoveToObject() -{ -} - -int EntryHeliMoveToObject::getTargetId() -{ - return 9; -} - -bool EntryHeliMoveToObject::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryHeliMoveToObject::execute"); -} - - -EntryHeliAimAt::EntryHeliAimAt() -{ -} - -EntryHeliAimAt::~EntryHeliAimAt() -{ -} - -int EntryHeliAimAt::getTargetId() -{ - return 6; -} - -bool EntryHeliAimAt::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryHeliAimAt::execute"); -} - - -EntryHeliResetControls::EntryHeliResetControls() -{ -} - -EntryHeliResetControls::~EntryHeliResetControls() -{ -} - -int EntryHeliResetControls::getTargetId() -{ - return 14; -} - -bool EntryHeliResetControls::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryHeliResetControls::execute"); -} - - -EntryHeliMoveAwayFromObject::EntryHeliMoveAwayFromObject() -{ -} - -EntryHeliMoveAwayFromObject::~EntryHeliMoveAwayFromObject() -{ -} - -int EntryHeliMoveAwayFromObject::getTargetId() -{ - return 10; -} - -bool EntryHeliMoveAwayFromObject::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryHeliMoveAwayFromObject::execute"); -} - - -} // namespace ai -} // namespace hfe -} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPEntries.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPEntries.h index d3d7ce0e2..acc4b1023 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPEntries.h +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPEntries.h @@ -1,487 +1,53 @@ -// Vehicle-specific action-plan primitives registered by statement type. +// The 44 vehicle-specific action-plan entries (one TU each in the image: Entry*.cpp). // Keep registry spellings such as Infantery and TriggerContinously unchanged. -// [CHOSEN, not recovered] These entries are grouped into one translation unit. -// [FRONTIER] Remaining execute methods stop by name. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execution, then split entries into their own files. +// S0 split the former single TU into the attested files; this header only gathers them. #ifndef AI_AIDLL_AI_AIPLANINTERPRETER_BAPENTRIES_H #define AI_AIDLL_AI_AIPLANINTERPRETER_BAPENTRIES_H -#include "BAPEntry.h" - -namespace dice { -namespace hfe { -namespace ai { - - -// EntryTankMoveTo - statement type 7. -class EntryTankMoveTo : public BAPEntry -{ -public: - EntryTankMoveTo(); - virtual ~EntryTankMoveTo(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryTankMoveToObject - statement type 9. -class EntryTankMoveToObject : public BAPEntry -{ -public: - EntryTankMoveToObject(); - virtual ~EntryTankMoveToObject(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryTankMoveToDirection - statement type 8. -class EntryTankMoveToDirection : public BAPEntry -{ -public: - EntryTankMoveToDirection(); - virtual ~EntryTankMoveToDirection(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryTankResetControls - statement type 14. -class EntryTankResetControls : public BAPEntry -{ -public: - EntryTankResetControls(); - virtual ~EntryTankResetControls(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryTankTurnTo - statement type 24. -class EntryTankTurnTo : public BAPEntry -{ -public: - EntryTankTurnTo(); - virtual ~EntryTankTurnTo(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); - // Everything else on these - // forty-two classes is the four slots below. - void getCentreOfFacingSide(const Vec2&, const Vec2&, const Vec2&, const Vec2&, Vec2&); -}; - -// EntryCarMoveTo - statement type 7. -class EntryCarMoveTo : public BAPEntry -{ -public: - EntryCarMoveTo(); - virtual ~EntryCarMoveTo(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryCarMoveToDirection - statement type 8. -class EntryCarMoveToDirection : public BAPEntry -{ -public: - EntryCarMoveToDirection(); - virtual ~EntryCarMoveToDirection(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryCarMoveToObject - statement type 9. -class EntryCarMoveToObject : public BAPEntry -{ -public: - EntryCarMoveToObject(); - virtual ~EntryCarMoveToObject(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryCarResetControls - statement type 14. -class EntryCarResetControls : public BAPEntry -{ -public: - EntryCarResetControls(); - virtual ~EntryCarResetControls(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryPlaneMoveTo - statement type 7. -class EntryPlaneMoveTo : public BAPEntry -{ -public: - EntryPlaneMoveTo(); - virtual ~EntryPlaneMoveTo(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryPlaneMoveToDirection - statement type 8. -class EntryPlaneMoveToDirection : public BAPEntry -{ -public: - EntryPlaneMoveToDirection(); - virtual ~EntryPlaneMoveToDirection(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryPlaneMoveToObject - statement type 9. -class EntryPlaneMoveToObject : public BAPEntry -{ -public: - EntryPlaneMoveToObject(); - virtual ~EntryPlaneMoveToObject(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryPlaneAimAt - statement type 6. -class EntryPlaneAimAt : public BAPEntry -{ -public: - EntryPlaneAimAt(); - virtual ~EntryPlaneAimAt(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryPlaneResetControls - statement type 14. -class EntryPlaneResetControls : public BAPEntry -{ -public: - EntryPlaneResetControls(); - virtual ~EntryPlaneResetControls(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryBoatMoveTo - statement type 7. -class EntryBoatMoveTo : public BAPEntry -{ -public: - EntryBoatMoveTo(); - virtual ~EntryBoatMoveTo(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryBoatMoveToObject - statement type 9. -class EntryBoatMoveToObject : public BAPEntry -{ -public: - EntryBoatMoveToObject(); - virtual ~EntryBoatMoveToObject(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryBoatMoveToDirection - statement type 8. -class EntryBoatMoveToDirection : public BAPEntry -{ -public: - EntryBoatMoveToDirection(); - virtual ~EntryBoatMoveToDirection(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryBoatResetControls - statement type 14. -class EntryBoatResetControls : public BAPEntry -{ -public: - EntryBoatResetControls(); - virtual ~EntryBoatResetControls(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryInfanteryMoveTo - statement type 7. -class EntryInfanteryMoveTo : public BAPEntry -{ -public: - EntryInfanteryMoveTo(); - virtual ~EntryInfanteryMoveTo(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryInfanteryMoveToObject - statement type 9. -class EntryInfanteryMoveToObject : public BAPEntry -{ -public: - EntryInfanteryMoveToObject(); - virtual ~EntryInfanteryMoveToObject(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryInfanteryMoveToDirection - statement type 8. -class EntryInfanteryMoveToDirection : public BAPEntry -{ -public: - EntryInfanteryMoveToDirection(); - virtual ~EntryInfanteryMoveToDirection(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryInfanteryResetControls - statement type 14. -class EntryInfanteryResetControls : public BAPEntry -{ -public: - EntryInfanteryResetControls(); - virtual ~EntryInfanteryResetControls(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryTrigger - statement type 11. -class EntryTrigger : public BAPEntry -{ -public: - EntryTrigger(); - virtual ~EntryTrigger(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryTriggerContinously - statement type 12. -class EntryTriggerContinously : public BAPEntry -{ -public: - EntryTriggerContinously(); - virtual ~EntryTriggerContinously(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryKeyTurretAimAt - statement type 6. -class EntryKeyTurretAimAt : public BAPEntry -{ -public: - EntryKeyTurretAimAt(); - virtual ~EntryKeyTurretAimAt(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryMouseTurretAimAt - statement type 6. -class EntryMouseTurretAimAt : public BAPEntry -{ -public: - EntryMouseTurretAimAt(); - virtual ~EntryMouseTurretAimAt(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryMouseTurretLookAt - statement type 23. -class EntryMouseTurretLookAt : public BAPEntry -{ -public: - EntryMouseTurretLookAt(); - virtual ~EntryMouseTurretLookAt(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntrySense - statement type 20. -class EntrySense : public BAPEntry -{ -public: - EntrySense(); - virtual ~EntrySense(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntrySoldierPose - statement type 26. -class EntrySoldierPose : public BAPEntry -{ -public: - EntrySoldierPose(); - virtual ~EntrySoldierPose(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryMoveToMedium - statement type 7. -class EntryMoveToMedium : public BAPEntry -{ -public: - EntryMoveToMedium(); - virtual ~EntryMoveToMedium(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryMoveToMediumBoat - statement type 7. -class EntryMoveToMediumBoat : public BAPEntry -{ -public: - EntryMoveToMediumBoat(); - virtual ~EntryMoveToMediumBoat(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryMoveToMediumSoldier - statement type 7. -class EntryMoveToMediumSoldier : public BAPEntry -{ -public: - EntryMoveToMediumSoldier(); - virtual ~EntryMoveToMediumSoldier(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryMoveToObjectMedium - statement type 9. -class EntryMoveToObjectMedium : public BAPEntry -{ -public: - EntryMoveToObjectMedium(); - virtual ~EntryMoveToObjectMedium(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryMoveToObjectMediumBoat - statement type 9. -class EntryMoveToObjectMediumBoat : public BAPEntry -{ -public: - EntryMoveToObjectMediumBoat(); - virtual ~EntryMoveToObjectMediumBoat(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryMoveToObjectMediumSoldier - statement type 9. -class EntryMoveToObjectMediumSoldier : public BAPEntry -{ -public: - EntryMoveToObjectMediumSoldier(); - virtual ~EntryMoveToObjectMediumSoldier(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryInfoWrapper - statement type 15. -class EntryInfoWrapper : public BAPEntry -{ -public: - EntryInfoWrapper(); - virtual ~EntryInfoWrapper(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryHeliMoveTo - statement type 7. -class EntryHeliMoveTo : public BAPEntry -{ -public: - EntryHeliMoveTo(); - virtual ~EntryHeliMoveTo(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryHeliMoveToDirection - statement type 8. -class EntryHeliMoveToDirection : public BAPEntry -{ -public: - EntryHeliMoveToDirection(); - virtual ~EntryHeliMoveToDirection(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryHeliMoveToObject - statement type 9. -class EntryHeliMoveToObject : public BAPEntry -{ -public: - EntryHeliMoveToObject(); - virtual ~EntryHeliMoveToObject(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryHeliAimAt - statement type 6. -class EntryHeliAimAt : public BAPEntry -{ -public: - EntryHeliAimAt(); - virtual ~EntryHeliAimAt(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryHeliResetControls - statement type 14. -class EntryHeliResetControls : public BAPEntry -{ -public: - EntryHeliResetControls(); - virtual ~EntryHeliResetControls(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryHeliMoveAwayFromObject - statement type 10. -class EntryHeliMoveAwayFromObject : public BAPEntry -{ -public: - EntryHeliMoveAwayFromObject(); - virtual ~EntryHeliMoveAwayFromObject(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - - -} // namespace ai -} // namespace hfe -} // namespace dice +#include "EntryBoatMoveTo.h" +#include "EntryBoatMoveToDirection.h" +#include "EntryBoatMoveToObject.h" +#include "EntryBoatResetControls.h" +#include "EntryCarMoveTo.h" +#include "EntryCarMoveToDirection.h" +#include "EntryCarMoveToObject.h" +#include "EntryCarResetControls.h" +#include "EntryHeliAimAt.h" +#include "EntryHeliMoveAwayFromObject.h" +#include "EntryHeliMoveTo.h" +#include "EntryHeliMoveToDirection.h" +#include "EntryHeliMoveToObject.h" +#include "EntryHeliResetControls.h" +#include "EntryInfanteryMoveTo.h" +#include "EntryInfanteryMoveToDirection.h" +#include "EntryInfanteryMoveToObject.h" +#include "EntryInfanteryResetControls.h" +#include "EntryInfoWrapper.h" +#include "EntryKeyTurretAimAt.h" +#include "EntryMouseTurretAimAt.h" +#include "EntryMouseTurretLookAt.h" +#include "EntryMoveToMedium.h" +#include "EntryMoveToMediumBoat.h" +#include "EntryMoveToMediumSoldier.h" +#include "EntryMoveToObjectMedium.h" +#include "EntryMoveToObjectMediumBoat.h" +#include "EntryMoveToObjectMediumSoldier.h" +#include "EntryPlaneAimAt.h" +#include "EntryPlaneMoveTo.h" +#include "EntryPlaneMoveToDirection.h" +#include "EntryPlaneMoveToObject.h" +#include "EntryPlaneResetControls.h" +#include "EntryPlaneRoll.h" +#include "EntrySense.h" +#include "EntrySoldierPose.h" +#include "EntryTankMoveTo.h" +#include "EntryTankMoveToDirection.h" +#include "EntryTankMoveToObject.h" +#include "EntryTankResetControls.h" +#include "EntryTankTurnTo.h" +#include "EntryTrigger.h" +#include "EntryTriggerContinously.h" +#include "EntryTurnToMedium.h" #endif // AI_AIDLL_AI_AIPLANINTERPRETER_BAPENTRIES_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPEntry.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPEntry.h index f7b2d5579..b9de11552 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPEntry.h +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPEntry.h @@ -16,7 +16,7 @@ class BAPEntry { public: BAPEntry() {} - virtual ~BAPEntry(); + virtual ~BAPEntry() {} // weak in the image (emitted in EntryBoatMoveTo.cpp) // execute reports success as bool; getTargetId returns the entry's integer target id. virtual bool execute(BotScript *, Bot *, bool&, bool&) = 0; diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPInterpreter.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPInterpreter.cpp new file mode 100644 index 000000000..bfbcb33cd --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPInterpreter.cpp @@ -0,0 +1,165 @@ +// BAPInterpreter: recovered by package A-core from libaidll.so (AI/AIDLL/AI/AIPlanInterpreter/ +// BAPInterpreter.cpp in the image's strings). Every body carries its ELF address. + +// static init: ELF 0x2A9F80 (__tcf_0 0x2A9FE0, _GLOBAL__I 0x2AA010): 's Init object only. +#include + +#include "BAPInterpreter.h" + +#include "BAPEntry.h" +#include "../AIBotActionPlan/BotScript.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPStatement.h" +#include "../../../../Core/Debug.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2A95E0 (C2; C1 0x2A96A0 is the same body). The rows are filled before the mask array is +// allocated, and neither allocation is checked. +BAPInterpreter::BAPInterpreter(int numStatementTypes) + : m_numStatementTypes(numStatementTypes) +{ + m_entries = new BAPEntry**[numStatementTypes]; + for (int type = 0; type < m_numStatementTypes; ++type) + { + m_entries[type] = new BAPEntry*[NumLodLevels]; + for (int lod = 0; lod < NumLodLevels; ++lod) + m_entries[type][lod] = 0; + } + + m_active = new unsigned long long[NumLodLevels]; + for (int lod = 0; lod < NumLodLevels; ++lod) + m_active[lod] = 0; +} + +// ELF 0x2A9760 (D2; D1 0x2A9830, D0 0x2A9900). The entries are not owned: the slots are cleared, +// not deleted (AIConsole builds the entries and keeps them). +BAPInterpreter::~BAPInterpreter() +{ + for (int type = 0; type < m_numStatementTypes; ++type) + { + for (int lod = 0; lod < NumLodLevels; ++lod) + { + if (m_entries[type][lod]) + m_entries[type][lod] = 0; + } + delete[] m_entries[type]; + m_entries[type] = 0; + } + delete[] m_entries; + m_entries = 0; + delete[] m_active; + m_active = 0; +} + +// ELF 0x2A99D0 (209 instructions). +// 1. A bot that has just spawned (Bot +0x118) interprets nothing this tick: ok, not finished. +// 2. Otherwise the statement type (BotScript* treated as BAPStatement, getId +0x10) and the bot's +// LOD (+0xC) select the active bit; with it set, the registered entry runs, or without an entry +// the statement's own execute (slot 0). The callee's result is returned. +// 3. A type that is not active at that LOD is an Error-level diagnostic (which aborts), then +// ok = false, finished = true, return 0. +bool BAPInterpreter::execute(BotScript* script, Bot* bot, bool& ok, bool& finished) +{ + if (bot->isJustSpawned()) + { + finished = false; + ok = true; + return true; + } + + BAPStatement* statement = static_cast(script); + const BAPStatementType type = statement->getId(); + const BotLodLevel lod = bot->getLodLevel(); + + if ((m_active[lod] >> type) & 1) + { + BAPEntry* entry = m_entries[type][lod]; + if (entry == 0) + return script->execute(bot, ok, finished); + return entry->execute(script, bot, ok, finished); + } + + // Retail: Debug(6, "AI/AIDLL/AI/AIPlanInterpreter/BAPInterpreter.cpp", 154, "") << getName() + // << " " << getBotId() << " lod level " << lod << " cannot interpret \n" << " (" << type << ") " + // << type << "." with operator<<(ostream&, BotLodLevel) 0x3C78B0 and (ostream&, BAPStatementType) + // 0x3C7D90 (Main/AIStreamOperators.cpp, not in the tree yet; requested from ai-main). Until those + // exist the two enums print as numbers. [CHOSEN, not recovered] [RETIRE-WHEN: ai-stream-operators] + Debug(DebugTypeError, __FILE__, __LINE__, "") + << bot->getName() << " " << static_cast(bot->getBotId()) << " lod level " + << static_cast(lod) << " cannot interpret \n" << " (" << static_cast(type) << ") " + << static_cast(type) << "."; + + finished = true; + ok = false; + return false; +} + +// ELF 0x2A9D10. +bool BAPInterpreter::addEntry(BAPEntry* entry) +{ + return addEntry(static_cast(0), entry); +} + +// ELF 0x2A9D50. The entry's target id (+0xC) is its statement type. It is registered at `lod` and +// at every coarser LOD up to the first one that already has an entry, and activated there. +bool BAPInterpreter::addEntry(BotLodLevel lod, BAPEntry* entry) +{ + const int type = entry->getTargetId(); + if (m_numStatementTypes <= type || m_entries[type][lod] != 0) + return false; + + const unsigned long long bit = 1ULL << type; + for (int level = lod; level < NumLodLevels; ++level) + { + if (m_entries[type][level] != 0) + break; + m_entries[type][level] = entry; + m_active[level] |= bit; + } + return true; +} + +// ELF 0x2A9E10. Clears every slot from `lod` on that holds this entry (no early exit). +bool BAPInterpreter::removeEntry(BotLodLevel lod, BAPEntry* entry) +{ + const int type = entry->getTargetId(); + if (m_numStatementTypes <= type) + return false; + + const unsigned long long bit = 1ULL << type; + for (int level = lod; level < NumLodLevels; ++level) + { + if (m_entries[type][level] == entry) + { + m_entries[type][level] = 0; + m_active[level] &= ~bit; + } + } + return true; +} + +// ELF 0x2A9ED0. Lets a type run its own execute (no entry) at `lod` and the coarser LODs up to the +// first one that has an entry. Refused when an entry is registered at `lod` itself. +bool BAPInterpreter::activateEntry(BAPStatementType type, BotLodLevel lod) +{ + if (m_numStatementTypes <= type || m_entries[type][lod] != 0) + return false; + + const unsigned long long bit = 1ULL << type; + for (int level = lod; level < NumLodLevels; ++level) + { + if (m_entries[type][level] != 0) + break; + m_active[level] |= bit; + } + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPInterpreter.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPInterpreter.h new file mode 100644 index 000000000..982174b50 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPInterpreter.h @@ -0,0 +1,52 @@ +// The plan interpreter: per statement type and LOD level, either a registered BAPEntry (the +// vehicle-specific control code) or the statement's own execute. Recovered by package A-core +// (docs/macos-ai-behaviour-plan.md) from libaidll.so; the virtual order is checked by +// tools/macos/ai_behaviour_vtables.py. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_BAPINTERPRETER_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_BAPINTERPRETER_H + +#include "../AIBotActionPlan/BAPTypes.h" +#include "PlanInterpreter.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPEntry; +class Bot; +class BotScript; + +// sizeof 0x10 (`operator new(0x10)` in AISettings::preparePlanInterpreterPool). Layout from the +// constructor 0x2A95E0: +4 = the argument, +0xC = new BAPEntry**[n] each new BAPEntry*[3] zeroed, +// +8 = new u64[3] zeroed. Three LOD rows (BotLodFull 0, Medium 1, Light 2): every loop stops at 2. +// ELF: vtable 0x4BCA48 (3 words), operator new 0x10, package A-core. +class BAPInterpreter : public PlanInterpreter +{ +public: + explicit BAPInterpreter(int numStatementTypes); // 0x2A96A0 + virtual ~BAPInterpreter(); // 0x2A9830 + + virtual bool execute(BotScript*, Bot*, bool& ok, bool& finished); // 0x2A99D0, slot +0x08; from the base declaration + + // The four return `al`: 0 when the type is out of range or (add/activate) the slot at the given + // LOD is already taken, 1 otherwise (also when the LOD is above 2 and nothing is done). + bool addEntry(BAPEntry*); // 0x2A9D10: addEntry(BotLodFull, entry) + bool addEntry(BotLodLevel, BAPEntry*); // 0x2A9D50 + bool removeEntry(BotLodLevel, BAPEntry*); // 0x2A9E10 + bool activateEntry(BAPStatementType, BotLodLevel); // 0x2A9ED0 + +private: + enum { NumLodLevels = 3 }; // [CHOSEN] name for the literal `cmpl $0x2` loop bound + + /* +0x04 */ int m_numStatementTypes; // the constructor argument (45 from AISettings) [INFERRED] name + /* +0x08 */ unsigned long long* m_active; // [lod]: bit `type` set = the type may be interpreted at that LOD + /* +0x0C */ BAPEntry*** m_entries; // [type][lod]: entry or 0 (not owned) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_BAPINTERPRETER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BoatControl.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BoatControl.cpp new file mode 100644 index 000000000..5bc79b40c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BoatControl.cpp @@ -0,0 +1,205 @@ +// Boat movement and input reset, recovered from libaidll.so. + +// static init: ELF 0x2AAE90 (__tcf_0 0x2AAEF0, _GLOBAL__I 0x2AAF20): 's Init object only. +#include + +#include "BoatControl.h" + +#include "CarControl.h" +#include "ControlFunctions.h" +#include "VehicleControlInline.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../../IO/Input/PlayerInput.h" +#include "../../../../Math/Mat4.h" +#include +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// Inline sign and clamp expansions in ELF 0x2AA090; NaN has sign zero and passes the clamp. +float sign(float value) +{ + return value > 0.0f ? 1.0f : (0.0f > value ? -1.0f : 0.0f); +} + +float clamp(float value, float minimum, float maximum) +{ + return minimum > value ? minimum : (value > maximum ? maximum : value); +} + +float mappedInput(io::PlayerInput* input, io::PlayerInputMap control) +{ + const int index = static_cast(control); + if (index <= 63 && ((input->mappingFlags >> (static_cast(index) & 63)) & 1ULL)) + return input->inputs[index]; + return 0.0f; +} + +} // namespace + +// ELF 0x2AA090 +bool BoatControl::speedControl(Bot* bot, Information* equipment, const Vec2& direction, + float speedFraction, float angle, BAPAMoveTo* move, + float speedLimit, io::PlayerInput* input, float selectedFraction) +{ + IPIMobile* const mobile = equipment->getMobile(); + const float speedMagnitude = mobile->getSpeedMagnitude(); + mobile->getSpeed(); + const Vec3& rotation = mobile->getRotationalSpeed(); + const Mat4& transform = equipment->getTransformation(); + const float yawSpeed = transform.m[4] * rotation.x + transform.m[5] * rotation.y + + transform.m[6] * rotation.z; + Vec2 position = {}; + Vec2 facing = {}; + Vec2 normal = {}; + vec3ToVec2XZ(equipment->getPosition(), position); + vec3ToVec2XZ(equipment->getFaceing(), facing); + getNormal(facing, normal); + vehiclecontrol::normalizeVec2(normal); + equipment->getAIObject()->releaseObjectFromSpawner(); + + if (speedFraction == 0.0f + || (static_cast(bot)->getMoveToStatus() == 0 && std::fabs(angle) > 0.5235988f)) + { + float turn = normal.x * direction.x + normal.y * direction.y; + const float alignment = facing.x * direction.x + facing.y * direction.y; + if (alignment <= 0.0f) + turn = sign(turn); + const Mat4& currentTransform = equipment->getTransformation(); + const Vec3& velocity = mobile->getSpeed(); + const float forwardSpeed = velocity.y * currentTransform.m[9] + velocity.x * currentTransform.m[8] + + velocity.z * currentTransform.m[10]; + input->setInput(static_cast(0), 0.0f); + const float throttle = mappedInput(input, static_cast(3)); + if (alignment > 0.996f) + { + float brake = 0.0f; + if (std::fabs(forwardSpeed) > 1.0f) + brake = -sign(forwardSpeed); + else if (std::fabs(forwardSpeed) > 0.03f) + brake = -sign(forwardSpeed) * log10f(std::fabs(forwardSpeed) * 9.0f + 1.0f); + input->setInput(static_cast(3), brake); + return true; + } + if (std::fabs(forwardSpeed) > 3.0f) + input->setInput(static_cast(3), -sign(forwardSpeed)); + else if (std::fabs(throttle) != 1.0f) + input->setInput(static_cast(3), sign(forwardSpeed)); + input->setInput(static_cast(0), sign(turn) * sign(forwardSpeed)); + return true; + } + + if (speedFraction != 0.0f && speedFraction != selectedFraction && speedMagnitude > 1.0f) + angle = -angle; + const float maximumSpeed = mobile->getMaxSpeed(); + const float targetSpeed = (maximumSpeed > speedLimit ? speedLimit : maximumSpeed) * speedFraction; + float throttle = mappedInput(input, equipment->getControlInfo()->getDriveThrottleControl()); + simpleReg(targetSpeed - speedMagnitude, move->m_previousSpeed - speedMagnitude, 1.0f, throttle); + const float turn = clamp(sinf(clamp(angle, -1.5707964f, 1.5707964f)) + - clamp(yawSpeed, -1.0f, 1.0f) * 0.1f, -1.0f, 1.0f); + move->m_previousHeading = facing; + move->m_previousSpeed = speedMagnitude; + // The template selects the input to read above; the shipped writes still use inputs 0 and 3. + input->setInput(static_cast(0), sign(turn) * log10f(std::fabs(turn) * 9.0f + 1.0f)); + input->setInput(static_cast(3), throttle); + return true; +} + +// ELF 0x2AA910 +bool BoatControl::towardsDirection(Bot* bot, Information* equipment, Vec2 direction, float distance, + BAPAMoveTo* move, io::PlayerInput* input, float speedLimit) +{ + float speedFraction; + float angle; + float selectedFraction; + float unused; + if (!CarControl::actionStatusDecision(bot, equipment, direction, distance, move, + speedFraction, angle, selectedFraction, unused)) + return false; + return speedControl(bot, equipment, direction, speedFraction, angle, move, speedLimit, input, selectedFraction); +} + +// ELF 0x2AA9D0 (listing; Ghidra cross-check). `done` is set first. Moving: the forward speed is +// the mobile's speed dot the transformation's third row (+0x20..+0x28); inputs 0, 2 and 1 are +// released; up to 1.0 the throttle (input 3) is released, above it the throttle is +// -sign(speed) * log10(|speed| * 9 + 1) (-sign alone at or below 0.03, unreachable after the 1.0 +// test, kept as compiled) and `done` is cleared. The information lookup is not null-tested. +// Look releases 4 and 5; trigger 8, 31, 14..30, 38, 37, 10 and 32. Returns 1. +int BoatControl::resetControls(Bot* bot, bool move, bool look, bool trigger, bool& done) +{ + io::PlayerInput* const input = bot->getInput(); + done = true; + if (move) + { + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* const mobile = equipment->getMobile(); // +0x38 + const Mat4& transformation = equipment->getTransformation(); // +0x3C + const Vec3& speed = mobile->getSpeed(); // +0x1C + const float forwardSpeed = speed.y * transformation.m[9] + speed.x * transformation.m[8] + + speed.z * transformation.m[10]; + input->setInput(static_cast(0), 0.0f); + input->setInput(static_cast(2), 0.0f); + input->setInput(static_cast(1), 0.0f); + if (std::fabs(forwardSpeed) > 1.0f) + { + const float sign = (forwardSpeed > 0.0f) ? 1.0f : ((0.0f > forwardSpeed) ? -1.0f : 0.0f); + float throttle; + if (std::fabs(forwardSpeed) > 0.03f) + throttle = log10f(std::fabs(forwardSpeed) * 9.0f + 1.0f) * -sign; + else + throttle = -sign; + input->setInput(static_cast(3), throttle); + done = false; + } + else + { + input->setInput(static_cast(3), 0.0f); + } + } + if (look) + { + input->setInput(static_cast(4), 0.0f); + input->setInput(static_cast(5), 0.0f); + } + if (trigger) + { + input->setInput(static_cast(8), 0.0f); + input->setInput(static_cast(31), 0.0f); + input->setInput(static_cast(14), 0.0f); + input->setInput(static_cast(15), 0.0f); + input->setInput(static_cast(16), 0.0f); + input->setInput(static_cast(17), 0.0f); + input->setInput(static_cast(18), 0.0f); + input->setInput(static_cast(19), 0.0f); + input->setInput(static_cast(20), 0.0f); + input->setInput(static_cast(21), 0.0f); + input->setInput(static_cast(22), 0.0f); + input->setInput(static_cast(23), 0.0f); + input->setInput(static_cast(24), 0.0f); + input->setInput(static_cast(25), 0.0f); + input->setInput(static_cast(26), 0.0f); + input->setInput(static_cast(27), 0.0f); + input->setInput(static_cast(28), 0.0f); + input->setInput(static_cast(29), 0.0f); + input->setInput(static_cast(30), 0.0f); + input->setInput(static_cast(38), 0.0f); + input->setInput(static_cast(37), 0.0f); + input->setInput(static_cast(10), 0.0f); + input->setInput(static_cast(32), 0.0f); + } + return 1; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BoatControl.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BoatControl.h new file mode 100644 index 000000000..6408395c1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BoatControl.h @@ -0,0 +1,30 @@ +// Boat steering, speed regulation and input reset. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_BOATCONTROL_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_BOATCONTROL_H + +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { + +namespace io { class PlayerInput; } +namespace ai { + +class BAPAMoveTo; +class Bot; +class Information; + +// [INFERRED] a namespace: no vtable, no constructor, and the first argument is never `this`. +namespace BoatControl +{ + bool speedControl(Bot*, Information*, const Vec2&, float, float, BAPAMoveTo*, float, io::PlayerInput*, float); // 0x2AA090 + bool towardsDirection(Bot*, Information*, Vec2, float, BAPAMoveTo*, io::PlayerInput*, float); // 0x2AA910 + int resetControls(Bot*, bool, bool, bool, bool&); // 0x2AA9D0; [INFERRED] ELF int +} + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_BOATCONTROL_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BotScriptDebugger.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BotScriptDebugger.cpp new file mode 100644 index 000000000..cbb255eca --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BotScriptDebugger.cpp @@ -0,0 +1,22 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#include "BotScriptDebugger.h" + + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2A95C0: `xor %eax,%eax` (no implementation; BAPDebugger overrides it). +int BotScriptDebugger::getImplementation() +{ + return 0; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BotScriptDebugger.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BotScriptDebugger.h new file mode 100644 index 000000000..ce1625f3f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BotScriptDebugger.h @@ -0,0 +1,36 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_BOTSCRIPTDEBUGGER_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_BOTSCRIPTDEBUGGER_H + + +namespace dice { +namespace hfe { + +namespace ai { + +class BotScript; + +// ELF: vtable 0x4BC9E8 (5 words), package S0-skeleton. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BotScriptDebugger +{ +public: + enum DebugLevel : int; // [UNRESOLVED] enumerators + enum DebugPlace : int; // [UNRESOLVED] enumerators + virtual ~BotScriptDebugger() {} // weak in the image (inline) + + virtual void debug(BotScriptDebugger::DebugLevel, BotScript*, BotScriptDebugger::DebugPlace, int) = 0; // no body, slot +0x08; [INFERRED] from BAPDebugger: ELF void + virtual void clear() = 0; // no body, slot +0x0C; [INFERRED] from BAPDebugger: ELF void + virtual int getImplementation(); // 0x2A95C0, slot +0x10; [INFERRED] ELF int +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_BOTSCRIPTDEBUGGER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CarControl.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CarControl.cpp new file mode 100644 index 000000000..659a5f423 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CarControl.cpp @@ -0,0 +1,835 @@ +// Car steering for the plan interpreter (libaidll.so CarControl TU). Every body is recovered. +// static init: the guard object only (ELF 0x2AF060, __tcf_0 0x2AF0C0, _GLOBAL__I 0x2AF0F0). + +#include "CarControl.h" + +#include "CommonControls.h" +#include "VehicleControlInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotNavigation.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../Main/IAIPathfinding.h" +#include "../Main/IBotManager.h" +#include "../../../../Math/LocalBoundingBox.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +#include +#include +#include + +#include "../../../../IO/Input/PlayerInput.h" + +namespace dice { +namespace hfe { +namespace ai { + +using namespace vehiclecontrol; + +// The TU's anonymous tweak_* values (.data 0x4BCB04..0x4BCB38: terrainSampleInterval 1, +// terrainLookAhead 20, maxSpeed 20, minSpeed 2, stopAndTurn_maxSpeed 7, +// stopAndTurn_angularDeviationThreshold 30, speedScale 2, speedCompensationFallOff 30, +// speedCompensationScale 1, maxSpeedCompensation 10, rotationalSpeedScale 1, +// rotationalSpeedCompensationFallOff 30, rotationalSpeedCompensationScale 1, +// maxRotationalSpeedCompensation 10) have no reader in the image and are not defined here. + +// ELF 0x2AAF40 (listing; Ghidra cross-check). Turns and throttles a car from the outputs of +// actionStatusDecision: `mode` (0 = turn on the spot towards `angle`, -1 = the same reversed by pi, +// else drive with `mode` as the speed sign), `angle` (the signed angle to the goal, negated while +// driving with mode != reference and faster than 1 m/s), `reference` and `limit` (the largest +// target speed). Physics is enabled for both sides when a speed is asked for. Driving: turn input +// clamp(3 * angle, -1, 1); target speed = speed * mode, reduced by up to 80 % for a sideways or +// forward slope (the larger |rotational speed| x/z above 0.15), capped at `limit`; throttle = +// clamp(min(1, (target - |v| * reference) / 3) + target / 15, -1, 1), and below 1.5 m/s a non-zero +// throttle becomes its sign (1 or -1, as 0 > throttle). Turning on the spot: the turn input (set only +// while mapped, through the inlined setInput) is min(1, |3 * (|angle| [- pi])|) against the angle's +// sign; the throttle input gets `mode`. Returns 1. +int CarControl::controlTowardsDirection(Information* info, IPIControlInfo* controlInfo, IPIMobile* mobile, + IPIPhysical*, io::PlayerInput* input, float speed, float mode, float angle, + float reference, float limit) +{ + const Mat4& transformation = info->getTransformation(); + Vec2 forward; + forward.x = forward.y = 0.0f; + vec3ToVec2XZ(*reinterpret_cast(&transformation.m[8]), forward); + Vec2 right; // read, never used + right.x = right.y = 0.0f; + vec3ToVec2XZ(*reinterpret_cast(&transformation.m[0]), right); + Vec2 position; // read, never used + position.x = position.y = 0.0f; + vec3ToVec2XZ(*reinterpret_cast(&transformation.m[12]), position); + mobile->getMaxSpeed(); // 0x2AAFB8, result discarded + Vec2 velocity; + velocity.x = velocity.y = 0.0f; + vec3ToVec2XZ(mobile->getSpeed(), velocity); + const float velocityLength = std::sqrt(velocity.x * velocity.x + velocity.y * velocity.y); + Vec2 heading; // computed, never used + if (velocityLength == 0.0f) + { + heading = forward; + } + else + { + const float inverse = 1.0f / velocityLength; + heading.x = velocity.x * inverse; + heading.y = inverse * velocity.y; + } + (void)heading; + if (mode != 0.0f && reference != mode && velocityLength > 1.0f) + angle = -angle; + if (speed != 0.0f) + { + // 0x2AB577 + IAIObjectPhysical* const object = info->getAIObject()->getPhysical(); + object->enablePhysics(1); + object->enablePhysics(2); + } + float sign = 0.0f; + if (angle <= 0.0f) + { + if (angle < 0.0f) + sign = -1.0f; + } + else + { + sign = 1.0f; + } + + float throttle; + if (mode != 0.0f) + { + // 0x2AB2E8 + const float scaledAngle = angle * 3.0f; + float turn = -1.0f; + if (-1.0f <= scaledAngle) + turn = (1.0f < scaledAngle) ? 1.0f : scaledAngle; + input->setInput(controlInfo->getDriveTurnControl(), turn); + speed = speed * mode; + const Vec3& rotation = mobile->getRotationalSpeed(); + float tilt = std::fabs(rotation.z); + if (std::fabs(rotation.z) <= std::fabs(rotation.x)) + tilt = std::fabs(rotation.x); + if (tilt > 0.15f) + { + float scale = (tilt - 0.15f) / 0.7f; + if (scale > 1.0f) + scale = 1.0f; + speed = (1.0f - scale * 0.8f) * speed; + } + if (std::fabs(speed) > limit) + { + float speedSign = 1.0f; + if (speed <= 0.0f) + speedSign = (speed < 0.0f) ? -1.0f : 0.0f; + speed = speedSign * limit; + } + float response = (speed - velocityLength * reference) / 3.0f; + if (response > 1.0f) + response = 1.0f; + response = response + speed / 15.0f; + throttle = -1.0f; + if (response >= -1.0f) + throttle = (response <= 1.0f) ? response : 1.0f; + if (throttle != 0.0f && !(1.5f <= std::fabs(velocityLength))) + { + float throttleSign = 1.0f; + if (throttle <= 0.0f) + throttleSign = (0.0f <= throttle) ? 0.0f : -1.0f; + throttle = throttleSign; + } + } + else + { + // 0x2AB0C7 + float turnAngle = std::fabs(angle); + if (mode == -1.0f) + turnAngle = turnAngle - 3.1415927f; + float turn = std::fabs(turnAngle * 3.0f); + if (turn > 1.0f) + turn = 1.0f; + input->setInput(controlInfo->getDriveTurnControl(), turn * -sign); + throttle = mode; + } + input->setInput(controlInfo->getDriveThrottleControl(), throttle); + return 1; +} + +// ELF 0x2AB5F0 (listing). Releases the selected input groups in the order move, look, trigger. +// Moving: the strafe/turn inputs 0, 2 and 1 are released, and the throttle (input 3) brakes against +// `forwardSpeed`: the speed is clamped to +-maxThrottle (a function static, 0.7), negated, and +// within 0.05 of zero the throttle is released; otherwise it is the sign times at least 0.4. +// Look releases inputs 4 and 5; trigger releases 8, 31, 14..30, 38, 37, 10 and 32. Returns 1. +int CarControl::resetControls(Bot*, io::PlayerInput* input, bool move, bool look, bool trigger, float forwardSpeed) +{ + static float maxThrottle = 0.7f; + if (move) + { + input->setInput(static_cast(0), 0.0f); + input->setInput(static_cast(2), 0.0f); + input->setInput(static_cast(1), 0.0f); + float clamped; + if (-maxThrottle > forwardSpeed) + clamped = -maxThrottle; + else + clamped = (forwardSpeed > maxThrottle) ? maxThrottle : forwardSpeed; + const float brake = -clamped; + float throttle = 0.0f; + if (std::fabs(brake) > 0.05f) + { + const float sign = (brake > 0.0f) ? 1.0f : ((0.0f > brake) ? -1.0f : 0.0f); + const float magnitude = std::fabs(brake); + throttle = sign * ((magnitude > 0.4f) ? magnitude : 0.4f); + } + input->setInput(static_cast(3), throttle); + } + if (look) + { + input->setInput(static_cast(4), 0.0f); + input->setInput(static_cast(5), 0.0f); + } + if (trigger) + { + input->setInput(static_cast(8), 0.0f); + input->setInput(static_cast(31), 0.0f); + for (int i = 14; i <= 30; ++i) + input->setInput(static_cast(i), 0.0f); + input->setInput(static_cast(38), 0.0f); + input->setInput(static_cast(37), 0.0f); + input->setInput(static_cast(10), 0.0f); + input->setInput(static_cast(32), 0.0f); + } + return 1; +} + +// ELF 0x2AB970 (listing block by block; Ghidra cross-check). The car's move-to state machine. +// Measures the free space around the vehicle with eight IAIPathfinding traces from its last valid +// position (forward, the two front diagonals of the bounding box and the same backwards, each +// diagonal/backward trace shortened by the obstacles the navigation holds, then right and left), +// asks CommonControls for the obstacle ahead and the vehicle to slow down for, picks an avoid +// side for a collided vehicle and then advances the bot's move-to status (0 drive, 2/3 and 9/11 +// turn forwards/backwards, 4/5 and 13/14 pass an obstacle, 6 avoid, 8 reverse, 12 back off). +// Outputs: `mode` (1 forward, -1 reverse, 666 = arrived at the collided object), `angle` (the +// signed steering angle, -2 = the slow-down stop), `speedSign` (the sign of the forward speed) +// and `speedLimit`. Returns 0 without a mobile or physical part, else 1. +// Shipped behaviour kept: the forward-space trace reads 0 when the trace hit is the zero vector, +// the space-with-obstacles front output is an uninitialised local that is never read, the +// collided object's information is dereferenced without a null test, and statuses 2/3 re-test the +// turn direction they are already in. +int CarControl::actionStatusDecision(Bot* bot, Information* info, const Vec2& direction, float speed, + BAPAMoveTo* moveTo, float& mode, float& angle, float& speedSign, + float& speedLimit) +{ + static float spaceTweak = 1.3f; // .data 0x4BCB40 + + IPIMobile* const mobile = info->getMobile(); + IPIPhysical* const physical = info->getPhysical(); + if (mobile == 0 || physical == 0) + return 0; + BotMain* const botMain = static_cast(bot); // slots 0x238.. are declared on BotMain only + const float radius = physical->getRadius(); + Vec2 desired = direction; + const Vec3& position3 = info->getPosition(); + Vec2 position; + position.x = position.y = 0.0f; + Vec2 forward; + forward.x = forward.y = 0.0f; + Vec2 normal; + normal.x = normal.y = 0.0f; + vec3ToVec2XZ(position3, position); + vec3ToVec2XZ(info->getFaceing(), forward); + normalizeVec2(forward); + getNormal(forward, normal); + Vec2 goal; + goal.x = goal.y = 0.0f; + vec3ToVec2XZ(moveTo->getCoordinate(), goal); + float goalDistance = moveTo->getTargetDistance(); + if (goalDistance == 0.0f) + { + Vec2 toGoal; + toGoal.x = position.x - goal.x; + toGoal.y = position.y - goal.y; + goalDistance = std::sqrt(toGoal.x * toGoal.x + toGoal.y * toGoal.y); + } + const float nearDistance = radius * 10.0f; + const float dot = desired.x * forward.x + desired.y * forward.y; + angle = getSignedDiffAngleToDirWithNormal(forward, normal, desired); + const bool angleNegative = 0.0f > angle; + const float speedMagnitude = mobile->getSpeedMagnitude(); + const Vec3& velocity = mobile->getSpeed(); + const Vec3 facing = info->getFaceing(); + if (velocity.x * facing.x + velocity.y * facing.y + velocity.z * facing.z >= 0.0f) + speedSign = 1.0f; + else + speedSign = -1.0f; + bool slowDownStop; + const float slowDown = CommonControls::checkSlowDown(bot, info, velocity, speedMagnitude * speedSign, position3, + slowDownStop); + Vec3 forward3; + forward3.x = forward3.y = forward3.z = 0.0f; + vec2ToVec3XZ(forward, forward3); + mode = 1.0f; + + // 0x2ABCE4: the eight space traces. + IAIPathfinding* const pathfinding = IAIPathfinding::instance; + mobile->getVehicleNumber(); // result discarded + BotNavigation* const navigation = bot->getBotNavigation(); + const float traceLength = radius + 10.0f; + Vec3 hit; + hit.x = hit.y = hit.z = 0.0f; + const IPIMobile::ValidPos& lastValid = mobile->getLastValidPosition(pathfinding->getTraceMapIndex()); + const int equipmentType = info->getUnit()->getEquipmentType(); + Vec3 right; + right.x = normal.x; + right.y = 0.0f; + right.z = normal.y; + int status = botMain->getMoveToStatus(); + const bool reversing = status > 7; + float back = 0.0f; + float front = 0.0f; + LocalBoundingBox* const box = const_cast(physical->getLocalBoundingBox()); + const Vec3& size = box->getSize(); + const float width = size.x; + const float length = size.z; + const Vec3 origin = lastValid.position; + const Vec3 ahead = forward3; + Vec3 frontLeft; + frontLeft.x = length * forward3.x - right.x * width; + frontLeft.y = length * forward3.y - right.y * width; + frontLeft.z = length * forward3.z - right.z * width; + normalizeVec3(frontLeft); + Vec3 frontRight; + frontRight.x = length * ahead.x + right.x * width; + frontRight.y = ahead.y * length + right.y * width; + frontRight.z = length * ahead.z + right.z * width; + normalizeVec3(frontRight); + unsigned int polygon; + unsigned char traceStatus; + float frontUnused; // -0x2CC: updateSpaceWithObstacles' front output, never initialised or read + + Vec3 target = alongFrom(origin, ahead, traceLength); + pathfinding->trace(navigation, true, target, hit, polygon, equipmentType, -1, 0.0f, 6, 0); + if (!isZeroVec3(hit)) + front = distanceVec3(hit, origin); + const float firstFront = front; + target = alongFrom(origin, frontLeft, traceLength); + pathfinding->trace(navigation, true, target, hit, polygon, equipmentType, -1, 0.0f, 6, &traceStatus); + if (traceStatus != 4 && !isZeroVec3(hit)) + { + const float d = distanceVec3(hit, origin); + front = (d > firstFront) ? firstFront : d; + } + target = alongFrom(origin, frontRight, traceLength); + pathfinding->trace(navigation, true, target, hit, polygon, equipmentType, -1, 0.0f, 6, &traceStatus); + if (traceStatus != 4 && !isZeroVec3(hit)) + { + const float d = distanceVec3(hit, origin); + front = (d > front) ? front : d; + } + target = backFrom(origin, ahead, traceLength); + pathfinding->trace(navigation, true, target, hit, polygon, equipmentType, -1, 0.0f, 6, 0); + if (!isZeroVec3(hit)) + back = distanceVec3(hit, origin); + CommonControls::updateSpaceWithObstacles(bot, origin, ahead, frontUnused, back, 0xFFFFFFFFu); + target = backFrom(origin, frontLeft, traceLength); + pathfinding->trace(navigation, true, target, hit, polygon, equipmentType, -1, 0.0f, 6, &traceStatus); + if (traceStatus != 4 && !isZeroVec3(hit)) + { + const float d = distanceVec3(hit, origin); + back = (d > back) ? back : d; + } + CommonControls::updateSpaceWithObstacles(bot, origin, frontLeft, frontUnused, back, 0xFFFFFFFFu); + target = backFrom(origin, frontRight, traceLength); + pathfinding->trace(navigation, true, target, hit, polygon, equipmentType, -1, 0.0f, 6, &traceStatus); + if (traceStatus != 4 && !isZeroVec3(hit)) + { + const float d = distanceVec3(hit, origin); + back = (d > back) ? back : d; + } + CommonControls::updateSpaceWithObstacles(bot, origin, frontRight, frontUnused, back, 0xFFFFFFFFu); + target = alongFrom(origin, right, traceLength); + pathfinding->trace(navigation, true, target, hit, polygon, equipmentType, -1, 0.0f, 6, &traceStatus); + float rightSpace = traceLength; + if (traceStatus != 4) + rightSpace = isZeroVec3(hit) ? 0.0f : distanceVec3(hit, origin); + target = backFrom(origin, right, traceLength); + pathfinding->trace(navigation, true, target, hit, polygon, equipmentType, -1, 0.0f, 6, &traceStatus); + float leftSpace = traceLength; + if (traceStatus != 4) + leftSpace = isZeroVec3(hit) ? 0.0f : distanceVec3(hit, origin); + + // 0x2AD236: the obstacle ahead. + const float spaceRadius = radius * spaceTweak; + unsigned int obstacle = 0xFFFFFFFFu; + unsigned int collided = botMain->getCollidedObject(); + int avoidSide = botMain->getAvoidSide(); + Vec2 desiredVelocity; + desiredVelocity.x = speed * direction.x; + desiredVelocity.y = speed * direction.y; + float dotForward; + float angleToObstacle; + bool outOfOurWay; + bool passing; + bool collidedSeen; + float avoidAngle; + float tangentAngle; + bool touching; + bool collision = CommonControls::checkCollisions(bot, info, physical, forward, dotForward, angleToObstacle, + outOfOurWay, desiredVelocity, desired, speed, passing, obstacle, + collided, collidedSeen, avoidAngle, tangentAngle, speedSign, + touching, static_cast(avoidSide), true); + if (collided != 0xFFFFFFFFu && !collidedSeen) + collision = false; + if (collision) + { + Information* const obstacleInfo = lookupInformation(obstacle); + const float limitSqr = botMain->getIgnoreObstacles() ? 2.5f * 2.5f : 1.0f; + if (obstacle == collided && obstacle != 0xFFFFFFFFu) + { + // 0x2AEB27: drop the collision once the collided object has moved away. + const Vec3& last = botMain->getCollidedObjectPosition(); + const Vec3& now = obstacleInfo->getPosition(); + Vec3 moved; + moved.x = now.x - last.x; + moved.y = now.y - last.y; + moved.z = now.z - last.z; + if (moved.x * moved.x + moved.y * moved.y + moved.z * moved.z > limitSqr) + collision = false; + } + else + { + botMain->setCollidedObjectPosition(obstacleInfo->getPosition()); + } + } + if (!collision) + { + botMain->setCollidedObject(0xFFFFFFFFu); + obstacle = 0xFFFFFFFFu; + collided = 0xFFFFFFFFu; + } + bool tooClose = false; + if (collision) + { + botMain->setCollidedObject(obstacle); + collided = obstacle; + if (avoidSide == 0) + { + // 0x2AD494: choose the side with more room around the collided vehicle. + Information* const other = lookupInformation(collided); + IPIMobile* const otherMobile = other->getMobile(); + IPIPhysical* const otherPhysical = other->getPhysical(); + if (otherMobile == 0) + { + avoidSide = 1; + } + else + { + const float clearance = radius + otherPhysical->getSmallestRadius() * 0.5f; + const float reach = clearance + 0.5f; + const int vehicleNumber = mobile->getVehicleNumber(); + const IPIMobile::ValidPos& otherValid = otherMobile->getLastValidPosition(vehicleNumber); + if (otherValid.polygon == 0xFFFFFFFFu || otherValid.island == 0xFFFFFFFFu) + { + avoidSide = 1; + } + else + { + Vec3 hitRight; + hitRight.x = hitRight.y = hitRight.z = 0.0f; + Vec3 hitLeft; + hitLeft.x = hitLeft.y = hitLeft.z = 0.0f; + unsigned int sidePolygon; + Vec3 sideTarget = alongFrom(otherValid.position, rightAxis(info->getTransformation()), reach); + pathfinding->trace(otherValid.polygon, otherValid.island, vehicleNumber, otherValid.position, + sideTarget, hitRight, sidePolygon, equipmentType, -1, 0.0f, 0, 0); + float roomRight = isZeroVec3(hitRight) ? 0.0f : distanceVec3(hitRight, otherValid.position); + sideTarget = backFrom(otherValid.position, rightAxis(info->getTransformation()), reach); + pathfinding->trace(otherValid.polygon, otherValid.island, vehicleNumber, otherValid.position, + sideTarget, hitLeft, sidePolygon, equipmentType, -1, 0.0f, 0, 0); + float roomLeft = isZeroVec3(hitLeft) ? 0.0f : distanceVec3(hitLeft, otherValid.position); + bool firstSide = roomRight < roomLeft; // before the obstacles shorten them + CommonControls::updateSpaceWithObstacles(bot, otherValid.position, + rightAxis(info->getTransformation()), roomRight, + roomLeft, collided); + const float smaller = (roomLeft < roomRight) ? roomLeft : roomRight; + const float larger = (roomRight > roomLeft) ? roomRight : roomLeft; + tooClose = clearance > larger; + if (smaller > clearance) + { + // 0x2AEA3E: room on both sides - the side the other vehicle lies on across the desired line. + Vec2 sideNormal; + sideNormal.x = sideNormal.y = 0.0f; + getNormal(desired, sideNormal); + Vec2 toOther; + toOther.x = otherValid.position.x - position.x; + toOther.y = otherValid.position.z - position.y; + firstSide = toOther.x * sideNormal.x + toOther.y * sideNormal.y > 0.0f; + } + else if (!(clearance * 0.7f > larger)) + { + firstSide = roomRight < roomLeft; + } + avoidSide = 2; + if (firstSide) + avoidSide = 1; + } + } + if (botMain->setAvoidSide(avoidSide) && !botMain->getIgnoreObstacles()) + { + status = 0; + botMain->setMoveToStatus(0); + botMain->setIgnoreObstacles(true); + } + } + } + else + { + botMain->setAvoidSide(0); + } + + // 0x2ADA40: arrived next to the collided object's goal? + bool hasCollided = collided != 0xFFFFFFFFu; + bot->setUnresolvedCollisionObject(collided); + if (hasCollided) + { + Information* const other = lookupInformation(collided); + if (other == 0) + { + hasCollided = false; + collided = 0xFFFFFFFFu; + } + else + { + Vec2 otherPosition; + otherPosition.x = otherPosition.y = 0.0f; + vec3ToVec2XZ(*reinterpret_cast(&other->getTransformation().m[12]), otherPosition); + const float otherRadius = other->getPhysical()->getRadius(); + Vec2 goalOffset; + goalOffset.x = goal.x - otherPosition.x; + goalOffset.y = goal.y - otherPosition.y; + if (otherRadius * otherRadius > goalOffset.x * goalOffset.x + goalOffset.y * goalOffset.y) + { + Vec2 toOther; + toOther.x = otherPosition.x - position.x; + toOther.y = otherPosition.y - position.y; + const float distanceSqr = toOther.x * toOther.x + toOther.y * toOther.y; + const float reach = other->getPhysical()->getRadius() + radius + 3.0f; + if (reach * reach > distanceSqr) + { + mode = 666.0f; + angle = 0.0f; + return 1; + } + } + } + } + else + { + avoidSide = 0; + botMain->setAvoidSide(0); + } + + // 0x2ADB2D: room flags and the speed limit. + bool wideSpace = false; + const bool obstacleAngleNegative = 0.0f > angleToObstacle; + if (leftSpace + rightSpace > radius * 2.7f && front + back > radius * 2.7f) + wideSpace = true; + bool veryWideSpace = false; + if (leftSpace + rightSpace > radius * 3.0f && front + back > radius * 3.0f) + veryWideSpace = true; + const float backRatio = (back - spaceRadius) / (traceLength - spaceRadius); + const float frontRatio = (front - spaceRadius) / (traceLength - spaceRadius); + bool stuck = false; + if (front == 0.0f && back == 0.0f) + { + stuck = true; + status = !(dot > 0.0f) ? 8 : 0; + } + const float maxSpeed = mobile->getMaxSpeed(); + const float minSpeed = 2.0f; + if (!reversing) + { + if (0.95f > frontRatio) + speedLimit = 5.0f - (1.0f - frontRatio) * (5.0f - minSpeed); + else + speedLimit = maxSpeed - (1.0f - frontRatio) * (maxSpeed - minSpeed); + } + else + { + speedLimit = 5.0f - (1.0f - backRatio) * (5.0f - minSpeed); + } + if (tooClose) + speedLimit = (7.0f > speedLimit) ? speedLimit : 7.0f; + if (!hasCollided) + { + botMain->setIgnoreObstacles(false); + botMain->setAvoidSide(0); + } + bool ignoring = botMain->getIgnoreObstacles(); + if (ignoring) + { + if (hasCollided) + { + // 0x2ADD1E: keep ignoring while we push the collided object, unless it has a human driver. + Information* const other = lookupInformation(collided); + IAIObjectPhysical* const otherObject = other->getAIObject()->getPhysical(); + otherObject->enablePhysics(1); + otherObject->enablePhysics(2); + if (botMain->getSlowDownToTarget() == collided) + ignoring = true; + if (other->getAIObject() != 0 && IBotManager::instance->getBot(other->getAIObject()) == 0 + && other->getUnit() != 0 && other->getUnit()->isOccupied()) + ignoring = false; + } + if (ignoring && (static_cast(status - 4) <= 2u || status == 13 || status == 14)) + { + status = 0; + botMain->setMoveToStatus(0); + } + } + + // 0x2ADE10 + switch (status) + { + case 0: + if (stuck) + { + mode = 1.0f; + speedLimit = maxSpeed * 0.5f; + break; + } + if (!(0.0f > dot) && !(spaceRadius > front)) + { + if (collision && !ignoring) + botMain->setMoveToStatus(6); + else + mode = 1.0f; + break; + } + if (nearDistance >= goalDistance && -0.6f > dot && back > spaceRadius) + { + botMain->setMoveToStatus(8); + break; + } + if (0.0f > dot && !wideSpace) + { + botMain->setMoveToStatus(12); + break; + } + botMain->setMoveToStatus(angleNegative ? 9 : 11); + break; + case 2: + if (angleNegative) + { + botMain->setMoveToStatus(dot > 0.0f ? 3 : 9); + break; + } + if (dot > 0.9f) + { + botMain->setMoveToStatus(0); + break; + } + if (spaceRadius > front || (dotForward > 0.5f && hasCollided && !outOfOurWay && !ignoring)) + { + botMain->setMoveToStatus(11); + break; + } + if (angleNegative && wideSpace && 0.0f > dot && back > spaceRadius) + { + botMain->setMoveToStatus(9); + break; + } + mode = 1.0f; + angle = std::fabs(angle); + break; + case 3: + if (!angleNegative) + { + botMain->setMoveToStatus(dot > 0.0f ? 2 : 11); + break; + } + if (dot > 0.9f) + { + botMain->setMoveToStatus(0); + break; + } + if (spaceRadius > front || (dotForward > 0.5f && hasCollided && !outOfOurWay && !ignoring)) + { + botMain->setMoveToStatus(9); + break; + } + if (!angleNegative && wideSpace && 0.0f > dot && back > spaceRadius) + { + botMain->setMoveToStatus(11); + break; + } + mode = 1.0f; + angle = -std::fabs(angle); + break; + case 4: + if (!hasCollided || (outOfOurWay && !obstacleAngleNegative)) + botMain->setMoveToStatus(6); + else if (spaceRadius > front || touching) + botMain->setMoveToStatus(13); + else + { + mode = 1.0f; + angle = -2.0f; + } + break; + case 5: + if (!hasCollided || (outOfOurWay && obstacleAngleNegative)) + botMain->setMoveToStatus(6); + else if (spaceRadius > front || touching) + botMain->setMoveToStatus(14); + else + { + mode = 1.0f; + angle = 2.0f; + } + break; + case 6: + if (!hasCollided || (passing && 0.3f > dotForward)) + { + botMain->setMoveToStatus(0.0f > angle ? 3 : 2); + break; + } + if (touching && !outOfOurWay && dotForward > 0.0f) + { + botMain->setMoveToStatus(avoidSide == 2 ? 14 : 13); + break; + } + if (front >= spaceRadius) + { + angle = avoidAngle; + break; + } + if (avoidSide == 2) + { + if (botMain->setAvoidSide(1) && !botMain->getIgnoreObstacles()) + { + botMain->setMoveToStatus(0); + botMain->setIgnoreObstacles(true); + } + else + { + botMain->setMoveToStatus(13); + } + } + else + { + if (botMain->setAvoidSide(2) && !botMain->getIgnoreObstacles()) + { + botMain->setMoveToStatus(0); + botMain->setIgnoreObstacles(true); + } + else + { + botMain->setMoveToStatus(14); + } + } + break; + case 8: + if (stuck) + { + mode = -1.0f; + angle = -angle; + reverseAngle(angle); + break; + } + if (dot > -0.5f || goalDistance > nearDistance + 5.0f || spaceRadius > back) + { + botMain->setMoveToStatus(0); + mode = 1.0f; + break; + } + if (-0.6f > dotForward && hasCollided) + { + botMain->setMoveToStatus(obstacleAngleNegative ? 3 : 2); + break; + } + mode = -1.0f; + reverseAngle(angle); + break; + case 9: + if (!angleNegative) + { + botMain->setMoveToStatus(dot > 0.0f ? 2 : 11); + break; + } + if (dot > 0.9f && front > spaceRadius) + botMain->setMoveToStatus(0); + else if (spaceRadius > back) + botMain->setMoveToStatus(3); + else + { + mode = -1.0f; + angle = std::fabs(angle); + } + break; + case 11: + if (angleNegative) + { + botMain->setMoveToStatus(dot > 0.0f ? 3 : 9); + break; + } + if (dot > 0.9f && front > spaceRadius) + botMain->setMoveToStatus(0); + else if (spaceRadius > back) + botMain->setMoveToStatus(2); + else + { + mode = -1.0f; + angle = -std::fabs(angle); + } + break; + case 12: + if (dot > 0.0f) + botMain->setMoveToStatus(0); + else if (nearDistance >= goalDistance && -0.6f > dot && back > spaceRadius) + botMain->setMoveToStatus(8); + else if (veryWideSpace) + botMain->setMoveToStatus(angleNegative ? 9 : 11); + else + { + mode = -1.0f; + reverseAngle(angle); + } + break; + case 13: + if (!hasCollided || (outOfOurWay && !obstacleAngleNegative)) + botMain->setMoveToStatus(6); + else if (spaceRadius > back) + botMain->setMoveToStatus(4); + mode = -1.0f; + angle = 2.0f; + break; + case 14: + if (!hasCollided || (outOfOurWay && obstacleAngleNegative)) + botMain->setMoveToStatus(6); + else if (spaceRadius > back) + botMain->setMoveToStatus(5); + mode = -1.0f; + angle = -2.0f; + break; + default: + break; + } + // 0x2ADE60 + if (speedLimit > slowDown) + speedLimit = slowDown; + if (slowDownStop) + angle = -2.0f; + return 1; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CarControl.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CarControl.h new file mode 100644 index 000000000..b44796897 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CarControl.h @@ -0,0 +1,37 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_CARCONTROL_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_CARCONTROL_H + +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { + +namespace io { class PlayerInput; } +namespace ai { + +class BAPAMoveTo; +class Bot; +class IPIControlInfo; +class IPIMobile; +class IPIPhysical; +class Information; + +// [INFERRED] a namespace: no vtable, no constructor, and the first argument is never `this`. +namespace CarControl +{ + int controlTowardsDirection(Information*, IPIControlInfo*, IPIMobile*, IPIPhysical*, io::PlayerInput*, float, float, float, float, float); // 0x2AAF40; [INFERRED] ELF int + int resetControls(Bot*, io::PlayerInput*, bool, bool, bool, float); // 0x2AB5F0; [INFERRED] ELF int + int actionStatusDecision(Bot*, Information*, const Vec2&, float, BAPAMoveTo*, float&, float&, float&, float&); // 0x2AB970; [INFERRED] ELF int +} + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_CARCONTROL_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CommonControls.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CommonControls.cpp new file mode 100644 index 000000000..41d191fd4 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CommonControls.cpp @@ -0,0 +1,477 @@ +// Shared vehicle steering helpers for CarControl and TankControl (libaidll.so CommonControls TU). +// static init: the guard object only (ELF 0x2B0910, __tcf_0 0x2B0970, _GLOBAL__I 0x2B09A0). +// Bodies recovered from the ELF listings (objdump with GOT/rodata resolved; Ghidra cross-check). +// Comparisons are written as compiled, so NaN takes the branch the x87/SSE code takes. +// [PLATFORM] the image keeps intermediate sums in x87 extended precision; the native build rounds +// each float operation. + +#include "CommonControls.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/BotNavigation.h" +#include "../AIBot/CommunicationAgent.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +#include +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +inline Information* lookupInformation(unsigned int handle) +{ + return informationManager->getInformation(handle); +} + +} // namespace + +// ELF 0x2AF110. Shortens the free space ahead (`front`) and behind (`back`) of `origin` along the +// unit direction `direction` by the obstacles the bot's navigation has collected: each other +// non-soldier object with a physical part (except `ignore` and the bot's own vehicle) whose +// smallest-radius sphere crosses the line within the current space limits the space to the +// sphere's near intersection. +void CommonControls::updateSpaceWithObstacles(Bot* bot, const Vec3& origin, const Vec3& direction, float& front, + float& back, unsigned int ignore) +{ + Information* const self = lookupInformation(bot->getCurrentEquipment()); + BotNavigation* const navigation = bot->getBotNavigation(); + const std::vector& obstacles = navigation->getObstacles(); + for (unsigned int i = 0; i < obstacles.size(); ++i) + { + const unsigned int handle = obstacles[i]; + if (handle == ignore) + continue; + Information* const obstacle = lookupInformation(handle); + if (self == obstacle || obstacle == 0) + continue; + IPIPhysical* const physical = obstacle->getPhysical(); + if (physical == 0 || obstacle->isOfType(ITSoldier)) + continue; + const float radius = physical->getSmallestRadius(); + const Vec3& position = obstacle->getPosition(); + Vec3 offset; + offset.x = position.x - origin.x; + offset.y = position.y - origin.y; + offset.z = position.z - origin.z; + const float along = direction.x * offset.x + direction.y * offset.y + direction.z * offset.z; + if (along > 0.0f) + { + if (!(along > radius + front)) + { + Vec3 perpendicular; + perpendicular.x = offset.x - direction.x * along; + perpendicular.y = offset.y - direction.y * along; + perpendicular.z = offset.z - direction.z * along; + const float distance = std::sqrt(perpendicular.x * perpendicular.x + perpendicular.y * perpendicular.y + + perpendicular.z * perpendicular.z); + if (!(distance > radius)) + { + const float half = std::sqrt(radius * radius - distance * distance); + const float space = along - half; + if (!(space > front)) + front = space; + } + } + } + else if (!(-along > radius + back)) + { + Vec3 perpendicular; + perpendicular.x = offset.x - direction.x * along; + perpendicular.y = offset.y - direction.y * along; + perpendicular.z = offset.z - direction.z * along; + const float distance = std::sqrt(perpendicular.x * perpendicular.x + perpendicular.y * perpendicular.y + + perpendicular.z * perpendicular.z); + if (!(distance > radius)) + { + const float half = std::sqrt(radius * radius - distance * distance); + const float space = -along - half; + if (!(space > back)) + back = space; + } + } + } +} + +// ELF 0x2AF500. Picks the obstacle the vehicle is about to hit. `forward` and `direction` are the +// unit heading and the desired direction (XZ), `velocity` the desired 2D velocity, `speed` its +// length and `speedSign` the sign of the forward speed (nothing is looked at while reversing). +// A candidate is a non-soldier obstacle within the look-ahead reach, ahead of the heading and +// within the combined radius of the heading line; the one closest to the line wins (low-angle +// ones only when they are the bot's collided object or there is none). With no candidate the +// collided object (`collided`, which also sets `collidedSeen` when it is still an obstacle) is +// kept. For the winner the body writes `dotForward` (its direction against the heading), +// `angleToObstacle`, `outOfOurWay` / `passing` (whether the heading / desired line clear its +// avoid circle), `touching`, the tangent angle `avoidAngle` (`tangentAngle` the direction to it), +// or, inside the avoid circle, the angle to the side's perpendicular (`tangentAngle` -666), and +// `obstacle`. Returns whether an obstacle was chosen; when the desired direction already leads +// away from it both handles are cleared and false is returned. +bool CommonControls::checkCollisions(Bot* bot, Information* info, IPIPhysical* physical, const Vec2& forward, + float& dotForward, float& angleToObstacle, bool& outOfOurWay, + const Vec2& velocity, const Vec2& direction, float speed, bool& passing, + unsigned int& obstacle, unsigned int& collided, bool& collidedSeen, + float& avoidAngle, float& tangentAngle, float speedSign, bool& touching, + AvoidSide side, bool tight) +{ + static float radiusTweak = 0.9f; // .data 0x4BCB84, not read by the body + static float obstacleRadiusTweak = 0.8f; // .data 0x4BCB88 + static float outOfOurWayTweak = 0.7f; // .data 0x4BCB8C + (void)radiusTweak; + + IPIMobile* const mobile = info->getMobile(); + const float radius = physical->getRadius(); + BotNavigation* const navigation = bot->getBotNavigation(); + const std::vector& obstacles = navigation->getObstacles(); + float bestDistanceSqr = 99999.0f; + dotForward = 0.0f; + collidedSeen = false; + const float lookAheadTime = 1.0f; + unsigned int best = 0xFFFFFFFFu; + for (unsigned int i = 0; i < obstacles.size(); ++i) + { + const unsigned int handle = obstacles[i]; + if (collided != 0xFFFFFFFFu && collided == handle) + collidedSeen = true; + if (0.0f > speedSign) + continue; + Information* const other = lookupInformation(handle); + if (info == other || other == 0) + continue; + IPIPhysical* const otherPhysical = other->getPhysical(); + if (otherPhysical == 0 || other->isOfType(ITSoldier)) + continue; + const float combinedRadius = otherPhysical->getRadius() + radius; + const Vec3& ownPosition = info->getPosition(); + const Vec3& otherPosition = other->getPosition(); + Vec3 offset; + offset.x = otherPosition.x - ownPosition.x; + offset.y = otherPosition.y - ownPosition.y; + offset.z = otherPosition.z - ownPosition.z; + Vec2 offset2; + offset2.x = offset.x; + offset2.y = offset.z; + const float distanceSqr = offset.x * offset.x + offset.y * offset.y + offset.z * offset.z; + const Vec3& ownSpeed = mobile->getSpeed(); + const Vec3 facing = info->getFaceing(); + const float minimumReach = (radius > 5.0f) ? radius : 5.0f; + const float reach = (facing.x * ownSpeed.x + facing.y * ownSpeed.y + facing.z * ownSpeed.z) * lookAheadTime + + minimumReach + combinedRadius; + if (distanceSqr > reach * reach) + continue; + if (distanceSqr > speed * speed) + { + Vec2 predicted; + predicted.x = offset2.x - velocity.x; + predicted.y = offset2.y - velocity.y; + if (predicted.x * predicted.x + predicted.y * predicted.y > combinedRadius * combinedRadius) + continue; + } + const float along = forward.x * offset2.x + forward.y * offset2.y; + if (0.0f > along) + continue; + const float length = std::sqrt(offset2.x * offset2.x + offset2.y * offset2.y); + const float cosine = along / length; + Vec2 perpendicular; + perpendicular.x = offset2.x - forward.x * along; + perpendicular.y = offset2.y - forward.y * along; + const float perpendicularSqr = perpendicular.x * perpendicular.x + perpendicular.y * perpendicular.y; + if (perpendicularSqr > combinedRadius * combinedRadius) + continue; + if (0.5f > cosine && collided != handle && collided != 0xFFFFFFFFu) + continue; + if (bestDistanceSqr > perpendicularSqr) + { + bestDistanceSqr = perpendicularSqr; + best = handle; + } + } + if (best == 0xFFFFFFFFu) + { + if (collidedSeen) + { + const unsigned int handle = collided; + best = lookupInformation(handle) ? handle : best; + } + if (best == 0xFFFFFFFFu) + return false; + } + Information* const target = lookupInformation(best); + if (target == 0) + return best != 0xFFFFFFFFu; + IPIPhysical* const targetPhysical = target->getPhysical(); + IPIMobile* const targetMobile = target->getMobile(); + if (targetMobile) + targetMobile->getSpeedMagnitude(); // result discarded + const float avoidRadius = targetPhysical->getRadius() * obstacleRadiusTweak + radius; + const float avoidRadiusSqr = avoidRadius * avoidRadius; + Vec2 ownPosition; + ownPosition.x = info->getPosition().x; + ownPosition.y = info->getPosition().z; + Vec2 targetPosition; + targetPosition.x = target->getPosition().x; + targetPosition.y = target->getPosition().z; + Vec2 toTarget; + toTarget.x = targetPosition.x - ownPosition.x; + toTarget.y = targetPosition.y - ownPosition.y; + const float distance = std::sqrt(toTarget.x * toTarget.x + toTarget.y * toTarget.y); + if (1e-05f > distance) + return false; + const float inverse = 1.0f / distance; + toTarget.x = toTarget.x * inverse; + toTarget.y = inverse * toTarget.y; + dotForward = toTarget.x * forward.x + toTarget.y * forward.y; + touching = targetPhysical->getRadius() + radius > distance; + Vec2 ahead = ownPosition; + const float aheadTime = tight ? 0.25f : 0.5f; + ahead.x = aheadTime * mobile->getSpeed().x + ahead.x; + ahead.y = aheadTime * mobile->getSpeed().z + ahead.y; + Vec2 toTargetAhead; + toTargetAhead.x = targetPosition.x - ahead.x; + toTargetAhead.y = targetPosition.y - ahead.y; + const float aheadDistance = std::sqrt(toTargetAhead.x * toTargetAhead.x + toTargetAhead.y * toTargetAhead.y); + const float aheadInverse = 1.0f / aheadDistance; + toTargetAhead.x = toTargetAhead.x * aheadInverse; + toTargetAhead.y = aheadInverse * toTargetAhead.y; + if (avoidRadius > aheadDistance) + { + // 0x2AFBAD: inside the avoid circle - steer along the side's perpendicular. + Vec2 sideDirection; + sideDirection.x = 0.0f; + sideDirection.y = 0.0f; + if (side == static_cast(2)) + { + sideDirection.x = toTargetAhead.y; + sideDirection.y = -toTargetAhead.x; + } + else + { + sideDirection.x = -toTargetAhead.y; + sideDirection.y = toTargetAhead.x; + } + avoidAngle = getSignedDiffAngleToDir(forward, sideDirection); + tangentAngle = -666.0f; + } + else + { + // 0x2AFE7D: the tangent past the avoid circle. + const float ratio = avoidRadius / aheadDistance; + float clamped = ratio; + if (-1.0f > ratio) + clamped = -1.0f; + else if (ratio > 1.0f) + clamped = 1.0f; + avoidAngle = std::asin(clamped); + const float angle = getSignedDiffAngleToDir(forward, toTargetAhead); + tangentAngle = angle; + if (side == static_cast(2)) + avoidAngle = angle + avoidAngle; + else + avoidAngle = angle - avoidAngle; + } + // 0x2AFC06: do the heading line and the desired line clear the target? + Vec2 headingPoint; + headingPoint.x = forward.x * dotForward * distance + ownPosition.x; + headingPoint.y = dotForward * forward.y * distance + ownPosition.y; + const float headingX = headingPoint.x - targetPosition.x; + const float headingY = headingPoint.y - targetPosition.y; + outOfOurWay = headingX * headingX + headingY * headingY > avoidRadiusSqr * outOfOurWayTweak; + const float alongDesired = toTarget.x * direction.x + toTarget.y * direction.y; + Vec2 desiredPoint; + desiredPoint.x = direction.x * alongDesired * distance + ownPosition.x; + desiredPoint.y = direction.y * alongDesired * distance + ownPosition.y; + const float desiredX = desiredPoint.x - targetPosition.x; + const float desiredY = desiredPoint.y - targetPosition.y; + bool clear = false; + if (desiredX * desiredX + desiredY * desiredY > avoidRadiusSqr) + clear = true; + else if (-0.1f > alongDesired && speedSign > 0.0f) + clear = true; + passing = clear; + if (0.0f > toTarget.x * direction.x + toTarget.y * direction.y + && forward.x * direction.x + forward.y * direction.y > 0.0f) + { + // 0x2AFD88: the desired direction already leads away from it. + collided = 0xFFFFFFFFu; + passing = true; + obstacle = 0xFFFFFFFFu; + outOfOurWay = true; + return false; + } + const float headingDot = forward.x * direction.x + forward.y * direction.y; + if (std::fabs(headingDot) > 0.85f) + angleToObstacle = getSignedDiffAngleToDir(direction, toTarget); + else + angleToObstacle = getSignedDiffAngleToDir(forward, toTarget); + obstacle = best; + return best != 0xFFFFFFFFu; +} + +// ELF 0x2AFF80. The speed limit for following the slowest vehicle ahead. At or below 2 m/s +// (`speed` is the signed forward speed) nothing is checked and 9999 is returned. Otherwise every +// obstacle whose sphere lies on the projected path within 15 m is rated by its speed along our +// heading minus 1 (at least 0); vehicles beyond 8 m (maxDist) or crossing our path count only +// when the relative speed is above 10 m/s, which also rates -20 and sets `stop` while the bot has +// no move-to status. The lowest rating is returned and its handle stored as the bot's slow-down +// target; a same-side object within 5 m (or a soldier ahead) is honked at when we carry a driver. +float CommonControls::checkSlowDown(Bot* bot, Information* info, const Vec3& velocity, float speed, + const Vec3& position, bool& stop) +{ + static float maxDist = 8.0f; // .data 0x4BCB90 + + stop = false; + if (2.0f >= speed) + return 9999.0f; + BotNavigation* const navigation = bot->getBotNavigation(); + const std::vector& obstacles = navigation->getObstacles(); + const Vec3 facing = info->getFaceing(); + const Vec3 facingAgain = info->getFaceing(); + const float facingDot = facingAgain.x * velocity.x + facingAgain.y * velocity.y + facingAgain.z * velocity.z; + float sign = 1.0f; + if (!(facingDot > 0.0f)) + sign = (0.0f > facingDot) ? -1.0f : 0.0f; + Vec3 heading; + heading.x = facing.x * sign; + heading.y = facing.y * sign; + heading.z = sign * facing.z; + float lowest = 9999.0f; + unsigned int lowestHandle = 0xFFFFFFFFu; + Information* honkTarget = 0; + IPIPhysical* const ownPhysical = info->getPhysical(); + IPIMobile* const ownMobile = info->getMobile(); + const float zero = 0.0f; + for (unsigned int i = 0; i < obstacles.size(); ++i) + { + Information* const other = lookupInformation(obstacles[i]); + if (other == 0 || other == info) + continue; + IPIPhysical* const otherPhysical = other->getPhysical(); + if (otherPhysical == 0) + continue; + if (other->isOfType(ITSoldier) && 0.0f >= otherPhysical->getHealth()) + continue; + IPIMobile* const otherMobile = other->getMobile(); + if (otherMobile == 0) + continue; + Information* const changeTarget = lookupInformation(bot->getChangeTarget()); + if (changeTarget && !changeTarget->isPrimary() + && changeTarget->getPrimaryObject(bot->getSide()) == obstacles[i]) + continue; + // 0x2B01AB: the centre of the other's sphere. + Vec3 offset; + offset.x = offset.y = offset.z = zero; + const Mat4& transformation = other->getTransformation(); + const Vec3 local = otherPhysical->getSphereLocalOffset(); + const float* const m = transformation.m; + offset.x = m[0] * local.x + m[4] * local.y + m[8] * local.z; + offset.y = m[1] * local.x + m[5] * local.y + m[9] * local.z; + offset.z = m[2] * local.x + m[6] * local.y + m[10] * local.z; + const Vec3& otherPosition = other->getPosition(); + Vec3 centre; + centre.x = offset.x + otherPosition.x; + centre.y = offset.y + otherPosition.y; + centre.z = offset.z + otherPosition.z; + Vec3 toCentre; + toCentre.x = centre.x - position.x; + toCentre.y = centre.y - position.y; + toCentre.z = centre.z - position.z; + float distance = std::sqrt(toCentre.x * toCentre.x + toCentre.y * toCentre.y + toCentre.z * toCentre.z); + const float otherRadius = otherPhysical->getSmallestRadius(); + const float radii = otherRadius + ownPhysical->getSmallestRadius(); + if (distance > 1e-05f) + { + const float inverse = 1.0f / distance; + toCentre.x = toCentre.x * inverse; + toCentre.y = toCentre.y * inverse; + toCentre.z = inverse * toCentre.z; + } + distance = distance - radii; + if (distance > 15.0f) + continue; + const float otherSpeed = otherMobile->getSpeedMagnitude(); + const float along = heading.x * toCentre.x + heading.y * toCentre.y + heading.z * toCentre.z; + const float reach = distance + radii; + Vec3 projected; + projected.x = heading.x * along * reach + position.x; + projected.y = heading.y * along * reach + position.y; + projected.z = heading.z * along * reach + position.z; + Vec3 miss; + miss.x = centre.x - projected.x; + miss.y = centre.y - projected.y; + miss.z = centre.z - projected.z; + if (miss.x * miss.x + miss.y * miss.y + miss.z * miss.z > radii * radii) + continue; + if (other->isOfType(ITSoldier)) + { + // 0x2B049C: a soldier ahead is only a horn candidate. + if (along > 0.0f && info->getSide() == other->getSide()) + honkTarget = other; + continue; + } + if (0.75f > along) + { + if (!(2.0f > distance)) + continue; + if (!(along > 0.0f)) + continue; + if (!(otherSpeed > 2.0f)) + continue; + } + // 0x2B054C + Vec3 otherVelocity = otherMobile->getSpeed(); + const bool moving = otherSpeed > 0.5f; + float rating = heading.x * otherVelocity.x + heading.y * otherVelocity.y + heading.z * otherVelocity.z - 1.0f; + if (!(rating > zero)) + rating = zero; + if (moving) + { + const float inverse = 1.0f / otherSpeed; + otherVelocity.x = otherVelocity.x * inverse; + otherVelocity.y = otherVelocity.y * inverse; + otherVelocity.z = otherVelocity.z * inverse; + } + const Vec3& otherSpeedVector = otherMobile->getSpeed(); + const Vec3& ownSpeedVector = ownMobile->getSpeed(); + Vec3 relative; + relative.x = otherSpeedVector.x - ownSpeedVector.x; + relative.y = otherSpeedVector.y - ownSpeedVector.y; + relative.z = otherSpeedVector.z - ownSpeedVector.z; + const bool fastApproach = relative.x * relative.x + relative.y * relative.y + relative.z * relative.z > 100.0f; + if (fastApproach && static_cast(bot)->getMoveToStatus() == 0) + { + rating = -20.0f; + stop = true; + } + if (distance > maxDist && !fastApproach) + continue; + const float otherDot = otherVelocity.x * heading.x + otherVelocity.y * heading.y + otherVelocity.z * heading.z; + if (moving && 0.6f > otherDot && otherDot > -0.75f && !fastApproach) + continue; + if (static_cast(bot)->getIgnoreObstacles() + && static_cast(bot)->getCollidedObject() == obstacles[i] && !fastApproach) + continue; + if (info->getSide() == other->getSide() && 5.0f > distance) + honkTarget = other; + if (lowest > rating) + { + lowest = rating; + lowestHandle = obstacles[i]; + } + } + if (honkTarget && info->getUnit()->isOccupied()) + bot->getCommunicationAgent()->honkHorn(honkTarget); + static_cast(bot)->setSlowDownToTarget(lowestHandle); + return lowest; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CommonControls.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CommonControls.h new file mode 100644 index 000000000..f90526c2a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CommonControls.h @@ -0,0 +1,38 @@ +// Shared vehicle steering helpers used by CarControl and TankControl (libaidll.so CommonControls TU). + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_COMMONCONTROLS_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_COMMONCONTROLS_H + +#include "../../../../Math/Vec3.h" +#include "../AIBotActionPlan/BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class IPIPhysical; +class Information; + +// [INFERRED] a namespace: no vtable, no constructor, and the first argument is never `this`. +namespace CommonControls +{ + void updateSpaceWithObstacles(Bot* bot, const Vec3& origin, const Vec3& direction, float& front, float& back, + unsigned int ignore); // 0x2AF110 + // 0x2AF500. Returns bool: CarControl::actionStatusDecision stores `al` (0x2AD375). + bool checkCollisions(Bot* bot, Information* info, IPIPhysical* physical, const Vec2& forward, float& dotForward, + float& angleToObstacle, bool& outOfOurWay, const Vec2& velocity, const Vec2& direction, + float speed, bool& passing, unsigned int& obstacle, unsigned int& collided, + bool& collidedSeen, float& avoidAngle, float& tangentAngle, float speedSign, + bool& touching, AvoidSide side, bool tight); + // 0x2AFF80. Returns the speed limit in st(0). + float checkSlowDown(Bot* bot, Information* info, const Vec3& velocity, float speed, const Vec3& position, + bool& stop); +} + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_COMMONCONTROLS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/ControlFunctions.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/ControlFunctions.cpp new file mode 100644 index 000000000..176cb94ff --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/ControlFunctions.cpp @@ -0,0 +1,622 @@ +// ControlFunctions: the shared regulator and geometry helpers of the plan-interpreter controls +// (attested TU `AI/AIDLL/AI/AIPlanInterpreter/ControlFunctions.cpp`, the path of changeReg's Debug). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32); every body carries its ELF address. x87 code +// was read in Intel syntax (llvm-objdump), which has no fsub(r)p/fdiv(r)p operand swap, and checked +// against the Ghidra decompilation. Parameter names are [INFERRED] from their use. +// +// The *Debug variants are the same computation as their non-debug twins in this build (the debug +// output was compiled out); they stay separate functions because the image has both symbols. + +// static init: ELF 0x2B2080 (__tcf_0 0x2B20E0, _GLOBAL__I 0x2B2110): 's Init object only. +#include + +#include "ControlFunctions.h" + +#include +#include + +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../../Core/Debug.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// [CHOSEN, not recovered] helpers for this TU's readability. The image indexes Vec2 as float[2] +// (`[v + 4*axis]`), and every regulator reads the frame time through IBFTimer slot +0x0C and +// narrows it to float (`fstp dword` / `fld dword` right after the call). +inline float& axisOf(Vec2& v, int axis) { return (&v.x)[axis]; } +inline float axisOf(const Vec2& v, int axis) { return (&v.x)[axis]; } + +inline float frameTime() +{ + return static_cast(static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease()); +} + +// The three-way sign the regulators compute inline: 1 above zero, -1 below, 0 at zero. NaN fails +// the `<= 0` test and gives 1, as in the image. +inline float signOf(float v) +{ + if (v <= 0.0f) + return (0.0f <= v) ? 0.0f : -1.0f; + return 1.0f; +} + +// The inline clamp at the end of every regulator (`fld -1; fucomi; ... fcmov`): NaN gives -1. +inline float clampUnit(float v) +{ + if (!(-1.0f <= v)) + return -1.0f; + if (1.0f < v) + return 1.0f; + return v; +} + +// One axis of getBoxIntersections (the image repeats the same code for x and then for y with the +// axes swapped). Box A is [aMin, aMax], box B is [bMin, bMax]. Returns false when the intervals are +// disjoint; lo/hi receive the overlap on `axis`. When one interval contains the other the image +// takes the overlap as a segment at a fixed coordinate of the other axis (`spans`, `other`). +bool boxAxisIntersection(const Vec2& aMin, const Vec2& aMax, const Vec2& bMin, const Vec2& bMax, + int axis, float& lo, float& hi, bool& spans, float& other) +{ + const int o = 1 - axis; + const float aMaxV = axisOf(aMax, axis); + const float bMaxV = axisOf(bMax, axis); + spans = false; + other = 0.0f; + if (bMaxV <= aMaxV) + { + const float aMinV = axisOf(aMin, axis); + if (aMaxV != bMaxV) + { + if (bMaxV < aMinV) + return false; + if (aMinV != bMaxV) + { + const float bMinV = axisOf(bMin, axis); + if (aMinV < bMinV) + { + // B lies strictly inside A on this axis. + spans = true; + other = axisOf(aMax, o); + if (axisOf(bMax, o) <= other) + other = axisOf(aMin, o); + lo = bMinV; + hi = bMaxV; + return true; + } + } + lo = aMinV; + hi = bMaxV; + return true; + } + // aMax == bMax + lo = axisOf(bMin, axis); + if (lo <= aMinV) + lo = aMinV; + hi = bMaxV; + return true; + } + const float bMinV = axisOf(bMin, axis); + if (!(bMinV <= aMaxV)) + return false; + if (aMaxV != bMinV) + { + const float aMinV = axisOf(aMin, axis); + if (!(aMinV < bMinV)) + { + // A lies inside B on this axis. + spans = true; + other = axisOf(bMax, o); + if (axisOf(aMax, o) <= other) + other = axisOf(bMin, o); + lo = aMinV; + hi = aMaxV; + return true; + } + } + lo = bMinV; + hi = aMaxV; + return true; +} + +} // namespace + +// ELF 0x2B09C0. Where the line through `point` (direction perpendicular to `normal`) leaves the box +// boxMin..boxMax; `point` must lie in the box. A box that is flat on either axis returns the point. +int getIntersection(const Vec2& boxMin, const Vec2& boxMax, const Vec2& normal, const Vec2& point, Vec2& out) +{ + const float px = point.x; + const float x0 = boxMin.x; + if (px < x0) + return 0; + const float x1 = boxMax.x; + if (x1 < px) + return 0; + const float py = point.y; + const float y0 = boxMin.y; + if (py < y0) + return 0; + const float y1 = boxMax.y; + if (y1 < py) + return 0; + + const float dx = x1 - x0; + const float dy = y1 - y0; + if (dx == 0.0f || dy == 0.0f) + { + out.x = px; + out.y = py; + return 1; + } + + const float ny = normal.y; + const float nx = normal.x; + const float mnx = -nx; + const float c = -(ny * px + py * mnx); + const float at0 = ny * x0 + mnx * y0 + c; + const float at1 = ny * x1 + mnx * y1 + c; + if (normal.y <= 0.0f) + { + if (normal.y < 0.0f) + { + const float t = -at0 / (dx * ny); + if (0.0f <= t && t <= 1.0f) + { + out.y = y0; + out.x = x0 + dx * t; + return 1; + } + } + } + else + { + const float t = at1 / (dx * ny); + if (0.0f <= t && t <= 1.0f) + { + out.y = y1; + out.x = x1 - dx * t; + return 1; + } + } + + if (0.0f <= nx) + { + if (nx <= 0.0f) + return 0; + const float t = at1 / (dy * mnx); + if (t < 0.0f) + return 0; + if (1.0f < t) + return 0; + out.x = x1; + out.y = y1 - t * dy; + } + else + { + const float t = -at0 / (dy * mnx); + if (t < 0.0f || 1.0f < t) + return 0; + out.x = x0; + out.y = t * dy + y0; + } + return 1; +} + +// ELF 0x2B0C30. Stepped proportional-derivative regulator for a linear quantity: `rate` is the +// change of `current` per second, the error is taken at the look-ahead point, and the step factor +// depends on the error relative to |target| in units of `scale`. `control` is clamped to [-1, 1]. +void updateLinear(float target, float current, float previous, float& control, float gain, float lookAhead, float scale) +{ + const float dt = frameTime(); + const float rate = (current - previous) / dt; + float error = target - (lookAhead * rate + current); + const float sign = signOf(error); + if (error < 0.0f) + error = -error; + float relative = error; + if (target != 0.0f) + relative = error / std::fabs(target); + + float step; + if (0.0f < rate * sign) + { + // already moving towards the target + if (relative < scale * 0.01f) + step = 0.02f; + else if (relative < scale * 0.05f) + step = 0.27f; + else + step = (relative < scale * 0.1f) ? 0.55f : 1.0f; + } + else + { + if (relative < scale * 0.01f) + return; + if (relative < scale * 0.05f) + step = 0.02f; + else if (relative < scale * 0.1f) + step = 0.27f; + else + step = (relative < scale * 0.4f) ? 0.55f : 1.0f; + } + control = control - step * dt * sign * gain * error; + control = clampUnit(control); +} + +// ELF 0x2B0DF0. Same computation as updateLinear (see the file comment). +void updateLinearDebug(float target, float current, float previous, float& control, float gain, float lookAhead, float scale) +{ + const float dt = frameTime(); + const float rate = (current - previous) / dt; + float error = target - (lookAhead * rate + current); + const float sign = signOf(error); + if (error < 0.0f) + error = -error; + float relative = error; + if (target != 0.0f) + relative = error / std::fabs(target); + + float step; + if (0.0f < rate * sign) + { + if (relative < scale * 0.01f) + step = 0.02f; + else if (relative < scale * 0.05f) + step = 0.27f; + else + step = (relative < scale * 0.1f) ? 0.55f : 1.0f; + } + else + { + if (relative < scale * 0.01f) + return; + if (relative < scale * 0.05f) + step = 0.02f; + else if (relative < scale * 0.1f) + step = 0.27f; + else + step = (relative < scale * 0.4f) ? 0.55f : 1.0f; + } + control = control - step * dt * sign * gain * error; + control = clampUnit(control); +} + +// ELF 0x2B0FE0. Angle regulator: `angle` is the remaining angle (radians), `angleChange` its change +// over the last frame. The thresholds are 0.5, 1, 2 and 4 degrees times `scale`; the gains are +// 0.01, 0.2, 0.5, 0.8, 1 and 1.5 times 180/pi (57.2957764). +void updateAngle(float angle, float angleChange, float& control, float gain, float lookAhead, float scale) +{ + const float dt = frameTime(); + const float rate = angleChange / dt; + float error = rate * lookAhead + angle; + const float sign = signOf(error); + if (error < 0.0f) + error = -error; + + float k; + if (0.0f < rate * sign) + { + if (error < scale * 0.0174532924f) + k = 28.6478882f; + else + k = (scale * 0.0349065848f <= error) ? 85.9436646f : 57.2957764f; + } + else + { + if (error < scale * 0.00872664619f) + return; + if (error < scale * 0.0174532924f) + k = 0.572957754f; + else if (error < scale * 0.0349065848f) + k = 11.4591551f; + else + k = (scale * 0.0698131695f <= error) ? 57.2957764f : 45.8366203f; + } + control = control - sign * gain * dt * error * k; + control = clampUnit(control); +} + +// ELF 0x2B1170. Same computation as updateAngle. +void updateAngleDebug(float angle, float angleChange, float& control, float gain, float lookAhead, float scale) +{ + const float dt = frameTime(); + const float rate = angleChange / dt; + float error = rate * lookAhead + angle; + const float sign = signOf(error); + if (error < 0.0f) + error = -error; + + float k; + if (0.0f < rate * sign) + { + if (error < scale * 0.0174532924f) + k = 28.6478882f; + else + k = (scale * 0.0349065848f <= error) ? 85.9436646f : 57.2957764f; + } + else + { + if (error < scale * 0.00872664619f) + return; + if (error < scale * 0.0174532924f) + k = 0.572957754f; + else if (error < scale * 0.0349065848f) + k = 11.4591551f; + else + k = (scale * 0.0698131695f <= error) ? 57.2957764f : 45.8366203f; + } + control = control - sign * gain * dt * error * k; + control = clampUnit(control); +} + +// ELF 0x2B1320. Intersection of the axis-aligned segment c..d with the box a..b. When `axis` +// differs from `lineAxis` the result is the single crossing point out1 (isSegment = false); +// otherwise the segment runs along `axis` and the result is the overlap out1..out2 (isSegment = true). +int getLineIntersections(Vec2& a, Vec2& b, Vec2& c, Vec2& d, Vec2& out1, Vec2& out2, bool& isSegment, int axis, int lineAxis) +{ + if (axis != lineAxis) + { + const float fixed = axisOf(a, lineAxis); + if (fixed < axisOf(c, lineAxis)) + return 0; + if (axisOf(d, lineAxis) < fixed) + return 0; + const float v = axisOf(c, axis); + if (v < axisOf(a, axis)) + return 0; + if (v <= axisOf(b, axis)) + { + axisOf(out1, axis) = v; + axisOf(out1, lineAxis) = axisOf(a, lineAxis); + isSegment = false; + return 1; + } + return 0; + } + + const int o = (axis + 1) % 2; + if (axisOf(d, o) != axisOf(c, o)) + return 0; + const float dv = axisOf(d, axis); + if (dv <= axisOf(a, axis)) + return 0; + const float bv = axisOf(b, axis); + if (bv < axisOf(c, axis)) + return 0; + out1 = (axisOf(c, axis) <= axisOf(a, axis)) ? a : c; + out2 = (dv <= bv) ? d : b; + isSegment = true; + return 1; +} + +// ELF 0x2B1490. Overlap of the boxes aMin..aMax and bMin..bMax, as the segment outMin..outMax. +int getBoxIntersections(Vec2& aMin, Vec2& aMax, Vec2& bMin, Vec2& bMax, Vec2& outMin, Vec2& outMax) +{ + float lo, hi, other; + bool spans; + if (!boxAxisIntersection(aMin, aMax, bMin, bMax, 0, lo, hi, spans, other)) + return 0; + outMin.x = lo; + outMax.x = hi; + if (spans) + { + outMin.y = other; + outMax.y = other; + return 1; + } + if (!boxAxisIntersection(aMin, aMax, bMin, bMax, 1, lo, hi, spans, other)) + return 0; + outMin.y = lo; + outMax.y = hi; + if (spans) + { + outMin.x = other; + outMax.x = other; + } + return 1; +} + +// ELF 0x2B17E0 +bool isInBox(const Vec2& point, const Vec2& boxMin, const Vec2& boxMax) +{ + bool aboveMin = false; + if (boxMin.x <= point.x && boxMin.y <= point.y) + aboveMin = true; + bool insideX = false; + if (aboveMin && point.x <= boxMax.x) + insideX = true; + return insideX && point.y <= boxMax.y; +} + +// ELF 0x2B1870. The angle regulator with an outer limit: the level is the larger of the remaining +// angle in units of `limitDegrees` and |limitValue| / limitRange. +void updateAngleOuterLimit(float angle, float angleChange, float& control, float gain, float lookAhead, float limitDegrees, float limitValue, float limitRange) +{ + const float dt = frameTime(); + const float rate = angleChange / dt; + const float error = rate * lookAhead + angle; + float sign; + if (error <= 0.0f) + sign = (error < 0.0f) ? -1.0f : 0.0f; + else + sign = 1.0f; + const float ratio = error / (limitDegrees * 0.0174532924f); + float level = std::fabs(limitValue) / limitRange; + if (std::fabs(limitValue) / limitRange <= ratio) + level = ratio; + internalAngle(error, level, sign * gain * dt, rate, control); +} + +// ELF 0x2B1930. Same computation as updateAngleOuterLimit. +void updateAngleOuterLimitDebug(float angle, float angleChange, float& control, float gain, float lookAhead, float limitDegrees, float limitValue, float limitRange) +{ + const float dt = frameTime(); + const float rate = angleChange / dt; + const float error = rate * lookAhead + angle; + float sign; + if (error <= 0.0f) + sign = (error < 0.0f) ? -1.0f : 0.0f; + else + sign = 1.0f; + const float ratio = error / (limitDegrees * 0.0174532924f); + float level = std::fabs(limitValue) / limitRange; + if (std::fabs(limitValue) / limitRange <= ratio) + level = ratio; + internalAngle(error, level, sign * gain * dt, rate, control); +} + +// ELF 0x2B1A00. The angle regulator limited by the angular rate: the level is the larger of the +// remaining angle in units of `limitDegrees` and |rate| / maxRate. +void updateAngleAccelerationLimit(float angle, float angleChange, float& control, float gain, float lookAhead, float limitDegrees, float maxRate) +{ + const float dt = frameTime(); + const float rate = angleChange / dt; + const float error = rate * lookAhead + angle; + float sign; + if (error <= 0.0f) + sign = (error < 0.0f) ? -1.0f : 0.0f; + else + sign = 1.0f; + const float ratio = error / (limitDegrees * 0.0174532924f); + float level = std::fabs(rate) / maxRate; + if (std::fabs(rate) / maxRate <= ratio) + level = ratio; + internalAngle(error, level, sign * gain * dt, rate, control); +} + +// ELF 0x2B1AC0. Same computation as updateAngleAccelerationLimit. +void updateAngleAccelerationLimitDebug(float angle, float angleChange, float& control, float gain, float lookAhead, float limitDegrees, float maxRate) +{ + const float dt = frameTime(); + const float rate = angleChange / dt; + const float error = rate * lookAhead + angle; + float sign; + if (error <= 0.0f) + sign = (error < 0.0f) ? -1.0f : 0.0f; + else + sign = 1.0f; + const float ratio = error / (limitDegrees * 0.0174532924f); + float level = std::fabs(rate) / maxRate; + if (std::fabs(rate) / maxRate <= ratio) + level = ratio; + internalAngle(error, level, sign * gain * dt, rate, control); +} + +// ELF 0x2B1B90. The stepped gain of the limited angle regulators; `level` is in limit units +// (thresholds 0.5, 1, 2, 4). +void internalAngle(float error, float level, float factor, float rate, float& control) +{ + const float sign = signOf(error); + if (error < 0.0f) + error = -error; + + float k; + if (0.0f < sign * rate) + { + if (level < 1.0f) + k = 28.6478882f; + else + k = (level < 2.0f) ? 57.2957764f : 85.9436646f; + } + else + { + if (level < 0.5f) + return; + if (level < 1.0f) + k = 0.572957754f; + else if (level < 2.0f) + k = 11.4591551f; + else + k = (level < 4.0f) ? 45.8366203f : 57.2957764f; + } + control = control - factor * error * k; + control = clampUnit(control); +} + +// ELF 0x2B1CE0. Adaptive bang-bang regulator. It estimates the response `gain` (rate change per +// second per unit of the last control change, low-pass 0.8/0.2, accepted only when it is below +// twice the current estimate or the estimate is still ~0), predicts the travel until the rate is +// zero and pushes, brakes or coasts. `previousValue`/`previousRate` are the caller's state. +void regulator(float target, float current, float& previousValue, float& previousRate, float& controlChange, float& gain, float strength, float& control) +{ + const float dt = frameTime(); + const float rate = (previousValue - current) / dt; + float g; + if (controlChange == 0.0f) + { + g = gain; + } + else + { + const float measured = ((rate - previousRate) / dt) / controlChange; + g = gain; + if (std::fabs(measured) < std::fabs(g) + std::fabs(g) || g < 1e-06f) + { + g = g * 0.8f + measured * 0.2f; + gain = g; + } + } + + const float diff = target - current; + const float sign = signOf(diff); + const float time = rate / std::fabs(g); + const float travel = -sign * g * time * time + rate * time; + const float remaining = target - (current + travel); + const float remainingSign = signOf(remaining); + if (remaining != 0.0f) + { + float next; + if (sign != remainingSign) + { + controlChange = strength * sign + control; + next = -sign * strength; + } + else + { + if (std::fabs(travel) * 10.0f <= std::fabs(diff)) + { + controlChange = control - sign * strength; + control = sign * strength; + previousValue = current; + previousRate = rate; + return; + } + next = (((rate * time + std::fabs(diff)) * -2.0f) / (time * time)) * strength * sign; + controlChange = control - next; + } + control = next; + } + previousValue = current; + previousRate = rate; +} + +// ELF 0x2B1EF0. A retired regulator: it clamps `value` into `control` and then reports that it +// must not be used (an Error Debug, which aborts in this build). +void changeReg(float value, float, float, float, float&, float& control) +{ + static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease(); // result unused + control = value; + control = clampUnit(value); + Debug(DebugTypeError, "AI/AIDLL/AI/AIPlanInterpreter/ControlFunctions.cpp", 1065, "") + << "Not using changeReg!"; +} + +// ELF 0x2B2030. Clamped proportional step: -1 below -1, else 1 above 1, else the difference (NaN +// passes through, unlike clampUnit: the order of the two tests is reversed here). +void simpleReg(float target, float current, float, float& control) +{ + const float diff = target - current; + if (-1.0f > diff) + control = -1.0f; + else + control = (diff > 1.0f) ? 1.0f : diff; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/ControlFunctions.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/ControlFunctions.h new file mode 100644 index 000000000..9b66ceaf3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/ControlFunctions.h @@ -0,0 +1,47 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_CONTROLFUNCTIONS_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_CONTROLFUNCTIONS_H + +#include "../../../AIInterface/BFKnowledge/SoldierPose.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +struct Mat4; +namespace io { class PlayerInput; } +namespace ai { + +class Bot; +class BAPAMoveTo; +class IPIControlInfo; +class IPIMobile; +class IPIPhysical; +class Information; + +int getIntersection(const Vec2&, const Vec2&, const Vec2&, const Vec2&, Vec2&); // 0x2B09C0; [INFERRED] ELF int +void updateLinear(float, float, float, float&, float, float, float); // 0x2B0C30; [INFERRED] ELF void +void updateLinearDebug(float, float, float, float&, float, float, float); // 0x2B0DF0; [INFERRED] ELF void +void updateAngle(float, float, float&, float, float, float); // 0x2B0FE0; [INFERRED] ELF void +void updateAngleDebug(float, float, float&, float, float, float); // 0x2B1170; [INFERRED] ELF void +int getLineIntersections(Vec2&, Vec2&, Vec2&, Vec2&, Vec2&, Vec2&, bool&, int, int); // 0x2B1320; [INFERRED] ELF int +int getBoxIntersections(Vec2&, Vec2&, Vec2&, Vec2&, Vec2&, Vec2&); // 0x2B1490; [INFERRED] ELF int +bool isInBox(const Vec2&, const Vec2&, const Vec2&); // 0x2B17E0; [INFERRED] ELF bool +void updateAngleOuterLimit(float, float, float&, float, float, float, float, float); // 0x2B1870; [INFERRED] ELF void +void updateAngleOuterLimitDebug(float, float, float&, float, float, float, float, float); // 0x2B1930; [INFERRED] ELF void +void updateAngleAccelerationLimit(float, float, float&, float, float, float, float); // 0x2B1A00; [INFERRED] ELF void +void updateAngleAccelerationLimitDebug(float, float, float&, float, float, float, float); // 0x2B1AC0; [INFERRED] ELF void +void internalAngle(float, float, float, float, float&); // 0x2B1B90; [INFERRED] ELF void +void regulator(float, float, float&, float&, float&, float&, float, float&); // 0x2B1CE0; [INFERRED] ELF void +void changeReg(float, float, float, float, float&, float&); // 0x2B1EF0; [INFERRED] ELF void +void simpleReg(float, float, float, float&); // 0x2B2030; [INFERRED] ELF void + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_CONTROLFUNCTIONS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveTo.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveTo.cpp new file mode 100644 index 000000000..442fff5fe --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveTo.cpp @@ -0,0 +1,101 @@ +// Boat movement entry for BAPAMoveTo. Attested TU: EntryBoatMoveTo.cpp. + +// static init: ELF 0x2B2520 (__tcf_0 0x2B2580, _GLOBAL__I 0x2B25B0): 's Init object only. +#include + +#include "EntryBoatMoveTo.h" + +#include "BoatControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2B2150 (C1; C2 0x2B2130). +EntryBoatMoveTo::EntryBoatMoveTo() +{ +} + +// ELF 0x2B2190 (D1; D2 0x2B2170, D0 0x2B21B0). +EntryBoatMoveTo::~EntryBoatMoveTo() +{ +} + +// ELF 0x2B2630. +int EntryBoatMoveTo::getTargetId() +{ + return 7; +} + +// ELF 0x2B21F0. The boat entry updates the path, releases movement inputs on arrival or failure, +// and otherwise steers towards the next point. resetControls may also update done. +bool EntryBoatMoveTo::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveTo* const moveTo = static_cast(script); + Vec2 point; + point.x = point.y = 0.0f; + Vec2 position; + position.x = position.y = 0.0f; + done = false; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info || !info->getMobile() || !info->getPhysical()) + { + done = true; + ok = false; + return true; + } + IAIObjectPhysical* const physical = info->getAIObject()->getPhysical(); + if (!physical->hasPhysicsEnabled()) + physical->enablePhysics(info->getSide()); + if (!info->getMobile() || !info->getControlInfo()) + { + done = true; + ok = false; + return true; + } + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + done = false; + bool arrived; + ok = static_cast(moveTo->update(point, done, arrived, 0.0f)) != 0; + if (!ok) + { + ok = static_cast(BoatControl::resetControls(bot, true, false, false, done)) != 0; + done = true; + return true; + } + if (arrived || done) + { + ok = static_cast(BoatControl::resetControls(bot, true, false, false, done)) != 0; + return true; + } + vec3ToVec2XZ(info->getPosition(), position); + Vec2 direction; + direction.x = point.x - position.x; + direction.y = point.y - position.y; + const float distance = std::sqrt(direction.x * direction.x + direction.y * direction.y); + if (distance > 1e-05f) + { + const float inverse = 1.0f / distance; + direction.x = direction.x * inverse; + direction.y = inverse * direction.y; + } + ok = static_cast(BoatControl::towardsDirection(bot, info, direction, distance, moveTo, bot->getInput(), 1e9f)) != 0; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveTo.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveTo.h new file mode 100644 index 000000000..1cb834cf9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveTo.h @@ -0,0 +1,27 @@ +// Boat movement entry for BAPAMoveTo. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYBOATMOVETO_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYBOATMOVETO_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryBoatMoveTo - statement type 7. +class EntryBoatMoveTo : public BAPEntry +{ +public: + EntryBoatMoveTo(); + virtual ~EntryBoatMoveTo(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYBOATMOVETO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToDirection.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToDirection.cpp new file mode 100644 index 000000000..3f72730b2 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToDirection.cpp @@ -0,0 +1,129 @@ +// EntryBoatMoveToDirection (split out of BAPEntries.cpp by S0, bodies unchanged). + +// static init: ELF 0x2B31E0 (__tcf_0 0x2B3240, _GLOBAL__I 0x2B3270): 's Init object only. +#include + +#include "EntryBoatMoveToDirection.h" + +#include "ControlFunctions.h" +#include "VehicleControlInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveToDirection.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../../../../IO/Input/PlayerInput.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2B2660 (C1; C2 0x2B2640). +EntryBoatMoveToDirection::EntryBoatMoveToDirection() +{ +} + +// ELF 0x2B26A0 (D1; D2 0x2B2680, D0 0x2B26C0). +EntryBoatMoveToDirection::~EntryBoatMoveToDirection() +{ +} + +// ELF 0x2B3290. +int EntryBoatMoveToDirection::getTargetId() +{ + return 8; +} + +// ELF 0x2B2700. +bool EntryBoatMoveToDirection::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveToDirection* const moveTo = static_cast(script); + Vec2 position = {0.0f, 0.0f}; + Vec2 facing = {0.0f, 0.0f}; + Vec2 normal = {0.0f, 0.0f}; + Vec2 point = {0.0f, 0.0f}; + Vec2 targetFacing = {0.0f, 0.0f}; + Vec2 targetNormal = {0.0f, 0.0f}; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + return true; + } + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + done = false; + const Mat4 transformation = info->getTransformation(); + const Vec3 forward = {transformation.m[8], transformation.m[9], transformation.m[10]}; + const Vec3 position3 = info->getPosition(); + const float magnitude = info->getMobile()->getSpeedMagnitude(); + const Vec3& speed = info->getMobile()->getSpeed(); + const float speedDot = forward.x * speed.x + forward.y * speed.y + forward.z * speed.z; + const float sign = speedDot > 0.0f ? 1.0f : (speedDot < 0.0f ? -1.0f : 0.0f); + const float signedSpeed = sign * magnitude; + const float radius = info->getMobile()->getTurnRadius(); + // The shipped caller stores only al and continues regardless of the update result. + ok = static_cast(moveTo->update(point, done)) != 0; + vec3ToVec2XZ(position3, position); + vec3ToVec2XZ(forward, facing); + vec3ToVec2XZ(moveTo->m_direction, targetFacing); + getNormal(facing, normal); + vehiclecontrol::normalizeVec2(normal); + getNormal(targetFacing, targetNormal); + vehiclecontrol::normalizeVec2(targetNormal); + Vec2 direction = {(radius * targetNormal.x + point.x) - (radius * normal.x + position.x), + (radius * targetNormal.y + point.y) - (radius * normal.y + position.y)}; + const float length = std::sqrt(direction.x * direction.x + direction.y * direction.y); + if (length > 1e-05f) + { + const float inverse = 1.0f / length; + direction.x *= inverse; + direction.y *= inverse; + } + const auto clampCos = [](float value) { + if (value < -1.0f) return -1.0f; + if (value > 1.0f) return 1.0f; + return value; + }; + float targetAngle = 0.0f; + if (length < radius * 0.2f) + moveTo->unimplementedDirectionSlot11(2); + else + { + targetAngle = std::acos(clampCos(direction.x * normal.x + direction.y * normal.y)) - 1.5707964f; + if (direction.x * facing.x + direction.y * facing.y < 0.0f) + { + const float angleSign = targetAngle > 0.0f ? 1.0f : (targetAngle < 0.0f ? -1.0f : 0.0f); + targetAngle = angleSign * 3.1415927f - targetAngle; + } + if (moveTo->unimplementedDirectionSlot10() == 1 || std::fabs(targetAngle) < 0.18325958f) + moveTo->unimplementedDirectionSlot11(1); + else + targetAngle = -1.5707964f; + } + const float maximum = info->getMobile()->getMaxSpeed(); + info->getMobile()->getVehicleNumber(); + io::PlayerInput* const input = bot->getInput(); + float turnInput = (input->mappingFlags & 1ULL) ? input->inputs[0] : 0.0f; + float throttle = (input->mappingFlags & 8ULL) ? input->inputs[3] : 0.0f; + const float previousDot = normal.x * moveTo->m_state68.y + normal.y * moveTo->m_state68.z; + updateAngle(targetAngle, std::acos(clampCos(previousDot)) - 1.5707964f, turnInput, 1.0f, 1.0f, 1.5f); + updateLinear(maximum, signedSpeed, moveTo->m_state68.x, throttle, -1.0f, 1.0f, 1.0f); + moveTo->m_state68.y = facing.x; + moveTo->m_state68.z = facing.y; + moveTo->m_state68.x = signedSpeed; + io::PlayerInput* const output = bot->getInput(); + if (output->mappingFlags & 1ULL) + output->inputs[0] = turnInput; + bot->getInput()->setInput(static_cast(3), throttle); + ok = true; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToDirection.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToDirection.h new file mode 100644 index 000000000..65a4f8831 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToDirection.h @@ -0,0 +1,27 @@ +// EntryBoatMoveToDirection: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYBOATMOVETODIRECTION_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYBOATMOVETODIRECTION_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryBoatMoveToDirection - statement type 8. +class EntryBoatMoveToDirection : public BAPEntry +{ +public: + EntryBoatMoveToDirection(); + virtual ~EntryBoatMoveToDirection(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYBOATMOVETODIRECTION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToObject.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToObject.cpp new file mode 100644 index 000000000..ebb1f3956 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToObject.cpp @@ -0,0 +1,108 @@ +// Boat movement entry for an object target. Attested TU: EntryBoatMoveToObject.cpp. + +// static init: ELF 0x2B3710 (__tcf_0 0x2B3770, _GLOBAL__I 0x2B37A0): 's Init object only. +#include + +#include "EntryBoatMoveToObject.h" + +#include "BoatControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFGameEffector.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2B32C0 (C1; C2 0x2B32A0). +EntryBoatMoveToObject::EntryBoatMoveToObject() +{ +} + +// ELF 0x2B3300 (D1; D2 0x2B32E0, D0 0x2B3320). +EntryBoatMoveToObject::~EntryBoatMoveToObject() +{ +} + +// ELF 0x2B37C0. +int EntryBoatMoveToObject::getTargetId() +{ + return 9; +} + +// ELF 0x2B3360. A missing target finishes successfully. On the movement path the position is +// read both before isFinished and after update; a stuck move asks the game effector to suicide. +bool EntryBoatMoveToObject::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveTo* const moveTo = static_cast(script); + Vec2 point; + point.x = point.y = 0.0f; + Vec2 position; + position.x = position.y = 0.0f; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info || !info->getMobile() || !info->getPhysical()) + { + done = true; + ok = false; + return true; + } + if (!informationManager->getInformation(moveTo->getObject())) + { + done = true; + ok = true; + return true; + } + IAIObjectPhysical* const physical = info->getAIObject()->getPhysical(); + if (!physical->hasPhysicsEnabled()) + physical->enablePhysics(info->getSide()); + vec3ToVec2XZ(info->getPosition(), position); + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + done = false; + bool arrived; + ok = static_cast(moveTo->update(point, done, arrived, 0.0f)) != 0; + if (!ok) + { + ok = static_cast(BoatControl::resetControls(bot, true, false, false, done)) != 0; + done = true; + return true; + } + if (arrived || done) + { + ok = static_cast(BoatControl::resetControls(bot, true, false, false, done)) != 0; + return true; + } + vec3ToVec2XZ(info->getPosition(), position); + Vec2 direction; + direction.x = point.x - position.x; + direction.y = point.y - position.y; + const float distance = std::sqrt(direction.x * direction.x + direction.y * direction.y); + if (distance > 1e-05f) + { + const float inverse = 1.0f / distance; + direction.x = direction.x * inverse; + direction.y = inverse * direction.y; + } + ok = static_cast(BoatControl::towardsDirection(bot, info, direction, distance, moveTo, bot->getInput(), 1e9f)) != 0; + if (moveTo->isStuck()) + { + IAIPlayer* const player = bot->getPlayer(); + static_cast(CommonSingletonServer::m_iaiGameEffector)->suicide(player); + } + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToObject.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToObject.h new file mode 100644 index 000000000..f69ff5d17 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToObject.h @@ -0,0 +1,27 @@ +// Boat movement entry for an object target. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYBOATMOVETOOBJECT_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYBOATMOVETOOBJECT_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryBoatMoveToObject - statement type 9. +class EntryBoatMoveToObject : public BAPEntry +{ +public: + EntryBoatMoveToObject(); + virtual ~EntryBoatMoveToObject(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYBOATMOVETOOBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatResetControls.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatResetControls.cpp new file mode 100644 index 000000000..8635fff91 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatResetControls.cpp @@ -0,0 +1,56 @@ +// EntryBoatResetControls (split out of BAPEntries.cpp by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +// static init: ELF 0x2B3AC0 (__tcf_0 0x2B3B20, _GLOBAL__I 0x2B3B50): 's Init object only. +#include + +#include "EntryBoatResetControls.h" + +#include "BoatControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../Main/AIDllFrontier.h" +#include "../../../../IO/Input/PlayerInput.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryBoatResetControls::EntryBoatResetControls() +{ +} + +EntryBoatResetControls::~EntryBoatResetControls() +{ +} + +int EntryBoatResetControls::getTargetId() +{ + return 14; +} + +// ELF 0x2B3890 (Ghidra). A single-input reset releases that one input and succeeds. The group +// form hands `done` to BoatControl::resetControls, which clears it while the boat still has to +// brake; `ok` is that call's answer. +bool EntryBoatResetControls::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAResetControls* const reset = static_cast(script); + if (reset->hasSingleInput()) + { + io::PlayerInput* const input = bot->getInput(); + input->setInput(static_cast(reset->getInput()), 0.0f); + ok = true; + done = true; + return true; + } + ok = BoatControl::resetControls(bot, reset->m_resetMove, reset->m_resetLook, reset->m_resetTrigger, + done) != 0; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatResetControls.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatResetControls.h new file mode 100644 index 000000000..91de4a7f4 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatResetControls.h @@ -0,0 +1,28 @@ +// EntryBoatResetControls: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYBOATRESETCONTROLS_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYBOATRESETCONTROLS_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryBoatResetControls - statement type 14. +class EntryBoatResetControls : public BAPEntry +{ +public: + EntryBoatResetControls(); + virtual ~EntryBoatResetControls(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYBOATRESETCONTROLS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveTo.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveTo.cpp new file mode 100644 index 000000000..4e70bce67 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveTo.cpp @@ -0,0 +1,199 @@ +// EntryCarMoveTo (attested TU `EntryCarMoveTo.cpp`, split out of BAPEntries.cpp by S0). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32): the interpreter entry that drives a car +// along a BAPAMoveTo. execute's flags follow the BotScript convention: `ok` (the step ran) and +// `done` (the statement is finished; with ok == false it failed). +// +// static init: ELF 0x2B43A0 (__tcf_0 0x2B4400, _GLOBAL__I 0x2B4430): the guard object only. + +#include "EntryCarMoveTo.h" + +#include "CarControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +EntryCarMoveTo::EntryCarMoveTo() +{ +} + +EntryCarMoveTo::~EntryCarMoveTo() +{ +} + +int EntryCarMoveTo::getTargetId() +{ + return 7; +} + +// ELF 0x2B3C40 (listing; Ghidra cross-check). Every second at most it asks the move whether it is +// finished; otherwise it updates the move and steers towards the returned point: +// CarControl::actionStatusDecision chooses the action (a first output of 666 means stop: reset the +// controls and finish), then controlTowardsDirection drives at the mobile's max speed scaled by +// the slower of a turn factor (1 - min(1, 1.8 * max(0, |largest angle diff| - startAngle)) * +// speedScale, while faster than 1 m/s) and an approach factor ((distance - smallest radius - 0.5)^2 +// / 225, at least 0.2, inside 15 m). Arrival, a finished move and a failed update reset the +// controls with the speed along the facing. +bool EntryCarMoveTo::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + static float startAngle = 0.2f; // .data 0x4BCD64 + static float speedScale = 0.8f; // .data 0x4BCD68 + + BAPAMoveTo* const moveTo = static_cast(script); + ok = true; + done = false; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + return true; + } + IAIObjectPhysical* const object = info->getAIObject()->getPhysical(); + if (!object->hasPhysicsEnabled()) + object->enablePhysics(info->getSide()); + IPIMobile* const mobile = info->getMobile(); + IPIControlInfo* const controlInfo = info->getControlInfo(); + IPIPhysical* const physical = info->getPhysical(); + if (!mobile || !controlInfo || !physical) + { + done = true; + ok = false; + return true; + } + + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + const double last = static_cast(bot)->getLastCheckMoveToFinishedTime(); // Bot +0x274 (pure in Bot, declared on BotMain in this tree) + done = false; + if (now - last > 1.0) + { + static_cast(bot)->setLastCheckMoveToFinishedTime(now); // +0x270 + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + } + + Vec2 target; + target.x = target.y = 0.0f; + bool arrived; + ok = moveTo->update(target, done, arrived, 0.0f) != 0; + if (!ok) + { + // 0x2B42CD + const Vec3 facing = info->getFaceing(); + const Vec3& speed = mobile->getSpeed(); + ok = CarControl::resetControls(bot, bot->getInput(), true, false, false, + speed.x * facing.x + speed.y * facing.y + speed.z * facing.z) != 0; + done = true; + return true; + } + if (arrived || done) + { + // 0x2B3DF3 + const Vec3 facing = info->getFaceing(); + const Vec3& speed = mobile->getSpeed(); + ok = CarControl::resetControls(bot, bot->getInput(), true, false, false, + speed.x * facing.x + speed.y * facing.y + speed.z * facing.z) != 0; + return true; + } + + // 0x2B3E6E + Vec2 position; + position.x = info->getPosition().x; + position.y = info->getPosition().z; + Vec2 forward; // read, never used + forward.x = info->getTransformation().m[8]; + forward.y = info->getTransformation().m[10]; + (void)forward; + Vec2 toTarget; + toTarget.x = target.x - position.x; + toTarget.y = target.y - position.y; + Vec2 direction = toTarget; + float distance = std::sqrt(toTarget.x * toTarget.x + toTarget.y * toTarget.y); + if (distance > 1e-06f) + { + const float inverse = 1.0f / distance; + direction.x = direction.x * inverse; + direction.y = inverse * direction.y; + } + float turnFactor = 1.0f; + // A -0.0f store to an otherwise unread local follows here (0x2B3F81). + float largestAngle; + if (std::fabs(mobile->getSpeedMagnitude()) > 1.0f && moveTo->getLargestAngleDiff(largestAngle)) + { + // 0x2B4266 + float excess = 0.0f; + if (0.0f <= std::fabs(largestAngle) - startAngle) + excess = std::fabs(largestAngle) - startAngle; + float scaled = excess * 1.8f; + if (1.0f < excess * 1.8f) + scaled = 1.0f; + turnFactor = 1.0f - scaled * speedScale; + } + + float mode; + float angle; + float reference; + float limit; + ok = CarControl::actionStatusDecision(bot, info, direction, distance, moveTo, mode, angle, reference, limit) != 0; + if (mode == 666.0f) + { + // 0x2B41C2 + const Vec3 facing = info->getFaceing(); + const Vec3& speed = mobile->getSpeed(); + ok = CarControl::resetControls(bot, bot->getInput(), true, false, false, + speed.x * facing.x + speed.y * facing.y + speed.z * facing.z) != 0; + done = true; + return true; + } + if (!ok) + return true; + + // 0x2B4012 + const float maxSpeed = mobile->getMaxSpeed(); + float approachFactor = 1.0f; + Vec2 speed2d; // computed, never read + speed2d.x = speed2d.y = 0.0f; + vec3ToVec2XZ(mobile->getSpeed(), speed2d); + Vec2 remaining; + remaining.x = target.x - position.x; + remaining.y = target.y - position.y; + const float remainingDistance = std::sqrt(remaining.x * remaining.x + remaining.y * remaining.y); + float gap = remainingDistance - physical->getSmallestRadius() - 0.5f; + if (gap <= 0.0f) + gap = 0.0f; + if (gap * gap < 225.0f) + { + float scale = gap * gap / 225.0f; + if (scale <= 0.2f) + scale = 0.2f; + approachFactor = scale; + } + if (turnFactor <= approachFactor) + approachFactor = turnFactor; + ok = CarControl::controlTowardsDirection(info, controlInfo, mobile, physical, bot->getInput(), + approachFactor * maxSpeed, mode, angle, reference, limit) != 0; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveTo.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveTo.h new file mode 100644 index 000000000..9a28b31a4 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveTo.h @@ -0,0 +1,28 @@ +// EntryCarMoveTo: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYCARMOVETO_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYCARMOVETO_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryCarMoveTo - statement type 7. +class EntryCarMoveTo : public BAPEntry +{ +public: + EntryCarMoveTo(); + virtual ~EntryCarMoveTo(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYCARMOVETO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToDirection.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToDirection.cpp new file mode 100644 index 000000000..d1b34f557 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToDirection.cpp @@ -0,0 +1,36 @@ +// EntryCarMoveToDirection (split out of BAPEntries.cpp by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +// static init: ELF 0x2B4540 (__tcf_0 0x2B45A0, _GLOBAL__I 0x2B45D0): 's Init object only. +#include + +#include "EntryCarMoveToDirection.h" + +#include "../Main/AIDllFrontier.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryCarMoveToDirection::EntryCarMoveToDirection() +{ +} + +EntryCarMoveToDirection::~EntryCarMoveToDirection() +{ +} + +int EntryCarMoveToDirection::getTargetId() +{ + return 8; +} + +// A retail stub - see the block above. , and all it does is succeed. +bool EntryCarMoveToDirection::execute(BotScript *, Bot *, bool&, bool&) +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToDirection.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToDirection.h new file mode 100644 index 000000000..28f852f39 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToDirection.h @@ -0,0 +1,28 @@ +// EntryCarMoveToDirection: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYCARMOVETODIRECTION_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYCARMOVETODIRECTION_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryCarMoveToDirection - statement type 8. +class EntryCarMoveToDirection : public BAPEntry +{ +public: + EntryCarMoveToDirection(); + virtual ~EntryCarMoveToDirection(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYCARMOVETODIRECTION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToObject.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToObject.cpp new file mode 100644 index 000000000..fd5d36ff2 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToObject.cpp @@ -0,0 +1,180 @@ +// EntryCarMoveToObject (attested TU `EntryCarMoveToObject.cpp`, split out of BAPEntries.cpp by S0). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32): the interpreter entry that drives a car +// to an object (a BAPAMoveTo with a target object). execute's flags follow the BotScript convention: `ok` (the step ran) and +// `done` (the statement is finished; with ok == false it failed). +// +// static init: ELF 0x2B4E50 (__tcf_0 0x2B4EB0, _GLOBAL__I 0x2B4EE0): the guard object only. + +#include "EntryCarMoveToObject.h" + +#include "CarControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +EntryCarMoveToObject::EntryCarMoveToObject() +{ +} + +EntryCarMoveToObject::~EntryCarMoveToObject() +{ +} + +int EntryCarMoveToObject::getTargetId() +{ + return 9; +} + +// ELF 0x2B46C0 (Ghidra; listing for the statics). EntryCarMoveTo's steering for a move to an +// object: fails (done, not ok) without the target's information, the equipment or its mobile or +// physical part (the control part is not tested); asks isFinished on every call (no one-second +// throttle); the direction is normalised above 1e-05. +bool EntryCarMoveToObject::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + static float startAngle = 0.2f; // .data 0x4BCE24 + static float speedScale = 0.8f; // .data 0x4BCE28 + + BAPAMoveTo* const moveTo = static_cast(script); + ok = true; + done = false; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* mobile; + IPIPhysical* physical; + if (!informationManager->getInformation(moveTo->getObject()) || !info || !(mobile = info->getMobile()) + || !(physical = info->getPhysical())) + { + done = true; + ok = false; + return true; + } + IPIControlInfo* const controlInfo = info->getControlInfo(); + IAIObjectPhysical* const object = info->getAIObject()->getPhysical(); + if (!object->hasPhysicsEnabled()) + object->enablePhysics(info->getSide()); + if (!informationManager->getInformation(moveTo->getObject())) + { + done = true; + ok = false; + return true; + } + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + + Vec2 target; + target.x = target.y = 0.0f; + done = false; + bool arrived; + ok = moveTo->update(target, done, arrived, 0.0f) != 0; + if (!ok) + { + const Vec3 facing = info->getFaceing(); + const Vec3& speed = mobile->getSpeed(); + ok = CarControl::resetControls(bot, bot->getInput(), true, false, false, + speed.x * facing.x + speed.y * facing.y + speed.z * facing.z) != 0; + done = true; + return true; + } + if (arrived || done) + { + const Vec3 facing = info->getFaceing(); + const Vec3& speed = mobile->getSpeed(); + ok = CarControl::resetControls(bot, bot->getInput(), true, false, false, + speed.x * facing.x + speed.y * facing.y + speed.z * facing.z) != 0; + return true; + } + + Vec2 position; + position.x = info->getPosition().x; + position.y = info->getPosition().z; + Vec2 forward; // read, never used + forward.x = info->getTransformation().m[8]; + forward.y = info->getTransformation().m[10]; + (void)forward; + Vec2 toTarget; + toTarget.x = target.x - position.x; + toTarget.y = target.y - position.y; + Vec2 direction = toTarget; + const float distance = std::sqrt(toTarget.x * toTarget.x + toTarget.y * toTarget.y); + if (distance > 1e-05f) + { + const float inverse = 1.0f / distance; + direction.x = direction.x * inverse; + direction.y = inverse * direction.y; + } + float turnFactor = 1.0f; + float largestAngle; + if (std::fabs(mobile->getSpeedMagnitude()) > 1.0f && moveTo->getLargestAngleDiff(largestAngle)) + { + float excess = 0.0f; + if (0.0f <= std::fabs(largestAngle) - startAngle) + excess = std::fabs(largestAngle) - startAngle; + float scaled = excess * 1.8f; + if (1.0f < excess * 1.8f) + scaled = 1.0f; + turnFactor = 1.0f - scaled * speedScale; + } + + float mode; + float angle; + float reference; + float limit; + ok = CarControl::actionStatusDecision(bot, info, direction, distance, moveTo, mode, angle, reference, limit) != 0; + if (mode == 666.0f) + { + const Vec3 facing = info->getFaceing(); + const Vec3& speed = mobile->getSpeed(); + ok = CarControl::resetControls(bot, bot->getInput(), true, false, false, + speed.x * facing.x + speed.y * facing.y + speed.z * facing.z) != 0; + done = true; + return true; + } + if (!ok) + return true; + + const float maxSpeed = mobile->getMaxSpeed(); + float approachFactor = 1.0f; + Vec2 speed2d; // computed, never read + speed2d.x = speed2d.y = 0.0f; + vec3ToVec2XZ(mobile->getSpeed(), speed2d); + Vec2 remaining; + remaining.x = target.x - position.x; + remaining.y = target.y - position.y; + const float remainingDistance = std::sqrt(remaining.x * remaining.x + remaining.y * remaining.y); + float gap = remainingDistance - physical->getSmallestRadius() - 0.5f; + if (gap <= 0.0f) + gap = 0.0f; + if (gap * gap < 225.0f) + { + float scale = gap * gap / 225.0f; + if (scale <= 0.2f) + scale = 0.2f; + approachFactor = scale; + } + if (turnFactor <= approachFactor) + approachFactor = turnFactor; + ok = CarControl::controlTowardsDirection(info, controlInfo, mobile, physical, bot->getInput(), + approachFactor * maxSpeed, mode, angle, reference, limit) != 0; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToObject.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToObject.h new file mode 100644 index 000000000..c9c825c68 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToObject.h @@ -0,0 +1,28 @@ +// EntryCarMoveToObject: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYCARMOVETOOBJECT_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYCARMOVETOOBJECT_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryCarMoveToObject - statement type 9. +class EntryCarMoveToObject : public BAPEntry +{ +public: + EntryCarMoveToObject(); + virtual ~EntryCarMoveToObject(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYCARMOVETOOBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarResetControls.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarResetControls.cpp new file mode 100644 index 000000000..07da55945 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarResetControls.cpp @@ -0,0 +1,67 @@ +// EntryCarResetControls (split out of BAPEntries.cpp by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +// static init: ELF 0x2B52A0 (__tcf_0 0x2B5300, _GLOBAL__I 0x2B5330): 's Init object only. +#include + +#include "EntryCarResetControls.h" + +#include "CarControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../Main/AIDllFrontier.h" +#include "../../../../IO/Input/PlayerInput.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryCarResetControls::EntryCarResetControls() +{ +} + +EntryCarResetControls::~EntryCarResetControls() +{ +} + +int EntryCarResetControls::getTargetId() +{ + return 14; +} + +// ELF 0x2B4FD0 (listing). A single-input reset releases that one input (setInput inlined with its +// range diagnostic) and succeeds. The group form resets through CarControl::resetControls with +// the equipment's forward speed (mobile speed dot facing); the information lookup is not +// null-tested, and the mobile's speed, the facing and the transformation are asked for once more +// beforehand and discarded, as compiled. `ok` is that call's answer; `done` is always set. +bool EntryCarResetControls::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAResetControls* const reset = static_cast(script); + if (reset->hasSingleInput()) + { + io::PlayerInput* const input = bot->getInput(); + input->setInput(static_cast(reset->getInput()), 0.0f); + ok = true; + done = true; + return true; + } + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* const mobile = equipment->getMobile(); // +0x38 + done = true; + mobile->getSpeed(); // +0x1C, discarded + equipment->getFaceing(); // +0x40, discarded + equipment->getTransformation(); // +0x3C, discarded + const Vec3 facing = equipment->getFaceing(); + const Vec3& speed = mobile->getSpeed(); + const float forwardSpeed = speed.y * facing.y + speed.x * facing.x + speed.z * facing.z; + ok = CarControl::resetControls(bot, bot->getInput(), reset->m_resetMove, reset->m_resetLook, + reset->m_resetTrigger, forwardSpeed) != 0; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarResetControls.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarResetControls.h new file mode 100644 index 000000000..663b2523a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarResetControls.h @@ -0,0 +1,28 @@ +// EntryCarResetControls: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYCARRESETCONTROLS_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYCARRESETCONTROLS_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryCarResetControls - statement type 14. +class EntryCarResetControls : public BAPEntry +{ +public: + EntryCarResetControls(); + virtual ~EntryCarResetControls(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYCARRESETCONTROLS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliAimAt.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliAimAt.cpp new file mode 100644 index 000000000..2f7e8047c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliAimAt.cpp @@ -0,0 +1,201 @@ +// EntryHeliAimAt (split out of BAPEntries.cpp by S0, bodies unchanged). + +// static init: ELF 0x2B6400 (__tcf_0 0x2B6460, _GLOBAL__I 0x2B6490): 's Init object only. +#include + +#include "EntryHeliAimAt.h" + +#include "HeliControl.h" +#include "VehicleControlInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAAimAtObject3d.h" +#include "../AIBotActionPlan/BAPCondition.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2B5380 (C1; C2 0x2B5360). +EntryHeliAimAt::EntryHeliAimAt() +{ +} + +// ELF 0x2B53C0 (D1; D2 0x2B53A0, D0 0x2B53E0). +EntryHeliAimAt::~EntryHeliAimAt() +{ +} + +// ELF 0x2B64B0. +int EntryHeliAimAt::getTargetId() +{ + return 6; +} + +// ELF 0x2B5420. +bool EntryHeliAimAt::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAAimAt3d* const aim = static_cast(script); + ok = true; + done = false; + if (aim->m_condition->evaluate(bot)) + done = true; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + aim->m_floats1AC[0] = 3.1415927f; + return true; + } + IPIArmament* const armament = info->getArmament(); + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation( + armament->getWeapon(armament->getActiveWeapon())); + IPIMobile* const mobile = info->getMobile(); + Information* target = 0; + if (aim->getAimAtType() == 1) + { + target = informationManager->getInformation(static_cast(aim)->m_target); + if (!target) + { + done = true; + ok = false; + aim->m_floats1AC[0] = 3.1415927f; + return true; + } + } + Vec3 direction = {0.0f, 0.0f, 1.0f}; + Vec3 firingDirection = {0.0f, 0.0f, 0.0f}; + const Mat4& origin = weapon->getProjectileOrigin(); + const Vec3& velocity = mobile->getSpeed(); + const Vec3& position = info->getPosition(); + // shipped defect: point-aim statements leave target null, yet it is read here. + const Vec3& targetPosition = target->getPosition(); + const float x = position.x - targetPosition.x; + const float y = position.y - targetPosition.y; + const float z = position.z - targetPosition.z; + const float distance = std::sqrt(x * x + y * y + z * z); + const bool airborne = target->isOfType(ITAir); + bool solved; + if (airborne) + { + const bool indirect = weapon->getIndirect(); + const float gravity = weapon->getGravityModifier(); + const float speed = weapon->getExitVelocity(); + const float drag = weapon->getDrag(); + solved = aim->getAimVec(origin, mobile->getSpeed(), direction, 0.5f, drag, speed, gravity, indirect); + if (solved) + { + firingDirection = direction; + vehiclecontrol::normalizeVec3(direction); + } + } + else + { + const bool indirect = weapon->getIndirect(); + const float gravity = weapon->getGravityModifier(); + const float speed = weapon->getExitVelocity(); + const float drag = weapon->getDrag(); + if (indirect) + { + const Vec3 stationary = {0.0f, 0.0f, 0.0f}; + solved = aim->getAimVec(origin, stationary, direction, 0.75f, drag, speed, gravity, false); + } + else + solved = aim->getAimVec(origin, velocity, direction, 0.5f, drag, speed, gravity, false); + if (solved) + { + firingDirection = direction; + if (indirect) + direction.y = 0.0f; + vehiclecontrol::normalizeVec3(direction); + } + } + if (!solved) + { + const bool found = aim->getVectorToTarget(info->getPosition(), direction); + if (!found && !airborne) + { + ok = false; + done = true; + } + vehiclecontrol::normalizeVec3(direction); + if (!found) + { + if (airborne) + { + ok = false; + done = true; + } + return true; + } + } + const float dt = static_cast(static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease()); + const Vec3& speed = mobile->getSpeed(); + const float inverse = 1.0f / dt; + const Vec3 acceleration = {(speed.x - aim->m_vecA8.x) * inverse, + (speed.y - aim->m_vecA8.y) * inverse, + (speed.z - aim->m_vecA8.z) * inverse}; + aim->m_vecA8 = speed; + Mat4 inverseOrigin = {{1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f}}; + inverseOrigin.setInverse(origin); + const Vec3 localDirection = { + direction.x * inverseOrigin.m[0] + direction.y * inverseOrigin.m[4] + direction.z * inverseOrigin.m[8], + direction.x * inverseOrigin.m[1] + direction.y * inverseOrigin.m[5] + direction.z * inverseOrigin.m[9], + direction.x * inverseOrigin.m[2] + direction.y * inverseOrigin.m[6] + direction.z * inverseOrigin.m[10]}; + const Mat4& transform = info->getTransformation(); + const Vec3 steeringDirection = { + localDirection.x * transform.m[0] + localDirection.y * transform.m[4] + localDirection.z * transform.m[8], + localDirection.x * transform.m[1] + localDirection.y * transform.m[5] + localDirection.z * transform.m[9], + localDirection.x * transform.m[2] + localDirection.y * transform.m[6] + localDirection.z * transform.m[10]}; + // [INFERRED] inline clamp expansion; unordered input passes through these two tests. + const auto clamp = [](float value, float low, float high) { + return low > value ? low : (value > high ? high : value); + }; + if (aim->isAimVecValid()) + { + const Mat4& weaponUp = weapon->getAbsoluteTransformation(); + float dot = firingDirection.x * weaponUp.m[4] + firingDirection.y * weaponUp.m[5] + firingDirection.z * weaponUp.m[6]; + const float pitch = std::acos(clamp(clamp(dot, -1.0f, 1.0f), -1.0f, 1.0f)) - 1.5707964f; + const Mat4& weaponRight = weapon->getAbsoluteTransformation(); + dot = firingDirection.x * weaponRight.m[0] + firingDirection.y * weaponRight.m[1] + firingDirection.z * weaponRight.m[2]; + float yaw = std::acos(clamp(clamp(dot, -1.0f, 1.0f), -1.0f, 1.0f)) - 1.5707964f; + const Mat4& weaponForward = weapon->getAbsoluteTransformation(); + dot = firingDirection.x * weaponForward.m[8] + firingDirection.y * weaponForward.m[9] + firingDirection.z * weaponForward.m[10]; + if (dot < 0.0f) + yaw = (yaw < 0.0f ? -3.1415927f : 3.1415927f) - yaw; + aim->m_floats1AC[1] = pitch; + aim->m_floats1AC[0] = yaw; + } + else + { + aim->m_floats1AC[1] = 3.1415927f; + aim->m_floats1AC[0] = 3.1415927f; + } + aim->m_vec24 = info->getFaceing(); + const Mat4& right = info->getTransformation(); + aim->m_vec30 = {right.m[0], right.m[1], right.m[2]}; + const Mat4& up = info->getTransformation(); + aim->m_vec3C = {up.m[4], up.m[5], up.m[6]}; + aim->m_floats1AC[3] = info->getPosition().y; + const float difference = direction.y - aim->m_vec1C8.y; + // 0x2B5C45..0x2B5C59: ja then fcmovnbe, so a NaN difference passes through to asin. + const float asinInput = clamp(difference, -1.0f, 1.0f); + const float pitchRate = clamp(std::asin(asinInput) / dt, -0.1f, 0.1f); + aim->m_vec1C8 = direction; + ok = HeliControl::aimAtDirection(bot, steeringDirection, distance, aim->m_float1A4, acceleration, pitchRate) != 0; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliAimAt.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliAimAt.h new file mode 100644 index 000000000..22226cc07 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliAimAt.h @@ -0,0 +1,27 @@ +// EntryHeliAimAt: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIAIMAT_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIAIMAT_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryHeliAimAt - statement type 6. +class EntryHeliAimAt : public BAPEntry +{ +public: + EntryHeliAimAt(); + virtual ~EntryHeliAimAt(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIAIMAT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveAwayFromObject.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveAwayFromObject.cpp new file mode 100644 index 000000000..8aef04b00 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveAwayFromObject.cpp @@ -0,0 +1,82 @@ +// EntryHeliMoveAwayFromObject (split out of BAPEntries.cpp by S0, bodies unchanged). + +// static init: ELF 0x2B6830 (__tcf_0 0x2B6890, _GLOBAL__I 0x2B68C0): 's Init object only. +#include + +#include "EntryHeliMoveAwayFromObject.h" + +#include "HeliControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveAwayFrom3dObject.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../../Math/Mat4.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2B64E0 (C1; C2 0x2B64C0). +EntryHeliMoveAwayFromObject::EntryHeliMoveAwayFromObject() +{ +} + +// ELF 0x2B6520 (D1; D2 0x2B6500, D0 0x2B6540). +EntryHeliMoveAwayFromObject::~EntryHeliMoveAwayFromObject() +{ +} + +// ELF 0x2B68E0. +int EntryHeliMoveAwayFromObject::getTargetId() +{ + return 10; +} + +// ELF 0x2B6580. +bool EntryHeliMoveAwayFromObject::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveAwayFrom3dObject* const moveAway = static_cast(script); + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + Information* const object = informationManager->getInformation(moveAway->m_object); + if (!info || !object) + { + done = true; + ok = false; + return true; + } + if (moveAway->isFinished(bot)) + { + done = true; + ok = true; + // shipped defect: the completed statement continues and overwrites both flags. + } + else + done = false; + IPIMobile* const mobile = info->getMobile(); + const Mat4& transform = info->getTransformation(); + const Vec3& speed = mobile->getSpeed(); + const Vec3 change = {speed.x - moveAway->m_vec30.x, + speed.y - moveAway->m_vec30.y, + speed.z - moveAway->m_vec30.z}; + const float dt = static_cast(static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease()); + const float inverse = 1.0f / dt; + const Vec3 acceleration = {change.x * inverse, change.y * inverse, change.z * inverse}; + moveAway->m_vec30 = speed; + const Vec3 point = {transform.m[8] * 100.0f + transform.m[12], + 0.0f * 100.0f + transform.m[13], + transform.m[10] * 100.0f + transform.m[14]}; + ok = HeliControl::moveToPoint(bot, point, 25.0f, acceleration) != 0; + const float distance = moveAway->m_distance; + const Vec3 target = *moveAway->getFirstPoint(); + const float x = target.x - transform.m[12]; + const float z = target.z - transform.m[14]; + done = x * x + 0.0f + z * z > distance * distance; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveAwayFromObject.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveAwayFromObject.h new file mode 100644 index 000000000..8dea0a8e7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveAwayFromObject.h @@ -0,0 +1,27 @@ +// EntryHeliMoveAwayFromObject: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIMOVEAWAYFROMOBJECT_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIMOVEAWAYFROMOBJECT_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryHeliMoveAwayFromObject - statement type 10. +class EntryHeliMoveAwayFromObject : public BAPEntry +{ +public: + EntryHeliMoveAwayFromObject(); + virtual ~EntryHeliMoveAwayFromObject(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIMOVEAWAYFROMOBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveTo.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveTo.cpp new file mode 100644 index 000000000..b4639fe34 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveTo.cpp @@ -0,0 +1,77 @@ +// EntryHeliMoveTo (split out of BAPEntries.cpp by S0, bodies unchanged). + +// static init: ELF 0x2B6BB0 (__tcf_0 0x2B6C10, _GLOBAL__I 0x2B6C40): 's Init object only. +#include + +#include "EntryHeliMoveTo.h" + +#include "HeliControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo3d.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../../Math/Mat4.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2B6910 (C1; C2 0x2B68F0). +EntryHeliMoveTo::EntryHeliMoveTo() +{ +} + +// ELF 0x2B6950 (D1; D2 0x2B6930, D0 0x2B6970). +EntryHeliMoveTo::~EntryHeliMoveTo() +{ +} + +// ELF 0x2B6C60. +int EntryHeliMoveTo::getTargetId() +{ + return 7; +} + +// ELF 0x2B69B0. +bool EntryHeliMoveTo::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveTo3d* const moveTo = static_cast(script); + Mat4 unused = {{1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f}}; + (void)unused; + Vec3 point = {0.0f, 0.0f, 0.0f}; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + // shipped defect: missing equipment does not stop execution. + } + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + done = false; + point = *moveTo->getFirstPoint(); + const Vec3& speed = info->getMobile()->getSpeed(); + const Vec3 change = {speed.x - moveTo->m_vec3C.x, + speed.y - moveTo->m_vec3C.y, + speed.z - moveTo->m_vec3C.z}; + const float dt = static_cast(static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease()); + const float inverse = 1.0f / dt; + const Vec3 acceleration = {change.x * inverse, change.y * inverse, change.z * inverse}; + moveTo->m_vec3C = speed; + ok = HeliControl::moveToPoint(bot, point, moveTo->m_distance, acceleration) != 0; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveTo.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveTo.h new file mode 100644 index 000000000..66375d5c0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveTo.h @@ -0,0 +1,27 @@ +// EntryHeliMoveTo: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIMOVETO_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIMOVETO_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryHeliMoveTo - statement type 7. +class EntryHeliMoveTo : public BAPEntry +{ +public: + EntryHeliMoveTo(); + virtual ~EntryHeliMoveTo(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIMOVETO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToDirection.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToDirection.cpp new file mode 100644 index 000000000..3061354cf --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToDirection.cpp @@ -0,0 +1,83 @@ +// EntryHeliMoveToDirection (split out of BAPEntries.cpp by S0, bodies unchanged). + +// static init: ELF 0x2B7260 (__tcf_0 0x2B72C0, _GLOBAL__I 0x2B72F0): 's Init object only. +#include + +#include "EntryHeliMoveToDirection.h" + +#include "HeliControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo3dDirection.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../../Math/Mat4.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2B6C90 (C1; C2 0x2B6C70). +EntryHeliMoveToDirection::EntryHeliMoveToDirection() +{ +} + +// ELF 0x2B6CD0 (D1; D2 0x2B6CB0, D0 0x2B6CF0). +EntryHeliMoveToDirection::~EntryHeliMoveToDirection() +{ +} + +// ELF 0x2B7310. +int EntryHeliMoveToDirection::getTargetId() +{ + return 8; +} + +// ELF 0x2B6D30. +bool EntryHeliMoveToDirection::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveTo3dDirection* const moveTo = static_cast(script); + Mat4 transform = {{1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f}}; + Mat4 transpose = transform; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + return true; + } + info->getMobile()->getTurnRadius(); + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + done = false; + transform = info->getTransformation(); + transpose.setTranspose(transform); + const Vec3 position = info->getPosition(); + (void)position; + info->getMobile()->getSpeedMagnitude(); + Vec3 point = moveTo->m_target; + const Vec3& speed = info->getMobile()->getSpeed(); + const Vec3 change = {speed.x - moveTo->m_vector24.x, + speed.y - moveTo->m_vector24.y, + speed.z - moveTo->m_vector24.z}; + const float dt = static_cast(static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease()); + const float inverse = 1.0f / dt; + const Vec3 acceleration = {change.x * inverse, change.y * inverse, change.z * inverse}; + moveTo->m_vector24 = speed; + point.y = -99999.0f; + ok = HeliControl::moveToPoint(bot, point, moveTo->m_altitude, acceleration) != 0; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToDirection.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToDirection.h new file mode 100644 index 000000000..777b2619b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToDirection.h @@ -0,0 +1,27 @@ +// EntryHeliMoveToDirection: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIMOVETODIRECTION_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIMOVETODIRECTION_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryHeliMoveToDirection - statement type 8. +class EntryHeliMoveToDirection : public BAPEntry +{ +public: + EntryHeliMoveToDirection(); + virtual ~EntryHeliMoveToDirection(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIMOVETODIRECTION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToObject.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToObject.cpp new file mode 100644 index 000000000..8033b9e77 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToObject.cpp @@ -0,0 +1,78 @@ +// EntryHeliMoveToObject (split out of BAPEntries.cpp by S0, bodies unchanged). + +// static init: ELF 0x2B7580 (__tcf_0 0x2B75E0, _GLOBAL__I 0x2B7610): 's Init object only. +#include + +#include "EntryHeliMoveToObject.h" + +#include "HeliControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo3dObject.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../../Math/Mat4.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2B7340 (C1; C2 0x2B7320). +EntryHeliMoveToObject::EntryHeliMoveToObject() +{ +} + +// ELF 0x2B7380 (D1; D2 0x2B7360, D0 0x2B73A0). +EntryHeliMoveToObject::~EntryHeliMoveToObject() +{ +} + +// ELF 0x2B7630. +int EntryHeliMoveToObject::getTargetId() +{ + return 9; +} + +// ELF 0x2B73E0. +bool EntryHeliMoveToObject::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveTo3dObject* const moveTo = static_cast(script); + Mat4 unused = {{1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f}}; + (void)unused; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + return true; + } + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + // shipped defect: the completed statement still drives the helicopter below. + } + else + done = false; + const Vec3& speed = info->getMobile()->getSpeed(); + const Vec3 change = {speed.x - moveTo->m_vec34.x, + speed.y - moveTo->m_vec34.y, + speed.z - moveTo->m_vec34.z}; + const float dt = static_cast(static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease()); + const float inverse = 1.0f / dt; + const Vec3 acceleration = {change.x * inverse, change.y * inverse, change.z * inverse}; + moveTo->m_vec34 = speed; + const float distance = moveTo->m_distance; + const Vec3& point = *moveTo->getFirstPoint(); + ok = HeliControl::moveToPoint(bot, point, distance, acceleration) != 0; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToObject.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToObject.h new file mode 100644 index 000000000..bc1153fe9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToObject.h @@ -0,0 +1,27 @@ +// EntryHeliMoveToObject: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIMOVETOOBJECT_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIMOVETOOBJECT_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryHeliMoveToObject - statement type 9. +class EntryHeliMoveToObject : public BAPEntry +{ +public: + EntryHeliMoveToObject(); + virtual ~EntryHeliMoveToObject(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIMOVETOOBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliResetControls.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliResetControls.cpp new file mode 100644 index 000000000..baa4a0ae8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliResetControls.cpp @@ -0,0 +1,60 @@ +// EntryHeliResetControls (split out of BAPEntries.cpp by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +// static init: ELF 0x2B7920 (__tcf_0 0x2B7980, _GLOBAL__I 0x2B79B0): 's Init object only. +#include + +#include "EntryHeliResetControls.h" + +#include "HeliControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../Main/AIDllFrontier.h" +#include "../../../../IO/Input/PlayerInput.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryHeliResetControls::EntryHeliResetControls() +{ +} + +EntryHeliResetControls::~EntryHeliResetControls() +{ +} + +int EntryHeliResetControls::getTargetId() +{ + return 14; +} + +// ELF 0x2B7700 (Ghidra). The bot's current equipment is looked up first and not used (only the +// virtual getCurrentEquipment call survives in the image). A single-input reset releases that one +// input; the group form resets through HeliControl::resetControls, ignores its answer, and sets +// `done` then `ok`. +bool EntryHeliResetControls::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + (void)equipment; + BAPAResetControls* const reset = static_cast(script); + if (reset->hasSingleInput()) + { + io::PlayerInput* const input = bot->getInput(); + input->setInput(static_cast(reset->getInput()), 0.0f); + ok = true; + done = true; + return true; + } + HeliControl::resetControls(bot, reset->m_resetMove, reset->m_resetLook, reset->m_resetTrigger); + done = true; + ok = true; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliResetControls.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliResetControls.h new file mode 100644 index 000000000..0b3191097 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliResetControls.h @@ -0,0 +1,28 @@ +// EntryHeliResetControls: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIRESETCONTROLS_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIRESETCONTROLS_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryHeliResetControls - statement type 14. +class EntryHeliResetControls : public BAPEntry +{ +public: + EntryHeliResetControls(); + virtual ~EntryHeliResetControls(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIRESETCONTROLS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveTo.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveTo.cpp new file mode 100644 index 000000000..41eb27830 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveTo.cpp @@ -0,0 +1,103 @@ +// EntryInfanteryMoveTo (attested TU `EntryInfanteryMoveTo.cpp`, split out of BAPEntries.cpp by S0). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32): the interpreter entry that executes a +// BAPAMoveTo for a soldier at full LOD. Package B; see docs/macos-ai-behaviour-plan.md. +// +// execute's two flags follow the BotScript convention: `ok` (the step ran) and `done` (the +// statement is finished; with ok == false it failed). + +// static init: ELF 0x2B7DC0 (__tcf_0 0x2B7E20, _GLOBAL__I 0x2B7E50): 's Init object only. +#include + +#include "EntryInfanteryMoveTo.h" + +#include "InfanteryControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../Math/Vec3.h" +#include "../AIBot/SquadMember.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryInfanteryMoveTo::EntryInfanteryMoveTo() +{ +} + +EntryInfanteryMoveTo::~EntryInfanteryMoveTo() +{ +} + +int EntryInfanteryMoveTo::getTargetId() +{ + return 7; +} + +// ELF 0x2B7AA0 +bool EntryInfanteryMoveTo::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveTo* moveTo = static_cast(script); + Vec2 dir; + dir.x = dir.y = 0.0f; + Vec2 unused; // [INFERRED] a zeroed local the image never reads (-0x48) + unused.x = unused.y = 0.0f; + Vec2 targetDir; + targetDir.x = targetDir.y = 0.0f; + Vec2 position; + position.x = position.y = 0.0f; + + Information* info = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* mobile; + if (info == 0 || (mobile = info->getMobile()) == 0) + { + done = true; + ok = false; + return true; + } + IAIObjectPhysical* physical = info->getAIObject()->getPhysical(); + if (!physical->hasPhysicsEnabled()) + physical->enablePhysics(info->getSide()); + vec3ToVec2XZ(info->getPosition(), position); + + if (bot->isFireAllowed() && moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + done = false; + bool arrived; + ok = moveTo->update(dir, done, arrived, 0.0f) != 0; + if (ok) + { + if (arrived || done) + { + ok = infanteryResetControls(bot, bot->getInput(), true, false, false); + return true; + } + if (!moveTo->getTargetDir(bot, dir, targetDir, 0, false)) + { + infantry_detail::setSensingMoveDirection(bot->getSensingAgent(), targetDir); + removeZoom(bot); + const bool sprint = moveTo->getIsSprinting(); + infanteryControlThrottle(bot, bot->getInput(), + info->getControlInfo(), mobile->getMaxSpeed(), sprint); + if (info->getSoldierPose() == SPSwimming) + return true; + bot->requestSoldierPose(SPStanding, true); + return true; + } + } + ok = infanteryResetControls(bot, bot->getInput(), true, false, false); + done = true; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveTo.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveTo.h new file mode 100644 index 000000000..627339548 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveTo.h @@ -0,0 +1,28 @@ +// EntryInfanteryMoveTo: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYINFANTERYMOVETO_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYINFANTERYMOVETO_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryInfanteryMoveTo - statement type 7. +class EntryInfanteryMoveTo : public BAPEntry +{ +public: + EntryInfanteryMoveTo(); + virtual ~EntryInfanteryMoveTo(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYINFANTERYMOVETO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToDirection.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToDirection.cpp new file mode 100644 index 000000000..d01afa007 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToDirection.cpp @@ -0,0 +1,36 @@ +// EntryInfanteryMoveToDirection (split out of BAPEntries.cpp by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +// static init: ELF 0x2B7F50 (__tcf_0 0x2B7FB0, _GLOBAL__I 0x2B7FE0): 's Init object only. +#include + +#include "EntryInfanteryMoveToDirection.h" + +#include "../Main/AIDllFrontier.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryInfanteryMoveToDirection::EntryInfanteryMoveToDirection() +{ +} + +EntryInfanteryMoveToDirection::~EntryInfanteryMoveToDirection() +{ +} + +int EntryInfanteryMoveToDirection::getTargetId() +{ + return 8; +} + +// A retail stub - see the block above. , and all it does is succeed. +bool EntryInfanteryMoveToDirection::execute(BotScript *, Bot *, bool&, bool&) +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToDirection.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToDirection.h new file mode 100644 index 000000000..a78f5829e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToDirection.h @@ -0,0 +1,28 @@ +// EntryInfanteryMoveToDirection: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYINFANTERYMOVETODIRECTION_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYINFANTERYMOVETODIRECTION_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryInfanteryMoveToDirection - statement type 8. +class EntryInfanteryMoveToDirection : public BAPEntry +{ +public: + EntryInfanteryMoveToDirection(); + virtual ~EntryInfanteryMoveToDirection(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYINFANTERYMOVETODIRECTION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToObject.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToObject.cpp new file mode 100644 index 000000000..bf26dd295 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToObject.cpp @@ -0,0 +1,129 @@ +// EntryInfanteryMoveToObject (attested TU `EntryInfanteryMoveToObject.cpp`, split out of +// BAPEntries.cpp by S0). Recovered from libaidll.so (Linux 1.5.3153, ia-32): the full-LOD soldier +// entry for BAPAMoveToObject (statement type 9). Package B; see docs/macos-ai-behaviour-plan.md. +// Flags as in EntryInfanteryMoveTo: `ok` (the step ran), `done` (finished; failed when !ok). + +// static init: ELF 0x2B8550 (__tcf_0 0x2B85B0, _GLOBAL__I 0x2B85E0): 's Init object only. +#include + +#include "EntryInfanteryMoveToObject.h" + +#include "InfanteryControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFGameEffector.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryInfanteryMoveToObject::EntryInfanteryMoveToObject() +{ +} + +EntryInfanteryMoveToObject::~EntryInfanteryMoveToObject() +{ +} + +int EntryInfanteryMoveToObject::getTargetId() +{ + return 9; +} + +// ELF 0x2B80D0 +bool EntryInfanteryMoveToObject::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveTo* moveTo = static_cast(script); + BotMain* botMain = static_cast(bot); + Vec2 dir; + dir.x = dir.y = 0.0f; + Vec2 unused; // [INFERRED] a zeroed local the image never reads (-0x48) + unused.x = unused.y = 0.0f; + Vec2 targetDir; + targetDir.x = targetDir.y = 0.0f; + Vec2 position; + position.x = position.y = 0.0f; + + Information* info = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* mobile; + if (info == 0 || (mobile = info->getMobile()) == 0) + { + done = true; + ok = false; + return true; + } + IAIObjectPhysical* physical = info->getAIObject()->getPhysical(); + if (!physical->hasPhysicsEnabled()) + physical->enablePhysics(info->getSide()); + + if (informationManager->getInformation(static_cast(moveTo->getObject())) == 0) + { + done = true; + ok = false; + return true; + } + if (bot->isFireAllowed() && moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + done = false; + + // BotMain +0x21C/+0x218/+0x220/+0x22C/+0x228, named as in AIBot/BotMain.h + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (now - botMain->getTimeOfLastFailedStaticSkyAttack() < 1.5) + { + botMain->setTimeOfLastFailedStaticAttack(now); + } + else if (botMain->getBotWantsToSimulateArtillery()) + { + botMain->setTimeOfLastFailedStaticSkyAttack(now); + botMain->setBotWantsToSimulateArtillery(false); + } + + vec3ToVec2XZ(info->getPosition(), position); + bool arrived; + ok = moveTo->update(dir, done, arrived, 0.0f) != 0; + if (ok) + { + if (arrived || done) + { + ok = infanteryResetControls(bot, bot->getInput(), true, false, false); + return true; + } + Information* target = informationManager->getInformation(static_cast(moveTo->getObject())); + const bool movingAway = moveTo->getIsMovingAway(); + if (!moveTo->getTargetDir(bot, dir, targetDir, target, movingAway)) + { + infantry_detail::setSensingMoveDirection(bot->getSensingAgent(), targetDir); + removeZoom(bot); + const bool sprint = moveTo->getIsSprinting(); + infanteryControlThrottle(bot, bot->getInput(), + info->getControlInfo(), mobile->getMaxSpeed(), sprint); + if (info->getSoldierPose() != SPSwimming) + bot->requestSoldierPose(SPStanding, true); + if (moveTo->isStuck()) + { + // a stuck soldier gives up: IAIGameEffector +0x30 + static_cast(CommonSingletonServer::m_iaiGameEffector)->suicide(bot->getPlayer()); + } + return true; + } + } + ok = infanteryResetControls(bot, bot->getInput(), true, false, false); + done = true; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToObject.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToObject.h new file mode 100644 index 000000000..22337963a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToObject.h @@ -0,0 +1,28 @@ +// EntryInfanteryMoveToObject: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYINFANTERYMOVETOOBJECT_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYINFANTERYMOVETOOBJECT_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryInfanteryMoveToObject - statement type 9. +class EntryInfanteryMoveToObject : public BAPEntry +{ +public: + EntryInfanteryMoveToObject(); + virtual ~EntryInfanteryMoveToObject(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYINFANTERYMOVETOOBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryResetControls.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryResetControls.cpp new file mode 100644 index 000000000..d0c7fcfc3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryResetControls.cpp @@ -0,0 +1,57 @@ +// EntryInfanteryResetControls (attested TU `EntryInfanteryResetControls.cpp`, split out of BAPEntries.cpp by S0). Recovered from +// libaidll.so (Linux 1.5.3153, ia-32): the soldier entry for BAPAResetControls (statement type 14). Package B; see docs/macos-ai-behaviour-plan.md. +// execute's flags follow the BotScript convention: `ok` (the step ran) and `done` (finished; with +// ok == false the statement failed). + +// static init: ELF 0x2B8900 (__tcf_0 0x2B8960, _GLOBAL__I 0x2B8990): 's Init object only. +#include + +#include "EntryInfanteryResetControls.h" + +#include "InfanteryControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../../../../IO/Input/PlayerInput.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryInfanteryResetControls::EntryInfanteryResetControls() +{ +} + +EntryInfanteryResetControls::~EntryInfanteryResetControls() +{ +} + +int EntryInfanteryResetControls::getTargetId() +{ + return 14; +} + +// ELF 0x2B86D0. A single-input reset releases that one input (the image inlines setInput(index, +// 0.0f) with its "1 setInput out of range" diagnostic); the group form resets through +// infanteryResetControls. Always succeeds and finishes at once. +bool EntryInfanteryResetControls::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAResetControls* reset = static_cast(script); + if (reset->hasSingleInput()) + { + io::PlayerInput* input = bot->getInput(); + input->setInput(static_cast(reset->getInput()), 0.0f); + } + else + { + // 0x2B88C0: movzbl +0x14 / +0x15 / +0x16 -> (move, look, trigger) + infanteryResetControls(bot, bot->getInput(), reset->m_resetMove, reset->m_resetLook, + reset->m_resetTrigger); + } + ok = true; + done = true; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryResetControls.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryResetControls.h new file mode 100644 index 000000000..1aa2ed6ab --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryResetControls.h @@ -0,0 +1,28 @@ +// EntryInfanteryResetControls: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYINFANTERYRESETCONTROLS_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYINFANTERYRESETCONTROLS_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryInfanteryResetControls - statement type 14. +class EntryInfanteryResetControls : public BAPEntry +{ +public: + EntryInfanteryResetControls(); + virtual ~EntryInfanteryResetControls(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYINFANTERYRESETCONTROLS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfoWrapper.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfoWrapper.cpp new file mode 100644 index 000000000..f39c6b0f4 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfoWrapper.cpp @@ -0,0 +1,41 @@ +// EntryInfoWrapper (attested TU `EntryInfoWrapper.cpp`, split out of BAPEntries.cpp by S0). Recovered from +// libaidll.so (Linux 1.5.3153, ia-32): the entry for BAPInfoWrapper (statement type 15). Package B; see docs/macos-ai-behaviour-plan.md. +// execute's flags follow the BotScript convention: `ok` (the step ran) and `done` (finished; with +// ok == false the statement failed). + +// static init: ELF 0x2B8AE0 (__tcf_0 0x2B8B40, _GLOBAL__I 0x2B8B70): 's Init object only. +#include + +#include "EntryInfoWrapper.h" + +#include "PlanInterpreter.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPInfoWrapper.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryInfoWrapper::EntryInfoWrapper() +{ +} + +EntryInfoWrapper::~EntryInfoWrapper() +{ +} + +int EntryInfoWrapper::getTargetId() +{ + return 15; +} + +// ELF 0x2B8A80. Runs the wrapped statement through the bot's plan interpreter (PlanInterpreter +8). +bool EntryInfoWrapper::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BotScript* inner = static_cast(script)->m_statement; // 0x2B8A98 +0x14 + return static_cast(bot)->getPlanInterpreter()->execute(inner, bot, ok, done); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfoWrapper.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfoWrapper.h new file mode 100644 index 000000000..d6c5f1dec --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfoWrapper.h @@ -0,0 +1,28 @@ +// EntryInfoWrapper: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYINFOWRAPPER_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYINFOWRAPPER_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryInfoWrapper - statement type 15. +class EntryInfoWrapper : public BAPEntry +{ +public: + EntryInfoWrapper(); + virtual ~EntryInfoWrapper(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYINFOWRAPPER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryKeyTurretAimAt.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryKeyTurretAimAt.cpp new file mode 100644 index 000000000..1a61d8e1b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryKeyTurretAimAt.cpp @@ -0,0 +1,147 @@ +// Key-driven turret aiming entry for BAPAAimAt. Attested TU: EntryKeyTurretAimAt.cpp. + +// static init: ELF 0x2B9580 (__tcf_0 0x2B95E0, _GLOBAL__I 0x2B9610): 's Init object only. +#include + +#include "EntryKeyTurretAimAt.h" + +#include "ControlFunctions.h" +#include "InfanteryControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAAimAt.h" +#include "../AIBotActionPlan/BAPCondition.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../../../../IO/Input/PlayerInput.h" +#include "../../../../Math/Mat4.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2B8BC0 (C1; C2 0x2B8BA0). +EntryKeyTurretAimAt::EntryKeyTurretAimAt() +{ +} + +// ELF 0x2B8C00 (D1; D2 0x2B8BE0, D0 0x2B8C20). +EntryKeyTurretAimAt::~EntryKeyTurretAimAt() +{ +} + +// ELF 0x2B9630. +int EntryKeyTurretAimAt::getTargetId() +{ + return 6; +} + +// ELF 0x2B8C60. Drives mapped pitch and yaw inputs from the weapon-relative aim vector and +// their previous errors. The plain target-vector fallback is used without normalising it. +bool EntryKeyTurretAimAt::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAAimAt* const aim = static_cast(script); + Vec3 direction; + direction.x = direction.y = direction.z = 0.0f; + Vec3 ownSpeed; + ownSpeed.x = ownSpeed.y = ownSpeed.z = 0.0f; + if (aim->m_endCondition->evaluate(bot)) + { + done = true; + ok = true; + aim->m_lastYawError = 3.141592741f; + return true; + } + done = false; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + aim->m_lastYawError = 3.141592741f; + return true; + } + IPIArmament* const armament = info->getArmament(); + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation( + armament->getWeapon(armament->getActiveWeapon())); + const Mat4& transformation = weapon->getAbsoluteTransformation(); + IPIMobile* mobile = info->getMobile(); + if (!mobile && !info->isPrimary()) + { + Information* const primary = informationManager->getInformation(info->getPrimaryObject(bot->getSide())); + if (primary) + mobile = primary->getMobile(); + } + if (mobile) + ownSpeed = mobile->getSpeed(); + const Mat4& origin = weapon->getProjectileOrigin(); + const bool indirect = weapon->getIndirect(); + const float gravity = weapon->getGravityModifier(); + const float velocity = weapon->getExitVelocity(); + const float drag = weapon->getDrag(); + if (!aim->getAimVec(origin, ownSpeed, direction, 0.5f, drag, velocity, gravity, indirect, bot)) + { + const Vec3& position = *reinterpret_cast(&transformation.m[12]); + if (!aim->getVectorToTarget(position, direction)) + { + done = true; + ok = false; + aim->m_lastYawError = 3.141592741f; + return true; + } + } + float pitchDot = direction.x * transformation.m[4] + direction.y * transformation.m[5] + + direction.z * transformation.m[6]; + if (pitchDot < -1.0f) + pitchDot = -1.0f; + else if (pitchDot > 1.0f) + pitchDot = 1.0f; + const float pitchError = acosf(pitchDot) - 1.570796371f; + float yawDot = direction.x * transformation.m[0] + direction.y * transformation.m[1] + + direction.z * transformation.m[2]; + if (yawDot < -1.0f) + yawDot = -1.0f; + else if (yawDot > 1.0f) + yawDot = 1.0f; + float yawError = acosf(yawDot) - 1.570796371f; + if (direction.x * transformation.m[8] + direction.y * transformation.m[9] + + direction.z * transformation.m[10] < 0.0f) + yawError = (yawError < 0.0f ? -3.141592741f : 3.141592741f) - yawError; + + IPIControlInfo* const controlInfo = info->getControlInfo(); + io::PlayerInput* const pitchInput = bot->getInput(); + const io::PlayerInputMap pitchMapping = controlInfo->getAimVerticalControl(); + float pitch = infantry_detail::inputValue(pitchInput, pitchMapping); + io::PlayerInput* const yawInput = bot->getInput(); + const io::PlayerInputMap yawMapping = controlInfo->getAimHorizontalControl(); + float yaw = infantry_detail::inputValue(yawInput, yawMapping); + const float pitchScale = controlInfo->getPitchScale(); + const float pitchLookAhead = controlInfo->getPitchLookAhead(); + const float pitchSensitivity = controlInfo->getPitchSensitivity(); + updateAngle(pitchError, pitchError - aim->m_pitchErrors[aim->m_pitchIndex], pitch, + pitchSensitivity, pitchLookAhead, pitchScale); + const float yawScale = controlInfo->getRollScale(); + const float yawLookAhead = controlInfo->getRollLookAhead(); + const float yawSensitivity = controlInfo->getRollSensitivity(); + updateAngle(yawError, yawError - aim->m_lastYawError, yaw, yawSensitivity, yawLookAhead, yawScale); + io::PlayerInput* const output = bot->getInput(); + const io::PlayerInputMap vertical = controlInfo->getAimVerticalControl(); + output->setInput(vertical, pitch); + const io::PlayerInputMap horizontal = controlInfo->getAimHorizontalControl(); + bot->getInput()->setInput(horizontal, yaw); + aim->m_pitchIndex = (aim->m_pitchIndex + 1) % 10; + aim->m_pitchErrors[aim->m_pitchIndex] = pitchError; + aim->m_lastYawError = yawError; + ok = true; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryKeyTurretAimAt.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryKeyTurretAimAt.h new file mode 100644 index 000000000..179d075a6 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryKeyTurretAimAt.h @@ -0,0 +1,27 @@ +// Key-driven turret aiming entry for BAPAAimAt. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYKEYTURRETAIMAT_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYKEYTURRETAIMAT_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryKeyTurretAimAt - statement type 6. +class EntryKeyTurretAimAt : public BAPEntry +{ +public: + EntryKeyTurretAimAt(); + virtual ~EntryKeyTurretAimAt(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYKEYTURRETAIMAT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretAimAt.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretAimAt.cpp new file mode 100644 index 000000000..a01a5ca8a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretAimAt.cpp @@ -0,0 +1,144 @@ +// EntryMouseTurretAimAt (attested TU `EntryMouseTurretAimAt.cpp`, split out of BAPEntries.cpp by S0). Recovered from +// libaidll.so (Linux 1.5.3153, ia-32): the soldier mouse-aim entry for BAPAAimAt and its subclasses (statement type 6). Package B; see docs/macos-ai-behaviour-plan.md. +// execute's flags follow the BotScript convention: `ok` (the step ran) and `done` (finished; with +// ok == false the statement failed). + +// static init: ELF 0x2B9D10 (__tcf_0 0x2B9D70, _GLOBAL__I 0x2B9DA0): 's Init object only. +#include + +#include "EntryMouseTurretAimAt.h" + +#include "InfanteryControl.h" +#include "MouseControl.h" +#include "../Main/CommonSingletonServer.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotSubObjects.h" +#include "../AIBot/SensingAgent.h" +#include "../AIBotActionPlan/BAPAAimAt.h" +#include "../AIBotActionPlan/BAPCondition.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryMouseTurretAimAt::EntryMouseTurretAimAt() +{ +} + +EntryMouseTurretAimAt::~EntryMouseTurretAimAt() +{ +} + +int EntryMouseTurretAimAt::getTargetId() +{ + return 6; +} + +// ELF 0x2B9700. Mouse-aims the soldier's active weapon with BAPAAimAt's ballistic aim vector +// (falling back to the plain vector to the target), with the target's angular speed as feed-forward +// and the average of the last ten pitch errors as the vertical bias. The end condition finishes it. +bool EntryMouseTurretAimAt::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAAimAt* aim = static_cast(script); + Vec3 dir; + dir.x = dir.y = dir.z = 0.0f; + Vec3 ownSpeed; + ownSpeed.x = ownSpeed.y = ownSpeed.z = 0.0f; + bot->getSensingAgent()->setOverride(true); + if (!aim->m_endCondition->evaluate(bot)) + { + done = false; + Information* info = informationManager->getInformation(bot->getCurrentEquipment()); + if (info != 0) + { + IPIControlInfo* controlInfo = info->getControlInfo(); + IPIArmament* armament = info->getArmament(); + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + const Mat4& weaponTransformation = weapon->getAbsoluteTransformation(); + IPIMobile* mobile = info->getMobile(); + if (mobile == 0 && !info->isPrimary()) + { + Information* primary = informationManager->getInformation(info->getPrimaryObject(bot->getSide())); + if (primary != 0) + mobile = primary->getMobile(); + } + if (mobile != 0) + ownSpeed = mobile->getSpeed(); + const Mat4& origin = weapon->getProjectileOrigin(); + Vec3 lastAim; + lastAim.x = lastAim.y = lastAim.z = 0.0f; + const bool haveLastAim = aim->getLastAimVec(lastAim) != 0; + const bool indirect = weapon->getIndirect(); + const float gravity = weapon->getGravityModifier(); + const float exitVelocity = weapon->getExitVelocity(); + const float drag = weapon->getDrag(); + if (!aim->getAimVec(origin, ownSpeed, dir, 0.5f, drag, exitVelocity, gravity, indirect, bot)) + { + Vec3 from; + from.x = weaponTransformation.m[12]; + from.y = weaponTransformation.m[13]; + from.z = weaponTransformation.m[14]; + if (!aim->getVectorToTarget(from, dir)) // slot +0x28, 0x2B9985 test al + { + done = true; + ok = false; + aim->m_lastYawError = 3.14159274f; + return true; + } + infantry_detail::normaliseInline(dir); + } + Vec3 predicted; + predicted.x = predicted.y = predicted.z = 0.0f; + aim->getPredictedPosition(predicted); + // 0x2B9A5C: BotMain +0xB4; only while a correction shot is out (+6). + FireCorrectionData* correction = static_cast(bot)->getFireCorrection(); + if (correction->m_flag6) + { + correction->m_aimDirection = dir; // +0x20 + correction->m_predictedTarget = predicted; // +0x38 + } + + float yawSpeed = 0.0f; + float pitchSpeed = 0.0f; + if (haveLastAim) + { + const float dt = static_cast(static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease()); + yawSpeed = getSignedDiffAngleToDirXZ(lastAim, dir) / dt; + pitchSpeed = getSignedDiffAngleToDirYZ(lastAim, dir) / dt; + } + ok = true; + const float averagePitch = aim->getAveragePitchAngle(); + float pitchError; + float yawError; + mouseControlLookAtDirection(bot, dir, origin, pitchError, aim->m_pitchErrors[aim->m_pitchIndex], yawError, + aim->m_lastYawError, 0.0043633231f, controlInfo, bot->getInput(), + averagePitch, yawSpeed, pitchSpeed); + aim->m_pitchIndex = (aim->m_pitchIndex + 1) % 10; + aim->m_pitchErrors[aim->m_pitchIndex] = pitchError; + aim->m_lastYawError = yawError; + return true; + } + done = true; + ok = false; + } + else + { + done = true; + ok = true; + } + aim->m_lastYawError = 3.14159274f; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretAimAt.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretAimAt.h new file mode 100644 index 000000000..382a4d3e5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretAimAt.h @@ -0,0 +1,28 @@ +// EntryMouseTurretAimAt: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOUSETURRETAIMAT_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOUSETURRETAIMAT_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryMouseTurretAimAt - statement type 6. +class EntryMouseTurretAimAt : public BAPEntry +{ +public: + EntryMouseTurretAimAt(); + virtual ~EntryMouseTurretAimAt(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOUSETURRETAIMAT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretLookAt.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretLookAt.cpp new file mode 100644 index 000000000..07ef75eea --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretLookAt.cpp @@ -0,0 +1,97 @@ +// EntryMouseTurretLookAt (attested TU `EntryMouseTurretLookAt.cpp`, split out of BAPEntries.cpp by S0). Recovered from +// libaidll.so (Linux 1.5.3153, ia-32): the soldier mouse-look entry for BAPALook and its subclasses (statement type 23). Package B; see docs/macos-ai-behaviour-plan.md. +// execute's flags follow the BotScript convention: `ok` (the step ran) and `done` (finished; with +// ok == false the statement failed). + +// static init: ELF 0x2BA240 (__tcf_0 0x2BA2A0, _GLOBAL__I 0x2BA2D0): 's Init object only. +#include + +#include "EntryMouseTurretLookAt.h" + +#include "MouseControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SensingAgent.h" +#include "../AIBotActionPlan/BAPALook.h" +#include "../AIBotActionPlan/BAPCondition.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" +#include "InfanteryControl.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryMouseTurretLookAt::EntryMouseTurretLookAt() +{ +} + +EntryMouseTurretLookAt::~EntryMouseTurretLookAt() +{ +} + +int EntryMouseTurretLookAt::getTargetId() +{ + return 23; +} + +// BAPALook fields as this entry uses them (0x2B9E90): +0x18 (m_lookSpeed) is +// mouseControlLookAtDirection's allowed deviation, +0x1C (m_deviation) the last yaw error and +// +0x20 (m_lastControl) the last pitch error. + +// ELF 0x2B9E90. Mouse-look towards BAPALook's direction; the end condition finishes the look. +// A direction that is not available fails the statement softly (not done, yaw error reset to pi). +bool EntryMouseTurretLookAt::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPALook* look = static_cast(script); + bot->getSensingAgent()->setOverride(true); + if (!look->m_endCondition->evaluate(bot)) + { + done = false; + Information* info = informationManager->getInformation(bot->getCurrentEquipment()); + if (info != 0) + { + Vec3 dir = look->getLookDirection(ok); + infantry_detail::normaliseInline(dir); + if (!ok) + { + done = false; + look->m_deviation = 3.14159274f; + return true; + } + IPIControlInfo* controlInfo = info->getControlInfo(); + ok = true; + io::PlayerInput* input = bot->getInput(); + const float allowed = look->m_lookSpeed; + const float lastYaw = look->m_deviation; + const float lastPitch = look->m_lastControl; + const Mat4& camera = *static_cast(bot->getPlayer()->getCameraTransformation()); + float pitchError; + float yawError; + mouseControlLookAtDirection(bot, dir, camera, pitchError, lastPitch, yawError, lastYaw, allowed, + controlInfo, input, 0.0f, 0.0f, 0.0f); + look->m_deviation = yawError; + look->m_lastControl = pitchError; + const Mat4& after = *static_cast(bot->getPlayer()->getCameraTransformation()); + look->m_cameraForward.x = after.m[8]; + look->m_cameraForward.y = after.m[9]; + look->m_cameraForward.z = after.m[10]; + return true; + } + done = true; + ok = false; + } + else + { + done = true; + ok = true; + } + look->m_deviation = 3.14159274f; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretLookAt.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretLookAt.h new file mode 100644 index 000000000..fe8739158 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretLookAt.h @@ -0,0 +1,28 @@ +// EntryMouseTurretLookAt: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOUSETURRETLOOKAT_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOUSETURRETLOOKAT_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryMouseTurretLookAt - statement type 23. +class EntryMouseTurretLookAt : public BAPEntry +{ +public: + EntryMouseTurretLookAt(); + virtual ~EntryMouseTurretLookAt(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOUSETURRETLOOKAT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMedium.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMedium.cpp new file mode 100644 index 000000000..4f6a458f8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMedium.cpp @@ -0,0 +1,207 @@ +// Medium-LOD vehicle movement entry. Attested TU: EntryMoveToMedium.cpp. + +// static init: ELF 0x2BB1C0 (__tcf_0 0x2BB220, _GLOBAL__I 0x2BB250): 's Init object only. +#include + +#include "EntryMoveToMedium.h" + +#include "InfanteryControl.h" +#include "TankControl.h" +#include "VehicleControlInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../Math/Mat4.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// ELF 0x2BA300. The output's y is cleared before the trigonometric calls; input may alias output. +void rotate2d(const Vec3& input, Vec3& output, float angle) +{ + output.y = 0.0f; + const float cosine = cosf(angle); + const float sine = sinf(angle); + output.x = cosine * input.x - sine * input.z; + output.z = sine * input.x + cosine * input.z; +} + +} // namespace + +// ELF 0x2BA3A0 (C1; C2 0x2BA380). +EntryMoveToMedium::EntryMoveToMedium() +{ +} + +// ELF 0x2BA3E0 (D1; D2 0x2BA3C0, D0 0x2BA400). +EntryMoveToMedium::~EntryMoveToMedium() +{ +} + +// ELF 0x2BB270. +int EntryMoveToMedium::getTargetId() +{ + return 7; +} + +// ELF 0x2BA440. Moves a vehicle without physics, limits its heading change by the turn radius, +// and aligns the resulting transform with the terrain normal. +bool EntryMoveToMedium::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveTo* const moveTo = static_cast(script); + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + return true; + } + IAIObject* const object = info->getAIObject(); + IAIObjectMobile* const mobile = object->getMobile(); + IAIObjectPhysical* const physical = object->getPhysical(); + if (physical->hasPhysicsEnabled()) + physical->disablePhysics(object->getSide()); + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + done = false; + const Vec3 facing = info->getFaceing(); + const Vec3& velocity = mobile->getSpeed(); + TankControl::resetControls(bot, bot->getInput(), true, false, false, + velocity.x * facing.x + velocity.y * facing.y + velocity.z * facing.z); + Vec3 position = object->getPosition(); + Vec2 position2; + vec3ToVec2XZ(position, position2); + Vec2 point; + point.x = point.y = 0.0f; + bool arrived; + ok = static_cast(moveTo->update(point, done, arrived, 0.0f)) != 0; + if (!ok) + { + done = true; + return true; + } + if (done || arrived) + return true; + Vec2 delta; + delta.x = point.x - position2.x; + delta.y = point.y - position2.y; + const float distance = std::sqrt(delta.x * delta.x + delta.y * delta.y); + const Mat4 previous = object->getTransformation(); + Vec2 forward2; + forward2.x = previous.m[8]; + forward2.y = previous.m[10]; + vehiclecontrol::normalizeVec2(forward2); + // The shipped angle calculation divides by distance even when it is zero. + const float inverse = 1.0f / distance; + const float targetX = inverse * delta.x; + const float targetZ = inverse * delta.y; + float rightDot = targetX * forward2.y - targetZ * forward2.x; + const float forwardDot = targetX * forward2.x + targetZ * forward2.y; + if (rightDot < -1.0f) + rightDot = -1.0f; + else if (rightDot > 1.0f) + rightDot = 1.0f; + float angle = acosf(rightDot) - 1.570796371f; + if (forwardDot < 0.0f) + { + const float sign = angle > 0.0f ? 1.0f : (0.0f > angle ? -1.0f : 0.0f); + angle = sign * 3.141592741f - angle; + } + const float speedFactor = forwardDot < 0.2f ? 0.2f : forwardDot; + const float scaledSpeed = speedFactor * previous.m[5] * 0.6f; + const float speed = mobile->getMaxSpeed() * scaledSpeed; + const double timeIncrease = static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease(); + const float dt = static_cast(timeIncrease); + const float step = dt * speed; + const float radius = mobile->getTurnRadius(); + const float limitedRadius = radius < 1.0f ? 1.0f : radius; + const float angularStep = step / limitedRadius; + const float limit = angularStep < 0.003926991f ? 0.003926991f : angularStep; + Vec3 forward; + if (limit < 6.283185482f && std::fabs(angle) > limit) + { + Vec3 current; + current.x = forward2.x; + current.y = 0.0f; + current.z = forward2.y; + const float sign = angle > 0.0f ? 1.0f : (0.0f > angle ? -1.0f : 0.0f); + rotate2d(current, forward, sign * limit); + } + else + { + forward.x = delta.x; + forward.y = 0.0f; + forward.z = delta.y; + } + if (!(static_cast(speed) * timeIncrease > static_cast(distance))) + { + if (distance > 1e-05f) + { + const float invDistance = 1.0f / distance; + delta.x = delta.x * invDistance; + delta.y = invDistance * delta.y; + } + position.x = delta.x * dt * speed + position.x; + position.z = delta.y * dt * speed + position.z; + } + else if (!(distance > 0.5f)) + { + position.x = previous.m[8] * 0.5f + position.x; + position.z = 0.5f * previous.m[10] + position.z; + } + else + { + position.x = delta.x + position.x; + position.z = delta.y + position.z; + } + vehiclecontrol::normalizeVec3(forward); + const float currentHeight = info->getPosition().y; + float height; + Vec3 up; + up.x = up.y = up.z = 0.0f; + float slope; + static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->getHeightAndNormalForObject(object, position, height, up, slope); + if (!(currentHeight > height) || !(currentHeight - height > slope + slope)) + position.y = mobile->getLodHeight() + height; + else + position.y = currentHeight - slope; + Vec3 right = infantry_detail::crossInline(up, forward); + vehiclecontrol::normalizeVec3(right); + forward = infantry_detail::crossInline(right, up); + vehiclecontrol::normalizeVec3(forward); + Mat4 transformation = object->getTransformation(); + transformation.m[0] = right.x; + transformation.m[1] = right.y; + transformation.m[2] = right.z; + transformation.m[4] = up.x; + transformation.m[5] = up.y; + transformation.m[6] = up.z; + transformation.m[8] = forward.x; + transformation.m[9] = forward.y; + transformation.m[10] = forward.z; + transformation.m[12] = position.x; + transformation.m[13] = position.y; + transformation.m[14] = position.z; + object->setTransformation(transformation, bot->getSide()); + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMedium.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMedium.h new file mode 100644 index 000000000..d60a58b50 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMedium.h @@ -0,0 +1,27 @@ +// Medium-LOD vehicle movement entry. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOMEDIUM_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOMEDIUM_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryMoveToMedium - statement type 7. +class EntryMoveToMedium : public BAPEntry +{ +public: + EntryMoveToMedium(); + virtual ~EntryMoveToMedium(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOMEDIUM_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumBoat.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumBoat.cpp new file mode 100644 index 000000000..8b74dfbdd --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumBoat.cpp @@ -0,0 +1,236 @@ +// Medium-LOD boat movement entry. Attested TU: EntryMoveToMediumBoat.cpp. + +// static init: ELF 0x2BC280 (__tcf_0 0x2BC2E0, _GLOBAL__I 0x2BC310): 's Init object only. +#include + +#include "EntryMoveToMediumBoat.h" + +#include "BoatControl.h" +#include "InfanteryControl.h" +#include "VehicleControlInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IAIPathfinding.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../Math/LocalBoundingBox.h" +#include "../../../../Math/Mat4.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// ELF 0x2BB280. +void rotate2d(const Vec3& input, Vec3& output, float angle) +{ + output.y = 0.0f; + const float cosine = cosf(angle); + const float sine = sinf(angle); + output.x = cosine * input.x - sine * input.z; + output.z = sine * input.x + cosine * input.z; +} + +} // namespace + +// ELF 0x2BB320 (C1; C2 0x2BB300). +EntryMoveToMediumBoat::EntryMoveToMediumBoat() +{ +} + +// ELF 0x2BB360 (D1; D2 0x2BB340, D0 0x2BB380). +EntryMoveToMediumBoat::~EntryMoveToMediumBoat() +{ +} + +// ELF 0x2BC330. +int EntryMoveToMediumBoat::getTargetId() +{ + return 7; +} + +// ELF 0x2BB3C0. Moves the boat without physics, retaining a running statement when both the +// current and proposed positions fail the pathfinding check. Grounded boats follow the terrain; +// floating boats use the water level and a world-up axis. +bool EntryMoveToMediumBoat::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveTo* const moveTo = static_cast(script); + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + return true; + } + IAIObject* const object = info->getAIObject(); + IAIObjectPhysical* const physical = object->getPhysical(); + if (physical->hasPhysicsEnabled()) + physical->disablePhysics(object->getSide()); + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + done = false; + bool resetDone; + BoatControl::resetControls(bot, true, false, false, resetDone); + Vec3 position = object->getPosition(); + Vec2 position2; + vec3ToVec2XZ(position, position2); + Vec2 point; + point.x = point.y = 0.0f; + bool arrived; + ok = static_cast(moveTo->update(point, done, arrived, 0.0f)) != 0; + if (!ok) + { + done = true; + return true; + } + if (done || arrived) + return true; + Vec2 delta; + delta.x = point.x - position2.x; + delta.y = point.y - position2.y; + const float distance = std::sqrt(delta.x * delta.x + delta.y * delta.y); + if (distance <= 0.01f) + { + done = true; + return true; + } + object->releaseObjectFromSpawner(); + IAIObjectMobile* const mobile = object->getMobile(); + const Mat4 previous = object->getTransformation(); + Vec2 forward2; + forward2.x = previous.m[8]; + forward2.y = previous.m[10]; + vehiclecontrol::normalizeVec2(forward2); + const float inverse = 1.0f / distance; + const float targetX = inverse * delta.x; + const float targetZ = inverse * delta.y; + float rightDot = targetX * forward2.y - targetZ * forward2.x; + const float forwardDot = targetX * forward2.x + targetZ * forward2.y; + if (rightDot < -1.0f) + rightDot = -1.0f; + else if (rightDot > 1.0f) + rightDot = 1.0f; + float angle = acosf(rightDot) - 1.570796371f; + if (forwardDot < 0.0f) + { + const float sign = angle > 0.0f ? 1.0f : (0.0f > angle ? -1.0f : 0.0f); + angle = sign * 3.141592741f - angle; + } + IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + const float speedFactor = forwardDot < 0.2f ? 0.2f : forwardDot; + const float scaledSpeed = speedFactor * previous.m[5] * 0.9f; + const float speed = mobile->getMaxSpeed() * scaledSpeed; + const double timeIncrease = static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease(); + const float dt = static_cast(timeIncrease); + const float step = dt * speed; + const float radius = mobile->getTurnRadius(); + const float limitedRadius = radius < 1.0f ? 1.0f : radius; + const float angularStep = step / limitedRadius; + const float limit = angularStep < 0.003926991f ? 0.003926991f : angularStep; + Vec3 forward; + if (limit < 6.283185482f && std::fabs(angle) > limit) + { + Vec3 current; + current.x = forward2.x; + current.y = 0.0f; + current.z = forward2.y; + const float sign = angle > 0.0f ? 1.0f : (0.0f > angle ? -1.0f : 0.0f); + rotate2d(current, forward, sign * limit); + } + else + { + forward.x = delta.x; + forward.y = 0.0f; + forward.z = delta.y; + } + if (!(static_cast(speed) * timeIncrease > static_cast(distance))) + { + if (distance > 1e-05f) + { + const float invDistance = 1.0f / distance; + delta.x = delta.x * invDistance; + delta.y = invDistance * delta.y; + } + position.x = delta.x * dt * speed + position.x; + position.z = delta.y * dt * speed + position.z; + } + else if (!(distance > 0.5f)) + { + position.x = previous.m[8] * 0.5f + position.x; + position.z = 0.5f * previous.m[10] + position.z; + } + else + { + position.x = delta.x + position.x; + position.z = delta.y + position.z; + } + vehiclecontrol::normalizeVec3(forward); + const int equipmentType = info->getUnit()->getEquipmentType(); + if (static_cast(moveTo->usesPathfinding())) + { + const Vec3& currentPosition = info->getPosition(); + const int vehicle = mobile->getVehicleNumber(); + if (!IAIPathfinding::instance->isValidPosition(vehicle, equipmentType, currentPosition, true)) + { + const int candidateVehicle = mobile->getVehicleNumber(); + if (!IAIPathfinding::instance->isValidPosition(candidateVehicle, equipmentType, position, true)) + return true; + } + } + Vec3 up; + up.x = up.y = up.z = 0.0f; + unsigned char material; + const float height = terrain->getHeightAndNormal(position.x, position.z, up, material); + const float water = terrain->getWaterLevel(position.x, position.z); + const float lodHeight = mobile->getLodHeight(); + Vec3 right; + if (water - lodHeight > height) + { + position.y = mobile->getLodHeight() + water; + up.x = 0.0f; + up.y = 1.0f; + up.z = 0.0f; + right = infantry_detail::crossInline(up, forward); + } + else + { + LocalBoundingBox* const bounds = const_cast(physical->getLocalBoundingBox()); + position.y = 0.5f * bounds->getSize().y + height; + right = infantry_detail::crossInline(up, forward); + vehiclecontrol::normalizeVec3(right); + forward = infantry_detail::crossInline(right, up); + vehiclecontrol::normalizeVec3(forward); + } + Mat4 transformation = object->getTransformation(); + transformation.m[0] = right.x; + transformation.m[1] = right.y; + transformation.m[2] = right.z; + transformation.m[4] = up.x; + transformation.m[5] = up.y; + transformation.m[6] = up.z; + transformation.m[8] = forward.x; + transformation.m[9] = forward.y; + transformation.m[10] = forward.z; + transformation.m[12] = position.x; + transformation.m[13] = position.y; + transformation.m[14] = position.z; + object->setTransformation(transformation, bot->getSide()); + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumBoat.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumBoat.h new file mode 100644 index 000000000..fa88d6110 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumBoat.h @@ -0,0 +1,27 @@ +// Medium-LOD boat movement entry. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOMEDIUMBOAT_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOMEDIUMBOAT_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryMoveToMediumBoat - statement type 7. +class EntryMoveToMediumBoat : public BAPEntry +{ +public: + EntryMoveToMediumBoat(); + virtual ~EntryMoveToMediumBoat(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOMEDIUMBOAT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumSoldier.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumSoldier.cpp new file mode 100644 index 000000000..b97ccf83b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumSoldier.cpp @@ -0,0 +1,193 @@ +// EntryMoveToMediumSoldier (attested TU `EntryMoveToMediumSoldier.cpp`, split out of BAPEntries.cpp by S0). Recovered from +// libaidll.so (Linux 1.5.3153, ia-32): the medium-LOD soldier entry for BAPAMoveTo (statement type 7). Package B; see docs/macos-ai-behaviour-plan.md. +// execute's flags follow the BotScript convention: `ok` (the step ran) and `done` (finished; with +// ok == false the statement failed). + +// static init: ELF 0x2BCFF0 (__tcf_0 0x2BD050, _GLOBAL__I 0x2BD080): 's Init object only. +#include + +#include "EntryMoveToMediumSoldier.h" + +#include "InfanteryControl.h" +#include "../Main/CommonSingletonServer.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryMoveToMediumSoldier::EntryMoveToMediumSoldier() +{ +} + +EntryMoveToMediumSoldier::~EntryMoveToMediumSoldier() +{ +} + +int EntryMoveToMediumSoldier::getTargetId() +{ + return 7; +} + +using infantry_detail::crossInline; +using infantry_detail::normaliseInline; + +// ELF 0x2BC400. Medium LOD: no inputs are simulated. Physics is switched off and the soldier's +// transformation is moved directly towards the BAPAMoveTo point at its top speed (halved +// crouching, quartered lying, 0 for any other pose), snapped to the ground (or let down by at most +// the slope step when it is above it) and oriented along the move; a lying soldier is aligned to +// the ground normal and lowered by 0.5. Close to the point (within one step) it jumps there, and +// within 0.5 m it moves half a metre along its current facing. +bool EntryMoveToMediumSoldier::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveTo* moveTo = static_cast(script); + Mat4 transformation; + for (int i = 0; i < 16; ++i) + transformation.m[i] = 0.0f; + Vec2 dir; + dir.x = dir.y = 0.0f; + Vec3 right; + right.x = right.y = right.z = 0.0f; + Vec3 forward; + forward.x = forward.y = forward.z = 0.0f; + Vec3 up; + up.x = up.y = up.z = 0.0f; + Vec2 goal; + goal.x = goal.y = 0.0f; + Vec3 position; + position.x = position.y = position.z = 0.0f; + Vec2 position2; + position2.x = position2.y = 0.0f; + + Information* info = informationManager->getInformation(bot->getCurrentEquipment()); + if (info == 0) + { + done = true; + ok = false; + return true; + } + IAIObject* object = info->getAIObject(); + IAIObjectPhysical* physical = object->getPhysical(); + if (physical->hasPhysicsEnabled()) + physical->disablePhysics(object->getSide()); + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + done = false; + infanteryResetControls(bot, bot->getInput(), true, false, false); + position = object->getPosition(); + vec3ToVec2XZ(position, position2); + bool arrived; + ok = moveTo->update(goal, done, arrived, 0.0f) != 0; + if (!ok) + { + done = true; + return true; + } + if (done || arrived) + return true; + + Vec2 delta; + delta.x = goal.x - position2.x; + delta.y = goal.y - position2.y; + const float distance = std::sqrt(delta.y * delta.y + delta.x * delta.x); + dir = delta; + IAIObjectMobile* mobile = object->getMobile(); + const float dt = static_cast(static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease()); + float speed = mobile->getMaxSpeed(); + bot->requestSoldierPose(SPStanding, false); + const SoldierPose pose = info->getSoldierPose(); + if (pose == SPCrouching) + speed = speed * 0.5f; + else if (pose == SPLying) + speed = speed * 0.25f; + else if (pose != SPStanding) + speed = 0.0f; + transformation = object->getTransformation(); + + if (dt * speed <= distance) + { + if (1e-05f < distance) + { + dir.x = dir.x * (1.0f / distance); + dir.y = (1.0f / distance) * dir.y; + } + const float stepZ = dt * dir.y * speed; + const float stepX = dir.x * dt * speed; + position.x = stepX + position.x; + position.z = stepZ + position.z; + vec2ToVec3XZ(dir, forward); + } + else if (distance <= 0.5f) + { + position.x = transformation.m[8] * 0.5f + position.x; + position.z = transformation.m[10] * 0.5f + position.z; + forward.x = transformation.m[8]; + forward.y = transformation.m[9]; + forward.z = transformation.m[10]; + } + else + { + position.x = dir.x + position.x; + position.z = dir.y + position.z; + vec2ToVec3XZ(dir, forward); + } + normaliseInline(forward); + + const float currentHeight = info->getPosition().y; + float ground; + float slope; + static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->getHeightAndNormalForObject(object, position, ground, up, slope); + if (currentHeight <= ground || currentHeight - ground <= slope + slope) + position.y = mobile->getLodHeight() + ground; + else + position.y = currentHeight - slope; + + if (pose == SPLying) + { + position.y = position.y - 0.5f; + right = crossInline(up, forward); + normaliseInline(right); + forward = crossInline(right, up); + normaliseInline(forward); + } + else + { + // upright: up is the world y axis; the right vector stays unnormalised here (retail) + up.x = 0.0f; + up.y = 1.0f; + up.z = 0.0f; + right = crossInline(up, forward); + } + transformation.m[12] = position.x; + transformation.m[13] = position.y; + transformation.m[14] = position.z; + transformation.m[0] = right.x; + transformation.m[1] = right.y; + transformation.m[2] = right.z; + transformation.m[4] = up.x; + transformation.m[5] = up.y; + transformation.m[6] = up.z; + transformation.m[8] = forward.x; + transformation.m[9] = forward.y; + transformation.m[10] = forward.z; + object->setTransformation(transformation, bot->getSide()); + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumSoldier.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumSoldier.h new file mode 100644 index 000000000..bffb745af --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumSoldier.h @@ -0,0 +1,28 @@ +// EntryMoveToMediumSoldier: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOMEDIUMSOLDIER_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOMEDIUMSOLDIER_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryMoveToMediumSoldier - statement type 7. +class EntryMoveToMediumSoldier : public BAPEntry +{ +public: + EntryMoveToMediumSoldier(); + virtual ~EntryMoveToMediumSoldier(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOMEDIUMSOLDIER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMedium.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMedium.cpp new file mode 100644 index 000000000..61791d003 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMedium.cpp @@ -0,0 +1,201 @@ +// Medium-LOD vehicle movement towards an object. Attested TU: EntryMoveToObjectMedium.cpp. + +// static init: ELF 0x2BDED0 (__tcf_0 0x2BDF30, _GLOBAL__I 0x2BDF60): 's Init object only. +#include + +#include "EntryMoveToObjectMedium.h" + +#include "InfanteryControl.h" +#include "TankControl.h" +#include "VehicleControlInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../Math/Mat4.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// ELF 0x2BD0B0. +void rotate2d(const Vec3& input, Vec3& output, float angle) +{ + output.y = 0.0f; + const float cosine = cosf(angle); + const float sine = sinf(angle); + output.x = cosine * input.x - sine * input.z; + output.z = sine * input.x + cosine * input.z; +} + +} // namespace + +// ELF 0x2BD150 (C1; C2 0x2BD130). +EntryMoveToObjectMedium::EntryMoveToObjectMedium() +{ +} + +// ELF 0x2BD190 (D1; D2 0x2BD170, D0 0x2BD1B0). +EntryMoveToObjectMedium::~EntryMoveToObjectMedium() +{ +} + +// ELF 0x2BDF80. +int EntryMoveToObjectMedium::getTargetId() +{ + return 9; +} + +// ELF 0x2BD1F0. A missing object finishes successfully. Arrival clears done, and movement +// follows the turn-limited heading until the remaining distance is shorter than a tick's step. +bool EntryMoveToObjectMedium::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveTo* const moveTo = static_cast(script); + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + return true; + } + IAIObject* const object = info->getAIObject(); + IAIObjectMobile* const mobile = object->getMobile(); + IAIObjectPhysical* const physical = object->getPhysical(); + if (physical->hasPhysicsEnabled()) + physical->disablePhysics(info->getSide()); + const Vec3 facing = info->getFaceing(); + const Vec3& velocity = mobile->getSpeed(); + TankControl::resetControls(bot, bot->getInput(), true, false, false, + velocity.x * facing.x + velocity.y * facing.y + velocity.z * facing.z); + Information* const target = informationManager->getInformation(moveTo->getObject()); + if (!target || moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + done = false; + Vec2 point; + point.x = point.y = 0.0f; + bool arrived; + ok = static_cast(moveTo->update(point, done, arrived, 0.0f)) != 0; + if (!ok) + { + done = true; + return true; + } + if (done || arrived) + { + done = false; + return true; + } + const float ownX = info->getPosition().x; + const float ownZ = info->getPosition().z; + const Vec3& ownPosition = info->getPosition(); + const Vec3& targetPosition = target->getPosition(); + (void)(targetPosition.z - ownPosition.z); + Vec2 delta; + delta.x = point.x - ownX; + delta.y = point.y - ownZ; + const float distance = std::sqrt(delta.x * delta.x + delta.y * delta.y); + if (distance <= 0.01f) + { + done = false; + return true; + } + Mat4 transformation = object->getTransformation(); + const double timeIncrease = static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease(); + Vec2 forward2; + forward2.x = transformation.m[8]; + forward2.y = transformation.m[10]; + vehiclecontrol::normalizeVec2(forward2); + const float inverse = 1.0f / distance; + const float targetX = inverse * delta.x; + const float targetZ = inverse * delta.y; + float rightDot = targetX * forward2.y - targetZ * forward2.x; + const float forwardDot = targetX * forward2.x + targetZ * forward2.y; + if (rightDot < -1.0f) + rightDot = -1.0f; + else if (rightDot > 1.0f) + rightDot = 1.0f; + float angle = acosf(rightDot) - 1.570796371f; + if (forwardDot < 0.0f) + { + const float sign = angle > 0.0f ? 1.0f : (0.0f > angle ? -1.0f : 0.0f); + angle = sign * 3.141592741f - angle; + } + const float speedFactor = forwardDot < 0.2f ? 0.2f : forwardDot; + const float scaledSpeed = speedFactor * transformation.m[5] * 0.6f; + const float speed = mobile->getMaxSpeed() * scaledSpeed; + Vec3 position = object->getPosition(); + Vec3 forward; + forward.x = delta.x / distance; + forward.y = 0.0f; + forward.z = delta.y / distance; + const float dt = static_cast(timeIncrease); + const float step = dt * speed; + const float radius = mobile->getTurnRadius(); + const float limitedRadius = radius < 1.0f ? 1.0f : radius; + const float angularStep = step / limitedRadius; + const float limit = angularStep < 0.003926991f ? 0.003926991f : angularStep; + if (limit < 6.283185482f && std::fabs(angle) > limit) + { + Vec3 current; + current.x = forward2.x; + current.y = 0.0f; + current.z = forward2.y; + const float sign = angle > 0.0f ? 1.0f : (0.0f > angle ? -1.0f : 0.0f); + rotate2d(current, forward, sign * limit); + } + float stepX = delta.x; + float stepZ = delta.y; + if (!(static_cast(speed) * timeIncrease > static_cast(distance))) + { + stepX = forward.x * dt * speed; + stepZ = forward.z * dt * speed; + } + position.x = stepX + position.x; + position.z = stepZ + position.z; + const float currentHeight = info->getPosition().y; + float height; + Vec3 up; + up.x = up.y = up.z = 0.0f; + float slope; + static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->getHeightAndNormalForObject(object, position, height, up, slope); + if (!(currentHeight > height) || !(currentHeight - height > slope + slope)) + position.y = mobile->getLodHeight() + height; + else + position.y = currentHeight - slope; + Vec3 right = infantry_detail::crossInline(up, forward); + vehiclecontrol::normalizeVec3(right); + forward = infantry_detail::crossInline(right, up); + vehiclecontrol::normalizeVec3(forward); + transformation.m[0] = right.x; + transformation.m[1] = right.y; + transformation.m[2] = right.z; + transformation.m[4] = up.x; + transformation.m[5] = up.y; + transformation.m[6] = up.z; + transformation.m[8] = forward.x; + transformation.m[9] = forward.y; + transformation.m[10] = forward.z; + transformation.m[12] = position.x; + transformation.m[13] = position.y; + transformation.m[14] = position.z; + object->setTransformation(transformation, bot->getSide()); + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMedium.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMedium.h new file mode 100644 index 000000000..850713390 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMedium.h @@ -0,0 +1,27 @@ +// Medium-LOD vehicle movement towards an object. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOOBJECTMEDIUM_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOOBJECTMEDIUM_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryMoveToObjectMedium - statement type 9. +class EntryMoveToObjectMedium : public BAPEntry +{ +public: + EntryMoveToObjectMedium(); + virtual ~EntryMoveToObjectMedium(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOOBJECTMEDIUM_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumBoat.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumBoat.cpp new file mode 100644 index 000000000..06ec9d5a0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumBoat.cpp @@ -0,0 +1,209 @@ +// Medium-LOD boat movement towards an object. Attested TU: EntryMoveToObjectMediumBoat.cpp. + +// static init: ELF 0x2BEE60 (__tcf_0 0x2BEEC0, _GLOBAL__I 0x2BEEF0): 's Init object only. +#include + +#include "EntryMoveToObjectMediumBoat.h" + +#include "InfanteryControl.h" +#include "VehicleControlInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../Math/LocalBoundingBox.h" +#include "../../../../Math/Mat4.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// ELF 0x2BDF90. +void rotate2d(const Vec3& input, Vec3& output, float angle) +{ + output.y = 0.0f; + const float cosine = cosf(angle); + const float sine = sinf(angle); + output.x = cosine * input.x - sine * input.z; + output.z = sine * input.x + cosine * input.z; +} + +} // namespace + +// ELF 0x2BE030 (C1; C2 0x2BE010). +EntryMoveToObjectMediumBoat::EntryMoveToObjectMediumBoat() +{ +} + +// ELF 0x2BE070 (D1; D2 0x2BE050, D0 0x2BE090). +EntryMoveToObjectMediumBoat::~EntryMoveToObjectMediumBoat() +{ +} + +// ELF 0x2BEF10. +int EntryMoveToObjectMediumBoat::getTargetId() +{ + return 9; +} + +// ELF 0x2BE0D0. A missing target finishes successfully; arrival keeps the statement active. +// The terrain basis uses the previous transform's forward axis, while movement uses the limited +// target heading. There is no zero-distance guard before the direction divisions. +bool EntryMoveToObjectMediumBoat::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveTo* const moveTo = static_cast(script); + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + return true; + } + IAIObject* const object = info->getAIObject(); + IAIObjectMobile* const mobile = object->getMobile(); + IAIObjectPhysical* const physical = object->getPhysical(); + if (physical->hasPhysicsEnabled()) + physical->disablePhysics(object->getSide()); + Information* const target = informationManager->getInformation(moveTo->getObject()); + if (!target || moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + done = false; + Vec2 point; + point.x = point.y = 0.0f; + bool arrived; + ok = static_cast(moveTo->update(point, done, arrived, 0.0f)) != 0; + if (!ok) + { + done = true; + return true; + } + if (done || arrived) + { + done = false; + return true; + } + const float ownX = info->getPosition().x; + const float ownZ = info->getPosition().z; + const Vec3& ownPosition = info->getPosition(); + const Vec3& targetPosition = target->getPosition(); + (void)(targetPosition.z - ownPosition.z); + Vec2 delta; + delta.x = point.x - ownX; + delta.y = point.y - ownZ; + const float distance = std::sqrt(delta.x * delta.x + delta.y * delta.y); + Mat4 transformation = object->getTransformation(); + const double timeIncrease = static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease(); + Vec2 forward2; + forward2.x = transformation.m[8]; + forward2.y = transformation.m[10]; + vehiclecontrol::normalizeVec2(forward2); + const float inverse = 1.0f / distance; + const float targetX = inverse * delta.x; + const float targetZ = inverse * delta.y; + float rightDot = targetX * forward2.y - targetZ * forward2.x; + const float forwardDot = targetX * forward2.x + targetZ * forward2.y; + if (rightDot < -1.0f) + rightDot = -1.0f; + else if (rightDot > 1.0f) + rightDot = 1.0f; + float angle = acosf(rightDot) - 1.570796371f; + if (forwardDot < 0.0f) + { + const float sign = angle > 0.0f ? 1.0f : (0.0f > angle ? -1.0f : 0.0f); + angle = sign * 3.141592741f - angle; + } + Vec3 position = object->getPosition(); + Vec3 up; + up.x = up.y = up.z = 0.0f; + const float speedFactor = forwardDot < 0.2f ? 0.2f : forwardDot; + // shipped defect: speed uses the still-zero terrain normal's y before the terrain query. + const float scaledSpeed = speedFactor * up.y * 0.6f; + const float speed = mobile->getMaxSpeed() * scaledSpeed; + Vec3 forward; + forward.x = delta.x / distance; + forward.y = 0.0f; + forward.z = delta.y / distance; + const float dt = static_cast(timeIncrease); + const float step = dt * speed; + const float radius = mobile->getTurnRadius(); + const float limitedRadius = radius < 1.0f ? 1.0f : radius; + const float angularStep = step / limitedRadius; + const float limit = angularStep < 0.003926991f ? 0.003926991f : angularStep; + if (limit < 6.283185482f && std::fabs(angle) > limit) + { + Vec3 current; + current.x = forward2.x; + current.y = 0.0f; + current.z = forward2.y; + const float sign = angle > 0.0f ? 1.0f : (0.0f > angle ? -1.0f : 0.0f); + rotate2d(current, forward, sign * limit); + } + float stepX = delta.x; + float stepZ = delta.y; + if (!(static_cast(speed) * timeIncrease > static_cast(distance))) + { + stepX = forward.x * dt * speed; + stepZ = forward.z * dt * speed; + } + position.x = stepX + position.x; + position.z = stepZ + position.z; + IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + unsigned char material; + const float height = terrain->getHeightAndNormal(position.x, position.z, up, material); + const float water = terrain->getWaterLevel(position.x, position.z); + const float lodHeight = mobile->getLodHeight(); + Vec3 previousForward; + previousForward.x = transformation.m[8]; + previousForward.y = transformation.m[9]; + previousForward.z = transformation.m[10]; + Vec3 right; + if (water - lodHeight > height) + { + position.y = mobile->getLodHeight() + water; + up.x = 0.0f; + up.y = 1.0f; + up.z = 0.0f; + right = infantry_detail::crossInline(up, previousForward); + vehiclecontrol::normalizeVec3(right); + } + else + { + LocalBoundingBox* const bounds = const_cast(physical->getLocalBoundingBox()); + position.y = 0.5f * bounds->getSize().y + height; + right = infantry_detail::crossInline(up, previousForward); + vehiclecontrol::normalizeVec3(right); + forward = infantry_detail::crossInline(right, up); + vehiclecontrol::normalizeVec3(forward); + } + transformation.m[0] = right.x; + transformation.m[1] = right.y; + transformation.m[2] = right.z; + transformation.m[4] = up.x; + transformation.m[5] = up.y; + transformation.m[6] = up.z; + transformation.m[8] = forward.x; + transformation.m[9] = forward.y; + transformation.m[10] = forward.z; + transformation.m[12] = position.x; + transformation.m[13] = position.y; + transformation.m[14] = position.z; + object->setTransformation(transformation, bot->getSide()); + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumBoat.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumBoat.h new file mode 100644 index 000000000..8b6b62e2a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumBoat.h @@ -0,0 +1,27 @@ +// Medium-LOD boat movement towards an object. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOOBJECTMEDIUMBOAT_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOOBJECTMEDIUMBOAT_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryMoveToObjectMediumBoat - statement type 9. +class EntryMoveToObjectMediumBoat : public BAPEntry +{ +public: + EntryMoveToObjectMediumBoat(); + virtual ~EntryMoveToObjectMediumBoat(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOOBJECTMEDIUMBOAT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumSoldier.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumSoldier.cpp new file mode 100644 index 000000000..c02caebf0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumSoldier.cpp @@ -0,0 +1,189 @@ +// EntryMoveToObjectMediumSoldier (attested TU `EntryMoveToObjectMediumSoldier.cpp`, split out of BAPEntries.cpp by S0). Recovered from +// libaidll.so (Linux 1.5.3153, ia-32): the medium-LOD soldier entry for BAPAMoveToObject (statement type 9). Package B; see docs/macos-ai-behaviour-plan.md. +// execute's flags follow the BotScript convention: `ok` (the step ran) and `done` (finished; with +// ok == false the statement failed). + +// static init: ELF 0x2BFAF0 (__tcf_0 0x2BFB50, _GLOBAL__I 0x2BFB80): 's Init object only. +#include + +#include "EntryMoveToObjectMediumSoldier.h" + +#include "InfanteryControl.h" +#include "../Main/CommonSingletonServer.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryMoveToObjectMediumSoldier::EntryMoveToObjectMediumSoldier() +{ +} + +EntryMoveToObjectMediumSoldier::~EntryMoveToObjectMediumSoldier() +{ +} + +int EntryMoveToObjectMediumSoldier::getTargetId() +{ + return 9; +} + +using infantry_detail::crossInline; +using infantry_detail::normaliseInline; + +// ELF 0x2BEFE0. Medium LOD for BAPAMoveToObject: as EntryMoveToMediumSoldier, but it finishes when +// the target object is gone, reports "not done" (instead of returning the action's done flag) when +// the action has arrived, stands still within 1 cm of the point, never jumps along the facing, and +// normalises the right vector of an upright soldier too. +bool EntryMoveToObjectMediumSoldier::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveTo* moveTo = static_cast(script); + Information* info = informationManager->getInformation(bot->getCurrentEquipment()); + if (info == 0) + { + done = true; + ok = false; + return true; + } + IAIObject* object = info->getAIObject(); + IAIObjectMobile* mobile = object->getMobile(); + IAIObjectPhysical* physical = info->getAIObject()->getPhysical(); + if (physical->hasPhysicsEnabled()) + physical->disablePhysics(object->getSide()); + infanteryResetControls(bot, bot->getInput(), true, false, false); + Information* target = informationManager->getInformation(static_cast(moveTo->getObject())); + if (target == 0 || moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + Vec2 goal; + goal.x = 0.0f; + done = false; + goal.y = goal.x; + bool arrived; + ok = moveTo->update(goal, done, arrived, 0.0f) != 0; + if (!ok) + { + done = true; + return true; + } + if (done || arrived) + { + done = false; + return true; + } + + Vec2 own; + own.x = info->getPosition().x; + own.y = info->getPosition().z; + // retail: the target's position is read here and only its z difference is formed, unused + const Vec3 ownPosition = info->getPosition(); + const Vec3& targetPosition = target->getPosition(); + (void)(targetPosition.z - ownPosition.z); + Vec2 delta; + delta.x = goal.x - own.x; + delta.y = goal.y - own.y; + const float distance = std::sqrt(delta.y * delta.y + delta.x * delta.x); + if (distance <= 0.01f) + { + done = false; + return true; + } + + const Mat4& current = object->getTransformation(); + Mat4 transformation; + for (int i = 0; i < 16; ++i) + transformation.m[i] = 0.0f; + for (int i = 0; i < 8; ++i) + transformation.m[i] = current.m[i]; + transformation.m[11] = current.m[11]; + transformation.m[15] = current.m[15]; + + const float dt = static_cast(static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease()); + bot->requestSoldierPose(SPStanding, false); + float speed = mobile->getMaxSpeed(); + const SoldierPose pose = info->getSoldierPose(); + if (pose == SPCrouching) + speed = speed * 0.5f; + else if (pose == SPLying) + speed = speed * 0.25f; + else if (pose != SPStanding) + speed = 0.0f; + + const Vec3& objectPosition = object->getPosition(); + Vec3 position; + position.y = objectPosition.y; + Vec3 forward; + forward.z = delta.y / distance; + forward.x = delta.x / distance; + forward.y = 0.0f; + float stepZ = delta.y; + float stepX = delta.x; + if (dt * speed <= distance) + { + stepZ = dt * forward.z * speed; + stepX = forward.x * dt * speed; + } + position.x = objectPosition.x + stepX; + position.z = objectPosition.z + stepZ; + + Vec3 up; + up.x = up.y = up.z = 0.0f; + const float currentHeight = info->getPosition().y; + float ground; + float slope; + static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->getHeightAndNormalForObject(object, position, ground, up, slope); + if (currentHeight <= ground || currentHeight - ground <= slope + slope) + position.y = mobile->getLodHeight() + ground; + else + position.y = currentHeight - slope; + + Vec3 right; + if (pose == SPLying) + { + position.y = position.y - 0.5f; + right = crossInline(up, forward); + normaliseInline(right); + forward = crossInline(right, up); + normaliseInline(forward); + } + else + { + up.x = 0.0f; + up.y = 1.0f; + up.z = 0.0f; + right = crossInline(up, forward); + normaliseInline(right); + } + transformation.m[0] = right.x; + transformation.m[1] = right.y; + transformation.m[2] = right.z; + transformation.m[4] = up.x; + transformation.m[5] = up.y; + transformation.m[6] = up.z; + transformation.m[8] = forward.x; + transformation.m[9] = forward.y; + transformation.m[10] = forward.z; + transformation.m[12] = position.x; + transformation.m[13] = position.y; + transformation.m[14] = position.z; + object->setTransformation(transformation, bot->getSide()); + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumSoldier.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumSoldier.h new file mode 100644 index 000000000..ff49fdb21 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumSoldier.h @@ -0,0 +1,28 @@ +// EntryMoveToObjectMediumSoldier: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOOBJECTMEDIUMSOLDIER_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOOBJECTMEDIUMSOLDIER_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryMoveToObjectMediumSoldier - statement type 9. +class EntryMoveToObjectMediumSoldier : public BAPEntry +{ +public: + EntryMoveToObjectMediumSoldier(); + virtual ~EntryMoveToObjectMediumSoldier(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOOBJECTMEDIUMSOLDIER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneAimAt.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneAimAt.cpp new file mode 100644 index 000000000..ebde5f942 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneAimAt.cpp @@ -0,0 +1,234 @@ +// EntryPlaneAimAt (split out of BAPEntries.cpp by S0, bodies unchanged). + +// static init: ELF 0x2C0B00 (__tcf_0 0x2C0B60, _GLOBAL__I 0x2C0B90): 's Init object only. +#include + +#include "EntryPlaneAimAt.h" + +#include "PlaneControl.h" +#include "VehicleControlInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAAimAtObject3d.h" +#include "../AIBotActionPlan/BAPCondition.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2BFBD0 (C1; C2 0x2BFBB0). +EntryPlaneAimAt::EntryPlaneAimAt() +{ +} + +// ELF 0x2BFC10 (D1; D2 0x2BFBF0, D0 0x2BFC30). +EntryPlaneAimAt::~EntryPlaneAimAt() +{ +} + +// ELF 0x2C0BB0. +int EntryPlaneAimAt::getTargetId() +{ + return 6; +} + +// ELF 0x2BFC70. +bool EntryPlaneAimAt::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAAimAt3d* const aim = static_cast(script); + ok = true; + done = false; + if (aim->m_condition->evaluate(bot)) + { + done = true; + return true; + } + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + aim->m_floats1AC[0] = 3.1415927f; + return true; + } + IPIArmament* const armament = info->getArmament(); + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation( + armament->getWeapon(armament->getActiveWeapon())); + IPIMobile* const mobile = info->getMobile(); + if (aim->getAimAtType() != 1) + { + done = true; + ok = false; + aim->m_floats1AC[0] = 3.1415927f; + return true; + } + Information* const target = informationManager->getInformation(static_cast(aim)->m_target); + if (!target) + { + done = true; + ok = false; + aim->m_floats1AC[0] = 3.1415927f; + return true; + } + Vec3 direction = {0.0f, 0.0f, 0.0f}; + Vec3 firingDirection = {0.0f, 0.0f, 0.0f}; + const Mat4& origin = weapon->getProjectileOrigin(); + const Mat4& targetTransform = target->getTransformation(); + float throttle = 1.0f; + float distance; + bool useForward = false; + if (target->isOfType(ITAir)) + { + const bool indirect = weapon->getIndirect(); + const float gravity = weapon->getGravityModifier(); + const float speed = weapon->getExitVelocity(); + const float drag = weapon->getDrag(); + bool solved = aim->getAimVec(origin, mobile->getSpeed(), direction, 0.5f, drag, speed, gravity, indirect); + if (solved) + firingDirection = direction; + else + { + if (!aim->getVectorToTarget(info->getPosition(), direction)) + { + ok = false; + done = true; + return true; + } + const float length = std::sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z); + if (length > 1.0f) + { + solved = true; + const float inverse = 1.0f / length; + direction.x *= inverse; + direction.y *= inverse; + direction.z *= inverse; + } + } + distance = std::sqrt(direction.x * direction.x + direction.z * direction.z); + useForward = !solved; + } + else + { + const bool indirect = weapon->getIndirect(); + const float gravity = weapon->getGravityModifier(); + const float speed = weapon->getExitVelocity(); + const float drag = weapon->getDrag(); + const bool solved = aim->getAimVec(origin, mobile->getSpeed(), direction, 0.75f, drag, speed, gravity, false); + throttle = 0.5f; + if (solved) + { + firingDirection = direction; + if (indirect) + { + const float x = origin.m[12] - targetTransform.m[12]; + const float y = origin.m[13] - targetTransform.m[13]; + const float z = origin.m[14] - targetTransform.m[14]; + distance = std::sqrt(x * x + y * y + z * z); + if (distance < 60.0f || distance > 300.0f) + { + direction.y = 0.0f; + if (std::sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z) > 1e-05f) + { + const float inverse = 1.0f / std::sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z); + direction.x *= inverse; + direction.y *= inverse; + direction.z *= inverse; + } + } + } + else + distance = std::sqrt(direction.x * direction.x + direction.z * direction.z); + } + else + { + if (!aim->getVectorToTarget(info->getPosition(), direction)) + { + ok = false; + done = true; + return true; + } + direction.y = 20.0f + direction.y; + distance = std::sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z); + if (distance > 1.0f) + { + const float inverse = 1.0f / distance; + direction.x *= inverse; + direction.y *= inverse; + direction.z *= inverse; + } + else + useForward = true; + } + } + if (useForward || -0.7f > direction.y) + { + direction = info->getFaceing(); + direction.y = 0.0f; + distance = 1.0f; + vehiclecontrol::normalizeVec3(direction); + } + const float dt = static_cast(static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease()); + const Vec3& speed = mobile->getSpeed(); + const float inverse = 1.0f / dt; + const Vec3 acceleration = {(speed.x - aim->m_vecA8.x) * inverse, + (speed.y - aim->m_vecA8.y) * inverse, + (speed.z - aim->m_vecA8.z) * inverse}; + (void)acceleration; + aim->m_vecA8 = speed; + Mat4 inverseOrigin = {{1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f}}; + inverseOrigin.setInverse(origin); + const Vec3 localDirection = { + direction.x * inverseOrigin.m[0] + direction.y * inverseOrigin.m[4] + direction.z * inverseOrigin.m[8], + direction.x * inverseOrigin.m[1] + direction.y * inverseOrigin.m[5] + direction.z * inverseOrigin.m[9], + direction.x * inverseOrigin.m[2] + direction.y * inverseOrigin.m[6] + direction.z * inverseOrigin.m[10]}; + const Mat4& transform = info->getTransformation(); + const Vec3 steeringDirection = { + localDirection.x * transform.m[0] + localDirection.y * transform.m[4] + localDirection.z * transform.m[8], + localDirection.x * transform.m[1] + localDirection.y * transform.m[5] + localDirection.z * transform.m[9], + localDirection.x * transform.m[2] + localDirection.y * transform.m[6] + localDirection.z * transform.m[10]}; + const auto clamp = [](float value) { + return -1.0f > value ? -1.0f : (value > 1.0f ? 1.0f : value); + }; + if (aim->isAimVecValid()) + { + const Mat4& weaponUp = weapon->getAbsoluteTransformation(); + float dot = firingDirection.x * weaponUp.m[4] + firingDirection.y * weaponUp.m[5] + firingDirection.z * weaponUp.m[6]; + const float pitch = std::acos(clamp(clamp(dot))) - 1.5707964f; + const Mat4& weaponRight = weapon->getAbsoluteTransformation(); + dot = firingDirection.x * weaponRight.m[0] + firingDirection.y * weaponRight.m[1] + firingDirection.z * weaponRight.m[2]; + float yaw = std::acos(clamp(clamp(dot))) - 1.5707964f; + const Mat4& weaponForward = weapon->getAbsoluteTransformation(); + dot = firingDirection.x * weaponForward.m[8] + firingDirection.y * weaponForward.m[9] + firingDirection.z * weaponForward.m[10]; + if (dot < 0.0f) + yaw = (yaw < 0.0f ? -3.1415927f : 3.1415927f) - yaw; + aim->m_floats1AC[1] = pitch; + aim->m_floats1AC[0] = yaw; + } + else + { + aim->m_floats1AC[1] = 3.1415927f; + aim->m_floats1AC[0] = 3.1415927f; + } + aim->m_vec24 = info->getFaceing(); + const Mat4& right = info->getTransformation(); + aim->m_vec30 = {right.m[0], right.m[1], right.m[2]}; + const Mat4& up = info->getTransformation(); + aim->m_vec3C = {up.m[4], up.m[5], up.m[6]}; + aim->m_floats1AC[3] = info->getPosition().y; + ok = PlaneControl::aimAtDirection(bot, info, steeringDirection, distance, throttle, aim->m_float1A4, + aim->m_vec24, aim->m_vec30, aim->m_vec3C, bot->getInput()); + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneAimAt.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneAimAt.h new file mode 100644 index 000000000..7fd11a476 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneAimAt.h @@ -0,0 +1,27 @@ +// EntryPlaneAimAt: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANEAIMAT_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANEAIMAT_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryPlaneAimAt - statement type 6. +class EntryPlaneAimAt : public BAPEntry +{ +public: + EntryPlaneAimAt(); + virtual ~EntryPlaneAimAt(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANEAIMAT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveTo.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveTo.cpp new file mode 100644 index 000000000..6d1beac66 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveTo.cpp @@ -0,0 +1,73 @@ +// EntryPlaneMoveTo (split out of BAPEntries.cpp by S0, bodies unchanged). + +// static init: ELF 0x2C0E80 (__tcf_0 0x2C0EE0, _GLOBAL__I 0x2C0F10): 's Init object only. +#include + +#include "EntryPlaneMoveTo.h" + +#include "PlaneControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo3d.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../../../../Math/Mat4.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2C0BE0 (C1; C2 0x2C0BC0). +EntryPlaneMoveTo::EntryPlaneMoveTo() +{ +} + +// ELF 0x2C0C20 (D1; D2 0x2C0C00, D0 0x2C0C40). +EntryPlaneMoveTo::~EntryPlaneMoveTo() +{ +} + +// ELF 0x2C0F30. +int EntryPlaneMoveTo::getTargetId() +{ + return 7; +} + +// ELF 0x2C0C80. +bool EntryPlaneMoveTo::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveTo3d* const moveTo = static_cast(script); + Mat4 unused = {{1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f}}; + (void)unused; + Vec3 point = {0.0f, 0.0f, 0.0f}; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + return true; + } + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + // shipped defect: the completed statement still drives the plane below. + } + else + done = false; + point = *moveTo->getFirstPoint(); + ok = PlaneControl::towardsPoint(bot, info, point, 1.0f, moveTo->m_forward, + moveTo->m_right, moveTo->m_up, moveTo->m_distance, bot->getInput()); + const Mat4& transform = info->getTransformation(); + moveTo->m_forward = {transform.m[8], transform.m[9], transform.m[10]}; + moveTo->m_up = {transform.m[4], transform.m[5], transform.m[6]}; + moveTo->m_right = {transform.m[0], transform.m[1], transform.m[2]}; + moveTo->m_int4C = transform.m[13]; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveTo.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveTo.h new file mode 100644 index 000000000..60807d35d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveTo.h @@ -0,0 +1,27 @@ +// EntryPlaneMoveTo: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANEMOVETO_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANEMOVETO_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryPlaneMoveTo - statement type 7. +class EntryPlaneMoveTo : public BAPEntry +{ +public: + EntryPlaneMoveTo(); + virtual ~EntryPlaneMoveTo(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANEMOVETO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToDirection.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToDirection.cpp new file mode 100644 index 000000000..24bebd6e5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToDirection.cpp @@ -0,0 +1,226 @@ +// EntryPlaneMoveToDirection (split out of BAPEntries.cpp by S0, bodies unchanged). + +// static init: ELF 0x2C2950 (__tcf_0 0x2C29B0, _GLOBAL__I 0x2C29E0): 's Init object only. +#include + +#include "EntryPlaneMoveToDirection.h" + +#include "ControlFunctions.h" +#include "VehicleControlInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo3dDirection.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../../../../Core/Debug.h" +#include "../../../../IO/Input/PlayerInput.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2C0F60 (C1; C2 0x2C0F40). +EntryPlaneMoveToDirection::EntryPlaneMoveToDirection() +{ +} + +// ELF 0x2C0FA0 (D1; D2 0x2C0F80, D0 0x2C0FC0). +EntryPlaneMoveToDirection::~EntryPlaneMoveToDirection() +{ +} + +// ELF 0x2C2A00. +int EntryPlaneMoveToDirection::getTargetId() +{ + return 8; +} + +// ELF 0x2C1000. +bool EntryPlaneMoveToDirection::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveTo3dDirection* const moveTo = static_cast(script); + Mat4 transform = {{1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f}}; + Mat4 transpose = transform; + io::PlayerInput* const input = bot->getInput(); + float yawInput = (input->mappingFlags & 1ULL) ? input->inputs[0] : 0.0f; + float pitchInput = (input->mappingFlags & 2ULL) ? input->inputs[1] : 0.0f; + float rollInput = (input->mappingFlags & 4ULL) ? input->inputs[2] : 0.0f; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + return true; + } + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + // shipped defect: the completed statement continues through the controls. + } + else + done = false; + transform = info->getTransformation(); + const Vec3 right = {transform.m[0], transform.m[1], transform.m[2]}; + const Vec3 up = {transform.m[4], transform.m[5], transform.m[6]}; + const Vec3 forward = {transform.m[8], transform.m[9], transform.m[10]}; + transpose.setTranspose(transform); + const Vec3 position = info->getPosition(); + info->getMobile()->getSpeedMagnitude(); + Vec3 point = moveTo->m_target; + const Vec3& speed = info->getMobile()->getSpeed(); + const Vec3 lookAhead = {speed.x * 10.0f, speed.y * 10.0f, speed.z * 10.0f}; + const float altitude = info->getAltitude(lookAhead); + moveTo->m_currentAltitude = altitude; + const float heightError = moveTo->m_altitude - altitude; + const float desiredHeight = heightError + position.y; + point.y = desiredHeight > point.y ? desiredHeight : point.y; + Vec2 position2, point2, forward2, targetDirection2, normal, targetNormal; + vec3ToVec2XZ(position, position2); + vec3ToVec2XZ(point, point2); + vec3ToVec2XZ(forward, forward2); + vec3ToVec2XZ(moveTo->m_direction, targetDirection2); + getNormal(forward2, normal); + vehiclecontrol::normalizeVec2(normal); + getNormal(targetDirection2, targetNormal); + vehiclecontrol::normalizeVec2(targetNormal); + const float radius = 80.0f; + const Vec2 targetCentre = {radius * targetNormal.x + point2.x, targetNormal.y * radius + point2.y}; + const Vec2 centreDifference = {targetCentre.x - (normal.x * radius + position2.x), + targetCentre.y - (normal.y * radius + position2.y)}; + const float centreDistance = std::sqrt(centreDifference.x * centreDifference.x + centreDifference.y * centreDifference.y); + const float pi = 3.1415927f; + const float halfPi = 1.5707964f; + const float twoPi = 6.2831855f; + // [INFERRED] inline comparison shapes. The cosine clamp maps unordered input to -1. + const auto clampUnit = [](float value) { + return -1.0f > value ? -1.0f : (value > 1.0f ? 1.0f : value); + }; + const auto clampCos = [](float value) { + const float upper = value > 1.0f ? 1.0f : value; + return upper > -1.0f ? upper : -1.0f; + }; + Vec3 direction; + float yawTarget; + // shipped defect: the height slope uses world-position magnitude, not target distance. + const auto perpendicular = [&]() { + return Vec3{normal.x, (point.y - position.y) / + std::sqrt(position.x * position.x + position.y * position.y + position.z * position.z), normal.y}; + }; + if (radius * 0.075f > centreDistance) + { + direction = perpendicular(); + moveTo->m_state = 2; + yawTarget = halfPi; + Debug(DebugTypeError, "AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToDirection.cpp", 210, "") + << "We don't think that we are using this code..., check yaw angle."; + } + else + { + float theta = std::acos(clampUnit(clampUnit(std::fabs(centreDifference.y) / centreDistance))); + if (centreDifference.x < 0.0f) + theta = twoPi - theta; + float normalTheta = std::acos(clampUnit(clampUnit(normal.y))); + if (normal.x < 0.0f) + normalTheta = twoPi - normalTheta; + float difference = theta - normalTheta; + if (difference < 0.0f) + difference = -difference; + if (difference > pi) + difference = twoPi - difference; + else if (difference < 0.0f) + difference += twoPi; + if (moveTo->m_state == 1 || 0.18325958f > difference) + { + const float sine = std::sin(theta); + const Vec3 turnPoint = {targetCentre.x - sine * radius, point.y, + targetCentre.y - radius * std::cos(theta)}; + direction = {turnPoint.x - position.x, turnPoint.y - position.y, turnPoint.z - position.z}; + Vec2 direction2; + vec3ToVec2XZ(direction, direction2); + vehiclecontrol::normalizeVec2(direction2); + const float dot = normal.x * direction2.x + direction2.y * normal.y; + yawTarget = std::acos(clampCos(dot)) - halfPi; + vehiclecontrol::normalizeVec3(direction); + moveTo->m_state = 1; + } + else + { + direction = perpendicular(); + yawTarget = halfPi; + } + } + vehiclecontrol::normalizeVec3(direction); + float rollTarget = -(std::acos(clampCos(right.y)) - halfPi); + const float yawChange = std::acos(clampCos(right.x * moveTo->m_forward.x + right.y * moveTo->m_forward.y + right.z * moveTo->m_forward.z)) - halfPi; + const float rollChange = rollTarget + (std::acos(clampCos(right.y)) - halfPi); + const float pitchChange = std::acos(clampCos(up.x * moveTo->m_forward.x + up.y * moveTo->m_forward.y + up.z * moveTo->m_forward.z)) - halfPi; + const Vec3 localUp = {transpose.m[0] * 0.0f + transpose.m[4] + transpose.m[8] * 0.0f, + transpose.m[1] * 0.0f + transpose.m[5] + transpose.m[9] * 0.0f, + transpose.m[2] * 0.0f + transpose.m[6] + transpose.m[10] * 0.0f}; + const float currentPitch = std::asin(clampUnit(localUp.z)); + float pitchTarget; + const auto dot = [](const Vec3& a, const Vec3& b) { + return a.x * b.x + a.y * b.y + a.z * b.z; + }; + if (heightError > moveTo->m_altitude * 0.1f) + { + pitchTarget = -(0.43633232f - currentPitch); + yawTarget = 0.0f; + pitchTarget /= 1.0001f - std::sin(rollTarget); + } + else if (!(0.08726646f > std::fabs(yawTarget))) + { + if (!(0.21816616f > std::fabs(yawTarget))) + { + const float angle = std::atan(dot(direction, right)); + yawTarget = 0.0f; + pitchTarget = -halfPi; + const float upDot = dot(up, direction); + const float absoluteUpDot = upDot < 0.0f ? -upDot : upDot; + rollTarget = (angle / absoluteUpDot) * 0.9f + 0.1f * rollTarget; + } + else + { + const float angle = std::acos(clampCos(dot(direction, up))) - halfPi; + pitchTarget = -(0.43633232f - currentPitch) / (1.0001f - std::sin(rollTarget)); + pitchTarget = pitchTarget > angle ? pitchTarget : angle; + const float rightAngle = std::acos(clampCos(dot(direction, right))) - halfPi; + rollTarget = rightAngle * -0.1f + rollTarget * 0.9f; + } + } + else + { + const float absoluteZ = direction.z < 0.0f ? -direction.z : direction.z; + const float targetPitch = std::atan(direction.y / absoluteZ); + const float forwardAbsoluteZ = forward.z < 0.0f ? -forward.z : forward.z; + const float facingPitch = std::atan(forward.y / forwardAbsoluteZ); + const float pitchDifference = targetPitch - facingPitch; + const float pitchLimit = (1.0f - std::cos(std::fabs(rollTarget))) * 1.2f * halfPi + (0.43633232f - currentPitch); + pitchTarget = -(pitchLimit > pitchDifference ? pitchDifference : pitchLimit); + const float rollSign = rollTarget > 0.0f ? 1.0f : (rollTarget < 0.0f ? -1.0f : 0.0f); + rollTarget = rollSign * rollTarget * rollTarget; + const float yawSign = yawTarget > 0.0f ? 1.0f : (yawTarget < 0.0f ? -1.0f : 0.0f); + yawTarget = yawSign * yawTarget * yawTarget; + } + updateAngle(yawTarget, yawChange, yawInput, 1.0f, 1.0f, 1.5f); + updateAngle(pitchTarget, pitchChange, pitchInput, -1.0f, 1.0f, 1.5f); + updateAngle(rollTarget, rollChange, rollInput, -0.5f, 1.0f, 1.5f); + io::PlayerInput* output = bot->getInput(); + if (output->mappingFlags & 1ULL) + output->inputs[0] = yawInput; + bot->getInput()->setInput(static_cast(1), pitchInput); + bot->getInput()->setInput(static_cast(2), rollInput); + bot->getInput()->setInput(static_cast(3), 1.0f); + ok = true; + moveTo->m_forward = forward; + moveTo->m_up = up; + moveTo->m_right = right; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToDirection.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToDirection.h new file mode 100644 index 000000000..3d56ed559 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToDirection.h @@ -0,0 +1,27 @@ +// EntryPlaneMoveToDirection: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANEMOVETODIRECTION_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANEMOVETODIRECTION_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryPlaneMoveToDirection - statement type 8. +class EntryPlaneMoveToDirection : public BAPEntry +{ +public: + EntryPlaneMoveToDirection(); + virtual ~EntryPlaneMoveToDirection(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANEMOVETODIRECTION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToObject.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToObject.cpp new file mode 100644 index 000000000..4db944e03 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToObject.cpp @@ -0,0 +1,112 @@ +// EntryPlaneMoveToObject (split out of BAPEntries.cpp by S0, bodies unchanged). + +// static init: ELF 0x2C2F40 (__tcf_0 0x2C2FA0, _GLOBAL__I 0x2C2FD0): 's Init object only. +#include + +#include "EntryPlaneMoveToObject.h" + +#include "PlaneControl.h" +#include "ControlFunctions.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo3dObject.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../../../../IO/Input/PlayerInput.h" +#include "../../../../Math/Mat4.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2C2A30 (C1; C2 0x2C2A10). +EntryPlaneMoveToObject::EntryPlaneMoveToObject() +{ +} + +// ELF 0x2C2A70 (D1; D2 0x2C2A50, D0 0x2C2A90). +EntryPlaneMoveToObject::~EntryPlaneMoveToObject() +{ +} + +// ELF 0x2C2FF0. +int EntryPlaneMoveToObject::getTargetId() +{ + return 9; +} + +// ELF 0x2C2AD0. +bool EntryPlaneMoveToObject::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveTo3dObject* const moveTo = static_cast(script); + Mat4 unused = {{1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f}}; + (void)unused; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + // shipped defect: current equipment is dereferenced before any validity check. + const Vec3 position = info->getPosition(); + (void)position; + Information* const target = informationManager->getInformation(moveTo->m_object); + if (!target) + { + done = true; + ok = false; + return true; + } + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + // shipped defect: the completed statement still drives the plane below. + } + else + done = false; + const Mat4& transform = info->getTransformation(); + const float speed = info->getMobile()->getSpeedMagnitude(); + float throttle; + if (target->isOfType(ITAir)) + { + io::PlayerInput* const input = bot->getInput(); + throttle = ((input->mappingFlags >> 3) & 1ULL) ? input->inputs[3] : 0.0f; + const Vec3& targetPosition = target->getPosition(); + const Vec3& currentPosition = info->getPosition(); + const float x = targetPosition.x - currentPosition.x; + const float y = targetPosition.y - currentPosition.y; + const float z = targetPosition.z - currentPosition.z; + const float distanceSquared = x * x + y * y + z * z; + IPIMobile* const targetMobile = target->getMobile(); + const float range = moveTo->m_float18; + float targetSpeed; + if (targetMobile) + targetSpeed = targetMobile->getSpeedMagnitude(); + else + targetSpeed = moveTo->m_maxArriveSpeed; + if (range * range >= distanceSquared) + updateLinear(targetSpeed, speed, moveTo->m_int40[0], throttle, -1.0f, 1.0f, 1.0f); + else if ((range + range) * (range + range) >= distanceSquared) + { + // shipped defect: the transition uses squared distance divided by range. + updateLinear((distanceSquared * targetSpeed) / range, speed, moveTo->m_int40[0], throttle, -1.0f, 1.0f, 1.0f); + } + else + throttle = 1.0f; + moveTo->m_int40[0] = speed; + } + else + throttle = 1.0f; + const float distance = moveTo->m_distance; + const Vec3 point = *moveTo->getFirstPoint(); + ok = PlaneControl::towardsPoint(bot, info, point, throttle, moveTo->m_right, + moveTo->m_forward, moveTo->m_up, distance, bot->getInput()); + moveTo->m_right = {transform.m[8], transform.m[9], transform.m[10]}; + moveTo->m_up = {transform.m[4], transform.m[5], transform.m[6]}; + moveTo->m_forward = {transform.m[0], transform.m[1], transform.m[2]}; + moveTo->m_int84 = transform.m[13]; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToObject.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToObject.h new file mode 100644 index 000000000..064729e97 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToObject.h @@ -0,0 +1,27 @@ +// EntryPlaneMoveToObject: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANEMOVETOOBJECT_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANEMOVETOOBJECT_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryPlaneMoveToObject - statement type 9. +class EntryPlaneMoveToObject : public BAPEntry +{ +public: + EntryPlaneMoveToObject(); + virtual ~EntryPlaneMoveToObject(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANEMOVETOOBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneResetControls.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneResetControls.cpp new file mode 100644 index 000000000..06e63dc65 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneResetControls.cpp @@ -0,0 +1,59 @@ +// EntryPlaneResetControls (split out of BAPEntries.cpp by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +// static init: ELF 0x2C3330 (__tcf_0 0x2C3390, _GLOBAL__I 0x2C33C0): 's Init object only. +#include + +#include "EntryPlaneResetControls.h" + +#include "PlaneControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../Main/AIDllFrontier.h" +#include "../../../../IO/Input/PlayerInput.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryPlaneResetControls::EntryPlaneResetControls() +{ +} + +EntryPlaneResetControls::~EntryPlaneResetControls() +{ +} + +int EntryPlaneResetControls::getTargetId() +{ + return 14; +} + +// ELF 0x2C30C0 (Ghidra). The bot's current equipment is looked up first (not null-tested). A +// single-input reset releases that one input; the group form resets through +// PlaneControl::resetControls with that information, ignores its answer, and sets `done` then `ok`. +bool EntryPlaneResetControls::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + BAPAResetControls* const reset = static_cast(script); + if (reset->hasSingleInput()) + { + io::PlayerInput* const input = bot->getInput(); + input->setInput(static_cast(reset->getInput()), 0.0f); + ok = true; + done = true; + return true; + } + PlaneControl::resetControls(bot, equipment, bot->getInput(), reset->m_resetMove, reset->m_resetLook, + reset->m_resetTrigger); + done = true; + ok = true; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneResetControls.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneResetControls.h new file mode 100644 index 000000000..c7d45c572 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneResetControls.h @@ -0,0 +1,28 @@ +// EntryPlaneResetControls: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANERESETCONTROLS_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANERESETCONTROLS_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryPlaneResetControls - statement type 14. +class EntryPlaneResetControls : public BAPEntry +{ +public: + EntryPlaneResetControls(); + virtual ~EntryPlaneResetControls(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANERESETCONTROLS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneRoll.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneRoll.cpp new file mode 100644 index 000000000..02fa904da --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneRoll.cpp @@ -0,0 +1,87 @@ +// Plane roll entry. Attested TU: EntryPlaneRoll.cpp. + +// static init: ELF 0x2C38B0 (__tcf_0 0x2C3910, _GLOBAL__I 0x2C3940): 's Init object only. +#include + +#include "EntryPlaneRoll.h" + +#include "PlaneControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPARoll3d.h" +#include "../AIBotActionPlan/BAPCondition.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../../../../Math/Mat4.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2C3410 (C1; C2 0x2C33F0). +EntryPlaneRoll::EntryPlaneRoll() +{ +} + +// ELF 0x2C3450 (D1; D2 0x2C3430, D0 0x2C3470). +EntryPlaneRoll::~EntryPlaneRoll() +{ +} + +// ELF 0x2C34B0 +bool EntryPlaneRoll::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPARoll3d* const roll = static_cast(script); + Mat4 unused = {{1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f}}; + (void)unused; + if (roll->getBreakCondition()->evaluate(bot)) + { + done = true; + ok = true; + // shipped defect: satisfying the break condition does not stop the controls. + } + else + done = false; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + return true; + } + const Mat4& transform = info->getTransformation(); + const Vec3 position = info->getPosition(); + const Vec3 speed = info->getMobile()->getSpeed(); + // shipped defect: +0x2C, used as the minimum altitude, is not initialized by the constructor. + const float minimumAltitude = roll->m_float2C; + const Vec3 lookAhead = {speed.x * 10.0f, speed.y * 10.0f, speed.z * 10.0f}; + const float heightDifference = minimumAltitude - info->getAltitude(lookAhead); + IPIControlInfo* const controls = info->getControlInfo(); + bool wrapped = false; + // The second argument is the local [ebp-0xA4] (zeroed 0x2C354E, read 0x2C37BB, never written); + // PlaneControl::roll does not read it. + ok = PlaneControl::roll(roll->m_roll, 0.0f, bot->getInput(), transform, roll->m_previousY, + heightDifference > 0.0f, roll->m_flatFacing, roll->m_vector78, roll->m_vector6C, + roll->m_forward, roll->m_right, roll->m_up, controls, 1.0f, + roll->m_direction == 1, wrapped) != 0; + if (wrapped) + roll->m_roll += roll->m_direction == 1 ? -6.2831855f : 6.2831855f; + roll->m_forward = {transform.m[8], transform.m[9], transform.m[10]}; + roll->m_up = {transform.m[4], transform.m[5], transform.m[6]}; + roll->m_right = {transform.m[0], transform.m[1], transform.m[2]}; + roll->m_previousY = position.y; + return true; +} + +// ELF 0x2C3960 +int EntryPlaneRoll::getTargetId() +{ + return 25; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneRoll.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneRoll.h new file mode 100644 index 000000000..056eba72c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneRoll.h @@ -0,0 +1,31 @@ +// Plane roll action-plan entry. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANEROLL_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANEROLL_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BD7A8 (4 words), package H-deferred. +class EntryPlaneRoll : public BAPEntry +{ +public: + EntryPlaneRoll(); // 0x2C3410 + virtual ~EntryPlaneRoll(); // 0x2C3450 + + virtual bool execute(BotScript*, Bot*, bool&, bool&); // 0x2C34B0, slot +0x08; from the base declaration + virtual int getTargetId(); // 0x2C3960, slot +0x0C; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANEROLL_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntrySense.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntrySense.cpp new file mode 100644 index 000000000..18efb0463 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntrySense.cpp @@ -0,0 +1,61 @@ +// EntrySense (attested TU `EntrySense.cpp`, split out of BAPEntries.cpp by S0). Recovered from +// libaidll.so (Linux 1.5.3153, ia-32): the entry for BAPASense (statement type 20). Package B; see docs/macos-ai-behaviour-plan.md. +// execute's flags follow the BotScript convention: `ok` (the step ran) and `done` (finished; with +// ok == false the statement failed). + +// static init: ELF 0x2C3AE0 (__tcf_0 0x2C3B40, _GLOBAL__I 0x2C3B70): 's Init object only. +#include + +#include "EntrySense.h" + +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPASense.h" +#include "../AIBotActionPlan/BAPCondition.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2C3990 (C1; C2 0x2C3970) +EntrySense::EntrySense() +{ +} + +// ELF 0x2C39D0 (D1; D2 0x2C39B0, D0 0x2C39F0) +EntrySense::~EntrySense() +{ +} + +// ELF 0x2C3B90 +int EntrySense::getTargetId() +{ + return 20; +} + +// ELF 0x2C3A30. The condition at +0x18 ends the statement at once. Otherwise the statement keeps +// running until the condition at +0x14 holds; then the bot's inverse attention is reset to 0 and it +// finishes. +bool EntrySense::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPASense* sense = static_cast(script); + if (sense->m_secondCondition->evaluate(bot)) + { + ok = true; + done = true; + return true; + } + if (!sense->m_firstCondition->evaluate(bot)) + { + ok = true; + done = false; + return true; + } + static_cast(bot)->setInvAttention(0.0f); + ok = true; + done = true; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntrySense.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntrySense.h new file mode 100644 index 000000000..660e18957 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntrySense.h @@ -0,0 +1,27 @@ +// Runs the sensing statement until either owned condition completes it. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYSENSE_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYSENSE_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntrySense - statement type 20. +class EntrySense : public BAPEntry +{ +public: + EntrySense(); + virtual ~EntrySense(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYSENSE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntrySoldierPose.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntrySoldierPose.cpp new file mode 100644 index 000000000..db6b63551 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntrySoldierPose.cpp @@ -0,0 +1,65 @@ +// EntrySoldierPose (attested TU `EntrySoldierPose.cpp`, split out of BAPEntries.cpp by S0). Recovered from +// libaidll.so (Linux 1.5.3153, ia-32): the soldier entry for BAPASoldierPose (statement type 26). Package B; see docs/macos-ai-behaviour-plan.md. +// execute's flags follow the BotScript convention: `ok` (the step ran) and `done` (finished; with +// ok == false the statement failed). + +// static init: ELF 0x2C3E50 (__tcf_0 0x2C3EB0, _GLOBAL__I 0x2C3EE0): 's Init object only. +#include + +#include "EntrySoldierPose.h" + +#include "InfanteryControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPASoldierPose.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntrySoldierPose::EntrySoldierPose() +{ +} + +EntrySoldierPose::~EntrySoldierPose() +{ +} + +int EntrySoldierPose::getTargetId() +{ + return 26; +} + +// ELF 0x2C3C60. Wanted pose: the statement's normal pose, or standing while the bot presses +// throttle, yaw or sprint. Done when the soldier is in it; otherwise the pose is requested (not while +// swimming). Without the bot's own information the image returns false and leaves the flags alone. +bool EntrySoldierPose::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPASoldierPose* pose = static_cast(script); + Information* info = informationManager->getInformation(bot->getCurrentEquipment()); + if (info == 0) + return false; + SoldierPose wanted = static_cast(static_cast(pose)->getNormalPose()); + const io::PlayerInput* input = bot->getInput(); + if (infantry_detail::inputValue(input, io::PIThrottle) != 0.0f + || infantry_detail::inputValue(input, io::PIYaw) != 0.0f + || infantry_detail::inputValue(input, io::PISprint) != 0.0f) + wanted = SPStanding; + if (info->getSoldierPose() == wanted) + { + ok = true; + done = true; + return true; + } + const SoldierPose current = info->getSoldierPose(); + if (current != SPSwimming && current != wanted) + bot->requestSoldierPose(wanted, pose->getFlag()); + ok = true; + done = false; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntrySoldierPose.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntrySoldierPose.h new file mode 100644 index 000000000..bee00d118 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntrySoldierPose.h @@ -0,0 +1,28 @@ +// EntrySoldierPose: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYSOLDIERPOSE_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYSOLDIERPOSE_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntrySoldierPose - statement type 26. +class EntrySoldierPose : public BAPEntry +{ +public: + EntrySoldierPose(); + virtual ~EntrySoldierPose(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYSOLDIERPOSE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveTo.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveTo.cpp new file mode 100644 index 000000000..68b8e64cf --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveTo.cpp @@ -0,0 +1,175 @@ +// EntryTankMoveTo (attested TU `EntryTankMoveTo.cpp`, split out of BAPEntries.cpp by S0). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32): the interpreter entry that drives a tank +// along a BAPAMoveTo. execute's flags follow the BotScript convention: `ok` (the step ran) and +// `done` (the statement is finished; with ok == false it failed). +// +// static init: ELF 0x2C4680 (__tcf_0 0x2C46E0, _GLOBAL__I 0x2C4710): the guard object only. + +#include "EntryTankMoveTo.h" + +#include "TankControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +EntryTankMoveTo::EntryTankMoveTo() +{ +} + +EntryTankMoveTo::~EntryTankMoveTo() +{ +} + +int EntryTankMoveTo::getTargetId() +{ + return 7; +} + +// ELF 0x2C3FC0 (listing; Ghidra cross-check). The car entry's shape with the tank's tuning: no +// initial flag stores; the equipment's mobile/control/physical members are read before the +// equipment is null-tested (as shipped); physics is enabled also when already on while the static +// alwaysEnable is set; turn factor 1 - min(1, 2.5 * max(0, |largest angle diff| - 0.35)) * 0.7 +// above 3 m/s; the approach factor uses the SQUARED distance minus the smallest radius and 0.5 +// against fallOffDistanceSqr (196), at least 0.35; and TankControl gets the normalised direction. +bool EntryTankMoveTo::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + static bool alwaysEnable; // .bss 0x4CE5B1 (false) + static float fallOffDistanceSqr = 196.0f; // .data 0x4BD8C4 + + BAPAMoveTo* const moveTo = static_cast(script); + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* const mobile = info->getMobile(); // read before the null test (0x2C401E) + IPIControlInfo* const controlInfo = info->getControlInfo(); + IPIPhysical* const physical = info->getPhysical(); + if (!info || !mobile || !controlInfo || !physical) + { + done = true; + ok = false; + return true; + } + IAIObjectPhysical* const object = info->getAIObject()->getPhysical(); + if (alwaysEnable || !object->hasPhysicsEnabled()) + object->enablePhysics(info->getSide()); + + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + const double last = static_cast(bot)->getLastCheckMoveToFinishedTime(); // Bot +0x274 + done = false; + if (now - last > 1.0) + { + static_cast(bot)->setLastCheckMoveToFinishedTime(now); // +0x270 + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + } + + Vec2 target; + target.x = target.y = 0.0f; + bool arrived; + ok = moveTo->update(target, done, arrived, 0.0f) != 0; + if (!ok) + { + const Vec3 facing = info->getFaceing(); + const Vec3& speed = mobile->getSpeed(); + ok = TankControl::resetControls(bot, bot->getInput(), true, false, false, + speed.x * facing.x + speed.y * facing.y + speed.z * facing.z) != 0; + done = true; + return true; + } + if (arrived || done) + { + const Vec3 facing = info->getFaceing(); + const Vec3& speed = mobile->getSpeed(); + ok = TankControl::resetControls(bot, bot->getInput(), true, false, false, + speed.x * facing.x + speed.y * facing.y + speed.z * facing.z) != 0; + return true; + } + + Vec2 position; + position.x = info->getPosition().x; + position.y = info->getPosition().z; + Vec2 forward; // read, never used + forward.x = info->getTransformation().m[8]; + forward.y = info->getTransformation().m[10]; + (void)forward; + Vec2 toTarget; + toTarget.x = target.x - position.x; + toTarget.y = target.y - position.y; + Vec2 direction = toTarget; + const float distance = std::sqrt(toTarget.x * toTarget.x + toTarget.y * toTarget.y); + if (distance > 1e-05f) + { + const float inverse = 1.0f / distance; + direction.x = direction.x * inverse; + direction.y = inverse * direction.y; + } + float turnFactor = 1.0f; + float largestAngle; + if (std::fabs(mobile->getSpeedMagnitude()) > 3.0f && moveTo->getLargestAngleDiff(largestAngle)) + { + float excess = 0.0f; + if (0.0f <= std::fabs(largestAngle) - 0.35f) + excess = std::fabs(largestAngle) - 0.35f; + float scaled = excess * 2.5f; + if (1.0f < excess * 2.5f) + scaled = 1.0f; + turnFactor = 1.0f - scaled * 0.7f; + } + + float mode; + float angle; + float reference; + float limit; + ok = TankControl::actionStatusDecision(bot, info, direction, distance, moveTo, mode, angle, reference, limit) != 0; + if (mode == 666.0f) + { + const Vec3 facing = info->getFaceing(); + const Vec3& speed = mobile->getSpeed(); + ok = TankControl::resetControls(bot, bot->getInput(), true, false, false, + speed.x * facing.x + speed.y * facing.y + speed.z * facing.z) != 0; + done = true; + return true; + } + if (!ok) + return true; + + const float maxSpeed = mobile->getMaxSpeed(); + Vec2 remaining; + remaining.x = target.x - position.x; + remaining.y = target.y - position.y; + const float remainingSqr = remaining.y * remaining.y + remaining.x * remaining.x; + float approachFactor = 1.0f; + const float gap = remainingSqr - physical->getSmallestRadius() - 0.5f; + if (gap < fallOffDistanceSqr) + { + approachFactor = gap / fallOffDistanceSqr; + if (approachFactor <= 0.35f) + approachFactor = 0.35f; + } + const float factor = (approachFactor < turnFactor) ? approachFactor : turnFactor; + ok = TankControl::controlTowardsDirection(info, controlInfo, mobile, physical, bot->getInput(), direction, + factor * maxSpeed, mode, angle, reference, limit) != 0; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveTo.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveTo.h new file mode 100644 index 000000000..7414c9287 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveTo.h @@ -0,0 +1,28 @@ +// EntryTankMoveTo: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTANKMOVETO_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTANKMOVETO_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryTankMoveTo - statement type 7. +class EntryTankMoveTo : public BAPEntry +{ +public: + EntryTankMoveTo(); + virtual ~EntryTankMoveTo(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTANKMOVETO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToDirection.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToDirection.cpp new file mode 100644 index 000000000..bbd0b6bdb --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToDirection.cpp @@ -0,0 +1,143 @@ +// EntryTankMoveToDirection (split out of BAPEntries.cpp by S0, bodies unchanged). + +// static init: ELF 0x2C5110 (__tcf_0 0x2C5170, _GLOBAL__I 0x2C51A0): 's Init object only. +#include + +#include "EntryTankMoveToDirection.h" + +#include "ControlFunctions.h" +#include "VehicleControlInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveToDirection.h" +#include "../AIBotActionPlan/BAPCondition.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../IO/Input/PlayerInput.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2C4760 (C1; C2 0x2C4740). +EntryTankMoveToDirection::EntryTankMoveToDirection() +{ +} + +// ELF 0x2C47A0 (D1; D2 0x2C4780, D0 0x2C47C0). +EntryTankMoveToDirection::~EntryTankMoveToDirection() +{ +} + +// ELF 0x2C51C0. +int EntryTankMoveToDirection::getTargetId() +{ + return 8; +} + +// ELF 0x2C4800. +bool EntryTankMoveToDirection::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveToDirection* const moveTo = static_cast(script); + Vec2 position = {0.0f, 0.0f}; + Vec2 direction = {0.0f, 0.0f}; + Vec2 normal = {0.0f, 0.0f}; + Vec2 facing = {0.0f, 0.0f}; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + return true; + } + IAIObjectPhysical* const physical = info->getAIObject()->getPhysical(); + if (!physical->hasPhysicsEnabled()) + physical->enablePhysics(info->getSide()); + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + done = false; + vec3ToVec2XZ(info->getPosition(), position); + const Vec3 face = info->getFaceing(); + vec3ToVec2XZ(face, facing); + getNormal(facing, normal); + vehiclecontrol::normalizeVec2(normal); + const float magnitude = info->getMobile()->getSpeedMagnitude(); + const Vec3 facing3 = info->getFaceing(); + const Vec3& speed = info->getMobile()->getSpeed(); + const float speedDot = speed.x * facing3.x + speed.y * facing3.y + speed.z * facing3.z; + const float sign = speedDot > 0.0f ? 1.0f : (speedDot < 0.0f ? -1.0f : 0.0f); + const float signedSpeed = sign * magnitude; + const auto clampCos = [](float value) { + const float upper = value > 1.0f ? 1.0f : value; + return upper > -1.0f ? upper : -1.0f; + }; + float targetAngle; + float targetSpeed; + if (moveTo->m_condition64->evaluate(bot)) + { + vec3ToVec2XZ(moveTo->m_direction, direction); + targetSpeed = 0.0f; + const float dot = direction.x * normal.x + direction.y * normal.y; + if (facing.x * direction.x + facing.y * direction.y > 0.0f) + targetAngle = std::acos(clampCos(dot)) - 1.5707964f; + else + { + const float clamped = clampCos(dot); + const float directionSign = clamped > 0.0f ? 1.0f : (clamped < 0.0f ? -1.0f : 0.0f); + targetAngle = directionSign * 1.5707964f; + } + } + else + { + Vec2 point = {0.0f, 0.0f}; + ok = moveTo->update(point, done) != 0; + if (!ok) + { + done = true; + return true; + } + direction = {point.x - position.x, point.y - position.y}; + const float length = std::sqrt(direction.x * direction.x + direction.y * direction.y); + if (length > 1e-06f) + { + const float inverse = 1.0f / length; + direction.x *= inverse; + direction.y *= inverse; + } + targetAngle = std::acos(clampCos(direction.x * normal.x + direction.y * normal.y)) - 1.5707964f; + const float angleSign = targetAngle > 0.0f ? 1.0f : (targetAngle < 0.0f ? -1.0f : 0.0f); + const float absoluteAngle = targetAngle < 0.0f ? -targetAngle : targetAngle; + const float facingDot = facing.x * direction.x + facing.y * direction.y; + vehiclecontrol::normalizeVec2(facing); + if (absoluteAngle > 0.87266463f || facingDot < 0.0f) + targetAngle = angleSign * 0.017453292f * 90.0f; + const float maximum = info->getMobile()->getMaxSpeed(); + targetSpeed = moveTo->m_maxSpeed > maximum ? maximum : moveTo->m_maxSpeed; + if (facingDot < 0.0f) + targetSpeed = 0.0f; + } + io::PlayerInput* const input = bot->getInput(); + float turnInput = (input->mappingFlags & 1ULL) ? input->inputs[0] : 0.0f; + float throttle = (input->mappingFlags & 8ULL) ? input->inputs[3] : 0.0f; + const float facingDot = facing.x * moveTo->m_state68.y + facing.y * moveTo->m_state68.z; + updateAngle(targetAngle, std::acos(clampCos(facingDot)), turnInput, 1.0f, 1.0f, 0.8f); + updateLinear(targetSpeed, signedSpeed, moveTo->m_state68.x, throttle, -0.9f, 1.0f, 1.0f); + moveTo->m_state68.y = facing.x; + moveTo->m_state68.z = facing.y; + moveTo->m_state68.x = signedSpeed; + io::PlayerInput* const output = bot->getInput(); + if (output->mappingFlags & 1ULL) + output->inputs[0] = turnInput; + bot->getInput()->setInput(static_cast(3), throttle); + ok = true; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToDirection.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToDirection.h new file mode 100644 index 000000000..6aa4b1d6b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToDirection.h @@ -0,0 +1,27 @@ +// EntryTankMoveToDirection: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTANKMOVETODIRECTION_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTANKMOVETODIRECTION_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryTankMoveToDirection - statement type 8. +class EntryTankMoveToDirection : public BAPEntry +{ +public: + EntryTankMoveToDirection(); + virtual ~EntryTankMoveToDirection(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTANKMOVETODIRECTION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToObject.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToObject.cpp new file mode 100644 index 000000000..5a3a0be0f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToObject.cpp @@ -0,0 +1,172 @@ +// EntryTankMoveToObject (attested TU `EntryTankMoveToObject.cpp`, split out of BAPEntries.cpp by S0). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32): the interpreter entry that drives a tank +// to an object (a BAPAMoveTo with a target object). execute's flags follow the BotScript +// convention: `ok` (the step ran) and `done` (the statement is finished; with ok == false it failed). +// +// static init: ELF 0x2C5940 (__tcf_0 0x2C59A0, _GLOBAL__I 0x2C59D0): the guard object only. + +#include "EntryTankMoveToObject.h" + +#include "TankControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +EntryTankMoveToObject::EntryTankMoveToObject() +{ +} + +EntryTankMoveToObject::~EntryTankMoveToObject() +{ +} + +int EntryTankMoveToObject::getTargetId() +{ + return 9; +} + +// ELF 0x2C5290 (listing; Ghidra cross-check). EntryTankMoveTo's steering for a move to an object, +// with these differences: physics is enabled only when off (no alwaysEnable static); it fails +// (done, not ok) without the target's information; isFinished is asked on every call (no +// one-second throttle); update gets the target's radius (its physical part +0x2C, unchecked); the +// direction is normalised above 1e-06. Shipped quirks kept: the equipment's parts are read before +// its null test, the fall-off compares the SQUARED distance (static fallOffDistanceSqr 196). +bool EntryTankMoveToObject::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + static float fallOffDistanceSqr = 196.0f; // .data 0x4BD984 + + BAPAMoveTo* const moveTo = static_cast(script); + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* const mobile = info->getMobile(); // read before the null test (0x2C52F6) + IPIControlInfo* const controlInfo = info->getControlInfo(); + IPIPhysical* const physical = info->getPhysical(); + if (!info || !mobile || !controlInfo || !physical) + { + done = true; + ok = false; + return true; + } + IAIObjectPhysical* const object = info->getAIObject()->getPhysical(); + if (!object->hasPhysicsEnabled()) + object->enablePhysics(info->getSide()); + Information* const target = informationManager->getInformation(moveTo->getObject()); + if (!target) + { + done = true; + ok = false; + return true; + } + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + done = false; + + Vec2 point; + point.x = point.y = 0.0f; + bool arrived; + ok = moveTo->update(point, done, arrived, target->getPhysical()->getRadius()) != 0; + if (!ok) + { + const Vec3 facing = info->getFaceing(); + const Vec3& speed = mobile->getSpeed(); + ok = TankControl::resetControls(bot, bot->getInput(), true, false, false, + speed.x * facing.x + speed.y * facing.y + speed.z * facing.z) != 0; + done = true; + return true; + } + if (arrived || done) + { + const Vec3 facing = info->getFaceing(); + const Vec3& speed = mobile->getSpeed(); + ok = TankControl::resetControls(bot, bot->getInput(), true, false, false, + speed.x * facing.x + speed.y * facing.y + speed.z * facing.z) != 0; + return true; + } + + Vec2 position; + position.x = info->getPosition().x; + position.y = info->getPosition().z; + Vec2 forward; // read, never used + forward.x = info->getTransformation().m[8]; + forward.y = info->getTransformation().m[10]; + (void)forward; + Vec2 toTarget; + toTarget.x = point.x - position.x; + toTarget.y = point.y - position.y; + Vec2 direction = toTarget; + const float distance = std::sqrt(toTarget.x * toTarget.x + toTarget.y * toTarget.y); + if (distance > 1e-06f) + { + const float inverse = 1.0f / distance; + direction.x = direction.x * inverse; + direction.y = inverse * direction.y; + } + float turnFactor = 1.0f; + float largestAngle; + if (std::fabs(mobile->getSpeedMagnitude()) > 3.0f && moveTo->getLargestAngleDiff(largestAngle)) + { + float excess = 0.0f; + if (0.0f <= std::fabs(largestAngle) - 0.35f) + excess = std::fabs(largestAngle) - 0.35f; + float scaled = excess * 2.5f; + if (1.0f < excess * 2.5f) + scaled = 1.0f; + turnFactor = 1.0f - scaled * 0.7f; + } + + float mode; + float angle; + float reference; + float limit; + ok = TankControl::actionStatusDecision(bot, info, direction, distance, moveTo, mode, angle, reference, limit) != 0; + if (mode == 666.0f) + { + const Vec3 facing = info->getFaceing(); + const Vec3& speed = mobile->getSpeed(); + ok = TankControl::resetControls(bot, bot->getInput(), true, false, false, + speed.x * facing.x + speed.y * facing.y + speed.z * facing.z) != 0; + done = true; + return true; + } + if (!ok) + return true; + + const float maxSpeed = mobile->getMaxSpeed(); + Vec2 remaining; + remaining.x = point.x - position.x; + remaining.y = point.y - position.y; + const float remainingSqr = remaining.y * remaining.y + remaining.x * remaining.x; + float approachFactor = 1.0f; + const float gap = remainingSqr - physical->getSmallestRadius() - 0.5f; + if (gap < fallOffDistanceSqr) + { + approachFactor = gap / fallOffDistanceSqr; + if (approachFactor <= 0.35f) + approachFactor = 0.35f; + } + const float factor = (approachFactor < turnFactor) ? approachFactor : turnFactor; + ok = TankControl::controlTowardsDirection(info, controlInfo, mobile, physical, bot->getInput(), direction, + factor * maxSpeed, mode, angle, reference, limit) != 0; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToObject.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToObject.h new file mode 100644 index 000000000..1b34f398c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToObject.h @@ -0,0 +1,28 @@ +// EntryTankMoveToObject: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTANKMOVETOOBJECT_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTANKMOVETOOBJECT_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryTankMoveToObject - statement type 9. +class EntryTankMoveToObject : public BAPEntry +{ +public: + EntryTankMoveToObject(); + virtual ~EntryTankMoveToObject(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTANKMOVETOOBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankResetControls.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankResetControls.cpp new file mode 100644 index 000000000..524622a72 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankResetControls.cpp @@ -0,0 +1,64 @@ +// EntryTankResetControls (split out of BAPEntries.cpp by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +// static init: ELF 0x2C5D70 (__tcf_0 0x2C5DD0, _GLOBAL__I 0x2C5E00): 's Init object only. +#include + +#include "EntryTankResetControls.h" + +#include "TankControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../Main/AIDllFrontier.h" +#include "../../../../IO/Input/PlayerInput.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryTankResetControls::EntryTankResetControls() +{ +} + +EntryTankResetControls::~EntryTankResetControls() +{ +} + +int EntryTankResetControls::getTargetId() +{ + return 14; +} + +// ELF 0x2C5AC0 (Ghidra, listing for the dot product). A single-input reset releases that one +// input (setInput inlined with its range diagnostic) and succeeds. The group form resets through +// TankControl::resetControls with the equipment's forward speed (mobile speed dot facing); the +// information lookup is not null-tested. Unlike the car entry, nothing is asked for twice. +// `ok` is that call's answer; `done` is always set. +bool EntryTankResetControls::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAResetControls* const reset = static_cast(script); + if (reset->hasSingleInput()) + { + io::PlayerInput* const input = bot->getInput(); + input->setInput(static_cast(reset->getInput()), 0.0f); + ok = true; + done = true; + return true; + } + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* const mobile = equipment->getMobile(); // +0x38 + done = true; + const Vec3 facing = equipment->getFaceing(); // +0x40 + const Vec3& speed = mobile->getSpeed(); // +0x1C + const float forwardSpeed = speed.y * facing.y + speed.x * facing.x + speed.z * facing.z; + ok = TankControl::resetControls(bot, bot->getInput(), reset->m_resetMove, reset->m_resetLook, + reset->m_resetTrigger, forwardSpeed) != 0; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankResetControls.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankResetControls.h new file mode 100644 index 000000000..20277ffbb --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankResetControls.h @@ -0,0 +1,28 @@ +// EntryTankResetControls: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTANKRESETCONTROLS_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTANKRESETCONTROLS_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryTankResetControls - statement type 14. +class EntryTankResetControls : public BAPEntry +{ +public: + EntryTankResetControls(); + virtual ~EntryTankResetControls(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTANKRESETCONTROLS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankTurnTo.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankTurnTo.cpp new file mode 100644 index 000000000..ff73471c1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankTurnTo.cpp @@ -0,0 +1,183 @@ +// Tank turning entry for BAPATurn. Attested TU: EntryTankTurnTo.cpp. + +// static init: ELF 0x2C6780 (__tcf_0 0x2C67E0, _GLOBAL__I 0x2C6810): 's Init object only. +#include + +#include "EntryTankTurnTo.h" + +#include "TankControl.h" +#include "VehicleControlInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPATurn.h" +#include "../AIBotActionPlan/BAPCondition.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2C5E50 (C1; C2 0x2C5E30). +EntryTankTurnTo::EntryTankTurnTo() +{ +} + +// ELF 0x2C5E90 (D1; D2 0x2C5E70, D0 0x2C5EB0). +EntryTankTurnTo::~EntryTankTurnTo() +{ +} + +// ELF 0x2C6830. +int EntryTankTurnTo::getTargetId() +{ + return 24; +} + +// ELF 0x2C5EF0. The end condition finishes the statement; otherwise getDirection supplies ok, +// and the entry turns or brakes while keeping the statement active. +bool EntryTankTurnTo::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPATurn* const turn = static_cast(script); + Vec2 position; + position.x = position.y = 0.0f; + if (turn->m_endCondition->evaluate(bot)) + { + done = true; + ok = true; + return true; + } + done = false; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + return true; + } + IAIObjectPhysical* const object = info->getAIObject()->getPhysical(); + if (!object->hasPhysicsEnabled()) + object->enablePhysics(info->getSide()); + IPIMobile* const mobile = info->getMobile(); + IPIControlInfo* const controlInfo = info->getControlInfo(); + IPIPhysical* const physical = info->getPhysical(); + if (!mobile || !controlInfo || !physical) + { + done = true; + ok = false; + return true; + } + vec3ToVec2XZ(info->getPosition(), position); + const Vec3 target = turn->getDirection(ok); + if (!ok) + { + done = true; + return true; + } + Vec2 direction; + vec3ToVec2XZ(target, direction); + vehiclecontrol::normalizeVec2(direction); + const Mat4& forwardTransform = info->getTransformation(); + const Vec3& forward3 = *reinterpret_cast(&forwardTransform.m[8]); + Vec2 forward; + vec3ToVec2XZ(forward3, forward); + vehiclecontrol::normalizeVec2(forward); + Vec2 right; + vec3ToVec2XZ(vehiclecontrol::rightAxis(info->getTransformation()), right); + vehiclecontrol::normalizeVec2(right); + float dot = right.x * direction.x + right.y * direction.y; + if (dot < -1.0f) + dot = -1.0f; + else if (dot > 1.0f) + dot = 1.0f; + const float halfPi = 1.570796371f; + float angle = acosf(dot) - halfPi; + if (angle < -halfPi) + angle = -halfPi; + else if (angle > halfPi) + angle = halfPi; + if (forward.x * direction.x + forward.y * direction.y < 0.0f) + { + if (angle == 0.0f) + angle = 3.141592741f; + else + { + const float sign = angle > 0.0f ? 1.0f : (0.0f > angle ? -1.0f : 0.0f); + angle = angle + sign * halfPi; + } + } + if (std::fabs(angle) > turn->m_turnSpeed) + TankControl::turnTowardsDirection(angle, turn->m_turnSpeed, true, info, mobile, + controlInfo, bot->getInput(), &ok); + else + { + const Vec3 facing = info->getFaceing(); + const Vec3& speed = mobile->getSpeed(); + TankControl::resetControls(bot, bot->getInput(), true, false, false, + speed.x * facing.x + speed.y * facing.y + speed.z * facing.z); + } + const Mat4& transformation = info->getTransformation(); + turn->m_vec28.x = transformation.m[8]; + turn->m_vec28.y = transformation.m[9]; + turn->m_vec28.z = transformation.m[10]; + turn->m_unwritten24 = mobile->getSpeedMagnitude(); + return true; +} + +// ELF 0x2C65E0. Returns the midpoint of the two lowest-scored relative box corners. +// Corners outside the facing half-plane receive -1 and remain eligible. +void EntryTankTurnTo::getCentreOfFacingSide(const Vec2& origin, const Vec2& minimum, + const Vec2& maximum, const Vec2& facing, Vec2& centre) +{ + Vec2 corners[4]; + corners[0] = minimum; + corners[1].x = minimum.x; + corners[1].y = maximum.y; + corners[2].x = maximum.x; + corners[2].y = minimum.y; + corners[3] = maximum; + const float dx = facing.x - origin.x; + const float dy = facing.y - origin.y; + float scores[4]; + for (int i = 0; i < 4; ++i) + { + corners[i].x = corners[i].x - origin.x; + corners[i].y = corners[i].y - origin.y; + if (dx * corners[i].x + dy * corners[i].y > 0.0f) + scores[i] = corners[i].x * corners[i].x + corners[i].y * corners[i].y; + else + scores[i] = -1.0f; + } + int first = 0; + int second = 1; + if (scores[0] > scores[1]) + { + first = 1; + second = 0; + } + for (int i = 2; i < 4; ++i) + { + if (scores[first] > scores[i]) + { + second = first; + first = i; + } + else if (scores[second] > scores[i]) + second = i; + } + centre = corners[first]; + centre.x = centre.x + corners[second].x; + centre.y = centre.y + corners[second].y; + centre.x = centre.x * 0.5f; + centre.y = centre.y * 0.5f; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankTurnTo.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankTurnTo.h new file mode 100644 index 000000000..0241c3394 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankTurnTo.h @@ -0,0 +1,30 @@ +// Tank turning entry for BAPATurn. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTANKTURNTO_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTANKTURNTO_H + +#include "BAPEntry.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryTankTurnTo - statement type 24. +class EntryTankTurnTo : public BAPEntry +{ +public: + EntryTankTurnTo(); + virtual ~EntryTankTurnTo(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); + // Returns a midpoint relative to the first argument, using the shipped corner scores. + void getCentreOfFacingSide(const Vec2&, const Vec2&, const Vec2&, const Vec2&, Vec2&); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTANKTURNTO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTrigger.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTrigger.cpp new file mode 100644 index 000000000..16861100a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTrigger.cpp @@ -0,0 +1,226 @@ +// EntryTrigger (attested TU `EntryTrigger.cpp`, split out of BAPEntries.cpp by S0). Recovered from +// libaidll.so (Linux 1.5.3153, ia-32): the soldier entry for BAPATrigger (statement type 11). Package B; see docs/macos-ai-behaviour-plan.md. +// execute's flags follow the BotScript convention: `ok` (the step ran) and `done` (finished; with +// ok == false the statement failed). + +// static init: ELF 0x2C7270 (__tcf_0 0x2C72D0, _GLOBAL__I 0x2C7300): 's Init object only. +#include + +#include "EntryTrigger.h" + +#include "InfanteryControl.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IBotManager.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPCondition.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../../IO/Input/PlayerInput.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryTrigger::EntryTrigger() +{ +} + +EntryTrigger::~EntryTrigger() +{ +} + +int EntryTrigger::getTargetId() +{ + return 11; +} + +namespace { + +inline Information* lookup(unsigned int handle) +{ + return informationManager->getInformation(handle); +} + +} // namespace + +// ELF 0x2C6900. Presses the statement's input once the start condition holds and releases it on the +// stop condition (or right away for a one-shot trigger: m_flag false finishes on the press). For +// weapon-select inputs it finishes as soon as that weapon is active. For PIFire/PIAltFire it first +// puts the soldier into the weapon's firing pose (crouching against a lying target closer than +// `range`) and tunes the weapon's bot skill: 1 for thrown or guided weapons, otherwise +// 1 - (1 - skill) * {0.5 direct fire, 0.8 explosive from a vehicle, 0.4 explosive on foot}, with +// direct fire at an occupied human vehicle left at the raw skill; the scale is 3 against an +// object flagged 0x10 by a secondary non-0x80 object (the image's flag tests on Information +4). +bool EntryTrigger::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + static float range = 1.0f; // ELF 0x4BDAA4 (.data), compared with a squared XZ distance + + BAPATrigger* trigger = static_cast(script); + BotMain* botMain = static_cast(bot); + int type = trigger->m_input; + Information* info = lookup(bot->getCurrentEquipment()); + IPIArmament* armament = info->getArmament(); + WeaponInfo* weapon = 0; + if (armament != 0 && armament->getActiveWeapon() != -1) + weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + + const io::PlayerInput* input = bot->getInput(); + bool moving = false; + if (infantry_detail::inputValue(input, io::PIThrottle) != 0.0f + || infantry_detail::inputValue(input, io::PIYaw) != 0.0f + || infantry_detail::inputValue(input, io::PISprint) != 0.0f) + moving = true; + bool isFire = false; + if (type == io::PIFire || type == io::PIAltFire) + isFire = true; + bool allowPress = true; + if (isFire && botMain->botInPoseTransition()) + allowPress = false; + + if (weapon != 0) + { + if (static_cast(type - io::PIWeaponSelect1) < 8) + { + if (weapon->getWeaponActivate() == type) + { + ok = true; + done = true; + return true; + } + if (trigger->m_started) + { + ok = true; + done = false; + return true; + } + } + else if (weapon->getWeaponZoom() == type) + { + if (moving) + return true; + } + else if (isFire) + { + if (!moving && weapon->getWeaponType() != 4) + { + SoldierPose pose = SPStanding; + if (info->isOfType(ITSoldier)) + { + pose = weapon->getFiringPose(); + if (armament->getActiveWeapon() == 0 + || (bot->getFiringTarget() != static_cast(-1) && weapon->getWeaponType() == 3)) + { + Vec2 own; + own.x = own.y = 0.0f; + Vec2 other; + other.x = other.y = 0.0f; + vec3ToVec2XZ(info->getPosition(), own); + Information* target = lookup(bot->getFiringTarget()); + if (target != 0) + { + vec3ToVec2XZ(target->getPosition(), other); + const float dx = other.x - own.x; + const float dy = other.y - own.y; + if (dy * dy + dx * dx < range && target->getSoldierPose() == SPLying) + pose = SPCrouching; + } + } + } + const SoldierPose current = info->getSoldierPose(); + if (current != SPSwimming && current != pose) + bot->requestSoldierPose(pose, false); + } + + Information* target = lookup(bot->getFiringTarget()); + float skill = static_cast(CommonSingletonServer::m_iaiSettings)->getBotSkill(); + bool humanVehicle = false; + if (target != 0 && target->getAIObject() != 0 + && IBotManager::instance->getBot(target->getAIObject()) == 0 + && target->getUnit() != 0 && target->getUnit()->isOccupied()) + humanVehicle = true; + if (weapon->getWeaponZoom() != io::PINone && bot->getSpawnKit() == 1) + weapon->getMaxRange(); // retail: the result is dropped + if (!weapon->getIsThrown()) + { + if (weapon->getExplosionRadius() == 0.0f) + { + if (!humanVehicle) + skill = 1.0f - (1.0f - skill) * 0.5f; + } + else if (!info->isOfType(ITSoldier)) + { + skill = 1.0f - (1.0f - skill) * 0.8f; + } + else + { + skill = 1.0f - (1.0f - skill) * 0.4f; + } + } + else + { + skill = 1.0f; + } + if (weapon->getWeaponGuidanceType() != 0) + skill = 1.0f; + float scale = 1.0f; + bool apply = true; + if (!info->isOfType(ITAir)) + { + if (target == 0) + apply = false; + else if (target->isOfType(ITAir) && !info->isPrimary() + && !info->isOfType(ITNaval)) + scale = 3.0f; + } + if (apply) + weapon->setBotSkill(skill, bot->getFiringTargetTime(), scale); + } + } + + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (now < trigger->m_endTime) + return true; + io::PlayerInput* writable = bot->getInput(); + if (trigger->m_stopCondition != 0 && trigger->m_stopCondition->evaluate(bot)) + { + // inlined setInput in the image + writable->setInput(static_cast(type), 0.0f); + trigger->m_started = false; + ok = true; + done = true; + return true; + } + if (!trigger->m_started || !trigger->m_flag) + { + if (allowPress && trigger->m_startCondition->evaluate(bot)) + { + writable->setInput(static_cast(trigger->m_input), 1.0f); + trigger->m_started = true; + ok = true; + done = !trigger->m_flag; + return true; + } + writable->setInput(static_cast(trigger->m_input), 0.0f); + trigger->m_started = false; + ok = true; + done = false; + return true; + } + writable->setInput(static_cast(trigger->m_input), 0.0f); + trigger->m_started = false; + ok = true; + done = true; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTrigger.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTrigger.h new file mode 100644 index 000000000..71b1fd4bd --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTrigger.h @@ -0,0 +1,28 @@ +// EntryTrigger: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTRIGGER_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTRIGGER_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryTrigger - statement type 11. +class EntryTrigger : public BAPEntry +{ +public: + EntryTrigger(); + virtual ~EntryTrigger(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTRIGGER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTriggerContinously.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTriggerContinously.cpp new file mode 100644 index 000000000..848a92b86 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTriggerContinously.cpp @@ -0,0 +1,180 @@ +// EntryTriggerContinously (attested TU `EntryTriggerContinously.cpp`, split out of BAPEntries.cpp by S0). Recovered from +// libaidll.so (Linux 1.5.3153, ia-32): the soldier entry for BAPATriggerContinously (statement type 12). Package B; see docs/macos-ai-behaviour-plan.md. +// execute's flags follow the BotScript convention: `ok` (the step ran) and `done` (finished; with +// ok == false the statement failed). + +// static init: ELF 0x2C7CD0 (__tcf_0 0x2C7D30, _GLOBAL__I 0x2C7D60): 's Init object only. +#include + +#include "EntryTriggerContinously.h" + +#include "InfanteryControl.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IBotManager.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPATriggerContinously.h" +#include "../AIBotActionPlan/BAPCondition.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../../IO/Input/PlayerInput.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryTriggerContinously::EntryTriggerContinously() +{ +} + +EntryTriggerContinously::~EntryTriggerContinously() +{ +} + +int EntryTriggerContinously::getTargetId() +{ + return 12; +} + +namespace { + +inline Information* lookup(unsigned int handle) +{ + return informationManager->getInformation(handle); +} + +} // namespace + +// ELF 0x2C73F0. Holds the statement's input while the start condition holds (or, once started, +// until the stop condition holds) and finishes on the abort condition. For PIFire/PIAltFire it puts +// the soldier into the weapon's firing pose (not for kit 4's weapon 5 on foot) and tunes the +// weapon's bot skill as EntryTrigger does, without the thrown-weapon case. Fails (ok false, done) +// for a fire input when the bot has weapons but no active one. +bool EntryTriggerContinously::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPATriggerContinously* trigger = static_cast(script); + BotMain* botMain = static_cast(bot); + Information* info = lookup(bot->getCurrentEquipment()); + IPIArmament* armament = info->getArmament(); + WeaponInfo* weapon = 0; + if (armament != 0 && armament->getActiveWeapon() != -1) + weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + + const int type = trigger->m_input; + bool isFire = false; + if (type == io::PIFire || type == io::PIAltFire) + isFire = true; + bool allowPress = true; + if (isFire) + { + allowPress = !botMain->botInPoseTransition(); + if (weapon == 0) + { + if (armament != 0) + { + ok = false; + done = true; + return true; + } + } + else + { + const io::PlayerInput* input = bot->getInput(); + if (infantry_detail::inputValue(input, io::PIThrottle) == 0.0f + && infantry_detail::inputValue(input, io::PIYaw) == 0.0f + && infantry_detail::inputValue(input, io::PISprint) == 0.0f + && !(bot->getSpawnKit() == 4 && info->isOfType(ITSoldier) + && armament->getActiveWeapon() == 5)) + { + SoldierPose pose = SPStanding; + if (info->isOfType(ITSoldier)) + pose = weapon->getFiringPose(); + const SoldierPose current = info->getSoldierPose(); + if (current != SPSwimming && current != pose) + bot->requestSoldierPose(pose, false); + } + + Information* target = lookup(bot->getFiringTarget()); + float skill = static_cast(CommonSingletonServer::m_iaiSettings)->getBotSkill(); + bool humanVehicle = false; + if (target != 0 && target->getAIObject() != 0 + && IBotManager::instance->getBot(target->getAIObject()) == 0 + && target->getUnit() != 0 && target->getUnit()->isOccupied()) + humanVehicle = true; + weapon->getExplosionRadius(); // retail: called twice, the first result dropped + if (weapon->getExplosionRadius() == 0.0f) + { + if (!humanVehicle) + skill = 1.0f - (1.0f - skill) * 0.5f; + } + else if (!info->isOfType(ITSoldier)) + { + skill = 1.0f - (1.0f - skill) * 0.8f; + } + else + { + skill = 1.0f - (1.0f - skill) * 0.4f; + } + if (weapon->getWeaponGuidanceType() != 0) + skill = 1.0f; + float scale = 1.0f; + bool apply = true; + if (!info->isOfType(ITAir)) + { + if (target == 0) + apply = false; + else if (target->isOfType(ITAir) && !info->isPrimary() + && !info->isOfType(ITNaval)) + scale = 3.0f; + } + if (apply) + weapon->setBotSkill(skill, bot->getFiringTargetTime(), scale); + } + } + + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (now < trigger->m_endTime) + return true; + if (trigger->m_abortCondition != 0 && trigger->m_abortCondition->evaluate(bot)) + { + ok = true; + done = true; + return true; + } + io::PlayerInput* writable = bot->getInput(); + if (allowPress) + { + if (trigger->m_startCondition->evaluate(bot)) + { + // inlined setInput in the image + writable->setInput(static_cast(type), 1.0f); + trigger->m_started = true; + ok = true; + done = false; + return true; + } + if (trigger->m_stopCondition != 0 && trigger->m_started && !trigger->m_stopCondition->evaluate(bot)) + { + writable->setInput(static_cast(type), 1.0f); + ok = true; + done = false; + return true; + } + } + // inlined setInput in the image + writable->setInput(static_cast(type), 0.0f); + trigger->m_started = false; + ok = true; + done = false; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTriggerContinously.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTriggerContinously.h new file mode 100644 index 000000000..c59cb8478 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTriggerContinously.h @@ -0,0 +1,28 @@ +// EntryTriggerContinously: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTRIGGERCONTINOUSLY_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTRIGGERCONTINOUSLY_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryTriggerContinously - statement type 12. +class EntryTriggerContinously : public BAPEntry +{ +public: + EntryTriggerContinously(); + virtual ~EntryTriggerContinously(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTRIGGERCONTINOUSLY_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTurnToMedium.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTurnToMedium.cpp new file mode 100644 index 000000000..2bdfb1231 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTurnToMedium.cpp @@ -0,0 +1,165 @@ +// Medium-LOD turning entry for BAPATurn. Attested TU: EntryTurnToMedium.cpp. + +// static init: ELF 0x2C89C0 (__tcf_0 0x2C8A20, _GLOBAL__I 0x2C8A50): 's Init object only. +#include + +#include "EntryTurnToMedium.h" + +#include "InfanteryControl.h" +#include "VehicleControlInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPATurn.h" +#include "../AIBotActionPlan/BAPCondition.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2C7DB0 (C1; C2 0x2C7D90). +EntryTurnToMedium::EntryTurnToMedium() +{ +} + +// ELF 0x2C7DF0 (D1; D2 0x2C7DD0, D0 0x2C7E10). +EntryTurnToMedium::~EntryTurnToMedium() +{ +} + +// ELF 0x2C7E50. Turns the object without physics using a fixed angular step per tick, then +// aligns its axes to the terrain normal without moving its position. Only the condition ends it. +bool EntryTurnToMedium::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPATurn* const turn = static_cast(script); + Vec2 position; + position.x = position.y = 0.0f; + if (turn->m_endCondition->evaluate(bot)) + { + done = true; + ok = true; + return true; + } + done = false; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + return true; + } + IAIObjectPhysical* const physical = info->getAIObject()->getPhysical(); + if (physical->hasPhysicsEnabled()) + physical->disablePhysics(info->getSide()); + IPIMobile* const mobile = info->getMobile(); + IPIControlInfo* const controlInfo = info->getControlInfo(); + IPIPhysical* const physicalInfo = info->getPhysical(); + if (!mobile || !controlInfo || !physicalInfo) + { + done = true; + ok = false; + return true; + } + vec3ToVec2XZ(info->getPosition(), position); + const Vec3 target = turn->getDirection(ok); + if (!ok) + { + done = true; + return true; + } + Vec2 direction; + vec3ToVec2XZ(target, direction); + vehiclecontrol::normalizeVec2(direction); + const Mat4& forwardTransform = info->getTransformation(); + const Vec3& forward3 = *reinterpret_cast(&forwardTransform.m[8]); + Vec2 forward2; + vec3ToVec2XZ(forward3, forward2); + vehiclecontrol::normalizeVec2(forward2); + Vec2 right2; + vec3ToVec2XZ(vehiclecontrol::rightAxis(info->getTransformation()), right2); + vehiclecontrol::normalizeVec2(right2); + float dot = right2.x * direction.x + right2.y * direction.y; + if (dot < -1.0f) + dot = -1.0f; + else if (dot > 1.0f) + dot = 1.0f; + const float halfPi = 1.570796371f; + float angle = acosf(dot) - halfPi; + if (angle < -halfPi) + angle = -halfPi; + else if (angle > halfPi) + angle = halfPi; + if (forward2.x * direction.x + forward2.y * direction.y < 0.0f) + { + const float sign = angle > 0.0f ? 1.0f : (0.0f > angle ? -1.0f : 0.0f); + angle = angle + sign * halfPi; + } + const float magnitude = std::fabs(angle); + if (magnitude > turn->m_turnSpeed) + { + IAIObject* const object = info->getAIObject(); + const Mat4& current = object->getTransformation(); + (void)info->getPosition(); + Vec3 forward; + const float step = 0.003926991f; + if (magnitude > step) + { + const float sign = angle > 0.0f ? 1.0f : (0.0f > angle ? -1.0f : 0.0f); + const Vec3& currentForward = *reinterpret_cast(¤t.m[8]); + rotateXZ(currentForward, forward, sign * step); + } + else + { + forward.x = direction.x; + forward.y = 0.0f; + forward.z = direction.y; + } + const Vec3& objectPosition = object->getPosition(); + float height; + Vec3 up; + up.x = up.y = up.z = 0.0f; + float slope; + static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->getHeightAndNormalForObject(object, objectPosition, height, up, slope); + Vec3 right = infantry_detail::crossInline(up, forward); + vehiclecontrol::normalizeVec3(right); + forward = infantry_detail::crossInline(right, up); + vehiclecontrol::normalizeVec3(forward); + Mat4 transformation = current; + transformation.m[0] = right.x; + transformation.m[1] = right.y; + transformation.m[2] = right.z; + transformation.m[4] = up.x; + transformation.m[5] = up.y; + transformation.m[6] = up.z; + transformation.m[8] = forward.x; + transformation.m[9] = forward.y; + transformation.m[10] = forward.z; + object->setTransformation(transformation, bot->getSide()); + } + const Mat4& transformation = info->getTransformation(); + turn->m_vec28.x = transformation.m[8]; + turn->m_vec28.y = transformation.m[9]; + turn->m_vec28.z = transformation.m[10]; + turn->m_unwritten24 = mobile->getSpeedMagnitude(); + return true; +} + +// ELF 0x2C8A70 +int EntryTurnToMedium::getTargetId() +{ + return 24; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTurnToMedium.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTurnToMedium.h new file mode 100644 index 000000000..5231920ab --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTurnToMedium.h @@ -0,0 +1,31 @@ +// Medium-LOD turning entry for BAPATurn. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTURNTOMEDIUM_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTURNTOMEDIUM_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BDB68; fieldless BAPEntry subclass. +class EntryTurnToMedium : public BAPEntry +{ +public: + EntryTurnToMedium(); // 0x2C7DB0 + virtual ~EntryTurnToMedium(); // 0x2C7DF0 + + virtual bool execute(BotScript*, Bot*, bool&, bool&); // 0x2C7E50, slot +0x08; from the base declaration + virtual int getTargetId(); // 0x2C8A70, slot +0x0C; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTURNTOMEDIUM_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/HeliControl.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/HeliControl.cpp new file mode 100644 index 000000000..05e46453e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/HeliControl.cpp @@ -0,0 +1,578 @@ +// Helicopter attitude, height and obstacle-avoidance controls. + +// static init: ELF 0x2CB150 (__tcf_0 0x2CB1B0, _GLOBAL__I 0x2CB1E0): 's Init object only. +#include + +#include "HeliControl.h" + +#include "VehicleControlInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIPathFinding/AerialHeightMap/AerialHeightMap.h" +#include "VehicleControlInline.h" +#include "../../../../IO/Input/PlayerInput.h" +#include "../../../../Math/Mat4.h" +#include +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// [INFERRED] Names for inline scalar/vector operations in the control bodies. +float clampHeliInput(float value, float minimum, float maximum) +{ + if (value < minimum) + return minimum; + return value > maximum ? maximum : value; +} + +Vec3 rotateHeliVector(const Mat4& matrix, const Vec3& v) +{ + // The retail expansions (moveToPoint 0x2C9A30..0x2C9A7D, aimAtDirection 0x2CA8CD..0x2CA91C) add the + // x and y products before the z product in every component. + return Vec3{matrix.m[0] * v.x + matrix.m[4] * v.y + matrix.m[8] * v.z, + matrix.m[1] * v.x + matrix.m[5] * v.y + matrix.m[9] * v.z, + matrix.m[2] * v.x + matrix.m[6] * v.y + matrix.m[10] * v.z}; +} + +} // namespace + +bool avoidRight(Bot* bot, float& clearance); + +// ELF 0x2C8A80 +void HeliControl::quickyMoveForward(Bot* bot, float heightDifference, const Vec3& rotationalSpeed) +{ + static float maxHeightDiff = 10.0f; + static float wantedPitchAtMaxHeight = -0.45f; + static float wantedPitchAtMinHeight = -0.1f; + Information* information = informationManager->getInformation(bot->getCurrentEquipment()); + io::PlayerInput* input = bot->getInput(); + input->setInput(information->getControlInfo()->getDriveThrottleControl(), 1.0f); + const float factor = clampHeliInput(heightDifference / maxHeightDiff, -1.0f, 1.0f); + keepPitchAt(bot, wantedPitchAtMinHeight + (wantedPitchAtMaxHeight - wantedPitchAtMinHeight) * + (1.0f - (factor + 1.0f) * 0.5f), + 1.0f, 0.3f, rotationalSpeed, 0.0f); +} + +// ELF 0x2C8D00 +int HeliControl::gotoHeight(Bot* bot, float height, const Vec3& rotationalSpeed) +{ + static float maxHeightDiff = 5.0f; + static float wantedElevationAtMaxHeightDiff = 5.0f; + static float maxElevationDiff = 2.0f; + static float minThrottleInput = 0.0f; + static float maxAngle = 0.3f; + static float wantedRotationSpeedAtMaxAngle = 0.5f; + static float maxRotationSpeedDiff = 0.4f; + Information* information = informationManager->getInformation(bot->getCurrentEquipment()); + io::PlayerInput* input = bot->getInput(); + if (!bot->isAirBorn() && information->getAltitude() > 5.0f) + bot->event_airborn(); + const Mat4& transformation = information->getTransformation(); + IPIMobile* mobile = information->getMobile(); + IPIControlInfo* controls = information->getControlInfo(); + const float elevation = clampHeliInput((height - transformation.m[13]) / maxHeightDiff, + -1.0f, 1.0f) * wantedElevationAtMaxHeightDiff; + const Vec3& speed = mobile->getSpeed(); + float throttle = clampHeliInput(clampHeliInput((elevation - speed.y) / maxElevationDiff, + -1.0f, 1.0f) + minThrottleInput, 0.0f, 1.0f); + if (elevation > 0.0f && speed.y < 0.0f && transformation.m[5] > 0.0f) + throttle = 1.0f; + input->setInput(controls->getDriveThrottleControl(), throttle); + float difference = (clampHeliInput(transformation.m[9] / maxAngle, -1.0f, 1.0f) * + wantedRotationSpeedAtMaxAngle - rotationalSpeed.x) / maxRotationSpeedDiff; + float value = difference * difference; + if (value > 1.0f) + value = 1.0f; + if (difference < 0.0f) + value = -value; + input->setInput(controls->getDrivePitchControl(), value); + difference = (-clampHeliInput(transformation.m[1] / maxAngle, -1.0f, 1.0f) * + wantedRotationSpeedAtMaxAngle - rotationalSpeed.z) / maxRotationSpeedDiff; + value = difference * difference; + if (value > 1.0f) + value = 1.0f; + if (difference > 0.0f) + value = -value; + input->setInput(controls->getDriveRollControl(), value); + input->setInput(controls->getDriveTurnControl(), 0.0f); + return 1; +} + +// ELF 0x2C9060 +void HeliControl::strafeTo(Bot* bot, const Vec3& target, const Vec3& rotationalSpeed) +{ + static float maxDist = 20.0f; + static float maxValue = 0.25f; + static float maxInput = 0.15f; + Information* information = informationManager->getInformation(bot->getCurrentEquipment()); + const Mat4& transformation = information->getTransformation(); + const Vec3 delta = {target.x - transformation.m[12], target.y - transformation.m[13], + target.z - transformation.m[14]}; + const float side = delta.x * transformation.m[0] + delta.y * transformation.m[1] + + delta.z * transformation.m[2]; + const float forward = delta.x * transformation.m[8] + delta.y * transformation.m[9] + + delta.z * transformation.m[10]; + keepRollAt(bot, -clampHeliInput(side / maxDist, -1.0f, 1.0f) * maxValue, + maxInput, 0.2f, rotationalSpeed); + keepPitchAt(bot, -clampHeliInput(forward / maxDist, -1.0f, 1.0f) * maxValue, + maxInput, 0.2f, rotationalSpeed, 0.0f); +} + +// ELF 0x2C9220 +void HeliControl::keepRollAt(Bot* bot, float dot, float maxInput, float maxSpeed, + const Vec3& rotationalSpeed) +{ + keepDotAt(bot, 2, dot, maxInput, maxSpeed, rotationalSpeed, 0.0f); +} + +// ELF 0x2C9280 +void HeliControl::keepPitchAt(Bot* bot, float dot, float maxInput, float maxSpeed, + const Vec3& rotationalSpeed, float feedForward) +{ + keepDotAt(bot, 0, dot, maxInput, maxSpeed, rotationalSpeed, feedForward); +} + +// ELF 0x2C92D0 +void HeliControl::keepDotAt(Bot* bot, int axis, float dot, float maxInput, float maxSpeed, + const Vec3& rotationalSpeed, float feedForward) +{ + static float maxDiff = 0.02f; + static float maxAngleSpeedDiff = 0.1f; + Information* information = informationManager->getInformation(bot->getCurrentEquipment()); + io::PlayerInput* input = bot->getInput(); + IPIControlInfo* controls = information->getControlInfo(); + const Mat4& transformation = information->getTransformation(); + const float currentDot = axis == 0 ? transformation.m[9] : transformation.m[1]; + const float speed = axis == 0 ? rotationalSpeed.x : rotationalSpeed.z; + float wantedSpeed = clampHeliInput((dot - currentDot) / maxDiff, -1.0f, 1.0f); + if (axis == 0) + wantedSpeed = -wantedSpeed; + float value = clampHeliInput(((wantedSpeed * maxSpeed - feedForward) - speed) / + maxAngleSpeedDiff, -1.0f, 1.0f) * maxInput; + if (axis == 2) + input->setInput(controls->getDriveRollControl(), -value); + else + input->setInput(controls->getDrivePitchControl(), value); +} + +// ELF 0x2C9450 +void HeliControl::limitSpeedTo(Bot* bot, float speed, float limit, float maxRotationSpeed, + const Vec3& rotationalSpeed) +{ + static float minPitch = 0.0f; + static float additional = 0.3f; + static float maxInput = 1.0f; + static float maxPitch = 0.5f; + if (limit > std::fabs(speed)) + return; + Information* information = informationManager->getInformation(bot->getCurrentEquipment()); + information->getTransformation(); + float factor = (std::fabs(speed) - limit) / 5.0f; + float sign = speed > 0.0f ? 1.0f : (speed < 0.0f ? -1.0f : 0.0f); + if (factor > 1.0f) + factor = 1.0f; + keepPitchAt(bot, factor * factor * (limit == 0.0f ? maxPitch : additional) * sign + minPitch, + maxInput, maxRotationSpeed, rotationalSpeed, 0.0f); +} + +// ELF 0x2C95D0 +float HeliControl::keepHeight(Bot* bot, float clearance, float minimumHeight, + const Vec3& rotationalSpeed) +{ + Information* information = informationManager->getInformation(bot->getCurrentEquipment()); + const Vec3& speed = information->getMobile()->getSpeed(); + const Mat4& transformation = information->getTransformation(); + (void)std::sqrt(speed.x * speed.x + speed.y * speed.y + speed.z * speed.z); + float highest = -999999.0f; + for (int i = 0; i < 5; ++i) + { + const float time = static_cast(i); + const Vec3 position = {speed.x * time + transformation.m[12], + speed.y * time + transformation.m[13], + speed.z * time + transformation.m[14]}; + const float height = AerialHeightMap::m_instance->getGroundHeight(position); + if (height > highest) + highest = height; + } + float height = clearance + highest; + if (!(height > minimumHeight)) + height = minimumHeight; + gotoHeight(bot, height, rotationalSpeed); + return height - transformation.m[13]; +} + +// ELF 0x2C9760 +int HeliControl::moveToPoint(Bot* bot, const Vec3& point, float height, const Vec3& acceleration) +{ + static float minAltitudeDiff = 5.0f; + static float maxAltitudeDiff = 15.0f; + static float maxDistanceForStrafe = 20.0f; + static float minDist = 5.0f; + static float speedAtMax = 5.0f; + static float speedAtMin = 3.0f; + static float maxSpeed = 35.0f; + static float altitudeFactorTweak = 0.9f; + static float maxSpeedDiff = 10.0f; + static float maxAcceleration = 15.0f; + static float maxAccelerationDiff = 6.0f; + static float maxDiff = 0.2f; + static float maxInput = 1.0f; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + io::PlayerInput* const input = bot->getInput(); + if (!info) + return false; + IPIMobile* const mobile = info->getMobile(); + const Vec3& speed = mobile->getSpeed(); + const Mat4& transform = info->getTransformation(); + IPIControlInfo* const controls = info->getControlInfo(); + const Vec3& position = info->getPosition(); + Vec3 direction = {point.x - position.x, 0.0f, point.z - position.z}; + const float distance = std::sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z); + if (distance < 0.001f) + direction = {0.0f, 0.0f, 1.0f}; + else + { + const float inverse = 1.0f / distance; + direction.x *= inverse; + direction.y *= inverse; + direction.z *= inverse; + } + const float altitude = AerialHeightMap::m_instance->getAltitude(info->getPosition()); + Mat4 inverseTransform = {{1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f}}; + inverseTransform.setInverse(transform); + Vec3 facing = info->getFaceing(); + facing.y = 0.0f; + vehiclecontrol::normalizeVec3(facing); + const float forwardAcceleration = facing.x * acceleration.x + facing.y * acceleration.y + facing.z * acceleration.z; + const float forwardSpeed = facing.x * speed.x + facing.y * speed.y + facing.z * speed.z; + const Vec3& rotation = mobile->getRotationalSpeed(); + const Vec3 localRotation = { + rotation.x * inverseTransform.m[0] + rotation.y * inverseTransform.m[4] + rotation.z * inverseTransform.m[8], + rotation.x * inverseTransform.m[1] + rotation.y * inverseTransform.m[5] + rotation.z * inverseTransform.m[9], + rotation.x * inverseTransform.m[2] + rotation.y * inverseTransform.m[6] + rotation.z * inverseTransform.m[10]}; + float groundHeight; + if (avoidCrash(bot, localRotation, groundHeight)) + return true; + const float clearanceHeight = height + groundHeight; + const float desiredHeight = clearanceHeight > point.y ? clearanceHeight : point.y; + gotoHeight(bot, desiredHeight, localRotation); + const float heightDifference = desiredHeight - transform.m[13]; + float altitudeFactor = 0.0f; + if (!(minAltitudeDiff > heightDifference)) + { + altitudeFactor = (heightDifference - minAltitudeDiff) / (maxAltitudeDiff - minAltitudeDiff); + if (altitudeFactor > 1.0f) + altitudeFactor = 1.0f; + } + if (maxDistanceForStrafe > distance && altitudeFactor < 0.1f) + { + float desiredSpeed = speedAtMin; + if (!(minDist > distance)) + desiredSpeed = ((distance - minDist) / (maxDistanceForStrafe - minDist)) * (speedAtMax - speedAtMin) + speedAtMin; + if (std::fabs(forwardSpeed) > desiredSpeed) + limitSpeedTo(bot, forwardSpeed, desiredSpeed, 0.3f, localRotation); + else + strafeTo(bot, point, localRotation); + return true; + } + float turn = 0.0f; + if (altitude > 5.0f) + turn = turnTowardsDirection(bot, direction, localRotation); + if (turn > 45.0f) + { + limitSpeedTo(bot, forwardSpeed, 5.0f, 0.3f, localRotation); + return true; + } + if (!(altitude > 5.0f)) + return true; + // [INFERRED] inline clamp expansion; unordered values pass through. + const auto clamp = [](float value, float low, float high) { + return low > value ? low : (value > high ? high : value); + }; + const float distanceFactor = distance / 50.0f < 1.0f ? distance / 50.0f : 1.0f; + const float desiredSpeed = distanceFactor * ((1.0f - altitudeFactor * altitudeFactorTweak) * maxSpeed); + const float speedFactor = clamp((desiredSpeed - forwardSpeed) / maxSpeedDiff, -1.0f, 1.0f); + const float accelerationFactor = clamp((speedFactor * maxAcceleration - forwardAcceleration) / maxAccelerationDiff, -0.1f, 1.0f); + const float pitchDifference = clamp(accelerationFactor * -0.4f - transform.m[9], -1.0f, 1.0f); + const float pitchFactor = clamp(pitchDifference / maxDiff, -1.0f, 1.0f); + const float damping = clamp(4.0f * localRotation.x, -1.2f, 1.2f); + const float pitchInput = clamp(pitchFactor * -maxInput - damping, -maxInput, maxInput); + input->setInput(controls->getDrivePitchControl(), pitchInput); + return true; +} + +// ELF 0x2C9F30 +bool HeliControl::avoidCrash(Bot* bot, const Vec3& rotationalSpeed, float& ground) +{ + static float tiltLimit = 0.2f; + static float safetyConstant = 0.08f; + static bool testAvoidCrash = false; + static float minDiffToTryToTurn = -10.0f; + static float roll = -0.2f; + static float maxInput = 0.5f; + static float maxRotSpeed = 0.5f; + static float maxDiff = 10.0f; + static float minValue = 0.1f; + static float addition = 0.3f; + static float speedLimit = 3.0f; + Information* information = informationManager->getInformation(bot->getCurrentEquipment()); + io::PlayerInput* input = bot->getInput(); + IPIMobile* mobile = information->getMobile(); + const Mat4& transformation = information->getTransformation(); + const Vec3& speed = mobile->getSpeed(); + IPIControlInfo* controls = information->getControlInfo(); + ground = -99999.0f; + const bool tilted = std::fabs(transformation.m[1]) > tiltLimit || + std::fabs(transformation.m[9]) > 0.6f; + const Vec3 facing = information->getFaceing(); + float forwardSpeed = facing.x * speed.x + facing.y * speed.y + facing.z * speed.z; + if (!(forwardSpeed > 4.0f)) + forwardSpeed = 4.0f; + float lowest = 999999.0f; + if (!tilted) + { + const Vec3 currentFacing = information->getFaceing(); + Vec3 direction = {currentFacing.x * forwardSpeed, currentFacing.y * forwardSpeed, + currentFacing.z * forwardSpeed}; + if (forwardSpeed > 0.00001f) + { + const float inverse = 1.0f / forwardSpeed; + direction.x *= inverse; + direction.y *= inverse; + direction.z *= inverse; + } + int count = static_cast((forwardSpeed * safetyConstant * forwardSpeed) / 15.0f) + 2; + if (count < 6) + count = 5; + for (int i = 0; i < count; ++i) + { + const float sample = static_cast(i); + const Vec3 position = {(direction.x * sample) * 15.0f + transformation.m[12], + (direction.y * sample) * 15.0f + transformation.m[13], + (direction.z * sample) * 15.0f + transformation.m[14]}; + const float altitude = AerialHeightMap::m_instance->getAltitude(position); + if (position.y - altitude > ground) + ground = position.y - altitude; + if (lowest > altitude) + lowest = altitude; + } + if (!(lowest < 5.0f && forwardSpeed > 4.0f) && !testAvoidCrash) + return false; + } + if (!(lowest < minDiffToTryToTurn) || tilted) + keepRollAt(bot, 0.0f, 1.0f, 0.5f, rotationalSpeed); + else + { + input->setInput(static_cast(0), 0.5f); + float sideClearance; + const bool right = avoidRight(bot, sideClearance); + keepRollAt(bot, right ? roll : -roll, maxInput, maxRotSpeed, rotationalSpeed); + if (sideClearance > -10.0f) + { + const float forward = speed.x * transformation.m[8] + speed.y * transformation.m[9] + + speed.z * transformation.m[10]; + limitSpeedTo(bot, forward, 5.0f, 0.3f, rotationalSpeed); + input->setInput(controls->getDriveThrottleControl(), 1.0f); + return true; + } + } + const float forward = speed.x * transformation.m[8] + speed.y * transformation.m[9] + + speed.z * transformation.m[10]; + float factor = 0.0f; + if (forward > 0.1f) + { + factor = std::fabs(forward) / maxDiff; + if (factor > 1.0f) + factor = 1.0f; + } + limitSpeedTo(bot, forward, speedLimit, factor * addition + minValue, rotationalSpeed); + if (transformation.m[9] > 0.0f) + input->setInput(controls->getDriveThrottleControl(), 1.0f); + return true; +} + +// ELF 0x2CA4B0 +bool avoidRight(Bot* bot, float& clearance) +{ + Information* information = informationManager->getInformation(bot->getCurrentEquipment()); + const Mat4& transformation = information->getTransformation(); + const Vec3 firstFacing = information->getFaceing(); + const Vec3 first = {firstFacing.x * 0.7f, firstFacing.y * 0.7f, firstFacing.z * 0.7f}; + const Mat4& firstTransformation = information->getTransformation(); + const Vec3 right = {0.1f * firstTransformation.m[0] + first.x, + 0.1f * firstTransformation.m[1] + first.y, + 0.1f * firstTransformation.m[2] + first.z}; + const Vec3 secondFacing = information->getFaceing(); + const Vec3 second = {secondFacing.x * 0.7f, secondFacing.y * 0.7f, secondFacing.z * 0.7f}; + const Mat4& secondTransformation = information->getTransformation(); + const Vec3 left = {second.x - 0.1f * secondTransformation.m[0], + second.y - 0.1f * secondTransformation.m[1], + second.z - 0.1f * secondTransformation.m[2]}; + // shipped defect: positive clearances cannot raise either minimum above its initial zero. + float minimumRight = 0.0f; + float minimumLeft = 0.0f; + float sumRight = 0.0f; + float sumLeft = 0.0f; + for (int i = 0; i < 12; ++i) + { + const float sample = static_cast(i); + const Vec3 position = {(right.x * sample) * 22.0f + transformation.m[12], + (right.y * sample) * 22.0f + transformation.m[13], + (right.z * sample) * 22.0f + transformation.m[14]}; + const float altitude = AerialHeightMap::m_instance->getAltitude(position); + sumRight += altitude; + if (minimumRight > altitude) + minimumRight = altitude; + } + for (int i = 0; i < 12; ++i) + { + const float sample = static_cast(i); + const Vec3 position = {(left.x * sample) * 22.0f + transformation.m[12], + (left.y * sample) * 22.0f + transformation.m[13], + (left.z * sample) * 22.0f + transformation.m[14]}; + const float altitude = AerialHeightMap::m_instance->getAltitude(position); + sumLeft += altitude; + if (minimumLeft > altitude) + minimumLeft = altitude; + } + clearance = sumRight > sumLeft ? minimumRight : minimumLeft; + return sumRight > sumLeft; +} + +// ELF 0x2CA7D0 +int HeliControl::aimAtDirection(Bot* bot, const Vec3& direction, float, float clearance, + const Vec3& acceleration, float feedForward) +{ + static float minDot = -0.6f; + static float maxDot = 0.35f; + static float maxAngleSpeed = 0.2f; + Information* information = informationManager->getInformation(bot->getCurrentEquipment()); + io::PlayerInput* input = bot->getInput(); + if (!information) + return 0; + IPIMobile* mobile = information->getMobile(); + const Mat4& transformation = information->getTransformation(); + Mat4 inverse = Mat4::getIdentity(); + inverse.setInverse(transformation); + const Vec3 rotationalSpeed = rotateHeliVector(inverse, mobile->getRotationalSpeed()); + float ground; + if (!avoidCrash(bot, rotationalSpeed, ground)) + { + gotoHeight(bot, ground + 10.0f, rotationalSpeed); + if (!(direction.y > minDot) || !(maxDot > direction.y)) + { + Vec3 forward = {transformation.m[8], 0.0f, transformation.m[10]}; + vehiclecontrol::normalizeVec3(forward); + const Vec3 target = {forward.x * 150.0f + transformation.m[12], + forward.y * 150.0f + transformation.m[13], + forward.z * 150.0f + transformation.m[14]}; + moveToPoint(bot, target, clearance, acceleration); + } + else + { + const float turn = turnTowardsDirection(bot, direction, rotationalSpeed); + if (turn < 10.0f && std::fabs(rotationalSpeed.y) < 0.1f) + keepPitchAt(bot, direction.y, 1.0f, maxAngleSpeed, rotationalSpeed, feedForward); + } + } + else + { + IPIControlInfo* controls = information->getControlInfo(); + if (transformation.m[9] > -0.15f && mobile->getSpeedMagnitude() > 2.0f) + input->setInput(controls->getDriveThrottleControl(), 1.0f); + } + return 1; +} + +// ELF 0x2CAC20 +float HeliControl::turnTowardsDirection(Bot* bot, const Vec3& direction, const Vec3& rotationalSpeed) +{ + static bool dontTurn = false; + static float maxAngleVelocity = 1.0f; + static float maxAngleVelocityDiff = 0.1f; + static float maxInput = 1.0f; + Information* information = informationManager->getInformation(bot->getCurrentEquipment()); + IPIControlInfo* controls = information->getControlInfo(); + io::PlayerInput* input = bot->getInput(); + if (dontTurn) + return 0.0f; + const Mat4& transformation = information->getTransformation(); + float z, x, yaw; + getRotationZXY(transformation, z, x, yaw); + if (yaw < 0.0f) + yaw += 360.0f; + Mat4 look = Mat4::getIdentity(); + const Vec3 up = {0.0f, 1.0f, 0.0f}; + const Vec3 target = {direction.x + transformation.m[12], direction.y + transformation.m[13], + direction.z + transformation.m[14]}; + const Vec3& position = *reinterpret_cast(&transformation.m[12]); + calcLookAtMatrix(look, position, target, up); + float targetZ, targetX, targetYaw; + getRotationZXY(look, targetZ, targetX, targetYaw); + if (targetYaw < 0.0f) + targetYaw += 360.0f; + float difference = targetYaw - yaw; + if (difference < -180.0f) + difference += 360.0f; + else if (difference > 180.0f) + difference -= 360.0f; + const float wantedSpeed = -clampHeliInput(difference / 30.0f, -1.0f, 1.0f) * maxAngleVelocity; + const float value = clampHeliInput((wantedSpeed - rotationalSpeed.y) / maxAngleVelocityDiff, + -1.0f, 1.0f); + const io::PlayerInputMap turnControl = controls->getDriveTurnControl(); + input->setInput(turnControl, value * maxInput); + return std::fabs(difference); +} + +// ELF 0x2CAF00 (Ghidra). Moving releases inputs 0, 2, 1 and 3; look 4 and 5; trigger 8, 31, +// 23..28, 14..16, 38, 37, 10, 32 and 47. Returns 1. +int HeliControl::resetControls(Bot* bot, bool move, bool look, bool trigger) +{ + io::PlayerInput* const input = bot->getInput(); + if (move) + { + input->setInput(static_cast(0), 0.0f); + input->setInput(static_cast(2), 0.0f); + input->setInput(static_cast(1), 0.0f); + input->setInput(static_cast(3), 0.0f); + } + if (look) + { + input->setInput(static_cast(4), 0.0f); + input->setInput(static_cast(5), 0.0f); + } + if (trigger) + { + input->setInput(static_cast(8), 0.0f); + input->setInput(static_cast(31), 0.0f); + input->setInput(static_cast(23), 0.0f); + input->setInput(static_cast(24), 0.0f); + input->setInput(static_cast(25), 0.0f); + input->setInput(static_cast(26), 0.0f); + input->setInput(static_cast(27), 0.0f); + input->setInput(static_cast(28), 0.0f); + input->setInput(static_cast(14), 0.0f); + input->setInput(static_cast(15), 0.0f); + input->setInput(static_cast(16), 0.0f); + input->setInput(static_cast(38), 0.0f); + input->setInput(static_cast(37), 0.0f); + input->setInput(static_cast(10), 0.0f); + input->setInput(static_cast(32), 0.0f); + input->setInput(static_cast(47), 0.0f); + } + return 1; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/HeliControl.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/HeliControl.h new file mode 100644 index 000000000..26e25e3e5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/HeliControl.h @@ -0,0 +1,38 @@ +// Helicopter controls. Rotational-speed arguments use the vehicle's local axes; movement and +// acceleration arguments use world coordinates. Most helpers require valid current equipment. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_HELICONTROL_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_HELICONTROL_H + +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// [INFERRED] a namespace: no vtable, no constructor, and the first argument is never `this`. +namespace HeliControl +{ + void quickyMoveForward(Bot*, float, const Vec3&); // 0x2C8A80; [INFERRED] ELF void + int gotoHeight(Bot*, float, const Vec3&); // 0x2C8D00; [INFERRED] ELF int + void strafeTo(Bot*, const Vec3&, const Vec3&); // 0x2C9060; [INFERRED] ELF void + void keepRollAt(Bot*, float, float, float, const Vec3&); // 0x2C9220; [INFERRED] ELF void + void keepPitchAt(Bot*, float, float, float, const Vec3&, float); // 0x2C9280; [INFERRED] ELF void + void keepDotAt(Bot*, int, float, float, float, const Vec3&, float); // 0x2C92D0; [INFERRED] ELF void + void limitSpeedTo(Bot*, float, float, float, const Vec3&); // 0x2C9450; [INFERRED] ELF void + float keepHeight(Bot*, float, float, const Vec3&); // 0x2C95D0; [INFERRED] ELF float + int moveToPoint(Bot*, const Vec3&, float, const Vec3&); // 0x2C9760; [INFERRED] ELF int + bool avoidCrash(Bot*, const Vec3&, float&); // 0x2C9F30; [INFERRED] ELF int, callers {'bool': 2} + int aimAtDirection(Bot*, const Vec3&, float, float, const Vec3&, float); // 0x2CA7D0; [INFERRED] ELF int + float turnTowardsDirection(Bot*, const Vec3&, const Vec3&); // 0x2CAC20; [INFERRED] ELF float + int resetControls(Bot*, bool, bool, bool); // 0x2CAF00; [INFERRED] ELF int +} + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_HELICONTROL_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/InfanteryControl.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/InfanteryControl.cpp new file mode 100644 index 000000000..246ae5ccb --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/InfanteryControl.cpp @@ -0,0 +1,495 @@ +// InfanteryControl (attested TU `AI/AIDLL/AI/AIPlanInterpreter/InfanteryControl.cpp`, the path of +// infanteryPose's Debug). Recovered from libaidll.so (Linux 1.5.3153, ia-32); every body carries its +// ELF address. Read in Intel syntax (no x87 operand swap) and checked against the Ghidra +// decompilation. Parameter and local names are [INFERRED]. +// +// Input writes: the image calls Input::setInput(index, float) out of line at +// most sites and inlines it at a few (removeZoom's release); both are the same function here. + +// static init: ELF 0x2CCE30 (__tcf_0 0x2CCE90, _GLOBAL__I 0x2CCEC0): 's Init object only. +#include + +#include "../AIBot/SensingAgent.h" +#include "InfanteryControl.h" + +#include +#include +#include + +#include "../Main/AIDllFrontier.h" +#include "../Main/IAIPathfinding.h" +#include "../Main/IBotManager.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotNavigation.h" +#include "../AIBot/SquadMember.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../../../../Core/Debug.h" +#include "../../../../IO/Input/PlayerInput.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace infantry_detail { + +float inputValue(const io::PlayerInput* input, io::PlayerInputMap index) +{ + const int i = static_cast(index); + if (i > 63) + return 0.0f; + if (!((input->mappingFlags >> (static_cast(i) & 0x3F)) & 1ULL)) + return 0.0f; + return input->inputs[i]; +} + +// [CHOSEN, not recovered] the image writes SensingAgent +0x50 (the move direction) and stores 0.0 +// at +0x7C (a double) inline (EntryInfanteryMoveTo 0x2B7CF7 `fstpl 0x7c(%eax)`, 0x2B7CFA/0x2B7CFD). +// The +0x7C store is SensingAgent::setOverrideTime (ai-bot). +void setSensingMoveDirection(SensingAgent* agent, const Vec2& direction) +{ + agent->setOverrideTime(0.0); + agent->setMoveDirection(direction); +} + +void normaliseInline(Vec3& v) +{ + const float lengthSqr = v.x * v.x + v.y * v.y + v.z * v.z; + if (!(1.1920929e-07f <= std::fabs(lengthSqr - 1.0f))) + return; + if (!(1.1920929e-07f <= std::fabs(lengthSqr))) + { + v.x = v.y = v.z = 0.0f; + return; + } + const float inverse = 1.0f / std::sqrt(lengthSqr); + v.x = v.x * inverse; + v.y = v.y * inverse; + v.z = inverse * v.z; +} + +Vec3 crossInline(const Vec3& a, const Vec3& b) +{ + Vec3 r; + r.x = a.y * b.z - a.z * b.y; + r.y = a.z * b.x - b.z * a.x; + r.z = b.y * a.x - b.x * a.y; + return r; +} + +} // namespace infantry_detail + +namespace { + +using infantry_detail::inputValue; + +inline Information* lookupInformation(unsigned int handle) +{ + return informationManager->getInformation(handle); +} + +// The inline zero test the image applies to trace results (|c - 0| <= FLT_EPSILON for x, y, z). +inline bool isZeroVec(const Vec3& v) +{ + const float eps = 1.1920929e-07f; + return std::fabs(v.x - 0.0f) <= eps && std::fabs(v.y - 0.0f) <= eps && std::fabs(v.z - 0.0f) <= eps; +} + +inline float distance(const Vec3& a, const Vec3& b) +{ + const float dx = a.x - b.x; + const float dy = a.y - b.y; + const float dz = a.z - b.z; + return std::sqrt(dx * dx + dy * dy + dz * dz); +} + +} // namespace + +// ELF 0x2CB200 +void removeZoom(Bot* bot) +{ + Information* info = lookupInformation(bot->getCurrentEquipment()); + IPIArmament* armament = info->getArmament(); + if (armament == 0) + return; + // [INFERRED] the image queries the active weapon twice and drops the first result. + const unsigned int unusedWeapon = armament->getWeapon(armament->getActiveWeapon()); + (void)unusedWeapon; + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + if (weapon == 0) + return; + if (weapon->getWeaponZoom() == io::PINone) + return; + + if (!weapon->isZoomed()) + { + bot->getInput()->setInput(static_cast(weapon->getWeaponZoom()), 0.0f); + return; + } + io::PlayerInput* input = bot->getInput(); + if (inputValue(input, static_cast(weapon->getWeaponZoom())) != 0.0f) + { + // the zoom key is held: release it (inlined setInput in the image, ELF 0x2CB3xx) + input->setInput(static_cast(weapon->getWeaponZoom()), 0.0f); + return; + } + // press it once to leave zoom + bot->getInput()->setInput(static_cast(weapon->getWeaponZoom()), 1.0f); +} + +// ELF 0x2CB550 +void infanteryControlThrottle(Bot* bot, io::PlayerInput* input, IPIControlInfo*, float maxSpeed, bool sprint) +{ + if (static_cast(bot)->getBotIsSimulatingArtillery()) // BotMain +0x234 + { + bot->getBotNavigation()->clearProgress(); + bot->requestSoldierPose(SPCrouching, true); + return; + } + const float squadSpeed = bot->getSquadMember()->getMaxSpeed(); // 0x2CB5D1 + if (sprint) + { + float throttle; + if (maxSpeed <= 0.0f) + throttle = (maxSpeed < 0.0f) ? -1.0f : 0.0f; + else + throttle = 1.0f; + input->setInput(io::PIThrottle, throttle); + input->setInput(io::PISprint, 1.0f); + } + else + { + input->setInput(io::PIThrottle, squadSpeed / maxSpeed); + input->setInput(io::PISprint, 0.0f); + } +} + +// ELF 0x2CB660 +bool infanteryResetControls(Bot* bot, io::PlayerInput* input, bool movement, bool look, bool weapons) +{ + if (movement) + { + input->setInput(io::PIAction, 0.0f); + input->setInput(io::PISprint, 0.0f); + input->setInput(io::PIYaw, 0.0f); + input->setInput(io::PIRoll, 0.0f); + input->setInput(io::PIPitch, 0.0f); + input->setInput(io::PIThrottle, 0.0f); + input->setInput(io::PIMouseLookX, 0.0f); + input->setInput(io::PIMouseLookY, 0.0f); + } + if (look) + { + // level the view: look down by the forward vector's height (transformation row 2, y) + Information* info = lookupInformation(bot->getCurrentEquipment()); + const Mat4& transformation = info->getTransformation(); + input->setInput(io::PIMouseLookX, 0.0f); + input->setInput(io::PIMouseLookY, -transformation.m[9]); + } + if (weapons) + { + input->setInput(io::PIFire, 0.0f); + input->setInput(io::PIAltFire, 0.0f); + input->setInput(io::PIWeaponSelect1, 0.0f); + input->setInput(io::PIWeaponSelect2, 0.0f); + input->setInput(io::PIWeaponSelect3, 0.0f); + input->setInput(io::PIWeaponSelect4, 0.0f); + input->setInput(io::PIWeaponSelect5, 0.0f); + input->setInput(io::PIWeaponSelect6, 0.0f); + input->setInput(io::PIWeaponSelect7, 0.0f); + input->setInput(io::PIWeaponSelect8, 0.0f); + input->setInput(io::PIPositionSelect1, 0.0f); + input->setInput(io::PIPositionSelect2, 0.0f); + input->setInput(io::PIPositionSelect3, 0.0f); + input->setInput(io::PIPositionSelect4, 0.0f); + input->setInput(io::PIPositionSelect5, 0.0f); + input->setInput(io::PIPositionSelect6, 0.0f); + input->setInput(io::PIPositionSelect7, 0.0f); + input->setInput(io::PIPositionSelect8, 0.0f); + input->setInput(io::PIUse, 0.0f); + input->setInput(io::PIReload, 0.0f); + input->setInput(io::PIFlareFire, 0.0f); + } + return true; +} + +// ELF 0x2CB9B0. PICrouch and PILie are toggles: the table presses the one that leads from the +// current to the wanted pose (and nothing when they are equal). +int infanteryPose(io::PlayerInput* input, SoldierPose current, SoldierPose wanted) +{ + int line; + switch (current) + { + case SPCrouching: + if (wanted == SPCrouching) + goto none; + if (wanted == SPStanding) + goto crouch; + if (wanted == SPLying) + goto lie; + line = 263; + break; + case SPStanding: + if (wanted == SPCrouching) + goto crouch; + if (wanted == SPStanding) + goto none; + if (wanted == SPLying) + goto lie; + line = 243; + break; + case SPLying: + if (wanted == SPCrouching) + goto crouch; + if (wanted == SPStanding) + goto lie; + if (wanted == SPLying) + goto none; + line = 283; + break; + default: + line = 288; + break; + } + Debug(DebugTypeError, "AI/AIDLL/AI/AIPlanInterpreter/InfanteryControl.cpp", line, "") + << "Internal error, unknown pose."; + return 0; + +none: + input->setInput(io::PICrouch, 0.0f); + input->setInput(io::PILie, 0.0f); + return 1; +crouch: + input->setInput(io::PICrouch, 1.0f); + input->setInput(io::PILie, 0.0f); + return 1; +lie: + input->setInput(io::PICrouch, 0.0f); + input->setInput(io::PILie, 1.0f); + return 1; +} + +// ELF 0x2CBC90 +bool needsUpdate(const Vec2& point, unsigned int handle, float radius) +{ + Information* info = lookupInformation(handle); + if (info == 0) + return false; + Vec2 position; + position.x = 0.0f; + position.y = 0.0f; + vec3ToVec2XZ(info->getPosition(), position); + const float distSqr = (point.y - position.y) * (point.y - position.y) + + (point.x - position.x) * (point.x - position.x); + return distSqr < radius * radius || (radius + 1.5f) * (radius + 1.5f) < distSqr; +} + +// ELF 0x2CBD70. Picks the nearest obstacle in front of the bot on the way to `target` (from the +// navigation's obstacle list: physical objects that are mobile or flagged 0x2000000, within 2 m of +// the bot's height and inside their radius + 1 of the path) and returns in `avoidPos` a point beside +// it: the obstacle position moved along the path normal by at most its radius, to the side where a +// pathfinding trace (15 m each way from the obstacle) has room. The obstacle's handle, position, +// radius and "damaged" state (flag 0x2000000 or health under the bail value) are returned through +// the other references; repair and change targets are never treated as damaged. +// Returns false in every normal case (also when there is no obstacle); true only when the obstacle +// stands on no valid pathfinding position (a retail quirk the callers rely on). +bool updateInfantryMoveToPosWithObstacles(Bot* bot, const Vec2& target, const Vec3&, unsigned int targetHandle, + Vec2& avoidPos, unsigned int& obstacleHandle, float& avoidOffset, + Vec2& obstaclePos, float& obstacleRadius, bool& obstacleDamaged, + Information* ignored, bool includeIgnored) +{ + Information* botInfo = lookupInformation(bot->getCurrentEquipment()); + BotNavigation* navigation = bot->getBotNavigation(); + float bestAlong = 99999.0f; + Vec2 closest; + closest.x = 0.0f; + closest.y = 0.0f; + const Vec3& botPos3 = botInfo->getPosition(); + Vec2 botPos; + botPos.x = 0.0f; + botPos.y = 0.0f; + vec3ToVec2XZ(botPos3, botPos); + Vec2 dir; + dir.x = target.x - botPos.x; + dir.y = target.y - botPos.y; + const float length = std::sqrt(dir.y * dir.y + dir.x * dir.x); + if (length < 0.0001f) + return false; + dir.x = dir.x * (1.0f / length); + dir.y = (1.0f / length) * dir.y; + Vec2 normal; + normal.x = 0.0f; + normal.y = 0.0f; + getNormal(dir, normal); + + IPIMobile* bestMobile = 0; + Information* targetInfo = lookupInformation(targetHandle); + Vec3 bestPos3; + bestPos3.x = 0.0f; + bestPos3.y = 0.0f; + bestPos3.z = 0.0f; + if (targetInfo != 0 && !targetInfo->isPrimary()) + targetInfo->getPrimaryObject(bot->getSide()); // retail: the result is dropped + avoidOffset = 0.0f; + + unsigned int changeTarget = bot->getChangeTarget(); + Information* changeInfo = lookupInformation(changeTarget); + if (changeInfo != 0 && !changeInfo->isPrimary()) + changeTarget = changeInfo->getPrimaryObject(bot->getSide()); + unsigned int repairTarget = bot->getRepairTarget(); + Information* repairInfo = lookupInformation(repairTarget); + if (repairInfo != 0 && !repairInfo->isPrimary()) + repairTarget = repairInfo->getPrimaryObject(bot->getSide()); + + const std::vector& obstacles = navigation->getObstacles(); // 0x2CBE2E: BotNavigation +0x58 + for (unsigned int i = 0; i < obstacles.size(); ++i) + { + Information* info = lookupInformation(obstacles[i]); + if (info == botInfo) + continue; + if (!(info != ignored || includeIgnored) || info == 0) + continue; + IPIPhysical* physical = info->getPhysical(); + if (physical == 0 || info->isOfType(ITSoldier)) + continue; + IPIMobile* mobile = info->getMobile(); + if (mobile == 0 && !info->isOfType(ITObstacle)) + continue; + + bool isTarget = false; + if (obstacles[i] == repairTarget || obstacles[i] == changeTarget) + isTarget = true; + const float health = physical->getHealth(); + bool damaged = false; + if (info->isOfType(ITObstacle) || health < IBotManager::instance->getVehicleBailValue()) + damaged = true; + float radius; + if (!damaged || isTarget) + { + radius = physical->getSmallestRadius(); + } + else + { + const float smallest = physical->getSmallestRadius(); + float grown = physical->getSmallestRadius() + 4.0f; + if (10.0f < grown) + grown = 10.0f; + if (grown <= smallest) + grown = smallest; + radius = grown * 1.3f; + } + + if (!(std::fabs(info->getPosition().y - botPos3.y) <= 2.0f)) + continue; + Vec2 pos; + pos.x = 0.0f; + pos.y = 0.0f; + vec3ToVec2XZ(info->getPosition(), pos); + const float rx = pos.x - botPos.x; + const float ry = pos.y - botPos.y; + const float distSqr = rx * rx + ry * ry; + const float along = rx * dir.x + ry * dir.y; + if (!(distSqr <= (radius + 1.0f) * (radius + 1.0f))) + continue; + if (!(0.1f <= along / std::sqrt(distSqr))) + continue; + if (radius + 1.0f <= std::fabs(rx * normal.x + ry * normal.y)) + continue; + if (bestAlong <= along) + continue; + closest = pos; + obstacleRadius = radius; + bestPos3 = info->getPosition(); + obstacleHandle = obstacles[i]; + obstaclePos = pos; + obstacleDamaged = damaged; + bestMobile = mobile; + bestAlong = along; + } + if (99999.0f <= bestAlong) + return false; + + const int vehicleNumber = botInfo->getMobile()->getVehicleNumber(); + bot->getBotNavigation(); // retail: called and dropped + const int equipmentType = botInfo->getUnit()->getEquipmentType(); + Vec3 hitBack; + hitBack.x = hitBack.y = hitBack.z = 0.0f; + Vec3 hitFront; + hitFront.x = hitFront.y = hitFront.z = 0.0f; + Vec3 normal3; + normal3.x = normal3.y = normal3.z = 0.0f; + vec2ToVec3XZ(normal, normal3); + IAIPathfinding* pathfinding = IAIPathfinding::instance; + unsigned int polygon; // trace output, unused + float frontDist; + if (bestMobile == 0) + { + if (!pathfinding->isValidPosition(vehicleNumber, equipmentType, bestPos3, true)) + return true; + Vec3 to; + to.x = normal3.x * 15.0f + bestPos3.x; + to.y = normal3.y * 15.0f + bestPos3.y; + to.z = normal3.z * 15.0f + bestPos3.z; + pathfinding->trace(vehicleNumber, bestPos3, to, hitFront, polygon, equipmentType, -1, 0.0f, 0, 0); + frontDist = isZeroVec(hitFront) ? 0.0f : distance(hitFront, bestPos3); + to.x = bestPos3.x - normal3.x * 15.0f; + to.y = bestPos3.y - normal3.y * 15.0f; + to.z = bestPos3.z - normal3.z * 15.0f; + pathfinding->trace(vehicleNumber, bestPos3, to, hitBack, polygon, equipmentType, -1, 0.0f, 0, 0); + } + else + { + const IPIMobile::ValidPos& valid = bestMobile->getLastValidPosition(vehicleNumber); + Vec3 to; + to.x = normal3.x * 15.0f + valid.position.x; + to.y = normal3.y * 15.0f + valid.position.y; + to.z = normal3.z * 15.0f + valid.position.z; + pathfinding->trace(valid.polygon, valid.island, vehicleNumber, valid.position, to, hitFront, polygon, + equipmentType, -1, 0.0f, 0, 0); + // retail: measured from the obstacle's position, not from the valid position traced from + frontDist = isZeroVec(hitFront) ? 0.0f : distance(hitFront, bestPos3); + to.x = valid.position.x - normal3.x * 15.0f; + to.y = valid.position.y - normal3.y * 15.0f; + to.z = valid.position.z - normal3.z * 15.0f; + pathfinding->trace(valid.polygon, valid.island, vehicleNumber, valid.position, to, hitBack, polygon, + equipmentType, -1, 0.0f, 0, 0); + } + const float backDist = isZeroVec(hitBack) ? 0.0f : distance(hitBack, bestPos3); + + avoidPos = closest; + bool goBack; + float room = frontDist; + float radius; + if ((closest.y - botPos.y) * normal.y + (closest.x - botPos.x) * normal.x <= 0.0f) + { + radius = obstacleRadius; + goBack = !(radius + 1.0f < frontDist || backDist < frontDist); + } + else + { + radius = obstacleRadius; + goBack = !(backDist <= radius + 1.0f && backDist <= frontDist); + } + if (goBack) + room = backDist; + float offset = radius; + if (room < offset) + offset = room; + const float signedOffset = goBack ? -offset : offset; + avoidPos.x = normal.x * signedOffset + avoidPos.x; + avoidPos.y = signedOffset * normal.y + avoidPos.y; + avoidOffset = offset; + return false; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/InfanteryControl.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/InfanteryControl.h new file mode 100644 index 000000000..718bc01f6 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/InfanteryControl.h @@ -0,0 +1,67 @@ +// InfanteryControl: the soldier input helpers of the infantry plan-interpreter entries +// (attested TU `AI/AIDLL/AI/AIPlanInterpreter/InfanteryControl.cpp`). Package B +// (docs/macos-ai-behaviour-plan.md). Signatures from the mangled ELF names; return types checked +// against the bodies and their callers. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_INFANTERYCONTROL_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_INFANTERYCONTROL_H + +#include "../../../AIInterface/BFKnowledge/SoldierPose.h" +#include "../../../../Math/Vec3.h" +#include "../../../../IO/Input/Input.h" + +namespace dice { +namespace hfe { +struct Mat4; +namespace io { class PlayerInput; } +namespace ai { + +class Bot; +class BAPAMoveTo; +class IPIControlInfo; +class IPIMobile; +class IPIPhysical; +class Information; +class SensingAgent; + +// Presses or releases the zoom input so that the bot's active weapon leaves zoom. +void removeZoom(Bot*); // 0x2CB200 +// Throttle (and sprint) for a soldier whose own top speed is maxSpeed; `sprint` comes from +// BAPAMoveTo::getIsSprinting. +void infanteryControlThrottle(Bot*, io::PlayerInput*, IPIControlInfo*, float maxSpeed, bool sprint); // 0x2CB550 +// Releases the movement inputs (`movement`), levels the look (`look`) and releases the fire, +// weapon-select and use inputs (`weapons`). Always true; the callers store it into their ok flag. +bool infanteryResetControls(Bot*, io::PlayerInput*, bool movement, bool look, bool weapons); // 0x2CB660 +// Presses PICrouch / PILie to go from `current` to `wanted`. 0 only after an unknown pose (an +// Error Debug, which aborts). +int infanteryPose(io::PlayerInput*, SoldierPose current, SoldierPose wanted); // 0x2CB9B0 +// True when the object `handle` left the ring [radius, radius + 1.5] around `point`. +bool needsUpdate(const Vec2& point, unsigned int handle, float radius); // 0x2CBC90 +bool updateInfantryMoveToPosWithObstacles(Bot*, const Vec2&, const Vec3&, unsigned int, Vec2&, unsigned int&, float&, Vec2&, float&, bool&, Information*, bool); // 0x2CBD70 + +namespace infantry_detail { + +// [INFERRED] The image expands an inline input reader at every site (`[input+0x100/0x104]`, +// shrd, `test 1`, then `fld [input+4*i]`): the value when the input is mapped, else 0. Indices +// above 63 read 0 (`cmp idx,0x3f; jg`). The Input template in IO/ has no such member, so the +// reader lives here. +float inputValue(const io::PlayerInput* input, io::PlayerInputMap index); + +// [INFERRED] The inline Vec3 normalise the entries expand: unchanged when |v|^2 is within +// FLT_EPSILON of 1, zeroed when |v|^2 is within FLT_EPSILON of 0, else scaled by 1/|v|. +void normaliseInline(Vec3& v); +// a x b, component order as the image computes it +Vec3 crossInline(const Vec3& a, const Vec3& b); + +// [CHOSEN, not recovered] Bridge to the SensingAgent move direction: the move entries store the +// direction inline at SensingAgent +0x50 (Vec2) and zero the double at +0x7C (both private in +// AIBot/SensingAgent.h). Stops by name until ai-bot adds the writer. +void setSensingMoveDirection(SensingAgent* agent, const Vec2& direction); + +} // namespace infantry_detail + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_INFANTERYCONTROL_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/MouseControl.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/MouseControl.cpp new file mode 100644 index 000000000..2a1168990 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/MouseControl.cpp @@ -0,0 +1,195 @@ +// MouseControl (attested TU `AI/AIDLL/AI/AIPlanInterpreter/MouseControl.cpp`, FILE symbol and +// static initialiser beside 0x2CCEE0). Recovered from libaidll.so (Linux 1.5.3153, ia-32), read in +// Intel syntax and checked against the Ghidra decompilation. Parameter names are [INFERRED]. + +// static init: ELF 0x2CDA50 (__tcf_0 0x2CDAB0, _GLOBAL__I 0x2CDAE0): 's Init object only. +#include + +#include "MouseControl.h" + +#include + +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "InfanteryControl.h" +#include "../../../../IO/Input/PlayerInput.h" +#include "../../../../Math/Vec3.h" +#include "../../../../Math/Mat4.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// The image's inline clamp (`fld -1; fucomi; ... fcmov`); NaN gives -1. The image clamps the +// direction cosines twice, which is the same value. +inline float clampUnit(float v) +{ + if (!(-1.0f <= v)) + return -1.0f; + if (1.0f < v) + return 1.0f; + return v; +} + +inline float signOf(float v) +{ + if (v <= 0.0f) + return (v < 0.0f) ? -1.0f : 0.0f; + return 1.0f; +} + +// sign of the target speed: NaN counts as positive here (`fld 1; ... p <= 0`), as in the image +inline float speedSign(float v) +{ + if (v <= 0.0f) + return (v < 0.0f) ? -1.0f : 0.0f; + return 1.0f; +} + +} // namespace + +// ELF 0x2CCEE0. Drives the mouse-look inputs so that the camera `camera` turns towards the unit +// direction `dir`. The pitch and yaw errors (radians, from the camera's up and right rows) are +// returned through pitchError/yawError; the previous frame's errors give the derivative term, and +// the target's own angular speeds (targetYawSpeed, targetPitchSpeed) add a feed-forward term that is +// halved when the target moves the same way as the error. With useAllowedDeviation (never set in +// this build) errors below allowedDeviation give no input. The vertical output is damped by bot +// skill; both are kept above minInput and inside the per-axis limits, which grow with bot skill. +// Soldiers (object flag 0x200000) look at full speed vertically and, while idle without a firing +// target, use a softer horizontal gain (newP) and limit (1.5). +void mouseControlLookAtDirection(Bot* bot, const Vec3& dir, const Mat4& camera, float& pitchError, float lastPitchError, + float& yawError, float lastYawError, float allowedDeviation, + IPIControlInfo* controlInfo, io::PlayerInput* input, + float pitchBias, float targetYawSpeed, float targetPitchSpeed) +{ + // function-local tuning statics (.data, never written in this build) + static float maxYInputNew = 2.0f; // ELF 0x4BDD14 + static float tweak = 0.05f; // ELF 0x4BDD18 + static float minInput = 0.01f; // ELF 0x4BDD1C + static bool useAllowedDeviation = false; // ELF 0x4CE5E5 (.bss) + + const float x = dir.x; + const float y = dir.y; + const float z = dir.z; + const float upCos = clampUnit(camera.m[6] * z + camera.m[5] * y + camera.m[4] * x); + const float rightCos = clampUnit(camera.m[2] * z + camera.m[1] * y + camera.m[0] * x); + const float forwardCos = clampUnit(z * camera.m[10] + camera.m[8] * x + y * camera.m[9]); + + pitchError = -(std::acos(clampUnit(upCos)) - 1.57079637f); + const float rightAngle = std::acos(clampUnit(rightCos)); + yawError = rightAngle; + if (forwardCos < 0.0f) + { + if (rightCos < 0.0f) + yawError = 4.71238899f - rightAngle; + else + yawError = -(rightAngle + 1.57079637f); + } + else + { + yawError = rightAngle - 1.57079637f; + } + + const float proportional = controlInfo->getProportionalConstant(); + float horizontalP = proportional; + const float derivative = controlInfo->getDerivativeConstant(); + const float angleSpeed = controlInfo->getAngleSpeedConstant(); + + float maxY = 4.0f; + float maxX; + Information* info = informationManager->getInformation(bot->getCurrentEquipment()); + const float skill = static_cast(CommonSingletonServer::m_iaiSettings)->getBotSkill(); + if (info == 0 || !info->isOfType(ITSoldier)) + { + static float maxXInputNew = 1.0f; // ELF 0x4BDD10 + maxY = (4.0f - maxYInputNew) * skill + maxYInputNew; + maxX = (4.0f - maxXInputNew) * skill + maxXInputNew; + } + else if (bot->getFiringTarget() == static_cast(-1) + && infantry_detail::inputValue(input, io::PIThrottle) == 0.0f + && infantry_detail::inputValue(input, io::PISprint) == 0.0f + && infantry_detail::inputValue(input, io::PIYaw) == 0.0f) + { + static float newP = -3.0f; // ELF 0x4BDD04 + static float maxXInputNew = 1.5f; // ELF 0x4BDD08 + horizontalP = newP; + maxX = maxXInputNew; + } + else if (infantry_detail::inputValue(input, io::PISprint) != 0.0f) + { + maxX = maxY; + } + else + { + static float maxXInputNew = 1.0f; // ELF 0x4BDD0C + maxX = (4.0f - maxXInputNew) * skill + maxXInputNew; + } + + // vertical + float feedForward = angleSpeed * targetPitchSpeed; + if (signOf(pitchError) == speedSign(targetPitchSpeed)) + feedForward = feedForward * 0.5f; + float bias = 0.0f; + if (pitchBias < -0.0001f) + { + const float t = pitchBias / -tweak; + bias = 0.75f; + if (t < 0.75f) + bias = t; + } + float vertical = proportional * pitchError + (pitchError - lastPitchError) * derivative + feedForward + bias; + if (!useAllowedDeviation || allowedDeviation <= std::fabs(pitchError)) + { + if (4.0f < std::fabs(vertical)) + vertical = 4.0f * signOf(vertical); + } + else + { + vertical = 0.0f; + } + vertical = vertical * (1.0f - skill * 0.5f) * 0.5f; + if (std::fabs(vertical) < minInput && vertical != 0.0f) + vertical = signOf(vertical) * minInput; + float verticalInput = -maxY; + if (-maxY <= vertical) + { + if (maxY < vertical) + vertical = maxY; + verticalInput = vertical; + } + // inlined setInput in the image (range diagnostic, then the mapped-bit store) + input->setInput(controlInfo->getLookVerticalControl(), verticalInput); + + // horizontal + float yawFeedForward = angleSpeed * targetYawSpeed; + if (signOf(yawError) == speedSign(targetYawSpeed)) + yawFeedForward = yawFeedForward * 0.5f; + const float horizontalRaw = horizontalP * yawError + (yawError - lastYawError) * derivative + yawFeedForward; + float horizontal = 0.0f; + if (!useAllowedDeviation || allowedDeviation <= std::fabs(yawError)) + { + horizontal = horizontalRaw; + if (4.0f < std::fabs(horizontalRaw)) + horizontal = signOf(horizontalRaw) * 4.0f; + } + if (std::fabs(horizontal) < minInput && horizontal != 0.0f) + horizontal = signOf(horizontal) * minInput; + float horizontalInput = -maxX; + if (-maxX <= horizontal) + { + horizontalInput = horizontal; + if (maxX < horizontal) + horizontalInput = maxX; + } + input->setInput(controlInfo->getLookHorizontalControl(), horizontalInput); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/MouseControl.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/MouseControl.h new file mode 100644 index 000000000..16a9fa74f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/MouseControl.h @@ -0,0 +1,32 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_MOUSECONTROL_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_MOUSECONTROL_H + +#include "../../../AIInterface/BFKnowledge/SoldierPose.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +struct Mat4; +namespace io { class PlayerInput; } +namespace ai { + +class Bot; +class BAPAMoveTo; +class IPIControlInfo; +class IPIMobile; +class IPIPhysical; +class Information; + +void mouseControlLookAtDirection(Bot*, const Vec3&, const Mat4&, float&, float, float&, float, float, IPIControlInfo*, io::PlayerInput*, float, float, float); // 0x2CCEE0; [INFERRED] ELF void + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_MOUSECONTROL_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PlanInterpreter.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PlanInterpreter.h new file mode 100644 index 000000000..18246b2aa --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PlanInterpreter.h @@ -0,0 +1,35 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_PLANINTERPRETER_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_PLANINTERPRETER_H + + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// Interpreter interface. Vtable 0x4BCA60: D1, D0, execute (pure). Inline in the image. +// ELF: vtable 0x4BCA60 (3 words), package S0-skeleton. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class PlanInterpreter +{ +public: + virtual ~PlanInterpreter() {} // weak in the image (inline) + + virtual bool execute(BotScript*, Bot*, bool& ok, bool& finished) = 0; // no body, slot +0x08; from the base declaration +}; + + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_PLANINTERPRETER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PlaneControl.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PlaneControl.cpp new file mode 100644 index 000000000..ade1c2c8b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PlaneControl.cpp @@ -0,0 +1,451 @@ +// Fixed-wing flight and attitude controls, recovered from libaidll.so. + +// static init: ELF 0x2D0700 (__tcf_0 0x2D0760, _GLOBAL__I 0x2D0790): 's Init object only. +#include + +#include "PlaneControl.h" + +#include "ControlFunctions.h" +#include "VehicleControlInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIPathFinding/AerialHeightMap/AerialHeightMap.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" +#include "../../../../IO/Input/PlayerInput.h" +#include "../../../../Math/Mat4.h" +#include +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { +// [CHOSEN, not recovered] Local packaging of the inline vector/scalar operations in +// ELF 0x2CDB00, 0x2CE3C0, 0x2CE6D0 and 0x2CF9F0. +float clampPlane(float value, float minimum, float maximum) +{ + return value < minimum ? minimum : (value > maximum ? maximum : value); +} + +float planeSign(float value) +{ + return value > 0.0f ? 1.0f : (value < 0.0f ? -1.0f : 0.0f); +} + +float dotPlane(const Vec3& a, const Vec3& b) +{ + return a.x * b.x + a.y * b.y + a.z * b.z; +} + +Vec3 crossPlane(const Vec3& a, const Vec3& b) +{ + return Vec3{a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x}; +} + +Vec3 rotatePlane(const Mat4& matrix, const Vec3& value) +{ + return Vec3{matrix.m[0] * value.x + matrix.m[4] * value.y + matrix.m[8] * value.z, + matrix.m[1] * value.x + matrix.m[5] * value.y + matrix.m[9] * value.z, + matrix.m[2] * value.x + matrix.m[6] * value.y + matrix.m[10] * value.z}; +} + +Mat4 planeIdentity() +{ + Mat4 matrix = {}; + matrix.m[0] = matrix.m[5] = matrix.m[10] = matrix.m[15] = 1.0f; + return matrix; +} + +float planeMappedInput(io::PlayerInput* input, io::PlayerInputMap control) +{ + const int index = static_cast(control); + if (index < 64 && ((input->mappingFlags >> (static_cast(index) & 63)) & 1ULL)) + return input->inputs[index]; + return 0.0f; +} + +float planeImpulse(float value) +{ + if (value < 0.0f && value > -0.15f) + return -0.15f; + if (value > 0.0f && value < 0.15f) + return 0.15f; + return value; +} + +float planeLogResponse(float value) +{ + return value < 0.0f ? -std::log10(1.0f - value * 9.0f) : std::log10(1.0f + value * 9.0f); +} +} + +// ELF 0x2CDB00 +bool PlaneControl::towardsPoint(Bot* bot, Information* equipment, Vec3 target, float, + const Vec3& previousForward, const Vec3& previousRight, + const Vec3& previousUp, float clearance, io::PlayerInput* input) +{ + IPIMobile* mobile = equipment->getMobile(); + IPIControlInfo* controls = equipment->getControlInfo(); + const Vec3 position = equipment->getPosition(); + const Vec3 velocity = mobile->getSpeed(); + Vec3 direction = {0.0f, 0.0f, 0.0f}; + const Mat4& transformation = equipment->getTransformation(); + const float dx = transformation.m[12] - target.x; + const float dz = transformation.m[14] - target.z; + const float horizontalDistanceSq = dx * dx + dz * dz; + if (horizontalDistanceSq < 10000.0f) + { + const float ground = AerialHeightMap::m_instance->getGroundHeight(target) + clearance; + const float floor = ground > transformation.m[13] ? ground : transformation.m[13]; + const float raised = (target.y - floor) * horizontalDistanceSq * 0.0001f + floor; + if (raised > target.y) + target.y = raised; + } + Vec3 prediction = velocity; + const float speed = mobile->getSpeedMagnitude(); + if (speed > 0.00001f) + { + const float inverse = 1.0f / speed; + prediction.x *= inverse; + prediction.y *= inverse; + prediction.z *= inverse; + } + prediction.x *= 100.0f; + prediction.y *= 100.0f; + prediction.z *= 100.0f; + const bool takingOff = !bot->isAirBorn(); + if (takingOff && equipment->getAltitude() > 50.0f && speed / mobile->getMaxSpeed() > 0.5f) + bot->event_airborn(); + float altitude = equipment->getAltitude(prediction); + if (prediction.y < -50.0f) + { + Vec3 horizontal = {velocity.x, 0.0f, velocity.z}; + vehiclecontrol::normalizeVec3(horizontal); + horizontal.x *= 100.0f; + horizontal.y *= 100.0f; + horizontal.z *= 100.0f; + const float horizontalAltitude = equipment->getAltitude(horizontal); + if (!(horizontalAltitude > altitude)) // 0x2CDDEA..0x2CDDF4: unordered keeps the sample + altitude = horizontalAltitude; + } + if (takingOff) + { + target = static_cast(bot)->getTakeOffPosition(); + const Vec3& zero = Vec3::getZero(); + if (std::fabs(target.x - zero.x) <= 1.1920929e-07f + && std::fabs(target.y - zero.y) <= 1.1920929e-07f + && std::fabs(target.z - zero.z) <= 1.1920929e-07f) + { + Vec3 forward = equipment->getFaceing(); + forward.y = 0.0f; + vehiclecontrol::normalizeVec3(forward); + target = Vec3{forward.x * 500.0f + position.x, + forward.y * 500.0f + position.y + 200.0f, + forward.z * 500.0f + position.z}; + static_cast(bot)->setTakeOffPosition(target); + } + } + direction = Vec3{target.x - position.x, target.y - position.y, target.z - position.z}; + const float distance = std::sqrt(dotPlane(direction, direction)); + if (distance > 0.0001f) + { + const float inverse = 1.0f / distance; + direction.x *= inverse; + direction.y *= inverse; + direction.z *= inverse; + } + else + { + const Mat4& current = equipment->getTransformation(); + direction = Vec3{current.m[8], current.m[9], current.m[10]}; + } + const float heightError = clearance - altitude; + IAITerrain* terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + if (!takingOff && terrain->isInsideCombatArea(bot->getPlayer())) + { + bool reverse = direction.y < -0.7f; + if (!reverse && horizontalDistanceSq < 250000.0f) + { + const Mat4& current = equipment->getTransformation(); + reverse = direction.x * current.m[8] + current.m[9] * direction.y + + direction.z * current.m[10] < 0.5f; + } + if (reverse) + { direction.x = -direction.x; direction.z = -direction.z; } + } + return towardsDirection(direction, distance, input, transformation, heightError, clearance, + false, previousForward, previousRight, previousUp, mobile, controls, + 1.0f, speed, false); +} + +// ELF 0x2CE3C0 +bool PlaneControl::aimAtDirection(Bot* bot, Information* equipment, const Vec3& wanted, + float distance, float throttle, float clearance, + const Vec3& previousForward, const Vec3& previousRight, + const Vec3& previousUp, io::PlayerInput* input) +{ + IPIMobile* mobile = equipment->getMobile(); + if (!mobile) + return false; + const Mat4& transformation = equipment->getTransformation(); + const Vec3& velocity = mobile->getSpeed(); + const float speed = std::sqrt(dotPlane(velocity, velocity)); + float lowest = 999999.0f; + for (int i = 0; i < 5; ++i) + { + const float step = static_cast(i); + const Vec3 sample = {step * velocity.x * 0.25f + transformation.m[12], + velocity.y * step * 0.25f + transformation.m[13], + velocity.z * step * 0.25f + transformation.m[14]}; + const float aboveGround = sample.y - AerialHeightMap::m_instance->getGroundHeight(sample); + if (lowest > aboveGround) + lowest = aboveGround; + } + const float heightError = (clearance - lowest) + (clearance - lowest); + IPIControlInfo* controls = equipment->getControlInfo(); + const bool takingOff = !bot->isAirBorn(); + Vec3 direction = wanted; + if (takingOff) + { + direction.y = 0.3333f; + if (equipment->getAltitude() > 50.0f && speed / mobile->getMaxSpeed() > 0.5f) + bot->event_airborn(); + } + const Mat4& current = equipment->getTransformation(); + return towardsDirection(direction, distance, input, current, heightError, clearance, takingOff, + previousForward, previousRight, previousUp, mobile, controls, + throttle, speed, true); +} + +// ELF 0x2CE6D0 +bool PlaneControl::towardsDirection(const Vec3& wanted, float, io::PlayerInput* input, + const Mat4& transformation, float heightError, float clearance, + bool takingOff, const Vec3&, const Vec3&, const Vec3&, + IPIMobile* mobile, IPIControlInfo* controls, float throttle, + float speed, bool aiming) +{ + static bool useAngle = true; // ELF .data 0x4BDD44; only read at 0x2CF088. + const Vec3 up = {transformation.m[4], transformation.m[5], transformation.m[6]}; + const Vec3 right = {transformation.m[0], transformation.m[1], transformation.m[2]}; + const Vec3 forward = {transformation.m[8], transformation.m[9], transformation.m[10]}; + Vec3 direction = wanted; + vehiclecontrol::normalizeVec3(direction); + const Vec3 worldUp = {0.0f, 1.0f, 0.0f}; + Vec3 levelRight = crossPlane(worldUp, forward); + vehiclecontrol::normalizeVec3(levelRight); + const Vec3 levelUp = crossPlane(forward, levelRight); + const bool behind = dotPlane(forward, direction) < 0.0f; + Mat4 inverse = planeIdentity(); + inverse.setInverse(transformation); + const Vec3 rotation = rotatePlane(inverse, mobile->getRotationalSpeed()); + const float upright = dotPlane(up, levelUp); + float bank = dotPlane(right, levelUp); + const float ratio = heightError / (clearance - 10.0f); + const float altitudeFactor = clampPlane(planeSign(ratio) * ratio * ratio, 0.0f, 1.0f); + const float blend = 1.0f - altitudeFactor; + float pitch = altitudeFactor + altitudeFactor; + const float speedFraction = clampPlane(speed / 43.0f, 0.0f, 1.0f); + const float exponential = std::exp(clampPlane((1.0f - speedFraction) * 2.302585125f, -10.0f, 10.0f)); + const float climb = ((exponential - 1.0f) / 9.0f) * -0.833f + 0.333f; + const float maxClimb = controls->getMaxClimbAngle(); + const float climbLimit = clampPlane(climb, -1.0f, maxClimb); + float pitchLimit = 1.0f; + if (levelUp.y > 0.0f) + { + if (forward.y > 0.0f) + pitchLimit = climbLimit < 0.0f ? (1.0f - levelUp.y) * climbLimit : climbLimit * levelUp.y; + else + pitchLimit = climbLimit / levelUp.y; + } + if (!(throttle > pitch)) + throttle = pitch; + const float wantedPitch = dotPlane(levelUp, direction); + if (!(wantedPitch > pitchLimit)) + pitchLimit = wantedPitch; + pitch += pitchLimit * blend; + float yaw = 0.0f; + if (!takingOff) + { + const float wantedYaw = dotPlane(levelRight, direction); + yaw = behind ? planeSign(wantedYaw) : wantedYaw; + } + if (aiming && pitch < 0.0f && dotPlane(forward, direction) > 0.9f && yaw < 0.1f) + pitch = -clampPlane(std::log10(1.0f - pitch * 18.0f), 0.3f, 1.0f); + if (climbLimit < forward.y) + { + const float limited = -std::log10(1.0f + (forward.y - climbLimit) * 9.0f); + if (limited < pitch) + pitch = limited; + } + pitch = clampPlane(pitch + clampPlane(rotation.x, -1.0f, 1.0f), -1.0f, 1.0f); + yaw = clampPlane(yaw - clampPlane(rotation.y, -1.0f, 1.0f) * 0.1f, -1.0f, 1.0f); + const float maxRoll = controls->getMaxRollAngle(); + const float pitchInput = -(dotPlane(up, levelRight) * yaw + upright * pitch) * 4.0f; + const float pitchBank = dotPlane(right, levelUp) * pitch; + const float yawInput = pitchBank + pitchBank + dotPlane(right, levelRight) * yaw; + if (upright < 0.0f) + bank = planeSign(bank) * 2.0f - bank; + const float angle = std::asin(clampPlane(yaw, -1.0f, 1.0f)); + const float wantedBank = useAngle ? angle * 3.0f : yaw + yaw; + // 0x2CF0F8 then 0x2CF14B: bank + clamped wanted bank first, then the half rotation added. + const float rollInput = clampPlane(rotation.z, -1.0f, 1.0f) * 0.5f + + (bank + clampPlane(wantedBank, -maxRoll, maxRoll)); + const float roll = planeImpulse(clampPlane(planeLogResponse(clampPlane(rollInput, -1.0f, 1.0f)), -1.0f, 1.0f)); + const float turn = planeImpulse(clampPlane(planeLogResponse(clampPlane(yawInput, -1.0f, 1.0f)), -1.0f, 1.0f)); + const float pitchOutput = clampPlane(clampPlane(pitchInput, -1.0f, 1.0f), -1.0f, 1.0f); + const float throttleOutput = clampPlane(throttle, 0.0f, 1.0f); + input->setInput(controls->getDriveThrottleControl(), throttleOutput); + input->setInput(controls->getDrivePitchControl(), pitchOutput); + input->setInput(controls->getDriveRollControl(), roll); + input->setInput(controls->getDriveTurnControl(), turn); + return true; +} + +// ELF 0x2CF9F0 +int PlaneControl::roll(float wantedRoll, float, io::PlayerInput* input, const Mat4& transformation, + float, bool takingOff, const Vec3& referenceForward, + const Vec3& referenceRight, const Vec3& referenceUp, const Vec3&, + const Vec3& previousRight, const Vec3& previousUp, + IPIControlInfo* controls, float throttle, bool left, bool& wrapped) +{ + Mat4 transpose = planeIdentity(); + float turnInput = planeMappedInput(input, controls->getDriveTurnControl()); + float pitchInput = planeMappedInput(input, controls->getDrivePitchControl()); + float rollInput = planeMappedInput(input, controls->getDriveRollControl()); + const Vec3 up = {transformation.m[4], transformation.m[5], transformation.m[6]}; + const Vec3 right = {transformation.m[0], transformation.m[1], transformation.m[2]}; + transpose.setTranspose(transformation); + const float halfPi = 1.570796371f; + const float pi = 3.141592741f; + const float twoPi = 6.283185482f; + const float firstPitch = std::acos(clampPlane(clampPlane(dotPlane(up, referenceForward), -1.0f, 1.0f), -1.0f, 1.0f)) - halfPi; + // The second pitch sample uses the same current up vector, as shipped. + const float secondPitch = std::acos(clampPlane(clampPlane(dotPlane(up, referenceForward), -1.0f, 1.0f), -1.0f, 1.0f)) - halfPi; + const Vec3 worldUp = {0.0f, 1.0f, 0.0f}; + const Vec3 localUp = rotatePlane(transpose, worldUp); + const float elevation = std::asin(clampPlane(localUp.z, -1.0f, 1.0f)); + float pitchDemand; + float pitchChange = 0.0f; + float yawDemand = 0.0f; + float yawChange = 0.0f; + float rollDemand; + float rollChange = 0.0f; + if (takingOff) + { + throttle = 1.0f; + const float maxClimb = controls->getMaxClimbAngle(); + float climb = (maxClimb - elevation) / (1.00001f - std::fabs(right.y)); + if (climb > halfPi) + climb = halfPi; + pitchDemand = -climb; + float angle = std::acos(clampPlane(clampPlane(right.y, -1.0f, 1.0f), -1.0f, 1.0f)) - halfPi; + if (up.y < 0.0f) + angle = planeSign(angle) * pi - angle; + // 0x2D02FC/0x2D032C store the angle as the roll change, 0x2D0345 its negation as the demand. + rollChange = angle; + rollDemand = -angle; + // The take-off arm leaves the caller's wrapped flag untouched. + } + else + { + pitchDemand = firstPitch * up.y; + pitchChange = pitchDemand - previousUp.y * secondPitch; + yawDemand = (1.0f - up.y) * firstPitch; + yawChange = yawDemand - (1.0f - previousUp.y) * secondPitch; + float angle = std::acos(clampPlane(clampPlane(dotPlane(right, referenceUp), -1.0f, 1.0f), -1.0f, 1.0f)) - halfPi; + if (dotPlane(referenceRight, right) < 0.0f) + angle = twoPi - angle; + float previous = std::acos(clampPlane(clampPlane(dotPlane(previousRight, referenceUp), -1.0f, 1.0f), -1.0f, 1.0f)) - halfPi; + if (dotPlane(referenceRight, previousRight) < 0.0f) + previous = twoPi - previous; + rollChange = angle - previous; + rollDemand = angle - wantedRoll; + if (left ? rollChange < -pi : rollChange > pi) + { + rollChange = left ? twoPi + rollChange : twoPi - rollChange; + wrapped = true; + } + else + wrapped = false; + } + const float pitchScale = controls->getPitchScale(); + const float pitchLookAhead = controls->getPitchLookAhead(); + const float pitchSensitivity = controls->getPitchSensitivity(); + updateAngle(pitchDemand, pitchChange, pitchInput, pitchSensitivity, pitchLookAhead, pitchScale); + const float rollScale = controls->getRollScale(); + const float rollLookAhead = controls->getRollLookAhead(); + const float rollSensitivity = controls->getRollSensitivity(); + updateAngle(rollDemand, rollChange, rollInput, rollSensitivity, rollLookAhead, rollScale); + if (takingOff) + turnInput = 0.0f; + else + { + const float yawScale = controls->getYawScale(); + const float yawLookAhead = controls->getYawLookAhead(); + const float yawSensitivity = controls->getYawSensitivity(); + updateAngle(yawDemand, yawChange, turnInput, yawSensitivity, yawLookAhead, yawScale); + } + input->setInput(controls->getDriveThrottleControl(), throttle); + input->setInput(controls->getDrivePitchControl(), pitchInput); + input->setInput(controls->getDriveRollControl(), rollInput); + input->setInput(controls->getDriveTurnControl(), turnInput); + return 1; +} + +// ELF 0x2D03E0 (listing; Ghidra cross-check). On the ground (BotMain +0x1A4 isAirBorn false) and +// slower than 0.1 (IPIMobile +0x24, asked before `move` is tested), moving releases inputs 0, 2, +// 1 and 3. Look releases 4 and 5; trigger 8, 31, 14..30, 38, 37, 10, 32 and 47. The information +// is not null-tested. Returns 1. +int PlaneControl::resetControls(Bot* bot, Information* equipment, io::PlayerInput* input, bool move, bool look, bool trigger) +{ + IPIMobile* const mobile = equipment->getMobile(); // +0x38 + if (!bot->isAirBorn() && mobile->getSpeedMagnitude() < 0.1f && move) + { + input->setInput(static_cast(0), 0.0f); + input->setInput(static_cast(2), 0.0f); + input->setInput(static_cast(1), 0.0f); + input->setInput(static_cast(3), 0.0f); + } + if (look) + { + input->setInput(static_cast(4), 0.0f); + input->setInput(static_cast(5), 0.0f); + } + if (trigger) + { + input->setInput(static_cast(8), 0.0f); + input->setInput(static_cast(31), 0.0f); + input->setInput(static_cast(14), 0.0f); + input->setInput(static_cast(15), 0.0f); + input->setInput(static_cast(16), 0.0f); + input->setInput(static_cast(17), 0.0f); + input->setInput(static_cast(18), 0.0f); + input->setInput(static_cast(19), 0.0f); + input->setInput(static_cast(20), 0.0f); + input->setInput(static_cast(21), 0.0f); + input->setInput(static_cast(22), 0.0f); + input->setInput(static_cast(23), 0.0f); + input->setInput(static_cast(24), 0.0f); + input->setInput(static_cast(25), 0.0f); + input->setInput(static_cast(26), 0.0f); + input->setInput(static_cast(27), 0.0f); + input->setInput(static_cast(28), 0.0f); + input->setInput(static_cast(29), 0.0f); + input->setInput(static_cast(30), 0.0f); + input->setInput(static_cast(38), 0.0f); + input->setInput(static_cast(37), 0.0f); + input->setInput(static_cast(10), 0.0f); + input->setInput(static_cast(32), 0.0f); + input->setInput(static_cast(47), 0.0f); + } + return 1; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PlaneControl.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PlaneControl.h new file mode 100644 index 000000000..320c514d0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PlaneControl.h @@ -0,0 +1,34 @@ +// Fixed-wing flight and attitude controls. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_PLANECONTROL_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_PLANECONTROL_H + +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { + +struct Mat4; +namespace io { class PlayerInput; } +namespace ai { + +class Bot; +class IPIControlInfo; +class IPIMobile; +class Information; + +// [INFERRED] a namespace: no vtable, no constructor, and the first argument is never `this`. +namespace PlaneControl +{ + bool towardsPoint(Bot*, Information*, Vec3, float, const Vec3&, const Vec3&, const Vec3&, float, io::PlayerInput*); // 0x2CDB00; [INFERRED] ELF bool + bool aimAtDirection(Bot*, Information*, const Vec3&, float, float, float, const Vec3&, const Vec3&, const Vec3&, io::PlayerInput*); // 0x2CE3C0; [INFERRED] ELF bool + bool towardsDirection(const Vec3&, float, io::PlayerInput*, const Mat4&, float, float, bool, const Vec3&, const Vec3&, const Vec3&, IPIMobile*, IPIControlInfo*, float, float, bool); // 0x2CE6D0; [INFERRED] ELF int, callers {'bool': 1} + int roll(float, float, io::PlayerInput*, const Mat4&, float, bool, const Vec3&, const Vec3&, const Vec3&, const Vec3&, const Vec3&, const Vec3&, IPIControlInfo*, float, bool, bool&); // 0x2CF9F0; [INFERRED] ELF int + int resetControls(Bot*, Information*, io::PlayerInput*, bool, bool, bool); // 0x2D03E0; [INFERRED] ELF int +} + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_PLANECONTROL_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PrettyPrinter.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PrettyPrinter.cpp new file mode 100644 index 000000000..09d691024 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PrettyPrinter.cpp @@ -0,0 +1,307 @@ +// Evidence: libaidll.so 1.5.3153 (ia-32), ELF 0x1CAC00..0x1CD520. [INFERRED] placement beside +// BAPDebugger in AIPlanInterpreter (no __FILE__ string). + +// static init: ELF 0x1CD160 (__tcf_0 0x1CD1C0, _GLOBAL__I 0x1CD1F0): 's Init object only. +#include + +#include "PrettyPrinter.h" + +#include +#include + +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPATriggerContinously.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPFlowCIf.h" +#include "../AIBotActionPlan/BAPFlowCWhile.h" +#include "../AIBotActionPlan/BAPInfoWrapper.h" +#include "../AIBotActionPlan/BAPStatement.h" +#include "../AIBotActionPlan/BAPTypes.h" +#include "../Main/AIDllFrontier.h" +#include "../Main/AIStreamOperators.h" // operator<<(ostream&, BAPStatementType) + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1CAC40 (C1), 0x1CAC00 (C2). +PrettyPrinter::PrettyPrinter(BAPStatement* statement, Bot* bot) + : m_statement(statement) + , m_bot(bot) + , m_root(0) +{ + update(); +} + +// ELF 0x1CACB0 (D1), 0x1CAC80 (D2). +PrettyPrinter::~PrettyPrinter() +{ + destroyPrettyTree(m_root); +} + +// ELF 0x1CACE0. The old tree is freed first, but m_root keeps pointing at it until the new root +// is stored. +void PrettyPrinter::update() +{ + destroyPrettyTree(m_root); + m_root = new Node; + m_root->m_statement = m_statement; + m_root->m_depth = 0; + m_root->m_specialInfo = PrettyActive; + prettyPrintScriptNode(m_root); +} + +// ELF 0x1CAD90. Children first, then the node. +void PrettyPrinter::destroyPrettyTree(Node* node) +{ + if (!node) + return; + for (std::list::iterator child = node->m_children.begin(); + child != node->m_children.end(); ++child) + destroyPrettyTree(*child); + delete node; +} + +// ELF 0x1CAE60. The node's text starts from the statement type's name; combiners, IF, WHILE and +// the info wrapper add one child node per sub-statement (depth + 1), and IF and WHILE add marker +// nodes at the node's own depth. A child is on the active path only where the node is: every +// child of a parallel combiner, the current child of a serial one, the IF branch last taken, the +// WHILE body and the wrapped statement. The parallel combiner's finished flags are fetched and +// not used (shipped). +void PrettyPrinter::prettyPrintScriptNode(Node* node) +{ + if (!node || !node->m_statement) + return; + + std::stringstream typeStream; + typeStream << node->m_statement->getId(); + + switch (node->m_statement->getId()) + { + case BAPSTParallel: + { + BAPCombinerParallel* const parallel = static_cast(node->m_statement); + std::stringstream text; + text << typeStream.str(); + if (parallel->m_debugId != -1) + text << "(" << parallel->m_debugId << ")"; + node->m_text = text.str(); + + parallel->getIsFinished(); + for (std::list::iterator it = parallel->m_statements.begin(); + it != parallel->m_statements.end(); ++it) + { + Node* child = new Node; + child->m_statement = *it; + child->m_depth = node->m_depth + 1; + if (node->m_specialInfo == PrettyActive) + child->m_specialInfo = PrettyActive; + else + child->m_specialInfo = PrettyNormal; + prettyPrintScriptNode(child); + node->m_children.push_back(child); + node->m_separators.push_back(std::string("---")); + } + break; + } + + case BAPSTSerial: + { + BAPCombinerSerial* const serial = static_cast(node->m_statement); + std::stringstream text; + text << typeStream.str(); + if (serial->m_debugId != -1) + text << "(" << serial->m_debugId << ")"; + node->m_text = text.str(); + + const std::list::iterator current = serial->m_current; + for (std::list::iterator it = serial->m_statements.begin(); + it != serial->m_statements.end(); ++it) + { + Node* child = new Node; + child->m_statement = *it; + child->m_depth = node->m_depth + 1; + if (it == current && node->m_specialInfo == PrettyActive) + child->m_specialInfo = PrettyActive; + else + child->m_specialInfo = PrettyNormal; + prettyPrintScriptNode(child); + node->m_children.push_back(child); + node->m_separators.push_back(std::string("---")); + } + break; + } + + case BAPSTIf: + { + BAPFlowCIf* const flow = static_cast(node->m_statement); + node->m_text = "IF"; + BAPStatement* const trueStatement = flow->getTrueStatement(); + BAPStatement* const active = flow->getActiveStatementDebug(); + + Node* trueNode = new Node; + trueNode->m_statement = trueStatement; + trueNode->m_depth = node->m_depth + 1; + trueNode->m_specialInfo = PrettyNormal; + if (node->m_specialInfo == PrettyActive && trueStatement == active) + trueNode->m_specialInfo = PrettyActive; + prettyPrintScriptNode(trueNode); + node->m_children.push_back(trueNode); + + BAPStatement* const falseStatement = flow->getFalseStatement(); + if (falseStatement) + { + Node* falseNode = new Node; + falseNode->m_statement = falseStatement; + falseNode->m_depth = node->m_depth + 1; + falseNode->m_specialInfo = PrettyNormal; + if (node->m_specialInfo == PrettyActive && falseStatement == active) + falseNode->m_specialInfo = PrettyActive; + + // the ELSE line goes in before the branch is printed + Node* elseNode = new Node; + elseNode->m_text = "ELSE"; + elseNode->m_depth = node->m_depth; + elseNode->m_specialInfo = PrettyNormal; + node->m_children.push_back(elseNode); + + prettyPrintScriptNode(falseNode); + node->m_children.push_back(falseNode); + } + + Node* endNode = new Node; + endNode->m_text = "ENDIF"; + endNode->m_depth = node->m_depth; + endNode->m_specialInfo = PrettyNormal; + node->m_children.push_back(endNode); + break; + } + + case BAPSTWhile: + { + BAPFlowCWhile* const flow = static_cast(node->m_statement); + node->m_text = typeStream.str(); + + Node* loopNode = new Node; + loopNode->m_statement = flow->getLoopStatement(); + loopNode->m_depth = node->m_depth + 1; + loopNode->m_specialInfo = node->m_specialInfo; + prettyPrintScriptNode(loopNode); + node->m_children.push_back(loopNode); + + Node* endNode = new Node; + endNode->m_text = "ENDWHILE"; + endNode->m_depth = node->m_depth; + endNode->m_specialInfo = PrettyNormal; + node->m_children.push_back(endNode); + break; + } + + case BAPSTTrigger: + { + BAPATrigger* const trigger = static_cast(node->m_statement); + std::stringstream text; + text << typeStream.str() << " "; + if (trigger->m_started) + text << "Trig "; + else + text << "NoTr "; + node->m_text = text.str(); + break; + } + + case BAPSTTriggerContinously: + { + BAPATriggerContinously* const trigger = + static_cast(node->m_statement); + std::stringstream text; + text << typeStream.str() << " "; + if (trigger->m_started) + text << "Trig "; + else + text << "NoTr "; + node->m_text = text.str(); + break; + } + + case BAPSTInfoWrapper: + { + BAPInfoWrapper* const wrapper = static_cast(node->m_statement); + node->m_text = typeStream.str(); + + Node* child = new Node; + child->m_statement = wrapper->m_statement; + child->m_depth = node->m_depth + 1; + child->m_specialInfo = node->m_specialInfo; + prettyPrintScriptNode(child); + node->m_children.push_back(child); + break; + } + + default: + node->m_text = typeStream.str(); + break; + } +} + +// ELF 0x1CCC00. +void PrettyPrinter::getLineStrings(std::list& lines) const +{ + getLinesRecursive(lines, m_root); +} + +// ELF 0x1CCC40. Each child's lines are collected in a list of their own and spliced on. +void PrettyPrinter::getLinesRecursive(std::list& lines, Node* node) const +{ + lines.insert(lines.end(), node->m_text); + for (std::list::iterator child = node->m_children.begin(); + child != node->m_children.end(); ++child) + { + std::list childLines; + getLinesRecursive(childLines, *child); + lines.splice(lines.end(), childLines); + } +} + +// ELF 0x1CCE60. +void PrettyPrinter::getLineDepths(std::list& depths) const +{ + getDepthsRecursive(depths, m_root); +} + +// ELF 0x1CCEA0. +void PrettyPrinter::getDepthsRecursive(std::list& depths, Node* node) const +{ + depths.insert(depths.end(), node->m_depth); + for (std::list::iterator child = node->m_children.begin(); + child != node->m_children.end(); ++child) + { + std::list childDepths; + getDepthsRecursive(childDepths, *child); + depths.splice(depths.end(), childDepths); + } +} + +// ELF 0x1CCFE0. +void PrettyPrinter::getLineSpecialInfos(std::list& infos) const +{ + getSpecialInfosRecursive(infos, m_root); +} + +// ELF 0x1CD020. +void PrettyPrinter::getSpecialInfosRecursive(std::list& infos, Node* node) const +{ + infos.insert(infos.end(), node->m_specialInfo); + for (std::list::iterator child = node->m_children.begin(); + child != node->m_children.end(); ++child) + { + std::list childInfos; + getSpecialInfosRecursive(childInfos, *child); + infos.splice(infos.end(), childInfos); + } +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PrettyPrinter.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PrettyPrinter.h new file mode 100644 index 000000000..d6505f687 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PrettyPrinter.h @@ -0,0 +1,73 @@ +// Builds a printable tree of a bot action plan: one node per statement plus IF/ELSE/ENDIF and +// ENDWHILE marker lines, each with its indentation depth and whether it lies on the active path. +// Evidence: libaidll.so 1.5.3153 (ia-32), ELF 0x1CAC00..0x1CD520; the TU's static-init symbol +// names PrettyPrinter's constructor. Nothing else in the DLL refers to the class. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_PRETTYPRINTER_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_PRETTYPRINTER_H + +#include +#include + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPStatement; +class Bot; + +// Per-line marker handed out by getLineSpecialInfos: 1 for lines on the plan's active path (the +// root, the running child of a serial combiner, the chosen IF branch), else 0. Four bytes. +// [INFERRED] an enum (the mangled name does not tell enum from class) and the enumerator names. +enum PrettySpecialInfo +{ + PrettyNormal = 0, + PrettyActive = 1 +}; + +// 12 bytes: the plan, the bot (stored, never read) and the tree's root. +class PrettyPrinter +{ +public: + // 24 bytes. The implicit constructor leaves the statement, depth and marker unset; the + // ELSE/ENDIF/ENDWHILE marker nodes never get a statement. + struct Node + { + /* +0x00 */ BAPStatement* m_statement; + /* +0x04 */ std::string m_text; + /* +0x08 */ int m_depth; + /* +0x0C */ PrettySpecialInfo m_specialInfo; + /* +0x10 */ std::list m_children; + /* +0x14 */ std::list m_separators; // "---" per combiner child; never read + }; + + // Builds the tree at once (update). + PrettyPrinter(BAPStatement* statement, Bot* bot); // ELF 0x1CAC40 (C1), 0x1CAC00 (C2) + ~PrettyPrinter(); // ELF 0x1CACB0 (D1), 0x1CAC80 (D2) + + // Rebuilds the tree from the plan's current state. + void update(); + void destroyPrettyTree(Node* node); + // Fills `node` (text and children) from its statement; nothing for a null node or statement. + void prettyPrintScriptNode(Node* node); + + // The tree in pre-order, one entry per line, appended to the caller's list. + void getLineStrings(std::list& lines) const; + void getLinesRecursive(std::list& lines, Node* node) const; + void getLineDepths(std::list& depths) const; + void getDepthsRecursive(std::list& depths, Node* node) const; + void getLineSpecialInfos(std::list& infos) const; + void getSpecialInfosRecursive(std::list& infos, Node* node) const; + +private: + /* +0x00 */ BAPStatement* m_statement; + /* +0x04 */ Bot* m_bot; + /* +0x08 */ Node* m_root; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_PRETTYPRINTER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/TankControl.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/TankControl.cpp new file mode 100644 index 000000000..8ec3ea5d7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/TankControl.cpp @@ -0,0 +1,869 @@ +// Tank steering for the plan interpreter (libaidll.so TankControl TU). Every body is recovered. +// static init: the guard object only (ELF 0x2D4AF0, __tcf_0 0x2D4B50, _GLOBAL__I 0x2D4B80). + +#include "TankControl.h" + +#include "CommonControls.h" +#include "VehicleControlInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotNavigation.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../Main/IAIPathfinding.h" +#include "../Main/IBotManager.h" +#include "../../../../Math/LocalBoundingBox.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../IO/Input/PlayerInput.h" +#include "../../../../Math/Mat4.h" +#include +#include "../../../../Math/Vec3.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +using namespace vehiclecontrol; + +namespace { + +// The TU's tweak values (.data 0x4BDD84..0x4BDDB8). Only the last three are read (by +// turnTowardsDirection); tweak_maxSpeed 20, tweak_minSpeed 2, tweak_stopAndTurn_maxSpeed 2, +// tweak_speedScale 2, tweak_speedCompensationFallOff 30, tweak_speedCompensationScale 1, +// tweak_maxSpeedCompensation 10, tweak_rotationalSpeedScale 1, +// tweak_rotationalSpeedCompensationFallOff 30, tweak_rotationalSpeedCompensationScale 1 and +// tweak_maxRotationalSpeedCompensation 10 have no reader in the image. +float tweak_velocityLimitModifier = 0.3f; // .data 0x4BDDB0 +float tweak_lowThrottle = 0.5f; // .data 0x4BDDB4 +float tweak_highThrottle = 1.0f; // .data 0x4BDDB8 + +// min(1, |signedSpeed|): the pass statuses' steering scale (0x2D3C39). +inline float passTurn(float signedSpeed) +{ + float magnitude = std::fabs(signedSpeed); + if (magnitude > 1.0f) + magnitude = 1.0f; + return magnitude; +} + +} // namespace + +// ELF 0x2D07B0 (Ghidra; listing for the statics and the inlined setInput). The car version with a +// speed-scaled turn: angle' = min(1, |v| / maxSpeed)^2 * angle, and 0 below minVelocity (the +// statics, 2 and 1). Driving: turn input clamp(3 * angle', -1, 1); target speed = speed * mode, +// capped at `limit` (no slope reduction); throttle = clamp(target / 15 + sign(r) * r^2, -1, 1) with +// r = min(1, (target - |v| * reference) / 3), and below 1.5 m/s a non-zero throttle becomes its sign. +// Turning on the spot: the turn input (only while mapped) is sign(angle') * min(1, |3 * (|angle'| +// [- pi])|); the throttle input gets `mode`. `direction` and the physical part are not read. +// Returns 1. +int TankControl::controlTowardsDirection(Information* info, IPIControlInfo* controlInfo, IPIMobile* mobile, + IPIPhysical*, io::PlayerInput* input, const Vec2&, float speed, float mode, + float angle, float reference, float limit) +{ + static float minVelocity = 1.0f; // .data 0x4BDDBC + static float maxSpeed = 2.0f; // .data 0x4BDDC0 + + const Mat4& transformation = info->getTransformation(); + Vec2 forward; + forward.x = forward.y = 0.0f; + vec3ToVec2XZ(*reinterpret_cast(&transformation.m[8]), forward); + Vec2 right; // read, never used + right.x = right.y = 0.0f; + vec3ToVec2XZ(*reinterpret_cast(&transformation.m[0]), right); + Vec2 position; // read, never used + position.x = position.y = 0.0f; + vec3ToVec2XZ(*reinterpret_cast(&transformation.m[12]), position); + Vec2 velocity; + velocity.x = velocity.y = 0.0f; + vec3ToVec2XZ(mobile->getSpeed(), velocity); + const float velocityLength = std::sqrt(velocity.x * velocity.x + velocity.y * velocity.y); + Vec2 heading; // computed, never used + if (velocityLength == 0.0f) + { + heading = forward; + } + else + { + const float inverse = 1.0f / velocityLength; + heading.x = velocity.x * inverse; + heading.y = inverse * velocity.y; + } + (void)heading; + if (mode != 0.0f && reference != mode && velocityLength > 1.0f) + angle = -angle; + float speedRatio = std::fabs(velocityLength) / maxSpeed; + if (std::fabs(velocityLength) < minVelocity) + angle = 0.0f; + if (speedRatio > 1.0f) + speedRatio = 1.0f; + const float scaledAngle = speedRatio * speedRatio * angle; + float sign = 1.0f; + if (scaledAngle <= 0.0f) + sign = (0.0f <= scaledAngle) ? 0.0f : -1.0f; + if (speed != 0.0f) + { + IAIObjectPhysical* const object = info->getAIObject()->getPhysical(); + object->enablePhysics(1); + object->enablePhysics(2); + } + + float throttle; + if (mode != 0.0f) + { + const float turnAngle = scaledAngle * 3.0f; + float turn = -1.0f; + if (-1.0f <= turnAngle) + turn = (1.0f < turnAngle) ? 1.0f : turnAngle; + input->setInput(controlInfo->getDriveTurnControl(), turn); + speed = speed * mode; + if (std::fabs(speed) > limit) + { + float speedSign = 0.0f; + if (speed <= 0.0f) + { + if (speed < 0.0f) + speedSign = -1.0f; + } + else + { + speedSign = 1.0f; + } + speed = speedSign * limit; + } + float response = (speed - velocityLength * reference) / 3.0f; + if (response > 1.0f) + response = 1.0f; + float responseSign = 1.0f; + if (response <= 0.0f) + responseSign = (0.0f <= response) ? 0.0f : -1.0f; + const float combined = speed / 15.0f + responseSign * response * response; + throttle = -1.0f; + if (-1.0f <= combined) + throttle = (combined <= 1.0f) ? combined : 1.0f; + if (throttle != 0.0f && !(1.5f <= std::fabs(velocityLength))) + { + float throttleSign = 1.0f; + if (throttle <= 0.0f) + throttleSign = (throttle < 0.0f) ? -1.0f : 0.0f; + throttle = throttleSign; + } + } + else + { + float turnAngle = std::fabs(scaledAngle); + if (mode == -1.0f) + turnAngle = turnAngle - 3.1415927f; + float turn = std::fabs(turnAngle * 3.0f); + if (turn > 1.0f) + turn = 1.0f; + input->setInput(controlInfo->getDriveTurnControl(), sign * turn); + throttle = mode; + } + input->setInput(controlInfo->getDriveThrottleControl(), throttle); + return 1; +} + +// ELF 0x2D0E30 (listing; Ghidra cross-check). Turns a tank on the spot towards `angle`: +// turn input -sign(angle) * (forward ? 1 : -1); the rotational speed about y is driven to +// min(1, (|angle| + 0.05) / maxOffsetAngle) times that and rotationTweak in steps of 0.05; the +// throttle is (forward ? 1 : -1) times tweak_lowThrottle while the ground speed is above +// min(1, angle^2 * tweak_velocityLimitModifier), else tweak_highThrottle. `unused` and `done` are +// not read; the normalised ground velocity is computed and dropped. +void TankControl::turnTowardsDirection(float angle, float, bool forward, Information* info, IPIMobile* mobile, + IPIControlInfo* controlInfo, io::PlayerInput* input, bool*) +{ + static float rotationTweak = 2.0f; // .data 0x4BDDC4 + static float maxOffsetAngle = 0.6f; // .data 0x4BDDC8 + + Vec2 velocity; + velocity.x = velocity.y = 0.0f; + vec3ToVec2XZ(mobile->getSpeed(), velocity); + const float velocityLength = std::sqrt(velocity.x * velocity.x + velocity.y * velocity.y); + const float inverse = 1.0f / velocityLength; + Vec2 heading; // computed, never used + heading.x = velocity.x * inverse; + heading.y = velocity.y * inverse; + (void)heading; + const float direction = forward ? 1.0f : -1.0f; + float sign = 1.0f; + if (!(angle > 0.0f)) + sign = (0.0f > angle) ? -1.0f : 0.0f; + float velocityLimit = angle * angle * tweak_velocityLimitModifier; + if (velocityLimit > 1.0f) + velocityLimit = 1.0f; + const float turn = -sign * direction; + input->setInput(controlInfo->getDriveTurnControl(), turn); + float offset = (std::fabs(angle) + 0.05f) / maxOffsetAngle; + if (offset > 1.0f) + offset = 1.0f; + info->getAIObject()->striveForRotationalSpeed(1, offset * turn * rotationTweak, 0.05f); + if (velocityLength > velocityLimit) + input->setInput(controlInfo->getDriveThrottleControl(), direction * tweak_lowThrottle); + else + input->setInput(controlInfo->getDriveThrottleControl(), direction * tweak_highThrottle); +} + +// ELF 0x2D1010 (Ghidra). The car's reset with the tank's own maxThrottle static (also 0.7): +// moving releases inputs 0, 2 and 1 and brakes the throttle (input 3) against `forwardSpeed` +// (clamped to +-maxThrottle, negated; released within 0.05 of zero, else the sign times at least +// 0.4). Look releases 4 and 5; trigger releases 8, 31, 14..30, 38, 37, 10 and 32. Returns 1. +int TankControl::resetControls(Bot*, io::PlayerInput* input, bool move, bool look, bool trigger, float forwardSpeed) +{ + static float maxThrottle = 0.7f; + if (move) + { + input->setInput(static_cast(0), 0.0f); + input->setInput(static_cast(2), 0.0f); + input->setInput(static_cast(1), 0.0f); + float clamped; + if (-maxThrottle > forwardSpeed) + clamped = -maxThrottle; + else + clamped = (forwardSpeed > maxThrottle) ? maxThrottle : forwardSpeed; + const float brake = -clamped; + float throttle = 0.0f; + if (std::fabs(brake) > 0.05f) + { + const float sign = (brake > 0.0f) ? 1.0f : ((0.0f > brake) ? -1.0f : 0.0f); + const float magnitude = std::fabs(brake); + throttle = sign * ((magnitude > 0.4f) ? magnitude : 0.4f); + } + input->setInput(static_cast(3), throttle); + } + if (look) + { + input->setInput(static_cast(4), 0.0f); + input->setInput(static_cast(5), 0.0f); + } + if (trigger) + { + input->setInput(static_cast(8), 0.0f); + input->setInput(static_cast(31), 0.0f); + for (int i = 14; i <= 30; ++i) + input->setInput(static_cast(i), 0.0f); + input->setInput(static_cast(38), 0.0f); + input->setInput(static_cast(37), 0.0f); + input->setInput(static_cast(10), 0.0f); + input->setInput(static_cast(32), 0.0f); + } + return 1; +} + +// ELF 0x2D1390 (listing, diffed against CarControl::actionStatusDecision 0x2AB970 instruction by +// instruction; Ghidra cross-check). The tank's move-to state machine, the car's with these changes: +// the near-goal distance is 5 radii (car 10), checkCollisions looks ahead 0.5 s (car 0.25 s), the +// speed limit is maxSpeed - (1 - ratio) * maxSpeed / 2 (no 5 m/s band), the pass statuses 4/5/13/14 +// steer +-0.2 * min(1, |signed speed|) (car +-2) and also leave when touching an obstacle more than +// 0.8 ahead, status 11 returns to 0 above 0.9 without the front-space test, and status 12 turns +// towards the side with more room. Outputs and shipped quirks as in the car version. +int TankControl::actionStatusDecision(Bot* bot, Information* info, const Vec2& direction, float speed, + BAPAMoveTo* moveTo, float& mode, float& angle, float& speedSign, + float& speedLimit) +{ + static float spaceTweak = 1.3f; // .data 0x4BDDD0 + + IPIMobile* const mobile = info->getMobile(); + IPIPhysical* const physical = info->getPhysical(); + if (mobile == 0 || physical == 0) + return 0; + BotMain* const botMain = static_cast(bot); // slots 0x238.. are declared on BotMain only + const float radius = physical->getRadius(); + Vec2 desired = direction; + const Vec3& position3 = info->getPosition(); + Vec2 position; + position.x = position.y = 0.0f; + Vec2 forward; + forward.x = forward.y = 0.0f; + Vec2 normal; + normal.x = normal.y = 0.0f; + vec3ToVec2XZ(position3, position); + vec3ToVec2XZ(info->getFaceing(), forward); + normalizeVec2(forward); + getNormal(forward, normal); + Vec2 goal; + goal.x = goal.y = 0.0f; + vec3ToVec2XZ(moveTo->getCoordinate(), goal); + float goalDistance = moveTo->getTargetDistance(); + if (goalDistance == 0.0f) + { + Vec2 toGoal; + toGoal.x = position.x - goal.x; + toGoal.y = position.y - goal.y; + goalDistance = std::sqrt(toGoal.x * toGoal.x + toGoal.y * toGoal.y); + } + const float nearDistance = radius * 5.0f; + const float dot = desired.x * forward.x + desired.y * forward.y; + angle = getSignedDiffAngleToDirWithNormal(forward, normal, desired); + const bool angleNegative = 0.0f > angle; + const float speedMagnitude = mobile->getSpeedMagnitude(); + const Vec3& velocity = mobile->getSpeed(); + const Vec3 facing = info->getFaceing(); + if (velocity.x * facing.x + velocity.y * facing.y + velocity.z * facing.z >= 0.0f) + speedSign = 1.0f; + else + speedSign = -1.0f; + bool slowDownStop; + const float signedSpeed = speedMagnitude * speedSign; + const float slowDown = CommonControls::checkSlowDown(bot, info, velocity, signedSpeed, position3, slowDownStop); + Vec3 forward3; + forward3.x = forward3.y = forward3.z = 0.0f; + vec2ToVec3XZ(forward, forward3); + mode = 1.0f; + + // 0x2ABCE4: the eight space traces. + IAIPathfinding* const pathfinding = IAIPathfinding::instance; + mobile->getVehicleNumber(); // result discarded + BotNavigation* const navigation = bot->getBotNavigation(); + const float traceLength = radius + 10.0f; + Vec3 hit; + hit.x = hit.y = hit.z = 0.0f; + const IPIMobile::ValidPos& lastValid = mobile->getLastValidPosition(pathfinding->getTraceMapIndex()); + const int equipmentType = info->getUnit()->getEquipmentType(); + Vec3 right; + right.x = normal.x; + right.y = 0.0f; + right.z = normal.y; + int status = botMain->getMoveToStatus(); + const bool reversing = status > 7; + float back = 0.0f; + float front = 0.0f; + LocalBoundingBox* const box = const_cast(physical->getLocalBoundingBox()); + const Vec3& size = box->getSize(); + const float width = size.x; + const float length = size.z; + const Vec3 origin = lastValid.position; + const Vec3 ahead = forward3; + Vec3 frontLeft; + frontLeft.x = length * forward3.x - right.x * width; + frontLeft.y = length * forward3.y - right.y * width; + frontLeft.z = length * forward3.z - right.z * width; + normalizeVec3(frontLeft); + Vec3 frontRight; + frontRight.x = length * ahead.x + right.x * width; + frontRight.y = ahead.y * length + right.y * width; + frontRight.z = length * ahead.z + right.z * width; + normalizeVec3(frontRight); + unsigned int polygon; + unsigned char traceStatus; + float frontUnused; // -0x2CC: updateSpaceWithObstacles' front output, never initialised or read + + Vec3 target = alongFrom(origin, ahead, traceLength); + pathfinding->trace(navigation, true, target, hit, polygon, equipmentType, -1, 0.0f, 6, 0); + if (!isZeroVec3(hit)) + front = distanceVec3(hit, origin); + const float firstFront = front; + target = alongFrom(origin, frontLeft, traceLength); + pathfinding->trace(navigation, true, target, hit, polygon, equipmentType, -1, 0.0f, 6, &traceStatus); + if (traceStatus != 4 && !isZeroVec3(hit)) + { + const float d = distanceVec3(hit, origin); + front = (d > firstFront) ? firstFront : d; + } + target = alongFrom(origin, frontRight, traceLength); + pathfinding->trace(navigation, true, target, hit, polygon, equipmentType, -1, 0.0f, 6, &traceStatus); + if (traceStatus != 4 && !isZeroVec3(hit)) + { + const float d = distanceVec3(hit, origin); + front = (d > front) ? front : d; + } + target = backFrom(origin, ahead, traceLength); + pathfinding->trace(navigation, true, target, hit, polygon, equipmentType, -1, 0.0f, 6, 0); + if (!isZeroVec3(hit)) + back = distanceVec3(hit, origin); + CommonControls::updateSpaceWithObstacles(bot, origin, ahead, frontUnused, back, 0xFFFFFFFFu); + target = backFrom(origin, frontLeft, traceLength); + pathfinding->trace(navigation, true, target, hit, polygon, equipmentType, -1, 0.0f, 6, &traceStatus); + if (traceStatus != 4 && !isZeroVec3(hit)) + { + const float d = distanceVec3(hit, origin); + back = (d > back) ? back : d; + } + CommonControls::updateSpaceWithObstacles(bot, origin, frontLeft, frontUnused, back, 0xFFFFFFFFu); + target = backFrom(origin, frontRight, traceLength); + pathfinding->trace(navigation, true, target, hit, polygon, equipmentType, -1, 0.0f, 6, &traceStatus); + if (traceStatus != 4 && !isZeroVec3(hit)) + { + const float d = distanceVec3(hit, origin); + back = (d > back) ? back : d; + } + CommonControls::updateSpaceWithObstacles(bot, origin, frontRight, frontUnused, back, 0xFFFFFFFFu); + target = alongFrom(origin, right, traceLength); + pathfinding->trace(navigation, true, target, hit, polygon, equipmentType, -1, 0.0f, 6, &traceStatus); + float rightSpace = traceLength; + if (traceStatus != 4) + rightSpace = isZeroVec3(hit) ? 0.0f : distanceVec3(hit, origin); + target = backFrom(origin, right, traceLength); + pathfinding->trace(navigation, true, target, hit, polygon, equipmentType, -1, 0.0f, 6, &traceStatus); + float leftSpace = traceLength; + if (traceStatus != 4) + leftSpace = isZeroVec3(hit) ? 0.0f : distanceVec3(hit, origin); + + // 0x2AD236: the obstacle ahead. + const float spaceRadius = radius * spaceTweak; + unsigned int obstacle = 0xFFFFFFFFu; + unsigned int collided = botMain->getCollidedObject(); + int avoidSide = botMain->getAvoidSide(); + Vec2 desiredVelocity; + desiredVelocity.x = speed * direction.x; + desiredVelocity.y = speed * direction.y; + float dotForward; + float angleToObstacle; + bool outOfOurWay; + bool passing; + bool collidedSeen; + float avoidAngle; + float tangentAngle; + bool touching; + bool collision = CommonControls::checkCollisions(bot, info, physical, forward, dotForward, angleToObstacle, + outOfOurWay, desiredVelocity, desired, speed, passing, obstacle, + collided, collidedSeen, avoidAngle, tangentAngle, speedSign, + touching, static_cast(avoidSide), false); + if (collided != 0xFFFFFFFFu && !collidedSeen) + collision = false; + if (collision) + { + Information* const obstacleInfo = lookupInformation(obstacle); + const float limitSqr = botMain->getIgnoreObstacles() ? 2.5f * 2.5f : 1.0f; + if (obstacle == collided && obstacle != 0xFFFFFFFFu) + { + // 0x2AEB27: drop the collision once the collided object has moved away. + const Vec3& last = botMain->getCollidedObjectPosition(); + const Vec3& now = obstacleInfo->getPosition(); + Vec3 moved; + moved.x = now.x - last.x; + moved.y = now.y - last.y; + moved.z = now.z - last.z; + if (moved.x * moved.x + moved.y * moved.y + moved.z * moved.z > limitSqr) + collision = false; + } + else + { + botMain->setCollidedObjectPosition(obstacleInfo->getPosition()); + } + } + if (!collision) + { + botMain->setCollidedObject(0xFFFFFFFFu); + obstacle = 0xFFFFFFFFu; + collided = 0xFFFFFFFFu; + } + bool tooClose = false; + if (collision) + { + botMain->setCollidedObject(obstacle); + collided = obstacle; + if (avoidSide == 0) + { + // 0x2AD494: choose the side with more room around the collided vehicle. + Information* const other = lookupInformation(collided); + IPIMobile* const otherMobile = other->getMobile(); + IPIPhysical* const otherPhysical = other->getPhysical(); + if (otherMobile == 0) + { + avoidSide = 1; + } + else + { + const float clearance = radius + otherPhysical->getSmallestRadius() * 0.5f; + const float reach = clearance + 0.5f; + const int vehicleNumber = mobile->getVehicleNumber(); + const IPIMobile::ValidPos& otherValid = otherMobile->getLastValidPosition(vehicleNumber); + if (otherValid.polygon == 0xFFFFFFFFu || otherValid.island == 0xFFFFFFFFu) + { + avoidSide = 1; + } + else + { + Vec3 hitRight; + hitRight.x = hitRight.y = hitRight.z = 0.0f; + Vec3 hitLeft; + hitLeft.x = hitLeft.y = hitLeft.z = 0.0f; + unsigned int sidePolygon; + Vec3 sideTarget = alongFrom(otherValid.position, rightAxis(info->getTransformation()), reach); + pathfinding->trace(otherValid.polygon, otherValid.island, vehicleNumber, otherValid.position, + sideTarget, hitRight, sidePolygon, equipmentType, -1, 0.0f, 0, 0); + float roomRight = isZeroVec3(hitRight) ? 0.0f : distanceVec3(hitRight, otherValid.position); + sideTarget = backFrom(otherValid.position, rightAxis(info->getTransformation()), reach); + pathfinding->trace(otherValid.polygon, otherValid.island, vehicleNumber, otherValid.position, + sideTarget, hitLeft, sidePolygon, equipmentType, -1, 0.0f, 0, 0); + float roomLeft = isZeroVec3(hitLeft) ? 0.0f : distanceVec3(hitLeft, otherValid.position); + bool firstSide = roomRight < roomLeft; // before the obstacles shorten them + CommonControls::updateSpaceWithObstacles(bot, otherValid.position, + rightAxis(info->getTransformation()), roomRight, + roomLeft, collided); + const float smaller = (roomLeft < roomRight) ? roomLeft : roomRight; + const float larger = (roomRight > roomLeft) ? roomRight : roomLeft; + tooClose = clearance > larger; + if (smaller > clearance) + { + // 0x2AEA3E: room on both sides - the side the other vehicle lies on across the desired line. + Vec2 sideNormal; + sideNormal.x = sideNormal.y = 0.0f; + getNormal(desired, sideNormal); + Vec2 toOther; + toOther.x = otherValid.position.x - position.x; + toOther.y = otherValid.position.z - position.y; + firstSide = toOther.x * sideNormal.x + toOther.y * sideNormal.y > 0.0f; + } + else if (!(clearance * 0.7f > larger)) + { + firstSide = roomRight < roomLeft; + } + avoidSide = 2; + if (firstSide) + avoidSide = 1; + } + } + if (botMain->setAvoidSide(avoidSide) && !botMain->getIgnoreObstacles()) + { + status = 0; + botMain->setMoveToStatus(0); + botMain->setIgnoreObstacles(true); + } + } + } + else + { + botMain->setAvoidSide(0); + } + + // 0x2ADA40: arrived next to the collided object's goal? + bool hasCollided = collided != 0xFFFFFFFFu; + bot->setUnresolvedCollisionObject(collided); + if (hasCollided) + { + Information* const other = lookupInformation(collided); + if (other == 0) + { + hasCollided = false; + collided = 0xFFFFFFFFu; + } + else + { + Vec2 otherPosition; + otherPosition.x = otherPosition.y = 0.0f; + vec3ToVec2XZ(*reinterpret_cast(&other->getTransformation().m[12]), otherPosition); + const float otherRadius = other->getPhysical()->getRadius(); + Vec2 goalOffset; + goalOffset.x = goal.x - otherPosition.x; + goalOffset.y = goal.y - otherPosition.y; + if (otherRadius * otherRadius > goalOffset.x * goalOffset.x + goalOffset.y * goalOffset.y) + { + Vec2 toOther; + toOther.x = otherPosition.x - position.x; + toOther.y = otherPosition.y - position.y; + const float distanceSqr = toOther.x * toOther.x + toOther.y * toOther.y; + const float reach = other->getPhysical()->getRadius() + radius + 3.0f; + if (reach * reach > distanceSqr) + { + mode = 666.0f; + angle = 0.0f; + return 1; + } + } + } + } + else + { + avoidSide = 0; + botMain->setAvoidSide(0); + } + + // 0x2ADB2D: room flags and the speed limit. + bool wideSpace = false; + const bool obstacleAngleNegative = 0.0f > angleToObstacle; + if (leftSpace + rightSpace > radius * 2.7f && front + back > radius * 2.7f) + wideSpace = true; + bool veryWideSpace = false; + if (leftSpace + rightSpace > radius * 3.0f && front + back > radius * 3.0f) + veryWideSpace = true; + const float frontRatio = (front - spaceRadius) / (traceLength - spaceRadius); + const float backRatio = (back - spaceRadius) / (traceLength - spaceRadius); + bool stuck = false; + if (front == 0.0f && back == 0.0f) + { + stuck = true; + status = !(dot > 0.0f) ? 8 : 0; + } + const float maxSpeed = mobile->getMaxSpeed(); + const float minSpeed = maxSpeed * 0.5f; + if (!reversing) + speedLimit = maxSpeed - (1.0f - frontRatio) * (maxSpeed - minSpeed); + else + speedLimit = maxSpeed - (1.0f - backRatio) * (maxSpeed - minSpeed); + if (tooClose) + speedLimit = (7.0f > speedLimit) ? speedLimit : 7.0f; + if (!hasCollided) + { + botMain->setIgnoreObstacles(false); + botMain->setAvoidSide(0); + } + bool ignoring = botMain->getIgnoreObstacles(); + if (ignoring) + { + if (hasCollided) + { + // 0x2ADD1E: keep ignoring while we push the collided object, unless it has a human driver. + Information* const other = lookupInformation(collided); + IAIObjectPhysical* const otherObject = other->getAIObject()->getPhysical(); + otherObject->enablePhysics(1); + otherObject->enablePhysics(2); + if (botMain->getSlowDownToTarget() == collided) + ignoring = true; + if (other->getAIObject() != 0 && IBotManager::instance->getBot(other->getAIObject()) == 0 + && other->getUnit() != 0 && other->getUnit()->isOccupied()) + ignoring = false; + } + if (ignoring && (static_cast(status - 4) <= 2u || status == 13 || status == 14)) + { + status = 0; + botMain->setMoveToStatus(0); + } + } + + // 0x2ADE10 + switch (status) + { + case 0: + if (stuck) + { + mode = 1.0f; + speedLimit = maxSpeed * 0.5f; + break; + } + if (!(0.0f > dot) && !(spaceRadius > front)) + { + if (collision && !ignoring) + botMain->setMoveToStatus(6); + else + mode = 1.0f; + break; + } + if (nearDistance >= goalDistance && -0.6f > dot && back > spaceRadius) + { + botMain->setMoveToStatus(8); + break; + } + if (0.0f > dot && !wideSpace) + { + botMain->setMoveToStatus(12); + break; + } + botMain->setMoveToStatus(angleNegative ? 9 : 11); + break; + case 2: + if (angleNegative) + { + botMain->setMoveToStatus(dot > 0.0f ? 3 : 9); + break; + } + if (dot > 0.9f) + { + botMain->setMoveToStatus(0); + break; + } + if (spaceRadius > front || (dotForward > 0.5f && hasCollided && !outOfOurWay && !ignoring)) + { + botMain->setMoveToStatus(11); + break; + } + if (angleNegative && wideSpace && 0.0f > dot && back > spaceRadius) + { + botMain->setMoveToStatus(9); + break; + } + mode = 1.0f; + angle = std::fabs(angle); + break; + case 3: + if (!angleNegative) + { + botMain->setMoveToStatus(dot > 0.0f ? 2 : 11); + break; + } + if (dot > 0.9f) + { + botMain->setMoveToStatus(0); + break; + } + if (spaceRadius > front || (dotForward > 0.5f && hasCollided && !outOfOurWay && !ignoring)) + { + botMain->setMoveToStatus(9); + break; + } + if (!angleNegative && wideSpace && 0.0f > dot && back > spaceRadius) + { + botMain->setMoveToStatus(11); + break; + } + mode = 1.0f; + angle = -std::fabs(angle); + break; + case 4: + if (!hasCollided || (outOfOurWay && !obstacleAngleNegative)) + botMain->setMoveToStatus(6); + else if (spaceRadius > front || (touching && dotForward > 0.8f)) + botMain->setMoveToStatus(13); + else + { + mode = 1.0f; + angle = passTurn(signedSpeed) * -0.2f; + } + break; + case 5: + if (!hasCollided || (outOfOurWay && obstacleAngleNegative)) + botMain->setMoveToStatus(6); + else if (spaceRadius > front || (touching && dotForward > 0.8f)) + botMain->setMoveToStatus(14); + else + { + mode = 1.0f; + angle = passTurn(signedSpeed) * 0.2f; + } + break; + case 6: + if (!hasCollided || (passing && 0.3f > dotForward)) + { + botMain->setMoveToStatus(0.0f > angle ? 3 : 2); + break; + } + if (touching && !outOfOurWay && dotForward > 0.0f) + { + botMain->setMoveToStatus(avoidSide == 2 ? 14 : 13); + break; + } + if (front >= spaceRadius) + { + angle = avoidAngle; + break; + } + if (avoidSide == 2) + { + if (botMain->setAvoidSide(1) && !botMain->getIgnoreObstacles()) + { + botMain->setMoveToStatus(0); + botMain->setIgnoreObstacles(true); + } + else + { + botMain->setMoveToStatus(13); + } + } + else + { + if (botMain->setAvoidSide(2) && !botMain->getIgnoreObstacles()) + { + botMain->setMoveToStatus(0); + botMain->setIgnoreObstacles(true); + } + else + { + botMain->setMoveToStatus(14); + } + } + break; + case 8: + if (stuck) + { + mode = -1.0f; + angle = -angle; + reverseAngle(angle); + break; + } + if (dot > -0.5f || goalDistance > nearDistance + 5.0f || spaceRadius > back) + { + botMain->setMoveToStatus(0); + mode = 1.0f; + break; + } + if (-0.6f > dotForward && hasCollided) + { + botMain->setMoveToStatus(obstacleAngleNegative ? 3 : 2); + break; + } + mode = -1.0f; + reverseAngle(angle); + break; + case 9: + if (!angleNegative) + { + botMain->setMoveToStatus(dot > 0.0f ? 2 : 11); + break; + } + if (dot > 0.9f && front > spaceRadius) + botMain->setMoveToStatus(0); + else if (spaceRadius > back) + botMain->setMoveToStatus(3); + else + { + mode = -1.0f; + angle = std::fabs(angle); + } + break; + case 11: + if (angleNegative) + { + botMain->setMoveToStatus(dot > 0.0f ? 3 : 9); + break; + } + if (dot > 0.9f) + botMain->setMoveToStatus(0); + else if (spaceRadius > back) + botMain->setMoveToStatus(2); + else + { + mode = -1.0f; + angle = -std::fabs(angle); + } + break; + case 12: + if (dot > 0.0f) + botMain->setMoveToStatus(0); + else if (nearDistance >= goalDistance && -0.6f > dot && back > spaceRadius) + botMain->setMoveToStatus(8); + else if (veryWideSpace) + botMain->setMoveToStatus(rightSpace > leftSpace ? 9 : 11); + else + { + mode = -1.0f; + reverseAngle(angle); + } + break; + case 13: + if (!hasCollided || (outOfOurWay && !obstacleAngleNegative)) + botMain->setMoveToStatus(6); + else if (spaceRadius > back) + botMain->setMoveToStatus(4); + mode = -1.0f; + angle = passTurn(signedSpeed) * 0.2f; + break; + case 14: + if (!hasCollided || (outOfOurWay && obstacleAngleNegative)) + botMain->setMoveToStatus(6); + else if (spaceRadius > back) + botMain->setMoveToStatus(5); + mode = -1.0f; + angle = passTurn(signedSpeed) * -0.2f; + break; + default: + break; + } + // 0x2ADE60 + if (speedLimit > slowDown) + speedLimit = slowDown; + if (slowDownStop) + angle = -2.0f; + return 1; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/TankControl.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/TankControl.h new file mode 100644 index 000000000..678b732af --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/TankControl.h @@ -0,0 +1,38 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_TANKCONTROL_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_TANKCONTROL_H + +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { + +namespace io { class PlayerInput; } +namespace ai { + +class BAPAMoveTo; +class Bot; +class IPIControlInfo; +class IPIMobile; +class IPIPhysical; +class Information; + +// [INFERRED] a namespace: no vtable, no constructor, and the first argument is never `this`. +namespace TankControl +{ + int controlTowardsDirection(Information*, IPIControlInfo*, IPIMobile*, IPIPhysical*, io::PlayerInput*, const Vec2&, float, float, float, float, float); // 0x2D07B0; [INFERRED] ELF int + void turnTowardsDirection(float, float, bool, Information*, IPIMobile*, IPIControlInfo*, io::PlayerInput*, bool*); // 0x2D0E30; [INFERRED] ELF void + int resetControls(Bot*, io::PlayerInput*, bool, bool, bool, float); // 0x2D1010; [INFERRED] ELF int + int actionStatusDecision(Bot*, Information*, const Vec2&, float, BAPAMoveTo*, float&, float&, float&, float&); // 0x2D1390; [INFERRED] ELF int +} + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_TANKCONTROL_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/VehicleControlInline.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/VehicleControlInline.h new file mode 100644 index 000000000..0bd6c0423 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/VehicleControlInline.h @@ -0,0 +1,121 @@ +// [CHOSEN, not recovered] header-only helpers for the vehicle controls (CarControl, TankControl). +// libaidll.so has no symbol for any of them: each is the inline expansion the actionStatusDecision +// bodies spell out in place (ELF 0x2AB970 / 0x2D1390), written once here. No build-list entry. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_VEHICLECONTROLINLINE_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_VEHICLECONTROLINLINE_H + +#include "../Main/InformationManager.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { +namespace vehiclecontrol { + +inline Information* lookupInformation(unsigned int handle) +{ + return informationManager->getInformation(handle); +} + +// The engine's inline Vec2 normalise: kept within FLT_EPSILON of unit length, zeroed below +// FLT_EPSILON^2, else scaled by 1/sqrt (0x2ABA6F). +inline void normalizeVec2(Vec2& v) +{ + const float lengthSqr = v.x * v.x + v.y * v.y; + if (std::fabs(lengthSqr - 1.0f) < 1.1920929e-07f) + return; + if (std::fabs(lengthSqr) < 1.4210855e-14f) + { + v.x = 0.0f; + v.y = 0.0f; + return; + } + const float inverse = 1.0f / std::sqrt(lengthSqr); + v.x = v.x * inverse; + v.y = inverse * v.y; +} + +// The Vec3 variant: zeroed below FLT_EPSILON (0x2ABEDC). +inline void normalizeVec3(Vec3& v) +{ + const float lengthSqr = v.x * v.x + v.y * v.y + v.z * v.z; + if (std::fabs(lengthSqr - 1.0f) < 1.1920929e-07f) + return; + if (std::fabs(lengthSqr) < 1.1920929e-07f) + { + v.x = v.y = v.z = 0.0f; + return; + } + const float inverse = 1.0f / std::sqrt(lengthSqr); + v.x = v.x * inverse; + v.y = v.y * inverse; + v.z = inverse * v.z; +} + +// The zero test the bodies apply to trace hits: |c - 0| <= FLT_EPSILON for x, y and z (NaN is +// not zero). +inline bool isZeroVec3(const Vec3& v) +{ + const float epsilon = 1.1920929e-07f; + return std::fabs(v.x - 0.0f) <= epsilon && std::fabs(v.y - 0.0f) <= epsilon && std::fabs(v.z - 0.0f) <= epsilon; +} + +// |a - b| +inline float distanceVec3(const Vec3& a, const Vec3& b) +{ + const float dx = a.x - b.x; + const float dy = a.y - b.y; + const float dz = a.z - b.z; + return std::sqrt(dx * dx + dy * dy + dz * dz); +} + +// origin + direction * length +inline Vec3 alongFrom(const Vec3& origin, const Vec3& direction, float length) +{ + Vec3 v; + v.x = length * direction.x + origin.x; + v.y = length * direction.y + origin.y; + v.z = length * direction.z + origin.z; + return v; +} + +// origin - direction * length +inline Vec3 backFrom(const Vec3& origin, const Vec3& direction, float length) +{ + Vec3 v; + v.x = origin.x - length * direction.x; + v.y = origin.y - length * direction.y; + v.z = origin.z - length * direction.z; + return v; +} + +// The first row of a transformation, passed where the bodies hand the Mat4 itself to a +// `const Vec3&` parameter. +inline const Vec3& rightAxis(const Mat4& transformation) +{ + return *reinterpret_cast(&transformation.m[0]); +} + +// Folds a steering angle beyond +-pi/2 back to the reverse direction: sign(a) * (pi - |a|), with +// sign 0 for 0 and NaN (0x2AE3E1). +inline void reverseAngle(float& angle) +{ + const float magnitude = std::fabs(angle); + if (!(magnitude > 1.5707964f)) + return; + float sign = 1.0f; + if (!(angle > 0.0f)) + sign = (0.0f > angle) ? -1.0f : 0.0f; + angle = sign * (3.1415927f - magnitude); +} + +} // namespace vehiclecontrol +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_VEHICLECONTROLINLINE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.cpp index 380de49c3..003c41a62 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.cpp @@ -1,18 +1,26 @@ // Strategic simulation and supporting statistics. -// [FRONTIER] Remaining strategic phases and object-query paths stop by name. -// [RETIRE-WHEN: aidll-02-skeleton] Implement and validate the remaining strategic operations. +// [RETIRE-WHEN: aidll-02-skeleton] chooseStrategy's body is recovered; remove this note after +// the coordinator validates strategy loading and selection at runtime. #include "SAI.h" +#include +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF 0x330020, +// __tcf_0 0x330080, _GLOBAL__I 0x3300B0). The image has four more such triads for the TUs this file +// merges [INFERRED]: CommanderInterface (0x323420 / 0x323480 / 0x3234B0), ISAI and +// EnemyStatistics (0x323A40 / 0x323AA0 / 0x323AD0), SAIBotDCB (0x331F30 / 0x331F90 / 0x331FC0) +// and SAIBotSCB (0x332200 / 0x332260 / 0x332290). +#include +#include +#include #include -#include "../Main/AIDllFrontier.h" #include "../Main/AISettingsInterfaces.h" // IAISettings::getMaxNBots #include "../Main/BotBehaviourManager.h" // getBehaviourId, by name #include "../Main/CommonSingletonServer.h" #include "../AIKnowledge/BFInformationEnvironment.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/IPIUnit.h" #include "../AIKnowledge/UnitPredicate.h" @@ -20,13 +28,25 @@ #include "../AIBot/BotMain.h" #include "../AIBot/BotSquad.h" #include "../AIBot/SquadManager.h" +#include "../AIBot/SquadCoordinator.h" +#include "../AIBot/SquadMember.h" // setHavePath +#include "../AIBot/WaypointList.h" // updateBotPositions: +5 / getId +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" +#include "../AIStrategicEntity/AIStrategicArea.h" +#include "../Main/AIRandom.h" #include "../AIStrategicEntity/AIStrategicObject.h" #include "../AIStrategicEntity/AIStrategicObjectManager.h" #include "../AIStrategicMap/BotSpawner.h" +#include "Strategy.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../Main/IBotManager.h" +#include "../Main/StrategyManager.h" #include "../AIUtils/checkPointer.h" #include "../../../AIInterface/BFKnowledge/BFCommander.h" // request-denial callbacks #include "../../../AIInterface/BFKnowledge/BFGame.h" // IAIGame counters #include "../../../AIInterface/BFKnowledge/AIPlayer.h" // IAIPlayer::setSpawnGroup +#include "../../../AIInterface/BFKnowledge/BFGameEffector.h" // IAIGameEffector::respawnBot #include "../../../AIInterface/BFKnowledge/BFTimer.h" // IBFTimer::getGameTime #include "../../../../Core/Debug.h" // update's shipped invalid-state diagnostic @@ -34,6 +54,31 @@ namespace dice { namespace hfe { namespace ai { +namespace { + +// ELF: std::list<(anonymous)::SquareInfo> nodes carry 8 bytes, {int +0, float +4}; list::sort +// (0x330C40, merge 0x3317F0) orders ascending by the float. Member names [INFERRED]. +struct SquareInfo +{ + int m_index; // strategic-object index (+0xF0 of the object) + float m_value; + bool operator<(const SquareInfo& other) const { return m_value < other.m_value; } +}; + +// ELF heap helpers 0x330FE0 / 0x3311F0: the object with the smallest assigned part of its wanted +// strength is on top. The side is the comparator's only state. +struct sobOrdering +{ + explicit sobOrdering(int side) : m_side(side) {} + bool operator()(const AIStrategicObject* a, const AIStrategicObject* b) const + { + return a->getAssignedPartOfWantedStrength(m_side) > b->getAssignedPartOfWantedStrength(m_side); + } + int m_side; +}; + +} // namespace + // The concrete callback names and signatures are ELF-attested. Their source-file placement here // is [INFERRED]; only SAI.cpp is attested for this part of the strategic subsystem. class SAIBotDCB : public IBotDeathCallBack @@ -186,34 +231,55 @@ CommanderInterface::~CommanderInterface() } -void CommanderInterface::giveAttackOrder(const Vec3&, SquadCoordinator*) +// ELF IBFCommander 0x10: (position, squad id + 1, side + 1, no target); side is read first. +void CommanderInterface::giveAttackOrder(const Vec3& position, SquadCoordinator* squad) { - BF2_AI_FRONTIER("dice::hfe::ai::CommanderInterface::giveAttackOrder (SquadCoordinator)"); + const int side = squad->getSide() + 1; + const int id = squad->getSquadId() + 1; + static_cast(CommonSingletonServer::m_iBFCommander)->giveAttackOrder(position, id, side, 0); } -void CommanderInterface::giveMoveOrder(const Vec3&, SquadCoordinator*) +// ELF IBFCommander 0x14: (position, squad id + 1, side + 1, no target); side is read first. +void CommanderInterface::giveMoveOrder(const Vec3& position, SquadCoordinator* squad) { - BF2_AI_FRONTIER("dice::hfe::ai::CommanderInterface::giveMoveOrder (SquadCoordinator)"); + const int side = squad->getSide() + 1; + const int id = squad->getSquadId() + 1; + static_cast(CommonSingletonServer::m_iBFCommander)->giveMoveOrder(position, id, side, 0); } -void CommanderInterface::giveDefendOrder(const Vec3&, SquadCoordinator*) +// ELF IBFCommander 0x18: (position, squad id + 1, side + 1, no target); side is read first. +void CommanderInterface::giveDefendOrder(const Vec3& position, SquadCoordinator* squad) { - BF2_AI_FRONTIER("dice::hfe::ai::CommanderInterface::giveDefendOrder (SquadCoordinator)"); + const int side = squad->getSide() + 1; + const int id = squad->getSquadId() + 1; + static_cast(CommonSingletonServer::m_iBFCommander)->giveDefendOrder(position, id, side, 0); } -void CommanderInterface::giveAttackOrder(const Vec3&, Bot*) +// ELF IBFCommander 0x10: (position, the bot squad's id +4, the bot's side, no target) - no +1 +// here, unlike the squad overloads; the squad is read first. +void CommanderInterface::giveAttackOrder(const Vec3& position, Bot* bot) { - BF2_AI_FRONTIER("dice::hfe::ai::CommanderInterface::giveAttackOrder (Bot)"); + BotSquad* const squad = bot->getBotSquad(); + const int side = bot->getSide(); + static_cast(CommonSingletonServer::m_iBFCommander)->giveAttackOrder(position, squad->getSquadId(), side, 0); } -void CommanderInterface::giveMoveOrder(const Vec3&, Bot*) +// ELF IBFCommander 0x14: (position, the bot squad's id +4, the bot's side, no target) - no +1 +// here, unlike the squad overloads; the squad is read first. +void CommanderInterface::giveMoveOrder(const Vec3& position, Bot* bot) { - BF2_AI_FRONTIER("dice::hfe::ai::CommanderInterface::giveMoveOrder (Bot)"); + BotSquad* const squad = bot->getBotSquad(); + const int side = bot->getSide(); + static_cast(CommonSingletonServer::m_iBFCommander)->giveMoveOrder(position, squad->getSquadId(), side, 0); } -void CommanderInterface::giveDefendOrder(const Vec3&, Bot*) +// ELF IBFCommander 0x18: (position, the bot squad's id +4, the bot's side, no target) - no +1 +// here, unlike the squad overloads; the squad is read first. +void CommanderInterface::giveDefendOrder(const Vec3& position, Bot* bot) { - BF2_AI_FRONTIER("dice::hfe::ai::CommanderInterface::giveDefendOrder (Bot)"); + BotSquad* const squad = bot->getBotSquad(); + const int side = bot->getSide(); + static_cast(CommonSingletonServer::m_iBFCommander)->giveDefendOrder(position, squad->getSquadId(), side, 0); } @@ -226,6 +292,7 @@ ISAI::~ISAI() // the unwind path the // constructor's possible throw needs is the other hundred bytes. +// ELF 0x3239B0. SAI* ISAI::create(int side, int gridWidth, int gridHeight, Vec2 min, Vec2 max) { return new SAI(side, gridWidth, gridHeight, min, max); @@ -234,9 +301,9 @@ SAI* ISAI::create(int side, int gridWidth, int gridHeight, Vec2 min, Vec2 max) // Starts the three integer states at -1 and the float accumulator at zero. SAI::BotInfo::BotInfo(Bot* bot) : m_bot(bot) - , m_int04(-1) - , m_int08(-1) - , m_int0C(-1) + , m_currentlyOrderedSquare(-1) + , m_lastOrderedSquare(-1) + , m_currentlyOccupiedSquare(-1) , m_float10(0.0f) , m_double14(0.0) { @@ -255,23 +322,23 @@ void SAI::clearStates(float* a, float* b) b[43] = 1.0f; } -// Creates strategic state for side. Grid dimensions and bounds are retained in the signature but unused. +// ELF 0x323AF0 (C2; C1 0x3249A0). Creates strategic state for side. Grid dimensions and bounds are +// retained in the signature but unused. +0xE0 is not constructed (no store in either body). SAI::SAI(int side, int, int, Vec2, Vec2) : m_flagAC(true) - , m_behaviourIdle(0) - , m_behaviourMoveTo(0) - , m_behaviourAvoid(0) - , m_behaviourFire(0) + , m_idleBehaviourId(0) + , m_moveToBehaviourId(0) + , m_avoidBehaviourId(0) + , m_fireBehaviourId(0) , m_intD8(0) , m_intDC(0) - , m_intE0(0) // The strategy cursor starts at `m_strategies.end`, which on a freshly built empty vector is // the null `finish` pointer. The binary copies the vector's finish word into it. , m_activeStrategy(0) , m_enemyStats(0) , m_friendlyStats(0) , m_int18C(19) - , m_float190(-992.0f) + , m_float190(-1000.0f) , m_side(side) , m_sideMask(1 << side) // the other side'S BIT, and the expression only has two answers - this is a two-sided game. @@ -294,10 +361,10 @@ SAI::SAI(int side, int, int, Vec2, Vec2) { m_commander = checkPointer(new CommanderInterface()); - m_behaviourIdle = BotBehaviourManager::m_instance->getBehaviourId(std::string("Idle")); - m_behaviourMoveTo = BotBehaviourManager::m_instance->getBehaviourId(std::string("MoveTo")); - m_behaviourAvoid = BotBehaviourManager::m_instance->getBehaviourId(std::string("Avoid")); - m_behaviourFire = BotBehaviourManager::m_instance->getBehaviourId(std::string("Fire")); + m_idleBehaviourId = BotBehaviourManager::m_instance->getBehaviourId(std::string("Idle")); + m_moveToBehaviourId = BotBehaviourManager::m_instance->getBehaviourId(std::string("MoveTo")); + m_avoidBehaviourId = BotBehaviourManager::m_instance->getBehaviourId(std::string("Avoid")); + m_fireBehaviourId = BotBehaviourManager::m_instance->getBehaviourId(std::string("Fire")); // four deadlines off one clock read. Three at a minute out and one at ten seconds, with the // fifth left at zero - so three slow reviews and one fast one, all stamped at construction. @@ -334,19 +401,32 @@ SAI::SAI(int side, int, int, Vec2, Vec2) const IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); - m_botInfo.resize(settings->getMaxNBots()); + m_bots.resize(settings->getMaxNBots()); for (int i = 0; i < settings->getMaxNBots(); ++i) - m_botInfo[i] = 0; + m_bots[i] = 0; } -// [FRONTIER] Strategy and distribution operations remain incomplete. -// [FRONTIER] Destruction stops until ordered teardown is implemented. -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -// Replace each stop when its corresponding behavior is recovered. +// ELF 0x3257A0 (D2; D1 0x325E70, D0 0x326540; from BF2AI::clear): deletes the commander interface +// (+0x1F8), the two EnemyStatistics (+0x124/+0x128), delete[]s the four state rows (+0x1E4..+0x1F0), +// each tested for null; every container member then goes in reverse declaration order. The +// BotInfo pointers in m_bots are not deleted (no BotInfo destructor call in the body). SAI::~SAI() { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::~SAI"); + if (m_commander) + delete m_commander; + if (m_enemyStats) + delete m_enemyStats; + if (m_friendlyStats) + delete m_friendlyStats; + if (m_stateA) + delete[] m_stateA; + if (m_stateB) + delete[] m_stateB; + if (m_stateC) + delete[] m_stateC; + if (m_stateD) + delete[] m_stateD; } @@ -360,9 +440,17 @@ void SAI::setMapYDimension(int) } -void SAI::addStrategy(Strategy*) +// ELF 0x326C10: appends {0, 0, 0, 1, strategy} and points the active strategy at the first one. +void SAI::addStrategy(Strategy* strategy) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::addStrategy"); + StrategyContainer container; + container.m_f00 = 0.0f; + container.m_f04 = 0.0f; + container.m_startTime = 0.0f; + container.m_i0C = 1; + container.strategy = strategy; + m_strategies.push_back(container); + m_activeStrategy = &m_strategies[0]; } // One resumable pass, with a budget check after each @@ -375,7 +463,7 @@ void SAI::update(double budget) const double start = timer->getUpdateTime(); updateRequestDenyTimers(); - for (std::vector::iterator it = m_botInfo.begin(); it != m_botInfo.end(); ++it) + for (std::vector::iterator it = m_bots.begin(); it != m_bots.end(); ++it) { if (*it) { @@ -553,19 +641,83 @@ void SAI::addBot(Bot* bot) bot->setSpawnCallBack(checkPointer(new SAIBotSCB(bot, this))); } -void SAI::setBotIsDead(int) +// ELF 0x328D10: handleDeadBot(botId). +void SAI::setBotIsDead(int botId) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::setBotIsDead"); + handleDeadBot(botId); +} + +// ELF 0x328DB0: a known bot leaves the strategic bookkeeping (BotInfo::remove); its assigned +// object (m_currentlyOrderedSquare, read before the removal) and spawn kit (+0x104) are recorded in the dead-bot +// map (+0x5C, insert_unique), its player's spawn group is reset to 0 (IAIPlayer +0x38), and the +// record is marked dead. +void SAI::handleDeadBot(int botId) +{ + BotInfo* const info = m_bots[botId]; + if (!info) + return; + const int kit = info->m_bot->getSpawnKit(); + const int object = m_bots[botId]->m_currentlyOrderedSquare; + m_bots[botId]->remove(this); + m_map5C.insert(std::make_pair(botId, std::make_pair(object, kit))); + m_bots[botId]->m_bot->getPlayer()->setSpawnGroup(0); + m_bots[botId]->setAsDead(this); } -void SAI::setBotIsAlive(int) +// ELF 0x328AE0: a known, living bot is placed at the closest strategic object to its current +// equipment's position (getClosestObject(pos, equipment type, vehicle number or -1, side)) and +// leaves the dead-bot map; the map is searched linearly (`cmpl %ecx,0x10(%edx)`) and the first +// match erased. The first spawn after a reset (+0xAC) resets the bridges. +void SAI::setBotIsAlive(int botId) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::setBotIsAlive"); + if (!m_bots[botId]) + return; + if (m_flagAC) + { + AIStrategicObjectManager::getInstance()->resetBridges(); + m_flagAC = false; + } + if (m_bots[botId]->m_bot->isDead()) + return; + Information* const information = + informationManager->getInformation(m_bots[botId]->m_bot->getCurrentEquipment()); + if (!information || !information->getUnit()) + return; + int vehicle = -1; + if (information->getMobile()) + vehicle = information->getMobile()->getVehicleNumber(); + const int equipment = information->getUnit()->getEquipmentType(); + const Vec3& position = information->getPosition(); + AIStrategicObject* const object = + AIStrategicObjectManager::getInstance()->getClosestObject(position, equipment, vehicle, m_side); + m_bots[botId]->respawn(object, this); + for (std::map >::iterator it = m_map5C.begin(); it != m_map5C.end(); ++it) + { + if (it->first == botId) + { + m_map5C.erase(it); + break; + } + } } -void SAI::removeBot(Bot*) +// ELF 0x329300: a dead bot only leaves the dead-bot map (linear key search, first match), a +// living one leaves the bookkeeping (BotInfo::remove); then its record is deleted. +void SAI::removeBot(Bot* bot) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::removeBot"); + const int id = bot->getBotId(); + if (!m_bots[id]) + return; + std::map >::iterator it = m_map5C.begin(); + for (; it != m_map5C.end(); ++it) + if (it->first == id) + break; + if (it != m_map5C.end()) + m_map5C.erase(it); + else + m_bots[id]->remove(this); + delete m_bots[id]; + m_bots[id] = 0; } // Both test the requested bit; x86 masks shift count. @@ -580,29 +732,79 @@ bool SAI::isFriend(int side) const return (static_cast(m_sideMask) & (1u << (side & 31))) != 0; } +// ELF 0x329450 / 0x329460 / 0x329470 / 0x329480: `lea 0x12C/0x144/0x15C/0x174(this)`; the +// index argument is ignored. The "types" rows hold the float counts the SAI accumulates +// (`+= 1.0f`), so they are returned as float* (the shared declaration said int*). float* SAI::getEnemyStrengths(int) const { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::getEnemyStrengths"); + return const_cast(m_enemyStrengths); } -int* SAI::getEnemyTypes(int) const +float* SAI::getEnemyTypes(int) const { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::getEnemyTypes"); + return const_cast(m_enemyCounts); } float* SAI::getFriendlyStrengths(int) const { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::getFriendlyStrengths"); + return const_cast(m_friendlyStrengths); +} + +float* SAI::getFriendlyTypes(int) const +{ + return const_cast(m_friendlyCounts); } -int* SAI::getFriendlyTypes(int) const +// ELF 0x32D5F0: the bot's squad member (by player id, IBotManager::getBot +0x14) forgets its +// path, then handleChangingBot. +void SAI::setBotHasChangedEquipment(int botId) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::getFriendlyTypes"); + Bot* const bot = IBotManager::instance->getBot(botId); + SquadMember* const member = SquadManager::m_instance->getSquadMember(bot->getPlayerId(), m_side); + if (member) + member->setHavePath(false); + handleChangingBot(botId); } -void SAI::setBotHasChangedEquipment(int) +// ELF 0x328FE0: a bot that is not in the free set gives up its assignment - an assigned object +// (m_currentlyOrderedSquare) is left through removeAssigned(release) + free(false), else a current object +// (m_currentlyOccupiedSquare) through free(true). Its last ordered square becomes -1, and when its current +// equipment's closest strategic object differs from the current one it moves there (occupy). +void SAI::handleChangingBot(int botId) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::setBotHasChangedEquipment"); + if (!m_bots[botId]) + return; + if (m_freeBots.find(botId) == m_freeBots.end()) + { + BotInfo* const info = m_bots[botId]; + if (info->m_currentlyOrderedSquare != -1) + { + AIStrategicObject* const object = + AIStrategicObjectManager::getInstance()->getStrategicObject(info->m_currentlyOrderedSquare); + m_bots[botId]->removeAssigned(object, true, this); + m_bots[botId]->free(false, this); + } + else if (info->m_currentlyOccupiedSquare != -1) + { + info->free(true, this); + } + } + m_bots[botId]->setLastOrderedSquare(-1); + Information* const information = + informationManager->getInformation(m_bots[botId]->m_bot->getCurrentEquipment()); + if (!information || !information->getUnit()) + return; + IPIMobile* const mobile = information->getMobile(); + AIStrategicObjectManager* const manager = AIStrategicObjectManager::getInstance(); + int vehicle = -1; + if (mobile) + vehicle = mobile->getVehicleNumber(); + const int equipment = information->getUnit()->getEquipmentType(); + AIStrategicObject* const closest = + manager->getClosestObject(information->getPosition(), equipment, vehicle, m_side); + if (closest->getIndex() == m_bots[botId]->m_currentlyOccupiedSquare) + return; + m_bots[botId]->occupy(manager->getStrategicObject(m_bots[botId]->m_currentlyOccupiedSquare), closest, this); } // find, update the second member of the existing pair, or do nothing. @@ -622,9 +824,20 @@ const std::map >& SAI::getDeadBots() const return m_map5C; } -void SAI::setPlayerIsCommander(bool) +// ELF 0x326CC0: a player giving up the commander seat (true -> false) unassigns the side's +// squads and restarts the commander timers: +0x68/+0x70/+0x78 = now + 60, +0x80 = now + 10. +void SAI::setPlayerIsCommander(bool isCommander) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::setPlayerIsCommander"); + if (!isCommander && m_flag1D1) + { + SquadManager::m_instance->unAssignSquads(m_side); + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + m_time68 = now + 60.0f; + m_time70 = now + 60.0f; + m_time78 = now + 60.0f; + m_time80 = now + 10.0f; + } + m_flag1D1 = isCommander; } // byte getter at +0x1D1 / +0x221. @@ -633,24 +846,126 @@ bool SAI::isPlayerCommander() return m_flag1D1; } -bool SAI::playerRequestsArtillery(int, Vec3) +// ELF 0x327420. Ignored while a player commands the side. Without artillery (IBFCommander +0x38 +// gameHasArtillery, +0x3C anyArtilleryPiecesLeft) an "unavailable" answer (type 2) is queued; with +// the artillery timer (+0x68) running a denial (type 1). Otherwise the timer re-arms 60 s ahead, the +// engine commander fires (+0x24, the request's x/z) and the squads are warned. +// [CHOSEN, not recovered] the shipped body never materialises a return value (eax is whatever the +// last call left); the courier passes it on and the engine ignores it. This build answers false. +bool SAI::playerRequestsArtillery(int playerId, Vec3 position) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::playerRequestsArtillery"); + if (m_flag1D1) + return false; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + IBFCommander* const commander = static_cast(CommonSingletonServer::m_iBFCommander); + if (commander->gameHasArtillery(m_side) && commander->anyArtilleryPiecesLeft(m_side)) + { + if (now > m_time68) + { + m_time68 = now + 60.0f; + Vec2 xz; + xz.x = position.x; + xz.y = position.z; + commander->fireArtillery(m_side, playerId, xz); + SquadManager::m_instance->incomingArtillery(position, m_side); + } + else + { + DenyRequest* const request = new DenyRequest(); + request->m_type = 1; + request->m_deadline = now + 2.0f + static_cast(AIRandom::m_instance->next()) * 2.3283064e-10f * 3.0f; + request->m_playerId = playerId; + m_denyRequests.push_back(request); + } + } + else + { + DenyRequest* const request = new DenyRequest(); + request->m_type = 2; + request->m_deadline = now + 2.0f + static_cast(AIRandom::m_instance->next()) * 2.3283064e-10f * 3.0f; + request->m_playerId = playerId; + m_denyRequests.push_back(request); + } + return false; } -bool SAI::playerRequestsUav(int, Vec3) +// ELF 0x327720. Ignored while a player commands the side; the UAV timer (+0x80) re-arms 30 s +// ahead and the engine commander sends it (+0x28), otherwise a denial (type 3) is queued. +// [CHOSEN, not recovered] no shipped return value; see playerRequestsArtillery. +bool SAI::playerRequestsUav(int playerId, Vec3 position) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::playerRequestsUav"); + if (m_flag1D1) + return false; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (now > m_time80) + { + m_time80 = now + 30.0f; + Vec2 xz; + xz.x = position.x; + xz.y = position.z; + static_cast(CommonSingletonServer::m_iBFCommander)->sendUav(m_side, playerId, xz); + } + else + { + DenyRequest* const request = new DenyRequest(); + request->m_type = 3; + request->m_deadline = now + 2.0f + static_cast(AIRandom::m_instance->next()) * 2.3283064e-10f * 3.0f; + request->m_playerId = playerId; + m_denyRequests.push_back(request); + } + return false; } -bool SAI::playerRequestsSupply(int, Vec3) +// ELF 0x3278C0. As the UAV request with the supply timer (+0x70, 60 s), dropSupply (+0x2C) and +// denial type 0. [CHOSEN, not recovered] no shipped return value; see playerRequestsArtillery. +bool SAI::playerRequestsSupply(int playerId, Vec3 position) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::playerRequestsSupply"); + if (m_flag1D1) + return false; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (now > m_time70) + { + m_time70 = now + 60.0f; + Vec2 xz; + xz.x = position.x; + xz.y = position.z; + static_cast(CommonSingletonServer::m_iBFCommander)->dropSupply(m_side, playerId, xz); + } + else + { + DenyRequest* const request = new DenyRequest(); + request->m_type = 0; + request->m_deadline = now + 2.0f + static_cast(AIRandom::m_instance->next()) * 2.3283064e-10f * 3.0f; + request->m_playerId = playerId; + m_denyRequests.push_back(request); + } + return false; } -bool SAI::playerRequestsVehicleDrop(int, Vec3) +// ELF 0x327A60. As the UAV request with the vehicle-drop timer (+0x78, 60 s), dropVehicle (+0x30) +// and denial type 4. [CHOSEN, not recovered] no shipped return value; see playerRequestsArtillery. +bool SAI::playerRequestsVehicleDrop(int playerId, Vec3 position) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::playerRequestsVehicleDrop"); + if (m_flag1D1) + return false; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (now > m_time78) + { + m_time78 = now + 60.0f; + Vec2 xz; + xz.x = position.x; + xz.y = position.z; + static_cast(CommonSingletonServer::m_iBFCommander)->dropVehicle(m_side, playerId, xz); + } + else + { + DenyRequest* const request = new DenyRequest(); + request->m_type = 4; + request->m_deadline = now + 2.0f + static_cast(AIRandom::m_instance->next()) * 2.3283064e-10f * 3.0f; + request->m_playerId = playerId; + m_denyRequests.push_back(request); + } + return false; } void SAI::updateRequestDenyTimers() @@ -707,91 +1022,349 @@ void SAI::updateRequestDenyTimers() } } +// ELF 0x326D60. The AI commander fires artillery when the player is not the commander, the game +// has more than one bot slot, the side has artillery pieces left and both timers (+0x68, +0x88) +// have expired. +0x88 is re-armed 10 s ahead first. A base under hostile takeover (virtual +0x6C) +// is shelled at a random point unless friendlies are within the safe distance or the 1-in-10 roll +// prefers camping humans; otherwise camping humans are the target. Firing re-arms +0x68 60 s +// ahead, asks the engine commander (+0x24 fireArtillery(side, -1, xz)) and warns the squads. +// [CHOSEN, not recovered] the roll is compared in double; the ELF compares the x87 product. void SAI::checkCommanderUseArtillery() { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::checkCommanderUseArtillery"); + bool singleSlot = false; + if (CommonSingletonServer::m_iaiSettings) + singleSlot = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots() - 1 <= 0; + if (m_flag1D1 || singleSlot) + return; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + IBFCommander* const commander = static_cast(CommonSingletonServer::m_iBFCommander); + if (!commander->gameHasArtillery(m_side) || !commander->anyArtilleryPiecesLeft(m_side)) + return; + if (!(now > m_time68) || !(now > m_time88)) + return; + m_time88 = now + 10.0f; + SquadManager* const squads = SquadManager::m_instance; + Vec2 position; + position.x = 0.0f; + position.y = 0.0f; + AIStrategicObject* base = 0; + if (hostileTakeoveInProgress(base, position)) + { + const double roll = static_cast(AIRandom::m_instance->next()) * 2.3283064e-10f; + if (roll > 0.1f) + { + IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + Vec3 target; + target.x = position.x; + target.y = terrain->getTerrainAltitude(position.x, position.y); + target.z = position.y; + const float safe = squads->getArtillerySafeDistance(); + if (!squads->friendliesCloseTo(target, safe, m_side)) + { + m_time68 = now + 60.0f; + commander->fireArtillery(m_side, -1, position); + squads->incomingArtillery(target, m_side); + return; + } + } + } + if (!squads->haveCampingHumans(m_side, position)) + return; + IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + Vec3 target; + target.x = position.x; + target.y = terrain->getTerrainAltitude(position.x, position.y); + target.z = position.y; + m_time68 = now + 60.0f; + commander->fireArtillery(m_side, -1, position); + squads->incomingArtillery(target, m_side); +} + +// ELF 0x327210. The first strategic object that is a control point (hasObjectTypeFlag(16)), +// being taken over by the enemy of this side and with a takeover counter below 0.75 is returned +// in base; position becomes a uniform random point of the box around its position (slot 3), +// mirrored at the area centre (+0x110): centre + 2 (position - centre) u, x then y. +bool SAI::hostileTakeoveInProgress(AIStrategicObject*& base, Vec2& position) +{ + const std::vector& objects = + AIStrategicObjectManager::getInstance()->getStrategicObjects(); + for (std::vector::const_iterator it = objects.begin(); it != objects.end(); ++it) + { + AIStrategicObject* const object = *it; + if (!object || !object->hasObjectTypeFlag(static_cast(16))) + continue; + if (!object->isEnemyTakingOverBase(m_side)) + continue; + if (!(0.75f > object->getControlPointTakeOverCounter())) + continue; + base = object; + const Vec2 centre = static_cast(object)->m_centre; + const Vec2 corner = object->getPosition(m_side); + const double u = static_cast(AIRandom::m_instance->next()) * 2.3283064e-10f; + position.x = static_cast(centre.x + (static_cast(corner.x) - centre.x) * 2.0 * u); + const double v = static_cast(AIRandom::m_instance->next()) * 2.3283064e-10f; + position.y = static_cast(centre.y + (static_cast(corner.y) - centre.y) * 2.0 * v); + return true; + } + return false; +} + +// ELF 0x3270A0: the closest object (getClosestObject(pos, side)) must be an owned control point +// (slot 19, type 16). Its control point (area +0x13C) gives centre and radius through IAIGame +// (+0x28); a positive maxRadius above that radius replaces it (`fcmovbe`). Inside means a squared +// 3-D distance below the squared radius and an active point; then object is the closest one. +bool SAI::isPosInsideOwnedControlPoint(AIStrategicObject*& object, Vec3 position, float maxRadius) +{ + bool inside = false; + AIStrategicObject* const closest = AIStrategicObjectManager::getInstance()->getClosestObject(position, m_side); + if (!closest->hasObjectTypeFlag(AIStrategicObject::ControlPoint) || closest->getStatus(m_side) != StatusMap::Owned) + return inside; + float radius = 0.0f; + Vec3 centre; + centre.x = 0.0f; + centre.y = 0.0f; + centre.z = 0.0f; + bool active; + static_cast(CommonSingletonServer::m_iaiGame)->getControlPointInfo( + static_cast(closest)->m_controlPointId, centre, radius, active); + if (maxRadius > 0.0f) + radius = maxRadius <= radius ? radius : maxRadius; + radius = radius * radius; + const float dx = centre.x - position.x; + const float dy = centre.y - position.y; + const float dz = centre.z - position.z; + const float distance = dx * dx + dy * dy + dz * dz; + if (active && radius > distance) + { + inside = true; + object = closest; + } + return inside; +} + +// ELF 0x328590: any strategic object (not only control points) the side owns. +bool SAI::haveAnyOwnedCps(int side) +{ + bool owned = false; + const std::vector& objects = + AIStrategicObjectManager::getInstance()->getStrategicObjects(); + for (std::vector::const_iterator it = objects.begin(); it != objects.end(); ++it) + { + if (*it && (*it)->getStatus(side) == StatusMap::Owned) + { + owned = true; + break; + } + } + return owned; +} + +// ELF 0x3285F0: an owned object whose control point (area +0x13C, -1 for none) the game reports +// as active. The position and radius outputs are zeroed once, before the loop. +bool SAI::haveAnyOwnedAndTakeableCps(int side) +{ + bool found = false; + const std::vector& objects = + AIStrategicObjectManager::getInstance()->getStrategicObjects(); + float radius = 0.0f; + Vec3 position; + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; + for (std::vector::const_iterator it = objects.begin(); it != objects.end(); ++it) + { + AIStrategicObject* const object = *it; + if (!object || object->getStatus(side) != StatusMap::Owned) + continue; + bool active = false; + const unsigned int cp = static_cast(object)->m_controlPointId; + if (cp != static_cast(-1)) + static_cast(CommonSingletonServer::m_iaiGame)->getControlPointInfo(cp, position, radius, active); + if (active) + { + found = true; + break; + } + } + return found; +} + +// ELF 0x3286C0: false as soon as an active control point is not owned by the side. +bool SAI::ownAllTakeableCps(int side) +{ + bool all = true; + const std::vector& objects = + AIStrategicObjectManager::getInstance()->getStrategicObjects(); + float radius = 0.0f; + Vec3 position; + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; + for (std::vector::const_iterator it = objects.begin(); it != objects.end(); ++it) + { + AIStrategicObject* const object = *it; + if (!object || object->getStatus(side) == StatusMap::Owned) + continue; + bool active = false; + const unsigned int cp = static_cast(object)->m_controlPointId; + if (cp != static_cast(-1)) + static_cast(CommonSingletonServer::m_iaiGame)->getControlPointInfo(cp, position, radius, active); + if (active) + { + all = false; + break; + } + } + return all; } -bool SAI::hostileTakeoveInProgress(AIStrategicObject*&, Vec2&) +// preserve unAssignSquads' full integer return. +// The caller's full-EAX additions establish the count contract; the body remains stopped. +// ELF 0x32D680: the object's index (+0xF0) and the side go to SquadManager::unAssignSquads. +int SAI::releaseSquadsFromObject(int object, int side) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::hostileTakeoveInProgress"); + AIStrategicObject* const target = AIStrategicObjectManager::getInstance()->getStrategicObject(object); + return SquadManager::m_instance->unAssignSquads(target->getIndex(), side); } -bool SAI::isPosInsideOwnedControlPoint(AIStrategicObject*&, Vec3, float) +// ELF 0x32D6D0: the unit leaves the object's assigned set and SAI's occupied set, then +// m_bots[*it]->free(false) runs - with the iterator removeAssigned has already advanced, so +// the image frees the *next* assigned unit (`movl (%esi),%eax` reloads it after the call). +// [CHOSEN, not recovered] When the released unit was the last one, the image reads the old +// libstdc++ header node's stale value as a bot index; here that second call is skipped. +// The side argument is unused; the image answers 1. +bool SAI::releaseUnitFromObject(int object, std::set::iterator& it, int) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::isPosInsideOwnedControlPoint"); + AIStrategicObject* const target = AIStrategicObjectManager::getInstance()->getStrategicObject(object); + m_bots[*it]->removeAssigned(target, it, true, this); + if (it != target->getAssignedUnits(m_side).end()) + m_bots[*it]->free(false, this); + return true; } -bool SAI::haveAnyOwnedCps(int) +// ELF 0x329250: erase the bot from the set at +0xF0; answers whether it was there. +bool SAI::foundDeadBot(int botId) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::haveAnyOwnedCps"); + std::set::iterator it = m_setF0.find(botId); + if (it == m_setF0.end()) + return false; + m_setF0.erase(it); + return true; } -bool SAI::haveAnyOwnedAndTakeableCps(int) +// ELF 0x32D770: membership in the set at +0xB0. +bool SAI::hasChangedEquipment(int botId) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::haveAnyOwnedAndTakeableCps"); + return m_setB0.find(botId) != m_setB0.end(); } -bool SAI::ownAllTakeableCps(int) +// ELF 0x32D7D0: erase from the set at +0xB0 when present. +void SAI::equipmentChangedFinished(int botId) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::ownAllTakeableCps"); + std::set::iterator it = m_setB0.find(botId); + if (it != m_setB0.end()) + m_setB0.erase(it); } -// preserve unAssignSquads' full integer return. -// The caller's full-EAX additions establish the count contract; the body remains stopped. -int SAI::releaseSquadsFromObject(int, int) +// ELF 0x32D870: answers the bot's current object index (m_currentlyOccupiedSquare, read first). +int SAI::assignBot(std::set::iterator& it, int object, int botId, bool attacker) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::releaseSquadsFromObject"); + const int current = m_bots[botId]->m_currentlyOccupiedSquare; + AIStrategicObject* const target = AIStrategicObjectManager::getInstance()->getStrategicObject(object); + m_bots[botId]->assignToObject(it, target, attacker, this); + return current; } -void SAI::releaseUnitFromObject(int, std::map::iterator&, int) +// ELF 0x32E830: the byte at +0x1CF. +bool SAI::strategicObjectsHasChanged() { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::releaseUnitFromObject"); + return m_flag1CF; } -void SAI::foundDeadBot(int) +// ELF 0x32E840: the id is appended to the teleporter list (+0x110). +void SAI::registerTeleporter(int id) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::foundDeadBot"); + m_list110.push_back(id); } -bool SAI::hasChangedEquipment(int) +// ELF 0x32E380: the container's first two floats (last distribution score, latest score); zero for +// an index past the end. +Vec2 SAI::getStrategyHeat(unsigned int index) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::hasChangedEquipment"); + Vec2 heat; + heat.x = 0.0f; + heat.y = 0.0f; + if (index < m_strategies.size()) + { + heat.x = m_strategies[index].m_f00; + heat.y = m_strategies[index].m_f04; + } + return heat; } -void SAI::equipmentChangedFinished(int) +// ELF 0x32E420: one " " line per container that has a strategy. +std::string SAI::listStrategies() { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::equipmentChangedFinished"); + std::ostringstream out; + for (unsigned int i = 0; i < m_strategies.size(); ++i) + { + if (m_strategies[i].strategy) + out << i << " " << m_strategies[i].strategy->getName() << std::endl; + } + return out.str(); } -void SAI::assignBot(std::map::iterator&, int, int, bool) +// ELF 0x32EA90: the active container's strategy, unguarded. +Strategy* SAI::getActiveStrategy() { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::assignBot"); + return m_activeStrategy->strategy; } -bool SAI::strategicObjectsHasChanged() +// ELF 0x32EAB0: the active container's three floats (zero, with no active container) and its +// strategy. The strategy is read even when the cursor is at end(), as shipped. +Strategy* SAI::getActiveStrategy(float& a, float& b, float& c) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::strategicObjectsHasChanged"); + if (m_activeStrategy != m_strategies.data() + m_strategies.size()) + { + a = m_activeStrategy->m_f00; + b = m_activeStrategy->m_f04; + c = m_activeStrategy->m_startTime; + } + else + { + a = 0.0f; + b = 0.0f; + c = 0.0f; + } + return m_activeStrategy->strategy; } -void SAI::registerTeleporter(int) +// ELF 0x32E2D0: membership in the free set (+0x44). +bool SAI::isBotFree(int botId) const { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::registerTeleporter"); + return m_freeBots.find(botId) != m_freeBots.end(); } -float SAI::getStrategyHeat(unsigned int) +// ELF 0x32E320: membership in the occupied set (+0xFC). +bool SAI::isBotAssigned(int botId) const { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::getStrategyHeat"); + return m_assignedBots.find(botId) != m_assignedBots.end(); } -void SAI::listStrategies() +// ELF 0x32CEE0: empty. +void SAI::updateMap(double) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::listStrategies"); } -int SAI::getActiveStrategy() +// ELF 0x329490: one 1.0f modifier per behaviour (IAISettings +0xC getNumberOfBehaviours); the +// caller owns the array. +float* SAI::createUnitMods() const { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::getActiveStrategy"); + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getNumberOfBehaviours(); + float* const mods = checkPointer(new float[count]); + for (int i = 0; i < count; ++i) + mods[i] = 1.0f; + return mods; } // insert (point,1), increment only on duplicate. @@ -804,24 +1377,34 @@ void SAI::addSpawnToPoint(int point) ++inserted.first->second; } -int SAI::getSpawnsToPoint(int) const +// ELF 0x32EF90: the spawn count of the point (map +0x1D8), 0 when unknown. +int SAI::getSpawnsToPoint(int point) const { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::getSpawnsToPoint"); + std::map::const_iterator it = m_map1D8.find(point); + if (it == m_map1D8.end()) + return 0; + return it->second; } -Vec3 SAI::getBotCurrentPos(int) const +// ELF 0x32E240 / 0x32E270 / 0x32E2A0: the bot's current object (m_currentlyOccupiedSquare), ordered object +// (m_currentlyOrderedSquare) and last ordered square (m_lastOrderedSquare) - indices, not positions (eax, no sret). An unknown +// bot answers -22, -44 and -1 (`movl $0xffffffea/$0xffffffd4/$0xffffffff,%edx`). +int SAI::getBotCurrentPos(int botId) const { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::getBotCurrentPos"); + const BotInfo* const info = m_bots[botId]; + return info ? info->m_currentlyOccupiedSquare : -22; } -Vec3 SAI::getBotOrderedPos(int) const +int SAI::getBotOrderedPos(int botId) const { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::getBotOrderedPos"); + const BotInfo* const info = m_bots[botId]; + return info ? info->m_currentlyOrderedSquare : -44; } -Vec3 SAI::getBotLastOrderedPos(int) const +int SAI::getBotLastOrderedPos(int botId) const { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::getBotLastOrderedPos"); + const BotInfo* const info = m_bots[botId]; + return info ? info->m_lastOrderedSquare : -1; } // Accumulate into the previous totals, then decay; no initial clear. @@ -1019,7 +1602,7 @@ void SAI::prepareUpdate() if (bot) { BotInfo* const info = checkPointer(new BotInfo(bot)); - m_botInfo[bot->getBotId()] = info; + m_bots[bot->getBotId()] = info; if (bot->isDead()) { m_map5C.insert(std::make_pair(static_cast(bot->getBotId()), std::make_pair(-1, 13))); @@ -1028,7 +1611,7 @@ void SAI::prepareUpdate() } else setBotIsAlive(bot->getBotId()); - (void)m_setFC.find(bot->getBotId()); // shipped discarded lookup + (void)m_assignedBots.find(bot->getBotId()); // shipped discarded lookup } } @@ -1048,7 +1631,7 @@ void SAI::prepareUpdate() m_friendlyStrengths[i] = 0.0f; m_friendlyCounts[i] = 0.0f; } - for (std::vector::iterator it = m_botInfo.begin(); it != m_botInfo.end(); ++it) + for (std::vector::iterator it = m_bots.begin(); it != m_bots.end(); ++it) { if (*it && !(*it)->m_bot->isDead()) { @@ -1079,7 +1662,7 @@ void SAI::prepareUpdate() for (std::map >::iterator it = m_map5C.begin(); it != m_map5C.end();) { IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); - BotInfo* const info = m_botInfo[it->first]; + BotInfo* const info = m_bots[it->first]; if (!info) { std::map >::iterator removed = it++; @@ -1097,11 +1680,11 @@ void SAI::prepareUpdate() for (std::vector::iterator it = m_vectorA0.begin(); it != m_vectorA0.end(); ++it) { - if (m_botInfo[(*it)->getBotId()]) + if (m_bots[(*it)->getBotId()]) { - m_botInfo[(*it)->getBotId()]->remove(this); - delete m_botInfo[(*it)->getBotId()]; - m_botInfo[(*it)->getBotId()] = 0; + m_bots[(*it)->getBotId()]->remove(this); + delete m_bots[(*it)->getBotId()]; + m_bots[(*it)->getBotId()] = 0; } } #if defined(_MSC_VER) @@ -1119,22 +1702,93 @@ void SAI::clearSpawnsToPoints() it->second = 0; } -// Remaining direct SAI::update dependencies. Paired callers and helper return paths establish -// these signatures; the strategic work behind them remains unrecovered. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -// BotInfo::remove: / , paired callers discard -// the result and neither body materializes a return. Assigned/free/present-unit removal is absent. -void SAI::BotInfo::remove(SAI*) +void SAI::BotInfo::remove(SAI* sai) +{ + const int id = m_bot->getBotId(); + AIStrategicObject* const current = AIStrategicObjectManager::getInstance()->getStrategicObject(m_currentlyOccupiedSquare); + AIStrategicObject* const assigned = AIStrategicObjectManager::getInstance()->getStrategicObject(m_currentlyOrderedSquare); + if (assigned) + { + removeAssigned(assigned, true, sai); + current->removeAsPresentUnit(id, sai->m_side); + } + else if (current) + { + if (sai->m_assignedBots.find(id) != sai->m_assignedBots.end()) + free(true, sai); + current->removeAsPresentUnit(id, sai->m_side); + } + std::set::iterator it = sai->m_freeBots.find(id); + if (it != sai->m_freeBots.end()) + sai->m_freeBots.erase(it); +} + +void SAI::BotInfo::removeAssigned(AIStrategicObject* object, bool release, SAI* sai) +{ + std::set::iterator it = object->getAssignedUnits(sai->m_side).find(m_bot->getBotId()); + removeAssigned(object, it, release, sai); +} + +void SAI::BotInfo::occupy(AIStrategicObject* from, AIStrategicObject* to, SAI* sai) +{ + std::set::iterator it = from->getPresentUnits(sai->m_side).find(m_bot->getBotId()); + occupy(it, from, to, sai); +} + +void SAI::BotInfo::assignToObject(std::set::iterator& it, AIStrategicObject* object, bool attacker, SAI* sai) +{ + m_currentlyOrderedSquare = object->getIndex(); + m_lastOrderedSquare = object->getIndex(); + m_double14 = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + AIStrategicObject* const current = AIStrategicObjectManager::getInstance()->getStrategicObject(m_currentlyOccupiedSquare); + if (attacker) + current->unregisterAvailableAttacker(it, sai->m_side); + else + current->unregisterAvailableDefender(it, sai->m_side); + object->getAssignedUnits(sai->m_side).insert(m_bot->getBotId()); +} + +void SAI::BotInfo::assignToObject(AIStrategicObject* object, bool attacker, SAI* sai) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::BotInfo::remove"); + std::set::iterator it = AIStrategicObjectManager::getInstance()->getStrategicObject(m_currentlyOccupiedSquare)-> + getAvailableBots(attacker, sai->m_side).find(m_bot->getBotId()); + assignToObject(it, object, attacker, sai); } -// Void is inferred from complete -// bodies and their callers. The spawn-group selector and dead-bot/respawn chain remain absent. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -void SAI::handleTeleportingBot(int) +void SAI::BotInfo::assign(bool attacker, SAI* sai) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::handleTeleportingBot"); + std::set::iterator it = sai->m_freeBots.find(m_bot->getBotId()); + assign(it, attacker, sai); +} + +void SAI::BotInfo::setAsDead(SAI*) +{ + m_currentlyOrderedSquare = -1; + m_lastOrderedSquare = -1; + m_currentlyOccupiedSquare = -1; + m_float10 = 0.0f; +} + +void SAI::BotInfo::setAsFree(SAI* sai) +{ + sai->m_freeBots.insert(m_bot->getBotId()); +} + +// ELF 0x328EF0: with a suitable spawn group the bot enters its transition phase (+0x180), +// is handled as dead, gets the group and is respawned through the game effector (+0x1C). +void SAI::handleTeleportingBot(int botId) +{ + if (!m_bots[botId]) + return; + AIStrategicObject* object; + const int group = BotSpawner::findSuitableSpawnGroup(m_side, object, m_bots[botId]->m_bot); + if (!group) + return; + m_bots[botId]->m_bot->setIsInTransitionPhase(true); + handleDeadBot(botId); + m_bots[botId]->m_bot->getPlayer()->setSpawnGroup(group); + static_cast(CommonSingletonServer::m_iaiGameEffector) + ->respawnBot(m_bots[botId]->m_bot->getPlayer()); } bool SAI::updateStrategicObjects() @@ -1185,45 +1839,808 @@ bool SAI::updateStrategicObjects() return true; } -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] +// ELF 0x329A10. A strategy forced for this side (StrategyManager::getForcedStrategy) is scored +// once (result discarded) and activated. Otherwise every strategy is re-scored into m_f04 +// (clamped at 0) against the latest friendly/enemy state arrays; when a score moved by 17% or +// more against the last distribution's m_f00 (ratio <= 0.83 or >= 1.2), or when the active +// strategy has outlived m_f20 * (2 - 2 * 0.5^m_i0C) seconds (then m_i0C counts up), the scores +// are copied to m_f00 and a strategy is drawn at random, weighted by its positive score. +// shipped defect: an empty strategy list still dereferences the end() active-strategy cursor. void SAI::chooseStrategy() { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::chooseStrategy"); + float total = 0.0f; + bool changed = false; + StrategyManager::getInstance()->isDebugEnabled(); // empty debug branch in the image + Strategy* const forced = StrategyManager::getInstance()->getForcedStrategy(m_side); + if (forced) + { + forced->calculatePrerequisite(m_int1F4 ? m_stateB : m_stateA, m_int1F4 ? m_stateD : m_stateC, + m_activeStrategy->strategy, m_side); + for (std::vector::iterator it = m_strategies.begin(); it != m_strategies.end(); ++it) + if (it->strategy == forced) + changeStrategy(it); + return; + } + for (std::vector::iterator it = m_strategies.begin(); it != m_strategies.end(); ++it) + { + it->m_f04 = it->strategy->calculatePrerequisite( + m_int1F4 ? m_stateB : m_stateA, m_int1F4 ? m_stateD : m_stateC, + m_activeStrategy->strategy, m_side); + if (total > it->m_f04) // total is still 0 here + it->m_f04 = total; + float ratio; + if (it->m_f04 != 0.0f) + ratio = it->m_f00 / it->m_f04; + else + ratio = it->m_f00 == 0.0f ? 1.0f : 0.0f; + if (ratio <= 0.83 || ratio >= 1.2) + changed = true; + } + if (!changed) + { + const float limit = m_activeStrategy->strategy->m_f20; + const float p = powf(0.5f, static_cast(m_activeStrategy->m_i0C)); + const float d = 0.5f - p; + const double threshold = ((d + d) + 1.0f) * limit; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (!(now - m_activeStrategy->m_startTime >= threshold)) + return; + ++m_activeStrategy->m_i0C; + } + + for (std::vector::iterator it = m_strategies.begin(); it != m_strategies.end(); ++it) + { + it->m_f00 = it->m_f04; + total += it->m_f04 > 0.0f ? it->m_f04 : 0.0f; + } + float pick = static_cast(AIRandom::m_instance->next()) * 2.3283064365386963e-10f * total; + std::vector::iterator it = m_strategies.begin(); + for (; it != m_strategies.end(); ++it) + { + pick -= it->m_f00 > 0.0f ? it->m_f00 : 0.0f; + if (0.0 >= pick) + break; + } + if (it == m_strategies.end()) + --it; + changeStrategy(it); } +// ELF 0x329610. Activating another strategy releases every object's assigned resources and +// frees all its available attackers and defenders; the new strategy's clock restarts. +void SAI::changeStrategy(std::vector::iterator& it) +{ + if (m_activeStrategy == &*it) + return; + m_activeStrategy = &*it; + const std::vector& objects = + AIStrategicObjectManager::getInstance()->getStrategicObjects(); + std::set::iterator unit; + for (std::vector::const_iterator object = objects.begin(); object != objects.end(); ++object) + { + (*object)->releaseAssignedResources(m_side); + std::set& attackers = (*object)->getAvailableAttackers(m_side); + for (unit = attackers.begin(); unit != attackers.end();) + m_bots[*unit]->free(*object, true, unit, this); + std::set& defenders = (*object)->getAvailableDefenders(m_side); + for (unit = defenders.begin(); unit != defenders.end();) + m_bots[*unit]->free(*object, false, unit, this); + } + StrategyContainer* const active = m_activeStrategy; + active->m_i0C = 1; + active->m_startTime = static_cast(static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime()); +} + +// ELF 0x32FDF0. The occupied-set erase uses find() unchecked, as shipped. +void SAI::BotInfo::free(AIStrategicObject* object, bool attacker, std::set::iterator& it, SAI* sai) +{ + const int id = m_bot->getBotId(); + if (attacker) + object->unregisterAvailableAttacker(it, sai->m_side); + else + object->unregisterAvailableDefender(it, sai->m_side); + sai->m_assignedBots.erase(sai->m_assignedBots.find(id)); + sai->m_freeBots.insert(m_bot->getBotId()); +} + +// ELF 0x3299A0: every strategic object (no null check) applies the active strategy's +// modifiers; the returned temperature is discarded. void SAI::modifyStrategicObjectsTemperatures() { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::modifyStrategicObjectsTemperatures"); + const std::vector& objects = + AIStrategicObjectManager::getInstance()->getStrategicObjects(); + for (std::vector::const_iterator it = objects.begin(); it != objects.end(); ++it) + (*it)->updateTemperature(m_activeStrategy->strategy, m_side); } +// ELF 0x32F290. The occupied-set find result is unused in the image. +void SAI::BotInfo::occupy(std::set::iterator& it, AIStrategicObject* from, AIStrategicObject* to, SAI* sai) +{ + const int id = m_bot->getBotId(); + to->setAsPresentUnit(id, sai->m_side); + bool moved = false; + if (from->unregisterAvailableAttacker(id, sai->m_side)) + { + to->registerAvailableAttacker(id, sai->m_side); + moved = true; + } + else if (from->unregisterAvailableDefender(id, sai->m_side)) + { + to->registerAvailableDefender(id, sai->m_side); + moved = true; + } + if (moved) + (void)sai->m_assignedBots.find(id); + from->removeAsPresentUnit(it, sai->m_side); + m_currentlyOccupiedSquare = to->getIndex(); +} + +// ELF 0x32D910. Per strategic area (getType 0): a present bot whose equipment fits a neighbour +// (+0x128 objects: allowed vehicle group, not expelled, an area, not a landing-zone user) with a +// stronger gravity at the bot's position moves there. Then the area's assigned units and its +// available attackers and defenders are retained (slot 28) when they have reached a MoveTo +// waypoint, sense at most one object, are present and their last order is older than 20 s on +// foot or 35 s in a vehicle. void SAI::updateBotPositions() { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::updateBotPositions"); + std::set::iterator unit; + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + IBotManager* const bots = IBotManager::instance; + const std::vector& objects = + AIStrategicObjectManager::getInstance()->getStrategicObjects(); + for (std::vector::const_iterator object = objects.begin(); object != objects.end(); ++object) + { + std::set& present = (*object)->getPresentUnits(m_side); + if ((*object)->getType() != 0) + continue; + const std::vector& neighbours = + static_cast(*object)->m_neighbouringObjects; + for (unit = present.begin(); unit != present.end();) + { + Bot* const bot = bots->getBotFromId(*unit); + Information* const information = informationManager->getInformation(bot->getCurrentEquipment()); + if (!information || !information->getUnit()) + { + ++unit; + continue; + } + const int equipment = information->getUnit()->getEquipmentType(); + const int group = settings->getVehicleGroup(equipment); + AIStrategicObject* best = *object; + float bestGravity = best->gravity(information->getPosition(), m_side); + for (std::vector::const_iterator n = neighbours.begin(); n != neighbours.end(); ++n) + { + if (!(*n)->isAllowedVehicleGroup(group)) + continue; + if ((*n)->isExpelledUnit(equipment) || (*n)->getType() != 0 + || static_cast(*n)->isLandingZoneUser(equipment)) + continue; + const float gravity = (*n)->gravity(information->getPosition(), m_side); + if (gravity > bestGravity) + { + bestGravity = gravity; + best = *n; + } + } + if (best == *object) + ++unit; + else + m_bots[*unit]->occupy(unit, *object, best, this); + } + + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + std::set* const groups[3] = { + &(*object)->getAssignedUnits(m_side), + &(*object)->getAvailableAttackers(m_side), + &(*object)->getAvailableDefenders(m_side) }; + for (int g = 0; g < 3; ++g) + { + for (std::set::iterator it = groups[g]->begin(); it != groups[g]->end(); ++it) + { + Bot* const bot = bots->getBotFromId(*it); + const unsigned int equipment = bot->getCurrentEquipment(); + const float wait = equipment != bot->getPlayer()->getSoldier()->getInformation(m_side) ? 35.0f : 20.0f; + // 0x32DC8C..0x32DF66: a reached (+5) MoveTo list (getId +0x10 == 1), the last order + // (BotInfo +0x14) older than `wait` (`fsubl 0x14; fucompi; jbe`), at most one sensed + // object (map node count `cmpl $0x1,0x4(%eax); ja`) and still present: retain the + // bot (slot 28, (side, unit, this)) and stamp the order time. + WaypointList* const waypoints = bot->getWaypoints(); + if (!waypoints->m_flag5 || waypoints->getId() != 1) + continue; + if (!(now - m_bots[*it]->m_double14 > wait)) + continue; + if (bot->getSensedObjects().size() > 1) + continue; + if (!(*object)->isPresentUnit(*it, m_side)) + continue; + (*object)->retainBot(m_side, *it, this); + m_bots[*it]->m_double14 = now; + } + } + } +} + +void SAI::BotInfo::free(bool release, SAI* sai) +{ + const int id = m_bot->getBotId(); + AIStrategicObject* const object = AIStrategicObjectManager::getInstance()->getStrategicObject(m_currentlyOccupiedSquare); + if (release) + { + if (!object->unregisterAvailableAttacker(id, sai->m_side)) + object->unregisterAvailableDefender(id, sai->m_side); + sai->m_assignedBots.erase(sai->m_assignedBots.find(id)); + } + sai->m_freeBots.insert(m_bot->getBotId()); +} + +namespace { + +// The unit of a bot's current equipment, or null (the inlined handle lookup of the image). +IPIUnit* currentUnit(unsigned int botId) +{ + Bot* const bot = IBotManager::instance->getBotFromId(botId); + Information* const information = informationManager->getInformation(bot->getCurrentEquipment()); + return information ? information->getUnit() : 0; } +// The mean of a unit's strategic strengths, summed in a float. +float meanStrength(IPIUnit* unit) +{ + float sum = 0.0f; + for (int i = 0; i < unit->getNStrategicStrengths(); ++i) + sum += unit->getStrategicStrengths()[i]; + sum /= static_cast(unit->getNStrategicStrengths()); + return sum; +} + +} // namespace + +// ELF 0x329E60. Recounts the side's attack (+0xD8, first strength), defence (+0xDC, second +// strength) and idle (+0xE0, mean strength of present units, less the attackers' and +// defenders' mean strengths at the end) resources over all strategic objects. With +0x1CD / +// +0x1CC set, the available attackers / defenders are freed instead (+0x1CE marks it). void SAI::updateDistribution() { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::updateDistribution"); + const std::vector& objects = + AIStrategicObjectManager::getInstance()->getStrategicObjects(); + float attackSum = 0.0f; + float defenceSum = 0.0f; + m_flag1CE = false; + m_intD8 = 0; + m_intDC = 0; + m_intE0 = 0; + for (std::vector::const_iterator object = objects.begin(); object != objects.end(); ++object) + { + if (m_flag1CD) + { + while ((*object)->getAvailableAttackers(m_side).size()) + { + m_bots[*(*object)->getAvailableAttackers(m_side).begin()]->free(true, this); + m_flag1CE = true; + } + } + else + { + for (std::set::iterator it = (*object)->getAvailableAttackers(m_side).begin(); + it != (*object)->getAvailableAttackers(m_side).end(); ++it) + { + IPIUnit* const unit = currentUnit(*it); + if (!unit) + continue; + m_intD8 += static_cast(unit->getStrategicStrengths()[0]); + attackSum += meanStrength(unit); + } + } + if (m_flag1CC) + { + while ((*object)->getAvailableDefenders(m_side).size()) + { + m_bots[*(*object)->getAvailableDefenders(m_side).begin()]->free(true, this); + m_flag1CE = true; + } + } + else + { + for (std::set::iterator it = (*object)->getAvailableDefenders(m_side).begin(); + it != (*object)->getAvailableDefenders(m_side).end(); ++it) + { + IPIUnit* const unit = currentUnit(*it); + if (!unit) + continue; + m_intDC += static_cast(unit->getStrategicStrengths()[1]); + defenceSum += meanStrength(unit); + } + } + for (std::set::iterator it = (*object)->getPresentUnits(m_side).begin(); + it != (*object)->getPresentUnits(m_side).end(); ++it) + { + IPIUnit* const unit = currentUnit(*it); + if (unit) + m_intE0 += static_cast(meanStrength(unit)); + } + for (std::set::iterator it = (*object)->getAssignedUnits(m_side).begin(); + it != (*object)->getAssignedUnits(m_side).end(); ++it) + { + IPIUnit* const unit = currentUnit(*it); + if (!unit) + continue; + if ((*object)->isAttack(m_side)) + { + m_intD8 += static_cast(unit->getStrategicStrengths()[0]); + attackSum += meanStrength(unit); + } + else + { + m_intDC += static_cast(unit->getStrategicStrengths()[1]); + defenceSum += meanStrength(unit); + } + } + } + defenceSum = defenceSum + attackSum; + m_intE0 -= static_cast(defenceSum); +} + +void SAI::BotInfo::respawn(AIStrategicObject* object, SAI* sai) +{ + m_currentlyOccupiedSquare = object->getIndex(); + object->setAsPresentUnit(m_bot->getBotId(), sai->m_side); + (void)sai->m_assignedBots.find(m_bot->getBotId()); // result unused in the image + sai->m_freeBots.insert(m_bot->getBotId()); } +void SAI::BotInfo::assign(std::set::iterator& it, bool attacker, SAI* sai) +{ + AIStrategicObject* const object = AIStrategicObjectManager::getInstance()->getStrategicObject(m_currentlyOccupiedSquare); + if (attacker) + object->registerAvailableAttacker(m_bot->getBotId(), sai->m_side); + else + object->registerAvailableDefender(m_bot->getBotId(), sai->m_side); + sai->m_freeBots.erase(it++); + sai->m_assignedBots.insert(m_bot->getBotId()); +} + +void SAI::BotInfo::removeAssigned(AIStrategicObject* object, std::set::iterator& it, bool release, SAI* sai) +{ + object->getAssignedUnits(sai->m_side).erase(it++); + if (release) + { + sai->m_assignedBots.erase(sai->m_assignedBots.find(m_bot->getBotId())); + } + else + { + AIStrategicObject* const current = AIStrategicObjectManager::getInstance()->getStrategicObject(m_currentlyOccupiedSquare); + if (current->isAttack(sai->m_side)) + current->registerAvailableAttacker(m_bot->getBotId(), sai->m_side); + else + current->registerAvailableDefender(m_bot->getBotId(), sai->m_side); + } + m_currentlyOrderedSquare = -1; + m_double14 = 0.0; +} + +int SAI::BotInfo::setLastOrderedSquare(int square) +{ + m_double14 = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + m_lastOrderedSquare = square; + return square; +} + +// ELF 0x32A690. Every free bot (+0x44) is placed at its strategic object (or, after a respawn, +// the closest fitting one), re-ordered there when its last ordered square differs, and assigned +// as attacker or defender: by the strategy's aggression share against the current attack share +// (all attack without friendly areas, all defence when nothing is neutral or hostile). Then +// +0x1CD / +0x1CC ask the next updateDistribution to free attackers / defenders when their +// share exceeds 1.2 times the wanted one. The unused bool[getMaxNBots] and the two +// list > locals are kept as shipped. void SAI::distributeResources() { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::distributeResources"); + std::list > unusedA; + std::list > unusedB; + bool lastWasDefence = true; + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + AIStrategicObjectManager* const manager = AIStrategicObjectManager::getInstance(); + const int slots = settings->getMaxNBots(); + bool* const flags = checkPointer(new bool[slots]); + for (int i = 0; i < slots; ++i) + flags[i] = false; + + const float* const friendly = m_int1F4 ? m_stateB : m_stateA; + float attackShare; + float defenceShare; + if (friendly[StrategyCondition::NumberOfFriendlyAreas] == 0.0f) + { + attackShare = 1.0f; + defenceShare = 0.0f; + } + else if (friendly[StrategyCondition::NumberOfNeutralAreas] == 0.0f + && friendly[StrategyCondition::NumberOfHostileAreas] == 0.0f) + { + attackShare = 0.0f; + defenceShare = 1.0f; + } + else + { + attackShare = m_activeStrategy->strategy->getAggression(); + defenceShare = 1.0f - m_activeStrategy->strategy->getAggression(); + } + + for (std::set::iterator it = m_freeBots.begin(); it != m_freeBots.end();) + { + BotInfo* const info = m_bots[*it]; + if (!info) + { + ++it; + continue; + } + Information* const information = informationManager->getInformation(info->m_bot->getCurrentEquipment()); + if (!information) + { + ++it; + continue; + } + AIStrategicObject* object = manager->getStrategicObject(info->m_currentlyOccupiedSquare); + if (!object) + { + if (!information->getUnit()) + { + ++it; + continue; + } + int vehicle = -1; + if (information->getMobile()) + vehicle = information->getMobile()->getVehicleNumber(); + const int equipment = information->getUnit()->getEquipmentType(); + object = manager->getClosestObject(information->getPosition(), equipment, vehicle, m_side); + if (!object) + { + ++it; + continue; + } + m_bots[*it]->respawn(object, this); + } + else + { + object->setAsPresentUnit(*it, m_side); + } + if (object->getIndex() != m_bots[*it]->m_lastOrderedSquare) + { + object->retainBot(m_side, *it, this); + m_bots[*it]->setLastOrderedSquare(object->getIndex()); + } + IPIUnit* const unit = information->getUnit(); // not null-checked on this path + const int attack = m_intD8; + const int defence = m_intDC; + bool toAttack; + if (attack + defence == 0) + toAttack = attackShare >= 0.5f; + else if (0.0f >= attackShare) + toAttack = false; + else if (0.0f >= defenceShare) + toAttack = true; + else + toAttack = attackShare >= static_cast(attack) / static_cast(attack + defence); + if (toAttack) + m_intD8 = static_cast(unit->getStrategicStrengths()[0]) + attack; + else + m_intDC = static_cast(unit->getStrategicStrengths()[1]) + defence; + m_intE0 -= static_cast(meanStrength(unit)); + lastWasDefence = !toAttack; + m_bots[*it]->assign(it, toAttack, this); + } + + const float total = static_cast(m_intD8 + m_intDC + m_intE0); + if (total == 0.0f) + { + m_flag1CD = false; + m_flag1CC = false; + } + else + { + if (static_cast(m_intD8) / total > attackShare * 1.2f && !lastWasDefence) + { + m_flag1CD = true; + m_flag1CE = true; + } + else + { + m_flag1CD = false; + } + if (static_cast(m_intDC) / total > 1.2f * defenceShare && lastWasDefence) + { + m_flag1CC = true; + m_flag1CE = true; + } + else + { + m_flag1CC = false; + } + } + delete[] flags; } +// ELF 0x32AE70: per category (or over all objects when there are none), unless the active +// strategy runs no defences. void SAI::distributeDefence() { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::distributeDefence"); + if (!m_activeStrategy->strategy->getNumberOfDefences()) + return; + AIStrategicObjectManager* const manager = AIStrategicObjectManager::getInstance(); + if (!manager->getNumberOfCategories()) + { + categoryDistributeDefence(manager->getStrategicObjects()); + return; + } + for (int category = 0; category < manager->getNumberOfCategories(); ++category) + categoryDistributeDefence(manager->getStrategicObjectsOfCategory(category)); +} + +// ELF 0x32AF10. Objects needing defence (need > 0.1) are ranked by need, highest first; objects +// with no need that are not attacked release their resources. Beyond twice the strategy's +// defence count, entries below 90% of the need at that rank are dropped (releasing their +// resources unless attacked). With +0x1CC set (and +0x1CE clear) and nothing released yet, the +// lowest-need defence releases resources instead. Otherwise up to getNumberOfDefences() areas +// are set to defend and fed one squad at a time, the least supplied first (sobOrdering). +void SAI::categoryDistributeDefence(const std::vector& objects) +{ + std::list squares; + int released = 0; + for (std::vector::const_iterator it = objects.begin(); it != objects.end(); ++it) + { + if (!*it) + continue; + SquareInfo square; + square.m_index = -1; + square.m_value = (*it)->calculateDefenseNeed(m_side); + if (square.m_value > 0.1f) + { + square.m_index = (*it)->getIndex(); + squares.push_back(square); + } + else if (0.0f >= square.m_value && !(*it)->isAttack(m_side)) + { + released += (*it)->releaseAssignedResources(m_side); + } + } + squares.sort(); + squares.reverse(); + if (squares.empty()) + return; + + float threshold = 0.0f; + unsigned int rank = 0; + std::list::iterator it = squares.begin(); + for (; it != squares.end(); ++it) + { + ++rank; + const unsigned int keep = m_activeStrategy->strategy->getNumberOfDefences() * 2; + if (rank == keep) + threshold = it->m_value; + else if (rank > keep && threshold * 0.9f > it->m_value) + break; + } + while (it != squares.end()) + { + AIStrategicObject* const object = AIStrategicObjectManager::getInstance()->getStrategicObject(it->m_index); + if (object && !object->isAttack(m_side)) + released += object->releaseAssignedResources(m_side); + it = squares.erase(it); + } + if (squares.empty()) + return; + + if (m_flag1CC && !m_flag1CE && !released) + { + squares.reverse(); + for (it = squares.begin(); it != squares.end(); ++it) + { + AIStrategicObject* const object = AIStrategicObjectManager::getInstance()->getStrategicObject(it->m_index); + if (!object || object->isAttack(m_side)) + continue; + released += object->releaseAssignedResources(m_side); + if (released > 0) + return; + } + return; + } + + unsigned int count = 0; + std::priority_queue, sobOrdering> queue((sobOrdering(m_side))); + for (it = squares.begin(); it != squares.end(); ++it) + { + AIStrategicObject* const object = AIStrategicObjectManager::getInstance()->getStrategicObject(it->m_index); + if (!object) + continue; + object->setAttack(false, m_side); + queue.push(object); + ++count; + if (!(m_activeStrategy->strategy->getNumberOfDefences() > count)) + break; + } + while (!queue.empty()) + { + AIStrategicObject* const object = queue.top(); + queue.pop(); + if (object->collectAdditionalSquadResources(1, m_side, this)) + queue.push(object); + } } +// ELF 0x32B9B0: per category (or over all objects when there are none), unless the active +// strategy runs no attacks. void SAI::distributeAttack() { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::distributeAttack"); + if (!m_activeStrategy->strategy->getNumberOfAttacks()) + return; + AIStrategicObjectManager* const manager = AIStrategicObjectManager::getInstance(); + if (!manager->getNumberOfCategories()) + { + categoryDistributeAttack(manager->getStrategicObjects()); + return; + } + for (int category = 0; category < manager->getNumberOfCategories(); ++category) + categoryDistributeAttack(manager->getStrategicObjectsOfCategory(category)); +} + +// ELF 0x32BA50. Areas worth attacking (value > 0.001) are ranked, highest first. The first +// getNumberOfAttacks() set the threshold; up to twice that many are kept while they reach 80% of +// it, the rest are dropped, releasing their resources when attacked. With +0x1CD set (and +0x1CE +// clear) and nothing released, the lowest entry is dropped as well and attacked areas release +// resources instead, until something was released. Otherwise already attacked areas are chosen +// first (up to numberOfAttacks + 1 entries, as shipped), filled up from the top of the ranking, +// set to attack, collect their squads (slot 23) and are then fed one more squad at a time, the +// least supplied first. The isAttack call for non-positive values is discarded, as shipped. +void SAI::categoryDistributeAttack(const std::vector& objects) +{ + std::list squares; + std::list chosen; + int released = 0; + for (std::vector::const_iterator it = objects.begin(); it != objects.end(); ++it) + { + if (!*it) + continue; + SquareInfo square; + square.m_index = -1; + square.m_value = (*it)->calculateAttackValue(m_side); + if (square.m_value > 0.001f) + { + square.m_index = (*it)->getIndex(); + squares.push_back(square); + } + else if (0.0f >= square.m_value) + { + (*it)->isAttack(m_side); + } + } + squares.sort(); + squares.reverse(); + if (squares.empty()) + return; + + float threshold = 0.0f; + unsigned int rank = 0; + std::list::iterator it = squares.begin(); + while (it != squares.end()) + { + ++rank; + if (rank <= m_activeStrategy->strategy->getNumberOfAttacks()) + threshold = it->m_value; + else if (rank > m_activeStrategy->strategy->getNumberOfAttacks() * 2 + || threshold * 0.8f > it->m_value) + break; + ++it; + } + while (it != squares.end()) + { + AIStrategicObject* const object = AIStrategicObjectManager::getInstance()->getStrategicObject(it->m_index); + if (object && object->isAttack(m_side)) + released += object->releaseAssignedResources(m_side); + it = squares.erase(it); + } + const bool shed = m_flag1CD && !m_flag1CE && !released; + if (shed) + { + it = squares.end(); + --it; + while (it != squares.end()) + it = squares.erase(it); + } + if (squares.empty()) + return; + if (shed) + { + for (it = squares.begin(); it != squares.end(); ++it) + { + AIStrategicObject* const object = AIStrategicObjectManager::getInstance()->getStrategicObject(it->m_index); + if (!object || !object->isAttack(m_side)) + continue; + released += object->releaseAssignedResources(m_side); + if (released > 0) + return; + } + return; + } + + it = squares.begin(); + while (it != squares.end() && !(chosen.size() > m_activeStrategy->strategy->getNumberOfAttacks())) + { + AIStrategicObject* const object = AIStrategicObjectManager::getInstance()->getStrategicObject(it->m_index); + if (object && object->isAttack(m_side)) + { + chosen.push_back(*it); + it = squares.erase(it); + } + else + { + ++it; + } + } + it = squares.begin(); + while (!(chosen.size() > m_activeStrategy->strategy->getNumberOfAttacks()) && it != squares.end()) + { + chosen.push_back(*it); + ++it; + } + for (it = chosen.begin(); it != chosen.end(); ++it) + { + AIStrategicObject* const object = AIStrategicObjectManager::getInstance()->getStrategicObject(it->m_index); + if (!object) + continue; + object->setAttack(true, m_side); + object->collectSquadResources(m_side, this); + } + std::priority_queue, sobOrdering> queue((sobOrdering(m_side))); + for (it = chosen.begin(); it != chosen.end(); ++it) + { + AIStrategicObject* const object = AIStrategicObjectManager::getInstance()->getStrategicObject(it->m_index); + if (object) + queue.push(object); + } + while (!queue.empty()) + { + AIStrategicObject* const object = queue.top(); + queue.pop(); + if (object->collectAdditionalSquadResources(1, m_side, this)) + queue.push(object); + } } +// ELF 0x32B6E0: per category, or over all objects when there are none. void SAI::distributeWithNoAreas() { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::distributeWithNoAreas"); + AIStrategicObjectManager* const manager = AIStrategicObjectManager::getInstance(); + if (!manager->getNumberOfCategories()) + { + categoryDistributeWithNoAreas(manager->getStrategicObjects()); + return; + } + for (int category = 0; category < manager->getNumberOfCategories(); ++category) + categoryDistributeWithNoAreas(manager->getStrategicObjectsOfCategory(category)); +} + +// ELF 0x32B770. Every non-null object becomes a SquareInfo {index, 1.0f} (in object order, not +// sorted here); each one that still resolves is set to attack unless the side owns it, then +// collects two additional squads (slot 24 with (2, side, this)). The second list is unused. +void SAI::categoryDistributeWithNoAreas(const std::vector& objects) +{ + std::list squares; + std::list unused; + for (std::vector::const_iterator it = objects.begin(); it != objects.end(); ++it) + { + if (!*it) + continue; + SquareInfo square; + square.m_value = 1.0f; + square.m_index = (*it)->getIndex(); + squares.push_back(square); + } + for (std::list::iterator it = squares.begin(); it != squares.end(); ++it) + { + AIStrategicObject* const object = AIStrategicObjectManager::getInstance()->getStrategicObject(it->m_index); + if (!object) + continue; + object->setAttack(object->getStatus(m_side) != StatusMap::Owned, m_side); + object->collectAdditionalSquadResources(2, m_side, this); + } } // Recovered empty helper: , (frame prologue/epilogue and return only). @@ -1253,9 +2670,51 @@ void SampleHelper::clear(float* strength, int* count) } } +// ELF 0x331B80 (weak, inline in the header): the owned commander interface at +0x1F8. CommanderInterface* SAI::getCommanderInterface() const { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::getCommanderInterface"); + return m_commander; +} + +// ELF 0x32E8A0: per-round state back to its constructed values (the strategy containers' first +// two floats, the four six-bucket rows, the flags, the resumable update state 19 with the -1000.0 +// timestamp, +0xD8/+0xDC), the deny requests freed, the four timers restarted from the game time +// (+0x68/+0x70/+0x78 now + 60, +0x80 now + 10, +0x88 zero), the squad manager reset, +0xAC set. +bool SAI::reset() +{ + for (std::vector::iterator it = m_strategies.begin(); it != m_strategies.end(); ++it) + { + it->m_f04 = 0.0f; + it->m_f00 = 0.0f; + } + for (int i = 0; i <= 5; ++i) + { + m_enemyStrengths[i] = 0.0f; + m_enemyCounts[i] = 0.0f; + m_friendlyStrengths[i] = 0.0f; + m_friendlyCounts[i] = 0.0f; + } + m_flag1C0 = false; + m_flag1C1 = false; + m_flag1CE = true; + m_float190 = -1000.0f; + m_int18C = 19; + m_intD8 = 0; + m_intDC = 0; + for (std::list::iterator it = m_denyRequests.begin(); it != m_denyRequests.end();) + { + ::operator delete(*it); + it = m_denyRequests.erase(it); + } + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + m_time80 = now + 10.0f; + m_time68 = now + 60.0f; + m_time70 = now + 60.0f; + m_time78 = now + 60.0f; + m_time88 = 0.0f; + SquadManager::m_instance->reset(); + m_flagAC = true; + return true; } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.h b/Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.h index d6b15e48f..aa585d0fb 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.h @@ -9,6 +9,7 @@ #include #include #include +#include #include #include "../../../../Math/Vec3.h" // Vec2 and Vec3 are typedefs in here - never forward-declare @@ -27,12 +28,14 @@ class Strategy; // count that divides by five, so `sizeof(StrategyContainer) == 20`; the destructor also runs // `__destroy_aux` over the range, which is what proves the vector holds these by value rather than // by pointer. updateStates subtracts the float at +8 from game time. -// Its name is [INFERRED]; the other sixteen bytes remain [UNRESOLVED]. +// Its name is [INFERRED]. SAI::addStrategy (ELF 0x326C10) builds {0, 0, 0, 1, strategy}. struct StrategyContainer { - unsigned char m_unresolved00[8]; - float m_startTime; // +8, [INFERRED] name - unsigned char m_unresolved0C[8]; + float m_f00; // +0x00, [UNRESOLVED] role; SAI::reset zeroes it + float m_f04; // +0x04, [UNRESOLVED] role; SAI::reset zeroes it + float m_startTime; // +0x08, [INFERRED] name + int m_i0C; // +0x0C, = 1 [UNRESOLVED] + Strategy* strategy; // +0x10, borrowed; owned by the StrategyManager; name: AIDLL_r assert "stratIter->strategy != 0" (0x1015BA90) }; // Running weighted averages over a fixed number of strength categories. @@ -73,12 +76,12 @@ class CommanderInterface CommanderInterface(); // - (empty) ~CommanderInterface(); // - (empty) - void giveAttackOrder(const Vec3& position, SquadCoordinator* squad); // [FRONTIER] - void giveMoveOrder(const Vec3& position, SquadCoordinator* squad); // [FRONTIER] - void giveDefendOrder(const Vec3& position, SquadCoordinator* squad); // [FRONTIER] - void giveAttackOrder(const Vec3& position, Bot* bot); // [FRONTIER] - void giveMoveOrder(const Vec3& position, Bot* bot); // [FRONTIER] - void giveDefendOrder(const Vec3& position, Bot* bot); // [FRONTIER] + void giveAttackOrder(const Vec3& position, SquadCoordinator* squad); // ELF 0x323180 + void giveMoveOrder(const Vec3& position, SquadCoordinator* squad); // ELF 0x3231F0 + void giveDefendOrder(const Vec3& position, SquadCoordinator* squad); // ELF 0x323260 + void giveAttackOrder(const Vec3& position, Bot* bot); // ELF 0x3232D0 + void giveMoveOrder(const Vec3& position, Bot* bot); // ELF 0x323340 + void giveDefendOrder(const Vec3& position, Bot* bot); // ELF 0x3233B0 }; // Strategic AI interface, including human-commander ability requests and their rate limits. @@ -99,9 +102,9 @@ class ISAI virtual bool isEnemy(int side) const = 0; // +10 virtual bool isFriend(int side) const = 0; // +11 virtual float* getEnemyStrengths(int index) const = 0; // +12 - virtual int* getEnemyTypes(int index) const = 0; // +13 + virtual float* getEnemyTypes(int index) const = 0; // +13 (float counts) virtual float* getFriendlyStrengths(int index) const = 0; // +14 - virtual int* getFriendlyTypes(int index) const = 0; // +15 + virtual float* getFriendlyTypes(int index) const = 0; // +15 (float counts) virtual void setBotHasChangedEquipment(int botId) = 0; // +16 virtual void setNewBotKit(int botId, int kit) = 0; // +17 // Borrowed map address: ELF +0x48 / PE +0x44; caller copies map>. @@ -127,21 +130,23 @@ class ISAI virtual bool ownAllTakeableCps(int side) = 0; // +31 // Full released-squad count: ELF callers add EAX; PE +0x7C forwards that count. virtual int releaseSquadsFromObject(int a, int b) = 0; // +32 - virtual void releaseUnitFromObject(int a, std::map::iterator& it, int b) = 0; // +33 - virtual void foundDeadBot(int botId) = 0; // +34 + virtual bool releaseUnitFromObject(int object, std::set::iterator& it, int side) = 0; // +33 + virtual bool foundDeadBot(int botId) = 0; // +34 virtual bool hasChangedEquipment(int botId) = 0; // +35 virtual void equipmentChangedFinished(int botId) = 0; // +36 - virtual void assignBot(std::map::iterator& it, int a, int b, bool c) = 0; // +37 + virtual int assignBot(std::set::iterator& it, int object, int botId, bool attacker) = 0; // +37 virtual bool strategicObjectsHasChanged() = 0; // +38 virtual void registerTeleporter(int id) = 0; // +39 - virtual float getStrategyHeat(unsigned int index) = 0; // +40 - virtual void listStrategies() = 0; // +41 - virtual int getActiveStrategy() = 0; // +42 + // ELF 0x32E380 returns the eight-byte {m_f00, m_f04} pair through the hidden result pointer; + // the Vec2 spelling is [INFERRED]. + virtual Vec2 getStrategyHeat(unsigned int index) = 0; // +40 + virtual std::string listStrategies() = 0; // +41, by value + virtual Strategy* getActiveStrategy() = 0; // +42 virtual void addSpawnToPoint(int point) = 0; // +43 virtual int getSpawnsToPoint(int point) const = 0; // +44 - virtual Vec3 getBotCurrentPos(int botId) const = 0; // +45 - virtual Vec3 getBotOrderedPos(int botId) const = 0; // +46 - virtual Vec3 getBotLastOrderedPos(int botId) const = 0; // +47 + virtual int getBotCurrentPos(int botId) const = 0; // +45 + virtual int getBotOrderedPos(int botId) const = 0; // +46 + virtual int getBotLastOrderedPos(int botId) const = 0; // +47 virtual CommanderInterface* getCommanderInterface() const = 0; // +48 // the factory is static and it is the only way in. : `operator new(0x1FC)` then the @@ -159,12 +164,52 @@ class SAI : public ISAI struct BotInfo { explicit BotInfo(Bot* bot); - void remove(SAI* sai); // named removal frontier + // ELF 0x32F3D0: leave the assigned object (removeAssigned with release) and the current + // object's present set - or, unassigned, the occupied set through free(true) - and the + // free set (+0x44). + void remove(SAI* sai); + // ELF 0x32F5B0: removeAssigned through object->getAssignedUnits(side).find(id) (no end + // check in the image). + void removeAssigned(AIStrategicObject* object, bool release, SAI* sai); + // ELF 0x32FF30: m_currentlyOrderedSquare/m_lastOrderedSquare/m_currentlyOccupiedSquare = -1, m_float10 = 0.0f. + void setAsDead(SAI* sai); + // ELF 0x32FF70: the id enters the free set (+0x44). + void setAsFree(SAI* sai); + // ELF 0x32FDF0: unregister the bot from the object's attacker/defender set (advancing + // it), move its id from SAI's occupied set (+0xFC) to the free set (+0x44). + void free(AIStrategicObject* object, bool attacker, std::set::iterator& it, SAI* sai); + // ELF 0x32FC80: with release, unregister from the current object (m_currentlyOccupiedSquare) and leave the + // occupied set; the id always enters the free set (+0x44). + void free(bool release, SAI* sai); + // ELF 0x32F0E0: the bot respawned at an object: present there, id into the free set. + void respawn(AIStrategicObject* object, SAI* sai); + // ELF 0x32FB10: register as attacker/defender of the current object; the id moves from + // the free set (erasing under the iterator) to the occupied set. + void assign(std::set::iterator& it, bool attacker, SAI* sai); + int setLastOrderedSquare(int square); // ELF 0x32FFD0; stamps m_double14 + // ELF 0x32F660: leave the object's assigned set (erasing under the iterator); with + // release also SAI's occupied set (+0xFC), otherwise become an available attacker or + // defender of the current object (m_currentlyOccupiedSquare). Clears m_currentlyOrderedSquare and m_double14. + void removeAssigned(AIStrategicObject* object, std::set::iterator& it, bool release, SAI* sai); + // ELF 0x32F290: the bot moves from one object's present set (advancing it) to another's, + // keeping its attacker/defender role there; m_currentlyOccupiedSquare becomes the new object's index. + void occupy(std::set::iterator& it, AIStrategicObject* from, AIStrategicObject* to, SAI* sai); + // ELF 0x32F1F0: the iterator overload with from->getPresentUnits(side).find(id). + void occupy(AIStrategicObject* from, AIStrategicObject* to, SAI* sai); + // ELF 0x32F950: ordered to the object (m_currentlyOrderedSquare = m_lastOrderedSquare = its index, m_double14 = now); + // leaves the current object's attackers/defenders under the iterator and joins the + // object's assigned set. + void assignToObject(std::set::iterator& it, AIStrategicObject* object, bool attacker, SAI* sai); + // ELF 0x32F860: the iterator overload with the current object's available attackers or + // defenders (getAvailableBots(attacker, side)).find(id). + void assignToObject(AIStrategicObject* object, bool attacker, SAI* sai); + // ELF 0x32FA60: the iterator overload with SAI's free set (+0x44).find(id). + void assign(bool attacker, SAI* sai); /* +0x00 */ Bot* m_bot; - /* +0x04 */ int m_int04; // = -1 - /* +0x08 */ int m_int08; // = -1 - /* +0x0C */ int m_int0C; // = -1 + /* +0x04 */ int m_currentlyOrderedSquare; // = -1 // name: AIDLL_r asserts 0x10157690, 0x10159C00 (+4) + /* +0x08 */ int m_lastOrderedSquare; // = -1 // name: AIDLL_r assert 0x101596A0 (+8) + /* +0x0C */ int m_currentlyOccupiedSquare; // = -1 // name: AIDLL_r asserts 0x10157250, 0x10159C00 (+0xC) /* +0x10 */ float m_float10; // = 0.0f; update accumulates the frame interval here /* +0x14 */ double m_double14; // = 0.0 }; @@ -183,6 +228,8 @@ class SAI : public ISAI SAI(int side, int gridWidth, int gridHeight, Vec2 min, Vec2 max); virtual ~SAI(); + bool reset(); // ELF 0x32E8A0, non-virtual; answers true + // the 49 interface slots. Unwritten bodies stop at named frontiers. virtual void addStrategy(Strategy* strategy); virtual void update(double budget); @@ -195,9 +242,9 @@ class SAI : public ISAI virtual bool isEnemy(int side) const; virtual bool isFriend(int side) const; virtual float* getEnemyStrengths(int index) const; - virtual int* getEnemyTypes(int index) const; + virtual float* getEnemyTypes(int index) const; virtual float* getFriendlyStrengths(int index) const; - virtual int* getFriendlyTypes(int index) const; + virtual float* getFriendlyTypes(int index) const; virtual void setBotHasChangedEquipment(int botId); virtual void setNewBotKit(int botId, int kit); virtual const std::map >& getDeadBots() const; @@ -216,21 +263,21 @@ class SAI : public ISAI virtual bool haveAnyOwnedAndTakeableCps(int side); virtual bool ownAllTakeableCps(int side); virtual int releaseSquadsFromObject(int a, int b); // frontier - virtual void releaseUnitFromObject(int a, std::map::iterator& it, int b); - virtual void foundDeadBot(int botId); + virtual bool releaseUnitFromObject(int object, std::set::iterator& it, int side); // ELF 0x32D6D0 + virtual bool foundDeadBot(int botId); // ELF 0x329250 virtual bool hasChangedEquipment(int botId); virtual void equipmentChangedFinished(int botId); - virtual void assignBot(std::map::iterator& it, int a, int b, bool c); + virtual int assignBot(std::set::iterator& it, int object, int botId, bool attacker); // ELF 0x32D870 virtual bool strategicObjectsHasChanged(); virtual void registerTeleporter(int id); - virtual float getStrategyHeat(unsigned int index); - virtual void listStrategies(); - virtual int getActiveStrategy(); + virtual Vec2 getStrategyHeat(unsigned int index); + virtual std::string listStrategies(); + virtual Strategy* getActiveStrategy(); virtual void addSpawnToPoint(int point); virtual int getSpawnsToPoint(int point) const; - virtual Vec3 getBotCurrentPos(int botId) const; - virtual Vec3 getBotOrderedPos(int botId) const; - virtual Vec3 getBotLastOrderedPos(int botId) const; + virtual int getBotCurrentPos(int botId) const; + virtual int getBotOrderedPos(int botId) const; + virtual int getBotLastOrderedPos(int botId) const; virtual CommanderInterface* getCommanderInterface() const; // non-virtual. The vtable does not carry these. @@ -244,6 +291,7 @@ class SAI : public ISAI void handleTeleportingBot(int botId); // named frontier bool updateStrategicObjects(); void chooseStrategy(); + void changeStrategy(std::vector::iterator& it); // ELF 0x329610 void modifyStrategicObjectsTemperatures(); void updateBotPositions(); void updateDistribution(); @@ -251,9 +299,21 @@ class SAI : public ISAI void distributeDefence(); void distributeAttack(); void distributeWithNoAreas(); + void categoryDistributeWithNoAreas(const std::vector& objects); // ELF 0x32B770 + void categoryDistributeAttack(const std::vector& objects); // ELF 0x32BA50 + void categoryDistributeDefence(const std::vector& objects); // ELF 0x32AF10 void distributeArtillery(); // genuinely empty, PE update elides it + void updateMap(double budget); // ELF 0x32CEE0, empty + float* createUnitMods() const; // ELF 0x329490 + bool isBotFree(int botId) const; // ELF 0x32E2D0 + bool isBotAssigned(int botId) const; // ELF 0x32E320 + Strategy* getActiveStrategy(float& a, float& b, float& c); // ELF 0x32EAB0 private: + // ELF 0x328DB0 (setBotIsDead's body, a direct call). + void handleDeadBot(int botId); + // ELF 0x328FE0 (setBotHasChangedEquipment's tail, a direct call). + void handleChangingBot(int botId); /* +0x000 */ // vptr - ISAI // forty bytes no constructor store and no destructor call ever touches. [UNRESOLVED]; kept // opaque so every offset below stays where the binary puts it. @@ -261,8 +321,8 @@ class SAI : public ISAI /* +0x02C */ std::vector m_vector2C; // 4-byte element; type [UNRESOLVED] /* +0x038 */ std::vector m_vector38; // 4-byte element; type [UNRESOLVED] - /* +0x044 */ std::set m_set44; - /* +0x050 */ std::vector m_botInfo; // resized to getMaxNBots by the constructor + /* +0x044 */ std::set m_freeBots; // name: AIDLL_r assert "sai->m_freeBots" 0x10157AB0 (PE +0x4C) + /* +0x050 */ std::vector m_bots; // resized to getMaxNBots by the constructor // name: AIDLL_r assert "m_bots[botId] != 0" 0x1015CF40 (PE +0x58) /* +0x05C */ std::map > m_map5C; // Five doubles. Four are stamped from the timer at construction: three at now + 60 and one at @@ -282,20 +342,20 @@ class SAI : public ISAI // four behaviour IDS resolved by name at construction, through BotBehaviourManager. If a // behaviour is missing the manager returns -1 and the id is stored anyway. - /* +0x0C8 */ int m_behaviourIdle; // "Idle" - /* +0x0CC */ int m_behaviourMoveTo; // "MoveTo" - /* +0x0D0 */ int m_behaviourAvoid; // "Avoid" - /* +0x0D4 */ int m_behaviourFire; // "Fire" + /* +0x0C8 */ int m_idleBehaviourId; // "Idle" // name: AIDLL_r assert 0x10160AB0 (PE +0xEC) + /* +0x0CC */ int m_moveToBehaviourId; // "MoveTo" // name: AIDLL_r assert 0x10160AB0 (PE +0xF0) + /* +0x0D0 */ int m_avoidBehaviourId; // "Avoid" // name: AIDLL_r assert 0x10160AB0 (PE +0xF4) + /* +0x0D4 */ int m_fireBehaviourId; // "Fire" // name: AIDLL_r assert 0x10160AB0 (PE +0xF8) /* +0x0D8 */ int m_intD8; // [UNRESOLVED] - the ctor zeroes it /* +0x0DC */ int m_intDC; // [UNRESOLVED] - the ctor zeroes it - /* +0x0E0 */ int m_intE0; // [UNRESOLVED] + /* +0x0E0 */ int m_intE0; // [UNRESOLVED]; not constructed, updateDistribution zeroes it /* +0x0E4 */ std::map > m_mapE4; // a map of maps - node 32 /* +0x0F0 */ std::set m_setF0; - /* +0x0FC */ std::set m_setFC; + /* +0x0FC */ std::set m_assignedBots; // name: AIDLL_r assert "sai->m_assignedBots" 0x10157AB0 (PE +0x120) /* +0x108 */ std::list m_list108; // 4-byte element; type [UNRESOLVED] /* +0x10C */ std::list m_list10C; // 4-byte element; type [UNRESOLVED] - /* +0x110 */ std::list m_list110; // 4-byte element; type [UNRESOLVED] + /* +0x110 */ std::list m_list110; // teleporter ids (registerTeleporter) // by value, not by pointer - the destructor runs `__destroy_aux` over the // range, and the deallocation size divides by five, so `sizeof(StrategyContainer) == 20`. @@ -312,7 +372,7 @@ class SAI : public ISAI /* +0x174 */ float m_friendlyCounts[6]; /* +0x18C */ int m_int18C; // = 19; resumable strategic update state - /* +0x190 */ float m_float190; // = -992.0f; last-update timestamp used by state 4 + /* +0x190 */ float m_float190; // = -1000.0f; last-update timestamp used by state 4 /* +0x194 */ int m_side; // the constructor's first argument /* +0x198 */ int m_sideMask; // = 1 << side /* +0x19C */ int m_enemyMask; // = (side == 1) ? 4 : 2 - the other side's bit diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/SCArea.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategic/SCArea.cpp new file mode 100644 index 000000000..7a9a58a3a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/SCArea.cpp @@ -0,0 +1,57 @@ +// Area condition. Evidence: libaidll.so (ia-32) 0x3322B0..0x332770. + +#include "SCArea.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF 0x3326E0, +// __tcf_0 0x332740, _GLOBAL__I 0x332770). +#include + +#include "../AIStrategicEntity/AIStrategicArea.h" +#include "../AIStrategicEntity/AIStrategicObject.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +SCArea::SCArea(const std::string& name, const std::string& areaName, int object, + StatusMap::Status status) + : StrategyCondition(name, 0.0f, static_cast(9), Friendly, Crisp, + static_cast(44)), + m_object(object), + m_areaName(areaName), + m_status(status) +{ +} + +SCArea::~SCArea() +{ +} + +// ELF 0x3325B0: 1 when the object is an area (getType 0) whose status for this side is the +// wanted one, -1 otherwise. The object is not null-checked. +float SCArea::compare(float*, float*, int side) const +{ + AIStrategicObject* const object = + AIStrategicObjectManager::getInstance()->getStrategicObject(m_object); + if (object->getType() != 0) + return -1.0f; + return object->getStatus(side) == m_status ? 1.0f : -1.0f; +} + +// ELF 0x332630: resolves the area by name through the manager's active-area cursor. +int SCArea::updateArea() +{ + AIStrategicObjectManager* const manager = AIStrategicObjectManager::getInstance(); + manager->setActive(m_areaName); + AIStrategicArea* const area = manager->getActiveArea(); + if (area) + m_object = area->getIndex(); + else + m_object = -1; + return m_object; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/SCArea.h b/Code/BF2/AI/AIDLL/AI/AIStrategic/SCArea.h new file mode 100644 index 000000000..89ce621fe --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/SCArea.h @@ -0,0 +1,35 @@ +// Condition on the status of one strategic area for the asking side. +// Evidence: libaidll.so (ia-32) 0x3322B0..0x332870, vtable 0x4BF458. + +#ifndef AI_AIDLL_AI_AISTRATEGIC_SCAREA_H +#define AI_AIDLL_AI_AISTRATEGIC_SCAREA_H + +#include "StatusMap.h" +#include "StrategyCondition.h" + +namespace dice { +namespace hfe { +namespace ai { + +class SCArea : public StrategyCondition +{ +public: + // ELF 0x3322B0: base (name, 0.0f, Compare 9, Friendly, Crisp, Conditional 44) - both + // out of range, so the base comparisons are never used. + SCArea(const std::string& name, const std::string& areaName, int object, + StatusMap::Status status); + virtual ~SCArea(); + virtual int getType() const { return 3; } // ELF 0x332870 (weak) + virtual float compare(float* friendly, float* enemy, int side) const; + int updateArea(); // ELF 0x332630 + + /* +0x24 */ int m_object; // strategic-object index, -1 when unresolved + /* +0x28 */ std::string m_areaName; + /* +0x2C */ StatusMap::Status m_status; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGIC_SCAREA_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/SCConstant.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategic/SCConstant.cpp new file mode 100644 index 000000000..b73fbfc35 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/SCConstant.cpp @@ -0,0 +1,34 @@ +// Constant condition. Evidence: libaidll.so (ia-32) 0x332880..0x332B10. + +#include "SCConstant.h" + +#include "../Main/StrategyManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +SCConstant::SCConstant(const std::string& name, CompareType compareType, Compare compare, + ConditionSide side, Conditional conditional, float constant, float target) + : StrategyCondition(name, target, compare, side, compareType, conditional), + m_constant(constant) +{ +} + +SCConstant::~SCConstant() +{ +} + +// ELF 0x332A90: Friendly reads the friendly array, every other side the enemy array. The +// debug query's branch is empty in the shipped image; only the call remains. +float SCConstant::compare(float* friendly, float* enemy, int) const +{ + float* const values = m_side == Friendly ? friendly : enemy; + const float result = internalCompare(values[m_conditional], m_constant); + StrategyManager::getInstance()->isDebugEnabled(); + return result; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/SCConstant.h b/Code/BF2/AI/AIDLL/AI/AIStrategic/SCConstant.h new file mode 100644 index 000000000..2df096f1a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/SCConstant.h @@ -0,0 +1,31 @@ +// Condition comparing one state value of the friendly or the enemy side with a constant. +// Evidence: libaidll.so (ia-32) 0x332880..0x332B10, vtable 0x4BF4A0. + +#ifndef AI_AIDLL_AI_AISTRATEGIC_SCCONSTANT_H +#define AI_AIDLL_AI_AISTRATEGIC_SCCONSTANT_H + +#include "StrategyCondition.h" + +namespace dice { +namespace hfe { +namespace ai { + +class SCConstant : public StrategyCondition +{ +public: + // ELF 0x332880: the base gets (name, target, compare, side, compareType, conditional); the + // first float is the constant operand at +0x24. + SCConstant(const std::string& name, CompareType compareType, Compare compare, + ConditionSide side, Conditional conditional, float constant, float target); + virtual ~SCConstant(); + virtual int getType() const { return Constant; } // ELF 0x332B10 (weak) + virtual float compare(float* friendly, float* enemy, int side) const; + + /* +0x24 */ float m_constant; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGIC_SCCONSTANT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/SCHeterogeneous.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategic/SCHeterogeneous.cpp new file mode 100644 index 000000000..985151d37 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/SCHeterogeneous.cpp @@ -0,0 +1,52 @@ +// Heterogeneous condition. Evidence: libaidll.so (ia-32) 0x332B20..0x332DD0. + +#include "SCHeterogeneous.h" + +#include "../Main/StrategyManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +SCHeterogeneous::SCHeterogeneous(const std::string& name, CompareType compareType, + Compare compare, ConditionSide side, Conditional first, + Conditional second, float target) + : StrategyCondition(name, target, compare, side, compareType, first), + m_secondConditional(second) +{ +} + +SCHeterogeneous::~SCHeterogeneous() +{ +} + +// ELF 0x332D30. An unknown side answers 0 without comparing. +float SCHeterogeneous::compare(float* friendly, float* enemy, int) const +{ + float* a; + float* b; + switch (m_side) + { + case Friendly: + a = friendly; + b = friendly; + break; + case Enemy: + a = enemy; + b = enemy; + break; + case Both: + a = friendly; + b = enemy; + break; + default: + return 0.0f; + } + const float result = internalCompare(a[m_conditional], b[m_secondConditional]); + StrategyManager::getInstance()->isDebugEnabled(); // empty debug branch in the image + return result; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/SCHeterogeneous.h b/Code/BF2/AI/AIDLL/AI/AIStrategic/SCHeterogeneous.h new file mode 100644 index 000000000..e4c7dec2d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/SCHeterogeneous.h @@ -0,0 +1,30 @@ +// Condition comparing two different state values (of one side, or friendly against enemy). +// Evidence: libaidll.so (ia-32) 0x332B20..0x332DD0, vtable 0x4BF4C8. + +#ifndef AI_AIDLL_AI_AISTRATEGIC_SCHETEROGENEOUS_H +#define AI_AIDLL_AI_AISTRATEGIC_SCHETEROGENEOUS_H + +#include "StrategyCondition.h" + +namespace dice { +namespace hfe { +namespace ai { + +class SCHeterogeneous : public StrategyCondition +{ +public: + // ELF 0x332B20: the first conditional goes to the base, the second to +0x24. + SCHeterogeneous(const std::string& name, CompareType compareType, Compare compare, + ConditionSide side, Conditional first, Conditional second, float target); + virtual ~SCHeterogeneous(); + virtual int getType() const { return Heterogeneous; } // ELF 0x332DD0 (weak) + virtual float compare(float* friendly, float* enemy, int side) const; + + /* +0x24 */ Conditional m_secondConditional; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGIC_SCHETEROGENEOUS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/SCHomogeneous.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategic/SCHomogeneous.cpp new file mode 100644 index 000000000..8b34b1984 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/SCHomogeneous.cpp @@ -0,0 +1,50 @@ +// Homogeneous condition. Evidence: libaidll.so (ia-32) 0x332DE0..0x333090. + +#include "SCHomogeneous.h" + +#include "../Main/StrategyManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +SCHomogeneous::SCHomogeneous(const std::string& name, CompareType compareType, Compare compare, + Conditional conditional, float target) + : StrategyCondition(name, target, compare, Both, compareType, conditional) +{ +} + +SCHomogeneous::~SCHomogeneous() +{ +} + +// ELF 0x332FF0. An unknown side answers 0 without comparing. +float SCHomogeneous::compare(float* friendly, float* enemy, int) const +{ + float* a; + float* b; + switch (m_side) + { + case Friendly: + a = friendly; + b = friendly; + break; + case Enemy: + a = enemy; + b = enemy; + break; + case Both: + a = friendly; + b = enemy; + break; + default: + return 0.0f; + } + const float result = internalCompare(a[m_conditional], b[m_conditional]); + StrategyManager::getInstance()->isDebugEnabled(); // empty debug branch in the image + return result; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/SCHomogeneous.h b/Code/BF2/AI/AIDLL/AI/AIStrategic/SCHomogeneous.h new file mode 100644 index 000000000..60151cb2f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/SCHomogeneous.h @@ -0,0 +1,28 @@ +// Condition comparing the same state value of two sides (friendly/friendly, enemy/enemy or +// friendly/enemy). Evidence: libaidll.so (ia-32) 0x332DE0..0x333090, vtable 0x4BF4F0. + +#ifndef AI_AIDLL_AI_AISTRATEGIC_SCHOMOGENEOUS_H +#define AI_AIDLL_AI_AISTRATEGIC_SCHOMOGENEOUS_H + +#include "StrategyCondition.h" + +namespace dice { +namespace hfe { +namespace ai { + +class SCHomogeneous : public StrategyCondition +{ +public: + // ELF 0x332DE0: the side is always Both. + SCHomogeneous(const std::string& name, CompareType compareType, Compare compare, + Conditional conditional, float target); + virtual ~SCHomogeneous(); + virtual int getType() const { return Homogeneous; } // ELF 0x333090 (weak) + virtual float compare(float* friendly, float* enemy, int side) const; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGIC_SCHOMOGENEOUS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/StatusMap.h b/Code/BF2/AI/AIDLL/AI/AIStrategic/StatusMap.h index 03543d555..39e820866 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategic/StatusMap.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/StatusMap.h @@ -1,11 +1,13 @@ -// Strategic status values used by scripts. Unknown input maps to Unknown. -// Writing an out-of-range value also produces Unknown, so such values do not round-trip. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. -// [INFERRED] Source placement. +// A row-major grid of strategic statuses, and the status values used by scripts. Unknown input +// maps to Unknown; writing an out-of-range value also produces Unknown, so such values do not +// round-trip. Evidence: libaidll.so (ia-32) 0x366000..0x3663E8 (AIStrategicMap/StatusMap.cpp); +// sizeof 12, the same shape as ScalarMap. Member names [INFERRED]. [INFERRED] header placement. #ifndef AI_AIDLL_AI_AISTRATEGIC_STATUSMAP_H // [INFERRED] guard style #define AI_AIDLL_AI_AISTRATEGIC_STATUSMAP_H +#include + namespace dice { namespace hfe { namespace ai { @@ -21,6 +23,17 @@ class StatusMap Neutral = 2, Unknown = 3 }; + + // Allocates width * height uninitialised statuses (checkPointer reports a failed allocation). + StatusMap(int width, int height); + ~StatusMap(); + + // Appends the index of every Owned square, row by row. + void getOwnedSquares(std::vector& squares) const; + + /* +0x0 */ int m_width; + /* +0x4 */ int m_height; + /* +0x8 */ Status* m_statuses; }; } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/Strategy.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategic/Strategy.cpp new file mode 100644 index 000000000..c14838ce9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/Strategy.cpp @@ -0,0 +1,274 @@ +// Strategy. Evidence: libaidll.so (ia-32) 0x3330A0..0x333DC0. + +#include "Strategy.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF 0x333DD0, +// __tcf_0 0x333E30, _GLOBAL__I 0x333E60). +#include + +#include "../Main/StrategyManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x3330A0. The counts and +0x2C are left as allocated. The specific-modifier vector is +// resized to 0 (with fill 0.0f) after the object modifiers are reset. +Strategy::Strategy(const std::string& name) + : m_treeModifiers(new TemperatureTreeModifiers()), + m_aggression(0.5f), + m_abortLevel(0.0f), + m_prerequisiteWeight(1.0f), + m_f20(1e9f), + m_prerequisite(0), + m_abortCondition(0), + m_name(name) +{ + clearAllStrategicObjectsModifiers(); + m_specificModifiers.resize(0, 0.0f); +} + +// ELF 0x333460: only the tree modifiers are owned (operator delete, no destructor call); +// prerequisite and abort condition belong to the StrategyManager. +Strategy::~Strategy() +{ + delete m_treeModifiers; +} + +TemperatureTreeModifiers* Strategy::getTemperatureTreeModifiers() const +{ + return m_treeModifiers; +} + +void Strategy::setTemperatureTreeModifiers(TemperatureTreeModifiers* modifiers) +{ + m_treeModifiers = modifiers; +} + +float Strategy::getAggression() const +{ + return m_aggression; +} + +void Strategy::setAggression(float aggression) +{ + m_aggression = aggression; +} + +unsigned int Strategy::getNumberOfAttacks() const +{ + return m_attacks; +} + +void Strategy::setNumberOfAttacks(unsigned int count) +{ + m_attacks = count; +} + +unsigned int Strategy::getNumberOfAttackConsiderations() const +{ + return m_attackConsiderations; +} + +void Strategy::setNumberOfAttackConsiderations(unsigned int count) +{ + m_attackConsiderations = count; +} + +unsigned int Strategy::getNumberOfDefences() const +{ + return m_defences; +} + +void Strategy::setNumberOfDefences(unsigned int count) +{ + m_defences = count; +} + +unsigned int Strategy::getNumberOfDefenceConsiderations() const +{ + return m_defenceConsiderations; +} + +void Strategy::setNumberOfDefenceConsiderations(unsigned int count) +{ + m_defenceConsiderations = count; +} + +void Strategy::setPrerequisite(StrategyPrerequisite* prerequisite) +{ + m_prerequisite = prerequisite; +} + +void Strategy::setAbortCondition(StrategyPrerequisite* condition) +{ + m_abortCondition = condition; +} + +// ELF 0x3337C0: 0 when a required predecessor list exists and does not contain previous, or +// when previous is prohibited; otherwise the weighted prerequisite score. The prerequisite is +// not null-checked. +float Strategy::calculatePrerequisite(float* friendly, float* enemy, Strategy* previous, int side) +{ + StrategyManager::getInstance()->isDebugEnabled(); // empty debug branch in the image + if (!m_requiredPreceding.empty() && m_requiredPreceding.find(previous) == m_requiredPreceding.end()) + return 0.0f; + if (!m_prohibitedPreceding.empty() && m_prohibitedPreceding.find(previous) != m_prohibitedPreceding.end()) + return 0.0f; + return m_prerequisite->evaluate(friendly, enemy, previous == this, side) * m_prerequisiteWeight; +} + +// ELF 0x333890: the abort level minus the abort condition's score (fsubrs +0x18). +float Strategy::calculateAbortCondition(float* friendly, float* enemy, Strategy* previous, int side) +{ + return m_abortLevel - m_abortCondition->evaluate(friendly, enemy, previous == this, side); +} + +float Strategy::setAbortLevel(float level) +{ + return m_abortLevel = level; +} + +float Strategy::getAbortLevel() const +{ + return m_abortLevel; +} + +float Strategy::setPrerequisiteWeight(float weight) +{ + return m_prerequisiteWeight = weight; +} + +float Strategy::getPrerequisiteWeight() const +{ + return m_prerequisiteWeight; +} + +// ELF 0x333930: nodes above 40 are ignored (unsigned compare). +void Strategy::setTreeModifier(TemperatureTreeNode node, float value) +{ + if (static_cast(node) <= 40) + m_treeModifiers->m_nodeModifiers[node] = value; +} + +float Strategy::getTreeModifier(TemperatureTreeNode node) const +{ + return m_treeModifiers->m_nodeModifiers[node]; +} + +// ELF 0x333960. Types outside 0..5 are ignored; the image still carries a type-6 arm that +// sets all six types, unreachable behind the range check, kept as shipped. +void Strategy::setTreeModifier(TemperatureTreeNode node, CombatStrengthType type, float value) +{ + if (static_cast(node) > 40 || type < 0 || type > 5) + return; + if (type == 6) + { + for (int i = 0; i <= 5; ++i) + m_treeModifiers->m_combatStrengthModifiers[node][i] = value; + return; + } + m_treeModifiers->m_combatStrengthModifiers[node][type] = value; +} + +float Strategy::getTreeModifier(TemperatureTreeNode node, CombatStrengthType type) const +{ + return m_treeModifiers->m_combatStrengthModifiers[node][type]; +} + +// ELF 0x3339F0: the same body and the same array as the three-argument setTreeModifier. +void Strategy::setTreeModifierCombatStrength(TemperatureTreeNode node, CombatStrengthType type, float value) +{ + if (static_cast(node) > 40 || type < 0 || type > 5) + return; + if (type == 6) + { + for (int i = 0; i <= 5; ++i) + m_treeModifiers->m_combatStrengthModifiers[node][i] = value; + return; + } + m_treeModifiers->m_combatStrengthModifiers[node][type] = value; +} + +float Strategy::getTreeModifierCombatStrength(TemperatureTreeNode node, CombatStrengthType type) const +{ + return m_treeModifiers->m_combatStrengthModifiers[node][type]; +} + +bool Strategy::addRequiredPrecedingStrategy(Strategy* strategy) +{ + if (!strategy) + return false; + return m_requiredPreceding.insert(strategy).second; +} + +bool Strategy::addProhibitedPrecedingStrategy(Strategy* strategy) +{ + if (!strategy) + return false; + return m_prohibitedPreceding.insert(strategy).second; +} + +void Strategy::setStrategicObjectsModifier(AIStrategicObject::StrategicObjectType type, float value) +{ + for (int status = 0; status < 3; ++status) + m_objectModifiers[status][type] = value; +} + +// ELF 0x333B70: the mean over the three statuses, summed from 0.0f. +float Strategy::getStrategicObjectsModifier(AIStrategicObject::StrategicObjectType type) const +{ + float sum = 0.0f; + for (int status = 0; status < 3; ++status) + sum += m_objectModifiers[status][type]; + return sum / 3.0f; +} + +void Strategy::setStrategicObjectsModifier(AIStrategicObject::StrategicObjectType type, float value, StatusMap::Status status) +{ + m_objectModifiers[status][type] = value; +} + +float Strategy::getStrategicObjectsModifier(AIStrategicObject::StrategicObjectType type, StatusMap::Status status) const +{ + return m_objectModifiers[status][type]; +} + +// ELF 0x333C20: negative indices are ignored; the vector grows with 1.0f to cover the index. +void Strategy::setSpecificStrategicObjectModifier(int object, float value) +{ + if (object < 0) + return; + if (object >= static_cast(m_specificModifiers.size())) + m_specificModifiers.resize(object + 1, 1.0f); + m_specificModifiers[object] = value; +} + +float Strategy::getSpecificStrategicObjectModifier(int object) const +{ + if (object >= 0 && object < static_cast(m_specificModifiers.size())) + return m_specificModifiers[object]; + return 1.0f; +} + +const float* Strategy::getStrategicObjectsModifiers(StatusMap::Status status) const +{ + return m_objectModifiers[status]; +} + +// ELF 0x333D70. +void Strategy::clearAllStrategicObjectsModifiers() +{ + for (int type = 0; type <= 26; ++type) + for (int status = 0; status < 3; ++status) + m_objectModifiers[status][type] = 1.0f; +} + +const std::string& Strategy::getName() const +{ + return m_name; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/Strategy.h b/Code/BF2/AI/AIDLL/AI/AIStrategic/Strategy.h new file mode 100644 index 000000000..4f2a1a22e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/Strategy.h @@ -0,0 +1,96 @@ +// A strategy of the strategic AI: the number of attacks/defences it runs, its aggression, the +// prerequisite and abort conditions that score it, which strategies may precede it, and the +// temperature and strategic-object modifiers it applies while active. The StrategyManager +// (Main) builds strategies from the ai/Strategies.ai scripts and owns them; SAI borrows them. +// Evidence: libaidll.so (ia-32) Strategy.cpp 0x3330A0..0x333DC0. + +#ifndef AI_AIDLL_AI_AISTRATEGIC_STRATEGY_H +#define AI_AIDLL_AI_AISTRATEGIC_STRATEGY_H + +#include +#include +#include + +#include "StatusMap.h" +#include "StrategyCondition.h" +#include "StrategyPrerequisite.h" +#include "../AIStrategicEntity/AIStrategicObject.h" +#include "../AIStrategicMap/TemperatureTreeModifiers.h" + +namespace dice { +namespace hfe { +namespace ai { + +enum TemperatureTreeNode : int; // index 0..40 (setTreeModifier checks > 0x28) +enum CombatStrengthType : int; // 0..5 per tree node + +class Strategy +{ +public: + explicit Strategy(const std::string& name); // ELF 0x3332E0 (complete) / 0x3330A0 + ~Strategy(); // ELF 0x333460 / 0x3335A0 + + TemperatureTreeModifiers* getTemperatureTreeModifiers() const; + void setTemperatureTreeModifiers(TemperatureTreeModifiers* modifiers); + float getAggression() const; + void setAggression(float aggression); + unsigned int getNumberOfAttacks() const; + void setNumberOfAttacks(unsigned int count); + unsigned int getNumberOfAttackConsiderations() const; + void setNumberOfAttackConsiderations(unsigned int count); + unsigned int getNumberOfDefences() const; + void setNumberOfDefences(unsigned int count); + unsigned int getNumberOfDefenceConsiderations() const; + void setNumberOfDefenceConsiderations(unsigned int count); + void setPrerequisite(StrategyPrerequisite* prerequisite); + void setAbortCondition(StrategyPrerequisite* condition); + float calculatePrerequisite(float* friendly, float* enemy, Strategy* previous, int side); + float calculateAbortCondition(float* friendly, float* enemy, Strategy* previous, int side); + float setAbortLevel(float level); // fsts: the value stays in st0 + float getAbortLevel() const; + float setPrerequisiteWeight(float weight); // fsts: the value stays in st0 + float getPrerequisiteWeight() const; + + void setTreeModifier(TemperatureTreeNode node, float value); + float getTreeModifier(TemperatureTreeNode node) const; + void setTreeModifier(TemperatureTreeNode node, CombatStrengthType type, float value); + float getTreeModifier(TemperatureTreeNode node, CombatStrengthType type) const; + void setTreeModifierCombatStrength(TemperatureTreeNode node, CombatStrengthType type, float value); + float getTreeModifierCombatStrength(TemperatureTreeNode node, CombatStrengthType type) const; + bool addRequiredPrecedingStrategy(Strategy* strategy); // null -> false + bool addProhibitedPrecedingStrategy(Strategy* strategy); // null -> false + void setStrategicObjectsModifier(AIStrategicObject::StrategicObjectType type, float value); // all three statuses + float getStrategicObjectsModifier(AIStrategicObject::StrategicObjectType type) const; // mean of the three + void setStrategicObjectsModifier(AIStrategicObject::StrategicObjectType type, float value, StatusMap::Status status); + float getStrategicObjectsModifier(AIStrategicObject::StrategicObjectType type, StatusMap::Status status) const; + void setSpecificStrategicObjectModifier(int object, float value); + float getSpecificStrategicObjectModifier(int object) const; // 1.0f outside the vector + const float* getStrategicObjectsModifiers(StatusMap::Status status) const; + void clearAllStrategicObjectsModifiers(); // 3 x 27 floats to 1.0f + const std::string& getName() const; + + // ELF layout (sizeof 0x1A8 on ia-32). Names [INFERRED] from the accessors. + /* +0x000 */ TemperatureTreeModifiers* m_treeModifiers; // owned, new'ed by the constructor + /* +0x004 */ float m_aggression; // 0.5f + /* +0x008 */ unsigned int m_attacks; // not written by the constructor + /* +0x00C */ unsigned int m_defences; + /* +0x010 */ unsigned int m_attackConsiderations; + /* +0x014 */ unsigned int m_defenceConsiderations; + /* +0x018 */ float m_abortLevel; // 0.0f + /* +0x01C */ float m_prerequisiteWeight; // 1.0f + /* +0x020 */ float m_f20; // 1e9f [UNRESOLVED] no reader in Strategy.cpp + /* +0x024 */ StrategyPrerequisite* m_prerequisite; // 0; borrowed + /* +0x028 */ StrategyPrerequisite* m_abortCondition; // 0; borrowed + /* +0x02C */ int m_i2C; // not written by the constructor [UNRESOLVED] + /* +0x030 */ std::set m_requiredPreceding; + /* +0x03C */ std::set m_prohibitedPreceding; + /* +0x048 */ float m_objectModifiers[3][27]; // [status][object type], stride 0x6C + /* +0x18C */ std::vector m_specificModifiers; // per strategic-object index + /* +0x198 */ std::string m_name; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGIC_STRATEGY_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/StrategyCondition.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategic/StrategyCondition.cpp new file mode 100644 index 000000000..0afe5ba1f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/StrategyCondition.cpp @@ -0,0 +1,158 @@ +// Strategy condition base: the crisp and fuzzy comparisons shared by all condition kinds. +// Evidence: libaidll.so (ia-32) 0x334150..0x334570. + +#include "StrategyCondition.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF 0x334580, +// __tcf_0 0x3345E0, _GLOBAL__I 0x334610). +#include + +#include + +namespace dice { +namespace hfe { +namespace ai { + +StrategyCondition::StrategyCondition(const std::string& name, float target, Compare compare, + ConditionSide side, CompareType compareType, + Conditional conditional) + : m_isAbortCondition(false), + m_targetValue(target), + m_compare(compare), + m_compareType(compareType), + m_side(side), + m_conditional(conditional), + m_strength(Required), + m_name(name) +{ +} + +float StrategyCondition::setTargetValue(float value) +{ + return m_targetValue = value; +} + +float StrategyCondition::getTargetValue() const +{ + return m_targetValue; +} + +void StrategyCondition::setConditionStrength(ConditionStrength strength) +{ + m_strength = strength; +} + +StrategyCondition::ConditionStrength StrategyCondition::getConditionStrength() const +{ + return m_strength; +} + +// ELF 0x334270. FuzzySqr keeps the sign of the fuzzy distance and squares its magnitude. +float StrategyCondition::internalCompare(float a, float b) const +{ + switch (m_compareType) + { + case Crisp: + return internalCompareCrisp(a, b); + case Fuzzy: + return internalCompareFuzzy(a, b); + case FuzzySqr: + { + const float r = internalCompareFuzzy(a, b); + const float sign = r > 0.0f ? 1.0f : (r < 0.0f ? -1.0f : 0.0f); + return sign * (r * r); + } + default: + return 0.0f; + } +} + +// ELF 0x334320: 1 when the relation to the target holds, -1 otherwise. A zero divisor answers +// -1, except QuotientGreater, which answers 1. +float StrategyCondition::internalCompareCrisp(float a, float b) const +{ + float x; + switch (m_compare) + { + case Equal: + case Difference: + x = a - b; + return x == m_targetValue ? 1.0f : -1.0f; + case EqualGreater: + case DifferenceGreater: + x = a - b; + return x < m_targetValue ? -1.0f : 1.0f; + case EqualSmaller: + case DifferenceSmaller: + x = a - b; + return m_targetValue < x ? -1.0f : 1.0f; + case Quotient: + if (b == 0.0f) + return -1.0f; + x = a / b; + return x == m_targetValue ? 1.0f : -1.0f; + case QuotientGreater: + if (b == 0.0f) + return 1.0f; + x = a / b; + return x < m_targetValue ? -1.0f : 1.0f; + case QuotientSmaller: + if (b == 0.0f) + return -1.0f; + x = a / b; + return m_targetValue < x ? -1.0f : 1.0f; + default: + return 0.0f; + } +} + +// ELF 0x334440: the signed distance to the target (negated absolute distance for the Equal +// kinds). A zero divisor answers -1000, except QuotientGreater, which answers 1000. +float StrategyCondition::internalCompareFuzzy(float a, float b) const +{ + switch (m_compare) + { + case Equal: + case Difference: + return -std::fabs(a - b - m_targetValue); + case EqualGreater: + case DifferenceGreater: + return a - b - m_targetValue; + case EqualSmaller: + case DifferenceSmaller: + return -(a - b - m_targetValue); + case Quotient: + if (b == 0.0f) + return -1000.0f; + return -std::fabs(a / b - m_targetValue); + case QuotientGreater: + if (b == 0.0f) + return 1000.0f; + return a / b - m_targetValue; + case QuotientSmaller: + if (b == 0.0f) + return -1000.0f; + return -(a / b - m_targetValue); + default: + return 0.0f; + } +} + +bool StrategyCondition::setIsAbortCondition(bool abort) +{ + return m_isAbortCondition = abort; +} + +bool StrategyCondition::getIsAbortCondition() const +{ + return m_isAbortCondition; +} + +bool StrategyCondition::isAbortCondition() const +{ + return m_isAbortCondition; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/StrategyCondition.h b/Code/BF2/AI/AIDLL/AI/AIStrategic/StrategyCondition.h new file mode 100644 index 000000000..5cbbe3611 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/StrategyCondition.h @@ -0,0 +1,116 @@ +// One condition of a strategy prerequisite: compares a value of the 44-entry strategic state +// arrays (SAI::updateStates) with a target and answers a score in [-1, 1] (crisp) or a distance +// (fuzzy). Subclasses choose the operands: SCConstant, SCHomogeneous, SCHeterogeneous, SCArea. +// Evidence: libaidll.so (ia-32) 0x332790..0x333090 and 0x334150..0x334570; vtable 0x4BF470 +// {D1, D0, getType, compare = __cxa_pure_virtual}. Enumerator names are the strings the +// shipped stream operators print (0x3C5D20..0x3C6D30); member names are [INFERRED]. + +#ifndef AI_AIDLL_AI_AISTRATEGIC_STRATEGYCONDITION_H +#define AI_AIDLL_AI_AISTRATEGIC_STRATEGYCONDITION_H + +#include + +namespace dice { +namespace hfe { +namespace ai { + +class StrategyCondition +{ +public: + // getType: SCConstant 0, SCHomogeneous 1, SCHeterogeneous 2, SCArea 3, the base 4. The + // printer names only 0..2. + // Fixed int representation also admits the parser's unnamed fallback value 4. + enum ConditionType : int + { + Constant = 0, + Homogeneous = 1, + Heterogeneous = 2 + }; + + enum ConditionStrength + { + Required = 0, + RequiredPositive = 1, + RequiredNegative = 2, + Advisory = 3, + AdvisoryPositive = 4, + AdvisoryNegative = 5 + }; + + enum CompareType + { + Crisp = 0, + Fuzzy = 1, + FuzzySqr = 2 + }; + + enum ConditionSide + { + Friendly = 0, + Enemy = 1, + Both = 2 + }; + + // Equal* compare the difference a - b, Quotient* the quotient a / b, Difference* repeat the + // Equal* arms (internalCompareCrisp/Fuzzy jump tables 0x4A2A00 / 0x4A2A24). + enum Compare + { + Equal = 0, + EqualGreater = 1, + EqualSmaller = 2, + Quotient = 3, + QuotientGreater = 4, + QuotientSmaller = 5, + Difference = 6, + DifferenceGreater = 7, + DifferenceSmaller = 8 + }; + + // Index into the 44-float state arrays. Spelled as the printer spells it ("Infantery"). + enum Conditional + { + Carrier = 0, BattleShip = 1, LCVP = 2, Naval = 3, Bomber = 4, Fighter = 5, AntiAir = 6, + Air = 7, Infantery = 8, Artillery = 9, AntiTank = 10, HeavyAttack = 11, FastAttack = 12, + Ticket = 13, ControlPoint = 14, Time = 15, StartTime = 16, Attacks = 17, Defences = 18, + NumberOfFriendlyAreas = 19, NumberOfNeutralAreas = 20, NumberOfHostileAreas = 21, + Flank = 22, Base = 23, Close = 24, Centre = 25, Remote = 26, Route = 27, Bridge = 28, + North = 29, West = 30, South = 31, East = 32, FrontFlank = 33, FrontBase = 34, + FrontClose = 35, FrontCentre = 36, FrontRemote = 37, FrontNeutral = 38, Front = 39, + Safe = 40, EnemyObject = 41, UnReachable = 42, UnitConstant = 43 + }; + + // ELF 0x334150: vptr, abort flag false, strength 0 (Required), name copied last. + StrategyCondition(const std::string& name, float target, Compare compare, ConditionSide side, + CompareType compareType, Conditional conditional); + virtual ~StrategyCondition() {} // ELF 0x332790 (weak) + virtual int getType() const { return 4; } // ELF 0x332860 (weak) + virtual float compare(float* friendly, float* enemy, int side) const = 0; + + float setTargetValue(float value); // ELF 0x334230; fsts leaves the value in st0 + float getTargetValue() const; + void setConditionStrength(ConditionStrength strength); + ConditionStrength getConditionStrength() const; + bool setIsAbortCondition(bool abort); // ELF 0x334540; answers the stored flag + bool getIsAbortCondition() const; + bool isAbortCondition() const; + + float internalCompare(float a, float b) const; + float internalCompareCrisp(float a, float b) const; + float internalCompareFuzzy(float a, float b) const; + + /* +0x00 */ // vptr + /* +0x04 */ bool m_isAbortCondition; + /* +0x08 */ float m_targetValue; + /* +0x0C */ Compare m_compare; + /* +0x10 */ CompareType m_compareType; + /* +0x14 */ ConditionSide m_side; + /* +0x18 */ Conditional m_conditional; + /* +0x1C */ ConditionStrength m_strength; + /* +0x20 */ std::string m_name; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGIC_STRATEGYCONDITION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/StrategyPrerequisite.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategic/StrategyPrerequisite.cpp new file mode 100644 index 000000000..0b0eeeacc --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/StrategyPrerequisite.cpp @@ -0,0 +1,84 @@ +// Strategy prerequisite. Evidence: libaidll.so (ia-32) 0x334630..0x334AA0. + +#include "StrategyPrerequisite.h" + +#include "StrategyCondition.h" +#include "../Main/StrategyManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x334630: the list is cleared again after the name is copied. +StrategyPrerequisite::StrategyPrerequisite(const std::string& name) + : m_name(name) +{ + m_conditions.clear(); +} + +StrategyPrerequisite::~StrategyPrerequisite() +{ +} + +// ELF 0x334880: null conditions are ignored. +void StrategyPrerequisite::addCondition(StrategyCondition* condition, float weight) +{ + if (condition) + m_conditions.push_back(std::make_pair(condition, weight)); +} + +// ELF 0x3348E0: the image counts the list (size(), not empty()). +StrategyCondition* StrategyPrerequisite::popFirstCondition() +{ + if (m_conditions.size() == 0) + return 0; + StrategyCondition* const condition = m_conditions.begin()->first; + m_conditions.erase(m_conditions.begin()); + return condition; +} + +// ELF 0x334960: the sum of weighted condition scores. A Required(Positive) condition scoring +// below zero, or a RequiredNegative one above zero, makes the whole prerequisite 0 at once; +// the Advisory kinds clamp their contribution instead. +float StrategyPrerequisite::evaluate(float* friendly, float* enemy, bool isActive, int side) +{ + float sum = 0.0f; + for (std::list >::iterator it = m_conditions.begin(); + it != m_conditions.end(); ++it) + { + if (!isActive && it->first->isAbortCondition()) + continue; + float value = it->first->compare(friendly, enemy, side) * it->second; + switch (it->first->getConditionStrength()) + { + case StrategyCondition::Required: + case StrategyCondition::RequiredPositive: + if (0.0f > value) + return 0.0f; + break; + case StrategyCondition::RequiredNegative: + if (value > 0.0f) + return 0.0f; + break; + case StrategyCondition::Advisory: + break; + case StrategyCondition::AdvisoryPositive: + if (0.0f > value) + value = 0.0f; + break; + case StrategyCondition::AdvisoryNegative: + if (value > 0.0f) + value = 0.0f; + break; + default: + break; + } + sum += value; + } + StrategyManager::getInstance()->isDebugEnabled(); // empty debug branch in the image + return sum; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/StrategyPrerequisite.h b/Code/BF2/AI/AIDLL/AI/AIStrategic/StrategyPrerequisite.h new file mode 100644 index 000000000..f9badfb94 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/StrategyPrerequisite.h @@ -0,0 +1,38 @@ +// A weighted list of strategy conditions; Strategy uses one as its prerequisite and one as its +// abort condition. Evidence: libaidll.so (ia-32) 0x334630..0x334AA0. Conditions are borrowed +// (the destructor frees only the list nodes); the StrategyManager owns them. + +#ifndef AI_AIDLL_AI_AISTRATEGIC_STRATEGYPREREQUISITE_H +#define AI_AIDLL_AI_AISTRATEGIC_STRATEGYPREREQUISITE_H + +#include +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +class StrategyCondition; + +class StrategyPrerequisite +{ +public: + explicit StrategyPrerequisite(const std::string& name); + ~StrategyPrerequisite(); + + void addCondition(StrategyCondition* condition, float weight); + StrategyCondition* popFirstCondition(); + // isActive: the strategy being scored is the current one (Strategy passes previous == this); + // only then do abort conditions count. + float evaluate(float* friendly, float* enemy, bool isActive, int side); + + /* +0x00 */ std::list > m_conditions; + /* +0x04 */ std::string m_name; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGIC_STRATEGYPREREQUISITE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZone.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZone.cpp new file mode 100644 index 000000000..6d3988dee --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZone.cpp @@ -0,0 +1,242 @@ +// AI landing zones. Evidence: libaidll.so (ia-32) 0x334BB0..0x335480. + +#include "AILandingZone.h" + +#include +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x3353D0, __tcf_0 0x335430, _GLOBAL__I 0x335460). +#include + +#include "../Main/AIRandom.h" +#include "../Main/IAIPathfinding.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// The image's inline uniform draw: lo + next() * 2^-32 * (hi - lo), unrounded until the store. +float randomBetween(float lo, float hi) +{ + const float range = hi - lo; + return lo + AIRandom::m_instance->next() * 2.3283064e-10f * range; +} + +} // namespace + +// ELF 0x334BB0 (C2; C1 0x334C40). +AILandingZone::AILandingZone(const std::string& name, int id, const Vec2& minCorner, + const Vec2& maxCorner, float height, + LandingZoneDirection beachDirection) + : m_minCorner(minCorner) + , m_maxCorner(maxCorner) + , m_beachDirection(beachDirection) + , m_name(name) + , m_id(id) + , m_height(height) +{ + if (m_minCorner.x > m_maxCorner.x) + { + const float x = m_minCorner.x; + m_minCorner.x = m_maxCorner.x; + m_maxCorner.x = x; + } + if (m_minCorner.y > m_maxCorner.y) + { + const float y = m_minCorner.y; + m_minCorner.y = m_maxCorner.y; + m_maxCorner.y = y; + } +} + +// ELF 0x334CD0 (D2; D1 0x334D20): the name is the only member with a destructor. +AILandingZone::~AILandingZone() +{ +} + +// ELF 0x334D70. The approach comes from the side opposite the beach; the modulo keeps the shipped +// sign test on the sum, not on the remainder. The pathfinder singleton is read once. +bool AILandingZone::getApproachPosition(int map, int type, Vec3& position, float distance) const +{ + IAIPathfinding* const pathfinding = IAIPathfinding::instance; + int attempts = 0; + const int opposite = m_beachDirection + 2; + const LandingZoneDirection side = + static_cast(opposite < 0 ? opposite % 4 + 4 : opposite % 4); + getRandomPosOnSide(side, map, position, distance); + do + { + if (pathfinding->isValidPosition(map, type, position, true)) + return true; + ++attempts; + getRandomPosOnSide(side, map, position, distance); + } while (attempts < 20); + return false; +} + +// ELF 0x334E60. +bool AILandingZone::getBeachPosition(int map, Vec3& position) const +{ + getRandomPosOnSide(m_beachDirection, map, position, 0.0f); + return true; +} + +// ELF 0x334EB0. +LandingZoneDirection AILandingZone::getBeachDirection() const +{ + return m_beachDirection; +} + +// ELF 0x334EC0. +void AILandingZone::setBeachDirection(LandingZoneDirection direction) +{ + m_beachDirection = direction; +} + +// ELF 0x334ED0. +bool AILandingZone::isInZone(const Vec2& position) const +{ + return insideCornerBox(position, m_minCorner, m_maxCorner); +} + +// ELF 0x334F10. +bool AILandingZone::isInZone(const Vec3& position) const +{ + Vec2 xz; + xz.x = 0.0f; + xz.y = 0.0f; + vec3ToVec2XZ(position, xz); + return isInZone(xz); +} + +// ELF 0x334F70. The direction from the centre is normalised inline as the image does elsewhere: +// left alone within FLT_EPSILON of unit length, zeroed below FLT_EPSILON squared, otherwise scaled +// by 1 / sqrt. Both tests are written so that NaN takes the scaling arm, as the shipped `ja` / +// `jbe` pair does. +float AILandingZone::getDistanceSqr(const Vec2& position) const +{ + if (isInZone(position)) + return 0.0f; + + Vec2 centre; + centre.x = 0.0f; + centre.y = 0.0f; + Vec2 direction; + direction.x = 0.0f; + direction.y = 0.0f; + Vec2 exit; + exit.x = 0.0f; + exit.y = 0.0f; + getBoxCentre(m_minCorner, centre, m_maxCorner); + direction.x = position.x - centre.x; + direction.y = position.y - centre.y; + const float lengthSq = direction.x * direction.x + direction.y * direction.y; + if (!(1.1920929e-07f > std::fabs(lengthSq - 1.0f))) + { + if (!(1.4210855e-14f > std::fabs(lengthSq))) + { + const float inverse = 1.0f / std::sqrt(lengthSq); + direction.x = direction.x * inverse; + direction.y = inverse * direction.y; + } + else + { + direction.x = 0.0f; + direction.y = 0.0f; + } + } + hfe::getIntersection(m_minCorner, m_maxCorner, direction, centre, exit); + const float dx = position.x - exit.x; + const float dy = position.y - exit.y; + return dx * dx + dy * dy; +} + +// ELF 0x335120. +float AILandingZone::getDistanceSqr(const Vec3& position) const +{ + Vec2 xz; + xz.x = 0.0f; + xz.y = 0.0f; + vec3ToVec2XZ(position, xz); + return getDistanceSqr(xz); +} + +// ELF 0x335170. +const std::string& AILandingZone::getName() const +{ + return m_name; +} + +// ELF 0x335180. +int AILandingZone::getId() const +{ + return m_id; +} + +// ELF 0x335190. +const Vec2& AILandingZone::getMinCorner() const +{ + return m_minCorner; +} + +// ELF 0x3351A0. +const Vec2& AILandingZone::getMaxCorner() const +{ + return m_maxCorner; +} + +// ELF 0x3351B0. +void AILandingZone::setMinCorner(const Vec2& corner) +{ + m_minCorner = corner; +} + +// ELF 0x3351D0. +void AILandingZone::setMaxCorner(const Vec2& corner) +{ + m_maxCorner = corner; +} + +// ELF 0x3351F0. Both ranges are taken before the first draw; x is drawn before z. +void AILandingZone::getRandomPosOnSide(LandingZoneDirection side, int, Vec3& position, + float distance) const +{ + float fromX; + float toX; + float fromZ; + float toZ; + switch (side) + { + case LZXMin: + fromX = toX = m_minCorner.x + distance; + fromZ = m_minCorner.y; + toZ = m_maxCorner.y; + break; + case LZZMin: + fromX = m_minCorner.x; + toX = m_maxCorner.x; + fromZ = toZ = m_minCorner.y + distance; + break; + case LZXMax: + fromX = toX = m_maxCorner.x - distance; + fromZ = m_minCorner.y; + toZ = m_maxCorner.y; + break; + case LZZMax: + fromX = m_minCorner.x; + toX = m_maxCorner.x; + fromZ = toZ = m_maxCorner.y - distance; + break; + default: + fromX = toX = fromZ = toZ = 0.0f; + break; + } + position.x = randomBetween(fromX, toX); + position.y = m_height; + position.z = randomBetween(fromZ, toZ); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZone.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZone.h new file mode 100644 index 000000000..bdc195f4a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZone.h @@ -0,0 +1,81 @@ +// A rectangular landing zone on the XZ plane with a beach side, used by the amphibious waypoints. +// Not polymorphic: the image has no vtable and no deleting destructor for it. sizeof is 32 (0x20) +// in the ia-32 image with its libstdc++ string; the native size differs. +// Placement in AIStrategicEntity is [INFERRED]: the TU sits in the image between +// StrategyPrerequisite and AIStrategicArea. +#ifndef AI_AIDLL_AI_AISTRATEGICENTITY_AILANDINGZONE_H +#define AI_AIDLL_AI_AISTRATEGICENTITY_AILANDINGZONE_H + +#include + +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +// The side of the zone a beach landing comes from. Names and values from the image's stream +// operators (ELF 0x3C89A0 / 0x3C8A20), which also accept them without the "LZ" prefix. +enum LandingZoneDirection : int +{ + LZXMin = 0, + LZZMin = 1, + LZXMax = 2, + LZZMax = 3, + LZUndefined = 4 +}; + +class AILandingZone +{ +public: + // The corners are sorted per axis after the copy, so minCorner <= maxCorner. + AILandingZone(const std::string& name, int id, const Vec2& minCorner, const Vec2& maxCorner, + float height, LandingZoneDirection beachDirection); + ~AILandingZone(); + + // A random position on the side opposite the beach, `distance` inside the zone, that the + // pathfinder accepts (IAIPathfinding::isValidPosition(map, type, position, true)); up to 21 + // draws. False when none was accepted; `position` then holds the last draw. + bool getApproachPosition(int map, int type, Vec3& position, float distance) const; + // A random position on the beach side's edge. Always true. + bool getBeachPosition(int map, Vec3& position) const; + LandingZoneDirection getBeachDirection() const; + void setBeachDirection(LandingZoneDirection direction); + // Inclusive XZ box test. + bool isInZone(const Vec2& position) const; + bool isInZone(const Vec3& position) const; + // 0 inside the zone; otherwise the squared distance to where the ray from the centre towards + // `position` leaves the box. + float getDistanceSqr(const Vec2& position) const; + float getDistanceSqr(const Vec3& position) const; + const std::string& getName() const; + int getId() const; + const Vec2& getMinCorner() const; + const Vec2& getMaxCorner() const; + void setMinCorner(const Vec2& corner); + void setMaxCorner(const Vec2& corner); + // A uniformly random point on the line `distance` inside the given side, at the zone's height. + // An undefined side yields (0, height, 0); both random draws are still taken. `map` is unused. + void getRandomPosOnSide(LandingZoneDirection side, int map, Vec3& position, + float distance) const; + +private: + // AIStrategicArea::attachLandingZone / ::listLandingZones (ELF 0x33B580, 0x33B7A0) and + // AILandingZoneManager::activeZone / ::listZones read m_name at +0x14 directly instead of + // calling getName. [INFERRED] friendship. + friend class AIStrategicArea; + friend class AILandingZoneManager; // activeZone / listZones, same direct read + + /* +0x00 */ Vec2 m_minCorner; + /* +0x08 */ Vec2 m_maxCorner; + /* +0x10 */ LandingZoneDirection m_beachDirection; + /* +0x14 */ std::string m_name; + /* +0x18 */ int m_id; + /* +0x1C */ float m_height; // y of every position the zone hands out [INFERRED name] +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGICENTITY_AILANDINGZONE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZoneManager.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZoneManager.cpp deleted file mode 100644 index 1a62116de..000000000 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZoneManager.cpp +++ /dev/null @@ -1,54 +0,0 @@ -// [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining AILandingZoneManager operations. - -#include "AILandingZoneManager.h" - -#include "../Main/AIDllFrontier.h" - -namespace dice { -namespace hfe { -namespace ai { - -AILandingZoneManager* AILandingZoneManager::m_instance = 0; - -// Initializes an inactive landing-zone manager and explicitly resizes its new vector to zero. -AILandingZoneManager::AILandingZoneManager() - : m_unresolved1C(0) - , m_unresolved20(0) - , m_activeZoneName("No valid zone is active") -{ - m_zones.resize(0); -} - -// Constructs the landing-zone manager at DLL load. BF2AI::clear owns its later destruction. -namespace { - -struct AILandingZoneManagerInstaller -{ - AILandingZoneManagerInstaller() - { - AILandingZoneManager::m_instance = new AILandingZoneManager(); - } -}; - -AILandingZoneManagerInstaller g_aiLandingZoneManagerInstaller; - -} // namespace - -// [FRONTIER] - the rest of the class. Addresses and sizes are in the header. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - -AILandingZoneManager::~AILandingZoneManager() -{ - BF2_AI_FRONTIER("dice::hfe::ai::AILandingZoneManager::~AILandingZoneManager"); -} - -void AILandingZoneManager::reset() -{ - BF2_AI_FRONTIER("dice::hfe::ai::AILandingZoneManager::reset"); -} - -} // namespace ai -} // namespace hfe -} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZoneManager.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZoneManager.h deleted file mode 100644 index 9d4a74e4a..000000000 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZoneManager.h +++ /dev/null @@ -1,66 +0,0 @@ -// Owns AI landing zones. Constructed when the DLL loads and destroyed by BF2AI::clear. -// reset is its only virtual method; the destructor is nonvirtual. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. -// [INFERRED] Source placement. - -#ifndef AI_AIDLL_AI_AISTRATEGICENTITY_AILANDINGZONEMANAGER_H // [INFERRED] guard style -#define AI_AIDLL_AI_AISTRATEGICENTITY_AILANDINGZONEMANAGER_H - -#include -#include -#include - -// Vec2 and Vec3 are Math aliases, so do not forward-declare them as classes in this namespace. -namespace dice { -namespace hfe { -namespace ai { - -class AILandingZone; - -// [UNRESOLVED] enumerators - one dword at `createLandingZone`'s last parameter. -enum LandingZoneDirection : int; - -// sizeof is 40 (0x28) in retail, from the `operator new(0x28)` in this file's static initialiser -// and it will not be 40 here - two of the members are real STL containers and a third is a string. -class AILandingZoneManager -{ -public: - AILandingZoneManager(); - - // not virtual - see the header block. , . - ~AILandingZoneManager(); // [FRONTIER] - - // The class's only virtual, and the only entry in its vtable. - virtual void reset(); // [FRONTIER] - - // - written inline because the shipped body is the vector size and nothing - // else. This is the method `AIRenderUtil`'s constructor calls. - int getNumberOfLandingZones() const - { - return static_cast(m_zones.size()); - } - - // [FRONTIER] Remaining landing-zone operations require implementation. - - // set by this file'S static initialiser, not by any `init`. See the header block. - static AILandingZoneManager* m_instance; - -private: - /* +0x00 */ // vptr - one slot, `reset` - /* +0x04 */ std::map m_zonesByName; - /* +0x10 */ std::vector m_zones; // what getNumberOfLandingZones measures - - // [UNRESOLVED] Two words initialized to zero; their roles are not yet established. - /* +0x1C */ int m_unresolved1C; - /* +0x20 */ int m_unresolved20; - - // constructed from A literal, and the literal is the class's whole personality: - // "No valid zone is active". - /* +0x24 */ std::string m_activeZoneName; -}; - -} // namespace ai -} // namespace hfe -} // namespace dice - -#endif // AI_AIDLL_AI_AISTRATEGICENTITY_AILANDINGZONEMANAGER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicArea.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicArea.cpp index 1c78ed584..b207b2a19 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicArea.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicArea.cpp @@ -1,8 +1,11 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining AIStrategicArea operations. - #include "AIStrategicArea.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x33F260, __tcf_0 0x33F2C0, _GLOBAL__I 0x33F2F0). +#include +#include #include // the two centre-to-corner distances +#include // listLandingZones #include "../AIUtils/checkPointer.h" #include "../Main/AIDllFrontier.h" @@ -10,13 +13,28 @@ #include "../Main/CommonSingletonServer.h" #include "../Main/IAIPathfinding.h" #include "../AIBot/SquadManager.h" -#include "../AIBotBehaviour/CustomCurve.h" +#include "../AIBot/SquadCoordinator.h" +#include "../AIUtils/CustomCurve.h" #include "../AIStrategic/SAI.h" +#include "../AIStrategic/Strategy.h" +#include "AIStrategicObjectManager.h" +#include "../AIBot/BotMain.h" +#include "../Main/IBotManager.h" +#include "../Main/AIMain.h" // IAIMain::m_instance->getSAI #include "../AIKnowledge/BFInformationEnvironment.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/Information.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIBot/SquadMember.h" // isSameWaypointList +#include "../AIBot/WPMoveTo.h" +#include "../AIBot/WPAltitudeMoveTo.h" +#include "../Main/AIRandom.h" +#include "SAWayPoint.h" +#include "AILandingZone.h" +#include "../Main/AILandingZoneManager.h" +#include "../AIKnowledge/AIInformationGrid.h" #include "../../../AIInterface/BFKnowledge/BFGame.h" // IAIGame - the control-point queries #include "../../../AIInterface/BFKnowledge/BFTerrain.h" // IAITerrain::getTerrainAltitude #include "../../../../Math/Vec3.h" // vec3ToVec2XZ / vec2ToVec3XZ @@ -25,13 +43,92 @@ namespace dice { namespace hfe { namespace ai { +namespace { + +// libaidll.so: std::list<(anonymous namespace)::ObjectSearchInfo> in AIStrategicArea.cpp, node +// 0x14 = twelve payload bytes, written as {object, predecessor, cost} by getDistances. +// [INFERRED] field names. +struct ObjectSearchInfo +{ + ObjectSearchInfo(AIStrategicObject* o, AIStrategicObject* p, float c) + : object(o), previous(p), cost(c) {} + AIStrategicObject* object; + AIStrategicObject* previous; + float cost; +}; + +// ELF vtable 0x4BF5F0: this TU's own predicate (mangled under AIStrategicArea.cpp's anonymous +// namespace; BotSpawner.cpp has a separate class of the same name). One slot, no destructor. +// Layout: vptr, side (+4). +class FreeUnitPred : public IAIInformationGridPredicate +{ +public: + explicit FreeUnitPred(int side) : m_side(side) {} + + // ELF 0x340B90. A known mobile unit (not types 0x80 / 0x200000) passes when it or one of its + // secondary objects is unoccupied. Only the root record's type and mobility are checked. + bool includeInformation(Information* information) const + { + if (!information->getUnit() || !information->hasMobile()) + return false; + if (information->isOfType(ITNaval) || information->isOfType(ITSoldier)) + return false; + + int iterator = information->getFirstSecondaryObjectIterator(); + Information* current = information; + while (current) + { + if (!current->getUnit()->isOccupied()) + return true; + // The ELF captures the manager before the secondary-object call. + InformationManager* const manager = informationManager; + const unsigned int handle = information->getSecondaryObject(iterator, m_side); + current = manager->getInformation(handle); + } + return false; + } + + int m_side; +}; + +} // namespace + +// ELF 0x335480 (C2; C1 0x335850). An area with explicit bounds: control point id -1, no +// control-point phase, the corner stored before the shared tail runs. +AIStrategicArea::AIStrategicArea(const std::string& name, Vec2 topLeft, Vec2 centre, float height, + float radius) + : AIStrategicObject(radius, height) + , m_list268() + , m_centre(topLeft) + , m_orderPos(checkPointer(new MapData[IAIPathfinding::instance->getNumberOfMaps()])) + , m_neighbours() + , m_neighbouringObjects() + , m_name(name) + , m_objectTypeFlags(0) + , m_controlPointId(static_cast(-1)) + , m_landingZones() + , m_i340(0) + , m_showNeighbours(false) +{ + m_i400 = -1; + m_visible = true; + m_statusChanged = false; + m_v416.x = 0.0f; + m_v416.y = 0.0f; + m_v416.z = 0.0f; + m_fromControlPoint = false; + m_orderPosesInitialised = false; + internalConstructorCall(topLeft, centre); +} + +// ELF 0x335B70 (C2; C1 0x335E70). // Creates a control-point area with an unset-height sentinel and one record per pathfinding map. AIStrategicArea::AIStrategicArea(const std::string& name, unsigned int controlPointId, float radius) : AIStrategicObject(radius, -666.0f) , m_list268() , m_centre() - , m_mapData(checkPointer(new MapData[IAIPathfinding::instance->getNumberOfMaps()])) + , m_orderPos(checkPointer(new MapData[IAIPathfinding::instance->getNumberOfMaps()])) , m_neighbours() , m_neighbouringObjects() , m_name(name) @@ -39,30 +136,39 @@ AIStrategicArea::AIStrategicArea(const std::string& name, unsigned int controlPo , m_controlPointId(controlPointId) , m_landingZones() , m_i340(0) - , m_b358(false) + , m_showNeighbours(false) { // The tail. Everything above this point lands before the three list members are constructed, so // it cannot be body code; everything here lands after them, so it cannot be an initialiser. m_i400 = -1; - m_b404 = true; + m_visible = true; m_statusChanged = false; - m_i416 = 0; - m_i420 = 0; - m_i424 = 0; + m_v416.x = 0.0f; + m_v416.y = 0.0f; + m_v416.z = 0.0f; m_fromControlPoint = true; // the phase selector - see the header m_orderPosesInitialised = false; } -// Eleven hundred bytes: the per-map array, four lists, the name, and whatever the twenty-eight -// unwritten slots own. Not reachable before shutdown - `AIStrategicObjectManager`'s destructor is -// the only caller and it already carries a guarded seam for its area delete loop. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] +// ELF 0x336F90 (D2; D1 0x337410, D0 0x337890; from AIStrategicObjectManager::reset/destructor): +// delete[] of the per-map data (+0x118), the two per-group flag arrays (+0x15C/+0x160) and the +// six per-group container arrays (+0x168..+0x17C, each element destroyed). The member lists, +// vectors and the name (+0x188 down to +0x10C) then go in reverse declaration order, then the base. AIStrategicArea::~AIStrategicArea() { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::~AIStrategicArea"); + delete[] m_orderPos; + delete[] m_flagsA; + delete[] m_flagsB; + delete[] m_listsA; + delete[] m_listsB; + delete[] m_mapsA; + delete[] m_mapsB; + delete[] m_mapsC; + delete[] m_mapsD; } // Returns type code zero. [UNRESOLVED] Its meaning is not established as a StrategicObjectType. +// ELF 0x340B70. int AIStrategicArea::getType() const { return 0; @@ -70,6 +176,7 @@ int AIStrategicArea::getType() const // - one load. The flag word an `.ai` script fills through // `aiStrategicArea.addObjectTypeFlag`. +// ELF 0x340B80. int AIStrategicArea::getObjectTypeFlags() const { return m_objectTypeFlags; @@ -77,12 +184,14 @@ int AIStrategicArea::getObjectTypeFlags() const // Returns twice the center-to-side-corner distance along X or Z. // Side indices are one-based and must be valid. +// ELF 0x33B540. float AIStrategicArea::getXExtent(int side) const { const float half = m_position[side - 1].x - m_centre.x; return half + half; } +// ELF 0x33B560. float AIStrategicArea::getZExtent(int side) const { const float half = m_position[side - 1].y - m_centre.y; @@ -92,6 +201,7 @@ float AIStrategicArea::getZExtent(int side) const // The query's own result and // its fourth (active) output are discarded; the local is seeded true only to be passed along. // Any assigned id answers true, whatever the engine wrote; the singleton is not null-checked. +// ELF 0x33A040. bool AIStrategicArea::getControlPointPosAndRadius(Vec3& position, float& radius) { bool active = true; @@ -103,6 +213,7 @@ bool AIStrategicArea::getControlPointPosAndRadius(Vec3& position, float& radius) } // Resolves control-point position, height, and ownership after world objects are available. +// ELF 0x337E20. void AIStrategicArea::postLoadInit() { if (m_fromControlPoint) @@ -169,8 +280,8 @@ void AIStrategicArea::postLoadInit() } } -// Initializes per-vehicle-group area arrays, with at least one element in each allocation. -// [FRONTIER] The destructor must release these arrays when its implementation is completed. +// ELF 0x336170. Initializes per-vehicle-group area arrays, with at least one element in each +// allocation (each new[] goes through checkPointer); the destructor releases them. void AIStrategicArea::internalConstructorCall(const Vec2& topLeft, const Vec2& centre) { // unused, and deliberately so - see the note above. @@ -198,8 +309,8 @@ void AIStrategicArea::internalConstructorCall(const Vec2& topLeft, const Vec2& c m_listsA = checkPointer(new std::list >[groups]); m_listsB = checkPointer(new std::list >[groups]); - m_mapsA = checkPointer(new std::map[groups]); - m_mapsB = checkPointer(new std::map[groups]); + m_mapsA = checkPointer(new std::map >[groups]); + m_mapsB = checkPointer(new std::map >[groups]); m_mapsC = checkPointer(new std::map[groups]); m_mapsD = checkPointer(new std::map[groups]); @@ -231,6 +342,7 @@ void AIStrategicArea::internalConstructorCall(const Vec2& topLeft, const Vec2& c } // Raises the stored area height to the terrain height when the terrain is higher. +// ELF 0x337D20. void AIStrategicArea::init() { const IAITerrain* const terrain = @@ -257,6 +369,7 @@ void AIStrategicArea::init() } // Resolves order positions to the navmesh and converts them to area-relative offsets once. +// ELF 0x336E80. void AIStrategicArea::initOrderPoses() { Vec3 areaPosition; @@ -271,7 +384,7 @@ void AIStrategicArea::initOrderPoses() for (int i = 0; i < pathfinding->getNumberOfMaps(); ++i) { - MapData& data = m_mapData[i]; + MapData& data = m_orderPos[i]; unsigned int polygon = 0; unsigned int island = 0; @@ -281,7 +394,7 @@ void AIStrategicArea::initOrderPoses() data.m_offset.y = data.m_offset.y - areaPosition.y; data.m_offset.z = data.m_offset.z - areaPosition.z; - data.m_island = island; + data.island = island; } m_orderPosesInitialised = true; @@ -289,6 +402,7 @@ void AIStrategicArea::initOrderPoses() // Returns the area position plus the selected map's delta; map -1 omits the delta. // The second parameter is unused; [UNRESOLVED] its original purpose is unknown. +// ELF 0x339830. Vec3 AIStrategicArea::getOrderPos(int map, int unused) const { (void)unused; @@ -300,7 +414,7 @@ Vec3 AIStrategicArea::getOrderPos(int map, int unused) const if (map != -1) { - const MapData& data = m_mapData[map]; + const MapData& data = m_orderPos[map]; position.x += data.m_offset.x; position.y += data.m_offset.y; position.z += data.m_offset.z; @@ -310,22 +424,69 @@ Vec3 AIStrategicArea::getOrderPos(int map, int unused) const } // Tests a StrategicObjectType bit position in the object flags. +// ELF 0x33A0B0. bool AIStrategicArea::hasObjectTypeFlag(StrategicObjectType type) const { return ((m_objectTypeFlags >> type) & 1) != 0; } -// Remaining virtual work keeps named stops. Live strategic ticks now reach the recovered update; -// later dirty/assignment/lifetime behavior remains separately bounded. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -void AIStrategicArea::updateTemperature(const Strategy*, int) +// ELF 0x33BD30. +bool AIStrategicArea::isLandingZoneUser(int equipment) { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::updateTemperature"); + return (m_i340 >> equipment) & 1; +} + +// ELF 0x33A0F0. Both temperature pairs of the side (+0xA0/+0xA8 + 4 * side, i.e. m_f164[side - 1] +// and m_f164[side + 1]) are scaled by the strategy's object modifiers for the area's status: one +// factor per object type flag the area has (types 0..20), then the status factor (Owned: Front +// when a hostile neighbour exists, else Safe; Hostile: Enemy; Neutral: Neutral), then the +// strategy's specific modifier for this object. Answers the scaled first temperature. +float AIStrategicArea::updateTemperature(const Strategy* strategy, int side) +{ + const float* const modifiers = strategy->getStrategicObjectsModifiers(getStatus(side)); + for (int type = 0; type <= 20; ++type) + { + if (hasObjectTypeFlag(static_cast(type))) + { + m_f164[side - 1] *= modifiers[type]; + m_f164[side + 1] *= modifiers[type]; + } + } + switch (getStatus(side)) + { + case StatusMap::Owned: + if (hasNeighbourWithStatus(StatusMap::Hostile, side)) + { + m_f164[side - 1] *= modifiers[Front]; + m_f164[side + 1] *= modifiers[Front]; + } + else + { + m_f164[side - 1] *= modifiers[Safe]; + m_f164[side + 1] *= modifiers[Safe]; + } + break; + case StatusMap::Hostile: + m_f164[side - 1] *= modifiers[Enemy]; + m_f164[side + 1] *= modifiers[Enemy]; + break; + case StatusMap::Neutral: + m_f164[side - 1] *= modifiers[NeutralType]; + m_f164[side + 1] *= modifiers[NeutralType]; + break; + default: + break; + } + m_f164[side - 1] *= strategy->getSpecificStrategicObjectModifier(m_index); + m_f164[side + 1] *= strategy->getSpecificStrategicObjectModifier(m_index); + AIStrategicObjectManager::getInstance(); // result unused in the image + return m_f164[side - 1]; } // Parameter types // are mangled; neither body materializes a return. Names of local aggregates are inferred. +// ELF 0x337FF0. void AIStrategicArea::update(int side, ISAI* sai, bool& changed) { IAIGame* const game = static_cast(CommonSingletonServer::m_iaiGame); @@ -398,13 +559,13 @@ void AIStrategicArea::update(int side, ISAI* sai, bool& changed) return; if (sai->isFriend(information->getSide())) { - if (!root || (information->getObjectTypeFlags() & 0x10u) == 0) + if (!root || !information->isOfType(ITAir)) ++friendlyUnits; friendly = static_cast(static_cast(security) * strength + friendly); } else if (sai->isEnemy(information->getSide())) { - if (!root || (information->getObjectTypeFlags() & 0x10u) == 0) + if (!root || !information->isOfType(ITAir)) ++enemyUnits; enemy = static_cast(static_cast(security) * strength + enemy); IPIPhysical* const physical = information->getPhysical(); @@ -540,12 +701,17 @@ void AIStrategicArea::update(int side, ISAI* sai, bool& changed) #endif } -int AIStrategicArea::getChangedAttackDefence(int) +// ELF 0x337FC0: 1 when the last update changed the status and the side does not own the area. +int AIStrategicArea::getChangedAttackDefence(int side) { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::getChangedAttackDefence"); + int changed = 0; + if (m_statusChanged && getStatus(side) != StatusMap::Owned) + changed = 1; + return changed; } // Full pair : fresh game/id after the flag callback. +// ELF 0x3399D0. float AIStrategicArea::getControlPointTakeOverCounter() { if (hasObjectTypeFlag(ControlPoint)) @@ -554,32 +720,74 @@ float AIStrategicArea::getControlPointTakeOverCounter() return 1.0f; } -bool AIStrategicArea::isEnemyTakingOverBase(int) +// ELF 0x338BF0. +bool AIStrategicArea::isEnemyTakingOverBase(int side) { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::isEnemyTakingOverBase"); + return m_enemyTakeover[side - 1]; } -int AIStrategicArea::calculateDefenseNeed(int) +// ELF 0x338C10 (slot 11 answers a float in st0). Only owned areas need defence: +// (2 - SCurve(need input)) * (enemy battle strength + temperature), times 1.5 with a hostile +// neighbour, else 1.25 with a neutral one. +float AIStrategicArea::calculateDefenseNeed(int side) { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::calculateDefenseNeed"); + if (getStatus(side) != StatusMap::Owned) + return 0.0f; + float need = (2.0f - SCurve::calculate(m_needCurveInput[side - 1])) + * (m_enemyBattleStrength[side - 1] + m_f164[side - 1]); + if (hasNeighbourWithStatus(StatusMap::Hostile, side)) + need = need * 1.5f; + else if (hasNeighbourWithStatus(StatusMap::Neutral, side)) + need = need * 1.25f; + return need; } -int AIStrategicArea::calculateAttackValue(int) +// ELF 0x338CE0 (float). A not-owned area next to an owned one is worth +// (1 + need input) * temperature, times 1.5 next to a neutral area or 1.25 otherwise (no +// factor next to a hostile one), scaled by 100 / distance of the closest squad to the area's +// first position when that lies in (1, 100000), else 0; minus the attack cost. +float AIStrategicArea::calculateAttackValue(int side) { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::calculateAttackValue"); + float value = 0.0f; + if (getStatus(side) != StatusMap::Owned && hasNeighbourWithStatus(StatusMap::Owned, side)) + { + value = 1.0f; + value = value + m_needCurveInput[side - 1]; + value = value * m_f164[side - 1]; + if (!hasNeighbourWithStatus(StatusMap::Hostile, side)) + value = (hasNeighbourWithStatus(StatusMap::Neutral, side) ? 1.5f : 1.25f) * value; + const float x = m_position[0].x; + Vec3 position; + position.y = static_cast(CommonSingletonServer::m_iaiTerrain)->getTerrainAltitude(x, m_position[0].y); + position.z = m_position[0].y; + position.x = x; + const float distance = SquadManager::m_instance->getDistanceToClosestSquad(position, side); + if (distance > 1.0f && 100000.0f > distance) + value = 1.0f / distance * 100.0f * value; + else + value = 0.0f; + } + value = value - calculateAttackCost(side); + return value; } -int AIStrategicArea::calculateAttackCost(int) +// ELF 0x338E60 (float): the enemy's second battle strength (-1 with fewer than two buckets) +// times (1.5 - 0.5 * need input) * (1 + friendly ratio). +float AIStrategicArea::calculateAttackCost(int side) { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::calculateAttackCost"); + const EnemyStatistics* const statistics = m_statistics[side - 1]; + const float strength = statistics->m_size > 1 ? statistics->m_strength[1] : -1.0f; + return strength * (1.5f - 0.5f * m_needCurveInput[side - 1]) * (1.0f + m_friendlyRatio[side - 1]); } -bool AIStrategicArea::isNeighbour(AIStrategicObject*) const +// ELF 0x339130. +bool AIStrategicArea::isNeighbour(AIStrategicObject* object) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::isNeighbour"); + return std::find(m_neighbours.begin(), m_neighbours.end(), object) != m_neighbours.end(); } // Native vector scan, captured end, no null/side guards; first matching status wins. +// ELF 0x339330. bool AIStrategicArea::hasNeighbourWithStatus(StatusMap::Status status, int side) const { const auto end = m_neighbours.end(); @@ -591,12 +799,15 @@ bool AIStrategicArea::hasNeighbourWithStatus(StatusMap::Status status, int side) return false; } -bool AIStrategicArea::isNeighbouringObject(AIStrategicObject*) const +// ELF 0x339370. +bool AIStrategicArea::isNeighbouringObject(AIStrategicObject* object) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::isNeighbouringObject"); + return std::find(m_neighbouringObjects.begin(), m_neighbouringObjects.end(), object) + != m_neighbouringObjects.end(); } // Applies the same scan to the second neighbor vector. +// ELF 0x3394C0. bool AIStrategicArea::hasNeighbouringObjectWithStatus(StatusMap::Status status, int side) const { const auto end = m_neighbouringObjects.end(); @@ -608,38 +819,318 @@ bool AIStrategicArea::hasNeighbouringObjectWithStatus(StatusMap::Status status, return false; } -bool AIStrategicArea::hasObjectTypeFlags(int) const +// ELF 0x33A0D0: all of the given flags. +bool AIStrategicArea::hasObjectTypeFlags(int flags) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::hasObjectTypeFlags"); + return (m_objectTypeFlags & flags) == flags; } -int AIStrategicArea::getTacticalStatus(int) const +// ELF 0x33A970: the int at +316 + 4 * side, i.e. m_i320 / m_i324 for sides 1 / 2. +int AIStrategicArea::getTacticalStatus(int side) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::getTacticalStatus"); + return side == 1 ? m_i320 : (side == 2 ? m_i324 : static_cast(m_controlPointId)); } +// ELF 0x339A30: the game reports the area's control point as active. The radius output is +// left uninitialised, as shipped. bool AIStrategicArea::isAreaTakeable() { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::isAreaTakeable"); + bool active = false; + const unsigned int cp = m_controlPointId; + if (cp != static_cast(-1)) + { + Vec3 position; + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; + float radius; + static_cast(CommonSingletonServer::m_iaiGame)->getControlPointInfo(cp, position, radius, active); + } + return active; +} + +// ELF 0x33A380: answers whether the assigned squad strength covers the need (+0xE0 + 4 side vs +// +0xD8 + 4 side). Otherwise the closest available squads are ordered to the area (y = m_f148) +// like collectAdditionalSquadResources does, while the assigned strength stays at or below the +// need (`jle` back to the query), so an exact match still asks for one more squad. +bool AIStrategicArea::collectSquadResources(int side, ISAI* sai) +{ + if (m_assignedSquadStrength[side - 1] >= m_resourceNeed[side - 1]) + return true; + int strength = 0; + Vec3 position; + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; + vec2ToVec3XZ(getPosition(side), position); + SquadManager* const squads = SquadManager::m_instance; + position.y = m_f148; + validateDistances(side); + if (m_assignedSquadStrength[side - 1] > m_resourceNeed[side - 1]) + return true; + do + { + SquadCoordinator* const squad = + squads->getClosestAvailableSquad(this, position, side, m_attack[side - 1], strength); + if (!squad) + break; + const StatusMap::Status status = getStatus(side); + bool defend; + if (status != StatusMap::Owned) + defend = m_enemyTakeover[side - 1] && status == StatusMap::Neutral; + else + defend = true; + if (defend) + sai->getCommanderInterface()->giveDefendOrder(position, squad); + else + sai->getCommanderInterface()->giveAttackOrder(position, squad); + m_assignedSquadStrength[side - 1] += strength; + } while (m_assignedSquadStrength[side - 1] <= m_resourceNeed[side - 1]); + return m_assignedSquadStrength[side - 1] >= m_resourceNeed[side - 1]; +} + +// ELF 0x33A530: up to `amount` of the closest available squads get an attack order to the +// area's position (y = m_f148), or a defend order when the side owns it or it is neutral and +// being taken over; their strength adds to m_assignedSquadStrength. Answers the squad count. +int AIStrategicArea::collectAdditionalSquadResources(int amount, int side, ISAI* sai) +{ + int count = 0; + int strength = 0; + Vec3 position; + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; + vec2ToVec3XZ(getPosition(side), position); + SquadManager* const squads = SquadManager::m_instance; + position.y = m_f148; + validateDistances(side); + for (; count < amount; ++count) + { + SquadCoordinator* const squad = + squads->getClosestAvailableSquad(this, position, side, m_attack[side - 1], strength); + if (!squad) + break; + const StatusMap::Status status = getStatus(side); + bool defend; + if (status != StatusMap::Owned) + defend = m_enemyTakeover[side - 1] && status == StatusMap::Neutral; + else + defend = true; + if (defend) + sai->getCommanderInterface()->giveDefendOrder(position, squad); + else + sai->getCommanderInterface()->giveAttackOrder(position, squad); + m_assignedSquadStrength[side - 1] += strength; + } + return count; +} + +// ELF 0x33BD50. +void AIStrategicArea::validateDistances(int side) +{ + if (!m_distancesDirty[side - 1]) + return; + m_distances[side - 1].clear(); + const int groups = static_cast(CommonSingletonServer::m_iaiSettings)->getNumberOfVehicleGroups(); + if (!groups) + { + validateDistances(side, 0); + insertUnitDistances(side, 0); + return; + } + for (int group = 0; group < groups; ++group) + { + validateDistances(side, group); + insertUnitDistances(side, group); + } +} + +// ELF 0x33BE30: a dirty group (m_flagsA/B[group]) is rebuilt: its distance list and both maps +// are cleared, then getDistances refills them for the group's bit. +void AIStrategicArea::validateDistances(int side, int group) +{ + bool* const flags = side == 1 ? m_flagsA : m_flagsB; + if (!flags[group]) + return; + flags[group] = false; + std::list >* const lists = side == 1 ? m_listsA : m_listsB; + std::map >* const routes = side == 1 ? m_mapsA : m_mapsB; + std::map* const costs = side == 1 ? m_mapsC : m_mapsD; + lists[group].clear(); + routes[group].clear(); + costs[group].clear(); + getDistances(side, lists[group], routes[group], costs[group], 1 << group); } -int AIStrategicArea::collectSquadResources(int, ISAI*) +// ELF 0x33AAC0: a breadth-ordered relaxation over the area graph from this area. Entries +// {object, predecessor, cost} are appended to a FIFO (std::list<(anonymous)::ObjectSearchInfo>, +// node 0x14); the front entry is expanded when it improves the object's best cost +// (`fucompi; jbe` = skip unless costs[object] > cost or no cost yet) and the object allows one of +// the groups in groupMask. Edge cost: the 2-D distance between the side's positions (slot 3), +// times 5.0f into a hostile area and 1.1f into a neutral one (rodata 0x49CDAC / 0x49DCA8). +// The object's route is its predecessor's route with the object pushed to the front. Finally +// every (cost, object) of costs is appended to distances, which is sorted. +void AIStrategicArea::getDistances(int side, std::list >& distances, + std::map >& routes, + std::map& costs, int groupMask) { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::collectSquadResources"); + std::list open; + std::list route; + route.clear(); // 0x33AB53, on the fresh list + if (!allowsSomeVehicleGroups(groupMask)) + return; + open.push_back(ObjectSearchInfo(this, this, 0.0f)); + routes.insert(std::make_pair(static_cast(this), route)); + std::list::iterator it = open.begin(); + while (!open.empty()) + { + std::map::iterator found = costs.find(it->object); + if ((found == costs.end() || found->second > it->cost) + && it->object->allowsSomeVehicleGroups(groupMask)) + { + // A copy of the area's neighbour vector (+0x11C), then one entry per neighbour. + std::vector neighbours = + static_cast(it->object)->m_neighbours; + for (std::vector::iterator n = neighbours.begin(); + n != neighbours.end(); ++n) + { + const Vec2& from = it->object->getPosition(side); + const Vec2& to = (*n)->getPosition(side); + Vec2 delta; + delta.x = to.x - from.x; + delta.y = to.y - from.y; + float distance = std::sqrt(delta.x * delta.x + delta.y * delta.y); + const StatusMap::Status status = (*n)->getStatus(side); + if (status == StatusMap::Neutral) + distance *= 1.1f; + else if (status == StatusMap::Hostile) + distance *= 5.0f; + open.push_back(ObjectSearchInfo(*n, it->object, it->cost + distance)); + } + if (found == costs.end()) + costs.insert(std::make_pair(it->object, it->cost)); + else + found->second = it->cost; + std::map >::iterator previous = + routes.find(it->previous); + std::map >::iterator own = + routes.find(it->object); + if (own == routes.end()) + { + routes.insert(std::make_pair(it->object, previous->second)); + own = routes.find(it->object); + } + else + { + own->second = previous->second; + } + own->second.push_front(it->object); + } + it = open.erase(it); + } + for (std::map::iterator c = costs.begin(); c != costs.end(); ++c) + distances.push_back(std::make_pair(c->second, c->first)); + distances.sort(); } -int AIStrategicArea::collectAdditionalSquadResources(int, int, ISAI*) +// ELF 0x33BF90: merges the group's sorted distance list into the side's AreaDistanceInfo list +// (sorted by distance). An entry of equal distance gains the group's bit (`orl %eax,0x8(%edx)`); +// otherwise a new {1 << group, area, distance} is inserted before the first larger entry, and +// whatever is left is appended. +void AIStrategicArea::insertUnitDistances(int side, int group) { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::collectAdditionalSquadResources"); + AreaDistanceInfo info; + std::list& merged = m_distances[side - 1]; + std::list >& distances = (side == 1 ? m_listsA : m_listsB)[group]; + std::list::iterator at = merged.begin(); + std::list >::iterator it = distances.begin(); + for (; it != distances.end(); ++it) + { + // [CHOSEN] The image compares before the end test, reading the libstdc++ list header's + // payload once at the end; the end test runs first here (same result, no sentinel read). + while (at != merged.end() && it->first > at->m_distance) + ++at; + if (at == merged.end()) + break; + if (at->m_distance == it->first) + { + at->m_vehicleGroups |= 1 << group; + } + else + { + info.m_vehicleGroups = 1 << group; + info.m_area = static_cast(it->second); + info.m_distance = it->first; + merged.insert(at, info); + } + } + for (; it != distances.end(); ++it) + { + info.m_vehicleGroups = 1 << group; + info.m_area = static_cast(it->second); + info.m_distance = it->first; + merged.push_back(info); + } } -int AIStrategicArea::releaseSurplus(int) +// ELF 0x33A6A0: with more strength assigned than needed, one assigned unit (+0x38 + 12 side, +// m_set68) is released. Units whose bot is gone are erased on the way. The pick prefers units +// not present in the area and, among those, the lowest strategic strength for the area's role +// (getStrategicStrengths()[attack ? 0 : 1], truncated to int). It is released through the side's +// SAI (slot 33) only if (assigned - strength) / need (integer division, `idivl` - a zero need +// traps as in the image) is still at least 1.1f; the assigned strength drops by that strength. +// The pick iterator starts value-initialised (null, not end()), as in the image: with no +// candidate the 1e9 start strength makes the ratio negative, so nothing is released. +bool AIStrategicArea::releaseSurplus(int side) { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::releaseSurplus"); + std::set::iterator best = std::set::iterator(); + if (m_resourceNeed[side - 1] > m_assignedSquadStrength[side - 1]) + return false; + bool bestIsPresent = true; + int bestStrength = 1000000000; + std::set& units = m_set68[side - 1]; + for (std::set::iterator it = units.begin(); it != units.end();) + { + Bot* const bot = IBotManager::instance->getBotFromId(*it); + if (!bot) + { + units.erase(it++); + continue; + } + Information* const information = informationManager->getInformation(bot->getCurrentEquipment()); + IPIUnit* const unit = information ? information->getUnit() : 0; + if (unit) + { + const bool present = isPresentUnit(*it, side); + if (!present || bestIsPresent) + { + const float* const strengths = unit->getStrategicStrengths(); + const int role = !m_attack[side - 1]; + if (static_cast(bestStrength) > strengths[role] || (!present && bestIsPresent)) + { + bestStrength = static_cast(strengths[role]); + bestIsPresent = present; + best = it; + } + } + } + ++it; + } + if (best == units.end()) + return true; + const int remaining = m_assignedSquadStrength[side - 1] - bestStrength; + const int ratio = remaining / m_resourceNeed[side - 1]; + if (static_cast(ratio) >= 1.1f) + { + m_assignedSquadStrength[side - 1] = remaining; + IAIMain::m_instance->getSAI(side)->releaseUnitFromObject(m_index, best, side); + } + return true; } // Both delegations stay virtual; // MSVC groups the Vec2/Vec3 overload slots in the opposite order to the ELF. +// ELF 0x33A990. float AIStrategicArea::gravity(const Vec3& position, int side) { Vec2 flat; @@ -651,6 +1142,7 @@ float AIStrategicArea::gravity(const Vec3& position, int side) // The position is read directly // using side-1. x87 keeps the arithmetic wide until the float call argument. +// ELF 0x33A9F0. float AIStrategicArea::gravity(const Vec2& position, int side) { const double dx = static_cast(position.x) - m_position[side - 1].x; @@ -666,23 +1158,502 @@ float AIStrategicArea::gravity(const Vec2& position, int side) return gravity(static_cast(distance), side); } -bool AIStrategicArea::retainBot(int, int, ISAI*) +// ELF 0x33EFA0: true when the bot's current equipment is a known mobile unit; the +// present-set find and the local object list are unused in the image. +bool AIStrategicArea::retainBot(int side, int unit, ISAI*) +{ + (void)m_presentUnits[side - 1].find(unit); + Bot* const bot = IBotManager::instance->getBotFromId(unit); + Information* const information = informationManager->getInformation(bot->getCurrentEquipment()); + if (!information || !information->getMobile() || !information->getUnit()) + return false; + std::list objects; + return true; +} + +// ELF 0x33F0B0: the side's distance flag (+0x157 + side) and every vehicle-group flag of that +// side (+0x158 + 4 * side: m_flagsA for side 1, m_flagsB for side 2) are set. With zero vehicle +// groups the first flag is still written. +void AIStrategicArea::setAsDirty(int side) +{ + m_distancesDirty[side - 1] = true; + const int groups = static_cast(CommonSingletonServer::m_iaiSettings)->getNumberOfVehicleGroups(); + bool* const flags = side == 1 ? m_flagsA : m_flagsB; + if (!groups) + { + flags[0] = true; + return; + } + for (int i = 0; i < groups; ++i) + flags[i] = true; +} + +// ELF 0x33F180. +bool AIStrategicArea::isInside(const Vec2& point) const +{ + return insideCentreBox(point, m_centre, m_position[0]); +} + +// ELF 0x3396E0: `lea eax, [this + 0x84]`. +const Vec2& AIStrategicArea::getCenterPosition() const +{ + return m_position[0]; +} + +// ELF 0x33F130. +bool AIStrategicArea::isInside(const Vec3& point) const +{ + Vec2 flat; + flat.x = 0.0f; + flat.y = 0.0f; + vec3ToVec2XZ(point, flat); + return isInside(flat); +} + +// ELF 0x33EF80. +Vec3 AIStrategicArea::getBotWaypoint(Vec3, Vec3 to, const std::vector&, int) +{ + return to; +} + +// ELF 0x339AB0: a position for a unit ordered to this area's control point. An active point +// (IAIGame +0x28) keeps `from` when it is within 0.8 radius and valid on the map (IAIPathfinding +// +0x30 with the area's island for the map); an inactive one uses twice the area's centre-to- +// position extent instead. Otherwise up to twenty-one randomized candidates around the point's +// centre (height m_f148; 0.8/radius resp. 1.0/twice-extent) are tried, then the object's order +// position (slot 5) is the answer. +void AIStrategicArea::getControlpointPos(AIStrategicObject* object, int side, int map, int unit, + const Vec3& from, Vec3& position) +{ + IAIPathfinding* const pathfinding = IAIPathfinding::instance; + IAIGame* const game = static_cast(CommonSingletonServer::m_iaiGame); + bool active = true; + int tries = 0; + float radius = 1.0f; + Vec3 centre; + centre.x = 0.0f; + centre.y = 0.0f; + centre.z = 0.0f; + game->getControlPointInfo(m_controlPointId, centre, radius, active); + float scale; + float spread; + if (active) + { + const float dx = centre.x - from.x; + const float dy = centre.y - from.y; + const float dz = centre.z - from.z; + const float distance = std::sqrt(dx * dx + dy * dy + dz * dz); + if (0.8f * radius > distance + && pathfinding->isValidPosition(map, unit, from, m_orderPos[map].island, true)) + { + position = from; + return; + } + scale = 0.8f; + spread = radius; + } + else + { + const Vec2 corner = m_centre; + const Vec2& anchor = getPosition(side); + const float hx = anchor.x - corner.x; + const float hy = anchor.y - corner.y; + const float extent = std::sqrt(hx * hx + hy * hy); + const float twice = extent + extent; + const float dx = centre.x - from.x; + const float dy = centre.y - from.y; + const float dz = centre.z - from.z; + const float distance = std::sqrt(dx * dx + dy * dy + dz * dz); + if (twice > distance + && pathfinding->isValidPosition(map, unit, from, m_orderPos[map].island, true)) + { + position = from; + return; + } + scale = 1.0f; + spread = twice; + } + position.x = centre.x; + position.y = m_f148; + position.z = centre.z; + object->randomizeControlpointPos(scale, spread, position); + for (; tries <= 19; ++tries) + { + if (pathfinding->isValidPosition(map, unit, position, m_orderPos[map].island, true)) + return; + position.x = centre.x; + position.y = m_f148; + position.z = centre.z; + object->randomizeControlpointPos(scale, spread, position); + } + // (sret, object, map, side): `movl 0x14(%ebp)` (map) before `0x10(%ebp)` (side) at 0x339CC8. + position = object->getOrderPos(map, side); +} + +// ELF 0x33C340: the unit's current equipment information decides the arm - object type bit +// 0x10 (`testb $0x10,0x4(%eax)`, the air bit the temperature samples also test) orders it as an +// air bot. The image does not check the information for null. eax is whatever the arm leaves. +void AIStrategicArea::orderBot(int side, const std::list& objects, int unit, ISAI* sai) +{ + Bot* const bot = IBotManager::instance->getBotFromId(unit); + Information* const information = informationManager->getInformation(bot->getCurrentEquipment()); + if (information->isOfType(ITAir)) + { + orderAirBot(side, objects, unit, sai); + return; + } + orderNormalBot(side, objects, unit, sai); +} + +// ELF 0x33C430: an air path 75 above the terrain (IAITerrain::getHeight, +0x08) at this area's +// position (no objects), at the one object's, or at every object after the first. The cruise +// altitude is min(m_size[side], 4.0f for object type bit 0x20 else 40.0f) (`fcmovnbe`); the +// waypoint is WPAltitudeMoveTo(altitude, 120.0f, 50.0f, 2, path) through checkPointer (0x33C650), +// handed to the bot (+0x44, also when the allocation failed). The image does not check the +// information for null. +void AIStrategicArea::orderAirBot(int side, const std::list& objects, int unit, ISAI*) +{ + std::list path; + float altitude = 1.0f; + Bot* const bot = IBotManager::instance->getBotFromId(unit); + Information* const information = informationManager->getInformation(bot->getCurrentEquipment()); + const IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + const float clearance = information->isOfType(ITHelicopter) ? 4.0f : 40.0f; + const std::size_t count = objects.size(); + if (count == 0 || count == 1) + { + const Vec2& anchor = count == 0 ? getPosition(side) : objects.front()->getPosition(side); + const float x = anchor.x; + Vec3 point; + point.y = terrain->getHeight(anchor.x, anchor.y) + 75.0f; + point.x = x; + point.z = anchor.y; + path.push_back(point); + altitude = m_size[side] > clearance ? clearance : m_size[side]; + } + else + { + std::list::const_iterator it = objects.begin(); + for (++it; it != objects.end(); ++it) + { + const Vec2& anchor = (*it)->getPosition(side); + const float x = anchor.x; + Vec3 point; + point.y = terrain->getHeight(anchor.x, anchor.y) + 75.0f; + point.x = x; + point.z = anchor.y; + path.push_back(point); + altitude = m_size[side] > clearance ? clearance : m_size[side]; + } + } + bot->setWaypoints(checkPointer(new WPAltitudeMoveTo(altitude, 120.0f, 50.0f, 2, path))); +} + +// ELF 0x33A2F0 (caller SquadMember::moveToGoalPos 0x1B4240): the side's route map +// (`0x16c(%edi,%esi,4)`, i.e. m_mapsA / m_mapsB for side 1 / 2, first group element) is searched +// for `from`; when found the route is copied out (list operator=) and the answer is true. +bool AIStrategicArea::getRouteList(int side, AIStrategicArea* from, std::list& route) +{ + bool found = false; + std::map >& routes = (side == 1 ? m_mapsA : m_mapsB)[0]; + std::map >::iterator it = routes.find(from); + if (it != routes.end()) + { + found = true; + route = it->second; + } + return found; +} + +namespace { + +float squaredDistance(const Vec3& a, const Vec3& b) +{ + const float dx = a.x - b.x; + const float dy = a.y - b.y; + const float dz = a.z - b.z; + return dx * dx + dy * dy + dz * dz; +} + +// (a - origin) . (b - origin): positive when a lies on the side of origin facing b. +float dotFrom(const Vec3& origin, const Vec3& a, const Vec3& b) +{ + return (a.x - origin.x) * (b.x - origin.x) + (a.y - origin.y) * (b.y - origin.y) + + (a.z - origin.z) * (b.z - origin.z); +} + +// The inline AIRandom draw of orderNormalBot (0x33D390 / 0x33E764): low 0.0f, high the waypoint +// count (`fildll` of the zero-extended size, stored to float), (high - low) * (draw * 2^-32) + low +// stored to float, then `cvttss2si`. +std::size_t randomWaypointIndex(std::size_t count) +{ + const float low = 0.0f; + const float high = static_cast(static_cast(count)); + const double draw = static_cast(AIRandom::m_instance->next()) * static_cast(2.32830644e-10f); + return static_cast(static_cast(static_cast((high - low) * draw + low))); +} + +// [CHOSEN] helper for a sequence orderNormalBot repeats in its three arms (0x33CB6E, 0x33E205, +// 0x33D6B2): randomizePos(side, 0.8f) around `object`, up to twenty candidates checked against +// the ordering area's island for the map (IAIPathfinding +0x30, always the ordering area's +// +0x118 data), then the object's order position (slot 5, (map, side)). +void findOrderPosition(const AIStrategicArea* area, AIStrategicObject* object, int side, int map, + int equipment, Vec3& position) { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::retainBot"); + IAIPathfinding* const pathfinding = IAIPathfinding::instance; + object->randomizePos(side, 0.8f, position); + for (int tries = 0; tries <= 19; ++tries) + { + if (pathfinding->isValidPosition(map, equipment, position, area->m_orderPos[map].island, true)) + return; + object->randomizePos(side, 0.8f, position); + } + position = object->getOrderPos(map, side); +} + +// [CHOSEN] helper for the `hasSameAssignedAreas` arm (0x33DC66 / 0x33EB83): the bot keeps its +// current waypoint (through getBotWaypoint) when it still leads towards `goal` and is closer to it +// than the bot; it is then stored again (Bot +0x20C) and the stored one (+0x210) becomes a goal +// with area -1. +bool keepCurrentWaypoint(AIStrategicArea* area, Bot* bot, Information* information, int side, int map, + const Vec3& botPosition, const Vec3& goal, float distance, + const std::vector& waypoints, WPMoveTo::GoalList& goals) +{ + const Vec3 current = static_cast(bot)->getCurrentWaypoint(); + const Vec3 from = information->getPosition(); + const Vec3 next = area->getBotWaypoint(from, current, waypoints, side); + if (dotFrom(botPosition, next, goal) > 0.0f && squaredDistance(next, goal) < distance) + { + static_cast(bot)->setCurrentWaypoint(next, map); + const Vec3 stored = static_cast(bot)->getCurrentWaypoint(); + goals.push_back(std::make_pair(stored, -1)); + return true; + } + return false; } -void AIStrategicArea::setAsDirty(int) +bool isOrderableControlPoint(const AIStrategicArea* area, int side) { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::setAsDirty"); + return area->hasObjectTypeFlag(AIStrategicObject::ControlPoint) + && area->m_controlPointId != 0xFFFFFFFFu && area->getStatus(side) != StatusMap::Owned; } -int AIStrategicArea::orderBot(int, const std::list&, int, ISAI*) +} // namespace + +// ELF 0x33C940 (0x33C940..0x33EF80). A ground unit's goal list (WPMoveTo goals, radius 60): +// * no objects: this area's control point (getControlpointPos, goal radius 0) when the area is a +// control point (+0x13C set, side status not Owned); else the bot's own position when it is +// inside the area and valid on the map, else a randomized order position (findOrderPosition); +// radius m_size[side] / 4 + the bot's diameter (IPIPhysical +0x2C, `fadd %st,%st`). +// * one object: a route waypoint between the bot's current strategic position (ISAI +0xB4) and +// the object first (AIStrategicObjectManager::getWaypoints; Bot +0x200..+0x214 track the +// assigned pair): the kept current waypoint, or one of three random picks that lies towards +// this area's position and closer to it than the bot, with a valid polygon. Then the object's +// (or this control point's) position with this area's index. +// * several objects: the same per consecutive pair (only the first pair updates the bot's +// assigned areas; only the first pick is direction-tested), each object's position with its own +// index; the radius is the last object's. +// Bot +0x200..+0x214 are declared on BotMain only (the established static_cast form). +// The waypoint list replaces the bot's unless SquadMember::isSameWaypointList says it is the same +// (then it is deleted). The image does not check the information or the squad member for null. +// ELF 0x33C940. +void AIStrategicArea::orderNormalBot(int side, const std::list& objects, int unit, ISAI* sai) { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::orderBot"); + WPMoveTo::GoalList goals; + float radius = 1.0f; + Vec2 botPosition2; + botPosition2.x = 0.0f; + botPosition2.y = 0.0f; + Vec3 controlPointPosition; + controlPointPosition.x = 0.0f; + controlPointPosition.y = 0.0f; + controlPointPosition.z = 0.0f; + Vec3 position = controlPointPosition; + IAIPathfinding* const pathfinding = IAIPathfinding::instance; + Bot* const bot = IBotManager::instance->getBotFromId(unit); + Information* const information = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* const mobile = information->getMobile(); + const float radiusPhysical = information->getPhysical()->getRadius(); + const float diameter = radiusPhysical + radiusPhysical; + const int map = mobile->getVehicleNumber(); + const int equipment = information->getUnit()->getEquipmentType(); + const Vec3& botPosition = information->getPosition(); + vec3ToVec2XZ(botPosition, botPosition2); + WPMoveTo* waypoint = 0; + + if (objects.empty()) + { + isLandingZoneUser(equipment); // 0x33CAB8: the answer is unused + if (isOrderableControlPoint(this, side)) + { + getControlpointPos(this, side, map, equipment, botPosition, controlPointPosition); + goals.push_back(std::make_pair(controlPointPosition, m_index)); + waypoint = checkPointer(new WPMoveTo(0.0f, 60.0f, 2, goals)); + } + else + { + bool found = false; + if (isInside(botPosition2) + && pathfinding->isValidPosition(map, equipment, information->getPosition(), + m_orderPos[map].island, true)) + { + position = information->getPosition(); + found = true; + } + if (!found) + findOrderPosition(this, this, side, map, equipment, position); + goals.push_back(std::make_pair(position, m_index)); + waypoint = checkPointer(new WPMoveTo(m_size[side] * 0.25f + diameter, 60.0f, 2, goals)); + } + } + else if (objects.size() == 1) + { + AIStrategicObject* const object = objects.front(); + if (object->getType() == 0) + static_cast(object)->isLandingZoneUser(equipment); // unused + AIStrategicObjectManager* const manager = AIStrategicObjectManager::getInstance(); + const int current = sai->getBotCurrentPos(unit); + const int target = object->getIndex(); + if (current != -1 && current != target) + { + // The goal of the route is this area's position (slot 3 on `this`, height m_f148). + Vec3 goal; + goal.x = 0.0f; + goal.y = 0.0f; + goal.z = 0.0f; + vec2ToVec3XZ(getPosition(side), goal); + goal.y = m_f148; + static_cast(bot)->setNewAssignedAreas(current, target); + const std::vector& waypoints = manager->getWaypoints(map, current, target); + const float distance = squaredDistance(goal, botPosition); + if (static_cast(bot)->hasSameAssignedAreas(map)) + { + keepCurrentWaypoint(this, bot, information, side, map, botPosition, goal, distance, + waypoints, goals); + } + else + { + bool added = false; + if (!waypoints.empty()) + { + for (int tries = 0;;) + { + const SAWayPoint* const candidate = waypoints[randomWaypointIndex(waypoints.size())]; + if (dotFrom(botPosition, candidate->getPosition(), goal) > 0.0f + && squaredDistance(candidate->getPosition(), goal) < distance + && candidate->getPolygon() != 0xFFFFFFFFu) + { + goals.push_back(std::make_pair(candidate->getPosition(), -1)); + static_cast(bot)->setCurrentWaypoint(candidate->getPosition(), map); + added = true; + break; + } + if (++tries > 2) + break; + } + } + if (!added) + static_cast(bot)->resetAssignedAreas(); + } + static_cast(bot)->copyAssignedAreas(); + } + if (object == this && isOrderableControlPoint(this, side)) + { + getControlpointPos(this, side, map, equipment, botPosition, controlPointPosition); + goals.push_back(std::make_pair(controlPointPosition, m_index)); + waypoint = checkPointer(new WPMoveTo(0.0f, 60.0f, 2, goals)); + } + else + { + findOrderPosition(this, object, side, map, equipment, position); + goals.push_back(std::make_pair(position, m_index)); + waypoint = checkPointer(new WPMoveTo(objects.front()->m_size[side] * 0.25f + diameter, + 60.0f, 2, goals)); + } + } + else + { + int previous = sai->getBotCurrentPos(unit); + bool first = true; + bool assigned = false; + AIStrategicObjectManager* const manager = AIStrategicObjectManager::getInstance(); + for (std::list::const_iterator it = objects.begin(); it != objects.end(); ++it) + { + AIStrategicObject* const object = *it; + const int target = object->getIndex(); + if (previous != -1 && previous != target) + { + Vec3 goal; + goal.x = 0.0f; + goal.y = 0.0f; + goal.z = 0.0f; + vec2ToVec3XZ(object->getPosition(side), goal); + goal.y = object->m_f148; + const std::vector& waypoints = manager->getWaypoints(map, previous, target); + bool added = false; + const float distance = squaredDistance(goal, botPosition); + if (!assigned) + { + static_cast(bot)->setNewAssignedAreas(previous, target); + if (static_cast(bot)->hasSameAssignedAreas(map)) + added = keepCurrentWaypoint(this, bot, information, side, map, botPosition, goal, + distance, waypoints, goals); + static_cast(bot)->copyAssignedAreas(); + } + if (waypoints.empty()) + static_cast(bot)->resetAssignedAreas(); // 0x33DBEB, whatever `assigned` is + if (!waypoints.empty() && !added) + { + for (int tries = 0;;) + { + const SAWayPoint* const candidate = waypoints[randomWaypointIndex(waypoints.size())]; + if ((!first || dotFrom(botPosition, candidate->getPosition(), goal) > 0.0f) + && candidate->getPolygon() != 0xFFFFFFFFu + && squaredDistance(candidate->getPosition(), goal) < distance) + { + goals.push_back(std::make_pair(candidate->getPosition(), -1)); + if (!assigned) + static_cast(bot)->setCurrentWaypoint(candidate->getPosition(), map); + added = true; + break; + } + if (++tries > 2) + break; + } + if (!assigned && !added) + static_cast(bot)->resetAssignedAreas(); + } + assigned = true; + } + first = false; + if (object == this && isOrderableControlPoint(this, side)) + { + getControlpointPos(this, side, map, equipment, botPosition, controlPointPosition); + goals.push_back(std::make_pair(controlPointPosition, m_index)); + radius = 0.0f; + } + else + { + findOrderPosition(this, object, side, map, equipment, position); + goals.push_back(std::make_pair(position, object->getIndex())); + radius = object->m_size[side] * 0.25f + diameter; + } + previous = target; + } + waypoint = checkPointer(new WPMoveTo(radius, 60.0f, 2, goals)); + } + + // 0x33CDA0: the bot's list (+0x40) is read before its squad member (+0x140). + WaypointList* const currentList = bot->getWaypoints(); + if (!bot->getSquadMember()->isSameWaypointList(currentList, waypoint)) + bot->setWaypoints(waypoint); + else + delete waypoint; // slot 1 when non-null } // The size uses side, unlike the // position's side-1 index above. Unordered distance takes the division arm. +// ELF 0x33AA80. float AIStrategicArea::gravity(float distance, int side) { if (distance <= 1.0f) @@ -691,6 +1662,305 @@ float AIStrategicArea::gravity(float distance, int side) return static_cast(m_size[side] / (wideDistance * wideDistance)); } +// ELF 0x339890 (added by ai-bot). The flag test is vtable +0x4C with 0x10 (ControlPoint). +bool AIStrategicArea::isOrderPosOutsideCpRadius(int map, int side) +{ + bool outside = false; + if (hasObjectTypeFlag(ControlPoint)) + { + const Vec3 order = getOrderPos(map, side); + float radius = 0.0f; + Vec3 centre; + centre.x = 0.0f; + centre.y = 0.0f; + centre.z = 0.0f; + bool active; + static_cast(CommonSingletonServer::m_iaiGame) + ->getControlPointInfo(m_controlPointId, centre, radius, active); + const float dx = order.x - centre.x; + const float dy = order.y - centre.y; + const float dz = order.z - centre.z; + if (std::sqrt(dx * dx + dy * dy + dz * dz) > radius) + outside = true; + } + return outside; +} + +// ELF 0x338FF0 (added by ai-bot). The records are read as two Vec3 (+0 / +0xC of the node value). +bool AIStrategicArea::getClosestFlankingPositions(Vec3 position, Vec3& first, Vec3& second) +{ + bool found = false; + float best = 3.40282347e+38f; + for (std::list >::const_iterator it = m_flankPositions.begin(); + it != m_flankPositions.end(); ++it) + { + const Vec3 a = it->first; + const Vec3 b = it->second; + const float dx = a.x - position.x; + const float dy = a.y - position.y; + const float dz = a.z - position.z; + const float d = dx * dx + dy * dy + dz * dz; + if (d < best) + { + best = d; + first = a; + second = b; + found = true; + } + } + return found; +} + +// ELF 0x338EC0. +void AIStrategicArea::addFlankPosition(Vec3 first, Vec3 second) +{ + m_flankPositions.push_back(std::pair(first, second)); +} + +// ELF 0x338F50: a copy of the flanking pairs. +std::list > AIStrategicArea::getFlankPositions() +{ + return m_flankPositions; +} + +// ELF 0x3391A0: appended unless already present. +void AIStrategicArea::addNeighbour(AIStrategicObject* object) +{ + for (int i = 0; i < static_cast(m_neighbours.size()); ++i) + { + if (m_neighbours[i] == object) + return; + } + m_neighbours.push_back(object); +} + +// ELF 0x339230. Shipped defect, preserved: the shift starts at the match, so it overwrites the +// element before the match (index -1 when the match is first) and keeps the match itself; the +// vector then shrinks by one whether or not the object was found. +void AIStrategicArea::removeNeighbour(AIStrategicObject* object) +{ + const int size = static_cast(m_neighbours.size()); + for (int i = 0; i < size; ++i) + { + if (m_neighbours[i] == object) + { + for (int j = i; j < size; ++j) + m_neighbours[j - 1] = m_neighbours[j]; + break; + } + } + m_neighbours.resize(size - 1); +} + +// ELF 0x3393E0: grown by one through resize, unless already present. +void AIStrategicArea::addNeighbouringObject(AIStrategicObject* object) +{ + const int size = static_cast(m_neighbouringObjects.size()); + for (int i = 0; i < size; ++i) + { + if (m_neighbouringObjects[i] == object) + return; + } + m_neighbouringObjects.resize(size + 1); + m_neighbouringObjects[size] = object; +} + +// ELF 0x339500: the neighbours, the neighbouring objects and the attached landing zones. +void AIStrategicArea::removeAllNeighbours() +{ + m_neighbours.resize(0); + m_neighbouringObjects.resize(0); + m_landingZones.resize(0); +} + +// ELF 0x339680: both sides' positions. +void AIStrategicArea::setPosition(const Vec2& position) +{ + m_position[0] = position; + m_position[1] = position; +} + +// ELF 0x3396B0: the same stores as setPosition. +void AIStrategicArea::setCenterPosition(const Vec2& position) +{ + m_position[0] = position; + m_position[1] = position; +} + +// ELF 0x3396F0. +void AIStrategicArea::setTopLeftCorner(const Vec2& corner) +{ + m_centre = corner; +} + +// ELF 0x339710. Before initOrderPoses the position is stored absolute; afterwards the map is +// queried with the stored (old) offset, as initOrderPoses does, and the new position is stored +// relative to the area position together with the island the query answered. Always true. +bool AIStrategicArea::setOrderPos(int map, const Vec3& position) +{ + if (!m_orderPosesInitialised) + { + m_orderPos[map].m_offset = position; + return true; + } + + Vec3 areaPosition; + areaPosition.x = 0.0f; + areaPosition.y = 0.0f; + areaPosition.z = 0.0f; + vec2ToVec3XZ(m_position[0], areaPosition); + areaPosition.y = m_f148; + + unsigned int polygon; + unsigned int island; + IAIPathfinding::instance->getPolygon(m_orderPos[map].m_offset, map, polygon, island, 1); + + Vec3 delta; + delta.x = position.x - areaPosition.x; + delta.y = position.y - areaPosition.y; + delta.z = position.z - areaPosition.z; + m_orderPos[map].m_offset = delta; + m_orderPos[map].island = island; + return true; +} + +// ELF 0x33A2B0. +int AIStrategicArea::setObjectTypeFlags(int flags) +{ + return m_objectTypeFlags = flags; +} + +// ELF 0x33A2D0. +int AIStrategicArea::addObjectTypeFlag(StrategicObjectType type) +{ + return m_objectTypeFlags |= 1 << type; +} + +// ELF 0x33B580: appends the named zone (grown through resize) and answers its name, or a +// message when the manager has no such zone. The zone name is read directly, not through +// AILandingZone::getName. +std::string AIStrategicArea::attachLandingZone(const std::string& name) +{ + AILandingZone* const zone = AILandingZoneManager::m_instance->getAILandingZone(name); + if (!zone) + return "No zone by that name found"; + + const int size = static_cast(m_landingZones.size()); + m_landingZones.resize(size + 1); + m_landingZones[size] = zone; + return zone->m_name; +} + +// ELF 0x33B6E0: unchecked index. +AILandingZone* AIStrategicArea::getLandingZone(int index) +{ + return m_landingZones[index]; +} + +// ELF 0x33B700: the attached zone with the id, and its index; 0 and -1 when none matches. +AILandingZone* AIStrategicArea::getLandingZone(int id, int& index) +{ + index = 0; + for (std::vector::iterator it = m_landingZones.begin(); + it != m_landingZones.end(); ++it) + { + if ((*it)->getId() == id) + return *it; + ++index; + } + index = -1; + return 0; +} + +// ELF 0x33B780. +std::vector& AIStrategicArea::getLandingZones() +{ + return m_landingZones; +} + +// ELF 0x33B790. +const std::vector& AIStrategicArea::getLandingZones() const +{ + return m_landingZones; +} + +// ELF 0x33B7A0: one attached zone name per line. +std::string AIStrategicArea::listLandingZones() +{ + std::stringstream stream; + for (int i = 0; i < static_cast(m_landingZones.size()); ++i) + { + const std::string name = m_landingZones[i]->m_name; + stream << name << std::endl; + } + return stream.str(); +} + +// ELF 0x33BC40: the attached zone with the smallest squared distance below 1e9; 0 when none. +AILandingZone* AIStrategicArea::getClosestLandingZone(const Vec2& position) +{ + float best = 1e9f; + AILandingZone* closest = 0; + for (std::vector::iterator it = m_landingZones.begin(); + it != m_landingZones.end(); ++it) + { + const float distance = (*it)->getDistanceSqr(position); + if (distance < best) + { + best = distance; + closest = *it; + } + } + return closest; +} + +// ELF 0x33BCC0: the XZ projection through the Vec2 form. +AILandingZone* AIStrategicArea::getClosestLandingZone(const Vec3& position) +{ + Vec2 flat; + flat.x = 0.0f; + flat.y = 0.0f; + vec3ToVec2XZ(position, flat); + return getClosestLandingZone(flat); +} + +// ELF 0x33BD10: the equipment bit isLandingZoneUser tests. +void AIStrategicArea::addToLandingZoneUsers(int equipment) +{ + m_i340 |= 1 << equipment; +} + +// ELF 0x33C260: clears the group bit in every distance record of the side and erases the +// records left without groups. +void AIStrategicArea::cleanUnitDistances(int side, int group) +{ + std::list::iterator it = m_distances[side - 1].begin(); + while (it != m_distances[side - 1].end()) + { + it->m_vehicleGroups &= ~(1 << group); + if (it->m_vehicleGroups == 0) + m_distances[side - 1].erase(it++); + else + ++it; + } +} + +// ELF 0x33F1C0: known vehicles with a free seat within m_f396 of the side's position. +// The ELF passes vec2ToVec3XZ's eax (the output address) as the position; the output local is the +// same object. +void AIStrategicArea::getKnownEmptyVehicles(std::vector& vehicles, int side) const +{ + const IAIInformationEnvironment* const environment = + static_cast(AISingletonServer::m_iaiInformationEnvironment); + Vec3 position; + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; + FreeUnitPred predicate(side); + vec2ToVec3XZ(m_position[side - 1], position); + environment->getObjectsWithinRadius(vehicles, position, m_f396, side, true, &predicate); +} + } // namespace ai } // namespace hfe } // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicArea.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicArea.h index 52a292fbc..0125189ef 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicArea.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicArea.h @@ -1,7 +1,6 @@ // Strategic area with explicit bounds or a control-point anchor. // Control-point areas defer initialization until world objects exist. // The base index is used to select the area's debug primitives. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. #ifndef AI_AIDLL_AI_AISTRATEGICENTITY_AISTRATEGICAREA_H // [INFERRED] guard style #define AI_AIDLL_AI_AISTRATEGICENTITY_AISTRATEGICAREA_H @@ -12,12 +11,14 @@ #include #include "AIStrategicObject.h" +#include "AreaDistanceInfo.h" namespace dice { namespace hfe { namespace ai { class AILandingZone; +class SAWayPoint; class AIStrategicArea : public AIStrategicObject { @@ -36,16 +37,15 @@ class AIStrategicArea : public AIStrategicObject } /* +0 */ Vec3 m_offset; // absolute until `initOrderPoses`, a delta afterwards - /* +12 */ unsigned int m_island; + /* +12 */ unsigned int island; // name: AIDLL_r assert "m_orderPos[vehicle].island" (0x100E45C0; PE +0x120 array, 16-byte entries) }; - // [UNRESOLVED] Distance record fields remain opaque pending their readers' type contracts. - struct AreaDistanceInfo { int m_w0; int m_w1; int m_w2; }; - // [UNRESOLVED] List payloads whose original element types have not been identified. struct AreaWord { int m_word; }; - struct AreaRecord { int m_words[6]; }; + // ELF 0x335480 (C2; C1 0x335850): an area with explicit bounds. The first float is the + // base's stored height (m_f148), the second its radius. [INFERRED] parameter names. + AIStrategicArea(const std::string& name, Vec2 topLeft, Vec2 centre, float height, float radius); AIStrategicArea(const std::string& name, unsigned int controlPointId, float radius); // [INFERRED] Initializes area state. Manager-created areas call this during initAreas; @@ -60,6 +60,45 @@ class AIStrategicArea : public AIStrategicObject // Writes the control-point position and radius; returns false for an unassigned id. bool getControlPointPosAndRadius(Vec3& position, float& radius); + // ELF 0x33BD30: bit test of the landing-zone equipment mask (+340). + bool isLandingZoneUser(int equipment); + // ELF 0x33BD50: with the side's distances dirty (+343 + side), rebuild them per vehicle + // group (or for group 0 when there are none). + void validateDistances(int side); + void validateDistances(int side, int group); // ELF 0x33BE30 + void insertUnitDistances(int side, int group); // ELF 0x33BF90 + void getDistances(int side, std::list >& distances, + std::map >& routes, + std::map& costs, int groupMask); // ELF 0x33AAC0 + + // ELF 0x33F180 / 0x33F130: inside the box from m_centre around the side-1 position (+0x84); + // the Vec3 form tests its XZ projection. + bool isInside(const Vec2& point) const; + bool isInside(const Vec3& point) const; + // ELF 0x3396E0: the address of the side-1 position (+0x84). Read by + // CommunicationHub::enemySpottedByAI. + const Vec2& getCenterPosition() const; + // ELF 0x339890 (added by ai-bot for closeAndShouldAvoidVehicles): a control point area + // (hasObjectTypeFlag(16)) whose order position for (map, side) lies beyond the control point's + // radius (IAIGame::getControlPointInfo(m_controlPointId)). + bool isOrderPosOutsideCpRadius(int map, int side); + // ELF 0x338FF0 (added by ai-bot for SquadCoordinator::squadManeuverStaticFlank): the flanking + // pair (+392 records: two Vec3) whose first position is closest to `position`; false when none. + bool getClosestFlankingPositions(Vec3 position, Vec3& first, Vec3& second); + + // ELF 0x33EF80: answers the second position; the first and the waypoint list are unused. + Vec3 getBotWaypoint(Vec3 from, Vec3 to, const std::vector& waypoints, int map); + // ELF 0x339AB0. + void getControlpointPos(AIStrategicObject* object, int side, int unit, int equipment, + const Vec3& from, Vec3& position); + + // ELF 0x33C430 / 0x33C940: orderBot's two arms (air units / everything else). Neither sets + // eax (both end in the goal list's deallocate), so they and orderBot answer nothing. + void orderAirBot(int side, const std::list& objects, int unit, ISAI* sai); + void orderNormalBot(int side, const std::list& objects, int unit, ISAI* sai); + // ELF 0x33A2F0. Declared by ai-bot for SquadMember::moveToGoalPos (0x1B4240). + bool getRouteList(int side, AIStrategicArea* from, std::list& route); + // Virtual declaration order: thirty-four ELF slots. virtual ~AIStrategicArea(); // slots 0/1, @@ -67,14 +106,14 @@ class AIStrategicArea : public AIStrategicObject // slots 3 and 4 are AIStrategicObject::getPosition / ::setPosition - not overridden virtual Vec3 getOrderPos(int a, int b) const; // slot 5, - virtual void updateTemperature(const Strategy* strategy, int side); // slot 6, + virtual float updateTemperature(const Strategy* strategy, int side); // slot 6, ELF 0x33A0F0 virtual void update(int side, ISAI* sai, bool& changed); // slot 7 virtual int getChangedAttackDefence(int side); // slot 8, virtual float getControlPointTakeOverCounter(); // slot 9 virtual bool isEnemyTakingOverBase(int side); // slot 10, - virtual int calculateDefenseNeed(int side); // slot 11, - virtual int calculateAttackValue(int side); // slot 12, - virtual int calculateAttackCost(int side); // slot 13, + virtual float calculateDefenseNeed(int side); // slot 11, + virtual float calculateAttackValue(int side); // slot 12, + virtual float calculateAttackCost(int side); // slot 13, virtual bool isNeighbour(AIStrategicObject* object) const; // slot 14, virtual bool hasNeighbourWithStatus(StatusMap::Status status, int side) const; // slot 15, @@ -87,30 +126,59 @@ class AIStrategicArea : public AIStrategicObject virtual bool hasObjectTypeFlags(int flags) const; // slot 20, virtual int getTacticalStatus(int side) const; // slot 21, virtual bool isAreaTakeable(); // slot 22, - virtual int collectSquadResources(int side, ISAI* sai); // slot 23, - virtual int collectAdditionalSquadResources(int side, int amount, ISAI* sai); + virtual bool collectSquadResources(int side, ISAI* sai); // slot 23, ELF 0x33A380 + virtual int collectAdditionalSquadResources(int amount, int side, ISAI* sai); // slot 24, - virtual int releaseSurplus(int side); // slot 25, + virtual bool releaseSurplus(int side); // slot 25, ELF 0x33A6A0 virtual float gravity(const Vec3& position, int side); // slot 26, virtual float gravity(const Vec2& position, int side); // slot 27, virtual bool retainBot(int side, int a, ISAI* sai); // slot 28, virtual float getXExtent(int side) const; // slot 29, virtual float getZExtent(int side) const; // slot 30, virtual void setAsDirty(int side); // slot 31, - virtual int orderBot(int side, const std::list& objects, - int a, ISAI* sai); // slot 32, + virtual void orderBot(int side, const std::list& objects, + int unit, ISAI* sai); // slot 32, ELF 0x33C340 // Additional virtual overload declared after the inherited slots. virtual float gravity(float distance, int side); // slot 33, -// [FRONTIER] Additional area operations remain undeclared until their signatures are established. + // Non-virtual area operations called by AIStrategicObjectManager and the console bindings. + void addFlankPosition(Vec3 first, Vec3 second); // ELF 0x338EC0 + std::list > getFlankPositions(); // ELF 0x338F50 + void addNeighbour(AIStrategicObject* object); // ELF 0x3391A0 + void removeNeighbour(AIStrategicObject* object); // ELF 0x339230 + void addNeighbouringObject(AIStrategicObject* object); // ELF 0x3393E0 + void removeAllNeighbours(); // ELF 0x339500 + // The base's virtual setPosition(int, const Vec2&) stays visible beside this overload. + using AIStrategicObject::setPosition; + void setPosition(const Vec2& position); // ELF 0x339680 + void setCenterPosition(const Vec2& position); // ELF 0x3396B0 + void setTopLeftCorner(const Vec2& corner); // ELF 0x3396F0 + bool setOrderPos(int map, const Vec3& position); // ELF 0x339710 + // Both answer the new flag word: AIStrategicObjectManager's forwarders (ELF 0x346850, + // 0x3467B0) return the call's eax as their own int result. + int setObjectTypeFlags(int flags); // ELF 0x33A2B0 + int addObjectTypeFlag(StrategicObjectType type); // ELF 0x33A2D0 + std::string attachLandingZone(const std::string& name); // ELF 0x33B580 + AILandingZone* getLandingZone(int index); // ELF 0x33B6E0 + AILandingZone* getLandingZone(int id, int& index); // ELF 0x33B700 + std::vector& getLandingZones(); // ELF 0x33B780 + const std::vector& getLandingZones() const; // ELF 0x33B790 + std::string listLandingZones(); // ELF 0x33B7A0 + AILandingZone* getClosestLandingZone(const Vec2& position); // ELF 0x33BC40 + AILandingZone* getClosestLandingZone(const Vec3& position); // ELF 0x33BCC0 + void addToLandingZoneUsers(int equipment); // ELF 0x33BD10 + void cleanUnitDistances(int side, int group); // ELF 0x33C260 + void getKnownEmptyVehicles(std::vector& vehicles, int side) const; // ELF 0x33F1C0 // layout, ELF offsets, read store by store out of the constructor // The base occupies 0..267. MSVC's own offsets will differ - a libstdc++ `std::list` is four // bytes and a `std::string` is four. These are documentation, not a layout claim for this build. /* +268 */ std::list m_list268; // [UNRESOLVED] - landing zones? node 12 B - /* +272 */ Vec2 m_centre; // zeroed; getXExtent/getZExtent subtract it - /* +280 */ MapData* m_mapData; // new MapData[IAIPathfinding::getNumberOfMaps] + // The top-left corner: the bounded constructor and setTopLeftCorner store it; [INFERRED] + // name kept from the control-point path, which derives it from the control-point radius. + /* +272 */ Vec2 m_centre; // getXExtent/getZExtent subtract it + /* +280 */ MapData* m_orderPos; // new MapData[IAIPathfinding::getNumberOfMaps] // name: AIDLL_r assert 0x100E45C0 (PE +0x120) // Separate vectors for neighboring areas and other neighboring strategic objects. /* +284 */ std::vector m_neighbours; /* +296 */ std::vector m_neighbouringObjects; @@ -118,11 +186,11 @@ class AIStrategicArea : public AIStrategicObject /* +312 */ int m_objectTypeFlags; // 0; `getObjectTypeFlags` returns exactly this /* +316 */ unsigned int m_controlPointId; // the second script argument, e.g. 502 // [UNRESOLVED] Both fields are initialized to 25; their meanings are unknown. - /* +320 */ int m_i320; // = 25 - /* +324 */ int m_i324; // = 25 + /* +320 */ int m_i320; // = 25; tactical status, side 1 (getTacticalStatus) + /* +324 */ int m_i324; // = 25; tactical status, side 2 // Landing zones associated with this area. /* +328 */ std::vector m_landingZones; - /* +340 */ int m_i340; // 0 [UNRESOLVED] + /* +340 */ int m_i340; // 0; landing-zone equipment bit mask // Per-vehicle-group arrays; each allocation has at least one element. // [INFERRED] Container element types remain partly uncertain. Side-indexed flags use side - 1. /* +344 */ bool m_distancesDirty[2]; // both = true [INFERRED] name @@ -130,31 +198,33 @@ class AIStrategicArea : public AIStrategicObject /* +348 */ bool* m_flagsA; // new bool[groups], all true [UNRESOLVED] /* +352 */ bool* m_flagsB; // new bool[groups], all true [UNRESOLVED] /* +356 */ bool m_sideEnabled[2]; // both true; [INFERRED] name, update side gates - /* +358 */ bool m_b358; // false [UNRESOLVED] (the constructor's) + /* +358 */ bool m_showNeighbours; // false; console showNeighbours /* +359 */ char m_pad359[1]; /* +360 */ std::list >* m_listsA; // [group] /* +364 */ std::list >* m_listsB; // [group] - /* +368 */ std::map* m_mapsA; // [group] - /* +372 */ std::map* m_mapsB; // [group] + /* +368 */ std::map >* m_mapsA; // list-valued (validateDistances teardown); [group] + /* +372 */ std::map >* m_mapsB; // list-valued (validateDistances teardown); [group] /* +376 */ std::map* m_mapsC; // [group] /* +380 */ std::map* m_mapsD; // [group] // Per-side distance records, indexed by side - 1 like m_distancesDirty. /* +384 */ std::list m_distances[2]; - /* +392 */ std::list m_list392; // node + // Flanking position pairs (addFlankPosition / getClosestFlankingPositions); node 0x20. + /* +392 */ std::list > m_flankPositions; // Stored doubled extent, initialized to twice m_size[1]. /* +396 */ float m_f396; // = 2 * m_size[1] [UNRESOLVED] meaning - /* +400 */ int m_i400; // 1 [UNRESOLVED] - /* +404 */ bool m_b404; // true + // -1 from both constructors. Read as a layer by AIStrategicObjectManager: neighbours must share + // it (addNeighbour) and streamWaypoints filters on it. [INFERRED] meaning; no writer known. + /* +400 */ int m_i400; + /* +404 */ bool m_visible; // true; console setVisible/getVisible /* +405 */ bool m_statusChanged; // false; update stores its changed output here // Additional state initialized by internalConstructorCall. /* +406 */ bool m_enemyTakeover[2]; // both false; [INFERRED] name, update's side flags /* +408 */ float m_f408; // = 1.0f [UNRESOLVED] /* +412 */ float m_f412; // = 1.0f [UNRESOLVED] - /* +416 */ int m_i416; // 0 [UNRESOLVED] - /* +420 */ int m_i420; // 0 [UNRESOLVED] - /* +424 */ int m_i424; // 0 [UNRESOLVED] - // Selects control-point initialization; explicit-position construction sets it false - // and uses control point id -1. + // Both constructors store 0.0f to all three words. [UNRESOLVED] meaning. + /* +416 */ Vec3 m_v416; + // Selects control-point initialization; the bounded constructor sets it false and uses + // control point id -1. /* +428 */ bool m_fromControlPoint; // true // Raised by `initOrderPoses` and by nothing else; both constructors clear it. [INFERRED] /* +429 */ bool m_orderPosesInitialised; // false diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObject.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObject.cpp index 3de86528b..0917f5058 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObject.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObject.cpp @@ -1,11 +1,23 @@ // [INFERRED] Source placement. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining AIStrategicObject operations. #include "AIStrategicObject.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x342FE0, __tcf_0 0x343040, _GLOBAL__I 0x343070). +#include + +#include + #include "../AIStrategic/SAI.h" // EnemyStatistics - the four objects the constructor makes #include "../Main/AIDllFrontier.h" #include "../Main/AIMain.h" +#include "../Main/AIRandom.h" +#include "../Main/AISettingsInterfaces.h" // IAISettings::getVehicleGroup +#include "../Main/CommonSingletonServer.h" +#include "../Main/IBotManager.h" +#include "../AIBot/BotMain.h" // Bot::getCurrentEquipment +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" namespace dice { namespace hfe { @@ -13,6 +25,7 @@ namespace ai { // Initializes strategic-object state and its owned enemy-statistics records. +// ELF 0x340C60 (C2; C1 0x341190). AIStrategicObject::AIStrategicObject(float radius, float f148) : m_position() // the two-iteration zeroing loop at +132, in member-declaration position { @@ -22,14 +35,14 @@ AIStrategicObject::AIStrategicObject(float radius, float f148) m_statistics[3] = new EnemyStatistics(2); const std::set empty; - m_set20[0] = empty; - m_set20[1] = empty; - m_set44[0] = empty; - m_set44[1] = empty; + m_availableAttackers[0] = empty; + m_availableAttackers[1] = empty; + m_availableDefenders[0] = empty; + m_availableDefenders[1] = empty; m_set68[0] = empty; m_set68[1] = empty; - m_set92[0] = empty; - m_set92[1] = empty; + m_presentUnits[0] = empty; + m_presentUnits[1] = empty; m_status[0] = StatusMap::Neutral; m_status[1] = StatusMap::Neutral; @@ -67,23 +80,28 @@ AIStrategicObject::AIStrategicObject(float radius, float f148) m_category = -1; } -// [FRONTIER] Destruction requires ordered statistics and container teardown. -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -// Replace the stop when the destructor is recovered. +// ELF 0x341600 (D2; D1 0x3418F0, D0 0x341BE0): deletes the four EnemyStatistics (+4..+0x10, each +// tested for null); the sets (+0x100 down to +0x14) go as members. AIStrategicObject::~AIStrategicObject() { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicObject::~AIStrategicObject"); + for (int i = 0; i < 4; ++i) + { + if (m_statistics[i]) + delete m_statistics[i]; + } } // native set size, side is one-based. // ELF getAssignedUnits(int) at returns the matching set; the two old STL layouts // place their counts four bytes apart. SAI::updateStates tests the signed result against zero. +// ELF 0x3423A0. int AIStrategicObject::getNumberOfAssignedUnits(int side) const { return static_cast(m_set68[side - 1].size()); } // byte at this + 0xEB + side, no bounds guard. +// ELF 0x341FD0. bool AIStrategicObject::isAttack(int side) const { return m_attack[side - 1]; @@ -93,6 +111,7 @@ bool AIStrategicObject::isAttack(int side) const // statistics pointer is at +4, so the side is one-based. The caller passes this // borrowed address to EnemyStatistics::add(EnemyStatistics&); pointer versus // reference return spelling is [INFERRED]. No null or side guard is present. +// ELF 0x3425E0. EnemyStatistics& AIStrategicObject::getBattleStatistics(int side) const { return *m_statistics[side - 1]; @@ -101,6 +120,7 @@ EnemyStatistics& AIStrategicObject::getBattleStatistics(int side) const // Returns the signed count of released resources, or zero when a commander refuses. // Re-queries the SAI after the commander callback and reads the object index afterward. // The downstream SAI release operation remains a named frontier. +// ELF 0x342090. int AIStrategicObject::releaseAssignedResources(int side) { if (IAIMain::m_instance->getSAI(side)->isPlayerCommander()) @@ -110,64 +130,432 @@ int AIStrategicObject::releaseAssignedResources(int side) return sai->releaseSquadsFromObject(m_index, side); } +// ELF 0x3422A0. +std::set& AIStrategicObject::getAvailableBots(bool attackers, int side) +{ + if (attackers) + return m_availableAttackers[side - 1]; + return m_availableDefenders[side - 1]; +} + +// ELF 0x3422D0. +std::set& AIStrategicObject::getAvailableAttackers(int side) +{ + return m_availableAttackers[side - 1]; +} + +// ELF 0x3422F0. +std::set& AIStrategicObject::getAvailableDefenders(int side) +{ + return m_availableDefenders[side - 1]; +} + +// ELF 0x3426E0. +bool AIStrategicObject::unregisterAvailableAttacker(std::set::iterator& it, int side) +{ + std::set& units = m_availableAttackers[side - 1]; + if (it == units.end()) + return false; + units.erase(it++); + return true; +} + +// ELF 0x342780. +bool AIStrategicObject::unregisterAvailableDefender(std::set::iterator& it, int side) +{ + std::set& units = m_availableDefenders[side - 1]; + if (it == units.end()) + return false; + units.erase(it++); + return true; +} + +// ELF 0x341FF0. +bool AIStrategicObject::registerAvailableAttacker(int unit, int side) +{ + m_availableAttackers[side - 1].insert(unit); + return true; +} + +// ELF 0x342040. +bool AIStrategicObject::registerAvailableDefender(int unit, int side) +{ + m_availableDefenders[side - 1].insert(unit); + return true; +} + +// ELF 0x342600. +bool AIStrategicObject::unregisterAvailableAttacker(int unit, int side) +{ + std::set::iterator it = m_availableAttackers[side - 1].find(unit); + return unregisterAvailableAttacker(it, side); +} + +// ELF 0x342670. +bool AIStrategicObject::unregisterAvailableDefender(int unit, int side) +{ + std::set::iterator it = m_availableDefenders[side - 1].find(unit); + return unregisterAvailableDefender(it, side); +} + +// ELF 0x342310. +std::set& AIStrategicObject::getAssignedUnits(int side) +{ + return m_set68[side - 1]; +} + +// ELF 0x3423E0. +std::set& AIStrategicObject::getPresentUnits(int side) +{ + return m_presentUnits[side - 1]; +} + +// ELF 0x342400. +bool AIStrategicObject::isPresentUnit(int unit, int side) const +{ + return m_presentUnits[side - 1].find(unit) != m_presentUnits[side - 1].end(); +} + +// ELF 0x342460. +std::pair::iterator, bool> AIStrategicObject::setAsPresentUnit(int unit, int side) +{ + return m_presentUnits[side - 1].insert(unit); +} + +// ELF 0x342550. +void AIStrategicObject::removeAsPresentUnit(std::set::iterator& it, int side) +{ + m_presentUnits[side - 1].erase(it++); +} + +// ELF 0x3424C0. +std::set::iterator AIStrategicObject::removeAsPresentUnit(int unit, int side) +{ + std::set::iterator it = m_presentUnits[side - 1].find(unit); + if (it != m_presentUnits[side - 1].end()) + removeAsPresentUnit(it, side); + return it; +} + +// ELF 0x342E80. +bool AIStrategicObject::isAllowedVehicleGroup(int group) const +{ + return (m_i244 >> group) & 1; +} + +// ELF 0x342EA0. +bool AIStrategicObject::allowsSomeVehicleGroups(int groupMask) const +{ + return (m_i244 & groupMask) != 0; +} + +// Two draws (AIRandom, the inline tempering), x then z: offset = draw * extent * scale - +// 0.5 * extent, each extent queried twice (`call *0x74/*0x78` per use). +// ELF 0x342B80. +void AIStrategicObject::randomizePos(int side, float scale, Vec3& position) +{ + AIRandom* const random = AIRandom::m_instance; + const float drawX = random->nextFloat(); + const float scaledX = getXExtent(side) * drawX * scale; + const float dx = scaledX - getXExtent(side) * 0.5f; + const float drawZ = random->nextFloat(); + const float scaledZ = drawZ * getZExtent(side) * scale; + const float dz = scaledZ - getZExtent(side) * 0.5f; + position.x = dx + m_position[side - 1].x; + position.y = m_f148; + position.z = dz + m_position[side - 1].y; +} + +// Kept in x87 extended precision in the image: the angle (draw * 2 * pi, rodata 3.14159274f) and +// the distance chain; sinf/cosf take the float angle. The direction is the image's +// (1,0,0) * sin + (0,0,1) * cos sum, zero products included. +// ELF 0x342990. +void AIStrategicObject::randomizeControlpointPos(float scale, float spread, Vec3& position) +{ + AIRandom* const random = AIRandom::m_instance; + const double turn = static_cast(random->next()) * static_cast(2.32830644e-10f); + const double angle = (turn + turn) * static_cast(3.14159274f); + const double draw = static_cast(random->next()) * static_cast(2.32830644e-10f); + const float distance = static_cast( + (0.5 + draw * (static_cast(spread) - 0.5)) * scale); + const double s = std::sin(static_cast(angle)); + const double c = std::cos(static_cast(angle)); + const double dirX = s * 1.0 + c * 0.0; + const double dirY = c * 0.0 + s * 0.0; + const double dirZ = c * 1.0 + s * 0.0; + position.x = static_cast(dirX * distance + position.x); + position.y = static_cast(dirY * distance + position.y); + position.z = static_cast(dirZ * distance + position.z); +} + +// ELF 0x342EF0. +bool AIStrategicObject::isExpelledUnit(int equipment) const +{ + return (m_i248 >> equipment) & 1; +} + +// ELF 0x341FB0. +void AIStrategicObject::setAttack(bool attack, int side) +{ + m_attack[side - 1] = attack; +} + +// ELF 0x342940. +float AIStrategicObject::getAssignedPartOfWantedStrength(int side) const +{ + const int need = m_resourceNeed[side - 1]; + if (!need) + return 1.0f; + return static_cast(m_assignedSquadStrength[side - 1] / need); +} + // The ten accessors. Every one of them is between seven and thirty-three bytes in the image. // Returns type code 3; AIStrategicArea returns 0. // [UNRESOLVED] These codes are not established as StrategicObjectType values. +// ELF 0x343280. int AIStrategicObject::getType() const { return 3; } // - `return (char *)this + 8 * side + 124;`, i.e. the 1-based fold. See the header. +// ELF 0x340B20. const Vec2& AIStrategicObject::getPosition(int side) const { return m_position[side - 1]; } // - two dword stores, a memberwise Vec2 copy. +// ELF 0x340B40. void AIStrategicObject::setPosition(int side, const Vec2& position) { m_position[side - 1] = position; } // Returns bit 27. [UNRESOLVED] No named StrategicObjectType enumerator covers that bit. +// ELF 0x343290. int AIStrategicObject::getObjectTypeFlags() const { return 0x8000000; } +// ELF 0x3432A0. bool AIStrategicObject::hasObjectTypeFlag(StrategicObjectType) const { return false; } +// ELF 0x3432B0. bool AIStrategicObject::hasObjectTypeFlags(int) const { return false; } +// ELF 0x3432C0. float AIStrategicObject::gravity(const Vec3&, int) { return 0.0f; } +// ELF 0x3432E0. float AIStrategicObject::gravity(const Vec2&, int) { return 0.0f; } // Returns twice the side-specific size for both axes; base strategic objects are square. +// ELF 0x343300. float AIStrategicObject::getXExtent(int side) const { return m_size[side] + m_size[side]; } +// ELF 0x343320. float AIStrategicObject::getZExtent(int side) const { return m_size[side] + m_size[side]; } +// ELF 0x342FC0: the current statuses (+0x74/+0x78) take the initial ones (+0x7C/+0x80). +void AIStrategicObject::resetStatus() +{ + m_status[0] = m_status[2]; + m_status[1] = m_status[3]; +} + +// ELF 0x341ED0. +void AIStrategicObject::setSide(int side) +{ + if (side == 1) + { + m_status[0] = StatusMap::Owned; + m_status[2] = StatusMap::Owned; + m_status[1] = StatusMap::Hostile; + m_status[3] = StatusMap::Hostile; + } + else if (side == 2) + { + m_status[0] = StatusMap::Hostile; + m_status[2] = StatusMap::Hostile; + m_status[1] = StatusMap::Owned; + m_status[3] = StatusMap::Owned; + } + else + { + m_status[2] = StatusMap::Neutral; + m_status[3] = StatusMap::Neutral; + } +} + +// ELF 0x341F40. +int AIStrategicObject::getSide() +{ + if (m_status[2] == StatusMap::Owned) + return 1; + return m_status[3] == StatusMap::Owned ? 2 : 0; +} + +// ELF 0x341F70. +void AIStrategicObject::setPriority(int priority, int side) +{ + m_unresolved212[side - 1] = priority; +} + +// ELF 0x341F90. +int AIStrategicObject::getPriority(int side) const +{ + return m_unresolved212[side - 1]; +} + +// ELF 0x342110. +bool AIStrategicObject::releaseAssignedUnit(int unit, int side) +{ + std::set::iterator it = m_set68[side - 1].find(unit); + if (it == m_set68[side - 1].end()) + return false; + return IAIMain::m_instance->getSAI(side)->releaseUnitFromObject(m_index, it, side); +} + +// ELF 0x3421C0. The find in the chosen available set is the image's (its result is unused). +bool AIStrategicObject::bookBot(bool attacker, int side, std::set::iterator& it) +{ + const int unit = *it; + if (attacker) + (void)m_availableAttackers[side - 1].find(unit); + else + (void)m_availableDefenders[side - 1].find(unit); + Bot* const bot = IBotManager::instance->getBotFromId(unit); + InformationManager* const manager = informationManager; + Information* const information = manager->getInformation(bot->getCurrentEquipment()); + return information && information->getUnit(); +} + +// ELF 0x342330. +int AIStrategicObject::getNumberOfAvailableBots(bool attackers, int side) const +{ + if (attackers) + return static_cast(m_availableAttackers[side - 1].size()); + return static_cast(m_availableDefenders[side - 1].size()); +} + +// ELF 0x342360. +int AIStrategicObject::getNumberOfAvailableAttackers(int side) const +{ + return static_cast(m_availableAttackers[side - 1].size()); +} + +// ELF 0x342380. +int AIStrategicObject::getNumberOfAvailableDefenders(int side) const +{ + return static_cast(m_availableDefenders[side - 1].size()); +} + +// ELF 0x3423C0. +int AIStrategicObject::getNumberOfPresentUnits(int side) const +{ + return static_cast(m_presentUnits[side - 1].size()); +} + +// ELF 0x3425F0. +EnemyStatistics& AIStrategicObject::getStrategicStatistics(int side) const +{ + return *m_statistics[side + 1]; +} + +// ELF 0x342820. +int AIStrategicObject::unregisterAllAvailableAttackers(int side) +{ + const int count = static_cast(m_availableAttackers[side - 1].size()); + m_availableAttackers[side - 1].clear(); + return count; +} + +// ELF 0x3428B0. +int AIStrategicObject::unregisterAllAvailableDefenders(int side) +{ + const int count = static_cast(m_availableDefenders[side - 1].size()); + m_availableDefenders[side - 1].clear(); + return count; +} + +// ELF 0x342D40. +void AIStrategicObject::addAllowedUnit(int equipment) +{ + addAllowedVehicleGroup( + static_cast(CommonSingletonServer::m_iaiSettings)->getVehicleGroup(equipment)); +} + +// ELF 0x342D90. +void AIStrategicObject::addAllowedVehicleGroup(int group) +{ + if (m_i244 == -1) + m_i244 = 0; + m_i244 |= 1 << group; +} + +// ELF 0x342DD0. +void AIStrategicObject::addAllowedVehicleGroup(const std::string& group) +{ + addAllowedVehicleGroup( + static_cast(CommonSingletonServer::m_iaiSettings)->getVehicleGroup(group)); +} + +// ELF 0x342E20. +int AIStrategicObject::getAllowedVehicleGroups() const +{ + return m_i244; +} + +// ELF 0x342E30. +bool AIStrategicObject::isAllowedUnit(int equipment) const +{ + return isAllowedVehicleGroup( + static_cast(CommonSingletonServer::m_iaiSettings)->getVehicleGroup(equipment)); +} + +// ELF 0x342EC0. +void AIStrategicObject::addExpelledUnit(int equipment) +{ + m_i248 |= 1 << equipment; +} + +// ELF 0x342EE0. +int AIStrategicObject::getExpelledVehicleTypes() const +{ + return m_i248; +} + +// ELF 0x342F10. +bool AIStrategicObject::removeGrouping(int group) +{ + std::set::iterator it = m_set256.find(group); + if (it == m_set256.end()) + return false; + m_set256.erase(it); + return true; +} + } // namespace ai } // namespace hfe } // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObject.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObject.h index 6d1584141..34933ebcc 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObject.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObject.h @@ -1,5 +1,4 @@ // Base interface and shared state for strategic objects. Preserve virtual declaration order. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. // [INFERRED] Source placement. #ifndef AI_AIDLL_AI_AISTRATEGICENTITY_AISTRATEGICOBJECT_H // [INFERRED] guard style @@ -7,6 +6,7 @@ #include #include +#include // Vec2 and Vec3 cannot be forward-declared in this tree: both are typedefs to // `dice::hfe::Math::Vec2/Vec3`, so a local `struct Vec3;` is a redefinition with a different basic @@ -70,14 +70,14 @@ class AIStrategicObject // and parameter list below is taken from the matching slot of `AIStrategicArea`'s vtable; the // return types are [INFERRED] from whether the override leaves its result in eax or in st0. virtual Vec3 getOrderPos(int a, int b) const = 0; // slot 5 - virtual void updateTemperature(const Strategy* strategy, int side) = 0; // slot 6 + virtual float updateTemperature(const Strategy* strategy, int side) = 0; // slot 6; SAI discards st0 virtual void update(int side, ISAI* sai, bool& changed) = 0; // slot 7; paired Area body has no return virtual int getChangedAttackDefence(int side) = 0; // slot 8 virtual float getControlPointTakeOverCounter() = 0; // slot 9; ST0 float chain virtual bool isEnemyTakingOverBase(int side) = 0; // slot 10 - virtual int calculateDefenseNeed(int side) = 0; // slot 11 - virtual int calculateAttackValue(int side) = 0; // slot 12 - virtual int calculateAttackCost(int side) = 0; // slot 13 + virtual float calculateDefenseNeed(int side) = 0; // slot 11 + virtual float calculateAttackValue(int side) = 0; // slot 12 + virtual float calculateAttackCost(int side) = 0; // slot 13 virtual bool isNeighbour(AIStrategicObject* object) const = 0; // slot 14 virtual bool hasNeighbourWithStatus(StatusMap::Status status, int side) const = 0; // slot 15 virtual bool isNeighbouringObject(AIStrategicObject* object) const = 0; // slot 16 @@ -90,9 +90,9 @@ class AIStrategicObject virtual int getTacticalStatus(int side) const = 0; // slot 21 virtual bool isAreaTakeable() = 0; // slot 22 - virtual int collectSquadResources(int side, ISAI* sai) = 0; // slot 23 - virtual int collectAdditionalSquadResources(int side, int amount, ISAI* sai) = 0; // slot 24 - virtual int releaseSurplus(int side) = 0; // slot 25 + virtual bool collectSquadResources(int side, ISAI* sai) = 0; // slot 23 + virtual int collectAdditionalSquadResources(int amount, int side, ISAI* sai) = 0; // slot 24 + virtual bool releaseSurplus(int side) = 0; // slot 25 virtual float gravity(const Vec3& position, int side); // slot 26, virtual float gravity(const Vec2& position, int side); // slot 27, @@ -103,29 +103,100 @@ class AIStrategicObject virtual float getZExtent(int side) const; // slot 30, virtual void setAsDirty(int side) = 0; // slot 31 - virtual int orderBot(int side, const std::list& objects, + // void: AIStrategicArea::orderBot (ELF 0x33C340) passes through its arms' eax, which neither + // arm sets. + virtual void orderBot(int side, const std::list& objects, int a, ISAI* sai) = 0; // slot 32 int getNumberOfAssignedUnits(int side) const; + // ELF 0x341ED0 / 0x341F40: the per-side statuses for owner 1 or 2 (any other value marks + // only the second pair Neutral); getSide answers 1, 2 or 0 from the second pair. + void setSide(int side); + int getSide(); + void setPriority(int priority, int side); // ELF 0x341F70 + int getPriority(int side) const; // ELF 0x341F90 + // ELF 0x342110: hands an assigned unit back through the side's SAI; false when unassigned. + bool releaseAssignedUnit(int unit, int side); + // ELF 0x3421C0: whether the unit under the iterator drives a known unit (its current + // equipment's information has a unit part). + bool bookBot(bool attacker, int side, std::set::iterator& it); + int getNumberOfAvailableBots(bool attackers, int side) const; // ELF 0x342330 + int getNumberOfAvailableAttackers(int side) const; // ELF 0x342360 + int getNumberOfAvailableDefenders(int side) const; // ELF 0x342380 + int getNumberOfPresentUnits(int side) const; // ELF 0x3423C0 + // ELF 0x3425F0: m_statistics[side + 1], the second (size-2) pair. Reference spelling + // [INFERRED], as getBattleStatistics. + EnemyStatistics& getStrategicStatistics(int side) const; + // ELF 0x342820 / 0x3428B0: empty the side's available set; answer the count it held + // (the image reloads the pre-clear size into eax). [INFERRED] int. + int unregisterAllAvailableAttackers(int side); + int unregisterAllAvailableDefenders(int side); + // ELF 0x342D40 / 0x342D90 / 0x342DD0: set a vehicle-group bit of +0xF4, which a -1 ("all") + // mask first resets to 0; the equipment and name forms map through IAISettings. + void addAllowedUnit(int equipment); + void addAllowedVehicleGroup(int group); + void addAllowedVehicleGroup(const std::string& group); + int getAllowedVehicleGroups() const; // ELF 0x342E20 + bool isAllowedUnit(int equipment) const; // ELF 0x342E30 + void addExpelledUnit(int equipment); // ELF 0x342EC0 + int getExpelledVehicleTypes() const; // ELF 0x342EE0 + // ELF 0x342F10: erases the group from m_set256; false when absent. + bool removeGrouping(int group); bool isAttack(int side) const; + void setAttack(bool attack, int side); // ELF 0x341FB0 + // ELF 0x342940: assigned squad strength / resource need (integer division), 1 without need. + float getAssignedPartOfWantedStrength(int side) const; // Borrowed mutable statistics at m_statistics[side - 1]; reference spelling is [INFERRED]. EnemyStatistics& getBattleStatistics(int side) const; int releaseAssignedResources(int side); + // ELF 0x3422A0..0x342300: the per-side available-unit sets (m_availableAttackers attackers, m_availableDefenders + // defenders), one-based side. Reference spelling [INFERRED]. + std::set& getAvailableBots(bool attackers, int side); + std::set& getAvailableAttackers(int side); + std::set& getAvailableDefenders(int side); + // ELF 0x3426E0 / 0x342780: erase the unit under the iterator and advance it; false at end(). + bool unregisterAvailableAttacker(std::set::iterator& it, int side); + bool unregisterAvailableDefender(std::set::iterator& it, int side); + bool registerAvailableAttacker(int unit, int side); // ELF 0x341FF0; always true + bool registerAvailableDefender(int unit, int side); // ELF 0x342040; always true + bool unregisterAvailableAttacker(int unit, int side); // ELF 0x342600 + bool unregisterAvailableDefender(int unit, int side); // ELF 0x342670 + // ELF 0x342310 / 0x3423E0..0x342550: assigned (m_set68) and present (m_presentUnits) units. + std::set& getAssignedUnits(int side); + std::set& getPresentUnits(int side); + bool isPresentUnit(int unit, int side) const; + std::pair::iterator, bool> setAsPresentUnit(int unit, int side); + void removeAsPresentUnit(std::set::iterator& it, int side); + // ELF 0x3424C0: find in the present set, erase when found; answers the find result. + std::set::iterator removeAsPresentUnit(int unit, int side); + // ELF 0x342E80 / 0x342EF0: bit tests of the vehicle-group mask (+0xF4) and the expelled + // equipment mask (+0xF8). + bool isAllowedVehicleGroup(int group) const; + bool isExpelledUnit(int equipment) const; + // ELF 0x342EA0: `mov 0xf4(%eax),%eax; and %edx,%eax; setne` - any bit of a group mask. + bool allowsSomeVehicleGroups(int groupMask) const; + // ELF 0x342B80: a uniform point in the side's extent box (slots 29/30) scaled by `scale`, + // around the side's position, at height m_f148. + void randomizePos(int side, float scale, Vec3& position); + // ELF 0x342990: position += (sin a, 0, cos a) * scale * (0.5 + draw * (spread - 0.5)), a a + // uniform angle. + void randomizeControlpointPos(float scale, float spread, Vec3& position); // [INFERRED] accessor names/forms. SAI::updateStates and the area's neighbour scans inline // these loads: status is at +0x70 + 4*side and index at +0xF0 in both shipped x86 ports. StatusMap::Status getStatus(int side) const { return m_status[side - 1]; } int getIndex() const { return m_index; } + void resetStatus(); // ELF 0x342FC0 // [CHOSEN, not recovered] Public fields allow manager access; the original may have // used friendship instead. Offsets document ELF layout and do not constrain modern STL sizes. /* +4 */ EnemyStatistics* m_statistics[4]; // new EnemyStatistics(6), (6), (2), (2) in order // Per-side strategic-object sets. [UNRESOLVED] Exact roles of these four pairs remain // unidentified; at least two pairs represent neighboring areas and objects. - /* +20 */ std::set m_set20[2]; - /* +44 */ std::set m_set44[2]; + /* +20 */ std::set m_availableAttackers[2]; // name: AIDLL_r assert 0x100E8A80 (PE +0x14) + /* +44 */ std::set m_availableDefenders[2]; // name: AIDLL_r assert 0x100E8A80 (PE +0x2C) /* +68 */ std::set m_set68[2]; // assigned units, one-based side accessor - /* +92 */ std::set m_set92[2]; + /* +92 */ std::set m_presentUnits[2]; // name: AIDLL_r assert 0x100E3E80 (PE +0x5C) // All four set to 2. `StatusMap::Status(2)` is `Neutral`, which is the only reason this member // carries that name - [INFERRED], on the strength of one coincidence. @@ -135,7 +206,10 @@ class AIStrategicObject /* +132 */ Vec2 m_position[2]; /* +148 */ float m_f148; // the constructor's second argument; -666.0f from every caller - /* +152 */ float m_size[3]; // [0] = the radius argument, [1] and [2] zeroed; read by side + // Console basicTemperature is element zero; update adds it to both temperature pairs. + // Keep the shared array spelling used by side-radius readers in other subsystems. + enum { kBasicTemperature = 0 }; + /* +152 */ float m_size[3]; // [kBasicTemperature] baseline temperature; [1..2] side radii /* +164 */ float m_f164[4]; // all four set to the radius argument [UNRESOLVED] // Paired Area::update reads/writes these as floats, not the formerly guessed ints. // [INFERRED] names; one-based side pairs, all zeroed by the base constructor. @@ -143,13 +217,13 @@ class AIStrategicObject /* +188 */ float m_friendlyRatio[2]; /* +196 */ float m_friendlyBattleStrength[2]; /* +204 */ float m_enemyBattleStrength[2]; - /* +212 */ int m_unresolved212[2]; // zeroed; these two preceding counts remain unidentified + /* +212 */ int m_unresolved212[2]; // zeroed; the per-side priority (setPriority / getPriority) /* +220 */ int m_resourceNeed[2]; /* +228 */ int m_assignedSquadStrength[2]; /* +236 */ bool m_attack[2]; // both true; isAttack(side) reads [side - 1] /* +240 */ int m_index; // not initialised here - addStrategicObject assigns it - /* +244 */ int m_i244; // 1 [UNRESOLVED] - /* +248 */ int m_i248; // 0 [UNRESOLVED] + /* +244 */ int m_i244; // -1; allowed vehicle-group bit mask (isAllowedVehicleGroup) + /* +248 */ int m_i248; // 0; expelled equipment bit mask (isExpelledUnit) /* +252 */ int m_category; // 1 until createFromControlPoint or create sets it /* +256 */ std::set m_set256; }; diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp index cff7ed937..00312a001 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp @@ -1,13 +1,29 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining AIStrategicObjectManager operations. - #include "AIStrategicObjectManager.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x34A400, __tcf_0 0x34A460, _GLOBAL__I 0x34A490). +#include + #include "AIStrategicArea.h" // createFromControlPoint constructs one +#include +#include // checkLayerStrList's strtok +#include "../AIKnowledge/Information.h" +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../AIBot/SquadManager.h" // haveHumanPlayerOnOwnSide +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../../../../Math/Mat4.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" #include "SAWayPoint.h" // the destructor and postLoadInitAreas own them #include "../AIUtils/checkPointer.h" #include "../AIUtils/DebugRendering/AIRenderUtil.h" // addStrategicObject's null-guarded tail #include "../Main/AIDllFrontier.h" -#include "../../../../Core/ConsoleObjectMacro.h" // the aiStrategicArea.* binding at the foot +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IAIPathfinding.h" +#include "../Main/AIStreamOperators.h" // StrategicObjectType names +#include "../../../../Core/StringUtil.h" // formatString namespace dice { namespace hfe { @@ -15,10 +31,70 @@ namespace ai { AIStrategicObjectManager* AIStrategicObjectManager::m_instance = 0; +// ELF 0x344F30: the object with the strongest gravity at the position among those allowing the +// equipment's vehicle group and not expelling it; areas that use the vehicle as a landing-zone +// user are skipped when a vehicle is given. Objects are not null-checked; ties keep the first. +AIStrategicObject* AIStrategicObjectManager::getClosestObject(const Vec3& position, int equipment, + int vehicle, int side) const +{ + AIStrategicObject* best = 0; + float bestGravity = 0.0f; + const int group = static_cast(CommonSingletonServer::m_iaiSettings)->getVehicleGroup(equipment); + for (std::vector::const_iterator it = m_strategicObjects.begin(); + it != m_strategicObjects.end(); ++it) + { + if (!(*it)->isAllowedVehicleGroup(group) || (*it)->isExpelledUnit(equipment)) + continue; + if ((*it)->getType() == 0 && vehicle != -1 + && static_cast(*it)->isLandingZoneUser(vehicle)) + continue; + const float gravity = (*it)->gravity(position, side); + if (gravity > bestGravity) + { + bestGravity = gravity; + best = *it; + } + } + return best; +} + +// ELF 0x344E80, added by ai-w1-e-fire for BBPFireInfantery::createPlanInternal (0x265DA6; +// coord/ai-requests.md 2026-11-01): as getClosestObject(position, side), but only objects whose +// status for the side is 0 (`status == 0` when the flag is set, `status != 0` otherwise). The +// gravity is evaluated before the status test, as in the image. +AIStrategicObject* AIStrategicObjectManager::getClosestObject(const Vec3& position, int side, + bool statusZero) const +{ + AIStrategicObject* closest = 0; + float best = -1.0f; + for (std::vector::const_iterator it = m_strategicObjects.begin(); + it != m_strategicObjects.end(); ++it) + { + const double gravity = (*it)->gravity(position, side); + const bool zero = (*it)->getStatus(side) == 0; + if (zero != statusZero) + continue; + if (gravity > best) + { + best = static_cast(gravity); + closest = *it; + } + } + return closest; +} + +// ELF 0x346D40: the active-area cursor is the lookup result, end() when not found. +bool AIStrategicObjectManager::setActive(std::string name) +{ + m_activeArea = m_strategicAreaMap.find(name); + return m_activeArea != m_strategicAreaMap.end(); +} + // "Closest" is the greatest virtual gravity // starting at -1, not a distance calculation here. Strict comparison preserves // first-wins ties and ignores unordered results. Both ports reload the selected // pointer after gravity and the vector end on each iteration; neither guards nulls. +// ELF 0x344DF0. AIStrategicObject* AIStrategicObjectManager::getClosestObject( const Vec3& position, int side) const { @@ -44,6 +120,26 @@ AIStrategicObject* AIStrategicObjectManager::getClosestObject( // lea eax, [this+12] ; -> this+12 // so any non-zero selects the second list. Written literally. +// ELF 0x343340 (C2; C1 0x343380): both lists empty. +AIStrategicObjectManager::WPContainer::WPContainer() + : m_wayPointsA() + , m_wayPointsB() +{ +} + +// ELF 0x3433C0 (C2; C1 0x3434F0): member-wise vector copies. +AIStrategicObjectManager::WPContainer::WPContainer(const WPContainer& other) + : m_wayPointsA(other.m_wayPointsA) + , m_wayPointsB(other.m_wayPointsB) +{ +} + +// ELF 0x343660 (D2; D1 0x3436D0): the vectors go as members; the waypoints are not deleted here. +AIStrategicObjectManager::WPContainer::~WPContainer() +{ +} + +// ELF 0x343640. std::vector& AIStrategicObjectManager::WPContainer::getWayPoints(int type) { if (type) @@ -52,6 +148,7 @@ std::vector& AIStrategicObjectManager::WPContainer::getWayPoints(in return m_wayPointsA; } +// ELF 0x343620. const std::vector& AIStrategicObjectManager::WPContainer::getWayPoints(int type) const { if (type) @@ -60,23 +157,38 @@ const std::vector& AIStrategicObjectManager::WPContainer::getWayPoi return m_wayPointsA; } +// ELF 0x348E20: the container of the unordered area pair (min, max) - found unchecked, as in the +// image - and its list of the given type. +const std::vector& AIStrategicObjectManager::getWaypoints(int type, int a, int b) const +{ + const std::pair key(a < b ? a : b, a > b ? a : b); + return m_waypointMap.find(key)->second.getWayPoints(type); +} + +// ELF 0x348EB0: by the two areas' indices (+0xF0). +const std::vector& AIStrategicObjectManager::getWaypoints(int type, const AIStrategicArea* a, + const AIStrategicArea* b) const +{ + return getWaypoints(type, a->getIndex(), b->getIndex()); +} + // Initializes strategic-area collections and the active selection. AIStrategicObjectManager::AIStrategicObjectManager() - : m_areasInitialised(false) - , m_b84(false) + : m_debugEnabled(false) + , m_drawVehicleSearchRadii(false) , m_wayPointsToDrawFirst(-1) , m_wayPointsToDrawSecond(-1) { m_strategicObjects.resize(0); - m_objectsByCategory.resize(0); + m_objectsPerCategory.resize(0); if (!m_instance) m_instance = this; - m_activeArea = m_strategicAreas.end(); + m_activeArea = m_strategicAreaMap.end(); - m_categoryNames.resize(0); + m_categoryToNames.resize(0); } // Deletes owned areas, waypoints and bridges, and clears the singleton if it refers to this object. @@ -86,17 +198,17 @@ AIStrategicObjectManager::~AIStrategicObjectManager() if (m_instance == this) m_instance = 0; - for (std::map::iterator area = m_strategicAreas.begin(); - area != m_strategicAreas.end(); ) + for (std::map::iterator area = m_strategicAreaMap.begin(); + area != m_strategicAreaMap.end(); ) { if (area->second) delete area->second; - m_strategicAreas.erase(area++); + m_strategicAreaMap.erase(area++); } - for (std::map, WPContainer>::iterator entry = m_wayPoints.begin(); - entry != m_wayPoints.end(); ++entry) + for (std::map, WPContainer>::iterator entry = m_waypointMap.begin(); + entry != m_waypointMap.end(); ++entry) { std::vector& first = entry->second.getWayPoints(0); @@ -123,12 +235,13 @@ AIStrategicObjectManager::~AIStrategicObjectManager() // Initializes areas and waypoints after level loading, before pathfinding-map initialization. // Waypoint containers use an unordered area pair as their key. +// ELF 0x347CF0. void AIStrategicObjectManager::postLoadInitAreas() { WPContainer prototype; - for (std::map::iterator entry = m_strategicAreas.begin(); - entry != m_strategicAreas.end(); ++entry) + for (std::map::iterator entry = m_strategicAreaMap.begin(); + entry != m_strategicAreaMap.end(); ++entry) { AIStrategicArea* const area = entry->second; @@ -143,14 +256,14 @@ void AIStrategicObjectManager::postLoadInitAreas() const int low = (mine < other) ? mine : other; const int high = (mine >= other) ? mine : other; - m_wayPoints.insert( + m_waypointMap.insert( std::pair, WPContainer>(std::pair(low, high), prototype)); } } - for (std::map, WPContainer>::iterator entry = m_wayPoints.begin(); - entry != m_wayPoints.end(); ++entry) + for (std::map, WPContainer>::iterator entry = m_waypointMap.begin(); + entry != m_waypointMap.end(); ++entry) { std::vector& first = entry->second.getWayPoints(0); @@ -176,6 +289,7 @@ void AIStrategicObjectManager::postLoadInitAreas() // `_List_base::__clear`, which in this libstdc++ both frees the nodes and re-links the header, so // the source is `clear` and calling it twice (here and again from `~list`) is safe. +// ELF 0x349A10. void AIStrategicObjectManager::deleteBridges() { for (std::list::iterator i = m_bridgeSegments.begin(); @@ -189,11 +303,12 @@ void AIStrategicObjectManager::deleteBridges() // Tracks each announced AI-enabled bridge segment by object pointer. Lookup stops at // the first match; unknown objects are ignored by update and removal operations. +// ELF 0x3498E0. void AIStrategicObjectManager::createBridgeSegment(IAIObject* object) { BridgeSegment* const segment = new BridgeSegment; // zeroes the position only - +4 stays unset segment->m_object = object; - segment->m_destroyed = false; + segment->isDestroyed = false; // The position is zeroed again, as its own statement: the PE stores it a second time outside // the new-expression's null-checked constructor block, the ELF copies a zeroed 12-byte temporary. const Vec3 origin = { 0.0f, 0.0f, 0.0f }; @@ -202,6 +317,7 @@ void AIStrategicObjectManager::createBridgeSegment(IAIObject* object) } // The record is freed with a bare delete (a plain struct), then its node is erased. +// ELF 0x349970. void AIStrategicObjectManager::removeBridgeSegment(IAIObject* object) { for (std::list::iterator i = m_bridgeSegments.begin(); @@ -216,6 +332,7 @@ void AIStrategicObjectManager::removeBridgeSegment(IAIObject* object) } } +// ELF 0x349E00. void AIStrategicObjectManager::bridgeSegmentDestroyed(IAIObject* object, int value) { for (std::list::iterator i = m_bridgeSegments.begin(); @@ -223,14 +340,64 @@ void AIStrategicObjectManager::bridgeSegmentDestroyed(IAIObject* object, int val { if ((*i)->m_object == object) { - (*i)->m_destroyed = true; + (*i)->isDestroyed = true; (*i)->m_i4 = value; return; } } } +// ELF 0x349ED0 (listing). Every segment's information position is read first (the object's +// information for side 1, IAIObject +0xB8, through the information manager; Information +0x30), +// including for intact segments, and neither lookup is null-tested. A destroyed segment counts +// unless it was destroyed by a human of `side` (the destroying player's id is +4; +// IAIPlayerFactory +0x20, getSide +0x6C, getIsAIPlayer +0x88) or, with no such player, a human of +// `side` is in the game (SquadManager::haveHumanPlayerOnOwnSide) - both only when no repair was +// requested. The nearest by squared distance from `from` to the information position wins: its +// record position and that squared distance are written out and its object returned; 0 for none. +IAIObject* AIStrategicObjectManager::getClosestDestroyedBridgeSegment(Vec3 from, bool repairRequested, int side, + Vec3& position, float& distance) +{ + IAIObject* closest = 0; + float best = 3.4028235e38f; + Vec3 segmentPosition = { 0.0f, 0.0f, 0.0f }; + IAIPlayerFactory* const players = static_cast(CommonSingletonServer::m_iaiPlayerFactory); + for (std::list::iterator i = m_bridgeSegments.begin(); i != m_bridgeSegments.end(); ++i) + { + BridgeSegment* const segment = *i; + segmentPosition = informationManager->getInformation(segment->m_object->getInformation(1))->getPosition(); + if (!segment->isDestroyed) + continue; + bool ownHuman = false; + IAIPlayer* const destroyer = players->getPlayerFromId(segment->m_i4); // +0x20 + if (destroyer) + { + if (destroyer->getSide() == side) // +0x6C + ownHuman = !destroyer->getIsAIPlayer(); // +0x88 + } + else if (SquadManager::m_instance->haveHumanPlayerOnOwnSide(side)) + { + ownHuman = true; + } + if (!repairRequested && ownHuman) + continue; + const float dx = segmentPosition.x - from.x; + const float dy = segmentPosition.y - from.y; + const float dz = segmentPosition.z - from.z; + const float d = dx * dx + dy * dy + dz * dz; + if (best > d) + { + best = d; + closest = segment->m_object; + distance = d; + position = segment->m_position; + } + } + return closest; +} + // Only the flag is cleared; +4 keeps the value the destruction wrote. +// ELF 0x349E70. void AIStrategicObjectManager::bridgeSegmentRepaired(IAIObject* object) { for (std::list::iterator i = m_bridgeSegments.begin(); @@ -238,40 +405,127 @@ void AIStrategicObjectManager::bridgeSegmentRepaired(IAIObject* object) { if ((*i)->m_object == object) { - (*i)->m_destroyed = false; + (*i)->isDestroyed = false; return; } } } -// [FRONTIER] Reset operations require the remaining strategic-area lifecycle behavior. -// [RETIRE-WHEN: aidll-02-skeleton] Implement and validate area resets and collection rebuilding. +// ELF 0x345150 (from BF2AI::clear): clears the initialised flag, deletes every named area (slot 1) +// while erasing it node by node, clears the area names, points the active area at end(), empties +// the object list, the category lists and the category names (each through resize(0), the +// `size == 0 ? _M_fill_insert : erase` pair), then erases the category map node by node. The way +// points and bridge segments are left alone. Always true. bool AIStrategicObjectManager::reset() { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicObjectManager::reset"); + m_debugEnabled = false; + for (std::map::iterator area = m_strategicAreaMap.begin(); + area != m_strategicAreaMap.end();) + { + if (area->second) + delete area->second; + m_strategicAreaMap.erase(area++); + } + if (!m_areaNames.empty()) + m_areaNames.clear(); + m_activeArea = m_strategicAreaMap.end(); + m_strategicObjects.resize(0, 0); + m_objectsPerCategory.resize(0, std::vector()); + m_categoryToNames.resize(0, std::string()); + for (std::map::iterator category = m_namesToCategory.begin(); category != m_namesToCategory.end();) + m_namesToCategory.erase(category++); + return true; } +// ELF 0x345520: clears the initialised flag and resets every area's status; always true. bool AIStrategicObjectManager::resetAreas() { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicObjectManager::resetAreas"); + m_debugEnabled = false; + for (std::map::iterator it = m_strategicAreaMap.begin(); + it != m_strategicAreaMap.end(); ++it) + it->second->resetStatus(); + return true; +} + +// ELF 0x349A80. Every segment is marked intact again and gets its direction (+0x0C) back: the +// unit vector to the first other segment whose squared distance d lies in (0.01, (2r + 5)^2), +// r being this segment's physical radius (the bound is stored as a float before the compare); +// without such a neighbour, the object's transformation row 2 (+0x20). A neighbour distance is +// kept as is when |d - 1| < FLT_EPSILON and becomes zero when |d| < FLT_EPSILON. +// [CHOSEN, not recovered] x87 extended intermediates are carried in double here. +void AIStrategicObjectManager::resetBridges() +{ + for (std::list::iterator it = m_bridgeSegments.begin(); it != m_bridgeSegments.end(); ++it) + { + BridgeSegment* const segment = *it; + segment->isDestroyed = false; + Information* const information = + informationManager->getInformation(segment->m_object->getHandle(1)); + const Vec3 position = information->getPosition(); + const double radius = information->getPhysical()->getRadius(); + const float bound = static_cast((radius + radius + 5.0f) * (radius + radius + 5.0f)); + bool found = false; + for (std::list::iterator other = m_bridgeSegments.begin(); + other != m_bridgeSegments.end(); ++other) + { + Information* const neighbour = + informationManager->getInformation((*other)->m_object->getHandle(1)); + const Vec3& q = neighbour->getPosition(); + const double dx = static_cast(q.x) - position.x; + const double dy = static_cast(q.y) - position.y; + const double dz = static_cast(q.z) - position.z; + Vec3 diff; + diff.x = static_cast(dx); + diff.y = static_cast(dy); + diff.z = static_cast(dz); + const double distanceSq = dx * dx + dy * dy + dz * dz; + if (!(distanceSq > 0.01f) || !(bound > distanceSq)) + continue; + found = true; + if (!(std::fabs(distanceSq - 1.0f) < 1.1920928955078125e-07f)) + { + if (!(std::fabs(distanceSq) < 1.1920928955078125e-07f)) + { + const double scale = 1.0f / std::sqrt(distanceSq); + diff.x = static_cast(diff.x * scale); + diff.y = static_cast(diff.y * scale); + diff.z = static_cast(diff.z * scale); + } + else + diff.x = diff.y = diff.z = 0.0f; + } + segment->m_position = diff; + break; + } + if (!found) + { + const Mat4& transformation = segment->m_object->getTransformation(); + segment->m_position.x = transformation.m[8]; + segment->m_position.y = transformation.m[9]; + segment->m_position.z = transformation.m[10]; + } + } } // The accessors that are two or three instructions. Each is transcribed from its own body; none of // them needs a type this file does not have. // `BF2AI::clear` destroys the object through this rather than through the // static, which is the only reason it exists. +// ELF 0x3448F0. AIStrategicObjectManager* AIStrategicObjectManager::getInstance() { return m_instance; } // - `return (char *)this + 4;` +// ELF 0x344AD0. const std::vector& AIStrategicObjectManager::getStrategicObjects() const { return m_strategicObjects; } // - the byte difference shifted right by two, i.e. the element count. +// ELF 0x344AE0. int AIStrategicObjectManager::getNumberOfStrategicObjects() const { return (int)m_strategicObjects.size(); @@ -281,37 +535,42 @@ int AIStrategicObjectManager::getNumberOfStrategicObjects() const const std::vector& AIStrategicObjectManager::getStrategicObjectsOfCategory(int category) const { - return m_objectsByCategory[category]; + return m_objectsPerCategory[category]; } // - same shape, four bytes per `std::string`, again unchecked. +// ELF 0x347910. const std::string& AIStrategicObjectManager::getCategoryName(int category) const { - return m_categoryNames[category]; + return m_categoryToNames[category]; } +// ELF 0x345610. int AIStrategicObjectManager::getNumberOfCategories() { - return (int)m_categoryNames.size(); + return (int)m_categoryToNames.size(); } // - `return (char *)this + 32;` +// ELF 0x3476A0. const std::map& AIStrategicObjectManager::getStrategicAreas() const { - return m_strategicAreas; + return m_strategicAreaMap; } // Returns null while no area is active - `m_activeArea` starts at `end` and // the constructor is the only thing that puts it there. +// ELF 0x345630. AIStrategicArea* AIStrategicObjectManager::getActiveArea() { - if (m_activeArea != m_strategicAreas.end()) + if (m_activeArea != m_strategicAreaMap.end()) return m_activeArea->second; return 0; } // This one checks both ends, and returns null rather than clamping. +// ELF 0x344910. AIStrategicObject* AIStrategicObjectManager::getStrategicObject(int index) const { if (index < 0) @@ -323,28 +582,59 @@ AIStrategicObject* AIStrategicObjectManager::getStrategicObject(int index) const return m_strategicObjects[index]; } +// ELF 0x344940 (added by air/s2 for GuardPosition::update): the named area, null when unknown. +AIStrategicObject* AIStrategicObjectManager::getStrategicObject(const std::string& name) const +{ + const std::map::const_iterator it = m_strategicAreaMap.find(name); + if (it != m_strategicAreaMap.end()) + return it->second; + return 0; +} + +// ELF 0x3449E0 (added by ai-bot for WPMoveTo::getUrgency): the object at `index` when its type +// (vtable +8, getType) is 0 - an area - else null; out-of-range indices give null. +AIStrategicArea* AIStrategicObjectManager::getStrategicArea(int index) const +{ + if (index < 0 || index >= (int)m_strategicObjects.size()) + return 0; + if (m_strategicObjects[index]->getType() != 0) + return 0; + return static_cast(m_strategicObjects[index]); +} + // Disables waypoint drawing by clearing the first key component; leaves the second unchanged. +// ELF 0x349390. void AIStrategicObjectManager::clearWaypointToDraw() { m_wayPointsToDrawFirst = -1; } -// [FRONTIER] Waypoint drawing cleanup remains unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding AIStrategicObjectManager operation. +// ELF 0x349040: every waypoint container (+0x58), type 0 then type 1, undraws each waypoint. void AIStrategicObjectManager::undrawWayPoints() const { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicObjectManager::undrawWayPoints"); + for (std::map, WPContainer>::const_iterator it = m_waypointMap.begin(); + it != m_waypointMap.end(); ++it) + { + for (int type = 0; type < 2; ++type) + { + const std::vector& points = it->second.getWayPoints(type); + for (std::vector::const_iterator wp = points.begin(); wp != points.end(); ++wp) + (*wp)->undraw(); + } + } } // Returns the category id for an existing name. The caller must ensure that exact // name exists; merely having a nonempty category map is insufficient. +// ELF 0x347930. int AIStrategicObjectManager::getCategoryFromName(const std::string& name) const { - return m_categories.find(name)->second; + return m_namesToCategory.find(name)->second; } // Adds an object to the category table and assigns its index. The object and category must be valid. // Other category rows retain null entries at that index. +// ELF 0x344B20. void AIStrategicObjectManager::addStrategicObject(AIStrategicObject* object) { const int index = (int)m_strategicObjects.size(); @@ -353,14 +643,14 @@ void AIStrategicObjectManager::addStrategicObject(AIStrategicObject* object) m_strategicObjects[index] = object; object->m_index = index; - for (int category = 0; category < (int)m_objectsByCategory.size(); ++category) + for (int category = 0; category < (int)m_objectsPerCategory.size(); ++category) { - m_objectsByCategory[category].resize(index + 1); + m_objectsPerCategory[category].resize(index + 1); if (category == object->m_category) - m_objectsByCategory[category][index] = object; + m_objectsPerCategory[category][index] = object; else - m_objectsByCategory[category][index] = 0; + m_objectsPerCategory[category][index] = 0; } if (AIRenderUtil::m_instance) @@ -368,10 +658,11 @@ void AIStrategicObjectManager::addStrategicObject(AIStrategicObject* object) } // Initializes areas with explicit bounds. Control-point areas wait for postLoadInit(). +// ELF 0x345590. void AIStrategicObjectManager::initAreas() { - for (std::map::iterator i = m_strategicAreas.begin(); - i != m_strategicAreas.end(); ++i) + for (std::map::iterator i = m_strategicAreaMap.begin(); + i != m_strategicAreaMap.end(); ++i) { if (!i->second->m_fromControlPoint) i->second->init(); @@ -380,21 +671,22 @@ void AIStrategicObjectManager::initAreas() // Creates a strategic area from a named control point and selects it. // Returns false and clears the active selection when creation is refused. +// ELF 0x345C40. bool AIStrategicObjectManager::createFromControlPoint(const std::string& name, unsigned controlPointId, float radius, const std::string& category) { - if (m_strategicAreas.find(name) != m_strategicAreas.end()) + if (m_strategicAreaMap.find(name) != m_strategicAreaMap.end()) { - m_activeArea = m_strategicAreas.end(); + m_activeArea = m_strategicAreaMap.end(); return false; } AIStrategicArea* const area = checkPointer(new AIStrategicArea(name, controlPointId, radius)); if (!area) { - m_activeArea = m_strategicAreas.end(); + m_activeArea = m_strategicAreaMap.end(); return false; } @@ -405,41 +697,630 @@ bool AIStrategicObjectManager::createFromControlPoint(const std::string& name, AIStrategicObjectManager::getInstance()->addStrategicObject(area); - m_strategicAreas[name] = area; + m_strategicAreaMap[name] = area; m_areaNames[area] = name; - m_activeArea = m_strategicAreas.find(name); + m_activeArea = m_strategicAreaMap.find(name); return true; } -// Console bindings for strategic-area configuration. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. +// ELF 0x344990: bounded by the object count, not by the category row. Unchecked category. +AIStrategicObject* AIStrategicObjectManager::getStrategicObjectOfCategory(int index, int category) const +{ + if (index < 0 || index >= static_cast(m_strategicObjects.size())) + return 0; + return m_objectsPerCategory[category][index]; +} -namespace { +// ELF 0x344A40: as getStrategicObjectOfCategory, but only an area (getType() == 0). +AIStrategicArea* AIStrategicObjectManager::getStrategicAreaOfCategory(int index, int category) const +{ + if (index < 0 || index >= static_cast(m_strategicObjects.size())) + return 0; + if (!m_objectsPerCategory[category][index] || m_objectsPerCategory[category][index]->getType() != 0) + return 0; + return static_cast(m_objectsPerCategory[category][index]); +} + +// ELF 0x344D00: clears the object's category slot (when its category is in range) and erases the +// first matching entry of the object list. Later objects keep their stored indices. +AIStrategicObject* AIStrategicObjectManager::removeStrategicObject(int index) +{ + if (index < 0 || index >= static_cast(m_strategicObjects.size())) + return 0; + + AIStrategicObject* const object = m_strategicObjects[index]; + const int category = object->m_category; + if (category >= 0 && category < static_cast(m_objectsPerCategory.size())) + m_objectsPerCategory[category][index] = 0; + + for (std::vector::iterator it = m_strategicObjects.begin(); + it != m_strategicObjects.end(); ++it) + { + if (*it == object) + { + m_strategicObjects.erase(it); + break; + } + } + return object; +} + +// ELF 0x345020: getClosestObject's vehicle-group form over one category row (0 for a category +// out of range). The vehicle group is queried before the range test. +AIStrategicObject* AIStrategicObjectManager::getClosestObjectinCategory(const Vec3& position, int side, + int category, int equipment, + int vehicle) const +{ + AIStrategicObject* best = 0; + float bestGravity = 0.0f; + const int group = + static_cast(CommonSingletonServer::m_iaiSettings)->getVehicleGroup(equipment); + if (category < 0 || category >= static_cast(m_objectsPerCategory.size())) + return best; + + const std::vector& objects = m_objectsPerCategory[category]; + for (std::vector::const_iterator it = objects.begin(); it != objects.end(); ++it) + { + if (!(*it)->isAllowedVehicleGroup(group) || (*it)->isExpelledUnit(equipment)) + continue; + if ((*it)->getType() == 0 && vehicle != -1 + && static_cast(*it)->isLandingZoneUser(vehicle)) + continue; + const float gravity = (*it)->gravity(position, side); + if (gravity > bestGravity) + { + bestGravity = gravity; + best = *it; + } + } + return best; +} + +// ELF 0x345650: unchecked active area. +void AIStrategicObjectManager::setFlankPosition(Vec3 first, Vec3 second) +{ + m_activeArea->second->addFlankPosition(first, second); +} + +// ELF 0x3456D0: createFromControlPoint's sequence around the bounded area constructor. +bool AIStrategicObjectManager::create(std::string name, Vec2 topLeft, Vec2 centre, float height, + float radius, const std::string& category) +{ + if (m_strategicAreaMap.find(name) != m_strategicAreaMap.end()) + { + m_activeArea = m_strategicAreaMap.end(); + return false; + } + + AIStrategicArea* const area = + checkPointer(new AIStrategicArea(name, topLeft, centre, height, radius)); + if (!area) + { + m_activeArea = m_strategicAreaMap.end(); + return false; + } + + if (getNumberOfCategories() <= 0) + area->m_category = 0; + else + area->m_category = getCategoryFromName(category); + + AIStrategicObjectManager::getInstance()->addStrategicObject(area); + + m_strategicAreaMap[name] = area; + m_areaNames[area] = name; + m_activeArea = m_strategicAreaMap.find(name); + return true; +} + +// ELF 0x3461A0: unlinks the active area from its neighbours, drops both name entries, its debug +// rendering and its object slot, then deletes it. AIRenderUtil::m_instance is not null-checked. +bool AIStrategicObjectManager::removeActive() +{ + if (m_activeArea == m_strategicAreaMap.end()) + return false; + AIStrategicArea* area = m_activeArea->second; + if (!area) + return false; + + for (std::vector::iterator it = area->m_neighbours.begin(); + it != area->m_neighbours.end(); ++it) + static_cast(*it)->removeNeighbour(area); + + std::map::iterator name = m_areaNames.find(area); + if (name != m_areaNames.end()) + m_areaNames.erase(name); + m_strategicAreaMap.erase(m_activeArea); + m_activeArea = m_strategicAreaMap.end(); + + AIRenderUtil::m_instance->unrenderStrategicArea(area); + AIRenderUtil::m_instance->updateNumberOfStrategicAreas(); + removeStrategicObject(area->m_index); + delete area; + return true; +} + +// ELF 0x3463B0: the active area (unchecked) gains the named area as a neighbour and the named +// area gains the active one as a neighbouring object. +bool AIStrategicObjectManager::addNeighbour(std::string name) +{ + std::map::iterator it = m_strategicAreaMap.find(name); + if (it == m_strategicAreaMap.end()) + return false; + if (m_activeArea->second->m_i400 != it->second->m_i400) + return false; + m_activeArea->second->addNeighbour(it->second); + it->second->addNeighbouringObject(m_activeArea->second); + return true; +} + +// ELF 0x346460: both directions, in the image's call order. +bool AIStrategicObjectManager::addTwoWayNeighbour(std::string first, std::string second) +{ + std::map::iterator a = m_strategicAreaMap.find(first); + if (a == m_strategicAreaMap.end()) + return false; + std::map::iterator b = m_strategicAreaMap.find(second); + if (b == m_strategicAreaMap.end()) + return false; + if (a->second->m_i400 != b->second->m_i400) + return false; + a->second->addNeighbour(b->second); + b->second->addNeighbouringObject(a->second); + b->second->addNeighbour(a->second); + a->second->addNeighbouringObject(b->second); + return true; +} + +// ELF 0x346590. +void AIStrategicObjectManager::removeAllNeighbours() +{ + if (m_activeArea != m_strategicAreaMap.end()) + m_activeArea->second->removeAllNeighbours(); +} + +// ELF 0x3465D0: the active area's neighbour names, each followed by a newline ("" without an +// active area). The neighbour list is copied first; the name lookups are unchecked. +std::string AIStrategicObjectManager::getNeighbours() +{ + if (m_activeArea == m_strategicAreaMap.end()) + return ""; + + const std::vector neighbours = m_activeArea->second->m_neighbours; + std::string names; + for (std::vector::const_iterator it = neighbours.begin(); + it != neighbours.end(); ++it) + { + names.append(m_areaNames.find(static_cast(*it))->second); + names.append("\n"); + } + return names; +} + +// ELF 0x3467B0. +int AIStrategicObjectManager::addObjectTypeFlag(AIStrategicObject::StrategicObjectType type) +{ + if (m_activeArea == m_strategicAreaMap.end() || type == 27) + return -1; + return m_activeArea->second->addObjectTypeFlag(type); +} + +// ELF 0x346800. Shipped defect, preserved: the bit is toggled (xor), not cleared. +int AIStrategicObjectManager::removeObjectTypeFlag(AIStrategicObject::StrategicObjectType type) +{ + if (m_activeArea == m_strategicAreaMap.end() || type == 27) + return -1; + return m_activeArea->second->m_objectTypeFlags ^= 1 << type; +} + +// ELF 0x346850. +int AIStrategicObjectManager::setObjectTypeFlags(int flags) +{ + if (m_activeArea == m_strategicAreaMap.end()) + return -1; + return m_activeArea->second->setObjectTypeFlags(flags); +} + +// ELF 0x3468A0: through the virtual getter (slot 18). +int AIStrategicObjectManager::getObjectTypeFlags() +{ + if (m_activeArea == m_strategicAreaMap.end()) + return -1; + return m_activeArea->second->getObjectTypeFlags(); +} + +// ELF 0x3468D0. +void AIStrategicObjectManager::removeAllObjectTypeFlags() +{ + if (m_activeArea != m_strategicAreaMap.end()) + m_activeArea->second->m_objectTypeFlags = 0; +} + +// ELF 0x346900: " " per line for the types 1..20. +std::string AIStrategicObjectManager::getObjectTypeFlagMapping() const +{ + std::stringstream stream; + for (unsigned int type = 1; type < 21; ++type) + stream << type << " " << static_cast(type) << std::endl; + return stream.str(); +} + +// ELF 0x346DB0: the active area's name, "" without one. +std::string AIStrategicObjectManager::getActive() const +{ + if (m_activeArea == m_strategicAreaMap.end()) + return ""; + return m_activeArea->first; +} + +// ELF 0x346E20: every area name, one per line. +std::string AIStrategicObjectManager::list() const +{ + std::stringstream stream; + for (std::map::const_iterator it = m_strategicAreaMap.begin(); + it != m_strategicAreaMap.end(); ++it) + { + const std::string name = it->first; + stream << name << std::endl; + } + return stream.str(); +} + +// ELF 0x3471A0: false without an active area or pathfinding, or for an unknown map name. +bool AIStrategicObjectManager::setOrderPosition(std::string map, const Vec3& position) +{ + if (m_activeArea == m_strategicAreaMap.end() || !IAIPathfinding::instance) + return false; + const int id = IAIPathfinding::instance->getMapIdFromName(map); + if (id == -1) + return false; + return m_activeArea->second->setOrderPos(id, position); +} + +// ELF 0x347240: the active area's order position on the named map; zero otherwise. +Vec3 AIStrategicObjectManager::getOrderPosition(std::string map) +{ + Vec3 position; + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; + if (m_activeArea == m_strategicAreaMap.end() || !IAIPathfinding::instance) + return position; + const int id = IAIPathfinding::instance->getMapIdFromName(map); + if (id == -1) + return position; + return m_activeArea->second->getOrderPos(id, 1); +} + +// ELF 0x347300: " x/y/z" per pathfinding map for the active area; "" without an +// active area or pathfinding. The image inlines the x/y/z stream operator. +std::string AIStrategicObjectManager::listOrderPositions() +{ + if (m_activeArea == m_strategicAreaMap.end() || !IAIPathfinding::instance) + return ""; + + std::ostringstream stream; + for (unsigned int map = 0; map < static_cast(IAIPathfinding::instance->getNumberOfMaps()); + ++map) + { + const std::string& name = IAIPathfinding::instance->getMapNameFromId(map); + const Vec3 position = m_activeArea->second->getOrderPos(map, 1); + stream << map << " " << name << " " << position.x << '/' << position.y << '/' << position.z + << "\n"; + } + return stream.str(); +} + +// ELF 0x3476B0: the area names joined by newlines. +std::string AIStrategicObjectManager::getStrategicAreaNames() +{ + std::string names; + for (std::map::const_iterator it = m_strategicAreaMap.begin(); + it != m_strategicAreaMap.end(); ++it) + names = names.empty() ? it->first : names + "\n" + it->first; + return names; +} + +// ELF 0x3478D0: the active area's side-1 position (slot 3); unchecked active area. +Vec2 AIStrategicObjectManager::getPosition() const +{ + return m_activeArea->second->getPosition(1); +} + +// ELF 0x347980: a new last category, its name index and an object row as long as the object list. +void AIStrategicObjectManager::createNewCategory(const std::string& name) +{ + const int index = static_cast(m_categoryToNames.size()); + m_categoryToNames.resize(index + 1); + m_categoryToNames[index] = name; + m_namesToCategory.insert(std::make_pair(name, index)); + m_objectsPerCategory.resize(index + 1); + m_objectsPerCategory[index].resize(m_strategicObjects.size()); +} + +// ELF 0x347C80: false for an unknown area name. +bool AIStrategicObjectManager::isInside(const std::string& name, const Vec2& position) +{ + std::map::iterator it = m_strategicAreaMap.find(name); + if (it == m_strategicAreaMap.end()) + return false; + return it->second->isInside(position); +} + +// ELF 0x348020: a waypoint on the named map between two different areas, keyed by their +// (lower, higher) indices; the container is created on first use. +void AIStrategicObjectManager::addWayPoint(const Vec3& position, const std::string& map, + const std::string& first, const std::string& second) +{ + std::map::iterator a = m_strategicAreaMap.find(first); + if (a == m_strategicAreaMap.end()) + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp", 1144, "") + << first << " is not the name of a valid strategic area."; + return; + } + std::map::iterator b = m_strategicAreaMap.find(second); + if (b == m_strategicAreaMap.end()) + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp", 1151, "") + << second << " is not the name of a valid strategic area."; + return; + } + + AIStrategicArea* low = b->second; + AIStrategicArea* high = a->second; + if (a->second->m_index < b->second->m_index) + { + low = a->second; + high = b->second; + } + if (low == high) + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp", 1171, "") + << "Must have two different strategic areas when adding waypoints."; + return; + } + + WPContainer container; + std::map, WPContainer>::iterator it = + m_waypointMap.insert(std::make_pair(std::make_pair(low->m_index, high->m_index), container)).first; + const int id = IAIPathfinding::instance->getMapIdFromName(map); + std::vector& points = it->second.getWayPoints(id); + points.push_back(checkPointer(new SAWayPoint(position, id))); +} + +// ELF 0x348630: deletes the waypoint of the pair's list closest to `position` within a squared +// distance of 10; false when none is that close or a name is unknown. Same-area pairs are not +// refused here, and the container lookup is unchecked. +bool AIStrategicObjectManager::removeWayPoint(const Vec3& position, const std::string& map, + const std::string& first, const std::string& second) +{ + std::map::iterator a = m_strategicAreaMap.find(first); + if (a == m_strategicAreaMap.end()) + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp", 1191, "") + << first << " is not the name of a valid strategic area."; + return false; + } + std::map::iterator b = m_strategicAreaMap.find(second); + if (b == m_strategicAreaMap.end()) + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp", 1198, "") + << second << " is not the name of a valid strategic area."; + return false; + } + + AIStrategicArea* low = b->second; + AIStrategicArea* high = a->second; + if (a->second->m_index < b->second->m_index) + { + low = a->second; + high = b->second; + } + + const std::pair key(low->m_index, high->m_index); + std::map, WPContainer>::iterator it = m_waypointMap.find(key); + const int id = IAIPathfinding::instance->getMapIdFromName(map); + std::vector& points = it->second.getWayPoints(id); + + float best = 10.0f; + std::vector::iterator closest = points.end(); + for (std::vector::iterator wp = points.begin(); wp != points.end(); ++wp) + { + const Vec3& at = (*wp)->getPosition(); + const float dx = at.x - position.x; + const float dy = at.y - position.y; + const float dz = at.z - position.z; + const float distance = dx * dx + dy * dy + dz * dz; + if (distance < best) + { + closest = wp; + best = distance; + } + } + if (closest == points.end()) + return false; + + delete *closest; + points.erase(closest); + return true; +} + +// ELF 0x348A90: deletes every waypoint of the pair's list on the named map and empties it +// (resize(0)). The container lookup is unchecked. +void AIStrategicObjectManager::clearWayPoints(const std::string& map, const std::string& first, + const std::string& second) +{ + std::map::iterator a = m_strategicAreaMap.find(first); + if (a == m_strategicAreaMap.end()) + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp", 1253, "") + << first << " is not the name of a valid strategic area."; + return; + } + std::map::iterator b = m_strategicAreaMap.find(second); + if (b == m_strategicAreaMap.end()) + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp", 1260, "") + << second << " is not the name of a valid strategic area."; + return; + } + + AIStrategicArea* low = b->second; + AIStrategicArea* high = a->second; + if (a->second->m_index < b->second->m_index) + { + low = a->second; + high = b->second; + } + + const std::pair key(low->m_index, high->m_index); + std::map, WPContainer>::iterator it = m_waypointMap.find(key); + const int id = IAIPathfinding::instance->getMapIdFromName(map); + std::vector& points = it->second.getWayPoints(id); + for (std::vector::iterator wp = points.begin(); wp != points.end(); ++wp) + delete *wp; + points.resize(0); +} + +// ELF 0x348F00: the selected pair's waypoints (lookup unchecked), or every container's when either +// half of the selection is -1; type 0 then type 1. +void AIStrategicObjectManager::drawWayPoints() const +{ + if (m_wayPointsToDrawFirst != -1 && m_wayPointsToDrawSecond != -1) + { + const std::pair key(m_wayPointsToDrawFirst, m_wayPointsToDrawSecond); + const WPContainer& container = m_waypointMap.find(key)->second; + const std::vector& infantry = container.getWayPoints(0); + for (std::vector::const_iterator wp = infantry.begin(); wp != infantry.end(); ++wp) + (*wp)->draw(); + const std::vector& vehicles = container.getWayPoints(1); + for (std::vector::const_iterator wp = vehicles.begin(); wp != vehicles.end(); ++wp) + (*wp)->draw(); + return; + } -const char* const kAiStrategicAreaConsoleTag = "aiStrategicArea"; + for (std::map, WPContainer>::const_iterator it = m_waypointMap.begin(); + it != m_waypointMap.end(); ++it) + { + const std::vector& infantry = it->second.getWayPoints(0); + for (std::vector::const_iterator wp = infantry.begin(); wp != infantry.end(); ++wp) + (*wp)->draw(); + const std::vector& vehicles = it->second.getWayPoints(1); + for (std::vector::const_iterator wp = vehicles.begin(); wp != vehicles.end(); ++wp) + (*wp)->draw(); + } +} -void consoleAiStrategicAreaCreateFromControlPoint(const std::string& name, - unsigned int controlPointId, - float radius) +// ELF 0x349100: selects the pair (lower, higher index) whose waypoints drawWayPoints shows. +void AIStrategicObjectManager::setWayPointsToDraw(const std::string& first, const std::string& second) { - // No null check on the singleton, matching every other console forwarder in this DLL: - // `BF2AI::init` builds the manager as step 17 during `initDll`, and `GameLogic::load` runs - // `StrategicAreas.ai` long afterwards. The `isObjectActive` test below is the real guard. - AIStrategicObjectManager::getInstance()->createFromControlPoint( - name, controlPointId, radius, std::string()); // [CHOSEN] empty category - see above + std::map::iterator a = m_strategicAreaMap.find(first); + if (a == m_strategicAreaMap.end()) + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp", 1371, "") + << first << " is not the name of a valid strategic area."; + return; + } + std::map::iterator b = m_strategicAreaMap.find(second); + if (b == m_strategicAreaMap.end()) + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp", 1378, "") + << second << " is not the name of a valid strategic area."; + return; + } + + AIStrategicArea* low = b->second; + AIStrategicArea* high = a->second; + if (a->second->m_index < b->second->m_index) + { + low = a->second; + high = b->second; + } + m_wayPointsToDrawFirst = low->m_index; + m_wayPointsToDrawSecond = high->m_index; +} + +namespace { + +// ELF 0x3493B0: whether the decimal layer is one of the "|"-separated entries. strtok runs on +// the copy's buffer. +bool checkLayerStrList(const std::string& list, int layer) +{ + std::string copy = list; + const std::string wanted = formatString("%d", layer); + char* token = std::strtok(const_cast(copy.c_str()), "|"); + while (token) + { + if (std::string(token) == wanted) + return true; + token = std::strtok(0, "|"); + } + return false; } -} // anonymous namespace +} // namespace -BF2_CONSOLE_OBJECT("aiStrategicArea", 2, 0) -BF2_CONSOLE_METHOD_3(createFromControlPoint, consoleAiStrategicAreaCreateFromControlPoint, - AIStrategicObjectManager::getInstance() != 0, - std::string, unsigned int, float, kAiStrategicAreaConsoleTag) +// ELF 0x349610. The image inlines the x/y/z stream operator. +void AIStrategicObjectManager::streamWaypoints(std::ostringstream& out, + const std::string& excludedLayers) const +{ + for (std::map, WPContainer>::const_iterator it = m_waypointMap.begin(); + it != m_waypointMap.end(); ++it) + { + AIStrategicArea* const first = getStrategicArea(it->first.first); + if (!excludedLayers.empty() && checkLayerStrList(excludedLayers, first->m_i400)) + continue; + AIStrategicArea* const second = getStrategicArea(it->first.second); + + const std::vector& infantry = it->second.getWayPoints(0); + for (std::vector::const_iterator wp = infantry.begin(); wp != infantry.end(); ++wp) + { + const Vec3& at = (*wp)->getPosition(); + out << "aiStrategicArea.addWayPoint " << at.x << '/' << at.y << '/' << at.z + << " Infantry " << first->m_name << " " << second->m_name << std::endl; + } + const std::vector& vehicles = it->second.getWayPoints(1); + for (std::vector::const_iterator wp = vehicles.begin(); wp != vehicles.end(); ++wp) + { + const Vec3& at = (*wp)->getPosition(); + out << "aiStrategicArea.addWayPoint " << at.x << '/' << at.y << '/' << at.z + << " Vehicle " << first->m_name << " " << second->m_name << std::endl; + } + } +} -// Handed to the console registry by AIModule::init, beside the `ai` and `aiSettings` lists. -ConsoleObjectList& aiStrategicAreaConsoleObjects() +// ELF 0x34A150: queries every area's order position on every map and discards them (the copy of +// the area map and the loop survive in the image; the checks they fed are compiled out). +void AIStrategicObjectManager::checkAllOrderPositions() const { - return consoleBindingList(kAiStrategicAreaConsoleTag); + IAIPathfinding* const pathfinding = IAIPathfinding::instance; + const std::map areas = getStrategicAreas(); + for (std::map::const_iterator it = areas.begin(); it != areas.end(); + ++it) + { + AIStrategicArea* const area = it->second; + const int maps = pathfinding->getNumberOfMaps(); + for (int map = 0; map < maps; ++map) + area->getOrderPos(map, 1); + } +} + +// ELF 0x34A350: walks every container's two lists without effect (the image keeps the empty +// loops; whatever they checked is compiled out). +void AIStrategicObjectManager::checkAllWayPoints() const +{ + for (std::map, WPContainer>::const_iterator it = m_waypointMap.begin(); + it != m_waypointMap.end(); ++it) + { + for (int type = 0; type < 2; ++type) + { + const std::vector& points = it->second.getWayPoints(type); + for (std::vector::const_iterator wp = points.begin(); wp != points.end(); ++wp) + { + } + } + } } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.h index e18fab36b..437cd839c 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.h @@ -5,6 +5,7 @@ #include #include +#include #include #include #include @@ -13,6 +14,7 @@ // `dice::hfe::Math::Vec2/Vec3`, not classes in `dice::hfe`, so a local `struct Vec3;` is a // redefinition with a different basic type (C2371). The header has to come in. #include "../../../../Math/Vec3.h" +#include "AIStrategicObject.h" // StrategicObjectType namespace dice { namespace hfe { @@ -30,6 +32,10 @@ class AIStrategicObjectManager class WPContainer { public: + WPContainer(); // ELF 0x343340 (C2; C1 0x343380) + WPContainer(const WPContainer& other); // ELF 0x3433C0 (C2; C1 0x3434F0) + ~WPContainer(); // ELF 0x343660 (D2; D1 0x3436D0) + std::vector& getWayPoints(int type); const std::vector& getWayPoints(int type) const; @@ -49,7 +55,7 @@ class AIStrategicObjectManager m_position.z = 0.0f; } - /* +0 */ bool m_destroyed; // 0 at creation; `bridgeSegmentDestroyed` sets it to 1 + /* +0 */ bool isDestroyed; // 0 at creation; `bridgeSegmentDestroyed` sets it to 1 // name: AIDLL_r assert "bridge->isDestroyed" (0x10086E40; +0) /* +4 */ int m_i4; // [UNRESOLVED] - written only by `bridgeSegmentDestroyed` /* +8 */ IAIObject* m_object; // the search key for all three of the methods above /* +12 */ Vec3 m_position; // [INFERRED] - three zeroed floats, never read here @@ -71,11 +77,14 @@ class AIStrategicObjectManager AIStrategicObject* getStrategicObject(const std::string&) const; AIStrategicObject* getStrategicObjectOfCategory(int, int) const; void addStrategicObject(AIStrategicObject*); - void removeStrategicObject(int); + // ELF 0x344D00: the removed object, or 0 for an index out of range. + AIStrategicObject* removeStrategicObject(int index); AIStrategicObject* getClosestObject(const Vec3&, int) const; AIStrategicObject* getClosestObject(const Vec3&, int, bool) const; AIStrategicObject* getClosestObject(const Vec3&, int, int, int) const; - AIStrategicObject* getClosestObjectinCategory(const Vec3&, int, int, int, int) const; + // ELF 0x345020. [INFERRED] parameter names, from their uses. + AIStrategicObject* getClosestObjectinCategory(const Vec3& position, int side, int category, + int equipment, int vehicle) const; // strategic areas AIStrategicArea* getStrategicArea(int) const; @@ -83,24 +92,29 @@ class AIStrategicObjectManager const std::map& getStrategicAreas() const; std::string getStrategicAreaNames(); AIStrategicArea* getActiveArea(); - void setActive(std::string); + bool setActive(std::string name); // ELF 0x346D40; answers whether the name was found std::string getActive() const; // Initializes strategic areas; has no return value. void initAreas(); void postLoadInitAreas(); Vec2 getPosition() const; bool isInside(const std::string&, const Vec2&); - void create(std::string, Vec2, Vec2, float, float, const std::string&); + // ELF 0x3456D0: answers false (and clears the active area) for a duplicate name or a failed + // allocation, true after creating and selecting the area. + bool create(std::string name, Vec2 topLeft, Vec2 centre, float height, float radius, + const std::string& category = ""); // ConsoleClass417 passes "" for five arguments // Creates an area from a control point. Returns false for duplicate names or allocation // failure and true after successful creation. - bool createFromControlPoint(const std::string&, unsigned, float, const std::string&); - void removeActive(); + // ConsoleClass419 passes "" when the category is omitted. + bool createFromControlPoint(const std::string&, unsigned, float, const std::string& = ""); + bool removeActive(); // ELF 0x3461A0; false without an active area void setFlankPosition(Vec3, Vec3); std::string list() const; // neighbours - void addNeighbour(std::string); - void addTwoWayNeighbour(std::string, std::string); + // ELF 0x3463B0 / 0x346460: false for an unknown name or areas of different layers (+0x190). + bool addNeighbour(std::string); + bool addTwoWayNeighbour(std::string, std::string); void removeAllNeighbours(); std::string getNeighbours(); @@ -111,9 +125,10 @@ class AIStrategicObjectManager void createNewCategory(const std::string&); // object type flags - void addObjectTypeFlag(int); - void removeObjectTypeFlag(int); - void setObjectTypeFlags(int); + // The active area's new flag word, or -1 without an active area (or for type 27). + int addObjectTypeFlag(AIStrategicObject::StrategicObjectType); // ELF 0x3467B0 + int removeObjectTypeFlag(AIStrategicObject::StrategicObjectType); // ELF 0x346800 + int setObjectTypeFlags(int); // ELF 0x346850 int getObjectTypeFlags(); void removeAllObjectTypeFlags(); std::string getObjectTypeFlagMapping() const; @@ -122,11 +137,11 @@ class AIStrategicObjectManager bool setOrderPosition(std::string, const Vec3&); Vec3 getOrderPosition(std::string); std::string listOrderPositions(); - std::string checkAllOrderPositions() const; + void checkAllOrderPositions() const; // ELF 0x34A150: no result (plain retl) // waypoints void addWayPoint(const Vec3&, const std::string&, const std::string&, const std::string&); - void removeWayPoint(const Vec3&, const std::string&, const std::string&, const std::string&); + bool removeWayPoint(const Vec3&, const std::string&, const std::string&, const std::string&); void clearWayPoints(const std::string&, const std::string&, const std::string&); const std::vector& getWaypoints(int, int, int) const; const std::vector& getWaypoints(int, const AIStrategicArea*, const AIStrategicArea*) const; @@ -134,7 +149,10 @@ class AIStrategicObjectManager void undrawWayPoints() const; void setWayPointsToDraw(const std::string&, const std::string&); void clearWaypointToDraw(); - std::string checkAllWayPoints() const; + void checkAllWayPoints() const; // ELF 0x34A350: no result (plain retl) + // ELF 0x349610: an `aiStrategicArea.addWayPoint` line per waypoint, skipping containers whose + // first area's layer is listed in `excludedLayers` ("|"-separated). + void streamWaypoints(std::ostringstream& out, const std::string& excludedLayers) const; // bridges void createBridgeSegment(IAIObject*); @@ -143,7 +161,11 @@ class AIStrategicObjectManager void resetBridges(); void bridgeSegmentDestroyed(IAIObject*, int); void bridgeSegmentRepaired(IAIObject*); - bool getClosestDestroyedBridgeSegment(Vec3, bool, int, Vec3&, float&); + // Returns the nearest destroyed segment's object (ELF 0x349ED0 returns the pointer; the mangled + // name carries no return type). `position` receives the segment record's position, `distance` + // the squared distance. + IAIObject* getClosestDestroyedBridgeSegment(Vec3 from, bool repairRequested, int side, Vec3& position, + float& distance); static AIStrategicObjectManager* m_instance; @@ -153,26 +175,28 @@ class AIStrategicObjectManager // MSVC's `sizeof` will differ - libstdc++ 3.x puts a `_Rb_tree` in twelve bytes (a header-node // pointer, a node count and four bytes of empty comparator) and a `std::list` in four. /* +4 */ std::vector m_strategicObjects; - /* +16 */ std::vector > m_objectsByCategory; - // [UNRESOLVED] Cleared by construction and resets, but no implemented method sets or - // reads it. The current name does not establish its meaning. - /* +28 */ bool m_areasInitialised; - /* +32 */ std::map m_strategicAreas; + /* +16 */ std::vector > m_objectsPerCategory; // name: AIDLL_r assert 0x10086290 (PE +0x14) +public: + // [CHOSEN, not recovered] Visibility for the generated inline debug control. + /* +28 */ bool m_debugEnabled; // false; console enableDebug +private: + /* +32 */ std::map m_strategicAreaMap; // name: AIDLL_r assert 0x1008B6F0 (PE +0x28) // The reverse index. Its value type is `std::string` - read straight off the destructor's // `_Rb_tree, ...>` teardown. /* +44 */ std::map m_areaNames; - // An iterator, not a pointer - one word in this libstdc++, initialised to `m_strategicAreas.end` + // An iterator, not a pointer - one word in this libstdc++, initialised to `m_strategicAreaMap.end` // by the constructor and compared against `end` by every reader (`getActiveArea` // `getObjectTypeFlags`, `setOrderPosition`, `getPosition`). /* +56 */ std::map::iterator m_activeArea; - /* +60 */ std::map m_categories; - /* +72 */ std::vector m_categoryNames; - // Written 0 by the constructor and never touched again anywhere in this class. [UNRESOLVED]. - /* +84 */ bool m_b84; - /* +88 */ std::map, WPContainer> m_wayPoints; - // The two halves of a `m_wayPoints` key, both -1 for "nothing selected". - // `clearWaypointToDraw` resets only the first of the two. `drawWayPoints` tests - // only the first as well, so the stale second half is never read - but it is left stale. + /* +60 */ std::map m_namesToCategory; // name: AIDLL_r assert 0x100892D0 (PE +0x44) + /* +72 */ std::vector m_categoryToNames; // name: AIDLL_r assert 0x100867B0 (PE +0x50) +public: + // [CHOSEN, not recovered] Visibility for the generated inline drawing control. + /* +84 */ bool m_drawVehicleSearchRadii; // false; console drawVehicleSearchRadi +private: + /* +88 */ std::map, WPContainer> m_waypointMap; // name: AIDLL_r assert 0x10089680 (PE +0x64) + // The two halves of a `m_waypointMap` key, both -1 for "nothing selected". + // `clearWaypointToDraw` resets only the first of the two; `drawWayPoints` tests both. /* +100 */ int m_wayPointsToDrawFirst; /* +104 */ int m_wayPointsToDrawSecond; /* +108 */ std::list m_bridgeSegments; diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AreaAssignment.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AreaAssignment.cpp new file mode 100644 index 000000000..9831b1067 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AreaAssignment.cpp @@ -0,0 +1,409 @@ +// [INFERRED] Source placement: the TU's static initializer is _GLOBAL__I__ZN4dice3hfe2ai14AreaAssignmentC2Ev. + +#include "AreaAssignment.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x34E7F0, __tcf_0 0x34E850, _GLOBAL__I 0x34E880). +#include + +#include "../AIStrategic/SAI.h" // EnemyStatistics + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x34D5A0 (C2; C1 0x34D630). +AreaAssignment::AreaAssignment() + : m_effectiveTarget(0), m_effectiveAssigned(0), m_assigned(0), m_target(0), m_testAssigned(0) + , m_testEffectiveAssigned(0), m_testQuotient(0), m_testDifference(0), m_testAssignedCount(0) + , m_assignedCount(0), m_targetCount(0), m_difference(0), m_quotient(0) + , m_sqrDistDifference(-1.0f), m_sqrDistTestDifference(-1.0f), m_sqrDistQuotient(-1.0f) + , m_sqrDistTestQuotient(-1.0f), m_size(0), m_calculated(false), m_b49(true) +{ +} + +// ELF 0x34D6C0 (C2; C1 0x34D770). +AreaAssignment::AreaAssignment(int size) + : m_effectiveTarget(0), m_effectiveAssigned(0), m_assigned(0), m_target(0), m_testAssigned(0) + , m_testEffectiveAssigned(0), m_testQuotient(0), m_testDifference(0), m_testAssignedCount(0) + , m_assignedCount(0), m_targetCount(0), m_difference(0), m_quotient(0) + , m_sqrDistDifference(-1.0f), m_sqrDistTestDifference(-1.0f), m_sqrDistQuotient(-1.0f) + , m_sqrDistTestQuotient(-1.0f), m_size(0), m_calculated(false), m_b49(true) +{ + setSize(size); +} + +// ELF 0x34D820 (C2; C1 0x34D990): fresh arrays of the other's size, then flags, the four +// results and every array element. +AreaAssignment::AreaAssignment(const AreaAssignment& other) + : m_effectiveTarget(0), m_effectiveAssigned(0), m_assigned(0), m_target(0), m_testAssigned(0) + , m_testEffectiveAssigned(0), m_testQuotient(0), m_testDifference(0), m_testAssignedCount(0) + , m_assignedCount(0), m_targetCount(0), m_difference(0), m_quotient(0), m_size(0) +{ + setSize(other.m_size); + m_calculated = other.m_calculated; + m_b49 = other.m_b49; + m_sqrDistDifference = other.m_sqrDistDifference; + m_sqrDistTestDifference = other.m_sqrDistTestDifference; + m_sqrDistQuotient = other.m_sqrDistQuotient; + m_sqrDistTestQuotient = other.m_sqrDistTestQuotient; + for (int i = 0; i < m_size; ++i) + { + m_assigned[i] = other.m_assigned[i]; + m_target[i] = other.m_target[i]; + m_difference[i] = other.m_difference[i]; + m_quotient[i] = other.m_quotient[i]; + m_assignedCount[i] = other.m_assignedCount[i]; + m_testAssigned[i] = other.m_testAssigned[i]; + m_testEffectiveAssigned[i] = other.m_testEffectiveAssigned[i]; + m_testQuotient[i] = other.m_testQuotient[i]; + m_testDifference[i] = other.m_testDifference[i]; + m_testAssignedCount[i] = other.m_testAssignedCount[i]; + m_targetCount[i] = other.m_targetCount[i]; + m_effectiveTarget[i] = other.m_effectiveTarget[i]; + m_effectiveAssigned[i] = other.m_effectiveAssigned[i]; + } +} + +// ELF 0x34DB00 (D2; D1 0x34DC60). +AreaAssignment::~AreaAssignment() +{ + delete[] m_assigned; + delete[] m_target; + delete[] m_difference; + delete[] m_quotient; + delete[] m_assignedCount; + delete[] m_targetCount; + delete[] m_effectiveTarget; + delete[] m_effectiveAssigned; + delete[] m_testAssigned; + delete[] m_testEffectiveAssigned; + delete[] m_testQuotient; + delete[] m_testDifference; + delete[] m_testAssignedCount; +} + +// ELF 0x34DDC0. +void AreaAssignment::setSize(int size) +{ + if (!m_size) + { + m_size = size; + m_assigned = new float[m_size]; + m_target = new float[m_size]; + m_targetCount = new int[m_size]; + m_difference = new float[m_size]; + m_quotient = new float[m_size]; + m_assignedCount = new int[m_size]; + m_effectiveAssigned = new float[m_size]; + m_effectiveTarget = new float[m_size]; + m_testAssigned = new float[m_size]; + m_testEffectiveAssigned = new float[m_size]; + m_testQuotient = new float[m_size]; + m_testDifference = new float[m_size]; + m_testAssignedCount = new int[m_size]; + } + for (int i = 0; i < m_size; ++i) + { + m_assigned[i] = 0.0f; + m_target[i] = 0.0f; + m_difference[i] = 0.0f; + m_quotient[i] = 0.0f; + m_assignedCount[i] = 0; + m_testAssigned[i] = 0.0f; + m_testEffectiveAssigned[i] = 0.0f; + m_testQuotient[i] = 0.0f; + m_testDifference[i] = 0.0f; + m_testAssignedCount[i] = 0; + m_targetCount[i] = 0; + m_effectiveTarget[i] = 0.0f; + m_effectiveAssigned[i] = 0.0f; + } + m_calculated = false; +} + +// ELF 0x34DF50: the target and its truncated counts; the assignment is cleared. +float* AreaAssignment::setVecToMatch(float* strength, float* count) +{ + for (int i = 0; i < m_size; ++i) + { + m_target[i] = strength[i]; + m_targetCount[i] = static_cast(count[i]); + m_assigned[i] = 0.0f; + m_assignedCount[i] = 0; + } + m_calculated = false; + return m_target; +} + +// ELF 0x34DFC0: as above from the statistics' strength and count arrays. +float* AreaAssignment::setVecToMatch(EnemyStatistics* statistics) +{ + float* const strength = statistics->m_strength; + float* const count = statistics->m_count; + for (int i = 0; i < m_size; ++i) + { + m_target[i] = strength[i]; + m_targetCount[i] = static_cast(count[i]); + m_assigned[i] = 0.0f; + m_assignedCount[i] = 0; + } + m_calculated = false; + return m_target; +} + +// ELF 0x34E050. +int AreaAssignment::getNumberOfAssignedUnits() +{ + int units = 0; + for (int i = 0; i < m_size; ++i) + units += m_assignedCount[i]; + return units; +} + +// ELF 0x34E080. As shipped, the target strength is divided by the assigned count and the +// assigned strength by the target count; a zero numerator or count gives 0. +void AreaAssignment::calculateEffectiveStrengths() +{ + for (int i = 0; i < m_size; ++i) + { + if (m_target[i] != 0.0f && m_assignedCount[i] != 0) + m_effectiveTarget[i] = m_target[i] / static_cast(m_assignedCount[i]); + else + m_effectiveTarget[i] = 0.0f; + if (m_assigned[i] != 0.0f && m_targetCount[i] != 0) + m_effectiveAssigned[i] = m_assigned[i] / static_cast(m_targetCount[i]); + else + m_effectiveAssigned[i] = 0.0f; + } + m_calculated = true; +} + +// ELF 0x34E130: difference = effective target - effective assigned. +void AreaAssignment::calculateDifference() +{ + add(-1.0f, m_difference, m_effectiveTarget, m_effectiveAssigned); +} + +// ELF 0x34E180. +float* AreaAssignment::getDifference() +{ + return m_difference; +} + +// ELF 0x34E190. +float AreaAssignment::calculateSqrDistDifference() +{ + return m_sqrDistDifference = sqrDist(m_difference); +} + +// ELF 0x34E1D0. +float AreaAssignment::getSqrDistDifference() +{ + return m_sqrDistDifference; +} + +// ELF 0x34E1E0. +float* AreaAssignment::getQuotient() +{ + return m_quotient; +} + +// ELF 0x34E1F0. +void AreaAssignment::calculateQuotient() +{ + quotient(m_quotient, m_effectiveAssigned); +} + +// ELF 0x34E230. +float AreaAssignment::getSummedQuotient() +{ + return sum(m_quotient); +} + +// ELF 0x34E260. +float AreaAssignment::calculateSqrDistQuotient() +{ + return m_sqrDistQuotient = sqrDist(m_quotient); +} + +// ELF 0x34E2A0. +float AreaAssignment::getSqrDistQuotient() +{ + return m_sqrDistQuotient; +} + +// ELF 0x34E2B0. +void AreaAssignment::calculate() +{ + calculateEffectiveStrengths(); + calculateQuotient(); + calculateDifference(); + calculateSqrDistQuotient(); + calculateSqrDistDifference(); +} + +// ELF 0x34E300: test strength = strength + test strength; one more test unit at `index`. +float* AreaAssignment::addTestStrength(float* strength, int index) +{ + add(1.0f, m_testAssigned, strength, m_testAssigned); + ++m_testAssignedCount[index]; + return m_testAssigned; +} + +// ELF 0x34E360. +void AreaAssignment::calculateTestDifference() +{ + add(-1.0f, m_testDifference, m_effectiveTarget, m_testEffectiveAssigned); +} + +// ELF 0x34E3B0. +float* AreaAssignment::getTestDifference() +{ + return m_testDifference; +} + +// ELF 0x34E3C0. Shipped defect, preserved: the result is not stored in m_sqrDistTestDifference. +float AreaAssignment::calculateSqrDistTestDifference() +{ + return sqrDist(m_testDifference); +} + +// ELF 0x34E3F0. +float AreaAssignment::getSqrDistTestDifference() +{ + return m_sqrDistTestDifference; +} + +// ELF 0x34E400. +float AreaAssignment::summedTestStrength() +{ + return sum(m_testAssigned); +} + +// ELF 0x34E430. +void AreaAssignment::calculateTestQuotient() +{ + quotient(m_testQuotient, m_testEffectiveAssigned); +} + +// ELF 0x34E470. +float* AreaAssignment::getTestQuotient() +{ + return m_testQuotient; +} + +// ELF 0x34E480. +float AreaAssignment::getSummedTestQuotient() +{ + return sum(m_testQuotient); +} + +// ELF 0x34E4B0. +float AreaAssignment::calculateSqrDistTestQuotient() +{ + return m_sqrDistTestQuotient = sqrDist(m_testQuotient); +} + +// ELF 0x34E4F0. +float AreaAssignment::getSqrDistTestQuotient() +{ + return m_sqrDistTestQuotient; +} + +// ELF 0x34E500. +float* AreaAssignment::addStrength(float* strength, int index) +{ + add(1.0f, m_assigned, strength); + ++m_assignedCount[index]; + m_calculated = false; + return m_assigned; +} + +// ELF 0x34E560. +void AreaAssignment::makeTestActual() +{ + for (int i = 0; i < m_size; ++i) + { + m_assigned[i] = m_testAssigned[i]; + m_effectiveAssigned[i] = m_testEffectiveAssigned[i]; + m_quotient[i] = m_testQuotient[i]; + m_difference[i] = m_testDifference[i]; + m_assignedCount[i] = m_testAssignedCount[i]; + } +} + +// ELF 0x34E5C0. +void AreaAssignment::resetTestCase() +{ + for (int i = 0; i < m_size; ++i) + { + m_testAssigned[i] = m_assigned[i]; + m_testEffectiveAssigned[i] = m_effectiveAssigned[i]; + m_testQuotient[i] = m_quotient[i]; + m_testDifference[i] = m_difference[i]; + m_testAssignedCount[i] = m_assignedCount[i]; + } +} + +// ELF 0x34E620: any negative difference entry. +bool AreaAssignment::hasNegativeStrength() +{ + for (int i = 0; i < m_size; ++i) + { + if (m_difference[i] < 0.0f) + return true; + } + return false; +} + +// ELF 0x34E670: out = in / effective target, 0 where either is 0. +void AreaAssignment::quotient(float* out, float* in) +{ + for (int i = 0; i < m_size; ++i) + { + if (in[i] == 0.0f || m_effectiveTarget[i] == 0.0f) + out[i] = 0.0f; + else + out[i] = in[i] / m_effectiveTarget[i]; + } +} + +// ELF 0x34E6E0: inOut += factor * in. +void AreaAssignment::add(float factor, float* inOut, float* in) +{ + for (int i = 0; i < m_size; ++i) + inOut[i] = inOut[i] + factor * in[i]; +} + +// ELF 0x34E720: out = in + factor * scaled. +void AreaAssignment::add(float factor, float* out, float* in, float* scaled) +{ + for (int i = 0; i < m_size; ++i) + out[i] = in[i] + factor * scaled[i]; +} + +// ELF 0x34E760. +float AreaAssignment::sum(float* values) +{ + float total = 0.0f; + for (int i = 0; i < m_size; ++i) + total += values[i]; + return total; +} + +// ELF 0x34E7A0. +float AreaAssignment::sqrDist(float* values) +{ + float total = 0.0f; + for (int i = 0; i < m_size; ++i) + { + if (values[i] > 0.0f) + total += values[i] * values[i]; + } + return total; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AreaAssignment.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AreaAssignment.h new file mode 100644 index 000000000..444364b14 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AreaAssignment.h @@ -0,0 +1,97 @@ +// Per-equipment strength bookkeeping for matching assigned units against a target distribution +// (libaidll.so AreaAssignment.cpp, 0x34D5A0..0x34E8A0). Nothing in the shipped image constructs +// one: every caller is another AreaAssignment member. +// [INFERRED] Source placement and member names; the offsets are the ELF layout. + +#ifndef AI_AIDLL_AI_AISTRATEGICENTITY_AREAASSIGNMENT_H // [INFERRED] guard style +#define AI_AIDLL_AI_AISTRATEGICENTITY_AREAASSIGNMENT_H + +namespace dice { +namespace hfe { +namespace ai { + +class EnemyStatistics; + +class AreaAssignment +{ +public: + AreaAssignment(); // ELF 0x34D5A0 (C2; C1 0x34D630) + explicit AreaAssignment(int size); // ELF 0x34D6C0 (C2; C1 0x34D770) + AreaAssignment(const AreaAssignment& other); // ELF 0x34D820 (C2; C1 0x34D990) + ~AreaAssignment(); // ELF 0x34DB00 (D2; D1 0x34DC60) + + // Allocates the thirteen arrays on first use (a later call keeps the old size and only + // clears them). + void setSize(int size); + // Both answer the target-strength array (the image reloads +0xC into eax). [INFERRED] type. + float* setVecToMatch(float* strength, float* count); + float* setVecToMatch(EnemyStatistics* statistics); + int getNumberOfAssignedUnits(); + + void calculateEffectiveStrengths(); + void calculateDifference(); + float* getDifference(); + float calculateSqrDistDifference(); + float getSqrDistDifference(); + float* getQuotient(); + void calculateQuotient(); + float getSummedQuotient(); + float calculateSqrDistQuotient(); + float getSqrDistQuotient(); + void calculate(); + + // Both answer the strength array they add into (explicit reload in the image). + float* addTestStrength(float* strength, int index); + void calculateTestDifference(); + float* getTestDifference(); + float calculateSqrDistTestDifference(); + float getSqrDistTestDifference(); + float summedTestStrength(); + void calculateTestQuotient(); + float* getTestQuotient(); + float getSummedTestQuotient(); + float calculateSqrDistTestQuotient(); + float getSqrDistTestQuotient(); + float* addStrength(float* strength, int index); + void makeTestActual(); + void resetTestCase(); + bool hasNegativeStrength(); + + // Element-wise helpers over m_size entries. The void returns are [INFERRED]: their + // callers forward eax without using it. + void quotient(float* out, float* in); + void add(float factor, float* inOut, float* in); + void add(float factor, float* out, float* in, float* scaled); + float sum(float* values); + // The sum of the squares of the positive entries. + float sqrDist(float* values); + +private: + /* +0x00 */ float* m_effectiveTarget; // m_target / m_assignedCount + /* +0x04 */ float* m_effectiveAssigned; // m_assigned / m_targetCount + /* +0x08 */ float* m_assigned; + /* +0x0C */ float* m_target; + /* +0x10 */ float* m_testAssigned; + /* +0x14 */ float* m_testEffectiveAssigned; + /* +0x18 */ float* m_testQuotient; + /* +0x1C */ float* m_testDifference; + /* +0x20 */ int* m_testAssignedCount; + /* +0x24 */ int* m_assignedCount; + /* +0x28 */ int* m_targetCount; + /* +0x2C */ float* m_difference; + /* +0x30 */ float* m_quotient; + /* +0x34 */ float m_sqrDistDifference; + // -1 from the constructors; calculateSqrDistTestDifference does not store its result here. + /* +0x38 */ float m_sqrDistTestDifference; + /* +0x3C */ float m_sqrDistQuotient; + /* +0x40 */ float m_sqrDistTestQuotient; + /* +0x44 */ int m_size; + /* +0x48 */ bool m_calculated; // set by calculateEffectiveStrengths + /* +0x49 */ bool m_b49; // true from every constructor [UNRESOLVED] +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGICENTITY_AREAASSIGNMENT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AreaDistanceInfo.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AreaDistanceInfo.cpp new file mode 100644 index 000000000..fcbf50678 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AreaDistanceInfo.cpp @@ -0,0 +1,35 @@ +// [INFERRED] Source placement: see AreaDistanceInfo.h. + +#include "AreaDistanceInfo.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x34E8A0: `movl $0x0,(%eax); movl $0x0,0x4(%eax); movl <0.0f>,0x8(%eax)`. +AreaDistanceInfo::AreaDistanceInfo() + : m_vehicleGroups(0) + , m_area(0) + , m_distance(0.0f) +{ +} + +// ELF 0x34E900: three word copies. +AreaDistanceInfo::AreaDistanceInfo(const AreaDistanceInfo& other) + : m_vehicleGroups(other.m_vehicleGroups) + , m_area(other.m_area) + , m_distance(other.m_distance) +{ +} + +// ELF 0x34E940: the arguments in field order. +AreaDistanceInfo::AreaDistanceInfo(int vehicleGroups, AIStrategicArea* area, float distance) + : m_vehicleGroups(vehicleGroups) + , m_area(area) + , m_distance(distance) +{ +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AreaDistanceInfo.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AreaDistanceInfo.h new file mode 100644 index 000000000..362f4fb25 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AreaDistanceInfo.h @@ -0,0 +1,31 @@ +// One entry of an area's per-side distance list (AIStrategicArea::m_distances): a strategic +// area, its route distance from the owner, and the vehicle groups that reach it at that distance. +// [INFERRED] Source placement and field names: the ctors sit between AreaAssignment.cpp and +// SAWayPoint.cpp in libaidll.so (0x34E8A0..0x34E960) without a FILE symbol of their own. + +#ifndef AI_AIDLL_AI_AISTRATEGICENTITY_AREADISTANCEINFO_H // [INFERRED] guard style +#define AI_AIDLL_AI_AISTRATEGICENTITY_AREADISTANCEINFO_H + +namespace dice { +namespace hfe { +namespace ai { + +class AIStrategicArea; + +// dice::hfe::ai::AreaDistanceInfo (namespace scope in the ELF mangling), twelve bytes. +struct AreaDistanceInfo +{ + AreaDistanceInfo(); // ELF 0x34E8A0 + AreaDistanceInfo(const AreaDistanceInfo& other); // ELF 0x34E900 + AreaDistanceInfo(int vehicleGroups, AIStrategicArea* area, float distance); // ELF 0x34E940 + + /* +0 */ int m_vehicleGroups; // bit mask, 1 << group (insertUnitDistances) + /* +4 */ AIStrategicArea* m_area; + /* +8 */ float m_distance; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGICENTITY_AREADISTANCEINFO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNode.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNode.cpp new file mode 100644 index 000000000..429421d35 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNode.cpp @@ -0,0 +1,122 @@ +// CPNode. Evidence: libaidll.so 1.5.3153 (ia-32), see CPNode.h. + +#include "CPNode.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x35C440, __tcf_0 0x35C4A0, _GLOBAL__I 0x35C4D0). +#include + +#include "../../AIUtils/checkPointer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x35BAC0 (C2; C1 0x35BB00): six zero words. +CPNode::CPNode() + : m_parent(0) + , m_next(0) + , m_prev(0) + , m_key(0) + , m_g(0.0f) + , m_f(0.0f) +{ +} + +// ELF 0x35BB40 (C2; C1 0x35BCC0). The cover position goes through checkPointer. +CPNode::CPNode(CPNode* parent, int coverPosition) + : m_parent(parent) + , m_next(0) + , m_prev(0) + , m_key(checkPointer(CoverPositionManager::m_instance->m_coverPositions[coverPosition])) + , m_g(0.0f) + , m_f(0.0f) +{ +} + +// ELF 0x35BE40 (C2; C1 0x35BE70): every word copied. +CPNode::CPNode(const CPNode& other) + : m_parent(other.m_parent) + , m_next(other.m_next) + , m_prev(other.m_prev) + , m_key(other.m_key) + , m_g(other.m_g) + , m_f(other.m_f) +{ +} + +// ELF 0x35BEA0 (D2; D1 0x35BEB0). +CPNode::~CPNode() +{ +} + +// ELF 0x35BEC0. +void CPNode::setCoverPosition(int index) +{ + m_key = checkPointer(CoverPositionManager::m_instance->m_coverPositions[index]); +} + +// ELF 0x35C010. +void CPNode::setCoverPosition(CoverPosition* coverPosition) +{ + m_key = coverPosition; +} + +// ELF 0x35C020. An empty neighbour set is tested by its size; the iterator then starts at begin. +CPNode* CPNode::expandFirst(CPNodeManager* manager, nodeStatus::Status& status, NeighbourIterator& it) +{ + if (m_key->m_moveNeighbours.empty()) + { + status = nodeStatus::kInvalid; + return 0; + } + it = m_key->m_moveNeighbours.begin(); + const int neighbour = *it; + ++it; + getStatus(manager, status, neighbour); + return manager->getNewNode(this, neighbour); +} + +// ELF 0x35C1E0. +CPNode* CPNode::expand(CPNodeManager* manager, nodeStatus::Status& status, NeighbourIterator& it) +{ + if (it == m_key->m_moveNeighbours.end()) + { + status = nodeStatus::kInvalid; + return 0; + } + const int neighbour = *it; + ++it; + getStatus(manager, status, neighbour); + return manager->getNewNode(this, neighbour); +} + +// ELF 0x35C3A0. The goal test comes first (0x35C3B8). The manager's +0x14 filter, when non-null, +// is then asked through its virtual +8 with the position (0x35C420..0x35C42C), and a false byte +// gives kInvalid (0x35C3C9 / 0x35C413). The filter is always null in retail (see CPNodeFilter), +// so that arm is never taken; it is kept as shipped. +void CPNode::getStatus(CPNodeManager* manager, nodeStatus::Status& status, int coverPosition) +{ + if (manager->m_goal == coverPosition) + { + status = nodeStatus::kGoal; + return; + } + bool mayEnter = true; + if (manager->m_filter != 0) + mayEnter = manager->m_filter->mayEnter(coverPosition); + if (!mayEnter) + { + status = nodeStatus::kInvalid; + return; + } + const std::pair& flags = manager->m_status[coverPosition]; + if (flags.first) + status = nodeStatus::kOpen; + else + status = flags.second ? nodeStatus::kClosed : nodeStatus::kUnvisited; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNode.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNode.h new file mode 100644 index 000000000..e834fc33a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNode.h @@ -0,0 +1,129 @@ +// The cover-position A* node: a cover position reached from its parent. Its neighbours are the +// cover position's move neighbours (CoverPosition +0x2C). The CPNodeManager inlines the search +// templates call are defined here, after both classes are complete. +// Evidence: libaidll.so 1.5.3153 (ia-32), ELF 0x35BAC0..0x35C4D0 (CPNode's own functions and the +// TU's static initialisation; its first symbol names CPNode::CPNode()). [INFERRED] Placement +// AIStrategicEntity/CoverPosition/CPNode.cpp; no __FILE__ string attests it. + +#ifndef AI_AIDLL_AI_AISTRATEGICENTITY_COVERPOSITION_CPNODE_H // [INFERRED] guard style +#define AI_AIDLL_AI_AISTRATEGICENTITY_COVERPOSITION_CPNODE_H + +#include + +#include "../../AIUtils/checkPointer.h" +#include "../../Main/AIPathfindingSearchTypes.h" // nodeStatus +#include "CPNodeManager.h" +#include "CoverPosition.h" +#include "CoverPositionManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// 24 bytes (operator new(0x18) in expandFirst, expand and CoverPositionManager::search). +class CPNode +{ +public: + // The iterator over a cover position's move neighbours that expandFirst / expand advance. + typedef std::set::const_iterator NeighbourIterator; + + CPNode(); + // A node on cover position `coverPosition`, reached from `parent`; costs and links cleared. + CPNode(CPNode* parent, int coverPosition); + CPNode(const CPNode& other); + ~CPNode(); + + // Points the node at cover position `index` of CoverPositionManager::m_instance. + void setCoverPosition(int index); + void setCoverPosition(CoverPosition* coverPosition); + + // Neighbour iteration for AStarResource::update: the next move neighbour as a node (from the + // manager's pool) and its status, or null with kInvalid when there is none. + CPNode* expandFirst(CPNodeManager* manager, nodeStatus::Status& status, NeighbourIterator& it); + CPNode* expand(CPNodeManager* manager, nodeStatus::Status& status, NeighbourIterator& it); + // kGoal for the manager's goal, kInvalid when the manager's filter refuses it, else kOpen, + // kClosed or kUnvisited from the manager's per-position flags. + void getStatus(CPNodeManager* manager, nodeStatus::Status& status, int coverPosition); + + // [INFERRED] The node has no depth word: AStarResource::update tests the search depth + // limit against the constant 0. + static const int m_depth = 0; + + // [INFERRED] names; offsets from the constructors and the search templates. + /* +0 */ CPNode* m_parent; + /* +4 */ CPNode* m_next; // hash chain and the manager's free-list link + /* +8 */ CPNode* m_prev; // hash chain back link + /* +12 */ CoverPosition* m_key; // the cover position; the search compares nodes by it + /* +16 */ float m_g; // cost from the start + /* +20 */ float m_f; // the open tree's order +}; + +// The Hash hooks (AIPathfindingSearchTypes.h): a CPNode hashes to its cover position's index with +// no modulus (Hash::insert 0x359B20, get 0x35B8C0, remove 0x35B960) and compares by cover +// position pointer. +inline int hashIndexOf(const CPNode* node, int) +{ + return node->m_key->m_id; +} + +inline bool hashKeyEquals(const CPNode* a, const CPNode* b) +{ + return a->m_key == b->m_key; +} + +// The manager's inline operations, as AStarResource (0x359BC0, 0x35B7D0) and +// CoverPositionManager::search inline them. [INFERRED] names (shared with QTSearchNodeManager). + +inline void CPNodeManager::setNodeOpen(CPNode* node) +{ + m_status[node->m_key->m_id].first = true; +} + +inline void CPNodeManager::setNodeClosed(CPNode* node) +{ + m_status[node->m_key->m_id].first = false; + m_status[node->m_key->m_id].second = true; +} + +inline void CPNodeManager::recycleNode(CPNode* node) +{ + if (node != 0) + { + node->m_next = m_nodes; + m_nodes = node; + } +} + +// A cheaper route through `from`: the cost is the distance-table entry plus from's g. Shipped +// defect, preserved: only f changes, by -(g + cost); g and the parent keep their old values. +inline bool CPNodeManager::updateNode(CPNode* from, CPNode* existing, int) +{ + const float cost = CoverPositionManager::m_instance->getDistance(from->m_key->m_id, + existing->m_key->m_id) + + from->m_g; + if (cost < existing->m_g) + { + existing->m_f -= existing->m_g + cost; + return true; + } + return false; +} + +// A node on `coverPosition` reached from `parent`: the head of the free list, re-pointed, or a new +// one. A reused node keeps its old costs. +inline CPNode* CPNodeManager::getNewNode(CPNode* parent, int coverPosition) +{ + CPNode* node = m_nodes; + if (node == 0) + return checkPointer(new CPNode(parent, coverPosition)); + m_nodes = node->m_next; + node->setCoverPosition(coverPosition); + node->m_parent = parent; + return node; +} + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGICENTITY_COVERPOSITION_CPNODE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNodeManager.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNodeManager.cpp index f5dce23af..b2e89ae14 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNodeManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNodeManager.cpp @@ -1,39 +1,52 @@ -// [INFERRED] Source placement. +// CPNodeManager. Evidence: libaidll.so 1.5.3153 (ia-32), see CPNodeManager.h. #include "CPNodeManager.h" -#include "../../Main/AIDllFrontier.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x35C800, __tcf_0 0x35C860, _GLOBAL__I 0x35C890). +#include + +#include "CPNode.h" +#include "CoverPositionManager.h" namespace dice { namespace hfe { namespace ai { -// Six words: three for the vector, a null chain head, -1, and a zero. +// ELF 0x35C4F0 (C2; C1 0x35C530): the empty vector, a null pool, goal -1, no filter. CPNodeManager::CPNodeManager() : m_nodes(0) - , m_i16(-1) - , m_i20(0) + , m_goal(-1) + , m_filter(0) { } -// [FRONTIER] Node-pool destruction requires complete CPNode ownership and linkage. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding CPNodeManager operation. - +// ELF 0x35C5F0 (D1; D2 0x35C570): every pooled node is unlinked and deleted (CPNode D1 0x35BEB0, +// then operator delete); the vector goes as a member. CPNodeManager::~CPNodeManager() { - BF2_AI_FRONTIER("dice::hfe::ai::CPNodeManager::~CPNodeManager"); + while (m_nodes != 0) + { + CPNode* const node = m_nodes; + m_nodes = node->m_next; + delete node; + } } -// - walks the same chain. [RETIRE-WHEN: aidll-02-skeleton] +// ELF 0x35C670. void CPNodeManager::init() { - BF2_AI_FRONTIER("dice::hfe::ai::CPNodeManager::init"); + m_status.resize(CoverPositionManager::m_instance->m_coverPositions.size(), + std::pair(false, false)); } -// - likewise. [RETIRE-WHEN: aidll-02-skeleton] +// ELF 0x35C710: resize(0) (the empty-vector arm calls _M_fill_insert with a count of 0, so this +// is resize rather than clear), then the init sizing. void CPNodeManager::reset() { - BF2_AI_FRONTIER("dice::hfe::ai::CPNodeManager::reset"); + m_status.resize(0, std::pair(false, false)); + m_status.resize(CoverPositionManager::m_instance->m_coverPositions.size(), + std::pair(false, false)); } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNodeManager.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNodeManager.h index 42e6b056a..8619ddc46 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNodeManager.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNodeManager.h @@ -1,10 +1,12 @@ -// Node manager for cover-position searches. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. -// [INFERRED] Source placement. +// The node pool and per-position open/closed flags of one cover-position search. +// Evidence: libaidll.so 1.5.3153 (ia-32), ELF 0x35C4F0..0x35C890 (constructors, destructors, init, +// reset, the TU's static initialisation and the vector >::erase instantiation). +// [INFERRED] Placement AIStrategicEntity/CoverPosition/CPNodeManager.cpp. #ifndef AI_AIDLL_AI_AISTRATEGICENTITY_COVERPOSITION_CPNODEMANAGER_H // [INFERRED] guard style #define AI_AIDLL_AI_AISTRATEGICENTITY_COVERPOSITION_CPNODEMANAGER_H +#include #include namespace dice { @@ -13,25 +15,58 @@ namespace ai { class CPNode; +// [CHOSEN, not recovered] Interface of CPNodeManager::m_filter, declared under AGENTS.md's +// null-only member pointer clause. libaidll.so writes that member only as null (constructors +// ELF 0x35C51B / 0x35C55B; amd-64 0x3962A6 / 0x3962D6), and no setter, copy, engine producer or +// vtable exists in any inspected image. So the single call through it (CPNode::getStatus, +// 0x35C429 `call [eax+8]`; amd-64 0x3958FE `call [rax+0x10]`) is never taken in retail. +// The call site proves only: receiver, one int position argument, a tested byte result. +// [UNRESOLVED] Original class, method names and leading slots. The two leading slots are not +// claimed to be destructors. Never give this interface an implementation, setter or factory. +class CPNodeFilter +{ +public: + virtual void chosenSlot0() = 0; // +0x00 [CHOSEN] + virtual void chosenSlot1() = 0; // +0x04 [CHOSEN] + virtual bool mayEnter(int coverPosition) = 0; // +0x08 [CHOSEN] name; bool for the tested byte + +protected: + ~CPNodeFilter() {} +}; + class CPNodeManager { public: CPNodeManager(); - ~CPNodeManager(); // , not virtual + ~CPNodeManager(); // not virtual + // Sizes the flags to the cover-position count, new entries (false, false). void init(); + // Clears every flag, then sizes them as init does. The node pool is kept. void reset(); + // [INFERRED] inline and empty, added by ai-nav: ~PathfindingEngine (ELF 0x3593F0, the CPNode + // instantiation) has no call between `+0xC = -1` and `+0x1C = -1` where the QTSearchNode + // (0x3AE784) and ClusterNode (0x3AE994) instantiations call returnReset, and the image has no + // CPNodeManager::returnReset symbol. + void returnReset() {} + + // Inline in retail; defined in CPNode.h. + void setNodeOpen(CPNode* node); + void setNodeClosed(CPNode* node); + void recycleNode(CPNode* node); + bool updateNode(CPNode* from, CPNode* existing, int maxSearchDepth); + CPNode* getNewNode(CPNode* parent, int coverPosition); -private: - // layout, , every word read from the 54-byte constructor - // The element size of the vector is two bytes: the destructor computes its count as - // `(end_of_storage - start) >> 1` and frees `2 * count`. What the shorts are is [UNRESOLVED]. - /* +0 */ std::vector m_v0; - // The head of a singly linked chain of nodes threaded through `CPNode + 4`; the destructor - // unlinks and deletes every one of them. - /* +12 */ CPNode* m_nodes; // [INFERRED] name - /* +16 */ int m_i16; // = -1 [UNRESOLVED] - the only non-zero the constructor writes - /* +20 */ int m_i20; // = 0 [UNRESOLVED] + // Layout from the 54-byte constructor; names [INFERRED]. + // Per cover position: (open, closed). setNodeOpen sets first; setNodeClosed clears first and + // sets second (the vector > instantiations in this TU and CPNode::getStatus). + /* +0 */ std::vector > m_status; + // The free list of recycled nodes, threaded through CPNode::m_next; the destructor deletes it. + /* +12 */ CPNode* m_nodes; + /* +16 */ int m_goal; // = -1; the goal's cover-position index (CoverPositionManager::search) + // = 0 and never written elsewhere in any inspected image. CPNode::getStatus asks a non-null one + // through its virtual +8 whether a position may be entered (see CPNodeFilter). + /* +20 */ CPNodeFilter* m_filter; }; } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPosition.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPosition.cpp new file mode 100644 index 000000000..3f3eadb98 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPosition.cpp @@ -0,0 +1,352 @@ +// CoverPosition. Evidence: libaidll.so 1.5.3153 (ia-32), see CoverPosition.h. + +#include "CoverPosition.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x354C20, __tcf_0 0x354C80, _GLOBAL__I 0x354CB0). +#include + +#include + +#include "CoverPositionManager.h" +#include "../../Main/CommonSingletonServer.h" +#include "../../../../AIInterface/BFKnowledge/AIAdapterTypes.h" // AIObjectPredicate +#include "../../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" // IAIObjectEnvironment +#include "../../../../AIInterface/BFKnowledge/BFTerrain.h" // IAITerrain +#include "../../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../../../Core/Debug.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// Lets only mobile objects block a line (vtable ELF 0x4BF780, typeinfo names this TU's anonymous +// namespace). +class MobilePredicate : public AIObjectPredicate +{ +public: + // ELF 0x356580 (weak): IAIObject +0x70. + virtual bool predicate(IAIObject* object) { return object->isMobile(); } +}; + +} // namespace + +// ELF 0x352AE0 (C2; C1 0x352C90): the corners; the id is left for the manager. +CoverPosition::CoverPosition(const Vec2& min, const Vec2& max) + : m_min(min) + , m_max(max) +{ +} + +// ELF 0x352EA0 (D1; D2 0x352D80): the set and the two maps go as members. +CoverPosition::~CoverPosition() +{ +} + +// ELF 0x352FC0. Shipped: the found iterator is dereferenced without an end check. +bool CoverPosition::canSee(CoverPosition* other) +{ + std::map::iterator it = m_attackable.find(other->m_id); + return it->second.m_type != ConnectionType::kBlocked && + it->second.m_type != ConnectionType::kUnknown; +} + +// ELF 0x353020. The candidates are this position's corners in Corner order; the first strictly +// better corner value wins, starting from kBlocked. +bool CoverPosition::findHighestVisibilityCorner(CoverPosition* other, Vec2& corner) +{ + bool found = false; + std::map::iterator it = m_attackable.find(other->m_id); + if (it != m_attackable.end()) + { + found = true; + int best = ConnectionType::kBlocked; + std::vector corners; + Vec2 point = m_min; + corners.push_back(point); + point.y = m_max.y; + corners.push_back(point); + point.x = m_max.x; + corners.push_back(point); + point.y = m_min.y; + corners.push_back(point); + corner = point; + for (unsigned int i = 0; i < it->second.m_corners.size(); ++i) + { + if (it->second.m_corners[i] < best) + { + best = it->second.m_corners[i]; + corner = corners[i]; + } + } + } + return found; +} + +// ELF 0x353250. As findHighestVisibilityCorner, starting from kVisible and taking the first +// strictly worse corner. +bool CoverPosition::findLowestVisibilityCorner(CoverPosition* other, Vec2& corner) +{ + bool found = false; + std::map::iterator it = m_attackable.find(other->m_id); + if (it != m_attackable.end()) + { + found = true; + int worst = ConnectionType::kVisible; + std::vector corners; + Vec2 point = m_min; + corners.push_back(point); + point.y = m_max.y; + corners.push_back(point); + point.x = m_max.x; + corners.push_back(point); + point.y = m_min.y; + corners.push_back(point); + corner = point; + for (unsigned int i = 0; i < it->second.m_corners.size(); ++i) + { + if (it->second.m_corners[i] > worst) + { + worst = it->second.m_corners[i]; + corner = corners[i]; + } + } + } + return found; +} + +// ELF 0x353480. +bool CoverPosition::isReachableNeighbour(int index) const +{ + return m_moveNeighbours.find(index) != m_moveNeighbours.end(); +} + +// ELF 0x3534D0. +bool CoverPosition::isAttackableNeighbour(int index) const +{ + return m_attackable.find(index) != m_attackable.end(); +} + +// ELF 0x353520. +bool CoverPosition::isDefendableNeighbour(int index) const +{ + return m_defendable.find(index) != m_defendable.end(); +} + +// ELF 0x353570. Per axis the facing edges when the boxes are apart, else the larger minimum on +// both sides. +float CoverPosition::getShortestDistance(CoverPosition* other) const +{ + float x0; + float x1; + if (m_min.x > other->m_max.x) + { + x0 = m_min.x; + x1 = other->m_max.x; + } + else if (other->m_min.x > m_max.x) + { + x0 = m_max.x; + x1 = other->m_min.x; + } + else + { + x0 = other->m_min.x < m_min.x ? m_min.x : other->m_min.x; + x1 = x0; + } + + float y0; + float y1; + if (m_min.y > other->m_max.y) + { + y0 = m_min.y; + y1 = other->m_max.y; + } + else if (other->m_min.y > m_max.y) + { + y0 = m_max.y; + y1 = other->m_min.y; + } + else + { + y0 = other->m_min.y < m_min.y ? m_min.y : other->m_min.y; + y1 = y0; + } + + return sqrtf((y1 - y0) * (y1 - y0) + (x1 - x0) * (x1 - x0)); +} + +// ELF 0x353660. The end is re-read after every call. +void CoverPosition::updateAttacks(bool force) +{ + std::vector& positions = CoverPositionManager::m_instance->m_coverPositions; + for (std::vector::iterator it = positions.begin(); it != positions.end(); ++it) + { + if (*it != this) + updateAttacks(*it, force); + } +} + +// ELF 0x3536C0 (4.8 KB, most of it the inlined ConnectionType copies). The target corners go +// (min, min), (max, min), (max, max), (min, max); the looking corners in Corner order. The +// overall attack value starts as the first corner's; afterwards it stays only while the corners +// agree and becomes kPartial otherwise. The defend value follows the corners with +// visible -> visible, partial -> partial unless already visible, blocked -> unchanged. Shipped, +// preserved: a link created by this call is left at its defaults unless `force` is set. +void CoverPosition::updateAttacks(CoverPosition* other, bool force) +{ + IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + Vec3 eye = { 0.0f, 0.0f, 0.0f }; + + Vec3 target0; + target0.x = other->m_min.x; + target0.y = terrain->getHeight(other->m_min.x, other->m_min.y) + 0.3f; + target0.z = other->m_min.y; + Vec3 target1; + target1.x = other->m_max.x; + target1.y = terrain->getHeight(other->m_max.x, other->m_min.y) + 0.3f; + target1.z = other->m_min.y; + Vec3 target2; + target2.x = other->m_max.x; + target2.y = terrain->getHeight(other->m_max.x, other->m_max.y) + 0.3f; + target2.z = other->m_max.y; + Vec3 target3; + target3.x = other->m_min.x; + target3.y = terrain->getHeight(other->m_min.x, other->m_max.y) + 0.3f; + target3.z = other->m_max.y; + + std::pair::iterator, bool> attackLink = + m_attackable.insert(std::make_pair(other->m_id, ConnectionType())); + if (!force && attackLink.second) + return; + + std::map::iterator defendLink = + other->m_defendable.insert(std::make_pair(m_id, ConnectionType())).first; + ConnectionType& attack = attackLink.first->second; + ConnectionType& defend = defendLink->second; + + eye.x = m_min.x; + eye.z = m_min.y; + eye.y = terrain->getHeight(m_min.x, m_min.y) + 1.5f; + updateCorner(eye, target0, target1, target2, target3, attack, defend, ConnectionType::kCorner0); + eye.x = m_min.x; + eye.z = m_max.y; + eye.y = terrain->getHeight(m_min.x, m_max.y) + 1.5f; + updateCorner(eye, target0, target1, target2, target3, attack, defend, ConnectionType::kCorner1); + eye.x = m_max.x; + eye.z = m_max.y; + eye.y = terrain->getHeight(m_max.x, m_max.y) + 1.5f; + updateCorner(eye, target0, target1, target2, target3, attack, defend, ConnectionType::kCorner2); + eye.x = m_max.x; + eye.z = m_min.y; + eye.y = terrain->getHeight(m_max.x, m_min.y) + 1.5f; + updateCorner(eye, target0, target1, target2, target3, attack, defend, ConnectionType::kCorner3); + + for (int i = 0; i < 4; ++i) + { + if (attack.m_type == ConnectionType::kUnknown) + { + switch (attack.m_corners[i]) + { + case ConnectionType::kVisible: + attack.m_type = ConnectionType::kVisible; + defend.m_type = ConnectionType::kVisible; + break; + case ConnectionType::kPartial: + attack.m_type = ConnectionType::kPartial; + defend.m_type = ConnectionType::kPartial; + break; + case ConnectionType::kBlocked: + attack.m_type = ConnectionType::kBlocked; + defend.m_type = ConnectionType::kBlocked; + break; + default: + Debug(DebugTypeError, "AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPosition.cpp", 393, "") + << "Unknown connectiontype."; + break; + } + } + else + { + attack.m_type = attack.m_corners[i] == attack.m_type ? attack.m_corners[i] + : ConnectionType::kPartial; + switch (attack.m_corners[i]) + { + case ConnectionType::kVisible: + defend.m_type = ConnectionType::kVisible; + break; + case ConnectionType::kPartial: + defend.m_type = defend.m_type != ConnectionType::kVisible ? ConnectionType::kPartial + : ConnectionType::kVisible; + break; + case ConnectionType::kBlocked: + break; + default: + Debug(DebugTypeError, "AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPosition.cpp", 424, "") + << "Unknown connectiontype."; + break; + } + } + } +} + +// ELF 0x3549A0. Each line is tested with IAIObjectEnvironment::collideLineWithWorld (+0x44, only +// mobile objects block) and stored in both links; the target corners land in line slots 0, 3, 2 +// and 1. +int CoverPosition::updateCorner(const Vec3& eye, const Vec3& corner0, const Vec3& corner1, + const Vec3& corner2, const Vec3& corner3, ConnectionType& attack, + ConnectionType& defend, const ConnectionType::Corner& corner) +{ + IAIObjectEnvironment* const environment = + static_cast(CommonSingletonServer::m_iaiObjectEnvironment); + MobilePredicate predicate; + int clear = 0; + + bool visible = !environment->collideLineWithWorld(eye, corner0, &predicate, 0); + ConnectionType::NeighbourConnection line = visible ? ConnectionType::kVisible : ConnectionType::kBlocked; + attack.m_lines[corner][0] = line; + defend.m_lines[corner][0] = line; + if (visible) + ++clear; + + visible = !environment->collideLineWithWorld(eye, corner1, &predicate, 0); + line = visible ? ConnectionType::kVisible : ConnectionType::kBlocked; + attack.m_lines[corner][3] = line; + defend.m_lines[corner][3] = line; + if (visible) + ++clear; + + visible = !environment->collideLineWithWorld(eye, corner2, &predicate, 0); + line = visible ? ConnectionType::kVisible : ConnectionType::kBlocked; + attack.m_lines[corner][2] = line; + defend.m_lines[corner][2] = line; + if (visible) + ++clear; + + visible = !environment->collideLineWithWorld(eye, corner3, &predicate, 0); + line = visible ? ConnectionType::kVisible : ConnectionType::kBlocked; + attack.m_lines[corner][1] = line; + defend.m_lines[corner][1] = line; + if (visible) + ++clear; + + if (clear == 0) + attack.m_corners[corner] = ConnectionType::kBlocked; + else if (clear == 4) + attack.m_corners[corner] = ConnectionType::kVisible; + else + attack.m_corners[corner] = ConnectionType::kPartial; + defend.m_corners[corner] = attack.m_corners[corner]; + return clear; +} + +// ELF 0x354C10: empty. +void CoverPosition::updateMoveNeighbours() +{ +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPosition.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPosition.h new file mode 100644 index 000000000..8f8332e03 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPosition.h @@ -0,0 +1,108 @@ +// A rectangular cover position and its visibility links to the other positions. +// Evidence: libaidll.so 1.5.3153 (ia-32), attested file +// AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPosition.cpp (the Debug __FILE__ strings and the +// anonymous namespace of MobilePredicate), ELF 0x352AE0..0x354CB0 plus its map / vector +// instantiations up to 0x356670. Size 0x38 (operator new(0x38) in +// CoverPositionManager::createCoverPosition). + +#ifndef AI_AIDLL_AI_AISTRATEGICENTITY_COVERPOSITION_COVERPOSITION_H // [INFERRED] guard style +#define AI_AIDLL_AI_AISTRATEGICENTITY_COVERPOSITION_COVERPOSITION_H + +#include +#include +#include + +#include "../../../../../Math/Vec3.h" // Vec2, Vec3 + +namespace dice { +namespace hfe { +namespace ai { + +// How well one cover position sees another: an overall value, one per corner of the looking +// position, and one per line from each of its corners to each corner of the other. 28 bytes (the +// map node is 0x30). Inline throughout; the default constructor is the inlined +// `-1, resize(4, -1), resize(4, corners)` sequence of CoverPosition::updateAttacks. +class ConnectionType +{ +public: + // [INFERRED] enumerator names; the values are the stored ones. Lines are kVisible or + // kBlocked; a corner is kVisible when all four of its lines are clear, kBlocked when none is, + // else kPartial. + enum NeighbourConnection + { + kUnknown = -1, + kVisible = 0, + kPartial = 1, + kBlocked = 2 + }; + + // The looking position's corners, in the order updateAttacks visits them: (min.x, min.y), + // (min.x, max.y), (max.x, max.y), (max.x, min.y). [INFERRED] enumerator names. + enum Corner + { + kCorner0 = 0, + kCorner1 = 1, + kCorner2 = 2, + kCorner3 = 3 + }; + + ConnectionType() + : m_type(kUnknown) + { + m_corners.resize(4, kUnknown); + m_lines.resize(4, m_corners); + } + + // [INFERRED] names. + /* +0 */ NeighbourConnection m_type; + /* +4 */ std::vector m_corners; + /* +16 */ std::vector > m_lines; +}; + +class CoverPosition +{ +public: + // The two corners are stored as given (CoverPositionManager orders them first). + CoverPosition(const Vec2& min, const Vec2& max); + ~CoverPosition(); + + // Whether this position's link to `other` is neither blocked nor unknown. Looks the link up + // without an end check. + bool canSee(CoverPosition* other); + // The corner of this position that sees `other` best (worst), true when a link to `other` + // exists; `corner` starts as the last corner and is untouched without a link. + bool findHighestVisibilityCorner(CoverPosition* other, Vec2& corner); + bool findLowestVisibilityCorner(CoverPosition* other, Vec2& corner); + bool isReachableNeighbour(int index) const; + bool isAttackableNeighbour(int index) const; + bool isDefendableNeighbour(int index) const; + // The gap between the two boxes (0 where they overlap on both axes). + float getShortestDistance(CoverPosition* other) const; + // updateAttacks(other, force) against every other cover position. + void updateAttacks(bool force); + // Line-of-sight from this position's corners (1.5 above the terrain) to `other`'s (0.3 above), + // stored in this position's attack link to `other` and in `other`'s defend link to this one. + // Without `force` an existing link is recomputed and a new one is left at its defaults. + void updateAttacks(CoverPosition* other, bool force); + // One looking corner against the other position's four corners; answers the clear-line count. + // [INFERRED] int return (the counter is a 32-bit word returned in eax; callers ignore it). + int updateCorner(const Vec3& eye, const Vec3& corner0, const Vec3& corner1, const Vec3& corner2, + const Vec3& corner3, ConnectionType& attack, ConnectionType& defend, + const ConnectionType::Corner& corner); + // Empty in retail: the move-neighbour set is never filled. + void updateMoveNeighbours(); + + // Layout from the constructor (0x352C90); names [INFERRED]. + /* +0 */ Vec2 m_min; + /* +8 */ Vec2 m_max; + /* +16 */ int m_id; // the index in CoverPositionManager; written by createCoverPosition + /* +20 */ std::map m_attackable; // isAttackableNeighbour; keyed by the other's id + /* +32 */ std::map m_defendable; // isDefendableNeighbour + /* +44 */ std::set m_moveNeighbours; // isReachableNeighbour; CPNode's expansion +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGICENTITY_COVERPOSITION_COVERPOSITION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPositionManager.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPositionManager.cpp index 945f741e3..3b1e6ceeb 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPositionManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPositionManager.cpp @@ -1,9 +1,18 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining CoverPositionManager operations. +// CoverPositionManager. Evidence: libaidll.so 1.5.3153 (ia-32), see CoverPositionManager.h. #include "CoverPositionManager.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x359190, __tcf_0 0x3591F0, _GLOBAL__I 0x359220). +#include + +#include +#include + +#include "CPNode.h" +#include "CoverPosition.h" #include "../../AIUtils/checkPointer.h" -#include "../../Main/AIDllFrontier.h" +#include "../../Main/AIRandom.h" namespace dice { namespace hfe { @@ -11,8 +20,8 @@ namespace ai { CoverPositionManager* CoverPositionManager::m_instance = 0; -// Initializes cover-position search resources and their node managers. - +// ELF 0x356680 (C2; C1 0x356F00): the engine, then five search resources (open tree 15, both +// hashes 20) whose ids go to the free list; the first manager becomes the singleton. CoverPositionManager::CoverPositionManager() { m_engine = checkPointer(new CPPathfindingEngine()); @@ -26,16 +35,16 @@ CoverPositionManager::CoverPositionManager() pool->m_searches.push_back(resource); - resource->m_i16 = 0; + resource->m_iterations = 0; resource->m_openSize = 15; resource->m_hashSize = 20; resource->m_open = checkPointer(new BinarySearchTree(15)); - resource->m_closed = checkPointer(new Hash(20)); - resource->m_cache = checkPointer(new Hash(20)); + resource->m_openOverflow = checkPointer(new Hash(20)); + resource->m_closed = checkPointer(new Hash(20)); - resource->m_closed->m_nodeManager = resource->m_nodeManager; - resource->m_cache->m_nodeManager = resource->m_nodeManager; + resource->m_openOverflow->m_nodeManager = resource->m_nodeManager; + resource->m_closed->m_nodeManager = resource->m_nodeManager; pool->m_available.push_back((unsigned int)(pool->m_searches.size() - 1)); } @@ -44,68 +53,299 @@ CoverPositionManager::CoverPositionManager() m_instance = this; } -// [FRONTIER] Cover-position destruction requires cleanup of its search engine and owned positions. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding CoverPositionManager operation. - +// ELF 0x357680 (D1, 337 B; recovered on the client track): the +// singleton is zeroed when it is this one, the CPNode pathfinding engine is deleted, every cover +// position is deleted (CoverPosition D1 0x352EA0 destroys members only) and the vector emptied; +// the distance table and the position vector then go as members. CoverPositionManager::~CoverPositionManager() { - BF2_AI_FRONTIER("dice::hfe::ai::CoverPositionManager::~CoverPositionManager"); + if (m_instance == this) + m_instance = 0; + if (m_engine) + delete m_engine; + for (unsigned int i = 0; i < m_coverPositions.size(); ++i) + delete m_coverPositions[i]; + m_coverPositions.erase(m_coverPositions.begin(), m_coverPositions.end()); } -// - `return m_coverPositions.back;`, with no empty check. On an empty +// ELF 0x357CF0: `return m_coverPositions.back();`, with no empty check. On an empty // vector it reads one element in front of the buffer. Shipped; preserved. CoverPosition* CoverPositionManager::getLastCoverPosition() const { return m_coverPositions.back(); } -// Cover-position search and query operations remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace each stop when the corresponding CoverPosition behavior is recovered. - -CoverPosition* CoverPositionManager::createCoverPosition(const Vec2&, const Vec2&) +// ELF 0x3577E0. The id is the index; the new table row has one zero per position including the +// new one, then the distances to the earlier positions are filled in. +void CoverPositionManager::createCoverPosition(const Vec2& a, const Vec2& b) { - BF2_AI_FRONTIER("dice::hfe::ai::CoverPositionManager::createCoverPosition"); + Vec2 low = a; + Vec2 high = b; + if (high.x < low.x) + { + high.x = a.x; + low.x = b.x; + } + if (high.y < low.y) + { + high.y = a.y; + low.y = b.y; + } + CoverPosition* const position = checkPointer(new CoverPosition(low, high)); + const int id = static_cast(m_coverPositions.size()); + position->m_id = id; + m_coverPositions.push_back(position); + m_distances.push_back(std::vector(id + 1, 0.0f)); + for (int i = 0; i < id; ++i) + m_distances[id][i] = position->getShortestDistance(m_coverPositions[i]); } -void CoverPositionManager::RandomizeCoverPos(Vec2, Vec2, Vec2&) +// ELF 0x357D10. One random draw per axis. +void CoverPositionManager::RandomizeCoverPos(Vec2 low, Vec2 high, Vec2& out) { - BF2_AI_FRONTIER("dice::hfe::ai::CoverPositionManager::RandomizeCoverPos"); + out.x = (high.x - low.x - 2.0f) * AIRandom::m_instance->nextFloat() + low.x + 1.0f; + out.y = (high.y - low.y - 2.0f) * AIRandom::m_instance->nextFloat() + low.y + 1.0f; } -void CoverPositionManager::RandomizeCoverPosAlongEdge(Vec2, Vec2, Vec2&) +// ELF 0x357E70. A first draw picks the edge direction (at least 0.5: along y); the second the +// offset. The step is taken away from the far side when it would leave the box, and the other +// axis moves 1 inward the same way. Shipped asymmetry, preserved: along x the back step is +// `d - 1`, along y it is `d`. +void CoverPositionManager::RandomizeCoverPosAlongEdge(Vec2 low, Vec2 high, Vec2& out) { - BF2_AI_FRONTIER("dice::hfe::ai::CoverPositionManager::RandomizeCoverPosAlongEdge"); + if (AIRandom::m_instance->nextFloat() >= 0.5f) + { + const float d = (high.y - low.y) * AIRandom::m_instance->nextFloat() * 0.5f; + float y = out.y + d; + if (high.y < y) + y = out.y - d; + out.y = y; + float x = out.x + 1.0f; + if (high.x < x) + x = out.x - 1.0f; + out.x = x; + } + else + { + const float d = (high.x - low.x) * AIRandom::m_instance->nextFloat() * 0.5f; + if (out.x + d <= high.x) + out.x = out.x + (d + 1.0f); + else + out.x = out.x - (d - 1.0f); + float y = out.y + 1.0f; + if (high.y < y) + y = out.y - 1.0f; + out.y = y; + } } -bool CoverPositionManager::isInCoverPosition(Vec2) +// ELF 0x3580E0: the first cover position whose box (+0 min, +8 max, bounds inclusive) holds the +// point, or null. The image answers the pointer (`mov (%edx),%edx; mov %edx,-0x40`), not a bool. +CoverPosition* CoverPositionManager::isInCoverPosition(Vec2 point) { - BF2_AI_FRONTIER("dice::hfe::ai::CoverPositionManager::isInCoverPosition"); + for (unsigned int i = 0; i < m_coverPositions.size(); ++i) + { + const Vec2 low = m_coverPositions[i]->m_min; + const Vec2 high = m_coverPositions[i]->m_max; + if (point.x >= low.x && point.y >= low.y && high.x >= point.x && high.y >= point.y) + return m_coverPositions[i]; + } + return 0; } -bool CoverPositionManager::getClosestAttackCoverPosition(const Vec2&, const Vec2&, float, float, - Vec2&) +// ELF 0x3581B0: a cover spot for attacking `to` from `from`. Only when the two are more than 5 +// apart (squared distance > 25): the answer starts as `from`; the reference point is +// from + (to - from) * fraction / 4. Each position whose centre is closer to it than the best so +// far, within maxDistance and within half the squared from-to distance, is found (answer true): +// when `from` is inside its box the answer is `from` (best 0); otherwise the centre, randomized in +// the box (RandomizeCoverPos) - or, when `to` is itself in cover and the position sees that cover +// best from a corner (findHighestVisibilityCorner), a point along that edge. +bool CoverPositionManager::getClosestAttackCoverPosition(const Vec2& from, const Vec2& to, float maxDistance, + float fraction, Vec2& out) { - BF2_AI_FRONTIER("dice::hfe::ai::CoverPositionManager::getClosestAttackCoverPosition"); + bool found = false; + const float dx = to.x - from.x; + const float dy = to.y - from.y; + const float distance = dy * dy + dx * dx; + if (!(distance > 25.0f)) + return found; + float best = 3.40282347e+38f; + out.y = from.y; + out.x = from.x; + Vec2 reference; + reference.x = (to.x - from.x) * fraction * 0.25f + from.x; + reference.y = (to.y - from.y) * fraction * 0.25f + from.y; + CoverPosition* const targetCover = isInCoverPosition(to); + for (unsigned int i = 0; i < m_coverPositions.size(); ++i) + { + CoverPosition* const cover = m_coverPositions[i]; + const Vec2 low = cover->m_min; + const Vec2 high = cover->m_max; + Vec2 centre; + centre.x = low.x + (high.x - low.x) * 0.5f; + centre.y = low.y + (high.y - low.y) * 0.5f; + const float cx = centre.x - reference.x; + const float cy = centre.y - reference.y; + const float d = cx * cx + cy * cy; + if (!(d < best) || !(d < maxDistance * maxDistance) || !(d < distance * 0.5f)) + continue; + found = true; + if (!(from.x < low.x || from.y < low.y || high.x < from.x || high.y < from.y)) + { + out = from; + best = 0.0f; + continue; + } + best = d; + if (targetCover) + { + if (cover->findHighestVisibilityCorner(targetCover, out)) + { + RandomizeCoverPosAlongEdge(low, high, out); + continue; + } + } + out = centre; + RandomizeCoverPos(low, high, out); + } + return found; } -bool CoverPositionManager::getClosestNavCoverPosition(Vec2, Vec2, Vec2&, CoverPosition*&) +// ELF 0x358610. A centre qualifies when it is closer to `from` than the best so far (and more than +// 0.001 away), closer to `to` than `from` is, closer to `from` than `to` is, and - when `from` is +// in cover - seen from that cover (CoverPosition::canSee, asked before the distance tests). The +// answer is the distance to the chosen centre, or from `from` to `to`. +float CoverPositionManager::getClosestNavCoverPosition(Vec2 from, Vec2 to, Vec2& out, + CoverPosition*& cover) { - BF2_AI_FRONTIER("dice::hfe::ai::CoverPositionManager::getClosestNavCoverPosition"); + const float dx = to.x - from.x; + const float dy = to.y - from.y; + const float total = dy * dy + dx * dx; + float best = FLT_MAX; + out.x = to.x; + out.y = to.y; + bool found = false; + CoverPosition* const current = isInCoverPosition(from); + cover = 0; + for (unsigned int i = 0; i < m_coverPositions.size(); ++i) + { + CoverPosition* const position = m_coverPositions[i]; + const Vec2 low = position->m_min; + const Vec2 high = position->m_max; + Vec2 centre; + centre.x = low.x + (high.x - low.x) * 0.5f; + centre.y = low.y + (high.y - low.y) * 0.5f; + bool visible = true; + const float d = (centre.x - from.x) * (centre.x - from.x) + (centre.y - from.y) * (centre.y - from.y); + const float rest = (to.y - centre.y) * (to.y - centre.y) + (to.x - centre.x) * (to.x - centre.x); + if (current != 0) + visible = current->canSee(position); + if (d < best && d > 0.001f && rest < total && d < total && visible) + { + cover = position; + out = centre; + found = true; + best = d; + } + } + if (!found) + best = (to.y - from.y) * (to.y - from.y) + (to.x - from.x) * (to.x - from.x); + return sqrtf(best); } +// ELF 0x3588A0. void CoverPositionManager::finaliseCoverPositions() { - BF2_AI_FRONTIER("dice::hfe::ai::CoverPositionManager::finaliseCoverPositions"); + for (std::vector::iterator it = m_coverPositions.begin(); + it != m_coverPositions.end(); ++it) + { + (*it)->updateAttacks(true); + (*it)->updateMoveNeighbours(); + } } -void CoverPositionManager::updatePathfinding(double) +// ELF 0x358900: the engine's update, inlined. +void CoverPositionManager::updatePathfinding(double budget) { - BF2_AI_FRONTIER("dice::hfe::ai::CoverPositionManager::updatePathfinding"); + m_engine->update(budget); } -int CoverPositionManager::search(int, int) +// ELF 0x358A40. Inlined, in order: take the first free resource for owner 1 (as +// AIPathfinding::acquireResource, without the locking test; none free gives index UINT_MAX, which +// retail then uses), size the node flags, take a start and a goal node from the pool, reset the +// search (counters, open tree, both hashes, node flags), then either finish at once when both name +// the same position (the goal node goes back to the pool) or record the goal, return its node to +// the pool and open the start. One engine update of 10000 then runs; an owned resource is +// released as AIPathfinding::releaseResource does. The start node is not returned. +bool CoverPositionManager::search(int start, int goal) { - BF2_AI_FRONTIER("dice::hfe::ai::CoverPositionManager::search"); + unsigned int resource; + std::list& available = m_engine->m_available; + if (available.empty()) + resource = 0xFFFFFFFFu; + else + { + std::list::iterator first = available.begin(); + resource = *first; + CPAStarResource* const candidate = m_engine->m_searches[resource]; + if (candidate->m_owner < 0) + { + candidate->m_owner = 1; + available.erase(first); + m_engine->m_inFlight.insert(m_engine->m_inFlight.end(), resource); + } + else + resource = 0xFFFFFFFFu; + } + + CPNodeManager* const manager = m_engine->m_searches[resource]->m_nodeManager; + manager->init(); + CPNode* const startNode = manager->getNewNode(0, start); + CPNode* const goalNode = manager->getNewNode(0, goal); + + CPAStarResource* search = m_engine->m_searches[resource]; + search->m_iterations = 0; + search->m_status = astarStatus::kIdle; + search->m_worstOpen = 0; + search->m_open->clear(); + search->m_openOverflow->clear(); + search->m_closed->clear(); + search->m_nodeManager->reset(); + + search = m_engine->m_searches[resource]; + if (startNode->m_key == goalNode->m_key) + { + goalNode->m_next = search->m_nodeManager->m_nodes; + search->m_nodeManager->m_nodes = goalNode; + search->m_status = astarStatus::kFound; + search->m_goal = startNode; + } + else + { + search->m_nodeManager->m_goal = goalNode->m_key->m_id; + goalNode->m_next = search->m_nodeManager->m_nodes; + search->m_nodeManager->m_nodes = goalNode; + search->pushOpenNode(startNode); + search->m_status = astarStatus::kSearching; + } + + m_engine->update(10000.0); + + search = m_engine->m_searches[resource]; + const int status = search->m_status; + if (search->m_owner == 1) + { + search->m_owner = -1; + search = m_engine->m_searches[resource]; + search->m_maxIterations = 0; + search->m_maxSearchDepth = -1; + search->m_nodeManager->returnReset(); + search->m_status = astarStatus::kIdle; + search->m_owner = -1; + m_engine->m_available.insert(m_engine->m_available.end(), resource); + m_engine->m_inFlight.remove(resource); + } + return status == astarStatus::kFound; } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPositionManager.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPositionManager.h index 1cb95051a..167c7f1ec 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPositionManager.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPositionManager.h @@ -1,10 +1,13 @@ -// Owns cover-position search resources and queries. -// [FRONTIER] Remaining queries require the cover-position implementation. +// Owns the cover positions, their distance table and the cover-position A* engine. +// Evidence: libaidll.so 1.5.3153 (ia-32), ELF 0x356680..0x359220 plus the engine's CPNode template +// instantiations up to 0x35BA70. [INFERRED] Placement +// AIStrategicEntity/CoverPosition/CoverPositionManager.cpp (the static-init symbol names +// CoverPositionManager::m_instance). #ifndef AI_AIDLL_AI_AISTRATEGICENTITY_COVERPOSITION_COVERPOSITIONMANAGER_H // [INFERRED] guard style #define AI_AIDLL_AI_AISTRATEGICENTITY_COVERPOSITION_COVERPOSITIONMANAGER_H -#include +#include #include #include "../../../../../Math/Vec3.h" // Vec2 and Vec3 are typedefs, not classes @@ -18,45 +21,56 @@ namespace ai { class CoverPosition; class CPNode; -// [PLATFORM] The original key is a libstdc++ tree iterator unavailable in MSVC. -// [CHOSEN, not recovered] This iterator substitute preserves current object layout; -// search methods must verify its required semantics before use. -typedef std::map::iterator CPSearchKey; - -typedef PathfindingEngine > +// The search key is the move-neighbour iterator CPNode::expandFirst / expand advance +// (std::_Rb_tree_iterator in the mangled names: libstdc++'s +// set iterator); the path type is vector. +typedef PathfindingEngine::const_iterator, std::vector > CPPathfindingEngine; -typedef AStarResource > +typedef AStarResource::const_iterator, std::vector > CPAStarResource; class CoverPositionManager { public: CoverPositionManager(); - ~CoverPositionManager(); // , not virtual + ~CoverPositionManager(); // not virtual - CoverPosition* createCoverPosition(const Vec2&, const Vec2&); + // A new position over the box spanned by the two points (corners ordered per axis), its + // distances to every existing position appended as a new table row. Returns nothing. + void createCoverPosition(const Vec2& a, const Vec2& b); CoverPosition* getLastCoverPosition() const; - void RandomizeCoverPos(Vec2, Vec2, Vec2&); - void RandomizeCoverPosAlongEdge(Vec2, Vec2, Vec2&); - bool isInCoverPosition(Vec2); - bool getClosestAttackCoverPosition(const Vec2&, const Vec2&, float, float, Vec2&); - bool getClosestNavCoverPosition(Vec2, Vec2, Vec2&, CoverPosition*&); + // Moves `out` to a random point at least 1 inside the box. + void RandomizeCoverPos(Vec2 low, Vec2 high, Vec2& out); + // Moves `out` (a corner) along one of the box's edges by a random fraction of half its length. + void RandomizeCoverPosAlongEdge(Vec2 low, Vec2 high, Vec2& out); + CoverPosition* isInCoverPosition(Vec2 point); // the containing position, not a bool + bool getClosestAttackCoverPosition(const Vec2& from, const Vec2& to, float maxDistance, + float fraction, Vec2& out); + // The closest cover centre between `from` and `to` that the cover `from` is in can see; + // answers the distance to it (or to `to` when none qualifies). + float getClosestNavCoverPosition(Vec2 from, Vec2 to, Vec2& out, CoverPosition*& cover); void finaliseCoverPositions(); - void updatePathfinding(double); - int search(int, int); + void updatePathfinding(double budget); + // A synchronous search between two cover positions; true when it reached the goal. + bool search(int start, int goal); + + // [INFERRED] Inline accessor for the lower-triangular distance table, as the CPNode search + // reads it (m_distances[larger][smaller]). + float getDistance(int a, int b) const + { + return a > b ? m_distances[a][b] : m_distances[b][a]; + } // dice's own capitalisation on the two `Randomize*` methods - initial capital, and the // American spelling next to `finaliseCoverPositions`'s British one, in the same class. static CoverPositionManager* m_instance; -private: - // layout, , read from the constructor and confirmed by the destructor + // Layout from the constructor and destructor; names [INFERRED]. Public: CPNode, + // CPNodeManager and CoverPosition read the positions through m_instance. /* +0 */ std::vector m_coverPositions; - // Never touched by the constructor; the destructor frees the inner buffers with a 12-byte - // stride, so the elements are vectors of a four-byte type. Which type is [UNRESOLVED] - the - // readers are `search` and `getClosestNavCoverPosition`, both frontiers. - /* +12 */ std::vector > m_v12; + // Row i holds the distances from position i to positions 0..i (createCoverPosition). + /* +12 */ std::vector > m_distances; /* +24 */ CPPathfindingEngine* m_engine; }; diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPosition.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPosition.cpp new file mode 100644 index 000000000..1b1556460 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPosition.cpp @@ -0,0 +1,210 @@ +// Guard positions. Evidence: libaidll.so (ia-32) 0x34EDB0..0x34FA8F. +// [INFERRED] Source placement. + +#include "GuardPosition.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x34F9E0, __tcf_0 0x34FA40, _GLOBAL__I 0x34FA70). +#include +#include + +#include "GuardPositionBotDCB.h" +#include "GuardPositionBotSCB.h" +#include "AIStrategicObject.h" +#include "AIStrategicObjectManager.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/WPMoveTo.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AIMain.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFGameEffector.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" + +namespace dice { namespace hfe { namespace ai { + +// ELF 0x34EDB0 (C2; C1 0x34EE70). +GuardPosition::GuardPosition(const Vec2& position, CombatStrengthType strengthType, int side, + int kit) + : m_strengthType(strengthType) + , m_active(true) + , m_side(side) + , m_kit(kit) + , m_minDistance(5.0f) + , m_bot(0) + , m_recruited(false) +{ + m_position.x = 0.0f; + m_position.y = 0.0f; + m_position.z = 0.0f; + m_rotation.x = 1.0f; + m_rotation.y = 0.0f; + m_rotation.z = 0.0f; + vec2ToVec3XZ(position, m_position); + m_position.y = static_cast(CommonSingletonServer::m_iaiTerrain) + ->getHeight(position.x, position.y) + 1.0f; +} + +// ELF 0x34EF30 (D2; D1 0x34EFE0). +GuardPosition::~GuardPosition() +{ +} + +// ELF 0x34F090. +CombatStrengthType GuardPosition::getStrengthType() const +{ + return m_strengthType; +} + +// ELF 0x34F0A0. +const Vec3& GuardPosition::getPosition() const +{ + return m_position; +} + +// ELF 0x34F0B0. +void GuardPosition::setRotation(const Vec3& rotation) +{ + m_rotation = rotation; +} + +// ELF 0x34F0F0. +const Vec3& GuardPosition::getRotation() const +{ + return m_rotation; +} + +// ELF 0x34F100. +void GuardPosition::setActive(bool active) +{ + m_active = active; +} + +// ELF 0x34F110. +bool GuardPosition::getActive() const +{ + return m_active; +} + +// ELF 0x34F120: the same load as getActive. +bool GuardPosition::active() const +{ + return m_active; +} + +// ELF 0x34F130. +void GuardPosition::setSide(int side) +{ + m_side = side; +} + +// ELF 0x34F140. +int GuardPosition::getSide() const +{ + return m_side; +} + +// ELF 0x34F150. +void GuardPosition::setMinDistance(float distance) +{ + m_minDistance = distance; +} + +// ELF 0x34F160. +float GuardPosition::getMinDistance() const +{ + return m_minDistance; +} + +// ELF 0x34F170. +bool GuardPosition::needBot() const +{ + return !m_recruited && m_bot == 0; +} + +// ELF 0x34F190. +void GuardPosition::recruit(Bot* bot) +{ + bot->setDeathCallBack(checkPointer(new GuardPositionBotDCB(bot, this))); + bot->setSpawnCallBack(checkPointer(new GuardPositionBotSCB(bot, this))); + m_bot = bot; + m_recruited = true; + if (bot->isDead()) + { + bot->setIsInTransitionPhase(true); + spawnBot(bot); + } + else + botIsAlive(bot); +} + +// ELF 0x34F4A0. A one-point path to the position: radius m_minDistance, step radius 60, flags 1, +// no last area. +void GuardPosition::botIsAlive(Bot* bot) +{ + std::list path; + path.push_back(m_position); + bot->setWaypoints(checkPointer(new WPMoveTo(m_minDistance, 60.0f, 1, path, -1))); +} + +// ELF 0x34F760. +void GuardPosition::botIsDead(Bot* bot) +{ + bot->setIsInTransitionPhase(true); + lostBot(); +} + +// ELF 0x34F7A0. IAIGameEffector::forceSpawnBot (+0x20) with the position and the facing. +void GuardPosition::spawnBot(Bot* bot) +{ + bot->setSpawnTarget(1, m_kit); + static_cast(CommonSingletonServer::m_iaiGameEffector) + ->forceSpawnBot(bot->getPlayer(), m_position, m_rotation); +} + +// ELF 0x34F820. IAIMain::registerFreeBot (+0x10). +void GuardPosition::lostBot() +{ + IAIMain::m_instance->registerFreeBot(m_bot); + m_bot = 0; +} + +// ELF 0x34F870. The object found by index is not null-tested; one found by name is, and an +// unknown name keeps the condition unresolved for the next update. +void GuardPosition::update() +{ + if (!m_bot) + return; + AIStrategicObjectManager* const manager = AIStrategicObjectManager::getInstance(); + for (std::vector::iterator it = m_areaConditions.begin(); + it != m_areaConditions.end(); ++it) + { + AIStrategicObject* object; + if (it->areaIndex == -1) + { + object = manager->getStrategicObject(it->areaName); + if (!object) + continue; + it->areaIndex = object->getIndex(); + } + else + object = manager->getStrategicObject(it->areaIndex); + if (object->getStatus(m_side) == it->status) + { + lostBot(); + return; + } + } +} + +// ELF 0x34F920. +void GuardPosition::addStrategicAreaAbortCondition(const std::string& areaName, + StatusMap::Status status) +{ + AreaCondition condition; + condition.areaName = areaName; + condition.areaIndex = -1; + condition.status = status; + m_areaConditions.push_back(condition); +} + +} } } diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPosition.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPosition.h index 68962a4ca..9bfcff03c 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPosition.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPosition.h @@ -16,19 +16,38 @@ enum CombatStrengthType : int; class GuardPosition { public: - // Attested signatures, declaration-only: no default or fixture constructor in production. - GuardPosition(const Vec2&, CombatStrengthType, int side, int value36); - // > : only AreaCondition vector/string cleanup. - // The borrowed bot is not deleted and no callback is invoked. - ~GuardPosition() = default; - - bool active() const { return m_active; } // byte +28 - int getSide() const { return m_side; } // int +32 - bool needBot() const - { - // Both images test the byte first. Neither active nor side participates in this predicate. - return !m_flag48 && m_bot == 0; - } + // The position is `position` on the terrain, one metre up; the facing starts at (1, 0, 0). + GuardPosition(const Vec2& position, CombatStrengthType strengthType, int side, int kit); + // Member cleanup only: the borrowed bot is not deleted and no callback is invoked. + ~GuardPosition(); + + CombatStrengthType getStrengthType() const; + const Vec3& getPosition() const; + void setRotation(const Vec3& rotation); + const Vec3& getRotation() const; + void setActive(bool active); + bool getActive() const; + bool active() const; + void setSide(int side); + int getSide() const; + void setMinDistance(float distance); + float getMinDistance() const; + // True while no bot was ever recruited: the recruited flag is tested before the bot. + bool needBot() const; + // Takes `bot`: installs this position's death and spawn callbacks, then either spawns a dead + // bot here or sends a living one on its way. + void recruit(Bot* bot); + // Gives the bot a waypoint list that walks to the position. + void botIsAlive(Bot* bot); + void botIsDead(Bot* bot); + // Sets the bot's spawn target (group 1, this position's kit) and force-spawns it here. + void spawnBot(Bot* bot); + // Hands the bot back to the bot pool. The recruited flag stays set. + void lostBot(); + // Releases the bot when any abort condition holds: an area of the position's side with the + // condition's status. Area indices are resolved by name on first use. + void update(); + void addStrategicAreaAbortCondition(const std::string& areaName, StatusMap::Status status); private: // Area abort condition. New entries start with areaIndex -1. @@ -46,10 +65,10 @@ class GuardPosition /* +24 */ CombatStrengthType m_strengthType; /* +28 */ bool m_active; /* +32 */ int m_side; - /* +36 */ int m_value36; // [UNRESOLVED] constructor's final parameter + /* +36 */ int m_kit; // spawnBot's setSpawnTarget kit [INFERRED name] /* +40 */ float m_minDistance; /* +44 */ Bot* m_bot; - /* +48 */ bool m_flag48; // [UNRESOLVED] name; recruit sets true + /* +48 */ bool m_recruited; // [INFERRED] name; recruit sets it, nothing clears it /* +52 */ std::vector m_areaConditions; }; diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPositionBotDCB.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPositionBotDCB.cpp new file mode 100644 index 000000000..0350c3924 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPositionBotDCB.cpp @@ -0,0 +1,32 @@ +// GuardPositionBotDCB. Evidence: libaidll.so (ia-32) 0x..0x34FFA0. +// [INFERRED] Source placement. + +#include "GuardPositionBotDCB.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x34FF40, __tcf_0 0x34FFA0, _GLOBAL__I 0x34FFD0). +#include + +#include "GuardPosition.h" + +namespace dice { namespace hfe { namespace ai { + +// ELF 0x (C2; C1 0x34FDB0). +GuardPositionBotDCB::GuardPositionBotDCB(Bot* bot, GuardPosition* guardPosition) + : IBotDeathCallBack(bot) + , m_guardPosition(guardPosition) +{ +} + +// ELF 0x34FE00 (D2; D1 0x34FE50, D0 0x34FE90). +GuardPositionBotDCB::~GuardPositionBotDCB() +{ +} + +// ELF 0x34FED0. Neither pointer is tested. +void GuardPositionBotDCB::reportDeath() +{ + m_guardPosition->botIsDead(m_bot); +} + +} } } diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPositionBotDCB.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPositionBotDCB.h new file mode 100644 index 000000000..89db438e4 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPositionBotDCB.h @@ -0,0 +1,27 @@ +// Hands the bot's death to its guard position. +// Placement is [INFERRED]; the class has its own TU in the image. +#ifndef AI_AIDLL_AI_AISTRATEGICENTITY_GUARDPOSITIONBOTDCB_H +#define AI_AIDLL_AI_AISTRATEGICENTITY_GUARDPOSITIONBOTDCB_H + +#include "../AIBot/BotCallBack.h" + +namespace dice { namespace hfe { namespace ai { + +class Bot; +class GuardPosition; + +class GuardPositionBotDCB : public IBotDeathCallBack +{ +public: + // The guard position is borrowed, not owned. + GuardPositionBotDCB(Bot* bot, GuardPosition* guardPosition); + virtual ~GuardPositionBotDCB(); + virtual void reportDeath(); + +private: + /* +8 */ GuardPosition* m_guardPosition; +}; + +} } } + +#endif diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPositionBotSCB.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPositionBotSCB.cpp new file mode 100644 index 000000000..124982677 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPositionBotSCB.cpp @@ -0,0 +1,32 @@ +// GuardPositionBotSCB. Evidence: libaidll.so (ia-32) 0x..0x3501E0. +// [INFERRED] Source placement. + +#include "GuardPositionBotSCB.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x350180, __tcf_0 0x3501E0, _GLOBAL__I 0x350210). +#include + +#include "GuardPosition.h" + +namespace dice { namespace hfe { namespace ai { + +// ELF 0x (C2; C1 0x34FFF0). +GuardPositionBotSCB::GuardPositionBotSCB(Bot* bot, GuardPosition* guardPosition) + : IBotSpawnCallBack(bot) + , m_guardPosition(guardPosition) +{ +} + +// ELF 0x350040 (D2; D1 0x350090, D0 0x3500D0). +GuardPositionBotSCB::~GuardPositionBotSCB() +{ +} + +// ELF 0x350110. Neither pointer is tested. +void GuardPositionBotSCB::reportSpawn() +{ + m_guardPosition->botIsAlive(m_bot); +} + +} } } diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPositionBotSCB.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPositionBotSCB.h new file mode 100644 index 000000000..6b689bfad --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPositionBotSCB.h @@ -0,0 +1,27 @@ +// Hands the bot's spawn to its guard position. +// Placement is [INFERRED]; the class has its own TU in the image. +#ifndef AI_AIDLL_AI_AISTRATEGICENTITY_GUARDPOSITIONBOTSCB_H +#define AI_AIDLL_AI_AISTRATEGICENTITY_GUARDPOSITIONBOTSCB_H + +#include "../AIBot/BotCallBack.h" + +namespace dice { namespace hfe { namespace ai { + +class Bot; +class GuardPosition; + +class GuardPositionBotSCB : public IBotSpawnCallBack +{ +public: + // The guard position is borrowed, not owned. + GuardPositionBotSCB(Bot* bot, GuardPosition* guardPosition); + virtual ~GuardPositionBotSCB(); + virtual void reportSpawn(); + +private: + /* +8 */ GuardPosition* m_guardPosition; +}; + +} } } + +#endif diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPath.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPath.cpp new file mode 100644 index 000000000..1e8eb5163 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPath.cpp @@ -0,0 +1,209 @@ +// PatrolPath. Evidence: libaidll.so (ia-32) 0x350230..0x350F80. +// [INFERRED] Source placement. + +#include "PatrolPath.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x350ED0, __tcf_0 0x350F30, _GLOBAL__I 0x350F60). +#include + +#include "PatrolPathBotDCB.h" +#include "PatrolPathBotSCB.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/WPPatrol.h" +#include "../AIStrategicMap/BotSpawner.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" // IAITerrain::getTerrainAltitude + +namespace dice { namespace hfe { namespace ai { + +// ELF 0x350230 (C2; C1 0x350360): active, minimum distance 1, patrol speed -1. +PatrolPath::PatrolPath(CombatStrengthType strengthType, int side) + : m_path() + , m_strengthType(strengthType) + , m_active(true) + , m_side(side) + , m_currentResources(0) + , m_requiredResources(0) + , m_minDistance(1.0f) + , m_patrolSpeed(-1.0f) + , m_bots() +{ +} + +// ELF 0x3503E0 (C2; C1 0x3504C0). +PatrolPath::PatrolPath(const std::vector& path, CombatStrengthType strengthType, int side) + : m_path(path) + , m_strengthType(strengthType) + , m_active(true) + , m_side(side) + , m_currentResources(0) + , m_requiredResources(0) + , m_minDistance(1.0f) + , m_patrolSpeed(-1.0f) + , m_bots() +{ +} + +// ELF 0x3505A0 (D2; D1 0x350620). +PatrolPath::~PatrolPath() +{ +} + +// ELF 0x3506A0. +CombatStrengthType PatrolPath::getStrengthType() const +{ + return m_strengthType; +} + +// ELF 0x3506B0. +const std::vector& PatrolPath::getPath() const +{ + return m_path; +} + +// ELF 0x3506C0. +void PatrolPath::addPathPoint(const Vec3& point) +{ + m_path.push_back(point); +} + +// ELF 0x350730. +void PatrolPath::addPathPoint(const Vec2& point) +{ + Vec3 position; + position.x = point.x; + position.y = static_cast(CommonSingletonServer::m_iaiTerrain) + ->getTerrainAltitude(point.x, point.y) + 3.0f; + position.z = point.y; + m_path.push_back(position); +} + +// ELF 0x3507E0. +void PatrolPath::setActive(bool active) +{ + m_active = active; +} + +// ELF 0x3507F0. +bool PatrolPath::getActive() const +{ + return m_active; +} + +// ELF 0x350800. +bool PatrolPath::active() const +{ + return m_active; +} + +// ELF 0x350810. +void PatrolPath::setSide(int side) +{ + m_side = side; +} + +// ELF 0x350820. +int PatrolPath::getSide() const +{ + return m_side; +} + +// ELF 0x350830. +void PatrolPath::setMinDistance(float distance) +{ + m_minDistance = distance; +} + +// ELF 0x350840. +float PatrolPath::getMinDistance() const +{ + return m_minDistance; +} + +// ELF 0x350850. +void PatrolPath::setPatrolSpeed(float speed) +{ + m_patrolSpeed = speed; +} + +// ELF 0x350860. +float PatrolPath::getPatrolSpeed() const +{ + return m_patrolSpeed; +} + +// ELF 0x350870. +void PatrolPath::setRequiredResources(int resources) +{ + m_requiredResources = resources; +} + +// ELF 0x350880. +int PatrolPath::getRequiredResources() const +{ + return m_requiredResources; +} + +// ELF 0x350890. +int PatrolPath::neededResources() const +{ + return m_requiredResources - m_currentResources; +} + +// ELF 0x3508A0. +void PatrolPath::recruit(Bot* bot) +{ + bot->setDeathCallBack(checkPointer(new PatrolPathBotDCB(bot, this))); + bot->setSpawnCallBack(checkPointer(new PatrolPathBotSCB(bot, this))); + if (bot->isDead()) + botIsDead(bot); + else + botIsAlive(bot); + ++m_currentResources; + m_bots.push_back(bot); +} + +// ELF 0x350BF0: a patrol over the path with this patrol's minimum distance as its radius and +// flags 5; the patrol speed goes to its +8 before the bot takes it. +void PatrolPath::botIsAlive(Bot* bot) +{ + WPPatrol* const patrol = checkPointer(new WPPatrol(m_minDistance, 5, m_path)); + patrol->m_float8 = m_patrolSpeed; + bot->setWaypoints(patrol); +} + +// ELF 0x350D70: a respawn group near the first path point; the result is unused. +void PatrolPath::botIsDead(Bot* bot) +{ + bot->setIsInTransitionPhase(true); + BotSpawner::findSuitableSpawnGroup(m_path[0], bot); +} + +// ELF 0x350DC0. Shipped defect, preserved: the current resources are incremented, not +// decremented. The first list entry for the bot is erased. +void PatrolPath::lost(Bot* bot) +{ + ++m_currentResources; + for (std::list::iterator it = m_bots.begin(); it != m_bots.end(); ++it) + { + if (*it == bot) + { + m_bots.erase(it); + return; + } + } +} + +// ELF 0x350E50: every dead bot in the list goes through botIsDead. +void PatrolPath::update() +{ + for (std::list::iterator it = m_bots.begin(); it != m_bots.end(); ++it) + { + if ((*it)->isDead()) + botIsDead(*it); + } +} + +} } } diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPath.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPath.h index f666cc113..9cc96bc15 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPath.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPath.h @@ -1,4 +1,4 @@ -// Patrol route and bot recruitment state. +// Patrol route and bot recruitment state (libaidll.so PatrolPath.cpp, 0x350230..0x350F80). // [INFERRED] Source placement. #ifndef AI_AIDLL_AI_AISTRATEGICENTITY_PATROLPATH_H #define AI_AIDLL_AI_AISTRATEGICENTITY_PATROLPATH_H @@ -15,20 +15,39 @@ enum CombatStrengthType : int; class PatrolPath { public: - // Attested signatures, declaration-only: no default or fixture constructor in production. - PatrolPath(CombatStrengthType, int side); - PatrolPath(const std::vector&, CombatStrengthType, int); - // list nodes/sentinel, then the Vec3 vector buffer. - // Ordinary reverse member destruction; bot pointers in the list are not deleted. - ~PatrolPath() = default; - - bool active() const { return m_active; } // +16 / +20 - int getSide() const { return m_side; } // +20 / +24 - int neededResources() const - { - // Signed required-minus-current, with no clamp. recruitBot tests the result > 0. - return m_requiredResources - m_currentResources; - } + PatrolPath(CombatStrengthType strengthType, int side); // ELF 0x350230 (C2; C1 0x350360) + PatrolPath(const std::vector& path, CombatStrengthType strengthType, int side); + // ELF 0x3503E0 (C2; C1 0x3504C0) + // Ordinary member destruction; bot pointers in the list are not deleted. + ~PatrolPath(); // ELF 0x3505A0 (D2; D1 0x350620) + + CombatStrengthType getStrengthType() const; + const std::vector& getPath() const; + void addPathPoint(const Vec3& point); + // The terrain height under the point, three metres up. + void addPathPoint(const Vec2& point); + void setActive(bool active); + bool getActive() const; + bool active() const; // the same load as getActive + void setSide(int side); + int getSide() const; + void setMinDistance(float distance); + float getMinDistance() const; + void setPatrolSpeed(float speed); + float getPatrolSpeed() const; + void setRequiredResources(int resources); + int getRequiredResources() const; + // Signed required-minus-current, with no clamp. recruitBot tests the result > 0. + int neededResources() const; + + // Installs the death/spawn callbacks, starts the patrol (or handles the dead bot) and + // counts the bot in. + void recruit(Bot* bot); + void botIsAlive(Bot* bot); + void botIsDead(Bot* bot); + // As shipped, losing a bot also increments the current resources. + void lost(Bot* bot); + void update(); private: // Member names [INFERRED] from the constructor, getters and recruitment increment. diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPathBotDCB.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPathBotDCB.cpp new file mode 100644 index 000000000..5b60eb587 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPathBotDCB.cpp @@ -0,0 +1,32 @@ +// PatrolPathBotDCB. Evidence: libaidll.so (ia-32) 0x351090..0x3512B0. +// [INFERRED] Source placement. + +#include "PatrolPathBotDCB.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x351220, __tcf_0 0x351280, _GLOBAL__I 0x3512B0). +#include + +#include "PatrolPath.h" + +namespace dice { namespace hfe { namespace ai { + +// ELF 0x351090 (C2; C1 0x3510E0). +PatrolPathBotDCB::PatrolPathBotDCB(Bot* bot, PatrolPath* patrolPath) + : IBotDeathCallBack(bot) + , m_patrolPath(patrolPath) +{ +} + +// ELF 0x351130 (D2; D1 0x351170, D0 0x3511B0). +PatrolPathBotDCB::~PatrolPathBotDCB() +{ +} + +// ELF 0x3511F0. Neither pointer is tested. +void PatrolPathBotDCB::reportDeath() +{ + m_patrolPath->botIsDead(m_bot); +} + +} } } diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPathBotDCB.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPathBotDCB.h new file mode 100644 index 000000000..3623fba79 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPathBotDCB.h @@ -0,0 +1,28 @@ +// Hands the bot's death to its patrol path. +// Placement is [INFERRED]; the class has its own TU in the image. + +#ifndef AI_AIDLL_AI_AISTRATEGICENTITY_PATROLPATHBOTDCB_H +#define AI_AIDLL_AI_AISTRATEGICENTITY_PATROLPATHBOTDCB_H + +#include "../AIBot/BotCallBack.h" + +namespace dice { namespace hfe { namespace ai { + +class Bot; +class PatrolPath; + +class PatrolPathBotDCB : public IBotDeathCallBack +{ +public: + // The patrol path is borrowed, not owned. + PatrolPathBotDCB(Bot* bot, PatrolPath* patrolPath); + virtual ~PatrolPathBotDCB(); + virtual void reportDeath(); + +private: + /* +8 */ PatrolPath* m_patrolPath; +}; + +} } } + +#endif diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPathBotSCB.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPathBotSCB.cpp new file mode 100644 index 000000000..bcc095cf0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPathBotSCB.cpp @@ -0,0 +1,32 @@ +// PatrolPathBotSCB. Evidence: libaidll.so (ia-32) 0x3512D0..0x3514F0. +// [INFERRED] Source placement. + +#include "PatrolPathBotSCB.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x351460, __tcf_0 0x3514C0, _GLOBAL__I 0x3514F0). +#include + +#include "PatrolPath.h" + +namespace dice { namespace hfe { namespace ai { + +// ELF 0x3512D0 (C2; C1 0x351320). +PatrolPathBotSCB::PatrolPathBotSCB(Bot* bot, PatrolPath* patrolPath) + : IBotSpawnCallBack(bot) + , m_patrolPath(patrolPath) +{ +} + +// ELF 0x351370 (D2; D1 0x3513B0, D0 0x3513F0). +PatrolPathBotSCB::~PatrolPathBotSCB() +{ +} + +// ELF 0x351430. Neither pointer is tested. +void PatrolPathBotSCB::reportSpawn() +{ + m_patrolPath->botIsAlive(m_bot); +} + +} } } diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPathBotSCB.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPathBotSCB.h new file mode 100644 index 000000000..626371bcb --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPathBotSCB.h @@ -0,0 +1,28 @@ +// Hands the bot's spawn to its patrol path. +// Placement is [INFERRED]; the class has its own TU in the image. + +#ifndef AI_AIDLL_AI_AISTRATEGICENTITY_PATROLPATHBOTSCB_H +#define AI_AIDLL_AI_AISTRATEGICENTITY_PATROLPATHBOTSCB_H + +#include "../AIBot/BotCallBack.h" + +namespace dice { namespace hfe { namespace ai { + +class Bot; +class PatrolPath; + +class PatrolPathBotSCB : public IBotSpawnCallBack +{ +public: + // The patrol path is borrowed, not owned. + PatrolPathBotSCB(Bot* bot, PatrolPath* patrolPath); + virtual ~PatrolPathBotSCB(); + virtual void reportSpawn(); + +private: + /* +8 */ PatrolPath* m_patrolPath; +}; + +} } } + +#endif diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/SAWayPoint.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/SAWayPoint.cpp index 29ca657e9..f38719cdd 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/SAWayPoint.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/SAWayPoint.cpp @@ -1,10 +1,13 @@ +// Strategic-area waypoints. Evidence: libaidll.so (ia-32) 0x34E980..0x34EDAF. // [INFERRED] Source placement. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining SAWayPoint operations. #include "SAWayPoint.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x34ED00, __tcf_0 0x34ED60, _GLOBAL__I 0x34ED90). +#include + #include "../DrawPrimitives/DPManager.h" -#include "../Main/AIDllFrontier.h" #include "../Main/CommonSingletonServer.h" #include "../Main/IAIPathfinding.h" @@ -12,7 +15,7 @@ namespace dice { namespace hfe { namespace ai { -// Five stores and no allocation. +// ELF 0x34E980 (C2; C1 0x34E9C0). Five stores and no allocation. SAWayPoint::SAWayPoint(const Vec3& position, int map) : m_position(position) , m_island(0xFFFFFFFFu) // 1, written as the dword the constructor stores @@ -22,13 +25,13 @@ SAWayPoint::SAWayPoint(const Vec3& position, int map) { } -// Removes the waypoint's debug primitive; the waypoint owns no other heap resources. +// ELF 0x34EA00 (D2; D1 0x34EA30). Removes the waypoint's debug primitive; the waypoint owns no other heap resources. SAWayPoint::~SAWayPoint() { undraw(); } -// Resolves the waypoint polygon with search mode 3 on the trace map and 0 otherwise. +// ELF 0x34EA60. Resolves the waypoint polygon with search mode 3 on the trace map and 0 otherwise. // Requires the pathfinder singleton and preserves its separate reads for query and search. void SAWayPoint::init() { @@ -40,7 +43,7 @@ void SAWayPoint::init() 3 * (traceMap == m_map)); } -// Deletes the debug circle when present and clears its handle unconditionally. +// ELF 0x34ECB0. Deletes the debug circle when present and clears its handle unconditionally. // Safe to repeat after an earlier undraw call. void SAWayPoint::undraw() const { @@ -53,11 +56,36 @@ void SAWayPoint::undraw() const m_debugPrimitive = 0; } -// [FRONTIER] Waypoint drawing requires the remaining primitive-manager interfaces. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding SAWayPoint operation. +// ELF 0x34EAD0. A debug circle at the waypoint: red while it has no polygon, green once resolved; +// draw type 6 on the trace map, 4 otherwise. The first call creates the circle, later calls +// update it in place. void SAWayPoint::draw() const { - BF2_AI_FRONTIER("dice::hfe::ai::SAWayPoint::draw"); + const int type = (IAIPathfinding::instance->getTraceMapIndex() == m_map) ? 6 : 4; + Vec3 normal; + if (!m_debugPrimitive) + { + const unsigned int colour = (m_polygon == 0xFFFFFFFFu) ? 0xFFBB0000u : 0xFF00BB00u; + normal.x = 0.0f; + normal.y = 1.0f; + normal.z = 0.0f; + // DPStaticCircle derives singly from DrawPrimitive (its typeinfo is a + // __si_class_type_info on DrawPrimitive) and the image stores the pointer unadjusted; + // neither class is defined in this tree, hence the cast. [CHOSEN, not recovered] + m_debugPrimitive = reinterpret_cast( + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticCircle(1.0e9f, colour, m_position, 1.0f, normal, false, type)); + } + else + { + const unsigned int colour = (m_polygon == 0xFFFFFFFFu) ? 0xFFBB0000u : 0xFF00BB00u; + normal.x = 0.0f; + normal.y = 1.0f; + normal.z = 0.0f; + static_cast(CommonSingletonServer::m_iDPManager) + ->setCircleAttributes(m_debugPrimitive, 1.0e9f, colour, m_position, 1.0f, normal, + false, type); + } } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/SAWayPoint.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/SAWayPoint.h index 1dd72315c..15ab8eb52 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/SAWayPoint.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/SAWayPoint.h @@ -1,5 +1,4 @@ // Strategic-area waypoint and its resolved navigation position. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. // [INFERRED] Source placement. #ifndef AI_AIDLL_AI_AISTRATEGICENTITY_SAWAYPOINT_H // [INFERRED] guard style @@ -22,9 +21,14 @@ class SAWayPoint // [INFERRED] Initializes the waypoint polygon; no result is returned to its caller. void init(); - void draw() const; // [FRONTIER] + void draw() const; void undraw() const; + // [INFERRED] accessor forms; AIStrategicArea::orderNormalBot (ELF 0x33C940) reads +0 (the + // position) and tests +0x10 against -1 inline. + const Vec3& getPosition() const { return m_position; } + unsigned int getPolygon() const { return m_polygon; } + private: // layout, on the ELF, read store by store out of the constructor /* +0 */ Vec3 m_position; // the constructor's first argument diff --git a/Code/BF2/AI/AIDLL/AI/Main/UserOrderManager.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/UserOrders/UserOrderManager.cpp similarity index 51% rename from Code/BF2/AI/AIDLL/AI/Main/UserOrderManager.cpp rename to Code/BF2/AI/AIDLL/AI/AIStrategicEntity/UserOrders/UserOrderManager.cpp index 53c8a165a..862acad81 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/UserOrderManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/UserOrders/UserOrderManager.cpp @@ -1,10 +1,12 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining UserOrderManager operations. +// Source placement: AIDLL_r.dll __FILE__ "Code\BF2\AI\AIDLL\AI\AIStrategicEntity\UserOrders\UserOrderManager.cpp" (asserts in 0x1007C7E0 / 0x1007C920). +// static init: ELF 0x3521D0 (__tcf_0 0x352230, _GLOBAL__I 0x352260): 's Init object only. +#include #include "UserOrderManager.h" -#include "AIDllFrontier.h" -#include "../AIStrategicEntity/GuardPosition.h" -#include "../AIStrategicEntity/PatrolPath.h" +#include "../../AIUtils/checkPointer.h" +#include "../GuardPosition.h" +#include "../PatrolPath.h" namespace dice { namespace hfe { @@ -13,7 +15,7 @@ namespace ai { // ds:, plain .bss. UserOrderManager* UserOrderManager::m_instance = 0; -// Initializes patrol-path and guard-position maps and registers the order manager. +// ELF 0x351510 / 0x351690. Initializes maps and registers the first order manager. UserOrderManager::UserOrderManager() : m_activePatrolPath(0) , m_patrolCursor(m_patrolPaths.end()) @@ -26,7 +28,7 @@ UserOrderManager::UserOrderManager() m_instance = this; } -// Deletes owned patrol paths before guard positions, advancing iterators after deletion +// ELF 0x351750 / 0x351900. Deletes patrol paths before guard positions, advancing after deletion // and re-reading end(). Clears a matching singleton after pointee cleanup; map members // then release their nodes in reverse declaration order. UserOrderManager::~UserOrderManager() @@ -46,54 +48,85 @@ UserOrderManager::~UserOrderManager() // the four accessors, 10- each // Each hands out a reference or a raw pointer straight into a member, with no copy and no guard. +// ELF 0x351D30. PatrolPath* UserOrderManager::getActivePatrolPath() const { return m_activePatrolPath; } +// ELF 0x351FE0. GuardPosition* UserOrderManager::getActiveGuardPosition() const { // Indeterminate until something assigns it - see the constructor. return m_activeGuardPosition; } +// ELF 0x3520F0. const std::map& UserOrderManager::getPatrolPaths() const { return m_patrolPaths; } +// ELF 0x351FD0. const std::map& UserOrderManager::getGuardPositions() const { return m_guardPositions; } -// [FRONTIER] Advances one patrol path or guard position per tick, with an idle phase between sweeps. -// The current body stops because PatrolPath::update and GuardPosition::update remain unimplemented. -// [UNRESOLVED] Purpose of the idle phase. -// [RETIRE-WHEN: aidll-02-skeleton] Implement and validate both dependent updates before enabling the cursor. +// ELF 0x352100. Each phase resets its exhausted cursor before advancing to the next phase. void UserOrderManager::update() { - BF2_AI_FRONTIER("dice::hfe::ai::UserOrderManager::update"); + switch (m_updatePhase) + { + case 0: + if (m_patrolCursor == m_patrolPaths.end()) + { + m_patrolCursor = m_patrolPaths.begin(); + m_updatePhase = 1; + } + else + { + m_patrolCursor->second->update(); + ++m_patrolCursor; + } + break; + case 1: + if (m_guardCursor == m_guardPositions.end()) + { + m_updatePhase = 2; + m_guardCursor = m_guardPositions.begin(); + } + else + { + m_guardCursor->second->update(); + ++m_guardCursor; + } + break; + case 2: + m_updatePhase = 0; + break; + } } -// [FRONTIER] the two creation bodies. `createPatrolPath` and `createGuardPosition` -// build the objects the two maps hold; their construction and behaviour remain unwritten. -// [RETIRE-WHEN: aidll-02-skeleton] -void UserOrderManager::createPatrolPath(const std::string&, CombatStrengthType, int) +// ELF 0x351AB0. A duplicate name still replaces the active pointer and leaks the new path. +void UserOrderManager::createPatrolPath(const std::string& name, CombatStrengthType strength, int side) { - BF2_AI_FRONTIER("dice::hfe::ai::UserOrderManager::createPatrolPath"); + m_activePatrolPath = checkPointer(new PatrolPath(strength, side)); + m_patrolPaths.insert(std::pair(name, m_activePatrolPath)); } -void UserOrderManager::createGuardPosition(const std::string&, const Vec2&, CombatStrengthType, - int, int) +// ELF 0x351D40. Duplicate names likewise leave an unregistered active position. +void UserOrderManager::createGuardPosition(const std::string& name, const Vec2& position, + CombatStrengthType strength, int side, int kit) { - BF2_AI_FRONTIER("dice::hfe::ai::UserOrderManager::createGuardPosition"); + m_activeGuardPosition = checkPointer(new GuardPosition(position, strength, side, kit)); + m_guardPositions.insert(std::pair(name, m_activeGuardPosition)); } -// Guard positions take priority over patrol paths; each map is traversed in key order. +// ELF 0x351FF0. Guard positions take priority over patrol paths; maps are traversed in key order. // Preserve short-circuit predicate order and reload end after each rejected entry. // Only exhausted maps return false. Retail's selected arm calls recruit(bot) and returns true -// independent of that call's result; its callback/plan dependencies remain unrecovered here. +// independent of that call's result. bool UserOrderManager::recruitBot(Bot* bot, int side) { for (std::map::iterator i = m_guardPositions.begin(); @@ -102,9 +135,8 @@ bool UserOrderManager::recruitBot(Bot* bot, int side) GuardPosition* const position = i->second; if (position->active() && position->getSide() == side && position->needBot()) { - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - // ELF GuardPosition::recruit ; bot is passed unchanged. - BF2_AI_FRONTIER("dice::hfe::ai::UserOrderManager::recruitBot (GuardPosition::recruit)"); + position->recruit(bot); + return true; } } @@ -114,9 +146,8 @@ bool UserOrderManager::recruitBot(Bot* bot, int side) PatrolPath* const path = i->second; if (path->active() && path->getSide() == side && path->neededResources() > 0) { - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - // ELF PatrolPath::recruit ; bot is passed unchanged. - BF2_AI_FRONTIER("dice::hfe::ai::UserOrderManager::recruitBot (PatrolPath::recruit)"); + path->recruit(bot); + return true; } } return false; diff --git a/Code/BF2/AI/AIDLL/AI/Main/UserOrderManager.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/UserOrders/UserOrderManager.h similarity index 86% rename from Code/BF2/AI/AIDLL/AI/Main/UserOrderManager.h rename to Code/BF2/AI/AIDLL/AI/AIStrategicEntity/UserOrders/UserOrderManager.h index 81ce26e88..f6789ca7f 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/UserOrderManager.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/UserOrders/UserOrderManager.h @@ -1,6 +1,5 @@ // Owns patrol paths and guard positions and assigns bots to user orders. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. -// [INFERRED] Source placement. +// Header placement [INFERRED]: beside its .cpp, whose path AIDLL_r.dll confirms (AIStrategicEntity/UserOrders/UserOrderManager.cpp: asserts in 0x1007C7E0 / 0x1007C920). #ifndef AI_AIDLL_AI_MAIN_USERORDERMANAGER_H #define AI_AIDLL_AI_MAIN_USERORDERMANAGER_H @@ -8,7 +7,7 @@ #include #include -#include "AIDllTypes.h" +#include "../../Main/AIDllTypes.h" namespace dice { namespace hfe { @@ -39,11 +38,10 @@ class UserOrderManager // the round-robin tick void update(); - // [FRONTIER] + // Creation selects the new object even if a duplicate name prevents its registration. void createPatrolPath(const std::string&, CombatStrengthType, int); void createGuardPosition(const std::string&, const Vec2&, CombatStrengthType, int, int); - // Returns false when the bot should fall back to its side's SAI. Selection is implemented; - // eligible guard/path recruitment still stops at the missing operation. + // Returns false when no eligible guard or patrol accepts this side, allowing fallback to SAI. bool recruitBot(Bot* bot, int side); // First-wins, set by the constructor; `BF2AI::clear` deletes through it. diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/AICamera.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/AICamera.cpp new file mode 100644 index 000000000..affa8a16b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/AICamera.cpp @@ -0,0 +1,28 @@ +// Camera access for the AI. Evidence: libaidll.so (ia-32) 0x366B20..0x366C9F. + +#include "AICamera.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x366BF0, __tcf_0 0x366C50, _GLOBAL__I 0x366C80). +#include + +#include "../../../../Game/Objects/ICameraObject.h" +#include "../../../../Game/Objects/IPlayer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x366B20. IPlayer::getCamera (+0x180), then ICameraObject::getTransformation(0.0f) (+0x10). +bool AICamera::GetCameraTrans(const world::IPlayer& player, Mat4& transform) +{ + world::ICameraObject* const camera = player.getCamera(); + if (!camera) + return false; + transform = camera->getTransformation(0.0f); + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/AICamera.h b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/AICamera.h new file mode 100644 index 000000000..d88a9b3d9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/AICamera.h @@ -0,0 +1,28 @@ +// Camera access for the AI. Placement next to TemperatureTreeModifiers is [INFERRED] from the +// image's address order; whether AICamera is a class or a namespace is not attested by the mangled +// name, and a class with a static member is [CHOSEN]. +#ifndef AI_AIDLL_AI_AISTRATEGICMAP_AICAMERA_H +#define AI_AIDLL_AI_AISTRATEGICMAP_AICAMERA_H + +#include "../../../../Math/Mat4.h" + +namespace dice { +namespace hfe { +namespace world { +class IPlayer; +} +namespace ai { + +class AICamera +{ +public: + // Copies the transformation of the player's current camera (taken at time 0) into `transform`. + // False, with `transform` untouched, when the player has no camera. + static bool GetCameraTrans(const world::IPlayer& player, Mat4& transform); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGICMAP_AICAMERA_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/AerialHeightMap.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/AerialHeightMap.cpp deleted file mode 100644 index 50debb2c1..000000000 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/AerialHeightMap.cpp +++ /dev/null @@ -1,154 +0,0 @@ -// [FRONTIER] Remaining methods stop by name until implemented. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining AerialHeightMap operations. - -#include "AerialHeightMap.h" - -#include "../Main/AIDllFrontier.h" -#include "../Main/CommonSingletonServer.h" -#include "../../../AIInterface/BFKnowledge/BFGame.h" // IAIGame::getLevelPath -#include "../../../AIInterface/BFKnowledge/BFTerrain.h" // IAITerrain, the world bounds -#include "../../../../IO/File/File.h" - -namespace dice { -namespace hfe { -namespace ai { - -AerialHeightMap* AerialHeightMap::m_instance = 0; - -namespace { - -// The cache's name, spelled dice's way in both directions. "AerialHeighMap" is missing a 't' and -// that is not a transcription slip - the reader and the writer share the literal, so a rebuilt -// server that corrects the spelling stops finding the file a shipped level ships with. -const char* const kHeightMapSuffix = "/AIPathFinding/AerialHeighMap.ahm"; - -} // namespace - -// Starts with cell size 16, zero origin, and no height buffer. -// Construction unconditionally replaces the singleton. -AerialHeightMap::AerialHeightMap() - : m_cellSize(16.0f) - , m_heights(0) -{ - m_origin.x = 0.0f; - m_origin.y = 0.0f; - - // m_width and m_height deliberately not initialised - the binary steps over both. See the - // header; `m_width` is genuinely read before anything is guaranteed to have written it. - m_instance = this; -} - -// it nulls the static unconditionally, without testing `== this`, so destroying a displaced -// instance clears the pointer to the live one. Reproduced. -AerialHeightMap::~AerialHeightMap() -{ - delete[] m_heights; - m_instance = 0; -} - -// Samples height above ground. Grid lookup requires a position inside the configured bounds. -// An unloaded map returns the missing-height sentinel 9999. -float AerialHeightMap::getAltitude(const Vec3& position) -{ - return position.y - getGroundHeight(position); -} - -float AerialHeightMap::getGroundHeight(const Vec3& position) -{ - return getGroundHeight(position.x, position.z); -} - -float AerialHeightMap::getGroundHeight(float x, float z) -{ - if (!m_heights) - return 9999.0f; - - const int column = static_cast((x - m_origin.x) / m_cellSize); - const int row = static_cast((z - m_origin.y) / m_cellSize); - - return static_cast(m_heights[column + m_width * row]); -} - -// Loads the level's cached height grid. Missing cache data leaves the map empty. -void AerialHeightMap::readHeightMapFromFile() -{ - const std::string levelPath = - static_cast(CommonSingletonServer::m_iaiGame)->getLevelPath(); - - io::File file; - - std::string path(levelPath); - path.append(kHeightMapSuffix); - - if (!file.open(path, io::FILEMODE_READ, static_cast(0), 0)) - return; - - file.read(m_cellSize); - file.read(m_width); - file.read(m_height); - file.read(m_origin); - - if (!m_heights) - m_heights = new unsigned short[m_width * m_height]; - - file.read(m_heights, 2 * m_width * m_height); - file.close(); -} - -// The exact mirror of the reader, field for field and in the same order. It shares the reader's -// silence on failure, and it writes the array unconditionally - a save on an object whose -// `m_heights` is still null passes a null pointer and a zero size to `File::write`. -void AerialHeightMap::saveHeightMapToFile() -{ - const std::string levelPath = - static_cast(CommonSingletonServer::m_iaiGame)->getLevelPath(); - - io::File file; - - std::string path(levelPath); - path.append(kHeightMapSuffix); - - if (file.open(path, static_cast(0), io::FILEACCESS_1, 0)) - { - file.write(m_cellSize); - file.write(m_width); - file.write(m_height); - file.write(m_origin); - file.write(m_heights, 2 * m_width * m_height); - file.close(); - } -} - -// Builds the aerial height grid from terrain bounds and saves it to the level cache. -void AerialHeightMap::createHeightMap(int samplesPerAxis) -{ - IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); - - m_width = static_cast(static_cast(terrain->getWorldSizeX()) / m_cellSize); - m_height = static_cast(static_cast(terrain->getWorldSizeZ()) / m_cellSize); - - m_origin.x = static_cast(terrain->getWorldMinX()); - m_origin.y = static_cast(terrain->getWorldMinZ()); - - if (m_heights) - delete[] m_heights; - - m_heights = new unsigned short[m_width * m_height]; - - for (int z = 0; z < m_height; ++z) - for (int x = 0; x < m_width; ++x) - m_heights[x + m_width * z] = computeHeightAt(x, z, samplesPerAxis); - - saveHeightMapToFile(); -} - -// [FRONTIER] Computes a cell height from a square sample grid once the required collision query is implemented. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. -unsigned short AerialHeightMap::computeHeightAt(int, int, int) -{ - BF2_AI_FRONTIER("dice::hfe::ai::AerialHeightMap::computeHeightAt (AIObjectPredicateNoVehicles: IAIObject +0x70)"); -} - -} // namespace ai -} // namespace hfe -} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BFStrategicEnvironment.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BFStrategicEnvironment.cpp index 9892d2f5b..067e276f0 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BFStrategicEnvironment.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BFStrategicEnvironment.cpp @@ -2,11 +2,20 @@ #include "BFStrategicEnvironment.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF 0x2E8D50, +// __tcf_0 0x2E8DB0, _GLOBAL__I 0x2E8DE0). +#include + #include #include "../../../../Core/ClassManager.h" #include "../Main/CommonSingletonServer.h" #include "../Main/AIDllFrontier.h" +#include "../Main/AIMain.h" // IAIMain::m_instance->getSAI +#include "../AIBot/BotMain.h" // Bot::getSide / getBotId +#include "../AIStrategic/SAI.h" +#include "../AIStrategicEntity/AIStrategicObject.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" namespace dice { namespace hfe { @@ -39,64 +48,85 @@ BFStrategicEnvironment::~BFStrategicEnvironment() { } -int BFStrategicEnvironment::getEnemyStrengths(Bot *) +// ELF 0x2E8860 / 0x2E88D0: the bot's side SAI rows (ISAI +0x30 / +0x34, by bot id). +float* BFStrategicEnvironment::getEnemyStrengths(Bot* bot) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFStrategicEnvironment::getEnemyStrengths"); + const int id = bot->getBotId(); + return IAIMain::m_instance->getSAI(bot->getSide())->getEnemyStrengths(id); } -int BFStrategicEnvironment::getEnemyTypes(Bot *) +float* BFStrategicEnvironment::getEnemyTypes(Bot* bot) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFStrategicEnvironment::getEnemyTypes"); + const int id = bot->getBotId(); + return IAIMain::m_instance->getSAI(bot->getSide())->getEnemyTypes(id); } -int BFStrategicEnvironment::getTemperature(Bot *) +// The Bot* overloads: the bot's current strategic object (ISAI::getBotCurrentPos, +0xB4) through +// the (object, side) overload of this vtable. The (object, side) overloads read the object's +// per-side float (+0xA0/+0xB0/+0xB8/+0xC0/+0xC8 + 4 side), or 0.0f (security: 1.0f) without one. +float BFStrategicEnvironment::getTemperature(Bot* bot) { - BF2_AI_FRONTIER("dice::hfe::ai::BFStrategicEnvironment::getTemperature"); + const int side = bot->getSide(); + const int id = bot->getBotId(); + return getTemperature(IAIMain::m_instance->getSAI(side)->getBotCurrentPos(id), side); } -float BFStrategicEnvironment::getTemperature(int, int) +float BFStrategicEnvironment::getTemperature(int object, int side) { - BF2_AI_FRONTIER("dice::hfe::ai::BFStrategicEnvironment::getTemperature"); + AIStrategicObject* const o = AIStrategicObjectManager::getInstance()->getStrategicObject(object); + return o ? o->m_f164[side - 1] : 0.0f; } -int BFStrategicEnvironment::getSecurity(Bot *) +float BFStrategicEnvironment::getSecurity(Bot* bot) { - BF2_AI_FRONTIER("dice::hfe::ai::BFStrategicEnvironment::getSecurity"); + const int side = bot->getSide(); + const int id = bot->getBotId(); + return getSecurity(IAIMain::m_instance->getSAI(side)->getBotCurrentPos(id), side); } -float BFStrategicEnvironment::getSecurity(int, int) +float BFStrategicEnvironment::getSecurity(int object, int side) { - BF2_AI_FRONTIER("dice::hfe::ai::BFStrategicEnvironment::getSecurity"); + AIStrategicObject* const o = AIStrategicObjectManager::getInstance()->getStrategicObject(object); + return o ? o->m_needCurveInput[side - 1] : 1.0f; } -int BFStrategicEnvironment::getControl(Bot *) +float BFStrategicEnvironment::getControl(Bot* bot) { - BF2_AI_FRONTIER("dice::hfe::ai::BFStrategicEnvironment::getControl"); + const int side = bot->getSide(); + const int id = bot->getBotId(); + return getControl(IAIMain::m_instance->getSAI(side)->getBotCurrentPos(id), side); } -float BFStrategicEnvironment::getControl(int, int) +float BFStrategicEnvironment::getControl(int object, int side) { - BF2_AI_FRONTIER("dice::hfe::ai::BFStrategicEnvironment::getControl"); + AIStrategicObject* const o = AIStrategicObjectManager::getInstance()->getStrategicObject(object); + return o ? o->m_friendlyRatio[side - 1] : 0.0f; } -int BFStrategicEnvironment::getFriendlyBattleStr(Bot *) +float BFStrategicEnvironment::getFriendlyBattleStr(Bot* bot) { - BF2_AI_FRONTIER("dice::hfe::ai::BFStrategicEnvironment::getFriendlyBattleStr"); + const int side = bot->getSide(); + const int id = bot->getBotId(); + return getFriendlyBattleStr(IAIMain::m_instance->getSAI(side)->getBotCurrentPos(id), side); } -float BFStrategicEnvironment::getFriendlyBattleStr(int, int) +float BFStrategicEnvironment::getFriendlyBattleStr(int object, int side) { - BF2_AI_FRONTIER("dice::hfe::ai::BFStrategicEnvironment::getFriendlyBattleStr"); + AIStrategicObject* const o = AIStrategicObjectManager::getInstance()->getStrategicObject(object); + return o ? o->m_friendlyBattleStrength[side - 1] : 0.0f; } -int BFStrategicEnvironment::getHostileBattleStr(Bot *) +float BFStrategicEnvironment::getHostileBattleStr(Bot* bot) { - BF2_AI_FRONTIER("dice::hfe::ai::BFStrategicEnvironment::getHostileBattleStr"); + const int side = bot->getSide(); + const int id = bot->getBotId(); + return getHostileBattleStr(IAIMain::m_instance->getSAI(side)->getBotCurrentPos(id), side); } -float BFStrategicEnvironment::getHostileBattleStr(int, int) +float BFStrategicEnvironment::getHostileBattleStr(int object, int side) { - BF2_AI_FRONTIER("dice::hfe::ai::BFStrategicEnvironment::getHostileBattleStr"); + AIStrategicObject* const o = AIStrategicObjectManager::getInstance()->getStrategicObject(object); + return o ? o->m_enemyBattleStrength[side - 1] : 0.0f; } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BFStrategicEnvironment.h b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BFStrategicEnvironment.h index 7cd0ab028..7179c8f1f 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BFStrategicEnvironment.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BFStrategicEnvironment.h @@ -25,18 +25,19 @@ class IAIStrategicEnvironment public: IAIStrategicEnvironment(); virtual ~IAIStrategicEnvironment(); - virtual int getEnemyStrengths(Bot *) = 0; - virtual int getEnemyTypes(Bot *) = 0; - virtual int getTemperature(Bot *) = 0; - virtual float getTemperature(int, int) = 0; - virtual int getSecurity(Bot *) = 0; - virtual float getSecurity(int, int) = 0; - virtual int getControl(Bot *) = 0; - virtual float getControl(int, int) = 0; - virtual int getFriendlyBattleStr(Bot *) = 0; - virtual float getFriendlyBattleStr(int, int) = 0; - virtual int getHostileBattleStr(Bot *) = 0; - virtual float getHostileBattleStr(int, int) = 0; + // Return types and constness from the ELF bodies (x87 returns, the ISAI row pointers). + virtual float* getEnemyStrengths(Bot* bot) const = 0; + virtual float* getEnemyTypes(Bot* bot) const = 0; + virtual float getTemperature(Bot* bot) = 0; + virtual float getTemperature(int object, int side) = 0; + virtual float getSecurity(Bot* bot) = 0; + virtual float getSecurity(int object, int side) = 0; + virtual float getControl(Bot* bot) = 0; + virtual float getControl(int object, int side) = 0; + virtual float getFriendlyBattleStr(Bot* bot) = 0; + virtual float getFriendlyBattleStr(int object, int side) = 0; + virtual float getHostileBattleStr(Bot* bot) = 0; + virtual float getHostileBattleStr(int object, int side) = 0; }; // BFStrategicEnvironment - sizeof == 4, from BF2AI::init step 6. @@ -47,18 +48,18 @@ class BFStrategicEnvironment : public IAIStrategicEnvironment virtual ~BFStrategicEnvironment(); // IAIStrategicEnvironment - virtual int getEnemyStrengths(Bot *); - virtual int getEnemyTypes(Bot *); - virtual int getTemperature(Bot *); - virtual float getTemperature(int, int); - virtual int getSecurity(Bot *); - virtual float getSecurity(int, int); - virtual int getControl(Bot *); - virtual float getControl(int, int); - virtual int getFriendlyBattleStr(Bot *); - virtual float getFriendlyBattleStr(int, int); - virtual int getHostileBattleStr(Bot *); - virtual float getHostileBattleStr(int, int); + virtual float* getEnemyStrengths(Bot* bot) const; // ELF 0x2E8860 + virtual float* getEnemyTypes(Bot* bot) const; // ELF 0x2E88D0 + virtual float getTemperature(Bot* bot); // ELF 0x2E8940 + virtual float getTemperature(int object, int side); // ELF 0x2E89C0 + virtual float getSecurity(Bot* bot); // ELF 0x2E8A10 + virtual float getSecurity(int object, int side); // ELF 0x2E8A90 + virtual float getControl(Bot* bot); // ELF 0x2E8AE0 + virtual float getControl(int object, int side); // ELF 0x2E8B60 + virtual float getFriendlyBattleStr(Bot* bot); // ELF 0x2E8BB0 + virtual float getFriendlyBattleStr(int object, int side); // ELF 0x2E8C30 + virtual float getHostileBattleStr(Bot* bot); // ELF 0x2E8C80 + virtual float getHostileBattleStr(int object, int side); // ELF 0x2E8D00 }; diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BotSpawner.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BotSpawner.cpp index 527d69d9b..579e6fe4a 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BotSpawner.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BotSpawner.cpp @@ -1,6 +1,10 @@ #include "BotSpawner.h" #include #include +// 's ios_base::Init object, m_kitWeightVector and m_pointWeightVector, in that order, are +// this TU's static initialisation (ELF 0x35ED80, _GLOBAL__I 0x35EF60) and teardown (__tcf_0 +// 0x35EE60, __tcf_1 0x35EE90, __tcf_2 0x35EEF0). +#include #include "../Main/AIDllFrontier.h" #include "../Main/AIMain.h" #include "../Main/AIRandom.h" @@ -14,7 +18,7 @@ #include "../AIKnowledge/AIInformationGrid.h" #include "../AIKnowledge/BFInformationEnvironment.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIUnit.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIUtils/VehicleOccupancy.h" @@ -24,11 +28,13 @@ #include "../AIStrategicEntity/AIStrategicObjectManager.h" #include "../../../AIInterface/BFKnowledge/AIPlayer.h" #include "../../../AIInterface/BFKnowledge/BFGame.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" // getInformation(side) #include "../../../AIInterface/BFKnowledge/KitTemplateManager.h" #include "../../../AIInterface/BFKnowledge/KitTemplate.h" namespace dice { namespace hfe { namespace ai { +std::vector BotSpawner::m_kitWeightVector; std::vector BotSpawner::m_pointWeightVector; namespace { @@ -46,8 +52,7 @@ class FreeUnitPred : public IAIInformationGridPredicate { if (!information->getUnit() || !information->hasMobile()) return false; - const unsigned int flags = information->getObjectTypeFlags(); - if ((flags & 0x80u) || (flags & 0x200000u)) + if (information->isOfType(ITNaval) || information->isOfType(ITSoldier)) return false; bool anyFree = false; @@ -166,6 +171,82 @@ bool BotSpawner::findSuitableSpawnGroup(float* enemyStrengths, float* enemyCount return true; } +// ELF 0x35D1B0. Spawn selection for a bot that must come back near a position (PatrolPath::botIsDead +// is the only caller and discards the result): the eligible spawn point nearest in XZ, then the +// strategic object closest to that point's position. The strength rows come from the bot's SAI by +// bot id. The game singleton is read twice, as shipped: once for the eligibility and empty-list +// checks, again for the search. Returns true unless the side has no spawn points; a bot that +// already has a spawn group, or whose own spawn point is still eligible, is left as it is. +bool BotSpawner::findSuitableSpawnGroup(const Vec3& position, Bot* bot) +{ + Vec3 spawnPosition = { 0.0f, 0.0f, 0.0f }; + const int side = bot->getSide(); + SAI* const sai = IAIMain::m_instance->getSAI(side); + const int botId = bot->getBotId(); + float* const enemyStrengths = sai->getEnemyStrengths(botId); + float* const enemyCounts = sai->getEnemyTypes(botId); + float* const friendlyStrengths = sai->getFriendlyStrengths(botId); + float* const friendlyCounts = sai->getFriendlyTypes(botId); + if (bot->getPlayer()->getSpawnGroup() > 0) + return true; + + IAIGame* const game = static_cast(CommonSingletonServer::m_iaiGame); + if (game->isEligibleSpawnpoint(side, bot->getSpawnPoint())) + { + sai->addSpawnToPoint(bot->getSpawnPoint()); + return true; + } + if (game->getSpawnPointList(side).empty()) + { + bot->setSpawnTarget(-1, 13); + return false; + } + + IAIGame* const searchGame = static_cast(CommonSingletonServer::m_iaiGame); + const std::list& groups = searchGame->getSpawnPointList(side); + int group = 0; + float best = 1.0e9f; + for (std::list::const_iterator it = groups.begin(); it != groups.end(); ++it) + { + if (searchGame->isEligibleSpawnpoint(side, *it)) + { + const float distance = distXZSqr(searchGame->getSpawnPointPosition(*it), position); + if (distance < best) + { + best = distance; + group = *it; + spawnPosition = searchGame->getSpawnPointPosition(group); + } + } + } + + AIStrategicObject* const object = + AIStrategicObjectManager::getInstance()->getClosestObject(spawnPosition, side); + const int kit = findSuitableKit(enemyStrengths, enemyCounts, friendlyStrengths, + friendlyCounts, object, side, bot); + if (object) + bot->setSpawnTarget(object->getIndex(), group, kit); + else + bot->setSpawnTarget(group, kit); + return true; +} + +// ELF 0x35DDE0. Over the six strength types: the squared shortfall of values below counts goes +// to sqrDist, the surplus (including NaN differences) to excess. No caller in the image. +void BotSpawner::sqrDistAndExcess(float* values, int* counts, float& sqrDist, float& excess) +{ + sqrDist = 0.0f; + excess = 0.0f; + for (int i = 0; i < 6; ++i) + { + const float difference = values[i] - static_cast(counts[i]); + if (difference < 0.0f) + sqrDist += difference * difference; + else + excess += difference; + } +} + // Empty input returns 0 without touching the output or static candidates. A // failed nonempty search returns -1, retaining any last output object write. // Deep path and Information forwarding bodies still stop at their actual calls. @@ -356,9 +437,19 @@ KitType BotSpawner::GetRandomKit(SquadMember*) #endif } +// ELF 0x35ED30. Squad leaders may not take kits 4 and 5; everyone else may take any kit. No +// caller in the image. +bool BotSpawner::isAllowedKit(SquadMember* member, KitType kit) +{ + bool allowed = true; + if (member->isSquadLeader() && static_cast(kit - 4) <= 1u) + allowed = false; + return allowed; +} + // Chooses a kit from squad needs and nearby equipment. Always consumes the initial // random-kit selection; only nonleaders can take the medic early return. -// Assigned-squad equipment remains an unimplemented boundary. +// The assigned-squad arm scores the squad's area (ELF 0x35E3C0). int BotSpawner::findSuitableKit(const float*, const float*, const float*, const float*, AIStrategicObject* object, int side, Bot* bot) { @@ -553,10 +644,87 @@ int BotSpawner::findSuitableKit(const float*, const float*, const float*, const } if (squad->isSquadAssignedToAnyArea()) { - // [FRONTIER] [TEMP] [CHOSEN, not recovered] - // [RETIRE-WHEN: aidll-02-skeleton] Recover the assigned squad's - // equipment scan, area geometry and scoring (the kitCounts consumer). - BF2_AI_FRONTIER("dice::hfe::ai::BotSpawner::findSuitableKit [assigned-squad equipment]"); + // ELF 0x35E3C0..0x35E6F4: the members' current vehicles are counted (strength types + // 1/2/4 vehicles, damaged below 0.5f health; 0 infantry, health read and discarded), + // then the enemies around the assigned area (rectangle centre - 2 (pos - centre), + // the object arm uses 3), then the same kit ladder as the object arm with an integer + // infantry comparison and a vehicle-repair test against kitCounts[4]. + int friendlyVehicles = 0, damagedFriendlyVehicles = 0, friendlyInfantry = 0; + for (int i = 0; i < members; ++i) + { + IAIObject* const vehicle = squad->getSquadMember(i)->getPlayer()->getCurrentVehicle(); + if (!vehicle) + continue; + Information* const entry = informationManager->getInformation(vehicle->getInformation(side)); + if (!entry || !entry->getUnit()) + continue; + IPIPhysical* const physical = entry->getPhysical(); + switch (physical->getStrengthType()) + { + case 1: case 2: case 4: + ++friendlyVehicles; + if (physical->getHealth() < 0.5f) + ++damagedFriendlyVehicles; + break; + case 0: + ++friendlyInfantry; + physical->getHealth(); // shipped discarded call + break; + } + } + AIStrategicObject* const area = AIStrategicObjectManager::getInstance()->getStrategicObject( + squad->getSquadStrategicAreaAssignment()->getIndex()); + Vec2 minimum = static_cast(area)->m_centre; + const Vec2 position = area->getPosition(side); + const double dx = static_cast(position.x) - minimum.x; + const double dy = static_cast(position.y) - minimum.y; + minimum.x = static_cast(static_cast(minimum.x) - dx * 2.0f); + minimum.y = static_cast(static_cast(minimum.y) - dy * 2.0f); + Vec2 maximum = {}; + maximum = getBoxMaxCorner(minimum, position, maximum); + IAIInformationEnvironment* const environment = + static_cast(AISingletonServer::m_iaiInformationEnvironment); + environment->getObjectsWithinRectangle(information, minimum, maximum, side, true, 0); + int enemyVehicles = 0, enemyInfantry = 0; + const int enemySide = (side == 1) + 1; + std::vector::const_iterator end = information.end(); + for (std::vector::const_iterator it = information.begin(); it != end; ++it) + { + Information* const entry = informationManager->getInformation(*it); + if (!entry) + continue; + IPIPhysical* const physical = entry->getPhysical(); + if (vehicleOccupied(*it, side) && entry->getSide() == enemySide) + { + switch (physical->getStrengthType()) + { + case 0: ++enemyInfantry; break; + case 1: case 2: case 4: ++enemyVehicles; break; + } + } + end = information.end(); // ELF refreshes after every nonnull record + } + if (enemyVehicles > friendlyVehicles + kitCounts[6] && templates[6]) + return 6; + if (enemyInfantry > friendlyInfantry) + { + AIRandom* const random = AIRandom::m_instance; + if (static_cast(random->m_index) >= AIRandom::kStateSize) + random->generateNumbers(); + const double draw = static_cast(random->next()) * (1.0 / 4294967296.0); + if (draw > 0.85f && templates[0]) + return 0; + if (draw > 0.55f && templates[2]) + return 2; + if (draw > 0.25f && templates[3]) + return 3; + if (templates[4]) + return 4; + } + else if (damagedFriendlyVehicles + friendlyVehicles > kitCounts[4] * 2 && templates[4]) + { + return 4; + } } } diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BotSpawner.h b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BotSpawner.h index 2de4422de..1d7e157eb 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BotSpawner.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BotSpawner.h @@ -5,6 +5,8 @@ #include +#include "../../../../Math/Vec3.h" + namespace dice { namespace hfe { enum KitType : int; namespace ai { @@ -26,6 +28,15 @@ struct SpawnChoice float weight; }; +// Element of BotSpawner::m_kitWeightVector. Only the 8-byte, trivially destructible element is +// attested (the teardown at ELF 0x35EE90 steps by 8 and frees capacity * 8); nothing in the image +// reads or writes the vector. The name and fields are [INFERRED]. +struct KitWeight +{ + int kit; + float weight; +}; + // These static contracts imply no instance layout, lifecycle or factory. class BotSpawner { @@ -33,15 +44,20 @@ class BotSpawner static bool findSuitableSpawnGroup(float* enemyStrengths, float* enemyCounts, float* friendlyStrengths, float* friendlyCounts, int strategicObjectId, Bot* bot); + // Return type bool as in the sibling overload [INFERRED]; the only caller discards it. + static bool findSuitableSpawnGroup(const Vec3& position, Bot* bot); static int findSuitableSpawnGroup(int side, AIStrategicObject*& object, Bot* bot); static int findSuitableKit(const float* enemyStrengths, const float* enemyCounts, const float* friendlyStrengths, const float* friendlyCounts, AIStrategicObject* object, int side, Bot* bot); static KitType GetRandomKit(SquadMember* member); + static void sqrDistAndExcess(float* values, int* counts, float& sqrDist, float& excess); + static bool isAllowedKit(SquadMember* member, KitType kit); // Shared static vector. Ordinary // static construction/destruction; retained capacity across selector calls. // Public access is [CHOSEN, not recovered], not an instance-layout claim. + static std::vector m_kitWeightVector; static std::vector m_pointWeightVector; }; diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMap.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMap.cpp new file mode 100644 index 000000000..bb4a0350f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMap.cpp @@ -0,0 +1,377 @@ +// Strategic grid map. Evidence: libaidll.so (ia-32) 0x35FD10..0x364544, the TU named by the +// anonymous-namespace symbols AI_AIDLL_AI_AIStrategicMap_SAIMap.cpp. + +#include "SAIMap.h" + +#include +// 's ios_base::Init object and defaultModifiers are this TU's static initialisation +// (ELF 0x364330, __tcf_0 0x3644C0, _GLOBAL__I 0x3644F0). +#include + +#include "SAIMapSquare.h" +#include "ScalarMap.h" +#include "TemperatureTreeModifiers.h" +#include "../AIKnowledge/AIInformationGrid.h" +#include "../AIKnowledge/BFInformationEnvironment.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIStrategic/SAI.h" +#include "../AIStrategic/StatusMap.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// ELF: the modifiers a SAIMap uses when constructed without any. +TemperatureTreeModifiers* defaultModifiers = checkPointer(new TemperatureTreeModifiers()); + +// ELF 0x364510 (weak; vtable 0x4BF808, one slot): information whose security is below 0.1. +class SecurityPredicate : public IAIInformationGridPredicate +{ +public: + bool includeInformation(Information* information) const override + { + return 0.1f > information->getSecurity(); + } +}; + +} // namespace + +// ELF 0x35FD10 (C2; C1 0x3618D0). Every allocation goes through checkPointer. The square sizes +// divide by the dimension arguments; the half-diagonal of a square is the bounding radius. Only +// buffer 0 of each layer is initialised. +0x24, +0x3C, +0x6C's values and the update state's +// index are left unwritten, as shipped. +SAIMap::SAIMap(int side, int dimX, int dimY, Vec2 min, Vec2 max, TemperatureTreeModifiers* modifiers) + : m_side(side) + , m_dimX(dimX) + , m_dimY(dimY) + , m_min(min) + , m_max(max) + , m_currentBuffer(0) + , m_modifiers(modifiers) +{ + m_layer44[0] = checkPointer(new ScalarMap(m_dimX, m_dimY)); + m_layer44[1] = checkPointer(new ScalarMap(m_dimX, m_dimY)); + m_layer4C[0] = checkPointer(new ScalarMap(m_dimX, m_dimY)); + m_layer4C[1] = checkPointer(new ScalarMap(m_dimX, m_dimY)); + m_layer54[0] = checkPointer(new ScalarMap(m_dimX, m_dimY)); + m_layer54[1] = checkPointer(new ScalarMap(m_dimX, m_dimY)); + m_layer5C[0] = checkPointer(new ScalarMap(m_dimX, m_dimY)); + m_layer5C[1] = checkPointer(new ScalarMap(m_dimX, m_dimY)); + m_layer64[0] = checkPointer(new ScalarMap(m_dimX, m_dimY)); + m_layer64[1] = checkPointer(new ScalarMap(m_dimX, m_dimY)); + m_layer6C = checkPointer(new ScalarMap(m_dimX, m_dimY)); + m_statusMaps[0] = checkPointer(new StatusMap(m_dimX, m_dimY)); + m_statusMaps[1] = checkPointer(new StatusMap(m_dimX, m_dimY)); + m_squares[0] = checkPointer(new SAIMapSquare[m_dimX * m_dimY]); + m_squares[1] = checkPointer(new SAIMapSquare[m_dimX * m_dimY]); + m_layer80[0] = checkPointer(new ScalarMap(m_dimX, m_dimY)); + m_layer80[1] = checkPointer(new ScalarMap(m_dimX, m_dimY)); + + m_squareXSize = (max.x - min.x) / static_cast(dimX); + m_squareYSize = (max.y - min.y) / static_cast(dimY); + Vec2 half; + half.x = m_squareXSize * 0.5f; + half.y = m_squareYSize * 0.5f; + m_squareBoundingCircleRadius = sqrtf(half.x * half.x + half.y * half.y); + + m_updateState = checkPointer(new UpdateState); + m_updateState->m_state = 0; + + m_stateA = checkPointer(new float[44]); + m_stateB = checkPointer(new float[44]); + m_stateC = checkPointer(new float[44]); + m_stateD = checkPointer(new float[44]); + clearStates(m_stateA, m_stateC); + clearStates(m_stateB, m_stateD); + + for (int x = 0; x < m_dimX; ++x) + { + for (int y = 0; y < m_dimY; ++y) + { + ScalarMap* map = m_layer44[m_currentBuffer]; + map->m_values[y * map->m_width + x] = 0.0f; + map = m_layer4C[m_currentBuffer]; + map->m_values[y * map->m_width + x] = 0.0f; + map = m_layer54[m_currentBuffer]; + map->m_values[y * map->m_width + x] = 0.0f; + map = m_layer5C[m_currentBuffer]; + map->m_values[y * map->m_width + x] = 0.0f; + map = m_layer64[m_currentBuffer]; + map->m_values[y * map->m_width + x] = 0.0f; + StatusMap* const status = m_statusMaps[m_currentBuffer]; + status->m_statuses[y * status->m_width + x] = StatusMap::Neutral; + map = m_layer80[m_currentBuffer]; + map->m_values[y * map->m_width + x] = 1.0f; + } + } + + if (!m_modifiers) + m_modifiers = defaultModifiers; +} + +// ELF 0x363490 (D2; D1 0x363790): the layers in member order except that +0x80/+0x84 go before +// the square arrays, then the update state and the four state rows. The modifiers are borrowed. +SAIMap::~SAIMap() +{ + if (m_layer44[0]) delete m_layer44[0]; + if (m_layer44[1]) delete m_layer44[1]; + if (m_layer4C[0]) delete m_layer4C[0]; + if (m_layer4C[1]) delete m_layer4C[1]; + if (m_layer54[0]) delete m_layer54[0]; + if (m_layer54[1]) delete m_layer54[1]; + if (m_layer5C[0]) delete m_layer5C[0]; + if (m_layer5C[1]) delete m_layer5C[1]; + if (m_layer64[0]) delete m_layer64[0]; + if (m_layer64[1]) delete m_layer64[1]; + if (m_layer6C) delete m_layer6C; + if (m_statusMaps[0]) delete m_statusMaps[0]; + if (m_statusMaps[1]) delete m_statusMaps[1]; + if (m_layer80[0]) delete m_layer80[0]; + if (m_layer80[1]) delete m_layer80[1]; + if (m_squares[0]) delete[] m_squares[0]; + if (m_squares[1]) delete[] m_squares[1]; + if (m_updateState) delete m_updateState; + if (m_stateA) delete[] m_stateA; + if (m_stateB) delete[] m_stateB; + if (m_stateC) delete[] m_stateC; + if (m_stateD) delete[] m_stateD; +} + +// ELF 0x363A90. A jump table over the update state (0..24): 0-3 collect every information id +// of both kinds, 4 add the side's insecure ones (SecurityPredicate as the second predicate), +// 5-7 visit the collected ids (resumable at m_index), 8-23 only advance, 24 flips the buffers +// and answers true. Each step checks the update-time deadline (timer read once) first; other +// states answer false. +bool SAIMap::update(SAI* sai, double budget) +{ + const int buffer = m_currentBuffer == 0; + IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); + const double deadline = timer->getUpdateTime() + budget; + IAIInformationEnvironment* environment; + switch (m_updateState->m_state) + { + case 0: case 1: case 2: case 3: + environment = static_cast(AISingletonServer::m_iaiInformationEnvironment); + environment->getAllInformation(m_updateState->m_ids, 0, true, 0, 0); + environment->getAllInformation(m_updateState->m_ids, 0, false, 0, 0); + m_updateState->m_state = 4; + m_updateState->m_index = 0; + if (timer->getUpdateTime() >= deadline) + return false; + // fall through + case 4: + { + environment = static_cast(AISingletonServer::m_iaiInformationEnvironment); + SecurityPredicate insecure; + environment->getAllInformation(m_updateState->m_ids, m_side, true, 0, &insecure); + environment->getAllInformation(m_updateState->m_ids, m_side, false, 0, &insecure); + m_updateState->m_state = 5; + m_updateState->m_index = 0; + if (timer->getUpdateTime() >= deadline) + return false; + } + // fall through + case 5: case 6: case 7: + for (unsigned int index = m_updateState->m_index; index < m_updateState->m_ids.size(); ++index) + { + if (timer->getUpdateTime() >= deadline) + { + m_updateState->m_index = index; + return false; + } + Information* information = informationManager->getInformation(m_updateState->m_ids[index]); + if (!information || information->isOfType(ITNoTemperature)) + continue; + if (information->getSecurity() == 0.0f) + continue; + updateInformation(information, sai, buffer); + int it; + for (Information* secondary = informationManager->getInformation(information->getFirstSecondaryObject(it, m_side)); + secondary; + secondary = informationManager->getInformation(information->getSecondaryObject(it, m_side))) + { + if (!secondary->isOfType(ITNoTemperature) && secondary->getSecurity() > 0.0f) + updateInformation(secondary, sai, buffer); + } + } + m_updateState->m_state = 8; + m_updateState->m_index = 0; + m_updateState->m_ids.resize(0); + if (timer->getUpdateTime() >= deadline) + return false; + // fall through + case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15: + m_updateState->m_state = 16; + m_updateState->m_index = 0; + if (timer->getUpdateTime() >= deadline) + return false; + // fall through + case 16: case 17: case 18: case 19: case 20: case 21: case 22: case 23: + m_updateState->m_state = 24; + m_updateState->m_index = 0; + if (timer->getUpdateTime() >= deadline) + return false; + // fall through + case 24: + m_updateState->m_state = 0; + m_currentBuffer = buffer; + return true; + default: + return false; + } +} + +// ELF 0x363FA0. +int SAIMap::getSide() const +{ + return m_side; +} + +// ELF 0x363FB0. +int SAIMap::getMapDimensionX() const +{ + return m_dimX; +} + +// ELF 0x363FC0. +int SAIMap::getMapDimensionY() const +{ + return m_dimY; +} + +// ELF 0x363FD0. +TemperatureTreeModifiers* SAIMap::getTemperatureTreeModifiers() const +{ + return m_modifiers; +} + +// ELF 0x363FE0. +void SAIMap::setTemperatureTreeModifiers(TemperatureTreeModifiers* modifiers) +{ + m_modifiers = modifiers; +} + +// ELF 0x364000. +float SAIMap::getSquareArea() const +{ + return m_squareArea; +} + +// ELF 0x364010. +float SAIMap::getSquareBoundingCircleRadius() const +{ + return m_squareBoundingCircleRadius; +} + +// ELF 0x364020. +float SAIMap::getSquareXSize() const +{ + return m_squareXSize; +} + +// ELF 0x364030. +float SAIMap::getSquareYSize() const +{ + return m_squareYSize; +} + +// ELF 0x364040. +Vec2 SAIMap::getCoordFromSquareId(int id) +{ + Vec2 coord; + coord.x = static_cast(id % m_dimX) * m_squareXSize + m_min.x + m_squareXSize * 0.5f; + coord.y = static_cast(id / m_dimX) * m_squareYSize + m_min.y + m_squareYSize * 0.5f; + return coord; +} + +// ELF 0x3640C0: empty. +void SAIMap::setMapDimensionX(int) +{ +} + +// ELF 0x3640D0: empty. +void SAIMap::setMapDimensionY(int) +{ +} + +// ELF 0x3640E0: the relative position is formed in float and truncated after the scale. +bool SAIMap::getSquareId(int& x, int& y, const Vec3& position) const +{ + Vec2 relative; + relative.x = (position.x - m_min.x) / (m_max.x - m_min.x); + relative.y = (position.z - m_min.y) / (m_max.y - m_min.y); + x = static_cast(relative.x * static_cast(m_dimX)); + y = static_cast(relative.y * static_cast(m_dimY)); + return x >= 0 && x < m_dimX && y >= 0 && y < m_dimY; +} + +// ELF 0x364180: both 44-element rows to zero, the last element of each to one. +void SAIMap::clearStates(float* a, float* b) +{ + for (int i = 0; i <= 43; ++i) + { + a[i] = 0.0f; + b[i] = 0.0f; + } + a[43] = 1.0f; + b[43] = 1.0f; +} + +// ELF 0x3641D0. +float SAIMap::setFastThreshold(float threshold) +{ + return m_fastThreshold = threshold; +} + +// ELF 0x3641E0. +float SAIMap::getFastThreshold() +{ + return m_fastThreshold; +} + +// ELF 0x3641F0. Only the square test and the final strength copy (+0x14 into +0x10) have an +// effect: the side classification, the occupancy query and the clamped strength sum are +// computed and unused, as shipped (the sum is never negative, so the early return never fires). +void SAIMap::updateInformation(Information* information, SAI* sai, int) +{ + int x; + int y; + if (!getSquareId(x, y, information->getPosition())) + return; + IPIUnit* const unit = information->getUnit(); + float total = 0.0f; + float strengths[6]; + const bool isFriend = sai->isFriend(information->getSide()); + const bool isEnemy = sai->isEnemy(information->getSide()); + bool neutral = false; + if (!isFriend && !isEnemy) + neutral = true; + else if (unit) + unit->isOccupied(); + (void)neutral; + if (unit) + { + for (int i = 0; i <= 5; ++i) + { + float strength = i < unit->getNBattleStrengths() ? unit->getBattleStrengths()[i] : 0.0f; + if (!(strength > 0.0f)) + strength = 0.0f; + strengths[i] = strength; + total += strength; + } + if (0.0f > total) + return; + } + information->setStrength(information->getBasicTemp()); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMap.h b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMap.h new file mode 100644 index 000000000..8d612921f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMap.h @@ -0,0 +1,99 @@ +// A grid view of one side's strategic situation: per-square scalar layers, status layers and +// temperature trees, double-buffered (the update writes the buffer that is not current and flips +// at the end), and a resumable update that collects the information ids it will visit. +// Evidence: libaidll.so (ia-32) SAIMap.cpp 0x35FD10..0x364544. Nothing in the image constructs a +// SAIMap. Offsets are ELF; layer names are [UNRESOLVED] where no accessor names them. + +#ifndef AI_AIDLL_AI_AISTRATEGICMAP_SAIMAP_H // [INFERRED] guard style +#define AI_AIDLL_AI_AISTRATEGICMAP_SAIMAP_H + +#include + +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +class Information; +class SAI; +class SAIMapSquare; +class ScalarMap; +class StatusMap; +class TemperatureTreeModifiers; + +class SAIMap +{ +public: + // ELF: a 28-byte record owned at +0x88. Only the state, the resume index and the id vector + // are touched; the last eight bytes are [UNRESOLVED]. Names [INFERRED]. + struct UpdateState + { + /* +0x00 */ int m_state; + /* +0x04 */ int m_index; + /* +0x08 */ std::vector m_ids; + /* +0x14 */ unsigned char m_unresolved14[8]; + }; + + // Allocates every layer at dimX * dimY; a null modifiers pointer selects the TU's defaults. + SAIMap(int side, int dimX, int dimY, Vec2 min, Vec2 max, TemperatureTreeModifiers* modifiers); + ~SAIMap(); + + // Runs the resumable update until the update-time budget is spent (false) or a full pass + // completed and the buffers flipped (true). + bool update(SAI* sai, double budget); + int getSide() const; + int getMapDimensionX() const; + int getMapDimensionY() const; + TemperatureTreeModifiers* getTemperatureTreeModifiers() const; + void setTemperatureTreeModifiers(TemperatureTreeModifiers* modifiers); + float getSquareArea() const; // +0x24 is never written in the image + float getSquareBoundingCircleRadius() const; + float getSquareXSize() const; + float getSquareYSize() const; + // The centre of the square, x = id % dimX and y = id / dimX. + Vec2 getCoordFromSquareId(int id); + void setMapDimensionX(int x); // empty + void setMapDimensionY(int y); // empty + // The square containing position (x, z); false outside the map. + bool getSquareId(int& x, int& y, const Vec3& position) const; + void clearStates(float* a, float* b); + float setFastThreshold(float threshold); // fsts: the value stays in st0 + float getFastThreshold(); + void updateInformation(Information* information, SAI* sai, int buffer); + +private: + /* +0x00 */ int m_side; + /* +0x04 */ int m_dimX; + /* +0x08 */ int m_dimY; + /* +0x0C */ Vec2 m_min; + /* +0x14 */ Vec2 m_max; + /* +0x1C */ float m_squareXSize; + /* +0x20 */ float m_squareYSize; + /* +0x24 */ float m_squareArea; // not constructed + /* +0x28 */ float m_squareBoundingCircleRadius; + // Four 44-float state rows, paired by clearStates as (A, C) and (B, D). + /* +0x2C */ float* m_stateA; + /* +0x30 */ float* m_stateB; + /* +0x34 */ float* m_stateC; + /* +0x38 */ float* m_stateD; + /* +0x3C */ float m_fastThreshold; // not constructed + /* +0x40 */ int m_currentBuffer; // 0 or 1; layers below are indexed by it + /* +0x44 */ ScalarMap* m_layer44[2]; // [UNRESOLVED] role; zeroed + /* +0x4C */ ScalarMap* m_layer4C[2]; // [UNRESOLVED] role; zeroed + /* +0x54 */ ScalarMap* m_layer54[2]; // [UNRESOLVED] role; zeroed + /* +0x5C */ ScalarMap* m_layer5C[2]; // [UNRESOLVED] role; zeroed + /* +0x64 */ ScalarMap* m_layer64[2]; // [UNRESOLVED] role; zeroed + /* +0x6C */ ScalarMap* m_layer6C; // [UNRESOLVED] role; not initialised + /* +0x70 */ StatusMap* m_statusMaps[2]; // Neutral + /* +0x78 */ SAIMapSquare* m_squares[2]; + /* +0x80 */ ScalarMap* m_layer80[2]; // [UNRESOLVED] role; one + /* +0x88 */ UpdateState* m_updateState; + /* +0x8C */ TemperatureTreeModifiers* m_modifiers; // borrowed +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGICMAP_SAIMAP_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMapRenderUtil.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMapRenderUtil.cpp new file mode 100644 index 000000000..4f4581258 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMapRenderUtil.cpp @@ -0,0 +1,34 @@ +// SAIMapRenderUtil. The FILE symbol attests the basename; directory placement is [INFERRED]. +#include "SAIMapRenderUtil.h" + +// static init: ELF 0x364590, 0x3645F0, 0x364620 (iostream Init and teardown only). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x364550; amd-64 0x39BF80 also clears eax and returns. +SAIMapRendInfo* SAIMapRenderUtil::createRenderInfo(SAIMap*, SAIMapRenderType) +{ + return 0; +} + +// ELF 0x364560; amd-64 0x39BF90 is also empty. +void SAIMapRenderUtil::update(SAIMapRendInfo*) +{ +} + +// ELF 0x364570; amd-64 0x39BFA0 is also empty. +void SAIMapRenderUtil::render(SAIMapRendInfo*) +{ +} + +// ELF 0x364580; amd-64 0x39BFB0 is also empty, including no deletion. +void SAIMapRenderUtil::releaseRenderInfo(SAIMapRendInfo*) +{ +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMapRenderUtil.h b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMapRenderUtil.h new file mode 100644 index 000000000..8e4a6ae1d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMapRenderUtil.h @@ -0,0 +1,31 @@ +// Strategic-map rendering hooks. The parameter names are attested by the ELF symbols; +// [CHOSEN, not recovered] a static utility class spells the otherwise ambiguous scope. +#ifndef AI_AIDLL_AI_AISTRATEGICMAP_SAIMAPRENDERUTIL_H +#define AI_AIDLL_AI_AISTRATEGICMAP_SAIMAPRENDERUTIL_H + +namespace dice { +namespace hfe { +namespace ai { + +class SAIMap; +class SAIMapRendInfo; +// [CHOSEN, not recovered] int permits an opaque enum declaration. Neither image reads +// this argument or attests enumerators or signedness; no values are introduced here. +enum SAIMapRenderType : int; + +class SAIMapRenderUtil +{ +public: + // The shipped AI image provides no rendering information and always returns null. + static SAIMapRendInfo* createRenderInfo(SAIMap* map, SAIMapRenderType type); + // These shipped hooks leave the supplied opaque information untouched. + static void update(SAIMapRendInfo* info); + static void render(SAIMapRendInfo* info); + static void releaseRenderInfo(SAIMapRendInfo* info); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGICMAP_SAIMAPRENDERUTIL_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMapSquare.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMapSquare.cpp new file mode 100644 index 000000000..e8e5e7198 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMapSquare.cpp @@ -0,0 +1,26 @@ +// Strategic grid square. Evidence: libaidll.so (ia-32) 0x3663F0..0x366508. + +#include "SAIMapSquare.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x366460, __tcf_0 0x3664C0, _GLOBAL__I 0x3664F0). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x3663F0 (C2; C1 0x366420): only the tree is constructed. +SAIMapSquare::SAIMapSquare() +{ +} + +// ELF 0x366450. +const TemperatureTree& SAIMapSquare::getTemperatureTree() const +{ + return m_temperatureTree; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMapSquare.h b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMapSquare.h new file mode 100644 index 000000000..eb63f1a6b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMapSquare.h @@ -0,0 +1,28 @@ +// One square of the strategic grid map: its temperature tree. Evidence: libaidll.so (ia-32) +// 0x3663F0..0x366458; sizeof 40 (SAIMap allocates count * 0x28 bytes, no array cookie). + +#ifndef AI_AIDLL_AI_AISTRATEGICMAP_SAIMAPSQUARE_H // [INFERRED] guard style +#define AI_AIDLL_AI_AISTRATEGICMAP_SAIMAPSQUARE_H + +#include "TemperatureTree.h" + +namespace dice { +namespace hfe { +namespace ai { + +class SAIMapSquare +{ +public: + SAIMapSquare(); + + // The image answers the square's own address; the reference spelling is [INFERRED]. + const TemperatureTree& getTemperatureTree() const; + + /* +0x00 */ TemperatureTree m_temperatureTree; // [INFERRED] name +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGICMAP_SAIMAPSQUARE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/ScalarMap.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/ScalarMap.cpp new file mode 100644 index 000000000..be03f843f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/ScalarMap.cpp @@ -0,0 +1,203 @@ +// Scalar grid smoothing and ranking. Evidence: libaidll.so (ia-32) 0x364640..0x365FF8; the +// smoothing error names AI/AIDLL/AI/AIStrategicMap/ScalarMap.cpp. The TU has no static +// initialisation in the image. + +#include "ScalarMap.h" + +#include +#include + +#include "../AIUtils/checkPointer.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../../Core/Debug.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// ELF: 8-byte heap element {index, value}. std::less (the instantiated comparator) orders +// by descending value, so the priority queue's top is the smallest kept value. +struct PQElem +{ + PQElem(int index, float value) : m_index(index), m_value(value) {} + bool operator<(const PQElem& other) const { return m_value > other.m_value; } + + int m_index; + float m_value; +}; + +} // namespace + +// ELF 0x364640 (C2; C1 0x3647A0). +ScalarMap::ScalarMap(int width, int height) + : m_width(width) + , m_height(height) +{ + m_values = checkPointer(new float[width * height]); +} + +// ELF 0x364900 (D2; D1 0x364930). +ScalarMap::~ScalarMap() +{ + if (m_values) + delete[] m_values; +} + +// ELF 0x364960. The result is indexed with its own width for the row and this map's width for the +// right column, as shipped. The update-time timer is read once. +bool ScalarMap::smooth(ScalarMap& result, double deadline, int& row) const +{ + if (m_height * m_width == 1) + return true; + + Debug(DebugTypeError, "AI/AIDLL/AI/AIStrategicMap/ScalarMap.cpp", 45, "") << "Does not work"; + + IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); + const float* const v = m_values; + if (row >= 0) + { + int y = row ? row : 1; + for (; y < m_height - 1; ++y) + { + if (timer->getUpdateTime() >= deadline) + { + row = y; + return false; + } + for (int x = 1; x < m_width - 1; ++x) + { + float& out = result.m_values[y * result.m_width + x]; + out = v[(y - 1) * m_width + x - 1]; + out += v[y * m_width + x - 1]; + out += v[(y + 1) * m_width + x - 1]; + out += v[(y - 1) * m_width + x]; + out += v[y * m_width + x]; + out += v[(y + 1) * m_width + x]; + out += v[(y - 1) * m_width + x + 1]; + out += v[y * m_width + x + 1]; + out += v[(y + 1) * m_width + x + 1]; + out *= 0.11111111f; + } + } + row = -1; + if (timer->getUpdateTime() >= deadline) + return false; + } + + // Top row. + for (int x = 1; x < m_width - 1; ++x) + { + float& out = result.m_values[x]; + out = v[x - 1]; + out += v[m_width + x - 1]; + out += v[x]; + out += v[m_width + x]; + out += v[x + 1]; + out += v[m_width + x + 1]; + out *= 0.16666667f; + } + // Bottom row. + for (int x = 1; x < m_width - 1; ++x) + { + float& out = result.m_values[(m_height - 1) * result.m_width + x]; + out = v[(m_height - 2) * m_width + x - 1]; + out += v[(m_height - 1) * m_width + x - 1]; + out += v[(m_height - 2) * m_width + x]; + out += v[(m_height - 1) * m_width + x]; + out += v[(m_height - 2) * m_width + x + 1]; + out += v[(m_height - 1) * m_width + x + 1]; + out *= 0.16666667f; + } + // Left column. + for (int y = 1; y < m_height - 1; ++y) + { + float& out = result.m_values[y * result.m_width]; + out = v[(y - 1) * m_width]; + out += v[y * m_width]; + out += v[(y + 1) * m_width]; + out += v[(y - 1) * m_width + 1]; + out += v[y * m_width + 1]; + out += v[(y + 1) * m_width + 1]; + out *= 0.16666667f; + } + // Right column. + for (int y = 1; y < m_height - 1; ++y) + { + float& out = result.m_values[y * result.m_width + m_width - 1]; + out = v[(y - 1) * m_width + m_width - 2]; + out += v[y * m_width + m_width - 2]; + out += v[(y + 1) * m_width + m_width - 2]; + out += v[(y - 1) * m_width + m_width - 1]; + out += v[y * m_width + m_width - 1]; + out += v[(y + 1) * m_width + m_width - 1]; + out *= 0.16666667f; + } + // Corners. + { + float& out = result.m_values[0]; + out = v[0]; + out += v[m_width]; + out += v[1]; + out += v[m_width + 1]; + out *= 0.25f; + } + { + float& out = result.m_values[m_width - 1]; + out = v[m_width - 2]; + out += v[2 * m_width - 2]; + out += v[m_width - 1]; + out += v[2 * m_width - 1]; + out *= 0.25f; + } + { + float& out = result.m_values[(m_height - 1) * result.m_width]; + out = v[(m_height - 2) * m_width]; + out += v[(m_height - 1) * m_width]; + out += v[(m_height - 2) * m_width + 1]; + out += v[(m_height - 1) * m_width + 1]; + out *= 0.25f; + } + { + float& out = result.m_values[(m_height - 1) * result.m_width + m_width - 1]; + out = v[(m_height - 2) * m_width + m_width - 2]; + out += v[(m_height - 1) * m_width + m_width - 2]; + out += v[(m_height - 2) * m_width + m_width - 1]; + out += v[(m_height - 1) * m_width + m_width - 1]; + out *= 0.25f; + } + return true; +} + +// ELF 0x365890. The queue starts with count placeholders {-1, -1e20}; a value above the smallest +// kept one replaces it. The queue is then emptied smallest first from the back of indices. +void ScalarMap::sortLargest(int count, int* indices) const +{ + std::priority_queue queue; + PQElem element(-1, -1e20f); + float threshold = -1e20f; + for (int i = 0; i < count; ++i) + queue.push(element); + for (int i = 0; i < m_width * m_height; ++i) + { + if (m_values[i] > threshold) + { + queue.pop(); + element.m_index = i; + element.m_value = m_values[i]; + queue.push(element); + threshold = queue.top().m_value; + } + } + for (int i = count - 1; i >= 0; --i) + { + indices[i] = queue.top().m_index; + queue.pop(); + } +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/ScalarMap.h b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/ScalarMap.h new file mode 100644 index 000000000..739413862 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/ScalarMap.h @@ -0,0 +1,37 @@ +// A row-major grid of floats over the strategic map. Evidence: libaidll.so (ia-32) +// 0x364640..0x365FF8; sizeof 12 (width, height, the owned array). Member names [INFERRED]. + +#ifndef AI_AIDLL_AI_AISTRATEGICMAP_SCALARMAP_H // [INFERRED] guard style +#define AI_AIDLL_AI_AISTRATEGICMAP_SCALARMAP_H + +namespace dice { +namespace hfe { +namespace ai { + +class ScalarMap +{ +public: + // Allocates width * height uninitialised values (checkPointer reports a failed allocation). + ScalarMap(int width, int height); + ~ScalarMap(); + + // Writes the 3x3 (edges 2x3, corners 2x2) box average of this map into result, which must + // have this map's size. Interior rows are resumable: row is the row to continue at (0 starts + // at the first interior row, -1 skips them); when the update-time budget (IBFTimer + // getUpdateTime() >= deadline) runs out the next row is stored and false returned. A 1x1 map + // answers true at once; any other size reports the shipped "Does not work" error first. + bool smooth(ScalarMap& result, double deadline, int& row) const; + // indices[0..count) receive the indices of the count largest values, largest last; with fewer + // candidates above -1e20 the remaining entries are -1. + void sortLargest(int count, int* indices) const; + + /* +0x0 */ int m_width; + /* +0x4 */ int m_height; + /* +0x8 */ float* m_values; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGICMAP_SCALARMAP_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/StatusMap.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/StatusMap.cpp new file mode 100644 index 000000000..2445d936b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/StatusMap.cpp @@ -0,0 +1,39 @@ +// Strategic status grid. Evidence: libaidll.so (ia-32) 0x366000..0x3663E8, a TU of its own +// without static initialisation between ScalarMap.cpp and SAIMapSquare.cpp. Its placement in +// AIStrategicMap is [INFERRED] from that address range; the header stays in AIStrategic. + +#include "../AIStrategic/StatusMap.h" + +#include "../AIUtils/checkPointer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x366000 (C2; C1 0x366160). +StatusMap::StatusMap(int width, int height) + : m_width(width) + , m_height(height) +{ + m_statuses = checkPointer(new Status[width * height]); +} + +// ELF 0x3662C0 (D2; D1 0x3662F0). +StatusMap::~StatusMap() +{ + if (m_statuses) + delete[] m_statuses; +} + +// ELF 0x366320. +void StatusMap::getOwnedSquares(std::vector& squares) const +{ + for (int y = 0; y < m_height; ++y) + for (int x = 0; x < m_width; ++x) + if (m_statuses[y * m_width + x] == Owned) + squares.push_back(x + y * m_width); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/TemperatureTree.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/TemperatureTree.cpp new file mode 100644 index 000000000..29ea0de46 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/TemperatureTree.cpp @@ -0,0 +1,107 @@ +// Strategic temperature tree. Evidence: libaidll.so (ia-32) 0x366510..0x366A55. The TU has no +// static initialisation in the image. Placement next to TemperatureTreeModifiers is [INFERRED] +// from the address range. + +#include "TemperatureTree.h" + +#include "TemperatureTreeModifiers.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x366510 (C2; C1 0x366540). +TemperatureTree::TemperatureTree() +{ + reset(); +} + +// ELF 0x366570 (C2; C1 0x3665C0): the ten words in order. The memberwise spelling is [INFERRED]. +TemperatureTree::TemperatureTree(const TemperatureTree& other) +{ + *this = other; +} + +// ELF 0x366610. +void TemperatureTree::reset() +{ + for (int i = 0; i <= 4; ++i) + { + m_temperatures[i] = 0.0f; + m_weights[i] = 1.0f; + } +} + +// ELF 0x366650. +void TemperatureTree::addTemperature(TemperatureTreeModifiers* modifiers, TemperatureTreeNode node, float temperature, float weight) +{ + propagateToParents(modifiers, node, temperature, weight); +} + +// ELF 0x3666A0. +void TemperatureTree::addTemperature(TemperatureTreeModifiers* modifiers, TemperatureTreeNode node, float* strengths, float weight) +{ + float temperature = 0.0f; + for (int i = 0; i <= 5; ++i) + temperature += strengths[i] * modifiers->m_combatStrengthModifiers[node][i]; + propagateToParents(modifiers, node, temperature, weight); +} + +// ELF 0x366720. +void TemperatureTree::addTemperature(TemperatureTreeModifiers* modifiers, TemperatureTreeNode node, float* strengths, float scale, float weight) +{ + float temperature = 0.0f; + for (int i = 0; i <= 5; ++i) + temperature += strengths[i] * modifiers->m_combatStrengthModifiers[node][i]; + propagateToParents(modifiers, node, temperature * scale, weight); +} + +// ELF 0x3667A0. +void TemperatureTree::addTemperature(const TemperatureTree& other) +{ + for (int i = 0; i <= 4; ++i) + m_temperatures[i] += other.m_temperatures[i]; +} + +// ELF 0x3667D0: a jump table over the 41 nodes; the image turns the parent calls into a loop. +// Nodes 0..4 are stored (temperature += t * modifier, weight *= w); every node except the root +// passes t * its modifier on to its parent. Nodes above 40 are ignored. +// [CHOSEN, not recovered] each level's product is rounded to float; the ELF keeps it in x87. +void TemperatureTree::propagateToParents(TemperatureTreeModifiers* modifiers, TemperatureTreeNode node, float temperature, float weight) +{ + const float* const m = modifiers->m_nodeModifiers; + int parent; + switch (static_cast(node)) + { + case 0: + m_temperatures[0] += temperature * m[0]; + m_weights[0] *= weight; + return; + case 1: case 2: case 3: case 4: + m_temperatures[node] += temperature * m[node]; + m_weights[node] *= weight; + parent = (node <= 2) ? 0 : 1; + break; + case 5: case 6: parent = 2; break; + case 7: case 9: case 13: parent = 3; break; + case 8: case 10: case 15: parent = 4; break; + case 29: case 30: case 31: case 32: parent = 5; break; + case 33: case 34: case 35: case 36: case 37: case 38: parent = 6; break; + case 11: case 12: parent = 7; break; + case 14: case 16: parent = 8; break; + case 17: case 18: parent = 11; break; + case 19: case 20: parent = 12; break; + case 21: case 22: parent = 13; break; + case 23: case 24: parent = 14; break; + case 27: case 28: parent = 15; break; + case 25: case 26: parent = 16; break; + case 39: case 40: parent = 38; break; + default: + return; + } + propagateToParents(modifiers, static_cast(parent), temperature * m[node], weight); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/TemperatureTree.h b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/TemperatureTree.h new file mode 100644 index 000000000..ff6c73676 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/TemperatureTree.h @@ -0,0 +1,44 @@ +// Per-square strategic temperature: five top-level tree nodes, each with an accumulated +// temperature and a multiplicative weight. Deeper nodes of the 41-node TemperatureTreeNode tree +// only scale a contribution on its way up to one of the five. Evidence: libaidll.so (ia-32) +// 0x366510..0x366A55; sizeof 40 (the copy constructor copies ten words). Member names [INFERRED]. + +#ifndef AI_AIDLL_AI_AISTRATEGICMAP_TEMPERATURETREE_H // [INFERRED] guard style +#define AI_AIDLL_AI_AISTRATEGICMAP_TEMPERATURETREE_H + +namespace dice { +namespace hfe { +namespace ai { + +class TemperatureTreeModifiers; +enum TemperatureTreeNode : int; // index 0..40 + +class TemperatureTree +{ +public: + TemperatureTree(); + TemperatureTree(const TemperatureTree& other); + + // Every temperature to 0, every weight to 1. + void reset(); + // Adds temperature at node (scaled by the modifiers up the tree) and multiplies the weight of + // every top-level node on the way by weight. + void addTemperature(TemperatureTreeModifiers* modifiers, TemperatureTreeNode node, float temperature, float weight); + // As above with the temperature formed from six combat strengths and the node's per-strength + // modifiers. + void addTemperature(TemperatureTreeModifiers* modifiers, TemperatureTreeNode node, float* strengths, float weight); + // As above with the strength sum multiplied by scale first. + void addTemperature(TemperatureTreeModifiers* modifiers, TemperatureTreeNode node, float* strengths, float scale, float weight); + // Adds the other tree's temperatures; the weights are untouched. + void addTemperature(const TemperatureTree& other); + void propagateToParents(TemperatureTreeModifiers* modifiers, TemperatureTreeNode node, float temperature, float weight); + + /* +0x00 */ float m_temperatures[5]; + /* +0x14 */ float m_weights[5]; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGICMAP_TEMPERATURETREE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/TemperatureTreeModifiers.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/TemperatureTreeModifiers.cpp new file mode 100644 index 000000000..dab0cb98f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/TemperatureTreeModifiers.cpp @@ -0,0 +1,26 @@ +// Temperature-tree modifiers. Evidence: libaidll.so (ia-32) 0x366A60..0x366B20. + +#include "TemperatureTreeModifiers.h" + +namespace dice { +namespace hfe { +namespace ai { + +TemperatureTreeModifiers::TemperatureTreeModifiers() +{ + reset(); +} + +// ELF 0x366AC0. +void TemperatureTreeModifiers::reset() +{ + for (unsigned int node = 0; node <= 40; ++node) + m_nodeModifiers[node] = 1.0f; + for (unsigned int node = 0; node <= 55; ++node) + for (unsigned int type = 0; type <= 5; ++type) + m_combatStrengthModifiers[node][type] = 1.0f; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/TemperatureTreeModifiers.h b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/TemperatureTreeModifiers.h new file mode 100644 index 000000000..955b6c35f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/TemperatureTreeModifiers.h @@ -0,0 +1,28 @@ +// Per-strategy multipliers for the strategic temperature tree: one per tree node and one per +// (node, combat-strength type). Evidence: libaidll.so (ia-32) 0x366A60..0x366B20 (constructor, +// reset) and Strategy's accessors (0x333930..0x333A80); operator new(0x5E4) in Strategy's +// constructor. Source file attested as TemperatureTreeModifiers.cpp (AIStrategicMap link block). + +#ifndef AI_AIDLL_AI_AISTRATEGICMAP_TEMPERATURETREEMODIFIERS_H +#define AI_AIDLL_AI_AISTRATEGICMAP_TEMPERATURETREEMODIFIERS_H + +namespace dice { +namespace hfe { +namespace ai { + +class TemperatureTreeModifiers +{ +public: + TemperatureTreeModifiers(); + void reset(); // every multiplier to 1.0f + + /* +0x000 */ float m_nodeModifiers[41]; // TemperatureTreeNode 0..40 + /* +0x0A4 */ float m_combatStrengthModifiers[56][6]; // [node][CombatStrengthType]; reset + // covers 56 rows, setters only 0..40 +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGICMAP_TEMPERATURETREEMODIFIERS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/AIVectorMath.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/AIVectorMath.cpp new file mode 100644 index 000000000..fdb1de108 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/AIVectorMath.cpp @@ -0,0 +1,103 @@ +// Free vector helpers of the AI image. See AIVectorMath.h for the placement note. + +#include "AIVectorMath.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x3679F0, __tcf_0 0x367A50, _GLOBAL__I 0x367A80). +#include + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x367500. +float distancePointLineSqr(const Vec3& point, const Vec3& linePoint, const Vec3& direction) +{ + const float dx = point.x - linePoint.x; + const float dy = point.y - linePoint.y; + const float dz = point.z - linePoint.z; + const float cx = direction.z * dy - direction.y * dz; + const float cy = dz * direction.x - direction.z * dx; + const float cz = dx * direction.y - dy * direction.x; + return (cx * cx + cy * cy + cz * cz) + / (direction.x * direction.x + direction.y * direction.y + direction.z * direction.z); +} + +// objFireLineDist - libaidll.so (ia-32) 0x367590, 687 B (objdump listing and Ghidra, 2026-11-02). +// The segment direction is normalised by multiplying with 1/length; the projection parameter +// is the dot product of that direction with point - from. Below zero the start is nearest, +// beyond the length the end; an unordered parameter takes the projection branch, as compiled. +float objFireLineDist(const Vec3& point, const Vec3& from, const Vec3& to) +{ + float result = 0.0f; + const float sx = to.x - from.x; + const float sy = to.y - from.y; + const float sz = to.z - from.z; + const float length = std::sqrt(sx * sx + sy * sy + sz * sz); + if (length < 0.001f) + return result; + + const float inv = 1.0f / length; + const float dirX = sx * inv; + const float dirY = sy * inv; + const float dirZ = sz * inv; + float dx = point.x - from.x; + float dy = point.y - from.y; + float dz = point.z - from.z; + const float t = dirX * dx + dirY * dy + dirZ * dz; + if (!(t < 0.0f)) + { + if (t > length) + { + dx = point.x - to.x; + dy = point.y - to.y; + dz = point.z - to.z; + } + else + { + dx -= dirX * t; + dy -= dirY * t; + dz -= dirZ * t; + } + } + result = std::sqrt(dx * dx + dy * dy + dz * dz); + return result; +} + +// ELF 0x367840. Row 2 is saved, row 1 set to `up`; row 0 takes the third axis of (row 1, row 2) +// (which rewrites rows 1 and 2), row 2 is put back, and row 1 takes the third axis of +// (row 2, row 0). +void makeTransOrthonormalUp(Mat4& transformation, const Vec3& up) +{ + Vec3& right = *reinterpret_cast(&transformation.m[0]); + Vec3& upRow = *reinterpret_cast(&transformation.m[4]); + Vec3& forward = *reinterpret_cast(&transformation.m[8]); + const Vec3 savedForward = forward; + upRow = up; + right.makeOrthonormalBasis(upRow, forward); + forward = savedForward; + upRow.makeOrthonormalBasis(forward, right); +} + +// ELF 0x3678D0. A zeroed matrix (the shipped Mat4 construction) set to identity; row 2 becomes +// `direction`; then row 1 takes the third axis of (row 2, row 0) and row 0 that of (row 1, row 2). +Mat4 getDofTransformation(const Vec3& direction) +{ + Mat4 transformation; + for (int i = 0; i < 16; ++i) + transformation.m[i] = 0.0f; + transformation = Mat4::getIdentity(); + Vec3& right = *reinterpret_cast(&transformation.m[0]); + Vec3& up = *reinterpret_cast(&transformation.m[4]); + Vec3& forward = *reinterpret_cast(&transformation.m[8]); + forward = direction; + up.makeOrthonormalBasis(forward, right); + right.makeOrthonormalBasis(up, forward); + return transformation; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/AIVectorMath.h b/Code/BF2/AI/AIDLL/AI/AIUtils/AIVectorMath.h new file mode 100644 index 000000000..328c1faa1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/AIVectorMath.h @@ -0,0 +1,38 @@ +// Free vector helpers of the AI image (namespace dice::hfe::ai). +// [INFERRED] Source placement and file name: libaidll.so keeps these in one translation unit with +// its own static initializer (ELF 0x367500..0x367A9F: distancePointLineSqr, objFireLineDist, +// makeTransOrthonormalUp, getDofTransformation); no __FILE__ string attests the path. + +#ifndef AI_AIDLL_AI_AIUTILS_AIVECTORMATH_H +#define AI_AIDLL_AI_AIUTILS_AIVECTORMATH_H + +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +// Squared distance from `point` to the infinite line through `linePoint` along `direction` +// (|(point - linePoint) x direction|^2 / |direction|^2). A zero direction divides by zero. +// No caller in libaidll.so. +float distancePointLineSqr(const Vec3& point, const Vec3& linePoint, const Vec3& direction); + +// Distance from `point` to the segment from `from` to `to`: the perpendicular distance where the +// projection falls inside the segment, otherwise the distance to the nearer end. A segment +// shorter than 0.001 answers 0. +float objFireLineDist(const Vec3& point, const Vec3& from, const Vec3& to); + +// Re-orthonormalises `transformation` around `up`: row 1 becomes `up`, then the rows are rebuilt +// keeping row 2's direction (the forward vector). No caller in libaidll.so. +void makeTransOrthonormalUp(Mat4& transformation, const Vec3& up); + +// An orthonormal transformation whose row 2 points along `direction`, no translation. No caller +// in libaidll.so. +Mat4 getDofTransformation(const Vec3& direction); + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIUTILS_AIVECTORMATH_H diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/AimerHelper.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/AimerHelper.cpp new file mode 100644 index 000000000..c12c66fda --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/AimerHelper.cpp @@ -0,0 +1,75 @@ +// Ballistic arc helper. [INFERRED] Source placement. + +// static init: ELF 0x2EA8B0 (__tcf_0 0x2EA910, _GLOBAL__I 0x2EA940): 's Init object only. +#include + +#include "AimerHelper.h" + +#include "checkPointer.h" +#include "../AIBotActionPlan/Aimer.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2EA2D0 (C1; C2 0x2EA160). +AimerHelper::AimerHelper() : m_aimer(checkPointer(new Aimer())) +{ +} + +// ELF 0x2EA4A0 (D1; D2 0x2EA440, D0 0x2EA500). +AimerHelper::~AimerHelper() +{ + if (m_aimer) + delete m_aimer; +} + +// ELF 0x2EA570 (amd-64 0x335D50). +bool AimerHelper::hasIndirectLineOfFire(float speed, const float& drag, const float& gravity, + const Vec3& relativePosition, const Vec3& origin, Vec3& predictedTarget, Vec3& velocity, Vec3& apex) +{ + m_aimer->m_speed = speed; + m_aimer->m_drag = drag; + m_aimer->m_inverseDrag = drag != 0.0f ? 1.0f / drag : 0.0f; + m_aimer->m_gravity = gravity; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + static Vec3 zero = {0.0f, 0.0f, 0.0f}; + const Vec3 shooterVelocity = {0.0f, 0.0f, 0.0f}; + m_aimer->setTargetData(relativePosition, zero, shooterVelocity, 0, now); + if (!m_aimer->getFiringDirection(now, 0.5f, true, velocity, predictedTarget, 0)) + return false; + const float lengthSqr = velocity.x * velocity.x + velocity.y * velocity.y + velocity.z * velocity.z; + if (!(std::fabs(lengthSqr - 1.0f) < 1.1920929e-07f)) + { + if (std::fabs(lengthSqr) < 1.1920929e-07f) + velocity.x = velocity.y = velocity.z = 0.0f; + else + { + const float inverse = 1.0f / std::sqrt(lengthSqr); + velocity.x *= inverse; + velocity.y *= inverse; + velocity.z *= inverse; + } + } + velocity.x *= speed; + velocity.y *= speed; + velocity.z *= speed; + const double extreme = m_aimer->getVerticalExtreme(); + const float time = static_cast(extreme); + const float halfTimeSquared = static_cast(extreme * extreme * 0.5); + const Vec3 displacement = {time * velocity.x, time * velocity.y, time * velocity.z}; + const Vec3 position = {displacement.x + origin.x, displacement.y + origin.y, displacement.z + origin.z}; + // Preserve the zero acceleration terms as well: zero times an infinite time is NaN. + const Vec3 fall = {halfTimeSquared * 0.0f, halfTimeSquared * gravity, halfTimeSquared * 0.0f}; + const Vec3 result = {position.x + fall.x, position.y + fall.y, position.z + fall.z}; + apex = result; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/AimerHelper.h b/Code/BF2/AI/AIDLL/AI/AIUtils/AimerHelper.h new file mode 100644 index 000000000..e82432db9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/AimerHelper.h @@ -0,0 +1,34 @@ +// Owns a ballistic aimer; the inherited slot remains pure. [INFERRED] Source placement. + +#ifndef AI_AIDLL_AI_AIUTILS_AIMERHELPER_H +#define AI_AIDLL_AI_AIUTILS_AIMERHELPER_H + +#include "IAimerHelper.h" + +namespace dice { +namespace hfe { +namespace ai { + +class Aimer; + +class AimerHelper : public IAimerHelper +{ +public: + AimerHelper(); + virtual ~AimerHelper(); + + // Finds a high arc, returning its predicted target, initial velocity and apex. + // ELF 0x2EA570: a new slot 3 (+0x0C ia-32, +0x18 amd-64), not a slot-2 override. + virtual bool hasIndirectLineOfFire(float speed, const float& drag, const float& gravity, + const Vec3& relativePosition, const Vec3& origin, Vec3& predictedTarget, + Vec3& velocity, Vec3& apex); + +private: + /* +0x04 (amd-64 +0x08) */ Aimer* m_aimer; // owned +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/CustomCurve.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/CustomCurve.cpp similarity index 61% rename from Code/BF2/AI/AIDLL/AI/AIBotBehaviour/CustomCurve.cpp rename to Code/BF2/AI/AIDLL/AI/AIUtils/CustomCurve.cpp index 7c1f7e3e1..40bbf04e0 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/CustomCurve.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/CustomCurve.cpp @@ -1,30 +1,23 @@ -// [INFERRED] Source placement. +// Source placement: retail libaidll.so 1.50 embeds "AI/AIDLL/AI/AIUtils/CustomCurve.cpp" (CustomCurve's asserts). #include "CustomCurve.h" -#include // isfinite - SCurve's guard only +#include // CustomCurve: the image asserts + +#include +#include +// static init: ELF 0x36E0E0, 0x36E140, 0x36E170: CustomCurve.cpp's iostream Init only. namespace dice { namespace hfe { namespace ai { -float* SCurve::curveValues = 0; +// SCurve lives in SCurve.cpp (AIDLL_r __FILE__). float* JCurve::curveValues = 0; float* DecleiningSlopeCurve::curveValues = 0; // Builds the shared table on construction and frees it on destruction. // Destruction retains the null guard and does not clear the shared pointer. -SCurve::SCurve() -{ - init(); -} - -SCurve::~SCurve() -{ - if (curveValues) - delete[] curveValues; -} - JCurve::JCurve() { init(); @@ -47,24 +40,6 @@ DecleiningSlopeCurve::~DecleiningSlopeCurve() delete[] curveValues; } -// Returns zero for non-finite input and clamps x >= 1 to one before interpolation. -// [PLATFORM] Uses the standard isfinite name for the original finite predicate. -float SCurve::calculate(float x) -{ - if (!std::isfinite(x)) - return 0.0f; - if (x >= 1.0f) - return 1.0f; - if (x < 0.0f) - return 0.0f; - - const float scaled = x * 100.0f; - const int index = static_cast(scaled); - const float frac = scaled - static_cast(index); - - return frac * curveValues[index + 1] + (1.0f - frac) * curveValues[index]; -} - // Extrapolates above one and has no NaN guard. At x == 1, interpolation reads one // element beyond the 101-entry table even though its coefficient is zero. float JCurve::calculate(float x) @@ -97,125 +72,6 @@ float DecleiningSlopeCurve::calculate(float x) return (1.0f - frac) * curveValues[index] + frac * curveValues[index + 1]; } -// 101 constants, transcribed. -void SCurve::init() -{ - curveValues = new float[101]; // operator new[](0x194) = 101 * 4 - - curveValues[ 0] = 0.0f; - curveValues[ 1] = 0.00224938989f; - curveValues[ 2] = 0.00338781998f; - curveValues[ 3] = 0.00463052979f; - curveValues[ 4] = 0.00598675013f; - curveValues[ 5] = 0.00746650994f; - curveValues[ 6] = 0.00908064004f; - curveValues[ 7] = 0.0108407997f; - curveValues[ 8] = 0.0127597004f; - curveValues[ 9] = 0.0148508996f; - - curveValues[ 10] = 0.0171288997f; - curveValues[ 11] = 0.0196096003f; - curveValues[ 12] = 0.0223098006f; - curveValues[ 13] = 0.0252474006f; - curveValues[ 14] = 0.0284416005f; - curveValues[ 15] = 0.0319131017f; - curveValues[ 16] = 0.0356835015f; - curveValues[ 17] = 0.0397756994f; - curveValues[ 18] = 0.0442142002f; - curveValues[ 19] = 0.0490242988f; - - curveValues[ 20] = 0.0542327985f; - curveValues[ 21] = 0.0598676018f; - curveValues[ 22] = 0.0659573004f; - curveValues[ 23] = 0.0725317001f; - curveValues[ 24] = 0.0796212032f; - curveValues[ 25] = 0.0872564986f; - curveValues[ 26] = 0.0954684988f; - curveValues[ 27] = 0.104287997f; - curveValues[ 28] = 0.113744996f; - curveValues[ 29] = 0.123869002f; - - curveValues[ 30] = 0.134688005f; - curveValues[ 31] = 0.146227002f; - curveValues[ 32] = 0.158509001f; - curveValues[ 33] = 0.171553999f; - curveValues[ 34] = 0.185376003f; - curveValues[ 35] = 0.199987993f; - curveValues[ 36] = 0.215393007f; - curveValues[ 37] = 0.231592f; - curveValues[ 38] = 0.248576f; - curveValues[ 39] = 0.266330004f; - - curveValues[ 40] = 0.284830987f; - curveValues[ 41] = 0.304048002f; - curveValues[ 42] = 0.323940992f; - curveValues[ 43] = 0.344460994f; - curveValues[ 44] = 0.365550995f; - curveValues[ 45] = 0.387147993f; - curveValues[ 46] = 0.409179002f; - curveValues[ 47] = 0.431564987f; - curveValues[ 48] = 0.45422399f; - curveValues[ 49] = 0.477064997f; - - curveValues[ 50] = 0.5f; - curveValues[ 51] = 0.52293402f; - curveValues[ 52] = 0.54577601f; - curveValues[ 53] = 0.568435013f; - curveValues[ 54] = 0.590821028f; - curveValues[ 55] = 0.612851977f; - curveValues[ 56] = 0.634449005f; - curveValues[ 57] = 0.655538976f; - curveValues[ 58] = 0.676059008f; - curveValues[ 59] = 0.695951998f; - - curveValues[ 60] = 0.715167999f; - curveValues[ 61] = 0.733669996f; - curveValues[ 62] = 0.751424015f; - curveValues[ 63] = 0.768408f; - curveValues[ 64] = 0.784606993f; - curveValues[ 65] = 0.800011992f; - curveValues[ 66] = 0.814624012f; - curveValues[ 67] = 0.828445971f; - curveValues[ 68] = 0.841490984f; - curveValues[ 69] = 0.853772998f; - - curveValues[ 70] = 0.86531198f; - curveValues[ 71] = 0.876130998f; - curveValues[ 72] = 0.886255026f; - curveValues[ 73] = 0.895712018f; - curveValues[ 74] = 0.904532015f; - curveValues[ 75] = 0.912743986f; - curveValues[ 76] = 0.920378983f; - curveValues[ 77] = 0.927468002f; - curveValues[ 78] = 0.93404299f; - curveValues[ 79] = 0.940132022f; - - curveValues[ 80] = 0.945766985f; - curveValues[ 81] = 0.950976014f; - curveValues[ 82] = 0.95578599f; - curveValues[ 83] = 0.960223973f; - curveValues[ 84] = 0.964317024f; - curveValues[ 85] = 0.968087018f; - curveValues[ 86] = 0.971557975f; - curveValues[ 87] = 0.974753022f; - curveValues[ 88] = 0.977689981f; - curveValues[ 89] = 0.980390012f; - - curveValues[ 90] = 0.982870996f; - curveValues[ 91] = 0.985149026f; - curveValues[ 92] = 0.987240016f; - curveValues[ 93] = 0.989158988f; - curveValues[ 94] = 0.990918994f; - curveValues[ 95] = 0.992533982f; - curveValues[ 96] = 0.994013011f; - curveValues[ 97] = 0.995369017f; - curveValues[ 98] = 0.996612012f; - curveValues[ 99] = 0.997750998f; - - curveValues[100] = 1.0f; - -} - // 101 constants, transcribed. void JCurve::init() { @@ -454,6 +310,162 @@ void DecleiningSlopeCurve::init() } +// ELF 0x36D630 +CustomCurve::CustomCurve(Function function, float min, float max, float step) + : m_function(function) + , m_table(0) + , m_min(min) + , m_max(max) + , m_step(step) +{ + init(); +} + +// ELF 0x36D7D0 +CustomCurve::~CustomCurve() +{ + if (m_table) + delete[] m_table; +} + +// ELF 0x36D800. The image asserts (expression "0") when x is outside [min, max] and when the +// interpolated index has no successor. +float CustomCurve::calculate(float x, bool interpolate) const +{ + if (m_min > x || x > m_max) + assert(0); + // The image keeps the step, offset and fraction on the x87 stack; doubles stand in for that. + const double step = (static_cast(m_max) - m_min) / static_cast(static_cast(m_size)); + const double offset = static_cast(x) - m_min; + const int index = static_cast(static_cast(offset / step)); + if (!interpolate) + return m_table[index]; + const double fraction = (offset - static_cast(static_cast(index)) * step) / step; + if (index >= m_size) + assert(0); + return static_cast(m_table[index] + (static_cast(m_table[index + 1]) - m_table[index]) * fraction); +} + +// ELF 0x36DFB0. Samples m_size + 1 points, then writes the two ends again from min and max exactly. +void CustomCurve::init() +{ + if (0.0f >= m_step) + assert(0); + if (m_table) + delete[] m_table; + m_size = static_cast(static_cast((static_cast(m_max) - m_min) / m_step)); + m_table = new float[m_size + 1]; + const double delta = (static_cast(m_max) - m_min) / static_cast(static_cast(m_size)); + for (int i = 0; i <= m_size; ++i) + m_table[i] = m_function(m_min + static_cast(i * delta)); + m_table[0] = m_function(m_min); + m_table[m_size] = m_function(m_max); +} + +// ELF 0x36D680 (C2), 0x36D6D0 (C1): resamples the function instead of copying table entries. +CustomCurve::CustomCurve(const CustomCurve& other) + : m_function(other.m_function), m_table(0), m_min(other.m_min), m_max(other.m_max), m_step(other.m_step) +{ + init(); +} + +// ELF 0x36D720. Shipped quirk: returns a new, resampled curve by value, even on self-assignment. +CustomCurve CustomCurve::operator=(const CustomCurve& other) +{ + if (this != &other) + { + if (m_table) delete[] m_table; + m_table = 0; + m_function = other.m_function; + m_min = other.m_min; + m_max = other.m_max; + m_step = other.m_step; + init(); + } + return *this; +} + +// ELF 0x36D8F0: zero-valued function samples contribute no error but still count in the divisor. +float CustomCurve::testAccuracy(float density, bool interpolate) const +{ + if (0.0f >= density) assert(0); + float error = 0.0f; + const float width = m_max - m_min; + const int count = static_cast(static_cast(m_size) * density); + const float divisor = static_cast(count); + const float step = width / divisor; + for (int i = 0; i < count; ++i) + { + const float position = m_min + static_cast(i) * step; + const float actual = m_function(position); + const float estimated = calculate(position, interpolate); + if (actual != 0.0f) error += std::fabs(estimated - actual); + } + return error / divisor; +} + +// ELF 0x36DA40. Shipped defect: the second pass also asks for interpolation. +bool CustomCurve::testBounds(float density, float minimum, float maximum) const +{ + if (0.0f >= density) assert(0); + bool valid = true; + for (float position = m_min; position < m_max; + position += (m_max - m_min) / (static_cast(m_size) * density)) + { + const float value = calculate(position, true); + if (value < minimum || value > maximum) + { + std::cout << "Interpolated value[" << position << "] = " << value + << " is out of boundary (" << minimum << "," << maximum << ")\n"; + valid = false; + } + } + for (float position = m_min; position < m_max; + position += (m_max - m_min) / (static_cast(m_size) * density)) + { + const float value = calculate(position, true); + if (value < minimum || value > maximum) + { + std::cout << "Non-interpolated value[" << position << "] = " << value + << " is out of boundary (" << minimum << "," << maximum << ")\n"; + valid = false; + } + } + if (valid) + std::cout << "All values are within bounds (" << minimum << "," << maximum << ")\n"; + else + std::cout << "BOUNDS CHECK : Failed\n"; + return valid; +} + +// ELF 0x36DD60. +void CustomCurve::accuracyTest(float density) const +{ + std::cout << "\nACCURACY TESTS:\n"; + const float interpolated = testAccuracy(density, true); + const float direct = testAccuracy(density, false); + std::cout << "Curve is " << (1.0f - direct) * 100.0f << "% accurate without interpolation\n"; + std::cout << "Curve is " << (1.0f - interpolated) * 100.0f << "% accurate with interpolation\n"; +} + +// ELF 0x36DE60: the fourth argument is unused; the byte estimate omits the final table element. +void CustomCurve::getStatistics(float density, float minimum, float maximum, int /*flags*/) const +{ + std::cout << "\nCUSTOMCURVE STATISTICS\n----------------------\n"; + std::cout << "Curve has " << m_size << " elements and uses a total of " + << sizeof(CustomCurve) + m_size * sizeof(float) << " bytes.\n\n"; + testBounds(density, minimum, maximum); + accuracyTest(density); +} + +// ELF 0x36DF50: preserves negative zero and unordered values. +float CustomCurve::calculateEstimation(float value, bool& nonnegative) const +{ + if (value < 0.0f) { nonnegative = false; return -value; } + nonnegative = true; + return value; +} + } // namespace ai } // namespace hfe } // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/CustomCurve.h b/Code/BF2/AI/AIDLL/AI/AIUtils/CustomCurve.h new file mode 100644 index 000000000..e17f6c616 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/CustomCurve.h @@ -0,0 +1,80 @@ +// Samples a supplied curve function into a table for later evaluation. +// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. +// Header placement [INFERRED]: beside its .cpp, whose path retail libaidll.so 1.50 embeds (AIUtils/CustomCurve.cpp). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_CUSTOMCURVE_H // [INFERRED] guard style +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_CUSTOMCURVE_H + +#include + +#include "SCurve.h" // SCurve (AIUtils/SCurve.cpp); kept reachable through this header + +namespace dice { +namespace hfe { +namespace ai { + +class JCurve +{ +public: + JCurve(); + ~JCurve(); + static void init(); + static float calculate(float x); // - extrapolates above 1 + static float* curveValues; +}; + +class DecleiningSlopeCurve // dice's spelling +{ +public: + DecleiningSlopeCurve(); + ~DecleiningSlopeCurve(); + static void init(); + static float calculate(float x); + static float* curveValues; +}; + +// A function sampled into a table over [min, max] (AI/AIDLL/AI/AIUtils/CustomCurve.cpp in the image). +// Recovered by ai-w1-d-behaviours for BBFire (its constructor builds one); libaidll.so addresses. +class CustomCurve +{ +public: + typedef float (*Function)(float); + + CustomCurve(Function function, float min, float max, float step); // 0x36D630 + ~CustomCurve(); // 0x36D7D0 + + // Table lookup of x in [min, max] (asserts outside), linearly interpolated when asked. + float calculate(float x, bool interpolate) const; // 0x36D800 + float testAccuracy(float density, bool interpolate) const; + bool testBounds(float density, float minimum, float maximum) const; + void accuracyTest(float density) const; + void getStatistics(float density, float minimum, float maximum, int flags) const; + float calculateEstimation(float value, bool& nonnegative) const; + + // Weak in BBFire.cpp (0x20BAB0): powf(2x - 0.95, 21) * 1.012 + 1. + static float modifiedSoftStepFunc(float x); + +private: + CustomCurve(const CustomCurve&); // 0x36D680 + CustomCurve operator=(const CustomCurve&); // 0x36D720: returns a resampled copy by value + + void init(); // 0x36DFB0 + + /* +0x00 */ Function m_function; + /* +0x04 */ float* m_table; // m_size + 1 samples + /* +0x08 */ int m_size; + /* +0x0C */ float m_min; + /* +0x10 */ float m_max; + /* +0x14 */ float m_step; +}; + +inline float CustomCurve::modifiedSoftStepFunc(float x) +{ + return std::pow(x + x - 0.95f, 21.0f) * 1.012f + 1.0f; +} + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_CUSTOMCURVE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/AIRenderUtil.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/AIRenderUtil.cpp index 452573279..9ef447331 100644 --- a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/AIRenderUtil.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/AIRenderUtil.cpp @@ -1,15 +1,36 @@ // [INFERRED] Source placement. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining AIRenderUtil operations. + +// static init: ELF 0x3BA330 (__tcf_0 0x3BA390, _GLOBAL__I 0x3BA3C0): 's Init object only. +#include +#include // drawArrow's length +#include // setCoordinate, renderStrategies #include "AIRenderUtil.h" -#include "../../AIStrategicEntity/AILandingZoneManager.h" +#include "../../../../AIInterface/BFKnowledge/BFTerrain.h" // IAITerrain::getTerrainAltitude +#include "../../AIStrategic/SAI.h" +#include "../../AIStrategic/Strategy.h" +#include "../../AIStrategicEntity/CoverPosition/CoverPosition.h" +#include "../../AIStrategicEntity/CoverPosition/CoverPositionManager.h" +#include "../../Main/AIMain.h" // IAIMain::m_instance->getSAI +#include "../../Main/AIPathfinding.h" +#include "../../Main/AIPathfindingSearchTypes.h" // QTPath, ClusterNodePath +#include "../AIVectorMath.h" +#include "../../AIStrategicEntity/GuardPosition.h" +#include "../../AIStrategicEntity/PatrolPath.h" +#include "../checkPointer.h" +#include "../../AIStrategicEntity/AILandingZone.h" +#include "../../Main/AILandingZoneManager.h" #include "../../AIStrategicEntity/AIStrategicObjectManager.h" +#include "../../AIStrategicEntity/AIStrategicArea.h" #include "../../DrawPrimitives/DPManager.h" +#include "../../DrawPrimitives/DPStaticCircle.h" +#include "../../DrawPrimitives/DPStaticLine.h" #include "../../Main/AIConsole.h" #include "../../Main/AIDllFrontier.h" #include "../../Main/AISettingsInterfaces.h" #include "../../Main/BotManager.h" +#include "../../AIBot/BotMain.h" // Bot::getBotId #include "../../Main/CommonSingletonServer.h" namespace dice { @@ -48,6 +69,13 @@ AIRenderUtil::BotPrimitives::BotPrimitives(DrawPrimitive* line0, DrawPrimitive* // declared and empty on purpose - see the header. Removing it would change which temporaries get // a destructor call in the emitted code. +// ELF 0x3B44B0 / 0x3B44F0. Copies the seven borrowed primitive handles. +AIRenderUtil::BotPrimitives::BotPrimitives(const BotPrimitives& other) + : m_line0(other.m_line0), m_line1(other.m_line1), m_circle0(other.m_circle0), + m_circle1(other.m_circle1), m_line2(other.m_line2), m_line3(other.m_line3), m_text3d(other.m_text3d) +{ +} + AIRenderUtil::BotPrimitives::~BotPrimitives() { } @@ -65,15 +93,32 @@ void AIRenderUtil::BotPrimitives::deletePrimitives() manager->delete3dText(m_text3d); } +// ELF 0x3B3790 / 0x3B3860. AIRenderUtil::StrategicAreaPrimitives::StrategicAreaPrimitives() : m_line0(0) , m_line1(0) , m_circle0(0) , m_circle1(0) , m_text3d(0) +{ + m_circles.resize(2, static_cast(0)); +} + +// ELF 0x3B3930 / 0x3B3B00. Copies both vectors before resizing the circle vector. +AIRenderUtil::StrategicAreaPrimitives::StrategicAreaPrimitives(const StrategicAreaPrimitives& other) + : m_line0(other.m_line0), m_line1(other.m_line1), m_lines(other.m_lines), + m_circle0(other.m_circle0), m_circle1(other.m_circle1), m_text3d(other.m_text3d), + m_circles(other.m_circles) +{ + m_circles.resize(2, static_cast(0)); +} + +// ELF 0x3B4050 / 0x3B40C0. Only the vectors' storage is released; handles are borrowed here. +AIRenderUtil::StrategicAreaPrimitives::~StrategicAreaPrimitives() { } +// ELF 0x3B3CD0 / 0x3B3E90. AIRenderUtil::StrategicAreaPrimitives::StrategicAreaPrimitives( DrawPrimitive* line0, DrawPrimitive* line1, const std::vector& lines, DrawPrimitive* circle0, DrawPrimitive* circle1, DrawPrimitive* text3d, @@ -86,6 +131,7 @@ AIRenderUtil::StrategicAreaPrimitives::StrategicAreaPrimitives( , m_text3d(text3d) , m_circles(circles) { + m_circles.resize(2, static_cast(0)); } void AIRenderUtil::StrategicAreaPrimitives::deletePrimitives() @@ -131,6 +177,13 @@ AIRenderUtil::LandingZonePrimitives::LandingZonePrimitives(DrawPrimitive* line0, { } +// ELF 0x3B4350 / 0x3B4380. +AIRenderUtil::LandingZonePrimitives::LandingZonePrimitives(const LandingZonePrimitives& other) + : m_line0(other.m_line0), m_line1(other.m_line1), m_line2(other.m_line2), + m_line3(other.m_line3), m_text3d(other.m_text3d) +{ +} + void AIRenderUtil::LandingZonePrimitives::deletePrimitives() { IDPManager* const manager = static_cast(CommonSingletonServer::m_iDPManager); @@ -155,6 +208,12 @@ AIRenderUtil::PatrolPathPrimitives::PatrolPathPrimitives( { } +// ELF 0x3B46C0 / 0x3B4760. +AIRenderUtil::PatrolPathPrimitives::PatrolPathPrimitives(const PatrolPathPrimitives& other) + : m_segments(other.m_segments), m_text3d(other.m_text3d) +{ +} + void AIRenderUtil::PatrolPathPrimitives::deletePrimitives() { IDPManager* const manager = static_cast(CommonSingletonServer::m_iDPManager); @@ -184,6 +243,12 @@ AIRenderUtil::GuardPositionPrimitives::GuardPositionPrimitives( { } +// ELF 0x3B4A70 / 0x3B4A90. +AIRenderUtil::GuardPositionPrimitives::GuardPositionPrimitives(const GuardPositionPrimitives& other) + : m_marker(other.m_marker), m_text3d(other.m_text3d) +{ +} + void AIRenderUtil::GuardPositionPrimitives::deletePrimitives() { IDPManager* const manager = static_cast(CommonSingletonServer::m_iDPManager); @@ -210,6 +275,13 @@ AIRenderUtil::CoverPositionPrimitives::CoverPositionPrimitives( { } +// ELF 0x3B4C10 / 0x3B4E10. +AIRenderUtil::CoverPositionPrimitives::CoverPositionPrimitives(const CoverPositionPrimitives& other) + : m_line0(other.m_line0), m_line1(other.m_line1), m_linesA(other.m_linesA), + m_linesB(other.m_linesB), m_linesC(other.m_linesC) +{ +} + void AIRenderUtil::CoverPositionPrimitives::deletePrimitives() { IDPManager* const manager = static_cast(CommonSingletonServer::m_iDPManager); @@ -389,26 +461,33 @@ void AIRenderUtil::unrenderAll() AIConsole::m_instance->removeCameraText(); } -// [FRONTIER] Bot primitive cleanup requires the remaining bot rendering contract. -// [RETIRE-WHEN: botmain-bases] Complete and validate the corresponding AIRenderUtil operation. -void AIRenderUtil::unrenderBot(Bot*) +// ELF 0x3B7410: the bot's id (+0xE8 getBotId) indexes the primitive records unchecked. +void AIRenderUtil::unrenderBot(Bot* bot) { - BF2_AI_FRONTIER("dice::hfe::ai::AIRenderUtil::unrenderBot (Bot::getBotId, botmain-bases)"); + m_botPrimitives[bot->getBotId()].deletePrimitives(); } -// [FRONTIER] Releases every bot's debug primitives once the required bot interfaces are available. -// [RETIRE-WHEN: botmain-bases] Remove when the corresponding implementation is complete and validated. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. +// ELF 0x3B7460: with a bot manager, every index below getBotCount (+0x08) goes through +// getBotFromId (+0x18) to unrenderBot. The count is read once. void AIRenderUtil::unrenderAllBots() { - BF2_AI_FRONTIER("dice::hfe::ai::AIRenderUtil::unrenderAllBots (IBotManager, botmanager-bases)"); + IBotManager* const bots = IBotManager::instance; + if (!bots) + return; + const int count = bots->getBotCount(); + for (int i = 0; i < count; ++i) + unrenderBot(bots->getBotFromId(static_cast(i))); } -// [FRONTIER] Area primitive cleanup requires its validated primitive index. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding AIRenderUtil operation. -void AIRenderUtil::unrenderStrategicArea(AIStrategicArea*) +// ELF 0x3B7FD0: the area's index (+0xF0, AIStrategicObject::m_index) selects its primitive +// record, then each landing zone's id (AILandingZone::getId) selects a landing-zone record. The +// zone vector is fetched again for every end() comparison. +void AIRenderUtil::unrenderStrategicArea(AIStrategicArea* area) { - BF2_AI_FRONTIER("dice::hfe::ai::AIRenderUtil::unrenderStrategicArea (AIStrategicArea layout)"); + m_strategicAreaPrimitives[area->getIndex()].deletePrimitives(); + for (std::vector::iterator zone = area->getLandingZones().begin(); + zone != area->getLandingZones().end(); ++zone) + m_landingZonePrimitives[(*zone)->getId()].deletePrimitives(); } // Copies the strategic-area map before iterating it to remove debug rendering. @@ -537,47 +616,450 @@ void AIRenderUtil::updateNumberOfLandingZones() m_landingZonePrimitives.resize(count); } -// [FRONTIER] Remaining console-driven rendering operations stop by name. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding AIRenderUtil operation. - -void AIRenderUtil::setCoordinate(const Vec3&) +// ELF 0x3B65C0. Replaces the text lines with one "x/y/z" line for `position` and shows them as +// the white 2D text at the screen origin, creating m_text2dA on first use and updating it after. +// [INFERRED] The three '/'-separated inserts may be an inlined Vec3 stream operator. +void AIRenderUtil::setCoordinate(const Vec3& position) { - BF2_AI_FRONTIER("dice::hfe::ai::AIRenderUtil::setCoordinate"); + m_text.resize(0); + std::stringstream stream; + stream << position.x << '/' << position.y << '/' << position.z; + m_text.push_back(stream.str()); + + if (m_text2dA) + { + const Vec2 origin = {0.0f, 0.0f}; + static_cast(CommonSingletonServer::m_iDPManager) + ->set2dTextAttributes(m_text2dA, 1.0e9f, 0xFFFFFFFFu, origin, m_text, 0, + static_cast(0), static_cast(0)); + } + else + { + const Vec2 origin = {0.0f, 0.0f}; + m_text2dA = static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStatic2dText(1.0e9f, 0xFFFFFFFFu, origin, m_text, 0, + static_cast(0), static_cast(0)); + } } +// ELF 0x3B6C10. Replaces the text lines with the active strategy of SAI sides 1 and 2, each as +// "name a b c" with the three values getActiveStrategy reports, and shows them as white 2D text +// twelve units down (m_text2dB). The strategy pointers are used unchecked (shipped). void AIRenderUtil::renderStrategies() { - BF2_AI_FRONTIER("dice::hfe::ai::AIRenderUtil::renderStrategies"); + m_text.resize(0); + std::stringstream stream; + SAI* const side1 = IAIMain::m_instance->getSAI(1); + SAI* const side2 = IAIMain::m_instance->getSAI(2); + float a = 0.0f; + float b = 0.0f; + float c = 0.0f; + + stream << side1->getActiveStrategy(a, b, c)->getName() << " " << a << " " << b << " " << c; + m_text.push_back(stream.str()); + stream.str(""); + + stream << side2->getActiveStrategy(a, b, c)->getName() << " " << a << " " << b << " " << c; + m_text.push_back(stream.str()); + + if (m_text2dB) + { + const Vec2 origin = {0.0f, 12.0f}; + static_cast(CommonSingletonServer::m_iDPManager) + ->set2dTextAttributes(m_text2dB, 1.0e9f, 0xFFFFFFFFu, origin, m_text, 0, + static_cast(0), static_cast(0)); + } + else + { + const Vec2 origin = {0.0f, 12.0f}; + m_text2dB = static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStatic2dText(1.0e9f, 0xFFFFFFFFu, origin, m_text, 0, + static_cast(0), static_cast(0)); + } } -void AIRenderUtil::drawArrow(float, unsigned int, const Vec3&, const Vec3&) +// ELF 0x3B7670. One static polyline in m_sensingLine: from `position` to the tip +// (`position` + `direction`), then over three barbs back to the tip. The barbs sit at 70% of the +// length, offset by a tenth of the length along the frame's first row, a twentieth along its +// second row, and a tenth against the first row. The line is 3% of the length wide. The frame is +// getDofTransformation's (third row forward), as in drawAxisPoint. The ia-32 build forms +// 1 - 0.3 at run time, so the three fractions were locals in the source. +void AIRenderUtil::drawArrow(float lifeTime, unsigned int colour, const Vec3& position, + const Vec3& direction) { - BF2_AI_FRONTIER("dice::hfe::ai::AIRenderUtil::drawArrow"); + const float length = std::sqrt(direction.x * direction.x + direction.y * direction.y + + direction.z * direction.z); + const Mat4 frame = getDofTransformation(direction); + Vec3 point = {0.0f, 0.0f, 0.0f}; + const float barbWidth = 0.1f; + const float barbLength = 0.3f; + const float barbHeight = 0.05f; + + m_sensingLine.resize(0, point); + m_sensingLine.push_back(position); + + // the tip + point.x = position.x + length * frame.m[8]; + point.y = position.y + length * frame.m[9]; + point.z = position.z + length * frame.m[10]; + m_sensingLine.push_back(point); + + // first barb: back along forward, out along the first row + point.x = position.x + length * frame.m[8] * (1.0f - barbLength) + length * frame.m[0] * barbWidth; + point.y = position.y + length * frame.m[9] * (1.0f - barbLength) + length * frame.m[1] * barbWidth; + point.z = position.z + length * frame.m[10] * (1.0f - barbLength) + length * frame.m[2] * barbWidth; + m_sensingLine.push_back(point); + + // second barb: out along the second row + point.x = position.x + length * frame.m[8] * (1.0f - barbLength) + length * frame.m[4] * barbHeight; + point.y = position.y + length * frame.m[9] * (1.0f - barbLength) + length * frame.m[5] * barbHeight; + point.z = position.z + length * frame.m[10] * (1.0f - barbLength) + length * frame.m[6] * barbHeight; + m_sensingLine.push_back(point); + + // third barb: against the first row + point.x = position.x + length * frame.m[8] * (1.0f - barbLength) - length * frame.m[0] * barbWidth; + point.y = position.y + length * frame.m[9] * (1.0f - barbLength) - length * frame.m[1] * barbWidth; + point.z = position.z + length * frame.m[10] * (1.0f - barbLength) - length * frame.m[2] * barbWidth; + m_sensingLine.push_back(point); + + // back to the tip + point.x = position.x + length * frame.m[8]; + point.y = position.y + length * frame.m[9]; + point.z = position.z + length * frame.m[10]; + m_sensingLine.push_back(point); + + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticLine(lifeTime, colour, m_sensingLine, length * 0.03f); } -void AIRenderUtil::drawAxisPoint(float, unsigned int, const Vec3&, const Vec3&, float) +// ELF 0x3B7DD0. Three static lines through `position`, one per axis of the frame +// getDofTransformation builds from `direction` (third row, then second, then first), each from +// position - axis to position + axis and a quarter of `size` wide. +void AIRenderUtil::drawAxisPoint(float lifeTime, unsigned int colour, const Vec3& position, + const Vec3& direction, float size) { - BF2_AI_FRONTIER("dice::hfe::ai::AIRenderUtil::drawAxisPoint"); + const Mat4 frame = getDofTransformation(direction); + Vec3 end; + Vec3 start; + size = size * 0.25f; + + end.x = position.x + frame.m[8]; + end.y = position.y + frame.m[9]; + end.z = position.z + frame.m[10]; + start.x = position.x - frame.m[8]; + start.y = position.y - frame.m[9]; + start.z = position.z - frame.m[10]; + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticLine(lifeTime, colour, start, end, size); + + end.x = position.x + frame.m[4]; + end.y = position.y + frame.m[5]; + end.z = position.z + frame.m[6]; + start.x = position.x - frame.m[4]; + start.y = position.y - frame.m[5]; + start.z = position.z - frame.m[6]; + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticLine(lifeTime, colour, start, end, size); + + end.x = position.x + frame.m[0]; + end.y = position.y + frame.m[1]; + end.z = position.z + frame.m[2]; + start.x = position.x - frame.m[0]; + start.y = position.y - frame.m[1]; + start.z = position.z - frame.m[2]; + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticLine(lifeTime, colour, start, end, size); } -void AIRenderUtil::renderPatrolPath(const std::string&, PatrolPath*) +// ELF 0x3B83E0. Once per patrol path: for every waypoint a short vertical post (built in +// m_sensingLine, which serves as the scratch point list) and a unit circle, recorded as a +// (line, circle) segment; then the name five units above the first waypoint. The text handle is +// not stored (shipped, kept). The path is fetched again for every end() comparison. +void AIRenderUtil::renderPatrolPath(const std::string& name, PatrolPath* path) { - BF2_AI_FRONTIER("dice::hfe::ai::AIRenderUtil::renderPatrolPath"); + if (m_patrolPathPrimitives.find(path) != m_patrolPathPrimitives.end()) + return; + PatrolPathPrimitives* const primitives = checkPointer(new PatrolPathPrimitives()); + IDPStaticCreator* const creator = static_cast(CommonSingletonServer::m_iDPStaticCreator); + + for (std::vector::const_iterator waypoint = path->getPath().begin(); + waypoint != path->getPath().end(); ++waypoint) + { + const Vec3 point = *waypoint; + Vec3 vertex = {0.0f, 0.0f, 0.0f}; + m_sensingLine.resize(0, vertex); + vertex.x = point.x; + vertex.y = point.y - 2.5f; + vertex.z = point.z + 0.1f; + m_sensingLine.push_back(vertex); + vertex.x = point.x; + vertex.y = 2.5f + point.y; + vertex.z = point.z - 0.1f; + m_sensingLine.push_back(vertex); + DrawPrimitive* const line = creator->createStaticLine(1.0e9f, 0xFF4422u, m_sensingLine, 0.2f); + + vertex.x = 0.0f; + vertex.y = 1.0f; + vertex.z = 0.0f; + DrawPrimitive* const circle + = creator->createStaticCircle(1.0e9f, 0xFF4422u, *waypoint, 1.0f, vertex, false, 255); + primitives->m_segments.push_back(std::make_pair(line, circle)); + } + + const Vec3& first = path->getPath()[0]; + Vec3 textPosition; + textPosition.x = first.x; + textPosition.y = first.y + 5.0f; + textPosition.z = first.z; + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStatic3dText(1.0e9f, 0xFFFFFFFFu, textPosition, name, 0, + static_cast(0), static_cast(0)); + m_patrolPathPrimitives.insert(std::make_pair(path, primitives)); } -void AIRenderUtil::renderGuardPosition(const std::string&, GuardPosition*) +// ELF 0x3B8BC0. Once per guard position: a circle of the minimum distance one unit above it, the +// name four units higher, and a line below the name. The text handle is not stored (the record's +// m_text3d stays at its default), and the line's upper end subtracts the circle height rather than +// an offset, so it ends near world height 4 (both shipped, kept). +void AIRenderUtil::renderGuardPosition(const std::string& name, GuardPosition* guardPosition) { - BF2_AI_FRONTIER("dice::hfe::ai::AIRenderUtil::renderGuardPosition"); + if (m_guardPositionPrimitives.find(guardPosition) != m_guardPositionPrimitives.end()) + return; + GuardPositionPrimitives* const primitives = checkPointer(new GuardPositionPrimitives()); + IDPStaticCreator* const creator = static_cast(CommonSingletonServer::m_iDPStaticCreator); + + Vec3 position = guardPosition->getPosition(); + position.y = position.y + 1.0f; + const float circleHeight = position.y; + const Vec3 up = {0.0f, 1.0f, 0.0f}; + primitives->m_marker.first = creator->createStaticCircle( + 1.0e9f, 0x117799u, position, guardPosition->getMinDistance(), up, false, 255); + + position.y = 4.0f + position.y; + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStatic3dText(1.0e9f, 0xFFFFFFFFu, position, name, 0, + static_cast(0), static_cast(0)); + m_guardPositionPrimitives.insert(std::make_pair(guardPosition, primitives)); + + Vec3 start; + start.x = position.x - 0.0f; + start.y = position.y - circleHeight; + start.z = position.z - 0.0f; + Vec3 end; + end.x = position.x - 0.0f; + end.y = position.y - 5.0f; + end.z = position.z - 0.0f; + primitives->m_marker.second = creator->createStaticLine(1.0e9f, 0x117799u, start, end, 0.1f); } -void AIRenderUtil::renderCoverPosition(int) +// ELF 0x3B9130. Once per cover position (the record's first line is the marker): its box as a +// closed outline half a unit above the terrain, a post at its centre, and one line from the +// centre to each linked position, five units higher per link kind: move neighbours (linesA, to +// the other box's first corner plus half a unit, grey), attackable links (linesB, to the first +// corner, coloured by the link type) and defendable links (linesC, likewise). The record vector +// grows to fit the index; a negative index is not caught (shipped). The first loop fetches the +// creator singleton again; the other calls use the copy taken on entry. +void AIRenderUtil::renderCoverPosition(int index) { - BF2_AI_FRONTIER("dice::hfe::ai::AIRenderUtil::renderCoverPosition"); + CoverPositionManager* const manager = CoverPositionManager::m_instance; + CoverPosition* const cover = manager->m_coverPositions[index]; + if (!cover) + return; + + if (index >= static_cast(m_coverPositionPrimitives.size())) + m_coverPositionPrimitives.resize(index + 1); + CoverPositionPrimitives& primitives = m_coverPositionPrimitives[index]; + if (primitives.m_line0) + return; + + IDPStaticCreator* const creator = static_cast(CommonSingletonServer::m_iDPStaticCreator); + const IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + + const Vec3 corner0 = {cover->m_min.x, + terrain->getTerrainAltitude(cover->m_min.x, cover->m_min.y) + 0.5f, + cover->m_min.y}; + const Vec3 corner1 = {cover->m_max.x, + terrain->getTerrainAltitude(cover->m_max.x, cover->m_min.y) + 0.5f, + cover->m_min.y}; + const Vec3 corner2 = {cover->m_max.x, + terrain->getTerrainAltitude(cover->m_max.x, cover->m_max.y) + 0.5f, + cover->m_max.y}; + const Vec3 corner3 = {cover->m_min.x, + terrain->getTerrainAltitude(cover->m_min.x, cover->m_max.y) + 0.5f, + cover->m_max.y}; + + const Vec3 zero = {0.0f, 0.0f, 0.0f}; + m_sensingLine.resize(0, zero); + m_sensingLine.push_back(corner0); + m_sensingLine.push_back(corner1); + m_sensingLine.push_back(corner2); + m_sensingLine.push_back(corner3); + m_sensingLine.push_back(corner0); + primitives.m_line0 = creator->createStaticLine(1.0e9f, 0x77777777u, m_sensingLine, 0.2f); + + Vec3 centre = {0.0f, 0.0f, 0.0f}; + centre.x = cover->m_min.x + (cover->m_max.x - cover->m_min.x) * 0.5f; + centre.z = cover->m_min.y + (cover->m_max.y - cover->m_min.y) * 0.5f; + centre.y = terrain->getTerrainAltitude(centre.x, centre.z); + + Vec3 top; + top.x = centre.x + 0.0f; + top.y = centre.y + 15.0f; + top.z = centre.z + 0.0f; + Vec3 foot; + foot.x = centre.x + 0.1f; + foot.y = centre.y + 0.0f; + foot.z = centre.z + 0.1f; + primitives.m_line1 = creator->createStaticLine(1.0e9f, 0x77777777u, foot, top, 0.2f); + + centre.y = centre.y + 5.0f; + Vec3 end = {0.0f, 0.0f, 0.0f}; + for (std::set::const_iterator it = cover->m_moveNeighbours.begin(); + it != cover->m_moveNeighbours.end(); ++it) + { + const CoverPosition* const other = manager->m_coverPositions[*it]; + if (!other) + continue; + end.x = other->m_min.x + 0.5f; + end.z = other->m_min.y + 0.5f; + end.y = terrain->getTerrainAltitude(end.x, end.z) + 5.0f; + primitives.m_linesA.push_back( + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticLine(1.0e9f, 0xAAAAAAAAu, centre, end, 0.1f)); + } + + centre.y = centre.y + 5.0f; + for (std::map::const_iterator it = cover->m_attackable.begin(); + it != cover->m_attackable.end(); ++it) + { + const CoverPosition* const other = manager->m_coverPositions[it->first]; + if (!other) + continue; + unsigned int colour; + switch (it->second.m_type) + { + case ConnectionType::kPartial: colour = 0xBBBB00u; break; + case ConnectionType::kBlocked: colour = 0xBB0000u; break; + case ConnectionType::kVisible: colour = 0x00BB00u; break; + default: colour = 0; break; + } + end.x = other->m_min.x; + end.z = other->m_min.y; + end.y = terrain->getTerrainAltitude(end.x, end.z) + 10.0f; + primitives.m_linesB.push_back(creator->createStaticLine(1.0e9f, colour, centre, end, 0.1f)); + } + + centre.y = centre.y + 5.0f; + for (std::map::const_iterator it = cover->m_defendable.begin(); + it != cover->m_defendable.end(); ++it) + { + const CoverPosition* const other = manager->m_coverPositions[it->first]; + if (!other) + continue; + unsigned int colour; + switch (it->second.m_type) + { + case ConnectionType::kPartial: colour = 0xBBBB00u; break; + case ConnectionType::kBlocked: colour = 0xBB0000u; break; + case ConnectionType::kVisible: colour = 0x00BB00u; break; + default: colour = 0; break; + } + end.x = other->m_min.x; + end.z = other->m_min.y; + end.y = terrain->getTerrainAltitude(end.x, end.z) + 15.0f; + primitives.m_linesC.push_back(creator->createStaticLine(1.0e9f, colour, centre, end, 0.1f)); + } } +// ELF 0x3B9D00 (dice's spelling, "redender"). The pathfinding debug tool's markers: the found +// path as one line (m_pathLine) once both search points are set, and a circle at each set search +// point (m_pathCircleA, m_pathCircleB), each created on first use and updated after. Setting the +// first point again deletes the line, and an unset point deletes its circle. The plain path is +// read through its own step cursor, which this advances; a cursor that does not start at zero +// runs off the end and copies through a null position (shipped). The cluster path skips its +// start step and ignores getPoint's answer. void AIRenderUtil::redenderPathfindingDebug() { - BF2_AI_FRONTIER("dice::hfe::ai::AIRenderUtil::redenderPathfindingDebug"); + AIPathfinding* const pathfinding = static_cast(IAIPathfinding::instance); + + if (m_pathLine) + { + if (pathfinding->getSearchPointToSet() == 1) + { + static_cast(CommonSingletonServer::m_iDPManager)->deleteLine(m_pathLine); + m_pathLine = 0; + } + } + else if (pathfinding->getSearchPointToSet() == 2) + { + const bool cluster = pathfinding->getClusterSearch(); + const unsigned int colour = cluster ? 0xFF00FF44u : 0xFFFF8800u; + IDPStaticCreator* const creator = static_cast(CommonSingletonServer::m_iDPStaticCreator); + std::vector points; + + if (!cluster) + { + QTPath* const path = pathfinding->getDebugPath(); + for (unsigned int i = 0; i < path->m_nodes.size(); ++i) + { + // [INFERRED] an inlined QTPath step accessor (unsigned compare, post-increment of + // the cursor); no out-of-line copy exists to name it. + const Vec3* position = 0; + if (static_cast(path->m_i0) < path->m_nodes.size()) + position = &path->m_nodes[path->m_i0++].third; + points.push_back(*position); + } + } + else + { + const ClusterNodePath* const path = pathfinding->getDebugClusterPath(); + Vec3 point = {0.0f, 0.0f, 0.0f}; + unsigned int polygon; + for (unsigned int i = 1; i < path->m_nodes.size(); ++i) + { + path->getPoint(point, polygon, i); + points.push_back(point); + } + } + + m_pathLine = creator->createStaticLine(1.0e9f, colour, points, 0.3f); + } + + if (pathfinding->getSearchPointToSet() > 0) + { + const Vec3 up = {0.0f, 1.0f, 0.0f}; + if (m_pathCircleA) + static_cast(CommonSingletonServer::m_iDPManager) + ->setCircleAttributes(m_pathCircleA, 1.0e9f, 0xFFFF8800u, + *pathfinding->getSearchPoint(0), 1.0f, up, false, 255); + else + m_pathCircleA = static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticCircle(1.0e9f, 0xFFFF8800u, *pathfinding->getSearchPoint(0), 1.0f, up, + false, 255); + } + else + { + static_cast(CommonSingletonServer::m_iDPManager)->deleteCircle(m_pathCircleA); + m_pathCircleA = 0; + } + + if (pathfinding->getSearchPointToSet() == 2) + { + const Vec3 up = {0.0f, 1.0f, 0.0f}; + if (m_pathCircleB) + static_cast(CommonSingletonServer::m_iDPManager) + ->setCircleAttributes(m_pathCircleB, 1.0e9f, 0xFFFF8800u, + *pathfinding->getSearchPoint(1), 1.0f, up, false, 255); + else + m_pathCircleB = static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticCircle(1.0e9f, 0xFFFF8800u, *pathfinding->getSearchPoint(1), 1.0f, up, + false, 255); + } + else + { + static_cast(CommonSingletonServer::m_iDPManager)->deleteCircle(m_pathCircleB); + m_pathCircleB = 0; + } } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/AIRenderUtil.h b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/AIRenderUtil.h index e6f7ad824..2f9a8bf71 100644 --- a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/AIRenderUtil.h +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/AIRenderUtil.h @@ -1,7 +1,5 @@ // Owns AI debug-drawing handles allocated by the primitive manager. // The dedicated build leaves per-frame render operations empty; console-driven operations remain active. -// [FRONTIER] Remaining render methods stop until implemented. -// [RETIRE-WHEN: aidll-02-skeleton] Implement and validate the remaining rendering operations. // [RETIRE-WHEN: botmain-bases] Remove when the corresponding implementation is complete and validated. // [INFERRED] Source placement. @@ -40,6 +38,7 @@ class AIRenderUtil struct BotPrimitives { BotPrimitives(); + BotPrimitives(const BotPrimitives&); BotPrimitives(DrawPrimitive* line0, DrawPrimitive* line1, DrawPrimitive* circle0, DrawPrimitive* circle1, DrawPrimitive* line2, DrawPrimitive* line3, DrawPrimitive* text3d); @@ -61,6 +60,9 @@ class AIRenderUtil struct StrategicAreaPrimitives { StrategicAreaPrimitives(); + // Every constructor resizes the circle vector to exactly two entries after copying it. + StrategicAreaPrimitives(const StrategicAreaPrimitives&); + ~StrategicAreaPrimitives(); StrategicAreaPrimitives(DrawPrimitive* line0, DrawPrimitive* line1, const std::vector& lines, DrawPrimitive* circle0, DrawPrimitive* circle1, DrawPrimitive* text3d, @@ -80,6 +82,7 @@ class AIRenderUtil struct LandingZonePrimitives { LandingZonePrimitives(); + LandingZonePrimitives(const LandingZonePrimitives&); LandingZonePrimitives(DrawPrimitive* line0, DrawPrimitive* line1, DrawPrimitive* line2, DrawPrimitive* line3, DrawPrimitive* text3d); @@ -95,6 +98,7 @@ class AIRenderUtil struct PatrolPathPrimitives { PatrolPathPrimitives(); + PatrolPathPrimitives(const PatrolPathPrimitives&); // the text comes first here and last in memory - see the header block. PatrolPathPrimitives(DrawPrimitive* text3d, const std::vector >& segments); @@ -108,6 +112,7 @@ class AIRenderUtil struct GuardPositionPrimitives { GuardPositionPrimitives(); + GuardPositionPrimitives(const GuardPositionPrimitives&); // Same inversion as PatrolPathPrimitives. GuardPositionPrimitives(DrawPrimitive* text3d, const std::pair& marker); @@ -121,6 +126,7 @@ class AIRenderUtil struct CoverPositionPrimitives { CoverPositionPrimitives(); + CoverPositionPrimitives(const CoverPositionPrimitives&); CoverPositionPrimitives(DrawPrimitive* line0, DrawPrimitive* line1, const std::vector& linesA, const std::vector& linesB, @@ -142,13 +148,13 @@ class AIRenderUtil void exit(); // - empty in retail // the render half. Every one of these with a five-byte body is empty in retail. - void setCoordinate(const Vec3& position); // [FRONTIER] - void renderStrategies(); // [FRONTIER] + void setCoordinate(const Vec3& position); + void renderStrategies(); void renderBot(BotMain*, const std::pair&, const std::pair&, float, const std::pair&); // - empty void addSensingLine(const Vec3& from, const Vec3& to, int side, bool visible); - void drawArrow(float, unsigned int, const Vec3&, const Vec3&); // [FRONTIER] - void drawAxisPoint(float, unsigned int, const Vec3&, const Vec3&, float); // [FRONTIER] + void drawArrow(float lifeTime, unsigned int colour, const Vec3& position, const Vec3& direction); + void drawAxisPoint(float, unsigned int, const Vec3&, const Vec3&, float); void renderPath(int, bool, const std::vector&, unsigned int); // - empty void renderWaypointList(BotMain*); // - empty void renderPathFinding(BotMain*); // - empty @@ -158,21 +164,21 @@ class AIRenderUtil void renderBotStats(BotMain*, const std::pair&, const std::pair&, float, const std::pair&); // - empty void renderBehaviourStats(BotMain*, std::vector&); // - empty - void renderPatrolPath(const std::string&, PatrolPath*); // [FRONTIER] - void renderGuardPosition(const std::string&, GuardPosition*); // [FRONTIER] - void renderCoverPosition(int); // [FRONTIER] - void redenderPathfindingDebug(); // [FRONTIER] + void renderPatrolPath(const std::string&, PatrolPath*); + void renderGuardPosition(const std::string&, GuardPosition*); + void renderCoverPosition(int); + void redenderPathfindingDebug(); // dice's spelling void renderObstacleInfo(Bot*); // - empty void initAIMeshRendering(); // - empty void cleanUpAIMeshRendering(); // - empty void renderAIMeshes(); // - empty - // the unrender half. All written except the two blocked on a missing type. + // the unrender half. void unrenderAll(); - void unrenderBot(Bot*); // [FRONTIER] + void unrenderBot(Bot*); void unrenderAllBots(); - void unrenderStrategicArea(AIStrategicArea*); // [FRONTIER] + void unrenderStrategicArea(AIStrategicArea*); void unrenderAllStrategicAreas(); void unrenderPatrolPath(PatrolPath*); void unrenderAllPatrolPaths(); @@ -192,8 +198,8 @@ class AIRenderUtil private: /* +0x00 */ std::vector m_sensingLine; // rebuilt from scratch by every addSensingLine - /* +0x0C */ std::vector m_text; // [UNRESOLVED] role - only the destructor - // which releases each string, proves the type + /* +0x0C */ std::vector m_text; // the 2D text lines setCoordinate and + // renderStrategies rebuild /* +0x18 */ std::vector m_botPrimitives; // indexed by Bot::getBotId /* +0x24 */ std::vector m_strategicAreaPrimitives; /* +0x30 */ std::vector m_landingZonePrimitives; @@ -202,8 +208,8 @@ class AIRenderUtil /* +0x54 */ std::vector m_coverPositionPrimitives; // The five loose handles, named by the delete slot each goes to. - /* +0x60 */ DrawPrimitive* m_text2dA; // delete2dText, from unrenderAll - /* +0x64 */ DrawPrimitive* m_text2dB; // delete2dText, from unrenderAll + /* +0x60 */ DrawPrimitive* m_text2dA; // setCoordinate's text; delete2dText, from unrenderAll + /* +0x64 */ DrawPrimitive* m_text2dB; // renderStrategies' text; delete2dText, from unrenderAll /* +0x68 */ DrawPrimitive* m_pathCircleA; // deleteCircle, from unrendenderPathfindingDebug /* +0x6C */ DrawPrimitive* m_pathCircleB; // deleteCircle, from unrendenderPathfindingDebug /* +0x70 */ DrawPrimitive* m_pathLine; // deleteLine, from unrendenderPathfindingDebug diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObject3dText.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObject3dText.cpp new file mode 100644 index 000000000..8ce626fab --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObject3dText.cpp @@ -0,0 +1,96 @@ +// World-space debug text meant to follow an AI object. Evidence: libaidll.so (ia-32) +// 0x36F5C0..0x36FB1F. Placement attested by the __FILE__ string +// "AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObject3dText.cpp". + +#include "DPDynamicPrimitives.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x36FB20, __tcf_0 0x36FB80, _GLOBAL__I 0x36FBB0; the _GLOBAL__I symbol names this TU's +// DPAIObject3dText constructor, although the ledger files the three rows under CustomCurve.cpp). +#include + +#include "../../../../../Core/Debug.h" +#include "../../../../AIInterface/BFKnowledge/DebugRenderer.h" +#include "../../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../AIBot/BotMain.h" +#include "../../AIKnowledge/Information.h" +#include "../../Main/InformationManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x36F5C0 (C2; C1 0x36F640). m_bot is left unwritten. +DPAIObject3dText::DPAIObject3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::string& text, unsigned int information, + DPDynamicTypes type, int size, AITextAlignmentX alignX, + AITextAlignmentY alignY) + : DPStatic3dText(lifeTime, colour, position, text, size, alignX, alignY) + , m_information(information) + , m_type(type) +{ +} + +// ELF 0x36F6C0 (C2; C1 0x36F740). m_bot is left unwritten. +DPAIObject3dText::DPAIObject3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::vector& lines, unsigned int information, + DPDynamicTypes type, int size, AITextAlignmentX alignX, + AITextAlignmentY alignY) + : DPStatic3dText(lifeTime, colour, position, lines, size, alignX, alignY) + , m_information(information) + , m_type(type) +{ +} + +// ELF 0x36F7C0 (D2; D1 0x36F800, D0 0x36F840). +DPAIObject3dText::~DPAIObject3dText() +{ +} + +// ELF 0x36F880. The position comes from the information's IAIObject, the type-3 transformation +// from the information itself (as DPDynamic3dText, translation added twice). +// shipped defect: the information is resolved through the unwritten m_bot. +bool DPAIObject3dText::draw(IDebugRenderer* renderer) +{ + Information* const information = informationManager->getInformation(m_bot->getCurrentEquipment()); + if (!information) + return false; + const Vec3& offset = information->getAIObject()->getPosition(); + Vec3 position; + position.x = m_position.x + offset.x; + position.y = m_position.y + offset.y; + position.z = m_position.z + offset.z; + switch (m_type) + { + case 0: + case 1: + case 2: + break; + case 3: + { + const Mat4& transformation = information->getTransformation(); + Vec3 transformed = {0.0f, 0.0f, 0.0f}; + transformed.x = position.x * transformation.m[0] + position.y * transformation.m[4] + + position.z * transformation.m[8] + transformation.m[12]; + transformed.y = position.x * transformation.m[1] + position.y * transformation.m[5] + + position.z * transformation.m[9] + transformation.m[13]; + transformed.z = position.x * transformation.m[2] + position.y * transformation.m[6] + + position.z * transformation.m[10] + transformation.m[14]; + position = transformed; + position.x += transformation.m[12]; + position.y += transformation.m[13]; + position.z += transformation.m[14]; + break; + } + default: + Debug(DebugTypeError, "AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObject3dText.cpp", 97, "") + << "Invalid type."; + break; + } + renderer->draw3dText(position, m_lines, m_size, m_colour, m_alignX, m_alignY); + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectCircle.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectCircle.cpp new file mode 100644 index 000000000..b7d383575 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectCircle.cpp @@ -0,0 +1,96 @@ +// Debug circle that follows an AI object. Evidence: libaidll.so (ia-32) +// 0x36FBD0..0x37012F. Placement attested by the __FILE__ string +// "AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectCircle.cpp". + +#include "DPDynamicPrimitives.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x370080, __tcf_0 0x3700E0, _GLOBAL__I 0x370110). +#include + +#include "../../../../../Core/Debug.h" +#include "../../../../AIInterface/BFKnowledge/DebugRenderer.h" +#include "../../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../AIKnowledge/Information.h" +#include "../../Main/InformationManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x36FBD0 (C2; C1 0x36FC40). +DPAIObjectCircle::DPAIObjectCircle(float lifeTime, unsigned int colour, const Vec3& position, + float radius, unsigned int information, DPDynamicTypes /*type*/, + const Vec3& normal, bool filled, int segments) + : DPStaticCircle(lifeTime, colour, position, radius, normal, filled, segments) + , m_information(information) +{ +} + +// ELF 0x36FCB0 (D2; D1 0x36FCF0, D0 0x36FD30). +DPAIObjectCircle::~DPAIObjectCircle() +{ +} + +// ELF 0x36FD70. DPDynamicCircle::draw over the information's IAIObject: the circle sits at +// m_position offset by the object's position; types 0 and 1 +// keep m_normal, 2 takes the transformation's third row and 3 its second row. An unknown type +// reports and draws with the zero centre and normal. +bool DPAIObjectCircle::draw(IDebugRenderer* renderer) +{ + Information* const information = informationManager->getInformation(m_information); + if (!information) + return false; + IAIObject* const object = information->getAIObject(); + + Vec3 normal = {0.0f, 0.0f, 0.0f}; + Vec3 centre = {0.0f, 0.0f, 0.0f}; + switch (m_type) + { + case 0: + case 1: + { + const Vec3& position = object->getPosition(); + centre.x = m_position.x + position.x; + centre.y = m_position.y + position.y; + centre.z = m_position.z + position.z; + normal = m_normal; + break; + } + case 2: + { + const Vec3& position = object->getPosition(); + centre.x = m_position.x + position.x; + centre.y = m_position.y + position.y; + centre.z = m_position.z + position.z; + const Mat4& transformation = object->getTransformation(); + normal.x = transformation.m[8]; + normal.y = transformation.m[9]; + normal.z = transformation.m[10]; + break; + } + case 3: + { + const Vec3& position = object->getPosition(); + centre.x = m_position.x + position.x; + centre.y = m_position.y + position.y; + centre.z = m_position.z + position.z; + const Mat4& transformation = object->getTransformation(); + normal.x = transformation.m[4]; + normal.y = transformation.m[5]; + normal.z = transformation.m[6]; + break; + } + case 4: // [INFERRED] the jump table has a fifth entry that shares the default target + default: + Debug(DebugTypeError, "AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectCircle.cpp", 73, "") + << "Invalid type."; + break; + } + renderer->drawCircle(normal, centre, m_radius, m_colour, m_filled, m_segments); + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectLine.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectLine.cpp new file mode 100644 index 000000000..580d96499 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectLine.cpp @@ -0,0 +1,140 @@ +// Debug polyline that follows an AI object. Evidence: libaidll.so (ia-32) +// 0x370130..0x370C1F. Placement attested by the __FILE__ string +// "AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectLine.cpp". + +#include "DPDynamicPrimitives.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x370B70, __tcf_0 0x370BD0, _GLOBAL__I 0x370C00). +#include + +#include + +#include "../../../../../Core/Debug.h" +#include "../../../../AIInterface/BFKnowledge/DebugRenderer.h" +#include "../../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../AIKnowledge/Information.h" +#include "../../Main/InformationManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x370130 (C2; C1 0x3701B0). +DPAIObjectLine::DPAIObjectLine(float lifeTime, unsigned int colour, const Vec3& start, const Vec3& end, + float width, unsigned int information, DPDynamicTypes type) + : DPStaticLine(lifeTime, colour, start, end, width) + , m_information(information) + , m_type(type) +{ +} + +// ELF 0x370230 (C2; C1 0x3702B0). +DPAIObjectLine::DPAIObjectLine(float lifeTime, unsigned int colour, const std::vector& points, + float width, unsigned int information, DPDynamicTypes type) + : DPStaticLine(lifeTime, colour, points, width) + , m_information(information) + , m_type(type) +{ +} + +// ELF 0x370330 (D2; D1 0x3703B0, D0 0x370430). +DPAIObjectLine::~DPAIObjectLine() +{ +} + +// ELF 0x3704B0. DPDynamicLine::draw over the information's IAIObject (its position and +// transformation slots) instead of the information itself. Type 2 derives a yaw from the transformation's third row (x and z normalised by +// their absolute sum, acos of the clamped x, +-pi when z is negative) and rotates every point by +// it before adding the translation. Type 3 transforms every point and then adds the translation a +// second time (shipped defect, kept). An unknown type reports and draws the empty point list. +bool DPAIObjectLine::draw(IDebugRenderer* renderer) +{ + m_drawPoints.resize(0); + Information* const information = informationManager->getInformation(m_information); + if (!information) + return false; + IAIObject* const object = information->getAIObject(); + + switch (m_type) + { + case 0: + { + const Vec3& position = object->getPosition(); + for (std::vector::const_iterator point = m_points.begin(); point != m_points.end(); ++point) + { + Vec3 placed; + placed.x = point->x + position.x; + placed.y = point->y + position.y; + placed.z = point->z + position.z; + m_drawPoints.push_back(placed); + } + break; + } + case 1: + m_drawPoints.push_back(object->getPosition()); + m_drawPoints.insert(m_drawPoints.end(), m_points.begin(), m_points.end()); + break; + case 2: + { + const Mat4& transformation = object->getTransformation(); + Vec3 rotated = {0.0f, 0.0f, 0.0f}; + const float scale = 1.0f / (std::fabs(transformation.m[8]) + std::fabs(transformation.m[10])); + float x = transformation.m[8] * scale; + const float z = transformation.m[10] * scale; + if (x < -1.0f) + x = -1.0f; + else if (x > 1.0f) + x = 1.0f; + float angle = std::acos(x); + if (z < 0.0f) + { + if (angle < 0.0f) + angle -= 3.14159265f; + else + angle += 3.14159265f; + } + for (std::vector::const_iterator point = m_points.begin(); point != m_points.end(); ++point) + { + rotateXZ(*point, rotated, angle); + Vec3 placed; + placed.x = rotated.x + transformation.m[12]; + placed.y = rotated.y + transformation.m[13]; + placed.z = rotated.z + transformation.m[14]; + m_drawPoints.push_back(placed); + } + break; + } + case 3: + { + const Mat4& transformation = object->getTransformation(); + Vec3 transformed = {0.0f, 0.0f, 0.0f}; + for (std::vector::const_iterator point = m_points.begin(); point != m_points.end(); ++point) + { + transformed.x = point->x * transformation.m[0] + point->y * transformation.m[4] + + point->z * transformation.m[8] + transformation.m[12]; + transformed.y = point->x * transformation.m[1] + point->y * transformation.m[5] + + point->z * transformation.m[9] + transformation.m[13]; + transformed.z = point->x * transformation.m[2] + point->y * transformation.m[6] + + point->z * transformation.m[10] + transformation.m[14]; + Vec3 placed; + placed.x = transformed.x + transformation.m[12]; + placed.y = transformed.y + transformation.m[13]; + placed.z = transformed.z + transformation.m[14]; + m_drawPoints.push_back(placed); + } + break; + } + case 4: // [INFERRED] the jump table has a fifth entry that shares the default target + default: + Debug(DebugTypeError, "AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectLine.cpp", 124, "") + << "Invalid type."; + break; + } + renderer->drawLine(m_drawPoints, m_colour, m_width); + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamic3dText.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamic3dText.cpp new file mode 100644 index 000000000..b9184baf1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamic3dText.cpp @@ -0,0 +1,118 @@ +// World-space debug text that follows a bot's equipment or an information. Evidence: libaidll.so +// (ia-32) 0x371500..0x371D3F. Placement attested by the __FILE__ string +// "AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamic3dText.cpp". + +#include "DPDynamicPrimitives.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x371C90, __tcf_0 0x371CF0, _GLOBAL__I 0x371D20). +#include + +#include "../../../../../Core/Debug.h" +#include "../../../../AIInterface/BFKnowledge/DebugRenderer.h" +#include "../../AIBot/BotMain.h" +#include "../../AIKnowledge/Information.h" +#include "../../Main/InformationManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x371500 (C2; C1 0x371580). +DPDynamic3dText::DPDynamic3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::string& text, Bot* bot, DPDynamicTypes type, int size, + AITextAlignmentX alignX, AITextAlignmentY alignY) + : DPStatic3dText(lifeTime, colour, position, text, size, alignX, alignY) + , m_bot(bot) + , m_information(0xFFFFFFFFu) + , m_type(type) +{ +} + +// ELF 0x371600 (C2; C1 0x371680). +DPDynamic3dText::DPDynamic3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::vector& lines, Bot* bot, DPDynamicTypes type, + int size, AITextAlignmentX alignX, AITextAlignmentY alignY) + : DPStatic3dText(lifeTime, colour, position, lines, size, alignX, alignY) + , m_bot(bot) + , m_information(0xFFFFFFFFu) + , m_type(type) +{ +} + +// ELF 0x371700 (C2; C1 0x371780). +DPDynamic3dText::DPDynamic3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::string& text, unsigned int information, + DPDynamicTypes type, int size, AITextAlignmentX alignX, + AITextAlignmentY alignY) + : DPStatic3dText(lifeTime, colour, position, text, size, alignX, alignY) + , m_bot(0) + , m_information(information) + , m_type(type) +{ +} + +// ELF 0x371800 (C2; C1 0x371880). +DPDynamic3dText::DPDynamic3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::vector& lines, unsigned int information, + DPDynamicTypes type, int size, AITextAlignmentX alignX, + AITextAlignmentY alignY) + : DPStatic3dText(lifeTime, colour, position, lines, size, alignX, alignY) + , m_bot(0) + , m_information(information) + , m_type(type) +{ +} + +// ELF 0x371900 (D2; D1 0x371940, D0 0x371980). +DPDynamic3dText::~DPDynamic3dText() +{ +} + +// ELF 0x3719C0. The text sits at m_position offset by the information's position; types 0-2 use +// that directly, type 3 transforms it and then adds the translation a second time (shipped +// defect, kept). A negative or larger type reports and still draws. +bool DPDynamic3dText::draw(IDebugRenderer* renderer) +{ + Information* const information + = informationManager->getInformation(m_bot ? m_bot->getCurrentEquipment() : m_information); + // shipped defect: no null test before the virtual call. + const Vec3& offset = information->getPosition(); + Vec3 position; + position.x = m_position.x + offset.x; + position.y = m_position.y + offset.y; + position.z = m_position.z + offset.z; + switch (m_type) + { + case 0: + case 1: + case 2: + break; + case 3: + { + const Mat4& transformation = information->getTransformation(); + Vec3 transformed = {0.0f, 0.0f, 0.0f}; + transformed.x = position.x * transformation.m[0] + position.y * transformation.m[4] + + position.z * transformation.m[8] + transformation.m[12]; + transformed.y = position.x * transformation.m[1] + position.y * transformation.m[5] + + position.z * transformation.m[9] + transformation.m[13]; + transformed.z = position.x * transformation.m[2] + position.y * transformation.m[6] + + position.z * transformation.m[10] + transformation.m[14]; + position = transformed; + position.x += transformation.m[12]; + position.y += transformation.m[13]; + position.z += transformation.m[14]; + break; + } + default: + Debug(DebugTypeError, "AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamic3dText.cpp", 141, "") + << "Invalid type."; + break; + } + renderer->draw3dText(position, m_lines, m_size, m_colour, m_alignX, m_alignY); + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicCircle.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicCircle.cpp new file mode 100644 index 000000000..bdecceee6 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicCircle.cpp @@ -0,0 +1,106 @@ +// Debug circle that follows a bot's equipment or an information. Evidence: libaidll.so (ia-32) +// 0x371D40..0x3723DF. Placement attested by the __FILE__ string +// "AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicCircle.cpp". + +#include "DPDynamicPrimitives.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x372330, __tcf_0 0x372390, _GLOBAL__I 0x3723C0). +#include + +#include "../../../../../Core/Debug.h" +#include "../../../../AIInterface/BFKnowledge/DebugRenderer.h" +#include "../../AIBot/BotMain.h" +#include "../../AIKnowledge/Information.h" +#include "../../Main/InformationManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x371D40 (C2; C1 0x371DC0). +DPDynamicCircle::DPDynamicCircle(float lifeTime, unsigned int colour, const Vec3& position, + float radius, Bot* bot, DPDynamicTypes /*type*/, const Vec3& normal, + bool filled, int segments) + : DPStaticCircle(lifeTime, colour, position, radius, normal, filled, segments) + , m_bot(bot) + , m_information(0xFFFFFFFFu) +{ +} + +// ELF 0x371E40 (C2; C1 0x371EC0). +DPDynamicCircle::DPDynamicCircle(float lifeTime, unsigned int colour, const Vec3& position, + float radius, unsigned int information, DPDynamicTypes /*type*/, + const Vec3& normal, bool filled, int segments) + : DPStaticCircle(lifeTime, colour, position, radius, normal, filled, segments) + , m_bot(0) + , m_information(information) +{ +} + +// ELF 0x371F40 (D2; D1 0x371F80, D0 0x371FC0). +DPDynamicCircle::~DPDynamicCircle() +{ +} + +// ELF 0x372000. The circle sits at m_position offset by the information's position; types 0 and 1 +// keep m_normal, 2 takes the transformation's third row and 3 its second row. An unknown type +// reports and draws with the zero centre and normal. +bool DPDynamicCircle::draw(IDebugRenderer* renderer) +{ + Information* const information + = informationManager->getInformation(m_bot ? m_bot->getCurrentEquipment() : m_information); + if (!information) + return false; + + Vec3 normal = {0.0f, 0.0f, 0.0f}; + Vec3 centre = {0.0f, 0.0f, 0.0f}; + switch (m_type) + { + case 0: + case 1: + { + const Vec3& position = information->getPosition(); + centre.x = m_position.x + position.x; + centre.y = m_position.y + position.y; + centre.z = m_position.z + position.z; + normal = m_normal; + break; + } + case 2: + { + const Vec3& position = information->getPosition(); + centre.x = m_position.x + position.x; + centre.y = m_position.y + position.y; + centre.z = m_position.z + position.z; + const Mat4& transformation = information->getTransformation(); + normal.x = transformation.m[8]; + normal.y = transformation.m[9]; + normal.z = transformation.m[10]; + break; + } + case 3: + { + const Vec3& position = information->getPosition(); + centre.x = m_position.x + position.x; + centre.y = m_position.y + position.y; + centre.z = m_position.z + position.z; + const Mat4& transformation = information->getTransformation(); + normal.x = transformation.m[4]; + normal.y = transformation.m[5]; + normal.z = transformation.m[6]; + break; + } + case 4: // [INFERRED] the jump table has a fifth entry that shares the default target + default: + Debug(DebugTypeError, "AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicCircle.cpp", 97, "") + << "Invalid type."; + break; + } + renderer->drawCircle(normal, centre, m_radius, m_colour, m_filled, m_segments); + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicLine.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicLine.cpp new file mode 100644 index 000000000..159e2de4a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicLine.cpp @@ -0,0 +1,161 @@ +// Debug polyline that follows a bot's equipment or an information. Evidence: libaidll.so (ia-32) +// 0x3723E0..0x37312F. Placement attested by the __FILE__ string +// "AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicLine.cpp". + +#include "DPDynamicPrimitives.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x373080, __tcf_0 0x3730E0, _GLOBAL__I 0x373110). +#include + +#include + +#include "../../../../../Core/Debug.h" +#include "../../../../AIInterface/BFKnowledge/DebugRenderer.h" +#include "../../AIBot/BotMain.h" +#include "../../AIKnowledge/Information.h" +#include "../../Main/InformationManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x3723E0 (C2; C1 0x372470). +DPDynamicLine::DPDynamicLine(float lifeTime, unsigned int colour, const Vec3& start, const Vec3& end, + float width, Bot* bot, DPDynamicTypes type) + : DPStaticLine(lifeTime, colour, start, end, width) + , m_bot(bot) + , m_information(0xFFFFFFFFu) + , m_type(type) +{ +} + +// ELF 0x372600 (C2; C1 0x372690). +DPDynamicLine::DPDynamicLine(float lifeTime, unsigned int colour, const Vec3& start, const Vec3& end, + float width, unsigned int information, DPDynamicTypes type) + : DPStaticLine(lifeTime, colour, start, end, width) + , m_bot(0) + , m_information(information) + , m_type(type) +{ +} + +// ELF 0x372500 (C2; C1 0x372580). +DPDynamicLine::DPDynamicLine(float lifeTime, unsigned int colour, const std::vector& points, + float width, Bot* bot, DPDynamicTypes type) + : DPStaticLine(lifeTime, colour, points, width) + , m_bot(bot) + , m_information(0xFFFFFFFFu) + , m_type(type) +{ +} + +// ELF 0x372720 (C2; C1 0x3727A0). +DPDynamicLine::DPDynamicLine(float lifeTime, unsigned int colour, const std::vector& points, + float width, unsigned int information, DPDynamicTypes type) + : DPStaticLine(lifeTime, colour, points, width) + , m_bot(0) + , m_information(information) + , m_type(type) +{ +} + +// ELF 0x372820 (D2; D1 0x3728A0, D0 0x372920). +DPDynamicLine::~DPDynamicLine() +{ +} + +// ELF 0x3729A0. Type 2 derives a yaw from the transformation's third row (x and z normalised by +// their absolute sum, acos of the clamped x, +-pi when z is negative) and rotates every point by +// it before adding the translation. Type 3 transforms every point and then adds the translation a +// second time (shipped defect, kept). An unknown type reports and draws the empty point list. +bool DPDynamicLine::draw(IDebugRenderer* renderer) +{ + m_drawPoints.resize(0); + Information* const information + = informationManager->getInformation(m_bot ? m_bot->getCurrentEquipment() : m_information); + if (!information) + return false; + + switch (m_type) + { + case 0: + { + const Vec3& position = information->getPosition(); + for (std::vector::const_iterator point = m_points.begin(); point != m_points.end(); ++point) + { + Vec3 placed; + placed.x = point->x + position.x; + placed.y = point->y + position.y; + placed.z = point->z + position.z; + m_drawPoints.push_back(placed); + } + break; + } + case 1: + m_drawPoints.push_back(information->getPosition()); + m_drawPoints.insert(m_drawPoints.end(), m_points.begin(), m_points.end()); + break; + case 2: + { + const Mat4& transformation = information->getTransformation(); + Vec3 rotated = {0.0f, 0.0f, 0.0f}; + const float scale = 1.0f / (std::fabs(transformation.m[8]) + std::fabs(transformation.m[10])); + float x = transformation.m[8] * scale; + const float z = transformation.m[10] * scale; + if (x < -1.0f) + x = -1.0f; + else if (x > 1.0f) + x = 1.0f; + float angle = std::acos(x); + if (z < 0.0f) + { + if (angle < 0.0f) + angle -= 3.14159265f; + else + angle += 3.14159265f; + } + for (std::vector::const_iterator point = m_points.begin(); point != m_points.end(); ++point) + { + rotateXZ(*point, rotated, angle); + Vec3 placed; + placed.x = rotated.x + transformation.m[12]; + placed.y = rotated.y + transformation.m[13]; + placed.z = rotated.z + transformation.m[14]; + m_drawPoints.push_back(placed); + } + break; + } + case 3: + { + const Mat4& transformation = information->getTransformation(); + Vec3 transformed = {0.0f, 0.0f, 0.0f}; + for (std::vector::const_iterator point = m_points.begin(); point != m_points.end(); ++point) + { + transformed.x = point->x * transformation.m[0] + point->y * transformation.m[4] + + point->z * transformation.m[8] + transformation.m[12]; + transformed.y = point->x * transformation.m[1] + point->y * transformation.m[5] + + point->z * transformation.m[9] + transformation.m[13]; + transformed.z = point->x * transformation.m[2] + point->y * transformation.m[6] + + point->z * transformation.m[10] + transformation.m[14]; + Vec3 placed; + placed.x = transformed.x + transformation.m[12]; + placed.y = transformed.y + transformation.m[13]; + placed.z = transformed.z + transformation.m[14]; + m_drawPoints.push_back(placed); + } + break; + } + case 4: // [INFERRED] the jump table has a fifth entry that shares the default target + default: + Debug(DebugTypeError, "AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicLine.cpp", 160, "") + << "Invalid type."; + break; + } + renderer->drawLine(m_drawPoints, m_colour, m_width); + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicPrimitives.h b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicPrimitives.h new file mode 100644 index 000000000..094734529 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicPrimitives.h @@ -0,0 +1,160 @@ +// Debug primitives that follow a bot's equipment or an AI object, drawn relative to it. +// Placement: each class's TU path is attested by its __FILE__ string +// (AI/AIDLL/AI/AIUtils/DebugRendering/DP*.cpp); this shared header name is [INFERRED]. + +#ifndef AI_AIDLL_AI_AIUTILS_DEBUGRENDERING_DPDYNAMICPRIMITIVES_H +#define AI_AIDLL_AI_AIUTILS_DEBUGRENDERING_DPDYNAMICPRIMITIVES_H + +#include +#include + +#include "../../DrawPrimitives/DPStatic3dText.h" +#include "../../DrawPrimitives/DPStaticCircle.h" +#include "../../DrawPrimitives/DPStaticLine.h" +#include "../../Main/AIDllTypes.h" + +namespace dice { +namespace hfe { +namespace ai { + +// The DPDynamic* primitives resolve their information either through Bot::getCurrentEquipment +// (when constructed with a bot) or through a stored information handle (bot null). The +// DPAIObject* primitives resolve a stored information handle and use its IAIObject. The +// [UNRESOLVED] DPDynamicTypes values select how the stored geometry is placed: +// 0 offset by the position, 1 (line: prefix the position), 2 yaw-rotated about the +// transformation (circle: normal = third matrix row), 3 fully transformed (circle: second row). + +// sizeof == 0x44 on ia-32. +class DPDynamicCircle : public DPStaticCircle +{ +public: + // shipped defect: neither constructor stores `type`, so m_type is never initialised. + DPDynamicCircle(float lifeTime, unsigned int colour, const Vec3& position, float radius, Bot* bot, + DPDynamicTypes type, const Vec3& normal, bool filled, int segments); + DPDynamicCircle(float lifeTime, unsigned int colour, const Vec3& position, float radius, + unsigned int information, DPDynamicTypes type, const Vec3& normal, bool filled, + int segments); + virtual ~DPDynamicCircle(); + + // Returns false once the information no longer resolves. + virtual bool draw(IDebugRenderer* renderer); + +protected: + /* +0x38 */ Bot* m_bot; + /* +0x3C */ unsigned int m_information; + /* +0x40 */ DPDynamicTypes m_type; +}; + +// sizeof == 0x3C on ia-32. +class DPDynamicLine : public DPStaticLine +{ +public: + DPDynamicLine(float lifeTime, unsigned int colour, const Vec3& start, const Vec3& end, float width, + Bot* bot, DPDynamicTypes type); + DPDynamicLine(float lifeTime, unsigned int colour, const Vec3& start, const Vec3& end, float width, + unsigned int information, DPDynamicTypes type); + DPDynamicLine(float lifeTime, unsigned int colour, const std::vector& points, float width, + Bot* bot, DPDynamicTypes type); + DPDynamicLine(float lifeTime, unsigned int colour, const std::vector& points, float width, + unsigned int information, DPDynamicTypes type); + virtual ~DPDynamicLine(); + + // Rebuilds m_drawPoints from m_points; returns false once the information no longer resolves. + virtual bool draw(IDebugRenderer* renderer); + +protected: + /* +0x24 */ Bot* m_bot; + /* +0x28 */ unsigned int m_information; + /* +0x2C */ DPDynamicTypes m_type; + /* +0x30 */ std::vector m_drawPoints; +}; + +// sizeof == 0x44 on ia-32. +class DPDynamic3dText : public DPStatic3dText +{ +public: + DPDynamic3dText(float lifeTime, unsigned int colour, const Vec3& position, const std::string& text, + Bot* bot, DPDynamicTypes type, int size, AITextAlignmentX alignX, + AITextAlignmentY alignY); + DPDynamic3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::vector& lines, Bot* bot, DPDynamicTypes type, int size, + AITextAlignmentX alignX, AITextAlignmentY alignY); + DPDynamic3dText(float lifeTime, unsigned int colour, const Vec3& position, const std::string& text, + unsigned int information, DPDynamicTypes type, int size, AITextAlignmentX alignX, + AITextAlignmentY alignY); + DPDynamic3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::vector& lines, unsigned int information, + DPDynamicTypes type, int size, AITextAlignmentX alignX, AITextAlignmentY alignY); + virtual ~DPDynamic3dText(); + + // shipped defect: the information is not null-tested, so an unresolved one is dereferenced. + virtual bool draw(IDebugRenderer* renderer); + +protected: + /* +0x38 */ Bot* m_bot; + /* +0x3C */ unsigned int m_information; + /* +0x40 */ DPDynamicTypes m_type; +}; + +// sizeof == 0x40 on ia-32. +class DPAIObjectCircle : public DPStaticCircle +{ +public: + // shipped defect: `type` is not stored, so m_type is never initialised. + DPAIObjectCircle(float lifeTime, unsigned int colour, const Vec3& position, float radius, + unsigned int information, DPDynamicTypes type, const Vec3& normal, bool filled, + int segments); + virtual ~DPAIObjectCircle(); + + virtual bool draw(IDebugRenderer* renderer); + +protected: + /* +0x38 */ unsigned int m_information; + /* +0x3C */ DPDynamicTypes m_type; +}; + +// sizeof == 0x38 on ia-32. +class DPAIObjectLine : public DPStaticLine +{ +public: + DPAIObjectLine(float lifeTime, unsigned int colour, const Vec3& start, const Vec3& end, + float width, unsigned int information, DPDynamicTypes type); + DPAIObjectLine(float lifeTime, unsigned int colour, const std::vector& points, float width, + unsigned int information, DPDynamicTypes type); + virtual ~DPAIObjectLine(); + + virtual bool draw(IDebugRenderer* renderer); + +protected: + /* +0x24 */ unsigned int m_information; + /* +0x28 */ DPDynamicTypes m_type; + /* +0x2C */ std::vector m_drawPoints; +}; + +// sizeof == 0x44 on ia-32. +class DPAIObject3dText : public DPStatic3dText +{ +public: + DPAIObject3dText(float lifeTime, unsigned int colour, const Vec3& position, const std::string& text, + unsigned int information, DPDynamicTypes type, int size, + AITextAlignmentX alignX, AITextAlignmentY alignY); + DPAIObject3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::vector& lines, unsigned int information, + DPDynamicTypes type, int size, AITextAlignmentX alignX, AITextAlignmentY alignY); + virtual ~DPAIObject3dText(); + + // shipped defect: resolves its information through m_bot, which no constructor writes; + // m_information is stored but never read. + virtual bool draw(IDebugRenderer* renderer); + +protected: + /* +0x38 */ Bot* m_bot; + /* +0x3C */ unsigned int m_information; + /* +0x40 */ DPDynamicTypes m_type; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIUTILS_DEBUGRENDERING_DPDYNAMICPRIMITIVES_H diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPGraph.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPGraph.cpp new file mode 100644 index 000000000..70783d14a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPGraph.cpp @@ -0,0 +1,84 @@ +// Debug graph primitive. Evidence: libaidll.so (ia-32) 0x373130..0x37348F. +// [INFERRED] Source placement. + +#include "DPGraph.h" + +#include "IBFGraph.h" + +#include "../../../../AIInterface/BFKnowledge/BFGraphCreator.h" +#include "../../Main/CommonSingletonServer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x373130 (C2; C1 0x373190). Colour 0. +DPGraph::DPGraph(float lifeTime) + : DrawPrimitive(lifeTime, 0) +{ + m_graph = static_cast(CommonSingletonServer::m_iBFGraphCreator)->createGraph(); +} + +// ELF 0x3731F0 (D2; D1 0x373240, D0 0x373290). +DPGraph::~DPGraph() +{ + static_cast(CommonSingletonServer::m_iBFGraphCreator)->destroyGraph(m_graph); +} + +// ELF 0x3732F0. +bool DPGraph::draw(IDebugRenderer* /*renderer*/) +{ + return true; +} + +// ELF 0x373300: m_graph slot 2 (BFGraph::setNumberOfSamples(int)). +void DPGraph::setNumberOfSamples(int samples) +{ + m_graph->setNumberOfSamples(samples); +} + +// ELF 0x373330: m_graph slot 3 (BFGraph::setDimensions(float, float, float, float)). +void DPGraph::setDimensions(float x, float y, float width, float height) +{ + m_graph->setDimensions(x, y, width, height); +} + +// ELF 0x373370: m_graph slot 4 (BFGraph::setColours(unsigned int, unsigned int, unsigned int)). +void DPGraph::setColours(unsigned int first, unsigned int second, unsigned int third) +{ + m_graph->setColours(first, second, third); +} + +// ELF 0x3733A0: m_graph slot 5 (BFGraph::setThresholds(float, float)). +void DPGraph::setThresholds(float low, float high) +{ + m_graph->setThresholds(low, high); +} + +// ELF 0x3733D0: m_graph slot 6 (BFGraph::setMinMaxY(float, float)). +void DPGraph::setMinMaxY(float minimum, float maximum) +{ + m_graph->setMinMaxY(minimum, maximum); +} + +// ELF 0x373400: m_graph slot 9 (BFGraph::addSample(float)). +void DPGraph::addSample(float sample) +{ + m_graph->addSample(sample); +} + +// ELF 0x373430: m_graph slot 7 (BFGraph::setCurrentSampleEnding(std::string const&)). +void DPGraph::setCurrentSampleEnding(const std::string& ending) +{ + m_graph->setCurrentSampleEnding(ending); +} + +// ELF 0x373460: m_graph slot 8 (BFGraph::setCurrentSampleOffset(int, int)). +void DPGraph::setCurrentSampleOffset(int x, int y) +{ + m_graph->setCurrentSampleOffset(x, y); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPGraph.h b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPGraph.h new file mode 100644 index 000000000..661ba8e47 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPGraph.h @@ -0,0 +1,45 @@ +// A timed debug graph backed by an engine IBFGraph. +// [INFERRED] Source placement (the TU is DPGraph.cpp; it links between the attested +// AIUtils/DebugRendering/DPDynamicLine.cpp and DPManager.cpp). + +#ifndef AI_AIDLL_AI_AIUTILS_DEBUGRENDERING_DPGRAPH_H +#define AI_AIDLL_AI_AIUTILS_DEBUGRENDERING_DPGRAPH_H + +#include + +#include "../../DrawPrimitives/DrawPrimitive.h" +#include "../../Main/AIDllTypes.h" + +namespace dice { +namespace hfe { +namespace ai { + +// sizeof == 0x18 on ia-32. The graph is created through IBFGraphCreator in the constructor and +// destroyed through it in the destructor; every setter forwards to it. +class DPGraph : public DrawPrimitive +{ +public: + explicit DPGraph(float lifeTime); + virtual ~DPGraph(); + + // The engine graph draws itself; this only reports the primitive alive. + virtual bool draw(IDebugRenderer* renderer); + + void setNumberOfSamples(int samples); + void setDimensions(float x, float y, float width, float height); + void setColours(unsigned int first, unsigned int second, unsigned int third); + void setThresholds(float low, float high); + void setMinMaxY(float minimum, float maximum); + void addSample(float sample); + void setCurrentSampleEnding(const std::string& ending); + void setCurrentSampleOffset(int x, int y); + +protected: + /* +0x14 */ IBFGraph* m_graph; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIUTILS_DEBUGRENDERING_DPGRAPH_H diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/IBFGraph.h b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/IBFGraph.h new file mode 100644 index 000000000..7acea1c3e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/IBFGraph.h @@ -0,0 +1,37 @@ +// Engine debug-graph interface, as the AI DLL calls it through DPGraph. +// [CHOSEN, not recovered] Declared AIDLL-side because the engine-side AIInterface tree has no +// declaration yet; move it next to BFGraphCreator.h once that tree adds one. +// Evidence: bf2 (ia-32) vtable for dice::hfe::ai::BFGraph at 0x88DB320 (slots below, D1/D0 first) +// and IBFGraph at 0x88DB440 (all eight pure); names and parameter types from the BFGraph symbols. +// Return types [INFERRED] void: the engine bodies only forward to an inner object, and every DLL +// call site (DPGraph's setters) discards the result register. + +#ifndef AI_AIDLL_AI_AIUTILS_DEBUGRENDERING_IBFGRAPH_H +#define AI_AIDLL_AI_AIUTILS_DEBUGRENDERING_IBFGRAPH_H + +#include + +namespace dice { +namespace hfe { +namespace ai { + +class IBFGraph +{ +public: + virtual ~IBFGraph() {} + + virtual void setNumberOfSamples(int samples) = 0; // slot 2 + virtual void setDimensions(float x, float y, float width, float height) = 0; // slot 3 + virtual void setColours(unsigned int first, unsigned int second, unsigned int third) = 0; // 4 + virtual void setThresholds(float low, float high) = 0; // slot 5 + virtual void setMinMaxY(float minimum, float maximum) = 0; // slot 6 + virtual void setCurrentSampleEnding(const std::string& ending) = 0; // slot 7 + virtual void setCurrentSampleOffset(int x, int y) = 0; // slot 8 + virtual void addSample(float sample) = 0; // slot 9 +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIUTILS_DEBUGRENDERING_IBFGRAPH_H diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/IAimerHelper.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/IAimerHelper.cpp new file mode 100644 index 000000000..3a801c4ca --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/IAimerHelper.cpp @@ -0,0 +1,32 @@ +// Aimer singleton registration. [INFERRED] Source placement. + +#include "IAimerHelper.h" + +#include "../../../../Core/ClassManager.h" +#include "../Main/CommonSingletonServer.h" + +namespace dice { +namespace hfe { + +extern ClassManager* classManager; + +namespace ai { + +// ELF 0x2EAA00 (C1; C2 0x2EA960). +IAimerHelper::IAimerHelper() +{ + // shipped defect: the cached singleton is looked up as "AimerHelper", not this name. + if (!CommonSingletonServer::m_iAimerHelper) + classManager->registerSimpleSingleton("IAimerHelper", this); +} + +// ELF 0x2EAB30 (D1; D2 0x2EAAA0, D0 0x2EABC0). +IAimerHelper::~IAimerHelper() +{ + if (CommonSingletonServer::m_iAimerHelper == this) + classManager->unregisterSimpleSingleton("IAimerHelper"); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/IAimerHelper.h b/Code/BF2/AI/AIDLL/AI/AIUtils/IAimerHelper.h new file mode 100644 index 000000000..8b711b8f7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/IAimerHelper.h @@ -0,0 +1,35 @@ +// Abstract registered aimer interface. [INFERRED] Source placement beside AimerHelper. + +#ifndef AI_AIDLL_AI_AIUTILS_IAIMERHELPER_H +#define AI_AIDLL_AI_AIUTILS_IAIMERHELPER_H + +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +class IAimerHelper +{ +public: + IAimerHelper(); + virtual ~IAimerHelper(); + + // [CHOSEN, not recovered] Name, pointer spellings/constness and byte return under + // the unimplemented-slot exception. Pure in IAimerHelper/AimerHelper vtables + // ia-32 ELF 0x4BE8E8/0x4BE8C0, amd-64 0x61D160/0x61D120, slot 2 (+0x08/+0x10). + // The sole caller is engine BFObjectEnvironment::hasIndirectLineOfFire: + // ia-32 0x8402408 passes stack this, &exitVelocity, &drag, &scaledGravity, + // &delta, &weaponPosition, &target, &velocity, &apex, then tests al at 0x840240D. + // amd-64 0x771752: rdi=this; rsi/rdx/rcx/r8/r9 are the first five addresses, + // the three output addresses are on the stack; al is tested at 0x771757. + // No AI-image call or concrete override exists. This is not the by-value-float slot 3. + virtual unsigned char unimplementedAimerSlot2(const float*, const float*, const float*, + const Vec3*, const Vec3*, Vec3*, Vec3*, Vec3*) = 0; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/IgnoreListPredicate.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/IgnoreListPredicate.cpp new file mode 100644 index 000000000..84c8496cd --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/IgnoreListPredicate.cpp @@ -0,0 +1,33 @@ +// Recovered from libaidll.so 1.5.3153 (0x2EA000..0x2EA0A1). + +#include "IgnoreListPredicate.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2EA0B0, __tcf_0 0x2EA110, _GLOBAL__I 0x2EA140). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2EA000 / 0x2EA030: the vptr, then the list's address at +4. +IgnoreListPredicate::IgnoreListPredicate(std::vector& ignore) + : m_ignore(&ignore) +{ +} + +// ELF 0x2EA060. Index walk; the size is read once, the data pointer on every step. +bool IgnoreListPredicate::predicate(IAIObject* object) +{ + const unsigned int count = static_cast(m_ignore->size()); + for (unsigned int i = 0; i < count; ++i) + { + if (object == (*m_ignore)[i]) + return false; + } + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/IgnoreListPredicate.h b/Code/BF2/AI/AIDLL/AI/AIUtils/IgnoreListPredicate.h new file mode 100644 index 000000000..902233b99 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/IgnoreListPredicate.h @@ -0,0 +1,31 @@ +// Object predicate that rejects the objects of a borrowed ignore list (line-of-fire and aiming +// traces). ELF: vtable 0x4BE8A8 (base AIObjectPredicate, one slot), ctor C1/C2 0x2EA000/0x2EA030, +// predicate 0x2EA060; attested FILE symbol IgnoreListPredicate.cpp (directory [INFERRED]). +#ifndef AI_AIDLL_AI_AIUTILS_IGNORELISTPREDICATE_H +#define AI_AIDLL_AI_AIUTILS_IGNORELISTPREDICATE_H + +#include + +#include "../../../AIInterface/BFKnowledge/AIAdapterTypes.h" // AIObjectPredicate + +namespace dice { +namespace hfe { +namespace ai { + +class IgnoreListPredicate : public AIObjectPredicate +{ +public: + explicit IgnoreListPredicate(std::vector& ignore); + + // False for an object in the list, true otherwise. + virtual bool predicate(IAIObject* object); + +private: + /* +0x04 */ std::vector* m_ignore; // borrowed; the constructor stores the address +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/Opening.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/Opening.cpp new file mode 100644 index 000000000..dd07ba62f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/Opening.cpp @@ -0,0 +1,153 @@ +// Opening visibility queries. [INFERRED] Source placement. + +// static init: ELF 0x3686D0 (__tcf_0 0x368730, _GLOBAL__I 0x368760): 's Init object only. +#include + +#include "Opening.h" + +#include "../../../AIInterface/BFKnowledge/PlanePolygon.h" + +#include +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// [CHOSEN, not recovered] Local factoring of the inline Vec2 normalization at ELF 0x368574..0x3685C3. +void normalizeOpeningNormal(Vec2& normal) +{ + const float lengthSqr = normal.x * normal.x + normal.y * normal.y; + if (std::fabs(lengthSqr - 1.0f) < 1.1920929e-07f) + return; + if (std::fabs(lengthSqr) < 1.4210855e-14f) + { + normal.x = normal.y = 0.0f; + return; + } + const float inverse = 1.0f / std::sqrt(lengthSqr); + normal.x *= inverse; + normal.y *= inverse; +} + +} // namespace + +// ELF 0x367AA0 (amd-64 0x39EF90). +bool Opening::spot(Vec2& origin, Vec2& towards, std::list* path, + std::list* openings, IPlanePolygon& polygon, Vec3& targetPosition) +{ + Vec2 position = {0.0f, 0.0f}; + Vec2 unused = {0.0f, 0.0f}; + Vec2 clipped = {0.0f, 0.0f}; + vec3ToVec2XZ(m_position, position); + const Vec3 delta = {targetPosition.x - m_position.x, targetPosition.y - m_position.y, + targetPosition.z - m_position.z}; + vec3ToVec2XZ(delta, unused); + for (std::list::iterator it = openings->begin(); it != openings->end(); ++it) + { + if ((*it)->isInside(origin, towards, clipped)) + { + // shipped defect: searches the same list being traversed, rather than path. + if (std::find(openings->begin(), openings->end(), *it) != openings->end()) + return true; + } + else + { + if (!polygon.intersects(clipped, position)) + return false; + bool rejected = false; + for (std::list::iterator p = path->begin(); p != path->end(); ++p) + { + // shipped defect: repeatedly tests *it, never the path entry *p. + if (!(*it)->isInside(origin, towards, clipped)) + { + rejected = true; + break; + } + } + if (rejected) + continue; + } + path->insert(path->begin(), *it); + if ((*it)->spot(origin, towards, path, openings, polygon, targetPosition)) + return true; + path->erase(path->begin()); + } + return false; +} + +// ELF 0x367EE0 (amd-64 0x39F1F0). +std::list* Opening::spotAll(Vec2& origin, Vec2& first, Vec2& second, + std::list* path, std::list* openings, IPlanePolygon& polygon, Vec3& targetPosition) +{ + Vec2 position = {0.0f, 0.0f}; + Vec2 unused = {0.0f, 0.0f}; + Vec2 clippedFirst = {0.0f, 0.0f}; + Vec2 clippedSecond = {0.0f, 0.0f}; + vec3ToVec2XZ(m_position, position); + std::list* const result = new std::list(); + const Vec3 delta = {targetPosition.x - m_position.x, targetPosition.y - m_position.y, + targetPosition.z - m_position.z}; + vec3ToVec2XZ(delta, unused); + for (std::list::iterator it = openings->begin(); it != openings->end(); ++it) + { + const bool firstInside = (*it)->isInside(origin, first, clippedFirst); + const bool secondInside = (*it)->isInside(origin, second, clippedSecond); + if (!firstInside) + { + if (!polygon.intersects(clippedFirst, position)) + return result; + for (std::list::iterator p = path->begin(); p != path->end(); ++p) + { + // shipped defect: tests the current opening instead of the path entry. + if (!(*it)->isInside(origin, first, clippedFirst)) + return result; + } + } + else + clippedFirst = first; + if (secondInside) + clippedSecond = second; + // shipped defect: searches openings, not path, just as spot does. + if (std::find(openings->begin(), openings->end(), *it) != openings->end()) + { + result->insert(result->end(), clippedFirst); + result->insert(result->end(), clippedSecond); + } + else + { + path->insert(path->begin(), *it); + std::list* const child = (*it)->spotAll(origin, clippedFirst, clippedSecond, + path, openings, polygon, targetPosition); + std::copy(child->begin(), child->end(), std::inserter(*result, result->begin())); + // shipped defect: the recursive result list and its nodes are not deleted. + path->erase(path->begin()); + } + } + return result; +} + +// ELF 0x368510 (amd-64 0x39EDC0). +bool Opening::isInside(Vec2& origin, Vec2& towards, Vec2& clipped) +{ + const Vec2 delta = {towards.x - origin.x, towards.y - origin.y}; + Vec2 normal = {-delta.y, delta.x}; + normalizeOpeningNormal(normal); + // The endpoints are dotted directly; origin is not subtracted from them. + const float firstDot = normal.x * m_first.x + normal.y * m_first.y; + const float secondDot = normal.x * m_second.x + normal.y * m_second.y; + if ((firstDot >= 0.0f && secondDot < 0.0f) || (firstDot < 0.0f && secondDot > 0.0f)) + { + clipped = towards; + return true; + } + clipped = firstDot > secondDot ? m_second : m_first; + return false; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/Opening.h b/Code/BF2/AI/AIDLL/AI/AIUtils/Opening.h new file mode 100644 index 000000000..e0bd164fa --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/Opening.h @@ -0,0 +1,63 @@ +// Opening visibility queries. [INFERRED] Source placement; no construction path is emitted. + +#ifndef AI_AIDLL_AI_AIUTILS_OPENING_H +#define AI_AIDLL_AI_AIUTILS_OPENING_H + +#include "../../../../Math/Vec3.h" + +#include +#include +#include + +namespace dice { +namespace hfe { + +class IPlanePolygon; + +namespace ai { + +class Opening +{ +public: + bool spot(Vec2& origin, Vec2& towards, std::list* path, std::list* openings, + IPlanePolygon& polygon, Vec3& targetPosition); + // Returns a newly allocated list owned by the caller; recursive intermediate lists leak as shipped. + std::list* spotAll(Vec2& origin, Vec2& first, Vec2& second, std::list* path, + std::list* openings, IPlanePolygon& polygon, Vec3& targetPosition); + bool isInside(Vec2& origin, Vec2& towards, Vec2& clipped); + + // [CHOSEN, not recovered] Unaccessed storage under AGENTS.md's member exception. + // No vtable/constructor/writer exists in either ELF. Only spot 0x367AA0 / amd-64 + // 0x39EF90, spotAll 0x367EE0 / 0x39F1F0 and isInside 0x368510 / 0x39EDC0 + // access this type; their object reads start at endpoints +0x04/+0x0C and position +0x1C. + // Their outputs and list nodes are distinct from the object prefix. Neighbouring Vec2 + // floats establish four-byte field alignment; no source-level prefix type is attested. + alignas(float) unsigned char m_unaccessedPrefix[4]; +#if INTPTR_MAX == INT64_MAX + // [PLATFORM] [UNRESOLVED] amd-64's unaccessed prefix is sixteen bytes, not four. + // [CHOSEN, not recovered] Extra native storage preserves its observed field offsets; + // it does not guess a container, pointer or original member type/alignment. + unsigned char m_nativeUnresolvedPrefix[12]; +#endif + /* +0x04 */ Vec2 m_first; // [INFERRED] endpoint names; amd-64 +0x10 + /* +0x0C */ Vec2 m_second; // amd-64 +0x18 + // [CHOSEN, not recovered] The eight bytes between endpoints and position are also unaccessed. + /* +0x14 */ unsigned char m_unaccessedBetween[8]; // amd-64 +0x20 + /* +0x1C */ Vec3 m_position; // [INFERRED] name; amd-64 +0x28 +}; + +#if INTPTR_MAX == INT32_MAX +static_assert(offsetof(Opening, m_first) == 0x04, "Opening ia-32 first endpoint"); +static_assert(offsetof(Opening, m_second) == 0x0C, "Opening ia-32 second endpoint"); +static_assert(offsetof(Opening, m_position) == 0x1C, "Opening ia-32 position"); +#elif INTPTR_MAX == INT64_MAX +static_assert(offsetof(Opening, m_first) == 0x10, "Opening native first endpoint"); +static_assert(offsetof(Opening, m_second) == 0x18, "Opening native second endpoint"); +static_assert(offsetof(Opening, m_position) == 0x28, "Opening native position"); +#endif + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/SCurve.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/SCurve.cpp new file mode 100644 index 000000000..40ddc9481 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/SCurve.cpp @@ -0,0 +1,168 @@ +// Source placement: AIDLL_r.dll __FILE__ "Code\BF2\AI\AIDLL\AI\AIUtils\SCurve.cpp" (SCurve::calculate +// 0x101AA8E0 asserts "dep: SCurve::calculate() saw NaN value -- fix me"; retail 1.50 has no assert +// and returns 0). Split out of CustomCurve.cpp; the functions are unchanged. In the ELF SCurve's +// functions follow JCurve's (0x36EEE0..0x36F500) without a static-init block of their own. + +#include "SCurve.h" + +#include // isfinite - SCurve's guard + +namespace dice { +namespace hfe { +namespace ai { + +float* SCurve::curveValues = 0; + +// Builds the shared table on construction and frees it on destruction. +// Destruction retains the null guard and does not clear the shared pointer. +SCurve::SCurve() +{ + init(); +} + +SCurve::~SCurve() +{ + if (curveValues) + delete[] curveValues; +} + +// Returns zero for non-finite input and clamps x >= 1 to one before interpolation. +// [PLATFORM] Uses the standard isfinite name for the original finite predicate. +float SCurve::calculate(float x) +{ + if (!std::isfinite(x)) + return 0.0f; + if (x >= 1.0f) + return 1.0f; + if (x < 0.0f) + return 0.0f; + + const float scaled = x * 100.0f; + const int index = static_cast(scaled); + const float frac = scaled - static_cast(index); + + return frac * curveValues[index + 1] + (1.0f - frac) * curveValues[index]; +} + +// 101 constants, transcribed. +void SCurve::init() +{ + curveValues = new float[101]; // operator new[](0x194) = 101 * 4 + + curveValues[ 0] = 0.0f; + curveValues[ 1] = 0.00224938989f; + curveValues[ 2] = 0.00338781998f; + curveValues[ 3] = 0.00463052979f; + curveValues[ 4] = 0.00598675013f; + curveValues[ 5] = 0.00746650994f; + curveValues[ 6] = 0.00908064004f; + curveValues[ 7] = 0.0108407997f; + curveValues[ 8] = 0.0127597004f; + curveValues[ 9] = 0.0148508996f; + + curveValues[ 10] = 0.0171288997f; + curveValues[ 11] = 0.0196096003f; + curveValues[ 12] = 0.0223098006f; + curveValues[ 13] = 0.0252474006f; + curveValues[ 14] = 0.0284416005f; + curveValues[ 15] = 0.0319131017f; + curveValues[ 16] = 0.0356835015f; + curveValues[ 17] = 0.0397756994f; + curveValues[ 18] = 0.0442142002f; + curveValues[ 19] = 0.0490242988f; + + curveValues[ 20] = 0.0542327985f; + curveValues[ 21] = 0.0598676018f; + curveValues[ 22] = 0.0659573004f; + curveValues[ 23] = 0.0725317001f; + curveValues[ 24] = 0.0796212032f; + curveValues[ 25] = 0.0872564986f; + curveValues[ 26] = 0.0954684988f; + curveValues[ 27] = 0.104287997f; + curveValues[ 28] = 0.113744996f; + curveValues[ 29] = 0.123869002f; + + curveValues[ 30] = 0.134688005f; + curveValues[ 31] = 0.146227002f; + curveValues[ 32] = 0.158509001f; + curveValues[ 33] = 0.171553999f; + curveValues[ 34] = 0.185376003f; + curveValues[ 35] = 0.199987993f; + curveValues[ 36] = 0.215393007f; + curveValues[ 37] = 0.231592f; + curveValues[ 38] = 0.248576f; + curveValues[ 39] = 0.266330004f; + + curveValues[ 40] = 0.284830987f; + curveValues[ 41] = 0.304048002f; + curveValues[ 42] = 0.323940992f; + curveValues[ 43] = 0.344460994f; + curveValues[ 44] = 0.365550995f; + curveValues[ 45] = 0.387147993f; + curveValues[ 46] = 0.409179002f; + curveValues[ 47] = 0.431564987f; + curveValues[ 48] = 0.45422399f; + curveValues[ 49] = 0.477064997f; + + curveValues[ 50] = 0.5f; + curveValues[ 51] = 0.52293402f; + curveValues[ 52] = 0.54577601f; + curveValues[ 53] = 0.568435013f; + curveValues[ 54] = 0.590821028f; + curveValues[ 55] = 0.612851977f; + curveValues[ 56] = 0.634449005f; + curveValues[ 57] = 0.655538976f; + curveValues[ 58] = 0.676059008f; + curveValues[ 59] = 0.695951998f; + + curveValues[ 60] = 0.715167999f; + curveValues[ 61] = 0.733669996f; + curveValues[ 62] = 0.751424015f; + curveValues[ 63] = 0.768408f; + curveValues[ 64] = 0.784606993f; + curveValues[ 65] = 0.800011992f; + curveValues[ 66] = 0.814624012f; + curveValues[ 67] = 0.828445971f; + curveValues[ 68] = 0.841490984f; + curveValues[ 69] = 0.853772998f; + + curveValues[ 70] = 0.86531198f; + curveValues[ 71] = 0.876130998f; + curveValues[ 72] = 0.886255026f; + curveValues[ 73] = 0.895712018f; + curveValues[ 74] = 0.904532015f; + curveValues[ 75] = 0.912743986f; + curveValues[ 76] = 0.920378983f; + curveValues[ 77] = 0.927468002f; + curveValues[ 78] = 0.93404299f; + curveValues[ 79] = 0.940132022f; + + curveValues[ 80] = 0.945766985f; + curveValues[ 81] = 0.950976014f; + curveValues[ 82] = 0.95578599f; + curveValues[ 83] = 0.960223973f; + curveValues[ 84] = 0.964317024f; + curveValues[ 85] = 0.968087018f; + curveValues[ 86] = 0.971557975f; + curveValues[ 87] = 0.974753022f; + curveValues[ 88] = 0.977689981f; + curveValues[ 89] = 0.980390012f; + + curveValues[ 90] = 0.982870996f; + curveValues[ 91] = 0.985149026f; + curveValues[ 92] = 0.987240016f; + curveValues[ 93] = 0.989158988f; + curveValues[ 94] = 0.990918994f; + curveValues[ 95] = 0.992533982f; + curveValues[ 96] = 0.994013011f; + curveValues[ 97] = 0.995369017f; + curveValues[ 98] = 0.996612012f; + curveValues[ 99] = 0.997750998f; + + curveValues[100] = 1.0f; + +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/SCurve.h b/Code/BF2/AI/AIDLL/AI/AIUtils/SCurve.h new file mode 100644 index 000000000..9b1bbfbd6 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/SCurve.h @@ -0,0 +1,27 @@ +// Header placement [INFERRED]: beside its .cpp, whose path AIDLL_r.dll confirms (AIUtils/SCurve.cpp). +// Split out of CustomCurve.h; CustomCurve.h includes it so existing users still see SCurve. + +#ifndef AI_AIDLL_AI_AIUTILS_SCURVE_H +#define AI_AIDLL_AI_AIUTILS_SCURVE_H + +namespace dice { +namespace hfe { +namespace ai { + +// Static curve table with no per-instance state. Construction initializes the shared +// table and destruction releases it. +class SCurve +{ +public: + SCurve(); // - calls init, nothing else + ~SCurve(); + static void init(); + static float calculate(float x); // - the only one with a NaN guard + static float* curveValues; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIUTILS_SCURVE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/TraceUtils.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/TraceUtils.cpp new file mode 100644 index 000000000..78087f7dc --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/TraceUtils.cpp @@ -0,0 +1,43 @@ +// Pathfinding trace helpers. Evidence: libaidll.so 1.5.3153 (ia-32), see TraceUtils.h. + +#include "TraceUtils.h" + +#include "../Main/IAIPathfinding.h" + +#include + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x36AD90, __tcf_0 0x36ADF0, _GLOBAL__I 0x36AE20). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x36AC90. The circle point is centre + rotated * radius with +// rotated = (d.x * cos - d.y * sin, 0, d.z * cos + d.z * sin) +// as compiled: the y component stays at its zero initialisation and the x/z terms do not form a +// rotation about Y (shipped defect, kept). The trace runs on map `map` from `from` to that point +// (IAIPathfinding +0x88: arguments 1, -1, 0.0f, 0, null; the polygon out-value is discarded). +// [PLATFORM] retail keeps the products and sums in x87 extended precision. +bool TraceUtils::tracePointOnCircle(const Vec3& direction, const Vec3& centre, const Vec3& from, int map, + float angle, float radius, Vec3& point) +{ + Vec3 target; + target.x = 0.0f; + target.y = 0.0f; + target.z = 0.0f; + const float sine = std::sin(angle); + const float cosine = std::cos(angle); + const float rotatedX = direction.x * cosine - direction.y * sine; + const float rotatedZ = direction.z * cosine + direction.z * sine; + target.x = rotatedX * radius + centre.x; + target.y = radius * target.y + centre.y; + target.z = rotatedZ * radius + centre.z; + unsigned int polygon; + return IAIPathfinding::instance->trace(map, from, target, point, polygon, 1, -1, 0.0f, 0, 0); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/TraceUtils.h b/Code/BF2/AI/AIDLL/AI/AIUtils/TraceUtils.h new file mode 100644 index 000000000..0ecc1bdc7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/TraceUtils.h @@ -0,0 +1,29 @@ +// Pathfinding trace helpers of the AI image. +// Evidence: libaidll.so 1.5.3153 (ia-32), FILE symbol TraceUtils.cpp; the AIUtils directory and +// the class form of TraceUtils (the mangled name fits a class with static members as well as a +// namespace) are [INFERRED]. + +#ifndef AI_AIDLL_AI_AIUTILS_TRACEUTILS_H // [INFERRED] guard style +#define AI_AIDLL_AI_AIUTILS_TRACEUTILS_H + +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +class TraceUtils +{ +public: + // Rotates `direction` by `angle` (see the body for the shipped formula), scales it by `radius` + // around `centre` and traces the pathfinding map `map` from `from` to that point; `point` + // receives the trace's end. Returns the trace's answer. + static bool tracePointOnCircle(const Vec3& direction, const Vec3& centre, const Vec3& from, int map, + float angle, float radius, Vec3& point); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIUTILS_TRACEUTILS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/VehicleOccupancy.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/VehicleOccupancy.cpp index 3332f4efd..b24862039 100644 --- a/Code/BF2/AI/AIDLL/AI/AIUtils/VehicleOccupancy.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/VehicleOccupancy.cpp @@ -1,9 +1,15 @@ // [INFERRED] path/name; see VehicleOccupancy.h. Full instructions read from // libaidll.so and AIDLL_w32ded.dll . #include "VehicleOccupancy.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x36CE90, __tcf_0 0x36CEF0, _GLOBAL__I 0x36CF20). +#include #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIUnit.h" +#include "../AIBot/SquadManager.h" +#include "../AIBot/SquadMember.h" namespace dice { namespace hfe { namespace ai { @@ -68,4 +74,97 @@ bool vehicleOccupied(unsigned int handle, int side) return false; } +// ELF 0x36CAB0: a primary occupation/booking decides immediately; otherwise inspect the +// secondary objects until a squad match. The resolved primary is deliberately unchecked. +int vehicleOccupiedBySquadMember(unsigned int handle, SquadMember* member, int side) +{ + int result = -1; + SquadManager* const squads = SquadManager::m_instance; + Information* const original = informationManager->getInformation(handle); + if (!original) + return result; + Information* primary = original; + if (!original->isPrimary()) + { + InformationManager* const manager = informationManager; + const unsigned int primaryHandle = original->getPrimaryObject(side); + primary = manager->getInformation(primaryHandle); + } + IPIUnit* unit = primary->getUnit(); + if (!unit) + return result; + if (unit->isOccupied()) + { + const unsigned int occupierHandle = unit->getOccupier(side); + Information* const occupier = informationManager->getInformation(occupierHandle); + if (occupier && occupier->getSide() == side) + { + const int playerId = unit->getOccupyingPlayerId(side); + SquadMember* const occupyingMember = squads->getSquadMember(playerId, side); + if (!occupyingMember) + return 0; + const int ownPlayerId = member->getPlayerId(); + if (ownPlayerId != occupyingMember->getPlayerId()) + { + const int ownSquadId = member->getSquadId(); + return ownSquadId == occupyingMember->getSquadId() ? 1 : 0; + } + } + } + else if (original->isBooked()) + { + const int playerId = original->getBookingPlayerId(); + SquadMember* const bookingMember = squads->getSquadMember(playerId, side); + if (bookingMember) + { + const int ownSquadId = member->getSquadId(); + return ownSquadId == bookingMember->getSquadId() ? 1 : 0; + } + } + + int iterator; + InformationManager* manager = informationManager; + const unsigned int firstHandle = primary->getFirstSecondaryObject(iterator, side); + Information* secondary = manager->getInformation(firstHandle); + while (secondary && result != 1) + { + unit = secondary->getUnit(); + if (unit && unit->isOccupied()) + { + const unsigned int occupierHandle = unit->getOccupier(side); + Information* const occupier = informationManager->getInformation(occupierHandle); + if (occupier && occupier->getSide() == side) + { + const int playerId = unit->getOccupyingPlayerId(side); + SquadMember* const occupyingMember = squads->getSquadMember(playerId, side); + if (!occupyingMember) + result = 0; + else + { + const int ownPlayerId = member->getPlayerId(); + if (ownPlayerId != occupyingMember->getPlayerId()) + { + const int ownSquadId = member->getSquadId(); + result = ownSquadId == occupyingMember->getSquadId() ? 1 : 0; + } + } + } + } + else if (secondary->isBooked()) + { + const int playerId = secondary->getBookingPlayerId(); + SquadMember* const bookingMember = squads->getSquadMember(playerId, side); + if (bookingMember) + { + const int ownSquadId = member->getSquadId(); + result = ownSquadId == bookingMember->getSquadId() ? 1 : 0; + } + } + manager = informationManager; + const unsigned int nextHandle = primary->getSecondaryObject(iterator, side); + secondary = manager->getInformation(nextHandle); + } + return result; +} + } } } diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/VehicleOccupancy.h b/Code/BF2/AI/AIDLL/AI/AIUtils/VehicleOccupancy.h index 2cf7d859f..a06f4045a 100644 --- a/Code/BF2/AI/AIDLL/AI/AIUtils/VehicleOccupancy.h +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/VehicleOccupancy.h @@ -6,8 +6,14 @@ namespace dice { namespace hfe { namespace ai { +class SquadMember; + // Parameter types/namespace from the ELF mangled name; Boolean materialized in both ports. bool vehicleOccupied(unsigned int handle, int side); +// Returns 1 for another member of the same squad, 0 for another squad or an unassigned +// occupier, and -1 when no qualifying occupation or booking was found. +int vehicleOccupiedBySquadMember(unsigned int handle, SquadMember* member, int side); + } } } #endif diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoManager.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/WeaponInfoManager.cpp similarity index 94% rename from Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoManager.cpp rename to Code/BF2/AI/AIDLL/AI/AIUtils/WeaponInfoManager.cpp index ab4216158..9cbaac07a 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/WeaponInfoManager.cpp @@ -1,8 +1,8 @@ -// [INFERRED] Source placement. +// Source placement: AIDLL_r.dll __FILE__ "Code\BF2\AI\AIDLL\AI\AIUtils\WeaponInfoManager.cpp" (0x1007D910). #include "WeaponInfoManager.h" -#include "../AIUtils/checkPointer.h" +#include "checkPointer.h" namespace dice { namespace hfe { diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoManager.h b/Code/BF2/AI/AIDLL/AI/AIUtils/WeaponInfoManager.h similarity index 92% rename from Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoManager.h rename to Code/BF2/AI/AIDLL/AI/AIUtils/WeaponInfoManager.h index d28de4b32..a4ddd521f 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoManager.h +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/WeaponInfoManager.h @@ -1,6 +1,6 @@ // Handle pool for weapon information. The singleton keeps the first instance. // setInformation and changeInformation perform the same guarded store; only changeInformation returns success. -// [INFERRED] Source placement. +// Header placement [INFERRED]: beside its .cpp, whose path AIDLL_r.dll confirms (AIUtils/WeaponInfoManager.cpp). #ifndef AI_AIDLL_AI_AIKNOWLEDGE_WEAPONINFOMANAGER_H #define AI_AIDLL_AI_AIKNOWLEDGE_WEAPONINFOMANAGER_H diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPManager.cpp b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPManager.cpp index 651742134..2dc4cdd36 100644 --- a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPManager.cpp @@ -1,12 +1,30 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining DPManager operations. - #include "DPManager.h" +// 's ios_base::Init object is the static initialisation and teardown of DPManager.cpp +// (ELF 0x3797D0, __tcf_0 0x379830, _GLOBAL__I 0x379860). The four interface constructors below +// were separate TUs in retail (file symbols IDPAIObjectCreator.cpp, IDPDynamicCreator.cpp, +// IDPManager.cpp, IDPStaticCreator.cpp), each with the same Init object: 0x381640/0x3816A0/ +// 0x3816D0, 0x3819F0/0x381A50/0x381A80, 0x381DA0/0x381E00/0x381E30, 0x382150/0x3821B0/0x3821E0. +// [INFERRED] keeping them in this TU. +#include + #include #include "../../../../Core/ClassManager.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/DebugRenderer.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AIMain.h" #include "../Main/CommonSingletonServer.h" #include "../Main/AIDllFrontier.h" +#include "../AIUtils/DebugRendering/DPDynamicPrimitives.h" +#include "DPStatic2dText.h" +#include "DPStatic3dText.h" +#include "DPStaticCircle.h" +#include "DPStaticLine.h" +#include "DPStaticMesh.h" +#include "DPStaticPolygon.h" +#include "DPStaticTriangle.h" namespace dice { namespace hfe { @@ -82,264 +100,693 @@ DPManager::~DPManager() { } -int DPManager::deleteCircle(DrawPrimitive *&) +// The delete*, get*Attributes and set*Attributes slots share one shape: the handle is looked up in +// that kind's map with find(); an unknown handle answers 0 (or does nothing in the void slots). + +// ELF 0x374260. A known handle deletes the value through its deleting destructor (null-tested), +// erases the node, nulls the caller's handle and answers 1. +int DPManager::deleteCircle(DrawPrimitive *& primitive) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::deleteCircle"); + std::map::iterator found = m_circles.find(primitive); + if (found == m_circles.end()) + return 0; + delete found->second; + m_circles.erase(found); + primitive = 0; + return 1; } -int DPManager::getCircleAttributes(DrawPrimitive *, float &, unsigned int &, Vec3 &, float &, Vec3 &, bool &, int &) +// ELF 0x374320. +int DPManager::getCircleAttributes(DrawPrimitive * primitive, float & lifeTime, unsigned int & colour, + Vec3 & position, float & radius, Vec3 & normal, bool & filled, + int & segments) const { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::getCircleAttributes"); + std::map::const_iterator found = m_circles.find(primitive); + if (found == m_circles.end()) + return 0; + found->second->getAttributes(lifeTime, colour, position, radius, normal, filled, segments); + return 1; } -int DPManager::setCircleAttributes(DrawPrimitive *, float, unsigned int, const Vec3&, float, const Vec3&, bool, int) +// ELF 0x3743C0. DPStaticCircle::setAttributes takes the position by value; the copy is made here. +int DPManager::setCircleAttributes(DrawPrimitive * primitive, float lifeTime, unsigned int colour, + const Vec3& position, float radius, const Vec3& normal, + bool filled, int segments) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::setCircleAttributes"); + std::map::iterator found = m_circles.find(primitive); + if (found == m_circles.end()) + return 0; + found->second->setAttributes(lifeTime, colour, position, radius, normal, filled, segments); + return 1; } -int DPManager::deleteLine(DrawPrimitive *&) +// ELF 0x374480. +int DPManager::deleteLine(DrawPrimitive *& primitive) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::deleteLine"); + std::map::iterator found = m_lines.find(primitive); + if (found == m_lines.end()) + return 0; + delete found->second; + m_lines.erase(found); + primitive = 0; + return 1; } -int DPManager::getLineAttributes(DrawPrimitive *, float &, unsigned int &, std::vector &, float &) +// ELF 0x374540. +int DPManager::getLineAttributes(DrawPrimitive * primitive, float & lifeTime, unsigned int & colour, + std::vector & points, float & width) const { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::getLineAttributes"); + std::map::const_iterator found = m_lines.find(primitive); + if (found == m_lines.end()) + return 0; + found->second->getAttributes(lifeTime, colour, points, width); + return 1; } -int DPManager::setLineAttributes(DrawPrimitive *, float, unsigned int, const std::vector&, float) +// ELF 0x3745C0. DPStaticLine::setAttributes takes references, so the by-value arguments are passed +// by address. +int DPManager::setLineAttributes(DrawPrimitive * primitive, float lifeTime, unsigned int colour, + const std::vector& points, float width) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::setLineAttributes"); + std::map::iterator found = m_lines.find(primitive); + if (found == m_lines.end()) + return 0; + found->second->setAttributes(lifeTime, colour, points, width); + return 1; } -int DPManager::delete2dText(DrawPrimitive *&) +// ELF 0x374640. +int DPManager::delete2dText(DrawPrimitive *& primitive) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::delete2dText"); + std::map::iterator found = m_text2d.find(primitive); + if (found == m_text2d.end()) + return 0; + delete found->second; + m_text2d.erase(found); + primitive = 0; + return 1; } -int DPManager::get2dTextAttributes(DrawPrimitive *, float &, unsigned int &, Vec2 &, std::vector &, int &, AITextAlignmentX &, AITextAlignmentY &) +// ELF 0x374700. +int DPManager::get2dTextAttributes(DrawPrimitive * primitive, float & lifeTime, unsigned int & colour, + Vec2 & position, std::vector & lines, int & size, + AITextAlignmentX & alignX, AITextAlignmentY & alignY) const { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::get2dTextAttributes"); + std::map::const_iterator found = m_text2d.find(primitive); + if (found == m_text2d.end()) + return 0; + found->second->getAttributes(lifeTime, colour, position, lines, size, alignX, alignY); + return 1; } -int DPManager::set2dTextAttributes(DrawPrimitive *, float, unsigned int, const Vec2&, const std::vector&, int, AITextAlignmentX, AITextAlignmentY) +// ELF 0x3747A0. +int DPManager::set2dTextAttributes(DrawPrimitive * primitive, float lifeTime, unsigned int colour, + const Vec2& position, const std::vector& lines, + int size, AITextAlignmentX alignX, AITextAlignmentY alignY) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::set2dTextAttributes"); + std::map::iterator found = m_text2d.find(primitive); + if (found == m_text2d.end()) + return 0; + found->second->setAttributes(lifeTime, colour, position, lines, size, alignX, alignY); + return 1; } -int DPManager::delete3dText(DrawPrimitive *&) +// ELF 0x374840. +int DPManager::delete3dText(DrawPrimitive *& primitive) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::delete3dText"); + std::map::iterator found = m_text3d.find(primitive); + if (found == m_text3d.end()) + return 0; + delete found->second; + m_text3d.erase(found); + primitive = 0; + return 1; } -int DPManager::get3dTextAttributes(DrawPrimitive *, float &, unsigned int &, Vec3 &, std::vector &, int &, AITextAlignmentX &, AITextAlignmentY &) +// ELF 0x374900. +int DPManager::get3dTextAttributes(DrawPrimitive * primitive, float & lifeTime, unsigned int & colour, + Vec3 & position, std::vector & lines, int & size, + AITextAlignmentX & alignX, AITextAlignmentY & alignY) const { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::get3dTextAttributes"); + std::map::const_iterator found = m_text3d.find(primitive); + if (found == m_text3d.end()) + return 0; + found->second->getAttributes(lifeTime, colour, position, lines, size, alignX, alignY); + return 1; } -int DPManager::set3dTextAttributes(DrawPrimitive *, float, unsigned int, const Vec3&, const std::vector&, int, AITextAlignmentX, AITextAlignmentY) +// ELF 0x3749A0. +int DPManager::set3dTextAttributes(DrawPrimitive * primitive, float lifeTime, unsigned int colour, + const Vec3& position, const std::vector& lines, + int size, AITextAlignmentX alignX, AITextAlignmentY alignY) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::set3dTextAttributes"); + std::map::iterator found = m_text3d.find(primitive); + if (found == m_text3d.end()) + return 0; + found->second->setAttributes(lifeTime, colour, position, lines, size, alignX, alignY); + return 1; } -int DPManager::deleteTriangle(DrawPrimitive *&) +// ELF 0x374A40. +int DPManager::deleteTriangle(DrawPrimitive *& primitive) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::deleteTriangle"); + std::map::iterator found = m_triangles.find(primitive); + if (found == m_triangles.end()) + return 0; + delete found->second; + m_triangles.erase(found); + primitive = 0; + return 1; } -int DPManager::getTriangleAttributes(DrawPrimitive *, float &, std::vector &, std::vector&, bool &) +// ELF 0x374B00. No result register is written on either path. +void DPManager::getTriangleAttributes(DrawPrimitive * primitive, float & lifeTime, + std::vector & vertices, + std::vector& colours, bool & filled) const { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::getTriangleAttributes"); + std::map::const_iterator found = m_triangles.find(primitive); + if (found != m_triangles.end()) + found->second->getAttributes(lifeTime, vertices, colours, filled); } -int DPManager::setTriangleAttributes(DrawPrimitive *, float &, const std::vector&, const std::vector&, bool &) +// ELF 0x374B80. +void DPManager::setTriangleAttributes(DrawPrimitive * primitive, float & lifeTime, + const std::vector& vertices, + const std::vector& colours, bool & filled) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::setTriangleAttributes"); + std::map::iterator found = m_triangles.find(primitive); + if (found != m_triangles.end()) + found->second->setAttributes(lifeTime, vertices, colours, filled); } -int DPManager::deletePolygon(DrawPrimitive *&) +// ELF 0x374C00. +int DPManager::deletePolygon(DrawPrimitive *& primitive) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::deletePolygon"); + std::map::iterator found = m_polygons.find(primitive); + if (found == m_polygons.end()) + return 0; + delete found->second; + m_polygons.erase(found); + primitive = 0; + return 1; } -int DPManager::getPolygonAttributes(DrawPrimitive *, float &, bool &) +// ELF 0x374CC0. +void DPManager::getPolygonAttributes(DrawPrimitive * primitive, float & lifeTime, bool & filled) const { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::getPolygonAttributes"); + std::map::const_iterator found = m_polygons.find(primitive); + if (found != m_polygons.end()) + found->second->getAttributes(lifeTime, filled); } -int DPManager::setPolygonAttributes(DrawPrimitive *, float &, bool &) +// ELF 0x374D30. +void DPManager::setPolygonAttributes(DrawPrimitive * primitive, float & lifeTime, bool & filled) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::setPolygonAttributes"); + std::map::iterator found = m_polygons.find(primitive); + if (found != m_polygons.end()) + found->second->setAttributes(lifeTime, filled); } -// Deletes a known mesh and clears the caller's handle. An unknown handle returns false. -// [FRONTIER] Known mesh deletion requires DPStaticMesh destruction. +// ELF 0x374DA0. Deletes a known mesh and clears the caller's handle; an unknown handle returns false. bool DPManager::deleteMesh(DrawPrimitive *& primitive) { - const std::map::iterator found = m_meshes.find(primitive); + std::map::iterator found = m_meshes.find(primitive); if (found == m_meshes.end()) return false; - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::deleteMesh [DPStaticMesh's destructor]"); + delete found->second; + m_meshes.erase(found); + primitive = 0; + return true; } -void DPManager::setTextGamma(float) +// ELF 0x374E60 +void DPManager::setTextGamma(float gamma) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::setTextGamma"); + m_textGamma = gamma; } -float DPManager::getTextGamma() +// ELF 0x374E70 +float DPManager::getTextGamma() const { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::getTextGamma"); + return m_textGamma; } -void DPManager::drawAll() -{ - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::drawAll"); -} +namespace { -void DPManager::nodrawUpdate() +// [CHOSEN, not recovered] Helper names for the loops drawAll, nodrawUpdate and deleteAll repeat +// once per map; each instantiation is inlined into its caller as the shipped bodies show. +// A primitive goes when it has expired, or (when drawing) when draw() answers false. +template +inline void drawMap(Map& primitives, double now, IDebugRenderer* renderer) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::nodrawUpdate"); + for (typename Map::iterator it = primitives.begin(); it != primitives.end();) + { + if (it->second->expired(now) || !it->second->draw(renderer)) + { + delete it->second; + primitives.erase(it++); + } + else + ++it; + } } -int DPManager::deleteAll() +template +inline void updateMap(Map& primitives, double now) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::deleteAll"); + for (typename Map::iterator it = primitives.begin(); it != primitives.end();) + { + if (it->second->expired(now)) + { + delete it->second; + primitives.erase(it++); + } + else + ++it; + } } -DPStaticCircle * DPManager::createStaticCircle(float, unsigned int, const Vec3&, float, const Vec3&, bool, int) +template +inline void deleteMap(Map& primitives) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createStaticCircle"); + for (typename Map::iterator it = primitives.begin(); it != primitives.end();) + { + delete it->second; + primitives.erase(it++); + } } -DPStaticLine * DPManager::createStaticLine(float, unsigned int, const Vec3&, const Vec3&, float) -{ - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createStaticLine"); -} +} // namespace -int DPManager::createStaticLine(float, unsigned int, const std::vector&, float) -{ - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createStaticLine"); -} - -DrawPrimitive * DPManager::createStatic2dText(float, unsigned int, const Vec2&, const std::string&, int, AITextAlignmentX, AITextAlignmentY) -{ - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createStatic2dText"); -} - -DrawPrimitive * DPManager::createStatic2dText(float, unsigned int, const Vec2&, const std::vector&, int, AITextAlignmentX, AITextAlignmentY) -{ - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createStatic2dText"); -} - -int DPManager::createStatic3dText(float, unsigned int, const Vec3&, const std::string&, int, AITextAlignmentX, AITextAlignmentY) -{ - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createStatic3dText"); -} - -int DPManager::createStatic3dText(float, unsigned int, const Vec3&, const std::vector&, int, AITextAlignmentX, AITextAlignmentY) -{ - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createStatic3dText"); -} - -int DPManager::createStaticTriangle(float, const std::vector&, const std::vector&, bool) -{ - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createStaticTriangle"); -} - -int DPManager::createStaticPolygon(float, const std::vector&, const std::vector&, bool) -{ - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createStaticPolygon"); -} - -DPStaticMesh * DPManager::createStaticMesh(float, unsigned int *, Vec3 *, unsigned int *, int, bool) -{ - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createStaticMesh"); -} - -int DPManager::createStaticMesh(float, unsigned int *, Polygon *, Vec3 *, unsigned int *, int, bool) +// ELF 0x374E80. Does nothing without an AI main. The renderer is read before the game time; the +// maps are walked circles, 2D text, 3D text, triangles, polygons, meshes, lines. +void DPManager::drawAll() { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createStaticMesh"); + if (!IAIMain::m_instance) + return; + IDebugRenderer* const renderer = static_cast(CommonSingletonServer::m_iDebugRenderer); + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + drawMap(m_circles, now, renderer); + drawMap(m_text2d, now, renderer); + drawMap(m_text3d, now, renderer); + drawMap(m_triangles, now, renderer); + drawMap(m_polygons, now, renderer); + drawMap(m_meshes, now, renderer); + drawMap(m_lines, now, renderer); } -int DPManager::testStatics(Mat4 &) +// ELF 0x375550. drawAll's expiry sweep without drawing, in the same map order. +void DPManager::nodrawUpdate() { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::testStatics"); + if (!IAIMain::m_instance) + return; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + updateMap(m_circles, now); + updateMap(m_text2d, now); + updateMap(m_text3d, now); + updateMap(m_triangles, now); + updateMap(m_polygons, now); + updateMap(m_meshes, now); + updateMap(m_lines, now); } -DPStaticCircle * DPManager::createDPDynamicCircle(float, unsigned int, const Vec3&, float, Bot *, DPDynamicTypes, const Vec3&, bool, int) +// ELF 0x375B00. Every map is drained in this order - circles, 2D text, 3D text, triangles, +// polygons, meshes, lines - deleting each value and erasing its node. +void DPManager::deleteAll() { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createDPDynamicCircle"); + deleteMap(m_circles); + deleteMap(m_text2d); + deleteMap(m_text3d); + deleteMap(m_triangles); + deleteMap(m_polygons); + deleteMap(m_meshes); + deleteMap(m_lines); } -DPStaticCircle * DPManager::createDPDynamicCircle(float, unsigned int, const Vec3&, float, unsigned int, DPDynamicTypes, const Vec3&, bool, int) -{ - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createDPDynamicCircle"); -} +// The create* slots share one shape: operator new of the concrete primitive, checkPointer (the +// AIUtils/checkPointer.h report on a null result), insert (primitive, primitive) into that kind's +// map, return the primitive. A null result is still inserted; the insert follows the report. -DPStaticLine * DPManager::createDynamicLine(float, unsigned int, const Vec3&, const Vec3&, float, Bot *, DPDynamicTypes) +// ELF 0x375F30 (sizeof 0x38). +DPStaticCircle * DPManager::createStaticCircle(float lifeTime, unsigned int colour, const Vec3& position, + float radius, const Vec3& normal, bool filled, int segments) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createDynamicLine"); + DPStaticCircle* const circle = checkPointer( + new DPStaticCircle(lifeTime, colour, position, radius, normal, filled, segments)); + m_circles.insert(std::make_pair(circle, circle)); + return circle; } -DPStaticLine * DPManager::createDynamicLine(float, unsigned int, const Vec3&, const Vec3&, float, unsigned int, DPDynamicTypes) +// ELF 0x376100 (sizeof 0x24). +DPStaticLine * DPManager::createStaticLine(float lifeTime, unsigned int colour, const Vec3& start, + const Vec3& end, float width) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createDynamicLine"); + DPStaticLine* const line = checkPointer(new DPStaticLine(lifeTime, colour, start, end, width)); + m_lines.insert(std::make_pair(line, line)); + return line; } -int DPManager::createDynamicLine(float, unsigned int, const std::vector&, float, Bot *, DPDynamicTypes) +// ELF 0x3762B0 (sizeof 0x24). +DrawPrimitive* DPManager::createStaticLine(float lifeTime, unsigned int colour, + const std::vector& points, float width) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createDynamicLine"); + DPStaticLine* const line = checkPointer(new DPStaticLine(lifeTime, colour, points, width)); + m_lines.insert(std::make_pair(line, line)); + return line; } -int DPManager::createDynamicLine(float, unsigned int, const std::vector&, float, unsigned int, DPDynamicTypes) +// ELF 0x376450 (sizeof 0x34). +DrawPrimitive * DPManager::createStatic2dText(float lifeTime, unsigned int colour, const Vec2& position, + const std::string& text, int size, + AITextAlignmentX alignX, AITextAlignmentY alignY) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createDynamicLine"); + DPStatic2dText* const primitive = checkPointer( + new DPStatic2dText(lifeTime, colour, position, text, size, alignX, alignY)); + m_text2d.insert(std::make_pair(primitive, primitive)); + return primitive; } -int DPManager::createDynamic3dText(float, unsigned int, const Vec3&, const std::string&, Bot *, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) +// ELF 0x376610 (sizeof 0x34). +DrawPrimitive * DPManager::createStatic2dText(float lifeTime, unsigned int colour, const Vec2& position, + const std::vector& lines, int size, + AITextAlignmentX alignX, AITextAlignmentY alignY) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createDynamic3dText"); + DPStatic2dText* const primitive = checkPointer( + new DPStatic2dText(lifeTime, colour, position, lines, size, alignX, alignY)); + m_text2d.insert(std::make_pair(primitive, primitive)); + return primitive; } -int DPManager::createDynamic3dText(float, unsigned int, const Vec3&, const std::vector&, Bot *, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) +// ELF 0x3767D0 (sizeof 0x38). +DrawPrimitive* DPManager::createStatic3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::string& text, int size, + AITextAlignmentX alignX, AITextAlignmentY alignY) +{ + DPStatic3dText* const primitive = checkPointer( + new DPStatic3dText(lifeTime, colour, position, text, size, alignX, alignY)); + m_text3d.insert(std::make_pair(primitive, primitive)); + return primitive; +} + +// ELF 0x376990 (sizeof 0x38). +DrawPrimitive* DPManager::createStatic3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::vector& lines, int size, + AITextAlignmentX alignX, AITextAlignmentY alignY) +{ + DPStatic3dText* const primitive = checkPointer( + new DPStatic3dText(lifeTime, colour, position, lines, size, alignX, alignY)); + m_text3d.insert(std::make_pair(primitive, primitive)); + return primitive; +} + +// ELF 0x376B50 (sizeof 0x30). +DrawPrimitive* DPManager::createStaticTriangle(float lifeTime, const std::vector& vertices, + const std::vector& colours, bool filled) +{ + DPStaticTriangle* const primitive = checkPointer( + new DPStaticTriangle(lifeTime, vertices, colours, filled)); + m_triangles.insert(std::make_pair(primitive, primitive)); + return primitive; +} + +// ELF 0x376D00 (sizeof 0x30). +DrawPrimitive* DPManager::createStaticPolygon(float lifeTime, const std::vector& vertices, + const std::vector& colours, bool filled) +{ + DPStaticPolygon* const primitive = checkPointer( + new DPStaticPolygon(lifeTime, vertices, colours, filled)); + m_polygons.insert(std::make_pair(primitive, primitive)); + return primitive; +} + +// ELF 0x376EB0 (sizeof 0x2C). +DPStaticMesh * DPManager::createStaticMesh(float lifeTime, unsigned int * colours, Vec3 * vertices, + unsigned int * indices, int count, bool filled) +{ + DPStaticMesh* const mesh = checkPointer( + new DPStaticMesh(lifeTime, colours, vertices, indices, count, filled)); + m_meshes.insert(std::make_pair(mesh, mesh)); + return mesh; +} + +// ELF 0x377070 (sizeof 0x2C). +DPStaticMesh * DPManager::createStaticMesh(float lifeTime, unsigned int * colours, Polygon * polygons, + Vec3 * vertices, unsigned int * indices, int count, + bool filled) +{ + DPStaticMesh* const mesh = checkPointer( + new DPStaticMesh(lifeTime, colours, polygons, vertices, indices, count, filled)); + m_meshes.insert(std::make_pair(mesh, mesh)); + return mesh; +} + +// ELF 0x377240. A demo of every static primitive kind at `transform`'s position, a tenth of a +// second each: a filled and an outlined circle of radius 5 facing up, a small circle 10 units +// along the third row facing along it, a line along the third row, the same line shifted a +// quarter unit along the first row as a point list (its end point pushed twice, shipped), and +// 2D and 3D text in both the line-list and single-string forms. Every call goes through this +// object's own virtual creators. Nothing is returned: the ia-32 body leaves eax unset, so the +// slot is void [INFERRED]. +void DPManager::testStatics(Mat4& transform) +{ + const float lifeTime = 0.1f; + float size = 10.0f; + const float width = 0.05f; + const Vec3& position = *reinterpret_cast(&transform.m[12]); + + Vec3 normal = {0.0f, 1.0f, 0.0f}; + const float radius = size * 0.5f; + createStaticCircle(lifeTime, 0xFF00FF00u, position, radius, normal, true, 255); + createStaticCircle(lifeTime, 0xFF00FF00u, position, radius, normal, false, 5); + + normal.x = transform.m[8]; + normal.y = transform.m[9]; + normal.z = transform.m[10]; + Vec3 end; + end.x = normal.x * size + position.x; + end.y = normal.y * size + position.y; + end.z = normal.z * size + position.z; + createStaticCircle(lifeTime, 0xFF00FF00u, end, radius / 20.0f, normal, false, 255); + + Vec3 start = position; + end.x = size * transform.m[8] + position.x; + end.y = size * transform.m[9] + position.y; + end.z = size * transform.m[10] + position.z; + createStaticLine(lifeTime, 0xFFFF0000u, start, end, width); + + std::vector points; + const float shiftX = width * transform.m[0] * 5.0f; + const float shiftY = width * transform.m[1] * 5.0f; + const float shiftZ = width * transform.m[2] * 5.0f; + start.x = start.x + shiftX; + start.y = start.y + shiftY; + start.z = start.z + shiftZ; + end.x = shiftX + end.x; + end.y = shiftY + end.y; + end.z = shiftZ + end.z; + points.push_back(start); + points.push_back(end); + points.push_back(end); + createStaticLine(lifeTime, 0xFFFF0000u, points, width + width); + + std::vector lines2d; + lines2d.push_back(std::string("Static 2D Text Demo")); + lines2d.push_back(std::string("Line 2")); + Vec2 screenPosition = {10.0f, 10.0f}; + createStatic2dText(lifeTime, 0xFFFFFF00u, screenPosition, lines2d, 5, + static_cast(0), static_cast(1)); + screenPosition.x = 40.0f; + screenPosition.y = 10.0f; + createStatic2dText(lifeTime, 0xFFFFFF00u, screenPosition, std::string("PureString"), 5, + static_cast(0), static_cast(1)); + + std::vector lines3d; + lines3d.push_back(std::string("Static 3D Text Demo")); + lines3d.push_back(std::string("Line 2")); + createStatic3dText(lifeTime, 0xFFFF00FFu, position, lines3d, 5, + static_cast(0), static_cast(1)); + const std::string pureString("PureString"); + size = size * 0.2f; + Vec3 textPosition; + textPosition.x = position.x; + textPosition.y = size + position.y; + textPosition.z = position.z; + createStatic3dText(lifeTime, 0xFFFF00FFu, textPosition, pureString, 5, + static_cast(0), static_cast(1)); +} + +// The dynamic and AI-object creators follow the static shape and file their primitive in the map +// of the static base: circles, lines or 3D text. + +// ELF 0x377D00 (sizeof 0x44). +DPStaticCircle * DPManager::createDPDynamicCircle(float lifeTime, unsigned int colour, const Vec3& position, + float radius, Bot * bot, DPDynamicTypes type, + const Vec3& normal, bool filled, int segments) +{ + DPDynamicCircle* const circle = checkPointer(new DPDynamicCircle( + lifeTime, colour, position, radius, bot, type, normal, filled, segments)); + m_circles.insert(std::make_pair(circle, circle)); + return circle; +} + +// ELF 0x377EE0 (sizeof 0x44). +DPStaticCircle * DPManager::createDPDynamicCircle(float lifeTime, unsigned int colour, const Vec3& position, + float radius, unsigned int information, + DPDynamicTypes type, const Vec3& normal, bool filled, + int segments) +{ + DPDynamicCircle* const circle = checkPointer(new DPDynamicCircle( + lifeTime, colour, position, radius, information, type, normal, filled, segments)); + m_circles.insert(std::make_pair(circle, circle)); + return circle; +} + +// ELF 0x3780C0 (sizeof 0x3C). +DPStaticLine * DPManager::createDynamicLine(float lifeTime, unsigned int colour, const Vec3& start, + const Vec3& end, float width, Bot * bot, DPDynamicTypes type) +{ + DPDynamicLine* const line = checkPointer( + new DPDynamicLine(lifeTime, colour, start, end, width, bot, type)); + m_lines.insert(std::make_pair(line, line)); + return line; +} + +// ELF 0x378280 (sizeof 0x3C). +DPStaticLine * DPManager::createDynamicLine(float lifeTime, unsigned int colour, const Vec3& start, + const Vec3& end, float width, unsigned int information, + DPDynamicTypes type) +{ + DPDynamicLine* const line = checkPointer( + new DPDynamicLine(lifeTime, colour, start, end, width, information, type)); + m_lines.insert(std::make_pair(line, line)); + return line; +} + +// ELF 0x378440 (sizeof 0x3C). +DrawPrimitive* DPManager::createDynamicLine(float lifeTime, unsigned int colour, + const std::vector& points, float width, Bot * bot, + DPDynamicTypes type) +{ + DPDynamicLine* const line = checkPointer( + new DPDynamicLine(lifeTime, colour, points, width, bot, type)); + m_lines.insert(std::make_pair(line, line)); + return line; +} + +// ELF 0x3785F0 (sizeof 0x3C). +DrawPrimitive* DPManager::createDynamicLine(float lifeTime, unsigned int colour, + const std::vector& points, float width, + unsigned int information, DPDynamicTypes type) +{ + DPDynamicLine* const line = checkPointer( + new DPDynamicLine(lifeTime, colour, points, width, information, type)); + m_lines.insert(std::make_pair(line, line)); + return line; +} + +// ELF 0x3787A0 (sizeof 0x44). +DrawPrimitive* DPManager::createDynamic3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::string& text, Bot * bot, DPDynamicTypes type, + int size, AITextAlignmentX alignX, AITextAlignmentY alignY) +{ + DPDynamic3dText* const primitive = checkPointer(new DPDynamic3dText( + lifeTime, colour, position, text, bot, type, size, alignX, alignY)); + m_text3d.insert(std::make_pair(primitive, primitive)); + return primitive; +} + +// ELF 0x378970 (sizeof 0x44). +DrawPrimitive* DPManager::createDynamic3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::vector& lines, Bot * bot, + DPDynamicTypes type, int size, AITextAlignmentX alignX, + AITextAlignmentY alignY) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createDynamic3dText"); + DPDynamic3dText* const primitive = checkPointer(new DPDynamic3dText( + lifeTime, colour, position, lines, bot, type, size, alignX, alignY)); + m_text3d.insert(std::make_pair(primitive, primitive)); + return primitive; } -int DPManager::createDynamic3dText(float, unsigned int, const Vec3&, const std::string&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) +// ELF 0x378B40 (sizeof 0x44). +DrawPrimitive* DPManager::createDynamic3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::string& text, unsigned int information, + DPDynamicTypes type, int size, AITextAlignmentX alignX, + AITextAlignmentY alignY) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createDynamic3dText"); + DPDynamic3dText* const primitive = checkPointer(new DPDynamic3dText( + lifeTime, colour, position, text, information, type, size, alignX, alignY)); + m_text3d.insert(std::make_pair(primitive, primitive)); + return primitive; } -int DPManager::createDynamic3dText(float, unsigned int, const Vec3&, const std::vector&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) +// ELF 0x378D10 (sizeof 0x44). +DrawPrimitive* DPManager::createDynamic3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::vector& lines, + unsigned int information, DPDynamicTypes type, int size, + AITextAlignmentX alignX, AITextAlignmentY alignY) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createDynamic3dText"); + DPDynamic3dText* const primitive = checkPointer(new DPDynamic3dText( + lifeTime, colour, position, lines, information, type, size, alignX, alignY)); + m_text3d.insert(std::make_pair(primitive, primitive)); + return primitive; } -DPStaticCircle * DPManager::createDPAIObjectCircle(float, unsigned int, const Vec3&, float, unsigned int, DPDynamicTypes, const Vec3&, bool, int) +// ELF 0x378EE0 (sizeof 0x40). +DPStaticCircle * DPManager::createDPAIObjectCircle(float lifeTime, unsigned int colour, const Vec3& position, + float radius, unsigned int information, + DPDynamicTypes type, const Vec3& normal, bool filled, + int segments) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createDPAIObjectCircle"); + DPAIObjectCircle* const circle = checkPointer(new DPAIObjectCircle( + lifeTime, colour, position, radius, information, type, normal, filled, segments)); + m_circles.insert(std::make_pair(circle, circle)); + return circle; } -DPStaticLine * DPManager::createAIObjectLine(float, unsigned int, const Vec3&, const Vec3&, float, unsigned int, DPDynamicTypes) +// ELF 0x3790C0 (sizeof 0x38). +DPStaticLine * DPManager::createAIObjectLine(float lifeTime, unsigned int colour, const Vec3& start, + const Vec3& end, float width, unsigned int information, + DPDynamicTypes type) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createAIObjectLine"); + DPAIObjectLine* const line = checkPointer( + new DPAIObjectLine(lifeTime, colour, start, end, width, information, type)); + m_lines.insert(std::make_pair(line, line)); + return line; } -int DPManager::createAIObjectLine(float, unsigned int, const std::vector&, float, unsigned int, DPDynamicTypes) +// ELF 0x379280 (sizeof 0x38). +DrawPrimitive* DPManager::createAIObjectLine(float lifeTime, unsigned int colour, + const std::vector& points, float width, + unsigned int information, DPDynamicTypes type) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createAIObjectLine"); + DPAIObjectLine* const line = checkPointer( + new DPAIObjectLine(lifeTime, colour, points, width, information, type)); + m_lines.insert(std::make_pair(line, line)); + return line; } -int DPManager::createAIObject3dText(float, unsigned int, const Vec3&, const std::string&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) +// ELF 0x379430 (sizeof 0x44). +DrawPrimitive* DPManager::createAIObject3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::string& text, unsigned int information, + DPDynamicTypes type, int size, AITextAlignmentX alignX, + AITextAlignmentY alignY) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createAIObject3dText"); + DPAIObject3dText* const primitive = checkPointer(new DPAIObject3dText( + lifeTime, colour, position, text, information, type, size, alignX, alignY)); + m_text3d.insert(std::make_pair(primitive, primitive)); + return primitive; } -int DPManager::createAIObject3dText(float, unsigned int, const Vec3&, const std::vector&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) +// ELF 0x379600 (sizeof 0x44). +DrawPrimitive* DPManager::createAIObject3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::vector& lines, + unsigned int information, DPDynamicTypes type, int size, + AITextAlignmentX alignX, AITextAlignmentY alignY) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createAIObject3dText"); + DPAIObject3dText* const primitive = checkPointer(new DPAIObject3dText( + lifeTime, colour, position, lines, information, type, size, alignX, alignY)); + m_text3d.insert(std::make_pair(primitive, primitive)); + return primitive; } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPManager.h b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPManager.h index 0a8a9ccaa..b5161bd10 100644 --- a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPManager.h +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPManager.h @@ -18,6 +18,11 @@ namespace dice { namespace hfe { namespace ai { +class DPStatic2dText; +class DPStatic3dText; +class DPStaticTriangle; +class DPStaticPolygon; + // Draw-manager interface. Registration guards the roster static, which may remain // stale until updateStaticMethods refreshes it. class IDPManager @@ -26,30 +31,30 @@ class IDPManager IDPManager(); virtual ~IDPManager(); virtual int deleteCircle(DrawPrimitive *&) = 0; - virtual int getCircleAttributes(DrawPrimitive *, float &, unsigned int &, Vec3 &, float &, Vec3 &, bool &, int &) = 0; + virtual int getCircleAttributes(DrawPrimitive *, float &, unsigned int &, Vec3 &, float &, Vec3 &, bool &, int &) const = 0; virtual int setCircleAttributes(DrawPrimitive *, float, unsigned int, const Vec3&, float, const Vec3&, bool, int) = 0; virtual int deleteLine(DrawPrimitive *&) = 0; - virtual int getLineAttributes(DrawPrimitive *, float &, unsigned int &, std::vector &, float &) = 0; + virtual int getLineAttributes(DrawPrimitive *, float &, unsigned int &, std::vector &, float &) const = 0; virtual int setLineAttributes(DrawPrimitive *, float, unsigned int, const std::vector&, float) = 0; virtual int delete2dText(DrawPrimitive *&) = 0; - virtual int get2dTextAttributes(DrawPrimitive *, float &, unsigned int &, Vec2 &, std::vector &, int &, AITextAlignmentX &, AITextAlignmentY &) = 0; + virtual int get2dTextAttributes(DrawPrimitive *, float &, unsigned int &, Vec2 &, std::vector &, int &, AITextAlignmentX &, AITextAlignmentY &) const = 0; virtual int set2dTextAttributes(DrawPrimitive *, float, unsigned int, const Vec2&, const std::vector&, int, AITextAlignmentX, AITextAlignmentY) = 0; virtual int delete3dText(DrawPrimitive *&) = 0; - virtual int get3dTextAttributes(DrawPrimitive *, float &, unsigned int &, Vec3 &, std::vector &, int &, AITextAlignmentX &, AITextAlignmentY &) = 0; + virtual int get3dTextAttributes(DrawPrimitive *, float &, unsigned int &, Vec3 &, std::vector &, int &, AITextAlignmentX &, AITextAlignmentY &) const = 0; virtual int set3dTextAttributes(DrawPrimitive *, float, unsigned int, const Vec3&, const std::vector&, int, AITextAlignmentX, AITextAlignmentY) = 0; virtual int deleteTriangle(DrawPrimitive *&) = 0; - virtual int getTriangleAttributes(DrawPrimitive *, float &, std::vector &, std::vector&, bool &) = 0; - virtual int setTriangleAttributes(DrawPrimitive *, float &, const std::vector&, const std::vector&, bool &) = 0; + virtual void getTriangleAttributes(DrawPrimitive *, float &, std::vector &, std::vector&, bool &) const = 0; + virtual void setTriangleAttributes(DrawPrimitive *, float &, const std::vector&, const std::vector&, bool &) = 0; virtual int deletePolygon(DrawPrimitive *&) = 0; - virtual int getPolygonAttributes(DrawPrimitive *, float &, bool &) = 0; - virtual int setPolygonAttributes(DrawPrimitive *, float &, bool &) = 0; + virtual void getPolygonAttributes(DrawPrimitive *, float &, bool &) const = 0; + virtual void setPolygonAttributes(DrawPrimitive *, float &, bool &) = 0; // bool virtual bool deleteMesh(DrawPrimitive *&) = 0; virtual void setTextGamma(float) = 0; - virtual float getTextGamma() = 0; + virtual float getTextGamma() const = 0; virtual void drawAll() = 0; virtual void nodrawUpdate() = 0; - virtual int deleteAll() = 0; + virtual void deleteAll() = 0; }; // IDPStaticCreator - 14 vtable slots. @@ -61,16 +66,19 @@ class IDPStaticCreator virtual ~IDPStaticCreator(); virtual DPStaticCircle * createStaticCircle(float, unsigned int, const Vec3&, float, const Vec3&, bool, int) = 0; virtual DPStaticLine * createStaticLine(float, unsigned int, const Vec3&, const Vec3&, float) = 0; - virtual int createStaticLine(float, unsigned int, const std::vector&, float) = 0; + virtual DrawPrimitive* createStaticLine(float, unsigned int, const std::vector&, float) = 0; virtual DrawPrimitive * createStatic2dText(float, unsigned int, const Vec2&, const std::string&, int, AITextAlignmentX, AITextAlignmentY) = 0; virtual DrawPrimitive * createStatic2dText(float, unsigned int, const Vec2&, const std::vector&, int, AITextAlignmentX, AITextAlignmentY) = 0; - virtual int createStatic3dText(float, unsigned int, const Vec3&, const std::string&, int, AITextAlignmentX, AITextAlignmentY) = 0; - virtual int createStatic3dText(float, unsigned int, const Vec3&, const std::vector&, int, AITextAlignmentX, AITextAlignmentY) = 0; - virtual int createStaticTriangle(float, const std::vector&, const std::vector&, bool) = 0; - virtual int createStaticPolygon(float, const std::vector&, const std::vector&, bool) = 0; + // ELF 0x3767D0 returns the allocated text pointer; QuadTreeManager stores the handle. + virtual DrawPrimitive* createStatic3dText(float, unsigned int, const Vec3&, const std::string&, int, AITextAlignmentX, AITextAlignmentY) = 0; + virtual DrawPrimitive* createStatic3dText(float, unsigned int, const Vec3&, const std::vector&, int, AITextAlignmentX, AITextAlignmentY) = 0; + virtual DrawPrimitive* createStaticTriangle(float, const std::vector&, const std::vector&, bool) = 0; + virtual DrawPrimitive* createStaticPolygon(float, const std::vector&, const std::vector&, bool) = 0; virtual DPStaticMesh * createStaticMesh(float, unsigned int *, Vec3 *, unsigned int *, int, bool) = 0; - virtual int createStaticMesh(float, unsigned int *, Polygon *, Vec3 *, unsigned int *, int, bool) = 0; - virtual int testStatics(Mat4 &) = 0; + // Returns the new DPStaticMesh (DPManager::createStaticMesh 0x377070; QuadTree::draw stores it). + virtual DPStaticMesh * createStaticMesh(float, unsigned int *, Polygon *, Vec3 *, unsigned int *, int, bool) = 0; + // void [INFERRED]: no caller exists and the ia-32 body (0x377240) leaves eax unset. + virtual void testStatics(Mat4 &) = 0; }; // IDPDynamicCreator - 12 vtable slots. @@ -84,12 +92,12 @@ class IDPDynamicCreator virtual DPStaticCircle * createDPDynamicCircle(float, unsigned int, const Vec3&, float, unsigned int, DPDynamicTypes, const Vec3&, bool, int) = 0; virtual DPStaticLine * createDynamicLine(float, unsigned int, const Vec3&, const Vec3&, float, Bot *, DPDynamicTypes) = 0; virtual DPStaticLine * createDynamicLine(float, unsigned int, const Vec3&, const Vec3&, float, unsigned int, DPDynamicTypes) = 0; - virtual int createDynamicLine(float, unsigned int, const std::vector&, float, Bot *, DPDynamicTypes) = 0; - virtual int createDynamicLine(float, unsigned int, const std::vector&, float, unsigned int, DPDynamicTypes) = 0; - virtual int createDynamic3dText(float, unsigned int, const Vec3&, const std::string&, Bot *, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) = 0; - virtual int createDynamic3dText(float, unsigned int, const Vec3&, const std::vector&, Bot *, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) = 0; - virtual int createDynamic3dText(float, unsigned int, const Vec3&, const std::string&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) = 0; - virtual int createDynamic3dText(float, unsigned int, const Vec3&, const std::vector&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) = 0; + virtual DrawPrimitive* createDynamicLine(float, unsigned int, const std::vector&, float, Bot *, DPDynamicTypes) = 0; + virtual DrawPrimitive* createDynamicLine(float, unsigned int, const std::vector&, float, unsigned int, DPDynamicTypes) = 0; + virtual DrawPrimitive* createDynamic3dText(float, unsigned int, const Vec3&, const std::string&, Bot *, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) = 0; + virtual DrawPrimitive* createDynamic3dText(float, unsigned int, const Vec3&, const std::vector&, Bot *, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) = 0; + virtual DrawPrimitive* createDynamic3dText(float, unsigned int, const Vec3&, const std::string&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) = 0; + virtual DrawPrimitive* createDynamic3dText(float, unsigned int, const Vec3&, const std::vector&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) = 0; }; // IDPAIObjectCreator - 7 vtable slots. @@ -101,9 +109,9 @@ class IDPAIObjectCreator virtual ~IDPAIObjectCreator(); virtual DPStaticCircle * createDPAIObjectCircle(float, unsigned int, const Vec3&, float, unsigned int, DPDynamicTypes, const Vec3&, bool, int) = 0; virtual DPStaticLine * createAIObjectLine(float, unsigned int, const Vec3&, const Vec3&, float, unsigned int, DPDynamicTypes) = 0; - virtual int createAIObjectLine(float, unsigned int, const std::vector&, float, unsigned int, DPDynamicTypes) = 0; - virtual int createAIObject3dText(float, unsigned int, const Vec3&, const std::string&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) = 0; - virtual int createAIObject3dText(float, unsigned int, const Vec3&, const std::vector&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) = 0; + virtual DrawPrimitive* createAIObjectLine(float, unsigned int, const std::vector&, float, unsigned int, DPDynamicTypes) = 0; + virtual DrawPrimitive* createAIObject3dText(float, unsigned int, const Vec3&, const std::string&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) = 0; + virtual DrawPrimitive* createAIObject3dText(float, unsigned int, const Vec3&, const std::vector&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) = 0; }; // DPManager - sizeof == 104, from BF2AI::init step 7. @@ -115,75 +123,76 @@ class DPManager : public IDPManager, public IDPStaticCreator, public IDPDynamicC // IDPManager virtual int deleteCircle(DrawPrimitive *&); - virtual int getCircleAttributes(DrawPrimitive *, float &, unsigned int &, Vec3 &, float &, Vec3 &, bool &, int &); + virtual int getCircleAttributes(DrawPrimitive *, float &, unsigned int &, Vec3 &, float &, Vec3 &, bool &, int &) const; virtual int setCircleAttributes(DrawPrimitive *, float, unsigned int, const Vec3&, float, const Vec3&, bool, int); virtual int deleteLine(DrawPrimitive *&); - virtual int getLineAttributes(DrawPrimitive *, float &, unsigned int &, std::vector &, float &); + virtual int getLineAttributes(DrawPrimitive *, float &, unsigned int &, std::vector &, float &) const; virtual int setLineAttributes(DrawPrimitive *, float, unsigned int, const std::vector&, float); virtual int delete2dText(DrawPrimitive *&); - virtual int get2dTextAttributes(DrawPrimitive *, float &, unsigned int &, Vec2 &, std::vector &, int &, AITextAlignmentX &, AITextAlignmentY &); + virtual int get2dTextAttributes(DrawPrimitive *, float &, unsigned int &, Vec2 &, std::vector &, int &, AITextAlignmentX &, AITextAlignmentY &) const; virtual int set2dTextAttributes(DrawPrimitive *, float, unsigned int, const Vec2&, const std::vector&, int, AITextAlignmentX, AITextAlignmentY); virtual int delete3dText(DrawPrimitive *&); - virtual int get3dTextAttributes(DrawPrimitive *, float &, unsigned int &, Vec3 &, std::vector &, int &, AITextAlignmentX &, AITextAlignmentY &); + virtual int get3dTextAttributes(DrawPrimitive *, float &, unsigned int &, Vec3 &, std::vector &, int &, AITextAlignmentX &, AITextAlignmentY &) const; virtual int set3dTextAttributes(DrawPrimitive *, float, unsigned int, const Vec3&, const std::vector&, int, AITextAlignmentX, AITextAlignmentY); virtual int deleteTriangle(DrawPrimitive *&); - virtual int getTriangleAttributes(DrawPrimitive *, float &, std::vector &, std::vector&, bool &); - virtual int setTriangleAttributes(DrawPrimitive *, float &, const std::vector&, const std::vector&, bool &); + virtual void getTriangleAttributes(DrawPrimitive *, float &, std::vector &, std::vector&, bool &) const; + virtual void setTriangleAttributes(DrawPrimitive *, float &, const std::vector&, const std::vector&, bool &); virtual int deletePolygon(DrawPrimitive *&); - virtual int getPolygonAttributes(DrawPrimitive *, float &, bool &); - virtual int setPolygonAttributes(DrawPrimitive *, float &, bool &); + virtual void getPolygonAttributes(DrawPrimitive *, float &, bool &) const; + virtual void setPolygonAttributes(DrawPrimitive *, float &, bool &); virtual bool deleteMesh(DrawPrimitive *&); virtual void setTextGamma(float); - virtual float getTextGamma(); + virtual float getTextGamma() const; virtual void drawAll(); virtual void nodrawUpdate(); - virtual int deleteAll(); + virtual void deleteAll(); // IDPStaticCreator virtual DPStaticCircle * createStaticCircle(float, unsigned int, const Vec3&, float, const Vec3&, bool, int); virtual DPStaticLine * createStaticLine(float, unsigned int, const Vec3&, const Vec3&, float); - virtual int createStaticLine(float, unsigned int, const std::vector&, float); + virtual DrawPrimitive* createStaticLine(float, unsigned int, const std::vector&, float); virtual DrawPrimitive * createStatic2dText(float, unsigned int, const Vec2&, const std::string&, int, AITextAlignmentX, AITextAlignmentY); virtual DrawPrimitive * createStatic2dText(float, unsigned int, const Vec2&, const std::vector&, int, AITextAlignmentX, AITextAlignmentY); - virtual int createStatic3dText(float, unsigned int, const Vec3&, const std::string&, int, AITextAlignmentX, AITextAlignmentY); - virtual int createStatic3dText(float, unsigned int, const Vec3&, const std::vector&, int, AITextAlignmentX, AITextAlignmentY); - virtual int createStaticTriangle(float, const std::vector&, const std::vector&, bool); - virtual int createStaticPolygon(float, const std::vector&, const std::vector&, bool); + virtual DrawPrimitive* createStatic3dText(float, unsigned int, const Vec3&, const std::string&, int, AITextAlignmentX, AITextAlignmentY); + virtual DrawPrimitive* createStatic3dText(float, unsigned int, const Vec3&, const std::vector&, int, AITextAlignmentX, AITextAlignmentY); + virtual DrawPrimitive* createStaticTriangle(float, const std::vector&, const std::vector&, bool); + virtual DrawPrimitive* createStaticPolygon(float, const std::vector&, const std::vector&, bool); virtual DPStaticMesh * createStaticMesh(float, unsigned int *, Vec3 *, unsigned int *, int, bool); - virtual int createStaticMesh(float, unsigned int *, Polygon *, Vec3 *, unsigned int *, int, bool); - virtual int testStatics(Mat4 &); + virtual DPStaticMesh * createStaticMesh(float, unsigned int *, Polygon *, Vec3 *, unsigned int *, int, bool); + virtual void testStatics(Mat4 &); // IDPDynamicCreator virtual DPStaticCircle * createDPDynamicCircle(float, unsigned int, const Vec3&, float, Bot *, DPDynamicTypes, const Vec3&, bool, int); virtual DPStaticCircle * createDPDynamicCircle(float, unsigned int, const Vec3&, float, unsigned int, DPDynamicTypes, const Vec3&, bool, int); virtual DPStaticLine * createDynamicLine(float, unsigned int, const Vec3&, const Vec3&, float, Bot *, DPDynamicTypes); virtual DPStaticLine * createDynamicLine(float, unsigned int, const Vec3&, const Vec3&, float, unsigned int, DPDynamicTypes); - virtual int createDynamicLine(float, unsigned int, const std::vector&, float, Bot *, DPDynamicTypes); - virtual int createDynamicLine(float, unsigned int, const std::vector&, float, unsigned int, DPDynamicTypes); - virtual int createDynamic3dText(float, unsigned int, const Vec3&, const std::string&, Bot *, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY); - virtual int createDynamic3dText(float, unsigned int, const Vec3&, const std::vector&, Bot *, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY); - virtual int createDynamic3dText(float, unsigned int, const Vec3&, const std::string&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY); - virtual int createDynamic3dText(float, unsigned int, const Vec3&, const std::vector&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY); + virtual DrawPrimitive* createDynamicLine(float, unsigned int, const std::vector&, float, Bot *, DPDynamicTypes); + virtual DrawPrimitive* createDynamicLine(float, unsigned int, const std::vector&, float, unsigned int, DPDynamicTypes); + virtual DrawPrimitive* createDynamic3dText(float, unsigned int, const Vec3&, const std::string&, Bot *, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY); + virtual DrawPrimitive* createDynamic3dText(float, unsigned int, const Vec3&, const std::vector&, Bot *, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY); + virtual DrawPrimitive* createDynamic3dText(float, unsigned int, const Vec3&, const std::string&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY); + virtual DrawPrimitive* createDynamic3dText(float, unsigned int, const Vec3&, const std::vector&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY); // IDPAIObjectCreator virtual DPStaticCircle * createDPAIObjectCircle(float, unsigned int, const Vec3&, float, unsigned int, DPDynamicTypes, const Vec3&, bool, int); virtual DPStaticLine * createAIObjectLine(float, unsigned int, const Vec3&, const Vec3&, float, unsigned int, DPDynamicTypes); - virtual int createAIObjectLine(float, unsigned int, const std::vector&, float, unsigned int, DPDynamicTypes); - virtual int createAIObject3dText(float, unsigned int, const Vec3&, const std::string&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY); - virtual int createAIObject3dText(float, unsigned int, const Vec3&, const std::vector&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY); + virtual DrawPrimitive* createAIObjectLine(float, unsigned int, const std::vector&, float, unsigned int, DPDynamicTypes); + virtual DrawPrimitive* createAIObject3dText(float, unsigned int, const Vec3&, const std::string&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY); + virtual DrawPrimitive* createAIObject3dText(float, unsigned int, const Vec3&, const std::vector&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY); private: - // Seven _Rb_trees, one per primitive kind, in the constructor's order. Element types are - // [FRONTIER] - the trees are only ever walked by the unwritten bodies. [UNRESOLVED] key type. - /* +0x10 */ std::set m_circles; - /* +0x1C */ std::set m_lines; - /* +0x28 */ std::set m_text2d; - /* +0x34 */ std::set m_text3d; - /* +0x40 */ std::set m_triangles; - /* +0x4C */ std::set m_polygons; - // Maps debug-primitive handles to their static meshes. The preceding six containers - // still have placeholder element types. - /* +0x58 */ std::map m_meshes; + // Seven maps from the caller's primitive handle to the owned static primitive, in the + // constructor's order. Key/value types are the ELF instantiations + // (_Rb_tree>); the offsets come from + // the delete* bodies: deleteLine +0x10, deleteCircle +0x1C, delete2dText +0x28, + // delete3dText +0x34, deleteTriangle +0x40, deletePolygon +0x4C, deleteMesh +0x58. + /* +0x10 */ std::map m_lines; + /* +0x1C */ std::map m_circles; + /* +0x28 */ std::map m_text2d; + /* +0x34 */ std::map m_text3d; + /* +0x40 */ std::map m_triangles; + /* +0x4C */ std::map m_polygons; + /* +0x58 */ std::map m_meshes; /* +0x64 */ float m_textGamma; // = 1.0f }; diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStatic2dText.cpp b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStatic2dText.cpp new file mode 100644 index 000000000..484d5a27c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStatic2dText.cpp @@ -0,0 +1,84 @@ +// Timed screen-space debug text. Evidence: libaidll.so (ia-32) 0x37B590..0x37BD6F. +// [INFERRED] Source placement. + +#include "DPStatic2dText.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x37BCC0, __tcf_0 0x37BD20, _GLOBAL__I 0x37BD50). +#include + +#include "../../../AIInterface/BFKnowledge/DebugRenderer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x37B590 (C2; C1 0x37B700). The line vector is built with the fill constructor, one copy of `text`. +DPStatic2dText::DPStatic2dText(float lifeTime, unsigned int colour, const Vec2& position, + const std::string& text, int size, AITextAlignmentX alignX, + AITextAlignmentY alignY) + : DrawPrimitive(lifeTime, colour) + , m_position(position) + , m_lines(1, text) + , m_size(size) + , m_alignX(alignX) + , m_alignY(alignY) +{ +} + +// ELF 0x37B7B0 (C2; C1 0x37B880). +DPStatic2dText::DPStatic2dText(float lifeTime, unsigned int colour, const Vec2& position, + const std::vector& lines, int size, + AITextAlignmentX alignX, AITextAlignmentY alignY) + : DrawPrimitive(lifeTime, colour) + , m_position(position) + , m_lines(lines) + , m_size(size) + , m_alignX(alignX) + , m_alignY(alignY) +{ +} + +// ELF 0x37B950 (D2; D1 0x37BA10, D0 0x37BAD0). +DPStatic2dText::~DPStatic2dText() +{ +} + +// ELF 0x37BC70. IDebugRenderer slot 6 (drawScreenText). +bool DPStatic2dText::draw(IDebugRenderer* renderer) +{ + renderer->drawScreenText(m_position, m_lines, m_size, m_colour, m_alignX, m_alignY); + return true; +} + +// ELF 0x37BB90. +void DPStatic2dText::getAttributes(float& lifeTime, unsigned int& colour, Vec2& position, + std::vector& lines, int& size, + AITextAlignmentX& alignX, AITextAlignmentY& alignY) const +{ + lifeTime = m_lifeTime; + colour = m_colour; + position = m_position; + lines = m_lines; + size = m_size; + alignX = m_alignX; + alignY = m_alignY; +} + +// ELF 0x37BC00. +void DPStatic2dText::setAttributes(float lifeTime, unsigned int colour, const Vec2& position, + const std::vector& lines, int size, + AITextAlignmentX alignX, AITextAlignmentY alignY) +{ + m_lifeTime = lifeTime; + m_colour = colour; + m_position = position; + m_lines = lines; + m_size = size; + m_alignX = alignX; + m_alignY = alignY; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStatic2dText.h b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStatic2dText.h new file mode 100644 index 000000000..1d8f17af5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStatic2dText.h @@ -0,0 +1,53 @@ +// A timed block of screen-space debug text. +// [INFERRED] Source placement. + +#ifndef AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATIC2DTEXT_H +#define AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATIC2DTEXT_H + +#include +#include + +#include "DrawPrimitive.h" +#include "../Main/AIDllTypes.h" + +namespace dice { +namespace hfe { +namespace ai { + +// sizeof == 0x34 on ia-32 (DPManager::createStatic2dText allocates 0x34). +class DPStatic2dText : public DrawPrimitive +{ +public: + // One line of text. + DPStatic2dText(float lifeTime, unsigned int colour, const Vec2& position, const std::string& text, int size, + AITextAlignmentX alignX, AITextAlignmentY alignY); + DPStatic2dText(float lifeTime, unsigned int colour, const Vec2& position, + const std::vector& lines, int size, AITextAlignmentX alignX, + AITextAlignmentY alignY); + virtual ~DPStatic2dText(); + + // Always draws and returns true. + virtual bool draw(IDebugRenderer* renderer); + + // Copies every attribute except the creation time. + void getAttributes(float& lifeTime, unsigned int& colour, Vec2& position, + std::vector& lines, int& size, AITextAlignmentX& alignX, + AITextAlignmentY& alignY) const; + // Replaces every attribute except the creation time. + void setAttributes(float lifeTime, unsigned int colour, const Vec2& position, + const std::vector& lines, int size, AITextAlignmentX alignX, + AITextAlignmentY alignY); + +protected: + /* +0x14 */ Vec2 m_position; + /* +0x1C */ std::vector m_lines; + /* +0x28 */ int m_size; + /* +0x2C */ AITextAlignmentX m_alignX; + /* +0x30 */ AITextAlignmentY m_alignY; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATIC2DTEXT_H diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStatic3dText.cpp b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStatic3dText.cpp new file mode 100644 index 000000000..2f834c060 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStatic3dText.cpp @@ -0,0 +1,84 @@ +// Timed world-space debug text. Evidence: libaidll.so (ia-32) 0x37C040..0x37C8DF. +// [INFERRED] Source placement. + +#include "DPStatic3dText.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x37C830, __tcf_0 0x37C890, _GLOBAL__I 0x37C8C0). +#include + +#include "../../../AIInterface/BFKnowledge/DebugRenderer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x37C040 (C2; C1 0x37C1C0). The line vector is built with the fill constructor, one copy of `text`. +DPStatic3dText::DPStatic3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::string& text, int size, AITextAlignmentX alignX, + AITextAlignmentY alignY) + : DrawPrimitive(lifeTime, colour) + , m_position(position) + , m_lines(1, text) + , m_size(size) + , m_alignX(alignX) + , m_alignY(alignY) +{ +} + +// ELF 0x37C2A0 (C2; C1 0x37C3A0). +DPStatic3dText::DPStatic3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::vector& lines, int size, + AITextAlignmentX alignX, AITextAlignmentY alignY) + : DrawPrimitive(lifeTime, colour) + , m_position(position) + , m_lines(lines) + , m_size(size) + , m_alignX(alignX) + , m_alignY(alignY) +{ +} + +// ELF 0x37C4A0 (D2; D1 0x37C560, D0 0x37C620). +DPStatic3dText::~DPStatic3dText() +{ +} + +// ELF 0x37C7E0. IDebugRenderer slot 7 (draw3dText). +bool DPStatic3dText::draw(IDebugRenderer* renderer) +{ + renderer->draw3dText(m_position, m_lines, m_size, m_colour, m_alignX, m_alignY); + return true; +} + +// ELF 0x37C6E0. +void DPStatic3dText::getAttributes(float& lifeTime, unsigned int& colour, Vec3& position, + std::vector& lines, int& size, + AITextAlignmentX& alignX, AITextAlignmentY& alignY) const +{ + lifeTime = m_lifeTime; + colour = m_colour; + position = m_position; + lines = m_lines; + size = m_size; + alignX = m_alignX; + alignY = m_alignY; +} + +// ELF 0x37C760. +void DPStatic3dText::setAttributes(float lifeTime, unsigned int colour, const Vec3& position, + const std::vector& lines, int size, + AITextAlignmentX alignX, AITextAlignmentY alignY) +{ + m_lifeTime = lifeTime; + m_colour = colour; + m_position = position; + m_lines = lines; + m_size = size; + m_alignX = alignX; + m_alignY = alignY; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStatic3dText.h b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStatic3dText.h new file mode 100644 index 000000000..6183a50b3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStatic3dText.h @@ -0,0 +1,53 @@ +// A timed block of world-space debug text. +// [INFERRED] Source placement. + +#ifndef AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATIC3DTEXT_H +#define AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATIC3DTEXT_H + +#include +#include + +#include "DrawPrimitive.h" +#include "../Main/AIDllTypes.h" + +namespace dice { +namespace hfe { +namespace ai { + +// sizeof == 0x38 on ia-32 (DPManager::createStatic3dText allocates 0x38). +class DPStatic3dText : public DrawPrimitive +{ +public: + // One line of text. + DPStatic3dText(float lifeTime, unsigned int colour, const Vec3& position, const std::string& text, int size, + AITextAlignmentX alignX, AITextAlignmentY alignY); + DPStatic3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::vector& lines, int size, AITextAlignmentX alignX, + AITextAlignmentY alignY); + virtual ~DPStatic3dText(); + + // Always draws and returns true. + virtual bool draw(IDebugRenderer* renderer); + + // Copies every attribute except the creation time. + void getAttributes(float& lifeTime, unsigned int& colour, Vec3& position, + std::vector& lines, int& size, AITextAlignmentX& alignX, + AITextAlignmentY& alignY) const; + // Replaces every attribute except the creation time. + void setAttributes(float lifeTime, unsigned int colour, const Vec3& position, + const std::vector& lines, int size, AITextAlignmentX alignX, + AITextAlignmentY alignY); + +protected: + /* +0x14 */ Vec3 m_position; + /* +0x20 */ std::vector m_lines; + /* +0x2C */ int m_size; + /* +0x30 */ AITextAlignmentX m_alignX; + /* +0x34 */ AITextAlignmentY m_alignY; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATIC3DTEXT_H diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticCircle.h b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticCircle.h new file mode 100644 index 000000000..2edbd887d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticCircle.h @@ -0,0 +1,45 @@ +// A timed debug circle in world space. +// [INFERRED] Source placement and header name (the TU is attested as DPStaticCirlce.cpp). + +#ifndef AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATICCIRCLE_H +#define AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATICCIRCLE_H + +#include "DrawPrimitive.h" +#include "../Main/AIDllTypes.h" + +namespace dice { +namespace hfe { +namespace ai { + +// sizeof == 0x38 (DPManager::createStaticCircle allocates 0x38). The renderer receives the normal +// as drawCircle's first vector and the position as its second. +class DPStaticCircle : public DrawPrimitive +{ +public: + DPStaticCircle(float lifeTime, unsigned int colour, const Vec3& position, float radius, + const Vec3& normal, bool filled, int segments); + virtual ~DPStaticCircle(); + + // Always draws and returns true. + virtual bool draw(IDebugRenderer* renderer); + + // Copies every attribute except the creation time. + void getAttributes(float& lifeTime, unsigned int& colour, Vec3& position, float& radius, + Vec3& normal, bool& filled, int& segments) const; + // Replaces every attribute except the creation time. + void setAttributes(float lifeTime, unsigned int colour, Vec3 position, float radius, + const Vec3& normal, bool filled, int segments); + +protected: + /* +0x14 */ Vec3 m_position; + /* +0x20 */ float m_radius; + /* +0x24 */ Vec3 m_normal; + /* +0x30 */ bool m_filled; + /* +0x34 */ int m_segments; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATICCIRCLE_H diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticCirlce.cpp b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticCirlce.cpp new file mode 100644 index 000000000..a3139586e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticCirlce.cpp @@ -0,0 +1,68 @@ +// Timed debug circle. Evidence: libaidll.so (ia-32) 0x37C8E0..0x37CCDF. The translation unit's +// file symbol is DPStaticCirlce.cpp (sic); the directory is [INFERRED]. + +#include "DPStaticCircle.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x37CC30, __tcf_0 0x37CC90, _GLOBAL__I 0x37CCC0). +#include + +#include "../../../AIInterface/BFKnowledge/DebugRenderer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x37C8E0 (C2; C1 0x37C990). +DPStaticCircle::DPStaticCircle(float lifeTime, unsigned int colour, const Vec3& position, + float radius, const Vec3& normal, bool filled, int segments) + : DrawPrimitive(lifeTime, colour) + , m_position(position) + , m_radius(radius) + , m_normal(normal) + , m_filled(filled) + , m_segments(segments) +{ +} + +// ELF 0x37CA40 (D2; D1 0x37CA80, D0 0x37CAC0). +DPStaticCircle::~DPStaticCircle() +{ +} + +// ELF 0x37CB00. IDebugRenderer slot 5 (drawCircle) takes the normal first. +bool DPStaticCircle::draw(IDebugRenderer* renderer) +{ + renderer->drawCircle(m_normal, m_position, m_radius, m_colour, m_filled, m_segments); + return true; +} + +// ELF 0x37CB50. +void DPStaticCircle::getAttributes(float& lifeTime, unsigned int& colour, Vec3& position, + float& radius, Vec3& normal, bool& filled, int& segments) const +{ + lifeTime = m_lifeTime; + colour = m_colour; + position = m_position; + radius = m_radius; + normal = m_normal; + filled = m_filled; + segments = m_segments; +} + +// ELF 0x37CBC0. +void DPStaticCircle::setAttributes(float lifeTime, unsigned int colour, Vec3 position, + float radius, const Vec3& normal, bool filled, int segments) +{ + m_lifeTime = lifeTime; + m_colour = colour; + m_position = position; + m_radius = radius; + m_normal = normal; + m_filled = filled; + m_segments = segments; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticLine.cpp b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticLine.cpp new file mode 100644 index 000000000..3337d97cc --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticLine.cpp @@ -0,0 +1,74 @@ +// Timed debug polyline. Evidence: libaidll.so (ia-32) 0x37CCE0..0x37D4BF. +// [INFERRED] Source placement. + +#include "DPStaticLine.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x37D410, __tcf_0 0x37D470, _GLOBAL__I 0x37D4A0). +#include + +#include "../../../AIInterface/BFKnowledge/DebugRenderer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x37CCE0 (C2; C1 0x37CDF0). Three push_backs: the start point, then the end point twice. +// shipped defect: the end point is stored twice, so the renderer receives a degenerate last segment. +DPStaticLine::DPStaticLine(float lifeTime, unsigned int colour, const Vec3& start, const Vec3& end, + float width) + : DrawPrimitive(lifeTime, colour) + , m_width(width) +{ + m_points.push_back(start); + m_points.push_back(end); + m_points.push_back(end); +} + +// ELF 0x37CF00 (C2; C1 0x37CFE0). +DPStaticLine::DPStaticLine(float lifeTime, unsigned int colour, const std::vector& points, + float width) + : DrawPrimitive(lifeTime, colour) + , m_points(points) + , m_width(width) +{ +} + +// ELF 0x37D0C0 (D2; D1 0x37D140, D0 0x37D1C0). +DPStaticLine::~DPStaticLine() +{ +} + +// ELF 0x37D240. IDebugRenderer slot 4 (drawLine). +bool DPStaticLine::draw(IDebugRenderer* renderer) +{ + renderer->drawLine(m_points, m_colour, m_width); + return true; +} + +// ELF 0x37D280. resize(0) then a range insert at the end, as the listing's erase/_M_fill_insert +// pair followed by _M_range_insert shows. +void DPStaticLine::getAttributes(float& lifeTime, unsigned int& colour, std::vector& points, + float& width) const +{ + lifeTime = m_lifeTime; + colour = m_colour; + width = m_width; + points.resize(0); + points.insert(points.end(), m_points.begin(), m_points.end()); +} + +// ELF 0x37D340. +void DPStaticLine::setAttributes(float& lifeTime, unsigned int& colour, + const std::vector& points, float& width) +{ + m_lifeTime = lifeTime; + m_colour = colour; + m_width = width; + m_points.resize(0); + m_points.insert(m_points.end(), points.begin(), points.end()); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticLine.h b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticLine.h new file mode 100644 index 000000000..c760a575b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticLine.h @@ -0,0 +1,42 @@ +// A timed debug polyline in world space. +// [INFERRED] Source placement. + +#ifndef AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATICLINE_H +#define AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATICLINE_H + +#include + +#include "DrawPrimitive.h" +#include "../Main/AIDllTypes.h" + +namespace dice { +namespace hfe { +namespace ai { + +// sizeof == 0x24 on ia-32 (DPManager::createStaticLine allocates 0x24). +class DPStaticLine : public DrawPrimitive +{ +public: + // A two-point line. The shipped constructor stores the end point twice (see the body). + DPStaticLine(float lifeTime, unsigned int colour, const Vec3& start, const Vec3& end, float width); + DPStaticLine(float lifeTime, unsigned int colour, const std::vector& points, float width); + virtual ~DPStaticLine(); + + // Always draws and returns true. + virtual bool draw(IDebugRenderer* renderer); + + // Copies lifetime, colour, points and width; `points` is replaced, not appended to. + void getAttributes(float& lifeTime, unsigned int& colour, std::vector& points, float& width) const; + // Replaces lifetime, colour, points and width; the creation time is kept. + void setAttributes(float& lifeTime, unsigned int& colour, const std::vector& points, float& width); + +protected: + /* +0x14 */ std::vector m_points; + /* +0x20 */ float m_width; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATICLINE_H diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticMesh.cpp b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticMesh.cpp new file mode 100644 index 000000000..ee6ac88b5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticMesh.cpp @@ -0,0 +1,82 @@ +// Timed debug mesh. Evidence: libaidll.so (ia-32) 0x37D850..0x37E61F. +// [INFERRED] Source placement. + +#include "DPStaticMesh.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x37E570, __tcf_0 0x37E5D0, _GLOBAL__I 0x37E600). +#include + +#include "../../../AIInterface/BFKnowledge/DebugRenderer.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AIRandom.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x37D850 (C2; C1 0x37DB20). The random base is drawn before the loop whether or not +// `colours` is given; the low-bit term is drawn per entry only on the null-`colours` path. +DPStaticMesh::DPStaticMesh(float lifeTime, unsigned int* colours, Vec3* vertices, + unsigned int* indices, int count, bool filled) + : DrawPrimitive(lifeTime, colours ? colours[0] : 0xFFFFFFFFu) + , m_vertices(vertices) + , m_indices(indices) + , m_count(count) + , m_filled(filled) +{ + m_colours = checkPointer(new unsigned int[m_count]); + m_ownsArrays = false; + const unsigned int base = AIRandom::m_instance->next() & 0xE0E0E0E0u; + for (int i = 0; i < m_count; ++i) + { + if (colours) + m_colours[i] = colours[i]; + else + m_colours[i] = (AIRandom::m_instance->next() & 0x1F1F1F1Fu) + base; + } +} + +// ELF 0x37DDF0 (C2; C1 0x37E0C0). Identical to the overload above apart from the ignored +// polygon pointer. +DPStaticMesh::DPStaticMesh(float lifeTime, unsigned int* colours, Polygon* /*polygons*/, + Vec3* vertices, unsigned int* indices, int count, bool filled) + : DrawPrimitive(lifeTime, colours ? colours[0] : 0xFFFFFFFFu) + , m_vertices(vertices) + , m_indices(indices) + , m_count(count) + , m_filled(filled) +{ + m_colours = checkPointer(new unsigned int[m_count]); + m_ownsArrays = false; + const unsigned int base = AIRandom::m_instance->next() & 0xE0E0E0E0u; + for (int i = 0; i < m_count; ++i) + { + if (colours) + m_colours[i] = colours[i]; + else + m_colours[i] = (AIRandom::m_instance->next() & 0x1F1F1F1Fu) + base; + } +} + +// ELF 0x37E390 (D2; D1 0x37E410, D0 0x37E490). +DPStaticMesh::~DPStaticMesh() +{ + delete[] m_colours; + if (m_ownsArrays) + { + delete[] m_vertices; + delete[] m_indices; + } +} + +// ELF 0x37E520. IDebugRenderer slot 9 (drawMesh). +bool DPStaticMesh::draw(IDebugRenderer* renderer) +{ + renderer->drawMesh(m_vertices, m_indices, m_count, m_colours, m_filled); + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticMesh.h b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticMesh.h new file mode 100644 index 000000000..1ff18c0c1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticMesh.h @@ -0,0 +1,45 @@ +// A timed debug mesh over caller-owned vertex and index arrays. +// [INFERRED] Source placement. + +#ifndef AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATICMESH_H +#define AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATICMESH_H + +#include "DrawPrimitive.h" +#include "../Main/AIDllTypes.h" + +namespace dice { +namespace hfe { +namespace ai { + +// sizeof == 0x2C on ia-32 (DPManager::createStaticMesh allocates 0x2C). +class DPStaticMesh : public DrawPrimitive +{ +public: + // Keeps `vertices` and `indices` by pointer (not owned) and copies `count` colours into an + // owned array. A null `colours` gives the primitive colour 0xFFFFFFFF and random per-entry + // colours: one high-bit base (& 0xE0E0E0E0) plus a fresh low-bit term (& 0x1F1F1F1F) each. + DPStaticMesh(float lifeTime, unsigned int* colours, Vec3* vertices, unsigned int* indices, + int count, bool filled); + // As above; the polygon pointer is accepted and ignored. + DPStaticMesh(float lifeTime, unsigned int* colours, Polygon* polygons, Vec3* vertices, + unsigned int* indices, int count, bool filled); + virtual ~DPStaticMesh(); + + // Always draws and returns true. + virtual bool draw(IDebugRenderer* renderer); + +protected: + /* +0x14 */ Vec3* m_vertices; + /* +0x18 */ unsigned int* m_indices; + /* +0x1C */ int m_count; + /* +0x20 */ bool m_filled; + /* +0x24 */ unsigned int* m_colours; + // [INFERRED] name. Always false here; when set, the destructor also frees the two arrays. + /* +0x28 */ bool m_ownsArrays; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATICMESH_H diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticPolygon.cpp b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticPolygon.cpp new file mode 100644 index 000000000..50277c094 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticPolygon.cpp @@ -0,0 +1,68 @@ +// Timed debug polygon. Evidence: libaidll.so (ia-32) 0x37E620..0x37F4CF. +// [INFERRED] Source placement. + +#include "DPStaticPolygon.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x37F420, __tcf_0 0x37F480, _GLOBAL__I 0x37F4B0). +#include + +#include "../../../AIInterface/BFKnowledge/DebugRenderer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x37E620 (C2; C1 0x37EAC0). Both outer vectors are resized to size - 2 (an unsigned count, +// so fewer than two vertices wraps), then each fan triangle receives v0, vi, vi+1 with its colours +// interleaved in that order. +DPStaticPolygon::DPStaticPolygon(float lifeTime, const std::vector& vertices, + const std::vector& colours, bool filled) + : DrawPrimitive(lifeTime, colours[0]) + , m_filled(filled) +{ + const unsigned int count = static_cast(vertices.size()); + m_triangles.resize(count - 2); + m_colours.resize(count - 2); + for (unsigned int i = 1; i < count - 1; ++i) + { + m_triangles[i - 1].push_back(vertices[0]); + m_colours[i - 1].push_back(colours[0]); + m_triangles[i - 1].push_back(vertices[i]); + m_colours[i - 1].push_back(colours[i]); + m_triangles[i - 1].push_back(vertices[i + 1]); + m_colours[i - 1].push_back(colours[i + 1]); + } +} + +// ELF 0x37EF60 (D2; D1 0x37F0B0, D0 0x37F200). +DPStaticPolygon::~DPStaticPolygon() +{ +} + +// ELF 0x37F350. The triangle count is read once before the loop. +bool DPStaticPolygon::draw(IDebugRenderer* renderer) +{ + const unsigned int count = static_cast(m_triangles.size()); + for (unsigned int i = 0; i < count; ++i) + renderer->drawTriangle(m_triangles[i], m_colours[i], m_filled); + return true; +} + +// ELF 0x37F3E0. +void DPStaticPolygon::getAttributes(float& lifeTime, bool& filled) const +{ + lifeTime = m_lifeTime; + filled = m_filled; +} + +// ELF 0x37F400. +void DPStaticPolygon::setAttributes(float& lifeTime, bool& filled) +{ + m_lifeTime = lifeTime; + m_filled = filled; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticPolygon.h b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticPolygon.h new file mode 100644 index 000000000..61420e4d6 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticPolygon.h @@ -0,0 +1,43 @@ +// A timed debug polygon, fan-triangulated at construction. +// [INFERRED] Source placement. + +#ifndef AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATICPOLYGON_H +#define AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATICPOLYGON_H + +#include + +#include "DrawPrimitive.h" +#include "../Main/AIDllTypes.h" + +namespace dice { +namespace hfe { +namespace ai { + +// sizeof == 0x30 on ia-32 (DPManager::createStaticPolygon allocates 0x30). +class DPStaticPolygon : public DrawPrimitive +{ +public: + // Splits the outline into the fan (v0, vi, vi+1); `colours` runs parallel to `vertices` and + // its first entry becomes the primitive colour. Needs at least one vertex and one colour. + DPStaticPolygon(float lifeTime, const std::vector& vertices, + const std::vector& colours, bool filled); + virtual ~DPStaticPolygon(); + + // Draws every fan triangle and returns true. + virtual bool draw(IDebugRenderer* renderer); + + void getAttributes(float& lifeTime, bool& filled) const; + // Replaces the lifetime and the fill flag; the triangles are kept. + void setAttributes(float& lifeTime, bool& filled); + +protected: + /* +0x14 */ std::vector > m_triangles; + /* +0x20 */ std::vector > m_colours; + /* +0x2C */ bool m_filled; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATICPOLYGON_H diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticTriangle.cpp b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticTriangle.cpp new file mode 100644 index 000000000..6f13741c4 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticTriangle.cpp @@ -0,0 +1,64 @@ +// Timed debug triangles. Evidence: libaidll.so (ia-32) 0x380730..0x380F8F. +// [INFERRED] Source placement. + +#include "DPStaticTriangle.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x380EE0, __tcf_0 0x380F40, _GLOBAL__I 0x380F70). +#include + +#include "../../../AIInterface/BFKnowledge/DebugRenderer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x380730 (C2; C1 0x3808A0). Reads colours[0] unchecked. +DPStaticTriangle::DPStaticTriangle(float lifeTime, const std::vector& vertices, + const std::vector& colours, bool filled) + : DrawPrimitive(lifeTime, colours[0]) + , m_vertices(vertices) + , m_colours(colours) + , m_filled(filled) +{ +} + +// ELF 0x380A10 (D2; D1 0x380AB0, D0 0x380B50). +DPStaticTriangle::~DPStaticTriangle() +{ +} + +// ELF 0x380BF0. IDebugRenderer slot 8 (drawTriangle). +bool DPStaticTriangle::draw(IDebugRenderer* renderer) +{ + renderer->drawTriangle(m_vertices, m_colours, m_filled); + return true; +} + +// ELF 0x380C30. +void DPStaticTriangle::getAttributes(float& lifeTime, std::vector& vertices, + std::vector& colours, bool& filled) const +{ + lifeTime = m_lifeTime; + vertices.resize(0); + vertices.insert(vertices.end(), m_vertices.begin(), m_vertices.end()); + colours.resize(0); + colours.insert(colours.end(), m_colours.begin(), m_colours.end()); + filled = m_filled; +} + +// ELF 0x380D70. +void DPStaticTriangle::setAttributes(float& lifeTime, const std::vector& vertices, + const std::vector& colours, bool& filled) +{ + m_lifeTime = lifeTime; + m_vertices.resize(0); + m_vertices.insert(m_vertices.end(), vertices.begin(), vertices.end()); + m_colours.resize(0); + m_colours.insert(m_colours.end(), colours.begin(), colours.end()); + m_filled = filled; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticTriangle.h b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticTriangle.h new file mode 100644 index 000000000..f17e0128a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticTriangle.h @@ -0,0 +1,45 @@ +// A timed set of debug triangles given as a vertex list and per-vertex colours. +// [INFERRED] Source placement. + +#ifndef AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATICTRIANGLE_H +#define AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATICTRIANGLE_H + +#include + +#include "DrawPrimitive.h" +#include "../Main/AIDllTypes.h" + +namespace dice { +namespace hfe { +namespace ai { + +// sizeof == 0x30 on ia-32 (DPManager::createStaticTriangle allocates 0x30). +class DPStaticTriangle : public DrawPrimitive +{ +public: + // The primitive colour is the first entry of `colours`, which must not be empty. + DPStaticTriangle(float lifeTime, const std::vector& vertices, + const std::vector& colours, bool filled); + virtual ~DPStaticTriangle(); + + // Always draws and returns true. + virtual bool draw(IDebugRenderer* renderer); + + // Copies lifetime, vertices, colours and the fill flag; the vectors are replaced. + void getAttributes(float& lifeTime, std::vector& vertices, + std::vector& colours, bool& filled) const; + // Replaces lifetime, vertices, colours and the fill flag; the primitive colour is kept. + void setAttributes(float& lifeTime, const std::vector& vertices, + const std::vector& colours, bool& filled); + +protected: + /* +0x14 */ std::vector m_vertices; + /* +0x20 */ std::vector m_colours; + /* +0x2C */ bool m_filled; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATICTRIANGLE_H diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DrawPrimitive.cpp b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DrawPrimitive.cpp new file mode 100644 index 000000000..ea853bf4d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DrawPrimitive.cpp @@ -0,0 +1,41 @@ +// AI debug primitive base. Evidence: libaidll.so (ia-32) 0x3811C0..0x38133C. +// [INFERRED] Source placement. + +#include "DrawPrimitive.h" + +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../Main/CommonSingletonServer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x3811C0 (C2; C1 0x381210). +DrawPrimitive::DrawPrimitive(float lifeTime, unsigned int colour) + : m_creationTime(static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime()) + , m_lifeTime(lifeTime) + , m_colour(colour) +{ +} + +// ELF 0x381260 (D2; D1 0x381280, D0 0x3812A0). +DrawPrimitive::~DrawPrimitive() +{ +} + +// ELF 0x381320. The sum creation + lifetime is formed in x87 precision from the double and the +// float, then compared unsigned-above against `time`. +bool DrawPrimitive::expired(double time) const +{ + return time > m_creationTime + m_lifeTime; +} + +// ELF 0x3812E0. Calls the out-of-line overload through the PLT. +bool DrawPrimitive::expired() const +{ + return expired(static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime()); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DrawPrimitive.h b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DrawPrimitive.h new file mode 100644 index 000000000..992b83d2e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DrawPrimitive.h @@ -0,0 +1,40 @@ +// Base of every AI debug primitive: a lifetime, a colour and one draw slot. +// [INFERRED] Source placement (the TU is DrawPrimitive.cpp; the directory is not attested). + +#ifndef AI_AIDLL_AI_DRAWPRIMITIVES_DRAWPRIMITIVE_H +#define AI_AIDLL_AI_DRAWPRIMITIVES_DRAWPRIMITIVE_H + +namespace dice { +namespace hfe { +namespace ai { + +class IDebugRenderer; + +// A timed debug primitive. The creation time is taken from the game timer when the primitive is +// constructed; DPManager deletes it once expired() reports true or draw() returns false. +class DrawPrimitive +{ +public: + DrawPrimitive(float lifeTime, unsigned int colour); + virtual ~DrawPrimitive(); + + // Draws the primitive through the renderer. Returns false when the primitive should be + // discarded (the dynamic primitives do so once their object is gone). + virtual bool draw(IDebugRenderer* renderer) = 0; + + // True once `time` lies strictly beyond creation time plus lifetime. + bool expired(double time) const; + // expired() against the current game time. + bool expired() const; + +protected: + /* +0x04 */ double m_creationTime; // ia-32: 4-byte aligned, so the double sits at +4 + /* +0x0C */ float m_lifeTime; + /* +0x10 */ unsigned int m_colour; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_DRAWPRIMITIVES_DRAWPRIMITIVE_H diff --git a/Code/BF2/AI/AIDLL/AI/Main/AICollisionHandler.cpp b/Code/BF2/AI/AIDLL/AI/Main/AICollisionHandler.cpp index c550177e1..7583af743 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AICollisionHandler.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/AICollisionHandler.cpp @@ -1,4 +1,8 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining AICollisionHandler operations. +// Bridges engine projectile events to the bots. libaidll.so (ia-32) 1.5.3153; every body carries +// its ELF address. [INFERRED] Source placement (one TU in the image, static initializer 0x383440). + +// static init: ELF 0x3833B0 (__tcf_0 0x383410, _GLOBAL__I 0x383440): 's Init object only. +#include #include "AICollisionHandler.h" @@ -6,7 +10,28 @@ #include "../../../../Core/ClassManager.h" #include "CommonSingletonServer.h" -#include "AIDllFrontier.h" +#include "IBotManager.h" +#include "../AIBot/BotMain.h" // Bot +0x94 / +0xD0 / +0xE0 +#include "../../../AIInterface/BFKnowledge/IAIObject.h" // IAIObject +0xB8 +#include "../AIBot/BotNavigation.h" +#include "../AIBot/SensedObject.h" +#include "../AIBot/SquadManager.h" +#include "../AIKnowledge/FireObject.h" +#include "../AIKnowledge/Information.h" +#include "InformationManager.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../AIUtils/AIVectorMath.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" +#include "../../../AIInterface/BFKnowledge/BFCollisionHandler.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../../Math/Mat4.h" + +#include namespace dice { namespace hfe { @@ -15,7 +40,9 @@ extern ClassManager* classManager; namespace ai { + // IAICollisionHandler +// libaidll.so 0x3E5F80 (C2) / 0x3E6020 (C1). IAICollisionHandler::IAICollisionHandler() { // the guard reads the roster static, not the registry. Reproduced. @@ -23,6 +50,7 @@ IAICollisionHandler::IAICollisionHandler() classManager->registerSimpleSingleton("IAICollisionHandler", this); } +// libaidll.so 0x3E60C0 (D2) / 0x3E6150 (D1) / 0x3E61E0 (D0). IAICollisionHandler::~IAICollisionHandler() { if (CommonSingletonServer::m_iAICollisionHandler == this) @@ -30,53 +58,324 @@ IAICollisionHandler::~IAICollisionHandler() } // Stateless collision adapter; construction requires only the base-class initialization. +// libaidll.so 0x382200 (C2) / 0x382240 (C1). AICollisionHandler::AICollisionHandler() { } // The vptr reset and the base call, which again is what C++ emits. +// libaidll.so 0x382280 (D2) / 0x3822C0 (D1) / 0x382300 (D0). AICollisionHandler::~AICollisionHandler() { } -void AICollisionHandler::handleProjectileFire(const Vec3&, world::IObject *, const Mat4&, int, IAIObject *, int, int) +namespace { + +inline IBFTimer* bfTimer() +{ + return static_cast(CommonSingletonServer::m_iBFTimer); +} + +inline IAIPlayerFactory* aiPlayerFactory() +{ + return static_cast(CommonSingletonServer::m_iaiPlayerFactory); +} + +} // namespace + +// handleProjectileFire - libaidll.so (ia-32) 0x382340, 689 B (objdump listing, 2026-11-02; Ghidra +// drops `this` here, so its parameters are shifted by one). `from` is the round's start point, +// `projectile` the round, `objectId` its object id, `shooter` the AI object of the shooter's root +// and `playerId` the shooter's player id; the transformation and the team are not read. A live +// bot books a fire correction for the round (BotMain::event_firing answers whether it may and the +// record's predicted target) and hands it to the engine collision handler. A thrown or launched +// explosive without guidance stamps the grenade time. Last, the firing target's information is +// resolved to its primary object and, when the bot senses it, the physical plug-in is asked its +// strength type; the answer is discarded, as compiled. +void AICollisionHandler::handleProjectileFire(const Vec3& from, world::IObject* projectile, const Mat4&, + int objectId, IAIObject* shooter, int playerId, int) +{ + if (!shooter) + return; + Bot* const bot = IBotManager::instance->getBotFromPlayerId(playerId); // +0x1C + if (!bot || bot->isDeactivated()) // +0xD0 + return; + if (projectile) + { + bool corrected; + const Vec3& target = static_cast(bot)->event_firing(corrected, objectId, from); // +0x2A8 + if (corrected) + static_cast(CommonSingletonServer::m_iBFCollisionHandler) + ->addBotProjectile(bot->getBotId(), projectile, target); // +0xE8, +0x3C + } + + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); // +0xD8 + IPIArmament* const armament = equipment ? equipment->getArmament() : 0; + const int activeWeapon = armament ? armament->getActiveWeapon() : -1; // +0x14 + if (activeWeapon == -1 || !armament) + return; + WeaponInfo* const weapon = + WeaponInfoManager::m_instance->getInformation(armament->getWeapon(activeWeapon)); // +0x1C + if (!weapon) + return; + if (weapon->getExplosionRadius() > 0.0f && weapon->getWeaponGuidanceType() == 0) + bot->setTimeOfLastGrenadeThrown(bfTimer()->getGameTime()); // +0xF4 + + unsigned int target = bot->getFiringTarget(); // +0x80 + Information* targetInfo = informationManager->getInformation(target); + if (targetInfo && !targetInfo->isPrimary()) + { + target = targetInfo->getPrimaryObject(bot->getSide()); // +0xE0 + targetInfo = informationManager->getInformation(target); + } + IPIPhysical* const physical = targetInfo ? targetInfo->getPhysical() : 0; + SensedObject* const sensed = bot->getSensedObjectFromHandle(target); // +0x94 + if (targetInfo && physical && sensed) + physical->getStrengthType(); // +0x44 +} + +// handleIndirectProjectileHit - libaidll.so 0x382600, 52 B: the bots near the round's flight line +// are told about it. The team, object id and last argument are not read. +// [CHOSEN, not recovered] the return value: the image returns whatever the void helper left in +// EAX; the only caller (BFCollisionHandler, bf2 0x83FDDC0) passes it on and its callers discard it. +int AICollisionHandler::handleIndirectProjectileHit(int, IAIObject* shooter, int, const Vec3& position, int) +{ + updateBotsOnProjectile(shooter, position); + return 0; +} + +// handleIndirectProjectileHit - libaidll.so 0x382640, 52 B: as above, without the object id. +// [CHOSEN, not recovered] the return value, as above (caller bf2 0x83FDC70). +int AICollisionHandler::handleIndirectProjectileHit(int, IAIObject* shooter, const Vec3& position, int) +{ + updateBotsOnProjectile(shooter, position); + return 0; +} + +// handleProjectileDamage - libaidll.so (ia-32) 0x392680, 128 B (read with rea, 2026-11-01). Only a +// shooting bot that is not deactivated reacts: it looks the victim up among its sensed objects by +// the victim's information handle for the bot's side (result discarded, as compiled). The +// strength and weapon index are not read. +// [CHOSEN, not recovered] the return value: the image sets none (EAX keeps the last call's result) +// and the only caller, BFCollisionHandler::handleProjectileDamage (bf2 0x83FE410), discards it. +int AICollisionHandler::handleProjectileDamage(IAIObject* shooter, IAIObject* victim, const int&, int) { - BF2_AI_FRONTIER("dice::hfe::ai::AICollisionHandler::handleProjectileFire"); + Bot* const bot = IBotManager::instance->getBot(shooter); // +0x24 + if (bot && !bot->isDeactivated()) // +0xD0 + bot->getSensedObjectFromHandle(victim->getInformation(bot->getSide())); // +0x94 / +0xB8 / +0xE0 + return 0; } -int AICollisionHandler::handleIndirectProjectileHit(int, IAIObject *, int, const Vec3&, int) +// handleProjectileMiss - libaidll.so 0x382710, 136 B. GameLogicCollision's terrain hit through +// BFCollisionHandler (bf2 0x83FE6A0): a live shooting bot records the miss of the round +// (event_shotMissed +0x174), then every bot near the flight line is told about it. +// [CHOSEN, not recovered] the return value: EAX is the void helper's leftover; the caller discards it. +int AICollisionHandler::handleProjectileMiss(IAIObject* shooter, int playerId, int objectId, const Vec3& position) { - BF2_AI_FRONTIER("dice::hfe::ai::AICollisionHandler::handleIndirectProjectileHit"); + Bot* const bot = IBotManager::instance->getBotFromPlayerId(playerId); // +0x1C + if (bot && !bot->isDeactivated()) // +0xD0 + bot->event_shotMissed(objectId, position); // +0x174 + updateBotsOnProjectile(shooter, position); + return 0; } -int AICollisionHandler::handleIndirectProjectileHit(int, IAIObject *, const Vec3&, int) +// victimUpdate - libaidll.so 0x3827A0, 966 B (objdump listing, Ghidra cross-check). Called by +// BFCollisionHandler::handleCollision (bf2 0x83FD5C0) when a round hits a player's object; it +// answers 1 when the victim is a live bot that was told about the shot. +// First the squads: when the shooter's information (as seen by the victim's side) and the +// victim's current vehicle are on different sides and the shooter does not carry C4, the +// victim's squad learns it was fired at; a human occupying the shooter's unit is booked the +// other way round. Then a live victim bot that is not hit by C4 receives the shot as incoming +// fire: a FireObject from the shooter's position to the hit point with the unit's battle +// strengths, direct, decay 1. The victim-side information is not null-tested before setTime, +// as compiled. `objectId` is not read. +int AICollisionHandler::victimUpdate(int victimPlayerId, int, const Vec3& position, IAIObject* victim, + IAIObject* shooter) { - BF2_AI_FRONTIER("dice::hfe::ai::AICollisionHandler::handleIndirectProjectileHit"); + IAIPlayer* const victimPlayer = aiPlayerFactory()->getPlayerFromId(victimPlayerId); // +0x20 + if (victimPlayer && shooter) + { + const unsigned int shooterHandle = + shooter->forceGetInformation(victimPlayer->getSide(), true); // +0x6C, +0xB4 + Information* const shooterInfo = informationManager->getInformation(shooterHandle); + IAIObject* const vehicle = shooterInfo ? victimPlayer->getCurrentVehicle() : 0; // +0x54 + if (vehicle) + { + Information* const vehicleInfo = + informationManager->getInformation(vehicle->getInformation(victimPlayer->getSide())); // +0xB8 + if (!isC4(shooter) && vehicleInfo && vehicleInfo->getSide() != shooterInfo->getSide()) // +0x44 + { + SquadManager* const squads = SquadManager::m_instance; + squads->shotsFired(victimPlayerId, victimPlayer->getSide(), shooterHandle); + if (IPIUnit* const unit = shooterInfo->getUnit()) + { + const int occupant = unit->getOccupyingPlayerId(shooterInfo->getSide()); + if (occupant != -1) + { + IAIPlayer* const occupantPlayer = aiPlayerFactory()->getPlayerFromId(occupant); + if (occupantPlayer && !occupantPlayer->getIsAIPlayer()) // +0x88 + squads->shotsFired(occupant, shooterInfo->getSide(), + victim->forceGetInformation(shooterInfo->getSide(), true)); + } + } + } + } + } + + Bot* const bot = IBotManager::instance->getBotFromPlayerId(victimPlayerId); // +0x1C + if (!bot || bot->isDeactivated() || isC4(shooter)) + return 0; + const unsigned int handle = shooter->forceGetInformation(bot->getSide(), true); + Information* const info = informationManager->getInformation(handle); + info->setTime(bfTimer()->getGameTime()); // +0x0C + IPIUnit* const unit = info->getUnit(); + if (!unit) + return 0; + FireObject* const fire = new FireObject(shooter->getPosition(), position, unit->getBattleStrengths(), + true, bfTimer()->getGameTime(), 1.0f); // +0xD4 + bot->event_projectile(fire, handle); // +0x16C + return 1; } -int AICollisionHandler::handleProjectileDamage(IAIObject *, IAIObject *, const int&, int) +// shooterUpdate - libaidll.so 0x382B70, 168 B. After victimUpdate answered 1: a live shooting bot +// counts one more hit in its sensed record of the victim (+0x48) and reports the hit of the round. +// [CHOSEN, not recovered] the return value: the image sets none; the caller discards it. +int AICollisionHandler::shooterUpdate(int playerId, int objectId, world::IObject* hitObject, IAIObject* victim, + const Vec3& position) { - BF2_AI_FRONTIER("dice::hfe::ai::AICollisionHandler::handleProjectileDamage"); + Bot* const bot = IBotManager::instance->getBotFromPlayerId(playerId); // +0x1C + if (!bot || bot->isDeactivated()) + return 0; + if (SensedObject* const sensed = bot->getSensedObjectFromHandle(victim->getInformation(bot->getSide()))) + ++sensed->m_fireRating; + bot->event_shotHit(objectId, hitObject, position); // +0x170 + return 0; } -int AICollisionHandler::handleProjectileMiss(IAIObject *, int, int, const Vec3&) +// handleProjectileTimeout - libaidll.so 0x382C20, 223 B. A round's reset or detonation through +// BFCollisionHandler (bf2 0x83FDA30): a live owning bot drops its fire correction for the round +// (event_shotTimeOut +0x2A4), the bots near the line from the owner's current vehicle are told, +// and a sticky round of a live bot that has C4 placed removes the C4. +// [CHOSEN, not recovered] the return value: the image sets none; both callers discard it. +int AICollisionHandler::handleProjectileTimeout(int objectId, int playerId, const Vec3& position, bool sticky) { - BF2_AI_FRONTIER("dice::hfe::ai::AICollisionHandler::handleProjectileMiss"); + Bot* const bot = IBotManager::instance->getBotFromPlayerId(playerId); // +0x1C + bool liveBot = false; + if (bot && !bot->isDeactivated()) + { + liveBot = true; + static_cast(bot)->event_shotTimeOut(objectId); // +0x2A4 + } + IAIPlayer* const player = aiPlayerFactory()->getPlayerFromId(playerId); // +0x20 + if (player) + updateBotsOnProjectile(player->getCurrentVehicle(), position); // +0x54 + if (liveBot && player && sticky && bot->isC4Placed()) // +0x150 + bot->removeC4(); // +0x154 + return 0; } -int AICollisionHandler::victimUpdate(int, int, const Vec3&, IAIObject *, IAIObject *) +// checkIfGrenade - libaidll.so 0x382D00, 728 B (objdump listing, Ghidra cross-check). A thrown +// explosive that lands within 10 m of the bot (and not on it) warns the bot's navigation: always +// within 5 m, otherwise only when it lies ahead of the bot (positive dot product with the +// equipment's forward axis, the third matrix row). The warning carries the weapon's firing time +// and whether it is the flashbang ("nshgr_flashbang"). The weapon name is copied, as compiled. +void AICollisionHandler::checkIfGrenade(Bot* bot, IAIObject* projectile, const Vec3& position) { - BF2_AI_FRONTIER("dice::hfe::ai::AICollisionHandler::victimUpdate"); + Information* const projectileInfo = + informationManager->getInformation(projectile->getInformation(projectile->getSide())); // +0x12C, +0xB8 + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + if (!projectileInfo || !equipment) + return; + IPIArmament* const armament = projectileInfo->getArmament(); + if (!armament || armament->getActiveWeapon() == -1) + return; + WeaponInfo* const weapon = + WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + if (!weapon || !weapon->getIsThrown() || !(weapon->getExplosionRadius() > 0.0f)) + return; + + const std::string name = weapon->getName(); + const Vec3& botPosition = equipment->getPosition(); // +0x30 + float dx = position.x - botPosition.x; + float dy = position.y - botPosition.y; + float dz = position.z - botPosition.z; + const float distance = std::sqrt(dx * dx + dy * dy + dz * dz); + if (!(distance < 10.0f) || !(distance > 1e-05f)) + return; + const float inv = 1.0f / distance; + dx *= inv; + dy *= inv; + dz = inv * dz; + bool warn = distance < 5.0f; + if (!warn) + { + const Mat4& transformation = equipment->getTransformation(); // +0x3C + warn = dx * transformation.m[8] + dy * transformation.m[9] + dz * transformation.m[10] > 0.0f; + } + if (warn) + { + const bool flashbang = name.compare("nshgr_flashbang") == 0; + const double time = weapon->getTimeOfFiring(); // +0x20 + bot->getBotNavigation()->setGrenadeWarning(position, time, flashbang); // +0xFC + } } -int AICollisionHandler::shooterUpdate(int, int, world::IObject *, IAIObject *, const Vec3&) +// isC4 - libaidll.so 0x382FE0, 201 B: the object's own information has an active weapon of +// weapon type 4. +bool AICollisionHandler::isC4(IAIObject* object) { - BF2_AI_FRONTIER("dice::hfe::ai::AICollisionHandler::shooterUpdate"); + Information* const info = informationManager->getInformation(object->getInformation(object->getSide())); + if (!info) + return false; + IPIArmament* const armament = info->getArmament(); + if (!armament) + return false; + if (armament->getActiveWeapon() == -1) + return false; + WeaponInfo* const weapon = + WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + if (!weapon) + return false; + return weapon->getWeaponType() == 4; } -int AICollisionHandler::handleProjectileTimeout(int, int, const Vec3&, bool) +// updateBotsOnProjectile - libaidll.so 0x3830B0, 763 B (objdump listing). Every active bot that is +// neither dead nor man-down is first checked for a grenade warning. A bot of another side than +// the round's object, not facing C4, whose equipment lies within 10 m of the line from that +// object to `position` (objFireLineDist), receives the round as indirect incoming fire: a +// FireObject from the object's position to `position` with the unit's battle strengths, not +// direct, decay 0.1. The bot count is re-read every pass; neither the bot, the information +// nor its unit plug-in is null-tested, as compiled. +void AICollisionHandler::updateBotsOnProjectile(IAIObject* projectile, const Vec3& position) { - BF2_AI_FRONTIER("dice::hfe::ai::AICollisionHandler::handleProjectileTimeout"); + if (!projectile) + return; + const Vec3& origin = projectile->getPosition(); // +0xD4 + const int side = projectile->getSide(); // +0x12C + IBotManager* const bots = IBotManager::instance; + for (unsigned int i = 0; i < static_cast(bots->getBotCount()); ++i) // +0x08 + { + Bot* const bot = bots->getBot(i); // +0x14 + if (bot->isDeactivated() || bot->isDead() || bot->getManDown()) // +0xD0, +0xC4, +0x1B0 + continue; + checkIfGrenade(bot, projectile, position); + if (bot->getPlayer()->getSide() == side) // +0xBC, +0x6C + continue; + if (isC4(projectile)) + continue; + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + if (!equipment) + continue; + if (!(objFireLineDist(equipment->getAIObject()->getPosition(), origin, position) < 10.0f)) + continue; + Information* const info = informationManager->getInformation( + projectile->forceGetInformation(bot->getSide(), true)); // +0xB4 + info->setTime(bfTimer()->getGameTime()); + IPIUnit* const unit = info->getUnit(); + FireObject* const fire = new FireObject(projectile->getPosition(), position, unit->getBattleStrengths(), + false, bfTimer()->getGameTime(), 0.1f); + bot->event_projectile(fire, projectile->getInformation(bot->getSide())); // +0x16C + } } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/Main/AICollisionHandler.h b/Code/BF2/AI/AIDLL/AI/Main/AICollisionHandler.h index 73f95b33e..64cb63344 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AICollisionHandler.h +++ b/Code/BF2/AI/AIDLL/AI/Main/AICollisionHandler.h @@ -1,6 +1,8 @@ // Handles collisions in the AI module. -// Preserve virtual declaration order. [INFERRED] Return types require validation where implementations remain incomplete. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. +// Preserve virtual declaration order. Parameter types are attested by the libaidll.so mangled +// names. [INFERRED] the int return types: the shipped bodies of handleIndirectProjectileHit, +// handleProjectileMiss, shooterUpdate and handleProjectileTimeout set no return value and +// every engine caller discards it; victimUpdate answers 0/1 and BFCollisionHandler tests it. // [INFERRED] Source placement. #ifndef AI_AIDLL_AI_MAIN_AICOLLISIONHANDLER_H @@ -52,6 +54,11 @@ class AICollisionHandler : public IAICollisionHandler virtual int shooterUpdate(int, int, world::IObject *, IAIObject *, const Vec3&); virtual int handleProjectileTimeout(int, int, const Vec3&, bool); + // Non-virtual helpers (mangled names in libaidll.so; [INFERRED] access and return spelling: + // checkIfGrenade and updateBotsOnProjectile set no return value, isC4 materialises a bool). + void checkIfGrenade(Bot* bot, IAIObject* projectile, const Vec3& position); // 0x382D00 + bool isC4(IAIObject* object); // 0x382FE0 + void updateBotsOnProjectile(IAIObject* projectile, const Vec3& position); // 0x3830B0 }; } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIConsole.cpp b/Code/BF2/AI/AIDLL/AI/Main/AIConsole.cpp index a3e466f82..91aad4b91 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIConsole.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/AIConsole.cpp @@ -1,4 +1,5 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining AIConsole operations. +// static init: ELF 0x3969C0 (__tcf_0 0x396A20, _GLOBAL__I 0x396A50): 's Init object only. +#include #include "AIConsole.h" @@ -6,10 +7,45 @@ #include "../AIBot/SquadManager.h" // init's second allocation #include "../AIUtils/checkPointer.h" // init's two dead null checks #include "../AIPlanInterpreter/BAPEntries.h" // the 42 registered primitives -#include "AIDllFrontier.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotOrder.h" +#include "../AIBot/SensingAgent.h" +#include "../AIBot/WPMoveTo.h" +#include "../AIBot/WPAltitudeMoveTo.h" +#include "../AIBot/WPPatrol.h" +#include "../AIBot/WPAltitudePatrol.h" +#include "../AIKnowledge/Information.h" +#include "InformationManager.h" +#include "../AIPathFinding/NavMesh/MapProperties.h" +#include "../AIStrategicEntity/AIStrategicArea.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" +#include "../AIStrategicEntity/AILandingZone.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" +#include "../../../AIInterface/BFKnowledge/BFGameEffector.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../../Core/Debug.h" +#include "../../../../Core/StringUtil.h" +#include "../../../../IO/File/File.h" +#include "../../../../Math/Mat4.h" +#include "IBotManager.h" +#include "AILODManager.h" +#include "IAIPathfinding.h" +#include +#include +#include +#include #include "AIMain.h" // IAIMain::m_instance -#include "../../../../Core/ConsoleObjectMacro.h" // the ai.init binding at the tail #include "CommonSingletonServer.h" +#include "AISettings.h" // IAISettings / IAISettingsModifier +#include "AIStreamOperators.h" // the script-vocabulary extractors +#include "../AIBotBehaviour/BotBehaviour.h" // setVehicleBehaviour's result +#include "BotBehaviourManager.h" // the behaviour commands +#include "StrategyManager.h" // the aiStrategy bindings +#include "../AIStrategic/SAI.h" // addSAIStrategy +#include "../AIStrategic/Strategy.h" namespace dice { namespace hfe { @@ -17,10 +53,9 @@ namespace ai { AIConsole* AIConsole::m_instance = 0; -// Registers Bot Action Plan primitives. -// [FRONTIER] Missing primitive implementations stop by name. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. +// ELF 0x383470 / 0x389360. Registers Bot Action Plan primitives and sensing patterns. AIConsole::AIConsole() + : m_activeBehaviourModifiers(), m_gap44() { // Publishes this console as the active singleton. m_instance = this; @@ -74,42 +109,94 @@ AIConsole::AIConsole() m_sensingAgentPatterns["MouseFreeLook"] = new SensingAgentMouseFreeLookPattern(); m_sensingAgentPatterns["Soldier"] = new SensingAgentSoldierPattern(); m_sensingAgentPatterns["Null"] = new SensingAgentNullPattern(); + + m_activeBehaviourModifiers = m_behaviourModifiers.end(); + m_aiMain = 0; + // shipped defect: this allocation is never stored or released. + MapProperties* const properties = new MapProperties(); + properties->setMaxSlope(0.36651915311813354f); } -// [FRONTIER] Destruction requires cleanup of owned plan entries, behavior entries and squad state. +// ELF 0x38F5C0 (D1, 1047 B; recovered on the client track). +// reset, then the SquadManager singleton is deleted and this singleton zeroed unconditionally. +// The BAP entries are deleted through their virtual deleting destructor (+4) and erased one by +// one; the modifier arrays are freed with delete[] but their nodes stay (only the cursor is +// moved to end). The sensing-pattern loop advances twice per pass - `++it` in the loop header on +// top of `erase(it++)` - so it deletes the 1st and 3rd of the four patterns and leaves the 2nd +// and 4th to the map's own destructor, which frees their nodes without deleting them. Shipped +// (0x38F774 and 0x38F7DF are both _M_increment); with the four patterns the constructor +// registers, the iterator never passes end(). AIConsole::~AIConsole() { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::~AIConsole"); + reset(); + if (SquadManager::m_instance) + delete SquadManager::m_instance; + m_instance = 0; + + std::map::iterator entry = m_bapEntries.begin(); + while (entry != m_bapEntries.end()) + { + delete entry->second; // virtual, slot +4 + m_bapEntries.erase(entry++); + } + + for (std::map::iterator modifier = m_behaviourModifiers.begin(); + modifier != m_behaviourModifiers.end(); ++modifier) + delete[] modifier->second; + m_activeBehaviourModifiers = m_behaviourModifiers.end(); // +0x10 + + for (std::map::iterator pattern = m_sensingAgentPatterns.begin(); + pattern != m_sensingAgentPatterns.end(); ++pattern) + { + delete pattern->second; // virtual, slot +4 + m_sensingAgentPatterns.erase(pattern++); + } } -// [FRONTIER] Reset must delete behavior-modifier arrays and Strategy objects and return -// true, while retaining plan-entry and sensing-pattern registries. Ordered cleanup is unimplemented. +// ELF 0x395F60 (528 B; recovered on the client track). Frees every behaviour-modifier array +// (delete[]) and erases its node, then deletes every Strategy (nonvirtual D1 + operator delete) +// and erases its node. The BAP and sensing registries and the modifier cursor are left alone. +// Returns 1. bool AIConsole::reset() { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::reset"); + std::map::iterator modifier = m_behaviourModifiers.begin(); + while (modifier != m_behaviourModifiers.end()) + { + delete[] modifier->second; + m_behaviourModifiers.erase(modifier++); + } + std::map::iterator strategy = m_strategies.begin(); + while (strategy != m_strategies.end()) + { + delete strategy->second; + m_strategies.erase(strategy++); + } + return true; } -// Dedicated-server console behavior: no single-player instance, no debug/camera-text -// action, and zero camera position and rotation. +// ELF 0x383460. The dedicated image has no single-player instance. AIConsole* AIConsole::getSinglePlayerInstance() { return 0; } +// ELF 0x38F9E0. IAIMain* AIConsole::getActiveAIMain() { return IAIMain::m_instance; } +// ELF 0x396170. Empty in the dedicated image. void AIConsole::debug() { } +// ELF 0x3934B0. Empty in the dedicated image. void AIConsole::removeCameraText() { } -// A zeroed Vec3, by value. Three immediate zero stores into the return slot and nothing else. +// ELF 0x392B40. A zeroed Vec3, by value. Vec3 AIConsole::getRendCameraPosition() { Vec3 position; @@ -119,6 +206,7 @@ Vec3 AIConsole::getRendCameraPosition() return position; } +// ELF 0x392B70. Vec3 AIConsole::getRendCameraRotation() { Vec3 rotation; @@ -128,19 +216,20 @@ Vec3 AIConsole::getRendCameraRotation() return rotation; } -// [FRONTIER] Remaining bot, behavior and interpreter commands require implementation. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. -BAPEntry* AIConsole::getBAPEntryFromName(std::string) +// ELF 0x392610: `m_bapEntries[name]` (lower_bound + insert_unique: an unknown name is inserted +// null, case-sensitive). +BAPEntry* AIConsole::getBAPEntryFromName(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::getBAPEntryFromName"); + return m_bapEntries[name]; } -ISensingAgentPattern* AIConsole::getSensingAgentPatternFromName(std::string) +// ELF 0x3927B0: `m_sensingAgentPatterns[name]` (operator[]: an unknown name is inserted null). +ISensingAgentPattern* AIConsole::getSensingAgentPatternFromName(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::getSensingAgentPatternFromName"); + return m_sensingAgentPatterns[name]; } -// Initializes AI from a level script. Returns immediately when an active AI runtime already exists. +// ELF 0x38FA00. Initializes AI from a level script, unless a runtime already exists. void AIConsole::init(int n) { if (getActiveAIMain()) @@ -161,254 +250,807 @@ void AIConsole::init(int n) (void)squadManager; } -void AIConsole::addBot(std::string, int, std::string, std::string) +// ELF 0x38FCF0. Unknown modifier names are inserted with a null value. +int AIConsole::addBot(std::string name, int side, std::string modifiers, std::string equipment) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::addBot"); + if (!IAIMain::m_instance || static_cast(side) > 2) + return -1; + IAIObject* object = 0; + if (equipment != "NoEquipment") + { + object = static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->getObjectFromName(equipment); + if (!object) + return -1; + } + const int playerId = static_cast(CommonSingletonServer::m_iaiPlayerFactory) + ->getPlayerIdFromName(name); + if (playerId == -1) + return -1; + float* const weights = m_behaviourModifiers[modifiers]; + if (!weights || !static_cast(IAIMain::m_instance)->addBot(playerId, side, weights, object)) + return -1; + return IBotManager::instance->getBotCount() - 1; } -void AIConsole::addUnspawnedBot(std::string, int, std::string) +// ELF 0x38FF90. The shipped command refuses the operation with an Error diagnostic. +int AIConsole::addUnspawnedBot(std::string, int, std::string) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::addUnspawnedBot"); + Debug(DebugTypeError, "AI/AIDLL/AI/Main/AIConsole.cpp", 363, "") << "Does not work"; + return -1; } -void AIConsole::updateBot(int) +// ELF 0x3900A0. +void AIConsole::updateBot(int id) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::updateBot"); + if (!getActiveAIMain()) + return; + Bot* const bot = getBotFromId(id); + if (bot) + bot->updateBot(); } -void AIConsole::killBotName(const std::string&) +// ELF 0x390100. The effector call is respawnBot, despite the command's name. +std::string AIConsole::killBotName(const std::string& name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::killBotName"); + std::stringstream out; + if (!IBotManager::instance) + { + out << "No active BotManager found."; + return out.str(); + } + Bot* const bot = IBotManager::instance->getBotFromName(name); + if (!bot) + out << "Failed to find bot with name: " << name << ". Check caps."; + else if (!bot->isDead()) + { + static_cast(CommonSingletonServer::m_iaiGameEffector)->respawnBot(bot->getPlayer()); + out << "Bot " << name << " id: " << bot->getBotId() << " has been killed."; + } + else + out << "Failed to kill bot " << name << " id: " << bot->getBotId() << "."; + return out.str(); } -void AIConsole::killBotId(int) +// ELF 0x390760. +std::string AIConsole::killBotId(int id) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::killBotId"); + std::stringstream out; + if (!IBotManager::instance) + { + out << "No active BotManager found."; + return out.str(); + } + Bot* const bot = IBotManager::instance->getBotFromId(id); + if (!bot) + out << "Failed to find bot with id: " << id << "."; + else if (!bot->isDead()) + { + static_cast(CommonSingletonServer::m_iaiGameEffector)->respawnBot(bot->getPlayer()); + const std::string& name = bot->getPlayer()->getName(); + out << "Bot " << name << " id: " << id << " has been killed."; + } + else + { + const std::string& name = bot->getPlayer()->getName(); + out << "Failed to kill bot " << name << " id: " << id << "."; + } + return out.str(); } +// ELF 0x390CB0. Count is captured once; null entries are skipped. void AIConsole::killAllBots() { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::killAllBots"); + IBotManager* const manager = IBotManager::instance; + if (!manager) + return; + const int count = manager->getBotCount(); + for (int i = 0; i < count; ++i) + { + Bot* const bot = manager->getBot(i); + if (bot) + static_cast(CommonSingletonServer::m_iaiGameEffector)->respawnBot(bot->getPlayer()); + } } -void* AIConsole::getBotFromId(int) +// ELF 0x392950. +Bot* AIConsole::getBotFromId(int id) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::getBotFromId"); + return IBotManager::instance ? IBotManager::instance->getBotFromId(id) : 0; } -void AIConsole::botMoveTo(float, Vec3, int) +// ELF 0x391D40. +void AIConsole::botMoveTo(float radius, Vec3 position, int id) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::botMoveTo"); + Bot* const bot = getBotFromId(id); + if (!bot) + return; + std::list positions; + positions.push_back(position); + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + WaypointList* waypoints; + if (equipment && equipment->isOfType(ITAir)) + waypoints = new WPAltitudeMoveTo(radius, radius, radius, 1, positions); + else + waypoints = new WPMoveTo(radius, 60.0f, 1, positions, -1); + bot->setWaypoints(waypoints); } -void AIConsole::botFlyTo(int, float, float, float, Vec3) +// ELF 0x391EE0. +void AIConsole::botFlyTo(int id, float first, float second, float third, Vec3 position) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::botFlyTo"); + Bot* const bot = getBotFromId(id); + if (!bot) + return; + std::list positions; + positions.push_back(position); + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + if (equipment && equipment->isOfType(ITAir)) + bot->setWaypoints(new WPAltitudeMoveTo(first, second, third, 1, positions)); } -void AIConsole::botSetWaypoints_Patrol(int, float, int, Vec3, Vec3, Vec3) +// ELF 0x392040. The flags retain count + 1 even when count exceeds the three supplied points. +void AIConsole::botSetWaypoints_Patrol(int id, float radius, int count, Vec3 a, Vec3 b, Vec3 c) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::botSetWaypoints_Patrol"); + Bot* const bot = getBotFromId(id); + if (!bot) + return; + std::list positions; + if (count > 0) positions.push_back(a); + if (count > 1) positions.push_back(b); + if (count > 2) positions.push_back(c); + bot->setWaypoints(new WPPatrol(radius, static_cast(count) + 1, positions)); } -void AIConsole::botSetWaypoints_Patrol3d(int, float, int, Vec3, Vec3, Vec3) +// ELF 0x3921D0. +void AIConsole::botSetWaypoints_Patrol3d(int id, float radius, int count, Vec3 a, Vec3 b, Vec3 c) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::botSetWaypoints_Patrol3d"); + Bot* const bot = getBotFromId(id); + if (!bot) + return; + std::list positions; + if (count > 0) positions.push_back(a); + if (count > 1) positions.push_back(b); + if (count > 2) positions.push_back(c); + bot->setWaypoints(new WPAltitudePatrol(radius, 10.0f, 100.0f, + static_cast(count) + 1, positions)); } -void AIConsole::botGiveOrder(int, std::string, std::string) +// ELF 0x392380. +void AIConsole::botGiveOrder(int id, std::string behaviour, std::string modifiers) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::botGiveOrder"); + Bot* const bot = getBotFromId(id); + if (!bot) + return; + const int behaviourId = BotBehaviourManager::m_instance->getBehaviourId(behaviour); + if (behaviourId == -1) + return; + float* const weights = m_behaviourModifiers[modifiers]; + if (weights) + bot->recieveOrder(new BotOrder(weights, static_cast(behaviourId))); } -void AIConsole::setBehaviour(int, std::string) +// ELF 0x390D50: names behaviour `id` (while AI settings exist). +void AIConsole::setBehaviour(int id, std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::setBehaviour"); + if (CommonSingletonServer::m_iaiSettings) + BotBehaviourManager::m_instance->setBehaviourName(id, name); } -std::string AIConsole::getBehaviour(int) +// ELF 0x390DE0. +std::string AIConsole::getBehaviour(int id) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::getBehaviour"); + return CommonSingletonServer::m_iaiSettings ? BotBehaviourManager::m_instance->getBehaviourName(id) : ""; } -void AIConsole::setVehicleDefaultBehaviour(std::string&, std::string&) +// ELF 0x390E60: nothing while the bot limit is unset (IAISettings slot 0 getMaxNBots() == -1) +// or for an unknown vehicle (+0x54 getVehicle) or behaviour; otherwise IAISettingsModifier +0x18. +void AIConsole::setVehicleDefaultBehaviour(std::string& vehicleName, std::string& behaviourName) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::setVehicleDefaultBehaviour"); + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + if (settings->getMaxNBots() == -1) + return; + const int vehicle = settings->getVehicle(vehicleName); + if (vehicle == -1) + return; + const int behaviour = BotBehaviourManager::m_instance->getBehaviourId(behaviourName); + if (behaviour == -1) + return; + static_cast(CommonSingletonServer::m_iaiSettingsModifier) + ->setDefaultBehaviour(vehicle, behaviour); } -void AIConsole::setVehicleBehaviour(std::string, std::string, std::string, std::string, int, - std::string, std::string) +// ELF 0x390F50 (761 bytes): the same two guards, then the named modifier set must exist. The +// behaviour "NULL" registers a null behaviour under getBehaviourId("NULL"); any other name goes +// through BotBehaviourManager::create, and only a non-null result is registered +// (IAISettingsModifier +0x14 addBehaviour). The create message is built and dropped. +void AIConsole::setVehicleBehaviour(std::string vehicleName, std::string behaviourName, + std::string createFunctionName, std::string patternName, + int mode, std::string urgeCurveName, std::string modifiersName) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::setVehicleBehaviour"); + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + if (settings->getMaxNBots() == -1) + return; + const int vehicle = settings->getVehicle(vehicleName); + if (vehicle == -1) + return; + const std::map::iterator modifiers = m_behaviourModifiers.find(modifiersName); + if (modifiers == m_behaviourModifiers.end()) + return; + + std::string message; + BotBehaviour* behaviour = 0; + if (behaviourName.compare("NULL") != 0) + { + behaviour = BotBehaviourManager::m_instance->create(behaviourName, createFunctionName, + patternName, mode, urgeCurveName, + modifiers->second, message); + if (!behaviour) + return; + } + const int id = BotBehaviourManager::m_instance->getBehaviourId(behaviourName); + static_cast(CommonSingletonServer::m_iaiSettingsModifier) + ->addBehaviour(vehicle, id, behaviour); } -void AIConsole::setBasicBotWeights(std::string) +// ELF 0x391500: `m_behaviourModifiers[name]` (operator[]: an unknown name is inserted with a +// null set); a non-null set becomes the bots' basic weights (IAISettingsModifier +0x30). +void AIConsole::setBasicBotWeights(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::setBasicBotWeights"); + float* const weights = m_behaviourModifiers[name]; + if (weights) + static_cast(CommonSingletonServer::m_iaiSettingsModifier) + ->setBasicBotWeights(weights); } -void AIConsole::createBehaviourModifiers(std::string) +// ELF 0x3916E0: a new set of getNumberOfBehaviours() zero weights (the count is re-read every +// iteration) under an unused name, which becomes the active set. An existing name does nothing. +void AIConsole::createBehaviourModifiers(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::createBehaviourModifiers"); + if (m_behaviourModifiers.find(name) != m_behaviourModifiers.end()) + return; + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + float* const weights = new float[settings->getNumberOfBehaviours()]; + for (int i = 0; i < settings->getNumberOfBehaviours(); ++i) + weights[i] = 0.0f; + m_behaviourModifiers.insert(std::pair(name, weights)); + m_activeBehaviourModifiers = m_behaviourModifiers.find(name); } -void AIConsole::setActiveBehaviourModifiers(std::string) +// ELF 0x3918C0. A missing name leaves the current selection unchanged. +void AIConsole::setActiveBehaviourModifiers(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::setActiveBehaviourModifiers"); + const std::map::iterator it = m_behaviourModifiers.find(name); + if (it != m_behaviourModifiers.end()) + m_activeBehaviourModifiers = it; } +// ELF 0x391920. std::string AIConsole::getActiveBehaviourModifiers() { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::getActiveBehaviourModifiers"); + return m_activeBehaviourModifiers == m_behaviourModifiers.end() ? "" : m_activeBehaviourModifiers->first; } -float AIConsole::getBehaviourModifier(std::string) +// ELF 0x391990. +float AIConsole::getBehaviourModifier(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::getBehaviourModifier"); + if (m_activeBehaviourModifiers == m_behaviourModifiers.end()) + return 0.0f; + const int id = BotBehaviourManager::m_instance->getBehaviourId(name); + return id == -1 ? 0.0f : m_activeBehaviourModifiers->second[id]; } -void AIConsole::setBehaviourModifier(std::string, float) +// ELF 0x391A50: one weight of the active set, by behaviour name; an unknown name or no active +// set does nothing. +void AIConsole::setBehaviourModifier(std::string name, float value) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::setBehaviourModifier"); + if (m_activeBehaviourModifiers == m_behaviourModifiers.end()) + return; + const int id = BotBehaviourManager::m_instance->getBehaviourId(name); + if (id == -1) + return; + m_activeBehaviourModifiers->second[id] = value; } -void AIConsole::listBehaviourModifiers() +// ELF 0x391B00. Names are looked up twice per row, as shipped. +std::string AIConsole::listBehaviourModifiers() { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::listBehaviourModifiers"); + if (m_activeBehaviourModifiers == m_behaviourModifiers.end()) + return ""; + std::string result; + char value[256]; + for (int i = 0; i < static_cast(CommonSingletonServer::m_iaiSettings)->getNumberOfBehaviours(); ++i) + { + result += BotBehaviourManager::m_instance->getBehaviourName(i); + result += " = "; + std::sprintf(value, "%f\n", getBehaviourModifier(BotBehaviourManager::m_instance->getBehaviourName(i))); + result += value; + } + return result; } -void AIConsole::addInterpreterEntry(std::string, std::string) +// ELF 0x391250: the entry is looked up first (an unknown name is inserted null and ignored), +// then the vehicle (IAISettings +0x54); IAISettingsModifier +0x1C. +void AIConsole::addInterpreterEntry(std::string vehicleName, std::string entryName) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::addInterpreterEntry"); + BAPEntry* const entry = getBAPEntryFromName(entryName); + if (!entry) + return; + const int vehicle = static_cast(CommonSingletonServer::m_iaiSettings)->getVehicle(vehicleName); + if (vehicle == -1) + return; + static_cast(CommonSingletonServer::m_iaiSettingsModifier) + ->addInterpreterEntry(vehicle, entry); } -void AIConsole::addInterpreterEntry(std::string, std::string, BotLodLevel) +// ELF 0x391310: as above, IAISettingsModifier +0x20. +void AIConsole::addInterpreterEntry(std::string vehicleName, std::string entryName, BotLodLevel lod) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::addInterpreterEntry"); + BAPEntry* const entry = getBAPEntryFromName(entryName); + if (!entry) + return; + const int vehicle = static_cast(CommonSingletonServer::m_iaiSettings)->getVehicle(vehicleName); + if (vehicle == -1) + return; + static_cast(CommonSingletonServer::m_iaiSettingsModifier) + ->addInterpreterEntry(vehicle, lod, entry); } -void AIConsole::removeInterpreterEntry(std::string, std::string, BotLodLevel) +// ELF 0x3913D0: as above, IAISettingsModifier +0x24. +void AIConsole::removeInterpreterEntry(std::string vehicleName, std::string entryName, BotLodLevel lod) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::removeInterpreterEntry"); + BAPEntry* const entry = getBAPEntryFromName(entryName); + if (!entry) + return; + const int vehicle = static_cast(CommonSingletonServer::m_iaiSettings)->getVehicle(vehicleName); + if (vehicle == -1) + return; + static_cast(CommonSingletonServer::m_iaiSettingsModifier) + ->removeInterpreterEntry(vehicle, lod, entry); } -void AIConsole::activateDefaultInterpreter(std::string, BAPStatementType, BotLodLevel) +// ELF 0x391490: a known vehicle gets IAISettingsModifier +0x28. +void AIConsole::activateDefaultInterpreter(std::string vehicleName, BAPStatementType type, BotLodLevel lod) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::activateDefaultInterpreter"); + const int vehicle = static_cast(CommonSingletonServer::m_iaiSettings)->getVehicle(vehicleName); + if (vehicle == -1) + return; + static_cast(CommonSingletonServer::m_iaiSettingsModifier) + ->activateDefaultInterpreter(vehicle, type, lod); } -void AIConsole::addSAIStrategy(int, std::string) +// ELF 0x392990: the side's SAI (IAIMain +0x3C) gets the named strategy (ISAI +0x08 +// addStrategy); an absent AI main, SAI or strategy does nothing. +void AIConsole::addSAIStrategy(int side, std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::addSAIStrategy"); + if (!getActiveAIMain()) + return; + SAI* const sai = getActiveAIMain()->getSAI(side); + if (!sai) + return; + Strategy* const strategy = StrategyManager::getInstance()->getStrategy(name); + if (strategy) + sai->addStrategy(strategy); } -void AIConsole::addSensingAgentPattern(const std::string&, const std::string&) +// ELF 0x3967A0: a known pattern for a known vehicle (IAISettings +0x54 getVehicle) is added +// through IAISettingsModifier +0x80. +void AIConsole::addSensingAgentPattern(const std::string& vehicle, const std::string& patternName) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::addSensingAgentPattern"); + ISensingAgentPattern* const pattern = getSensingAgentPatternFromName(patternName); + if (!pattern) + return; + const int id = static_cast(CommonSingletonServer::m_iaiSettings)->getVehicle(vehicle); + if (id == -1) + return; + static_cast(CommonSingletonServer::m_iaiSettingsModifier) + ->addSensingAgentPattern(id, pattern); } -void AIConsole::setSensingAgentPatternName(const std::string&) +// ELF 0x396860: IAISettingsModifier +0x78. +void AIConsole::setSensingAgentPatternName(const std::string& name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::setSensingAgentPatternName"); + static_cast(CommonSingletonServer::m_iaiSettingsModifier) + ->setSensingAgentPatternName(name); } -void AIConsole::setSensingAgentNullPattern(const std::string&) +// ELF 0x3968A0: IAISettingsModifier +0x7C with the named pattern (null when unknown). +void AIConsole::setSensingAgentNullPattern(const std::string& name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::setSensingAgentNullPattern"); + static_cast(CommonSingletonServer::m_iaiSettingsModifier) + ->setSensingAgentNullPattern(getSensingAgentPatternFromName(name)); } +// ELF 0x396930. Stops at the first absent bot id, rather than scanning the manager's count. void AIConsole::sensingAgentDebug() { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::sensingAgentDebug"); + int id = 0; + while (Bot* bot = IBotManager::instance->getBotFromId(id)) + { + ++id; + bot->getSensingAgent()->m_flag134 = true; + } + if (id) + { + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->setDraw(true); + static_cast(IAIMain::m_instance)->showAll(false); + } } -void AIConsole::addAllowedUnit(const std::string&) +// ELF 0x395E40. The vehicle lookup's -1 result is passed on unchecked. +void AIConsole::addAllowedUnit(const std::string& name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::addAllowedUnit"); + const int vehicle = static_cast(CommonSingletonServer::m_iaiSettings)->getVehicle(name); + AIStrategicObjectManager::getInstance()->getActiveArea()->addAllowedUnit(vehicle); } -void AIConsole::addExpelledUnit(const std::string&) +// ELF 0x395EA0. +void AIConsole::addExpelledUnit(const std::string& name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::addExpelledUnit"); + const int vehicle = static_cast(CommonSingletonServer::m_iaiSettings)->getVehicle(name); + AIStrategicObjectManager::getInstance()->getActiveArea()->addExpelledUnit(vehicle); } -void AIConsole::addLandingZoneUnit(const std::string&) +// ELF 0x395F00. +void AIConsole::addLandingZoneUnit(const std::string& name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::addLandingZoneUnit"); + const int vehicle = static_cast(CommonSingletonServer::m_iaiSettings)->getVehicle(name); + AIStrategicObjectManager::getInstance()->getActiveArea()->addToLandingZoneUsers(vehicle); } -void AIConsole::setVehicleMods(const std::string&, const std::string&) +// ELF 0x396690: the vehicle id is taken unchecked (-1 is passed on); a known modifier set goes to +// IAISettingsModifier +0x10 setVehicleMods. +void AIConsole::setVehicleMods(const std::string& vehicleName, const std::string& modifiersName) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::setVehicleMods"); + const int vehicle = static_cast(CommonSingletonServer::m_iaiSettings)->getVehicle(vehicleName); + const std::map::iterator it = m_behaviourModifiers.find(modifiersName); + if (it == m_behaviourModifiers.end()) + return; + static_cast(CommonSingletonServer::m_iaiSettingsModifier) + ->setVehicleMods(vehicle, it->second); } -void AIConsole::setStandardPersonality(const std::string&, int) +// ELF 0x396720: a known modifier set becomes the side's standard personality +// (IAISettingsModifier +0x50). The ELF answers the low byte of that void call's EAX; the console +// class (297) is void and drops it. +void AIConsole::setStandardPersonality(const std::string& name, int side) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::setStandardPersonality"); + const std::map::iterator it = m_behaviourModifiers.find(name); + if (it == m_behaviourModifiers.end()) + return; + static_cast(CommonSingletonServer::m_iaiSettingsModifier) + ->setStandardPersonality(it->second, side); } +// ELF 0x392AE0. The SAI lookup is discarded; the result is always -1. float AIConsole::getFastThreshold() { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::getFastThreshold"); + if (getActiveAIMain()) + getActiveAIMain()->getSAI(1); + return -1.0f; } +// ELF 0x392A70. The argument is unused and neither SAI is modified. void AIConsole::setFastThreshold(float) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::setFastThreshold"); + if (getActiveAIMain()) + { + getActiveAIMain()->getSAI(1); + getActiveAIMain()->getSAI(2); + } } +// ELF 0x392BA0. The three diagnostic strings are constructed, then discarded. void AIConsole::freeCameraFire() { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::freeCameraFire"); + IAIObjectEnvironment* const environment = + static_cast(CommonSingletonServer::m_iaiObjectEnvironment); + Mat4 camera = {}; + camera.m[0] = camera.m[5] = camera.m[10] = camera.m[15] = 1.0f; + environment->getLocalPlayerCameraTransformation(camera); + const Vec3 start = { camera.m[12], camera.m[13], camera.m[14] }; + const Vec3 end = { start.x + 1000.0f * camera.m[8], + start.y + 1000.0f * camera.m[9], + start.z + 1000.0f * camera.m[10] }; + Vec3 hit = {}; + if (environment->collideLineWithWorld(start, end, 0, &hit)) + { + std::stringstream out; + std::vector text; + out << "Start: " << start.x << '/' << start.y << '/' << start.z; + text.push_back(out.str()); + out.str(""); + out << "End: " << hit.x << '/' << hit.y << '/' << hit.z; + text.push_back(out.str()); + out.str(""); + const Vec3 difference = { hit.x - start.x, hit.y - start.y, hit.z - start.z }; + out << "Distance: " << std::sqrt(difference.x * difference.x + difference.y * difference.y + + difference.z * difference.z) << "m"; + text.push_back(out.str()); + } } -void AIConsole::showAISettings() +// ELF 0x3934C0. The shipped report leaves each vehicle's opening brace unmatched. +std::string AIConsole::showAISettings() { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::showAISettings"); + std::stringstream out; + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + out << "Number of vehicle types: " << settings->getNumberOfVehicles() << std::endl; + out << "Maximum number of bots: " << settings->getMaxNBots() << std::endl; + out << "Number of behaviours: " << settings->getNumberOfBehaviours() << std::endl; + out << "World size (x,z): (" + << static_cast(CommonSingletonServer::m_iaiTerrain)->getWorldSizeX() << ", " + << static_cast(CommonSingletonServer::m_iaiTerrain)->getWorldSizeZ() << ")" << std::endl; + for (int vehicle = 0; vehicle < settings->getNumberOfVehicles(); ++vehicle) + { + out << "Vehicle '" << static_cast(CommonSingletonServer::m_iaiSettings)->getVehicle(vehicle) + << "'" << std::endl; + out << "{" << std::endl; + for (int behaviour = 0; behaviour < settings->getNumberOfBehaviours(); ++behaviour) + { + out << " " << BotBehaviourManager::m_instance->getBehaviourName(behaviour) << ", "; + out << (settings->getPlanGenerator(vehicle, behaviour) ? "HasGenerator=TRUE" : "HasGenerator=FALSE") + << std::endl; + } + } + return out.str(); } -void AIConsole::createLODManager(float, float) +// ELF 0x393B50. ConsoleClass315 discards this string result. +std::string AIConsole::createLODManager(float distance, float speedScale) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::createLODManager"); + std::stringstream out; + if (!AILODManager::m_instance) + { + new AILODManager(distance, speedScale); + out << "LODManager created."; + } + else + out << "LODManager already created."; + return out.str(); } -void AIConsole::saveAll(const std::string&, const std::string&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::saveAll"); -} +namespace { -float AIConsole::getCurrentPitchAngle() +// ELF 0x393E10. Tokenization deliberately uses the copied string's buffer. +bool checkLayerStrList(const std::string& list, int layer) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::getCurrentPitchAngle"); + std::string copy = list; + const std::string wanted = formatString("%d", layer); + char* token = std::strtok(const_cast(copy.c_str()), "|"); + while (token) + { + if (std::string(token) == wanted) + return true; + token = std::strtok(0, "|"); + } + return false; } -float AIConsole::getCurrentYawAngle() +} // namespace + +// ELF 0x394070. Writes the seven sections in retail order; write results are discarded. +bool AIConsole::saveAll(const std::string& directory, const std::string& layers) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::getCurrentYawAngle"); + AIStrategicObjectManager* const manager = AIStrategicObjectManager::getInstance(); + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + const std::string filename = directory + "/AI/StrategicAreas.ai"; + const int groups = settings->getNumberOfVehicleGroups(); + io::File file; + if (!file.open(filename, static_cast(0), io::FILEACCESS_2, 0)) + return false; + + std::ostringstream areas, assignments, landingZones, vehicleGroups, vehicles, categories; + if (groups > 0) + { + vehicleGroups << "rem *** Create vehicle groups ***\n\n"; + for (int i = 0; i < groups; ++i) + { + const std::string& name = settings->getVehicleGroupName(i); + vehicleGroups << "aiSettings.createVehicleGroup " << name << "\n"; + } + vehicleGroups << "\n"; + vehicles << "rem * add vehicles to the groups *\n\n"; + for (int i = 0; i < settings->getNumberOfVehicles(); ++i) + { + const int group = settings->getVehicleGroup(i); + const std::string& name = settings->getVehicleGroupName(group); + vehicles << "aiSettings.addVehicleToVehicleGroup " << i << " " << name << "\n"; + } + vehicles << "\n\n"; + // shipped defect: categories are emitted only when there are vehicle groups. + categories << "rem *** Create categories ***\n\n"; + for (int i = 0; i < manager->getNumberOfCategories(); ++i) + { + const std::string& name = manager->getCategoryName(i); + categories << "aiStrategicArea.createNewCategory " << name << "\n"; + } + categories << "\n"; + } + + areas << "rem *** Create strategic areas ***\n"; + for (std::map::const_iterator it = manager->getStrategicAreas().begin(); + it != manager->getStrategicAreas().end(); ++it) + { + AIStrategicArea* const area = it->second; + if (!layers.empty() && !checkLayerStrList(layers, area->m_i400)) + continue; + const std::string name = it->first; + if (area->m_fromControlPoint) + areas << "aiStrategicArea.createFromControlPoint " << name << " " + << area->m_controlPointId << " " << area->m_size[0]; + else + { + areas << "aiStrategicArea.create " << name << " " << area->m_centre.x << '/' + << area->m_centre.y << " "; + const Vec2& position = area->getPosition(1); + areas << position.x << '/' << position.y << " " << area->m_f148 << " " << area->m_size[0]; + } + if (manager->getNumberOfCategories() > 0) + { + const std::string& category = manager->getCategoryName(area->m_category); + areas << " " << category; + } + areas << "\n"; + areas << "aiStrategicArea.layer " << area->m_i400 << "\n\n"; + assignments << "aiStrategicArea.setActive " << name << "\n"; + + IAISettings* const currentSettings = static_cast(CommonSingletonServer::m_iaiSettings); + const int groupCount = currentSettings->getNumberOfVehicleGroups(); + const int allowed = area->getAllowedVehicleGroups(); + if (allowed != -1) + { + for (int i = 0; i < groupCount; ++i) + if ((allowed >> (i & 31)) & 1) + { + const std::string& group = currentSettings->getVehicleGroupName(i); + assignments << "AIStrategicArea.addAllowedVehicleGroup " << group << "\n"; + } + } + const int expelled = area->getExpelledVehicleTypes(); + const int vehicleCount = currentSettings->getNumberOfVehicles(); + if (expelled) + { + for (int i = 0; i < vehicleCount; ++i) + if ((expelled >> (i & 31)) & 1) + { + const std::string& vehicle = currentSettings->getVehicle(i); + assignments << "AIStrategicArea.addExpelledUnit " << vehicle << "\n"; + } + } + const int landingZoneVehicles = currentSettings->getNumberOfVehicles(); + for (int i = 0; i < landingZoneVehicles; ++i) + if (area->isLandingZoneUser(i)) + { + const std::string& vehicle = currentSettings->getVehicle(i); + assignments << "AIStrategicArea.addLandingZoneUnit " << vehicle << "\n"; + } + + const std::vector zones = area->getLandingZones(); + for (std::vector::const_iterator zone = zones.begin(); zone != zones.end(); ++zone) + { + if (!*zone) + continue; + const LandingZoneDirection beach = (*zone)->getBeachDirection(); + landingZones << "AILandingZone.createLandingZone " << (*zone)->getName() << " "; + const Vec2& minimum = (*zone)->getMinCorner(); + landingZones << minimum.x << '/' << minimum.y << " "; + const Vec2& maximum = (*zone)->getMaxCorner(); + landingZones << maximum.x << '/' << maximum.y << " " << beach << "\n\n"; + assignments << "AIStrategicArea.attachLandingZone " << (*zone)->getName() << "\n"; + } + if (!zones.empty() && landingZoneVehicles < 1) + assignments << "AIStrategicArea.addLandingZoneUnit LandingCraft\n"; + + const std::vector neighbours = area->m_neighbours; + for (std::vector::const_iterator neighbour = neighbours.begin(); + neighbour != neighbours.end(); ++neighbour) + assignments << "AIStrategicArea.addNeighbour " + << static_cast(*neighbour)->m_name << "\n"; + const int flags = area->getObjectTypeFlags(); + for (int i = 1; i < 21; ++i) + if ((flags >> i) & 1) + assignments << "aiStrategicArea.addObjectTypeFlag " + << static_cast(i) << "\n"; + for (int i = 0; i < IAIPathfinding::instance->getNumberOfMaps(); ++i) + if (IAIPathfinding::instance->isMapUsed(i)) + { + const std::string& map = IAIPathfinding::instance->getMapNameFromId(i); + assignments << "AIStrategicArea.setOrderPosition " << map << " "; + const Vec3 position = area->getOrderPos(i, 1); + assignments << position.x << '/' << position.y << '/' << position.z << "\n"; + } + assignments << "aiStrategicArea.setSide " << area->getSide() << "\n"; + if (std::fabs(area->m_f396 - area->m_size[0]) > 0.25f) + assignments << "aiStrategicArea.vehicleSearchRadius " << area->m_f396 << "\n"; + if (!area->m_sideEnabled[0]) + assignments << "aiStrategicArea.setTakeable 1 0\n"; + if (!area->m_sideEnabled[1]) + assignments << "aiStrategicArea.setTakeable 2 0\n"; + assignments << "\n"; + } + + std::ostringstream waypoints; + manager->streamWaypoints(waypoints, layers); + file.write(vehicleGroups); + file.write(vehicles); + file.write(categories); + file.write(areas); + file.write(landingZones); + file.write(assignments); + file.write(waypoints); + file.close(); + return true; } -// Console binding for ai.init. Calls may reach named stops in dependent subsystems. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. - -namespace { - -const char* const kAiConsoleTag = "ai"; - -void consoleAiInit(int n) +// ELF 0x396180. Projects both forward directions onto XZ before comparing them. +float AIConsole::getCurrentPitchAngle() const { - // Requires AIConsole initialization before level scripts invoke this command. - AIConsole::m_instance->init(n); + IAIPlayer* const player = static_cast(CommonSingletonServer::m_iaiPlayerFactory) + ->getPlayerFromLocalHumanPlayer(); + if (!player) + return -1.0f; + const Mat4& camera = *static_cast(player->getCameraTransformation()); + Vec3 first = { camera.m[8], 0.0f, camera.m[10] }; + const auto normalize = [](Vec3& v) { + const float lengthSqr = v.x * v.x + v.y * v.y + v.z * v.z; + if (!(std::fabs(lengthSqr - 1.0f) < 1.1920928955078125e-7f)) + { + if (std::fabs(lengthSqr) < 1.1920928955078125e-7f) + v = Vec3(); + else + { + const float scale = 1.0f / std::sqrt(lengthSqr); + v.x *= scale; v.y *= scale; v.z *= scale; + } + } + }; + normalize(first); + IAIObject* const vehicle = player->getCurrentVehicle(); + Vec3 second; + second.x = vehicle->getTransformation().m[8]; + second.y = 0.0f; + second.z = vehicle->getTransformation().m[10]; + normalize(second); + float dot = second.x * first.x + second.y * first.y + second.z * first.z; + if (dot < -1.0f) dot = -1.0f; + if (dot > 1.0f) dot = 1.0f; + return std::acos(dot) * 57.2957763671875f; } -} // anonymous namespace - -BF2_CONSOLE_OBJECT("ai", 2, 0) -BF2_CONSOLE_METHOD_1(init, consoleAiInit, int, kAiConsoleTag) - -// Handed to the console registry by AIModule::init. -ConsoleObjectList& aiConsoleObjects() +// ELF 0x396410. Projects onto YZ, retaining the shipped pitch/yaw naming. +float AIConsole::getCurrentYawAngle() const { - return consoleBindingList(kAiConsoleTag); + IAIPlayer* const player = static_cast(CommonSingletonServer::m_iaiPlayerFactory) + ->getPlayerFromLocalHumanPlayer(); + if (!player) + return -1.0f; + const Mat4& camera = *static_cast(player->getCameraTransformation()); + Vec3 first = { 0.0f, camera.m[9], camera.m[10] }; + const auto normalize = [](Vec3& v) { + const float lengthSqr = v.x * v.x + v.y * v.y + v.z * v.z; + if (!(std::fabs(lengthSqr - 1.0f) < 1.1920928955078125e-7f)) + { + if (std::fabs(lengthSqr) < 1.1920928955078125e-7f) + v = Vec3(); + else + { + const float scale = 1.0f / std::sqrt(lengthSqr); + v.x *= scale; v.y *= scale; v.z *= scale; + } + } + }; + normalize(first); + IAIObject* const vehicle = player->getCurrentVehicle(); + Vec3 second; + second.x = 0.0f; + second.y = vehicle->getTransformation().m[9]; + second.z = vehicle->getTransformation().m[10]; + normalize(second); + float dot = second.x * first.x + second.y * first.y + second.z * first.z; + if (dot < -1.0f) dot = -1.0f; + if (dot > 1.0f) dot = 1.0f; + return std::acos(dot) * 57.2957763671875f; } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIConsole.h b/Code/BF2/AI/AIDLL/AI/Main/AIConsole.h index 215f5e452..1f1e741cb 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIConsole.h +++ b/Code/BF2/AI/AIDLL/AI/Main/AIConsole.h @@ -1,7 +1,5 @@ // Bot Action Plan registry and AI commands, recovered from the symbolized libaidll.so. // AI/Main/AIConsole.cpp is attested; this header path is [INFERRED]. -// frontier: the constructor omits MapProperties; teardown, reset and most commands remain unwritten. -// [RETIRE-WHEN: aidll-02-skeleton] Complete those bodies and the missing constructor state. #ifndef AI_AIDLL_AI_MAIN_AICONSOLE_H #define AI_AIDLL_AI_MAIN_AICONSOLE_H @@ -16,6 +14,7 @@ namespace hfe { namespace ai { class BAPEntry; +class Bot; class IAIMain; class ISensingAgentPattern; class MapProperties; @@ -49,17 +48,18 @@ class AIConsole // constructs SquadManager. It returns void: the binding emits no result // and the two exits do not materialize a common return value. void init(int); - void addBot(std::string, int, std::string, std::string); - void addUnspawnedBot(std::string, int, std::string); + int addBot(std::string, int, std::string, std::string); // ConsoleClass186 stores the int + int addUnspawnedBot(std::string, int, std::string); // ConsoleClass187 stores the int void updateBot(int); - void killBotName(const std::string&); - void killBotId(int); + std::string killBotName(const std::string&); // ConsoleClass191 assigns the string + std::string killBotId(int); // ConsoleClass190 assigns the string void killAllBots(); - void* getBotFromId(int); + Bot* getBotFromId(int); void botMoveTo(float, Vec3, int); void botFlyTo(int, float, float, float, Vec3); - void botSetWaypoints_Patrol(int, float, int, Vec3, Vec3, Vec3); - void botSetWaypoints_Patrol3d(int, float, int, Vec3, Vec3, Vec3); + // ConsoleClass196/197 pass a zero Vec3 for an omitted sixth argument [INFERRED spelling: value-initialised]. + void botSetWaypoints_Patrol(int, float, int, Vec3, Vec3, Vec3 = Vec3()); + void botSetWaypoints_Patrol3d(int, float, int, Vec3, Vec3, Vec3 = Vec3()); void botGiveOrder(int, std::string, std::string); // Behaviors and modifier weights. @@ -74,7 +74,7 @@ class AIConsole std::string getActiveBehaviourModifiers(); float getBehaviourModifier(std::string); void setBehaviourModifier(std::string, float); - void listBehaviourModifiers(); + std::string listBehaviourModifiers(); // ConsoleClass310 assigns the string // Plan interpreter. void addInterpreterEntry(std::string, std::string); @@ -101,12 +101,12 @@ class AIConsole Vec3 getRendCameraRotation(); // ; retail returns zero void freeCameraFire(); void removeCameraText(); // ; retail no-op - void showAISettings(); - void createLODManager(float, float); - void saveAll(const std::string&, const std::string&); + std::string showAISettings(); // ConsoleClass311 assigns the string + std::string createLODManager(float, float); // ConsoleClass315 discards the string + bool saveAll(const std::string&, const std::string&); // ConsoleClass476 stores the bool void debug(); // ; retail no-op - float getCurrentPitchAngle(); - float getCurrentYawAngle(); + float getCurrentPitchAngle() const; + float getCurrentYawAngle() const; // Neither body uses this. Keep member declarations: getFastThreshold calls through an object; // identical-code folding prevents establishing staticness from these bodies alone. @@ -121,14 +121,13 @@ class AIConsole /* +16 */ std::map::iterator m_activeBehaviourModifiers; // [INFERRED] /* +20 */ std::map m_bapEntries; // 42 owned primitives /* +32 */ std::map m_strategies; // [INFERRED] name - /* +44 */ char m_gap44[4]; // [UNRESOLVED] + /* +44 */ char m_gap44[4]; // [UNRESOLVED]; constructor zeroes this word /* +48 */ std::map m_sensingAgentPatterns; // 4 owned patterns - // Retail construction allocates MapProperties and calls setMaxSlope. Its destination is - // [UNRESOLVED], so that allocation is not implemented here. + // Retail construction allocates MapProperties and calls setMaxSlope, then loses the pointer. // init writes +60; getActiveAIMain reads the static instance instead. Other readers of this // cached pointer are [UNRESOLVED]; do not assume it is dead. /* +60 */ AIMain* m_aiMain; - /* +64 */ char m_gap64[4]; // [UNRESOLVED]; this is the one that may be the MapProperties* + /* +64 */ char m_gap64[4]; // [UNRESOLVED]; unwritten by the constructor // Published by the constructor ( via GOT ), cleared by retail teardown. // BF2AI::clear deletes through this pointer. diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIDllFrontier.h b/Code/BF2/AI/AIDLL/AI/Main/AIDllFrontier.h index 4a72faa85..015ee1906 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIDllFrontier.h +++ b/Code/BF2/AI/AIDLL/AI/Main/AIDllFrontier.h @@ -1,6 +1,7 @@ // [CHOSEN, not recovered] Reports a missing AI DLL method to stderr, flushes, and aborts. // The argument is its fully qualified name as a string literal. This macro never returns. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. +// The stop mechanism itself, not a stop: since dbg/ai-frontiers no Code/BF2/AI code calls it (the +// header is still included in many files). [RETIRE-WHEN: aidll-02-skeleton] remove with the includes. #ifndef AI_AIDLL_AI_MAIN_AIDLLFRONTIER_H #define AI_AIDLL_AI_MAIN_AIDLLFRONTIER_H diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIDllTypes.h b/Code/BF2/AI/AIDLL/AI/Main/AIDllTypes.h index b0455e2ff..b4c2a125c 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIDllTypes.h +++ b/Code/BF2/AI/AIDLL/AI/Main/AIDllTypes.h @@ -13,14 +13,14 @@ namespace hfe { namespace world { // AIEventCourier::eventMissileLock's second parameter. Passed by pointer only. -class MissileLockMessage; +struct MissileLockMessage; } // namespace world namespace ai { // knowledge records -class Information; // the SpHandlePool payload; see AIKnowledge/InformationManager.h -class WeaponInfo; // likewise; see AIKnowledge/WeaponInfoManager.h +class Information; // the SpHandlePool payload; see Main/InformationManager.h +class WeaponInfo; // likewise; see AIUtils/WeaponInfoManager.h // the bot itself // `Bot*` and `unsigned int` appear as alternative first arguments on the same DPManager creators diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIEventCourier.cpp b/Code/BF2/AI/AIDLL/AI/Main/AIEventCourier.cpp index 79377ee7e..bee618aca 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIEventCourier.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/AIEventCourier.cpp @@ -1,4 +1,5 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining AIEventCourier operations. +// static init: ELF 0x3998D0 (__tcf_0 0x399930, _GLOBAL__I 0x399960): 's Init object only. +#include #include "AIEventCourier.h" @@ -7,11 +8,26 @@ #include "../../../../Core/ClassManager.h" #include "../../../../Core/Debug.h" // the map-part events' fatal Debugs #include "CommonSingletonServer.h" -#include "AIDllFrontier.h" #include "IAIPathfinding.h" // IAIPathfindingSetup::initMaps #include "../AIStrategicEntity/AIStrategicObjectManager.h" // postLoadInitAreas #include "AIMain.h" // IAIMain::spawnBots -#include "../AIBot/SquadManager.h" // squad notification forwarders +#include "../AIBot/SquadManager.h" +#include "../AIBot/SquadMember.h" // squad notification forwarders +#include "../AIUtils/DebugRendering/AIRenderUtil.h" // event_worldReset +#include "../DrawPrimitives/DPManager.h" // event_worldReset +#include "CommunicationHub.h" // event_worldReset +#include "IBotManager.h" // the bot-state forwarders +#include "AILODManager.h" // eventPlayerDisconnect +#include "AIConsole.h" // event_freeCameraFire +#include "../AIBot/BotMain.h" // event_isRepaired +#include "../AIStrategic/SAI.h" // the commander and request events +#include "../AIKnowledge/Information.h" // eventManDown +#include "InformationManager.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" // IAIObjectUnit - eventMissileLock +#include "../../../AIInterface/BFKnowledge/BFGame.h" // eventDrawDebug +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" // event_incomingArtillery namespace dice { namespace hfe { @@ -20,172 +36,259 @@ extern ClassManager* classManager; namespace ai { -// IAIEventCourier +// ELF 0x3E6280 / 0x3E6390. IAIEventCourier::IAIEventCourier() { if (!classManager->getSimpleSingleton("IAIEventCourier")) classManager->registerSimpleSingleton("IAIEventCourier", this); } +// ELF 0x3E64A0 / 0x3E6590 / 0x3E6680. IAIEventCourier::~IAIEventCourier() { if (classManager->getSimpleSingleton("IAIEventCourier") == this) classManager->unregisterSimpleSingleton("IAIEventCourier"); } -// Stateless event courier; construction requires only the base-class initialization. +// ELF 0x398570 / 0x3985B0. Stateless; construction only initializes the base. AIEventCourier::AIEventCourier() { } -// The vptr reset and the base call, which again is what C++ emits. +// ELF 0x3985F0 / 0x398630 / 0x398670. Member and base teardown only. AIEventCourier::~AIEventCourier() { } -void AIEventCourier::eventMissileLock(IAIObject *, world::MissileLockMessage *) +// ELF 0x3986B0: the locked object's unit plug-in (IAIObject +0x98 getUnit) gets +// IAIObjectUnit +0x78 setMissileLockStatus(1). The message pointer is not read. +void AIEventCourier::eventMissileLock(IAIObject* object, world::MissileLockMessage*) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::eventMissileLock"); + if (object) + { + IAIObjectUnit* const unit = object->getUnit(); + if (unit) + unit->setMissileLockStatus(1); + } } -int AIEventCourier::eventPlayerSpawned(int) +// ELF 0x3986F0: IBotManager +0x38 setBotIsAlive, unguarded. +void AIEventCourier::eventPlayerSpawned(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::eventPlayerSpawned"); + IBotManager::instance->setBotIsAlive(playerId); } -void AIEventCourier::eventPlayerKilled(int, int) +// ELF 0x398780: IBotManager +0x34 setBotIsDead (unguarded), then the guarded squad member's +// squadMemberKilled. The second argument is the side the squad lookup uses. +void AIEventCourier::eventPlayerKilled(int playerId, int side) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::eventPlayerKilled"); + IBotManager::instance->setBotIsDead(playerId); + if (SquadManager::m_instance) + { + SquadMember* const member = SquadManager::m_instance->getSquadMember(playerId, side); + if (member) + member->squadMemberKilled(); + } } -// Notifies the active AI runtime that a player was created, if the runtime exists. +// ELF 0x398740. Notifies the active AI runtime, when present, of player creation. void AIEventCourier::eventPlayerCreated(bool isAI) { if (IAIMain::m_instance) IAIMain::m_instance->newPlayerCreated(isAI); // IAIMain vtable +0x20 } +// ELF 0x398730 is a bare `ret`: the kit change is not forwarded. void AIEventCourier::eventChangedKit(KitType) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::eventChangedKit"); } -void AIEventCourier::eventPlayerDisconnect(int) +// ELF 0x3987F0: the LOD manager drops the player (when it exists). With an AI main, a leaving +// bot is deactivated (IAIMain +0x1C); for anyone else IAIMain +0x24 reactivateBot runs, which +// refills the bot population. +void AIEventCourier::eventPlayerDisconnect(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::eventPlayerDisconnect"); + if (AILODManager::m_instance) + AILODManager::m_instance->removePlayer(playerId); + if (IAIMain::m_instance) + { + if (IBotManager::instance->getBotFromPlayerId(playerId)) + IAIMain::m_instance->deactivateBot(playerId); + else + IAIMain::m_instance->reactivateBot(playerId); + } } -int AIEventCourier::eventPlayerEnterVehicle(int, IAIObject *, IAIObject *) +// ELF 0x398880: IBotManager +0x30 setBotChangedVehicle(player, first object); the second +// object is not read. +void AIEventCourier::eventPlayerEnterVehicle(int playerId, IAIObject* vehicle, IAIObject*) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::eventPlayerEnterVehicle"); + IBotManager::instance->setBotChangedVehicle(playerId, vehicle); } -int AIEventCourier::eventPlayerExitVehicle(IAIObject *, int) +// ELF 0x3988C0: IAIMain +0x60 setPlayerExitedVehicle, unguarded. +void AIEventCourier::eventPlayerExitVehicle(IAIObject* vehicle, int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::eventPlayerExitVehicle"); + IAIMain::m_instance->setPlayerExitedVehicle(vehicle, playerId); } +// ELF 0x398900: draws only while the game is playing (IAIGame +0x60 isPlaying). void AIEventCourier::eventDrawDebug() { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::eventDrawDebug"); + IAIGame* const game = static_cast(CommonSingletonServer::m_iaiGame); + if (game && game->isPlaying()) + IAIMain::m_instance->draw(); } -// Starts bot spawning when the game-start event arrives. -// [CHOSEN, not recovered] Returns zero; the original scalar return contract is unverified. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. -int AIEventCourier::eventGameStart() +// ELF 0x398950. Starts bot spawning without producing a scalar result. +void AIEventCourier::eventGameStart() { IAIMain::m_instance->spawnBots(); // IAIMain vtable +0x54 - - return 0; // [CHOSEN, not recovered] - see above } +// ELF 0x398980 is a bare `ret`. void AIEventCourier::event_roundEnd() { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_roundEnd"); } +// ELF 0x398990: four guarded resets, in this order. AIRenderUtil and CommunicationHub are +// direct calls; the DP manager is reached through its singleton interface (+0x64 deleteAll, +// result dropped) and the AI main through IAIMain +0x4C resetLevel. void AIEventCourier::event_worldReset() { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_worldReset"); + if (AIRenderUtil::m_instance) + AIRenderUtil::m_instance->unrenderAll(); + if (CommonSingletonServer::m_iDPManager) + static_cast(CommonSingletonServer::m_iDPManager)->deleteAll(); + if (IAIMain::m_instance) + IAIMain::m_instance->resetLevel(); + if (CommunicationHub::m_instance) + CommunicationHub::m_instance->reset(); } -int AIEventCourier::eventManDown(int, IAIObject *) +// ELF 0x398A00: IBotManager +0x3C setBotIsManDown; then, for a sided object, the opposing +// side's information about it (IAIObject +0xB8 getInformation(side == 1 ? 2 : 1), resolved +// inline through the information pool) has its physical plug-in's health set to 0 +// (IPIPhysical +0x18 setHealth, the 0.0f constant at ELF 0x49CB34). +void AIEventCourier::eventManDown(int playerId, IAIObject* object) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::eventManDown"); + IBotManager::instance->setBotIsManDown(playerId, object); + const int side = object->getSide(); + if (side) + { + Information* const information = + informationManager->getInformation(object->getInformation((side == 1) + 1)); + if (information) + information->getPhysical()->setHealth(0.0f); + } } -int AIEventCourier::eventRevived(int, IAIObject *) +// ELF 0x398AC0: IBotManager +0x40 setBotIsRevived, unguarded. +void AIEventCourier::eventRevived(int playerId, IAIObject* object) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::eventRevived"); + IBotManager::instance->setBotIsRevived(playerId, object); } -int AIEventCourier::eventRadioMessage(const AIRadioMessageSettings&, int, int) +// ELF 0x398B00: the hub filters and delivers the message; the fourth argument is false. +void AIEventCourier::eventRadioMessage(const AIRadioMessageSettings& settings, int a, int b) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::eventRadioMessage"); + CommunicationHub::m_instance->filterAndReceiveAIRadioMessage(settings, a, b, false); } -int AIEventCourier::event_mineRemoved(unsigned int) +// ELF 0x398ED0: IBotManager +0x6C removeMineTarget, unguarded. +void AIEventCourier::event_mineRemoved(unsigned int handle) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_mineRemoved"); + IBotManager::instance->removeMineTarget(handle); } -int AIEventCourier::event_enemySpotted(IAIObject *, unsigned char) +// ELF 0x398F10: forwarded to the hub unchanged. +void AIEventCourier::event_enemySpotted(IAIObject* object, unsigned char value) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_enemySpotted"); + CommunicationHub::m_instance->enemySpottedByHuman(object, value); } -int AIEventCourier::event_isRepaired(int) +// ELF 0x398F50: a bot player's BotMain +0x1E0 setIsRepaired(true). The slot lies past the +// Bot interface's last declared one (+0x1DC); BotMain is the only Bot in the image. +void AIEventCourier::event_isRepaired(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_isRepaired"); + Bot* const bot = IBotManager::instance->getBotFromPlayerId(playerId); + if (bot) + static_cast(bot)->setIsRepaired(true); } -void AIEventCourier::event_requestNewOrders(int, int) +// ELF 0x3991A0: guarded SquadManager::repeatOrder with the two arguments swapped. +void AIEventCourier::event_requestNewOrders(int a, int b) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_requestNewOrders"); + if (SquadManager::m_instance) + SquadManager::m_instance->repeatOrder(b, a); // ELF 0x3991D1 } -void AIEventCourier::event_recievedAttackCommanderOrder(int) +// ELF 0x398B90: guarded SquadManager::setSquadReceivedOrder(BotSquad::OrderType 0, squad, true). +void AIEventCourier::event_recievedAttackCommanderOrder(int squadId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_recievedAttackCommanderOrder"); + if (SquadManager::m_instance) + SquadManager::m_instance->setSquadReceivedOrder(BotSquad::OrderAttack, squadId, true); } -void AIEventCourier::event_recievedDefendCommanderOrder(int) +// ELF 0x398BE0: guarded SquadManager::setSquadReceivedOrder(BotSquad::OrderType 1, squad, true). +void AIEventCourier::event_recievedDefendCommanderOrder(int squadId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_recievedDefendCommanderOrder"); + if (SquadManager::m_instance) + SquadManager::m_instance->setSquadReceivedOrder(BotSquad::OrderDefend, squadId, true); } -void AIEventCourier::event_recievedMoveCommanderOrder(int) +// ELF 0x398C30: guarded SquadManager::setSquadReceivedOrder(BotSquad::OrderType 2, squad, true). +void AIEventCourier::event_recievedMoveCommanderOrder(int squadId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_recievedMoveCommanderOrder"); + if (SquadManager::m_instance) + SquadManager::m_instance->setSquadReceivedOrder(BotSquad::OrderMove, squadId, true); } -void AIEventCourier::event_incomingArtillery(int, Vec2) +// ELF 0x398C80: guarded; the 2D position gets the terrain altitude (IAITerrain +0x14 +// getTerrainAltitude(x, z)) as its y, and SquadManager::incomingArtillery(Vec3, side) follows. +void AIEventCourier::event_incomingArtillery(int side, Vec2 position) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_incomingArtillery"); + if (SquadManager::m_instance) + { + const float height = static_cast(CommonSingletonServer::m_iaiTerrain) + ->getTerrainAltitude(position.x, position.y); + Vec3 impact; + impact.x = position.x; + impact.y = height; + impact.z = position.y; + SquadManager::m_instance->incomingArtillery(impact, side); + } } -int AIEventCourier::event_receivedArtilleryRequest(int, int, Vec3) +// ELF 0x398D10: the side's SAI (IAIMain +0x3C getSAI) gets SAI +0x54 playerRequestsArtillery(player, position). +// The ELF returns the SAI's bool in EAX unchanged. +int AIEventCourier::event_receivedArtilleryRequest(int side, int playerId, Vec3 position) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_receivedArtilleryRequest"); + return IAIMain::m_instance->getSAI(side)->playerRequestsArtillery(playerId, position); } -int AIEventCourier::event_receivedUavRequest(int, int, Vec3) +// ELF 0x398D80: the side's SAI (IAIMain +0x3C getSAI) gets SAI +0x58 playerRequestsUav(player, position). +// The ELF returns the SAI's bool in EAX unchanged. +int AIEventCourier::event_receivedUavRequest(int side, int playerId, Vec3 position) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_receivedUavRequest"); + return IAIMain::m_instance->getSAI(side)->playerRequestsUav(playerId, position); } -int AIEventCourier::event_receivedSupplyRequest(int, int, Vec3) +// ELF 0x398DF0: the side's SAI (IAIMain +0x3C getSAI) gets SAI +0x5C playerRequestsSupply(player, position). +// The ELF returns the SAI's bool in EAX unchanged. +int AIEventCourier::event_receivedSupplyRequest(int side, int playerId, Vec3 position) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_receivedSupplyRequest"); + return IAIMain::m_instance->getSAI(side)->playerRequestsSupply(playerId, position); } -int AIEventCourier::event_receivedVehicleDropRequest(int, int, Vec3) +// ELF 0x398E60: the side's SAI (IAIMain +0x3C getSAI) gets SAI +0x60 playerRequestsVehicleDrop(player, position). +// The ELF returns the SAI's bool in EAX unchanged. +int AIEventCourier::event_receivedVehicleDropRequest(int side, int playerId, Vec3 position) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_receivedVehicleDropRequest"); + return IAIMain::m_instance->getSAI(side)->playerRequestsVehicleDrop(playerId, position); } -// Both guard the singleton and forward the +// ELF 0x398FA0. Guards the singleton and forwards the // unchanged squad id through IAIMain +0x68 / +0x64. The concrete AIMain callback is empty // in both images ; this courier still performs the virtual call. void AIEventCourier::event_commanderOrderAccepted(int squadId) @@ -194,27 +297,33 @@ void AIEventCourier::event_commanderOrderAccepted(int squadId) IAIMain::m_instance->commanderOrderAccepted(squadId); } -void AIEventCourier::event_commanderOrderRejected(int) +// ELF 0x398FE0: guarded IAIMain +0x6C, the same shape as event_commanderOrderAccepted. +void AIEventCourier::event_commanderOrderRejected(int squadId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_commanderOrderRejected"); + if (IAIMain::m_instance) + IAIMain::m_instance->commanderOrderRejected(squadId); } -int AIEventCourier::event_appliedForCommander(int) +// ELF 0x399020: IAIMain +0x70, unguarded. +void AIEventCourier::event_appliedForCommander(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_appliedForCommander"); + IAIMain::m_instance->appliedForCommander(playerId); } -int AIEventCourier::event_acceptedCommander(int, int) +// ELF 0x399060: the second argument's SAI gets SAI +0x4C setPlayerIsCommander(true), unguarded. +void AIEventCourier::event_acceptedCommander(int, int side) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_acceptedCommander"); + IAIMain::m_instance->getSAI(side)->setPlayerIsCommander(true); } -void AIEventCourier::event_resignAsCommander(int, int) +// ELF 0x3990B0: guarded; setPlayerIsCommander(false) on the second argument's SAI. +void AIEventCourier::event_resignAsCommander(int, int side) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_resignAsCommander"); + if (IAIMain::m_instance) + IAIMain::m_instance->getSAI(side)->setPlayerIsCommander(false); } -// Only the SquadManager singleton is guarded; +// ELF 0x398B50. Only the SquadManager singleton is guarded; // the manager receives the original one-based side and squad id without validation here. void AIEventCourier::eventNewSquadLeader(int side, int squadId) { @@ -222,7 +331,7 @@ void AIEventCourier::eventNewSquadLeader(int side, int squadId) SquadManager::m_instance->newSquadLeader(side, squadId); } -// The order is player id, squad id, side. +// ELF 0x399100. The order is player id, squad id, side. // Both images pass all three integers unchanged after testing the manager singleton. void AIEventCourier::event_joinedSquad(int playerId, int squadId, int side) { @@ -230,67 +339,82 @@ void AIEventCourier::event_joinedSquad(int playerId, int squadId, int side) SquadManager::m_instance->playerJoinsSquad(playerId, squadId, side); } -void AIEventCourier::event_removedFromSquad(int, int, int) +// ELF 0x399150: forwarded unchanged to the squad manager when it exists. +void AIEventCourier::event_removedFromSquad(int playerId, int squadId, int side) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_removedFromSquad"); + if (SquadManager::m_instance) + SquadManager::m_instance->playerRemovedFromSquad(playerId, squadId, side); } -void AIEventCourier::event_recievedAttackSquadOrder(int) +// ELF 0x3991E0: guarded SquadManager::setSquadReceivedOrder(BotSquad::OrderType 0, squad, false). +void AIEventCourier::event_recievedAttackSquadOrder(int squadId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_recievedAttackSquadOrder"); + if (SquadManager::m_instance) + SquadManager::m_instance->setSquadReceivedOrder(BotSquad::OrderAttack, squadId, false); } -void AIEventCourier::event_recievedDefendSquadOrder(int) +// ELF 0x399230: guarded SquadManager::setSquadReceivedOrder(BotSquad::OrderType 1, squad, false). +void AIEventCourier::event_recievedDefendSquadOrder(int squadId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_recievedDefendSquadOrder"); + if (SquadManager::m_instance) + SquadManager::m_instance->setSquadReceivedOrder(BotSquad::OrderDefend, squadId, false); } -void AIEventCourier::event_recievedMoveSquadOrder(int) +// ELF 0x399280: guarded SquadManager::setSquadReceivedOrder(BotSquad::OrderType 2, squad, false). +void AIEventCourier::event_recievedMoveSquadOrder(int squadId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_recievedMoveSquadOrder"); + if (SquadManager::m_instance) + SquadManager::m_instance->setSquadReceivedOrder(BotSquad::OrderMove, squadId, false); } -void AIEventCourier::event_receivedRepairSquadOrder(int) +// ELF 0x3992D0: guarded SquadManager::setSquadReceivedOrder(BotSquad::OrderType 3, squad, false). +void AIEventCourier::event_receivedRepairSquadOrder(int squadId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_receivedRepairSquadOrder"); + if (SquadManager::m_instance) + SquadManager::m_instance->setSquadReceivedOrder(static_cast(3), squadId, false); } +// ELF 0x399320 and 0x399330 are bare `ret`s. void AIEventCourier::event_squadOrderAccepted(int, int) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_squadOrderAccepted"); } void AIEventCourier::event_squadOrderRejected(int, int) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_squadOrderRejected"); } -int AIEventCourier::event_botTeamKilled(int, int) +// ELF 0x399340: IBotManager +0x60 setBotTeamKilled, unguarded. +void AIEventCourier::event_botTeamKilled(int a, int b) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_botTeamKilled"); + IBotManager::instance->setBotTeamKilled(a, b); } -int AIEventCourier::event_freeCameraFire(bool) +// ELF 0x399380: IAIPathfinding +0xF0 searchPointSelected(!fire), then the console's +// freeCameraFire. Neither singleton is tested. +void AIEventCourier::event_freeCameraFire(bool fire) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_freeCameraFire"); + IAIPathfinding::instance->searchPointSelected(!fire); + AIConsole::m_instance->freeCameraFire(); } +// ELF 0x399780: guarded SquadManager::removeAllSquads. void AIEventCourier::event_removeAllSquadMembers() { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_removeAllSquadMembers"); + if (SquadManager::m_instance) + SquadManager::m_instance->removeAllSquads(); } -// Forwards destroyable-map and bridge events to pathfinding and strategic owners. +// ELF 0x3993D0. Forwards map-part initialization unchanged, including the bool argument. // Requires initialized owners; negative map-part IDs emit an error diagnostic. -int AIEventCourier::event_retrievePathfindingMapId(int& mapPartId, bool walkable, const Vec3& minCorner, +void AIEventCourier::event_retrievePathfindingMapId(int& mapPartId, bool walkable, const Vec3& minCorner, const Vec3& maxCorner, const Mat4& transformation) { IAIPathfinding::instance->initializeDestroyableMapPart(mapPartId, walkable, minCorner, maxCorner, transformation); // +0xE0 / PE +0xDC - return 0; // [CHOSEN, not recovered] - see above } -int AIEventCourier::event_pathfindingMapIdDestroyed(int mapPartId, IAIObject* object) +// ELF 0x399430. +void AIEventCourier::event_pathfindingMapIdDestroyed(int mapPartId, IAIObject* object) { if (mapPartId < 0) { @@ -303,16 +427,16 @@ int AIEventCourier::event_pathfindingMapIdDestroyed(int mapPartId, IAIObject* ob if (object) AIStrategicObjectManager::getInstance()->removeBridgeSegment(object); } - return 0; // [CHOSEN, not recovered] - see above } -int AIEventCourier::event_pathfindingMapIdRestored(int mapPartId) +// ELF 0x399580. +void AIEventCourier::event_pathfindingMapIdRestored(int mapPartId) { IAIPathfinding::instance->restoreMapPart(mapPartId); // +0xE8 / PE +0xE4 - return 0; // [CHOSEN, not recovered] - see above } -int AIEventCourier::event_pathfindingMapIdRestoreOriginalMaterials(int mapPartId, IAIObject* object) +// ELF 0x3995C0. +void AIEventCourier::event_pathfindingMapIdRestoreOriginalMaterials(int mapPartId, IAIObject* object) { if (mapPartId < 0) { @@ -325,49 +449,47 @@ int AIEventCourier::event_pathfindingMapIdRestoreOriginalMaterials(int mapPartId if (object) AIStrategicObjectManager::getInstance()->removeBridgeSegment(object); } - return 0; // [CHOSEN, not recovered] - see above } -// The int lands in the segment's +4, [UNRESOLVED] (see AIStrategicObjectManager::BridgeSegment). -int AIEventCourier::event_bridgeDestroyed(IAIObject* object, int value) +// ELF 0x399710. The int lands in the segment's +4, [UNRESOLVED] (see AIStrategicObjectManager::BridgeSegment). +void AIEventCourier::event_bridgeDestroyed(IAIObject* object, int value) { AIStrategicObjectManager::getInstance()->bridgeSegmentDestroyed(object, value); - return 0; // [CHOSEN, not recovered] - see above } -int AIEventCourier::event_bridgeRepaired(IAIObject* object) +// ELF 0x399750. +void AIEventCourier::event_bridgeRepaired(IAIObject* object) { AIStrategicObjectManager::getInstance()->bridgeSegmentRepaired(object); - return 0; // [CHOSEN, not recovered] - see above } -int AIEventCourier::event_bridgeCreated(IAIObject* object) +// ELF 0x3997B0. +void AIEventCourier::event_bridgeCreated(IAIObject* object) { AIStrategicObjectManager::getInstance()->createBridgeSegment(object); - return 0; // [CHOSEN, not recovered] - see above } -int AIEventCourier::event_bridgeRemoved(IAIObject* object) +// ELF 0x3997E0. +void AIEventCourier::event_bridgeRemoved(IAIObject* object) { AIStrategicObjectManager::getInstance()->removeBridgeSegment(object); - return 0; // [CHOSEN, not recovered] - see above } -// Initializes strategic areas, then pathfinding maps after level loading. -int AIEventCourier::event_levelLoaded() +// ELF 0x399810. Initializes strategic areas before pathfinding maps. +void AIEventCourier::event_levelLoaded() { AIStrategicObjectManager::getInstance()->postLoadInitAreas(); IAIPathfindingSetup::instance->initMaps(); - return 0; // [CHOSEN, not recovered] - see above } -int AIEventCourier::event_botSwitchSides(int) +// ELF 0x399850: IAIMain +0x28 switchSides(int), unguarded. +void AIEventCourier::event_botSwitchSides(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_botSwitchSides"); + IAIMain::m_instance->switchSides(playerId); } -// Forwards a side switch when the IAIMain singleton exists. +// ELF 0x399890. Forwards a side switch when the IAIMain singleton exists. void AIEventCourier::event_playerSwitchSides(int side, int playerId) { if (IAIMain::m_instance) diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIEventCourier.h b/Code/BF2/AI/AIDLL/AI/Main/AIEventCourier.h index 540a2b978..b436d5e6c 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIEventCourier.h +++ b/Code/BF2/AI/AIDLL/AI/Main/AIEventCourier.h @@ -1,6 +1,5 @@ // Routes game events into the AI module. -// Preserve virtual declaration order. [INFERRED] Return types require validation where implementations remain incomplete. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. +// Preserve virtual declaration order. Notification callbacks forward without a scalar result. #ifndef AI_AIDLL_AI_MAIN_AIEVENTCOURIER_H #define AI_AIDLL_AI_MAIN_AIEVENTCOURIER_H @@ -25,23 +24,23 @@ class IAIEventCourier IAIEventCourier(); virtual ~IAIEventCourier(); virtual void eventMissileLock(IAIObject *, world::MissileLockMessage *) = 0; - virtual int eventPlayerSpawned(int) = 0; + virtual void eventPlayerSpawned(int) = 0; virtual void eventPlayerKilled(int, int) = 0; virtual void eventPlayerCreated(bool) = 0; virtual void eventChangedKit(KitType) = 0; virtual void eventPlayerDisconnect(int) = 0; - virtual int eventPlayerEnterVehicle(int, IAIObject *, IAIObject *) = 0; - virtual int eventPlayerExitVehicle(IAIObject *, int) = 0; + virtual void eventPlayerEnterVehicle(int, IAIObject *, IAIObject *) = 0; + virtual void eventPlayerExitVehicle(IAIObject *, int) = 0; virtual void eventDrawDebug() = 0; - virtual int eventGameStart() = 0; + virtual void eventGameStart() = 0; virtual void event_roundEnd() = 0; virtual void event_worldReset() = 0; - virtual int eventManDown(int, IAIObject *) = 0; - virtual int eventRevived(int, IAIObject *) = 0; - virtual int eventRadioMessage(const AIRadioMessageSettings&, int, int) = 0; - virtual int event_mineRemoved(unsigned int) = 0; - virtual int event_enemySpotted(IAIObject *, unsigned char) = 0; - virtual int event_isRepaired(int) = 0; + virtual void eventManDown(int, IAIObject *) = 0; + virtual void eventRevived(int, IAIObject *) = 0; + virtual void eventRadioMessage(const AIRadioMessageSettings&, int, int) = 0; + virtual void event_mineRemoved(unsigned int) = 0; + virtual void event_enemySpotted(IAIObject *, unsigned char) = 0; + virtual void event_isRepaired(int) = 0; virtual void event_requestNewOrders(int, int) = 0; virtual void event_recievedAttackCommanderOrder(int) = 0; virtual void event_recievedDefendCommanderOrder(int) = 0; @@ -53,8 +52,8 @@ class IAIEventCourier virtual int event_receivedVehicleDropRequest(int, int, Vec3) = 0; virtual void event_commanderOrderAccepted(int) = 0; virtual void event_commanderOrderRejected(int) = 0; - virtual int event_appliedForCommander(int) = 0; - virtual int event_acceptedCommander(int, int) = 0; + virtual void event_appliedForCommander(int) = 0; + virtual void event_acceptedCommander(int, int) = 0; virtual void event_resignAsCommander(int, int) = 0; virtual void eventNewSquadLeader(int, int) = 0; virtual void event_joinedSquad(int, int, int) = 0; @@ -65,19 +64,19 @@ class IAIEventCourier virtual void event_receivedRepairSquadOrder(int) = 0; virtual void event_squadOrderAccepted(int, int) = 0; virtual void event_squadOrderRejected(int, int) = 0; - virtual int event_botTeamKilled(int, int) = 0; - virtual int event_freeCameraFire(bool) = 0; + virtual void event_botTeamKilled(int, int) = 0; + virtual void event_freeCameraFire(bool) = 0; virtual void event_removeAllSquadMembers() = 0; - virtual int event_retrievePathfindingMapId(int &, bool, const Vec3&, const Vec3&, const Mat4&) = 0; - virtual int event_pathfindingMapIdDestroyed(int, IAIObject *) = 0; - virtual int event_pathfindingMapIdRestored(int) = 0; - virtual int event_pathfindingMapIdRestoreOriginalMaterials(int, IAIObject *) = 0; - virtual int event_bridgeDestroyed(IAIObject *, int) = 0; - virtual int event_bridgeRepaired(IAIObject *) = 0; - virtual int event_bridgeCreated(IAIObject *) = 0; - virtual int event_bridgeRemoved(IAIObject *) = 0; - virtual int event_levelLoaded() = 0; - virtual int event_botSwitchSides(int) = 0; + virtual void event_retrievePathfindingMapId(int &, bool, const Vec3&, const Vec3&, const Mat4&) = 0; + virtual void event_pathfindingMapIdDestroyed(int, IAIObject *) = 0; + virtual void event_pathfindingMapIdRestored(int) = 0; + virtual void event_pathfindingMapIdRestoreOriginalMaterials(int, IAIObject *) = 0; + virtual void event_bridgeDestroyed(IAIObject *, int) = 0; + virtual void event_bridgeRepaired(IAIObject *) = 0; + virtual void event_bridgeCreated(IAIObject *) = 0; + virtual void event_bridgeRemoved(IAIObject *) = 0; + virtual void event_levelLoaded() = 0; + virtual void event_botSwitchSides(int) = 0; virtual void event_playerSwitchSides(int, int) = 0; }; @@ -90,23 +89,23 @@ class AIEventCourier : public IAIEventCourier // IAIEventCourier virtual void eventMissileLock(IAIObject *, world::MissileLockMessage *); - virtual int eventPlayerSpawned(int); + virtual void eventPlayerSpawned(int); virtual void eventPlayerKilled(int, int); virtual void eventPlayerCreated(bool); virtual void eventChangedKit(KitType); virtual void eventPlayerDisconnect(int); - virtual int eventPlayerEnterVehicle(int, IAIObject *, IAIObject *); - virtual int eventPlayerExitVehicle(IAIObject *, int); + virtual void eventPlayerEnterVehicle(int, IAIObject *, IAIObject *); + virtual void eventPlayerExitVehicle(IAIObject *, int); virtual void eventDrawDebug(); - virtual int eventGameStart(); + virtual void eventGameStart(); virtual void event_roundEnd(); virtual void event_worldReset(); - virtual int eventManDown(int, IAIObject *); - virtual int eventRevived(int, IAIObject *); - virtual int eventRadioMessage(const AIRadioMessageSettings&, int, int); - virtual int event_mineRemoved(unsigned int); - virtual int event_enemySpotted(IAIObject *, unsigned char); - virtual int event_isRepaired(int); + virtual void eventManDown(int, IAIObject *); + virtual void eventRevived(int, IAIObject *); + virtual void eventRadioMessage(const AIRadioMessageSettings&, int, int); + virtual void event_mineRemoved(unsigned int); + virtual void event_enemySpotted(IAIObject *, unsigned char); + virtual void event_isRepaired(int); virtual void event_requestNewOrders(int, int); virtual void event_recievedAttackCommanderOrder(int); virtual void event_recievedDefendCommanderOrder(int); @@ -118,8 +117,8 @@ class AIEventCourier : public IAIEventCourier virtual int event_receivedVehicleDropRequest(int, int, Vec3); virtual void event_commanderOrderAccepted(int); // guarded IAIMain forward virtual void event_commanderOrderRejected(int); - virtual int event_appliedForCommander(int); - virtual int event_acceptedCommander(int, int); + virtual void event_appliedForCommander(int); + virtual void event_acceptedCommander(int, int); virtual void event_resignAsCommander(int, int); virtual void eventNewSquadLeader(int, int); // side then squad id virtual void event_joinedSquad(int, int, int); // player id, squad id, side @@ -130,20 +129,20 @@ class AIEventCourier : public IAIEventCourier virtual void event_receivedRepairSquadOrder(int); virtual void event_squadOrderAccepted(int, int); virtual void event_squadOrderRejected(int, int); - virtual int event_botTeamKilled(int, int); - virtual int event_freeCameraFire(bool); + virtual void event_botTeamKilled(int, int); + virtual void event_freeCameraFire(bool); virtual void event_removeAllSquadMembers(); // the eight below: / - virtual int event_retrievePathfindingMapId(int &, bool, const Vec3&, const Vec3&, const Mat4&); // IAIPathfinding forward - virtual int event_pathfindingMapIdDestroyed(int, IAIObject *); // Debug(Error) if < 0, line 508 - virtual int event_pathfindingMapIdRestored(int); // IAIPathfinding forward - virtual int event_pathfindingMapIdRestoreOriginalMaterials(int, IAIObject *); // Debug(Error) if < 0, line 532 - virtual int event_bridgeDestroyed(IAIObject *, int); // AIStrategicObjectManager forwards - virtual int event_bridgeRepaired(IAIObject *); // no singleton test - virtual int event_bridgeCreated(IAIObject *); - virtual int event_bridgeRemoved(IAIObject *); - virtual int event_levelLoaded(); - virtual int event_botSwitchSides(int); + virtual void event_retrievePathfindingMapId(int &, bool, const Vec3&, const Vec3&, const Mat4&); // IAIPathfinding forward + virtual void event_pathfindingMapIdDestroyed(int, IAIObject *); // Debug(Error) if < 0, line 508 + virtual void event_pathfindingMapIdRestored(int); // IAIPathfinding forward + virtual void event_pathfindingMapIdRestoreOriginalMaterials(int, IAIObject *); // Debug(Error) if < 0, line 532 + virtual void event_bridgeDestroyed(IAIObject *, int); // AIStrategicObjectManager forwards + virtual void event_bridgeRepaired(IAIObject *); // no singleton test + virtual void event_bridgeCreated(IAIObject *); + virtual void event_bridgeRemoved(IAIObject *); + virtual void event_levelLoaded(); + virtual void event_botSwitchSides(int); virtual void event_playerSwitchSides(int, int); }; diff --git a/Code/BF2/AI/AIDLL/AI/Main/AILODManager.cpp b/Code/BF2/AI/AIDLL/AI/Main/AILODManager.cpp index ca9fce5f0..70ae5947e 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AILODManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/AILODManager.cpp @@ -1,9 +1,23 @@ // [INFERRED] Source placement. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining AILODManager operations. + +// static init: ELF 0x39C180 (__tcf_0 0x39C1E0, _GLOBAL__I 0x39C210): 's Init object only. +#include #include "AILODManager.h" -#include "AIDllFrontier.h" +#include +#include "CommonSingletonServer.h" +#include "IBotManager.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../Math/Mat4.h" namespace dice { namespace hfe { @@ -11,17 +25,56 @@ namespace ai { AILODManager* AILODManager::m_instance = 0; -// Seeds both LOD distance fields from the same value and updates players before +// ELF 0x39B0D0 / 0x39B100. +PlayerLODStats::PlayerLODStats() : m_position(), m_player(0), m_lodDistance(0.0f) {} + +// ELF 0x39B130 / 0x39B160. +PlayerLODStats::PlayerLODStats(IAIPlayer* player) + : m_position(), m_player(player), m_lodDistance(0.0f) {} + +// ELF 0x39B190 / 0x39B1D0. +PlayerLODStats::PlayerLODStats(const PlayerLODStats& other) + : m_position(other.m_position), m_player(other.m_player), m_lodDistance(other.m_lodDistance) {} + +// ELF 0x39B210 / 0x39B220. Does not own the player. +PlayerLODStats::~PlayerLODStats() {} + +// ELF 0x39B230. Dead players, or those without a vehicle, use the camera position. +void PlayerLODStats::update(float basicDistance, float speedScale) +{ + float speed = 0.0f; + IAIObject* vehicle = 0; + if (m_player->getIsAlive()) + vehicle = m_player->getCurrentVehicle(); + if (vehicle) + { + m_position = vehicle->getPosition(); + if (vehicle->isMobile()) + speed = vehicle->getMobile()->getSpeedMagnitude(); + } + else + { + const Mat4* const camera = static_cast(m_player->getCameraTransformation()); + m_position.x = camera->m[12]; + m_position.y = camera->m[13]; + m_position.z = camera->m[14]; + } + speedScale *= speed; + m_lodDistance = basicDistance + speedScale; + m_lodDistance *= m_player->getFieldOfViewModifier(); +} + +// ELF 0x39B320 / 0x39B4C0. Seeds both distances equally and updates players before // publishing the singleton. Player initialization must work before publication. AILODManager::AILODManager(float basicLODDistance, float f36) : m_playerStats() - , m_set16() + , m_updatedPlayerIds() , m_basicLODDistance(basicLODDistance) , m_maxLODDistance(basicLODDistance) , m_f36(f36) , m_lodEnable(true) - , m_i44(-1) - , m_i48(0) + , m_playerCursor(-1) + , m_botCursor(0) { updateAllPlayers(); @@ -29,77 +82,203 @@ AILODManager::AILODManager(float basicLODDistance, float f36) m_instance = this; } -// [FRONTIER] LOD-manager teardown remains unimplemented. -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -// Replace the stop when ordered destruction is recovered. +// ELF 0x39B690 (D1, 240 B; recovered on the client track): the +// singleton is zeroed when it is this one; the set and the stats map go as members. AILODManager::~AILODManager() { - BF2_AI_FRONTIER("dice::hfe::ai::AILODManager::~AILODManager"); + if (m_instance == this) + m_instance = 0; } -// Updates players, clears their statistics, and enables LOD regardless of its previous setting. -void AILODManager::reset() +// ELF 0x39C090. Updates players, clears their statistics, and enables LOD. +bool AILODManager::reset() { updatePlayers(); m_playerStats.clear(); m_lodEnable = true; + return true; } -// - one store. `AISettings::setViewDistance` is its only caller in the image. +// ELF 0x39C170. `AISettings::setViewDistance` is its only caller in the image. void AILODManager::setBasicLODDistance(float distance) { m_basicLODDistance = distance; } // Setter and getter intentionally share the lodEnable name. -void AILODManager::lodEnable(bool enable) +// ELF 0x39C060: stores the byte and returns it (movzbl of the argument). +bool AILODManager::lodEnable(bool enable) { m_lodEnable = enable; + return enable; } -bool AILODManager::lodEnable() const +// ELF 0x39C080. Nonconst by the mangled symbol. +bool AILODManager::lodEnable() { return m_lodEnable; } -// [FRONTIER] Player LOD updates remain unimplemented; construction reaches updateAllPlayers. -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -// Replace each stop when its corresponding update behavior is recovered. - +// ELF 0x39B780. void AILODManager::updateAllPlayers() { - BF2_AI_FRONTIER("dice::hfe::ai::AILODManager::updateAllPlayers"); + if (!m_lodEnable) + return; + const std::vector& players = static_cast( + CommonSingletonServer::m_iaiObjectEnvironment)->getActivePlayerIds(); + m_updatedPlayerIds.clear(); + for (std::vector::const_iterator it = players.begin(); it != players.end(); ++it) + updatePlayer(*it); + updatePlayerMap(); + m_updatedPlayerIds.clear(); } +// ELF 0x39B880. A completed sweep prunes stale entries before clearing its ID set. void AILODManager::updatePlayers() { - BF2_AI_FRONTIER("dice::hfe::ai::AILODManager::updatePlayers"); + IAIObjectEnvironment* const environment = static_cast( + CommonSingletonServer::m_iaiObjectEnvironment); + const std::vector& players = environment->getActivePlayerIds(); + if (environment->isValidPlayerId(m_playerCursor)) + { + updatePlayer(m_playerCursor); + m_playerCursor = environment->getNextPlayerId(m_playerCursor); + } + else + { + if (!players.empty()) + { + m_playerCursor = players.front(); + updatePlayerMap(); + } + m_updatedPlayerIds.clear(); + } } -void AILODManager::updatePlayer(int) +// ELF 0x39B970. Disabled LOD still answers true without touching player state. +bool AILODManager::updatePlayer(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::AILODManager::updatePlayer"); + if (m_lodEnable) + { + std::map::iterator it = m_playerStats.find(playerId); + if (it == m_playerStats.end()) + { + IAIPlayer* const player = static_cast( + CommonSingletonServer::m_iaiPlayerFactory)->getPlayerFromId(playerId); + it = m_playerStats.insert(std::pair( + playerId, PlayerLODStats(player))).first; + } + it->second.update(m_basicLODDistance, m_f36); + m_updatedPlayerIds.insert(it->first); + } + return true; } +// ELF 0x39BB80. Equal container sizes skip the scan, even if their keys differ. void AILODManager::updatePlayerMap() { - BF2_AI_FRONTIER("dice::hfe::ai::AILODManager::updatePlayerMap"); + if (m_updatedPlayerIds.size() == m_playerStats.size()) + return; + std::map::iterator it = m_playerStats.begin(); + while (it != m_playerStats.end()) + { + if (m_updatedPlayerIds.find(it->first) == m_updatedPlayerIds.end()) + m_playerStats.erase(it++); + else + ++it; + } } +// ELF 0x39BC90. Limits each enabled pass to four successful updates, retaining the cursor. void AILODManager::updateBots() { - BF2_AI_FRONTIER("dice::hfe::ai::AILODManager::updateBots"); + IBotManager* const manager = IBotManager::instance; + if (!manager || manager->getBotCount() == 0) + return; + int updated = 0; + Bot* const first = manager->getBot(static_cast(m_botCursor)); + ++m_botCursor; + if (!m_lodEnable) + first->setLodLevel(BotLodFull); + else + { + if (updateBot(first)) + updated = 1; + while (updated < 4 && m_botCursor < manager->getBotCount()) + { + Bot* const bot = manager->getBot(static_cast(m_botCursor)); + const bool success = updateBot(bot); + ++m_botCursor; + if (success) + ++updated; + } + } + if (m_botCursor >= manager->getBotCount()) + m_botCursor = 0; } -void AILODManager::updateBot(Bot*) +// ELF 0x39BD70. Hysteresis depends on the old level; each pass begins at light detail. +bool AILODManager::updateBot(Bot* bot) { - BF2_AI_FRONTIER("dice::hfe::ai::AILODManager::updateBot"); + const BotLodLevel oldLevel = bot->getLodLevel(); + bot->setLodLevel(BotLodLight); + if (bot->isDead()) + return false; + Information* const information = informationManager->getInformation(bot->getCurrentEquipment()); + if (!information) + return false; + IAIObject* const object = information->getAIObject(); + const Vec3& position = information->getPosition(); + float fullThreshold = 1.0f; + float mediumThreshold = 1.425f; + if (oldLevel == BotLodFull) + { + fullThreshold = 1.05f; + mediumThreshold = 1.5f; + } + else if (oldLevel == BotLodMedium) + { + fullThreshold = 0.95f; + mediumThreshold = 1.575f; + } + float speed = 0.0f; + IPIMobile* const mobile = information->getMobile(); + if (mobile) + speed = mobile->getSpeedMagnitude(); + for (std::map::iterator it = m_playerStats.begin(); + it != m_playerStats.end(); ++it) + { + const float x = it->second.m_position.x - position.x; + const float y = it->second.m_position.y - position.y; + const float z = it->second.m_position.z - position.z; + float distance = std::sqrt(x * x + y * y + z * z) - speed * m_f36; + if (it->second.m_lodDistance > 1.0e-7f) + distance /= it->second.m_lodDistance; + if (distance < fullThreshold) + { + bot->setLodLevel(BotLodFull); + if (oldLevel != BotLodFull && object->isMobile() && object->isPhysical()) + { + IAIObjectPhysical* const physical = object->getPhysical(); + if (!physical->hasPhysicsEnabled()) + physical->enablePhysics(bot->getSide()); + } + break; + } + if (bot->getLodLevel() > BotLodMedium && distance < mediumThreshold) + bot->setLodLevel(BotLodMedium); + } + return true; } -void AILODManager::removePlayer(int) +// ELF 0x39C110. +void AILODManager::removePlayer(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::AILODManager::removePlayer"); + if (m_playerCursor == playerId) + m_playerCursor = -1; + m_playerStats.erase(playerId); + m_updatedPlayerIds.erase(playerId); } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/Main/AILODManager.h b/Code/BF2/AI/AIDLL/AI/Main/AILODManager.h index 1fe481295..43653e801 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AILODManager.h +++ b/Code/BF2/AI/AIDLL/AI/Main/AILODManager.h @@ -1,5 +1,4 @@ // Controls AI level of detail and update budgets. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. // [INFERRED] Source placement. #ifndef AI_AIDLL_AI_MAIN_AILODMANAGER_H // [INFERRED] guard style @@ -7,56 +6,63 @@ #include #include +#include "../../../../Math/Vec3.h" namespace dice { namespace hfe { namespace ai { class Bot; +class IAIPlayer; -// Per-player LOD record. [CHOSEN, not recovered] Five words preserve its known 20-byte -// size; field meanings remain unknown. +// Per-player position and distance used when selecting bot detail levels. class PlayerLODStats { public: - int m_words[5]; + PlayerLODStats(); + explicit PlayerLODStats(IAIPlayer* player); + PlayerLODStats(const PlayerLODStats& other); + ~PlayerLODStats(); + void update(float basicDistance, float speedScale); + + // ELF offsets; names are [INFERRED]. The player is borrowed. + /* +0x00 */ Vec3 m_position; + /* +0x0C */ IAIPlayer* m_player; + /* +0x10 */ float m_lodDistance; }; class AILODManager { public: AILODManager(float basicLODDistance, float f36); - ~AILODManager(); // , [FRONTIER] + ~AILODManager(); // ELF 0x39B690 // The whole vtable. See the header note. - virtual void reset(); + virtual bool reset(); void setBasicLODDistance(float distance); - void lodEnable(bool enable); - bool lodEnable() const; + bool lodEnable(bool enable); // ELF 0x39C060 answers the stored value (ConsoleClass293 keeps it) + bool lodEnable(); - // the seven that are not written - // Each is a named stop; `updateAllPlayers` is reached from the constructor and the rest from - // `reset` or from the console, so none of them runs on a path this tree exercises. - void updateAllPlayers(); // [FRONTIER] - void updatePlayers(); // [FRONTIER] - void updatePlayer(int playerId); // [FRONTIER] - void updatePlayerMap(); // [FRONTIER] - void updateBots(); // [FRONTIER] - void updateBot(Bot* bot); // [FRONTIER] - void removePlayer(int playerId); // [FRONTIER] + void updateAllPlayers(); + void updatePlayers(); + bool updatePlayer(int playerId); // [INFERRED] bool: every exit returns 1 + void updatePlayerMap(); + void updateBots(); + bool updateBot(Bot* bot); + void removePlayer(int playerId); static AILODManager* m_instance; // layout, on the ELF, read store by store out of the constructor /* +4 */ std::map m_playerStats; // `reset` clears it - /* +16 */ std::set m_set16; // [UNRESOLVED] - a 4-byte element + /* +16 */ std::set m_updatedPlayerIds; // [INFERRED] IDs seen in the current sweep /* +28 */ float m_basicLODDistance; // = the first argument; `setBasicLODDistance` writes it /* +32 */ float m_maxLODDistance; // = the first argument too - see the header note [INFERRED] - /* +36 */ float m_f36; // = the second argument [UNRESOLVED] + /* +36 */ float m_f36; // speed scale; second constructor argument /* +40 */ bool m_lodEnable; // = true; the `lodEnable` pair, and `reset` raises it again - /* +44 */ int m_i44; // = -1 [UNRESOLVED] - /* +48 */ int m_i48; // = 0 [UNRESOLVED] + /* +44 */ int m_playerCursor; // = -1; next player ID [INFERRED] + /* +48 */ int m_botCursor; // = 0; next bot index [INFERRED] }; } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/Main/AILandingZoneManager.cpp b/Code/BF2/AI/AIDLL/AI/Main/AILandingZoneManager.cpp new file mode 100644 index 000000000..e65447ce8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/Main/AILandingZoneManager.cpp @@ -0,0 +1,192 @@ +// Source placement: AIDLL_r.dll __FILE__ "Code\BF2\AI\AIDLL\AI\Main\AILandingZoneManager.cpp" (0x10081FA0). + +// static init: ELF 0x39AA80, __tcf_0 0x39AB10, _GLOBAL__I 0x39AB40: stream Init precedes the manager. +#include + +#include "AILandingZoneManager.h" + +#include + +#include "../AIStrategicEntity/AILandingZone.h" +#include "../AIUtils/checkPointer.h" +#include "../AIUtils/DebugRendering/AIRenderUtil.h" // updateNumberOfLandingZones + +namespace dice { +namespace hfe { +namespace ai { + +AILandingZoneManager* AILandingZoneManager::m_instance = 0; + +// ELF 0x399980 (C1; C2 0x399B50). Initializes an inactive landing-zone manager and explicitly +// resizes its new vector to zero. +AILandingZoneManager::AILandingZoneManager() + : m_activeZone(0) + , m_unresolved20(0) + , m_activeZoneName("No valid zone is active") +{ + m_zones.resize(0); +} + +// static init: ELF 0x39AA80 (with __tcf_0 0x39AB10 and _GLOBAL__I 0x39AB40): +// constructs the landing-zone manager at DLL load. BF2AI::clear owns its later destruction. +namespace { + +struct AILandingZoneManagerInstaller +{ + AILandingZoneManagerInstaller() + { + AILandingZoneManager::m_instance = new AILandingZoneManager(); + } +}; + +AILandingZoneManagerInstaller g_aiLandingZoneManagerInstaller; + +} // namespace + +// ELF 0x399C50 (D1; D0 0x399D60): deletes every non-null zone (AILandingZone D1 + operator delete), +// then the name, the vector and the map go as members. m_instance is not cleared. +AILandingZoneManager::~AILandingZoneManager() +{ + for (std::vector::iterator zone = m_zones.begin(); zone != m_zones.end(); ++zone) + { + if (*zone) + delete *zone; + } +} + +// ELF 0x39A350: deletes the zones (as above), zeroes +0x20 and +0x1C, renames the active zone +// "No valid zone is active" and empties the zone vector (resize(0)); the name map is kept. +bool AILandingZoneManager::reset() +{ + for (std::vector::iterator zone = m_zones.begin(); zone != m_zones.end(); ++zone) + { + if (*zone) + delete *zone; + } + m_unresolved20 = 0; + m_activeZone = 0; + m_activeZoneName = "No valid zone is active"; + m_zones.resize(0, 0); + return true; +} + +// ELF 0x399E70. +const std::string& AILandingZoneManager::activeZone() +{ + return m_activeZone ? m_activeZone->m_name : m_activeZoneName; +} + +// ELF 0x399E90. +const std::string& AILandingZoneManager::activeZone(int index) +{ + if (index < static_cast(m_zones.size()) && index >= 0) + { + m_activeZone = m_zones[index]; + return m_activeZone->m_name; + } + m_activeZone = 0; + return m_activeZoneName; +} + +// ELF 0x399ED0. +const std::string& AILandingZoneManager::activeZone(const std::string& name) +{ + std::map::iterator it = m_zonesByName.find(name); + if (it == m_zonesByName.end()) + { + m_activeZone = 0; + return m_activeZoneName; + } + m_activeZone = it->second; + return m_activeZone->m_name; +} + +// ELF 0x399F40. +AILandingZone* AILandingZoneManager::getActiveZone() +{ + return m_activeZone; +} + +// ELF 0x399F50. +AILandingZone* AILandingZoneManager::getAILandingZone(int index) +{ + if (index < static_cast(m_zones.size()) && index >= 0) + return m_zones[index]; + return 0; +} + +// ELF 0x399F80. +AILandingZone* AILandingZoneManager::getAILandingZone(const std::string& name) +{ + std::map::iterator it = m_zonesByName.find(name); + if (it == m_zonesByName.end()) + return 0; + return it->second; +} + +// ELF 0x399FE0. +int AILandingZoneManager::getNumberOfLandingZones() const +{ + return static_cast(m_zones.size()); +} + +// ELF 0x39A000. AIRenderUtil::m_instance is not null-checked. +AILandingZone* AILandingZoneManager::createLandingZone(const std::string& name, const Vec2& minCorner, + const Vec2& maxCorner, float height, + LandingZoneDirection beachDirection) +{ + const int id = static_cast(m_zones.size()); + AILandingZone* const zone = + checkPointer(new AILandingZone(name, id, minCorner, maxCorner, height, beachDirection)); + m_zones.resize(m_zones.size() + 1); + m_zones[id] = zone; + m_activeZone = zone; + m_zonesByName.insert(std::make_pair(name, zone)); + AIRenderUtil::m_instance->updateNumberOfLandingZones(); + return zone; +} + +// ELF 0x39A460. +bool AILandingZoneManager::isInsideLandingZone(const Vec3& position) const +{ + AILandingZone* zone; + return isInsideLandingZone(position, zone); +} + +// ELF 0x39A4A0: `zone` receives the zone, 0 when none contains the position. +bool AILandingZoneManager::isInsideLandingZone(const Vec3& position, AILandingZone*& zone) const +{ + for (std::vector::const_iterator it = m_zones.begin(); it != m_zones.end(); ++it) + { + if ((*it)->isInZone(position)) + { + zone = *it; + return true; + } + } + zone = 0; + return false; +} + +// ELF 0x39A510. Null slots are skipped; the corners use the image's inlined x/y Vec2 output and +// the direction prints as an int. +std::string AILandingZoneManager::listZones() +{ + std::stringstream stream; + for (std::vector::iterator it = m_zones.begin(); it != m_zones.end(); ++it) + { + AILandingZone* const zone = *it; + if (!zone) + continue; + const Vec2& minCorner = zone->getMinCorner(); + const Vec2& maxCorner = zone->getMaxCorner(); + stream << zone->m_name << " " << minCorner.x << '/' << minCorner.y << " " << maxCorner.x + << '/' << maxCorner.y << " " << static_cast(zone->getBeachDirection()) + << std::endl; + } + return stream.str(); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/Main/AILandingZoneManager.h b/Code/BF2/AI/AIDLL/AI/Main/AILandingZoneManager.h new file mode 100644 index 000000000..076df21e0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/Main/AILandingZoneManager.h @@ -0,0 +1,84 @@ +// Owns AI landing zones. Constructed when the DLL loads and destroyed by BF2AI::clear. +// reset is its only virtual method; the destructor is nonvirtual. +// Header placement [INFERRED]: beside its .cpp, whose path AIDLL_r.dll confirms (Main/AILandingZoneManager.cpp). + +#ifndef AI_AIDLL_AI_AISTRATEGICENTITY_AILANDINGZONEMANAGER_H // [INFERRED] guard style +#define AI_AIDLL_AI_AISTRATEGICENTITY_AILANDINGZONEMANAGER_H + +#include +#include +#include + +#include "../../../../Math/Vec3.h" + +// Vec2 and Vec3 are Math aliases, so do not forward-declare them as classes in this namespace. +namespace dice { +namespace hfe { +namespace ai { + +class AILandingZone; + +// Defined, with its enumerators, in AILandingZone.h. +enum LandingZoneDirection : int; + +// sizeof is 40 (0x28) in retail, from the `operator new(0x28)` in this file's static initialiser +// and it will not be 40 here - two of the members are real STL containers and a third is a string. +class AILandingZoneManager +{ +public: + AILandingZoneManager(); + + // Not virtual. Deletes the zones. + ~AILandingZoneManager(); // ELF 0x399C50 (D1; D0 0x399D60) + + // The class's only virtual, and the only entry in its vtable. + // ELF 0x39A350: deletes the zones and answers true (`mov $0x1,%eax`). + virtual bool reset(); + + // ELF 0x399E70 / 0x399E90 / 0x399ED0: the active zone's name, or "No valid zone is active" + // when there is none; the int and name forms first select the zone (0 when not found). + const std::string& activeZone(); + const std::string& activeZone(int index); + const std::string& activeZone(const std::string& name); + AILandingZone* getActiveZone(); // ELF 0x399F40 + + // ELF 0x399F50: 0 for an index out of range. + AILandingZone* getAILandingZone(int index); + // ELF 0x399F80: the zone registered under the name, 0 when there is none. + AILandingZone* getAILandingZone(const std::string& name); + // ELF 0x399FE0. This is the method `AIRenderUtil`'s constructor calls. + int getNumberOfLandingZones() const; + + // ELF 0x39A000: a new zone with the next id, registered by name and made active. + AILandingZone* createLandingZone(const std::string& name, const Vec2& minCorner, + const Vec2& maxCorner, float height, + LandingZoneDirection beachDirection); + // ELF 0x39A460 / 0x39A4A0: the first zone containing the position. + bool isInsideLandingZone(const Vec3& position) const; + bool isInsideLandingZone(const Vec3& position, AILandingZone*& zone) const; + // ELF 0x39A510: " " per zone. + std::string listZones(); + + // set by this file'S static initialiser, not by any `init`. See the header block. + static AILandingZoneManager* m_instance; + +private: + /* +0x00 */ // vptr - one slot, `reset` + /* +0x04 */ std::map m_zonesByName; + /* +0x10 */ std::vector m_zones; // what getNumberOfLandingZones measures + + // The active zone (activeZone / createLandingZone), 0 for none. + /* +0x1C */ AILandingZone* m_activeZone; + // [UNRESOLVED] Initialized to zero; no reader in this class. + /* +0x20 */ int m_unresolved20; + + // constructed from A literal, and the literal is the class's whole personality: + // "No valid zone is active". + /* +0x24 */ std::string m_activeZoneName; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGICENTITY_AILANDINGZONEMANAGER_H diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIMain.cpp b/Code/BF2/AI/AIDLL/AI/Main/AIMain.cpp index b370b581f..62594c746 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIMain.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/AIMain.cpp @@ -1,13 +1,16 @@ // AI runtime lifecycle, population management and simulation updates. +// static init: ELF 0x39F580 (__tcf_0 0x39F5E0, _GLOBAL__I 0x39F610): 's Init object only. +#include + #include "AIMain.h" #include // std::min - spawnBots' bot budget +#include #include -#include "AIDllFrontier.h" // the twenty named stops below #include "../AIUtils/checkPointer.h" // the ctor's dead null check -#include "../AIBotBehaviour/CustomCurve.h" // SCurve / JCurve / DecleiningSlopeCurve +#include "../AIUtils/CustomCurve.h" // SCurve / JCurve / DecleiningSlopeCurve #include "../../../AIInterface/Module/BFConsole.h" // IBFModuleCourier::aiMainInit #include "BotManager.h" // getNumberOfActiveBots #include "CommonSingletonServer.h" // m_iaiGame / Settings / Effector @@ -15,7 +18,7 @@ #include "../../../AIInterface/BFKnowledge/BFGame.h" // IAIGame #include "../../../AIInterface/BFKnowledge/BFGameEffector.h" // IAIGameEffector::addBot #include "IAIPathfinding.h" // IAIPathfindingSetup::instance -#include "../AIStrategicMap/AerialHeightMap.h" // readHeightMapFromFile +#include "../AIPathFinding/AerialHeightMap/AerialHeightMap.h" // readHeightMapFromFile #include "../AIKnowledge/BFInformationEnvironment.h" // built and dropped by init #include "../AIUtils/DebugRendering/AIRenderUtil.h" // built and dropped by init #include "../AIStrategic/SAI.h" // ISAI::create, one per side @@ -24,35 +27,25 @@ #include "../../../AIInterface/BFKnowledge/AIPlayer.h" // IAIPlayer - newPlayerCreated #include "../AIBot/BotMain.h" // Bot - switchSides #include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" // isValidPlayerId -#include "UserOrderManager.h" // recruitBot's first refusal +#include "../AIStrategicEntity/UserOrders/UserOrderManager.h" // recruitBot's first refusal #include // the per-bot pair series #include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" // getPlayerFromId, the id sweep #include "../../../AIInterface/BFKnowledge/BFTimer.h" // action's three timer methods #include "../../../AIInterface/BFKnowledge/BFCollisionHandler.h" // updateBotProjectiles #include "../AIBot/SquadManager.h" // update(double) -#include "AIMineManager.h" // IAIMineManager::update +#include "../AIKnowledge/AIMineManager.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" // updateAIObject, vehicle changes +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" // IAIObjectUnit +#include "CommunicationHub.h" // resetLevel // IAIMineManager::update namespace dice { namespace hfe { namespace ai { -// Active IAIMain instance; construction replaces it unconditionally. -IAIMain* IAIMain::m_instance = 0; - -// Construction replaces the active IAIMain pointer. Destruction clears it unconditionally. -// Only one IAIMain may be alive when callers use this singleton. -IAIMain::IAIMain() -{ - m_instance = this; -} - -IAIMain::~IAIMain() -{ - m_instance = 0; -} - +// IAIMain's constructor, destructor and m_instance live in IAIMain.cpp (AIDLL_r __FILE__). // Returns whether initialization has completed. [INFERRED] State-field name. +// ELF 0x39F9F0 bool AIMain::isInitialised() { return m_initialised; @@ -63,38 +56,46 @@ bool AIMain::isInitialised() // The AI's debug rendering entry point - inert on a dedicated server build, which is the // only build this pair comes from. So none of the ~20 show*/render* console switches this class // exposes can produce any output here; they set flags that only a client-side AIMain would read. +// ELF 0x39DD60 void AIMain::draw() { } // The sound-event hook is empty, so it never fills the sound queue. // [UNRESOLVED] SoundEffect members cannot be established from this path. +// ELF 0x39EF60 void AIMain::queueSoundEffect(const Vec3& /*pos*/, int /*a*/, int /*b*/) { } // These five commander notifications intentionally do nothing in AIMain. +// ELF 0x39F530 void AIMain::commanderOrderAccepted(int /*a*/) { } +// ELF 0x39F540 void AIMain::commanderOrderRejected(int /*a*/) { } +// ELF 0x39F550 void AIMain::appliedForCommander(int /*a*/) { } +// ELF 0x39F560 void AIMain::acceptedAsCommander(int /*a*/) { } +// ELF 0x39F570 void AIMain::resignedAsCommander(int /*a*/) { } // Creates and activates bots up to the configured population budget when a round starts. +// ELF 0x39F3C0 void AIMain::spawnBots() { IAIGame* const game = static_cast(CommonSingletonServer::m_iaiGame); @@ -123,41 +124,42 @@ void AIMain::spawnBots() } } -// Constructs and destroys the AI runtime. Remaining dependencies use named frontier stops. +// Constructs the AI runtime and its bot manager. +// ELF 0x39C970 / 0x39CDD0 AIMain::AIMain() // Keep BotManager allocation in the initializer list to preserve its position between // the surrounding container constructions. : m_aiSystemQuotient(0.15f) // the float constant, widened - see AIMain.h - , m_dword12(0.875) + , m_botManagerQuotient(0.875) , m_componentQuotient(0.125) , m_double28(0.0) , m_dword36(0) - , m_double40(3.0) + , m_botStatisticUpdateSpeed(3.0) , m_dword100(0) , m_initialised(false) , m_saiEnabled(false) , m_dword108(0) , m_dword112(0) , m_float120(100.0f) - , m_dword128(1) + , m_renderSide(1) , m_dword132(0) - , m_flag136(false) - , m_flag137(true) - , m_flag138(false) - , m_flag139(true) - , m_flag140(true) - , m_flag141(false) + , m_showBotUrgencies(false) + , m_showStrategies(true) + , m_showSAIStats(false) + , m_showBotStats(true) + , m_showStrategicAreas(true) + , m_showBotSpawnCoord(false) , m_dword144(0) , m_flag148(false) , m_componentCursor(0) - , m_dword168(64) - , m_dword172(64) + , m_saiMapXDimension(64) + , m_saiMapYDimension(64) // FLT_MAX in A double, as the float constant and widened - that is what the binary // stores and the `f` suffix is what reproduces it exactly. A "no value yet" sentinel. , m_double176(-3.4028235e38f) , m_double184(-3.4028235e38f) , m_botManager(checkPointer(new BotManager)) - , m_flag196(false) + , m_validateDataStructuresEnabled(false) , m_botCount(0) , m_humanCount(0) { @@ -180,31 +182,49 @@ AIMain::AIMain() m_sai[2] = 0; } +// ELF 0x39D390 (D1, 538 B; recovered on the client track). The +// per-side SAIs 1..getNSides() go through their virtual deleting destructor (+4) and are zeroed +// - the side count is asked again on every pass (IAISettings +0x40) - then the bot manager the +// same way. The containers and the IAIMain base follow as members. AIMain::~AIMain() { - BF2_AI_FRONTIER("dice::hfe::ai::AIMain::~AIMain"); + for (int side = 1; side < static_cast(CommonSingletonServer::m_iaiSettings)->getNSides() + 1; ++side) + { + if (m_sai[side]) + { + delete m_sai[side]; + m_sai[side] = 0; + } + } + if (m_botManager) + delete m_botManager; } -// The twenty remaining virtual slots, in vtable order. Addresses and sizes are in the [FRONTIER] -// list at the bottom of this file; nothing here adds evidence. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - -void AIMain::addNewPlayer(world::IPlayer* /*player*/) +// ELF 0x39F920 (weak): list insert at end() - the iterator is the list header itself. +void AIMain::addNewPlayer(world::IPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::AIMain::addNewPlayer"); + m_playerQueue.push_back(player); } -void AIMain::popPlayer() +// ELF 0x39F970 (weak): counts the list (SGI size()), answers null when empty, else erases the +// first node and returns its player. +world::IPlayer* AIMain::popPlayer() { - BF2_AI_FRONTIER("dice::hfe::ai::AIMain::popPlayer"); + if (m_playerQueue.size() == 0) + return 0; + world::IPlayer* const player = m_playerQueue.front(); + m_playerQueue.erase(m_playerQueue.begin()); + return player; } -void AIMain::registerFreeBot(Bot* /*bot*/) +// ELF 0x39E1B0: list insert at end() of the pending list action() hands to the SAIs. +void AIMain::registerFreeBot(Bot* bot) { - BF2_AI_FRONTIER("dice::hfe::ai::AIMain::registerFreeBot"); + m_pendingBots.push_back(bot); } // Activates the bot associated with a player ID. +// ELF 0x39E3B0 bool AIMain::activateBot(int playerId, int side, const std::string& name) { IAIObjectEnvironment* const environment = @@ -222,7 +242,27 @@ bool AIMain::activateBot(int playerId, int side, const std::string& name) return addUnspawnedBot(playerId, side, settings->getStandardPersonality(side)); } +// ELF 0x39DDA0 +bool AIMain::addBot(int playerId, int side, float* personality, IAIObject* object) +{ + if (!m_botManager->addBot(playerId, side, personality, object)) + return false; + const int index = m_botManager->getBotCount() - 1; + Bot* const bot = m_botManager->getBot(static_cast(index)); + if (!UserOrderManager::m_instance->recruitBot(bot, side)) + { + if (m_sai[side]) + m_sai[side]->addBot(bot); + } + m_perBot48.push_back(std::pair(0.0f, 0.0f)); + m_perBot60.push_back(std::pair(0.0f, 0.0f)); + m_perBot72.push_back(std::pair(0.0f, 0.0f)); + m_perBot84.push_back(0.0f); + return true; +} + // Adds an unspawned bot to either player-directed orders or its side's strategic AI. +// ELF 0x39DFA0 bool AIMain::addUnspawnedBot(int playerId, int side, float* personality) { const IAISettings* const settings = @@ -251,18 +291,44 @@ bool AIMain::addUnspawnedBot(int playerId, int side, float* personality) return true; } -void AIMain::deactivateBot(int& /*a*/, int /*b*/) +// ELF 0x39E210: the player leaves its squad, a bot of the side is deactivated (-1: the +// player id becomes -1, false), the side's SAI (when set) drops it (SAI +0x1C) and the player +// id becomes the bot's. +bool AIMain::deactivateBot(int& playerId, int side) { - BF2_AI_FRONTIER("dice::hfe::ai::AIMain::deactivateBot(int&, int)"); + SquadManager::m_instance->removeSquadMember(playerId, side); + const int botId = m_botManager->deactivateBot(side); + if (botId == -1) + { + playerId = -1; + return false; + } + Bot* const bot = m_botManager->getBotFromId(static_cast(botId)); + if (m_sai[side]) + m_sai[side]->removeBot(bot); + playerId = bot->getPlayerId(); + return true; } -void AIMain::deactivateBot(int /*a*/) +// ELF 0x39E2E0: the player's squad member is destroyed, the dead bot of this player is +// deactivated (-1: false) and its side's SAI drops it. +bool AIMain::deactivateBot(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIMain::deactivateBot(int)"); + IAIPlayer* const player = static_cast(CommonSingletonServer::m_iaiPlayerFactory) + ->getPlayerFromId(playerId); + SquadManager::m_instance->destroySquadMember(playerId, player->getSide()); + const int botId = m_botManager->deactivateBotFromPlayerId(playerId); + if (botId == -1) + return false; + Bot* const bot = m_botManager->getBotFromId(static_cast(botId)); + if (m_sai[bot->getSide()]) + m_sai[bot->getSide()]->removeBot(bot); + return true; } // Updates population counts when a player is created. // A human joining may remove a bot when humans count toward the configured population limit. +// ELF 0x39E7B0 void AIMain::newPlayerCreated(bool isAI) { if (isAI) @@ -338,17 +404,55 @@ void AIMain::newPlayerCreated(bool isAI) } } -void AIMain::reactivateBot(int /*a*/) +// ELF 0x39E460: a leaving human. The human count drops, the player's squad member is +// destroyed, and when humans count toward the limit and the population is below the game's +// maximum, spawnBots refills it (IAIMain +0x54). +void AIMain::reactivateBot(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIMain::reactivateBot"); + IAIPlayer* const player = static_cast(CommonSingletonServer::m_iaiPlayerFactory) + ->getPlayerFromId(playerId); + if (!player) + return; + --m_humanCount; + SquadManager::m_instance->destroySquadMember(playerId, player->getSide()); + if (!static_cast(CommonSingletonServer::m_iaiSettings)->getmaxBotsIncludeHumans()) + return; + if (m_botCount + m_humanCount < static_cast(CommonSingletonServer::m_iaiGame)->getMaxNumberOfPlayers()) + spawnBots(); } -void AIMain::switchSides(int /*a*/) +// ELF 0x39E510 +void AIMain::switchSides(int side) { - BF2_AI_FRONTIER("dice::hfe::ai::AIMain::switchSides(int)"); + IAIPlayer* selected = 0; + const std::vector players = + static_cast(CommonSingletonServer::m_iaiPlayerFactory)->getAllPlayers(); + for (std::vector::const_iterator it = players.begin(); it != players.end(); ++it) + { + IAIPlayer* const player = *it; + if (!player || !player->getIsAIPlayer() || player->getSide() != side) + continue; + if (selected) + { + const int score = player->getScore(); + const int selectedScore = selected->getScore(); + if (score >= selectedScore) + continue; + } + selected = player; + } + if (selected) + { + selected->setSide((side == 1) + 1); + const int playerId = selected->getId(); + Bot* const bot = IBotManager::instance->getBotFromPlayerId(playerId); + getSAI(side)->removeBot(bot); + getSAI((side == 1) + 1)->addBot(bot); + } } // Moves a bot between sides and updates both strategic AI owners. +// ELF 0x39E6E0 void AIMain::switchSides(int side, int playerId) { Bot* const bot = IBotManager::instance->getBotFromPlayerId(playerId); @@ -376,6 +480,7 @@ void AIMain::switchSides(int side, int playerId) // Recovered caller: . This retires the entry stop, not the // scheduled callees' individual frontiers (RW-102); no completed tick is implied by linking it. +// ELF 0x39DB90 bool AIMain::action() { IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); @@ -437,54 +542,144 @@ bool AIMain::action() return true; // Explicit EAX=1 (ELF) / AL=1 (PE), after every scheduled call returns. } +// ELF 0x39EB00: `movzbl 0x69(this)`. bool AIMain::getSAIEnable() { - BF2_AI_FRONTIER("dice::hfe::ai::AIMain::getSAIEnable"); + return m_saiEnabled; } // an unchecked side-indexed pointer read. +// ELF 0x39EA00 SAI* AIMain::getSAI(int side) { return m_sai[side]; } -void AIMain::updateAIObject(IAIObject* /*o*/) +// ELF 0x39EF40: IAIObject +0x104 positionChanged. +void AIMain::updateAIObject(IAIObject* object) { - BF2_AI_FRONTIER("dice::hfe::ai::AIMain::updateAIObject"); + object->positionChanged(); } -void AIMain::reset() +// ELF 0x39EF70 +bool AIMain::reset() { - BF2_AI_FRONTIER("dice::hfe::ai::AIMain::reset"); + if (m_initialised) + { + for (int side = 1; side < static_cast(CommonSingletonServer::m_iaiSettings)->getNSides() + 1; ++side) + { + if (m_sai[side]) + { + delete m_sai[side]; + m_sai[side] = 0; + } + } + m_dword132 = 0; + m_saiMapYDimension = 32; + m_dword144 = 0; + m_aiSystemQuotient = 0.2; + m_renderSide = 1; + m_dword100 = 0; + m_initialised = false; + m_botManagerQuotient = 0.75f; + m_saiMapXDimension = 32; + m_saiEnabled = false; + m_showBotUrgencies = false; + m_componentQuotient = 0.25f; + m_validateDataStructuresEnabled = false; + m_flag148 = false; + m_dword36 = 0; + m_double28 = 0.0f; + m_botStatisticUpdateSpeed = 3.0f; + IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + const float width = static_cast(terrain->getWorldSizeX()); + const float height = static_cast(terrain->getWorldSizeZ()); + m_float120 = 100.0f; + // [CHOSEN, not recovered] Native libm marks log const; this barrier retains all four shipped calls. + double (*volatile logarithm)(double) = &std::log; + (void)logarithm(static_cast(width)); + (void)logarithm(2.0); + (void)logarithm(static_cast(height)); + (void)logarithm(2.0); + IAIPathfinding::instance->reset(); + IBotManager::instance->reset(); + static_cast(CommonSingletonServer::m_iBFTimer)->reset(); + static_cast(CommonSingletonServer::m_iBFModuleCourier)->reset(); + } + return true; } -void AIMain::resetLevel() +// ELF 0x39F140. The bridges are reset, then the strategic areas (AIStrategicObjectManager +0x04 +// resetAreas); every side's SAI is reset only while all previous resets succeeded (the && chain +// short-circuits). Then the projectiles (IBFCollisionHandler +0x08), the destroyable map parts +// (IAIPathfinding +0x10), the bridges a second time, the communication hub and the mines +// (IAIMineManager +0x0C). Returns the combined strategic reset result. +bool AIMain::resetLevel() { - BF2_AI_FRONTIER("dice::hfe::ai::AIMain::resetLevel"); + AIStrategicObjectManager::getInstance()->resetBridges(); + bool ok = AIStrategicObjectManager::getInstance()->resetAreas(); + for (int side = 1; side < static_cast(CommonSingletonServer::m_iaiSettings)->getNSides() + 1; ++side) + { + if (m_sai[side]) + ok = ok && m_sai[side]->reset(); + } + static_cast(CommonSingletonServer::m_iBFCollisionHandler)->removeAllProjectiles(); + IAIPathfinding::instance->resetDestroyableMapParts(); + AIStrategicObjectManager::getInstance()->resetBridges(); + CommunicationHub::m_instance->reset(); + static_cast(CommonSingletonServer::m_iAIMineManager)->reset(); + return ok; } -void AIMain::setAISystemQuotient(const double& /*q*/) +// ELF 0x39DAE0. The two x87 tests against 0.0f (ELF 0x49CB34) and 1.0f (0x49CB2C) are joined +// with "or": the value is stored unless it is below 0 and above 1 at once, i.e. always (a NaN +// too: its first comparison is unordered and takes the storing branch). +void AIMain::setAISystemQuotient(const double& q) { - BF2_AI_FRONTIER("dice::hfe::ai::AIMain::setAISystemQuotient"); + if (!(q < 0.0f) || !(q > 1.0f)) + m_aiSystemQuotient = q; } +// ELF 0x39FA00 (weak): `fldl 0x4(this)`. double AIMain::getAISystemQuotient() const { - BF2_AI_FRONTIER("dice::hfe::ai::AIMain::getAISystemQuotient"); + return m_aiSystemQuotient; } -void AIMain::setPlayerExitedVehicle(IAIObject* /*o*/, int /*a*/) +// ELF 0x39F230. When a human (IAIPlayer +0x88 getIsAIPlayer false) leaves a unit, the unit +// records the game time as its last possession (IAIObjectUnit +0x64; the unit plug-in is +// fetched before the time) and its primary object is allowed to bots again (+0x9C). +void AIMain::setPlayerExitedVehicle(IAIObject* vehicle, int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIMain::setPlayerExitedVehicle"); + IAIPlayer* const player = static_cast(CommonSingletonServer::m_iaiPlayerFactory) + ->getPlayerFromId(playerId); + if (vehicle && vehicle->isUnit() && player && !player->getIsAIPlayer()) + { + IAIObjectUnit* const unit = vehicle->getUnit(); + unit->setLastPlayerPossesionTime( + static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime()); + vehicle->getPrimaryObject()->setIsAllowedByBots(true); + } } -void AIMain::setPlayerEnteredVehicle(IAIObject* /*o*/, IAIObject* /*v*/, int /*a*/) +// ELF 0x39F2F0. A human moving between two units with different primary objects leaves the +// first unit's last possession at -1000.0f (ELF 0x49CDC8). The second object is tested first. +void AIMain::setPlayerEnteredVehicle(IAIObject* from, IAIObject* to, int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIMain::setPlayerEnteredVehicle"); + IAIPlayer* const player = static_cast(CommonSingletonServer::m_iaiPlayerFactory) + ->getPlayerFromId(playerId); + if (to && to->isUnit() && from && from->isUnit() && player && !player->getIsAIPlayer()) + { + IAIObject* const toPrimary = to->getPrimaryObject(); + IAIObject* const fromPrimary = from->getPrimaryObject(); + if (toPrimary && fromPrimary && toPrimary != fromPrimary) + from->getUnit()->setLastPlayerPossesionTime(-1000.0f); + } } // Initializes the AI synchronously from the level script and returns a status message. // The integer argument is unused. +// ELF 0x39D7E0 std::string AIMain::init(int) { // built first, before any work. The message is constructed at the top of the body and @@ -519,11 +714,8 @@ std::string AIMain::init(int) return result; } -// [FRONTIER] [TEMP] [CHOSEN, not recovered] -// The methods below stop until their remaining behavior is implemented and validated. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. - // Creates one strategic AI instance for each side. +// ELF 0x39EA20 void AIMain::createSAI() { const IAISettings* const settings = @@ -542,11 +734,12 @@ void AIMain::createSAI() max.x = static_cast(terrain->getWorldSizeX()); max.y = static_cast(terrain->getWorldSizeZ()); - m_sai[side] = ISAI::create(side, m_dword168, m_dword172, min, max); + m_sai[side] = ISAI::create(side, m_saiMapXDimension, m_saiMapYDimension, min, max); } } // Sets the requested state and returns the value accepted, or false when refused. +// ELF 0x39EB10 bool AIMain::setSAIEnable(bool enable) { if (AIStrategicObjectManager::getInstance()->getNumberOfStrategicObjects()) @@ -562,7 +755,117 @@ bool AIMain::setSAIEnable(bool enable) return false; } -// [FRONTIER] The remaining declarations require implementations before use. +// ELF 0x39DB30 +void AIMain::setAISystemComponentsQuotient(unsigned int botManager, unsigned int strategic) +{ + const unsigned int sum = botManager + strategic; + if (sum) + { + m_botManagerQuotient = static_cast(botManager) / sum; + m_componentQuotient = static_cast(strategic) / sum; + } +} + +// ELF 0x39EC60 +void AIMain::setSAIMapXDimension(int n) +{ + m_saiMapXDimension = n; + // Shipped defect: this tests the array address, not whether any SAI exists. + if (m_sai) + for (int side = 1; side < static_cast(CommonSingletonServer::m_iaiSettings)->getNSides() + 1; ++side) + if (m_sai[side]) + m_sai[side]->setMapXDimension(n); +} + +// ELF 0x39ECE0 +void AIMain::setSAIMapYDimension(int n) +{ + m_saiMapYDimension = n; + // Shipped defect: this tests the array address, not whether any SAI exists. + if (m_sai) + for (int side = 1; side < static_cast(CommonSingletonServer::m_iaiSettings)->getNSides() + 1; ++side) + if (m_sai[side]) + m_sai[side]->setMapYDimension(n); +} + +// ELF 0x39ED60 +int AIMain::getSAIMapXDimension() const { return m_saiMapXDimension; } + +// ELF 0x39ED70 +int AIMain::getSAIMapYDimension() const { return m_saiMapYDimension; } + +// ELF 0x39DD70 +int AIMain::getRenderSide() const { return m_renderSide; } + +// ELF 0x39DD80 +void AIMain::setRenderSide(int side) { m_renderSide = side; } + +// ELF 0x39ED80 +bool AIMain::getValidateDataStructuresEnabled() const { return m_validateDataStructuresEnabled; } + +// ELF 0x39ED90 +void AIMain::setValidateDataStructuresEnabled(bool b) { m_validateDataStructuresEnabled = b; } + +// ELF 0x39EDD0 +bool AIMain::getShowBotUrgencies() const { return m_showBotUrgencies; } + +// ELF 0x39EDB0 +void AIMain::setShowBotUrgencies(bool b) { m_showBotUrgencies = b; } + +// ELF 0x39EE00 +bool AIMain::getShowBotSpawnCoord() const { return m_showBotSpawnCoord; } + +// ELF 0x39EDE0 +void AIMain::setShowBotSpawnCoord(bool b) { m_showBotSpawnCoord = b; } + +// ELF 0x39EE30 +bool AIMain::getShowStrategies() const { return m_showStrategies; } + +// ELF 0x39EE10 +void AIMain::setShowStrategies(bool b) { m_showStrategies = b; } + +// ELF 0x39EE60 +bool AIMain::getShowSAIStats() const { return m_showSAIStats; } + +// ELF 0x39EE40 +void AIMain::setShowSAIStats(bool b) { m_showSAIStats = b; } + +// ELF 0x39EE90 +bool AIMain::getShowBotStats() const { return m_showBotStats; } + +// ELF 0x39EE70 +void AIMain::setShowBotStats(bool b) { m_showBotStats = b; } + +// ELF 0x39EEC0 +bool AIMain::getShowStrategicAreas() const { return m_showStrategicAreas; } + +// ELF 0x39EEA0 +void AIMain::setShowStrategicAreas(bool b) { m_showStrategicAreas = b; } + +// ELF 0x39EED0 +void AIMain::showAll(bool b) +{ + m_showBotUrgencies = b; + m_showStrategies = b; + m_showSAIStats = b; + m_showBotStats = b; + m_showStrategicAreas = b; +} + +// ELF 0x39EF00 +void AIMain::showStrategic(bool b) +{ + m_showStrategies = b; + m_showSAIStats = b; + m_showStrategicAreas = b; +} + +// ELF 0x39EF20 +void AIMain::showBot(bool b) +{ + m_showBotUrgencies = b; + m_showBotStats = b; +} } // namespace ai } // namespace hfe diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIMain.h b/Code/BF2/AI/AIDLL/AI/Main/AIMain.h index 1e2df4527..38f487cd2 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIMain.h +++ b/Code/BF2/AI/AIDLL/AI/Main/AIMain.h @@ -22,7 +22,6 @@ namespace world { class IPlayer; } namespace ai { class Bot; -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. class BotManager; class IAIObject; class SAI; @@ -34,12 +33,12 @@ class IAIMain virtual ~IAIMain(); // +0x00 / +0x04 virtual void addNewPlayer(world::IPlayer* player) = 0; // +0x08 - virtual void popPlayer() = 0; // +0x0C + virtual world::IPlayer* popPlayer() = 0; // +0x0C front of the queue, or null virtual void registerFreeBot(Bot* bot) = 0; // +0x10 // Returns whether the player was activated or queued successfully. virtual bool activateBot(int playerId, int side, const std::string& name) = 0; // +0x14 - virtual void deactivateBot(int& a, int b) = 0; // +0x18 - virtual void deactivateBot(int a) = 0; // +0x1C + virtual bool deactivateBot(int& playerId, int side) = 0; // +0x18 ELF answers 0/1 + virtual bool deactivateBot(int playerId) = 0; // +0x1C ELF answers 0/1 virtual void newPlayerCreated(bool b) = 0; // +0x20 virtual void reactivateBot(int a) = 0; // +0x24 virtual void switchSides(int a) = 0; // +0x28 @@ -52,8 +51,8 @@ class IAIMain virtual SAI* getSAI(int side) = 0; // +0x3C virtual void draw() = 0; // +0x40 virtual void updateAIObject(IAIObject* o) = 0; // +0x44 - virtual void reset() = 0; // +0x48 - virtual void resetLevel() = 0; // +0x4C + virtual bool reset() = 0; // +0x48 + virtual bool resetLevel() = 0; // +0x4C virtual void queueSoundEffect(const Vec3& pos, int a, int b) = 0;// +0x50 virtual void spawnBots() = 0; // +0x54 virtual void setAISystemQuotient(const double& q) = 0; // +0x58 @@ -81,17 +80,18 @@ class AIMain : public IAIMain // IAIMain, in vtable order virtual void addNewPlayer(world::IPlayer* player); - virtual void popPlayer(); + virtual world::IPlayer* popPlayer(); virtual void registerFreeBot(Bot* bot); virtual bool activateBot(int playerId, int side, const std::string& name); - virtual void deactivateBot(int& a, int b); - virtual void deactivateBot(int a); + virtual bool deactivateBot(int& playerId, int side); + virtual bool deactivateBot(int playerId); virtual void newPlayerCreated(bool b); virtual void reactivateBot(int a); // Queues an unspawned bot with its side-specific personality weights. // This nonvirtual AIMain entry is distinct from BotManager::addUnspawnedBot. bool addUnspawnedBot(int playerId, int side, float* personality); + bool addBot(int playerId, int side, float* personality, IAIObject* object); virtual void switchSides(int a); virtual void switchSides(int side, int playerId); virtual bool isInitialised(); @@ -100,8 +100,8 @@ class AIMain : public IAIMain virtual SAI* getSAI(int side); virtual void draw(); // - empty virtual void updateAIObject(IAIObject* o); - virtual void reset(); - virtual void resetLevel(); + virtual bool reset(); + virtual bool resetLevel(); virtual void queueSoundEffect(const Vec3& pos, int a, int b); // - empty virtual void spawnBots(); virtual void setAISystemQuotient(const double& q); @@ -117,7 +117,7 @@ class AIMain : public IAIMain // Initializes AI and returns its status message. The integer parameter is unused. std::string init(int); - void setAISystemComponentsQuotient(unsigned int a, unsigned int b); + void setAISystemComponentsQuotient(unsigned int botManager, unsigned int strategic); // Creates per-side strategic AI. setSAIEnable returns the resulting enabled state, // including false when enabling is refused. @@ -163,19 +163,22 @@ class AIMain : public IAIMain // by accessors. The three leading doubles partition frame time between AI and its subsystems. /* 0 */ // vptr /* 4 */ double m_aiSystemQuotient; // Frame-time share, initialized by widening 0.15f to double. - /* 12 */ double m_dword12; // = 0.875 [UNRESOLVED] + /* 12 */ double m_botManagerQuotient; // = 0.875 /* 20 */ double m_componentQuotient; // = 0.125; fraction of the AI budget // handed to the selected side's SAI // with action's additional 0.95 factor. /* 28 */ double m_double28; // = 0.0 [UNRESOLVED] /* 36 */ int m_dword36; // = 0 - /* 40 */ double m_double40; // = 3.0 [UNRESOLVED] +public: + // [CHOSEN, not recovered] Visibility for the generated inline console property. + /* 40 */ double m_botStatisticUpdateSpeed; // = 3.0; console stores its nonnegative magnitude +private: // Parallel per-bot data arrays, appended together when a bot is admitted. /* 48 */ std::vector > m_perBot48; /* 60 */ std::vector > m_perBot60; /* 72 */ std::vector > m_perBot72; /* 84 */ std::vector m_perBot84; - /* 96 */ std::list m_list96; + /* 96 */ std::list m_playerQueue; // addNewPlayer / popPlayer (ELF 0x39F920 / 0x39F970). Name [INFERRED]. /* 100 */ int m_dword100; // = 0 /* 104 */ bool m_initialised; // Set by init; read by isInitialised. // Gates strategic-AI updates; setSAIEnable controls it and init attempts to enable it. @@ -185,28 +188,28 @@ class AIMain : public IAIMain /* 116 */ char m_gap116[4]; // [UNRESOLVED] - the ctor never writes +116 /* 120 */ float m_float120; // Initially 100.0f; this field is a float. /* 124 */ char m_gap124[4]; // [UNRESOLVED] - never written - /* 128 */ int m_dword128; // = 1 + /* 128 */ int m_renderSide; // = 1 /* 132 */ int m_dword132; // = 0 - /* 136 */ bool m_flag136; // = false ] six adjacent bools, written - /* 137 */ bool m_flag137; // = true ] individually. Almost certainly - /* 138 */ bool m_flag138; // = false ] the show* debug switches, but - /* 139 */ bool m_flag139; // = true ] the setters have not been read - /* 140 */ bool m_flag140; // = true ] yet, so nothing is claimed. - /* 141 */ bool m_flag141; // = false ] [UNRESOLVED] + /* 136 */ bool m_showBotUrgencies; // = false + /* 137 */ bool m_showStrategies; // = true + /* 138 */ bool m_showSAIStats; // = false + /* 139 */ bool m_showBotStats; // = true + /* 140 */ bool m_showStrategicAreas; // = true + /* 141 */ bool m_showBotSpawnCoord; // = false /* 144 */ int m_dword144; // = 0 /* 148 */ bool m_flag148; // = false // One-based SAI array; slot zero remains null. Callers must supply a valid side. // The action cursor wraps modulo the side count, with no zero-count guard. /* 152 */ SAI* m_sai[3]; // 1-based; [0] is never used /* 164 */ unsigned int m_componentCursor; // [CHOSEN] - the round-robin cursor - /* 168 */ int m_dword168; // = 64 - /* 172 */ int m_dword172; // = 64 + /* 168 */ int m_saiMapXDimension; // = 64 + /* 172 */ int m_saiMapYDimension; // = 64 /* 176 */ double m_double176; // = -3.4028235e38 that is -FLT_MAX stored /* 184 */ double m_double184; // = -3.4028235e38 in a double. A "no value // yet" sentinel written with the float // constant. [UNRESOLVED] what they time. /* 192 */ BotManager* m_botManager; // Owned manager; action passes it the remaining time budget. - /* 196 */ bool m_flag196; // = false + /* 196 */ bool m_validateDataStructuresEnabled; // = false /* 200 */ std::list m_soundEffects; // allocate(28) -> 8 + 20; see SoundEffect // [UNRESOLVED] Map key and value types; current declarations preserve the observed storage shape. /* 204 */ std::map m_map204; // +204 node, +208 count, +212 comparator diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIModule.cpp b/Code/BF2/AI/AIDLL/AI/Main/AIModule.cpp index c205a1b44..b741a0a6c 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIModule.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/AIModule.cpp @@ -3,15 +3,47 @@ #include "AIModule.h" +#include #include +#include +#include #include #include "../../../../Core/ClassManager.h" #include "../../../../Core/ConsoleObjects.h" #include "../../../../Core/DllModule.h" #include "../../../../Core/Ids.h" +#include "../../../../Core/ConsoleObjectBase.h" +#include "../../../../Core/ConsoleObjectMacro.h" // BF2_CC_HEAD_NAMED, BF2_CC_ARG, return/range hooks #include "../AIUtils/checkPointer.h" #include "BF2AI.h" +#include "../AIPathFinding/Material/Material.h" +#include "../AIStrategic/Strategy.h" +#include "../AIStrategic/StrategyCondition.h" +#include "../AIStrategicEntity/AILandingZone.h" +#include "AILandingZoneManager.h" +#include "../AIStrategicEntity/AIStrategicArea.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" +#include "../AIStrategicEntity/CoverPosition/CoverPositionManager.h" +#include "../AIStrategicEntity/GuardPosition.h" +#include "../AIStrategicEntity/PatrolPath.h" +#include "../AIPathFinding/AerialHeightMap/AerialHeightMap.h" +#include "../DrawPrimitives/DPManager.h" +#include "AIConsole.h" +#include "AILODManager.h" +#include "AIMain.h" +#include "AIRandom.h" +#include "AISettings.h" +#include "AISettingsInterfaces.h" +#include "AIStreamOperators.h" +#include "BotBehaviourManager.h" +#include "BotPlacementManager.h" +#include "CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "IAIPathfinding.h" +#include "IBotManager.h" +#include "StrategyManager.h" +#include "../AIStrategicEntity/UserOrders/UserOrderManager.h" namespace dice { namespace hfe { @@ -21,31 +53,117 @@ namespace hfe { extern ClassManager* classManager; extern ConsoleObjects* mainConsoleObjects; -// Module instances allocated during DLL initialization. +// static init: ELF 0x486170 / 0x4861D0. The module pointer is initialized before the console list. IModule* dllmodules[] = { new ai::AIModule, 0 }; +// [INFERRED] The two unsigned spellings the bindings' type strings use ("hfe::uint", "u32"); both +// are extracted by istream::operator>>(unsigned int&) in the image. +typedef unsigned int uint; +typedef unsigned int u32; + namespace ai { +// The receivers of the generated console bindings (ELF 0x3EE940..0x3EEB40): each returns the +// active object of its manager, or null while the manager does not exist. + +// ELF 0x3EE940 +PatrolPath* getActivePatrolPathIfManager() +{ + PatrolPath* path = 0; + if (UserOrderManager::m_instance) + path = UserOrderManager::m_instance->getActivePatrolPath(); + return path; +} + +// ELF 0x3EE980 +GuardPosition* getActiveGuardPositionIfManager() +{ + GuardPosition* position = 0; + if (UserOrderManager::m_instance) + position = UserOrderManager::m_instance->getActiveGuardPosition(); + return position; +} + +// ELF 0x3EE9C0: IAIPathfindingSetup +0x50. +IAIPathfindingSetup::IMapContainer* getActiveMapContainer() +{ + if (!IAIPathfindingSetup::instance) + return 0; + return IAIPathfindingSetup::instance->getActiveMapContainer(); +} + +// ELF 0x3EEA00: getInstance is called twice, once for the test and once for the call. +Strategy* getActiveStrategy() +{ + Strategy* strategy = 0; + if (StrategyManager::getInstance()) + strategy = StrategyManager::getInstance()->getActiveStrategy(); + return strategy; +} + +// ELF 0x3EEA40. The executors call AIMain members on the result non-virtually, so the helper's +// type is AIMain* [INFERRED]; IAIMain is AIMain's only base, the conversion moves no pointer. +AIMain* getActiveAIMain() +{ + AIMain* aiMain = 0; + if (AIConsole::m_instance) + aiMain = static_cast(AIConsole::m_instance->getActiveAIMain()); + return aiMain; +} + +// ELF 0x3EEA80 +StrategyCondition* getActiveCondition() +{ + StrategyCondition* condition = 0; + if (StrategyManager::getInstance()) + condition = StrategyManager::getInstance()->getActiveCondition(); + return condition; +} + +// ELF 0x3EEAC0 +AIStrategicArea* getActiveStrategicArea() +{ + AIStrategicArea* area = 0; + if (AIStrategicObjectManager::getInstance()) + area = AIStrategicObjectManager::getInstance()->getActiveArea(); + return area; +} + +// ELF 0x3EEB00 +AILandingZone* getActiveLandingZone() +{ + AILandingZone* zone = 0; + if (AILandingZoneManager::m_instance) + zone = AILandingZoneManager::m_instance->getActiveZone(); + return zone; +} + +// ELF 0x3EEB40: the settings singleton, unchecked. +IAISettings* getAISettings() +{ + return static_cast(CommonSingletonServer::m_iaiSettings); +} + namespace { -// Console objects registered by module initialization and removed on close. +// static init: ELF 0x3EEE90, _GLOBAL__I 0x40FA70; stream cleanup __tcf_111 0x40A860. +// [CHOSEN, not recovered] Explicit object retains the two merged TUs' initialization order. +std::ios_base::Init consoleStreamInit; -} // anonymous namespace +// The one list every generated binding of this file appends itself to; init registers it. +// static init: ELF 0x3EEE90; list cleanup __tcf_112 0x40A890 releases nodes, not their pointers. +ConsoleObjects::ConsoleObjectList aiList; -// Defined in AIConsole.cpp, beside the binding itself. -ConsoleObjects::ConsoleObjectList& aiConsoleObjects(); -ConsoleObjects::ConsoleObjectList& aiSettingsConsoleObjects(); // AISettings.cpp -// AIStrategicEntity/AIStrategicObjectManager.cpp - `aiStrategicArea.createFromControlPoint`, the -// one command of nine on that object whose whole chain is written. -ConsoleObjects::ConsoleObjectList& aiStrategicAreaConsoleObjects(); -// Pathfinding console commands for navigation meshes, properties, and the trace map. -ConsoleObjects::ConsoleObjectList& aiPathfindingConsoleObjects(); +#include "AIModuleConsole.inc" + +} // anonymous namespace // Two stores and nothing else - the vptr, and a refcount of one. +// ELF 0x4861F0 AIModule::AIModule() : m_refCount(1) { @@ -54,11 +172,13 @@ AIModule::AIModule() // The IBase quartet. Textbook, and reproduced because "textbook" is itself a finding - the AI module // does not do anything unusual with lifetime. +// ELF 0x40FA90 void AIModule::addRef() { ++m_refCount; } +// ELF 0x40FAA0 int AIModule::getRef() { return m_refCount; @@ -66,6 +186,7 @@ int AIModule::getRef() // Decrements the reference count and frees this without a destructor at zero. // Requires a heap-allocated module with no member cleanup. +// ELF 0x40FAB0 int AIModule::release() { const int n = --m_refCount; @@ -75,6 +196,7 @@ int AIModule::release() } // Returns the interface pointer for IBase, IClassServer, or IModule, testing in that order. +// ELF 0x40FAF0 void* AIModule::queryInterface(unsigned int iid) const { if (iid == IID_IBase || iid == IID_IClassServer) @@ -90,40 +212,37 @@ void* AIModule::queryInterface(unsigned int iid) const // class ids and is therefore reachable only as a simple singleton. // - a bare `ret`. +// ELF 0x3EEDD0 void AIModule::getClassList(std::vector& /*out*/) { } // - a bare `ret`. +// ELF 0x3EEDC0 void AIModule::getSingletonList(std::vector& /*out*/) { } // Creates the AI singleton and publishes its console bindings. +// ELF 0x3EEB60 bool AIModule::init() { - std::fflush(stderr); - mainConsoleObjects->registerConsoleObjects(aiConsoleObjects()); - mainConsoleObjects->registerConsoleObjects(aiSettingsConsoleObjects()); - mainConsoleObjects->registerConsoleObjects(aiStrategicAreaConsoleObjects()); - mainConsoleObjects->registerConsoleObjects(aiPathfindingConsoleObjects()); + mainConsoleObjects->registerConsoleObjects(aiList); BF2AI* ai = new BF2AI; // Preserves the explicit allocation check even with throwing operator new. checkPointer(ai); - // true even if the above failed - see the file header. + // Returns true if the allocation diagnostic returns. return true; } // Unregisters console objects and looks up the AI through getSingleton. The original // uses the wrong registry for this simple singleton, leaving the object allocated. +// ELF 0x3EECB0 bool AIModule::close() { - mainConsoleObjects->unregisterConsoleObjects(aiConsoleObjects()); - mainConsoleObjects->unregisterConsoleObjects(aiSettingsConsoleObjects()); - mainConsoleObjects->unregisterConsoleObjects(aiStrategicAreaConsoleObjects()); - mainConsoleObjects->unregisterConsoleObjects(aiPathfindingConsoleObjects()); + mainConsoleObjects->unregisterConsoleObjects(aiList); // getSingleton (+0x4C) searches m_normalSingletons. "AI" was registered into // m_simpleSingletons. This returns null on every run. @@ -134,11 +253,8 @@ bool AIModule::close() if (ai) { - // IAI vtable +0x04 - the deleting destructor , not release. IAI is not an IBase and - // has no refcount to drop. [FRONTIER] to express in C++ until IAI's destructor is declared - // in a way this file can reach; the call is recorded rather than written, because on every - // real run `ai` is null and the arm is dead. - // reinterpret_cast(ai)->~IAI; // conceptually; the slot is , so: delete + // shipped defect: the normal-registry result is treated as IAI despite its IBase type. + delete reinterpret_cast(ai); } return true; diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIModuleConsole.inc b/Code/BF2/AI/AIDLL/AI/Main/AIModuleConsole.inc new file mode 100644 index 000000000..a3dbd9d14 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/Main/AIModuleConsole.inc @@ -0,0 +1,9595 @@ +// GENERATED FILE - do not edit by hand. Regenerate with +// python3 tools/ai-reconstruct/gen_console_bindings.py +// from libaidll.so (Linux 1.5.3153, ia-32, with symbols). Every address is an ELF address. +// +// The AI image's console bindings: 298 generated classes ConsoleClass, all in the +// anonymous namespace of AIModule.cpp (the original __LINE__ is the class number). Emitted here: +// 298; the 0 left out are listed in place with the reason (their commands stay +// unregistered, as before this file existed). Shared shapes recovered from the image: +// - constructor (inlined into AIModule.cpp's static initializer, ELF 0x3EEE90): object name, +// access and category from the SetConsoleClassDefaults in force; function name, m_type, +// min/max argument count, return-type and argument-type strings (the stringized C++ types), +// the +0xA1 flag (1 exactly when getReturnValueAsString formats a value), then the +// needs-conversion flags (`argType != "std::string"`) and `aiList.push_back(this)`. +// - isObjectActive: `receiver != 0`, the receiver being a global or an AIModule.cpp getter. +// - executeObjectMethod: one arm per accepted argument count; m_hasReturnValue is stored before +// the receiver is evaluated; the arm calls receiver->method(arguments) (virtual calls through +// the receiver's static type) and stores the result when the flag is set. Arms that pass fewer +// arguments than the target takes rely on the target's C++ default arguments. +// The verified inline bodies preserve argument copies before that flag, unchecked indices, +// repeated stores and discarded results; see each class's inline-body note and JSON hash. +// - setArgFromString(index): `static T arg; std::istringstream in(value); in >> arg; +// m_args[index - 1] = &arg;` with no fail check (no temporary, unlike Core's BF2_CC_CONVERT). +// - getReturnValueAsString / range hooks: Core/ConsoleObjectMacro.h's BF2_CC_RETURN_AS_STRING, +// BF2_CC_NO_RETURN_AS_STRING and BF2_CC_COMMON_HOOKS (one shape each in the image). +// [INFERRED] The original macro names; the class bodies are spelled out because the shared +// BF2_CONSOLE_* families hard-code a different +0xA1 value and the temp-and-commit conversion. + +#pragma push_macro("BF2_CC_NAME") + +// Converts argument `oneBasedIndex` into its function-local static (one per argument). +#define AIMODULE_CC_EXTRACT(T, oneBasedIndex) \ + if (index == (oneBasedIndex)) \ + { \ + static T arg; \ + std::istringstream in(value); \ + in >> arg; \ + m_args[(oneBasedIndex) - 1] = reinterpret_cast(&arg); \ + } + +// The same, where the image calls a named extractor that overload resolution would not pick. +#define AIMODULE_CC_EXTRACT_WITH(T, oneBasedIndex, extractor) \ + if (index == (oneBasedIndex)) \ + { \ + static T arg; \ + std::istringstream in(value); \ + extractor(in, arg); \ + m_args[(oneBasedIndex) - 1] = reinterpret_cast(&arg); \ + } + +// Closes the constructor BF2_CC_HEAD_NAMED opened: conversion flags, then this file's list. +#define AIMODULE_CC_TAIL(nArgs) \ + for (int i = 0; i < (nArgs); ++i) \ + m_argNeedsConversion[i] = \ + (std::string(m_argTypes[i]) == "std::string") ? 0 : -1; \ + aiList.push_back(this); \ + } + + +SetConsoleClassDefaults IAIfullAccessSetConsoleClassDefaults("IAI", 2, 0); + +SetConsoleClassDefaults AIfullAccessSetConsoleClassDefaults("AI", 2, 0); + +// ConsoleClass161 AI.createHeightMap: method, 0..1 arguments, no result. +// ELF isObjectActive 0x40FF70, executeObjectMethod 0x4102D0, +// setArgFromString 0x410090, getReturnValueAsString 0x40FF30, D1 0x40FF10, D0 0x40FED0. +// argc 0: dice::hfe::ai::AerialHeightMap::createHeightMap(int) (call at 0x41031B; ledger done) +// argc 1: dice::hfe::ai::AerialHeightMap::createHeightMap(int) (call at 0x41031B; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass161 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createHeightMap", 0, 0, 1, "void", false) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AerialHeightMap::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + AerialHeightMap::m_instance->createHeightMap(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + AerialHeightMap::m_instance->createHeightMap(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject161; + +// ConsoleClass162 AI.readHeightMapFromFile: method, 0..0 arguments, no result. +// ELF isObjectActive 0x4103E0, executeObjectMethod 0x410510, +// setArgFromString 0x410500, getReturnValueAsString 0x4103A0, D1 0x410380, D0 0x410340. +// argc 0: dice::hfe::ai::AerialHeightMap::readHeightMapFromFile() (call at 0x410549; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass162 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("readHeightMapFromFile", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AerialHeightMap::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + AerialHeightMap::m_instance->readHeightMapFromFile(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject162; + +// ConsoleClass165 AI.init: method, 1..1 arguments, no result. +// ELF isObjectActive 0x4105F0, executeObjectMethod 0x410950, +// setArgFromString 0x410710, getReturnValueAsString 0x4105B0, D1 0x410590, D0 0x410550. +// argc 1: dice::hfe::ai::AIConsole::init(int) (call at 0x410991; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass165 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("init", 0, 1, 1, "void", false) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + AIConsole::m_instance->init(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject165; + +// ConsoleClass168 AI.debug: method, 0..0 arguments, no result. +// ELF isObjectActive 0x410A40, executeObjectMethod 0x410B70, +// setArgFromString 0x410B60, getReturnValueAsString 0x410A00, D1 0x4109E0, D0 0x4109A0. +// argc 0: dice::hfe::ai::AIConsole::debug() (call at 0x410BA9; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass168 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("debug", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + AIConsole::m_instance->debug(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject168; + +// ConsoleClass171 AI.writeBotPlans: method, 0..0 arguments, no result. +// ELF isObjectActive 0x410C50, executeObjectMethod 0x410D80, +// setArgFromString 0x410D70, getReturnValueAsString 0x410C10, D1 0x410BF0, D0 0x410BB0. +// argc 0: dice::hfe::ai::BotManager::writeBotPlans() (slot +0x7C at 0x410DBB; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass171 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("writeBotPlans", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManager::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + IBotManager::instance->writeBotPlans(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject171; + +// ConsoleClass174 AI.aiSystemQuotient: property, 0..1 arguments, returns double. +// ELF isObjectActive 0x411060, executeObjectMethod 0x4113D0, +// setArgFromString 0x411190, getReturnValueAsString 0x410E20, D1 0x410E00, D0 0x410DC0. +// argc 0: dice::hfe::ai::AIMain::getAISystemQuotient() const (slot +0x5C at 0x411438; ledger done) +// argc 1: dice::hfe::ai::AIMain::setAISystemQuotient(double const&) (slot +0x58 at 0x411420; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass174 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("aiSystemQuotient", 1, 0, 1, "double", true) + m_argTypes[0] = "double"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveAIMain()->getAISystemQuotient(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveAIMain()->setAISystemQuotient(BF2_CC_ARG(double, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(double, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + double m_returnValue; +}; +BF2_CC_NAME consoleObject174; + +// ConsoleClass175 AI.setAISystemComponentsQuotient: method, 2..2 arguments, no result. +// ELF isObjectActive 0x4114F0, executeObjectMethod 0x411AA0, +// setArgFromString 0x411620, getReturnValueAsString 0x4114B0, D1 0x411490, D0 0x411450. +// argc 2: dice::hfe::ai::AIMain::setAISystemComponentsQuotient(unsigned int, unsigned int) (call at 0x411AF3; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass175 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setAISystemComponentsQuotient", 0, 2, 2, "void", false) + m_argTypes[0] = "hfe::uint"; + m_argTypes[1] = "hfe::uint"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + getActiveAIMain()->setAISystemComponentsQuotient(BF2_CC_ARG(hfe::uint, 0), BF2_CC_ARG(hfe::uint, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(hfe::uint, 1) + AIMODULE_CC_EXTRACT(hfe::uint, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject175; + +// ConsoleClass176 AI.getBotManagerQuotient: method, 0..0 arguments, double result discarded. +// ELF isObjectActive 0x411BA0, executeObjectMethod 0x411CE0, +// setArgFromString 0x411CD0, getReturnValueAsString 0x411B60, D1 0x411B40, D0 0x411B00. +// argc 0: verified inline body, discarded quotient getter; evaluates only the receiver +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass176 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getBotManagerQuotient", 0, 0, 0, "double", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + (void)getActiveAIMain(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject176; + +// ConsoleClass177 AI.getSAIQuotient: method, 0..0 arguments, double result discarded. +// ELF isObjectActive 0x411DC0, executeObjectMethod 0x411F00, +// setArgFromString 0x411EF0, getReturnValueAsString 0x411D80, D1 0x411D60, D0 0x411D20. +// argc 0: verified inline body, discarded quotient getter; evaluates only the receiver +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass177 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getSAIQuotient", 0, 0, 0, "double", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + (void)getActiveAIMain(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject177; + +// ConsoleClass178 AI.botStatisticUpdateSpeed: property, 0..1 arguments, returns double. +// ELF isObjectActive 0x4121E0, executeObjectMethod 0x412550, +// setArgFromString 0x412310, getReturnValueAsString 0x411FA0, D1 0x411F80, D0 0x411F40. +// argc 0: verified inline body, statistic speed; ia-32 negates exactly when value < 0 (retains -0 and unordered values) +// argc 1: verified inline body, statistic speed; ia-32 negates exactly when value < 0 (retains -0 and unordered values) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass178 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("botStatisticUpdateSpeed", 1, 0, 1, "double", true) + m_argTypes[0] = "double"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveAIMain()->m_botStatisticUpdateSpeed; + } + else if (m_argCount == 1) + { + const double value = BF2_CC_ARG(double, 0); + m_hasReturnValue = false; + AIMain* const object = getActiveAIMain(); + object->m_botStatisticUpdateSpeed = value < 0.0 ? -value : value; + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(double, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + double m_returnValue; +}; +BF2_CC_NAME consoleObject178; + +// ConsoleClass181 AI.getBotCount: method, 0..0 arguments, returns hfe::uint. +// ELF isObjectActive 0x412870, executeObjectMethod 0x4129A0, +// setArgFromString 0x412990, getReturnValueAsString 0x412630, D1 0x412610, D0 0x4125D0. +// argc 0: dice::hfe::ai::BotManager::getBotCount() const (slot +0x8 at 0x4129D5; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass181 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getBotCount", 0, 0, 0, "hfe::uint", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManager::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManager::instance->getBotCount(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + hfe::uint m_returnValue; +}; +BF2_CC_NAME consoleObject181; + +// ConsoleClass182 AI.getNumberOfActiveBots: method, 0..0 arguments, returns hfe::uint. +// ELF isObjectActive 0x412CA0, executeObjectMethod 0x412DD0, +// setArgFromString 0x412DC0, getReturnValueAsString 0x412A60, D1 0x412A40, D0 0x412A00. +// argc 0: dice::hfe::ai::BotManager::getNumberOfActiveBots() const (slot +0xC at 0x412E05; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass182 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getNumberOfActiveBots", 0, 0, 0, "hfe::uint", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManager::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManager::instance->getNumberOfActiveBots(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + hfe::uint m_returnValue; +}; +BF2_CC_NAME consoleObject182; + +// ConsoleClass183 AI.getNumberOfDeactivedBots: method, 0..0 arguments, returns hfe::uint. +// ELF isObjectActive 0x4130D0, executeObjectMethod 0x413200, +// setArgFromString 0x4131F0, getReturnValueAsString 0x412E90, D1 0x412E70, D0 0x412E30. +// argc 0: dice::hfe::ai::BotManager::getNumberOfDeactivedBots() const (slot +0x10 at 0x413235; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass183 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getNumberOfDeactivedBots", 0, 0, 0, "hfe::uint", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManager::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManager::instance->getNumberOfDeactivedBots(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + hfe::uint m_returnValue; +}; +BF2_CC_NAME consoleObject183; + +// ConsoleClass186 AI.addBot: method, 4..4 arguments, returns int. +// ELF isObjectActive 0x413530, executeObjectMethod 0x413FC0, +// setArgFromString 0x413650, getReturnValueAsString 0x4132C0, D1 0x4132A0, D0 0x413260. +// argc 4: dice::hfe::ai::AIConsole::addBot(std::string, int, std::string, std::string) (call at 0x4140AF; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass186 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addBot", 0, 4, 4, "int", true) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "int"; + m_argTypes[2] = "std::string"; + m_argTypes[3] = "std::string"; + AIMODULE_CC_TAIL(4) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 4) + { + m_hasReturnValue = true; + m_returnValue = AIConsole::m_instance->addBot(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(int, 1), BF2_CC_ARG(std::string, 2), BF2_CC_ARG(std::string, 3)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(int, 2) + AIMODULE_CC_EXTRACT(std::string, 3) + AIMODULE_CC_EXTRACT(std::string, 4) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject186; + +// ConsoleClass187 AI.addUnspawnedBot: method, 3..3 arguments, returns int. +// ELF isObjectActive 0x4144B0, executeObjectMethod 0x414CE0, +// setArgFromString 0x4145D0, getReturnValueAsString 0x414240, D1 0x414220, D0 0x4141E0. +// argc 3: dice::hfe::ai::AIConsole::addUnspawnedBot(std::string, int, std::string) (call at 0x414D80; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass187 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addUnspawnedBot", 0, 3, 3, "int", true) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "int"; + m_argTypes[2] = "std::string"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = true; + m_returnValue = AIConsole::m_instance->addUnspawnedBot(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(int, 1), BF2_CC_ARG(std::string, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(int, 2) + AIMODULE_CC_EXTRACT(std::string, 3) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject187; + +// ConsoleClass188 AI.deactivateBot: method, 1..1 arguments, returns bool. +// ELF isObjectActive 0x4150E0, executeObjectMethod 0x415450, +// setArgFromString 0x415210, getReturnValueAsString 0x414EA0, D1 0x414E80, D0 0x414E40. +// argc 1: dice::hfe::ai::AIMain::deactivateBot(int) (slot +0x1C at 0x41548D; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass188 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("deactivateBot", 0, 1, 1, "bool", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = getActiveAIMain()->deactivateBot(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject188; + +// ConsoleClass189 AI.updateBot: method, 1..1 arguments, no result. +// ELF isObjectActive 0x415560, executeObjectMethod 0x4158C0, +// setArgFromString 0x415680, getReturnValueAsString 0x415520, D1 0x415500, D0 0x4154C0. +// argc 1: dice::hfe::ai::AIConsole::updateBot(int) (call at 0x415901; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass189 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("updateBot", 0, 1, 1, "void", false) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + AIConsole::m_instance->updateBot(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject189; + +// ConsoleClass190 AI.killBotId: method, 1..1 arguments, returns std::string. +// ELF isObjectActive 0x415C30, executeObjectMethod 0x415F90, +// setArgFromString 0x415D50, getReturnValueAsString 0x4159F0, D1 0x415980, D0 0x415910. +// argc 1: dice::hfe::ai::AIConsole::killBotId(int) (call at 0x415FDB; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass190 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("killBotId", 0, 1, 1, "std::string", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = AIConsole::m_instance->killBotId(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject190; + +// ConsoleClass191 AI.killBotName: method, 1..1 arguments, returns std::string. +// ELF isObjectActive 0x416350, executeObjectMethod 0x4166F0, +// setArgFromString 0x416470, getReturnValueAsString 0x416110, D1 0x4160A0, D0 0x416030. +// argc 1: dice::hfe::ai::AIConsole::killBotName(std::string const&) (call at 0x416754; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass191 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("killBotName", 0, 1, 1, "std::string", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = AIConsole::m_instance->killBotName(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject191; + +// ConsoleClass192 AI.killAllBots: method, 0..0 arguments, no result. +// ELF isObjectActive 0x416870, executeObjectMethod 0x4169A0, +// setArgFromString 0x416990, getReturnValueAsString 0x416830, D1 0x416810, D0 0x4167D0. +// argc 0: dice::hfe::ai::AIConsole::killAllBots() (call at 0x4169D9; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass192 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("killAllBots", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + AIConsole::m_instance->killAllBots(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject192; + +// ConsoleClass195 AI.botGiveOrder: method, 3..3 arguments, no result. +// ELF isObjectActive 0x416A80, executeObjectMethod 0x4172B0, +// setArgFromString 0x416BA0, getReturnValueAsString 0x416A40, D1 0x416A20, D0 0x4169E0. +// argc 3: dice::hfe::ai::AIConsole::botGiveOrder(int, std::string, std::string) (call at 0x41735E; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass195 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("botGiveOrder", 0, 3, 3, "void", false) + m_argTypes[0] = "int"; + m_argTypes[1] = "std::string"; + m_argTypes[2] = "std::string"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = false; + AIConsole::m_instance->botGiveOrder(BF2_CC_ARG(int, 0), BF2_CC_ARG(std::string, 1), BF2_CC_ARG(std::string, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + AIMODULE_CC_EXTRACT(std::string, 3) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject195; + +// ConsoleClass196 AI.botSetWaypoints_Patrol: method, 5..6 arguments, no result. +// ELF isObjectActive 0x417490, executeObjectMethod 0x418570, +// setArgFromString 0x4175B0, getReturnValueAsString 0x417450, D1 0x417430, D0 0x4173F0. +// argc 5: dice::hfe::ai::AIConsole::botSetWaypoints_Patrol(int, float, int, dice::hfe::Vec3, dice::hfe::Vec3, dice::hfe::Vec3) (call at 0x418671; ledger stop) +// argc 6: dice::hfe::ai::AIConsole::botSetWaypoints_Patrol(int, float, int, dice::hfe::Vec3, dice::hfe::Vec3, dice::hfe::Vec3) (call at 0x418671; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass196 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("botSetWaypoints_Patrol", 0, 5, 6, "void", false) + m_argTypes[0] = "int"; + m_argTypes[1] = "float"; + m_argTypes[2] = "int"; + m_argTypes[3] = "hfe::Vec3"; + m_argTypes[4] = "hfe::Vec3"; + m_argTypes[5] = "hfe::Vec3"; + AIMODULE_CC_TAIL(6) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 5) + { + m_hasReturnValue = false; + AIConsole::m_instance->botSetWaypoints_Patrol(BF2_CC_ARG(int, 0), BF2_CC_ARG(float, 1), BF2_CC_ARG(int, 2), BF2_CC_ARG(hfe::Vec3, 3), BF2_CC_ARG(hfe::Vec3, 4)); + } + else if (m_argCount == 6) + { + m_hasReturnValue = false; + AIConsole::m_instance->botSetWaypoints_Patrol(BF2_CC_ARG(int, 0), BF2_CC_ARG(float, 1), BF2_CC_ARG(int, 2), BF2_CC_ARG(hfe::Vec3, 3), BF2_CC_ARG(hfe::Vec3, 4), BF2_CC_ARG(hfe::Vec3, 5)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + AIMODULE_CC_EXTRACT(float, 2) + AIMODULE_CC_EXTRACT(int, 3) + AIMODULE_CC_EXTRACT(hfe::Vec3, 4) + AIMODULE_CC_EXTRACT(hfe::Vec3, 5) + AIMODULE_CC_EXTRACT(hfe::Vec3, 6) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject196; + +// ConsoleClass197 AI.botSetWaypoints_Patrol3d: method, 5..6 arguments, no result. +// ELF isObjectActive 0x4187D0, executeObjectMethod 0x4198B0, +// setArgFromString 0x4188F0, getReturnValueAsString 0x418790, D1 0x418770, D0 0x418730. +// argc 5: dice::hfe::ai::AIConsole::botSetWaypoints_Patrol3d(int, float, int, dice::hfe::Vec3, dice::hfe::Vec3, dice::hfe::Vec3) (call at 0x4199B1; ledger stop) +// argc 6: dice::hfe::ai::AIConsole::botSetWaypoints_Patrol3d(int, float, int, dice::hfe::Vec3, dice::hfe::Vec3, dice::hfe::Vec3) (call at 0x4199B1; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass197 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("botSetWaypoints_Patrol3d", 0, 5, 6, "void", false) + m_argTypes[0] = "int"; + m_argTypes[1] = "float"; + m_argTypes[2] = "int"; + m_argTypes[3] = "hfe::Vec3"; + m_argTypes[4] = "hfe::Vec3"; + m_argTypes[5] = "hfe::Vec3"; + AIMODULE_CC_TAIL(6) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 5) + { + m_hasReturnValue = false; + AIConsole::m_instance->botSetWaypoints_Patrol3d(BF2_CC_ARG(int, 0), BF2_CC_ARG(float, 1), BF2_CC_ARG(int, 2), BF2_CC_ARG(hfe::Vec3, 3), BF2_CC_ARG(hfe::Vec3, 4)); + } + else if (m_argCount == 6) + { + m_hasReturnValue = false; + AIConsole::m_instance->botSetWaypoints_Patrol3d(BF2_CC_ARG(int, 0), BF2_CC_ARG(float, 1), BF2_CC_ARG(int, 2), BF2_CC_ARG(hfe::Vec3, 3), BF2_CC_ARG(hfe::Vec3, 4), BF2_CC_ARG(hfe::Vec3, 5)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + AIMODULE_CC_EXTRACT(float, 2) + AIMODULE_CC_EXTRACT(int, 3) + AIMODULE_CC_EXTRACT(hfe::Vec3, 4) + AIMODULE_CC_EXTRACT(hfe::Vec3, 5) + AIMODULE_CC_EXTRACT(hfe::Vec3, 6) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject197; + +// ConsoleClass198 AI.botMoveTo: method, 3..3 arguments, no result. +// ELF isObjectActive 0x419B10, executeObjectMethod 0x41A370, +// setArgFromString 0x419C30, getReturnValueAsString 0x419AD0, D1 0x419AB0, D0 0x419A70. +// argc 3: dice::hfe::ai::AIConsole::botMoveTo(float, dice::hfe::Vec3, int) (call at 0x41A3F0; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass198 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("botMoveTo", 0, 3, 3, "void", false) + m_argTypes[0] = "float"; + m_argTypes[1] = "hfe::Vec3"; + m_argTypes[2] = "int"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = false; + AIConsole::m_instance->botMoveTo(BF2_CC_ARG(float, 0), BF2_CC_ARG(hfe::Vec3, 1), BF2_CC_ARG(int, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + AIMODULE_CC_EXTRACT(hfe::Vec3, 2) + AIMODULE_CC_EXTRACT(int, 3) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject198; + +// ConsoleClass199 AI.botFlyTo: method, 5..5 arguments, no result. +// ELF isObjectActive 0x41A4A0, executeObjectMethod 0x41B150, +// setArgFromString 0x41A5C0, getReturnValueAsString 0x41A460, D1 0x41A440, D0 0x41A400. +// argc 5: dice::hfe::ai::AIConsole::botFlyTo(int, float, float, float, dice::hfe::Vec3) (call at 0x41B1E2; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass199 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("botFlyTo", 0, 5, 5, "void", false) + m_argTypes[0] = "int"; + m_argTypes[1] = "float"; + m_argTypes[2] = "float"; + m_argTypes[3] = "float"; + m_argTypes[4] = "hfe::Vec3"; + AIMODULE_CC_TAIL(5) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 5) + { + m_hasReturnValue = false; + AIConsole::m_instance->botFlyTo(BF2_CC_ARG(int, 0), BF2_CC_ARG(float, 1), BF2_CC_ARG(float, 2), BF2_CC_ARG(float, 3), BF2_CC_ARG(hfe::Vec3, 4)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + AIMODULE_CC_EXTRACT(float, 2) + AIMODULE_CC_EXTRACT(float, 3) + AIMODULE_CC_EXTRACT(float, 4) + AIMODULE_CC_EXTRACT(hfe::Vec3, 5) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject199; + +// ConsoleClass202 AI.createSAI: method, 0..0 arguments, no result. +// ELF isObjectActive 0x41B290, executeObjectMethod 0x41B3D0, +// setArgFromString 0x41B3C0, getReturnValueAsString 0x41B250, D1 0x41B230, D0 0x41B1F0. +// argc 0: dice::hfe::ai::AIMain::createSAI() (call at 0x41B406; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass202 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createSAI", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + getActiveAIMain()->createSAI(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject202; + +// ConsoleClass203 AI.saiEnable: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x41B6B0, executeObjectMethod 0x41BA20, +// setArgFromString 0x41B7E0, getReturnValueAsString 0x41B470, D1 0x41B450, D0 0x41B410. +// argc 0: dice::hfe::ai::AIMain::getSAIEnable() (slot +0x38 at 0x41BA91; ledger done) +// argc 1: dice::hfe::ai::AIMain::setSAIEnable(bool) (call at 0x41BA70; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass203 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("saiEnable", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveAIMain()->getSAIEnable(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveAIMain()->setSAIEnable(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject203; + +// ConsoleClass204 AI.saiMapXDimension: property, 0..1 arguments, returns int. +// ELF isObjectActive 0x41BD80, executeObjectMethod 0x41C0F0, +// setArgFromString 0x41BEB0, getReturnValueAsString 0x41BB10, D1 0x41BAF0, D0 0x41BAB0. +// argc 0: dice::hfe::ai::AIMain::getSAIMapXDimension() const (call at 0x41C156; ledger done) +// argc 1: dice::hfe::ai::AIMain::setSAIMapXDimension(int) (call at 0x41C13E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass204 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("saiMapXDimension", 1, 0, 1, "int", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveAIMain()->getSAIMapXDimension(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveAIMain()->setSAIMapXDimension(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject204; + +// ConsoleClass205 AI.saiMapYDimension: property, 0..1 arguments, returns int. +// ELF isObjectActive 0x41C440, executeObjectMethod 0x41C7B0, +// setArgFromString 0x41C570, getReturnValueAsString 0x41C1D0, D1 0x41C1B0, D0 0x41C170. +// argc 0: dice::hfe::ai::AIMain::getSAIMapYDimension() const (call at 0x41C816; ledger done) +// argc 1: dice::hfe::ai::AIMain::setSAIMapYDimension(int) (call at 0x41C7FE; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass205 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("saiMapYDimension", 1, 0, 1, "int", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveAIMain()->getSAIMapYDimension(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveAIMain()->setSAIMapYDimension(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject205; + +// ConsoleClass206 AI.addSAIStrategy: method, 2..2 arguments, no result. +// ELF isObjectActive 0x41C8D0, executeObjectMethod 0x41CEC0, +// setArgFromString 0x41C9F0, getReturnValueAsString 0x41C890, D1 0x41C870, D0 0x41C830. +// argc 2: dice::hfe::ai::AIConsole::addSAIStrategy(int, std::string) (call at 0x41CF40; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass206 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addSAIStrategy", 0, 2, 2, "void", false) + m_argTypes[0] = "int"; + m_argTypes[1] = "std::string"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + AIConsole::m_instance->addSAIStrategy(BF2_CC_ARG(int, 0), BF2_CC_ARG(std::string, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject206; + +// ConsoleClass209 AI.renderSide: property, 0..1 arguments, returns int. +// ELF isObjectActive 0x41D260, executeObjectMethod 0x41D5D0, +// setArgFromString 0x41D390, getReturnValueAsString 0x41CFF0, D1 0x41CFD0, D0 0x41CF90. +// argc 0: dice::hfe::ai::AIMain::getRenderSide() const (call at 0x41D636; ledger done) +// argc 1: dice::hfe::ai::AIMain::setRenderSide(int) (call at 0x41D61E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass209 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("renderSide", 1, 0, 1, "int", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveAIMain()->getRenderSide(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveAIMain()->setRenderSide(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject209; + +// ConsoleClass211 AI.validateDataStructuresEnabled: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x41D8F0, executeObjectMethod 0x41DC60, +// setArgFromString 0x41DA20, getReturnValueAsString 0x41D6B0, D1 0x41D690, D0 0x41D650. +// argc 0: dice::hfe::ai::AIMain::getValidateDataStructuresEnabled() const (call at 0x41DCCF; ledger done) +// argc 1: dice::hfe::ai::AIMain::setValidateDataStructuresEnabled(bool) (call at 0x41DCB0; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass211 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("validateDataStructuresEnabled", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveAIMain()->getValidateDataStructuresEnabled(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveAIMain()->setValidateDataStructuresEnabled(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject211; + +// ConsoleClass212 AI.showBotUrgencies: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x41DF90, executeObjectMethod 0x41E300, +// setArgFromString 0x41E0C0, getReturnValueAsString 0x41DD50, D1 0x41DD30, D0 0x41DCF0. +// argc 0: dice::hfe::ai::AIMain::getShowBotUrgencies() const (call at 0x41E36F; ledger done) +// argc 1: dice::hfe::ai::AIMain::setShowBotUrgencies(bool) (call at 0x41E350; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass212 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("showBotUrgencies", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveAIMain()->getShowBotUrgencies(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveAIMain()->setShowBotUrgencies(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject212; + +// ConsoleClass213 AI.showBotSpawnCoord: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x41E630, executeObjectMethod 0x41E9A0, +// setArgFromString 0x41E760, getReturnValueAsString 0x41E3F0, D1 0x41E3D0, D0 0x41E390. +// argc 0: dice::hfe::ai::AIMain::getShowBotSpawnCoord() const (call at 0x41EA0F; ledger done) +// argc 1: dice::hfe::ai::AIMain::setShowBotSpawnCoord(bool) (call at 0x41E9F0; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass213 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("showBotSpawnCoord", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveAIMain()->getShowBotSpawnCoord(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveAIMain()->setShowBotSpawnCoord(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject213; + +// ConsoleClass214 AI.showStrategies: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x41ECD0, executeObjectMethod 0x41F040, +// setArgFromString 0x41EE00, getReturnValueAsString 0x41EA90, D1 0x41EA70, D0 0x41EA30. +// argc 0: dice::hfe::ai::AIMain::getShowStrategies() const (call at 0x41F0AF; ledger done) +// argc 1: dice::hfe::ai::AIMain::setShowStrategies(bool) (call at 0x41F090; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass214 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("showStrategies", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveAIMain()->getShowStrategies(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveAIMain()->setShowStrategies(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject214; + +// ConsoleClass215 AI.showSAIStats: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x41F370, executeObjectMethod 0x41F6E0, +// setArgFromString 0x41F4A0, getReturnValueAsString 0x41F130, D1 0x41F110, D0 0x41F0D0. +// argc 0: dice::hfe::ai::AIMain::getShowSAIStats() const (call at 0x41F74F; ledger done) +// argc 1: dice::hfe::ai::AIMain::setShowSAIStats(bool) (call at 0x41F730; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass215 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("showSAIStats", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveAIMain()->getShowSAIStats(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveAIMain()->setShowSAIStats(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject215; + +// ConsoleClass216 AI.showBotStats: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x41FA10, executeObjectMethod 0x41FD80, +// setArgFromString 0x41FB40, getReturnValueAsString 0x41F7D0, D1 0x41F7B0, D0 0x41F770. +// argc 0: dice::hfe::ai::AIMain::getShowBotStats() const (call at 0x41FDEF; ledger done) +// argc 1: dice::hfe::ai::AIMain::setShowBotStats(bool) (call at 0x41FDD0; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass216 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("showBotStats", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveAIMain()->getShowBotStats(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveAIMain()->setShowBotStats(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject216; + +// ConsoleClass217 AI.showBotSense: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x4200B0, executeObjectMethod 0x420410, +// setArgFromString 0x4201D0, getReturnValueAsString 0x41FE70, D1 0x41FE50, D0 0x41FE10. +// argc 0: dice::hfe::ai::BotManager::getRenderBotSensing() const (slot +0x78 at 0x420484; ledger done) +// argc 1: dice::hfe::ai::BotManager::setRenderBotSensing(bool) (slot +0x74 at 0x420465; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass217 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("showBotSense", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return IBotManager::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManager::instance->getRenderBotSensing(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + IBotManager::instance->setRenderBotSensing(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject217; + +// ConsoleClass218 AI.showStrategicAreas: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x420740, executeObjectMethod 0x420AB0, +// setArgFromString 0x420870, getReturnValueAsString 0x420500, D1 0x4204E0, D0 0x4204A0. +// argc 0: dice::hfe::ai::AIMain::getShowStrategicAreas() const (call at 0x420B1F; ledger done) +// argc 1: dice::hfe::ai::AIMain::setShowStrategicAreas(bool) (call at 0x420B00; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass218 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("showStrategicAreas", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveAIMain()->getShowStrategicAreas(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveAIMain()->setShowStrategicAreas(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject218; + +// ConsoleClass219 AI.showAll: method, 1..1 arguments, no result. +// ELF isObjectActive 0x420BE0, executeObjectMethod 0x420F50, +// setArgFromString 0x420D10, getReturnValueAsString 0x420BA0, D1 0x420B80, D0 0x420B40. +// argc 1: dice::hfe::ai::AIMain::showAll(bool) (call at 0x420F96; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass219 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("showAll", 0, 1, 1, "void", false) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveAIMain()->showAll(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject219; + +// ConsoleClass220 AI.showStrategic: method, 1..1 arguments, no result. +// ELF isObjectActive 0x421040, executeObjectMethod 0x4213B0, +// setArgFromString 0x421170, getReturnValueAsString 0x421000, D1 0x420FE0, D0 0x420FA0. +// argc 1: dice::hfe::ai::AIMain::showStrategic(bool) (call at 0x4213F6; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass220 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("showStrategic", 0, 1, 1, "void", false) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveAIMain()->showStrategic(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject220; + +// ConsoleClass221 AI.showBot: method, 1..1 arguments, no result. +// ELF isObjectActive 0x4214A0, executeObjectMethod 0x421810, +// setArgFromString 0x4215D0, getReturnValueAsString 0x421460, D1 0x421440, D0 0x421400. +// argc 1: dice::hfe::ai::AIMain::showBot(bool) (call at 0x421856; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass221 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("showBot", 0, 1, 1, "void", false) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveAIMain()->showBot(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject221; + +// ConsoleClass223 AI.getRendCameraPosition: method, 0..0 arguments, returns hfe::Vec3. +// ELF isObjectActive 0x421B60, executeObjectMethod 0x421C90, +// setArgFromString 0x421C80, getReturnValueAsString 0x4218C0, D1 0x4218A0, D0 0x421860. +// argc 0: dice::hfe::ai::AIConsole::getRendCameraPosition() (call at 0x421CD3; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass223 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getRendCameraPosition", 0, 0, 0, "hfe::Vec3", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIConsole::m_instance->getRendCameraPosition(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + hfe::Vec3 m_returnValue; +}; +BF2_CC_NAME consoleObject223; + +// ConsoleClass224 AI.getRendCameraRotation: method, 0..0 arguments, returns hfe::Vec3. +// ELF isObjectActive 0x422010, executeObjectMethod 0x422140, +// setArgFromString 0x422130, getReturnValueAsString 0x421D70, D1 0x421D50, D0 0x421D10. +// argc 0: dice::hfe::ai::AIConsole::getRendCameraRotation() (call at 0x422183; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass224 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getRendCameraRotation", 0, 0, 0, "hfe::Vec3", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIConsole::m_instance->getRendCameraRotation(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + hfe::Vec3 m_returnValue; +}; +BF2_CC_NAME consoleObject224; + +// ConsoleClass228 AI.getCurrentPitchAngle: method, 0..0 arguments, returns float. +// ELF isObjectActive 0x422460, executeObjectMethod 0x422590, +// setArgFromString 0x422580, getReturnValueAsString 0x422220, D1 0x422200, D0 0x4221C0. +// argc 0: dice::hfe::ai::AIConsole::getCurrentPitchAngle() const (call at 0x4225C3; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass228 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getCurrentPitchAngle", 0, 0, 0, "float", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIConsole::m_instance->getCurrentPitchAngle(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject228; + +// ConsoleClass229 AI.getCurrentYawAngle: method, 0..0 arguments, returns float. +// ELF isObjectActive 0x422890, executeObjectMethod 0x4229C0, +// setArgFromString 0x4229B0, getReturnValueAsString 0x422650, D1 0x422630, D0 0x4225F0. +// argc 0: dice::hfe::ai::AIConsole::getCurrentYawAngle() const (call at 0x4229F3; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass229 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getCurrentYawAngle", 0, 0, 0, "float", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIConsole::m_instance->getCurrentYawAngle(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject229; + +// ConsoleClass248 AI.addPlacement: method, 6..6 arguments, returns bool. +// ELF isObjectActive 0x422CC0, executeObjectMethod 0x423D10, +// setArgFromString 0x422DE0, getReturnValueAsString 0x422A80, D1 0x422A60, D0 0x422A20. +// argc 6: dice::hfe::ai::BotPlacementManager::addPlacement(std::string const&, dice::hfe::Vec3 const&, dice::hfe::Vec3 const&, std::string const&, int, std::string const&) (call at 0x423DFC; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass248 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addPlacement", 0, 6, 6, "bool", true) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "hfe::Vec3"; + m_argTypes[2] = "hfe::Vec3"; + m_argTypes[3] = "std::string"; + m_argTypes[4] = "int"; + m_argTypes[5] = "std::string"; + AIMODULE_CC_TAIL(6) + virtual bool isObjectActive() const { return BotPlacementManager::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 6) + { + m_hasReturnValue = true; + m_returnValue = BotPlacementManager::m_instance->addPlacement(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(hfe::Vec3, 1), BF2_CC_ARG(hfe::Vec3, 2), BF2_CC_ARG(std::string, 3), BF2_CC_ARG(int, 4), BF2_CC_ARG(std::string, 5)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(hfe::Vec3, 2) + AIMODULE_CC_EXTRACT(hfe::Vec3, 3) + AIMODULE_CC_EXTRACT(std::string, 4) + AIMODULE_CC_EXTRACT(int, 5) + AIMODULE_CC_EXTRACT(std::string, 6) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject248; + +// ConsoleClass249 AI.spawnBot: method, 1..1 arguments, returns bool. +// ELF isObjectActive 0x424140, executeObjectMethod 0x4244A0, +// setArgFromString 0x424260, getReturnValueAsString 0x423F00, D1 0x423EE0, D0 0x423EA0. +// argc 1: dice::hfe::ai::BotPlacementManager::spawnBot(int) (call at 0x4244DB; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass249 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("spawnBot", 0, 1, 1, "bool", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return BotPlacementManager::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = BotPlacementManager::m_instance->spawnBot(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject249; + +// ConsoleClass252 AI.pause: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x4247A0, executeObjectMethod 0x424B00, +// setArgFromString 0x4248C0, getReturnValueAsString 0x424560, D1 0x424540, D0 0x424500. +// argc 0: dice::hfe::ai::BFTimer::getPause() (slot +0x1C at 0x424B74; bf2 ELF 0x841C080) +// argc 1: dice::hfe::ai::BFTimer::setPause(bool) (slot +0x18 at 0x424B55; bf2 ELF 0x841C060) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass252 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("pause", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iBFTimer) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = static_cast(CommonSingletonServer::m_iBFTimer)->getPause(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iBFTimer)->setPause(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject252; + +SetConsoleClassDefaults aiSettingsfullAccessSetConsoleClassDefaults("aiSettings", 2, 0); + +// ConsoleClass259 aiSettings.setMaxNBots: method, 1..1 arguments, no result. +// ELF isObjectActive 0x424C30, executeObjectMethod 0x424F90, +// setArgFromString 0x424D50, getReturnValueAsString 0x424BF0, D1 0x424BD0, D0 0x424B90. +// argc 1: dice::hfe::ai::AISettings::setMaxNBots(int) (slot +0x0 at 0x424FD3; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass259 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setMaxNBots", 0, 1, 1, "void", false) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->setMaxNBots(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject259; + +// ConsoleClass260 aiSettings.maxBotsIncludeHumans: method, 1..1 arguments, no result. +// ELF isObjectActive 0x425080, executeObjectMethod 0x4253E0, +// setArgFromString 0x4251A0, getReturnValueAsString 0x425040, D1 0x425020, D0 0x424FE0. +// argc 1: dice::hfe::ai::AISettings::maxBotsIncludeHumans(bool) (slot +0x4 at 0x42542B; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass260 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("maxBotsIncludeHumans", 0, 1, 1, "void", false) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->maxBotsIncludeHumans(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject260; + +// ConsoleClass261 aiSettings.setIgnoreCommanderDistance: method, 1..1 arguments, no result. +// ELF isObjectActive 0x4254D0, executeObjectMethod 0x425830, +// setArgFromString 0x4255F0, getReturnValueAsString 0x425490, D1 0x425470, D0 0x425430. +// argc 1: dice::hfe::ai::AISettings::setIgnoreCommanderDistance(float) (slot +0x8 at 0x425873; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass261 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setIgnoreCommanderDistance", 0, 1, 1, "void", false) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->setIgnoreCommanderDistance(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject261; + +// ConsoleClass262 aiSettings.setMaxNumberOfBehaviours: method, 1..1 arguments, no result. +// ELF isObjectActive 0x425920, executeObjectMethod 0x425C80, +// setArgFromString 0x425A40, getReturnValueAsString 0x4258E0, D1 0x4258C0, D0 0x425880. +// argc 1: dice::hfe::ai::AISettings::setMaxNumberOfBehaviours(int) (slot +0xC at 0x425CC3; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass262 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setMaxNumberOfBehaviours", 0, 1, 1, "void", false) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->setMaxNumberOfBehaviours(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject262; + +// ConsoleClass263 aiSettings.setViewDistance: method, 1..1 arguments, no result. +// ELF isObjectActive 0x425D70, executeObjectMethod 0x4260D0, +// setArgFromString 0x425E90, getReturnValueAsString 0x425D30, D1 0x425D10, D0 0x425CD0. +// argc 1: dice::hfe::ai::AISettings::setViewDistance(float) (slot +0x34 at 0x426113; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass263 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setViewDistance", 0, 1, 1, "void", false) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->setViewDistance(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject263; + +// ConsoleClass264 aiSettings.setStatsViewDistance: method, 1..1 arguments, no result. +// ELF isObjectActive 0x4261C0, executeObjectMethod 0x426520, +// setArgFromString 0x4262E0, getReturnValueAsString 0x426180, D1 0x426160, D0 0x426120. +// argc 1: dice::hfe::ai::AISettings::setStatsViewDistance(float) (slot +0x38 at 0x426563; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass264 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setStatsViewDistance", 0, 1, 1, "void", false) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->setStatsViewDistance(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject264; + +// ConsoleClass265 aiSettings.setDrawBotStats: method, 1..1 arguments, no result. +// ELF isObjectActive 0x426610, executeObjectMethod 0x426970, +// setArgFromString 0x426730, getReturnValueAsString 0x4265D0, D1 0x4265B0, D0 0x426570. +// argc 1: dice::hfe::ai::AISettings::setDrawBotStats(bool) (slot +0x3C at 0x4269BB; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass265 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setDrawBotStats", 0, 1, 1, "void", false) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->setDrawBotStats(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject265; + +// ConsoleClass266 aiSettings.setInformationGridDimension: method, 1..1 arguments, no result. +// ELF isObjectActive 0x426A60, executeObjectMethod 0x426DC0, +// setArgFromString 0x426B80, getReturnValueAsString 0x426A20, D1 0x426A00, D0 0x4269C0. +// argc 1: dice::hfe::ai::AISettings::setInformationGridDimension(int) (slot +0x40 at 0x426E03; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass266 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setInformationGridDimension", 0, 1, 1, "void", false) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->setInformationGridDimension(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject266; + +// ConsoleClass267 aiSettings.setVehicle: method, 1..1 arguments, no result. +// ELF isObjectActive 0x426EB0, executeObjectMethod 0x427250, +// setArgFromString 0x426FD0, getReturnValueAsString 0x426E70, D1 0x426E50, D0 0x426E10. +// argc 1: dice::hfe::ai::AISettings::setVehicle(std::string const&) (slot +0x5C at 0x4272AF; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass267 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setVehicle", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->setVehicle(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject267; + +// ConsoleClass268 aiSettings.setVehicleClusterMapping: method, 2..2 arguments, no result. +// ELF isObjectActive 0x427380, executeObjectMethod 0x427990, +// setArgFromString 0x4274A0, getReturnValueAsString 0x427340, D1 0x427320, D0 0x4272E0. +// argc 2: dice::hfe::ai::AISettings::setVehicleClusterMapping(std::string const&, std::string const&) (slot +0x60 at 0x427A10; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass268 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setVehicleClusterMapping", 0, 2, 2, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "std::string"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->setVehicleClusterMapping(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(std::string, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject268; + +// ConsoleClass269 aiSettings.setVehicleMaterialCost: method, 3..3 arguments, no result. +// ELF isObjectActive 0x427B00, executeObjectMethod 0x4282E0, +// setArgFromString 0x427C20, getReturnValueAsString 0x427AC0, D1 0x427AA0, D0 0x427A60. +// argc 3: dice::hfe::ai::AISettings::setVehicleMaterialCost(std::string const&, unsigned char, float) (slot +0x8C at 0x428356; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass269 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setVehicleMaterialCost", 0, 3, 3, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "materialId"; + m_argTypes[2] = "float"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->setVehicleMaterialCost(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(materialId, 1), BF2_CC_ARG(float, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT_WITH(materialId, 2, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT(float, 3) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject269; + +// ConsoleClass270 aiSettings.setManDownEquipment: method, 1..1 arguments, no result. +// ELF isObjectActive 0x428430, executeObjectMethod 0x4287D0, +// setArgFromString 0x428550, getReturnValueAsString 0x4283F0, D1 0x4283D0, D0 0x428390. +// argc 1: dice::hfe::ai::AISettings::setManDownEquipment(std::string const&) (slot +0x88 at 0x42882F; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass270 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setManDownEquipment", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->setManDownEquipment(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject270; + +// ConsoleClass271 aiSettings.getInformationGridDimension: method, 0..0 arguments, returns int. +// ELF isObjectActive 0x428B30, executeObjectMethod 0x428C60, +// setArgFromString 0x428C50, getReturnValueAsString 0x4288C0, D1 0x4288A0, D0 0x428860. +// argc 0: dice::hfe::ai::AISettings::getInformationGridDimension() const (slot +0x3C at 0x428C95; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass271 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getInformationGridDimension", 0, 0, 0, "int", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettings) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = static_cast(CommonSingletonServer::m_iaiSettings)->getInformationGridDimension(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject271; + +// ConsoleClass272 aiSettings.getViewDistance: method, 0..0 arguments, returns float. +// ELF isObjectActive 0x428F60, executeObjectMethod 0x429090, +// setArgFromString 0x429080, getReturnValueAsString 0x428D20, D1 0x428D00, D0 0x428CC0. +// argc 0: dice::hfe::ai::AISettings::getViewDistance() const (slot +0x28 at 0x4290C5; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass272 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getViewDistance", 0, 0, 0, "float", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettings) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = static_cast(CommonSingletonServer::m_iaiSettings)->getViewDistance(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject272; + +// ConsoleClass273 aiSettings.getStatsViewDistance: method, 0..0 arguments, returns float. +// ELF isObjectActive 0x429390, executeObjectMethod 0x4294C0, +// setArgFromString 0x4294B0, getReturnValueAsString 0x429150, D1 0x429130, D0 0x4290F0. +// argc 0: dice::hfe::ai::AISettings::getStatsViewDistance() const (slot +0x2C at 0x4294F5; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass273 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getStatsViewDistance", 0, 0, 0, "float", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettings) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = static_cast(CommonSingletonServer::m_iaiSettings)->getStatsViewDistance(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject273; + +// ConsoleClass274 aiSettings.getVehicle: method, 1..1 arguments, returns std::string. +// ELF isObjectActive 0x429840, executeObjectMethod 0x429BA0, +// setArgFromString 0x429960, getReturnValueAsString 0x429600, D1 0x429590, D0 0x429520. +// argc 1: dice::hfe::ai::AISettings::getVehicle(int) const (slot +0x50 at 0x429BE3; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass274 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getVehicle", 0, 1, 1, "std::string", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettings) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = static_cast(CommonSingletonServer::m_iaiSettings)->getVehicle(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject274; + +// ConsoleClass275 aiSettings.getVehicleClusterMapping: method, 1..1 arguments, returns std::string. +// ELF isObjectActive 0x429F30, executeObjectMethod 0x42A2D0, +// setArgFromString 0x42A050, getReturnValueAsString 0x429CF0, D1 0x429C80, D0 0x429C10. +// argc 1: dice::hfe::ai::AISettings::getVehicleClusterMapping(std::string const&) const (slot +0x58 at 0x42A326; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass275 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getVehicleClusterMapping", 0, 1, 1, "std::string", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettings) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = static_cast(CommonSingletonServer::m_iaiSettings)->getVehicleClusterMapping(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject275; + +// ConsoleClass276 aiSettings.setNSides: method, 1..1 arguments, no result. +// ELF isObjectActive 0x42A410, executeObjectMethod 0x42A770, +// setArgFromString 0x42A530, getReturnValueAsString 0x42A3D0, D1 0x42A3B0, D0 0x42A370. +// argc 1: dice::hfe::ai::AISettings::setNSides(int) (slot +0x44 at 0x42A7B3; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass276 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setNSides", 0, 1, 1, "void", false) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->setNSides(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject276; + +// ConsoleClass277 aiSettings.getNSides: method, 0..0 arguments, returns int. +// ELF isObjectActive 0x42AA90, executeObjectMethod 0x42ABC0, +// setArgFromString 0x42ABB0, getReturnValueAsString 0x42A820, D1 0x42A800, D0 0x42A7C0. +// argc 0: dice::hfe::ai::AISettings::getNSides() const (slot +0x40 at 0x42ABF5; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass277 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getNSides", 0, 0, 0, "int", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettings) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = static_cast(CommonSingletonServer::m_iaiSettings)->getNSides(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject277; + +// ConsoleClass278 aiSettings.setBotSkill: method, 1..1 arguments, no result. +// ELF isObjectActive 0x42ACC0, executeObjectMethod 0x42B020, +// setArgFromString 0x42ADE0, getReturnValueAsString 0x42AC80, D1 0x42AC60, D0 0x42AC20. +// argc 1: dice::hfe::ai::AISettings::setBotSkill(float) (slot +0x48 at 0x42B063; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass278 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setBotSkill", 0, 1, 1, "void", false) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->setBotSkill(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject278; + +// ConsoleClass279 aiSettings.getBotSkill: method, 0..0 arguments, returns float. +// ELF isObjectActive 0x42B310, executeObjectMethod 0x42B440, +// setArgFromString 0x42B430, getReturnValueAsString 0x42B0D0, D1 0x42B0B0, D0 0x42B070. +// argc 0: dice::hfe::ai::AISettings::getBotSkill() const (slot +0x44 at 0x42B475; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass279 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getBotSkill", 0, 0, 0, "float", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettings) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = static_cast(CommonSingletonServer::m_iaiSettings)->getBotSkill(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject279; + +// ConsoleClass280 aiSettings.getNumberOfVehicleGroups: method, 0..0 arguments, returns int. +// ELF isObjectActive 0x42B770, executeObjectMethod 0x42B8A0, +// setArgFromString 0x42B890, getReturnValueAsString 0x42B500, D1 0x42B4E0, D0 0x42B4A0. +// argc 0: dice::hfe::ai::AISettings::getNumberOfVehicleGroups() const (slot +0x64 at 0x42B8D5; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass280 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getNumberOfVehicleGroups", 0, 0, 0, "int", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettings) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = static_cast(CommonSingletonServer::m_iaiSettings)->getNumberOfVehicleGroups(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject280; + +// ConsoleClass281 aiSettings.getVehicleGroup: method, 1..1 arguments, returns int. +// ELF isObjectActive 0x42BBD0, executeObjectMethod 0x42BF30, +// setArgFromString 0x42BCF0, getReturnValueAsString 0x42B960, D1 0x42B940, D0 0x42B900. +// argc 1: dice::hfe::ai::AISettings::getVehicleGroup(int) const (slot +0x68 at 0x42BF6D; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass281 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getVehicleGroup", 0, 1, 1, "int", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettings) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = static_cast(CommonSingletonServer::m_iaiSettings)->getVehicleGroup(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject281; + +// ConsoleClass282 aiSettings.getVehicleGroupName: method, 1..1 arguments, returns std::string. +// ELF isObjectActive 0x42C2B0, executeObjectMethod 0x42C610, +// setArgFromString 0x42C3D0, getReturnValueAsString 0x42C070, D1 0x42C000, D0 0x42BF90. +// argc 1: dice::hfe::ai::AISettings::getVehicleGroupName(int) const (slot +0x70 at 0x42C653; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass282 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getVehicleGroupName", 0, 1, 1, "std::string", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettings) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = static_cast(CommonSingletonServer::m_iaiSettings)->getVehicleGroupName(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject282; + +// ConsoleClass283 aiSettings.createVehicleGroup: method, 1..1 arguments, no result. +// ELF isObjectActive 0x42C720, executeObjectMethod 0x42CAC0, +// setArgFromString 0x42C840, getReturnValueAsString 0x42C6E0, D1 0x42C6C0, D0 0x42C680. +// argc 1: dice::hfe::ai::AISettings::createVehicleGroup(std::string const&) (slot +0x64 at 0x42CB1F; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass283 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createVehicleGroup", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->createVehicleGroup(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject283; + +// ConsoleClass284 aiSettings.addVehicleToVehicleGroup: method, 2..2 arguments, no result. +// ELF isObjectActive 0x42CBF0, executeObjectMethod 0x42D200, +// setArgFromString 0x42CD10, getReturnValueAsString 0x42CBB0, D1 0x42CB90, D0 0x42CB50. +// argc 2: dice::hfe::ai::AISettings::addVehicleToVehicleGroup(std::string const&, std::string const&) (slot +0x6C at 0x42D280; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass284 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addVehicleToVehicleGroup", 0, 2, 2, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "std::string"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->addVehicleToVehicleGroup(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(std::string, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject284; + +// ConsoleClass285 aiSettings.getSAIUpdateFrequency: method, 0..0 arguments, returns float. +// ELF isObjectActive 0x42D570, executeObjectMethod 0x42D6A0, +// setArgFromString 0x42D690, getReturnValueAsString 0x42D330, D1 0x42D310, D0 0x42D2D0. +// argc 0: dice::hfe::ai::AISettings::getSAIUpdateFrequency() const (slot +0x48 at 0x42D6D5; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass285 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getSAIUpdateFrequency", 0, 0, 0, "float", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettings) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = static_cast(CommonSingletonServer::m_iaiSettings)->getSAIUpdateFrequency(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject285; + +// ConsoleClass286 aiSettings.setSAIUpdateFrequency: method, 1..1 arguments, no result. +// ELF isObjectActive 0x42D7A0, executeObjectMethod 0x42DB00, +// setArgFromString 0x42D8C0, getReturnValueAsString 0x42D760, D1 0x42D740, D0 0x42D700. +// argc 1: dice::hfe::ai::AISettings::setSAIUpdateFrequency(float) (slot +0x4C at 0x42DB43; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass286 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setSAIUpdateFrequency", 0, 1, 1, "void", false) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->setSAIUpdateFrequency(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject286; + +// ConsoleClass287 aiSettings.setRespawnAllowed: method, 1..1 arguments, no result. +// ELF isObjectActive 0x42DBF0, executeObjectMethod 0x42DF50, +// setArgFromString 0x42DD10, getReturnValueAsString 0x42DBB0, D1 0x42DB90, D0 0x42DB50. +// argc 1: dice::hfe::ai::AISettings::setRespawnAllowed(bool) (slot +0x58 at 0x42DF9B; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass287 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setRespawnAllowed", 0, 1, 1, "void", false) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->setRespawnAllowed(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject287; + +// ConsoleClass288 aiSettings.addBotName: method, 2..2 arguments, no result. +// ELF isObjectActive 0x42E040, executeObjectMethod 0x42E650, +// setArgFromString 0x42E160, getReturnValueAsString 0x42E000, D1 0x42DFE0, D0 0x42DFA0. +// argc 2: dice::hfe::ai::AISettings::addBotName(std::string const&, std::string const&) (slot +0x90 at 0x42E6D0; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass288 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addBotName", 0, 2, 2, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "std::string"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->addBotName(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(std::string, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject288; + +// ConsoleClass289 aiSettings.isRespawnAllowed: method, 0..0 arguments, returns bool. +// ELF isObjectActive 0x42E9C0, executeObjectMethod 0x42EAF0, +// setArgFromString 0x42EAE0, getReturnValueAsString 0x42E780, D1 0x42E760, D0 0x42E720. +// argc 0: dice::hfe::ai::AISettings::isRespawnAllowed() const (slot +0x4C at 0x42EB25; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass289 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("isRespawnAllowed", 0, 0, 0, "bool", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettings) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = static_cast(CommonSingletonServer::m_iaiSettings)->isRespawnAllowed(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject289; + +// ConsoleClass290 aiSettings.overrideMenuSettings: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x42EDF0, executeObjectMethod 0x42F160, +// setArgFromString 0x42EF20, getReturnValueAsString 0x42EBB0, D1 0x42EB90, D0 0x42EB50. +// argc 0: dice::hfe::ai::AISettings::getOverrideMenuSettings() const (slot +0xBC at 0x42F1D1; ledger done) +// argc 1: dice::hfe::ai::AISettings::setOverrideMenuSettings(bool) (slot +0x15C at 0x42F1B2; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass290 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("overrideMenuSettings", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getAISettings() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getAISettings()->getOverrideMenuSettings(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(getAISettings())->setOverrideMenuSettings(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject290; + +// ConsoleClass293 aiSettings.lodEnable: method, 0..1 arguments, returns bool. +// ELF isObjectActive 0x42F490, executeObjectMethod 0x42F7F0, +// setArgFromString 0x42F5B0, getReturnValueAsString 0x42F250, D1 0x42F230, D0 0x42F1F0. +// argc 0: dice::hfe::ai::AILODManager::lodEnable() (call at 0x42F862; ledger done) +// argc 1: dice::hfe::ai::AILODManager::lodEnable(bool) (call at 0x42F835; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass293 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("lodEnable", 0, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AILODManager::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AILODManager::m_instance->lodEnable(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = AILODManager::m_instance->lodEnable(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject293; + +// ConsoleClass294 aiSettings.setBasicLODDistance: method, 1..1 arguments, no result. +// ELF isObjectActive 0x42F910, executeObjectMethod 0x42FC70, +// setArgFromString 0x42FA30, getReturnValueAsString 0x42F8D0, D1 0x42F8B0, D0 0x42F870. +// argc 1: dice::hfe::ai::AILODManager::setBasicLODDistance(float) (call at 0x42FCB1; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass294 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setBasicLODDistance", 0, 1, 1, "void", false) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AILODManager::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + AILODManager::m_instance->setBasicLODDistance(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject294; + +// ConsoleClass296 aiSettings.setVehicleMods: method, 2..2 arguments, no result. +// ELF isObjectActive 0x42FD60, executeObjectMethod 0x430370, +// setArgFromString 0x42FE80, getReturnValueAsString 0x42FD20, D1 0x42FD00, D0 0x42FCC0. +// argc 2: dice::hfe::ai::AIConsole::setVehicleMods(std::string const&, std::string const&) (call at 0x4303EE; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass296 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setVehicleMods", 0, 2, 2, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "std::string"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + AIConsole::m_instance->setVehicleMods(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(std::string, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject296; + +// ConsoleClass297 aiSettings.setStandardPersonality: method, 2..2 arguments, no result. +// ELF isObjectActive 0x4304E0, executeObjectMethod 0x430AB0, +// setArgFromString 0x430600, getReturnValueAsString 0x4304A0, D1 0x430480, D0 0x430440. +// argc 2: dice::hfe::ai::AIConsole::setStandardPersonality(std::string const&, int) (call at 0x430B16; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass297 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setStandardPersonality", 0, 2, 2, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "int"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + AIConsole::m_instance->setStandardPersonality(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(int, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(int, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject297; + +// ConsoleClass298 aiSettings.setVehicleBehaviour: method, 7..7 arguments, no result. +// ELF isObjectActive 0x430BE0, executeObjectMethod 0x431D90, +// setArgFromString 0x430D00, getReturnValueAsString 0x430BA0, D1 0x430B80, D0 0x430B40. +// argc 7: dice::hfe::ai::AIConsole::setVehicleBehaviour(std::string, std::string, std::string, std::string, int, std::string, std::string) (call at 0x431F5A; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass298 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setVehicleBehaviour", 0, 7, 7, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "std::string"; + m_argTypes[2] = "std::string"; + m_argTypes[3] = "std::string"; + m_argTypes[4] = "int"; + m_argTypes[5] = "std::string"; + m_argTypes[6] = "std::string"; + AIMODULE_CC_TAIL(7) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 7) + { + m_hasReturnValue = false; + AIConsole::m_instance->setVehicleBehaviour(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(std::string, 1), BF2_CC_ARG(std::string, 2), BF2_CC_ARG(std::string, 3), BF2_CC_ARG(int, 4), BF2_CC_ARG(std::string, 5), BF2_CC_ARG(std::string, 6)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + AIMODULE_CC_EXTRACT(std::string, 3) + AIMODULE_CC_EXTRACT(std::string, 4) + AIMODULE_CC_EXTRACT(int, 5) + AIMODULE_CC_EXTRACT(std::string, 6) + AIMODULE_CC_EXTRACT(std::string, 7) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject298; + +// ConsoleClass299 aiSettings.setVehicleDefaultBehaviour: method, 2..2 arguments, no result. +// ELF isObjectActive 0x4321D0, executeObjectMethod 0x4327E0, +// setArgFromString 0x4322F0, getReturnValueAsString 0x432190, D1 0x432170, D0 0x432130. +// argc 2: dice::hfe::ai::AIConsole::setVehicleDefaultBehaviour(std::string&, std::string&) (call at 0x43285E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass299 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setVehicleDefaultBehaviour", 0, 2, 2, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "std::string"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + AIConsole::m_instance->setVehicleDefaultBehaviour(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(std::string, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject299; + +// ConsoleClass300 aiSettings.addInterpreterEntry: method, 2..3 arguments, no result. +// ELF isObjectActive 0x432950, executeObjectMethod 0x433180, +// setArgFromString 0x432A70, getReturnValueAsString 0x432910, D1 0x4328F0, D0 0x4328B0. +// argc 2: dice::hfe::ai::AIConsole::addInterpreterEntry(std::string, std::string) (call at 0x43333D; ledger done) +// argc 3: dice::hfe::ai::AIConsole::addInterpreterEntry(std::string, std::string, dice::hfe::ai::BotLodLevel) (call at 0x43323F; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass300 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addInterpreterEntry", 0, 2, 3, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "std::string"; + m_argTypes[2] = "BotLodLevel"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + AIConsole::m_instance->addInterpreterEntry(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(std::string, 1)); + } + else if (m_argCount == 3) + { + m_hasReturnValue = false; + AIConsole::m_instance->addInterpreterEntry(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(std::string, 1), BF2_CC_ARG(BotLodLevel, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + AIMODULE_CC_EXTRACT_WITH(BotLodLevel, 3, dice::hfe::ai::operator>>) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject300; + +// ConsoleClass301 aiSettings.removeInterpreterEntry: method, 3..3 arguments, no result. +// ELF isObjectActive 0x433460, executeObjectMethod 0x433C90, +// setArgFromString 0x433580, getReturnValueAsString 0x433420, D1 0x433400, D0 0x4333C0. +// argc 3: dice::hfe::ai::AIConsole::removeInterpreterEntry(std::string, std::string, dice::hfe::ai::BotLodLevel) (call at 0x433D3E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass301 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("removeInterpreterEntry", 0, 3, 3, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "std::string"; + m_argTypes[2] = "BotLodLevel"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = false; + AIConsole::m_instance->removeInterpreterEntry(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(std::string, 1), BF2_CC_ARG(BotLodLevel, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + AIMODULE_CC_EXTRACT_WITH(BotLodLevel, 3, dice::hfe::ai::operator>>) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject301; + +// ConsoleClass302 aiSettings.activateDefaultInterpreter: method, 3..3 arguments, no result. +// ELF isObjectActive 0x433E70, executeObjectMethod 0x434650, +// setArgFromString 0x433F90, getReturnValueAsString 0x433E30, D1 0x433E10, D0 0x433DD0. +// argc 3: dice::hfe::ai::AIConsole::activateDefaultInterpreter(std::string, dice::hfe::ai::BAPStatementType, dice::hfe::ai::BotLodLevel) (call at 0x4346DF; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass302 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("activateDefaultInterpreter", 0, 3, 3, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "BAPStatementType"; + m_argTypes[2] = "BotLodLevel"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = false; + AIConsole::m_instance->activateDefaultInterpreter(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(BAPStatementType, 1), BF2_CC_ARG(BotLodLevel, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT_WITH(BAPStatementType, 2, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT_WITH(BotLodLevel, 3, dice::hfe::ai::operator>>) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject302; + +// ConsoleClass303 aiSettings.setBasicBotWeights: method, 1..1 arguments, no result. +// ELF isObjectActive 0x4347D0, executeObjectMethod 0x434B70, +// setArgFromString 0x4348F0, getReturnValueAsString 0x434790, D1 0x434770, D0 0x434730. +// argc 1: dice::hfe::ai::AIConsole::setBasicBotWeights(std::string) (call at 0x434BE1; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass303 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setBasicBotWeights", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + AIConsole::m_instance->setBasicBotWeights(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject303; + +// ConsoleClass304 aiSettings.setBehaviour: method, 2..2 arguments, no result. +// ELF isObjectActive 0x434CD0, executeObjectMethod 0x4352C0, +// setArgFromString 0x434DF0, getReturnValueAsString 0x434C90, D1 0x434C70, D0 0x434C30. +// argc 2: dice::hfe::ai::AIConsole::setBehaviour(int, std::string) (call at 0x435340; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass304 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setBehaviour", 0, 2, 2, "void", false) + m_argTypes[0] = "int"; + m_argTypes[1] = "std::string"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + AIConsole::m_instance->setBehaviour(BF2_CC_ARG(int, 0), BF2_CC_ARG(std::string, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject304; + +// ConsoleClass305 aiSettings.getBehaviour: method, 1..1 arguments, returns std::string. +// ELF isObjectActive 0x4356B0, executeObjectMethod 0x435A10, +// setArgFromString 0x4357D0, getReturnValueAsString 0x435470, D1 0x435400, D0 0x435390. +// argc 1: dice::hfe::ai::AIConsole::getBehaviour(int) (call at 0x435A5B; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass305 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getBehaviour", 0, 1, 1, "std::string", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = AIConsole::m_instance->getBehaviour(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject305; + +// ConsoleClass306 aiSettings.createBehaviourModifiers: method, 1..1 arguments, no result. +// ELF isObjectActive 0x435B50, executeObjectMethod 0x435EF0, +// setArgFromString 0x435C70, getReturnValueAsString 0x435B10, D1 0x435AF0, D0 0x435AB0. +// argc 1: dice::hfe::ai::AIConsole::createBehaviourModifiers(std::string) (call at 0x435F61; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass306 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createBehaviourModifiers", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + AIConsole::m_instance->createBehaviourModifiers(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject306; + +// ConsoleClass307 aiSettings.activeBehaviourModifiers: property, 0..1 arguments, returns std::string. +// ELF isObjectActive 0x4362D0, executeObjectMethod 0x436670, +// setArgFromString 0x4363F0, getReturnValueAsString 0x436090, D1 0x436020, D0 0x435FB0. +// argc 0: dice::hfe::ai::AIConsole::getActiveBehaviourModifiers() (call at 0x436755; ledger stop) +// argc 1: dice::hfe::ai::AIConsole::setActiveBehaviourModifiers(std::string) (call at 0x4366EF; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass307 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("activeBehaviourModifiers", 1, 0, 1, "std::string", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIConsole::m_instance->getActiveBehaviourModifiers(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + AIConsole::m_instance->setActiveBehaviourModifiers(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject307; + +// ConsoleClass308 aiSettings.setBehaviourModifier: method, 2..2 arguments, no result. +// ELF isObjectActive 0x436840, executeObjectMethod 0x436E10, +// setArgFromString 0x436960, getReturnValueAsString 0x436800, D1 0x4367E0, D0 0x4367A0. +// argc 2: dice::hfe::ai::AIConsole::setBehaviourModifier(std::string, float) (call at 0x436E90; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass308 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setBehaviourModifier", 0, 2, 2, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "float"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + AIConsole::m_instance->setBehaviourModifier(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(float, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(float, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject308; + +// ConsoleClass309 aiSettings.getBehaviourModifier: method, 1..1 arguments, returns float. +// ELF isObjectActive 0x437180, executeObjectMethod 0x437520, +// setArgFromString 0x4372A0, getReturnValueAsString 0x436F40, D1 0x436F20, D0 0x436EE0. +// argc 1: dice::hfe::ai::AIConsole::getBehaviourModifier(std::string) (call at 0x437583; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass309 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getBehaviourModifier", 0, 1, 1, "float", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = AIConsole::m_instance->getBehaviourModifier(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject309; + +// ConsoleClass310 aiSettings.listBehaviourModifiers: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x437920, executeObjectMethod 0x437A50, +// setArgFromString 0x437A40, getReturnValueAsString 0x4376E0, D1 0x437670, D0 0x437600. +// argc 0: dice::hfe::ai::AIConsole::listBehaviourModifiers() (call at 0x437A93; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass310 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("listBehaviourModifiers", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIConsole::m_instance->listBehaviourModifiers(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject310; + +// ConsoleClass311 aiSettings.showAISettings: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x437E10, executeObjectMethod 0x437F40, +// setArgFromString 0x437F30, getReturnValueAsString 0x437BD0, D1 0x437B60, D0 0x437AF0. +// argc 0: dice::hfe::ai::AIConsole::showAISettings() (call at 0x437F83; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass311 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("showAISettings", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIConsole::m_instance->showAISettings(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject311; + +// ConsoleClass312 aiSettings.createUCConstant: method, 2..2 arguments, no result. +// ELF isObjectActive 0x438080, executeObjectMethod 0x438650, +// setArgFromString 0x4381A0, getReturnValueAsString 0x438040, D1 0x438020, D0 0x437FE0. +// argc 2: dice::hfe::ai::BotBehaviourManager::createUCConstant(std::string&, float) (call at 0x4386C2; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass312 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createUCConstant", 0, 2, 2, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "float"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return BotBehaviourManager::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + BotBehaviourManager::m_instance->createUCConstant(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(float, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(float, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject312; + +// ConsoleClass313 aiSettings.createUCLinear: method, 3..3 arguments, no result. +// ELF isObjectActive 0x4387B0, executeObjectMethod 0x438F90, +// setArgFromString 0x4388D0, getReturnValueAsString 0x438770, D1 0x438750, D0 0x438710. +// argc 3: dice::hfe::ai::BotBehaviourManager::createUCLinear(std::string&, float, float) (call at 0x439011; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass313 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createUCLinear", 0, 3, 3, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "float"; + m_argTypes[2] = "float"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return BotBehaviourManager::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = false; + BotBehaviourManager::m_instance->createUCLinear(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(float, 1), BF2_CC_ARG(float, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(float, 2) + AIMODULE_CC_EXTRACT(float, 3) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject313; + +// ConsoleClass314 aiSettings.createUCXInverse: method, 5..5 arguments, no result. +// ELF isObjectActive 0x439100, executeObjectMethod 0x439D00, +// setArgFromString 0x439220, getReturnValueAsString 0x4390C0, D1 0x4390A0, D0 0x439060. +// argc 5: dice::hfe::ai::BotBehaviourManager::createUCXInverse(std::string&, float, float, float, float) (call at 0x439D93; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass314 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createUCXInverse", 0, 5, 5, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "float"; + m_argTypes[2] = "float"; + m_argTypes[3] = "float"; + m_argTypes[4] = "float"; + AIMODULE_CC_TAIL(5) + virtual bool isObjectActive() const { return BotBehaviourManager::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 5) + { + m_hasReturnValue = false; + BotBehaviourManager::m_instance->createUCXInverse(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(float, 1), BF2_CC_ARG(float, 2), BF2_CC_ARG(float, 3), BF2_CC_ARG(float, 4)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(float, 2) + AIMODULE_CC_EXTRACT(float, 3) + AIMODULE_CC_EXTRACT(float, 4) + AIMODULE_CC_EXTRACT(float, 5) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject314; + +// ConsoleClass315 aiSettings.createLODManager: method, 2..2 arguments, std::string result discarded. +// ELF isObjectActive 0x439E80, executeObjectMethod 0x43A420, +// setArgFromString 0x439FA0, getReturnValueAsString 0x439E40, D1 0x439E20, D0 0x439DE0. +// argc 2: dice::hfe::ai::AIConsole::createLODManager(float, float) (call at 0x43A47E; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass315 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createLODManager", 0, 2, 2, "std::string", false) + m_argTypes[0] = "float"; + m_argTypes[1] = "float"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + AIConsole::m_instance->createLODManager(BF2_CC_ARG(float, 0), BF2_CC_ARG(float, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + AIMODULE_CC_EXTRACT(float, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject315; + +// ConsoleClass316 aiSettings.setSensingAgentPatternName: method, 1..1 arguments, no result. +// ELF isObjectActive 0x43A550, executeObjectMethod 0x43A8F0, +// setArgFromString 0x43A670, getReturnValueAsString 0x43A510, D1 0x43A4F0, D0 0x43A4B0. +// argc 1: dice::hfe::ai::AIConsole::setSensingAgentPatternName(std::string const&) (call at 0x43A94D; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass316 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setSensingAgentPatternName", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + AIConsole::m_instance->setSensingAgentPatternName(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject316; + +// ConsoleClass317 aiSettings.setSensingAgentNullPattern: method, 1..1 arguments, no result. +// ELF isObjectActive 0x43AA20, executeObjectMethod 0x43ADC0, +// setArgFromString 0x43AB40, getReturnValueAsString 0x43A9E0, D1 0x43A9C0, D0 0x43A980. +// argc 1: dice::hfe::ai::AIConsole::setSensingAgentNullPattern(std::string const&) (call at 0x43AE1D; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass317 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setSensingAgentNullPattern", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + AIConsole::m_instance->setSensingAgentNullPattern(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject317; + +// ConsoleClass318 aiSettings.addSensingAgentPattern: method, 2..2 arguments, no result. +// ELF isObjectActive 0x43AEF0, executeObjectMethod 0x43B500, +// setArgFromString 0x43B010, getReturnValueAsString 0x43AEB0, D1 0x43AE90, D0 0x43AE50. +// argc 2: dice::hfe::ai::AIConsole::addSensingAgentPattern(std::string const&, std::string const&) (call at 0x43B57E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass318 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addSensingAgentPattern", 0, 2, 2, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "std::string"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + AIConsole::m_instance->addSensingAgentPattern(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(std::string, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject318; + +// ConsoleClass319 aiSettings.sensingAgentDebug: method, 0..0 arguments, no result. +// ELF isObjectActive 0x43B670, executeObjectMethod 0x43B7A0, +// setArgFromString 0x43B790, getReturnValueAsString 0x43B630, D1 0x43B610, D0 0x43B5D0. +// argc 0: dice::hfe::ai::AIConsole::sensingAgentDebug() (call at 0x43B7D9; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass319 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("sensingAgentDebug", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + AIConsole::m_instance->sensingAgentDebug(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject319; + +// ConsoleClass321 aiSettings.autoSpawnBots: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x43BA80, executeObjectMethod 0x43BDE0, +// setArgFromString 0x43BBA0, getReturnValueAsString 0x43B840, D1 0x43B820, D0 0x43B7E0. +// argc 0: dice::hfe::ai::AISettings::getAutoSpawnBots() const (slot +0x90 at 0x43BE54; ledger done) +// argc 1: dice::hfe::ai::AISettings::setAutoSpawnBots(bool) (slot +0x148 at 0x43BE35; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass321 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("autoSpawnBots", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettings) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = static_cast(CommonSingletonServer::m_iaiSettings)->getAutoSpawnBots(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(static_cast(CommonSingletonServer::m_iaiSettings))->setAutoSpawnBots(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject321; + +SetConsoleClassDefaults AIBotManagerfullAccessSetConsoleClassDefaults("AIBotManager", 2, 0); + +// ConsoleClass327 AIBotManager.setLodLevelTicks: method, 3..3 arguments, no result. +// ELF isObjectActive 0x43BF10, executeObjectMethod 0x43C6E0, +// setArgFromString 0x43C030, getReturnValueAsString 0x43BED0, D1 0x43BEB0, D0 0x43BE70. +// argc 3: dice::hfe::ai::BotManager::setLodLevelTicks(unsigned int, unsigned int, unsigned int) (slot +0x8 at 0x43C741; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass327 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setLodLevelTicks", 0, 3, 3, "void", false) + m_argTypes[0] = "hfe::uint"; + m_argTypes[1] = "hfe::uint"; + m_argTypes[2] = "hfe::uint"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = false; + IBotManagerModifier::instance->setLodLevelTicks(BF2_CC_ARG(hfe::uint, 0), BF2_CC_ARG(hfe::uint, 1), BF2_CC_ARG(hfe::uint, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(hfe::uint, 1) + AIMODULE_CC_EXTRACT(hfe::uint, 2) + AIMODULE_CC_EXTRACT(hfe::uint, 3) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject327; + +// ConsoleClass328 AIBotManager.setLodLevelPriority: method, 3..3 arguments, no result. +// ELF isObjectActive 0x43C7F0, executeObjectMethod 0x43CFC0, +// setArgFromString 0x43C910, getReturnValueAsString 0x43C7B0, D1 0x43C790, D0 0x43C750. +// argc 3: dice::hfe::ai::BotManager::setLodLevelPriority(unsigned int, unsigned int, unsigned int) (slot +0xC at 0x43D021; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass328 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setLodLevelPriority", 0, 3, 3, "void", false) + m_argTypes[0] = "hfe::uint"; + m_argTypes[1] = "hfe::uint"; + m_argTypes[2] = "hfe::uint"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = false; + IBotManagerModifier::instance->setLodLevelPriority(BF2_CC_ARG(hfe::uint, 0), BF2_CC_ARG(hfe::uint, 1), BF2_CC_ARG(hfe::uint, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(hfe::uint, 1) + AIMODULE_CC_EXTRACT(hfe::uint, 2) + AIMODULE_CC_EXTRACT(hfe::uint, 3) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject328; + +// ConsoleClass329 AIBotManager.setPlannedDecisionMakingThreshold: method, 3..3 arguments, no result. +// ELF isObjectActive 0x43D0D0, executeObjectMethod 0x43D8A0, +// setArgFromString 0x43D1F0, getReturnValueAsString 0x43D090, D1 0x43D070, D0 0x43D030. +// argc 3: dice::hfe::ai::BotManager::setPlannedDecisionMakingThreshold(double const&, double const&, double const&) (slot +0x10 at 0x43D907; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass329 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setPlannedDecisionMakingThreshold", 0, 3, 3, "void", false) + m_argTypes[0] = "double"; + m_argTypes[1] = "double"; + m_argTypes[2] = "double"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = false; + IBotManagerModifier::instance->setPlannedDecisionMakingThreshold(BF2_CC_ARG(double, 0), BF2_CC_ARG(double, 1), BF2_CC_ARG(double, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(double, 1) + AIMODULE_CC_EXTRACT(double, 2) + AIMODULE_CC_EXTRACT(double, 3) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject329; + +// ConsoleClass330 AIBotManager.setUnplannedDecisionMakingThreshold: method, 3..3 arguments, no result. +// ELF isObjectActive 0x43D9B0, executeObjectMethod 0x43E180, +// setArgFromString 0x43DAD0, getReturnValueAsString 0x43D970, D1 0x43D950, D0 0x43D910. +// argc 3: dice::hfe::ai::BotManager::setUnplannedDecisionMakingThreshold(double const&, double const&, double const&) (slot +0x14 at 0x43E1E7; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass330 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setUnplannedDecisionMakingThreshold", 0, 3, 3, "void", false) + m_argTypes[0] = "double"; + m_argTypes[1] = "double"; + m_argTypes[2] = "double"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = false; + IBotManagerModifier::instance->setUnplannedDecisionMakingThreshold(BF2_CC_ARG(double, 0), BF2_CC_ARG(double, 1), BF2_CC_ARG(double, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(double, 1) + AIMODULE_CC_EXTRACT(double, 2) + AIMODULE_CC_EXTRACT(double, 3) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject330; + +// ConsoleClass331 AIBotManager.setDecisionMakingInterleave: method, 2..2 arguments, no result. +// ELF isObjectActive 0x43E290, executeObjectMethod 0x43E830, +// setArgFromString 0x43E3B0, getReturnValueAsString 0x43E250, D1 0x43E230, D0 0x43E1F0. +// argc 2: dice::hfe::ai::BotManager::setDecisionMakingInterleave(unsigned int, unsigned int) (slot +0x18 at 0x43E886; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass331 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setDecisionMakingInterleave", 0, 2, 2, "void", false) + m_argTypes[0] = "hfe::uint"; + m_argTypes[1] = "hfe::uint"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + IBotManagerModifier::instance->setDecisionMakingInterleave(BF2_CC_ARG(hfe::uint, 0), BF2_CC_ARG(hfe::uint, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(hfe::uint, 1) + AIMODULE_CC_EXTRACT(hfe::uint, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject331; + +// ConsoleClass332 AIBotManager.setSensingQuotient: method, 2..2 arguments, no result. +// ELF isObjectActive 0x43E930, executeObjectMethod 0x43EED0, +// setArgFromString 0x43EA50, getReturnValueAsString 0x43E8F0, D1 0x43E8D0, D0 0x43E890. +// argc 2: dice::hfe::ai::BotManager::setSensingQuotient(unsigned int, unsigned int) (slot +0x1C at 0x43EF26; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass332 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setSensingQuotient", 0, 2, 2, "void", false) + m_argTypes[0] = "hfe::uint"; + m_argTypes[1] = "hfe::uint"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + IBotManagerModifier::instance->setSensingQuotient(BF2_CC_ARG(hfe::uint, 0), BF2_CC_ARG(hfe::uint, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(hfe::uint, 1) + AIMODULE_CC_EXTRACT(hfe::uint, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject332; + +// ConsoleClass333 AIBotManager.setSystemQuotient: method, 3..3 arguments, no result. +// ELF isObjectActive 0x43EFD0, executeObjectMethod 0x43F7A0, +// setArgFromString 0x43F0F0, getReturnValueAsString 0x43EF90, D1 0x43EF70, D0 0x43EF30. +// argc 3: dice::hfe::ai::BotManager::setSystemQuotient(unsigned int, unsigned int, unsigned int) (slot +0x20 at 0x43F801; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass333 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setSystemQuotient", 0, 3, 3, "void", false) + m_argTypes[0] = "hfe::uint"; + m_argTypes[1] = "hfe::uint"; + m_argTypes[2] = "hfe::uint"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = false; + IBotManagerModifier::instance->setSystemQuotient(BF2_CC_ARG(hfe::uint, 0), BF2_CC_ARG(hfe::uint, 1), BF2_CC_ARG(hfe::uint, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(hfe::uint, 1) + AIMODULE_CC_EXTRACT(hfe::uint, 2) + AIMODULE_CC_EXTRACT(hfe::uint, 3) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject333; + +// ConsoleClass334 AIBotManager.getLodLevelFullTicks: method, 0..0 arguments, returns hfe::uint. +// ELF isObjectActive 0x43FAB0, executeObjectMethod 0x43FBE0, +// setArgFromString 0x43FBD0, getReturnValueAsString 0x43F870, D1 0x43F850, D0 0x43F810. +// argc 0: dice::hfe::ai::BotManager::getLodLevelFullTicks() const (slot +0x24 at 0x43FC15; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass334 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getLodLevelFullTicks", 0, 0, 0, "hfe::uint", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getLodLevelFullTicks(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + hfe::uint m_returnValue; +}; +BF2_CC_NAME consoleObject334; + +// ConsoleClass335 AIBotManager.getLodLevelMediumTicks: method, 0..0 arguments, returns hfe::uint. +// ELF isObjectActive 0x43FEE0, executeObjectMethod 0x440010, +// setArgFromString 0x440000, getReturnValueAsString 0x43FCA0, D1 0x43FC80, D0 0x43FC40. +// argc 0: dice::hfe::ai::BotManager::getLodLevelMediumTicks() const (slot +0x28 at 0x440045; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass335 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getLodLevelMediumTicks", 0, 0, 0, "hfe::uint", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getLodLevelMediumTicks(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + hfe::uint m_returnValue; +}; +BF2_CC_NAME consoleObject335; + +// ConsoleClass336 AIBotManager.getLodLevelLightTicks: method, 0..0 arguments, returns hfe::uint. +// ELF isObjectActive 0x440310, executeObjectMethod 0x440440, +// setArgFromString 0x440430, getReturnValueAsString 0x4400D0, D1 0x4400B0, D0 0x440070. +// argc 0: dice::hfe::ai::BotManager::getLodLevelLightTicks() const (slot +0x2C at 0x440475; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass336 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getLodLevelLightTicks", 0, 0, 0, "hfe::uint", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getLodLevelLightTicks(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + hfe::uint m_returnValue; +}; +BF2_CC_NAME consoleObject336; + +// ConsoleClass337 AIBotManager.getLodLevelFullPriority: method, 0..0 arguments, returns hfe::uint. +// ELF isObjectActive 0x440740, executeObjectMethod 0x440870, +// setArgFromString 0x440860, getReturnValueAsString 0x440500, D1 0x4404E0, D0 0x4404A0. +// argc 0: dice::hfe::ai::BotManager::getLodLevelFullPriority() const (slot +0x30 at 0x4408A5; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass337 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getLodLevelFullPriority", 0, 0, 0, "hfe::uint", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getLodLevelFullPriority(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + hfe::uint m_returnValue; +}; +BF2_CC_NAME consoleObject337; + +// ConsoleClass338 AIBotManager.getLodLevelMediumPriority: method, 0..0 arguments, returns hfe::uint. +// ELF isObjectActive 0x440B70, executeObjectMethod 0x440CA0, +// setArgFromString 0x440C90, getReturnValueAsString 0x440930, D1 0x440910, D0 0x4408D0. +// argc 0: dice::hfe::ai::BotManager::getLodLevelMediumPriority() const (slot +0x34 at 0x440CD5; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass338 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getLodLevelMediumPriority", 0, 0, 0, "hfe::uint", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getLodLevelMediumPriority(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + hfe::uint m_returnValue; +}; +BF2_CC_NAME consoleObject338; + +// ConsoleClass339 AIBotManager.getLodLevelLightPriority: method, 0..0 arguments, returns hfe::uint. +// ELF isObjectActive 0x440FA0, executeObjectMethod 0x4410D0, +// setArgFromString 0x4410C0, getReturnValueAsString 0x440D60, D1 0x440D40, D0 0x440D00. +// argc 0: dice::hfe::ai::BotManager::getLodLevelLightPriority() const (slot +0x38 at 0x441105; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass339 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getLodLevelLightPriority", 0, 0, 0, "hfe::uint", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getLodLevelLightPriority(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + hfe::uint m_returnValue; +}; +BF2_CC_NAME consoleObject339; + +// ConsoleClass340 AIBotManager.getPlannedDecisionMakingThresholdFull: method, 0..0 arguments, returns double. +// ELF isObjectActive 0x4413D0, executeObjectMethod 0x441500, +// setArgFromString 0x4414F0, getReturnValueAsString 0x441190, D1 0x441170, D0 0x441130. +// argc 0: dice::hfe::ai::BotManager::getPlannedDecisionMakingThresholdFull() const (slot +0x3C at 0x441535; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass340 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getPlannedDecisionMakingThresholdFull", 0, 0, 0, "double", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getPlannedDecisionMakingThresholdFull(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + double m_returnValue; +}; +BF2_CC_NAME consoleObject340; + +// ConsoleClass341 AIBotManager.getPlannedDecisionMakingThresholdMedium: method, 0..0 arguments, returns double. +// ELF isObjectActive 0x441800, executeObjectMethod 0x441930, +// setArgFromString 0x441920, getReturnValueAsString 0x4415C0, D1 0x4415A0, D0 0x441560. +// argc 0: dice::hfe::ai::BotManager::getPlannedDecisionMakingThresholdMedium() const (slot +0x40 at 0x441965; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass341 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getPlannedDecisionMakingThresholdMedium", 0, 0, 0, "double", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getPlannedDecisionMakingThresholdMedium(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + double m_returnValue; +}; +BF2_CC_NAME consoleObject341; + +// ConsoleClass342 AIBotManager.getPlannedDecisionMakingThresholdLight: method, 0..0 arguments, returns double. +// ELF isObjectActive 0x441C30, executeObjectMethod 0x441D60, +// setArgFromString 0x441D50, getReturnValueAsString 0x4419F0, D1 0x4419D0, D0 0x441990. +// argc 0: dice::hfe::ai::BotManager::getPlannedDecisionMakingThresholdLight() const (slot +0x44 at 0x441D95; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass342 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getPlannedDecisionMakingThresholdLight", 0, 0, 0, "double", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getPlannedDecisionMakingThresholdLight(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + double m_returnValue; +}; +BF2_CC_NAME consoleObject342; + +// ConsoleClass343 AIBotManager.getUnplannedDecisionMakingThresholdFull: method, 0..0 arguments, returns double. +// ELF isObjectActive 0x442060, executeObjectMethod 0x442190, +// setArgFromString 0x442180, getReturnValueAsString 0x441E20, D1 0x441E00, D0 0x441DC0. +// argc 0: dice::hfe::ai::BotManager::getUnplannedDecisionMakingThresholdFull() const (slot +0x48 at 0x4421C5; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass343 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getUnplannedDecisionMakingThresholdFull", 0, 0, 0, "double", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getUnplannedDecisionMakingThresholdFull(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + double m_returnValue; +}; +BF2_CC_NAME consoleObject343; + +// ConsoleClass344 AIBotManager.getUnplannedDecisionMakingThresholdMedium: method, 0..0 arguments, returns double. +// ELF isObjectActive 0x442490, executeObjectMethod 0x4425C0, +// setArgFromString 0x4425B0, getReturnValueAsString 0x442250, D1 0x442230, D0 0x4421F0. +// argc 0: dice::hfe::ai::BotManager::getUnplannedDecisionMakingThresholdMedium() const (slot +0x4C at 0x4425F5; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass344 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getUnplannedDecisionMakingThresholdMedium", 0, 0, 0, "double", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getUnplannedDecisionMakingThresholdMedium(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + double m_returnValue; +}; +BF2_CC_NAME consoleObject344; + +// ConsoleClass345 AIBotManager.getUnplannedDecisionMakingThresholdLight: method, 0..0 arguments, returns double. +// ELF isObjectActive 0x4428C0, executeObjectMethod 0x4429F0, +// setArgFromString 0x4429E0, getReturnValueAsString 0x442680, D1 0x442660, D0 0x442620. +// argc 0: dice::hfe::ai::BotManager::getUnplannedDecisionMakingThresholdLight() const (slot +0x50 at 0x442A25; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass345 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getUnplannedDecisionMakingThresholdLight", 0, 0, 0, "double", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getUnplannedDecisionMakingThresholdLight(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + double m_returnValue; +}; +BF2_CC_NAME consoleObject345; + +// ConsoleClass346 AIBotManager.getPlannedDecisionMakingInterleave: method, 0..0 arguments, returns hfe::uint. +// ELF isObjectActive 0x442CF0, executeObjectMethod 0x442E20, +// setArgFromString 0x442E10, getReturnValueAsString 0x442AB0, D1 0x442A90, D0 0x442A50. +// argc 0: dice::hfe::ai::BotManager::getPlannedDecisionMakingInterleave() const (slot +0x54 at 0x442E55; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass346 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getPlannedDecisionMakingInterleave", 0, 0, 0, "hfe::uint", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getPlannedDecisionMakingInterleave(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + hfe::uint m_returnValue; +}; +BF2_CC_NAME consoleObject346; + +// ConsoleClass347 AIBotManager.getUnplannedDecisionMakingInterleave: method, 0..0 arguments, returns hfe::uint. +// ELF isObjectActive 0x443120, executeObjectMethod 0x443250, +// setArgFromString 0x443240, getReturnValueAsString 0x442EE0, D1 0x442EC0, D0 0x442E80. +// argc 0: dice::hfe::ai::BotManager::getUnplannedDecisionMakingInterleave() const (slot +0x58 at 0x443285; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass347 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getUnplannedDecisionMakingInterleave", 0, 0, 0, "hfe::uint", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getUnplannedDecisionMakingInterleave(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + hfe::uint m_returnValue; +}; +BF2_CC_NAME consoleObject347; + +// ConsoleClass348 AIBotManager.getSensingQuotient: method, 0..0 arguments, returns double. +// ELF isObjectActive 0x443550, executeObjectMethod 0x443680, +// setArgFromString 0x443670, getReturnValueAsString 0x443310, D1 0x4432F0, D0 0x4432B0. +// argc 0: dice::hfe::ai::BotManager::getSensingQuotient() const (slot +0x5C at 0x4436B5; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass348 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getSensingQuotient", 0, 0, 0, "double", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getSensingQuotient(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + double m_returnValue; +}; +BF2_CC_NAME consoleObject348; + +// ConsoleClass349 AIBotManager.getMemoryUpdateQuotient: method, 0..0 arguments, returns double. +// ELF isObjectActive 0x443980, executeObjectMethod 0x443AB0, +// setArgFromString 0x443AA0, getReturnValueAsString 0x443740, D1 0x443720, D0 0x4436E0. +// argc 0: dice::hfe::ai::BotManager::getMemoryUpdateQuotient() const (slot +0x60 at 0x443AE5; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass349 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getMemoryUpdateQuotient", 0, 0, 0, "double", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getMemoryUpdateQuotient(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + double m_returnValue; +}; +BF2_CC_NAME consoleObject349; + +// ConsoleClass350 AIBotManager.getSystemDecisionMakingQuotient: method, 0..0 arguments, returns double. +// ELF isObjectActive 0x443DB0, executeObjectMethod 0x443EE0, +// setArgFromString 0x443ED0, getReturnValueAsString 0x443B70, D1 0x443B50, D0 0x443B10. +// argc 0: dice::hfe::ai::BotManager::getSystemDecisionMakingQuotient() const (slot +0x64 at 0x443F15; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass350 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getSystemDecisionMakingQuotient", 0, 0, 0, "double", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getSystemDecisionMakingQuotient(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + double m_returnValue; +}; +BF2_CC_NAME consoleObject350; + +// ConsoleClass351 AIBotManager.getSystemPathfindingQuotient: method, 0..0 arguments, returns double. +// ELF isObjectActive 0x4441E0, executeObjectMethod 0x444310, +// setArgFromString 0x444300, getReturnValueAsString 0x443FA0, D1 0x443F80, D0 0x443F40. +// argc 0: dice::hfe::ai::BotManager::getSystemPathfindingQuotient() const (slot +0x68 at 0x444345; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass351 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getSystemPathfindingQuotient", 0, 0, 0, "double", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getSystemPathfindingQuotient(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + double m_returnValue; +}; +BF2_CC_NAME consoleObject351; + +// ConsoleClass352 AIBotManager.getSystemSensingQuotient: method, 0..0 arguments, returns double. +// ELF isObjectActive 0x444610, executeObjectMethod 0x444740, +// setArgFromString 0x444730, getReturnValueAsString 0x4443D0, D1 0x4443B0, D0 0x444370. +// argc 0: dice::hfe::ai::BotManager::getSystemSensingQuotient() const (slot +0x6C at 0x444775; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass352 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getSystemSensingQuotient", 0, 0, 0, "double", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getSystemSensingQuotient(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + double m_returnValue; +}; +BF2_CC_NAME consoleObject352; + +// ConsoleClass353 AIBotManager.enableBotScriptDebugger: method, 1..1 arguments, no result. +// ELF isObjectActive 0x444840, executeObjectMethod 0x444BA0, +// setArgFromString 0x444960, getReturnValueAsString 0x444800, D1 0x4447E0, D0 0x4447A0. +// argc 1: dice::hfe::ai::BotManager::enableBotScriptDebugger(bool) (slot +0xA8 at 0x444BEB; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass353 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("enableBotScriptDebugger", 0, 1, 1, "void", false) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + IBotManagerModifier::instance->enableBotScriptDebugger(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject353; + +SetConsoleClassDefaults aiStrategyfullAccessSetConsoleClassDefaults("aiStrategy", 2, 0); + +// ConsoleClass361 aiStrategy.createStrategy: method, 1..1 arguments, no result. +// ELF isObjectActive 0x444CA0, executeObjectMethod 0x445050, +// setArgFromString 0x444DD0, getReturnValueAsString 0x444C60, D1 0x444C40, D0 0x444C00. +// argc 1: dice::hfe::ai::StrategyManager::createStrategy(std::string) (call at 0x4450BE; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass361 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createStrategy", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + StrategyManager::getInstance()->createStrategy(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject361; + +// ConsoleClass362 aiStrategy.setActiveStrategy: method, 1..1 arguments, no result. +// ELF isObjectActive 0x4451B0, executeObjectMethod 0x445560, +// setArgFromString 0x4452E0, getReturnValueAsString 0x445170, D1 0x445150, D0 0x445110. +// argc 1: dice::hfe::ai::StrategyManager::setActiveStrategy(std::string) (call at 0x4455CE; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass362 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setActiveStrategy", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + StrategyManager::getInstance()->setActiveStrategy(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject362; + +// ConsoleClass363 aiStrategy.getActiveStrategyName: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x445940, executeObjectMethod 0x445A80, +// setArgFromString 0x445A70, getReturnValueAsString 0x445700, D1 0x445690, D0 0x445620. +// argc 0: dice::hfe::ai::StrategyManager::getActiveStrategyName() (call at 0x445AC0; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass363 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getActiveStrategyName", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = StrategyManager::getInstance()->getActiveStrategyName(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject363; + +// ConsoleClass364 aiStrategy.aggression: property, 0..1 arguments, returns float. +// ELF isObjectActive 0x445DB0, executeObjectMethod 0x446120, +// setArgFromString 0x445EE0, getReturnValueAsString 0x445B70, D1 0x445B50, D0 0x445B10. +// argc 0: dice::hfe::ai::Strategy::getAggression() const (call at 0x446186; ledger done) +// argc 1: dice::hfe::ai::Strategy::setAggression(float) (call at 0x44616E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass364 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("aggression", 1, 0, 1, "float", true) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategy() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategy()->getAggression(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveStrategy()->setAggression(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject364; + +// ConsoleClass365 aiStrategy.timeLimit: property, 0..1 arguments, returns float. +// ELF isObjectActive 0x446440, executeObjectMethod 0x4467B0, +// setArgFromString 0x446570, getReturnValueAsString 0x446200, D1 0x4461E0, D0 0x4461A0. +// argc 0: inline accessor, reads the member at +0x20 (m_f20) +// argc 1: inline accessor, stores the member at +0x20 (m_f20) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass365 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("timeLimit", 1, 0, 1, "float", true) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategy() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategy()->m_f20; + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveStrategy()->m_f20 = BF2_CC_ARG(float, 0); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject365; + +// ConsoleClass366 aiStrategy.getPrerequisiteWeight: method, 0..0 arguments, returns float. +// ELF isObjectActive 0x446AC0, executeObjectMethod 0x446C00, +// setArgFromString 0x446BF0, getReturnValueAsString 0x446880, D1 0x446860, D0 0x446820. +// argc 0: dice::hfe::ai::Strategy::getPrerequisiteWeight() const (call at 0x446C30; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass366 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getPrerequisiteWeight", 0, 0, 0, "float", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveStrategy() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategy()->getPrerequisiteWeight(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject366; + +// ConsoleClass367 aiStrategy.setPrerequisiteWeight: method, 1..1 arguments, no result. +// ELF isObjectActive 0x446D00, executeObjectMethod 0x447070, +// setArgFromString 0x446E30, getReturnValueAsString 0x446CC0, D1 0x446CA0, D0 0x446C60. +// argc 1: dice::hfe::ai::Strategy::setPrerequisiteWeight(float) (call at 0x4470B8; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass367 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setPrerequisiteWeight", 0, 1, 1, "void", false) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategy() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveStrategy()->setPrerequisiteWeight(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject367; + +// ConsoleClass368 aiStrategy.listStrategies: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x4473F0, executeObjectMethod 0x447530, +// setArgFromString 0x447520, getReturnValueAsString 0x4471B0, D1 0x447140, D0 0x4470D0. +// argc 0: dice::hfe::ai::StrategyManager::listStrategies() (call at 0x447570; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass368 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("listStrategies", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = StrategyManager::getInstance()->listStrategies(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject368; + +// ConsoleClass369 aiStrategy.setTreeModifier: method, 2..2 arguments, float result discarded. +// ELF isObjectActive 0x447660, executeObjectMethod 0x447C10, +// setArgFromString 0x447790, getReturnValueAsString 0x447620, D1 0x447600, D0 0x4475C0. +// argc 2: dice::hfe::ai::Strategy::setTreeModifier(dice::hfe::ai::TemperatureTreeNode, float) (call at 0x447C63; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass369 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setTreeModifier", 0, 2, 2, "float", false) + m_argTypes[0] = "TemperatureTreeNode"; + m_argTypes[1] = "float"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return getActiveStrategy() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + getActiveStrategy()->setTreeModifier(BF2_CC_ARG(TemperatureTreeNode, 0), BF2_CC_ARG(float, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT_WITH(TemperatureTreeNode, 1, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT(float, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject369; + +// ConsoleClass370 aiStrategy.getTreeModifier: method, 1..1 arguments, returns float. +// ELF isObjectActive 0x447F10, executeObjectMethod 0x448280, +// setArgFromString 0x448040, getReturnValueAsString 0x447CD0, D1 0x447CB0, D0 0x447C70. +// argc 1: dice::hfe::ai::Strategy::getTreeModifier(dice::hfe::ai::TemperatureTreeNode) const (call at 0x4482BB; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass370 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getTreeModifier", 0, 1, 1, "float", true) + m_argTypes[0] = "TemperatureTreeNode"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategy() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategy()->getTreeModifier(BF2_CC_ARG(TemperatureTreeNode, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT_WITH(TemperatureTreeNode, 1, dice::hfe::ai::operator>>) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject370; + +// ConsoleClass371 aiStrategy.setTreeModifierCombatStrength: method, 3..3 arguments, float result discarded. +// ELF isObjectActive 0x448390, executeObjectMethod 0x448B70, +// setArgFromString 0x4484C0, getReturnValueAsString 0x448350, D1 0x448330, D0 0x4482F0. +// argc 3: dice::hfe::ai::Strategy::setTreeModifierCombatStrength(dice::hfe::ai::TemperatureTreeNode, dice::hfe::ai::CombatStrengthType, float) (call at 0x448BD2; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass371 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setTreeModifierCombatStrength", 0, 3, 3, "float", false) + m_argTypes[0] = "TemperatureTreeNode"; + m_argTypes[1] = "CombatStrengthType"; + m_argTypes[2] = "float"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return getActiveStrategy() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = false; + getActiveStrategy()->setTreeModifierCombatStrength(BF2_CC_ARG(TemperatureTreeNode, 0), BF2_CC_ARG(CombatStrengthType, 1), BF2_CC_ARG(float, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT_WITH(TemperatureTreeNode, 1, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT_WITH(CombatStrengthType, 2, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT(float, 3) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject371; + +// ConsoleClass372 aiStrategy.getTreeModifierCombatStrength: method, 2..2 arguments, returns float. +// ELF isObjectActive 0x448E80, executeObjectMethod 0x449430, +// setArgFromString 0x448FB0, getReturnValueAsString 0x448C40, D1 0x448C20, D0 0x448BE0. +// argc 2: dice::hfe::ai::Strategy::getTreeModifierCombatStrength(dice::hfe::ai::TemperatureTreeNode, dice::hfe::ai::CombatStrengthType) const (call at 0x449479; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass372 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getTreeModifierCombatStrength", 0, 2, 2, "float", true) + m_argTypes[0] = "TemperatureTreeNode"; + m_argTypes[1] = "CombatStrengthType"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return getActiveStrategy() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategy()->getTreeModifierCombatStrength(BF2_CC_ARG(TemperatureTreeNode, 0), BF2_CC_ARG(CombatStrengthType, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT_WITH(TemperatureTreeNode, 1, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT_WITH(CombatStrengthType, 2, dice::hfe::ai::operator>>) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject372; + +// ConsoleClass373 aiStrategy.numberOfAttacks: property, 0..1 arguments, returns int. +// ELF isObjectActive 0x449780, executeObjectMethod 0x449AF0, +// setArgFromString 0x4498B0, getReturnValueAsString 0x449510, D1 0x4494F0, D0 0x4494B0. +// argc 0: dice::hfe::ai::Strategy::getNumberOfAttacks() const (call at 0x449B56; ledger done) +// argc 1: dice::hfe::ai::Strategy::setNumberOfAttacks(unsigned int) (call at 0x449B3E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass373 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("numberOfAttacks", 1, 0, 1, "int", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategy() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategy()->getNumberOfAttacks(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveStrategy()->setNumberOfAttacks(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject373; + +// ConsoleClass374 aiStrategy.numberOfDefences: property, 0..1 arguments, returns int. +// ELF isObjectActive 0x449E40, executeObjectMethod 0x44A1B0, +// setArgFromString 0x449F70, getReturnValueAsString 0x449BD0, D1 0x449BB0, D0 0x449B70. +// argc 0: dice::hfe::ai::Strategy::getNumberOfDefences() const (call at 0x44A216; ledger done) +// argc 1: dice::hfe::ai::Strategy::setNumberOfDefences(unsigned int) (call at 0x44A1FE; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass374 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("numberOfDefences", 1, 0, 1, "int", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategy() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategy()->getNumberOfDefences(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveStrategy()->setNumberOfDefences(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject374; + +// ConsoleClass375 aiStrategy.setPrerequisite: method, 1..1 arguments, no result. +// ELF isObjectActive 0x44A2D0, executeObjectMethod 0x44A680, +// setArgFromString 0x44A400, getReturnValueAsString 0x44A290, D1 0x44A270, D0 0x44A230. +// argc 1: dice::hfe::ai::StrategyManager::setPrerequisite(std::string) (call at 0x44A6EE; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass375 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setPrerequisite", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + StrategyManager::getInstance()->setPrerequisite(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject375; + +// ConsoleClass376 aiStrategy.addRequiredPrecedingStrategy: method, 1..1 arguments, returns bool. +// ELF isObjectActive 0x44A9E0, executeObjectMethod 0x44AD90, +// setArgFromString 0x44AB10, getReturnValueAsString 0x44A7A0, D1 0x44A780, D0 0x44A740. +// argc 1: dice::hfe::ai::StrategyManager::addRequiredPrecedingStrategy(std::string) (call at 0x44ADF0; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass376 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addRequiredPrecedingStrategy", 0, 1, 1, "bool", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = StrategyManager::getInstance()->addRequiredPrecedingStrategy(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject376; + +// ConsoleClass377 aiStrategy.addProhibitedPrecedingStrategy: method, 1..1 arguments, returns bool. +// ELF isObjectActive 0x44B110, executeObjectMethod 0x44B4C0, +// setArgFromString 0x44B240, getReturnValueAsString 0x44AED0, D1 0x44AEB0, D0 0x44AE70. +// argc 1: dice::hfe::ai::StrategyManager::addProhibitedPrecedingStrategy(std::string) (call at 0x44B520; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass377 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addProhibitedPrecedingStrategy", 0, 1, 1, "bool", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = StrategyManager::getInstance()->addProhibitedPrecedingStrategy(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject377; + +// ConsoleClass378 aiStrategy.setStrategicObjectsModifier: method, 2..3 arguments, no result. +// ELF isObjectActive 0x44B640, executeObjectMethod 0x44BE20, +// setArgFromString 0x44B770, getReturnValueAsString 0x44B600, D1 0x44B5E0, D0 0x44B5A0. +// argc 2: dice::hfe::ai::Strategy::setStrategicObjectsModifier(dice::hfe::ai::AIStrategicObject::StrategicObjectType, float) (call at 0x44BEBE; ledger done) +// argc 3: dice::hfe::ai::Strategy::setStrategicObjectsModifier(dice::hfe::ai::AIStrategicObject::StrategicObjectType, float, dice::hfe::ai::StatusMap::Status) (call at 0x44BE90; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass378 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setStrategicObjectsModifier", 0, 2, 3, "void", false) + m_argTypes[0] = "AIStrategicObject::StrategicObjectType"; + m_argTypes[1] = "float"; + m_argTypes[2] = "StatusMap::Status"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return getActiveStrategy() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + getActiveStrategy()->setStrategicObjectsModifier(BF2_CC_ARG(AIStrategicObject::StrategicObjectType, 0), BF2_CC_ARG(float, 1)); + } + else if (m_argCount == 3) + { + m_hasReturnValue = false; + getActiveStrategy()->setStrategicObjectsModifier(BF2_CC_ARG(AIStrategicObject::StrategicObjectType, 0), BF2_CC_ARG(float, 1), BF2_CC_ARG(StatusMap::Status, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT_WITH(AIStrategicObject::StrategicObjectType, 1, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT(float, 2) + AIMODULE_CC_EXTRACT_WITH(StatusMap::Status, 3, dice::hfe::ai::operator>>) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject378; + +// ConsoleClass379 aiStrategy.getStrategicObjectsModifier: method, 1..2 arguments, returns float. +// ELF isObjectActive 0x44C170, executeObjectMethod 0x44C720, +// setArgFromString 0x44C2A0, getReturnValueAsString 0x44BF30, D1 0x44BF10, D0 0x44BED0. +// argc 1: dice::hfe::ai::Strategy::getStrategicObjectsModifier(dice::hfe::ai::AIStrategicObject::StrategicObjectType) const (call at 0x44C7AD; ledger done) +// argc 2: dice::hfe::ai::Strategy::getStrategicObjectsModifier(dice::hfe::ai::AIStrategicObject::StrategicObjectType, dice::hfe::ai::StatusMap::Status) const (call at 0x44C773; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass379 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getStrategicObjectsModifier", 0, 1, 2, "float", true) + m_argTypes[0] = "AIStrategicObject::StrategicObjectType"; + m_argTypes[1] = "StatusMap::Status"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return getActiveStrategy() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategy()->getStrategicObjectsModifier(BF2_CC_ARG(AIStrategicObject::StrategicObjectType, 0)); + } + else if (m_argCount == 2) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategy()->getStrategicObjectsModifier(BF2_CC_ARG(AIStrategicObject::StrategicObjectType, 0), BF2_CC_ARG(StatusMap::Status, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT_WITH(AIStrategicObject::StrategicObjectType, 1, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT_WITH(StatusMap::Status, 2, dice::hfe::ai::operator>>) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject379; + +// ConsoleClass380 aiStrategy.clearAllStrategicObjectsModifiers: method, 0..0 arguments, no result. +// ELF isObjectActive 0x44C860, executeObjectMethod 0x44C9A0, +// setArgFromString 0x44C990, getReturnValueAsString 0x44C820, D1 0x44C800, D0 0x44C7C0. +// argc 0: dice::hfe::ai::Strategy::clearAllStrategicObjectsModifiers() (call at 0x44C9D6; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass380 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("clearAllStrategicObjectsModifiers", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveStrategy() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + getActiveStrategy()->clearAllStrategicObjectsModifiers(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject380; + +// ConsoleClass381 aiStrategy.addSpecificObjectModifier: method, 2..2 arguments, returns bool. +// ELF isObjectActive 0x44CC80, executeObjectMethod 0x44D260, +// setArgFromString 0x44CDB0, getReturnValueAsString 0x44CA40, D1 0x44CA20, D0 0x44C9E0. +// argc 2: dice::hfe::ai::StrategyManager::addSpecificObjectModifier(std::string, float) (call at 0x44D2CF; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass381 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addSpecificObjectModifier", 0, 2, 2, "bool", true) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "float"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = true; + m_returnValue = StrategyManager::getInstance()->addSpecificObjectModifier(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(float, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(float, 2) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject381; + +// ConsoleClass382 aiStrategy.completeStrategies: method, 0..0 arguments, no result. +// ELF isObjectActive 0x44D3F0, executeObjectMethod 0x44D530, +// setArgFromString 0x44D520, getReturnValueAsString 0x44D3B0, D1 0x44D390, D0 0x44D350. +// argc 0: dice::hfe::ai::StrategyManager::completeStrategies() (call at 0x44D566; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass382 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("completeStrategies", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + StrategyManager::getInstance()->completeStrategies(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject382; + +// ConsoleClass385 aiStrategy.createPrerequisite: method, 1..1 arguments, no result. +// ELF isObjectActive 0x44D610, executeObjectMethod 0x44D9C0, +// setArgFromString 0x44D740, getReturnValueAsString 0x44D5D0, D1 0x44D5B0, D0 0x44D570. +// argc 1: dice::hfe::ai::StrategyManager::createPrerequisite(std::string) (call at 0x44DA2E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass385 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createPrerequisite", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + StrategyManager::getInstance()->createPrerequisite(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject385; + +// ConsoleClass386 aiStrategy.setActivePrerequisite: method, 1..1 arguments, no result. +// ELF isObjectActive 0x44DB20, executeObjectMethod 0x44DED0, +// setArgFromString 0x44DC50, getReturnValueAsString 0x44DAE0, D1 0x44DAC0, D0 0x44DA80. +// argc 1: dice::hfe::ai::StrategyManager::setActivePrerequisite(std::string) (call at 0x44DF3E; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass386 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setActivePrerequisite", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + StrategyManager::getInstance()->setActivePrerequisite(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject386; + +// ConsoleClass387 aiStrategy.getActivePrerequisiteName: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x44E2B0, executeObjectMethod 0x44E3F0, +// setArgFromString 0x44E3E0, getReturnValueAsString 0x44E070, D1 0x44E000, D0 0x44DF90. +// argc 0: dice::hfe::ai::StrategyManager::getActivePrerequisiteName() (call at 0x44E430; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass387 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getActivePrerequisiteName", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = StrategyManager::getInstance()->getActivePrerequisiteName(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject387; + +// ConsoleClass388 aiStrategy.listPrerequisites: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x44E7A0, executeObjectMethod 0x44E8E0, +// setArgFromString 0x44E8D0, getReturnValueAsString 0x44E560, D1 0x44E4F0, D0 0x44E480. +// argc 0: dice::hfe::ai::StrategyManager::listPrerequisites() (call at 0x44E920; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass388 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("listPrerequisites", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = StrategyManager::getInstance()->listPrerequisites(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject388; + +// ConsoleClass389 aiStrategy.addCondition: method, 1..2 arguments, no result. +// ELF isObjectActive 0x44EA10, executeObjectMethod 0x44EFF0, +// setArgFromString 0x44EB40, getReturnValueAsString 0x44E9D0, D1 0x44E9B0, D0 0x44E970. +// argc 1: dice::hfe::ai::StrategyManager::addCondition(std::string) (call at 0x44F10A; ledger done) +// argc 2: dice::hfe::ai::StrategyManager::addCondition(std::string, float) (call at 0x44F081; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass389 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addCondition", 0, 1, 2, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "float"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + StrategyManager::getInstance()->addCondition(BF2_CC_ARG(std::string, 0)); + } + else if (m_argCount == 2) + { + m_hasReturnValue = false; + StrategyManager::getInstance()->addCondition(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(float, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(float, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject389; + +// ConsoleClass392 aiStrategy.setActiveCondition: method, 1..1 arguments, no result. +// ELF isObjectActive 0x44F1F0, executeObjectMethod 0x44F5A0, +// setArgFromString 0x44F320, getReturnValueAsString 0x44F1B0, D1 0x44F190, D0 0x44F150. +// argc 1: dice::hfe::ai::StrategyManager::setActiveCondition(std::string) (call at 0x44F60E; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass392 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setActiveCondition", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + StrategyManager::getInstance()->setActiveCondition(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject392; + +// ConsoleClass393 aiStrategy.getActiveConditionName: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x44F980, executeObjectMethod 0x44FAC0, +// setArgFromString 0x44FAB0, getReturnValueAsString 0x44F740, D1 0x44F6D0, D0 0x44F660. +// argc 0: dice::hfe::ai::StrategyManager::getActiveConditionName() (call at 0x44FB00; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass393 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getActiveConditionName", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = StrategyManager::getInstance()->getActiveConditionName(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject393; + +// ConsoleClass394 aiStrategy.listConditions: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x44FE70, executeObjectMethod 0x44FFB0, +// setArgFromString 0x44FFA0, getReturnValueAsString 0x44FC30, D1 0x44FBC0, D0 0x44FB50. +// argc 0: dice::hfe::ai::StrategyManager::listConditions() (call at 0x44FFF0; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass394 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("listConditions", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = StrategyManager::getInstance()->listConditions(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject394; + +// ConsoleClass395 aiStrategy.createConstantCondition: method, 6..6 arguments, returns bool. +// ELF isObjectActive 0x4502E0, executeObjectMethod 0x451100, +// setArgFromString 0x450410, getReturnValueAsString 0x4500A0, D1 0x450080, D0 0x450040. +// argc 6: dice::hfe::ai::StrategyManager::createConstantCondition(std::string, dice::hfe::ai::StrategyCondition::CompareType, dice::hfe::ai::StrategyCondition::Compare, dice::hfe::ai::StrategyCondition::ConditionSide, dice::hfe::ai::StrategyCondition::Conditional, float) (call at 0x4511A5; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass395 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createConstantCondition", 0, 6, 6, "bool", true) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "StrategyCondition::CompareType"; + m_argTypes[2] = "StrategyCondition::Compare"; + m_argTypes[3] = "StrategyCondition::ConditionSide"; + m_argTypes[4] = "StrategyCondition::Conditional"; + m_argTypes[5] = "float"; + AIMODULE_CC_TAIL(6) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 6) + { + m_hasReturnValue = true; + m_returnValue = StrategyManager::getInstance()->createConstantCondition(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(StrategyCondition::CompareType, 1), BF2_CC_ARG(StrategyCondition::Compare, 2), BF2_CC_ARG(StrategyCondition::ConditionSide, 3), BF2_CC_ARG(StrategyCondition::Conditional, 4), BF2_CC_ARG(float, 5)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT_WITH(StrategyCondition::CompareType, 2, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT_WITH(StrategyCondition::Compare, 3, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT_WITH(StrategyCondition::ConditionSide, 4, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT_WITH(StrategyCondition::Conditional, 5, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT(float, 6) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject395; + +// ConsoleClass396 aiStrategy.createHomogenousCondition: method, 4..4 arguments, returns bool. +// ELF isObjectActive 0x4514C0, executeObjectMethod 0x451EC0, +// setArgFromString 0x4515F0, getReturnValueAsString 0x451280, D1 0x451260, D0 0x451220. +// argc 4: dice::hfe::ai::StrategyManager::createHomogenousCondition(std::string, dice::hfe::ai::StrategyCondition::CompareType, dice::hfe::ai::StrategyCondition::Compare, dice::hfe::ai::StrategyCondition::Conditional) (call at 0x451F47; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass396 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createHomogenousCondition", 0, 4, 4, "bool", true) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "StrategyCondition::CompareType"; + m_argTypes[2] = "StrategyCondition::Compare"; + m_argTypes[3] = "StrategyCondition::Conditional"; + AIMODULE_CC_TAIL(4) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 4) + { + m_hasReturnValue = true; + m_returnValue = StrategyManager::getInstance()->createHomogenousCondition(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(StrategyCondition::CompareType, 1), BF2_CC_ARG(StrategyCondition::Compare, 2), BF2_CC_ARG(StrategyCondition::Conditional, 3)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT_WITH(StrategyCondition::CompareType, 2, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT_WITH(StrategyCondition::Compare, 3, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT_WITH(StrategyCondition::Conditional, 4, dice::hfe::ai::operator>>) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject396; + +// ConsoleClass397 aiStrategy.createHeterogeneousCondition: method, 6..6 arguments, returns bool. +// ELF isObjectActive 0x452260, executeObjectMethod 0x453080, +// setArgFromString 0x452390, getReturnValueAsString 0x452020, D1 0x452000, D0 0x451FC0. +// argc 6: dice::hfe::ai::StrategyManager::createHeterogeneousCondition(std::string, dice::hfe::ai::StrategyCondition::CompareType, dice::hfe::ai::StrategyCondition::Compare, dice::hfe::ai::StrategyCondition::ConditionSide, dice::hfe::ai::StrategyCondition::Conditional, dice::hfe::ai::StrategyCondition::Conditional) (call at 0x453125; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass397 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createHeterogeneousCondition", 0, 6, 6, "bool", true) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "StrategyCondition::CompareType"; + m_argTypes[2] = "StrategyCondition::Compare"; + m_argTypes[3] = "StrategyCondition::ConditionSide"; + m_argTypes[4] = "StrategyCondition::Conditional"; + m_argTypes[5] = "StrategyCondition::Conditional"; + AIMODULE_CC_TAIL(6) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 6) + { + m_hasReturnValue = true; + m_returnValue = StrategyManager::getInstance()->createHeterogeneousCondition(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(StrategyCondition::CompareType, 1), BF2_CC_ARG(StrategyCondition::Compare, 2), BF2_CC_ARG(StrategyCondition::ConditionSide, 3), BF2_CC_ARG(StrategyCondition::Conditional, 4), BF2_CC_ARG(StrategyCondition::Conditional, 5)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT_WITH(StrategyCondition::CompareType, 2, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT_WITH(StrategyCondition::Compare, 3, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT_WITH(StrategyCondition::ConditionSide, 4, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT_WITH(StrategyCondition::Conditional, 5, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT_WITH(StrategyCondition::Conditional, 6, dice::hfe::ai::operator>>) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject397; + +// ConsoleClass398 aiStrategy.createAreaCondition: method, 3..3 arguments, returns bool. +// ELF isObjectActive 0x453440, executeObjectMethod 0x453C80, +// setArgFromString 0x453570, getReturnValueAsString 0x453200, D1 0x4531E0, D0 0x4531A0. +// argc 3: dice::hfe::ai::StrategyManager::createAreaCondition(std::string, std::string, dice::hfe::ai::StatusMap::Status) (call at 0x453D1D; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass398 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createAreaCondition", 0, 3, 3, "bool", true) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "std::string"; + m_argTypes[2] = "StatusMap::Status"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = true; + m_returnValue = StrategyManager::getInstance()->createAreaCondition(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(std::string, 1), BF2_CC_ARG(StatusMap::Status, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + AIMODULE_CC_EXTRACT_WITH(StatusMap::Status, 3, dice::hfe::ai::operator>>) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject398; + +// ConsoleClass399 aiStrategy.setConditionStrength: method, 1..1 arguments, no result. +// ELF isObjectActive 0x453E80, executeObjectMethod 0x4541F0, +// setArgFromString 0x453FB0, getReturnValueAsString 0x453E40, D1 0x453E20, D0 0x453DE0. +// argc 1: dice::hfe::ai::StrategyCondition::setConditionStrength(dice::hfe::ai::StrategyCondition::ConditionStrength) (call at 0x454238; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass399 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setConditionStrength", 0, 1, 1, "void", false) + m_argTypes[0] = "StrategyCondition::ConditionStrength"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveCondition() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveCondition()->setConditionStrength(BF2_CC_ARG(StrategyCondition::ConditionStrength, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT_WITH(StrategyCondition::ConditionStrength, 1, dice::hfe::ai::operator>>) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject399; + +// ConsoleClass400 aiStrategy.getConditionStrength: method, 0..0 arguments, returns StrategyCondition::ConditionStrength. +// ELF isObjectActive 0x4544E0, executeObjectMethod 0x454620, +// setArgFromString 0x454610, getReturnValueAsString 0x4542A0, D1 0x454280, D0 0x454240. +// argc 0: dice::hfe::ai::StrategyCondition::getConditionStrength() const (call at 0x454650; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass400 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getConditionStrength", 0, 0, 0, "StrategyCondition::ConditionStrength", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveCondition() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveCondition()->getConditionStrength(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + StrategyCondition::ConditionStrength m_returnValue; +}; +BF2_CC_NAME consoleObject400; + +// ConsoleClass401 aiStrategy.setIsAbortCondition: method, 1..1 arguments, no result. +// ELF isObjectActive 0x454720, executeObjectMethod 0x454A90, +// setArgFromString 0x454850, getReturnValueAsString 0x4546E0, D1 0x4546C0, D0 0x454680. +// argc 1: dice::hfe::ai::StrategyCondition::setIsAbortCondition(bool) (call at 0x454AD6; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass401 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setIsAbortCondition", 0, 1, 1, "void", false) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveCondition() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveCondition()->setIsAbortCondition(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject401; + +// ConsoleClass402 aiStrategy.isAbortCondition: method, 0..0 arguments, returns bool. +// ELF isObjectActive 0x454D80, executeObjectMethod 0x454EC0, +// setArgFromString 0x454EB0, getReturnValueAsString 0x454B40, D1 0x454B20, D0 0x454AE0. +// argc 0: dice::hfe::ai::StrategyCondition::isAbortCondition() const (call at 0x454EF0; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass402 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("isAbortCondition", 0, 0, 0, "bool", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveCondition() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveCondition()->isAbortCondition(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject402; + +// ConsoleClass403 aiStrategy.completeConditions: method, 0..0 arguments, no result. +// ELF isObjectActive 0x454FC0, executeObjectMethod 0x455100, +// setArgFromString 0x4550F0, getReturnValueAsString 0x454F80, D1 0x454F60, D0 0x454F20. +// argc 0: dice::hfe::ai::StrategyManager::completeConditions() (call at 0x455136; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass403 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("completeConditions", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + StrategyManager::getInstance()->completeConditions(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject403; + +// ConsoleClass404 aiStrategy.targetValue: property, 0..1 arguments, returns float. +// ELF isObjectActive 0x4553E0, executeObjectMethod 0x455750, +// setArgFromString 0x455510, getReturnValueAsString 0x4551A0, D1 0x455180, D0 0x455140. +// argc 0: dice::hfe::ai::StrategyCondition::getTargetValue() const (call at 0x4557BF; ledger done) +// argc 1: dice::hfe::ai::StrategyCondition::setTargetValue(float) (call at 0x45579E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass404 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("targetValue", 1, 0, 1, "float", true) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveCondition() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveCondition()->getTargetValue(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveCondition()->setTargetValue(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject404; + +// ConsoleClass407 aiStrategy.forceStrategy: method, 2..2 arguments, returns std::string. +// ELF isObjectActive 0x455B00, executeObjectMethod 0x4560E0, +// setArgFromString 0x455C30, getReturnValueAsString 0x4558C0, D1 0x455850, D0 0x4557E0. +// argc 2: dice::hfe::ai::StrategyManager::forceStrategy(std::string, int) (call at 0x456159; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass407 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("forceStrategy", 0, 2, 2, "std::string", true) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "int"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = true; + m_returnValue = StrategyManager::getInstance()->forceStrategy(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(int, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(int, 2) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject407; + +// ConsoleClass408 aiStrategy.enableDebug: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x456490, executeObjectMethod 0x456800, +// setArgFromString 0x4565C0, getReturnValueAsString 0x456250, D1 0x456230, D0 0x4561F0. +// argc 0: dice::hfe::ai::StrategyManager::getEnableDebug() (call at 0x45686F; ledger done) +// argc 1: dice::hfe::ai::StrategyManager::setEnableDebug(bool) (call at 0x456850; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass408 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("enableDebug", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = StrategyManager::getInstance()->getEnableDebug(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + StrategyManager::getInstance()->setEnableDebug(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject408; + +// ConsoleClass411 aiStrategy.thresholdSpeed: property, 0..1 arguments, returns float. +// ELF isObjectActive 0x456B30, executeObjectMethod 0x456E90, +// setArgFromString 0x456C50, getReturnValueAsString 0x4568F0, D1 0x4568D0, D0 0x456890. +// argc 0: dice::hfe::ai::AIConsole::getFastThreshold() (call at 0x456EF6; ledger stop) +// argc 1: dice::hfe::ai::AIConsole::setFastThreshold(float) (call at 0x456EDB; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass411 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("thresholdSpeed", 1, 0, 1, "float", true) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIConsole::m_instance->getFastThreshold(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + AIConsole::m_instance->setFastThreshold(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject411; + +SetConsoleClassDefaults AIStrategicAreafullAccessSetConsoleClassDefaults("AIStrategicArea", 2, 0); + +// ConsoleClass417 AIStrategicArea.create: method, 5..6 arguments, returns bool. +// ELF isObjectActive 0x4571B0, executeObjectMethod 0x4580E0, +// setArgFromString 0x4572E0, getReturnValueAsString 0x456F70, D1 0x456F50, D0 0x456F10. +// argc 5: dice::hfe::ai::AIStrategicObjectManager::create(std::string, dice::hfe::Vec2, dice::hfe::Vec2, float, float, std::string const&) (call at 0x458399; ledger done) +// argc 6: dice::hfe::ai::AIStrategicObjectManager::create(std::string, dice::hfe::Vec2, dice::hfe::Vec2, float, float, std::string const&) (call at 0x45820B; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass417 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("create", 0, 5, 6, "bool", true) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "Vec2"; + m_argTypes[2] = "Vec2"; + m_argTypes[3] = "float"; + m_argTypes[4] = "float"; + m_argTypes[5] = "std::string"; + AIMODULE_CC_TAIL(6) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 5) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->create(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(Vec2, 1), BF2_CC_ARG(Vec2, 2), BF2_CC_ARG(float, 3), BF2_CC_ARG(float, 4)); + } + else if (m_argCount == 6) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->create(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(Vec2, 1), BF2_CC_ARG(Vec2, 2), BF2_CC_ARG(float, 3), BF2_CC_ARG(float, 4), BF2_CC_ARG(std::string, 5)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(Vec2, 2) + AIMODULE_CC_EXTRACT(Vec2, 3) + AIMODULE_CC_EXTRACT(float, 4) + AIMODULE_CC_EXTRACT(float, 5) + AIMODULE_CC_EXTRACT(std::string, 6) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject417; + +// ConsoleClass418 AIStrategicArea.setFlankPosition: method, 2..2 arguments, no result. +// ELF isObjectActive 0x4584D0, executeObjectMethod 0x458BC0, +// setArgFromString 0x458600, getReturnValueAsString 0x458490, D1 0x458470, D0 0x458430. +// argc 2: dice::hfe::ai::AIStrategicObjectManager::setFlankPosition(dice::hfe::Vec3, dice::hfe::Vec3) (call at 0x458C53; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass418 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setFlankPosition", 0, 2, 2, "void", false) + m_argTypes[0] = "Vec3"; + m_argTypes[1] = "Vec3"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + AIStrategicObjectManager::getInstance()->setFlankPosition(BF2_CC_ARG(Vec3, 0), BF2_CC_ARG(Vec3, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(Vec3, 1) + AIMODULE_CC_EXTRACT(Vec3, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject418; + +// ConsoleClass419 AIStrategicArea.createFromControlPoint: method, 3..4 arguments, returns bool. +// ELF isObjectActive 0x458F00, executeObjectMethod 0x459950, +// setArgFromString 0x459030, getReturnValueAsString 0x458CC0, D1 0x458CA0, D0 0x458C60. +// argc 3: dice::hfe::ai::AIStrategicObjectManager::createFromControlPoint(std::string const&, unsigned int, float, std::string const&) (call at 0x459AC9; ledger done) +// argc 4: dice::hfe::ai::AIStrategicObjectManager::createFromControlPoint(std::string const&, unsigned int, float, std::string const&) (call at 0x4599EB; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass419 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createFromControlPoint", 0, 3, 4, "bool", true) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "u32"; + m_argTypes[2] = "float"; + m_argTypes[3] = "std::string"; + AIMODULE_CC_TAIL(4) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->createFromControlPoint(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(u32, 1), BF2_CC_ARG(float, 2)); + } + else if (m_argCount == 4) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->createFromControlPoint(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(u32, 1), BF2_CC_ARG(float, 2), BF2_CC_ARG(std::string, 3)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(u32, 2) + AIMODULE_CC_EXTRACT(float, 3) + AIMODULE_CC_EXTRACT(std::string, 4) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject419; + +// ConsoleClass420 AIStrategicArea.removeActive: method, 0..0 arguments, returns bool. +// ELF isObjectActive 0x459DD0, executeObjectMethod 0x459F10, +// setArgFromString 0x459F00, getReturnValueAsString 0x459B90, D1 0x459B70, D0 0x459B30. +// argc 0: dice::hfe::ai::AIStrategicObjectManager::removeActive() (call at 0x459F40; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass420 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("removeActive", 0, 0, 0, "bool", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->removeActive(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject420; + +// ConsoleClass421 AIStrategicArea.setActive: method, 1..1 arguments, returns bool. +// ELF isObjectActive 0x45A210, executeObjectMethod 0x45A5C0, +// setArgFromString 0x45A340, getReturnValueAsString 0x459FD0, D1 0x459FB0, D0 0x459F70. +// argc 1: dice::hfe::ai::AIStrategicObjectManager::setActive(std::string) (call at 0x45A620; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass421 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setActive", 0, 1, 1, "bool", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->setActive(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject421; + +// ConsoleClass422 AIStrategicArea.getActive: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x45A9C0, executeObjectMethod 0x45AB00, +// setArgFromString 0x45AAF0, getReturnValueAsString 0x45A780, D1 0x45A710, D0 0x45A6A0. +// argc 0: dice::hfe::ai::AIStrategicObjectManager::getActive() const (call at 0x45AB40; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass422 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getActive", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->getActive(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject422; + +// ConsoleClass423 AIStrategicArea.addNeighbour: method, 1..1 arguments, returns bool. +// ELF isObjectActive 0x45AE30, executeObjectMethod 0x45B1E0, +// setArgFromString 0x45AF60, getReturnValueAsString 0x45ABF0, D1 0x45ABD0, D0 0x45AB90. +// argc 1: dice::hfe::ai::AIStrategicObjectManager::addNeighbour(std::string) (call at 0x45B240; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass423 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addNeighbour", 0, 1, 1, "bool", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->addNeighbour(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject423; + +// ConsoleClass424 AIStrategicArea.addTwoWayNeighbour: method, 2..2 arguments, returns bool. +// ELF isObjectActive 0x45B560, executeObjectMethod 0x45BB80, +// setArgFromString 0x45B690, getReturnValueAsString 0x45B320, D1 0x45B300, D0 0x45B2C0. +// argc 2: dice::hfe::ai::AIStrategicObjectManager::addTwoWayNeighbour(std::string, std::string) (call at 0x45BC0E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass424 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addTwoWayNeighbour", 0, 2, 2, "bool", true) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "std::string"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->addTwoWayNeighbour(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(std::string, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject424; + +// ConsoleClass425 AIStrategicArea.getNeighbours: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x45BFF0, executeObjectMethod 0x45C130, +// setArgFromString 0x45C120, getReturnValueAsString 0x45BDB0, D1 0x45BD40, D0 0x45BCD0. +// argc 0: dice::hfe::ai::AIStrategicObjectManager::getNeighbours() (call at 0x45C170; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass425 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getNeighbours", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->getNeighbours(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject425; + +// ConsoleClass426 AIStrategicArea.layer: property, 0..1 arguments, returns int. +// ELF isObjectActive 0x45C490, executeObjectMethod 0x45C800, +// setArgFromString 0x45C5C0, getReturnValueAsString 0x45C220, D1 0x45C200, D0 0x45C1C0. +// argc 0: inline accessor, reads the member at +0x190 (m_i400) +// argc 1: inline accessor, stores the member at +0x190 (m_i400) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass426 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("layer", 1, 0, 1, "int", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->m_i400; + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveStrategicArea()->m_i400 = BF2_CC_ARG(int, 0); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject426; + +// ConsoleClass427 AIStrategicArea.setVisible: method, 1..1 arguments, no result. +// ELF isObjectActive 0x45C920, executeObjectMethod 0x45CC90, +// setArgFromString 0x45CA50, getReturnValueAsString 0x45C8E0, D1 0x45C8C0, D0 0x45C880. +// argc 1: verified inline body, normalized visibility store +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass427 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setVisible", 0, 1, 1, "void", false) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + const bool value = BF2_CC_ARG(bool, 0); + m_hasReturnValue = false; + getActiveStrategicArea()->m_visible = (value != 0); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject427; + +// ConsoleClass428 AIStrategicArea.getVisible: method, 0..0 arguments, returns bool. +// ELF isObjectActive 0x45CF80, executeObjectMethod 0x45D0C0, +// setArgFromString 0x45D0B0, getReturnValueAsString 0x45CD40, D1 0x45CD20, D0 0x45CCE0. +// argc 0: verified inline body, normalized visibility load +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass428 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getVisible", 0, 0, 0, "bool", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = (getActiveStrategicArea()->m_visible != 0); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject428; + +// ConsoleClass429 AIStrategicArea.drawVehicleSearchRadi: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x45D3C0, executeObjectMethod 0x45D730, +// setArgFromString 0x45D4F0, getReturnValueAsString 0x45D180, D1 0x45D160, D0 0x45D120. +// argc 0: verified inline body, vehicle-search-radius drawing switch +// argc 1: verified inline body, vehicle-search-radius drawing switch +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass429 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("drawVehicleSearchRadi", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->m_drawVehicleSearchRadii; + } + else if (m_argCount == 1) + { + const bool value = BF2_CC_ARG(bool, 0); + m_hasReturnValue = false; + AIStrategicObjectManager::getInstance()->m_drawVehicleSearchRadii = value; + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject429; + +// ConsoleClass430 AIStrategicArea.removeAllNeighbours: method, 0..0 arguments, no result. +// ELF isObjectActive 0x45D840, executeObjectMethod 0x45D980, +// setArgFromString 0x45D970, getReturnValueAsString 0x45D800, D1 0x45D7E0, D0 0x45D7A0. +// argc 0: dice::hfe::ai::AIStrategicObjectManager::removeAllNeighbours() (call at 0x45D9B6; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass430 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("removeAllNeighbours", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + AIStrategicObjectManager::getInstance()->removeAllNeighbours(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject430; + +// ConsoleClass431 AIStrategicArea.setPosition: method, 1..1 arguments, no result. +// ELF isObjectActive 0x45DA60, executeObjectMethod 0x45DE30, +// setArgFromString 0x45DB90, getReturnValueAsString 0x45DA20, D1 0x45DA00, D0 0x45D9C0. +// argc 1: dice::hfe::ai::AIStrategicArea::setPosition(dice::hfe::Vec2 const&) (call at 0x45DE84; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass431 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setPosition", 0, 1, 1, "void", false) + m_argTypes[0] = "hfe::Vec2"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveStrategicArea()->setPosition(BF2_CC_ARG(hfe::Vec2, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(hfe::Vec2, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject431; + +// ConsoleClass432 AIStrategicArea.getPosition: method, 0..0 arguments, returns hfe::Vec2. +// ELF isObjectActive 0x45E160, executeObjectMethod 0x45E2A0, +// setArgFromString 0x45E290, getReturnValueAsString 0x45DEF0, D1 0x45DED0, D0 0x45DE90. +// argc 0: dice::hfe::ai::AIStrategicObjectManager::getPosition() const (call at 0x45E2E5; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass432 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getPosition", 0, 0, 0, "hfe::Vec2", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->getPosition(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + hfe::Vec2 m_returnValue; +}; +BF2_CC_NAME consoleObject432; + +// ConsoleClass433 AIStrategicArea.centerPosition: property, 0..1 arguments, returns hfe::Vec2. +// ELF isObjectActive 0x45E5F0, executeObjectMethod 0x45E9C0, +// setArgFromString 0x45E720, getReturnValueAsString 0x45E380, D1 0x45E360, D0 0x45E320. +// argc 0: dice::hfe::ai::AIStrategicArea::getCenterPosition() const (call at 0x45EA38; ledger done) +// argc 1: dice::hfe::ai::AIStrategicArea::setCenterPosition(dice::hfe::Vec2 const&) (call at 0x45EA1A; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass433 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("centerPosition", 1, 0, 1, "hfe::Vec2", true) + m_argTypes[0] = "hfe::Vec2"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->getCenterPosition(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveStrategicArea()->setCenterPosition(BF2_CC_ARG(hfe::Vec2, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(hfe::Vec2, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + hfe::Vec2 m_returnValue; +}; +BF2_CC_NAME consoleObject433; + +// ConsoleClass434 AIStrategicArea.topLeftCorner: property, 0..1 arguments, returns hfe::Vec2. +// ELF isObjectActive 0x45ED20, executeObjectMethod 0x45F0F0, +// setArgFromString 0x45EE50, getReturnValueAsString 0x45EAB0, D1 0x45EA90, D0 0x45EA50. +// argc 0: inline accessor, reads the member at +0x110 (m_centre) +// argc 1: dice::hfe::ai::AIStrategicArea::setTopLeftCorner(dice::hfe::Vec2 const&) (call at 0x45F14A; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass434 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("topLeftCorner", 1, 0, 1, "hfe::Vec2", true) + m_argTypes[0] = "hfe::Vec2"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->m_centre; + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveStrategicArea()->setTopLeftCorner(BF2_CC_ARG(hfe::Vec2, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(hfe::Vec2, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + hfe::Vec2 m_returnValue; +}; +BF2_CC_NAME consoleObject434; + +// ConsoleClass435 AIStrategicArea.list: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x45F4A0, executeObjectMethod 0x45F5E0, +// setArgFromString 0x45F5D0, getReturnValueAsString 0x45F260, D1 0x45F1F0, D0 0x45F180. +// argc 0: dice::hfe::ai::AIStrategicObjectManager::list() const (call at 0x45F620; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass435 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("list", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->list(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject435; + +// ConsoleClass436 AIStrategicArea.addObjectTypeFlag: method, 1..1 arguments, returns int. +// ELF isObjectActive 0x45F940, executeObjectMethod 0x45FCB0, +// setArgFromString 0x45FA70, getReturnValueAsString 0x45F6D0, D1 0x45F6B0, D0 0x45F670. +// argc 1: dice::hfe::ai::AIStrategicObjectManager::addObjectTypeFlag(dice::hfe::ai::AIStrategicObject::StrategicObjectType) (call at 0x45FCEB; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass436 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addObjectTypeFlag", 0, 1, 1, "int", true) + m_argTypes[0] = "AIStrategicObject::StrategicObjectType"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->addObjectTypeFlag(BF2_CC_ARG(AIStrategicObject::StrategicObjectType, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT_WITH(AIStrategicObject::StrategicObjectType, 1, dice::hfe::ai::operator>>) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject436; + +// ConsoleClass437 AIStrategicArea.setObjectTypeFlags: method, 1..1 arguments, returns int. +// ELF isObjectActive 0x45FFF0, executeObjectMethod 0x460360, +// setArgFromString 0x460120, getReturnValueAsString 0x45FD80, D1 0x45FD60, D0 0x45FD20. +// argc 1: dice::hfe::ai::AIStrategicObjectManager::setObjectTypeFlags(int) (call at 0x46039B; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass437 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setObjectTypeFlags", 0, 1, 1, "int", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->setObjectTypeFlags(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject437; + +// ConsoleClass438 AIStrategicArea.getObjectTypeFlags: method, 0..0 arguments, returns int. +// ELF isObjectActive 0x4606A0, executeObjectMethod 0x4607E0, +// setArgFromString 0x4607D0, getReturnValueAsString 0x460430, D1 0x460410, D0 0x4603D0. +// argc 0: dice::hfe::ai::AIStrategicObjectManager::getObjectTypeFlags() (call at 0x460810; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass438 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getObjectTypeFlags", 0, 0, 0, "int", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->getObjectTypeFlags(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject438; + +// ConsoleClass439 AIStrategicArea.removeObjectTypeFlag: method, 1..1 arguments, returns int. +// ELF isObjectActive 0x460B10, executeObjectMethod 0x460E80, +// setArgFromString 0x460C40, getReturnValueAsString 0x4608A0, D1 0x460880, D0 0x460840. +// argc 1: dice::hfe::ai::AIStrategicObjectManager::removeObjectTypeFlag(dice::hfe::ai::AIStrategicObject::StrategicObjectType) (call at 0x460EBB; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass439 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("removeObjectTypeFlag", 0, 1, 1, "int", true) + m_argTypes[0] = "AIStrategicObject::StrategicObjectType"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->removeObjectTypeFlag(BF2_CC_ARG(AIStrategicObject::StrategicObjectType, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT_WITH(AIStrategicObject::StrategicObjectType, 1, dice::hfe::ai::operator>>) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject439; + +// ConsoleClass440 AIStrategicArea.setStatus: method, 2..2 arguments, returns StatusMap::Status. +// ELF isObjectActive 0x461190, executeObjectMethod 0x461740, +// setArgFromString 0x4612C0, getReturnValueAsString 0x460F50, D1 0x460F30, D0 0x460EF0. +// argc 2: verified inline body, unchecked status stores: saved pair first, current pair second, then return the status +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass440 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setStatus", 0, 2, 2, "StatusMap::Status", true) + m_argTypes[0] = "int"; + m_argTypes[1] = "StatusMap::Status"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + const int side = BF2_CC_ARG(int, 0); + const StatusMap::Status value = BF2_CC_ARG(StatusMap::Status, 1); + m_hasReturnValue = true; + AIStrategicArea* const object = getActiveStrategicArea(); + object->m_status[side + 1] = value; + object->m_status[side - 1] = value; + m_returnValue = value; + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + AIMODULE_CC_EXTRACT_WITH(StatusMap::Status, 2, dice::hfe::ai::operator>>) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + StatusMap::Status m_returnValue; +}; +BF2_CC_NAME consoleObject440; + +// ConsoleClass441 AIStrategicArea.category: property, 0..1 arguments, returns int. +// ELF isObjectActive 0x461A80, executeObjectMethod 0x461DF0, +// setArgFromString 0x461BB0, getReturnValueAsString 0x461810, D1 0x4617F0, D0 0x4617B0. +// argc 0: verified inline body, inherited category property +// argc 1: verified inline body, inherited category property +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass441 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("category", 1, 0, 1, "int", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->m_category; + } + else if (m_argCount == 1) + { + const int value = BF2_CC_ARG(int, 0); + m_hasReturnValue = false; + getActiveStrategicArea()->m_category = value; + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject441; + +// ConsoleClass442 AIStrategicArea.vehicleSearchRadius: property, 0..1 arguments, returns float. +// ELF isObjectActive 0x462110, executeObjectMethod 0x462480, +// setArgFromString 0x462240, getReturnValueAsString 0x461ED0, D1 0x461EB0, D0 0x461E70. +// argc 0: inline accessor, reads the member at +0x18C (m_f396) +// argc 1: inline accessor, stores the member at +0x18C (m_f396) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass442 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("vehicleSearchRadius", 1, 0, 1, "float", true) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->m_f396; + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveStrategicArea()->m_f396 = BF2_CC_ARG(float, 0); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject442; + +// ConsoleClass443 AIStrategicArea.setTakeable: method, 2..2 arguments, no result. +// ELF isObjectActive 0x4625A0, executeObjectMethod 0x462B50, +// setArgFromString 0x4626D0, getReturnValueAsString 0x462560, D1 0x462540, D0 0x462500. +// argc 2: verified inline body, unchecked one-based takeability store +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass443 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setTakeable", 0, 2, 2, "void", false) + m_argTypes[0] = "int"; + m_argTypes[1] = "bool"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + const int side = BF2_CC_ARG(int, 0); + const bool value = BF2_CC_ARG(bool, 1); + m_hasReturnValue = false; + getActiveStrategicArea()->m_sideEnabled[side - 1] = value; + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + AIMODULE_CC_EXTRACT(bool, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject443; + +// ConsoleClass444 AIStrategicArea.isTakeable: method, 1..1 arguments, returns bool. +// ELF isObjectActive 0x462E50, executeObjectMethod 0x4631C0, +// setArgFromString 0x462F80, getReturnValueAsString 0x462C10, D1 0x462BF0, D0 0x462BB0. +// argc 1: verified inline body, unchecked one-based takeability load +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass444 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("isTakeable", 0, 1, 1, "bool", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + const int side = BF2_CC_ARG(int, 0); + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->m_sideEnabled[side - 1]; + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject444; + +// ConsoleClass445 AIStrategicArea.removeAllObjectTypeFlags: method, 0..0 arguments, no result. +// ELF isObjectActive 0x4632C0, executeObjectMethod 0x463400, +// setArgFromString 0x4633F0, getReturnValueAsString 0x463280, D1 0x463260, D0 0x463220. +// argc 0: dice::hfe::ai::AIStrategicObjectManager::removeAllObjectTypeFlags() (call at 0x463436; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass445 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("removeAllObjectTypeFlags", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + AIStrategicObjectManager::getInstance()->removeAllObjectTypeFlags(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject445; + +// ConsoleClass446 AIStrategicArea.getObjectTypeFlagMapping: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x463760, executeObjectMethod 0x4638A0, +// setArgFromString 0x463890, getReturnValueAsString 0x463520, D1 0x4634B0, D0 0x463440. +// argc 0: dice::hfe::ai::AIStrategicObjectManager::getObjectTypeFlagMapping() const (call at 0x4638E0; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass446 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getObjectTypeFlagMapping", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->getObjectTypeFlagMapping(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject446; + +// ConsoleClass447 AIStrategicArea.basicTemperature: property, 0..1 arguments, returns float. +// ELF isObjectActive 0x463BD0, executeObjectMethod 0x463F40, +// setArgFromString 0x463D00, getReturnValueAsString 0x463990, D1 0x463970, D0 0x463930. +// argc 0: verified inline body, inherited baseline temperature, the first word of the shared temperature/radius storage +// argc 1: verified inline body, inherited baseline temperature, the first word of the shared temperature/radius storage +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass447 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("basicTemperature", 1, 0, 1, "float", true) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->m_size[AIStrategicObject::kBasicTemperature]; + } + else if (m_argCount == 1) + { + const float value = BF2_CC_ARG(float, 0); + m_hasReturnValue = false; + getActiveStrategicArea()->m_size[AIStrategicObject::kBasicTemperature] = value; + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject447; + +// ConsoleClass448 AIStrategicArea.setOrderPosition: method, 2..2 arguments, returns bool. +// ELF isObjectActive 0x464260, executeObjectMethod 0x4648F0, +// setArgFromString 0x464390, getReturnValueAsString 0x464020, D1 0x464000, D0 0x463FC0. +// argc 2: dice::hfe::ai::AIStrategicObjectManager::setOrderPosition(std::string, dice::hfe::Vec3 const&) (call at 0x46496B; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass448 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setOrderPosition", 0, 2, 2, "bool", true) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "Vec3"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->setOrderPosition(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(Vec3, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(Vec3, 2) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject448; + +// ConsoleClass449 AIStrategicArea.getOrderPosition: method, 1..1 arguments, returns Vec3. +// ELF isObjectActive 0x464CE0, executeObjectMethod 0x465090, +// setArgFromString 0x464E10, getReturnValueAsString 0x464A40, D1 0x464A20, D0 0x4649E0. +// argc 1: dice::hfe::ai::AIStrategicObjectManager::getOrderPosition(std::string) (call at 0x465100; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass449 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getOrderPosition", 0, 1, 1, "Vec3", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->getOrderPosition(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + Vec3 m_returnValue; +}; +BF2_CC_NAME consoleObject449; + +// ConsoleClass450 AIStrategicArea.listOrderPositions: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x4654A0, executeObjectMethod 0x4655E0, +// setArgFromString 0x4655D0, getReturnValueAsString 0x465260, D1 0x4651F0, D0 0x465180. +// argc 0: dice::hfe::ai::AIStrategicObjectManager::listOrderPositions() (call at 0x465620; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass450 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("listOrderPositions", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->listOrderPositions(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject450; + +// ConsoleClass451 AIStrategicArea.addWayPoint: method, 4..4 arguments, no result. +// ELF isObjectActive 0x465710, executeObjectMethod 0x466290, +// setArgFromString 0x465840, getReturnValueAsString 0x4656D0, D1 0x4656B0, D0 0x465670. +// argc 4: dice::hfe::ai::AIStrategicObjectManager::addWayPoint(dice::hfe::Vec3 const&, std::string const&, std::string const&, std::string const&) (call at 0x46634B; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass451 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addWayPoint", 0, 4, 4, "void", false) + m_argTypes[0] = "Vec3"; + m_argTypes[1] = "std::string"; + m_argTypes[2] = "std::string"; + m_argTypes[3] = "std::string"; + AIMODULE_CC_TAIL(4) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 4) + { + m_hasReturnValue = false; + AIStrategicObjectManager::getInstance()->addWayPoint(BF2_CC_ARG(Vec3, 0), BF2_CC_ARG(std::string, 1), BF2_CC_ARG(std::string, 2), BF2_CC_ARG(std::string, 3)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(Vec3, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + AIMODULE_CC_EXTRACT(std::string, 3) + AIMODULE_CC_EXTRACT(std::string, 4) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject451; + +// ConsoleClass452 AIStrategicArea.removeWayPoint: method, 4..4 arguments, returns bool. +// ELF isObjectActive 0x466660, executeObjectMethod 0x4671E0, +// setArgFromString 0x466790, getReturnValueAsString 0x466420, D1 0x466400, D0 0x4663C0. +// argc 4: dice::hfe::ai::AIStrategicObjectManager::removeWayPoint(dice::hfe::Vec3 const&, std::string const&, std::string const&, std::string const&) (call at 0x467287; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass452 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("removeWayPoint", 0, 4, 4, "bool", true) + m_argTypes[0] = "Vec3"; + m_argTypes[1] = "std::string"; + m_argTypes[2] = "std::string"; + m_argTypes[3] = "std::string"; + AIMODULE_CC_TAIL(4) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 4) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->removeWayPoint(BF2_CC_ARG(Vec3, 0), BF2_CC_ARG(std::string, 1), BF2_CC_ARG(std::string, 2), BF2_CC_ARG(std::string, 3)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(Vec3, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + AIMODULE_CC_EXTRACT(std::string, 3) + AIMODULE_CC_EXTRACT(std::string, 4) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject452; + +// ConsoleClass453 AIStrategicArea.clearWayPoints: method, 3..3 arguments, no result. +// ELF isObjectActive 0x4673C0, executeObjectMethod 0x467C40, +// setArgFromString 0x4674F0, getReturnValueAsString 0x467380, D1 0x467360, D0 0x467320. +// argc 3: dice::hfe::ai::AIStrategicObjectManager::clearWayPoints(std::string const&, std::string const&, std::string const&) (call at 0x467CD7; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass453 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("clearWayPoints", 0, 3, 3, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "std::string"; + m_argTypes[2] = "std::string"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = false; + AIStrategicObjectManager::getInstance()->clearWayPoints(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(std::string, 1), BF2_CC_ARG(std::string, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + AIMODULE_CC_EXTRACT(std::string, 3) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject453; + +// ConsoleClass454 AIStrategicArea.setWayPointsToDraw: method, 2..2 arguments, no result. +// ELF isObjectActive 0x467DE0, executeObjectMethod 0x468400, +// setArgFromString 0x467F10, getReturnValueAsString 0x467DA0, D1 0x467D80, D0 0x467D40. +// argc 2: dice::hfe::ai::AIStrategicObjectManager::setWayPointsToDraw(std::string const&, std::string const&) (call at 0x46847B; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass454 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setWayPointsToDraw", 0, 2, 2, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "std::string"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + AIStrategicObjectManager::getInstance()->setWayPointsToDraw(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(std::string, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject454; + +// ConsoleClass455 AIStrategicArea.clearWaypointToDraw: method, 0..0 arguments, no result. +// ELF isObjectActive 0x468570, executeObjectMethod 0x4686B0, +// setArgFromString 0x4686A0, getReturnValueAsString 0x468530, D1 0x468510, D0 0x4684D0. +// argc 0: dice::hfe::ai::AIStrategicObjectManager::clearWaypointToDraw() (call at 0x4686E6; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass455 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("clearWaypointToDraw", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + AIStrategicObjectManager::getInstance()->clearWaypointToDraw(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject455; + +// ConsoleClass456 AIStrategicArea.setSide: method, 1..1 arguments, no result. +// ELF isObjectActive 0x468790, executeObjectMethod 0x468B00, +// setArgFromString 0x4688C0, getReturnValueAsString 0x468750, D1 0x468730, D0 0x4686F0. +// argc 1: dice::hfe::ai::AIStrategicObject::setSide(int) (call at 0x468B48; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass456 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setSide", 0, 1, 1, "void", false) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveStrategicArea()->setSide(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject456; + +// ConsoleClass457 AIStrategicArea.getSide: method, 0..0 arguments, returns int. +// ELF isObjectActive 0x468E20, executeObjectMethod 0x468F60, +// setArgFromString 0x468F50, getReturnValueAsString 0x468BB0, D1 0x468B90, D0 0x468B50. +// argc 0: dice::hfe::ai::AIStrategicObject::getSide() (call at 0x468F90; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass457 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getSide", 0, 0, 0, "int", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->getSide(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject457; + +// ConsoleClass458 AIStrategicArea.enableDebug: method, 1..1 arguments, returns bool. +// ELF isObjectActive 0x469260, executeObjectMethod 0x4695D0, +// setArgFromString 0x469390, getReturnValueAsString 0x469020, D1 0x469000, D0 0x468FC0. +// argc 1: verified inline body, store and return the debug switch +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass458 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("enableDebug", 0, 1, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + const bool value = BF2_CC_ARG(bool, 0); + m_hasReturnValue = true; + AIStrategicObjectManager::getInstance()->m_debugEnabled = value; + m_returnValue = value; + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject458; + +// ConsoleClass459 AIStrategicArea.addAllowedVehicleGroup: method, 1..1 arguments, no result. +// ELF isObjectActive 0x4696D0, executeObjectMethod 0x469A80, +// setArgFromString 0x469800, getReturnValueAsString 0x469690, D1 0x469670, D0 0x469630. +// argc 1: dice::hfe::ai::AIStrategicObject::addAllowedVehicleGroup(std::string const&) (call at 0x469ADA; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass459 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addAllowedVehicleGroup", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveStrategicArea()->addAllowedVehicleGroup(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject459; + +// ConsoleClass460 AIStrategicArea.attachLandingZone: method, 1..1 arguments, no result. +// ELF isObjectActive 0x469BB0, executeObjectMethod 0x469F60, +// setArgFromString 0x469CE0, getReturnValueAsString 0x469B70, D1 0x469B50, D0 0x469B10. +// argc 1: dice::hfe::ai::AIStrategicArea::attachLandingZone(std::string const&) (call at 0x469FC6; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass460 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("attachLandingZone", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveStrategicArea()->attachLandingZone(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject460; + +// ConsoleClass461 AIStrategicArea.listLandingZones: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x46A330, executeObjectMethod 0x46A470, +// setArgFromString 0x46A460, getReturnValueAsString 0x46A0F0, D1 0x46A080, D0 0x46A010. +// argc 0: dice::hfe::ai::AIStrategicArea::listLandingZones() (call at 0x46A4B0; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass461 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("listLandingZones", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->listLandingZones(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject461; + +// ConsoleClass462 AIStrategicArea.getTemperature: method, 1..1 arguments, returns float. +// ELF isObjectActive 0x46A7A0, executeObjectMethod 0x46AB10, +// setArgFromString 0x46A8D0, getReturnValueAsString 0x46A560, D1 0x46A540, D0 0x46A500. +// argc 1: verified inline body, unchecked one-based current-temperature load +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass462 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getTemperature", 0, 1, 1, "float", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + const int side = BF2_CC_ARG(int, 0); + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->m_f164[side - 1]; + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject462; + +// ConsoleClass463 AIStrategicArea.getStatus: method, 1..1 arguments, returns StatusMap::Status. +// ELF isObjectActive 0x46AE10, executeObjectMethod 0x46B180, +// setArgFromString 0x46AF40, getReturnValueAsString 0x46ABD0, D1 0x46ABB0, D0 0x46AB70. +// argc 1: verified inline body, unchecked one-based current-status load +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass463 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getStatus", 0, 1, 1, "StatusMap::Status", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + const int side = BF2_CC_ARG(int, 0); + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->m_status[side - 1]; + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + StatusMap::Status m_returnValue; +}; +BF2_CC_NAME consoleObject463; + +// ConsoleClass464 AIStrategicArea.getNumberOfPresentUnits: method, 1..1 arguments, returns int. +// ELF isObjectActive 0x46B4B0, executeObjectMethod 0x46B820, +// setArgFromString 0x46B5E0, getReturnValueAsString 0x46B240, D1 0x46B220, D0 0x46B1E0. +// argc 1: dice::hfe::ai::AIStrategicObject::getNumberOfPresentUnits(int) const (call at 0x46B85B; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass464 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getNumberOfPresentUnits", 0, 1, 1, "int", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->getNumberOfPresentUnits(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject464; + +// ConsoleClass465 AIStrategicArea.getNumberOfAvailableAttackers: method, 1..1 arguments, returns int. +// ELF isObjectActive 0x46BB60, executeObjectMethod 0x46BED0, +// setArgFromString 0x46BC90, getReturnValueAsString 0x46B8F0, D1 0x46B8D0, D0 0x46B890. +// argc 1: dice::hfe::ai::AIStrategicObject::getNumberOfAvailableAttackers(int) const (call at 0x46BF0B; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass465 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getNumberOfAvailableAttackers", 0, 1, 1, "int", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->getNumberOfAvailableAttackers(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject465; + +// ConsoleClass466 AIStrategicArea.getNumberOfAvailableDefenders: method, 1..1 arguments, returns int. +// ELF isObjectActive 0x46C210, executeObjectMethod 0x46C580, +// setArgFromString 0x46C340, getReturnValueAsString 0x46BFA0, D1 0x46BF80, D0 0x46BF40. +// argc 1: dice::hfe::ai::AIStrategicObject::getNumberOfAvailableDefenders(int) const (call at 0x46C5BB; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass466 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getNumberOfAvailableDefenders", 0, 1, 1, "int", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->getNumberOfAvailableDefenders(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject466; + +// ConsoleClass467 AIStrategicArea.getNumberOfAssignedUnits: method, 1..1 arguments, returns int. +// ELF isObjectActive 0x46C8C0, executeObjectMethod 0x46CC30, +// setArgFromString 0x46C9F0, getReturnValueAsString 0x46C650, D1 0x46C630, D0 0x46C5F0. +// argc 1: dice::hfe::ai::AIStrategicObject::getNumberOfAssignedUnits(int) const (call at 0x46CC6B; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass467 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getNumberOfAssignedUnits", 0, 1, 1, "int", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->getNumberOfAssignedUnits(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject467; + +// ConsoleClass468 AIStrategicArea.getCategoryName: method, 1..1 arguments, returns std::string. +// ELF isObjectActive 0x46CFC0, executeObjectMethod 0x46D330, +// setArgFromString 0x46D0F0, getReturnValueAsString 0x46CD80, D1 0x46CD10, D0 0x46CCA0. +// argc 1: dice::hfe::ai::AIStrategicObjectManager::getCategoryName(int) const (call at 0x46D371; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass468 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getCategoryName", 0, 1, 1, "std::string", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->getCategoryName(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject468; + +// ConsoleClass469 AIStrategicArea.getCategoryFromName: method, 1..1 arguments, returns int. +// ELF isObjectActive 0x46D670, executeObjectMethod 0x46DA20, +// setArgFromString 0x46D7A0, getReturnValueAsString 0x46D400, D1 0x46D3E0, D0 0x46D3A0. +// argc 1: dice::hfe::ai::AIStrategicObjectManager::getCategoryFromName(std::string const&) const (call at 0x46DA6E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass469 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getCategoryFromName", 0, 1, 1, "int", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->getCategoryFromName(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject469; + +// ConsoleClass470 AIStrategicArea.createNewCategory: method, 1..1 arguments, no result. +// ELF isObjectActive 0x46DB60, executeObjectMethod 0x46DF10, +// setArgFromString 0x46DC90, getReturnValueAsString 0x46DB20, D1 0x46DB00, D0 0x46DAC0. +// argc 1: dice::hfe::ai::AIStrategicObjectManager::createNewCategory(std::string const&) (call at 0x46DF6A; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass470 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createNewCategory", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + AIStrategicObjectManager::getInstance()->createNewCategory(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject470; + +// ConsoleClass471 AIStrategicArea.showNeighbours: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x46E240, executeObjectMethod 0x46E5B0, +// setArgFromString 0x46E370, getReturnValueAsString 0x46E000, D1 0x46DFE0, D0 0x46DFA0. +// argc 0: verified inline body, neighbour drawing switch +// argc 1: verified inline body, neighbour drawing switch +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass471 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("showNeighbours", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->m_showNeighbours; + } + else if (m_argCount == 1) + { + const bool value = BF2_CC_ARG(bool, 0); + m_hasReturnValue = false; + getActiveStrategicArea()->m_showNeighbours = value; + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject471; + +// ConsoleClass472 AIStrategicArea.getStrategicAreaNames: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x46E950, executeObjectMethod 0x46EA90, +// setArgFromString 0x46EA80, getReturnValueAsString 0x46E710, D1 0x46E6A0, D0 0x46E630. +// argc 0: dice::hfe::ai::AIStrategicObjectManager::getStrategicAreaNames() (call at 0x46EAD0; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass472 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getStrategicAreaNames", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->getStrategicAreaNames(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject472; + +// ConsoleClass473 AIStrategicArea.isInside: method, 2..2 arguments, returns bool. +// ELF isObjectActive 0x46EDC0, executeObjectMethod 0x46F400, +// setArgFromString 0x46EEF0, getReturnValueAsString 0x46EB80, D1 0x46EB60, D0 0x46EB20. +// argc 2: dice::hfe::ai::AIStrategicObjectManager::isInside(std::string const&, dice::hfe::Vec2 const&) (call at 0x46F46D; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass473 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("isInside", 0, 2, 2, "bool", true) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "hfe::Vec2"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->isInside(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(hfe::Vec2, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(hfe::Vec2, 2) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject473; + +// ConsoleClass474 AIStrategicArea.strategicAreaName: property, 0..1 arguments, returns std::string. +// ELF isObjectActive 0x46F7E0, executeObjectMethod 0x46FB90, +// setArgFromString 0x46F910, getReturnValueAsString 0x46F5A0, D1 0x46F530, D0 0x46F4C0. +// argc 0: verified inline body, name load; shipped defect: setter copies and destroys the argument without assigning it +// argc 1: verified inline body, name load; shipped defect: setter copies and destroys the argument without assigning it +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass474 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("strategicAreaName", 1, 0, 1, "std::string", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->m_name; + } + else if (m_argCount == 1) + { + std::string value(BF2_CC_ARG(std::string, 0)); + m_hasReturnValue = false; + (void)getActiveStrategicArea(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject474; + +// ConsoleClass476 AIStrategicArea.saveAll: method, 2..2 arguments, returns bool. +// ELF isObjectActive 0x46FED0, executeObjectMethod 0x4704E0, +// setArgFromString 0x46FFF0, getReturnValueAsString 0x46FC90, D1 0x46FC70, D0 0x46FC30. +// argc 2: dice::hfe::ai::AIConsole::saveAll(std::string const&, std::string const&) (call at 0x470550; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass476 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("saveAll", 0, 2, 2, "bool", true) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "std::string"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = true; + m_returnValue = AIConsole::m_instance->saveAll(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(std::string, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject476; + +// ConsoleClass477 AIStrategicArea.addAllowedUnit: method, 1..1 arguments, no result. +// ELF isObjectActive 0x470670, executeObjectMethod 0x470A10, +// setArgFromString 0x470790, getReturnValueAsString 0x470630, D1 0x470610, D0 0x4705D0. +// argc 1: dice::hfe::ai::AIConsole::addAllowedUnit(std::string const&) (call at 0x470A6D; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass477 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addAllowedUnit", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + AIConsole::m_instance->addAllowedUnit(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject477; + +// ConsoleClass478 AIStrategicArea.addExpelledUnit: method, 1..1 arguments, no result. +// ELF isObjectActive 0x470B40, executeObjectMethod 0x470EE0, +// setArgFromString 0x470C60, getReturnValueAsString 0x470B00, D1 0x470AE0, D0 0x470AA0. +// argc 1: dice::hfe::ai::AIConsole::addExpelledUnit(std::string const&) (call at 0x470F3D; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass478 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addExpelledUnit", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + AIConsole::m_instance->addExpelledUnit(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject478; + +// ConsoleClass479 AIStrategicArea.addLandingZoneUnit: method, 1..1 arguments, no result. +// ELF isObjectActive 0x471010, executeObjectMethod 0x4713B0, +// setArgFromString 0x471130, getReturnValueAsString 0x470FD0, D1 0x470FB0, D0 0x470F70. +// argc 1: dice::hfe::ai::AIConsole::addLandingZoneUnit(std::string const&) (call at 0x47140D; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass479 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addLandingZoneUnit", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + AIConsole::m_instance->addLandingZoneUnit(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject479; + +SetConsoleClassDefaults AILandingZonefullAccessSetConsoleClassDefaults("AILandingZone", 2, 0); + +// ConsoleClass485 AILandingZone.activeZone: method, 0..1 arguments, returns std::string. +// ELF isObjectActive 0x471760, executeObjectMethod 0x471B00, +// setArgFromString 0x471880, getReturnValueAsString 0x471520, D1 0x4714B0, D0 0x471440. +// argc 0: dice::hfe::ai::AILandingZoneManager::activeZone() (call at 0x471BB8; ledger done) +// argc 1: dice::hfe::ai::AILandingZoneManager::activeZone(std::string const&) (call at 0x471B5A; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass485 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("activeZone", 0, 0, 1, "std::string", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AILandingZoneManager::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AILandingZoneManager::m_instance->activeZone(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = AILandingZoneManager::m_instance->activeZone(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject485; + +// ConsoleClass486 AILandingZone.createLandingZone: method, 5..5 arguments, no result. +// ELF isObjectActive 0x471C70, executeObjectMethod 0x472990, +// setArgFromString 0x471D90, getReturnValueAsString 0x471C30, D1 0x471C10, D0 0x471BD0. +// argc 5: dice::hfe::ai::AILandingZoneManager::createLandingZone(std::string const&, dice::hfe::Vec2 const&, dice::hfe::Vec2 const&, float, dice::hfe::ai::LandingZoneDirection) (call at 0x472A38; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass486 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createLandingZone", 0, 5, 5, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "Vec2"; + m_argTypes[2] = "Vec2"; + m_argTypes[3] = "float"; + m_argTypes[4] = "LandingZoneDirection"; + AIMODULE_CC_TAIL(5) + virtual bool isObjectActive() const { return AILandingZoneManager::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 5) + { + m_hasReturnValue = false; + AILandingZoneManager::m_instance->createLandingZone(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(Vec2, 1), BF2_CC_ARG(Vec2, 2), BF2_CC_ARG(float, 3), BF2_CC_ARG(LandingZoneDirection, 4)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(Vec2, 2) + AIMODULE_CC_EXTRACT(Vec2, 3) + AIMODULE_CC_EXTRACT(float, 4) + AIMODULE_CC_EXTRACT_WITH(LandingZoneDirection, 5, dice::hfe::ai::operator>>) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject486; + +// ConsoleClass487 AILandingZone.listZones: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x472D90, executeObjectMethod 0x472EC0, +// setArgFromString 0x472EB0, getReturnValueAsString 0x472B50, D1 0x472AE0, D0 0x472A70. +// argc 0: dice::hfe::ai::AILandingZoneManager::listZones() (call at 0x472F03; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass487 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("listZones", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AILandingZoneManager::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AILandingZoneManager::m_instance->listZones(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject487; + +// ConsoleClass488 AILandingZone.minCorner: property, 0..1 arguments, returns Vec2. +// ELF isObjectActive 0x473230, executeObjectMethod 0x473600, +// setArgFromString 0x473360, getReturnValueAsString 0x472FC0, D1 0x472FA0, D0 0x472F60. +// argc 0: dice::hfe::ai::AILandingZone::getMinCorner() const (call at 0x473678; ledger done) +// argc 1: dice::hfe::ai::AILandingZone::setMinCorner(dice::hfe::Vec2 const&) (call at 0x47365A; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass488 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("minCorner", 1, 0, 1, "Vec2", true) + m_argTypes[0] = "Vec2"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveLandingZone() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveLandingZone()->getMinCorner(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveLandingZone()->setMinCorner(BF2_CC_ARG(Vec2, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(Vec2, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + Vec2 m_returnValue; +}; +BF2_CC_NAME consoleObject488; + +// ConsoleClass489 AILandingZone.maxCorner: property, 0..1 arguments, returns Vec2. +// ELF isObjectActive 0x473960, executeObjectMethod 0x473D30, +// setArgFromString 0x473A90, getReturnValueAsString 0x4736F0, D1 0x4736D0, D0 0x473690. +// argc 0: dice::hfe::ai::AILandingZone::getMaxCorner() const (call at 0x473DA8; ledger done) +// argc 1: dice::hfe::ai::AILandingZone::setMaxCorner(dice::hfe::Vec2 const&) (call at 0x473D8A; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass489 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("maxCorner", 1, 0, 1, "Vec2", true) + m_argTypes[0] = "Vec2"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveLandingZone() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveLandingZone()->getMaxCorner(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveLandingZone()->setMaxCorner(BF2_CC_ARG(Vec2, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(Vec2, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + Vec2 m_returnValue; +}; +BF2_CC_NAME consoleObject489; + +// ConsoleClass490 AILandingZone.beachDirection: property, 0..1 arguments, returns LandingZoneDirection. +// ELF isObjectActive 0x474060, executeObjectMethod 0x4743D0, +// setArgFromString 0x474190, getReturnValueAsString 0x473E20, D1 0x473E00, D0 0x473DC0. +// argc 0: dice::hfe::ai::AILandingZone::getBeachDirection() const (call at 0x474436; ledger done) +// argc 1: dice::hfe::ai::AILandingZone::setBeachDirection(dice::hfe::ai::LandingZoneDirection) (call at 0x47441E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass490 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("beachDirection", 1, 0, 1, "LandingZoneDirection", true) + m_argTypes[0] = "LandingZoneDirection"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveLandingZone() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveLandingZone()->getBeachDirection(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveLandingZone()->setBeachDirection(BF2_CC_ARG(LandingZoneDirection, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT_WITH(LandingZoneDirection, 1, dice::hfe::ai::operator>>) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + LandingZoneDirection m_returnValue; +}; +BF2_CC_NAME consoleObject490; + +SetConsoleClassDefaults AIPathFindingfullAccessSetConsoleClassDefaults("AIPathFinding", 2, 0); + +// ConsoleClass496 AIPathFinding.createMap: method, 1..1 arguments, returns bool. +// ELF isObjectActive 0x4746F0, executeObjectMethod 0x474A90, +// setArgFromString 0x474810, getReturnValueAsString 0x4744B0, D1 0x474490, D0 0x474450. +// argc 1: dice::hfe::ai::AIPathfinding::createMap(std::string const&) (slot +0x10 at 0x474AE3; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass496 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createMap", 0, 1, 1, "bool", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return IAIPathfindingSetup::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = IAIPathfindingSetup::instance->createMap(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject496; + +// ConsoleClass497 AIPathFinding.deleteMap: method, 1..1 arguments, returns bool. +// ELF isObjectActive 0x474DD0, executeObjectMethod 0x475170, +// setArgFromString 0x474EF0, getReturnValueAsString 0x474B90, D1 0x474B70, D0 0x474B30. +// argc 1: dice::hfe::ai::AIPathfinding::deleteMap(std::string const&) (slot +0x14 at 0x4751C3; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass497 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("deleteMap", 0, 1, 1, "bool", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return IAIPathfindingSetup::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = IAIPathfindingSetup::instance->deleteMap(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject497; + +// ConsoleClass498 AIPathFinding.activeMap: property, 0..1 arguments, returns std::string. +// ELF isObjectActive 0x475530, executeObjectMethod 0x4758D0, +// setArgFromString 0x475650, getReturnValueAsString 0x4752F0, D1 0x475280, D0 0x475210. +// argc 0: dice::hfe::ai::AIPathfinding::getActiveMap() const (slot +0x1C at 0x47597A; ledger done) +// argc 1: dice::hfe::ai::AIPathfinding::setActiveMap(std::string const&) (slot +0x18 at 0x475933; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass498 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("activeMap", 1, 0, 1, "std::string", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return IAIPathfindingSetup::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IAIPathfindingSetup::instance->getActiveMap(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + IAIPathfindingSetup::instance->setActiveMap(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject498; + +// ConsoleClass499 AIPathFinding.traceMap: property, 0..1 arguments, returns std::string. +// ELF isObjectActive 0x475CB0, executeObjectMethod 0x476050, +// setArgFromString 0x475DD0, getReturnValueAsString 0x475A70, D1 0x475A00, D0 0x475990. +// argc 0: dice::hfe::ai::AIPathfinding::getTraceMap() const (slot +0x24 at 0x4760FA; ledger done) +// argc 1: dice::hfe::ai::AIPathfinding::setTraceMap(std::string const&) (slot +0x20 at 0x4760B3; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass499 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("traceMap", 1, 0, 1, "std::string", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return IAIPathfindingSetup::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IAIPathfindingSetup::instance->getTraceMap(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + IAIPathfindingSetup::instance->setTraceMap(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject499; + +// ConsoleClass500 AIPathFinding.getMapList: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x476430, executeObjectMethod 0x476560, +// setArgFromString 0x476550, getReturnValueAsString 0x4761F0, D1 0x476180, D0 0x476110. +// argc 0: dice::hfe::ai::AIPathfinding::getMapList() (slot +0x3C at 0x4765A5; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass500 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getMapList", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IAIPathfindingSetup::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IAIPathfindingSetup::instance->getMapList(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject500; + +// ConsoleClass502 AIPathFinding.map.maxSlope: property, 0..1 arguments, returns float. +// ELF isObjectActive 0x4768A0, executeObjectMethod 0x476C10, +// setArgFromString 0x4769D0, getReturnValueAsString 0x476660, D1 0x476640, D0 0x476600. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::getMaxSlope() const (slot +0x1C at 0x476C78; ledger done) +// argc 1: dice::hfe::ai::AIPathfinding::MapContainer::setMaxSlope(float) (slot +0x20 at 0x476C60; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass502 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.maxSlope", 1, 0, 1, "float", true) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveMapContainer()->getMaxSlope(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveMapContainer()->setMaxSlope(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject502; + +// ConsoleClass503 AIPathFinding.map.headClearance: property, 0..1 arguments, returns float. +// ELF isObjectActive 0x476F30, executeObjectMethod 0x4772A0, +// setArgFromString 0x477060, getReturnValueAsString 0x476CF0, D1 0x476CD0, D0 0x476C90. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::getHeadClearance() const (slot +0x28 at 0x477308; ledger done) +// argc 1: dice::hfe::ai::AIPathfinding::MapContainer::setHeadClearance(float) (slot +0x24 at 0x4772F0; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass503 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.headClearance", 1, 0, 1, "float", true) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveMapContainer()->getHeadClearance(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveMapContainer()->setHeadClearance(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject503; + +// ConsoleClass504 AIPathFinding.map.radius: property, 0..1 arguments, returns float. +// ELF isObjectActive 0x4775C0, executeObjectMethod 0x477930, +// setArgFromString 0x4776F0, getReturnValueAsString 0x477380, D1 0x477360, D0 0x477320. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::getRadius() const (slot +0x30 at 0x477998; ledger done) +// argc 1: dice::hfe::ai::AIPathfinding::MapContainer::setRadius(float) (slot +0x2C at 0x477980; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass504 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.radius", 1, 0, 1, "float", true) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveMapContainer()->getRadius(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveMapContainer()->setRadius(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject504; + +// ConsoleClass505 AIPathFinding.map.allowedHeightDiff: property, 0..1 arguments, returns float. +// ELF isObjectActive 0x477C50, executeObjectMethod 0x477FC0, +// setArgFromString 0x477D80, getReturnValueAsString 0x477A10, D1 0x4779F0, D0 0x4779B0. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::getAllowedHeightDiff() const (slot +0x38 at 0x478028; ledger done) +// argc 1: dice::hfe::ai::AIPathfinding::MapContainer::setAllowedHeightDiff(float) (slot +0x34 at 0x478010; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass505 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.allowedHeightDiff", 1, 0, 1, "float", true) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveMapContainer()->getAllowedHeightDiff(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveMapContainer()->setAllowedHeightDiff(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject505; + +// ConsoleClass506 AIPathFinding.map.minPolygonsInLeaf: property, 0..1 arguments, returns int. +// ELF isObjectActive 0x478310, executeObjectMethod 0x478680, +// setArgFromString 0x478440, getReturnValueAsString 0x4780A0, D1 0x478080, D0 0x478040. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::getMinPolygonsInLeaf() const (slot +0xC at 0x4786E8; ledger done) +// argc 1: dice::hfe::ai::AIPathfinding::MapContainer::setMinPolygonsInLeaf(int) (slot +0x10 at 0x4786D0; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass506 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.minPolygonsInLeaf", 1, 0, 1, "int", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveMapContainer()->getMinPolygonsInLeaf(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveMapContainer()->setMinPolygonsInLeaf(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject506; + +// ConsoleClass507 AIPathFinding.map.maxDepthInTree: property, 0..1 arguments, returns int. +// ELF isObjectActive 0x4789D0, executeObjectMethod 0x478D40, +// setArgFromString 0x478B00, getReturnValueAsString 0x478760, D1 0x478740, D0 0x478700. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::getMaxDepthInTree() const (slot +0x14 at 0x478DA8; ledger done) +// argc 1: dice::hfe::ai::AIPathfinding::MapContainer::setMaxDepthInTree(int) (slot +0x18 at 0x478D90; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass507 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.maxDepthInTree", 1, 0, 1, "int", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveMapContainer()->getMaxDepthInTree(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveMapContainer()->setMaxDepthInTree(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject507; + +// ConsoleClass509 AIPathFinding.map.addVehicleForClusterCost: method, 1..1 arguments, no result. +// ELF isObjectActive 0x478E60, executeObjectMethod 0x479210, +// setArgFromString 0x478F90, getReturnValueAsString 0x478E20, D1 0x478E00, D0 0x478DC0. +// argc 1: dice::hfe::ai::AIPathfinding::MapContainer::addVehicleForClusterCost(std::string const&) (slot +0x70 at 0x47926C; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass509 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.addVehicleForClusterCost", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveMapContainer()->addVehicleForClusterCost(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject509; + +// ConsoleClass510 AIPathFinding.map.draw: method, 0..0 arguments, no result. +// ELF isObjectActive 0x479340, executeObjectMethod 0x479480, +// setArgFromString 0x479470, getReturnValueAsString 0x479300, D1 0x4792E0, D0 0x4792A0. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::draw() const (slot +0x3C at 0x4794B8; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass510 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.draw", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + getActiveMapContainer()->draw(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject510; + +// ConsoleClass511 AIPathFinding.map.undraw: method, 0..0 arguments, no result. +// ELF isObjectActive 0x479560, executeObjectMethod 0x4796A0, +// setArgFromString 0x479690, getReturnValueAsString 0x479520, D1 0x479500, D0 0x4794C0. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::undraw() const (slot +0x40 at 0x4796D8; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass511 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.undraw", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + getActiveMapContainer()->undraw(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject511; + +// ConsoleClass512 AIPathFinding.map.drawCluster: method, 0..0 arguments, no result. +// ELF isObjectActive 0x479780, executeObjectMethod 0x4798C0, +// setArgFromString 0x4798B0, getReturnValueAsString 0x479740, D1 0x479720, D0 0x4796E0. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::drawCluster() const (slot +0x44 at 0x4798F8; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass512 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.drawCluster", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + getActiveMapContainer()->drawCluster(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject512; + +// ConsoleClass513 AIPathFinding.map.undrawCluster: method, 0..0 arguments, no result. +// ELF isObjectActive 0x4799A0, executeObjectMethod 0x479AE0, +// setArgFromString 0x479AD0, getReturnValueAsString 0x479960, D1 0x479940, D0 0x479900. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::undrawCluster() const (slot +0x48 at 0x479B18; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass513 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.undrawCluster", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + getActiveMapContainer()->undrawCluster(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject513; + +// ConsoleClass514 AIPathFinding.map.drawClusterNeighbourIndices: method, 1..1 arguments, no result. +// ELF isObjectActive 0x479BC0, executeObjectMethod 0x479FD0, +// setArgFromString 0x479CF0, getReturnValueAsString 0x479B80, D1 0x479B60, D0 0x479B20. +// argc 1: dice::hfe::ai::AIPathfinding::MapContainer::drawClusterNeighbourIndices(dice::hfe::Vec3 const&) const (slot +0x4C at 0x47A02E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass514 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.drawClusterNeighbourIndices", 0, 1, 1, "void", false) + m_argTypes[0] = "Vec3"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveMapContainer()->drawClusterNeighbourIndices(BF2_CC_ARG(Vec3, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(Vec3, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject514; + +// ConsoleClass516 AIPathFinding.map.buildDebugMeshes: method, 0..0 arguments, no result. +// ELF isObjectActive 0x47A0E0, executeObjectMethod 0x47A220, +// setArgFromString 0x47A210, getReturnValueAsString 0x47A0A0, D1 0x47A080, D0 0x47A040. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::buildDebugMeshes() (slot +0x54 at 0x47A258; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass516 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.buildDebugMeshes", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + getActiveMapContainer()->buildDebugMeshes(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject516; + +// ConsoleClass517 AIPathFinding.map.buildDebugClusterMeshes: method, 0..0 arguments, no result. +// ELF isObjectActive 0x47A300, executeObjectMethod 0x47A440, +// setArgFromString 0x47A430, getReturnValueAsString 0x47A2C0, D1 0x47A2A0, D0 0x47A260. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::buildDebugClusterMeshes() (slot +0x5C at 0x47A478; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass517 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.buildDebugClusterMeshes", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + getActiveMapContainer()->buildDebugClusterMeshes(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject517; + +// ConsoleClass518 AIPathFinding.map.loadGTSDebugMeshes: method, 0..0 arguments, no result. +// ELF isObjectActive 0x47A520, executeObjectMethod 0x47A660, +// setArgFromString 0x47A650, getReturnValueAsString 0x47A4E0, D1 0x47A4C0, D0 0x47A480. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::loadGTSDebugMeshes() (slot +0x50 at 0x47A698; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass518 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.loadGTSDebugMeshes", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + getActiveMapContainer()->loadGTSDebugMeshes(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject518; + +// ConsoleClass519 AIPathFinding.map.unloadDebugMeshes: method, 0..0 arguments, no result. +// ELF isObjectActive 0x47A740, executeObjectMethod 0x47A880, +// setArgFromString 0x47A870, getReturnValueAsString 0x47A700, D1 0x47A6E0, D0 0x47A6A0. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::unloadDebugMeshes() (slot +0x58 at 0x47A8B8; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass519 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.unloadDebugMeshes", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + getActiveMapContainer()->unloadDebugMeshes(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject519; + +// ConsoleClass520 AIPathFinding.map.unloadDebugClusterMeshes: method, 0..0 arguments, no result. +// ELF isObjectActive 0x47A960, executeObjectMethod 0x47AAA0, +// setArgFromString 0x47AA90, getReturnValueAsString 0x47A920, D1 0x47A900, D0 0x47A8C0. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::unloadDebugClusterMeshes() (slot +0x60 at 0x47AAD8; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass520 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.unloadDebugClusterMeshes", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + getActiveMapContainer()->unloadDebugClusterMeshes(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject520; + +// ConsoleClass521 AIPathFinding.map.recalculatePortalCosts: method, 0..0 arguments, no result. +// ELF isObjectActive 0x47AB80, executeObjectMethod 0x47ACC0, +// setArgFromString 0x47ACB0, getReturnValueAsString 0x47AB40, D1 0x47AB20, D0 0x47AAE0. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::recalculatePortalCosts() (slot +0x74 at 0x47ACF8; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass521 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.recalculatePortalCosts", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + getActiveMapContainer()->recalculatePortalCosts(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject521; + +// ConsoleClass524 AIPathFinding.map.loadQuadTrees: method, 0..0 arguments, no result. +// ELF isObjectActive 0x47ADA0, executeObjectMethod 0x47AEE0, +// setArgFromString 0x47AED0, getReturnValueAsString 0x47AD60, D1 0x47AD40, D0 0x47AD00. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::loadQuadTrees() (slot +0x68 at 0x47AF18; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass524 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.loadQuadTrees", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + getActiveMapContainer()->loadQuadTrees(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject524; + +// ConsoleClass525 AIPathFinding.saveQuadTrees: method, 0..0 arguments, no result. +// ELF isObjectActive 0x47AFC0, executeObjectMethod 0x47B0F0, +// setArgFromString 0x47B0E0, getReturnValueAsString 0x47AF80, D1 0x47AF60, D0 0x47AF20. +// argc 0: dice::hfe::ai::AIPathfinding::saveQuadTrees() (slot +0x28 at 0x47B12B; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass525 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("saveQuadTrees", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IAIPathfindingSetup::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + IAIPathfindingSetup::instance->saveQuadTrees(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject525; + +// ConsoleClass526 AIPathFinding.loadQuadTrees: method, 0..0 arguments, no result. +// ELF isObjectActive 0x47B1D0, executeObjectMethod 0x47B300, +// setArgFromString 0x47B2F0, getReturnValueAsString 0x47B190, D1 0x47B170, D0 0x47B130. +// argc 0: dice::hfe::ai::AIPathfinding::loadQuadTrees() (slot +0x2C at 0x47B33B; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass526 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("loadQuadTrees", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IAIPathfindingSetup::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + IAIPathfindingSetup::instance->loadQuadTrees(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject526; + +// ConsoleClass527 AIPathFinding.loadGTSData: method, 0..0 arguments, no result. +// ELF isObjectActive 0x47B3E0, executeObjectMethod 0x47B510, +// setArgFromString 0x47B500, getReturnValueAsString 0x47B3A0, D1 0x47B380, D0 0x47B340. +// argc 0: dice::hfe::ai::AIPathfinding::loadGTSData() (slot +0x30 at 0x47B54B; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass527 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("loadGTSData", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IAIPathfindingSetup::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + IAIPathfindingSetup::instance->loadGTSData(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject527; + +// ConsoleClass528 AIPathFinding.exportGTSMeshes: method, 0..0 arguments, returns bool. +// ELF isObjectActive 0x47B7F0, executeObjectMethod 0x47B920, +// setArgFromString 0x47B910, getReturnValueAsString 0x47B5B0, D1 0x47B590, D0 0x47B550. +// argc 0: dice::hfe::ai::AIPathfinding::exportGTSMeshes() const (slot +0x34 at 0x47B955; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass528 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("exportGTSMeshes", 0, 0, 0, "bool", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IAIPathfindingSetup::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IAIPathfindingSetup::instance->exportGTSMeshes(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject528; + +// ConsoleClass529 AIPathFinding.exportGTSMeshesWithinBoundary: method, 2..2 arguments, returns bool. +// ELF isObjectActive 0x47BC20, executeObjectMethod 0x47C280, +// setArgFromString 0x47BD40, getReturnValueAsString 0x47B9E0, D1 0x47B9C0, D0 0x47B980. +// argc 2: dice::hfe::ai::AIPathfinding::exportGTSMeshesWithinBoundary(dice::hfe::Vec2 const&, dice::hfe::Vec2 const&) const (slot +0x38 at 0x47C2E1; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass529 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("exportGTSMeshesWithinBoundary", 0, 2, 2, "bool", true) + m_argTypes[0] = "Vec2"; + m_argTypes[1] = "Vec2"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return IAIPathfindingSetup::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = true; + m_returnValue = IAIPathfindingSetup::instance->exportGTSMeshesWithinBoundary(BF2_CC_ARG(Vec2, 0), BF2_CC_ARG(Vec2, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(Vec2, 1) + AIMODULE_CC_EXTRACT(Vec2, 2) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject529; + +// ConsoleClass530 AIPathFinding.maxWaterDepth: property, 0..1 arguments, returns float. +// ELF isObjectActive 0x47C5B0, executeObjectMethod 0x47C910, +// setArgFromString 0x47C6D0, getReturnValueAsString 0x47C370, D1 0x47C350, D0 0x47C310. +// argc 0: dice::hfe::ai::AIPathfinding::getMaxWaterDepth() const (slot +0x44 at 0x47C978; ledger done) +// argc 1: dice::hfe::ai::AIPathfinding::setMaxWaterDepth(float) (slot +0x40 at 0x47C95D; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass530 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("maxWaterDepth", 1, 0, 1, "float", true) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return IAIPathfindingSetup::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IAIPathfindingSetup::instance->getMaxWaterDepth(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + IAIPathfindingSetup::instance->setMaxWaterDepth(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject530; + +// ConsoleClass531 AIPathFinding.drawDynamicAIObjects: method, 0..0 arguments, no result. +// ELF isObjectActive 0x47CA30, executeObjectMethod 0x47CB60, +// setArgFromString 0x47CB50, getReturnValueAsString 0x47C9F0, D1 0x47C9D0, D0 0x47C990. +// argc 0: dice::hfe::ai::AIPathfinding::drawDynamicAIObjects() const (slot +0x48 at 0x47CB9B; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass531 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("drawDynamicAIObjects", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IAIPathfindingSetup::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + IAIPathfindingSetup::instance->drawDynamicAIObjects(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject531; + +SetConsoleClassDefaults AIDebugfullAccessSetConsoleClassDefaults("AIDebug", 2, 0); + +// ConsoleClass537 AIDebug.textGamma: property, 0..1 arguments, returns float. +// ELF isObjectActive 0x47CE40, executeObjectMethod 0x47D1A0, +// setArgFromString 0x47CF60, getReturnValueAsString 0x47CC00, D1 0x47CBE0, D0 0x47CBA0. +// argc 0: dice::hfe::ai::DPManager::getTextGamma() const (slot +0x58 at 0x47D208; ledger done) +// argc 1: dice::hfe::ai::DPManager::setTextGamma(float) (slot +0x54 at 0x47D1ED; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass537 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("textGamma", 1, 0, 1, "float", true) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iDPManager) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = static_cast(CommonSingletonServer::m_iDPManager)->getTextGamma(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iDPManager)->setTextGamma(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject537; + +// ConsoleClass538 AIDebug.draw: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x47D4C0, executeObjectMethod 0x47D820, +// setArgFromString 0x47D5E0, getReturnValueAsString 0x47D280, D1 0x47D260, D0 0x47D220. +// argc 0: dice::hfe::ai::AISettings::getDraw() const (slot +0x80 at 0x47D894; ledger done) +// argc 1: dice::hfe::ai::AISettings::setDraw(bool) (slot +0x138 at 0x47D875; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass538 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("draw", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettings) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = static_cast(CommonSingletonServer::m_iaiSettings)->getDraw(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(static_cast(CommonSingletonServer::m_iaiSettings))->setDraw(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject538; + +// ConsoleClass539 AIDebug.ToolPathfinding: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x47DB50, executeObjectMethod 0x47DEB0, +// setArgFromString 0x47DC70, getReturnValueAsString 0x47D910, D1 0x47D8F0, D0 0x47D8B0. +// argc 0: dice::hfe::ai::AIPathfinding::getActivatePathfindingDebugTool() const (slot +0x108 at 0x47DF24; ledger done) +// argc 1: dice::hfe::ai::AIPathfinding::setActivatePathfindingDebugTool(bool) (slot +0x104 at 0x47DF05; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass539 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("ToolPathfinding", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return IAIPathfinding::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IAIPathfinding::instance->getActivatePathfindingDebugTool(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + IAIPathfinding::instance->setActivatePathfindingDebugTool(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject539; + +// ConsoleClass540 AIDebug.pathfindingDebugToolVehicle: property, 0..1 arguments, returns std::string. +// ELF isObjectActive 0x47E260, executeObjectMethod 0x47E600, +// setArgFromString 0x47E380, getReturnValueAsString 0x47E020, D1 0x47DFB0, D0 0x47DF40. +// argc 0: dice::hfe::ai::AIPathfinding::getPathfindingDebugToolVehicle() const (slot +0x110 at 0x47E6AA; ledger done) +// argc 1: dice::hfe::ai::AIPathfinding::setPathfindingDebugToolVehicle(std::string const&) (slot +0x10C at 0x47E663; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass540 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("pathfindingDebugToolVehicle", 1, 0, 1, "std::string", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return IAIPathfinding::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IAIPathfinding::instance->getPathfindingDebugToolVehicle(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + IAIPathfinding::instance->setPathfindingDebugToolVehicle(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject540; + +// ConsoleClass541 AIDebug.clusterSearch: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x47E970, executeObjectMethod 0x47ECD0, +// setArgFromString 0x47EA90, getReturnValueAsString 0x47E730, D1 0x47E710, D0 0x47E6D0. +// argc 0: dice::hfe::ai::AIPathfinding::getClusterSearch() const (slot +0x100 at 0x47ED44; ledger done) +// argc 1: dice::hfe::ai::AIPathfinding::setClusterSearch(bool) (slot +0xFC at 0x47ED25; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass541 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("clusterSearch", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return IAIPathfinding::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IAIPathfinding::instance->getClusterSearch(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + IAIPathfinding::instance->setClusterSearch(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject541; + +// ConsoleClass542 AIDebug.setPathfindingDebugToolVehicleId: method, 1..1 arguments, no result. +// ELF isObjectActive 0x47EE00, executeObjectMethod 0x47F160, +// setArgFromString 0x47EF20, getReturnValueAsString 0x47EDC0, D1 0x47EDA0, D0 0x47ED60. +// argc 1: dice::hfe::ai::AIPathfinding::setPathfindingDebugToolVehicleId(int) (slot +0x114 at 0x47F1A3; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass542 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setPathfindingDebugToolVehicleId", 0, 1, 1, "void", false) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return IAIPathfinding::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + IAIPathfinding::instance->setPathfindingDebugToolVehicleId(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject542; + +// ConsoleClass543 AIDebug.tryPath: method, 2..2 arguments, no result. +// ELF isObjectActive 0x47F250, executeObjectMethod 0x47F930, +// setArgFromString 0x47F370, getReturnValueAsString 0x47F210, D1 0x47F1F0, D0 0x47F1B0. +// argc 2: dice::hfe::ai::AIPathfinding::tryPath(dice::hfe::Vec3 const&, dice::hfe::Vec3 const&) (slot +0xF4 at 0x47F9B2; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass543 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("tryPath", 0, 2, 2, "void", false) + m_argTypes[0] = "Vec3"; + m_argTypes[1] = "Vec3"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return IAIPathfinding::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + IAIPathfinding::instance->tryPath(BF2_CC_ARG(Vec3, 0), BF2_CC_ARG(Vec3, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(Vec3, 1) + AIMODULE_CC_EXTRACT(Vec3, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject543; + +// ConsoleClass544 AIDebug.tryClusterPath: method, 2..2 arguments, no result. +// ELF isObjectActive 0x47FA60, executeObjectMethod 0x480140, +// setArgFromString 0x47FB80, getReturnValueAsString 0x47FA20, D1 0x47FA00, D0 0x47F9C0. +// argc 2: dice::hfe::ai::AIPathfinding::tryClusterPath(dice::hfe::Vec3 const&, dice::hfe::Vec3 const&) (slot +0xF8 at 0x4801C2; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass544 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("tryClusterPath", 0, 2, 2, "void", false) + m_argTypes[0] = "Vec3"; + m_argTypes[1] = "Vec3"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return IAIPathfinding::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + IAIPathfinding::instance->tryClusterPath(BF2_CC_ARG(Vec3, 0), BF2_CC_ARG(Vec3, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(Vec3, 1) + AIMODULE_CC_EXTRACT(Vec3, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject544; + +SetConsoleClassDefaults AIOrderfullAccessSetConsoleClassDefaults("AIOrder", 2, 0); + +// ConsoleClass551 AIOrder.createPatrolPath: method, 3..3 arguments, no result. +// ELF isObjectActive 0x480270, executeObjectMethod 0x480A50, +// setArgFromString 0x480390, getReturnValueAsString 0x480230, D1 0x480210, D0 0x4801D0. +// argc 3: dice::hfe::ai::UserOrderManager::createPatrolPath(std::string const&, dice::hfe::ai::CombatStrengthType, int) (call at 0x480ABF; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass551 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createPatrolPath", 0, 3, 3, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "CombatStrengthType"; + m_argTypes[2] = "int"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return UserOrderManager::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = false; + UserOrderManager::m_instance->createPatrolPath(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(CombatStrengthType, 1), BF2_CC_ARG(int, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT_WITH(CombatStrengthType, 2, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT(int, 3) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject551; + +// ConsoleClass553 AIOrder.addPathPoint: method, 1..1 arguments, no result. +// ELF isObjectActive 0x480B90, executeObjectMethod 0x480F60, +// setArgFromString 0x480CC0, getReturnValueAsString 0x480B50, D1 0x480B30, D0 0x480AF0. +// argc 1: dice::hfe::ai::PatrolPath::addPathPoint(dice::hfe::Vec2 const&) (call at 0x480FB4; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass553 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addPathPoint", 0, 1, 1, "void", false) + m_argTypes[0] = "Vec2"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActivePatrolPathIfManager() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + getActivePatrolPathIfManager()->addPathPoint(BF2_CC_ARG(Vec2, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(Vec2, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject553; + +// ConsoleClass554 AIOrder.requiredResources: property, 0..1 arguments, returns int. +// ELF isObjectActive 0x481290, executeObjectMethod 0x481600, +// setArgFromString 0x4813C0, getReturnValueAsString 0x481020, D1 0x481000, D0 0x480FC0. +// argc 0: dice::hfe::ai::PatrolPath::getRequiredResources() const (call at 0x481666; ledger done) +// argc 1: dice::hfe::ai::PatrolPath::setRequiredResources(int) (call at 0x48164E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass554 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("requiredResources", 1, 0, 1, "int", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActivePatrolPathIfManager() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActivePatrolPathIfManager()->getRequiredResources(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActivePatrolPathIfManager()->setRequiredResources(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject554; + +// ConsoleClass555 AIOrder.minDistance: property, 0..1 arguments, returns float. +// ELF isObjectActive 0x481920, executeObjectMethod 0x481C90, +// setArgFromString 0x481A50, getReturnValueAsString 0x4816E0, D1 0x4816C0, D0 0x481680. +// argc 0: dice::hfe::ai::PatrolPath::getMinDistance() const (call at 0x481CF6; ledger done) +// argc 1: dice::hfe::ai::PatrolPath::setMinDistance(float) (call at 0x481CDE; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass555 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("minDistance", 1, 0, 1, "float", true) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActivePatrolPathIfManager() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActivePatrolPathIfManager()->getMinDistance(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActivePatrolPathIfManager()->setMinDistance(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject555; + +// ConsoleClass556 AIOrder.patrolSpeed: property, 0..1 arguments, returns float. +// ELF isObjectActive 0x481FB0, executeObjectMethod 0x482320, +// setArgFromString 0x4820E0, getReturnValueAsString 0x481D70, D1 0x481D50, D0 0x481D10. +// argc 0: dice::hfe::ai::PatrolPath::getPatrolSpeed() const (call at 0x482386; ledger done) +// argc 1: dice::hfe::ai::PatrolPath::setPatrolSpeed(float) (call at 0x48236E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass556 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("patrolSpeed", 1, 0, 1, "float", true) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActivePatrolPathIfManager() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActivePatrolPathIfManager()->getPatrolSpeed(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActivePatrolPathIfManager()->setPatrolSpeed(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject556; + +// ConsoleClass559 AIOrder.createGuardPosition: method, 5..5 arguments, no result. +// ELF isObjectActive 0x482440, executeObjectMethod 0x483100, +// setArgFromString 0x482560, getReturnValueAsString 0x482400, D1 0x4823E0, D0 0x4823A0. +// argc 5: dice::hfe::ai::UserOrderManager::createGuardPosition(std::string const&, dice::hfe::Vec2 const&, dice::hfe::ai::CombatStrengthType, int, int) (call at 0x483199; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass559 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createGuardPosition", 0, 5, 5, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "Vec2"; + m_argTypes[2] = "CombatStrengthType"; + m_argTypes[3] = "int"; + m_argTypes[4] = "int"; + AIMODULE_CC_TAIL(5) + virtual bool isObjectActive() const { return UserOrderManager::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 5) + { + m_hasReturnValue = false; + UserOrderManager::m_instance->createGuardPosition(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(Vec2, 1), BF2_CC_ARG(CombatStrengthType, 2), BF2_CC_ARG(int, 3), BF2_CC_ARG(int, 4)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(Vec2, 2) + AIMODULE_CC_EXTRACT_WITH(CombatStrengthType, 3, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT(int, 4) + AIMODULE_CC_EXTRACT(int, 5) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject559; + +// ConsoleClass560 AIOrder.minDistance: property, 0..1 arguments, returns float. +// ELF isObjectActive 0x483470, executeObjectMethod 0x4837E0, +// setArgFromString 0x4835A0, getReturnValueAsString 0x483230, D1 0x483210, D0 0x4831D0. +// argc 0: dice::hfe::ai::GuardPosition::getMinDistance() const (call at 0x483846; ledger done) +// argc 1: dice::hfe::ai::GuardPosition::setMinDistance(float) (call at 0x48382E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass560 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("minDistance", 1, 0, 1, "float", true) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveGuardPositionIfManager() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveGuardPositionIfManager()->getMinDistance(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveGuardPositionIfManager()->setMinDistance(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject560; + +// ConsoleClass561 AIOrder.rotation: property, 0..1 arguments, returns Vec3. +// ELF isObjectActive 0x483B60, executeObjectMethod 0x483F70, +// setArgFromString 0x483C90, getReturnValueAsString 0x4838C0, D1 0x4838A0, D0 0x483860. +// argc 0: dice::hfe::ai::GuardPosition::getRotation() const (call at 0x483FF5; ledger done) +// argc 1: dice::hfe::ai::GuardPosition::setRotation(dice::hfe::Vec3 const&) (call at 0x483FD0; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass561 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("rotation", 1, 0, 1, "Vec3", true) + m_argTypes[0] = "Vec3"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveGuardPositionIfManager() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveGuardPositionIfManager()->getRotation(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveGuardPositionIfManager()->setRotation(BF2_CC_ARG(Vec3, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(Vec3, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + Vec3 m_returnValue; +}; +BF2_CC_NAME consoleObject561; + +// ConsoleClass562 AIOrder.addStrategicAreaAbortCondition: method, 2..2 arguments, no result. +// ELF isObjectActive 0x4840C0, executeObjectMethod 0x4846A0, +// setArgFromString 0x4841F0, getReturnValueAsString 0x484080, D1 0x484060, D0 0x484020. +// argc 2: dice::hfe::ai::GuardPosition::addStrategicAreaAbortCondition(std::string const&, dice::hfe::ai::StatusMap::Status) (call at 0x484709; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass562 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addStrategicAreaAbortCondition", 0, 2, 2, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "StatusMap::Status"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return getActiveGuardPositionIfManager() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + getActiveGuardPositionIfManager()->addStrategicAreaAbortCondition(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(StatusMap::Status, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT_WITH(StatusMap::Status, 2, dice::hfe::ai::operator>>) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject562; + +SetConsoleClassDefaults AICoverfullAccessSetConsoleClassDefaults("AICover", 2, 0); + +// ConsoleClass569 AICover.createCoverPosition: method, 2..2 arguments, no result. +// ELF isObjectActive 0x4847D0, executeObjectMethod 0x484E30, +// setArgFromString 0x4848F0, getReturnValueAsString 0x484790, D1 0x484770, D0 0x484730. +// argc 2: dice::hfe::ai::CoverPositionManager::createCoverPosition(dice::hfe::Vec2 const&, dice::hfe::Vec2 const&) (call at 0x484E9E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass569 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createCoverPosition", 0, 2, 2, "void", false) + m_argTypes[0] = "Vec2"; + m_argTypes[1] = "Vec2"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return CoverPositionManager::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + CoverPositionManager::m_instance->createCoverPosition(BF2_CC_ARG(Vec2, 0), BF2_CC_ARG(Vec2, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(Vec2, 1) + AIMODULE_CC_EXTRACT(Vec2, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject569; + +// ConsoleClass570 AICover.finaliseCoverPositions: method, 0..0 arguments, no result. +// ELF isObjectActive 0x484F50, executeObjectMethod 0x485080, +// setArgFromString 0x485070, getReturnValueAsString 0x484F10, D1 0x484EF0, D0 0x484EB0. +// argc 0: dice::hfe::ai::CoverPositionManager::finaliseCoverPositions() (call at 0x4850B9; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass570 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("finaliseCoverPositions", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return CoverPositionManager::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + CoverPositionManager::m_instance->finaliseCoverPositions(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject570; + +// ConsoleClass571 AICover.search: method, 2..2 arguments, returns bool. +// ELF isObjectActive 0x485360, executeObjectMethod 0x485900, +// setArgFromString 0x485480, getReturnValueAsString 0x485120, D1 0x485100, D0 0x4850C0. +// argc 2: dice::hfe::ai::CoverPositionManager::search(int, int) (call at 0x485944; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass571 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("search", 0, 2, 2, "bool", true) + m_argTypes[0] = "int"; + m_argTypes[1] = "int"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return CoverPositionManager::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = true; + m_returnValue = CoverPositionManager::m_instance->search(BF2_CC_ARG(int, 0), BF2_CC_ARG(int, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + AIMODULE_CC_EXTRACT(int, 2) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject571; + +SetConsoleClassDefaults AIRandomfullAccessSetConsoleClassDefaults("AIRandom", 2, 0); + +// ConsoleClass576 AIRandom.seed: property, 0..1 arguments, returns u32. +// ELF isObjectActive 0x485C10, executeObjectMethod 0x485F70, +// setArgFromString 0x485D30, getReturnValueAsString 0x4859D0, D1 0x4859B0, D0 0x485970. +// argc 0: verified inline body, seed word at offset zero of a non-polymorphic receiver +// argc 1: verified inline body, seed word at offset zero of a non-polymorphic receiver +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass576 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("seed", 1, 0, 1, "u32", true) + m_argTypes[0] = "u32"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIRandom::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIRandom::m_instance->m_seed; + } + else if (m_argCount == 1) + { + const u32 value = BF2_CC_ARG(u32, 0); + m_hasReturnValue = false; + AIRandom::m_instance->m_seed = value; + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(u32, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + u32 m_returnValue; +}; +BF2_CC_NAME consoleObject576; + +#undef AIMODULE_CC_TAIL +#undef AIMODULE_CC_EXTRACT_WITH +#undef AIMODULE_CC_EXTRACT +#pragma pop_macro("BF2_CC_NAME") diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIPathfinding.cpp b/Code/BF2/AI/AIDLL/AI/Main/AIPathfinding.cpp index bc0df3c76..1daf04d88 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIPathfinding.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/AIPathfinding.cpp @@ -1,21 +1,34 @@ -// [FRONTIER] Remaining methods stop by name until implemented. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining AIPathfinding operations. +// Navigation searches, map lifecycle and offline GTS export. + +// static init: ELF 0x3AE2B0 (__tcf_0 0x3AE310, _GLOBAL__I 0x3AE340): 's Init object only. +#include #include "AIPathfinding.h" #include // std::remove - deleteMap uses the erase-remove idiom +#include // traceKnown's line length #include - +#include +#include "../../../../Core/Debug.h" +#include "../../../../IO/File/File.h" +#include "../../../../IO/File/FileManager.h" + +#include "../../../AIInterface/BFKnowledge/BFGame.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" +#include "../AIUtils/DebugRendering/AIRenderUtil.h" +#include "../DrawPrimitives/DPManager.h" +#include "../AIPathFinding/NavMesh/MeshImporterExporter.h" +#include "../AIBot/BotNavigation.h" // trace(BotNavigation*): getMapIndex +#include "../AIPathFinding/Cluster/ClusterGraph.h" // areNeighbours, updatePortalCosts #include "../AIPathFinding/Cluster/ClusterNodeManager.h" // init builds one per cluster search +#include "../AIPathFinding/Material/MaterialManager.h" // traceKnown: isValidMaterial #include "../AIPathFinding/NavMesh/QuadTree.h" // MapContainer polygon vertex query #include "../AIPathFinding/NavMesh/QTSearchNodeManager.h" // init builds one per local search #include "../AIStrategicEntity/AIStrategicObjectManager.h" // loadQuadTrees' tail calls initAreas #include "../AIUtils/checkPointer.h" -#include "AIDllFrontier.h" -#include "AIMineManager.h" // loadQuadTrees / loadGTSData call IAIMineManager::init +#include "../AIKnowledge/AIMineManager.h" // loadQuadTrees / loadGTSData call IAIMineManager::init #include "AISettingsInterfaces.h" // IAISettings::getVehicle / getVehicleMaterialManager #include "CommonSingletonServer.h" -#include "../../../../Core/ConsoleObjectMacro.h" // the aiPathfinding.* bindings at the foot namespace dice { namespace hfe { @@ -33,12 +46,14 @@ typedef AStarResource ClusterResource; + // Allocates the pathfinding engines, search resources and debug paths. +// ELF 0x3A1DC0, 0x3A2630 (compiler-emitted variants). AIPathfinding::AIPathfinding() : m_activatePathfindingDebugTool(false) , m_pathfindingDebugToolVehicleId(0) , m_searchPointToSet(0) - , m_debugPath(0) + , m_path(0) , m_debugClusterPath(0) , m_d36(-1000.0) , m_clusterSearch(false) @@ -50,8 +65,8 @@ AIPathfinding::AIPathfinding() , m_maxWaterDepth(0.5f) , m_locking(false) { - m_debugPath = new QTPath(); - checkPointer(m_debugPath); + m_path = new QTPath(); + checkPointer(m_path); m_debugClusterPath = new ClusterNodePath(); checkPointer(m_debugClusterPath); @@ -73,13 +88,14 @@ AIPathfinding::AIPathfinding() // Resets debug paths before deleting engines, paths, maps, and search points. // Preserves the explicit null check before each map deletion. +// ELF 0x3A2EA0, 0x3A3060, 0x3A3220 (compiler-emitted variants). AIPathfinding::~AIPathfinding() { reset(); delete m_engine; delete m_clusterEngine; - delete m_debugPath; + delete m_path; delete m_debugClusterPath; delete m_searchPoint[0]; delete m_searchPoint[1]; @@ -92,15 +108,16 @@ AIPathfinding::~AIPathfinding() } // Resets pathfinding debug state. Loaded maps and in-flight searches remain active. +// ELF 0x3A4120. int AIPathfinding::reset() { m_activatePathfindingDebugTool = false; m_d36 = -1000.0; m_searchPointToSet = 0; - m_debugPath->m_nodes.resize(0); - m_debugPath->m_i0 = 0; - m_debugPath->m_i20 = 0; + m_path->m_nodes.resize(0); + m_path->m_i0 = 0; + m_path->m_i20 = 0; m_debugClusterPath->m_nodes.resize(0); m_debugClusterPath->m_i0 = 0; @@ -111,21 +128,25 @@ int AIPathfinding::reset() // Requests a cooperative pause. Poll isLockComplete() until both search pools are idle. // This is not a thread synchronization primitive. +// ELF 0x3A4260. void AIPathfinding::lock() { m_locking = true; } +// ELF 0x3A4270. void AIPathfinding::unlock() { m_locking = false; } +// ELF 0x3A4280. bool AIPathfinding::isLocking() const { return m_locking; } +// ELF 0x3A4290. bool AIPathfinding::isLockComplete() const { if (m_engine->m_inFlight.size() != 0) @@ -136,11 +157,13 @@ bool AIPathfinding::isLockComplete() const } // Map-name lookup is case-insensitive. Negative stored IDs are treated as missing. +// ELF 0x3A7350. int AIPathfinding::getNumberOfMaps() const { return static_cast(m_maps.size()); } +// ELF 0x3A7370. bool AIPathfinding::isMapUsed(int id) const { if (id < 0) @@ -150,6 +173,7 @@ bool AIPathfinding::isMapUsed(int id) const // Returns the stored map name directly for a nonnegative id; the caller must ensure // it is below the map count. Negative ids use the fallback name. +// ELF 0x3A7280. const std::string& AIPathfinding::getMapNameFromId(int id) const { if (id >= 0) @@ -159,6 +183,7 @@ const std::string& AIPathfinding::getMapNameFromId(int id) const return m_returnedName; } +// ELF 0x3A72F0. int AIPathfinding::getMapIdFromName(const std::string& name) const { const std::map::const_iterator i = m_mapIds.find(name); @@ -167,6 +192,7 @@ int AIPathfinding::getMapIdFromName(const std::string& name) const return i->second; } +// ELF 0x3A6CD0. void AIPathfinding::setActiveMap(const std::string& name) { const std::map::const_iterator i = m_mapIds.find(name); @@ -176,6 +202,7 @@ void AIPathfinding::setActiveMap(const std::string& name) m_activeMap = m_maps[i->second]; } +// ELF 0x3A6D40. const std::string& AIPathfinding::getActiveMap() const { if (m_activeMap) @@ -186,6 +213,7 @@ const std::string& AIPathfinding::getActiveMap() const } // 666 is the "NO TRACE MAP" sentinel, not -1, and it is written here on every miss. +// ELF 0x3A6DB0. void AIPathfinding::setTraceMap(const std::string& name) { const std::map::const_iterator i = m_mapIds.find(name); @@ -197,6 +225,7 @@ void AIPathfinding::setTraceMap(const std::string& name) // the literal has no space before its closing star - "* NO ACTIVE TRACE MAP*" - unlike its // neighbour above. Copied exactly; it is a shipped string a console user can see. +// ELF 0x3A6E10. const std::string& AIPathfinding::getTraceMap() const { if (m_traceMapIndex == -666) @@ -207,11 +236,13 @@ const std::string& AIPathfinding::getTraceMap() const return m_maps[m_traceMapIndex]->getName(); } +// ELF 0x3B1CB0. int AIPathfinding::getTraceMapIndex() const { return m_traceMapIndex; } +// ELF 0x3A6E80. IAIPathfindingSetup::IMapContainer* AIPathfinding::getActiveMapContainer() const { return m_activeMap; @@ -219,6 +250,7 @@ IAIPathfindingSetup::IMapContainer* AIPathfinding::getActiveMapContainer() const // no bounds check and no guard - it walks whatever is in the list and calls the non-virtual // `MapContainer::init` on each. +// ELF 0x3A40D0. void AIPathfinding::initMaps() { for (std::vector::iterator i = m_maps.begin(); i != m_maps.end(); ++i) @@ -226,48 +258,57 @@ void AIPathfinding::initMaps() } // Debug vehicle selection uses the vehicle IDs and names in AI settings. +// ELF 0x3A6810. bool AIPathfinding::getActivatePathfindingDebugTool() const { return m_activatePathfindingDebugTool; } +// ELF 0x3A53A0. void AIPathfinding::setPathfindingDebugToolVehicle(const std::string& name) { IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); m_pathfindingDebugToolVehicleId = settings->getVehicle(name); } -void* AIPathfinding::getPathfindingDebugToolVehicle() const +// ELF 0x3A53E0. +const std::string& AIPathfinding::getPathfindingDebugToolVehicle() const { IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); - return const_cast(&settings->getVehicle(m_pathfindingDebugToolVehicleId)); + return settings->getVehicle(m_pathfindingDebugToolVehicleId); } +// ELF 0x3A5420. void AIPathfinding::setPathfindingDebugToolVehicleId(int id) { m_pathfindingDebugToolVehicleId = id; } +// ELF 0x3A5380. void AIPathfinding::setClusterSearch(bool on) { m_clusterSearch = on; } +// ELF 0x3A5390. bool AIPathfinding::getClusterSearch() const { return m_clusterSearch; } +// ELF 0x3A6710. int AIPathfinding::getSearchPointToSet() const { return m_searchPointToSet; } +// ELF 0x3A6720. QTPath* AIPathfinding::getDebugPath() const { - return m_debugPath; + return m_path; } +// ELF 0x3A6730. ClusterNodePath* AIPathfinding::getDebugClusterPath() const { return m_debugClusterPath; @@ -275,22 +316,26 @@ ClusterNodePath* AIPathfinding::getDebugClusterPath() const // unchecked, and the array has exactly two elements. `searchPointSelected` subscripts it with // `m_searchPointToSet`, which that function is careful to keep at 0 or 1; nothing here enforces it. +// ELF 0x3A6740. Vec3* AIPathfinding::getSearchPoint(int index) const { return m_searchPoint[index]; } +// ELF 0x3A09B0. void AIPathfinding::setMaxWaterDepth(float depth) { m_maxWaterDepth = depth; } +// ELF 0x3A09A0. float AIPathfinding::getMaxWaterDepth() const { return m_maxWaterDepth; } // Queries navigation using the selected map and vehicle-specific material rules. +// ELF 0x3A79D0. bool AIPathfinding::getPolygon(const Vec3& position, int map, unsigned int& polygon, unsigned int& quadTree, int vehicleId) const { @@ -303,6 +348,7 @@ bool AIPathfinding::getPolygon(const Vec3& position, int map, unsigned int& poly return m_maps[map]->getPolygon(position, polygon, quadTree, materials); } +// ELF 0x3A7B00. void AIPathfinding::getPolygonsInRadius(std::list& polygons, int map, unsigned int quadTree, unsigned int polygon, const Vec3& centre, float radius) const @@ -313,6 +359,7 @@ void AIPathfinding::getPolygonsInRadius(std::list& polygons, int m m_maps[map]->getPolygonsInRadius(polygons, quadTree, polygon, centre, radius); } +// ELF 0x3A7B70. void AIPathfinding::getPolygonsInTriangle(std::list& polygons, int map, unsigned int quadTree, unsigned int polygon, const Vec3& corner0, const Vec3& corner1, @@ -324,14 +371,15 @@ void AIPathfinding::getPolygonsInTriangle(std::list& polygons, int m_maps[map]->getPolygonsInTriangle(polygons, quadTree, polygon, corner0, corner1, corner2); } -// no bounds check - see the block above. -void AIPathfinding::setMaterial(int map, unsigned int quadTree, unsigned int polygon, +// no bounds check - see the block above. ELF 0x3A7D50 returns the container's result. +bool AIPathfinding::setMaterial(int map, unsigned int quadTree, unsigned int polygon, unsigned char material) const { - m_maps[map]->setMaterial(quadTree, polygon, material); + return m_maps[map]->setMaterial(quadTree, polygon, material); } // no bounds check. +// ELF 0x3A7D00. bool AIPathfinding::getMaterial(int map, unsigned int quadTree, unsigned int polygon, unsigned char& material) const { @@ -339,6 +387,7 @@ bool AIPathfinding::getMaterial(int map, unsigned int quadTree, unsigned int pol } // no bounds check, and it draws unconditionally in the shipped server build. +// ELF 0x3A7F30. void AIPathfinding::drawPolygon(int map, unsigned int quadTree, unsigned int polygon, float* colour, float duration) const { @@ -347,43 +396,184 @@ void AIPathfinding::drawPolygon(int map, unsigned int quadTree, unsigned int pol // Requires a valid map index. Validation checks the vehicle vector while cost lookup // indexes the other vector; the caller must also ensure that lookup index is valid. +// ELF 0x3AE200. bool AIPathfinding::isValidClusterType(int map, unsigned int type) const { return type < m_maps[map]->m_clusterCostVehicles.size(); } +// ELF 0x3A5E10. Acquires a search resource (owner 2000), empties the shared debug path and runs +// the portal-to-portal search with the vehicle of cluster cost type `costType`, updating the +// engine (10 ms budget) until it stops searching. Appends -1 when a polygon is missing or its +// material is invalid for that vehicle, or when the search fails. Retail quirk kept: a search +// that finds its path on the first call appends the straight distance times the first polygon's +// material cost, not the path cost; only a search that needed updates appends the path cost. +// Topology smoothing is switched on for every map but map 0. The resource is released last. +void AIPathfinding::getPortalCost(std::vector& costs, unsigned short costType, int map, + unsigned int island, const Vec3& from, + unsigned int fromPolygon, const Vec3& to, + unsigned int toPolygon, + const std::set& allowedClusters) +{ + unsigned int resource = 0xFFFFFFFFu; + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + QuadTree* const quadTree = m_maps[map]->m_quadTreeManager->getIsland(island); + acquireResource(resource, 2000); + + const int vehicleId = settings->getVehicle(m_maps[map]->m_clusterCostVehicles[costType]); + QTPath* const path = m_path; + path->m_nodes.resize(0); + path->m_i0 = 0; + path->m_i20 = 0.0f; + MaterialManager* const materials = settings->getVehicleMaterialManager(vehicleId); + + if (fromPolygon == 0xFFFFFFFFu || toPolygon == 0xFFFFFFFFu) + { + costs.push_back(-1.0f); + } + else + { + const unsigned char fromMaterial = quadTree->getMaterialOfPolygon(fromPolygon); + if (!materials->isValidMaterial(fromMaterial) + || !materials->isValidMaterial(quadTree->getMaterialOfPolygon(toPolygon))) + { + costs.push_back(-1.0f); + } + else + { + QTSearchNodeManager* const manager = m_engine->m_searches[resource]->m_nodeManager; + manager->m_allowedClusters = &allowedClusters; + if (map != 0) + manager->m_usePathTopologySmoothing = true; + + if (localSearch(resource, map, island, fromPolygon, from, toPolygon, to, vehicleId, + m_path) == astarStatus::kFound) + { + const float dx = to.x - from.x; + const float dy = to.y - from.y; + const float dz = to.z - from.z; + const float distance = std::sqrt(dx * dx + dy * dy + dz * dz); + costs.push_back(materials->getMaterialCost(fromMaterial) * distance); + } + else + { + while (m_engine->m_searches[resource]->m_status == astarStatus::kSearching) + m_engine->update(10.0f); + if (localSearch(resource, map, island, fromPolygon, from, toPolygon, to, + vehicleId, m_path) != astarStatus::kFound) + m_path->m_i20 = -1.0f; + costs.push_back(m_path->m_i20); + } + } + } + + releaseResource(resource, 2000); +} + +// ELF 0x3A63B0. Runs the portal-to-portal search on the shared debug path (m_path is +// emptied first: resize(0), step and cost zeroed) with the vehicle of cluster cost type +// `costType`. Both polygons must exist and carry a material valid for that vehicle, else the cost +// is -1 (true). The search is limited to `allowedClusters`; topology smoothing is switched on +// for every map but map 0 (retail tests the map index, nothing else). Search status 1 (still +// running) answers false; 2 (found) takes the path cost, or for a zero-cost path (both portals +// on one polygon) the straight distance times the first polygon's material cost; anything else +// is -1. All non-running outcomes answer true. +bool AIPathfinding::getPortalCost(float& cost, unsigned int resource, int map, unsigned int island, + unsigned short costType, const Vec3& from, + unsigned int fromPolygon, const Vec3& to, + unsigned int toPolygon, + const std::set& allowedClusters) +{ + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + QuadTree* const quadTree = m_maps[map]->m_quadTreeManager->getIsland(island); + + QTPath* const path = m_path; + path->m_nodes.resize(0); + path->m_i0 = 0; + path->m_i20 = 0.0f; + + const int vehicleId = settings->getVehicle(m_maps[map]->m_clusterCostVehicles[costType]); + MaterialManager* const materials = settings->getVehicleMaterialManager(vehicleId); + + if (fromPolygon == 0xFFFFFFFFu || toPolygon == 0xFFFFFFFFu) + { + cost = -1.0f; + return true; + } + const unsigned char fromMaterial = quadTree->getMaterialOfPolygon(fromPolygon); + if (!materials->isValidMaterial(fromMaterial) + || !materials->isValidMaterial(quadTree->getMaterialOfPolygon(toPolygon))) + { + cost = -1.0f; + return true; + } + + QTSearchNodeManager* const manager = m_engine->m_searches[resource]->m_nodeManager; + manager->m_allowedClusters = &allowedClusters; + if (map != 0) + manager->m_usePathTopologySmoothing = true; + + const int status = localSearch(resource, map, island, fromPolygon, from, toPolygon, to, + vehicleId, m_path); + if (status == astarStatus::kSearching) + return false; + if (status != astarStatus::kFound) + { + cost = -1.0f; + return true; + } + if (m_path->m_i20 == 0.0f) + { + const float dx = to.x - from.x; + const float dy = to.y - from.y; + const float dz = to.z - from.z; + cost = std::sqrt(dx * dx + dy * dy + dz * dz); + cost = materials->getMaterialCost(fromMaterial) * cost; + return true; + } + cost = m_path->m_i20; + return true; +} + +// ELF 0x3AE280. int AIPathfinding::getClusterCostType(int map, unsigned int type) const { return m_maps[map]->m_clusterCostTypes[type]; } // AIPathfinding::MapContainer - the trivial accessors. -const std::string& AIPathfinding::MapContainer::getName() +// ELF 0x3B1CC0. +const std::string& AIPathfinding::MapContainer::getName() const { return m_name; } -int AIPathfinding::MapContainer::getMinPolygonsInLeaf() +// ELF 0x3A08F0. +int AIPathfinding::MapContainer::getMinPolygonsInLeaf() const { return m_minPolygonsInLeaf; } +// ELF 0x3A0900. void AIPathfinding::MapContainer::setMinPolygonsInLeaf(int n) { m_minPolygonsInLeaf = n; } -int AIPathfinding::MapContainer::getMaxDepthInTree() +// ELF 0x3A0910. +int AIPathfinding::MapContainer::getMaxDepthInTree() const { return m_maxDepthInTree; } +// ELF 0x3A0920. void AIPathfinding::MapContainer::setMaxDepthInTree(int n) { m_maxDepthInTree = n; } // Owns a navigation map with defaults of four polygons per leaf and tree depth eight. +// ELF 0x39FAD0, 0x39FDA0 (compiler-emitted variants). AIPathfinding::MapContainer::MapContainer(const std::string& name, int id) : m_id(id) , m_name(name) @@ -403,6 +593,7 @@ AIPathfinding::MapContainer::MapContainer(const std::string& name, int id) // manager goes first and the properties second, which is the reverse of the order the constructor // built them - and both are `delete` with a null test the binary spells out even though `delete` // already handles null. +// ELF 0x3A0070, 0x3A01C0, 0x3A0310 (compiler-emitted variants). AIPathfinding::MapContainer::~MapContainer() { delete m_quadTreeManager; @@ -410,107 +601,127 @@ AIPathfinding::MapContainer::~MapContainer() } // Slope setters accept degrees; getters return radians. -float AIPathfinding::MapContainer::getMaxSlope() +// ELF 0x3A0930. +float AIPathfinding::MapContainer::getMaxSlope() const { return m_properties->getMaxSlope(); } // Converts the supplied slope from degrees to radians. The corresponding getter // returns radians, so console input and output use different units. +// ELF 0x3A0960. void AIPathfinding::MapContainer::setMaxSlope(float degrees) { m_properties->setMaxSlope(0.017453292f * degrees); } +// ELF 0x3A0C50. void AIPathfinding::MapContainer::setHeadClearance(float clearance) { m_properties->setHeadClearance(clearance); } -float AIPathfinding::MapContainer::getHeadClearance() +// ELF 0x3A0C80. +float AIPathfinding::MapContainer::getHeadClearance() const { return m_properties->getHeadClearance(); } +// ELF 0x3A0BE0. void AIPathfinding::MapContainer::setRadius(float radius) { m_properties->setRadius(radius); } -float AIPathfinding::MapContainer::getRadius() +// ELF 0x3A0BB0. +float AIPathfinding::MapContainer::getRadius() const { return m_properties->getRadius(); } +// ELF 0x3A0C10. void AIPathfinding::MapContainer::setAllowedHeightDiff(float diff) { m_properties->setAllowedHeightDiff(diff); } // A direct member read - see the block above. -float AIPathfinding::MapContainer::getAllowedHeightDiff() +// ELF 0x3A0C40. +float AIPathfinding::MapContainer::getAllowedHeightDiff() const { return m_properties->m_allowedHeightDiff; } // Forwards map operations to QuadTreeManager. Build/load operations use m_name as the // file stem for quad-tree and GTS mesh data. -void AIPathfinding::MapContainer::draw() +// ELF 0x3A0CB0. +void AIPathfinding::MapContainer::draw() const { m_quadTreeManager->draw(); } -void AIPathfinding::MapContainer::undraw() +// ELF 0x3A0CE0. +void AIPathfinding::MapContainer::undraw() const { m_quadTreeManager->undraw(); } -void AIPathfinding::MapContainer::drawCluster() +// ELF 0x3A0D10. +void AIPathfinding::MapContainer::drawCluster() const { m_quadTreeManager->drawCluster(); } -void AIPathfinding::MapContainer::undrawCluster() +// ELF 0x3A0D40. +void AIPathfinding::MapContainer::undrawCluster() const { m_quadTreeManager->undrawCluster(); } -void AIPathfinding::MapContainer::drawClusterNeighbourIndices(const Vec3& position) +// ELF 0x3A0D70. +void AIPathfinding::MapContainer::drawClusterNeighbourIndices(const Vec3& position) const { m_quadTreeManager->drawClusterNeighbourIndices(position); } +// ELF 0x3A0DA0. void AIPathfinding::MapContainer::loadGTSDebugMeshes() { m_quadTreeManager->loadGTSDebugMeshes(m_name); } +// ELF 0x3A0DD0. void AIPathfinding::MapContainer::buildDebugMeshes() { m_quadTreeManager->buildDebugMeshes(m_name); } +// ELF 0x3A0E00. void AIPathfinding::MapContainer::unloadDebugMeshes() { m_quadTreeManager->unloadDebugMeshes(); } +// ELF 0x3A0E30. void AIPathfinding::MapContainer::buildDebugClusterMeshes() { m_quadTreeManager->buildDebugClusterMeshes(m_name); } +// ELF 0x3A0E60. void AIPathfinding::MapContainer::unloadDebugClusterMeshes() { m_quadTreeManager->unloadDebugClusterMeshes(); } +// ELF 0x3A0740. void AIPathfinding::MapContainer::saveQuadTrees() { m_quadTreeManager->saveQuadTrees(m_name); } // Loads navigation data and supplies its dimensions to the mine manager. +// ELF 0x3A0770. void AIPathfinding::MapContainer::loadQuadTrees() { m_quadTreeManager->loadQuadTrees(m_name); @@ -522,6 +733,7 @@ void AIPathfinding::MapContainer::loadQuadTrees() islands); } +// ELF 0x3A07F0. void AIPathfinding::MapContainer::loadGTSData(int a, float b) { // the tree parameters GO in depth-then-leaf order, which is the reverse of the order they are @@ -536,16 +748,19 @@ void AIPathfinding::MapContainer::loadGTSData(int a, float b) } // Appends a vehicle name only. init populates the parallel cost-type vector later. +// ELF 0x3A0880. void AIPathfinding::MapContainer::addVehicleForClusterCost(const std::string& vehicle) { m_clusterCostVehicles.push_back(vehicle); } +// ELF 0x3A0E90. void AIPathfinding::MapContainer::recalculatePortalCosts() { m_quadTreeManager->recalculatePortalCosts(m_id); } +// ELF 0x3A0470. void AIPathfinding::MapContainer::init() { // Build the map-local vehicle @@ -572,27 +787,85 @@ void AIPathfinding::MapContainer::init() } } -bool AIPathfinding::MapContainer::isValidPosition(const Vec3&, MaterialManager*, bool) const -{ - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::MapContainer::isValidPosition"); -} - -bool AIPathfinding::MapContainer::isValidPosition(const Vec3&, MaterialManager*, unsigned int, - bool) const +// ELF 0x3A0F30. A position is valid when it lies on a polygon; unless `ignoreMaterial` is set, the +// polygon's material must also be readable and not 5. [INFERRED] name of the flag. +bool AIPathfinding::MapContainer::isValidPosition(const Vec3& position, MaterialManager* materials, + bool ignoreMaterial) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::MapContainer::isValidPosition"); + unsigned int polygon; + const unsigned int island = m_quadTreeManager->findPolygon( + position, polygon, materials, m_properties->m_allowedHeightDiff); + bool valid = false; + if (island != 0xFFFFFFFFu && polygon != 0xFFFFFFFFu) + { + valid = true; + if (!ignoreMaterial) + { + unsigned char material; + if (!getMaterial(island, polygon, material)) + return false; + if (material == 5) + return false; + } + } + return valid; } -bool AIPathfinding::MapContainer::isValidPosition(const Vec3&, MaterialManager*, unsigned int, - unsigned int, bool) const +// ELF 0x3A0FD0. The island is given; only that island's quad tree is searched. The return value of +// QuadTree::findPolygon and the polygon output are both tested. +bool AIPathfinding::MapContainer::isValidPosition(const Vec3& position, MaterialManager* materials, + unsigned int island, bool ignoreMaterial) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::MapContainer::isValidPosition"); + unsigned int polygon; + const bool found = m_quadTreeManager->getIsland(island)->findPolygon( + position, polygon, materials, m_properties->m_allowedHeightDiff); + bool valid = false; + if (found && polygon != 0xFFFFFFFFu) + valid = true; + if (valid && !ignoreMaterial) + { + unsigned char material; + if (!getMaterial(island, polygon, material)) + return false; + if (material == 5) + return false; + } + return valid; +} + +// ELF 0x3A1090. The known island and polygon seed the manager's search; note the order: the +// first unsigned argument is the island (0x3A10B7..0x3A10C8 pass the second as findPolygon's +// known polygon), the reverse of the getPolygon overload at 0x3A12A0. +bool AIPathfinding::MapContainer::isValidPosition(const Vec3& position, MaterialManager* materials, + unsigned int knownIsland, + unsigned int knownPolygon, + bool ignoreMaterial) const +{ + unsigned int polygon; + const unsigned int island = m_quadTreeManager->findPolygon( + position, polygon, knownPolygon, knownIsland, materials, + m_properties->m_allowedHeightDiff); + bool valid = false; + if (island != 0xFFFFFFFFu && polygon != 0xFFFFFFFFu) + { + valid = true; + if (!ignoreMaterial) + { + unsigned char material; + if (!getMaterial(island, polygon, material)) + return false; + if (material == 5) + return false; + } + } + return valid; } // Resolves polygon then island outputs. Always writes the full-width island result; // on failure it is UINT_MAX and the polygon output is unchanged. The vertex overload // appends without clearing, and known ids are validated before reuse. -bool AIPathfinding::MapContainer::getPolygon(std::vector& vertices, Vec3& position, +// ELF 0x3A1140. +bool AIPathfinding::MapContainer::getPolygon(std::vector& vertices, const Vec3& position, unsigned int& polygon, unsigned int& island, MaterialManager* materials) const { @@ -601,6 +874,7 @@ bool AIPathfinding::MapContainer::getPolygon(std::vector& vertices, return getPolygon(vertices, polygon, island); } +// ELF 0x3A11C0. bool AIPathfinding::MapContainer::getPolygon(std::vector& vertices, unsigned int polygon, unsigned int island) const { @@ -611,6 +885,7 @@ bool AIPathfinding::MapContainer::getPolygon(std::vector& vertices, return true; } +// ELF 0x3A1230. bool AIPathfinding::MapContainer::getPolygon(const Vec3& position, unsigned int& polygon, unsigned int& island, MaterialManager* materials) const @@ -620,6 +895,7 @@ bool AIPathfinding::MapContainer::getPolygon(const Vec3& position, unsigned int& return island != 0xFFFFFFFFu && polygon != 0xFFFFFFFFu; } +// ELF 0x3A12A0. bool AIPathfinding::MapContainer::getPolygon(const Vec3& position, unsigned int& polygon, unsigned int& island, unsigned int knownPolygon, unsigned int knownIsland, @@ -630,32 +906,54 @@ bool AIPathfinding::MapContainer::getPolygon(const Vec3& position, unsigned int& return island != 0xFFFFFFFFu && polygon != 0xFFFFFFFFu; } -void AIPathfinding::MapContainer::getPolygonsInRadius(std::list&, unsigned int, - unsigned int, const Vec3&, float) const +// ELF 0x3A1320: forwarded unchanged to the quad-tree manager. +void AIPathfinding::MapContainer::getPolygonsInRadius(std::list& polygons, + unsigned int quadTree, unsigned int polygon, + const Vec3& centre, float radius) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::MapContainer::getPolygonsInRadius"); + m_quadTreeManager->getPolygonsInRadius(polygons, quadTree, polygon, centre, radius); } -void AIPathfinding::MapContainer::getPolygonsInTriangle(std::list&, unsigned int, - unsigned int, const Vec3&, const Vec3&, - const Vec3&) const +// ELF 0x3A1370: forwarded unchanged to the quad-tree manager. +void AIPathfinding::MapContainer::getPolygonsInTriangle(std::list& polygons, + unsigned int quadTree, + unsigned int polygon, const Vec3& a, + const Vec3& b, const Vec3& c) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::MapContainer::getPolygonsInTriangle"); + m_quadTreeManager->getPolygonsInTriangle(polygons, quadTree, polygon, a, b, c); } -bool AIPathfinding::MapContainer::getPolygonFromIsland(const Vec3&, unsigned int&, unsigned int&, - MaterialManager*) const +// ELF 0x3A13D0. Searches only the given island; QuadTree::findPolygon's own result is discarded and +// the polygon output decides. The island reference is read, never written. +bool AIPathfinding::MapContainer::getPolygonFromIsland(const Vec3& position, unsigned int& polygon, + unsigned int& island, + MaterialManager* materials) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::MapContainer::getPolygonFromIsland"); + const float allowedHeightDiff = m_properties->m_allowedHeightDiff; + m_quadTreeManager->getIsland(island)->findPolygon(position, polygon, materials, + allowedHeightDiff); + return polygon != 0xFFFFFFFFu; } -bool AIPathfinding::MapContainer::getMaterial(const Vec3&, MaterialManager*, unsigned char&) const +// ELF 0x3A1440. The material is zeroed when no polygon is found. +bool AIPathfinding::MapContainer::getMaterial(const Vec3& position, MaterialManager* materials, + unsigned char& material) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::MapContainer::getMaterial"); + unsigned int polygon; + const unsigned int island = m_quadTreeManager->findPolygon( + position, polygon, materials, m_properties->m_allowedHeightDiff); + if (island == 0xFFFFFFFFu || polygon == 0xFFFFFFFFu) + { + material = 0; + return false; + } + material = m_quadTreeManager->getIsland(island)->getMaterialOfPolygon(polygon); + return true; } // UINT_MAX in either index is the only rejected input. Other // out-of-range values retain retail's unchecked island and polygon indexing. +// ELF 0x3A14E0. bool AIPathfinding::MapContainer::getMaterial(unsigned int quadTree, unsigned int polygon, unsigned char& material) const { @@ -669,45 +967,172 @@ bool AIPathfinding::MapContainer::getMaterial(unsigned int quadTree, unsigned in return true; } -bool AIPathfinding::MapContainer::setMaterial(unsigned int, unsigned int, unsigned char) +// ELF 0x3A1550. UINT_MAX in either index is rejected; other values index unchecked. +bool AIPathfinding::MapContainer::setMaterial(unsigned int quadTree, unsigned int polygon, + unsigned char material) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::MapContainer::setMaterial"); + if (quadTree == 0xFFFFFFFFu || polygon == 0xFFFFFFFFu) + return false; + m_quadTreeManager->getIsland(quadTree)->setMaterialOfPolygon(polygon, material); + return true; } -void AIPathfinding::MapContainer::getPolygonCentre(Vec3&, unsigned int, unsigned int) const +// ELF 0x3A15C0. +void AIPathfinding::MapContainer::getPolygonCentre(Vec3& centre, unsigned int polygon, + unsigned int island) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::MapContainer::getPolygonCentre"); + m_quadTreeManager->getIsland(island)->getCentreOfPolygon(centre, polygon); } -void AIPathfinding::MapContainer::getEdge(Vec3&, Vec3&, unsigned int, unsigned int, - unsigned int) const +// ELF 0x3A1610. The shared edge of `polygon` towards `neighbour`: its two corners, the vertex at the +// neighbour's index and the next one (wrapping). False when the polygon id is out of range or the +// neighbour is not adjacent. +bool AIPathfinding::MapContainer::getEdge(Vec3& first, Vec3& second, unsigned int polygon, + unsigned int neighbour, unsigned int island) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::MapContainer::getEdge"); -} + const QuadTree* const quadTree = m_quadTreeManager->getIsland(island); + const Polygon* const record = quadTree->getPolygon(polygon); + if (record == 0) + return false; -bool AIPathfinding::MapContainer::trace(unsigned int&, unsigned int&, const Vec3&, const Vec3&, - Vec3&, unsigned int&, int, float, MaterialManager*, - unsigned char, unsigned char*) const -{ - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::MapContainer::trace"); + unsigned char index = 0; + if (!quadTree->getNeighbourIndexForPolygon(index, polygon, neighbour)) + return false; + + first = *quadTree->getVertexForPolygon(polygon, index); + second = *quadTree->getVertexForPolygon( + polygon, static_cast((index + 1) % record->vertexCount)); + return true; } -bool AIPathfinding::MapContainer::traceKnown(unsigned int, unsigned int, const Vec3&, const Vec3&, - Vec3&, unsigned int&, int, float, MaterialManager*, - unsigned char, unsigned char*) const +// ELF 0x3A1720. Resolves the start polygon from the caller's hints (both written back), then traces +// from that known polygon. +bool AIPathfinding::MapContainer::trace(unsigned int& polygon, unsigned int& island, + const Vec3& from, const Vec3& to, Vec3& end, + unsigned int& endPolygon, int maxSteps, float width, + MaterialManager* materials, unsigned char flags, + unsigned char* materialOut) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::MapContainer::traceKnown"); + island = m_quadTreeManager->findPolygon(from, polygon, polygon, island, materials, + m_properties->m_allowedHeightDiff); + if (polygon == 0xFFFFFFFFu || island == 0xFFFFFFFFu) + return false; + return traceKnown(polygon, island, from, to, end, endPolygon, maxSteps, width, materials, + flags, materialOut); +} + +// ELF 0x3A1800. Walks polygon to polygon along the XZ line from `from` towards `to`, starting in +// the known polygon. True when `to` is reached (within 0.05 along the line or 0.025 squared in +// XZ; `end` is then `to`), or when the very first polygon has no exit at all. False on a border, +// after `maxSteps` polygons (-1: no limit) or 30,001, on a material the vehicle cannot use, on +// `stopMaterial` (5 and 6 also stop on 7), or where a non-zero `width` does not fit through an +// edge. `endPolygon` tracks the last polygon entered; `end` the last edge crossing. +// [INFERRED] parameter names. +bool AIPathfinding::MapContainer::traceKnown(unsigned int polygon, unsigned int island, + const Vec3& from, const Vec3& to, Vec3& end, + unsigned int& endPolygon, int maxSteps, float width, + MaterialManager* materials, + unsigned char stopMaterial, + unsigned char* materialOut) const +{ + const QuadTree* const quadTree = m_quadTreeManager->getIsland(island); + + Vec3 direction; + direction.x = to.x - from.x; + direction.y = to.y - from.y; + direction.z = to.z - from.z; + const float length = + std::sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z); + if (!(length > 1e-6f)) + { + endPolygon = polygon; + return true; + } + const float inverse = 1.0f / length; + direction.x *= inverse; + direction.y *= inverse; + direction.z *= inverse; + + end = from; + unsigned int previousPolygon = 0xFFFFFFFFu; + endPolygon = polygon; + int steps = 0; + for (;;) + { + if (polygon == 0xFFFFFFFFu) + return false; + if (maxSteps != -1 && steps >= maxSteps) + return false; + if (steps > 30000) + return false; + endPolygon = polygon; + ++steps; + + float clearance; + // [CHOSEN, not recovered] The callee never writes its second float output, so retail + // compares an uninitialised stack value below. Zero keeps that width test inert. + float unused = 0.0f; + unsigned char edge; + const bool crossed = quadTree->getLineIntersectionOnEdgeInPolygon( + end, polygon, edge, previousPolygon, from, direction, + width == 0.0f ? 0 : &clearance, width == 0.0f ? 0 : &unused); + if (!crossed) + { + if (previousPolygon != 0xFFFFFFFFu) + return false; + end = to; + return true; + } + previousPolygon = polygon; + + const float dx = end.x - from.x; + const float dy = end.y - from.y; + const float dz = end.z - from.z; + if (std::sqrt(dx * dx + dy * dy + dz * dz) + 0.05f >= length || + 0.025f >= distXZSqr(to, end)) + { + end = to; + return true; + } + + if (width != 0.0f && unused > clearance + clearance && width > clearance) + return false; + + polygon = quadTree->getNeighbourOfPolygon(polygon, edge); + if (polygon == 0xFFFFFFFFu) + return false; + const unsigned char material = quadTree->getMaterialOfPolygon(polygon); + if (materialOut != 0) + *materialOut = material; + if (!materials->isValidMaterial(material)) + return false; + if (stopMaterial != 0) + { + if (material == stopMaterial) + return false; + if (static_cast(stopMaterial - 5) <= 1 && material == 7) + return false; + } + } } -bool AIPathfinding::MapContainer::getLineIntersectionWithPolygon(Vec3&, unsigned int, unsigned int, - const Vec3&, const Vec3&) const +// ELF 0x3A1B90. Any edge of the polygon (no previous edge, UINT_MAX) and no parameter outputs. +bool AIPathfinding::MapContainer::getLineIntersectionWithPolygon(Vec3& intersection, + unsigned int polygon, + unsigned int island, + const Vec3& from, + const Vec3& to) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::MapContainer::getLineIntersectionWithPolygon"); + unsigned char edge; + return m_quadTreeManager->getIsland(island)->getLineIntersectionOnEdgeInPolygon( + intersection, polygon, edge, 0xFFFFFFFFu, from, to, 0, 0); } -void AIPathfinding::MapContainer::drawPolygon(unsigned int, unsigned int, float*, float) const +// ELF 0x3A1C10. +void AIPathfinding::MapContainer::drawPolygon(unsigned int island, unsigned int polygon, + float* height, float duration) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::MapContainer::drawPolygon"); + m_quadTreeManager->getIsland(island)->drawPolygon(polygon, height, duration); } // Sample `limit` equally spaced points from @@ -715,8 +1140,9 @@ void AIPathfinding::MapContainer::drawPolygon(unsigned int, unsigned int, float* // advances `closest` once more after the final failed sample, so failure can leave it beyond `to`; // preserve that observable quirk. The output ids are cleared before the zero-limit return, polygon // first and island second, and receive the successful lookup in that same order. -bool AIPathfinding::MapContainer::findClosestValidPolygon(unsigned int& quadTree, - unsigned int& polygon, Vec3& closest, +// ELF 0x3A1C60. +bool AIPathfinding::MapContainer::findClosestValidPolygon(unsigned int& polygon, + unsigned int& island, Vec3& closest, const Vec3& from, const Vec3& to, unsigned int limit, MaterialManager* materials) const @@ -735,8 +1161,8 @@ bool AIPathfinding::MapContainer::findClosestValidPolygon(unsigned int& quadTree } closest = from; + island = 0xFFFFFFFFu; // stores 0x3A1D19 (second) then 0x3A1D1F (first) polygon = 0xFFFFFFFFu; - quadTree = 0xFFFFFFFFu; if (limit == 0) return false; @@ -754,74 +1180,239 @@ bool AIPathfinding::MapContainer::findClosestValidPolygon(unsigned int& quadTree return false; } + // 0x3A1D91..0x3A1D9F: the first reference receives getPolygon's polygon, the second its island. + island = foundIsland; polygon = foundPolygon; - quadTree = foundIsland; return true; } -void AIPathfinding::MapContainer::updateClusterPortalCosts( - unsigned int&, triple&, unsigned int, - unsigned short) +// ELF 0x3A0EC0. The map id is this container's own. +bool AIPathfinding::MapContainer::updateClusterPortalCosts( + unsigned int& resource, triple& portal, + unsigned int island, unsigned short costType) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::MapContainer::updateClusterPortalCosts"); + return m_quadTreeManager->getClusterGraph(island)->updatePortalCosts(resource, portal, m_id, + island, costType); } // AIPathfinding, the unwritten half // Resets destroyable map parts in every map's quad-tree manager. +// ELF 0x3A8680. void AIPathfinding::resetDestroyableMapParts() { for (unsigned int i = 0; i < m_maps.size(); ++i) m_maps[i]->m_quadTreeManager->resetDestroyableMapParts(); } -int AIPathfinding::localSearch(int, int, unsigned int, unsigned int, const Vec3&, unsigned int, - const Vec3&, int, QTPath*) -{ - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::localSearch"); -} +// ELF 0x3A5430. Polls or starts the resource's navigation-mesh search. A failed (3) search reports +// that until the resource is released; a found (2) one hands its path over through +// internalLocalSearch with the polygon hints cleared. A new search needs all three polygon ids; +// otherwise the answer is 4 and nothing starts. Retail fetches the vehicle's material table here +// and discards it. +int AIPathfinding::localSearch(int resource, int map, unsigned int island, + unsigned int startPolygon, const Vec3& start, + unsigned int goalPolygon, const Vec3& goal, int vehicleId, + QTPath* path) +{ + const int status = m_engine->m_searches[resource]->m_status; + if (status == astarStatus::kFailed || status == astarStatus::kInvalid) + return status; + if (status == astarStatus::kFound) + return internalLocalSearch(resource, map, 0xFFFFFFFFu, 0xFFFFFFFFu, start, 0xFFFFFFFFu, + goal, vehicleId, path); + if (status == astarStatus::kSearching) + return status; -int AIPathfinding::clusterSearch(int, int, unsigned int, unsigned int, const Vec3&, unsigned int, - const Vec3&, int, ClusterNodePath*) -{ - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::clusterSearch"); + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + settings->getVehicleMaterialManager(vehicleId); + if (island == 0xFFFFFFFFu || startPolygon == 0xFFFFFFFFu || goalPolygon == 0xFFFFFFFFu) + return astarStatus::kInvalid; + return internalLocalSearch(resource, map, island, startPolygon, start, goalPolygon, goal, + vehicleId, path); +} + +// ELF 0x3A5990. Polls or starts the resource's cluster-graph search. Failed (3) and invalid (4) +// report as such; a found one appends its path when a goal node exists. A new search runs on +// `island`'s cluster graph from the start polygon's cluster to the goal polygon's, with the +// vehicle's cluster cost type, the two positions and emptied open, overflow and closed sets. +// Unlike localSearch the polygon ids are not checked. +int AIPathfinding::clusterSearch(int resource, int map, unsigned int island, + unsigned int startPolygon, const Vec3& start, + unsigned int goalPolygon, const Vec3& goal, int vehicleId, + ClusterNodePath* path) +{ + ClusterResource* search = m_clusterEngine->m_searches[resource]; + const int status = search->m_status; + if (status == astarStatus::kFailed || status == astarStatus::kInvalid) + return status; + if (status == astarStatus::kFound) + { + if (search->m_goal != 0) + search->m_nodeManager->buildPath(*path, search->m_goal); + return status; + } + if (status == astarStatus::kSearching) + return status; + + ClusterNodeManager* const manager = search->m_nodeManager; + path->m_island = static_cast(island); + path->setVehicle(map, vehicleId); + + QuadTree* const quadTree = m_maps[map]->m_quadTreeManager->getIsland(island); + manager->setQuadTree(quadTree); + manager->setClusterGraph(m_maps[map]->m_quadTreeManager->getClusterGraph(island)); + + ClusterNode* const startNode = + manager->getNewNode(quadTree->getPolygon(startPolygon)->cluster, 0, 0); + ClusterNode* const goalNode = + manager->getNewNode(quadTree->getPolygon(goalPolygon)->cluster, 0, 0); + manager->m_start = start; + manager->m_goalPosition = goal; + manager->m_costType = m_maps[map]->m_clusterCostTypes[vehicleId]; + + search = m_clusterEngine->m_searches[resource]; + search->m_iterations = 0; + search->m_status = astarStatus::kIdle; + search->m_worstOpen = 0; + search->m_open->clear(); + search->m_openOverflow->clear(); + search->m_closed->clear(); + search->m_nodeManager->reset(); + + search = m_clusterEngine->m_searches[resource]; + if (startNode->m_key == goalNode->m_key) + { + search->m_nodeManager->recycleNode(goalNode); + search->m_status = astarStatus::kFound; + search->m_goal = startNode; + return search->m_status; + } + + search->m_nodeManager->setGoal(goalNode); + search->pushOpenNode(startNode); + search->m_status = astarStatus::kSearching; + return search->m_status; } -int AIPathfinding::internalLocalSearch(int, int, unsigned int, unsigned int, const Vec3&, - unsigned int, const Vec3&, int, QTPath*) +// ELF 0x3A5550. While the resource is searching it only reports; once found it appends the path +// (when a goal node exists) and reports. Otherwise it starts a new search: the quad tree of +// `island`, a start and a goal node, the vehicle's material table, and emptied open, overflow and +// closed sets. A start already on the goal polygon is found at once; else the goal is stored and +// the start opened. +int AIPathfinding::internalLocalSearch(int resource, int map, unsigned int island, + unsigned int startPolygon, const Vec3& start, + unsigned int goalPolygon, const Vec3& goal, int vehicleId, + QTPath* path) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::internalLocalSearch"); + LocalResource* search = m_engine->m_searches[resource]; + if (search->m_status == astarStatus::kSearching || search->m_status == astarStatus::kFound) + { + search = m_engine->m_searches[resource]; + if (search->m_status == astarStatus::kFound && search->m_goal != 0) + search->m_nodeManager->buildPath(*path, search->m_goal); + return m_engine->m_searches[resource]->m_status; + } + + QTSearchNodeManager* const manager = search->m_nodeManager; + path->m_island = static_cast(island); + manager->setQuadTree(m_maps[map]->m_quadTreeManager->getIsland(island)); + + QTSearchNode* const startNode = manager->getNewNode(startPolygon, 0, 0); + startNode->m_position = start; + startNode->m_g = 0.0f; + QTSearchNode* const goalNode = manager->getNewNode(goalPolygon, 0, 0); + goalNode->m_position = goal; + + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + manager->m_materials = settings->getVehicleMaterialManager(vehicleId); + + search = m_engine->m_searches[resource]; + search->m_iterations = 0; + search->m_status = astarStatus::kIdle; + search->m_worstOpen = 0; + search->m_open->clear(); + search->m_openOverflow->clear(); + search->m_closed->clear(); + search->m_nodeManager->reset(); + + search = m_engine->m_searches[resource]; + if (startNode->m_key == goalNode->m_key) + { + search->m_nodeManager->recycleNode(goalNode); + search->m_status = astarStatus::kFound; + search->m_goal = startNode; + return search->m_status; + } + + search->m_nodeManager->setGoal(goalNode); + search->pushOpenNode(startNode); + search->m_status = astarStatus::kSearching; + return search->m_status; } -bool AIPathfinding::isValidPosition(int, int, const Vec3&, bool) const +// ELF 0x3A70E0. A negative map index means "no map" and every position is valid; the upper bound +// is not checked. The next two overloads share the shape. +bool AIPathfinding::isValidPosition(int map, int vehicleId, const Vec3& position, + bool ignoreMaterial) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::isValidPosition"); + if (map < 0) + return true; + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + MaterialManager* const materials = settings->getVehicleMaterialManager(vehicleId); + return m_maps[map]->isValidPosition(position, materials, ignoreMaterial); } -bool AIPathfinding::isValidPosition(int, int, const Vec3&, unsigned int, bool) const +// ELF 0x3A7160. +bool AIPathfinding::isValidPosition(int map, int vehicleId, const Vec3& position, + unsigned int island, bool ignoreMaterial) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::isValidPosition"); + if (map < 0) + return true; + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + MaterialManager* const materials = settings->getVehicleMaterialManager(vehicleId); + return m_maps[map]->isValidPosition(position, materials, island, ignoreMaterial); } -bool AIPathfinding::isValidPosition(int, int, const Vec3&, unsigned int, unsigned int, bool) const +// ELF 0x3A71F0. +bool AIPathfinding::isValidPosition(int map, int vehicleId, const Vec3& position, + unsigned int knownIsland, unsigned int knownPolygon, + bool ignoreMaterial) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::isValidPosition"); + if (map < 0) + return true; + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + MaterialManager* const materials = settings->getVehicleMaterialManager(vehicleId); + return m_maps[map]->isValidPosition(position, materials, knownIsland, knownPolygon, + ignoreMaterial); } -int AIPathfinding::getPolygon(std::vector&, int, const Vec3&, int) const +// ELF 0x3A7910. Unlike the Vec3-only overloads, the vertex overloads do not check the map index. +bool AIPathfinding::getPolygon(std::vector& vertices, int map, + const Vec3& position, int vehicleId) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::getPolygon"); + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + MaterialManager* const materials = settings->getVehicleMaterialManager(vehicleId); + unsigned int polygon; + unsigned int island; + return m_maps[map]->getPolygon(vertices, position, polygon, island, materials); } -int AIPathfinding::getPolygon(std::vector&, int, const Vec3&, unsigned int&, - unsigned int&, int) const +// ELF 0x3A78A0. +bool AIPathfinding::getPolygon(std::vector& vertices, int map, + const Vec3& position, unsigned int& polygon, + unsigned int& island, int vehicleId) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::getPolygon"); + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + MaterialManager* const materials = settings->getVehicleMaterialManager(vehicleId); + return m_maps[map]->getPolygon(vertices, position, polygon, island, materials); } -int AIPathfinding::getPolygon(std::vector&, int, unsigned int, unsigned int) const +// ELF 0x3A7980. +bool AIPathfinding::getPolygon(std::vector& vertices, int map, + unsigned int polygon, unsigned int island) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::getPolygon"); + return m_maps[map]->getPolygon(vertices, polygon, island); } // This is the saved-position variant used by the information @@ -829,6 +1420,7 @@ int AIPathfinding::getPolygon(std::vector&, int, unsigned int, unsi // they can be reused or whether it must fall back to a normal spatial search. As in the adjacent // overload, retail leaves both output references untouched when the map index is invalid and does // not guard the settings singleton. +// ELF 0x3A7A60. bool AIPathfinding::getPolygon(const Vec3& position, int map, unsigned int& polygon, unsigned int& quadTree, unsigned int knownPolygon, unsigned int knownQuadTree, int vehicleId) const @@ -843,77 +1435,141 @@ bool AIPathfinding::getPolygon(const Vec3& position, int map, unsigned int& poly materials); } -int AIPathfinding::getPolygonFromIsland(const Vec3&, int, unsigned int&, unsigned int, int) const +// ELF 0x3A7BE0. The island is passed by value and handed down by reference to a local copy. +bool AIPathfinding::getPolygonFromIsland(const Vec3& position, int map, unsigned int& polygon, + unsigned int island, int vehicleId) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::getPolygonFromIsland"); + if (map < 0 || getNumberOfMaps() <= map) + return false; + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + MaterialManager* const materials = settings->getVehicleMaterialManager(vehicleId); + return m_maps[map]->getPolygonFromIsland(position, polygon, island, materials); } -bool AIPathfinding::getMaterial(const Vec3&, int, int, unsigned char&) const +// ELF 0x3A7C70. An invalid map index returns false and leaves the material untouched. +bool AIPathfinding::getMaterial(const Vec3& position, int map, int vehicleId, + unsigned char& material) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::getMaterial"); + if (map < 0 || getNumberOfMaps() <= map) + return false; + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + MaterialManager* const materials = settings->getVehicleMaterialManager(vehicleId); + return m_maps[map]->getMaterial(position, materials, material); } -void* AIPathfinding::getQuadTree(int, unsigned int) const +// ELF 0x3A7DF0. +void* AIPathfinding::getQuadTree(int map, unsigned int island) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::getQuadTree"); + return m_maps[map]->m_quadTreeManager->getIsland(island); } -void* AIPathfinding::getClusterGraph(int, unsigned int) const +// ELF 0x3A7E30. +void* AIPathfinding::getClusterGraph(int map, unsigned int island) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::getClusterGraph"); + return m_maps[map]->m_quadTreeManager->getClusterGraph(island); } -void AIPathfinding::getPolygonCentre(Vec3&, int, unsigned int, unsigned int) const +// ELF 0x3A7DA0. +void AIPathfinding::getPolygonCentre(Vec3& centre, int map, unsigned int polygon, + unsigned int island) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::getPolygonCentre"); + m_maps[map]->getPolygonCentre(centre, polygon, island); } -void AIPathfinding::getEdge(Vec3&, Vec3&, int, unsigned int, unsigned int, unsigned int) const +// ELF 0x3A7E70. +bool AIPathfinding::getEdge(Vec3& first, Vec3& second, int map, unsigned int polygon, + unsigned int neighbour, unsigned int island) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::getEdge"); + return m_maps[map]->getEdge(first, second, polygon, neighbour, island); } -bool AIPathfinding::getLineIntersectionWithPolygon(Vec3&, int, unsigned int, unsigned int, - const Vec3&, const Vec3&) const +// ELF 0x3A7ED0. +bool AIPathfinding::getLineIntersectionWithPolygon(Vec3& intersection, int map, + unsigned int polygon, unsigned int island, + const Vec3& from, const Vec3& to) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::getLineIntersectionWithPolygon"); + return m_maps[map]->getLineIntersectionWithPolygon(intersection, polygon, island, from, to); } -int AIPathfinding::getClusterOfPolygon(int, unsigned int, unsigned int) const +// ELF 0x3A7F80. The polygon's 16-bit cluster id; an out-of-range polygon dereferences null, as in +// retail. +int AIPathfinding::getClusterOfPolygon(int map, unsigned int island, unsigned int polygon) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::getClusterOfPolygon"); + return m_maps[map]->m_quadTreeManager->getIsland(island)->getPolygon(polygon)->cluster; } -bool AIPathfinding::areNeighbouringClusters(int, unsigned int, unsigned short, - unsigned short) const +// ELF 0x3A7FD0. +bool AIPathfinding::areNeighbouringClusters(int map, unsigned int island, unsigned short first, + unsigned short second) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::areNeighbouringClusters"); + return m_maps[map]->m_quadTreeManager->getClusterGraph(island)->areNeighbours(first, second); } -void AIPathfinding::updateClusterPortalCosts(unsigned int&, +// ELF 0x3A8040. +bool AIPathfinding::updateClusterPortalCosts(unsigned int& resource, triple&, int, unsigned int, - unsigned short) + unsigned short>& portal, int map, + unsigned int island, unsigned short costType) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::updateClusterPortalCosts"); + return m_maps[map]->updateClusterPortalCosts(resource, portal, island, costType); } -bool AIPathfinding::trace(int, const Vec3&, const Vec3&, Vec3&, unsigned int&, int, int, float, - unsigned char, unsigned char*) const +// ELF 0x3A80A0. No polygon or island hint. +bool AIPathfinding::trace(int map, const Vec3& from, const Vec3& to, Vec3& end, + unsigned int& endPolygon, int vehicleId, int maxSteps, float width, + unsigned char stopMaterial, unsigned char* materialOut) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::trace"); + return trace(0xFFFFFFFFu, 0xFFFFFFFFu, map, from, to, end, endPolygon, vehicleId, maxSteps, + width, stopMaterial, materialOut); } -bool AIPathfinding::trace(unsigned int, unsigned int, int, const Vec3&, const Vec3&, Vec3&, - unsigned int&, int, int, float, unsigned char, unsigned char*) const +// ELF 0x3A8120. The hints are local copies: the container's resolved ids are not handed back. +// No map-index check. +bool AIPathfinding::trace(unsigned int polygon, unsigned int island, int map, const Vec3& from, + const Vec3& to, Vec3& end, unsigned int& endPolygon, int vehicleId, + int maxSteps, float width, unsigned char stopMaterial, + unsigned char* materialOut) const +{ + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + MaterialManager* const materials = settings->getVehicleMaterialManager(vehicleId); + return m_maps[map]->trace(polygon, island, from, to, end, endPolygon, maxSteps, width, + materials, stopMaterial, materialOut); +} + +namespace { + +// [TEMP] BotNavigation::getTraceData (ELF 0x194F10, ai-bot's AIBot/BotNavigation) is declared but +// not recovered yet; request on coord/ai-requests.md. Replace with the direct call once it lands. +void traceDataOf(BotNavigation* navigation, int map, unsigned int& polygon, unsigned int& island, + Vec3& from) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::trace"); + navigation->getTraceData(map, polygon, island, from); } -bool AIPathfinding::trace(BotNavigation*, bool, const Vec3&, Vec3&, unsigned int&, int, int, float, - unsigned char, unsigned char*) const +} // anonymous namespace + +// ELF 0x3A81C0. Traces from the bot's current trace start: on the trace map when +// `useTraceMap`, else on the bot's own map (BotNavigation +0x50). The start position, polygon +// and island come from BotNavigation::getTraceData; without a polygon or island the answer is +// false. The trace itself is MapContainer::traceKnown, with the vehicle's material table. +bool AIPathfinding::trace(BotNavigation* navigation, bool useTraceMap, const Vec3& to, Vec3& end, + unsigned int& endPolygon, int vehicleId, int maxSteps, float width, + unsigned char stopMaterial, unsigned char* materialOut) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::trace"); + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + MaterialManager* const materials = settings->getVehicleMaterialManager(vehicleId); // +0xB0 + const int map = useTraceMap ? m_traceMapIndex : navigation->getMapIndex(); + Vec3 from; + from.x = 0.0f; + from.y = 0.0f; + from.z = 0.0f; + unsigned int polygon; + unsigned int island; + traceDataOf(navigation, map, polygon, island, from); + if (polygon == 0xFFFFFFFFu || island == 0xFFFFFFFFu) + return false; + return m_maps[map]->traceKnown(polygon, island, from, to, end, endPolygon, maxSteps, width, + materials, stopMaterial, materialOut); } // The @@ -922,86 +1578,187 @@ bool AIPathfinding::trace(BotNavigation*, bool, const Vec3&, Vec3&, unsigned int // unguarded - no sign or bounds test on the map index (getPolygon above has one; this has none) // so the -666 "no trace map" sentinel would index before the vector. Both images. Retail always has // a trace map: `aiPathfinding.traceMap Infantry` (AIPathFinding.ai), bound at the foot of this file. -bool AIPathfinding::findClosestValidPolygon(unsigned int& quadTree, unsigned int& polygon, +// ELF 0x3A8310. +bool AIPathfinding::findClosestValidPolygon(unsigned int& polygon, unsigned int& island, Vec3& closest, int map, const Vec3& from, const Vec3& to, unsigned int limit, int vehicleId) const { IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); MaterialManager* const materials = settings->getVehicleMaterialManager(vehicleId); // +0xB0 - return m_maps[map]->findClosestValidPolygon(quadTree, polygon, closest, from, to, limit, + return m_maps[map]->findClosestValidPolygon(polygon, island, closest, from, to, limit, materials); } -bool AIPathfinding::acquireResource(unsigned int&, int) +// ELF 0x3A73A0. Takes the first free local-search resource for `owner`. Fails (and writes +// UINT_MAX) while map parts are locking, when none is free, or when the first free one is still +// owned. The id moves from the free list to the back of the in-flight list. +bool AIPathfinding::acquireResource(unsigned int& resource, int owner) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::acquireResource"); + if (m_locking) + { + resource = 0xFFFFFFFFu; + return false; + } + + std::list& available = m_engine->m_available; + if (available.empty()) + { + resource = 0xFFFFFFFFu; + return false; + } + + std::list::iterator first = available.begin(); + resource = *first; + LocalResource* const search = m_engine->m_searches[resource]; + if (search->m_owner >= 0) + { + resource = 0xFFFFFFFFu; + return false; + } + + search->m_owner = owner; + available.erase(first); + m_engine->m_inFlight.insert(m_engine->m_inFlight.end(), resource); + return true; } -void AIPathfinding::releaseResource(unsigned int&, int) +// ELF 0x3A7480. Only the owner can release. Clears the search limits, the node manager's per-search +// options and the status, returns the id to the back of the free list and invalidates the +// caller's handle. +void AIPathfinding::releaseResource(unsigned int& resource, int owner) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::releaseResource"); + if (m_engine->m_searches[resource]->m_owner != owner) + return; + + m_engine->m_searches[resource]->m_owner = -1; + LocalResource* const search = m_engine->m_searches[resource]; + search->m_maxIterations = 0; + search->m_maxSearchDepth = -1; + search->m_nodeManager->returnReset(); + search->m_status = 0; + search->m_owner = -1; + m_engine->m_available.insert(m_engine->m_available.end(), resource); + m_engine->m_inFlight.remove(resource); + resource = 0xFFFFFFFFu; } -bool AIPathfinding::acquireClusterResource(unsigned int&, int) +// ELF 0x3A7560 (the local body on the cluster engine). Takes the first free cluster-search resource for `owner`. Fails (and writes +// UINT_MAX) while map parts are locking, when none is free, or when the first free one is still +// owned. The id moves from the free list to the back of the in-flight list. +bool AIPathfinding::acquireClusterResource(unsigned int& resource, int owner) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::acquireClusterResource"); + if (m_locking) + { + resource = 0xFFFFFFFFu; + return false; + } + + std::list& available = m_clusterEngine->m_available; + if (available.empty()) + { + resource = 0xFFFFFFFFu; + return false; + } + + std::list::iterator first = available.begin(); + resource = *first; + ClusterResource* const search = m_clusterEngine->m_searches[resource]; + if (search->m_owner >= 0) + { + resource = 0xFFFFFFFFu; + return false; + } + + search->m_owner = owner; + available.erase(first); + m_clusterEngine->m_inFlight.insert(m_clusterEngine->m_inFlight.end(), resource); + return true; } -void AIPathfinding::releaseClusterResource(unsigned int&, int) +// ELF 0x3A7640 (the local body on the cluster engine). Only the owner can release. Clears the search limits, the node manager's per-search +// options and the status, returns the id to the back of the free list and invalidates the +// caller's handle. +void AIPathfinding::releaseClusterResource(unsigned int& resource, int owner) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::releaseClusterResource"); + if (m_clusterEngine->m_searches[resource]->m_owner != owner) + return; + + m_clusterEngine->m_searches[resource]->m_owner = -1; + ClusterResource* const search = m_clusterEngine->m_searches[resource]; + search->m_maxIterations = 0; + search->m_maxSearchDepth = -1; + search->m_nodeManager->returnReset(); + search->m_status = 0; + search->m_owner = -1; + m_clusterEngine->m_available.insert(m_clusterEngine->m_available.end(), resource); + m_clusterEngine->m_inFlight.remove(resource); + resource = 0xFFFFFFFFu; } -// Search-record mutations remain unimplemented: status, iteration/depth limits, -// additional goals, allowed clusters, and smoothing must use the confirmed record layout. -void AIPathfinding::setMaxIterationsForResource(unsigned int&, unsigned int) +// ELF 0x3A7720. +void AIPathfinding::setMaxIterationsForResource(unsigned int& resource, unsigned int iterations) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::setMaxIterationsForResource"); + m_engine->m_searches[resource]->m_maxIterations = iterations; } -void AIPathfinding::setMaxSearchDepthForResource(unsigned int&, unsigned int) +// ELF 0x3A7740. +void AIPathfinding::setMaxSearchDepthForResource(unsigned int& resource, unsigned int depth) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::setMaxSearchDepthForResource"); + m_engine->m_searches[resource]->m_maxSearchDepth = depth; } -void AIPathfinding::setAdditionalGoals(unsigned int, const std::set*) +// ELF 0x3A8460. The set is borrowed, not copied; releaseResource clears the pointer. +void AIPathfinding::setAdditionalGoals(unsigned int resource, const std::set* goals) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::setAdditionalGoals"); + m_engine->m_searches[resource]->m_nodeManager->m_additionalGoals = goals; } -void AIPathfinding::setAllowedClusters(unsigned int, const std::set*) +// ELF 0x3A8480. Borrowed as well; releaseResource leaves it set. +void AIPathfinding::setAllowedClusters(unsigned int resource, + const std::set* clusters) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::setAllowedClusters"); + m_engine->m_searches[resource]->m_nodeManager->m_allowedClusters = clusters; } -void AIPathfinding::setUsePathTopologySmoothing(unsigned int, bool) +// ELF 0x3A84A0. +void AIPathfinding::setUsePathTopologySmoothing(unsigned int resource, bool use) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::setUsePathTopologySmoothing"); + m_engine->m_searches[resource]->m_nodeManager->m_usePathTopologySmoothing = use; } -int AIPathfinding::getStatus(unsigned int) const +// ELF 0x3A7760. The local engine's status word; cluster searches have their own. +int AIPathfinding::getStatus(unsigned int resource) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::getStatus"); + return m_engine->m_searches[resource]->m_status; } -void AIPathfinding::setStatus(unsigned int, astar::Status) +// ELF 0x3A7780. +void AIPathfinding::setStatus(unsigned int resource, astar::Status status) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::setStatus"); + m_engine->m_searches[resource]->m_status = status; } -void AIPathfinding::updateQuadTree(unsigned int, int, unsigned int) +// ELF 0x3A77A0. Points the resource's node manager at another quad tree. +void AIPathfinding::updateQuadTree(unsigned int resource, int map, unsigned int island) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::updateQuadTree"); + QuadTree* const quadTree = m_maps[map]->m_quadTreeManager->getIsland(island); + m_engine->m_searches[resource]->m_nodeManager->setQuadTree(quadTree); } -float AIPathfinding::calculateCostOfPath(unsigned int, int, unsigned int, const QTPath&) const +// ELF 0x3A7810. Costs `path` with the resource's node manager, which keeps the material table of +// its last search. +float AIPathfinding::calculateCostOfPath(unsigned int resource, int map, unsigned int island, + const QTPath& path) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::calculateCostOfPath"); + QuadTree* const quadTree = m_maps[map]->m_quadTreeManager->getIsland(island); + m_engine->m_searches[resource]->m_nodeManager->setQuadTree(quadTree); + return m_engine->m_searches[resource]->m_nodeManager->calculateCostOfPath(path); } // Splits the time budget between cluster and polygon searches by queue length. // With both queues empty, the cluster share is NaN and no cluster work runs. +// ELF 0x3A8390. void AIPathfinding::updatePathfinding(double budget) { IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); @@ -1014,6 +1771,7 @@ void AIPathfinding::updatePathfinding(double budget) } // Assigns an ID to a destroyable map part and propagates its lifecycle to all navigation meshes. +// ELF 0x3A84C0. void AIPathfinding::initializeDestroyableMapPart(int& mapPartId, bool walkable, const Vec3& minCorner, const Vec3& maxCorner, const Mat4& transformation) { @@ -1023,52 +1781,234 @@ void AIPathfinding::initializeDestroyableMapPart(int& mapPartId, bool walkable, maxCorner, transformation); } +// ELF 0x3A8560. void AIPathfinding::destroyMapPart(int mapPartId) { for (unsigned int i = 0; i < m_maps.size(); ++i) m_maps[i]->m_quadTreeManager->destroyMapPart(mapPartId); } +// ELF 0x3A85C0. void AIPathfinding::restoreMapPart(int mapPartId) { for (unsigned int i = 0; i < m_maps.size(); ++i) m_maps[i]->m_quadTreeManager->restoreMapPart(mapPartId); } +// ELF 0x3A8620. void AIPathfinding::resetOriginalMaterialOfDestroyableMapPart(int mapPartId) { for (unsigned int i = 0; i < m_maps.size(); ++i) m_maps[i]->m_quadTreeManager->resetOriginalMaterialOfDestroyableMapPart(mapPartId); } -void AIPathfinding::searchPointSelected(bool) +// ELF 0x3A42F0. Selects the two debug endpoints with a two-second click interval. +void AIPathfinding::searchPointSelected(bool resetPoints) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::searchPointSelected"); + if (!m_activatePathfindingDebugTool) + return; + const double nextSelection = m_d36 + 2.0; + if (nextSelection >= + static_cast(CommonSingletonServer::m_iBFTimer)->getUpdateTime()) + return; + if (resetPoints || m_searchPointToSet == 2) + { + m_d36 = -1000.0; + m_searchPointToSet = 0; + m_path->m_nodes.resize(0); + m_path->m_i0 = 0; + m_path->m_i20 = 0.0f; + if (resetPoints) + return; + } + m_d36 = static_cast(CommonSingletonServer::m_iBFTimer)->getUpdateTime(); + IAIObjectEnvironment* const environment = + static_cast(CommonSingletonServer::m_iaiObjectEnvironment); + Mat4 camera = {{1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f}}; + environment->getLocalPlayerCameraTransformation(camera); + const Vec3 origin = {camera.m[12], camera.m[13], camera.m[14]}; + const Vec3 end = {camera.m[8] * 250.0f + origin.x, + camera.m[9] * 250.0f + origin.y, + camera.m[10] * 250.0f + origin.z}; + if (!environment->collideLineWithWorld(origin, end, 0, m_searchPoint[m_searchPointToSet])) + return; + if (!isValidPosition(m_pathfindingDebugToolVehicleId != 3, + m_pathfindingDebugToolVehicleId, + *m_searchPoint[m_searchPointToSet], true)) + return; + unsigned int resource = 0xFFFFFFFFu; + unsigned int fromPolygon, island; + getPolygon(*m_searchPoint[0], m_pathfindingDebugToolVehicleId != 3, + fromPolygon, island, m_pathfindingDebugToolVehicleId); + if (island == 0xFFFFFFFFu || fromPolygon == 0xFFFFFFFFu) + return; + if (m_searchPointToSet == 0 && m_clusterSearch) + { + QuadTree* const tree = m_maps[m_pathfindingDebugToolVehicleId != 3] + ->m_quadTreeManager->getIsland(island); + const Polygon* const polygon = tree->getPolygon(fromPolygon); + const int type = m_maps[m_pathfindingDebugToolVehicleId != 3] + ->m_clusterCostTypes[m_pathfindingDebugToolVehicleId]; + m_maps[m_pathfindingDebugToolVehicleId != 3]->m_quadTreeManager + ->getClusterGraph(island)->drawCluster(polygon->cluster, type); + } + unsigned int toPolygon; + // shipped defect: this also queries the second endpoint before the first click completes. + getPolygonFromIsland(*m_searchPoint[1], m_pathfindingDebugToolVehicleId != 3, + toPolygon, island, m_pathfindingDebugToolVehicleId); + if (toPolygon == 0xFFFFFFFFu) + return; + if (m_searchPointToSet == 1) + { + const bool acquired = !m_clusterSearch ? acquireResource(resource, 2000) + : acquireClusterResource(resource, 2000); + if (!acquired) + { + m_searchPointToSet = 1; + return; + } + } + if (++m_searchPointToSet != 2) + return; + if (!m_clusterSearch) + { + m_path->m_nodes.resize(0); + m_path->m_i0 = 0; + m_path->m_i20 = 0.0f; + if (localSearch(resource, m_pathfindingDebugToolVehicleId != 3, island, fromPolygon, + *m_searchPoint[0], toPolygon, *m_searchPoint[1], + m_pathfindingDebugToolVehicleId, m_path) != 2) + { + while (m_engine->m_searches[resource]->m_status == 1) + m_engine->update(10.0); + localSearch(resource, m_pathfindingDebugToolVehicleId != 3, island, fromPolygon, + *m_searchPoint[0], toPolygon, *m_searchPoint[1], + m_pathfindingDebugToolVehicleId, m_path); + } + } + else + { + m_debugClusterPath->m_nodes.resize(0); + m_debugClusterPath->m_i0 = 0; + if (clusterSearch(resource, m_pathfindingDebugToolVehicleId != 3, island, fromPolygon, + *m_searchPoint[0], toPolygon, *m_searchPoint[1], + m_pathfindingDebugToolVehicleId, m_debugClusterPath) != 2) + { + while (m_clusterEngine->m_searches[resource]->m_status == 1) + m_clusterEngine->update(10.0); + clusterSearch(resource, m_pathfindingDebugToolVehicleId != 3, island, fromPolygon, + *m_searchPoint[0], toPolygon, *m_searchPoint[1], + m_pathfindingDebugToolVehicleId, m_debugClusterPath); + } + } + if (!m_clusterSearch) + releaseResource(resource, 2000); + else + releaseClusterResource(resource, 2000); } -bool AIPathfinding::tryPath(const Vec3&, const Vec3&) +// ELF 0x3A4D30. Failed endpoint lookup leaves the acquired debug resource owned, as shipped. +void AIPathfinding::tryPath(const Vec3& from, const Vec3& to) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::tryPath"); + unsigned int resource = 0xFFFFFFFFu; + if (!acquireResource(resource, 2000)) + return; + AIRenderUtil::m_instance->unrendenderPathfindingDebug(); + m_searchPointToSet = 2; + m_d36 = -1000.0; + *m_searchPoint[0] = from; + *m_searchPoint[1] = to; + m_path->m_nodes.resize(0); + m_path->m_i0 = 0; + m_path->m_i20 = 0.0f; + unsigned int fromPolygon, island, toPolygon; + getPolygon(*m_searchPoint[0], m_pathfindingDebugToolVehicleId != 3, + fromPolygon, island, m_pathfindingDebugToolVehicleId); + if (island == 0xFFFFFFFFu || fromPolygon == 0xFFFFFFFFu) + return; + getPolygonFromIsland(*m_searchPoint[1], m_pathfindingDebugToolVehicleId != 3, + toPolygon, island, m_pathfindingDebugToolVehicleId); + if (toPolygon == 0xFFFFFFFFu) + return; + m_path->m_nodes.resize(0); + m_path->m_i0 = 0; + m_path->m_i20 = 0.0f; + if (localSearch(resource, m_pathfindingDebugToolVehicleId != 3, island, fromPolygon, + *m_searchPoint[0], toPolygon, *m_searchPoint[1], + m_pathfindingDebugToolVehicleId, m_path) != 2) + { + while (m_engine->m_searches[resource]->m_status == 1) + m_engine->update(10.0); + localSearch(resource, m_pathfindingDebugToolVehicleId != 3, island, fromPolygon, + *m_searchPoint[0], toPolygon, *m_searchPoint[1], + m_pathfindingDebugToolVehicleId, m_path); + } + releaseResource(resource, 2000); } -bool AIPathfinding::tryClusterPath(const Vec3&, const Vec3&) +// ELF 0x3A5060. Clears the local path first even for a cluster search. +void AIPathfinding::tryClusterPath(const Vec3& from, const Vec3& to) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::tryClusterPath"); + unsigned int resource = 0xFFFFFFFFu; + if (!acquireClusterResource(resource, 2000)) + return; + AIRenderUtil::m_instance->unrendenderPathfindingDebug(); + m_searchPointToSet = 2; + m_d36 = -1000.0; + *m_searchPoint[0] = from; + *m_searchPoint[1] = to; + m_path->m_nodes.resize(0); + m_path->m_i0 = 0; + m_path->m_i20 = 0.0f; + unsigned int fromPolygon, island, toPolygon; + getPolygon(*m_searchPoint[0], m_pathfindingDebugToolVehicleId != 3, + fromPolygon, island, m_pathfindingDebugToolVehicleId); + if (island == 0xFFFFFFFFu || fromPolygon == 0xFFFFFFFFu) + return; + getPolygonFromIsland(*m_searchPoint[1], m_pathfindingDebugToolVehicleId != 3, + toPolygon, island, m_pathfindingDebugToolVehicleId); + if (toPolygon == 0xFFFFFFFFu) + return; + m_debugClusterPath->m_nodes.resize(0); + m_debugClusterPath->m_i0 = 0; + if (clusterSearch(resource, m_pathfindingDebugToolVehicleId != 3, island, fromPolygon, + *m_searchPoint[0], toPolygon, *m_searchPoint[1], + m_pathfindingDebugToolVehicleId, m_debugClusterPath) != 2) + { + while (m_clusterEngine->m_searches[resource]->m_status == 1) + m_clusterEngine->update(10.0); + clusterSearch(resource, m_pathfindingDebugToolVehicleId != 3, island, fromPolygon, + *m_searchPoint[0], toPolygon, *m_searchPoint[1], + m_pathfindingDebugToolVehicleId, m_debugClusterPath); + } + releaseClusterResource(resource, 2000); } -void AIPathfinding::setActivatePathfindingDebugTool(bool) +// ELF 0x3A6750. Disabling clears only the polygon path and the endpoint selection. +void AIPathfinding::setActivatePathfindingDebugTool(bool active) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::setActivatePathfindingDebugTool"); + m_activatePathfindingDebugTool = active; + if (!active) + { + m_path->m_nodes.resize(0); + m_path->m_i0 = 0; + m_path->m_i20 = 0.0f; + m_searchPointToSet = 0; + } } -void* AIPathfinding::getEquipmentTypeFromClusterCostType(int, unsigned short) const +// ELF 0x3AE230. Returns the settings vehicle ID for the map's cluster-cost vehicle name. +int AIPathfinding::getEquipmentTypeFromClusterCostType(int map, unsigned short type) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::getEquipmentTypeFromClusterCostType"); + return static_cast(CommonSingletonServer::m_iaiSettings) + ->getVehicle(m_maps[map]->m_clusterCostVehicles[type]); } -// IAIPathfindingSetup, the half that is now one body shorter - // Allocates the search-resource pool: one resource per four bots, with a minimum of two. +// ELF 0x3A33F0. void AIPathfinding::init() { IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); @@ -1081,16 +2021,16 @@ void AIPathfinding::init() resource->m_maxIterations = 30000; m_engine->m_searches.push_back(resource); - resource->m_i16 = 0; + resource->m_iterations = 0; resource->m_openSize = 21; resource->m_hashSize = 1031; resource->m_open = checkPointer(new BinarySearchTree(21)); - resource->m_closed = + resource->m_openOverflow = checkPointer(new Hash(1031)); - resource->m_cache = + resource->m_closed = checkPointer(new Hash(1031)); - resource->m_closed->m_nodeManager = resource->m_nodeManager; - resource->m_cache->m_nodeManager = resource->m_nodeManager; + resource->m_openOverflow->m_nodeManager = resource->m_nodeManager; + resource->m_closed->m_nodeManager = resource->m_nodeManager; m_engine->m_available.push_back( static_cast(m_engine->m_searches.size() - 1)); @@ -1101,16 +2041,16 @@ void AIPathfinding::init() clusterResource->m_maxIterations = 5000; m_clusterEngine->m_searches.push_back(clusterResource); - clusterResource->m_i16 = 0; + clusterResource->m_iterations = 0; clusterResource->m_openSize = 13; clusterResource->m_hashSize = 313; clusterResource->m_open = checkPointer(new BinarySearchTree(13)); - clusterResource->m_closed = + clusterResource->m_openOverflow = checkPointer(new Hash(313)); - clusterResource->m_cache = + clusterResource->m_closed = checkPointer(new Hash(313)); - clusterResource->m_closed->m_nodeManager = clusterResource->m_nodeManager; - clusterResource->m_cache->m_nodeManager = clusterResource->m_nodeManager; + clusterResource->m_openOverflow->m_nodeManager = clusterResource->m_nodeManager; + clusterResource->m_closed->m_nodeManager = clusterResource->m_nodeManager; m_clusterEngine->m_available.push_back( static_cast(m_clusterEngine->m_searches.size() - 1)); @@ -1118,6 +2058,7 @@ void AIPathfinding::init() } // Creates and selects a named map. Duplicate names fail and clear the active selection. +// ELF 0x3A6820. bool AIPathfinding::createMap(const std::string& name) { if (m_mapIds.find(name) != m_mapIds.end()) @@ -1137,6 +2078,7 @@ bool AIPathfinding::createMap(const std::string& name) } // Deletes the active map. The supplied map argument does not select the map to remove. +// ELF 0x3A6BA0. bool AIPathfinding::deleteMap(const std::string& name) { const std::map::iterator i = m_mapIds.find(name); @@ -1152,12 +2094,15 @@ bool AIPathfinding::deleteMap(const std::string& name) return true; } +// ELF 0x3A6FE0. void AIPathfinding::saveQuadTrees() { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::saveQuadTrees"); + for (std::vector::iterator i = m_maps.begin(); i != m_maps.end(); ++i) + (*i)->saveQuadTrees(); } // Loads quad trees and notifies the strategic layer after loading. +// ELF 0x3A7020. void AIPathfinding::loadQuadTrees() { for (std::vector::iterator i = m_maps.begin(); i != m_maps.end(); ++i) @@ -1166,30 +2111,266 @@ void AIPathfinding::loadQuadTrees() AIStrategicObjectManager::getInstance()->initAreas(); } +// ELF 0x3A7070. void AIPathfinding::loadGTSData() { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::loadGTSData"); + int map = 0; + for (std::vector::iterator i = m_maps.begin(); i != m_maps.end(); ++i) + { + const float radius = (*i)->getRadius(); + (*i)->loadGTSData(map++, radius); + } + AIStrategicObjectManager::getInstance()->initAreas(); } +// ELF 0x3AD260. bool AIPathfinding::exportGTSMeshes() const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::exportGTSMeshes"); -} - -bool AIPathfinding::exportGTSMeshesWithinBoundary(const Vec2&, const Vec2&) const -{ - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::exportGTSMeshesWithinBoundary"); + std::list meshes; + std::list water; + std::map addOns; + std::list ladders; + std::pair bounds = {}; + IAIObjectEnvironment* const environment = + static_cast(CommonSingletonServer::m_iaiObjectEnvironment); + if (!environment->initAiCombatAreas()) + return false; + const std::string overgrowth = static_cast(CommonSingletonServer::m_iaiGame) + ->getLevelPath() + "/overgrowth/OvergrowthCollision.con"; + if (!environment->loadOvergrowthCollision(overgrowth)) + return false; + const unsigned char layer = static_cast(environment->getAiCombatAreaLayer()); + if (!environment->getAllStaticCollisionMeshes(meshes, water, addOns, ladders, bounds, layer)) + return false; + std::vector vertices; + std::vector> edges; + std::list> faces; + IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + terrain->getAllTerrainPolygons(bounds, vertices, edges, faces); + if (!MeshImporterExporter::exportMesh(vertices, edges, faces, "Ground")) + return false; + return createGTSFiles(meshes, water, addOns, ladders, terrain, layer); } -// 18,942 bytes in retail - the offline level compiler. Nothing on a server route reaches it. -bool AIPathfinding::createGTSFiles(std::list&, std::list&, - std::map&, std::list&, - IAITerrain*, unsigned char) const +// ELF 0x3ADA70. +bool AIPathfinding::exportGTSMeshesWithinBoundary(const Vec2& min, const Vec2& max) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::createGTSFiles"); + std::list meshes; + std::list water; + std::map addOns; + std::list ladders; + std::pair bounds = {}; + IAIObjectEnvironment* const environment = + static_cast(CommonSingletonServer::m_iaiObjectEnvironment); + if (!environment->initAiCombatAreas()) + return false; + const std::string overgrowth = static_cast(CommonSingletonServer::m_iaiGame) + ->getLevelPath() + "/overgrowth/OvergrowthCollision.con"; + if (!environment->loadOvergrowthCollision(overgrowth)) + { + Debug(DebugTypeError, "AI/AIDLL/AI/Main/AIPathfinding.cpp", 2653, "") + << "Couldn't load OvergrowthCollision.con\nABORTING EXPORT!"; + // shipped defect: if the diagnostic is filtered, export continues. + } + const unsigned char layer = static_cast(environment->getAiCombatAreaLayer()); + if (!environment->getAllStaticCollisionMeshesWithinBoundary( + min, max, meshes, water, addOns, ladders, bounds, layer)) + return false; + std::vector vertices; + std::vector> edges; + std::list> faces; + IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + terrain->getAllTerrainPolygonsWithinBoundary(bounds, min, max, vertices, edges, faces); + if (!MeshImporterExporter::exportMesh(vertices, edges, faces, "Ground")) + return false; + return createGTSFiles(meshes, water, addOns, ladders, terrain, layer); +} + +// ELF 0x3A86D0. Resets the stream contents and appends a prefix and five-digit decimal index. +void getFileName(std::stringstream& stream, const std::string& prefix, int index) +{ + stream.str(""); + stream << prefix; + if (index <= 9) + stream << "0000" << index; + else if (index <= 99) + stream << "000" << index; + else if (index <= 999) + stream << "00" << index; + else if (index <= 9999) + stream << "0" << index; + else + stream << index; +} + +// ELF 0x3A8860. Exports navigation input meshes and the generator configuration. +bool AIPathfinding::createGTSFiles( + std::list& meshes, + std::list& water, + std::map& addOns, + std::list& ladders, + IAITerrain* terrain, unsigned char layer) const +{ + bool success = false; + MapContainer* const infantry = m_maps[0]; + MapContainer* const vehicle = m_maps[1]; + std::stringstream config; + config << "MaxSlopeInfantry: " << infantry->getMaxSlope() << std::endl; + config << "MaxSlopeVehicle: " << vehicle->getMaxSlope() << std::endl; + config << "RadiusInfantry: " << infantry->getRadius() << std::endl; + config << "RadiusVehicle: " << vehicle->getRadius() << std::endl; + config << "HeadClearanceInfantry: " << infantry->getHeadClearance() << std::endl; + config << "HeadClearanceVehicle: " << vehicle->getHeadClearance() << std::endl; + config << "MaxWaterDepth: " << getMaxWaterDepth() << std::endl; + config << "WaterLevel: " << terrain->getSeaWaterLevel() << std::endl; + std::vector infantryPoints; + static_cast(CommonSingletonServer::m_iaiGame) + ->getSpawnPointPositions(infantryPoints, layer); + config << "Infantry_NumberOfKeyPoints: " << infantryPoints.size() << std::endl; + for (unsigned int i = 0; i < infantryPoints.size(); ++i) + config << infantryPoints[i].x << " " << infantryPoints[i].y << " " + << infantryPoints[i].z << std::endl; + std::vector vehiclePoints; + static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->getVehicleSpawnerPositions(vehiclePoints, layer); + config << "Vehicle_NumberOfKeyPoints: " << vehiclePoints.size() << std::endl; + for (unsigned int i = 0; i < vehiclePoints.size(); ++i) + config << vehiclePoints[i].x << " " << vehiclePoints[i].y << " " + << vehiclePoints[i].z << std::endl; + std::stringstream meshName, boxName, addOnName; + config << "NumberOfMeshes: " << meshes.size() << std::endl; + int meshIndex = 0; + for (std::list::iterator i = meshes.begin(); + i != meshes.end(); ++i) + { + getFileName(meshName, "Object", meshIndex); + getFileName(boxName, "ObjectBB", meshIndex); + // shipped defect: each ordinary mesh overwrites previous export failures. + success = MeshImporterExporter::exportMesh(i->mesh.vertices, i->mesh.edges, + i->mesh.faces, meshName.str()) && + MeshImporterExporter::exportMesh(i->boundingBox.vertices, i->boundingBox.edges, + i->boundingBox.faces, boxName.str()); + config << meshName.str() << " " << i->name << std::endl; + meshName.str(""); + boxName.str(""); + ++meshIndex; + } + config << "NumberOfDestructableMeshes: " << addOns.size() << std::endl; + int addOnIndex = 0; + for (std::map::iterator + i = addOns.begin(); i != addOns.end(); ++i) + { + const std::string walkable = i->second.initiallyWalkable ? "IW" : "INW"; + getFileName(addOnName, "ObjectDestr", addOnIndex); + config << addOnName.str() << " " << walkable << std::endl; + success = success && MeshImporterExporter::exportMesh( + i->second.mesh.vertices, i->second.mesh.edges, + i->second.mesh.faces, addOnName.str()); + ++addOnIndex; + } + std::stringstream waterName; + config << "NumberOfWaterMeshes: " << water.size() << std::endl; + int waterIndex = 0; + for (std::list::iterator i = water.begin(); + i != water.end(); ++i) + { + getFileName(waterName, "ObjectWaterMesh", waterIndex); + success = success && MeshImporterExporter::exportMesh( + i->mesh.vertices, i->mesh.edges, i->mesh.faces, waterName.str()); + config << waterName.str() << std::endl; + ++waterIndex; + waterName.str(""); + } + config << "NumberOfLadders: " << ladders.size() << std::endl; + int ladderIndex = 0; + for (std::list::iterator i = ladders.begin(); + i != ladders.end(); ++i) + { + getFileName(meshName, "Ladder", ladderIndex); + getFileName(boxName, "LaddertBB", ladderIndex); + // shipped defect: ladders also overwrite the accumulated failure status. + success = MeshImporterExporter::exportMesh(i->mesh.vertices, i->mesh.edges, + i->mesh.faces, meshName.str()) && + MeshImporterExporter::exportMesh(i->boundingBox.vertices, i->boundingBox.edges, + i->boundingBox.faces, boxName.str()); + config << meshName.str() << " " << i->name << std::endl; + meshName.str(""); + boxName.str(""); + ++ladderIndex; + } + const std::string levelPath = static_cast(CommonSingletonServer::m_iaiGame) + ->getLevelPath(); + bool deleted; + do + { + deleted = false; + getFileName(meshName, "Object", meshIndex); + getFileName(boxName, "ObjectBB", meshIndex); + getFileName(addOnName, "ObjectDestr", addOnIndex); + if (io::fileManager->fileExists(levelPath + "/GTSData/Meshes/" + meshName.str() + ".gts")) + { + io::fileManager->deleteFile(levelPath + "/GTSData/Meshes/" + meshName.str() + ".gts"); + deleted = true; + } + if (io::fileManager->fileExists(levelPath + "/GTSData/Meshes/" + boxName.str() + ".gts")) + { + io::fileManager->deleteFile(levelPath + "/GTSData/Meshes/" + boxName.str() + ".gts"); + deleted = true; + } + if (io::fileManager->fileExists(levelPath + "/GTSData/Meshes/" + addOnName.str() + ".gts")) + { + io::fileManager->deleteFile(levelPath + "/GTSData/Meshes/" + addOnName.str() + ".gts"); + deleted = true; + } + ++meshIndex; + ++addOnIndex; + meshName.str(""); + boxName.str(""); + addOnName.str(""); + getFileName(meshName, "Ladder", ladderIndex); + getFileName(boxName, "LaddertBB", ladderIndex); + if (io::fileManager->fileExists(levelPath + "/GTSData/Meshes/" + meshName.str() + ".gts")) + { + io::fileManager->deleteFile(levelPath + "/GTSData/Meshes/" + meshName.str() + ".gts"); + deleted = true; + } + if (io::fileManager->fileExists(levelPath + "/GTSData/Meshes/" + boxName.str() + ".gts")) + { + io::fileManager->deleteFile(levelPath + "/GTSData/Meshes/" + boxName.str() + ".gts"); + deleted = true; + } + ++ladderIndex; + meshName.str(""); + boxName.str(""); + } while (deleted); + { + io::File file; + if (!file.open(levelPath + "/GTSData/Meshes/config.dat", + static_cast(0), static_cast(1), 0)) + return false; + file.write(config.str()); + file.close(); + } + { + io::File file; + if (!file.open(levelPath + "/GTSData/Meshes/CombatArea.dat", + static_cast(0), static_cast(1), 0)) + return false; + std::stringstream combatArea; + std::list points; + static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->getAICombatArea(points); + combatArea << points.size() << std::endl; + for (std::list::iterator i = points.begin(); i != points.end(); ++i) + combatArea << i->x << " " << i->y << std::endl; + file.write(combatArea.str()); + file.close(); + } + return success; } // Returns virtual getName results joined by newlines, with no trailing newline. +// ELF 0x3A6E90. std::string AIPathfinding::getMapList() { std::string list; @@ -1205,103 +2386,24 @@ std::string AIPathfinding::getMapList() return list; } +// ELF 0x3A09C0. Draws a line between each object's two transformed bounds corners. void AIPathfinding::drawDynamicAIObjects() const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::drawDynamicAIObjects"); -} - -// Console bindings for pathfinding configuration and map loading. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. - -// a free function of the generated console TU: the setup's active map, or null -// without a setup. Every `map.*` binding reads through it, and tests it. -IAIPathfindingSetup::IMapContainer* getActiveMapContainer() -{ - if (!IAIPathfindingSetup::instance) - return 0; - return IAIPathfindingSetup::instance->getActiveMapContainer(); // +0x50 -} - -namespace { - -const char* const kAiPathfindingConsoleTag = "aiPathfinding"; - -// No null test on the instance: the binding's isObjectActive is the guard, as in the executor. -bool consoleAiPathfindingCreateMap(const std::string& name) -{ - return IAIPathfindingSetup::instance->createMap(name); // +0x10 -} - -} // anonymous namespace - -BF2_CONSOLE_OBJECT("AIPathFinding", 2, 0) -BF2_CONSOLE_METHOD_1_RET_ACTIVE(createMap, consoleAiPathfindingCreateMap, bool, - IAIPathfindingSetup::instance != 0, std::string, - kAiPathfindingConsoleTag) -BF2_CONSOLE_PROPERTY_FN(activeMap, std::string, IAIPathfindingSetup::instance != 0, - IAIPathfindingSetup::instance->getActiveMap(), - IAIPathfindingSetup::instance->setActiveMap, kAiPathfindingConsoleTag) -BF2_CONSOLE_PROPERTY_FN(traceMap, std::string, IAIPathfindingSetup::instance != 0, - IAIPathfindingSetup::instance->getTraceMap(), - IAIPathfindingSetup::instance->setTraceMap, kAiPathfindingConsoleTag) -BF2_CONSOLE_PROPERTY_FN_NAMED("map.maxSlope", float, getActiveMapContainer() != 0, - getActiveMapContainer()->getMaxSlope(), - getActiveMapContainer()->setMaxSlope, kAiPathfindingConsoleTag) -BF2_CONSOLE_PROPERTY_FN_NAMED("map.headClearance", float, getActiveMapContainer() != 0, - getActiveMapContainer()->getHeadClearance(), - getActiveMapContainer()->setHeadClearance, kAiPathfindingConsoleTag) -BF2_CONSOLE_PROPERTY_FN_NAMED("map.radius", float, getActiveMapContainer() != 0, - getActiveMapContainer()->getRadius(), - getActiveMapContainer()->setRadius, kAiPathfindingConsoleTag) -BF2_CONSOLE_PROPERTY_FN_NAMED("map.allowedHeightDiff", float, getActiveMapContainer() != 0, - getActiveMapContainer()->getAllowedHeightDiff(), - getActiveMapContainer()->setAllowedHeightDiff, kAiPathfindingConsoleTag) - -// map.addVehicleForClusterCost is family 1a (BF2_CONSOLE_METHOD_1_ACTIVE's shape: type 0, exactly one -// argument, "void", a real availability test) under a console spelling with a dot in it, which that -// macro cannot take. [CHOSEN] A one-shot local macro with the named head: everything expands inside -// one macro invocation, so `BF2_CC_NAME`'s __LINE__ agrees between the class and its constructor (a -// hand-written class would not). Core/ConsoleObjectMacro.h is another front's live file and is not -// touched for one binding. -#define BF2_AIPATHFINDING_CONSOLE_METHOD_1_ACTIVE_NAMED(fnNameLiteral, target, activeExpr, A0, listTag) \ -namespace { \ -class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl \ -{ \ - BF2_CC_HEAD_NAMED(fnNameLiteral, 0, 1, 1, "void", true) \ - m_argTypes[0] = #A0; \ - BF2_CC_TAIL(1, listTag) \ - virtual bool isObjectActive() const { return (activeExpr); } \ - virtual void executeObjectMethod() \ - { \ - if (m_argCount != 1) return; \ - m_hasReturnValue = false; \ - target(BF2_CC_ARG(A0, 0)); \ - } \ - virtual void setArgFromString(int index, const std::string& value) \ - { \ - BF2_CC_CONVERT(A0, 1) \ - } \ - BF2_CC_NO_RETURN_AS_STRING \ - BF2_CC_COMMON_HOOKS \ -}; \ -static BF2_CC_NAME BF2_CC_INSTANCE; \ -} - -BF2_AIPATHFINDING_CONSOLE_METHOD_1_ACTIVE_NAMED("map.addVehicleForClusterCost", - getActiveMapContainer()->addVehicleForClusterCost, - getActiveMapContainer() != 0, std::string, - kAiPathfindingConsoleTag) -#undef BF2_AIPATHFINDING_CONSOLE_METHOD_1_ACTIVE_NAMED - -BF2_CONSOLE_PROPERTY_FN(maxWaterDepth, float, IAIPathfindingSetup::instance != 0, - IAIPathfindingSetup::instance->getMaxWaterDepth(), - IAIPathfindingSetup::instance->setMaxWaterDepth, kAiPathfindingConsoleTag) - -// Handed to the console registry by AIModule::init, beside the `ai`, `aiSettings` and -// `aiStrategicArea` lists. -ConsoleObjectList& aiPathfindingConsoleObjects() -{ - return consoleBindingList(kAiPathfindingConsoleTag); + std::vector objects; + static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->getAllDestroyableObjects(objects); + for (std::vector::iterator i = objects.begin(); i != objects.end(); ++i) + { + const float* const m = i->transform.m; + const Vec3 from = {i->min.x * m[0] + i->min.y * m[4] + i->min.z * m[8] + m[12], + i->min.x * m[1] + i->min.y * m[5] + i->min.z * m[9] + m[13], + i->min.x * m[2] + i->min.y * m[6] + i->min.z * m[10] + m[14]}; + const Vec3 to = {i->max.x * m[0] + i->max.y * m[4] + i->max.z * m[8] + m[12], + i->max.x * m[1] + i->max.y * m[5] + i->max.z * m[9] + m[13], + i->max.x * m[2] + i->max.y * m[6] + i->max.z * m[10] + m[14]}; + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticLine(60.0f, 0, from, to, 0.05f); + } } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIPathfinding.h b/Code/BF2/AI/AIDLL/AI/Main/AIPathfinding.h index 841cd31c2..6c72b24e7 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIPathfinding.h +++ b/Code/BF2/AI/AIDLL/AI/Main/AIPathfinding.h @@ -1,6 +1,5 @@ // Pathfinding queries and map lifecycle through separate query and setup interfaces. // Use typed interface conversions for the secondary base subobject. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. #ifndef AI_AIDLL_AI_MAIN_AIPATHFINDING_H #define AI_AIDLL_AI_MAIN_AIPATHFINDING_H @@ -16,6 +15,7 @@ #include "../AIPathFinding/NavMesh/QuadTreeManager.h" // and one of these #include "AIPathfindingSearchTypes.h" // QTPath, ClusterNodePath, PathfindingEngine #include "IAIPathfinding.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" namespace dice { namespace hfe { @@ -42,24 +42,24 @@ class AIPathfinding : public IAIPathfinding, public IAIPathfindingSetup virtual ~MapContainer(); // IMapContainer, slots 2..29, in vtable order - virtual const std::string& getName(); - virtual int getMinPolygonsInLeaf(); + virtual const std::string& getName() const; + virtual int getMinPolygonsInLeaf() const; virtual void setMinPolygonsInLeaf(int); - virtual int getMaxDepthInTree(); + virtual int getMaxDepthInTree() const; virtual void setMaxDepthInTree(int); - virtual float getMaxSlope(); + virtual float getMaxSlope() const; virtual void setMaxSlope(float); virtual void setHeadClearance(float); - virtual float getHeadClearance(); + virtual float getHeadClearance() const; virtual void setRadius(float); - virtual float getRadius(); + virtual float getRadius() const; virtual void setAllowedHeightDiff(float); - virtual float getAllowedHeightDiff(); - virtual void draw(); - virtual void undraw(); - virtual void drawCluster(); - virtual void undrawCluster(); - virtual void drawClusterNeighbourIndices(const Vec3&); + virtual float getAllowedHeightDiff() const; + virtual void draw() const; + virtual void undraw() const; + virtual void drawCluster() const; + virtual void undrawCluster() const; + virtual void drawClusterNeighbourIndices(const Vec3&) const; virtual void loadGTSDebugMeshes(); virtual void buildDebugMeshes(); virtual void unloadDebugMeshes(); @@ -78,7 +78,7 @@ class AIPathfinding : public IAIPathfinding, public IAIPathfindingSetup bool isValidPosition(const Vec3&, MaterialManager *, bool) const; bool isValidPosition(const Vec3&, MaterialManager *, unsigned int, bool) const; bool isValidPosition(const Vec3&, MaterialManager *, unsigned int, unsigned int, bool) const; - bool getPolygon(std::vector&, Vec3&, unsigned int&, unsigned int&, MaterialManager *) const; + bool getPolygon(std::vector&, const Vec3&, unsigned int&, unsigned int&, MaterialManager *) const; bool getPolygon(std::vector&, unsigned int, unsigned int) const; bool getPolygon(const Vec3&, unsigned int&, unsigned int&, MaterialManager *) const; bool getPolygon(const Vec3&, unsigned int&, unsigned int&, unsigned int, unsigned int, MaterialManager *) const; @@ -89,13 +89,13 @@ class AIPathfinding : public IAIPathfinding, public IAIPathfindingSetup bool getMaterial(unsigned int, unsigned int, unsigned char&) const; bool setMaterial(unsigned int, unsigned int, unsigned char); void getPolygonCentre(Vec3&, unsigned int, unsigned int) const; - void getEdge(Vec3&, Vec3&, unsigned int, unsigned int, unsigned int) const; + bool getEdge(Vec3&, Vec3&, unsigned int, unsigned int, unsigned int) const; bool trace(unsigned int&, unsigned int&, const Vec3&, const Vec3&, Vec3&, unsigned int&, int, float, MaterialManager *, unsigned char, unsigned char *) const; bool traceKnown(unsigned int, unsigned int, const Vec3&, const Vec3&, Vec3&, unsigned int&, int, float, MaterialManager *, unsigned char, unsigned char *) const; bool getLineIntersectionWithPolygon(Vec3&, unsigned int, unsigned int, const Vec3&, const Vec3&) const; void drawPolygon(unsigned int, unsigned int, float *, float) const; bool findClosestValidPolygon(unsigned int&, unsigned int&, Vec3&, const Vec3&, const Vec3&, unsigned int, MaterialManager *) const; - void updateClusterPortalCosts(unsigned int&, triple&, unsigned int, unsigned short); + bool updateClusterPortalCosts(unsigned int&, triple&, unsigned int, unsigned short); // the layout, from the 720-byte constructor /* +4 */ int m_id; // = the caller's index into AIPathfinding::m_maps @@ -126,26 +126,26 @@ class AIPathfinding : public IAIPathfinding, public IAIPathfindingSetup virtual bool isValidPosition(int, int, const Vec3&, bool) const; virtual bool isValidPosition(int, int, const Vec3&, unsigned int, bool) const; virtual bool isValidPosition(int, int, const Vec3&, unsigned int, unsigned int, bool) const; - virtual int getPolygon(std::vector&, int, const Vec3&, int) const; - virtual int getPolygon(std::vector&, int, const Vec3&, unsigned int&, unsigned int&, int) const; - virtual int getPolygon(std::vector&, int, unsigned int, unsigned int) const; + virtual bool getPolygon(std::vector&, int, const Vec3&, int) const; + virtual bool getPolygon(std::vector&, int, const Vec3&, unsigned int&, unsigned int&, int) const; + virtual bool getPolygon(std::vector&, int, unsigned int, unsigned int) const; virtual bool getPolygon(const Vec3&, int, unsigned int&, unsigned int&, int) const; virtual bool getPolygon(const Vec3&, int, unsigned int&, unsigned int&, unsigned int, unsigned int, int) const; virtual void getPolygonsInRadius(std::list&, int, unsigned int, unsigned int, const Vec3&, float) const; virtual void getPolygonsInTriangle(std::list&, int, unsigned int, unsigned int, const Vec3&, const Vec3&, const Vec3&) const; - virtual int getPolygonFromIsland(const Vec3&, int, unsigned int&, unsigned int, int) const; + virtual bool getPolygonFromIsland(const Vec3&, int, unsigned int&, unsigned int, int) const; virtual bool getMaterial(const Vec3&, int, int, unsigned char&) const; virtual bool getMaterial(int, unsigned int, unsigned int, unsigned char&) const; - virtual void setMaterial(int, unsigned int, unsigned int, unsigned char) const; + virtual bool setMaterial(int, unsigned int, unsigned int, unsigned char) const; virtual void* getQuadTree(int, unsigned int) const; virtual void* getClusterGraph(int, unsigned int) const; virtual void getPolygonCentre(Vec3&, int, unsigned int, unsigned int) const; - virtual void getEdge(Vec3&, Vec3&, int, unsigned int, unsigned int, unsigned int) const; + virtual bool getEdge(Vec3&, Vec3&, int, unsigned int, unsigned int, unsigned int) const; virtual bool getLineIntersectionWithPolygon(Vec3&, int, unsigned int, unsigned int, const Vec3&, const Vec3&) const; virtual void drawPolygon(int, unsigned int, unsigned int, float *, float) const; virtual int getClusterOfPolygon(int, unsigned int, unsigned int) const; virtual bool areNeighbouringClusters(int, unsigned int, unsigned short, unsigned short) const; - virtual void updateClusterPortalCosts(unsigned int&, triple&, int, unsigned int, unsigned short); + virtual bool updateClusterPortalCosts(unsigned int&, triple&, int, unsigned int, unsigned short); virtual bool trace(int, const Vec3&, const Vec3&, Vec3&, unsigned int&, int, int, float, unsigned char, unsigned char *) const; virtual bool trace(unsigned int, unsigned int, int, const Vec3&, const Vec3&, Vec3&, unsigned int&, int, int, float, unsigned char, unsigned char *) const; virtual bool trace(BotNavigation *, bool, const Vec3&, Vec3&, unsigned int&, int, int, float, unsigned char, unsigned char *) const; @@ -173,14 +173,14 @@ class AIPathfinding : public IAIPathfinding, public IAIPathfindingSetup virtual void restoreMapPart(int); virtual void resetOriginalMaterialOfDestroyableMapPart(int); virtual void searchPointSelected(bool); - virtual bool tryPath(const Vec3&, const Vec3&); - virtual bool tryClusterPath(const Vec3&, const Vec3&); + virtual void tryPath(const Vec3&, const Vec3&); + virtual void tryClusterPath(const Vec3&, const Vec3&); virtual void setClusterSearch(bool); virtual bool getClusterSearch() const; virtual void setActivatePathfindingDebugTool(bool); virtual bool getActivatePathfindingDebugTool() const; virtual void setPathfindingDebugToolVehicle(const std::string&); - virtual void* getPathfindingDebugToolVehicle() const; + virtual const std::string& getPathfindingDebugToolVehicle() const; virtual void setPathfindingDebugToolVehicleId(int); virtual int getClusterCostType(int, unsigned int) const; @@ -199,10 +199,12 @@ class AIPathfinding : public IAIPathfinding, public IAIPathfindingSetup virtual void loadGTSData(); virtual bool exportGTSMeshes() const; virtual bool exportGTSMeshesWithinBoundary(const Vec2&, const Vec2&) const; - // 18,942 bytes. The offline level-compile path: it turns the level's meshes, water and - // destroyable add-ons into GTS files. Editor work; nothing on a server route reaches it. - virtual bool createGTSFiles(std::list&, std::list&, std::map&, - std::list&, IAITerrain *, unsigned char) const; + // Exports level meshes, water, ladders and destroyable add-ons for navigation generation. + virtual bool createGTSFiles(std::list&, + std::list&, + std::map&, + std::list&, + IAITerrain*, unsigned char) const; virtual IAIPathfindingSetup::IMapContainer* getActiveMapContainer() const; virtual std::string getMapList(); virtual void setMaxWaterDepth(float); @@ -219,7 +221,19 @@ class AIPathfinding : public IAIPathfinding, public IAIPathfindingSetup ClusterNodePath* getDebugClusterPath() const; Vec3* getSearchPoint(int) const; bool isValidClusterType(int, unsigned int) const; - void* getEquipmentTypeFromClusterCostType(int, unsigned short) const; + // ELF 0x3A5E10. The blocking variant for ClusterGraph::calculatePortalCosts: acquires its own + // resource, runs the search to completion and appends one cost to `costs`; see the definition. + void getPortalCost(std::vector& costs, unsigned short costType, int map, + unsigned int island, const Vec3& from, unsigned int fromPolygon, + const Vec3& to, unsigned int toPolygon, + const std::set& allowedClusters); + // ELF 0x3A63B0. One portal-to-portal local search for ClusterGraph::updatePortalCosts; see + // the definition. False while the search is still running. + bool getPortalCost(float& cost, unsigned int resource, int map, unsigned int island, + unsigned short costType, const Vec3& from, unsigned int fromPolygon, + const Vec3& to, unsigned int toPolygon, + const std::set& allowedClusters); + int getEquipmentTypeFromClusterCostType(int, unsigned short) const; private: // The original layout has base-interface vptrs at +0 and +4; secondary-base calls @@ -231,9 +245,9 @@ class AIPathfinding : public IAIPathfinding, public IAIPathfindingSetup // Both elements are separately heap-allocated zeroed `Vec3`s; `tryPath` writes the caller's two // positions straight into them. /* +20 */ Vec3* m_searchPoint[2]; - /* +28 */ QTPath* m_debugPath; // = new QTPath + /* +28 */ QTPath* m_path; // = new QTPath // name: AIDLL_r asserts 0x100A70E0 (PE +0x1C) /* +32 */ ClusterNodePath* m_debugClusterPath; // = new ClusterNodePath - /* +36 */ double m_d36; // = -1000.0; reset and tryPath restore it [UNRESOLVED] + /* +36 */ double m_d36; // Last debug endpoint selection time; reset sentinel -1000.0. /* +44 */ bool m_clusterSearch; // = false; the debug tool's cluster/local toggle /* +48 */ PathfindingEngine* m_engine; diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIPathfindingSearchTypes.h b/Code/BF2/AI/AIDLL/AI/Main/AIPathfindingSearchTypes.h index caff74315..81b7501e3 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIPathfindingSearchTypes.h +++ b/Code/BF2/AI/AIDLL/AI/Main/AIPathfindingSearchTypes.h @@ -1,15 +1,14 @@ // Shared path containers, node records and reusable A* search resources. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining AIPathfindingSearchTypes operations. #ifndef AI_AIDLL_AI_MAIN_AIPATHFINDINGSEARCHTYPES_H #define AI_AIDLL_AI_MAIN_AIPATHFINDINGSEARCHTYPES_H #include +#include #include #include #include "IAIPathfinding.h" // ai::triple, and Vec3 through AIDllTypes.h -#include "AIDllFrontier.h" // AStarResource::update's named stop #include "CommonSingletonServer.h" // PathfindingEngine::update's clock #include "../../../AIInterface/BFKnowledge/BFTimer.h" @@ -17,128 +16,312 @@ namespace dice { namespace hfe { namespace ai { -// Navigation path result with polygon positions and traversal state. +// Navigation path result. The node vector holds one (polygon, entered-from polygon, entry point) +// triple per step, in travel order. class QTPath { public: - QTPath() - : m_i0(0) - , m_sentinel16(-1) - , m_i20(0) + QTPath(); + ~QTPath(); + + // [INFERRED] Inline accessors as calculateCostOfPath reads them: an index outside the vector + // (signed compare) yields UINT_MAX and a null position. + unsigned int getPolygon(unsigned int index) const + { + return static_cast(index) < static_cast(m_nodes.size()) + ? m_nodes[index].first + : 0xFFFFFFFFu; + } + const Vec3* getPosition(unsigned int index) const { - // The vector is default-constructed (three null pointers in retail) by the member above - // being absent from this list - the binary's four zero stores at +0 and +4..+15 are that - // and nothing more. + return static_cast(index) < static_cast(m_nodes.size()) ? &m_nodes[index].third + : 0; } - /* +0 */ int m_i0; // = 0 [UNRESOLVED] + // m_i0 and m_i20 keep their placeholder names because AIBot code already writes them. + /* +0 */ int m_i0; // = 0; [INFERRED] the first step still ahead /* +4 */ std::vector > m_nodes; - /* +16 */ int m_sentinel16; // = -1 [UNRESOLVED] - /* +20 */ int m_i20; // = 0 [UNRESOLVED] + /* +16 */ int m_island; // = -1; internalLocalSearch stores the quad tree + /* +20 */ float m_i20; // = 0; the path cost: buildPath copies the goal's f }; -// Cluster-level path result and traversal state. +// Cluster-level path result: (cluster, entry portal) pairs in travel order, for one map, island +// and cluster cost type. class ClusterNodePath { public: - ClusterNodePath() - : m_i0(0) - { - // m_gap4 deliberately not initialised - the binary steps over it. See above. - } + // +4 .. +15 deliberately not initialised - the constructor steps over them. + ClusterNodePath(); + ~ClusterNodePath(); - /* +0 */ int m_i0; // = 0 [UNRESOLVED] - /* +4 */ char m_gap4[12]; // never written + // Stores the map and looks up the vehicle's cluster cost type for it. + void setVehicle(int map, int vehicleId); + // The entry portal of step `index`: its position and polygon. False past the end or for the + // start step (no entry portal). + bool getPoint(Vec3& position, unsigned int& polygon, unsigned int index) const; + // The entry portal position of step m_i0 + `index`, or Vec3::getZero(). + const Vec3& getPoint(unsigned int index) const; + + /* +0 */ int m_i0; // = 0; the current step (BotNavigation resets it) + /* +4 */ int m_map; + /* +8 */ int m_costType; // IAIPathfinding::getClusterCostType + /* +12 */ int m_island; // clusterSearch writes it /* +16 */ std::vector > m_nodes; }; -// Reusable A* node pools, hash tables and search state. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding AIPathfindingSearchTypes operation. +// What QTSearchNodeManager::getNeighbourOfNode found for a neighbour. [INFERRED] enumerator +// names; the values are those the search switches on. +namespace nodeStatus { +enum Status +{ + kUnvisited = 0, // new: costed and to be opened + kOpen = 1, + kClosed = 2, + kGoal = 3, // the goal (or an additional goal) polygon + kInvalid = 4 // no further edge, impassable material or a disallowed cluster +}; +} // namespace nodeStatus -// Allocated only by `BinarySearchTree`'s constructor, which writes two of -// its four words: `+0 = 0` and `+8 = `. The other two are whatever the -// allocator returned. A classic node shape, but which word is left/right/parent is [UNRESOLVED] -// until `insert`/`merge`/`flatten` are read. +// Search-node tree record. `m_left` doubles as the free-list link, and `flatten` threads a whole +// tree through it. template class BSTNode { public: BSTNode() - : m_i0(0) + : m_data(0) { - // +4 and +12 deliberately not initialised - the constructor at writes only +0 and - // +8, and +8 is the free-list link the tree sets after construction. + // +4 .. +12 deliberately not initialised: only +0 is written; insert sets the children and + // the tree's free list writes +8. } - /* +0 */ int m_i0; // = 0 [UNRESOLVED] - /* +4 */ int m_i4; // never written by the constructor - /* +8 */ BSTNode* m_next; // the free-list link [INFERRED] - /* +12 */ int m_i12; // never written by the constructor + /* +0 */ T* m_data; + /* +4 */ BSTNode* m_parent; + /* +8 */ BSTNode* m_left; // smaller f cost; also the free-list link + /* +12 */ BSTNode* m_right; // equal or larger f cost }; -// Search-node tree and reusable node storage. +// The A* open list: an unbalanced binary tree ordered by the nodes' f cost, with its minimum +// cached. Removed tree records go to a free list and are reused. template class BinarySearchTree { public: explicit BinarySearchTree(int n) - : m_root(0) + : m_count(0) , m_free(0) - , m_i12(0) + , m_root(0) { - // m_i8 deliberately not initialised - see above. + // m_min deliberately not initialised: the constructor writes +0, +4 and +12 only. for (int i = n; i > 0; --i) { BSTNode* const node = new BSTNode(); - node->m_next = m_free; + node->m_left = m_free; m_free = node; } } - /* +0 */ BSTNode* m_root; // [INFERRED] - /* +4 */ BSTNode* m_free; // the pre-allocated pool, proven by the loop - /* +8 */ int m_i8; // never written by the constructor [UNRESOLVED] - /* +12 */ int m_i12; // = 0 [UNRESOLVED] + ~BinarySearchTree(); + + void insert(SearchNode* data); + SearchNode* pop(); + SearchNode* remove(SearchNode* data); + BSTNode* get(SearchNode* data, BSTNode* node); + void clear(); + + /* +0 */ int m_count; + /* +4 */ BSTNode* m_free; + /* +8 */ BSTNode* m_min; + /* +12 */ BSTNode* m_root; + +private: + void insert(BSTNode* at, BSTNode* node); + void merge(BSTNode* at, BSTNode* node); + BSTNode* getLeftmostChildOfTree(BSTNode* node) const; + void flatten(BSTNode* node, BSTNode*& last); }; -// Bucketed search-node lookup with a shared node manager. +// The hash key of a stored element: a search node's own key. ClusterNodeManager's status +// records overload it (their key is their node's), found by argument-dependent lookup. +template +inline auto hashKeyOf(const SearchNode* node) -> decltype(node->m_key) +{ + return node->m_key; +} + +// [INFERRED] Helper names. QTSearchNode uses signed division, then adds the capacity for a +// negative key (even when its remainder is zero). ClusterNode uses unsigned division instead. +inline int hashIndexForKey(int key, int capacity) +{ + int index = key % capacity; + if (key < 0) + index += capacity; + return index; +} + +inline int hashIndexForKey(unsigned int key, int capacity) +{ + return hashIndexForKey(static_cast(key), capacity); +} + +inline int hashIndexForKey(unsigned short key, int capacity) +{ + return static_cast(key) % static_cast(capacity); +} + +// CPNode overloads this with its cover position's index (no modulus), and hashKeyEquals with +// its cover position pointer. The hooks are found by argument-dependent lookup. +template +inline int hashIndexOf(const SearchNode* node, int capacity) +{ + return hashIndexForKey(hashKeyOf(node), capacity); +} + +// [INFERRED] Whether two stored elements carry the same key; see hashIndexOf. +template +inline bool hashKeyEquals(const SearchNode* a, const SearchNode* b) +{ + return hashKeyOf(a) == hashKeyOf(b); +} + +// One hash bucket. Non-empty buckets are threaded on a doubly linked "used" list so clearing and +// iteration only visit those. +template +struct HashBucket +{ + // Inlined in Hash's array construction (ELF 0x3B1EB0, also 0x35B3A0). + HashBucket() + : m_nextUsed(0), m_prevUsed(0), m_head(0) + { + } + + HashBucket* m_nextUsed; + HashBucket* m_prevUsed; + SearchNode* m_head; +}; + +template +class Hash; + +// Forward iterator over a Hash: the bucket, the node in it, and the owning hash. +template +struct HashIterator +{ + HashBucket* m_bucket; + SearchNode* m_node; + Hash* m_hash; + + bool operator==(const HashIterator& other) const + { + return m_bucket == other.m_bucket && m_node == other.m_node; + } + bool operator!=(const HashIterator& other) const { return !(*this == other); } + + // ELF 0x321E00 (the OCData instantiation): the next node in the bucket, else the next used + // bucket's head. + HashIterator& operator++() + { + m_node = m_node->m_next; + if (m_node == 0) + { + m_bucket = m_bucket->m_nextUsed; + if (m_bucket != 0) + m_node = m_bucket->m_head; + } + return *this; + } +}; + +// Intrusive chained hash of search nodes keyed by Node::m_key, chained through the nodes' own +// m_next / m_prev words. The modulus is the constructor's n; n + 1 buckets are allocated. template class Hash { public: + typedef HashIterator iterator; + + // ELF instances: 0x3B1CD0 (QTSearchNode), 0x3B1EB0 (ClusterNode), 0x321D60 + // (ClusterNodeManager::OCData), 0x35B3A0 (CPNode). explicit Hash(unsigned int n) - : m_self0((Hash*)this) - , m_i12(0) - , m_i16(0) - , m_self1((Hash*)this) - , m_buckets(new int[3 * n + 3]) - , m_i28(0) - , m_i32(0) + : m_buckets(new HashBucket[n + 1]) + , m_used(0) + , m_count(0) , m_capacity((int)n) , m_nodeManager(0) { - // m_i0 and m_i4 deliberately not initialised - see above. - // n + 1 entries of three words each, cleared from n down through zero. - for (unsigned int i = 0; i <= n; ++i) + // The bucket constructors run before the fields above are initialized. m_begin's + // bucket and node are not written here; begin() fills them. + m_end.m_bucket = 0; + m_end.m_node = 0; + m_end.m_hash = this; + m_begin.m_hash = this; + } + + void insert(SearchNode* node); + SearchNode* get(SearchNode* node) const; + void remove(SearchNode* node); + + // Inlined in every retail user: empties the buckets on the used list without touching the + // nodes, which the node manager owns. + void clear() + { + m_count = 0; + for (HashBucket* bucket = m_used; bucket != 0; bucket = bucket->m_nextUsed) + bucket->m_head = 0; + m_used = 0; + } + + // Inlined in handleOpenCacheUnderflow (ELF 0x35A5E0 / 0x3B0D00): refreshes the cached + // begin iterator even when empty. + iterator begin() + { + if (m_count == 0) + m_begin = m_end; + else { - m_buckets[3 * i] = 0; - m_buckets[3 * i + 1] = 0; - m_buckets[3 * i + 2] = 0; + m_begin.m_bucket = m_used; + m_begin.m_node = m_used->m_head; } + return m_begin; } + const iterator& end() const { return m_end; } + + /* +0 */ iterator m_begin; + /* +12 */ iterator m_end; + /* +24 */ HashBucket* m_buckets; + /* +28 */ HashBucket* m_used; + /* +32 */ int m_count; + /* +36 */ int m_capacity; + /* +40 */ NodeManager* m_nodeManager; // = 0, written by the owner right after construction + +private: + // The bucket of a node (hashIndexOf). + HashBucket* bucketOf(const SearchNode* node) const + { + return &m_buckets[hashIndexOf(node, m_capacity)]; + } +}; + +// Orders search nodes by f cost for handleOpenCacheUnderflow's multiset. Retail defines it in an +// anonymous namespace of AIPathfinding.cpp (attested by the multiset's mangled names); it is here +// because the templates that use it are defined in this header. +template +struct NodeCompare +{ + bool operator()(const SearchNode* a, const SearchNode* b) const { return a->m_f < b->m_f; } +}; - /* +0 */ int m_i0; // never written by the constructor - /* +4 */ int m_i4; // never written by the constructor - /* +8 */ Hash* m_self0; // = this (an intrusive list sentinel) - /* +12 */ int m_i12; // = 0 - /* +16 */ int m_i16; // = 0 - /* +20 */ Hash* m_self1; // = this - /* +24 */ int* m_buckets; // operator new[](3 * n + 3) ints, all zeroed - /* +28 */ int m_i28; // = 0 - /* +32 */ int m_i32; // = 0 - /* +36 */ int m_capacity; // = n - /* +40 */ NodeManager* m_nodeManager;// = 0, written by the owner right after construction +namespace astarStatus { +// Values of AStarResource::m_status. [INFERRED] names; the values are the ones the search writes. +enum +{ + kIdle = 0, + kSearching = 1, + kFound = 2, + kFailed = 3, + kInvalid = 4 // localSearch's answer for an unusable request; never stored }; +} // namespace astarStatus // State for one in-flight A* search. Its node manager and hash tables belong to the search resource. template @@ -149,61 +332,52 @@ class AStarResource : m_status(0) , m_maxIterations(0) , m_maxSearchDepth(-1) - , m_i16(0) + , m_iterations(0) , m_openSize(0) , m_hashSize(0) - , m_i28(-1) + , m_owner(-1) , m_nodeManager(nodeManager) - , m_i36(0) + , m_worstOpen(0) , m_open(0) + , m_openOverflow(0) , m_closed(0) - , m_i48(0) - , m_i52(0) - , m_i56(0) - , m_cache(0) - , m_i64(0) + , m_goal(0) { // m_i4 deliberately not initialised - see above. } - // One A* step against a deadline. ELF: ClusterNode , QTSearchNode - // CPNode , all `...AStarResource...6updateEd`. The - // result is discarded by PathfindingEngine::update. A named stop until the search is read; - // the definition follows the class. + // Runs A* steps until the deadline, the goal, exhaustion or a limit. void update(double deadline); + void pushOpenNode(SearchNode* node); + SearchNode* popOpenNode(); + void handleOpenCacheUnderflow(); - /* +0 */ int m_status; // = 0 `PathfindingEngine::getStatus` reads this word + /* +0 */ int m_status; // astarStatus; PathfindingEngine::getStatus reads this word /* +4 */ int m_i4; // never written - /* +8 */ int m_maxIterations; // = 0 [INFERRED] - `setMaxIterationsForResource` writes +8 - /* +12 */ int m_maxSearchDepth; // = -1 [INFERRED] - `setMaxSearchDepthForResource` writes +12 - /* +16 */ int m_i16; // = 0, set by the owner after the push - /* +20 */ int m_openSize; // = the int handed to BinarySearchTree's constructor + /* +8 */ int m_maxIterations; // 0 = no limit (the counter never equals it) + /* +12 */ int m_maxSearchDepth; // -1 = no limit + /* +16 */ int m_iterations; // closed nodes this search + /* +20 */ int m_openSize; // the tree's capacity before nodes overflow into the hash /* +24 */ int m_hashSize; // = the int handed to both Hash constructors - /* +28 */ int m_i28; // = -1 [UNRESOLVED] + /* +28 */ int m_owner; // = -1 free; acquireResource stores the caller's owner id /* +32 */ NodeManager* m_nodeManager; - /* +36 */ int m_i36; // = 0 [UNRESOLVED] + /* +36 */ SearchNode* m_worstOpen; // the largest f cost refilled into the tree /* +40 */ BinarySearchTree* m_open; - /* +44 */ Hash* m_closed; // [INFERRED] which is which - /* +48 */ int m_i48; // = 0 [UNRESOLVED] - /* +52 */ int m_i52; // = 0 [UNRESOLVED] - /* +56 */ int m_i56; // = 0 [UNRESOLVED] - /* +60 */ Hash* m_cache; // [INFERRED] - /* +64 */ int m_i64; // = 0 [UNRESOLVED] + /* +44 */ Hash* m_openOverflow; + /* +48 */ std::vector m_v48; // [UNRESOLVED] handleOpenCacheUnderflow only resizes it to 0 + /* +60 */ Hash* m_closed; + /* +64 */ SearchNode* m_goal; // the goal node once found; buildPath starts from it }; -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -// Defined here because every instantiation needs it; reached only when a search is in flight. -template -void AStarResource::update(double) -{ - BF2_AI_FRONTIER("dice::hfe::ai::AStarResource::update"); -} // Pathfinding engine and its pool of reusable search resources. template class PathfindingEngine { public: PathfindingEngine() {} + // ELF 0x3AE720 (QTSearchNode), 0x3AE930 (ClusterNode), 0x3593F0 (CPNode); weak, one per + // instantiation, identical apart from the node manager's calls. + ~PathfindingEngine(); // [INFERRED] Steps active searches round-robin until now + budget, at most once per // search per call, moving each processed search from front to back. @@ -237,6 +411,609 @@ void PathfindingEngine::update(double } } +// Every search resource is first returned and reset inline (the releaseResource and +// internalLocalSearch sequences, in that order), then its parts are deleted: node manager, open +// tree, both hashes (bucket array first: Hash has no destructor of its own, as in +// ~ClusterNodeManager), and the resource itself, whose only implicit member is m_v48. Null slots +// are skipped. The bound is re-read from the vector on every step. The two lists and the vector +// are then destroyed in reverse declaration order (+16, +12, +0). +template +PathfindingEngine::~PathfindingEngine() +{ + for (unsigned int i = 0; i < m_searches.size(); ++i) + { + AStarResource* const search = m_searches[i]; + if (search == 0) + continue; + + search->m_maxIterations = 0; + search->m_maxSearchDepth = -1; + search->m_nodeManager->returnReset(); + search->m_owner = -1; + search->m_iterations = 0; + search->m_status = astarStatus::kIdle; + search->m_worstOpen = 0; + search->m_open->clear(); + search->m_openOverflow->clear(); + search->m_closed->clear(); + search->m_nodeManager->reset(); + + delete search->m_nodeManager; + delete search->m_open; + if (search->m_openOverflow != 0) + { + if (search->m_openOverflow->m_buckets != 0) + delete[] search->m_openOverflow->m_buckets; + delete search->m_openOverflow; + } + if (search->m_closed != 0) + { + if (search->m_closed->m_buckets != 0) + delete[] search->m_closed->m_buckets; + delete search->m_closed; + } + delete search; + } +} + +// BinarySearchTree. Instantiation addresses are the QTSearchNode ones in the ELF. + +// ELF 0x3B0750 (QTSearchNode), 0x35A490 (CPNode), 0x3B07C0 (ClusterNode). +// Pops every element, then frees the record pool. +template +BinarySearchTree::~BinarySearchTree() +{ + while (m_count > 0) + pop(); + while (m_free != 0) + { + BSTNode* const node = m_free; + m_free = node->m_left; + delete node; + } +} + +// ELF 0x3AF950 (QTSearchNode), 0x35A230 (CPNode), 0x3AFB20 (ClusterNode). +// Equal costs go right; the cached minimum moves only to a strictly cheaper node. +template +void BinarySearchTree::insert(SearchNode* data) +{ + BSTNode* node = m_free; + if (node != 0) + m_free = node->m_left; + else + node = new BSTNode(); + node->m_left = 0; + node->m_right = 0; + node->m_data = data; + + if (m_count == 0) + { + m_min = node; + m_root = node; + node->m_parent = 0; + ++m_count; + return; + } + + BSTNode* const root = m_root; + if (root->m_data->m_f > data->m_f) + { + if (root->m_left == 0) + { + root->m_left = node; + node->m_parent = root; + } + else + insert(root->m_left, node); + } + else + { + if (root->m_right == 0) + { + root->m_right = node; + node->m_parent = root; + } + else + insert(root->m_right, node); + } + + if (m_min->m_data->m_f > node->m_data->m_f) + m_min = node; + ++m_count; +} + +// ELF 0x3B2BD0 (QTSearchNode), 0x35BA00 (CPNode), 0x3B2C40 (ClusterNode). +// Descends from `at` to a free child slot. +template +void BinarySearchTree::insert(BSTNode* at, BSTNode* node) +{ + for (;;) + { + if (at->m_data->m_f > node->m_data->m_f) + { + if (at->m_left == 0) + { + at->m_left = node; + break; + } + at = at->m_left; + } + else + { + if (at->m_right == 0) + { + at->m_right = node; + break; + } + at = at->m_right; + } + } + node->m_parent = at; +} + +// ELF 0x3B2CB0 (QTSearchNode), 0x35BA70 (CPNode), 0x3B2D00 (ClusterNode). +// insert with a null subtree accepted. +template +void BinarySearchTree::merge(BSTNode* at, BSTNode* node) +{ + if (node == 0) + return; + insert(at, node); +} + +// ELF 0x3B2C10 (QTSearchNode), 0x35BA40 (CPNode), 0x3B2C80 (ClusterNode). +template +BSTNode* +BinarySearchTree::getLeftmostChildOfTree(BSTNode* node) const +{ + BSTNode* leftmost = 0; + while (node != 0) + { + leftmost = node; + node = node->m_left; + } + return leftmost; +} + +// ELF 0x3AFA40 (QTSearchNode), 0x35A320 (CPNode), 0x3AFC10 (ClusterNode). +// Removes and returns the cheapest node, or null when empty. +template +SearchNode* BinarySearchTree::pop() +{ + BSTNode* const min = m_min; + if (min == 0) + return 0; + + --m_count; + if (min->m_right != 0) + { + if (min->m_parent != 0) + { + min->m_parent->m_left = min->m_right; + min->m_right->m_parent = min->m_parent; + m_min = min->m_right->m_left != 0 ? getLeftmostChildOfTree(min->m_right->m_left) + : min->m_right; + } + else + { + m_root = min->m_right; + min->m_right->m_parent = 0; + m_min = getLeftmostChildOfTree(min->m_right); + } + } + else + { + m_min = min->m_parent; + if (m_min != 0) + m_min->m_left = 0; + else + { + m_min = min->m_right; + m_root = min->m_right; + if (m_min != 0) + { + m_min->m_parent = 0; + while (m_min->m_left != 0) + m_min = m_min->m_left; + } + } + } + + min->m_left = m_free; + m_free = min; + return min->m_data; +} + +// ELF 0x3B2910 (QTSearchNode), 0x35B900 (CPNode), 0x3B2AD0 (ClusterNode). +// Depth-first by key; the left subtree recursively, the right iteratively. +template +BSTNode* BinarySearchTree::get(SearchNode* data, + BSTNode* node) +{ + while (node != 0) + { + if (data->m_key == node->m_data->m_key) + return node; + BSTNode* const found = get(data, node->m_left); + if (found != 0) + return found; + node = node->m_right; + } + return 0; +} + +// ELF 0x3B0B90 (QTSearchNode), 0x35A940 (CPNode), 0x3B1060 (ClusterNode). +// Removes the node with data's key. The cached minimum is only maintained through +// pop; a non-minimum removal leaves it alone. The removed node's left subtree is merged under its +// right one. +template +SearchNode* BinarySearchTree::remove(SearchNode* data) +{ + if (m_count == 0) + return 0; + if (m_min->m_data->m_key == data->m_key) + return pop(); + + BSTNode* const node = get(data, m_root); + if (node == 0) + return 0; + + --m_count; + BSTNode* const parent = node->m_parent; + if (parent != 0) + { + BSTNode** const slot = + parent->m_left == node ? &parent->m_left : &parent->m_right; + if (node->m_right != 0) + { + *slot = node->m_right; + node->m_right->m_parent = node->m_parent; + merge(*slot, node->m_left); + } + else + { + *slot = node->m_left; + if (node->m_left != 0) + node->m_left->m_parent = node->m_parent; + } + } + else if (node->m_right != 0) + { + m_root = node->m_right; + node->m_right->m_parent = 0; + merge(node->m_right, node->m_left); + } + else + { + // Retail does not test the left child here. + m_root = node->m_left; + node->m_left->m_parent = 0; + } + + node->m_left = m_free; + m_free = node; + return node->m_data; +} + +// ELF 0x3B2360 (QTSearchNode), 0x35B720 (CPNode), 0x3B25E0 (ClusterNode). +// Threads the subtree into one chain through m_left: the node, its left chain, then +// its right chain. `last` receives the chain's tail. +template +void BinarySearchTree::flatten(BSTNode* node, + BSTNode*& last) +{ + if (node->m_left == 0) + { + if (node->m_right == 0) + { + last = node; + return; + } + flatten(node->m_right, last); + node->m_left = node->m_right; + return; + } + + BSTNode* leftLast; + flatten(node->m_left, leftLast); + if (node->m_right == 0) + { + last = leftLast; + return; + } + flatten(node->m_right, last); + leftLast->m_left = node->m_right; +} + +// ELF 0x3B22F0 (QTSearchNode), 0x35B6B0 (CPNode), 0x3B2570 (ClusterNode). +// Returns every record to the free list in one splice. +template +void BinarySearchTree::clear() +{ + if (m_root == 0) + return; + BSTNode* last; + flatten(m_root, last); + last->m_left = m_free; + m_free = m_root; + m_count = 0; + m_root = 0; + m_min = 0; +} + +// Hash. Instantiation addresses are the QTSearchNode ones in the ELF. + +// ELF 0x3B24B0 (QTSearchNode), 0x359B20 (CPNode), 0x3B2730 (ClusterNode). +// Pushes at the bucket head; an empty bucket joins the front of the used list. +template +void Hash::insert(SearchNode* node) +{ + HashBucket* const bucket = bucketOf(node); + SearchNode* const head = bucket->m_head; + if (head != 0) + head->m_prev = node; + else + { + bucket->m_nextUsed = m_used; + if (m_used != 0) + m_used->m_prevUsed = bucket; + bucket->m_prevUsed = 0; + m_used = bucket; + } + node->m_next = head; + node->m_prev = 0; + bucket->m_head = node; + ++m_count; +} + +// ELF 0x3B28B0 (QTSearchNode; also 0x3B2A80 ClusterNode, 0x321E40 ClusterNodeManager::OCData, +// 0x35B8C0 CPNode). The stored node with the same key, or null. +template +SearchNode* Hash::get(SearchNode* node) const +{ + for (SearchNode* entry = bucketOf(node)->m_head; entry != 0; entry = entry->m_next) + { + if (hashKeyEquals(entry, node)) + return entry; + } + return 0; +} + +// ELF 0x3B2970 (QTSearchNode), 0x35B960 (CPNode), 0x3B2B30 (ClusterNode). +// Unlinks a stored node; a bucket that empties leaves the used list. +template +void Hash::remove(SearchNode* node) +{ + if (node->m_prev != 0) + node->m_prev->m_next = node->m_next; + else + { + HashBucket* const bucket = bucketOf(node); + bucket->m_head = node->m_next; + if (bucket->m_head == 0) + { + if (m_used == bucket) + m_used = bucket->m_nextUsed; + else + bucket->m_prevUsed->m_nextUsed = bucket->m_nextUsed; + if (bucket->m_nextUsed != 0) + bucket->m_nextUsed->m_prevUsed = bucket->m_prevUsed; + } + } + --m_count; + if (node->m_next != 0) + node->m_next->m_prev = node->m_prev; +} + +// AStarResource. Instantiation addresses are the QTSearchNode ones in the ELF. + +// ELF 0x3B2410 (QTSearchNode), 0x35B7D0 (CPNode), 0x3B2690 (ClusterNode). +// Marks the node open. It goes into the tree only while the tree is non-empty and +// the node is cheaper than the worst node last refilled; a full tree is first flushed, cheapest +// first, into the overflow hash. Everything else goes straight to the overflow hash. +template +void AStarResource::pushOpenNode(SearchNode* node) +{ + m_nodeManager->setNodeOpen(node); + if (m_open->m_count != 0 && m_worstOpen->m_f > node->m_f) + { + if (m_open->m_count >= m_openSize) + { + do + m_openOverflow->insert(m_open->pop()); + while (m_open->m_count != 0); + } + m_open->insert(node); + return; + } + m_openOverflow->insert(node); +} + +// ELF 0x3B2860 (QTSearchNode), 0x35B870 (CPNode), 0x3B2A30 (ClusterNode). +// The cheapest open node, refilling the tree from the overflow hash when it is +// empty; null when both are empty. +template +SearchNode* AStarResource::popOpenNode() +{ + for (;;) + { + if (m_open->m_count != 0) + return m_open->pop(); + if (m_openOverflow->m_count == 0) + return 0; + handleOpenCacheUnderflow(); + } +} + +// ELF 0x3B0830 (QTSearchNode), 0x35A5E0 (CPNode), 0x3B0D00 (ClusterNode). +// Moves the m_openSize cheapest overflow nodes into the tree and remembers the most +// expensive of them. The candidates are kept in a multiset by f cost; displacing the current worst +// erases it by key, which removes every candidate with that same cost (retail behaviour). +template +void AStarResource::handleOpenCacheUnderflow() +{ + m_v48.resize(0); + + Hash* const hash = m_openOverflow; + typename Hash::iterator it = hash->begin(); + if (it == hash->end()) + return; + + std::multiset > best; + SearchNode* worst = it.m_node; + for (int taken = 0; taken < m_openSize && it != hash->end(); ++taken) + { + best.insert(it.m_node); + if (it.m_node->m_f > worst->m_f) + worst = it.m_node; + ++it; + } + + while (it != hash->end()) + { + if (!(it.m_node->m_f > worst->m_f)) + { + typename std::multiset >::iterator last = + best.end(); + --last; + best.erase(*last); + best.insert(it.m_node); + ++it; + last = best.end(); + --last; + worst = *last; + } + else + ++it; + } + + for (typename std::multiset >::iterator i = best.begin(); + i != best.end(); ++i) + { + m_openOverflow->remove(*i); + m_open->insert(*i); + } + m_worstOpen = worst; +} + +// ELF 0x3AEEA0 (QTSearchNode), 0x359BC0 (CPNode), 0x3AF400 (ClusterNode). +// One time slice of the search. Each popped node is expanded edge by edge (never +// back into its own parent); new neighbours are opened, cheaper routes to open or closed nodes +// re-open those, and reaching the goal closes the search. A node whose edges are exhausted is +// closed and counted against the iteration and depth limits. +template +void AStarResource::update(double deadline) +{ + IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); + if (m_status != astarStatus::kSearching) + return; + + for (;;) + { + if (!(deadline > timer->getUpdateTime())) + return; + + SearchNode* const node = popOpenNode(); + if (node == 0) + { + m_status = astarStatus::kFailed; + return; + } + + nodeStatus::Status status; + Key edge; + SearchNode* neighbour = node->expandFirst(m_nodeManager, status, edge); + while (neighbour != 0 && node->m_parent != 0 && neighbour->m_key == node->m_parent->m_key) + { + m_nodeManager->recycleNode(neighbour); + neighbour = node->expand(m_nodeManager, status, edge); + } + + while (neighbour != 0) + { + switch (status) + { + case nodeStatus::kUnvisited: + pushOpenNode(neighbour); + break; + + case nodeStatus::kOpen: + { + SearchNode* existing = m_openOverflow->get(neighbour); + if (existing == 0) + { + BSTNode* const record = m_open->get(neighbour, m_open->m_root); + existing = record != 0 ? record->m_data : 0; + } + if (m_nodeManager->updateNode(node, existing, m_maxSearchDepth)) + { + SearchNode* const hashed = m_openOverflow->get(neighbour); + if (hashed != 0) + m_openOverflow->remove(hashed); + else + m_open->remove(neighbour); + pushOpenNode(existing); + } + m_nodeManager->recycleNode(neighbour); + break; + } + + case nodeStatus::kClosed: + { + SearchNode* const existing = m_closed->get(neighbour); + if (m_nodeManager->updateNode(node, existing, m_maxSearchDepth)) + { + m_closed->remove(existing); + pushOpenNode(existing); + } + m_nodeManager->recycleNode(neighbour); + break; + } + + case nodeStatus::kGoal: + m_goal = neighbour; + neighbour->m_parent = node; + m_nodeManager->setNodeClosed(node); + m_closed->insert(node); + m_status = astarStatus::kFound; + break; + + case nodeStatus::kInvalid: + m_nodeManager->recycleNode(neighbour); + break; + + default: + break; + } + + if (m_status == astarStatus::kFound) + return; + + neighbour = node->expand(m_nodeManager, status, edge); + while (neighbour != 0 && node->m_parent != 0 && + neighbour->m_key == node->m_parent->m_key) + { + m_nodeManager->recycleNode(neighbour); + neighbour = node->expand(m_nodeManager, status, edge); + } + } + + if (m_status == astarStatus::kFound) + return; + + const int depth = node->m_depth; + m_nodeManager->setNodeClosed(node); + m_closed->insert(node); + ++m_iterations; + if (m_iterations == m_maxIterations || m_maxSearchDepth == depth) + { + m_status = astarStatus::kFailed; + return; + } + } +} + } // namespace ai } // namespace hfe } // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIPlayerCourier.cpp b/Code/BF2/AI/AIDLL/AI/Main/AIPlayerCourier.cpp index 50dbae10d..65c69ee1f 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIPlayerCourier.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/AIPlayerCourier.cpp @@ -1,4 +1,6 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining AIPlayerCourier operations. + +// static init: ELF 0x3B3090 (__tcf_0 0x3B30F0, _GLOBAL__I 0x3B3120): 's Init object only. +#include #include "AIPlayerCourier.h" @@ -6,7 +8,11 @@ #include "../../../../Core/ClassManager.h" #include "CommonSingletonServer.h" -#include "AIDllFrontier.h" +#include "IBotManager.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "InformationManager.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" namespace dice { namespace hfe { @@ -38,24 +44,55 @@ AIPlayerCourier::~AIPlayerCourier() { } -int AIPlayerCourier::getSelectedVehicle(int) +// ELF 0x3B2E90: the bot's getChangeTarget handle (Bot +0x1BC) resolved through the information pool; the +// information's AI object answers its engine object (IObjectComponent +0x20 getObject). Null for +// a non-bot or an unknown handle. +world::IObject* AIPlayerCourier::getSelectedVehicle(int playerId) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayerCourier::getSelectedVehicle"); + Bot* const bot = IBotManager::instance->getBotFromPlayerId(playerId); + if (!bot) + return 0; + Information* const information = informationManager->getInformation(bot->getChangeTarget()); + if (!information) + return 0; + return information->getAIObject()->getObject(); } -int AIPlayerCourier::getRepairTarget(int) +// ELF 0x3B2F20: the bot's getBridgeRepairTarget handle (Bot +0x1D4) resolved through the information pool; the +// information's AI object answers its engine object (IObjectComponent +0x20 getObject). Null for +// a non-bot or an unknown handle. +world::IObject* AIPlayerCourier::getRepairTarget(int playerId) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayerCourier::getRepairTarget"); + Bot* const bot = IBotManager::instance->getBotFromPlayerId(playerId); + if (!bot) + return 0; + Information* const information = informationManager->getInformation(bot->getBridgeRepairTarget()); + if (!information) + return 0; + return information->getAIObject()->getObject(); } -int AIPlayerCourier::getReviveTarget(int) +// ELF 0x3B2FB0: the bot's getReviveTarget handle (Bot +0x1DC) resolved through the information pool; the +// information's AI object answers its engine object (IObjectComponent +0x20 getObject). Null for +// a non-bot or an unknown handle. +world::IObject* AIPlayerCourier::getReviveTarget(int playerId) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayerCourier::getReviveTarget"); + Bot* const bot = IBotManager::instance->getBotFromPlayerId(playerId); + if (!bot) + return 0; + Information* const information = informationManager->getInformation(bot->getReviveTarget()); + if (!information) + return 0; + return information->getAIObject()->getObject(); } -int AIPlayerCourier::getMineDefuseTarget(int) +// ELF 0x3B3040: the bot's mine target (BotMain +0x1FC, past the Bot interface), or -1. +unsigned int AIPlayerCourier::getMineDefuseTarget(int playerId) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayerCourier::getMineDefuseTarget"); + Bot* const bot = IBotManager::instance->getBotFromPlayerId(playerId); + if (!bot) + return static_cast(-1); + return static_cast(bot)->getMineTarget(); } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIPlayerCourier.h b/Code/BF2/AI/AIDLL/AI/Main/AIPlayerCourier.h index 7c7218189..863bce38a 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIPlayerCourier.h +++ b/Code/BF2/AI/AIDLL/AI/Main/AIPlayerCourier.h @@ -25,10 +25,12 @@ class IAIPlayerCourier public: IAIPlayerCourier(); virtual ~IAIPlayerCourier(); - virtual int getSelectedVehicle(int) = 0; - virtual int getRepairTarget(int) = 0; - virtual int getReviveTarget(int) = 0; - virtual int getMineDefuseTarget(int) = 0; + // The engine side (AIInterface/IAIPlayerCourier.h) reads the first three as world::IObject* + // and the fourth as an unsigned grid id; the ELF names are const (0x3B2E90..0x3B3040). + virtual world::IObject* getSelectedVehicle(int playerId) const = 0; + virtual world::IObject* getRepairTarget(int playerId) const = 0; + virtual world::IObject* getReviveTarget(int playerId) const = 0; + virtual unsigned int getMineDefuseTarget(int playerId) const = 0; }; // AIPlayerCourier - sizeof == 4, from BF2AI::init step 12. @@ -39,10 +41,10 @@ class AIPlayerCourier : public IAIPlayerCourier virtual ~AIPlayerCourier(); // IAIPlayerCourier - virtual int getSelectedVehicle(int); - virtual int getRepairTarget(int); - virtual int getReviveTarget(int); - virtual int getMineDefuseTarget(int); + virtual world::IObject* getSelectedVehicle(int playerId) const; + virtual world::IObject* getRepairTarget(int playerId) const; + virtual world::IObject* getReviveTarget(int playerId) const; + virtual unsigned int getMineDefuseTarget(int playerId) const; }; diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIRadio.cpp b/Code/BF2/AI/AIDLL/AI/Main/AIRadio.cpp new file mode 100644 index 000000000..18c7cc0eb --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/Main/AIRadio.cpp @@ -0,0 +1,77 @@ +// [INFERRED] Source placement; see AIRadio.h. + +// static init: ELF 0x3B3390 (__tcf_0 0x3B33F0, _GLOBAL__I 0x3B3420): 's Init object only. +#include + +#include "AIRadio.h" + +#include "CommonSingletonServer.h" // m_iaiSettings +#include "AISettingsInterfaces.h" // IAISettings::getMaxNBots (slot 0) +#include "../../../AIInterface/BFKnowledge/BFTimer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// .bss: zero until a constructor runs, and none does in the shipped image. +AIRadio* AIRadio::m_instance = 0; + +// ELF 0x3B3190 (C1; C2 0x3B3140 is the same): stores 0.0 (the float constant at ELF 0x49CB34) into +// the update time, asks the settings for the bot count once and discards it, then publishes +// itself. +0x04 is left unwritten. +AIRadio::AIRadio() +{ + m_lastUpdateTime = 0.0f; + const int bots = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + (void)bots; + m_instance = this; +} + +// ELF 0x3B3240 (D1; D2 0x3B31E0 is the same): asks the settings for the bot count once and clears +// each bot's messages (an empty body, so the shipped loop only counts down), frees the +0x04 +// array, then zeroes m_instance unconditionally. +AIRadio::~AIRadio() +{ + const int bots = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + for (int bot = 0; bot < bots; ++bot) + clearMessagesForBot(bot); + delete[] m_unresolved4; + m_instance = 0; +} + +// ELF 0x3B3330: push ebp / mov ebp, esp / pop ebp / ret. +void AIRadio::clearMessagesForBot(int) +{ +} + +// ELF 0x3B32A0: the time is stored unless it is less than 0.5 s past the last one. +void AIRadio::update() +{ + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (!(0.5f > now - m_lastUpdateTime)) + m_lastUpdateTime = now; +} + +// ELF 0x3B32F0. +bool AIRadio::reset() +{ + const int bots = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + (void)bots; + return true; +} + +// ELF 0x3B3340. +void AIRadio::setLastUpdateTime() +{ + m_lastUpdateTime = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); +} + +// ELF 0x3B3380: the float widened into the double. +void AIRadio::setLastUpdateTime(float time) +{ + m_lastUpdateTime = time; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIRadio.h b/Code/BF2/AI/AIDLL/AI/Main/AIRadio.h new file mode 100644 index 000000000..c87154a06 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/Main/AIRadio.h @@ -0,0 +1,46 @@ +// The AI radio singleton. Nothing in libaidll.so constructs one: the constructors (ELF 0x3B3140, +// 0x3B3190) have no callers and no PLT entry, and this file's static initializer (0x3B3390) only +// sets up . m_instance (.bss) is written only by the constructor and the destructor, so +// it stays null; AISettings::~AISettings and AISettings::reset still read it, and the destructor +// deletes it when set. +// [INFERRED] Source placement. + +#ifndef AI_AIDLL_AI_MAIN_AIRADIO_H // [INFERRED] guard style +#define AI_AIDLL_AI_MAIN_AIRADIO_H + +namespace dice { +namespace hfe { +namespace ai { + +class AIRadio +{ +public: + AIRadio(); // ELF 0x3B3140 (C2), 0x3B3190 (C1) + ~AIRadio(); // ELF 0x3B31E0 (D2), 0x3B3240 (D1) - not virtual + + void clearMessagesForBot(int); // ELF 0x3B3330 - an empty body + // ELF 0x3B32A0: the update time follows the game time in steps of at least 0.5 s. + void update(); + // ELF 0x3B32F0: asks the settings for the bot count, discards it, returns 1. [INFERRED] bool, + // like the sibling resets; the mangled name carries no return type. + bool reset(); + void setLastUpdateTime(); // ELF 0x3B3340: the game time + void setLastUpdateTime(float); // ELF 0x3B3380 + + static AIRadio* m_instance; + +private: + // Retail layout as far as the recovered bodies touch it; the size is not attested (no + // allocation site exists). + /* +0x00 */ int m_unresolved0; // [UNRESOLVED] never touched by the recovered bodies + // Freed with delete[] by the destructor; the constructor never writes it (shipped). The + // element type is [UNRESOLVED]; delete[] with no element destructor fits a trivial type. + /* +0x04 */ unsigned char* m_unresolved4; + /* +0x08 */ double m_lastUpdateTime; // [INFERRED] name: update and setLastUpdateTime use it +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_MAIN_AIRADIO_H diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIRandom.cpp b/Code/BF2/AI/AIDLL/AI/Main/AIRandom.cpp index 8b48ed183..1d11dee9a 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIRandom.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/AIRandom.cpp @@ -1,4 +1,7 @@ +// static init: ELF 0x3B36E0 (__tcf_0 0x3B3740, _GLOBAL__I 0x3B3770): 's Init object only. +#include + #include "AIRandom.h" #include "CommonSingletonServer.h" diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIRandom.h b/Code/BF2/AI/AIDLL/AI/Main/AIRandom.h index 8b5dbe37a..9ea461a15 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIRandom.h +++ b/Code/BF2/AI/AIDLL/AI/Main/AIRandom.h @@ -19,7 +19,8 @@ class AIRandom // Returns the next tempered random value. [CHOSEN] Name for an inline operation. unsigned int next() { - if (m_index > kStateSize - 1) + // Unsigned comparison, including the inlined draws at ELF 0x30C60D / 0x30CD9F. + if (static_cast(m_index) > kStateSize - 1) generateNumbers(); unsigned int y = m_state[m_index++]; @@ -48,7 +49,10 @@ class AIRandom // this index before the draw: PE spills its running weight to float only // across the refill call. No new state, virtual slot or random policy. friend class BotSpawner; +public: + // [CHOSEN, not recovered] Visibility for the generated inline seed property. /* +0x000 */ int m_seed; +private: /* +0x004 */ unsigned int m_state[kStateSize]; /* +0x9C4 */ int m_index; }; diff --git a/Code/BF2/AI/AIDLL/AI/Main/AISettings.cpp b/Code/BF2/AI/AIDLL/AI/Main/AISettings.cpp index 249f2a31c..6b2892312 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AISettings.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/AISettings.cpp @@ -3,20 +3,36 @@ #include "AISettings.h" -#include "AIDllFrontier.h" +#include +#include #include "../../../../Core/Debug.h" #include "../../../../Core/ClassManager.h" #include "CommonSingletonServer.h" -#include "../../../../Core/ConsoleObjectMacro.h" // the aiSettings.* bindings at the foot #include "AIMain.h" // IAIMain::spawnBots - setAutoSpawnBots' trigger #include "AILODManager.h" // setViewDistance's second broadcast #include "AIRandom.h" // addBotName's weight draw +#include "AIRadio.h" // the destructor's first delete #include "IBotManager.h" // setViewDistance walks the bot pool #include "../AIBot/BotMain.h" // Bot::isDeactivated / Bot::getPlayer #include "../AIPathFinding/Material/Material.h" // materialId console spelling and extractor #include "../AIPathFinding/Material/MaterialManager.h" #include "../AIUtils/checkPointer.h" +#include "../AIPlanInterpreter/BAPInterpreter.h" // the per-vehicle plan interpreter pool +#include "../AIBotBehaviour/BotBehaviour.h" // the destructor's virtual deleting destructors +#include "../AIBotBehaviourPattern/PlanGenerator.h" // (complete types, or delete skips them) #include "../../../AIInterface/BFKnowledge/AIPlayer.h" // IAIPlayer::setViewDistance, slot +0x68 +#include "../AIUtils/DebugRendering/AIRenderUtil.h" + +namespace { +// [CHOSEN, not recovered] These three original TUs share this source file; retain their +// three independent stream-initialization lifetimes with explicit objects. +// static init: ELF 0x3C1570 (__tcf_0 0x3C15D0, _GLOBAL__I 0x3C1600). +std::ios_base::Init aiSettingsStreams; +// static init: ELF 0x3E7400 (__tcf_0 0x3E7460, _GLOBAL__I 0x3E7490). +std::ios_base::Init iaiSettingsStreams; +// static init: ELF 0x3E77B0 (__tcf_0 0x3E7810, _GLOBAL__I 0x3E7840). +std::ios_base::Init iaiSettingsModifierStreams; +} namespace dice { namespace hfe { @@ -25,89 +41,104 @@ extern ClassManager* classManager; namespace ai { // Returns whether AI configuration overrides the game menu settings. +// ELF 0x3C1530. bool AISettings::overrideMenuSettings() const { return m_overrideMenuSettings; } // The same byte, under a second name. See above. +// ELF 0x3C1540. bool AISettings::getOverrideMenuSettings() const { return m_overrideMenuSettings; } -// Recovered accessors and the remaining explicitly named stops follow in shipped declaration order. -// The production stops below diagnose and abort; none returns a fabricated value. +// Recovered accessors follow the shipped declaration order. +// ELF 0x3BEF90. int AISettings::getNumberOfBehaviours() const { - return m_numberOfBehaviours; + return m_behaviourCount; } +// ELF 0x3BEFA0. int AISettings::getNumberOfVehicles() const { - return static_cast(m_behaviours.size()); + return static_cast(m_behaviourPool.size()); } -float* AISettings::getVehicleMods(int vehicle) const +// ELF 0x3C0EF0. +float* AISettings::getVehicleMods(int vehicleTypeId) const { - return m_vehicleMods[vehicle]; + return m_vehicleMods[vehicleTypeId]; } +// ELF 0x3BF640. BotBehaviour* AISettings::getBehaviour(int vehicle, int index) const { - return m_behaviours[vehicle][index]; + return m_behaviourPool[vehicle][index]; } +// ELF 0x3BF670. BotBehaviour* AISettings::getDefaultBehaviour(int vehicle) const { const int index = m_defaultBehaviour[vehicle]; if (index != -1) - return m_behaviours[vehicle][index]; + return m_behaviourPool[vehicle][index]; return 0; } -void* AISettings::getPlanInterpreter(int vehicle) const +// ELF 0x3BF6B0. +PlanInterpreter* AISettings::getPlanInterpreter(int vehicle) const { - return m_planInterpreters[vehicle]; + return m_planInterpreterPool[vehicle]; } +// ELF 0x3BF6D0. PlanGenerator* AISettings::getPlanGenerator(int vehicle, int index) const { - return m_planGenerators[vehicle][index]; + return m_planGeneratorPool[vehicle][index]; } +// ELF 0x3C0230. float AISettings::getStatsViewDistance() const { return m_statsViewDistance; } +// ELF 0x3C0250. bool AISettings::getDrawBotStats() const { return m_drawBotStats; } +// ELF 0x3C01F0. int AISettings::getNBattleStrengths() { return 6; } +// ELF 0x3C0200. int AISettings::getNStrategicStrengths() { return 2; } +// ELF 0x3C0220. int AISettings::getInformationGridDimension() const { return m_informationGridDimension; } +// ELF 0x3C0A00. float AISettings::getSAIUpdateFrequency() const { return m_saiUpdateFrequency; } // [INFERRED] reference spelling, proven borrowed string object. +// ELF 0x3BF320. const std::string& AISettings::getVehicle(int vehicle) const { if (vehicle < 0 || vehicle >= static_cast(m_vehicleNames.size())) @@ -121,53 +152,62 @@ const std::string& AISettings::getVehicle(int vehicle) const return m_vehicleNames[vehicle]; } +// ELF 0x3BF4A0. int AISettings::getVehicle(const std::string& name) const { // (!) guarded, and the sibling below is not. Same map type, same find, opposite discipline. - const std::map::const_iterator i = m_vehicleIndex.find(name); - if (i == m_vehicleIndex.end()) + const std::map::const_iterator i = m_vehicleIdMap.find(name); + if (i == m_vehicleIdMap.end()) return -1; return i->second; } // Every lookup/index is unchecked in both images. +// ELF 0x3BF500. const std::string& AISettings::getVehicleClusterMapping(const std::string& name) const { - const int vehicle = m_vehicleIndex.find(name)->second; + const int vehicle = m_vehicleIdMap.find(name)->second; return m_vehicleNames[m_clusterCostTypes[vehicle]]; } +// ELF 0x3BF570. int AISettings::getClusterCostType(int index) const { return m_clusterCostTypes[index]; } +// ELF 0x3BF590. const std::vector& AISettings::getClusterCostTypes() const { return m_clusterCostTypes; } +// ELF 0x3C0950. int AISettings::getNumberOfVehicleGroups() const { return static_cast(m_vehicleGroupNames.size()); } +// ELF 0x3C0970. int AISettings::getVehicleGroup(int index) const { return m_vehicleGroups[index]; } +// ELF 0x3C0990. int AISettings::getVehicleGroup(const std::string& name) const { // Requires an existing group name; the lookup result is dereferenced without checking end(). - return m_vehicleGroupIndex.find(name)->second; + return m_namesToVehicleGroups.find(name)->second; } +// ELF 0x3C09E0. const std::string& AISettings::getVehicleGroupName(int group) const { return m_vehicleGroupNames[group]; } +// ELF 0x3C0A60. float* AISettings::getStandardPersonality(int side) const { // (!) 1-based. The binary computes `this + 176 + 4*side`, i.e. this array at +180 subscripted @@ -175,11 +215,13 @@ float* AISettings::getStandardPersonality(int side) const return m_standardPersonality[side - 1]; } +// ELF 0x3C0A80. BotMoralAdmin* AISettings::getStandardMoralAdmin(int side) const { return m_standardMoralAdmin[side - 1]; } +// ELF 0x3C0AD0. bool AISettings::hasActiveRenderer() const { // This unsupported operation emits an error diagnostic. @@ -187,17 +229,20 @@ bool AISettings::hasActiveRenderer() const return false; } +// ELF 0x3C0C00. bool AISettings::getDraw() const { return m_draw; } // - a bare member return, the shape every accessor in this run has. +// ELF 0x3C4140. const std::map& AISettings::getSensingAgentPatterns() const { return m_sensingAgentPatterns; } +// ELF 0x3C0E20. ISensingAgentPattern* AISettings::getSensingAgentPattern(int id) const { const std::map::const_iterator i = m_sensingAgentPatterns.find(id); @@ -206,38 +251,45 @@ ISensingAgentPattern* AISettings::getSensingAgentPattern(int id) const return i->second; } +// ELF 0x3C0E70. ISensingAgentPattern* AISettings::getSensingAgentNullPattern() const { - return m_sensingAgentNullPattern; + return m_nullPattern; } +// ELF 0x3C0FD0. int AISettings::getManDownEquipmentType() { // Preserve virtual dispatch so derived getVehicle implementations are honored. return getVehicle(m_manDownEquipment); } +// ELF 0x3C1090. bool AISettings::isValidMaterial(int vehicle, unsigned char material) const { - return m_vehicleMaterialManagers[vehicle]->isValidMaterial(material); + return m_materialManagers[vehicle]->isValidMaterial(material); } +// ELF 0x3C1110. float AISettings::getVehicleMaterialCost(const std::string& name, unsigned char material) const { - return m_vehicleMaterialManagers[getVehicle(name)]->getMaterialCost(material); + return m_materialManagers[getVehicle(name)]->getMaterialCost(material); } +// ELF 0x3C10D0. float AISettings::getVehicleMaterialCost(int vehicle, unsigned char material) const { - return m_vehicleMaterialManagers[vehicle]->getMaterialCost(material); + return m_materialManagers[vehicle]->getMaterialCost(material); } +// ELF 0x3C1170. MaterialManager* AISettings::getVehicleMaterialManager(int vehicle) const { - return m_vehicleMaterialManagers[vehicle]; + return m_materialManagers[vehicle]; } // Returns the next bot name and rotates the roster for the following request. +// ELF 0x3C1480. const std::string& AISettings::getBotName() const { m_botNames.push_back(m_botNames.front()); @@ -247,92 +299,164 @@ const std::string& AISettings::getBotName() const } // The shared bot value narrows, the settings value does not. +// ELF 0x3BEF50. void AISettings::setMaxNumberOfBehaviours(int count) { BotMain::setNBehaviours(static_cast(count)); - m_numberOfBehaviours = count; + m_behaviourCount = count; +} + +// ELF 0x3C0F10: grows the table to the vehicle (new slots null), then stores the set. +void AISettings::setVehicleMods(int vehicle, float* mods) +{ + if (static_cast(m_vehicleMods.size()) <= vehicle) + m_vehicleMods.resize(vehicle + 1, 0); + m_vehicleMods[vehicle] = mods; +} + +// ELF 0x3BF730. +void AISettings::addBehaviour(int vehicleTypeId, int behaviourId, BotBehaviour* behaviour) +{ + prepareBehaviourPool(vehicleTypeId, behaviourId); + m_behaviourPool[vehicleTypeId][behaviourId] = behaviour; } -void AISettings::setVehicleMods(int, float *) +// ELF 0x3BF7A0: the pool is prepared for (vehicle, index) although only the default slot is set. +void AISettings::setDefaultBehaviour(int vehicleTypeId, int behaviourId) { - BF2_AI_FRONTIER("dice::hfe::ai::AISettings::setVehicleMods"); + prepareBehaviourPool(vehicleTypeId, behaviourId); + m_defaultBehaviour[vehicleTypeId] = behaviourId; } -void AISettings::addBehaviour(int, int, BotBehaviour *) +// ELF 0x3BF870: BAPInterpreter::addEntry(entry) on the vehicle's interpreter. +void AISettings::addInterpreterEntry(int vehicleTypeId, BAPEntry* entry) { - BF2_AI_FRONTIER("dice::hfe::ai::AISettings::addBehaviour"); + preparePlanInterpreterPool(vehicleTypeId); + static_cast(m_planInterpreterPool[vehicleTypeId])->addEntry(entry); } -void AISettings::setDefaultBehaviour(int, int) +// ELF 0x3BF8D0. +void AISettings::addInterpreterEntry(int vehicleTypeId, BotLodLevel lod, BAPEntry* entry) { - BF2_AI_FRONTIER("dice::hfe::ai::AISettings::setDefaultBehaviour"); + preparePlanInterpreterPool(vehicleTypeId); + static_cast(m_planInterpreterPool[vehicleTypeId])->addEntry(lod, entry); } -void AISettings::addInterpreterEntry(int, BAPEntry *) +// ELF 0x3BF930. +void AISettings::removeInterpreterEntry(int vehicleTypeId, BotLodLevel lod, BAPEntry* entry) { - BF2_AI_FRONTIER("dice::hfe::ai::AISettings::addInterpreterEntry"); + preparePlanInterpreterPool(vehicleTypeId); + static_cast(m_planInterpreterPool[vehicleTypeId])->removeEntry(lod, entry); } -void AISettings::addInterpreterEntry(int, BotLodLevel, BAPEntry *) +// ELF 0x3BF990. +void AISettings::activateDefaultInterpreter(int vehicleTypeId, BAPStatementType type, BotLodLevel lod) { - BF2_AI_FRONTIER("dice::hfe::ai::AISettings::addInterpreterEntry"); + preparePlanInterpreterPool(vehicleTypeId); + static_cast(m_planInterpreterPool[vehicleTypeId])->activateEntry(type, lod); } -void AISettings::removeInterpreterEntry(int, BotLodLevel, BAPEntry *) +// ELF 0x3BF800. +void AISettings::addGenerator(int vehicleTypeId, int behaviourId, PlanGenerator* generator) { - BF2_AI_FRONTIER("dice::hfe::ai::AISettings::removeInterpreterEntry"); + preparePlanGeneratorPool(vehicleTypeId, behaviourId); + m_planGeneratorPool[vehicleTypeId][behaviourId] = generator; } -void AISettings::activateDefaultInterpreter(int, BAPStatementType, BotLodLevel) +// ELF 0x3BFA20: one behaviour list per vehicle up to `vehicle`; a list too short for `index` is +// sized to the number of behaviours (not to index + 1); the default table grows with -1 entries. +// Every size test is signed (`cmpl ...; jg`). +void AISettings::prepareBehaviourPool(int vehicleTypeId, int behaviourId) { - BF2_AI_FRONTIER("dice::hfe::ai::AISettings::activateDefaultInterpreter"); + if (static_cast(m_behaviourPool.size()) <= vehicleTypeId) + m_behaviourPool.resize(vehicleTypeId + 1, std::vector()); + std::vector& behaviours = m_behaviourPool[vehicleTypeId]; + if (static_cast(behaviours.size()) <= behaviourId) + behaviours.resize(m_behaviourCount, 0); + prepareVehicleGroup(vehicleTypeId); + if (static_cast(m_defaultBehaviour.size()) <= vehicleTypeId) + m_defaultBehaviour.resize(vehicleTypeId + 1, -1); +} + +// ELF 0x3BFC50: as prepareBehaviourPool, with the vehicle group prepared before the inner list. +void AISettings::preparePlanGeneratorPool(int vehicleTypeId, int behaviourId) +{ + if (static_cast(m_planGeneratorPool.size()) <= vehicleTypeId) + m_planGeneratorPool.resize(vehicleTypeId + 1, std::vector()); + prepareVehicleGroup(vehicleTypeId); + std::vector& generators = m_planGeneratorPool[vehicleTypeId]; + if (static_cast(generators.size()) <= behaviourId) + generators.resize(m_behaviourCount, 0); +} + +// ELF 0x3BFDE0: one `new BAPInterpreter(45)` (operator new 0x10; 45 statement types) per missing +// vehicle, each checked (checkPointer, the Debug at line 46) and pushed back. +void AISettings::preparePlanInterpreterPool(int vehicle) +{ + if (static_cast(m_planInterpreterPool.size()) <= vehicle) + { + for (unsigned int i = static_cast(m_planInterpreterPool.size()); i < static_cast(vehicle + 1); ++i) + m_planInterpreterPool.push_back(checkPointer(new BAPInterpreter(45))); + } + prepareVehicleGroup(vehicle); } -void AISettings::addGenerator(int, int, PlanGenerator *) +// ELF 0x3C0040: the vehicle-group table grows to the vehicle with group 0. +void AISettings::prepareVehicleGroup(int vehicle) { - BF2_AI_FRONTIER("dice::hfe::ai::AISettings::addGenerator"); + if (vehicle >= static_cast(m_vehicleGroups.size())) + m_vehicleGroups.resize(vehicle + 1, 0); } -void AISettings::setBasicBotWeights(float *) +// ELF 0x3BF9F0: the class static BotMain reads (BotMain::setBasicWeights). +void AISettings::setBasicBotWeights(float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::AISettings::setBasicBotWeights"); + BotMain::setBasicWeights(weights); } +// ELF 0x3C0240. void AISettings::setStatsViewDistance(float distance) { m_statsViewDistance = distance; } +// ELF 0x3C0260. void AISettings::setDrawBotStats(bool draw) { m_drawBotStats = draw; } +// ELF 0x3C0210. void AISettings::setInformationGridDimension(int dimension) { m_informationGridDimension = dimension; } +// ELF 0x3C0280. void AISettings::setNSides(int sides) { m_nSides = sides; } +// ELF 0x3C0A10. void AISettings::setSAIUpdateFrequency(float frequency) { m_saiUpdateFrequency = frequency; } +// ELF 0x3C0A20. void AISettings::setStandardPersonality(float* weights, int side) { m_standardPersonality[side - 1] = weights; } +// ELF 0x3C0A40. void AISettings::setStandardMoralAdmin(BotMoralAdmin* admin, int side) { m_standardMoralAdmin[side - 1] = admin; } +// ELF 0x3C0AB0. void AISettings::setRespawnAllowed(bool allowed) { m_respawnAllowed = allowed; @@ -340,32 +464,36 @@ void AISettings::setRespawnAllowed(bool allowed) // Duplicate insertion failure is deliberately ignored; the three // parallel vectors still grow, while the name map retains the first id. +// ELF 0x3BEFC0. void AISettings::setVehicle(const std::string& name) { - const int id = static_cast(m_vehicleIndex.size()); - m_vehicleIndex.insert(std::make_pair(name, id)); + const int id = static_cast(m_vehicleIdMap.size()); + m_vehicleIdMap.insert(std::make_pair(name, id)); m_vehicleNames.push_back(name); - m_vehicleMaterialManagers.push_back(checkPointer(new MaterialManager)); + m_materialManagers.push_back(checkPointer(new MaterialManager)); m_clusterCostTypes.push_back(-1); } // Both map finds are intentionally unguarded. +// ELF 0x3BF5A0. void AISettings::setVehicleClusterMapping(const std::string& vehicle, const std::string& clusterVehicle) { - const int vehicleId = m_vehicleIndex.find(vehicle)->second; - const int clusterVehicleId = m_vehicleIndex.find(clusterVehicle)->second; + const int vehicleId = m_vehicleIdMap.find(vehicle)->second; + const int clusterVehicleId = m_vehicleIdMap.find(clusterVehicle)->second; m_clusterCostTypes[vehicleId] = clusterVehicleId; } // Retail uses resize rather than push_back and ignores duplicates. +// ELF 0x3C0640. void AISettings::createVehicleGroup(const std::string& name) { const int id = static_cast(m_vehicleGroupNames.size()); m_vehicleGroupNames.resize(m_vehicleGroupNames.size() + 1, name); - m_vehicleGroupIndex.insert(std::make_pair(name, id)); + m_namesToVehicleGroups.insert(std::make_pair(name, id)); } +// ELF 0x3C0790. void AISettings::addVehicleToVehicleGroup(int vehicle, const std::string& group) { // [PLATFORM] This single expression is load-bearing: PE captures the destination before the @@ -373,6 +501,7 @@ void AISettings::addVehicleToVehicleGroup(int vehicle, const std::string& group) m_vehicleGroups[vehicle] = getVehicleGroup(group); } +// ELF 0x3C07D0. void AISettings::addVehicleToVehicleGroup(const std::string& vehicle, const std::string& group) { @@ -392,6 +521,7 @@ void AISettings::addVehicleToVehicleGroup(const std::string& vehicle, // Stores the auto-spawn flag. Enabling also requests immediate spawning when IAIMain // exists; disabling performs no spawn action. +// ELF 0x3C0EA0. void AISettings::setAutoSpawnBots(bool enable) { m_autoSpawnBots = enable; @@ -400,39 +530,50 @@ void AISettings::setAutoSpawnBots(bool enable) IAIMain::m_instance->spawnBots(); } -void AISettings::setDraw(bool) +// ELF 0x3C0C10. Disabling drawing clears render objects without a singleton guard. +void AISettings::setDraw(bool draw) { - BF2_AI_FRONTIER("dice::hfe::ai::AISettings::setDraw"); + m_draw = draw; + if (!draw) + AIRenderUtil::m_instance->unrenderAll(); } -void AISettings::setSensingAgentPatternName(const std::string&) +// ELF 0x3C0C50: registers the name under the next index (insert_unique: a known name keeps its +// index). +void AISettings::setSensingAgentPatternName(const std::string& name) { - BF2_AI_FRONTIER("dice::hfe::ai::AISettings::setSensingAgentPatternName"); + const int index = static_cast(m_sensingAgentPatternIds.size()); + m_sensingAgentPatternIds.insert(std::pair(name, index)); } +// ELF 0x3C0D80. void AISettings::setSensingAgentNullPattern(ISensingAgentPattern* pattern) { - m_sensingAgentNullPattern = pattern; + m_nullPattern = pattern; } -void AISettings::addSensingAgentPattern(int, ISensingAgentPattern *) +// ELF 0x3C0DA0: insert_unique(vehicle, pattern) into the +0x6C map. +void AISettings::addSensingAgentPattern(int vehicle, ISensingAgentPattern* pattern) { - BF2_AI_FRONTIER("dice::hfe::ai::AISettings::addSensingAgentPattern"); + m_sensingAgentPatterns.insert(std::pair(vehicle, pattern)); } +// ELF 0x3C0FF0. void AISettings::setManDownEquipment(const std::string& equipment) { m_manDownEquipment = equipment; } +// ELF 0x3C1020. void AISettings::setVehicleMaterialCost(const std::string& vehicle, unsigned char material, float cost) { - m_vehicleMaterialManagers[getVehicle(vehicle)]->setMaterialCost(material, cost); + m_materialManagers[getVehicle(vehicle)]->setMaterialCost(material, cost); } // Adds a name to the bot-name roster used by getBotName. +// ELF 0x3C1190. void AISettings::addBotName(const std::string& first, const std::string& last) { const unsigned int count = static_cast(m_botNames.size()); @@ -458,6 +599,7 @@ void AISettings::addBotName(const std::string& first, const std::string& last) m_botNames.insert(position, std::pair(weight, first + " " + last)); } +// ELF 0x3C1520. void AISettings::setBotNameUnused(const std::string&) { // (*) five bytes in the binary - a bare `ret`. dice declared it, the .ai console binds it, and @@ -465,10 +607,10 @@ void AISettings::setBotNameUnused(const std::string&) } -// Initializes AI settings and their default values. +// ELF 0x3BD020 / 0x3BD5B0. Initializes AI settings and their default values. AISettings::AISettings() : m_maxNBots(-1) - , m_numberOfBehaviours(0) + , m_behaviourCount(0) , m_viewDistance(-1.0f) , m_statsViewDistance(30.0f) , m_botSkill(0.75f) @@ -483,7 +625,7 @@ AISettings::AISettings() , m_overrideMenuSettings(false) , m_drawBotStats(true) { - // Defect 1: m_sensingAgentNullPattern is deliberately not initialised here. See above. + // Defect 1: m_nullPattern is deliberately not initialised here. See above. // Both arrays are indexed [side - 1]; the constructor nulls all four words. m_standardMoralAdmin[0] = 0; @@ -508,104 +650,122 @@ AISettings::AISettings() // Registers the first settings/modifier instance using roster-static guards. // Those guards can remain stale until updateStaticMethods refreshes the roster. +// ELF 0x3E7100 / 0x3E71A0. IAISettings::IAISettings() { if (!CommonSingletonServer::m_iaiSettings) classManager->registerSimpleSingleton("IAISettings", this); } +// ELF 0x3E7240 / 0x3E72D0 / 0x3E7360. IAISettings::~IAISettings() { if (CommonSingletonServer::m_iaiSettings == this) classManager->unregisterSimpleSingleton("IAISettings"); } +// ELF 0x3E74B0 / 0x3E7550. IAISettingsModifier::IAISettingsModifier() { if (!CommonSingletonServer::m_iaiSettingsModifier) classManager->registerSimpleSingleton("IAISettingsModifier", this); } +// ELF 0x3E75F0 / 0x3E7680 / 0x3E7710. IAISettingsModifier::~IAISettingsModifier() { if (CommonSingletonServer::m_iaiSettingsModifier == this) classManager->unregisterSimpleSingleton("IAISettingsModifier"); } -// Remaining recovered field accessors. The constructor now supplies their proven backing fields; -// AISettings teardown remains a separate named frontier below. +// Remaining recovered field accessors. +// ELF 0x3BEF20. int AISettings::getMaxNBots() const { return m_maxNBots; } +// ELF 0x3BEF30. bool AISettings::getmaxBotsIncludeHumans() const { return m_maxBotsIncludeHumans; } +// ELF 0x3BEF40. float AISettings::getIgnoreCommanderDistance() const { return m_ignoreCommanderDistance; } +// ELF 0x3C00F0. float AISettings::getViewDistance() const { return m_viewDistance; } +// ELF 0x3C0620. float AISettings::getBotSkill() const { return m_botSkill; } +// ELF 0x3C0290. int AISettings::getNSides() const { return m_nSides; } +// ELF 0x3C0AA0. bool AISettings::isRespawnAllowed() const { return m_respawnAllowed; } +// ELF 0x3C0E90. bool AISettings::getAutoSpawnBots() const { return m_autoSpawnBots; } +// ELF 0x3C0BD0. const float* AISettings::getArmourClassValues() const { return m_armourClassValues; } +// ELF 0x3C0BE0. float AISettings::getArmourClassValue(int index) const { return m_armourClassValues[index]; } +// ELF 0x3BF700. void AISettings::setMaxNBots(int n) { m_maxNBots = n; } +// ELF 0x3BF710. void AISettings::maxBotsIncludeHumans(bool include) { m_maxBotsIncludeHumans = include; } +// ELF 0x3BF720. void AISettings::setIgnoreCommanderDistance(float distance) { m_ignoreCommanderDistance = distance; } +// ELF 0x3C0630. void AISettings::setBotSkill(float skill) { m_botSkill = skill; } // Sets the AI view distance and propagates it to every live bot player. +// ELF 0x3C0100. void AISettings::setViewDistance(float distance) { m_viewDistance = distance; @@ -639,179 +799,78 @@ void AISettings::setViewDistance(float distance) } } +// ELF 0x3C1550. void AISettings::setOverrideMenuSettings(bool override_) { m_overrideMenuSettings = override_; } -void AISettings::reset() -{ - BF2_AI_FRONTIER("dice::hfe::ai::AISettings::reset"); -} - - -// [FRONTIER] Destruction requires cleanup of owned settings collections. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding AISettings operation. +// ELF 0x3C02A0. Resets only the shipped subset of settings and registries. +bool AISettings::reset() +{ + if (AIRadio::m_instance) + AIRadio::m_instance->reset(); + // shipped defect: deleted entries stay in their vectors and can be deleted again. + for (unsigned int row = 0; row < m_behaviourPool.size(); ++row) + for (unsigned int i = 0; i < m_behaviourPool[row].size(); ++i) + if (m_behaviourPool[row][i]) + delete m_behaviourPool[row][i]; + for (unsigned int row = 0; row < m_planGeneratorPool.size(); ++row) + for (unsigned int i = 0; i < m_planGeneratorPool[row].size(); ++i) + if (m_planGeneratorPool[row][i]) + delete m_planGeneratorPool[row][i]; + for (unsigned int i = 0; i < m_planInterpreterPool.size(); ++i) + if (m_planInterpreterPool[i]) + delete m_planInterpreterPool[i]; + m_vehicleIdMap.clear(); + m_vehicleNames.resize(0); + m_sensingAgentPatternIds.clear(); + m_sensingAgentPatterns.clear(); + m_maxNBots = -1; + // [UNRESOLVED] Types/names of the two words at +0x10/+0x14; both are zeroed here. + std::memset(m_gap16, 0, sizeof(m_gap16)); + m_behaviourCount = 0; + m_informationGridDimension = 32; + m_viewDistance = 600.0f; + m_nSides = 0; + m_standardPersonality[0] = 0; + m_statsViewDistance = 512.0f; + m_standardPersonality[1] = 0; + m_autoSpawnBots = false; + m_botSkill = 0.75f; + m_respawnAllowed = true; + m_draw = false; + m_saiUpdateFrequency = 2.0f; + m_standardMoralAdmin[0] = 0; + m_standardMoralAdmin[1] = 0; + return true; +} + + +// ELF 0x3BE130 (1772 B; the other variants are 0x3BDA40 and 0x3BE820). The shipped body first deletes +// AIRadio::m_instance (null-tested, nonvirtual D1 + operator delete). Nothing in libaidll.so +// constructs an AIRadio (see AIRadio.h), so the pointer is null and the step does nothing; it is +// kept because the instruction is there. Then every behaviour and every plan generator (per +// vehicle row) and every plan interpreter go through their virtual deleting destructors (+4), +// and every vehicle material manager through its nonvirtual one. The pointers are not cleared. +// The containers, the strings and both interface bases follow as members. AISettings::~AISettings() { - BF2_AI_FRONTIER("dice::hfe::ai::AISettings::~AISettings"); -} - -// Console bindings for bot population and startup settings. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. - -namespace { - -const char* const kAiSettingsConsoleTag = "aiSettings"; - -// Every forwarder takes the same receiver, and the [CHOSEN] caveat above covers all of them. -AISettings* consoleAiSettings() -{ - return static_cast( - static_cast(CommonSingletonServer::m_iaiSettings)); -} - -void consoleAiSettingsSetMaxNBots(int n) { consoleAiSettings()->setMaxNBots(n); } -void consoleAiSettingsSetNSides(int sides) { consoleAiSettings()->setNSides(sides); } -void consoleAiSettingsSetBotSkill(float skill) { consoleAiSettings()->setBotSkill(skill); } -void consoleAiSettingsMaxBotsIncludeHumans(bool include){ consoleAiSettings()->maxBotsIncludeHumans(include); } -void consoleAiSettingsSetInformationGridDimension(int d){ consoleAiSettings()->setInformationGridDimension(d); } -// the only forwarder here that is not A store: `setAutoSpawnBots` also calls -// `IAIMain::spawnBots`, so this console line has a side effect the other five do not. -void consoleAiSettingsSetAutoSpawnBots(bool enable) { consoleAiSettings()->setAutoSpawnBots(enable); } -// two arguments for one name: the console splits `addBotName T. Karlsson` on whitespace and -// the receiver puts the space back. See addBotName's own note. -void consoleAiSettingsAddBotName(std::string first, std::string last) - { consoleAiSettings()->addBotName(first, last); } - -// The recovered roster classes dispatch through the registered write interface and report -// inactive while it is absent. Their argument type strings and relative order are paired in both -// generated-console images. -IAISettingsModifier* consoleAiSettingsModifier() -{ - return static_cast(CommonSingletonServer::m_iaiSettingsModifier); -} - -void consoleAiSettingsSetMaxNumberOfBehaviours(int count) -{ - consoleAiSettingsModifier()->setMaxNumberOfBehaviours(count); -} - -void consoleAiSettingsSetVehicle(std::string name) -{ - consoleAiSettingsModifier()->setVehicle(name); -} - -void consoleAiSettingsSetVehicleClusterMapping(std::string vehicle, - std::string clusterVehicle) -{ - consoleAiSettingsModifier()->setVehicleClusterMapping(vehicle, clusterVehicle); -} - -void consoleAiSettingsSetVehicleMaterialCost(std::string vehicle, - materialId material, - float cost) -{ - consoleAiSettingsModifier()->setVehicleMaterialCost(vehicle, material, cost); -} - -void consoleAiSettingsSetManDownEquipment(std::string equipment) -{ - consoleAiSettingsModifier()->setManDownEquipment(equipment); -} - -void consoleAiSettingsCreateVehicleGroup(std::string name) -{ - consoleAiSettingsModifier()->createVehicleGroup(name); -} - -void consoleAiSettingsAddVehicleToVehicleGroup(std::string vehicle, - std::string group) -{ - consoleAiSettingsModifier()->addVehicleToVehicleGroup(vehicle, group); -} - -// Generic generated arguments retain the shared temp-and-commit extraction rule. materialId is the -// one recovered exception: its generated class calls the AI material extractor directly into the -// byte-sized static storage. -template -void convertAiSettingsRosterArgument(const std::string& text, T& storage) -{ - T value = storage; - std::istringstream stream(text); - stream >> value; - if (!stream.fail()) - storage = value; -} - -void convertAiSettingsRosterArgument(const std::string& text, materialId& storage) -{ - std::istringstream stream(text); - ::dice::hfe::ai::operator>>(stream, storage); -} - -} // anonymous namespace - -// Console bindings for AI settings and vehicle definitions. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. -BF2_CONSOLE_OBJECT("aiSettings", 2, 0) -BF2_CONSOLE_METHOD_1(setMaxNBots, consoleAiSettingsSetMaxNBots, int, kAiSettingsConsoleTag) -BF2_CONSOLE_METHOD_1(setNSides, consoleAiSettingsSetNSides, int, kAiSettingsConsoleTag) -BF2_CONSOLE_METHOD_1(setBotSkill, consoleAiSettingsSetBotSkill, float, kAiSettingsConsoleTag) -BF2_CONSOLE_METHOD_1(maxBotsIncludeHumans, consoleAiSettingsMaxBotsIncludeHumans, bool, kAiSettingsConsoleTag) -BF2_CONSOLE_METHOD_1(setInformationGridDimension, consoleAiSettingsSetInformationGridDimension, int, kAiSettingsConsoleTag) -// Exposes the auto-spawn setting used by level scripts. -BF2_CONSOLE_METHOD_1(setAutoSpawnBots, consoleAiSettingsSetAutoSpawnBots, bool, kAiSettingsConsoleTag) -// Registers the command used by BotNames.ai to populate the bot-name roster. -BF2_CONSOLE_METHOD_2(addBotName, consoleAiSettingsAddBotName, std::string, std::string, kAiSettingsConsoleTag) - -// ELF generated classes 262/267/268/269/270/283/284 and the matching PE CRT initializer order. The -// temporary BF2_CC_CONVERT specialization keeps every ordinary conversion unchanged while routing -// the `materialId` spelling through Material.cpp rather than std's character extractor. -#pragma push_macro("BF2_CC_CONVERT") -#undef BF2_CC_CONVERT -#define BF2_CC_CONVERT(T, oneBasedIndex) \ - if (index == (oneBasedIndex)) \ - { \ - static T s; \ - convertAiSettingsRosterArgument(value, s); \ - m_args[(oneBasedIndex) - 1] = reinterpret_cast(&s); \ - } - -BF2_CONSOLE_METHOD_1_STATIC_ACTIVE(setMaxNumberOfBehaviours, - consoleAiSettingsSetMaxNumberOfBehaviours, - CommonSingletonServer::m_iaiSettingsModifier != 0, - int, kAiSettingsConsoleTag) -BF2_CONSOLE_METHOD_1_STATIC_ACTIVE(setVehicle, consoleAiSettingsSetVehicle, - CommonSingletonServer::m_iaiSettingsModifier != 0, - std::string, kAiSettingsConsoleTag) -BF2_CONSOLE_METHOD_2_STATIC_ACTIVE(setVehicleClusterMapping, - consoleAiSettingsSetVehicleClusterMapping, - CommonSingletonServer::m_iaiSettingsModifier != 0, - std::string, std::string, kAiSettingsConsoleTag) -BF2_CONSOLE_METHOD_3_STATIC_ACTIVE(setVehicleMaterialCost, - consoleAiSettingsSetVehicleMaterialCost, - CommonSingletonServer::m_iaiSettingsModifier != 0, - std::string, materialId, float, kAiSettingsConsoleTag) -BF2_CONSOLE_METHOD_1_STATIC_ACTIVE(setManDownEquipment, - consoleAiSettingsSetManDownEquipment, - CommonSingletonServer::m_iaiSettingsModifier != 0, - std::string, kAiSettingsConsoleTag) -BF2_CONSOLE_METHOD_1_STATIC_ACTIVE(createVehicleGroup, - consoleAiSettingsCreateVehicleGroup, - CommonSingletonServer::m_iaiSettingsModifier != 0, - std::string, kAiSettingsConsoleTag) -BF2_CONSOLE_METHOD_2_STATIC_ACTIVE(addVehicleToVehicleGroup, - consoleAiSettingsAddVehicleToVehicleGroup, - CommonSingletonServer::m_iaiSettingsModifier != 0, - std::string, std::string, kAiSettingsConsoleTag) - -#pragma pop_macro("BF2_CC_CONVERT") - -// Handed to the console registry by AIModule::init, beside the `ai` object's list. -ConsoleObjectList& aiSettingsConsoleObjects() -{ - return consoleBindingList(kAiSettingsConsoleTag); + delete AIRadio::m_instance; + for (unsigned int row = 0; row < m_behaviourPool.size(); ++row) + for (unsigned int i = 0; i < m_behaviourPool[row].size(); ++i) + if (m_behaviourPool[row][i]) + delete m_behaviourPool[row][i]; + for (unsigned int row = 0; row < m_planGeneratorPool.size(); ++row) + for (unsigned int i = 0; i < m_planGeneratorPool[row].size(); ++i) + if (m_planGeneratorPool[row][i]) + delete m_planGeneratorPool[row][i]; + for (unsigned int i = 0; i < m_planInterpreterPool.size(); ++i) + if (m_planInterpreterPool[i]) + delete m_planInterpreterPool[i]; + for (unsigned int i = 0; i < m_materialManagers.size(); ++i) + if (m_materialManagers[i]) + delete m_materialManagers[i]; } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/Main/AISettings.h b/Code/BF2/AI/AIDLL/AI/Main/AISettings.h index abb85fb56..07b2a7848 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AISettings.h +++ b/Code/BF2/AI/AIDLL/AI/Main/AISettings.h @@ -10,7 +10,13 @@ #include #include +#include + +#include "../AIStrategic/StatusMap.h" +#include "../AIStrategic/StrategyCondition.h" +#include "../AIStrategicEntity/AIStrategicObject.h" #include "AISettingsInterfaces.h" // the two bases, all 87 slots - RW-9's retirement +#include "AIStreamOperators.h" // the console argument extractors namespace dice { namespace hfe { @@ -21,6 +27,7 @@ class BotBehaviour; class BotMoralAdmin; class ISensingAgentPattern; class PlanGenerator; +class PlanInterpreter; // The two abstract halves are declared in AISettingsInterfaces.h with all 87 virtual positions. // AISettings is the concrete implementation in both recovered images. @@ -44,7 +51,7 @@ class AISettings : public IAISettings, public IAISettingsModifier virtual float* getVehicleMods(int) const; virtual BotBehaviour* getBehaviour(int, int) const; virtual BotBehaviour* getDefaultBehaviour(int) const; - virtual void* getPlanInterpreter(int) const; + virtual PlanInterpreter* getPlanInterpreter(int) const; virtual PlanGenerator* getPlanGenerator(int, int) const; virtual float getViewDistance() const; virtual float getStatsViewDistance() const; @@ -75,7 +82,7 @@ class AISettings : public IAISettings, public IAISettingsModifier virtual bool getAutoSpawnBots() const; virtual const float* getArmourClassValues() const; virtual float getArmourClassValue(int) const; - virtual void reset(); + virtual bool reset(); virtual int getManDownEquipmentType(); virtual bool isValidMaterial(int, unsigned char) const; virtual float getVehicleMaterialCost(const std::string&, unsigned char) const; @@ -86,8 +93,11 @@ class AISettings : public IAISettings, public IAISettingsModifier virtual bool overrideMenuSettings() const; virtual bool getOverrideMenuSettings() const; - // IAISettingsModifier, slots 0..38 in vtable order; reset is shared with the read - // side above and is therefore declared only once. + // The IAISettingsModifier overriders, in AISettings's own primary-vtable order (ELF vtable for + // AISettings +0xC8..+0x15C; the order differs from the interface's: createVehicleGroup precedes + // setVehicle, and setAutoSpawnBots follows addSensingAgentPattern). The interface's own slot + // order is IAISettingsModifier's declaration order. reset is shared with the read side above + // and is therefore declared only once. virtual void setMaxNBots(int); virtual void maxBotsIncludeHumans(bool); virtual void setIgnoreCommanderDistance(float); @@ -108,19 +118,19 @@ class AISettings : public IAISettings, public IAISettingsModifier virtual void setNSides(int); virtual void setBotSkill(float); virtual void setSAIUpdateFrequency(float); - virtual void setStandardPersonality(float *, int); - virtual void setStandardMoralAdmin(BotMoralAdmin *, int); - virtual void setRespawnAllowed(bool); + virtual void createVehicleGroup(const std::string&); virtual void setVehicle(const std::string&); virtual void setVehicleClusterMapping(const std::string&, const std::string&); - virtual void createVehicleGroup(const std::string&); virtual void addVehicleToVehicleGroup(int, const std::string&); virtual void addVehicleToVehicleGroup(const std::string&, const std::string&); - virtual void setAutoSpawnBots(bool); + virtual void setStandardPersonality(float *, int); + virtual void setStandardMoralAdmin(BotMoralAdmin *, int); + virtual void setRespawnAllowed(bool); virtual void setDraw(bool); virtual void setSensingAgentPatternName(const std::string&); virtual void setSensingAgentNullPattern(ISensingAgentPattern *); virtual void addSensingAgentPattern(int, ISensingAgentPattern *); + virtual void setAutoSpawnBots(bool); virtual void setManDownEquipment(const std::string&); virtual void setVehicleMaterialCost(const std::string&, unsigned char, float); virtual void addBotName(const std::string&, const std::string&); @@ -128,11 +138,16 @@ class AISettings : public IAISettings, public IAISettingsModifier virtual void setOverrideMenuSettings(bool); private: + // Non-virtual pool helpers (direct PLT calls), ELF 0x3BFA20 / 0x3BFC50 / 0x3BFDE0 / 0x3C0040. + void prepareBehaviourPool(int vehicleTypeId, int behaviourId); + void preparePlanGeneratorPool(int vehicleTypeId, int behaviourId); + void preparePlanInterpreterPool(int vehicle); + void prepareVehicleGroup(int vehicle); + // Field offsets describe retail x86 layout; native STL sizes may differ. /* 8 */ int m_maxNBots; // = -1 getMaxNBots / setMaxNBots - /* 12 */ int m_numberOfBehaviours; // = 0 getNumberOfBehaviours - /* 16 */ char m_gap16[8]; // the constructor never writes these eight bytes - // and no accessor reads them. [UNRESOLVED] + /* 12 */ int m_behaviourCount; // = 0 getNumberOfBehaviours // name: AIDLL_r assert 0x100C2690 (PE +0xC) + /* 16 */ char m_gap16[8]; // [UNRESOLVED] two words reset zeroes; ctor leaves them alone /* 24 */ float m_viewDistance; // = -1.0f getViewDistance /* 28 */ float m_statsViewDistance; // = 30.0f get/setStatsViewDistance /* 32 */ float m_botSkill; // = 0.75f get/setBotSkill @@ -150,19 +165,19 @@ class AISettings : public IAISettings, public IAISettingsModifier /* 56 */ std::string m_manDownEquipment; // the size of this vector is `getNumberOfVehicles`. The AI counts vehicles by counting - // behaviour lists, one per vehicle; `getBehaviour(vehicle, i)` is `m_behaviours[vehicle][i]`. - /* 60 */ std::vector > m_behaviours; - /* 72 */ std::vector m_defaultBehaviour; // index into m_behaviours[v]; -1 = none - /* 84 */ std::vector > m_planGenerators; - /* 96 */ std::vector m_planInterpreters; // [UNRESOLVED] element type - placeholder + // behaviour lists, one per vehicle; `getBehaviour(vehicle, i)` is `m_behaviourPool[vehicle][i]`. + /* 60 */ std::vector > m_behaviourPool; // name: AIDLL_r assert 0x100C2980 (PE +0x50) + /* 72 */ std::vector m_defaultBehaviour; // index into m_behaviourPool[v]; -1 = none + /* 84 */ std::vector > m_planGeneratorPool; // name: AIDLL_r assert 0x100C2DD0 (PE +0x70) + /* 96 */ std::vector m_planInterpreterPool; // each a BAPInterpreter (vector::_M_insert_aux) // name: AIDLL_r assert 0x100C0DF0 (PE +0x80) /* 108 */ std::map m_sensingAgentPatterns; - /* 120 */ std::vector m_vehicleMaterialManagers; + /* 120 */ std::vector m_materialManagers; // name: AIDLL_r assert 0x100BD950 (PE +0xA0) // Uninitialized until setSensingAgentNullPattern is called; callers must set it before use. - /* 132 */ ISensingAgentPattern* m_sensingAgentNullPattern; + /* 132 */ ISensingAgentPattern* m_nullPattern; // name: AIDLL_r assert "m_nullPattern != 0" (0x100BA3F0) /* 136 */ std::vector m_vehicleGroupNames; // size == getNumberOfVehicleGroups - /* 148 */ std::map m_vehicleGroupIndex; // createVehicleGroup inserts here + /* 148 */ std::map m_namesToVehicleGroups; // createVehicleGroup inserts here // name: AIDLL_r assert 0x100BED20 (PE +0xC4) /* 160 */ std::vector m_vehicleGroups; // Two per-side arrays indexed by side - 1; callers must supply side 1 or 2. @@ -170,7 +185,7 @@ class AISettings : public IAISettings, public IAISettingsModifier /* 180 */ float* m_standardPersonality[2]; /* 188 */ std::vector m_vehicleMods; - /* 200 */ std::map m_vehicleIndex; // setVehicle inserts; getVehicle(name) reads + /* 200 */ std::map m_vehicleIdMap; // setVehicle inserts; getVehicle(name) reads // name: AIDLL_r assert 0x100BE960 (PE +0x100) /* 212 */ std::vector m_vehicleNames; // setVehicle push_backs the same name here /* 224 */ std::vector m_clusterCostTypes; /* 236 */ std::string m_sensingAgentPatternName; // [INFERRED] setSensingAgentPatternName @@ -178,13 +193,17 @@ class AISettings : public IAISettings, public IAISettingsModifier // Six zero-based armor-class weights, initialized to 1, 3, 8, 15, 10, and 12. /* 240 */ float m_armourClassValues[6]; - /* 264 */ std::map m_tree264; // [UNRESOLVED] Key and mapped types are placeholders. + // Pattern name -> registration index (setSensingAgentPatternName, ELF 0x3C0C50: insert_unique of + // the map's size before the insert). Name [INFERRED]. + /* 264 */ std::map m_sensingAgentPatternIds; // Mutable because getBotName rotates the list while satisfying the const interface. /* 276 */ mutable std::list > m_botNames; // addBotName / getBotName /* 280 */ bool m_overrideMenuSettings; // = false overrideMenuSettings + getOverrideMenuSettings /* 281 */ bool m_drawBotStats; // = true getDrawBotStats / setDrawBotStats }; +// The console argument extractors moved to AIStreamOperators.h (included above). + } // namespace ai } // namespace hfe } // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/Main/AISettingsInterfaces.h b/Code/BF2/AI/AIDLL/AI/Main/AISettingsInterfaces.h index a9fc688ab..07c17284b 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AISettingsInterfaces.h +++ b/Code/BF2/AI/AIDLL/AI/Main/AISettingsInterfaces.h @@ -19,6 +19,7 @@ class BotBehaviour; class BotMoralAdmin; class ISensingAgentPattern; class PlanGenerator; +class PlanInterpreter; // [UNRESOLVED] enumerators. Both are one dword on the stack at every call site. enum BotLodLevel : int; @@ -38,7 +39,7 @@ class IAISettings virtual float* getVehicleMods(int) const = 0; virtual BotBehaviour* getBehaviour(int, int) const = 0; virtual BotBehaviour* getDefaultBehaviour(int) const = 0; - virtual void* getPlanInterpreter(int) const = 0; + virtual PlanInterpreter* getPlanInterpreter(int) const = 0; virtual PlanGenerator* getPlanGenerator(int, int) const = 0; virtual float getViewDistance() const = 0; virtual float getStatsViewDistance() const = 0; @@ -72,7 +73,7 @@ class IAISettings virtual bool getAutoSpawnBots() const = 0; virtual const float* getArmourClassValues() const = 0; virtual float getArmourClassValue(int) const = 0; - virtual void reset() = 0; + virtual bool reset() = 0; virtual int getManDownEquipmentType() = 0; virtual bool isValidMaterial(int, unsigned char) const = 0; virtual float getVehicleMaterialCost(const std::string&, unsigned char) const = 0; @@ -124,7 +125,7 @@ class IAISettingsModifier virtual void setSensingAgentPatternName(const std::string&) = 0; virtual void setSensingAgentNullPattern(ISensingAgentPattern *) = 0; virtual void addSensingAgentPattern(int, ISensingAgentPattern *) = 0; - virtual void reset() = 0; + virtual bool reset() = 0; virtual void setManDownEquipment(const std::string&) = 0; virtual void setVehicleMaterialCost(const std::string&, unsigned char, float) = 0; virtual void addBotName(const std::string&, const std::string&) = 0; diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIStreamOperators.cpp b/Code/BF2/AI/AIDLL/AI/Main/AIStreamOperators.cpp new file mode 100644 index 000000000..680519add --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/Main/AIStreamOperators.cpp @@ -0,0 +1,1029 @@ +// The AI script vocabulary: stream operators for the AI enums. AI/Main/AIStreamOperators.cpp is an +// attested FILE symbol of libaidll.so (its static initializer is named after the TU's first function, +// operator>>(istream&, vector&) 0x3C4150); the text runs to 0x3C9170. + +// static init: ELF 0x3C9170 (__tcf_0 0x3C91D0, _GLOBAL__I 0x3C9200): 's Init object only. +#include + +#include "AIStreamOperators.h" +#include "../../../../Core/StringUtil.h" +#include "../../../../IO/Input/Input.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// The strategy vocabulary extractors (moved from AISettings.cpp; this TU is their image placement). Each table is the ELF's compare chain +// in code order; the chains compare the whole token with std::string::compare. +namespace { + +struct AIEnumSpelling +{ + const char* name; + int value; +}; + +// Answers the first matching spelling's value, or `fallback`; the caller decides whether to assign it. +int readAIEnumSpelling(std::istream& in, const AIEnumSpelling* table, int count, int fallback) +{ + std::string token; + in >> token; + for (int i = 0; i < count; ++i) + { + if (token.compare(table[i].name) == 0) + return table[i].value; + } + return fallback; +} + +} // anonymous namespace + +static const AIEnumSpelling kTemperatureTreeNodeSpellings[] = { + { "TTNTop", 0 }, + { "TTNDynamic", 1 }, + { "TTNStatic", 2 }, + { "TTNFriendly", 3 }, + { "TTNHostile", 4 }, + { "TTNTactical", 5 }, + { "TTNStrategic", 6 }, + { "TTNFriendGroundAndNaval", 7 }, + { "TTNHostileGroundAndNaval", 8 }, + { "TTNFriendArtillery", 9 }, + { "TTNHostileArtillery", 10 }, + { "TTNFriendGround", 11 }, + { "TTNFriendNaval", 12 }, + { "TTNFriendAir", 13 }, + { "TTNHostileGround", 14 }, + { "TTNHostileAir", 15 }, + { "TTNHostileNaval", 16 }, + { "TTNFriendGroundFixed", 17 }, + { "TTNFriendGroundMobile", 18 }, + { "TTNFriendNavalFixed", 19 }, + { "TTNFriendNavalMobile", 20 }, + { "TTNFriendAirFixed", 21 }, + { "TTNFriendAirMobile", 22 }, + { "TTNHostileGroundFixed", 23 }, + { "TTNHostileGroundMobile", 24 }, + { "TTNHostileNavalFixed", 25 }, + { "TTNHostileNavalMobile", 26 }, + { "TTNHostileAirFixed", 27 }, + { "TTNHostileAirMobile", 28 }, + { "TTNDefensivePos", 29 }, + { "TTNTopography", 30 }, + { "TTNEditors", 31 }, + { "TTNFixedWeapons", 32 }, + { "TTNAirfield", 33 }, + { "TTNProduction", 34 }, + { "TTNRadar", 35 }, + { "TTNTransportation", 36 }, + { "TTNControlPoint", 37 }, + { "TTNSupplies", 38 }, + { "TTNSuppliesRepair", 39 }, + { "TTNSuppliesAmmunition", 40 }, +}; + +// ELF 0x3C5400 +std::istream& operator>>(std::istream& in, TemperatureTreeNode& value) +{ + value = static_cast(readAIEnumSpelling(in, kTemperatureTreeNodeSpellings, + sizeof(kTemperatureTreeNodeSpellings) / sizeof(kTemperatureTreeNodeSpellings[0]), -1)); + return in; +} + +static const AIEnumSpelling kCombatStrengthTypeSpellings[] = { + { "0", 0 }, { "CSTInfantry", 0 }, { "CSTInfantery", 0 }, { "Infantry", 0 }, { "Infantery", 0 }, + { "1", 1 }, { "CSTLightArmour", 1 }, { "LightArmour", 1 }, + { "2", 2 }, { "CSTHeavyArmour", 2 }, { "HeavyArmour", 2 }, + { "3", 3 }, { "CSTNavalArmour", 3 }, { "NavalArmour", 3 }, + { "4", 4 }, { "CSTHelicopter", 4 }, { "Helicopter", 4 }, + { "5", 5 }, { "CSTAirPlane", 5 }, { "AirPlane", 5 }, + { "CSTNumberOfTypes", 6 }, { "All", 6 }, +}; + +// ELF 0x3C5A60. The final "All" comparison is made even though either outcome stores 6. +std::istream& operator>>(std::istream& in, CombatStrengthType& value) +{ + value = static_cast(readAIEnumSpelling(in, kCombatStrengthTypeSpellings, + sizeof(kCombatStrengthTypeSpellings) / sizeof(kCombatStrengthTypeSpellings[0]), 6)); + return in; +} + +static const AIEnumSpelling kLandingZoneDirectionSpellings[] = { + { "LZXMin", 0 }, { "XMin", 0 }, { "0", 0 }, + { "LZZMin", 1 }, { "ZMin", 1 }, { "1", 1 }, + { "LZXMax", 2 }, { "XMax", 2 }, { "2", 2 }, + { "LZZMax", 3 }, { "ZMax", 3 }, { "3", 3 }, + { "LZUndefined", 4 }, { "Undefined", 4 }, { "-1", 4 }, { "4", 4 }, +}; + +// ELF 0x3C8A20. The final "4" comparison is made even though either outcome stores 4. +std::istream& operator>>(std::istream& in, LandingZoneDirection& value) +{ + value = static_cast(readAIEnumSpelling(in, kLandingZoneDirectionSpellings, + sizeof(kLandingZoneDirectionSpellings) / sizeof(kLandingZoneDirectionSpellings[0]), 4)); + return in; +} + +// ELF 0x3C5F00. +static const AIEnumSpelling kConditionStrengthSpellings[] = { + { "Required", 0 }, + { "RequiredPositive", 1 }, + { "RequiredNegative", 2 }, + { "Advisory", 3 }, + { "AdvisoryPositive", 4 }, + { "AdvisoryNegative", 5 }, +}; + +std::istream& operator>>(std::istream& in, StrategyCondition::ConditionStrength& value) +{ + value = static_cast(readAIEnumSpelling(in, kConditionStrengthSpellings, sizeof(kConditionStrengthSpellings) / sizeof(kConditionStrengthSpellings[0]), 6)); + return in; +} + +// ELF 0x3C60E0. +static const AIEnumSpelling kCompareTypeSpellings[] = { + { "Crisp", 0 }, + { "Fuzzy", 1 }, + { "FuzzySqr", 2 }, +}; + +std::istream& operator>>(std::istream& in, StrategyCondition::CompareType& value) +{ + value = static_cast(readAIEnumSpelling(in, kCompareTypeSpellings, sizeof(kCompareTypeSpellings) / sizeof(kCompareTypeSpellings[0]), 3)); + return in; +} + +// ELF 0x3C6240. +static const AIEnumSpelling kConditionSideSpellings[] = { + { "Friendly", 0 }, + { "Enemy", 1 }, + { "Both", 2 }, +}; + +std::istream& operator>>(std::istream& in, StrategyCondition::ConditionSide& value) +{ + value = static_cast(readAIEnumSpelling(in, kConditionSideSpellings, sizeof(kConditionSideSpellings) / sizeof(kConditionSideSpellings[0]), 3)); + return in; +} + +// ELF 0x3C68A0. +static const AIEnumSpelling kCompareSpellings[] = { + { "Equal", 0 }, + { "=", 0 }, + { "EqualGreater", 1 }, + { ">=", 1 }, + { "EqualSmaller", 2 }, + { "<=", 2 }, + { "Quotient", 3 }, + { "/", 3 }, + { "QuotientGreater", 4 }, + { ">/", 4 }, + { "QuotientSmaller", 5 }, + { "-", 7 }, + { "DifferenceSmaller", 8 }, + { "<-", 8 }, +}; + +std::istream& operator>>(std::istream& in, StrategyCondition::Compare& value) +{ + value = static_cast(readAIEnumSpelling(in, kCompareSpellings, sizeof(kCompareSpellings) / sizeof(kCompareSpellings[0]), 9)); + return in; +} + +// ELF 0x3C6D30. +static const AIEnumSpelling kConditionalSpellings[] = { + { "Ticket", 13 }, + { "ControlPoint", 14 }, + { "Time", 15 }, + { "StartTime", 16 }, + { "Attacks", 17 }, + { "Defences", 18 }, + { "Carrier", 0 }, + { "HeavyNaval", 1 }, + { "Naval", 3 }, + { "Bomber", 4 }, + { "Fighter", 5 }, + { "AntiAir", 6 }, + { "Air", 7 }, + { "LCVP", 2 }, + { "Infantry", 8 }, + { "Infantery", 8 }, + { "Artillery", 9 }, + { "AntiTank", 10 }, + { "HeavyAttack", 11 }, + { "FastAttack", 12 }, + { "NumberOfFriendlyAreas", 19 }, + { "NumberOfNeutralAreas", 20 }, + { "NumberOfHostileAreas", 21 }, + { "Flank", 22 }, + { "Base", 23 }, + { "Close", 24 }, + { "Centre", 25 }, + { "Remote", 26 }, + { "North", 29 }, + { "East", 32 }, + { "South", 31 }, + { "West", 30 }, + { "Route", 27 }, + { "Bridge", 28 }, + { "FrontFlank", 33 }, + { "FrontBase", 34 }, + { "FrontClose", 35 }, + { "FrontCentre", 36 }, + { "FrontRemote", 37 }, + { "FrontNeutral", 38 }, + { "Front", 39 }, + { "Safe", 40 }, + { "EnemyObject", 41 }, + { "UnReachable", 42 }, + { "UnitConstant", 43 }, +}; + +std::istream& operator>>(std::istream& in, StrategyCondition::Conditional& value) +{ + value = static_cast(readAIEnumSpelling(in, kConditionalSpellings, sizeof(kConditionalSpellings) / sizeof(kConditionalSpellings[0]), 44)); + return in; +} + +// ELF 0x3C6330: a 27-entry jump table (cmpl $0x1a); 0, 21, 25 and values above 26 print nothing. +std::ostream& operator<<(std::ostream& out, AIStrategicObject::StrategicObjectType type) +{ + switch (type) + { + case AIStrategicObject::Flank: out << "Flank"; break; + case AIStrategicObject::Centre: out << "Centre"; break; + case AIStrategicObject::Base: out << "Base"; break; + case AIStrategicObject::Close: out << "Close"; break; + case AIStrategicObject::Remote: out << "Remote"; break; + case AIStrategicObject::AirSpawner: out << "AirSpawner"; break; + case AIStrategicObject::LandSpawner: out << "LandSpawner"; break; + case AIStrategicObject::NavalSpawner: out << "NavalSpawner"; break; + case AIStrategicObject::SoldierSpawner: out << "SoldierSpawner"; break; + case AIStrategicObject::StrongPoint: out << "StrongPoint"; break; + case AIStrategicObject::ChokePoint: out << "ChokePoint"; break; + case AIStrategicObject::Bridge: out << "Bridge"; break; + case AIStrategicObject::AirField: out << "AirField"; break; + case AIStrategicObject::SupplyPoint: out << "SupplyPoint"; break; + case AIStrategicObject::Route: out << "Route"; break; + case AIStrategicObject::ControlPoint: out << "ControlPoint"; break; + case AIStrategicObject::North: out << "North"; break; + case AIStrategicObject::West: out << "West"; break; + case AIStrategicObject::South: out << "South"; break; + case AIStrategicObject::East: out << "East"; break; + case AIStrategicObject::Front: out << "Front"; break; + case AIStrategicObject::Safe: out << "Safe"; break; + case AIStrategicObject::Enemy: out << "Enemy"; break; + case AIStrategicObject::NeutralType: out << "Neutral"; break; + default: break; + } + return out; +} + +// ELF 0x3C6460. +static const AIEnumSpelling kStrategicObjectTypeSpellings[] = { + { "Flank", 1 }, + { "Centre", 2 }, + { "Base", 3 }, + { "Close", 4 }, + { "Remote", 5 }, + { "AirSpawner", 6 }, + { "LandSpawner", 7 }, + { "NavalSpawner", 8 }, + { "SoldierSpawner", 9 }, + { "StrongPoint", 10 }, + { "ChokePoint", 11 }, + { "Bridge", 12 }, + { "AirField", 13 }, + { "SupplyPoint", 14 }, + { "Route", 15 }, + { "ControlPoint", 16 }, + { "Front", 22 }, + { "Safe", 23 }, + { "Enemy", 24 }, + { "Neutral", 26 }, + { "North", 17 }, + { "West", 18 }, + { "South", 19 }, + { "East", 20 }, +}; + +std::istream& operator>>(std::istream& in, AIStrategicObject::StrategicObjectType& value) +{ + value = static_cast(readAIEnumSpelling(in, kStrategicObjectTypeSpellings, sizeof(kStrategicObjectTypeSpellings) / sizeof(kStrategicObjectTypeSpellings[0]), 27)); + return in; +} + +// ELF 0x3C8CC0. +static const AIEnumSpelling kStatusSpellings[] = { + { "Owned", 0 }, + { "Hostile", 1 }, + { "Neutral", 2 }, + { "Unknown", 3 }, +}; + +std::istream& operator>>(std::istream& in, StatusMap::Status& value) +{ + const int read = readAIEnumSpelling(in, kStatusSpellings, sizeof(kStatusSpellings) / sizeof(kStatusSpellings[0]), -1); + if (read != -1) + value = static_cast(read); + return in; +} + +// ELF 0x3C78B0: the four spellings; any other value prints nothing. +std::ostream& operator<<(std::ostream& out, BotLodLevel lod) +{ + switch (lod) + { + case 0: out << "BLLFull"; break; + case 1: out << "BLLMedium"; break; + case 2: out << "BLLLight"; break; + case 3: out << "BLLNone"; break; + default: break; + } + return out; +} + +// ELF 0x3C7930: "BLLFull"/"Full"/"0" 0, "BLLMedium"/"Medium"/"1" 1, "BLLLight"/"Light"/"2" 2, +// anything else 3 (BLLNone). The image still compares "BLLNone" and then "None", but both +// outcomes store 3 (the last compare's result is not tested). +std::istream& operator>>(std::istream& in, BotLodLevel& lod) +{ + std::string token; + in >> token; + if (token.compare("BLLFull") == 0 || token.compare("Full") == 0 || token.compare("0") == 0) + lod = static_cast(0); + else if (token.compare("BLLMedium") == 0 || token.compare("Medium") == 0 || token.compare("1") == 0) + lod = static_cast(1); + else if (token.compare("BLLLight") == 0 || token.compare("Light") == 0 || token.compare("2") == 0) + lod = static_cast(2); + else + lod = static_cast(3); // BotMain.h's enum has no name for 3 (BLLNone) + return in; +} + +// ELF 0x3C7AE0: a 59-entry jump table (cmpl $0x3a); 48 and values above 58 print nothing. +std::ostream& operator<<(std::ostream& out, BAPConditionType type) +{ + static const char* const kNames[59] = { + "LookDeviation", "Precision", "Precision3d", "BombPrecision3d", "&&", "EndOfPath", "false", + "Generic1Arg", "Generic2Arg", "InsideBattleZone", "Iteration", "LineOfFire", + "PointDistance", "PointInFront", "!", "DistanceToProj", "StrategicObjectStatus", + "ObjectBehind", "ObjectDistance", "ObjectDistanceToPoint", "ObjectEnemyOccupied", + "ObjectExists", "ObjectHealth", "ObjectInFront", "ObjectInLandingZone", + "ObjectInsideFrustum", "ObjectLineOfFire", "ObjectManDown", "ObjectMoved", + "ObjectOccupied", "ObjectSpeed", "ObjectTouchingGround", "ObjectValidAiming", + "ObjectValidPosition", "ObjectVisible", "||", "PointAt", "Position", "SharedCondition", + "Time", "true", "WeaponMagAmmo", "WeaponTotalAmmo", "TotalWeaponAmmo", + "WeaponReadyToFire", "WeaponTargetReachable", "WeaponHeat", "WeaponHasLockOnTarget", + 0, "IsTriggered", "Allow fire", "Sprinting", "Zoomed", "Detonator active", + "Weapon active", "<", "Ok to throw grenade", "Splash damage", "Triggerable Active" + }; + const unsigned int index = static_cast(type); // `ja` default: unsigned bound + if (index < 59 && kNames[index]) + out << kNames[index]; + return out; +} + +// ELF 0x3C7D90: a 45-entry jump table (cmpl $0x2c); 30 and values above 44 print nothing. +// The names are the BAPST* spellings without the prefix, except "if" and "while" (lower case). +std::ostream& operator<<(std::ostream& out, BAPStatementType type) +{ + static const char* const kNames[45] = { + "Parallel", "Serial", "PlanEnd", "if", "Wait", "while", "AimAt", "MoveTo", + "MoveToDirection", "MoveToObject", "MoveAwayFromObject", "Trigger", "TriggerContinously", + "Idle", "ResetControls", "InfoWrapper", "AimingWrapper", "FinishedWrapper", + "WeaponWrapper", "LookAtWrapper", "Sense", "OverrideSensingAgent", "PlaceC4", "LookAt", + "Turn", "Roll3d", "SoldierPose", "UpdateVehicle", "ChangeWeapon", "ICChangeVehicle", 0, + "ICTurnLock", "Evaluate", "NotifyBot", "PhysicsEnable", "SetSensingAgentFocus", + "MergeSoldierInputs", "SendRadioMessage", "Debug", "ForgetTarget", + "UseFlareOnMissileLock", "RunOverObject", "HonkHorn", "EvaluateCondition", "Revive" + }; + const unsigned int index = static_cast(type); + if (index < 45 && kNames[index]) + out << kNames[index]; + return out; +} + +// ELF 0x3C7FA0: the BAPST* spelling or the bare name, in the image's compare order (note "AImAt", +// "TurnLock" and "ChangeVehicle" for the IC statements); no match gives 45. +static const AIEnumSpelling kStatementTypeSpellings[] = { + { "BAPSTParallel", 0 }, { "Parallel", 0 }, + { "BAPSTSerial", 1 }, { "Serial", 1 }, + { "BAPSTPlanEnd", 2 }, { "PlanEnd", 2 }, + { "BAPSTIf", 3 }, { "If", 3 }, + { "BAPSTWait", 4 }, { "Wait", 4 }, + { "BAPSTWhile", 5 }, { "While", 5 }, + { "BAPSTAimAt", 6 }, { "AImAt", 6 }, + { "BAPSTMoveTo", 7 }, { "MoveTo", 7 }, + { "BAPSTTurn", 24 }, { "Turn", 24 }, + { "BAPSTMoveToDirection", 8 }, { "MoveToDirection", 8 }, + { "BAPSTMoveToObject", 9 }, { "MoveToObject", 9 }, + { "BAPSTMoveAwayFromObject", 10 }, { "MoveAwayFromObject", 10 }, + { "BAPSTTrigger", 11 }, { "Trigger", 11 }, + { "BAPSTTriggerContinously", 12 }, { "TriggerContinously", 12 }, + { "BAPSTIdle", 13 }, { "Idle", 13 }, + { "BAPSTResetControls", 14 }, { "ResetControls", 14 }, + { "BAPSTInfoWrapper", 15 }, { "InfoWrapper", 15 }, + { "BAPSTSense", 20 }, { "Sense", 20 }, + { "BAPSTLookAt", 23 }, { "LookAt", 23 }, + { "BAPSTOverrideSensingAgent", 21 }, { "OverrideSensingAgent", 21 }, + { "BAPSTPlaceC4", 22 }, { "PlaceC4", 22 }, + { "BAPSTRoll3d", 25 }, { "Roll3d", 25 }, + { "BAPSTSoldierPose", 26 }, { "SoldierPose", 26 }, + { "BAPSTUpdateVehicle", 27 }, { "UpdateVehicle", 27 }, + { "BAPSTChangeWeapon", 28 }, { "ChangeWeapon", 28 }, + { "BAPSTICTurnLock", 31 }, { "TurnLock", 31 }, + { "BAPSTICChangeVehicle", 29 }, { "ChangeVehicle", 29 }, + { "BAPSTEvaluate", 32 }, { "Evaluate", 32 }, + { "BAPSTNotifyBot", 33 }, { "NotifyBot", 33 }, + { "BAPSTAimingWrapper", 16 }, { "AimingWrapper", 16 }, + { "BAPSTWeaponWrapper", 18 }, { "WeaponWrapper", 18 }, + { "BAPSTLookAtWrapper", 19 }, { "LookAtWrapper", 19 }, + { "BAPSTFinishedWrapper", 17 }, { "FinishedWrapper", 17 }, + { "BAPSTPhysicsEnable", 34 }, { "PhysicsEnable", 34 }, + { "BAPSTSetSensingAgentFocus", 35 }, { "SetSensingAgentFocus", 35 }, + { "BAPSTMergeSoldierInputs", 36 }, { "MergeSoldierInputs", 36 }, + { "BAPSTSendRadioMessage", 37 }, { "SendRadioMessage", 37 }, + { "BAPSTDebug", 38 }, { "Debug", 38 }, + { "BAPSTForgetTarget", 39 }, { "ForgetTarget", 39 }, + { "BAPSTUseFlareOnMissileLock", 40 }, { "UseFlareOnMissileLock", 40 }, + { "BAPSTRunOverObject", 41 }, { "RunOverObject", 41 }, + { "BAPSTHonkHorn", 42 }, { "HonkHorn", 42 }, + { "BAPSTEvaluateCondition", 43 }, { "EvaluateCondition", 43 }, + { "BAPSTRevive", 44 }, { "Revive", 44 }, +}; + +std::istream& operator>>(std::istream& in, BAPStatementType& type) +{ + type = static_cast(readAIEnumSpelling(in, kStatementTypeSpellings, sizeof(kStatementTypeSpellings) / sizeof(kStatementTypeSpellings[0]), 45)); + return in; +} + +// ELF 0x3C4150 +std::istream& operator>>(std::istream& in, std::vector& values) +{ + values.erase(values.begin(), values.end()); + unsigned value; + for (;;) + { + in >> value; + values.push_back(value); + if (in.peek() == std::char_traits::eof() || in.peek() == ' ') + break; + char separator; + in >> separator; + } + return in; +} + +// ELF 0x3C4220 +std::ostream& operator>>(std::ostream& out, const std::vector& values) +{ + for (std::vector::const_iterator it = values.begin(); it != values.end(); ++it) + { + out << static_cast(*it); + // shipped defect: tests the current iterator, so even the final element gets a slash. + if (it != values.end()) + out << "/"; + } + return out; +} + +// ELF 0x3C42A0 +std::ostream& operator<<(std::ostream& out, const std::list& values) +{ + std::list::const_iterator it = values.begin(); + // shipped defect: the iterator is never incremented. + while (it != values.end()) + { + out << it->x << '/'; + out << it->y; + if (it != values.end()) + out << ","; + } + return out; +} + +// ELF 0x3C4350 +std::istream& operator>>(std::istream& in, std::list& values) +{ + values.clear(); + float value; + for (;;) + { + Vec2 point = { 0.0f, 0.0f }; + char separator; + in >> value >> separator; + point.x = value; + in >> value; + point.y = value; + values.insert(values.end(), point); + if (in.peek() == std::char_traits::eof() || in.peek() == ' ') + break; + in >> separator; + } + return in; +} + +static const char* const kInformationNames[] = { + "ITProduction", + "ITAmmunition", + "ITRepair", + "ITUnit", + "ITAir", + "ITHelicopter", + "ITGround", + "ITNaval", + "ITControlpoint", + "ITRadar", + "ITAirfield", + "ITTransportation", + "ITArtillery", + "ITFixed", + "ITCover", + "ITMobile", + "ITUnmanned", + "ITLowPriority", + "ITStructure", + "ITBiological", + "ITVegetation", + "ITSoldier", + "ITObstructedView", + "ITNoTemperature", + "ITHasWreck", + "ITObstacle", + "ITHasCarHorn", +}; +// ELF 0x3C4440 +std::ostream& operator<<(std::ostream& out, InformationType value) +{ + const unsigned index = static_cast(value); + if (index < 27) + out << kInformationNames[index]; + return out; +} + +// ELF 0x3C4590 +std::istream& operator>>(std::istream& in, InformationType& value) +{ + static const AIEnumSpelling spellings[] = { + { "ITProduction", 0 }, + { "ITAmmunition", 1 }, + { "ITRepair", 2 }, + { "ITUnit", 3 }, + { "ITAir", 4 }, + { "ITGround", 6 }, + { "ITNaval", 7 }, + { "ITControlpoint", 8 }, + { "ITRadar", 9 }, + { "ITAirfield", 10 }, + { "ITTransportation", 11 }, + { "ITArtillery", 12 }, + { "ITFixed", 13 }, + { "ITCover", 14 }, + { "ITMobile", 15 }, + { "ITHasWreck", 24 }, + { "ITObstacle", 25 }, + { "ITHasCarHorn", 26 }, + { "ITUnmanned", 16 }, + { "ITLowPriority", 17 }, + { "ITStructure", 18 }, + { "ITBiological", 19 }, + { "ITVegetation", 20 }, + { "ITSoldier", 21 }, + { "ITObstructedView", 22 }, + { "ITNoTemperature", 23 }, + { "ITHelicopter", 5 }, + }; + value = static_cast(readAIEnumSpelling(in, spellings, 27, -1)); + return in; +} + +static const char* const kPlayerInputNames[] = { + "PIYaw", + "PIPitch", + "PIRoll", + "PIThrottle", + "PIMouseLookX", + "PIMouseLookY", + "PICameraX", + "PICameraY", + "PIFire", + "PIAction", + "PIUse", + "PIMouseLook", + "PIAltSprint", + "PISprint", + "PIWeaponSelect1", + "PIWeaponSelect2", + "PIWeaponSelect3", + "PIWeaponSelect4", + "PIWeaponSelect5", + "PIWeaponSelect6", + "PIWeaponSelect7", + "PIWeaponSelect8", + "PIWeaponSelect9", + "PIPositionSelect1", + "PIPositionSelect2", + "PIPositionSelect3", + "PIPositionSelect4", + "PIPositionSelect5", + "PIPositionSelect6", + "PIPositionSelect7", + "PIPositionSelect8", + "PIAltFire", + "PIReload", + nullptr, + "PIDrop", + "PIToggleCameraMode", + "PIToggleCamera", + "PILie", + "PICrouch", + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + "PIFlareFire", + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + "PISayAll", + "PISayTeam", + "PINextItem", + "PIPrevItem", + "PICommunication", + nullptr, + "PINone", +}; +// These are the AI namespace overloads, distinct from IO/Input's io namespace operators. +// ELF 0x3C4990 +std::ostream& operator<<(std::ostream& out, io::PlayerInputMap value) +{ + const unsigned index = static_cast(value); + if (index < 65 && kPlayerInputNames[index]) + out << kPlayerInputNames[index]; + return out; +} + +// ELF 0x3C4BB0 +std::istream& operator>>(std::istream& in, io::PlayerInputMap& value) +{ + static const AIEnumSpelling spellings[] = { + { "PIYaw", 0 }, + { "PIPitch", 1 }, + { "PIRoll", 2 }, + { "PIThrottle", 3 }, + { "PIMouseLookX", 4 }, + { "PIMouseLookY", 5 }, + { "PICameraX", 6 }, + { "PICameraY", 7 }, + { "PIFire", 8 }, + { "PIAction", 9 }, + { "PIUse", 10 }, + { "PIMouseLook", 11 }, + { "PIAltSprint", 12 }, + { "PISprint", 13 }, + { "PISayAll", 58 }, + { "PISayTeam", 59 }, + { "PINextItem", 60 }, + { "PIPrevItem", 61 }, + { "PICommunication", 62 }, + { "PIWeaponSelect1", 14 }, + { "PIWeaponSelect2", 15 }, + { "PIWeaponSelect3", 16 }, + { "PIWeaponSelect4", 17 }, + { "PIWeaponSelect5", 18 }, + { "PIWeaponSelect6", 19 }, + { "PIWeaponSelect7", 20 }, + { "PIWeaponSelect8", 21 }, + { "PIWeaponSelect9", 22 }, + { "PIPositionSelect1", 23 }, + { "PIPositionSelect2", 24 }, + { "PIPositionSelect3", 25 }, + { "PIPositionSelect4", 26 }, + { "PIPositionSelect5", 27 }, + { "PIPositionSelect6", 28 }, + { "PIPositionSelect7", 29 }, + { "PIPositionSelect8", 30 }, + { "PIAltFire", 31 }, + { "PIReload", 32 }, + { "PIDrop", 34 }, + { "PIFlareFire", 47 }, + { "PIToggleCameraMode", 35 }, + { "PIToggleCamera", 36 }, + { "PILie", 37 }, + { "PICrouch", 38 }, + { "PINone", 64 }, + }; + value = static_cast(readAIEnumSpelling(in, spellings, + sizeof(spellings) / sizeof(spellings[0]), -1)); + return in; +} + +// ELF 0x3C5210 +std::ostream& operator<<(std::ostream& out, TemperatureTreeNode value) +{ + const unsigned index = static_cast(value); + if (index < 41) + out << kTemperatureTreeNodeSpellings[index].name; + return out; +} + +static const char* const kCombatStrengthNames[] = { + "CSTInfantry", + "CSTLightArmour", + "CSTHeavyArmour", + "CSTNavalArmour", + "CSTHelicopter", + "CSTAirPlane", + "CSTNumberOfTypes", +}; +// ELF 0x3C59D0 +std::ostream& operator<<(std::ostream& out, CombatStrengthType value) +{ + const unsigned index = static_cast(value); + if (index < 7) + out << kCombatStrengthNames[index]; + return out; +} + +static const char* const kConditionTypeNames[] = { + "Constant", + "Homogeneous", + "Heterogeneous", +}; +// ELF 0x3C5D20 +std::ostream& operator<<(std::ostream& out, StrategyCondition::ConditionType value) +{ + const unsigned index = static_cast(value); + if (index < 3) + out << kConditionTypeNames[index]; + return out; +} + +// ELF 0x3C5D90 +std::istream& operator>>(std::istream& in, StrategyCondition::ConditionType& value) +{ + static const AIEnumSpelling spellings[] = { + { "Constant", 0 }, { "Homogeneous", 1 }, { "Heterogeneous", 2 } + }; + value = static_cast(readAIEnumSpelling(in, spellings, 3, 4)); + return in; +} + +// ELF 0x3C5E80 +std::ostream& operator<<(std::ostream& out, StrategyCondition::ConditionStrength value) +{ + const unsigned index = static_cast(value); + if (index < 6) + out << kConditionStrengthSpellings[index].name; + return out; +} + +// ELF 0x3C6070 +std::ostream& operator<<(std::ostream& out, StrategyCondition::CompareType value) +{ + const unsigned index = static_cast(value); + if (index < 3) + out << kCompareTypeSpellings[index].name; + return out; +} + +// ELF 0x3C61D0 +std::ostream& operator<<(std::ostream& out, StrategyCondition::ConditionSide value) +{ + const unsigned index = static_cast(value); + if (index < 3) + out << kConditionSideSpellings[index].name; + return out; +} + +// ELF 0x3C6800 +std::ostream& operator<<(std::ostream& out, StrategyCondition::Compare value) +{ + const unsigned index = static_cast(value); + if (index < 9) + out << kCompareSpellings[index * 2].name; + return out; +} + +static const char* const kConditionalNames[] = { + "Carrier", + "BattleShip", + "LCVP", + "Naval", + "Bomber", + "Fighter", + "AntiAir", + "Air", + "Infantery", + "Artillery", + "AntiTank", + "HeavyAttack", + "FastAttack", + "Ticket", + "ControlPoint", + "Time", + "StartTime", + "Attacks", + "Defences", + "NumberOfFriendlyAreas", + "NumberOfNeutralAreas", + "NumberOfHostileAreas", + "Flank", + "Base", + "Close", + "Centre", + "Remote", + "Route", + "Bridge", + "North", + "West", + "South", + "East", + "FrontFlank", + "FrontBase", + "FrontClose", + "FrontCentre", + "FrontRemote", + "FrontNeutral", + "Front", + "Safe", + "EnemyObject", + "UnReachable", + "UnitConstant", +}; +// ELF 0x3C6B20 +std::ostream& operator<<(std::ostream& out, StrategyCondition::Conditional value) +{ + const unsigned index = static_cast(value); + if (index < 44) + out << kConditionalNames[index]; + return out; +} + +// Kit types: AIDLL_r.dll's operator<< (0x100D4D70, jump table 0x100D4F40) confirms every value: +// 0 KTSpecops, 1 KTSniper, 2 KTAssault, 3 KTSupport, 4 KTEngineer, 5 KTMedic, 6 KTAT (anti-tank), +// 7..12 KTExtended1..6. hfe::KitType itself is declared opaque (Game/Objects/Game/KitTemplate.h). +static const char* const kKitNames[] = { + "KTSpecops", + "KTSniper", + "KTAssault", + "KTSupport", + "KTEngineer", + "KTMedic", + "KTAT", + "KTExtended1", + "KTExtended2", + "KTExtended3", + "KTExtended4", + "KTExtended5", + "KTExtended6", +}; +// ELF 0x3C7370 +std::ostream& operator<<(std::ostream& out, KitType value) +{ + const unsigned index = static_cast(value); + if (index < 13) + out << kKitNames[index]; + return out; +} + +// ELF 0x3C7430 +std::istream& operator>>(std::istream& in, KitType& value) +{ + static const AIEnumSpelling spellings[] = { + { "KTSpecops", 0 }, { "Specops", 0 }, { "0", 0 }, + { "KTSniper", 1 }, { "Sniper", 1 }, { "1", 1 }, + { "KTAssault", 2 }, { "Assault", 2 }, { "2", 2 }, + { "KTSupport", 3 }, { "Support", 3 }, { "3", 3 }, + { "KTEngineer", 4 }, { "Engineer", 4 }, { "4", 4 }, + { "KTMedic", 5 }, { "Medic", 5 }, { "5", 5 }, + { "KTAT", 6 }, { "AT", 6 }, { "6", 6 }, + { "KTExtended1", 7 }, { "Extended1", 7 }, { "7", 7 }, + { "KTExtended2", 8 }, { "Extended2", 8 }, { "8", 8 }, + { "KTExtended3", 9 }, { "Extended3", 9 }, { "9", 9 }, + { "KTExtended4", 10 }, { "Extended4", 10 }, { "10", 10 }, + { "KTExtended5", 11 }, { "Extended5", 11 }, { "11", 11 }, + { "KTExtended6", 12 }, { "Extended6", 12 }, { "12", 12 }, + }; + value = static_cast(readAIEnumSpelling(in, spellings, 39, 13)); + return in; +} + +static const char* const kLandingZoneNames[] = { + "LZXMin", + "LZZMin", + "LZXMax", + "LZZMax", + "LZUndefined", +}; +// ELF 0x3C89A0 +std::ostream& operator<<(std::ostream& out, LandingZoneDirection value) +{ + const unsigned index = static_cast(value); + if (index < 5) + out << kLandingZoneNames[index]; + return out; +} + +static const char* const kStatusNames[] = { + "Owned", + "Hostile", + "Neutral", +}; +// ELF 0x3C8C50 +std::ostream& operator<<(std::ostream& out, StatusMap::Status value) +{ + const unsigned index = static_cast(value); + if (index < 3) + out << kStatusNames[index]; + else + out << "Unknown"; + return out; +} + +static const char* const kMeshNames[] = { + "Bullet", + "Vehicle", + "Soldier", +}; +// ELF 0x3C8DC0 +std::ostream& operator<<(std::ostream& out, mesh::MeshType value) +{ + const unsigned index = static_cast(value); + if (index < 3) + out << kMeshNames[index]; + else + out << "Error"; + return out; +} + +// ELF 0x3C8E30 +std::istream& operator>>(std::istream& in, mesh::MeshType& value) +{ + std::string token; + in >> token; + if (equalsIgnoreCase(token, std::string("Bullet"))) + value = static_cast(0); + else if (equalsIgnoreCase(token, std::string("Vehicle"))) + value = static_cast(1); + else if (equalsIgnoreCase(token, std::string("Soldier"))) + value = static_cast(2); + else + { + equalsIgnoreCase(token, std::string("Error")); + value = static_cast(4); + } + return in; +} + +static const char* const kMTStatusNames[] = { + "Forward", + "Behind", + "Right Forwards", + "Left Forwards", + "Avoid obstacle forwards left", + "Avoid obstacle forwards right", + "Avoid Obstacle Forward", + "Ignore obstacle", + "Back up", + "Right Backwards", + "Avoid Obstacle Backwards", + "Left Backwards", + "Back up until room", + "Avoid obstacle backwards right", + "Avoid obstacle backwards left", +}; +// ELF 0x3C90A0 +std::ostream& operator<<(std::ostream& out, MTStatus value) +{ + const unsigned index = static_cast(value); + if (index < 15) + out << kMTStatusNames[index]; + else + out << "Error"; + return out; +} + + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIStreamOperators.h b/Code/BF2/AI/AIDLL/AI/Main/AIStreamOperators.h new file mode 100644 index 000000000..4e391d0f9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/Main/AIStreamOperators.h @@ -0,0 +1,79 @@ +// Stream operators for the AI script vocabulary (AI/Main/AIStreamOperators.cpp, attested FILE +// symbol; header path [INFERRED]). The console uses the extractors to parse enum arguments; the +// plan dumps (streamSelf) and BAPInterpreter's diagnostics use the inserters. + +#ifndef AI_AIDLL_AI_MAIN_AISTREAMOPERATORS_H +#define AI_AIDLL_AI_MAIN_AISTREAMOPERATORS_H + +#include +#include +#include +#include +#include "../../../../Math/Vec3.h" +#include "../../../AIInterface/BFKnowledge/InformationType.h" + +#include "../AIBotActionPlan/BAPTypes.h" +#include "../AIStrategic/StatusMap.h" +#include "../AIStrategic/StrategyCondition.h" +#include "../AIStrategicEntity/AIStrategicObject.h" + +namespace dice { +namespace hfe { +enum KitType : int; +namespace ai { +namespace mesh { enum MeshType : int; } + +enum TemperatureTreeNode : int; +enum CombatStrengthType : int; +enum LandingZoneDirection : int; +enum MTStatus : int; + +std::istream& operator>>(std::istream& in, std::vector& values); +// The output overload is spelled >> in the shipped symbol and always writes a trailing slash. +std::ostream& operator>>(std::ostream& out, const std::vector& values); +// A nonempty list never advances its iterator in the shipped inserter. +std::ostream& operator<<(std::ostream& out, const std::list& values); +std::istream& operator>>(std::istream& in, std::list& values); +std::ostream& operator<<(std::ostream& out, TemperatureTreeNode value); +std::ostream& operator<<(std::ostream& out, CombatStrengthType value); +std::ostream& operator<<(std::ostream& out, LandingZoneDirection value); +std::ostream& operator<<(std::ostream& out, StrategyCondition::ConditionType value); +std::istream& operator>>(std::istream& in, StrategyCondition::ConditionType& value); +std::ostream& operator<<(std::ostream& out, StrategyCondition::ConditionStrength value); +std::ostream& operator<<(std::ostream& out, StrategyCondition::CompareType value); +std::ostream& operator<<(std::ostream& out, StrategyCondition::ConditionSide value); +std::ostream& operator<<(std::ostream& out, StrategyCondition::Compare value); +std::ostream& operator<<(std::ostream& out, StrategyCondition::Conditional value); +std::ostream& operator<<(std::ostream& out, KitType value); +std::istream& operator>>(std::istream& in, KitType& value); +std::ostream& operator<<(std::ostream& out, StatusMap::Status value); +std::ostream& operator<<(std::ostream& out, mesh::MeshType value); +std::istream& operator>>(std::istream& in, mesh::MeshType& value); +std::ostream& operator<<(std::ostream& out, MTStatus value); + +// Each extractor reads one token and maps its spelling. Unknown tokens normally yield the value +// one past the last name; TemperatureTreeNode yields -1, Status retains its previous value, +// BotLodLevel yields 3, CombatStrengthType yields 6, and LandingZoneDirection yields 4. +std::istream& operator>>(std::istream& in, TemperatureTreeNode& value); +std::istream& operator>>(std::istream& in, CombatStrengthType& value); +std::istream& operator>>(std::istream& in, LandingZoneDirection& value); +std::istream& operator>>(std::istream& in, StrategyCondition::ConditionStrength& value); // 0x3C5F00 +std::istream& operator>>(std::istream& in, StrategyCondition::CompareType& value); // 0x3C60E0 +std::istream& operator>>(std::istream& in, StrategyCondition::ConditionSide& value); // 0x3C6240 +std::istream& operator>>(std::istream& in, StrategyCondition::Compare& value); // 0x3C68A0 +std::istream& operator>>(std::istream& in, StrategyCondition::Conditional& value); // 0x3C6D30 +std::ostream& operator<<(std::ostream& out, AIStrategicObject::StrategicObjectType type); // 0x3C6330 +std::istream& operator>>(std::istream& in, AIStrategicObject::StrategicObjectType& value); // 0x3C6460 +std::istream& operator>>(std::istream& in, StatusMap::Status& value); // 0x3C8CC0 + +std::ostream& operator<<(std::ostream& out, BotLodLevel lod); // 0x3C78B0 +std::istream& operator>>(std::istream& in, BotLodLevel& lod); // 0x3C7930 +std::ostream& operator<<(std::ostream& out, BAPConditionType type); // 0x3C7AE0 +std::ostream& operator<<(std::ostream& out, BAPStatementType type); // 0x3C7D90 +std::istream& operator>>(std::istream& in, BAPStatementType& type); // 0x3C7FA0 + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_MAIN_AISTREAMOPERATORS_H diff --git a/Code/BF2/AI/AIDLL/AI/Main/BF2AI.cpp b/Code/BF2/AI/AIDLL/AI/Main/BF2AI.cpp index 7bbd8b5bb..125d5e75b 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/BF2AI.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/BF2AI.cpp @@ -3,10 +3,11 @@ // These statics belong to the AI module; do not share their definitions with the engine image. // [INFERRED] Source placement. +// static init: ELF 0x3EE360 (__tcf_0 0x3EE3C0, _GLOBAL__I 0x3EE3F0): 's Init object only. +#include + #include "BF2AI.h" -#include // the [FRONTIER] stop in init - stderr, not BF2Log; see that body -#include // std::abort - same #include #include "../../../../Core/ClassManager.h" @@ -14,28 +15,31 @@ #include "../AIKnowledge/BFInformationCourier.h" // step 4 #include "../AIKnowledge/BFInformationEnvironment.h" #include "../AIKnowledge/InformationFactory.h" // step 8 -#include "../AIKnowledge/InformationManager.h" // step 1, and clear's table teardown -#include "../AIKnowledge/WeaponInfoManager.h" // step 2 +#include "InformationManager.h" // step 1, and clear's table teardown +#include "../AIUtils/WeaponInfoManager.h" // step 2 #include "../AIStrategicMap/BFStrategicEnvironment.h" // step 6 #include "../DrawPrimitives/DPManager.h" // step 7 #include "../AIUtils/checkPointer.h" #include "AICollisionHandler.h" // step 10 #include "AIEventCourier.h" // step 11 #include "AIMain.h" -#include "AIMineManager.h" // step 13 +#include "../AIKnowledge/AIMineManager.h" // step 13 #include "AIPlayerCourier.h" // step 12 #include "AIConsole.h" // step 15 +#include "../AIUtils/DebugRendering/AIRenderUtil.h" // clear: the debug renderer +#include "AILandingZoneManager.h" // clear: the landing-zone manager #include "BotBehaviourManager.h" // step 16 #include "../AIStrategicEntity/AIStrategicObjectManager.h" // step 17 #include "../AIStrategicEntity/CoverPosition/CoverPositionManager.h" // step 18 +#include "BotPlacementManager.h" // clear only - the static initializer builds it #include "AILODManager.h" // clear only - `init` never builds one #include "AIPathfinding.h" // step 21, and clear #include "AIRandom.h" // step 22, and clear #include "AISettings.h" // step 9 #include "BFPathfindingCourier.h" // step 5 -#include "UserOrderManager.h" // step 14 +#include "../AIStrategicEntity/UserOrders/UserOrderManager.h" // step 14 #include "StrategyManager.h" // step 19, and clear -#include "../AIStrategicMap/AerialHeightMap.h" // step 20, and clear +#include "../AIPathFinding/AerialHeightMap/AerialHeightMap.h" // step 20, and clear #include "CommunicationHub.h" // step 23, and clear #include "AISettingsInterfaces.h" // IAISettings / IAISettingsModifier #include "../../../AIInterface/BFKnowledge/BFGame.h" // IAIGame::getAISettingsFromGame @@ -50,6 +54,7 @@ namespace ai { // Registers the first AI in the simple-singleton registry. Later instances remain // unregistered; this intentionally differs from AIModule::close's normal-registry lookup. +// ELF 0x3EE430 / 0x3EE540 IAI::IAI() { if (!classManager->getSimpleSingleton("AI")) @@ -58,6 +63,7 @@ IAI::IAI() // The exact mirror of the constructor: unregister only if the registered "AI" is still this object. // A second IAI that never registered will not tear down the first one's entry on its way out. +// ELF 0x3EE650 / 0x3EE740 / 0x3EE830 IAI::~IAI() { if (classManager->getSimpleSingleton("AI") == this) @@ -65,6 +71,7 @@ IAI::~IAI() } // Two bytes. Everything that matters happened in the base constructor above. +// ELF 0x3EC720 / 0x3EC770 BF2AI::BF2AI() : m_initialized(false) , m_shuttingDown(false) @@ -75,11 +82,13 @@ BF2AI::BF2AI() // call are the whole body. It does not call clear; tearing the AI down is shutdown's job and // nothing chains the two. Destroying a BF2AI without shutting it down first leaks every one of the // twenty-four subsystems init built. +// ELF 0x3EC7C0 / 0x3EC800 / 0x3EC840 BF2AI::~BF2AI() { } // Constructs the AI subsystems and refreshes their registered interfaces. +// ELF 0x3EC890 bool BF2AI::init() { // Raises the shutdown flag before checking initialization. A repeated init returns @@ -241,6 +250,7 @@ bool BF2AI::init() } // Tears down AI subsystems in dependency order, refreshing cached interfaces during destruction. +// ELF 0x3EDDF0 bool BF2AI::clear() { if (!m_initialized) @@ -258,8 +268,11 @@ bool BF2AI::clear() if (updater) delete updater; - // [FRONTIER: AIRenderUtil] delete AIRenderUtil::m_instance; � , then operator delete - // Never built by `init` either; see the note beside AILODManager near the end. + // ELF D1 call at 0x3EDEAC: the debug renderer, nonvirtual D1 + operator delete. + // Recovered on the client track; init never builds it, so + // this only runs once a debug command has made one. + if (AIRenderUtil::m_instance) + delete AIRenderUtil::m_instance; if (CommonSingletonServer::m_iaiInformationCourier) delete static_cast(CommonSingletonServer::m_iaiInformationCourier); @@ -300,8 +313,10 @@ bool BF2AI::clear() if (UserOrderManager::m_instance) delete UserOrderManager::m_instance; - // [FRONTIER: AIConsole] Cleanup is deferred until AIConsole destruction is implemented. - // [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding BF2AI operation. + // ELF D1 call at 0x3EDFFB: the console (its destructor resets it and deletes the SquadManager). + // Recovered on the client track. + if (AIConsole::m_instance) + delete AIConsole::m_instance; // Destruction clears the behavior-manager singleton, making repeated cleanup harmless. if (BotBehaviourManager::m_instance) @@ -332,7 +347,7 @@ bool BF2AI::clear() // both, with no destructor call on either - which is what establishes that `SpHandlePool` is // trivially destructible and that `InformationManager` owns nothing else. Written as the two // raw frees the binary makes rather than as `delete informationManager`, because a typed delete - // would call the destructor the binary does not call. See AIKnowledge/InformationManager.h. + // would call the destructor the binary does not call. See Main/InformationManager.h. if (informationManager) { if (informationManager->getPool()) @@ -362,19 +377,31 @@ bool BF2AI::clear() if (AIRandom::m_instance) delete AIRandom::m_instance; - // Deletes the LOD manager when present; an existing instance reaches its teardown frontier. + // Deletes the LOD manager when present. delete AILODManager::m_instance; - // [FRONTIER: AILandingZoneManager] Cleanup is deferred until its destructor is implemented. + // ELF D1 call at 0x3EE1A0 / PE read at 0x10001D5B: the landing-zone manager the static installer made. + // Its destructor does not zero m_instance (ELF 0x399D60, PE 0x10039B00), so the pointer dangles + // until the library is unloaded and its static initializers run again on the next load + // (AIConnection::clear unloads it right after this). No platform reset is added: on macOS + // dlclose does unmap libaidll.dylib (no thread-local or Objective-C sections, only libc++ and + // libSystem as dependencies; a dlopen/dlclose/RTLD_NOLOAD probe finds it gone after each close), + // so the next load re-runs the installer exactly as the retail DLL reload does. + if (AILandingZoneManager::m_instance) + delete AILandingZoneManager::m_instance; if (CommunicationHub::m_instance) delete CommunicationHub::m_instance; - // [FRONTIER: BotPlacementManager] delete BotPlacementManager::m_instance; init never made it + // ELF D1 call at 0x3EE1D0, the last delete: the placement manager the static initializer + // (0x3E4BD5) made at load. Its destructor zeroes m_instance. + if (BotPlacementManager::m_instance) + delete BotPlacementManager::m_instance; m_initialized = false; return true; } // Invokes virtual clear so a derived implementation can override shutdown cleanup. +// ELF 0x3EE270 bool BF2AI::shutdown() { clear(); // virtual, IAI vtable +0x0C @@ -382,12 +409,14 @@ bool BF2AI::shutdown() } // Advances the AI using its own timer. The supplied engine delta is ignored. +// ELF 0x3EE290 int BF2AI::update(double /*dt*/) { return IAIMain::m_instance->action(); // IAIMain vtable +0x34 } // Copies game settings into the AI configuration and initializes the runtime as needed. +// ELF 0x3EE2C0 int BF2AI::getSettingsFromMenu(bool /*fromMenu*/) { IAISettings* const settings = @@ -418,12 +447,14 @@ int BF2AI::getSettingsFromMenu(bool /*fromMenu*/) } // - a bare byte load. The engine's gate on every .ai load and on the AI tick. +// ELF 0x3EE410 bool BF2AI::isInitialized() const { return m_initialized; } // - a bare byte load. Also reports true for the whole of init; see BF2AI.h. +// ELF 0x3EE420 bool BF2AI::isShuttingDown() const { return m_shuttingDown; diff --git a/Code/BF2/AI/AIDLL/AI/Main/BF2AI.h b/Code/BF2/AI/AIDLL/AI/Main/BF2AI.h index 08fcf136a..61a27a3b0 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/BF2AI.h +++ b/Code/BF2/AI/AIDLL/AI/Main/BF2AI.h @@ -34,7 +34,7 @@ class BF2AI : public IAI virtual ~BF2AI(); virtual bool init(); - virtual bool clear(); // [FRONTIER] + virtual bool clear(); virtual bool shutdown(); virtual int getSettingsFromMenu(bool fromMenu); virtual int update(double dt); diff --git a/Code/BF2/AI/AIDLL/AI/Main/BFPathfindingCourier.cpp b/Code/BF2/AI/AIDLL/AI/Main/BFPathfindingCourier.cpp index 7bca24084..ed0fdf874 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/BFPathfindingCourier.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/BFPathfindingCourier.cpp @@ -1,14 +1,29 @@ // [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining BFPathfindingCourier operations. +// static init: ELF 0x2E8670 (__tcf_0 0x2E86D0, _GLOBAL__I 0x2E8700): 's Init object only. +#include + +#include "../AIBot/SquadManager.h" +#include "../AIBot/SquadMember.h" #include "BFPathfindingCourier.h" +#include +#include #include #include "../../../../Core/ClassManager.h" #include "CommonSingletonServer.h" #include "AIDllFrontier.h" #include "IAIPathfinding.h" // getVehicleNumberFromName's one forward -#include "AISettingsInterfaces.h" // IAISettings::getVehicle - findClosestValidInfantryPolygon +#include "AISettingsInterfaces.h" +#include "../AIBot/SquadManager.h" +#include "../AIBot/SquadMember.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/Information.h" +#include "InformationManager.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/BFGame.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" // IAISettings::getVehicle - findClosestValidInfantryPolygon namespace dice { namespace hfe { @@ -41,29 +56,104 @@ BFPathfindingCourier::~BFPathfindingCourier() { } +// ELF 0x2E8200. A "vehicle" here is a pathfinding map. int BFPathfindingCourier::getNumberOfVehicles() const { - BF2_AI_FRONTIER("dice::hfe::ai::BFPathfindingCourier::getNumberOfVehicles"); + return IAIPathfinding::instance->getNumberOfMaps(); } -bool BFPathfindingCourier::isVehicleUsed(unsigned int) const +// ELF 0x2E8230. +bool BFPathfindingCourier::isVehicleUsed(unsigned int map) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFPathfindingCourier::isVehicleUsed"); + return IAIPathfinding::instance->isMapUsed(static_cast(map)); } -bool BFPathfindingCourier::isValidPosition(int, int, const Vec3&) const +// ELF 0x2E8270. Ignores materials. +bool BFPathfindingCourier::isValidPosition(int map, int vehicleId, const Vec3& position) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFPathfindingCourier::isValidPosition"); + return IAIPathfinding::instance->isValidPosition(map, vehicleId, position, true); } -bool BFPathfindingCourier::isValidPosition(const Vec3&) const +// ELF 0x2E82C0. On the trace map, as vehicle 1, ignoring materials. +bool BFPathfindingCourier::isValidPosition(const Vec3& position) const +{ + IAIPathfinding* const pathfinding = IAIPathfinding::instance; + return pathfinding->isValidPosition(pathfinding->getTraceMapIndex(), 1, position, true); +} + +namespace { + +// [TEMP] [RETIRE-WHEN: ai-bot-squad-leader-closest] Neither callee is declared yet (request to +// ai-bot in coord/ai-requests.md); each stops by name until it is. +SquadMember* squadLeaderClosestTo(SquadManager* manager, const Vec3& position) { - BF2_AI_FRONTIER("dice::hfe::ai::BFPathfindingCourier::isValidPosition"); + return manager->getSquadLeaderClosestTo(position); } -void BFPathfindingCourier::getLastValidSquadleaderPosition(const Vec3&) const +int sideOf(SquadMember* member) +{ + return member->getSide(); +} + +} // anonymous namespace + +// ELF 0x2E8320. The squad leader closest to `position` (no null test, as in retail): the last +// valid infantry position of its vehicle's information for its side when the vehicle, that +// information, its unit and mobile plug-ins exist and the position's polygon is valid. +// Otherwise the eligible spawn point of its side closest (strictly, squared) to the leader's +// position; (-4000, -4000, -4000) when the leader has no position or no spawn point qualifies. +Vec3 BFPathfindingCourier::getLastValidSquadleaderPosition(const Vec3& position) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFPathfindingCourier::getLastValidSquadleaderPosition"); + SquadMember* const leader = squadLeaderClosestTo(SquadManager::m_instance, position); + const int side = sideOf(leader); + + IAIObject* const vehicle = leader->getPlayer()->getCurrentVehicle(); + if (vehicle != 0) + { + Information* const information = + informationManager->getInformation(vehicle->getInformation(side)); + if (information != 0 && information->getUnit() != 0 && information->getMobile() != 0) + { + const IPIMobile::ValidPos& valid = information->getMobile()->getLastValidInfantryPos(); + if (valid.polygon != 0xFFFFFFFFu) + return valid.position; + } + } + + IAIGame* const game = static_cast(CommonSingletonServer::m_iaiGame); + const std::list& spawnPoints = game->getSpawnPointList(side); + float bestDistance = FLT_MAX; + std::list::const_iterator best = spawnPoints.end(); + Vec3 leaderPosition; + leaderPosition.x = 0.0f; + leaderPosition.y = 0.0f; + leaderPosition.z = 0.0f; + if (leader->getPosition(leaderPosition)) + { + for (std::list::const_iterator i = spawnPoints.begin(); i != spawnPoints.end(); ++i) + { + if (!game->isEligibleSpawnpoint(side, *i)) + continue; + const Vec3& spawn = game->getSpawnPointPosition(*i); + const float dx = leaderPosition.x - spawn.x; + const float dy = leaderPosition.y - spawn.y; + const float dz = leaderPosition.z - spawn.z; + const float distance = dx * dx + dy * dy + dz * dz; + if (bestDistance > distance) + { + bestDistance = distance; + best = i; + } + } + if (best != spawnPoints.end()) + return game->getSpawnPointPosition(*best); + } + + Vec3 nowhere; + nowhere.x = -4000.0f; + nowhere.y = -4000.0f; + nowhere.z = -4000.0f; + return nowhere; } // Returns the case-insensitive pathfinding map id, or -1 for an unknown name. diff --git a/Code/BF2/AI/AIDLL/AI/Main/BFPathfindingCourier.h b/Code/BF2/AI/AIDLL/AI/Main/BFPathfindingCourier.h index 128aefa7c..902de49e4 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/BFPathfindingCourier.h +++ b/Code/BF2/AI/AIDLL/AI/Main/BFPathfindingCourier.h @@ -33,7 +33,8 @@ class IAIPathfindingCourier virtual bool isVehicleUsed(unsigned int) const = 0; virtual bool isValidPosition(int, int, const Vec3&) const = 0; virtual bool isValidPosition(const Vec3&) const = 0; - virtual void getLastValidSquadleaderPosition(const Vec3&) const = 0; + // Returns by value (ELF `ret $4`: hidden result pointer), not void. + virtual Vec3 getLastValidSquadleaderPosition(const Vec3&) const = 0; virtual int getVehicleNumberFromName(const std::string&) const = 0; // bool // with no widening before `ret 10h` - an int return would need the `movzx` it lacks. (The ELF's @@ -53,7 +54,7 @@ class BFPathfindingCourier : public IAIPathfindingCourier virtual bool isVehicleUsed(unsigned int) const; virtual bool isValidPosition(int, int, const Vec3&) const; virtual bool isValidPosition(const Vec3&) const; - virtual void getLastValidSquadleaderPosition(const Vec3&) const; + virtual Vec3 getLastValidSquadleaderPosition(const Vec3&) const; virtual int getVehicleNumberFromName(const std::string&) const; virtual bool findClosestValidInfantryPolygon(Vec3&, const Vec3&, const Vec3&, unsigned int) const; diff --git a/Code/BF2/AI/AIDLL/AI/Main/BotBehaviourManager.cpp b/Code/BF2/AI/AIDLL/AI/Main/BotBehaviourManager.cpp index 3df8a4614..63e1067ee 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/BotBehaviourManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/BotBehaviourManager.cpp @@ -1,9 +1,69 @@ +// static init: ELF 0x3D3120 (__tcf_0 0x3D3180, _GLOBAL__I 0x3D31B0): 's Init object only. +#include + #include "BotBehaviourManager.h" #include "../AIBotBehaviour/UrgeCurve.h" // UCConstant / UCLinear / UCXInverse - the three factories #include "../AIUtils/checkPointer.h" // inlined 26 times in the constructor #include "AIDllFrontier.h" +#include "../AIBotBehaviour/BBAvoid.h" +#include "../AIBotBehaviour/BBBridgeRepair.h" +#include "../AIBotBehaviour/BBC4.h" +#include "../AIBotBehaviour/BBCallForMedic.h" +#include "../AIBotBehaviour/BBChange.h" +#include "../AIBotBehaviour/BBChangeLandingCraft.h" +#include "../AIBotBehaviour/BBChangeTeleport.h" +#include "../AIBotBehaviour/BBDefuseMines.h" +#include "../AIBotBehaviour/BBFire.h" +#include "../AIBotBehaviour/BBFire3d.h" +#include "../AIBotBehaviour/BBFireArtilleryDriver.h" +#include "../AIBotBehaviour/BBFireInfantery.h" +#include "../AIBotBehaviour/BBFireLargeBore.h" +#include "../AIBotBehaviour/BBFireUnarmed.h" +#include "../AIBotBehaviour/BBIdle.h" +#include "../AIBotBehaviour/BBMedicAssist.h" +#include "../AIBotBehaviour/BBMoveTo.h" +#include "../AIBotBehaviour/BBMoveToFixed.h" +#include "../AIBotBehaviour/BBRandom.h" +#include "../AIBotBehaviour/BBRevive.h" +#include "../AIBotBehaviour/BBRunOverSoldier.h" +#include "../AIBotBehaviour/BBSuicide.h" +#include "../AIBotBehaviour/BBTakeCover.h" +#include "../AIBotBehaviour/BBTakeCover3d.h" +#include "../AIBotBehaviour/BBTakeCoverInfantry.h" +#include "../AIBotBehaviour/BBTriggerable.h" +#include "../AIBotBehaviourPattern/BBPAvoidCollision2d.h" +#include "../AIBotBehaviourPattern/BBPAvoidCollision3d.h" +#include "../AIBotBehaviourPattern/BBPAvoidCollisionInfantery.h" +#include "../AIBotBehaviourPattern/BBPBridgeRepair.h" +#include "../AIBotBehaviourPattern/BBPC4.h" +#include "../AIBotBehaviourPattern/BBPCallForMedic.h" +#include "../AIBotBehaviourPattern/BBPChange.h" +#include "../AIBotBehaviourPattern/BBPChangeLandingCraft.h" +#include "../AIBotBehaviourPattern/BBPChangeTeleport.h" +#include "../AIBotBehaviourPattern/BBPDefuseMines.h" +#include "../AIBotBehaviourPattern/BBPFire2d.h" +#include "../AIBotBehaviourPattern/BBPFire2dDriver.h" +#include "../AIBotBehaviourPattern/BBPFire3d.h" +#include "../AIBotBehaviourPattern/BBPFireInfantery.h" +#include "../AIBotBehaviourPattern/BBPGotoWaypoints2d.h" +#include "../AIBotBehaviourPattern/BBPGotoWaypoints3d.h" +#include "../AIBotBehaviourPattern/BBPGotoWaypointsBoat.h" +#include "../AIBotBehaviourPattern/BBPGotoWaypointsInfantery.h" +#include "../AIBotBehaviourPattern/BBPHeliFire3d.h" +#include "../AIBotBehaviourPattern/BBPIdle2d.h" +#include "../AIBotBehaviourPattern/BBPIdle3d.h" +#include "../AIBotBehaviourPattern/BBPIdleInfantery.h" +#include "../AIBotBehaviourPattern/BBPMedicAssist.h" +#include "../AIBotBehaviourPattern/BBPRandom.h" +#include "../AIBotBehaviourPattern/BBPRevive.h" +#include "../AIBotBehaviourPattern/BBPRunOverSoldier.h" +#include "../AIBotBehaviourPattern/BBPSuicide.h" +#include "../AIBotBehaviourPattern/BBPTakeCover.h" +#include "../AIBotBehaviourPattern/BBPTakeCover3d.h" +#include "../AIBotBehaviourPattern/BBPTakeCoverInfantry.h" +#include "../AIBotBehaviourPattern/BBPTriggerable.h" namespace dice { namespace hfe { @@ -19,208 +79,208 @@ namespace { class BBCreateFunctionAvoid : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBMoveTo`. class BBCreateFunctionMoveTo : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBMoveToFixed`. class BBCreateFunctionMoveToFixed : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBMedicAssist`. class BBCreateFunctionMedicAssist : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBIdle`. class BBCreateFunctionIdle : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBFire`. class BBCreateFunctionFire : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBFire3d`. class BBCreateFunctionFire3d : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBFireInfantery`. class BBCreateFunctionFireInfantery : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBFireUnarmed`. class BBCreateFunctionFireUnarmed : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBFireLargeBore`. class BBCreateFunctionFireLargeBore : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBTakeCover`. class BBCreateFunctionTakeCover : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBTakeCoverInfantry`. class BBCreateFunctionTakeCoverInfantry : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBFireDriver`. class BBCreateFunctionFireDriver : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBChange`. class BBCreateFunctionChange : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBChangeLandingCraft`. class BBCreateFunctionChangeLandingCraft : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBChangeTeleport`. class BBCreateFunctionChangeTeleport : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBSuicide`. class BBCreateFunctionSuicide : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBCallForMedic`. class BBCreateFunctionCallForMedic : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBRevive`. class BBCreateFunctionRevive : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBTakeCover3d`. class BBCreateFunctionTakeCover3d : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBC4`. class BBCreateFunctionC4 : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBRunOverSoldier`. class BBCreateFunctionRunOverSoldier : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBBridgeRepair`. class BBCreateFunctionBridgeRepair : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBDefuseMines`. class BBCreateFunctionDefuseMines : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBRandom`. class BBCreateFunctionRandom : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBTriggerable`. class BBCreateFunctionTriggerable : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; } // anonymous namespace @@ -322,7 +382,7 @@ std::string BotBehaviourManager::getBehaviourName(int id) // Creates a named behavior through a registered factory. -int BotBehaviourManager::create(std::string behaviourName, std::string createFunctionName, +BotBehaviour* BotBehaviourManager::create(std::string behaviourName, std::string createFunctionName, std::string name, int mode, std::string urgeCurveName, float* weights, std::string& message) { @@ -368,190 +428,312 @@ std::string BotBehaviourManager::createUCXInverse(std::string& name, float numer return "UCXInverse created"; } -// The twenty-six frontier bodies. +// The twenty-six create functions (weak in the image, 0x3D4190..0x3D8DD0). Each compares the +// pattern name with its candidates in the image's order, builds the first match with the behaviour +// id, and builds the behaviour with (id, mode) narrowed to bytes (`movzbl`), the pattern (null when +// no name matches), the urge curve and the weights. Every allocation goes through checkPointer +// (the Debug(6, ..., 46, ...) "Allocation failed" branch after each `new`). namespace { -// Creation of BBAvoid and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionAvoid::operator()(int, std::string&, int, UrgeCurve*, float*) -{ - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionAvoid::operator()"); +// ELF 0x3D4190. +BotBehaviour* BBCreateFunctionAvoid::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) +{ + BBPAvoidCollision* pattern = 0; + if (name.compare("BBPAvoidCollision2d") == 0) + pattern = checkPointer(new BBPAvoidCollision2d(behaviourId)); + else if (name.compare("BBPAvoidCollision3d") == 0) + pattern = checkPointer(new BBPAvoidCollision3d(behaviourId)); + else if (name.compare("BBPAvoidCollisionInfantery") == 0) + pattern = checkPointer(new BBPAvoidCollisionInfantery(behaviourId)); + return checkPointer(new BBAvoid(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBMoveTo and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionMoveTo::operator()(int, std::string&, int, UrgeCurve*, float*) -{ - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionMoveTo::operator()"); -} +// ELF 0x3D4690. +BotBehaviour* BBCreateFunctionMoveTo::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) +{ + BBPGotoWaypoint* pattern = 0; + if (name.compare("BBPGotoWaypoint2d") == 0) + pattern = checkPointer(new BBPGotoWaypoint2d(behaviourId)); + else if (name.compare("BBPGotoWaypointBoat") == 0) + pattern = checkPointer(new BBPGotoWaypointBoat(behaviourId)); + else if (name.compare("BBPGotoWaypoint3d") == 0) + pattern = checkPointer(new BBPGotoWaypoint3d(behaviourId)); + else if (name.compare("BBPGotoWaypointInfantery") == 0) + pattern = checkPointer(new BBPGotoWaypointSoldier(behaviourId)); + return checkPointer(new BBMoveTo(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); +} -// Creation of BBMoveToFixed and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionMoveToFixed::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D4CC0. +BotBehaviour* BBCreateFunctionMoveToFixed::operator()(int behaviourId, std::string&, int mode, + UrgeCurve*, float*) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionMoveToFixed::operator()"); + return checkPointer(new BBMoveToFixed(static_cast(behaviourId), static_cast(mode))); } -// Creation of BBMedicAssist and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionMedicAssist::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D5D90. +BotBehaviour* BBCreateFunctionMedicAssist::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionMedicAssist::operator()"); + PlanGenerator* pattern = 0; + if (name.compare("BBPMedicAssist") == 0) + pattern = checkPointer(new BBPMedicAssist(behaviourId)); + return checkPointer(new BBMedicAssist(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBIdle and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionIdle::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D4F80. +BotBehaviour* BBCreateFunctionIdle::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionIdle::operator()"); + BBPIdle* pattern = 0; + if (name.compare("BBPIdle2d") == 0) + pattern = checkPointer(new BBPIdle2d(behaviourId)); + else if (name.compare("BBPIdle3d") == 0) + pattern = checkPointer(new BBPIdle3d(behaviourId)); + else if (name.compare("BBPIdleInfantery") == 0) + pattern = checkPointer(new BBPIdleInfantery(behaviourId)); + return checkPointer(new BBIdle(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBFire and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionFire::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D6030. +BotBehaviour* BBCreateFunctionFire::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionFire::operator()"); + BBPFire* pattern = 0; + if (name.compare("BBPFire2d") == 0) + pattern = checkPointer(new BBPFire2d(behaviourId)); + else if (name.compare("BBPFireInfantery") == 0) + pattern = checkPointer(new BBPFireInfantery(behaviourId)); + return checkPointer(new BBFire(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBFire3d and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionFire3d::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D6A80. +BotBehaviour* BBCreateFunctionFire3d::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionFire3d::operator()"); + BBPFire* pattern = 0; + if (name.compare("BBPFire3d") == 0) + pattern = checkPointer(new BBPFire3d(behaviourId)); + else if (name.compare("BBPHeliFire3d") == 0) + pattern = checkPointer(new BBPHeliFire3d(behaviourId)); + return checkPointer(new BBFire3d(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBFireInfantery and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionFireInfantery::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D6E50. +BotBehaviour* BBCreateFunctionFireInfantery::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionFireInfantery::operator()"); + BBPFireInfantery* pattern = 0; + if (name.compare("BBPFireInfantery") == 0) + pattern = checkPointer(new BBPFireInfantery(behaviourId)); + return checkPointer(new BBFireInfantery(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBFireUnarmed and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionFireUnarmed::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D4E20. +BotBehaviour* BBCreateFunctionFireUnarmed::operator()(int behaviourId, std::string&, int mode, + UrgeCurve*, float*) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionFireUnarmed::operator()"); + return checkPointer(new BBFireUnarmed(static_cast(behaviourId), static_cast(mode))); } -// Creation of BBFireLargeBore and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionFireLargeBore::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D6400. +BotBehaviour* BBCreateFunctionFireLargeBore::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionFireLargeBore::operator()"); + BBPFire* pattern = 0; + if (name.compare("BBPFire2d") == 0) + pattern = checkPointer(new BBPFire2d(behaviourId)); + else if (name.compare("BBPFireInfantery") == 0) + pattern = checkPointer(new BBPFireInfantery(behaviourId)); + return checkPointer(new BBFireLargeBore(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights, false)); } -// Creation of BBTakeCover and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionTakeCover::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D70F0. +BotBehaviour* BBCreateFunctionTakeCover::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionTakeCover::operator()"); + PlanGenerator* pattern = 0; + if (name.compare("BBPTakeCover") == 0) + pattern = checkPointer(new BBPTakeCover(behaviourId)); + return checkPointer(new BBTakeCover(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBTakeCoverInfantry and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionTakeCoverInfantry::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D7390. +BotBehaviour* BBCreateFunctionTakeCoverInfantry::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionTakeCoverInfantry::operator()"); + PlanGenerator* pattern = 0; + if (name.compare("BBPTakeCoverInfantry") == 0) + pattern = checkPointer(new BBPTakeCoverInfantry(behaviourId)); + return checkPointer(new BBTakeCoverInfantry(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBFireDriver and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionFireDriver::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D67E0. +BotBehaviour* BBCreateFunctionFireDriver::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionFireDriver::operator()"); + BBPFire* pattern = 0; + if (name.compare("BBPFire2dDriver") == 0) + pattern = checkPointer(new BBPFire2dDriver(behaviourId)); + return checkPointer(new BBFireArtilleryDriver(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBChange and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionChange::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D5480. +BotBehaviour* BBCreateFunctionChange::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionChange::operator()"); + PlanGenerator* pattern = 0; + if (name.compare("BBPChange") == 0) + pattern = checkPointer(new BBPChange(behaviourId)); + return checkPointer(new BBChange(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBChangeLandingCraft and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionChangeLandingCraft::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D5720. +BotBehaviour* BBCreateFunctionChangeLandingCraft::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionChangeLandingCraft::operator()"); + PlanGenerator* pattern = 0; + if (name.compare("BBPChangeLandingCraft") == 0) + pattern = checkPointer(new BBPChangeLandingCraft(behaviourId)); + else if (name.compare("BBPChange") == 0) + pattern = checkPointer(new BBPChange(behaviourId)); + return checkPointer(new BBChangeLandingCraft(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBChangeTeleport and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionChangeTeleport::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D5AF0. +BotBehaviour* BBCreateFunctionChangeTeleport::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionChangeTeleport::operator()"); + PlanGenerator* pattern = 0; + if (name.compare("BBPChangeTeleport") == 0) + pattern = checkPointer(new BBPChangeTeleport(behaviourId)); + return checkPointer(new BBChangeTeleport(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBSuicide and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionSuicide::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D7630. +BotBehaviour* BBCreateFunctionSuicide::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionSuicide::operator()"); + BBPSuicide* pattern = 0; + if (name.compare("BBPSuicide") == 0) + pattern = checkPointer(new BBPSuicide(behaviourId)); + return checkPointer(new BBSuicide(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBCallForMedic and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionCallForMedic::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D78D0. +BotBehaviour* BBCreateFunctionCallForMedic::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionCallForMedic::operator()"); + BBPCallForMedic* pattern = 0; + if (name.compare("BBPCallForMedic") == 0) + pattern = checkPointer(new BBPCallForMedic(behaviourId)); + return checkPointer(new BBCallForMedic(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBRevive and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionRevive::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D7B70. +BotBehaviour* BBCreateFunctionRevive::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionRevive::operator()"); + BBPRevive* pattern = 0; + if (name.compare("BBPRevive") == 0) + pattern = checkPointer(new BBPRevive(behaviourId)); + return checkPointer(new BBRevive(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBTakeCover3d and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionTakeCover3d::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D7E10. +BotBehaviour* BBCreateFunctionTakeCover3d::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionTakeCover3d::operator()"); + PlanGenerator* pattern = 0; + if (name.compare("BBPTakeCover3d") == 0) + pattern = checkPointer(new BBPTakeCover3d(behaviourId)); + return checkPointer(new BBTakeCover3d(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBC4 and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionC4::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D80B0. +BotBehaviour* BBCreateFunctionC4::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionC4::operator()"); + PlanGenerator* pattern = 0; + if (name.compare("BBPC4") == 0) + pattern = checkPointer(new BBPC4(behaviourId)); + return checkPointer(new BBC4(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBRunOverSoldier and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionRunOverSoldier::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D8890. +BotBehaviour* BBCreateFunctionRunOverSoldier::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionRunOverSoldier::operator()"); + PlanGenerator* pattern = 0; + if (name.compare("BBPRunOverSoldier") == 0) + pattern = checkPointer(new BBPRunOverSoldier(behaviourId)); + return checkPointer(new BBRunOverSoldier(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBBridgeRepair and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionBridgeRepair::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D8350. +BotBehaviour* BBCreateFunctionBridgeRepair::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionBridgeRepair::operator()"); + PlanGenerator* pattern = 0; + if (name.compare("BBPBridgeRepair") == 0) + pattern = checkPointer(new BBPBridgeRepair(behaviourId)); + return checkPointer(new BBBridgeRepair(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBDefuseMines and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionDefuseMines::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D85F0. +BotBehaviour* BBCreateFunctionDefuseMines::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionDefuseMines::operator()"); + PlanGenerator* pattern = 0; + if (name.compare("BBPDefuseMines") == 0) + pattern = checkPointer(new BBPDefuseMines(behaviourId)); + return checkPointer(new BBDefuseMines(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBRandom and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionRandom::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D8B30. +BotBehaviour* BBCreateFunctionRandom::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionRandom::operator()"); + PlanGenerator* pattern = 0; + if (name.compare("BBPRandom") == 0) + pattern = checkPointer(new BBPRandom(behaviourId)); + return checkPointer(new BBRandom(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBTriggerable and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionTriggerable::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D8DD0. +BotBehaviour* BBCreateFunctionTriggerable::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionTriggerable::operator()"); + PlanGenerator* pattern = 0; + if (name.compare("BBPTriggerable") == 0) + pattern = checkPointer(new BBPTriggerable(behaviourId)); + return checkPointer(new BBTriggerable(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } } // anonymous namespace diff --git a/Code/BF2/AI/AIDLL/AI/Main/BotBehaviourManager.h b/Code/BF2/AI/AIDLL/AI/Main/BotBehaviourManager.h index f0d906ab4..c0439ec88 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/BotBehaviourManager.h +++ b/Code/BF2/AI/AIDLL/AI/Main/BotBehaviourManager.h @@ -13,14 +13,17 @@ namespace dice { namespace hfe { namespace ai { +class BotBehaviour; class UrgeCurve; // Factory interface for constructing bot behaviors. class BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights) = 0; + // Returns the new behaviour (`movl %edi, %eax` after `new BB...`); an unknown pattern name + // still builds the behaviour, with a null pattern. + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) = 0; }; class BotBehaviourManager @@ -41,7 +44,9 @@ class BotBehaviourManager // the factory dispatch // Called by `AIConsole::setVehicleBehaviour` , which is the `.ai` script binding. - int create(std::string behaviourName, std::string createFunctionName, std::string name, + // Returns the created behaviour, or null with `message` set (AIConsole::setVehicleBehaviour + // registers a non-null result). + BotBehaviour* create(std::string behaviourName, std::string createFunctionName, std::string name, int mode, std::string urgeCurveName, float* weights, std::string& message); // the urge-curve factories diff --git a/Code/BF2/AI/AIDLL/AI/Main/BotManager.cpp b/Code/BF2/AI/AIDLL/AI/Main/BotManager.cpp index 09c95a1ad..2e1e39eb8 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/BotManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/BotManager.cpp @@ -1,16 +1,26 @@ // Owns the bot pool and schedules sensing, decisions and plan execution. // Work is distributed across ticks according to per-bot update deadlines and detail level. +// static init: ELF 0x3E1470 (__tcf_0 0x3E14D0, _GLOBAL__I 0x3E1500): 's Init object only. +#include + +#include #include "BotManager.h" -#include "AIDllFrontier.h" +#include +#include "../AIBot/WPEmpty.h" +#include "../AIBotActionPlan/BAPStatement.h" +#include "../../../AIInterface/BFKnowledge/BFGame.h" +#include "../../../../IO/File/FileManager.h" +#include "../../../../Game/Objects/IObject.h" +#include "../../../../Game/Objects/IObjectTemplate.h" #include "AIMain.h" // IAIMain::m_instance - cached at +60 #include "AISettingsInterfaces.h" // IAISettings::getMaxNBots #include "../AIBot/BotMain.h" // the preallocated pool #include "../AIBot/BotMemory.h" #include "../AIBot/BotOrder.h" -#include "../AIBotBehaviour/UrgencyMerger.h" +#include "../AIBot/UrgencyMerger.h" #include "BotBehaviourManager.h" #include "../AIUtils/checkPointer.h" #include "CommonSingletonServer.h" @@ -22,20 +32,37 @@ #include "../AIBot/BotNavigation.h" // actionComAgent / actionUpdateNavPoints #include "../AIBot/CommunicationAgent.h" // actionComAgent #include "../AIKnowledge/Information.h" // updateDamages -#include "../AIKnowledge/InformationManager.h" +#include "InformationManager.h" #include "../AIKnowledge/IPIMobile.h" // actionExecutePlan's stall test, actionPathfinding #include "IAIPathfinding.h" // actionPathfinding hands the searcher its share #include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" // actionHearing's object list #include "../AIKnowledge/IPIPhysical.h" #include "../../../../IO/Input/PlayerInput.h" // actionExecutePlan presses a climber's inputs +#include "../../../AIInterface/BFKnowledge/IAIObject.h" // the object map, vehicle changes +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" // IAIObjectPhysical::enablePhysics +#include "../AIBot/BotCallBack.h" // death and spawn reports +#include "../AIBot/BotSquad.h" // the order forwarders +#include "../../../AIInterface/BFKnowledge/IWeapon.h" // actionHearing namespace dice { namespace hfe { namespace ai { +int BotManager::s_tabLevel = 0; + // Runs the scheduled bot work within the supplied time budget. +// ELF 0x3DD580 void BotManager::action(const double& budget) { +#if !defined(_WIN32) + // [TEMP] [CHOSEN, not recovered] BF2_AI_SPAWN_ONLY=1: bots spawn and stay in the game but + // run no per-tick AI (no plans, sensing, decisions), so a round with bots runs while the AI + // reconstruction (branch ai-reconstruct) is incomplete. Off by default. + // [RETIRE-WHEN: ai-reconstruct reaches a full round without stops] + static const bool spawnOnly = std::getenv("BF2_AI_SPAWN_ONLY") != 0; + if (spawnOnly) + return; +#endif IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); const double deadline = timer->getUpdateTime() + budget; @@ -107,18 +134,19 @@ void BotManager::action(const double& budget) } // Applies accumulated bot damage once per tick. +// ELF 0x3E0AF0 void BotManager::updateDamages() { IAIGameEffector* const effector = static_cast(CommonSingletonServer::m_iaiGameEffector); - for (std::vector::iterator it = m_botInfos.begin(); it != m_botInfos.end(); ++it) + for (std::vector::iterator it = m_bots.begin(); it != m_bots.end(); ++it) { if (!(*it)->m_bot->isDead() && (*it)->m_damage > 0.0f) { world::IPlayer* const from = - m_botInfos[(*it)->m_attackerIndex]->m_bot->getPlayer()->getPlayer(); + m_bots[(*it)->m_attackerIndex]->m_bot->getPlayer()->getPlayer(); #if defined(_WIN32) - Bot* const attacker = m_botInfos[(*it)->m_attackerIndex]->m_bot; + Bot* const attacker = m_bots[(*it)->m_attackerIndex]->m_bot; const unsigned int handle = (*it)->m_bot->getCurrentEquipment(); Information* const information = (handle & 0xffffu) ? informationManager->getInformation(handle) : nullptr; @@ -127,7 +155,7 @@ void BotManager::updateDamages() effector->giveDamage(target, from, attacker->getSide(), damage); #else BotInfo* const info = *it; - const int side = m_botInfos[info->m_attackerIndex]->m_bot->getSide(); + const int side = m_bots[info->m_attackerIndex]->m_bot->getSide(); InformationManager* const manager = informationManager; const unsigned int handle = (*it)->m_bot->getCurrentEquipment(); Information* const information = manager->getInformation(handle); @@ -140,26 +168,27 @@ void BotManager::updateDamages() // [INFERRED] Services one eligible bot's radio per tick, resuming from the saved cursor. // Skips dead, man-down, or navigation-blocked bots and makes at most one roster circuit. +// ELF 0x3DE360 void BotManager::actionComAgent() { const unsigned int start = m_comAgentCursor; - if (m_botInfos.empty()) + if (m_bots.empty()) return; - Bot* bot = m_botInfos[m_comAgentCursor]->m_bot; + Bot* bot = m_bots[m_comAgentCursor]->m_bot; for (;;) { if (!bot->isDead() && !bot->getManDown() && !bot->getBotNavigation()->isPathSearchPending()) { bot->getCommunicationAgent()->update(); - if (++m_comAgentCursor >= m_botInfos.size()) + if (++m_comAgentCursor >= m_bots.size()) m_comAgentCursor = 0; return; } - if (++m_comAgentCursor >= m_botInfos.size()) + if (++m_comAgentCursor >= m_bots.size()) m_comAgentCursor = 0; if (start == m_comAgentCursor) return; - bot = m_botInfos[m_comAgentCursor]->m_bot; + bot = m_bots[m_comAgentCursor]->m_bot; } } @@ -174,19 +203,20 @@ static bool speedSquaredAtMost(const Vec3& speed, float limit) } // Executes plans for the scheduled portion of the roster and refills work queues within the budget. +// ELF 0x3DDA90 void BotManager::actionExecutePlan(const double& slice) { IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); const double deadline = timer->getUpdateTime() + slice; - m_queuePriorityA->clear(); - m_queuePriorityB->clear(); - m_queueSensing->clear(); + m_planned->clear(); + m_unplanned->clear(); + m_sensingQueue->clear(); m_planExecutionsThisTick = 0; m_tickCount180 = 0; m_tickCount184 = 0; - const unsigned int size = static_cast(m_botInfos.size()); + const unsigned int size = static_cast(m_bots.size()); m_planHalfToggle = !m_planHalfToggle; unsigned int count = size / 2 + 1; if (count > size) @@ -197,7 +227,7 @@ void BotManager::actionExecutePlan(const double& slice) unsigned int processed = 0; while (processed < count) { - BotInfo* info = m_botInfos[m_planCursor]; + BotInfo* info = m_bots[m_planCursor]; Bot* const bot = info->m_bot; if (!bot || bot->isDead() || bot->isDeactivated() || !bot->getSquadMember()) { @@ -222,14 +252,14 @@ void BotManager::actionExecutePlan(const double& slice) { if (bot->getPlayer() && bot->getPlayer()->getCurrentVehicle()) { - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - // Retail: `IAIObject* primary = getPlayer->getCurrentVehicle->getPrimaryObject; - // if (primary) { bot->setBotStuck(true); primary->setIsAllowedByBots(false); }` - // IAIObject slots ELF +0xFC / +0x9C (PE +0xF8 / +0x98), named from the engine's - // AIObjectReal table (bf2 ). IAIObject has no declaration in this tree. - IAIObject* const vehicle = bot->getPlayer()->getCurrentVehicle(); - (void)vehicle; - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::actionExecutePlan (IAIObject::getPrimaryObject)"); + // ELF 0x3DE2A7: IAIObject +0xFC getPrimaryObject; a stuck bot marks its vehicle's + // primary object as not allowed to bots (+0x9C), after Bot +0x148 setBotStuck. + IAIObject* const primary = bot->getPlayer()->getCurrentVehicle()->getPrimaryObject(); + if (primary) + { + bot->setBotStuck(true); + primary->setIsAllowedByBots(false); + } } bool onFoot = false; if (bot->getPlayer()) @@ -276,13 +306,13 @@ void BotManager::actionExecutePlan(const double& slice) if (bot->hasPlan() && !bot->hasDefaultPlan()) { if (info->m_double24 > m_plannedDecisionMakingThresholdFull) - m_queuePriorityA->push(info); + m_planned->push(info); } else if (info->m_double24 > m_unplannedDecisionMakingThresholdFull) { - m_queuePriorityB->push(info); + m_unplanned->push(info); } - m_queueSensing->push(info); + m_sensingQueue->push(info); bot->updatePlayerAction(!inBudget); if (!executed) break; @@ -291,25 +321,26 @@ void BotManager::actionExecutePlan(const double& slice) } for (unsigned int i = 0; i < size - processed; ++i) - m_botInfos[m_planCursor]->m_bot->updatePlayerAction(false); + m_bots[m_planCursor]->m_bot->updatePlayerAction(false); } // [INFERRED] Visits at most one roster circuit and refreshes at most size/16 + 1 active // navigations, skipping dead and man-down bots. Requires nonnull bot records: a null bot // does not advance the cursor and would loop indefinitely. +// ELF 0x3DD980 void BotManager::actionUpdateNavPoints() { - if (m_botInfos.empty()) + if (m_bots.empty()) return; - const unsigned int limit = static_cast(m_botInfos.size() >> 4) + 1; + const unsigned int limit = static_cast(m_bots.size() >> 4) + 1; unsigned int updated = 0; unsigned int visited = 0; - while (updated < limit && visited < m_botInfos.size()) + while (updated < limit && visited < m_bots.size()) { - Bot* const bot = m_botInfos[m_navPointCursor]->m_bot; + Bot* const bot = m_bots[m_navPointCursor]->m_bot; if (!bot) continue; - m_navPointCursor = (m_navPointCursor + 1) % static_cast(m_botInfos.size()); + m_navPointCursor = (m_navPointCursor + 1) % static_cast(m_bots.size()); ++visited; if (bot->isDead() || bot->getManDown()) continue; @@ -323,6 +354,7 @@ void BotManager::actionUpdateNavPoints() } // Schedules decisions using the interleave limits and each bot's detail level. +// ELF 0x3DE850 void BotManager::actionDecisionMaking(const double& slice) { unsigned int light = 0; @@ -332,16 +364,16 @@ void BotManager::actionDecisionMaking(const double& slice) static_cast(CommonSingletonServer::m_iBFTimer)->getUpdateTime() + slice; int spare = static_cast(m_plannedDecisionMakingInterleave) - - static_cast(m_queuePriorityA->size()); + - static_cast(m_planned->size()); if (spare < 0) spare = 0; const unsigned int unplannedLimit = m_unplannedDecisionMakingInterleave + spare; m_selectedBots.resize(0); - while (!m_queuePriorityB->empty() && m_selectedBots.size() < unplannedLimit) + while (!m_unplanned->empty() && m_selectedBots.size() < unplannedLimit) { - BotInfo* info = m_queuePriorityB->top(); - m_queuePriorityB->pop(); + BotInfo* info = m_unplanned->top(); + m_unplanned->pop(); switch (info->m_bot->getLodLevel()) { case BotLodFull: @@ -360,10 +392,10 @@ void BotManager::actionDecisionMaking(const double& slice) } unsigned int planned = 0; - while (!m_queuePriorityA->empty() && planned++ < m_plannedDecisionMakingInterleave) + while (!m_planned->empty() && planned++ < m_plannedDecisionMakingInterleave) { - BotInfo* info = m_queuePriorityA->top(); - m_queuePriorityA->pop(); + BotInfo* info = m_planned->top(); + m_planned->pop(); switch (info->m_bot->getLodLevel()) { case BotLodFull: @@ -426,19 +458,20 @@ void BotManager::actionDecisionMaking(const double& slice) } // Uses one tenth of the slice for bot path requests and the remainder for search processing. +// ELF 0x3DF7F0 void BotManager::actionPathfinding(const double& slice) { IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); const double now = timer->getUpdateTime(); const double deadline = now + slice; const double botDeadline = now + slice * 0.1; - const unsigned int size = static_cast(m_botInfos.size()); + const unsigned int size = static_cast(m_bots.size()); for (unsigned int visited = 0; visited < size; ++visited) { if (timer->getUpdateTime() > botDeadline) break; - BotInfo* const info = m_botInfos[m_pathfindingCursor]; + BotInfo* const info = m_bots[m_pathfindingCursor]; Bot* const bot = info->m_bot; if (bot && !bot->isDead() && !bot->isDeactivated() && bot->getSquadMember() && info->m_bot->getBotNavigation()->isSearchActive() @@ -463,7 +496,7 @@ void BotManager::actionPathfinding(const double& slice) for (unsigned int i = 0; i < size; ++i) { - BotInfo* const info = m_botInfos[i]; + BotInfo* const info = m_bots[i]; Bot* const bot = info->m_bot; if (bot && !bot->isDead() && !bot->isDeactivated() && bot->getSquadMember() && info->m_bot->getBotNavigation()->isSearchActive() @@ -475,8 +508,17 @@ void BotManager::actionPathfinding(const double& slice) } } -// Scans occupied world objects for hearing within the supplied slice. -// [FRONTIER] The object-query path remains incomplete. +// ELF 0x3DE440. Scans the occupied world objects round-robin from the last resume id. A sided +// object with an armament or a mobile plug-in gets a sound radius: the mobile's +// getSoundSphereRadius (IAIObjectMobile +0x40), or the last fired weapon's (IWeapon +0x10C) +// when that fired within 3.0f seconds (ELF 0x49CC90) and is larger. Without a mobile plug-in the +// ELF keeps the radius at its 0.0f start, so a weapon alone is never heard. A radius above 0.1f +// (ELF 0x49CC80) is heard by every live, standing enemy bot within it (squared distance against +// the float-rounded squared radius), through Bot +0x178 event_heardObject with the object's +// information for the bot's side (IAIObject +0xB4 forceGetInformation(side, false)). The slice +// deadline is tested only after such a pass. +// [PLATFORM] The ELF keeps the time difference and the distance sum in x87 extended precision; +// both are double here. void BotManager::actionHearing(const double& slice) { const double deadline = @@ -499,19 +541,54 @@ void BotManager::actionHearing(const double& slice) if (++next == m_occupiedObjects.end()) next = m_occupiedObjects.begin(); ++visited; - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - // The body's first call is `object->getSide` (IAIObject ELF +0x12C / PE +0x128), and - // IAIObject has no declaration in this tree; see the outline above. - (void)object; - (void)gameTime; - (void)deadline; - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::actionHearing (IAIObject hearing query)"); + if (!object->getSide()) + continue; + IAIObjectArmament* const armament = object->getArmament(); + IAIObjectMobile* const mobile = object->getMobile(); + if (!armament && !mobile) + continue; + + float weaponRadius = 0.0f; + float radius = 0.0f; + if (armament) + { + IWeapon* const weapon = armament->getLastFiredWeapon(); + if (weapon && 3.0f > gameTime - weapon->getTimeOfFiring()) + weaponRadius = weapon->getSoundSphereRadius(); + } + if (mobile) + { + const float mobileRadius = mobile->getSoundSphereRadius(); + radius = weaponRadius > mobileRadius ? weaponRadius : mobileRadius; + } + if (radius <= 0.1f) + continue; + + const float radiusSquared = radius * radius; + const int side = object->getSide(); + const Vec3& position = object->getPosition(); + for (std::vector >::iterator it = m_occupiedObjects.begin(); + it != m_occupiedObjects.end(); ++it) + { + Bot* const bot = getBot(it->second); + if (!bot || bot->isDead() || bot->getManDown() || bot->getSide() == side) + continue; + const Vec3& other = it->second->getPosition(); + const double dx = static_cast(position.x) - other.x; + const double dy = static_cast(position.y) - other.y; + const double dz = static_cast(position.z) - other.z; + if (!((dx * dx + dy * dy) + dz * dz > radiusSquared)) + bot->event_heardObject(object->forceGetInformation(bot->getSide(), false)); + } + if (static_cast(CommonSingletonServer::m_iBFTimer)->getUpdateTime() > deadline) + break; } if (count > 0) m_hearingResumeId = next->first; } // Processes at most two sensing updates per tick using the full-detail update rate. +// ELF 0x3DF180 void BotManager::actionSensing(const double& slice) { const double deadline = @@ -521,10 +598,10 @@ void BotManager::actionSensing(const double& slice) unsigned int medium = 0; unsigned int light = 0; unsigned int taken = 0; - while (!m_queueSensing->empty() && taken <= 1) + while (!m_sensingQueue->empty() && taken <= 1) { - BotInfo* info = m_queueSensing->top(); - m_queueSensing->pop(); + BotInfo* info = m_sensingQueue->top(); + m_sensingQueue->pop(); Bot* const bot = info->m_bot; if (!informationManager->getInformation(info->m_bot->getCurrentEquipment())) continue; @@ -587,9 +664,9 @@ void BotManager::actionSensing(const double& slice) // [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding BotManager operation. BotManager::BotManager() // The IBotManager and IBotManagerModifier bases construct their own interface subobjects. - : m_queuePriorityA(new BotQueue) - , m_queuePriorityB(new BotQueue) - , m_queueSensing(new SensingQueue) + : m_planned(new BotQueue) + , m_unplanned(new BotQueue) + , m_sensingQueue(new SensingQueue) , m_comAgentCursor(0) // cached, not looked UP later. Every later use of the AI main goes through this copy, so a // BotManager built before an AIMain exists caches a null and never notices. @@ -640,7 +717,7 @@ BotManager::BotManager() IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); if (settings->getMaxNBots() != -1) { - m_botInfos.reserve(settings->getMaxNBots()); + m_bots.reserve(settings->getMaxNBots()); // Re-queries the maximum bot count on every iteration, independently of the reserve call. for (int i = 0; i < settings->getMaxNBots(); ++i) @@ -663,7 +740,7 @@ BotManager::BotManager() new BotMain(0, static_cast(i), 0, 1.0f, 1, 0, memory, 0, 0, merger, generators)); - m_bots.insert(m_bots.end(), bot); + m_preallocatedBots.insert(m_preallocatedBots.end(), bot); } } @@ -673,6 +750,7 @@ BotManager::BotManager() // These configuration methods remain virtual through IBotManagerModifier. +// ELF 0x3DAD20 void BotManager::setLodLevelTicks(unsigned full, unsigned medium, unsigned light) { m_lodLevelFullTicks = full; @@ -680,6 +758,7 @@ void BotManager::setLodLevelTicks(unsigned full, unsigned medium, unsigned light m_lodLevelLightTicks = light; } +// ELF 0x3DAD50 void BotManager::setLodLevelPriority(unsigned full, unsigned medium, unsigned light) { m_lodLevelFullPriority = full; @@ -709,6 +788,7 @@ void BotManager::setUnplannedDecisionMakingThreshold(const double& full, m_unplannedDecisionMakingThresholdLight = light < 0.0 ? -light : light; } +// ELF 0x3DAE30 void BotManager::setDecisionMakingInterleave(unsigned planned, unsigned unplanned) { m_plannedDecisionMakingInterleave = planned; @@ -717,6 +797,7 @@ void BotManager::setDecisionMakingInterleave(unsigned planned, unsigned unplanne // Normalizes two integer weights into complementary shares. Leaves both unchanged // when their unsigned sum is zero. +// ELF 0x3DAE50 void BotManager::setSensingQuotient(unsigned a, unsigned b) { if (a + b) @@ -729,6 +810,7 @@ void BotManager::setSensingQuotient(unsigned a, unsigned b) // Normalizes three weights but stores only the first two fractions. // Leaves existing shares unchanged when the unsigned total is zero. +// ELF 0x3DAEB0 void BotManager::setSystemQuotient(unsigned a, unsigned b, unsigned c) { const unsigned total = a + b + c; @@ -739,52 +821,53 @@ void BotManager::setSystemQuotient(unsigned a, unsigned b, unsigned c) } } -// [FRONTIER] Active-bot counting requires the remaining state predicates. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding BotManager operation. - -// [FRONTIER] Bot-manager destruction remains unimplemented. -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -// Replace the stop when owned bot and scheduler teardown is recovered. +// ELF 0x3DA7A0 (D1; recovered on the client track): reset, then the +// three scheduling queues are deleted (reset has already replaced A and B with fresh ones). The +// containers and both interface bases follow as members. BotManager::~BotManager() { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::~BotManager"); + reset(); + delete m_planned; + delete m_unplanned; + delete m_sensingQueue; } -// [FRONTIER] Remaining bot-manager virtual operations stop visibly when reached. -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -// Replace each stop when its corresponding behavior is recovered. - // - the vector's byte span shifted right by two, i.e. its element count. // It counts admitted records, including deactivated bots. The constructor only reserves capacity; // addUnspawnedBot appends a record after consuming or allocating a BotMain. +// ELF 0x3DB060 int BotManager::getBotCount() const { - return static_cast(m_botInfos.size()); + return static_cast(m_bots.size()); } // Reports the bot counts from the managed roster. +// ELF 0x3DB080 int BotManager::getNumberOfActiveBots() const { - return static_cast(m_botInfos.size()) - static_cast(m_deactivatedBots.size()); + return static_cast(m_bots.size()) - static_cast(m_deactivatedBots.size()); } +// ELF 0x3DB0D0 int BotManager::getNumberOfDeactivedBots() const { return static_cast(m_deactivatedBots.size()); } // Returns the bot at index. The caller must supply a valid index and a live record. +// ELF 0x3DB100 Bot* BotManager::getBot(unsigned int index) const { - return m_botInfos[index]->m_bot; + return m_bots[index]->m_bot; } // Bot-ID lookup checks bounds; player lookup requires a valid association. +// ELF 0x3DB1A0 Bot* BotManager::getBotFromId(unsigned int id) const { - if (id < m_botInfos.size()) + if (id < m_bots.size()) { - BotInfo* const info = m_botInfos[id]; + BotInfo* const info = m_bots[id]; if (info) return info->m_bot; @@ -794,6 +877,7 @@ Bot* BotManager::getBotFromId(unsigned int id) const } // no bounds check on `playerId` - see the block above. +// ELF 0x3E0A80 Bot* BotManager::getBotFromPlayerId(int playerId) const { if (m_botByPlayerId[playerId] == -1) @@ -803,9 +887,15 @@ Bot* BotManager::getBotFromPlayerId(int playerId) const return getBotFromId(static_cast(m_botByPlayerId[playerId])); } -Bot* BotManager::getBotFromName(const std::string&) const +// ELF 0x3DB1D0: the first record whose player's name (IAIPlayer +0x18) equals the argument. +Bot* BotManager::getBotFromName(const std::string& name) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getBotFromName"); + for (std::vector::const_iterator it = m_bots.begin(); it != m_bots.end(); ++it) + { + if ((*it)->m_bot->getPlayer()->getName() == name) + return (*it)->m_bot; + } + return 0; } // BotManager::BotInfo - inlined in ELF addUnspawnedBot at ; @@ -820,7 +910,89 @@ BotManager::BotInfo::BotInfo(Bot* bot) { } +// ELF 0x3DB2E0 +bool exitAddBot(int playerId) +{ + static_cast(CommonSingletonServer::m_iaiGameEffector)->terminatePlayer(playerId); + return false; +} + +// ELF 0x3DB320 +bool BotManager::addBot(int playerId, int side, float* personality, IAIObject* object) +{ + const std::size_t rosterSize = m_bots.size(); + if (rosterSize >= static_cast( + static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots())) + return exitAddBot(playerId); + if (m_botByPlayerId[playerId] != -1) + return exitAddBot(playerId); + + m_lastCreatedBot = 0; + IAIPlayer* const player = static_cast(CommonSingletonServer::m_iaiPlayerFactory) + ->getPlayerFromId(playerId); + IAIGameEffector* const effector = static_cast(CommonSingletonServer::m_iaiGameEffector); + if (object) + { + IAIObject* const currentVehicle = player->getCurrentVehicle(); + if (currentVehicle != player->getDefaultVehicle()) + effector->exitVehicle(player); + if (!object->isUnit()) + return exitAddBot(playerId); + effector->enterVehicle(player, object); + } + IAIObject* const vehicle = player->getCurrentVehicle(); + if (!vehicle) + return exitAddBot(playerId); + vehicle->setSide(side); + + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getNumberOfBehaviours(); + BotMain* bot; + if (m_preallocatedBots.empty()) + { + UrgencyGenerator** const generators = checkPointer(new UrgencyGenerator*[count]); + UrgencyMerger* const merger = checkPointer(new UrgencyMerger(count, personality, generators)); + float* const weights = checkPointer(new float[count]); + for (int i = 0; i < count; ++i) + weights[i] = 1.0f; + BotOrder* const order = checkPointer(new BotOrder(weights, static_cast( + BotBehaviourManager::m_instance->getBehaviourId("Idle")))); + player->setViewDistance(static_cast(CommonSingletonServer::m_iaiSettings)->getViewDistance()); + bot = checkPointer(new BotMain(player, static_cast(m_bots.size()), + personality, 1.0f, 1, order, new BotMemory(), 0, side, merger, generators)); + } + else + { + bot = static_cast(m_preallocatedBots.front()); + bot->setPlayer(player); + bot->m_basicWeights = personality; + bot->setSide(side); + float* const weights = checkPointer(new float[count]); + for (int i = 0; i < count; ++i) + weights[i] = 1.0f; + BotOrder* const order = checkPointer(new BotOrder(weights, static_cast( + BotBehaviourManager::m_instance->getBehaviourId("Idle")))); + bot->recieveOrder(order); + m_preallocatedBots.erase(m_preallocatedBots.begin()); + } + + bot->updateBotVehicle(0); + bot->updateBot(); + Information* const information = informationManager->getInformation(bot->getCurrentEquipment()); + if (!information) + return exitAddBot(playerId); + information->setStrength(information->getStrength() + 1.0f); + bot->setWaypoints(checkPointer(new WPEmpty(information->getPosition()))); + m_bots.push_back(checkPointer(new BotInfo(bot))); + // shipped defect: grows to playerId, then writes element playerId; the first lookup is unchecked too. + if (static_cast(m_botByPlayerId.size()) < playerId) + m_botByPlayerId.resize(playerId, -1); + m_botByPlayerId[playerId] = static_cast(bot->getBotId()); + m_lastCreatedBot = bot; + return true; +} + // Admits an unspawned player using the first available preallocated bot. +// ELF 0x3DC300 bool BotManager::addUnspawnedBot(int playerId, int side, float* personality) { m_lastCreatedBot = 0; @@ -828,7 +1000,7 @@ bool BotManager::addUnspawnedBot(int playerId, int side, float* personality) ->getNumberOfBehaviours(); BotMain* bot; - if (m_bots.empty()) + if (m_preallocatedBots.empty()) { UrgencyGenerator** const generators = checkPointer(new UrgencyGenerator*[count]); UrgencyMerger* const merger = checkPointer(new UrgencyMerger(count, personality, generators)); @@ -841,12 +1013,12 @@ bool BotManager::addUnspawnedBot(int playerId, int side, float* personality) ->getPlayerFromId(playerId); // BotMain storage is allocated before this nested BotMemory construction in both images. // Unlike the preallocation constructor, this path does not checkPointer the memory. - bot = checkPointer(new BotMain(player, static_cast(m_botInfos.size()), + bot = checkPointer(new BotMain(player, static_cast(m_bots.size()), personality, 1.0f, 1, order, new BotMemory(), 0, side, merger, generators)); } else { - bot = static_cast(m_bots.front()); + bot = static_cast(m_preallocatedBots.front()); bot->setPlayer(static_cast(CommonSingletonServer::m_iaiPlayerFactory) ->getPlayerFromId(playerId)); bot->setSide(side); @@ -858,10 +1030,10 @@ bool BotManager::addUnspawnedBot(int playerId, int side, float* personality) BotBehaviourManager::m_instance->getBehaviourId("Idle")))); bot->recieveOrder(order); // Reload begin after the virtual calls, as retail does. - m_bots.erase(m_bots.begin()); + m_preallocatedBots.erase(m_preallocatedBots.begin()); } - m_botInfos.push_back(checkPointer(new BotInfo(bot))); + m_bots.push_back(checkPointer(new BotInfo(bot))); if (static_cast(m_botByPlayerId.size()) < playerId) m_botByPlayerId.resize(playerId, -1); m_botByPlayerId[playerId] = static_cast(bot->getBotId()); @@ -869,7 +1041,67 @@ bool BotManager::addUnspawnedBot(int playerId, int side, float* personality) return true; } +// ELF 0x3DD240. Picks the first dead bot of the side, else the first bot of the side; with none +// the index stays 0 (the ELF's initial value) and record 0 is deactivated. Its name returns to +// the pool (IAISettingsModifier +0x94 setBotNameUnused), its id is queued first in the +// deactivated list, its player slot cleared, its player detached (IAIPlayer +0x14 setPlayer(0)) +// and the bot marked deactivated. Both list inserts are at end() (the list header itself). +int BotManager::deactivateBot(int side) +{ + unsigned int index = 0; + bool found = false; + for (unsigned int i = 0; i < m_bots.size(); ++i) + { + Bot* const bot = m_bots[i]->m_bot; + if (bot && bot->getSide() == side && bot->isDead()) + { + index = i; + found = true; + break; + } + } + if (!found) + { + for (unsigned int i = 0; i < m_bots.size(); ++i) + { + Bot* const bot = m_bots[i]->m_bot; + if (bot && bot->getSide() == side) + { + index = i; + break; + } + } + } + static_cast(CommonSingletonServer::m_iaiSettingsModifier) + ->setBotNameUnused(m_bots[index]->m_bot->getPlayer()->getName()); + m_deactivatedBots.push_back(index); + m_botByPlayerId[m_bots[index]->m_bot->getPlayerId()] = -1; + m_bots[index]->m_bot->getPlayer()->setPlayer(static_cast(0)); + m_bots[index]->m_bot->setAsDeactivated(true); + return static_cast(index); +} + +// ELF 0x3DD450. The name goes back to the pool before the test; only a dead bot is then +// deactivated (a live one answers -1). +int BotManager::deactivateBotFromPlayerId(int playerId) +{ + Bot* const bot = getBotFromPlayerId(playerId); + if (!bot) + return -1; + static_cast(CommonSingletonServer::m_iaiSettingsModifier) + ->setBotNameUnused(bot->getPlayer()->getName()); + const unsigned int botId = bot->getBotId(); + if (!bot->isDead()) + return -1; + m_deactivatedBots.push_back(botId); + bot->setAsDeactivated(true); + bot->getPlayer()->setPlayer(static_cast(0)); + m_botByPlayerId[playerId] = -1; + return static_cast(botId); +} + // Reactivates a retired bot for a player and restores it to the active roster. +// ELF 0x3DD040 bool BotManager::reactivateBot(int playerId, int side, const std::string& name) { if (m_deactivatedBots.empty()) @@ -882,7 +1114,7 @@ bool BotManager::reactivateBot(int playerId, int side, const std::string& name) const std::list::iterator oldest = m_deactivatedBots.begin(); const unsigned int botId = *oldest; - Bot* const bot = m_botInfos[botId]->m_bot; + Bot* const bot = m_bots[botId]->m_bot; bot->getPlayer()->setPlayer(playerId); bot->setSide(side); @@ -902,300 +1134,578 @@ bool BotManager::reactivateBot(int playerId, int side, const std::string& name) return true; } -Bot* BotManager::getBot(IAIObject*) const +// ELF 0x3DB120: the object map's bot id, then that record's bot (a null record answers null). +Bot* BotManager::getBot(IAIObject* object) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getBot"); + const std::map::const_iterator it = m_vehicleBots.find(object); + if (it == m_vehicleBots.end()) + return 0; + BotInfo* const info = m_bots[it->second]; + return info ? info->m_bot : 0; } +// ELF 0x3E0C90 Bot* BotManager::getLastCreatedBot() const { // return [this+228]. PE uses the corresponding member at +276. return m_lastCreatedBot; } -void BotManager::updateBotVehicle(Bot*, IAIObject*) +// ELF 0x3E0100: drops the first map entry that carries this bot's id, then maps the object to +// it (insert_unique: an object already mapped keeps its old bot). +void BotManager::updateBotVehicle(Bot* bot, IAIObject* vehicle) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::updateBotVehicle"); -} - -void BotManager::setBotChangedVehicle(int, IAIObject*) -{ - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::setBotChangedVehicle"); -} - -void BotManager::setBotIsDead(int) -{ - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::setBotIsDead"); + const unsigned int botId = bot->getBotId(); + for (std::map::iterator it = m_vehicleBots.begin(); it != m_vehicleBots.end(); ++it) + { + if (it->second == botId) + { + m_vehicleBots.erase(it); + break; + } + } + m_vehicleBots.insert(std::pair(vehicle, botId)); } -void BotManager::setBotIsAlive(int) +// ELF 0x3E0210. A physical vehicle first gets IAIObjectPhysical +0x74 enablePhysics(its own +// side) - the plug-in is fetched before the side. A bot outside its transition phase and alive +// then refreshes its vehicle (+0x2C, null out-flag) and itself (+0x30), drops its plan (+0x5C), +// and, with the SAI enabled, reports the equipment change to its side's SAI (+0x40, bot id +// read before the side). +void BotManager::setBotChangedVehicle(int playerId, IAIObject* vehicle) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::setBotIsAlive"); + Bot* const bot = getBotFromPlayerId(playerId); + if (!bot) + return; + if (vehicle && vehicle->isPhysical()) + { + IAIObjectPhysical* const physical = vehicle->getPhysical(); + physical->enablePhysics(vehicle->getSide()); + } + if (bot->isInTransitionPhase()) + return; + if (bot->isDead()) + return; + bot->updateBotVehicle(0); + bot->updateBot(); + bot->invalidatePlan(); + if (m_aiMain->getSAIEnable()) + { + const unsigned int botId = bot->getBotId(); + m_aiMain->getSAI(bot->getSide())->setBotHasChangedEquipment(botId); + } } -void BotManager::setBotIsManDown(int, IAIObject*) +// ELF 0x3E0340. The first object-map entry whose bot id equals the player id is dropped (the +// ELF compares the mapped bot id with the player id). The bot leaves man-down, enters its +// transition phase, resets navigation and its assigned areas (BotMain +0x214, past the Bot +// interface), its record's +4 word becomes 1 and the bot resets; equipment is cleared (-1), +// placed C4 removed, and the death callback (+0x11C) reports. +// The side's SAI is fetched (IAIMain +0x3C) and not used, as in the ELF. +void BotManager::setBotIsDead(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::setBotIsManDown"); + Bot* const bot = getBotFromPlayerId(playerId); + if (!bot) + return; + for (std::map::iterator it = m_vehicleBots.begin(); it != m_vehicleBots.end(); ++it) + { + if (it->second == static_cast(playerId)) + { + m_vehicleBots.erase(it); + break; + } + } + bot->setManDown(false); + bot->setIsInTransitionPhase(true); + bot->getBotNavigation()->resetAll(); + static_cast(bot)->resetAssignedAreas(); + BotInfo* const info = m_bots[bot->getBotId()]; + IAIMain::m_instance->getSAI(info->m_bot->getSide()); + info->m_word4 = 1; + info->m_bot->reset(); + bot->setCurrentEquipment(static_cast(-1)); + if (bot->isC4Placed()) + bot->removeC4(); + IBotDeathCallBack* const callBack = bot->getDeathCallBack(); + if (callBack) + callBack->reportDeath(); +} + +// ELF 0x3E0510. Only a bot in its transition phase: the phase ends, vehicle and bot refresh, +// the last change time becomes -1000000.0 (float constant, ELF 0x49CDA4), the record's +// priorities, +0x18 double and +0x14 flag clear, the spawn coordinate is taken from the +// bot's information (Information +0x30 getPosition) and the spawn callback reports. +void BotManager::setBotIsAlive(int playerId) +{ + Bot* const bot = getBotFromPlayerId(playerId); + if (!bot || !bot->isInTransitionPhase()) + return; + bot->setIsInTransitionPhase(false); + bot->updateBotVehicle(0); + bot->updateBot(); + bot->setLastChangeTime(-1000000.0f); + BotInfo* const info = m_bots[bot->getBotId()]; + info->m_priority = 0; + info->m_double24 = 0.0f; + info->m_word4 = 0; + info->m_flag20 = false; + Information* const information = informationManager->getInformation(bot->getCurrentEquipment()); + if (information) + static_cast(bot)->setSpawnCoord(information->getPosition()); + IBotSpawnCallBack* const callBack = bot->getSpawnCallBack(); + if (callBack) + callBack->reportSpawn(); +} + +// ELF 0x3E0640: the object is not read. +void BotManager::setBotIsManDown(int playerId, IAIObject*) +{ + Bot* const bot = getBotFromPlayerId(playerId); + if (!bot) + return; + bot->setManDown(true); + bot->updateBot(); + bot->updateBotVehicle(0); + bot->invalidatePlan(); + bot->getBotNavigation()->resetAll(); } -void BotManager::setBotIsRevived(int, IAIObject*) +// ELF 0x3E06C0. The revived bot leaves man-down, refreshes, resets navigation (reset, not +// resetAll), drops its plan, queues radio message 8 on channel 6 (args 2, 1.0f - ELF +// 0x49CB2C - and -1), and with the SAI enabled reports an equipment change (bot id first). +void BotManager::setBotIsRevived(int playerId, IAIObject*) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::setBotIsRevived"); + Bot* const bot = getBotFromPlayerId(playerId); + if (!bot) + return; + bot->setManDown(false); + bot->updateBot(); + bot->getBotNavigation()->reset(); + bot->invalidatePlan(); + bot->getCommunicationAgent()->enqueueRadioMessage(static_cast(8), + static_cast(6), 2u, 1.0f, -1); + if (m_aiMain->getSAIEnable()) + { + const unsigned int botId = bot->getBotId(); + m_aiMain->getSAI(bot->getSide())->setBotHasChangedEquipment(botId); + } } -void BotManager::setBotReceivedRadioMessage(const AIRadioMessageSettings&, int, int) +// ELF 0x3E07C0: the third argument names the receiving player. +void BotManager::setBotReceivedRadioMessage(const AIRadioMessageSettings& settings, int a, int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::setBotReceivedRadioMessage"); + Bot* const bot = getBotFromPlayerId(playerId); + if (!bot) + return; + bot->getCommunicationAgent()->receiveRadioMessage(settings, a, false); // ELF 0x3E080E } -void BotManager::setBotRecievedAttackCommanderOrder(int) +// ELF 0x3E0820: the bot's squad (+0x34 getBotSquad) receives the order. +void BotManager::setBotRecievedAttackCommanderOrder(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::setBotRecievedAttackCommanderOrder"); + Bot* const bot = getBotFromPlayerId(playerId); + if (bot) + bot->getBotSquad()->recieveAttackCommanderOrder(); } -void BotManager::setBotRecievedDefendCommanderOrder(int) +// ELF 0x3E0870: the bot's squad (+0x34 getBotSquad) receives the order. +void BotManager::setBotRecievedDefendCommanderOrder(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::setBotRecievedDefendCommanderOrder"); + Bot* const bot = getBotFromPlayerId(playerId); + if (bot) + bot->getBotSquad()->recieveDefendCommanderOrder(); } -void BotManager::setBotRecievedMoveCommanderOrder(int) +// ELF 0x3E08C0: the bot's squad (+0x34 getBotSquad) receives the order. +void BotManager::setBotRecievedMoveCommanderOrder(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::setBotRecievedMoveCommanderOrder"); + Bot* const bot = getBotFromPlayerId(playerId); + if (bot) + bot->getBotSquad()->recieveMoveCommanderOrder(); } -void BotManager::setBotRecievedAttackSquadOrder(int) +// ELF 0x3E0910: the bot's squad (+0x34 getBotSquad) receives the order. +void BotManager::setBotRecievedAttackSquadOrder(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::setBotRecievedAttackSquadOrder"); + Bot* const bot = getBotFromPlayerId(playerId); + if (bot) + bot->getBotSquad()->recieveAttackSquadOrder(); } -void BotManager::setBotRecievedDefendSquadOrder(int) +// ELF 0x3E0960: the bot's squad (+0x34 getBotSquad) receives the order. +void BotManager::setBotRecievedDefendSquadOrder(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::setBotRecievedDefendSquadOrder"); + Bot* const bot = getBotFromPlayerId(playerId); + if (bot) + bot->getBotSquad()->recieveDefendSquadOrder(); } -void BotManager::setBotRecievedMoveSquadOrder(int) +// ELF 0x3E09B0: the bot's squad (+0x34 getBotSquad) receives the order. +void BotManager::setBotRecievedMoveSquadOrder(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::setBotRecievedMoveSquadOrder"); + Bot* const bot = getBotFromPlayerId(playerId); + if (bot) + bot->getBotSquad()->recieveMoveSquadOrder(); } -void BotManager::setBotTeamKilled(int, int) +// ELF 0x3E0A00: the second argument is not read. +void BotManager::setBotTeamKilled(int playerId, int) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::setBotTeamKilled"); + Bot* const bot = getBotFromPlayerId(playerId); + if (!bot) + return; + bot->getCommunicationAgent()->enqueueRadioMessage(static_cast(9), + static_cast(6), 3u, 0.0f, -1); } -void BotManager::registerDamageOnBot(float, int, int) +// ELF 0x3E0AC0: unchecked index; updateDamages applies and clears the sum each tick. +void BotManager::registerDamageOnBot(float damage, int botIndex, int attackerIndex) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::registerDamageOnBot"); + m_bots[botIndex]->m_damage += damage; + m_bots[botIndex]->m_attackerIndex = attackerIndex; } +// ELF 0x3DAD10: `flds 0xE8(this)`. float BotManager::getVehicleBailValue() { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getVehicleBailValue"); + return m_float232; } -void BotManager::removeMineTarget(unsigned int) +// ELF 0x3DB280: every bot targeting the mine (BotMain +0x1FC) gets target -1 (+0x1F8). +void BotManager::removeMineTarget(unsigned int handle) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::removeMineTarget"); + for (std::vector::iterator it = m_bots.begin(); it != m_bots.end(); ++it) + { + BotMain* const bot = static_cast((*it)->m_bot); + if (bot->getMineTarget() == handle) + bot->setMineTarget(static_cast(-1)); + } } +// ELF 0x3DFCE0 (1056 B; recovered on the client track). Clears the +// plan cursor, deletes every bot record (its bot through the virtual deleting destructor, +4, +// then the record) and empties the record vector and the bot list; frees the two priority +// queues and empties the +56 list; re-applies the construction-time scheduling defaults through +// the virtual setters (+0x8C..+0xA4); allocates two empty priority queues; clears +188. +// The sensing queue is left alone. Returns 1. bool BotManager::reset() { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::reset"); + m_planCursor = 0; // +0x104 + for (std::vector::iterator info = m_bots.begin(); info != m_bots.end(); ++info) + { + if (*info) + { + if ((*info)->m_bot) + delete (*info)->m_bot; // virtual, slot +4 + delete *info; + } + } + m_bots.resize(0, 0); + m_preallocatedBots.resize(0, 0); + delete m_planned; + delete m_unplanned; + m_list56.clear(); // +0x38 + setLodLevelTicks(3, 2, 1); // +0x8C + setLodLevelPriority(3, 2, 1); // +0x90 + setPlannedDecisionMakingThreshold(0.5, 1.0, 3.0); // +0x94 + setUnplannedDecisionMakingThreshold(0.3, 0.8, 2.0); // +0x98 + setDecisionMakingInterleave(2, 2); // +0x9C + setSensingQuotient(1, 1); // +0xA0 + setSystemQuotient(30, 40, 30); // +0xA4 + m_planned = new BotQueue; + m_unplanned = new BotQueue; + m_hearingResumeId = 0; // +0xBC + return true; } -void BotManager::setRenderBotSensing(bool) +// ELF 0x3E2CC0 (weak): `movb %dl, 0xEC(this)`. +void BotManager::setRenderBotSensing(bool render) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::setRenderBotSensing"); + m_flag236 = render; } +// ELF 0x3E2CE0 (weak): `movzbl 0xEC(this)`. bool BotManager::getRenderBotSensing() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getRenderBotSensing"); + return m_flag236; } +// ELF 0x3E0CA0 void BotManager::writeBotPlans() { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::writeBotPlans"); + s_tabLevel = 0; + const std::string levelPath = static_cast(CommonSingletonServer::m_iaiGame)->getLevelPath(); + io::IStream* file = io::fileManager->open(levelPath + "../../../AI/BotPlans.cpp", + static_cast(0), static_cast(2), 0); + for (std::vector::iterator it = m_bots.begin(); it != m_bots.end(); ++it) + { + Bot* const bot = (*it)->m_bot; + if (bot->isDead()) + continue; + BotScript* const plan = bot->getPlan(); + if (!file) + continue; + Information* const information = informationManager->getInformation(bot->getCurrentEquipment()); + std::ostringstream out; + out << "/*******************************************************/" << std::endl; + const std::string& name = bot->getPlayer()->getName(); + out << "/* Name: " << name << std::endl; + // shipped defect: a missing information record is dereferenced, and a null plan is not checked. + const std::string& equipment = information->getAIObject()->getObject()->getTemplate()->getName(); + out << "/* Equipment: " << equipment << " Pos: "; + const Vec3& position = information->getPosition(); + out << position.x << '/'; + out << position.y << '/'; + out << position.z << " */" << std::endl; + out << "/*******************************************************/" << std::endl; + out << *static_cast(plan) << std::endl; + const std::string lengthSource = out.str(); + const std::string text = out.str(); + file->write(text.c_str(), static_cast(lengthSource.size())); + } + if (file) + file->release(); } +// ELF 0x3E2CF0 / 0x3E2D10 (weak): `incl` / `decl` of the class static. void BotManager::increaseTabLevel() { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::increaseTabLevel"); + ++s_tabLevel; } +// ELF 0x3E2D10 void BotManager::decreaseTabLevel() { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::decreaseTabLevel"); + --s_tabLevel; } -void BotManager::tabulate(std::ostream&) +// ELF 0x3E1410 +void BotManager::tabulate(std::ostream& out) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::tabulate"); + for (int i = 0; i < s_tabLevel; ++i) + out << '\t'; } +// ELF 0x3DAF10: `movl 0x84(this)`. unsigned BotManager::getLodLevelFullTicks() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getLodLevelFullTicks"); + return m_lodLevelFullTicks; } +// ELF 0x3DAF20: `movl 0x88(this)`. unsigned BotManager::getLodLevelMediumTicks() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getLodLevelMediumTicks"); + return m_lodLevelMediumTicks; } +// ELF 0x3DAF30: `movl 0x8C(this)`. unsigned BotManager::getLodLevelLightTicks() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getLodLevelLightTicks"); + return m_lodLevelLightTicks; } +// ELF 0x3DAF40: `movl 0x40(this)`. unsigned BotManager::getLodLevelFullPriority() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getLodLevelFullPriority"); + return m_lodLevelFullPriority; } +// ELF 0x3DAF50: `movl 0x44(this)`. unsigned BotManager::getLodLevelMediumPriority() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getLodLevelMediumPriority"); + return m_lodLevelMediumPriority; } +// ELF 0x3DAF60: `movl 0x48(this)`. unsigned BotManager::getLodLevelLightPriority() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getLodLevelLightPriority"); + return m_lodLevelLightPriority; } +// ELF 0x3DAF70: `fldl 0x54(this)`. double BotManager::getPlannedDecisionMakingThresholdFull() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getPlannedDecisionMakingThresholdFull"); + return m_plannedDecisionMakingThresholdFull; } +// ELF 0x3DAF80: `fldl 0x5C(this)`. double BotManager::getPlannedDecisionMakingThresholdMedium() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getPlannedDecisionMakingThresholdMedium"); + return m_plannedDecisionMakingThresholdMedium; } +// ELF 0x3DAF90: `fldl 0x64(this)`. double BotManager::getPlannedDecisionMakingThresholdLight() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getPlannedDecisionMakingThresholdLight"); + return m_plannedDecisionMakingThresholdLight; } +// ELF 0x3DAFA0: `fldl 0x6C(this)`. double BotManager::getUnplannedDecisionMakingThresholdFull() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getUnplannedDecisionMakingThresholdFull"); + return m_unplannedDecisionMakingThresholdFull; } +// ELF 0x3DAFB0: `fldl 0x74(this)`. double BotManager::getUnplannedDecisionMakingThresholdMedium() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getUnplannedDecisionMakingThresholdMedium"); + return m_unplannedDecisionMakingThresholdMedium; } +// ELF 0x3DAFC0: `fldl 0x7C(this)`. double BotManager::getUnplannedDecisionMakingThresholdLight() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getUnplannedDecisionMakingThresholdLight"); + return m_unplannedDecisionMakingThresholdLight; } +// ELF 0x3DAFD0: `movl 0x4C(this)`. unsigned BotManager::getPlannedDecisionMakingInterleave() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getPlannedDecisionMakingInterleave"); + return m_plannedDecisionMakingInterleave; } +// ELF 0x3DAFE0: `movl 0x50(this)`. unsigned BotManager::getUnplannedDecisionMakingInterleave() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getUnplannedDecisionMakingInterleave"); + return m_unplannedDecisionMakingInterleave; } +// ELF 0x3DAFF0: `fldl 0xA0(this)`. double BotManager::getSensingQuotient() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getSensingQuotient"); + return m_sensingQuotient; } +// ELF 0x3DB000: `fldl 0xA8(this) - the sensing split's second share`. double BotManager::getMemoryUpdateQuotient() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getMemoryUpdateQuotient"); + return m_sensingQuotientInverse; } +// ELF 0x3DB010: `fldl 0x90(this)`. double BotManager::getSystemDecisionMakingQuotient() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getSystemDecisionMakingQuotient"); + return m_systemDecisionMakingQuotient; } +// ELF 0x3DB020: `fldl 0x98(this) - setSystemQuotient's second share`. double BotManager::getSystemPathfindingQuotient() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getSystemPathfindingQuotient"); + return m_systemQuotient2; } +// ELF 0x3DB030: the third share setSystemQuotient does not store, `1.0f - [0x98] - [0x90]` +// (1.0f at ELF 0x49CB2C, evaluated left to right in x87). double BotManager::getSystemSensingQuotient() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getSystemSensingQuotient"); + return (1.0f - m_systemQuotient2) - m_systemDecisionMakingQuotient; } +// ELF 0x3DFA80: every record's four counters (+0x20..+0x2C) and three run times (+0x30..+0x40). void BotManager::resetStatistics() { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::resetStatistics"); + for (std::vector::iterator it = m_bots.begin(); it != m_bots.end(); ++it) + { + BotInfo* const info = *it; + info->m_behaviourUpdateCount = 0; + info->m_word36 = 0; + info->m_word40 = 0; + info->m_word44 = 0; + info->m_double48 = 0.0f; + info->m_double56 = 0.0f; + info->m_double64 = 0.0f; + } +} + +// ELF 0x3DFAF0: the same for one unchecked index (the records are reached through pointers). +void BotManager::resetStatistics(unsigned int botIndex) const +{ + BotInfo* const info = m_bots[botIndex]; + info->m_behaviourUpdateCount = 0; + info->m_word36 = 0; + info->m_word40 = 0; + info->m_word44 = 0; + info->m_double48 = 0.0f; + info->m_double56 = 0.0f; + info->m_double64 = 0.0f; } -void BotManager::resetStatistics(unsigned int) const +// ELF 0x3DFB50 (+0x24), unchecked index. +unsigned BotManager::getPlanExecutionUpdateCount(unsigned int botIndex) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::resetStatistics"); + return m_bots[botIndex]->m_word36; } -unsigned BotManager::getPlanExecutionUpdateCount(unsigned int) const +// ELF 0x3DFB70 (+0x28), unchecked index. +unsigned BotManager::getDecisionMakingUpdateCount(unsigned int botIndex) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getPlanExecutionUpdateCount"); + return m_bots[botIndex]->m_word40; } -unsigned BotManager::getDecisionMakingUpdateCount(unsigned int) const +// ELF 0x3DFB90 (+0x2C), unchecked index. +unsigned BotManager::getSensingUpdateCount(unsigned int botIndex) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getDecisionMakingUpdateCount"); + return m_bots[botIndex]->m_word44; } -unsigned BotManager::getSensingUpdateCount(unsigned int) const +// ELF 0x3DFCC0 (+0x20), unchecked index. +unsigned BotManager::getDecisionMakingBehaviourUpdateCount(unsigned int botIndex) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getSensingUpdateCount"); + return m_bots[botIndex]->m_behaviourUpdateCount; } -unsigned BotManager::getDecisionMakingBehaviourUpdateCount(unsigned int) const +// ELF 0x3DFBB0 (+0x30), unchecked index. +double BotManager::getPlanExecutionRunTime(unsigned int botIndex) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getDecisionMakingBehaviourUpdateCount"); + return m_bots[botIndex]->m_double48; } -double BotManager::getPlanExecutionRunTime(unsigned int) const +// ELF 0x3DFBD0 (+0x38), unchecked index. +double BotManager::getDecisionMakingRunTime(unsigned int botIndex) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getPlanExecutionRunTime"); + return m_bots[botIndex]->m_double56; } -double BotManager::getDecisionMakingRunTime(unsigned int) const +// ELF 0x3DFBF0 (+0x40), unchecked index. +double BotManager::getSensingRunTime(unsigned int botIndex) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getDecisionMakingRunTime"); + return m_bots[botIndex]->m_double64; } -double BotManager::getSensingRunTime(unsigned int) const +// ELF 0x3DFC10 (+0x14), unchecked index. +bool BotManager::isPathfinding(unsigned int botIndex) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getSensingRunTime"); + return m_bots[botIndex]->m_flag20; } -bool BotManager::isPathfinding(unsigned int) const +// ELF 0x3DFC40 (+0x48), unchecked index. +bool BotManager::getLastPathfindingSucceeded(unsigned int botIndex) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::isPathfinding"); + return m_bots[botIndex]->m_flag72; } -bool BotManager::getLastPathfindingSucceeded(unsigned int) const +// ELF 0x3DFC70 (+0x49), unchecked index. +bool BotManager::getPathfindingStall(unsigned int botIndex) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getLastPathfindingSucceeded"); + return m_bots[botIndex]->m_flag73; } -bool BotManager::getPathfindingStall(unsigned int) const +// ELF 0x3DFCA0 (+0x4C), unchecked index. +double BotManager::getLastPathfindingRunTime(unsigned int botIndex) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getPathfindingStall"); + return m_bots[botIndex]->m_double76; } -double BotManager::getLastPathfindingRunTime(unsigned int) const +// ELF 0x3E0C40 +void BotManager::enableBotScriptDebugger(bool enable) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getLastPathfindingRunTime"); + for (std::vector::iterator it = m_bots.begin(); it != m_bots.end(); ++it) + (*it)->m_bot->enableBotScriptDebugger(enable); } -void BotManager::enableBotScriptDebugger(bool) +// ELF 0x3E0AB0 +void BotManager::buildObjectMap() { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::enableBotScriptDebugger"); } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/Main/BotManager.h b/Code/BF2/AI/AIDLL/AI/Main/BotManager.h index 67d1f0a7c..3a1e73c60 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/BotManager.h +++ b/Code/BF2/AI/AIDLL/AI/Main/BotManager.h @@ -50,7 +50,7 @@ class BotManager : public IBotManager, public IBotManagerModifier { explicit BotInfo(Bot* bot); // * +0 - // one dereferences the record: `return *(Bot)m_botInfos[index];`. So the first word + // one dereferences the record: `return *(Bot)m_bots[index];`. So the first word // of a BotInfo is the bot it describes. Bot* m_bot; // +0 unsigned m_word4; // +4 = 0 [UNRESOLVED] @@ -106,7 +106,7 @@ class BotManager : public IBotManager, public IBotManagerModifier typedef BotPriorityQueue SensingQueue; BotManager(); - // Virtual destruction is inherited from both interfaces; ordered teardown remains a named stop. + // Virtual destruction is inherited from both interfaces. virtual ~BotManager(); // the tick @@ -182,42 +182,47 @@ class BotManager : public IBotManager, public IBotManagerModifier virtual double getSystemPathfindingQuotient() const; // +0x0EC virtual double getSystemSensingQuotient() const; // +0x0F0 virtual void resetStatistics(); // +0x0F4 - virtual void resetStatistics(unsigned int index) const; // +0x0F8 - virtual unsigned getPlanExecutionUpdateCount(unsigned int index) const; // +0x0FC - virtual unsigned getDecisionMakingUpdateCount(unsigned int index) const; // +0x100 - virtual unsigned getSensingUpdateCount(unsigned int index) const; // +0x104 - virtual unsigned getDecisionMakingBehaviourUpdateCount(unsigned int index) const; // +0x108 - virtual double getPlanExecutionRunTime(unsigned int index) const; // +0x10C - virtual double getDecisionMakingRunTime(unsigned int index) const; // +0x110 - virtual double getSensingRunTime(unsigned int index) const; // +0x114 - virtual bool isPathfinding(unsigned int index) const; // +0x118 - virtual bool getLastPathfindingSucceeded(unsigned int index) const; // +0x11C - virtual bool getPathfindingStall(unsigned int index) const; // +0x120 - virtual double getLastPathfindingRunTime(unsigned int index) const; // +0x124 + virtual void resetStatistics(unsigned int botIndex) const; // +0x0F8 + virtual unsigned getPlanExecutionUpdateCount(unsigned int botIndex) const; // +0x0FC + virtual unsigned getDecisionMakingUpdateCount(unsigned int botIndex) const; // +0x100 + virtual unsigned getSensingUpdateCount(unsigned int botIndex) const; // +0x104 + virtual unsigned getDecisionMakingBehaviourUpdateCount(unsigned int botIndex) const; // +0x108 + virtual double getPlanExecutionRunTime(unsigned int botIndex) const; // +0x10C + virtual double getDecisionMakingRunTime(unsigned int botIndex) const; // +0x110 + virtual double getSensingRunTime(unsigned int botIndex) const; // +0x114 + virtual bool isPathfinding(unsigned int botIndex) const; // +0x118 + virtual bool getLastPathfindingSucceeded(unsigned int botIndex) const; // +0x11C + virtual bool getPathfindingStall(unsigned int botIndex) const; // +0x120 + virtual double getLastPathfindingRunTime(unsigned int botIndex) const; // +0x124 virtual void enableBotScriptDebugger(bool enable); // +0x128 // population, and not part of either base - // These five are absent from both vtables, so they are BotManager's own non-virtual API. - void addBot(int side, int id, float* weights, IAIObject* obj); + // These methods are absent from both vtables, so they are BotManager's own non-virtual API. + bool addBot(int playerId, int side, float* weights, IAIObject* object); + void buildObjectMap(); // Adds an unspawned bot for playerId and side using personality weights; returns true. bool addUnspawnedBot(int playerId, int side, float* personality); // Returns whether the player's bot was reactivated on the requested side. bool reactivateBot(int playerId, int side, const std::string& name); - void deactivateBot(int id); - void deactivateBotFromPlayerId(int playerId); // indexes m_botByPlayerId + // Both answer the deactivated bot's id, or -1 (ELF 0x3DD240 / 0x3DD450). + int deactivateBot(int side); + int deactivateBotFromPlayerId(int playerId); // indexes m_botByPlayerId + + // ELF .bss 0x4CE8F8 (4 bytes); increaseTabLevel / decreaseTabLevel step it. [INFERRED] type int. + static int s_tabLevel; private: // Three priority queues hold pending bot work. Native container sizes depend on the compiler ABI. - /* 8 */ BotQueue* m_queuePriorityA; - /* 12 */ BotQueue* m_queuePriorityB; - /* 16 */ SensingQueue* m_queueSensing; - /* 20 */ std::list m_bots; // the ctor inserts every preallocated BotMain - /* 24 */ std::vector m_botInfos; // reserve(getMaxNBots) - // Deactivated bot ids in oldest-first order; values index m_botInfos. + /* 8 */ BotQueue* m_planned; // name: AIDLL_r assert 0x101A6170 (PE +8) + /* 12 */ BotQueue* m_unplanned; // name: AIDLL_r assert 0x101A6170 (PE +0xC) + /* 16 */ SensingQueue* m_sensingQueue; // name: AIDLL_r assert 0x101A6810 (PE +0x10) + /* 20 */ std::list m_preallocatedBots; // the ctor inserts every preallocated BotMain [INFERRED] name: AIDLL_r names the BotInfo vector m_bots (0x101A2880) + /* 24 */ std::vector m_bots; // reserve(getMaxNBots) // name: AIDLL_r asserts "botIndex < m_bots.size()" 0x101A2880.. (PE +0x20) + // Deactivated bot ids in oldest-first order; values index m_bots. /* 36 */ std::list m_deactivatedBots; // bot ids, oldest first // [CHOSEN name] Player-id to bot-index table, sized to 256 and initialized to -1. /* 40 */ std::vector m_botByPlayerId; - // actionComAgent's round-robin position in m_botInfos (ELF +0x34 / PE +0x4C); unsigned from + // actionComAgent's round-robin position in m_bots (ELF +0x34 / PE +0x4C); unsigned from // its `jb` wrap test. Name [INFERRED]. /* 52 */ unsigned int m_comAgentCursor; // = 0 /* 56 */ std::list m_list56; // allocate(12) -> a 4-byte element. [UNRESOLVED] type @@ -254,8 +259,9 @@ class BotManager : public IBotManager, public IBotManagerModifier /* 192 */ void* m_ptr192; // = 0 /* 196 */ void* m_ptr196; // = 0 /* 200 */ void* m_ptr200; // = 0 - // [UNRESOLVED] Map key and value types; the declarations preserve the observed storage width. - /* 204 */ std::map m_map204; // +204 node, +208 count, +212 comparator + // Object -> bot id, std::map by the shipped instantiations + // (ELF getBot(IAIObject*) 0x3DB120 find, updateBotVehicle 0x3E0100 insert_unique). Name [INFERRED]. + /* 204 */ std::map m_vehicleBots; // +204 node, +208 count, +212 comparator // [INFERRED] Shared scratch selection, cleared and filled from queues by decision-making // and sensing passes before they process the selected bots. /* 216 */ std::vector m_selectedBots; diff --git a/Code/BF2/AI/AIDLL/AI/Main/BotPlacementManager.cpp b/Code/BF2/AI/AIDLL/AI/Main/BotPlacementManager.cpp new file mode 100644 index 000000000..527552196 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/Main/BotPlacementManager.cpp @@ -0,0 +1,96 @@ +// Registered bot placements and the retail console spawn operation. + +// static init: ELF 0x3E4B60, __tcf_0 0x3E4BF0, _GLOBAL__I 0x3E4C20: stream Init precedes the manager. +#include + +#include "BotPlacementManager.h" + +#include + +#include "../../../../Core/Debug.h" +#include "../AIBot/BotMain.h" +#include "IBotManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// static init: ELF 0x3E4B60 (_GLOBAL__I 0x3E4C20): `operator new(8)`, the constructor, then +// the store to m_instance - the manager exists from the moment the library is loaded. BF2AI::clear +// deletes it (ELF 0x3EE1D0, the last delete there); a fresh library load makes the next one. +BotPlacementManager* BotPlacementManager::m_instance = new BotPlacementManager(); + +// ELF 0x3E2D30: constructs the two empty team lists and nothing else; it does not touch +// m_instance. +BotPlacementManager::BotPlacementManager() +{ +} + +// ELF 0x3E2EF0 (D1): clears m_instance only when it names this object, then the two lists are +// destroyed in reverse order, each destroying its placements (three strings apiece). +BotPlacementManager::~BotPlacementManager() +{ + if (m_instance == this) + m_instance = 0; +} + +// ELF 0x3E2F60 +bool BotPlacementManager::addPlacement(const std::string& name, const Vec3& position, + const Vec3& rotation, const std::string& string1C, + int team, const std::string& string20) +{ + BotPlacement placement = {}; + placement.m_name = name; + placement.m_position = position; + placement.m_rotation = rotation; + placement.m_string1C = string1C; + placement.m_string20 = string20; + m_placements[team - 1].insert(m_placements[team - 1].end(), placement); + return true; +} + +// ELF 0x3E30E0 +bool BotPlacementManager::spawnBot(int team) +{ + std::stringstream command; + std::stringstream count; + std::string name; + BotPlacement placement = {}; + + Debug(DebugTypeError, "AI/AIDLL/AI/Main/BotPlacementManager.cpp", 90, "") + << "This does not work!"; + + if (m_placements[team - 1].empty()) + return false; + + const std::list::iterator it = m_placements[team - 1].begin(); + name = "FIXME"; + command << it->m_name << " " << it->m_position << " " << it->m_rotation << " " + << it->m_string1C << " " << team << " "; + command << name << " "; + command << it->m_string20; + + std::stringstream position; + std::stringstream rotation; + std::stringstream side; + position << it->m_position; + rotation << it->m_rotation; + side << team; + placement = *it; + m_placements[team - 1].erase(m_placements[team - 1].begin()); + + count << static_cast(IBotManager::instance->getBotCount()); + Bot* const bot = IBotManager::instance->getLastCreatedBot(); + if (bot) + { + // shipped defect: none of the command streams is executed, and the placeholder name + // is applied to the already existing last-created bot. + bot->setName(name); + return true; + } + return false; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/Main/BotPlacementManager.h b/Code/BF2/AI/AIDLL/AI/Main/BotPlacementManager.h new file mode 100644 index 000000000..2381acf5f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/Main/BotPlacementManager.h @@ -0,0 +1,56 @@ +// Holds the per-team bot placements that console commands register and spawnBot consumes. +// Constructed when the DLL loads (this file's static initializer) and destroyed by BF2AI::clear. +// Source placement is attested by spawnBot's diagnostic path. + +#ifndef AI_AIDLL_AI_MAIN_BOTPLACEMENTMANAGER_H // [INFERRED] guard style +#define AI_AIDLL_AI_MAIN_BOTPLACEMENTMANAGER_H + +#include +#include + +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +// One registered placement. Retail element size is 0x24 (list node 0x2C): the list's __clear +// (0x3E4C40) destroys strings at +0x00, +0x1C and +0x20; +0x04..+0x1B hold no destructor and are +// filled from addPlacement's two Vec3 arguments. Field names [INFERRED] from addPlacement's +// parameter order (std::string const&, Vec3 const&, Vec3 const&, std::string const&, int, +// std::string const&); the int selects the team list and is not stored. +struct BotPlacement +{ + /* +0x00 */ std::string m_name; + /* +0x04 */ Vec3 m_position; + /* +0x10 */ Vec3 m_rotation; + /* +0x1C */ std::string m_string1C; // [UNRESOLVED] meaning + /* +0x20 */ std::string m_string20; // [UNRESOLVED] meaning +}; + +class BotPlacementManager +{ +public: + BotPlacementManager(); // ELF 0x3E2D30 (C2), 0x3E2E30 (C1) + ~BotPlacementManager(); // ELF 0x3E2E80 (D2), 0x3E2EF0 (D1) - not virtual + + // Appends a placement to team 1 or 2. The team index is unchecked. + bool addPlacement(const std::string& name, const Vec3& position, const Vec3& rotation, + const std::string& string1C, int team, const std::string& string20); + // Emits the retail error, then consumes one placement when available. If the error is + // filtered, the retail body only renames the last-created bot; it creates no new bot. + bool spawnBot(int team); + + static BotPlacementManager* m_instance; + +private: + // Retail size 8 (`operator new(8)` in the static initializer): two list heads, one per team, + // indexed team - 1 by addPlacement. The constructor and destructor walk them as an array. + /* +0x00 */ std::list m_placements[2]; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_MAIN_BOTPLACEMENTMANAGER_H diff --git a/Code/BF2/AI/AIDLL/AI/Main/CommonSingletonServer.cpp b/Code/BF2/AI/AIDLL/AI/Main/CommonSingletonServer.cpp index da92ce876..3f8e3d314 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/CommonSingletonServer.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/CommonSingletonServer.cpp @@ -15,8 +15,14 @@ extern ClassManager* classManager; namespace ai { +// ELF 0x2EC020 / 0x2EC040; engine ELF 0x841BE50 / 0x841BE60. +ISingletonServerUpdater::ISingletonServerUpdater() +{ +} + // Shared out-of-line destructor used by engine and DLL updater classes. Keep it before // update in the interface: update occupies ELF +0x08 and PE +0x04. +// ELF 0x2EC060 / 0x2EC080 / 0x2EC0A0 ISingletonServerUpdater::~ISingletonServerUpdater() { } @@ -53,12 +59,14 @@ void* CommonSingletonServer::m_iAIMineManager = 0; // - a bare `ret`. See the header: the base publishes the entry point and does // nothing with it. AISingletonServer::updateStaticMethods is the one that is actually called. +// ELF 0x2EB570 void CommonSingletonServer::updateStaticMethods() { } // Refreshes all 28 singleton pointers in order. Missing names store null without logging // or reporting failure; callers must validate the interfaces they require. +// ELF 0x2EB580 void CommonSingletonServer::updateStaticMethodsInternal() { m_iAimerHelper = classManager->getSimpleSingleton("AimerHelper"); @@ -92,6 +100,7 @@ void CommonSingletonServer::updateStaticMethodsInternal() } // The same twenty-eight, same order, all nulled. +// ELF 0x2EB410 void CommonSingletonServer::clearAllStaticMethods() { m_iAimerHelper = 0; diff --git a/Code/BF2/AI/AIDLL/AI/Main/CommunicationHub.cpp b/Code/BF2/AI/AIDLL/AI/Main/CommunicationHub.cpp index 49c8003b7..0bfe8edb4 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/CommunicationHub.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/CommunicationHub.cpp @@ -1,8 +1,34 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining CommunicationHub operations. +// [INFERRED] Source placement. + +// static init: ELF 0x3E5BD0 (__tcf_0 0x3E5C30, _GLOBAL__I 0x3E5C60): 's Init object only. +#include #include "CommunicationHub.h" -#include "AIDllFrontier.h" +#include +#include +#include +#include + +#include "../AIStrategicEntity/AIStrategicObjectManager.h" // reset: the area count +#include "../AIStrategicEntity/AIStrategicArea.h" // enemySpottedByAI: area centres + +#include "CommonSingletonServer.h" // enemySpottedByHuman's timer +#include "IBotManager.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/CommunicationAgent.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "InformationManager.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" // IAIPlayer +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" // IAIPlayerFactory::getPlayerFromId +#include "../../../AIInterface/BFKnowledge/BFGame.h" // IAIGame::enemySpottedByAI +#include "../../../AIInterface/BFKnowledge/BFRadioComm.h" // IBFRadioComm::sendAIRadioMessage +#include "../../../AIInterface/Module/BFConsole.h" // IBFModuleCourier, AIRadioMessageSettings +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" namespace dice { namespace hfe { @@ -28,34 +54,219 @@ CommunicationHub::~CommunicationHub() m_instance = 0; } -// [FRONTIER] Behavior methods stop until their strategic-object dependencies are implemented. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. +// ELF 0x3E5170. The three timestamps go to -1000.0. Each side's strength vector gets one entry +// per strategic area: appended as {6, -1000.0} while side 0's vector is empty, otherwise the +// first areaCount entries of both are overwritten in place (sizes are not checked again). void CommunicationHub::reset() { - BF2_AI_FRONTIER("dice::hfe::ai::CommunicationHub::reset"); + const double never = -1000.0; + m_lastReqPickupSendTime[0] = never; + m_lastReqPickupSendTime[1] = never; + m_time44 = never; + const int areas = static_cast(AIStrategicObjectManager::getInstance()->getStrategicAreas().size()); + if (m_combatStrength[0].empty()) + { + for (int i = 0; i < areas; ++i) + { + m_combatStrength[0].push_back(std::make_pair(static_cast(6), static_cast(-1000))); + m_combatStrength[1].push_back(std::make_pair(static_cast(6), static_cast(-1000))); + } + return; + } + for (int i = 0; i < areas; ++i) + { + m_combatStrength[0][i].first = static_cast(6); + m_combatStrength[1][i].first = static_cast(6); + m_combatStrength[0][i].second = never; + m_combatStrength[1][i].second = never; + } } -void CommunicationHub::enemySpottedByAI(IAIPlayer*, IAIObject*, int) +// ELF 0x3E57E0 (776 bytes). The side's information about the object must be primary (Information +// ::isPrimary is called on the lookup result without a null test) and have a physical plug-in. +// The object's XZ position is tested against every strategic area's centre (AIStrategicArea +// ::getCenterPosition), within 100 m for strength types 4 and 5, else 30 m. For the first area in +// range that has news the game is told (IAIGame +0x6C) and the scan ends: +// * types 4/5: more than 60 s since the last such report (+44, shared by both sides); +// * the area's entry for the side is older than 60 s: it takes the type and the time; +// * the entry holds type 0 or 1 and the enemy is type 2: it becomes 2 with the time. +// The object's world object is fetched before the bot's player, as shipped. +void CommunicationHub::enemySpottedByAI(IAIPlayer* player, IAIObject* object, int side) { - BF2_AI_FRONTIER("dice::hfe::ai::CommunicationHub::enemySpottedByAI"); + Information* const information = informationManager->getInformation(object->getInformation(side)); + if (!information->isPrimary()) + return; + IPIPhysical* const physical = information->getPhysical(); + if (!physical) + return; + const int strengthType = physical->getStrengthType(); + const std::map& areas = + AIStrategicObjectManager::getInstance()->getStrategicAreas(); + const bool largeType = static_cast(strengthType - 4) <= 1; + const float rangeSq = largeType ? 10000.0f : 900.0f; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + std::vector >& strengths = m_combatStrength[side - 1]; + + unsigned int index = 0; + for (std::map::const_iterator it = areas.begin(); it != areas.end(); + ++it, ++index) + { + Vec2 position; + position.x = 0.0f; + position.y = 0.0f; + vec3ToVec2XZ(object->getPosition(), position); + const Vec2& centre = it->second->getCenterPosition(); + const float dx = position.x - centre.x; + const float dy = position.y - centre.y; + if (!(rangeSq > dx * dx + dy * dy)) + continue; + if (largeType && now - m_time44 > 60.0f) + { + m_time44 = now; + break; + } + std::pair& entry = strengths[index]; + if (now - entry.second > 60.0f) + { + entry.first = static_cast(strengthType); + entry.second = now; + break; + } + if ((entry.first == 0 || entry.first == 1) && strengthType == 2) + { + strengths[index].first = static_cast(2); + strengths[index].second = now; + break; + } + } + if (index == areas.size()) + return; // no area had news: the shipped loop exit skips the report + + world::IObject* const spotted = object->getObject(); + world::IPlayer* const spotter = player->getPlayer(); + static_cast(CommonSingletonServer::m_iaiGame)->enemySpottedByAI(spotter, spotted); } -void CommunicationHub::enemySpottedByHuman(IAIObject*, unsigned char) const +// ELF 0x3E5AF0. The side's information about the object (IAIObject +0xB8 getInformation), +// else forced into existence (+0xB4 forceGetInformation(side, true)), is stamped with the game +// time (Information +0xC setTime). Neither lookup result is tested before the stamp. +void CommunicationHub::enemySpottedByHuman(IAIObject* object, unsigned char side) const { - BF2_AI_FRONTIER("dice::hfe::ai::CommunicationHub::enemySpottedByHuman"); + Information* information = informationManager->getInformation(object->getInformation(side)); + if (!information) + information = informationManager->getInformation(object->forceGetInformation(side, true)); + information->setTime(static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime()); } -void CommunicationHub::filterAndSendAIRadioMessage(BotMain*, int, ChannelMessageType, - AIRadioChannelType, AIRadioMessageType, - unsigned char, int, unsigned char, - unsigned char) +// ELF 0x3E5330 (395 bytes). The game time is read first in every case. A type-2 message is sent +// only when more than 20 s have passed since the side's last one, whose time is then renewed from +// a second timer read. Inside the 20 s it is not sent: when `argument` names an AI player, the +// settings of message type 2 (IBFModuleCourier +0x1C, then +0x18; the voice lookup's result is +// not tested) go straight to filterAndReceiveAIRadioMessage(settings, playerId, argument, true). +// Everything else reaches IBFRadioComm +8 without the message type; its result is discarded. +void CommunicationHub::filterAndSendAIRadioMessage(BotMain*, int senderPlayerId, + ChannelMessageType channelMessage, + AIRadioChannelType channel, AIRadioMessageType type, + unsigned char voice, int playerId, unsigned char side, + unsigned char argument) { - BF2_AI_FRONTIER("dice::hfe::ai::CommunicationHub::filterAndSendAIRadioMessage"); + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (type == 2) + { + if (!(20.0f > now - m_lastReqPickupSendTime[side - 1])) + { + m_lastReqPickupSendTime[side - 1] = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + } + else + { + IAIPlayer* const receiver = + static_cast(CommonSingletonServer::m_iaiPlayerFactory)->getPlayerFromId(argument); + if (!receiver || !receiver->getIsAIPlayer()) + return; + IBFModuleCourier* const courier = + static_cast(CommonSingletonServer::m_iBFModuleCourier); + int typeVoice; + courier->getVoiceFromAiMessageType(static_cast(2), typeVoice); + AIRadioMessageSettings settings; + courier->getAIMessageSettings(typeVoice, settings); + filterAndReceiveAIRadioMessage(settings, playerId, argument, true); + return; + } + } + static_cast(CommonSingletonServer::m_iBFRadioComm) + ->sendAIRadioMessage(senderPlayerId, channelMessage, channel, voice, playerId, side, argument); } -void CommunicationHub::filterAndReceiveAIRadioMessage(const AIRadioMessageSettings&, int, int, bool) +// ELF 0x3E54C0 (795 bytes). The receiver is IBotManager +0x1C getBotFromPlayerId(receiver), used +// without a null test; its own messages (BotMain +0xB4 getPlayerId == sender) are dropped. A +// message of type 0, 1 or 2 (settings +0) whose sender is a human player (IAIPlayerFactory +0x20, +// IAIPlayer +0x88 false) is filtered first; an unknown or AI sender is not: +// * type 2 is dropped when the receiver's current equipment lies more than 90 degrees off the +// human's camera forward axis (row 2), seen from the camera position (row 3). The direction +// is normalised as shipped: kept when |d.d - 1| < FLT_EPSILON, zero when |d.d| < FLT_EPSILON. +// The equipment information is not null-tested; +// * types 1 and 0 set the human's current vehicle's primary object allowed (1) or not allowed +// (0) for bots (IAIObject +0xFC, +0x9C); the vehicle itself is not null-tested. +// Then CommunicationAgent::receiveRadioMessage(settings, sender, flag) files it. +// [CHOSEN, not recovered] x87 extended intermediates are carried in double here. +void CommunicationHub::filterAndReceiveAIRadioMessage(const AIRadioMessageSettings& settings, + int senderPlayerId, int receiverPlayerId, bool flag) { - BF2_AI_FRONTIER("dice::hfe::ai::CommunicationHub::filterAndReceiveAIRadioMessage"); + Bot* const bot = IBotManager::instance->getBotFromPlayerId(receiverPlayerId); + if (senderPlayerId == bot->getPlayerId()) + return; + int type; + std::memcpy(&type, settings.m_opaque0, sizeof(type)); // +0, opaque in BFConsole.h + IAIPlayerFactory* const players = static_cast(CommonSingletonServer::m_iaiPlayerFactory); + if (type == 0 || type == 1) + { + IAIPlayer* const sender = players->getPlayerFromId(senderPlayerId); + if (sender && !sender->getIsAIPlayer()) + { + if (IAIObject* const primary = sender->getCurrentVehicle()->getPrimaryObject()) + primary->setIsAllowedByBots(type == 1); + } + } + else if (type == 2) + { + IAIPlayer* const sender = players->getPlayerFromId(senderPlayerId); + if (sender && !sender->getIsAIPlayer()) + { + const Mat4& camera = *static_cast(sender->getCameraTransformation()); + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + const Vec3& target = equipment->getPosition(); + Vec3 direction; + direction.x = target.x - camera.m[12]; + direction.y = target.y - camera.m[13]; + direction.z = target.z - camera.m[14]; + const double lengthSq = static_cast(direction.x) * direction.x + + static_cast(direction.y) * direction.y + + static_cast(direction.z) * direction.z; + if (!(std::fabs(lengthSq - 1.0f) < 1.1920928955078125e-07f)) + { + if (!(std::fabs(static_cast(lengthSq)) < 1.1920928955078125e-07f)) + { + const double scale = 1.0f / std::sqrt(lengthSq); + direction.x = static_cast(direction.x * scale); + direction.y = static_cast(direction.y * scale); + direction.z = static_cast(direction.z * scale); + } + else + direction.x = direction.y = direction.z = 0.0f; + } + const Mat4& view = *static_cast(sender->getCameraTransformation()); + double cosine = static_cast(view.m[8]) * direction.x + + static_cast(view.m[9]) * direction.y + + static_cast(view.m[10]) * direction.z; + if (-1.0f > cosine) + cosine = -1.0f; + else if (cosine > 1.0f) + cosine = 1.0f; + if (std::acos(static_cast(cosine)) > 1.5707963705062866f) + return; + } + } + bot->getCommunicationAgent()->receiveRadioMessage(settings, senderPlayerId, flag); } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/Main/CommunicationHub.h b/Code/BF2/AI/AIDLL/AI/Main/CommunicationHub.h index ff066edbf..e24fdb10c 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/CommunicationHub.h +++ b/Code/BF2/AI/AIDLL/AI/Main/CommunicationHub.h @@ -1,6 +1,4 @@ // Filters and distributes bot radio messages and enemy sightings. -// [FRONTIER] Remaining message behavior requires implementation. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. // [INFERRED] Source placement. #ifndef AI_AIDLL_AI_MAIN_COMMUNICATIONHUB_H @@ -32,26 +30,36 @@ enum CombatStrengthType : int; class CommunicationHub { public: - CommunicationHub(); // 0x??, - virtual ~CommunicationHub(); // 0x??, - (vtable slots 0 and 1) + CommunicationHub(); // ELF 0x3E4F10 (C1), 0x3E4EB0 (C2) + virtual ~CommunicationHub(); // ELF 0x3E5010 (D1), 0x3E4F70 (D2), 0x3E50B0 (D0) - void reset(); - void enemySpottedByAI(IAIPlayer *, IAIObject *, int); - void enemySpottedByHuman(IAIObject *, unsigned char) const; - void filterAndSendAIRadioMessage(BotMain *, int, ChannelMessageType, - AIRadioChannelType, AIRadioMessageType, - unsigned char, int, unsigned char, unsigned char); - void filterAndReceiveAIRadioMessage(const AIRadioMessageSettings&, int, int, bool); + void reset(); // ELF 0x3E5170 + // ELF 0x3E57E0: reports a bot's sighting of `object` to the game (IAIGame +0x6C) when it is + // new for one of `side`'s strategic areas. + void enemySpottedByAI(IAIPlayer* player, IAIObject* object, int side); + void enemySpottedByHuman(IAIObject *, unsigned char) const; // ELF 0x3E5AF0 + // ELF 0x3E5330: hands a bot's message to the engine radio (IBFRadioComm +8). The BotMain + // argument is not read. A type-2 message within 20 s of the side's last one is not sent; + // it is delivered to `argument` directly when that player is a bot. + void filterAndSendAIRadioMessage(BotMain* bot, int senderPlayerId, ChannelMessageType channelMessage, + AIRadioChannelType channel, AIRadioMessageType type, + unsigned char voice, int playerId, unsigned char side, + unsigned char argument); + // ELF 0x3E54C0: files `settings` with the bot of `receiverPlayerId` (unless it sent it). + // Messages of types 0..2 from a human sender are filtered first; see the .cpp. + void filterAndReceiveAIRadioMessage(const AIRadioMessageSettings& settings, int senderPlayerId, + int receiverPlayerId, bool flag); // Offsets describe the original ELF layout. STL sizes and double alignment depend on // the target compiler; do not treat 52 bytes as a portable object size. // These timestamps are uninitialized until reset is called. - /* +4 */ double m_time4; // [UNRESOLVED] - reset puts -1000.0 here - /* +12 */ double m_time12; // [UNRESOLVED] - likewise + // Game time of each side's last sent type-2 message (indexed side - 1); reset: -1000.0. + /* +4 */ double m_lastReqPickupSendTime[2]; // name: AIDLL_r assert (0x10079AD0) // Two per-side combat-strength vectors. Each original ELF element occupies 12 bytes. /* +20 */ std::vector > m_combatStrength[2]; - /* +44 */ double m_time44; // [UNRESOLVED] - reset puts -1000.0 here too + // enemySpottedByAI: last report of a strength-type 4/5 enemy, either side; reset: -1000.0. + /* +44 */ double m_time44; // first wins here (`if (!m_instance)`), and the destructor does test `== this` - the opposite // discipline from `AerialHeightMap`, one step earlier in the same init sequence. diff --git a/Code/BF2/AI/AIDLL/AI/Main/IAIMain.cpp b/Code/BF2/AI/AIDLL/AI/Main/IAIMain.cpp new file mode 100644 index 000000000..826f6644f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/Main/IAIMain.cpp @@ -0,0 +1,31 @@ +// Source placement: AIDLL_r.dll __FILE__ "Code\BF2\AI\AIDLL\AI\Main\IAIMain.cpp" (the constructor +// 0x10055900 asserts "!m_instance", "Singleton already created"; asserts are compiled out of retail +// 1.50). Split out of AIMain.cpp; the functions are unchanged. The ELF also keeps them apart from +// AIMain.cpp's functions (0x3E6790.. against AIMain's 0x39xxxx). + +#include "AIMain.h" + +namespace dice { +namespace hfe { +namespace ai { + +// Active IAIMain instance; construction replaces it unconditionally. +IAIMain* IAIMain::m_instance = 0; + +// Construction replaces the active IAIMain pointer. Destruction clears it unconditionally. +// Only one IAIMain may be alive when callers use this singleton. +// ELF 0x3E6790 / 0x3E67C0 +IAIMain::IAIMain() +{ + m_instance = this; +} + +// ELF 0x3E67F0 / 0x3E6820 / 0x3E6850 +IAIMain::~IAIMain() +{ + m_instance = 0; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/Main/IAIPathfinding.cpp b/Code/BF2/AI/AIDLL/AI/Main/IAIPathfinding.cpp index 8466be28f..19fc139e0 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/IAIPathfinding.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/IAIPathfinding.cpp @@ -1,6 +1,13 @@ - +#include #include "IAIPathfinding.h" +// IAIPathfindingSetup lives in IAIPathfindingSetup.cpp (AIDLL_r __FILE__). +namespace { +// Local object name [INFERRED]. +// static init: ELF 0x3E6990 (__tcf_0 0x3E69F0, _GLOBAL__I 0x3E6A20), IAIPathfinding.cpp. +std::ios_base::Init pathfindingStreamInit; +} + namespace dice { namespace hfe { namespace ai { @@ -19,29 +26,6 @@ IAIPathfinding::~IAIPathfinding() instance = 0; } -// Setup has its own singleton pointer, replaced on construction and cleared on destruction. -// An AIPathfinding instance publishes both interfaces. -IAIPathfindingSetup* IAIPathfindingSetup::instance = 0; - -IAIPathfindingSetup::IAIPathfindingSetup() -{ - instance = this; -} - -IAIPathfindingSetup::~IAIPathfindingSetup() -{ - instance = 0; -} - -// Stateless map-container interface with no registry entry or custom lifecycle work. -IAIPathfindingSetup::IMapContainer::IMapContainer() -{ -} - -IAIPathfindingSetup::IMapContainer::~IMapContainer() -{ -} - } // namespace ai } // namespace hfe } // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/Main/IAIPathfinding.h b/Code/BF2/AI/AIDLL/AI/Main/IAIPathfinding.h index bd35c7875..3d002389c 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/IAIPathfinding.h +++ b/Code/BF2/AI/AIDLL/AI/Main/IAIPathfinding.h @@ -28,6 +28,18 @@ struct triple C third; }; +// Attested as `ai::make_triple` (ELF), the triple counterpart of +// std::make_pair. +template +triple make_triple(const A& first, const B& second, const C& third) +{ + triple result; + result.first = first; + result.second = second; + result.third = third; + return result; +} + namespace astar { // `setStatus`'s second argument and `getStatus`'s result. [UNRESOLVED] enumerators. enum Status : int; @@ -59,28 +71,28 @@ class IAIPathfinding virtual bool isValidPosition(int, int, const Vec3&, unsigned int, bool) const = 0; virtual bool isValidPosition(int, int, const Vec3&, unsigned int, unsigned int, bool) const = 0; // Appends pointers to const vertices through a mutable output vector. - virtual int getPolygon(std::vector&, int, const Vec3&, int) const = 0; - virtual int getPolygon(std::vector&, int, const Vec3&, unsigned int&, unsigned int&, int) const = 0; - virtual int getPolygon(std::vector&, int, unsigned int, unsigned int) const = 0; + virtual bool getPolygon(std::vector&, int, const Vec3&, int) const = 0; + virtual bool getPolygon(std::vector&, int, const Vec3&, unsigned int&, unsigned int&, int) const = 0; + virtual bool getPolygon(std::vector&, int, unsigned int, unsigned int) const = 0; // Returns whether a polygon was found; invalid map indices return false. // [INFERRED] The second overload's bool result follows the first overload's contract. virtual bool getPolygon(const Vec3&, int, unsigned int&, unsigned int&, int) const = 0; virtual bool getPolygon(const Vec3&, int, unsigned int&, unsigned int&, unsigned int, unsigned int, int) const = 0; virtual void getPolygonsInRadius(std::list&, int, unsigned int, unsigned int, const Vec3&, float) const = 0; virtual void getPolygonsInTriangle(std::list&, int, unsigned int, unsigned int, const Vec3&, const Vec3&, const Vec3&) const = 0; - virtual int getPolygonFromIsland(const Vec3&, int, unsigned int&, unsigned int, int) const = 0; + virtual bool getPolygonFromIsland(const Vec3&, int, unsigned int&, unsigned int, int) const = 0; virtual bool getMaterial(const Vec3&, int, int, unsigned char&) const = 0; virtual bool getMaterial(int, unsigned int, unsigned int, unsigned char&) const = 0; - virtual void setMaterial(int, unsigned int, unsigned int, unsigned char) const = 0; // const, and mutates + virtual bool setMaterial(int, unsigned int, unsigned int, unsigned char) const = 0; // const, and mutates virtual void* getQuadTree(int, unsigned int) const = 0; virtual void* getClusterGraph(int, unsigned int) const = 0; virtual void getPolygonCentre(Vec3&, int, unsigned int, unsigned int) const = 0; - virtual void getEdge(Vec3&, Vec3&, int, unsigned int, unsigned int, unsigned int) const = 0; + virtual bool getEdge(Vec3&, Vec3&, int, unsigned int, unsigned int, unsigned int) const = 0; virtual bool getLineIntersectionWithPolygon(Vec3&, int, unsigned int, unsigned int, const Vec3&, const Vec3&) const = 0; virtual void drawPolygon(int, unsigned int, unsigned int, float *, float) const = 0; // const, and draws virtual int getClusterOfPolygon(int, unsigned int, unsigned int) const = 0; virtual bool areNeighbouringClusters(int, unsigned int, unsigned short, unsigned short) const = 0; - virtual void updateClusterPortalCosts(unsigned int&, triple&, int, unsigned int, unsigned short) = 0; + virtual bool updateClusterPortalCosts(unsigned int&, triple&, int, unsigned int, unsigned short) = 0; virtual bool trace(int, const Vec3&, const Vec3&, Vec3&, unsigned int&, int, int, float, unsigned char, unsigned char *) const = 0; virtual bool trace(unsigned int, unsigned int, int, const Vec3&, const Vec3&, Vec3&, unsigned int&, int, int, float, unsigned char, unsigned char *) const = 0; virtual bool trace(BotNavigation *, bool, const Vec3&, Vec3&, unsigned int&, int, int, float, unsigned char, unsigned char *) const = 0; @@ -111,14 +123,16 @@ class IAIPathfinding virtual void restoreMapPart(int) = 0; virtual void resetOriginalMaterialOfDestroyableMapPart(int) = 0; virtual void searchPointSelected(bool) = 0; - virtual bool tryPath(const Vec3&, const Vec3&) = 0; - virtual bool tryClusterPath(const Vec3&, const Vec3&) = 0; + virtual void tryPath(const Vec3&, const Vec3&) = 0; + virtual void tryClusterPath(const Vec3&, const Vec3&) = 0; virtual void setClusterSearch(bool) = 0; virtual bool getClusterSearch() const = 0; virtual void setActivatePathfindingDebugTool(bool) = 0; virtual bool getActivatePathfindingDebugTool() const = 0; virtual void setPathfindingDebugToolVehicle(const std::string&) = 0; - virtual void* getPathfindingDebugToolVehicle() const = 0; + // ELF 0x3A53E0 returns IAISettings +0x50 getVehicle(int) unchanged; ConsoleClass540 assigns it + // to a std::string, so the borrowed reference is the result [INFERRED spelling]. + virtual const std::string& getPathfindingDebugToolVehicle() const = 0; virtual void setPathfindingDebugToolVehicleId(int) = 0; virtual int getClusterCostType(int, unsigned int) const = 0; @@ -138,24 +152,24 @@ class IAIPathfindingSetup IMapContainer(); virtual ~IMapContainer(); // slots 0, 1 - virtual const std::string& getName() = 0; // 2 - virtual int getMinPolygonsInLeaf() = 0; // 3 + virtual const std::string& getName() const = 0; // 2 + virtual int getMinPolygonsInLeaf() const = 0; // 3 virtual void setMinPolygonsInLeaf(int) = 0; // 4 - virtual int getMaxDepthInTree() = 0; // 5 + virtual int getMaxDepthInTree() const = 0; // 5 virtual void setMaxDepthInTree(int) = 0; // 6 - virtual float getMaxSlope() = 0; // 7 + virtual float getMaxSlope() const = 0; // 7 virtual void setMaxSlope(float) = 0; // 8 virtual void setHeadClearance(float) = 0; // 9 - virtual float getHeadClearance() = 0; // 10 + virtual float getHeadClearance() const = 0; // 10 virtual void setRadius(float) = 0; // 11 - virtual float getRadius() = 0; // 12 + virtual float getRadius() const = 0; // 12 virtual void setAllowedHeightDiff(float) = 0; // 13 - virtual float getAllowedHeightDiff() = 0; // 14 - virtual void draw() = 0; // 15 - virtual void undraw() = 0; // 16 - virtual void drawCluster() = 0; // 17 - virtual void undrawCluster() = 0; // 18 - virtual void drawClusterNeighbourIndices(const Vec3&) = 0; // 19 + virtual float getAllowedHeightDiff() const = 0; // 14 + virtual void draw() const = 0; // 15 + virtual void undraw() const = 0; // 16 + virtual void drawCluster() const = 0; // 17 + virtual void undrawCluster() const = 0; // 18 + virtual void drawClusterNeighbourIndices(const Vec3&) const = 0; // 19 virtual void loadGTSDebugMeshes() = 0; // 20 virtual void buildDebugMeshes() = 0; // 21 virtual void unloadDebugMeshes() = 0; // 22 @@ -204,4 +218,4 @@ class IAIPathfindingSetup } // namespace hfe } // namespace dice -#endif // AI_AIDLL_AI_MAIN_IAIPATHFINDING_H \ No newline at end of file +#endif // AI_AIDLL_AI_MAIN_IAIPATHFINDING_H diff --git a/Code/BF2/AI/AIDLL/AI/Main/IAIPathfindingSetup.cpp b/Code/BF2/AI/AIDLL/AI/Main/IAIPathfindingSetup.cpp new file mode 100644 index 000000000..e07f2abc8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/Main/IAIPathfindingSetup.cpp @@ -0,0 +1,42 @@ +// Source placement: AIDLL_r.dll __FILE__ "Code\BF2\AI\AIDLL\AI\Main\IAIPathfindingSetup.cpp" (the +// constructor 0x100CE290 asserts "!instance", "Singleton already created"; asserts are compiled out +// of retail 1.50). Split out of IAIPathfinding.cpp; the functions are unchanged. +#include +#include "IAIPathfinding.h" + +namespace { +// Local object name [INFERRED]. +// static init: ELF 0x3E6B40 (__tcf_0 0x3E6BA0, _GLOBAL__I 0x3E6BD0), IAIPathfindingSetup.cpp. +std::ios_base::Init pathfindingSetupStreamInit; +} + +namespace dice { +namespace hfe { +namespace ai { + +// Setup has its own singleton pointer, replaced on construction and cleared on destruction. +// An AIPathfinding instance publishes both interfaces. +IAIPathfindingSetup* IAIPathfindingSetup::instance = 0; + +IAIPathfindingSetup::IAIPathfindingSetup() +{ + instance = this; +} + +IAIPathfindingSetup::~IAIPathfindingSetup() +{ + instance = 0; +} + +// Stateless map-container interface with no registry entry or custom lifecycle work. +IAIPathfindingSetup::IMapContainer::IMapContainer() +{ +} + +IAIPathfindingSetup::IMapContainer::~IMapContainer() +{ +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/Main/IBotManager.cpp b/Code/BF2/AI/AIDLL/AI/Main/IBotManager.cpp index 04a2da041..5025a7ce3 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/IBotManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/IBotManager.cpp @@ -1,4 +1,5 @@ -// [INFERRED] Source placement. +// Source placement: AIDLL_r.dll __FILE__ "Code\BF2\AI\AIDLL\AI\Main\IBotManager.cpp" (constructor 0x100CE370). +// IBotManagerModifier lives in IBotManagerModifier.cpp (AIDLL_r __FILE__). // [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining IBotManager operations. #include "IBotManager.h" @@ -8,7 +9,6 @@ namespace hfe { namespace ai { IBotManager* IBotManager::instance = 0; -IBotManagerModifier* IBotManagerModifier::instance = 0; // Each interface publishes its singleton unconditionally and clears it on destruction. // Destroying a displaced manager can clear the pointer to a newer instance. @@ -23,16 +23,6 @@ IBotManager::~IBotManager() instance = 0; } -IBotManagerModifier::IBotManagerModifier() -{ - instance = this; -} - -IBotManagerModifier::~IBotManagerModifier() -{ - instance = 0; -} - } // namespace ai } // namespace hfe } // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/Main/IBotManager.h b/Code/BF2/AI/AIDLL/AI/Main/IBotManager.h index 812bd06bc..5adc9a14c 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/IBotManager.h +++ b/Code/BF2/AI/AIDLL/AI/Main/IBotManager.h @@ -12,7 +12,7 @@ namespace dice { namespace hfe { namespace ai { -class AIRadioMessageSettings; +struct AIRadioMessageSettings; class Bot; class IAIObject; diff --git a/Code/BF2/AI/AIDLL/AI/Main/IBotManagerModifier.cpp b/Code/BF2/AI/AIDLL/AI/Main/IBotManagerModifier.cpp new file mode 100644 index 000000000..74757af08 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/Main/IBotManagerModifier.cpp @@ -0,0 +1,26 @@ +// Source placement: AIDLL_r.dll __FILE__ "Code\BF2\AI\AIDLL\AI\Main\IBotManagerModifier.cpp" (the +// constructor 0x100DB450 asserts "instance == 0", "IBotManagerModifier is singleton"; asserts are +// compiled out of retail 1.50). Split out of IBotManager.cpp; the functions are unchanged. + +#include "IBotManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +IBotManagerModifier* IBotManagerModifier::instance = 0; + +// Publishes its singleton unconditionally and clears it on destruction, like IBotManager. +IBotManagerModifier::IBotManagerModifier() +{ + instance = this; +} + +IBotManagerModifier::~IBotManagerModifier() +{ + instance = 0; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationManager.cpp b/Code/BF2/AI/AIDLL/AI/Main/InformationManager.cpp similarity index 85% rename from Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationManager.cpp rename to Code/BF2/AI/AIDLL/AI/Main/InformationManager.cpp index 7080102c0..82955fa52 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/InformationManager.cpp @@ -1,4 +1,4 @@ -// [INFERRED] Source placement. +// [INFERRED] Source placement: beside its header, whose path AIDLL_r.dll confirms (Main/InformationManager.h). #include "InformationManager.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationManager.h b/Code/BF2/AI/AIDLL/AI/Main/InformationManager.h similarity index 78% rename from Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationManager.h rename to Code/BF2/AI/AIDLL/AI/Main/InformationManager.h index 2d9a4a5ff..6a940a677 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationManager.h +++ b/Code/BF2/AI/AIDLL/AI/Main/InformationManager.h @@ -1,6 +1,6 @@ // Handle pool for AI information. The pool does not own the referenced information objects. // [INFERRED] Method names represent the observed pool operations. -// [INFERRED] Source placement. +// Source placement: AIDLL_r.dll __FILE__ "Code/BF2//AI/AIDLL/AI/Main/InformationManager.h" (an inline assert). #ifndef AI_AIDLL_AI_AIKNOWLEDGE_INFORMATIONMANAGER_H #define AI_AIDLL_AI_AIKNOWLEDGE_INFORMATIONMANAGER_H @@ -11,8 +11,8 @@ namespace dice { namespace hfe { namespace ai { -// [FRONTIER] the pooled type. `Information` is the AI's knowledge record; the pool only ever stores -// `Information*`, so nothing here needs it complete. Chunk 07 owns it. +// The pooled type. `Information` is the AI's knowledge record (AIKnowledge/Information.h); the pool +// only ever stores `Information*`, so nothing here needs it complete. class Information; // sizeof == 4, from `operator new(4u)`: one pointer and nothing else. diff --git a/Code/BF2/AI/AIDLL/AI/Main/StrategyManager.cpp b/Code/BF2/AI/AIDLL/AI/Main/StrategyManager.cpp index 7328a6be1..cb14c3a53 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/StrategyManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/StrategyManager.cpp @@ -1,8 +1,18 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining StrategyManager operations. +// static init: ELF 0x3EAC80 (__tcf_0 0x3EACE0, _GLOBAL__I 0x3EAD10): 's Init object only. +#include #include "StrategyManager.h" -#include "AIDllFrontier.h" +#include "../../../../Core/Debug.h" +#include "../AIUtils/checkPointer.h" +#include "../AIStrategic/Strategy.h" +#include "../AIStrategic/StrategyPrerequisite.h" +#include "../AIStrategic/SCConstant.h" +#include "../AIStrategic/SCHomogeneous.h" +#include "../AIStrategic/SCHeterogeneous.h" +#include "../AIStrategic/SCArea.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" +#include "../AIStrategicEntity/AIStrategicArea.h" namespace dice { namespace hfe { @@ -10,7 +20,7 @@ namespace ai { StrategyManager* StrategyManager::m_instance = 0; -// Initializes strategy collections and installs the singleton when none exists. +// ELF 0x3E7A60 / 0x3E7D40. Initializes collections and installs the first singleton. StrategyManager::StrategyManager() : m_activeStrategy(0) , m_activePrerequisite(0) @@ -26,7 +36,7 @@ StrategyManager::StrategyManager() m_instance = this; } -// Resets strategy state and releases the owned collections. +// ELF 0x3E7F70 / 0x3E8160. Resets state and releases the owned collections. StrategyManager::~StrategyManager() { reset(); @@ -35,45 +45,51 @@ StrategyManager::~StrategyManager() m_instance = 0; } -// Static access to the concrete strategy manager, whose destructor is nonvirtual. +// ELF 0x3E8350. Static access to the manager, whose destructor is nonvirtual. StrategyManager* StrategyManager::getInstance() { return m_instance; } +// ELF 0x3E8370. void StrategyManager::setInstance(StrategyManager* instance) { m_instance = instance; } +// ELF 0x3EA7B0. bool StrategyManager::getEnableDebug() { return m_enableDebug; } -void StrategyManager::setEnableDebug(bool on) +// ELF 0x3EA790. The stored byte is explicitly returned in EAX. +bool StrategyManager::setEnableDebug(bool on) { m_enableDebug = on; + return on; } +// ELF 0x3E8730. Strategy* StrategyManager::getActiveStrategy() { return m_activeStrategy; } -// by value - the shipped function is `__stdcall` with a hidden return slot, i.e. it copies the +// ELF 0x3E8740. The shipped function has a hidden return slot, i.e. it copies the // member rather than handing back a reference to it. std::string StrategyManager::getActiveStrategyName() { return m_activeStrategyName; } +// ELF 0x3E9410. StrategyPrerequisite* StrategyManager::getActivePrerequisite() { return m_activePrerequisite; } -// the cursor is checked before it is dereferenced, and a miss returns null rather than a sentinel. +// ELF 0x3EA3B0. A missing active condition returns null. StrategyCondition* StrategyManager::getActiveCondition() { if (m_activeCondition == m_conditions.end()) @@ -81,136 +97,378 @@ StrategyCondition* StrategyManager::getActiveCondition() return m_activeCondition->second; } -// 1-based, and unclamped - see the member note in the header. `team == 0` reads the dword that +// ELF 0x3EA770. 1-based and unclamped. `team == 0` reads the dword that // holds `m_enableDebug`. Strategy* StrategyManager::getForcedStrategy(int team) { return m_forcedStrategy[team - 1]; } -// [FRONTIER] Remaining strategy-management operations require strategy and condition behavior. -// reset is also reached by destruction. -// [RETIRE-WHEN: aidll-02-skeleton] Replace each stop when its corresponding behavior is recovered. -void StrategyManager::reset() -{ - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::reset"); -} - +// ELF 0x3EA7D0 (1192 B; recovered on the client track). Clears the +// forced strategies and the debug flag, then empties the three owning maps one node at a time: +// value deleted first (Strategy and StrategyPrerequisite through their nonvirtual destructors, +// conditions through the virtual deleting destructor, vtable +4), then the node erased. The +// active name/pointer pairs are reset from a temporary {name, 0}; the shipped strategy text is +// "No Strategiws" (sic, the constructor says "No Strategies"). The modifier and area lists are +// left alone. Returns 1 (`mov eax, 1` at 0x3EAB7C). +bool StrategyManager::reset() +{ + m_forcedStrategy[0] = 0; // +0x48 + m_forcedStrategy[1] = 0; // +0x4C + m_enableDebug = false; // +0x44 + + std::map::iterator strategy = m_strategies.begin(); + while (strategy != m_strategies.end()) + { + delete strategy->second; + m_strategies.erase(strategy++); + } + m_activeStrategyName = std::string("No Strategiws"); // +0x04 + m_activeStrategy = 0; // +0x08 + + std::map::iterator prerequisite = m_prerequisites.begin(); + while (prerequisite != m_prerequisites.end()) + { + delete prerequisite->second; + m_prerequisites.erase(prerequisite++); + } + m_activePrerequisiteName = std::string("No Prerequisites"); // +0x1C + m_activePrerequisite = 0; // +0x20 + + std::map::iterator condition = m_conditions.begin(); + while (condition != m_conditions.end()) + { + delete condition->second; // virtual, slot +4 + m_conditions.erase(condition++); + } + m_activeCondition = m_conditions.end(); // +0x30 + return true; +} + +// ELF 0x3EA7C0: `movzbl 0x44(this)`, the same body as getEnableDebug. bool StrategyManager::isDebugEnabled() { - // twelve bytes, the same size as `getEnableDebug`, so it is almost certainly the identical - // body under a second name - but it was not read, and a size coincidence is not a reading. - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::isDebugEnabled"); + return m_enableDebug; } +// ELF 0x3E9420: a copy of the +0x1C string. std::string StrategyManager::getActivePrerequisiteName() { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::getActivePrerequisiteName"); + return m_activePrerequisiteName; } +// ELF 0x3EA3D0: the active condition's key, or "" (the empty tail of a string literal at +// ELF GOT-0xFD12) while the iterator is end(). std::string StrategyManager::getActiveConditionName() { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::getActiveConditionName"); -} - -Strategy* StrategyManager::getStrategy(std::string) -{ - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::getStrategy"); + if (m_activeCondition == m_conditions.end()) + return ""; + return m_activeCondition->first; } -StrategyCondition* StrategyManager::getCondition(std::string) +// ELF 0x3E8930: map find, null when absent. +Strategy* StrategyManager::getStrategy(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::getCondition"); + const std::map::iterator it = m_strategies.find(name); + return it == m_strategies.end() ? 0 : it->second; } -StrategyPrerequisite* StrategyManager::getPrerequisite(std::string) +// ELF 0x3EA4C0: map find, null when absent. +StrategyCondition* StrategyManager::getCondition(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::getPrerequisite"); + const std::map::iterator it = m_conditions.find(name); + return it == m_conditions.end() ? 0 : it->second; } -void StrategyManager::setActiveStrategy(std::string) +// ELF 0x3E9610: map find, null when absent. +StrategyPrerequisite* StrategyManager::getPrerequisite(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::setActiveStrategy"); + const std::map::iterator it = m_prerequisites.find(name); + return it == m_prerequisites.end() ? 0 : it->second; } -void StrategyManager::setActivePrerequisite(std::string) +// ELF 0x3E8780. Both images explicitly return the selected pointer. +Strategy* StrategyManager::setActiveStrategy(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::setActivePrerequisite"); + const std::map::iterator it = m_strategies.find(name); + const std::pair active = it == m_strategies.end() + ? std::pair("NULL", 0) + : std::pair(it->first, it->second); + m_activeStrategyName = active.first; + m_activeStrategy = active.second; + return m_activeStrategy; } -void StrategyManager::setActiveCondition(std::string) +// ELF 0x3E9460. +StrategyPrerequisite* StrategyManager::setActivePrerequisite(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::setActiveCondition"); + const std::map::iterator it = m_prerequisites.find(name); + const std::pair active = it == m_prerequisites.end() + ? std::pair("", 0) + : std::pair(it->first, it->second); + m_activePrerequisiteName = active.first; + m_activePrerequisite = active.second; + return m_activePrerequisite; } -void StrategyManager::setPrerequisite(std::string) +// ELF 0x3EA440. +StrategyCondition* StrategyManager::setActiveCondition(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::setPrerequisite"); + m_activeCondition = m_conditions.find(name); + // shipped defect: a missing condition leaves end(), which is still dereferenced. + return m_activeCondition->second; } -void StrategyManager::forceStrategy(std::string, int) +// ELF 0x3E8A50: the named prerequisite (null when unknown) goes to the active strategy; with +// none an Error debug (line 182) is raised. +void StrategyManager::setPrerequisite(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::forceStrategy"); -} - -void StrategyManager::createStrategy(std::string) + if (!m_activeStrategy) + { + Debug(DebugTypeError, "AI/AIDLL/AI/Main/StrategyManager.cpp", 182, "") + << "Cannot set prerequisite " << name << " - there is no active strategy."; + return; + } + m_activeStrategy->setPrerequisite(getPrerequisite(name)); +} + +// ELF 0x3EA650. +std::string StrategyManager::forceStrategy(std::string name, int side) { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::createStrategy"); + std::string result; + if (side != 1 && side != 2) + { + result += "Side must be 1 or 2, current side: "; + // shipped defect: append the side as one character, rather than a decimal number. + result += static_cast(side); + return result; + } + const std::map::iterator it = m_strategies.find(name); + if (it == m_strategies.end()) + { + m_forcedStrategy[side - 1] = 0; + result += "No active strategy chosen : "; + } + else + { + m_forcedStrategy[side - 1] = it->second; + result += "Strategy is activated : "; + } + result += name; + return result; } -void StrategyManager::createPrerequisite(std::string) +// ELF 0x3E8390. An existing name clears the active strategy (name "NULL") and answers false; +// otherwise the new strategy is registered and becomes active. +bool StrategyManager::createStrategy(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::createPrerequisite"); + if (m_strategies.find(name) != m_strategies.end()) + { + m_activeStrategyName.assign("NULL"); + m_activeStrategy = 0; + return false; + } + Strategy* const strategy = checkPointer(new Strategy(name)); + m_strategies[name] = strategy; + m_activeStrategyName = name; + m_activeStrategy = strategy; + return true; } -void StrategyManager::addCondition(std::string) +// ELF 0x3E90C0: the createStrategy shape for prerequisites; an existing name answers false and +// leaves the active prerequisite as it is. +bool StrategyManager::createPrerequisite(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::addCondition"); + if (m_prerequisites.find(name) != m_prerequisites.end()) + return false; + StrategyPrerequisite* const prerequisite = checkPointer(new StrategyPrerequisite(name)); + m_prerequisites[name] = prerequisite; + m_activePrerequisiteName = name; + m_activePrerequisite = prerequisite; + return true; } -void StrategyManager::addCondition(std::string, float) +// ELF 0x3E97C0: weight 1.0f (ELF 0x49CB2C). Neither overload tests the active prerequisite. +void StrategyManager::addCondition(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::addCondition"); + m_activePrerequisite->addCondition(getCondition(name), 1.0f); } -void StrategyManager::addSpecificObjectModifier(std::string, float) +// ELF 0x3E9730. +void StrategyManager::addCondition(std::string name, float weight) { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::addSpecificObjectModifier"); + m_activePrerequisite->addCondition(getCondition(name), weight); } -void StrategyManager::addRequiredPrecedingStrategy(std::string) +// ELF 0x3E8F20. The active strategy is recorded unchecked and resolved against an area later. +bool StrategyManager::addSpecificObjectModifier(std::string name, float modifier) { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::addRequiredPrecedingStrategy"); + ObjectStrategyModifierTuple tuple; + tuple.m_objectName = name; + tuple.m_strategy = m_activeStrategy; + tuple.m_modifier = modifier; + m_objectModifiers.insert(m_objectModifiers.end(), tuple); + return true; } -void StrategyManager::addProhibitedPrecedingStrategy(std::string) +// ELF 0x3E8BE0. +bool StrategyManager::addRequiredPrecedingStrategy(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::addProhibitedPrecedingStrategy"); -} - + if (!m_activeStrategy) + { + Debug(DebugTypeError, "AI/AIDLL/AI/Main/StrategyManager.cpp", 193, "") + << "Cannot add required preceding strategy " << name << " - there is no active strategy."; + return false; + } + return m_activeStrategy->addRequiredPrecedingStrategy(getStrategy(name)); +} + +// ELF 0x3E8D80. +bool StrategyManager::addProhibitedPrecedingStrategy(std::string name) +{ + if (!m_activeStrategy) + { + Debug(DebugTypeError, "AI/AIDLL/AI/Main/StrategyManager.cpp", 204, "") + << "Cannot add prohibited preceding strategy " << name << " - there is no active strategy."; + return false; + } + return m_activeStrategy->addProhibitedPrecedingStrategy(getStrategy(name)); +} + +// ELF 0x3E8FD0. Retains the tuples and leaves the last area selected. void StrategyManager::completeStrategies() { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::completeStrategies"); + AIStrategicObjectManager* const manager = AIStrategicObjectManager::getInstance(); + for (std::list::iterator it = m_objectModifiers.begin(); + it != m_objectModifiers.end(); ++it) + { + manager->setActive(it->m_objectName); + AIStrategicArea* const area = manager->getActiveArea(); + if (area) + it->m_strategy->setSpecificStrategicObjectModifier(area->m_index, it->m_modifier); + } } +// ELF 0x3EA5E0. The singleton lookup is retained even for an empty list. void StrategyManager::completeConditions() { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::completeConditions"); -} - -void StrategyManager::listStrategies() -{ - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::listStrategies"); -} - -void StrategyManager::listPrerequisites() -{ - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::listPrerequisites"); -} - -void StrategyManager::listConditions() -{ - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::listConditions"); + AIStrategicObjectManager::getInstance(); + for (std::list::iterator it = m_areas.begin(); it != m_areas.end(); ++it) + (*it)->updateArea(); +} + +// ELF 0x3E89A0. +std::string StrategyManager::listStrategies() +{ + std::string result; + for (std::map::iterator it = m_strategies.begin(); + it != m_strategies.end(); ++it) + { + result += it->first; + result += "\n"; + } + return result; +} + +// ELF 0x3E9680. +std::string StrategyManager::listPrerequisites() +{ + std::string result; + for (std::map::iterator it = m_prerequisites.begin(); + it != m_prerequisites.end(); ++it) + { + result += it->first; + result += "\n"; + } + return result; +} + +// ELF 0x3EA530. +std::string StrategyManager::listConditions() +{ + std::string result; + for (std::map::iterator it = m_conditions.begin(); + it != m_conditions.end(); ++it) + { + result += it->first; + result += "\n"; + } + return result; +} + +// ELF 0x3E9850. The target value starts at 0.0f (ELF 0x49CB34); a new condition becomes the +// active one (the insert's iterator). +bool StrategyManager::createConstantCondition(std::string name, + StrategyCondition::CompareType compareType, + StrategyCondition::Compare compare, + StrategyCondition::ConditionSide side, + StrategyCondition::Conditional conditional, + float constant) +{ + if (m_conditions.find(name) != m_conditions.end()) + { + m_activeCondition = m_conditions.end(); + return false; + } + StrategyCondition* const condition = checkPointer( + new SCConstant(name, compareType, compare, side, conditional, constant, 0.0f)); + m_activeCondition = + m_conditions.insert(std::pair(name, condition)).first; + return true; +} + +// ELF 0x3E9B20 +bool StrategyManager::createHomogenousCondition(std::string name, + StrategyCondition::CompareType compareType, + StrategyCondition::Compare compare, + StrategyCondition::Conditional conditional) +{ + if (m_conditions.find(name) != m_conditions.end()) + { + m_activeCondition = m_conditions.end(); + return false; + } + StrategyCondition* const condition = checkPointer( + new SCHomogeneous(name, compareType, compare, conditional, 0.0f)); + m_activeCondition = + m_conditions.insert(std::pair(name, condition)).first; + return true; +} + +// ELF 0x3E9DE0 +bool StrategyManager::createHeterogeneousCondition(std::string name, + StrategyCondition::CompareType compareType, + StrategyCondition::Compare compare, + StrategyCondition::ConditionSide side, + StrategyCondition::Conditional first, + StrategyCondition::Conditional second) +{ + if (m_conditions.find(name) != m_conditions.end()) + { + m_activeCondition = m_conditions.end(); + return false; + } + StrategyCondition* const condition = checkPointer( + new SCHeterogeneous(name, compareType, compare, side, first, second, 0.0f)); + m_activeCondition = + m_conditions.insert(std::pair(name, condition)).first; + return true; +} + +// ELF 0x3EA0B0 +bool StrategyManager::createAreaCondition(std::string name, std::string areaName, + StatusMap::Status status) +{ + if (m_conditions.find(name) != m_conditions.end()) + { + m_activeCondition = m_conditions.end(); + return false; + } + SCArea* const condition = checkPointer(new SCArea(name, areaName, -1, status)); + m_activeCondition = + m_conditions.insert(std::pair(name, condition)).first; + m_areas.insert(m_areas.end(), condition); + return true; } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/Main/StrategyManager.h b/Code/BF2/AI/AIDLL/AI/Main/StrategyManager.h index 24d835063..37e37cde1 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/StrategyManager.h +++ b/Code/BF2/AI/AIDLL/AI/Main/StrategyManager.h @@ -1,6 +1,4 @@ // Owns strategies and their conditions. -// [FRONTIER] Operations with unresolved nested parameter types remain undeclared. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. #ifndef AI_AIDLL_AI_MAIN_STRATEGYMANAGER_H #define AI_AIDLL_AI_MAIN_STRATEGYMANAGER_H @@ -10,6 +8,8 @@ #include #include "AIDllTypes.h" +#include "../AIStrategic/StrategyCondition.h" // the condition creators' enum parameters +#include "../AIStrategic/StatusMap.h" namespace dice { namespace hfe { @@ -27,19 +27,27 @@ class StrategyManager class ObjectStrategyModifierTuple { public: - char m_opaque[12]; // [UNRESOLVED] fields; size attested + // ELF 0x3E8F20 constructs these in order; names are [INFERRED]. + /* +0 */ std::string m_objectName; + /* +4 */ Strategy* m_strategy; + /* +8 */ float m_modifier; }; - StrategyManager(); // 0x?? / - ~StrategyManager(); // 0x??, - not virtual + StrategyManager(); + ~StrategyManager(); // nonvirtual - virtual void reset(); // the only virtual, vtable slot 0 + // The only virtual, vtable slot 0. ELF 0x3EA7D0 materializes `mov eax, 1` before its return, + // so it is not void; its direct callers (the D1/D2 destructors, ELF 0x3E7F95 / 0x3E8185) drop + // the value. The mangled name carries no return type: bool is [INFERRED] from the sibling + // sole-virtual resets (AIConsole, AIStrategicObjectManager, AILandingZoneManager, + // BotBehaviourManager), not from the PE. + virtual bool reset(); static StrategyManager* getInstance(); static void setInstance(StrategyManager *); bool getEnableDebug(); - void setEnableDebug(bool); + bool setEnableDebug(bool); bool isDebugEnabled(); Strategy* getActiveStrategy(); @@ -53,23 +61,41 @@ class StrategyManager Strategy* getStrategy(std::string); StrategyCondition* getCondition(std::string); StrategyPrerequisite* getPrerequisite(std::string); - void setActiveStrategy(std::string); - void setActivePrerequisite(std::string); - void setActiveCondition(std::string); + Strategy* setActiveStrategy(std::string); + StrategyPrerequisite* setActivePrerequisite(std::string); + // The shipped setter dereferences the resulting iterator even when the name is absent. + StrategyCondition* setActiveCondition(std::string); void setPrerequisite(std::string); - void forceStrategy(std::string, int); - void createStrategy(std::string); - void createPrerequisite(std::string); + std::string forceStrategy(std::string, int); // ConsoleClass407 assigns the string + bool createStrategy(std::string); // ELF 0x3E8390: false when the name exists + bool createPrerequisite(std::string); // ELF 0x3E90C0: likewise void addCondition(std::string); void addCondition(std::string, float); - void addSpecificObjectModifier(std::string, float); - void addRequiredPrecedingStrategy(std::string); - void addProhibitedPrecedingStrategy(std::string); + bool addSpecificObjectModifier(std::string, float); // ConsoleClass381 stores the bool + bool addRequiredPrecedingStrategy(std::string); // ConsoleClass376 stores the bool + bool addProhibitedPrecedingStrategy(std::string); // ConsoleClass377 stores the bool void completeStrategies(); void completeConditions(); - void listStrategies(); - void listPrerequisites(); - void listConditions(); + // ConsoleClass368/388/394 assign the strings. + std::string listStrategies(); + std::string listPrerequisites(); + std::string listConditions(); + + // ELF 0x3E9850: false (and the active condition cleared) when the name exists. + bool createConstantCondition(std::string name, StrategyCondition::CompareType compareType, + StrategyCondition::Compare compare, + StrategyCondition::ConditionSide side, + StrategyCondition::Conditional conditional, float constant); + // Each creator clears the active condition and returns false for a duplicate name. + bool createHomogenousCondition(std::string name, StrategyCondition::CompareType compareType, + StrategyCondition::Compare compare, + StrategyCondition::Conditional conditional); + bool createHeterogeneousCondition(std::string name, StrategyCondition::CompareType compareType, + StrategyCondition::Compare compare, + StrategyCondition::ConditionSide side, + StrategyCondition::Conditional first, + StrategyCondition::Conditional second); + bool createAreaCondition(std::string name, std::string areaName, StatusMap::Status status); // the layout, from the 545-byte constructor cross-checked against the destructor // the three registries each come as A (name, active-pointer, map) triple, in the same order. diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/AIAdapterTypes.h b/Code/BF2/AI/AIInterface/BFKnowledge/AIAdapterTypes.h index 5b63f1a65..513908481 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/AIAdapterTypes.h +++ b/Code/BF2/AI/AIInterface/BFKnowledge/AIAdapterTypes.h @@ -23,7 +23,8 @@ class IProjectileObject; // `dice::hfe::ChannelMessageType` - BFRadioComm::sendAIRadioMessage's second parameter // (`NS0_18ChannelMessageType`, i.e. hfe scope, not ai). Passed by value; an opaque enum with an -// explicit `int` base gives it the 4-byte slot the call frame shows. [FRONTIER] its enumerators. +// explicit `int` base gives it the 4-byte slot the call frame shows. [CHOSEN] opaque here: the AI +// only passes values through; the enumerators belong to the engine side (Game/IGame.h). enum ChannelMessageType : int; // `dice::hfe::KitType` - KitTemplateManager::getTemplate's parameter (`NS0_7KitType`). @@ -43,7 +44,17 @@ class AIObjectPredicate virtual bool predicate(IAIObject* object) = 0; // +0x00, both images }; -class DestroyableObject; // BFObjectEnvironment::getAllDestroyableObjects, by value in a vector +// Object-local navigation bounds and transformation, returned by getAllDestroyableObjects. +// ELF bf2 0x8401390 writes the byte, both vectors and the complete matrix; libaidll's +// drawDynamicAIObjects consumes a 92-byte element. Member names are [INFERRED]. +class DestroyableObject +{ +public: + /* +0x00 */ bool initiallyWalkable; + /* +0x04 */ Vec3 min; + /* +0x10 */ Vec3 max; + /* +0x1C */ Mat4 transform; +}; class TargetData; // BFObjectEnvironment::getTargetObjects, likewise class IWeapon; // BFObjectEnvironment::hasIndirectLineOfFire class IKitTemplate; // KitTemplateManager's two containers diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/AIFrontier.h b/Code/BF2/AI/AIInterface/BFKnowledge/AIFrontier.h deleted file mode 100644 index 744e92009..000000000 --- a/Code/BF2/AI/AIInterface/BFKnowledge/AIFrontier.h +++ /dev/null @@ -1,20 +0,0 @@ -// [CHOSEN, not recovered] Reports an unimplemented method to stderr, flushes, and aborts. -// The argument must be its fully qualified name as a string literal. This macro never returns. -// [RETIRE-WHEN: aidll-01-adapters] Remove after all adapter bodies are implemented and validated. - -#ifndef AI_AIINTERFACE_BFKNOWLEDGE_AIFRONTIER_H -#define AI_AIINTERFACE_BFKNOWLEDGE_AIFRONTIER_H - -#include -#include - -#define BF2_AI_FRONTIER(qualifiedName) \ - do \ - { \ - std::fprintf(stderr, "[FRONTIER] " qualifiedName " reached\n"); \ - std::fflush(stderr); \ - std::abort(); \ - } \ - while (false) - -#endif // AI_AIINTERFACE_BFKNOWLEDGE_AIFRONTIER_H diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/AIObjectMobile.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/AIObjectMobile.cpp index 65f86d55e..3fe2fa5b2 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/AIObjectMobile.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/AIObjectMobile.cpp @@ -1,12 +1,7 @@ -// [FRONTIER] Remaining methods stop by name until implemented. -// [TEMP] Temporary implementation boundaries remain. -// [RETIRE-WHEN: aidll-07-knowledge] Complete and validate the remaining AIObjectMobile operations. - #include "AIObjectMobile.h" #include -#include "AIFrontier.h" #include "AITemplateMobile.h" #include "../SingletonServer.h" // BFSingletonServer::m_iInformationFactory @@ -16,6 +11,8 @@ #include "../../AIDLL/AI/Main/CommonSingletonServer.h" #include "../../../Core/Ids.h" +#include "../../../Core/Debug.h" +#include "../../../Scene/Object/WorldObjTemplPortal/PortalEvent.h" #include "../../../Game/Objects/IObject.h" #include "../../../Game/Objects/ISoldier.h" #include "../../../Game/Objects/ObjectLayoutAccess.h" // IObject +0x44, the physics node @@ -229,14 +226,16 @@ float AIObjectMobile::getSprintStamina() const return 0.0f; } -// read: type 0 stores the event's portal id in -// the owner's m_lastPassedPortal, type 1 stores -1, and anything else is retail's -// Debug(Error, "AI/AIInterface/BFKnowledge/AIObjectMobile.cpp", 57) "Unwanted event sent to -// callback". It needs world::PortalEvent::getType / getPortalId, which this tree does not declare. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-07-knowledge] -void AIObjectMobile::PortalEventCallback::handleEvent(world::PortalEvent* /*event*/) +// ELF 0x8417450. Preserve the repeated type query before the leave-sector branch. +void AIObjectMobile::PortalEventCallback::handleEvent(world::PortalEvent* event) { - BF2_AI_FRONTIER("dice::hfe::ai::AIObjectMobile::PortalEventCallback::handleEvent (world::PortalEvent)"); + if (event->getType() == world::PORTAL_EVENT_ENTER_SECTOR) + m_owner->m_lastPassedPortal = static_cast(event->getPortalId()); + else if (event->getType() == world::PORTAL_EVENT_LEAVE_SECTOR) + m_owner->m_lastPassedPortal = -1; + else + Debug(DebugTypeError, "AI/AIInterface/BFKnowledge/AIObjectMobile.cpp", 57) + << "Unwanted event sent to callback"; } } // namespace ai diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/AIObjectMobile.h b/Code/BF2/AI/AIInterface/BFKnowledge/AIObjectMobile.h index 524e15817..f571cf47a 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/AIObjectMobile.h +++ b/Code/BF2/AI/AIInterface/BFKnowledge/AIObjectMobile.h @@ -25,7 +25,7 @@ class AIObjectMobile : public IAIObjectMobile { public: explicit PortalEventCallback(AIObjectMobile* owner) : m_owner(owner) {} - virtual void handleEvent(world::PortalEvent* event); // [FRONTIER] + virtual void handleEvent(world::PortalEvent* event); private: /* +0x04 */ AIObjectMobile* m_owner; diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/AIObjectPhysical.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/AIObjectPhysical.cpp index 3e750de93..3faf7c3b6 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/AIObjectPhysical.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/AIObjectPhysical.cpp @@ -1,12 +1,8 @@ // [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. -// [TEMP] Temporary implementation boundaries remain. -// [CHOSEN, not recovered] Temporary implementation boundaries remain. -// [RETIRE-WHEN: aidll-07-knowledge] Complete and validate the remaining AIObjectPhysical operations. #include "AIObjectPhysical.h" -#include "AIFrontier.h" +#include "../../AIDLL/AI/AIUtils/checkPointer.h" #include "AITemplatePhysical.h" #include "BFGame.h" // IAIGame::getIsPrecaching (+0x68) @@ -18,15 +14,18 @@ #include "../../../Core/Ids.h" #include "../../../Game/Objects/DestroyableObjectTemplate.h" // usedByAi / initiallyWalkable / corners #include "../../../Game/Objects/GameLogicComp/IArmorGLComp.h" +#include "../../../Game/Objects/GameLogicComp/ArmorGLCompTemplate.h" // getTimeToStayAsWreck #include "../../../Game/Objects/IObject.h" #include "../../../Game/Objects/IObjectTemplate.h" #include "../../../Game/Objects/IPlayer.h" #include "../../../Game/Objects/ObjectLayoutAccess.h" #include "../../../Math/LocalBoundingBox.h" +#include "../../../Math/BoundingBox.h" #include "../../../Physics/ICollisionMesh.h" #include "../../../Physics/IPhysicsNode.h" #include "../../../Physics/IResponsePhysics.h" #include "../../../Physics/PhysicsUtil.h" // hfe::resetPhysics +#include "../../../Physics/SoldierResponse.h" // m_byteFA (+0xFA), a friend #include "../../../Scene/Object/ObjectTypes/Game/IPlayerControlObject.h" namespace dice { @@ -56,12 +55,14 @@ world::IResponsePhysics* responsePhysics(world::IObject* object) } // anonymous namespace // . +0x0C is left unwritten. +// ELF 0x8419940 / 0x8419980. AIObjectPhysical::AIObjectPhysical(IAIObject* object, AITemplatePhysical* aiTemplate) : IAIObjectPhysical(object), m_template(aiTemplate), m_physicsNode(0), m_mapPosId(-1) { } // A pathfinding-relevant object gives its map entry back. +// ELF 0x8419AD0 / 0x8419B30 / 0x8419B90. AIObjectPhysical::~AIObjectPhysical() { if (m_template->m_affectsPathfinding) @@ -69,12 +70,14 @@ AIObjectPhysical::~AIObjectPhysical() m_mapPosId, m_object); // +0xC4 } +// ELF 0x8419D00. int AIObjectPhysical::getId() const { return AIOFPhysical; } // - the factory's three-argument request under this plug-in's own id. +// ELF 0x8419BF0. void AIObjectPhysical::createInformationPlugIn(unsigned int handle, bool real) { informationFactory()->requestInformationPlugin(handle, getId(), real); // +0x20 @@ -87,6 +90,7 @@ void AIObjectPhysical::createInformationPlugIn(unsigned int handle, bool real) // announces itself as a bridge. // The template is cast to DestroyableObjectTemplate unchecked - only such templates can set // m_affectsPathfinding (AITemplatePhysical::initFromObject). +// ELF 0x84199C0. void AIObjectPhysical::init() { m_maxHealth = m_template->m_maxHealth; @@ -109,11 +113,13 @@ void AIObjectPhysical::init() } // empty. +// ELF 0x841A740. void AIObjectPhysical::update() { } // Returns 1,000,000 when there is no armour component. +// ELF 0x841A170. float AIObjectPhysical::getHealth() { world::IArmorGLComp* const armor = @@ -124,32 +130,38 @@ float AIObjectPhysical::getHealth() } // / - template reads. +// ELF 0x8419C40. float AIObjectPhysical::getMaxHealth() const { return m_template->m_maxHealth; } +// ELF 0x8419C50. float AIObjectPhysical::getMass() const { return m_template->m_mass; } +// ELF 0x8419CC0. float AIObjectPhysical::getVolume() const { return m_template->m_volume; } +// ELF 0x8419CE0. float AIObjectPhysical::getBestArmour() const { return m_template->m_bestArmour; } +// ELF 0x8419CF0. int AIObjectPhysical::getStrType() const { return m_template->m_strType; } // a constant, whatever the direction. +// ELF 0x8419CD0. float AIObjectPhysical::getArmour(const Vec3& /*direction*/) const { return 1.0f; @@ -157,6 +169,7 @@ float AIObjectPhysical::getArmour(const Vec3& /*direction*/) const // an object without collision LOD 1 calls abort - retail's own, not a // frontier. Otherwise the collision mesh's LOD-1 box. +// ELF 0x841A1A0. const LocalBoundingBox* AIObjectPhysical::getLocalBoundingBox() const { if (!m_object->getObject()->hasCollisionLod(1)) // +0xCC @@ -164,21 +177,33 @@ const LocalBoundingBox* AIObjectPhysical::getLocalBoundingBox() const return collisionMesh(m_object->getObject())->getBoundingBox(1); // +0x58 } -// `new BoundingBox` (0x60 B, eight zeroed corners), initWithLocalBoundingBox( -// getLocalBoundingBox), transform(object->getAbsoluteTransformation), checkPointer'd. The -// BoundingBox class is not in this tree. +// ELF 0x841A280. Allocation precedes the virtual queries; initialization follows them. BoundingBox* AIObjectPhysical::getCurrentBoundingBox() { - BF2_AI_FRONTIER("dice::hfe::ai::AIObjectPhysical::getCurrentBoundingBox (BoundingBox)"); + BoundingBox* const box = new BoundingBox; + const LocalBoundingBox* const local = getLocalBoundingBox(); + const Mat4& transformation = m_object->getObject()->getAbsoluteTransformation(); + for (int i = 0; i < 8; ++i) + box->m_corners[i] = Vec3{ 0.0f, 0.0f, 0.0f }; + box->initWithLocalBoundingBox(*local); + box->transform(transformation); + return checkPointer(box); } -// the same with the caller's transformation. -BoundingBox* AIObjectPhysical::getBoundingBox(const Mat4& /*transformation*/) +// ELF 0x841A400. +BoundingBox* AIObjectPhysical::getBoundingBox(const Mat4& transformation) { - BF2_AI_FRONTIER("dice::hfe::ai::AIObjectPhysical::getBoundingBox (BoundingBox)"); + BoundingBox* const box = new BoundingBox; + const LocalBoundingBox* const local = getLocalBoundingBox(); + for (int i = 0; i < 8; ++i) + box->m_corners[i] = Vec3{ 0.0f, 0.0f, 0.0f }; + box->initWithLocalBoundingBox(*local); + box->transform(transformation); + return checkPointer(box); } // The collision mesh's LOD-1 radius, 0 without that LOD. +// ELF 0x8419C60. float AIObjectPhysical::getRadius() const { if (!m_object->getObject()->hasCollisionLod(1)) // +0xCC @@ -188,6 +213,7 @@ float AIObjectPhysical::getRadius() const // The box centre, recomputed first when stale - through a const pointer, as // retail does (the derived data is cached state). +// ELF 0x841A200. Vec3 AIObjectPhysical::getSphereLocalOffset() const { LocalBoundingBox* const box = const_cast(getLocalBoundingBox()); // +0x30 @@ -197,6 +223,7 @@ Vec3 AIObjectPhysical::getSphereLocalOffset() const } // the radius about the centre. +// ELF 0x841A250. float AIObjectPhysical::getSmallestRadius() const { LocalBoundingBox* const box = const_cast(getLocalBoundingBox()); @@ -205,33 +232,89 @@ float AIObjectPhysical::getSmallestRadius() const return box->m_radiusFromCentre; } -// the LOD-1 box's longer horizontal side split into equal circles along its middle -// (pushed into `out` as Vec2), the step returned. Read; not yet transcribed. -float AIObjectPhysical::getSubSpheres2d(std::vector& /*out*/) const +// ELF 0x8419E50. Appends circles along the longer horizontal side; returns their spacing. +float AIObjectPhysical::getSubSpheres2d(std::vector& out) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIObjectPhysical::getSubSpheres2d"); + const LocalBoundingBox* const minimum = getLocalBoundingBox(); + const LocalBoundingBox* const maximum = getLocalBoundingBox(); + const float minX = minimum->m_min.x; + const float minZ = minimum->m_min.z; + const float width = maximum->m_max.x - minX; + const float depth = maximum->m_max.z - minZ; + if (depth > width) + { + if (width != 0.0f) + { + const float count = depth / width; + if (count > 1.0f) + { + Vec2 position = { minX + width * 0.5f, minZ }; + const float step = depth / (count + 1.0f); + for (int i = 0; static_cast(i) < count; ++i) + { + position.y += step; + out.push_back(position); + } + return step; + } + } + } + else if (width > depth && depth != 0.0f) + { + const float count = width / depth; + if (count > 1.0f) + { + Vec2 position = { minX, minZ + depth * 0.5f }; + const float step = width / (count + 1.0f); + for (int i = 0; static_cast(i) < count; ++i) + { + position.x += step; + out.push_back(position); + } + return step; + } + } + // shipped defect: both coordinates use x, with two independent virtual queries. + const float x = getSphereLocalOffset().x; + const float z = getSphereLocalOffset().x; + out.push_back(Vec2{ x, z }); + return getSmallestRadius(); } +// ELF 0x841A090. bool AIObjectPhysical::isTouchingTerrain(Vec3& out) const { return responsePhysics(m_object->getObject())->getIsIntersectingTerrain(out); // +0x7C } -// false while the physics node sleeps; a soldier answers the negation of a raw -// byte at +0xFA of its response physics (the soldier physics' ground flag - no class for it in this -// tree); anything else asks the node's getIsInAir (+0x1B0). +// bf2 0x841A0C0 (ELF listing). The ISoldier query comes first; then false while the physics node +// sleeps (+0x11C); a soldier answers the negation of its response physics' ground-contact byte +// (SoldierResponsePhysics +0xFA, the object asked for again); anything else asks the node's +// getIsInAir (+0x1B0). bool AIObjectPhysical::isInAir() const { - BF2_AI_FRONTIER("dice::hfe::ai::AIObjectPhysical::isInAir (soldier response physics +0xFA)"); + void* const soldier = m_object->getObject()->queryInterface(world::IID_ISoldier); // +0x0C + if (m_physicsNode->getIsSleeping()) // +0x11C + return false; + if (soldier) + { + const world::SoldierResponsePhysics* const response = + static_cast( + world::object_detail::LayoutAccess::responsePhysics(m_object->getObject())); + return !response->m_byteFA; + } + return m_physicsNode->getIsInAir(); // +0x1B0 } // strictly above zero (`setnbe` after fucomip - unordered is false). +// ELF 0x841A140. bool AIObjectPhysical::isInWater() const { return m_physicsNode->getUnderWater() > 0.0f; // +0x10C } // The engine object is asked for and discarded; the answer is always 0. +// ELF 0x841A560. int AIObjectPhysical::getMaterial() const { m_object->getObject(); @@ -240,6 +323,7 @@ int AIObjectPhysical::getMaterial() const // The occupying player's man-down clock, when it has a // control object, an occupant, and that occupant is down. The occupant is asked for twice. +// ELF 0x841A580. float AIObjectPhysical::getManDownTimeLeft() const { world::IPlayerControlObject* const pco = static_cast( @@ -252,14 +336,21 @@ float AIObjectPhysical::getManDownTimeLeft() const return player->getManDownTimeLeft(); // +0xF8 } -// the ArmorGLCompTemplate component's +0x110 accessor (not declared in this tree) -// 1.0 without the component. +// bf2 0x841A5F0 (ELF listing). The object's template component of class ArmorGLCompTemplate +// (IObjectTemplate +0x60, getComponentFromClassID) answers its +0x110 slot, which the ELF primary +// vtable (_ZTVN4dice3hfe5world19ArmorGLCompTemplateE) holds as getTimeToStayAsWreck; 1.0 without +// the component. float AIObjectPhysical::getMaxManDownTime() const { - BF2_AI_FRONTIER("dice::hfe::ai::AIObjectPhysical::getMaxManDownTime (ArmorGLCompTemplate +0x110)"); + world::ArmorGLCompTemplate* const armorTemplate = static_cast( + m_object->getObject()->getTemplate()->getComponentFromClassID(world::CID_ArmorGLCompTemplate)); + if (!armorTemplate) + return 1.0f; + return armorTemplate->getTimeToStayAsWreck(); // +0x110 } // status 1 on the armour component. +// ELF 0x841A640. bool AIObjectPhysical::getManDown() const { world::IArmorGLComp* const armor = @@ -269,11 +360,13 @@ bool AIObjectPhysical::getManDown() const return false; } +// ELF 0x841A680. bool AIObjectPhysical::doesAffectPathfinding() const { return m_template->m_affectsPathfinding; } +// ELF 0x841A730. int AIObjectPhysical::getMapPosId() const { return m_mapPosId; @@ -283,6 +376,7 @@ int AIObjectPhysical::getMapPosId() const // physics node and the response physics of the node's object are switched together, and an enable // resets the object's physics (hfe::resetPhysics, player control objects included). Both answer // true for the owning side whether or not anything changed. +// ELF 0x8419D90. bool AIObjectPhysical::enablePhysics(int side) { if (side != m_object->getSide()) // +0x12C @@ -296,6 +390,7 @@ bool AIObjectPhysical::enablePhysics(int side) return true; } +// ELF 0x8419D10. bool AIObjectPhysical::disablePhysics(int side) { if (side != m_object->getSide()) @@ -308,6 +403,7 @@ bool AIObjectPhysical::disablePhysics(int side) return true; } +// ELF 0x8419E30. bool AIObjectPhysical::hasPhysicsEnabled() { return m_physicsNode->getEnabled(); // +0x1C diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/AIObjectPhysical.h b/Code/BF2/AI/AIInterface/BFKnowledge/AIObjectPhysical.h index 4be6d8c5b..9e047183f 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/AIObjectPhysical.h +++ b/Code/BF2/AI/AIInterface/BFKnowledge/AIObjectPhysical.h @@ -34,19 +34,20 @@ class AIObjectPhysical : public IAIObjectPhysical virtual float getArmour(const Vec3& direction) const; // +0x28 virtual float getBestArmour() const; // +0x2C virtual const LocalBoundingBox* getLocalBoundingBox() const; // +0x30 - virtual BoundingBox* getCurrentBoundingBox(); // +0x34, [FRONTIER] - virtual BoundingBox* getBoundingBox(const Mat4& transformation); // +0x38, [FRONTIER] + // Returns a new transformed box; the caller owns it. + virtual BoundingBox* getCurrentBoundingBox(); // +0x34 + virtual BoundingBox* getBoundingBox(const Mat4& transformation); // +0x38 virtual float getRadius() const; // +0x3C virtual Vec3 getSphereLocalOffset() const; // +0x40 virtual float getSmallestRadius() const; // +0x44 - virtual float getSubSpheres2d(std::vector& out) const; // +0x48, [FRONTIER] + virtual float getSubSpheres2d(std::vector& out) const; // +0x48 virtual int getStrType() const; // +0x4C virtual bool isTouchingTerrain(Vec3& out) const; // +0x50 - virtual bool isInAir() const; // +0x54, [FRONTIER] + virtual bool isInAir() const; // +0x54 virtual bool isInWater() const; // +0x58 virtual int getMaterial() const; // +0x5C virtual float getManDownTimeLeft() const; // +0x60 - virtual float getMaxManDownTime() const; // +0x64, [FRONTIER] + virtual float getMaxManDownTime() const; // +0x64 virtual bool getManDown() const; // +0x68 virtual bool doesAffectPathfinding() const; // +0x6C virtual int getMapPosId() const; // +0x70 diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/AIPlayer.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/AIPlayer.cpp index 47adedbd5..c3dbeb44c 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/AIPlayer.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/AIPlayer.cpp @@ -1,10 +1,10 @@ // Engine implementation of the AI player interface. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. // [INFERRED] Source placement. #include "AIPlayer.h" -#include "AIFrontier.h" +#include +#include #include "../../AIDLL/AI/Main/CommonSingletonServer.h" #include "../../AIDLL/AI/AIUtils/checkPointer.h" @@ -12,10 +12,14 @@ #include "../../../Game/GameLogic/Player.h" // world::IPlayer - every forward's target #include "../../../Game/Objects/IObject.h" // getTemplate #include "../../../Game/Objects/IObjectTemplate.h" // getClassID +#include "../../../Game/Objects/ICameraObject.h" // getCameraTransformation #include "../../../Math/Mat4.h" // the lazily built identity matrix #include "../../../Scene/Object/PlayerManager.h" // the `playerManager` global #include "../../../Scene/Object/ObjectTypes/Game/IPlayerControlObject.h" -#include "AIPlayerFactory.h" // the id-to-player mapping pair +#include "AIPlayerFactory.h" +#include "../../../Game/IGameLogic.h" // gameLogic - removePlayerFromGame +#include "../AIInstance.h" // the AI instance test in the destructor +#include "../../AIDLL/AI/Main/AISettingsInterfaces.h" // setBotNameUnused // the id-to-player mapping pair namespace dice { namespace hfe { @@ -25,11 +29,12 @@ namespace ai { Mat4* AIPlayer::identityMatrix = 0; // The interface destructor has no additional cleanup. +// ELF 0x83FCB40 / 0x83FCB50. IAIPlayer::~IAIPlayer() { } -// Wraps the supplied player and initializes view distance from its current value. +// ELF 0x83FBA60 / 0x83FBC30. Wraps the supplied player and initializes view distance from its current value. // The player is borrowed and must outlive this wrapper. AIPlayer::AIPlayer(world::IPlayer* player) : m_player(player) @@ -40,42 +45,61 @@ AIPlayer::AIPlayer(world::IPlayer* player) if (!identityMatrix) { - Mat4* const matrix = checkPointer(new Mat4); + Mat4* const matrix = new Mat4{{ + 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f + }}; + identityMatrix = checkPointer(matrix); // Preserves the repeated identity-matrix stores, including diagonal indices 0, 5, 10, and 15. matrix->m[0] = 1.0f; matrix->m[1] = 0.0f; matrix->m[2] = 0.0f; matrix->m[3] = 0.0f; matrix->m[4] = 0.0f; matrix->m[5] = 1.0f; matrix->m[6] = 0.0f; matrix->m[7] = 0.0f; matrix->m[8] = 0.0f; matrix->m[9] = 0.0f; matrix->m[10] = 1.0f; matrix->m[11] = 0.0f; matrix->m[12] = 0.0f; matrix->m[13] = 0.0f; matrix->m[14] = 0.0f; matrix->m[15] = 1.0f; - - identityMatrix = matrix; } } -// - eight bytes longer than the `(IPlayer*)` form and not read. -// The extra length is presumably the null player it starts from; nothing in this tree calls it. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] +// ELF 0x83FBE00 / 0x83FBFD0. An unattached wrapper shares the same lazy identity matrix. AIPlayer::AIPlayer() + : m_player(0) + , m_i8(0) + , m_viewDistance(0.0f) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayer::AIPlayer()"); + if (!identityMatrix) + { + Mat4* const matrix = new Mat4{{ + 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f + }}; + identityMatrix = checkPointer(matrix); + matrix->m[0] = 1.0f; matrix->m[1] = 0.0f; matrix->m[2] = 0.0f; matrix->m[3] = 0.0f; + matrix->m[4] = 0.0f; matrix->m[5] = 1.0f; matrix->m[6] = 0.0f; matrix->m[7] = 0.0f; + matrix->m[8] = 0.0f; matrix->m[9] = 0.0f; matrix->m[10] = 1.0f; matrix->m[11] = 0.0f; + matrix->m[12] = 0.0f; matrix->m[13] = 0.0f; matrix->m[14] = 0.0f; matrix->m[15] = 1.0f; + } } -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -// Destruction remains unimplemented; AIPlayerFactory::destroy reaches this boundary. +// bf2 0x83FC280: while the AI instance (0x8AC37F8) exists and is not shutting down, a bot's +// name goes back to the pool (IAISettingsModifier +0x94 setBotNameUnused). +// ELF 0x83FC1A0 / 0x83FC210 / 0x83FC280. AIPlayer::~AIPlayer() { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayer::~AIPlayer"); + if (g_aiInstance && !aiInstance()->isShuttingDown() && m_player && getIsAIPlayer()) + static_cast(CommonSingletonServer::m_iaiSettingsModifier) + ->setBotNameUnused(m_player->getName()); } // Delegates to the wrapped engine player through the typed interface. // - and it resets the one field that is genuinely this object's, not the // player's. A recycled `AIPlayer` therefore keeps its view distance; only +8 is cleared. +// ELF 0x83FC300. void AIPlayer::reset() { m_i8 = 0; } +// ELF 0x83FC440. world::IPlayer* AIPlayer::getPlayer() const { return m_player; @@ -83,6 +107,7 @@ world::IPlayer* AIPlayer::getPlayer() const // it resolves the ID and then calls its own virtual slot +0x14 - a virtual // self-call, not a direct one, so an override of the pointer form would catch this path too. +// ELF 0x83FC310. void AIPlayer::setPlayer(int playerId) { setPlayer(world::playerManager->getPlayerFromId(playerId)); @@ -90,6 +115,7 @@ void AIPlayer::setPlayer(int playerId) // Replaces the factory id mapping when the player changes. Seeds view distance only // when its current value equals zero; NaN is left unchanged. +// ELF 0x83FC350. void AIPlayer::setPlayer(world::IPlayer* player) { IAIPlayerFactory* const factory = @@ -108,12 +134,14 @@ void AIPlayer::setPlayer(world::IPlayer* player) } // - IPlayer +0x24. +// ELF 0x83FC450. const std::string& AIPlayer::getName() const { return m_player->getName(); } // - IPlayer +0x54. +// ELF 0x83FC4C0. int AIPlayer::getId() const { return m_player->getId(); @@ -121,30 +149,35 @@ int AIPlayer::getId() const // - IPlayer +0x50. A different number from `getId`, and the two slots are // adjacent on both classes; do not collapse them. +// ELF 0x83FC4E0. int AIPlayer::getInputId() const { return m_player->getInputId(); } // - IPlayer +0x6C, narrowed with `movzx`. +// ELF 0x83FC500. bool AIPlayer::getIsAlive() const { return m_player->getIsAlive(); } // - IPlayer +0x68. +// ELF 0x83FC520. void AIPlayer::setIsAlive(bool alive) { m_player->setIsAlive(alive); } // - IPlayer +0x100. +// ELF 0x83FC550. bool AIPlayer::isManDown() const { return m_player->getIsManDown(); } // Checks the current vehicle template to identify ladder and parachute states. +// ELF 0x83FC570. bool AIPlayer::isClimbingLadder() const { world::IObject* const vehicle = m_player->getVehicle(); @@ -155,6 +188,7 @@ bool AIPlayer::isClimbingLadder() const return vehicle->getTemplate()->getClassID() == world::CID_LadderContainerTemplate; } +// ELF 0x83FC5B0. bool AIPlayer::isParachuting() const { world::IObject* const vehicle = m_player->getVehicle(); @@ -166,6 +200,7 @@ bool AIPlayer::isParachuting() const } // - IPlayer +0x154. +// ELF 0x83FC610. void AIPlayer::setSpawnGroup(int group) { m_player->setSpawnGroup(group); @@ -173,6 +208,7 @@ void AIPlayer::setSpawnGroup(int group) // forward the selected kit unchanged to // IPlayer::setKit (ELF +0x16C / PE +0x168), with no player-null guard or validation. +// ELF 0x83FC640. void AIPlayer::setSpawnKit(int kit) { m_player->setKit(kit); @@ -180,6 +216,7 @@ void AIPlayer::setSpawnKit(int kit) // - IPlayer +0x90, `getFov`. this is what corrected the declared return type: // the body materialises nothing in eax and leaves the player's float in st0. +// ELF 0x83FC880. float AIPlayer::getFieldOfView() { return m_player->getFov(); @@ -187,41 +224,82 @@ float AIPlayer::getFieldOfView() // - IPlayer +0x9C, `getAIPlayerInput`. the player has A separate input block // for AI, and this is the slot that hands it over; the name on the player side says so outright. +// ELF 0x83FC5F0. const void* AIPlayer::getPlayerInput() const { return m_player->getAIPlayerInput(); } -// [FRONTIER] Unimplemented player queries and actions stop by name. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding AIPlayer operation. - +// ELF 0x83FC670. int AIPlayer::getSpawnGroup() const { // IPlayer virtual +0x158/+0x154, without a null guard or value conversion. return m_player->getSpawnGroup(); } +// ELF 0x83FC690. int AIPlayer::getSpawnKit() const { // IPlayer virtual +0x170/+0x16C, with no null guard or value conversion. return m_player->getKit(); } +// bf2 0x83FC6B0. Without a vehicle -1. Otherwise the first player control object on the +// vehicle's parent chain (queryInterface IID_IPlayerControlObject, then IObject +0x28) answers +// its PCO id (+0x30). Ladder, parachute, zipline and rope containers first hop to the object +// their control object occupies (+0x14) and search from there. A chain without one reads +// through a null pointer, as the ELF does. +namespace { +world::IPlayerControlObject* findControlObject(world::IObject* object) +{ + for (; object; object = object->getParent()) + { + world::IPlayerControlObject* const control = static_cast( + object->queryInterface(world::IID_IPlayerControlObject)); + if (control) + return control; + } + return 0; +} +} // anonymous namespace + +// ELF 0x83FC6B0. unsigned int AIPlayer::getPlayerControlObjectId() { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayer::getPlayerControlObjectId"); + // The ELF reads the template before its null test (a null vehicle faults there); testing + // first keeps the C++ defined. [CHOSEN, not recovered] ordering only. + world::IObject* const vehicle = m_player->getVehicle(); + if (!vehicle) + return static_cast(-1); + const unsigned int classId = vehicle->getTemplate()->getClassID(); + if (classId == world::CID_LadderContainerTemplate || classId == world::CID_ParachuteTemplate || + classId == world::CID_ZiplineContainerTemplate || + classId == world::CID_GrapplingHookRopeContainerTemplate) + { + world::IObject* const occupied = findControlObject(vehicle)->getOccupingObject(); + return static_cast(findControlObject(occupied)->getPcoId()); + } + return static_cast(findControlObject(vehicle)->getPcoId()); } +// bf2 0x83FC7C0: the default vehicle's AI component; a player without one aborts (the ELF +// calls abort directly - an inlined assertion). +// ELF 0x83FC7C0. IAIObject* AIPlayer::getSoldier() { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayer::getSoldier"); + if (!m_player->getDefaultVehicle()) + std::abort(); + return static_cast(m_player->getDefaultVehicle()->getAIComponent()); } +// bf2 0x83FC7A0: IPlayer +0xA4, then the object's cached AI component (+0x34), unchecked. +// ELF 0x83FC7A0. IAIObject* AIPlayer::getDefaultVehicle() { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayer::getDefaultVehicle"); + return static_cast(m_player->getDefaultVehicle()->getAIComponent()); } +// ELF 0x83FC800. IAIObject* AIPlayer::getCurrentVehicle() { // One vehicle lookup; no template/occupant guards. @@ -243,28 +321,51 @@ IAIObject* AIPlayer::getCurrentVehicle() return static_cast(vehicle->getAIComponent()); } +// bf2 0x83FC8B0. Without a camera (IPlayer +0x180) 1.0. Otherwise cot(fov / 2) scaled by a +// function static cot(0.6f) built on first use (0x8AC3310 flag, 0x8AC3318 value, 1.0f / tan). +// [PLATFORM] the ELF keeps the quotients in x87 extended precision. +// ELF 0x83FC8B0. float AIPlayer::getFieldOfViewModifier() { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayer::getFieldOfViewModifier"); + if (!m_player->getCamera()) + return 1.0f; + static bool s_initialised = false; + static float s_standardCotangent; + if (!s_initialised) + { + const float standard = 0.6f; + s_initialised = true; + s_standardCotangent = 1.0f / (sinf(standard) / cosf(standard)); + } + const float half = m_player->getFov() * 0.5f; + return (cosf(half) / sinf(half)) * s_standardCotangent; } +// bf2: `flds` of the 1.2f constant at 0x889AA58. +// ELF 0x83FC8A0. float AIPlayer::getStandardFieldOfView() { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayer::getStandardFieldOfView" - " - eleven bytes, one float constant at ds:0x889AA58, not yet read"); + return 1.2f; } +// bf2 0x83FC960: a fifth of the stored distance (0.2f at 0x8899EF0) on night maps +// (IPlayer +0x2FC), reached through this wrapper's own getPlayer (+0x0C). +// ELF 0x83FC960. float AIPlayer::getViewDistance() { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayer::getViewDistance"); + if (getPlayer()->isPlayerInNightMap()) + return 0.2f * m_viewDistance; + return m_viewDistance; } -void AIPlayer::setViewDistance(float) +// bf2: a plain store to +0x0C. +// ELF 0x83FC9A0. +void AIPlayer::setViewDistance(float distance) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayer::setViewDistance" - " - fourteen bytes; AISettings::setViewDistance reaches it once per live bot"); + m_viewDistance = distance; } +// ELF 0x83FC9B0. int AIPlayer::getSide() { // unchecked IPlayer::getTeam forward. @@ -273,49 +374,76 @@ int AIPlayer::getSide() // forward the side and false to // IPlayer::setTeam (ELF +0xE4 / PE +0xE0), with no player-null guard. +// ELF 0x83FC9D0. void AIPlayer::setSide(int side) { m_player->setTeam(side, false); } +// bf2 0x83FCA00 (seven bytes, `xor %eax,%eax`): always 0; the weapon is not read. +// ELF 0x83FCA00. int AIPlayer::getNumShotsFired(IWeapon*) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayer::getNumShotsFired" - " - seven bytes, so it returns a constant and ignores the weapon"); + return 0; } +// bf2 0x83FC3D0 (recovered on the client track). The singleton at +// ds:0x8AC37F8 is AIInstanceServer::m_iAI (g_aiInstance here); +0x20 is isShuttingDown. While the +// AI is not shutting down, a live player (IPlayer +0x6C) is killed through the game logic +// (ds:0x8ACBFA0, IGameLogic +0x6C, killPlayer(player, true, false)). The instance is not null- +// tested, as shipped. +// ELF 0x83FC3D0. void AIPlayer::removePlayerFromGame() { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayer::removePlayerFromGame" - " - read except for the singleton at ds:0x8AC37F8"); + if (aiInstance()->isShuttingDown()) + return; + if (m_player && m_player->getIsAlive()) + gameLogic->killPlayer(m_player, true, false); } -void AIPlayer::setName(const std::string&) +// bf2 0x83FCA10: IPlayer +0x20. +// ELF 0x83FCA10. +void AIPlayer::setName(const std::string& name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayer::setName"); + m_player->setName(name); } +// bf2 0x83FCA40: the first int of the player's score data (IPlayer +0x174), 0 without one. +// [UNRESOLVED] PlayerScoreData's layout; only its leading score word is read here. +// ELF 0x83FCA40. int AIPlayer::getScore() { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayer::getScore"); + world::PlayerScoreData* const data = m_player->getScoreData(); + return data ? *reinterpret_cast(data) : 0; } -void AIPlayer::setIsAIPlayer(bool) +// bf2 0x83FCA70: IPlayer +0x60. +// ELF 0x83FCA70. +void AIPlayer::setIsAIPlayer(bool isAI) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayer::setIsAIPlayer"); + m_player->setIsAIPlayer(isAI); } // forward the player's // Boolean query through IPlayer (+0x64 / +0x60), with no null guard. +// ELF 0x83FCAA0. bool AIPlayer::getIsAIPlayer() { return m_player->getIsAIPlayer(); } +// bf2 0x83FC470: the player's camera (IPlayer +0x180 getCamera) as a world::IObject +// (queryInterface(IID_IObject), +0x0C) gives its absolute transformation (IObject +0x84); without +// a camera the shared identity matrix. The result is the Mat4's address. +// ELF 0x83FC470. const void* AIPlayer::getCameraTransformation() const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayer::getCameraTransformation" - " - read in outline; the camera object's transform slot is not confirmed"); + world::ICameraObject* const camera = m_player->getCamera(); + if (!camera) + return identityMatrix; + const world::IObject* const object = + static_cast(camera->queryInterface(world::IID_IObject)); + return &object->getAbsoluteTransformation(); } } // namespace ai diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/AIPlayer.h b/Code/BF2/AI/AIInterface/BFKnowledge/AIPlayer.h index 632ef4a6a..879cb8a1f 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/AIPlayer.h +++ b/Code/BF2/AI/AIInterface/BFKnowledge/AIPlayer.h @@ -1,6 +1,5 @@ // AI view of an engine player, implemented by AIPlayer in the executable. // [INFERRED] Return types are derived from implementations; preserve virtual declaration order. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. // [INFERRED] Source placement. #ifndef AI_AIINTERFACE_BFKNOWLEDGE_AIPLAYER_H // [INFERRED] guard style @@ -66,13 +65,12 @@ class IAIPlayer // Forwards player state and actions to a borrowed world::IPlayer. // The wrapped player must outlive this object. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. class AIPlayer : public IAIPlayer { public: explicit AIPlayer(world::IPlayer* player); - AIPlayer(); // [FRONTIER] - virtual ~AIPlayer(); // [FRONTIER] + AIPlayer(); + virtual ~AIPlayer(); virtual void reset(); virtual world::IPlayer* getPlayer() const; @@ -90,24 +88,24 @@ class AIPlayer : public IAIPlayer virtual void setSpawnKit(int kit); virtual int getSpawnGroup() const; virtual int getSpawnKit() const; // forwards getKit - virtual unsigned int getPlayerControlObjectId(); // [FRONTIER] - virtual IAIObject* getSoldier(); // [FRONTIER] - virtual IAIObject* getDefaultVehicle(); // [FRONTIER] + virtual unsigned int getPlayerControlObjectId(); + virtual IAIObject* getSoldier(); + virtual IAIObject* getDefaultVehicle(); virtual IAIObject* getCurrentVehicle(); virtual float getFieldOfView(); - virtual float getFieldOfViewModifier(); // [FRONTIER] - virtual float getStandardFieldOfView(); // [FRONTIER] - virtual float getViewDistance(); // [FRONTIER] - virtual void setViewDistance(float distance); // [FRONTIER] + virtual float getFieldOfViewModifier(); + virtual float getStandardFieldOfView(); + virtual float getViewDistance(); + virtual void setViewDistance(float distance); virtual int getSide(); - virtual void setSide(int side); // [FRONTIER] - virtual int getNumShotsFired(IWeapon* weapon); // [FRONTIER] - virtual void removePlayerFromGame(); // [FRONTIER] - virtual void setName(const std::string& name); // [FRONTIER] - virtual int getScore(); // [FRONTIER] - virtual void setIsAIPlayer(bool isAI); // [FRONTIER] + virtual void setSide(int side); + virtual int getNumShotsFired(IWeapon* weapon); + virtual void removePlayerFromGame(); // bf2 0x83FC3D0 + virtual void setName(const std::string& name); + virtual int getScore(); + virtual void setIsAIPlayer(bool isAI); virtual bool getIsAIPlayer(); - virtual const void* getCameraTransformation() const; // [FRONTIER] + virtual const void* getCameraTransformation() const; virtual const void* getPlayerInput() const; // ds: - one `Mat4`, allocated by whichever `AIPlayer` is constructed first and never diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/AIPlayerFactory.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/AIPlayerFactory.cpp index 96e77d1eb..08e34364a 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/AIPlayerFactory.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/AIPlayerFactory.cpp @@ -1,19 +1,17 @@ // [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. -// [TEMP] Temporary implementation boundaries remain. -// [CHOSEN, not recovered] Temporary implementation boundaries remain. -// [RETIRE-WHEN: aidll-01-adapters] Complete and validate the remaining AIPlayerFactory operations. #include "AIPlayerFactory.h" - -#include "AIFrontier.h" +#include #include "AIPlayer.h" // the concrete wrapper this creates +#include "IAIObject.h" // isOccupiedObject +#include "IAIObjectPlugIn.h" // IAIObjectUnit::isOccupied #include "../../AIDLL/AI/AIUtils/checkPointer.h" #include "../../../Game/GameLogic/Player.h" // world::IPlayer::getId #include "../../AIDLL/AI/Main/CommonSingletonServer.h" #include "../../../Core/ClassManager.h" +#include "../../../Scene/Object/PlayerManager.h" // the player lookups #include "../SingletonServer.h" // BFSingletonServer::updateStaticMethods namespace dice { @@ -23,7 +21,30 @@ extern ClassManager* classManager; namespace ai { +// bf2 0x842B700. The primary object's unit is tested first (null unit: false); the secondary +// objects' units are not null-checked (`call *0x48(%eax)` straight after getUnit), as in the image. +bool isOccupiedObject(IAIObject* object, IAIObject* exclude) +{ + IAIObject* const primary = object->getPrimaryObject(); // +0xFC + IAIObjectUnit* const unit = primary->getUnit(); // +0x98 + if (!unit) + return false; + if (exclude != primary && unit->isOccupied()) // IAIObjectUnit +0x48 + return true; + int iterator; + for (IAIObject* secondary = primary->getFirstSecondaryObject(iterator); // +0x11C + secondary; + secondary = primary->getSecondaryObject(iterator)) // +0x114 + { + IAIObjectUnit* const secondaryUnit = secondary->getUnit(); + if (exclude != secondary && secondaryUnit->isOccupied()) + return true; + } + return false; +} + // First wins in, exact match out. +// ELF 0x842DDA0 / 0x842DE30. IAIPlayerFactory::IAIPlayerFactory() { if (!CommonSingletonServer::m_iaiPlayerFactory) @@ -34,6 +55,7 @@ IAIPlayerFactory::IAIPlayerFactory() } } +// ELF 0x842DEC0 / 0x842DF40 / 0x842DFC0. IAIPlayerFactory::~IAIPlayerFactory() { if (CommonSingletonServer::m_iaiPlayerFactory == this) @@ -47,34 +69,43 @@ IAIPlayerFactory::~IAIPlayerFactory() // The ELF's _M_fill_insert / erase pair on an empty vector is `resize(256, 0)` - libstdc++ 3.x // expands resize into exactly that branch. 256 is the player-id space, so the vector is an // id-indexed table from the first instruction. +// ELF 0x842B7B0 / 0x842B850. AIPlayerFactory::AIPlayerFactory() { m_players.resize(256, 0); } +// ELF 0x842B8F0 / 0x842B970 / 0x842B9F0. AIPlayerFactory::~AIPlayerFactory() { } -// Creation overloads identify unsupported paths by their argument types in frontier diagnostics. - +// ELF 0x842BA80. Creates an unattached wrapper without inserting it into the id table. IAIPlayer* AIPlayerFactory::create() { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayerFactory::create()"); + return checkPointer(new AIPlayer()); } +// bf2 0x842BBA0: the player manager's player by id, wrapped through this factory's own +// create(IPlayer*) (+0x14); null for an unknown id. +// ELF 0x842BBA0. IAIPlayer* AIPlayerFactory::create(int id) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayerFactory::create(int)"); + world::IPlayer* const player = world::playerManager->getPlayerFromId(id); + return player ? create(player) : 0; } +// bf2 0x842BBE0: the same by name (+0x1C getPlayerFromName). +// ELF 0x842BBE0. IAIPlayer* AIPlayerFactory::create(const std::string& name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayerFactory::create(const std::string&)"); + world::IPlayer* const player = world::playerManager->getPlayerFromName(name); + return player ? create(player) : 0; } // Wraps a player and stores it at its player id. The caller must size m_players first; // this function neither grows the vector nor checks the index. +// ELF 0x842BC20. IAIPlayer* AIPlayerFactory::create(world::IPlayer* player) { AIPlayer* const created = checkPointer(new AIPlayer(player)); @@ -85,14 +116,32 @@ IAIPlayer* AIPlayerFactory::create(world::IPlayer* player) return created; } +// bf2 0x842BDC0: the table slot is cleared by id while the wrapper has a player, else by +// searching for the pointer; the wrapper is then deleted (null tolerated by the test before the +// deleting destructor). +// ELF 0x842BDC0. void AIPlayerFactory::destroy(IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayerFactory::destroy"); + if (player->getPlayer()) + { + m_players[player->getId()] = 0; + } + else + { + const std::vector::iterator it = std::find(m_players.begin(), m_players.end(), player); + if (it != m_players.end()) + *it = 0; + } + if (player) + delete player; } +// bf2: the named player's id (IPlayer +0x54), or -1. +// ELF 0x842BE80. int AIPlayerFactory::getPlayerIdFromName(const std::string& name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayerFactory::getPlayerIdFromName"); + world::IPlayer* const player = world::playerManager->getPlayerFromName(name); + return player ? player->getId() : -1; } // IAIPlayerFactory's ELF slot +0x20 @@ -107,25 +156,32 @@ IAIPlayer* AIPlayerFactory::getPlayerFromId(int id) return m_players[id]; } +// bf2: unchecked store at the wrapper's id (IAIPlayer +0x1C). +// ELF 0x842BD60. void AIPlayerFactory::setIdToPlayerMapping(IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayerFactory::setIdToPlayerMapping"); + m_players[player->getId()] = player; } +// ELF 0x842BD90. void AIPlayerFactory::removeIdToPlayerMapping(IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayerFactory::removeIdToPlayerMapping"); + m_players[player->getId()] = 0; } // - a bare member load, so it hands back the vector itself. +// ELF 0x842BE70. const std::vector& AIPlayerFactory::getAllPlayers() { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayerFactory::getAllPlayers"); + return m_players; } +// bf2: the local human (+0x30 getLocalHumanPlayer) looked up by id, null without one. +// ELF 0x842BEC0. IAIPlayer* AIPlayerFactory::getPlayerFromLocalHumanPlayer() { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayerFactory::getPlayerFromLocalHumanPlayer"); + world::IPlayer* const player = world::playerManager->getLocalHumanPlayer(); + return player ? m_players[player->getId()] : 0; } } // namespace ai diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/AIPlayerFactory.h b/Code/BF2/AI/AIInterface/BFKnowledge/AIPlayerFactory.h index 1ad3a814b..af39dcff7 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/AIPlayerFactory.h +++ b/Code/BF2/AI/AIInterface/BFKnowledge/AIPlayerFactory.h @@ -20,6 +20,13 @@ class IBase; namespace ai { +class IAIObject; + +// bf2 0x842B700, the first function of AIPlayerFactory.cpp's text (exported, `T`): whether any +// unit of the object's primary object or of its secondary objects other than `exclude` is +// occupied. AIEventListener's vehicle-exit arm uses it. +bool isOccupiedObject(IAIObject* object, IAIObject* exclude); + class IAIPlayerFactory { public: diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFCollisionHandler.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/BFCollisionHandler.cpp index b5d43811d..7472bc1f2 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFCollisionHandler.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFCollisionHandler.cpp @@ -1,12 +1,7 @@ // [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. -// [TEMP] Temporary implementation boundaries remain. -// [CHOSEN, not recovered] Temporary implementation boundaries remain. -// [RETIRE-WHEN: aidll-01-adapters] Complete and validate the remaining BFCollisionHandler operations. #include "BFCollisionHandler.h" -#include "AIFrontier.h" #include "../../../Game/Objects/IObject.h" // getAbsolutePosition, the +0x6C / +0x68 slot #include "../../AIDLL/AI/Main/CommonSingletonServer.h" @@ -14,6 +9,23 @@ #include "../SingletonServer.h" // BFSingletonServer::updateStaticMethods #include "../../AIDLL/AI/AIUtils/checkPointer.h" #include "../../AIDLL/AI/Main/AISettingsInterfaces.h" // IAISettings::getMaxNBots - slot +0 +#include "../../AIDLL/AI/Main/AICollisionHandler.h" // IAICollisionHandler +0x14 - handleProjectileDamage +#include "IAIObject.h" +#include "IAIObjectPlugIn.h" // IAIObjectArmament / IAIObjectPhysical +#include "WeaponTemplateManager.h" +#include "WeaponTemplate.h" +#include "../../../Game/Objects/IObjectTemplate.h" +#include "../../../Game/Objects/IPlayer.h" +#include "../../../Game/Objects/Base/SimpleObjectTemplate.h" // m_aiTemplate (+0x128), friended +#include "../../../Game/Objects/ObjectLayoutAccess.h" // IObject +0x34, the AI object +#include "../../../Scene/Object/ObjectTypes/Base/ObjectTemplateManager.h" +#include "../../../Scene/Object/PlayerManager.h" +#include "../../../Core/Ids.h" // CID_SimpleObjectTemplate +#include "../../../Game/Objects/IObjectTemplateComponent.h" // getClassID +0x10 +#include "../../../Game/Objects/Projectiles/GenericProjectile.h" // IProjectileObject's implementor +#include "../../../Scene/Object/ObjectTypes/Game/IPlayerControlObject.h" +#include "../../AIDLL/AI/AIKnowledge/AIMineManager.h" // minePlaced +0x18 / mineRemoved +0x14 +#include namespace dice { namespace hfe { @@ -90,68 +102,329 @@ static bool botProjectileShortOfTarget(const Vec3& start, const Vec3& position, return dx * dx + dz * dz < passDistanceSq; } +// bf2 0x83FD2F0: every record is deleted, then the array - with scalar delete although the +// constructor allocated it with new[] (a shipped defect, kept: the element type is a plain +// pointer, so no array cookie is involved). The count is read live; with no bots (-1) the loop +// does not run and the null array is deleted. BFCollisionHandler::~BFCollisionHandler() { + for (int i = 0; i < m_count; ++i) + delete m_projectiles[i]; + delete m_projectiles; } +// bf2 0x83FD3F0: every bot's record is deleted and replaced by a fresh one (checkPointer on the +// allocation). [CHOSEN, not recovered] The ELF's inline construction clears only the +4 flag byte +// and the four Vec3s; the shared constructor also clears the +5 flag, which no path reads before +// botProjectilePassedPoint sets it. void BFCollisionHandler::removeAllProjectiles() { - BF2_AI_FRONTIER("dice::hfe::ai::BFCollisionHandler::removeAllProjectiles"); + for (int i = 0; i < m_count; ++i) + { + delete m_projectiles[i]; + m_projectiles[i] = checkPointer(new BotProjectile()); + } +} + +namespace { + +// [INFERRED] local helper: handleCollision and handleProjectileMiss end in the same inlined block. +// A round that shows a mine icon is reported to the mine manager: radius-trigger type 2 as type 1 +// with radius 9, otherwise, when the template's detonation component is the default one, as type 0 +// with radius 7.5. The template's component query is not null-tested, as compiled. +void reportPlacedMine(world::IObject* object, unsigned int objectId) +{ + world::IProjectileDetonationComp* detonation = static_cast( + object->queryComponent(world::IID_IProjectileDetonationComp, + world::IID_IProjectileDetonationComp)); // +0x5C + if (!detonation || !detonation->getShowMineIndicationIcon()) // +0x74 + return; + detonation = static_cast( + object->queryComponent(world::IID_IProjectileDetonationComp, + world::IID_IProjectileDetonationComp)); // asked again + IAIMineManager* const mines = static_cast(CommonSingletonServer::m_iAIMineManager); + if (detonation->getRadiusTriggerType() == 2) // +0x78 + { + mines->minePlaced(static_cast(1), objectId, + object->getAbsoluteTransformation(), 9.0f); // +0x18 + return; + } + // [CHOSEN, not recovered] const_cast: the template's queryComponent (+0x5C) is not const. + world::IObjectTemplate* const objectTemplate = + const_cast(object->getTemplate()); // +0x14 + if (objectTemplate->queryComponent(world::IID_IProjectileDetonationCompTemplate)->getClassID() + != world::CID_DefaultDetonationCompTemplate) + return; + mines->minePlaced(static_cast(0), objectId, + object->getAbsoluteTransformation(), 7.5f); +} + +// GenericProjectile is IProjectileObject's only implementor (see world::projectileOwner in +// GenericProjectile.cpp); the typed downcast is the retail subtable dispatch minus the thunk. +inline world::GenericProjectile* asGenericProjectile(world::IProjectileObject* projectile) +{ + return static_cast(projectile); +} + +inline IAIObject* aiObjectOf(world::IObject* object) +{ + return static_cast(world::object_detail::LayoutAccess::aiObject(object)); // +0x34 } -void BFCollisionHandler::handleCollision(world::IObject* a, world::IObject* b, const Vec3& at) +} // namespace + +// handleCollision - bf2 0x83FD5C0, 1118 B (objdump, 2026-11-01). GameLogicCollision's object hit: +// `projectile` hit `hitObject` at `at`. A round fired from a vehicle with an AI object tells the AI +// collision handler about the victim (victimUpdate +0x1C, the victim's player id from the nearest +// player-control object up the hit object's chain) and, when that answers true, the shooter +// (shooterUpdate +0x20); then the indirect hit (+0x2C) is reported with the victim's player id +// (-1 without one). The mine block follows for every hit. Without a hit object the indirect hit +// is reported with a null player, AI object and projectile: the next two slots then dereference +// the null player, as compiled (GameLogicCollision never passes a null hit object). +void BFCollisionHandler::handleCollision(world::IObject* projectile, world::IObject* hitObject, const Vec3& at) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCollisionHandler::handleCollision"); + if (!hitObject) + { + world::IProjectileObject* const proj = projectile + ? static_cast(projectile->queryInterface(world::IID_IProjectileObject)) + : 0; + if (!proj) + return; + world::IPlayer* const player = asGenericProjectile(proj)->getPlayer(); // +0x54 + if (!player) + return; + world::IObject* const vehicle = player->getVehicle(); // +0x48 + if (!vehicle || !aiObjectOf(vehicle)) + return; + handleIndirectProjectileHit(0, 0, static_cast(0), projectile, -1); // +0x2C + return; + } + if (!projectile) + return; + + world::IProjectileObject* const proj = + static_cast(projectile->queryInterface(world::IID_IProjectileObject)); + world::IPlayer* const player = proj ? asGenericProjectile(proj)->getPlayer() : 0; + world::IObject* const vehicle = player ? player->getVehicle() : 0; + IAIObject* const shooter = vehicle ? aiObjectOf(vehicle) : 0; + if (shooter) + { + int victimPlayerId = -1; + IAIObject* const victim = aiObjectOf(world::getRootParent(hitObject)); + if (victim) + { + world::IPlayerControlObject* pco = 0; + for (world::IObject* o = hitObject; o; o = o->getParent()) + { + pco = static_cast( + o->queryInterface(world::IID_IPlayerControlObject)); + if (pco) + break; + } + world::IPlayer* const victimPlayer = pco ? pco->getOccupingPlayer() : 0; // +0x10 + if (victimPlayer) + { + victimPlayerId = victimPlayer->getId(); // +0x54 + const Vec3& position = projectile->getAbsolutePosition(); // +0x6C + IAICollisionHandler* const ai = + checkPointer(static_cast(CommonSingletonServer::m_iAICollisionHandler)); + if (ai->victimUpdate(victimPlayerId, projectile->getObjectId(), position, victim, shooter)) + static_cast(CommonSingletonServer::m_iAICollisionHandler) + ->shooterUpdate(asGenericProjectile(proj)->getPlayer()->getId(), + projectile->getObjectId(), hitObject, victim, at); + } + } + handleIndirectProjectileHit(player, shooter, proj, projectile, victimPlayerId); // +0x2C + } + reportPlacedMine(projectile, projectile->getObjectId()); } +// handleProjectileTimeout - bf2 0x83FDA30, 483 B. GenericProjectile's reset and detonate: the +// owner's AI hears the round's object id, the owner's id, the round's position and whether its +// template carries a sticky-collision component (+0x24). A round that shows a mine icon is +// removed from the mine manager (+0x14). +// [CHOSEN, not recovered] the return value: the image sets none; both callers discard it. int BFCollisionHandler::handleProjectileTimeout(world::IProjectileObject* projectile, world::IObject* owner) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCollisionHandler::handleProjectileTimeout"); + world::IPlayer* const player = asGenericProjectile(projectile)->getPlayer(); // +0x54 + if (player) + { + const int playerId = player->getId(); + const unsigned int objectId = owner->getObjectId(); + bool sticky = false; + const world::IObjectTemplate* const objectTemplate = owner->getTemplate(); + if (objectTemplate && objectTemplate->getComponentFromClassID(world::CID_StickyCollisionCompTemplate)) // +0x60 + sticky = true; + const Vec3& position = owner->getAbsolutePosition(); + checkPointer(static_cast(CommonSingletonServer::m_iAICollisionHandler)) + ->handleProjectileTimeout(static_cast(objectId), playerId, position, sticky); // +0x24 + } + world::IProjectileDetonationComp* const detonation = static_cast( + owner->queryComponent(world::IID_IProjectileDetonationComp, world::IID_IProjectileDetonationComp)); + if (detonation && detonation->getShowMineIndicationIcon()) + static_cast(CommonSingletonServer::m_iAIMineManager)->mineRemoved(owner->getObjectId()); + return 0; } -int BFCollisionHandler::handleProjectileFire(const Vec3& from, world::IProjectileObject* projectile, world::IObject* weapon, world::IPlayer* player) +// handleProjectileFire - bf2 0x83FDF80, 501 B. `object` is the fired round (GenericFireArm / +// MultiFireComp pass it as the second argument of the short form); `projectile` is not read. A +// player in a vehicle with an AI object reports the shot to the AI collision handler (+0x08: the +// start point, the round, its transformation and object id, the AI object of the shooter's root, +// the player's id and team) and marks the vehicle's last fired weapon (armament +0x28). +// [CHOSEN, not recovered] the return value: the image sets none; the caller discards it. +int BFCollisionHandler::handleProjectileFire(const Vec3& from, world::IProjectileObject* /*projectile*/, + world::IObject* object, world::IPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCollisionHandler::handleProjectileFire"); + world::IObject* const vehicle = player->getVehicle(); // +0x48 + IAIObject* const shooter = vehicle ? aiObjectOf(vehicle) : 0; + if (!shooter) + return 0; + world::IObject* const shooterObject = shooter->getObject(); // +0x20 + const int team = player->getTeam(); // +0xE8 + const int playerId = player->getId(); // +0x54 + IAIObject* const root = aiObjectOf(world::getRootParent(shooterObject)); + const unsigned int objectId = object->getObjectId(); + const Mat4& transformation = object->getAbsoluteTransformation(); // +0x84 + checkPointer(static_cast(CommonSingletonServer::m_iAICollisionHandler)) + ->handleProjectileFire(from, object, transformation, static_cast(objectId), root, + playerId, team); // +0x08 + if (IAIObjectArmament* const armament = shooter->getArmament()) // +0x84 + armament->setLastFiredWeapon(); // +0x28 + return 0; } -void BFCollisionHandler::handleProjectileFire(world::IProjectileObject* projectile, world::IObject* weapon) +// handleProjectileFire - bf2 0x83FDF10, 106 B. A round with an owner is reported with its start +// point (IProjectileObject +0x6C) through the long form (+0x14). +void BFCollisionHandler::handleProjectileFire(world::IProjectileObject* projectile, world::IObject* object) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCollisionHandler::handleProjectileFire"); + if (!projectile) + return; + world::IPlayer* const player = asGenericProjectile(projectile)->getPlayer(); // +0x54 + if (!player) + return; + const Vec3 from = asGenericProjectile(projectile)->getStartPos(); // +0x6C + handleProjectileFire(from, projectile, object, player); // +0x14 } -void BFCollisionHandler::handleProjectileDamage(world::IObject* target, float amount, int type, unsigned int id, Vec3 at) +// handleProjectileDamage - ELF 0x83FE410, 651 B (read with objdump/rea, 2026-11-01). Called by +// GameLogicDamage::serverGiveDamage after the damage is applied, result unused. `id` is the weapon's +// template id, `type` the player id: the AI weapon template is looked up by the weapon template's +// m_aiTemplate name (a copied string, as compiled), then the shooter is that player's current +// vehicle's AI object and the victim the target's; the strength row is the weapon template's +// m_strengths for the victim's combat-strength type. Every lookup that fails returns silently. +// The handler goes through checkPointer (a null one is logged, then called, as shipped). +// `amount` and `at` are not read. +void BFCollisionHandler::handleProjectileDamage(world::IObject* target, float /*amount*/, int type, + unsigned int id, Vec3 /*at*/) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCollisionHandler::handleProjectileDamage"); + if (id == static_cast(-1)) + return; + world::IObjectTemplate* const objectTemplate = world::objectTemplateManager->getTemplate(id); // +0x60 + if (!objectTemplate) + return; + world::SimpleObjectTemplate* const simple = static_cast( + objectTemplate->queryImplementation(world::CID_SimpleObjectTemplate)); // +0x50 + if (!simple) + return; + WeaponTemplate* weapon; + { + const std::string aiTemplate(simple->m_aiTemplate); // +0x128 + weapon = WeaponTemplateManager::m_instance->getTemplate(aiTemplate); + } + if (!weapon) + return; + + world::IPlayer* const player = world::playerManager->getPlayerFromId(type); // +0x20 + if (!player) + return; + world::IObject* const vehicle = player->getVehicle(); // +0x48 + if (!vehicle) + return; + IAIObject* const shooter = static_cast( + world::object_detail::LayoutAccess::aiObject(vehicle)); // +0x34 + if (!shooter) + return; + IAIObjectArmament* const armament = shooter->getArmament(); // +0x84 + if (!armament) + return; + IAIObject* const victim = static_cast( + world::object_detail::LayoutAccess::aiObject(target)); // +0x34 + if (!victim) + return; + IAIObjectPhysical* const physical = victim->getPhysical(); // +0x94 + if (!physical) + return; + const int weaponIndex = armament->getWeaponIdFromActivationId(weapon->m_weaponActivate, // +0x34 + weapon->m_weaponFire); + if (weaponIndex == -1) + return; + const int strength = weapon->m_strengths[physical->getStrType()]; // +0x4C + checkPointer(static_cast(CommonSingletonServer::m_iAICollisionHandler)) + ->handleProjectileDamage(shooter, victim, strength, weaponIndex); // +0x14 } -void BFCollisionHandler::handleExplosionDamage(world::IObject* target, float amount, int type, unsigned int id, Vec3 at) + +// handleExplosionDamage - bf2 0x83FE180, 651 B: GameLogicExplosion's queued damage. It compiles to +// the same instructions as handleProjectileDamage (register choice in the checkPointer diagnostic +// aside); [CHOSEN, not recovered] the body is shared through a non-virtual call. +void BFCollisionHandler::handleExplosionDamage(world::IObject* target, float amount, int type, + unsigned int id, Vec3 at) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCollisionHandler::handleExplosionDamage"); + BFCollisionHandler::handleProjectileDamage(target, amount, type, id, at); } +// handleIndirectProjectileHit - bf2 0x83FDC70, 325 B: the player's team, then the AI collision +// handler's short form (+0x10). Returns its answer. int BFCollisionHandler::handleIndirectProjectileHit(world::IPlayer* player, IAIObject* object, const Vec3& at, int a) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCollisionHandler::handleIndirectProjectileHit"); + const int team = player->getTeam(); // +0xE8 + return checkPointer(static_cast(CommonSingletonServer::m_iAICollisionHandler)) + ->handleIndirectProjectileHit(team, object, at, a); // +0x10 } +// handleIndirectProjectileHit - bf2 0x83FDDC0, 332 B: the player's team, then the long form (+0x0C). int BFCollisionHandler::handleIndirectProjectileHit(world::IPlayer* player, IAIObject* object, int a, const Vec3& at, int b) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCollisionHandler::handleIndirectProjectileHit"); + const int team = player->getTeam(); // +0xE8 + return checkPointer(static_cast(CommonSingletonServer::m_iAICollisionHandler)) + ->handleIndirectProjectileHit(team, object, a, at, b); // +0x0C } -int BFCollisionHandler::handleIndirectProjectileHit(world::IPlayer* player, IAIObject* object, world::IProjectileObject* projectile, world::IObject* weapon, int a) +// handleIndirectProjectileHit - bf2 0x83FDC20, 76 B: the round's object id and position, through +// the (int, Vec3) form (+0x28). `projectile` is not read. +int BFCollisionHandler::handleIndirectProjectileHit(world::IPlayer* player, IAIObject* object, + world::IProjectileObject* /*projectile*/, + world::IObject* weapon, int a) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCollisionHandler::handleIndirectProjectileHit"); + const Vec3& position = weapon->getAbsolutePosition(); // +0x6C + return handleIndirectProjectileHit(player, object, static_cast(weapon->getObjectId()), + position, a); // +0x28 } -int BFCollisionHandler::handleProjectileMiss(int a, world::IObject* object, int b, const Vec3& at) +// handleProjectileMiss - bf2 0x83FE6A0, 586 B. GameLogicCollision's terrain hit: `playerId` is the +// round's owner (-1 without one), `objectId` the round's object id. The owner's vehicle's AI +// object reports the miss (+0x18); the mine block follows with that id. +// [CHOSEN, not recovered] the return value: the image sets none; the caller discards it. +int BFCollisionHandler::handleProjectileMiss(int playerId, world::IObject* object, int objectId, const Vec3& at) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCollisionHandler::handleProjectileMiss"); + if (world::IPlayer* const player = world::playerManager->getPlayerFromId(playerId)) // +0x20 + { + world::IObject* const vehicle = player->getVehicle(); // +0x48 + IAIObject* const shooter = vehicle ? aiObjectOf(vehicle) : 0; + if (shooter) + checkPointer(static_cast(CommonSingletonServer::m_iAICollisionHandler)) + ->handleProjectileMiss(shooter, playerId, objectId, at); // +0x18 + } + reportPlacedMine(object, static_cast(objectId)); + return 0; } +// reset - bf2 0x83FEB80, 45 B: every bot's projectile record is removed (+0x40); the count is +// read live. void BFCollisionHandler::reset() { - BF2_AI_FRONTIER("dice::hfe::ai::BFCollisionHandler::reset"); + for (int id = 0; id < m_count; ++id) + removeBotProjectile(id); } // Every live, unpassed round is sampled once per AI tick: its highest Y is kept, and it is diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFCommander.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/BFCommander.cpp index 42e800c37..f3c4bba08 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFCommander.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFCommander.cpp @@ -1,12 +1,21 @@ // [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. -// [TEMP] Temporary implementation boundaries remain. -// [CHOSEN, not recovered] Temporary implementation boundaries remain. -// [RETIRE-WHEN: aidll-01-adapters] Complete and validate the remaining BFCommander operations. #include "BFCommander.h" -#include "AIFrontier.h" +#include "IAIObject.h" +#include "AIPlayer.h" +#include "../../../IO/Network/INetworkable.h" +#include "../../../Game/Objects/IObject.h" +#include "../../../Game/GameLogic/SquadManager/SquadOrder.h" +#include "../../../Game/Objects/Game/ArtilleryHandler.h" // the two artillery queries +#include "../../../Game/GameEvents/ArtilleryEvent.h" // fireArtillery +#include "../../../Game/GameEvents/UAVEvent.h" +#include "../../../Game/GameEvents/SupplyDropEvent.h" +#include "../../../Game/GameEvents/DropVehicleEvent.h" +#include "../../../Game/GameLogic/GameLogic.h" +#include "../../../Game/GameLogic/VoiceMessages.h" +#include "../../../Game/GameLogic/SquadManager/ISquadManager.h" +#include "../../../Core/EventManager.h" #include "../../AIDLL/AI/Main/CommonSingletonServer.h" #include "../../../Core/ClassManager.h" @@ -16,9 +25,29 @@ namespace dice { namespace hfe { extern ClassManager* classManager; +extern IBase* squadManager; // ds:0x8ACBFA4 - Core/Globals.cpp namespace ai { +namespace { +// Shared spelling of the lookup/play sequence in ELF 0x840F7F0..0x8410463. +void playCommanderMessage(int team, const char* name) +{ + int messageId = 0, voiceId = 0, filterId = 0; + bool found; + { + const std::string filter(""); + const std::string voice("commander"); + const std::string message(name); + found = static_cast(gameLogic)->getVoiceMessages()->namesToIds( + &messageId, &voiceId, &filterId, message, voice, filter); + } + if (found) + static_cast(gameLogic)->getVoiceMessages()->playRadioMessage( + team, messageId, voiceId, filterId); +} +} + // First wins in, exact match out. IBFCommander::IBFCommander() { @@ -48,95 +77,177 @@ BFCommander::~BFCommander() { } +// bf2 ELF 0x840F340: ISquadManager::applyForCommander(side +0x6C, id +0x1C) (+0x58). +// [CHOSEN] The image returns whatever the void call leaves in eax; 0 here (callers discard it). int BFCommander::applyAsCommander(IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::applyAsCommander"); + const int id = player->getId(); + static_cast(squadManager)->applyForCommander(player->getSide(), id); + return 0; } +// bf2 ELF 0x840F390: ISquadManager::resignCommander(side) (+0x68). Return as above. int BFCommander::retireAsCommander(IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::retireAsCommander"); + static_cast(squadManager)->resignCommander(player->getSide()); + return 0; } +// bf2 ELF 0x840F3C0 / 0x840F400 / 0x840F440: giveOrder with order type 5 / 4 / 6. The image +// tail-returns giveOrder's leftover eax; 0 here ([CHOSEN], CommanderInterface discards it). int BFCommander::giveAttackOrder(const Vec3& position, int a, int b, IAIObject* target) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::giveAttackOrder"); + giveOrder(position, a, b, target, static_cast(5)); + return 0; } int BFCommander::giveMoveOrder(const Vec3& position, int a, int b, IAIObject* target) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::giveMoveOrder"); + giveOrder(position, a, b, target, static_cast(4)); + return 0; } int BFCommander::giveDefendOrder(const Vec3& position, int a, int b, IAIObject* target) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::giveDefendOrder"); + giveOrder(position, a, b, target, static_cast(6)); + return 0; } -void BFCommander::sendAttackMessage(int a, int b) +// bf2 ELF 0x840F740: a commander order {type, target network id or 0, points = {position, 0, 0}, +// flag2C false} for (team, squad) through ISquadManager::issueCommanderOrder (+0x48, last +// argument false). The target's id is its object's networkable id (IObjectComponent +0x20, +// IObject::getNetworkable slot 54, ushort at +4). +void BFCommander::giveOrder(const Vec3& position, int squadId, int team, IAIObject* target, SquadOrderType type) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::sendAttackMessage"); + SquadOrder order; + for (int i = 0; i < 3; ++i) + { + order.points[i].x = 0.0f; + order.points[i].y = 0.0f; + order.points[i].z = 0.0f; + } + order.flag2C = false; + order.orderId = type; + order.points[0] = position; + order.targetNetId = 0; + if (target) + { + io::INetworkable* const networkable = target->getObject()->getNetworkable(); + if (networkable) + order.targetNetId = static_cast(networkable->m_networkableId); + } + static_cast(squadManager)->issueCommanderOrder(team, squadId, order, false); } -void BFCommander::sendDefendMessage(int a, int b) +// ELF 0x840F7F0. The squad argument is unused. +void BFCommander::sendAttackMessage(int team, int /*squadId*/) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::sendDefendMessage"); + playCommanderMessage(team, "attack_position"); } -int BFCommander::fireArtillery(int a, int b, Vec2 position) +// ELF 0x840F980. +void BFCommander::sendDefendMessage(int team, int /*squadId*/) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::fireArtillery"); + playCommanderMessage(team, "defend"); +} + +// bf2 0x840F480. Queues a request-fire ArtilleryEvent (type 1, the team in the byte at +0x14, +// GameLogic category, id 15) for the next update. A squad id other than -1 also marks that +// squad's order accepted (ISquadManager +0x24: false, order type 2, squad order type 0, false). +// [CHOSEN, not recovered] The ELF leaves the last call's EAX; no caller reads it, 0 here. +int BFCommander::fireArtillery(int team, int squadId, Vec2 position) +{ + ArtilleryEvent* const event = new ArtilleryEvent(); + event->m_target = position; + event->m_artilleryType = ArtilleryEvent::ArtilleryTypeRequestFire; + event->m_team = static_cast(team); + eventManager->postEventNextUpdate(ECGameLogic, 15, static_cast(event)); + if (squadId != -1) + { + static_cast(squadManager) + ->setIsAccepted(team, squadId, false, static_cast(2), + static_cast(0), false); + } + return 0; } -int BFCommander::sendUav(int a, int b, Vec2 position) +// ELF 0x840F530. Unlike fireArtillery, these producers do not guard squadId == -1. +void BFCommander::sendUav(int team, int squadId, Vec2 position) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::sendUav"); + UAVEvent* const event = new UAVEvent(position.x, position.y, team, false); + eventManager->postEventNextUpdate(ECGameLogic, 15, event); + static_cast(squadManager)->setIsAccepted( + team, squadId, false, static_cast(2), static_cast(1), false); } -int BFCommander::dropSupply(int a, int b, Vec2 position) +// ELF 0x840F5E0. +void BFCommander::dropSupply(int team, int squadId, Vec2 position) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::dropSupply"); + SupplyDropEvent* const event = new SupplyDropEvent(position.x, position.y, team); + eventManager->postEventNextUpdate(ECGameLogic, 15, event); + static_cast(squadManager)->setIsAccepted( + team, squadId, false, static_cast(2), static_cast(3), false); } -int BFCommander::dropVehicle(int a, int b, Vec2 position) +// ELF 0x840F690. The producer deliberately leaves the trailing event byte untouched. +void BFCommander::dropVehicle(int team, int squadId, Vec2 position) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::dropVehicle"); + DropVehicleEvent* const event = new DropVehicleEvent(team, position); + eventManager->postEventNextUpdate(ECGameLogic, 15, event); + static_cast(squadManager)->setIsAccepted( + team, squadId, false, static_cast(2), static_cast(2), false); } -int BFCommander::denyArtilleryRequest(int a, int b) +// ELF 0x840FB10. Acceptance state is cleared even when message lookup fails. +void BFCommander::denyArtilleryRequest(int team, int squadId) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::denyArtilleryRequest"); + playCommanderMessage(team, "artillery_deny"); + static_cast(squadManager)->setIsAccepted( + team, squadId, false, static_cast(2), static_cast(0), false); } +// bf2 0x840FCE0: the team's handler (one-based, unchecked) has any artillery piece registered. bool BFCommander::gameHasArtillery(int team) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::gameHasArtillery"); + return world::artilleryManager->getHandler(static_cast(team))->hasArtilleryPieces(); } +// bf2 0x840FD00: the handler's haveAnyArtillery (pieces that still have an owner object). bool BFCommander::anyArtilleryPiecesLeft(int team) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::anyArtilleryPiecesLeft"); + return world::artilleryManager->getHandler(static_cast(team))->haveAnyArtillery(); } -// dice's capital A. Frozen - it is the mangled name. -int BFCommander::ArtilleryUnavailable(int a, int b) +// ELF 0x840FD30. The capital A is attested by the mangled name. +void BFCommander::ArtilleryUnavailable(int team, int squadId) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::ArtilleryUnavailable"); + playCommanderMessage(team, "artillery_unavailable"); + static_cast(squadManager)->setIsAccepted( + team, squadId, false, static_cast(2), static_cast(0), false); } -int BFCommander::denySupplyRequest(int a, int b) +// ELF 0x840FF00. +void BFCommander::denySupplyRequest(int team, int squadId) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::denySupplyRequest"); + playCommanderMessage(team, "supply_deny"); + static_cast(squadManager)->setIsAccepted( + team, squadId, false, static_cast(2), static_cast(3), false); } -int BFCommander::denyVehicleDropRequest(int a, int b) +// ELF 0x84100D0. +void BFCommander::denyVehicleDropRequest(int team, int squadId) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::denyVehicleDropRequest"); + playCommanderMessage(team, "vehicledrop_deny"); + static_cast(squadManager)->setIsAccepted( + team, squadId, false, static_cast(2), static_cast(2), false); } -int BFCommander::denyUavRequest(int a, int b) +// ELF 0x84102A0. +void BFCommander::denyUavRequest(int team, int squadId) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::denyUavRequest"); + playCommanderMessage(team, "uav_deny"); + static_cast(squadManager)->setIsAccepted( + team, squadId, false, static_cast(2), static_cast(1), false); } } // namespace ai diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFCommander.h b/Code/BF2/AI/AIInterface/BFKnowledge/BFCommander.h index 64968a541..df9b1036a 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFCommander.h +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFCommander.h @@ -17,6 +17,7 @@ namespace dice { namespace hfe { class IBase; +enum SquadOrderType : int; // Game/GameLogic/SquadManager/ISquadInfo.h namespace ai { @@ -34,16 +35,16 @@ class IBFCommander virtual void sendAttackMessage(int a, int b) = 0; virtual void sendDefendMessage(int a, int b) = 0; virtual int fireArtillery(int a, int b, Vec2 position) = 0; - virtual int sendUav(int a, int b, Vec2 position) = 0; - virtual int dropSupply(int a, int b, Vec2 position) = 0; - virtual int dropVehicle(int a, int b, Vec2 position) = 0; - virtual int denyArtilleryRequest(int a, int b) = 0; + virtual void sendUav(int a, int b, Vec2 position) = 0; + virtual void dropSupply(int a, int b, Vec2 position) = 0; + virtual void dropVehicle(int a, int b, Vec2 position) = 0; + virtual void denyArtilleryRequest(int a, int b) = 0; virtual bool gameHasArtillery(int team) = 0; virtual bool anyArtilleryPiecesLeft(int team) = 0; - virtual int ArtilleryUnavailable(int a, int b) = 0; - virtual int denySupplyRequest(int a, int b) = 0; - virtual int denyVehicleDropRequest(int a, int b) = 0; - virtual int denyUavRequest(int a, int b) = 0; + virtual void ArtilleryUnavailable(int a, int b) = 0; + virtual void denySupplyRequest(int a, int b) = 0; + virtual void denyVehicleDropRequest(int a, int b) = 0; + virtual void denyUavRequest(int a, int b) = 0; }; class BFCommander : public IBFCommander @@ -60,16 +61,20 @@ class BFCommander : public IBFCommander virtual void sendAttackMessage(int a, int b); virtual void sendDefendMessage(int a, int b); virtual int fireArtillery(int a, int b, Vec2 position); - virtual int sendUav(int a, int b, Vec2 position); - virtual int dropSupply(int a, int b, Vec2 position); - virtual int dropVehicle(int a, int b, Vec2 position); - virtual int denyArtilleryRequest(int a, int b); + virtual void sendUav(int a, int b, Vec2 position); + virtual void dropSupply(int a, int b, Vec2 position); + virtual void dropVehicle(int a, int b, Vec2 position); + virtual void denyArtilleryRequest(int a, int b); virtual bool gameHasArtillery(int team); virtual bool anyArtilleryPiecesLeft(int team); - virtual int ArtilleryUnavailable(int a, int b); - virtual int denySupplyRequest(int a, int b); - virtual int denyVehicleDropRequest(int a, int b); - virtual int denyUavRequest(int a, int b); + virtual void ArtilleryUnavailable(int a, int b); + virtual void denySupplyRequest(int a, int b); + virtual void denyVehicleDropRequest(int a, int b); + virtual void denyUavRequest(int a, int b); + +private: + // bf2 ELF 0x840F740: the shared body of the three give*Order methods. + void giveOrder(const Vec3& position, int squadId, int team, IAIObject* target, SquadOrderType type); }; } // namespace ai diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFGame.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/BFGame.cpp index 1f9c6ea57..cc1cc103a 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFGame.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFGame.cpp @@ -7,9 +7,14 @@ #include "../../../Core/Debug.h" // the no-settings report -#include "AIFrontier.h" +#include "../../../Game/Objects/ISpawnPoint.h" // getSpawnPointPositions +#include "../../../Game/Objects/IObject.h" #include "../../AIDLL/AI/Main/CommonSingletonServer.h" +#include "../../AIDLL/AI/Main/AISettingsInterfaces.h" // IAISettings, the menu arm's override +#include "../../../Game/GeneralSettings.h" // IGeneralSettings, the menu arm +#include "../../../Game/LocalProfileManager.h" // ILocalProfileManager, the menu arm +#include "../../../Core/StringUtil.h" // compareIgnoreCase (0x431950) #include "../../../Core/ClassManager.h" #include "../../../Game/GameServer/ServerSettings.h" #include "../../../Game/IGame.h" // the `game` global and queryInterface (+0x0C) @@ -23,6 +28,16 @@ #include "../../../Game/GameLogic/SpawnSystem/SpawnManager.h" #include "../../../Game/GameLogic/SpawnSystem/SpawnGroup.h" +#include "../../../Game/Objects/Projectiles/IProjectileObject.h" +#include "../../../Game/Objects/Projectiles/GenericProjectile.h" // getTeam, IProjectileDetonationComp +#include "../../../Game/Objects/ObjectLayoutAccess.h" // IObject +0x34, the AI object +#include "../../../Game/Objects/IPlayer.h" // getCloseMines, getId +#include "../../../IO/Network/INetworkable.h" // m_networkableId +#include "../../../Math/Vec3.h" // vec3ToVec2XZ, insideCentreBox +#include "AIPlayer.h" +#include "IAIObject.h" + +#include // std::find over the ignore list #include // the control-point map's own type namespace dice { @@ -65,13 +80,45 @@ int BFGame::getMaxNumberOfPlayers() const } // Copies game settings into the AI configuration, including bot population and team balance. -// [RETIRE-WHEN: aidll-01-adapters] Remove when the corresponding implementation is complete and validated. +// BF2.exe 0x815C50 (530 B, RET 0xC). With a "GeneralSettings" singleton (the client hosting a game +// from the menu) the values come from the profile's GeneralSettings; otherwise from serverSettings. +// The menu arm, in order: +// 1. "LocalProfileManager" (string 0x87FD98) must exist and have a current profile (+0x44); +// otherwise return false (0x815DB4) and leave a/b/c alone. +// 2. settings +0x40 stringGet("GSGameMode", "gpm_cq") (0x880688 / 0x89B4D0); when it equals +// "sp1" (0x89B200, compareIgnoreCase 0x431950), the bot count is forced: 16, or +// IAISettings (CommonSingletonServer, 0xA3867C) slot 0 getMaxNBots when IAISettings exists +// and its slot +0xB8 overrideMenuSettings() answers true; then GeneralSettings +0xB4 +// setMaxBots(count). +// 3. a = +0xB0 getMaxBots, b = +0xB8 getMaxBotsIncludeHumans, c = +0xC0 getBotSkill (stored +// through the x87 stack as a float); return true. int BFGame::getAISettingsFromGame(int& a, bool& b, float& c) const { - if (classManager->getSingleton(std::string("GeneralSettings"))) + IBase* general = classManager->getSingleton(std::string("GeneralSettings")); + // The same arm in both images: bf2 (ia-32, dedicated) 0x83FED10 makes the identical calls. No + // dedicated module registers "GeneralSettings", so the dedicated image never takes it. + if (general) { - BF2_AI_FRONTIER("dice::hfe::ai::BFGame::getAISettingsFromGame" - " - the MENU arm; this image has no GeneralSettings slots"); + IGeneralSettings* generalSettings = static_cast(general); + ILocalProfileManager* profiles = static_cast( + classManager->getSingleton(std::string("LocalProfileManager"))); + if (!profiles || !profiles->getCurrentProfile()) // +0x44 + return 0; + const std::string gameMode(settings->stringGet(std::string("GSGameMode"), // +0x40 + std::string("gpm_cq"))); + if (compareIgnoreCase(gameMode, std::string("sp1")) == 0) + { + int count = 16; + const IAISettings* aiSettings = + static_cast(CommonSingletonServer::m_iaiSettings); + if (aiSettings && aiSettings->overrideMenuSettings()) // +0xB8 + count = aiSettings->getMaxNBots(); // +0x00 + generalSettings->setMaxBots(count); // +0xB4 + } + a = generalSettings->getMaxBots(); // +0xB0 + b = generalSettings->getMaxBotsIncludeHumans(); // +0xB8 + c = generalSettings->getBotSkill(); // +0xC0 + return 1; } // no settings and no menu is A reported failure, not A silent zero - and the caller honours @@ -107,9 +154,71 @@ int BFGame::getTickets(int team) const return static_cast(world::scoreManager)->getTeamScore(team)->m_tickets; } +// bf2 0x83FF9B0 (ELF listing, Ghidra pseudo-code as cross-check). Walks the player's close mines +// (IPlayer +0x32C) for at most 100 entries, counting skipped ones. A mine counts when its +// projectile team (IProjectileObject +0x64) differs from the bot's side (IAIPlayer +0x6C) and its +// object id is not in `ignore`; the nearest by squared distance wins. For each new best, in this +// order: id, position (IObject +0x6C), normal = the transformation's third row (+0x84, bytes +// 0x20..0x28), found = true, then found = false when the detonation component's +// getRadiusTriggerType (+0x78) is 2. Neither the projectile face nor the component is null-tested. +// The return value is whether any mine was taken (a byte; the caller tests %al). int BFGame::getClosestHostileMine(IAIPlayer* player, Vec3 from, bool& found, Vec3& position, Vec3& normal, unsigned int& id, std::vector& ignore) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFGame::getClosestHostileMine"); + bool any = false; + world::IPlayer* const owner = player->getPlayer(); // +0x0C + const int side = player->getSide(); // +0x6C + std::vector mines; + owner->getCloseMines(mines); // +0x32C + int count = 0; + Vec3 minePosition; + minePosition.x = 0.0f; + minePosition.y = 0.0f; + minePosition.z = 0.0f; + float best = 3.4028235e38f; + if (!mines.empty()) + { + for (std::vector::iterator it = mines.begin(); it != mines.end(); ++it) + { + if (++count > 100) + break; + world::IObject* const mine = *it; + // GenericProjectile is IProjectileObject's only implementor; the typed downcast is the + // retail +0x64 subtable dispatch (thunk _ZThn316_ ... getTeam at vtable +0x37C). + world::GenericProjectile* const projectile = static_cast( + static_cast( + mine->queryInterface(world::IID_IProjectileObject))); // +0x0C + if (projectile->getTeam() == side) // +0x64 + continue; + const unsigned int mineId = mine->getObjectId(); // +0x10 + if (std::find(ignore.begin(), ignore.end(), mineId) != ignore.end()) + continue; + minePosition = mine->getAbsolutePosition(); // +0x6C + const Vec3 at = from; + const float dx = at.x - minePosition.x; + const float dy = at.y - minePosition.y; + const float dz = at.z - minePosition.z; + const float distance = dx * dx + dy * dy + dz * dz; + if (distance < best) + { + any = true; + id = mineId; + best = distance; + position = minePosition; + const float* const m = mine->getAbsoluteTransformation().m; // +0x84 + normal.x = m[8]; + normal.y = m[9]; + normal.z = m[10]; + world::IProjectileDetonationComp* const detonation = + static_cast( + mine->queryComponent(world::IID_IProjectileDetonationComp, + world::IID_IProjectileDetonationComp)); // +0x5C + found = true; + if (detonation->getRadiusTriggerType() == 2) // +0x78 + found = false; + } + } + } + return any; } // Only gameLogic is guarded. @@ -189,12 +298,25 @@ bool BFGame::getControlPointInfo(unsigned int index, Vec3& position, float& radi return active; } -// [FRONTIER] Finds a control point within the horizontal box defined by a and b. -// [RETIRE-WHEN: aidll-01-adapters] Implement and validate insideCentreBox before enabling this query. +// bf2 0x83FF350. The id of the first control point (key order) whose XZ position lies in the box +// insideCentreBox(position, a, b) (bf2 0x83F7A20, same code as the AI image's) describes; -1 when +// there is none or no game logic. The Vec2 scratch is zeroed once, before the walk. int BFGame::findControlPoint(const Vec2& a, const Vec2& b) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFGame::findControlPoint" - " - the walk is read; dice::hfe::insideCentreBox is not"); + Vec2 position; + position.x = 0.0f; + position.y = 0.0f; + if (!gameLogic) + return -1; + typedef std::map ControlPointMap; + ControlPointMap* const points = gameLogic->getControlPointMap(); // +0x174 + for (ControlPointMap::iterator it = points->begin(); it != points->end(); ++it) + { + vec3ToVec2XZ(it->second->getAbsolutePosition(), position); // +0x6C + if (insideCentreBox(position, a, b)) + return static_cast(it->first); + } + return -1; } // The returned list is @@ -219,14 +341,43 @@ int BFGame::getControlPointId(int index) const return static_cast(static_cast(spawnManager)->getSpawnGroup(index)->getControlPointId()); } -int BFGame::getSpawnPointPositions(std::vector& out, unsigned char team) const +// bf2 0x83FF800. Every group's spawn points (copied vector, ISpawnGroup +0x40) that are neither +// AI-enter-on-spawn (+0x24), enter-on-spawn (+0x20) nor human-only (+0x50) add their spawn +// position (+0x34, checkAI true, from a zero Vec3). The team is not read. +// [CHOSEN, not recovered] The ELF leaves the last call's EAX; no caller reads it, 0 here. +int BFGame::getSpawnPointPositions(std::vector& out, unsigned char) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFGame::getSpawnPointPositions"); + const std::map& groups = + static_cast(spawnManager)->getSpawnGroups(); + for (std::map::const_iterator group = groups.begin(); + group != groups.end(); ++group) + { + const std::vector points = group->second->getSpawnPoints(); + for (std::vector::const_iterator it = points.begin(); it != points.end(); ++it) + { + ISpawnPoint* const point = *it; + if (point->getAIEnterOnSpawn() || point->getEnterOnSpawn() || point->getOnlyForHuman()) + continue; + Vec3 position; + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; + point->getSpawnPosition(position, true); + out.push_back(position); + } + } + return 0; } -void BFGame::getControlPointPositions(std::vector& out, unsigned char team) const +// bf2 0x83FFCB0: every control point's absolute position (IObject +0x6C), from the game logic's +// control-point map (IGameLogic +0x174); nothing without a game logic. The team is not read. +void BFGame::getControlPointPositions(std::vector& out, unsigned char) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFGame::getControlPointPositions"); + if (!gameLogic) + return; + std::map* const points = gameLogic->getControlPointMap(); + for (std::map::iterator it = points->begin(); it != points->end(); ++it) + out.push_back(it->second->getAbsolutePosition()); } // Capture team before @@ -250,14 +401,37 @@ bool BFGame::isEligibleSpawnpoint(int team, int groupId) const return active; } +// bf2 0x83FF530. Group 0 or an unknown group is false; otherwise the group's AI spawn point +// (ISpawnGroup +0x44, true) answers enter-on-spawn (+0x20) or AI-enter-on-spawn (+0x24). The +// returned point is not null-tested. bool BFGame::isEnterOnSpawnSpawnpoint(int index) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFGame::isEnterOnSpawnSpawnpoint"); + if (index == 0) + return false; + ISpawnGroup* const group = static_cast(spawnManager)->getSpawnGroup(index); // +0x28 + if (!group) + return false; + ISpawnPoint* const point = group->getSpawnPoint(true); // +0x44 + return point->getEnterOnSpawn() || point->getAIEnterOnSpawn(); // +0x20 / +0x24 } +// bf2 0x83FF5B0. 0 for group 0 or an unknown group; otherwise the AI spawn point's object to +// enter (ISpawnPoint +0x28, (true, side)) and that object's AI object (IObject +0x34): -1 without +// one, else its getInformation(side) (IAIObject +0xB8). Neither the point nor the object is +// null-tested. int BFGame::getEnterOnSpawnSpawnpointObject(int a, int b) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFGame::getEnterOnSpawnSpawnpointObject"); + if (a == 0) + return 0; + ISpawnGroup* const group = static_cast(spawnManager)->getSpawnGroup(a); // +0x28 + if (!group) + return 0; + world::IObject* const object = group->getSpawnPoint(true)->getObjectToEnter(true, b); // +0x44, +0x28 + IAIObject* const aiObject = + static_cast(world::object_detail::LayoutAccess::aiObject(object)); // +0x34 + if (!aiObject) + return -1; + return static_cast(aiObject->getInformation(b)); // +0xB8 } // Returns the level directory joined with the configured level name. @@ -329,9 +503,25 @@ bool BFGame::getIsPrecaching() const return m_isPrecaching; } +// bf2 0x83FFE30. Without a game nothing happens. Otherwise the spotted object's networkable id +// (IObject +0xD8, the u16 at +0x04; 0 without one) goes out as a spotted message with a zero Vec2 +// and vehicle type 26 (IGame +0xD0), and the game's spotted text for that id (+0xCC) is sent as a +// team radio message from the player (+0x58, (TCTeam, text, player id, 0, false, false)). +// [UNRESOLVED] the name of VehicleType 26. void BFGame::enemySpottedByAI(world::IPlayer* player, world::IObject* object) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFGame::enemySpottedByAI"); + if (!game) + return; + unsigned short networkableId = 0; + if (io::INetworkable* const networkable = object->getNetworkable()) // +0xD8 + networkableId = networkable->m_networkableId; + Vec2 zero; + zero.x = 0.0f; + zero.y = 0.0f; + game->sendSpottedMessage(player, networkableId, zero, static_cast(26)); // +0xD0 + const unsigned int playerId = static_cast(player->getId()); // +0x54 + const std::string message = game->getSpottedMessage(networkableId); // +0xCC + game->radioMessageFromPlayer(TCTeam, message, playerId, 0, false, false); // +0x58 } } // namespace ai diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFGameEffector.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/BFGameEffector.cpp index 097f837ac..e49be6613 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFGameEffector.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFGameEffector.cpp @@ -1,13 +1,7 @@ // [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. -// [TEMP] Temporary implementation boundaries remain. -// [CHOSEN, not recovered] Temporary implementation boundaries remain. -// [RETIRE-WHEN: aidll-01-adapters] Complete and validate the remaining BFGameEffector operations. #include "BFGameEffector.h" -#include "AIFrontier.h" - #include "../../AIDLL/AI/Main/CommonSingletonServer.h" #include "../../AIDLL/AI/Main/AISettingsInterfaces.h" // IAISettings::getBotName #include "../../../Core/ClassManager.h" @@ -15,60 +9,88 @@ #include "../../../Game/IGame.h" // the `game` global #include "../../../Game/IGameServer.h" // createPlayer, slot +0x20 #include "../../../Scene/Object/PlayerManager.h" // the `playerManager` global +#include "../../../Game/IGameLogic.h" // the `gameLogic` global +#include "../../../Game/GameLogic/ServerGameLogic.h" // forceSpawnBot +#include "../../../Core/SettingsRepostitory.h" // the `settings` global +#include "../../../Physics/MaterialManager.h" +#include "AIPlayer.h" +#include "IAIObject.h" namespace dice { namespace hfe { extern ClassManager* classManager; +namespace world { extern IBase* materialManager; } namespace ai { // First wins in, exact match out. +// ELF 0x840E1E0 / 0x840E260. IAIGameEffector::IAIGameEffector() { if (!CommonSingletonServer::m_iaiGameEffector) classManager->registerSimpleSingleton(std::string("IAIGameEffector"), this); } +// ELF 0x840E2E0 / 0x840E360 / 0x840E3E0. IAIGameEffector::~IAIGameEffector() { if (CommonSingletonServer::m_iaiGameEffector == this) classManager->unregisterSimpleSingleton(std::string("IAIGameEffector")); } +// ELF 0x8400300 / 0x8400340. BFGameEffector::BFGameEffector() - : m_unknown04(0) - , m_unknown08(0) - , m_unknown0C(0) { } +// ELF 0x8400380 / 0x84003E0 / 0x8400440. BFGameEffector::~BFGameEffector() { } +// bf2 0x84004B0: IGame +0xA4 enterVehicle(player, the vehicle's engine object, false); the +// vehicle's object (IObjectComponent +0x20) is read before the player. +// ELF 0x84004B0. int BFGameEffector::enterVehicle(IAIPlayer* player, IAIObject* vehicle) { - BF2_AI_FRONTIER("dice::hfe::ai::BFGameEffector::enterVehicle"); + world::IObject* const object = vehicle->getObject(); + return game->enterVehicle(player->getPlayer(), object, false); } +// bf2 0x8400500: IGame +0xA8 exitVehicle(player, true, true). +// ELF 0x8400500. int BFGameEffector::exitVehicle(IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFGameEffector::exitVehicle"); + return game->exitVehicle(player->getPlayer(), true, true); } // Includes the overload arguments in the terminatePlayer frontier diagnostic. +// bf2 0x8400720: the player manager's player (+0x20) goes to IGameServer +0x28 destroyPlayer +// (the server is queried from `game`, which is not tested before the query's own null arm). +// [CHOSEN, not recovered] destroyPlayer is void; the ELF answers its leftover AL. 0 here. int BFGameEffector::terminatePlayer(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::BFGameEffector::terminatePlayer(int)"); + world::IPlayer* const player = world::playerManager->getPlayerFromId(playerId); + IGameServer* const server = + game ? static_cast(game->queryInterface(IID_IGameServer)) : 0; + server->destroyPlayer(player); + return 0; } +// bf2 0x8400780: the same for the wrapper's player. +// ELF 0x8400780. int BFGameEffector::terminatePlayer(IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFGameEffector::terminatePlayer(IAIPlayer*)"); + world::IPlayer* const target = player->getPlayer(); + IGameServer* const server = + game ? static_cast(game->queryInterface(IID_IGameServer)) : 0; + server->destroyPlayer(target); + return 0; } // Creates an AI player through the game server and returns its player ID. +// ELF 0x8400540. int BFGameEffector::addBot(int& a, int& b, std::string& name) { if (name.empty()) @@ -99,35 +121,74 @@ int BFGameEffector::addBot(int& a, int& b, std::string& name) return 0; } +// bf2 0x8400620: IGameLogic +0x70 reSpawnPlayer. +// ELF 0x8400620. int BFGameEffector::respawnBot(IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFGameEffector::respawnBot"); + return gameLogic->reSpawnPlayer(player->getPlayer()); } +// bf2 0x8400650: only on a server (setting "GSIsServer", default false), the server game logic +// spawns the player at (position, rotation). +// ELF 0x8400650. void BFGameEffector::forceSpawnBot(IAIPlayer* player, const Vec3& position, const Vec3& rotation) { - BF2_AI_FRONTIER("dice::hfe::ai::BFGameEffector::forceSpawnBot"); + if (!settings->boolGet(std::string("GSIsServer"), false)) + return; + std::pair at(position, rotation); + static_cast(gameLogic)->spawnPlayer(player->getPlayer(), &at); } +// bf2 0x84007D0: IGameLogic +0xE4 giveDamage on the target's engine object with no victim +// list, weapon or projectile objects, a zero position and an up (0, 1, 0) direction, -1 and the +// flags false, true, false. The int is the damage type slot. +// ELF 0x84007D0. int BFGameEffector::giveDamage(IAIObject* target, world::IPlayer* from, int type, float amount) { - BF2_AI_FRONTIER("dice::hfe::ai::BFGameEffector::giveDamage"); + world::IObject* const object = target->getObject(); + Vec3 position; + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; + Vec3 direction; + direction.x = 0.0f; + direction.y = 1.0f; + direction.z = 0.0f; + return gameLogic->giveDamage(object, amount, from, 0, 0, type, 0, 0, position, direction, -1, + false, true, false); +} + +// ELF 0x8400880. The final engine effect call has no return value. +void BFGameEffector::playEffect(const Vec3& position, int a, int b) +{ + queueSoundEffect(position, a, b); + const Vec3 up = { 0.0f, 1.0f, 0.0f }; + const world::IObjectTemplate* const effect = static_cast( + static_cast(world::materialManager) + ->getEffectTemplate(static_cast(a), static_cast(b), 0)); + const Vec3 point = position; + gameLogic->playEffect(point, effect, up); } -int BFGameEffector::playEffect(const Vec3& position, int a, int b) +// ELF 0x8400920. The dedicated ELF ships an empty body. +void BFGameEffector::playSoundEffects(double) { - BF2_AI_FRONTIER("dice::hfe::ai::BFGameEffector::playEffect"); } -// 5 bytes - A bare ret. dice's own empty body, not a gap. -void BFGameEffector::playSoundEffects(double dt) +// ELF 0x8400930. The dedicated ELF ships an empty body. +void BFGameEffector::queueSoundEffect(const Vec3&, int, int) { - BF2_AI_FRONTIER("dice::hfe::ai::BFGameEffector::playSoundEffects"); } +// bf2 0x8400940: this effector's own giveDamage (+0x24) of 1e8f on the player's soldier, from +// the player, typed with its side; side, player and soldier are read in that order. +// ELF 0x8400940. int BFGameEffector::suicide(IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFGameEffector::suicide"); + const int side = player->getSide(); + world::IPlayer* const from = player->getPlayer(); + IAIObject* const soldier = player->getSoldier(); + return giveDamage(soldier, from, side, 1e8f); } } // namespace ai diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFGameEffector.h b/Code/BF2/AI/AIInterface/BFKnowledge/BFGameEffector.h index 452eb7f32..e17850424 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFGameEffector.h +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFGameEffector.h @@ -34,7 +34,7 @@ class IAIGameEffector virtual int respawnBot(IAIPlayer* player) = 0; virtual void forceSpawnBot(IAIPlayer* player, const Vec3& position, const Vec3& rotation) = 0; virtual int giveDamage(IAIObject* target, world::IPlayer* from, int type, float amount) = 0; - virtual int playEffect(const Vec3& position, int a, int b) = 0; + virtual void playEffect(const Vec3& position, int a, int b) = 0; virtual void playSoundEffects(double dt) = 0; virtual int suicide(IAIPlayer* player) = 0; }; @@ -53,15 +53,22 @@ class BFGameEffector : public IAIGameEffector virtual int respawnBot(IAIPlayer* player); virtual void forceSpawnBot(IAIPlayer* player, const Vec3& position, const Vec3& rotation); virtual int giveDamage(IAIObject* target, world::IPlayer* from, int type, float amount); - virtual int playEffect(const Vec3& position, int a, int b); + virtual void playEffect(const Vec3& position, int a, int b); virtual void playSoundEffects(double dt); virtual int suicide(IAIPlayer* player); private: + void queueSoundEffect(const Vec3& position, int a, int b); + + // [INFERRED] Element name. Both ELF destructors iterate in 20-byte steps. + // [UNRESOLVED] Entry fields: the ELF queue/play methods are empty, so no writer exists. + struct SoundEffect + { + unsigned char unread[20]; + }; + /* +0x00 */ // vptr - /* +0x04 */ int m_unknown04; // [UNRESOLVED] - the constructor zeroes all three - /* +0x08 */ int m_unknown08; - /* +0x0C */ int m_unknown0C; + /* +0x04 */ std::vector m_soundEffects; // [INFERRED] name; native STL layout }; } // namespace ai diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFGraphCreator.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/BFGraphCreator.cpp index 65255ce12..f73ffa275 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFGraphCreator.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFGraphCreator.cpp @@ -1,15 +1,14 @@ -// [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. -// [TEMP] Temporary implementation boundaries remain. -// [CHOSEN, not recovered] Temporary implementation boundaries remain. -// [RETIRE-WHEN: aidll-01-adapters] Complete and validate the remaining BFGraphCreator operations. +// [INFERRED] Source placement. One TU with BFGraph: bf2 (ia-32) lays BFGraph (0x842E050..0x842E3F0) +// directly before BFGraphCreator (0x842E420..0x842E610) under one static initialiser +// (_GLOBAL__I__ZN4dice3hfe2ai7BFGraphC2Ev, 0x842E690). #include "BFGraphCreator.h" -#include "AIFrontier.h" - #include "../../AIDLL/AI/Main/CommonSingletonServer.h" +#include "../../AIDLL/AI/AIUtils/DebugRendering/IBFGraph.h" +#include "../../AIDLL/AI/AIUtils/checkPointer.h" #include "../../../Core/ClassManager.h" +#include "../../../Core/Ids.h" // geom::CID_DebugLineGraphD3D, geom::IID_IDebugGraph namespace dice { namespace hfe { @@ -18,6 +17,145 @@ extern ClassManager* classManager; namespace ai { +// geom::IDebugGraph (IID 80039) as BFGraph calls it: the renderer's line graph (geom::DebugLineGraphD3D, +// GeomMisc/DebugLineGraphD3d.cpp, RendDX9 image, PE table 0x1020C7E8). The engine images share no +// header for it, so the slots BFGraph and Core/DebugCounterManager.cpp use are declared here, in +// table order; parameter types are the ones bf2 (ia-32) and BF2.exe pass. [INFERRED] slot names +// (GeomMisc's), [UNRESOLVED] return types where no caller reads them. +class IDebugGraph : public IBase +{ +public: + virtual char setRect(const float* rect) = 0; // +0x10 + virtual void setColour(unsigned int colour) = 0; // +0x14 + virtual void setName(const std::string& name) = 0; // +0x18 + virtual void setBounds(float minimum, float maximum) = 0; // +0x1C + virtual void resetExtrema() = 0; // +0x20 + virtual void draw() = 0; // +0x24 + virtual char setFlag05(char value) = 0; // +0x28 + virtual unsigned char getFlag05() = 0; // +0x2C + virtual void clearLegend() = 0; // +0x30 + virtual void addLegend(const std::string& name, unsigned int colour) = 0; // +0x34 + virtual void setLegendPosition(int x, int y) = 0; // +0x38 + virtual void setHistorySize(int samples) = 0; // +0x3C + virtual void addSample(float sample) = 0; // +0x40 + virtual void setColors(unsigned int a, unsigned int b, unsigned int c) = 0; // +0x44 + virtual void setAutoScale(unsigned char value) = 0; // +0x48 + virtual char setRange(float low, float high) = 0; // +0x4C + virtual char setEnabled(char value) = 0; // +0x50 + virtual bool setByte41(unsigned char value) = 0; // +0x54 + virtual void setDrawValue(unsigned char value) = 0; // +0x58 + virtual unsigned char getDrawValue() = 0; // +0x5C + virtual void setValuePosition(int x, int y) = 0; // +0x60 + virtual void setValueSuffix(const std::string& suffix) = 0; // +0x64 + +protected: + ~IDebugGraph() {} +}; + +// The "DebugLineGraphRenderer" singleton (IID_IDebugGraphRenderer 80040): BFGraph uses +0x10 only. +// [INFERRED] name; Core/DebugCounterManager.cpp calls the same slot to add a graph. +class IDebugGraphRenderer : public IBase +{ +public: + virtual void addGraph(IDebugGraph* graph) = 0; // +0x10 + +protected: + ~IDebugGraphRenderer() {} +}; + +// The AI's debug graph: an IBFGraph over one renderer line graph. sizeof 8 (`operator new(8)` in +// createGraph): the vptr and the line graph. +class BFGraph : public IBFGraph +{ +public: + BFGraph(); + virtual ~BFGraph(); + + virtual void setNumberOfSamples(int samples); + virtual void setDimensions(float x, float y, float width, float height); + virtual void setColours(unsigned int first, unsigned int second, unsigned int third); + virtual void setThresholds(float low, float high); + virtual void setMinMaxY(float minimum, float maximum); + virtual void setCurrentSampleEnding(const std::string& ending); + virtual void setCurrentSampleOffset(int x, int y); + virtual void addSample(float sample); + +private: + IDebugGraph* m_graph; // +0x04 a geom::DebugLineGraphD3D (IID_IDebugGraph) +}; + +// ELF 0x842E110 (C1; C2 0x842E050), PE 0x815AE0. ClassManager +0x34 createInstance( +// CID_DebugLineGraphD3D, IID_IDebugGraph, 0), no null check; the graph's +0x58 (1); then the +// "DebugLineGraphRenderer" singleton, when there is one, takes the graph (+0x10). +BFGraph::BFGraph() +{ + // createInstance answers the IID_IDebugGraph interface pointer. + m_graph = static_cast( + classManager->createInstance(geom::CID_DebugLineGraphD3D, geom::IID_IDebugGraph, 0)); + m_graph->setDrawValue(1); + IDebugGraphRenderer* const renderer = static_cast( + classManager->getSingleton(std::string("DebugLineGraphRenderer"))); + if (renderer) + renderer->addGraph(m_graph); +} + +// ELF 0x842E200 (D1; D2 0x842E1D0, D0 0x842E230), PE 0x815B60. The line graph is freed with plain +// operator delete - not released, and not removed from the graph renderer - in both images. +BFGraph::~BFGraph() +{ + operator delete(m_graph); +} + +// ELF 0x842E270, PE 0x8159D0: the graph's +0x3C. +void BFGraph::setNumberOfSamples(int samples) +{ + m_graph->setHistorySize(samples); +} + +// ELF 0x842E2A0, PE 0x815BA0: the four floats as one rectangle to the graph's +0x10. +void BFGraph::setDimensions(float x, float y, float width, float height) +{ + const float rect[4] = { x, y, width, height }; + m_graph->setRect(rect); +} + +// ELF 0x842E2E0, PE 0x8159E0: the graph's +0x44. +void BFGraph::setColours(unsigned int first, unsigned int second, unsigned int third) +{ + m_graph->setColors(first, second, third); +} + +// ELF 0x842E310, PE 0x8159F0: the graph's +0x4C (low, high), then +0x50 (1). +void BFGraph::setThresholds(float low, float high) +{ + m_graph->setRange(low, high); + m_graph->setEnabled(1); +} + +// ELF 0x842E360, PE 0x826460 (folded): the graph's +0x1C. +void BFGraph::setMinMaxY(float minimum, float maximum) +{ + m_graph->setBounds(minimum, maximum); +} + +// ELF 0x842E390, PE 0x826180 (folded): the graph's +0x64. +void BFGraph::setCurrentSampleEnding(const std::string& ending) +{ + m_graph->setValueSuffix(ending); +} + +// ELF 0x842E3C0, PE 0x815A20: the graph's +0x60. +void BFGraph::setCurrentSampleOffset(int x, int y) +{ + m_graph->setValuePosition(x, y); +} + +// ELF 0x842E3F0, PE 0x815A30: the graph's +0x40. +void BFGraph::addSample(float sample) +{ + m_graph->addSample(sample); +} + // First wins in, exact match out. IBFGraphCreator::IBFGraphCreator() { @@ -39,14 +177,15 @@ BFGraphCreator::~BFGraphCreator() { } +// ELF 0x842E4F0, PE 0x815C00: a new BFGraph through checkPointer. IBFGraph* BFGraphCreator::createGraph() { - BF2_AI_FRONTIER("dice::hfe::ai::BFGraphCreator::createGraph"); + return checkPointer(new BFGraph); } void BFGraphCreator::destroyGraph(IBFGraph* graph) { - // ELF: `if (graph) graph->[vtable +0x04]` - Itanium's deleting destructor, which is what + // ELF 0x842E610: `if (graph) graph->[vtable +0x04]` - Itanium's deleting destructor, which is what // `delete` compiles to. The null guard is dice's and is kept. if (graph) delete graph; diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFObjectEnvironment.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/BFObjectEnvironment.cpp index 7dcf62585..4d94a789d 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFObjectEnvironment.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFObjectEnvironment.cpp @@ -3,12 +3,15 @@ #include "BFObjectEnvironment.h" -#include "AIFrontier.h" #include "../../AIDLL/AI/Main/CommonSingletonServer.h" +#include "../../AIDLL/AI/AIUtils/IAimerHelper.h" #include "../../../Core/ClassManager.h" #include "../SingletonServer.h" // BFSingletonServer::updateStaticMethods #include +#include +#include "IAIObject.h" +#include "IAIObjectPlugIn.h" // IAIObjectUnit::isOccupied #include "../../../Scene/Object/PlayerManager.h" // isValidPlayerId's one call #include "../../../Core/Ids.h" // the four container CIDs, IID_IPlayerControlObject #include "../../../Game/Objects/IObject.h" // getTemplate, getAIComponent @@ -19,15 +22,376 @@ #include "../../../Game/IGameLogic.h" // gameLogic: getPcoMap, giveDamage #include "../../../Game/Objects/GameLogicComp/IArmorGLComp.h" // getHitPoints / getMaxHitPoints #include "../../../Game/Objects/GameLogicComp/ArmorGLCompTemplate.h" // getCanBeDestroyed +#include "../../../Scene/Object/ObjectManager.h" // getObjectFromName +#include "BFTerrain.h" // IAITerrain::intersectTerrain (+0x64) #include "BFTimer.h" // IBFTimer::getGameTime +#include "../../../Game/GameLogic/CombatArea.h" // getAiCombatAreaLayer +#include "../../../Game/GameLogic/CombatAreaManager.h" +#include "../../../Game/Objects/DestroyableObjectTemplate.h" +#include "../../../Game/Objects/ObjectSpawnerTemplate.h" +#include "../../../Game/Objects/Game/TargetObject.h" +#include "../../../Scene/Object/ObjectTypes/Base/ObjectTemplateManager.h" +#include "../../../Game/IGame.h" +#include "../../../Core/Debug.h" +#include "../../../Math/LocalBoundingBox.h" +#include "AITemplate.h" +#include "AITemplateManager.h" +#include +#include "IWeapon.h" // hasIndirectLineOfFire's weapon reads +#include "BFPhysics.h" // IAIPhysics::getGravity +#include "../../../Core/Random.h" // Rand (ELF dice::hfe::Rand) +#include "../../../Game/Objects/Game/Soldier.h" // Soldier::getCameras +#include "../../../Game/Objects/ICameraObject.h" +#include "../../../Game/Objects/ObjectLayoutAccess.h" // the cached collision mesh (+0x40) +#include "../../../Physics/ICollisionMesh.h" // the sense mesh's faces and vertices +#include "../../../Physics/MaterialManager.h" // RayCastStopPredicate::predicateSurface +#include "../../../Physics/IPhysicsNode.h" // isAsleep +#include "../../../Physics/Material.h" +#include "../../../Scene/Object/ObjectPredicator.h" +#include namespace dice { namespace hfe { extern ClassManager* classManager; +namespace world { extern IBase* materialManager; } // ds:0x8AD2820 - Core/Globals.cpp + namespace ai { +// ELF 0x8400A30 / 0x8400A50. +TargetData::TargetData(unsigned int idValue, const Vec3& positionValue, IAIObject* objectValue) + : id(idValue), position(positionValue), object(objectValue) +{ +} + +// ELF 0x8400A70 / 0x8400A90. +TargetData::TargetData(const TargetData& other) + : id(other.id), position(other.position), object(other.object) +{ +} + +// ELF 0x8400AB0. The error can be filtered; then only id and object are copied. +TargetData& TargetData::operator=(const TargetData& other) +{ + Debug(DebugTypeError, "AI/AIInterface/BFKnowledge/BFObjectEnvironment.cpp", 75) + << "This does not work!"; + id = other.id; + object = other.object; + return *this; +} + +namespace { + +// ELF 0x840B200, 0x840B260, 0x840B270. +class DestroyableObjectsPredicate : public world::ObjectPredicator +{ +public: + virtual bool predicate(world::IObject* object) + { + world::IObjectTemplate* const objectTemplate = static_cast( + object->getTemplate()->queryInterface(world::IID_IObjectTemplate)); + return objectTemplate && objectTemplate->getClassID() == world::CID_DestroyableObjectTemplate + && static_cast(objectTemplate)->usedByAi; + } + virtual unsigned int getFlags() const { return 0x1000000; } + virtual bool performCulling(world::IObject*) { return true; } +}; + +// ELF 0x840B4F0, 0x840B540, 0x840B550 (the AI TU's predicate). +class NoMobilePredicate : public world::ObjectPredicator +{ +public: + virtual bool predicate(world::IObject* object) + { + if (!object->hasCollisionLod(0)) + return false; + world::IPhysicsNode* const node = static_cast( + world::object_detail::LayoutAccess::physicsNode(object)); + return !node || !node->getIsMobile(); + } + virtual unsigned int getFlags() const { return 0x1000000; } + virtual bool performCulling(world::IObject*) { return true; } +}; + +// ELF 0x840B560, 0x840B590, 0x840B5A0. +class ObjectSpawnerPredicate : public world::ObjectPredicator +{ +public: + virtual bool predicate(world::IObject* object) + { + return object->getTemplate()->getClassID() == world::CID_ObjectSpawnerTemplate; + } + virtual unsigned int getFlags() const { return 0x1000000; } + virtual bool performCulling(world::IObject*) { return true; } +}; + +// ELF 0x840A1A0's inlined comparison orders only the signed endpoint pair. +struct Edge +{ + int first, second, index; + bool operator<(const Edge& other) const + { + return first == other.first ? second < other.second : first < other.first; + } +}; + +// bf2 0x8400BC0. The object's cached AI component; failing that, for the four container templates +// the occupying object's. The four tests are independent ifs, each overwriting the answer when its +// occupying object exists, as the image runs them in sequence. The parachute's +// IPlayerControlObject is used unchecked. +IAIObject* getIAIObject(world::IObject* object) +{ + IAIObject* aiObject = static_cast(object->getAIComponent()); // +0x34 + if (aiObject) + return aiObject; + + if (object->getTemplate()->getClassID() == world::CID_LadderContainerTemplate) + { + world::IObject* const occupying = + static_cast(object)->getOccupingObject(); // +0x18C + if (occupying) + aiObject = static_cast(occupying->getAIComponent()); + } + if (object->getTemplate()->getClassID() == world::CID_ParachuteTemplate) + { + world::IPlayerControlObject* const control = static_cast( + object->queryInterface(world::IID_IPlayerControlObject)); + world::IObject* const occupying = control->getOccupingObject(); // +0x14 + if (occupying) + aiObject = static_cast(occupying->getAIComponent()); + } + if (object->getTemplate()->getClassID() == world::CID_ZiplineContainerTemplate) + { + world::IObject* const occupying = + static_cast(object)->getOccupingObject(); + if (occupying) + aiObject = static_cast(occupying->getAIComponent()); + } + if (object->getTemplate()->getClassID() == world::CID_GrapplingHookRopeContainerTemplate) + { + world::IObject* const occupying = + static_cast(object)->getOccupingObject(); + if (occupying) + aiObject = static_cast(occupying->getAIComponent()); + } + return aiObject; +} + +// The TU's own one-slot object filter (typeinfo without a base, vtable of one entry). +class IObjectPredicate +{ +public: + virtual bool predicate(world::IObject* object) = 0; // +0x00 +}; + +// bf2 0x840B1D0 (vtable 0x88D75F8): objects with a collision LOD 0 (IObject slot 51). +class CollisionPredicate : public IObjectPredicate +{ +public: + virtual bool predicate(world::IObject* object) { return object->hasCollisionLod(0); } +}; + +// bf2 0x840B450. Pre-order: the object itself when the predicate (if any) takes it, then every +// object down its getChild chain (IObject +0xF0, read literally: the chain is followed through +// getChild, not the sibling link), each recursively. +void getAllChildren(world::IObject* object, std::vector& out, IObjectPredicate* filter) +{ + if (!filter || filter->predicate(object)) + out.push_back(object); + for (world::IObject* child = object->getChild(); child; child = child->getChild()) + getAllChildren(child, out, filter); +} + +// bf2 0x840B310 / 0x840B360 (vtable 0x88D75B0): the line test's stop filter. Objects whose AI +// object is in `ignore` do not stop the line; any other object is remembered for predicateSurface. +// With `seeThroughStops` a see-through surface (material +0x7C) does not stop the line either, but +// it records the squared distance from `from` to that object's position when nearer than the best +// so far; every other surface stops it. +class RayCastStopPredicate : public world::ObjectPredicator +{ +public: + RayCastStopPredicate(const std::vector& ignore, bool seeThroughStops, const Vec3& from) + : m_ignore(&ignore) + , m_seeThroughStops(seeThroughStops) + , m_nearestSeeThroughSq(FLT_MAX) + , m_from(from) + { + } + + virtual bool predicate(world::IObject* object) + { + IAIObject* const aiObject = getIAIObject(object); + if (aiObject) + { + for (std::vector::const_iterator it = m_ignore->begin(); it != m_ignore->end(); ++it) + if (aiObject == *it) + return false; + } + m_object = object; + return true; + } + virtual unsigned int getFlags() const { return 0x1000000; } + virtual bool performCulling(world::IObject*) { return true; } + virtual bool predicateSurface(int surface) + { + world::Material* const material = static_cast(world::materialManager) + ->getMaterialPtr(static_cast(surface)); // +0x24 + if (!m_seeThroughStops || !material->getIsSeeThrough()) // +0x7C + return true; + const Vec3& position = m_object->getAbsolutePosition(); // +0x6C + Vec3 delta; + delta.x = m_from.x - position.x; + delta.y = m_from.y - position.y; + delta.z = m_from.z - position.z; + const float distanceSq = delta.x * delta.x + delta.y * delta.y + delta.z * delta.z; + if (m_nearestSeeThroughSq > distanceSq) + m_nearestSeeThroughSq = distanceSq; + return false; + } + + /* +0x04 */ const std::vector* m_ignore; + /* +0x08 */ bool m_seeThroughStops; + /* +0x0C */ world::IObject* m_object; // left unset until predicate takes an object + /* +0x10 */ float m_nearestSeeThroughSq; + /* +0x14 */ Vec3 m_from; +}; + +// bf2 0x840B280 (vtable 0x88D75C8): the sphere pass's filter. Objects without an AI object pass; +// an object whose AI object is the primary object (IAIObject +0xFC) of a non-null `ignore` entry +// is refused. The flag is stored and never read. +class SphereExcludeFilter : public world::ObjectPredicator +{ +public: + SphereExcludeFilter(const std::vector& ignore, bool flag) + : m_ignore(&ignore) + , m_flag(flag) + { + } + + virtual bool predicate(world::IObject* object) + { + IAIObject* const aiObject = getIAIObject(object); + if (!aiObject) + return true; + for (std::vector::const_iterator it = m_ignore->begin(); it != m_ignore->end(); ++it) + { + if (*it && (*it)->getPrimaryObject() == aiObject) + return false; + } + return true; + } + virtual unsigned int getFlags() const { return 0x1000000; } + virtual bool performCulling(world::IObject*) { return true; } + + /* +0x04 */ const std::vector* m_ignore; + /* +0x08 */ bool m_flag; +}; + +// bf2 0x840B0C0 (vtable 0x88D7620): an engine-side wrapper of an AI filter. Objects without an AI +// object answer `noAIObject`; with one, the filter (if any) decides. +class AIPredWrapper : public world::ObjectPredicator +{ +public: + AIPredWrapper(AIObjectPredicate* filter, bool noAIObject) + : m_filter(filter) + , m_noAIObject(noAIObject) + { + } + + virtual bool predicate(world::IObject* object) + { + IAIObject* const aiObject = getIAIObject(object); + if (!aiObject) + return m_noAIObject; + if (!m_filter) + return true; + return m_filter->predicate(aiObject); + } + virtual unsigned int getFlags() const { return 0x1000000; } + virtual bool performCulling(world::IObject*) { return true; } + + /* +0x04 */ AIObjectPredicate* m_filter; + /* +0x08 */ bool m_noAIObject; +}; + +// bf2 0x840B130 / 0x840B180 (vtable 0x88D7608): AIPredWrapper's test, and see-through surfaces +// (material +0x7C) do not stop a line. +class AISeeingPredWrapper : public world::ObjectPredicator +{ +public: + AISeeingPredWrapper(AIObjectPredicate* filter, bool noAIObject) + : m_filter(filter) + , m_noAIObject(noAIObject) + { + } + + virtual bool predicate(world::IObject* object) + { + IAIObject* const aiObject = getIAIObject(object); + if (!aiObject) + return m_noAIObject; + if (!m_filter) + return true; + return m_filter->predicate(aiObject); + } + virtual unsigned int getFlags() const { return 0x1000000; } + virtual bool performCulling(world::IObject*) { return true; } + virtual bool predicateSurface(int surface) + { + world::Material* const material = static_cast(world::materialManager) + ->getMaterialPtr(static_cast(surface)); // +0x24 + return !material->getIsSeeThrough(); // +0x7C + } + + /* +0x04 */ AIObjectPredicate* m_filter; + /* +0x08 */ bool m_noAIObject; +}; + +// The image's inlined uniform draw, 2^-24 * ((((raw >> 7) | 1) + 1)), and the rounded index pick +// built on it: lo + (hi - lo) * draw + 0.5, truncated. [CHOSEN] helper spellings for inlined code. +inline float randomUnit() +{ + return static_cast(static_cast(((Rand.getRaw() >> 7) | 1u) + 1u)) * 5.9604645e-08f; +} + +inline unsigned int randomIndex(float hi) +{ + const float lo = 0.0f; + return static_cast(static_cast(lo + (hi - lo) * randomUnit() + 0.5f)); +} + +// Row-vector point transform, p * m (m[12..14] the translation). [CHOSEN] spelling of the inlined +// operator. +inline Vec3 transformPoint(const Vec3& p, const Mat4& m) +{ + Vec3 out; + out.x = p.x * m.m[0] + p.y * m.m[4] + p.z * m.m[8] + m.m[12]; + out.y = p.x * m.m[1] + p.y * m.m[5] + p.z * m.m[9] + m.m[13]; + out.z = p.x * m.m[2] + p.y * m.m[6] + p.z * m.m[10] + m.m[14]; + return out; +} + +// Common topology in ELF 0x8405F70 and 0x8407300. IDs are relative to zero even on append. +void appendBoxTopology(IAIObjectEnvironment::Mesh& mesh) +{ + static const std::pair edges[] = { + {0, 1}, {0, 2}, {0, 4}, {0, 6}, {1, 2}, {1, 3}, {1, 4}, {1, 5}, {2, 3}, + {2, 6}, {2, 7}, {3, 5}, {3, 7}, {4, 5}, {4, 6}, {4, 7}, {5, 7}, {6, 7} + }; + static const triple faces[] = { + {12, 10, 8}, {10, 17, 9}, {9, 3, 1}, {3, 14, 2}, {2, 6, 0}, {13, 7, 6}, + {17, 15, 14}, {15, 16, 13}, {16, 12, 11}, {11, 5, 7}, {8, 4, 5}, {4, 1, 0} + }; + mesh.edges.reserve(18); + for (unsigned int i = 0; i < 18; ++i) + mesh.edges.push_back(edges[i]); + for (unsigned int i = 0; i < 12; ++i) + mesh.faces.push_back(make_triple(faces[i].first, faces[i].second, faces[i].third)); +} + +} // namespace + // First wins in, exact match out. IAIObjectEnvironment::IAIObjectEnvironment() { @@ -49,47 +413,143 @@ IAIObjectEnvironment::~IAIObjectEnvironment() } } -// Zeroes the opaque vector storage, flag, and severe-damage timestamp separately. +// bf2 0x8400CA0: the three vectors default-constructed, the flag and severe-damage timestamp zeroed. // Leaves padding at +0x29..+0x2B untouched. BFObjectEnvironment::BFObjectEnvironment() { - std::memset(m_opaque, 0, sizeof(m_opaque)); // +0x04 .. +0x27, the three vectors m_byte28 = 0; // +0x28, a byte m_lastSevereDamageTime = 0.0; // +0x2C, a double } +// bf2 0x8400DA0: the members' destructors (the three vectors, last first). BFObjectEnvironment::~BFObjectEnvironment() { } +// bf2 0x8400F50 (Hex-Rays; listing for the call). The frustum query (object manager +0x50, flag +// true, 0.0, 0.0) into the scratch list through AIPredWrapper(filter, false), then each AI object. void BFObjectEnvironment::getWorldFrustumObjects(std::vector& out, const Frustum& frustum, AIObjectPredicate* filter) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getWorldFrustumObjects"); + std::vector& objects = const_cast&>(m_senseObjects); + objects.resize(0); + AIPredWrapper wrapper(filter, false); + world::objectManager->getObjectsFromGrid(frustum, objects, &wrapper, true, 0.0f, 0.0f); // +0x50 + pushAIObjects(out, objects); } +// bf2 0x84010C0 (Hex-Rays). As getWorldFrustumObjects with the sphere query (+0x40). void BFObjectEnvironment::getWorldSphereObjects(std::vector& out, const Vec3& centre, float radius, AIObjectPredicate* filter) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getWorldSphereObjects"); + std::vector& objects = const_cast&>(m_senseObjects); + objects.resize(0); + AIPredWrapper wrapper(filter, false); + world::objectManager->getObjectsFromGrid(centre, radius, objects, &wrapper); // +0x40 + pushAIObjects(out, objects); } +// bf2 0x8401230 (Hex-Rays). As getWorldFrustumObjects with the whole-grid query (+0x3C). void BFObjectEnvironment::getAllWorldObjects(std::vector& out, AIObjectPredicate* filter) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getAllWorldObjects"); + std::vector& objects = const_cast&>(m_senseObjects); + objects.resize(0); + AIPredWrapper wrapper(filter, false); + world::objectManager->getObjectsFromGrid(objects, &wrapper); // +0x3C + pushAIObjects(out, objects); } void BFObjectEnvironment::getAllDestroyableObjects(std::vector& out) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getAllDestroyableObjects"); + // ELF 0x8401390. This query does not clear the scratch vector before dispatch. + DestroyableObjectsPredicate predicate; + std::vector& objects = const_cast&>(m_senseObjects); + world::objectManager->getObjectsFromGrid(objects, &predicate); + for (std::vector::const_iterator it = objects.begin(); it != objects.end(); ++it) + { + world::DestroyableObjectTemplate* const objectTemplate = + static_cast(static_cast( + (*it)->getTemplate()->queryInterface(world::IID_IObjectTemplate))); + DestroyableObject entry; + entry.initiallyWalkable = objectTemplate->initiallyWalkable; + entry.min = Vec3{objectTemplate->minCorner[0], objectTemplate->minCorner[1], objectTemplate->minCorner[2]}; + entry.max = Vec3{objectTemplate->maxCorner[0], objectTemplate->maxCorner[1], objectTemplate->maxCorner[2]}; + entry.transform = (*it)->getAbsoluteTransformation(); + out.push_back(entry); + } } +// bf2 0x8401670: every player in the player manager's list (+0x3C), its id (IPlayer +0x54). void BFObjectEnvironment::getWorldPlayerIds(std::vector& out) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getWorldPlayerIds"); + const std::list& players = world::playerManager->getPlayers(); + for (std::list::const_iterator it = players.begin(); it != players.end(); ++it) + out.push_back((*it)->getId()); } +// bf2 0x8401700. Every alive, not man-down player with a vehicle contributes its vehicle's AI +// object (for ladder, zipline and grappling-hook containers the occupying object's, for a +// parachute the IPlayerControlObject's occupying object's, unchecked). A primary object (+0xF8) +// is taken directly (through the filter, if any); any other object contributes its primary object +// (+0xFC) to a set, and each set member whose unit is not occupied (IAIObjectUnit +0x48) is +// taken afterwards, also through the filter. void BFObjectEnvironment::getWorldPlayerOccupiedObjects(std::vector& out, AIObjectPredicate* filter) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getWorldPlayerOccupiedObjects"); + const std::list& players = world::playerManager->getPlayers(); + std::set primaries; + for (std::list::const_iterator it = players.begin(); it != players.end(); ++it) + { + world::IPlayer* const player = *it; + if (!player || !player->getIsAlive() || player->getIsManDown() || !player->getVehicle()) + continue; + + IAIObject* aiObject = static_cast(player->getVehicle()->getAIComponent()); + if (!aiObject) + { + const unsigned int classId = player->getVehicle()->getTemplate()->getClassID(); + if (classId == world::CID_LadderContainerTemplate) + { + world::IObject* const occupying = + static_cast(player->getVehicle())->getOccupingObject(); + if (occupying) + aiObject = static_cast(occupying->getAIComponent()); + } + else if (player->getVehicle()->getTemplate()->getClassID() == world::CID_ParachuteTemplate) + { + world::IPlayerControlObject* const control = static_cast( + player->getVehicle()->queryInterface(world::IID_IPlayerControlObject)); + aiObject = static_cast(control->getOccupingObject()->getAIComponent()); + } + else if (player->getVehicle()->getTemplate()->getClassID() == world::CID_ZiplineContainerTemplate + || player->getVehicle()->getTemplate()->getClassID() + == world::CID_GrapplingHookRopeContainerTemplate) + { + world::IObject* const occupying = + static_cast(player->getVehicle())->getOccupingObject(); + if (occupying) + aiObject = static_cast(occupying->getAIComponent()); + } + if (!aiObject) + continue; + } + + if (aiObject->isPrimary()) + { + if (!filter || filter->predicate(aiObject)) + out.push_back(aiObject); + } + else + { + primaries.insert(aiObject->getPrimaryObject()); + } + } + + for (std::set::const_iterator it = primaries.begin(); it != primaries.end(); ++it) + { + IAIObject* const primary = *it; + if (primary->getUnit()->isOccupied()) + continue; + if (!filter || filter->predicate(primary)) + out.push_back(primary); + } } // Collects AI objects matching the supplied predicate within the requested region. @@ -146,29 +606,70 @@ void BFObjectEnvironment::getWorldPlayerOccupiedObjectsWithIds(std::vectorgetLocalHumanPlayer(); // +0x30 + if (!player) + return 0; + world::IObject* const vehicle = player->getVehicle(); // +0x48 + return vehicle ? static_cast(vehicle->getAIComponent()) : 0; } +// bf2 0x8403320 (Hex-Rays): the translation of the local human player's camera (IPlayer +0x180, +// as an IObject, unchecked). bool BFObjectEnvironment::getLocalPlayerPosition(Vec3& position) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getLocalPlayerPosition"); + if (!world::playerManager) + return false; + world::IPlayer* const player = world::playerManager->getLocalHumanPlayer(); + if (!player) + return false; + world::ICameraObject* const camera = player->getCamera(); // +0x180 + if (!camera) + return false; + world::IObject* const object = static_cast(camera->queryInterface(world::IID_IObject)); + const Mat4& transform = object->getAbsoluteTransformation(); + position.x = transform.m[12]; + position.y = transform.m[13]; + position.z = transform.m[14]; + return true; } +// bf2 0x84033A0 (Hex-Rays): the local human player's camera transformation (no player-manager +// null test here). bool BFObjectEnvironment::getLocalPlayerCameraTransformation(Mat4& transform) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getLocalPlayerCameraTransformation"); + world::IPlayer* const player = world::playerManager->getLocalHumanPlayer(); + if (!player) + return false; + world::ICameraObject* const camera = player->getCamera(); + if (!camera) + return false; + world::IObject* const object = static_cast(camera->queryInterface(world::IID_IObject)); + transform = object->getAbsoluteTransformation(); + return true; } +// bf2 0x8403490 (Hex-Rays): the local human player's id, 0 without one. int BFObjectEnvironment::getLocalPlayerId() const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getLocalPlayerId"); + world::IPlayer* const player = world::playerManager->getLocalHumanPlayer(); + return player ? player->getId() : 0; } +// bf2 0x84034C0 (Hex-Rays): the ids of connected human players, rebuilt in the member list. const std::vector& BFObjectEnvironment::getActivePlayerIds() const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getActivePlayerIds"); + const std::list& players = world::playerManager->getPlayers(); // +0x3C + std::vector& ids = const_cast&>(m_activePlayerIds); + ids.resize(0); + for (std::list::const_iterator it = players.begin(); it != players.end(); ++it) + { + if (!(*it)->getIsAIPlayer() && (*it)->getIsConnected()) // +0x64, +0x78 + ids.push_back((*it)->getId()); + } + return m_activePlayerIds; } // Returns whether PlayerManager resolves the id to a player. @@ -177,105 +678,613 @@ bool BFObjectEnvironment::isValidPlayerId(int id) const return world::playerManager->getPlayerFromId(id) != 0; } +// bf2 0x8403600. The player after `id` (+0x24 getNextPlayerFromId) is answered when it is a +// connected human; AI players and disconnected ones are skipped by asking again with the same +// id, which returns the same player, so the loop ends at -1. Read literally. int BFObjectEnvironment::getNextPlayerId(int id) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getNextPlayerId"); + world::IPlayer* const first = world::playerManager->getNextPlayerFromId(id); + if (!first) + return -1; + world::IPlayer* player = first; + do + { + if (!player->getIsAIPlayer() && player->getIsConnected()) + return player->getId(); + player = world::playerManager->getNextPlayerFromId(id); + } + while (player != first); + return -1; } +// bf2 0x8401DD0 (ELF listing, Ghidra cross-check). The terrain first (IAITerrain +0x64 +// intersectTerrain into zeroed scratch); a terrain hit is a hit. Otherwise the answer is the +// object test (this +0x90, collideLineWithObjects) with every argument forwarded. The image also +// computes `to - from` into a local that nothing reads; it is left out. bool BFObjectEnvironment::collideLineWithWorld(const Vec3& from, const Vec3& to, const std::vector& ignore, bool a, float b, bool c, bool& hit) { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::collideLineWithWorld"); + Vec3 terrainHit; + terrainHit.x = 0.0f; + terrainHit.y = 0.0f; + terrainHit.z = 0.0f; + Vec3 terrainNormal; + terrainNormal.x = 0.0f; + terrainNormal.y = 0.0f; + terrainNormal.z = 0.0f; + float distance; + if (static_cast(CommonSingletonServer::m_iaiTerrain) + ->intersectTerrain(from, to, terrainHit, distance, terrainNormal)) // +0x64 + return true; + return collideLineWithObjects(from, to, ignore, a, b, c, hit) != 0; // +0x90 } +// bf2 0x8401FF0 (listing). Objects first: intersectLine (+0x68, flags 1, 0, 0, 1, mask 0) along +// `to - from` through AISeeingPredWrapper(filter, true), or no predicate at all without a filter; +// then the terrain (IAITerrain +0x64). The hit point goes to `hit`, or a local when it is null. bool BFObjectEnvironment::collideLineWithWorld(const Vec3& from, const Vec3& to, AIObjectPredicate* filter, Vec3* hit) { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::collideLineWithWorld"); + Vec3 localHit; + localHit.x = 0.0f; + localHit.y = 0.0f; + localHit.z = 0.0f; + Vec3& hitPoint = hit ? *hit : localHit; + Vec3 normal; + normal.x = 0.0f; + normal.y = 0.0f; + normal.z = 0.0f; + Vec3 direction; + direction.x = to.x - from.x; + direction.y = to.y - from.y; + direction.z = to.z - from.z; + AISeeingPredWrapper wrapper(filter, true); + world::IObject* hitObject; + int hitPart; + if (world::objectManager->intersectLine(hitObject, hitPoint, normal, hitPart, from, direction, + filter ? &wrapper : 0, true, false, false, true, 0)) // +0x68 + return true; + float distance; + return static_cast(CommonSingletonServer::m_iaiTerrain) + ->intersectTerrain(from, to, hitPoint, distance, normal) != 0; // +0x64 } +// bf2 0x8401EC0 (Hex-Rays; listing for the calls). The first object hit along `to - from` +// (AIPredWrapper(filter, true), or none without a filter), else the terrain hit; `height` is that +// point's y. False when neither is hit (height untouched). bool BFObjectEnvironment::getMaxHeight(const Vec3& from, const Vec3& to, AIObjectPredicate* filter, float& height) { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getMaxHeight"); + AIPredWrapper wrapper(filter, true); + Vec3 hitPoint; + hitPoint.x = 0.0f; + hitPoint.y = 0.0f; + hitPoint.z = 0.0f; + Vec3 normal; + normal.x = 0.0f; + normal.y = 0.0f; + normal.z = 0.0f; + Vec3 direction; + direction.x = to.x - from.x; + direction.y = to.y - from.y; + direction.z = to.z - from.z; + world::IObject* hitObject; + int hitPart; + float distance; + if (world::objectManager->intersectLine(hitObject, hitPoint, normal, hitPart, from, direction, + filter ? &wrapper : 0, true, false, false, true, 0) + || static_cast(CommonSingletonServer::m_iaiTerrain) + ->intersectTerrain(from, to, hitPoint, distance, normal)) + { + height = hitPoint.y; + return true; + } + return false; } +// Engine ELF 0x84022F0 (amd-64 0x7715E0). Tests both segments through the helper's apex. +// shipped defect: this calls pure IAimerHelper slot 2, not AimerHelper's by-value-float slot 3. +// No AimerHelper is constructed in either AI image; no null guard is added to the retail call. bool BFObjectEnvironment::hasIndirectLineOfFire(IWeapon* weapon, const Vec3& from, const Vec3& to, const std::vector& ignore) { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::hasIndirectLineOfFire"); + static Vec3 zero = { 0.0f, 0.0f, 0.0f }; + (void)zero; + const float gravity = static_cast(CommonSingletonServer::m_iaiPhysics)->getGravity(); // +0x08 + Vec3 predictedTarget = {0.0f, 0.0f, 0.0f}; + Vec3 velocity = {0.0f, 0.0f, 0.0f}; + Vec3 apex = {0.0f, 0.0f, 0.0f}; + const Vec3& weaponPosition = weapon->getPosition(); // +0x5C + Vec3 delta; + delta.x = to.x - from.x; + delta.y = to.y - from.y; + delta.z = to.z - from.z; + const float scaledGravity = weapon->getGravityModifier() * gravity; // +0x80 + const float drag = weapon->getDrag(); // +0x7C + const float exitVelocity = weapon->getExitVelocity(); // +0x84 + if (!static_cast(CommonSingletonServer::m_iAimerHelper)->unimplementedAimerSlot2( + &exitVelocity, &drag, &scaledGravity, &delta, &weaponPosition, &predictedTarget, &velocity, &apex)) + return false; + bool hit; + return !collideLineWithWorld(from, apex, ignore, false, 0.0f, false, hit) + && !collideLineWithWorld(apex, to, ignore, false, 0.0f, false, hit); } -void BFObjectEnvironment::pickRandomSensePosition(Vec3& position, Vec3& normal, Vec3 hint, IAIObject* object) +// bf2 0x84024B0 (ELF listing; Hex-Rays cross-check). A random point on the object's collision +// surface, in world space (`position`) and in the root object's frame (`localPosition`). The +// scratch list is the root and its getChild chain with a collision LOD 0. While no mesh is found +// and there is more than one candidate, a random candidate's collision mesh (IObject +0x40) is +// taken when it has LOD 0; failing that the first candidate's, unchecked. With faces, a random +// face and a uniform point in it (the u + v > 1 half folded back); with vertices only, a random +// vertex; with neither (or no candidates) the object's position and a zero local point. `hint` is +// not read. The object's bounding radius is fetched and discarded on the fallback path. +void BFObjectEnvironment::pickRandomSensePosition(Vec3& position, Vec3& localPosition, Vec3 hint, IAIObject* object) { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::pickRandomSensePosition"); + world::IObject* const root = object->getObject(); // +0x20 + m_senseObjects.resize(0); + + CollisionPredicate collision; + getAllChildren(root, m_senseObjects, &collision); + + if (!m_senseObjects.empty()) + { + Mat4 rootInverse = root->getAbsoluteTransformation(); // slot 33 + const Mat4 rootTransform = rootInverse; + rootInverse.setInverse(rootTransform); + + world::ICollisionMesh* mesh = 0; + world::IObject* chosen = 0; + while (!mesh && m_senseObjects.size() > 1) + { + chosen = m_senseObjects[randomIndex(static_cast(m_senseObjects.size()) - 1.0f)]; + if (chosen->hasCollisionLod(0)) + mesh = static_cast(world::object_detail::LayoutAccess::collisionMesh(chosen)); + } + if (!mesh) + { + chosen = m_senseObjects[0]; + if (chosen->hasCollisionLod(0)) + mesh = static_cast(world::object_detail::LayoutAccess::collisionMesh(chosen)); + } + + const unsigned int faceCount = static_cast(mesh->getFaceCount(0)); // slot 19 + const unsigned int vertexCount = mesh->getVertexCount(0); // slot 16 + Vec3 world; + if (faceCount) + { + const unsigned int face = randomIndex(static_cast(faceCount) - 1.0f); + float u = randomUnit(); + float v = randomUnit(); + if (u + v > 1.0f) + { + u = 1.0f - u; + v = 1.0f - v; + } + const unsigned short* const faces = static_cast(mesh->getFaceVector(0)); // slot 20 + const Vec3* const vertices = static_cast(mesh->getVertexVector(0)); // slot 17 + const unsigned short* const f = faces + face * 4; // 8-byte faces + const Vec3& p0 = vertices[f[0]]; + Vec3 edge1; + edge1.x = vertices[f[1]].x - p0.x; + edge1.y = vertices[f[1]].y - p0.y; + edge1.z = vertices[f[1]].z - p0.z; + Vec3 edge2; + edge2.x = vertices[f[2]].x - p0.x; + edge2.y = vertices[f[2]].y - p0.y; + edge2.z = vertices[f[2]].z - p0.z; + localPosition.x = p0.x + edge1.x * u + edge2.x * v; + localPosition.y = p0.y + edge1.y * u + edge2.y * v; + localPosition.z = p0.z + edge1.z * u + edge2.z * v; + world = transformPoint(localPosition, chosen->getAbsoluteTransformation()); + } + else if (vertexCount) + { + const unsigned int vertex = randomIndex(static_cast(vertexCount - 1)); + localPosition = static_cast(mesh->getVertexVector(0))[vertex]; + world = transformPoint(localPosition, chosen->getAbsoluteTransformation()); + } + else + { + // The same fallback as an empty list (the image shares the block). + object->getBoundingRadius(); // +0xE8, unused + localPosition.x = 0.0f; + localPosition.y = 0.0f; + localPosition.z = 0.0f; + position = object->getPosition(); // +0xD4 + return; + } + position = world; + localPosition = transformPoint(world, rootInverse); + return; + } + + object->getBoundingRadius(); // +0xE8, unused + localPosition.x = 0.0f; + localPosition.y = 0.0f; + localPosition.z = 0.0f; + position = object->getPosition(); // +0xD4 } -bool BFObjectEnvironment::pickSoldierRandomSensePosition(Vec3& position, Vec3& normal, IAIObject* object, unsigned int& part) +// bf2 0x8403010 (listing; Hex-Rays cross-check), byte-identical to getSoldierSensePosition: for a +// soldier (object with an IObject, IAIObject +0xA4 isOfType(ITSoldier), template implementing +// CID_SoldierTemplate) the first camera of Soldier::getCameras (the map's leftmost entry, unchecked) +// as an IObject: its absolute position and its relative position. `part` is neither read nor written. +bool BFObjectEnvironment::pickSoldierRandomSensePosition(Vec3& position, Vec3& localPosition, IAIObject* object, unsigned int& part) { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::pickSoldierRandomSensePosition"); + if (!object->getObject() || !object || !object->isOfType(ITSoldier)) // +0x20, +0xA4 + return false; + world::IObject* const soldier = object->getObject(); + if (!const_cast(soldier->getTemplate()) + ->queryImplementation(world::CID_SoldierTemplate)) // +0x50 + return false; + + world::ICameraObject* const camera = + static_cast(soldier)->getCameras()->begin()->second; // +0x1A4 + world::IObject* cameraObject = 0; + if (camera) + cameraObject = static_cast(camera->queryInterface(world::IID_IObject)); + position = cameraObject->getAbsolutePosition(); // +0x6C + localPosition = cameraObject->getRelativePosition(); // +0xE0 + return true; } -bool BFObjectEnvironment::getSoldierSensePosition(Vec3& position, Vec3& normal, IAIObject* object, unsigned int part) +// bf2 0x8403100 (listing; Hex-Rays cross-check). See pickSoldierRandomSensePosition; `part` unused. +bool BFObjectEnvironment::getSoldierSensePosition(Vec3& position, Vec3& localPosition, IAIObject* object, unsigned int part) { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getSoldierSensePosition"); + if (!object->getObject() || !object || !object->isOfType(ITSoldier)) // +0x20, +0xA4 + return false; + world::IObject* const soldier = object->getObject(); + if (!const_cast(soldier->getTemplate()) + ->queryImplementation(world::CID_SoldierTemplate)) // +0x50 + return false; + + world::ICameraObject* const camera = + static_cast(soldier)->getCameras()->begin()->second; // +0x1A4 + world::IObject* cameraObject = 0; + if (camera) + cameraObject = static_cast(camera->queryInterface(world::IID_IObject)); + position = cameraObject->getAbsolutePosition(); // +0x6C + localPosition = cameraObject->getRelativePosition(); // +0xE0 + return true; } +// bf2 0x84031F0 (listing). `slope` is the physical plug-in's smallest radius (+0x94, +0x44); +// height and normal are the terrain's at the position's x/z (IAITerrain +0x28). The object's +// position and an isOfType(ITSoldier) answer are fetched, and a probe segment from radius above +// the object's height down by 2 * radius is built, but none of them is used. Returns 0. int BFObjectEnvironment::getHeightAndNormalForObject(IAIObject* object, const Vec3& position, float& height, Vec3& normal, float& slope) { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getHeightAndNormalForObject"); + const float radius = object->getPhysical()->getSmallestRadius(); + slope = radius; + const Vec3 objectPosition = object->getPosition(); // +0xD4 + object->isOfType(ITSoldier); // +0xA4, unused + Vec3 probeFrom; + probeFrom.x = position.x; + probeFrom.y = radius + objectPosition.y; + probeFrom.z = position.z; + Vec3 probeDelta; + probeDelta.x = 0.0f; + probeDelta.y = radius * -2.0f; + probeDelta.z = 0.0f; + (void)probeFrom; + (void)probeDelta; + Vec3 terrainNormal; + terrainNormal.x = 0.0f; + terrainNormal.y = 0.0f; + terrainNormal.z = 0.0f; + unsigned char material; + height = static_cast(CommonSingletonServer::m_iaiTerrain) + ->getHeightAndNormal(position.x, position.z, terrainNormal, material); // +0x28 + normal = terrainNormal; + return 0; } -void BFObjectEnvironment::getVehicleSpawnerPositions(std::vector& out, unsigned char team) const +// ELF 0x8403770. The team parameter is unused; the object map is copied before iteration. +void BFObjectEnvironment::getVehicleSpawnerPositions(std::vector& out, unsigned char /*team*/) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getVehicleSpawnerPositions"); + const std::map objects = world::objectManager->getAllObjectsFromGrid(); + for (std::map::const_iterator it = objects.begin(); it != objects.end(); ++it) + { + world::IObject* const object = it->second; + if (object->getNotInAI() || object->getTemplate()->getClassID() != world::CID_ObjectSpawnerTemplate) + continue; + const world::ObjectSpawnerTemplate* const spawner = + static_cast(object->getTemplate()); + for (unsigned int slot = 0; slot <= 2; ++slot) + { + const std::string name = spawner->getObjectTemplate(slot); + world::IObjectTemplate* const objectTemplate = world::objectTemplateManager->getTemplate(name); + if (!objectTemplate) + break; + world::SimpleObjectTemplate* const simple = static_cast( + objectTemplate->queryImplementation(world::CID_SimpleObjectTemplate)); + if (simple) + { + const std::string aiName = simple->m_aiTemplate; + if (!aiName.empty()) + { + AITemplate* const aiTemplate = AITemplateManager::m_instance->getTemplate(aiName); + if (aiTemplate && !(aiTemplate->m_types & 4) && aiTemplate->isMobile()) + out.push_back(object->getAbsolutePosition()); + } + } + } + } } +// bf2 0x8403680: the object manager's name lookup (+0x24), its cached AI component (+0x34). IAIObject* BFObjectEnvironment::getObjectFromName(const std::string& name) { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getObjectFromName"); + world::IObject* const object = world::objectManager->getObjectFromNameHash(name); + return object ? static_cast(object->getAIComponent()) : 0; } -int BFObjectEnvironment::getAllStaticCollisionMeshes(std::list& meshes, std::list& water, std::map& addOns, std::list& more, std::pair& bounds, unsigned char team) const +// bf2 0x84036B0 (Hex-Rays; listing). The boundary query (+0x6C) over the primary terrain's +// extent (IAITerrain +0x54 .. +0x60, as floats). +bool BFObjectEnvironment::getAllStaticCollisionMeshes(std::list& meshes, std::list& water, std::map& addOns, std::list& more, std::pair& bounds, unsigned char team) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getAllStaticCollisionMeshes"); + IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + Vec2 min; + min.x = static_cast(terrain->getPrimaryWorldMinX()); + min.y = static_cast(terrain->getPrimaryWorldMinZ()); + Vec2 max; + max.x = static_cast(terrain->getPrimaryWorldMaxX()); + max.y = static_cast(terrain->getPrimaryWorldMaxZ()); + return getAllStaticCollisionMeshesWithinBoundary(min, max, meshes, water, addOns, more, bounds, team); } -int BFObjectEnvironment::getAllStaticCollisionMeshesWithinBoundary(const Vec2& min, const Vec2& max, std::list& meshes, std::list& water, std::map& addOns, std::list& more, std::pair& bounds, unsigned char team) const +bool BFObjectEnvironment::getAllStaticCollisionMeshesWithinBoundary(const Vec2& min, const Vec2& max, std::list& meshes, std::list& water, std::map& addOns, std::list& more, std::pair& bounds, unsigned char team) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getAllStaticCollisionMeshesWithinBoundary"); + // ELF 0x8403B20. The team parameter does not participate in this query. + (void)team; + std::vector objects; + Vec3 boxMin = {0.0f, 0.0f, 0.0f}, boxMax = {0.0f, 0.0f, 0.0f}; + NoMobilePredicate noMobile; + ObjectSpawnerPredicate spawners; + vec2ToVec3XZ(min, boxMin); + vec2ToVec3XZ(max, boxMax); + world::objectManager->getObjectsInBoxFromGrid(boxMin, boxMax, objects, &noMobile); + world::objectManager->getObjectsInBoxFromGrid(boxMin, boxMax, objects, &spawners); + std::pair combatBounds; + combatBounds.first = Vec2{0.0f, 0.0f}; + combatBounds.second = Vec2{0.0f, 0.0f}; + createBoundingBoxFromCombatAreas(combatBounds); + bounds = combatBounds; + + for (std::vector::const_iterator it = objects.begin(); it != objects.end(); ++it) + { + world::IObject* const object = *it; + world::IObjectTemplate* const objectTemplate = static_cast( + object->getTemplate()->queryInterface(world::IID_IObjectTemplate)); + if (!objectTemplate) + continue; + const std::string& name = objectTemplate->getName(); + objectTemplate->getClassID(); // The shipped body discards this query. + if (object->getNotInAI()) + continue; + if (object->getTemplate()->getClassID() != world::CID_ObjectSpawnerTemplate) + { + if (hasOnlyInfantryCollMesh(object) || !objectOverlapsCombatAreas(object, bounds)) + continue; + const Mat4& transform = object->getAbsoluteTransformation(); + if (object->hasCollisionLod(3)) + { + world::ICollisionMesh* const collision = static_cast( + world::object_detail::LayoutAccess::collisionMesh(object)); + if (objectTemplate->getClassID() == world::CID_DestroyableObjectTemplate) + { + world::DestroyableObjectTemplate* const destroyable = + static_cast(objectTemplate); + if (destroyable->usedByAi) + { + DestroyableAddOnMesh entry; + entry.name = object->getTemplate()->getName(); + entry.initiallyWalkable = destroyable->initiallyWalkable; + const Vec3 low = {destroyable->minCorner[0], destroyable->minCorner[1], destroyable->minCorner[2]}; + const Vec3 high = {destroyable->maxCorner[0], destroyable->maxCorner[1], destroyable->maxCorner[2]}; + createBoundingBoxFromLocalCoordinates(low, high, transform, entry.mesh); + const IAIObject* const aiObject = static_cast(object->getAIComponent()); + addOns.insert(std::make_pair(aiObject, entry)); + } + if (!destroyable->initiallyWalkable) + continue; + } + const bool ladder = objectTemplate->getClassID() == world::CID_LadderTemplate; + std::list& output = ladder ? more : meshes; + { + MeshAndBoundingBox entry; + entry.name = name; + // shipped defect: the owner is copied before it is assigned below. + output.push_back(entry); + } + MeshAndBoundingBox& entry = output.back(); + entry.object = static_cast(object->getAIComponent()); + createMeshFromObject(collision, 3, transform, entry.mesh); + const LocalBoundingBox* const box = collision->getBoundingBox(3); + createBoundingBoxFromLocalCoordinates(box->m_min, box->m_max, transform, entry.boundingBox); + } + else if (object->hasCollisionLod(0)) + { + world::ICollisionMesh* const collision = static_cast( + world::object_detail::LayoutAccess::collisionMesh(object)); + std::vector>* const materials = objectTemplate->getMaterialVector(); + const int count = static_cast(materials->size()); + bool hasWater = false; + for (int i = 0; i < count; ++i) + { + world::Material* const material = static_cast(world::materialManager) + ->getMaterialPtr((*materials)[i].second); + if (material->getHasWaterPhysics()) + { + hasWater = true; + break; + } + } + if (hasWater) + { + WaterMesh entry; // The retail name stays empty. + createMeshFromObject(collision, 0, transform, entry.mesh); + water.push_back(entry); + } + } + continue; + } + + const world::ObjectSpawnerTemplate* const spawner = + static_cast(object->getTemplate()); + bool valid[3] = {false, false, false}; + Mesh slotMeshes[3]; + bool rejected = false; + for (unsigned int slot = 0; slot <= 2; ++slot) + { + const std::string templateName = spawner->getObjectTemplate(slot); + world::IObjectTemplate* const spawnedTemplate = world::objectTemplateManager->getTemplate(templateName); + if (!spawnedTemplate) + continue; + const Vec3 rotation = Vec3::getZero(); + const Vec3 position = Vec3::getZero(); + world::IObject* const spawned = gameLogic->spawnObject(spawnedTemplate, position, rotation, 0); + if (spawned->queryInterface(world::IID_IPlayerControlObject)) + { + world::IPhysicsNode* const node = static_cast( + world::object_detail::LayoutAccess::physicsNode(spawned)); + if (node && node->getIsMobile()) + { + game->destroyObject(spawned); + rejected = true; + break; + } + } + world::IObjectTemplate* const spawnedObjectTemplate = static_cast( + spawned->getTemplate()->queryInterface(world::IID_IObjectTemplate)); + if (spawnedObjectTemplate->getClassID() == world::CID_DestroyableObjectTemplate + && static_cast(spawnedObjectTemplate)->usedByAi) + { + game->destroyObject(spawned); + rejected = true; + break; + } + const Mat4& transform = object->getAbsoluteTransformation(); + if (spawned->hasCollisionLod(3)) + { + world::ICollisionMesh* const collision = static_cast( + world::object_detail::LayoutAccess::collisionMesh(spawned)); + const LocalBoundingBox* const box = collision->getBoundingBox(3); + createBoundingBoxFromLocalCoordinates(box->m_min, box->m_max, transform, slotMeshes[slot]); + game->destroyObject(spawned); + valid[slot] = true; + } + else + game->destroyObject(spawned); + } + if (rejected || (!valid[0] && !valid[1] && !valid[2])) + continue; + { + MeshAndBoundingBox entry; + entry.name = name; + meshes.push_back(entry); + } + MeshAndBoundingBox& entry = meshes.back(); + entry.object = 0; + Vec3 low = {100000.0f, 100000.0f, 100000.0f}; + Vec3 high = {-100000.0f, -100000.0f, -100000.0f}; + for (unsigned int slot = 0; slot <= 2; ++slot) + { + if (!valid[slot]) + continue; + for (unsigned int i = 0; i < slotMeshes[slot].vertices.size(); ++i) + { + const Vec3& p = slotMeshes[slot].vertices[i]; + if (low.x > p.x) low.x = p.x; + if (low.y > p.y) low.y = p.y; + if (low.z > p.z) low.z = p.z; + if (p.x > high.x) high.x = p.x; + if (p.y > high.y) high.y = p.y; + if (p.z > high.z) high.z = p.z; + } + } + createBoundingBoxFromWorldCoordinates(low, high, entry.boundingBox); + createBoundingBoxFromWorldCoordinates(low, high, entry.mesh); + } + bounds.first.x -= 3.0f; + bounds.first.y -= 3.0f; + bounds.second.x += 3.0f; + bounds.second.y += 3.0f; + return true; } +// bf2 0x8405840 (Hex-Rays): an object in the grid (object manager +0x30) without a physics node, +// or whose node sleeps (+0x11C). Unknown ids are not asleep. bool BFObjectEnvironment::isAsleep(unsigned int id) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::isAsleep"); + world::IObject* const object = world::objectManager->getObjectFromGrid(id); + if (!object) + return false; + world::IPhysicsNode* const node = + static_cast(world::object_detail::LayoutAccess::physicsNode(object)); // +0x44 + return !node || node->getIsSleeping(); } -int BFObjectEnvironment::getTargetObjects(std::vector& out, int team) const +// ELF 0x8405740. The target map's owning player determines the team filter. +void BFObjectEnvironment::getTargetObjects(std::vector& out, int team) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getTargetObjects"); + const std::map* const objects = + static_cast*>(gameLogic->getTargetObjectMap()); + for (std::map::const_iterator it = objects->begin(); it != objects->end(); ++it) + { + world::IObject* const object = it->second; + world::IPlayer* const player = world::playerManager->getPlayerFromId( + static_cast(object)->getTargetPlayerId()); + if (player && player->getTeam() == team) + { + IAIObject* const aiObject = static_cast(world::getRootParent(object)->getAIComponent()); + const Vec3& position = object->getAbsolutePosition(); + out.push_back(TargetData(it->first, position, aiObject)); + } + } } -// ELF, 10 bytes. Empty in the dedicated image. -void BFObjectEnvironment::loadOvergrowthCollision(const std::string& path) const +// bf2 0x8405890, 10 bytes: `mov eax, 1` and return; the materialised 1 is why the declaration +// returns bool (the mangled name carries no return type). +bool BFObjectEnvironment::loadOvergrowthCollision(const std::string& path) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::loadOvergrowthCollision"); + return true; } bool BFObjectEnvironment::initAiCombatAreas() const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::initAiCombatAreas"); + // ELF 0x84058A0. Capture the singleton before resizing the vector. + CombatAreaManager* const manager = CombatAreaManager::getInstance(); + std::vector& areas = const_cast&>(m_combatAreas); + areas.resize(0); + return manager->getAiCombatAreas(areas); } bool BFObjectEnvironment::isAiPositionInsideCombatArea(const Vec3& position) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::isAiPositionInsideCombatArea"); + // ELF 0x8405930. + return CombatAreaManager::getInstance()->isAiPositionInside(position, m_combatAreas); } +// bf2 0x8405960 (Hex-Rays; listing): the first AI combat area's layer, read as a byte (movzbl +// of +0x30), or 255 without one. int BFObjectEnvironment::getAiCombatAreaLayer() const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getAiCombatAreaLayer"); + int layer = 255; + if (m_combatAreas.size()) + layer = *reinterpret_cast(&m_combatAreas[0]->m_layer); + return layer; } -int BFObjectEnvironment::getAICombatArea(std::list& out) const +// ELF 0x8405990. Always clear the output, then orient the first area's polygon clockwise. +void BFObjectEnvironment::getAICombatArea(std::list& out) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getAICombatArea"); + out.clear(); + if (m_combatAreas.empty()) + return; + const CombatArea* const area = m_combatAreas[0]; + if (area->isClockwise()) + for (std::vector::const_iterator it = area->m_points.begin(); it != area->m_points.end(); ++it) + out.push_back(*it); + else + for (std::vector::const_reverse_iterator it = area->m_points.rbegin(); it != area->m_points.rend(); ++it) + out.push_back(*it); } // Updates the AI object environment during the simulation tick. @@ -336,9 +1345,224 @@ void BFObjectEnvironment::damageSeverelyDamagedVehicles() } } -int BFObjectEnvironment::collideLineWithObjects(const Vec3& from, const Vec3& to, const std::vector& ignore, bool a, float b, bool c, bool& hit) +// bf2 0x8402130 (listing; Hex-Rays cross-check). The object line test from `from` along +// `to - from`: without spheres the object manager's intersectLine (+0x68, flags 1, 0, 0, 1, mask 0) +// through a RayCastStopPredicate; with spheres intersectLineWithSpheres (+0x70) with a +// SphereExcludeFilter first and the stop predicate second, `sphereRadius` last. `hitBeyondSeeThrough` +// is whether the hit point lies farther from `from` than the nearest see-through surface the stop +// predicate skipped (always false when none was). Returns the intersection's answer. +// bf2 0x8408350 (Hex-Rays). Reserves for the new objects, then appends each object's AI object +// (getIAIObject), skipping objects without one. `objects` is taken by value. +void BFObjectEnvironment::pushAIObjects(std::vector& out, std::vector objects) const +{ + out.reserve(objects.size() + out.size()); + for (std::vector::iterator it = objects.begin(); it != objects.end(); ++it) + { + IAIObject* const aiObject = getIAIObject(*it); + if (aiObject) + out.push_back(aiObject); + } +} + +int BFObjectEnvironment::collideLineWithObjects(const Vec3& from, const Vec3& to, const std::vector& ignore, bool useSpheres, float sphereRadius, bool seeThroughStops, bool& hitBeyondSeeThrough) +{ + Vec3 hitPoint; + hitPoint.x = 0.0f; + hitPoint.y = 0.0f; + hitPoint.z = 0.0f; + Vec3 hitNormal; + hitNormal.x = 0.0f; + hitNormal.y = 0.0f; + hitNormal.z = 0.0f; + Vec3 unused; // a third zeroed Vec3 (-0x38), never passed + unused.x = 0.0f; + unused.y = 0.0f; + unused.z = 0.0f; + (void)unused; + RayCastStopPredicate stop(ignore, seeThroughStops, from); + world::IObject* hitObject; + int hitPart; + bool result; + if (useSpheres) + { + SphereExcludeFilter exclude(ignore, seeThroughStops); + Vec3 direction; + direction.x = to.x - from.x; + direction.y = to.y - from.y; + direction.z = to.z - from.z; + result = world::objectManager->intersectLineWithSpheres(hitObject, hitPoint, hitNormal, hitPart, + from, direction, &exclude, &stop, + sphereRadius); // +0x70 + } + else + { + Vec3 direction; + direction.x = to.x - from.x; + direction.y = to.y - from.y; + direction.z = to.z - from.z; + result = world::objectManager->intersectLine(hitObject, hitPoint, hitNormal, hitPart, from, + direction, &stop, true, false, false, true, 0); // +0x68 + } + const float dx = hitPoint.x - from.x; + const float dy = hitPoint.y - from.y; + const float dz = hitPoint.z - from.z; + hitBeyondSeeThrough = dx * dx + dy * dy + dz * dz > stop.m_nearestSeeThroughSq; + return result; +} + +// ELF 0x8405C30. Each face contributes undirected edges, stored once in insertion order. +void BFObjectEnvironment::createMeshFromObject(world::ICollisionMesh* collision, int lod, + const Mat4& transform, Mesh& mesh) const +{ + const Vec3* const vertices = static_cast(collision->getVertexVector(lod)); + const int vertexCount = static_cast(collision->getVertexCount(lod)); + mesh.vertices.reserve(static_cast(vertexCount)); + for (int i = 0; i < vertexCount; ++i) + mesh.vertices.push_back(transformPoint(vertices[i], transform)); + + std::set uniqueEdges; + const int faceCount = collision->getFaceCount(lod); + // Three unsigned 16-bit indices in an eight-byte record; the last word is not read here. + struct ExportFace { unsigned short indices[3]; unsigned char unread[2]; }; + const ExportFace* const faces = static_cast(collision->getFaceVector(lod)); + for (int i = 0; i < faceCount; ++i) + { + int previous = faces[i].indices[2]; + triple triangle; + for (int j = 0; j <= 2; ++j) + { + const int current = faces[i].indices[j]; + const Edge edge = {previous < current ? previous : current, + current < previous ? previous : current, + static_cast(mesh.edges.size())}; + const std::pair::iterator, bool> inserted = uniqueEdges.insert(edge); + if (inserted.second) + mesh.edges.push_back(std::make_pair(inserted.first->first, inserted.first->second)); + // ELF 0x840A100: insert_in_triple(triangle, 2 - j, index). + if (j == 0) triangle.third = inserted.first->index; + else if (j == 1) triangle.second = inserted.first->index; + else triangle.first = inserted.first->index; + previous = current; + } + mesh.faces.push_back(triangle); + } +} + +// ELF 0x8405F70. Corner ordering uses x/y/z bits 4/2/1, then the shared box topology. +void BFObjectEnvironment::createBoundingBoxFromLocalCoordinates(const Vec3& min, const Vec3& max, + const Mat4& transform, Mesh& mesh) const +{ + mesh.vertices.reserve(8); + for (unsigned int i = 0; i < 8; ++i) + { + const Vec3 corner = {(i & 4) ? max.x : min.x, (i & 2) ? max.y : min.y, (i & 1) ? max.z : min.z}; + mesh.vertices.push_back(transformPoint(corner, transform)); + } + appendBoxTopology(mesh); +} + +// ELF 0x8407300. +void BFObjectEnvironment::createBoundingBoxFromWorldCoordinates(const Vec3& min, const Vec3& max, Mesh& mesh) const +{ + mesh.vertices.reserve(8); + for (unsigned int i = 0; i < 8; ++i) + { + const Vec3 corner = {(i & 4) ? max.x : min.x, (i & 2) ? max.y : min.y, (i & 1) ? max.z : min.z}; + mesh.vertices.push_back(corner); + } + appendBoxTopology(mesh); +} + +// ELF 0x84083F0. Every area's vertices participate, including exclusions. +void BFObjectEnvironment::createBoundingBoxFromCombatAreas(std::pair& bounds) const +{ + Vec2 low = {100000.0f, 100000.0f}; + Vec2 high = {-100000.0f, -100000.0f}; + for (unsigned int i = 0; i < m_combatAreas.size(); ++i) + { + const std::vector& points = m_combatAreas[i]->m_points; + for (unsigned int j = 0; j < points.size(); ++j) + { + if (low.x > points[j].x) low.x = points[j].x; + if (low.y > points[j].y) low.y = points[j].y; + if (points[j].x > high.x) high.x = points[j].x; + if (points[j].y > high.y) high.y = points[j].y; + } + } + bounds.first = low; + bounds.second = high; +} + +// ELF 0x8408500. Walk each transformed bottom edge in unit XZ steps until an AI area accepts it. +bool BFObjectEnvironment::objectOverlapsCombatAreas(const world::IObject* object, + std::pair& bounds) const +{ + if (!object->hasCollisionLod(3)) + return false; + world::ICollisionMesh* const collision = static_cast( + world::object_detail::LayoutAccess::collisionMesh(const_cast(object))); + const LocalBoundingBox* const box = collision->getBoundingBox(3); + CombatAreaManager* const manager = CombatAreaManager::getInstance(); + const Mat4& transform = object->getAbsoluteTransformation(); + std::vector points; + const Vec3 corners[4] = { + transformPoint(Vec3{box->m_min.x, box->m_min.y, box->m_min.z}, transform), + transformPoint(Vec3{box->m_max.x, box->m_min.y, box->m_min.z}, transform), + transformPoint(Vec3{box->m_max.x, box->m_min.y, box->m_max.z}, transform), + transformPoint(Vec3{box->m_min.x, box->m_min.y, box->m_max.z}, transform) + }; + for (unsigned int i = 0; i < 4; ++i) + points.push_back(corners[i]); + for (unsigned int i = 0; i < 4; ++i) + { + const Vec3& a = points[i]; + const Vec3& b = points[(i + 1) & 3]; + Vec3 direction = {b.x - a.x, 0.0f, b.z - a.z}; + const float length = std::sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z); + const float lengthSq = direction.x * direction.x + direction.y * direction.y + direction.z * direction.z; + if (!(FLT_EPSILON > std::fabs(lengthSq - 1.0f))) + { + if (!(FLT_EPSILON > std::fabs(lengthSq))) + { + const float scale = 1.0f / std::sqrt(lengthSq); + direction.x *= scale; + direction.y *= scale; + direction.z *= scale; + } + else + direction.x = direction.y = direction.z = 0.0f; + } + const int count = static_cast(length) + 1; + Vec3 position = points[i]; + for (int sample = 0; sample < count; ++sample) + { + if (manager->isAiPositionInside(position, m_combatAreas)) + { + for (unsigned int j = 0; j < 4; ++j) + { + if (bounds.first.x > points[j].x) bounds.first.x = points[j].x; + if (bounds.first.y > points[j].z) bounds.first.y = points[j].z; + if (points[j].x > bounds.second.x) bounds.second.x = points[j].x; + if (points[j].z > bounds.second.y) bounds.second.y = points[j].z; + } + return true; + } + position.x = direction.x + position.x; + position.y = direction.y + position.y; + position.z = direction.z + position.z; + } + } + return false; +} + +// ELF 0x8408C00. +bool BFObjectEnvironment::hasOnlyInfantryCollMesh(world::IObject* object) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::collideLineWithObjects"); + world::ICollisionMesh* const collision = static_cast( + world::object_detail::LayoutAccess::collisionMesh(object)); + if (!collision || object->hasCollisionLod(1) || !object->hasCollisionLod(2)) + return false; + return !collision->sameInstance(0, 2, 0, 3); } } // namespace ai diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFObjectEnvironment.h b/Code/BF2/AI/AIInterface/BFKnowledge/BFObjectEnvironment.h index aea65fe37..fc6d286e0 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFObjectEnvironment.h +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFObjectEnvironment.h @@ -11,22 +11,61 @@ #include #include "AIAdapterTypes.h" +#include "../../AIDLL/AI/Main/IAIPathfinding.h" // Complete triple elements in the mesh face lists. namespace dice { namespace hfe { class IBase; +class CombatArea; +namespace world { class IObject; class ICollisionMesh; } namespace ai { +// A borrowed target position; assignment keeps the destination's existing reference. +class TargetData +{ +public: + TargetData(unsigned int id, const Vec3& position, IAIObject* object); + TargetData(const TargetData& other); + TargetData& operator=(const TargetData& other); + + // Member spellings are [INFERRED]; ELF constructors establish their order. + unsigned int id; // x86 +0x00 + const Vec3& position; // x86 +0x04 + IAIObject* object; // x86 +0x08 +}; + class IAIObjectEnvironment { public: - // [FRONTIER] These nested mesh types belong to IAIObjectEnvironment. - // Their member layouts are not yet known. - struct MeshAndBoundingBox; - struct WaterMesh; - struct DestroyableAddOnMesh; + // Mesh data exchanged with the offline navigation exporter. Field names are [INFERRED]. + // ELF MeshAndBoundingBox/WaterMesh list destruction and Mesh copy construction attest + // these source-level containers; their native STL layouts are compiler-dependent. + struct Mesh + { + std::vector vertices; + std::vector> edges; + std::list> faces; + }; + struct MeshAndBoundingBox + { + std::string name; + IAIObject* object; // x86 +0x04; assigned after insertion from the object's cached AI component. + Mesh boundingBox; + Mesh mesh; + }; + struct WaterMesh + { + std::string name; + Mesh mesh; + }; + struct DestroyableAddOnMesh + { + std::string name; + bool initiallyWalkable; + Mesh mesh; + }; IAIObjectEnvironment(); virtual ~IAIObjectEnvironment(); @@ -55,15 +94,15 @@ class IAIObjectEnvironment virtual int getHeightAndNormalForObject(IAIObject* object, const Vec3& position, float& height, Vec3& normal, float& slope) = 0; virtual void getVehicleSpawnerPositions(std::vector& out, unsigned char team) const = 0; virtual IAIObject* getObjectFromName(const std::string& name) = 0; - virtual int getAllStaticCollisionMeshes(std::list& meshes, std::list& water, std::map& addOns, std::list& more, std::pair& bounds, unsigned char team) const = 0; - virtual int getAllStaticCollisionMeshesWithinBoundary(const Vec2& min, const Vec2& max, std::list& meshes, std::list& water, std::map& addOns, std::list& more, std::pair& bounds, unsigned char team) const = 0; + virtual bool getAllStaticCollisionMeshes(std::list& meshes, std::list& water, std::map& addOns, std::list& more, std::pair& bounds, unsigned char team) const = 0; + virtual bool getAllStaticCollisionMeshesWithinBoundary(const Vec2& min, const Vec2& max, std::list& meshes, std::list& water, std::map& addOns, std::list& more, std::pair& bounds, unsigned char team) const = 0; virtual bool isAsleep(unsigned int id) const = 0; - virtual int getTargetObjects(std::vector& out, int team) const = 0; - virtual void loadOvergrowthCollision(const std::string& path) const = 0; + virtual void getTargetObjects(std::vector& out, int team) const = 0; + virtual bool loadOvergrowthCollision(const std::string& path) const = 0; virtual bool initAiCombatAreas() const = 0; virtual bool isAiPositionInsideCombatArea(const Vec3& position) const = 0; virtual int getAiCombatAreaLayer() const = 0; - virtual int getAICombatArea(std::list& out) const = 0; + virtual void getAICombatArea(std::list& out) const = 0; virtual void damageSeverelyDamagedVehicles() = 0; virtual int collideLineWithObjects(const Vec3& from, const Vec3& to, const std::vector& ignore, bool a, float b, bool c, bool& hit) = 0; }; @@ -92,28 +131,41 @@ class BFObjectEnvironment : public IAIObjectEnvironment virtual bool collideLineWithWorld(const Vec3& from, const Vec3& to, AIObjectPredicate* filter, Vec3* hit); virtual bool getMaxHeight(const Vec3& from, const Vec3& to, AIObjectPredicate* filter, float& height); virtual bool hasIndirectLineOfFire(IWeapon* weapon, const Vec3& from, const Vec3& to, const std::vector& ignore); - virtual void pickRandomSensePosition(Vec3& position, Vec3& normal, Vec3 hint, IAIObject* object); - virtual bool pickSoldierRandomSensePosition(Vec3& position, Vec3& normal, IAIObject* object, unsigned int& part); - virtual bool getSoldierSensePosition(Vec3& position, Vec3& normal, IAIObject* object, unsigned int part); + virtual void pickRandomSensePosition(Vec3& position, Vec3& localPosition, Vec3 hint, IAIObject* object); + virtual bool pickSoldierRandomSensePosition(Vec3& position, Vec3& localPosition, IAIObject* object, unsigned int& part); + virtual bool getSoldierSensePosition(Vec3& position, Vec3& localPosition, IAIObject* object, unsigned int part); virtual int getHeightAndNormalForObject(IAIObject* object, const Vec3& position, float& height, Vec3& normal, float& slope); virtual void getVehicleSpawnerPositions(std::vector& out, unsigned char team) const; virtual IAIObject* getObjectFromName(const std::string& name); - virtual int getAllStaticCollisionMeshes(std::list& meshes, std::list& water, std::map& addOns, std::list& more, std::pair& bounds, unsigned char team) const; - virtual int getAllStaticCollisionMeshesWithinBoundary(const Vec2& min, const Vec2& max, std::list& meshes, std::list& water, std::map& addOns, std::list& more, std::pair& bounds, unsigned char team) const; + virtual bool getAllStaticCollisionMeshes(std::list& meshes, std::list& water, std::map& addOns, std::list& more, std::pair& bounds, unsigned char team) const; + virtual bool getAllStaticCollisionMeshesWithinBoundary(const Vec2& min, const Vec2& max, std::list& meshes, std::list& water, std::map& addOns, std::list& more, std::pair& bounds, unsigned char team) const; virtual bool isAsleep(unsigned int id) const; - virtual int getTargetObjects(std::vector& out, int team) const; - virtual void loadOvergrowthCollision(const std::string& path) const; + virtual void getTargetObjects(std::vector& out, int team) const; + virtual bool loadOvergrowthCollision(const std::string& path) const; virtual bool initAiCombatAreas() const; virtual bool isAiPositionInsideCombatArea(const Vec3& position) const; virtual int getAiCombatAreaLayer() const; - virtual int getAICombatArea(std::list& out) const; + virtual void getAICombatArea(std::list& out) const; virtual void damageSeverelyDamagedVehicles(); virtual int collideLineWithObjects(const Vec3& from, const Vec3& to, const std::vector& ignore, bool a, float b, bool c, bool& hit); private: + void createMeshFromObject(world::ICollisionMesh* collision, int lod, const Mat4& transform, Mesh& mesh) const; + void createBoundingBoxFromLocalCoordinates(const Vec3& min, const Vec3& max, const Mat4& transform, Mesh& mesh) const; + void createBoundingBoxFromWorldCoordinates(const Vec3& min, const Vec3& max, Mesh& mesh) const; + void createBoundingBoxFromCombatAreas(std::pair& bounds) const; + bool objectOverlapsCombatAreas(const world::IObject* object, std::pair& bounds) const; + bool hasOnlyInfantryCollMesh(world::IObject* object) const; + + void pushAIObjects(std::vector& out, std::vector objects) const; + /* +0x00 */ // vptr - // [UNRESOLVED] Three pointer-vector fields remain opaque. The trailing clock value is a double. - /* +0x04 */ unsigned char m_opaque[0x24]; // three std::vector members, zeroed as retail does + // The element types come from the std::vector instantiations each member's users call + // (erase / _M_fill_insert / _M_insert_aux); the destructor frees the three in reverse order. + // [CHOSEN] member names. + /* +0x04 */ std::vector m_senseObjects; // pickRandomSensePosition's scratch + /* +0x10 */ std::vector m_activePlayerIds; // getActivePlayerIds' answer + /* +0x1C */ std::vector m_combatAreas; // the AI combat-area set /* +0x28 */ unsigned char m_byte28; // [UNRESOLVED] ctor 0 /* +0x2C */ double m_lastSevereDamageTime; // [CHOSEN] name; ELF +0x2C / PE +0x38, ctor 0.0 }; diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFPhysics.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/BFPhysics.cpp index c8f74877e..e0d1e1b36 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFPhysics.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFPhysics.cpp @@ -1,15 +1,10 @@ // [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. -// [TEMP] Temporary implementation boundaries remain. -// [CHOSEN, not recovered] Temporary implementation boundaries remain. -// [RETIRE-WHEN: aidll-01-adapters] Complete and validate the remaining BFPhysics operations. #include "BFPhysics.h" -#include "AIFrontier.h" - #include "../../AIDLL/AI/Main/CommonSingletonServer.h" #include "../../../Core/ClassManager.h" +#include "../../../Physics/BasicPhysicsSystem.h" // IPhysicsSystem::getGravity (+0x20) namespace dice { namespace hfe { @@ -19,31 +14,36 @@ extern ClassManager* classManager; namespace ai { // First wins in, exact match out. +// ELF 0x840E790 / 0x840E810. IAIPhysics::IAIPhysics() { if (!CommonSingletonServer::m_iaiPhysics) classManager->registerSimpleSingleton(std::string("IAIPhysics"), this); } +// ELF 0x840E890 / 0x840E910 / 0x840E990. IAIPhysics::~IAIPhysics() { if (CommonSingletonServer::m_iaiPhysics == this) classManager->unregisterSimpleSingleton(std::string("IAIPhysics")); } +// ELF 0x840B740 / 0x840B770. BFPhysics::BFPhysics() { } +// ELF 0x840B7A0 / 0x840B7C0 / 0x840B7E0. BFPhysics::~BFPhysics() { } -// - world::basicPhysicsSystem (ds:) vtable +0x20. -// The whole class is a one-call forwarder; four bytes, one virtual. +// bf2 0x840B810: a forwarder to world::basicPhysicsSystem's getGravity (IPhysicsSystem +0x20), +// no null guard. +// ELF 0x840B810. float BFPhysics::getGravity() const { - BF2_AI_FRONTIER("dice::hfe::ai::BFPhysics::getGravity"); + return static_cast(world::basicPhysicsSystem)->getGravity(); } } // namespace ai diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFRadioComm.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/BFRadioComm.cpp index 18efbb0d2..ebc9504df 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFRadioComm.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFRadioComm.cpp @@ -1,15 +1,14 @@ -// [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. -// [TEMP] Temporary implementation boundaries remain. -// [CHOSEN, not recovered] Temporary implementation boundaries remain. -// [RETIRE-WHEN: aidll-01-adapters] Complete and validate the remaining BFRadioComm operations. +// Placement attested by the ELF's "AI/AIInterface/BFKnowledge/BFRadioComm.cpp" __FILE__ string. #include "BFRadioComm.h" -#include "AIFrontier.h" - #include "../../AIDLL/AI/Main/CommonSingletonServer.h" +#include "../../AIDLL/AI/AIUtils/checkPointer.h" #include "../../../Core/ClassManager.h" +#include "../../../Core/Debug.h" +#include "../../../Core/EventManager.h" +#include "../../../Game/IEventListener.h" // ECNetwork +#include "../../../Game/GameEvents/RadioMessageEvent.h" // RadioMessageReceivedEvent namespace dice { namespace hfe { @@ -39,10 +38,36 @@ BFRadioComm::~BFRadioComm() { } -// - the single virtual, and the AI's only way to speak. +// bf2 0x840B900: the AI's only way to speak. The AI channel is mapped to the engine channel +// 0..8 -> 6, 7, 8, 3, 2, 4, 10, 11, 14 (an unknown one reports an Error and becomes 19), and a +// RadioMessageReceivedEvent {connection = playerId, message = a, sender = b, team = c, flags = d, +// that channel, type = channel} is posted as ECNetwork event at time 0 (EventManager +0x10). +// The allocation goes through checkPointer (its "AI/AIDLL/AI/AIUtils/checkPointer.h" Debug block +// is inlined here). [INFERRED] int: the value is the postEvent result left in eax; the only +// caller (CommunicationHub::filterAndSendAIRadioMessage) discards it. int BFRadioComm::sendAIRadioMessage(int playerId, ChannelMessageType channel, AIRadioChannelType type, unsigned char a, int b, unsigned char c, unsigned char d) { - BF2_AI_FRONTIER("dice::hfe::ai::BFRadioComm::sendAIRadioMessage"); + int engineChannel; + switch (static_cast(type)) + { + case 0: engineChannel = 6; break; + case 1: engineChannel = 7; break; + case 2: engineChannel = 8; break; + case 3: engineChannel = 3; break; + case 4: engineChannel = 2; break; + case 5: engineChannel = 4; break; + case 6: engineChannel = 10; break; + case 7: engineChannel = 11; break; + case 8: engineChannel = 14; break; + default: + engineChannel = 19; + Debug(DebugTypeError, __FILE__, 77, "") << "Unknown AI radio channel number " + << static_cast(type); // line 0x4D + break; + } + EventNode* const event = checkPointer(new RadioMessageReceivedEvent( + playerId, a, static_cast(b), c, d, engineChannel, static_cast(channel))); + return static_cast(eventManager->postEvent(ECNetwork, event, 0.0f)); } } // namespace ai diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFSquad.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/BFSquad.cpp index 14e6822bd..b62650c2b 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFSquad.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFSquad.cpp @@ -1,17 +1,18 @@ // [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. -// [TEMP] Temporary implementation boundaries remain. -// [CHOSEN, not recovered] Temporary implementation boundaries remain. -// [RETIRE-WHEN: aidll-01-adapters] Complete and validate the remaining BFSquad operations. #include "BFSquad.h" #include "AIPlayer.h" -#include "AIFrontier.h" - #include "../../AIDLL/AI/Main/CommonSingletonServer.h" #include "../../../Core/ClassManager.h" #include "../../../Game/GameLogic/SquadManager/ISquadManager.h" +#include "../../../Game/GameLogic/SquadManager/ISquadInfo.h" +#include "../../../Game/GameLogic/SquadManager/SquadOrder.h" +#include "../../../Game/GameEvents/RequestEvent.h" +#include "../../../Game/Objects/IObject.h" +#include "../../../IO/Network/NetworkManager.h" +#include "../../../IO/Network/INetworkable.h" +#include "IAIObject.h" #include "../SingletonServer.h" // BFSingletonServer::updateStaticMethods namespace dice { @@ -51,9 +52,10 @@ BFSquad::~BFSquad() { } +// bf2 0x84108F0: ISquadManager +0x40 getFirstUnusedSquad. int BFSquad::getNextEmptySquad(int team) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::getNextEmptySquad"); + return static_cast(squadManager)->getFirstUnusedSquad(team); } // Preserve id-before-side virtual calls. @@ -64,9 +66,14 @@ bool BFSquad::joinSquad(int squad, IAIPlayer* player) return static_cast(squadManager)->addToSquad(side, squad, playerId); } +// ELF 0x8410960: id, then side, then ISquadManager +0x34 removeFromSquad(side, squad, id, false). +// The ELF answers the zero-extended low byte of that void call; nothing reads it, 0 is answered. int BFSquad::exitSquad(int squad, IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::exitSquad"); + const int playerId = player->getId(); + const int side = player->getSide(); + static_cast(squadManager)->removeFromSquad(side, squad, playerId, false); + return 0; } bool BFSquad::isSquadLeader(int squad, IAIPlayer* player) @@ -84,86 +91,169 @@ bool BFSquad::isSquadLeader(int squad, IAIPlayer* player) return playerId == leader; } +// bf2 0x8410A10: id, then side, then ISquadManager +0x38 setSquadLeader(side, squad, id, false). +// The ELF answers the low byte of that void call; nothing reads it, 0 is answered. int BFSquad::assignAsSquadLeader(int squad, IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::assignAsSquadLeader"); + const int playerId = player->getId(); + const int side = player->getSide(); + static_cast(squadManager)->setSquadLeader(side, squad, playerId, false); + return 0; } +// bf2 0x8410A70: a player who is not the leader answers 1; the leader is replaced by -1 +// (setSquadLeader(side, squad, -1, false), whose void low byte the ELF answers; 0 here). int BFSquad::retireAsSquadLeader(int squad, IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::retireAsSquadLeader"); + const int playerId = player->getId(); + if (playerId != static_cast(squadManager)->getSquadLeader(player->getSide(), squad)) + return 1; + static_cast(squadManager)->setSquadLeader(player->getSide(), squad, -1, false); + return 0; } +// bf2 0x8410B00: issueOrder with squad order type 5. int BFSquad::issueSquadAttackOrder(const Vec3& position, int a, int b, IAIObject* target) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::issueSquadAttackOrder"); + return issueOrder(position, a, b, target, 5); } +// bf2 0x8410B30: issueOrder with squad order type 4. int BFSquad::issueSquadMoveOrder(const Vec3& position, int a, int b, IAIObject* target) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::issueSquadMoveOrder"); + return issueOrder(position, a, b, target, 4); } +// bf2 0x8410B60: issueOrder with squad order type 6. int BFSquad::issueSquadDefendOrder(const Vec3& position, int a, int b, IAIObject* target) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::issueSquadDefendOrder"); + return issueOrder(position, a, b, target, 6); } // 5 bytes - a bare ret. Empty, like its decline twin. -void BFSquad::acceptSquadOrder(int squad, IAIPlayer* player) +// bf2 0x8410C70 and 0x8410C80 are bare `ret`s. +void BFSquad::acceptSquadOrder(int, IAIPlayer*) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::acceptSquadOrder"); } // ELF, - empty. -void BFSquad::declineSquadOrder(int squad, IAIPlayer* player) +void BFSquad::declineSquadOrder(int, IAIPlayer*) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::declineSquadOrder"); } int BFSquad::acceptCommanderAttackOrder(int squad, IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::acceptCommanderAttackOrder"); + return acceptCommanderOrder(squad, player, 5); } int BFSquad::acceptCommanderDefendOrder(int squad, IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::acceptCommanderDefendOrder"); + return acceptCommanderOrder(squad, player, 6); } int BFSquad::acceptCommanderMoveOrder(int squad, IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::acceptCommanderMoveOrder"); + return acceptCommanderOrder(squad, player, 4); } int BFSquad::declineCommanderAttackOrder(int squad, IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::declineCommanderAttackOrder"); + return declineCommanderOrder(squad, player, 5); } int BFSquad::declineCommanderDefendOrder(int squad, IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::declineCommanderDefendOrder"); + return declineCommanderOrder(squad, player, 6); } int BFSquad::declineCommanderMoveOrder(int squad, IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::declineCommanderMoveOrder"); + return declineCommanderOrder(squad, player, 4); } +// bf2 0x8410F30: for a human only, a RequestEvent (side, squad, type 1) executed on the server +// for the player's id (GameEvent +0x28) and released. +// [CHOSEN, not recovered] The ELF leaves the last call's EAX; no caller reads it, 0 here. int BFSquad::requestNewCommanderOrder(int squad, IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::requestNewCommanderOrder"); + if (player->getIsAIPlayer()) + return 0; + RequestEvent* const event = + new RequestEvent(player->getSide(), squad, static_cast(1)); + event->executeServer(player->getId()); + event->release(); + return 0; +} + +// bf2 0x8410FB0: the squad's commander order (ISquadInfo +0x14) gives the position (its first +// point) and the target through the network id. The target argument is not read. +world::IObject* BFSquad::getCommanderOrder(int a, int b, Vec3& position, IAIObject*) +{ + SquadOrder* const order = static_cast(squadManager)->getSquadInfo(a, b)->getCommanderOrders(); + position = order->points[0]; + return io::networkManager->getObject(order->targetNetId); +} + +// bf2 0x8411020: the same for the squad order (ISquadInfo +0x10). +world::IObject* BFSquad::getSquadOrder(int a, int b, Vec3& position, IAIObject*) +{ + SquadOrder* const order = static_cast(squadManager)->getSquadInfo(a, b)->getSquadOrders(); + position = order->points[0]; + return io::networkManager->getObject(order->targetNetId); +} + +// bf2 0x8410BC0. The order: the type, the target's network id (0 without a target or a +// networkable), the position as the first of three points (the other two zero); the flag at +// +0x2C is left unset as in the ELF. ISquadManager +0x44 issueSquadOrder(b, a, order, false). +int BFSquad::issueOrder(const Vec3& position, int a, int b, IAIObject* target, int orderType) +{ + SquadOrder order; + for (int i = 0; i < 3; ++i) + { + order.points[i].x = 0.0f; + order.points[i].y = 0.0f; + order.points[i].z = 0.0f; + } + order.orderId = orderType; + order.points[0] = position; + order.targetNetId = 0; + if (target) + { + io::INetworkable* const networkable = target->getObject()->getNetworkable(); + if (networkable) + order.targetNetId = networkable->m_networkableId; + } + static_cast(squadManager)->issueSquadOrder(b, a, order, false); + return 0; } -world::IObject* BFSquad::getCommanderOrder(int a, int b, Vec3& position, IAIObject* target) +// bf2 0x8410D20 / 0x8410E70. The order is marked accepted (or not) for the player's side +// (ISquadManager +0x24: accepted, OrderType 1, the squad order type, false); a human's +// acceptance (RequestEvent type 2) or decline (type 3) is executed for the player and released. +int BFSquad::acceptCommanderOrder(int squad, IAIPlayer* player, int orderType) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::getCommanderOrder"); + static_cast(squadManager)->setIsAccepted(player->getSide(), squad, true, static_cast(1), + static_cast(orderType), false); + if (player->getIsAIPlayer()) + return 0; + RequestEvent* const event = + new RequestEvent(player->getSide(), squad, static_cast(2)); + event->executeServer(player->getId()); + event->release(); + return 0; } -world::IObject* BFSquad::getSquadOrder(int a, int b, Vec3& position, IAIObject* target) +int BFSquad::declineCommanderOrder(int squad, IAIPlayer* player, int orderType) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::getSquadOrder"); + static_cast(squadManager)->setIsAccepted(player->getSide(), squad, false, static_cast(1), + static_cast(orderType), false); + if (player->getIsAIPlayer()) + return 0; + RequestEvent* const event = + new RequestEvent(player->getSide(), squad, static_cast(3)); + event->executeServer(player->getId()); + event->release(); + return 0; } } // namespace ai diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFSquad.h b/Code/BF2/AI/AIInterface/BFKnowledge/BFSquad.h index ea7e9df4c..c1fa61de9 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFSquad.h +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFSquad.h @@ -74,6 +74,12 @@ class BFSquad : public IBFSquad virtual int requestNewCommanderOrder(int squad, IAIPlayer* player); virtual world::IObject* getCommanderOrder(int a, int b, Vec3& position, IAIObject* target); virtual world::IObject* getSquadOrder(int a, int b, Vec3& position, IAIObject* target); + +private: + // Non-virtual ELF helpers (0x8410BC0, 0x8410D20, 0x8410E70); the int is a SquadOrderType value. + int issueOrder(const Vec3& position, int a, int b, IAIObject* target, int orderType); + int acceptCommanderOrder(int squad, IAIPlayer* player, int orderType); + int declineCommanderOrder(int squad, IAIPlayer* player, int orderType); }; } // namespace ai diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFTerrain.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/BFTerrain.cpp index 200a91f4f..1b3d8f2d7 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFTerrain.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFTerrain.cpp @@ -1,12 +1,14 @@ // [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. -// [TEMP] Temporary implementation boundaries remain. -// [CHOSEN, not recovered] Temporary implementation boundaries remain. -// [RETIRE-WHEN: aidll-01-adapters] Complete and validate the remaining BFTerrain operations. #include "BFTerrain.h" -#include "AIFrontier.h" +#include "../../../Core/Debug.h" +#include "../../AIDLL/AI/Main/IAIPathfinding.h" +#include +#include +#include "AIPlayer.h" +#include "../../../Physics/Heightmap.h" +#include "../../../Game/GameLogic/CombatAreaManager.h" #include "../../AIDLL/AI/Main/CommonSingletonServer.h" #include "../../../Core/ClassManager.h" @@ -100,35 +102,55 @@ float BFTerrain::getTerrainAltitude(float x, float z) const return water; } -unsigned char BFTerrain::getMaterial(float x, float z) const +// ELF 0x840C000. The shipped method reports its own unimplemented operation. +unsigned char BFTerrain::getMaterial(float /*x*/, float /*z*/) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::getMaterial"); + Debug(DebugTypeError, "AI/AIInterface/BFKnowledge/BFTerrain.cpp", 111) << "Not implemented"; + return 0; } // ELF, - a constant. +// bf2 0x840C0F0: `mov eax, -1`. int BFTerrain::getMaterialToGiveDamage() const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::getMaterialToGiveDamage"); + return -1; } +// bf2 0x840DEB0: the combat area manager (unchecked) tests the wrapper's player. bool BFTerrain::isInsideCombatArea(IAIPlayer* player) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::isInsideCombatArea"); + return CombatAreaManager::getInstance()->isPlayerInside(player->getPlayer()); } +// bf2 0x840C100: IHeightmapCluster +0x7C getNormalInWorldCoords. void BFTerrain::getNormal(float x, float z, Vec3& normal) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::getNormal"); + static_cast(m_heightmapCluster)->getNormalInWorldCoords(x, z, normal); } -void BFTerrain::getHeightAndNormal(float x, float z, Vec3& normal, unsigned char& material) const +// bf2 0x840C130: IHeightmapCluster +0x84 getHeightAndNormalInWorldCoords, its float passed on +// (the caller pops it from st0, hence the float return the port's declaration lacked). +float BFTerrain::getHeightAndNormal(float x, float z, Vec3& normal, unsigned char& material) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::getHeightAndNormal"); + return static_cast(m_heightmapCluster) + ->getHeightAndNormalInWorldCoords(x, z, normal, material); } +// bf2 0x840C170: acos of the terrain normal's y (IHeightmapCluster +0x7C into a zeroed Vec3), +// clamped to [-1, 1]. float BFTerrain::getSlope(float x, float z) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::getSlope"); + Vec3 normal; + normal.x = 0.0f; + normal.y = 0.0f; + normal.z = 0.0f; + static_cast(m_heightmapCluster)->getNormalInWorldCoords(x, z, normal); + float y = normal.y; + if (-1.0f > y) + y = -1.0f; + else if (y > 1.0f) + y = 1.0f; + return std::acos(y); } // slot 12 - the second half of `getTerrainAltitude`, and the same one-line @@ -139,14 +161,38 @@ float BFTerrain::getWaterLevel(float x, float z) const ->getWaterLevelInWorldCoords(x, z); } +// bf2 0x840C210: the primary heightmap's sea level (IHeightmap +0x68). float BFTerrain::getSeaWaterLevel() const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::getSeaWaterLevel"); + return static_cast(m_heightmapCluster)->getPrimaryHeightmap()->getSeaWaterLevel(); } -bool BFTerrain::findTerrainPoint(const Vec3& from, const Vec3& to, float step, Vec3& hit) const +// ELF 0x840C230. The second vector is a direction, normalized before scaling by step. +bool BFTerrain::findTerrainPoint(const Vec3& from, const Vec3& direction, float step, Vec3& hit) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::findTerrainPoint"); + Vec3 unit = direction; + const float lengthSq = unit.x * unit.x + unit.y * unit.y + unit.z * unit.z; + if (!(FLT_EPSILON > std::fabs(lengthSq - 1.0f))) + { + if (!(FLT_EPSILON > std::fabs(lengthSq))) + { + const float scale = 1.0f / std::sqrt(lengthSq); + unit.x *= scale; + unit.y *= scale; + unit.z *= scale; + } + else + unit.x = unit.y = unit.z = 0.0f; + } + Vec3 to; + to.x = step * unit.x + from.x; + to.y = step * unit.y + from.y; + to.z = step * unit.z + from.z; + Vec3 normal = {0.0f, 0.0f, 0.0f}; + float distance; + unsigned char material; + return static_cast(m_heightmapCluster) + ->intersectRayInWorldCoords(from, to, hit, distance, normal, material, true); } // ELF, - a bare member load. All ten of these are. @@ -186,49 +232,224 @@ int BFTerrain::getWorldMaxZ() const return m_worldMaxZ; } +// bf2 0x840C420: floor of the primary heightmap's getLowBoundaryX (as double), stored to float, then truncated. int BFTerrain::getPrimaryWorldMinX() const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::getPrimaryWorldMinX"); + return static_cast(static_cast( + std::floor(static_cast(static_cast(m_heightmapCluster)->getPrimaryHeightmap()->getLowBoundaryX())))); } +// bf2 0x840C460: floor of the primary heightmap's getLowBoundaryZ (as double), stored to float, then truncated. int BFTerrain::getPrimaryWorldMinZ() const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::getPrimaryWorldMinZ"); + return static_cast(static_cast( + std::floor(static_cast(static_cast(m_heightmapCluster)->getPrimaryHeightmap()->getLowBoundaryZ())))); } +// bf2 0x840C4A0: ceil of the primary heightmap's getHighBoundaryX (as double), stored to float, then truncated. int BFTerrain::getPrimaryWorldMaxX() const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::getPrimaryWorldMaxX"); + return static_cast(static_cast( + std::ceil(static_cast(static_cast(m_heightmapCluster)->getPrimaryHeightmap()->getHighBoundaryX())))); } +// bf2 0x840C4E0: ceil of the primary heightmap's getHighBoundaryZ (as double), stored to float, then truncated. int BFTerrain::getPrimaryWorldMaxZ() const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::getPrimaryWorldMaxZ"); + return static_cast(static_cast( + std::ceil(static_cast(static_cast(m_heightmapCluster)->getPrimaryHeightmap()->getHighBoundaryZ())))); } +// bf2 0x840C520: the heightmap cluster's intersectRayInWorldCoords (+0x90, verified in the ELF +// primary vtable), two-sided, into a discarded material byte. bool BFTerrain::intersectTerrain(const Vec3& from, const Vec3& to, Vec3& hit, float& distance, Vec3& normal) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::intersectTerrain"); + unsigned char material; + return static_cast(m_heightmapCluster) + ->intersectRayInWorldCoords(from, to, hit, distance, normal, material, true); } +// ELF 0x840C580. Output references are forwarded in their original order. bool BFTerrain::getTriangle(const Vec3& position, Vec3& a, Vec3& b, Vec3& c, Vec3& normal, unsigned char& material) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::getTriangle"); + return static_cast(m_heightmapCluster) + ->getTriangleAndNormalAndMaterialInWorldCoords(position.x, position.z, a, b, c, normal, material); } +// ELF 0x840C5E0. Sample just beyond the selected edge, away from the opposite vertex. bool BFTerrain::getTriangleNeighbour(const Vec3& a, const Vec3& b, const Vec3& c, unsigned int edge, Vec3& na, Vec3& nb, Vec3& nc, Vec3& normal, unsigned char& material) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::getTriangleNeighbour"); + const Vec3 *first, *second, *opposite; + switch (edge) + { + case 0: first = &b; second = &a; opposite = &c; break; + case 1: first = &c; second = &b; opposite = &a; break; + case 2: first = &a; second = &c; opposite = &b; break; + default: return false; + } + Vec3 midpoint; + midpoint.x = (first->x + second->x) * 0.5f; + midpoint.y = (first->y + second->y) * 0.5f; + midpoint.z = (first->z + second->z) * 0.5f; + Vec3 position; + position.x = (midpoint.x - opposite->x) * 0.2f + midpoint.x; + position.y = (midpoint.y - opposite->y) * 0.2f + midpoint.y; + position.z = (midpoint.z - opposite->z) * 0.2f + midpoint.z; + return getTriangle(position, na, nb, nc, normal, material); +} + +// ELF 0x840C7B0. +void BFTerrain::getAllTerrainPolygons(std::pair bounds, std::vector& vertices, std::vector >& edges, std::list >& triangles) const +{ + world::IHeightmap* const heightmap = + static_cast(m_heightmapCluster)->getPrimaryHeightmap(); + Vec2 max; + max.x = heightmap->getHighBoundaryX(); + max.y = heightmap->getHighBoundaryZ(); + Vec2 min; + min.x = heightmap->getLowBoundaryX(); + min.y = heightmap->getLowBoundaryZ(); + getAllTerrainPolygonsWithinBoundary(bounds, min, max, vertices, edges, triangles); +} + +// ELF 0x840C880. +void BFTerrain::getAllTerrainPolygonsWithinBoundary(std::pair bounds, const Vec2& min, const Vec2& max, std::vector& vertices, std::vector >& edges, std::list >& triangles) const +{ + world::IHeightmap* const heightmap = + static_cast(m_heightmapCluster)->getPrimaryHeightmap(); + const Vec3& scale = heightmap->getScale(); + const float maxX = std::ceil(max.x / scale.x) * scale.x; + const float maxZ = std::ceil(max.y / scale.z) * scale.z; + const float minX = std::floor(min.x / scale.x) * scale.x; + const float minZ = std::floor(min.y / scale.z) * scale.z; + const int countX = static_cast((maxX - minX) / scale.x) + 1; + const int countZ = static_cast((maxZ - minZ) / scale.z) + 1; + const unsigned int count = static_cast(countX * countZ); + + // [CHOSEN, not recovered] The shared CRT heap policy has no per-allocation cap: + // https://github.com/B2BF/OpenBF2/issues/7 (docs/architecture.md, Images and boundaries). + // Retail Memory.cpp set_max_alloc_size/reset_max_alloc_size calls are omitted here and + // in checkUnconnectedMeshData; no ineffectual replacement setters are published. + vertices.reserve(count); + std::vector vertexMap; + vertexMap.reserve(count); + int nextVertex = 0; + for (float x = minX; maxX >= x; x += scale.x) + { + for (float z = minZ; maxZ >= z; z += scale.z) + { + Vec3 position; + position.x = x; + position.y = heightmap->getHeightInWorldCoords(x, z); + position.z = z; + if (pointInsideBbox(position, bounds)) + { + vertices.push_back(position); + vertexMap.push_back(nextVertex++); + } + else + vertexMap.push_back(-1); + } + } + + // ELF 0x840C860: edgesSize(countX, countZ). + const int edgeCount = (countZ - 1) * (countX - 1) + (countZ - 1) * countX + countZ * (countX - 1); + edges.reserve(static_cast(edgeCount)); + std::vector edgeMap; + edgeMap.reserve(static_cast(3 * countZ * countX)); + int nextEdge = 0; + for (int x = 0; x < countX; ++x) + { + for (int z = 0; z < countZ - 1; ++z) + { + const int a = vertexMap[x * countZ + z]; + const int b = vertexMap[x * countZ + z + 1]; + if (a >= 0 && b >= 0) + { + edges.push_back(std::make_pair(a, b)); + edgeMap.push_back(nextEdge++); + } + else + edgeMap.push_back(-1); + } + } + for (int x = 0; x < countX - 1; ++x) + { + for (int z = 0; z < countZ; ++z) + { + const int a = vertexMap[x * countZ + z]; + const int b = vertexMap[(x + 1) * countZ + z]; + if (a >= 0 && b >= 0) + { + edges.push_back(std::make_pair(a, b)); + edgeMap.push_back(nextEdge++); + } + else + edgeMap.push_back(-1); + } + } + for (int x = 0; x < countX - 1; ++x) + { + for (int z = 1; z < countZ; ++z) + { + const int a = vertexMap[x * countZ + z]; + const int b = vertexMap[(x + 1) * countZ + z - 1]; + if (a >= 0 && b >= 0) + { + edges.push_back(std::make_pair(a, b)); + edgeMap.push_back(nextEdge++); + } + else + edgeMap.push_back(-1); + } + } + const int horizontalCount = (countZ - 1) * countX; + const int diagonalStart = horizontalCount + countZ * (countX - 1); + for (int x = 0; x < countX - 1; ++x) + { + for (int z = 0; z < countZ - 1; ++z) + { + const int horizontal = x * (countZ - 1) + z; + const int vertical = horizontalCount + countZ * x + z; + const int diagonal = diagonalStart + x * (countZ - 1) + z; + if (edgeMap[horizontal] >= 0 && edgeMap[diagonal] >= 0 && edgeMap[vertical] >= 0) + triangles.push_back(make_triple(edgeMap[horizontal], edgeMap[diagonal], edgeMap[vertical])); + if (edgeMap[vertical + 1] >= 0 && edgeMap[(x + 1) * (countZ - 1) + z] >= 0 && edgeMap[diagonal] >= 0) + triangles.push_back(make_triple(edgeMap[vertical + 1], edgeMap[(x + 1) * (countZ - 1) + z], edgeMap[diagonal])); + } + } + // shipped defect: output is appended, but generated vertex and edge IDs start at zero. + checkUnconnectedMeshData(vertices, edges, triangles); } -int BFTerrain::getAllTerrainPolygons(std::pair bounds, std::vector& vertices, std::vector >& edges, std::list >& triangles) const +// ELF 0x840D470. The retail trailing scans do not remove or remap any mesh data. +void BFTerrain::checkUnconnectedMeshData(std::vector& vertices, + std::vector>& edges, + std::list>& triangles) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::getAllTerrainPolygons"); + std::vector usedVertices(vertices.size(), false); + std::vector usedEdges(edges.size(), false); + for (std::list>::const_iterator it = triangles.begin(); it != triangles.end(); ++it) + { + usedVertices[edges[it->first].first] = true; + usedVertices[edges[it->first].second] = true; + usedVertices[edges[it->second].first] = true; + usedVertices[edges[it->second].second] = true; + usedVertices[edges[it->third].first] = true; + usedVertices[edges[it->third].second] = true; + usedEdges[it->first] = true; + usedEdges[it->second] = true; + usedEdges[it->third] = true; + } + for (unsigned int i = 0; i < usedVertices.size(); ++i) {} + for (unsigned int i = 0; i < usedEdges.size(); ++i) {} } -void BFTerrain::getAllTerrainPolygonsWithinBoundary(std::pair bounds, const Vec2& min, const Vec2& max, std::vector& vertices, std::vector >& edges, std::list >& triangles) const +// ELF 0x840DE60. Ordered comparisons reject NaN in either coordinate or boundary. +bool BFTerrain::pointInsideBbox(const Vec3& position, const std::pair& bounds) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::getAllTerrainPolygonsWithinBoundary"); + return position.x >= bounds.first.x && position.z >= bounds.first.y + && bounds.second.x >= position.x && bounds.second.y >= position.z; } } // namespace ai diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFTerrain.h b/Code/BF2/AI/AIInterface/BFKnowledge/BFTerrain.h index c0a85b8c6..e601bdedb 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFTerrain.h +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFTerrain.h @@ -33,7 +33,7 @@ class IAITerrain virtual int getMaterialToGiveDamage() const = 0; virtual bool isInsideCombatArea(IAIPlayer* player) const = 0; virtual void getNormal(float x, float z, Vec3& normal) const = 0; - virtual void getHeightAndNormal(float x, float z, Vec3& normal, unsigned char& material) const = 0; + virtual float getHeightAndNormal(float x, float z, Vec3& normal, unsigned char& material) const = 0; virtual float getSlope(float x, float z) const = 0; virtual float getWaterLevel(float x, float z) const = 0; virtual float getSeaWaterLevel() const = 0; @@ -51,7 +51,7 @@ class IAITerrain virtual bool intersectTerrain(const Vec3& from, const Vec3& to, Vec3& hit, float& distance, Vec3& normal) const = 0; virtual bool getTriangle(const Vec3& position, Vec3& a, Vec3& b, Vec3& c, Vec3& normal, unsigned char& material) const = 0; virtual bool getTriangleNeighbour(const Vec3& a, const Vec3& b, const Vec3& c, unsigned int edge, Vec3& na, Vec3& nb, Vec3& nc, Vec3& normal, unsigned char& material) const = 0; - virtual int getAllTerrainPolygons(std::pair bounds, std::vector& vertices, std::vector >& edges, std::list >& triangles) const = 0; + virtual void getAllTerrainPolygons(std::pair bounds, std::vector& vertices, std::vector >& edges, std::list >& triangles) const = 0; virtual void getAllTerrainPolygonsWithinBoundary(std::pair bounds, const Vec2& min, const Vec2& max, std::vector& vertices, std::vector >& edges, std::list >& triangles) const = 0; }; @@ -69,7 +69,7 @@ class BFTerrain : public IAITerrain virtual int getMaterialToGiveDamage() const; virtual bool isInsideCombatArea(IAIPlayer* player) const; virtual void getNormal(float x, float z, Vec3& normal) const; - virtual void getHeightAndNormal(float x, float z, Vec3& normal, unsigned char& material) const; + virtual float getHeightAndNormal(float x, float z, Vec3& normal, unsigned char& material) const; virtual float getSlope(float x, float z) const; virtual float getWaterLevel(float x, float z) const; virtual float getSeaWaterLevel() const; @@ -87,10 +87,14 @@ class BFTerrain : public IAITerrain virtual bool intersectTerrain(const Vec3& from, const Vec3& to, Vec3& hit, float& distance, Vec3& normal) const; virtual bool getTriangle(const Vec3& position, Vec3& a, Vec3& b, Vec3& c, Vec3& normal, unsigned char& material) const; virtual bool getTriangleNeighbour(const Vec3& a, const Vec3& b, const Vec3& c, unsigned int edge, Vec3& na, Vec3& nb, Vec3& nc, Vec3& normal, unsigned char& material) const; - virtual int getAllTerrainPolygons(std::pair bounds, std::vector& vertices, std::vector >& edges, std::list >& triangles) const; + virtual void getAllTerrainPolygons(std::pair bounds, std::vector& vertices, std::vector >& edges, std::list >& triangles) const; virtual void getAllTerrainPolygonsWithinBoundary(std::pair bounds, const Vec2& min, const Vec2& max, std::vector& vertices, std::vector >& edges, std::list >& triangles) const; private: + bool pointInsideBbox(const Vec3& position, const std::pair& bounds) const; + void checkUnconnectedMeshData(std::vector& vertices, std::vector>& edges, + std::list>& triangles) const; + /* +0x00 */ // vptr /* +0x04 */ IBase* m_heightmapCluster; // getSingleton("HeightmapCluster") /* +0x08 */ int m_worldSizeX; // heightmapCluster vtable +0x30 diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFTimer.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/BFTimer.cpp index edef8a9ce..64561cde0 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFTimer.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFTimer.cpp @@ -1,13 +1,7 @@ // [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. -// [TEMP] Temporary implementation boundaries remain. -// [CHOSEN, not recovered] Temporary implementation boundaries remain. -// [RETIRE-WHEN: aidll-01-adapters] Complete and validate the remaining BFTimer operations. #include "BFTimer.h" -#include "AIFrontier.h" - #include "../../AIDLL/AI/Main/CommonSingletonServer.h" #include "../../../Core/ClassManager.h" #include "../../../Core/System.h" // namespace WorldPref @@ -25,29 +19,32 @@ extern ClassManager* classManager; namespace ai { // First wins in, exact match out. +// ELF 0x841C100 / 0x841C180. IBFTimer::IBFTimer() { if (!CommonSingletonServer::m_iBFTimer) classManager->registerSimpleSingleton(std::string("IBFTimer"), this); } +// ELF 0x841C200 / 0x841C280 / 0x841C300. IBFTimer::~IBFTimer() { if (CommonSingletonServer::m_iBFTimer == this) classManager->unregisterSimpleSingleton(std::string("IBFTimer")); } +// ELF 0x841BEB0 / 0x841BF00. BFTimer::BFTimer() - : m_paused(false) - , m_resetMark(0.0) - , m_wallClock(new BFTimerWallClock) { - bfTimerNow(m_wallClock); + BFTimerWallClock* const clock = new BFTimerWallClock; + bfTimerNow(clock); + m_wallClock = clock; reset(); } // the vptr reset, `operator delete` on the wall // clock, then the base destructor. It really does free the eight bytes the ctor allocated. +// ELF 0x841BF50 / 0x841BF80 / 0x841BFB0. BFTimer::~BFTimer() { delete m_wallClock; @@ -58,18 +55,21 @@ BFTimer::~BFTimer() // - `push ebp / mov ebp, esp / pop ebp / jmp WorldPref::getWorldTime`. A tail // jump: the timer owns no game clock, it forwards to WorldPref. +// ELF 0x841BFF0. double BFTimer::getGameTime() const { return WorldPref::getWorldTime(); } // - the same shape, to WorldPref::getTickTime. +// ELF 0x841C000. double BFTimer::getTimeIncrease() const { return WorldPref::getTickTime(); } // Returns elapsed wall-clock time in seconds, including the microsecond fraction. +// ELF 0x841C010. double BFTimer::getUpdateTime() const { BFTimerWallClock now; @@ -79,12 +79,14 @@ double BFTimer::getUpdateTime() const } // Returns the system wall-clock time. +// ELF 0x841C0E0. double BFTimer::getWallClockTime() const { return g_system->getWallClockTime(); } // - two tail jumps, one per branch. +// ELF 0x841C060. void BFTimer::setPause(bool paused) { if (paused) @@ -94,11 +96,13 @@ void BFTimer::setPause(bool paused) } // - `movzx eax, byte ptr [eax+4]`. +// ELF 0x841C080. bool BFTimer::getPause() { return m_paused; } +// ELF 0x841C0B0. void BFTimer::reset() { m_paused = false; @@ -108,11 +112,13 @@ void BFTimer::reset() // each. not virtual - absent from the vtable, and setPause is // their only caller. +// ELF 0x841C090. void BFTimer::pause() { m_paused = true; } +// ELF 0x841C0A0. void BFTimer::unpause() { m_paused = false; diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFTimer.h b/Code/BF2/AI/AIInterface/BFKnowledge/BFTimer.h index cc5d58cf0..fc18ae80d 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFTimer.h +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFTimer.h @@ -18,7 +18,8 @@ namespace hfe { namespace ai { // Stored wall-clock value used by the AI timer. -// [RETIRE-WHEN: aidll-01-adapters] Complete and validate the corresponding BFTimer operation. +// [RETIRE-WHEN: aidll-01-adapters] Confirm and validate the Win32 clock route against the +// original Win32 image before retiring that chosen route; the ELF timeval calls are verified. struct BFTimerWallClock { long tv_sec; diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/DebugRenderer.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/DebugRenderer.cpp index cdabb140c..c8a3f81b3 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/DebugRenderer.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/DebugRenderer.cpp @@ -1,16 +1,16 @@ // [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. -// [TEMP] Temporary implementation boundaries remain. -// [CHOSEN, not recovered] Temporary implementation boundaries remain. -// [RETIRE-WHEN: aidll-01-adapters] Complete and validate the remaining DebugRenderer operations. +// The AI's debug renderer forwards to the engine's debug drawers (RenderSingletonServer, filled by +// its updateStaticMethods). bf2 (ia-32, dedicated) and BF2.exe (client, vtable 0x947AE8) have the +// same bodies: drawAll and reset are empty, the draw calls forward without a null check. #include "DebugRenderer.h" -#include "AIFrontier.h" - #include "../../AIDLL/AI/Main/CommonSingletonServer.h" #include "../SingletonServer.h" // (!) its roster static is BFSingletonServer's, not Common's #include "../../../Core/ClassManager.h" +#include "../../../Core/IBase.h" +#include "../../../GeomMisc/DebugCircleDrawer.h" +#include "../../../GeomMisc/DebugLineDrawer.h" namespace dice { namespace hfe { @@ -19,6 +19,55 @@ extern ClassManager* classManager; namespace ai { +namespace { + +// The line and circle drawers use the GeomMisc interfaces recovered with RendDX9. The text writer's +// slots are declared locally, in table order ([INFERRED] interface name). Slot offsets and +// argument order are BF2.exe's (0x818080..0x818170); the geom::DebugTextWriter slots are the ones +// GeomMisc/DebugTextWriter.cpp implements. bf2 (ia-32) calls the text writer at +0x38/+0x40 +// instead - the Linux engine's writer table is ordered differently - with the same arguments. + +// "DebugTextWriter" (geom::DebugTextWriter, IID_IDebugTextWriter 80043). +class IDebugTextWriter : public IBase +{ +public: + virtual bool setFont(const std::string& path) = 0; // +0x10 + virtual bool isEnabled() const = 0; // +0x14 + virtual void setEnabled(bool enabled) = 0; // +0x18 + virtual unsigned int getColour() const = 0; // +0x1C + virtual void setColour(unsigned int colour) = 0; // +0x20 + virtual void queueWorldGroupColoured(const Vec3& position, unsigned int colour, + const std::vector& text, int spacing, + int alignment, int bottomAligned) = 0; // +0x24 + virtual void queueWorldTextColoured(const Vec3& position, unsigned int colour, + const std::string& text, int alignment) = 0; // +0x28 + virtual void queueGroupColoured(int x, int y, unsigned int colour, + const std::vector& text, int spacing, + int alignment, int bottomAligned) = 0; // +0x2C + +protected: + ~IDebugTextWriter() {} +}; + +// The line drawer's table is recovered with RendDX9 (geom::IDebugLineDrawer, PE 0x1020C758). +inline geom::IDebugLineDrawer* lineDrawer() +{ + return static_cast(RenderSingletonServer::m_debugLineDrawer); +} + +// The circle drawer's table is recovered with RendDX9 (geom::IDebugCircleDrawer, PE 0x1020CB98). +inline geom::IDebugCircleDrawer* circleDrawer() +{ + return static_cast(RenderSingletonServer::m_debugCircleDrawer); +} + +inline IDebugTextWriter* textWriter() +{ + return static_cast(RenderSingletonServer::m_debugTextWriter); +} + +} // namespace + // First wins in, exact match out. IDebugRenderer::IDebugRenderer() { @@ -40,46 +89,68 @@ DebugRenderer::~DebugRenderer() { } -// 5 bytes - a bare ret. Empty in the dedicated image. +// ELF 0x842E780, PE 0x83D270 (a shared `ret`): empty in both images. void DebugRenderer::drawAll() { - BF2_AI_FRONTIER("dice::hfe::ai::DebugRenderer::drawAll"); } -// - likewise empty. +// ELF 0x842E790, PE 0x83D270 (a shared `ret`): empty in both images. void DebugRenderer::reset() { - BF2_AI_FRONTIER("dice::hfe::ai::DebugRenderer::reset"); } +// ELF 0x842E7A0, PE 0x818080: the line drawer's +0x20 (drawRibbon) with depth true. Retail hands +// the Vec3 vector to the D3DX-vector slot as it is; both element types are three packed floats. +// [CHOSEN, not recovered] Returns 0: the slot is void (no caller reads the result). int DebugRenderer::drawLine(const std::vector& points, unsigned int colour, float width) const { - BF2_AI_FRONTIER("dice::hfe::ai::DebugRenderer::drawLine"); + lineDrawer()->drawRibbon(reinterpret_cast&>(points), colour, width, true); + return 0; } -int DebugRenderer::drawCircle(const Vec3& centre, const Vec3& normal, float radius, unsigned int colour, bool filled, int segments) const +// ELF 0x842E7E0, PE 0x8180A0 (a tail jump): the circle drawer's +0x10, a void slot. The Boolean +// selects terrain heights for the vertices; the count goes through unchanged. +// [CHOSEN, not recovered] Returns 0: the tail jump leaves the drawer's register (no caller reads it). +int DebugRenderer::drawCircle(const Vec3& normal, const Vec3& centre, float radius, unsigned int colour, bool terrain, int segments) const { - BF2_AI_FRONTIER("dice::hfe::ai::DebugRenderer::drawCircle"); + circleDrawer()->drawCircle(normal, centre, radius, colour, terrain, static_cast(segments)); + return 0; } +// ELF 0x842E830, PE 0x8180B0: the text writer's queueGroupColoured at the truncated screen +// position; `size` is the line spacing, right alignment is AITextAlignmentX 1, bottom alignment +// any non-zero AITextAlignmentY. +// [CHOSEN, not recovered] Both images return the register the void call leaves; 0 here (no caller +// reads it). int DebugRenderer::drawScreenText(const Vec2& position, const std::vector& lines, int size, unsigned int colour, AITextAlignmentX ax, AITextAlignmentY ay) const { - BF2_AI_FRONTIER("dice::hfe::ai::DebugRenderer::drawScreenText"); + textWriter()->queueGroupColoured(static_cast(position.x), static_cast(position.y), colour, + lines, size, ax == 1, ay != 0); + return 0; } +// ELF 0x842E8A0, PE 0x818120: as drawScreenText, through queueWorldGroupColoured. +// [CHOSEN, not recovered] Returns 0 for the same reason. int DebugRenderer::draw3dText(const Vec3& position, const std::vector& lines, int size, unsigned int colour, AITextAlignmentX ax, AITextAlignmentY ay) const { - BF2_AI_FRONTIER("dice::hfe::ai::DebugRenderer::draw3dText"); + textWriter()->queueWorldGroupColoured(position, colour, lines, size, ax == 1, ay != 0); + return 0; } -int DebugRenderer::drawTriangle(const std::vector& vertices, const std::vector& indices, bool filled) const +// ELF 0x842E8F0, PE 0x818160 (a tail jump): the line drawer's +0x2C (drawTriangles, per-triangle +// colours). [CHOSEN, not recovered] Returns 0: the slot is void. +int DebugRenderer::drawTriangle(const std::vector& vertices, const std::vector& colours, bool depth) const { - BF2_AI_FRONTIER("dice::hfe::ai::DebugRenderer::drawTriangle"); + lineDrawer()->drawTriangles(vertices, colours, depth); + return 0; } -int DebugRenderer::drawMesh(Vec3* vertices, unsigned int* indices, int count, unsigned int* colours, bool filled) const +// ELF 0x842E920, PE 0x818170 (a tail jump): the line drawer's +0x30. [CHOSEN, not recovered] +// Returns 0: the slot is void. +int DebugRenderer::drawMesh(Vec3* vertices, unsigned int* indices, int count, unsigned int* colours, bool depth) const { - BF2_AI_FRONTIER("dice::hfe::ai::DebugRenderer::drawMesh"); + lineDrawer()->drawMesh(vertices, indices, count, colours, depth); + return 0; } } // namespace ai diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/DebugRenderer.h b/Code/BF2/AI/AIInterface/BFKnowledge/DebugRenderer.h index 3e408e663..9167113f0 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/DebugRenderer.h +++ b/Code/BF2/AI/AIInterface/BFKnowledge/DebugRenderer.h @@ -29,11 +29,11 @@ class IDebugRenderer virtual void drawAll() = 0; virtual void reset() = 0; virtual int drawLine(const std::vector& points, unsigned int colour, float width) const = 0; - virtual int drawCircle(const Vec3& centre, const Vec3& normal, float radius, unsigned int colour, bool filled, int segments) const = 0; + virtual int drawCircle(const Vec3& normal, const Vec3& centre, float radius, unsigned int colour, bool terrain, int segments) const = 0; virtual int drawScreenText(const Vec2& position, const std::vector& lines, int size, unsigned int colour, AITextAlignmentX ax, AITextAlignmentY ay) const = 0; virtual int draw3dText(const Vec3& position, const std::vector& lines, int size, unsigned int colour, AITextAlignmentX ax, AITextAlignmentY ay) const = 0; - virtual int drawTriangle(const std::vector& vertices, const std::vector& indices, bool filled) const = 0; - virtual int drawMesh(Vec3* vertices, unsigned int* indices, int count, unsigned int* colours, bool filled) const = 0; + virtual int drawTriangle(const std::vector& vertices, const std::vector& colours, bool depth) const = 0; + virtual int drawMesh(Vec3* vertices, unsigned int* indices, int count, unsigned int* colours, bool depth) const = 0; }; class DebugRenderer : public IDebugRenderer @@ -45,11 +45,11 @@ class DebugRenderer : public IDebugRenderer virtual void drawAll(); virtual void reset(); virtual int drawLine(const std::vector& points, unsigned int colour, float width) const; - virtual int drawCircle(const Vec3& centre, const Vec3& normal, float radius, unsigned int colour, bool filled, int segments) const; + virtual int drawCircle(const Vec3& normal, const Vec3& centre, float radius, unsigned int colour, bool terrain, int segments) const; virtual int drawScreenText(const Vec2& position, const std::vector& lines, int size, unsigned int colour, AITextAlignmentX ax, AITextAlignmentY ay) const; virtual int draw3dText(const Vec3& position, const std::vector& lines, int size, unsigned int colour, AITextAlignmentX ax, AITextAlignmentY ay) const; - virtual int drawTriangle(const std::vector& vertices, const std::vector& indices, bool filled) const; - virtual int drawMesh(Vec3* vertices, unsigned int* indices, int count, unsigned int* colours, bool filled) const; + virtual int drawTriangle(const std::vector& vertices, const std::vector& colours, bool depth) const; + virtual int drawMesh(Vec3* vertices, unsigned int* indices, int count, unsigned int* colours, bool depth) const; }; } // namespace ai diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/PlanePolygon.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/PlanePolygon.cpp index 5e7d86d72..a9e4a193b 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/PlanePolygon.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/PlanePolygon.cpp @@ -1,36 +1,193 @@ // [INFERRED] Source placement. +// static init: ELF 0x36A780 (__tcf_0 0x36A7E0, _GLOBAL__I 0x36A810): 's Init object only. +#include + #include "PlanePolygon.h" -#include "AIFrontier.h" +#include "../../../Math/BoundingBox.h" +#include +#include namespace dice { namespace hfe { -// an empty list, or a copy of the caller's. +// ELF 0x83F81F0 / 0x83F82D0 (bf2); 0x3688C0 / 0x3689C0 (libaidll.so). PlanePolygon::PlanePolygon() { } +// ELF 0x83F8300 / 0x83F8360 (bf2); 0x368A10 / 0x368A80 (libaidll.so). PlanePolygon::PlanePolygon(const std::list& vertices) : m_vertices(vertices) { } -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-07-knowledge] -// Paired ABI evidence fixes this signature (, ELF imported symbol), but the 2,037-byte -// PE body and BoundingBox surface are not recovered. IPICover's physical fallback now stops at the -// exact callee instead of fabricating an outline. -PlanePolygon::PlanePolygon(BoundingBox* /*box*/, const Mat4& /*transformation*/) +// ELF 0x83F83C0 / 0x83F89E0 (bf2); 0x368AF0 / 0x369150 (libaidll.so). +PlanePolygon::PlanePolygon(BoundingBox* box, const Mat4& transformation) { - BF2_AI_FRONTIER("dice::hfe::PlanePolygon::PlanePolygon(BoundingBox*, const Mat4&)"); + Mat4 inverse = {}; + inverse.m[0] = inverse.m[5] = inverse.m[10] = inverse.m[15] = 1.0f; + inverse.setInverse(transformation); + Vec2* outline = new Vec2[4](); + Vec3* corners = new Vec3[8](); + for (int i = 0; i < 8; ++i) + { + const Vec3& p = box->m_corners[i]; + corners[i].x = inverse.m[0] * p.x + inverse.m[4] * p.y + inverse.m[8] * p.z + inverse.m[12]; + corners[i].y = inverse.m[1] * p.x + inverse.m[5] * p.y + inverse.m[9] * p.z + inverse.m[13]; + corners[i].z = p.x * inverse.m[2] + p.y * inverse.m[6] + p.z * inverse.m[10] + inverse.m[14]; + } + + int* indices = new int[4]; + float* heights = new float[4]; + indices[0] = 0; + heights[0] = corners[0].y; + for (int i = 1; i < 4; ++i) + { + float height = corners[i].y; + int index = i; + // shipped defect: compares the uninitialized heights[i], with bound 3-i. + for (int j = 0; j < 3 - i; ++j) + { + if (heights[i] > height) + { + std::swap(height, heights[j]); + std::swap(index, indices[j]); + } + } + heights[i] = height; + // shipped defect: the displaced index is discarded. + indices[i] = i; + } + for (int i = 4; i < 8; ++i) + { + const float height = corners[i].y; + // shipped defect: this bound is negative, so corners 4..7 never enter the set. + for (int j = 0; j < 3 - i; ++j) + { + if (heights[i] > height) + { + heights[j] = height; + indices[j] = i; + } + } + } + + unsigned int mask = 0; + for (int i = 0; i < 4; ++i) + mask |= 1U << indices[i]; + switch (mask) + { + case 0x0F: + vec3ToVec2XZ(corners[2], outline[0]); + vec3ToVec2XZ(corners[3], outline[1]); + vec3ToVec2XZ(corners[1], outline[2]); + vec3ToVec2XZ(corners[0], outline[3]); + break; + case 0x33: + vec3ToVec2XZ(corners[0], outline[0]); + vec3ToVec2XZ(corners[4], outline[1]); + vec3ToVec2XZ(corners[5], outline[2]); + vec3ToVec2XZ(corners[1], outline[3]); + break; + case 0x55: + vec3ToVec2XZ(corners[0], outline[0]); + vec3ToVec2XZ(corners[4], outline[1]); + vec3ToVec2XZ(corners[6], outline[2]); + vec3ToVec2XZ(corners[2], outline[3]); + break; + case 0xAA: + vec3ToVec2XZ(corners[7], outline[0]); + vec3ToVec2XZ(corners[3], outline[1]); + vec3ToVec2XZ(corners[1], outline[2]); + vec3ToVec2XZ(corners[5], outline[3]); + break; + case 0xCC: + vec3ToVec2XZ(corners[7], outline[0]); + vec3ToVec2XZ(corners[3], outline[1]); + vec3ToVec2XZ(corners[2], outline[2]); + vec3ToVec2XZ(corners[6], outline[3]); + break; + case 0xF0: + vec3ToVec2XZ(corners[4], outline[0]); + vec3ToVec2XZ(corners[5], outline[1]); + vec3ToVec2XZ(corners[7], outline[2]); + vec3ToVec2XZ(corners[6], outline[3]); + break; + } + for (int i = 0; i < 4; ++i) + m_vertices.push_back(outline[i]); + + // shipped defect: scalar deletes for arrays; the transformed corners are leaked. + ::operator delete(indices); + ::operator delete(heights); + ::operator delete(outline); } -// the list's own destructor. +// ELF 0x83F9000 / 0x83F93E0 (bf2); 0x3697B0 / 0x369BE0 (libaidll.so). +PlanePolygon::PlanePolygon(const Vec3& direction, BoundingBox* box) +{ + Vec3* highest = new Vec3[4](); + Vec2* outline = new Vec2[4](); + highest[0] = box->m_corners[0]; + float lowest = highest[0].y; + for (int i = 1; i < 8; ++i) + { + Vec3 candidate = box->m_corners[i]; + if (i < 4 && lowest > candidate.y) + lowest = candidate.y; + for (int j = 0; j < 4; ++j) + { + if (i == j) + { + highest[i] = candidate; + break; + } + if (highest[j].y < candidate.y) + { + // shipped defect: takes the displaced value from the original box. + const Vec3 displaced = box->m_corners[j]; + highest[j] = candidate; + candidate = displaced; + } + } + } + (void)lowest; + for (int i = 0; i < 4; ++i) + vec3ToVec2XZ(highest[i], outline[i]); + const Vec2 normal = { -direction.z, direction.x }; + int minIndex = 0; + int maxIndex = 0; + float minimum = normal.x * outline[0].x + normal.y * outline[0].y; + float maximum = minimum; + for (int i = 1; i < 4; ++i) + { + const float projection = normal.x * outline[i].x + normal.y * outline[i].y; + if (minimum > projection) + { + minimum = projection; + minIndex = i; + } + else if (maximum < projection) + { + maximum = projection; + maxIndex = i; + } + } + m_vertices.push_back(outline[maxIndex]); + m_vertices.push_back(outline[minIndex]); + // shipped defect: arrays are released with scalar delete. + ::operator delete(highest); + ::operator delete(outline); +} + +// ELF 0x83F97C0 / 0x83F9800 / 0x83F9840 (bf2); 0x36A010 / 0x36A070 / 0x36A0D0 (libaidll.so). PlanePolygon::~PlanePolygon() { } +// ELF 0x83F9890 (bf2); 0x36A140 (libaidll.so). // Each corner goes XZ -> Vec3 (y = 0), through the transformation // as a point (row vector: x' = m0*x + m4*y + m8*z + m12, and so on), and back to XZ, appended to a // temporary list; a new empty PlanePolygon then takes that list through its own setVertices slot. @@ -69,19 +226,20 @@ IPlanePolygon* PlanePolygon::fromTransform(const Mat4& transformation) const return polygon; } -// cleared, then refilled from the caller's list. +// ELF 0x83F9A10 (bf2); 0x36A300 (libaidll.so). Clears, then refills from the caller's list. void PlanePolygon::setVertices(std::list& vertices) { m_vertices.clear(); m_vertices.assign(vertices.begin(), vertices.end()); } +// ELF 0x83F9A70 (bf2); 0x36A370 (libaidll.so). const std::list& PlanePolygon::getVertices() const { return m_vertices; } -// `out` cleared, then each corner scaled per axis and appended. +// ELF 0x83F9A80 (bf2); 0x36A380 (libaidll.so). Clears out, then appends each corner scaled per axis. void PlanePolygon::getScaledVertices(std::list& out, const Vec2& scale) const { Vec2 scaled; @@ -96,16 +254,64 @@ void PlanePolygon::getScaledVertices(std::list& out, const Vec2& scale) co } } -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-07-knowledge] -bool PlanePolygon::intersects(const Vec2& /*a*/, const Vec2& /*b*/) const +// ELF 0x83F9B10 (bf2); 0x36A430 (libaidll.so). +bool PlanePolygon::intersects(const Vec2& a, const Vec2& b) const { - BF2_AI_FRONTIER("dice::hfe::PlanePolygon::intersects"); + Vec2 normal = { 0.0f, 0.0f }; + getNormal(a, normal); + // shipped defect: dereferences end() for the initial edge endpoint. + const Vec2& last = *m_vertices.end(); + float previous = (last.x - b.x) * normal.x + (last.y - b.y) * normal.y; + std::list::const_iterator it = m_vertices.begin(); + float current = (it->x - b.x) * normal.x + (it->y - b.y) * normal.y; + // Unordered previous values follow the negative arm in both ELF builds. + if (previous >= 0.0f ? current <= 0.0f : current >= 0.0f) + return true; + previous = current; + for (++it; it != m_vertices.end(); ++it) + { + current = (it->x - b.x) * normal.x + (it->y - b.y) * normal.y; + if (!(previous >= 0.0f)) + { + // shipped defect: tests the untouched zero vector instead of current. + if (normal.x * 0.0f + normal.y * 0.0f >= 0.0f) + return true; + } + else if (current <= 0.0f) + return true; + previous = current; + } + return false; } -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-07-knowledge] -bool PlanePolygon::isInside(const Vec2& /*a*/, const Vec2& /*b*/) const +// ELF 0x83F9CF0 (bf2); 0x36A640 (libaidll.so). +bool PlanePolygon::isInside(const Vec2& a, const Vec2& b) const { - BF2_AI_FRONTIER("dice::hfe::PlanePolygon::isInside"); + const Vec2 normal = { -a.y, a.x }; + int crossings = 0; + std::list::const_iterator last = m_vertices.end(); + --last; + for (std::list::const_iterator it = m_vertices.begin(); it != last; ++it) + { + std::list::const_iterator next = it; + ++next; + // shipped defect: adds b, omits the closing edge, and accepts even crossing counts. + const float first = (it->x + b.x) * normal.x + (it->y + b.y) * normal.y; + const float second = (next->x + b.x) * normal.x + (next->y + b.y) * normal.y; + if (first > 0.0f) + { + if (second <= 0.0f) + ++crossings; + } + else if (first < 0.0f) + { + if (second >= 0.0f) + ++crossings; + } + else if (second == 0.0f) + ++crossings; + } + return (crossings & 1) == 0; } } // namespace hfe diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/PlanePolygon.h b/Code/BF2/AI/AIInterface/BFKnowledge/PlanePolygon.h index 15dff818e..1398b90d7 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/PlanePolygon.h +++ b/Code/BF2/AI/AIInterface/BFKnowledge/PlanePolygon.h @@ -1,9 +1,5 @@ // Planar polygon geometry and transforms. -// [FRONTIER] Intersection and containment operations remain incomplete. // [INFERRED] Source placement. -// [TEMP] Temporary implementation boundaries remain. -// [CHOSEN, not recovered] Temporary implementation boundaries remain. -// [RETIRE-WHEN: aidll-07-knowledge] Complete and validate the remaining PlanePolygon operations. #ifndef AI_AIINTERFACE_BFKNOWLEDGE_PLANEPOLYGON_H #define AI_AIINTERFACE_BFKNOWLEDGE_PLANEPOLYGON_H @@ -38,15 +34,16 @@ class PlanePolygon : public IPlanePolygon public: PlanePolygon(); explicit PlanePolygon(const std::list& vertices); - PlanePolygon(BoundingBox* box, const Mat4& transformation); // [FRONTIER] + PlanePolygon(BoundingBox* box, const Mat4& transformation); + PlanePolygon(const Vec3& direction, BoundingBox* box); virtual ~PlanePolygon(); virtual IPlanePolygon* fromTransform(const Mat4& transformation) const; virtual void setVertices(std::list& vertices); virtual const std::list& getVertices() const; virtual void getScaledVertices(std::list& out, const Vec2& scale) const; - virtual bool intersects(const Vec2& a, const Vec2& b) const; // [FRONTIER] - virtual bool isInside(const Vec2& a, const Vec2& b) const; // [FRONTIER] + virtual bool intersects(const Vec2& a, const Vec2& b) const; + virtual bool isInside(const Vec2& a, const Vec2& b) const; private: /* +0x04 */ std::list m_vertices; diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/WeaponObject.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/WeaponObject.cpp index 8dc64ecda..abd2c4b49 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/WeaponObject.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/WeaponObject.cpp @@ -122,7 +122,7 @@ void WeaponObject::init(world::IObject* object) if (projectileTemplate->getComponentFromClassID(world::CID_ResurrectCollisionCompTemplate)) weaponType = WTResurrect; // +0x60 else if (projectileTemplate->getComponentFromClassID(world::CID_StickyCollisionCompTemplate)) - weaponType = WTSticky; + weaponType = WTC4; } float gravityModifier = 1.0f; diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/WeaponTemplate.h b/Code/BF2/AI/AIInterface/BFKnowledge/WeaponTemplate.h index 9cb52a47b..aef2bad4b 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/WeaponTemplate.h +++ b/Code/BF2/AI/AIInterface/BFKnowledge/WeaponTemplate.h @@ -18,10 +18,12 @@ namespace ai { class IWeapon; // ai::WeaponType - the name is the mangled parameter type of WeaponTemplate::init; the enumerator -// names are [CHOSEN], from how WeaponObject::init derives each value: a replenishing ammo component -// gives 1 (ReplenishingType RTHeal) or 2 (RTAmmo), a projectile with a resurrect collision component -// gives 3, with a sticky collision component 4 (checked in that order, overriding the ammo answer) -// anything else 0. AIObjectArmament counts only type-0 weapons into a unit's battle strength, and +// names 0..3 are [CHOSEN], from how WeaponObject::init derives each value: a replenishing ammo +// component gives 1 (ReplenishingType RTHeal) or 2 (RTAmmo), a projectile with a resurrect collision +// component gives 3, with a sticky collision component 4 (checked in that order, overriding the ammo +// answer), anything else 0. 4 is DICE's `WTC4`: AIDLL_r.dll (BoosterPack2 debug build) BBC4.cpp asserts +// "wInfo->getWeaponType() == WTC4" ("Expected C4 weapon type"), string at 0x1029E0AC. +// AIObjectArmament counts only type-0 weapons into a unit's battle strength, and // WeaponObject::getReplenishRadius answers only for 1 and 2. enum WeaponType { @@ -29,7 +31,7 @@ enum WeaponType WTHeal = 1, WTAmmo = 2, WTResurrect = 3, - WTSticky = 4 + WTC4 = 4 }; // ai::WeaponGuidingSystem - mangled name attested; enumerators [CHOSEN] after world::TargetSystem diff --git a/Code/BF2/AI/AIInterface/Main/AIEventListener.cpp b/Code/BF2/AI/AIInterface/Main/AIEventListener.cpp index 81754e555..41bf3169d 100644 --- a/Code/BF2/AI/AIInterface/Main/AIEventListener.cpp +++ b/Code/BF2/AI/AIInterface/Main/AIEventListener.cpp @@ -1,6 +1,7 @@ #include "AIEventListener.h" +#include #include #include #include @@ -10,11 +11,15 @@ #include "../../../Game/Objects/IPlayer.h" // world::IPlayer::getId / getIsAIPlayer #include "../SingletonServer.h" // BFSingletonServer::m_iaiEventCourier #include "../BFKnowledge/BFGame.h" // IAIGame::setIsPrecaching / isPlaying -#include "../BFKnowledge/AIPlayerFactory.h" // IAIPlayerFactory +#include "../BFKnowledge/AIPlayerFactory.h" // IAIPlayerFactory, isOccupiedObject +#include "../BFKnowledge/IAIObject.h" // the vehicle and armament arms +#include "../BFKnowledge/IAIObjectPlugIn.h" // IAIObjectUnit / IAIObjectPhysical +#include "../Module/BFConsole.h" // BFConsole::getAIMessageSettings (radio) +#include "../../AIDLL/AI/AIKnowledge/BFInformationCourier.h" // IAIInformationCourier armament #include "../../AIDLL/AI/Main/CommonSingletonServer.h" #include "../../AIDLL/AI/Main/AIEventCourier.h" // IAIEventCourier - 55 named slots #include "../../AIDLL/AI/Main/AISettingsInterfaces.h" // IAISettings::getDraw -#include "../../AIDLL/AI/Main/AIMineManager.h" // IAIMineManager::mineRemoved +#include "../../AIDLL/AI/AIKnowledge/AIMineManager.h" // IAIMineManager::mineRemoved #include "../../../Game/GameServer/ServerSettings.h" // the team-ratio inversion below #include "../../../Scene/Object/PlayerManager.h" // the three lookups it needs #include "../../AIDLL/AI/DrawPrimitives/DPManager.h"// IDPManager::drawAll / nodrawUpdate @@ -75,17 +80,90 @@ void AIEventListener::registerEvents() namespace { -// [FRONTIER] [TEMP] [CHOSEN, not recovered] - one per unwritten arm, each naming its own -// (category, id) so the next person knows exactly which dispatch entry is wanted rather than only -// that `handleEvent` was reached. [RETIRE-WHEN: aidll-01-adapters] -void unwrittenArm(const char* what, int category, unsigned int id) +// Category 3 id 0x16 (enemy spotted): SpottedEvent::executeServer's eight-byte stack block, an AI +// object pointer followed by the low byte of the team. The x86 layout is retail's (team at +4); +// the struct keeps the team after the full pointer on native x64. +struct SpottedPayload { - std::fprintf(stderr, - "[FRONTIER] dice::hfe::ai::AIEventListener::handleEvent - %s" "\n" - " category=%d id=%u" "\n", - what, category, id); - std::fflush(stderr); - std::abort(); + IAIObject* aiObject; // +0x00 + unsigned char team; // +0x04 +}; +#if defined(_M_IX86) +static_assert(offsetof(SpottedPayload, team) == 4, "retail spotted-event team byte"); +#endif + +// Category 3 ids 1 and 2 (seat entered / left): the five-dword block Soldier::enter posts +// (Soldier.cpp SoldierAiSeatPayload). The arms read +0x10 as a byte (`cmpb $0x0, 0x10(%esi)`). +struct SeatPayload +{ + IAIObject* object; // +0x00 the entered object (id 1) / the leaving soldier (id 2) + IAIObject* other; // +0x04 id 1: the armament lender; id 2: the vehicle left + int team; // +0x08 + int playerId; // +0x0C + int flag; // +0x10 low byte tested +}; + +// Category 3 id 0 (player killed): two ints, then the object whose borrowed armament is returned. +struct KilledPayload +{ + int a; // +0x00 eventPlayerKilled's second argument + int b; // +0x04 its first + IAIObject* object; // +0x08 +}; + +// Category 3 ids 6 / 7 (man down / revived): Soldier.cpp SoldierAiPlayerPayload. +struct ObjectPlayerPayload +{ + IAIObject* object; // +0x00 + int playerId; // +0x04 +}; + +// Category 3 ids 3 and 17: an int followed by an object. +struct IntObjectPayload +{ + int value; // +0x00 id 3: eventPlayerExitVehicle's int; id 17: the bridge's int + IAIObject* object; // +0x04 +}; + +// Category 3 id 10 (radio): the message key and two ints, all forwarded. +struct RadioPayload +{ + int message; // +0x00 BFConsole::getAIMessageSettings key + int a; // +0x04 + int b; // +0x08 +}; + +// Category 3 id 15 (commander request), 68 bytes copied to the stack whole (bf2 0x842FE75). +// Only +0x00 (type), +0x30, +0x34 and +0x38 are read; the rest is [UNRESOLVED]. +struct CommanderRequestPayload +{ + int type; // +0x00 0 artillery, 1 UAV, 2 vehicle drop, 3 supply + unsigned short unknown04; // +0x04 + Vec3 unknown08[3];// +0x08 + unsigned char unknown2C; // +0x2C + int a; // +0x30 + int b; // +0x34 + Vec3 position; // +0x38 +}; +static_assert(sizeof(CommanderRequestPayload) == 0x44, "retail 68-byte commander request"); + +#if defined(_M_IX86) +static_assert(sizeof(SeatPayload) == 20 && offsetof(KilledPayload, object) == 8 + && offsetof(IntObjectPayload, object) == 4, "retail ECAI payloads"); +#endif + +IAIInformationCourier* informationCourier() +{ + return static_cast(CommonSingletonServer::m_iaiInformationCourier); +} + +// The armament hand-back of ids 0, 2 and 14 once the unit must borrow armament: reset it, and the +// information courier resets both sides' handles (1 then 2). +void returnArmament(IAIObject* object) +{ + object->resetArmament(); // +0x80 + informationCourier()->resetArmament(object->getHandle(1)); // +0x30 + informationCourier()->resetArmament(object->getHandle(2)); } } // anonymous namespace @@ -253,9 +331,9 @@ void AIEventListener::handleEvent(EventCategory category, case 0x16u: { - // The payload is an object pointer followed by a team byte at offset 4. - const unsigned char* const bytes = static_cast(userData); - courier->event_enemySpotted(*static_cast(userData), bytes[4]); + // The payload is an object pointer followed by a team byte (offset 4 on x86). + const SpottedPayload* const payload = static_cast(userData); + courier->event_enemySpotted(payload->aiObject, payload->team); } return; @@ -263,56 +341,179 @@ void AIEventListener::handleEvent(EventCategory category, courier->event_isRepaired(*static_cast(userData)); return; - // the arms that dereference the payload as a world::IObject - // Each of these walks a vehicle or a pathfinding map through `world::IObject` vtable slots - // this tree does not name yet (decimal +116, +124, +128, +148, +152, +200, +204, +208, +252 - // and +296). Naming them is a `world::IObject` slot-map job, not an AI one, and guessing - // them would put ten wrong method names in the tree. Each stop below says which arm it is. + // bf2 0x842F7BE: the kill, then a non-null unit object's borrowed armament goes back + // (isUnit +0x74 gates the getUnit dereference). case 0u: - unwrittenArm("category 3 id 0 - player killed, plus the vehicle's armament release", - (int)category, id); + { + const KilledPayload* const p = static_cast(userData); + courier->eventPlayerKilled(p->b, p->a); + IAIObject* const object = p->object; + if (object && object->isUnit() // no getUnit null test here + && object->getUnit()->mustBorrowArmament(object)) + returnArmament(object); + } return; + + // bf2 0x842F870: entering a seat. The entered object takes the team (setSide +0x128), its + // primary object's physics are enabled for that team (IAIObjectPhysical +0x74), a unit that + // must borrow armament borrows the lender's (+0x7C) and the information courier links both + // sides' handles (+0x2C lender, borrower), the lender leaves the grid (+0xC8), and the AI + // hears eventPlayerEnterVehicle(playerId, object, lender). case 1u: - unwrittenArm("category 3 id 1 - player entered vehicle (and the 'not prepared for use" - " with AI' Debug at line 166)", (int)category, id); + { + const SeatPayload* const p = static_cast(userData); + IAIObject* const object = p->object; + if (!object) + { + if (static_cast(p->flag)) + return; + // The image logs and carries on into the null object (line 166). + Debug(DebugTypeError, "AI/AIInterface/Main/AIEventListener.cpp", 166, "") + << "You have tried to enter a vehicle that is not prepared for use with AI." + " Game will crash."; + } + IAIObject* const primary = object->getPrimaryObject(); + IAIObject* const lender = p->other; + object->setSide(p->team); + if (primary) + { + IAIObjectPhysical* const physical = primary->getPhysical(); + if (physical) + physical->enablePhysics(p->team); + } + if (lender && object->getUnit() && object->getUnit()->mustBorrowArmament(object)) + { + object->borrowArmament(lender); + { + const unsigned int borrower = object->getHandle(1); + informationCourier()->borrowArmament(lender->getHandle(1), borrower); + } + { + const unsigned int borrower = object->getHandle(2); + informationCourier()->borrowArmament(lender->getHandle(2), borrower); + } + } + if (p->other) + p->other->removeFromGrid(); + courier->eventPlayerEnterVehicle(p->playerId, p->object, p->other); + } return; + + // bf2 0x842FAB0: leaving a seat. The vehicle left returns borrowed armament and, when + // nobody else occupies it, goes neutral (setSide 0); the soldier re-enters the grid. case 2u: - unwrittenArm("category 3 id 2 - player exited vehicle", (int)category, id); + { + const SeatPayload* const p = static_cast(userData); + if (static_cast(p->flag)) + return; + IAIObject* const vehicle = p->other; + IAIObject* const soldier = p->object; + if (vehicle) + { + if (vehicle->getUnit() && vehicle->getUnit()->mustBorrowArmament(vehicle)) + returnArmament(vehicle); + if (!isOccupiedObject(vehicle, vehicle)) + vehicle->setSide(0); + } + if (soldier) + soldier->reInsertInGrid(); // +0xCC + } return; + + // bf2 0x842FB84. case 3u: - unwrittenArm("category 3 id 3 - eventPlayerExitVehicle", (int)category, id); + { + const IntObjectPayload* const p = static_cast(userData); + courier->eventPlayerExitVehicle(p->object, p->value); + } return; + + // bf2 0x842FBE9: the payload is the AI object (Soldier's kit pick-up); update +0x4C. case 5u: - unwrittenArm("category 3 id 5 - object slot +76", (int)category, id); + static_cast(userData)->update(); return; + + // bf2 0x842FBF6. case 6u: - unwrittenArm("category 3 id 6 - man down", (int)category, id); + { + const ObjectPlayerPayload* const p = static_cast(userData); + courier->eventManDown(p->playerId, p->object); + } return; + + // bf2 0x842FC16: the object is updated first. case 7u: - unwrittenArm("category 3 id 7 - revived", (int)category, id); + { + const ObjectPlayerPayload* const p = static_cast(userData); + p->object->update(); + courier->eventRevived(p->playerId, p->object); + } return; + + // bf2 0x842FD3F: a known message (BFConsole::m_instance, read directly) is forwarded. case 0xAu: - unwrittenArm("category 3 id 10 - radio message (needs BFConsole::getAIMessageSettings," - " itself a frontier)", (int)category, id); + { + const RadioPayload* const p = static_cast(userData); + AIRadioMessageSettings settings; + if (BFConsole::m_instance->getAIMessageSettings(p->message, settings)) + courier->eventRadioMessage(settings, p->a, p->b); + } return; + + // bf2 0x842FDF7: armament release of a non-null object. case 0xEu: - unwrittenArm("category 3 id 14 - vehicle armament release", (int)category, id); + { + IAIObject* const object = static_cast(userData); + if (object && object->getUnit() && object->getUnit()->mustBorrowArmament(object)) + returnArmament(object); + } return; + + // bf2 0x842FE75: the commander's requests by type; others are logged at line 449. case 0xFu: - unwrittenArm("category 3 id 15 - commander request (artillery/uav/supply/vehicle drop)," - " a 68-byte payload struct", (int)category, id); + { + const CommanderRequestPayload request = *static_cast(userData); + switch (request.type) + { + case 0: courier->event_receivedArtilleryRequest(request.a, request.b, request.position); break; + case 1: courier->event_receivedUavRequest(request.a, request.b, request.position); break; + case 2: courier->event_receivedVehicleDropRequest(request.a, request.b, request.position); break; + case 3: courier->event_receivedSupplyRequest(request.a, request.b, request.position); break; + default: + Debug(DebugTypeError, "AI/AIInterface/Main/AIEventListener.cpp", 449, "") + << "AI received unknown request type: " << request.type; + break; + } + } return; + + // bf2 0x84301D9: while playing (IAIGame +0x60), the bridge's map position id is destroyed + // (with a null object) and the bridge reported destroyed. case 0x11u: - unwrittenArm("category 3 id 17 - bridge destroyed", (int)category, id); + if (static_cast(CommonSingletonServer::m_iaiGame)->isPlaying()) + { + const IntObjectPayload* const p = static_cast(userData); + IAIObject* const bridge = p->object; + courier->event_pathfindingMapIdDestroyed(bridge->getPhysical()->getMapPosId(), 0); + courier->event_bridgeDestroyed(bridge, p->value); + } return; + + // bf2 0x843023F: the payload is the AI object (ArmorGLComp's repair post). case 0x12u: - unwrittenArm("category 3 id 18 - bridge repaired", (int)category, id); + { + IAIObject* const bridge = static_cast(userData); + courier->event_pathfindingMapIdRestored(bridge->getPhysical()->getMapPosId()); + courier->event_bridgeRepaired(bridge); + } return; + + // bf2 0x8430280 / 0x843028A: the payload is the AI object. case 0x13u: - unwrittenArm("category 3 id 19 - object slot +204", (int)category, id); + static_cast(userData)->reInsertInGrid(); return; case 0x14u: - unwrittenArm("category 3 id 20 - object slot +200", (int)category, id); + static_cast(userData)->removeFromGrid(); return; default: diff --git a/Code/BF2/AI/AIInterface/Module/BFConsole.cpp b/Code/BF2/AI/AIInterface/Module/BFConsole.cpp index 5caa0cf25..3af04b197 100644 --- a/Code/BF2/AI/AIInterface/Module/BFConsole.cpp +++ b/Code/BF2/AI/AIInterface/Module/BFConsole.cpp @@ -1,12 +1,13 @@ #include "BFConsole.h" -#include // the [FRONTIER] stops - stderr, not Debug; see the note at the first one -#include // std::abort - same +#include #include "../../AIDLL/AI/AIUtils/checkPointer.h" #include "../../AIDLL/AI/Main/CommonSingletonServer.h" #include "../../../Core/ClassManager.h" +#include "../../../Core/Debug.h" +#include "../../../Core/Ids.h" #include "../AIInstance.h" #include "../SingletonServer.h" #include "../Main/AIEventListener.h" @@ -48,13 +49,23 @@ #include "../BFKnowledge/WeaponTemplateManager.h" #include "../../../Core/ConsoleObjectMacro.h" #include "../../../Core/StringUtil.h" - +#include "../../../Game/IGameLogic.h" // addAIRadioMessage: gameLogic +#include "../../../Game/IGame.h" +#include "../../../Game/Objects/IPlayer.h" +#include "../../../Scene/Object/PlayerManager.h" +#include "../../../Game/GameLogic/ScoreSystem/ScoreManager.h" +#include "../../../Physics/BasicPhysicsSystem.h" +#include "../../../Game/GameLogic/GameLogic.h" // getVoiceMessages +#include "../../../Game/GameLogic/VoiceMessages.h" // namesToIds + +#include #include namespace dice { namespace hfe { extern ClassManager* classManager; +namespace world { extern IBase* scoreManager; } namespace ai { @@ -130,7 +141,7 @@ KitTemplate* getActiveKitTemplate() namespace { // [CHOSEN] native list key. Retail pushes every generated binding of this TU onto one list -// this tree's recovered subset - aiTemplate, aiTemplatePlugIn and kitTemplate so far +// this tree's recovered subset - aiTemplate, aiTemplatePlugIn, kitTemplate and aiComm so far // shares this one. const char* const kKitTemplateConsoleTag = "hfe.ai.kitTemplate"; @@ -655,6 +666,18 @@ BF2_CONSOLE_METHOD_2_STATIC_ACTIVE(setBattleStrength, consoleKitTemplateSetBattl getActiveKitTemplate() != 0, CombatStrengthType, int, kKitTemplateConsoleTag) #pragma pop_macro("BF2_CC_CONVERT") +// aiComm (ConsoleClass262, bf2 0x887E470): access 2, category 0; active while the console exists. +// The executor copies the name and forwards the three floats to the console instance. +namespace { +void consoleAddAIRadioMessage(std::string name, float modifier, float maxSendPeriod, float receiveTimeToLive) +{ + BFConsole::m_instance->addAIRadioMessage(name, modifier, maxSendPeriod, receiveTimeToLive); +} +} // namespace +BF2_CONSOLE_OBJECT("aiComm", 2, 0) +BF2_CONSOLE_METHOD_4_STATIC_ACTIVE(addAIRadioMessage, consoleAddAIRadioMessage, BFConsole::m_instance != 0, + std::string, float, float, float, kKitTemplateConsoleTag) + ConsoleObjectList& kitTemplateConsoleObjects() { return consoleBindingList(kKitTemplateConsoleTag); @@ -665,6 +688,7 @@ ConsoleObjectList& kitTemplateConsoleObjects() BFConsole* BFConsole::m_instance = 0; // Initializes console state and registers the AI adapter types. Registration keeps the first singleton. +// ELF 0x887ED00 / 0x887F790. BFConsole::BFConsole() : m_skipBulkClear(false) , m_singletonsCreated(false) @@ -694,6 +718,7 @@ BFConsole::BFConsole() } // Unregisters this console instance when it is the active singleton. +// ELF 0x8880190 / 0x88802C0. BFConsole::~BFConsole() { if (m_instance == this) @@ -701,12 +726,14 @@ BFConsole::~BFConsole() } // Returns null in this build. +// ELF 0x8881B50. void* BFConsole::getSinglePlayerInstance() { return 0; } // Constructs the engine-side AI adapters and refreshes cached singleton interfaces. +// ELF 0x88803F0. void BFConsole::createSingletons() { if (!m_singletonsCreated) @@ -761,6 +788,7 @@ void BFConsole::createSingletons() // Destroys the engine-side AI adapters and refreshes cached interfaces. // m_skipBulkClear suppresses one clearing pass. +// ELF 0x8881300. void BFConsole::clearSingletons() { if (m_skipBulkClear) @@ -815,8 +843,7 @@ void BFConsole::clearSingletons() } // Initializes the AI adapters needed for a game. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] -// [RETIRE-WHEN: aidll-01-adapters] Replace remaining adapter stops with validated implementations. +// ELF 0x8881430. void BFConsole::aiMainInit() { // the two world adapters - see the block above. @@ -842,21 +869,66 @@ void BFConsole::aiMainInit() AITemplateManager::m_instance->createWreckTemplates(); } +// bf2 0x88816E0 (1135 B; recovered on the client track). The +// collision handler drops every tracked projectile (+0x08); the three template managers are +// deleted (nonvirtual destructors) and the kit manager through its deleting destructor (+0x10); +// all four are built again (their constructors install the singletons), each allocation checked +// like createSingletons (the Debug arms log and carry on); finally the AI game is told it is +// precaching (IAIGame +0x64, true). +// ELF 0x88816E0. void BFConsole::reset() { - std::fprintf(stderr, "[FRONTIER] dice::hfe::ai::BFConsole::reset reached\n"); - std::fflush(stderr); - std::abort(); -} - -void BFConsole::addAIRadioMessage(const std::string& /*name*/, float, float, float) -{ - std::fprintf(stderr, "[FRONTIER] dice::hfe::ai::BFConsole::addAIRadioMessage reached\n"); - std::fflush(stderr); - std::abort(); + if (CommonSingletonServer::m_iBFCollisionHandler) + static_cast(CommonSingletonServer::m_iBFCollisionHandler)->removeAllProjectiles(); + if (AITemplateManager::m_instance) + delete AITemplateManager::m_instance; + if (AITemplatePlugInManager::m_instance) + delete AITemplatePlugInManager::m_instance; + if (WeaponTemplateManager::m_instance) + delete WeaponTemplateManager::m_instance; + if (KitTemplateManager::m_instance) + delete static_cast(KitTemplateManager::m_instance); + + AITemplateManager* templateManager = new AITemplateManager; // 0x24 + checkPointer(templateManager); + AITemplatePlugInManager* plugInManager = new AITemplatePlugInManager; // 0x20 + checkPointer(plugInManager); + WeaponTemplateManager* weaponTemplates = new WeaponTemplateManager(6); // 0x24 + checkPointer(weaponTemplates); + KitTemplateManager* kitTemplates = new KitTemplateManager; // 0x2C + checkPointer(kitTemplates); + + if (CommonSingletonServer::m_iaiGame) + static_cast(CommonSingletonServer::m_iaiGame)->setIsPrecaching(true); +} + +// bf2 0x8881BE0 (Hex-Rays; called only by the aiComm.addAIRadioMessage executor, ConsoleClass262). +// The voice message id comes from GameLogic's VoiceMessages (no voice, no filter); the radio +// message type from the name table the constructor filled, read without an end() test (an +// unknown name reads the header node, as shipped). Both maps keep an existing entry +// (insert_unique): settings[(unsigned char)id] = {type, modifier, max send period, receive time to +// live}, voices[type] = (unsigned char)id. AIRadioMessages.ai calls it once per message. +// ELF 0x8881B60. +void BFConsole::addAIRadioMessage(const std::string& name, float modifier, float maxSendPeriod, + float receiveTimeToLive) +{ + int messageId; + const std::string filter; + const std::string voice; + static_cast(gameLogic)->getVoiceMessages()->namesToIds(&messageId, 0, 0, name, voice, filter); + const AIRadioMessageType type = m_radioMessageTypes.find(name)->second; + AIRadioMessageSettings settings; + const int typeWord = static_cast(type); + std::memcpy(settings.m_opaque0, &typeWord, sizeof(typeWord)); + settings.m_modifier = modifier; + settings.m_maxSendPeriod = maxSendPeriod; + settings.m_receiveTimeToLive = receiveTimeToLive; + m_messageSettings.insert(std::make_pair(static_cast(messageId), settings)); + m_messageVoices.insert(std::make_pair(type, static_cast(messageId))); } // Resolves radio-message identifiers through the module courier. +// ELF 0x8881D90. bool BFConsole::getAIMessageSettings(int voiceId, AIRadioMessageSettings& settings) { // The key is the low byte - see the block above. @@ -870,6 +942,7 @@ bool BFConsole::getAIMessageSettings(int voiceId, AIRadioMessageSettings& settin return true; } +// ELF 0x8881E00. bool BFConsole::getVoiceFromAiMessageType(AIRadioMessageType type, int& voice) { std::map::const_iterator it = m_messageVoices.find(type); @@ -880,11 +953,101 @@ bool BFConsole::getVoiceFromAiMessageType(AIRadioMessageType type, int& voice) return true; } -void BFConsole::code(const std::string&) +// ELF 0x8881E50. ConsoleClass268's returned-string assignment also attests the result type. +std::string BFConsole::code(const std::string& command) { - std::fprintf(stderr, "[FRONTIER] dice::hfe::ai::BFConsole::code reached\n"); - std::fflush(stderr); - std::abort(); + std::stringstream result; + world::IScoreManager* const scores = static_cast(world::scoreManager); + world::IPlayer* const player = world::playerManager->getLocalHumanPlayer(); + Debug(DebugTypeError, "AI/AIInterface/Module/BFConsole.cpp", 322, "") << "Does not work"; + if (!player) + { + result << "Error, could not find local player."; + return result.str(); + } + + const unsigned int team = static_cast(player->getTeam()); + const int tickets = scores->getTeamScore(team)->m_tickets; + float fraction = 0.0f; + bool reduceTickets = true; + if (equalsIgnoreCase(std::string(command.c_str()), std::string("Tobias.Karlsson"))) + { + if (game) + game->queryInterface(IID_IGameServer); + else + result << "Error, no game server active."; + // shipped defect: the failed server lookup does not prevent the ticket change. + fraction = 0.25f; + } + else if (equalsIgnoreCase(std::string(command.c_str()), std::string("Jonathan.Gustavsson"))) + { + if (gameLogic->getGameStatus() == 1) + result << "Error, no active BotManager found."; + else + result << "Error, game must be running for this command."; + return result.str(); + } + else if (equalsIgnoreCase(std::string(command.c_str()), std::string("Thomas.Skoldenborg")) || + equalsIgnoreCase(std::string(command.c_str()), std::string("Thomas.Sk\xF6ldenborg"))) + { + fraction = 0.33f; + } + else if (equalsIgnoreCase(std::string(command.c_str()), std::string("TheAllSeeingEyeOfTheAIProgrammer"))) + { + fraction = 0.5f; + } + else if (equalsIgnoreCase(std::string(command.c_str()), std::string("BotsCanCheatToo"))) + { + result << "The bots are CHEATING now, be aware."; + fraction = 0.75f; + } + else if (equalsIgnoreCase(std::string(command.c_str()), std::string("ChallengeMyComputer"))) + { + result << "There goes the FRAME RATE."; + fraction = 0.75f; + } + else if (equalsIgnoreCase(std::string(command.c_str()), std::string("EarthWalk"))) + { + static_cast(world::basicPhysicsSystem)->setGravity(-10.0f); + result << "GRAVITY set to EARTH. Home sweet home."; + reduceTickets = false; + } + else if (equalsIgnoreCase(std::string(command.c_str()), std::string("MoonWalk"))) + { + static_cast(world::basicPhysicsSystem)->setGravity(-1.67f); + result << "GRAVITY set to MOON. Let's dance!"; + fraction = 0.75f; + } + else if (equalsIgnoreCase(std::string(command.c_str()), std::string("SpaceWalk"))) + { + static_cast(world::basicPhysicsSystem)->setGravity(-0.1f); + result << "GRAVITY set to SPACE. Better hold on tight!"; + fraction = 0.5f; + } + else if (equalsIgnoreCase(std::string(command.c_str()), std::string("FUBAR"))) + { + result << "QWERTY!"; + reduceTickets = false; + } + else + { + result << "Trying to cheat? \nShame on you! \n Feel my Wrath."; + const int remaining = tickets < 2 ? tickets : 1; + scores->getTeamScore(team)->setTickets(remaining); + reduceTickets = false; + } + + if (reduceTickets) + { + world::TeamScore* const score = scores->getTeamScore(team); + const float remaining = static_cast(tickets) * fraction; + score->setTickets(static_cast(remaining)); + } + // shipped defect: a busy loop only polls tickets and increments a local counter. + for (int i = 0; i < tickets - scores->getTeamScore(team)->m_tickets; ++i) + { + } + return result.str(); } // Registers the module courier interface for access through the singleton registry. diff --git a/Code/BF2/AI/AIInterface/Module/BFConsole.h b/Code/BF2/AI/AIInterface/Module/BFConsole.h index cb86ab276..daa07a74d 100644 --- a/Code/BF2/AI/AIInterface/Module/BFConsole.h +++ b/Code/BF2/AI/AIInterface/Module/BFConsole.h @@ -18,7 +18,7 @@ std::list& kitTemplateConsoleObjects(); class AIEventListener; // Radio-message values are four-byte integers; the constructor maps names to values -// 0..4 and 6..17. [FRONTIER] Enumerator names are unknown, so the enum remains opaque. +// 0..4 and 6..17. [UNRESOLVED] Enumerator names are unknown, so the enum remains opaque. enum AIRadioMessageType : int; // Settings for an AI radio message; preserve the field order used by the courier. @@ -36,15 +36,15 @@ class BFConsole BFConsole(); ~BFConsole(); - void createSingletons(); // [FRONTIER] - void clearSingletons(); // [FRONTIER] | - void aiMainInit(); // [FRONTIER] - void reset(); // [FRONTIER] + void createSingletons(); + void clearSingletons(); + void aiMainInit(); + void reset(); void addAIRadioMessage(const std::string& name, float a, float b, float c); - // [FRONTIER] - bool getAIMessageSettings(int, AIRadioMessageSettings&); // [FRONTIER] - bool getVoiceFromAiMessageType(AIRadioMessageType, int&); // [FRONTIER] - void code(const std::string&); // [FRONTIER] + bool getAIMessageSettings(int, AIRadioMessageSettings&); + bool getVoiceFromAiMessageType(AIRadioMessageType, int&); + // Emits the retail error diagnostic, then processes a legacy single-player code. + std::string code(const std::string& command); // Always returns null. static void* getSinglePlayerInstance(); diff --git a/Code/BF2/AI/AIInterface/SingletonServer.h b/Code/BF2/AI/AIInterface/SingletonServer.h index 4eb40ae2b..d537e85ec 100644 --- a/Code/BF2/AI/AIInterface/SingletonServer.h +++ b/Code/BF2/AI/AIInterface/SingletonServer.h @@ -14,6 +14,7 @@ class IAIEventCourier; class ISingletonServerUpdater { public: + ISingletonServerUpdater(); virtual ~ISingletonServerUpdater(); virtual void update() = 0; }; diff --git a/Code/BF2/Animation/BoneAnimation/BoneAnimation.cpp b/Code/BF2/Animation/BoneAnimation/BoneAnimation.cpp index e20269fbb..932f7e13b 100644 --- a/Code/BF2/Animation/BoneAnimation/BoneAnimation.cpp +++ b/Code/BF2/Animation/BoneAnimation/BoneAnimation.cpp @@ -14,6 +14,7 @@ #include // rand - getValue's root-bone jitter #include "../../Math/Quat.h" // Quat::slerp #include "../../Math/Vec3.h" +#include "../../Platform/MsvcRand.h" // [CHOSEN, not recovered] the client CRT's rand (MSVCR71) namespace dice { @@ -325,12 +326,12 @@ void BoneAnimation::getValue(int bone, float time, hfe::Quat& rotation, hfe::Vec position.z = ta.z; } - if (bone == 0 && m_jitterChance != 0 && rand() % 10 < m_jitterChance) + if (bone == 0 && m_jitterChance != 0 && bf2crt::rand() % 10 < m_jitterChance) { const float amplitudeX = jitter * m_jitterAmplitude; - position.x = amplitudeX * static_cast(rand() % 256 - 128) * 0.00390625f + position.x; + position.x = amplitudeX * static_cast(bf2crt::rand() % 256 - 128) * 0.00390625f + position.x; const float amplitudeY = jitter * m_jitterAmplitude; - position.y = 0.00390625f * (static_cast(rand() % 256 - 128) * amplitudeY) + position.y; + position.y = 0.00390625f * (static_cast(bf2crt::rand() % 256 - 128) * amplitudeY) + position.y; } } diff --git a/Code/BF2/Animation/BoneAnimation/ModuleBoneAnimation.cpp b/Code/BF2/Animation/BoneAnimation/ModuleBoneAnimation.cpp index e168f3619..c06edab1e 100644 --- a/Code/BF2/Animation/BoneAnimation/ModuleBoneAnimation.cpp +++ b/Code/BF2/Animation/BoneAnimation/ModuleBoneAnimation.cpp @@ -456,14 +456,7 @@ namespace { inline anim::RagDollTemplate* ragDollTemplate() { return anim::g_ragDollTemplate; } void rdReset() { ragDollTemplate()->m_resetRequested = true; } // cc96: +0x02 = 1 -// Constraint serialization remains a named stop. [TEMP] [CHOSEN, not recovered] -// [RETIRE-WHEN: ragdoll-write-constraints] -void rdSave() -{ - std::fprintf(stderr, "[FRONTIER] dice::anim::RagDollTemplate::writeConstraints reached\n"); - std::fflush(stderr); - std::abort(); -} +void rdSave() { ragDollTemplate()->writeConstraints(); } // cc97: ELF 0x8822215 void rdActive(bool v) { ragDollTemplate()->m_active = v; } // cc98: +0x01 void rdDrawConstraints(bool v) { ragDollTemplate()->m_drawConstraints = v; } // cc99: +0x00 void rdGravity(float v) { ragDollTemplate()->m_gravity = v; } // cc100: +0x04 diff --git a/Code/BF2/Animation/BoneAnimation/RagDoll.cpp b/Code/BF2/Animation/BoneAnimation/RagDoll.cpp index 53b536a51..4932175e3 100644 --- a/Code/BF2/Animation/BoneAnimation/RagDoll.cpp +++ b/Code/BF2/Animation/BoneAnimation/RagDoll.cpp @@ -6,8 +6,10 @@ #include // FLT_EPSILON - the inlined Vec3::normalize guard #include // sqrtf / fabsf -#include // fprintf / fflush - the two [FRONTIER] stops +#include #include // abort +#include +#include #include #include "../../Core/Ids.h" // CID_TriggerableTargetTemplate @@ -25,6 +27,8 @@ #include "../../Math/LocalBoundingBox.h" #include "../../IO/BitStream.h" #include "../../Core/IBase.h" +#include "../../Core/SmartItf.h" // classManager - the DebugRenderer singleton +#include "../../Core/ClassManager.h" namespace dice { @@ -763,21 +767,161 @@ void RagDoll::checkDistanceLessThanConstraints() } -// Client debug line/constraint drawing remains a named stop; dedicated servers do not draw constraints. -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: ragdoll-debug-draw] +// Constraint debug drawing: each segment is the renderer's debug cylinder (CID 81016) stretched +// between its two points, 0.002 thick, coloured through the mesh's IID 80007 interface. +namespace { + +// "DebugRenderer" (geom::IDebugRenderer, GeomMisc/DebugRenderer.h): the slots used here, in table +// order. Declared locally, as AI's DebugRenderer.cpp does for its writer. +class IDebugGeometryQueue : public hfe::IBase +{ +public: + virtual void flush() = 0; // +0x10 + virtual void queueGeometry(unsigned int classId, const hfe::Mat4& transform, + const std::string& technique) = 0; // +0x14 + virtual hfe::IBase* acquireGeometry(unsigned int classId) = 0; // +0x18 + +protected: + ~IDebugGeometryQueue() {} +}; + +// The debug mesh's table up to its colour setter: entry 62 (+0xF8) of the DebugCylinderMesh table +// (RendDX9 PE 0x1020BD00, GeomMisc/DebugCylinderMesh.cpp). The entries before it are not called. +class IDebugMeshColour : public hfe::IBase +{ +public: + virtual void unused10() = 0; + virtual void unused14() = 0; + virtual void unused18() = 0; + virtual void unused1C() = 0; + virtual void unused20() = 0; + virtual void unused24() = 0; + virtual void unused28() = 0; + virtual void unused2C() = 0; + virtual void unused30() = 0; + virtual void unused34() = 0; + virtual void unused38() = 0; + virtual void unused3C() = 0; + virtual void unused40() = 0; + virtual void unused44() = 0; + virtual void unused48() = 0; + virtual void unused4C() = 0; + virtual void unused50() = 0; + virtual void unused54() = 0; + virtual void unused58() = 0; + virtual void unused5C() = 0; + virtual void unused60() = 0; + virtual void unused64() = 0; + virtual void unused68() = 0; + virtual void unused6C() = 0; + virtual void unused70() = 0; + virtual void unused74() = 0; + virtual void unused78() = 0; + virtual void unused7C() = 0; + virtual void unused80() = 0; + virtual void unused84() = 0; + virtual void unused88() = 0; + virtual void unused8C() = 0; + virtual void unused90() = 0; + virtual void unused94() = 0; + virtual void unused98() = 0; + virtual void unused9C() = 0; + virtual void unusedA0() = 0; + virtual void unusedA4() = 0; + virtual void unusedA8() = 0; + virtual void unusedAC() = 0; + virtual void unusedB0() = 0; + virtual void unusedB4() = 0; + virtual void unusedB8() = 0; + virtual void unusedBC() = 0; + virtual void unusedC0() = 0; + virtual void unusedC4() = 0; + virtual void unusedC8() = 0; + virtual void unusedCC() = 0; + virtual void unusedD0() = 0; + virtual void unusedD4() = 0; + virtual void unusedD8() = 0; + virtual void unusedDC() = 0; + virtual void unusedE0() = 0; + virtual void unusedE4() = 0; + virtual void unusedE8() = 0; + virtual void unusedEC() = 0; + virtual void unusedF0() = 0; + virtual void unusedF4() = 0; + virtual void setColour(const hfe::Vec4& colour) = 0; // +0xF8 + +protected: + ~IDebugMeshColour() {} +}; + +const unsigned int kDebugCylinderMesh = 81016u; // CID_DebugCylinderMesh (BF2.exe ds:0x94F660) +const unsigned int kIDebugCylinderMesh = 80007u; // IID_IDebugCylinderMesh (BF2.exe ds:0x94F5D0) + +IDebugGeometryQueue* debugRenderer() +{ + return static_cast(hfe::classManager->getSingleton(std::string("DebugRenderer"))); +} + +// The shared segment body (BF2.exe 0x7E71B0..0x7E7450, ELF 0x8343F40): scale(0.002, 0.002, |d|) +// times the orthonormal basis built from d, translated to the midpoint, queued and coloured. The +// renderer and the acquired geometry are used unchecked; only the colour interface is tested. +void queueSegment(IDebugGeometryQueue* renderer, const hfe::Vec3& from, const hfe::Vec3& to, + const hfe::Vec4& colour) +{ + hfe::Vec3 d; + d.x = to.x - from.x; + d.y = to.y - from.y; + d.z = to.z - from.z; + + hfe::Mat4 transform = hfe::Mat4::getIdentity(); + hfe::Vec3 thickness; + thickness.x = 0.002f; + thickness.y = 0.002f; + thickness.z = std::sqrt(d.z * d.z + d.y * d.y + d.x * d.x); + transform.scale(thickness); + + // Rows: x (1,0,0), y (0,1,0), z = d; y.makeOrthonormalBasis(z, x), as the call is made. + hfe::Vec3 right; right.x = 1.0f; right.y = 0.0f; right.z = 0.0f; + hfe::Vec3 up; up.x = 0.0f; up.y = 1.0f; up.z = 0.0f; + hfe::Vec3 forward = d; + up.makeOrthonormalBasis(forward, right); + hfe::Mat4 basis = hfe::Mat4::getIdentity(); + basis.m[0] = right.x; basis.m[1] = right.y; basis.m[2] = right.z; + basis.m[4] = up.x; basis.m[5] = up.y; basis.m[6] = up.z; + basis.m[8] = forward.x; basis.m[9] = forward.y; basis.m[10] = forward.z; + basis.m[12] = d.x * 0.5f + from.x; + basis.m[13] = d.y * 0.5f + from.y; + basis.m[14] = d.z * 0.5f + from.z; + + const hfe::Mat4 scaled = transform; + transform.mult(scaled, basis); + + renderer->queueGeometry(kDebugCylinderMesh, transform, std::string("")); + hfe::IBase* geometry = renderer->acquireGeometry(kDebugCylinderMesh); + IDebugMeshColour* mesh = static_cast(geometry->queryInterface(kIDebugCylinderMesh)); + if (mesh) + mesh->setColour(colour); +} + +} // namespace -void RagDoll::drawDebugLine(const Vec3& /*from*/, const Vec3& /*to*/, const hfe::Vec4& /*colour*/) +// ELF 0x8343F40. No caller in the ELF, and BF2.exe has no copy (the linker dropped it); kept as the +// ELF has it. +void RagDoll::drawDebugLine(const Vec3& from, const Vec3& to, const hfe::Vec4& colour) { - std::fprintf(stderr, "[FRONTIER] dice::anim::RagDoll::drawDebugLine reached\n"); - std::fflush(stderr); - std::abort(); + queueSegment(debugRenderer(), from, to, colour); } +// BF2.exe 0x7E7160 (ELF 0x83458D0): every distance constraint as a red segment between its two +// particles. The renderer is looked up once, before the loop. void RagDoll::drawConstraints() { - std::fprintf(stderr, "[FRONTIER] dice::anim::RagDoll::drawConstraints reached\n"); - std::fflush(stderr); - std::abort(); + IDebugGeometryQueue* renderer = debugRenderer(); + hfe::Vec4 red; + red.x = 1.0f; red.y = 0.0f; red.z = 0.0f; red.w = 1.0f; + for (std::list::iterator it = m_template->m_distanceConstraints.begin(); + it != m_template->m_distanceConstraints.end(); ++it) + queueSegment(renderer, m_particles[it->m_a].m_position, m_particles[it->m_b].m_position, red); } diff --git a/Code/BF2/Animation/BoneAnimation/RagDollTemplate.cpp b/Code/BF2/Animation/BoneAnimation/RagDollTemplate.cpp index f1eefeb85..363f47362 100644 --- a/Code/BF2/Animation/BoneAnimation/RagDollTemplate.cpp +++ b/Code/BF2/Animation/BoneAnimation/RagDollTemplate.cpp @@ -9,6 +9,7 @@ #include "../../Game/Utility/Vars.h" // dice::hfe::Vars::getFloat - the cvar handle pattern #include "RagDoll.h" // the instance half of the same ELF TU #include "Skeleton.h" // the owned reference skeleton: skeleton(), getBoneDistance +#include "../../IO/File/File.h" // io::File - writeConstraints #include // FLT_EPSILON #include // sqrtf, fabsf @@ -16,6 +17,7 @@ #include // abort #include #include +#include #include #include #include @@ -47,6 +49,12 @@ inline unsigned long long rdtsc() { #if defined(_WIN32) return __rdtsc(); +#elif defined(__aarch64__) + // [CHOSEN, not recovered] arm64 macOS port (untested): the generic timer's virtual count is + // the constant-rate counter that stands in for the TSC; callers calibrate its frequency. + unsigned long long count; + __asm__ __volatile__("mrs %0, cntvct_el0" : "=r"(count)); + return count; #else unsigned int lo, hi; __asm__ __volatile__("rdtsc" : "=a"(lo), "=d"(hi)); @@ -504,6 +512,33 @@ void RagDollTemplate::removeConstraint(int a, int b) m_distanceConstraints.erase(it); } +// The console `ragDoll.save` tool (ELF 0x8341110): one "ragDoll.addConstraint " +// line per distance constraint, written through io::File to ragDollConstraints.inc (mode 0, +// access 2, as SettingsManagerBase::save opens its files). The particle indices map back to bone +// ids; the getBoneDistance result is computed and discarded, as shipped. +void RagDollTemplate::writeConstraints() +{ + // Retail writes the relative name, which lands in the game folder; the macOS client does the + // same (docs/macos-write-paths.md). + const char* const path = "ragDollConstraints.inc"; + hfe::io::File file; + file.open(path, static_cast(0), hfe::io::IFileSystem::FILEACCESS_2, 0); + hfe::io::IStream* stream = file.getStream(); + std::ostringstream text; + for (std::list::iterator it = m_distanceConstraints.begin(); + it != m_distanceConstraints.end(); ++it) + { + const int boneA = findBoneIndex(it->m_a); + const int boneB = findBoneIndex(it->m_b); + (void)getBoneDistance(boneA, boneB); + text << "ragDoll.addConstraint " << boneA << " " << boneB << " " + << static_cast(it->m_length) << std::endl; + } + const std::string out = text.str(); + stream->write(out.data(), static_cast(out.length())); + file.close(); +} + // Loads the reference skeleton once; a failed load deletes it again. void RagDollTemplate::skeleton(const std::string& name) { diff --git a/Code/BF2/Animation/BoneAnimation/RagDollTemplate.h b/Code/BF2/Animation/BoneAnimation/RagDollTemplate.h index ba3e678d2..3dad5e587 100644 --- a/Code/BF2/Animation/BoneAnimation/RagDollTemplate.h +++ b/Code/BF2/Animation/BoneAnimation/RagDollTemplate.h @@ -87,8 +87,8 @@ class RagDollTemplate void addCapsuleCollision(int a, int b); void addJointConstraint(int a, int b); void removeConstraint(int a, int b); - // writes the constraint set back out as .con text (the console - // `ragDoll.writeConstraints` tool). Editor tooling; declaration only. [FRONTIER] + // Writes the distance constraints to ragDollConstraints.inc as ragDoll.addConstraint lines + // (the console `ragDoll.save` tool, ELF 0x8341110). void writeConstraints(); void skeleton(const std::string& name); void setParticleCollisionCriteria(float minImpact, float debounce); diff --git a/Code/BF2/Animation/BoneAnimation/Trigger.cpp b/Code/BF2/Animation/BoneAnimation/Trigger.cpp index 331a6a61b..47a89a97b 100644 --- a/Code/BF2/Animation/BoneAnimation/Trigger.cpp +++ b/Code/BF2/Animation/BoneAnimation/Trigger.cpp @@ -12,6 +12,7 @@ #include // rand - Random / Idle triggers #include #include "../../IO/Stream/IStream.h" +#include "../../Platform/MsvcRand.h" // [CHOSEN, not recovered] the client CRT's rand (MSVCR71) namespace dice { namespace anim { @@ -267,7 +268,7 @@ void RandomTrigger::applyAnimations(AnimationSystem& system) { if (m_bundles.empty()) return; - const unsigned int pick = static_cast(rand()) % static_cast(m_bundles.size()); + const unsigned int pick = static_cast(bf2crt::rand()) % static_cast(m_bundles.size()); system.playBundle(this, m_bundles[pick], m_prio, -1.0f, 1.0f); } @@ -283,12 +284,12 @@ bool IdleTrigger::update(AnimationSystem& system) if (m_nextIdleTime > system.getIdleTime() || system.getIdleTime() > m_idleTimeMax) return true; - m_nextIdleTime = static_cast(rand() % 100) / 100.0f * (m_idleTimeMax - m_idleTimeMin) + m_nextIdleTime = static_cast(bf2crt::rand() % 100) / 100.0f * (m_idleTimeMax - m_idleTimeMin) + m_idleTimeMin; if (!m_bundles.empty()) { const unsigned int pick = - static_cast(rand()) % static_cast(m_bundles.size()); + static_cast(bf2crt::rand()) % static_cast(m_bundles.size()); system.playBundle(this, m_bundles[pick], m_prio, -1.0f, 1.0f); } return Trigger::update(system); diff --git a/Code/BF2/Core/ClassFactoryInstantiations.cpp b/Code/BF2/Core/ClassFactoryInstantiations.cpp index 300138765..887c42f8e 100644 --- a/Code/BF2/Core/ClassFactoryInstantiations.cpp +++ b/Code/BF2/Core/ClassFactoryInstantiations.cpp @@ -159,4 +159,3 @@ template struct dice::hfe::world::ClassFactory; template struct dice::hfe::world::ClassFactory; template struct dice::hfe::world::ClassFactory; -template struct dice::hfe::world::ClassFactory; diff --git a/Code/BF2/Core/ConsoleObjectBase.cpp b/Code/BF2/Core/ConsoleObjectBase.cpp index a9df93be6..d3868e8ed 100644 --- a/Code/BF2/Core/ConsoleObjectBase.cpp +++ b/Code/BF2/Core/ConsoleObjectBase.cpp @@ -1,6 +1,9 @@ // Path: [INFERRED] - see ConsoleObjectBase.h header block. // Contents: recovered from bf2.i64 (ELF, symbolised), 0x83be630 - 0x83beab6. +// static init: ELF 0x4863B0 (__tcf_0 0x486410, _GLOBAL__I 0x486440): 's Init object only. +#include + #include "ConsoleObjectBase.h" #include "ConsoleObjectMacro.h" // consoleBindingList / the three default accessors #include @@ -13,6 +16,9 @@ namespace hfe { // Converts typed arguments or stores raw string pointers, executes the binding and formats its result. // setArgFromString uses one-based indices; argument storage belongs to the generated binding. +// ELF 0x486320; engine 0x83BE630. Slots +0x68, +0x7C, +0x60, +0x64 are attested in both images. +// RendDX9.dll copy PE 0x1007BFD0 (`retn 0Ch`, hidden result first; the MSVC table's slots +0x64, +// +0x78, +0x5C, +0x60). The trace block below is the [TEMP] harness, not part of the copy. std::string ConsoleObjectBaseImpl::execute(std::string* args, int argCount) { // [TEMP] [CHOSEN, not recovered] BF2_TRACE_CONSOLE logs each invoked binding. @@ -87,21 +93,26 @@ bool ConsoleObjectBaseImpl::isDynamic() const { return m_isDynami // -> +0x50 + index*4. no bounds check in the original - the array is ten wide and the caller is // trusted to stay inside it. execute() iterates its supplied count without clamping; // ordinary console callers perform the command's arity check before dispatch. +// PE 0x10051D60 (the RendDX9.dll copy: mov eax, [ecx + 4*eax + 0x50]; retn 4). const char* ConsoleObjectBaseImpl::getArgType(int index) const { return m_argTypes[index]; } // Range access forwards to the generated object's virtual hooks. // Range endpoints are pointers to mutable members. Preserve hook slot order without swapping the forwarder targets. bool ConsoleObjectBaseImpl::hasRange() const { return objectHasRange(); } +// PE 0x10051DB0 (RendDX9.dll copy: tail call through vtable +0x6C, the result slot passed straight through). std::pair ConsoleObjectBaseImpl::getRange() const { return getObjectRange(); } +// PE 0x10051E80 (RendDX9.dll copy: forwards through vtable +0x74). std::pair ConsoleObjectBaseImpl::getRangeAsString() const { return getObjectRangeAsString(); // sret passed straight through } +// PE 0x10051DD0 (RendDX9.dll copy: forwards through vtable +0x70). std::string ConsoleObjectBaseImpl::getDeltaAsString() const { return getObjectDeltaAsString(); } bool ConsoleObjectBaseImpl::hasBundledType() const { return objectHasBundledType(); } +// PE 0x10051E20 (RendDX9.dll copy: forwards through vtable +0x80). std::string ConsoleObjectBaseImpl::getTypeDescription() const { return getObjectTypeDescription(); } // The eight object-level hooks. Stubs here by design - this is the half the macro overrides, and @@ -112,17 +123,23 @@ void ConsoleObjectBaseImpl::executeObjectMethod() { } std::string ConsoleObjectBaseImpl::getReturnValueAsString() const { return std::string(); } void ConsoleObjectBaseImpl::setArgFromString(int, const std::string&) { } // empty, 5 bytes bool ConsoleObjectBaseImpl::objectHasRange() const { return false; } +// PE 0x100525C0 (RendDX9.dll copy, the vtable +0x6C default of the renderer bindings: stores two zero words +// through its result pointer; retn 4). std::pair ConsoleObjectBaseImpl::getObjectRange() const { return std::pair(0, 0); // zeroes the two pointer out-fields } -std::string ConsoleObjectBaseImpl::getObjectDeltaAsString() const { return std::string(); } +// PE 0x10051E40 (RendDX9.dll copy), BF2.exe 0x410C61 and ELF 0x83BE930 (ConsoleObjectBaseImpl::getObjectDeltaAsString): +// every image's default builds the literal "No Delta" (BF2.exe .rdata 0x881164, ELF .rodata 0x88D0C70); 2703 BF2.exe +// binding vtables point at 0x410C61. The earlier empty-string default was a reconstruction error. +std::string ConsoleObjectBaseImpl::getObjectDeltaAsString() const { return std::string("No Delta"); } std::pair ConsoleObjectBaseImpl::getObjectRangeAsString() const { return std::pair(); // two empty strings into the sret } void ConsoleObjectBaseImpl::checkObjectRange(bool) { } bool ConsoleObjectBaseImpl::objectHasBundledType() const { return false; } +// PE 0x10051E60 (RendDX9.dll copy, vtable +0x80 default: constructs an empty string). std::string ConsoleObjectBaseImpl::getObjectTypeDescription() const { return std::string(); } ConsoleObjectBaseImpl::~ConsoleObjectBaseImpl() { } @@ -132,6 +149,8 @@ ConsoleObject::~ConsoleObject() { } // Defaults for subsequent generated bindings: object name, access and category. // Only the first character of the copied name is lowercased; names must fit the 32-byte allocation. +// The RendDX9 image defines its own copy (Code/RendDX9Abi/NativeConsoleObjects.cpp, PE 0x1007BF60). +#if !defined(BF2_IMAGE_RENDDX9) namespace { const char* g_defaultNameLower = ""; unsigned int g_defaultAccess = 0; @@ -157,6 +176,7 @@ SetConsoleClassDefaults::SetConsoleClassDefaults(const char* objectName, unsigne g_defaultAccess = access; g_defaultCategory = category; } +#endif // !BF2_IMAGE_RENDDX9 // One list per translation-unit tag. Function-local static: the generated constructors run during // static initialisation and this must already exist when the first of them fires. diff --git a/Code/BF2/Core/ConsoleObjectMacro.h b/Code/BF2/Core/ConsoleObjectMacro.h index 0e12bd465..adf77d1bf 100644 --- a/Code/BF2/Core/ConsoleObjectMacro.h +++ b/Code/BF2/Core/ConsoleObjectMacro.h @@ -8,6 +8,7 @@ #include "ConsoleObjects.h" #include #include +#include #include #include @@ -27,6 +28,60 @@ const char* consoleDefaultName(); unsigned int consoleDefaultAccess(); unsigned char consoleDefaultCategory(); +#if defined(BF2_IMAGE_RENDDX9) +// The defaults' object name as passed, before the first character is lowercased (RendDX9 PE +// 0x10247C20; ELF ConsoleObject::mDefaultStaticObjectName). Four RendDX9 binding constructors +// read it. Defined by the RendDX9 image's copy in Code/RendDX9Abi/NativeConsoleObjects.cpp. +const char* consoleDefaultStaticName(); +#endif + +// Where BF2_CC_CONVERT extracts one console argument: its persistent per-type static. Every image extracts straight +// into the static with no stream-state test: RendDX9.dll PE 0x10054B20 (bool), BF2.exe PE 0x00411DD1 +// (bool) and PE 0x00411CEC (float), Linux bf2 ELF 0x08822DE0 (std::string) and ELF 0x087609E0 (int). +// Their libraries (MSVCP71, GCC 3.x libstdc++) leave a scalar target unchanged when the read fails or +// is out of range; C++11 libraries store 0 or the range limit there instead. [PLATFORM] Scalars are +// therefore read through a local that starts as the stored value and stored only when the read +// succeeds, which gives the retail result on every library. Every other type (std::string, the Vec +// types, the template proxies) is extracted in place, partial component writes included, as retail. +template::value> +struct ConsoleArgumentSlot +{ + explicit ConsoleArgumentSlot(T& stored) : m_target(stored) {} + T& target() { return m_target; } + void commit(bool) {} + + T& m_target; +}; + +template +struct ConsoleArgumentSlot +{ + explicit ConsoleArgumentSlot(T& stored) : m_stored(stored), m_value(stored) {} + T& target() { return m_value; } + void commit(bool succeeded) { if (succeeded) m_stored = m_value; } + + T& m_stored; + T m_value; +}; + +#if defined(_WIN32) && !DEDICATED && defined(_MSC_VER) && _MSC_VER > 1310 +// [PLATFORM] [CHOSEN, not recovered] The shipped client calls MSVCP71's operator>>(float&) +// (BF2.exe imports ...QAEAAV01@AAM@Z, not the double overload), which parses through a double +// before narrowing. A modern CRT's direct float extraction can change near-midpoint values and +// reject values that only exceed the float range, so newer toolchains read a double here. The +// VC7.1 matching build keeps the retail float extraction. Preserve failed reads. +template<> +struct ConsoleArgumentSlot +{ + explicit ConsoleArgumentSlot(float& stored) : m_stored(stored), m_value(stored) {} + double& target() { return m_value; } + void commit(bool succeeded) { if (succeeded) m_stored = static_cast(m_value); } + + float& m_stored; + double m_value; +}; +#endif + // Token paste with __LINE__ needs two levels, or you paste the literal text #define BF2_CC_CAT2(a, b) a##b #define BF2_CC_CAT(a, b) BF2_CC_CAT2(a, b) @@ -38,18 +93,17 @@ unsigned char consoleDefaultCategory(); static ::dice::hfe::SetConsoleClassDefaults \ BF2_CC_CAT(s_consoleDefaults, __LINE__)((objectName), (accessLevel), (categoryId)); -// Converts one-based arguments into persistent per-type storage. -// Extract into a temporary and commit only on success so malformed input preserves the previous value. -// String extraction takes one token; normal string arguments bypass this through execute's raw branch. +// Converts one-based arguments into persistent per-type storage, extracting straight into it (see +// ConsoleArgumentSlot). String extraction takes one token; normal string arguments bypass +// this through execute's raw branch. #define BF2_CC_CONVERT(T, oneBasedIndex) \ if (index == (oneBasedIndex)) \ { \ static T s; \ - T tmp = s; \ std::istringstream in(value); \ - in >> tmp; \ - if (!in.fail()) \ - s = tmp; \ + ::dice::hfe::ConsoleArgumentSlot slot(s); \ + in >> slot.target(); \ + slot.commit(!in.fail()); \ m_args[(oneBasedIndex) - 1] = reinterpret_cast(&s); \ } diff --git a/Code/BF2/Core/ConsoleObjects.cpp b/Code/BF2/Core/ConsoleObjects.cpp index 904eb9b63..b89bf2e3e 100644 --- a/Code/BF2/Core/ConsoleObjects.cpp +++ b/Code/BF2/Core/ConsoleObjects.cpp @@ -1,5 +1,8 @@ // Console binding registration and lookup. [INFERRED] Source placement. +// static init: ELF 0x4872D0 (__tcf_0 0x487330, _GLOBAL__I 0x487360): 's Init object only. +#include + #include "ConsoleObjects.h" #include // strncasecmp / _strnicmp - see prefixMatchesNoCase below @@ -29,6 +32,9 @@ inline std::string registryKey(const ConsoleObject* object) } // anonymous namespace // Default-constructs the lookup hash, binding map and registration-order list. +// RendDX9.dll copy PE 0x1007B7E0, unreached there (no code or data reference): Hash (stack functor +// byte, 3011 = 0xBC3 buckets) via 0x1007B840, the multimap head (0x1007BAF0; nil byte +0x2D set, +// links to itself, size 0), the list head (0x1007B890, size 0), in member order. ConsoleObjects::ConsoleObjects() { } @@ -79,6 +85,8 @@ const ConsoleObjects::ConsoleObjectList& ConsoleObjects::getConsoleObjects() con // Returns the first active binding in the key's equal range, or null. // Inactive bindings stay registered and allow later duplicates to match. +// RendDX9.dll copy PE 0x1007B320 (lower_bound 0x101C0A60, upper_bound 0x1007BA80, vslot +0x2C per +// entry); unreached there (only its dead caller 0x1007B3B0 refers to it). ConsoleObject* ConsoleObjects::findInMultiMap(const std::string& key) { std::multimap::iterator it = @@ -99,6 +107,8 @@ ConsoleObject* ConsoleObjects::findInMultiMap(const std::string& key) // Resolves a console binding by exact name, then case-insensitive get/set prefixes. // The fallback accepts property types 1/3 for get and 1/2 for set. This differs from the command // dispatcher's read/write polarity; preserve those constants until both call paths justify a change. +// RendDX9.dll copy PE 0x1007B3B0 (`retn 8`; _strnicmp, substr(3, size - 3), vslot +0x10 getType), +// unreached there (no code or data reference). ConsoleObject* ConsoleObjects::getConsoleObject(const std::string& objectName, const std::string& methodName) { @@ -130,15 +140,11 @@ ConsoleObject* ConsoleObjects::getConsoleObject(const std::string& objectName, } // Registers a case-insensitive conversion key. Returns false for an existing key without replacing it. +// RendDX9.dll copy: the wrapper PE 0x1007B310 tail-jumps to the Hash member (Hash::insertUnique, +// cited in Core/Hash.h). Unreached in RendDX9 (no code or data reference). bool ConsoleObjects::registerTypeConversion(const std::string& from, const std::string& to) { - const unsigned int bucket = m_typeConversions.bucketOf(from); - - if (m_typeConversions.exists(from, bucket)) - return false; - - m_typeConversions.insert(from, to, bucket); - return true; + return m_typeConversions.insertUnique(from, to); } // typeAsString - @@ -146,6 +152,7 @@ bool ConsoleObjects::registerTypeConversion(const std::string& from, const std:: // A lookup with the key as its own default: an unregistered type name is returned unchanged. The // leading `_InterlockedAdd(&_S_empty_rep_storage.refcount, 1)` in the decompilation is libstdc++ // constructing an empty std::string, i.e. compiler scaffolding, not a member being touched. +// RendDX9.dll copy PE 0x1007B2C0 over the Hash::get copy PE 0x1007BA20; unreached there. std::string ConsoleObjects::typeAsString(const std::string& type) const { std::string converted; diff --git a/Code/BF2/Core/Debug.cpp b/Code/BF2/Core/Debug.cpp index ad0f67080..9a06a0d99 100644 --- a/Code/BF2/Core/Debug.cpp +++ b/Code/BF2/Core/Debug.cpp @@ -88,6 +88,8 @@ Debug::~Debug() } // No bounds check, no locking. +// RendDX9.dll copy PE 0x10074340 (type/callback in ECX/EDX, data on the stack; unreachable in 1.50: +// no code or data references). void setDebugCallback(DebugType type, DebugCallback callback, void* data) { bfGlobal_callback[type] = callback; @@ -96,6 +98,7 @@ void setDebugCallback(DebugType type, DebugCallback callback, void* data) // (the clear() is inlined here and called out of line in turnOffAllDebug - // compiler variance, same source). plain `int` parameter, attested by the mangling. +// RendDX9.dll copy PE 0x10074850 (clear() as a tail jump to the Hash clear). void turnOnAllDebug(int type) { debugOn[type] = true; @@ -103,6 +106,7 @@ void turnOnAllDebug(int type) } +// RendDX9.dll copy PE 0x10074870. void turnOffAllDebug(int type) { debugOn[type] = false; @@ -111,6 +115,9 @@ void turnOffAllDebug(int type) // Enables debugging for module. The exception list is an exclusion list when the type is on // and an inclusion list when it is off; insertion avoids duplicate entries. +// RendDX9.dll copy PE 0x10074890 (fastcall type/module). Its exists-then-insert is one out-of-line +// Hash member there, PE 0x10074940: bucket, exists(), then a node with the key and an empty value +// pushed on the chain, answering whether it inserted; the same operations as below. void turnOnDebug(int type, const std::string& module) { if (debugOn[type]) @@ -119,7 +126,7 @@ void turnOnDebug(int type, const std::string& module) debugModules[type].insert(module, std::string()); } -// Exact mirror, same caller-side guard. +// Exact mirror, same caller-side guard. RendDX9.dll copy PE 0x100748C0. void turnOffDebug(int type, const std::string& module) { if (!debugOn[type]) diff --git a/Code/BF2/Core/DllStlAllocator.cpp b/Code/BF2/Core/DllStlAllocator.cpp new file mode 100644 index 000000000..f32372c11 --- /dev/null +++ b/Code/BF2/Core/DllStlAllocator.cpp @@ -0,0 +1,22 @@ +// DllStlAllocator.cpp is an original ELF FILE symbol. Function placement [INFERRED] +// from its position between DllModule.cpp and Random.cpp. +#include "DllStlAllocator.h" + +namespace dice { +namespace hfe { + +// ELF 0x48A7F0; engine 0x83C3420. +void* HeapAlloc(unsigned long size) +{ + return new char[size]; +} + +// ELF 0x48A820; engine 0x83C3430. +void HeapFree(void* storage) +{ + if (storage) + delete[] static_cast(storage); +} + +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/Core/DllStlAllocator.h b/Code/BF2/Core/DllStlAllocator.h new file mode 100644 index 000000000..3fe3bf060 --- /dev/null +++ b/Code/BF2/Core/DllStlAllocator.h @@ -0,0 +1,16 @@ +// Allocation pair shared by the engine and side DLLs. Header placement [INFERRED]. +#ifndef CORE_DLLSTLALLOCATOR_H +#define CORE_DLLSTLALLOCATOR_H + +namespace dice { +namespace hfe { + +// Allocates uninitialized array storage; allocation failure follows operator new[]. +void* HeapAlloc(unsigned long size); +// Releases storage from HeapAlloc; a null pointer has no effect. +void HeapFree(void* storage); + +} // namespace hfe +} // namespace dice + +#endif diff --git a/Code/BF2/Core/Globals.cpp b/Code/BF2/Core/Globals.cpp index 2da7cb944..c867bb428 100644 --- a/Code/BF2/Core/Globals.cpp +++ b/Code/BF2/Core/Globals.cpp @@ -111,8 +111,8 @@ namespace ai { IBase* g_aiConnection = 0; // ds:0x8B29AE0 _ZN4dice3hfe2ai14g_aiConnectionE // [CHOSEN] AI-instance singleton name. Its bots-game query controls whether loading includes .ai files. IBase* g_aiInstance = 0; // ds:0x8AC37F8 [CHOSEN name] -// [CHOSEN] AI collision-handler singleton name. Null without an AI DLL; consumers report damage and firing here. -IBase* g_bfCollisionHandler = 0; // ds:0x8AC35E4 [CHOSEN name] +// ds:0x8AC35E4 is CommonSingletonServer::m_iBFCollisionHandler (AIDLL/AI/Main), not a separate +// global: the engine's fire, timeout, collision, explosion and damage reports read it there. } namespace world { diff --git a/Code/BF2/Core/Hash.h b/Code/BF2/Core/Hash.h index 4b1acf4dd..74f3a15db 100644 --- a/Code/BF2/Core/Hash.h +++ b/Code/BF2/Core/Hash.h @@ -71,6 +71,8 @@ class Hash }; // Constructs maxSize buckets and explicitly zeroes them. + // RendDX9.dll copy PE 0x1007B840 (`retn 8`: functor reference, maxSize; it stores the functor + // address at +0x08, which this rebuild keeps null). // The default 3011 is [CHOSEN, not recovered] syntax for the observed standard bucket count. explicit Hash(unsigned int maxSize = 3011) { @@ -92,6 +94,7 @@ class Hash } // Returns whether key exists in the specified bucket. The caller must supply a valid reduced bucket index. + // RendDX9.dll copy (StringHashFunc) PE 0x100748F0. bool exists(const K& key, unsigned int bucket) const { for (Node* n = m_buckets[bucket]; n != 0; n = n->next) @@ -114,6 +117,7 @@ class Hash } // Copies the matching value to value and returns true. A miss leaves value unchanged and returns false. + // RendDX9.dll copy (StringHashFunc, string value) PE 0x1007BA20, unreached there. bool get(const K& key, V& value) const { for (Node* n = m_buckets[bucketOf(key)]; n != 0; n = n->next) @@ -128,6 +132,7 @@ class Hash } // Deletes every node while retaining the bucket array and capacity for reuse. + // RendDX9.dll copy (StringHashFunc) PE 0x10074A50. void clear() { for (unsigned int i = 0; i < m_maxSize; ++i) @@ -144,6 +149,7 @@ class Hash } // Removes the first matching key and returns true. Returns false when the key is absent. + // RendDX9.dll copy (StringHashFunc) PE 0x100749C0. bool remove(const K& key) { const unsigned int bucket = bucketOf(key); @@ -167,6 +173,23 @@ class Hash } unsigned int bucketOf(const K& key) const { return HashFunc()(key) % m_maxSize; } + + // Inserts key/value unless the key is already present; answers false for an existing key. + // RendDX9.dll copy (StringHashFunc, string value) PE 0x1007B9A0 (`retn 8`): bucket from the + // hash modulo +0x04, exists, then a 0x3C-byte node whose next is the old head, key and value + // copy-constructed, stored as the head; true. The engine ELF inlines the same steps into + // ConsoleObjects::registerTypeConversion. [PLATFORM] the PE engine allocator can return null, + // and that arm stores the null as the bucket head (dropping the chain) and still answers true; + // operator new here throws instead, so the arm cannot occur. + // [INFERRED] name; the member is unreached in RendDX9 (only the dead wrapper PE 0x1007B310). + bool insertUnique(const K& key, const V& value) + { + const unsigned int bucket = bucketOf(key); + if (exists(key, bucket)) + return false; + insert(key, value, bucket); + return true; + } // [CHOSEN, not recovered] Convenience overloads compute the bucket before forwarding. bool exists(const K& key) const { return exists(key, bucketOf(key)); } void insert(const K& key, const V& value) { insert(key, value, bucketOf(key)); } diff --git a/Code/BF2/Core/LoadStat.cpp b/Code/BF2/Core/LoadStat.cpp index f67ed9bb7..942309d5e 100644 --- a/Code/BF2/Core/LoadStat.cpp +++ b/Code/BF2/Core/LoadStat.cpp @@ -128,8 +128,19 @@ void LoadStat::registerLoadCallback(void (*fn)()) // nothing is pushed. That matters for a rebuild tempted to add an observer here. void LoadStat::setCurrentFile(const std::string& file) { - // Update the polled loading filename without invoking callbacks or setting a dirty flag. +#if !DEDICATED + // BF2.exe 0x45D610 (all seven FileManager/Win32FileSystem callers): `lea eax,[ecx+28h]; + // push eax; add ecx,0Ch; call basic_string::assign; ret 4`. The client ignores the file name + // and copies the phase name (+0x28 in the MSVC layout, m_string10; resetLoadStats 0x45D540 + // clears +0x28 then +0x0C, as the Linux reset clears m_string10 then m_string0C). So the + // loading screen's progressText (endOfRound.swf, dice.bf2.Client.getCurrentLoadFile) shows + // the load phase, never individual files. + (void) file; + m_string0C = m_string10; +#else + // Linux server (0x83C4980): update the polled loading filename, no callback, no dirty flag. m_string0C = file; +#endif } diff --git a/Code/BF2/Core/ModuleRegistry.cpp b/Code/BF2/Core/ModuleRegistry.cpp index fc66af5c9..31e5d2316 100644 --- a/Code/BF2/Core/ModuleRegistry.cpp +++ b/Code/BF2/Core/ModuleRegistry.cpp @@ -80,6 +80,7 @@ std::list& toolObjectConsoleObjects(); // Scene/Object/Tool #include "../Game/GeneralSettings.h" // client factory4106BE, native settings owner #include "../Game/GameServerSettings.h" // client factory41067C, the ServerSettings mirror #include "../Game/HudInformationLayer.h" // client factory40FECC, native HUD data owner +#include "../Game/DistributedLightRenderer/DistributedLightRenderer.h" // client factory 40FF0E #include "../Game/VideoSettings.h" // client factory4105FB, the renderer options owner #include "../Game/ControlSettings.h" // client factory41063D, the control-map backup owner #include "../Game/HapticSettings.h" // client factory410700, the force-feedback tuning owner @@ -95,13 +96,23 @@ std::list& toolObjectConsoleObjects(); // Scene/Object/Tool #include "../Menu/MenuTeamManager.h" // client factory41053B, team/kit menu data #include "../Menu/ServerBrowserManager.h" // client factory410205, the lists' owner #include "../IO/Input/DX8InputDeviceManager.h" // client InputDX8Module factory rows +#if defined(__APPLE__) +// [CHOSEN, not recovered] macOS port: MacInputDeviceManager answers the DX8 row (docs/macos-s2-4.md). +#include "../IO/Input/MacInputDeviceManager.h" +#endif #include "../IO/Input/InputManager.h" #endif #if !DEDICATED #ifndef NOMINMAX #define NOMINMAX #endif +#if defined(_WIN32) #include // LoadLibraryA / GetProcAddress / FreeLibrary - BfSoundModule +#else +// [CHOSEN, not recovered] The macOS client resolves BF2Audio through the POSIX loader wrappers, +// which answer statically linked images first (docs/macos-port.md). +#include "PluginDll.h" +#endif #include "../Game/Utility/Vars.h" // Vars::getInt("opt-nosound") - BfSoundModule::init #endif #include "System.h" // g_system - io::ModuleIO::init calls resetExactTime @@ -374,7 +385,9 @@ void ModuleGame::getClassList(std::vector& out) // PE430A53..430A7B, then430A9F..430AC7: settings, then HUD information. out.push_back(ClassRegInfo{CID_GameServerSettings, "dice.hfe.GameServerSettings", &GameServerSettings::create}); out.push_back(ClassRegInfo{CID_HudInformationLayer, "dice.bf2.HudInformationLayer", &HudInformationLayer::create}); - // PE430B1D..430B45 and430B5C..430B84; DistributedLightRenderer lies between HUD and host. + // PE430ADE..430B06: the distributed lightmap renderer, between HUD and host. + out.push_back(ClassRegInfo{CID_DistributedLightRenderer, "dice.bf2.DistributedLightRenderer", &DistributedLightRenderer::create}); + // PE430B1D..430B45 and430B5C..430B84. out.push_back(ClassRegInfo{CID_SwiffHost, "dice.hfe.SwiffHost", &SwiffHost::create}); out.push_back(ClassRegInfo{CID_MainMenuLogic, "dice.hfe.MainMenuLogic", &MainMenuLogic::create}); // Loading-screen logic created by the InitLoadingScreen menu event. @@ -584,7 +597,14 @@ void InputDX8Module::getClassList(std::vector& out) // PE6AC3E6, c { // [PLATFORM] Client table89AE6C supplies these two rows in this order. // Use native ClassRegInfo/factory ABI, never the retail36-byte STL record. +#if defined(__APPLE__) + // [CHOSEN, not recovered] macOS port: the Cocoa-backed manager under the DX8 CID and name, so + // BF2EngineSetup's setSingletonClass("InputDeviceManager", CID_DX8InputDeviceManager) and every + // caller stay unchanged (docs/macos-s2-4.md). + out.push_back(ClassRegInfo{CID_DX8InputDeviceManager, "dice.hfe.io.InputDeviceManager.DX8", &MacInputDeviceManager::create}); +#else out.push_back(ClassRegInfo{CID_DX8InputDeviceManager, "dice.hfe.io.InputDeviceManager.DX8", &DX8InputDeviceManager::create}); +#endif out.push_back(ClassRegInfo{CID_InputManager, "dice.hfe.io.InputManager", &InputManager::create}); } #else @@ -1162,7 +1182,11 @@ bool MathModule::init() bool MathModule::close() { closeMath(); return true; } #if !DEDICATED +#if defined(_WIN32) static HMODULE s_audioLibrary = 0; // BF2.exe ds:0xA24CB0 - the BF2Audio.dll handle +#else +static void* s_audioLibrary = 0; // [CHOSEN] POSIX loader-wrapper handle +#endif #endif bool BfSoundModule::init() { @@ -1185,7 +1209,11 @@ bool BfSoundModule::init() } BfSound* facade = new BfSound; g_bfSound = facade; +#if defined(_WIN32) s_audioLibrary = LoadLibraryA("BF2Audio.dll"); +#else + s_audioLibrary = ::LoadLibrary("BF2Audio.dll"); +#endif if (s_audioLibrary) { typedef ISoundEngine* (*GetSoundEngineFn)(); diff --git a/Code/BF2/Core/MsvcCrtCompat.h b/Code/BF2/Core/MsvcCrtCompat.h new file mode 100644 index 000000000..fb4fa1628 --- /dev/null +++ b/Code/BF2/Core/MsvcCrtCompat.h @@ -0,0 +1,288 @@ +// [CHOSEN, not recovered] MSVC 7.1 CRT functions that client code calls, rebuilt for the native +// POSIX ports with the MSVC observable semantics (return values, truncation, wide-format +// conversions). See docs/macos-port.md, "Win32 and CRT items (S2.5/S2.8)". +// +// Include it only where one of these names is used. On MSVC it is empty: the real CRT is used. +#ifndef CORE_MSVCCRTCOMPAT_H +#define CORE_MSVCCRTCOMPAT_H + +#if !defined(_MSC_VER) + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace bf2crt { + +// Rewrites an MSVC wide-printf format for the C library. In MSVC's wide family `%s`/`%c` take +// wide arguments and `%S`/`%C` narrow ones (an `h` prefix forces narrow, `l`/`w` wide); C99 uses +// `%ls`/`%lc` for wide and `%s`/`%c` for narrow. `I64` becomes `ll`, `I32` is dropped and `I` +// becomes `z`. Everything else is copied unchanged. +inline std::wstring translateWideFormat(const wchar_t* fmt) +{ + std::wstring out; + if (!fmt) + return out; + for (const wchar_t* p = fmt; *p; ) { + if (*p != L'%') { + out += *p++; + continue; + } + out += *p++; // '%' + if (*p == L'%') { + out += *p++; + continue; + } + while (*p && std::wcschr(L"-+ #0", *p)) // flags + out += *p++; + while (*p == L'*' || (*p >= L'0' && *p <= L'9')) // width + out += *p++; + if (*p == L'.') { // precision + out += *p++; + while (*p == L'*' || (*p >= L'0' && *p <= L'9')) + out += *p++; + } + // Length prefix: 0 none, 'h' narrow, 'l' wide/long, 'w' wide. + wchar_t size = 0; + std::wstring lengthText; + for (;;) { + if (p[0] == L'I' && p[1] == L'6' && p[2] == L'4') { lengthText += L"ll"; p += 3; continue; } + if (p[0] == L'I' && p[1] == L'3' && p[2] == L'2') { p += 3; continue; } + if (p[0] == L'I') { lengthText += L"z"; ++p; continue; } + if (*p == L'h') { size = L'h'; lengthText += *p++; continue; } + if (*p == L'l') { if (size == 0) size = L'l'; lengthText += *p++; continue; } + if (*p == L'w') { size = L'w'; ++p; continue; } + if (*p == L'L' || *p == L'j' || *p == L'z' || *p == L't') { lengthText += *p++; continue; } + break; + } + const wchar_t conv = *p; + if (!conv) + break; + ++p; + switch (conv) { + case L's': + out += (size == L'h') ? L"s" : L"ls"; + break; + case L'S': + out += (size == L'l' || size == L'w') ? L"ls" : L"s"; + break; + case L'c': + out += (size == L'h') ? L"c" : L"lc"; + break; + case L'C': + out += (size == L'l' || size == L'w') ? L"lc" : L"c"; + break; + default: + out += lengthText; + out += conv; + break; + } + } + return out; +} + +// Formats the whole output of an MSVC wide format. Returns false when the C library refuses +// (an encoding error or more than 16M characters). +inline bool formatWideFully(std::vector& out, int& length, const wchar_t* fmt, va_list args) +{ + const std::wstring format = translateWideFormat(fmt); + std::size_t capacity = 256; + for (;;) { + out.assign(capacity, L'\0'); + va_list copy; + va_copy(copy, args); + const int n = std::vswprintf(out.data(), capacity, format.c_str(), copy); + va_end(copy); + if (n >= 0) { + length = n; + return true; + } + if (capacity >= (std::size_t(1) << 24)) + return false; + capacity *= 4; + } +} + +} // namespace bf2crt + +// _vsnwprintf (MSVC 7.1): at most `count` characters are written. A shorter result is +// terminated and its length returned; a result of exactly `count` characters is written without +// a terminator and `count` returned; a longer one writes its first `count` characters, no +// terminator, and returns -1. A format the C library refuses returns -1 and writes nothing. +inline int _vsnwprintf(wchar_t* buffer, std::size_t count, const wchar_t* fmt, va_list args) +{ + std::vector full; + int length = 0; + if (!bf2crt::formatWideFully(full, length, fmt, args)) + return -1; + const std::size_t len = static_cast(length); + if (len < count) { + std::wmemcpy(buffer, full.data(), len + 1); + return length; + } + std::wmemcpy(buffer, full.data(), count); + return len == count ? length : -1; +} + +// _swprintf (MSVC 7.1 legacy, no size argument): the whole result and its terminator are written. +// Returns the length, or -1 for a format the C library refuses. +inline int _swprintf(wchar_t* buffer, const wchar_t* fmt, ...) +{ + va_list args; + va_start(args, fmt); + std::vector full; + int length = 0; + const bool ok = bf2crt::formatWideFully(full, length, fmt, args); + va_end(args); + if (!ok) + return -1; + std::wmemcpy(buffer, full.data(), static_cast(length) + 1); + return length; +} + +// _TRUNCATE and _snprintf_s (MSVC 8 secure CRT): with count == _TRUNCATE, as much as fits in +// sizeInBytes - 1 characters is written and terminated; the answer is the length, or -1 when the +// output was truncated. A finite count also limits the characters written, with the same -1 +// answer when the limit cut the output. +#ifndef _TRUNCATE +#define _TRUNCATE (static_cast(-1)) +#endif +inline int _vsnprintf_s(char* buffer, std::size_t sizeInBytes, std::size_t count, const char* fmt, va_list args) +{ + if (!buffer || sizeInBytes == 0) + return -1; + std::size_t limit = sizeInBytes - 1; + if (count != _TRUNCATE && count < limit) + limit = count; + va_list copy; + va_copy(copy, args); + const int n = std::vsnprintf(buffer, limit + 1, fmt, copy); + va_end(copy); + if (n < 0) { + buffer[0] = '\0'; + return -1; + } + return static_cast(n) > limit ? -1 : n; +} +inline int _snprintf_s(char* buffer, std::size_t sizeInBytes, std::size_t count, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + const int n = _vsnprintf_s(buffer, sizeInBytes, count, fmt, args); + va_end(args); + return n; +} + +// sprintf_s, the array form (MSVC 8 secure CRT): the formatted text with its terminator, or, when +// it does not fit, the invalid-parameter handler, whose default ends the process. That stop is +// kept: the text is reported on stderr and the process aborts. +template +inline int sprintf_s(char (&buffer)[N], const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + const int n = std::vsnprintf(buffer, N, fmt, args); + va_end(args); + if (n < 0 || static_cast(n) >= N) { + buffer[0] = '\0'; + std::fprintf(stderr, "sprintf_s: buffer of %u bytes too small for \"%s\" (invalid parameter)\n", + static_cast(N), fmt); + std::fflush(stderr); + std::abort(); + } + return n; +} + +// __time32_t / _time32: seconds since the epoch as a 32-bit value; -1 once that no longer fits +// (from 2038), as the MSVC function answers. +typedef std::int32_t __time32_t; +inline __time32_t _time32(__time32_t* out) +{ + const std::time_t now = std::time(nullptr); + const __time32_t value = (now < 0 || now > static_cast(INT32_MAX)) + ? static_cast<__time32_t>(-1) : static_cast<__time32_t>(now); + if (out) + *out = value; + return value; +} + +// _time64: 64-bit seconds since the epoch. +inline long long _time64(long long* out) +{ + const long long value = static_cast(std::time(nullptr)); + if (out) + *out = value; + return value; +} + +// _splitpath (MSVC 7.1 splitpath.c, single-byte): a drive is the first two characters when the +// second is ':'; the directory runs to the last '/' or '\\' inclusive; the extension starts at +// the last '.' after it. Each part is truncated to the MSVC limits (_MAX_DRIVE 3, _MAX_DIR 256, +// _MAX_FNAME 256, _MAX_EXT 256, terminator included) and every non-null output is terminated. +// As in MSVC, the caller's buffers must hold those limits. +inline void _splitpath(const char* path, char* drive, char* dir, char* fname, char* ext) +{ + const std::size_t maxDrive = 3, maxDir = 256, maxFname = 256, maxExt = 256; + if (std::strlen(path) >= maxDrive - 2 && path[maxDrive - 2] == ':') { + if (drive) { + std::strncpy(drive, path, maxDrive - 1); + drive[maxDrive - 1] = '\0'; + } + path += maxDrive - 1; + } else if (drive) { + *drive = '\0'; + } + const char* lastSlash = nullptr; + const char* dot = nullptr; + const char* p = path; + for (; *p; ++p) { + if (*p == '/' || *p == '\\') + lastSlash = p + 1; + else if (*p == '.') + dot = p; + } + if (lastSlash) { + if (dir) { + std::size_t len = static_cast(lastSlash - path); + if (len > maxDir - 1) len = maxDir - 1; + std::strncpy(dir, path, len); + dir[len] = '\0'; + } + path = lastSlash; + } else if (dir) { + *dir = '\0'; + } + if (dot && dot >= path) { + if (fname) { + std::size_t len = static_cast(dot - path); + if (len > maxFname - 1) len = maxFname - 1; + std::strncpy(fname, path, len); + fname[len] = '\0'; + } + if (ext) { + std::size_t len = static_cast(p - dot); + if (len > maxExt - 1) len = maxExt - 1; + std::strncpy(ext, dot, len); + ext[len] = '\0'; + } + } else { + if (fname) { + std::size_t len = static_cast(p - path); + if (len > maxFname - 1) len = maxFname - 1; + std::strncpy(fname, path, len); + fname[len] = '\0'; + } + if (ext) + *ext = '\0'; + } +} + +#endif // !_MSC_VER +#endif // CORE_MSVCCRTCOMPAT_H diff --git a/Code/BF2/Core/Mutex.cpp b/Code/BF2/Core/Mutex.cpp index 61c6ff14e..2d604c15e 100644 --- a/Code/BF2/Core/Mutex.cpp +++ b/Code/BF2/Core/Mutex.cpp @@ -1,5 +1,6 @@ // Opaque mutex ownership with a one-pointer public layout; source path [INFERRED]. -// The POSIX implementation follows the original; the Windows primitive is a chosen platform adaptation. +// The POSIX payload follows the original except its type (recursive, see the constructor); the Windows +// primitive is a chosen platform adaptation. #include "Mutex.h" @@ -27,7 +28,25 @@ Mutex::Mutex() // build dice used those agreed; on another they need not. Written as sizeof() here because a // hardcoded 24 would be silently wrong on any platform whose mutex is larger. pthread_mutex_t* p = static_cast(::operator new(sizeof(pthread_mutex_t))); - pthread_mutex_init(p, 0); // null attributes — the binary passes 0 + // [CHOSEN, not recovered] Recursive: a deliberate divergence from the Linux retail image in favour + // of the Windows retail behaviour. The ELF passes null attributes (0x83D2CC0), a normal glibc + // mutex; the shared code was written against Windows' recursive CRITICAL_SECTION and relocks on + // one thread: CBF2VoipServer::Shutdown holds mMutex and calls ReleaseAllInstances, + // which locks it again (ELF 0x84EC920 -> 0x84EC6CD, the same in the PE). With a normal mutex + // that path hangs forever (local-host shutdown on macOS and the Linux dedicated server). No + // user waits on its own lock or pairs it with a condition variable, so recursion only removes + // self-deadlocks; other threads are excluded exactly as before. + // [CHOSEN, not recovered] owner-approved 2026-11-13 (in place of a linked issue): matches the + // Windows retail image (CRITICAL_SECTION recursion) on every platform; deviates from the Linux + // retail image, whose non-recursive mutex self-deadlocks in CBF2VoipServer::Shutdown. [PLATFORM] + // retail defect of the Linux image: Mutex::Mutex (ELF 0x83D2CA0 / 0x83D2CE0) calls + // pthread_mutex_init(p, NULL); CBF2VoipServer::Shutdown (ELF 0x84EC900) locks this+8 at 0x84EC920, + // and ReleaseAllInstances relocks it at 0x84EC6CD. + pthread_mutexattr_t attributes; + pthread_mutexattr_init(&attributes); + pthread_mutexattr_settype(&attributes, PTHREAD_MUTEX_RECURSIVE); + pthread_mutex_init(p, &attributes); + pthread_mutexattr_destroy(&attributes); m_mutex = p; #endif } diff --git a/Code/BF2/Core/PlatformCompat.h b/Code/BF2/Core/PlatformCompat.h index 3b8a86143..74220ce0c 100644 --- a/Code/BF2/Core/PlatformCompat.h +++ b/Code/BF2/Core/PlatformCompat.h @@ -19,6 +19,30 @@ #include // alloca #include // std::isfinite, std::isnan +#if !defined(_WIN32) +// [CHOSEN, not recovered] POSIX Interlocked adapters (macOSplan.md, S2.10). +// Targets must be naturally aligned native words, never fields in packed file/packet data. +// Increment/decrement/add return the new value; exchange/add-exchange/CAS return the old value. +template inline T InterlockedIncrement(volatile T* target) +{ return __atomic_add_fetch(target, 1, __ATOMIC_SEQ_CST); } +template inline T InterlockedDecrement(volatile T* target) +{ return __atomic_sub_fetch(target, 1, __ATOMIC_SEQ_CST); } +template inline T InterlockedAdd(volatile T* target, V value) +{ return __atomic_add_fetch(target, static_cast(value), __ATOMIC_SEQ_CST); } +template inline T InterlockedExchangeAdd(volatile T* target, V value) +{ return __atomic_fetch_add(target, static_cast(value), __ATOMIC_SEQ_CST); } +template inline T InterlockedExchange(volatile T* target, V value) +{ return __atomic_exchange_n(target, static_cast(value), __ATOMIC_SEQ_CST); } +template +inline T InterlockedCompareExchange(volatile T* target, V value, C comparand) +{ + T previous = static_cast(comparand); + __atomic_compare_exchange_n(target, &previous, static_cast(value), false, + __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); + return previous; +} +#endif + // Win32 calling-convention spellings are empty for this non-MSVC native port. #ifndef __cdecl #define __cdecl diff --git a/Code/BF2/Core/PluginDll.cpp b/Code/BF2/Core/PluginDll.cpp index 074eebcd4..0aabdc503 100644 --- a/Code/BF2/Core/PluginDll.cpp +++ b/Code/BF2/Core/PluginDll.cpp @@ -1,5 +1,5 @@ // Loads engine plugins for client and dedicated images; source path [INFERRED]. -// Windows unload calls optional deinitDll and reports exceptions. ELF unload only closes the library. +// Windows unload calls optional deinitDll and reports exceptions. Linux also deinitializes before close. #include "PluginDll.h" @@ -12,6 +12,9 @@ #endif #include "ClassManager.h" +#if defined(BF2_STATIC_PLUGINS) +#include "../../StaticPlugins/StaticPlugins.h" +#endif #if !defined(_WIN32) // [PLATFORM] Global-namespace library wrappers for ELF; placement is [INFERRED]. @@ -24,18 +27,43 @@ void* LoadLibrary(const char* name) const char* const dot = std::strrchr(name, '.'); if (!dot) return 0; +#if defined(BF2_STATIC_PLUGINS) + // [CHOSEN, not recovered] The macOS client links its plugin images statically + // (Code/StaticPlugins/StaticPlugins.h); a linked image is answered before dlopen is tried. + if (void* image = bf2staticplugins::find(std::string(name, dot).c_str())) + return image; +#endif std::string file = std::string("lib") + std::string(name, dot); +#if defined(__APPLE__) + // [CHOSEN, not recovered] The macOS port's shared-library suffix (docs/macos-port.md). + file.append(".dylib"); +#else file.append(".so"); +#endif return ::dlopen(file.c_str(), RTLD_LAZY); } void* GetProcAddress(void* handle, const char* name) { +#if defined(BF2_STATIC_PLUGINS) + if (bf2staticplugins::isStaticHandle(handle)) + return bf2staticplugins::symbol(handle, name); +#endif return ::dlsym(handle, name); } bool FreeLibrary(void* handle) { +#if defined(BF2_STATIC_PLUGINS) + // A statically linked image stays mapped for the life of the process; there is nothing to close. + // It is only marked released, so the next load can rebuild its module table + // (StaticPlugins.h, menu re-entry). + if (bf2staticplugins::isStaticHandle(handle)) + { + bf2staticplugins::release(handle); + return true; + } +#endif if (handle) return ::dlclose(handle) == 0; return false; @@ -113,9 +141,42 @@ bool FreeLibraryBf(void* handle, const char* diagnosticName) return false; } #else - // : the bare wrapper call. No deinitDll lookup, no diagnostic, and the - // second argument is never read. (void)diagnosticName; +#if defined(BF2_STATIC_PLUGINS) + // [CHOSEN, not recovered] A linked image that retail unloads per use (SwiffPlayer, on every + // menu exit) gets the Win32 body's deinitDll before the release, so its modules are closed, + // unregistered and released as BF2.exe 0x446CE0 does before FreeLibrary (StaticPlugins.h). + if (bf2staticplugins::isStaticHandle(handle) && bf2staticplugins::unloadsWithDeinit(handle)) + { + DeinitDllFn deinitDll = reinterpret_cast(::GetProcAddress(handle, "deinitDll")); + if (deinitDll) + deinitDll(); + } +#endif +#if defined(__APPLE__) || defined(__linux__) + // [PLATFORM] [CHOSEN, not recovered] Native-port design, not retail: a dlopen'ed image + // (libaidll.dylib, libaidll.so) gets the Win32 body's deinitDll before dlclose. The ELF body (bf2 0x83C3400 -> FreeLibrary 0x83D3170) is the bare + // dlclose, so AIModule::close (libaidll.so 0x3EECB0) never runs and the "AI" simple singleton + // that the IAI constructor (0x3EE430) registered stays in the host registry. The next load's + // IAI constructor then finds "AI" taken and leaves the new BF2AI unregistered, and + // AIConnection::init hands back the old object. [INFERRED] Retail Linux survives this only + // while dlopen maps the reloaded image at the closed one's address, which makes the old vtable + // pointer valid again (not observed on a retail run). dyld does not reuse the address: dlclose unmaps the dylib and the old vtable + // pointer dangles (the second singleplayer game faulted with pc=0 at GameServer::loadPath's + // aiSingleton->init()). The Win32 body (BF2.exe 0x446CE0) calls deinitDll first; AIModule::close + // then unregisters "AI" and the module's console lists, and the reload registers fresh ones. + // Request R4 of the AI track's client hand-off. + bool dlopened = handle != 0; +#if defined(BF2_STATIC_PLUGINS) + dlopened = dlopened && !bf2staticplugins::isStaticHandle(handle); +#endif + if (dlopened) + { + DeinitDllFn deinitDll = reinterpret_cast(::GetProcAddress(handle, "deinitDll")); + if (deinitDll) + deinitDll(); + } +#endif return ::FreeLibrary(handle); #endif } diff --git a/Code/BF2/Core/PluginDll.h b/Code/BF2/Core/PluginDll.h index a50248cd9..bd67519a9 100644 --- a/Code/BF2/Core/PluginDll.h +++ b/Code/BF2/Core/PluginDll.h @@ -3,6 +3,15 @@ #ifndef CORE_PLUGINDLL_H #define CORE_PLUGINDLL_H +#if !defined(_WIN32) +// [PLATFORM] The ELF's global-namespace LoadLibrary/GetProcAddress/FreeLibrary wrappers over +// dlopen/dlsym/dlclose, defined in PluginDll.cpp. Under BF2_STATIC_PLUGINS (the macOS client) they +// answer the statically linked plugin images first. +void* LoadLibrary(const char* name); +void* GetProcAddress(void* handle, const char* name); +bool FreeLibrary(void* handle); +#endif + namespace dice { namespace hfe { diff --git a/Code/BF2/Core/PosixRegistry.h b/Code/BF2/Core/PosixRegistry.h new file mode 100644 index 000000000..fee57e702 --- /dev/null +++ b/Code/BF2/Core/PosixRegistry.h @@ -0,0 +1,23 @@ +// [CHOSEN, not recovered] Owner-requested POSIX Registry.con backend. +#ifndef CORE_POSIXREGISTRY_H +#define CORE_POSIXREGISTRY_H + +#if !defined(_WIN32) && !DEDICATED +#include "RegistryFile.h" + +namespace dice { namespace hfe { namespace posixRegistry { + +// Reads and parses @HOME@/Registry.con (RegistryFile.h); empty for an absent/unreadable file. +registryFile::Values readFile(); + +// Reads a named value from @HOME@/Registry.con. An empty name denotes the default value. +// Returns false for an absent/unreadable file or value, leaving output untouched. +bool readValue(RegKeyCategory category, const std::string& path, + const std::string& name, std::string& output); + +// Tests whether the file contains a value in this key or one of its descendants. +bool keyExists(RegKeyCategory category, const std::string& path); + +} } } +#endif +#endif diff --git a/Code/BF2/Core/Random.cpp b/Code/BF2/Core/Random.cpp index d73d31190..29090f778 100644 --- a/Code/BF2/Core/Random.cpp +++ b/Code/BF2/Core/Random.cpp @@ -1,4 +1,8 @@ -// Stream serialization for shared random-distribution types. [INFERRED] Source placement. +// Random state and distribution serialization. [INFERRED] Core placement; AI FILE symbol: Random.cpp. + +// static init (each image's own Random.cpp): iostream Init, then Rand. +// bf2 ELF 0x83CB610 (seed store 0x83CB642); libaidll ELF 0x48A850 (__tcf_0 0x48A8D0, _GLOBAL__I 0x48A900). +#include #include "Random.h" @@ -10,6 +14,14 @@ namespace dice { namespace hfe { +// Each image owns one instance under the same symbol, dice::hfe::Rand: bf2 ds:0x8ABBCB0 and +// libaidll BSS 0x4DD454. The initializers store Random's default seed (0x759DC150). +Random Rand; + +#if !defined(BF2_IMAGE_AIDLL) +// [CHOSEN, not recovered] Image partition: these distribution codecs belong to the engine; +// the original AI Random.cpp contributes its independent state and initialization only. + // ELF 0x83CFC50 (87 B), PE 0x5C10D0 (91 B). The default arm covers CRD_NONE and every invalid // selector; do not print an unknown integer numerically. std::ostream& operator<<(std::ostream& stream, ContRandDist distribution) @@ -93,5 +105,7 @@ std::istream& operator>>(std::istream& stream, RandomDistribution& distribution) return stream; } +#endif + } // namespace hfe } // namespace dice diff --git a/Code/BF2/Core/Random.h b/Code/BF2/Core/Random.h index 7dc9d5931..f658c52fb 100644 --- a/Code/BF2/Core/Random.h +++ b/Code/BF2/Core/Random.h @@ -60,7 +60,9 @@ static_assert(sizeof(Random) == 4, "Random must retain its shipped x86 layout"); static_assert(sizeof(RandomDistribution) == 0x14, "RandomDistribution must retain its shipped x86 layout"); -extern Random g_random; // ELF ds:0x8ABBCB0 [CHOSEN symbol name] +// The image's random instance, defined in Random.cpp: dice::hfe::Rand in both retail images +// (bf2 ds:0x8ABBCB0, libaidll BSS 0x4DD454); the engine and the AI DLL each have their own. +extern Random Rand; } // namespace hfe } // namespace dice diff --git a/Code/BF2/Core/Registry.cpp b/Code/BF2/Core/Registry.cpp index 60f4b2510..2b7751dbc 100644 --- a/Code/BF2/Core/Registry.cpp +++ b/Code/BF2/Core/Registry.cpp @@ -1,8 +1,30 @@ // Path attested: _GLOBAL__N_Core_Registry.cppvohp2b9rinstance in the symbolized ELF. #include "Registry.h" +#if !DEDICATED +// [CHOSEN, not recovered] Owner decisions: the client's registry file (RegistryFile.h). +#include "RegistryFile.h" +#include +#include +#include +#endif #ifdef _WIN32 #include +#if !DEDICATED +#include +#include +#pragma comment(lib, "crypt32.lib") +#pragma comment(lib, "shell32.lib") +#pragma comment(lib, "ole32.lib") +#endif +#elif !DEDICATED +#include "PosixRegistry.h" +#include +#if defined(__APPLE__) +#include "../Platform/macOS/ClientPaths.h" +#else +#include "../IO/File/FileManager.h" +#endif #endif namespace dice { namespace hfe { @@ -28,7 +50,16 @@ bool readRegistryString(RegKeyCategory category, const std::string& name, path = std::string("SOFTWARE\\Electronic Arts\\EA Games\\") + modName; bool found = false; +#if defined(_M_IX86) if (RegOpenKeyA(root, path.c_str(), &key) == ERROR_SUCCESS) +#else + // [CHOSEN, not recovered] x64 (https://github.com/B2BF/OpenBF2/issues/7): BF2's 32-bit installer + // writes these keys into the 32-bit registry view (WOW6432Node), which a 32-bit process reads + // implicitly; a 64-bit process must ask for that view or it finds no keys (an empty CD key then + // takes translateCdKey's shipped null-blob fault at the first server challenge). Subkeys opened + // relative to this handle stay in the same view. + if (RegOpenKeyExA(root, path.c_str(), 0, KEY_READ | KEY_WOW64_32KEY, &key) == ERROR_SUCCESS) +#endif { BYTE data[1024]; DWORD type; @@ -72,6 +103,188 @@ bool readRegistryString(RegKeyCategory category, const std::string& name, Registry* registry = &rinstance; +#if !DEDICATED +// [CHOSEN, not recovered] File syntax and owner decisions: docs/registry-file.md. +namespace registryFile { +namespace { +std::string trim(const std::string& text) +{ + const auto first = text.find_first_not_of(" \t\r"); + return first == std::string::npos ? std::string() : + text.substr(first, text.find_last_not_of(" \t\r") - first + 1); +} + +std::string fold(std::string text) +{ + for (char& c : text) + if (c >= 'A' && c <= 'Z') + c += 'a' - 'A'; + return text; +} + +std::string keyPath(RegKeyCategory category, const std::string& path) +{ + return fold(std::string(category == RegKeyLocalMachine ? + "HKEY_LOCAL_MACHINE\\" : "HKEY_CURRENT_USER\\") + path); +} +} // namespace + +Values parse(const std::string& text, const char* sourceName) +{ + Values values; + // A leading UTF-8 byte-order mark is not part of the first line. + std::istringstream input(text.compare(0, 3, "\xEF\xBB\xBF") == 0 ? text.substr(3) : text); + std::string line; + unsigned int number = 0; + while (std::getline(input, line)) { + ++number; + line = trim(line); + if (line.empty() || line[0] == '#' || line[0] == ';') + continue; + const auto separator = line.find('='); + const std::string key = fold(trim(line.substr(0, separator))); + const auto last = key.find_last_of('\\'); + if (separator == std::string::npos || line.find('\0') != std::string::npos || + (key.compare(0, 19, "hkey_local_machine\\") != 0 && + key.compare(0, 18, "hkey_current_user\\") != 0) || + last == std::string::npos || last + 1 == key.size() || + key.find("\\\\") != std::string::npos) { + // Never include values: the file can contain a CD key. + std::fprintf(stderr, "%s: ignoring malformed line %u\n", sourceName, number); + std::fflush(stderr); + continue; + } + values[key] = trim(line.substr(separator + 1)); + } + return values; +} + +bool readValue(const Values& values, RegKeyCategory category, const std::string& path, + const std::string& name, std::string& output) +{ + const auto found = values.find(keyPath(category, path) + "\\" + + (name.empty() ? "@" : fold(name))); + if (found == values.end()) + return false; + output = found->second; + return true; +} + +bool keyExists(const Values& values, RegKeyCategory category, const std::string& path) +{ + const std::string prefix = keyPath(category, path) + "\\"; + const auto found = values.lower_bound(prefix); + return found != values.end() && found->first.compare(0, prefix.size(), prefix) == 0; +} + +bool readGameValue(const Values& values, RegKeyCategory category, const std::string& name, + const std::string& modName, std::string& output) +{ + const std::string path = std::string("SOFTWARE\\Electronic Arts\\EA Games\\") + + (modName.empty() ? "Battlefield 2" : modName); + return readValue(values, category, path, name, output) || + readValue(values, category, path + "\\" + name, "", output); +} + +#ifdef _WIN32 +bool unprotect(const std::string& blob, std::string& text) +{ + DATA_BLOB input; + input.pbData = reinterpret_cast(const_cast(blob.data())); + input.cbData = static_cast(blob.size()); + DATA_BLOB output = { 0, 0 }; + // CurrentUser scope (the blob was protected without CRYPTPROTECT_LOCAL_MACHINE), no entropy, + // and never a prompt. + if (blob.empty() || !CryptUnprotectData(&input, 0, 0, 0, 0, CRYPTPROTECT_UI_FORBIDDEN, &output)) + return false; + std::string plain(reinterpret_cast(output.pbData), output.cbData); + SecureZeroMemory(output.pbData, output.cbData); + LocalFree(output.pbData); + // A writer that protects a C string with its terminator leaves a NUL behind the text. + while (!plain.empty() && plain[plain.size() - 1] == '\0') + plain.erase(plain.size() - 1); + text.swap(plain); + return true; +} + +bool readProtectedFile(const std::wstring& path, Values& values) +{ + if (path.empty()) + return false; + HANDLE file = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, 0); + if (file == INVALID_HANDLE_VALUE) + return false; + std::string blob; + LARGE_INTEGER size; + bool read = GetFileSizeEx(file, &size) && size.QuadPart > 0 && size.QuadPart <= 64 * 1024; + if (read) { + blob.resize(static_cast(size.QuadPart)); + DWORD bytes = 0; + read = ReadFile(file, &blob[0], static_cast(blob.size()), &bytes, 0) && + bytes == blob.size(); + } + CloseHandle(file); + std::string text; + if (!read || !unprotect(blob, text)) { + std::fprintf(stderr, "Registry.dat: unreadable, using the registry\n"); + std::fflush(stderr); + return false; + } + values = parse(text, "Registry.dat"); + SecureZeroMemory(&text[0], text.size()); + return true; +} + +std::wstring protectedFilePath() +{ + PWSTR folder = 0; + std::wstring path; + if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, 0, &folder)) && folder && *folder) + path = std::wstring(folder) + L"\\OpenBF2\\Registry.dat"; + CoTaskMemFree(folder); + return path; +} +#endif +} // namespace registryFile +#endif + +#if !defined(_WIN32) && !DEDICATED +namespace posixRegistry { +// Each lookup reopens the file; nothing is cached. +registryFile::Values readFile() +{ +#if defined(__APPLE__) + const std::string home = macos::clientDataDirectory(); +#else + // Use the filesystem's @HOME@ policy when a future POSIX client supplies it. + if (!io::fileManager) + return registryFile::Values(); + const std::string home = io::fileManager->getHomeSubstitution(); +#endif + if (home.empty()) + return registryFile::Values(); + std::ifstream input(home + "/Registry.con", std::ios::binary); + std::ostringstream text; + text << input.rdbuf(); + if (input.bad()) + return registryFile::Values(); + return registryFile::parse(text.str(), "Registry.con"); +} + +bool readValue(RegKeyCategory category, const std::string& path, + const std::string& name, std::string& output) +{ + return registryFile::readValue(readFile(), category, path, name, output); +} + +bool keyExists(RegKeyCategory category, const std::string& path) +{ + return registryFile::keyExists(readFile(), category, path); +} +} // namespace posixRegistry +#endif + // Client PE 0x450FE0. [PLATFORM] ELF 0x83CB6F0 constructs an empty string and // ignores even the supplied default; this is an actual shipped Linux body. std::string Registry::getString(RegKeyCategory category, const std::string& name, @@ -79,8 +292,23 @@ std::string Registry::getString(RegKeyCategory category, const std::string& name { #ifdef _WIN32 std::string result = defaultValue; +#if !DEDICATED + // [CHOSEN, not recovered] Owner decision: a value in the per-user, DPAPI-protected Registry.dat + // wins; without the file, or without the value in it, the registry is read as retail does. + registryFile::Values values; + if (registryFile::readProtectedFile(registryFile::protectedFilePath(), values) && + registryFile::readGameValue(values, category, name, modName, result)) + return result; +#endif readRegistryString(category, name, defaultValue, result, modName); return result; +#elif !DEDICATED + // [CHOSEN, not recovered] POSIX clients read Registry.con; missing values retain the + // Windows absent-key defaults. + std::string result; + if (registryFile::readGameValue(posixRegistry::readFile(), category, name, modName, result)) + return result; + return defaultValue; #else return std::string(""); #endif diff --git a/Code/BF2/Core/RegistryFile.h b/Code/BF2/Core/RegistryFile.h new file mode 100644 index 000000000..1d8dbfef1 --- /dev/null +++ b/Code/BF2/Core/RegistryFile.h @@ -0,0 +1,49 @@ +// [CHOSEN, not recovered] The client's registry file, shared by every client platform: the plain +// Registry.con on POSIX (PosixRegistry.h) and, on Windows, Registry.dat, the same text protected with +// DPAPI. Owner decisions; the file contract is docs/registry-file.md. Bodies in Core/Registry.cpp. +#ifndef CORE_REGISTRYFILE_H +#define CORE_REGISTRYFILE_H + +#if !DEDICATED +#include "Registry.h" +#include +#include + +namespace dice { namespace hfe { namespace registryFile { + +// Folded "hive\path\name" (a final "@" for a key's default value) -> value text. +typedef std::map Values; + +// Parses the file text: one `HIVE\path\name = value` line per value. sourceName only names the file +// in the line-number-only diagnostics; values never appear in them (the file holds CD keys). +Values parse(const std::string& text, const char* sourceName); + +// A named value of `HIVE\path`; an empty name denotes the key's default value. +bool readValue(const Values& values, RegKeyCategory category, const std::string& path, + const std::string& name, std::string& output); + +// True when the text has a value in `HIVE\path` or one of its descendants. +bool keyExists(const Values& values, RegKeyCategory category, const std::string& path); + +// Registry::getString's lookup: the value `name` of SOFTWARE\Electronic Arts\EA Games\, else the default value of its subkey `name`, as the registry reader falls back. +// Leaves output untouched when neither is present. +bool readGameValue(const Values& values, RegKeyCategory category, const std::string& name, + const std::string& modName, std::string& output); + +#ifdef _WIN32 +// CryptUnprotectData(CurrentUser blob, no entropy, CRYPTPROTECT_UI_FORBIDDEN); trailing NUL bytes of +// the plaintext are dropped. False when the blob does not decrypt for this user. +bool unprotect(const std::string& blob, std::string& text); + +// Reads, decrypts and parses the file at path. False, leaving values untouched, when it is absent, +// unreadable, larger than 64 KiB or does not decrypt. +bool readProtectedFile(const std::wstring& path, Values& values); + +// %LOCALAPPDATA%\OpenBF2\Registry.dat (FOLDERID_LocalAppData); empty when the folder is unknown. +std::wstring protectedFilePath(); +#endif + +} } } +#endif +#endif diff --git a/Code/BF2/Core/SoundSeamFrontier.h b/Code/BF2/Core/SoundSeamFrontier.h deleted file mode 100644 index 3ec3cd4ac..000000000 --- a/Code/BF2/Core/SoundSeamFrontier.h +++ /dev/null @@ -1,30 +0,0 @@ -// [TEMP] [CHOSEN, not recovered] Sound-only fallback that reports a skipped call and continues. -// [RETIRE-WHEN: sound-seam-owner] Remove when all callers use typed g_bfSound playSound/stopSound. -// Each site names its caller and sound, counts every hit, and reports the first three then every -// 256th to stderr. No value is fabricated. Existing audio remains unchanged by the skipped call. -// Use only for an unrecovered audible effect; other frontiers retain their stop. stderr avoids -// early-boot logging dependencies and Debug's abort behavior. -#ifndef CORE_SOUNDSEAMFRONTIER_H -#define CORE_SOUNDSEAMFRONTIER_H -#include - -namespace dice { -namespace hfe { - -// `hits` is the caller's own counter - give each call site a distinct one so the -// rate limiting and the count stay per-seam. `action` is "start" or "stop". -inline void soundSeamFrontier(unsigned int& hits, const char* qualified, - const char* detail, const char* action, const char* sound) -{ - ++hits; - if (hits > 3u && (hits & 0xFFu) != 0u) return; - std::fprintf(stderr, - "[FRONTIER] %s reached (%s): would %s sound \"%s\" - REPORTED AND CONTINUED, " - "hit %u\n", - qualified, detail, action, sound, hits); - std::fflush(stderr); -} - -} // namespace hfe -} // namespace dice -#endif // CORE_SOUNDSEAMFRONTIER_H diff --git a/Code/BF2/Core/SpHandlePool.h b/Code/BF2/Core/SpHandlePool.h index 5ca45b06e..b7b60c849 100644 --- a/Code/BF2/Core/SpHandlePool.h +++ b/Code/BF2/Core/SpHandlePool.h @@ -25,6 +25,7 @@ class SpHandlePool }; // Initializes empty records with generation zero and links every slot into the free list. + // libaidll.so: the SpHandlePool instantiation is ELF 0x36D580 (weak). SpHandlePool() { for (int i = 0; i < N; ++i) diff --git a/Code/BF2/Core/StringTokenizer.h b/Code/BF2/Core/StringTokenizer.h new file mode 100644 index 000000000..ec1ca5c1e --- /dev/null +++ b/Code/BF2/Core/StringTokenizer.h @@ -0,0 +1,66 @@ +// A character-set string tokenizer. BF2.exe 0x59E110 (destructor), 0x59E120 (assign), 0x59E1B0 +// (constructor), 0x59E1F0 (nextToken). [INFERRED] class, member and header names and placement: no +// symbol or __FILE__ string names this class. SwiffHost::parseResolution (0x489210) is the menu caller. +// +// Retail layout (x86, 0x40 bytes): +0x00 the text (a VC7.1 std::string), +0x1C a std::bitset<256> +// of delimiter characters, +0x3C the scan position. The native object keeps the same members with +// the native STL; nothing outside the owner reads them. +#ifndef CORE_STRINGTOKENIZER_H +#define CORE_STRINGTOKENIZER_H + +#include +#include + +namespace dice { +namespace hfe { + +class StringTokenizer +{ +public: + // 0x59E1B0: the bitset is zeroed (eight words), the position cleared, then assign(). + StringTokenizer(const std::string& text, const std::string& delimiters) + : m_position(0) + { + assign(text, delimiters); + } + + // 0x59E120: position 0, the text copied, then one bit set per delimiter byte. Bits already + // set by an earlier assign() are kept (the shipped body does not clear the set). + void assign(const std::string& text, const std::string& delimiters) + { + m_position = 0; + m_text = text; + for (std::string::size_type i = 0; i < delimiters.size(); ++i) + m_delimiters.set(static_cast(delimiters[i])); + } + + // 0x59E1F0: `token` is cleared first (std::string::clear). Delimiters are skipped; at the end of the text the answer + // is false and `token` stays empty. Otherwise the run up to the next delimiter (or the end) is + // copied out with substr and the answer is true. The position is left on the delimiter that + // ended the token, so the next call skips it. + bool nextToken(std::string& token) + { + token.clear(); + while (m_position < m_text.size() + && m_delimiters.test(static_cast(m_text[m_position]))) + ++m_position; + if (m_position >= m_text.size()) + return false; + const std::string::size_type start = m_position; + while (m_position < m_text.size() + && !m_delimiters.test(static_cast(m_text[m_position]))) + ++m_position; + token = m_text.substr(start, m_position - start); + return true; + } + +private: + std::string m_text; // retail +0x00 + std::bitset<256> m_delimiters; // retail +0x1C + std::string::size_type m_position; // retail +0x3C +}; + +} // namespace hfe +} // namespace dice + +#endif // CORE_STRINGTOKENIZER_H diff --git a/Code/BF2/Core/StringUtil.cpp b/Code/BF2/Core/StringUtil.cpp index 79aed2d31..6dc9df725 100644 --- a/Code/BF2/Core/StringUtil.cpp +++ b/Code/BF2/Core/StringUtil.cpp @@ -1,6 +1,9 @@ // Shared string comparisons, hashing, formatting and path helpers. // Source path is attested by anonymous-namespace symbols. +#if defined(__APPLE__) +#include +#endif #include "StringUtil.h" #include // formatString is variadic @@ -8,6 +11,7 @@ #include // vsnprintf / sprintf #include #include +#include "MsvcCrtCompat.h" // [CHOSEN, not recovered] _vsnwprintf/_swprintf outside MSVC #ifdef _MSC_VER # include @@ -17,16 +21,123 @@ # include #endif +namespace { + +// ELF 0x48BE30 (string), 0x48C420 (wstring); engine ELF 0x83D1510/0x83D1A40. +// PE 0x100757A0, 0x10075580: the wstring and string instantiations. +template +String extractFileExt_internal(const String& path) +{ + typedef typename String::value_type Char; + const int dot = static_cast(path.rfind(static_cast('.'))); + if (dot == -1 || (dot > 1 && path[dot - 1] == static_cast('.'))) + return String(); + return path.substr(dot + 1); +} + +// ELF 0x48BEF0 (string), 0x48C4E0 (wstring); engine ELF 0x83D15B0/0x83D1AE0. +// PE 0x10075800, 0x10075600: the wstring and string instantiations. +template +String extractFileName_internal(const String& path) +{ + typedef typename String::value_type Char; + int last = static_cast(path.rfind(static_cast('\\'))); + const int slash = static_cast(path.rfind(static_cast('/'))); + if (slash > last) last = slash; + return last == -1 ? path : path.substr(last + 1); +} + +// ELF 0x48BFB0 (string), 0x48C5A0 (wstring); engine ELF 0x83D1660/0x83D1B90. +// PE 0x10075870, 0x10075680: the wstring and string instantiations. +template +String extractFilePath_internal(const String& path, Char delimiter) +{ + int last = static_cast(path.rfind(static_cast('\\'))); + const int slash = static_cast(path.rfind(static_cast('/'))); + if (slash > last) last = slash; + if (last == -1) return String(); + return path.substr(0, last) + delimiter; +} + +// ELF 0x48C0A0 (string), 0x48C690 (wstring); engine ELF 0x83D1740/0x83D1C70; RendDX9.dll PE 0x10075970 (string). +// PE 0x100759E0: wstring. +template +String extractFileNameWithoutExt_internal(const String& path) +{ + const String name = dice::hfe::extractFileName(path); + const int dot = static_cast(name.rfind(static_cast('.'))); + return dot == -1 ? name : name.substr(0, dot); +} + +// ELF 0x48C160 (string), 0x48C750 (wstring); engine ELF 0x83D17F0/0x83D1D20. +// PE 0x10075B50: wstring. +template +String extractEverythingExceptExt_internal(const String& path) +{ + typedef typename String::value_type Char; + const String normalized = dice::hfe::getFixPathDelimiters(path, static_cast('/')); + const int dot = static_cast(normalized.rfind(static_cast('.'))); + return dot == -1 ? normalized : normalized.substr(0, dot); +} + +// ELF 0x48C230 (string), 0x48C820 (wstring); engine ELF 0x83D18A0/0x83D1DD0; RendDX9.dll PE 0x100752C0 (string). +// PE 0x10075350: wstring. +template +void fixPath_internal(String& path, Char delimiter) +{ + if (!path.empty()) + { + dice::hfe::fixPathDelimiters(path, delimiter); + if (path[path.length() - 1] != delimiter) + path.append(1, delimiter); + } +} + +// ELF 0x48C2D0 (string), 0x48C8A0 (wstring); engine ELF 0x83D1920/0x83D1E50. +// PE 0x10075910: wstring. +template +void fixPathDelimiters_internal(String& path, Char delimiter) +{ + const typename String::size_type length = path.length(); + for (typename String::size_type i = 0; i < length; ++i) + if (path[i] == static_cast('/') || path[i] == static_cast('\\')) + path[i] = delimiter; +} + +// ELF 0x48C380 (string), 0x48C950 (wstring); engine ELF 0x83D19C0/0x83D1EF0. +// PE 0x10075AE0, 0x10075BE0: string and wstring instantiations. +template +String getFixPath_internal(const String& path, Char delimiter) +{ + String result(path); + dice::hfe::fixPath(result, delimiter); + return result; +} + +// ELF 0x48C3D0 (string), 0x48C9A0 (wstring); engine ELF 0x83D1A00/0x83D1F30. +// PE 0x10075300, 0x10075390: string and wstring instantiations. +template +String getFixPathDelimiters_internal(const String& path, Char delimiter) +{ + String result(path); + dice::hfe::fixPathDelimiters(result, delimiter); + return result; +} + +} // anonymous namespace + namespace dice { namespace hfe { +// ELF 0x48A920. +// static init: ELF 0x48BDE0 (getEmptyString's local static teardown). const std::string& getEmptyString() { static const std::string empty; return empty; } -// Converts wide text using the active C locale. The existing error check tests count + 1, +// ELF 0x48BA40; RendDX9.dll PE 0x10075430. Converts wide text using the active C locale. The existing error check tests count + 1, // so callers must not rely on it to reject every invalid conversion. std::string makeNarrow(const std::wstring& source) { @@ -42,7 +153,7 @@ std::string makeNarrow(const std::wstring& source) return std::string(buffer.data(), converted); } -// Converts multibyte text to wide characters using the active C locale. +// ELF 0x48BCA0. Converts multibyte text to wide characters using the active C locale. std::wstring makeWide(const std::string& source) { const std::size_t capacity = std::mbstowcs(0, source.c_str(), 0) + 1; @@ -57,7 +168,16 @@ std::wstring makeWide(const std::string& source) return result; } -// Formats into a shared 4-KB buffer and returns a string copy; not reentrant or thread-safe. +// Engine ELF 0x83D0340 (dice::hfe::stringToFloat(std::string const&): atof(c_str()), narrowed +// through fstps/flds); RendDX9.dll PE 0x1007B290 (atof on the SSO buffer or the heap pointer by +// capacity +0x18 >= 16, ST0 returned without a narrowing store: VC7.1 keeps the float return in +// the x87 register, the caller narrows at its store). +float stringToFloat(const std::string& s) +{ + return static_cast(std::atof(s.c_str())); +} + +// ELF 0x48A990; RendDX9.dll PE 0x10074AB0 (the same body over .data 0x10244AF8). Formats into a shared 4-KB buffer and returns a string copy; not reentrant or thread-safe. // A negative vsnprintf result replaces the message with a warning. Successful formatting writes // the terminator at the reported length. Preserve the original runtime-dependent overflow behavior. std::string formatString(const char* fmt, ...) @@ -79,9 +199,29 @@ std::string formatString(const char* fmt, ...) return std::string(s_buffer); } +// ELF 0x48AA30; engine ELF 0x83D0440. +std::wstring formatWstring(const wchar_t* fmt, ...) +{ + static wchar_t buffer[4096]; + va_list args; + va_start(args, fmt); + const int count = std::vswprintf(buffer, 0xFFF, fmt, args); + va_end(args); + if (count == -1) + { + // shipped defect: POSIX %s reads the wide warning as narrow bytes, producing only "W". + std::swprintf(buffer, 0x1000, L"%s", + L"WARNING: The original message was too long for formatString(). \n"); + } + else + buffer[count] = 0; + return std::wstring(buffer); +} + #if !DEDICATED // Client PE 431130, all 29 instructions read. Buffer 99C158 is shared, and // _vsnwprintf's -1 result replaces the whole message with the shipped warning. +// PE 0x10074B10: own buffer 0x10245AF8. std::wstring formatString(const wchar_t* fmt, ...) { static wchar_t buffer[4096]; @@ -98,38 +238,80 @@ std::wstring formatString(const wchar_t* fmt, ...) } #endif -// Compares null-terminated strings without case. String overloads delegate through c_str(). +// ELF 0x48AB30. Compares null-terminated strings without case. String overloads delegate through c_str(). int compareIgnoreCase(const char* a, const char* b) { return strcasecmp(a, b); } +// ELF 0x48ABD0. +// PE 0x10074B80 int compareIgnoreCase(const char* a, const char* b, int n) { + if (n == 0) + return 0; return strncasecmp(a, b, n); } +// ELF 0x48AAD0. int compareIgnoreCase(const std::string& a, const std::string& b) { return compareIgnoreCase(a.c_str(), b.c_str()); } +// ELF 0x48AB60. +// PE 0x10075040 int compareIgnoreCase(const std::string& a, const std::string& b, int n) { return compareIgnoreCase(a.c_str(), b.c_str(), n); } +// ELF 0x48AC10; RendDX9.dll PE 0x10075080 (the compare inlined: `_stricmp` on the two c_str()s). bool equalsIgnoreCase(const std::string& a, const std::string& b) { return compareIgnoreCase(a, b) == 0; } +// ELF 0x48AC50. +// PE 0x100750C0 bool equalsIgnoreCase(const std::string& a, const std::string& b, int n) { return compareIgnoreCase(a, b, n) == 0; } -// Returns the engine's case-insensitive hash using ASCII-only uppercase folding. +// ELF 0x48AC90; engine ELF 0x83D0600. amd-64 preserves the full size_type return. +std::string::size_type lowerCaseFind(const std::string& text, const std::string& pattern) +{ + std::string loweredText(text); + std::string loweredPattern(pattern); + setLowerCase(loweredText); + setLowerCase(loweredPattern); + return loweredText.find(loweredPattern); +} + +// ELF 0x48AD60; engine ELF 0x83D06B0; RendDX9.dll PE 0x10074BA0. +void eraseSubString(std::string& text, const std::string& pattern) +{ + const std::string::size_type at = text.find(pattern); + if (at != std::string::npos) + text.erase(at, pattern.length()); +} + +// ELF 0x48B9A0; engine ELF 0x83D10F0. Both images explicitly return the input pointer. +// PE 0x10074F60 +std::string* replaceAll(std::string* text, const std::string& pattern, const std::string& replacement) +{ + std::string::size_type at = 0; + while ((at = text->find(pattern, at)) != std::string::npos) + { + text->replace(at, pattern.length(), replacement); + // Read the replacement length after the mutation too, preserving argument aliasing. + at += replacement.length(); + } + return text; +} + +// ELF 0x487AF0. Returns the engine's case-insensitive hash using ASCII-only uppercase folding. // Preserve its constants and shifts because bucket order affects duplicate selection. unsigned int calcStringHashValueNoCase(const std::string& s) { @@ -157,7 +339,7 @@ unsigned int calcStringHashValueNoCase(const std::string& s) return (hash >> 16) + hash; // hiword(hash) + hash } -// Reports whether the virtual-filesystem path is absolute under the selected platform rules. +// ELF 0x48B910. Reports whether the virtual-filesystem path is absolute under the selected platform rules. // [PLATFORM] POSIX requires a leading slash; Windows searches for :\ or :/ anywhere in the string. // Leading slash alone is relative on Windows, allowing engine search-path resolution. bool isPathAbsolute(const std::string& s) @@ -169,41 +351,60 @@ bool isPathAbsolute(const std::string& s) #endif } +#if defined(__APPLE__) && !DEDICATED +// [CHOSEN, not recovered] macOS client port. On Windows +// isPathAbsolute only accepts drive paths, so game paths such as "/Levels/..." (SwiffPlayer) or +// "/objects/..." (SF and booster mesh texture names) are relative. On a POSIX host every '/' path +// would count as absolute; host-absolute paths in the client come from the absolute @HOME@ +// substitution (or a developer's own absolute path) and are told apart by a first component that +// exists at the host root. +bool isHostAbsolutePath(const std::string& path) +{ + if (!isPathAbsolute(path)) + return false; + const std::string::size_type end = path.find('/', 1); + const std::string first = path.substr(0, end); + struct stat st; + return first.size() > 1 && ::stat(first.c_str(), &st) == 0; +} +#endif + // Normalizes both slash forms to c. fixPath additionally ensures a trailing separator; // both preserve an empty string as empty. +// ELF 0x48B3E0. void fixPathDelimiters(std::string& s, char c) { - for (std::string::size_type i = 0; i < s.size(); ++i) - if (s[i] == '/' || s[i] == '\\') - s[i] = c; + fixPathDelimiters_internal(s, c); } +// ELF 0x48B3B0. void fixPath(std::string& s, char c) { - if (s.empty()) - return; // guarded - "" stays "" - - fixPathDelimiters(s, c); - - if (s[s.size() - 1] != c) - s.append(1, c); // guarantee the trailing separator + fixPath_internal(s, c); } +// ELF 0x48B460. std::string getFixPathDelimiters(const std::string& s, char c) { - std::string out(s); - fixPathDelimiters(out, c); - return out; + return getFixPathDelimiters_internal(s, c); } +// ELF 0x48B410. +// PE 0x100753E0: hidden-result wrapper over 0x10075AE0. std::string getFixPath(const std::string& s, char c) { - std::string out(s); - fixPath(out, c); - return out; + return getFixPath_internal(s, c); } -// Wide-character helper counterparts remain [UNRESOLVED]; the narrow implementations follow below. +// ELF 0x48B600; engine ELF 0x83D0DF0. +void fixPath(std::wstring& s, wchar_t c) { fixPath_internal(s, c); } +// ELF 0x48B630; engine ELF 0x83D0E00. +void fixPathDelimiters(std::wstring& s, wchar_t c) { fixPathDelimiters_internal(s, c); } +// ELF 0x48B660; engine ELF 0x83D0E10. +// PE 0x10075410: hidden-result wrapper over 0x10075BE0. +std::wstring getFixPath(const std::wstring& s, wchar_t c) { return getFixPath_internal(s, c); } +// ELF 0x48B6B0; engine ELF 0x83D0E40. +std::wstring getFixPathDelimiters(const std::wstring& s, wchar_t c) { return getFixPathDelimiters_internal(s, c); } // Changes case using explicit Latin-1 pairs for Ã¥/Ã…, ä/Ä, ö/Ö, ü/Ü and é/É before CRT fallback. // Keep these mappings independent of the active locale; archive and content lookup depend on them. @@ -227,7 +428,7 @@ const unsigned int kLatin1CasePairCount = sizeof(kLatin1CasePairs) / sizeof(kLat } // anonymous namespace -// Uppercases text in place, handling the explicit extended-character pairs before toupper. +// ELF 0x48AE00. Uppercases text in place, handling the explicit extended-character pairs before toupper. void setUpperCase(std::string& s) { for (std::string::size_type i = 0; i < s.size(); ++i) @@ -249,7 +450,7 @@ void setUpperCase(std::string& s) } } -// The exact mirror - same five pairs, tested upper-first. +// ELF 0x48AFF0. The exact mirror - same five pairs, tested upper-first. void setLowerCase(std::string& s) { for (std::string::size_type i = 0; i < s.size(); ++i) @@ -277,6 +478,7 @@ void setLowerCase(std::string& s) // settles it in the opposite direction. Here the body constructs into the hidden sret pointer // (`std::string::string(this, a2)` where `this` is the return slot) and hands that back. A // reference-returning function has nothing to construct. +// ELF 0x48B1E0. std::string getUpperCase(const std::string& s) { std::string result(s); @@ -284,6 +486,7 @@ std::string getUpperCase(const std::string& s) return result; } +// ELF 0x48B220; RendDX9.dll PE 0x10074E80. std::string getLowerCase(const std::string& s) { std::string result(s); @@ -291,64 +494,48 @@ std::string getLowerCase(const std::string& s) return result; } -// Returns the directory through the last slash of either kind, using delimiter for the trailing separator. +// ELF 0x48B2E0. Returns the directory through the last slash of either kind, using delimiter for the trailing separator. // Returns an empty string when no separator exists. +// PE 0x100751A0: hidden-result wrapper over 0x10075680. std::string extractFilePath(const std::string& path, char delimiter) { - std::string::size_type last = path.rfind('\\'); - const std::string::size_type slash = path.rfind('/'); - if (slash != std::string::npos && (last == std::string::npos || slash > last)) - last = slash; - if (last == std::string::npos) - return std::string(); - - std::string out = path.substr(0, last); - out.append(1, delimiter); - return out; + return extractFilePath_internal(path, delimiter); } -// Returns text after the last dot, or empty for no dot/trailing dot. +// ELF 0x48B260; RendDX9.dll PE 0x10075180 (hidden-result wrapper over 0x10075580). Returns text +// after the last dot, or empty for no dot/trailing dot. // A preceding dot suppresses extensions only when the last dot is at index 2 or later: // ..x yields x, while a..x yields empty. std::string extractFileExt(const std::string& path) { - const std::string::size_type dot = path.rfind('.'); - if (dot == std::string::npos) - return std::string(); - - if (dot > 1 && path[dot - 1] == '.') - return std::string(); - - return path.substr(dot + 1); + return extractFileExt_internal(path); } -// Normalizes repeated separators, strips a leading slash and recursively collapses /../ segments. -// Traversal beyond the beginning is absorbed rather than rejected; this is not a containment check. -// [CHOSEN, not recovered] removeDoubleSlashes still requires direct binary verification, including -// backslash and leading-double-slash behavior. +// ELF 0x48B870; engine ELF 0x83D0FD0; RendDX9.dll PE 0x10074EC0 (the recursion is a loop there). void removeDoubleSlashes(std::string& path) { - std::string::size_type at = path.find("//"); - while (at != std::string::npos) + const std::string::size_type at = path.find("//"); + if (at != std::string::npos) { path.erase(at, 1); - at = path.find("//", at); + removeDoubleSlashes(path); } } -void goUpInPath(std::string& path) +namespace { +// ELF 0x48B700; engine ELF 0x83D0E70; RendDX9.dll PE 0x10075220. +void goUpInPath_worker(std::string& path) { removeDoubleSlashes(path); if (!path.empty() && path[0] == '/') - path.erase(0, 1); // absolute becomes relative - see above + path.erase(0, 1); const std::string::size_type found = path.find("/../"); if (found == std::string::npos) return; - std::string::size_type start = (found == 0) ? std::string::npos - : path.rfind('/', found - 1); + std::string::size_type start = path.rfind("/", found - 1); if (start == std::string::npos) start = 0; @@ -358,33 +545,64 @@ void goUpInPath(std::string& path) path.erase(start, count); - goUpInPath(path); // recurse until no "/../" remains + goUpInPath_worker(path); +} +} // anonymous namespace + +// ELF 0x48B930; engine ELF 0x83D1090: isPathAbsolute, the worker, then "/" re-inserted for an +// absolute path (on ELF exactly a path with a leading '/'). +// PE BF2.exe 0x00431BE0: a jump to the worker 0x00431B60, no restore. Drive paths never had a +// leading '/', and a game path's leading '/' is dropped, which is what lets "/objects/..." +// texture names (SF and booster meshes) resolve in the archives mounted at "objects/". +void goUpInPath(std::string& path) +{ +#if defined(_WIN32) + goUpInPath_worker(path); +#else +#if defined(__APPLE__) && !DEDICATED + // [PLATFORM] the client keeps the Windows meaning for game paths; only host-absolute paths + // (isHostAbsolutePath) get their '/' back. + const bool absolute = isHostAbsolutePath(path); +#else + const bool absolute = isPathAbsolute(path); +#endif + goUpInPath_worker(path); + if (absolute) + path.insert(0, "/"); +#endif } -// Returns the final path component without its last extension. Names without a dot remain unchanged. +// ELF 0x48B330; RendDX9.dll PE 0x100752B0 (hidden-result wrapper over 0x10075970). Returns the final path component without its last extension. Names without a dot remain unchanged. std::string extractFileNameWithoutExt(const std::string& path) { - const std::string name = extractFileName(path); - const std::string::size_type dot = name.rfind('.'); - if (dot == std::string::npos) - return name; - return name.substr(0, dot); + return extractFileNameWithoutExt_internal(path); } -// Returns the component after the last slash of either kind. A trailing slash produces an empty name. +// ELF 0x48B2A0. Returns the component after the last slash of either kind. A trailing slash produces an empty name. +// PE 0x10075190: hidden-result wrapper over 0x10075600. std::string extractFileName(const std::string& path) { - const std::string::size_type backslash = path.rfind('\\'); - const std::string::size_type slash = path.rfind('/'); - - std::string::size_type last = backslash; - if (slash != std::string::npos && (last == std::string::npos || slash > last)) - last = slash; - - if (last == std::string::npos) - return path; - return path.substr(last + 1); + return extractFileName_internal(path); } + +// ELF 0x48B370; engine ELF 0x83D0C30. +std::string extractEverythingExceptExt(const std::string& path) { return extractEverythingExceptExt_internal(path); } +// ELF 0x48B4B0; engine ELF 0x83D0D00. +// PE 0x100751D0: hidden-result wrapper over 0x100757A0. +std::wstring extractFileExt(const std::wstring& path) { return extractFileExt_internal(path); } +// ELF 0x48B4F0; engine ELF 0x83D0D30. +// PE 0x100751E0: hidden-result wrapper over 0x10075800. +std::wstring extractFileName(const std::wstring& path) { return extractFileName_internal(path); } +// ELF 0x48B530; engine ELF 0x83D0D60. +// PE 0x100751F0: hidden-result wrapper over 0x10075870. +std::wstring extractFilePath(const std::wstring& path, wchar_t c) { return extractFilePath_internal(path, c); } +// ELF 0x48B580; engine ELF 0x83D0D90. +// PE 0x10075340: hidden-result wrapper over 0x100759E0. +std::wstring extractFileNameWithoutExt(const std::wstring& path) { return extractFileNameWithoutExt_internal(path); } +// ELF 0x48B5C0; engine ELF 0x83D0DC0. +// PE 0x10075400: hidden-result wrapper over 0x10075B50. +std::wstring extractEverythingExceptExt(const std::wstring& path) { return extractEverythingExceptExt_internal(path); } // Converts multibyte text to wide characters; failed conversion returns an empty string. +// PE 0x100754F0 std::wstring toWideString(const std::string& s) { const size_t count = mbstowcs(0, s.c_str(), 0) + 1; // + terminator; 0 on an invalid sequence diff --git a/Code/BF2/Core/StringUtil.h b/Code/BF2/Core/StringUtil.h index ca578fc99..6c7b6875d 100644 --- a/Code/BF2/Core/StringUtil.h +++ b/Code/BF2/Core/StringUtil.h @@ -1,5 +1,4 @@ // Engine string/path helpers from the attested Core/StringUtil.cpp translation unit. -// This header declares narrow-string helpers; the original also instantiates wide counterparts. #ifndef CORE_STRINGUTIL_H // [INFERRED] guard style #define CORE_STRINGUTIL_H @@ -9,8 +8,9 @@ namespace dice { namespace hfe { -// Formats printf-style arguments into a string. [UNRESOLVED] Original return type beyond observed string consumers. +// Formats printf-style arguments in a shared buffer and returns a copy; not thread-safe. std::string formatString(const char* fmt, ...); +std::wstring formatWstring(const wchar_t* fmt, ...); #if !DEDICATED // Client PE 431130: wide overload, including the shared buffer and overflow warning. // [INFERRED] overload spelling; the dedicated ELF has no HUD caller for it. @@ -20,6 +20,9 @@ std::wstring formatString(const wchar_t* fmt, ...); // Converts multibyte text to wide characters, returning an empty string on failure. [INFERRED] Name. std::wstring toWideString(const std::string& s); +// atof over the text; no error reporting (unparsable text answers 0). +float stringToFloat(const std::string& s); + // Case-insensitive comparison // Four overloads exist. The (const char*, const char*) form is a straight strcasecmp; the // std::string forms null-terminate their operands first and then delegate to it. @@ -30,6 +33,12 @@ int compareIgnoreCase(const std::string& a, const std::string& b, int n); bool equalsIgnoreCase(const std::string& a, const std::string& b); bool equalsIgnoreCase(const std::string& a, const std::string& b, int n); +std::string::size_type lowerCaseFind(const std::string& text, const std::string& pattern); +// Removes only the first occurrence, if any. +void eraseSubString(std::string& text, const std::string& pattern); +// Replaces matches in place and returns text; text must be non-null. +// An empty pattern has no terminating case. +std::string* replaceAll(std::string* text, const std::string& pattern, const std::string& replacement); // Case conversion // The set* forms are 479 bytes each - they go through the locale, not a naive toupper loop. @@ -53,11 +62,21 @@ void fixPathDelimiters(std::string&, char); void fixPath(std::string&, char); std::string getFixPathDelimiters(const std::string&, char); std::string getFixPath(const std::string&, char); +void fixPathDelimiters(std::wstring&, wchar_t); +void fixPath(std::wstring&, wchar_t); +std::wstring getFixPathDelimiters(const std::wstring&, wchar_t); +std::wstring getFixPath(const std::wstring&, wchar_t); bool isPathAbsolute(const std::string&); -// Normalizes repeated path separators before parent traversal. -// [CHOSEN, not recovered] The helper body still needs direct binary verification. +#if defined(__APPLE__) && !DEDICATED +// [CHOSEN, not recovered] macOS client: a '/' path whose first component exists at the host root +// ("/Users", "/private", "/Volumes", ...). Game paths with a leading '/' keep the Windows meaning. +bool isHostAbsolutePath(const std::string&); +#endif +// Recursively removes doubled forward slashes; backslashes are unchanged. void removeDoubleSlashes(std::string&); +// Collapses /../ segments and repeated forward slashes, preserving an absolute leading slash. +// Traversal beyond the beginning is absorbed; this is not a containment check. void goUpInPath(std::string&); std::string extractFilePath(const std::string&, char); @@ -65,6 +84,11 @@ std::string extractFileName(const std::string&); std::string extractFileNameWithoutExt(const std::string&); std::string extractFileExt(const std::string&); std::string extractEverythingExceptExt(const std::string&); // internal 0x83d17f0 +std::wstring extractFilePath(const std::wstring&, wchar_t); +std::wstring extractFileName(const std::wstring&); +std::wstring extractFileNameWithoutExt(const std::wstring&); +std::wstring extractFileExt(const std::wstring&); +std::wstring extractEverythingExceptExt(const std::wstring&); // Misc // Returns a shared empty std::string. Used as a sentinel return by FileManager::fileExistsEx and diff --git a/Code/BF2/Core/System.cpp b/Code/BF2/Core/System.cpp index ae1f0ac42..748ff6cbe 100644 --- a/Code/BF2/Core/System.cpp +++ b/Code/BF2/Core/System.cpp @@ -43,6 +43,12 @@ inline unsigned long long rdtsc() { #if defined(_WIN32) return __rdtsc(); +#elif defined(__aarch64__) + // [CHOSEN, not recovered] arm64 macOS port (untested): the generic timer's virtual count is + // the constant-rate counter that stands in for the TSC; callers calibrate its frequency. + unsigned long long count; + __asm__ __volatile__("mrs %0, cntvct_el0" : "=r"(count)); + return count; #else unsigned int lo, hi; __asm__ __volatile__("rdtsc" : "=a"(lo), "=d"(hi)); diff --git a/Code/BF2/Core/WeakPtr.h b/Code/BF2/Core/WeakPtr.h index dfe7aa952..1314eec03 100644 --- a/Code/BF2/Core/WeakPtr.h +++ b/Code/BF2/Core/WeakPtr.h @@ -32,6 +32,7 @@ class WeakPtr releaseControl(m_ctrl); } + // PE 0x101326F0: the IPlayer specialization; the other retail copies are identical. WeakPtr& operator=(const WeakPtr& other) { // Both recovered assignment specializations retain the incoming block first. This also diff --git a/Code/BF2/External/BFMeme/Action.cpp b/Code/BF2/External/BFMeme/Action.cpp index 96191df85..769760650 100644 --- a/Code/BF2/External/BFMeme/Action.cpp +++ b/Code/BF2/External/BFMeme/Action.cpp @@ -12,6 +12,8 @@ TypeDescriptor* Action::getClassType() TypeDescriptor* Action::getType() { return getClassType(); } unsigned int Action::getObjectSize() { return sizeof(Action); } bool Action::execute(System*, const Rect*, const NodeState*, const NodeInputEvent*) { return false; } +#if defined(_M_IX86) static_assert(sizeof(Action) == 4, "BFMeme Action layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/ActionListAction.cpp b/Code/BF2/External/BFMeme/ActionListAction.cpp index aa9563116..458646439 100644 --- a/Code/BF2/External/BFMeme/ActionListAction.cpp +++ b/Code/BF2/External/BFMeme/ActionListAction.cpp @@ -36,6 +36,8 @@ bool ActionListAction::execute(System* system, const Rect* bounds, const NodeSta } return false; } +#if defined(_M_IX86) static_assert(sizeof(ActionListAction) == 24, "client ActionListAction"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/ActionNode.cpp b/Code/BF2/External/BFMeme/ActionNode.cpp index b8718e954..109fc91ae 100644 --- a/Code/BF2/External/BFMeme/ActionNode.cpp +++ b/Code/BF2/External/BFMeme/ActionNode.cpp @@ -31,7 +31,9 @@ class ActionNodeTypeDescriptor final : public TypeDescriptor int getInstanceCount() override { return actionNodeInstances; } unsigned int getInstanceSize() override { return sizeof(ActionNode); } }; +#if defined(_M_IX86) static_assert(sizeof(ActionNodeTypeDescriptor) == 16, "ActionNode metadata storage"); +#endif } ActionNode::ActionNode() : m_action(nullptr) {} @@ -71,6 +73,8 @@ bool ActionNode::updateSelf(System* system, const NodeState* state, return true; } +#if defined(_M_IX86) static_assert(sizeof(ActionNode) == 12, "client BFMeme ActionNode"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/AlphaFadeEffect.cpp b/Code/BF2/External/BFMeme/AlphaFadeEffect.cpp index bbe29c4f1..ff27af05e 100644 --- a/Code/BF2/External/BFMeme/AlphaFadeEffect.cpp +++ b/Code/BF2/External/BFMeme/AlphaFadeEffect.cpp @@ -1,14 +1,21 @@ // Path [INFERRED]. All primary/metadata targets, eager/factory and differing // bodies read from the client PE before implementation. See the status document. #include "AlphaFadeEffect.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../../Math/PortableX87.h" +#endif #if !DEDICATED #include "Node.h" #include "Quad.h" #include "TypeDescriptor.h" +#if !defined(_M_IX86) +#include +#include +#endif namespace dice { namespace meme { namespace { -int alphaFadeEffectInstances = 0; // A39FC0, loader-zeroed +int alphaFadeEffectInstances = 0; // A39FC0, loader-zeroed // Concrete descriptor spelling [INFERRED]; complete table94DCD8. class AlphaFadeEffectTypeDescriptor : public TypeDescriptor { @@ -31,6 +38,8 @@ class AlphaFadeEffectTypeDescriptor : public TypeDescriptor // native mulss does not reproduce that case. Both operands are loaded afresh. void multiplyAlpha(float* alpha, const float* factor) { +#if defined(_WIN32) +#if defined(_M_IX86) __asm { mov edx, factor mov eax, alpha @@ -38,6 +47,29 @@ void multiplyAlpha(float* alpha, const float* factor) fmul dword ptr [eax] fstp dword ptr [eax] } +#else + // [PLATFORM] x64: SSE2 arithmetic. The product of two floats is exact in double, so the + // single float rounding matches. The two-NaN case is selected explicitly: fld quiets the + // factor, and a quiet alpha NaN with a larger significand wins over it, as in x87. + const float first = *factor; + const float second = *alpha; + std::uint32_t firstBits, secondBits; + std::memcpy(&firstBits, &first, sizeof firstBits); + std::memcpy(&secondBits, &second, sizeof secondBits); + if ((firstBits & 0x7FFFFFFFu) > 0x7F800000u && (secondBits & 0x7FFFFFFFu) > 0x7F800000u) { + std::uint32_t result = firstBits | 0x00400000u; + if ((secondBits & 0x00400000u) && (secondBits & 0x007FFFFFu) > (result & 0x007FFFFFu)) + result = secondBits; + std::memcpy(alpha, &result, sizeof result); + return; + } + *alpha = static_cast(static_cast(first) * second); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-port.md). + // [CHOSEN, not recovered] Preserve x87 load, two-NaN payload selection and float store. + *alpha = bf2x87::multiply(*factor, *alpha); +#endif } } @@ -53,7 +85,7 @@ namespace { TypeDescriptor* const registeredAlphaFadeEffectType = AlphaFadeEffect::getClassType(); } -bool AlphaFadeEffect::drawCharacter(System* system, int character, int font, +bool AlphaFadeEffect::drawCharacter(System* system, int character, FontHandle font, int elementIndex, Quad* quad, RenderContext* context) { // each component is read, multiplied and stored as float32 before @@ -62,7 +94,7 @@ bool AlphaFadeEffect::drawCharacter(System* system, int character, int font, multiplyAlpha(&corner.color.a, &context->field18); return Effect::drawCharacter(system, character, font, elementIndex, quad, context); } -bool AlphaFadeEffect::drawTexture(System* system, int texture, Quad* quad, +bool AlphaFadeEffect::drawTexture(System* system, TextureHandle texture, Quad* quad, RenderContext* context) { for (auto& corner : quad->corners) @@ -70,6 +102,8 @@ bool AlphaFadeEffect::drawTexture(System* system, int texture, Quad* quad, return Effect::drawTexture(system, texture, quad, context); } +#if defined(_M_IX86) static_assert(sizeof(AlphaFadeEffect) == 4, "Native x86 AlphaFadeEffect allocation"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/AlphaFadeEffect.h b/Code/BF2/External/BFMeme/AlphaFadeEffect.h index 6e1c7ea2f..d4ecaf24e 100644 --- a/Code/BF2/External/BFMeme/AlphaFadeEffect.h +++ b/Code/BF2/External/BFMeme/AlphaFadeEffect.h @@ -11,9 +11,9 @@ class AlphaFadeEffect : public Effect // Inlined83581E/79DD40 construction installs only the primary; no fields. AlphaFadeEffect() = default; TypeDescriptor* getType() override; - bool drawCharacter(System*, int character, int font, int elementIndex, + bool drawCharacter(System*, int character, FontHandle font, int elementIndex, Quad*, RenderContext*) override; // +4C 834F10 - bool drawTexture(System*, int texture, Quad*, RenderContext*) override; + bool drawTexture(System*, TextureHandle texture, Quad*, RenderContext*) override; static TypeDescriptor* getClassType(); }; } } diff --git a/Code/BF2/External/BFMeme/AndData.cpp b/Code/BF2/External/BFMeme/AndData.cpp index 076f196af..47bc039d7 100644 --- a/Code/BF2/External/BFMeme/AndData.cpp +++ b/Code/BF2/External/BFMeme/AndData.cpp @@ -27,7 +27,9 @@ float AndData::getFloat(System* system) return m_second->getFloat(system) != 0.0f ? 1.0f : 0.0f; } +#if defined(_M_IX86) static_assert(sizeof(AndData) == 16, "client BFMeme AndData"); static_assert(sizeof(ClassTypeDescriptor) == 16, "AndData metadata"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/BlendFuncEffect.cpp b/Code/BF2/External/BFMeme/BlendFuncEffect.cpp index ef5d5d7b4..ef433a192 100644 --- a/Code/BF2/External/BFMeme/BlendFuncEffect.cpp +++ b/Code/BF2/External/BFMeme/BlendFuncEffect.cpp @@ -54,7 +54,7 @@ bool BlendFuncEffect::streamProperties(System* system, Stream* stream) "Destination blend func"); } -bool BlendFuncEffect::drawCharacter(System* system, int character, int font, +bool BlendFuncEffect::drawCharacter(System* system, int character, FontHandle font, int elementIndex, Quad* quad, RenderContext* context) { // Both words are stamped before the chain continues; retail inlines @@ -63,7 +63,7 @@ bool BlendFuncEffect::drawCharacter(System* system, int character, int font, quad->state0c = m_destination; return Effect::drawCharacter(system, character, font, elementIndex, quad, context); } -bool BlendFuncEffect::drawTexture(System* system, int texture, Quad* quad, +bool BlendFuncEffect::drawTexture(System* system, TextureHandle texture, Quad* quad, RenderContext* context) { quad->state08 = m_source; @@ -71,6 +71,8 @@ bool BlendFuncEffect::drawTexture(System* system, int texture, Quad* quad, return Effect::drawTexture(system, texture, quad, context); } +#if defined(_M_IX86) static_assert(sizeof(BlendFuncEffect) == 12, "PE BlendFuncEffect allocation"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/BlendFuncEffect.h b/Code/BF2/External/BFMeme/BlendFuncEffect.h index fb709c417..076d882de 100644 --- a/Code/BF2/External/BFMeme/BlendFuncEffect.h +++ b/Code/BF2/External/BFMeme/BlendFuncEffect.h @@ -24,9 +24,9 @@ class BlendFuncEffect : public Effect TypeDescriptor* getType() override; unsigned int getObjectSize() override; bool streamProperties(System*, Stream*) override; - bool drawCharacter(System*, int character, int font, int elementIndex, + bool drawCharacter(System*, int character, FontHandle font, int elementIndex, Quad*, RenderContext*) override; - bool drawTexture(System*, int texture, Quad*, RenderContext*) override; + bool drawTexture(System*, TextureHandle texture, Quad*, RenderContext*) override; static TypeDescriptor* getClassType(); // 8396E0, metadata94EB38 protected: // Both are written straight into the quad's two state words; the class diff --git a/Code/BF2/External/BFMeme/BoolData.cpp b/Code/BF2/External/BFMeme/BoolData.cpp index a5b7d8fdd..1ca27b93a 100644 --- a/Code/BF2/External/BFMeme/BoolData.cpp +++ b/Code/BF2/External/BFMeme/BoolData.cpp @@ -50,7 +50,9 @@ int BoolData::getCharacter(System*, int character) return (value ? "true" : "false")[character]; } +#if defined(_M_IX86) static_assert(sizeof(BoolData) == 12, "client BFMeme BoolData"); static_assert(sizeof(ClassTypeDescriptor) == 16, "BoolData metadata"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/CallFunctionAction.cpp b/Code/BF2/External/BFMeme/CallFunctionAction.cpp index 93f3f40e9..96a486765 100644 --- a/Code/BF2/External/BFMeme/CallFunctionAction.cpp +++ b/Code/BF2/External/BFMeme/CallFunctionAction.cpp @@ -32,6 +32,8 @@ bool CallFunctionAction::execute(System* system, const Rect*, const NodeState*, if (!m_function) return false; return m_function->call(system); } +#if defined(_M_IX86) static_assert(sizeof(CallFunctionAction) == 8, "client CallFunctionAction"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/ClassIStream.cpp b/Code/BF2/External/BFMeme/ClassIStream.cpp index 7ea2117d7..216571d4f 100644 --- a/Code/BF2/External/BFMeme/ClassIStream.cpp +++ b/Code/BF2/External/BFMeme/ClassIStream.cpp @@ -30,8 +30,8 @@ bool ForwardingIStream::streamInt(int* p, const char* label) { return m_input->s bool ForwardingIStream::streamString(char** p, const char* label) { return m_input->streamString(p,label); } bool ForwardingIStream::streamWideString(wchar_t** p, const char* label) { return m_input->streamWideString(p,label); } bool ForwardingIStream::streamCharacter(wchar_t* p, const char* label) { return m_input->streamCharacter(p,label); } -bool ForwardingIStream::streamTexture(System* s, int* p, const char* label) { return m_input->streamTexture(s,p,label); } -bool ForwardingIStream::streamFont(System* s, int* p, const char* label) { return m_input->streamFont(s,p,label); } +bool ForwardingIStream::streamTexture(System* s, TextureHandle* p, const char* label) { return m_input->streamTexture(s,p,label); } +bool ForwardingIStream::streamFont(System* s, FontHandle* p, const char* label) { return m_input->streamFont(s,p,label); } bool ForwardingIStream::streamSound(System* s, int* p, const char* label) { return m_input->streamSound(s,p,label); } bool ForwardingIStream::streamCollection(System* s, ObjectCollection* p, const char* label) { return m_input->streamCollection(s,p,label); } bool ForwardingIStream::streamEnum(int* p, EnumNext next, EnumName name, const char* label) { return m_input->streamEnum(p,next,name,label); } @@ -49,6 +49,14 @@ ClassIStream::~ClassIStream() char** entry = m_strings; while (*entry) { ::operator delete(*entry); *entry++ = nullptr; } } +// 83C2B0: guarded "dice::meme::ClassIStream" descriptor; base slot 83C1D0 jumps to IStream's +// getter, factory 83C1E0 allocates 0x814 bytes and runs ClassIStream(nullptr) inline. +TypeDescriptor* ClassIStream::getClassType() +{ + static ClassTypeDescriptor type("dice::meme::ClassIStream"); + return &type; +} +TypeDescriptor* ClassIStream::getType() { return getClassType(); } unsigned int ClassIStream::getObjectSize() { return sizeof(ClassIStream); } bool ClassIStream::init(System* system) { @@ -188,7 +196,9 @@ bool readObject(System* system, Object*& value, IStream* input) + static_cast(start))); // Return ignored; signed backward skip is possible. return true; } +#if defined(_M_IX86) static_assert(sizeof(ForwardingIStream) == 16, "forwarding input layout"); static_assert(sizeof(ClassIStream) == 0x814, "class input dictionary layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/ClassIStream.h b/Code/BF2/External/BFMeme/ClassIStream.h index 9a33a6d1b..70ecc68c6 100644 --- a/Code/BF2/External/BFMeme/ClassIStream.h +++ b/Code/BF2/External/BFMeme/ClassIStream.h @@ -21,8 +21,8 @@ class ForwardingIStream : public IStream bool streamString(char**, const char*) override; bool streamWideString(wchar_t**, const char*) override; bool streamCharacter(wchar_t*, const char*) override; - bool streamTexture(System*, int*, const char*) override; - bool streamFont(System*, int*, const char*) override; + bool streamTexture(System*, TextureHandle*, const char*) override; + bool streamFont(System*, FontHandle*, const char*) override; bool streamSound(System*, int*, const char*) override; bool streamCollection(System*, ObjectCollection*, const char*) override; bool streamEnum(int*, EnumNext, EnumName, const char*) override; @@ -40,15 +40,16 @@ class ForwardingIStream : public IStream class ClassIStream : public ForwardingIStream { public: - explicit ClassIStream(IStream* input); // 83BFF0, owns input + // 83BFF0, owns input. The descriptor factory 83C1E0 inlines the same body with a null input. + explicit ClassIStream(IStream* input = nullptr); ~ClassIStream() override; - TypeDescriptor* getType() override; // 83C2B0 [FRONTIER] factory closure + TypeDescriptor* getType() override; // 83C2B0, descriptor table 94F2BC unsigned int getObjectSize() override; int getPosition() override; // 83C140, relative to payload bool setPosition(int) override; bool readShortString(System*, char*, int, const char*) override; bool init(System*); - static TypeDescriptor* getClassType(); // [FRONTIER] no partial publication + static TypeDescriptor* getClassType(); // 83C2B0, base slot 83C1D0 -> IStream private: int m_payloadStart; // +10 char* m_strings[512]; // +14, only first null initialized diff --git a/Code/BF2/External/BFMeme/ClassOStream.cpp b/Code/BF2/External/BFMeme/ClassOStream.cpp index b062b26dd..c35bcd7ae 100644 --- a/Code/BF2/External/BFMeme/ClassOStream.cpp +++ b/Code/BF2/External/BFMeme/ClassOStream.cpp @@ -21,8 +21,8 @@ bool ForwardingOStream::streamInt(int* p, const char* label) { return m_destinat bool ForwardingOStream::streamString(char** p, const char* label) { return m_destination->streamString(p,label); } bool ForwardingOStream::streamWideString(wchar_t** p, const char* label) { return m_destination->streamWideString(p,label); } bool ForwardingOStream::streamCharacter(wchar_t* p, const char* label) { return m_destination->streamCharacter(p,label); } -bool ForwardingOStream::streamTexture(System* s, int* p, const char* label) { return m_destination->streamTexture(s,p,label); } -bool ForwardingOStream::streamFont(System* s, int* p, const char* label) { return m_destination->streamFont(s,p,label); } +bool ForwardingOStream::streamTexture(System* s, TextureHandle* p, const char* label) { return m_destination->streamTexture(s,p,label); } +bool ForwardingOStream::streamFont(System* s, FontHandle* p, const char* label) { return m_destination->streamFont(s,p,label); } bool ForwardingOStream::streamSound(System* s, int* p, const char* label) { return m_destination->streamSound(s,p,label); } bool ForwardingOStream::streamEnum(int* p, EnumNext next, EnumName name, const char* label) { return m_destination->streamEnum(p,next,name,label); } int ForwardingOStream::write(const void* p, int count) { return m_destination->write(p,count); } @@ -116,8 +116,10 @@ bool saveNamedObject(System* system, Object*& value) } return true; } +#if defined(_M_IX86) static_assert(sizeof(ForwardingOStream) == 8, "forwarding stream layout"); static_assert(sizeof(MemoryOStream) == 16, "memory stream layout"); static_assert(sizeof(ClassOStream) == 0x81C, "class output dictionary layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/ClassOStream.h b/Code/BF2/External/BFMeme/ClassOStream.h index d241de7a1..6919ac70d 100644 --- a/Code/BF2/External/BFMeme/ClassOStream.h +++ b/Code/BF2/External/BFMeme/ClassOStream.h @@ -21,8 +21,8 @@ class ForwardingOStream : public OStream bool streamString(char**, const char*) override; bool streamWideString(wchar_t**, const char*) override; bool streamCharacter(wchar_t*, const char*) override; - bool streamTexture(System*, int*, const char*) override; - bool streamFont(System*, int*, const char*) override; + bool streamTexture(System*, TextureHandle*, const char*) override; + bool streamFont(System*, FontHandle*, const char*) override; bool streamSound(System*, int*, const char*) override; bool streamEnum(int*, EnumNext, EnumName, const char*) override; int write(const void*, int) override; diff --git a/Code/BF2/External/BFMeme/ColorEffect.cpp b/Code/BF2/External/BFMeme/ColorEffect.cpp index 80d5ebd30..51019e52a 100644 --- a/Code/BF2/External/BFMeme/ColorEffect.cpp +++ b/Code/BF2/External/BFMeme/ColorEffect.cpp @@ -22,18 +22,20 @@ bool ColorEffect::streamProperties(System* system, Stream* stream) && stream->streamFloat(&m_color.b, "Blue") && stream->streamFloat(&m_color.a, "Alpha"); } -bool ColorEffect::drawCharacter(System* system, int character, int font, +bool ColorEffect::drawCharacter(System* system, int character, FontHandle font, int elementIndex, Quad* quad, RenderContext* context) { for (auto& corner : quad->corners) corner.color = m_color; return Effect::drawCharacter(system, character, font, elementIndex, quad, context); } -bool ColorEffect::drawTexture(System* system, int texture, Quad* quad, RenderContext* context) +bool ColorEffect::drawTexture(System* system, TextureHandle texture, Quad* quad, RenderContext* context) { for (auto& corner : quad->corners) corner.color = m_color; return Effect::drawTexture(system, texture, quad, context); } +#if defined(_M_IX86) static_assert(sizeof(ColorEffect) == 20, "Native x86 ColorEffect layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/ColorEffect.h b/Code/BF2/External/BFMeme/ColorEffect.h index 8e794bf9b..e0a7110fa 100644 --- a/Code/BF2/External/BFMeme/ColorEffect.h +++ b/Code/BF2/External/BFMeme/ColorEffect.h @@ -14,9 +14,9 @@ class ColorEffect : public Effect { unsigned int getObjectSize() override; bool streamProperties(System*, Stream*) override; Color* getColor() override; - bool drawCharacter(System*, int character, int font, int elementIndex, + bool drawCharacter(System*, int character, FontHandle font, int elementIndex, Quad*, RenderContext*) override; - bool drawTexture(System*, int texture, Quad*, RenderContext*) override; + bool drawTexture(System*, TextureHandle texture, Quad*, RenderContext*) override; static TypeDescriptor* getClassType(); private: Color m_color; diff --git a/Code/BF2/External/BFMeme/CullNode.cpp b/Code/BF2/External/BFMeme/CullNode.cpp index d4e4ce0fa..6d140d8da 100644 --- a/Code/BF2/External/BFMeme/CullNode.cpp +++ b/Code/BF2/External/BFMeme/CullNode.cpp @@ -3,6 +3,9 @@ // 33-slot prefix uses the owner-approved startup exception; inherited // event/reset suffix calls still stop at their known Node callers. #include "CullNode.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../../Math/PortableX87.h" +#endif #if !DEDICATED #include "Data.h" #include "Stream.h" @@ -31,13 +34,17 @@ class CullNodeTypeDescriptor final : public TypeDescriptor int getInstanceCount() override { return cullNodeInstances; } unsigned int getInstanceSize() override { return sizeof(CullNode); } }; +#if defined(_M_IX86) static_assert(sizeof(CullNodeTypeDescriptor) == 16, "CullNode metadata storage"); +#endif // 835F25..835F45 and835F69..835F82 store the rounded float before comparing // the still-extended x87 result. Keep that order, including unordered results // and the sign of values that round to zero. Helper names are [INFERRED]. float decreaseFade(float current, float delta, float duration) { +#if defined(_WIN32) +#if defined(_M_IX86) float result; const float zero = 0.0f; __asm { @@ -53,9 +60,25 @@ float decreaseFade(float current, float delta, float duration) decreased: } return result; +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + // Only an ordered negative unrounded result is replaced by +0. + const double unrounded = static_cast(current) - static_cast(delta) / duration; + return unrounded < 0.0 ? 0.0f : static_cast(unrounded); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-port.md). + float result; + const float zero = 0.0f; + // [CHOSEN, not recovered] Preserve x87 fade decrease. + result = bf2x87::fade(current, delta, duration, false); + return result; +#endif } float increaseFade(float current, float delta, float duration) { +#if defined(_WIN32) +#if defined(_M_IX86) float result; const float one = 1.0f; __asm { @@ -71,6 +94,20 @@ float increaseFade(float current, float delta, float duration) increased: } return result; +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + // Only an ordered unrounded result above one is clamped; equal and unordered keep it. + const double unrounded = static_cast(delta) / duration + current; + return unrounded > 1.0 ? 1.0f : static_cast(unrounded); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-port.md). + float result; + const float one = 1.0f; + // [CHOSEN, not recovered] Preserve x87 fade increase. + result = bf2x87::fade(current, delta, duration, true); + return result; +#endif } } @@ -142,6 +179,8 @@ bool CullNode::update(System* system, const NodeState* state, return true; } +#if defined(_M_IX86) static_assert(sizeof(CullNode) == 24, "client BFMeme CullNode"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/CullVariableActionNode.cpp b/Code/BF2/External/BFMeme/CullVariableActionNode.cpp index 4e28e8111..5fb546620 100644 --- a/Code/BF2/External/BFMeme/CullVariableActionNode.cpp +++ b/Code/BF2/External/BFMeme/CullVariableActionNode.cpp @@ -31,7 +31,9 @@ class CullVariableActionNodeTypeDescriptor final : public TypeDescriptor int getInstanceCount() override { return cullVariableActionNodeInstances; } unsigned int getInstanceSize() override { return sizeof(CullVariableActionNode); } }; +#if defined(_M_IX86) static_assert(sizeof(CullVariableActionNodeTypeDescriptor) == 16, "CullVariableActionNode metadata storage"); +#endif } CullVariableActionNode::CullVariableActionNode() : m_variable(nullptr) {} @@ -65,6 +67,8 @@ bool CullVariableActionNode::dispatchEvent(System* system, const Rect* bounds, return m_action->execute(system, bounds, state, event); } +#if defined(_M_IX86) static_assert(sizeof(CullVariableActionNode) == 16, "client BFMeme CullVariableActionNode"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/Data.cpp b/Code/BF2/External/BFMeme/Data.cpp index b6cf76036..72870b780 100644 --- a/Code/BF2/External/BFMeme/Data.cpp +++ b/Code/BF2/External/BFMeme/Data.cpp @@ -1,5 +1,11 @@ // All instructions read from BF2.exe. No matching dedicated ELF Data class. +#if defined(__APPLE__) +#include "../../Platform/X87Compat.h" // [CHOSEN, not recovered] x87 conversion results, including invalid inputs. +#endif #include "Data.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../../Math/PortableX87.h" +#endif #if !DEDICATED #include "DataFormatting.h" #include "TypeDescriptor.h" @@ -9,6 +15,9 @@ #include #include #include +#if defined(_WIN32) && !defined(_M_IX86) +#include +#endif namespace dice { namespace meme { namespace { char* cloneName(const char* name) @@ -40,12 +49,14 @@ class StringDataTypeDescriptor : public ClassTypeDescriptor // Whole and fractional conversions use different integer widths and overflow behavior. void formatStringDataFloat(float value, char* output, int digits) { +#if defined(_WIN32) double magnitude = value; char* cursor = output; if (value < 0.0f) { *cursor++ = '-'; magnitude = -magnitude; } +#if defined(_M_IX86) unsigned short oldControl, truncControl; __int64 whole; int integral; @@ -63,6 +74,11 @@ void formatStringDataFloat(float value, char* output, int digits) mov eax, dword ptr whole mov integral, eax } +#else + // cvttsd2si truncates like the chopped fistp and yields the same integer-indefinite + // value for NaN and out-of-range input; the low dword is kept, as above. + const int integral = static_cast(_mm_cvttsd_si64(_mm_set_sd(magnitude))); +#endif int remaining = integral; if (remaining == 0) { *cursor++ = '0'; @@ -76,6 +92,7 @@ void formatStringDataFloat(float value, char* output, int digits) while (length != 0) *cursor++ = reverse[--length]; } *cursor++ = '.'; +#if defined(_M_IX86) const double ten = 10.0; int digit; __asm { @@ -99,7 +116,54 @@ void formatStringDataFloat(float value, char* output, int digits) fstp st(0) mov cursor, edi } +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + // The dec/jnz counter is unsigned: a nonpositive digit count runs 2^32 times, as shipped. + { + double fraction = magnitude - static_cast(integral); + unsigned int count = static_cast(digits); + do { + fraction *= 10.0; + const int digit = _mm_cvttsd_si32(_mm_set_sd(fraction)); + *cursor++ = static_cast(static_cast(digit) + 0x30); + fraction -= static_cast(digit); + } while (--count != 0); + } +#endif *cursor = 0; +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-port.md). + double magnitude = value; + char* cursor = output; + if (value < 0.0f) { + *cursor++ = '-'; + magnitude = -magnitude; + } + unsigned short oldControl, truncControl; + __int64 whole; + int integral; + // [CHOSEN, not recovered] Preserve x87 truncating int64 conversion and low dword. + whole = bf2x87::integer(bf2x87::wide(magnitude)); + integral = bf2x87::lowWord(whole); + int remaining = integral; + if (remaining == 0) { + *cursor++ = '0'; + } else { + char reverse[32]; + int length = 0; + do { + reverse[length++] = static_cast(remaining % 10 + '0'); + remaining /= 10; // signed idiv; overflow-derived negative digits stay negative + } while (remaining != 0); + while (length != 0) *cursor++ = reverse[--length]; + } + *cursor++ = '.'; + const double ten = 10.0; + int digit; + // [CHOSEN, not recovered] Preserve x87 retained fractional remainder. + bf2x87::fractionalDigits(magnitude, integral, digits, cursor); + *cursor = 0; +#endif } // Plain sprintf through literal89E620 ("%i"); no width, precision or @@ -280,8 +344,16 @@ bool BoolRefData::bind(System*, bool* value) namespace { // the wide-character allocation, widening copy and // clone the wide reference class uses. Names [INFERRED]. +#if defined(_WIN32) wchar_t* allocateWide(unsigned int characters) { return static_cast(::operator new(characters * 2)); } +#else +// [CHOSEN, not recovered] The shipped `characters * 2` is the byte size of a 16-bit +// Windows wchar_t. POSIX wchar_t is 32 bits, so the same character count needs +// sizeof(wchar_t) bytes each; `* 2` made every clone/widen write past its allocation. +wchar_t* allocateWide(unsigned int characters) +{ return static_cast(::operator new(characters * sizeof(wchar_t))); } +#endif void widenInto(wchar_t* output, const char* text) { while (*text) *output++ = static_cast(*text++); @@ -446,7 +518,11 @@ bool IntRefData::setFloat(System*, float value) { // Round half away from zero, then the ordinary truncating x86 cast // (fnstcw / or 0C00h / fistp / fldcw). A NaN takes the negative arm. +#if defined(__APPLE__) + *m_value = bf2x87::toIntTruncate(value < 0.0f ? value - 0.5f : value + 0.5f); +#else *m_value = static_cast(value < 0.0f ? value - 0.5f : value + 0.5f); +#endif return true; } bool IntRefData::setString(System* system, const char* value) // 82E110, shared body diff --git a/Code/BF2/External/BFMeme/DynamicIndexPointer.cpp b/Code/BF2/External/BFMeme/DynamicIndexPointer.cpp index d5d525f6f..83dd8c3e5 100644 --- a/Code/BF2/External/BFMeme/DynamicIndexPointer.cpp +++ b/Code/BF2/External/BFMeme/DynamicIndexPointer.cpp @@ -59,6 +59,8 @@ bool DynamicIndexPointer::event2(System* system, int first, int index) system->enqueueEvent(2, mapped, static_cast(first), 0.0f, 0); return true; } +#if defined(_M_IX86) static_assert(sizeof(DynamicIndexPointer) == 60, "client DynamicIndexPointer native layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/Effect.cpp b/Code/BF2/External/BFMeme/Effect.cpp index c700df836..04087e8c9 100644 --- a/Code/BF2/External/BFMeme/Effect.cpp +++ b/Code/BF2/External/BFMeme/Effect.cpp @@ -26,33 +26,35 @@ bool updateEffect(System* system, Effect* effect, float delta) } bool drawContextCharacter(RenderContext* context, System* system, int character, - int font, int elementIndex, Quad* quad) + FontHandle font, int elementIndex, Quad* quad) { while (context && !context->effect) context = context->parent; if (!context) return system->drawCharacter(character, font, quad); return context->effect->drawCharacter(system, character, font, elementIndex, quad, context); } -bool drawContextTexture(RenderContext* context, System* system, int texture, +bool drawContextTexture(RenderContext* context, System* system, TextureHandle texture, Quad* quad) { while (context && !context->effect) context = context->parent; if (!context) return system->drawTexture(texture, quad); return context->effect->drawTexture(system, texture, quad, context); } -bool Effect::drawCharacter(System* system, int character, int font, int elementIndex, +bool Effect::drawCharacter(System* system, int character, FontHandle font, int elementIndex, Quad* quad, RenderContext* context) { // Retail requires a context and dereferences it even when its parent is null. return drawContextCharacter(context->parent, system, character, font, elementIndex, quad); } -bool Effect::drawTexture(System* system, int texture, Quad* quad, +bool Effect::drawTexture(System* system, TextureHandle texture, Quad* quad, RenderContext* context) { return drawContextTexture(context->parent, system, texture, quad); } TypeDescriptor* getEffectClassType() { return Effect::getClassType(); } +#if defined(_M_IX86) static_assert(sizeof(Effect) == 4, "PE Effect allocation"); static_assert(sizeof(RenderContext) == 28, "seven-word Effect context"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/Effect.h b/Code/BF2/External/BFMeme/Effect.h index 767ad32ca..0ac378bde 100644 --- a/Code/BF2/External/BFMeme/Effect.h +++ b/Code/BF2/External/BFMeme/Effect.h @@ -19,17 +19,17 @@ class Effect : public Object virtual bool setColor(float r, float g, float b, float a); virtual Color* getColor(); virtual bool update(System*, float delta); - virtual bool drawCharacter(System*, int character, int font, int elementIndex, + virtual bool drawCharacter(System*, int character, FontHandle font, int elementIndex, Quad*, RenderContext*); // +4C 82D810 - virtual bool drawTexture(System*, int texture, Quad*, RenderContext*); + virtual bool drawTexture(System*, TextureHandle texture, Quad*, RenderContext*); static TypeDescriptor* getClassType(); // 82D860, factory82D8A0 }; // Named free-function spellings are [INFERRED]. Retail82D730/82D790 use ECX // for context; all callers here are rebuilt together using these typed helpers. -bool drawContextCharacter(RenderContext*, System*, int character, int font, +bool drawContextCharacter(RenderContext*, System*, int character, FontHandle font, int elementIndex, Quad*); -bool drawContextTexture(RenderContext*, System*, int texture, Quad*); +bool drawContextTexture(RenderContext*, System*, TextureHandle texture, Quad*); bool updateEffect(System*, Effect*, float delta); TypeDescriptor* getEffectClassType(); // 82D860, Stream adapter } } diff --git a/Code/BF2/External/BFMeme/EffectNode.cpp b/Code/BF2/External/BFMeme/EffectNode.cpp index ac0a2d97a..dc7941bc6 100644 --- a/Code/BF2/External/BFMeme/EffectNode.cpp +++ b/Code/BF2/External/BFMeme/EffectNode.cpp @@ -30,7 +30,9 @@ class EffectNodeTypeDescriptor final : public TypeDescriptor int getInstanceCount() override { return effectNodeInstances; } unsigned int getInstanceSize() override { return sizeof(EffectNode); } }; +#if defined(_M_IX86) static_assert(sizeof(EffectNodeTypeDescriptor) == 16, "EffectNode metadata storage"); +#endif } EffectNode::EffectNode(Effect* effect) : Node(), m_effect(effect) {} @@ -82,6 +84,8 @@ bool EffectNode::updateSelf(System* system, const NodeState*, const Rect*, float return updateEffect(system, m_effect, delta); } +#if defined(_M_IX86) static_assert(sizeof(EffectNode) == 12, "client BFMeme EffectNode"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/EqualData.cpp b/Code/BF2/External/BFMeme/EqualData.cpp index 935886754..8a440d344 100644 --- a/Code/BF2/External/BFMeme/EqualData.cpp +++ b/Code/BF2/External/BFMeme/EqualData.cpp @@ -28,7 +28,9 @@ float EqualData::getFloat(System* system) return firstValue == second->getFloat(system) ? 1.0f : 0.0f; } +#if defined(_M_IX86) static_assert(sizeof(EqualData) == 16, "client BFMeme EqualData"); static_assert(sizeof(ClassTypeDescriptor) == 16, "EqualData metadata"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/Event.cpp b/Code/BF2/External/BFMeme/Event.cpp index 89fd1cc60..9c8f56ec4 100644 --- a/Code/BF2/External/BFMeme/Event.cpp +++ b/Code/BF2/External/BFMeme/Event.cpp @@ -20,6 +20,8 @@ bool Event::streamProperties(System* system, Stream* stream) } bool Event::matches(System*, const NodeInputEvent* input) // 83AED0, null input not guarded. { return m_inputIndex == 0 || input->index == m_inputIndex; } +#if defined(_M_IX86) static_assert(sizeof(Event) == 8, "BFMeme Event layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/EventQueue.cpp b/Code/BF2/External/BFMeme/EventQueue.cpp index e18f0dca9..c4f7968b4 100644 --- a/Code/BF2/External/BFMeme/EventQueue.cpp +++ b/Code/BF2/External/BFMeme/EventQueue.cpp @@ -140,7 +140,9 @@ bool EventQueue::process(System* system) m_last = nullptr; return true; } +#if defined(_M_IX86) static_assert(sizeof(QueuedEvent) == 24, "client queue record"); static_assert(sizeof(EventQueue) == 12, "client queue owner"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/FileIStream.cpp b/Code/BF2/External/BFMeme/FileIStream.cpp index d475e3348..6a16a3960 100644 --- a/Code/BF2/External/BFMeme/FileIStream.cpp +++ b/Code/BF2/External/BFMeme/FileIStream.cpp @@ -30,6 +30,8 @@ int FileIStream::read(void* buffer, int bytes) int FileIStream::getPosition() { return m_memory->getPosition(); } bool FileIStream::setPosition(int position) { return static_cast(m_memory->seek(hfe::io::SEEKORIGIN_BEGIN, position)) != 0; } +#if defined(_M_IX86) static_assert(sizeof(FileIStream) == 12, "client file-input visitor layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/FileOStream.cpp b/Code/BF2/External/BFMeme/FileOStream.cpp index d55dcb12c..b156baa0b 100644 --- a/Code/BF2/External/BFMeme/FileOStream.cpp +++ b/Code/BF2/External/BFMeme/FileOStream.cpp @@ -17,6 +17,8 @@ int FileOStream::write(const void* buffer, int bytes) int FileOStream::getPosition() { return m_file->getPosition(); } bool FileOStream::setPosition(int position) { return static_cast(m_file->seek(hfe::io::SEEKORIGIN_BEGIN, position)) != 0; } +#if defined(_M_IX86) static_assert(sizeof(FileOStream) == 8, "client file-output stream layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/FloatData.cpp b/Code/BF2/External/BFMeme/FloatData.cpp index 9c38646e3..8ecd7908a 100644 --- a/Code/BF2/External/BFMeme/FloatData.cpp +++ b/Code/BF2/External/BFMeme/FloatData.cpp @@ -61,7 +61,9 @@ int FloatData::getCharacter(System*, int character) return static_cast(m_text[character]); } +#if defined(_M_IX86) static_assert(sizeof(FloatData) == 20, "client BFMeme FloatData"); static_assert(sizeof(ClassTypeDescriptor) == 16, "FloatData metadata"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/Function.cpp b/Code/BF2/External/BFMeme/Function.cpp index 8b779c737..1745bc776 100644 --- a/Code/BF2/External/BFMeme/Function.cpp +++ b/Code/BF2/External/BFMeme/Function.cpp @@ -37,6 +37,8 @@ bool Function::call(System* system) if (m_name) systemPrintf(system, "Meme: FunctionCall: %s\r\n", m_name); return true; } +#if defined(_M_IX86) static_assert(sizeof(Function) == 8, "BFMeme Function layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/IStream.cpp b/Code/BF2/External/BFMeme/IStream.cpp index 31b104b63..06b46bc93 100644 --- a/Code/BF2/External/BFMeme/IStream.cpp +++ b/Code/BF2/External/BFMeme/IStream.cpp @@ -2,7 +2,12 @@ #include "IStream.h" #if !DEDICATED #include "System.h" +#include "TypeDescriptor.h" #include +#if !defined(_WIN32) +#include +#include +#endif namespace dice { namespace meme { namespace { // [INFERRED] Factored identical resource-name read sequences839E00/839EB0/839F60. @@ -17,6 +22,15 @@ bool readResourceName(IStream* input, char* name) } IStream::IStream(IStream* source) : m_source(source ? source : this) {} IStream::~IStream() {} // 794CA0, borrowed source is not deleted +// 83A160 is both the +04 slot and the class getter: a guarded "dice::meme::IStream" descriptor +// whose base slot jumps to RuntimeObject's (82B9E0) and whose factory 83A1C0 builds a +// self-sourced eight-byte IStream. +TypeDescriptor* IStream::getClassType() +{ + static ClassTypeDescriptor type("dice::meme::IStream"); + return &type; +} +TypeDescriptor* IStream::getType() { return getClassType(); } unsigned int IStream::getObjectSize() { return sizeof(IStream); } IStream* IStream::getSource() // 839B60; repeated forwarding, no cycle/null guard { @@ -28,8 +42,28 @@ bool IStream::streamUByte(unsigned char* value, const char*) { return getSource( bool IStream::streamByte(char* value, const char*) { return getSource()->read(value, 1) == 1; } bool IStream::streamUShort(unsigned short* value, const char*) { return getSource()->read(value, 2) == 2; } bool IStream::streamShort(short* value, const char*) { return getSource()->read(value, 2) == 2; } +#if defined(_WIN32) bool IStream::streamULong(unsigned long* value, const char*) { return getSource()->read(value, 4) == 4; } bool IStream::streamLong(long* value, const char*) { return getSource()->read(value, 4) == 4; } +#else +// [CHOSEN, not recovered] The wire Long is 32 bits (Windows long). LP64 long is 64 bits, so +// reading 4 bytes into it left the upper half uninitialized: readObject's frame end and its +// "reading differs" check used garbage. Read the 32-bit value and sign/zero-extend it. +bool IStream::streamULong(unsigned long* value, const char*) +{ + std::uint32_t wire; + if (getSource()->read(&wire, 4) != 4) return false; + *value = wire; + return true; +} +bool IStream::streamLong(long* value, const char*) +{ + std::int32_t wire; + if (getSource()->read(&wire, 4) != 4) return false; + *value = wire; + return true; +} +#endif bool IStream::streamFloat(float* value, const char*) { return getSource()->read(value, 4) == 4; } bool IStream::streamBool(bool* value, const char* label) // 839C10, clear before attempted read { @@ -64,9 +98,23 @@ bool IStream::streamWideString(wchar_t** value, const char*) int length; if (!getSource()->streamInt(&length, "Int")) return false; if (length) { +#if defined(_WIN32) *value = static_cast(::operator new((static_cast(length) + 1) * 2)); if (getSource()->read(*value, 2 * length) != 2 * length) return false; (*value)[length] = 0; +#else + // [CHOSEN, not recovered] The wire holds `length` 16-bit Windows wchar_t units + // (UTF-16LE); POSIX wchar_t is 32 bits. Allocate native characters, read the units + // separately and widen each one, so the count and terminator index stay the shipped + // ones. No surrogate pairing: one unit stays one character, as in the Windows buffer. + const unsigned int count = static_cast(length); + *value = static_cast(::operator new((count + 1) * sizeof(wchar_t))); + std::vector units(2u * count); + if (getSource()->read(units.data(), 2 * length) != 2 * length) return false; + for (unsigned int i = 0; i < count; ++i) + (*value)[i] = static_cast(units[2 * i] | (units[2 * i + 1] << 8)); + (*value)[length] = 0; +#endif } return true; } @@ -77,7 +125,7 @@ bool IStream::streamCharacter(wchar_t* value, const char* label) // 839DC0, wire *value = static_cast(temporary); return true; } -bool IStream::streamTexture(System* system, int* texture, const char*) +bool IStream::streamTexture(System* system, TextureHandle* texture, const char*) { *texture = 0; char name[256]; @@ -85,7 +133,7 @@ bool IStream::streamTexture(System* system, int* texture, const char*) *texture = system->loadTexture(name, true); return true; } -bool IStream::streamFont(System* system, int* font, const char*) +bool IStream::streamFont(System* system, FontHandle* font, const char*) { *font = 0; char name[256]; @@ -123,6 +171,8 @@ bool IStream::readShortString(System*, char* buffer, int capacity, const char*) buffer[length] = 0; // equality is allowed above: caller needs space for the terminator return true; } +#if defined(_M_IX86) static_assert(sizeof(IStream) == 8, "BFMeme input stream layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/IStream.h b/Code/BF2/External/BFMeme/IStream.h index bdca54e6f..517b6714e 100644 --- a/Code/BF2/External/BFMeme/IStream.h +++ b/Code/BF2/External/BFMeme/IStream.h @@ -12,7 +12,7 @@ class IStream : public Stream public: explicit IStream(IStream* source = nullptr); // 83A1A0, null source means self ~IStream() override; - TypeDescriptor* getType() override; // 83A160 [FRONTIER] + TypeDescriptor* getType() override; // 83A160, descriptor table 94EC00 unsigned int getObjectSize() override; bool streamUByte(unsigned char*, const char*) override; bool streamByte(char*, const char*) override; @@ -26,8 +26,8 @@ class IStream : public Stream bool streamString(char**, const char*) override; bool streamWideString(wchar_t**, const char*) override; bool streamCharacter(wchar_t*, const char*) override; - bool streamTexture(System*, int*, const char*) override; - bool streamFont(System*, int*, const char*) override; + bool streamTexture(System*, TextureHandle*, const char*) override; + bool streamFont(System*, FontHandle*, const char*) override; bool streamSound(System*, int*, const char*) override; bool streamCollection(System*, ObjectCollection*, const char*) override; bool streamEnum(int*, EnumNext, EnumName, const char*) override; @@ -39,7 +39,7 @@ class IStream : public Stream virtual bool setPosition(int); // +9C 455400 virtual bool readShortString(System*, char*, int capacity, const char*); // +A0 83A0A0 IStream* getSource(); // 839B60, follows self-terminated chain - static TypeDescriptor* getClassType(); // [FRONTIER] no partial publication + static TypeDescriptor* getClassType(); // 83A160; factory 83A1C0 inlines IStream(nullptr) private: IStream* m_source; // +4 borrowed; destructor does not free }; diff --git a/Code/BF2/External/BFMeme/InputNodeVisitors.cpp b/Code/BF2/External/BFMeme/InputNodeVisitors.cpp index c2e70fba7..6a3d2d0ed 100644 --- a/Code/BF2/External/BFMeme/InputNodeVisitors.cpp +++ b/Code/BF2/External/BFMeme/InputNodeVisitors.cpp @@ -80,11 +80,13 @@ void ReleaseStateNodeVisitor::visit(System* system, Node*& node, const Rect* rec node->visitChildren(system, state, rect, this); } } +#if defined(_M_IX86) static_assert(sizeof(Event1NodeVisitor) == 24, "client event1 visitor"); static_assert(sizeof(Event2NodeVisitor) == 16, "client event2 visitor"); static_assert(sizeof(Event4NodeVisitor) == 20, "client event4 visitor"); static_assert(sizeof(Event5NodeVisitor) == 16, "client event5 visitor, including unwritten index"); static_assert(sizeof(PressStateNodeVisitor) == 8, "client press state visitor"); static_assert(sizeof(ReleaseStateNodeVisitor) == 8, "client release state visitor"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/IntData.cpp b/Code/BF2/External/BFMeme/IntData.cpp index c687d0e75..8cd5a29b5 100644 --- a/Code/BF2/External/BFMeme/IntData.cpp +++ b/Code/BF2/External/BFMeme/IntData.cpp @@ -2,6 +2,9 @@ // factory82DB60, eager870360 and every differing body read before recovery. // The class is reachable from Bf2HudBuilder::setNodeLogicShowVariable, which // pairs it with IntRefData under an EqualData. +#if defined(__APPLE__) +#include "../../Platform/X87Compat.h" // [CHOSEN, not recovered] x87 conversion results, including invalid inputs. +#endif #include "IntData.h" #if !DEDICATED #include "DataFormatting.h" @@ -42,7 +45,11 @@ bool IntData::setFloat(System*, float value) // Round half away from zero, then the ordinary truncating x86 cast // (fnstcw / or 0C00h / fistp / fldcw). A NaN takes the negative arm. // Text/cache refresh is deferred until character access. +#if defined(__APPLE__) + m_value = bf2x87::toIntTruncate(value < 0.0f ? value - 0.5f : value + 0.5f); +#else m_value = static_cast(value < 0.0f ? value - 0.5f : value + 0.5f); +#endif return true; } bool IntData::setString(System* system, const char* value) @@ -66,7 +73,9 @@ int IntData::getCharacter(System*, int character) return static_cast(m_text[character]); } +#if defined(_M_IX86) static_assert(sizeof(IntData) == 20, "client BFMeme IntData"); static_assert(sizeof(ClassTypeDescriptor) == 16, "IntData metadata"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/LogicalData.cpp b/Code/BF2/External/BFMeme/LogicalData.cpp index fcc9721c9..e824b8283 100644 --- a/Code/BF2/External/BFMeme/LogicalData.cpp +++ b/Code/BF2/External/BFMeme/LogicalData.cpp @@ -48,7 +48,9 @@ int LogicalData::getCharacter(System* system, int character) return (value ? "true" : "false")[character]; } +#if defined(_M_IX86) static_assert(sizeof(LogicalData) == 16, "client BFMeme LogicalData"); static_assert(sizeof(ClassTypeDescriptor) == 16, "LogicalData metadata"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/MoveEffect.cpp b/Code/BF2/External/BFMeme/MoveEffect.cpp index c1ef5df98..32dea370f 100644 --- a/Code/BF2/External/BFMeme/MoveEffect.cpp +++ b/Code/BF2/External/BFMeme/MoveEffect.cpp @@ -51,7 +51,7 @@ void computeMoveOffset(MoveEffect* self, System* system, Data* direction, Data* } } -bool MoveEffect::drawCharacter(System* system, int character, int font, +bool MoveEffect::drawCharacter(System* system, int character, FontHandle font, int elementIndex, Quad* quad, RenderContext* context) { float dx = 0.0f, dy = 0.0f; @@ -75,7 +75,7 @@ bool MoveEffect::drawCharacter(System* system, int character, int font, return drawn; } -bool MoveEffect::drawTexture(System* system, int texture, Quad* quad, +bool MoveEffect::drawTexture(System* system, TextureHandle texture, Quad* quad, RenderContext* context) { float dx = 0.0f, dy = 0.0f; @@ -95,6 +95,8 @@ bool MoveEffect::drawTexture(System* system, int texture, Quad* quad, return drawn; } +#if defined(_M_IX86) static_assert(sizeof(MoveEffect) == 12, "PE MoveEffect allocation"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/MoveEffect.h b/Code/BF2/External/BFMeme/MoveEffect.h index f6648c507..02a35e23e 100644 --- a/Code/BF2/External/BFMeme/MoveEffect.h +++ b/Code/BF2/External/BFMeme/MoveEffect.h @@ -16,9 +16,9 @@ class MoveEffect : public Effect TypeDescriptor* getType() override; unsigned int getObjectSize() override; bool streamProperties(System*, Stream*) override; - bool drawCharacter(System*, int character, int font, int elementIndex, + bool drawCharacter(System*, int character, FontHandle font, int elementIndex, Quad*, RenderContext*) override; - bool drawTexture(System*, int texture, Quad*, RenderContext*) override; + bool drawTexture(System*, TextureHandle texture, Quad*, RenderContext*) override; static TypeDescriptor* getClassType(); // 832700, metadata94CB6C protected: // Both are borrowed expression nodes sampled every frame. The stream labels diff --git a/Code/BF2/External/BFMeme/MovePointer.cpp b/Code/BF2/External/BFMeme/MovePointer.cpp index 7c6e1eca2..c3c94434e 100644 --- a/Code/BF2/External/BFMeme/MovePointer.cpp +++ b/Code/BF2/External/BFMeme/MovePointer.cpp @@ -1,7 +1,9 @@ -// Full operational instructions read from BF2.exe. Construction and descriptor -// remain declaration-only while TransformNode identity is unpublished. +// Full operational instructions read from BF2.exe, including construction and the descriptor. // No raw Node suffix dispatch is introduced. #include "MovePointer.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../../Math/PortableX87.h" +#endif #if !DEDICATED #include "TransformNode.h" #include "System.h" @@ -14,6 +16,8 @@ namespace { // bits when the caller selects extended precision (82B302..82B384). float moveOffset(float value, float start, float origin) { +#if defined(_WIN32) +#if defined(_M_IX86) float result; __asm { fld value @@ -22,9 +26,22 @@ float moveOffset(float value, float start, float origin) fstp result } return result; +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + return static_cast(static_cast(value) - start + origin); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-port.md). + float result; + // [CHOSEN, not recovered] Preserve x87 extended subtract/add. + result = bf2x87::offset(value, start, origin); + return result; +#endif } float outlineThickness(float dimension) // 82B6D9..82B6EF and three repeated arms { +#if defined(_WIN32) +#if defined(_M_IX86) float result; __asm { fld1 @@ -33,6 +50,17 @@ float outlineThickness(float dimension) // 82B6D9..82B6EF and three repeated arm fstp result } return result; +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + return static_cast(1.0 - dimension + dimension); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-port.md). + float result; + // [CHOSEN, not recovered] Preserve x87 extended cancellation. + result = bf2x87::offset(1.0f, dimension, dimension); + return result; +#endif } TransformNode* asTransform(Node* node) { @@ -127,7 +155,22 @@ class PaintTransformVisitor : public NodeVisitor bool* m_next; }; } +// The only body is the copy inlined in the descriptor factory 82B4E0: Pointer's constructor +// (829140), then every MovePointer field zeroed in declaration order. +MovePointer::MovePointer() + : m_selected(nullptr), m_dragging(false), m_relativeX(0.0f), m_relativeY(0.0f), + m_startX(0.0f), m_startY(0.0f), m_startPositionX(0.0f), m_startPositionY(0.0f), + m_startWidth(0.0f), m_startHeight(0.0f), m_resizing(false) +{ +} MovePointer::~MovePointer() {} // 82B8D0, inherited Pointer owns no graphic +// 82B900: guarded "dice::meme::MovePointer" descriptor (table 94A04C). Its table 949FF0 overrides +// exactly the slots declared in MovePointer.h; the rest are Pointer's. +TypeDescriptor* MovePointer::getClassType() +{ + static ClassTypeDescriptor type("dice::meme::MovePointer"); + return &type; +} TypeDescriptor* MovePointer::getType() { return getClassType(); } unsigned int MovePointer::getObjectSize() { return sizeof(MovePointer); } bool MovePointer::paint(System* system) @@ -215,6 +258,8 @@ bool MovePointer::event2(System* system, int, int) // 82B940; no enabled guard } return true; } +#if defined(_M_IX86) static_assert(sizeof(MovePointer) == 64, "Native x86 MovePointer layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/MovePointer.h b/Code/BF2/External/BFMeme/MovePointer.h index 6e04be26b..7f20b8c79 100644 --- a/Code/BF2/External/BFMeme/MovePointer.h +++ b/Code/BF2/External/BFMeme/MovePointer.h @@ -1,6 +1,5 @@ // Descriptor name82B900 attests dice::meme::MovePointer. Full23-slot table949FF0. -// Native64-byte storage, no STL. Construction/descriptor stay unpublished; -// the TransformNode descriptor remains unresolved. +// Native64-byte storage, no STL. #ifndef BFMEME_MOVEPOINTER_H #define BFMEME_MOVEPOINTER_H #include "Pointer.h" @@ -9,7 +8,7 @@ namespace dice { namespace meme { class TransformNode; class MovePointer : public Pointer { public: - MovePointer(); // inlined82B4E0 [FRONTIER], operational dependency remains open + MovePointer(); // inlined in descriptor factory 82B4E0 ~MovePointer() override; // 82B8D0 -> Pointer destructor TypeDescriptor* getType() override; // 82B900, named descriptor dependency unsigned int getObjectSize() override; @@ -17,7 +16,7 @@ class MovePointer : public Pointer { bool setPosition(System*, float x, float y) override; bool event1(System*, int first, int index, int second) override; bool event2(System*, int first, int index) override; - static TypeDescriptor* getClassType(); // [FRONTIER], no incomplete factory + static TypeDescriptor* getClassType(); // 82B900, base slot 82B4D0 -> Pointer protected: TransformNode* m_selected; // +14, borrowed bool m_dragging; // +18 diff --git a/Code/BF2/External/BFMeme/NameNode.cpp b/Code/BF2/External/BFMeme/NameNode.cpp index c1792decc..ce9e2a3a9 100644 --- a/Code/BF2/External/BFMeme/NameNode.cpp +++ b/Code/BF2/External/BFMeme/NameNode.cpp @@ -73,7 +73,9 @@ bool NameNode::setName(const char* name) } bool NameNode::slot_0x20() { return true; } bool NameNode::slot_0x24() { return true; } +#if defined(_M_IX86) static_assert(sizeof(NameNode) == 12, "client BFMeme NameNode"); static_assert(sizeof(NameNodeTypeDescriptor) == 16, "client NameNode descriptor"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/NamedInputStream.cpp b/Code/BF2/External/BFMeme/NamedInputStream.cpp index 66659263b..4cbabb57f 100644 --- a/Code/BF2/External/BFMeme/NamedInputStream.cpp +++ b/Code/BF2/External/BFMeme/NamedInputStream.cpp @@ -40,7 +40,9 @@ int RelativeIStream::getPosition() + static_cast(m_skippedBytes) - static_cast(m_initialPosition)); } +#if defined(_M_IX86) static_assert(sizeof(TeeIStream) == 20, "client recording input layout"); static_assert(sizeof(RelativeIStream) == 24, "client relative input layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/NamedObjectRegistry.cpp b/Code/BF2/External/BFMeme/NamedObjectRegistry.cpp index b453d1d41..b30d41d21 100644 --- a/Code/BF2/External/BFMeme/NamedObjectRegistry.cpp +++ b/Code/BF2/External/BFMeme/NamedObjectRegistry.cpp @@ -312,11 +312,13 @@ bool NameTreeObjectEntry::stream(System* system, Stream* output) if (m_object && !output->streamObject(system, m_object, "Object", nullptr)) return false; return next ? next->stream(system, output) : true; } -// [FRONTIER] saveNamedObject82AB60 and specialized visitor descriptor defaults -// are still deeper dependencies. No registry/System factory is published. +// saveNamedObject is defined in ClassOStream.cpp; System::init owns registry creation. +// [FRONTIER] Specialized visitor descriptor defaults remain outside this registry. +#if defined(_M_IX86) static_assert(sizeof(NameTreeNode) == 8, "name-tree node layout"); static_assert(sizeof(NameTreeContainer) == 16, "name-tree container layout"); static_assert(sizeof(NameTreeRoot) == 16, "name-tree root layout"); static_assert(sizeof(NameTreeObjectEntry) == 12, "name-tree object entry layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/NativeSavedDispatch.h b/Code/BF2/External/BFMeme/NativeSavedDispatch.h new file mode 100644 index 000000000..68db9e0f2 --- /dev/null +++ b/Code/BF2/External/BFMeme/NativeSavedDispatch.h @@ -0,0 +1,92 @@ +// [CHOSEN, not recovered] Native saved-table dispatch for the macOS port. +#ifndef BFMEME_NATIVE_SAVED_DISPATCH_H +#define BFMEME_NATIVE_SAVED_DISPATCH_H +#if defined(__APPLE__) && defined(__LP64__) && !defined(__arm64e__) +#include +#include +#include +#include +#include +#include + +namespace dice { namespace meme { namespace native_dispatch { + +/// Itanium virtual-member encoding; a non-virtual member is a programming error and asserts. x86-64 marks a virtual +/// member by ptr = vtable byte offset + 1; the ARM variant of the C++ ABI (Apple arm64) keeps +/// ptr = vtable byte offset and marks it in adj = 2 * this-adjustment + 1. +struct VirtualMember +{ + std::ptrdiff_t offset; + std::ptrdiff_t adjustment; + + template + static VirtualMember decode(Member member) + { + static_assert(std::is_member_function_pointer::value, "virtual member required"); + struct Representation { std::ptrdiff_t pointer; std::ptrdiff_t adjustment; }; + static_assert(sizeof(Member) == sizeof(Representation), "standard Itanium member encoding required"); + static_assert(sizeof(void (*)()) == sizeof(std::ptrdiff_t), "native function pointer width required"); + Representation bits; + std::memcpy(&bits, &member, sizeof(bits)); +#if defined(__aarch64__) || defined(__arm64__) + const bool supported = (bits.adjustment & 1) && bits.pointer >= 0 && + bits.pointer % sizeof(void (*)()) == 0; + const VirtualMember decoded = {bits.pointer, bits.adjustment >> 1}; +#else + const bool supported = bits.pointer > 0 && (bits.pointer & 1) && + (bits.pointer - 1) % sizeof(void (*)()) == 0; + const VirtualMember decoded = {bits.pointer - 1, bits.adjustment}; +#endif + if (!supported) + { + // An invariant of this platform layer, not missing retail code: every caller passes a + // virtual member, so only a programming error (null or non-virtual member) lands here. + // bf2_meme_dispatch_check's death mode pins it. + std::fprintf(stderr, "[ASSERT] dice::meme::native_dispatch::VirtualMember::decode: not a virtual member\n"); + std::fflush(stderr); + std::abort(); + } + return decoded; + } + + std::size_t slot() const { return static_cast(offset) / sizeof(void (*)()); } +}; + +template class SavedVirtual; + +/// Captures the adjusted receiver's table, then calls it on a later compatible receiver. +/// Both receivers must have live, layout-compatible subobjects for the selected method. +/// The stored table and its adjustment thunks must remain alive through the call. +template +class SavedVirtual +{ +public: + using Member = R (C::*)(Args...); + + SavedVirtual(C* receiver, Member member) : m_member(VirtualMember::decode(member)) + { + const char* adjusted = reinterpret_cast(receiver) + m_member.adjustment; + std::memcpy(&m_table, adjusted, sizeof(m_table)); + } + + R operator()(C* receiver, Args... args) const + { + // Keep the captured address point (including secondary-base thunks). Only + // this is reloaded/adjusted; reading receiver's current vptr would change + // the recovered capture-before-source-getter semantics. See the port guide. + using Function = R (*)(void*, Args...); + static_assert(sizeof(Function) == sizeof(void*), "native table entry width required"); + Function function; + std::memcpy(&function, m_table + m_member.offset, sizeof(function)); + void* adjusted = reinterpret_cast(receiver) + m_member.adjustment; + return function(adjusted, std::forward(args)...); + } + +private: + VirtualMember m_member; + const char* m_table; +}; + +} } } +#endif +#endif diff --git a/Code/BF2/External/BFMeme/Node.cpp b/Code/BF2/External/BFMeme/Node.cpp index 393495be2..92f045add 100644 --- a/Code/BF2/External/BFMeme/Node.cpp +++ b/Code/BF2/External/BFMeme/Node.cpp @@ -6,9 +6,11 @@ #if !DEDICATED #include "Stream.h" #include "TypeDescriptor.h" +#include "System.h" // Concrete menu node types permit event-20 dispatch while the shared Node suffix remains untyped. #include "../../Menu/Bf2ButtonNode.h" #include "../../Menu/Bf2ObjectMarkerNode.h" +#include "../../Menu/Bf2EditNode.h" #include #include #include @@ -37,7 +39,9 @@ class NodeTypeDescriptor : public TypeDescriptor static int instanceCount; }; int NodeTypeDescriptor::instanceCount = 0; +#if defined(_M_IX86) static_assert(sizeof(NodeTypeDescriptor) == 16, "Node metadata stores its counter separately"); +#endif } TypeDescriptor* Node::getClassType() // 82C190, shared by the virtual getter @@ -199,13 +203,23 @@ bool dispatchNodeEvent15(Node*, System*, const Rect*, const NodeState*) // [CHOSEN, not recovered] [RETIRE-WHEN: node-suffix-call-frontiers] return false; } -bool dispatchNodeEvent16(Node*, System*, const Rect*, const NodeState*) +bool dispatchNodeEvent16(Node* node, System* system, const Rect*, const NodeState*) { - // [FRONTIER] [TEMP] [CHOSEN, not recovered] Event 16 stops because edit and path nodes have nonempty handlers. - // [RETIRE-WHEN: node-suffix-call-frontiers] Implement the typed virtual handlers before replacing this stop. - std::fprintf(stderr, "[FRONTIER] dice::meme::dispatchNodeEvent16 reached (Node virtual+A0 - NOT a false default: 5 of 74 tables override it, BfEditNode/Bf2EditNode 7AA9B0, BfEditNodeInt 7AACF0, PathNode/StackPathNode 836A80)\n"); - std::fflush(stderr); - std::abort(); + // Match exact descriptors while the remaining Node suffix is untyped. BfEditNode/Bf2EditNode + // +A0 (7AA9B0): drop focus and unlock the pointer, then the 455410 false default. + TypeDescriptor* const type = node->getType(); + if (type == BfEditNode::getClassType() || type == Bf2EditNode::getClassType()) { + BfEditNode* const edit = static_cast(node); + if (edit->m_focused) { + edit->m_focused = false; + system->unlockPointer(); + } + return false; + } + // Every other class in this tree keeps Node's own +A0, the shared `return false` at 455410. The + // remaining overrides belong to classes the tree does not build yet - BfEditNodeInt (7AACF0) and + // PathNode/StackPathNode (836A80); each brings its handler with it. + return false; } bool dispatchNodeEvent13(Node*, System*, const Rect*, const NodeState*) { @@ -274,10 +288,14 @@ void resetNodeSelf(Node*) { } +#if defined(_M_IX86) static_assert(sizeof(Node) == 8, "client BFMeme Node"); +#endif static_assert(sizeof(NodeState) == 8, "client BFMeme interaction state"); static_assert(sizeof(NodeInputEvent) == 20, "client BFMeme input payload"); +#if defined(_M_IX86) static_assert(sizeof(RenderContext) == 28, "client BFMeme effect chain context"); static_assert(sizeof(NodeVisitor) == 8, "client BFMeme three-slot visitor"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/Node.h b/Code/BF2/External/BFMeme/Node.h index 73edb4e0e..1d59e45ad 100644 --- a/Code/BF2/External/BFMeme/Node.h +++ b/Code/BF2/External/BFMeme/Node.h @@ -91,7 +91,7 @@ bool dispatchNodeEvent10(Node*, System*, const Rect*, const NodeState*); // chos bool dispatchNodeEvent11(Node*, System*, const Rect*, const NodeState*); // chosen native default for +94; 74/74 PE455410 bool dispatchNodeEvent12(Node*, System*, const Rect*, const NodeState*); // chosen native default for +98; 74/74 PE455410 bool dispatchNodeEvent15(Node*, System*, const Rect*, const NodeState*); // chosen native default for +9C; 74/74 PE455410 -bool dispatchNodeEvent16(Node*, System*, const Rect*, const NodeState*); // +A0 [FRONTIER] - 5 tables override it, see Node.cpp +bool dispatchNodeEvent16(Node*, System*, const Rect*, const NodeState*); // +A0 - 455410 false default, BfEditNode/Bf2EditNode 7AA9B0 bool dispatchNodeEvent13(Node*, System*, const Rect*, const NodeState*); // +A4 bool dispatchNodeEvent17(Node*, System*, const Rect*, const NodeState*); // chosen native default for +A8; no virtual suffix access bool dispatchNodeEvent18(Node*, System*, const Rect*, const NodeState*); // chosen native default for +AC; 74/74 PE455410 diff --git a/Code/BF2/External/BFMeme/NodeState.cpp b/Code/BF2/External/BFMeme/NodeState.cpp index 321e2cf3e..763e5dafd 100644 --- a/Code/BF2/External/BFMeme/NodeState.cpp +++ b/Code/BF2/External/BFMeme/NodeState.cpp @@ -66,7 +66,9 @@ void emitStateEvent(int type, System* system, Node*& eventRoot, const Rect* rect StateEventVisitor visitor(event); visitor.traverse(system, eventRoot, rect, state); } +#if defined(_M_IX86) static_assert(sizeof(StateEventVisitor) == 32, "client state event visitor"); +#endif } void updateNodeState(NodeState* state, System* system, Node* transitionSource, Node* eventRoot, const Rect* rect, float delta, bool pointerInside, bool enabled) diff --git a/Code/BF2/External/BFMeme/NotData.cpp b/Code/BF2/External/BFMeme/NotData.cpp index 9134ca759..34b50550a 100644 --- a/Code/BF2/External/BFMeme/NotData.cpp +++ b/Code/BF2/External/BFMeme/NotData.cpp @@ -31,7 +31,9 @@ float NotData::getFloat(System* system) return m_first->getFloat(system) == 0.0f ? 1.0f : 0.0f; } +#if defined(_M_IX86) static_assert(sizeof(NotData) == 16, "client BFMeme NotData"); static_assert(sizeof(ClassTypeDescriptor) == 16, "NotData metadata"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/OStream.cpp b/Code/BF2/External/BFMeme/OStream.cpp index 6d1da11e0..927ba3fe9 100644 --- a/Code/BF2/External/BFMeme/OStream.cpp +++ b/Code/BF2/External/BFMeme/OStream.cpp @@ -6,6 +6,9 @@ #include "TypeDescriptor.h" #include #include +#if !defined(_WIN32) +#include +#endif namespace dice { namespace meme { namespace { // [INFERRED] Factored identical resource-name write sequences838190/838210/838290. @@ -19,6 +22,14 @@ bool writeResourceName(OStream* output, const char* name) } } OStream::~OStream() {} +// 8383E0: guarded "dice::meme::OStream" descriptor, base slot 82B9E0 (RuntimeObject), factory +// 838420 (four bytes, table 9352A0), size slot 8149E0 (4). +TypeDescriptor* OStream::getClassType() +{ + static ClassTypeDescriptor type("dice::meme::OStream"); + return &type; +} +TypeDescriptor* OStream::getType() { return getClassType(); } unsigned int OStream::getObjectSize() { return sizeof(OStream); } bool OStream::streamUByte(unsigned char* value, const char*) { return write(value, 1) == 1; } bool OStream::streamByte(char* value, const char*) { return write(value, 1) == 1; } @@ -48,7 +59,22 @@ bool OStream::streamWideString(wchar_t** value, const char*) { int length = *value ? static_cast(std::wcslen(*value)) : 0; if (!streamInt(&length, "Int")) return false; +#if defined(_WIN32) if (*value && write(*value, 2 * length) != 2 * length) return false; +#else + // [CHOSEN, not recovered] Keep the Windows wire format: `length` UTF-16LE units. Writing + // 2 * length raw bytes of a 32-bit POSIX wchar_t buffer would emit half the text, mangled. + // Characters above U+FFFF keep their low 16 bits, as the 16-bit getCharacter does. + if (*value) { + std::vector units(2u * static_cast(length)); + for (int i = 0; i < length; ++i) { + const unsigned int unit = static_cast((*value)[i]) & 0xFFFFu; + units[2 * i] = static_cast(unit); + units[2 * i + 1] = static_cast(unit >> 8); + } + if (write(units.data(), 2 * length) != 2 * length) return false; + } +#endif return true; } bool OStream::streamCharacter(wchar_t* value, const char* label) // 838170 uses32-bit serialization @@ -56,9 +82,9 @@ bool OStream::streamCharacter(wchar_t* value, const char* label) // 838170 uses3 int temporary = *value; return streamInt(&temporary, label); } -bool OStream::streamTexture(System* system, int* texture, const char*) +bool OStream::streamTexture(System* system, TextureHandle* texture, const char*) { return writeResourceName(this, system->getTextureName(*texture)); } -bool OStream::streamFont(System* system, int* font, const char*) +bool OStream::streamFont(System* system, FontHandle* font, const char*) { return writeResourceName(this, system->getFontName(*font)); } bool OStream::streamSound(System* system, int* sound, const char*) { return writeResourceName(this, system->getSoundName(*sound)); } @@ -110,6 +136,8 @@ bool writeObject(System* system, Object*& value, OStream* output) return true; } // Descriptor is intentionally unpublished while deeper dependencies stay open. +#if defined(_M_IX86) static_assert(sizeof(OStream) == 4, "BFMeme output stream layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/OStream.h b/Code/BF2/External/BFMeme/OStream.h index 2208b4431..afa64e65e 100644 --- a/Code/BF2/External/BFMeme/OStream.h +++ b/Code/BF2/External/BFMeme/OStream.h @@ -8,7 +8,7 @@ class OStream : public Stream { public: ~OStream() override; // 794CA0 -> RuntimeObject dtor - TypeDescriptor* getType() override; // 8383E0 [FRONTIER] publication + TypeDescriptor* getType() override; // 8383E0, descriptor table 94E954 unsigned int getObjectSize() override; bool streamUByte(unsigned char*, const char*) override; bool streamByte(char*, const char*) override; @@ -22,8 +22,8 @@ class OStream : public Stream bool streamString(char**, const char*) override; bool streamWideString(wchar_t**, const char*) override; bool streamCharacter(wchar_t*, const char*) override; - bool streamTexture(System*, int*, const char*) override; - bool streamFont(System*, int*, const char*) override; + bool streamTexture(System*, TextureHandle*, const char*) override; + bool streamFont(System*, FontHandle*, const char*) override; bool streamSound(System*, int*, const char*) override; bool streamCollection(System*, ObjectCollection*, const char*) override; bool streamEnum(int*, EnumNext, EnumName, const char*) override; @@ -33,7 +33,7 @@ class OStream : public Stream virtual int getPosition(); // +94 80D430; serializer82AA00 virtual bool setPosition(int); virtual bool writeShortString(System*, const char*, const char* label); // +9C 838330 - static TypeDescriptor* getClassType(); // [FRONTIER], no partial factory + static TypeDescriptor* getClassType(); // 8383E0; factory 838420 builds a bare OStream }; } } #endif diff --git a/Code/BF2/External/BFMeme/Object.cpp b/Code/BF2/External/BFMeme/Object.cpp index a6134e73f..fe9a215f7 100644 --- a/Code/BF2/External/BFMeme/Object.cpp +++ b/Code/BF2/External/BFMeme/Object.cpp @@ -84,7 +84,9 @@ bool createRuntimeObject(RuntimeObject*& object, TypeDescriptor* type) created->getType()->addInstance(); return true; } +#if defined(_M_IX86) static_assert(sizeof(RuntimeObject) == 4, "BFMeme RuntimeObject layout"); static_assert(sizeof(Object) == 4, "BFMeme Object layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/Object.h b/Code/BF2/External/BFMeme/Object.h index 0b981ec6c..385fb7f96 100644 --- a/Code/BF2/External/BFMeme/Object.h +++ b/Code/BF2/External/BFMeme/Object.h @@ -4,7 +4,21 @@ #define BFMEME_OBJECT_H #include "../../Core/BuildConfig.h" #if !DEDICATED +#include +#include namespace dice { namespace meme { +// Font and texture handles carry the Font* / IMemeTexture* that the menu System returns, so +// they are pointer-sized. MSVC x86 defines intptr_t as int: retail layouts and x86 signatures +// are unchanged. [CHOSEN, not recovered] x64 port, issue #7. +typedef std::intptr_t FontHandle; +typedef std::intptr_t TextureHandle; +#if defined(_M_IX86) +static_assert(std::is_same::value && std::is_same::value, + "x86 meme handles keep the retail int type"); +static_assert(std::is_same::value, + "x86 unsigned handle words keep the retail uint32_t type"); +#endif + class TypeDescriptor; class System; class Stream; // [INFERRED] common stream/visitor identity, not Object-derived. diff --git a/Code/BF2/External/BFMeme/ObjectCollection.cpp b/Code/BF2/External/BFMeme/ObjectCollection.cpp index 43d2c69c3..8144215d0 100644 --- a/Code/BF2/External/BFMeme/ObjectCollection.cpp +++ b/Code/BF2/External/BFMeme/ObjectCollection.cpp @@ -140,6 +140,8 @@ bool ObjectCollection::writeObjects(System* system, OStream* output) object = nullptr; return writeObject(system, object, output); // Always emit the null terminator. } +#if defined(_M_IX86) static_assert(sizeof(ObjectCollection) == 4, "BFMeme collection base layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/ObjectList.cpp b/Code/BF2/External/BFMeme/ObjectList.cpp index 2c6e6837f..b82063fcd 100644 --- a/Code/BF2/External/BFMeme/ObjectList.cpp +++ b/Code/BF2/External/BFMeme/ObjectList.cpp @@ -16,7 +16,9 @@ struct ObjectList::Link ~Link() { delete next; } // 839750, reverse free order, no payload deletion static Link* allocate(Object* object) { +#if defined(_M_IX86) static_assert(sizeof(Link) == 12, "client ObjectList link"); +#endif void* memory = ::operator new(sizeof(Link)); return memory ? new(memory) Link(object) : nullptr; } @@ -123,6 +125,8 @@ bool ObjectList::readObjects(System* system, IStream* stream) m_cursor = m_first; return true; } +#if defined(_M_IX86) static_assert(sizeof(ObjectList) == 20, "client concrete ObjectList"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/OrData.cpp b/Code/BF2/External/BFMeme/OrData.cpp index a7f72e4dd..9528d7c38 100644 --- a/Code/BF2/External/BFMeme/OrData.cpp +++ b/Code/BF2/External/BFMeme/OrData.cpp @@ -28,7 +28,9 @@ float OrData::getFloat(System* system) return m_second->getFloat(system) != 0.0f ? 1.0f : 0.0f; } +#if defined(_M_IX86) static_assert(sizeof(OrData) == 16, "client BFMeme OrData"); static_assert(sizeof(ClassTypeDescriptor) == 16, "OrData metadata"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/PictureNode.cpp b/Code/BF2/External/BFMeme/PictureNode.cpp index 890fc6e67..53ff5acee 100644 --- a/Code/BF2/External/BFMeme/PictureNode.cpp +++ b/Code/BF2/External/BFMeme/PictureNode.cpp @@ -28,10 +28,12 @@ class PictureNodeTypeDescriptor final : public TypeDescriptor int getInstanceCount() override { return pictureNodeInstances; } unsigned int getInstanceSize() override { return sizeof(PictureNode); } }; +#if defined(_M_IX86) static_assert(sizeof(PictureNodeTypeDescriptor) == 16, "PictureNode metadata storage"); +#endif } -PictureNode::PictureNode(int texture) : Node(), m_texture(texture) {} +PictureNode::PictureNode(TextureHandle texture) : Node(), m_texture(texture) {} TypeDescriptor* PictureNode::getClassType() { static PictureNodeTypeDescriptor type; diff --git a/Code/BF2/External/BFMeme/PictureNode.h b/Code/BF2/External/BFMeme/PictureNode.h index 5c16ea8fa..bc3d8a3b9 100644 --- a/Code/BF2/External/BFMeme/PictureNode.h +++ b/Code/BF2/External/BFMeme/PictureNode.h @@ -6,16 +6,18 @@ namespace dice { namespace meme { class PictureNode : public Node { public: - explicit PictureNode(int texture); + explicit PictureNode(TextureHandle texture); TypeDescriptor* getType() override; unsigned int getObjectSize() override; bool streamProperties(System*, Stream*) override; void paintSelf(System*, const NodeState*, const Rect*, const Rect*, RenderContext*) override; static TypeDescriptor* getClassType(); // 836320, factory8362F0 protected: - int m_texture; // +08, signed texture handle + TextureHandle m_texture; // +08, signed texture handle }; +#if defined(_M_IX86) static_assert(sizeof(PictureNode)==12, "native PictureNode prefix storage"); +#endif } } #endif #endif diff --git a/Code/BF2/External/BFMeme/Pointer.cpp b/Code/BF2/External/BFMeme/Pointer.cpp index 8b149c9e2..7a5651b12 100644 --- a/Code/BF2/External/BFMeme/Pointer.cpp +++ b/Code/BF2/External/BFMeme/Pointer.cpp @@ -80,6 +80,8 @@ bool updatePointer(System* s, Pointer* p, float d) { return p && p->isEnabled() bool positionPointer(System* s, Pointer* p, float x, float y) { return p && p->isEnabled() ? p->setPosition(s, x, y) : true; } bool pointerEvent1(System* s, Pointer* p, int a, int i, int b) { return p && p->isEnabled() ? p->event1(s, a, i, b) : true; } bool pointerEvent2(System* s, Pointer* p, int a, int i) { return p && p->isEnabled() ? p->event2(s, a, i) : true; } +#if defined(_M_IX86) static_assert(sizeof(Pointer) == 20, "Pointer has no STL-dependent members"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/Quad.cpp b/Code/BF2/External/BFMeme/Quad.cpp index f8639a6c0..f44771c36 100644 --- a/Code/BF2/External/BFMeme/Quad.cpp +++ b/Code/BF2/External/BFMeme/Quad.cpp @@ -1,5 +1,11 @@ #include "Quad.h" +#include "Stream.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../../Math/PortableX87.h" +#endif #if !DEDICATED +#include +#include namespace dice { namespace meme { Quad::Quad() : clip(nullptr), blend(1), state08(7), state0c(8), @@ -66,6 +72,8 @@ Quad::Quad(const Rect* bounds, const Rect* clipping, const Color* color) corners[3].z = z; corners[3].color = *color; } +// PE 0x101C4F00: RendDX9's copy of this body (cosine and sine from fcos/fsin once, then the four +// corners in order); unreachable in 1.50 there: no code or data references. // Each corner rotates about the supplied centre. The cosine and sine // come from the x87 fcos/fsin pair, not the CRT, and both are evaluated once // before the four corners; keep that or the shipped pixel positions move. @@ -74,7 +82,9 @@ Quad::Quad(const Rect* bounds, const Rect* clipping, const Color* color) // stack; the named float locals below reproduce the rounding that matters. void rotateQuad(Quad* quad, const float center[2], float radians) { +#if defined(_WIN32) float cosine, sine; +#if defined(_M_IX86) __asm { fld radians fcos @@ -83,12 +93,31 @@ void rotateQuad(Quad* quad, const float center[2], float radians) fsin fstp sine } +#else + // [PLATFORM] x64: no x87 fcos/fsin. The CRT double results rounded to float match the + // x87 ones except in rare last-bit cases; |radians| >= 2^63 (left unreduced by x87) differs. + cosine = static_cast(std::cos(static_cast(radians))); + sine = static_cast(std::sin(static_cast(radians))); +#endif + for (unsigned int i = 0; i < 4; ++i) { + const float dx = quad->corners[i].x - center[0]; + const float dy = quad->corners[i].y - center[1]; + quad->corners[i].x = dx * cosine + dy * sine + center[0]; + quad->corners[i].y = dy * cosine - dx * sine + center[1]; + } +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-port.md). + float cosine, sine; + // [CHOSEN, not recovered] Preserve x87 float trig stores. + cosine = bf2x87::store(bf2x87::cosine(bf2x87::wide(radians))); + sine = bf2x87::store(bf2x87::sine(bf2x87::wide(radians))); for (unsigned int i = 0; i < 4; ++i) { const float dx = quad->corners[i].x - center[0]; const float dy = quad->corners[i].y - center[1]; quad->corners[i].x = dx * cosine + dy * sine + center[0]; quad->corners[i].y = dy * cosine - dx * sine + center[1]; } +#endif } // Overwrites all four corner colors; no alpha or range handling. @@ -127,7 +156,130 @@ void setQuadBounds(Quad* quad, float x, float y, float width, float height) quad->corners[3].z = z; } +// PE 0x101C4E50 (ecx = quad, out on the stack): the mean of the four corner positions, summed in +// corner order with a float store per addition, then scaled by 0.25. +void quadCenter(const Quad* quad, float out[3]) +{ + out[0] = 0.0f; + out[1] = 0.0f; + out[2] = 0.0f; + out[0] = quad->corners[0].x; + out[1] = quad->corners[0].y; + out[2] = quad->corners[0].z; + for (unsigned int i = 1; i < 4; ++i) { + out[0] = quad->corners[i].x + out[0]; + out[1] = quad->corners[i].y + out[1]; + out[2] = quad->corners[i].z + out[2]; + } + out[0] = out[0] * 0.25f; + out[1] = out[1] * 0.25f; + out[2] = out[2] * 0.25f; +} + +// PE 0x101C5060 (ecx = quad, margin on the stack): grows the quad outward by the margin: corner 0 +// moves by (-mx, -my), corner 1 by (+mx, -my), corner 2 by (+mx, +my), corner 3 by (-mx, +my). +void expandQuad(Quad* quad, const float margin[2]) +{ + quad->corners[0].x = -margin[0] + quad->corners[0].x; + quad->corners[0].y = -margin[1] + quad->corners[0].y; + quad->corners[1].x = quad->corners[1].x + margin[0]; + quad->corners[1].y = -margin[1] + quad->corners[1].y; + quad->corners[2].x = quad->corners[2].x + margin[0]; + quad->corners[2].y = margin[1] + quad->corners[2].y; + quad->corners[3].x = -margin[0] + quad->corners[3].x; + quad->corners[3].y = margin[1] + quad->corners[3].y; +} + +namespace { +// Exchanges the seven leading words (position and colour) of two corners; the eighth word of each +// corner is not touched. +void swapCorners(QuadCorner& a, QuadCorner& b) +{ + const QuadCorner saved = a; + a.x = b.x; + a.y = b.y; + a.z = b.z; + a.color = b.color; + b.x = saved.x; + b.y = saved.y; + b.z = saved.z; + b.color = saved.color; +} +} + +// PE 0x101C50D0 (ecx = quad): corners 0 and 1, then 2 and 3, exchange position and colour. +void flipQuadHorizontal(Quad* quad) +{ + swapCorners(quad->corners[0], quad->corners[1]); + swapCorners(quad->corners[2], quad->corners[3]); +} + +// PE 0x101C5210 (ecx = quad): corners 0 and 3, then 1 and 2, exchange position and colour. +void flipQuadVertical(Quad* quad) +{ + swapCorners(quad->corners[0], quad->corners[3]); + swapCorners(quad->corners[1], quad->corners[2]); +} + +// PE 0x101C4BE0 (ecx = rect, bounds on the stack): false, leaving the rect alone, when the two +// rectangles do not overlap (each edge compared with `>=`, a NaN edge counts as no overlap); +// otherwise trims the rect to the bounds' left, top, right and bottom in that order and answers +// true. [CHOSEN, not recovered] the retail x87 keeps each delta unrounded on the stack; a double +// delta is used here because no 1.50 path executes the body. +bool clipRect(Rect* rect, const Rect* bounds) +{ + if (!(rect->x + rect->width >= bounds->x)) return false; + if (!(rect->y + rect->height >= bounds->y)) return false; + if (!(bounds->x + bounds->width >= rect->x)) return false; + if (!(bounds->height + bounds->y >= rect->y)) return false; + double delta = static_cast(bounds->x) - rect->x; + if (delta > 0.0) { + rect->width = static_cast(rect->width - delta); + rect->x = bounds->x; + } + delta = static_cast(bounds->y) - rect->y; + if (delta > 0.0) { + rect->height = static_cast(rect->height - delta); + rect->y = bounds->y; + } + delta = static_cast(rect->x + rect->width) - (bounds->x + bounds->width); + if (delta > 0.0) + rect->width = static_cast(rect->width - delta); + delta = static_cast(rect->y + rect->height) - (bounds->height + bounds->y); + if (delta > 0.0) + rect->height = static_cast(rect->height - delta); + return true; +} + +// PE 0x101C4B30 (ecx = colour, stream on the stack): streams "Red", "Green", "Blue" and "Alpha" +// into the four floats, stopping at the first refusal. +bool streamColor(Color* color, Stream* stream) +{ + if (!stream->streamFloat(&color->r, "Red")) return false; + if (!stream->streamFloat(&color->g, "Green")) return false; + if (!stream->streamFloat(&color->b, "Blue")) return false; + return stream->streamFloat(&color->a, "Alpha"); +} + +// PE 0x101C4CC0 (ecx = rect, stream on the stack): streams "X", "Y", "Width" and "Height" into the first four floats, +// stopping at the first refusal. +bool streamRect(Rect* rect, Stream* stream) +{ + if (!stream->streamFloat(&rect->x, "X")) return false; + if (!stream->streamFloat(&rect->y, "Y")) return false; + if (!stream->streamFloat(&rect->width, "Width")) return false; + return stream->streamFloat(&rect->height, "Height"); +} + static_assert(sizeof(QuadCorner) == 32, "retail quad corner stride"); +#if defined(_M_IX86) static_assert(sizeof(Quad) == 192, "retail QuadDrawer request size"); +#else +// RendDX9's QuadDrawRequest (GeomMisc/MenuRend/QuadDrawer.cpp) declares an 8-byte clip pointer, +// a pointer texture2 and 0x20 bytes before the corners; with the pointer-sized handle both +// sides place texture2 at +0x20 and the corners at +0x48 on x64. +static_assert(offsetof(Quad, texture2) == 0x20 && offsetof(Quad, corners) == 0x48 + && sizeof(Quad) == 0xC8, "x64 QuadDrawer request layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/Quad.h b/Code/BF2/External/BFMeme/Quad.h index a70daabdf..1271d50f3 100644 --- a/Code/BF2/External/BFMeme/Quad.h +++ b/Code/BF2/External/BFMeme/Quad.h @@ -25,7 +25,7 @@ struct Quad int state08, state0c, state10, state14; // +08..+14 unsigned char state18; // +18 unsigned char padding19[3]; // untouched - int texture2; // +1C, opaque texture handle + TextureHandle texture2; // +1C, texture handle; RendDX9 reads an IMemeTexture* std::uint32_t state20[8]; // +20..+3C, all zeroed QuadCorner corners[4]; // +40,+60,+80,+A0 }; @@ -38,6 +38,17 @@ void rotateQuad(Quad*, const float center[2], float radians); void colorQuad(Quad*, const Color*); void translateQuad(Quad*, float dx, float dy, float dz); void setQuadBounds(Quad*, float x, float y, float width, float height); + +// RendDX9's own copies of further Quad / Rect / Color helpers (PE 0x101C4B30..0x101C5210). Every body +// below is unreachable in 1.50: no code or data references. Names and placement are [INFERRED]. + +void quadCenter(const Quad*, float out[3]); // PE 0x101C4E50 +void expandQuad(Quad*, const float margin[2]); // PE 0x101C5060 +void flipQuadHorizontal(Quad*); // PE 0x101C50D0 +void flipQuadVertical(Quad*); // PE 0x101C5210 +bool clipRect(Rect* rect, const Rect* bounds); // PE 0x101C4BE0 +bool streamColor(Color* color, Stream*); // PE 0x101C4B30 +bool streamRect(Rect* rect, Stream*); // PE 0x101C4CC0 } } #endif #endif diff --git a/Code/BF2/External/BFMeme/SetVariableAction.cpp b/Code/BF2/External/BFMeme/SetVariableAction.cpp index 6bd59865e..a57798b7f 100644 --- a/Code/BF2/External/BFMeme/SetVariableAction.cpp +++ b/Code/BF2/External/BFMeme/SetVariableAction.cpp @@ -5,18 +5,37 @@ #include "Data.h" #include "Stream.h" #include "TypeDescriptor.h" +#if defined(__APPLE__) && defined(__LP64__) +#include "NativeSavedDispatch.h" +#endif namespace dice { namespace meme { namespace { // MSVC x86 dispatch captures the destination table before reading the source, then reloads the receiver. // Preserve the saved table: a normal virtual call could select a replacement receiver's implementation. // Helper names and isolation are [INFERRED]. +#if defined(__APPLE__) && defined(__LP64__) +// [CHOSEN, not recovered] Select the compiler's native slot while retaining the saved table. +using DataMethodTable = native_dispatch::SavedVirtual; +DataMethodTable captureDataMethods(Data* data) +{ return DataMethodTable(data, &Data::setFloat); } +#else using DataSetFloatMethod = bool (__thiscall*)(Data*, System*, float); using DataMethodTable = void* const*; DataMethodTable captureDataMethods(Data* data) { return *reinterpret_cast(data); } +// Slot 0x4C/4 is setFloat in both MSVC table layouts (one destructor slot); on x64 the +// __thiscall spelling is ignored and the same table index is read. +#endif void callCapturedSetFloat(DataMethodTable methods, Data* receiver, System* system, float value) +#if defined(__APPLE__) && defined(__LP64__) +// [CHOSEN, not recovered] Native ABI counterpart of the unchanged PE arm below. +{ methods(receiver, system, value); } +#else { reinterpret_cast(methods[0x4C / 4])(receiver, system, value); } +#if defined(_M_IX86) static_assert(sizeof(void*) == 4, "PE Data dispatch is x86"); +#endif +#endif } SetVariableAction::SetVariableAction() : m_variable(nullptr), m_data(nullptr) {} SetVariableAction::~SetVariableAction() {} @@ -47,6 +66,8 @@ bool SetVariableAction::execute(System* system, const Rect*, const NodeState*, c } return false; // The destination setter's result is discarded in retail. } +#if defined(_M_IX86) static_assert(sizeof(SetVariableAction) == 12, "client SetVariableAction"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/SetVariableSineAction.cpp b/Code/BF2/External/BFMeme/SetVariableSineAction.cpp index acf488e05..06da27eda 100644 --- a/Code/BF2/External/BFMeme/SetVariableSineAction.cpp +++ b/Code/BF2/External/BFMeme/SetVariableSineAction.cpp @@ -1,11 +1,17 @@ // [INFERRED] path. Complete table94D000, metadata94CD6C, constructor8330D0, // factory/eager and all differing instructions read. No runtime math shim. #include "SetVariableSineAction.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../../Math/PortableX87.h" +#endif #if !DEDICATED #include "Data.h" #include "Node.h" #include "Stream.h" #include "TypeDescriptor.h" +#if !defined(_M_IX86) +#include +#endif namespace dice { namespace meme { namespace { // PE832B86..C39, same x87 order and float stores. Helper/name [INFERRED]. @@ -15,9 +21,11 @@ namespace { bool chooseSineValue(float current, float target, float delta, float speed, float braking, float& value) { +#if defined(_WIN32) const float angle = 1.57075f; // 94CB68, bytes56 0E C9 3F float rounded; bool changed = false; +#if defined(_M_IX86) __asm { fld target fld current @@ -90,8 +98,40 @@ bool chooseSineValue(float current, float target, float delta, float speed, fstp st(0) done: } +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates) and the CRT cosine in + // place of fcos; the argument stays within [0, k], where both agree to double precision. + // Equal or unordered samples write nothing; an unordered braking test takes full speed. + if (current < target) { + const double distance = static_cast(target) - current; + const double step = distance < braking + ? std::cos(angle - distance / braking * angle) * speed * delta + : static_cast(delta) * speed; + const double candidate = step + current; + rounded = candidate > target ? target : static_cast(candidate); + changed = true; + } else if (current > target) { + const double distance = static_cast(current) - target; + const double step = distance < braking + ? std::cos(angle - distance / braking * angle) * speed * delta + : static_cast(delta) * speed; + const double candidate = current - step; + rounded = candidate < target ? target : static_cast(candidate); + changed = true; + } +#endif if (changed) value = rounded; return changed; +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-port.md). + const float angle = 1.57075f; // 94CB68, bytes56 0E C9 3F + float rounded; + bool changed = false; + // [CHOSEN, not recovered] Preserve x87 ordered movement and retained candidate comparison. + changed = bf2x87::chooseValue(current, target, delta, speed, braking, true, rounded); + if (changed) value = rounded; + return changed; +#endif } } SetVariableSineAction::SetVariableSineAction() : m_brakingDistance(0.0f) {} @@ -127,8 +167,10 @@ bool SetVariableSineAction::execute(System* system, const Rect*, const NodeState } return false; } +#if defined(_M_IX86) static_assert(sizeof(SetVariableSineAction) == 20, "client SetVariableSineAction"); static_assert(sizeof(ClassTypeDescriptor) == 16, "SetVariableSineAction metadata"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/SetVariableSoftAction.cpp b/Code/BF2/External/BFMeme/SetVariableSoftAction.cpp index c1312d26e..2b07f048b 100644 --- a/Code/BF2/External/BFMeme/SetVariableSoftAction.cpp +++ b/Code/BF2/External/BFMeme/SetVariableSoftAction.cpp @@ -1,6 +1,9 @@ // [INFERRED] path. Complete table94CF98, metadata94CD4C and every differing // body/factory/eager instruction read. #include "SetVariableSoftAction.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../../Math/PortableX87.h" +#endif #if !DEDICATED #include "Data.h" #include "Node.h" @@ -14,8 +17,10 @@ namespace { // Equal/unordered initial samples perform no write; unordered candidates survive. bool chooseSoftValue(float current, float target, float delta, float speed, float& value) { +#if defined(_WIN32) float rounded; bool changed = false; +#if defined(_M_IX86) __asm { fld target fld current @@ -57,8 +62,31 @@ bool chooseSoftValue(float current, float target, float delta, float speed, floa fstp st(0) done: } +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + // An ordered current below the target moves up, above it moves down; equal or unordered + // samples write nothing. Only an ordered overshoot of the unrounded candidate clamps. + if (current < target) { + const double candidate = static_cast(delta) * speed + current; + rounded = candidate > target ? target : static_cast(candidate); + changed = true; + } else if (current > target) { + const double candidate = current - static_cast(delta) * speed; + rounded = candidate < target ? target : static_cast(candidate); + changed = true; + } +#endif if (changed) value = rounded; return changed; +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-port.md). + float rounded; + bool changed = false; + // [CHOSEN, not recovered] Preserve x87 ordered movement and retained candidate comparison. + changed = bf2x87::chooseValue(current, target, delta, speed, 0.0f, false, rounded); + if (changed) value = rounded; + return changed; +#endif } } SetVariableSoftAction::SetVariableSoftAction() : m_speed(100.0f) {} // 8331A0..AC @@ -93,8 +121,10 @@ bool SetVariableSoftAction::execute(System* system, const Rect*, const NodeState } return false; } +#if defined(_M_IX86) static_assert(sizeof(SetVariableSoftAction) == 16, "client SetVariableSoftAction"); static_assert(sizeof(ClassTypeDescriptor) == 16, "SetVariableSoftAction metadata"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/ShowEffectNode.cpp b/Code/BF2/External/BFMeme/ShowEffectNode.cpp index 68eafd631..0ac03e0c6 100644 --- a/Code/BF2/External/BFMeme/ShowEffectNode.cpp +++ b/Code/BF2/External/BFMeme/ShowEffectNode.cpp @@ -69,7 +69,9 @@ void ShowEffectNode::paint(System* system, const NodeState* state, } Node::paint(system, state, bounds, clip, context); } +#if defined(_M_IX86) static_assert(sizeof(ShowEffectNode) == 12, "client ShowEffectNode prefix storage"); static_assert(sizeof(ShowEffectNodeTypeDescriptor) == 16, "ShowEffectNode metadata"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/SliderNode.cpp b/Code/BF2/External/BFMeme/SliderNode.cpp index a9f9b13b2..92f9c1b63 100644 --- a/Code/BF2/External/BFMeme/SliderNode.cpp +++ b/Code/BF2/External/BFMeme/SliderNode.cpp @@ -1,12 +1,15 @@ -// dice::meme::SliderNode. Constructor, metadata, both child accessors and -// visitChildren are read in full from BF2.exe; the six per-frame/event bodies -// below are named frontiers with their addresses and byte counts recorded. +// dice::meme::SliderNode, read in full from BF2.exe 0x833660..0x833DD2 (BFMeme library slider; the +// HUD builds Bf2FixedSliderNode). x87 intermediates are carried in double and stored as float +// where the shipped code stores them; the owner dropped the bit-exact goal (2026-11-05). #include "SliderNode.h" #if !DEDICATED #include "TypeDescriptor.h" #include "Style.h" // dice::meme::Rect is defined here -#include -#include +#include "Data.h" +#include "SliderNodeMath.h" +#include "NodeState.h" +#include "Stream.h" +#include "System.h" namespace dice { namespace meme { // Node() first, then nine own words in the shipped order: the vptr @@ -68,40 +71,155 @@ void SliderNode::visitChildren(System* system, NodeState* state, const Rect* bou } -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: slider-node-bodies] -// Unfinished drawing and input methods diagnose and stop on use; BfFixedSliderNode shares these boundaries. +using namespace slider; -namespace { -void sliderFrontier(const char* method, const char* site) +// 833700: the thumb's width on a track of the given width. +float SliderNode::thumbExtent(const float* width) const { - std::fprintf(stderr, "[FRONTIER] dice::meme::SliderNode::%s reached (BF2.exe %s)\n", - method, site); - std::fflush(stderr); - std::abort(); + return static_cast(m_thumbSpan / orderedSpan(m_minimum, m_maximum) * *width); } + +// 833740: places the thumb from the bound value; nothing without a Data. The value +// scale uses the plain max - min (not the ordered span) as shipped. +void SliderNode::syncFromData(System* system, const float* width) +{ + if (!m_data) return; + const double thumb = m_thumbSpan / orderedSpan(m_minimum, m_maximum) * *width; + const float scale = static_cast((*width - thumb) / + (static_cast(m_maximum) - m_minimum)); + m_thumbOffset = static_cast( + (static_cast(m_data->getFloat(system)) - m_minimum) * scale); } -bool SliderNode::streamProperties(System*, Stream*) -{ sliderFrontier("streamProperties", "833660, 151 B"); return false; } +// 833660: Node's properties, then the cursor (thumb) node, the bound Data and the three +// range floats, each stream answer gating the next. +bool SliderNode::streamProperties(System* system, Stream* stream) +{ + if (!Node::streamProperties(system, stream)) return false; + if (!stream->streamNode0x84(system, m_child1, "Cursor node", nullptr)) return false; + if (!stream->streamData(system, m_data, "Data", nullptr)) return false; + if (!stream->streamFloat(&m_minimum, "Minimum value")) return false; + if (!stream->streamFloat(&m_maximum, "Maximum value")) return false; + return stream->streamFloat(&m_thumbSpan, "Number visible"); +} -void SliderNode::paint(System*, const NodeState*, const Rect*, const Rect*, RenderContext*) -{ sliderFrontier("paint", "833B80, 269 B"); } +// 833B80: the thumb rectangle, painted with the slider's own state; under an effect it +// gets a child context (the parent, no effect, the decoded state and its rate) as a +// TransformNode builds one. Then Node's own paint. +void SliderNode::paint(System* system, const NodeState* state, const Rect* bounds, + const Rect* clip, RenderContext* context) +{ + if (m_child1) { + Rect thumb = *bounds; + thumb.x = bounds->x + m_thumbOffset; + thumb.width = static_cast(m_thumbSpan / orderedSpan(m_minimum, m_maximum) * thumb.width); + if (context->effect) { + RenderContext child = {context, nullptr, context->field08, context->field0c, + context->field10, decodedState(m_state.current), 1.0f}; + child.field10 = stateRate(m_state); + m_child1->paint(system, &m_state, &thumb, clip, &child); + } else { + m_child1->paint(system, &m_state, &thumb, clip, context); + } + } + Node::paint(system, state, bounds, clip, context); +} -bool SliderNode::update(System*, const NodeState*, const Rect*, float) -{ sliderFrontier("update", "833C90, 325 B"); return false; } +// 833C90: the slider's state follows the pointer over the thumb (only while the parent +// is pressed, edges included, NaN inside) and the parent's decoded state; then the thumb +// updates, and a refusal stops the walk before Node's own update. +bool SliderNode::update(System* system, const NodeState* state, const Rect* bounds, float delta) +{ + Rect thumb = *bounds; + thumb.x = bounds->x + m_thumbOffset; + thumb.width = static_cast(m_thumbSpan / orderedSpan(m_minimum, m_maximum) * thumb.width); + bool inside = false; + if (state->target < 0.0f) inside = pointerInside(system->getPointerPosition(), thumb); + const bool enabled = !(decodedState(state->target) < 1.0f); + updateNodeState(&m_state, system, this, m_child1, &thumb, delta, inside, enabled); + if (m_child1 && !m_child1->update(system, &m_state, &thumb, delta)) return false; + return Node::update(system, state, bounds, delta); +} -bool SliderNode::updateSelf(System*, const NodeState*, const Rect*, float) -{ sliderFrontier("updateSelf", "833810, 233 B"); return false; } +// 833810: while a press is held the thumb follows the pointer (clamped into the track, +// less the grab offset, kept inside [0, width - thumb]) and writes the value back to the +// Data; otherwise it is placed from the Data. Always true. +bool SliderNode::updateSelf(System* system, const NodeState* state, const Rect* rect, float) +{ + if (!m_data) return true; + if (!pressHeld(state, system)) { + syncFromData(system, &rect->width); + return true; + } + const float* pointer = system->getPointerPosition(); + float position[2] = {pointer[0], pointer[1]}; + clampToRect(position, rect); + position[0] = position[0] - rect->x; + const double thumb = m_thumbSpan / orderedSpan(m_minimum, m_maximum) * rect->width; + const double offset = static_cast(position[0]) - m_grabOffset; + m_thumbOffset = static_cast(offset); + if (offset < 0.0) m_thumbOffset = 0.0f; + const double limit = rect->width - thumb; + if (!(m_thumbOffset < limit) && !(limit != limit) && !(m_thumbOffset != m_thumbOffset)) + m_thumbOffset = static_cast(limit); + const double value = m_thumbOffset / + ((rect->width - thumb) / (static_cast(m_maximum) - m_minimum)) + m_minimum; + m_data->setFloat(system, static_cast(value)); + return true; +} -bool SliderNode::onEvent1(System*, const Rect*, const NodeState*, int, int, int) -{ sliderFrontier("onEvent1", "833900, 292 B"); return false; } +// 833900: a primary press (first 1, second 1) that is not already held locks the pointer +// and records where on the thumb it landed. A press beside the thumb pages it by whole +// thumb widths towards the pointer (clamped at both track ends), then the slider updates +// once with a zero delta. A held or other press is refused. +bool SliderNode::onEvent1(System* system, const Rect* rect, const NodeState* state, + int first, int, int second) +{ + if (pressHeld(state, system)) return false; + if (first != 1 || second != 1) return false; + system->lockPointer(); + const float* pointer = system->getPointerPosition(); + const float local = static_cast(static_cast(pointer[0]) - rect->x); + m_grabOffset = static_cast(static_cast(local) - m_thumbOffset); + const float grab = m_grabOffset; + const float page = thumbExtent(&rect->width); + if (grab < 0.0f) { + do { + m_thumbOffset = static_cast(static_cast(m_thumbOffset) - page); + m_grabOffset = static_cast(static_cast(page) + m_grabOffset); + if (m_thumbOffset < 0.0f) { + m_grabOffset = local; + m_thumbOffset = 0.0f; + } + } while (m_grabOffset < 0.0f); + } + while (m_grabOffset > page) { + m_thumbOffset = static_cast(static_cast(page) + m_thumbOffset); + m_grabOffset = static_cast(static_cast(m_grabOffset) - page); + if (static_cast(page) + m_thumbOffset >= rect->width) { // `test ah,1`: NaN skips + m_thumbOffset = static_cast(static_cast(rect->width) - page); + m_grabOffset = static_cast(static_cast(local) - m_thumbOffset); + } + } + updateSelf(system, state, rect, 0.0f); + return true; +} -// One shipped body serves both slots +78 and +7C; it is not duplicated code. -bool SliderNode::onEvent2(System*, const Rect*, const NodeState*, int, int) -{ sliderFrontier("onEvent2", "833A30, 46 B, shared with onEvent3"); return false; } +// 833A30, both slots +78 and +7C: the release of the primary press unlocks the pointer and +// re-places the thumb from the Data. Never consumes the event. +bool SliderNode::onEvent2(System* system, const Rect* rect, const NodeState*, int first, int) +{ + if (first == 1) { + system->unlockPointer(); + syncFromData(system, &rect->width); + } + return false; +} -bool SliderNode::onEvent3(System*, const Rect*, const NodeState*, int, int) -{ sliderFrontier("onEvent3", "833A30, 46 B, shared with onEvent2"); return false; } +bool SliderNode::onEvent3(System* system, const Rect* rect, const NodeState* state, int first, int index) +{ + return SliderNode::onEvent2(system, rect, state, first, index); +} } } #endif diff --git a/Code/BF2/External/BFMeme/SliderNode.h b/Code/BF2/External/BFMeme/SliderNode.h index 07dbb1716..035d81516 100644 --- a/Code/BF2/External/BFMeme/SliderNode.h +++ b/Code/BF2/External/BFMeme/SliderNode.h @@ -15,20 +15,25 @@ class SliderNode : public Node // nothing, so nothing is freed. TypeDescriptor* getType() override; unsigned int getObjectSize() override; - bool streamProperties(System*, Stream*) override; // 833660 [FRONTIER] + bool streamProperties(System*, Stream*) override; // 833660 int getChildCount() override; // 828A70, the shared 2 Node*& getChild(int index) override; void setChild(int index, Node* child) override; void visitChildren(System*, NodeState*, const Rect*, NodeVisitor*) override; - void paint(System*, const NodeState*, const Rect*, const Rect*, RenderContext*) override; // 833B80 [FRONTIER] - bool update(System*, const NodeState*, const Rect*, float) override; // 833C90 [FRONTIER] - bool updateSelf(System*, const NodeState*, const Rect*, float) override; // 833810 [FRONTIER] - bool onEvent1(System*, const Rect*, const NodeState*, int, int, int) override; // 833900 [FRONTIER] - bool onEvent2(System*, const Rect*, const NodeState*, int, int) override; // 833A30 [FRONTIER] + void paint(System*, const NodeState*, const Rect*, const Rect*, RenderContext*) override; // 833B80 + bool update(System*, const NodeState*, const Rect*, float) override; // 833C90 + bool updateSelf(System*, const NodeState*, const Rect*, float) override; // 833810 + bool onEvent1(System*, const Rect*, const NodeState*, int, int, int) override; // 833900 + bool onEvent2(System*, const Rect*, const NodeState*, int, int) override; // 833A30 bool onEvent3(System*, const Rect*, const NodeState*, int, int) override; // 833A30, same body static TypeDescriptor* getClassType(); + // Public: fixtures reach them, and MSVC mangles member access into the name. + float thumbExtent(const float* width) const; // 833700 + void syncFromData(System*, const float* width); // 833740 + protected: + friend struct SliderNodeFixture; // Names [INFERRED] from visitChildren 833AF0 and the BfFixedSliderNode // clone's drag arithmetic (7D4250); the constructor's values are exact. @@ -36,12 +41,14 @@ class SliderNode : public Node float m_thumbOffset; // +0C, ctor 0; added to bounds.x for the thumb float m_minimum; // +10, ctor 0 float m_maximum; // +14, ctor 1.0 - float m_thumbSpan; // +18, ctor 1.0; divided by |max - min| + float m_thumbSpan; // +18, ctor 1.0; "Number visible", divided by |max - min| Data* m_data; // +1C, ctor null Node* m_child1; // +20, ctor null; the thumb, child index 1 NodeState m_state; // +24/+28, ctor {1.0, 1.0} }; +#if defined(_M_IX86) static_assert(sizeof(SliderNode) == 44, "retail and native SliderNode storage"); +#endif } } #endif #endif diff --git a/Code/BF2/External/BFMeme/SliderNodeMath.h b/Code/BF2/External/BFMeme/SliderNodeMath.h new file mode 100644 index 000000000..0e041136d --- /dev/null +++ b/Code/BF2/External/BFMeme/SliderNodeMath.h @@ -0,0 +1,63 @@ +// Path and names [INFERRED]. Arithmetic shared by SliderNode (BF2.exe 0x833660..) and its clone +// BfFixedSliderNode (0x7D3D50..): retail repeats each of these inline or as small helpers in both. +// x87 intermediates are carried in double; stores are float where the shipped code stores. +#ifndef BFMEME_SLIDERNODEMATH_H +#define BFMEME_SLIDERNODEMATH_H +#include "Node.h" +#include "Style.h" // Rect +#include "System.h" +#if !DEDICATED +namespace dice { namespace meme { namespace slider { +// The span every body re-derives with one `fcomp`: only a maximum strictly below the minimum +// takes the reversed subtraction, so NaN falls with the normal case. +inline double orderedSpan(float minimum, float maximum) +{ + return maximum < minimum ? static_cast(minimum) - maximum + : static_cast(maximum) - minimum; +} +// The negative-encoded NodeState value (`fadd 1.0; fchs` on an ordered negative), as +// TransformNode's copy; zero, positive and NaN pass through. +inline float decodedState(float value) +{ + return static_cast(value < 0.0f ? -(static_cast(value) + 1.0) : value); +} +// 838F40: the transition rate a child context carries (TransformNode's stateRate). +inline float stateRate(const NodeState& state) +{ + const float current = decodedState(state.current); + const float target = decodedState(state.target); + if (target < current) return -3.0f; + if (target > current) return 3.0f; + return 0.0f; +} +// 838EF0: a press is held - the pointer is locked (6CFB80 nonzero) and the node's current +// state is ordered-negative (the pressed encoding). +inline bool pressHeld(const NodeState* state, System* system) +{ + return system->getLockCount() != 0 && state->current < 0.0f; +} +// 74DBA0: clamps a point into the rectangle, far edges included; each test is the shipped +// `fcomp`/`jp` pair, so an unordered coordinate is left untouched. +inline void clampToRect(float point[2], const Rect* rect) +{ + if (point[0] < rect->x) point[0] = rect->x; + else { + const float right = rect->width + rect->x; + if (right < point[0]) point[0] = right; + } + if (point[1] < rect->y) point[1] = rect->y; + else { + const float bottom = rect->height + rect->y; + if (bottom < point[1]) point[1] = bottom; + } +} +// The pointer-over-thumb test of update(): edges included, unordered coordinates pass. +inline bool pointerInside(const float* pointer, const Rect& thumb) +{ + return !(pointer[0] < thumb.x) && !(pointer[1] < thumb.y) + && !(static_cast(thumb.width) + thumb.x < pointer[0]) + && !(static_cast(thumb.height) + thumb.y < pointer[1]); +} +} } } +#endif +#endif diff --git a/Code/BF2/External/BFMeme/SplitNode.cpp b/Code/BF2/External/BFMeme/SplitNode.cpp index 60c2b1579..ff23976f2 100644 --- a/Code/BF2/External/BFMeme/SplitNode.cpp +++ b/Code/BF2/External/BFMeme/SplitNode.cpp @@ -76,7 +76,9 @@ namespace { // Eager initializer871650 shares the lazy descriptor, registering before lookup. TypeDescriptor* const registeredSplitNodeType = SplitNode::getClassType(); } +#if defined(_M_IX86) static_assert(sizeof(SplitNode) == 12, "client BFMeme SplitNode"); static_assert(sizeof(SplitNodeTypeDescriptor) == 16, "client SplitNode metadata"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/Stream.cpp b/Code/BF2/External/BFMeme/Stream.cpp index 3da873c8c..9831c719d 100644 --- a/Code/BF2/External/BFMeme/Stream.cpp +++ b/Code/BF2/External/BFMeme/Stream.cpp @@ -7,7 +7,11 @@ #include "Event.h" #include "Action.h" #include "Function.h" +#include "Tree.h" +#include +#include namespace dice { namespace meme { +TypeDescriptor* getTreeClassType() { return Tree::getClassType(); } // 0x83D010 (Tree.cpp) TypeDescriptor* getEventClassType() { return Event::getClassType(); } TypeDescriptor* getActionClassType() { return Action::getClassType(); } TypeDescriptor* getFunctionClassType() { return Function::getClassType(); } @@ -24,8 +28,8 @@ bool Stream::streamInt(int*, const char*) { return isPassive(); } bool Stream::streamString(char**, const char*) { return isPassive(); } bool Stream::streamWideString(wchar_t**, const char*) { return isPassive(); } bool Stream::streamCharacter(wchar_t*, const char*) { return isPassive(); } -bool Stream::streamTexture(System*, int*, const char*) { return isPassive(); } -bool Stream::streamFont(System*, int*, const char*) { return isPassive(); } +bool Stream::streamTexture(System*, TextureHandle*, const char*) { return isPassive(); } +bool Stream::streamFont(System*, FontHandle*, const char*) { return isPassive(); } bool Stream::streamSound(System*, int*, const char*) { return isPassive(); } bool Stream::streamCollection(System*, ObjectCollection*, const char*) { return isPassive(); } bool Stream::streamEnum(int*, EnumNext, EnumName, const char*) { return isPassive(); } @@ -94,7 +98,9 @@ bool createObject(System* system, Object*& value, TypeDescriptor* type) deletion.streamObject(system, value, "Object", nullptr); // ignored result return false; } +#if defined(_M_IX86) static_assert(sizeof(Stream) == 4, "BFMeme stream prefix"); static_assert(sizeof(DeletionStream) == 8, "BFMeme deletion visitor"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/Stream.h b/Code/BF2/External/BFMeme/Stream.h index a2cfec252..c1f943921 100644 --- a/Code/BF2/External/BFMeme/Stream.h +++ b/Code/BF2/External/BFMeme/Stream.h @@ -39,8 +39,8 @@ class Stream : public RuntimeObject virtual bool streamString(char**, const char*); // +40 virtual bool streamWideString(wchar_t**, const char*); // +44 virtual bool streamCharacter(wchar_t*, const char*); // +48 - virtual bool streamTexture(System*, int*, const char*); // +4C 837D20 - virtual bool streamFont(System*, int*, const char*); // +50 + virtual bool streamTexture(System*, TextureHandle*, const char*); // +4C 837D20 + virtual bool streamFont(System*, FontHandle*, const char*); // +50 virtual bool streamSound(System*, int*, const char*); // +54 virtual bool streamCollection(System*, ObjectCollection*, const char*); // +58 virtual bool streamEnum(int*, EnumNext, EnumName, const char*); // +5C 837D30 @@ -85,7 +85,7 @@ TypeDescriptor* getActionClassType(); // 83C320, complete Action TypeDescriptor* getEffectClassType(); // 82D860, complete Effect family TypeDescriptor* getFunctionClassType(); // 82E510, complete Function family TypeDescriptor* getNodeClassType(); // 82C190, real native-prefix metadata/factory; suffix caller stops -TypeDescriptor* getTreeClassType(); // 83D010 [FRONTIER] +TypeDescriptor* getTreeClassType(); // 83D010 [FRONTIER] stops; Tree family unrecovered } } #endif #endif diff --git a/Code/BF2/External/BFMeme/Style.cpp b/Code/BF2/External/BFMeme/Style.cpp index 2620f2616..5dc623df3 100644 --- a/Code/BF2/External/BFMeme/Style.cpp +++ b/Code/BF2/External/BFMeme/Style.cpp @@ -26,7 +26,7 @@ char* cloneStyleName(const char* name) // shared helper0x737DC0 } } -Style::Style(const char* name, int font) +Style::Style(const char* name, FontHandle font) : m_font(font), m_name(cloneStyleName(name)) { // Retail deliberately leaves m_shadowFont and both scale fields untouched. @@ -199,7 +199,9 @@ void Style::positionGlyphInt(Rect* output, const GlyphMetrics* metrics, *y = static_cast(floatY); } +#if defined(_M_IX86) static_assert(sizeof(Style) == 24, "PE Style allocation"); +#endif static_assert(sizeof(GlyphMetrics) == 20, "five scalar glyph metrics"); static_assert(sizeof(Rect) == 20, "five scalar drawing bounds"); } } diff --git a/Code/BF2/External/BFMeme/Style.h b/Code/BF2/External/BFMeme/Style.h index 1dd1622ef..c441850cd 100644 --- a/Code/BF2/External/BFMeme/Style.h +++ b/Code/BF2/External/BFMeme/Style.h @@ -22,7 +22,7 @@ struct Rect class Style : public Object { public: - Style(const char* name = 0, int font = 0); + Style(const char* name = 0, FontHandle font = 0); ~Style() override; TypeDescriptor* getType() override; unsigned int getObjectSize() override; @@ -42,8 +42,8 @@ class Style : public Object static TypeDescriptor* getClassType(); // 838C90, descriptor factory838D40 protected: - int m_font; // +04, integer handle - int m_shadowFont; // +08, not written by ctor + FontHandle m_font; // +04, integer handle + FontHandle m_shadowFont; // +08, not written by ctor char* m_name; // +0C, owned clone float m_scale, m_reciprocalScale; // +10/+14, not written by ctor }; diff --git a/Code/BF2/External/BFMeme/System.cpp b/Code/BF2/External/BFMeme/System.cpp index f651a98f8..cb4855caa 100644 --- a/Code/BF2/External/BFMeme/System.cpp +++ b/Code/BF2/External/BFMeme/System.cpp @@ -42,7 +42,9 @@ class SystemTypeDescriptor final : public TypeDescriptor static int instanceCount; }; int SystemTypeDescriptor::instanceCount = 0; +#if defined(_M_IX86) static_assert(sizeof(SystemTypeDescriptor) == 16, "System metadata stores its counter separately"); +#endif // A3970C is a plain dword whose bit zero is set before construction. Retail has no lock and no // exception rollback here; avoid the compiler's C++11 thread-safe function-static guard. @@ -164,19 +166,19 @@ OStream* System::createOutputStream(const char*) { return nullptr; } void System::deleteOutputStream(OStream* stream) { delete stream; } void System::deleteInputStream(IStream* stream) { delete stream; } bool System::pointerPositionChanged(float*, float*) { return true; } -bool System::drawCharacter(int, int, Quad*) { return false; } -bool System::getGlyphMetrics(int, int, GlyphMetrics*) { return false; } -float System::getKerning(int, int, int) { return 0.0f; } -float System::getFontHeight(int) { return 0.0f; } -int System::loadFont(const char*) { return 0; } -const char* System::getFontName(int) { return nullptr; } -bool System::drawTexture(int, Quad*) { return false; } -int System::loadTexture(const char*, bool) { return 0; } -void System::releaseTexture(int) {} // 5AB2A0, real empty default -const char* System::getTextureName(int) { return nullptr; } -float System::getTextureWidth(int) { return 0.0f; } -float System::getTextureHeight(int) { return 0.0f; } -void System::setDefaultTexture(int texture) { m_field054 = texture; } +bool System::drawCharacter(int, FontHandle, Quad*) { return false; } +bool System::getGlyphMetrics(int, FontHandle, GlyphMetrics*) { return false; } +float System::getKerning(int, int, FontHandle) { return 0.0f; } +float System::getFontHeight(FontHandle) { return 0.0f; } +FontHandle System::loadFont(const char*) { return 0; } +const char* System::getFontName(FontHandle) { return nullptr; } +bool System::drawTexture(TextureHandle, Quad*) { return false; } +TextureHandle System::loadTexture(const char*, bool) { return 0; } +void System::releaseTexture(TextureHandle) {} // 5AB2A0, real empty default +const char* System::getTextureName(TextureHandle) { return nullptr; } +float System::getTextureWidth(TextureHandle) { return 0.0f; } +float System::getTextureHeight(TextureHandle) { return 0.0f; } +void System::setDefaultTexture(TextureHandle texture) { m_field054 = texture; } bool System::playSound(int, float) { return false; } // 455420, real default int System::loadSound(const char*) { return 0; } const char* System::getSoundName(int) { return nullptr; } @@ -255,7 +257,9 @@ class EventNodeVisitor : public NodeVisitor private: NodeInputEvent m_event; }; +#if defined(_M_IX86) static_assert(sizeof(EventNodeVisitor) == 28, "client generic event visitor"); +#endif Node* castMenuNode(Object* object) { @@ -355,9 +359,11 @@ void systemPrintf(System* system, const char* format, ...) } } +#if defined(_M_IX86) static_assert(sizeof(Object) == 4, "BF2 client Object prefix size"); static_assert(sizeof(OStream) == 4, "Ref2System embeds a four-byte OStream"); static_assert(sizeof(System) == 0x58, "System has no STL-dependent members"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/System.h b/Code/BF2/External/BFMeme/System.h index 14b29589f..5840fc2ef 100644 --- a/Code/BF2/External/BFMeme/System.h +++ b/Code/BF2/External/BFMeme/System.h @@ -47,24 +47,24 @@ class System : public Object // +6C: Pointer829000 passes addresses of its two float arguments. Pointer // versus reference source spelling and method name are [INFERRED]. virtual bool pointerPositionChanged(float* x, float* y); - virtual bool drawCharacter(int character, int font, Quad*); - virtual bool getGlyphMetrics(int character, int font, GlyphMetrics*); + virtual bool drawCharacter(int character, FontHandle font, Quad*); + virtual bool getGlyphMetrics(int character, FontHandle font, GlyphMetrics*); // Source character spelling [INFERRED]; full dwords cross Font+10 and the // .dif backend deliberately keeps only the low sixteen bits of each key. - virtual float getKerning(int previous, int current, int font); - virtual float getFontHeight(int font); // +7C 829A30 - virtual int loadFont(const char* name); - virtual const char* getFontName(int font); - virtual bool drawTexture(int texture, Quad*); - virtual int loadTexture(const char* name, bool menuPath); // +8C 6212F0 - virtual void releaseTexture(int texture); - virtual const char* getTextureName(int texture); - virtual float getTextureWidth(int texture); - virtual float getTextureHeight(int texture); // +9C 829A30 + virtual float getKerning(int previous, int current, FontHandle font); + virtual float getFontHeight(FontHandle font); // +7C 829A30 + virtual FontHandle loadFont(const char* name); + virtual const char* getFontName(FontHandle font); + virtual bool drawTexture(TextureHandle texture, Quad*); + virtual TextureHandle loadTexture(const char* name, bool menuPath); // +8C 6212F0 + virtual void releaseTexture(TextureHandle texture); + virtual const char* getTextureName(TextureHandle texture); + virtual float getTextureWidth(TextureHandle texture); + virtual float getTextureHeight(TextureHandle texture); // +9C 829A30 // Setter return spelling is [INFERRED]: HUD7583D5 supplies loadTexture's // int handle and discards EAX.5C9490 leaves the stored argument in EAX; // that alone does not prove a source-level return value. - virtual void setDefaultTexture(int texture); // +A0 5C9490 + virtual void setDefaultTexture(TextureHandle texture); // +A0 5C9490 virtual bool playSound(int sound, float volume); // +A4 455420 virtual int loadSound(const char* name); // +A8 4553E0 virtual const char* getSoundName(int sound); // +AC 4553E0 @@ -120,7 +120,7 @@ class System : public Object EventQueue* m_eventQueue; // +48 IStream* m_field04c; // +4C, cache replay input; wrappers borrow it OStream* m_field050; // +50, cache recording output; wrappers borrow it - int m_field054; // +54, default texture handle + TextureHandle m_field054; // +54, default texture handle }; // 0x82A340; exact return is unused by recovered callers, source name [INFERRED]. diff --git a/Code/BF2/External/BFMeme/TextNode.cpp b/Code/BF2/External/BFMeme/TextNode.cpp index 1022bc382..9349be783 100644 --- a/Code/BF2/External/BFMeme/TextNode.cpp +++ b/Code/BF2/External/BFMeme/TextNode.cpp @@ -73,7 +73,9 @@ void drawStyledText(System* system, Style* style, const Rect* bounds, style->drawText(system, data, elementIndex, bounds, clip, context); } +#if defined(_M_IX86) static_assert(sizeof(BfTextNode) == 24, "native BfTextNode storage"); static_assert(sizeof(ClassTypeDescriptor) == 16, "BfTextNode metadata"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/TextNode.h b/Code/BF2/External/BFMeme/TextNode.h index 2b4cc07ae..57ca97378 100644 --- a/Code/BF2/External/BFMeme/TextNode.h +++ b/Code/BF2/External/BFMeme/TextNode.h @@ -26,7 +26,9 @@ class BfTextNode : public Node Data* m_type; // +10, streamed as "Type", borrowed; gates the paint ColorEffect* m_shadow; // +14, owned; the constructor allocates a black one }; +#if defined(_M_IX86) static_assert(sizeof(BfTextNode) == 24, "native BfTextNode storage"); +#endif // A free __fastcall helper, not a member: the System and the Style sit // in ECX/EDX and the rest on the stack. Name [INFERRED]. diff --git a/Code/BF2/External/BFMeme/ToggleData.cpp b/Code/BF2/External/BFMeme/ToggleData.cpp index 443696fec..fa2f60030 100644 --- a/Code/BF2/External/BFMeme/ToggleData.cpp +++ b/Code/BF2/External/BFMeme/ToggleData.cpp @@ -60,7 +60,9 @@ int ToggleData::getCharacter(System* system, int character) Data* selected = m_toggle && m_toggle->getFloat(system) == 0.0f ? m_first : m_second; return selected ? selected->getCharacter(system, character) : 0; } +#if defined(_M_IX86) static_assert(sizeof(ToggleData) == 20, "client ToggleData"); static_assert(sizeof(ToggleDataDescriptor) == 16, "client ToggleData metadata"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/TransformLayout.h b/Code/BF2/External/BFMeme/TransformLayout.h new file mode 100644 index 000000000..85b4f3c66 --- /dev/null +++ b/Code/BF2/External/BFMeme/TransformLayout.h @@ -0,0 +1,20 @@ +// [CHOSEN, not recovered] Optional native layout policy; no object or vtable layout changes. +// https://github.com/kr4uzi/OpenBF2/issues/33 +#ifndef BFMEME_TRANSFORMLAYOUT_H +#define BFMEME_TRANSFORMLAYOUT_H +#include "../../Core/BuildConfig.h" +#if !DEDICATED +#include "Style.h" +#include "../../Math/Vec3.h" +namespace dice { namespace meme { +class Node; +class System; +typedef void (*TransformBoundsFilter)(System*, Node*, Rect&); +extern TransformBoundsFilter transformBoundsFilter; + +// Compute the same bounds for painting, input and traversal, without changing authored geometry. +Rect layoutTransformBounds(System*, Node*, const Rect& parent, + const hfe::Vec2& position, const hfe::Vec2& size); +} } +#endif +#endif diff --git a/Code/BF2/External/BFMeme/TransformNode.cpp b/Code/BF2/External/BFMeme/TransformNode.cpp index 666df438b..49ea38754 100644 --- a/Code/BF2/External/BFMeme/TransformNode.cpp +++ b/Code/BF2/External/BFMeme/TransformNode.cpp @@ -1,5 +1,9 @@ // Transform-node state updates and metadata; unsupported Node suffix calls retain diagnostic stops. #include "TransformNode.h" +#include "TransformLayout.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../../Math/PortableX87.h" +#endif #if !DEDICATED #include "NodeState.h" #include "Stream.h" @@ -7,6 +11,15 @@ #include "System.h" #include "TypeDescriptor.h" namespace dice { namespace meme { +// [CHOSEN, not recovered] Issue #33: clients may supply a layout policy for their own System. +TransformBoundsFilter transformBoundsFilter = nullptr; +Rect layoutTransformBounds(System* system, Node* node, const Rect& parent, + const hfe::Vec2& position, const hfe::Vec2& size) +{ + Rect result = {parent.x + position.x, parent.y + position.y, size.x, size.y, parent.z}; + if (transformBoundsFilter) transformBoundsFilter(system, node, result); + return result; +} namespace { // [INFERRED] descriptor class name. Table94AE90 is a complete eight-slot // interface; its independent counterA398D4 is not adjusted by construction. @@ -30,6 +43,8 @@ class TransformNodeTypeDescriptor final : public TypeDescriptor unsigned int getInstanceSize() override { return sizeof(TransformNode); } }; +// PE 0x101C4BA0: RendDX9's standalone copy (ecx = value, stream and the two names on the stack, retn +// 0xC); unreachable in 1.50 there: no code or data references. bool streamPair(hfe::Vec2& value, Stream* stream, const char* first, const char* second) { if (!stream->streamFloat(&value.x, first)) return false; @@ -37,6 +52,8 @@ bool streamPair(hfe::Vec2& value, Stream* stream, const char* first, const char* } float decodedState(float value) // float stores in838F40 and82D340 { +#if defined(_WIN32) +#if defined(_M_IX86) float result; __asm { fld value @@ -51,6 +68,20 @@ float decodedState(float value) // float stores in838F40 and82D340 fstp result } return result; +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + // Only an ordered negative value is decoded; zero, positive and NaN pass through the + // double round trip, which quiets a signalling NaN as fld/fstp does. + const double loaded = value; + return static_cast(value < 0.0f ? -(loaded + 1.0) : loaded); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-port.md). + float result; + // [CHOSEN, not recovered] Preserve x87 negative-state decoding and float store. + result = bf2x87::store(bf2x87::decoded(value)); + return result; +#endif } float stateRate(const NodeState& state) // 838F40 ->82BD30; System/Node receivers unused { @@ -62,6 +93,8 @@ float stateRate(const NodeState& state) // 838F40 ->82BD30; System/Node receiver } bool sumNotLess(float first, float second, float limit) // 82D49E..4BB, unordered passes { +#if defined(_WIN32) +#if defined(_M_IX86) bool result; __asm { fld first @@ -72,6 +105,19 @@ bool sumNotLess(float first, float second, float limit) // 82D49E..4BB, unordere setp result } return result; +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + // setp after test ah,5: false only for an ordered sum below the limit. + const double sum = static_cast(first) + second; + return !(sum < limit); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-port.md). + bool result; + // [CHOSEN, not recovered] Preserve x87 unordered-or-not-less sum. + result = bf2x87::sumNotLess(first, second, limit); + return result; +#endif } } @@ -109,16 +155,14 @@ bool TransformNode::streamProperties(System* system, Stream* stream) void TransformNode::visitChildren(System* system, NodeState* state, const Rect* bounds, NodeVisitor* visitor) { - const Rect transformed = {bounds->x + m_position.x, bounds->y + m_position.y, - m_size.x, m_size.y, bounds->z}; + const Rect transformed = layoutTransformBounds(system, this, *bounds, m_position, m_size); visitor->traverse0x08(system, m_child, &transformed, &m_state); visitor->visit(system, m_next, bounds, state); } void TransformNode::paint(System* system, const NodeState* state, const Rect* bounds, const Rect* clip, RenderContext* context) { - const Rect transformed = {bounds->x + m_position.x, bounds->y + m_position.y, - m_size.x, m_size.y, bounds->z}; + const Rect transformed = layoutTransformBounds(system, this, *bounds, m_position, m_size); paintSelf(system, state, &transformed, clip, context); if (m_child) { if (context->effect) { @@ -133,8 +177,7 @@ void TransformNode::paint(System* system, const NodeState* state, const Rect* bo bool TransformNode::update(System* system, const NodeState* state, const Rect* bounds, float delta) { - const Rect transformed = {bounds->x + m_position.x, bounds->y + m_position.y, - m_size.x, m_size.y, bounds->z}; + const Rect transformed = layoutTransformBounds(system, this, *bounds, m_position, m_size); bool inside = false; if (state->target < 0.0f) { const float* position = system->getPointerPosition(); @@ -154,7 +197,9 @@ void TransformNode::reset() // 82D560; Node's real+C4 dispatch remains a named f if (m_child) m_child->reset(); Node::reset(); } +#if defined(_M_IX86) static_assert(sizeof(TransformNode) == 36, "native x86 TransformNode storage"); static_assert(sizeof(TransformNodeTypeDescriptor) == 16, "native TransformNode metadata"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/Tree.cpp b/Code/BF2/External/BFMeme/Tree.cpp new file mode 100644 index 000000000..d161f37f7 --- /dev/null +++ b/Code/BF2/External/BFMeme/Tree.cpp @@ -0,0 +1,246 @@ +// dice::meme::Tree and TreeNode, BF2.exe 0x83C8C0..0x83D0F0 (see Tree.h for the layout). +// +// The whole-tree passes are free functions in the image (fastcall: System in ECX, the tree in EDX). +// Each link direction has its own walker so a sibling chain only continues the way it came: +// delete 0x83C900 one walker, unlinks each sibling before descending into it +// properties 0x83CF00 / 0x83CAE0 / 0x83CF80 (from a node / along next / along previous) +// save 0x83CC70 / 0x83C9B0 / 0x83CD10 +// load 0x83CDA0 / 0x83CA40 / 0x83CE60 +// Save and load mark each link with streamBool(present, "Bool"); load creates the node through the +// tree's +0x44 and lets it read itself through +0x34, save lets it write itself through +0x38. +#include "Tree.h" +#if !DEDICATED +#include "Stream.h" +#include "TypeDescriptor.h" +#include +#include +namespace dice { namespace meme { +namespace { + +const char kPresentName[] = "Bool"; // ds:0x94F4D0 + +char* cloneTreeName(const char* name) // 0x737DC0 +{ + if (!name) return nullptr; + const unsigned int bytes = static_cast(std::strlen(name)) + 1; + char* result = static_cast(::operator new(bytes)); + std::memcpy(result, name, bytes); + return result; +} + +// 0x83C900. Streams the node through +0x2C, then its child, previous and next (each sibling unlinked +// from this node first), then deletes it. +bool destroyNodes(System* system, Tree* tree, Stream* stream, TreeNode*& slot) +{ + TreeNode* node = slot; + if (!node) return true; + if (!node->visit0x2c(system, stream)) return false; + if (!destroyNodes(system, tree, stream, node->m_child)) return false; + if (node->m_previous) { + node->m_previous->m_next = nullptr; + if (!destroyNodes(system, tree, stream, node->m_previous)) return false; + } + if (node->m_next) { + node->m_next->m_previous = nullptr; + if (!destroyNodes(system, tree, stream, node->m_next)) return false; + } + delete slot; + slot = nullptr; + return true; +} + +bool streamNextProperties(System*, Tree*, Stream*, TreeNode*&); +bool streamPreviousProperties(System*, Tree*, Stream*, TreeNode*&); + +bool streamNodeProperties(System* system, Tree* tree, Stream* stream, TreeNode*& slot) // 0x83CF00 +{ + TreeNode* node = slot; + if (!node) return true; + if (!node->streamProperties(system, stream)) return false; + if (!streamNodeProperties(system, tree, stream, slot->m_child)) return false; + if (!streamNextProperties(system, tree, stream, slot->m_next)) return false; + return streamPreviousProperties(system, tree, stream, slot->m_previous); +} + +bool streamNextProperties(System* system, Tree* tree, Stream* stream, TreeNode*& slot) // 0x83CAE0 +{ + TreeNode* node = slot; + if (!node) return true; + if (!node->streamProperties(system, stream)) return false; + if (!streamNodeProperties(system, tree, stream, slot->m_child)) return false; + return streamNextProperties(system, tree, stream, slot->m_next); +} + +bool streamPreviousProperties(System* system, Tree* tree, Stream* stream, TreeNode*& slot) // 0x83CF80 +{ + TreeNode* node = slot; + if (!node) return true; + if (!node->streamProperties(system, stream)) return false; + if (!streamNodeProperties(system, tree, stream, slot->m_child)) return false; + return streamPreviousProperties(system, tree, stream, slot->m_previous); +} + +bool saveNext(System*, Tree*, Stream*, TreeNode*); +bool savePrevious(System*, Tree*, Stream*, TreeNode*); + +bool saveNode(System* system, Tree* tree, Stream* stream, TreeNode* node) // 0x83CC70 +{ + bool present = node != nullptr; + if (!stream->streamBool(&present, kPresentName)) return false; + if (!present) return true; + if (!node->visit0x38(system, stream)) return false; + if (!saveNode(system, tree, stream, node->m_child)) return false; + if (!saveNext(system, tree, stream, node->m_next)) return false; + return savePrevious(system, tree, stream, node->m_previous); +} + +bool saveNext(System* system, Tree* tree, Stream* stream, TreeNode* node) // 0x83C9B0 +{ + bool present = node != nullptr; + if (!stream->streamBool(&present, kPresentName)) return false; + if (!present) return true; + if (!node->visit0x38(system, stream)) return false; + if (!saveNode(system, tree, stream, node->m_child)) return false; + return saveNext(system, tree, stream, node->m_next); +} + +bool savePrevious(System* system, Tree* tree, Stream* stream, TreeNode* node) // 0x83CD10 +{ + bool present = node != nullptr; + if (!stream->streamBool(&present, kPresentName)) return false; + if (!present) return true; + if (!node->visit0x38(system, stream)) return false; + if (!saveNode(system, tree, stream, node->m_child)) return false; + return savePrevious(system, tree, stream, node->m_previous); +} + +bool loadNext(System*, Tree*, Stream*, TreeNode*&, TreeNode*); +bool loadPrevious(System*, Tree*, Stream*, TreeNode*&, TreeNode*); + +// [CHOSEN, not recovered] The load walkers' present flag is not initialized in the image (it reuses a +// byte of the stream argument's slot), so a stream that leaves it untouched decides on garbage; it +// starts false here. + +// 0x83CDA0: a child of `parent` (null for the root). +bool loadNode(System* system, Tree* tree, Stream* stream, TreeNode*& slot, TreeNode* parent) +{ + slot = nullptr; + bool present = false; + if (!stream->streamBool(&present, kPresentName)) return false; + if (!present) return true; + slot = tree->createNode(system, parent, nullptr, nullptr, nullptr); + if (!slot->visit0x34(system, stream)) return false; + if (!loadNode(system, tree, stream, slot->m_child, slot)) return false; + if (!loadNext(system, tree, stream, slot->m_next, slot)) return false; + return loadPrevious(system, tree, stream, slot->m_previous, slot); +} + +// 0x83CA40: the next sibling of `previous`. +bool loadNext(System* system, Tree* tree, Stream* stream, TreeNode*& slot, TreeNode* previous) +{ + slot = nullptr; + bool present = false; + if (!stream->streamBool(&present, kPresentName)) return false; + if (!present) return true; + slot = tree->createNode(system, previous->m_parent, nullptr, previous, nullptr); + if (!slot->visit0x34(system, stream)) return false; + if (!loadNode(system, tree, stream, slot->m_child, slot)) return false; + return loadNext(system, tree, stream, slot->m_next, slot); +} + +// 0x83CE60: the previous sibling of `next`. +bool loadPrevious(System* system, Tree* tree, Stream* stream, TreeNode*& slot, TreeNode* next) +{ + slot = nullptr; + bool present = false; + if (!stream->streamBool(&present, kPresentName)) return false; + if (!present) return true; + slot = tree->createNode(system, next->m_parent, next, nullptr, nullptr); + if (!slot->visit0x34(system, stream)) return false; + if (!loadNode(system, tree, stream, slot->m_child, slot)) return false; + return loadPrevious(system, tree, stream, slot->m_previous, slot); +} + +} // namespace + +// ---- TreeNode ---- + +TreeNode::TreeNode(TreeNode* parent, TreeNode* next, TreeNode* previous, TreeNode* child) + : m_previous(previous), m_next(next), m_child(child), m_parent(parent) +{ +} +TreeNode::~TreeNode() {} +bool TreeNode::visit0x2c(System* system, Stream* stream) { return streamProperties(system, stream); } +bool TreeNode::visit0x34(System* system, Stream* stream) { return streamProperties(system, stream); } +bool TreeNode::visit0x38(System* system, Stream* stream) { return streamProperties(system, stream); } + +// ---- Tree ---- + +Tree::Tree() : m_root(nullptr), m_name(nullptr) {} +Tree::~Tree() { ::operator delete(m_name); m_name = nullptr; } // the nodes are not freed here +// 0x83D010: published on first use; the only caller is Stream::streamTree's null-type branch (0x837F80). +TypeDescriptor* Tree::getClassType() +{ + static ClassTypeDescriptor type("dice::meme::Tree"); + return &type; +} +TypeDescriptor* Tree::getType() { return getClassType(); } +unsigned int Tree::getObjectSize() { return sizeof(Tree); } +const char* Tree::getName() { return m_name; } +bool Tree::setName(const char* name) +{ + ::operator delete(m_name); + m_name = nullptr; + m_name = cloneTreeName(name); // freed before the copy, as shipped: self-aliasing is unsafe + return true; +} +bool Tree::slot_0x20() { return true; } + +bool Tree::visit0x2c(System* system, Stream* stream) +{ + if (!Object::visit0x2c(system, stream)) return false; // 0x82AC70: this->streamProperties + return destroyNodes(system, this, stream, m_root); +} + +bool Tree::streamProperties(System* system, Stream* stream) +{ + if (!Object::streamProperties(system, stream)) return false; // 0x4553F0: true + return streamNodeProperties(system, this, stream, m_root); +} + +bool Tree::visit0x34(System* system, Stream* stream) +{ + return loadNode(system, this, stream, m_root, nullptr); +} + +bool Tree::visit0x38(System* system, Stream* stream) +{ + return saveNode(system, this, stream, m_root); +} + +TreeNode* Tree::slot_0x40(System*, void*, bool* found, void*) +{ + *found = false; + return nullptr; +} + +TreeNode* Tree::createNode(System*, TreeNode* parent, TreeNode* next, TreeNode* previous, TreeNode* child) +{ + void* allocation = ::operator new(sizeof(TreeNode)); // 0x737D60(0x14) + return allocation ? new(allocation) TreeNode(parent, next, previous, child) : nullptr; +} + +void Tree::deleteNode(System*, TreeNode*& node) +{ + if (node) + delete node; + node = nullptr; +} + +#if defined(_M_IX86) +static_assert(sizeof(Tree) == 12, "BFMeme Tree layout"); +static_assert(sizeof(TreeNode) == 0x14, "BFMeme TreeNode layout"); +#endif + +} } +#endif diff --git a/Code/BF2/External/BFMeme/Tree.h b/Code/BF2/External/BFMeme/Tree.h new file mode 100644 index 000000000..8f9ab918c --- /dev/null +++ b/Code/BF2/External/BFMeme/Tree.h @@ -0,0 +1,62 @@ +// dice::meme::Tree and its node, BF2.exe 0x83C8C0..0x83D0F0: Tree table 0x94F440 (19 slots, descriptor +// 0x94F4D8 "dice::meme::Tree", base Object, factory 0x83CFF0), TreeNode table 0x94F490. Path and the +// node class name are [INFERRED]; the node is not registered (its type slot is Object's). +// +// A tree is a root node plus a name. Nodes are linked as a doubly linked sibling list (+4 previous, +// +8 next) with a first-child link (+0xC) and a parent link (+0x10). Every whole-tree pass walks +// child, then next, then previous from the root, and each sibling direction only continues in its +// own direction. +#ifndef BFMEME_TREE_H +#define BFMEME_TREE_H +#include "Object.h" +#if !DEDICATED +namespace dice { namespace meme { + +class TreeNode : public Object +{ +public: + TreeNode(TreeNode* parent, TreeNode* next, TreeNode* previous, TreeNode* child); + ~TreeNode() override; // 0x83CC40 + // 0x83C8F0, shared by the three visit slots: a tail call to streamProperties. + bool visit0x2c(System*, Stream*) override; + bool visit0x34(System*, Stream*) override; + bool visit0x38(System*, Stream*) override; + + TreeNode* m_previous; // +0x04 + TreeNode* m_next; // +0x08 + TreeNode* m_child; // +0x0C + TreeNode* m_parent; // +0x10 +}; + +class Tree : public Object +{ +public: + Tree(); // factory 0x83CFF0: both fields zero + ~Tree() override; // 0x83CB80: frees the name only + TypeDescriptor* getType() override; // 0x83D010 + unsigned int getObjectSize() override; // 0x834800 (12) + const char* getName() override; // 0x68E7B0 + bool setName(const char*) override; // 0x8375C0 + bool slot_0x20() override; // 0x5A5E20: true + bool visit0x2c(System*, Stream*) override; // 0x83CBC0: stream, then destroy every node + bool streamProperties(System*, Stream*) override; // 0x83D050: every node's properties + bool visit0x34(System*, Stream*) override; // 0x83D090: load the node structure + bool visit0x38(System*, Stream*) override; // 0x83D0B0: save the node structure + + // +0x40, 0x83C8C0: clears the flag and answers null. [UNRESOLVED] name and parameters. + virtual TreeNode* slot_0x40(System*, void*, bool* found, void*); + // +0x44, 0x83CC00: a 0x14-byte node with its links set; the System is unused. + virtual TreeNode* createNode(System*, TreeNode* parent, TreeNode* next, TreeNode* previous, + TreeNode* child); + // +0x48, 0x83C8D0: deletes the node (if any) and clears the pointer. + virtual void deleteNode(System*, TreeNode*& node); + + static TypeDescriptor* getClassType(); + + TreeNode* m_root; // +0x04 + char* m_name; // +0x08, owned copy +}; + +} } +#endif +#endif diff --git a/Code/BF2/External/BFMeme/TypeDescriptor.cpp b/Code/BF2/External/BFMeme/TypeDescriptor.cpp index d44a33f7c..359d34f8b 100644 --- a/Code/BF2/External/BFMeme/TypeDescriptor.cpp +++ b/Code/BF2/External/BFMeme/TypeDescriptor.cpp @@ -61,6 +61,8 @@ bool TypeDescriptor::isDerivedFrom(TypeDescriptor* base) } return true; } +#if defined(_M_IX86) static_assert(sizeof(TypeDescriptor) == 16, "BFMeme descriptor layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/VariableColorEffect.cpp b/Code/BF2/External/BFMeme/VariableColorEffect.cpp index 4ac35d466..cb10cfbca 100644 --- a/Code/BF2/External/BFMeme/VariableColorEffect.cpp +++ b/Code/BF2/External/BFMeme/VariableColorEffect.cpp @@ -34,7 +34,7 @@ bool VariableColorEffect::streamProperties(System* system, Stream* stream) && stream->streamData(system, m_alpha, "Alpha", nullptr); } -bool VariableColorEffect::drawCharacter(System* system, int character, int font, +bool VariableColorEffect::drawCharacter(System* system, int character, FontHandle font, int elementIndex, Quad* quad, RenderContext* context) { // read each current field only after the preceding callback. Each @@ -48,7 +48,7 @@ bool VariableColorEffect::drawCharacter(System* system, int character, int font, return Effect::drawCharacter(system, character, font, elementIndex, quad, context); } -bool VariableColorEffect::drawTexture(System* system, int texture, Quad* quad, +bool VariableColorEffect::drawTexture(System* system, TextureHandle texture, Quad* quad, RenderContext* context) { // 7CAC40 has the same ordered sampling, including independent null defaults. @@ -61,7 +61,9 @@ bool VariableColorEffect::drawTexture(System* system, int texture, Quad* quad, return Effect::drawTexture(system, texture, quad, context); } +#if defined(_M_IX86) static_assert(sizeof(ClassTypeDescriptor) == 16, "VariableColorEffect metadata storage"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/VariableColorEffect.h b/Code/BF2/External/BFMeme/VariableColorEffect.h index 3bb8f02ec..7402601b3 100644 --- a/Code/BF2/External/BFMeme/VariableColorEffect.h +++ b/Code/BF2/External/BFMeme/VariableColorEffect.h @@ -14,9 +14,9 @@ class VariableColorEffect : public Effect TypeDescriptor* getType() override; unsigned int getObjectSize() override; bool streamProperties(System*, Stream*) override; - bool drawCharacter(System*, int character, int font, int elementIndex, + bool drawCharacter(System*, int character, FontHandle font, int elementIndex, Quad*, RenderContext*) override; - bool drawTexture(System*, int texture, Quad*, RenderContext*) override; + bool drawTexture(System*, TextureHandle texture, Quad*, RenderContext*) override; static TypeDescriptor* getClassType(); protected: Data* m_red; // +04, all borrowed @@ -24,7 +24,9 @@ class VariableColorEffect : public Effect Data* m_blue; // +0C Data* m_alpha; // +10 }; +#if defined(_M_IX86) static_assert(sizeof(VariableColorEffect) == 20, "client VariableColorEffect"); +#endif } } #endif #endif diff --git a/Code/BF2/External/GameSpy/LOCAL_CHANGES.md b/Code/BF2/External/GameSpy/LOCAL_CHANGES.md index 858a2f74f..9332a6283 100644 --- a/Code/BF2/External/GameSpy/LOCAL_CHANGES.md +++ b/Code/BF2/External/GameSpy/LOCAL_CHANGES.md @@ -8,7 +8,30 @@ keep integration changes identifiable in the source. | --- | --- | --- | | `serverbrowsing/sb_serverbrowsing.c`: `ServerBrowserAuxUpdateIP` | Check for an existing server address before starting and appending a new server. | Avoid rejecting the newly appended server as its own duplicate before the synchronous wait. | | `qr2/qr2.c`: `qr2_init_socketA` | Initialize `denyresp2_ip_callback` to `NULL` with the other callbacks. | The enabled query-parser hook must not call an uninitialized function pointer. | +| `common/gsPlatformSocket.h`: `_MACOSX` socket-call macros | Apply the `socklen_t` casting macros to C translation units only. | Macro definitions such as `connect(s,a,al)` rewrite C++ member functions of the same name in engine sources that include the SDK; the engine already passes `socklen_t`. Affects only the macOS port. | +| `common/gsAvailable.c`: `GSIStartAvailableCheckA`, `GSIAvailableCheckThink` | `[CHOSEN, not recovered]` Once a check has ended without an answer (the host name did not resolve, or both tries timed out), later checks in the same process end at once with the same result, `GSIACAvailable`. | The game repeats the check before every use of a service: eight server lists at client start-up, each login, each server start. A host that resolves but does not answer costs two 2-second tries per check, 32 seconds at client start-up. | +| `gp/gpiConnect.c`: `gpiStartConnect`; `gp/gpiSearch.c`: `gpiStartProfileSearch` | `[CHOSEN, not recovered]` The two host-lookup error texts read "manager" instead of "mananger". | `ProfileManager::reportError` maps the texts of the SDK revision Battlefield 2 shipped with ("Could not resolve connection manager host name.", "Could not resolve search manager host name.") to the localised connection-failed message. | +| `serverbrowsing/sb_serverlist.c`: `ServerListConnect` | `[CHOSEN, not recovered]` The master-list connect is non-blocking with a 5-second limit (`SB_CONNECT_TIMEOUT`), then blocking again as before; a timeout returns `sbe_connecterror`. | The SDK's blocking `connect` waits for the operating system's TCP timeout (75 s on macOS, about 21 s on Windows) when the name resolves to an address that never answers, with the menu frozen. | +| `gp/gpi.h`, `gp/gpiConnect.c`: `gpiStartConnect`, `gpiCheckConnect`; `gp/gpiSearch.c`: `gpiProcessSearch` | `[CHOSEN, not recovered]` A connection-manager or search-manager connect that has not completed after 5 seconds (`GPI_CONNECT_TIMEOUT`) fails: login with `GP_LOGIN_CONNECTION_FAILED` ("The server has not answered the connection."), search with `GP_SEARCH_TIMED_OUT`. | Same as above; Battlefield 2 runs these operations blocking. | +| `ghttp/ghttpConnection.h`, `ghttp/ghttpProcess.c`: `ghiDoConnecting` | `[CHOSEN, not recovered]` A connect that has not completed after 5 seconds (`GHI_CONNECT_TIMEOUT`) ends the request with `GHTTPConnectFailed`. | Same as above; most stats requests are blocking. | Both client and dedicated-server integrations can use these shared SDK files. +S2.10 adds these POSIX-only changes, all [CHOSEN, not recovered]: + +- `common/{linux,macosx}/gsThread*.c`: sequentially consistent atomic increment/decrement, + returning the new value. The SDK previously asserted and returned 1. +- `common/gsCore.c`: sequentially consistent atomic loads/stores for initialization/shutdown + flags and the reference-count read; the C record layout and task-list critical section stay intact. +- `natneg/natneg.c`, `NNProcessData`: reject input shorter than the base header before reading + its magic/type. Packed payloads already copy with `memcpy`. + +The service domain is the SDK's own `GSI_DOMAIN_NAME` (`gamespy.com`). The game replaces it at +run time without a source change: `Game/MatchMaking/OnlineProviderGameSpy.cpp` writes the service +names into the SDK's host-name variables (`GSIACHostname`, `qr2_hostname`, `gcd_hostname`, +`StatsServerHostname`, `GPConnectionManagerHostname`, `GPSearchManagerHostname`, +`SBOverrideMasterServer`, `Matchup1Hostname` to `Matchup3Hostname`). A new SDK revision must keep +these variables, the name formats `OnlineProvider.cpp` mirrors, and the master-server index hash +of `sb_serverlist.c`. + Changing the SDK revision requires checking the interfaces and behavior used by those integrations. diff --git a/Code/BF2/External/GameSpy/common/gsAvailable.c b/Code/BF2/External/GameSpy/common/gsAvailable.c index 00d5a526d..8f3aaf72c 100644 --- a/Code/BF2/External/GameSpy/common/gsAvailable.c +++ b/Code/BF2/External/GameSpy/common/gsAvailable.c @@ -27,6 +27,11 @@ static struct int retryCount; } AC; +// [CHOSEN, not recovered] OpenBF2 local change (LOCAL_CHANGES.md): set once a check has ended +// without an answer, because the host name did not resolve or every try timed out. Later checks +// then end at once with the same result instead of repeating the lookup and the wait. +static int ACUnanswered = 0; + static int get_sockaddrin(const char * hostname, int port, SOCKADDR_IN * saddr) { GS_ASSERT(hostname) @@ -68,6 +73,10 @@ void GSIStartAvailableCheckA(const char * gamename) // clear the sock AC.sock = INVALID_SOCKET; + // [CHOSEN, not recovered] OpenBF2 local change: see ACUnanswered + if(ACUnanswered) + return; + // startup sockets SocketStartUp(); @@ -79,7 +88,10 @@ void GSIStartAvailableCheckA(const char * gamename) // get the master address rcode = get_sockaddrin(override?GSIACHostname:hostname, MASTER_PORT, &AC.address); if(!rcode) + { + ACUnanswered = 1; // [CHOSEN, not recovered] OpenBF2 local change return; + } // create the socket AC.sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); @@ -192,6 +204,7 @@ GSIACResult GSIAvailableCheckThink(void) { // default to available closesocket(AC.sock); + ACUnanswered = 1; // [CHOSEN, not recovered] OpenBF2 local change __GSIACResult = GSIACAvailable; return __GSIACResult; } diff --git a/Code/BF2/External/GameSpy/common/gsCore.c b/Code/BF2/External/GameSpy/common/gsCore.c index d23f8f196..777f77562 100644 --- a/Code/BF2/External/GameSpy/common/gsCore.c +++ b/Code/BF2/External/GameSpy/common/gsCore.c @@ -9,6 +9,13 @@ #include "gsAssert.h" #include "../ghttp/ghttp.h" +/* [CHOSEN, not recovered] C SDK publication flags on POSIX use the same sequentially + consistent operations as its Interlocked reference count. Keep the SDK's scalar layout. */ +#if defined(_MACOSX) || defined(_LINUX) +#define GSI_CORE_LOAD(word) __atomic_load_n(&(word), __ATOMIC_SEQ_CST) +#define GSI_CORE_STORE(word, value) __atomic_store_n(&(word), (value), __ATOMIC_SEQ_CST) +#endif + @@ -51,14 +58,22 @@ void gsCoreInitialize() GSCoreMgr* aCore = gsiGetStaticCore(); // Is someone else shutting down the core? +#if defined(_MACOSX) || defined(_LINUX) + while(gsi_is_true(GSI_CORE_LOAD(aCore->mIsShuttingDown))) +#else while(gsi_is_true(aCore->mIsShuttingDown)) +#endif msleep(GSI_CORE_INIT_YIELD_MS); // yield to other thread // If we're the first reference, initialize the core if (gsiInterlockedIncrement(&aCore->mRefCount) == 1) { // Are we the first ever? +#if defined(_MACOSX) || defined(_LINUX) + if (gsi_is_false(GSI_CORE_LOAD(aCore->mIsStaticInitComplete))) +#else if (gsi_is_false(aCore->mIsStaticInitComplete)) +#endif { // perform one-time initialization of core critical section gsiInitializeCriticalSection(&aCore->mQueueCrit); @@ -69,7 +84,11 @@ void gsCoreInitialize() #endif // one time init completed +#if defined(_MACOSX) || defined(_LINUX) + GSI_CORE_STORE(aCore->mIsStaticInitComplete, gsi_true); +#else aCore->mIsStaticInitComplete = gsi_true; +#endif } // take the critical section to begin initialization @@ -79,7 +98,11 @@ void gsCoreInitialize() // wait here if another thread is concurrently shutting down the core // we may need to wait a few times if the shutdown does not complete immediately +#if defined(_MACOSX) || defined(_LINUX) + while(gsi_is_true(GSI_CORE_LOAD(aCore->mIsShuttingDown))) +#else while(gsi_is_true(aCore->mIsShuttingDown)) +#endif msleep(GSI_CORE_INIT_YIELD_MS); // Setup the task array @@ -95,14 +118,22 @@ void gsCoreInitialize() // release other threads that may have blocked during init // - this must be the last thing done at end of init +#if defined(_MACOSX) || defined(_LINUX) + GSI_CORE_STORE(aCore->mIsInitialized, gsi_true); +#else aCore->mIsInitialized = gsi_true; +#endif } else { // Core is already initialized -OR- another thread will initialize the core // make sure critical section has been initialized +#if defined(_MACOSX) || defined(_LINUX) + while(gsi_is_false(GSI_CORE_LOAD(aCore->mIsStaticInitComplete))) +#else while(gsi_is_false(aCore->mIsStaticInitComplete)) +#endif msleep(GSI_CORE_INIT_YIELD_MS); // take the critical section @@ -111,7 +142,11 @@ void gsCoreInitialize() gsiLeaveCriticalSection(&aCore->mQueueCrit); // wait for other thread to initial core +#if defined(_MACOSX) || defined(_LINUX) + while(gsi_is_false(GSI_CORE_LOAD(aCore->mIsInitialized))) +#else while(gsi_is_false(aCore->mIsInitialized)) +#endif msleep(GSI_CORE_INIT_YIELD_MS); } } @@ -231,7 +266,11 @@ void gsCoreThink(gsi_time theMS) gsi_time aStartTime = 0; gsi_i32 allTasksAreDead = 1; +#if defined(_MACOSX) || defined(_LINUX) + if (gsi_is_false(GSI_CORE_LOAD(aCore->mIsInitialized))) +#else if (gsi_is_false(aCore->mIsInitialized)) +#endif return; // enter queue critical section @@ -273,7 +312,11 @@ void gsCoreThink(gsi_time theMS) #endif // shutting down? +#if defined(_MACOSX) || defined(_LINUX) + if (GSI_CORE_LOAD(aCore->mIsShuttingDown) && allTasksAreDead) +#else if (aCore->mIsShuttingDown && allTasksAreDead) +#endif { ghttpCleanup(); @@ -285,7 +328,11 @@ void gsCoreThink(gsi_time theMS) } #endif +#if defined(_MACOSX) || defined(_LINUX) + GSI_CORE_STORE(aCore->mIsShuttingDown, 0); +#else aCore->mIsShuttingDown = 0; +#endif } // leave queue critical section @@ -303,7 +350,11 @@ void gsCoreShutdown() int i=0; // If not initialized, just bail +#if defined(_MACOSX) || defined(_LINUX) + if (gsi_is_false(GSI_CORE_LOAD(aCore->mIsInitialized))) +#else if (gsi_is_false(aCore->mIsInitialized)) +#endif return; // Take the critical section to prevent anyone from re-initializing while @@ -321,7 +372,11 @@ void gsCoreShutdown() // we released the final reference, begin shutdown // no other thread will begin using the core until // mIsShuttingDown has been set back to false +#if defined(_MACOSX) || defined(_LINUX) + GSI_CORE_STORE(aCore->mIsShuttingDown, gsi_true); +#else aCore->mIsShuttingDown = gsi_true; +#endif // Cancel all tasks #ifdef GSICORE_DYNAMIC_TASK_LIST @@ -352,9 +407,17 @@ GSCoreValue gsCoreIsShutdown() { GSCoreMgr* aCore = gsiGetStaticCore(); +#if defined(_MACOSX) || defined(_LINUX) + if (gsi_is_true(GSI_CORE_LOAD(aCore->mIsShuttingDown))) +#else if (gsi_is_true(aCore->mIsShuttingDown)) +#endif return GSCore_SHUTDOWN_PENDING; +#if defined(_MACOSX) || defined(_LINUX) + if (GSI_CORE_LOAD(aCore->mRefCount) == 0) +#else if (aCore->mRefCount == 0) +#endif return GSCore_SHUTDOWN_COMPLETE; // The core isn't shutting down, and ref count > 0, diff --git a/Code/BF2/External/GameSpy/common/gsPlatform.h b/Code/BF2/External/GameSpy/common/gsPlatform.h index 70f866dde..a4daf16eb 100644 --- a/Code/BF2/External/GameSpy/common/gsPlatform.h +++ b/Code/BF2/External/GameSpy/common/gsPlatform.h @@ -268,7 +268,7 @@ #endif #if !defined(GSI_DOMAIN_NAME) - #define GSI_DOMAIN_NAME "openspy.net" // official is gamespy.com + #define GSI_DOMAIN_NAME "gamespy.com" #endif diff --git a/Code/BF2/External/GameSpy/common/gsPlatformSocket.h b/Code/BF2/External/GameSpy/common/gsPlatformSocket.h index ab7f2e079..bb2c5b6d8 100644 --- a/Code/BF2/External/GameSpy/common/gsPlatformSocket.h +++ b/Code/BF2/External/GameSpy/common/gsPlatformSocket.h @@ -588,7 +588,9 @@ int gsiShutdown(SOCKET s, int how); #define EWOULDBLOCK sceNET_EWOULDBLOCK #endif -#if defined(_MACOSX) +// [CHOSEN, not recovered] OpenBF2 macOS port: C only. In C++ these function-like macros rename +// every member called connect/bind/accept (StatsManager::connect); the engine passes socklen_t. +#if defined(_MACOSX) && !defined(__cplusplus) #define accept(s,a,al) accept(s,a,(socklen_t*)(al)) #define bind(s,a,al) bind(s,a,(socklen_t)(al)) #define connect(s,a,al) connect(s,a,(socklen_t)(al)) diff --git a/Code/BF2/External/GameSpy/common/linux/gsThreadLinux.c b/Code/BF2/External/GameSpy/common/linux/gsThreadLinux.c index a06181697..d5656dcf8 100644 --- a/Code/BF2/External/GameSpy/common/linux/gsThreadLinux.c +++ b/Code/BF2/External/GameSpy/common/linux/gsThreadLinux.c @@ -22,14 +22,13 @@ gsi_u32 gsiInterlockedIncrement(gsi_u32 * value) { - GS_ASSERT_STR(gsi_false, "gsiInterlockIncrement is unsupported for LINUX in the current version of the SDK\n"); - return 1; + /* [CHOSEN, not recovered] POSIX atomic increment returns the new value, as Win32 does. */ + return __atomic_add_fetch(value, 1, __ATOMIC_SEQ_CST); } gsi_u32 gsiInterlockedDecrement(gsi_u32 * value) { - GS_ASSERT_STR(gsi_false, "gsiInterlockIncrement is unsupported for LINUX in the current version of the SDK\n"); - return 1; + return __atomic_sub_fetch(value, 1, __ATOMIC_SEQ_CST); } /////////////////////////////////////////////////////////////////////////////// diff --git a/Code/BF2/External/GameSpy/common/macosx/gsThreadMacOSX.c b/Code/BF2/External/GameSpy/common/macosx/gsThreadMacOSX.c index e0522a5b6..06e4b54e7 100644 --- a/Code/BF2/External/GameSpy/common/macosx/gsThreadMacOSX.c +++ b/Code/BF2/External/GameSpy/common/macosx/gsThreadMacOSX.c @@ -23,14 +23,13 @@ gsi_u32 gsiInterlockedIncrement(gsi_u32 * value) { - GS_ASSERT_STR(gsi_false, "gsiInterlockIncrement is unsupported for Mac OSX in the current version of the SDK\n"); - return 1; + /* [CHOSEN, not recovered] POSIX atomic increment returns the new value, as Win32 does. */ + return __atomic_add_fetch(value, 1, __ATOMIC_SEQ_CST); } gsi_u32 gsiInterlockedDecrement(gsi_u32 * value) { - GS_ASSERT_STR(gsi_false, "gsiInterlockIncrement is unsupported for Mac OSX in the current version of the SDK\n"); - return 1; + return __atomic_sub_fetch(value, 1, __ATOMIC_SEQ_CST); } /////////////////////////////////////////////////////////////////////////////// diff --git a/Code/BF2/External/GameSpy/ghttp/ghttpConnection.h b/Code/BF2/External/GameSpy/ghttp/ghttpConnection.h index b80b3bbfc..6c11ec35a 100644 --- a/Code/BF2/External/GameSpy/ghttp/ghttpConnection.h +++ b/Code/BF2/External/GameSpy/ghttp/ghttpConnection.h @@ -153,6 +153,7 @@ typedef struct GHIConnection GHIPostingState postingState; // If posting, the state of the upload. gsi_time maxRecvTime; // Max time spent receiving per call to "Think" - Prevents blocking on ultrafast connections + gsi_time connectStartTime; // [CHOSEN, not recovered] OpenBF2 local change, see GHI_CONNECT_TIMEOUT char * proxyOverrideServer; // Allows use of a different proxy than the global proxy unsigned short proxyOverridePort; diff --git a/Code/BF2/External/GameSpy/ghttp/ghttpProcess.c b/Code/BF2/External/GameSpy/ghttp/ghttpProcess.c index 2be268a36..e8d8add78 100644 --- a/Code/BF2/External/GameSpy/ghttp/ghttpProcess.c +++ b/Code/BF2/External/GameSpy/ghttp/ghttpProcess.c @@ -330,6 +330,12 @@ void ghiDoLookupPending /*************** ** CONNECTING ** ***************/ +// [CHOSEN, not recovered] OpenBF2 local change (LOCAL_CHANGES.md): a connect gives up after this +// many milliseconds with GHTTPConnectFailed. The SDK waits for the operating system's TCP timeout +// (75 s on macOS, about 21 s on Windows) when a host name resolves to an address that never +// answers; BF2 sends most of its stats requests blocking, so the menu is frozen meanwhile. +#define GHI_CONNECT_TIMEOUT 5000 + void ghiDoConnecting ( GHIConnection * connection @@ -398,6 +404,7 @@ void ghiDoConnecting return; } } + connection->connectStartTime = current_time(); // [CHOSEN, not recovered] GHI_CONNECT_TIMEOUT } // Check if the connect has completed. @@ -426,6 +433,16 @@ void ghiDoConnecting connection->state = GHTTPSecuringSession; ghiCallProgressCallback(connection, NULL, 0); } + // [CHOSEN, not recovered] OpenBF2 local change (LOCAL_CHANGES.md): see GHI_CONNECT_TIMEOUT. A + // socket handed in by ghttpSetRequestSocket starts its clock here. + else if(connection->connectStartTime == 0) + connection->connectStartTime = current_time(); + else if((current_time() - connection->connectStartTime) > GHI_CONNECT_TIMEOUT) + { + connection->completed = GHTTPTrue; + connection->result = GHTTPConnectFailed; + connection->socketError = WSAETIMEDOUT; + } } /****************** diff --git a/Code/BF2/External/GameSpy/gp/gpi.h b/Code/BF2/External/GameSpy/gp/gpi.h index 0c23ad39a..4a3c76475 100644 --- a/Code/BF2/External/GameSpy/gp/gpi.h +++ b/Code/BF2/External/GameSpy/gp/gpi.h @@ -143,6 +143,7 @@ typedef struct char loginTicket[GP_LOGIN_TICKET_LEN]; GPEnum quietModeFlags; gsi_time kaTransmit; + gsi_time connectStartTime; // [CHOSEN, not recovered] OpenBF2 local change, see GPI_CONNECT_TIMEOUT #ifdef GSI_UNICODE unsigned short errorString_W[GP_ERROR_STRING_LEN]; @@ -177,6 +178,12 @@ typedef struct } GPIConnection; +// [CHOSEN, not recovered] OpenBF2 local change (LOCAL_CHANGES.md): the connection and search +// managers' TCP connects give up after this many milliseconds. The SDK waits for the operating +// system's TCP timeout (75 s on macOS, about 21 s on Windows) when a host name resolves to an +// address that never answers; BF2 runs these operations blocking, so the menu is frozen meanwhile. +#define GPI_CONNECT_TIMEOUT 5000 + //FUNCTIONS /////////// GPResult diff --git a/Code/BF2/External/GameSpy/gp/gpiConnect.c b/Code/BF2/External/GameSpy/gp/gpiConnect.c index 86fd558bf..0dbf51e29 100644 --- a/Code/BF2/External/GameSpy/gp/gpiConnect.c +++ b/Code/BF2/External/GameSpy/gp/gpiConnect.c @@ -192,7 +192,9 @@ gpiStartConnect( { host = gethostbyname(GPConnectionManagerHostname); if(host == NULL) - CallbackFatalError(connection, GP_NETWORK_ERROR, GP_NETWORK, "Could not resolve connection mananger host name."); + // [CHOSEN, not recovered] OpenBF2 local change (LOCAL_CHANGES.md): "manager", as in the SDK + // revision BF2 shipped with; ProfileManager::reportError compares this text. + CallbackFatalError(connection, GP_NETWORK_ERROR, GP_NETWORK, "Could not resolve connection manager host name."); address.sin_addr.s_addr = *(unsigned int *)host->h_addr_list[0]; //printf("Resolved Hostname and copied address: %s\n", inet_ntoa(address.sin_addr)); } @@ -220,6 +222,7 @@ gpiStartConnect( ///////////////////////////////////////////// operation->state = GPI_CONNECTING; iconnection->connectState = GPI_CONNECTING; + iconnection->connectStartTime = current_time(); // [CHOSEN, not recovered] GPI_CONNECT_TIMEOUT return GP_NO_ERROR; } @@ -831,7 +834,13 @@ gpiCheckConnect( // Check if not finished connecting. //////////////////////////////////// if(state == GPI_NOT_CONNECTED) + { + // [CHOSEN, not recovered] OpenBF2 local change (LOCAL_CHANGES.md): give up after + // GPI_CONNECT_TIMEOUT, reported like a refused connection. + if((current_time() - iconnection->connectStartTime) > GPI_CONNECT_TIMEOUT) + CallbackFatalError(connection, GP_SERVER_ERROR, GP_LOGIN_CONNECTION_FAILED, "The server has not answered the connection."); return GP_NO_ERROR; + } // We're now negotiating the connection. //////////////////////////////////////// diff --git a/Code/BF2/External/GameSpy/gp/gpiSearch.c b/Code/BF2/External/GameSpy/gp/gpiSearch.c index 52b2a1ee9..99e6f380d 100644 --- a/Code/BF2/External/GameSpy/gp/gpiSearch.c +++ b/Code/BF2/External/GameSpy/gp/gpiSearch.c @@ -76,7 +76,9 @@ gpiStartProfileSearch( /////////////////////// host = gethostbyname(GPSearchManagerHostname); if(host == NULL) - CallbackFatalError(connection, GP_NETWORK_ERROR, GP_NETWORK, "Could not resolve search mananger host name."); + // [CHOSEN, not recovered] OpenBF2 local change (LOCAL_CHANGES.md): "manager", as in the SDK + // revision BF2 shipped with; ProfileManager::reportError compares this text. + CallbackFatalError(connection, GP_NETWORK_ERROR, GP_NETWORK, "Could not resolve search manager host name."); // Connect the socket. ////////////////////// @@ -569,6 +571,14 @@ gpiProcessSearch( if(state == GPI_DISCONNECTED) CallbackError(connection, GP_SERVER_ERROR, GP_SEARCH_CONNECTION_FAILED, "Could not connect to the search manager."); + // [CHOSEN, not recovered] OpenBF2 local change (LOCAL_CHANGES.md): give up after + // GPI_CONNECT_TIMEOUT (searchStartTime is set when the connect starts). + if((state == GPI_NOT_CONNECTED) && ((current_time() - data->searchStartTime) > GPI_CONNECT_TIMEOUT)) + { + data->remove = GPITrue; + CallbackError(connection, GP_NETWORK_ERROR, GP_SEARCH_TIMED_OUT, "Could not connect to the search manager."); + } + // Check if finished connecting. //////////////////////////////// if(state == GPI_CONNECTED) diff --git a/Code/BF2/External/GameSpy/natneg/natneg.c b/Code/BF2/External/GameSpy/natneg/natneg.c index 2f778e751..e85ed9d47 100644 --- a/Code/BF2/External/GameSpy/natneg/natneg.c +++ b/Code/BF2/External/GameSpy/natneg/natneg.c @@ -771,6 +771,13 @@ void NNProcessData(char *data, int len, struct sockaddr_in *fromaddr) NATNegotiator neg; unsigned char ptype; +#if defined(_MACOSX) || defined(_LINUX) + /* [CHOSEN, not recovered] Inspect only a complete header before reading its magic/type. + Payloads below already use memcpy into packed local storage, never atomic word access. */ + if (len < BASEPACKET_SIZE) + return; +#endif + if (!CheckMagic(data)) return; //invalid packet diff --git a/Code/BF2/External/GameSpy/serverbrowsing/sb_internal.h b/Code/BF2/External/GameSpy/serverbrowsing/sb_internal.h index 855091b89..c413f9335 100644 --- a/Code/BF2/External/GameSpy/serverbrowsing/sb_internal.h +++ b/Code/BF2/External/GameSpy/serverbrowsing/sb_internal.h @@ -246,6 +246,11 @@ struct _SBServerList SOCKET slsocket; gsi_time lanstarttime; +#if !defined(_WIN32) + // [CHOSEN, not recovered] errno of the first failed broadcast sendto of the last LAN browse + // (0 when every send went out); read through ServerBrowserLANSendError. + int lansenderror; +#endif int fromgamever; GOACryptState cryptkey; int queryoptions; diff --git a/Code/BF2/External/GameSpy/serverbrowsing/sb_serverbrowsing.c b/Code/BF2/External/GameSpy/serverbrowsing/sb_serverbrowsing.c index 9e1a3bf33..647459509 100644 --- a/Code/BF2/External/GameSpy/serverbrowsing/sb_serverbrowsing.c +++ b/Code/BF2/External/GameSpy/serverbrowsing/sb_serverbrowsing.c @@ -240,6 +240,15 @@ SBError ServerBrowserLANUpdate(ServerBrowser sb, SBBool async, unsigned short st return err; } +#if !defined(_WIN32) +// [CHOSEN, not recovered] errno of the first failed broadcast send of the last +// ServerBrowserLANUpdate, 0 when all went out (sb_serverlist.c SBServerListGetLANList). +int ServerBrowserLANSendError(ServerBrowser sb) +{ + return sb->list.lansenderror; +} +#endif + static SBError WaitForTriggerUpdate(ServerBrowser sb, SBBool viaMaster) { SBError err = sbe_noerror; diff --git a/Code/BF2/External/GameSpy/serverbrowsing/sb_serverbrowsing.h b/Code/BF2/External/GameSpy/serverbrowsing/sb_serverbrowsing.h index 81a652027..b743628c3 100644 --- a/Code/BF2/External/GameSpy/serverbrowsing/sb_serverbrowsing.h +++ b/Code/BF2/External/GameSpy/serverbrowsing/sb_serverbrowsing.h @@ -208,6 +208,14 @@ startSearchPort - The initial port to begin searching for servers on endSearchPort - The final port to search. All ports between start and end will be queried. */ SBError ServerBrowserLANUpdate(ServerBrowser sb, SBBool async, unsigned short startSearchPort, unsigned short endSearchPort); +#if !defined(_WIN32) +/* ServerBrowserLANSendError +------------------- +[CHOSEN, not recovered] Not in the SDK. The errno of the first failed broadcast send of the +last ServerBrowserLANUpdate, or 0 when every send went out. */ +int ServerBrowserLANSendError(ServerBrowser sb); +#endif + /* ServerBrowserAuxUpdateIP ------------------- Manually updates a server given an IP address and query port. Use to manually add servers to the list when you just diff --git a/Code/BF2/External/GameSpy/serverbrowsing/sb_serverlist.c b/Code/BF2/External/GameSpy/serverbrowsing/sb_serverlist.c index 40a1465fa..dfef52ba5 100644 --- a/Code/BF2/External/GameSpy/serverbrowsing/sb_serverlist.c +++ b/Code/BF2/External/GameSpy/serverbrowsing/sb_serverlist.c @@ -370,6 +370,9 @@ void SBServerListInit(SBServerList *slist, const char *queryForGamename, const c #endif slist->state = sl_disconnected; +#if !defined(_WIN32) + slist->lansenderror = 0; +#endif SBAllocateServerList(slist); SBRefStrHash(slist); //make sure it's initialized strcpy(slist->queryforgamename, queryForGamename); @@ -440,6 +443,52 @@ static int StringHash(const char *s, int numbuckets) +// [CHOSEN, not recovered] OpenBF2 local change (LOCAL_CHANGES.md): the master-list connect gives +// up after this many milliseconds. The SDK's blocking connect waits for the operating system's TCP +// timeout (75 s on macOS, about 21 s on Windows) when the list server's name resolves to an address +// that never answers, and the game's menu is frozen for that time. +#define SB_CONNECT_TIMEOUT 5000 + +// [CHOSEN, not recovered] OpenBF2 local change: connect with SB_CONNECT_TIMEOUT. Returns 0 when +// connected; the socket is blocking again afterwards, as after the SDK's connect. +static int ServerListConnectWithTimeout(SOCKET sock, struct sockaddr_in *saddr) +{ + fd_set writeSet; + fd_set exceptSet; + struct timeval timeout; + int error = 0; +#if defined(_WIN32) + int errorLen = (int)sizeof(error); +#else + socklen_t errorLen = (socklen_t)sizeof(error); +#endif + int rcode; + + if (!SetSockBlocking(sock, 0)) + return connect(sock, (struct sockaddr *)saddr, sizeof(*saddr)); + rcode = connect(sock, (struct sockaddr *)saddr, sizeof(*saddr)); + if (gsiSocketIsError(rcode)) + { + error = GOAGetLastError(sock); + if (error != WSAEWOULDBLOCK && error != WSAEINPROGRESS) + return -1; + FD_ZERO(&writeSet); + FD_SET(sock, &writeSet); + FD_ZERO(&exceptSet); + FD_SET(sock, &exceptSet); + timeout.tv_sec = SB_CONNECT_TIMEOUT / 1000; + timeout.tv_usec = (SB_CONNECT_TIMEOUT % 1000) * 1000; + rcode = select(FD_SETSIZE, NULL, &writeSet, &exceptSet, &timeout); + if (rcode <= 0 || FD_ISSET(sock, &exceptSet)) + return -1; // timed out, select failed, or (Windows) the connect failed + error = 0; + if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (char *)&error, &errorLen) != 0 || error != 0) + return -1; // (POSIX) the connect failed + } + SetSockBlocking(sock, 1); + return 0; +} + static SBError ServerListConnect(SBServerList *slist) { struct sockaddr_in saddr; @@ -470,7 +519,8 @@ static SBError ServerListConnect(SBServerList *slist) if (slist->slsocket == INVALID_SOCKET) return sbe_socketerror; } - if (connect ( slist->slsocket, (struct sockaddr *) &saddr, sizeof saddr ) != 0) + // [CHOSEN, not recovered] OpenBF2 local change: a bounded connect (SB_CONNECT_TIMEOUT). + if (ServerListConnectWithTimeout(slist->slsocket, &saddr) != 0) { closesocket(slist->slsocket); slist->slsocket = INVALID_SOCKET; @@ -692,6 +742,10 @@ SBError SBServerListGetLANList(SBServerList *slist, unsigned short startport, un unsigned short i; unsigned char qr2_echo_request[] = {QR2_MAGIC_1, QR2_MAGIC_2, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00}; int qr2requestlen = sizeof(qr2_echo_request) / sizeof(qr2_echo_request[0]); +#if !defined(_WIN32) + int sendFailure = 0; + slist->lansenderror = 0; +#endif if (slist->state != sl_disconnected) SBServerListDisconnect(slist); @@ -726,12 +780,34 @@ SBError SBServerListGetLANList(SBServerList *slist, unsigned short startport, un endport = (unsigned short)(startport + 500); for (i = startport ; i <= endport ; i += 1) { +#if !defined(_WIN32) + int sent; +#endif saddr.sin_port = htons(i); +#if !defined(_WIN32) + if (queryversion == QVERSION_QR2) //send a QR2 echo request + sent = (int)sendto(slist->slsocket, (char*)qr2_echo_request,qr2requestlen,0,(struct sockaddr *)&saddr,sizeof(saddr)); + else //send a GOA echo request + sent = (int)sendto(slist->slsocket, "\\echo\\test",10,0,(struct sockaddr *)&saddr,sizeof(saddr)); + // [CHOSEN, not recovered] the browse itself is unchanged (a failed send is not an error). + // A denied macOS Local Network permission (or a firewall) fails the broadcast sendto and + // the LAN list stays silently empty; the first failure is logged once per browse and kept + // in lansenderror, from which the menu's ServerBrowser raises a message. + if (sent < 0 && sendFailure == 0) + sendFailure = errno; +#else if (queryversion == QVERSION_QR2) //send a QR2 echo request sendto(slist->slsocket, (char*)qr2_echo_request,qr2requestlen,0,(struct sockaddr *)&saddr,sizeof(saddr)); else //send a GOA echo request sendto(slist->slsocket, "\\echo\\test",10,0,(struct sockaddr *)&saddr,sizeof(saddr)); +#endif } +#if !defined(_WIN32) + slist->lansenderror = sendFailure; + if (sendFailure != 0) + fprintf(stderr, "LAN server search: sending the broadcast failed (%s); on macOS allow Local Network " + "access for OpenBF2 in System Settings > Privacy & Security > Local Network\n", strerror(sendFailure)); +#endif slist->state = sl_lanbrowse; slist->lanstarttime = current_time(); return sbe_noerror; diff --git a/Code/BF2/External/NovintHFX/NovintHFX.def b/Code/BF2/External/NovintHFX/NovintHFX.def deleted file mode 100644 index 48e6a6a71..000000000 --- a/Code/BF2/External/NovintHFX/NovintHFX.def +++ /dev/null @@ -1,16 +0,0 @@ -; Exact subset of the original BF2.exe import names, exported by stock NovintHFX.dll. -; Import library only: lib /nologo /machine:x86 /def:NovintHFX.def /out:/NovintHFX.lib -LIBRARY NovintHFX.dll -EXPORTS - Haptics DATA - ??0mouse_settings@ApplicationData@NovintHFX@@QAE@XZ - ?AttachApplication@HapticsSystem@NovintHFX@@QAE_NAAUApplicationData@2@@Z - ?RecountConnectedDevices@HapticsSystem@NovintHFX@@QAEXXZ - ?ConnectedDeviceCount@HapticsSystem@NovintHFX@@QBEHXZ - ?RunDevice@HapticsSystem@NovintHFX@@QAE_NPAPAVDevice@2@H@Z - ?StartMouse@HapticsSystem@NovintHFX@@QAEXPAVDevice@2@@Z - ?StopRunningDevice@HapticsSystem@NovintHFX@@QAE_NPAPAVDevice@2@@Z - ?InputUpdate@HapticsSystem@NovintHFX@@QAEHXZ - ?InputUpdate@Device@NovintHFX@@QAEXXZ - ?GetButtonData@Device@NovintHFX@@QBEXPAH00@Z - ?GetToolPosition@Device@NovintHFX@@QBEXQAN@Z diff --git a/Code/BF2/External/NovintHFX/NovintHFX.h b/Code/BF2/External/NovintHFX/NovintHFX.h deleted file mode 100644 index 6c65a7c8c..000000000 --- a/Code/BF2/External/NovintHFX/NovintHFX.h +++ /dev/null @@ -1,45 +0,0 @@ -// [INFERRED] local ABI header; no Novint implementation is reconstructed here. -// Narrow declarations from BF2.exe's NovintHFX imports and its call-site layouts. -// See IO/Input/FALCON_DEVICE_STATUS.md. The matching stock DLL supplies all bodies. -#ifndef EXTERNAL_NOVINTHFX_ABI_H -#define EXTERNAL_NOVINTHFX_ABI_H -#include -namespace NovintHFX { -struct ApplicationData { - struct mouse_settings { - __declspec(dllimport) mouse_settings(); - private: - // Opaque SDK state, 28-byte stack extent at BF2.exe 0x6A4EF0. - // Its own SDK constructor owns every field; no fabricated initialization. - alignas(4) unsigned char m_sdkState[28]; - }; - HWND window; // [INFERRED] name; HWND at byte 0, 0x6A4F23. - mouse_settings mouse; -}; -class Device { -public: - __declspec(dllimport) void InputUpdate(); - __declspec(dllimport) void GetButtonData(int*, int*, int*) const; - __declspec(dllimport) void GetToolPosition(double* const) const; -private: - Device(); // Opaque DLL-owned instance; never allocate from this declaration. -}; -class HapticsSystem { -public: - __declspec(dllimport) bool AttachApplication(ApplicationData&); - __declspec(dllimport) void RecountConnectedDevices(); - __declspec(dllimport) int ConnectedDeviceCount() const; - __declspec(dllimport) bool RunDevice(Device**, int); - __declspec(dllimport) void StartMouse(Device*); - __declspec(dllimport) bool StopRunningDevice(Device**); - __declspec(dllimport) int InputUpdate(); -private: - HapticsSystem(); // Opaque DLL-owned instance; never allocate or copy. -}; -} -// PE IAT 0x87F788: a single IAT load supplies this, i.e. the exported object's -// address. This is neither a pointer variable nor a callable Haptics() function. -extern "C" __declspec(dllimport) NovintHFX::HapticsSystem Haptics; -static_assert(sizeof(NovintHFX::ApplicationData::mouse_settings) == 28, "SDK ABI"); -static_assert(sizeof(NovintHFX::ApplicationData) == 32, "x86 SDK ABI"); -#endif diff --git a/Code/BF2/External/README.md b/Code/BF2/External/README.md index 7ac699a82..c4fbbeb70 100644 --- a/Code/BF2/External/README.md +++ b/Code/BF2/External/README.md @@ -13,9 +13,13 @@ local changes small and documented alongside the affected dependency. | TinyXML | `TinyXML/`; upstream TinyXML source | XML parsing through engine wrappers | | GameSpy SDK | `GameSpy/`; December 2007 SDK, including qr2 3.04.00 | Network service integrations | | gameswf and base | `gameswf/` and `base/`; Thatcher Ulrich's tu-testbed snapshot of 27 February 2006 | SwiffPlayer menu playback | +| Expat 1.95.0 | `expat/`; official `libexpat` tag `R_1_95_0`, unchanged MIT sources ([provenance and hashes](expat/README.md)); [CHOSEN, not recovered] substitute for DICE's modified parser | SwiffPlayer XML | | libogg 1.3.6 and libvorbis 1.3.7 | `libogg-1.3.6/` and `libvorbis-1.3.7/`; Xiph.Org sources | BF2Audio Ogg/Vorbis decoding | +| Speex 1.0.5 | `speex-1.0.5/`; official Xiph.Org release tarball, unmodified, BSD ([COPYING](speex-1.0.5/COPYING), [provenance, retail table match and build notes](speex-1.0.5/LOCAL_CHANGES.md)) | GameSpy Voice2 codec for the VoIP client (`gvSpeex.c`) | | Dear ImGui | `imgui/`; `v1.92.9b-docking`, commit `b48d1af` | Editor UI | | ImGuizmo | `ImGuizmo/`; tag `1.10`, commit `b796ac3` | Editor transform gizmo | +| FFmpeg Bink decoders | `ffmpeg-bink/`; seven unmodified files of FFmpeg 7.1.1 plus an OpenBF2 shim ([README](ffmpeg-bink/README.md)), LGPL-2.1+ | Bink movie playback on macOS and Windows x64 (`RendDX9Abi/BinkFFmpeg.cpp`); Windows x86 uses RAD's `binkw32.dll` | +| meshoptimizer | `meshoptimizer/`; `src/meshoptimizer.h` and `src/stripifier.cpp` of zeux/meshoptimizer tag `v1.3`, unmodified, MIT ([LICENSE](meshoptimizer/LICENSE.md)) | macOS D3DX subset: `D3DXConvertMeshSubsetToSingleStrip` (`Platform/Gfx/Metal/D3DXMesh.cpp`) | The table describes the vendored inputs, not a promise that every SDK module is part of each executable. Build manifests select the files for each image. @@ -24,7 +28,10 @@ covered by the claim that an upstream library is unmodified. The individual sources and license files govern their respective components. Keep the [Python license](python-embedded/py-src-2.3.4/LICENSE), -[Dear ImGui license](imgui/LICENSE.txt), and [ImGuizmo license](ImGuizmo/LICENSE) +[FFmpeg LGPL notice](ffmpeg-bink/COPYING.LGPLv2.1), +[Dear ImGui license](imgui/LICENSE.txt), [ImGuizmo license](ImGuizmo/LICENSE), +[meshoptimizer license](meshoptimizer/LICENSE.md) and +[Speex license](speex-1.0.5/COPYING) with their distributions. Other dependencies carry notices in their source files and accompanying upstream documentation. @@ -69,8 +76,7 @@ of the vendored library when changing the wrapper. ### Audio codecs [bf2audio.cmd](../../Build/bf2audio.cmd) compiles the selected Ogg/Vorbis C files -into BF2Audio. Setting `BF2AUDIO_NO_VORBIS` omits the decoder; Ogg playback then -reports the unavailable path and remains silent. The +into BF2Audio; the decoder is required and the build stops if its sources are missing. The [audio comparison harness](../../Build/bf2audio_diff.cmd) treats decoder PCM hash differences separately from the other checks. diff --git a/Code/BF2/External/base/Makefile b/Code/BF2/External/base/Makefile deleted file mode 100644 index f3109dcc7..000000000 --- a/Code/BF2/External/base/Makefile +++ /dev/null @@ -1,59 +0,0 @@ -# Makefile for tu-testbed/base library - - -TOP = .. -include $(TOP)/config - -INCLUDE_PATHS := $(SDL_INCLUDE) $(ENGINE_INCLUDE) $(LIBPNG_INCLUDE) $(ZLIB_INCLUDE) $(JPEGLIB_INCLUDE) - -CFLAGS := $(CFLAGS) $(SDL_CFLAGS) $(INCLUDE_PATHS) $(CC_DEBUG_FLAGS) -LDFLAGS := -lGL -lGLU $(SDL_LDFLAGS) $(LIB_DEBUG_FLAGS) - -BASE_LIB = $(LIB_PRE)base.$(LIB_EXT) -all: $(BASE_LIB) - -# Source files. -SRCS := \ - config.cpp \ - container.cpp \ - demo.cpp \ - dlmalloc.c \ - file_util.cpp \ - image.cpp \ - image_filters.cpp \ - jpeg.cpp \ - logger.cpp \ - membuf.cpp \ - ogl.cpp \ - png_helper.cpp \ - postscript.cpp \ - triangulate_float.cpp \ - triangulate_sint32.cpp \ - tu_file.cpp \ - tu_file_SDL.cpp \ - tu_random.cpp \ - tu_timer.cpp \ - tu_types.cpp \ - utf8.cpp \ - utility.cpp \ - zlib_adapter.cpp - -OBJS := $(SRCS:.cpp=.$(OBJ_EXT)) -OBJS := $(OBJS:.c=.$(OBJ_EXT)) - -triangulate_sint32.$(OBJ_EXT) triangulate_float.$(OBJ_EXT): triangulate_impl.h triangulate.h grid_index.h - -$(BASE_LIB): $(OBJS) - $(AR) $(LIB_OUT_FLAG)$(BASE_LIB) $(OBJS) - -clean: - -@rm -f $(BASE_LIB) $(OBJS) - -echo: - echo $(OBJS) - echo $(BASE_LIB) - -# Local Variables: -# tab-width: 8 -# indent-tabs-mode: t -# End: diff --git a/Code/BF2/External/base/component_hackery.cpp b/Code/BF2/External/base/component_hackery.cpp deleted file mode 100644 index 03a96360c..000000000 --- a/Code/BF2/External/base/component_hackery.cpp +++ /dev/null @@ -1,42 +0,0 @@ - -#include - - -class Component { -// typedef vector::iterator; - - template< class interface > - class iterator { - - - operator++() - { - } - }; -}; - - -class SpecialInterface : public Component { - void DoStuff() - { - printf( "doing stuff.\n" ); - } -}; - - -class Actor { - -}; - - -#define foreach( _decl, _p, _actor ) \ - for ( _decl _p, Component::iterator _i( _p ) = _actor.components.get_first( _p ); _i != _actor.components.end(); ++ _i, _p = *_i ) - - - -foreach(SpecialInterface*, p, actors) -{ - p->DoStuff(); - some_list.push_back( p ); -} - diff --git a/Code/BF2/External/base/container.cpp b/Code/BF2/External/base/container.cpp index 65a48c313..b27d5591c 100644 --- a/Code/BF2/External/base/container.cpp +++ b/Code/BF2/External/base/container.cpp @@ -34,10 +34,9 @@ void tu_string::append_wide_char(uint32 c) } +// Retail SwiffPlayer.dll 0x1006E3B0; forwarding veneer 0x1006EBC0. void tu_string::resize(int new_size) { - assert(new_size >= 0); - if (using_heap() == false) { if (new_size < 15) @@ -53,7 +52,6 @@ void tu_string::resize(int new_size) // round up. capacity = (capacity + 15) & ~15; char* buf = (char*) tu_malloc(capacity); - memset(buf, 0, capacity); // Copy existing data. strcpy(buf, m_local.m_buffer); @@ -162,22 +160,32 @@ void tu_string::encode_utf8_from_wchar(tu_string* result, const uint32* wstr) } +// Retail SwiffPlayer.dll 0x1006E5A0: two passes over individual 16-bit units. +// Surrogate pairs are encoded as two units, without combining them. void tu_string::encode_utf8_from_wchar(tu_string* result, const uint16* wstr) { encode_utf8_from_wchar_generic(result, wstr); } +// Retail SwiffPlayer.dll 0x1006E480; POSIX CRT spelling follows the port seam below. /*static*/ int tu_string::stricmp(const char* a, const char* b) { #ifdef _WIN32 return ::stricmp(a, b); #else - return strcasecmp(a, b); + // [CHOSEN, not recovered] Qualified: Core/PlatformCompat.h (force-included on POSIX) defines + // `stricmp` as `strcasecmp`, which renames this member to tu_string::strcasecmp. An + // unqualified call then found the member itself (unbounded self-recursion, which -O2 + // folded into a garbage result), so every tu_stringi comparison failed and no + // stringi_hash lookup ever matched: _global.Object/Array/ASSetPropFlags and all + // menu namespaces were "absent" to ActionScript. + return ::strcasecmp(a, b); #endif } +// Retail SwiffPlayer.dll 0x1006E4D0: decode once, then repeat while --index > 0. uint32 tu_string::utf8_char_at(int index) const { const char* buf = get_buffer(); @@ -191,11 +199,10 @@ uint32 tu_string::utf8_char_at(int index) const if (c == 0) { // We've hit the end of the string; don't go further. - assert(index == 0); return c; } } - while (index >= 0); + while (index > 0); return c; } @@ -240,6 +247,7 @@ tu_string tu_string::utf8_to_lower() const } +// Retail SwiffPlayer.dll 0x1006E490. /*static*/ int tu_string::utf8_char_count(const char* buf, int buflen) { const char* p = buf; @@ -260,10 +268,9 @@ tu_string tu_string::utf8_to_lower() const } +// Retail SwiffPlayer.dll 0x1006E620. tu_string tu_string::utf8_substring(int start, int end) const { - assert(start <= end); - if (start == end) { // Special case, always return empty string. @@ -295,7 +302,6 @@ tu_string tu_string::utf8_substring(int start, int end) const { if (index < end) { - assert(0); end_pointer = p; } break; diff --git a/Code/BF2/External/base/container.h b/Code/BF2/External/base/container.h index d1111397e..894c898c0 100644 --- a/Code/BF2/External/base/container.h +++ b/Code/BF2/External/base/container.h @@ -15,6 +15,7 @@ #include "base/tu_config.h" #include "base/utility.h" +#include "base/hash_capacity.h" #include #include // for strcmp and friends #include // for placement new @@ -87,6 +88,7 @@ template class array : public std::vector std::vector::insert(end(), other.begin(), other.end()); } + // SwiffPlayer.dll 0x10097AA0: append eight-byte records after one resize. void append(const T other[], int count) { // This will probably work. Depends on std::vector::iterator being typedef'd as T* @@ -109,6 +111,12 @@ template class array : public std::vector std::vector temp; this->swap(temp); } + // [CHOSEN, not recovered] S3 bridge; same reverse value lifetime as below. + void clear_reverse() + { + while (this->size()) this->pop_back(); + release(); + } }; @@ -202,6 +210,7 @@ class array { // Default constructor and destructor get called on the elements as // they are added or removed from the active part of the array. public: + // Retail SwiffPlayer.dll 0x1006FE10 / 0x10070280. array() : m_buffer(0), m_size(0), m_buffer_size(0) {} array(int size_hint) : m_buffer(0), m_size(0), m_buffer_size(0) { resize(size_hint); } array(const array& a) @@ -217,10 +226,14 @@ class array { } // Basic array access. + // Retail SwiffPlayer.dll 0x1006FD60 / 0x1006FE20 / 0x10070290. T& operator[](int index) { assert(index >= 0 && index < m_size); return m_buffer[index]; } const T& operator[](int index) const { assert(index >= 0 && index < m_size); return m_buffer[index]; } + // Retail SwiffPlayer.dll 0x1006FD70 / 0x1006FE30 / 0x100702B0. int size() const { return m_size; } + // Retail SwiffPlayer.dll 0x10074760 / 0x10085DB0 / 0x10098850 (path): + // resize before assignment, including the nested edge array and final flag. void push_back(const T& val) // Insert the given element at the end of the array. { @@ -234,6 +247,7 @@ class array { (*this)[new_size-1] = val; } + // Retail SwiffPlayer.dll 0x10085DE0 / 0x1009D570. void pop_back() // Remove the last element. { @@ -246,9 +260,15 @@ class array { const T& front() const { return (*this)[0]; } // Access the last element. + // Retail SwiffPlayer.dll 0x10084F30 / 0x10084F80 / 0x1009D530. T& back() { return (*this)[m_size-1]; } const T& back() const { return (*this)[m_size-1]; } + // Retail SwiffPlayer.dll 0x10074900 / 0x10074DC0: resize to zero. + // Trivial-element instances: 0x10072490 (edge), 0x10074810 (byte), + // 0x10074860 (dictionary pointer), 0x10074980 / 0x10074DF0 / 0x10074E40 + // (word; exact type unproved), 0x10072AB0 (pointer), 0x100A5830 (recti). + // 0x10074370 is the edge tail veneer. Live trivial destructors have no effects. void clear() // Empty and destruct all elements. { @@ -257,6 +277,16 @@ class array { void release() { clear(); } + // [CHOSEN, not recovered] S3 bridge for native storage of fixed arrays: + // destroy the last value first, retaining every element address until finished. + void clear_reverse() + { + for (int i = m_size; i > 0; --i) (m_buffer + i - 1)->~T(); + m_size = 0; + reserve(0); + } + + // Retail SwiffPlayer.dll 0x10085740 / 0x10085EB0 / 0x100748B0 (as_value). void operator=(const array& a) // Array copy. Copies the contents of a into this array. { @@ -267,6 +297,7 @@ class array { } + // Retail SwiffPlayer.dll 0x10081550 / 0x100A63B0. void remove(int index) // Removing an element from the array is an expensive operation! // It compacts only after removing the last element. @@ -287,6 +318,7 @@ class array { } + // Retail SwiffPlayer.dll 0x100A24E0. void insert(int index, const T& val = T()) // Insert the given object at the given index shifting all the elements up. { @@ -328,6 +360,9 @@ class array { } + // Retail SwiffPlayer.dll 0x10075280 / 0x100741F0 / 0x100A5480, + // 0x100A0760 (texture_glyph) / 0x100A64F0 (pending_glyph_info): + // shrink destructors precede reserve; only newly active elements are constructed. void resize(int new_size) // Preserve existing elements via realloc. // @@ -361,6 +396,8 @@ class array { }} } + // Retail SwiffPlayer.dll 0x100752E0 / 0x100851B0 (4-byte elements), + // 0x100A4C00 (8), 0x100A4BA0 (16), 0x100A4E20 (48): allocate raw capacity. void reserve(int rsize) // @@ TODO change this to use ctor, dtor, and operator= // instead of preserving existing elements via binary copy via @@ -383,7 +420,6 @@ class array { m_buffer = (T*) tu_realloc(m_buffer, sizeof(T) * m_buffer_size, sizeof(T) * old_size); } else { m_buffer = (T*) tu_malloc(sizeof(T) * m_buffer_size); - memset(m_buffer, 0, (sizeof(T) * m_buffer_size)); } assert(m_buffer); // need to throw (or something) on malloc failure! } @@ -424,7 +460,9 @@ class hash { public: hash() : m_table(NULL) { } hash(int size_hint) : m_table(NULL) { set_capacity(size_hint); } - ~hash() { clear(); } + // Retail SwiffPlayer.dll 0x100724E0 / 0x10082E10: destruction leaves the word alone. + // Interval-record instance: 0x1007DA60, tail veneer 0x1007EB10. + ~hash() { destroy_table(); } hash(const hash& src) : @@ -447,7 +485,10 @@ class hash { } } - // @@ need a "remove()" + // SwiffPlayer.dll 0x1007DA10 (interval records). The key must exist. + // [INFERRED] Source-level name. Retail destroys only this entry: neither + // the chain nor the entry count is repaired, including for a chain head. + void invalidate(const T& key) { E(find_index(key)).clear(); } void set(const T& key, const U& value) // Set a new or existing value under the key, to the value. @@ -463,6 +504,8 @@ class hash { add(key, value); } + // Retail SwiffPlayer.dll 0x10071E30 / 0x10074550 / 0x10076CF0: + // expand, increment count, hash, then insert or relocate a chain head. void add(const T& key, const U& value) // Add a new value to the hash table, under the specified key. { @@ -472,8 +515,12 @@ class hash { assert(m_table); m_table->m_entry_count++; - unsigned int hash_value = hash_functor()(key); - int index = hash_value & m_table->m_size_mask; + // [CHOSEN, not recovered] x64 (https://github.com/B2BF/OpenBF2/issues/7): the stored hash + // keeps the functor's full size_t, as find_index() compares it. The upstream unsigned int, + // widened through entry()'s int parameter, sign-extended on x64 and lost every key whose + // hash had bit 31 set. Same 32-bit values on x86. + size_t hash_value = hash_functor()(key); + int index = (int) (hash_value & m_table->m_size_mask); entry* natural_entry = &(E(index)); @@ -540,20 +587,9 @@ class hash { void clear() // Remove all entries from the hash table. { - if (m_table) - { - // Delete the entries. - for (int i = 0, n = m_table->m_size_mask; i <= n; i++) - { - entry* e = &E(i); - if (e->is_empty() == false) - { - e->clear(); - } - } - tu_free(m_table, sizeof(table) + sizeof(entry) * (m_table->m_size_mask + 1)); - m_table = NULL; - } + // Retail SwiffPlayer.dll 0x1008BEF0 / 0x100975C0. + destroy_table(); + m_table = NULL; } bool is_empty() const @@ -563,6 +599,8 @@ class hash { } + // Retail SwiffPlayer.dll 0x10074430 / 0x10076E90. + // SwiffPlayer.dll 0x10074720: optional output assignment on a successful lookup. bool get(const T& key, U* value) const // Retrieve the value under the given key. // @@ -593,6 +631,7 @@ class hash { } + // Retail SwiffPlayer.dll 0x100705B0 / 0x10070730: grow from entry count. void check_expand() // Resize the hash table to fit one more entry. Often this // doesn't involve any action. @@ -602,7 +641,7 @@ class hash { set_raw_capacity(16); } else if (m_table->m_entry_count * 3 > (m_table->m_size_mask + 1) * 2) { // Table is more than 2/3rds full. Expand. - set_raw_capacity((m_table->m_size_mask + 1) * 2); + set_raw_capacity(m_table->m_entry_count * 2); } } @@ -639,17 +678,29 @@ class hash { U second; entry() : m_next_in_chain(-2) {} + // SwiffPlayer.dll 0x10077CA0 (interval records); 0x10075090 (word/string), + // 0x100761A0 (string/word), 0x10076220 (string/held pointer), + // 0x10072B80 (word/held pointer), 0x10076400 (16-bit key/as_value). entry(const entry& e) : m_next_in_chain(e.m_next_in_chain), m_hash_value(e.m_hash_value), first(e.first), second(e.second) { } - entry(const T& key, const U& value, int next_in_chain, int hash_value) + // SwiffPlayer.dll 0x10077CD0 (interval records), 0x100750C0 (word/string), + // 0x100761E0 (string/word), 0x10076270 (string/held pointer), + // 0x10072BC0 (word/held pointer), 0x10076450 (16-bit key/as_value). + // Hash width is a native port choice; unidentified pointee types stay inferred. + entry(const T& key, const U& value, int next_in_chain, size_t hash_value) // [CHOSEN, not recovered] x64 (issue 7): was int : m_next_in_chain(next_in_chain), m_hash_value(hash_value), first(key), second(value) { } + // Retail SwiffPlayer.dll 0x100707D0 / 0x100707E0. bool is_empty() const { return m_next_in_chain == -2; } bool is_end_of_chain() const { return m_next_in_chain == -1; } + // Retail SwiffPlayer.dll 0x10072C00 / 0x10084910. + // Interval-record instance: 0x1007CD50. + // 0x10072DE0 destroys a trivial key/as_value; 0x10074E90 destroys a + // string key before releasing the held pointer, then writes the sentinel. void clear() { first.~T(); // placement delete @@ -665,6 +716,7 @@ class hash { T get_key() const { return m_hash->E(m_index).first; } U get_value() const { return m_hash->E(m_index).second; } + // Retail SwiffPlayer.dll 0x100707C0 / 0x10071F90: hash/index to entry. const entry& operator*() const { assert(is_end() == false && (m_hash->E(m_index).is_empty() == false)); @@ -672,6 +724,7 @@ class hash { } const entry* operator->() const { return &(operator*()); } + // Retail SwiffPlayer.dll 0x10071FA0 / 0x10079A90 / 0x10072120. void operator++() { assert(m_hash); @@ -688,6 +741,7 @@ class hash { } } + // Retail SwiffPlayer.dll 0x10072890 / 0x10079AE0: any two ends compare equal. bool operator==(const const_iterator& it) const { if (is_end() && it.is_end()) @@ -702,9 +756,11 @@ class hash { } } + // Retail SwiffPlayer.dll 0x100744D0 / 0x100747F0. bool operator!=(const const_iterator& it) const { return ! (*this == it); } + // Retail SwiffPlayer.dll 0x10070F50 / 0x100710D0. bool is_end() const { return @@ -714,7 +770,7 @@ class hash { } protected: - friend class hash; + friend class ::hash; // [BUILD-FIX SwiffPlayer: qualified; MSVC finds std::hash too in TUs with using namespace std] const_iterator(const hash* h, int index) : @@ -732,6 +788,7 @@ class hash { struct iterator : public const_iterator { // Allow non-const access to entries. + // SwiffPlayer.dll 0x10072100: reload the current table through its owner. entry& operator*() const { assert(const_iterator::is_end() == false); @@ -740,7 +797,7 @@ class hash { entry* operator->() const { return &(operator*()); } private: - friend class hash; + friend class ::hash; // [BUILD-FIX SwiffPlayer: qualified; MSVC finds std::hash too in TUs with using namespace std] iterator(hash* h, int i0) : @@ -751,6 +808,7 @@ class hash { friend struct iterator; + // Retail SwiffPlayer.dll 0x10074470 / 0x10079B40 / 0x10097F80. iterator begin() { if (m_table == 0) return iterator(NULL, 0); @@ -783,6 +841,31 @@ class hash { private: + // Retail SwiffPlayer.dll 0x10074910 / 0x10074AC0 / 0x10074D30 / 0x10074A40: + // destroy occupied entries in index order, then free storage. + // 0x10075C90 / 0x10075CB0 / 0x10075CC0 / 0x10075CD0 / 0x10075CE0 + // are destructor tail veneers; no final null-word write is made. + // Further destructor veneers: 0x10074420 -> 0x100724E0, + // 0x10075C60 -> 0x10074910, 0x10075C80 / 0x10076690 -> 0x100749D0, + // 0x10075CF0 / 0x100766B0 -> 0x10074CC0, + // 0x10075D00 / 0x100766D0 -> 0x10074D30, + // 0x10075DE0 -> 0x100746A0, 0x10076F10 / 0x10077790 -> 0x10075D50. + // Template types remain [INFERRED]; native compiler emits forwarding as needed. + void destroy_table() + { + if (m_table) + { + for (int i = 0, n = m_table->m_size_mask; i <= n; i++) + { + entry* e = &E(i); + if (e->is_empty() == false) e->clear(); + } + tu_free(m_table, sizeof(table) + sizeof(entry) * (m_table->m_size_mask + 1)); + } + } + + // Retail SwiffPlayer.dll 0x10078560 / 0x10075FE0 / 0x100A0C90: + // reject empty/displaced heads, then compare cached hash and key along the chain. int find_index(const T& key) const // Find the index of the matching entry. If no match, then return -1. { @@ -819,6 +902,10 @@ class hash { } // Helpers. + // Retail SwiffPlayer.dll 0x100705E0 / 0x10070600 / 0x10070620 / 0x10070640 + // and 0x10070660 / 0x10070680 / 0x100706A0 use 16-byte retail entries; + // 0x10070760 / 0x10070780 / 0x100707A0 use 28-byte entries. + // [INFERRED] template arguments; native sizeof(entry) includes pointer widths. entry& E(int index) { assert(m_table); @@ -833,6 +920,12 @@ class hash { } + // SwiffPlayer.dll capacity instances (template arguments remain [INFERRED]): + // 0x10074F90, 0x100762C0, 0x100764A0, 0x10077240, 0x10077370, + // 0x10077510, 0x10078FC0, 0x10079100, 0x10079240, 0x10079380, + // 0x1007A330, 0x1007A950, 0x1007EB20, 0x100830A0, 0x100836C0, + // 0x100847F0, 0x1008DFC0, 0x10097C20, 0x10099B80, 0x100A11B0, + // 0x100A12B0, 0x100A65F0. Native entry widths/ownership remain adapted. void set_raw_capacity(int new_size) // Resize the hash table to the given size (Rehash the // contents of the current table). The arg is the number of @@ -840,30 +933,27 @@ class hash { // actually contain (which will be less than this). { if (new_size <= 0) { - // Special case. + // [CHOSEN, not recovered] Existing native clear adapter: older PE + // instances (0x10074F90) call destruction without nulling; later + // instances (0x10097C20 / 0x1008DFC0) call clear and null the word. + // [RETIRE-WHEN: swf-hash-clear-generation] Establish each concrete + // template's cleanup variant and validate nonpositive resize ownership. clear(); return; } - // Force new_size to be a power of two. - int bits = fchop(log2((float)(new_size-1)) + 1); - assert((1 << bits) >= new_size); - - new_size = 1 << bits; - - // Minimum size; don't incur rehashing cost when - // expanding very small tables. - if (new_size < 16) - { - new_size = 16; - } + // [CHOSEN, not recovered] Native mode binding selects the normal + // client's 24-bit/nearest contract instead of querying host FP control. + // The helper's integer results are recovered for that mode. + const uint32_t capacity = tu_util::hash_raw_capacity(new_size); + new_size = capacity <= 0x7fffffffu ? int(capacity) : (-2147483647 - 1); hash new_hash; - new_hash.m_table = (table*) tu_malloc(sizeof(table) + sizeof(entry) * new_size); + new_hash.m_table = (table*) tu_malloc(sizeof(table) + sizeof(entry) * capacity); assert(new_hash.m_table); // @@ need to throw (or something) on malloc failure! new_hash.m_table->m_entry_count = 0; - new_hash.m_table->m_size_mask = new_size - 1; + new_hash.m_table->m_size_mask = int(capacity - 1u); {for (int i = 0; i < new_size; i++) { new_hash.E(i).m_next_in_chain = -2; // mark empty @@ -910,7 +1000,8 @@ class tu_stringi; class tu_string { public: - tu_string() { m_local.m_size = 1; memset(m_local.m_buffer, 0, 15); } + // Retail SwiffPlayer.dll 0x100924FF: initialize only the size and terminator. + tu_string() { m_local.m_size = 1; m_local.m_buffer[0] = 0; } tu_string(const char* str) { m_local.m_size = 1; @@ -920,6 +1011,7 @@ class tu_string resize(new_size); strcpy(get_buffer(), str); } + // Retail SwiffPlayer.dll 0x1006E510. tu_string(const char* buf, int buflen) { m_local.m_size = 1; @@ -930,6 +1022,7 @@ class tu_string memcpy(get_buffer(), buf, buflen); get_buffer()[buflen] = 0; // terminate. } + // Retail SwiffPlayer.dll 0x10009770 (also used by base template instances). tu_string(const tu_string& str) { m_local.m_size = 1; @@ -943,14 +1036,16 @@ class tu_string m_local.m_size = 1; m_local.m_buffer[0] = 0; - *this = wide_char_str; + // [CHOSEN, not recovered] S3 bridge for the 2006 32-bit-unit overload. + encode_utf8_from_wchar(this, wide_char_str); } tu_string(const uint16* wide_char_str) { m_local.m_size = 1; m_local.m_buffer[0] = 0; - *this = wide_char_str; + // Retail helper 0x1006E5A0, constructed-empty caller 0x100924FF. + encode_utf8_from_wchar(this, wide_char_str); } ~tu_string() @@ -989,6 +1084,16 @@ class tu_string strcpy(get_buffer(), str.get_buffer()); } + // Retail SwiffPlayer.dll 0x10089360; method name [INFERRED]. + // Copy exactly buflen bytes and append a NUL. The source must survive resize. + void assign(const char* buf, int buflen) + { + resize(buflen); + memcpy(get_buffer(), buf, buflen); + get_buffer()[buflen] = 0; + } + + // Retail SwiffPlayer.dll 0x100858F0. bool operator==(const char* str) const { return strcmp(*this, str) == 0; @@ -1022,6 +1127,7 @@ class tu_string } int size() const { return length(); } + // Retail SwiffPlayer.dll 0x1006E580. char& operator[](int index) { assert(index >= 0 && index <= size()); @@ -1032,6 +1138,7 @@ class tu_string return (*(const_cast(this)))[index]; } + // Retail SwiffPlayer.dll 0x10072F30. void operator+=(const char* str) { int str_length = strlen(str); @@ -1047,12 +1154,16 @@ class tu_string assert(old_length >= 0); resize(old_length + 1); strncpy(get_buffer() + old_length, (char *)&ch, 1); + // [CHOSEN, not recovered] S3 bridge: the retained 2006 character append + // needs its own terminator when retail resize moves local data to the heap. + get_buffer()[old_length + 1] = 0; } // Append wide char. Both versions of wide char. void append_wide_char(uint16 ch); void append_wide_char(uint32 ch); + // Retail SwiffPlayer.dll 0x10088CA0. void operator+=(const tu_string& str) { int str_length = str.length(); @@ -1062,12 +1173,13 @@ class tu_string strcpy(get_buffer() + old_length, str.c_str()); } + // Retail SwiffPlayer.dll 0x10088D10: copy the appended temporary into the result. tu_string operator+(const char* str) const // NOT EFFICIENT! But convenient. { tu_string new_string(*this); new_string += str; - return new_string; + return tu_string(new_string); } bool operator<(const char* str) const @@ -1094,6 +1206,8 @@ class tu_string // Sets buffer size to new_size+1 (i.e. enough room for // new_size chars, plus terminating 0). + // Growing from local to heap storage preserves the old terminator but leaves + // the new tail uninitialized; callers that fill the tail must terminate it. void resize(int new_size); // Set *result to the UTF-8 encoded version of wstr[]. @@ -1109,7 +1223,8 @@ class tu_string static int stricmp(const char* a, const char* b); // Return the Unicode char at the specified character - // position. index is in UTF-8 chars, NOT bytes. + // position. Positive positions are one-based; zero and negative positions + // also decode the first character. Returns zero at the terminator. uint32 utf8_char_at(int index) const; // Return the string in this container as all upper case letters @@ -1260,7 +1375,9 @@ class string_hash_functor public: size_t operator()(const T& data) const { - int size = data.length(); + // Retail SwiffPlayer.dll 0x100846F0: string comparison and hashing both + // stop at the first NUL, even when the stored byte length is larger. + int size = (int) strlen((const char*) data); return bernstein_hash((const char*) data, size); } @@ -1281,7 +1398,9 @@ class stringi_hash_functor public: size_t operator()(const T& data) const { - int size = data.length(); + // Retail SwiffPlayer.dll 0x10075FE0 / 0x10079E40 / 0x10099860: + // key hashing stops at the first NUL, as the comparison does. + int size = (int) strlen((const char*) data); return bernstein_hash_case_insensitive((const char*) data, size); } diff --git a/Code/BF2/External/base/cschema.h b/Code/BF2/External/base/cschema.h deleted file mode 100644 index 78e043031..000000000 --- a/Code/BF2/External/base/cschema.h +++ /dev/null @@ -1,208 +0,0 @@ -// Notes for contemplated "Pretty good C++ schema system" - -/* -These are some recurring needs in C++ game development: - -* to initialize hard-coded C++ structures (structs & classes) from a - softer data source such as XML, Lua, s-lists, .INI or whatever - custom data format you've cooked up to describe game levels. - -* to serialize the state of the C++ program in order to implement - game-saving. - -* to dynamically tweak live values in the program in order to tune - gameplay. - -There are many ways to service these needs. The needs are not -identical, and need not be implemented through a common system. -Nevertheless, at the core, they do all have something in common: in -some way, they all require ways to annotate the content of C++ -datatypes. In other words, they provide a "schema" that describes -what's inside live C++ data structures. - -It seems to me that a "pretty good" universal schema system for C++, -tailored for the above game-development needs, would be extremely -useful to have. "Pretty good" is not a modest target; I've -implemented variations on the above tasks dozens of times in my career -and IMO none of my implementations have risen to the status of "pretty -good". - -These are some requirements I would expect from a "pretty good C++ -schema system": - -* Fast path. Data assets are compilable into a compact format, with a - "fast path" for loading. Ideally the compact format would just be a - memory dump of live data structures, so loading it is essentially - just fread(), plus minimal fixup. Notes: - - * in order to be safe, you need to check that the schema of the - saved data matches the schema of the objects you're about to - fread() into. This can be done by storing a digest (hash) of the - schema description with the saved data, and comparing the digest - on load. If the digests match, then fread() is safe. If they - don't match, then you want to fall back on a slower path, which - uses a stored digest in the saved data to interpret the dumped - binary data, and push it as well as possible into the matching - elements of the run-time data structure. - -* Human-readable capability. It should be possible to initialize data - structures from a reasonably sane ASCII format. This doesn't have - to be the format of the final shipped assets (see "fast path" - above), but this is so useful during development that you want to be - able to support it. - -* Minimal impact on C++ code. There is no way to implement a C++ - schema system without either adding some code to your C++ program, - or implementing some kind of processor that reads your C++ source or - object files in order to understand your data structures. There are - different schools of thought on this: - - 1 Add code and macros to describe/iterate the C++ structures. This - is what you're doing when you write "save/load" code that reads & - writes each of the members in your data structures. One - (arguable) improvement is a set of macros & templates where you - declare the members of your structs, which initializes some info - that the run-time system can use to iterate over your structs. - - 2 Use a tool to read your C++ source and extract the schemas. - E.g. SWIG, tolua, etc. This cuts down on busy-work for the - programmer, but on the other hand, creates some extra complexity - in the building process. - - 3 Parse some side-data emitted by the compiler. See Bilas' FUBI for - example. http://www.drizzle.com/~scottb/publish/gpgems1_fubi.htm - - For a generic "pretty good" system, the only acceptable approach is - 1. 2 can be nice, but it's a tough sell for cross-platform - development, especially if one of the platforms involves MSVC. 3 is - necessarily compiler-specific. - -* Acceptable level of complexity. Remains to be seen how bad - "acceptable" is. - -* Needs to deal with virtual inheritance in C++ (not to mention - regular inheritance), because IMO it's useful. - -Random thoughts on implementation: - -* use a function per-class to iterate over internals. Use some kind - of visitor pattern to accomodate various needs. The schema - iteration could compile a schema description for later use - (generating digests), or serialize the state of an object directly. - E.g. - - class some_class : virtual public parent_class1, virtual public parent_class2 - { - ... - virtual void do_schema(cschema_visitor* v); - - private: - int m_member1; - some_other_class* m_member2; - ... - }; - - - void some_class::do_schema(cschema_visitor* v) - { - // these might be overloaded macro/template magic - schema_start(v, some_class); - do_schema(v, (parent_class1*) this); - do_schema(v, (parent_class2*) this); - do_schema(v, m_member1); - do_schema(v, m_member2); - ... - } - - Basically, when it gets down to basic datatypes, do_schema() calls - cschema_visitor::notify_member(member_type, member_name, member_address) - - Note to self: overloading a built-in operator (e.g. like C++ streams - do w/ operator<<) has advantages, since you can provide an overload - that matches a class, *without* making it a member function. - -* It's good to have a "update_cached()" method that gets called after - loading from a schema. - -* For tweaking in particular, it's helpful to have a way to add extra - annotation. E.g.: - - do_schema(v, m_some_member, "min=0 max=100 desc='number of widgets emitted per second'"); - - Where the extra info gets exposed to a tweaking tool. - -* Pointers are important. Basically, in order to serialize pointers, - what we need is: - - * Given a pointer to a live object, be able to get a descriptor of - its concrete type (e.g. a type name string; could be - typeid(*ptr).name(), but that tends to make an ugly string, and - would require users to enable RTTI). - - * table of factory functions that take a stream for init, indexed by - type descriptor. - - The rest we can implement with a pointer map, by just tracing all - pointers and serializing objects as we go. - -The above discussion is a lot of "how", i.e. how to build schemas, but -not enough "what", i.e. what exactly are these schemas? - -Schemas -======= - -A cschema is a description of a block of memory, corresponding to a -compiled C++ datatype. - -... - - -A Totally Different Approach -============================ - -Another approach to this problem is to "fix" C++'s data model. What I -have in mind is replacing C++'s heap and static variables with -something that is SQL-like, and then bind the SQL data structures to -some fancy DB back-end. - -Half-baked sketch: - -table entities { - // table layout; roughly equivalent to 'struct' or 'class' - int id = 0 (primary key autoincrement); - string name = ""; - bool updatable = true; - vec3 position = vec3::zero; - float health = 100; - ... - - // allow member functions in here too? I guess so. -} = { - // some static initialization - { , "world", false, 0, ... }, - { , "player0", true, vec3(100, 0, 100), 100, ... }, - ... -}; - -void update_entities() -{ - // SQL-like iteration through a subset of the rows; maybe there is a better - // way to express this using "views" or something. - for (entities.iterator e = entities.where("updatable = true"); e != entities.end(); ++e) - { - e.row.update(); // or update_entity(e) or entities.update_row(e.id) or ??? - } -} - -So the idea is that persistence can happen easily via something like -"database.dump(filename)", and the SQL key crud automatically deals -with pointer fixup and GC, and under the hood the back-end can do lots -of intelligent stuff to optimize your queries, with minimal hinting -from the programmer. - -To implement this, I guess the reasonable thing would be to preprocess -the augmented language and output C++ code. Hm, unfortunate. Or, -perhaps there is some insane template trickery that could do it -(although not necessarily with all the syntax amenities)? - -*/ diff --git a/Code/BF2/External/base/demo.cpp b/Code/BF2/External/base/demo.cpp deleted file mode 100644 index c8dbec7c1..000000000 --- a/Code/BF2/External/base/demo.cpp +++ /dev/null @@ -1,131 +0,0 @@ -// demo.cpp -- Thatcher Ulrich 2005 - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - -// Some helper code for making graphical demos. Covers OpenGL/SDL -// initialization, and some basic viewport navigation. - - -#include "base/tu_config.h" -#include "base/demo.h" -#include "base/ogl.h" -#include "SDL.h" - - -namespace demo -{ - void init_video(int width, int height, int depth) - { - // Display. - // Initialize the SDL subsystems we're using. - if (SDL_Init(SDL_INIT_VIDEO /* | SDL_INIT_JOYSTICK | SDL_INIT_CDROM | SDL_INIT_AUDIO*/)) - { - fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError()); - exit(1); - } - atexit(SDL_Quit); - - SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); - - // Set the video mode. - if (SDL_SetVideoMode(width, height, depth, SDL_OPENGL) == 0) - { - fprintf(stderr, "SDL_SetVideoMode() failed."); - exit(1); - } - - ogl::open(); - } - - - bool update_nav2d(nav2d_state* state) - { - state->m_keys.resize(0); - - // Handle input. - SDL_Event event; - while (SDL_PollEvent(&event)) - { - switch (event.type) - { - case SDL_KEYDOWN: - { - int key = event.key.keysym.sym; - - if (key == SDLK_q || key == SDLK_ESCAPE) - { - return true; - } else if (key == SDLK_EQUALS) { - state->m_scale *= 0.5f; - } else if (key == SDLK_MINUS) { - state->m_scale *= 2.0f; - } else { - state->m_keys.push_back(key); - } - break; - } - - case SDL_MOUSEMOTION: - { - int new_x = (int) (event.motion.x); - int new_y = (int) (event.motion.y); - state->m_mouse_dx = new_x - state->m_mouse_x; - state->m_mouse_dy = new_y - state->m_mouse_y; - if (state->m_mouse_buttons & 2) { - // Left drag: move. - state->m_center_x -= state->m_mouse_dx * state->m_scale; - state->m_center_y += state->m_mouse_dy * state->m_scale; - } - state->m_mouse_x = new_x; - state->m_mouse_y = new_y; - break; - } - - case SDL_MOUSEBUTTONDOWN: - case SDL_MOUSEBUTTONUP: - { - int mask = 1 << (event.button.button); - if (event.button.state == SDL_PRESSED) - { - state->m_mouse_buttons |= mask; - } - else - { - state->m_mouse_buttons &= ~mask; - } - break; - } - - case SDL_QUIT: - return true; - break; - - default: - break; - } - } - - return false; - } - - - void set_nav2d_viewport(const nav2d_state& state) - { - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - glOrtho(state.m_center_x - 500 * state.m_scale, state.m_center_x + 500 * state.m_scale, - state.m_center_y - 500 * state.m_scale, state.m_center_y + 500 * state.m_scale, -1, 1); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - } -} - - -// Local Variables: -// mode: C++ -// c-basic-offset: 8 -// tab-width: 8 -// indent-tabs-mode: t -// End: - diff --git a/Code/BF2/External/base/demo.h b/Code/BF2/External/base/demo.h deleted file mode 100644 index 52345abca..000000000 --- a/Code/BF2/External/base/demo.h +++ /dev/null @@ -1,86 +0,0 @@ -// demo.h -- Thatcher Ulrich 2005 - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - -// Some helper code for making graphical demos. Covers OpenGL/SDL -// initialization, and some basic viewport navigation. - - -#ifndef DEMO_H -#define DEMO_H - - -#include "base/tu_config.h" -#include "base/container.h" - - -namespace demo -{ - // Open an OpenGL window with the given dimensions. - void init_video(int width, int height, int depth); - - // A state object you can use to manage 2D scrolling & zooming. - struct nav2d_state - { - // 2d viewport state. - float m_center_x; - float m_center_y; - float m_scale; - - // Current mouse state. - int m_mouse_x; - int m_mouse_y; - int m_mouse_buttons; - - // Change in mouse position in pixels, this frame. - int m_mouse_dx; - int m_mouse_dy; - - // Codes of any keys pushed this frame. - array m_keys; - - nav2d_state() - : - m_center_x(0), - m_center_y(0), - m_scale(1), - m_mouse_x(0), - m_mouse_y(0), - m_mouse_buttons(0), - m_mouse_dx(0), - m_mouse_dy(0) - { - } - - void mouse_to_world(float* x, float* y) - // Returns the current world-coords of the mouse pointer. - { - *x = (m_mouse_x - 500) * m_scale + m_center_x; - *y = (500 - m_mouse_y) * m_scale + m_center_y; - } - }; - - // Checks and processes the SDL message queue. Returns true - // if the user wants to exit. - // - // TODO: do some kind of callback registry for handling misc - // app-specific inputs - bool update_nav2d(nav2d_state* state); - - // Sets the OpenGL projection & modelview according to the 2d - // view state. - void set_nav2d_viewport(const nav2d_state& state); -} - - -#endif // DEMO_H - - -// Local Variables: -// mode: C++ -// c-basic-offset: 8 -// tab-width: 8 -// indent-tabs-mode: t -// End: - diff --git a/Code/BF2/External/base/dlmalloc.c b/Code/BF2/External/base/dlmalloc.c deleted file mode 100644 index 58a185e0e..000000000 --- a/Code/BF2/External/base/dlmalloc.c +++ /dev/null @@ -1,5406 +0,0 @@ -/* - This is a version (aka dlmalloc) of malloc/free/realloc written by - Doug Lea and released to the public domain. Use, modify, and - redistribute this code without permission or acknowledgement in any - way you wish. Send questions, comments, complaints, performance - data, etc to dl@cs.oswego.edu - -* VERSION 2.7.0 Sun Mar 11 14:14:06 2001 Doug Lea (dl at gee) - - Note: There may be an updated version of this malloc obtainable at - ftp://gee.cs.oswego.edu/pub/misc/malloc.c - Check before installing! - -* Quickstart - - This library is all in one file to simplify the most common usage: - ftp it, compile it (-O), and link it into another program. All - of the compile-time options default to reasonable values for use on - most unix platforms. Compile -DWIN32 for reasonable defaults on windows. - You might later want to step through various compile-time and dynamic - tuning options. - - For convenience, an include file for code using this malloc is at: - ftp://gee.cs.oswego.edu/pub/misc/malloc-2.7.0.h - You don't really need this .h file unless you call functions not - defined in your system include files. The .h file contains only the - excerpts from this file needed for using this malloc on ANSI C/C++ - systems, so long as you haven't changed compile-time options about - naming and tuning parameters. If you do, then you can create your - own malloc.h that does include all settings by cutting at the point - indicated below. - -* Why use this malloc? - - This is not the fastest, most space-conserving, most portable, or - most tunable malloc ever written. However it is among the fastest - while also being among the most space-conserving, portable and tunable. - Consistent balance across these factors results in a good general-purpose - allocator for malloc-intensive programs. - - The main properties of the algorithms are: - * For large (>= 512 bytes) requests, it is a pure best-fit allocator, - with ties normally decided via FIFO (i.e. least recently used). - * For small (<= 64 bytes by default) requests, it is a caching - allocator, that maintains pools of quickly recycled chunks. - * In between, and for combinations of large and small requests, it does - the best it can trying to meet both goals at once. - * For very large requests (>= 128KB by default), it relies on system - memory mapping facilities, if supported. - - For a longer but slightly out of date high-level description, see - http://gee.cs.oswego.edu/dl/html/malloc.html - - You may already by default be using a C library containing a malloc - that is based on some version of this malloc (for example in - linux). You might still want to use the one in this file in order to - customize settings or to avoid overheads associated with library - versions. - -* Contents, described in more detail in "description of public routines" below. - - Standard (ANSI/SVID/...) functions: - malloc(size_t n); - calloc(size_t n_elements, size_t element_size); - free(Void_t* p); - realloc(Void_t* p, size_t n); - memalign(size_t alignment, size_t n); - valloc(size_t n); - mallinfo() - mallopt(int parameter_number, int parameter_value) - - Additional functions: - independent_calloc(size_t n_elements, size_t size, Void_t* chunks[]); - independent_comalloc(size_t n_elements, size_t sizes[], Void_t* chunks[]); - pvalloc(size_t n); - cfree(Void_t* p); - malloc_trim(size_t pad); - malloc_usable_size(Void_t* p); - malloc_stats(); - -* Vital statistics: - - Supported pointer representation: 4 or 8 bytes - Supported size_t representation: 4 or 8 bytes - Note that size_t is allowed to be 4 bytes even if pointers are 8. - You can adjust this by defining INTERNAL_SIZE_T - - Alignment: 2 * sizeof(size_t) (default) - (i.e., 8 byte alignment with 4byte size_t). This suffices for - nearly all current machines and C compilers. However, you can - define MALLOC_ALIGNMENT to be wider than this if necessary. - - Minimum overhead per allocated chunk: 4 or 8 bytes - Each malloced chunk has a hidden word of overhead holding size - and status information. - - Minimum allocated size: 4-byte ptrs: 16 bytes (including 4 overhead) - 8-byte ptrs: 24/32 bytes (including, 4/8 overhead) - - When a chunk is freed, 12 (for 4byte ptrs) or 20 (for 8 byte - ptrs but 4 byte size) or 24 (for 8/8) additional bytes are - needed; 4 (8) for a trailing size field and 8 (16) bytes for - free list pointers. Thus, the minimum allocatable size is - 16/24/32 bytes. - - Even a request for zero bytes (i.e., malloc(0)) returns a - pointer to something of the minimum allocatable size. - - The maximum overhead wastage (i.e., number of extra bytes - allocated than were requested in malloc) is less than or equal - to the minimum size, except for requests >= mmap_threshold that - are serviced via mmap(), where the worst case wastage is 2 * - sizeof(size_t) bytes plus the remainder from a system page (the - minimal mmap unit); typically 4096 or 8192 bytes. - - Maximum allocated size: 4-byte size_t: 2^32 minus about two pages - 8-byte size_t: 2^64 minus about two pages - - It is assumed that (possibly signed) size_t values suffice to - represent chunk sizes. `Possibly signed' is due to the fact - that `size_t' may be defined on a system as either a signed or - an unsigned type. The ISO C standard says that it must be - unsigned, but a few systems are known not to adhere to this. - Additionally, even when size_t is unsigned, sbrk (which is by - default used to obtain memory from system) accepts signed - arguments, and may not be able to handle size_t-wide arguments - with negative sign bit. Generally, values that would - appear as negative after accounting for overhead and alignment - are supported only via mmap(), which does not have this - limitation. - - Requests for sizes outside the allowed range will perform an optional - failure action and then return null. (Requests may also - also fail because a system is out of memory.) - - Thread-safety: NOT thread-safe unless USE_MALLOC_LOCK defined - - When USE_MALLOC_LOCK is defined, wrappers are created to - surround every public call with either a pthread mutex or - a win32 spinlock (depending on WIN32). This is not - especially fast, and can be a major bottleneck. - It is designed only to provide minimal protection - in concurrent environments, and to provide a basis for - extensions. If you are using malloc in a concurrent program, - you would be far better off obtaining ptmalloc, which is - derived from a version of this malloc, and is well-tuned for - concurrent programs. (See http://www.malloc.de) - - Compliance: I believe it is compliant with the 1997 Single Unix Specification - (See http://www.opennc.org). Also SVID/XPG, ANSI C, and probably - others as well. - -* Synopsis of compile-time options: - - People have reported using previous versions of this malloc on all - versions of Unix, sometimes by tweaking some of the defines - below. It has been tested most extensively on Solaris and - Linux. It is also reported to work on WIN32 platforms. - People also report using it in stand-alone embedded systems. - - The implementation is in straight, hand-tuned ANSI C. It is not - at all modular. (Sorry!) It uses a lot of macros. To be at all - usable, this code should be compiled using an optimizing compiler - (for example gcc -O3) that can simplify expressions and control - paths. (FAQ: some macros import variables as arguments rather than - declare locals because people reported that some debuggers - otherwise get confused.) - - OPTION DEFAULT VALUE - - Compilation Environment options: - - __STD_C derived from C compiler defines - WIN32 NOT defined - HAVE_MEMCPY defined - USE_MEMCPY 1 if HAVE_MEMCPY is defined - HAVE_MMAP defined as 1 - MMAP_CLEARS 1 - HAVE_MREMAP 0 unless linux defined - malloc_getpagesize derived from system #includes, or 4096 if not - HAVE_USR_INCLUDE_MALLOC_H NOT defined - LACKS_UNISTD_H NOT defined unless WIN32 - LACKS_SYS_PARAM_H NOT defined unless WIN32 - LACKS_SYS_MMAN_H NOT defined unless WIN32 - - Changing default word sizes: - - INTERNAL_SIZE_T size_t - MALLOC_ALIGNMENT 2 * sizeof(INTERNAL_SIZE_T) - - Configuration and functionality options: - - USE_DL_PREFIX NOT defined - USE_PUBLIC_MALLOC_WRAPPERS NOT defined - USE_MALLOC_LOCK NOT defined - DEBUG NOT defined - REALLOC_ZERO_BYTES_FREES NOT defined - MALLOC_FAILURE_ACTION errno = ENOMEM, if __STD_C defined, else no-op - TRIM_FASTBINS 0 - - Options for customizing MORECORE: - - MORECORE sbrk - MORECORE_CONTIGUOUS 1 - MORECORE_CANNOT_TRIM NOT defined - MMAP_AS_MORECORE_SIZE (1024 * 1024) - - Tuning options that are also dynamically changeable via mallopt: - - DEFAULT_MXFAST 64 - DEFAULT_TRIM_THRESHOLD 128 * 1024 - DEFAULT_TOP_PAD 0 - DEFAULT_MMAP_THRESHOLD 128 * 1024 - DEFAULT_MMAP_MAX 65536 - - There are several other #defined constants and macros that you - probably don't want to touch unless you are extending or adapting malloc. -*/ - -/* tu: we must be thread-safe. */ -#define USE_MALLOC_LOCK -/* tu: prefix the malloc functions. MSVC has problems otherwise... */ -#define USE_DL_PREFIX - - -/* - WIN32 sets up defaults for MS environment and compilers. - Otherwise defaults are for unix. -*/ - -/* #define WIN32 */ - -#ifdef WIN32 - -#define WIN32_LEAN_AND_MEAN -#include - -/* Win32 doesn't supply or need the following headers */ -#define LACKS_UNISTD_H -#define LACKS_SYS_PARAM_H -#define LACKS_SYS_MMAN_H - -/* Use the supplied emulation of sbrk */ -#define MORECORE sbrk -#define MORECORE_CONTIGUOUS 1 -#define MORECORE_FAILURE ((void*)(-1)) - -/* Use the supplied emulation of mmap and munmap */ -#define HAVE_MMAP 1 -#define MUNMAP_FAILURE (-1) -#define MMAP_CLEARS 1 - -/* These values don't really matter in windows mmap emulation */ -#define MAP_PRIVATE 1 -#define MAP_ANONYMOUS 2 -#define PROT_READ 1 -#define PROT_WRITE 2 - -/* Emulation functions defined at the end of this file */ - -/* If USE_MALLOC_LOCK, use supplied critical-section-based lock functions */ -#ifdef USE_MALLOC_LOCK -static int slwait(int *sl); -static int slrelease(int *sl); -#endif - -static long getpagesize(void); -static long getregionsize(void); -static void *sbrk(long size); -static void *mmap(void *ptr, long size, long prot, long type, long handle, long arg); -static long munmap(void *ptr, long size); - -static void vminfo (unsigned long *free, unsigned long *reserved, unsigned long *committed); -static int cpuinfo (int whole, unsigned long *kernel, unsigned long *user); - -#endif - -/* - __STD_C should be nonzero if using ANSI-standard C compiler, a C++ - compiler, or a C compiler sufficiently close to ANSI to get away - with it. -*/ - -#ifndef __STD_C -#if defined(__STDC__) || defined(_cplusplus) -#define __STD_C 1 -#else -#define __STD_C 0 -#endif -#endif /*__STD_C*/ - - -/* - Void_t* is the pointer type that malloc should say it returns -*/ - -#ifndef Void_t -#if (__STD_C || defined(WIN32)) -#define Void_t void -#else -#define Void_t char -#endif -#endif /*Void_t*/ - -#if __STD_C -#include /* for size_t */ -#else -#include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/* define LACKS_UNISTD_H if your system does not have a . */ - -/* #define LACKS_UNISTD_H */ - -#ifndef LACKS_UNISTD_H -#include -#endif - -/* define LACKS_SYS_PARAM_H if your system does not have a . */ - -/* #define LACKS_SYS_PARAM_H */ - - -#include /* needed for malloc_stats */ -#include /* needed for optional MALLOC_FAILURE_ACTION */ - - -/* - Debugging: - - Because freed chunks may be overwritten with bookkeeping fields, this - malloc will often die when freed memory is overwritten by user - programs. This can be very effective (albeit in an annoying way) - in helping track down dangling pointers. - - If you compile with -DDEBUG, a number of assertion checks are - enabled that will catch more memory errors. You probably won't be - able to make much sense of the actual assertion errors, but they - should help you locate incorrectly overwritten memory. The - checking is fairly extensive, and will slow down execution - noticeably. Calling malloc_stats or mallinfo with DEBUG set will - attempt to check every non-mmapped allocated and free chunk in the - course of computing the summmaries. (By nature, mmapped regions - cannot be checked very much automatically.) - - Setting DEBUG may also be helpful if you are trying to modify - this code. The assertions in the check routines spell out in more - detail the assumptions and invariants underlying the algorithms. - - Setting DEBUG does NOT provide an automated mechanism for checking - that all accesses to malloced memory stay within their - bounds. However, there are several add-ons and adaptations of this - or other mallocs available that do this. -*/ - -#if DEBUG -#include -#else -#define assert(x) ((void)0) -#endif - - -/* - INTERNAL_SIZE_T is the word-size used for internal bookkeeping - of chunk sizes. - - The default version is the same as size_t. - - While not strictly necessary, it is best to define this as an - unsigned type, even if size_t is a signed type. This may avoid some - artificial size limitations on some systems. - - On a 64-bit machine, you may be able to reduce malloc overhead by - defining INTERNAL_SIZE_T to be a 32 bit `unsigned int' at the - expense of not being able to handle more than 2^32 of malloced - space. If this limitation is acceptable, you are encouraged to set - this unless you are on a platform requiring 16byte alignments. In - this case the alignment requirements turn out to negate any - potential advantages of decreasing size_t word size. - - Implementors: Beware of the possible combinations of: - - INTERNAL_SIZE_T might be signed or unsigned, might be 32 or 64 bits, - and might be the same width as int or as long - - size_t might have different width and signedness as INTERNAL_SIZE_T - - int and long might be 32 or 64 bits, and might be the same width - To deal with this, most comparisons and difference computations - among INTERNAL_SIZE_Ts should cast them to unsigned long, being - aware of the fact that casting an unsigned int to a wider long does - not sign-extend. (This also makes checking for negative numbers - awkward.) Some of these casts result in harmless compiler warnings - on some systems. -*/ - -#ifndef INTERNAL_SIZE_T -#define INTERNAL_SIZE_T size_t -#endif - -/* The corresponding word size */ -#define SIZE_SZ (sizeof(INTERNAL_SIZE_T)) - - -/* - MALLOC_ALIGNMENT is the minimum alignment for malloc'ed chunks. - It must be a power of two at least 2 * SIZE_SZ, even on machines - for which smaller alignments would suffice. It may be defined as - larger than this though. Note however that code and data structures - are optimized for the case of 8-byte alignment. -*/ - - -#ifndef MALLOC_ALIGNMENT -#define MALLOC_ALIGNMENT (2 * SIZE_SZ) -#endif - -/* The corresponding bit mask value */ -#define MALLOC_ALIGN_MASK (MALLOC_ALIGNMENT - 1) - - - -/* - REALLOC_ZERO_BYTES_FREES should be set if a call to - realloc with zero bytes should be the same as a call to free. - Some people think it should. Otherwise, since this malloc - returns a unique pointer for malloc(0), so does realloc(p, 0). -*/ - -/* #define REALLOC_ZERO_BYTES_FREES */ - -/* - TRIM_FASTBINS controls whether free() of a very small chunk can - immediately lead to trimming. Setting to true (1) can reduce memory - footprint, but will almost always slow down programs that use a lot - of small chunks. - - Define this only if you are willing to give up some speed to more - aggressively reduce system-level memory footprint when releasing - memory in programs that use many small chunks. You can get - essentially the same effect by setting MXFAST to 0, but this can - lead to even greater slowdowns in programs using many small chunks. - TRIM_FASTBINS is an in-between compile-time option, that disables - only those chunks bordering topmost memory from being placed in - fastbins. -*/ - -#ifndef TRIM_FASTBINS -#define TRIM_FASTBINS 0 -#endif - - -/* - USE_DL_PREFIX will prefix all public routines with the string 'dl'. - This is necessary when you only want to use this malloc in one part - of a program, using your regular system malloc elsewhere. -*/ - -/* #define USE_DL_PREFIX */ - - -/* - USE_MALLOC_LOCK causes wrapper functions to surround each - callable routine with pthread mutex lock/unlock. - - USE_MALLOC_LOCK forces USE_PUBLIC_MALLOC_WRAPPERS to be defined -*/ - - -/* #define USE_MALLOC_LOCK */ - - -/* - If USE_PUBLIC_MALLOC_WRAPPERS is defined, every public routine is - actually a wrapper function that first calls MALLOC_PREACTION, then - calls the internal routine, and follows it with - MALLOC_POSTACTION. This is needed for locking, but you can also use - this, without USE_MALLOC_LOCK, for purposes of interception, - instrumentation, etc. It is a sad fact that using wrappers often - noticeably degrades performance of malloc-intensive programs. -*/ - -#ifdef USE_MALLOC_LOCK -#define USE_PUBLIC_MALLOC_WRAPPERS -#else -/* #define USE_PUBLIC_MALLOC_WRAPPERS */ -#endif - - -/* - Two-phase name translation. - All of the actual routines are given mangled names. - When wrappers are used, they become the public callable versions. - When DL_PREFIX is used, the callable names are prefixed. -*/ - -#ifndef USE_PUBLIC_MALLOC_WRAPPERS -#define cALLOc public_cALLOc -#define fREe public_fREe -#define cFREe public_cFREe -#define mALLOc public_mALLOc -#define mEMALIGn public_mEMALIGn -#define rEALLOc public_rEALLOc -#define vALLOc public_vALLOc -#define pVALLOc public_pVALLOc -#define mALLINFo public_mALLINFo -#define mALLOPt public_mALLOPt -#define mTRIm public_mTRIm -#define mSTATs public_mSTATs -#define mUSABLe public_mUSABLe -#define iCALLOc public_iCALLOc -#define iCOMALLOc public_iCOMALLOc -#endif - -#ifdef USE_DL_PREFIX -#define public_cALLOc dlcalloc -#define public_fREe dlfree -#define public_cFREe dlcfree -#define public_mALLOc dlmalloc -#define public_mEMALIGn dlmemalign -#define public_rEALLOc dlrealloc -#define public_vALLOc dlvalloc -#define public_pVALLOc dlpvalloc -#define public_mALLINFo dlmallinfo -#define public_mALLOPt dlmallopt -#define public_mTRIm dlmalloc_trim -#define public_mSTATs dlmalloc_stats -#define public_mUSABLe dlmalloc_usable_size -#define public_iCALLOc dlindependent_calloc -#define public_iCOMALLOc dlindependent_comalloc -#else /* USE_DL_PREFIX */ -#define public_cALLOc calloc -#define public_fREe free -#define public_cFREe cfree -#define public_mALLOc malloc -#define public_mEMALIGn memalign -#define public_rEALLOc realloc -#define public_vALLOc valloc -#define public_pVALLOc pvalloc -#define public_mALLINFo mallinfo -#define public_mALLOPt mallopt -#define public_mTRIm malloc_trim -#define public_mSTATs malloc_stats -#define public_mUSABLe malloc_usable_size -#define public_iCALLOc independent_calloc -#define public_iCOMALLOc independent_comalloc -#endif /* USE_DL_PREFIX */ - - -/* - HAVE_MEMCPY should be defined if you are not otherwise using - ANSI STD C, but still have memcpy and memset in your C library - and want to use them in calloc and realloc. Otherwise simple - macro versions are defined below. - - USE_MEMCPY should be defined as 1 if you actually want to - have memset and memcpy called. People report that the macro - versions are faster than libc versions on some systems. - - Even if USE_MEMCPY is set to 1, loops to copy/clear small chunks - (of <= 36 bytes) are manually unrolled in realloc and calloc. -*/ - -#define HAVE_MEMCPY - -#ifndef USE_MEMCPY -#ifdef HAVE_MEMCPY -#define USE_MEMCPY 1 -#else -#define USE_MEMCPY 0 -#endif -#endif - - -#if (__STD_C || defined(HAVE_MEMCPY)) - -#ifdef WIN32 -/* On Win32 memset and memcpy are already declared in windows.h */ -#else -#if __STD_C -void* memset(void*, int, size_t); -void* memcpy(void*, const void*, size_t); -#else -Void_t* memset(); -Void_t* memcpy(); -#endif -#endif -#endif - -/* - MALLOC_FAILURE_ACTION is the action to take before "return 0" when - malloc fails to be able to return memory, either because memory is - exhausted or because of illegal arguments. - - By default, sets errno if running on STD_C platform, else does nothing. -*/ - -#ifndef MALLOC_FAILURE_ACTION -#if __STD_C -#define MALLOC_FAILURE_ACTION \ - errno = ENOMEM; - -#else -#define MALLOC_FAILURE_ACTION -#endif -#endif - -/* - MORECORE-related declarations. By default, rely on sbrk -*/ - - -#ifdef LACKS_UNISTD_H -#if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__) -#if __STD_C -extern Void_t* sbrk(ptrdiff_t); -#else -extern Void_t* sbrk(); -#endif -#endif -#endif - -/* - MORECORE is the name of the routine to call to obtain more memory - from the system. See below for general guidance on writing - alternative MORECORE functions, as well as a version for WIN32 and a - sample version for pre-OSX macos. -*/ - -#ifndef MORECORE -#define MORECORE sbrk -#endif - -/* - MORECORE_FAILURE is the value returned upon failure of MORECORE - as well as mmap. Since it cannot be an otherwise valid memory address, - and must reflect values of standard sys calls, you probably ought not - try to redefine it. -*/ - -#ifndef MORECORE_FAILURE -#define MORECORE_FAILURE (-1) -#endif - -/* - If MORECORE_CONTIGUOUS is true, take advantage of fact that - consecutive calls to MORECORE with positive arguments always return - contiguous increasing addresses. This is true of unix sbrk. Even - if not defined, when regions happen to be contiguous, malloc will - permit allocations spanning regions obtained from different - calls. But defining this when applicable enables some stronger - consistency checks and space efficiencies. -*/ - -#ifndef MORECORE_CONTIGUOUS -#define MORECORE_CONTIGUOUS 1 -#endif - -/* - Define MORECORE_CANNOT_TRIM if your version of MORECORE - cannot release space back to the system when given negative - arguments. This is generally necessary only if you are using - a hand-crafted MORECORE function that cannot handle negative arguments. -*/ - -/* #define MORECORE_CANNOT_TRIM */ - - -/* - Define HAVE_MMAP as true to optionally make malloc() use mmap() to - allocate very large blocks. These will be returned to the - operating system immediately after a free(). Also, if mmap - is available, it is used as a backup strategy in cases where - MORECORE fails to provide space from system. - - This malloc is best tuned to work with mmap for large requests. - If you do not have mmap, operations involving very large chunks (1MB - or so) may be slower than you'd like. -*/ - -#ifndef HAVE_MMAP -#define HAVE_MMAP 1 - -/* - Standard unix mmap using /dev/zero clears memory so calloc doesn't - need to. -*/ - -#ifndef MMAP_CLEARS -#define MMAP_CLEARS 1 -#endif - -#else /* no mmap */ -#ifndef MMAP_CLEARS -#define MMAP_CLEARS 0 -#endif -#endif - - -/* - MMAP_AS_MORECORE_SIZE is the minimum mmap size argument to use if - sbrk fails, and mmap is used as a backup (which is done only if - HAVE_MMAP). The value must be a multiple of page size. This - backup strategy generally applies only when systems have "holes" in - address space, so sbrk cannot perform contiguous expansion, but - there is still space available on system. On systems for which - this is known to be useful (i.e. most linux kernels), this occurs - only when programs allocate huge amounts of memory. Between this, - and the fact that mmap regions tend to be limited, the size should - be large, to avoid too many mmap calls and thus avoid running out - of kernel resources. -*/ - -#ifndef MMAP_AS_MORECORE_SIZE -#define MMAP_AS_MORECORE_SIZE (1024 * 1024) -#endif - -/* - Define HAVE_MREMAP to make realloc() use mremap() to re-allocate - large blocks. This is currently only possible on Linux with - kernel versions newer than 1.3.77. -*/ - -#ifndef HAVE_MREMAP -#ifdef linux -#define HAVE_MREMAP 1 -#else -#define HAVE_MREMAP 0 -#endif - -#endif /* HAVE_MMAP */ - - -/* - The system page size. To the extent possible, this malloc manages - memory from the system in page-size units. Note that this value is - cached during initialization into a field of malloc_state. So even - if malloc_getpagesize is a function, it is only called once. - - The following mechanics for getpagesize were adapted from bsd/gnu - getpagesize.h. If none of the system-probes here apply, a value of - 4096 is used, which should be OK: If they don't apply, then using - the actual value probably doesn't impact performance. -*/ - - -#ifndef malloc_getpagesize - -#ifndef LACKS_UNISTD_H -# include -#endif - -# ifdef _SC_PAGESIZE /* some SVR4 systems omit an underscore */ -# ifndef _SC_PAGE_SIZE -# define _SC_PAGE_SIZE _SC_PAGESIZE -# endif -# endif - -# ifdef _SC_PAGE_SIZE -# define malloc_getpagesize sysconf(_SC_PAGE_SIZE) -# else -# if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE) - extern size_t getpagesize(); -# define malloc_getpagesize getpagesize() -# else -# ifdef WIN32 /* use supplied emulation of getpagesize */ -# define malloc_getpagesize getpagesize() -# else -# ifndef LACKS_SYS_PARAM_H -# include -# endif -# ifdef EXEC_PAGESIZE -# define malloc_getpagesize EXEC_PAGESIZE -# else -# ifdef NBPG -# ifndef CLSIZE -# define malloc_getpagesize NBPG -# else -# define malloc_getpagesize (NBPG * CLSIZE) -# endif -# else -# ifdef NBPC -# define malloc_getpagesize NBPC -# else -# ifdef PAGESIZE -# define malloc_getpagesize PAGESIZE -# else /* just guess */ -# define malloc_getpagesize (4096) -# endif -# endif -# endif -# endif -# endif -# endif -# endif -#endif - -/* - This version of malloc supports the standard SVID/XPG mallinfo - routine that returns a struct containing usage properties and - statistics. It should work on any SVID/XPG compliant system that has - a /usr/include/malloc.h defining struct mallinfo. (If you'd like to - install such a thing yourself, cut out the preliminary declarations - as described above and below and save them in a malloc.h file. But - there's no compelling reason to bother to do this.) - - The main declaration needed is the mallinfo struct that is returned - (by-copy) by mallinfo(). The SVID/XPG malloinfo struct contains a - bunch of field that are not even meaningful in this version of - malloc. These fields are are instead filled by mallinfo() with - other numbers that might be of interest. - - HAVE_USR_INCLUDE_MALLOC_H should be set if you have a - /usr/include/malloc.h file that includes a declaration of struct - mallinfo. If so, it is included; else an SVID2/XPG2 compliant - version is declared below. These must be precisely the same for - mallinfo() to work. The original SVID version of this struct, - defined on most systems with mallinfo, declares all fields as - ints. But some others define as unsigned long. If your system - defines the fields using a type of different width than listed here, - you must #include your system version and #define - HAVE_USR_INCLUDE_MALLOC_H. -*/ - -/* #define HAVE_USR_INCLUDE_MALLOC_H */ - -#ifdef HAVE_USR_INCLUDE_MALLOC_H -#include "/usr/include/malloc.h" -#else - -/* SVID2/XPG mallinfo structure */ - -struct mallinfo { - int arena; /* non-mmapped space allocated from system */ - int ordblks; /* number of free chunks */ - int smblks; /* number of fastbin blocks */ - int hblks; /* number of mmapped regions */ - int hblkhd; /* space in mmapped regions */ - int usmblks; /* maximum total allocated space */ - int fsmblks; /* space available in freed fastbin blocks */ - int uordblks; /* total allocated space */ - int fordblks; /* total free space */ - int keepcost; /* top-most, releasable (via malloc_trim) space */ -}; - -/* - SVID/XPG defines four standard parameter numbers for mallopt, - normally defined in malloc.h. Only one of these (M_MXFAST) is used - in this malloc. The others (M_NLBLKS, M_GRAIN, M_KEEP) don't apply, - so setting them has no effect. But this malloc also supports other - options in mallopt described below. -*/ -#endif - - -/* ---------- description of public routines ------------ */ - -/* - malloc(size_t n) - Returns a pointer to a newly allocated chunk of at least n bytes, or null - if no space is available. Additionally, on failure, errno is - set to ENOMEM on ANSI C systems. - - If n is zero, malloc returns a minumum-sized chunk. (The minimum - size is 16 bytes on most 32bit systems, and 24 or 32 bytes on 64bit - systems.) On most systems, size_t is an unsigned type, so calls - with negative arguments are interpreted as requests for huge amounts - of space, which will often fail. The maximum supported value of n - differs across systems, but is in all cases less than the maximum - representable value of a size_t. -*/ -#if __STD_C -Void_t* public_mALLOc(size_t); -#else -Void_t* public_mALLOc(); -#endif - -/* - free(Void_t* p) - Releases the chunk of memory pointed to by p, that had been previously - allocated using malloc or a related routine such as realloc. - It has no effect if p is null. It can have arbitrary (i.e., bad!) - effects if p has already been freed. - - Unless disabled (using mallopt), freeing very large spaces will - when possible, automatically trigger operations that give - back unused memory to the system, thus reducing program footprint. -*/ -#if __STD_C -void public_fREe(Void_t*); -#else -void public_fREe(); -#endif - -/* - calloc(size_t n_elements, size_t element_size); - Returns a pointer to n_elements * element_size bytes, with all locations - set to zero. -*/ -#if __STD_C -Void_t* public_cALLOc(size_t, size_t); -#else -Void_t* public_cALLOc(); -#endif - -/* - realloc(Void_t* p, size_t n) - Returns a pointer to a chunk of size n that contains the same data - as does chunk p up to the minimum of (n, p's size) bytes, or null - if no space is available. - - The returned pointer may or may not be the same as p. The algorithm - prefers extending p when possible, otherwise it employs the - equivalent of a malloc-copy-free sequence. - - If p is null, realloc is equivalent to malloc. - - If space is not available, realloc returns null, errno is set (if on - ANSI) and p is NOT freed. - - if n is for fewer bytes than already held by p, the newly unused - space is lopped off and freed if possible. Unless the #define - REALLOC_ZERO_BYTES_FREES is set, realloc with a size argument of - zero (re)allocates a minimum-sized chunk. - - Large chunks that were internally obtained via mmap will always - be reallocated using malloc-copy-free sequences unless - the system supports MREMAP (currently only linux). - - The old unix realloc convention of allowing the last-free'd chunk - to be used as an argument to realloc is not supported. -*/ -#if __STD_C -Void_t* public_rEALLOc(Void_t*, size_t); -#else -Void_t* public_rEALLOc(); -#endif - -/* - memalign(size_t alignment, size_t n); - Returns a pointer to a newly allocated chunk of n bytes, aligned - in accord with the alignment argument. - - The alignment argument should be a power of two. If the argument is - not a power of two, the nearest greater power is used. - 8-byte alignment is guaranteed by normal malloc calls, so don't - bother calling memalign with an argument of 8 or less. - - Overreliance on memalign is a sure way to fragment space. -*/ -#if __STD_C -Void_t* public_mEMALIGn(size_t, size_t); -#else -Void_t* public_mEMALIGn(); -#endif - -/* - valloc(size_t n); - Equivalent to memalign(pagesize, n), where pagesize is the page - size of the system. If the pagesize is unknown, 4096 is used. -*/ -#if __STD_C -Void_t* public_vALLOc(size_t); -#else -Void_t* public_vALLOc(); -#endif - - - -/* - mallopt(int parameter_number, int parameter_value) - Sets tunable parameters The format is to provide a - (parameter-number, parameter-value) pair. mallopt then sets the - corresponding parameter to the argument value if it can (i.e., so - long as the value is meaningful), and returns 1 if successful else - 0. SVID/XPG/ANSI defines four standard param numbers for mallopt, - normally defined in malloc.h. Only one of these (M_MXFAST) is used - in this malloc. The others (M_NLBLKS, M_GRAIN, M_KEEP) don't apply, - so setting them has no effect. But this malloc also supports four - other options in mallopt. See below for details. Briefly, supported - parameters are as follows (listed defaults are for "typical" - configurations). - - Symbol param # default allowed param values - M_MXFAST 1 64 0-80 (0 disables fastbins) - M_TRIM_THRESHOLD -1 128*1024 any (-1U disables trimming) - M_TOP_PAD -2 0 any - M_MMAP_THRESHOLD -3 128*1024 any (or 0 if no MMAP support) - M_MMAP_MAX -4 65536 any (0 disables use of mmap) -*/ -#if __STD_C -int public_mALLOPt(int, int); -#else -int public_mALLOPt(); -#endif - - -/* - mallinfo() - Returns (by copy) a struct containing various summary statistics: - - arena: current total non-mmapped bytes allocated from system - ordblks: the number of free chunks - smblks: the number of fastbin blocks (i.e., small chunks that - have been freed but not use resused or consolidated) - hblks: current number of mmapped regions - hblkhd: total bytes held in mmapped regions - usmblks: the maximum total allocated space. This will be greater - than current total if trimming has occurred. - fsmblks: total bytes held in fastbin blocks - uordblks: current total allocated space (normal or mmapped) - fordblks: total free space - keepcost: the maximum number of bytes that could ideally be released - back to system via malloc_trim. ("ideally" means that - it ignores page restrictions etc.) - - Because these fields are ints, but internal bookkeeping may - be kept as longs, the reported values may wrap around zero and - thus be inaccurate. -*/ -#if __STD_C -struct mallinfo public_mALLINFo(void); -#else -struct mallinfo public_mALLINFo(); -#endif - -/* - independent_calloc(size_t n_elements, size_t element_size, Void_t* chunks[]); - - independent_calloc is similar to calloc, but instead of returning a - single cleared space, it returns an array of pointers to n_elements - independent elements that can hold contents of size elem_size, each - of which starts out cleared, and can be independently freed, - realloc'ed etc. The elements are guaranteed to be adjacently - allocated (this is not guaranteed to occur with multiple callocs or - mallocs), which may also improve cache locality in some - applications. - - The "chunks" argument is optional (i.e., may be null, which is - probably the most typical usage). If it is null, the returned array - is itself dynamically allocated and should also be freed when it is - no longer needed. Otherwise, the chunks array must be of at least - n_elements in length. It is filled in with the pointers to the - chunks. - - In either case, independent_calloc returns this pointer array, or - null if the allocation failed. If n_elements is zero and "chunks" - is null, it returns a chunk representing an array with zero elements - (which should be freed if not wanted). - - Each element must be individually freed when it is no longer - needed. If you'd like to instead be able to free all at once, you - should instead use regular calloc and assign pointers into this - space to represent elements. (In this case though, you cannot - independently free elements.) - - independent_calloc simplifies and speeds up implementations of many - kinds of pools. It may also be useful when constructing large data - structures that initially have a fixed number of fixed-sized nodes, - but the number is not known at compile time, and some of the nodes - may later need to be freed. For example: - - struct Node { int item; struct Node* next; }; - - struct Node* build_list() { - struct Node** pool; - int n = read_number_of_nodes_needed(); - if (n <= 0) return 0; - pool = (struct Node**)(independent_calloc(n, sizeof(struct Node), 0); - if (pool == 0) die(); - // organize into a linked list... - struct Node* first = pool[0]; - for (i = 0; i < n-1; ++i) - pool[i]->next = pool[i+1]; - free(pool); // Can now free the array (or not, if it is needed later) - return first; - } -*/ -#if __STD_C -Void_t** public_iCALLOc(size_t, size_t, Void_t**); -#else -Void_t** public_iCALLOc(); -#endif - -/* - independent_comalloc(size_t n_elements, size_t sizes[], Void_t* chunks[]); - - independent_comalloc allocates, all at once, a set of n_elements - chunks with sizes indicated in the "sizes" array. It returns - an array of pointers to these elements, each of which can be - independently freed, realloc'ed etc. The elements are guaranteed to - be adjacently allocated (this is not guaranteed to occur with - multiple callocs or mallocs), which may also improve cache locality - in some applications. - - The "chunks" argument is optional (i.e., may be null). If it is null - the returned array is itself dynamically allocated and should also - be freed when it is no longer needed. Otherwise, the chunks array - must be of at least n_elements in length. It is filled in with the - pointers to the chunks. - - In either case, independent_comalloc returns this pointer array, or - null if the allocation failed. If n_elements is zero and chunks is - null, it returns a chunk representing an array with zero elements - (which should be freed if not wanted). - - Each element must be individually freed when it is no longer - needed. If you'd like to instead be able to free all at once, you - should instead use a single regular malloc, and assign pointers at - particular offsets in the aggregate space. (In this case though, you - cannot independently free elements.) - - independent_comallac differs from independent_calloc in that each - element may have a different size, and also that it does not - automatically clear elements. - - independent_comalloc can be used to speed up allocation in cases - where several structs or objects must always be allocated at the - same time. For example: - - struct Head { ... } - struct Foot { ... } - - void send_message(char* msg) { - int msglen = strlen(msg); - size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) }; - void* chunks[3]; - if (independent_comalloc(3, sizes, chunks) == 0) - die(); - struct Head* head = (struct Head*)(chunks[0]); - char* body = (char*)(chunks[1]); - struct Foot* foot = (struct Foot*)(chunks[2]); - // ... - } - - In general though, independent_comalloc is worth using only for - larger values of n_elements. For small values, you probably won't - detect enough difference from series of malloc calls to bother. - - Overuse of independent_comalloc can increase overall memory usage, - since it cannot reuse existing noncontiguous small chunks that - might be available for some of the elements. -*/ -#if __STD_C -Void_t** public_iCOMALLOc(size_t, size_t*, Void_t**); -#else -Void_t** public_iCOMALLOc(); -#endif - - -/* - pvalloc(size_t n); - Equivalent to valloc(minimum-page-that-holds(n)), that is, - round up n to nearest pagesize. - */ -#if __STD_C -Void_t* public_pVALLOc(size_t); -#else -Void_t* public_pVALLOc(); -#endif - -/* - cfree(Void_t* p); - Equivalent to free(p). - - cfree is needed/defined on some systems that pair it with calloc, - for odd historical reasons (such as: cfree is used in example - code in the first edition of K&R). -*/ -#if __STD_C -void public_cFREe(Void_t*); -#else -void public_cFREe(); -#endif - -/* - malloc_trim(size_t pad); - - If possible, gives memory back to the system (via negative - arguments to sbrk) if there is unused memory at the `high' end of - the malloc pool. You can call this after freeing large blocks of - memory to potentially reduce the system-level memory requirements - of a program. However, it cannot guarantee to reduce memory. Under - some allocation patterns, some large free blocks of memory will be - locked between two used chunks, so they cannot be given back to - the system. - - The `pad' argument to malloc_trim represents the amount of free - trailing space to leave untrimmed. If this argument is zero, - only the minimum amount of memory to maintain internal data - structures will be left (one page or less). Non-zero arguments - can be supplied to maintain enough trailing space to service - future expected allocations without having to re-obtain memory - from the system. - - Malloc_trim returns 1 if it actually released any memory, else 0. - On systems that do not support "negative sbrks", it will always - rreturn 0. -*/ -#if __STD_C -int public_mTRIm(size_t); -#else -int public_mTRIm(); -#endif - -/* - malloc_usable_size(Void_t* p); - - Returns the number of bytes you can actually use in - an allocated chunk, which may be more than you requested (although - often not) due to alignment and minimum size constraints. - You can use this many bytes without worrying about - overwriting other allocated objects. This is not a particularly great - programming practice. malloc_usable_size can be more useful in - debugging and assertions, for example: - - p = malloc(n); - assert(malloc_usable_size(p) >= 256); - -*/ -#if __STD_C -size_t public_mUSABLe(Void_t*); -#else -size_t public_mUSABLe(); -#endif - -/* - malloc_stats(); - Prints on stderr the amount of space obtained from the system (both - via sbrk and mmap), the maximum amount (which may be more than - current if malloc_trim and/or munmap got called), and the current - number of bytes allocated via malloc (or realloc, etc) but not yet - freed. Note that this is the number of bytes allocated, not the - number requested. It will be larger than the number requested - because of alignment and bookkeeping overhead. Because it includes - alignment wastage as being in use, this figure may be greater than - zero even when no user-level chunks are allocated. - - The reported current and maximum system memory can be inaccurate if - a program makes other calls to system memory allocation functions - (normally sbrk) outside of malloc. - - malloc_stats prints only the most commonly interesting statistics. - More information can be obtained by calling mallinfo. - -*/ -#if __STD_C -void public_mSTATs(); -#else -void public_mSTATs(); -#endif - -/* mallopt tuning options */ - -/* - M_MXFAST is the maximum request size used for "fastbins", special bins - that hold returned chunks without consolidating their spaces. This - enables future requests for chunks of the same size to be handled - very quickly, but can increase fragmentation, and thus increase the - overall memory footprint of a program. - - This malloc manages fastbins very conservatively yet still - efficiently, so fragmentation is rarely a problem for values less - than or equal to the default. The maximum supported value of MXFAST - is 80. You wouldn't want it any higher than this anyway. Fastbins - are designed especially for use with many small structs, objects or - strings -- the default handles structs/objects/arrays with sizes up - to 8 4byte fields, or small strings representing words, tokens, - etc. Using fastbins for larger objects normally worsens - fragmentation without improving speed. - - M_MXFAST is set in REQUEST size units. It is internally used in - chunksize units, which adds padding and alignment. You can reduce - M_MXFAST to 0 to disable all use of fastbins. This causes the malloc - algorithm to be a closer approximation of fifo-best-fit in all cases, - not just for larger requests, but will generally cause it to be - slower. -*/ - - -/* M_MXFAST is a standard SVID/XPG tuning option, usually listed in malloc.h */ -#ifndef M_MXFAST -#define M_MXFAST 1 -#endif - -#ifndef DEFAULT_MXFAST -#define DEFAULT_MXFAST 64 -#endif - - -/* - M_TRIM_THRESHOLD is the maximum amount of unused top-most memory - to keep before releasing via malloc_trim in free(). - - Automatic trimming is mainly useful in long-lived programs. - Because trimming via sbrk can be slow on some systems, and can - sometimes be wasteful (in cases where programs immediately - afterward allocate more large chunks) the value should be high - enough so that your overall system performance would improve by - releasing this much memory. - - The trim threshold and the mmap control parameters (see below) - can be traded off with one another. Trimming and mmapping are - two different ways of releasing unused memory back to the - system. Between these two, it is often possible to keep - system-level demands of a long-lived program down to a bare - minimum. For example, in one test suite of sessions measuring - the XF86 X server on Linux, using a trim threshold of 128K and a - mmap threshold of 192K led to near-minimal long term resource - consumption. - - If you are using this malloc in a long-lived program, it should - pay to experiment with these values. As a rough guide, you - might set to a value close to the average size of a process - (program) running on your system. Releasing this much memory - would allow such a process to run in memory. Generally, it's - worth it to tune for trimming rather tham memory mapping when a - program undergoes phases where several large chunks are - allocated and released in ways that can reuse each other's - storage, perhaps mixed with phases where there are no such - chunks at all. And in well-behaved long-lived programs, - controlling release of large blocks via trimming versus mapping - is usually faster. - - However, in most programs, these parameters serve mainly as - protection against the system-level effects of carrying around - massive amounts of unneeded memory. Since frequent calls to - sbrk, mmap, and munmap otherwise degrade performance, the default - parameters are set to relatively high values that serve only as - safeguards. - - The trim value It must be greater than page size to have any useful - effect. To disable trimming completely, you can set to - (unsigned long)(-1) - - Trim settings interact with fastbin (MXFAST) settings: Unless - TRIM_FASTBINS is defined, automatic trimming never takes place upon - freeing a chunk with size less than or equal to MXFAST. Trimming is - instead delayed until subsequent freeing of larger chunks. However, - you can still force an attempted trim by calling malloc_trim. - - Also, trimming is not generally possible in cases where - the main arena is obtained via mmap. - - Note that the trick some people use of mallocing a huge space and - then freeing it at program startup, in an attempt to reserve system - memory, doesn't have the intended effect under automatic trimming, - since that memory will immediately be returned to the system. -*/ - -#define M_TRIM_THRESHOLD -1 - -#ifndef DEFAULT_TRIM_THRESHOLD -#define DEFAULT_TRIM_THRESHOLD (128 * 1024) -#endif - -/* - M_TOP_PAD is the amount of extra `padding' space to allocate or - retain whenever sbrk is called. It is used in two ways internally: - - * When sbrk is called to extend the top of the arena to satisfy - a new malloc request, this much padding is added to the sbrk - request. - - * When malloc_trim is called automatically from free(), - it is used as the `pad' argument. - - In both cases, the actual amount of padding is rounded - so that the end of the arena is always a system page boundary. - - The main reason for using padding is to avoid calling sbrk so - often. Having even a small pad greatly reduces the likelihood - that nearly every malloc request during program start-up (or - after trimming) will invoke sbrk, which needlessly wastes - time. - - Automatic rounding-up to page-size units is normally sufficient - to avoid measurable overhead, so the default is 0. However, in - systems where sbrk is relatively slow, it can pay to increase - this value, at the expense of carrying around more memory than - the program needs. -*/ - -#define M_TOP_PAD -2 - -#ifndef DEFAULT_TOP_PAD -#define DEFAULT_TOP_PAD (0) -#endif - -/* - M_MMAP_THRESHOLD is the request size threshold for using mmap() - to service a request. Requests of at least this size that cannot - be allocated using already-existing space will be serviced via mmap. - (If enough normal freed space already exists it is used instead.) - - Using mmap segregates relatively large chunks of memory so that - they can be individually obtained and released from the host - system. A request serviced through mmap is never reused by any - other request (at least not directly; the system may just so - happen to remap successive requests to the same locations). - - Segregating space in this way has the benefits that: - - 1. Mmapped space can ALWAYS be individually released back - to the system, which helps keep the system level memory - demands of a long-lived program low. - 2. Mapped memory can never become `locked' between - other chunks, as can happen with normally allocated chunks, which - means that even trimming via malloc_trim would not release them. - 3. On some systems with "holes" in address spaces, mmap can obtain - memory that sbrk cannot. - - However, it has the disadvantages that: - - 1. The space cannot be reclaimed, consolidated, and then - used to service later requests, as happens with normal chunks. - 2. It can lead to more wastage because of mmap page alignment - requirements - 3. It causes malloc performance to be more dependent on host - system memory management support routines which may vary in - implementation quality and may impose arbitrary - limitations. Generally, servicing a request via normal - malloc steps is faster than going through a system's mmap. - - The advantages of mmap nearly always outweigh disadvantages for - "large" chunks, but the value of "large" varies across systems. The - default is an empirically derived value that works well in most - systems. -*/ - -#define M_MMAP_THRESHOLD -3 - -#ifndef DEFAULT_MMAP_THRESHOLD -#define DEFAULT_MMAP_THRESHOLD (128 * 1024) -#endif - -/* - M_MMAP_MAX is the maximum number of requests to simultaneously - service using mmap. This parameter exists because -. Some systems have a limited number of internal tables for - use by mmap, and using more than a few of them may degrade - performance. - - The default is set to a value that serves only as a safeguard. - Setting to 0 disables use of mmap for servicing large requests. If - HAVE_MMAP is not set, the default value is 0, and attempts to set it - to non-zero values in mallopt will fail. -*/ - -#define M_MMAP_MAX -4 - -#ifndef DEFAULT_MMAP_MAX -#if HAVE_MMAP -#define DEFAULT_MMAP_MAX (65536) -#else -#define DEFAULT_MMAP_MAX (0) -#endif -#endif - -#ifdef __cplusplus -}; /* end of extern "C" */ -#endif - -/* - ======================================================================== - To make a fully customizable malloc.h header file, cut everything - above this line, put into file malloc.h, edit to suit, and #include it - on the next line, as well as in programs that use this malloc. - ======================================================================== -*/ - -/* #include "malloc.h" */ - -/* --------------------- public wrappers ---------------------- */ - -#ifdef USE_PUBLIC_MALLOC_WRAPPERS - -/* Declare all routines as internal */ -#if __STD_C -static Void_t* mALLOc(size_t); -static void fREe(Void_t*); -static Void_t* rEALLOc(Void_t*, size_t); -static Void_t* mEMALIGn(size_t, size_t); -static Void_t* vALLOc(size_t); -static Void_t* pVALLOc(size_t); -static Void_t* cALLOc(size_t, size_t); -static Void_t** iCALLOc(size_t, size_t, Void_t**); -static Void_t** iCOMALLOc(size_t, size_t*, Void_t**); -static void cFREe(Void_t*); -static int mTRIm(size_t); -static size_t mUSABLe(Void_t*); -static void mSTATs(); -static int mALLOPt(int, int); -static struct mallinfo mALLINFo(void); -#else -static Void_t* mALLOc(); -static void fREe(); -static Void_t* rEALLOc(); -static Void_t* mEMALIGn(); -static Void_t* vALLOc(); -static Void_t* pVALLOc(); -static Void_t* cALLOc(); -static Void_t** iCALLOc(); -static Void_t** iCOMALLOc(); -static void cFREe(); -static int mTRIm(); -static size_t mUSABLe(); -static void mSTATs(); -static int mALLOPt(); -static struct mallinfo mALLINFo(); -#endif - -/* - MALLOC_PREACTION and MALLOC_POSTACTION should be - defined to return 0 on success, and nonzero on failure. - The return value of MALLOC_POSTACTION is currently ignored - in wrapper functions since there is no reasonable default - action to take on failure. -*/ - - -#ifdef USE_MALLOC_LOCK - -#ifdef WIN32 - -static int mALLOC_MUTEx; -#define MALLOC_PREACTION slwait(&mALLOC_MUTEx) -#define MALLOC_POSTACTION slrelease(&mALLOC_MUTEx) - -#else - -#include - -static pthread_mutex_t mALLOC_MUTEx = PTHREAD_MUTEX_INITIALIZER; - -#define MALLOC_PREACTION pthread_mutex_lock(&mALLOC_MUTEx) -#define MALLOC_POSTACTION pthread_mutex_unlock(&mALLOC_MUTEx) - -#endif /* USE_MALLOC_LOCK */ - -#else - -/* Substitute anything you like for these */ - -#define MALLOC_PREACTION (0) -#define MALLOC_POSTACTION (0) - -#endif - -Void_t* public_mALLOc(size_t bytes) { - Void_t* m; - if (MALLOC_PREACTION != 0) { - return 0; - } - m = mALLOc(bytes); - if (MALLOC_POSTACTION != 0) { - } - return m; -} - -void public_fREe(Void_t* m) { - if (MALLOC_PREACTION != 0) { - return; - } - fREe(m); - if (MALLOC_POSTACTION != 0) { - } -} - -Void_t* public_rEALLOc(Void_t* m, size_t bytes) { - if (MALLOC_PREACTION != 0) { - return 0; - } - m = rEALLOc(m, bytes); - if (MALLOC_POSTACTION != 0) { - } - return m; -} - -Void_t* public_mEMALIGn(size_t alignment, size_t bytes) { - Void_t* m; - if (MALLOC_PREACTION != 0) { - return 0; - } - m = mEMALIGn(alignment, bytes); - if (MALLOC_POSTACTION != 0) { - } - return m; -} - -Void_t* public_vALLOc(size_t bytes) { - Void_t* m; - if (MALLOC_PREACTION != 0) { - return 0; - } - m = vALLOc(bytes); - if (MALLOC_POSTACTION != 0) { - } - return m; -} - -Void_t* public_pVALLOc(size_t bytes) { - Void_t* m; - if (MALLOC_PREACTION != 0) { - return 0; - } - m = pVALLOc(bytes); - if (MALLOC_POSTACTION != 0) { - } - return m; -} - -Void_t* public_cALLOc(size_t n, size_t elem_size) { - Void_t* m; - if (MALLOC_PREACTION != 0) { - return 0; - } - m = cALLOc(n, elem_size); - if (MALLOC_POSTACTION != 0) { - } - return m; -} - - -Void_t** public_iCALLOc(size_t n, size_t elem_size, Void_t** chunks) { - Void_t** m; - if (MALLOC_PREACTION != 0) { - return 0; - } - m = iCALLOc(n, elem_size, chunks); - if (MALLOC_POSTACTION != 0) { - } - return m; -} - -Void_t** public_iCOMALLOc(size_t n, size_t sizes[], Void_t** chunks) { - Void_t** m; - if (MALLOC_PREACTION != 0) { - return 0; - } - m = iCOMALLOc(n, sizes, chunks); - if (MALLOC_POSTACTION != 0) { - } - return m; -} - -void public_cFREe(Void_t* m) { - if (MALLOC_PREACTION != 0) { - return; - } - cFREe(m); - if (MALLOC_POSTACTION != 0) { - } -} - -int public_mTRIm(size_t s) { - int result; - if (MALLOC_PREACTION != 0) { - return 0; - } - result = mTRIm(s); - if (MALLOC_POSTACTION != 0) { - } - return result; -} - -size_t public_mUSABLe(Void_t* m) { - size_t result; - if (MALLOC_PREACTION != 0) { - return 0; - } - result = mUSABLe(m); - if (MALLOC_POSTACTION != 0) { - } - return result; -} - -void public_mSTATs() { - if (MALLOC_PREACTION != 0) { - return; - } - mSTATs(); - if (MALLOC_POSTACTION != 0) { - } -} - -struct mallinfo public_mALLINFo() { - struct mallinfo m; - if (MALLOC_PREACTION != 0) { - struct mallinfo nm = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; - return nm; - } - m = mALLINFo(); - if (MALLOC_POSTACTION != 0) { - } - return m; -} - -int public_mALLOPt(int p, int v) { - int result; - if (MALLOC_PREACTION != 0) { - return 0; - } - result = mALLOPt(p, v); - if (MALLOC_POSTACTION != 0) { - } - return result; -} - -#endif - - - -/* ------------- Optional versions of memcopy ---------------- */ - - -#if USE_MEMCPY - -/* - Note: memcpy is ONLY invoked with non-overlapping regions, - so the (usually slower) memmove is not needed. -*/ - -#define MALLOC_COPY(dest, src, nbytes) memcpy(dest, src, nbytes) -#define MALLOC_ZERO(dest, nbytes) memset(dest, 0, nbytes) - -#else /* !USE_MEMCPY */ - -/* Use Duff's device for good zeroing/copying performance. */ - -#define MALLOC_ZERO(charp, nbytes) \ -do { \ - INTERNAL_SIZE_T* mzp = (INTERNAL_SIZE_T*)(charp); \ - unsigned long mctmp = (nbytes)/sizeof(INTERNAL_SIZE_T); \ - long mcn; \ - if (mctmp < 8) mcn = 0; else { mcn = (mctmp-1)/8; mctmp %= 8; } \ - switch (mctmp) { \ - case 0: for(;;) { *mzp++ = 0; \ - case 7: *mzp++ = 0; \ - case 6: *mzp++ = 0; \ - case 5: *mzp++ = 0; \ - case 4: *mzp++ = 0; \ - case 3: *mzp++ = 0; \ - case 2: *mzp++ = 0; \ - case 1: *mzp++ = 0; if(mcn <= 0) break; mcn--; } \ - } \ -} while(0) - -define MALLOC_COPY(dest,src,nbytes) \ -do { \ - INTERNAL_SIZE_T* mcsrc = (INTERNAL_SIZE_T*) src; \ - INTERNAL_SIZE_T* mcdst = (INTERNAL_SIZE_T*) dest; \ - unsigned long mctmp = (nbytes)/sizeof(INTERNAL_SIZE_T); \ - long mcn; \ - if (mctmp < 8) mcn = 0; else { mcn = (mctmp-1)/8; mctmp %= 8; } \ - switch (mctmp) { \ - case 0: for(;;) { *mcdst++ = *mcsrc++; \ - case 7: *mcdst++ = *mcsrc++; \ - case 6: *mcdst++ = *mcsrc++; \ - case 5: *mcdst++ = *mcsrc++; \ - case 4: *mcdst++ = *mcsrc++; \ - case 3: *mcdst++ = *mcsrc++; \ - case 2: *mcdst++ = *mcsrc++; \ - case 1: *mcdst++ = *mcsrc++; if(mcn <= 0) break; mcn--; } \ - } \ -} while(0) - -#endif - -/* ------------------ MMAP support ------------------ */ - - -#if HAVE_MMAP - -#include -#ifndef LACKS_SYS_MMAN_H -#include -#endif - -#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON) -#define MAP_ANONYMOUS MAP_ANON -#endif - -/* - Nearly all versions of mmap support MAP_ANONYMOUS, - so the following is unlikely to be needed, but is - supplied just in case. -*/ - -#ifndef MAP_ANONYMOUS - -static int dev_zero_fd = -1; /* Cached file descriptor for /dev/zero. */ - -#define MMAP(addr, size, prot, flags) ((dev_zero_fd < 0) ? \ - (dev_zero_fd = open("/dev/zero", O_RDWR), \ - mmap((addr), (size), (prot), (flags), dev_zero_fd, 0)) : \ - mmap((addr), (size), (prot), (flags), dev_zero_fd, 0)) - -#else - -#define MMAP(addr, size, prot, flags) \ - (mmap((addr), (size), (prot), (flags)|MAP_ANONYMOUS, -1, 0)) - -#endif - - -#endif /* HAVE_MMAP */ - - -/* - ----------------------- Chunk representations ----------------------- -*/ - - -/* - This struct declaration is misleading (but accurate and necessary). - It declares a "view" into memory allowing access to necessary - fields at known offsets from a given base. See explanation below. -*/ - -struct malloc_chunk { - - INTERNAL_SIZE_T prev_size; /* Size of previous chunk (if free). */ - INTERNAL_SIZE_T size; /* Size in bytes, including overhead. */ - - struct malloc_chunk* fd; /* double links -- used only if free. */ - struct malloc_chunk* bk; -}; - - -typedef struct malloc_chunk* mchunkptr; - -/* - malloc_chunk details: - - (The following includes lightly edited explanations by Colin Plumb.) - - Chunks of memory are maintained using a `boundary tag' method as - described in e.g., Knuth or Standish. (See the paper by Paul - Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a - survey of such techniques.) Sizes of free chunks are stored both - in the front of each chunk and at the end. This makes - consolidating fragmented chunks into bigger chunks very fast. The - size fields also hold bits representing whether chunks are free or - in use. - - An allocated chunk looks like this: - - - chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Size of previous chunk, if allocated | | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Size of chunk, in bytes |P| - mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | User data starts here... . - . . - . (malloc_usable_space() bytes) . - . | -nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Size of chunk | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - - - Where "chunk" is the front of the chunk for the purpose of most of - the malloc code, but "mem" is the pointer that is returned to the - user. "Nextchunk" is the beginning of the next contiguous chunk. - - Chunks always begin on even word boundries, so the mem portion - (which is returned to the user) is also on an even word boundary, and - thus at least double-word aligned. - - Free chunks are stored in circular doubly-linked lists, and look like this: - - chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Size of previous chunk | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - `head:' | Size of chunk, in bytes |P| - mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Forward pointer to next chunk in list | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Back pointer to previous chunk in list | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Unused space (may be 0 bytes long) . - . . - . | -nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - `foot:' | Size of chunk, in bytes | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - - The P (PREV_INUSE) bit, stored in the unused low-order bit of the - chunk size (which is always a multiple of two words), is an in-use - bit for the *previous* chunk. If that bit is *clear*, then the - word before the current chunk size contains the previous chunk - size, and can be used to find the front of the previous chunk. - The very first chunk allocated always has this bit set, - preventing access to non-existent (or non-owned) memory. If - prev_inuse is set for any given chunk, then you CANNOT determine - the size of the previous chunk, and might even get a memory - addressing fault when trying to do so. - - Note that the `foot' of the current chunk is actually represented - as the prev_size of the NEXT chunk. This makes it easier to - deal with alignments etc but can be very confusing when trying - to extend or adapt this code. - - The two exceptions to all this are - - 1. The special chunk `top' doesn't bother using the - trailing size field since there is no next contiguous chunk - that would have to index off it. After initialization, `top' - is forced to always exist. If it would become less than - MINSIZE bytes long, it is replenished. - - 2. Chunks allocated via mmap, which have the second-lowest-order - bit (IS_MMAPPED) set in their size fields. Because they are - allocated one-by-one, each must contain its own trailing size field. - -*/ - -/* - ---------- Size and alignment checks and conversions ---------- -*/ - -/* conversion from malloc headers to user pointers, and back */ - -#define chunk2mem(p) ((Void_t*)((char*)(p) + 2*SIZE_SZ)) -#define mem2chunk(mem) ((mchunkptr)((char*)(mem) - 2*SIZE_SZ)) - -/* The smallest possible chunk */ -#define MIN_CHUNK_SIZE (sizeof(struct malloc_chunk)) - -/* The smallest size we can malloc is an aligned minimal chunk */ - -#define MINSIZE \ - (unsigned long)(((MIN_CHUNK_SIZE+MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK)) - -/* Check if m has acceptable alignment */ - -#define aligned_OK(m) (((unsigned long)((m)) & (MALLOC_ALIGN_MASK)) == 0) - - -/* - Check if a request is so large that it would wrap around zero when - padded and aligned. To simplify some other code, the bound is made - low enough so that adding MINSIZE will also not wrap around sero. -*/ - -#define REQUEST_OUT_OF_RANGE(req) \ - ((unsigned long)(req) >= \ - (unsigned long)(INTERNAL_SIZE_T)(-2 * MINSIZE)) - -/* pad request bytes into a usable size -- internal version */ - -#define request2size(req) \ - (((req) + SIZE_SZ + MALLOC_ALIGN_MASK < MINSIZE) ? \ - MINSIZE : \ - ((req) + SIZE_SZ + MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK) - -/* Same, except also perform argument check */ - -#define checked_request2size(req, sz) \ - if (REQUEST_OUT_OF_RANGE(req)) { \ - MALLOC_FAILURE_ACTION; \ - return 0; \ - } \ - (sz) = request2size(req); - -/* - --------------- Physical chunk operations --------------- -*/ - - -/* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */ -#define PREV_INUSE 0x1 - -/* extract inuse bit of previous chunk */ -#define prev_inuse(p) ((p)->size & PREV_INUSE) - - -/* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */ -#define IS_MMAPPED 0x2 - -/* check for mmap()'ed chunk */ -#define chunk_is_mmapped(p) ((p)->size & IS_MMAPPED) - -/* - Bits to mask off when extracting size - - Note: IS_MMAPPED is intentionally not masked off from size field in - macros for which mmapped chunks should never be seen. This should - cause helpful core dumps to occur if it is tried by accident by - people extending or adapting this malloc. -*/ -#define SIZE_BITS (PREV_INUSE|IS_MMAPPED) - -/* Get size, ignoring use bits */ -#define chunksize(p) ((p)->size & ~(SIZE_BITS)) - - -/* Ptr to next physical malloc_chunk. */ -#define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->size & ~PREV_INUSE) )) - -/* Ptr to previous physical malloc_chunk */ -#define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_size) )) - -/* Treat space at ptr + offset as a chunk */ -#define chunk_at_offset(p, s) ((mchunkptr)(((char*)(p)) + (s))) - -/* extract p's inuse bit */ -#define inuse(p)\ -((((mchunkptr)(((char*)(p))+((p)->size & ~PREV_INUSE)))->size) & PREV_INUSE) - -/* set/clear chunk as being inuse without otherwise disturbing */ -#define set_inuse(p)\ -((mchunkptr)(((char*)(p)) + ((p)->size & ~PREV_INUSE)))->size |= PREV_INUSE - -#define clear_inuse(p)\ -((mchunkptr)(((char*)(p)) + ((p)->size & ~PREV_INUSE)))->size &= ~(PREV_INUSE) - - -/* check/set/clear inuse bits in known places */ -#define inuse_bit_at_offset(p, s)\ - (((mchunkptr)(((char*)(p)) + (s)))->size & PREV_INUSE) - -#define set_inuse_bit_at_offset(p, s)\ - (((mchunkptr)(((char*)(p)) + (s)))->size |= PREV_INUSE) - -#define clear_inuse_bit_at_offset(p, s)\ - (((mchunkptr)(((char*)(p)) + (s)))->size &= ~(PREV_INUSE)) - - -/* Set size at head, without disturbing its use bit */ -#define set_head_size(p, s) ((p)->size = (((p)->size & PREV_INUSE) | (s))) - -/* Set size/use field */ -#define set_head(p, s) ((p)->size = (s)) - -/* Set size at footer (only when chunk is not in use) */ -#define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_size = (s)) - - -/* - -------------------- Internal data structures -------------------- - - All internal state is held in an instance of malloc_state defined - below. There are no other static variables, except in two optional - cases: - * If USE_MALLOC_LOCK is defined, the mALLOC_MUTEx declared above. - * If HAVE_MMAP is true, but mmap doesn't support - MAP_ANONYMOUS, a dummy file descriptor for mmap. - - Beware of lots of tricks that minimize the total bookkeeping space - requirements. The result is a little over 1K bytes (for 4byte - pointers and size_t.) -*/ - -/* - Bins - - An array of bin headers for free chunks. Each bin is doubly - linked. The bins are approximately proportionally (log) spaced. - There are a lot of these bins (128). This may look excessive, but - works very well in practice. Most bins hold sizes that are - unusual as malloc request sizes, but are more usual for fragments - and consolidated sets of chunks, which is what these bins hold, so - they can be found quickly. All procedures maintain the invariant - that no consolidated chunk physically borders another one, so each - chunk in a list is known to be preceeded and followed by either - inuse chunks or the ends of memory. - - Chunks in bins are kept in size order, with ties going to the - approximately least recently used chunk. Ordering isn't needed - for the small bins, which all contain the same-sized chunks, but - facilitates best-fit allocation for larger chunks. These lists - are just sequential. Keeping them in order almost never requires - enough traversal to warrant using fancier ordered data - structures. - - Chunks of the same size are linked with the most - recently freed at the front, and allocations are taken from the - back. This results in LRU (FIFO) allocation order, which tends - to give each chunk an equal opportunity to be consolidated with - adjacent freed chunks, resulting in larger free chunks and less - fragmentation. - - To simplify use in double-linked lists, each bin header acts - as a malloc_chunk. This avoids special-casing for headers. - But to conserve space and improve locality, we allocate - only the fd/bk pointers of bins, and then use repositioning tricks - to treat these as the fields of a malloc_chunk*. -*/ - -typedef struct malloc_chunk* mbinptr; - -/* addressing -- note that bin_at(0) does not exist */ -#define bin_at(m, i) ((mbinptr)((char*)&((m)->bins[(i)<<1]) - (SIZE_SZ<<1))) - -/* analog of ++bin */ -#define next_bin(b) ((mbinptr)((char*)(b) + (sizeof(mchunkptr)<<1))) - -/* Reminders about list directionality within bins */ -#define first(b) ((b)->fd) -#define last(b) ((b)->bk) - -/* Take a chunk off a bin list */ -#define unlink(P, BK, FD) { \ - FD = P->fd; \ - BK = P->bk; \ - FD->bk = BK; \ - BK->fd = FD; \ -} - -/* - Indexing - - Bins for sizes < 512 bytes contain chunks of all the same size, spaced - 8 bytes apart. Larger bins are approximately logarithmically spaced: - - 64 bins of size 8 - 32 bins of size 64 - 16 bins of size 512 - 8 bins of size 4096 - 4 bins of size 32768 - 2 bins of size 262144 - 1 bin of size what's left - - There is actually a little bit of slop in the numbers in bin_index - for the sake of speed. This makes no difference elsewhere. - - The bins top out around 1MB because we expect to service large - requests via mmap. -*/ - -#define NBINS 128 -#define NSMALLBINS 64 -#define SMALLBIN_WIDTH 8 -#define MIN_LARGE_SIZE 512 - -#define in_smallbin_range(sz) \ - ((unsigned long)(sz) < (unsigned long)MIN_LARGE_SIZE) - -#define smallbin_index(sz) (((unsigned)(sz)) >> 3) - -#define largebin_index(sz) \ -(((((unsigned long)(sz)) >> 6) <= 32)? 56 + (((unsigned long)(sz)) >> 6): \ - ((((unsigned long)(sz)) >> 9) <= 20)? 91 + (((unsigned long)(sz)) >> 9): \ - ((((unsigned long)(sz)) >> 12) <= 10)? 110 + (((unsigned long)(sz)) >> 12): \ - ((((unsigned long)(sz)) >> 15) <= 4)? 119 + (((unsigned long)(sz)) >> 15): \ - ((((unsigned long)(sz)) >> 18) <= 2)? 124 + (((unsigned long)(sz)) >> 18): \ - 126) - -#define bin_index(sz) \ - ((in_smallbin_range(sz)) ? smallbin_index(sz) : largebin_index(sz)) - - -/* - Unsorted chunks - - All remainders from chunk splits, as well as all returned chunks, - are first placed in the "unsorted" bin. They are then placed - in regular bins after malloc gives them ONE chance to be used before - binning. So, basically, the unsorted_chunks list acts as a queue, - with chunks being placed on it in free (and malloc_consolidate), - and taken off (to be either used or placed in bins) in malloc. -*/ - -/* The otherwise unindexable 1-bin is used to hold unsorted chunks. */ -#define unsorted_chunks(M) (bin_at(M, 1)) - -/* - Top - - The top-most available chunk (i.e., the one bordering the end of - available memory) is treated specially. It is never included in - any bin, is used only if no other chunk is available, and is - released back to the system if it is very large (see - M_TRIM_THRESHOLD). Because top initially - points to its own bin with initial zero size, thus forcing - extension on the first malloc request, we avoid having any special - code in malloc to check whether it even exists yet. But we still - need to do so when getting memory from system, so we make - initial_top treat the bin as a legal but unusable chunk during the - interval between initialization and the first call to - sYSMALLOc. (This is somewhat delicate, since it relies on - the 2 preceding words to be zero during this interval as well.) -*/ - -/* Conveniently, the unsorted bin can be used as dummy top on first call */ -#define initial_top(M) (unsorted_chunks(M)) - -/* - Binmap - - To help compensate for the large number of bins, a one-level index - structure is used for bin-by-bin searching. `binmap' is a - bitvector recording whether bins are definitely empty so they can - be skipped over during during traversals. The bits are NOT always - cleared as soon as bins are empty, but instead only - when they are noticed to be empty during traversal in malloc. -*/ - -/* Conservatively use 32 bits per map word, even if on 64bit system */ -#define BINMAPSHIFT 5 -#define BITSPERMAP (1U << BINMAPSHIFT) -#define BINMAPSIZE (NBINS / BITSPERMAP) - -#define idx2block(i) ((i) >> BINMAPSHIFT) -#define idx2bit(i) ((1U << ((i) & ((1U << BINMAPSHIFT)-1)))) - -#define mark_bin(m,i) ((m)->binmap[idx2block(i)] |= idx2bit(i)) -#define unmark_bin(m,i) ((m)->binmap[idx2block(i)] &= ~(idx2bit(i))) -#define get_binmap(m,i) ((m)->binmap[idx2block(i)] & idx2bit(i)) - -/* - Fastbins - - An array of lists holding recently freed small chunks. Fastbins - are not doubly linked. It is faster to single-link them, and - since chunks are never removed from the middles of these lists, - double linking is not necessary. Also, unlike regular bins, they - are not even processed in FIFO order (they use faster LIFO) since - ordering doesn't much matter in the transient contexts in which - fastbins are normally used. - - Chunks in fastbins keep their inuse bit set, so they cannot - be consolidated with other free chunks. malloc_consolidate - releases all chunks in fastbins and consolidates them with - other free chunks. -*/ - -typedef struct malloc_chunk* mfastbinptr; - -/* offset 2 to use otherwise unindexable first 2 bins */ -#define fastbin_index(sz) ((((unsigned int)(sz)) >> 3) - 2) - -/* The maximum fastbin request size we support */ -#define MAX_FAST_SIZE 80 - -#define NFASTBINS (fastbin_index(request2size(MAX_FAST_SIZE))+1) - -/* - FASTBIN_CONSOLIDATION_THRESHOLD is the size of a chunk in free() - that triggers automatic consolidation of possibly-surrounding - fastbin chunks. This is a heuristic, so the exact value should not - matter too much. It is defined at half the default trim threshold as a - compromise heuristic to only attempt consolidation if it is likely - to lead to trimming. However, it is not dynamically tunable, since - consolidation reduces fragmentation surrounding loarge chunks even - if trimming is not used. -*/ - -#define FASTBIN_CONSOLIDATION_THRESHOLD (65536UL) - -/* - Since the lowest 2 bits in max_fast don't matter in size comparisons, - they are used as flags. -*/ - -/* - FASTCHUNKS_BIT held in max_fast indicates that there are probably - some fastbin chunks. It is set true on entering a chunk into any - fastbin, and cleared only in malloc_consolidate. - - The truth value is inverted so that have_fastchunks will be true - upon startup (since statics are zero-filled), simplifying - initialization checks. -*/ - -#define FASTCHUNKS_BIT (1U) - -#define have_fastchunks(M) (((M)->max_fast & FASTCHUNKS_BIT) == 0) -#define clear_fastchunks(M) ((M)->max_fast |= FASTCHUNKS_BIT) -#define set_fastchunks(M) ((M)->max_fast &= ~FASTCHUNKS_BIT) - -/* - NONCONTIGUOUS_BIT indicates that MORECORE does not return contiguous - regions. Otherwise, contiguity is exploited in merging together, - when possible, results from consecutive MORECORE calls. - - The initial value comes from MORECORE_CONTIGUOUS, but is - changed dynamically if mmap is ever used as an sbrk substitute. -*/ - -#define NONCONTIGUOUS_BIT (2U) - -#define contiguous(M) (((M)->max_fast & NONCONTIGUOUS_BIT) == 0) -#define noncontiguous(M) (((M)->max_fast & NONCONTIGUOUS_BIT) != 0) -#define set_noncontiguous(M) ((M)->max_fast |= NONCONTIGUOUS_BIT) -#define set_contiguous(M) ((M)->max_fast &= ~NONCONTIGUOUS_BIT) - -/* - Set value of max_fast. - Use impossibly small value if 0. - Precondition: there are no existing fastbin chunks. - Setting the value clears fastchunk bit but preserves noncontiguous bit. -*/ - -#define set_max_fast(M, s) \ - (M)->max_fast = (((s) == 0)? SMALLBIN_WIDTH: request2size(s)) | \ - FASTCHUNKS_BIT | \ - ((M)->max_fast & NONCONTIGUOUS_BIT) - - -/* - ----------- Internal state representation and initialization ----------- -*/ - -struct malloc_state { - - /* The maximum chunk size to be eligible for fastbin */ - INTERNAL_SIZE_T max_fast; /* low 2 bits used as flags */ - - /* Fastbins */ - mfastbinptr fastbins[NFASTBINS]; - - /* Base of the topmost chunk -- not otherwise kept in a bin */ - mchunkptr top; - - /* The remainder from the most recent split of a small request */ - mchunkptr last_remainder; - - /* Normal bins packed as described above */ - mchunkptr bins[NBINS * 2]; - - /* Bitmap of bins */ - unsigned int binmap[BINMAPSIZE]; - - /* Tunable parameters */ - unsigned long trim_threshold; - INTERNAL_SIZE_T top_pad; - INTERNAL_SIZE_T mmap_threshold; - - /* Memory map support */ - int n_mmaps; - int n_mmaps_max; - int max_n_mmaps; - - /* Cache malloc_getpagesize */ - unsigned int pagesize; - - /* Statistics */ - INTERNAL_SIZE_T mmapped_mem; - INTERNAL_SIZE_T sbrked_mem; - INTERNAL_SIZE_T max_sbrked_mem; - INTERNAL_SIZE_T max_mmapped_mem; - INTERNAL_SIZE_T max_total_mem; -}; - -typedef struct malloc_state *mstate; - -/* - There is exactly one instance of this struct in this malloc. - If you are adapting this malloc in a way that does NOT use a static - malloc_state, you MUST explicitly zero-fill it before using. This - malloc relies on the property that malloc_state is initialized to - all zeroes (as is true of C statics). -*/ - -static struct malloc_state av_; /* never directly referenced */ - -/* - All uses of av_ are via get_malloc_state(). - At most one "call" to get_malloc_state is made per invocation of - the public versions of malloc and free, but other routines - that in turn invoke malloc and/or free may call more then once. - Also, it is called in check* routines if DEBUG is set. -*/ - -#define get_malloc_state() (&(av_)) - -/* - Initialize a malloc_state struct. - - This is called only from within malloc_consolidate, which needs - be called in the same contexts anyway. It is never called directly - outside of malloc_consolidate because some optimizing compilers try - to inline it at all call points, which turns out not to be an - optimization at all. (Inlining it in malloc_consolidate is fine though.) -*/ - -#if __STD_C -static void malloc_init_state(mstate av) -#else -static void malloc_init_state(av) mstate av; -#endif -{ - int i; - mbinptr bin; - - /* Establish circular links for normal bins */ - for (i = 1; i < NBINS; ++i) { - bin = bin_at(av,i); - bin->fd = bin->bk = bin; - } - - av->top_pad = DEFAULT_TOP_PAD; - av->n_mmaps_max = DEFAULT_MMAP_MAX; - av->mmap_threshold = DEFAULT_MMAP_THRESHOLD; - av->trim_threshold = DEFAULT_TRIM_THRESHOLD; - -#if !MORECORE_CONTIGUOUS - set_noncontiguous(av); -#endif - - set_max_fast(av, DEFAULT_MXFAST); - - av->top = initial_top(av); - av->pagesize = malloc_getpagesize; -} - -/* - Other internal utilities operating on mstates -*/ - -#if __STD_C -static Void_t* sYSMALLOc(INTERNAL_SIZE_T, mstate); -static int sYSTRIm(size_t, mstate); -static void malloc_consolidate(mstate); -static Void_t** iALLOc(size_t, size_t*, int, Void_t**); -#else -static Void_t* sYSMALLOc(); -static int sYSTRIm(); -static void malloc_consolidate(); -static Void_t** iALLOc(); -#endif - -/* - Debugging support - - These routines make a number of assertions about the states - of data structures that should be true at all times. If any - are not true, it's very likely that a user program has somehow - trashed memory. (It's also possible that there is a coding error - in malloc. In which case, please report it!) -*/ - -#if ! DEBUG - -#define check_chunk(P) -#define check_free_chunk(P) -#define check_inuse_chunk(P) -#define check_remalloced_chunk(P,N) -#define check_malloced_chunk(P,N) -#define check_malloc_state() - -#else -#define check_chunk(P) do_check_chunk(P) -#define check_free_chunk(P) do_check_free_chunk(P) -#define check_inuse_chunk(P) do_check_inuse_chunk(P) -#define check_remalloced_chunk(P,N) do_check_remalloced_chunk(P,N) -#define check_malloced_chunk(P,N) do_check_malloced_chunk(P,N) -#define check_malloc_state() do_check_malloc_state() - -/* - Properties of all chunks -*/ - -#if __STD_C -static void do_check_chunk(mchunkptr p) -#else -static void do_check_chunk(p) mchunkptr p; -#endif -{ - mstate av = get_malloc_state(); - unsigned long sz = chunksize(p); - /* min and max possible addresses assuming contiguous allocation */ - char* max_address = (char*)(av->top) + chunksize(av->top); - char* min_address = max_address - av->sbrked_mem; - - if (!chunk_is_mmapped(p)) { - - /* Has legal address ... */ - if (p != av->top) { - if (contiguous(av)) { - assert(((char*)p) >= min_address); - assert(((char*)p + sz) <= ((char*)(av->top))); - } - } - else { - /* top size is always at least MINSIZE */ - assert((unsigned long)(sz) >= MINSIZE); - /* top predecessor always marked inuse */ - assert(prev_inuse(p)); - } - - } - else { -#if HAVE_MMAP - /* address is outside main heap */ - if (contiguous(av) && av->top != initial_top(av)) { - assert(((char*)p) < min_address || ((char*)p) > max_address); - } - /* chunk is page-aligned */ - assert(((p->prev_size + sz) & (av->pagesize-1)) == 0); - /* mem is aligned */ - assert(aligned_OK(chunk2mem(p))); -#else - /* force an appropriate assert violation if debug set */ - assert(!chunk_is_mmapped(p)); -#endif - } -} - -/* - Properties of free chunks -*/ - -#if __STD_C -static void do_check_free_chunk(mchunkptr p) -#else -static void do_check_free_chunk(p) mchunkptr p; -#endif -{ - mstate av = get_malloc_state(); - - INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE; - mchunkptr next = chunk_at_offset(p, sz); - - do_check_chunk(p); - - /* Chunk must claim to be free ... */ - assert(!inuse(p)); - assert (!chunk_is_mmapped(p)); - - /* Unless a special marker, must have OK fields */ - if ((unsigned long)(sz) >= MINSIZE) - { - assert((sz & MALLOC_ALIGN_MASK) == 0); - assert(aligned_OK(chunk2mem(p))); - /* ... matching footer field */ - assert(next->prev_size == sz); - /* ... and is fully consolidated */ - assert(prev_inuse(p)); - assert (next == av->top || inuse(next)); - - /* ... and has minimally sane links */ - assert(p->fd->bk == p); - assert(p->bk->fd == p); - } - else /* markers are always of size SIZE_SZ */ - assert(sz == SIZE_SZ); -} - -/* - Properties of inuse chunks -*/ - -#if __STD_C -static void do_check_inuse_chunk(mchunkptr p) -#else -static void do_check_inuse_chunk(p) mchunkptr p; -#endif -{ - mstate av = get_malloc_state(); - mchunkptr next; - do_check_chunk(p); - - if (chunk_is_mmapped(p)) - return; /* mmapped chunks have no next/prev */ - - /* Check whether it claims to be in use ... */ - assert(inuse(p)); - - next = next_chunk(p); - - /* ... and is surrounded by OK chunks. - Since more things can be checked with free chunks than inuse ones, - if an inuse chunk borders them and debug is on, it's worth doing them. - */ - if (!prev_inuse(p)) { - /* Note that we cannot even look at prev unless it is not inuse */ - mchunkptr prv = prev_chunk(p); - assert(next_chunk(prv) == p); - do_check_free_chunk(prv); - } - - if (next == av->top) { - assert(prev_inuse(next)); - assert(chunksize(next) >= MINSIZE); - } - else if (!inuse(next)) - do_check_free_chunk(next); -} - -/* - Properties of chunks recycled from fastbins -*/ - -#if __STD_C -static void do_check_remalloced_chunk(mchunkptr p, INTERNAL_SIZE_T s) -#else -static void do_check_remalloced_chunk(p, s) mchunkptr p; INTERNAL_SIZE_T s; -#endif -{ - INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE; - - do_check_inuse_chunk(p); - - /* Legal size ... */ - assert((sz & MALLOC_ALIGN_MASK) == 0); - assert((unsigned long)(sz) >= MINSIZE); - /* ... and alignment */ - assert(aligned_OK(chunk2mem(p))); - /* chunk is less than MINSIZE more than request */ - assert((long)(sz) - (long)(s) >= 0); - assert((long)(sz) - (long)(s + MINSIZE) < 0); -} - -/* - Properties of nonrecycled chunks at the point they are malloced -*/ - -#if __STD_C -static void do_check_malloced_chunk(mchunkptr p, INTERNAL_SIZE_T s) -#else -static void do_check_malloced_chunk(p, s) mchunkptr p; INTERNAL_SIZE_T s; -#endif -{ - /* same as recycled case ... */ - do_check_remalloced_chunk(p, s); - - /* - ... plus, must obey implementation invariant that prev_inuse is - always true of any allocated chunk; i.e., that each allocated - chunk borders either a previously allocated and still in-use - chunk, or the base of its memory arena. This is ensured - by making all allocations from the the `lowest' part of any found - chunk. This does not necessarily hold however for chunks - recycled via fastbins. - */ - - assert(prev_inuse(p)); -} - - -/* - Properties of malloc_state. - - This may be useful for debugging malloc, as well as detecting user - programmer errors that somehow write into malloc_state. - - If you are extending or experimenting with this malloc, you can - probably figure out how to hack this routine to print out or - display chunk addresses, sizes, bins, and other instrumentation. -*/ - -static void do_check_malloc_state() -{ - mstate av = get_malloc_state(); - int i; - mchunkptr p; - mchunkptr q; - mbinptr b; - unsigned int binbit; - int empty; - unsigned int idx; - INTERNAL_SIZE_T size; - unsigned long total = 0; - int max_fast_bin; - - /* internal size_t must be no wider than pointer type */ - assert(sizeof(INTERNAL_SIZE_T) <= sizeof(char*)); - - /* alignment is a power of 2 */ - assert((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT-1)) == 0); - - /* cannot run remaining checks until fully initialized */ - if (av->top == 0 || av->top == initial_top(av)) - return; - - /* pagesize is a power of 2 */ - assert((av->pagesize & (av->pagesize-1)) == 0); - - /* properties of fastbins */ - - /* max_fast is in allowed range */ - assert((av->max_fast & ~1) <= request2size(MAX_FAST_SIZE)); - - max_fast_bin = fastbin_index(av->max_fast); - - for (i = 0; i < NFASTBINS; ++i) { - p = av->fastbins[i]; - - /* all bins past max_fast are empty */ - if (i > max_fast_bin) - assert(p == 0); - - while (p != 0) { - /* each chunk claims to be inuse */ - do_check_inuse_chunk(p); - total += chunksize(p); - /* chunk belongs in this bin */ - assert(fastbin_index(chunksize(p)) == i); - p = p->fd; - } - } - - if (total != 0) - assert(have_fastchunks(av)); - else if (!have_fastchunks(av)) - assert(total == 0); - - /* check normal bins */ - for (i = 1; i < NBINS; ++i) { - b = bin_at(av,i); - - /* binmap is accurate (except for bin 1 == unsorted_chunks) */ - if (i >= 2) { - binbit = get_binmap(av,i); - empty = last(b) == b; - if (!binbit) - assert(empty); - else if (!empty) - assert(binbit); - } - - for (p = last(b); p != b; p = p->bk) { - /* each chunk claims to be free */ - do_check_free_chunk(p); - size = chunksize(p); - total += size; - if (i >= 2) { - /* chunk belongs in bin */ - idx = bin_index(size); - assert(idx == i); - /* lists are sorted */ - assert(p->bk == b || - (unsigned long)chunksize(p->bk) >= (unsigned long)chunksize(p)); - } - /* chunk is followed by a legal chain of inuse chunks */ - for (q = next_chunk(p); - (q != av->top && inuse(q) && - (unsigned long)(chunksize(q)) >= MINSIZE); - q = next_chunk(q)) - do_check_inuse_chunk(q); - } - } - - /* top chunk is OK */ - check_chunk(av->top); - - /* sanity checks for statistics */ - - assert(total <= (unsigned long)(av->max_total_mem)); - assert(av->n_mmaps >= 0); - assert(av->n_mmaps <= av->n_mmaps_max); - assert(av->n_mmaps <= av->max_n_mmaps); - - assert((unsigned long)(av->sbrked_mem) <= - (unsigned long)(av->max_sbrked_mem)); - - assert((unsigned long)(av->mmapped_mem) <= - (unsigned long)(av->max_mmapped_mem)); - - assert((unsigned long)(av->max_total_mem) >= - (unsigned long)(av->mmapped_mem) + (unsigned long)(av->sbrked_mem)); -} -#endif - - -/* ----------- Routines dealing with system allocation -------------- */ - -/* - sysmalloc handles malloc cases requiring more memory from the system. - On entry, it is assumed that av->top does not have enough - space to service request for nb bytes, thus requiring that av->top - be extended or replaced. -*/ - -#if __STD_C -static Void_t* sYSMALLOc(INTERNAL_SIZE_T nb, mstate av) -#else -static Void_t* sYSMALLOc(nb, av) INTERNAL_SIZE_T nb; mstate av; -#endif -{ - mchunkptr old_top; /* incoming value of av->top */ - INTERNAL_SIZE_T old_size; /* its size */ - char* old_end; /* its end address */ - - long size; /* arg to first MORECORE or mmap call */ - char* brk; /* return value from MORECORE */ - - long correction; /* arg to 2nd MORECORE call */ - char* snd_brk; /* 2nd return val */ - - INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of new space */ - INTERNAL_SIZE_T end_misalign; /* partial page left at end of new space */ - char* aligned_brk; /* aligned offset into brk */ - - mchunkptr p; /* the allocated/returned chunk */ - mchunkptr remainder; /* remainder from allocation */ - unsigned long remainder_size; /* its size */ - - unsigned long sum; /* for updating stats */ - - size_t pagemask = av->pagesize - 1; - - -#if HAVE_MMAP - - /* - If have mmap, and the request size meets the mmap threshold, and - the system supports mmap, and there are few enough currently - allocated mmapped regions, try to directly map this request - rather than expanding top. - */ - - if ((unsigned long)(nb) >= (unsigned long)(av->mmap_threshold) && - (av->n_mmaps < av->n_mmaps_max)) { - - char* mm; /* return value from mmap call*/ - - /* - Round up size to nearest page. For mmapped chunks, the overhead - is one SIZE_SZ unit larger than for normal chunks, because there - is no following chunk whose prev_size field could be used. - */ - size = (nb + SIZE_SZ + MALLOC_ALIGN_MASK + pagemask) & ~pagemask; - - /* Don't try if size wraps around 0 */ - if ((unsigned long)(size) > (unsigned long)(nb)) { - - mm = (char*)(MMAP(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE)); - - if (mm != (char*)(MORECORE_FAILURE)) { - - /* - The offset to the start of the mmapped region is stored - in the prev_size field of the chunk. This allows us to adjust - returned start address to meet alignment requirements here - and in memalign(), and still be able to compute proper - address argument for later munmap in free() and realloc(). - */ - - front_misalign = (INTERNAL_SIZE_T)chunk2mem(mm) & MALLOC_ALIGN_MASK; - if (front_misalign > 0) { - correction = MALLOC_ALIGNMENT - front_misalign; - p = (mchunkptr)(mm + correction); - p->prev_size = correction; - set_head(p, (size - correction) |IS_MMAPPED); - } - else { - p = (mchunkptr)mm; - set_head(p, size|IS_MMAPPED); - } - - /* update statistics */ - - if (++av->n_mmaps > av->max_n_mmaps) - av->max_n_mmaps = av->n_mmaps; - - sum = av->mmapped_mem += size; - if (sum > (unsigned long)(av->max_mmapped_mem)) - av->max_mmapped_mem = sum; - sum += av->sbrked_mem; - if (sum > (unsigned long)(av->max_total_mem)) - av->max_total_mem = sum; - - check_chunk(p); - - return chunk2mem(p); - } - } - } -#endif - - /* Record incoming configuration of top */ - - old_top = av->top; - old_size = chunksize(old_top); - old_end = (char*)(chunk_at_offset(old_top, old_size)); - - brk = snd_brk = (char*)(MORECORE_FAILURE); - - /* - If not the first time through, we require old_size to be - at least MINSIZE and to have prev_inuse set. - */ - - assert((old_top == initial_top(av) && old_size == 0) || - ((unsigned long) (old_size) >= MINSIZE && - prev_inuse(old_top))); - - /* Precondition: not enough current space to satisfy nb request */ - assert((unsigned long)(old_size) < (unsigned long)(nb + MINSIZE)); - - /* Precondition: all fastbins are consolidated */ - assert(!have_fastchunks(av)); - - - /* Request enough space for nb + pad + overhead */ - - size = nb + av->top_pad + MINSIZE; - - /* - If contiguous, we can subtract out existing space that we hope to - combine with new space. We add it back later only if - we don't actually get contiguous space. - */ - - if (contiguous(av)) - size -= old_size; - - /* - Round to a multiple of page size. - If MORECORE is not contiguous, this ensures that we only call it - with whole-page arguments. And if MORECORE is contiguous and - this is not first time through, this preserves page-alignment of - previous calls. Otherwise, we correct to page-align below. - */ - - size = (size + pagemask) & ~pagemask; - - /* - Don't try to call MORECORE if argument is so big as to appear - negative. Note that since mmap takes size_t arg, it may succeed - below even if we cannot call MORECORE. - */ - - if (size > 0) - brk = (char*)(MORECORE(size)); - - /* - If have mmap, try using it as a backup when MORECORE fails or - cannot be used. This is worth doing on systems that have "holes" in - address space, so sbrk cannot extend to give contiguous space, but - space is available elsewhere. Note that we ignore mmap max count - and threshold limits, since the space will not be used as a - segregated mmap region. - */ - -#if HAVE_MMAP - if (brk == (char*)(MORECORE_FAILURE)) { - - /* Cannot merge with old top, so add its size back in */ - if (contiguous(av)) - size = (size + old_size + pagemask) & ~pagemask; - - /* If we are relying on mmap as backup, then use larger units */ - if ((unsigned long)(size) < (unsigned long)(MMAP_AS_MORECORE_SIZE)) - size = MMAP_AS_MORECORE_SIZE; - - /* Don't try if size wraps around 0 */ - if ((unsigned long)(size) > (unsigned long)(nb)) { - - brk = (char*)(MMAP(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE)); - - if (brk != (char*)(MORECORE_FAILURE)) { - - /* We do not need, and cannot use, another sbrk call to find end */ - snd_brk = brk + size; - - /* - Record that we no longer have a contiguous sbrk region. - After the first time mmap is used as backup, we do not - ever rely on contiguous space since this could incorrectly - bridge regions. - */ - set_noncontiguous(av); - } - } - } -#endif - - if (brk != (char*)(MORECORE_FAILURE)) { - av->sbrked_mem += size; - - /* - If MORECORE extends previous space, we can likewise extend top size. - */ - - if (brk == old_end && snd_brk == (char*)(MORECORE_FAILURE)) { - set_head(old_top, (size + old_size) | PREV_INUSE); - } - - /* - Otherwise, make adjustments: - - * If the first time through or noncontiguous, we need to call sbrk - just to find out where the end of memory lies. - - * We need to ensure that all returned chunks from malloc will meet - MALLOC_ALIGNMENT - - * If there was an intervening foreign sbrk, we need to adjust sbrk - request size to account for fact that we will not be able to - combine new space with existing space in old_top. - - * Almost all systems internally allocate whole pages at a time, in - which case we might as well use the whole last page of request. - So we allocate enough more memory to hit a page boundary now, - which in turn causes future contiguous calls to page-align. - */ - - else { - front_misalign = 0; - end_misalign = 0; - correction = 0; - aligned_brk = brk; - - /* handle contiguous cases */ - if (contiguous(av)) { - - /* Guarantee alignment of first new chunk made from this space */ - - front_misalign = (INTERNAL_SIZE_T)chunk2mem(brk) & MALLOC_ALIGN_MASK; - if (front_misalign > 0) { - - /* - Skip over some bytes to arrive at an aligned position. - We don't need to specially mark these wasted front bytes. - They will never be accessed anyway because - prev_inuse of av->top (and any chunk created from its start) - is always true after initialization. - */ - - correction = MALLOC_ALIGNMENT - front_misalign; - aligned_brk += correction; - } - - /* - If this isn't adjacent to existing space, then we will not - be able to merge with old_top space, so must add to 2nd request. - */ - - correction += old_size; - - /* Extend the end address to hit a page boundary */ - end_misalign = (INTERNAL_SIZE_T)(brk + size + correction); - correction += ((end_misalign + pagemask) & ~pagemask) - end_misalign; - - assert(correction >= 0); - snd_brk = (char*)(MORECORE(correction)); - - /* - If can't allocate correction, try to at least find out current - brk. It might be enough to proceed without failing. - - Note that if second sbrk did NOT fail, we assume that space - is contiguous with first sbrk. This is a safe assumption unless - program is multithreaded but doesn't use locks and a foreign sbrk - occurred between our first and second calls. - */ - - if (snd_brk == (char*)(MORECORE_FAILURE)) { - correction = 0; - snd_brk = (char*)(MORECORE(0)); - } - } - - /* handle non-contiguous cases */ - else { - /* MORECORE/mmap must correctly align */ - assert(((unsigned long)chunk2mem(brk) & MALLOC_ALIGN_MASK) == 0); - - /* Find out current end of memory */ - if (snd_brk == (char*)(MORECORE_FAILURE)) { - snd_brk = (char*)(MORECORE(0)); - } - } - - /* Adjust top based on results of second sbrk */ - if (snd_brk != (char*)(MORECORE_FAILURE)) { - av->top = (mchunkptr)aligned_brk; - set_head(av->top, (snd_brk - aligned_brk + correction) | PREV_INUSE); - av->sbrked_mem += correction; - - /* - If not the first time through, we either have a - gap due to foreign sbrk or a non-contiguous region. Insert a - double fencepost at old_top to prevent consolidation with space - we don't own. These fenceposts are artificial chunks that are - marked as inuse and are in any case too small to use. We need - two to make sizes and alignments work out. - */ - - if (old_size != 0) { - /* - Shrink old_top to insert fenceposts, keeping size a - multiple of MALLOC_ALIGNMENT. We know there is at least - enough space in old_top to do this. - */ - old_size = (old_size - 3*SIZE_SZ) & ~MALLOC_ALIGN_MASK; - set_head(old_top, old_size | PREV_INUSE); - - /* - Note that the following assignments completely overwrite - old_top when old_size was previously MINSIZE. This is - intentional. We need the fencepost, even if old_top otherwise gets - lost. - */ - chunk_at_offset(old_top, old_size )->size = - SIZE_SZ|PREV_INUSE; - - chunk_at_offset(old_top, old_size + SIZE_SZ)->size = - SIZE_SZ|PREV_INUSE; - - /* If possible, release the rest. */ - if (old_size >= MINSIZE) { - fREe(chunk2mem(old_top)); - } - - } - } - } - - /* Update statistics */ - sum = av->sbrked_mem; - if (sum > (unsigned long)(av->max_sbrked_mem)) - av->max_sbrked_mem = sum; - - sum += av->mmapped_mem; - if (sum > (unsigned long)(av->max_total_mem)) - av->max_total_mem = sum; - - check_malloc_state(); - - /* finally, do the allocation */ - p = av->top; - size = chunksize(p); - - /* check that one of the above allocation paths succeeded */ - if ((unsigned long)(size) >= (unsigned long)(nb + MINSIZE)) { - remainder_size = size - nb; - remainder = chunk_at_offset(p, nb); - av->top = remainder; - set_head(p, nb | PREV_INUSE); - set_head(remainder, remainder_size | PREV_INUSE); - check_malloced_chunk(p, nb); - return chunk2mem(p); - } - } - - /* catch all failure paths */ - MALLOC_FAILURE_ACTION; - return 0; -} - - -/* - sYSTRIm is an inverse of sorts to sYSMALLOc. It gives memory back - to the system (via negative arguments to sbrk) if there is unused - memory at the `high' end of the malloc pool. It is called - automatically by free() when top space exceeds the trim - threshold. It is also called by the public malloc_trim routine. It - returns 1 if it actually released any memory, else 0. -*/ - -#if __STD_C -static int sYSTRIm(size_t pad, mstate av) -#else -static int sYSTRIm(pad, av) size_t pad; mstate av; -#endif -{ - long top_size; /* Amount of top-most memory */ - long extra; /* Amount to release */ - long released; /* Amount actually released */ - char* current_brk; /* address returned by pre-check sbrk call */ - char* new_brk; /* address returned by post-check sbrk call */ - size_t pagesz; - - pagesz = av->pagesize; - top_size = chunksize(av->top); - - /* Release in pagesize units, keeping at least one page */ - extra = ((top_size - pad - MINSIZE + (pagesz-1)) / pagesz - 1) * pagesz; - - if (extra > 0) { - - /* - Only proceed if end of memory is where we last set it. - This avoids problems if there were foreign sbrk calls. - */ - current_brk = (char*)(MORECORE(0)); - if (current_brk == (char*)(av->top) + top_size) { - - /* - Attempt to release memory. We ignore MORECORE return value, - and instead call again to find out where new end of memory is. - This avoids problems if first call releases less than we asked, - of if failure somehow altered brk value. (We could still - encounter problems if it altered brk in some very bad way, - but the only thing we can do is adjust anyway, which will cause - some downstream failure.) - */ - - MORECORE(-extra); - new_brk = (char*)(MORECORE(0)); - - if (new_brk != (char*)MORECORE_FAILURE) { - released = (long)(current_brk - new_brk); - - if (released != 0) { - /* Success. Adjust top. */ - av->sbrked_mem -= released; - set_head(av->top, (top_size - released) | PREV_INUSE); - check_malloc_state(); - return 1; - } - } - } - } - return 0; -} - -/* - ------------------------------ malloc ------------------------------ -*/ - -#if __STD_C -Void_t* mALLOc(size_t bytes) -#else - Void_t* mALLOc(bytes) size_t bytes; -#endif -{ - mstate av = get_malloc_state(); - - INTERNAL_SIZE_T nb; /* normalized request size */ - unsigned int idx; /* associated bin index */ - mbinptr bin; /* associated bin */ - mfastbinptr* fb; /* associated fastbin */ - - mchunkptr victim; /* inspected/selected chunk */ - INTERNAL_SIZE_T size; /* its size */ - int victim_index; /* its bin index */ - - mchunkptr remainder; /* remainder from a split */ - unsigned long remainder_size; /* its size */ - - unsigned int block; /* bit map traverser */ - unsigned int bit; /* bit map traverser */ - unsigned int map; /* current word of binmap */ - - mchunkptr fwd; /* misc temp for linking */ - mchunkptr bck; /* misc temp for linking */ - - /* - Convert request size to internal form by adding SIZE_SZ bytes - overhead plus possibly more to obtain necessary alignment and/or - to obtain a size of at least MINSIZE, the smallest allocatable - size. Also, checked_request2size traps (returning 0) request sizes - that are so large that they wrap around zero when padded and - aligned. - */ - - checked_request2size(bytes, nb); - - /* - If the size qualifies as a fastbin, first check corresponding bin. - This code is safe to execute even if av is not yet initialized, so we - can try it without checking, which saves some time on this fast path. - */ - - if ((unsigned long)(nb) <= (unsigned long)(av->max_fast)) { - fb = &(av->fastbins[(fastbin_index(nb))]); - if ( (victim = *fb) != 0) { - *fb = victim->fd; - check_remalloced_chunk(victim, nb); - return chunk2mem(victim); - } - } - - /* - If a small request, check regular bin. Since these "smallbins" - hold one size each, no searching within bins is necessary. - (For a large request, we need to wait until unsorted chunks are - processed to find best fit. But for small ones, fits are exact - anyway, so we can check now, which is faster.) - */ - - if (in_smallbin_range(nb)) { - idx = smallbin_index(nb); - bin = bin_at(av,idx); - - if ( (victim = last(bin)) != bin) { - if (victim == 0) /* initialization check */ - malloc_consolidate(av); - else { - bck = victim->bk; - set_inuse_bit_at_offset(victim, nb); - bin->bk = bck; - bck->fd = bin; - - check_malloced_chunk(victim, nb); - return chunk2mem(victim); - } - } - } - - /* - If this is a large request, consolidate fastbins before continuing. - While it might look excessive to kill all fastbins before - even seeing if there is space available, this avoids - fragmentation problems normally associated with fastbins. - Also, in practice, programs tend to have runs of either small or - large requests, but less often mixtures, so consolidation is not - invoked all that often in most programs. And the programs that - it is called frequently in otherwise tend to fragment. - */ - - else { - idx = largebin_index(nb); - if (have_fastchunks(av)) - malloc_consolidate(av); - } - - /* - Process recently freed or remaindered chunks, taking one only if - it is exact fit, or, if this a small request, the chunk is remainder from - the most recent non-exact fit. Place other traversed chunks in - bins. Note that this step is the only place in any routine where - chunks are placed in bins. - - The outer loop here is needed because we might not realize until - near the end of malloc that we should have consolidated, so must - do so and retry. This happens at most once, and only when we would - otherwise need to expand memory to service a "small" request. - */ - - for(;;) { - - while ( (victim = unsorted_chunks(av)->bk) != unsorted_chunks(av)) { - bck = victim->bk; - size = chunksize(victim); - - /* - If a small request, try to use last remainder if it is the - only chunk in unsorted bin. This helps promote locality for - runs of consecutive small requests. This is the only - exception to best-fit, and applies only when there is - no exact fit for a small chunk. - */ - - if (in_smallbin_range(nb) && - bck == unsorted_chunks(av) && - victim == av->last_remainder && - (unsigned long)(size) > (unsigned long)(nb + MINSIZE)) { - - /* split and reattach remainder */ - remainder_size = size - nb; - remainder = chunk_at_offset(victim, nb); - unsorted_chunks(av)->bk = unsorted_chunks(av)->fd = remainder; - av->last_remainder = remainder; - remainder->bk = remainder->fd = unsorted_chunks(av); - - set_head(victim, nb | PREV_INUSE); - set_head(remainder, remainder_size | PREV_INUSE); - set_foot(remainder, remainder_size); - - check_malloced_chunk(victim, nb); - return chunk2mem(victim); - } - - /* remove from unsorted list */ - unsorted_chunks(av)->bk = bck; - bck->fd = unsorted_chunks(av); - - /* Take now instead of binning if exact fit */ - - if (size == nb) { - set_inuse_bit_at_offset(victim, size); - check_malloced_chunk(victim, nb); - return chunk2mem(victim); - } - - /* place chunk in bin */ - - if (in_smallbin_range(size)) { - victim_index = smallbin_index(size); - bck = bin_at(av, victim_index); - fwd = bck->fd; - } - else { - victim_index = largebin_index(size); - bck = bin_at(av, victim_index); - fwd = bck->fd; - - /* maintain large bins in sorted order */ - if (fwd != bck) { - size |= PREV_INUSE; /* Or with inuse bit to speed comparisons */ - /* if smaller than smallest, bypass loop below */ - if ((unsigned long)(size) <= (unsigned long)(bck->bk->size)) { - fwd = bck; - bck = bck->bk; - } - else { - while ((unsigned long)(size) < (unsigned long)(fwd->size)) - fwd = fwd->fd; - bck = fwd->bk; - } - } - } - - mark_bin(av, victim_index); - victim->bk = bck; - victim->fd = fwd; - fwd->bk = victim; - bck->fd = victim; - } - - /* - If a large request, scan through the chunks of current bin in - sorted order to find smallest that fits. This is the only step - where an unbounded number of chunks might be scanned without doing - anything useful with them. However the lists tend to be short. - */ - - if (!in_smallbin_range(nb)) { - bin = bin_at(av, idx); - - /* skip scan if empty or largest chunk is too small */ - if ((victim = last(bin)) != bin && - (unsigned long)(first(bin)->size) >= (unsigned long)(nb)) { - - while (((unsigned long)(size = chunksize(victim)) < - (unsigned long)(nb))) - victim = victim->bk; - - remainder_size = size - nb; - unlink(victim, bck, fwd); - - /* Exhaust */ - if (remainder_size < MINSIZE) { - set_inuse_bit_at_offset(victim, size); - check_malloced_chunk(victim, nb); - return chunk2mem(victim); - } - /* Split */ - else { - remainder = chunk_at_offset(victim, nb); - unsorted_chunks(av)->bk = unsorted_chunks(av)->fd = remainder; - remainder->bk = remainder->fd = unsorted_chunks(av); - set_head(victim, nb | PREV_INUSE); - set_head(remainder, remainder_size | PREV_INUSE); - set_foot(remainder, remainder_size); - check_malloced_chunk(victim, nb); - return chunk2mem(victim); - } - } - } - - /* - Search for a chunk by scanning bins, starting with next largest - bin. This search is strictly by best-fit; i.e., the smallest - (with ties going to approximately the least recently used) chunk - that fits is selected. - - The bitmap avoids needing to check that most blocks are nonempty. - The particular case of skipping all bins during warm-up phases - when no chunks have been returned yet is faster than it might look. - */ - - ++idx; - bin = bin_at(av,idx); - block = idx2block(idx); - map = av->binmap[block]; - bit = idx2bit(idx); - - for (;;) { - - /* Skip rest of block if there are no more set bits in this block. */ - if (bit > map || bit == 0) { - do { - if (++block >= BINMAPSIZE) /* out of bins */ - goto use_top; - } while ( (map = av->binmap[block]) == 0); - - bin = bin_at(av, (block << BINMAPSHIFT)); - bit = 1; - } - - /* Advance to bin with set bit. There must be one. */ - while ((bit & map) == 0) { - bin = next_bin(bin); - bit <<= 1; - assert(bit != 0); - } - - /* Inspect the bin. It is likely to be non-empty */ - victim = last(bin); - - /* If a false alarm (empty bin), clear the bit. */ - if (victim == bin) { - av->binmap[block] = map &= ~bit; /* Write through */ - bin = next_bin(bin); - bit <<= 1; - } - - else { - size = chunksize(victim); - - /* We know the first chunk in this bin is big enough to use. */ - assert((unsigned long)(size) >= (unsigned long)(nb)); - - remainder_size = size - nb; - - /* unlink */ - bck = victim->bk; - bin->bk = bck; - bck->fd = bin; - - /* Exhaust */ - if (remainder_size < MINSIZE) { - set_inuse_bit_at_offset(victim, size); - check_malloced_chunk(victim, nb); - return chunk2mem(victim); - } - - /* Split */ - else { - remainder = chunk_at_offset(victim, nb); - - unsorted_chunks(av)->bk = unsorted_chunks(av)->fd = remainder; - remainder->bk = remainder->fd = unsorted_chunks(av); - /* advertise as last remainder */ - if (in_smallbin_range(nb)) - av->last_remainder = remainder; - - set_head(victim, nb | PREV_INUSE); - set_head(remainder, remainder_size | PREV_INUSE); - set_foot(remainder, remainder_size); - check_malloced_chunk(victim, nb); - return chunk2mem(victim); - } - } - } - - use_top: - /* - If large enough, split off the chunk bordering the end of memory - (held in av->top). Note that this is in accord with the best-fit - search rule. In effect, av->top is treated as larger (and thus - less well fitting) than any other available chunk since it can - be extended to be as large as necessary (up to system - limitations). - - We require that av->top always exists (i.e., has size >= - MINSIZE) after initialization, so if it would otherwise be - exhuasted by current request, it is replenished. (The main - reason for ensuring it exists is that we may need MINSIZE space - to put in fenceposts in sysmalloc.) - */ - - victim = av->top; - size = chunksize(victim); - - if ((unsigned long)(size) >= (unsigned long)(nb + MINSIZE)) { - remainder_size = size - nb; - remainder = chunk_at_offset(victim, nb); - av->top = remainder; - set_head(victim, nb | PREV_INUSE); - set_head(remainder, remainder_size | PREV_INUSE); - - check_malloced_chunk(victim, nb); - return chunk2mem(victim); - } - - /* - If there is space available in fastbins, consolidate and retry, - to possibly avoid expanding memory. This can occur only if nb is - in smallbin range so we didn't consolidate upon entry. - */ - - else if (have_fastchunks(av)) { - assert(in_smallbin_range(nb)); - malloc_consolidate(av); - idx = smallbin_index(nb); /* restore original bin index */ - } - - /* - Otherwise, relay to handle system-dependent cases - */ - else - return sYSMALLOc(nb, av); - } -} - -/* - ------------------------------ free ------------------------------ -*/ - -#if __STD_C -void fREe(Void_t* mem) -#else -void fREe(mem) Void_t* mem; -#endif -{ - mstate av = get_malloc_state(); - - mchunkptr p; /* chunk corresponding to mem */ - INTERNAL_SIZE_T size; /* its size */ - mfastbinptr* fb; /* associated fastbin */ - mchunkptr nextchunk; /* next contiguous chunk */ - INTERNAL_SIZE_T nextsize; /* its size */ - int nextinuse; /* true if nextchunk is used */ - INTERNAL_SIZE_T prevsize; /* size of previous contiguous chunk */ - mchunkptr bck; /* misc temp for linking */ - mchunkptr fwd; /* misc temp for linking */ - - - /* free(0) has no effect */ - if (mem != 0) { - p = mem2chunk(mem); - size = chunksize(p); - - check_inuse_chunk(p); - - /* - If eligible, place chunk on a fastbin so it can be found - and used quickly in malloc. - */ - - if ((unsigned long)(size) <= (unsigned long)(av->max_fast) - -#if TRIM_FASTBINS - /* - If TRIM_FASTBINS set, don't place chunks - bordering top into fastbins - */ - && (chunk_at_offset(p, size) != av->top) -#endif - ) { - - set_fastchunks(av); - fb = &(av->fastbins[fastbin_index(size)]); - p->fd = *fb; - *fb = p; - } - - /* - Consolidate other non-mmapped chunks as they arrive. - */ - - else if (!chunk_is_mmapped(p)) { - nextchunk = chunk_at_offset(p, size); - nextsize = chunksize(nextchunk); - - /* consolidate backward */ - if (!prev_inuse(p)) { - prevsize = p->prev_size; - size += prevsize; - p = chunk_at_offset(p, -((long) prevsize)); - unlink(p, bck, fwd); - } - - if (nextchunk != av->top) { - /* get and clear inuse bit */ - nextinuse = inuse_bit_at_offset(nextchunk, nextsize); - set_head(nextchunk, nextsize); - - /* consolidate forward */ - if (!nextinuse) { - unlink(nextchunk, bck, fwd); - size += nextsize; - } - - /* - Place the chunk in unsorted chunk list. Chunks are - not placed into regular bins until after they have - been given one chance to be used in malloc. - */ - - bck = unsorted_chunks(av); - fwd = bck->fd; - p->bk = bck; - p->fd = fwd; - bck->fd = p; - fwd->bk = p; - - set_head(p, size | PREV_INUSE); - set_foot(p, size); - - check_free_chunk(p); - } - - /* - If the chunk borders the current high end of memory, - consolidate into top - */ - - else { - size += nextsize; - set_head(p, size | PREV_INUSE); - av->top = p; - check_chunk(p); - } - - /* - If freeing a large space, consolidate possibly-surrounding - chunks. Then, if the total unused topmost memory exceeds trim - threshold, ask malloc_trim to reduce top. - - Unless max_fast is 0, we don't know if there are fastbins - bordering top, so we cannot tell for sure whether threshold - has been reached unless fastbins are consolidated. But we - don't want to consolidate on each free. As a compromise, - consolidation is performed if FASTBIN_CONSOLIDATION_THRESHOLD - is reached. - */ - - if ((unsigned long)(size) >= FASTBIN_CONSOLIDATION_THRESHOLD) { - if (have_fastchunks(av)) - malloc_consolidate(av); - -#ifndef MORECORE_CANNOT_TRIM - if ((unsigned long)(chunksize(av->top)) >= - (unsigned long)(av->trim_threshold)) - sYSTRIm(av->top_pad, av); -#endif - } - - } - /* - If the chunk was allocated via mmap, release via munmap() - Note that if HAVE_MMAP is false but chunk_is_mmapped is - true, then user must have overwritten memory. There's nothing - we can do to catch this error unless DEBUG is set, in which case - check_inuse_chunk (above) will have triggered error. - */ - - else { -#if HAVE_MMAP - int ret; - INTERNAL_SIZE_T offset = p->prev_size; - av->n_mmaps--; - av->mmapped_mem -= (size + offset); - ret = munmap((char*)p - offset, size + offset); - /* munmap returns non-zero on failure */ - assert(ret == 0); -#endif - } - } -} - -/* - ------------------------- malloc_consolidate ------------------------- - - malloc_consolidate is a specialized version of free() that tears - down chunks held in fastbins. Free itself cannot be used for this - purpose since, among other things, it might place chunks back onto - fastbins. So, instead, we need to use a minor variant of the same - code. - - Also, because this routine needs to be called the first time through - malloc anyway, it turns out to be the perfect place to trigger - initialization code. -*/ - -#if __STD_C -static void malloc_consolidate(mstate av) -#else -static void malloc_consolidate(av) mstate av; -#endif -{ - mfastbinptr* fb; /* current fastbin being consolidated */ - mfastbinptr* maxfb; /* last fastbin (for loop control) */ - mchunkptr p; /* current chunk being consolidated */ - mchunkptr nextp; /* next chunk to consolidate */ - mchunkptr unsorted_bin; /* bin header */ - mchunkptr first_unsorted; /* chunk to link to */ - - /* These have same use as in free() */ - mchunkptr nextchunk; - INTERNAL_SIZE_T size; - INTERNAL_SIZE_T nextsize; - INTERNAL_SIZE_T prevsize; - int nextinuse; - mchunkptr bck; - mchunkptr fwd; - - /* - If max_fast is 0, we know that av hasn't - yet been initialized, in which case do so below - */ - - if (av->max_fast != 0) { - clear_fastchunks(av); - - unsorted_bin = unsorted_chunks(av); - - /* - Remove each chunk from fast bin and consolidate it, placing it - then in unsorted bin. Among other reasons for doing this, - placing in unsorted bin avoids needing to calculate actual bins - until malloc is sure that chunks aren't immediately going to be - reused anyway. - */ - - maxfb = &(av->fastbins[fastbin_index(av->max_fast)]); - fb = &(av->fastbins[0]); - do { - if ( (p = *fb) != 0) { - *fb = 0; - - do { - check_inuse_chunk(p); - nextp = p->fd; - - /* Slightly streamlined version of consolidation code in free() */ - size = p->size & ~PREV_INUSE; - nextchunk = chunk_at_offset(p, size); - nextsize = chunksize(nextchunk); - - if (!prev_inuse(p)) { - prevsize = p->prev_size; - size += prevsize; - p = chunk_at_offset(p, -((long) prevsize)); - unlink(p, bck, fwd); - } - - if (nextchunk != av->top) { - nextinuse = inuse_bit_at_offset(nextchunk, nextsize); - set_head(nextchunk, nextsize); - - if (!nextinuse) { - size += nextsize; - unlink(nextchunk, bck, fwd); - } - - first_unsorted = unsorted_bin->fd; - unsorted_bin->fd = p; - first_unsorted->bk = p; - - set_head(p, size | PREV_INUSE); - p->bk = unsorted_bin; - p->fd = first_unsorted; - set_foot(p, size); - } - - else { - size += nextsize; - set_head(p, size | PREV_INUSE); - av->top = p; - } - - } while ( (p = nextp) != 0); - - } - } while (fb++ != maxfb); - } - else { - malloc_init_state(av); - check_malloc_state(); - } -} - -/* - ------------------------------ realloc ------------------------------ -*/ - - -#if __STD_C -Void_t* rEALLOc(Void_t* oldmem, size_t bytes) -#else -Void_t* rEALLOc(oldmem, bytes) Void_t* oldmem; size_t bytes; -#endif -{ - mstate av = get_malloc_state(); - - INTERNAL_SIZE_T nb; /* padded request size */ - - mchunkptr oldp; /* chunk corresponding to oldmem */ - INTERNAL_SIZE_T oldsize; /* its size */ - - mchunkptr newp; /* chunk to return */ - INTERNAL_SIZE_T newsize; /* its size */ - Void_t* newmem; /* corresponding user mem */ - - mchunkptr next; /* next contiguous chunk after oldp */ - - mchunkptr remainder; /* extra space at end of newp */ - unsigned long remainder_size; /* its size */ - - mchunkptr bck; /* misc temp for linking */ - mchunkptr fwd; /* misc temp for linking */ - - unsigned long copysize; /* bytes to copy */ - unsigned int ncopies; /* INTERNAL_SIZE_T words to copy */ - INTERNAL_SIZE_T* s; /* copy source */ - INTERNAL_SIZE_T* d; /* copy destination */ - - -#ifdef REALLOC_ZERO_BYTES_FREES - if (bytes == 0) { - fREe(oldmem); - return 0; - } -#endif - - /* realloc of null is supposed to be same as malloc */ - if (oldmem == 0) return mALLOc(bytes); - - checked_request2size(bytes, nb); - - oldp = mem2chunk(oldmem); - oldsize = chunksize(oldp); - - check_inuse_chunk(oldp); - - if (!chunk_is_mmapped(oldp)) { - - if ((unsigned long)(oldsize) >= (unsigned long)(nb)) { - /* already big enough; split below */ - newp = oldp; - newsize = oldsize; - } - - else { - next = chunk_at_offset(oldp, oldsize); - - /* Try to expand forward into top */ - if (next == av->top && - (unsigned long)(newsize = oldsize + chunksize(next)) >= - (unsigned long)(nb + MINSIZE)) { - set_head_size(oldp, nb); - av->top = chunk_at_offset(oldp, nb); - set_head(av->top, (newsize - nb) | PREV_INUSE); - return chunk2mem(oldp); - } - - /* Try to expand forward into next chunk; split off remainder below */ - else if (next != av->top && - !inuse(next) && - (unsigned long)(newsize = oldsize + chunksize(next)) >= - (unsigned long)(nb)) { - newp = oldp; - unlink(next, bck, fwd); - } - - /* allocate, copy, free */ - else { - newmem = mALLOc(nb - MALLOC_ALIGN_MASK); - if (newmem == 0) - return 0; /* propagate failure */ - - newp = mem2chunk(newmem); - newsize = chunksize(newp); - - /* - Avoid copy if newp is next chunk after oldp. - */ - if (newp == next) { - newsize += oldsize; - newp = oldp; - } - else { - /* - Unroll copy of <= 36 bytes (72 if 8byte sizes) - We know that contents have an odd number of - INTERNAL_SIZE_T-sized words; minimally 3. - */ - - copysize = oldsize - SIZE_SZ; - s = (INTERNAL_SIZE_T*)(oldmem); - d = (INTERNAL_SIZE_T*)(newmem); - ncopies = copysize / sizeof(INTERNAL_SIZE_T); - assert(ncopies >= 3); - - if (ncopies > 9) - MALLOC_COPY(d, s, copysize); - - else { - *(d+0) = *(s+0); - *(d+1) = *(s+1); - *(d+2) = *(s+2); - if (ncopies > 4) { - *(d+3) = *(s+3); - *(d+4) = *(s+4); - if (ncopies > 6) { - *(d+5) = *(s+5); - *(d+6) = *(s+6); - if (ncopies > 8) { - *(d+7) = *(s+7); - *(d+8) = *(s+8); - } - } - } - } - - fREe(oldmem); - check_inuse_chunk(newp); - return chunk2mem(newp); - } - } - } - - /* If possible, free extra space in old or extended chunk */ - - assert((unsigned long)(newsize) >= (unsigned long)(nb)); - - remainder_size = newsize - nb; - - if (remainder_size < MINSIZE) { /* not enough extra to split off */ - set_head_size(newp, newsize); - set_inuse_bit_at_offset(newp, newsize); - } - else { /* split remainder */ - remainder = chunk_at_offset(newp, nb); - set_head_size(newp, nb); - set_head(remainder, remainder_size | PREV_INUSE); - /* Mark remainder as inuse so free() won't complain */ - set_inuse_bit_at_offset(remainder, remainder_size); - fREe(chunk2mem(remainder)); - } - - check_inuse_chunk(newp); - return chunk2mem(newp); - } - - /* - Handle mmap cases - */ - - else { -#if HAVE_MMAP - -#if HAVE_MREMAP - INTERNAL_SIZE_T offset = oldp->prev_size; - size_t pagemask = av->pagesize - 1; - char *cp; - unsigned long sum; - - /* Note the extra SIZE_SZ overhead */ - newsize = (nb + offset + SIZE_SZ + pagemask) & ~pagemask; - - /* don't need to remap if still within same page */ - if (oldsize == newsize - offset) - return oldmem; - - cp = (char*)mremap((char*)oldp - offset, oldsize + offset, newsize, 1); - - if (cp != (char*)MORECORE_FAILURE) { - - newp = (mchunkptr)(cp + offset); - set_head(newp, (newsize - offset)|IS_MMAPPED); - - assert(aligned_OK(chunk2mem(newp))); - assert((newp->prev_size == offset)); - - /* update statistics */ - sum = av->mmapped_mem += newsize - oldsize; - if (sum > (unsigned long)(av->max_mmapped_mem)) - av->max_mmapped_mem = sum; - sum += av->sbrked_mem; - if (sum > (unsigned long)(av->max_total_mem)) - av->max_total_mem = sum; - - return chunk2mem(newp); - } -#endif - - /* Note the extra SIZE_SZ overhead. */ - if ((unsigned long)(oldsize) >= (unsigned long)(nb + SIZE_SZ)) - newmem = oldmem; /* do nothing */ - else { - /* Must alloc, copy, free. */ - newmem = mALLOc(nb - MALLOC_ALIGN_MASK); - if (newmem != 0) { - MALLOC_COPY(newmem, oldmem, oldsize - 2*SIZE_SZ); - fREe(oldmem); - } - } - return newmem; - -#else - /* If !HAVE_MMAP, but chunk_is_mmapped, user must have overwritten mem */ - check_malloc_state(); - MALLOC_FAILURE_ACTION; - return 0; -#endif - } -} - -/* - ------------------------------ memalign ------------------------------ -*/ - -#if __STD_C -Void_t* mEMALIGn(size_t alignment, size_t bytes) -#else -Void_t* mEMALIGn(alignment, bytes) size_t alignment; size_t bytes; -#endif -{ - INTERNAL_SIZE_T nb; /* padded request size */ - char* m; /* memory returned by malloc call */ - mchunkptr p; /* corresponding chunk */ - char* brk; /* alignment point within p */ - mchunkptr newp; /* chunk to return */ - INTERNAL_SIZE_T newsize; /* its size */ - INTERNAL_SIZE_T leadsize; /* leading space before alignment point */ - mchunkptr remainder; /* spare room at end to split off */ - unsigned long remainder_size; /* its size */ - INTERNAL_SIZE_T size; - - /* If need less alignment than we give anyway, just relay to malloc */ - - if (alignment <= MALLOC_ALIGNMENT) return mALLOc(bytes); - - /* Otherwise, ensure that it is at least a minimum chunk size */ - - if (alignment < MINSIZE) alignment = MINSIZE; - - /* Make sure alignment is power of 2 (in case MINSIZE is not). */ - if ((alignment & (alignment - 1)) != 0) { - size_t a = MALLOC_ALIGNMENT * 2; - while ((unsigned long)a < (unsigned long)alignment) a <<= 1; - alignment = a; - } - - checked_request2size(bytes, nb); - - /* - Strategy: find a spot within that chunk that meets the alignment - request, and then possibly free the leading and trailing space. - */ - - - /* Call malloc with worst case padding to hit alignment. */ - - m = (char*)(mALLOc(nb + alignment + MINSIZE)); - - if (m == 0) return 0; /* propagate failure */ - - p = mem2chunk(m); - - if ((((unsigned long)(m)) % alignment) != 0) { /* misaligned */ - - /* - Find an aligned spot inside chunk. Since we need to give back - leading space in a chunk of at least MINSIZE, if the first - calculation places us at a spot with less than MINSIZE leader, - we can move to the next aligned spot -- we've allocated enough - total room so that this is always possible. - */ - - brk = (char*)mem2chunk(((unsigned long)(m + alignment - 1)) & - -((signed long) alignment)); - if ((unsigned long)(brk - (char*)(p)) < MINSIZE) - brk += alignment; - - newp = (mchunkptr)brk; - leadsize = brk - (char*)(p); - newsize = chunksize(p) - leadsize; - - /* For mmapped chunks, just adjust offset */ - if (chunk_is_mmapped(p)) { - newp->prev_size = p->prev_size + leadsize; - set_head(newp, newsize|IS_MMAPPED); - return chunk2mem(newp); - } - - /* Otherwise, give back leader, use the rest */ - set_head(newp, newsize | PREV_INUSE); - set_inuse_bit_at_offset(newp, newsize); - set_head_size(p, leadsize); - fREe(chunk2mem(p)); - p = newp; - - assert (newsize >= nb && - (((unsigned long)(chunk2mem(p))) % alignment) == 0); - } - - /* Also give back spare room at the end */ - if (!chunk_is_mmapped(p)) { - size = chunksize(p); - if ((unsigned long)(size) > (unsigned long)(nb + MINSIZE)) { - remainder_size = size - nb; - remainder = chunk_at_offset(p, nb); - set_head(remainder, remainder_size | PREV_INUSE); - set_head_size(p, nb); - fREe(chunk2mem(remainder)); - } - } - - check_inuse_chunk(p); - return chunk2mem(p); -} - -/* - ------------------------------ calloc ------------------------------ -*/ - -#if __STD_C -Void_t* cALLOc(size_t n_elements, size_t elem_size) -#else -Void_t* cALLOc(n_elements, elem_size) size_t n_elements; size_t elem_size; -#endif -{ - mchunkptr p; - unsigned long clearsize; - unsigned long nclears; - INTERNAL_SIZE_T* d; - - Void_t* mem = mALLOc(n_elements * elem_size); - - if (mem != 0) { - p = mem2chunk(mem); - -#if MMAP_CLEARS - if (!chunk_is_mmapped(p)) /* don't need to clear mmapped space */ -#endif - { - /* - Unroll clear of <= 36 bytes (72 if 8byte sizes) - We know that contents have an odd number of - INTERNAL_SIZE_T-sized words; minimally 3. - */ - - d = (INTERNAL_SIZE_T*)mem; - clearsize = chunksize(p) - SIZE_SZ; - nclears = clearsize / sizeof(INTERNAL_SIZE_T); - assert(nclears >= 3); - - if (nclears > 9) - MALLOC_ZERO(d, clearsize); - - else { - *(d+0) = 0; - *(d+1) = 0; - *(d+2) = 0; - if (nclears > 4) { - *(d+3) = 0; - *(d+4) = 0; - if (nclears > 6) { - *(d+5) = 0; - *(d+6) = 0; - if (nclears > 8) { - *(d+7) = 0; - *(d+8) = 0; - } - } - } - } - } - } - return mem; -} - -/* - ------------------------------ cfree ------------------------------ -*/ - -#if __STD_C -void cFREe(Void_t *mem) -#else -void cFREe(mem) Void_t *mem; -#endif -{ - fREe(mem); -} - -/* - ------------------------- independent_calloc ------------------------- -*/ - -#if __STD_C -Void_t** iCALLOc(size_t n_elements, size_t elem_size, Void_t* chunks[]) -#else -Void_t** iCALLOc(n_elements, elem_size, chunks) size_t n_elements; size_t elem_size; Void_t* chunks[]; -#endif -{ - size_t sz = elem_size; /* serves as 1-element array */ - /* opts arg of 3 means all elements are same size, and should be cleared */ - return iALLOc(n_elements, &sz, 3, chunks); -} - -/* - ------------------------- independent_comalloc ------------------------- -*/ - -#if __STD_C -Void_t** iCOMALLOc(size_t n_elements, size_t sizes[], Void_t* chunks[]) -#else -Void_t** iCOMALLOc(n_elements, sizes, chunks) size_t n_elements; size_t sizes[]; Void_t* chunks[]; -#endif -{ - return iALLOc(n_elements, sizes, 0, chunks); -} - - -/* - ------------------------------ ialloc ------------------------------ - ialloc provides common support for independent_X routines, handling all of - the combinations that can result. - - The opts arg has: - bit 0 set if all elements are same size (using sizes[0]) - bit 1 set if elements should be zeroed -*/ - - -#if __STD_C -static Void_t** iALLOc(size_t n_elements, - size_t* sizes, - int opts, - Void_t* chunks[]) -#else -static Void_t** iALLOc(n_elements, sizes, opts, chunks) size_t n_elements; size_t* sizes; int opts; Void_t* chunks[]; -#endif -{ - mstate av = get_malloc_state(); - INTERNAL_SIZE_T element_size; /* chunksize of each element, if all same */ - INTERNAL_SIZE_T contents_size; /* total size of elements */ - INTERNAL_SIZE_T array_size; /* request size of pointer array */ - Void_t* mem; /* malloced aggregate space */ - mchunkptr p; /* corresponding chunk */ - INTERNAL_SIZE_T remainder_size; /* remaining bytes while splitting */ - Void_t** marray; /* either "chunks" or malloced ptr array */ - mchunkptr array_chunk; /* chunk for malloced ptr array */ - int mmx; /* to disable mmap */ - INTERNAL_SIZE_T size; - size_t i; - - /* Ensure initialization/consolidation */ - if (have_fastchunks(av)) malloc_consolidate(av); - - /* compute array length, if needed */ - if (chunks != 0) { - if (n_elements == 0) - return chunks; /* nothing to do */ - marray = chunks; - array_size = 0; - } - else { - /* if empty req, must still return chunk representing empty array */ - if (n_elements == 0) - return (Void_t**) mALLOc(0); - marray = 0; - array_size = request2size(n_elements * (sizeof(Void_t*))); - } - - /* compute total element size */ - if (opts & 0x1) { /* all-same-size */ - element_size = request2size(*sizes); - contents_size = n_elements * element_size; - } - else { /* add up all the sizes */ - element_size = 0; - contents_size = 0; - for (i = 0; i != n_elements; ++i) - contents_size += request2size(sizes[i]); - } - - /* subtract out alignment bytes from total to minimize overallocation */ - size = contents_size + array_size - MALLOC_ALIGN_MASK; - - /* - Allocate the aggregate chunk. - But first disable mmap so malloc won't use it, since - we would not be able to later free/realloc space internal - to a segregated mmap region. - */ - mmx = av->n_mmaps_max; /* disable mmap */ - av->n_mmaps_max = 0; - mem = mALLOc(size); - av->n_mmaps_max = mmx; /* reset mmap */ - if (mem == 0) - return 0; - - p = mem2chunk(mem); - assert(!chunk_is_mmapped(p)); - remainder_size = chunksize(p); - - if (opts & 0x2) { /* optionally clear the elements */ - MALLOC_ZERO(mem, remainder_size - SIZE_SZ - array_size); - } - - /* If not provided, allocate the pointer array as final part of chunk */ - if (marray == 0) { - array_chunk = chunk_at_offset(p, contents_size); - marray = (Void_t**) (chunk2mem(array_chunk)); - set_head(array_chunk, (remainder_size - contents_size) | PREV_INUSE); - remainder_size = contents_size; - } - - /* split out elements */ - for (i = 0; ; ++i) { - marray[i] = chunk2mem(p); - if (i != n_elements-1) { - if (element_size != 0) - size = element_size; - else - size = request2size(sizes[i]); - remainder_size -= size; - set_head(p, size | PREV_INUSE); - p = chunk_at_offset(p, size); - } - else { /* the final element absorbs any overallocation slop */ - set_head(p, remainder_size | PREV_INUSE); - break; - } - } - -#if DEBUG - if (marray != chunks) { - /* final element must have exactly exhausted chunk */ - if (element_size != 0) - assert(remainder_size == element_size); - else - assert(remainder_size == request2size(sizes[i])); - check_inuse_chunk(mem2chunk(marray)); - } - - for (i = 0; i != n_elements; ++i) - check_inuse_chunk(mem2chunk(marray[i])); -#endif - - return marray; -} - - -/* - ------------------------------ valloc ------------------------------ -*/ - -#if __STD_C -Void_t* vALLOc(size_t bytes) -#else -Void_t* vALLOc(bytes) size_t bytes; -#endif -{ - /* Ensure initialization/consolidation */ - mstate av = get_malloc_state(); - if (have_fastchunks(av)) malloc_consolidate(av); - return mEMALIGn(av->pagesize, bytes); -} - -/* - ------------------------------ pvalloc ------------------------------ -*/ - - -#if __STD_C -Void_t* pVALLOc(size_t bytes) -#else -Void_t* pVALLOc(bytes) size_t bytes; -#endif -{ - mstate av = get_malloc_state(); - size_t pagesz; - - /* Ensure initialization/consolidation */ - if (have_fastchunks(av)) malloc_consolidate(av); - pagesz = av->pagesize; - return mEMALIGn(pagesz, (bytes + pagesz - 1) & ~(pagesz - 1)); -} - - -/* - ------------------------------ malloc_trim ------------------------------ -*/ - -#if __STD_C -int mTRIm(size_t pad) -#else -int mTRIm(pad) size_t pad; -#endif -{ - mstate av = get_malloc_state(); - /* Ensure initialization/consolidation */ - malloc_consolidate(av); - -#ifndef MORECORE_CANNOT_TRIM - return sYSTRIm(pad, av); -#else - return 0; -#endif -} - - -/* - ------------------------- malloc_usable_size ------------------------- -*/ - -#if __STD_C -size_t mUSABLe(Void_t* mem) -#else -size_t mUSABLe(mem) Void_t* mem; -#endif -{ - mchunkptr p; - if (mem != 0) { - p = mem2chunk(mem); - if (chunk_is_mmapped(p)) - return chunksize(p) - 2*SIZE_SZ; - else if (inuse(p)) - return chunksize(p) - SIZE_SZ; - } - return 0; -} - -/* - ------------------------------ mallinfo ------------------------------ -*/ - -struct mallinfo mALLINFo() -{ - mstate av = get_malloc_state(); - struct mallinfo mi; - int i; - mbinptr b; - mchunkptr p; - INTERNAL_SIZE_T avail; - INTERNAL_SIZE_T fastavail; - int nblocks; - int nfastblocks; - - /* Ensure initialization */ - if (av->top == 0) malloc_consolidate(av); - - check_malloc_state(); - - /* Account for top */ - avail = chunksize(av->top); - nblocks = 1; /* top always exists */ - - /* traverse fastbins */ - nfastblocks = 0; - fastavail = 0; - - for (i = 0; i < (int) NFASTBINS; ++i) { - for (p = av->fastbins[i]; p != 0; p = p->fd) { - ++nfastblocks; - fastavail += chunksize(p); - } - } - - avail += fastavail; - - /* traverse regular bins */ - for (i = 1; i < NBINS; ++i) { - b = bin_at(av, i); - for (p = last(b); p != b; p = p->bk) { - ++nblocks; - avail += chunksize(p); - } - } - - mi.smblks = nfastblocks; - mi.ordblks = nblocks; - mi.fordblks = avail; - mi.uordblks = av->sbrked_mem - avail; - mi.arena = av->sbrked_mem; - mi.hblks = av->n_mmaps; - mi.hblkhd = av->mmapped_mem; - mi.fsmblks = fastavail; - mi.keepcost = chunksize(av->top); - mi.usmblks = av->max_total_mem; - return mi; -} - -/* - ------------------------------ malloc_stats ------------------------------ -*/ - -void mSTATs() -{ - struct mallinfo mi = mALLINFo(); - -#ifdef WIN32 - { - unsigned long free, reserved, committed; - vminfo (&free, &reserved, &committed); - fprintf(stderr, "free bytes = %10lu\n", - free); - fprintf(stderr, "reserved bytes = %10lu\n", - reserved); - fprintf(stderr, "committed bytes = %10lu\n", - committed); - } -#endif - - - fprintf(stderr, "max system bytes = %10lu\n", - (unsigned long)(mi.usmblks)); - fprintf(stderr, "system bytes = %10lu\n", - (unsigned long)(mi.arena + mi.hblkhd)); - fprintf(stderr, "in use bytes = %10lu\n", - (unsigned long)(mi.uordblks + mi.hblkhd)); - - -#ifdef WIN32 - { - unsigned long kernel, user; - if (cpuinfo (TRUE, &kernel, &user)) { - fprintf(stderr, "kernel ms = %10lu\n", - kernel); - fprintf(stderr, "user ms = %10lu\n", - user); - } - } -#endif -} - - -/* - ------------------------------ mallopt ------------------------------ -*/ - -#if __STD_C -int mALLOPt(int param_number, int value) -#else -int mALLOPt(param_number, value) int param_number; int value; -#endif -{ - mstate av = get_malloc_state(); - /* Ensure initialization/consolidation */ - malloc_consolidate(av); - - switch(param_number) { - case M_MXFAST: - if (value >= 0 && value <= MAX_FAST_SIZE) { - set_max_fast(av, value); - return 1; - } - else - return 0; - - case M_TRIM_THRESHOLD: - av->trim_threshold = value; - return 1; - - case M_TOP_PAD: - av->top_pad = value; - return 1; - - case M_MMAP_THRESHOLD: - av->mmap_threshold = value; - return 1; - - case M_MMAP_MAX: -#if !HAVE_MMAP - if (value != 0) - return 0; -#endif - av->n_mmaps_max = value; - return 1; - - default: - return 0; - } -} - - -/* - -------------------- Alternative MORECORE functions -------------------- -*/ - - -/* - General Requirements for MORECORE. - - The MORECORE function must have the following properties: - - If MORECORE_CONTIGUOUS is false: - - * MORECORE must allocate in multiples of pagesize. It will - only be called with arguments that are multiples of pagesize. - - * MORECORE(0) must return an address that is at least - MALLOC_ALIGNMENT aligned. (Page-aligning always suffices.) - - else (i.e. If MORECORE_CONTIGUOUS is true): - - * Consecutive calls to MORECORE with positive arguments - return increasing addresses, indicating that space has been - contiguously extended. - - * MORECORE need not allocate in multiples of pagesize. - Calls to MORECORE need not have args of multiples of pagesize. - - * MORECORE need not page-align. - - In either case: - - * MORECORE may allocate more memory than requested. (Or even less, - but this will generally result in a malloc failure.) - - * MORECORE must not allocate memory when given argument zero, but - instead return one past the end address of memory from previous - nonzero call. This malloc does NOT call MORECORE(0) - until at least one call with positive arguments is made, so - the initial value returned is not important. - - * Even though consecutive calls to MORECORE need not return contiguous - addresses, it must be OK for malloc'ed chunks to span multiple - regions in those cases where they do happen to be contiguous. - - * MORECORE need not handle negative arguments -- it may instead - just return MORECORE_FAILURE when given negative arguments. - Negative arguments are always multiples of pagesize. MORECORE - must not misinterpret negative args as large positive unsigned - args. You can suppress all such calls from even occurring by defining - MORECORE_CANNOT_TRIM, - - There is some variation across systems about the type of the - argument to sbrk/MORECORE. If size_t is unsigned, then it cannot - actually be size_t, because sbrk supports negative args, so it is - normally the signed type of the same width as size_t (sometimes - declared as "intptr_t", and sometimes "ptrdiff_t"). It doesn't much - matter though. Internally, we use "long" as arguments, which should - work across all reasonable possibilities. - - Additionally, if MORECORE ever returns failure for a positive - request, and HAVE_MMAP is true, then mmap is used as a noncontiguous - system allocator. This is a useful backup strategy for systems with - holes in address spaces -- in this case sbrk cannot contiguously - expand the heap, but mmap may be able to map noncontiguous space. - - If you'd like mmap to ALWAYS be used, you can define MORECORE to be - a function that always returns MORECORE_FAILURE. - - If you are using this malloc with something other than sbrk (or its - emulation) to supply memory regions, you probably want to set - MORECORE_CONTIGUOUS as false. As an example, here is a custom - allocator kindly contributed for pre-OSX macOS. It uses virtually - but not necessarily physically contiguous non-paged memory (locked - in, present and won't get swapped out). You can use it by - uncommenting this section, adding some #includes, and setting up the - appropriate defines above: - - #define MORECORE osMoreCore - #define MORECORE_CONTIGUOUS 0 - - There is also a shutdown routine that should somehow be called for - cleanup upon program exit. - - #define MAX_POOL_ENTRIES 100 - #define MINIMUM_MORECORE_SIZE (64 * 1024) - static int next_os_pool; - void *our_os_pools[MAX_POOL_ENTRIES]; - - void *osMoreCore(int size) - { - void *ptr = 0; - static void *sbrk_top = 0; - - if (size > 0) - { - if (size < MINIMUM_MORECORE_SIZE) - size = MINIMUM_MORECORE_SIZE; - if (CurrentExecutionLevel() == kTaskLevel) - ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0); - if (ptr == 0) - { - return (void *) MORECORE_FAILURE; - } - // save ptrs so they can be freed during cleanup - our_os_pools[next_os_pool] = ptr; - next_os_pool++; - ptr = (void *) ((((unsigned long) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK); - sbrk_top = (char *) ptr + size; - return ptr; - } - else if (size < 0) - { - // we don't currently support shrink behavior - return (void *) MORECORE_FAILURE; - } - else - { - return sbrk_top; - } - } - - // cleanup any allocated memory pools - // called as last thing before shutting down driver - - void osCleanupMem(void) - { - void **ptr; - - for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++) - if (*ptr) - { - PoolDeallocate(*ptr); - *ptr = 0; - } - } - -*/ - - -/* - -------------------------------------------------------------- - - Emulation of sbrk for win32. - Donated by J. Walter . - For additional information about this code, and malloc on Win32, see - http://www.genesys-e.de/jwalter/ -*/ - - -#ifdef WIN32 - -#ifdef _DEBUG -/* #define TRACE */ -#endif - -/* Support for USE_MALLOC_LOCK */ -#ifdef USE_MALLOC_LOCK - -/* Wait for spin lock */ -static int slwait (int *sl) { - while (InterlockedCompareExchange ((void **) sl, (void *) 1, (void *) 0) != 0) - Sleep (0); - return 0; -} - -/* Release spin lock */ -static int slrelease (int *sl) { - InterlockedExchange (sl, 0); - return 0; -} - -#ifdef NEEDED -/* Spin lock for emulation code */ -static int g_sl; -#endif - -#endif /* USE_MALLOC_LOCK */ - -/* getpagesize for windows */ -static long getpagesize (void) { - static long g_pagesize = 0; - if (! g_pagesize) { - SYSTEM_INFO system_info; - GetSystemInfo (&system_info); - g_pagesize = system_info.dwPageSize; - } - return g_pagesize; -} -static long getregionsize (void) { - static long g_regionsize = 0; - if (! g_regionsize) { - SYSTEM_INFO system_info; - GetSystemInfo (&system_info); - g_regionsize = system_info.dwAllocationGranularity; - } - return g_regionsize; -} - -/* A region list entry */ -typedef struct _region_list_entry { - void *top_allocated; - void *top_committed; - void *top_reserved; - long reserve_size; - struct _region_list_entry *previous; -} region_list_entry; - -/* Allocate and link a region entry in the region list */ -static int region_list_append (region_list_entry **last, void *base_reserved, long reserve_size) { - region_list_entry *next = HeapAlloc (GetProcessHeap (), 0, sizeof (region_list_entry)); - if (! next) - return FALSE; - next->top_allocated = (char *) base_reserved; - next->top_committed = (char *) base_reserved; - next->top_reserved = (char *) base_reserved + reserve_size; - next->reserve_size = reserve_size; - next->previous = *last; - *last = next; - return TRUE; -} -/* Free and unlink the last region entry from the region list */ -static int region_list_remove (region_list_entry **last) { - region_list_entry *previous = (*last)->previous; - if (! HeapFree (GetProcessHeap (), sizeof (region_list_entry), *last)) - return FALSE; - *last = previous; - return TRUE; -} - -#define CEIL(size,to) (((size)+(to)-1)&~((to)-1)) -#define FLOOR(size,to) ((size)&~((to)-1)) - -#define SBRK_SCALE 0 -/* #define SBRK_SCALE 1 */ -/* #define SBRK_SCALE 2 */ -/* #define SBRK_SCALE 4 */ - -/* sbrk for windows */ -static void *sbrk (long size) { - static long g_pagesize, g_my_pagesize; - static long g_regionsize, g_my_regionsize; - static region_list_entry *g_last; - void *result = (void *) MORECORE_FAILURE; -#ifdef TRACE - printf ("sbrk %d\n", size); -#endif -#if defined (USE_MALLOC_LOCK) && defined (NEEDED) - /* Wait for spin lock */ - slwait (&g_sl); -#endif - /* First time initialization */ - if (! g_pagesize) { - g_pagesize = getpagesize (); - g_my_pagesize = g_pagesize << SBRK_SCALE; - } - if (! g_regionsize) { - g_regionsize = getregionsize (); - g_my_regionsize = g_regionsize << SBRK_SCALE; - } - if (! g_last) { - if (! region_list_append (&g_last, 0, 0)) - goto sbrk_exit; - } - /* Assert invariants */ - assert (g_last); - assert ((char *) g_last->top_reserved - g_last->reserve_size <= (char *) g_last->top_allocated && - g_last->top_allocated <= g_last->top_committed); - assert ((char *) g_last->top_reserved - g_last->reserve_size <= (char *) g_last->top_committed && - g_last->top_committed <= g_last->top_reserved && - (unsigned) g_last->top_committed % g_pagesize == 0); - assert ((unsigned) g_last->top_reserved % g_regionsize == 0); - assert ((unsigned) g_last->reserve_size % g_regionsize == 0); - /* Allocation requested? */ - if (size >= 0) { - /* Allocation size is the requested size */ - long allocate_size = size; - /* Compute the size to commit */ - long to_commit = (char *) g_last->top_allocated + allocate_size - (char *) g_last->top_committed; - /* Do we reach the commit limit? */ - if (to_commit > 0) { - /* Round size to commit */ - long commit_size = CEIL (to_commit, g_my_pagesize); - /* Compute the size to reserve */ - long to_reserve = (char *) g_last->top_committed + commit_size - (char *) g_last->top_reserved; - /* Do we reach the reserve limit? */ - if (to_reserve > 0) { - /* Compute the remaining size to commit in the current region */ - long remaining_commit_size = (char *) g_last->top_reserved - (char *) g_last->top_committed; - if (remaining_commit_size > 0) { - /* Assert preconditions */ - assert ((unsigned) g_last->top_committed % g_pagesize == 0); - assert (0 < remaining_commit_size && remaining_commit_size % g_pagesize == 0); { - /* Commit this */ - void *base_committed = VirtualAlloc (g_last->top_committed, remaining_commit_size, - MEM_COMMIT, PAGE_READWRITE); - /* Check returned pointer for consistency */ - if (base_committed != g_last->top_committed) - goto sbrk_exit; - /* Assert postconditions */ - assert ((unsigned) base_committed % g_pagesize == 0); -#ifdef TRACE - printf ("Commit %p %d\n", base_committed, remaining_commit_size); -#endif - /* Adjust the regions commit top */ - g_last->top_committed = (char *) base_committed + remaining_commit_size; - } - } { - /* Now we are going to search and reserve. */ - int contiguous = -1; - int found = FALSE; - MEMORY_BASIC_INFORMATION memory_info; - void *base_reserved; - long reserve_size; - do { - /* Assume contiguous memory */ - contiguous = TRUE; - /* Round size to reserve */ - reserve_size = CEIL (to_reserve, g_my_regionsize); - /* Start with the current region's top */ - memory_info.BaseAddress = g_last->top_reserved; - /* Assert preconditions */ - assert ((unsigned) memory_info.BaseAddress % g_pagesize == 0); - assert (0 < reserve_size && reserve_size % g_regionsize == 0); - while (VirtualQuery (memory_info.BaseAddress, &memory_info, sizeof (memory_info))) { - /* Assert postconditions */ - assert ((unsigned) memory_info.BaseAddress % g_pagesize == 0); -#ifdef TRACE - printf ("Query %p %d %s\n", memory_info.BaseAddress, memory_info.RegionSize, - memory_info.State == MEM_FREE ? "FREE": - (memory_info.State == MEM_RESERVE ? "RESERVED": - (memory_info.State == MEM_COMMIT ? "COMMITTED": "?"))); -#endif - /* Region is free, well aligned and big enough: we are done */ - if (memory_info.State == MEM_FREE && - (unsigned) memory_info.BaseAddress % g_regionsize == 0 && - memory_info.RegionSize >= (unsigned) reserve_size) { - found = TRUE; - break; - } - /* From now on we can't get contiguous memory! */ - contiguous = FALSE; - /* Recompute size to reserve */ - reserve_size = CEIL (allocate_size, g_my_regionsize); - memory_info.BaseAddress = (char *) memory_info.BaseAddress + memory_info.RegionSize; - /* Assert preconditions */ - assert ((unsigned) memory_info.BaseAddress % g_pagesize == 0); - assert (0 < reserve_size && reserve_size % g_regionsize == 0); - } - /* Search failed? */ - if (! found) - goto sbrk_exit; - /* Assert preconditions */ - assert ((unsigned) memory_info.BaseAddress % g_regionsize == 0); - assert (0 < reserve_size && reserve_size % g_regionsize == 0); - /* Try to reserve this */ - base_reserved = VirtualAlloc (memory_info.BaseAddress, reserve_size, - MEM_RESERVE, PAGE_NOACCESS); - if (! base_reserved) { - int rc = GetLastError (); - if (rc != ERROR_INVALID_ADDRESS) - goto sbrk_exit; - } - /* A null pointer signals (hopefully) a race condition with another thread. */ - /* In this case, we try again. */ - } while (! base_reserved); - /* Check returned pointer for consistency */ - if (memory_info.BaseAddress && base_reserved != memory_info.BaseAddress) - goto sbrk_exit; - /* Assert postconditions */ - assert ((unsigned) base_reserved % g_regionsize == 0); -#ifdef TRACE - printf ("Reserve %p %d\n", base_reserved, reserve_size); -#endif - /* Did we get contiguous memory? */ - if (contiguous) { - long start_size = (char *) g_last->top_committed - (char *) g_last->top_allocated; - /* Adjust allocation size */ - allocate_size -= start_size; - /* Adjust the regions allocation top */ - g_last->top_allocated = g_last->top_committed; - /* Recompute the size to commit */ - to_commit = (char *) g_last->top_allocated + allocate_size - (char *) g_last->top_committed; - /* Round size to commit */ - commit_size = CEIL (to_commit, g_my_pagesize); - } - /* Append the new region to the list */ - if (! region_list_append (&g_last, base_reserved, reserve_size)) - goto sbrk_exit; - /* Didn't we get contiguous memory? */ - if (! contiguous) { - /* Recompute the size to commit */ - to_commit = (char *) g_last->top_allocated + allocate_size - (char *) g_last->top_committed; - /* Round size to commit */ - commit_size = CEIL (to_commit, g_my_pagesize); - } - } - } - /* Assert preconditions */ - assert ((unsigned) g_last->top_committed % g_pagesize == 0); - assert (0 < commit_size && commit_size % g_pagesize == 0); { - /* Commit this */ - void *base_committed = VirtualAlloc (g_last->top_committed, commit_size, - MEM_COMMIT, PAGE_READWRITE); - /* Check returned pointer for consistency */ - if (base_committed != g_last->top_committed) - goto sbrk_exit; - /* Assert postconditions */ - assert ((unsigned) base_committed % g_pagesize == 0); -#ifdef TRACE - printf ("Commit %p %d\n", base_committed, commit_size); -#endif - /* Adjust the regions commit top */ - g_last->top_committed = (char *) base_committed + commit_size; - } - } - /* Adjust the regions allocation top */ - g_last->top_allocated = (char *) g_last->top_allocated + allocate_size; - result = (char *) g_last->top_allocated - size; - /* Deallocation requested? */ - } else if (size < 0) { - long deallocate_size = - size; - /* As long as we have a region to release */ - while ((char *) g_last->top_allocated - deallocate_size < (char *) g_last->top_reserved - g_last->reserve_size) { - /* Get the size to release */ - long release_size = g_last->reserve_size; - /* Get the base address */ - void *base_reserved = (char *) g_last->top_reserved - release_size; - /* Assert preconditions */ - assert ((unsigned) base_reserved % g_regionsize == 0); - assert (0 < release_size && release_size % g_regionsize == 0); { - /* Release this */ - int rc = VirtualFree (base_reserved, 0, - MEM_RELEASE); - /* Check returned code for consistency */ - if (! rc) - goto sbrk_exit; -#ifdef TRACE - printf ("Release %p %d\n", base_reserved, release_size); -#endif - } - /* Adjust deallocation size */ - deallocate_size -= (char *) g_last->top_allocated - (char *) base_reserved; - /* Remove the old region from the list */ - if (! region_list_remove (&g_last)) - goto sbrk_exit; - } { - /* Compute the size to decommit */ - long to_decommit = (char *) g_last->top_committed - ((char *) g_last->top_allocated - deallocate_size); - if (to_decommit >= g_my_pagesize) { - /* Compute the size to decommit */ - long decommit_size = FLOOR (to_decommit, g_my_pagesize); - /* Compute the base address */ - void *base_committed = (char *) g_last->top_committed - decommit_size; - /* Assert preconditions */ - assert ((unsigned) base_committed % g_pagesize == 0); - assert (0 < decommit_size && decommit_size % g_pagesize == 0); { - /* Decommit this */ - int rc = VirtualFree ((char *) base_committed, decommit_size, - MEM_DECOMMIT); - /* Check returned code for consistency */ - if (! rc) - goto sbrk_exit; -#ifdef TRACE - printf ("Decommit %p %d\n", base_committed, decommit_size); -#endif - } - /* Adjust deallocation size and regions commit and allocate top */ - deallocate_size -= (char *) g_last->top_allocated - (char *) base_committed; - g_last->top_committed = base_committed; - g_last->top_allocated = base_committed; - } - } - /* Adjust regions allocate top */ - g_last->top_allocated = (char *) g_last->top_allocated - deallocate_size; - /* Check for underflow */ - if ((char *) g_last->top_reserved - g_last->reserve_size > (char *) g_last->top_allocated || - g_last->top_allocated > g_last->top_committed) { - /* Adjust regions allocate top */ - g_last->top_allocated = (char *) g_last->top_reserved - g_last->reserve_size; - goto sbrk_exit; - } - result = g_last->top_allocated; - } - /* Assert invariants */ - assert (g_last); - assert ((char *) g_last->top_reserved - g_last->reserve_size <= (char *) g_last->top_allocated && - g_last->top_allocated <= g_last->top_committed); - assert ((char *) g_last->top_reserved - g_last->reserve_size <= (char *) g_last->top_committed && - g_last->top_committed <= g_last->top_reserved && - (unsigned) g_last->top_committed % g_pagesize == 0); - assert ((unsigned) g_last->top_reserved % g_regionsize == 0); - assert ((unsigned) g_last->reserve_size % g_regionsize == 0); - -sbrk_exit: -#if defined (USE_MALLOC_LOCK) && defined (NEEDED) - /* Release spin lock */ - slrelease (&g_sl); -#endif - return result; -} - -/* mmap for windows */ -static void *mmap (void *ptr, long size, long prot, long type, long handle, long arg) { - static long g_pagesize; - static long g_regionsize; -#ifdef TRACE - printf ("mmap %d\n", size); -#endif -#if defined (USE_MALLOC_LOCK) && defined (NEEDED) - /* Wait for spin lock */ - slwait (&g_sl); -#endif - /* First time initialization */ - if (! g_pagesize) - g_pagesize = getpagesize (); - if (! g_regionsize) - g_regionsize = getregionsize (); - /* Assert preconditions */ - assert ((unsigned) ptr % g_regionsize == 0); - assert (size % g_pagesize == 0); - /* Allocate this */ - ptr = VirtualAlloc (ptr, size, - MEM_RESERVE | MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE); - if (! ptr) { - ptr = (void *) MORECORE_FAILURE; - goto mmap_exit; - } - /* Assert postconditions */ - assert ((unsigned) ptr % g_regionsize == 0); -#ifdef TRACE - printf ("Commit %p %d\n", ptr, size); -#endif -mmap_exit: -#if defined (USE_MALLOC_LOCK) && defined (NEEDED) - /* Release spin lock */ - slrelease (&g_sl); -#endif - return ptr; -} - -/* munmap for windows */ -static long munmap (void *ptr, long size) { - static long g_pagesize; - static long g_regionsize; - int rc = MUNMAP_FAILURE; -#ifdef TRACE - printf ("munmap %p %d\n", ptr, size); -#endif -#if defined (USE_MALLOC_LOCK) && defined (NEEDED) - /* Wait for spin lock */ - slwait (&g_sl); -#endif - /* First time initialization */ - if (! g_pagesize) - g_pagesize = getpagesize (); - if (! g_regionsize) - g_regionsize = getregionsize (); - /* Assert preconditions */ - assert ((unsigned) ptr % g_regionsize == 0); - assert (size % g_pagesize == 0); - /* Free this */ - if (! VirtualFree (ptr, 0, - MEM_RELEASE)) - goto munmap_exit; - rc = 0; -#ifdef TRACE - printf ("Release %p %d\n", ptr, size); -#endif -munmap_exit: -#if defined (USE_MALLOC_LOCK) && defined (NEEDED) - /* Release spin lock */ - slrelease (&g_sl); -#endif - return rc; -} - -static void vminfo (unsigned long *free, unsigned long *reserved, unsigned long *committed) { - MEMORY_BASIC_INFORMATION memory_info; - memory_info.BaseAddress = 0; - *free = *reserved = *committed = 0; - while (VirtualQuery (memory_info.BaseAddress, &memory_info, sizeof (memory_info))) { - switch (memory_info.State) { - case MEM_FREE: - *free += memory_info.RegionSize; - break; - case MEM_RESERVE: - *reserved += memory_info.RegionSize; - break; - case MEM_COMMIT: - *committed += memory_info.RegionSize; - break; - } - memory_info.BaseAddress = (char *) memory_info.BaseAddress + memory_info.RegionSize; - } -} - -static int cpuinfo (int whole, unsigned long *kernel, unsigned long *user) { - if (whole) { - __int64 creation64, exit64, kernel64, user64; - int rc = GetProcessTimes (GetCurrentProcess (), - (FILETIME *) &creation64, - (FILETIME *) &exit64, - (FILETIME *) &kernel64, - (FILETIME *) &user64); - if (! rc) { - *kernel = 0; - *user = 0; - return FALSE; - } - *kernel = (unsigned long) (kernel64 / 10000); - *user = (unsigned long) (user64 / 10000); - return TRUE; - } else { - __int64 creation64, exit64, kernel64, user64; - int rc = GetThreadTimes (GetCurrentThread (), - (FILETIME *) &creation64, - (FILETIME *) &exit64, - (FILETIME *) &kernel64, - (FILETIME *) &user64); - if (! rc) { - *kernel = 0; - *user = 0; - return FALSE; - } - *kernel = (unsigned long) (kernel64 / 10000); - *user = (unsigned long) (user64 / 10000); - return TRUE; - } -} - -#endif /* WIN32 */ - -/* ------------------------------------------------------------ -History: - - V2.7.0 Sun Mar 11 14:14:06 2001 Doug Lea (dl at gee) - * Introduce independent_comalloc and independent_calloc. - Thanks to Michael Pachos for motivation and help. - * Make optional .h file available - * Allow > 2GB requests on 32bit systems. - * new WIN32 sbrk, mmap, munmap, lock code from . - Thanks also to Andreas Mueller , - and Anonymous. - * Allow override of MALLOC_ALIGNMENT (Thanks to Ruud Waij for - helping test this.) - * memalign: check alignment arg - * realloc: don't try to shift chunks backwards, since this - leads to more fragmentation in some programs and doesn't - seem to help in any others. - * Collect all cases in malloc requiring system memory into sYSMALLOc - * Use mmap as backup to sbrk - * Place all internal state in malloc_state - * Introduce fastbins (although similar to 2.5.1) - * Many minor tunings and cosmetic improvements - * Introduce USE_PUBLIC_MALLOC_WRAPPERS, USE_MALLOC_LOCK - * Introduce MALLOC_FAILURE_ACTION, MORECORE_CONTIGUOUS - Thanks to Tony E. Bennett and others. - * Include errno.h to support default failure action. - - V2.6.6 Sun Dec 5 07:42:19 1999 Doug Lea (dl at gee) - * return null for negative arguments - * Added Several WIN32 cleanups from Martin C. Fong - * Add 'LACKS_SYS_PARAM_H' for those systems without 'sys/param.h' - (e.g. WIN32 platforms) - * Cleanup header file inclusion for WIN32 platforms - * Cleanup code to avoid Microsoft Visual C++ compiler complaints - * Add 'USE_DL_PREFIX' to quickly allow co-existence with existing - memory allocation routines - * Set 'malloc_getpagesize' for WIN32 platforms (needs more work) - * Use 'assert' rather than 'ASSERT' in WIN32 code to conform to - usage of 'assert' in non-WIN32 code - * Improve WIN32 'sbrk()' emulation's 'findRegion()' routine to - avoid infinite loop - * Always call 'fREe()' rather than 'free()' - - V2.6.5 Wed Jun 17 15:57:31 1998 Doug Lea (dl at gee) - * Fixed ordering problem with boundary-stamping - - V2.6.3 Sun May 19 08:17:58 1996 Doug Lea (dl at gee) - * Added pvalloc, as recommended by H.J. Liu - * Added 64bit pointer support mainly from Wolfram Gloger - * Added anonymously donated WIN32 sbrk emulation - * Malloc, calloc, getpagesize: add optimizations from Raymond Nijssen - * malloc_extend_top: fix mask error that caused wastage after - foreign sbrks - * Add linux mremap support code from HJ Liu - - V2.6.2 Tue Dec 5 06:52:55 1995 Doug Lea (dl at gee) - * Integrated most documentation with the code. - * Add support for mmap, with help from - Wolfram Gloger (Gloger@lrz.uni-muenchen.de). - * Use last_remainder in more cases. - * Pack bins using idea from colin@nyx10.cs.du.edu - * Use ordered bins instead of best-fit threshhold - * Eliminate block-local decls to simplify tracing and debugging. - * Support another case of realloc via move into top - * Fix error occuring when initial sbrk_base not word-aligned. - * Rely on page size for units instead of SBRK_UNIT to - avoid surprises about sbrk alignment conventions. - * Add mallinfo, mallopt. Thanks to Raymond Nijssen - (raymond@es.ele.tue.nl) for the suggestion. - * Add `pad' argument to malloc_trim and top_pad mallopt parameter. - * More precautions for cases where other routines call sbrk, - courtesy of Wolfram Gloger (Gloger@lrz.uni-muenchen.de). - * Added macros etc., allowing use in linux libc from - H.J. Lu (hjl@gnu.ai.mit.edu) - * Inverted this history list - - V2.6.1 Sat Dec 2 14:10:57 1995 Doug Lea (dl at gee) - * Re-tuned and fixed to behave more nicely with V2.6.0 changes. - * Removed all preallocation code since under current scheme - the work required to undo bad preallocations exceeds - the work saved in good cases for most test programs. - * No longer use return list or unconsolidated bins since - no scheme using them consistently outperforms those that don't - given above changes. - * Use best fit for very large chunks to prevent some worst-cases. - * Added some support for debugging - - V2.6.0 Sat Nov 4 07:05:23 1995 Doug Lea (dl at gee) - * Removed footers when chunks are in use. Thanks to - Paul Wilson (wilson@cs.texas.edu) for the suggestion. - - V2.5.4 Wed Nov 1 07:54:51 1995 Doug Lea (dl at gee) - * Added malloc_trim, with help from Wolfram Gloger - (wmglo@Dent.MED.Uni-Muenchen.DE). - - V2.5.3 Tue Apr 26 10:16:01 1994 Doug Lea (dl at g) - - V2.5.2 Tue Apr 5 16:20:40 1994 Doug Lea (dl at g) - * realloc: try to expand in both directions - * malloc: swap order of clean-bin strategy; - * realloc: only conditionally expand backwards - * Try not to scavenge used bins - * Use bin counts as a guide to preallocation - * Occasionally bin return list chunks in first scan - * Add a few optimizations from colin@nyx10.cs.du.edu - - V2.5.1 Sat Aug 14 15:40:43 1993 Doug Lea (dl at g) - * faster bin computation & slightly different binning - * merged all consolidations to one part of malloc proper - (eliminating old malloc_find_space & malloc_clean_bin) - * Scan 2 returns chunks (not just 1) - * Propagate failure in realloc if malloc returns 0 - * Add stuff to allow compilation on non-ANSI compilers - from kpv@research.att.com - - V2.5 Sat Aug 7 07:41:59 1993 Doug Lea (dl at g.oswego.edu) - * removed potential for odd address access in prev_chunk - * removed dependency on getpagesize.h - * misc cosmetics and a bit more internal documentation - * anticosmetics: mangled names in macros to evade debugger strangeness - * tested on sparc, hp-700, dec-mips, rs6000 - with gcc & native cc (hp, dec only) allowing - Detlefs & Zorn comparison study (in SIGPLAN Notices.) - - Trial version Fri Aug 28 13:14:29 1992 Doug Lea (dl at g.oswego.edu) - * Based loosely on libg++-1.2X malloc. (It retains some of the overall - structure of old version, but most details differ.) - -*/ diff --git a/Code/BF2/External/base/grid_index.h b/Code/BF2/External/base/grid_index.h deleted file mode 100644 index 28e5c4cb9..000000000 --- a/Code/BF2/External/base/grid_index.h +++ /dev/null @@ -1,778 +0,0 @@ -// grid_index.h -- Thatcher Ulrich 2004 - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - -// Simple grid-based spatial index container. - -#ifndef GRID_INDEX_H -#define GRID_INDEX_H - - -#include "base/tu_config.h" -#include "base/container.h" - - -// -// grid_index_point -// - - -template -struct index_point -// Simple point class for spatial index. -{ - index_point() {} - index_point(coord_t x_in, coord_t y_in) - : - x(x_in), - y(y_in) - { - } - - bool operator==(const index_point& pt) const - { - return x == pt.x && y == pt.y; - } - -//data: - coord_t x, y; -}; - - -template -struct index_box -// Simple bounding box class. -{ - index_box() {} - index_box(const index_point& min_max_in) - : - min(min_max_in), - max(min_max_in) - { - } - index_box(const index_point& min_in, const index_point& max_in) - : - min(min_in), - max(max_in) - { - } - - coord_t get_width() const { return max.x - min.x; } - coord_t get_height() const { return max.y - min.y; } - - void expand_to_enclose(const index_point& loc) - { - if (loc.x < min.x) min.x = loc.x; - if (loc.y < min.y) min.y = loc.y; - if (loc.x > max.x) max.x = loc.x; - if (loc.y > max.y) max.y = loc.y; - } - - bool contains_point(const index_point& loc) const - { - if (loc.x >= min.x && loc.x <= max.x && loc.y >= min.y && loc.y <= max.y) - { - return true; - } - else - { - return false; - } - } - -//data: - index_point min; - index_point max; -}; - - -template -struct grid_entry_point -// Holds one entry for a grid point cell. -{ - index_point location; - payload_t value; - - grid_entry_point* m_next; -}; - - -template -struct grid_index_point -// Grid-based container for points. -{ - typedef index_point point_t; - typedef index_box box_t; - typedef grid_entry_point grid_entry_t; - - grid_index_point(const box_t& bound, int x_cells, int y_cells) - : - m_bound(bound), - m_x_cells(x_cells), - m_y_cells(y_cells) - { - assert(x_cells > 0 && y_cells > 0); - assert(bound.min.x <= bound.max.x); - assert(bound.min.y <= bound.max.y); - - // Allocate the grid. - m_grid = new grid_entry_t*[x_cells * y_cells]; - memset(&m_grid[0], 0, sizeof(grid_entry_t*) * x_cells * y_cells); - } - - ~grid_index_point() - { - for (int y = 0; y < m_y_cells; y++) - { - for (int x = 0; x < m_x_cells; x++) - { - grid_entry_t* e = get_cell(x, y); - while (e) - { - grid_entry_t* next = e->m_next; - delete e; - e = next; - } - } - } - - delete [] m_grid; - } - - const box_t& get_bound() const { return m_bound; } - - struct iterator - { - grid_index_point* m_index; - box_t m_query; - index_box m_query_cells; - int m_current_cell_x, m_current_cell_y; - grid_entry_t* m_current_entry; - - iterator() - : - m_index(NULL), - m_query(point_t(0, 0), point_t(0, 0)), - m_query_cells(index_point(0, 0), index_point(0, 0)), - m_current_cell_x(0), - m_current_cell_y(0), - m_current_entry(NULL) - { - } - - bool at_end() const { return m_current_entry == NULL; } - - void operator++() - { - if (at_end() == false) - { - advance(); - } - } - - void advance() - // Point at next element in the iteration. - { - if (m_current_entry) - { - // Continue through current cell. - m_current_entry = m_current_entry->m_next; - - if (at_end() == false) - { - return; - } - } - assert(m_current_entry == NULL); - - // Done with current cell; go to next cell. - m_current_cell_x++; - while (m_current_cell_y <= m_query_cells.max.y) - { - for (;;) - { - if (m_current_cell_x > m_query_cells.max.x) - { - break; - } - - m_current_entry = m_index->get_cell(m_current_cell_x, m_current_cell_y); - if (m_current_entry) - { - // Found a valid cell. - return; - } - - m_current_cell_x++; - } - m_current_cell_x = m_query_cells.min.x; - m_current_cell_y++; - } - - assert(m_current_cell_x == m_query_cells.min.x); - assert(m_current_cell_y == m_query_cells.max.y + 1); - - // No more valid cells. - assert(at_end()); - } - - grid_entry_t& operator*() - { - assert(at_end() == false && m_current_entry != NULL); - return *m_current_entry; - } - grid_entry_t* operator->() { return &(operator*()); } - - // @@ TODO Finish - // - //bool operator==(const const_iterator& it) const - //{ - // if (at_end() && it.at_end()) - // { - // return true; - // } - // else - // { - // return - // m_hash == it.m_hash - // && m_index == it.m_index; - // } - //} - // - //bool operator!=(const const_iterator& it) const { return ! (*this == it); } - }; - - iterator begin(const box_t& q) - { - iterator it; - it.m_index = this; - it.m_query = q; - it.m_query_cells.min = get_containing_cell_clamped(q.min); - it.m_query_cells.max = get_containing_cell_clamped(q.max); - - assert(it.m_query_cells.min.x <= it.m_query_cells.max.x); - assert(it.m_query_cells.min.y <= it.m_query_cells.max.y); - - it.m_current_cell_x = it.m_query_cells.min.x; - it.m_current_cell_y = it.m_query_cells.min.y; - it.m_current_entry = get_cell(it.m_current_cell_x, it.m_current_cell_y); - - // Make sure iterator starts valid. - if (it.m_current_entry == NULL) - { - it.advance(); - } - - return it; - } - - iterator end() const - { - iterator it; - it.m_index = this; - it.m_current_entry = NULL; - - return it; - } - - void add(const point_t& location, payload p) - // Insert a point, with the given location and payload, into - // our index. - { - index_point ip = get_containing_cell_clamped(location); - - grid_entry_t* new_entry = new grid_entry_t; - new_entry->location = location; - new_entry->value = p; - - // Link it into the containing cell. - int index = get_cell_index(ip); - new_entry->m_next = m_grid[index]; - m_grid[index] = new_entry; - } - - void remove(grid_entry_t* entry) - // Removes the entry from the index, and deletes it. - { - assert(entry); - - index_point ip = get_containing_cell_clamped(entry->location); - int index = get_cell_index(ip); - - // Unlink matching entry. - grid_entry_t** prev_ptr = &m_grid[index]; - grid_entry_t* ptr = *prev_ptr; - while (ptr) - { - if (ptr == entry) - { - // This is the one; unlink it. - *prev_ptr = ptr->m_next; - - delete entry; - - return; - } - - // Go to the next entry. - prev_ptr = &ptr->m_next; - ptr = *prev_ptr; - } - - // Didn't find entry! Something is wrong. - assert(0); - } - - iterator find(const point_t& location, payload p) - // Helper. Search for matching entry. - { - iterator it; - for (it = begin(box_t(location, location)); ! it.at_end(); ++it) - { - if (it->location == location && it->value == p) - { - // Found it. - return it; - } - } - - // Didn't find it. - assert(it.at_end()); - return it; - } - -private: - - grid_entry_t* get_cell(int x, int y) - { - assert(x >= 0 && x < m_x_cells); - assert(y >= 0 && y < m_y_cells); - - return m_grid[x + y * m_x_cells]; - } - - int get_cell_index(const index_point& ip) - { - assert(ip.x >= 0 && ip.x < m_x_cells); - assert(ip.y >= 0 && ip.y < m_y_cells); - - int index = ip.x + ip.y * m_x_cells; - - return index; - } - - index_point get_containing_cell_clamped(const point_t& p) - // Get the indices of the cell that contains the given point. - { - index_point ip; - ip.x = int(((p.x - m_bound.min.x) * coord_t(m_x_cells)) / (m_bound.max.x - m_bound.min.x)); - ip.y = int(((p.y - m_bound.min.y) * coord_t(m_y_cells)) / (m_bound.max.y - m_bound.min.y)); - - // Clamp. - if (ip.x < 0) ip.x = 0; - if (ip.x >= m_x_cells) ip.x = m_x_cells - 1; - if (ip.y < 0) ip.y = 0; - if (ip.y >= m_y_cells) ip.y = m_y_cells - 1; - - return ip; - } - -//data: - box_t m_bound; - int m_x_cells; - int m_y_cells; - grid_entry_t** m_grid; -}; - - -// -// grid_index_box -// - - -template -struct grid_entry_box -// Holds one entry for a grid cell. -{ - index_box bound; - payload value; - - int m_last_query_id; // avoid returning the same item multiple times - - grid_entry_box() : m_last_query_id(0) {} -}; - - -template -struct grid_index_box -// Grid-based container for boxes. -{ - typedef index_point point_t; - typedef index_box box_t; - typedef grid_entry_box grid_entry_t; - - grid_index_box(const box_t& bound, int x_cells, int y_cells) - : - m_bound(bound), - m_x_cells(x_cells), - m_y_cells(y_cells), - m_query_id(0) - { - assert(x_cells > 0 && y_cells > 0); - assert(bound.min.x <= bound.max.x); - assert(bound.min.y <= bound.max.y); - - // Allocate the grid. - m_grid = new array[x_cells * y_cells]; - } - - ~grid_index_box() - { - // Need to delete all entries (be careful to only - // delete each entry once, even though entries may be - // repeated many times). - for (iterator it = begin_all(); ! it.at_end(); ++it) - { - index_point ip = get_containing_cell_clamped(it->bound.max); - if (ip.x == it.m_current_cell_x && ip.y == it.m_current_cell_y) - { - // This is the last time this entry - // appears in the index. Delete it. - delete it.m_current_entry; - } - } - - delete [] m_grid; - } - - const box_t& get_bound() const { return m_bound; } - int get_query_id() const { return m_query_id; } - - struct iterator - { - grid_index_box* m_index; - box_t m_query; - index_box m_query_cells; - int m_current_cell_x, m_current_cell_y; - int m_current_cell_array_index; - grid_entry_t* m_current_entry; - - iterator() - : - m_index(NULL), - m_query(point_t(0, 0), point_t(0, 0)), - m_query_cells(index_point(0, 0), index_point(0, 0)), - m_current_cell_x(0), - m_current_cell_y(0), - m_current_cell_array_index(-1), - m_current_entry(NULL) - { - } - - bool at_end() const { return m_current_entry == NULL; } - - void operator++() - { - if (at_end() == false) - { - advance(); - } - } - - void advance() - // Point at next element in the iteration. - { - if (advance_in_cell()) - { - return; - } - - // Done with current cell; go to next cell. - m_current_cell_x++; - while (m_current_cell_y <= m_query_cells.max.y) - { - for (;;) - { - if (m_current_cell_x > m_query_cells.max.x) - { - break; - } - - if (advance_in_cell()) - { - // We're good. - return; - } - - m_current_cell_x++; - } - m_current_cell_x = m_query_cells.min.x; - m_current_cell_y++; - } - - assert(m_current_cell_x == m_query_cells.min.x); - assert(m_current_cell_y == m_query_cells.max.y + 1); - - // No more valid cells. - assert(at_end()); - } - - bool advance_in_cell() - // Go to the next valid element in the current cell. - // If we reach the end of the cell, set - // m_current_cell_array_index to -1 and return false. - // Otherwise point m_current_entry at the valid - // element, and return true. - { - int query_id = m_index->get_query_id(); - array* cell_array = m_index->get_cell(m_current_cell_x, m_current_cell_y); - - while (++m_current_cell_array_index < cell_array->size()) - { - // Continue through the current cell. - m_current_entry = (*cell_array)[m_current_cell_array_index]; - if (m_current_entry->m_last_query_id == query_id) - { - // Skip this one; we already iterated over it. - } - else - { - // Valid entry. - - // Update query id. - m_current_entry->m_last_query_id = query_id; - - return true; - } - } - - // No more valid entries in this cell. - m_current_entry = NULL; - m_current_cell_array_index = -1; - - return false; - } - - grid_entry_t& operator*() - { - assert(at_end() == false && m_current_entry != NULL); - return *m_current_entry; - } - grid_entry_t* operator->() { return &(operator*()); } - - // @@ TODO Finish - // - //bool operator==(const const_iterator& it) const - //{ - // if (at_end() && it.at_end()) - // { - // return true; - // } - // else - // { - // return - // m_hash == it.m_hash - // && m_index == it.m_index; - // } - //} - // - //bool operator!=(const const_iterator& it) const { return ! (*this == it); } - }; - - iterator begin(const box_t& q) - { - m_query_id++; - if (m_query_id == 0) - { - // Query id wrapped around! Clear m_last_query_id in all entries in our - // array, to avoid aliasing from old queries. - int cell_count = m_x_cells * m_y_cells; - for (int i = 0; i < cell_count; i++) - { - array* cell_array = &m_grid[i]; - for (int j = 0, n = cell_array->size(); j < n; j++) - { - (*cell_array)[j]->m_last_query_id = 0; - } - } - m_query_id = 1; - } - - iterator it; - it.m_index = this; - it.m_query = q; - it.m_query_cells.min = get_containing_cell_clamped(q.min); - it.m_query_cells.max = get_containing_cell_clamped(q.max); - - assert(it.m_query_cells.min.x <= it.m_query_cells.max.x); - assert(it.m_query_cells.min.y <= it.m_query_cells.max.y); - - it.m_current_cell_x = it.m_query_cells.min.x; - it.m_current_cell_y = it.m_query_cells.min.y; - - it.advance(); // find first valid entry. - - return it; - } - - iterator begin_all() - // For convenience. - { - return begin(get_bound()); - } - - iterator end() const - { - iterator it; - it.m_index = this; - it.m_current_entry = NULL; - - return it; - } - - void add(const box_t& bound, payload p) - // Insert a box, with the given payload, into our index. - { - index_box ib = get_containing_cells_clamped(bound); - - grid_entry_t* new_entry = new grid_entry_t; - new_entry->bound = bound; - new_entry->value = p; - - // Add it to all cells it overlaps with. - for (int iy = ib.min.y; iy <= ib.max.y; iy++) - { - for (int ix = ib.min.x; ix <= ib.max.x; ix++) - { - array* cell_array = get_cell(ix, iy); - cell_array->push_back(new_entry); - } - } - } - - - void remove(grid_entry_t* entry) - // Removes the entry from the index, and deletes it. - { - assert(entry); - - // Find and remove the entry from all cells that it overlaps with. - index_box ib = get_containing_cells_clamped(entry->bound); - - for (int iy = ib.min.y; iy <= ib.max.y; iy++) - { - for (int ix = ib.min.x; ix <= ib.max.x; ix++) - { - array* cell_array = get_cell(ix, iy); - - int i, n; - for (i = 0, n = cell_array->size(); i < n; i++) - { - // Find entry, and remove it. - if ((*cell_array)[i] == entry) - { - cell_array->remove(i); - break; - } - } - - assert(i < n); // Didn't find entry in this cell! Something is wrong. - } - } - - delete entry; - } - - - iterator find(const box_t& bound, payload p) - // Helper. Search for matching entry. - { - iterator it; - for (it = begin(bound); ! it.at_end(); ++it) - { - if (it->bound == bound && it->value == p) - { - // Found it. - return it; - } - } - - // Didn't find it. - assert(it.at_end()); - return it; - } - - grid_entry_t* find_payload_from_point(const index_point& loc, payload p) - // Helper. Search for matching payload, given any point within its bound. - // Should be relatively quick, assuming payload is unique. - { - index_point ip = get_containing_cell_clamped(loc); - array* cell_array = get_cell(ip.x, ip.y); - - for (int i = 0, n = cell_array->size(); i < n; i++) - { - grid_entry_t* entry = (*cell_array)[i]; - if (entry->value == p) - { - // Found it. - return entry; - } - } - - // Didn't find it. - return NULL; - } - -private: - - array* get_cell(int x, int y) - { - assert(x >= 0 && x < m_x_cells); - assert(y >= 0 && y < m_y_cells); - - return &m_grid[x + y * m_x_cells]; - } - - index_point get_containing_cell_clamped(const point_t& p) const - // Get the indices of the cell that contains the given point. - { - index_point ip; - ip.x = int(((p.x - m_bound.min.x) * coord_t(m_x_cells)) / (m_bound.max.x - m_bound.min.x)); - ip.y = int(((p.y - m_bound.min.y) * coord_t(m_y_cells)) / (m_bound.max.y - m_bound.min.y)); - - // Clamp. - if (ip.x < 0) ip.x = 0; - if (ip.x >= m_x_cells) ip.x = m_x_cells - 1; - if (ip.y < 0) ip.y = 0; - if (ip.y >= m_y_cells) ip.y = m_y_cells - 1; - - return ip; - } - - index_box get_containing_cells_clamped(const box_t& p) const - // Get the indices of the cell that contains the given point. - { - index_box ib(get_containing_cell_clamped(p.min), get_containing_cell_clamped(p.max)); - return ib; - } - -//data: - box_t m_bound; - int m_x_cells; - int m_y_cells; - int m_query_id; - array* m_grid; -}; - - -#endif // GRID_INDEX_H - - -// Local Variables: -// mode: C++ -// c-basic-offset: 8 -// tab-width: 8 -// indent-tabs-mode: t -// End: - diff --git a/Code/BF2/External/base/hash_capacity.h b/Code/BF2/External/base/hash_capacity.h new file mode 100644 index 000000000..5643566a0 --- /dev/null +++ b/Code/BF2/External/base/hash_capacity.h @@ -0,0 +1,34 @@ +// This source code has been donated to the Public Domain. + +#ifndef TU_HASH_CAPACITY_H +#define TU_HASH_CAPACITY_H + +#include + +namespace tu_util { + +// Returns the raw bucket-count bits for a positive signed 32-bit request. +// The table reproduces SwiffPlayer's 24-bit, nearest-rounding arithmetic; +// inherited 53/64-bit precision and directed rounding have different tables. +inline uint32_t hash_raw_capacity(int requested_size) +{ + static_assert(sizeof(int) == 4, "SwiffPlayer capacity requests are 32-bit"); + static const int transitions[] = { + 2, 3, 5, 9, 17, 33, 65, 129, 257, 513, 1025, 2049, + 4097, 8193, 16385, 32769, 65537, 131073, 262145, 524289, + 1048577, 2097153, 4194304, 8388606, 16777210, 33554419, + 67108837, 134217674, 268435350, 536870703, 1073741414, 2147482846 + }; + unsigned lo = 0, hi = sizeof(transitions) / sizeof(transitions[0]); + while (lo < hi) + { + const unsigned mid = lo + (hi - lo) / 2; + if (requested_size < transitions[mid]) hi = mid; + else lo = mid + 1; + } + return uint32_t(1) << (lo & 31u); +} + +} // namespace tu_util + +#endif diff --git a/Code/BF2/External/base/logger.cpp b/Code/BF2/External/base/logger.cpp deleted file mode 100644 index 3e4506709..000000000 --- a/Code/BF2/External/base/logger.cpp +++ /dev/null @@ -1,110 +0,0 @@ -// logger.cpp -- Thatcher Ulrich 2006 - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - -// Helpers for logging messages & errors. - - -#include "base/logger.h" - -#include -#include - - -namespace logger -{ - // Function pointer to log callback. - static void (*s_log_callback)(log_type e, const char* message) = NULL; - - void register_log_callback(void (*callback)(log_type e, const char* message)) - // The host app can use this to install a function to receive log - // & error messages from gameswf. - // - // Pass in NULL to inhibit logging of messages & errors. - { - s_log_callback = callback; - } - - - void register_log_callback(void (*callback)(log_type e, const char* message)); - - - void standard_logger(log_type e, const char* message) - { - if (e == ERROR) { - fprintf(stderr, message); - } else { - // NORMAL or VERBOSE - printf(message); - } - } - - - // Log to stdout/stderr. - void set_standard_log_handlers() - { - register_log_callback(standard_logger); - } - - - // Toggle this to enable verbose logging by the standard log - // handlers. - extern bool FLAG_verbose_log = false; - - -#ifdef _WIN32 -#define vsnprintf _vsnprintf -#endif // _WIN32 - - static const int BUFFER_SIZE = 500; - -#define FORMAT_INTO_BUFFER(fmt) \ - char buffer[BUFFER_SIZE]; \ - va_list ap; \ - va_start(ap, fmt); \ - vsnprintf(buffer, BUFFER_SIZE, fmt, ap);\ - va_end(ap); - - - void vmsg(const char* fmt, ...) - // Printf-style informational log. - { - if (FLAG_verbose_log && s_log_callback) - { - FORMAT_INTO_BUFFER(fmt); - s_log_callback(VERBOSE, buffer); - } - } - - - void msg(const char* fmt, ...) - // Printf-style informational log. - { - if (s_log_callback) - { - FORMAT_INTO_BUFFER(fmt); - s_log_callback(NORMAL, buffer); - } - } - - - void error(const char* fmt, ...) - // Printf-style error log. - { - if (s_log_callback) - { - FORMAT_INTO_BUFFER(fmt); - s_log_callback(ERROR, buffer); - } - } -} - - -// Local Variables: -// mode: C++ -// c-basic-offset: 8 -// tab-width: 8 -// indent-tabs-mode: t -// End: - diff --git a/Code/BF2/External/base/logger.h b/Code/BF2/External/base/logger.h deleted file mode 100644 index f9d1c76be..000000000 --- a/Code/BF2/External/base/logger.h +++ /dev/null @@ -1,63 +0,0 @@ -// logger.h -- Thatcher Ulrich 2006 - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - -// Helpers for logging messages & errors. - - -#ifndef BASE_LOGGER_H -#define BASE_LOGGER_H - - -namespace logger -{ - // Log to stdout/stderr. - void set_standard_log_handlers(); - - // Toggle this to enable verbose logging by the standard log - // handlers. - extern bool FLAG_verbose_log; - - // Use this to register your own log handler. If you don't - // register a log handler, the logs don't go anywhere. - enum log_type { - VERBOSE, - NORMAL, - ERROR, - }; - void register_log_callback(void (*callback)(log_type e, const char* message)); - - - // gcc has some nice printf arg checking stuff. -#ifdef __GNUC__ - #define ATTRCHECK __attribute__((format (printf, 1, 2))) -#else - #define ATTRCHECK -#endif - - // These are the logging functions. Printf-style interfaces. - - // Verbose log. - void vmsg(const char* fmt, ...) ATTRCHECK; - // Normal log. - void msg(const char* fmt, ...) ATTRCHECK; - // Error log. - void error(const char* fmt, ...) ATTRCHECK; -} - -// Shorter aliases for the logging functions. TODO add __FILE__, __LINE__ etc. -#define LOG logger::msg -#define VLOG logger::vmsg -#define LOGERROR logger::error - - -#endif // BASE_LOGGER_H - - -// Local Variables: -// mode: C++ -// c-basic-offset: 8 -// tab-width: 8 -// indent-tabs-mode: t -// End: diff --git a/Code/BF2/External/base/ogl.cpp b/Code/BF2/External/base/ogl.cpp deleted file mode 100644 index 200a1bfa0..000000000 --- a/Code/BF2/External/base/ogl.cpp +++ /dev/null @@ -1,441 +0,0 @@ -// ogl.cpp -- by Thatcher Ulrich - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - -// Some OpenGL helpers; mainly to generically deal with extensions. - - -#include -#include "base/ogl.h" -#include "base/utility.h" -#include -#include - - -namespace ogl { - - bool is_open = false; - - // Pointers to extension functions. - typedef void * (APIENTRY * PFNWGLALLOCATEMEMORYNVPROC) (int size, float readfreq, float writefreq, float priority); - typedef void (APIENTRY * PFNWGLFREEMEMORYNVPROC) (void *pointer); - typedef void (APIENTRY * PFNGLVERTEXARRAYRANGENVPROC) (int size, void* buffer); - typedef void (APIENTRY * PFNGLGENFENCESNVPROC) (GLsizei n, GLuint *fence_array); - typedef void (APIENTRY * PFNGLSETFENCENVPROC) (GLuint fence_id, GLenum condition); - typedef void (APIENTRY * PFNGLFINISHFENCENVPROC) (GLuint fence_id); - - typedef void (APIENTRY * PFNGLACTIVETEXTUREARBPROC) (GLenum texture); - typedef void (APIENTRY * PFNGLCLIENTACTIVETEXTUREARBPROC) (GLenum texture); - typedef void (APIENTRY * PFNGLMULTITEXCOORD2FARBPROC) (GLenum target, GLfloat s, GLfloat t); - typedef void (APIENTRY * PFNGLMULTITEXCOORD2FVARBPROC) (GLenum target, const GLfloat *v); - - PFNWGLALLOCATEMEMORYNVPROC wglAllocateMemoryNV = 0; - PFNWGLFREEMEMORYNVPROC wglFreeMemoryNV = 0; - PFNGLVERTEXARRAYRANGENVPROC glVertexArrayRangeNV = 0; - PFNGLGENFENCESNVPROC glGenFencesNV = 0; - PFNGLSETFENCENVPROC glSetFenceNV = 0; - PFNGLFINISHFENCENVPROC glFinishFenceNV = 0; - - PFNGLACTIVETEXTUREARBPROC glActiveTextureARB = 0; - PFNGLCLIENTACTIVETEXTUREARBPROC glClientActiveTextureARB = 0; - PFNGLMULTITEXCOORD2FARBPROC glMultiTexCoord2fARB = 0; - PFNGLMULTITEXCOORD2FVARBPROC glMultiTexCoord2fvARB = 0; - - - // GL_CLAMP or GL_CLAMP_TO_EDGE, depending on which is available. - int s_clamp_to_edge = GL_CLAMP; - - // Big, fast vertex-memory buffer. - const int VERTEX_BUFFER_SIZE = 4 << 20; - void* vertex_memory_buffer = 0; - int vertex_memory_top = 0; - bool vertex_memory_from_malloc = false; // tells us whether to wglFreeMemoryNV() or free() the buffer when we're done. - - - const int STREAM_SUB_BUFFER_COUNT = 2; - - class vertex_stream - { - // Class to facilitate streaming verts to the video card. Takes - // care of fencing, and buffer bookkeeping. - public: - vertex_stream(int buffer_size); - ~vertex_stream(); - - void* reserve_memory(int size); - void flush_combiners(); - - private: - int m_sub_buffer_size; - int m_buffer_top; - void* m_buffer; - int m_extra_bytes; // extra bytes after last block; used to pad up to write-combiner alignment - - unsigned int m_fence[4]; - }; - - - vertex_stream* s_stream = NULL; - - - void open() - // Scan for extensions. - { - wglAllocateMemoryNV = (PFNWGLALLOCATEMEMORYNVPROC) SDL_GL_GetProcAddress( PROC_NAME_PREFIX "AllocateMemoryNV" ); - wglFreeMemoryNV = (PFNWGLFREEMEMORYNVPROC) SDL_GL_GetProcAddress( PROC_NAME_PREFIX "FreeMemoryNV" ); - glVertexArrayRangeNV = (PFNGLVERTEXARRAYRANGENVPROC) SDL_GL_GetProcAddress( "glVertexArrayRangeNV" ); - - glGenFencesNV = (PFNGLGENFENCESNVPROC) SDL_GL_GetProcAddress( "glGenFencesNV" ); - glSetFenceNV = (PFNGLSETFENCENVPROC) SDL_GL_GetProcAddress( "glSetFenceNV" ); - glFinishFenceNV = (PFNGLFINISHFENCENVPROC) SDL_GL_GetProcAddress( "glFinishFenceNV" ); - - glActiveTextureARB = (PFNGLACTIVETEXTUREARBPROC) SDL_GL_GetProcAddress("glActiveTextureARB"); - glClientActiveTextureARB = (PFNGLCLIENTACTIVETEXTUREARBPROC) SDL_GL_GetProcAddress("glClientActiveTextureARB"); - glMultiTexCoord2fARB = (PFNGLMULTITEXCOORD2FARBPROC) SDL_GL_GetProcAddress("glMultiTexCoord2fARB"); - glMultiTexCoord2fvARB = (PFNGLMULTITEXCOORD2FVARBPROC) SDL_GL_GetProcAddress("glMultiTexCoord2fvARB"); - - if (check_extension("GL_SGIS_texture_edge_clamp") - || check_extension("GL_EXT_texture_edge_clamp")) - { - // Use CLAMP_TO_EDGE, since it's available. - s_clamp_to_edge = GL_CLAMP_TO_EDGE; - } - } - - - void close() - // Release anything we need to. - { - // @@ free that mongo vertex buffer. - } - - - int get_clamp_mode() - // Return a constant to pass to glTexParameteri(GL_TEXTURE_2D, - // GL_TEXTURE_WRAP_x, ...), which is either GL_CLAMP or - // GL_CLAMP_TO_EDGE, depending on whether GL_CLAMP_TO_EDGE is - // available. - { - return s_clamp_to_edge; - } - - - bool check_extension(const char* extension) - // Some extension checking code snipped from glut. - { - static const char* extensions = NULL; - const char* start; - char* where; - char* terminator; - bool supported; - - // Extension names should not have spaces - where = strchr(extension, ' '); - if (where || *extension == '\0') return false; - - // Grab extensions (but only once) - if (!extensions) extensions = (const char*)glGetString(GL_EXTENSIONS); - - // Look for extension - start = extensions; - supported = false; - while (!supported) - { - // Does extension SEEM to be supported? - where = strstr((const char*)start, extension); - if (!where) break; - - // Ok, extension SEEMS to be supported - supported = true; - - // Check for space before extension - supported &= (where == start) || (where[-1] == ' '); - - // Check for space after extension - terminator = where + strlen(extension); - supported &= (*terminator == '\0') || (*terminator == ' '); - - // Next search starts at current terminator - start = terminator; - } - - return supported; - } - - - void* allocate_vertex_memory( int size ) - // Allocate a block of memory for storing vertex data. Using this - // allocator will hopefully give you faster glDrawElements(), if - // you do vertex_array_range on it before rendering. - { - // For best results, we must allocate one big ol' chunk of - // vertex memory on the first call to this function, via - // wglAllocateMemoryNV, and then allocate sub-chunks out of - // it. - - if ( vertex_memory_buffer == 0 ) { - // Need to allocate the big chunk. - - // If we have NV's allocator, then use it. - if ( wglAllocateMemoryNV ) { - vertex_memory_buffer = wglAllocateMemoryNV( VERTEX_BUFFER_SIZE, 0.f, 0.f, 0.5f ); // @@ this gets us AGP memory. -// wglAllocateMemoryNV( size, 0.f, 0.f, 1.0f ); // @@ this gets us video memory. - vertex_memory_from_malloc = false; - vertex_memory_top = 0; - - if ( vertex_memory_buffer && glVertexArrayRangeNV ) { - glVertexArrayRangeNV( VERTEX_BUFFER_SIZE, vertex_memory_buffer ); - } - - glEnableClientState(GL_VERTEX_ARRAY_RANGE_NV); // GL_VERTEX_ARRAY_RANGE_WITHOUT_FLUSH_NV - } - // else we'll fall back on malloc() for vb allocations. - } - - // Carve a chunk out of our big buffer, or out of malloc if - // the buffer is dry. - - if ( vertex_memory_buffer && vertex_memory_top + size <= VERTEX_BUFFER_SIZE ) { - // Just allocate from the end of the big buffer and increment the top. - unsigned char* buffer = (unsigned char*) vertex_memory_buffer + vertex_memory_top; - vertex_memory_top += size; - - return (void*) buffer; - - } else { - // Fall back to malloc. - printf( "avm: warning, falling back to malloc!\n" ); - return malloc( size ); - } - } - - - void free_vertex_memory(void* buffer) - // Frees a buffer previously allocated via allocate_vertex_memory(). - { - // this function is not ready for prime-time. - assert( 0 ); - } - - - void gen_fences(int count, unsigned int* fence_array) - // Wrapper for glGenFencesNV. - { - if (glGenFencesNV) { - glGenFencesNV(count, (GLuint*)fence_array); - } - else - { - // set all fences to 0. - for (int i = 0; i < count; i++) { - fence_array[i] = 0; - } - } - } - - - void set_fence(unsigned int fence_id) - // Use this to declare all previous glDrawElements() calls as - // belonging to the specified fence. A subsequent - // finish_fence(id) will block until those drawing calls have - // completed. - { - if (glSetFenceNV) - { - glSetFenceNV(fence_id, GL_ALL_COMPLETED_NV); - } - // else no-op. - } - - - void finish_fence(unsigned int fence_id) - // Block until all gl drawing calls, associated with the specified - // fence, have completed. - { - if (glFinishFenceNV) - { - glFinishFenceNV(fence_id); - } - // else no-op. - } - - - void* stream_get_vertex_memory(int size) - // Return a buffer to contain size bytes of vertex memory. - // Put your vertex data in it, then call - // stream_flush_combiners(), then call glDrawElements() to - // draw the primitives. - { - if (s_stream == NULL) { - s_stream = new vertex_stream(VERTEX_BUFFER_SIZE); - } - - return s_stream->reserve_memory(size); - } - - - void stream_flush_combiners() - // Make sure to flush all data written to the most recently - // requested vertex buffer (requested by the last call to - // stream_get_vertex_memory()). Ensure that the data doesn't - // get hung up in a processor write-combiner. - { - assert(s_stream); - if (s_stream == NULL) return; - - s_stream->flush_combiners(); - } - - - static const int WRITE_COMBINER_ALIGNMENT = 64; // line-size (in bytes) of the write-combiners, must be power of 2 - - - int wc_align_up(int size) - // Return given size, rounded up to the next nearest write combiner - // alignment boundary. - { - assert((WRITE_COMBINER_ALIGNMENT & (WRITE_COMBINER_ALIGNMENT - 1)) == 0); // make sure it's a power of 2 - - return (size + WRITE_COMBINER_ALIGNMENT - 1) & ~(WRITE_COMBINER_ALIGNMENT - 1); - } - - - // - // vertex_stream - // - - vertex_stream::vertex_stream(int buffer_size) - // Construct a streaming buffer, with vertex RAM of the specified size. - { - assert(buffer_size >= STREAM_SUB_BUFFER_COUNT); - - m_sub_buffer_size = buffer_size / STREAM_SUB_BUFFER_COUNT; - m_buffer = ogl::allocate_vertex_memory(buffer_size); - m_buffer_top = 0; - m_extra_bytes = 0; - - // set up fences. - ogl::gen_fences(4, &m_fence[0]); - - // Set (dummy) fences which will be finished as we reach them. - ogl::set_fence(m_fence[1]); - ogl::set_fence(m_fence[2]); - ogl::set_fence(m_fence[3]); - } - - vertex_stream::~vertex_stream() - { -// ogl::free_vertex_memory(m_buffer); - } - - void* vertex_stream::reserve_memory(int size) - // Clients should call this to get a temporary chunk of fast - // vertex memory. Fill it with vertex info and call - // glVertexPointer()/glDrawElements(). The memory won't get - // stomped until the drawing is finished, provided you use the - // returned buffer in a glDrawElements call before you call - // reserve_memory() to get the next chunk. - { - assert(size <= m_sub_buffer_size); - - int aligned_size = wc_align_up(size); - m_extra_bytes = aligned_size - size; - - for (int sub_buffer = 1; sub_buffer <= STREAM_SUB_BUFFER_COUNT; sub_buffer++) - { - int border = m_sub_buffer_size * sub_buffer; - - if (m_buffer_top <= border - && m_buffer_top + aligned_size > border) - { - // Crossing into the next sub-buffer. - - int prev_buffer = sub_buffer - 1; - int next_buffer = sub_buffer % STREAM_SUB_BUFFER_COUNT; - - // Protect the previous sub-buffer. - ogl::set_fence(m_fence[prev_buffer]); - - // Don't overwrite the next sub-buffer while it's still active. - ogl::finish_fence(m_fence[next_buffer]); - - // Start the next quarter-buffer. - m_buffer_top = m_sub_buffer_size * next_buffer; - } - } - - void* buf = ((char*) m_buffer) + m_buffer_top; - m_buffer_top += aligned_size; - - return buf; - } - - - void vertex_stream::flush_combiners() - // Make sure the tail of the block returned by the last call - // to reserve_memory() gets written to the system RAM. If the - // block doesn't end on a write-combiner line boundary, the - // last bit of data may still be waiting to be flushed. - // - // That's my theory anyway -- farfetched but I'm not sure how - // else to explain certain bug reports of spurious triangles - // being rendered. - { - if (m_extra_bytes) { - // Fill up the rest of the last write-combiner line. - memset(((char*) m_buffer) + m_buffer_top - m_extra_bytes, 0, m_extra_bytes); - } - } - - - // Wrappers for multitexture extensions; no-op if the extension doesn't exist. - - void active_texture(int stage) - // Set the currently active texture stage; use GL_TEXTUREx_ARB. - { - if (glActiveTextureARB) - { - glActiveTextureARB(stage); - } - } - - void client_active_texture(int stage) - // Set the currently active texture stage for vertex array - // setup; use GL_TEXTUREx_ARB. - { - if (glClientActiveTextureARB) - { - glClientActiveTextureARB(stage); - } - } - - void multi_tex_coord_2f(int stage, float s, float t) - // Texture coords for the current vertex, in the specified - // stage. - { - if (glMultiTexCoord2fARB) - { - glMultiTexCoord2fARB(stage, s, t); - } - } - - void multi_tex_coord_2fv(int stage, float* st) - // Texture coords for the current vertex, in the specified - // stage. - { - if (glMultiTexCoord2fvARB) - { - glMultiTexCoord2fvARB(stage, st); - } - } -}; - - -// Local Variables: -// mode: C++ -// c-basic-offset: 8 -// tab-width: 8 - -// indent-tabs-mode: t -// End: diff --git a/Code/BF2/External/base/ogl.h b/Code/BF2/External/base/ogl.h deleted file mode 100644 index 6b174288d..000000000 --- a/Code/BF2/External/base/ogl.h +++ /dev/null @@ -1,70 +0,0 @@ -// ogl.h -- by Thatcher Ulrich - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - -// Some OpenGL helpers; mainly to generically deal with extensions. - -#ifndef OGL_H -#define OGL_H - -#include "base/tu_config.h" -#include "base/tu_opengl_includes.h" - -namespace ogl { - void open(); - void close(); - - // Return true if the specified extension is available. - bool check_extension(const char* extension); - - // Return GL_CLAMP, or GL_CLAMP_TO_EDGE_EXT, depending on - // which is available. I pretty much always want the - // GL_CLAMP_TO_EDGE_EXT behavior, but it's not in the OpenGL - // 1.1 standard, so in those cases I must fall back to - // GL_CLAMP. - int get_clamp_mode(); - - // For allocating DMA or video memory, for holding vertex arrays. - void* allocate_vertex_memory( int size ); // @@ add a flag for selecting AGP vs. video mem? - void free_vertex_memory( void* buffer ); - - // Fences; for synchronizing with the GPU. - void gen_fences(int count, unsigned int* fence_array); - void set_fence(unsigned int fence_id); - void finish_fence(unsigned int fence_id); - - // Stream operations; for pushing dynamic vertex data. - void* stream_get_vertex_memory(int size); - void stream_flush_combiners(); // do this after filling your buffer, and before calling glDrawElements() - - // Rudimentary multitexture stuff. - void active_texture(int stage); - void client_active_texture(int stage); - void multi_tex_coord_2f(int stage, float s, float t); - void multi_tex_coord_2fv(int stage, float* st); -}; - - -// Some old gl/gl.h files don't define these, e.g. default Windows includes. -// It shouldn't hurt anything to call glTexEnvf() with these values on a system -// that doesn't implement them. - -#ifndef GL_TEXTURE_FILTER_CONTROL_EXT -#define GL_TEXTURE_FILTER_CONTROL_EXT 0x8500 -#endif - -#ifndef GL_TEXTURE_LOD_BIAS_EXT -#define GL_TEXTURE_LOD_BIAS_EXT 0x8501 -#endif - - -#endif // OGL_H - - -// Local Variables: -// mode: C++ -// c-basic-offset: 8 -// tab-width: 8 -// indent-tabs-mode: t -// End: diff --git a/Code/BF2/External/base/png_helper.cpp b/Code/BF2/External/base/png_helper.cpp deleted file mode 100644 index 97fdf8bde..000000000 --- a/Code/BF2/External/base/png_helper.cpp +++ /dev/null @@ -1,98 +0,0 @@ -// png_helper.cpp -- Thatcher Ulrich 2004 - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - -// Wrapper for png file operations. The actual work is done by the -// libpng lib. - - -#include "base/utility.h" -#include "base/png_helper.h" -#include "base/tu_file.h" -#include - -#if TU_CONFIG_LINK_TO_LIBPNG - -#include - - -namespace png_helper -{ - void write_grayscale(FILE* out, uint8* data, int width, int height) - // Writes an 8-bit grayscale image in .png format, to the - // given output stream. - { - png_structp png_ptr; - png_infop info_ptr; - - png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); - if (png_ptr == NULL) - { - // @@ log error here! - return; - } - - info_ptr = png_create_info_struct(png_ptr); - if (info_ptr == NULL) - { - // @@ log error here! - png_destroy_write_struct(&png_ptr, NULL); - return; - } - - if (setjmp(png_jmpbuf(png_ptr))) - { - // Error. - png_destroy_write_struct(&png_ptr, &info_ptr); - return; - } - - png_init_io(png_ptr, out); - - png_set_IHDR( - png_ptr, - info_ptr, - width, - height, - 8, - PNG_COLOR_TYPE_GRAY, - PNG_INTERLACE_NONE, - PNG_COMPRESSION_TYPE_DEFAULT, - PNG_FILTER_TYPE_DEFAULT); - - png_write_info(png_ptr, info_ptr); - - for (int y = 0; y < height; y++) - { - png_write_row(png_ptr, data + width * y); - } - - png_write_end(png_ptr, info_ptr); - - png_destroy_write_struct(&png_ptr, &info_ptr); - } -} - - -#else // not TU_CONFIG_LINK_TO_JPEGLIB - - -namespace jpeg -{ - void write_grayscale(FILE* out, uint8* data, int width, int height) - { - // no-op - } -} - - -#endif // not TU_CONFIG_LINK_TO_LIBPNG - - -// Local Variables: -// mode: C++ -// c-basic-offset: 8 -// tab-width: 8 -// indent-tabs-mode: t -// End: diff --git a/Code/BF2/External/base/png_helper.h b/Code/BF2/External/base/png_helper.h deleted file mode 100644 index 2fc2b9a0b..000000000 --- a/Code/BF2/External/base/png_helper.h +++ /dev/null @@ -1,32 +0,0 @@ -// png_helper.h -- Thatcher Ulrich 2004 - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - -// Wrapper for png file operations. The actual work is done by the -// libpng lib. - -#ifndef PNG_HELPER_H -#define PNG_HELPER_H - - -#include "base/tu_config.h" -#include - - -namespace png_helper -{ - void write_grayscale(FILE* out, uint8* data, int width, int height); - - // TODO: add more helpers as needed... -} - - -#endif // PNG_HELPER_H - -// Local Variables: -// mode: C++ -// c-basic-offset: 8 -// tab-width: 8 -// indent-tabs-mode: t -// End: diff --git a/Code/BF2/External/base/postscript.cpp b/Code/BF2/External/base/postscript.cpp deleted file mode 100644 index 6e4c295fe..000000000 --- a/Code/BF2/External/base/postscript.cpp +++ /dev/null @@ -1,288 +0,0 @@ -// postscript.cpp -- by Thatcher Ulrich - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - -// Some helpers for generating Postscript graphics. - - -#include "base/postscript.h" - -#include "base/tu_file.h" -#include "base/utility.h" -#include - - -// Loosely translated into C++ from: -// -- ps.lua -// -- lua interface to postscript -// -- Luiz Henrique de Figueiredo (lhf@csg.uwaterloo.ca) -// -- 14 May 96 -// -// From the Lua 4.0.1 distribution, see http://www.lua.org - - - -postscript::postscript(tu_file* out, const char* title, bool encapsulated) - : - m_out(out), - m_page(0), - m_x0(1000), - m_x1(0), - m_y0(1000), - m_y1(0), - m_empty(true) -// Initialize the file & this struct, etc. -{ - assert(m_out != NULL); - - if (title == NULL) - { - title = "no title"; - } - - if (encapsulated) - { - m_out->printf("%%!PS-Adobe-2.0 EPSF-1.2\n"); - } - else - { - m_out->printf("%%!PS-Adobe 3.0\n"); - } - m_out->printf("%%%%Title: %s\n", title); - m_out->printf( - "%%%%Creator: postscript.cpp from tu-testbed\n" - "%%%%CreationDate: 1 1 2001\n" - "%%%%Pages: (atend)\n" - "%%%%BoundingBox: (atend)\n" - "%%%%EndComments\n" - "%%%%BeginProcSet: postscript.cpp\n" - "/s { stroke } bind def\n" - "/f { fill } bind def\n" - "/m { moveto } bind def\n" - "/l { lineto } bind def\n" - "/L { moveto lineto stroke } bind def\n" - "/t { show } bind def\n" - "/o { 0 360 arc stroke } bind def\n" - "/O { 0 360 arc fill } bind def\n" - "/p { 3 0 360 arc fil } bind def\n" - "/F { findfont exch scalefont setfont } bind def\n" - "/LS { 0 setdash } bind def\n" - "/LW { setlinewidth } bind def\n" - "%%%%EndProcSet: postscript.cpp\n" - "%%%%EndProlog\n" - "%%%%BeginSetup\n" - "0 setlinewidth\n" - "1 setlinejoin\n" - "1 setlinecap\n" - "10 /Times-Roman F\n" - "%%%%EndSetup\n\n" - "%%%%Page: 1 1\n"); -} - - -postscript::~postscript() -// End the Postscript info. -{ - m_out->printf( - "stroke\n" - "showpage\n" - "%%%%Trailer\n" - "%%%%Pages: %d %d\n" - "%%%%BoundingBox: %d %d %d %d\n" - "%%%%EOF\n", - m_page + 1, m_page + 1, - int(m_x0), int(m_y0), int(m_x1), int(m_y1) - ); - -} - - -void postscript::clear() -// New page. -{ - if (m_empty) return; - - m_page++; - m_out->printf("showpage\n%%%%Page: %d %d\n", m_page + 1, m_page + 1); - - m_empty = true; -} - - -void postscript::comment(const char* s) -// Insert a comment into the output. -{ - m_out->printf("%% %s\n", s); -} - - -void postscript::rgbcolor(float r, float g, float b) -// Set the pen color. Components range from 0 to 1. -{ - m_out->printf("%f %f %f setrgbcolor\n", r, g, b); -} - - -void postscript::gray(float amount) -// 0 == black, 1 == white -{ - m_out->printf("%f setgray\n", amount); -} - - -void postscript::black() -{ - rgbcolor(0, 0, 0); -} - - -void postscript::line(float x0, float y0, float x1, float y1) -{ - m_out->printf( - "%f %f %f %f L\n", - x1, y1, x0, y0); - - update(x0, y0); - update(x1, y1); -} - - -void postscript::moveto(float x0, float y0) -{ - m_out->printf( - "%f %f m\n", - x0, y0); - - update(x0, y0); -} - - -void postscript::lineto(float x0, float y0) -{ - m_out->printf( - "%f %f l\n", - x0, y0); - - update(x0, y0); -} - - -void postscript::linewidth(float w) -{ - m_out->printf("%f LW\n", w); -} - - -// @@ linestyle ? - - -void postscript::fill() -{ - m_out->printf("f\n"); -} - - -void postscript::font(const char* name, float size) -{ - m_out->printf("%f /%s F\n", size, name); -} - - -#ifdef _WIN32 -#define vsnprintf _vsnprintf -#endif // _WIN32 - - -void postscript::printf(float x, float y, const char* fmt, ...) -{ - static const int BUFFER_SIZE = 1000; - - char buffer[BUFFER_SIZE]; - - va_list ap; - va_start(ap, fmt); - vsnprintf(buffer, BUFFER_SIZE, fmt, ap); - va_end(ap); - - m_out->printf("%f %f m (%s) t\n", x, y, buffer); - update(x, y); - update(x + 100, y + 10); // @@ should get bounds of text and update properly! -} - - -void postscript::circle(float x, float y, float radius) -{ - m_out->printf("%f %f %f o\n", x, y, radius); - update(x - radius, y - radius); - update(x + radius, y + radius); -} - - -void postscript::disk(float x, float y, float radius) -{ - m_out->printf("%f %f %f O\n", x, y, radius); - update(x - radius, y - radius); - update(x + radius, y + radius); -} - - -void postscript::dot(float x, float y) -{ - m_out->printf("%f %f p\n", x, y); - update(x, y); -} - - -void postscript::rectangle(float x0, float x1, float y0, float y1) -{ - m_out->printf( - "%f %f m " - "%f %f l " - "%f %f l " - "%f %f l " - "%f %f l s\n", - x0, y0, - x1, y0, - x1, y1, - x0, y1, - x0, y0); - update(x0, y0); - update(x1, y1); -} - - -void postscript::box(float x0, float x1, float y0, float y1) -{ - m_out->printf( - "%f %f m " - "%f %f l " - "%f %f l " - "%f %f l f\n", - x0, y0, - x1, y0, - x1, y1, - x0, y1); - update(x0, y0); - update(x1, y1); -} - - -void postscript::update(float x, float y) -// enlarge the bounding box if necessary. -{ - if (x < m_x0) m_x0 = floorf(x); - if (x > m_x1) m_x1 = ceilf(x); - if (y < m_y0) m_y0 = floorf(y); - if (y > m_y1) m_y1 = ceilf(y); - - m_empty = false; -} - - -// Local Variables: -// mode: C++ -// c-basic-offset: 8 -// tab-width: 8 -// indent-tabs-mode: t -// End: diff --git a/Code/BF2/External/base/postscript.h b/Code/BF2/External/base/postscript.h deleted file mode 100644 index 37ea6ff0c..000000000 --- a/Code/BF2/External/base/postscript.h +++ /dev/null @@ -1,78 +0,0 @@ -// postscript.h -- by Thatcher Ulrich - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - -// Some helpers for generating Postscript graphics. - -#ifndef POSTSCRIPT_H -#define POSTSCRIPT_H - - -#include "base/tu_config.h" - -// Loosely translated into C++ from: -// -- ps.lua -// -- lua interface to postscript -// -- Luiz Henrique de Figueiredo (lhf@csg.uwaterloo.ca) -// -- 14 May 96 -// -// From the Lua 4.0.1 distribution, see http://www.lua.org - - -class tu_file; - - -// Postscript units are 72 per inch. - -// @@ TODO all these functions need to take floats, not ints... - -struct postscript -{ - postscript(tu_file* out, const char* title, bool encapsulated = true); - ~postscript(); - - void clear(); // New page - void comment(const char* s); - void rgbcolor(float r, float g, float b); - void black(); - void gray(float amount); // 0 == black, 1 == white - - void line(float x0, float y0, float x1, float y1); - void moveto(float x0, float y0); - void lineto(float x0, float y0); - void linewidth(float w); - // linestyle ? - - void fill(); // after a sequence of moveto/lineto - - void font(const char* name, float size); - void printf(float x, float y, const char* fmt, ...); // printf-style output - - void circle(float x, float y, float radius); - void disk(float x, float y, float radius); - void dot(float x, float y); - - void rectangle(float x0, float x1, float y0, float y1); - void box(float x0, float x1, float y0, float y1); - -private: - void update(float x0, float y0); // enlarge the bounding box if necessary. - - tu_file* m_out; - int m_page; - float m_x0, m_x1, m_y0, m_y1; // bounding box - bool m_empty; -}; - - -#endif // POSTSCRIPT_H - - - -// Local Variables: -// mode: C++ -// c-basic-offset: 8 -// tab-width: 8 -// indent-tabs-mode: t -// End: diff --git a/Code/BF2/External/base/smart_ptr.h b/Code/BF2/External/base/smart_ptr.h index b983fe5b6..dcadd3425 100644 --- a/Code/BF2/External/base/smart_ptr.h +++ b/Code/BF2/External/base/smart_ptr.h @@ -27,6 +27,7 @@ template class smart_ptr { public: + // Retail SwiffPlayer.dll 0x1006FC50 / 0x1006FCD0 / 0x10070010. smart_ptr(T* ptr) : m_ptr(ptr) @@ -48,6 +49,7 @@ class smart_ptr } } + // Retail SwiffPlayer.dll 0x1006FC80 / 0x1006FD00 / 0x10070040. ~smart_ptr() { if (m_ptr) @@ -57,9 +59,12 @@ class smart_ptr } // operator bool() const { return m_ptr != NULL; } + // Retail SwiffPlayer.dll 0x10085660 / 0x100A21A0 / 0x100A5B20. + // 0x10072040 / 0x10072A60: held-pointer instances, with the same identity check. void operator=(const smart_ptr& s) { set_ref(s.m_ptr); } void operator=(T* ptr) { set_ref(ptr); } // void operator=(const weak_ptr& w); + // Retail SwiffPlayer.dll 0x10085020 / 0x10085030. T* operator->() const { assert(m_ptr); return m_ptr; } T* get_ptr() const { return m_ptr; } bool operator==(const smart_ptr& p) const { return m_ptr == p.m_ptr; } @@ -70,6 +75,7 @@ class smart_ptr // Provide work-alikes for static_cast, dynamic_cast, implicit up-cast? ("gentle_cast" a la ajb?) private: + // Retail SwiffPlayer.dll 0x100704F0 / 0x100707F0: release, store, retain. void set_ref(T* ptr) { if (ptr != m_ptr) @@ -97,6 +103,7 @@ class smart_ptr class weak_proxy { public: + // Retail SwiffPlayer.dll 0x1006EC50. weak_proxy() : m_ref_count(0), @@ -108,13 +115,16 @@ class weak_proxy bool is_alive() const { return m_alive; } // Only the actual object should call this. + // Retail SwiffPlayer.dll 0x1006EC60. void notify_object_died() { m_alive = false; } + // Retail SwiffPlayer.dll 0x1006EC70. void add_ref() { assert(m_ref_count >= 0); m_ref_count++; } + // Retail SwiffPlayer.dll 0x1006EC80. void drop_ref() { assert(m_ref_count > 0); diff --git a/Code/BF2/External/base/test_ogl.cpp b/Code/BF2/External/base/test_ogl.cpp deleted file mode 100644 index 7d9a2c769..000000000 --- a/Code/BF2/External/base/test_ogl.cpp +++ /dev/null @@ -1,42 +0,0 @@ -// ogl.cpp -- by Thatcher Ulrich - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - -// test program for ogl wrapper - - -#include -#include "base/ogl.h" -#include - - -#undef main // SDL weirdness under WIN32!! -extern "C" int main(int argc, char *argv[]) -{ - if (SDL_Init(SDL_INIT_VIDEO /* | SDL_INIT_JOYSTICK | SDL_INIT_CDROM | SDL_INIT_AUDIO*/)) - { - fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError()); - exit(1); - } - atexit(SDL_Quit); - - int bpp = 24; - int flags = SDL_OPENGL | (0 ? SDL_FULLSCREEN : 0); - - SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 ); - SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 ); - SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 ); - SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 ); - SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); - - // Set the video mode. - if (SDL_SetVideoMode(320, 240, bpp, flags) == 0) { - fprintf(stderr, "SDL_SetVideoMode() failed."); - exit(1); - } - - ogl::open(); - - return 0; -} diff --git a/Code/BF2/External/base/triangulate.h b/Code/BF2/External/base/triangulate.h deleted file mode 100644 index 750c067de..000000000 --- a/Code/BF2/External/base/triangulate.h +++ /dev/null @@ -1,64 +0,0 @@ -// triangulate.h -- Thatcher Ulrich 2004 - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - -// Code to triangulate arbitrary 2D polygonal regions. - - -#ifndef TRIANGULATE_H -#define TRIANGULATE_H - -#include "base/container.h" -#include "base/tu_types.h" - -namespace triangulate -{ - // Input is a list of closed paths that form the overall - // region. The region does not need to be connected, and may - // contain holes/islands. The paths should not intersect each - // other, or themselves. - // - // The paths should be in counter-clockwise orientation, - // meaning that the inside of the shape is to the left of the - // directed path. So a closed region is in CCW order, while - // an island inside a closed region is in CW (reverse) order. - // - // The output is a triangle list; each tri consists of 6 - // coords: (x0, y0, x1, y1, x2, y2). - - // Version using float coords - void compute( - array* results, - int path_count, - const array paths[], - int debug_halt_step = -1, - array* debug_remaining_loop = NULL); - - // Version using short coords - void compute( - array* results, // indexed trilist - int path_count, - const array paths[], - int debug_halt_step = -1, - array* debug_remaining_loop = NULL); - - // Version using int coords - void compute( - array* results, // indexed trilist - int path_count, - const array paths[], - int debug_halt_step = -1, - array* debug_remaining_loop = NULL); -} - - -#endif // TRIANGULATE - - -// Local Variables: -// mode: C++ -// c-basic-offset: 8 -// tab-width: 8 -// indent-tabs-mode: t -// End: diff --git a/Code/BF2/External/base/triangulate_float.cpp b/Code/BF2/External/base/triangulate_float.cpp deleted file mode 100644 index 4ba8b1452..000000000 --- a/Code/BF2/External/base/triangulate_float.cpp +++ /dev/null @@ -1,84 +0,0 @@ -// triangulate_float.cpp -- Thatcher Ulrich 2004 - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - -// Code to triangulate arbitrary 2D polygonal regions. -// -// Instantiate our templated algo from triangulate_inst.h - -#include "base/triangulate_impl.h" - - -namespace triangulate -{ - // Version using float coords - void compute( - array* result, // trilist - int path_count, - const array paths[], - int debug_halt_step /* = -1 */, - array* debug_remaining_loop /* = NULL */) - { - compute_triangulation(result, path_count, paths, debug_halt_step, debug_remaining_loop); - } -} - - - -#ifdef TEST_TRIANGULATE_FLOAT - -// Compile test with something like: -// -// gcc -o triangulate_test -I../ triangulate_float.cpp tu_random.cpp -DTEST_TRIANGULATE_FLOAT -lstdc++ -// -// or -// -// cl -Od -Zi -o triangulate_test.exe -I../ triangulate_float.cpp tu_random.cpp -DTEST_TRIANGULATE_FLOAT - - -void test_square() -// A very minimal, easy test. -{ - array result; - array > paths; - - // Make a square. - paths.resize(1); - paths[0].push_back(0); - paths[0].push_back(0); - paths[0].push_back(1); - paths[0].push_back(0); - paths[0].push_back(1); - paths[0].push_back(1); - paths[0].push_back(0); - paths[0].push_back(1); - - // Triangulate. - triangulate::compute(&result, paths.size(), &paths[0]); - - // Dump. - for (int i = 0; i < result.size(); i++) - { - printf("%f\n", result[i]); - } -} - - -int main() -{ - test_square(); - - return 0; -} - - -#endif // TEST_TRIANGULATE_FLOAT - - -// Local Variables: -// mode: C++ -// c-basic-offset: 8 -// tab-width: 8 -// indent-tabs-mode: t -// End: diff --git a/Code/BF2/External/base/triangulate_impl.h b/Code/BF2/External/base/triangulate_impl.h deleted file mode 100644 index bdbd5003e..000000000 --- a/Code/BF2/External/base/triangulate_impl.h +++ /dev/null @@ -1,2511 +0,0 @@ -// triangulate_impl.h -- Thatcher Ulrich 2004 - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - -// Code to triangulate arbitrary 2D polygonal regions. -// -// Use the basic robust ear-clipping algorithm from "FIST: Fast -// Industrial-Strength Triangulation of Polygons" by Martin Held. -// -// NOTE: This code is based on the algorithm described in the FIST -// paper, but this is NOT the official FIST code written by Martin -// Held! This code may not be as robust or as fast as FIST, and is -// certainly not as well tested. Also, it deviates in some places -// from the algorithm as described in the FIST paper; I have tried to -// document those places in the code, along with my reasoning, but -// this code is not warranted in any way. -// -// In particular, the recovery_process is currently not as good as -// official FIST or even what's in the FIST paper. This routine may -// do some ugly stuff with self-intersecting input. -// -// For information on obtaining the offical industrial-strength FIST -// code, see the FIST web page at: -// http://www.cosy.sbg.ac.at/~held/projects/triang/triang.html - - -#include "base/utility.h" -#include "base/triangulate.h" -#include "base/tu_random.h" -#include "base/grid_index.h" - -#define PROFILE_TRIANGULATE -#ifdef PROFILE_TRIANGULATE -#include "base/tu_timer.h" -#endif // PROFILE_TRIANGULATE - - -// Template this whole thing on coord_t, so sint16 and float versions -// can easily reuse the code. -// -// These templates are instantiated in triangulate_.cpp files. -// They're in separate cpp files so the linker will discard code for -// unused types. - - -// convenience struct; this could use some public vec2 type, but often -// it's nicer for users if the external interface is smaller and more -// c-like, since they probably have their own vec2 that they prefer. -template -struct vec2 -{ - vec2() : x(0), y(0) {} - vec2(coord_t _x, coord_t _y) : x(_x), y(_y) {} - - bool operator==(const vec2& v) const - { - return x == v.x && y == v.y; - } - -//data: - coord_t x, y; -}; - - -inline double determinant_float(const vec2& a, const vec2& b, const vec2& c) -{ - return (double(b.x) - double(a.x)) * (double(c.y) - double(a.y)) - - (double(b.y) - double(a.y)) * (double(c.x) - double(a.x)); -} - - -inline sint64 determinant_sint32(const vec2& a, const vec2& b, const vec2& c) -{ - return (sint64(b.x) - sint64(a.x)) * (sint64(c.y) - sint64(a.y)) - - (sint64(b.y) - sint64(a.y)) * (sint64(c.x) - sint64(a.x)); -} - - -// Return {-1,0,1} if c is {to the right, on, to the left} of the -// directed edge defined by a->b. -template -inline int vertex_left_test(const vec2& a, const vec2& b, const vec2& c) -{ - compiler_assert(0); // must specialize - return -1; -} - - -template<> -inline int vertex_left_test(const vec2& a, const vec2& b, const vec2& c) -// Specialize for vec2 -{ - double det = determinant_float(a, b, c); - if (det > 0) return 1; - else if (det < 0) return -1; - else return 0; -} - - -template<> -inline int vertex_left_test(const vec2& a, const vec2& b, const vec2& c) -// Specialize for vec2 -{ - sint64 det = determinant_sint32(a, b, c); - if (det > 0) return 1; - else if (det < 0) return -1; - else return 0; -} - - -template -bool vertex_in_ear(const vec2& v, const vec2& a, const vec2& b, const vec2& c) -// Return true if v is on or inside the ear (a,b,c). -// (a,b,c) must be in ccw order! -{ - assert(vertex_left_test(b, a, c) <= 0); // check ccw order - - if (v == a || v == c) - { - // Special case; we don't care if v is coincident with a or c. - return false; - } - - // Include the triangle boundary in our test. - bool ab_in = vertex_left_test(a, b, v) >= 0; - bool bc_in = vertex_left_test(b, c, v) >= 0; - bool ca_in = vertex_left_test(c, a, v) >= 0; - - return ab_in && bc_in && ca_in; -} - - -template struct poly; - - - -inline int remap_index_for_duped_verts(int index, int duped_v0, int duped_v1) -// Helper. Return the new value of index, for the case of verts [duped_v0] -// and [duped_v1] being duplicated and subsequent verts being shifted up. -{ - assert(duped_v0 < duped_v1); - if (index <= duped_v0) - { - // No shift. - return index; - } - else if (index <= duped_v1) - { - // Shift up one. - return index + 1; - } - else - { - // Shift up two. - return index + 2; - } -} - - -template -struct poly_vert -{ - poly_vert() {} - poly_vert(coord_t x, coord_t y, poly* owner, int my_index) - : - m_v(x, y), - m_my_index(my_index), - m_next(-1), - m_prev(-1), - m_convex_result(0), // 1 (convex), 0 (colinear), -1 (reflex) - m_is_ear(false), - m_poly_owner(owner) - { - } - - void remap(const array& remap_table) - { - m_my_index = remap_table[m_my_index]; - m_next = remap_table[m_next]; - m_prev = remap_table[m_prev]; - } - - index_point get_index_point() const { return index_point(m_v.x, m_v.y); } - -//data: - vec2 m_v; - int m_my_index; // my index into sorted_verts array - int m_next; - int m_prev; - int m_convex_result; // (@@ only need 2 bits) - bool m_is_ear; - poly* m_poly_owner; // needed? -}; - - -template -int compare_vertices(const void* a, const void* b) -// For qsort. Sort by x, then by y. -{ - const poly_vert* vert_a = (const poly_vert*) a; - const poly_vert* vert_b = (const poly_vert*) b; - - if (vert_a->m_v.x < vert_b->m_v.x) - return -1; - else if (vert_a->m_v.x > vert_b->m_v.x) - return 1; - else - { - if (vert_a->m_v.y < vert_b->m_v.y) - return -1; - else if (vert_a->m_v.y > vert_b->m_v.y) - return 1; - } - - return 0; -} - - -template -inline bool edges_intersect_sub(const array >& sorted_verts, int e0v0, int e0v1, int e1v0, int e1v1) -// Return true if edge (e0v0,e0v1) intersects (e1v0,e1v1). -{ - // Need to specialize this on coord_t, in order to get it - // correct and avoid overflow. - compiler_assert(0); - return -1; -} - - -template<> -inline bool edges_intersect_sub(const array >& sorted_verts, int e0v0i, int e0v1i, int e1v0i, int e1v1i) -// Return true if edge (e0v0,e0v1) intersects (e1v0,e1v1). -// -// Specialized for float. -{ - // If e1v0,e1v1 are on opposite sides of e0, and e0v0,e0v1 are - // on opposite sides of e1, then the segments cross. These - // are all determinant checks. - - // The main degenerate case we need to watch out for is if - // both segments are zero-length. - // - // If only one is degenerate, our tests are still OK. - - const vec2& e0v0 = sorted_verts[e0v0i].m_v; - const vec2& e0v1 = sorted_verts[e0v1i].m_v; - const vec2& e1v0 = sorted_verts[e1v0i].m_v; - const vec2& e1v1 = sorted_verts[e1v1i].m_v; - - // Note: exact equality here. I think the reason to use - // epsilons would be underflow in case of very small - // determinants. Our determinants are doubles, so I think - // we're good. - if (e0v0.x == e0v1.x && e0v0.y == e0v1.y) - { - // e0 is zero length. - if (e1v0.x == e1v1.x && e1v0.y == e1v1.y) - { - // Both edges are zero length. - // They intersect only if they're coincident. - return e0v0.x == e1v0.x && e0v0.y == e1v0.y; - } - } - - // See if e1 crosses line of e0. - double det10 = determinant_float(e0v0, e0v1, e1v0); - double det11 = determinant_float(e0v0, e0v1, e1v1); - - // Note: we do > 0, which means a vertex on a line counts as - // intersecting. In general, if one vert is on the other - // segment, we have to go searching along the path in either - // direction to see if it crosses or not, and it gets - // complicated. Better to treat it as intersection. - - if (det10 * det11 > 0) - { - // e1 doesn't cross the line of e0. - return false; - } - - // See if e0 crosses line of e1. - double det00 = determinant_float(e1v0, e1v1, e0v0); - double det01 = determinant_float(e1v0, e1v1, e0v1); - - if (det00 * det01 > 0) - { - // e0 doesn't cross the line of e1. - return false; - } - - // They both cross each other; the segments intersect. - return true; -} - - -template<> -inline bool edges_intersect_sub(const array >& sorted_verts, int e0v0i, int e0v1i, int e1v0i, int e1v1i) -// Return true if edge (e0v0,e0v1) intersects (e1v0,e1v1). -// -// Specialized for sint32 -{ - // If e1v0,e1v1 are on opposite sides of e0, and e0v0,e0v1 are - // on opposite sides of e1, then the segments cross. These - // are all determinant checks. - - // The main degenerate case we need to watch out for is if - // both segments are zero-length. - // - // If only one is degenerate, our tests are still OK. - - const vec2& e0v0 = sorted_verts[e0v0i].m_v; - const vec2& e0v1 = sorted_verts[e0v1i].m_v; - const vec2& e1v0 = sorted_verts[e1v0i].m_v; - const vec2& e1v1 = sorted_verts[e1v1i].m_v; - - if (e0v0.x == e0v1.x && e0v0.y == e0v1.y) - { - // e0 is zero length. - if (e1v0.x == e1v1.x && e1v0.y == e1v1.y) - { - // Both edges are zero length. Treat them as - // non-coincident (even if they're all on the - // same point). - return false; - } - } - - // See if e1 crosses line of e0. - sint64 det10 = determinant_sint32(e0v0, e0v1, e1v0); - sint64 det11 = determinant_sint32(e0v0, e0v1, e1v1); - - // Note: we do > 0, which means a vertex on a line counts as - // intersecting. In general, if one vert is on the other - // segment, we have to go searching along the path in either - // direction to see if it crosses or not, and it gets - // complicated. Better to treat it as intersection. - - if (det10 * det11 > 0) - { - // e1 doesn't cross the line of e0. - return false; - } - - // See if e0 crosses line of e1. - sint64 det00 = determinant_sint32(e1v0, e1v1, e0v0); - sint64 det01 = determinant_sint32(e1v0, e1v1, e0v1); - - if (det00 * det01 > 0) - { - // e0 doesn't cross the line of e1. - return false; - } - - // They both cross each other; the segments intersect. - return true; -} - - -template -bool edges_intersect(const array >& sorted_verts, int e0v0, int e0v1, int e1v0, int e1v1) -// Return true if edge (e0v0,e0v1) intersects (e1v0,e1v1). -{ - // Deal with special case: edges that share exactly one vert. - // We treat these as no intersection, even though technically - // they share one point. - // - // We're not just comparing indices, because duped verts (for - // bridges) might have different indices. - // - // @@ this needs review -- might be wrong. - bool coincident[2][2]; - coincident[0][0] = (sorted_verts[e0v0].m_v == sorted_verts[e1v0].m_v); - coincident[0][1] = (sorted_verts[e0v0].m_v == sorted_verts[e1v1].m_v); - coincident[1][0] = (sorted_verts[e0v1].m_v == sorted_verts[e1v0].m_v); - coincident[1][1] = (sorted_verts[e0v1].m_v == sorted_verts[e1v1].m_v); - if (coincident[0][0] && !coincident[1][1]) return false; - if (coincident[1][0] && !coincident[0][1]) return false; - if (coincident[0][1] && !coincident[1][0]) return false; - if (coincident[1][1] && !coincident[0][0]) return false; - -// @@ eh, I think we really want this to be an intersection -#if 0 - // Both verts identical: early out. - // - // Note: treat this as no intersection! This is mainly useful - // for things like coincident vertical bridge edges. - if (coincident[0][0] && coincident[1][1]) return false; - if (coincident[1][0] && coincident[0][1]) return false; -#endif // 0 - - // Check for intersection. - return edges_intersect_sub(sorted_verts, e0v0, e0v1, e1v0, e1v1); -} - - - -template -bool is_convex_vert(const array >& sorted_verts, int vi) -// Return true if vert vi is convex. -{ - const poly_vert* pvi = &(sorted_verts[vi]); - const poly_vert* pv_prev = &(sorted_verts[pvi->m_prev]); - const poly_vert* pv_next = &(sorted_verts[pvi->m_next]); - - return vertex_left_test(pv_prev->m_v, pvi->m_v, pv_next->m_v) > 0; -} - - -template -struct poly -{ - typedef poly_vert vert_t; - - poly(/*@@ TODO array* sorted_verts*/) - : - // @@ TODO m_sorted_verts(sorted_verts), - m_loop(-1), - m_leftmost_vert(-1), - m_vertex_count(0), - m_ear_count(0), - m_edge_index(NULL), - m_reflex_point_index(NULL) - { - } - - ~poly() - { - delete m_edge_index; - m_edge_index = NULL; - - delete m_reflex_point_index; - m_reflex_point_index = NULL; - } - - bool is_valid(const array& sorted_verts, bool check_consecutive_dupes = true) const; - - // init/prep - void append_vert(array* sorted_verts, int vert_index); - void remap(const array& remap_table); - void remap_for_duped_verts(const array& sorted_verts, int v0, int v1); - - void init_edge_index(const array& sorted_verts, index_box& bound_of_all_verts); - int find_valid_bridge_vert(const array& sorted_verts, int v1); - void update_connected_sub_poly(array* sorted_verts, int v_start, int v_stop); - void init_for_ear_clipping(array* sorted_verts); - - // Edges are indexed using their first vert (i.e. edge (v1,v2) is indexed using v1) - void add_edge(const array& sorted_verts, int vi); - void remove_edge(const array& sorted_verts, int vi); - - // tests/queries - bool any_edge_intersection(const array& sorted_verts, int external_vert, int v2); - bool vert_can_see_cone_a(const array& sorted_verts, int v, int cone_a_vert, int cone_b_vert); - bool vert_in_cone(const array& sorted_verts, int vert, int cone_v0, int cone_v1, int cone_v2); - bool vert_is_duplicated(const array& sorted_verts, int v0); - bool ear_contains_reflex_vertex(const array& sorted_verts, int v0, int v1, int v2); - - void classify_vert(array* sorted_verts, int vi); - void dirty_vert(array* sorted_verts, int vi); - - int get_vertex_count() const { return m_vertex_count; } - int get_ear_count() const { return m_ear_count; } - int get_next_ear(const array& sorted_verts, tu_random::generator* rg); - int remove_degenerate_chain(array* sorted_verts, int vi); - void emit_and_remove_ear(array* result, array* sorted_verts, int v0, int v1, int v2); - bool build_ear_list(array* sorted_verts, tu_random::generator* rg); - - void invalidate(const array& sorted_verts); - -//data: -//@@ TODO array* m_sorted_verts; - int m_loop; // index of first vert - int m_leftmost_vert; - int m_vertex_count; - int m_ear_count; - - // edge search_index (for finding possibly intersecting edges during bridge finding) - // - // The payload stored is the index of the first vert in the edge. - typedef grid_index_box box_index_t; - typedef typename box_index_t::iterator ib_iterator; - grid_index_box* m_edge_index; - - // point search index (for finding reflex verts within a potential ear) - typedef grid_index_point point_index_t; - typedef typename point_index_t::iterator ip_iterator; - point_index_t* m_reflex_point_index; -}; - - -template -bool poly::is_valid(const array& sorted_verts, bool check_consecutive_dupes /* = true */) const -// Assert validity. -{ -#ifndef NDEBUG - - if (m_loop == -1 && m_leftmost_vert == -1 && m_vertex_count == 0) - { - // Empty poly. - return true; - } - - assert(m_leftmost_vert == -1 || sorted_verts[m_leftmost_vert].m_poly_owner == this); - - // Check vert count. - int first_vert = m_loop; - int vi = first_vert; - int vert_count = 0; - int ear_count = 0; - bool found_leftmost = false; - int reflex_vert_count = 0; - do - { - const poly_vert* pvi = &sorted_verts[vi]; - - // Check ownership. - assert(pvi->m_poly_owner == this); - - // Check leftmost vert. - assert(m_leftmost_vert == -1 - || compare_vertices( - (const void*) &sorted_verts[m_leftmost_vert], - (const void*) &sorted_verts[vi]) <= 0); - - // Check link integrity. - int v_next = pvi->m_next; - assert(sorted_verts[v_next].m_prev == vi); - - if (vi == m_leftmost_vert) - { - found_leftmost = true; - } - - if (check_consecutive_dupes && v_next != vi) - { - // Subsequent verts are not allowed to be - // coincident; that causes errors in ear - // classification. - assert((pvi->m_v == sorted_verts[v_next].m_v) == false); - } - - if (pvi->m_convex_result < 0) - { - reflex_vert_count++; - } - if (pvi->m_is_ear) - { - ear_count++; - } - vert_count++; - vi = v_next; - } - while (vi != first_vert); - - assert(ear_count == m_ear_count); - assert(vert_count == m_vertex_count); - assert(found_leftmost || m_leftmost_vert == -1); - - // Count reflex verts in the grid index. - if (m_reflex_point_index) - { - int check_count = 0; - for (ip_iterator it = m_reflex_point_index->begin(m_reflex_point_index->get_bound()); - ! it.at_end(); - ++it) - { - check_count++; - } - - assert(check_count == reflex_vert_count); - } - - // Count edges in the edge index. There should be exactly one edge per vert. - if (m_edge_index) - { - int check_count = 0; - for (ib_iterator it = m_edge_index->begin(m_edge_index->get_bound()); - ! it.at_end(); - ++it) - { - check_count++; - } - - assert(check_count == vert_count); - } - - // Might be nice to check that all verts with (m_poly_owner == - // this) are in our loop. - -#endif // not NDEBUG - - return true; -} - - -template -void poly::invalidate(const array& sorted_verts) -// Mark as invalid/empty. Do this after linking into another poly, -// for safety/debugging. -{ - assert(m_loop == -1 || sorted_verts[m_loop].m_poly_owner != this); // make sure our verts have been stolen already. - - m_loop = -1; - m_leftmost_vert = -1; - m_vertex_count = 0; - - assert(is_valid(sorted_verts)); -} - - -template -int compare_polys_by_leftmost_vert(const void* a, const void* b) -{ - const poly* poly_a = * (const poly**) a; - const poly* poly_b = * (const poly**) b; - - // Vert indices are sorted, so we just compare the indices, - // not the actual vert coords. - if (poly_a->m_leftmost_vert < poly_b->m_leftmost_vert) - { - return -1; - } - else - { - // polys are not allowed to share verts, so the - // leftmost vert must be different! - assert(poly_a->m_leftmost_vert > poly_b->m_leftmost_vert); - - return 1; - } -} - - -template -void poly::append_vert(array* sorted_verts, int vert_index) -// Link the specified vert into our loop. -{ - assert(vert_index >= 0 && vert_index < sorted_verts->size()); - assert(is_valid(*sorted_verts, false /* don't check for consecutive dupes, poly is not finished */)); - - m_vertex_count++; - - if (m_loop == -1) - { - // First vert. - assert(m_vertex_count == 1); - m_loop = vert_index; - poly_vert* pv = &(*sorted_verts)[vert_index]; - pv->m_next = vert_index; - pv->m_prev = vert_index; - pv->m_poly_owner = this; - - m_leftmost_vert = vert_index; - } - else - { - // We have a loop. Link the new vert in, behind the - // first vert. - poly_vert* pv0 = &(*sorted_verts)[m_loop]; - poly_vert* pv = &(*sorted_verts)[vert_index]; - pv->m_next = m_loop; - pv->m_prev = pv0->m_prev; - pv->m_poly_owner = this; - (*sorted_verts)[pv0->m_prev].m_next = vert_index; - pv0->m_prev = vert_index; - - // Update m_leftmost_vert - poly_vert* pvl = &(*sorted_verts)[m_leftmost_vert]; - if (compare_vertices(pv, pvl) < 0) - { - // v is to the left of vl; it's the new leftmost vert - m_leftmost_vert = vert_index; - } - } - - assert(is_valid(*sorted_verts, false /* don't check for consecutive dupes, poly is not finished */)); -} - - -template -int poly::find_valid_bridge_vert(const array& sorted_verts, int v1) -// Find a vert v, in this poly, such that v is to the left of v1, and -// the edge (v,v1) doesn't intersect any edges in this poly. -{ - assert(is_valid(sorted_verts)); - - const poly_vert* pv1 = &(sorted_verts[v1]); - assert(pv1->m_poly_owner != this); // v1 must not be part of this poly already - - // Held recommends searching verts near v1 first. And for - // correctness, we may only consider verts to the left of v1. - // A fast & easy way to implement this is to walk backwards in - // our vert array, starting with v1-1. - - // Walk forward to include all coincident but later verts! - int vi = v1; - while ((vi + 1) < sorted_verts.size() && sorted_verts[vi + 1].m_v == pv1->m_v) - { - vi++; - } - - // Now scan backwards for the vert to bridge onto. - for ( ; vi >= 0; vi--) - { - const poly_vert* pvi = &sorted_verts[vi]; - - assert(compare_vertices((void*) pvi, (void*) pv1) <= 0); - - if (pvi->m_poly_owner == this) - { - // Candidate is to the left of pv1, so it - // might be valid. We don't consider verts to - // the right of v1, because of possible - // intersection with other polys. Due to the - // poly sorting, we know that the edge - // (pvi,pv1) can only intersect this poly. - - if (any_edge_intersection(sorted_verts, v1, vi) == false) - { - return vi; - } - } - } - - // Ugh! No valid bridge vert. Shouldn't happen with valid - // data. For invalid data, just pick something and live with - // the intersection. - fprintf(stderr, "can't find bridge for vert %d!\n", v1);//xxxxxxxxx - - return m_leftmost_vert; -} - - -template -void poly::remap(const array& remap_table) -{ - assert(m_loop > -1); - assert(m_leftmost_vert > -1); - - m_loop = remap_table[m_loop]; - m_leftmost_vert = remap_table[m_leftmost_vert]; -} - - -template -void poly::remap_for_duped_verts(const array& sorted_verts, int v0, int v1) -// Remap for the case of v0 and v1 being duplicated, and subsequent -// verts being shifted up. -{ - assert(m_loop > -1); - assert(m_leftmost_vert > -1); - - m_loop = remap_index_for_duped_verts(m_loop, v0, v1); - m_leftmost_vert = remap_index_for_duped_verts(m_leftmost_vert, v0, v1); - - // Remap the vert indices stored in the edge index. - if (m_edge_index) - { - // Optimization: we don't need to remap anything - // that's wholly to the left of v0. Towards the end - // of bridge building, this could be the vast majority - // of edges. - assert(v0 < v1); - index_box bound = m_edge_index->get_bound(); - bound.min.x = sorted_verts[v0].m_v.x; - - for (ib_iterator it = m_edge_index->begin(bound); - ! it.at_end(); - ++it) - { - it->value = remap_index_for_duped_verts(it->value, v0, v1); - } - } - - // We shouldn't have a point index right now. - assert(m_reflex_point_index == NULL); -} - - -template -void poly::classify_vert(array* sorted_verts, int vi) -// Decide if vi is an ear, and mark its m_is_ear flag & update counts. -{ - poly_vert* pvi = &((*sorted_verts)[vi]); - const poly_vert* pv_prev = &((*sorted_verts)[pvi->m_prev]); - const poly_vert* pv_next = &((*sorted_verts)[pvi->m_next]); - - if (pvi->m_convex_result > 0) - { - if (vert_in_cone(*sorted_verts, pvi->m_prev, vi, pvi->m_next, pv_next->m_next) - && vert_in_cone(*sorted_verts, pvi->m_next, pv_prev->m_prev, pvi->m_prev, vi)) - { - if (! ear_contains_reflex_vertex(*sorted_verts, pvi->m_prev, vi, pvi->m_next)) - { - // Valid ear. - assert(pvi->m_is_ear == false); - pvi->m_is_ear = true; - m_ear_count++; - } - } - } -} - - -template -void poly::dirty_vert(array* sorted_verts, int vi) -// Call when an adjacent vert gets clipped. Recomputes -// m_convex_result and clears m_is_ear for the vert. -{ - poly_vert* pvi = &((*sorted_verts)[vi]); - - int new_convex_result = - vertex_left_test((*sorted_verts)[pvi->m_prev].m_v, pvi->m_v, (*sorted_verts)[pvi->m_next].m_v); - if (new_convex_result < 0 && pvi->m_convex_result >= 0) - { - // Vert is newly reflex. - // Add to reflex vert index - assert(m_reflex_point_index); - m_reflex_point_index->add(index_point(pvi->m_v.x, pvi->m_v.y), vi); - } - else if (pvi->m_convex_result < 0 && new_convex_result >= 0) - { - // Vert is newly convex/colinear. - // Remove from reflex vert index. - assert(m_reflex_point_index); - ip_iterator it = m_reflex_point_index->find(index_point(pvi->m_v.x, pvi->m_v.y), vi); - assert(it.at_end() == false); - - m_reflex_point_index->remove(&(*it)); - } - pvi->m_convex_result = new_convex_result; - - if (pvi->m_is_ear) - { - // Clear its ear flag. - pvi->m_is_ear = false; - m_ear_count--; - } -} - - -template -bool poly::build_ear_list(array* sorted_verts, tu_random::generator* rg) -// Initialize our ear loop with all the ears that can be clipped. -// -// Returns true if we clipped any degenerates while looking for ears. -{ - assert(is_valid(*sorted_verts)); - assert(m_ear_count == 0); - - bool clipped_any_degenerates = false; - - if (m_vertex_count < 3) - { - // Not a real poly, no ears. - return false; - } - - // Go around the loop, evaluating the verts. - int vi = m_loop; - int verts_processed_count = 0; - for (;;) - { - const poly_vert* pvi = &((*sorted_verts)[vi]); - const poly_vert* pv_prev = &((*sorted_verts)[pvi->m_prev]); - const poly_vert* pv_next = &((*sorted_verts)[pvi->m_next]); - - // classification of ear, CE2 from FIST paper: - // - // v[i-1],v[i],v[i+1] of P form an ear of P iff - // - // 1. v[i] is a convex vertex - // - // 2. the interior plus boundary of triangle - // v[i-1],v[i],v[i+1] does not contain any reflex vertex of P - // (except v[i-1] or v[i+1]) - // - // 3. v[i-1] is in the cone(v[i],v[i+1],v[i+2]) and v[i+1] is - // in the cone(v[i-2],v[i-1],v[i]) (not strictly necessary, - // but used for efficiency and robustness) - - if ((pvi->m_v == pv_next->m_v) - || (pvi->m_v == pv_prev->m_v) - || (vertex_left_test(pv_prev->m_v, pvi->m_v, pv_next->m_v) == 0 - && vert_is_duplicated(*sorted_verts, vi) == false)) - { - // Degenerate case: zero-area triangle. - // - // Remove it (and any additional degenerates chained onto this ear). - vi = remove_degenerate_chain(sorted_verts, vi); - - clipped_any_degenerates = true; - - if (m_vertex_count < 3) - { - break; - } - - continue; - } - else - { - classify_vert(sorted_verts, vi); - } - - vi = pvi->m_next; - verts_processed_count++; - - if (verts_processed_count >= m_vertex_count) - { - break; - } - - // Performance optimization: if we're finding lots of - // ears, keep our working set local by processing a - // few ears soon after examining them. - if (m_ear_count > 5 && verts_processed_count > 10) - { - break; - } - } - - assert(is_valid(*sorted_verts, true /* do check for dupes */)); - - // @@ idea for cheap ear shape control: m_loop = best_ear_found; - - return clipped_any_degenerates; -} - - -template -int poly::get_next_ear(const array& sorted_verts, tu_random::generator* rg) -// Return the next ear to be clipped. -{ - assert(m_ear_count > 0); - - while (sorted_verts[m_loop].m_is_ear == false) - { - m_loop = sorted_verts[m_loop].m_next; - } - - int next_ear = m_loop; - -// define this if you want to randomize the ear selection (should -// improve the average ear shape, at low cost). -//#define RANDOMIZE -#ifdef RANDOMIZE - // Randomization: skip a random number of ears. - if (m_ear_count > 6) - { - // Decide how many ears to skip. - - // Here's a lot of twiddling to avoid a % op. Worth it? - int random_range = m_ear_count >> 2; - static const int MASK_TABLE_SIZE = 8; - int random_mask[MASK_TABLE_SIZE] = { - 1, 1, 1, 3, 3, 3, 3, 7 // roughly, the largest (2^N-1) <= index - }; - if (random_range >= MASK_TABLE_SIZE) random_range = MASK_TABLE_SIZE - 1; - assert(random_range > 0); - - int random_skip = rg->next_random() & random_mask[random_range]; - - // Do the skipping, by manipulating m_loop. - while (random_skip > 0) - { - if (sorted_verts[m_loop].m_is_ear) - { - random_skip--; - } - m_loop = sorted_verts[m_loop].m_next; - } - - assert(is_valid(sorted_verts)); - } -#endif // RANDOMIZE - - assert(sorted_verts[next_ear].m_is_ear == true); - - return next_ear; -} - - -template -void poly::emit_and_remove_ear( - array* result, - array* sorted_verts, - int v0, - int v1, - int v2) -// Push the ear triangle into the output; remove the triangle -// (i.e. vertex v1) from this poly. -{ - assert(is_valid(*sorted_verts)); - assert(m_vertex_count >= 3); - - poly_vert* pv0 = &(*sorted_verts)[v0]; - poly_vert* pv1 = &(*sorted_verts)[v1]; - poly_vert* pv2 = &(*sorted_verts)[v2]; - - assert((*sorted_verts)[v1].m_is_ear); - - if (m_loop == v1) - { - // Change m_loop, since we're about to lose it. - m_loop = v0; - } - - // Make sure m_leftmost_vert is dead; we don't need it now. - m_leftmost_vert = -1; - - if (vertex_left_test(pv0->m_v, pv1->m_v, pv2->m_v) == 0) - { - // Degenerate triangle! Don't emit it. - assert(0); // This should have already been removed by remove_degenerate_chain(). - } - else - { - // emit the vertex list for the triangle. - result->push_back(pv0->m_v.x); - result->push_back(pv0->m_v.y); - result->push_back(pv1->m_v.x); - result->push_back(pv1->m_v.y); - result->push_back(pv2->m_v.x); - result->push_back(pv2->m_v.y); - } - - // Unlink v1. - - if (pv1->m_convex_result < 0) - { - // Vert was reflex (can happen due to e.g. recovery). - // Remove from reflex vert index. - assert(m_reflex_point_index); - ip_iterator it = m_reflex_point_index->find(index_point(pv1->m_v.x, pv1->m_v.y), v1); - assert(it.at_end() == false); - - m_reflex_point_index->remove(&(*it)); - } - - assert(pv0->m_poly_owner == this); - assert(pv1->m_poly_owner == this); - assert(pv2->m_poly_owner == this); - - pv0->m_next = v2; - pv2->m_prev = v0; - - pv1->m_next = -1; - pv1->m_prev = -1; - pv1->m_poly_owner = NULL; - - // We lost v1. - m_vertex_count--; - m_ear_count--; - - if (pv0->m_v == pv2->m_v) - { - // remove_degenerate_chain() should have taken care of - // this before we got here. - assert(0); - } - - // ear status of v0 and v2 could have changed now. - dirty_vert(sorted_verts, v0); - dirty_vert(sorted_verts, v2); - - // Big huge performance boost: recheck these local verts now; - // often we'll clip them right away. - // - // @@ what happens if v0 or v2 are now degenerate??? - classify_vert(sorted_verts, v0); - classify_vert(sorted_verts, v2); - - assert(is_valid(*sorted_verts)); -} - - -template -int poly::remove_degenerate_chain(array* sorted_verts, int vi) -// Remove the degenerate ear at vi, and any degenerate ear formed as -// we remove the previous one. -// -// Return the index of a vertex just prior to the chain we've removed. -{ - assert(m_leftmost_vert == -1); - - int retval = vi; - - for (;;) - { - assert(is_valid(*sorted_verts, false /* don't check for dupes yet */)); - - poly_vert* pv1 = &(*sorted_verts)[vi]; - poly_vert* pv0 = &(*sorted_verts)[pv1->m_prev]; - poly_vert* pv2 = &(*sorted_verts)[pv1->m_next]; - - if (m_loop == vi) - { - // Change m_loop, since we're about to lose it. - m_loop = pv0->m_my_index; - } - - // Unlink vi. - - assert(pv0->m_poly_owner == this); - assert(pv1->m_poly_owner == this); - assert(pv2->m_poly_owner == this); - - pv0->m_next = pv2->m_my_index; - pv2->m_prev = pv0->m_my_index; - - pv1->m_next = -1; - pv1->m_prev = -1; - pv1->m_poly_owner = NULL; - - if (pv1->m_convex_result < 0) - { - // vi was reflex, remove it from index - assert(m_reflex_point_index); - ip_iterator it = - m_reflex_point_index->find(index_point(pv1->m_v.x, pv1->m_v.y), vi); - assert(it.at_end() == false); - - m_reflex_point_index->remove(&(*it)); - } - - if (pv1->m_is_ear) - { - m_ear_count--; - } - - // We lost vi. - m_vertex_count--; - - assert(is_valid(*sorted_verts, false /* don't check for dupes yet */)); - - if (m_vertex_count < 3) - { - retval = pv0->m_my_index; - break; - } - - // If we've created another degenerate, then remove it as well. - if (pv0->m_v == pv2->m_v) - { - // We've created a dupe in the chain, remove it now. - vi = pv0->m_my_index; - } - else if (vertex_left_test((*sorted_verts)[pv0->m_prev].m_v, pv0->m_v, pv2->m_v) == 0) - { - // More degenerate. - vi = pv0->m_my_index; - } - else if (vertex_left_test(pv0->m_v, pv2->m_v, (*sorted_verts)[pv2->m_next].m_v) == 0) - { - // More degenerate. - vi = pv2->m_my_index; - } - else - { - // ear/reflex status of pv0 & pv2 may have changed. - dirty_vert(sorted_verts, pv0->m_my_index); - dirty_vert(sorted_verts, pv2->m_my_index); - - retval = pv0->m_my_index; - - break; - } - } - - assert(is_valid(*sorted_verts, true /* do check for dupes; there shouldn't be any! */)); - - return retval; -} - - -template -void poly::update_connected_sub_poly(array* sorted_verts, int v_first_in_subloop, int v_first_after_subloop) -// Given the beginning and end of a sub-loop that has just been linked -// into our loop, update the verts on the sub-loop to have the correct -// owner, update our m_leftmost_vert and our m_vert_count. -{ - assert(v_first_in_subloop != v_first_after_subloop); - - int vi = v_first_in_subloop; - do - { - vert_t* pv = &(*sorted_verts)[vi]; - - pv->m_poly_owner = this; - m_vertex_count++; - - // Update leftmost vert. - if (pv->m_my_index < m_leftmost_vert) - { - m_leftmost_vert = pv->m_my_index; - } - - // Insert new edge into the edge index. - add_edge(*sorted_verts, vi); - - vi = pv->m_next; - } - while (vi != v_first_after_subloop); - - assert(is_valid(*sorted_verts)); -} - - - -template -void poly::init_edge_index(const array& sorted_verts, index_box& bound_of_all_verts) -// Initialize our edge-search structure, for quickly finding possible -// intersecting edges (when constructing bridges to join polys). -{ - assert(is_valid(sorted_verts)); - assert(m_edge_index == NULL); - - // Compute grid density. - int x_cells = 1; - int y_cells = 1; - if (sorted_verts.size() > 0) - { - const float GRID_SCALE = sqrtf(0.5f); - coord_t width = bound_of_all_verts.get_width(); - coord_t height = bound_of_all_verts.get_height(); - float area = float(width) * float(height); - if (area > 0) - { - float sqrt_n = sqrt((float) sorted_verts.size()); - float w = width * width / area * GRID_SCALE; - float h = height * height / area * GRID_SCALE; - x_cells = int(w * sqrt_n); - y_cells = int(h * sqrt_n); - } - else - { - // Zero area. - if (width > 0) - { - x_cells = int(GRID_SCALE * GRID_SCALE * sorted_verts.size()); - } - else - { - y_cells = int(GRID_SCALE * GRID_SCALE * sorted_verts.size()); - } - } - x_cells = iclamp(x_cells, 1, 256); - y_cells = iclamp(y_cells, 1, 256); - } - - m_edge_index = new grid_index_box(bound_of_all_verts, x_cells, y_cells); - - // Insert current edges into the index. - int vi = m_loop; - for (;;) - { - add_edge(sorted_verts, vi); - - vi = sorted_verts[vi].m_next; - if (vi == m_loop) - { - break; - } - } - - assert(is_valid(sorted_verts)); -} - - -template -void poly::init_for_ear_clipping(array* sorted_verts) -// Classify all verts for convexity. -// -// Initialize our point-search structure, for quickly finding reflex -// verts within a potential ear. -{ - assert(is_valid(*sorted_verts)); - - // Kill m_leftmost_vert; don't need it once all the polys are - // joined together into one loop. - m_leftmost_vert = -1; - - // Kill edge index; we don't need it for ear clipping. - delete m_edge_index; - m_edge_index = NULL; - - int reflex_vert_count = 0; - - bool bound_inited = false; - index_box reflex_bound(index_point(0, 0), index_point(0, 0)); - - int vi = m_loop; - for (;;) - { - // Classify vi as reflex/convex. - vert_t* pvi = &(*sorted_verts)[vi]; - pvi->m_convex_result = - vertex_left_test((*sorted_verts)[pvi->m_prev].m_v, pvi->m_v, (*sorted_verts)[pvi->m_next].m_v); - - if (pvi->m_convex_result < 0) - { - reflex_vert_count++; - - // Update bounds. - index_point location(pvi->m_v.x, pvi->m_v.y); - if (bound_inited == false) - { - bound_inited = true; - reflex_bound = index_box(location, location); - } - else - { - reflex_bound.expand_to_enclose(location); - } - } - - vi = (*sorted_verts)[vi].m_next; - if (vi == m_loop) - { - break; - } - } - - // Compute grid density. FIST recommends w * sqrt(N) * h * - // sqrt(N), where w*h is between 0.5 and 2. (N is the reflex - // vert count.) - int x_cells = 1; - int y_cells = 1; - if (reflex_vert_count > 0) - { - const float GRID_SCALE = sqrtf(0.5f); - coord_t width = reflex_bound.get_width(); - coord_t height = reflex_bound.get_height(); - float area = float(width) * float(height); - if (area > 0) - { - float sqrt_n = sqrt((float) reflex_vert_count); - float w = width * width / area * GRID_SCALE; - float h = height * height / area * GRID_SCALE; - x_cells = int(w * sqrt_n); - y_cells = int(h * sqrt_n); - } - else - { - // Zero area. - if (width > 0) - { - x_cells = int(GRID_SCALE * GRID_SCALE * reflex_vert_count); - } - else - { - y_cells = int(GRID_SCALE * GRID_SCALE * reflex_vert_count); - } - } - x_cells = iclamp(x_cells, 1, 256); - y_cells = iclamp(y_cells, 1, 256); - } - - m_reflex_point_index = new grid_index_point(reflex_bound, x_cells, y_cells); - - // Insert reflex verts into the index. - vi = m_loop; - for (;;) - { - vert_t* pvi = &(*sorted_verts)[vi]; - if (pvi->m_convex_result < 0) - { - // Reflex. Insert it. - m_reflex_point_index->add(index_point(pvi->m_v.x, pvi->m_v.y), vi); - } - - vi = (*sorted_verts)[vi].m_next; - if (vi == m_loop) - { - break; - } - } - - assert(is_valid(*sorted_verts)); -} - - -template -void poly::add_edge(const array& sorted_verts, int vi) -// Insert the edge (vi, vi->m_next) into the index. -{ - index_box ib(sorted_verts[vi].get_index_point()); - ib.expand_to_enclose(sorted_verts[sorted_verts[vi].m_next].get_index_point()); - - assert(m_edge_index); - - // Make sure edge isn't already in the index. - assert(m_edge_index->find_payload_from_point(sorted_verts[vi].get_index_point(), vi) == NULL); - - m_edge_index->add(ib, vi); -} - - -template -void poly::remove_edge(const array& sorted_verts, int vi) -// Remove the edge (vi, vi->m_next) from the index. -{ - assert(m_edge_index); - - grid_entry_box* entry = m_edge_index->find_payload_from_point(sorted_verts[vi].get_index_point(), vi); - assert(entry); - - m_edge_index->remove(entry); -} - - -template -bool poly::vert_can_see_cone_a(const array& sorted_verts, int v, int cone_a_vert, int cone_b_vert) -// Return true if v can see cone_a_vert, without logically crossing cone_b. -// cone_a_vert and cone_b_vert are coincident. -{ - assert(sorted_verts[cone_a_vert].m_v == sorted_verts[cone_b_vert].m_v); - - // @@ Thought: Would it be more robust to know whether v is - // part of a ccw or cw loop, and then decide based on the - // relative insideness/outsideness of v w/r/t the cones? - - // Analyze the two cones, to see if the segment - // (v,cone_a_vert) is blocked by cone_b_vert. Since - // cone_a_vert and cone_b_vert are coincident, we need to - // figure out the relationship among v and the cones. - - // Sort the cones so that they're in convex order. - const vert_t* pa = &sorted_verts[cone_a_vert]; - vec2 cone_a[3] = { sorted_verts[pa->m_prev].m_v, pa->m_v, sorted_verts[pa->m_next].m_v }; - if (vertex_left_test(cone_a[0], cone_a[1], cone_a[2]) < 0) - { - swap(&cone_a[0], &cone_a[2]); - } - - const vert_t* pb = &sorted_verts[cone_b_vert]; - vec2 cone_b[3] = { sorted_verts[pb->m_prev].m_v, pb->m_v, sorted_verts[pb->m_next].m_v }; - if (vertex_left_test(cone_b[0], cone_b[1], cone_b[2]) < 0) - { - swap(&cone_b[0], &cone_b[2]); - } - - // Characterize the cones w/r/t each other. - int a_in_b_sum = 0; - a_in_b_sum += vertex_left_test(cone_b[0], cone_b[1], cone_a[0]); - a_in_b_sum += vertex_left_test(cone_b[1], cone_b[2], cone_a[0]); - a_in_b_sum += vertex_left_test(cone_b[0], cone_b[1], cone_a[2]); - a_in_b_sum += vertex_left_test(cone_b[1], cone_b[2], cone_a[2]); - - int b_in_a_sum = 0; - b_in_a_sum += vertex_left_test(cone_a[0], cone_a[1], cone_b[0]); - b_in_a_sum += vertex_left_test(cone_a[1], cone_a[2], cone_b[0]); - b_in_a_sum += vertex_left_test(cone_a[0], cone_a[1], cone_b[2]); - b_in_a_sum += vertex_left_test(cone_a[1], cone_a[2], cone_b[2]); - - // Eeek! Need a better way of doing this... - bool a_in_b = false; - if (a_in_b_sum >= 4) - { - assert(b_in_a_sum <= -2); - a_in_b = true; - } - else if (a_in_b_sum == 3) - { - assert(b_in_a_sum <= 3); - - if (b_in_a_sum >= 3) - { - // Inconsistent (crossing cones). No good. - return false; - } - a_in_b = true; - } - else if (a_in_b_sum <= -4) - { - assert(b_in_a_sum >= 2); - a_in_b = false; - } - else if (a_in_b_sum == -3) - { - assert(b_in_a_sum >= -3); - - if (b_in_a_sum <= -3) - { - // Inconsistent (crossing cones). No good. - return false; - } - a_in_b = false; - } - else - { - if (b_in_a_sum >= 4) - { - assert(a_in_b_sum <= -2); - a_in_b = false; - } - else if (b_in_a_sum == 3) - { - a_in_b = false; - } - else if (b_in_a_sum <= -4) - { - assert(a_in_b_sum >= 2); - a_in_b = true; - } - else if (b_in_a_sum == -3) - { - a_in_b = true; - } - else - { - // Inconsistent or coincident. No good. - return false; - } - } - - if (a_in_b) - { - assert(a_in_b); - - bool v_in_a = - (vertex_left_test(cone_a[0], cone_a[1], sorted_verts[v].m_v) > 0) - && (vertex_left_test(cone_a[1], cone_a[2], sorted_verts[v].m_v) > 0); - if (v_in_a) - { - return true; - } - else - { - return false; - } - } - else - { - bool v_in_b = - (vertex_left_test(cone_b[0], cone_b[1], sorted_verts[v].m_v) > 0) - && (vertex_left_test(cone_b[1], cone_b[2], sorted_verts[v].m_v) > 0); - if (v_in_b) - { - return false; - } - else - { - return true; - } - } -} - - -template -bool poly::any_edge_intersection(const array& sorted_verts, int external_vert, int my_vert) -// Return true if edge (external_vert,my_vert) intersects any edge in our poly. -{ - // Check the edge index for potentially overlapping edges. - - const vert_t* pmv = &sorted_verts[my_vert]; - const vert_t* pev = &sorted_verts[external_vert]; - - assert(m_edge_index); - - index_box query_box(pmv->get_index_point()); - query_box.expand_to_enclose(pev->get_index_point()); - - for (ib_iterator it = m_edge_index->begin(query_box); - ! it.at_end(); - ++it) - { - int vi = it->value; - int v_next = sorted_verts[vi].m_next; - - if (vi != my_vert) - { - if (sorted_verts[vi].m_v == sorted_verts[my_vert].m_v) - { - // Coincident verts. - if (vert_can_see_cone_a(sorted_verts, external_vert, my_vert, vi) == false) - { - // Logical edge crossing. - return true; - } - } - else if (edges_intersect(sorted_verts, vi, v_next, external_vert, my_vert)) - { - return true; - } - } - } - - return false; -} - - -template -bool poly::ear_contains_reflex_vertex(const array& sorted_verts, int v0, int v1, int v2) -// Return true if any of this poly's reflex verts are inside the -// specified ear. The definition of inside is: a reflex vertex in the -// interior of the triangle (v0,v1,v2), or on the segments [v1,v0) or -// [v1,v2). -{ - // Compute the bounding box of reflex verts we want to check. - index_box query_bound(sorted_verts[v0].get_index_point()); - query_bound.expand_to_enclose(index_point(sorted_verts[v1].m_v.x, sorted_verts[v1].m_v.y)); - query_bound.expand_to_enclose(index_point(sorted_verts[v2].m_v.x, sorted_verts[v2].m_v.y)); - - for (ip_iterator it = m_reflex_point_index->begin(query_bound); - ! it.at_end(); - ++it) - { - int vk = it->value; - - const vert_t* pvk = &sorted_verts[vk]; - if (pvk->m_poly_owner != this) - { - // Not part of this poly; ignore it. - continue; - } - - if (vk != v0 && vk != v1 && vk != v2 - && query_bound.contains_point(index_point(pvk->m_v.x, pvk->m_v.y))) - { -#if 0 - //xxxxxx debug hook - if (v1 == 131 && vk == 132) - { - vk = vk;//xxxxx breakpoint here - } -#endif - - int v_next = pvk->m_next; - int v_prev = pvk->m_prev; - - if (pvk->m_v == sorted_verts[v1].m_v) - { - // Tricky case. See section 4.3 in FIST paper. - - // Note: I'm explicitly considering convex vk in here, unlike FIST. - // This is to handle the triple dupe case, where a loop validly comes - // straight through our cone. - // - // Note: the triple-dupe case is technically not a valid poly, since - // it contains a twist. - // - // @@ Fix this back to the FIST way? - - int v_prev_left01 = vertex_left_test( - sorted_verts[v0].m_v, - sorted_verts[v1].m_v, - sorted_verts[v_prev].m_v); - int v_next_left01 = vertex_left_test( - sorted_verts[v0].m_v, - sorted_verts[v1].m_v, - sorted_verts[v_next].m_v); - int v_prev_left12 = vertex_left_test( - sorted_verts[v1].m_v, - sorted_verts[v2].m_v, - sorted_verts[v_prev].m_v); - int v_next_left12 = vertex_left_test( - sorted_verts[v1].m_v, - sorted_verts[v2].m_v, - sorted_verts[v_next].m_v); - - if ((v_prev_left01 > 0 && v_prev_left12 > 0) - || (v_next_left01 > 0 && v_next_left12 > 0)) - { - // Local interior near vk intersects this - // ear; ear is clearly not valid. - return true; - } - - // Check colinear case, where cones of vk and v1 overlap exactly. - if ((v_prev_left01 == 0 && v_next_left12 == 0) - || (v_prev_left12 == 0 && v_next_left01 == 0)) - { - // @@ TODO: there's a somewhat complex non-local area test that tells us - // whether vk qualifies as a contained reflex vert. - // - // For the moment, deny the ear. - // - // The question is, is this test required for correctness? Because it - // seems pretty expensive to compute. If it's not required, I think it's - // better to always assume the ear is invalidated. - - //xxx - //fprintf(stderr, "colinear case in ear_contains_reflex_vertex; returning true\n"); - - return true; - } - } - else - { - assert(pvk->m_convex_result < 0); - if (vertex_in_ear( - pvk->m_v, sorted_verts[v0].m_v, sorted_verts[v1].m_v, sorted_verts[v2].m_v)) - { - // Found one. - return true; - } - } - } - } - - // Didn't find any qualifying verts. - return false; -} - - -template -bool poly::vert_in_cone(const array& sorted_verts, int vert, int cone_v0, int cone_v1, int cone_v2) -// Returns true if vert is within the cone defined by [v0,v1,v2]. -/* -// (out) v0 -// / -// v1 < (in) -// \ -// v2 -*/ -{ - bool acute_cone = vertex_left_test(sorted_verts[cone_v0].m_v, sorted_verts[cone_v1].m_v, sorted_verts[cone_v2].m_v) > 0; - - // Include boundary in our tests. - bool left_of_01 = - vertex_left_test(sorted_verts[cone_v0].m_v, sorted_verts[cone_v1].m_v, sorted_verts[vert].m_v) >= 0; - bool left_of_12 = - vertex_left_test(sorted_verts[cone_v1].m_v, sorted_verts[cone_v2].m_v, sorted_verts[vert].m_v) >= 0; - - if (acute_cone) - { - // Acute cone. Cone is intersection of half-planes. - return left_of_01 && left_of_12; - } - else - { - // Obtuse cone. Cone is union of half-planes. - return left_of_01 || left_of_12; - } -} - - -template -bool poly::vert_is_duplicated(const array& sorted_verts, int vert) -// Return true if there's another vertex in this poly, coincident with vert. -{ - // Scan backwards. - {for (int vi = vert - 1; vi >= 0; vi--) - { - if ((sorted_verts[vi].m_v == sorted_verts[vert].m_v) == false) - { - // No more coincident verts scanning backward. - break; - } - if (sorted_verts[vi].m_poly_owner == this) - { - // Found a dupe vert. - return true; - } - }} - - // Scan forwards. - {for (int vi = vert + 1, n = sorted_verts.size(); vi < n; vi++) - { - if ((sorted_verts[vi].m_v == sorted_verts[vert].m_v) == false) - { - // No more coincident verts scanning forward. - break; - } - if (sorted_verts[vi].m_poly_owner == this) - { - // Found a dupe vert. - return true; - } - }} - - // Didn't find a dupe. - return false; -} - - -// -// poly_env -// - - -template -struct poly_env -// Struct that holds the state of a triangulation. -{ -//data: - array > m_sorted_verts; - array*> m_polys; - - index_box m_bound; - int m_estimated_triangle_count; - -//code: - void init(int path_count, const array paths[]); - void join_paths_into_one_poly(); - - int get_estimated_triangle_count() const { return m_estimated_triangle_count; } - - poly_env() - : - m_bound(index_point(0, 0), index_point(0, 0)), - m_estimated_triangle_count(0) - { - } - - ~poly_env() - { - // delete the polys that got new'd during init() - for (int i = 0, n = m_polys.size(); i < n; i++) - { - delete m_polys[i]; - } - } - -private: - // Internal helpers. - void join_paths_with_bridge( - poly* main_poly, - poly* sub_poly, - int vert_on_main_poly, - int vert_on_sub_poly); - void dupe_two_verts(int v0, int v1); -}; - - -template -void poly_env::init(int path_count, const array paths[]) -// Initialize our state, from the given set of paths. Sort vertices -// and component polys. -{ - // Only call this on a fresh poly_env - assert(m_sorted_verts.size() == 0); - assert(m_polys.size() == 0); - - // Count total verts. - int vert_count = 0; - for (int i = 0; i < path_count; i++) - { - vert_count += paths[i].size(); - } - - // Slight over-estimate; the true number depends on how many - // of the paths are actually islands. - m_estimated_triangle_count = vert_count /* - 2 * path_count */; - - // Collect the input verts and create polys for the input paths. - m_sorted_verts.reserve(vert_count + (path_count - 1) * 2); // verts, plus two duped verts for each path, for bridges - m_polys.reserve(path_count); - - for (int i = 0; i < path_count; i++) - { - // Create a poly for this path. - const array& path = paths[i]; - - if (path.size() < 3) - { - // Degenerate path, ignore it. - continue; - } - - poly* p = new poly; - m_polys.push_back(p); - - // Add this path's verts to our list. - int path_size = path.size(); - if (path.size() & 1) - { - // Bad input, odd number of coords. - assert(0); - fprintf(stderr, "path[%d] has odd number of coords (%d), dropping last value\n", i, path.size());//xxxx - path_size--; - } - for (int j = 0; j < path_size; j += 2) // vertex coords come in pairs. - { - int prev_point = j - 2; - if (j == 0) prev_point = path_size - 2; - - if (path[j] == path[prev_point] && path[j + 1] == path[prev_point + 1]) - { - // Duplicate point; drop it. - continue; - } - - // Insert point. - int vert_index = m_sorted_verts.size(); - - poly_vert vert(path[j], path[j+1], p, vert_index); - m_sorted_verts.push_back(vert); - - p->append_vert(&m_sorted_verts, vert_index); - - index_point ip(vert.m_v.x, vert.m_v.y); - if (vert_index == 0) - { - // Initialize the bounding box. - m_bound.min = ip; - m_bound.max = ip; - } - else - { - // Expand the bounding box. - m_bound.expand_to_enclose(ip); - } - assert(m_bound.contains_point(ip)); - } - assert(p->is_valid(m_sorted_verts)); - - if (p->m_vertex_count == 0) - { - // This path was degenerate; kill it. - delete p; - m_polys.pop_back(); - } - } - - // Sort the vertices. - qsort(&m_sorted_verts[0], m_sorted_verts.size(), sizeof(m_sorted_verts[0]), compare_vertices); - assert(m_sorted_verts.size() <= 1 - || compare_vertices((void*) &m_sorted_verts[0], (void*) &m_sorted_verts[1]) <= 0); // check order - - // Remap the vertex indices, so that the polys and the - // sorted_verts have the correct, sorted, indices. We can - // then use vert indices to judge the left/right relationship - // of two verts. - array vert_remap; // vert_remap[i] == new index of original vert[i] - vert_remap.resize(m_sorted_verts.size()); - for (int i = 0, n = m_sorted_verts.size(); i < n; i++) - { - int new_index = i; - int original_index = m_sorted_verts[new_index].m_my_index; - vert_remap[original_index] = new_index; - } - {for (int i = 0, n = m_sorted_verts.size(); i < n; i++) - { - m_sorted_verts[i].remap(vert_remap); - }} - {for (int i = 0, n = m_polys.size(); i < n; i++) - { - m_polys[i]->remap(vert_remap); - assert(m_polys[i]->is_valid(m_sorted_verts)); - }} -} - - -template -void poly_env::join_paths_into_one_poly() -// Use zero-area bridges to connect separate polys & islands into one -// big continuous poly. -{ - // Connect separate paths with bridge edges, into one big path. - // - // Bridges are zero-area regions that connect a vert on each - // of two paths. - if (m_polys.size() > 1) - { - // Sort polys in order of each poly's leftmost vert. - qsort(&m_polys[0], m_polys.size(), sizeof(m_polys[0]), compare_polys_by_leftmost_vert); - assert(m_polys.size() <= 1 - || compare_polys_by_leftmost_vert((void*) &m_polys[0], (void*) &m_polys[1]) == -1); - - // assume that the enclosing boundary is the leftmost - // path; this is true if the regions are valid and - // don't intersect. - poly* full_poly = m_polys[0]; - - full_poly->init_edge_index(m_sorted_verts, m_bound); - - // Iterate from left to right - while (m_polys.size() > 1) - { - int v1 = m_polys[1]->m_leftmost_vert; - - // find v2 in full_poly, such that: - // v2 is to the left of v1, - // and v1-v2 seg doesn't intersect any other edges - - // // (note that since v1 is next-most-leftmost, v1-v2 can't - // // hit anything in p, or any paths further down the list, - // // it can only hit edges in full_poly) (need to think - // // about equality cases) - // - int v2 = full_poly->find_valid_bridge_vert(m_sorted_verts, v1); - - // once we've found v1 & v2, we use it to make a bridge, - // inserting p into full_poly - // - assert(m_sorted_verts[v2].m_poly_owner == m_polys[0]); - assert(m_sorted_verts[v1].m_poly_owner == m_polys[1]); - join_paths_with_bridge(full_poly, m_polys[1], v2, v1); - - // Drop the joined poly. - delete m_polys[1]; - m_polys.remove(1); - } - } - - m_polys[0]->init_for_ear_clipping(&m_sorted_verts); - - assert(m_polys.size() == 1); - // assert(all verts in m_sorted_verts have m_polys[0] as their owner); -} - - -template -void poly_env::join_paths_with_bridge( - poly* main_poly, - poly* sub_poly, - int vert_on_main_poly, - int vert_on_sub_poly) -// Absorb the sub-poly into the main poly, using a zero-area bridge -// between the two given verts. -{ - assert(vert_on_main_poly != vert_on_sub_poly); - assert(main_poly != NULL); - assert(sub_poly != NULL); - assert(main_poly != sub_poly); - assert(main_poly == m_sorted_verts[vert_on_main_poly].m_poly_owner); - assert(sub_poly == m_sorted_verts[vert_on_sub_poly].m_poly_owner); - - if (m_sorted_verts[vert_on_main_poly].m_v == m_sorted_verts[vert_on_sub_poly].m_v) - { - // Special case: verts to join are coincident. We - // don't actually need to make a bridge with new - // verts; we only need to adjust the links and do - // fixup. - poly_vert* pv_main = &m_sorted_verts[vert_on_main_poly]; - poly_vert* pv_sub = &m_sorted_verts[vert_on_sub_poly]; - - int main_next = pv_main->m_next; - - // Remove the edge we're about to break. - main_poly->remove_edge(m_sorted_verts, vert_on_main_poly); - - pv_main->m_next = pv_sub->m_next; - m_sorted_verts[pv_main->m_next].m_prev = vert_on_main_poly; - - pv_sub->m_next = main_next; - m_sorted_verts[main_next].m_prev = vert_on_sub_poly; - - // Add edge that connects to sub poly. - main_poly->add_edge(m_sorted_verts, vert_on_main_poly); - - // Fixup sub poly so it's now properly a part of the main poly. - main_poly->update_connected_sub_poly(&m_sorted_verts, pv_main->m_next, main_next); - sub_poly->invalidate(m_sorted_verts); - - return; - } - - // Normal case, need to dupe verts and create zero-area bridge. - dupe_two_verts(vert_on_main_poly, vert_on_sub_poly); - - // Fixup the old indices to account for the new dupes. - if (vert_on_sub_poly < vert_on_main_poly) - { - vert_on_main_poly++; - } - else - { - vert_on_sub_poly++; - } - - poly_vert* pv_main = &m_sorted_verts[vert_on_main_poly]; - poly_vert* pv_sub = &m_sorted_verts[vert_on_sub_poly]; - poly_vert* pv_main2 = &m_sorted_verts[vert_on_main_poly + 1]; - poly_vert* pv_sub2 = &m_sorted_verts[vert_on_sub_poly + 1]; - - // Remove the edge we're about to break. - main_poly->remove_edge(m_sorted_verts, vert_on_main_poly); - - // Link the loops together. - pv_main2->m_next = pv_main->m_next; - pv_main2->m_prev = vert_on_sub_poly + 1; // (pv_sub2) - m_sorted_verts[pv_main2->m_next].m_prev = pv_main2->m_my_index; - - pv_sub2->m_prev = pv_sub->m_prev; - pv_sub2->m_next = vert_on_main_poly + 1; // (pv_main2) - m_sorted_verts[pv_sub2->m_prev].m_next = pv_sub2->m_my_index; - - pv_main->m_next = vert_on_sub_poly; // (pv_sub) - pv_sub->m_prev = vert_on_main_poly; // (pv_main) - - // Add edge that connects to sub poly. - main_poly->add_edge(m_sorted_verts, vert_on_main_poly); - - // Fixup sub poly so it's now properly a part of the main poly. - main_poly->update_connected_sub_poly(&m_sorted_verts, vert_on_sub_poly, pv_main2->m_next); - sub_poly->invalidate(m_sorted_verts); - - assert(pv_main->m_poly_owner->is_valid(m_sorted_verts)); -} - - -template -void poly_env::dupe_two_verts(int v0, int v1) -// Duplicate the two indexed verts, remapping polys & verts as necessary. -{ - // Order the verts. - if (v0 > v1) - { - swap(&v0, &v1); - } - assert(v0 < v1); - - // Duplicate verts. - poly_vert v0_copy = m_sorted_verts[v0]; - poly_vert v1_copy = m_sorted_verts[v1]; - - // @@ This stuff can be costly! E.g. lots of separate little - // polys that need bridges, with a high total vert count. - - // Slower, clearer code to insert the two new verts. This - // ends up moving the data between ((v1+1), end) twice. - if (0) { - // Insert v1 first, so v0 doesn't get moved. - m_sorted_verts.insert(v1 + 1, v1_copy); - m_sorted_verts.insert(v0 + 1, v0_copy); - } - else - // Faster, more obfuscated code to insert the two new verts. - // - // NOTE: I tried doing this in one pass, with a complicated - // explicit move & remap in the same pass. It was much - // slower! (VC7, Win2K.) memmove() must be magical? - { - // Make room. - m_sorted_verts.resize(m_sorted_verts.size() + 2); - - // Move the two subsegments. - memmove(&m_sorted_verts[v1 + 3], &m_sorted_verts[v1 + 1], sizeof(m_sorted_verts[0]) * (m_sorted_verts.size() - 3 - v1)); - memmove(&m_sorted_verts[v0 + 2], &m_sorted_verts[v0 + 1], sizeof(m_sorted_verts[0]) * (v1 - v0)); - - // Insert the new duplicate verts. - m_sorted_verts[v0 + 1] = v0_copy; - m_sorted_verts[v1 + 2] = v1_copy; - } - - // Remap the indices within the verts. - for (int i = 0, n = m_sorted_verts.size(); i < n; i++) - { - m_sorted_verts[i].m_my_index = i; - m_sorted_verts[i].m_next = remap_index_for_duped_verts(m_sorted_verts[i].m_next, v0, v1); - m_sorted_verts[i].m_prev = remap_index_for_duped_verts(m_sorted_verts[i].m_prev, v0, v1); - } - - // Remap the polys. - {for (int i = 0, n = m_polys.size(); i < n; i++) - { - m_polys[i]->remap_for_duped_verts(m_sorted_verts, v0, v1); - - assert(m_polys[i]->is_valid(m_sorted_verts)); - }} -} - - -// -// Helpers. -// - - -template -static void recovery_process( - array*>* polys, // polys waiting to be processed - poly* P, // current poly - array >* sorted_verts, - tu_random::generator* rg); - - -template -inline void debug_emit_poly_loop( - array* result, - const array >& sorted_verts, - poly* P) -// Fill *result with a poly loop representing P. -{ - result->resize(0); // clear existing junk. - - int first_vert = P->m_loop; - int vi = first_vert; - do - { - result->push_back(sorted_verts[vi].m_v.x); - result->push_back(sorted_verts[vi].m_v.y); - vi = sorted_verts[vi].m_next; - } - while (vi != first_vert); - - // Loop back to beginning, and pad to a multiple of 3 coords. - do - { - result->push_back(sorted_verts[vi].m_v.x); - result->push_back(sorted_verts[vi].m_v.y); - } - while (result->size() % 6); -} - - -template -static void compute_triangulation( - array* result, - int path_count, - const array paths[], - int debug_halt_step, - array* debug_remaining_loop) -// Compute triangulation. -// -// The debug_ args are optional; they're for terminating early and -// returning the remaining loop to be triangulated. -{ - if (path_count <= 0) - { - // Empty paths --> no triangles to emit. - return; - } - -#ifdef PROFILE_TRIANGULATE - uint64 start_ticks = tu_timer::get_profile_ticks(); -#endif // PROFILE_TRIANGULATE - - // Local generator, for some parts of the algo that need random numbers. - tu_random::generator rand_gen; - - // Poly environment; most of the state of the algo. - poly_env penv; - - penv.init(path_count, paths); - - penv.join_paths_into_one_poly(); - - result->reserve(2 * 3 * penv.get_estimated_triangle_count()); - - int input_vert_count = 0; - if (penv.m_polys.size() > 0) - { - input_vert_count = penv.m_polys[0]->get_vertex_count(); - } - -#ifdef PROFILE_TRIANGULATE - uint64 join_ticks = tu_timer::get_profile_ticks(); - fprintf(stderr, "join poly = %1.6f sec\n", tu_timer::profile_ticks_to_seconds(join_ticks - start_ticks)); -#endif // PROFILE_TRIANGULATE - -// Debugging only: dump coords of joined poly. -//#define DUMP_JOINED_POLY -#ifdef DUMP_JOINED_POLY - { - int first_vert = penv.m_polys[0]->m_loop; - int vi = first_vert; - do - { - printf("%f, %f\n", penv.m_sorted_verts[vi].m_v.x, penv.m_sorted_verts[vi].m_v.y); - vi = penv.m_sorted_verts[vi].m_next; - } - while (vi != first_vert); - } -#endif - -// Debugging only: just emit our joined poly, without triangulating. -//#define EMIT_JOINED_POLY -#ifdef EMIT_JOINED_POLY - { - int first_vert = penv.m_polys[0]->m_loop; - int vi = first_vert; - do - { - result->push_back(penv.m_sorted_verts[vi].m_v.x); - result->push_back(penv.m_sorted_verts[vi].m_v.y); - vi = penv.m_sorted_verts[vi].m_next; - } - while (vi != first_vert); - - // Loop back to beginning, and pad to a multiple of 3 coords. - do - { - result->push_back(penv.m_sorted_verts[vi].m_v.x); - result->push_back(penv.m_sorted_verts[vi].m_v.y); - } - while (result->size() % 6); - } - - return; -#endif // EMIT_JOINED_POLY - - // ear-clip, adapted from FIST paper: - // - // list L; - // L.insert(full_poly) - // while L not empty: - // P = L.pop() - // Q = priority queue of ears of P - // while P.vert_count > 3 do: - // if Q not empty: - // e = Q.pop - // emit e - // update P by deleting e - // else if an ear was clipped in previous pass then: - // Q = priority queue of ears of P (i.e. reexamine P) - // else - // // we're stuck - // recovery_process() // do something drastic to make the next move - // emit last 3 verts of P as the final triangle - - while (penv.m_polys.size()) - { - poly* P = penv.m_polys.back(); - penv.m_polys.pop_back(); - - P->build_ear_list(&penv.m_sorted_verts, &rand_gen); - - bool ear_was_clipped = false; - while (P->get_vertex_count() > 3) - { - if (P->get_ear_count() > 0) - { - // Clip the next ear from Q. - int v1 = P->get_next_ear(penv.m_sorted_verts, &rand_gen); - int v0 = penv.m_sorted_verts[v1].m_prev; - int v2 = penv.m_sorted_verts[v1].m_next; - - P->emit_and_remove_ear(result, &penv.m_sorted_verts, v0, v1, v2); - ear_was_clipped = true; - - // For debugging -- terminate early if the debug counter hits zero. - debug_halt_step--; - if (debug_halt_step == 0) { - if (debug_remaining_loop) { - debug_emit_poly_loop(debug_remaining_loop, penv.m_sorted_verts, P); - } - return; - } - } - else if (ear_was_clipped == true) - { - // Re-examine P for new ears. - ear_was_clipped = P->build_ear_list(&penv.m_sorted_verts, &rand_gen); - } - else - { - // No valid ears; we're in trouble so try some fallbacks. - -#if 1 - // xxx hack for debugging: show the state of P when we hit the recovery process. - debug_emit_poly_loop(result, penv.m_sorted_verts, P); - return; -#endif - - recovery_process(&penv.m_polys, P, &penv.m_sorted_verts, &rand_gen); - ear_was_clipped = false; - } - } - - if (P->get_vertex_count() == 3) - { - // Emit the final triangle. - if (penv.m_sorted_verts[P->m_loop].m_is_ear == false) - { - // Force an arbitrary vert to be an ear. - penv.m_sorted_verts[P->m_loop].m_is_ear = true; - P->m_ear_count++; - } - P->emit_and_remove_ear( - result, - &penv.m_sorted_verts, - penv.m_sorted_verts[P->m_loop].m_prev, - P->m_loop, - penv.m_sorted_verts[P->m_loop].m_next); - } - delete P; - } - -#ifdef PROFILE_TRIANGULATE - uint64 clip_ticks = tu_timer::get_profile_ticks(); - fprintf(stderr, "clip poly = %1.6f sec\n", tu_timer::profile_ticks_to_seconds(clip_ticks - join_ticks)); - fprintf(stderr, "total for poly = %1.6f sec\n", tu_timer::profile_ticks_to_seconds(clip_ticks - start_ticks)); - fprintf(stderr, "vert count = %d, verts clipped / sec = %f\n", - input_vert_count, - input_vert_count / tu_timer::profile_ticks_to_seconds(clip_ticks - join_ticks)); -#endif // PROFILE_TRIANGULATE - - assert(penv.m_polys.size() == 0); - // assert(for all penv.m_sorted_verts: owning poly == NULL); - - assert((result->size() % 6) == 0); -} - - -template -void recovery_process( - array*>* polys, - poly* P, - array >* sorted_verts, - tu_random::generator* rg) -{ - // recovery_process: - // if two edges in P, e[i-1] and e[i+1] intersect: - // insert two tris incident on e[i-1] & e[i+1] as ears into Q - // else if P can be split with a valid diagonal: - // P = one side - // L += the other side - // Q = ears of P - // else if P has any convex vertex: - // pick a random convex vert and add it to Q - // else - // pick a random vert and add it to Q - - // Case 1: two edges, e[i-1] and e[i+1], intersect; we insert - // the overlapping ears into Q and resume. - {for (int vi = (*sorted_verts)[P->m_loop].m_next; vi != P->m_loop; vi = (*sorted_verts)[vi].m_next) - { - int ev0 = vi; - int ev1 = (*sorted_verts)[ev0].m_next; - int ev2 = (*sorted_verts)[ev1].m_next; - int ev3 = (*sorted_verts)[ev2].m_next; - if (edges_intersect(*sorted_verts, ev0, ev1, ev2, ev3)) - { - // Insert (1,2,3) as an ear. - (*sorted_verts)[ev2].m_is_ear = true; - P->m_ear_count++; - - fprintf(stderr, "recovery_process: self-intersecting sequence, treating %d as an ear\n", ev2);//xxxx - - // Resume regular processing. - return; - } - }} - -// Deviation from FIST: Because I'm lazy, I'm skipping this test for -// now... -// -// @@ This seems to be helpful for doing reasonable things in case the -// input is a little bit self-intersecting. Otherwise, clipping any -// old convex or random vert can create crazy junk in the -// triangulation. It's probably worth implementing at some point. -#if 0 - // Case 2: P can be split with a valid diagonal. - // - // A "valid diagonal" passes these checks, according to FIST: - // - // 1. diagonal is locally within poly - // - // 2. its relative interior does not intersect any edge of the poly - // - // 3. the winding number of the polygon w/r/t the midpoint of - // the diagonal is one - // - {for (int vi = verts[0, end]) - { - for (int vj = verts[vi->m_next, end]) - { - if (P->valid_diagonal(vi, vj)) - { - // Split P, insert leftover piece into polys - poly* leftover = P->split(vi, vj); - polys->push_back(leftover); - - // Resume regular processing. - return; - } - } - }} -#endif // 0 - - // Case 3: P has any convex vert - int first_vert = P->m_loop; - int vi = first_vert; - int vert_count = 0; - do - { - if (is_convex_vert(*sorted_verts, vi)) - { - // vi is convex; treat it as an ear, - // regardless of other problems it may have. - (*sorted_verts)[vi].m_is_ear = true; - P->m_ear_count++; - - fprintf(stderr, "recovery_process: found convex vert, treating %d as an ear\n", vi);//xxxx - - // Resume regular processing. - return; - } - - vert_count++; - vi = (*sorted_verts)[vi].m_next; - } - while (vi != first_vert); - - // Case 4: Pick a random vert and treat it as an ear. - int random_vert = rg->next_random() % vert_count; - for (vi = first_vert; random_vert > 0; random_vert--) - { - vi = (*sorted_verts)[vi].m_next; - } - (*sorted_verts)[vi].m_is_ear = true; - P->m_ear_count++; - - fprintf(stderr, "recovery_process: treating random vert %d as an ear\n", vi);//xxxx - - // Resume. - return; -} - - -// Local Variables: -// mode: C++ -// c-basic-offset: 8 -// tab-width: 8 -// indent-tabs-mode: t -// End: diff --git a/Code/BF2/External/base/triangulate_sint32.cpp b/Code/BF2/External/base/triangulate_sint32.cpp deleted file mode 100644 index 339fbc6e9..000000000 --- a/Code/BF2/External/base/triangulate_sint32.cpp +++ /dev/null @@ -1,33 +0,0 @@ -// triangulate_sint32.cpp -- Thatcher Ulrich 2004 - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - -// Code to triangulate arbitrary 2D polygonal regions. -// -// Instantiate our templated algo from triangulate_inst.h - -#include "base/triangulate_impl.h" - - -namespace triangulate -{ - // Version using sint32 coords - void compute( - array* result, // trilist - int path_count, - const array paths[], - int debug_halt_step /* = -1 */, - array* debug_remaining_loop /* = NULL */) - { - compute_triangulation(result, path_count, paths, debug_halt_step, debug_remaining_loop); - } -} - - -// Local Variables: -// mode: C++ -// c-basic-offset: 8 -// tab-width: 8 -// indent-tabs-mode: t -// End: diff --git a/Code/BF2/External/base/tu_file.cpp b/Code/BF2/External/base/tu_file.cpp index b73f5993f..6cec69aca 100644 --- a/Code/BF2/External/base/tu_file.cpp +++ b/Code/BF2/External/base/tu_file.cpp @@ -1,11 +1,12 @@ -// tu_file.cpp -- Ignacio Castaño, Thatcher Ulrich 2003 +// tu_file.cpp -- Ignacio Castaño, Thatcher Ulrich 2003 // This source code has been donated to the Public Domain. Do // whatever you want with it. // A file class that can be customized with callbacks. - +#include +#include #include "base/tu_file.h" #include "base/utility.h" #include "base/container.h" @@ -17,6 +18,7 @@ // +// Retail SwiffPlayer.dll 0x1006DCB0. static int std_read_func(void* dst, int bytes, void* appdata) // Return the number of bytes actually read. EOF or an error would // cause that to not be equal to "bytes". @@ -26,6 +28,7 @@ static int std_read_func(void* dst, int bytes, void* appdata) return fread( dst, 1, bytes, (FILE *)appdata ); } +// Retail SwiffPlayer.dll 0x1006DCD0. static int std_write_func(const void* src, int bytes, void* appdata) // Return the number of bytes actually written. { @@ -34,6 +37,7 @@ static int std_write_func(const void* src, int bytes, void* appdata) return fwrite( src, 1, bytes, (FILE *)appdata ); } +// Retail SwiffPlayer.dll 0x1006DCF0. static int std_seek_func(int pos, void *appdata) // Return 0 on success, or TU_FILE_SEEK_ERROR on failure. { @@ -48,6 +52,7 @@ static int std_seek_func(int pos, void *appdata) return 0; } +// Retail SwiffPlayer.dll 0x1006DD20. static int std_seek_to_end_func(void *appdata) // Return 0 on success, TU_FILE_SEEK_ERROR on failure. { @@ -61,6 +66,7 @@ static int std_seek_to_end_func(void *appdata) return 0; } +// Retail SwiffPlayer.dll 0x1006DD40. static int std_tell_func(const void *appdata) // Return the file position, or -1 on failure. { @@ -68,6 +74,7 @@ static int std_tell_func(const void *appdata) return ftell((FILE*)appdata); } +// Retail SwiffPlayer.dll 0x1006DD50: use the CRT's EOF flag. static bool std_get_eof_func(void *appdata) // Return true if we're at EOF. { @@ -82,6 +89,7 @@ static bool std_get_eof_func(void *appdata) } } +// Retail SwiffPlayer.dll 0x1006DD60. static int std_close_func(void *appdata) // Return 0 on success, or TU_FILE_CLOSE_ERROR on failure. { @@ -103,12 +111,16 @@ static int std_close_func(void *appdata) struct filebuf { - membuf m_; + int m_size; + void* m_data; int m_position; bool m_read_only; + // Retail SwiffPlayer.dll 0x1006DD80 (S1 called this membuf). filebuf() : + m_size(0), + m_data(0), m_position(0), m_read_only(false) { @@ -116,28 +128,35 @@ struct filebuf filebuf(int size, void* data) : - m_(membuf::READ_ONLY, data, size), + m_size(size), + m_data(data), m_position(0), m_read_only(true) { } + // Retail SwiffPlayer.dll 0x1006DDB0 / deleting veneer 0x1006DF40. ~filebuf() { + if (!m_read_only && m_data) tu_free(m_data, m_size); } + // Retail SwiffPlayer.dll 0x1006DDD0; allocation uses the native issue #7 hook. bool resize(int new_size) // Return false if we couldn't resize. { if (m_read_only) return false; - m_.resize(new_size); + void* data = tu_realloc(m_data, new_size, m_size); + if (new_size > 0 && data == 0) return false; + m_data = data; + m_size = new_size; // Hm, does this make sense? We're truncating the file, so clamping the cursor. // Alternative would be to disallow resize, but that doesn't seem good either. - if (m_position > m_.size()) + if (m_position > m_size) { - m_position = m_.size(); + m_position = m_size; } return true; @@ -147,13 +166,15 @@ struct filebuf { return m_position >= 0 - && m_position <= m_.size(); + && m_position <= m_size; } - unsigned char* get_cursor() { return ((unsigned char*) m_.data()) + m_position; } + // Retail SwiffPlayer.dll 0x1006DE20. + unsigned char* get_cursor() { return ((unsigned char*) m_data) + m_position; } }; +// Retail SwiffPlayer.dll 0x1006DE30. static int mem_read_func(void* dst, int bytes, void* appdata) // Return the number of bytes actually read. EOF or an error would // cause that to not be equal to "bytes". @@ -164,7 +185,7 @@ static int mem_read_func(void* dst, int bytes, void* appdata) filebuf* buf = (filebuf*) appdata; assert(buf->is_valid()); - int bytes_to_read = imin(bytes, buf->m_.size() - buf->m_position); + int bytes_to_read = imin(bytes, buf->m_size - buf->m_position); if (bytes_to_read) { memcpy(dst, buf->get_cursor(), bytes_to_read); @@ -175,6 +196,7 @@ static int mem_read_func(void* dst, int bytes, void* appdata) } +// Retail SwiffPlayer.dll 0x1006DE80. static int mem_write_func(const void* src, int bytes, void* appdata) // Return the number of bytes actually written. { @@ -185,10 +207,10 @@ static int mem_write_func(const void* src, int bytes, void* appdata) assert(buf->is_valid()); // Expand buffer if necessary. - int bytes_to_expand = imax(0, buf->m_position + bytes - buf->m_.size()); + int bytes_to_expand = imax(0, buf->m_position + bytes - buf->m_size); if (bytes_to_expand) { - if (buf->resize(buf->m_.size() + bytes_to_expand) == false) + if (buf->resize(buf->m_size + bytes_to_expand) == false) { // Couldn't expand! return 0; @@ -201,11 +223,11 @@ static int mem_write_func(const void* src, int bytes, void* appdata) return bytes; } +// Retail SwiffPlayer.dll 0x1006DEE0. static int mem_seek_func(int pos, void *appdata) // Return 0 on success, or TU_FILE_SEEK_ERROR on failure. { assert(appdata); - assert(pos >= 0); filebuf* buf = (filebuf*) appdata; assert(buf->is_valid()); @@ -216,9 +238,9 @@ static int mem_seek_func(int pos, void *appdata) return TU_FILE_SEEK_ERROR; } - if (pos > buf->m_.size()) + if (pos > buf->m_size) { - buf->m_position = buf->m_.size(); + buf->m_position = buf->m_size; return TU_FILE_SEEK_ERROR; } @@ -226,6 +248,7 @@ static int mem_seek_func(int pos, void *appdata) return 0; } +// Retail SwiffPlayer.dll 0x1006DF10. static int mem_seek_to_end_func(void* appdata) // Return 0 on success, TU_FILE_SEEK_ERROR on failure. { @@ -234,10 +257,11 @@ static int mem_seek_to_end_func(void* appdata) filebuf* buf = (filebuf*) appdata; assert(buf->is_valid()); - buf->m_position = buf->m_.size(); + buf->m_position = buf->m_size; return 0; } +// Retail SwiffPlayer.dll 0x1006DF20. static int mem_tell_func(const void* appdata) // Return the file position, or -1 on failure. { @@ -249,6 +273,7 @@ static int mem_tell_func(const void* appdata) return buf->m_position; } +// Retail SwiffPlayer.dll 0x1006DF30. static bool mem_get_eof_func(void* appdata) // Return true if we're positioned at the end of the buffer. { @@ -257,17 +282,14 @@ static bool mem_get_eof_func(void* appdata) filebuf* buf = (filebuf*) appdata; assert(buf->is_valid()); - return buf->m_position >= buf->m_.size(); + return buf->m_position >= buf->m_size; } +// Retail SwiffPlayer.dll 0x1006E280. static int mem_close_func(void* appdata) // Return 0 on success, or TU_FILE_CLOSE_ERROR on failure. { - assert(appdata); - filebuf* buf = (filebuf*) appdata; - assert(buf->is_valid()); - delete buf; return 0; @@ -279,6 +301,7 @@ static int mem_close_func(void* appdata) // +// Retail SwiffPlayer.dll 0x1006DF80. tu_file::tu_file( void * appdata, read_func rf, @@ -302,6 +325,7 @@ tu_file::tu_file( } +// Retail SwiffPlayer.dll 0x1006DFC0. tu_file::tu_file(FILE* fp, bool autoclose=false) // Create a file from a standard file pointer. { @@ -317,6 +341,7 @@ tu_file::tu_file(FILE* fp, bool autoclose=false) } +// Retail SwiffPlayer.dll 0x1006E010. tu_file::tu_file(const char * name, const char * mode) // Create a file from the given name and the given mode. { @@ -346,10 +371,11 @@ tu_file::tu_file(const char * name, const char * mode) } +// Retail SwiffPlayer.dll 0x1006E2B0. tu_file::tu_file(memory_buffer_enum m) // Create a read/write memory buffer. { - m_data = new membuf; + m_data = new (std::nothrow) filebuf; m_read = mem_read_func; m_write = mem_write_func; @@ -362,10 +388,11 @@ tu_file::tu_file(memory_buffer_enum m) } +// Retail SwiffPlayer.dll 0x1006E310: borrow data; only growth is refused. tu_file::tu_file(memory_buffer_enum m, int size, void* data) -// Create a read-only memory buffer, using the given data. +// Create a borrowed memory buffer that cannot grow. { - m_data = new membuf(data, size); + m_data = new (std::nothrow) filebuf(size, data); m_read = mem_read_func; m_write = mem_write_func; @@ -378,6 +405,7 @@ tu_file::tu_file(memory_buffer_enum m, int size, void* data) } +// Retail SwiffPlayer.dll 0x1006E380. tu_file::~tu_file() // Close this file when destroyed. { @@ -385,6 +413,7 @@ tu_file::~tu_file() } +// Retail SwiffPlayer.dll 0x1006E090: end/EOF callbacks and error are left alone. void tu_file::close() // Close this file. { @@ -401,6 +430,7 @@ void tu_file::close() } +// Retail SwiffPlayer.dll 0x1006E0C0. void tu_file::copy_from(tu_file* src) // Copy remaining contents of *src into *this. { @@ -441,6 +471,7 @@ void tu_file::copy_to(membuf* dst) } +// Retail SwiffPlayer.dll 0x1006E110. int tu_file::copy_bytes(tu_file* src, int byte_count) // Copy a fixed number of bytes from *src into *this. Return the // number of bytes copied. @@ -474,20 +505,18 @@ int tu_file::copy_bytes(tu_file* src, int byte_count) } +// Retail SwiffPlayer.dll 0x1006E190: test the next byte; omit its NUL. void tu_file::write_string(const char* src) { - for (;;) + do { - write8(*src); - if (*src == 0) - { - break; - } - src++; + write8(*src++); } + while (*src != 0); } +// Retail SwiffPlayer.dll 0x1006E1D0. int tu_file::read_string(char* dst, int max_length) { int i=0; @@ -508,24 +537,27 @@ int tu_file::read_string(char* dst, int max_length) -#include -#include - -#ifdef _WIN32 -#define vsnprintf _vsnprintf -#endif // _WIN32 - - int tu_file::printf(const char* fmt, ...) // Use printf-like semantics to send output to this stream. { + // SwiffPlayer.dll 0x1006E220: format, scan for NUL, forward the write result. // Workspace for vsnprintf formatting. static const int BUFFER_SIZE = 1000; char buffer[BUFFER_SIZE]; va_list ap; va_start(ap, fmt); - vsnprintf(buffer, BUFFER_SIZE, fmt, ap); +#if defined(_WIN32) + _vsnprintf(buffer, BUFFER_SIZE, fmt, ap); +#else + // [CHOSEN, not recovered] POSIX CRT bridge: retain native formatting, + // locale and error semantics, with the retail full-workspace nontermination. + char formatted[BUFFER_SIZE + 1]; + memcpy(formatted, buffer, BUFFER_SIZE); + const int count = vsnprintf(formatted, sizeof(formatted), fmt, ap); + const int bytes = count >= 0 && count < BUFFER_SIZE ? count + 1 : BUFFER_SIZE; + memcpy(buffer, formatted, bytes); +#endif va_end(ap); return write_bytes(buffer, strlen(buffer)); diff --git a/Code/BF2/External/base/tu_file.h b/Code/BF2/External/base/tu_file.h index 0ea5a59da..ea13953a8 100644 --- a/Code/BF2/External/base/tu_file.h +++ b/Code/BF2/External/base/tu_file.h @@ -1,4 +1,4 @@ -// tu_file.h -- Ignacio Castaño, Thatcher Ulrich 2003 +// tu_file.h -- Ignacio Castaño, Thatcher Ulrich 2003 // This source code has been donated to the Public Domain. Do // whatever you want with it. @@ -72,9 +72,12 @@ class tu_file enum memory_buffer_enum { memory_buffer }; tu_file(memory_buffer_enum m); - // A read-only memory-buffer with predefined data. + // Borrow a fixed-size buffer. In-range writes modify data; growth is refused. + // The caller keeps data alive until this file is destroyed. tu_file(memory_buffer_enum m, int size, void* data); + // SwiffPlayer.dll 0x1006E380; scalar deleting wrapper 0x1006F300. + // The wrapper alone does not establish a virtual destructor slot. ~tu_file(); // Copy remaining contents of *in into *this. @@ -106,9 +109,10 @@ class tu_file // Read/write a byte buffer. // Returns number of bytes read/written. int read_bytes(void* dst, int num) { return m_read(dst, num, m_data); } + // Retail SwiffPlayer.dll 0x1006DC10. int write_bytes(const void* src, int num) { return m_write(src, num, m_data); } - // write a 0-terminated string. + // Write the bytes of a nonempty 0-terminated string, excluding the terminator. void write_string(const char* src); // Read up to max_length characters, returns the number of characters @@ -126,14 +130,20 @@ class tu_file double read_double64(); // get/set pos + // Retail SwiffPlayer.dll 0x1006EA70. int get_position() const { return m_tell(m_data); } + // Retail SwiffPlayer.dll 0x1009D1F0 discards the seek callback's result. void set_position(int p) { m_seek(p, m_data); } + // Retail SwiffPlayer.dll 0x100A47B0 forwards only the application data. void go_to_end() { m_seek_to_end(m_data); } + // Retail SwiffPlayer.dll 0x1006DC30. bool get_eof() { return m_get_eof(m_data); } + // Retail SwiffPlayer.dll 0x1006DC40. int get_error() { return m_error; } - // printf-style convenience function. + // Formats into a 1000-byte workspace and returns the write callback's result. + // A full workspace remains unterminated when its length is scanned. int printf(const char* fmt, ...); // UNSAFE back door, for testing only. @@ -142,13 +152,16 @@ class tu_file private: Uint64 read64() { Uint64 u; m_read(&u, 8, m_data); return u; } + // Retail SwiffPlayer.dll 0x1006EA80 / 0x1006EAA0 (integer/float callers). Uint32 read32() { Uint32 u; m_read(&u, 4, m_data); return u; } Uint16 read16() { Uint16 u; m_read(&u, 2, m_data); return u; } + // Retail SwiffPlayer.dll 0x1006DC50 / 0x1009D340: discard the callback result. Uint8 read8() { Uint8 u; m_read(&u, 1, m_data); return u; } void write64(Uint64 u) { m_write(&u, 8, m_data); } void write32(Uint32 u) { m_write(&u, 4, m_data); } void write16(Uint16 u) { m_write(&u, 2, m_data); } + // Retail SwiffPlayer.dll 0x1006DC70 / 0x100A4F40. void write8(Uint8 u) { m_write(&u, 1, m_data); } void close(); diff --git a/Code/BF2/External/base/tu_file_SDL.cpp b/Code/BF2/External/base/tu_file_SDL.cpp deleted file mode 100644 index 6586de852..000000000 --- a/Code/BF2/External/base/tu_file_SDL.cpp +++ /dev/null @@ -1,120 +0,0 @@ -// tu_file_SDL.cpp -- Ignacio Castaño, Thatcher Ulrich 2003 - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - -// tu_file constructor, for creating a tu_file from an SDL_RWops* -// stream. In its own source file so that if clients of the base -// library don't call it, it won't get pulled in by the linker and -// won't try to link with SDL. - - -#include "base/tu_file.h" -#include "base/utility.h" -#include - - -// TODO: add error detection and reporting!!! - -static int sdl_read_func(void* dst, int bytes, void* appdata) -{ - assert(dst); - assert(appdata); - int result = SDL_RWread((SDL_RWops*) appdata, dst, 1, bytes); - if (result == -1) - { - // @@ set appdata->m_error? - return 0; - } - return result; -} - -static int sdl_write_func(const void* src, int bytes, void* appdata) -{ - assert(src); - assert(appdata); - int result = SDL_RWwrite((SDL_RWops*) appdata, src, 1, bytes); - if (result == -1) - { - // @@ set m_errer? - return 0; - } - return result; -} - -static int sdl_seek_func(int pos, void *appdata) -{ - assert(pos >= 0); - assert(appdata); - return SDL_RWseek((SDL_RWops*) appdata, pos, SEEK_SET); -} - -static int sdl_seek_to_end_func(void *appdata) -{ - assert(appdata); - return SDL_RWseek((SDL_RWops*) appdata, 0, SEEK_END); -} - -static int sdl_tell_func(const void *appdata) -{ - assert(appdata); - return SDL_RWtell((SDL_RWops*) appdata); -} - -static bool sdl_get_eof_func(void* appdata) -{ - assert(appdata); - - int cur_pos = sdl_tell_func(appdata); - sdl_seek_to_end_func(appdata); - int end_pos = sdl_tell_func(appdata); - if (end_pos <= cur_pos) - { - return true; - } - else - { - sdl_seek_func(cur_pos, appdata); - return false; - } -} - -static int sdl_close_func(void *appdata) -{ - assert(appdata); - int result = SDL_RWclose((SDL_RWops*) appdata); - if (result != 0) - { - return TU_FILE_CLOSE_ERROR; - } - return 0; -} - - -tu_file::tu_file(SDL_RWops* sdl_stream, bool autoclose) -// Create a tu_file object that can be used to read/write stuff. Use -// an SDL_RWops* as the underlying implementation. -// -// If autoclose is true, then the sdl_stream has SDL_RWclose() -// called on it when the resulting file object is destructed. -{ - assert(sdl_stream); - - m_data = (void*) sdl_stream; - m_read = sdl_read_func; - m_write = sdl_write_func; - m_seek = sdl_seek_func; - m_seek_to_end = sdl_seek_to_end_func; - m_tell = sdl_tell_func; - m_get_eof = sdl_get_eof_func; - m_close = autoclose ? sdl_close_func : NULL; - m_error = TU_FILE_NO_ERROR; -} - - -// Local Variables: -// mode: C++ -// c-basic-offset: 8 -// tab-width: 8 -// indent-tabs-mode: t -// End: diff --git a/Code/BF2/External/base/tu_math.h b/Code/BF2/External/base/tu_math.h index 8dcfa69a8..a06240398 100644 --- a/Code/BF2/External/base/tu_math.h +++ b/Code/BF2/External/base/tu_math.h @@ -10,10 +10,16 @@ #include "base/tu_config.h" #include +#ifdef __cplusplus +#include +#endif #include // OSX doesn't have single precision math functions defined in math.h -#ifdef __MACH__ +// [BUILD-FIX SwiffPlayer: every supported macOS SDK declares the float functions, and these macros +// rename unrelated identifiers (renddx9abi::logf). The Windows build never took this branch, so +// it stays off on macOS too and the menu player uses the same float math everywhere.] +#if defined(__MACH__) && 0 #define sinf sin #define cosf cos #define tanf tan @@ -30,11 +36,14 @@ // isfinite() comes with C99; fake version here in case compiler lacks it. -#ifndef isfinite +// [BUILD-FIX SwiffPlayer: include C++ math declarations before the legacy fallback and +// use the toolchain's isfinite on MSVC 2013+ or C++11+, where it need not be a macro.] +#if !defined(isfinite) && !(defined(_MSC_VER) && _MSC_VER >= 1800) \ + && !(defined(__cplusplus) && __cplusplus >= 201103L) #define isfinite(x) (sizeof(x) == sizeof(float) ? isfinitef(x) : isfinited(x)) #define isfinitef(x) ((x) >= -FLT_MAX && (x) <= FLT_MAX) // NAN should fail this, yes? #define isfinited(x) ((x) >= -DBL_MAX && (x) <= DBL_MAX) -#endif // not isfinite +#endif // legacy toolchain without isfinite #endif // TU_MATH_H diff --git a/Code/BF2/External/base/tu_opengl_includes.h b/Code/BF2/External/base/tu_opengl_includes.h deleted file mode 100644 index 1729a750c..000000000 --- a/Code/BF2/External/base/tu_opengl_includes.h +++ /dev/null @@ -1,89 +0,0 @@ -// ogl.h -- by Thatcher Ulrich -// -- Willem Kokke - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - -// platform independent opengl includes - -#ifndef TU_OPENGL_INCLUDES_H -#define TU_OPENGL_INCLUDES_H - -#include "base/tu_config.h" - -// WIN32 includes. We don't want to have to include windows.h because -// it's such a pig, so #define a couple things that are required to -// make the gl.h stuff work. -#ifdef WIN32 -# ifndef _INC_WINDOWS - -# define WINAPI __stdcall -# define APIENTRY WINAPI -# define CALLBACK __stdcall -# define DECLSPEC_IMPORT __declspec(dllimport) - -# if !defined(_GDI32_) -# define WINGDIAPI DECLSPEC_IMPORT -# else -# define WINGDIAPI -# endif - -# else -# define WIN32_LEAN_AND_MEAN -# include -# endif - -# ifndef _WCHAR_T_DEFINED - typedef unsigned short wchar_t; -# define _WCHAR_T_DEFINED -# endif // _WCHAR_T_DEFINED - -# define PROC_NAME_PREFIX "wgl" - -# include -# include -#endif // WIN32 - -#ifdef __MACH__ -# include -# include -# define APIENTRY -# define PROC_NAME_PREFIX -#endif // __MACH__ - -#if !defined(WIN32) && !defined(__MACH__) -# include -# include -#ifndef APIENTRY -# define APIENTRY -#endif -# define PROC_NAME_PREFIX "glX" -#endif // no WIN32 or OSX - -// GL extension constants... -// WK: is there no glext.h equivalent for this? - -# define GL_VERTEX_ARRAY_RANGE_NV 0x851D -# define GL_VERTEX_ARRAY_RANGE_LENGTH_NV 0x851E -# define GL_VERTEX_ARRAY_RANGE_VALID_NV 0x851F -# define GL_MAX_VERTEX_ARRAY_RANGE_ELEMENT_NV 0x8520 -# define GL_VERTEX_ARRAY_RANGE_POINTER_NV 0x8521 - -# define GL_VERTEX_ARRAY_RANGE_WITHOUT_FLUSH_NV 0x8533 - -# define GL_TEXTURE0_ARB 0x84C0 -# define GL_TEXTURE1_ARB 0x84C1 -# define GL_MAX_TEXTURE_UNITS_ARB 0x84E2 - -# define GL_CLAMP_TO_EDGE 0x812F - -# define GL_ALL_COMPLETED_NV 0x84F2 - -#endif // TU_OPENGL_INCLUDES_H - -// Local Variables: -// mode: C++ -// c-basic-offset: 8 -// tab-width: 8 -// indent-tabs-mode: t -// End: diff --git a/Code/BF2/External/base/tu_types.h b/Code/BF2/External/base/tu_types.h index d6d7ffaf5..53a562f71 100644 --- a/Code/BF2/External/base/tu_types.h +++ b/Code/BF2/External/base/tu_types.h @@ -15,7 +15,9 @@ #include -#if defined(__i386__) || defined(_WIN32) +// [BUILD-FIX SwiffPlayer: the 64-bit macOS client (docs/macos-port.md) adds x86-64 and AArch64, +// both little-endian with 32-bit int and 64-bit long long. Without them base falls back to SDL.] +#if defined(__i386__) || defined(_WIN32) || defined(__x86_64__) || defined(__aarch64__) // On known little-endian platforms, define this stuff. #define _TU_LITTLE_ENDIAN_ 1 diff --git a/Code/BF2/External/base/utf8.cpp b/Code/BF2/External/base/utf8.cpp index fcb29c574..013f63c71 100644 --- a/Code/BF2/External/base/utf8.cpp +++ b/Code/BF2/External/base/utf8.cpp @@ -11,6 +11,7 @@ #include "base/utf8.h" +// Retail SwiffPlayer.dll 0x1006E6A0. Uint32 utf8::decode_next_unicode_character(const char** utf8_buffer) { Uint32 uc; @@ -111,6 +112,7 @@ Uint32 utf8::decode_next_unicode_character(const char** utf8_buffer) } +// Retail SwiffPlayer.dll 0x1006E980. void utf8::encode_unicode_character(char* buffer, int* index, Uint32 ucs_character) { if (ucs_character <= 0x7F) diff --git a/Code/BF2/External/base/utility.cpp b/Code/BF2/External/base/utility.cpp index 262805c0f..51235b658 100644 --- a/Code/BF2/External/base/utility.cpp +++ b/Code/BF2/External/base/utility.cpp @@ -14,7 +14,11 @@ int tu_testbed_assert_break(const char* filename, int linenum, const char* expression) { // @@ TODO output print error message +#if defined(_M_IX86) __asm { int 3 } +#else + __debugbreak(); // [CHOSEN, not recovered] x64 (https://github.com/B2BF/OpenBF2/issues/7): no inline asm +#endif return 0; } diff --git a/Code/BF2/External/base/utility.h b/Code/BF2/External/base/utility.h index 3a06b30ec..21029d2a2 100644 --- a/Code/BF2/External/base/utility.h +++ b/Code/BF2/External/base/utility.h @@ -24,8 +24,17 @@ // On windows, replace ANSI assert with our own, for a less annoying // debugging experience. //int tu_testbed_assert_break(const char* filename, int linenum, const char* expression); +#if !defined(_M_IX86) +#include // __debugbreak, the x64 arm below +#endif #undef assert +#if defined(_M_IX86) #define assert(x) if (!(x)) { __asm { int 3 } } // tu_testbed_assert_break(__FILE__, __LINE__, #x)) +#else +// [CHOSEN, not recovered] x64 (https://github.com/B2BF/OpenBF2/issues/7): no inline asm on x64; +// the same breakpoint through the intrinsic. +#define assert(x) if (!(x)) { __debugbreak(); } +#endif #endif // not NDEBUG #endif // _WIN32 @@ -74,11 +83,21 @@ void operator delete[](void* ptr); // some misc handy math functions // +// [BUILD-FIX SwiffPlayer: fmax, fmin and log2(float) live in namespace tu_util and are called +// qualified. libc++'s brings std::fmax/fmin/log2(float) into the global namespace, where +// these global definitions conflict. The C library versions answer differently for NaN and +// signed-zero inputs (fmax(NaN, 1) is 1 there, NaN or 1 here depending on order), so gameswf keeps +// its own comparisons on every toolchain.] +namespace tu_util { +// Retail SwiffPlayer.dll 0x1006EAC0 / 0x1006EAE0: preserve unordered/equal operand choice. +inline float fmax(float a, float b) { if (a < b) return b; else return a; } +inline float fmin(float a, float b) { if (a < b) return a; else return b; } +} + inline int iabs(int i) { if (i < 0) return -i; else return i; } +// Retail SwiffPlayer.dll 0x1006DC90 / 0x1006DCA0: signed comparison. inline int imax(int a, int b) { if (a < b) return b; else return a; } -inline float fmax(float a, float b) { if (a < b) return b; else return a; } inline int imin(int a, int b) { if (a < b) return a; else return b; } -inline float fmin(float a, float b) { if (a < b) return a; else return b; } inline int iclamp(int i, int min, int max) { @@ -86,17 +105,24 @@ inline int iclamp(int i, int min, int max) { return imax(min, imin(i, max)); } +// Retail SwiffPlayer.dll 0x1006EB00. inline float fclamp(float f, float xmin, float xmax) { assert( xmin <= xmax ); - return fmax(xmin, fmin(f, xmax)); + return tu_util::fmax(xmin, tu_util::fmin(f, xmax)); } inline float flerp(float a, float b, float f) { return (b - a) * f + a; } const float LN_2 = 0.693147180559945f; -inline float log2(float f) { return logf(f) / LN_2; } +namespace tu_util { +inline float log2(float f) { return logf(f) / LN_2; } // [BUILD-FIX SwiffPlayer: see fmax above.] +} inline int fchop( float f ) { return (int) f; } // replace w/ inline asm if desired +// [UNRESOLVED] Retail 0x1009D7D0 adds in x87 then truncates to a signed dword. +// [RETIRE-WHEN: swf-s3-base-rounding] Establish precision-control and integer- +// indefinite behavior, and validate half-integers, range edges, infinities and NaN +// before replacing this retained upstream expression. inline int frnd(float f) { return fchop(f + 0.5f); } // replace with inline asm if desired @@ -129,6 +155,7 @@ inline size_t bernstein_hash(const void* data_in, int size, unsigned int seed = } +// Retail SwiffPlayer.dll 0x1006EB30 (S1's bernstein_hash name was incorrect). inline size_t sdbm_hash(const void* data_in, int size, unsigned int seed = 5381) // Alternative: "sdbm" hash function, suggested at same web page // above, http::/www.cs.yorku.ca/~oz/hash.html @@ -147,6 +174,7 @@ inline size_t sdbm_hash(const void* data_in, int size, unsigned int seed = 5381) } +// Retail SwiffPlayer.dll 0x10008D30, called by the base string-key instances. inline size_t bernstein_hash_case_insensitive(const void* data_in, int size, unsigned int seed = 5381) // Computes a hash of the given data buffer; does tolower() on each // byte. Hash function suggested by diff --git a/Code/BF2/External/base/zlib_adapter.cpp b/Code/BF2/External/base/zlib_adapter.cpp deleted file mode 100644 index 124ad53c0..000000000 --- a/Code/BF2/External/base/zlib_adapter.cpp +++ /dev/null @@ -1,326 +0,0 @@ -// zlib_adapter.cpp -- Thatcher Ulrich 2003 - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - -// Code to wrap zlib compression/decompression around a tu_file -// stream. - - -#include "base/zlib_adapter.h" -#include "base/tu_file.h" -#include "base/utility.h" - - -#if !TU_CONFIG_LINK_TO_ZLIB - - -// Stubs, in case client doesn't want to link to zlib. -namespace zlib_adapter -{ - tu_file* make_inflater(tu_file* in) { return NULL; } - tu_file* make_deflater(tu_file* out) { return NULL; } -} - - -#else // TU_CONFIG_LINK_TO_ZLIB - - -#include - - -namespace zlib_adapter -{ - const int ZBUF_SIZE = 4096; - - struct inflater_impl - { - tu_file* m_in; - z_stream m_zstream; - int m_initial_stream_pos; // position of the input stream where we started inflating. - int m_logical_stream_pos; // current stream position of uncompressed data. - bool m_at_eof; - - unsigned char m_rawdata[ZBUF_SIZE]; - - int m_error; - - - inflater_impl(tu_file* in) - // Constructor. - : - m_in(in), - m_initial_stream_pos(in->get_position()), - m_logical_stream_pos(0), - m_at_eof(false), - m_error(0) - { - assert(m_in); - - m_zstream.zalloc = (alloc_func)0; - m_zstream.zfree = (free_func)0; - m_zstream.opaque = (voidpf)0; - - m_zstream.next_in = 0; - m_zstream.avail_in = 0; - - m_zstream.next_out = 0; - m_zstream.avail_out = 0; - - int err = inflateInit(&m_zstream); - if (err != Z_OK) { - //log_error("error: inflater_impl::ctor() inflateInit() returned %d\n", err); - m_error = 1; - return; - } - - // Ready to go! - } - - - void reset() - // Discard current results and rewind to the beginning. - // Necessary in order to seek backwards. - { - m_error = 0; - m_at_eof = 0; - int err = inflateReset(&m_zstream); - if (err != Z_OK) { - m_error = 1; - return; - } - - m_zstream.next_in = 0; - m_zstream.avail_in = 0; - - m_zstream.next_out = 0; - m_zstream.avail_out = 0; - - // Rewind the underlying stream. - m_in->set_position(m_initial_stream_pos); - - m_logical_stream_pos = 0; - } - - - int inflate_from_stream(void* dst, int bytes) - { - if (m_error) - { - return 0; - } - - m_zstream.next_out = (unsigned char*) dst; - m_zstream.avail_out = bytes; - - for (;;) - { - if (m_zstream.avail_in == 0) - { - // Get more raw data. - int new_bytes = m_in->read_bytes(m_rawdata, ZBUF_SIZE); - if (new_bytes == 0) - { - // The cupboard is bare! We have nothing to feed to inflate(). - break; - } - else - { - m_zstream.next_in = m_rawdata; - m_zstream.avail_in = new_bytes; - } - } - - int err = inflate(&m_zstream, Z_SYNC_FLUSH); - if (err == Z_STREAM_END) - { - m_at_eof = true; - break; - } - if (err != Z_OK) - { - // something's wrong. - m_error = 1; - break; - } - - if (m_zstream.avail_out == 0) - { - break; - } - } - - int bytes_read = bytes - m_zstream.avail_out; - m_logical_stream_pos += bytes_read; - - return bytes_read; - } - - void rewind_unused_bytes() - // If we have unused bytes in our input buffer, rewind - // to before they started. - { - if (m_zstream.avail_in > 0) - { - int pos = m_in->get_position(); - int rewound_pos = pos - m_zstream.avail_in; - assert(pos >= 0); - assert(pos >= m_initial_stream_pos); - assert(rewound_pos >= 0); - assert(rewound_pos >= m_initial_stream_pos); - - m_in->set_position(rewound_pos); - } - } - }; - - - int inflate_read(void* dst, int bytes, void* appdata) - // Return number of bytes actually read. - { - inflater_impl* inf = (inflater_impl*) appdata; - if (inf->m_error) - { - return 0; - } - - return inf->inflate_from_stream(dst, bytes); - } - - - int inflate_write(const void* src, int bytes, void* appdata) - // Return number of bytes actually written. - { - // *In*flaters can't write!!! - assert(0); - return 0; - } - - - int inflate_seek(int pos, void* appdata) - // Try to go to pos. Return actual pos. - { - inflater_impl* inf = (inflater_impl*) appdata; - if (inf->m_error) - { - return inf->m_logical_stream_pos; - } - - // If we're seeking backwards, then restart from the beginning. - if (pos < inf->m_logical_stream_pos) - { - inf->reset(); - } - - unsigned char temp[ZBUF_SIZE]; - - // Now seek forwards, by just reading data in blocks. - while (inf->m_logical_stream_pos < pos) - { - int to_read = pos - inf->m_logical_stream_pos; - int to_read_this_time = imin(to_read, ZBUF_SIZE); - assert(to_read_this_time > 0); - - int bytes_read = inf->inflate_from_stream(temp, to_read_this_time); - assert(bytes_read <= to_read_this_time); - if (bytes_read == 0) - { - // Trouble; can't seek any further. - break; - } - } - - assert(inf->m_logical_stream_pos <= pos); - - return inf->m_logical_stream_pos; - } - - - int inflate_seek_to_end(void* appdata) - { - inflater_impl* inf = (inflater_impl*) appdata; - if (inf->m_error) - { - return inf->m_logical_stream_pos; - } - - // Keep reading until we can't read any more. - - unsigned char temp[ZBUF_SIZE]; - - // Seek forwards. - for (;;) - { - int bytes_read = inf->inflate_from_stream(temp, ZBUF_SIZE); - if (bytes_read == 0) - { - // We've seeked as far as we can. - break; - } - } - - return inf->m_logical_stream_pos; - } - - int inflate_tell(const void* appdata) - { - inflater_impl* inf = (inflater_impl*) appdata; - - return inf->m_logical_stream_pos; - } - - bool inflate_get_eof(void* appdata) - { - inflater_impl* inf = (inflater_impl*) appdata; - - return inf->m_at_eof; - } - - int inflate_close(void* appdata) - { - inflater_impl* inf = (inflater_impl*) appdata; - - inf->rewind_unused_bytes(); - int err = inflateEnd(&(inf->m_zstream)); - - delete inf; - - if (err != Z_OK) - { - return TU_FILE_CLOSE_ERROR; - } - - return 0; - } - - - tu_file* make_inflater(tu_file* in) - { - assert(in); - - inflater_impl* inflater = new inflater_impl(in); - return new tu_file( - inflater, - inflate_read, - inflate_write, - inflate_seek, - inflate_seek_to_end, - inflate_tell, - inflate_get_eof, - inflate_close); - } - - - // @@ TODO - // tu_file* make_deflater(tu_file* out) { ... } -} - -#endif // TU_CONFIG_LINK_TO_ZLIB - - -// Local Variables: -// mode: C++ -// c-basic-offset: 8 -// tab-width: 8 -// indent-tabs-mode: t -// End: diff --git a/Code/BF2/External/base/zlib_adapter.h b/Code/BF2/External/base/zlib_adapter.h deleted file mode 100644 index f95782f22..000000000 --- a/Code/BF2/External/base/zlib_adapter.h +++ /dev/null @@ -1,47 +0,0 @@ -// zlib_adapter.h -- Thatcher Ulrich 2003 - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - -// Code to wrap zlib compression/decompression around a tu_file -// stream. - - -#ifndef ZLIB_ADAPTER_H -#define ZLIB_ADAPTER_H - - -#include "base/tu_config.h" -class tu_file; - - -namespace zlib_adapter -{ - // NOTE: these functions will return NULL if - // TU_CONFIG_LINK_TO_ZLIB is set to 0. - - // Returns a read-only tu_file stream that inflates the remaining - // content of the given input stream, as you read data from the - // new stream. - // - // The caller owns the returned tu_file*. The caller also owns - // the input tu_file*; don't delete it until you've deleted the - // returned tu_file. - // @@ Here's a good case for ref-counting... - tu_file* make_inflater(tu_file* in); - - // Returns a write-only tu_file stream that deflates the remaining - // content of the given input stream. - tu_file* make_deflater(tu_file* out); -} - - -#endif // ZLIB_ADAPTER_H - - -// Local Variables: -// mode: C++ -// c-basic-offset: 8 -// tab-width: 8 -// indent-tabs-mode: t -// End: diff --git a/Code/BF2/External/expat/COPYING b/Code/BF2/External/expat/COPYING new file mode 100644 index 000000000..fc97b02d9 --- /dev/null +++ b/Code/BF2/External/expat/COPYING @@ -0,0 +1,21 @@ +Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd + and Clark Cooper + +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/Code/BF2/External/expat/README.md b/Code/BF2/External/expat/README.md new file mode 100644 index 000000000..efa520d5b --- /dev/null +++ b/Code/BF2/External/expat/README.md @@ -0,0 +1,76 @@ +# SwiffPlayer Expat substitute + +[CHOSEN, not recovered] Owner decision 2026-11-08: use official libexpat +1.95.0 as a documented substitute for DICE's modified Expat. Retail +`SwiffPlayer.dll` links a modified C++ parser whose exact source is no longer +available: James Clark's 1.x distribution site is gone and was not archived. +Retail differs from every published release inspected, including a 328-word +`namingBitmap` versus 320 and older xmlrole role numbering. The swf track identified it +against the published releases. +This dependency is not recovered DICE source or an exact retail match. + +The known behavior difference is XML name-character classification: retail's +extra bitmap page 40 (words 320–327), referenced by the name page-table entry +for U+30xx, and differing name/name-start page-table entries admit additional +code points. The identification report's full BMP comparison found 385 additional +name-start classifications and 402 additional name classifications in retail; +none were unique to the official 1.95.0 tables. The substitute retains upstream +classification. Older role numbering also differs internally; no claim of +complete parser equivalence or an exhaustive behavioral-difference list is made. + +## Source and license + +- Source: +- Tag: `R_1_95_0` (official release 1.95.0). +- Archive: +- Archive SHA-256: `0d0ea80686a51330e34f541dde726c7bb4914fe0cbbd167fb8f724d160400846`. +- License: MIT (Expat), copyright the original authors, Thai Open Source + Software Center Ltd and Clark Cooper. Preserve [COPYING](COPYING) and all + source notices. The old C++ files elsewhere in the archive are not vendored. + +Only `expat/COPYING` and the required `expat/lib/` sources/headers were copied. +All upstream files are unchanged. For each file below, `tar -xOf` from the +owner-supplied archive was piped through `shasum -a 256` and compared with the +read-only extracted tree before copying. The vendored copy was also checked. +No upstream test, documentation or build script was copied or executed. + +| File | Archive SHA-256 | Extracted and vendored SHA-256 | +| --- | --- | --- | +| COPYING | `0e5a15440a08015d814b5fee7c1aac9f6c56ee6fc8e8288cba1eef5abd259bfc` | `0e5a15440a08015d814b5fee7c1aac9f6c56ee6fc8e8288cba1eef5abd259bfc` | +| xmlparse.c | `a0aa5a78b63dd74372332e491a57d464070952a09c286d0b24f276b373abbda9` | `a0aa5a78b63dd74372332e491a57d464070952a09c286d0b24f276b373abbda9` | +| xmltok.c | `bc9b77523e30046e2985ea000baccbbb58735c56824c8ca5b7ffe9d3f34d7ab1` | `bc9b77523e30046e2985ea000baccbbb58735c56824c8ca5b7ffe9d3f34d7ab1` | +| xmltok_impl.c | `035e5fde53aacfd38b4dd499ab5bc0d64eb8574b305e24177a44d3358cde481d` | `035e5fde53aacfd38b4dd499ab5bc0d64eb8574b305e24177a44d3358cde481d` | +| xmltok_ns.c | `a02dac0b291801fe427f7642e63e55cf319e047b19539e246bea7d10293d948c` | `a02dac0b291801fe427f7642e63e55cf319e047b19539e246bea7d10293d948c` | +| xmlrole.c | `744268a80b6f328afddc6d09142d56f8e4ecad686e755b81e8f5b14cc97a221a` | `744268a80b6f328afddc6d09142d56f8e4ecad686e755b81e8f5b14cc97a221a` | +| expat.h | `69aaf81d7f0b1ad7cfb99c70392421f52a6c2610c46b71f39d57cf43e9d152a5` | `69aaf81d7f0b1ad7cfb99c70392421f52a6c2610c46b71f39d57cf43e9d152a5` | +| xmlrole.h | `552324a96e741a748e29be322b48329c21427d19d0961ee69229bab608ca193b` | `552324a96e741a748e29be322b48329c21427d19d0961ee69229bab608ca193b` | +| xmltok.h | `0d436cbd3a3f313aeb7ab4601af3ae917f560abd24f70728625207d4250fae04` | `0d436cbd3a3f313aeb7ab4601af3ae917f560abd24f70728625207d4250fae04` | +| xmltok_impl.h | `577149bf7372ad62e8ad3e36ba82686c90efac0b694a19270c7b728999af7a39` | `577149bf7372ad62e8ad3e36ba82686c90efac0b694a19270c7b728999af7a39` | +| ascii.h | `00455fbd18eff9b9d444da082f9710189042c2b6d3907f3f863300aff9d1e484` | `00455fbd18eff9b9d444da082f9710189042c2b6d3907f3f863300aff9d1e484` | +| asciitab.h | `bfcf3aeff5a7ab136b54e86bd54dfe79ef610ebc792ff13a1dc0f0575e5912d4` | `bfcf3aeff5a7ab136b54e86bd54dfe79ef610ebc792ff13a1dc0f0575e5912d4` | +| iasciitab.h | `d8d1746408ac696427578ffd3491fb1714dec19bc58a39aca5cc142ba3114f92` | `d8d1746408ac696427578ffd3491fb1714dec19bc58a39aca5cc142ba3114f92` | +| latin1tab.h | `e46ab81b6bd03431b5878b8cc2db1098aa9eeaa8068a52f63fb2ec29a286f05e` | `e46ab81b6bd03431b5878b8cc2db1098aa9eeaa8068a52f63fb2ec29a286f05e` | +| nametab.h | `63a71bfd650c5a883aa630a042ec1636307773988ae648305c90c0036aa0335b` | `63a71bfd650c5a883aa630a042ec1636307773988ae648305c90c0036aa0335b` | +| utf8tab.h | `1e941e1bd2c5a94c8e4c269f3ec419c6ccbfa5008a186e3451d8f372429406b6` | `1e941e1bd2c5a94c8e4c269f3ec419c6ccbfa5008a186e3451d8f372429406b6` | + +## OpenBF2 integration + +`config.h` is a separate OpenBF2 file, [CHOSEN, not recovered]. The build adds +this directory to the parser include path so upstream's `` resolves +it. It selects native byte order, standard memory functions and narrow UTF-8 +callbacks, with namespace processing and parameter-entity/DTD support disabled +as observed in retail. No upstream file is force-edited. The three C translation +units are `xmlparse.c`, `xmltok.c` and `xmlrole.c`; `xmltok_impl.c` and +`xmltok_ns.c` are included fragments and must not be compiled independently. + +CMake builds `bf2_expat_static` and links it to the macOS SwiffPlayer/client. +`Code/Build/swiffplayer.cmd` uses `/TC` and `lib.exe` for both MSVC x86/x64. +Every C compile selects `DEDICATED=0` and force-includes `Core/BuildConfig.h`. +The native C++ facade in `gameswf_xml.cpp` preserves the inspected create, +handler-storage and XML-load call sequence, adapting parser-owned state and +callbacks to the C API. It does not reproduce the retail parser layout or +30-slot virtual interface. All platforms use the recovered XML load behavior: +non-final input, status 0 only for parse result 1, parser release before onData, +and a String source argument even on parse failure. Existing S3 String/graph/VM +bridges remain chosen. The dependency does not enable the XML factories in the +action layer; publication and native teardown integration remain maintainer work. diff --git a/Code/BF2/External/expat/ascii.h b/Code/BF2/External/expat/ascii.h new file mode 100644 index 000000000..6376b1f31 --- /dev/null +++ b/Code/BF2/External/expat/ascii.h @@ -0,0 +1,86 @@ +/* +Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd +See the file COPYING for copying permission. +*/ + +#define ASCII_A 0x41 +#define ASCII_B 0x42 +#define ASCII_C 0x43 +#define ASCII_D 0x44 +#define ASCII_E 0x45 +#define ASCII_F 0x46 +#define ASCII_G 0x47 +#define ASCII_H 0x48 +#define ASCII_I 0x49 +#define ASCII_J 0x4A +#define ASCII_K 0x4B +#define ASCII_L 0x4C +#define ASCII_M 0x4D +#define ASCII_N 0x4E +#define ASCII_O 0x4F +#define ASCII_P 0x50 +#define ASCII_Q 0x51 +#define ASCII_R 0x52 +#define ASCII_S 0x53 +#define ASCII_T 0x54 +#define ASCII_U 0x55 +#define ASCII_V 0x56 +#define ASCII_W 0x57 +#define ASCII_X 0x58 +#define ASCII_Y 0x59 +#define ASCII_Z 0x5A + +#define ASCII_a 0x61 +#define ASCII_b 0x62 +#define ASCII_c 0x63 +#define ASCII_d 0x64 +#define ASCII_e 0x65 +#define ASCII_f 0x66 +#define ASCII_g 0x67 +#define ASCII_h 0x68 +#define ASCII_i 0x69 +#define ASCII_j 0x6A +#define ASCII_k 0x6B +#define ASCII_l 0x6C +#define ASCII_m 0x6D +#define ASCII_n 0x6E +#define ASCII_o 0x6F +#define ASCII_p 0x70 +#define ASCII_q 0x71 +#define ASCII_r 0x72 +#define ASCII_s 0x73 +#define ASCII_t 0x74 +#define ASCII_u 0x75 +#define ASCII_v 0x76 +#define ASCII_w 0x77 +#define ASCII_x 0x78 +#define ASCII_y 0x79 +#define ASCII_z 0x7A + +#define ASCII_0 0x30 +#define ASCII_1 0x31 +#define ASCII_2 0x32 +#define ASCII_3 0x33 +#define ASCII_4 0x34 +#define ASCII_5 0x35 +#define ASCII_6 0x36 +#define ASCII_7 0x37 +#define ASCII_8 0x38 +#define ASCII_9 0x39 + +#define ASCII_TAB 0x09 +#define ASCII_SPACE 0x20 +#define ASCII_EXCL 0x21 +#define ASCII_QUOT 0x22 +#define ASCII_AMP 0x26 +#define ASCII_APOS 0x27 +#define ASCII_MINUS 0x2D +#define ASCII_PERIOD 0x2E +#define ASCII_COLON 0x3A +#define ASCII_SEMI 0x3B +#define ASCII_LT 0x3C +#define ASCII_EQUALS 0x3D +#define ASCII_GT 0x3E +#define ASCII_LSQB 0x5B +#define ASCII_RSQB 0x5D +#define ASCII_UNDERSCORE 0x5F diff --git a/Code/BF2/External/expat/asciitab.h b/Code/BF2/External/expat/asciitab.h new file mode 100644 index 000000000..eb445cc52 --- /dev/null +++ b/Code/BF2/External/expat/asciitab.h @@ -0,0 +1,37 @@ +/* +Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd +See the file COPYING for copying permission. +*/ + +/* 0x00 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, +/* 0x04 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, +/* 0x08 */ BT_NONXML, BT_S, BT_LF, BT_NONXML, +/* 0x0C */ BT_NONXML, BT_CR, BT_NONXML, BT_NONXML, +/* 0x10 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, +/* 0x14 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, +/* 0x18 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, +/* 0x1C */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, +/* 0x20 */ BT_S, BT_EXCL, BT_QUOT, BT_NUM, +/* 0x24 */ BT_OTHER, BT_PERCNT, BT_AMP, BT_APOS, +/* 0x28 */ BT_LPAR, BT_RPAR, BT_AST, BT_PLUS, +/* 0x2C */ BT_COMMA, BT_MINUS, BT_NAME, BT_SOL, +/* 0x30 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT, +/* 0x34 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT, +/* 0x38 */ BT_DIGIT, BT_DIGIT, BT_COLON, BT_SEMI, +/* 0x3C */ BT_LT, BT_EQUALS, BT_GT, BT_QUEST, +/* 0x40 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX, +/* 0x44 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT, +/* 0x48 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0x4C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0x50 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0x54 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0x58 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_LSQB, +/* 0x5C */ BT_OTHER, BT_RSQB, BT_OTHER, BT_NMSTRT, +/* 0x60 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX, +/* 0x64 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT, +/* 0x68 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0x6C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0x70 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0x74 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0x78 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER, +/* 0x7C */ BT_VERBAR, BT_OTHER, BT_OTHER, BT_OTHER, diff --git a/Code/BF2/External/expat/config.h b/Code/BF2/External/expat/config.h new file mode 100644 index 000000000..212150291 --- /dev/null +++ b/Code/BF2/External/expat/config.h @@ -0,0 +1,22 @@ +/* [CHOSEN, not recovered] OpenBF2 configuration for the unchanged Expat 1.95.0 + C sources. Owner-approved substitute, not DICE's parser; see README.md. */ +#ifndef OPENBF2_EXPAT_CONFIG_H +#define OPENBF2_EXPAT_CONFIG_H + +#include +#include + +#define STDC_HEADERS 1 +#define HAVE_MEMMOVE 1 +#define VERSION "1.95.0" + +#if defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ +#define XML_BYTE_ORDER 21 +#else +#define XML_BYTE_ORDER 12 +#endif + +/* Retail observations: narrow UTF-8 callbacks, no XML_NS and no XML_DTD. + Leave XML_UNICODE, XML_NS, XML_DTD and XML_CONTEXT_BYTES undefined. */ + +#endif diff --git a/Code/BF2/External/expat/expat.h b/Code/BF2/External/expat/expat.h new file mode 100644 index 000000000..d913e5992 --- /dev/null +++ b/Code/BF2/External/expat/expat.h @@ -0,0 +1,710 @@ +/* +Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd +See the file COPYING for copying permission. +*/ + +#ifndef XmlParse_INCLUDED +#define XmlParse_INCLUDED 1 + +#include + +#ifndef XMLPARSEAPI +# ifdef __declspec +# define XMLPARSEAPI __declspec(dllimport) +# else +# define XMLPARSEAPI /* nothing */ +# endif +#endif /* not defined XMLPARSEAPI */ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void *XML_Parser; + +/* Information is UTF-8 encoded. */ +typedef char XML_Char; +typedef char XML_LChar; + +enum XML_Content_Type { + XML_CTYPE_EMPTY = 1, + XML_CTYPE_ANY, + XML_CTYPE_MIXED, + XML_CTYPE_NAME, + XML_CTYPE_CHOICE, + XML_CTYPE_SEQ +}; + +enum XML_Content_Quant { + XML_CQUANT_NONE, + XML_CQUANT_OPT, + XML_CQUANT_REP, + XML_CQUANT_PLUS +}; + +/* If type == XML_CTYPE_EMPTY or XML_CTYPE_ANY, then quant will be + XML_CQUANT_NONE, and the other fields will be zero or NULL. + If type == XML_CTYPE_MIXED, then quant will be NONE or REP and + numchildren will contain number of elements that may be mixed in + and children point to an array of XML_Content cells that will be + all of XML_CTYPE_NAME type with no quantification. + + If type == XML_CTYPE_NAME, then the name points to the name, and + the numchildren field will be zero and children will be NULL. The + quant fields indicates any quantifiers placed on the name. + + CHOICE and SEQ will have name NULL, the number of children in + numchildren and children will point, recursively, to an array + of XML_Content cells. + + The EMPTY, ANY, and MIXED types will only occur at top level. +*/ + +typedef struct XML_cp XML_Content; + +struct XML_cp { + enum XML_Content_Type type; + enum XML_Content_Quant quant; + const XML_Char * name; + unsigned int numchildren; + XML_Content * children; +}; + + +/* This is called for an element declaration. See above for + description of the model argument. It's the caller's responsibility + to free model when finished with it. +*/ + +typedef void (*XML_ElementDeclHandler) (void *userData, + const XML_Char *name, + XML_Content *model); + +void XMLPARSEAPI +XML_SetElementDeclHandler(XML_Parser parser, + XML_ElementDeclHandler eldecl); + +/* + The Attlist declaration handler is called for *each* attribute. So + a single Attlist declaration with multiple attributes declared will + generate multiple calls to this handler. The "default" parameter + may be NULL in the case of the "#IMPLIED" or "#REQUIRED" keyword. + The "isrequired" parameter will be true and the default value will + be NULL in the case of "#REQUIRED". If "isrequired" is true and + default is non-NULL, then this is a "#FIXED" default. + */ + +typedef void (*XML_AttlistDeclHandler) (void *userData, + const XML_Char *elname, + const XML_Char *attname, + const XML_Char *att_type, + const XML_Char *dflt, + int isrequired); + +void XMLPARSEAPI +XML_SetAttlistDeclHandler(XML_Parser parser, + XML_AttlistDeclHandler attdecl); + + + /* The XML declaration handler is called for *both* XML declarations and + text declarations. The way to distinguish is that the version parameter + will be null for text declarations. The encoding parameter may be null + for XML declarations. The standalone parameter will be -1, 0, or 1 + indicating respectively that there was no standalone parameter in + the declaration, that it was given as no, or that it was given as yes. + */ + +typedef void (*XML_XmlDeclHandler) (void *userData, + const XML_Char *version, + const XML_Char *encoding, + int standalone); + +void XMLPARSEAPI +XML_SetXmlDeclHandler(XML_Parser parser, + XML_XmlDeclHandler xmldecl); + + +typedef struct { + void *(*malloc_fcn)(size_t size); + void *(*realloc_fcn)(void *ptr, size_t size); + void (*free_fcn)(void *ptr); +} XML_Memory_Handling_Suite; + +/* Constructs a new parser; encoding is the encoding specified by the external +protocol or null if there is none specified. */ + +XML_Parser XMLPARSEAPI +XML_ParserCreate(const XML_Char *encoding); + +/* Constructs a new parser and namespace processor. Element type names +and attribute names that belong to a namespace will be expanded; +unprefixed attribute names are never expanded; unprefixed element type +names are expanded only if there is a default namespace. The expanded +name is the concatenation of the namespace URI, the namespace separator character, +and the local part of the name. If the namespace separator is '\0' then +the namespace URI and the local part will be concatenated without any +separator. When a namespace is not declared, the name and prefix will be +passed through without expansion. */ + +XML_Parser XMLPARSEAPI +XML_ParserCreateNS(const XML_Char *encoding, XML_Char namespaceSeparator); + + +/* Constructs a new parser using the memory management suit referred to + by memsuite. If memsuite is NULL, then use the standard library memory + suite. If namespaceSeparator is non-NULL it creates a parser with + namespace processing as described above. The character pointed at + will serve as the namespace separator. + + All further memory operations used for the created parser will come from + the given suite. +*/ + +XML_Parser XMLPARSEAPI +XML_ParserCreate_MM(const XML_Char *encoding, + const XML_Memory_Handling_Suite *memsuite, + const XML_Char *namespaceSeparator); + +/* atts is array of name/value pairs, terminated by 0; + names and values are 0 terminated. */ + +typedef void (*XML_StartElementHandler)(void *userData, + const XML_Char *name, + const XML_Char **atts); + +typedef void (*XML_EndElementHandler)(void *userData, + const XML_Char *name); + + +/* s is not 0 terminated. */ +typedef void (*XML_CharacterDataHandler)(void *userData, + const XML_Char *s, + int len); + +/* target and data are 0 terminated */ +typedef void (*XML_ProcessingInstructionHandler)(void *userData, + const XML_Char *target, + const XML_Char *data); + +/* data is 0 terminated */ +typedef void (*XML_CommentHandler)(void *userData, const XML_Char *data); + +typedef void (*XML_StartCdataSectionHandler)(void *userData); +typedef void (*XML_EndCdataSectionHandler)(void *userData); + +/* This is called for any characters in the XML document for +which there is no applicable handler. This includes both +characters that are part of markup which is of a kind that is +not reported (comments, markup declarations), or characters +that are part of a construct which could be reported but +for which no handler has been supplied. The characters are passed +exactly as they were in the XML document except that +they will be encoded in UTF-8. Line boundaries are not normalized. +Note that a byte order mark character is not passed to the default handler. +There are no guarantees about how characters are divided between calls +to the default handler: for example, a comment might be split between +multiple calls. */ + +typedef void (*XML_DefaultHandler)(void *userData, + const XML_Char *s, + int len); + +/* This is called for the start of the DOCTYPE declaration, before + any DTD or internal subset is parsed. */ + +typedef void (*XML_StartDoctypeDeclHandler)(void *userData, + const XML_Char *doctypeName, + const XML_Char *sysid, + const XML_Char *pubid, + int has_internal_subset + ); + +/* This is called for the start of the DOCTYPE declaration when the +closing > is encountered, but after processing any external subset. */ +typedef void (*XML_EndDoctypeDeclHandler)(void *userData); + +/* This is called for entity declarations. The is_parameter_entity + argument will be non-zero if the entity is a parameter entity, zero + otherwise. + + For internal entities (), value will + be non-null and systemId, publicID, and notationName will be null. + The value string is NOT null terminated; the length is provided in + the value_length argument. Since it is legal to have zero-length + values, do not use this argument to test for internal entities. + + For external entities, value will be null and systemId will be non-null. + The publicId argument will be null unless a public identifier was + provided. The notationName argument will have a non-null value only + for unparsed entity declarations. +*/ + +typedef void (*XML_EntityDeclHandler) (void *userData, + const XML_Char *entityName, + int is_parameter_entity, + const XML_Char *value, + int value_length, + const XML_Char *base, + const XML_Char *systemId, + const XML_Char *publicId, + const XML_Char *notationName); + +void XMLPARSEAPI +XML_SetEntityDeclHandler(XML_Parser parser, + XML_EntityDeclHandler handler); + +/* OBSOLETE -- OBSOLETE -- OBSOLETE + This handler has been superceded by the EntityDeclHandler above. + It is provided here for backward compatibility. +This is called for a declaration of an unparsed (NDATA) +entity. The base argument is whatever was set by XML_SetBase. +The entityName, systemId and notationName arguments will never be null. +The other arguments may be. */ + +typedef void (*XML_UnparsedEntityDeclHandler)(void *userData, + const XML_Char *entityName, + const XML_Char *base, + const XML_Char *systemId, + const XML_Char *publicId, + const XML_Char *notationName); + +/* This is called for a declaration of notation. +The base argument is whatever was set by XML_SetBase. +The notationName will never be null. The other arguments can be. */ + +typedef void (*XML_NotationDeclHandler)(void *userData, + const XML_Char *notationName, + const XML_Char *base, + const XML_Char *systemId, + const XML_Char *publicId); + +/* When namespace processing is enabled, these are called once for +each namespace declaration. The call to the start and end element +handlers occur between the calls to the start and end namespace +declaration handlers. For an xmlns attribute, prefix will be null. +For an xmlns="" attribute, uri will be null. */ + +typedef void (*XML_StartNamespaceDeclHandler)(void *userData, + const XML_Char *prefix, + const XML_Char *uri); + +typedef void (*XML_EndNamespaceDeclHandler)(void *userData, + const XML_Char *prefix); + +/* This is called if the document is not standalone (it has an +external subset or a reference to a parameter entity, but does not +have standalone="yes"). If this handler returns 0, then processing +will not continue, and the parser will return a +XML_ERROR_NOT_STANDALONE error. */ + +typedef int (*XML_NotStandaloneHandler)(void *userData); + +/* This is called for a reference to an external parsed general entity. +The referenced entity is not automatically parsed. +The application can parse it immediately or later using +XML_ExternalEntityParserCreate. +The parser argument is the parser parsing the entity containing the reference; +it can be passed as the parser argument to XML_ExternalEntityParserCreate. +The systemId argument is the system identifier as specified in the entity declaration; +it will not be null. +The base argument is the system identifier that should be used as the base for +resolving systemId if systemId was relative; this is set by XML_SetBase; +it may be null. +The publicId argument is the public identifier as specified in the entity declaration, +or null if none was specified; the whitespace in the public identifier +will have been normalized as required by the XML spec. +The context argument specifies the parsing context in the format +expected by the context argument to +XML_ExternalEntityParserCreate; context is valid only until the handler +returns, so if the referenced entity is to be parsed later, it must be copied. +The handler should return 0 if processing should not continue because of +a fatal error in the handling of the external entity. +In this case the calling parser will return an XML_ERROR_EXTERNAL_ENTITY_HANDLING +error. +Note that unlike other handlers the first argument is the parser, not userData. */ + +typedef int (*XML_ExternalEntityRefHandler)(XML_Parser parser, + const XML_Char *context, + const XML_Char *base, + const XML_Char *systemId, + const XML_Char *publicId); + +/* This structure is filled in by the XML_UnknownEncodingHandler +to provide information to the parser about encodings that are unknown +to the parser. +The map[b] member gives information about byte sequences +whose first byte is b. +If map[b] is c where c is >= 0, then b by itself encodes the Unicode scalar value c. +If map[b] is -1, then the byte sequence is malformed. +If map[b] is -n, where n >= 2, then b is the first byte of an n-byte +sequence that encodes a single Unicode scalar value. +The data member will be passed as the first argument to the convert function. +The convert function is used to convert multibyte sequences; +s will point to a n-byte sequence where map[(unsigned char)*s] == -n. +The convert function must return the Unicode scalar value +represented by this byte sequence or -1 if the byte sequence is malformed. +The convert function may be null if the encoding is a single-byte encoding, +that is if map[b] >= -1 for all bytes b. +When the parser is finished with the encoding, then if release is not null, +it will call release passing it the data member; +once release has been called, the convert function will not be called again. + +Expat places certain restrictions on the encodings that are supported +using this mechanism. + +1. Every ASCII character that can appear in a well-formed XML document, +other than the characters + + $@\^`{}~ + +must be represented by a single byte, and that byte must be the +same byte that represents that character in ASCII. + +2. No character may require more than 4 bytes to encode. + +3. All characters encoded must have Unicode scalar values <= 0xFFFF, +(ie characters that would be encoded by surrogates in UTF-16 +are not allowed). Note that this restriction doesn't apply to +the built-in support for UTF-8 and UTF-16. + +4. No Unicode character may be encoded by more than one distinct sequence +of bytes. */ + +typedef struct { + int map[256]; + void *data; + int (*convert)(void *data, const char *s); + void (*release)(void *data); +} XML_Encoding; + +/* This is called for an encoding that is unknown to the parser. +The encodingHandlerData argument is that which was passed as the +second argument to XML_SetUnknownEncodingHandler. +The name argument gives the name of the encoding as specified in +the encoding declaration. +If the callback can provide information about the encoding, +it must fill in the XML_Encoding structure, and return 1. +Otherwise it must return 0. +If info does not describe a suitable encoding, +then the parser will return an XML_UNKNOWN_ENCODING error. */ + +typedef int (*XML_UnknownEncodingHandler)(void *encodingHandlerData, + const XML_Char *name, + XML_Encoding *info); + +void XMLPARSEAPI +XML_SetElementHandler(XML_Parser parser, + XML_StartElementHandler start, + XML_EndElementHandler end); + +void XMLPARSEAPI +XML_SetStartElementHandler(XML_Parser, XML_StartElementHandler); + +void XMLPARSEAPI +XML_SetEndElementHandler(XML_Parser, XML_EndElementHandler); + +void XMLPARSEAPI +XML_SetCharacterDataHandler(XML_Parser parser, + XML_CharacterDataHandler handler); + +void XMLPARSEAPI +XML_SetProcessingInstructionHandler(XML_Parser parser, + XML_ProcessingInstructionHandler handler); +void XMLPARSEAPI +XML_SetCommentHandler(XML_Parser parser, + XML_CommentHandler handler); + +void XMLPARSEAPI +XML_SetCdataSectionHandler(XML_Parser parser, + XML_StartCdataSectionHandler start, + XML_EndCdataSectionHandler end); + +void XMLPARSEAPI +XML_SetStartCdataSectionHandler(XML_Parser parser, + XML_StartCdataSectionHandler start); + +void XMLPARSEAPI +XML_SetEndCdataSectionHandler(XML_Parser parser, + XML_EndCdataSectionHandler end); + +/* This sets the default handler and also inhibits expansion of internal entities. +The entity reference will be passed to the default handler. */ + +void XMLPARSEAPI +XML_SetDefaultHandler(XML_Parser parser, + XML_DefaultHandler handler); + +/* This sets the default handler but does not inhibit expansion of internal entities. +The entity reference will not be passed to the default handler. */ + +void XMLPARSEAPI +XML_SetDefaultHandlerExpand(XML_Parser parser, + XML_DefaultHandler handler); + +void XMLPARSEAPI +XML_SetDoctypeDeclHandler(XML_Parser parser, + XML_StartDoctypeDeclHandler start, + XML_EndDoctypeDeclHandler end); + +void XMLPARSEAPI +XML_SetStartDoctypeDeclHandler(XML_Parser parser, + XML_StartDoctypeDeclHandler start); + +void XMLPARSEAPI +XML_SetEndDoctypeDeclHandler(XML_Parser parser, + XML_EndDoctypeDeclHandler end); + +void XMLPARSEAPI +XML_SetUnparsedEntityDeclHandler(XML_Parser parser, + XML_UnparsedEntityDeclHandler handler); + +void XMLPARSEAPI +XML_SetNotationDeclHandler(XML_Parser parser, + XML_NotationDeclHandler handler); + +void XMLPARSEAPI +XML_SetNamespaceDeclHandler(XML_Parser parser, + XML_StartNamespaceDeclHandler start, + XML_EndNamespaceDeclHandler end); + +void XMLPARSEAPI +XML_SetStartNamespaceDeclHandler(XML_Parser parser, + XML_StartNamespaceDeclHandler start); + +void XMLPARSEAPI +XML_SetEndNamespaceDeclHandler(XML_Parser parser, + XML_EndNamespaceDeclHandler end); + +void XMLPARSEAPI +XML_SetNotStandaloneHandler(XML_Parser parser, + XML_NotStandaloneHandler handler); + +void XMLPARSEAPI +XML_SetExternalEntityRefHandler(XML_Parser parser, + XML_ExternalEntityRefHandler handler); + +/* If a non-null value for arg is specified here, then it will be passed +as the first argument to the external entity ref handler instead +of the parser object. */ +void XMLPARSEAPI +XML_SetExternalEntityRefHandlerArg(XML_Parser, void *arg); + +void XMLPARSEAPI +XML_SetUnknownEncodingHandler(XML_Parser parser, + XML_UnknownEncodingHandler handler, + void *encodingHandlerData); + +/* This can be called within a handler for a start element, end element, +processing instruction or character data. It causes the corresponding +markup to be passed to the default handler. */ +void XML_DefaultCurrent(XML_Parser parser); + +/* If do_nst is non-zero, and namespace processing is in effect, and + a name has a prefix (i.e. an explicit namespace qualifier) then + that name is returned as a triplet in a single + string separated by the separator character specified when the parser + was created: URI + sep + local_name + sep + prefix. + + If do_nst is zero, then namespace information is returned in the + default manner (URI + sep + local_name) whether or not the names + has a prefix. +*/ + +void XMLPARSEAPI +XML_SetReturnNSTriplet(XML_Parser parser, int do_nst); + +/* This value is passed as the userData argument to callbacks. */ +void XMLPARSEAPI +XML_SetUserData(XML_Parser parser, void *userData); + +/* Returns the last value set by XML_SetUserData or null. */ +#define XML_GetUserData(parser) (*(void **)(parser)) + +/* This is equivalent to supplying an encoding argument +to XML_ParserCreate. It must not be called after XML_Parse +or XML_ParseBuffer. */ + +int XMLPARSEAPI +XML_SetEncoding(XML_Parser parser, const XML_Char *encoding); + +/* If this function is called, then the parser will be passed +as the first argument to callbacks instead of userData. +The userData will still be accessible using XML_GetUserData. */ + +void XMLPARSEAPI +XML_UseParserAsHandlerArg(XML_Parser parser); + +/* Sets the base to be used for resolving relative URIs in system identifiers in +declarations. Resolving relative identifiers is left to the application: +this value will be passed through as the base argument to the +XML_ExternalEntityRefHandler, XML_NotationDeclHandler +and XML_UnparsedEntityDeclHandler. The base argument will be copied. +Returns zero if out of memory, non-zero otherwise. */ + +int XMLPARSEAPI +XML_SetBase(XML_Parser parser, const XML_Char *base); + +const XML_Char XMLPARSEAPI * +XML_GetBase(XML_Parser parser); + +/* Returns the number of the attribute/value pairs passed in last call +to the XML_StartElementHandler that were specified in the start-tag +rather than defaulted. Each attribute/value pair counts as 2; thus +this correspondds to an index into the atts array passed to the +XML_StartElementHandler. */ + +int XMLPARSEAPI +XML_GetSpecifiedAttributeCount(XML_Parser parser); + +/* Returns the index of the ID attribute passed in the last call to +XML_StartElementHandler, or -1 if there is no ID attribute. Each +attribute/value pair counts as 2; thus this correspondds to an index +into the atts array passed to the XML_StartElementHandler. */ + +int XMLPARSEAPI +XML_GetIdAttributeIndex(XML_Parser parser); + +/* Parses some input. Returns 0 if a fatal error is detected. +The last call to XML_Parse must have isFinal true; +len may be zero for this call (or any other). */ +int XMLPARSEAPI +XML_Parse(XML_Parser parser, const char *s, int len, int isFinal); + +void XMLPARSEAPI * +XML_GetBuffer(XML_Parser parser, int len); + +int XMLPARSEAPI +XML_ParseBuffer(XML_Parser parser, int len, int isFinal); + +/* Creates an XML_Parser object that can parse an external general entity; +context is a '\0'-terminated string specifying the parse context; +encoding is a '\0'-terminated string giving the name of the externally specified encoding, +or null if there is no externally specified encoding. +The context string consists of a sequence of tokens separated by formfeeds (\f); +a token consisting of a name specifies that the general entity of the name +is open; a token of the form prefix=uri specifies the namespace for a particular +prefix; a token of the form =uri specifies the default namespace. +This can be called at any point after the first call to an ExternalEntityRefHandler +so longer as the parser has not yet been freed. +The new parser is completely independent and may safely be used in a separate thread. +The handlers and userData are initialized from the parser argument. +Returns 0 if out of memory. Otherwise returns a new XML_Parser object. */ +XML_Parser XMLPARSEAPI +XML_ExternalEntityParserCreate(XML_Parser parser, + const XML_Char *context, + const XML_Char *encoding); + +enum XML_ParamEntityParsing { + XML_PARAM_ENTITY_PARSING_NEVER, + XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE, + XML_PARAM_ENTITY_PARSING_ALWAYS +}; + +/* Controls parsing of parameter entities (including the external DTD +subset). If parsing of parameter entities is enabled, then references +to external parameter entities (including the external DTD subset) +will be passed to the handler set with +XML_SetExternalEntityRefHandler. The context passed will be 0. +Unlike external general entities, external parameter entities can only +be parsed synchronously. If the external parameter entity is to be +parsed, it must be parsed during the call to the external entity ref +handler: the complete sequence of XML_ExternalEntityParserCreate, +XML_Parse/XML_ParseBuffer and XML_ParserFree calls must be made during +this call. After XML_ExternalEntityParserCreate has been called to +create the parser for the external parameter entity (context must be 0 +for this call), it is illegal to make any calls on the old parser +until XML_ParserFree has been called on the newly created parser. If +the library has been compiled without support for parameter entity +parsing (ie without XML_DTD being defined), then +XML_SetParamEntityParsing will return 0 if parsing of parameter +entities is requested; otherwise it will return non-zero. */ + +int XMLPARSEAPI +XML_SetParamEntityParsing(XML_Parser parser, + enum XML_ParamEntityParsing parsing); + +enum XML_Error { + XML_ERROR_NONE, + XML_ERROR_NO_MEMORY, + XML_ERROR_SYNTAX, + XML_ERROR_NO_ELEMENTS, + XML_ERROR_INVALID_TOKEN, + XML_ERROR_UNCLOSED_TOKEN, + XML_ERROR_PARTIAL_CHAR, + XML_ERROR_TAG_MISMATCH, + XML_ERROR_DUPLICATE_ATTRIBUTE, + XML_ERROR_JUNK_AFTER_DOC_ELEMENT, + XML_ERROR_PARAM_ENTITY_REF, + XML_ERROR_UNDEFINED_ENTITY, + XML_ERROR_RECURSIVE_ENTITY_REF, + XML_ERROR_ASYNC_ENTITY, + XML_ERROR_BAD_CHAR_REF, + XML_ERROR_BINARY_ENTITY_REF, + XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF, + XML_ERROR_MISPLACED_XML_PI, + XML_ERROR_UNKNOWN_ENCODING, + XML_ERROR_INCORRECT_ENCODING, + XML_ERROR_UNCLOSED_CDATA_SECTION, + XML_ERROR_EXTERNAL_ENTITY_HANDLING, + XML_ERROR_NOT_STANDALONE +}; + +/* If XML_Parse or XML_ParseBuffer have returned 0, then XML_GetErrorCode +returns information about the error. */ + +enum XML_Error XML_GetErrorCode(XML_Parser parser); + +/* These functions return information about the current parse location. +They may be called when XML_Parse or XML_ParseBuffer return 0; +in this case the location is the location of the character at which +the error was detected. +They may also be called from any other callback called to report +some parse event; in this the location is the location of the first +of the sequence of characters that generated the event. */ + +int XML_GetCurrentLineNumber(XML_Parser parser); +int XML_GetCurrentColumnNumber(XML_Parser parser); +long XML_GetCurrentByteIndex(XML_Parser parser); + +/* Return the number of bytes in the current event. +Returns 0 if the event is in an internal entity. */ + +int XMLPARSEAPI +XML_GetCurrentByteCount(XML_Parser parser); + +/* If XML_CONTEXT_BYTES is defined, returns the input buffer, sets + the integer pointed to by offset to the offset within this buffer + of the current parse position, and sets the integer pointed to by size + to the size of this buffer (the number of input bytes). Otherwise + returns a null pointer. Also returns a null pointer if a parse isn't active. + + NOTE: The character pointer returned should not be used outside + the handler that makes the call. */ + +const char XMLPARSEAPI * +XML_GetInputContext(XML_Parser parser, + int *offset, + int *size); + +/* For backwards compatibility with previous versions. */ +#define XML_GetErrorLineNumber XML_GetCurrentLineNumber +#define XML_GetErrorColumnNumber XML_GetCurrentColumnNumber +#define XML_GetErrorByteIndex XML_GetCurrentByteIndex + +/* Frees memory used by the parser. */ +void XMLPARSEAPI +XML_ParserFree(XML_Parser parser); + +/* Returns a string describing the error. */ +const XML_LChar XMLPARSEAPI * +XML_ErrorString(int code); + +/* Return a string containing the version number of this expat */ +const XML_LChar XMLPARSEAPI * +XML_ExpatVersion(); + +#ifdef __cplusplus +} +#endif + +#endif /* not XmlParse_INCLUDED */ diff --git a/Code/BF2/External/expat/iasciitab.h b/Code/BF2/External/expat/iasciitab.h new file mode 100644 index 000000000..55dbc398b --- /dev/null +++ b/Code/BF2/External/expat/iasciitab.h @@ -0,0 +1,38 @@ +/* +Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd +See the file COPYING for copying permission. +*/ + +/* Like asciitab.h, except that 0xD has code BT_S rather than BT_CR */ +/* 0x00 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, +/* 0x04 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, +/* 0x08 */ BT_NONXML, BT_S, BT_LF, BT_NONXML, +/* 0x0C */ BT_NONXML, BT_S, BT_NONXML, BT_NONXML, +/* 0x10 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, +/* 0x14 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, +/* 0x18 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, +/* 0x1C */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, +/* 0x20 */ BT_S, BT_EXCL, BT_QUOT, BT_NUM, +/* 0x24 */ BT_OTHER, BT_PERCNT, BT_AMP, BT_APOS, +/* 0x28 */ BT_LPAR, BT_RPAR, BT_AST, BT_PLUS, +/* 0x2C */ BT_COMMA, BT_MINUS, BT_NAME, BT_SOL, +/* 0x30 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT, +/* 0x34 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT, +/* 0x38 */ BT_DIGIT, BT_DIGIT, BT_COLON, BT_SEMI, +/* 0x3C */ BT_LT, BT_EQUALS, BT_GT, BT_QUEST, +/* 0x40 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX, +/* 0x44 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT, +/* 0x48 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0x4C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0x50 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0x54 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0x58 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_LSQB, +/* 0x5C */ BT_OTHER, BT_RSQB, BT_OTHER, BT_NMSTRT, +/* 0x60 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX, +/* 0x64 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT, +/* 0x68 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0x6C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0x70 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0x74 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0x78 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER, +/* 0x7C */ BT_VERBAR, BT_OTHER, BT_OTHER, BT_OTHER, diff --git a/Code/BF2/External/expat/latin1tab.h b/Code/BF2/External/expat/latin1tab.h new file mode 100644 index 000000000..178b1d186 --- /dev/null +++ b/Code/BF2/External/expat/latin1tab.h @@ -0,0 +1,37 @@ +/* +Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd +See the file COPYING for copying permission. +*/ + +/* 0x80 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, +/* 0x84 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, +/* 0x88 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, +/* 0x8C */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, +/* 0x90 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, +/* 0x94 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, +/* 0x98 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, +/* 0x9C */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, +/* 0xA0 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, +/* 0xA4 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, +/* 0xA8 */ BT_OTHER, BT_OTHER, BT_NMSTRT, BT_OTHER, +/* 0xAC */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, +/* 0xB0 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, +/* 0xB4 */ BT_OTHER, BT_NMSTRT, BT_OTHER, BT_NAME, +/* 0xB8 */ BT_OTHER, BT_OTHER, BT_NMSTRT, BT_OTHER, +/* 0xBC */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, +/* 0xC0 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0xC4 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0xC8 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0xCC */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0xD0 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0xD4 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER, +/* 0xD8 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0xDC */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0xE0 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0xE4 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0xE8 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0xEC */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0xF0 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0xF4 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER, +/* 0xF8 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0xFC */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, diff --git a/Code/BF2/External/expat/nametab.h b/Code/BF2/External/expat/nametab.h new file mode 100644 index 000000000..b05e62c77 --- /dev/null +++ b/Code/BF2/External/expat/nametab.h @@ -0,0 +1,150 @@ +static const unsigned namingBitmap[] = { +0x00000000, 0x00000000, 0x00000000, 0x00000000, +0x00000000, 0x00000000, 0x00000000, 0x00000000, +0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, +0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, +0x00000000, 0x04000000, 0x87FFFFFE, 0x07FFFFFE, +0x00000000, 0x00000000, 0xFF7FFFFF, 0xFF7FFFFF, +0xFFFFFFFF, 0x7FF3FFFF, 0xFFFFFDFE, 0x7FFFFFFF, +0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFE00F, 0xFC31FFFF, +0x00FFFFFF, 0x00000000, 0xFFFF0000, 0xFFFFFFFF, +0xFFFFFFFF, 0xF80001FF, 0x00000003, 0x00000000, +0x00000000, 0x00000000, 0x00000000, 0x00000000, +0xFFFFD740, 0xFFFFFFFB, 0x547F7FFF, 0x000FFFFD, +0xFFFFDFFE, 0xFFFFFFFF, 0xDFFEFFFF, 0xFFFFFFFF, +0xFFFF0003, 0xFFFFFFFF, 0xFFFF199F, 0x033FCFFF, +0x00000000, 0xFFFE0000, 0x027FFFFF, 0xFFFFFFFE, +0x0000007F, 0x00000000, 0xFFFF0000, 0x000707FF, +0x00000000, 0x07FFFFFE, 0x000007FE, 0xFFFE0000, +0xFFFFFFFF, 0x7CFFFFFF, 0x002F7FFF, 0x00000060, +0xFFFFFFE0, 0x23FFFFFF, 0xFF000000, 0x00000003, +0xFFF99FE0, 0x03C5FDFF, 0xB0000000, 0x00030003, +0xFFF987E0, 0x036DFDFF, 0x5E000000, 0x001C0000, +0xFFFBAFE0, 0x23EDFDFF, 0x00000000, 0x00000001, +0xFFF99FE0, 0x23CDFDFF, 0xB0000000, 0x00000003, +0xD63DC7E0, 0x03BFC718, 0x00000000, 0x00000000, +0xFFFDDFE0, 0x03EFFDFF, 0x00000000, 0x00000003, +0xFFFDDFE0, 0x03EFFDFF, 0x40000000, 0x00000003, +0xFFFDDFE0, 0x03FFFDFF, 0x00000000, 0x00000003, +0x00000000, 0x00000000, 0x00000000, 0x00000000, +0xFFFFFFFE, 0x000D7FFF, 0x0000003F, 0x00000000, +0xFEF02596, 0x200D6CAE, 0x0000001F, 0x00000000, +0x00000000, 0x00000000, 0xFFFFFEFF, 0x000003FF, +0x00000000, 0x00000000, 0x00000000, 0x00000000, +0x00000000, 0x00000000, 0x00000000, 0x00000000, +0x00000000, 0xFFFFFFFF, 0xFFFF003F, 0x007FFFFF, +0x0007DAED, 0x50000000, 0x82315001, 0x002C62AB, +0x40000000, 0xF580C900, 0x00000007, 0x02010800, +0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, +0x0FFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x03FFFFFF, +0x3F3FFFFF, 0xFFFFFFFF, 0xAAFF3F3F, 0x3FFFFFFF, +0xFFFFFFFF, 0x5FDFFFFF, 0x0FCF1FDC, 0x1FDC1FFF, +0x00000000, 0x00004C40, 0x00000000, 0x00000000, +0x00000007, 0x00000000, 0x00000000, 0x00000000, +0x00000080, 0x000003FE, 0xFFFFFFFE, 0xFFFFFFFF, +0x001FFFFF, 0xFFFFFFFE, 0xFFFFFFFF, 0x07FFFFFF, +0xFFFFFFE0, 0x00001FFF, 0x00000000, 0x00000000, +0x00000000, 0x00000000, 0x00000000, 0x00000000, +0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, +0xFFFFFFFF, 0x0000003F, 0x00000000, 0x00000000, +0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, +0xFFFFFFFF, 0x0000000F, 0x00000000, 0x00000000, +0x00000000, 0x07FF6000, 0x87FFFFFE, 0x07FFFFFE, +0x00000000, 0x00800000, 0xFF7FFFFF, 0xFF7FFFFF, +0x00FFFFFF, 0x00000000, 0xFFFF0000, 0xFFFFFFFF, +0xFFFFFFFF, 0xF80001FF, 0x00030003, 0x00000000, +0xFFFFFFFF, 0xFFFFFFFF, 0x0000003F, 0x00000003, +0xFFFFD7C0, 0xFFFFFFFB, 0x547F7FFF, 0x000FFFFD, +0xFFFFDFFE, 0xFFFFFFFF, 0xDFFEFFFF, 0xFFFFFFFF, +0xFFFF007B, 0xFFFFFFFF, 0xFFFF199F, 0x033FCFFF, +0x00000000, 0xFFFE0000, 0x027FFFFF, 0xFFFFFFFE, +0xFFFE007F, 0xBBFFFFFB, 0xFFFF0016, 0x000707FF, +0x00000000, 0x07FFFFFE, 0x0007FFFF, 0xFFFF03FF, +0xFFFFFFFF, 0x7CFFFFFF, 0xFFEF7FFF, 0x03FF3DFF, +0xFFFFFFEE, 0xF3FFFFFF, 0xFF1E3FFF, 0x0000FFCF, +0xFFF99FEE, 0xD3C5FDFF, 0xB080399F, 0x0003FFCF, +0xFFF987E4, 0xD36DFDFF, 0x5E003987, 0x001FFFC0, +0xFFFBAFEE, 0xF3EDFDFF, 0x00003BBF, 0x0000FFC1, +0xFFF99FEE, 0xF3CDFDFF, 0xB0C0398F, 0x0000FFC3, +0xD63DC7EC, 0xC3BFC718, 0x00803DC7, 0x0000FF80, +0xFFFDDFEE, 0xC3EFFDFF, 0x00603DDF, 0x0000FFC3, +0xFFFDDFEC, 0xC3EFFDFF, 0x40603DDF, 0x0000FFC3, +0xFFFDDFEC, 0xC3FFFDFF, 0x00803DCF, 0x0000FFC3, +0x00000000, 0x00000000, 0x00000000, 0x00000000, +0xFFFFFFFE, 0x07FF7FFF, 0x03FF7FFF, 0x00000000, +0xFEF02596, 0x3BFF6CAE, 0x03FF3F5F, 0x00000000, +0x03000000, 0xC2A003FF, 0xFFFFFEFF, 0xFFFE03FF, +0xFEBF0FDF, 0x02FE3FFF, 0x00000000, 0x00000000, +0x00000000, 0x00000000, 0x00000000, 0x00000000, +0x00000000, 0x00000000, 0x1FFF0000, 0x00000002, +0x000000A0, 0x003EFFFE, 0xFFFFFFFE, 0xFFFFFFFF, +0x661FFFFF, 0xFFFFFFFE, 0xFFFFFFFF, 0x77FFFFFF, +}; +static const unsigned char nmstrtPages[] = { +0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x00, +0x00, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, +0x10, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x13, +0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x15, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x17, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x18, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +}; +static const unsigned char namePages[] = { +0x19, 0x03, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x00, +0x00, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, +0x10, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x13, +0x26, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x27, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x17, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x18, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +}; diff --git a/Code/BF2/External/expat/utf8tab.h b/Code/BF2/External/expat/utf8tab.h new file mode 100644 index 000000000..9e3b6b83e --- /dev/null +++ b/Code/BF2/External/expat/utf8tab.h @@ -0,0 +1,38 @@ +/* +Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd +See the file COPYING for copying permission. +*/ + + +/* 0x80 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, +/* 0x84 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, +/* 0x88 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, +/* 0x8C */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, +/* 0x90 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, +/* 0x94 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, +/* 0x98 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, +/* 0x9C */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, +/* 0xA0 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, +/* 0xA4 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, +/* 0xA8 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, +/* 0xAC */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, +/* 0xB0 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, +/* 0xB4 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, +/* 0xB8 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, +/* 0xBC */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, +/* 0xC0 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2, +/* 0xC4 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2, +/* 0xC8 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2, +/* 0xCC */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2, +/* 0xD0 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2, +/* 0xD4 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2, +/* 0xD8 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2, +/* 0xDC */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2, +/* 0xE0 */ BT_LEAD3, BT_LEAD3, BT_LEAD3, BT_LEAD3, +/* 0xE4 */ BT_LEAD3, BT_LEAD3, BT_LEAD3, BT_LEAD3, +/* 0xE8 */ BT_LEAD3, BT_LEAD3, BT_LEAD3, BT_LEAD3, +/* 0xEC */ BT_LEAD3, BT_LEAD3, BT_LEAD3, BT_LEAD3, +/* 0xF0 */ BT_LEAD4, BT_LEAD4, BT_LEAD4, BT_LEAD4, +/* 0xF4 */ BT_LEAD4, BT_NONXML, BT_NONXML, BT_NONXML, +/* 0xF8 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, +/* 0xFC */ BT_NONXML, BT_NONXML, BT_MALFORM, BT_MALFORM, diff --git a/Code/BF2/External/expat/xmlparse.c b/Code/BF2/External/expat/xmlparse.c new file mode 100644 index 000000000..1c7c8f325 --- /dev/null +++ b/Code/BF2/External/expat/xmlparse.c @@ -0,0 +1,4603 @@ +/* +Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd +See the file COPYING for copying permission. +*/ + +static char RCSId[] + = "$Header$"; + +#include + +#ifdef __declspec +# define XMLPARSEAPI __declspec(dllexport) +#endif + +#include "expat.h" + +#ifdef __declspec +# undef XMLPARSEAPI +#endif + +#include + +#ifdef XML_UNICODE +#define XML_ENCODE_MAX XML_UTF16_ENCODE_MAX +#define XmlConvert XmlUtf16Convert +#define XmlGetInternalEncoding XmlGetUtf16InternalEncoding +#define XmlGetInternalEncodingNS XmlGetUtf16InternalEncodingNS +#define XmlEncode XmlUtf16Encode +#define MUST_CONVERT(enc, s) (!(enc)->isUtf16 || (((unsigned long)s) & 1)) +typedef unsigned short ICHAR; +#else +#define XML_ENCODE_MAX XML_UTF8_ENCODE_MAX +#define XmlConvert XmlUtf8Convert +#define XmlGetInternalEncoding XmlGetUtf8InternalEncoding +#define XmlGetInternalEncodingNS XmlGetUtf8InternalEncodingNS +#define XmlEncode XmlUtf8Encode +#define MUST_CONVERT(enc, s) (!(enc)->isUtf8) +typedef char ICHAR; +#endif + + +#ifndef XML_NS + +#define XmlInitEncodingNS XmlInitEncoding +#define XmlInitUnknownEncodingNS XmlInitUnknownEncoding +#undef XmlGetInternalEncodingNS +#define XmlGetInternalEncodingNS XmlGetInternalEncoding +#define XmlParseXmlDeclNS XmlParseXmlDecl + +#endif + +#ifdef XML_UNICODE_WCHAR_T +#define XML_T(x) L ## x +#else +#define XML_T(x) x +#endif + +/* Round up n to be a multiple of sz, where sz is a power of 2. */ +#define ROUND_UP(n, sz) (((n) + ((sz) - 1)) & ~((sz) - 1)) + +#include "xmltok.h" +#include "xmlrole.h" + +typedef const XML_Char *KEY; + +typedef struct { + KEY name; +} NAMED; + +typedef struct { + NAMED **v; + size_t size; + size_t used; + size_t usedLim; + XML_Memory_Handling_Suite *mem; +} HASH_TABLE; + +typedef struct { + NAMED **p; + NAMED **end; +} HASH_TABLE_ITER; + +#define INIT_TAG_BUF_SIZE 32 /* must be a multiple of sizeof(XML_Char) */ +#define INIT_DATA_BUF_SIZE 1024 +#define INIT_ATTS_SIZE 16 +#define INIT_BLOCK_SIZE 1024 +#define INIT_BUFFER_SIZE 1024 + +#define EXPAND_SPARE 24 + +typedef struct binding { + struct prefix *prefix; + struct binding *nextTagBinding; + struct binding *prevPrefixBinding; + const struct attribute_id *attId; + XML_Char *uri; + int uriLen; + int uriAlloc; +} BINDING; + +typedef struct prefix { + const XML_Char *name; + BINDING *binding; +} PREFIX; + +typedef struct { + const XML_Char *str; + const XML_Char *localPart; + int uriLen; +} TAG_NAME; + +typedef struct tag { + struct tag *parent; + const char *rawName; + int rawNameLength; + TAG_NAME name; + char *buf; + char *bufEnd; + BINDING *bindings; +} TAG; + +typedef struct { + const XML_Char *name; + const XML_Char *textPtr; + int textLen; + const XML_Char *systemId; + const XML_Char *base; + const XML_Char *publicId; + const XML_Char *notation; + char open; + char is_param; +} ENTITY; + +typedef struct { + enum XML_Content_Type type; + enum XML_Content_Quant quant; + const XML_Char * name; + int firstchild; + int lastchild; + int childcnt; + int nextsib; +} CONTENT_SCAFFOLD; + +typedef struct block { + struct block *next; + int size; + XML_Char s[1]; +} BLOCK; + +typedef struct { + BLOCK *blocks; + BLOCK *freeBlocks; + const XML_Char *end; + XML_Char *ptr; + XML_Char *start; + XML_Memory_Handling_Suite *mem; +} STRING_POOL; + +/* The XML_Char before the name is used to determine whether +an attribute has been specified. */ +typedef struct attribute_id { + XML_Char *name; + PREFIX *prefix; + char maybeTokenized; + char xmlns; +} ATTRIBUTE_ID; + +typedef struct { + const ATTRIBUTE_ID *id; + char isCdata; + const XML_Char *value; +} DEFAULT_ATTRIBUTE; + +typedef struct { + const XML_Char *name; + PREFIX *prefix; + const ATTRIBUTE_ID *idAtt; + int nDefaultAtts; + int allocDefaultAtts; + DEFAULT_ATTRIBUTE *defaultAtts; +} ELEMENT_TYPE; + +typedef struct { + HASH_TABLE generalEntities; + HASH_TABLE elementTypes; + HASH_TABLE attributeIds; + HASH_TABLE prefixes; + STRING_POOL pool; + int complete; + int standalone; +#ifdef XML_DTD + HASH_TABLE paramEntities; +#endif /* XML_DTD */ + PREFIX defaultPrefix; + /* === scaffolding for building content model === */ + int in_eldecl; + CONTENT_SCAFFOLD *scaffold; + unsigned contentStringLen; + unsigned scaffSize; + unsigned scaffCount; + int scaffLevel; + int *scaffIndex; +} DTD; + +typedef struct open_internal_entity { + const char *internalEventPtr; + const char *internalEventEndPtr; + struct open_internal_entity *next; + ENTITY *entity; +} OPEN_INTERNAL_ENTITY; + +typedef enum XML_Error Processor(XML_Parser parser, + const char *start, + const char *end, + const char **endPtr); + +static Processor prologProcessor; +static Processor prologInitProcessor; +static Processor contentProcessor; +static Processor cdataSectionProcessor; +#ifdef XML_DTD +static Processor ignoreSectionProcessor; +#endif /* XML_DTD */ +static Processor epilogProcessor; +static Processor errorProcessor; +static Processor externalEntityInitProcessor; +static Processor externalEntityInitProcessor2; +static Processor externalEntityInitProcessor3; +static Processor externalEntityContentProcessor; + +static enum XML_Error +handleUnknownEncoding(XML_Parser parser, const XML_Char *encodingName); +static enum XML_Error +processXmlDecl(XML_Parser parser, int isGeneralTextEntity, const char *, const char *); +static enum XML_Error +initializeEncoding(XML_Parser parser); +static enum XML_Error +doProlog(XML_Parser parser, const ENCODING *enc, const char *s, + const char *end, int tok, const char *next, const char **nextPtr); +static enum XML_Error +processInternalParamEntity(XML_Parser parser, ENTITY *entity); +static enum XML_Error +doContent(XML_Parser parser, int startTagLevel, const ENCODING *enc, + const char *start, const char *end, const char **endPtr); +static enum XML_Error +doCdataSection(XML_Parser parser, const ENCODING *, const char **startPtr, const char *end, const char **nextPtr); +#ifdef XML_DTD +static enum XML_Error +doIgnoreSection(XML_Parser parser, const ENCODING *, const char **startPtr, const char *end, const char **nextPtr); +#endif /* XML_DTD */ +static enum XML_Error storeAtts(XML_Parser parser, const ENCODING *, const char *s, + TAG_NAME *tagNamePtr, BINDING **bindingsPtr); +static +int addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId, const XML_Char *uri, BINDING **bindingsPtr); + +static int +defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *, + int isCdata, int isId, const XML_Char *dfltValue, + XML_Parser parser); + +static enum XML_Error +storeAttributeValue(XML_Parser parser, const ENCODING *, int isCdata, const char *, const char *, + STRING_POOL *); +static enum XML_Error +appendAttributeValue(XML_Parser parser, const ENCODING *, int isCdata, const char *, const char *, + STRING_POOL *); +static ATTRIBUTE_ID * +getAttributeId(XML_Parser parser, const ENCODING *enc, const char *start, const char *end); +static int setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *); +static enum XML_Error +storeEntityValue(XML_Parser parser, const ENCODING *enc, const char *start, const char *end); +static int +reportProcessingInstruction(XML_Parser parser, const ENCODING *enc, const char *start, const char *end); +static int +reportComment(XML_Parser parser, const ENCODING *enc, const char *start, const char *end); +static void +reportDefault(XML_Parser parser, const ENCODING *enc, const char *start, const char *end); + +static const XML_Char *getContext(XML_Parser parser); +static int setContext(XML_Parser parser, const XML_Char *context); +static void normalizePublicId(XML_Char *s); +static int dtdInit(DTD *, XML_Parser parser); + +static void dtdDestroy(DTD *, XML_Parser parser); + +static int dtdCopy(DTD *newDtd, const DTD *oldDtd, XML_Parser parser); + +static int copyEntityTable(HASH_TABLE *, STRING_POOL *, const HASH_TABLE *, + XML_Parser parser); + +#ifdef XML_DTD +static void dtdSwap(DTD *, DTD *); +#endif /* XML_DTD */ + +static NAMED *lookup(HASH_TABLE *table, KEY name, size_t createSize); + +static void hashTableInit(HASH_TABLE *, XML_Memory_Handling_Suite *ms); + +static void hashTableDestroy(HASH_TABLE *); +static void hashTableIterInit(HASH_TABLE_ITER *, const HASH_TABLE *); +static NAMED *hashTableIterNext(HASH_TABLE_ITER *); +static void poolInit(STRING_POOL *, XML_Memory_Handling_Suite *ms); +static void poolClear(STRING_POOL *); +static void poolDestroy(STRING_POOL *); +static XML_Char *poolAppend(STRING_POOL *pool, const ENCODING *enc, + const char *ptr, const char *end); +static XML_Char *poolStoreString(STRING_POOL *pool, const ENCODING *enc, + const char *ptr, const char *end); + +static int poolGrow(STRING_POOL *pool); + +static int nextScaffoldPart(XML_Parser parser); +static XML_Content *build_model(XML_Parser parser); + +static const XML_Char *poolCopyString(STRING_POOL *pool, const XML_Char *s); +static const XML_Char *poolCopyStringN(STRING_POOL *pool, const XML_Char *s, int n); +static const XML_Char *poolAppendString(STRING_POOL *pool, const XML_Char *s); +static ELEMENT_TYPE * getElementType(XML_Parser Paraser, + const ENCODING *enc, + const char *ptr, + const char *end); + +#define poolStart(pool) ((pool)->start) +#define poolEnd(pool) ((pool)->ptr) +#define poolLength(pool) ((pool)->ptr - (pool)->start) +#define poolChop(pool) ((void)--(pool->ptr)) +#define poolLastChar(pool) (((pool)->ptr)[-1]) +#define poolDiscard(pool) ((pool)->ptr = (pool)->start) +#define poolFinish(pool) ((pool)->start = (pool)->ptr) +#define poolAppendChar(pool, c) \ + (((pool)->ptr == (pool)->end && !poolGrow(pool)) \ + ? 0 \ + : ((*((pool)->ptr)++ = c), 1)) + +typedef struct { + /* The first member must be userData so that the XML_GetUserData macro works. */ + void *m_userData; + void *m_handlerArg; + char *m_buffer; + XML_Memory_Handling_Suite m_mem; + /* first character to be parsed */ + const char *m_bufferPtr; + /* past last character to be parsed */ + char *m_bufferEnd; + /* allocated end of buffer */ + const char *m_bufferLim; + long m_parseEndByteIndex; + const char *m_parseEndPtr; + XML_Char *m_dataBuf; + XML_Char *m_dataBufEnd; + XML_StartElementHandler m_startElementHandler; + XML_EndElementHandler m_endElementHandler; + XML_CharacterDataHandler m_characterDataHandler; + XML_ProcessingInstructionHandler m_processingInstructionHandler; + XML_CommentHandler m_commentHandler; + XML_StartCdataSectionHandler m_startCdataSectionHandler; + XML_EndCdataSectionHandler m_endCdataSectionHandler; + XML_DefaultHandler m_defaultHandler; + XML_StartDoctypeDeclHandler m_startDoctypeDeclHandler; + XML_EndDoctypeDeclHandler m_endDoctypeDeclHandler; + XML_UnparsedEntityDeclHandler m_unparsedEntityDeclHandler; + XML_NotationDeclHandler m_notationDeclHandler; + XML_StartNamespaceDeclHandler m_startNamespaceDeclHandler; + XML_EndNamespaceDeclHandler m_endNamespaceDeclHandler; + XML_NotStandaloneHandler m_notStandaloneHandler; + XML_ExternalEntityRefHandler m_externalEntityRefHandler; + void *m_externalEntityRefHandlerArg; + XML_UnknownEncodingHandler m_unknownEncodingHandler; + XML_ElementDeclHandler m_elementDeclHandler; + XML_AttlistDeclHandler m_attlistDeclHandler; + XML_EntityDeclHandler m_entityDeclHandler; + XML_XmlDeclHandler m_xmlDeclHandler; + const ENCODING *m_encoding; + INIT_ENCODING m_initEncoding; + const ENCODING *m_internalEncoding; + const XML_Char *m_protocolEncodingName; + int m_ns; + int m_ns_triplets; + void *m_unknownEncodingMem; + void *m_unknownEncodingData; + void *m_unknownEncodingHandlerData; + void (*m_unknownEncodingRelease)(void *); + PROLOG_STATE m_prologState; + Processor *m_processor; + enum XML_Error m_errorCode; + const char *m_eventPtr; + const char *m_eventEndPtr; + const char *m_positionPtr; + OPEN_INTERNAL_ENTITY *m_openInternalEntities; + int m_defaultExpandInternalEntities; + int m_tagLevel; + ENTITY *m_declEntity; + const XML_Char *m_doctypeName; + const XML_Char *m_doctypeSysid; + const XML_Char *m_doctypePubid; + const XML_Char *m_declAttributeType; + const XML_Char *m_declNotationName; + const XML_Char *m_declNotationPublicId; + ELEMENT_TYPE *m_declElementType; + ATTRIBUTE_ID *m_declAttributeId; + char m_declAttributeIsCdata; + char m_declAttributeIsId; + DTD m_dtd; + const XML_Char *m_curBase; + TAG *m_tagStack; + TAG *m_freeTagList; + BINDING *m_inheritedBindings; + BINDING *m_freeBindingList; + int m_attsSize; + int m_nSpecifiedAtts; + int m_idAttIndex; + ATTRIBUTE *m_atts; + POSITION m_position; + STRING_POOL m_tempPool; + STRING_POOL m_temp2Pool; + char *m_groupConnector; + unsigned m_groupSize; + int m_hadExternalDoctype; + XML_Char m_namespaceSeparator; +#ifdef XML_DTD + enum XML_ParamEntityParsing m_paramEntityParsing; + XML_Parser m_parentParser; +#endif +} Parser; + +#define MALLOC(s) (((Parser *)parser)->m_mem.malloc_fcn((s))) +#define REALLOC(p,s) (((Parser *)parser)->m_mem.realloc_fcn((p),(s))) +#define FREE(p) (((Parser *)parser)->m_mem.free_fcn((p))) + +#define userData (((Parser *)parser)->m_userData) +#define handlerArg (((Parser *)parser)->m_handlerArg) +#define startElementHandler (((Parser *)parser)->m_startElementHandler) +#define endElementHandler (((Parser *)parser)->m_endElementHandler) +#define characterDataHandler (((Parser *)parser)->m_characterDataHandler) +#define processingInstructionHandler (((Parser *)parser)->m_processingInstructionHandler) +#define commentHandler (((Parser *)parser)->m_commentHandler) +#define startCdataSectionHandler (((Parser *)parser)->m_startCdataSectionHandler) +#define endCdataSectionHandler (((Parser *)parser)->m_endCdataSectionHandler) +#define defaultHandler (((Parser *)parser)->m_defaultHandler) +#define startDoctypeDeclHandler (((Parser *)parser)->m_startDoctypeDeclHandler) +#define endDoctypeDeclHandler (((Parser *)parser)->m_endDoctypeDeclHandler) +#define unparsedEntityDeclHandler (((Parser *)parser)->m_unparsedEntityDeclHandler) +#define notationDeclHandler (((Parser *)parser)->m_notationDeclHandler) +#define startNamespaceDeclHandler (((Parser *)parser)->m_startNamespaceDeclHandler) +#define endNamespaceDeclHandler (((Parser *)parser)->m_endNamespaceDeclHandler) +#define notStandaloneHandler (((Parser *)parser)->m_notStandaloneHandler) +#define externalEntityRefHandler (((Parser *)parser)->m_externalEntityRefHandler) +#define externalEntityRefHandlerArg (((Parser *)parser)->m_externalEntityRefHandlerArg) +#define unknownEncodingHandler (((Parser *)parser)->m_unknownEncodingHandler) +#define elementDeclHandler (((Parser *)parser)->m_elementDeclHandler) +#define attlistDeclHandler (((Parser *)parser)->m_attlistDeclHandler) +#define entityDeclHandler (((Parser *)parser)->m_entityDeclHandler) +#define xmlDeclHandler (((Parser *)parser)->m_xmlDeclHandler) +#define encoding (((Parser *)parser)->m_encoding) +#define initEncoding (((Parser *)parser)->m_initEncoding) +#define internalEncoding (((Parser *)parser)->m_internalEncoding) +#define unknownEncodingMem (((Parser *)parser)->m_unknownEncodingMem) +#define unknownEncodingData (((Parser *)parser)->m_unknownEncodingData) +#define unknownEncodingHandlerData \ + (((Parser *)parser)->m_unknownEncodingHandlerData) +#define unknownEncodingRelease (((Parser *)parser)->m_unknownEncodingRelease) +#define protocolEncodingName (((Parser *)parser)->m_protocolEncodingName) +#define ns (((Parser *)parser)->m_ns) +#define ns_triplets (((Parser *)parser)->m_ns_triplets) +#define prologState (((Parser *)parser)->m_prologState) +#define processor (((Parser *)parser)->m_processor) +#define errorCode (((Parser *)parser)->m_errorCode) +#define eventPtr (((Parser *)parser)->m_eventPtr) +#define eventEndPtr (((Parser *)parser)->m_eventEndPtr) +#define positionPtr (((Parser *)parser)->m_positionPtr) +#define position (((Parser *)parser)->m_position) +#define openInternalEntities (((Parser *)parser)->m_openInternalEntities) +#define defaultExpandInternalEntities (((Parser *)parser)->m_defaultExpandInternalEntities) +#define tagLevel (((Parser *)parser)->m_tagLevel) +#define buffer (((Parser *)parser)->m_buffer) +#define bufferPtr (((Parser *)parser)->m_bufferPtr) +#define bufferEnd (((Parser *)parser)->m_bufferEnd) +#define parseEndByteIndex (((Parser *)parser)->m_parseEndByteIndex) +#define parseEndPtr (((Parser *)parser)->m_parseEndPtr) +#define bufferLim (((Parser *)parser)->m_bufferLim) +#define dataBuf (((Parser *)parser)->m_dataBuf) +#define dataBufEnd (((Parser *)parser)->m_dataBufEnd) +#define dtd (((Parser *)parser)->m_dtd) +#define curBase (((Parser *)parser)->m_curBase) +#define declEntity (((Parser *)parser)->m_declEntity) +#define doctypeName (((Parser *)parser)->m_doctypeName) +#define doctypeSysid (((Parser *)parser)->m_doctypeSysid) +#define doctypePubid (((Parser *)parser)->m_doctypePubid) +#define declAttributeType (((Parser *)parser)->m_declAttributeType) +#define declNotationName (((Parser *)parser)->m_declNotationName) +#define declNotationPublicId (((Parser *)parser)->m_declNotationPublicId) +#define declElementType (((Parser *)parser)->m_declElementType) +#define declAttributeId (((Parser *)parser)->m_declAttributeId) +#define declAttributeIsCdata (((Parser *)parser)->m_declAttributeIsCdata) +#define declAttributeIsId (((Parser *)parser)->m_declAttributeIsId) +#define freeTagList (((Parser *)parser)->m_freeTagList) +#define freeBindingList (((Parser *)parser)->m_freeBindingList) +#define inheritedBindings (((Parser *)parser)->m_inheritedBindings) +#define tagStack (((Parser *)parser)->m_tagStack) +#define atts (((Parser *)parser)->m_atts) +#define attsSize (((Parser *)parser)->m_attsSize) +#define nSpecifiedAtts (((Parser *)parser)->m_nSpecifiedAtts) +#define idAttIndex (((Parser *)parser)->m_idAttIndex) +#define tempPool (((Parser *)parser)->m_tempPool) +#define temp2Pool (((Parser *)parser)->m_temp2Pool) +#define groupConnector (((Parser *)parser)->m_groupConnector) +#define groupSize (((Parser *)parser)->m_groupSize) +#define hadExternalDoctype (((Parser *)parser)->m_hadExternalDoctype) +#define namespaceSeparator (((Parser *)parser)->m_namespaceSeparator) +#ifdef XML_DTD +#define parentParser (((Parser *)parser)->m_parentParser) +#define paramEntityParsing (((Parser *)parser)->m_paramEntityParsing) +#endif /* XML_DTD */ + +#ifdef _MSC_VER +#ifdef _DEBUG +Parser *asParser(XML_Parser parser) +{ + return parser; +} +#endif +#endif + +XML_Parser XML_ParserCreate(const XML_Char *encodingName) +{ + return XML_ParserCreate_MM(encodingName, NULL, NULL); +} + +XML_Parser XML_ParserCreateNS(const XML_Char *encodingName, XML_Char nsSep) +{ + XML_Char tmp[2]; + *tmp = nsSep; + return XML_ParserCreate_MM(encodingName, NULL, tmp); +} + +XML_Parser +XML_ParserCreate_MM(const XML_Char *encodingName, + const XML_Memory_Handling_Suite *memsuite, + const XML_Char *nameSep) { + + XML_Parser parser; + static + const XML_Char implicitContext[] = { + XML_T('x'), XML_T('m'), XML_T('l'), XML_T('='), + XML_T('h'), XML_T('t'), XML_T('t'), XML_T('p'), XML_T(':'), + XML_T('/'), XML_T('/'), XML_T('w'), XML_T('w'), XML_T('w'), + XML_T('.'), XML_T('w'), XML_T('3'), + XML_T('.'), XML_T('o'), XML_T('r'), XML_T('g'), + XML_T('/'), XML_T('X'), XML_T('M'), XML_T('L'), + XML_T('/'), XML_T('1'), XML_T('9'), XML_T('9'), XML_T('8'), + XML_T('/'), XML_T('n'), XML_T('a'), XML_T('m'), XML_T('e'), + XML_T('s'), XML_T('p'), XML_T('a'), XML_T('c'), XML_T('e'), + XML_T('\0') + }; + + + if (memsuite) { + XML_Memory_Handling_Suite *mtemp; + parser = memsuite->malloc_fcn(sizeof(Parser)); + mtemp = &(((Parser *) parser)->m_mem); + mtemp->malloc_fcn = memsuite->malloc_fcn; + mtemp->realloc_fcn = memsuite->realloc_fcn; + mtemp->free_fcn = memsuite->free_fcn; + } + else { + XML_Memory_Handling_Suite *mtemp; + parser = malloc(sizeof(Parser)); + mtemp = &(((Parser *) parser)->m_mem); + mtemp->malloc_fcn = malloc; + mtemp->realloc_fcn = realloc; + mtemp->free_fcn = free; + } + + if (!parser) + return parser; + processor = prologInitProcessor; + XmlPrologStateInit(&prologState); + userData = 0; + handlerArg = 0; + startElementHandler = 0; + endElementHandler = 0; + characterDataHandler = 0; + processingInstructionHandler = 0; + commentHandler = 0; + startCdataSectionHandler = 0; + endCdataSectionHandler = 0; + defaultHandler = 0; + startDoctypeDeclHandler = 0; + endDoctypeDeclHandler = 0; + unparsedEntityDeclHandler = 0; + notationDeclHandler = 0; + startNamespaceDeclHandler = 0; + endNamespaceDeclHandler = 0; + notStandaloneHandler = 0; + externalEntityRefHandler = 0; + externalEntityRefHandlerArg = parser; + unknownEncodingHandler = 0; + elementDeclHandler = 0; + attlistDeclHandler = 0; + entityDeclHandler = 0; + xmlDeclHandler = 0; + buffer = 0; + bufferPtr = 0; + bufferEnd = 0; + parseEndByteIndex = 0; + parseEndPtr = 0; + bufferLim = 0; + declElementType = 0; + declAttributeId = 0; + declEntity = 0; + doctypeName = 0; + doctypeSysid = 0; + doctypePubid = 0; + declAttributeType = 0; + declNotationName = 0; + declNotationPublicId = 0; + memset(&position, 0, sizeof(POSITION)); + errorCode = XML_ERROR_NONE; + eventPtr = 0; + eventEndPtr = 0; + positionPtr = 0; + openInternalEntities = 0; + tagLevel = 0; + tagStack = 0; + freeTagList = 0; + freeBindingList = 0; + inheritedBindings = 0; + attsSize = INIT_ATTS_SIZE; + atts = MALLOC(attsSize * sizeof(ATTRIBUTE)); + nSpecifiedAtts = 0; + dataBuf = MALLOC(INIT_DATA_BUF_SIZE * sizeof(XML_Char)); + groupSize = 0; + groupConnector = 0; + hadExternalDoctype = 0; + unknownEncodingMem = 0; + unknownEncodingRelease = 0; + unknownEncodingData = 0; + unknownEncodingHandlerData = 0; + namespaceSeparator = '!'; +#ifdef XML_DTD + parentParser = 0; + paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER; +#endif + ns = 0; + ns_triplets = 0; + poolInit(&tempPool, &(((Parser *) parser)->m_mem)); + poolInit(&temp2Pool, &(((Parser *) parser)->m_mem)); + protocolEncodingName = encodingName ? poolCopyString(&tempPool, encodingName) : 0; + curBase = 0; + if (!dtdInit(&dtd, parser) || !atts || !dataBuf + || (encodingName && !protocolEncodingName)) { + XML_ParserFree(parser); + return 0; + } + dataBufEnd = dataBuf + INIT_DATA_BUF_SIZE; + + if (nameSep) { + XmlInitEncodingNS(&initEncoding, &encoding, 0); + ns = 1; + internalEncoding = XmlGetInternalEncodingNS(); + namespaceSeparator = *nameSep; + + if (! setContext(parser, implicitContext)) { + XML_ParserFree(parser); + return 0; + } + } + else { + XmlInitEncoding(&initEncoding, &encoding, 0); + internalEncoding = XmlGetInternalEncoding(); + } + + return parser; +} /* End XML_ParserCreate_MM */ + +int XML_SetEncoding(XML_Parser parser, const XML_Char *encodingName) +{ + if (!encodingName) + protocolEncodingName = 0; + else { + protocolEncodingName = poolCopyString(&tempPool, encodingName); + if (!protocolEncodingName) + return 0; + } + return 1; +} + +XML_Parser XML_ExternalEntityParserCreate(XML_Parser oldParser, + const XML_Char *context, + const XML_Char *encodingName) +{ + XML_Parser parser = oldParser; + DTD *oldDtd = &dtd; + XML_StartElementHandler oldStartElementHandler = startElementHandler; + XML_EndElementHandler oldEndElementHandler = endElementHandler; + XML_CharacterDataHandler oldCharacterDataHandler = characterDataHandler; + XML_ProcessingInstructionHandler oldProcessingInstructionHandler = processingInstructionHandler; + XML_CommentHandler oldCommentHandler = commentHandler; + XML_StartCdataSectionHandler oldStartCdataSectionHandler = startCdataSectionHandler; + XML_EndCdataSectionHandler oldEndCdataSectionHandler = endCdataSectionHandler; + XML_DefaultHandler oldDefaultHandler = defaultHandler; + XML_UnparsedEntityDeclHandler oldUnparsedEntityDeclHandler = unparsedEntityDeclHandler; + XML_NotationDeclHandler oldNotationDeclHandler = notationDeclHandler; + XML_StartNamespaceDeclHandler oldStartNamespaceDeclHandler = startNamespaceDeclHandler; + XML_EndNamespaceDeclHandler oldEndNamespaceDeclHandler = endNamespaceDeclHandler; + XML_NotStandaloneHandler oldNotStandaloneHandler = notStandaloneHandler; + XML_ExternalEntityRefHandler oldExternalEntityRefHandler = externalEntityRefHandler; + XML_UnknownEncodingHandler oldUnknownEncodingHandler = unknownEncodingHandler; + XML_ElementDeclHandler oldElementDeclHandler = elementDeclHandler; + XML_AttlistDeclHandler oldAttlistDeclHandler = attlistDeclHandler; + XML_EntityDeclHandler oldEntityDeclHandler = entityDeclHandler; + XML_XmlDeclHandler oldXmlDeclHandler = xmlDeclHandler; + ELEMENT_TYPE * oldDeclElementType = declElementType; + + void *oldUserData = userData; + void *oldHandlerArg = handlerArg; + int oldDefaultExpandInternalEntities = defaultExpandInternalEntities; + void *oldExternalEntityRefHandlerArg = externalEntityRefHandlerArg; +#ifdef XML_DTD + int oldParamEntityParsing = paramEntityParsing; +#endif + int oldns_triplets = ns_triplets; + + if (ns) { + XML_Char tmp[2]; + + *tmp = namespaceSeparator; + parser = XML_ParserCreate_MM(encodingName, &((Parser *)parser)->m_mem, + tmp); + } + else { + parser = XML_ParserCreate_MM(encodingName, &((Parser *)parser)->m_mem, + NULL); + } + + if (!parser) + return 0; + + startElementHandler = oldStartElementHandler; + endElementHandler = oldEndElementHandler; + characterDataHandler = oldCharacterDataHandler; + processingInstructionHandler = oldProcessingInstructionHandler; + commentHandler = oldCommentHandler; + startCdataSectionHandler = oldStartCdataSectionHandler; + endCdataSectionHandler = oldEndCdataSectionHandler; + defaultHandler = oldDefaultHandler; + unparsedEntityDeclHandler = oldUnparsedEntityDeclHandler; + notationDeclHandler = oldNotationDeclHandler; + startNamespaceDeclHandler = oldStartNamespaceDeclHandler; + endNamespaceDeclHandler = oldEndNamespaceDeclHandler; + notStandaloneHandler = oldNotStandaloneHandler; + externalEntityRefHandler = oldExternalEntityRefHandler; + unknownEncodingHandler = oldUnknownEncodingHandler; + elementDeclHandler = oldElementDeclHandler; + attlistDeclHandler = oldAttlistDeclHandler; + entityDeclHandler = oldEntityDeclHandler; + xmlDeclHandler = oldXmlDeclHandler; + declElementType = oldDeclElementType; + userData = oldUserData; + if (oldUserData == oldHandlerArg) + handlerArg = userData; + else + handlerArg = parser; + if (oldExternalEntityRefHandlerArg != oldParser) + externalEntityRefHandlerArg = oldExternalEntityRefHandlerArg; + defaultExpandInternalEntities = oldDefaultExpandInternalEntities; + ns_triplets = oldns_triplets; +#ifdef XML_DTD + paramEntityParsing = oldParamEntityParsing; + if (context) { +#endif /* XML_DTD */ + if (!dtdCopy(&dtd, oldDtd, parser) || !setContext(parser, context)) { + XML_ParserFree(parser); + return 0; + } + processor = externalEntityInitProcessor; +#ifdef XML_DTD + } + else { + dtdSwap(&dtd, oldDtd); + parentParser = oldParser; + XmlPrologStateInitExternalEntity(&prologState); + dtd.complete = 1; + hadExternalDoctype = 1; + } +#endif /* XML_DTD */ + return parser; +} + +static +void destroyBindings(BINDING *bindings, XML_Parser parser) +{ + for (;;) { + BINDING *b = bindings; + if (!b) + break; + bindings = b->nextTagBinding; + FREE(b->uri); + FREE(b); + } +} + +void XML_ParserFree(XML_Parser parser) +{ + for (;;) { + TAG *p; + if (tagStack == 0) { + if (freeTagList == 0) + break; + tagStack = freeTagList; + freeTagList = 0; + } + p = tagStack; + tagStack = tagStack->parent; + FREE(p->buf); + destroyBindings(p->bindings, parser); + FREE(p); + } + destroyBindings(freeBindingList, parser); + destroyBindings(inheritedBindings, parser); + poolDestroy(&tempPool); + poolDestroy(&temp2Pool); +#ifdef XML_DTD + if (parentParser) { + if (hadExternalDoctype) + dtd.complete = 0; + dtdSwap(&dtd, &((Parser *)parentParser)->m_dtd); + } +#endif /* XML_DTD */ + dtdDestroy(&dtd, parser); + FREE((void *)atts); + if (groupConnector) + FREE(groupConnector); + if (buffer) + FREE(buffer); + FREE(dataBuf); + if (unknownEncodingMem) + FREE(unknownEncodingMem); + if (unknownEncodingRelease) + unknownEncodingRelease(unknownEncodingData); + FREE(parser); +} + +void XML_UseParserAsHandlerArg(XML_Parser parser) +{ + handlerArg = parser; +} + +void +XML_SetReturnNSTriplet(XML_Parser parser, int do_nst) { + ns_triplets = do_nst; +} + +void XML_SetUserData(XML_Parser parser, void *p) +{ + if (handlerArg == userData) + handlerArg = userData = p; + else + userData = p; +} + +int XML_SetBase(XML_Parser parser, const XML_Char *p) +{ + if (p) { + p = poolCopyString(&dtd.pool, p); + if (!p) + return 0; + curBase = p; + } + else + curBase = 0; + return 1; +} + +const XML_Char *XML_GetBase(XML_Parser parser) +{ + return curBase; +} + +int XML_GetSpecifiedAttributeCount(XML_Parser parser) +{ + return nSpecifiedAtts; +} + +int XML_GetIdAttributeIndex(XML_Parser parser) +{ + return idAttIndex; +} + +void XML_SetElementHandler(XML_Parser parser, + XML_StartElementHandler start, + XML_EndElementHandler end) +{ + startElementHandler = start; + endElementHandler = end; +} + +void XML_SetStartElementHandler(XML_Parser parser, + XML_StartElementHandler start) { + startElementHandler = start; +} + +void XML_SetEndElementHandler(XML_Parser parser, + XML_EndElementHandler end) { + endElementHandler = end; +} + +void XML_SetCharacterDataHandler(XML_Parser parser, + XML_CharacterDataHandler handler) +{ + characterDataHandler = handler; +} + +void XML_SetProcessingInstructionHandler(XML_Parser parser, + XML_ProcessingInstructionHandler handler) +{ + processingInstructionHandler = handler; +} + +void XML_SetCommentHandler(XML_Parser parser, + XML_CommentHandler handler) +{ + commentHandler = handler; +} + +void XML_SetCdataSectionHandler(XML_Parser parser, + XML_StartCdataSectionHandler start, + XML_EndCdataSectionHandler end) +{ + startCdataSectionHandler = start; + endCdataSectionHandler = end; +} + +void XML_SetStartCdataSectionHandler(XML_Parser parser, + XML_StartCdataSectionHandler start) { + startCdataSectionHandler = start; +} + +void XML_SetEndCdataSectionHandler(XML_Parser parser, + XML_EndCdataSectionHandler end) { + endCdataSectionHandler = end; +} + +void XML_SetDefaultHandler(XML_Parser parser, + XML_DefaultHandler handler) +{ + defaultHandler = handler; + defaultExpandInternalEntities = 0; +} + +void XML_SetDefaultHandlerExpand(XML_Parser parser, + XML_DefaultHandler handler) +{ + defaultHandler = handler; + defaultExpandInternalEntities = 1; +} + +void XML_SetDoctypeDeclHandler(XML_Parser parser, + XML_StartDoctypeDeclHandler start, + XML_EndDoctypeDeclHandler end) +{ + startDoctypeDeclHandler = start; + endDoctypeDeclHandler = end; +} + +void XML_SetStartDoctypeDeclHandler(XML_Parser parser, + XML_StartDoctypeDeclHandler start) { + startDoctypeDeclHandler = start; +} + +void XML_SetEndDoctypeDeclHandler(XML_Parser parser, + XML_EndDoctypeDeclHandler end) { + endDoctypeDeclHandler = end; +} + +void XML_SetUnparsedEntityDeclHandler(XML_Parser parser, + XML_UnparsedEntityDeclHandler handler) +{ + unparsedEntityDeclHandler = handler; +} + +void XML_SetNotationDeclHandler(XML_Parser parser, + XML_NotationDeclHandler handler) +{ + notationDeclHandler = handler; +} + +void XML_SetNamespaceDeclHandler(XML_Parser parser, + XML_StartNamespaceDeclHandler start, + XML_EndNamespaceDeclHandler end) +{ + startNamespaceDeclHandler = start; + endNamespaceDeclHandler = end; +} + +void XML_SetStartNamespaceDeclHandler(XML_Parser parser, + XML_StartNamespaceDeclHandler start) { + startNamespaceDeclHandler = start; +} + +void XML_SetEndNamespaceDeclHandler(XML_Parser parser, + XML_EndNamespaceDeclHandler end); + + +void XML_SetNotStandaloneHandler(XML_Parser parser, + XML_NotStandaloneHandler handler) +{ + notStandaloneHandler = handler; +} + +void XML_SetExternalEntityRefHandler(XML_Parser parser, + XML_ExternalEntityRefHandler handler) +{ + externalEntityRefHandler = handler; +} + +void XML_SetExternalEntityRefHandlerArg(XML_Parser parser, void *arg) +{ + if (arg) + externalEntityRefHandlerArg = arg; + else + externalEntityRefHandlerArg = parser; +} + +void XML_SetUnknownEncodingHandler(XML_Parser parser, + XML_UnknownEncodingHandler handler, + void *data) +{ + unknownEncodingHandler = handler; + unknownEncodingHandlerData = data; +} + +void XML_SetElementDeclHandler(XML_Parser parser, + XML_ElementDeclHandler eldecl) +{ + elementDeclHandler = eldecl; +} + +void XML_SetAttlistDeclHandler(XML_Parser parser, + XML_AttlistDeclHandler attdecl) +{ + attlistDeclHandler = attdecl; +} + +void XML_SetEntityDeclHandler(XML_Parser parser, + XML_EntityDeclHandler handler) +{ + entityDeclHandler = handler; +} + +void XML_SetXmlDeclHandler(XML_Parser parser, + XML_XmlDeclHandler handler) { + xmlDeclHandler = handler; +} + +int XML_SetParamEntityParsing(XML_Parser parser, + enum XML_ParamEntityParsing parsing) +{ +#ifdef XML_DTD + paramEntityParsing = parsing; + return 1; +#else + return parsing == XML_PARAM_ENTITY_PARSING_NEVER; +#endif +} + +int XML_Parse(XML_Parser parser, const char *s, int len, int isFinal) +{ + if (len == 0) { + if (!isFinal) + return 1; + positionPtr = bufferPtr; + errorCode = processor(parser, bufferPtr, parseEndPtr = bufferEnd, 0); + if (errorCode == XML_ERROR_NONE) + return 1; + eventEndPtr = eventPtr; + processor = errorProcessor; + return 0; + } +#ifndef XML_CONTEXT_BYTES + else if (bufferPtr == bufferEnd) { + const char *end; + int nLeftOver; + parseEndByteIndex += len; + positionPtr = s; + if (isFinal) { + errorCode = processor(parser, s, parseEndPtr = s + len, 0); + if (errorCode == XML_ERROR_NONE) + return 1; + eventEndPtr = eventPtr; + processor = errorProcessor; + return 0; + } + errorCode = processor(parser, s, parseEndPtr = s + len, &end); + if (errorCode != XML_ERROR_NONE) { + eventEndPtr = eventPtr; + processor = errorProcessor; + return 0; + } + XmlUpdatePosition(encoding, positionPtr, end, &position); + nLeftOver = s + len - end; + if (nLeftOver) { + if (buffer == 0 || nLeftOver > bufferLim - buffer) { + /* FIXME avoid integer overflow */ + buffer = buffer == 0 ? MALLOC(len * 2) : REALLOC(buffer, len * 2); + /* FIXME storage leak if realloc fails */ + if (!buffer) { + errorCode = XML_ERROR_NO_MEMORY; + eventPtr = eventEndPtr = 0; + processor = errorProcessor; + return 0; + } + bufferLim = buffer + len * 2; + } + memcpy(buffer, end, nLeftOver); + bufferPtr = buffer; + bufferEnd = buffer + nLeftOver; + } + return 1; + } +#endif /* not defined XML_CONTEXT_BYTES */ + else { + memcpy(XML_GetBuffer(parser, len), s, len); + return XML_ParseBuffer(parser, len, isFinal); + } +} + +int XML_ParseBuffer(XML_Parser parser, int len, int isFinal) +{ + const char *start = bufferPtr; + positionPtr = start; + bufferEnd += len; + parseEndByteIndex += len; + errorCode = processor(parser, start, parseEndPtr = bufferEnd, + isFinal ? (const char **)0 : &bufferPtr); + if (errorCode == XML_ERROR_NONE) { + if (!isFinal) + XmlUpdatePosition(encoding, positionPtr, bufferPtr, &position); + return 1; + } + else { + eventEndPtr = eventPtr; + processor = errorProcessor; + return 0; + } +} + +void *XML_GetBuffer(XML_Parser parser, int len) +{ + if (len > bufferLim - bufferEnd) { + /* FIXME avoid integer overflow */ + int neededSize = len + (bufferEnd - bufferPtr); +#ifdef XML_CONTEXT_BYTES + int keep = bufferPtr - buffer; + + if (keep > XML_CONTEXT_BYTES) + keep = XML_CONTEXT_BYTES; + neededSize += keep; +#endif /* defined XML_CONTEXT_BYTES */ + if (neededSize <= bufferLim - buffer) { +#ifdef XML_CONTEXT_BYTES + if (keep < bufferPtr - buffer) { + int offset = (bufferPtr - buffer) - keep; + memmove(buffer, &buffer[offset], bufferEnd - bufferPtr + keep); + bufferEnd -= offset; + bufferPtr -= offset; + } +#else + memmove(buffer, bufferPtr, bufferEnd - bufferPtr); + bufferEnd = buffer + (bufferEnd - bufferPtr); + bufferPtr = buffer; +#endif /* not defined XML_CONTEXT_BYTES */ + } + else { + char *newBuf; + int bufferSize = bufferLim - bufferPtr; + if (bufferSize == 0) + bufferSize = INIT_BUFFER_SIZE; + do { + bufferSize *= 2; + } while (bufferSize < neededSize); + newBuf = MALLOC(bufferSize); + if (newBuf == 0) { + errorCode = XML_ERROR_NO_MEMORY; + return 0; + } + bufferLim = newBuf + bufferSize; +#ifdef XML_CONTEXT_BYTES + if (bufferPtr) { + int keep = bufferPtr - buffer; + if (keep > XML_CONTEXT_BYTES) + keep = XML_CONTEXT_BYTES; + memcpy(newBuf, &bufferPtr[-keep], bufferEnd - bufferPtr + keep); + FREE(buffer); + buffer = newBuf; + bufferEnd = buffer + (bufferEnd - bufferPtr) + keep; + bufferPtr = buffer + keep; + } + else { + bufferEnd = newBuf + (bufferEnd - bufferPtr); + bufferPtr = buffer = newBuf; + } +#else + if (bufferPtr) { + memcpy(newBuf, bufferPtr, bufferEnd - bufferPtr); + FREE(buffer); + } + bufferEnd = newBuf + (bufferEnd - bufferPtr); + bufferPtr = buffer = newBuf; +#endif /* not defined XML_CONTEXT_BYTES */ + } + } + return bufferEnd; +} + +enum XML_Error XML_GetErrorCode(XML_Parser parser) +{ + return errorCode; +} + +long XML_GetCurrentByteIndex(XML_Parser parser) +{ + if (eventPtr) + return parseEndByteIndex - (parseEndPtr - eventPtr); + return -1; +} + +int XML_GetCurrentByteCount(XML_Parser parser) +{ + if (eventEndPtr && eventPtr) + return eventEndPtr - eventPtr; + return 0; +} + +const char * XML_GetInputContext(XML_Parser parser, int *offset, int *size) +{ +#ifdef XML_CONTEXT_BYTES + if (eventPtr && buffer) { + *offset = eventPtr - buffer; + *size = bufferEnd - buffer; + return buffer; + } +#endif /* defined XML_CONTEXT_BYTES */ + return (char *) 0; +} + +int XML_GetCurrentLineNumber(XML_Parser parser) +{ + if (eventPtr) { + XmlUpdatePosition(encoding, positionPtr, eventPtr, &position); + positionPtr = eventPtr; + } + return position.lineNumber + 1; +} + +int XML_GetCurrentColumnNumber(XML_Parser parser) +{ + if (eventPtr) { + XmlUpdatePosition(encoding, positionPtr, eventPtr, &position); + positionPtr = eventPtr; + } + return position.columnNumber; +} + +void XML_DefaultCurrent(XML_Parser parser) +{ + if (defaultHandler) { + if (openInternalEntities) + reportDefault(parser, + internalEncoding, + openInternalEntities->internalEventPtr, + openInternalEntities->internalEventEndPtr); + else + reportDefault(parser, encoding, eventPtr, eventEndPtr); + } +} + +const XML_LChar *XML_ErrorString(int code) +{ + static const XML_LChar *message[] = { + 0, + XML_T("out of memory"), + XML_T("syntax error"), + XML_T("no element found"), + XML_T("not well-formed"), + XML_T("unclosed token"), + XML_T("unclosed token"), + XML_T("mismatched tag"), + XML_T("duplicate attribute"), + XML_T("junk after document element"), + XML_T("illegal parameter entity reference"), + XML_T("undefined entity"), + XML_T("recursive entity reference"), + XML_T("asynchronous entity"), + XML_T("reference to invalid character number"), + XML_T("reference to binary entity"), + XML_T("reference to external entity in attribute"), + XML_T("xml processing instruction not at start of external entity"), + XML_T("unknown encoding"), + XML_T("encoding specified in XML declaration is incorrect"), + XML_T("unclosed CDATA section"), + XML_T("error in processing external entity reference"), + XML_T("document is not standalone") + }; + if (code > 0 && code < sizeof(message)/sizeof(message[0])) + return message[code]; + return 0; +} + +const XML_LChar * +XML_ExpatVersion() { + return VERSION; +} + +static +enum XML_Error contentProcessor(XML_Parser parser, + const char *start, + const char *end, + const char **endPtr) +{ + return doContent(parser, 0, encoding, start, end, endPtr); +} + +static +enum XML_Error externalEntityInitProcessor(XML_Parser parser, + const char *start, + const char *end, + const char **endPtr) +{ + enum XML_Error result = initializeEncoding(parser); + if (result != XML_ERROR_NONE) + return result; + processor = externalEntityInitProcessor2; + return externalEntityInitProcessor2(parser, start, end, endPtr); +} + +static +enum XML_Error externalEntityInitProcessor2(XML_Parser parser, + const char *start, + const char *end, + const char **endPtr) +{ + const char *next; + int tok = XmlContentTok(encoding, start, end, &next); + switch (tok) { + case XML_TOK_BOM: + start = next; + break; + case XML_TOK_PARTIAL: + if (endPtr) { + *endPtr = start; + return XML_ERROR_NONE; + } + eventPtr = start; + return XML_ERROR_UNCLOSED_TOKEN; + case XML_TOK_PARTIAL_CHAR: + if (endPtr) { + *endPtr = start; + return XML_ERROR_NONE; + } + eventPtr = start; + return XML_ERROR_PARTIAL_CHAR; + } + processor = externalEntityInitProcessor3; + return externalEntityInitProcessor3(parser, start, end, endPtr); +} + +static +enum XML_Error externalEntityInitProcessor3(XML_Parser parser, + const char *start, + const char *end, + const char **endPtr) +{ + const char *next; + int tok = XmlContentTok(encoding, start, end, &next); + switch (tok) { + case XML_TOK_XML_DECL: + { + enum XML_Error result = processXmlDecl(parser, 1, start, next); + if (result != XML_ERROR_NONE) + return result; + start = next; + } + break; + case XML_TOK_PARTIAL: + if (endPtr) { + *endPtr = start; + return XML_ERROR_NONE; + } + eventPtr = start; + return XML_ERROR_UNCLOSED_TOKEN; + case XML_TOK_PARTIAL_CHAR: + if (endPtr) { + *endPtr = start; + return XML_ERROR_NONE; + } + eventPtr = start; + return XML_ERROR_PARTIAL_CHAR; + } + processor = externalEntityContentProcessor; + tagLevel = 1; + return doContent(parser, 1, encoding, start, end, endPtr); +} + +static +enum XML_Error externalEntityContentProcessor(XML_Parser parser, + const char *start, + const char *end, + const char **endPtr) +{ + return doContent(parser, 1, encoding, start, end, endPtr); +} + +static enum XML_Error +doContent(XML_Parser parser, + int startTagLevel, + const ENCODING *enc, + const char *s, + const char *end, + const char **nextPtr) +{ + const char **eventPP; + const char **eventEndPP; + if (enc == encoding) { + eventPP = &eventPtr; + eventEndPP = &eventEndPtr; + } + else { + eventPP = &(openInternalEntities->internalEventPtr); + eventEndPP = &(openInternalEntities->internalEventEndPtr); + } + *eventPP = s; + for (;;) { + const char *next = s; /* XmlContentTok doesn't always set the last arg */ + int tok = XmlContentTok(enc, s, end, &next); + *eventEndPP = next; + switch (tok) { + case XML_TOK_TRAILING_CR: + if (nextPtr) { + *nextPtr = s; + return XML_ERROR_NONE; + } + *eventEndPP = end; + if (characterDataHandler) { + XML_Char c = 0xA; + characterDataHandler(handlerArg, &c, 1); + } + else if (defaultHandler) + reportDefault(parser, enc, s, end); + if (startTagLevel == 0) + return XML_ERROR_NO_ELEMENTS; + if (tagLevel != startTagLevel) + return XML_ERROR_ASYNC_ENTITY; + return XML_ERROR_NONE; + case XML_TOK_NONE: + if (nextPtr) { + *nextPtr = s; + return XML_ERROR_NONE; + } + if (startTagLevel > 0) { + if (tagLevel != startTagLevel) + return XML_ERROR_ASYNC_ENTITY; + return XML_ERROR_NONE; + } + return XML_ERROR_NO_ELEMENTS; + case XML_TOK_INVALID: + *eventPP = next; + return XML_ERROR_INVALID_TOKEN; + case XML_TOK_PARTIAL: + if (nextPtr) { + *nextPtr = s; + return XML_ERROR_NONE; + } + return XML_ERROR_UNCLOSED_TOKEN; + case XML_TOK_PARTIAL_CHAR: + if (nextPtr) { + *nextPtr = s; + return XML_ERROR_NONE; + } + return XML_ERROR_PARTIAL_CHAR; + case XML_TOK_ENTITY_REF: + { + const XML_Char *name; + ENTITY *entity; + XML_Char ch = XmlPredefinedEntityName(enc, + s + enc->minBytesPerChar, + next - enc->minBytesPerChar); + if (ch) { + if (characterDataHandler) + characterDataHandler(handlerArg, &ch, 1); + else if (defaultHandler) + reportDefault(parser, enc, s, next); + break; + } + name = poolStoreString(&dtd.pool, enc, + s + enc->minBytesPerChar, + next - enc->minBytesPerChar); + if (!name) + return XML_ERROR_NO_MEMORY; + entity = (ENTITY *)lookup(&dtd.generalEntities, name, 0); + poolDiscard(&dtd.pool); + if (!entity) { + if (dtd.complete || dtd.standalone) + return XML_ERROR_UNDEFINED_ENTITY; + if (defaultHandler) + reportDefault(parser, enc, s, next); + break; + } + if (entity->open) + return XML_ERROR_RECURSIVE_ENTITY_REF; + if (entity->notation) + return XML_ERROR_BINARY_ENTITY_REF; + if (entity) { + if (entity->textPtr) { + enum XML_Error result; + OPEN_INTERNAL_ENTITY openEntity; + if (defaultHandler && !defaultExpandInternalEntities) { + reportDefault(parser, enc, s, next); + break; + } + entity->open = 1; + openEntity.next = openInternalEntities; + openInternalEntities = &openEntity; + openEntity.entity = entity; + openEntity.internalEventPtr = 0; + openEntity.internalEventEndPtr = 0; + result = doContent(parser, + tagLevel, + internalEncoding, + (char *)entity->textPtr, + (char *)(entity->textPtr + entity->textLen), + 0); + entity->open = 0; + openInternalEntities = openEntity.next; + if (result) + return result; + } + else if (externalEntityRefHandler) { + const XML_Char *context; + entity->open = 1; + context = getContext(parser); + entity->open = 0; + if (!context) + return XML_ERROR_NO_MEMORY; + if (!externalEntityRefHandler(externalEntityRefHandlerArg, + context, + entity->base, + entity->systemId, + entity->publicId)) + return XML_ERROR_EXTERNAL_ENTITY_HANDLING; + poolDiscard(&tempPool); + } + else if (defaultHandler) + reportDefault(parser, enc, s, next); + } + break; + } + case XML_TOK_START_TAG_WITH_ATTS: + if (!startElementHandler) { + enum XML_Error result = storeAtts(parser, enc, s, 0, 0); + if (result) + return result; + } + /* fall through */ + case XML_TOK_START_TAG_NO_ATTS: + { + TAG *tag; + if (freeTagList) { + tag = freeTagList; + freeTagList = freeTagList->parent; + } + else { + tag = MALLOC(sizeof(TAG)); + if (!tag) + return XML_ERROR_NO_MEMORY; + tag->buf = MALLOC(INIT_TAG_BUF_SIZE); + if (!tag->buf) + return XML_ERROR_NO_MEMORY; + tag->bufEnd = tag->buf + INIT_TAG_BUF_SIZE; + } + tag->bindings = 0; + tag->parent = tagStack; + tagStack = tag; + tag->name.localPart = 0; + tag->rawName = s + enc->minBytesPerChar; + tag->rawNameLength = XmlNameLength(enc, tag->rawName); + if (nextPtr) { + /* Need to guarantee that: + tag->buf + ROUND_UP(tag->rawNameLength, sizeof(XML_Char)) <= tag->bufEnd - sizeof(XML_Char) */ + if (tag->rawNameLength + (int)(sizeof(XML_Char) - 1) + (int)sizeof(XML_Char) > tag->bufEnd - tag->buf) { + int bufSize = tag->rawNameLength * 4; + bufSize = ROUND_UP(bufSize, sizeof(XML_Char)); + tag->buf = REALLOC(tag->buf, bufSize); + if (!tag->buf) + return XML_ERROR_NO_MEMORY; + tag->bufEnd = tag->buf + bufSize; + } + memcpy(tag->buf, tag->rawName, tag->rawNameLength); + tag->rawName = tag->buf; + } + ++tagLevel; + if (startElementHandler) { + enum XML_Error result; + XML_Char *toPtr; + for (;;) { + const char *rawNameEnd = tag->rawName + tag->rawNameLength; + const char *fromPtr = tag->rawName; + int bufSize; + if (nextPtr) + toPtr = (XML_Char *)(tag->buf + ROUND_UP(tag->rawNameLength, sizeof(XML_Char))); + else + toPtr = (XML_Char *)tag->buf; + tag->name.str = toPtr; + XmlConvert(enc, + &fromPtr, rawNameEnd, + (ICHAR **)&toPtr, (ICHAR *)tag->bufEnd - 1); + if (fromPtr == rawNameEnd) + break; + bufSize = (tag->bufEnd - tag->buf) << 1; + tag->buf = REALLOC(tag->buf, bufSize); + if (!tag->buf) + return XML_ERROR_NO_MEMORY; + tag->bufEnd = tag->buf + bufSize; + if (nextPtr) + tag->rawName = tag->buf; + } + *toPtr = XML_T('\0'); + result = storeAtts(parser, enc, s, &(tag->name), &(tag->bindings)); + if (result) + return result; + startElementHandler(handlerArg, tag->name.str, (const XML_Char **)atts); + poolClear(&tempPool); + } + else { + tag->name.str = 0; + if (defaultHandler) + reportDefault(parser, enc, s, next); + } + break; + } + case XML_TOK_EMPTY_ELEMENT_WITH_ATTS: + if (!startElementHandler) { + enum XML_Error result = storeAtts(parser, enc, s, 0, 0); + if (result) + return result; + } + /* fall through */ + case XML_TOK_EMPTY_ELEMENT_NO_ATTS: + if (startElementHandler || endElementHandler) { + const char *rawName = s + enc->minBytesPerChar; + enum XML_Error result; + BINDING *bindings = 0; + TAG_NAME name; + name.str = poolStoreString(&tempPool, enc, rawName, + rawName + XmlNameLength(enc, rawName)); + if (!name.str) + return XML_ERROR_NO_MEMORY; + poolFinish(&tempPool); + result = storeAtts(parser, enc, s, &name, &bindings); + if (result) + return result; + poolFinish(&tempPool); + if (startElementHandler) + startElementHandler(handlerArg, name.str, (const XML_Char **)atts); + if (endElementHandler) { + if (startElementHandler) + *eventPP = *eventEndPP; + endElementHandler(handlerArg, name.str); + } + poolClear(&tempPool); + while (bindings) { + BINDING *b = bindings; + if (endNamespaceDeclHandler) + endNamespaceDeclHandler(handlerArg, b->prefix->name); + bindings = bindings->nextTagBinding; + b->nextTagBinding = freeBindingList; + freeBindingList = b; + b->prefix->binding = b->prevPrefixBinding; + } + } + else if (defaultHandler) + reportDefault(parser, enc, s, next); + if (tagLevel == 0) + return epilogProcessor(parser, next, end, nextPtr); + break; + case XML_TOK_END_TAG: + if (tagLevel == startTagLevel) + return XML_ERROR_ASYNC_ENTITY; + else { + int len; + const char *rawName; + TAG *tag = tagStack; + tagStack = tag->parent; + tag->parent = freeTagList; + freeTagList = tag; + rawName = s + enc->minBytesPerChar*2; + len = XmlNameLength(enc, rawName); + if (len != tag->rawNameLength + || memcmp(tag->rawName, rawName, len) != 0) { + *eventPP = rawName; + return XML_ERROR_TAG_MISMATCH; + } + --tagLevel; + if (endElementHandler && tag->name.str) { + if (tag->name.localPart) { + XML_Char *to = (XML_Char *)tag->name.str + tag->name.uriLen; + const XML_Char *from = tag->name.localPart; + while ((*to++ = *from++) != 0) + ; + } + endElementHandler(handlerArg, tag->name.str); + } + else if (defaultHandler) + reportDefault(parser, enc, s, next); + while (tag->bindings) { + BINDING *b = tag->bindings; + if (endNamespaceDeclHandler) + endNamespaceDeclHandler(handlerArg, b->prefix->name); + tag->bindings = tag->bindings->nextTagBinding; + b->nextTagBinding = freeBindingList; + freeBindingList = b; + b->prefix->binding = b->prevPrefixBinding; + } + if (tagLevel == 0) + return epilogProcessor(parser, next, end, nextPtr); + } + break; + case XML_TOK_CHAR_REF: + { + int n = XmlCharRefNumber(enc, s); + if (n < 0) + return XML_ERROR_BAD_CHAR_REF; + if (characterDataHandler) { + XML_Char buf[XML_ENCODE_MAX]; + characterDataHandler(handlerArg, buf, XmlEncode(n, (ICHAR *)buf)); + } + else if (defaultHandler) + reportDefault(parser, enc, s, next); + } + break; + case XML_TOK_XML_DECL: + return XML_ERROR_MISPLACED_XML_PI; + case XML_TOK_DATA_NEWLINE: + if (characterDataHandler) { + XML_Char c = 0xA; + characterDataHandler(handlerArg, &c, 1); + } + else if (defaultHandler) + reportDefault(parser, enc, s, next); + break; + case XML_TOK_CDATA_SECT_OPEN: + { + enum XML_Error result; + if (startCdataSectionHandler) + startCdataSectionHandler(handlerArg); +#if 0 + /* Suppose you doing a transformation on a document that involves + changing only the character data. You set up a defaultHandler + and a characterDataHandler. The defaultHandler simply copies + characters through. The characterDataHandler does the transformation + and writes the characters out escaping them as necessary. This case + will fail to work if we leave out the following two lines (because & + and < inside CDATA sections will be incorrectly escaped). + + However, now we have a start/endCdataSectionHandler, so it seems + easier to let the user deal with this. */ + + else if (characterDataHandler) + characterDataHandler(handlerArg, dataBuf, 0); +#endif + else if (defaultHandler) + reportDefault(parser, enc, s, next); + result = doCdataSection(parser, enc, &next, end, nextPtr); + if (!next) { + processor = cdataSectionProcessor; + return result; + } + } + break; + case XML_TOK_TRAILING_RSQB: + if (nextPtr) { + *nextPtr = s; + return XML_ERROR_NONE; + } + if (characterDataHandler) { + if (MUST_CONVERT(enc, s)) { + ICHAR *dataPtr = (ICHAR *)dataBuf; + XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)dataBufEnd); + characterDataHandler(handlerArg, dataBuf, dataPtr - (ICHAR *)dataBuf); + } + else + characterDataHandler(handlerArg, + (XML_Char *)s, + (XML_Char *)end - (XML_Char *)s); + } + else if (defaultHandler) + reportDefault(parser, enc, s, end); + if (startTagLevel == 0) { + *eventPP = end; + return XML_ERROR_NO_ELEMENTS; + } + if (tagLevel != startTagLevel) { + *eventPP = end; + return XML_ERROR_ASYNC_ENTITY; + } + return XML_ERROR_NONE; + case XML_TOK_DATA_CHARS: + if (characterDataHandler) { + if (MUST_CONVERT(enc, s)) { + for (;;) { + ICHAR *dataPtr = (ICHAR *)dataBuf; + XmlConvert(enc, &s, next, &dataPtr, (ICHAR *)dataBufEnd); + *eventEndPP = s; + characterDataHandler(handlerArg, dataBuf, dataPtr - (ICHAR *)dataBuf); + if (s == next) + break; + *eventPP = s; + } + } + else + characterDataHandler(handlerArg, + (XML_Char *)s, + (XML_Char *)next - (XML_Char *)s); + } + else if (defaultHandler) + reportDefault(parser, enc, s, next); + break; + case XML_TOK_PI: + if (!reportProcessingInstruction(parser, enc, s, next)) + return XML_ERROR_NO_MEMORY; + break; + case XML_TOK_COMMENT: + if (!reportComment(parser, enc, s, next)) + return XML_ERROR_NO_MEMORY; + break; + default: + if (defaultHandler) + reportDefault(parser, enc, s, next); + break; + } + *eventPP = s = next; + } + /* not reached */ +} + +/* If tagNamePtr is non-null, build a real list of attributes, +otherwise just check the attributes for well-formedness. */ + +static enum XML_Error storeAtts(XML_Parser parser, const ENCODING *enc, + const char *attStr, TAG_NAME *tagNamePtr, + BINDING **bindingsPtr) +{ + ELEMENT_TYPE *elementType = 0; + int nDefaultAtts = 0; + const XML_Char **appAtts; /* the attribute list to pass to the application */ + int attIndex = 0; + int i; + int n; + int nPrefixes = 0; + BINDING *binding; + const XML_Char *localPart; + + /* lookup the element type name */ + if (tagNamePtr) { + elementType = (ELEMENT_TYPE *)lookup(&dtd.elementTypes, tagNamePtr->str,0); + if (!elementType) { + tagNamePtr->str = poolCopyString(&dtd.pool, tagNamePtr->str); + if (!tagNamePtr->str) + return XML_ERROR_NO_MEMORY; + elementType = (ELEMENT_TYPE *)lookup(&dtd.elementTypes, tagNamePtr->str, sizeof(ELEMENT_TYPE)); + if (!elementType) + return XML_ERROR_NO_MEMORY; + if (ns && !setElementTypePrefix(parser, elementType)) + return XML_ERROR_NO_MEMORY; + } + nDefaultAtts = elementType->nDefaultAtts; + } + /* get the attributes from the tokenizer */ + n = XmlGetAttributes(enc, attStr, attsSize, atts); + if (n + nDefaultAtts > attsSize) { + int oldAttsSize = attsSize; + attsSize = n + nDefaultAtts + INIT_ATTS_SIZE; + atts = REALLOC((void *)atts, attsSize * sizeof(ATTRIBUTE)); + if (!atts) + return XML_ERROR_NO_MEMORY; + if (n > oldAttsSize) + XmlGetAttributes(enc, attStr, n, atts); + } + appAtts = (const XML_Char **)atts; + for (i = 0; i < n; i++) { + /* add the name and value to the attribute list */ + ATTRIBUTE_ID *attId = getAttributeId(parser, enc, atts[i].name, + atts[i].name + + XmlNameLength(enc, atts[i].name)); + if (!attId) + return XML_ERROR_NO_MEMORY; + /* detect duplicate attributes */ + if ((attId->name)[-1]) { + if (enc == encoding) + eventPtr = atts[i].name; + return XML_ERROR_DUPLICATE_ATTRIBUTE; + } + (attId->name)[-1] = 1; + appAtts[attIndex++] = attId->name; + if (!atts[i].normalized) { + enum XML_Error result; + int isCdata = 1; + + /* figure out whether declared as other than CDATA */ + if (attId->maybeTokenized) { + int j; + for (j = 0; j < nDefaultAtts; j++) { + if (attId == elementType->defaultAtts[j].id) { + isCdata = elementType->defaultAtts[j].isCdata; + break; + } + } + } + + /* normalize the attribute value */ + result = storeAttributeValue(parser, enc, isCdata, + atts[i].valuePtr, atts[i].valueEnd, + &tempPool); + if (result) + return result; + if (tagNamePtr) { + appAtts[attIndex] = poolStart(&tempPool); + poolFinish(&tempPool); + } + else + poolDiscard(&tempPool); + } + else if (tagNamePtr) { + /* the value did not need normalizing */ + appAtts[attIndex] = poolStoreString(&tempPool, enc, atts[i].valuePtr, atts[i].valueEnd); + if (appAtts[attIndex] == 0) + return XML_ERROR_NO_MEMORY; + poolFinish(&tempPool); + } + /* handle prefixed attribute names */ + if (attId->prefix && tagNamePtr) { + if (attId->xmlns) { + /* deal with namespace declarations here */ + if (!addBinding(parser, attId->prefix, attId, appAtts[attIndex], bindingsPtr)) + return XML_ERROR_NO_MEMORY; + --attIndex; + } + else { + /* deal with other prefixed names later */ + attIndex++; + nPrefixes++; + (attId->name)[-1] = 2; + } + } + else + attIndex++; + } + if (tagNamePtr) { + int j; + nSpecifiedAtts = attIndex; + if (elementType->idAtt && (elementType->idAtt->name)[-1]) { + for (i = 0; i < attIndex; i += 2) + if (appAtts[i] == elementType->idAtt->name) { + idAttIndex = i; + break; + } + } + else + idAttIndex = -1; + /* do attribute defaulting */ + for (j = 0; j < nDefaultAtts; j++) { + const DEFAULT_ATTRIBUTE *da = elementType->defaultAtts + j; + if (!(da->id->name)[-1] && da->value) { + if (da->id->prefix) { + if (da->id->xmlns) { + if (!addBinding(parser, da->id->prefix, da->id, da->value, bindingsPtr)) + return XML_ERROR_NO_MEMORY; + } + else { + (da->id->name)[-1] = 2; + nPrefixes++; + appAtts[attIndex++] = da->id->name; + appAtts[attIndex++] = da->value; + } + } + else { + (da->id->name)[-1] = 1; + appAtts[attIndex++] = da->id->name; + appAtts[attIndex++] = da->value; + } + } + } + appAtts[attIndex] = 0; + } + i = 0; + if (nPrefixes) { + /* expand prefixed attribute names */ + for (; i < attIndex; i += 2) { + if (appAtts[i][-1] == 2) { + ATTRIBUTE_ID *id; + ((XML_Char *)(appAtts[i]))[-1] = 0; + id = (ATTRIBUTE_ID *)lookup(&dtd.attributeIds, appAtts[i], 0); + if (id->prefix->binding) { + int j; + const BINDING *b = id->prefix->binding; + const XML_Char *s = appAtts[i]; + for (j = 0; j < b->uriLen; j++) { + if (!poolAppendChar(&tempPool, b->uri[j])) + return XML_ERROR_NO_MEMORY; + } + while (*s++ != ':') + ; + do { + if (!poolAppendChar(&tempPool, *s)) + return XML_ERROR_NO_MEMORY; + } while (*s++); + if (ns_triplets) { + tempPool.ptr[-1] = namespaceSeparator; + s = b->prefix->name; + do { + if (!poolAppendChar(&tempPool, *s)) + return XML_ERROR_NO_MEMORY; + } while (*s++); + } + + appAtts[i] = poolStart(&tempPool); + poolFinish(&tempPool); + } + if (!--nPrefixes) + break; + } + else + ((XML_Char *)(appAtts[i]))[-1] = 0; + } + } + /* clear the flags that say whether attributes were specified */ + for (; i < attIndex; i += 2) + ((XML_Char *)(appAtts[i]))[-1] = 0; + if (!tagNamePtr) + return XML_ERROR_NONE; + for (binding = *bindingsPtr; binding; binding = binding->nextTagBinding) + binding->attId->name[-1] = 0; + /* expand the element type name */ + if (elementType->prefix) { + binding = elementType->prefix->binding; + if (!binding) + return XML_ERROR_NONE; + localPart = tagNamePtr->str; + while (*localPart++ != XML_T(':')) + ; + } + else if (dtd.defaultPrefix.binding) { + binding = dtd.defaultPrefix.binding; + localPart = tagNamePtr->str; + } + else + return XML_ERROR_NONE; + tagNamePtr->localPart = localPart; + tagNamePtr->uriLen = binding->uriLen; + for (i = 0; localPart[i++];) + ; + n = i + binding->uriLen; + if (n > binding->uriAlloc) { + TAG *p; + XML_Char *uri = MALLOC((n + EXPAND_SPARE) * sizeof(XML_Char)); + if (!uri) + return XML_ERROR_NO_MEMORY; + binding->uriAlloc = n + EXPAND_SPARE; + memcpy(uri, binding->uri, binding->uriLen * sizeof(XML_Char)); + for (p = tagStack; p; p = p->parent) + if (p->name.str == binding->uri) + p->name.str = uri; + FREE(binding->uri); + binding->uri = uri; + } + memcpy(binding->uri + binding->uriLen, localPart, i * sizeof(XML_Char)); + tagNamePtr->str = binding->uri; + return XML_ERROR_NONE; +} + +static +int addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId, const XML_Char *uri, BINDING **bindingsPtr) +{ + BINDING *b; + int len; + for (len = 0; uri[len]; len++) + ; + if (namespaceSeparator) + len++; + if (freeBindingList) { + b = freeBindingList; + if (len > b->uriAlloc) { + b->uri = REALLOC(b->uri, sizeof(XML_Char) * (len + EXPAND_SPARE)); + if (!b->uri) + return 0; + b->uriAlloc = len + EXPAND_SPARE; + } + freeBindingList = b->nextTagBinding; + } + else { + b = MALLOC(sizeof(BINDING)); + if (!b) + return 0; + b->uri = MALLOC(sizeof(XML_Char) * (len + EXPAND_SPARE)); + if (!b->uri) { + FREE(b); + return 0; + } + b->uriAlloc = len + EXPAND_SPARE; + } + b->uriLen = len; + memcpy(b->uri, uri, len * sizeof(XML_Char)); + if (namespaceSeparator) + b->uri[len - 1] = namespaceSeparator; + b->prefix = prefix; + b->attId = attId; + b->prevPrefixBinding = prefix->binding; + if (*uri == XML_T('\0') && prefix == &dtd.defaultPrefix) + prefix->binding = 0; + else + prefix->binding = b; + b->nextTagBinding = *bindingsPtr; + *bindingsPtr = b; + if (startNamespaceDeclHandler) + startNamespaceDeclHandler(handlerArg, prefix->name, + prefix->binding ? uri : 0); + return 1; +} + +/* The idea here is to avoid using stack for each CDATA section when +the whole file is parsed with one call. */ + +static +enum XML_Error cdataSectionProcessor(XML_Parser parser, + const char *start, + const char *end, + const char **endPtr) +{ + enum XML_Error result = doCdataSection(parser, encoding, &start, end, endPtr); + if (start) { + processor = contentProcessor; + return contentProcessor(parser, start, end, endPtr); + } + return result; +} + +/* startPtr gets set to non-null is the section is closed, and to null if +the section is not yet closed. */ + +static +enum XML_Error doCdataSection(XML_Parser parser, + const ENCODING *enc, + const char **startPtr, + const char *end, + const char **nextPtr) +{ + const char *s = *startPtr; + const char **eventPP; + const char **eventEndPP; + if (enc == encoding) { + eventPP = &eventPtr; + *eventPP = s; + eventEndPP = &eventEndPtr; + } + else { + eventPP = &(openInternalEntities->internalEventPtr); + eventEndPP = &(openInternalEntities->internalEventEndPtr); + } + *eventPP = s; + *startPtr = 0; + for (;;) { + const char *next; + int tok = XmlCdataSectionTok(enc, s, end, &next); + *eventEndPP = next; + switch (tok) { + case XML_TOK_CDATA_SECT_CLOSE: + if (endCdataSectionHandler) + endCdataSectionHandler(handlerArg); +#if 0 + /* see comment under XML_TOK_CDATA_SECT_OPEN */ + else if (characterDataHandler) + characterDataHandler(handlerArg, dataBuf, 0); +#endif + else if (defaultHandler) + reportDefault(parser, enc, s, next); + *startPtr = next; + return XML_ERROR_NONE; + case XML_TOK_DATA_NEWLINE: + if (characterDataHandler) { + XML_Char c = 0xA; + characterDataHandler(handlerArg, &c, 1); + } + else if (defaultHandler) + reportDefault(parser, enc, s, next); + break; + case XML_TOK_DATA_CHARS: + if (characterDataHandler) { + if (MUST_CONVERT(enc, s)) { + for (;;) { + ICHAR *dataPtr = (ICHAR *)dataBuf; + XmlConvert(enc, &s, next, &dataPtr, (ICHAR *)dataBufEnd); + *eventEndPP = next; + characterDataHandler(handlerArg, dataBuf, dataPtr - (ICHAR *)dataBuf); + if (s == next) + break; + *eventPP = s; + } + } + else + characterDataHandler(handlerArg, + (XML_Char *)s, + (XML_Char *)next - (XML_Char *)s); + } + else if (defaultHandler) + reportDefault(parser, enc, s, next); + break; + case XML_TOK_INVALID: + *eventPP = next; + return XML_ERROR_INVALID_TOKEN; + case XML_TOK_PARTIAL_CHAR: + if (nextPtr) { + *nextPtr = s; + return XML_ERROR_NONE; + } + return XML_ERROR_PARTIAL_CHAR; + case XML_TOK_PARTIAL: + case XML_TOK_NONE: + if (nextPtr) { + *nextPtr = s; + return XML_ERROR_NONE; + } + return XML_ERROR_UNCLOSED_CDATA_SECTION; + default: + abort(); + } + *eventPP = s = next; + } + /* not reached */ +} + +#ifdef XML_DTD + +/* The idea here is to avoid using stack for each IGNORE section when +the whole file is parsed with one call. */ + +static +enum XML_Error ignoreSectionProcessor(XML_Parser parser, + const char *start, + const char *end, + const char **endPtr) +{ + enum XML_Error result = doIgnoreSection(parser, encoding, &start, end, endPtr); + if (start) { + processor = prologProcessor; + return prologProcessor(parser, start, end, endPtr); + } + return result; +} + +/* startPtr gets set to non-null is the section is closed, and to null if +the section is not yet closed. */ + +static +enum XML_Error doIgnoreSection(XML_Parser parser, + const ENCODING *enc, + const char **startPtr, + const char *end, + const char **nextPtr) +{ + const char *next; + int tok; + const char *s = *startPtr; + const char **eventPP; + const char **eventEndPP; + if (enc == encoding) { + eventPP = &eventPtr; + *eventPP = s; + eventEndPP = &eventEndPtr; + } + else { + eventPP = &(openInternalEntities->internalEventPtr); + eventEndPP = &(openInternalEntities->internalEventEndPtr); + } + *eventPP = s; + *startPtr = 0; + tok = XmlIgnoreSectionTok(enc, s, end, &next); + *eventEndPP = next; + switch (tok) { + case XML_TOK_IGNORE_SECT: + if (defaultHandler) + reportDefault(parser, enc, s, next); + *startPtr = next; + return XML_ERROR_NONE; + case XML_TOK_INVALID: + *eventPP = next; + return XML_ERROR_INVALID_TOKEN; + case XML_TOK_PARTIAL_CHAR: + if (nextPtr) { + *nextPtr = s; + return XML_ERROR_NONE; + } + return XML_ERROR_PARTIAL_CHAR; + case XML_TOK_PARTIAL: + case XML_TOK_NONE: + if (nextPtr) { + *nextPtr = s; + return XML_ERROR_NONE; + } + return XML_ERROR_SYNTAX; /* XML_ERROR_UNCLOSED_IGNORE_SECTION */ + default: + abort(); + } + /* not reached */ +} + +#endif /* XML_DTD */ + +static enum XML_Error +initializeEncoding(XML_Parser parser) +{ + const char *s; +#ifdef XML_UNICODE + char encodingBuf[128]; + if (!protocolEncodingName) + s = 0; + else { + int i; + for (i = 0; protocolEncodingName[i]; i++) { + if (i == sizeof(encodingBuf) - 1 + || (protocolEncodingName[i] & ~0x7f) != 0) { + encodingBuf[0] = '\0'; + break; + } + encodingBuf[i] = (char)protocolEncodingName[i]; + } + encodingBuf[i] = '\0'; + s = encodingBuf; + } +#else + s = protocolEncodingName; +#endif + if ((ns ? XmlInitEncodingNS : XmlInitEncoding)(&initEncoding, &encoding, s)) + return XML_ERROR_NONE; + return handleUnknownEncoding(parser, protocolEncodingName); +} + +static enum XML_Error +processXmlDecl(XML_Parser parser, int isGeneralTextEntity, + const char *s, const char *next) +{ + const char *encodingName = 0; + const char *storedEncName = 0; + const ENCODING *newEncoding = 0; + const char *version = 0; + const char *versionend; + const char *storedversion = 0; + int standalone = -1; + if (!(ns + ? XmlParseXmlDeclNS + : XmlParseXmlDecl)(isGeneralTextEntity, + encoding, + s, + next, + &eventPtr, + &version, + &versionend, + &encodingName, + &newEncoding, + &standalone)) + return XML_ERROR_SYNTAX; + if (!isGeneralTextEntity && standalone == 1) { + dtd.standalone = 1; +#ifdef XML_DTD + if (paramEntityParsing == XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE) + paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER; +#endif /* XML_DTD */ + } + if (xmlDeclHandler) { + if (encodingName) { + storedEncName = poolStoreString(&temp2Pool, + encoding, + encodingName, + encodingName + + XmlNameLength(encoding, encodingName)); + if (! storedEncName) + return XML_ERROR_NO_MEMORY; + poolFinish(&temp2Pool); + } + if (version) { + storedversion = poolStoreString(&temp2Pool, + encoding, + version, + versionend - encoding->minBytesPerChar); + if (! storedversion) + return XML_ERROR_NO_MEMORY; + } + xmlDeclHandler(handlerArg, storedversion, storedEncName, standalone); + } + else if (defaultHandler) + reportDefault(parser, encoding, s, next); + if (!protocolEncodingName) { + if (newEncoding) { + if (newEncoding->minBytesPerChar != encoding->minBytesPerChar) { + eventPtr = encodingName; + return XML_ERROR_INCORRECT_ENCODING; + } + encoding = newEncoding; + } + else if (encodingName) { + enum XML_Error result; + if (! storedEncName) { + storedEncName = poolStoreString(&temp2Pool, + encoding, + encodingName, + encodingName + + XmlNameLength(encoding, encodingName)); + if (! storedEncName) + return XML_ERROR_NO_MEMORY; + } + result = handleUnknownEncoding(parser, storedEncName); + poolClear(&tempPool); + if (result == XML_ERROR_UNKNOWN_ENCODING) + eventPtr = encodingName; + return result; + } + } + + if (storedEncName || storedversion) + poolClear(&temp2Pool); + + return XML_ERROR_NONE; +} + +static enum XML_Error +handleUnknownEncoding(XML_Parser parser, const XML_Char *encodingName) +{ + if (unknownEncodingHandler) { + XML_Encoding info; + int i; + for (i = 0; i < 256; i++) + info.map[i] = -1; + info.convert = 0; + info.data = 0; + info.release = 0; + if (unknownEncodingHandler(unknownEncodingHandlerData, encodingName, &info)) { + ENCODING *enc; + unknownEncodingMem = MALLOC(XmlSizeOfUnknownEncoding()); + if (!unknownEncodingMem) { + if (info.release) + info.release(info.data); + return XML_ERROR_NO_MEMORY; + } + enc = (ns + ? XmlInitUnknownEncodingNS + : XmlInitUnknownEncoding)(unknownEncodingMem, + info.map, + info.convert, + info.data); + if (enc) { + unknownEncodingData = info.data; + unknownEncodingRelease = info.release; + encoding = enc; + return XML_ERROR_NONE; + } + } + if (info.release) + info.release(info.data); + } + return XML_ERROR_UNKNOWN_ENCODING; +} + +static enum XML_Error +prologInitProcessor(XML_Parser parser, + const char *s, + const char *end, + const char **nextPtr) +{ + enum XML_Error result = initializeEncoding(parser); + if (result != XML_ERROR_NONE) + return result; + processor = prologProcessor; + return prologProcessor(parser, s, end, nextPtr); +} + +static enum XML_Error +prologProcessor(XML_Parser parser, + const char *s, + const char *end, + const char **nextPtr) +{ + const char *next; + int tok = XmlPrologTok(encoding, s, end, &next); + return doProlog(parser, encoding, s, end, tok, next, nextPtr); +} + +static enum XML_Error +doProlog(XML_Parser parser, + const ENCODING *enc, + const char *s, + const char *end, + int tok, + const char *next, + const char **nextPtr) +{ +#ifdef XML_DTD + static const XML_Char externalSubsetName[] = { '#' , '\0' }; +#endif /* XML_DTD */ + + const char **eventPP; + const char **eventEndPP; + enum XML_Content_Quant quant; + + if (enc == encoding) { + eventPP = &eventPtr; + eventEndPP = &eventEndPtr; + } + else { + eventPP = &(openInternalEntities->internalEventPtr); + eventEndPP = &(openInternalEntities->internalEventEndPtr); + } + for (;;) { + int role; + *eventPP = s; + *eventEndPP = next; + if (tok <= 0) { + if (nextPtr != 0 && tok != XML_TOK_INVALID) { + *nextPtr = s; + return XML_ERROR_NONE; + } + switch (tok) { + case XML_TOK_INVALID: + *eventPP = next; + return XML_ERROR_INVALID_TOKEN; + case XML_TOK_PARTIAL: + return XML_ERROR_UNCLOSED_TOKEN; + case XML_TOK_PARTIAL_CHAR: + return XML_ERROR_PARTIAL_CHAR; + case XML_TOK_NONE: +#ifdef XML_DTD + if (enc != encoding) + return XML_ERROR_NONE; + if (parentParser) { + if (XmlTokenRole(&prologState, XML_TOK_NONE, end, end, enc) + == XML_ROLE_ERROR) + return XML_ERROR_SYNTAX; + hadExternalDoctype = 0; + return XML_ERROR_NONE; + } +#endif /* XML_DTD */ + return XML_ERROR_NO_ELEMENTS; + default: + tok = -tok; + next = end; + break; + } + } + role = XmlTokenRole(&prologState, tok, s, next, enc); + switch (role) { + case XML_ROLE_XML_DECL: + { + enum XML_Error result = processXmlDecl(parser, 0, s, next); + if (result != XML_ERROR_NONE) + return result; + enc = encoding; + } + break; + case XML_ROLE_DOCTYPE_NAME: + if (startDoctypeDeclHandler) { + doctypeName = poolStoreString(&tempPool, enc, s, next); + if (! doctypeName) + return XML_ERROR_NO_MEMORY; + poolFinish(&tempPool); + doctypeSysid = 0; + doctypePubid = 0; + } + break; + case XML_ROLE_DOCTYPE_INTERNAL_SUBSET: + if (startDoctypeDeclHandler) { + startDoctypeDeclHandler(handlerArg, doctypeName, doctypeSysid, + doctypePubid, 1); + doctypeName = 0; + poolClear(&tempPool); + } + break; +#ifdef XML_DTD + case XML_ROLE_TEXT_DECL: + { + enum XML_Error result = processXmlDecl(parser, 1, s, next); + if (result != XML_ERROR_NONE) + return result; + enc = encoding; + } + break; +#endif /* XML_DTD */ + case XML_ROLE_DOCTYPE_PUBLIC_ID: + if (startDoctypeDeclHandler) { + doctypePubid = poolStoreString(&tempPool, enc, s + 1, next - 1); + if (! doctypePubid) + return XML_ERROR_NO_MEMORY; + poolFinish(&tempPool); + } +#ifdef XML_DTD + declEntity = (ENTITY *)lookup(&dtd.paramEntities, + externalSubsetName, + sizeof(ENTITY)); + if (!declEntity) + return XML_ERROR_NO_MEMORY; +#endif /* XML_DTD */ + /* fall through */ + case XML_ROLE_ENTITY_PUBLIC_ID: + if (!XmlIsPublicId(enc, s, next, eventPP)) + return XML_ERROR_SYNTAX; + if (declEntity) { + XML_Char *tem = poolStoreString(&dtd.pool, + enc, + s + enc->minBytesPerChar, + next - enc->minBytesPerChar); + if (!tem) + return XML_ERROR_NO_MEMORY; + normalizePublicId(tem); + declEntity->publicId = tem; + poolFinish(&dtd.pool); + } + break; + case XML_ROLE_DOCTYPE_CLOSE: + if (doctypeName) { + startDoctypeDeclHandler(handlerArg, doctypeName, + doctypeSysid, doctypePubid, 0); + poolClear(&tempPool); + } + if (dtd.complete && hadExternalDoctype) { + dtd.complete = 0; +#ifdef XML_DTD + if (paramEntityParsing && externalEntityRefHandler) { + ENTITY *entity = (ENTITY *)lookup(&dtd.paramEntities, + externalSubsetName, + 0); + if (!externalEntityRefHandler(externalEntityRefHandlerArg, + 0, + entity->base, + entity->systemId, + entity->publicId)) + return XML_ERROR_EXTERNAL_ENTITY_HANDLING; + } +#endif /* XML_DTD */ + if (!dtd.complete + && !dtd.standalone + && notStandaloneHandler + && !notStandaloneHandler(handlerArg)) + return XML_ERROR_NOT_STANDALONE; + } + if (endDoctypeDeclHandler) + endDoctypeDeclHandler(handlerArg); + break; + case XML_ROLE_INSTANCE_START: + processor = contentProcessor; + return contentProcessor(parser, s, end, nextPtr); + case XML_ROLE_ATTLIST_ELEMENT_NAME: + declElementType = getElementType(parser, enc, s, next); + if (!declElementType) + return XML_ERROR_NO_MEMORY; + break; + case XML_ROLE_ATTRIBUTE_NAME: + declAttributeId = getAttributeId(parser, enc, s, next); + if (!declAttributeId) + return XML_ERROR_NO_MEMORY; + declAttributeIsCdata = 0; + declAttributeType = 0; + declAttributeIsId = 0; + break; + case XML_ROLE_ATTRIBUTE_TYPE_CDATA: + declAttributeIsCdata = 1; + declAttributeType = "CDATA"; + break; + case XML_ROLE_ATTRIBUTE_TYPE_ID: + declAttributeIsId = 1; + declAttributeType = "ID"; + break; + case XML_ROLE_ATTRIBUTE_TYPE_IDREF: + declAttributeType = "IDREF"; + break; + case XML_ROLE_ATTRIBUTE_TYPE_IDREFS: + declAttributeType = "IDREFS"; + break; + case XML_ROLE_ATTRIBUTE_TYPE_ENTITY: + declAttributeType = "ENTITY"; + break; + case XML_ROLE_ATTRIBUTE_TYPE_ENTITIES: + declAttributeType = "ENTITIES"; + break; + case XML_ROLE_ATTRIBUTE_TYPE_NMTOKEN: + declAttributeType = "NMTOKEN"; + break; + case XML_ROLE_ATTRIBUTE_TYPE_NMTOKENS: + declAttributeType = "NMTOKENS"; + break; + + case XML_ROLE_ATTRIBUTE_ENUM_VALUE: + case XML_ROLE_ATTRIBUTE_NOTATION_VALUE: + if (attlistDeclHandler) + { + char *prefix; + if (declAttributeType) { + prefix = "|"; + } + else { + prefix = (role == XML_ROLE_ATTRIBUTE_NOTATION_VALUE + ? "NOTATION(" + : "("); + } + if (! poolAppendString(&tempPool, prefix)) + return XML_ERROR_NO_MEMORY; + if (! poolAppend(&tempPool, enc, s, next)) + return XML_ERROR_NO_MEMORY; + declAttributeType = tempPool.start; + } + break; + case XML_ROLE_IMPLIED_ATTRIBUTE_VALUE: + case XML_ROLE_REQUIRED_ATTRIBUTE_VALUE: + if (dtd.complete + && !defineAttribute(declElementType, declAttributeId, + declAttributeIsCdata, declAttributeIsId, 0, + parser)) + return XML_ERROR_NO_MEMORY; + if (attlistDeclHandler && declAttributeType) { + if (*declAttributeType == '(' + || *declAttributeType == 'N' && declAttributeType[1] == 'O') { + /* Enumerated or Notation type */ + if (! poolAppendChar(&tempPool, ')') + || ! poolAppendChar(&tempPool, '\0')) + return XML_ERROR_NO_MEMORY; + declAttributeType = tempPool.start; + poolFinish(&tempPool); + } + *eventEndPP = s; + attlistDeclHandler(handlerArg, declElementType->name, + declAttributeId->name, declAttributeType, + 0, role == XML_ROLE_REQUIRED_ATTRIBUTE_VALUE); + poolClear(&tempPool); + } + break; + case XML_ROLE_DEFAULT_ATTRIBUTE_VALUE: + case XML_ROLE_FIXED_ATTRIBUTE_VALUE: + { + const XML_Char *attVal; + enum XML_Error result + = storeAttributeValue(parser, enc, declAttributeIsCdata, + s + enc->minBytesPerChar, + next - enc->minBytesPerChar, + &dtd.pool); + if (result) + return result; + attVal = poolStart(&dtd.pool); + poolFinish(&dtd.pool); + if (dtd.complete + /* ID attributes aren't allowed to have a default */ + && !defineAttribute(declElementType, declAttributeId, declAttributeIsCdata, 0, attVal, parser)) + return XML_ERROR_NO_MEMORY; + if (attlistDeclHandler && declAttributeType) { + if (*declAttributeType == '(' + || *declAttributeType == 'N' && declAttributeType[1] == 'O') { + /* Enumerated or Notation type */ + if (! poolAppendChar(&tempPool, ')') + || ! poolAppendChar(&tempPool, '\0')) + return XML_ERROR_NO_MEMORY; + declAttributeType = tempPool.start; + poolFinish(&tempPool); + } + *eventEndPP = s; + attlistDeclHandler(handlerArg, declElementType->name, + declAttributeId->name, declAttributeType, + attVal, + role == XML_ROLE_FIXED_ATTRIBUTE_VALUE); + poolClear(&tempPool); + } + break; + } + case XML_ROLE_ENTITY_VALUE: + { + enum XML_Error result = storeEntityValue(parser, enc, + s + enc->minBytesPerChar, + next - enc->minBytesPerChar); + if (declEntity) { + declEntity->textPtr = poolStart(&dtd.pool); + declEntity->textLen = poolLength(&dtd.pool); + poolFinish(&dtd.pool); + if (entityDeclHandler) { + *eventEndPP = s; + entityDeclHandler(handlerArg, + declEntity->name, + declEntity->is_param, + declEntity->textPtr, + declEntity->textLen, + curBase, 0, 0, 0); + } + } + else + poolDiscard(&dtd.pool); + if (result != XML_ERROR_NONE) + return result; + } + break; + case XML_ROLE_DOCTYPE_SYSTEM_ID: + if (startDoctypeDeclHandler) { + doctypeSysid = poolStoreString(&tempPool, enc, s + 1, next - 1); + if (! doctypeSysid) + return XML_ERROR_NO_MEMORY; + poolFinish(&tempPool); + } + if (!dtd.standalone +#ifdef XML_DTD + && !paramEntityParsing +#endif /* XML_DTD */ + && notStandaloneHandler + && !notStandaloneHandler(handlerArg)) + return XML_ERROR_NOT_STANDALONE; + hadExternalDoctype = 1; +#ifndef XML_DTD + break; +#else /* XML_DTD */ + if (!declEntity) { + declEntity = (ENTITY *)lookup(&dtd.paramEntities, + externalSubsetName, + sizeof(ENTITY)); + declEntity->publicId = 0; + if (!declEntity) + return XML_ERROR_NO_MEMORY; + } + /* fall through */ +#endif /* XML_DTD */ + case XML_ROLE_ENTITY_SYSTEM_ID: + if (declEntity) { + declEntity->systemId = poolStoreString(&dtd.pool, enc, + s + enc->minBytesPerChar, + next - enc->minBytesPerChar); + if (!declEntity->systemId) + return XML_ERROR_NO_MEMORY; + declEntity->base = curBase; + poolFinish(&dtd.pool); + } + break; + case XML_ROLE_ENTITY_COMPLETE: + if (declEntity && entityDeclHandler) { + *eventEndPP = s; + entityDeclHandler(handlerArg, + declEntity->name, + 0,0,0, + declEntity->base, + declEntity->systemId, + declEntity->publicId, + 0); + } + break; + case XML_ROLE_ENTITY_NOTATION_NAME: + if (declEntity) { + declEntity->notation = poolStoreString(&dtd.pool, enc, s, next); + if (!declEntity->notation) + return XML_ERROR_NO_MEMORY; + poolFinish(&dtd.pool); + if (unparsedEntityDeclHandler) { + *eventEndPP = s; + unparsedEntityDeclHandler(handlerArg, + declEntity->name, + declEntity->base, + declEntity->systemId, + declEntity->publicId, + declEntity->notation); + } + else if (entityDeclHandler) { + *eventEndPP = s; + entityDeclHandler(handlerArg, + declEntity->name, + 0,0,0, + declEntity->base, + declEntity->systemId, + declEntity->publicId, + declEntity->notation); + } + } + break; + case XML_ROLE_GENERAL_ENTITY_NAME: + { + const XML_Char *name; + if (XmlPredefinedEntityName(enc, s, next)) { + declEntity = 0; + break; + } + name = poolStoreString(&dtd.pool, enc, s, next); + if (!name) + return XML_ERROR_NO_MEMORY; + if (dtd.complete) { + declEntity = (ENTITY *)lookup(&dtd.generalEntities, name, sizeof(ENTITY)); + if (!declEntity) + return XML_ERROR_NO_MEMORY; + if (declEntity->name != name) { + poolDiscard(&dtd.pool); + declEntity = 0; + } + else { + poolFinish(&dtd.pool); + declEntity->publicId = 0; + declEntity->is_param = 0; + } + } + else { + poolDiscard(&dtd.pool); + declEntity = 0; + } + } + break; + case XML_ROLE_PARAM_ENTITY_NAME: +#ifdef XML_DTD + if (dtd.complete) { + const XML_Char *name = poolStoreString(&dtd.pool, enc, s, next); + if (!name) + return XML_ERROR_NO_MEMORY; + declEntity = (ENTITY *)lookup(&dtd.paramEntities, + name, sizeof(ENTITY)); + if (!declEntity) + return XML_ERROR_NO_MEMORY; + if (declEntity->name != name) { + poolDiscard(&dtd.pool); + declEntity = 0; + } + else { + poolFinish(&dtd.pool); + declEntity->publicId = 0; + declEntity->is_param = 1; + } + } +#else /* not XML_DTD */ + declEntity = 0; +#endif /* not XML_DTD */ + break; + case XML_ROLE_NOTATION_NAME: + declNotationPublicId = 0; + declNotationName = 0; + if (notationDeclHandler) { + declNotationName = poolStoreString(&tempPool, enc, s, next); + if (!declNotationName) + return XML_ERROR_NO_MEMORY; + poolFinish(&tempPool); + } + break; + case XML_ROLE_NOTATION_PUBLIC_ID: + if (!XmlIsPublicId(enc, s, next, eventPP)) + return XML_ERROR_SYNTAX; + if (declNotationName) { + XML_Char *tem = poolStoreString(&tempPool, + enc, + s + enc->minBytesPerChar, + next - enc->minBytesPerChar); + if (!tem) + return XML_ERROR_NO_MEMORY; + normalizePublicId(tem); + declNotationPublicId = tem; + poolFinish(&tempPool); + } + break; + case XML_ROLE_NOTATION_SYSTEM_ID: + if (declNotationName && notationDeclHandler) { + const XML_Char *systemId + = poolStoreString(&tempPool, enc, + s + enc->minBytesPerChar, + next - enc->minBytesPerChar); + if (!systemId) + return XML_ERROR_NO_MEMORY; + *eventEndPP = s; + notationDeclHandler(handlerArg, + declNotationName, + curBase, + systemId, + declNotationPublicId); + } + poolClear(&tempPool); + break; + case XML_ROLE_NOTATION_NO_SYSTEM_ID: + if (declNotationPublicId && notationDeclHandler) { + *eventEndPP = s; + notationDeclHandler(handlerArg, + declNotationName, + curBase, + 0, + declNotationPublicId); + } + poolClear(&tempPool); + break; + case XML_ROLE_ERROR: + switch (tok) { + case XML_TOK_PARAM_ENTITY_REF: + return XML_ERROR_PARAM_ENTITY_REF; + case XML_TOK_XML_DECL: + return XML_ERROR_MISPLACED_XML_PI; + default: + return XML_ERROR_SYNTAX; + } +#ifdef XML_DTD + case XML_ROLE_IGNORE_SECT: + { + enum XML_Error result; + if (defaultHandler) + reportDefault(parser, enc, s, next); + result = doIgnoreSection(parser, enc, &next, end, nextPtr); + if (!next) { + processor = ignoreSectionProcessor; + return result; + } + } + break; +#endif /* XML_DTD */ + case XML_ROLE_GROUP_OPEN: + if (prologState.level >= groupSize) { + if (groupSize) { + groupConnector = REALLOC(groupConnector, groupSize *= 2); + if (dtd.scaffIndex) + dtd.scaffIndex = REALLOC(dtd.scaffIndex, groupSize * sizeof(int)); + } + else + groupConnector = MALLOC(groupSize = 32); + if (!groupConnector) + return XML_ERROR_NO_MEMORY; + } + groupConnector[prologState.level] = 0; + if (dtd.in_eldecl) { + int myindex = nextScaffoldPart(parser); + if (myindex < 0) + return XML_ERROR_NO_MEMORY; + dtd.scaffIndex[dtd.scaffLevel] = myindex; + dtd.scaffLevel++; + dtd.scaffold[myindex].type = XML_CTYPE_SEQ; + } + break; + case XML_ROLE_GROUP_SEQUENCE: + if (groupConnector[prologState.level] == '|') + return XML_ERROR_SYNTAX; + groupConnector[prologState.level] = ','; + break; + case XML_ROLE_GROUP_CHOICE: + if (groupConnector[prologState.level] == ',') + return XML_ERROR_SYNTAX; + if (dtd.in_eldecl + && ! groupConnector[prologState.level] + && dtd.scaffold[dtd.scaffIndex[dtd.scaffLevel - 1]].type != XML_CTYPE_MIXED + ) { + dtd.scaffold[dtd.scaffIndex[dtd.scaffLevel - 1]].type = XML_CTYPE_CHOICE; + } + groupConnector[prologState.level] = '|'; + break; + case XML_ROLE_PARAM_ENTITY_REF: +#ifdef XML_DTD + case XML_ROLE_INNER_PARAM_ENTITY_REF: + if (paramEntityParsing + && (dtd.complete || role == XML_ROLE_INNER_PARAM_ENTITY_REF)) { + const XML_Char *name; + ENTITY *entity; + name = poolStoreString(&dtd.pool, enc, + s + enc->minBytesPerChar, + next - enc->minBytesPerChar); + if (!name) + return XML_ERROR_NO_MEMORY; + entity = (ENTITY *)lookup(&dtd.paramEntities, name, 0); + poolDiscard(&dtd.pool); + if (!entity) { + /* FIXME what to do if !dtd.complete? */ + return XML_ERROR_UNDEFINED_ENTITY; + } + if (entity->open) + return XML_ERROR_RECURSIVE_ENTITY_REF; + if (entity->textPtr) { + enum XML_Error result; + result = processInternalParamEntity(parser, entity); + if (result != XML_ERROR_NONE) + return result; + break; + } + if (role == XML_ROLE_INNER_PARAM_ENTITY_REF) + return XML_ERROR_PARAM_ENTITY_REF; + if (externalEntityRefHandler) { + dtd.complete = 0; + entity->open = 1; + if (!externalEntityRefHandler(externalEntityRefHandlerArg, + 0, + entity->base, + entity->systemId, + entity->publicId)) { + entity->open = 0; + return XML_ERROR_EXTERNAL_ENTITY_HANDLING; + } + entity->open = 0; + if (dtd.complete) + break; + } + } +#endif /* XML_DTD */ + if (!dtd.standalone + && notStandaloneHandler + && !notStandaloneHandler(handlerArg)) + return XML_ERROR_NOT_STANDALONE; + dtd.complete = 0; + if (defaultHandler) + reportDefault(parser, enc, s, next); + break; + + /* Element declaration stuff */ + + case XML_ROLE_ELEMENT_NAME: + if (elementDeclHandler) { + declElementType = getElementType(parser, enc, s, next); + if (! declElementType) + return XML_ERROR_NO_MEMORY; + dtd.scaffLevel = 0; + dtd.scaffCount = 0; + dtd.in_eldecl = 1; + } + break; + + case XML_ROLE_CONTENT_ANY: + case XML_ROLE_CONTENT_EMPTY: + if (dtd.in_eldecl) { + if (elementDeclHandler) { + XML_Content * content = (XML_Content *) MALLOC(sizeof(XML_Content)); + if (! content) + return XML_ERROR_NO_MEMORY; + content->quant = XML_CQUANT_NONE; + content->name = 0; + content->numchildren = 0; + content->children = 0; + content->type = ((role == XML_ROLE_CONTENT_ANY) ? + XML_CTYPE_ANY : + XML_CTYPE_EMPTY); + *eventEndPP = s; + elementDeclHandler(handlerArg, declElementType->name, content); + } + dtd.in_eldecl = 0; + } + break; + + case XML_ROLE_CONTENT_PCDATA: + if (dtd.in_eldecl) { + dtd.scaffold[dtd.scaffIndex[dtd.scaffLevel - 1]].type = XML_CTYPE_MIXED; + } + break; + + case XML_ROLE_CONTENT_ELEMENT: + quant = XML_CQUANT_NONE; + goto elementContent; + case XML_ROLE_CONTENT_ELEMENT_OPT: + quant = XML_CQUANT_OPT; + goto elementContent; + case XML_ROLE_CONTENT_ELEMENT_REP: + quant = XML_CQUANT_REP; + goto elementContent; + case XML_ROLE_CONTENT_ELEMENT_PLUS: + quant = XML_CQUANT_PLUS; + elementContent: + if (dtd.in_eldecl) + { + ELEMENT_TYPE *el; + const char *nxt = quant == XML_CQUANT_NONE ? next : next - 1; + int myindex = nextScaffoldPart(parser); + if (myindex < 0) + return XML_ERROR_NO_MEMORY; + dtd.scaffold[myindex].type = XML_CTYPE_NAME; + dtd.scaffold[myindex].quant = quant; + el = getElementType(parser, enc, s, nxt); + if (! el) + return XML_ERROR_NO_MEMORY; + dtd.scaffold[myindex].name = el->name; + dtd.contentStringLen += nxt - s + 1; + } + break; + + case XML_ROLE_GROUP_CLOSE: + quant = XML_CQUANT_NONE; + goto closeGroup; + case XML_ROLE_GROUP_CLOSE_OPT: + quant = XML_CQUANT_OPT; + goto closeGroup; + case XML_ROLE_GROUP_CLOSE_REP: + quant = XML_CQUANT_REP; + goto closeGroup; + case XML_ROLE_GROUP_CLOSE_PLUS: + quant = XML_CQUANT_PLUS; + closeGroup: + if (dtd.in_eldecl) { + dtd.scaffLevel--; + dtd.scaffold[dtd.scaffIndex[dtd.scaffLevel]].quant = quant; + if (dtd.scaffLevel == 0) { + if (elementDeclHandler) { + XML_Content *model = build_model(parser); + if (! model) + return XML_ERROR_NO_MEMORY; + *eventEndPP = s; + elementDeclHandler(handlerArg, declElementType->name, model); + } + dtd.in_eldecl = 0; + dtd.contentStringLen = 0; + } + } + break; + /* End element declaration stuff */ + + case XML_ROLE_NONE: + switch (tok) { + case XML_TOK_PI: + if (!reportProcessingInstruction(parser, enc, s, next)) + return XML_ERROR_NO_MEMORY; + break; + case XML_TOK_COMMENT: + if (!reportComment(parser, enc, s, next)) + return XML_ERROR_NO_MEMORY; + break; + } + break; + } + if (defaultHandler) { + switch (tok) { + case XML_TOK_PI: + case XML_TOK_COMMENT: + case XML_TOK_BOM: + case XML_TOK_XML_DECL: +#ifdef XML_DTD + case XML_TOK_IGNORE_SECT: +#endif /* XML_DTD */ + case XML_TOK_PARAM_ENTITY_REF: + break; + default: +#ifdef XML_DTD + if (role != XML_ROLE_IGNORE_SECT) +#endif /* XML_DTD */ + reportDefault(parser, enc, s, next); + } + } + s = next; + tok = XmlPrologTok(enc, s, end, &next); + } + /* not reached */ +} + +static +enum XML_Error epilogProcessor(XML_Parser parser, + const char *s, + const char *end, + const char **nextPtr) +{ + processor = epilogProcessor; + eventPtr = s; + for (;;) { + const char *next; + int tok = XmlPrologTok(encoding, s, end, &next); + eventEndPtr = next; + switch (tok) { + case -XML_TOK_PROLOG_S: + if (defaultHandler) { + eventEndPtr = end; + reportDefault(parser, encoding, s, end); + } + /* fall through */ + case XML_TOK_NONE: + if (nextPtr) + *nextPtr = end; + return XML_ERROR_NONE; + case XML_TOK_PROLOG_S: + if (defaultHandler) + reportDefault(parser, encoding, s, next); + break; + case XML_TOK_PI: + if (!reportProcessingInstruction(parser, encoding, s, next)) + return XML_ERROR_NO_MEMORY; + break; + case XML_TOK_COMMENT: + if (!reportComment(parser, encoding, s, next)) + return XML_ERROR_NO_MEMORY; + break; + case XML_TOK_INVALID: + eventPtr = next; + return XML_ERROR_INVALID_TOKEN; + case XML_TOK_PARTIAL: + if (nextPtr) { + *nextPtr = s; + return XML_ERROR_NONE; + } + return XML_ERROR_UNCLOSED_TOKEN; + case XML_TOK_PARTIAL_CHAR: + if (nextPtr) { + *nextPtr = s; + return XML_ERROR_NONE; + } + return XML_ERROR_PARTIAL_CHAR; + default: + return XML_ERROR_JUNK_AFTER_DOC_ELEMENT; + } + eventPtr = s = next; + } +} + +#ifdef XML_DTD + +static enum XML_Error +processInternalParamEntity(XML_Parser parser, ENTITY *entity) +{ + const char *s, *end, *next; + int tok; + enum XML_Error result; + OPEN_INTERNAL_ENTITY openEntity; + entity->open = 1; + openEntity.next = openInternalEntities; + openInternalEntities = &openEntity; + openEntity.entity = entity; + openEntity.internalEventPtr = 0; + openEntity.internalEventEndPtr = 0; + s = (char *)entity->textPtr; + end = (char *)(entity->textPtr + entity->textLen); + tok = XmlPrologTok(internalEncoding, s, end, &next); + result = doProlog(parser, internalEncoding, s, end, tok, next, 0); + entity->open = 0; + openInternalEntities = openEntity.next; + return result; +} + +#endif /* XML_DTD */ + +static +enum XML_Error errorProcessor(XML_Parser parser, + const char *s, + const char *end, + const char **nextPtr) +{ + return errorCode; +} + +static enum XML_Error +storeAttributeValue(XML_Parser parser, const ENCODING *enc, int isCdata, + const char *ptr, const char *end, + STRING_POOL *pool) +{ + enum XML_Error result = appendAttributeValue(parser, enc, isCdata, ptr, end, pool); + if (result) + return result; + if (!isCdata && poolLength(pool) && poolLastChar(pool) == 0x20) + poolChop(pool); + if (!poolAppendChar(pool, XML_T('\0'))) + return XML_ERROR_NO_MEMORY; + return XML_ERROR_NONE; +} + +static enum XML_Error +appendAttributeValue(XML_Parser parser, const ENCODING *enc, int isCdata, + const char *ptr, const char *end, + STRING_POOL *pool) +{ + for (;;) { + const char *next; + int tok = XmlAttributeValueTok(enc, ptr, end, &next); + switch (tok) { + case XML_TOK_NONE: + return XML_ERROR_NONE; + case XML_TOK_INVALID: + if (enc == encoding) + eventPtr = next; + return XML_ERROR_INVALID_TOKEN; + case XML_TOK_PARTIAL: + if (enc == encoding) + eventPtr = ptr; + return XML_ERROR_INVALID_TOKEN; + case XML_TOK_CHAR_REF: + { + XML_Char buf[XML_ENCODE_MAX]; + int i; + int n = XmlCharRefNumber(enc, ptr); + if (n < 0) { + if (enc == encoding) + eventPtr = ptr; + return XML_ERROR_BAD_CHAR_REF; + } + if (!isCdata + && n == 0x20 /* space */ + && (poolLength(pool) == 0 || poolLastChar(pool) == 0x20)) + break; + n = XmlEncode(n, (ICHAR *)buf); + if (!n) { + if (enc == encoding) + eventPtr = ptr; + return XML_ERROR_BAD_CHAR_REF; + } + for (i = 0; i < n; i++) { + if (!poolAppendChar(pool, buf[i])) + return XML_ERROR_NO_MEMORY; + } + } + break; + case XML_TOK_DATA_CHARS: + if (!poolAppend(pool, enc, ptr, next)) + return XML_ERROR_NO_MEMORY; + break; + break; + case XML_TOK_TRAILING_CR: + next = ptr + enc->minBytesPerChar; + /* fall through */ + case XML_TOK_ATTRIBUTE_VALUE_S: + case XML_TOK_DATA_NEWLINE: + if (!isCdata && (poolLength(pool) == 0 || poolLastChar(pool) == 0x20)) + break; + if (!poolAppendChar(pool, 0x20)) + return XML_ERROR_NO_MEMORY; + break; + case XML_TOK_ENTITY_REF: + { + const XML_Char *name; + ENTITY *entity; + XML_Char ch = XmlPredefinedEntityName(enc, + ptr + enc->minBytesPerChar, + next - enc->minBytesPerChar); + if (ch) { + if (!poolAppendChar(pool, ch)) + return XML_ERROR_NO_MEMORY; + break; + } + name = poolStoreString(&temp2Pool, enc, + ptr + enc->minBytesPerChar, + next - enc->minBytesPerChar); + if (!name) + return XML_ERROR_NO_MEMORY; + entity = (ENTITY *)lookup(&dtd.generalEntities, name, 0); + poolDiscard(&temp2Pool); + if (!entity) { + if (dtd.complete) { + if (enc == encoding) + eventPtr = ptr; + return XML_ERROR_UNDEFINED_ENTITY; + } + } + else if (entity->open) { + if (enc == encoding) + eventPtr = ptr; + return XML_ERROR_RECURSIVE_ENTITY_REF; + } + else if (entity->notation) { + if (enc == encoding) + eventPtr = ptr; + return XML_ERROR_BINARY_ENTITY_REF; + } + else if (!entity->textPtr) { + if (enc == encoding) + eventPtr = ptr; + return XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF; + } + else { + enum XML_Error result; + const XML_Char *textEnd = entity->textPtr + entity->textLen; + entity->open = 1; + result = appendAttributeValue(parser, internalEncoding, isCdata, (char *)entity->textPtr, (char *)textEnd, pool); + entity->open = 0; + if (result) + return result; + } + } + break; + default: + abort(); + } + ptr = next; + } + /* not reached */ +} + +static +enum XML_Error storeEntityValue(XML_Parser parser, + const ENCODING *enc, + const char *entityTextPtr, + const char *entityTextEnd) +{ + STRING_POOL *pool = &(dtd.pool); + for (;;) { + const char *next; + int tok = XmlEntityValueTok(enc, entityTextPtr, entityTextEnd, &next); + switch (tok) { + case XML_TOK_PARAM_ENTITY_REF: +#ifdef XML_DTD + if (parentParser || enc != encoding) { + enum XML_Error result; + const XML_Char *name; + ENTITY *entity; + name = poolStoreString(&tempPool, enc, + entityTextPtr + enc->minBytesPerChar, + next - enc->minBytesPerChar); + if (!name) + return XML_ERROR_NO_MEMORY; + entity = (ENTITY *)lookup(&dtd.paramEntities, name, 0); + poolDiscard(&tempPool); + if (!entity) { + if (enc == encoding) + eventPtr = entityTextPtr; + return XML_ERROR_UNDEFINED_ENTITY; + } + if (entity->open) { + if (enc == encoding) + eventPtr = entityTextPtr; + return XML_ERROR_RECURSIVE_ENTITY_REF; + } + if (entity->systemId) { + if (enc == encoding) + eventPtr = entityTextPtr; + return XML_ERROR_PARAM_ENTITY_REF; + } + entity->open = 1; + result = storeEntityValue(parser, + internalEncoding, + (char *)entity->textPtr, + (char *)(entity->textPtr + entity->textLen)); + entity->open = 0; + if (result) + return result; + break; + } +#endif /* XML_DTD */ + eventPtr = entityTextPtr; + return XML_ERROR_SYNTAX; + case XML_TOK_NONE: + return XML_ERROR_NONE; + case XML_TOK_ENTITY_REF: + case XML_TOK_DATA_CHARS: + if (!poolAppend(pool, enc, entityTextPtr, next)) + return XML_ERROR_NO_MEMORY; + break; + case XML_TOK_TRAILING_CR: + next = entityTextPtr + enc->minBytesPerChar; + /* fall through */ + case XML_TOK_DATA_NEWLINE: + if (pool->end == pool->ptr && !poolGrow(pool)) + return XML_ERROR_NO_MEMORY; + *(pool->ptr)++ = 0xA; + break; + case XML_TOK_CHAR_REF: + { + XML_Char buf[XML_ENCODE_MAX]; + int i; + int n = XmlCharRefNumber(enc, entityTextPtr); + if (n < 0) { + if (enc == encoding) + eventPtr = entityTextPtr; + return XML_ERROR_BAD_CHAR_REF; + } + n = XmlEncode(n, (ICHAR *)buf); + if (!n) { + if (enc == encoding) + eventPtr = entityTextPtr; + return XML_ERROR_BAD_CHAR_REF; + } + for (i = 0; i < n; i++) { + if (pool->end == pool->ptr && !poolGrow(pool)) + return XML_ERROR_NO_MEMORY; + *(pool->ptr)++ = buf[i]; + } + } + break; + case XML_TOK_PARTIAL: + if (enc == encoding) + eventPtr = entityTextPtr; + return XML_ERROR_INVALID_TOKEN; + case XML_TOK_INVALID: + if (enc == encoding) + eventPtr = next; + return XML_ERROR_INVALID_TOKEN; + default: + abort(); + } + entityTextPtr = next; + } + /* not reached */ +} + +static void +normalizeLines(XML_Char *s) +{ + XML_Char *p; + for (;; s++) { + if (*s == XML_T('\0')) + return; + if (*s == 0xD) + break; + } + p = s; + do { + if (*s == 0xD) { + *p++ = 0xA; + if (*++s == 0xA) + s++; + } + else + *p++ = *s++; + } while (*s); + *p = XML_T('\0'); +} + +static int +reportProcessingInstruction(XML_Parser parser, const ENCODING *enc, const char *start, const char *end) +{ + const XML_Char *target; + XML_Char *data; + const char *tem; + if (!processingInstructionHandler) { + if (defaultHandler) + reportDefault(parser, enc, start, end); + return 1; + } + start += enc->minBytesPerChar * 2; + tem = start + XmlNameLength(enc, start); + target = poolStoreString(&tempPool, enc, start, tem); + if (!target) + return 0; + poolFinish(&tempPool); + data = poolStoreString(&tempPool, enc, + XmlSkipS(enc, tem), + end - enc->minBytesPerChar*2); + if (!data) + return 0; + normalizeLines(data); + processingInstructionHandler(handlerArg, target, data); + poolClear(&tempPool); + return 1; +} + +static int +reportComment(XML_Parser parser, const ENCODING *enc, const char *start, const char *end) +{ + XML_Char *data; + if (!commentHandler) { + if (defaultHandler) + reportDefault(parser, enc, start, end); + return 1; + } + data = poolStoreString(&tempPool, + enc, + start + enc->minBytesPerChar * 4, + end - enc->minBytesPerChar * 3); + if (!data) + return 0; + normalizeLines(data); + commentHandler(handlerArg, data); + poolClear(&tempPool); + return 1; +} + +static void +reportDefault(XML_Parser parser, const ENCODING *enc, const char *s, const char *end) +{ + if (MUST_CONVERT(enc, s)) { + const char **eventPP; + const char **eventEndPP; + if (enc == encoding) { + eventPP = &eventPtr; + eventEndPP = &eventEndPtr; + } + else { + eventPP = &(openInternalEntities->internalEventPtr); + eventEndPP = &(openInternalEntities->internalEventEndPtr); + } + do { + ICHAR *dataPtr = (ICHAR *)dataBuf; + XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)dataBufEnd); + *eventEndPP = s; + defaultHandler(handlerArg, dataBuf, dataPtr - (ICHAR *)dataBuf); + *eventPP = s; + } while (s != end); + } + else + defaultHandler(handlerArg, (XML_Char *)s, (XML_Char *)end - (XML_Char *)s); +} + + +static int +defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId, int isCdata, + int isId, const XML_Char *value, XML_Parser parser) +{ + DEFAULT_ATTRIBUTE *att; + if (value || isId) { + /* The handling of default attributes gets messed up if we have + a default which duplicates a non-default. */ + int i; + for (i = 0; i < type->nDefaultAtts; i++) + if (attId == type->defaultAtts[i].id) + return 1; + if (isId && !type->idAtt && !attId->xmlns) + type->idAtt = attId; + } + if (type->nDefaultAtts == type->allocDefaultAtts) { + if (type->allocDefaultAtts == 0) { + type->allocDefaultAtts = 8; + type->defaultAtts = MALLOC(type->allocDefaultAtts*sizeof(DEFAULT_ATTRIBUTE)); + } + else { + type->allocDefaultAtts *= 2; + type->defaultAtts = REALLOC(type->defaultAtts, + type->allocDefaultAtts*sizeof(DEFAULT_ATTRIBUTE)); + } + if (!type->defaultAtts) + return 0; + } + att = type->defaultAtts + type->nDefaultAtts; + att->id = attId; + att->value = value; + att->isCdata = isCdata; + if (!isCdata) + attId->maybeTokenized = 1; + type->nDefaultAtts += 1; + return 1; +} + +static int setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *elementType) +{ + const XML_Char *name; + for (name = elementType->name; *name; name++) { + if (*name == XML_T(':')) { + PREFIX *prefix; + const XML_Char *s; + for (s = elementType->name; s != name; s++) { + if (!poolAppendChar(&dtd.pool, *s)) + return 0; + } + if (!poolAppendChar(&dtd.pool, XML_T('\0'))) + return 0; + prefix = (PREFIX *)lookup(&dtd.prefixes, poolStart(&dtd.pool), sizeof(PREFIX)); + if (!prefix) + return 0; + if (prefix->name == poolStart(&dtd.pool)) + poolFinish(&dtd.pool); + else + poolDiscard(&dtd.pool); + elementType->prefix = prefix; + + } + } + return 1; +} + +static ATTRIBUTE_ID * +getAttributeId(XML_Parser parser, const ENCODING *enc, const char *start, const char *end) +{ + ATTRIBUTE_ID *id; + const XML_Char *name; + if (!poolAppendChar(&dtd.pool, XML_T('\0'))) + return 0; + name = poolStoreString(&dtd.pool, enc, start, end); + if (!name) + return 0; + ++name; + id = (ATTRIBUTE_ID *)lookup(&dtd.attributeIds, name, sizeof(ATTRIBUTE_ID)); + if (!id) + return 0; + if (id->name != name) + poolDiscard(&dtd.pool); + else { + poolFinish(&dtd.pool); + if (!ns) + ; + else if (name[0] == 'x' + && name[1] == 'm' + && name[2] == 'l' + && name[3] == 'n' + && name[4] == 's' + && (name[5] == XML_T('\0') || name[5] == XML_T(':'))) { + if (name[5] == '\0') + id->prefix = &dtd.defaultPrefix; + else + id->prefix = (PREFIX *)lookup(&dtd.prefixes, name + 6, sizeof(PREFIX)); + id->xmlns = 1; + } + else { + int i; + for (i = 0; name[i]; i++) { + if (name[i] == XML_T(':')) { + int j; + for (j = 0; j < i; j++) { + if (!poolAppendChar(&dtd.pool, name[j])) + return 0; + } + if (!poolAppendChar(&dtd.pool, XML_T('\0'))) + return 0; + id->prefix = (PREFIX *)lookup(&dtd.prefixes, poolStart(&dtd.pool), sizeof(PREFIX)); + if (id->prefix->name == poolStart(&dtd.pool)) + poolFinish(&dtd.pool); + else + poolDiscard(&dtd.pool); + break; + } + } + } + } + return id; +} + +#define CONTEXT_SEP XML_T('\f') + +static +const XML_Char *getContext(XML_Parser parser) +{ + HASH_TABLE_ITER iter; + int needSep = 0; + + if (dtd.defaultPrefix.binding) { + int i; + int len; + if (!poolAppendChar(&tempPool, XML_T('='))) + return 0; + len = dtd.defaultPrefix.binding->uriLen; + if (namespaceSeparator != XML_T('\0')) + len--; + for (i = 0; i < len; i++) + if (!poolAppendChar(&tempPool, dtd.defaultPrefix.binding->uri[i])) + return 0; + needSep = 1; + } + + hashTableIterInit(&iter, &(dtd.prefixes)); + for (;;) { + int i; + int len; + const XML_Char *s; + PREFIX *prefix = (PREFIX *)hashTableIterNext(&iter); + if (!prefix) + break; + if (!prefix->binding) + continue; + if (needSep && !poolAppendChar(&tempPool, CONTEXT_SEP)) + return 0; + for (s = prefix->name; *s; s++) + if (!poolAppendChar(&tempPool, *s)) + return 0; + if (!poolAppendChar(&tempPool, XML_T('='))) + return 0; + len = prefix->binding->uriLen; + if (namespaceSeparator != XML_T('\0')) + len--; + for (i = 0; i < len; i++) + if (!poolAppendChar(&tempPool, prefix->binding->uri[i])) + return 0; + needSep = 1; + } + + + hashTableIterInit(&iter, &(dtd.generalEntities)); + for (;;) { + const XML_Char *s; + ENTITY *e = (ENTITY *)hashTableIterNext(&iter); + if (!e) + break; + if (!e->open) + continue; + if (needSep && !poolAppendChar(&tempPool, CONTEXT_SEP)) + return 0; + for (s = e->name; *s; s++) + if (!poolAppendChar(&tempPool, *s)) + return 0; + needSep = 1; + } + + if (!poolAppendChar(&tempPool, XML_T('\0'))) + return 0; + return tempPool.start; +} + +static +int setContext(XML_Parser parser, const XML_Char *context) +{ + const XML_Char *s = context; + + while (*context != XML_T('\0')) { + if (*s == CONTEXT_SEP || *s == XML_T('\0')) { + ENTITY *e; + if (!poolAppendChar(&tempPool, XML_T('\0'))) + return 0; + e = (ENTITY *)lookup(&dtd.generalEntities, poolStart(&tempPool), 0); + if (e) + e->open = 1; + if (*s != XML_T('\0')) + s++; + context = s; + poolDiscard(&tempPool); + } + else if (*s == '=') { + PREFIX *prefix; + if (poolLength(&tempPool) == 0) + prefix = &dtd.defaultPrefix; + else { + if (!poolAppendChar(&tempPool, XML_T('\0'))) + return 0; + prefix = (PREFIX *)lookup(&dtd.prefixes, poolStart(&tempPool), sizeof(PREFIX)); + if (!prefix) + return 0; + if (prefix->name == poolStart(&tempPool)) { + prefix->name = poolCopyString(&dtd.pool, prefix->name); + if (!prefix->name) + return 0; + } + poolDiscard(&tempPool); + } + for (context = s + 1; *context != CONTEXT_SEP && *context != XML_T('\0'); context++) + if (!poolAppendChar(&tempPool, *context)) + return 0; + if (!poolAppendChar(&tempPool, XML_T('\0'))) + return 0; + if (!addBinding(parser, prefix, 0, poolStart(&tempPool), &inheritedBindings)) + return 0; + poolDiscard(&tempPool); + if (*context != XML_T('\0')) + ++context; + s = context; + } + else { + if (!poolAppendChar(&tempPool, *s)) + return 0; + s++; + } + } + return 1; +} + + +static +void normalizePublicId(XML_Char *publicId) +{ + XML_Char *p = publicId; + XML_Char *s; + for (s = publicId; *s; s++) { + switch (*s) { + case 0x20: + case 0xD: + case 0xA: + if (p != publicId && p[-1] != 0x20) + *p++ = 0x20; + break; + default: + *p++ = *s; + } + } + if (p != publicId && p[-1] == 0x20) + --p; + *p = XML_T('\0'); +} + +static int dtdInit(DTD *p, XML_Parser parser) +{ + XML_Memory_Handling_Suite *ms = &((Parser *) parser)->m_mem; + poolInit(&(p->pool), ms); + hashTableInit(&(p->generalEntities), ms); + hashTableInit(&(p->elementTypes), ms); + hashTableInit(&(p->attributeIds), ms); + hashTableInit(&(p->prefixes), ms); + p->complete = 1; + p->standalone = 0; +#ifdef XML_DTD + hashTableInit(&(p->paramEntities), ms); +#endif /* XML_DTD */ + p->defaultPrefix.name = 0; + p->defaultPrefix.binding = 0; + + p->in_eldecl = 0; + p->scaffIndex = 0; + p->scaffLevel = 0; + p->scaffold = 0; + p->contentStringLen = 0; + p->scaffSize = 0; + p->scaffCount = 0; + + return 1; +} + +#ifdef XML_DTD + +static void dtdSwap(DTD *p1, DTD *p2) +{ + DTD tem; + memcpy(&tem, p1, sizeof(DTD)); + memcpy(p1, p2, sizeof(DTD)); + memcpy(p2, &tem, sizeof(DTD)); +} + +#endif /* XML_DTD */ + +static void dtdDestroy(DTD *p, XML_Parser parser) +{ + HASH_TABLE_ITER iter; + hashTableIterInit(&iter, &(p->elementTypes)); + for (;;) { + ELEMENT_TYPE *e = (ELEMENT_TYPE *)hashTableIterNext(&iter); + if (!e) + break; + if (e->allocDefaultAtts != 0) + FREE(e->defaultAtts); + } + hashTableDestroy(&(p->generalEntities)); +#ifdef XML_DTD + hashTableDestroy(&(p->paramEntities)); +#endif /* XML_DTD */ + hashTableDestroy(&(p->elementTypes)); + hashTableDestroy(&(p->attributeIds)); + hashTableDestroy(&(p->prefixes)); + poolDestroy(&(p->pool)); + if (p->scaffIndex) + FREE(p->scaffIndex); + if (p->scaffold) + FREE(p->scaffold); +} + +/* Do a deep copy of the DTD. Return 0 for out of memory; non-zero otherwise. +The new DTD has already been initialized. */ + +static int dtdCopy(DTD *newDtd, const DTD *oldDtd, XML_Parser parser) +{ + HASH_TABLE_ITER iter; + + /* Copy the prefix table. */ + + hashTableIterInit(&iter, &(oldDtd->prefixes)); + for (;;) { + const XML_Char *name; + const PREFIX *oldP = (PREFIX *)hashTableIterNext(&iter); + if (!oldP) + break; + name = poolCopyString(&(newDtd->pool), oldP->name); + if (!name) + return 0; + if (!lookup(&(newDtd->prefixes), name, sizeof(PREFIX))) + return 0; + } + + hashTableIterInit(&iter, &(oldDtd->attributeIds)); + + /* Copy the attribute id table. */ + + for (;;) { + ATTRIBUTE_ID *newA; + const XML_Char *name; + const ATTRIBUTE_ID *oldA = (ATTRIBUTE_ID *)hashTableIterNext(&iter); + + if (!oldA) + break; + /* Remember to allocate the scratch byte before the name. */ + if (!poolAppendChar(&(newDtd->pool), XML_T('\0'))) + return 0; + name = poolCopyString(&(newDtd->pool), oldA->name); + if (!name) + return 0; + ++name; + newA = (ATTRIBUTE_ID *)lookup(&(newDtd->attributeIds), name, sizeof(ATTRIBUTE_ID)); + if (!newA) + return 0; + newA->maybeTokenized = oldA->maybeTokenized; + if (oldA->prefix) { + newA->xmlns = oldA->xmlns; + if (oldA->prefix == &oldDtd->defaultPrefix) + newA->prefix = &newDtd->defaultPrefix; + else + newA->prefix = (PREFIX *)lookup(&(newDtd->prefixes), oldA->prefix->name, 0); + } + } + + /* Copy the element type table. */ + + hashTableIterInit(&iter, &(oldDtd->elementTypes)); + + for (;;) { + int i; + ELEMENT_TYPE *newE; + const XML_Char *name; + const ELEMENT_TYPE *oldE = (ELEMENT_TYPE *)hashTableIterNext(&iter); + if (!oldE) + break; + name = poolCopyString(&(newDtd->pool), oldE->name); + if (!name) + return 0; + newE = (ELEMENT_TYPE *)lookup(&(newDtd->elementTypes), name, sizeof(ELEMENT_TYPE)); + if (!newE) + return 0; + if (oldE->nDefaultAtts) { + newE->defaultAtts = (DEFAULT_ATTRIBUTE *)MALLOC(oldE->nDefaultAtts * sizeof(DEFAULT_ATTRIBUTE)); + if (!newE->defaultAtts) + return 0; + } + if (oldE->idAtt) + newE->idAtt = (ATTRIBUTE_ID *)lookup(&(newDtd->attributeIds), oldE->idAtt->name, 0); + newE->allocDefaultAtts = newE->nDefaultAtts = oldE->nDefaultAtts; + if (oldE->prefix) + newE->prefix = (PREFIX *)lookup(&(newDtd->prefixes), oldE->prefix->name, 0); + for (i = 0; i < newE->nDefaultAtts; i++) { + newE->defaultAtts[i].id = (ATTRIBUTE_ID *)lookup(&(newDtd->attributeIds), oldE->defaultAtts[i].id->name, 0); + newE->defaultAtts[i].isCdata = oldE->defaultAtts[i].isCdata; + if (oldE->defaultAtts[i].value) { + newE->defaultAtts[i].value = poolCopyString(&(newDtd->pool), oldE->defaultAtts[i].value); + if (!newE->defaultAtts[i].value) + return 0; + } + else + newE->defaultAtts[i].value = 0; + } + } + + /* Copy the entity tables. */ + if (!copyEntityTable(&(newDtd->generalEntities), + &(newDtd->pool), + &(oldDtd->generalEntities), parser)) + return 0; + +#ifdef XML_DTD + if (!copyEntityTable(&(newDtd->paramEntities), + &(newDtd->pool), + &(oldDtd->paramEntities), parser)) + return 0; +#endif /* XML_DTD */ + + newDtd->complete = oldDtd->complete; + newDtd->standalone = oldDtd->standalone; + + /* Don't want deep copying for scaffolding */ + newDtd->in_eldecl = oldDtd->in_eldecl; + newDtd->scaffold = oldDtd->scaffold; + newDtd->contentStringLen = oldDtd->contentStringLen; + newDtd->scaffSize = oldDtd->scaffSize; + newDtd->scaffLevel = oldDtd->scaffLevel; + newDtd->scaffIndex = oldDtd->scaffIndex; + + return 1; +} /* End dtdCopy */ + +static int copyEntityTable(HASH_TABLE *newTable, + STRING_POOL *newPool, + const HASH_TABLE *oldTable, + XML_Parser parser) +{ + HASH_TABLE_ITER iter; + const XML_Char *cachedOldBase = 0; + const XML_Char *cachedNewBase = 0; + + hashTableIterInit(&iter, oldTable); + + for (;;) { + ENTITY *newE; + const XML_Char *name; + const ENTITY *oldE = (ENTITY *)hashTableIterNext(&iter); + if (!oldE) + break; + name = poolCopyString(newPool, oldE->name); + if (!name) + return 0; + newE = (ENTITY *)lookup(newTable, name, sizeof(ENTITY)); + if (!newE) + return 0; + if (oldE->systemId) { + const XML_Char *tem = poolCopyString(newPool, oldE->systemId); + if (!tem) + return 0; + newE->systemId = tem; + if (oldE->base) { + if (oldE->base == cachedOldBase) + newE->base = cachedNewBase; + else { + cachedOldBase = oldE->base; + tem = poolCopyString(newPool, cachedOldBase); + if (!tem) + return 0; + cachedNewBase = newE->base = tem; + } + } + } + else { + const XML_Char *tem = poolCopyStringN(newPool, oldE->textPtr, oldE->textLen); + if (!tem) + return 0; + newE->textPtr = tem; + newE->textLen = oldE->textLen; + } + if (oldE->notation) { + const XML_Char *tem = poolCopyString(newPool, oldE->notation); + if (!tem) + return 0; + newE->notation = tem; + } + } + return 1; +} + +#define INIT_SIZE 64 + +static +int keyeq(KEY s1, KEY s2) +{ + for (; *s1 == *s2; s1++, s2++) + if (*s1 == 0) + return 1; + return 0; +} + +static +unsigned long hash(KEY s) +{ + unsigned long h = 0; + while (*s) + h = (h << 5) + h + (unsigned char)*s++; + return h; +} + +static +NAMED *lookup(HASH_TABLE *table, KEY name, size_t createSize) +{ + size_t i; + if (table->size == 0) { + size_t tsize; + + if (!createSize) + return 0; + tsize = INIT_SIZE * sizeof(NAMED *); + table->v = table->mem->malloc_fcn(tsize); + if (!table->v) + return 0; + memset(table->v, 0, tsize); + table->size = INIT_SIZE; + table->usedLim = INIT_SIZE / 2; + i = hash(name) & (table->size - 1); + } + else { + unsigned long h = hash(name); + for (i = h & (table->size - 1); + table->v[i]; + i == 0 ? i = table->size - 1 : --i) { + if (keyeq(name, table->v[i]->name)) + return table->v[i]; + } + if (!createSize) + return 0; + if (table->used == table->usedLim) { + /* check for overflow */ + size_t newSize = table->size * 2; + size_t tsize = newSize * sizeof(NAMED *); + NAMED **newV = table->mem->malloc_fcn(tsize); + if (!newV) + return 0; + memset(newV, 0, tsize); + for (i = 0; i < table->size; i++) + if (table->v[i]) { + size_t j; + for (j = hash(table->v[i]->name) & (newSize - 1); + newV[j]; + j == 0 ? j = newSize - 1 : --j) + ; + newV[j] = table->v[i]; + } + table->mem->free_fcn(table->v); + table->v = newV; + table->size = newSize; + table->usedLim = newSize/2; + for (i = h & (table->size - 1); + table->v[i]; + i == 0 ? i = table->size - 1 : --i) + ; + } + } + table->v[i] = table->mem->malloc_fcn(createSize); + if (!table->v[i]) + return 0; + memset(table->v[i], 0, createSize); + table->v[i]->name = name; + (table->used)++; + return table->v[i]; +} + +static +void hashTableDestroy(HASH_TABLE *table) +{ + size_t i; + for (i = 0; i < table->size; i++) { + NAMED *p = table->v[i]; + if (p) + table->mem->free_fcn(p); + } + if (table->v) + table->mem->free_fcn(table->v); +} + +static +void hashTableInit(HASH_TABLE *p, XML_Memory_Handling_Suite *ms) +{ + p->size = 0; + p->usedLim = 0; + p->used = 0; + p->v = 0; + p->mem = ms; +} + +static +void hashTableIterInit(HASH_TABLE_ITER *iter, const HASH_TABLE *table) +{ + iter->p = table->v; + iter->end = iter->p + table->size; +} + +static +NAMED *hashTableIterNext(HASH_TABLE_ITER *iter) +{ + while (iter->p != iter->end) { + NAMED *tem = *(iter->p)++; + if (tem) + return tem; + } + return 0; +} + + +static +void poolInit(STRING_POOL *pool, XML_Memory_Handling_Suite *ms) +{ + pool->blocks = 0; + pool->freeBlocks = 0; + pool->start = 0; + pool->ptr = 0; + pool->end = 0; + pool->mem = ms; +} + +static +void poolClear(STRING_POOL *pool) +{ + if (!pool->freeBlocks) + pool->freeBlocks = pool->blocks; + else { + BLOCK *p = pool->blocks; + while (p) { + BLOCK *tem = p->next; + p->next = pool->freeBlocks; + pool->freeBlocks = p; + p = tem; + } + } + pool->blocks = 0; + pool->start = 0; + pool->ptr = 0; + pool->end = 0; +} + +static +void poolDestroy(STRING_POOL *pool) +{ + BLOCK *p = pool->blocks; + while (p) { + BLOCK *tem = p->next; + pool->mem->free_fcn(p); + p = tem; + } + pool->blocks = 0; + p = pool->freeBlocks; + while (p) { + BLOCK *tem = p->next; + pool->mem->free_fcn(p); + p = tem; + } + pool->freeBlocks = 0; + pool->ptr = 0; + pool->start = 0; + pool->end = 0; +} + +static +XML_Char *poolAppend(STRING_POOL *pool, const ENCODING *enc, + const char *ptr, const char *end) +{ + if (!pool->ptr && !poolGrow(pool)) + return 0; + for (;;) { + XmlConvert(enc, &ptr, end, (ICHAR **)&(pool->ptr), (ICHAR *)pool->end); + if (ptr == end) + break; + if (!poolGrow(pool)) + return 0; + } + return pool->start; +} + +static const XML_Char *poolCopyString(STRING_POOL *pool, const XML_Char *s) +{ + do { + if (!poolAppendChar(pool, *s)) + return 0; + } while (*s++); + s = pool->start; + poolFinish(pool); + return s; +} + +static const XML_Char *poolCopyStringN(STRING_POOL *pool, const XML_Char *s, int n) +{ + if (!pool->ptr && !poolGrow(pool)) + return 0; + for (; n > 0; --n, s++) { + if (!poolAppendChar(pool, *s)) + return 0; + + } + s = pool->start; + poolFinish(pool); + return s; +} + +static +const XML_Char *poolAppendString(STRING_POOL *pool, const XML_Char *s) +{ + while (*s) { + if (!poolAppendChar(pool, *s)) + return 0; + s++; + } + return pool->start; +} /* End poolAppendString */ + +static +XML_Char *poolStoreString(STRING_POOL *pool, const ENCODING *enc, + const char *ptr, const char *end) +{ + if (!poolAppend(pool, enc, ptr, end)) + return 0; + if (pool->ptr == pool->end && !poolGrow(pool)) + return 0; + *(pool->ptr)++ = 0; + return pool->start; +} + +static +int poolGrow(STRING_POOL *pool) +{ + if (pool->freeBlocks) { + if (pool->start == 0) { + pool->blocks = pool->freeBlocks; + pool->freeBlocks = pool->freeBlocks->next; + pool->blocks->next = 0; + pool->start = pool->blocks->s; + pool->end = pool->start + pool->blocks->size; + pool->ptr = pool->start; + return 1; + } + if (pool->end - pool->start < pool->freeBlocks->size) { + BLOCK *tem = pool->freeBlocks->next; + pool->freeBlocks->next = pool->blocks; + pool->blocks = pool->freeBlocks; + pool->freeBlocks = tem; + memcpy(pool->blocks->s, pool->start, (pool->end - pool->start) * sizeof(XML_Char)); + pool->ptr = pool->blocks->s + (pool->ptr - pool->start); + pool->start = pool->blocks->s; + pool->end = pool->start + pool->blocks->size; + return 1; + } + } + if (pool->blocks && pool->start == pool->blocks->s) { + int blockSize = (pool->end - pool->start)*2; + pool->blocks = pool->mem->realloc_fcn(pool->blocks, offsetof(BLOCK, s) + blockSize * sizeof(XML_Char)); + if (!pool->blocks) + return 0; + pool->blocks->size = blockSize; + pool->ptr = pool->blocks->s + (pool->ptr - pool->start); + pool->start = pool->blocks->s; + pool->end = pool->start + blockSize; + } + else { + BLOCK *tem; + int blockSize = pool->end - pool->start; + if (blockSize < INIT_BLOCK_SIZE) + blockSize = INIT_BLOCK_SIZE; + else + blockSize *= 2; + tem = pool->mem->malloc_fcn(offsetof(BLOCK, s) + blockSize * sizeof(XML_Char)); + if (!tem) + return 0; + tem->size = blockSize; + tem->next = pool->blocks; + pool->blocks = tem; + if (pool->ptr != pool->start) + memcpy(tem->s, pool->start, (pool->ptr - pool->start) * sizeof(XML_Char)); + pool->ptr = tem->s + (pool->ptr - pool->start); + pool->start = tem->s; + pool->end = tem->s + blockSize; + } + return 1; +} + +static int +nextScaffoldPart(XML_Parser parser) +{ + CONTENT_SCAFFOLD * me; + int next; + + if (! dtd.scaffIndex) { + dtd.scaffIndex = MALLOC(groupSize * sizeof(int)); + if (! dtd.scaffIndex) + return -1; + dtd.scaffIndex[0] = 0; + } + + if (dtd.scaffCount >= dtd.scaffSize) { + if (dtd.scaffold) { + dtd.scaffSize *= 2; + dtd.scaffold = (CONTENT_SCAFFOLD *) REALLOC(dtd.scaffold, + dtd.scaffSize * sizeof(CONTENT_SCAFFOLD)); + } + else { + dtd.scaffSize = 32; + dtd.scaffold = (CONTENT_SCAFFOLD *) MALLOC(dtd.scaffSize * sizeof(CONTENT_SCAFFOLD)); + } + if (! dtd.scaffold) + return -1; + } + next = dtd.scaffCount++; + me = &dtd.scaffold[next]; + if (dtd.scaffLevel) { + CONTENT_SCAFFOLD *parent = &dtd.scaffold[dtd.scaffIndex[dtd.scaffLevel - 1]]; + if (parent->lastchild) { + dtd.scaffold[parent->lastchild].nextsib = next; + } + if (! parent->childcnt) + parent->firstchild = next; + parent->lastchild = next; + parent->childcnt++; + } + me->firstchild = me->lastchild = me->childcnt = me->nextsib = 0; + return next; +} /* End nextScaffoldPart */ + +static void +build_node (XML_Parser parser, + int src_node, + XML_Content *dest, + XML_Content **contpos, + char **strpos) +{ + dest->type = dtd.scaffold[src_node].type; + dest->quant = dtd.scaffold[src_node].quant; + if (dest->type == XML_CTYPE_NAME) { + const char *src; + dest->name = *strpos; + src = dtd.scaffold[src_node].name; + for (;;) { + *(*strpos)++ = *src; + if (! *src) + break; + src++; + } + dest->numchildren = 0; + dest->children = 0; + } + else { + int i, cn; + dest->numchildren = dtd.scaffold[src_node].childcnt; + dest->children = *contpos; + *contpos += dest->numchildren; + for (i = 0, cn = dtd.scaffold[src_node].firstchild; + i < dest->numchildren; + i++, cn = dtd.scaffold[cn].nextsib) { + build_node(parser, cn, &(dest->children[i]), contpos, strpos); + } + dest->name = 0; + } +} /* End build_node */ + +static XML_Content * +build_model (XML_Parser parser) +{ + int node; + XML_Content *ret; + XML_Content *cpos; + char * str; + int allocsize = dtd.scaffCount * sizeof(XML_Content) + dtd.contentStringLen; + + ret = MALLOC(allocsize); + if (! ret) + return 0; + + str = (char *) (&ret[dtd.scaffCount]); + cpos = &ret[1]; + + build_node(parser, 0, ret, &cpos, &str); + return ret; +} /* End build_model */ + +static ELEMENT_TYPE * +getElementType(XML_Parser parser, + const ENCODING *enc, + const char *ptr, + const char *end) +{ + const XML_Char *name = poolStoreString(&dtd.pool, enc, ptr, end); + ELEMENT_TYPE *ret; + + if (! name) + return 0; + ret = (ELEMENT_TYPE *) lookup(&dtd.elementTypes, name, sizeof(ELEMENT_TYPE)); + if (! ret) + return 0; + if (ret->name != name) + poolDiscard(&dtd.pool); + else { + poolFinish(&dtd.pool); + if (!setElementTypePrefix(parser, ret)) + return 0; + } + return ret; +} /* End getElementType */ diff --git a/Code/BF2/External/expat/xmlrole.c b/Code/BF2/External/expat/xmlrole.c new file mode 100644 index 000000000..6c3518fbd --- /dev/null +++ b/Code/BF2/External/expat/xmlrole.c @@ -0,0 +1,1270 @@ +/* +Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd +See the file COPYING for copying permission. +*/ + +static char RCSId[] + = "$Header$"; + +#include +#include "xmlrole.h" +#include "ascii.h" + +/* Doesn't check: + + that ,| are not mixed in a model group + content of literals + +*/ + +static const char KW_ANY[] = { ASCII_A, ASCII_N, ASCII_Y, '\0' }; +static const char KW_ATTLIST[] = { ASCII_A, ASCII_T, ASCII_T, ASCII_L, ASCII_I, ASCII_S, ASCII_T, '\0' }; +static const char KW_CDATA[] = { ASCII_C, ASCII_D, ASCII_A, ASCII_T, ASCII_A, '\0' }; +static const char KW_DOCTYPE[] = { ASCII_D, ASCII_O, ASCII_C, ASCII_T, ASCII_Y, ASCII_P, ASCII_E, '\0' }; +static const char KW_ELEMENT[] = { ASCII_E, ASCII_L, ASCII_E, ASCII_M, ASCII_E, ASCII_N, ASCII_T, '\0' }; +static const char KW_EMPTY[] = { ASCII_E, ASCII_M, ASCII_P, ASCII_T, ASCII_Y, '\0' }; +static const char KW_ENTITIES[] = { ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T, ASCII_I, ASCII_E, ASCII_S, '\0' }; +static const char KW_ENTITY[] = { ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T, ASCII_Y, '\0' }; +static const char KW_FIXED[] = { ASCII_F, ASCII_I, ASCII_X, ASCII_E, ASCII_D, '\0' }; +static const char KW_ID[] = { ASCII_I, ASCII_D, '\0' }; +static const char KW_IDREF[] = { ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, '\0' }; +static const char KW_IDREFS[] = { ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, ASCII_S, '\0' }; +static const char KW_IGNORE[] = { ASCII_I, ASCII_G, ASCII_N, ASCII_O, ASCII_R, ASCII_E, '\0' }; +static const char KW_IMPLIED[] = { ASCII_I, ASCII_M, ASCII_P, ASCII_L, ASCII_I, ASCII_E, ASCII_D, '\0' }; +static const char KW_INCLUDE[] = { ASCII_I, ASCII_N, ASCII_C, ASCII_L, ASCII_U, ASCII_D, ASCII_E, '\0' }; +static const char KW_NDATA[] = { ASCII_N, ASCII_D, ASCII_A, ASCII_T, ASCII_A, '\0' }; +static const char KW_NMTOKEN[] = { ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K, ASCII_E, ASCII_N, '\0' }; +static const char KW_NMTOKENS[] = { ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K, ASCII_E, ASCII_N, ASCII_S, '\0' }; +static const char KW_NOTATION[] = { ASCII_N, ASCII_O, ASCII_T, ASCII_A, ASCII_T, ASCII_I, ASCII_O, ASCII_N, '\0' }; +static const char KW_PCDATA[] = { ASCII_P, ASCII_C, ASCII_D, ASCII_A, ASCII_T, ASCII_A, '\0' }; +static const char KW_PUBLIC[] = { ASCII_P, ASCII_U, ASCII_B, ASCII_L, ASCII_I, ASCII_C, '\0' }; +static const char KW_REQUIRED[] = { ASCII_R, ASCII_E, ASCII_Q, ASCII_U, ASCII_I, ASCII_R, ASCII_E, ASCII_D, '\0' }; +static const char KW_SYSTEM[] = { ASCII_S, ASCII_Y, ASCII_S, ASCII_T, ASCII_E, ASCII_M, '\0' }; + +#ifndef MIN_BYTES_PER_CHAR +#define MIN_BYTES_PER_CHAR(enc) ((enc)->minBytesPerChar) +#endif + +#ifdef XML_DTD +#define setTopLevel(state) \ + ((state)->handler = ((state)->documentEntity \ + ? internalSubset \ + : externalSubset1)) +#else /* not XML_DTD */ +#define setTopLevel(state) ((state)->handler = internalSubset) +#endif /* not XML_DTD */ + +typedef int PROLOG_HANDLER(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc); + +static PROLOG_HANDLER + prolog0, prolog1, prolog2, + doctype0, doctype1, doctype2, doctype3, doctype4, doctype5, + internalSubset, + entity0, entity1, entity2, entity3, entity4, entity5, entity6, + entity7, entity8, entity9, + notation0, notation1, notation2, notation3, notation4, + attlist0, attlist1, attlist2, attlist3, attlist4, attlist5, attlist6, + attlist7, attlist8, attlist9, + element0, element1, element2, element3, element4, element5, element6, + element7, +#ifdef XML_DTD + externalSubset0, externalSubset1, + condSect0, condSect1, condSect2, +#endif /* XML_DTD */ + declClose, + error; + +static +int common(PROLOG_STATE *state, int tok); + +static +int prolog0(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + state->handler = prolog1; + return XML_ROLE_NONE; + case XML_TOK_XML_DECL: + state->handler = prolog1; + return XML_ROLE_XML_DECL; + case XML_TOK_PI: + state->handler = prolog1; + return XML_ROLE_NONE; + case XML_TOK_COMMENT: + state->handler = prolog1; + case XML_TOK_BOM: + return XML_ROLE_NONE; + case XML_TOK_DECL_OPEN: + if (!XmlNameMatchesAscii(enc, + ptr + 2 * MIN_BYTES_PER_CHAR(enc), + end, + KW_DOCTYPE)) + break; + state->handler = doctype0; + return XML_ROLE_NONE; + case XML_TOK_INSTANCE_START: + state->handler = error; + return XML_ROLE_INSTANCE_START; + } + return common(state, tok); +} + +static +int prolog1(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_PI: + case XML_TOK_COMMENT: + case XML_TOK_BOM: + return XML_ROLE_NONE; + case XML_TOK_DECL_OPEN: + if (!XmlNameMatchesAscii(enc, + ptr + 2 * MIN_BYTES_PER_CHAR(enc), + end, + KW_DOCTYPE)) + break; + state->handler = doctype0; + return XML_ROLE_NONE; + case XML_TOK_INSTANCE_START: + state->handler = error; + return XML_ROLE_INSTANCE_START; + } + return common(state, tok); +} + +static +int prolog2(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_PI: + case XML_TOK_COMMENT: + return XML_ROLE_NONE; + case XML_TOK_INSTANCE_START: + state->handler = error; + return XML_ROLE_INSTANCE_START; + } + return common(state, tok); +} + +static +int doctype0(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_NAME: + case XML_TOK_PREFIXED_NAME: + state->handler = doctype1; + return XML_ROLE_DOCTYPE_NAME; + } + return common(state, tok); +} + +static +int doctype1(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_OPEN_BRACKET: + state->handler = internalSubset; + return XML_ROLE_DOCTYPE_INTERNAL_SUBSET; + case XML_TOK_DECL_CLOSE: + state->handler = prolog2; + return XML_ROLE_DOCTYPE_CLOSE; + case XML_TOK_NAME: + if (XmlNameMatchesAscii(enc, ptr, end, KW_SYSTEM)) { + state->handler = doctype3; + return XML_ROLE_NONE; + } + if (XmlNameMatchesAscii(enc, ptr, end, KW_PUBLIC)) { + state->handler = doctype2; + return XML_ROLE_NONE; + } + break; + } + return common(state, tok); +} + +static +int doctype2(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_LITERAL: + state->handler = doctype3; + return XML_ROLE_DOCTYPE_PUBLIC_ID; + } + return common(state, tok); +} + +static +int doctype3(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_LITERAL: + state->handler = doctype4; + return XML_ROLE_DOCTYPE_SYSTEM_ID; + } + return common(state, tok); +} + +static +int doctype4(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_OPEN_BRACKET: + state->handler = internalSubset; + return XML_ROLE_DOCTYPE_INTERNAL_SUBSET; + case XML_TOK_DECL_CLOSE: + state->handler = prolog2; + return XML_ROLE_DOCTYPE_CLOSE; + } + return common(state, tok); +} + +static +int doctype5(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_DECL_CLOSE: + state->handler = prolog2; + return XML_ROLE_DOCTYPE_CLOSE; + } + return common(state, tok); +} + +static +int internalSubset(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_DECL_OPEN: + if (XmlNameMatchesAscii(enc, + ptr + 2 * MIN_BYTES_PER_CHAR(enc), + end, + KW_ENTITY)) { + state->handler = entity0; + return XML_ROLE_NONE; + } + if (XmlNameMatchesAscii(enc, + ptr + 2 * MIN_BYTES_PER_CHAR(enc), + end, + KW_ATTLIST)) { + state->handler = attlist0; + return XML_ROLE_NONE; + } + if (XmlNameMatchesAscii(enc, + ptr + 2 * MIN_BYTES_PER_CHAR(enc), + end, + KW_ELEMENT)) { + state->handler = element0; + return XML_ROLE_NONE; + } + if (XmlNameMatchesAscii(enc, + ptr + 2 * MIN_BYTES_PER_CHAR(enc), + end, + KW_NOTATION)) { + state->handler = notation0; + return XML_ROLE_NONE; + } + break; + case XML_TOK_PI: + case XML_TOK_COMMENT: + return XML_ROLE_NONE; + case XML_TOK_PARAM_ENTITY_REF: + return XML_ROLE_PARAM_ENTITY_REF; + case XML_TOK_CLOSE_BRACKET: + state->handler = doctype5; + return XML_ROLE_NONE; + } + return common(state, tok); +} + +#ifdef XML_DTD + +static +int externalSubset0(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + state->handler = externalSubset1; + if (tok == XML_TOK_XML_DECL) + return XML_ROLE_TEXT_DECL; + return externalSubset1(state, tok, ptr, end, enc); +} + +static +int externalSubset1(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_COND_SECT_OPEN: + state->handler = condSect0; + return XML_ROLE_NONE; + case XML_TOK_COND_SECT_CLOSE: + if (state->includeLevel == 0) + break; + state->includeLevel -= 1; + return XML_ROLE_NONE; + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_CLOSE_BRACKET: + break; + case XML_TOK_NONE: + if (state->includeLevel) + break; + return XML_ROLE_NONE; + default: + return internalSubset(state, tok, ptr, end, enc); + } + return common(state, tok); +} + +#endif /* XML_DTD */ + +static +int entity0(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_PERCENT: + state->handler = entity1; + return XML_ROLE_NONE; + case XML_TOK_NAME: + state->handler = entity2; + return XML_ROLE_GENERAL_ENTITY_NAME; + } + return common(state, tok); +} + +static +int entity1(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_NAME: + state->handler = entity7; + return XML_ROLE_PARAM_ENTITY_NAME; + } + return common(state, tok); +} + +static +int entity2(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_NAME: + if (XmlNameMatchesAscii(enc, ptr, end, KW_SYSTEM)) { + state->handler = entity4; + return XML_ROLE_NONE; + } + if (XmlNameMatchesAscii(enc, ptr, end, KW_PUBLIC)) { + state->handler = entity3; + return XML_ROLE_NONE; + } + break; + case XML_TOK_LITERAL: + state->handler = declClose; + return XML_ROLE_ENTITY_VALUE; + } + return common(state, tok); +} + +static +int entity3(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_LITERAL: + state->handler = entity4; + return XML_ROLE_ENTITY_PUBLIC_ID; + } + return common(state, tok); +} + + +static +int entity4(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_LITERAL: + state->handler = entity5; + return XML_ROLE_ENTITY_SYSTEM_ID; + } + return common(state, tok); +} + +static +int entity5(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_DECL_CLOSE: + setTopLevel(state); + return XML_ROLE_ENTITY_COMPLETE; + case XML_TOK_NAME: + if (XmlNameMatchesAscii(enc, ptr, end, KW_NDATA)) { + state->handler = entity6; + return XML_ROLE_NONE; + } + break; + } + return common(state, tok); +} + +static +int entity6(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_NAME: + state->handler = declClose; + return XML_ROLE_ENTITY_NOTATION_NAME; + } + return common(state, tok); +} + +static +int entity7(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_NAME: + if (XmlNameMatchesAscii(enc, ptr, end, KW_SYSTEM)) { + state->handler = entity9; + return XML_ROLE_NONE; + } + if (XmlNameMatchesAscii(enc, ptr, end, KW_PUBLIC)) { + state->handler = entity8; + return XML_ROLE_NONE; + } + break; + case XML_TOK_LITERAL: + state->handler = declClose; + return XML_ROLE_ENTITY_VALUE; + } + return common(state, tok); +} + +static +int entity8(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_LITERAL: + state->handler = entity9; + return XML_ROLE_ENTITY_PUBLIC_ID; + } + return common(state, tok); +} + +static +int entity9(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_LITERAL: + state->handler = declClose; + return XML_ROLE_ENTITY_SYSTEM_ID; + } + return common(state, tok); +} + +static +int notation0(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_NAME: + state->handler = notation1; + return XML_ROLE_NOTATION_NAME; + } + return common(state, tok); +} + +static +int notation1(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_NAME: + if (XmlNameMatchesAscii(enc, ptr, end, KW_SYSTEM)) { + state->handler = notation3; + return XML_ROLE_NONE; + } + if (XmlNameMatchesAscii(enc, ptr, end, KW_PUBLIC)) { + state->handler = notation2; + return XML_ROLE_NONE; + } + break; + } + return common(state, tok); +} + +static +int notation2(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_LITERAL: + state->handler = notation4; + return XML_ROLE_NOTATION_PUBLIC_ID; + } + return common(state, tok); +} + +static +int notation3(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_LITERAL: + state->handler = declClose; + return XML_ROLE_NOTATION_SYSTEM_ID; + } + return common(state, tok); +} + +static +int notation4(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_LITERAL: + state->handler = declClose; + return XML_ROLE_NOTATION_SYSTEM_ID; + case XML_TOK_DECL_CLOSE: + setTopLevel(state); + return XML_ROLE_NOTATION_NO_SYSTEM_ID; + } + return common(state, tok); +} + +static +int attlist0(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_NAME: + case XML_TOK_PREFIXED_NAME: + state->handler = attlist1; + return XML_ROLE_ATTLIST_ELEMENT_NAME; + } + return common(state, tok); +} + +static +int attlist1(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_DECL_CLOSE: + setTopLevel(state); + return XML_ROLE_NONE; + case XML_TOK_NAME: + case XML_TOK_PREFIXED_NAME: + state->handler = attlist2; + return XML_ROLE_ATTRIBUTE_NAME; + } + return common(state, tok); +} + +static +int attlist2(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_NAME: + { + static const char *types[] = { + KW_CDATA, + KW_ID, + KW_IDREF, + KW_IDREFS, + KW_ENTITY, + KW_ENTITIES, + KW_NMTOKEN, + KW_NMTOKENS, + }; + int i; + for (i = 0; i < (int)(sizeof(types)/sizeof(types[0])); i++) + if (XmlNameMatchesAscii(enc, ptr, end, types[i])) { + state->handler = attlist8; + return XML_ROLE_ATTRIBUTE_TYPE_CDATA + i; + } + } + if (XmlNameMatchesAscii(enc, ptr, end, KW_NOTATION)) { + state->handler = attlist5; + return XML_ROLE_NONE; + } + break; + case XML_TOK_OPEN_PAREN: + state->handler = attlist3; + return XML_ROLE_NONE; + } + return common(state, tok); +} + +static +int attlist3(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_NMTOKEN: + case XML_TOK_NAME: + case XML_TOK_PREFIXED_NAME: + state->handler = attlist4; + return XML_ROLE_ATTRIBUTE_ENUM_VALUE; + } + return common(state, tok); +} + +static +int attlist4(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_CLOSE_PAREN: + state->handler = attlist8; + return XML_ROLE_NONE; + case XML_TOK_OR: + state->handler = attlist3; + return XML_ROLE_NONE; + } + return common(state, tok); +} + +static +int attlist5(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_OPEN_PAREN: + state->handler = attlist6; + return XML_ROLE_NONE; + } + return common(state, tok); +} + + +static +int attlist6(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_NAME: + state->handler = attlist7; + return XML_ROLE_ATTRIBUTE_NOTATION_VALUE; + } + return common(state, tok); +} + +static +int attlist7(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_CLOSE_PAREN: + state->handler = attlist8; + return XML_ROLE_NONE; + case XML_TOK_OR: + state->handler = attlist6; + return XML_ROLE_NONE; + } + return common(state, tok); +} + +/* default value */ +static +int attlist8(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_POUND_NAME: + if (XmlNameMatchesAscii(enc, + ptr + MIN_BYTES_PER_CHAR(enc), + end, + KW_IMPLIED)) { + state->handler = attlist1; + return XML_ROLE_IMPLIED_ATTRIBUTE_VALUE; + } + if (XmlNameMatchesAscii(enc, + ptr + MIN_BYTES_PER_CHAR(enc), + end, + KW_REQUIRED)) { + state->handler = attlist1; + return XML_ROLE_REQUIRED_ATTRIBUTE_VALUE; + } + if (XmlNameMatchesAscii(enc, + ptr + MIN_BYTES_PER_CHAR(enc), + end, + KW_FIXED)) { + state->handler = attlist9; + return XML_ROLE_NONE; + } + break; + case XML_TOK_LITERAL: + state->handler = attlist1; + return XML_ROLE_DEFAULT_ATTRIBUTE_VALUE; + } + return common(state, tok); +} + +static +int attlist9(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_LITERAL: + state->handler = attlist1; + return XML_ROLE_FIXED_ATTRIBUTE_VALUE; + } + return common(state, tok); +} + +static +int element0(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_NAME: + case XML_TOK_PREFIXED_NAME: + state->handler = element1; + return XML_ROLE_ELEMENT_NAME; + } + return common(state, tok); +} + +static +int element1(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_NAME: + if (XmlNameMatchesAscii(enc, ptr, end, KW_EMPTY)) { + state->handler = declClose; + return XML_ROLE_CONTENT_EMPTY; + } + if (XmlNameMatchesAscii(enc, ptr, end, KW_ANY)) { + state->handler = declClose; + return XML_ROLE_CONTENT_ANY; + } + break; + case XML_TOK_OPEN_PAREN: + state->handler = element2; + state->level = 1; + return XML_ROLE_GROUP_OPEN; + } + return common(state, tok); +} + +static +int element2(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_POUND_NAME: + if (XmlNameMatchesAscii(enc, + ptr + MIN_BYTES_PER_CHAR(enc), + end, + KW_PCDATA)) { + state->handler = element3; + return XML_ROLE_CONTENT_PCDATA; + } + break; + case XML_TOK_OPEN_PAREN: + state->level = 2; + state->handler = element6; + return XML_ROLE_GROUP_OPEN; + case XML_TOK_NAME: + case XML_TOK_PREFIXED_NAME: + state->handler = element7; + return XML_ROLE_CONTENT_ELEMENT; + case XML_TOK_NAME_QUESTION: + state->handler = element7; + return XML_ROLE_CONTENT_ELEMENT_OPT; + case XML_TOK_NAME_ASTERISK: + state->handler = element7; + return XML_ROLE_CONTENT_ELEMENT_REP; + case XML_TOK_NAME_PLUS: + state->handler = element7; + return XML_ROLE_CONTENT_ELEMENT_PLUS; + } + return common(state, tok); +} + +static +int element3(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_CLOSE_PAREN: + state->handler = declClose; + return XML_ROLE_GROUP_CLOSE; + case XML_TOK_CLOSE_PAREN_ASTERISK: + state->handler = declClose; + return XML_ROLE_GROUP_CLOSE_REP; + case XML_TOK_OR: + state->handler = element4; + return XML_ROLE_NONE; + } + return common(state, tok); +} + +static +int element4(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_NAME: + case XML_TOK_PREFIXED_NAME: + state->handler = element5; + return XML_ROLE_CONTENT_ELEMENT; + } + return common(state, tok); +} + +static +int element5(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_CLOSE_PAREN_ASTERISK: + state->handler = declClose; + return XML_ROLE_GROUP_CLOSE_REP; + case XML_TOK_OR: + state->handler = element4; + return XML_ROLE_NONE; + } + return common(state, tok); +} + +static +int element6(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_OPEN_PAREN: + state->level += 1; + return XML_ROLE_GROUP_OPEN; + case XML_TOK_NAME: + case XML_TOK_PREFIXED_NAME: + state->handler = element7; + return XML_ROLE_CONTENT_ELEMENT; + case XML_TOK_NAME_QUESTION: + state->handler = element7; + return XML_ROLE_CONTENT_ELEMENT_OPT; + case XML_TOK_NAME_ASTERISK: + state->handler = element7; + return XML_ROLE_CONTENT_ELEMENT_REP; + case XML_TOK_NAME_PLUS: + state->handler = element7; + return XML_ROLE_CONTENT_ELEMENT_PLUS; + } + return common(state, tok); +} + +static +int element7(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_CLOSE_PAREN: + state->level -= 1; + if (state->level == 0) + state->handler = declClose; + return XML_ROLE_GROUP_CLOSE; + case XML_TOK_CLOSE_PAREN_ASTERISK: + state->level -= 1; + if (state->level == 0) + state->handler = declClose; + return XML_ROLE_GROUP_CLOSE_REP; + case XML_TOK_CLOSE_PAREN_QUESTION: + state->level -= 1; + if (state->level == 0) + state->handler = declClose; + return XML_ROLE_GROUP_CLOSE_OPT; + case XML_TOK_CLOSE_PAREN_PLUS: + state->level -= 1; + if (state->level == 0) + state->handler = declClose; + return XML_ROLE_GROUP_CLOSE_PLUS; + case XML_TOK_COMMA: + state->handler = element6; + return XML_ROLE_GROUP_SEQUENCE; + case XML_TOK_OR: + state->handler = element6; + return XML_ROLE_GROUP_CHOICE; + } + return common(state, tok); +} + +#ifdef XML_DTD + +static +int condSect0(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_NAME: + if (XmlNameMatchesAscii(enc, ptr, end, KW_INCLUDE)) { + state->handler = condSect1; + return XML_ROLE_NONE; + } + if (XmlNameMatchesAscii(enc, ptr, end, KW_IGNORE)) { + state->handler = condSect2; + return XML_ROLE_NONE; + } + break; + } + return common(state, tok); +} + +static +int condSect1(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_OPEN_BRACKET: + state->handler = externalSubset1; + state->includeLevel += 1; + return XML_ROLE_NONE; + } + return common(state, tok); +} + +static +int condSect2(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_OPEN_BRACKET: + state->handler = externalSubset1; + return XML_ROLE_IGNORE_SECT; + } + return common(state, tok); +} + +#endif /* XML_DTD */ + +static +int declClose(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_DECL_CLOSE: + setTopLevel(state); + return XML_ROLE_NONE; + } + return common(state, tok); +} + +#if 0 + +static +int ignore(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_DECL_CLOSE: + state->handler = internalSubset; + return 0; + default: + return XML_ROLE_NONE; + } + return common(state, tok); +} +#endif + +static +int error(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + return XML_ROLE_NONE; +} + +static +int common(PROLOG_STATE *state, int tok) +{ +#ifdef XML_DTD + if (!state->documentEntity && tok == XML_TOK_PARAM_ENTITY_REF) + return XML_ROLE_INNER_PARAM_ENTITY_REF; +#endif + state->handler = error; + return XML_ROLE_ERROR; +} + +void XmlPrologStateInit(PROLOG_STATE *state) +{ + state->handler = prolog0; +#ifdef XML_DTD + state->documentEntity = 1; + state->includeLevel = 0; +#endif /* XML_DTD */ +} + +#ifdef XML_DTD + +void XmlPrologStateInitExternalEntity(PROLOG_STATE *state) +{ + state->handler = externalSubset0; + state->documentEntity = 0; + state->includeLevel = 0; +} + +#endif /* XML_DTD */ diff --git a/Code/BF2/External/expat/xmlrole.h b/Code/BF2/External/expat/xmlrole.h new file mode 100644 index 000000000..db3ebc848 --- /dev/null +++ b/Code/BF2/External/expat/xmlrole.h @@ -0,0 +1,100 @@ +/* +Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd +See the file COPYING for copying permission. +*/ + +#ifndef XmlRole_INCLUDED +#define XmlRole_INCLUDED 1 + +#include "xmltok.h" + +#ifdef __cplusplus +extern "C" { +#endif + +enum { + XML_ROLE_ERROR = -1, + XML_ROLE_NONE = 0, + XML_ROLE_XML_DECL, + XML_ROLE_INSTANCE_START, + XML_ROLE_DOCTYPE_NAME, + XML_ROLE_DOCTYPE_SYSTEM_ID, + XML_ROLE_DOCTYPE_PUBLIC_ID, + XML_ROLE_DOCTYPE_INTERNAL_SUBSET, + XML_ROLE_DOCTYPE_CLOSE, + XML_ROLE_GENERAL_ENTITY_NAME, + XML_ROLE_PARAM_ENTITY_NAME, + XML_ROLE_ENTITY_VALUE, + XML_ROLE_ENTITY_SYSTEM_ID, + XML_ROLE_ENTITY_PUBLIC_ID, + XML_ROLE_ENTITY_COMPLETE, + XML_ROLE_ENTITY_NOTATION_NAME, + XML_ROLE_NOTATION_NAME, + XML_ROLE_NOTATION_SYSTEM_ID, + XML_ROLE_NOTATION_NO_SYSTEM_ID, + XML_ROLE_NOTATION_PUBLIC_ID, + XML_ROLE_ATTRIBUTE_NAME, + XML_ROLE_ATTRIBUTE_TYPE_CDATA, + XML_ROLE_ATTRIBUTE_TYPE_ID, + XML_ROLE_ATTRIBUTE_TYPE_IDREF, + XML_ROLE_ATTRIBUTE_TYPE_IDREFS, + XML_ROLE_ATTRIBUTE_TYPE_ENTITY, + XML_ROLE_ATTRIBUTE_TYPE_ENTITIES, + XML_ROLE_ATTRIBUTE_TYPE_NMTOKEN, + XML_ROLE_ATTRIBUTE_TYPE_NMTOKENS, + XML_ROLE_ATTRIBUTE_ENUM_VALUE, + XML_ROLE_ATTRIBUTE_NOTATION_VALUE, + XML_ROLE_ATTLIST_ELEMENT_NAME, + XML_ROLE_IMPLIED_ATTRIBUTE_VALUE, + XML_ROLE_REQUIRED_ATTRIBUTE_VALUE, + XML_ROLE_DEFAULT_ATTRIBUTE_VALUE, + XML_ROLE_FIXED_ATTRIBUTE_VALUE, + XML_ROLE_ELEMENT_NAME, + XML_ROLE_CONTENT_ANY, + XML_ROLE_CONTENT_EMPTY, + XML_ROLE_CONTENT_PCDATA, + XML_ROLE_GROUP_OPEN, + XML_ROLE_GROUP_CLOSE, + XML_ROLE_GROUP_CLOSE_REP, + XML_ROLE_GROUP_CLOSE_OPT, + XML_ROLE_GROUP_CLOSE_PLUS, + XML_ROLE_GROUP_CHOICE, + XML_ROLE_GROUP_SEQUENCE, + XML_ROLE_CONTENT_ELEMENT, + XML_ROLE_CONTENT_ELEMENT_REP, + XML_ROLE_CONTENT_ELEMENT_OPT, + XML_ROLE_CONTENT_ELEMENT_PLUS, +#ifdef XML_DTD + XML_ROLE_TEXT_DECL, + XML_ROLE_IGNORE_SECT, + XML_ROLE_INNER_PARAM_ENTITY_REF, +#endif /* XML_DTD */ + XML_ROLE_PARAM_ENTITY_REF +}; + +typedef struct prolog_state { + int (*handler)(struct prolog_state *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc); + unsigned level; +#ifdef XML_DTD + unsigned includeLevel; + int documentEntity; +#endif /* XML_DTD */ +} PROLOG_STATE; + +void XmlPrologStateInit(PROLOG_STATE *); +#ifdef XML_DTD +void XmlPrologStateInitExternalEntity(PROLOG_STATE *); +#endif /* XML_DTD */ + +#define XmlTokenRole(state, tok, ptr, end, enc) \ + (((state)->handler)(state, tok, ptr, end, enc)) + +#ifdef __cplusplus +} +#endif + +#endif /* not XmlRole_INCLUDED */ diff --git a/Code/BF2/External/expat/xmltok.c b/Code/BF2/External/expat/xmltok.c new file mode 100644 index 000000000..788e79f93 --- /dev/null +++ b/Code/BF2/External/expat/xmltok.c @@ -0,0 +1,1563 @@ +/* +Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd +See the file COPYING for copying permission. +*/ + +static char RCSId[] + = "$Header$"; + +#include +#include "xmltok.h" +#include "nametab.h" + +#ifdef XML_DTD +#define IGNORE_SECTION_TOK_VTABLE , PREFIX(ignoreSectionTok) +#else +#define IGNORE_SECTION_TOK_VTABLE /* as nothing */ +#endif + +#define VTABLE1 \ + { PREFIX(prologTok), PREFIX(contentTok), \ + PREFIX(cdataSectionTok) IGNORE_SECTION_TOK_VTABLE }, \ + { PREFIX(attributeValueTok), PREFIX(entityValueTok) }, \ + PREFIX(sameName), \ + PREFIX(nameMatchesAscii), \ + PREFIX(nameLength), \ + PREFIX(skipS), \ + PREFIX(getAtts), \ + PREFIX(charRefNumber), \ + PREFIX(predefinedEntityName), \ + PREFIX(updatePosition), \ + PREFIX(isPublicId) + +#define VTABLE VTABLE1, PREFIX(toUtf8), PREFIX(toUtf16) + +#define UCS2_GET_NAMING(pages, hi, lo) \ + (namingBitmap[(pages[hi] << 3) + ((lo) >> 5)] & (1 << ((lo) & 0x1F))) + +/* A 2 byte UTF-8 representation splits the characters 11 bits +between the bottom 5 and 6 bits of the bytes. +We need 8 bits to index into pages, 3 bits to add to that index and +5 bits to generate the mask. */ +#define UTF8_GET_NAMING2(pages, byte) \ + (namingBitmap[((pages)[(((byte)[0]) >> 2) & 7] << 3) \ + + ((((byte)[0]) & 3) << 1) \ + + ((((byte)[1]) >> 5) & 1)] \ + & (1 << (((byte)[1]) & 0x1F))) + +/* A 3 byte UTF-8 representation splits the characters 16 bits +between the bottom 4, 6 and 6 bits of the bytes. +We need 8 bits to index into pages, 3 bits to add to that index and +5 bits to generate the mask. */ +#define UTF8_GET_NAMING3(pages, byte) \ + (namingBitmap[((pages)[((((byte)[0]) & 0xF) << 4) \ + + ((((byte)[1]) >> 2) & 0xF)] \ + << 3) \ + + ((((byte)[1]) & 3) << 1) \ + + ((((byte)[2]) >> 5) & 1)] \ + & (1 << (((byte)[2]) & 0x1F))) + +#define UTF8_GET_NAMING(pages, p, n) \ + ((n) == 2 \ + ? UTF8_GET_NAMING2(pages, (const unsigned char *)(p)) \ + : ((n) == 3 \ + ? UTF8_GET_NAMING3(pages, (const unsigned char *)(p)) \ + : 0)) + +#define UTF8_INVALID3(p) \ + ((*p) == 0xED \ + ? (((p)[1] & 0x20) != 0) \ + : ((*p) == 0xEF \ + ? ((p)[1] == 0xBF && ((p)[2] == 0xBF || (p)[2] == 0xBE)) \ + : 0)) + +#define UTF8_INVALID4(p) ((*p) == 0xF4 && ((p)[1] & 0x30) != 0) + +static +int isNever(const ENCODING *enc, const char *p) +{ + return 0; +} + +static +int utf8_isName2(const ENCODING *enc, const char *p) +{ + return UTF8_GET_NAMING2(namePages, (const unsigned char *)p); +} + +static +int utf8_isName3(const ENCODING *enc, const char *p) +{ + return UTF8_GET_NAMING3(namePages, (const unsigned char *)p); +} + +#define utf8_isName4 isNever + +static +int utf8_isNmstrt2(const ENCODING *enc, const char *p) +{ + return UTF8_GET_NAMING2(nmstrtPages, (const unsigned char *)p); +} + +static +int utf8_isNmstrt3(const ENCODING *enc, const char *p) +{ + return UTF8_GET_NAMING3(nmstrtPages, (const unsigned char *)p); +} + +#define utf8_isNmstrt4 isNever + +#define utf8_isInvalid2 isNever + +static +int utf8_isInvalid3(const ENCODING *enc, const char *p) +{ + return UTF8_INVALID3((const unsigned char *)p); +} + +static +int utf8_isInvalid4(const ENCODING *enc, const char *p) +{ + return UTF8_INVALID4((const unsigned char *)p); +} + +struct normal_encoding { + ENCODING enc; + unsigned char type[256]; +#ifdef XML_MIN_SIZE + int (*byteType)(const ENCODING *, const char *); + int (*isNameMin)(const ENCODING *, const char *); + int (*isNmstrtMin)(const ENCODING *, const char *); + int (*byteToAscii)(const ENCODING *, const char *); + int (*charMatches)(const ENCODING *, const char *, int); +#endif /* XML_MIN_SIZE */ + int (*isName2)(const ENCODING *, const char *); + int (*isName3)(const ENCODING *, const char *); + int (*isName4)(const ENCODING *, const char *); + int (*isNmstrt2)(const ENCODING *, const char *); + int (*isNmstrt3)(const ENCODING *, const char *); + int (*isNmstrt4)(const ENCODING *, const char *); + int (*isInvalid2)(const ENCODING *, const char *); + int (*isInvalid3)(const ENCODING *, const char *); + int (*isInvalid4)(const ENCODING *, const char *); +}; + +#ifdef XML_MIN_SIZE + +#define STANDARD_VTABLE(E) \ + E ## byteType, \ + E ## isNameMin, \ + E ## isNmstrtMin, \ + E ## byteToAscii, \ + E ## charMatches, + +#else + +#define STANDARD_VTABLE(E) /* as nothing */ + +#endif + +#define NORMAL_VTABLE(E) \ + E ## isName2, \ + E ## isName3, \ + E ## isName4, \ + E ## isNmstrt2, \ + E ## isNmstrt3, \ + E ## isNmstrt4, \ + E ## isInvalid2, \ + E ## isInvalid3, \ + E ## isInvalid4 + +static int checkCharRefNumber(int); + +#include "xmltok_impl.h" +#include "ascii.h" + +#ifdef XML_MIN_SIZE +#define sb_isNameMin isNever +#define sb_isNmstrtMin isNever +#endif + +#ifdef XML_MIN_SIZE +#define MINBPC(enc) ((enc)->minBytesPerChar) +#else +/* minimum bytes per character */ +#define MINBPC(enc) 1 +#endif + +#define SB_BYTE_TYPE(enc, p) \ + (((struct normal_encoding *)(enc))->type[(unsigned char)*(p)]) + +#ifdef XML_MIN_SIZE +static +int sb_byteType(const ENCODING *enc, const char *p) +{ + return SB_BYTE_TYPE(enc, p); +} +#define BYTE_TYPE(enc, p) \ + (((const struct normal_encoding *)(enc))->byteType(enc, p)) +#else +#define BYTE_TYPE(enc, p) SB_BYTE_TYPE(enc, p) +#endif + +#ifdef XML_MIN_SIZE +#define BYTE_TO_ASCII(enc, p) \ + (((const struct normal_encoding *)(enc))->byteToAscii(enc, p)) +static +int sb_byteToAscii(const ENCODING *enc, const char *p) +{ + return *p; +} +#else +#define BYTE_TO_ASCII(enc, p) (*(p)) +#endif + +#define IS_NAME_CHAR(enc, p, n) \ + (((const struct normal_encoding *)(enc))->isName ## n(enc, p)) +#define IS_NMSTRT_CHAR(enc, p, n) \ + (((const struct normal_encoding *)(enc))->isNmstrt ## n(enc, p)) +#define IS_INVALID_CHAR(enc, p, n) \ + (((const struct normal_encoding *)(enc))->isInvalid ## n(enc, p)) + +#ifdef XML_MIN_SIZE +#define IS_NAME_CHAR_MINBPC(enc, p) \ + (((const struct normal_encoding *)(enc))->isNameMin(enc, p)) +#define IS_NMSTRT_CHAR_MINBPC(enc, p) \ + (((const struct normal_encoding *)(enc))->isNmstrtMin(enc, p)) +#else +#define IS_NAME_CHAR_MINBPC(enc, p) (0) +#define IS_NMSTRT_CHAR_MINBPC(enc, p) (0) +#endif + +#ifdef XML_MIN_SIZE +#define CHAR_MATCHES(enc, p, c) \ + (((const struct normal_encoding *)(enc))->charMatches(enc, p, c)) +static +int sb_charMatches(const ENCODING *enc, const char *p, int c) +{ + return *p == c; +} +#else +/* c is an ASCII character */ +#define CHAR_MATCHES(enc, p, c) (*(p) == c) +#endif + +#define PREFIX(ident) normal_ ## ident +#include "xmltok_impl.c" + +#undef MINBPC +#undef BYTE_TYPE +#undef BYTE_TO_ASCII +#undef CHAR_MATCHES +#undef IS_NAME_CHAR +#undef IS_NAME_CHAR_MINBPC +#undef IS_NMSTRT_CHAR +#undef IS_NMSTRT_CHAR_MINBPC +#undef IS_INVALID_CHAR + +enum { /* UTF8_cvalN is value of masked first byte of N byte sequence */ + UTF8_cval1 = 0x00, + UTF8_cval2 = 0xc0, + UTF8_cval3 = 0xe0, + UTF8_cval4 = 0xf0 +}; + +static +void utf8_toUtf8(const ENCODING *enc, + const char **fromP, const char *fromLim, + char **toP, const char *toLim) +{ + char *to; + const char *from; + if (fromLim - *fromP > toLim - *toP) { + /* Avoid copying partial characters. */ + for (fromLim = *fromP + (toLim - *toP); fromLim > *fromP; fromLim--) + if (((unsigned char)fromLim[-1] & 0xc0) != 0x80) + break; + } + for (to = *toP, from = *fromP; from != fromLim; from++, to++) + *to = *from; + *fromP = from; + *toP = to; +} + +static +void utf8_toUtf16(const ENCODING *enc, + const char **fromP, const char *fromLim, + unsigned short **toP, const unsigned short *toLim) +{ + unsigned short *to = *toP; + const char *from = *fromP; + while (from != fromLim && to != toLim) { + switch (((struct normal_encoding *)enc)->type[(unsigned char)*from]) { + case BT_LEAD2: + *to++ = ((from[0] & 0x1f) << 6) | (from[1] & 0x3f); + from += 2; + break; + case BT_LEAD3: + *to++ = ((from[0] & 0xf) << 12) | ((from[1] & 0x3f) << 6) | (from[2] & 0x3f); + from += 3; + break; + case BT_LEAD4: + { + unsigned long n; + if (to + 1 == toLim) + break; + n = ((from[0] & 0x7) << 18) | ((from[1] & 0x3f) << 12) | ((from[2] & 0x3f) << 6) | (from[3] & 0x3f); + n -= 0x10000; + to[0] = (unsigned short)((n >> 10) | 0xD800); + to[1] = (unsigned short)((n & 0x3FF) | 0xDC00); + to += 2; + from += 4; + } + break; + default: + *to++ = *from++; + break; + } + } + *fromP = from; + *toP = to; +} + +#ifdef XML_NS +static const struct normal_encoding utf8_encoding_ns = { + { VTABLE1, utf8_toUtf8, utf8_toUtf16, 1, 1, 0 }, + { +#include "asciitab.h" +#include "utf8tab.h" + }, + STANDARD_VTABLE(sb_) NORMAL_VTABLE(utf8_) +}; +#endif + +static const struct normal_encoding utf8_encoding = { + { VTABLE1, utf8_toUtf8, utf8_toUtf16, 1, 1, 0 }, + { +#define BT_COLON BT_NMSTRT +#include "asciitab.h" +#undef BT_COLON +#include "utf8tab.h" + }, + STANDARD_VTABLE(sb_) NORMAL_VTABLE(utf8_) +}; + +#ifdef XML_NS + +static const struct normal_encoding internal_utf8_encoding_ns = { + { VTABLE1, utf8_toUtf8, utf8_toUtf16, 1, 1, 0 }, + { +#include "iasciitab.h" +#include "utf8tab.h" + }, + STANDARD_VTABLE(sb_) NORMAL_VTABLE(utf8_) +}; + +#endif + +static const struct normal_encoding internal_utf8_encoding = { + { VTABLE1, utf8_toUtf8, utf8_toUtf16, 1, 1, 0 }, + { +#define BT_COLON BT_NMSTRT +#include "iasciitab.h" +#undef BT_COLON +#include "utf8tab.h" + }, + STANDARD_VTABLE(sb_) NORMAL_VTABLE(utf8_) +}; + +static +void latin1_toUtf8(const ENCODING *enc, + const char **fromP, const char *fromLim, + char **toP, const char *toLim) +{ + for (;;) { + unsigned char c; + if (*fromP == fromLim) + break; + c = (unsigned char)**fromP; + if (c & 0x80) { + if (toLim - *toP < 2) + break; + *(*toP)++ = ((c >> 6) | UTF8_cval2); + *(*toP)++ = ((c & 0x3f) | 0x80); + (*fromP)++; + } + else { + if (*toP == toLim) + break; + *(*toP)++ = *(*fromP)++; + } + } +} + +static +void latin1_toUtf16(const ENCODING *enc, + const char **fromP, const char *fromLim, + unsigned short **toP, const unsigned short *toLim) +{ + while (*fromP != fromLim && *toP != toLim) + *(*toP)++ = (unsigned char)*(*fromP)++; +} + +#ifdef XML_NS + +static const struct normal_encoding latin1_encoding_ns = { + { VTABLE1, latin1_toUtf8, latin1_toUtf16, 1, 0, 0 }, + { +#include "asciitab.h" +#include "latin1tab.h" + }, + STANDARD_VTABLE(sb_) +}; + +#endif + +static const struct normal_encoding latin1_encoding = { + { VTABLE1, latin1_toUtf8, latin1_toUtf16, 1, 0, 0 }, + { +#define BT_COLON BT_NMSTRT +#include "asciitab.h" +#undef BT_COLON +#include "latin1tab.h" + }, + STANDARD_VTABLE(sb_) +}; + +static +void ascii_toUtf8(const ENCODING *enc, + const char **fromP, const char *fromLim, + char **toP, const char *toLim) +{ + while (*fromP != fromLim && *toP != toLim) + *(*toP)++ = *(*fromP)++; +} + +#ifdef XML_NS + +static const struct normal_encoding ascii_encoding_ns = { + { VTABLE1, ascii_toUtf8, latin1_toUtf16, 1, 1, 0 }, + { +#include "asciitab.h" +/* BT_NONXML == 0 */ + }, + STANDARD_VTABLE(sb_) +}; + +#endif + +static const struct normal_encoding ascii_encoding = { + { VTABLE1, ascii_toUtf8, latin1_toUtf16, 1, 1, 0 }, + { +#define BT_COLON BT_NMSTRT +#include "asciitab.h" +#undef BT_COLON +/* BT_NONXML == 0 */ + }, + STANDARD_VTABLE(sb_) +}; + +static int unicode_byte_type(char hi, char lo) +{ + switch ((unsigned char)hi) { + case 0xD8: case 0xD9: case 0xDA: case 0xDB: + return BT_LEAD4; + case 0xDC: case 0xDD: case 0xDE: case 0xDF: + return BT_TRAIL; + case 0xFF: + switch ((unsigned char)lo) { + case 0xFF: + case 0xFE: + return BT_NONXML; + } + break; + } + return BT_NONASCII; +} + +#define DEFINE_UTF16_TO_UTF8(E) \ +static \ +void E ## toUtf8(const ENCODING *enc, \ + const char **fromP, const char *fromLim, \ + char **toP, const char *toLim) \ +{ \ + const char *from; \ + for (from = *fromP; from != fromLim; from += 2) { \ + int plane; \ + unsigned char lo2; \ + unsigned char lo = GET_LO(from); \ + unsigned char hi = GET_HI(from); \ + switch (hi) { \ + case 0: \ + if (lo < 0x80) { \ + if (*toP == toLim) { \ + *fromP = from; \ + return; \ + } \ + *(*toP)++ = lo; \ + break; \ + } \ + /* fall through */ \ + case 0x1: case 0x2: case 0x3: \ + case 0x4: case 0x5: case 0x6: case 0x7: \ + if (toLim - *toP < 2) { \ + *fromP = from; \ + return; \ + } \ + *(*toP)++ = ((lo >> 6) | (hi << 2) | UTF8_cval2); \ + *(*toP)++ = ((lo & 0x3f) | 0x80); \ + break; \ + default: \ + if (toLim - *toP < 3) { \ + *fromP = from; \ + return; \ + } \ + /* 16 bits divided 4, 6, 6 amongst 3 bytes */ \ + *(*toP)++ = ((hi >> 4) | UTF8_cval3); \ + *(*toP)++ = (((hi & 0xf) << 2) | (lo >> 6) | 0x80); \ + *(*toP)++ = ((lo & 0x3f) | 0x80); \ + break; \ + case 0xD8: case 0xD9: case 0xDA: case 0xDB: \ + if (toLim - *toP < 4) { \ + *fromP = from; \ + return; \ + } \ + plane = (((hi & 0x3) << 2) | ((lo >> 6) & 0x3)) + 1; \ + *(*toP)++ = ((plane >> 2) | UTF8_cval4); \ + *(*toP)++ = (((lo >> 2) & 0xF) | ((plane & 0x3) << 4) | 0x80); \ + from += 2; \ + lo2 = GET_LO(from); \ + *(*toP)++ = (((lo & 0x3) << 4) \ + | ((GET_HI(from) & 0x3) << 2) \ + | (lo2 >> 6) \ + | 0x80); \ + *(*toP)++ = ((lo2 & 0x3f) | 0x80); \ + break; \ + } \ + } \ + *fromP = from; \ +} + +#define DEFINE_UTF16_TO_UTF16(E) \ +static \ +void E ## toUtf16(const ENCODING *enc, \ + const char **fromP, const char *fromLim, \ + unsigned short **toP, const unsigned short *toLim) \ +{ \ + /* Avoid copying first half only of surrogate */ \ + if (fromLim - *fromP > ((toLim - *toP) << 1) \ + && (GET_HI(fromLim - 2) & 0xF8) == 0xD8) \ + fromLim -= 2; \ + for (; *fromP != fromLim && *toP != toLim; *fromP += 2) \ + *(*toP)++ = (GET_HI(*fromP) << 8) | GET_LO(*fromP); \ +} + +#define SET2(ptr, ch) \ + (((ptr)[0] = ((ch) & 0xff)), ((ptr)[1] = ((ch) >> 8))) +#define GET_LO(ptr) ((unsigned char)(ptr)[0]) +#define GET_HI(ptr) ((unsigned char)(ptr)[1]) + +DEFINE_UTF16_TO_UTF8(little2_) +DEFINE_UTF16_TO_UTF16(little2_) + +#undef SET2 +#undef GET_LO +#undef GET_HI + +#define SET2(ptr, ch) \ + (((ptr)[0] = ((ch) >> 8)), ((ptr)[1] = ((ch) & 0xFF))) +#define GET_LO(ptr) ((unsigned char)(ptr)[1]) +#define GET_HI(ptr) ((unsigned char)(ptr)[0]) + +DEFINE_UTF16_TO_UTF8(big2_) +DEFINE_UTF16_TO_UTF16(big2_) + +#undef SET2 +#undef GET_LO +#undef GET_HI + +#define LITTLE2_BYTE_TYPE(enc, p) \ + ((p)[1] == 0 \ + ? ((struct normal_encoding *)(enc))->type[(unsigned char)*(p)] \ + : unicode_byte_type((p)[1], (p)[0])) +#define LITTLE2_BYTE_TO_ASCII(enc, p) ((p)[1] == 0 ? (p)[0] : -1) +#define LITTLE2_CHAR_MATCHES(enc, p, c) ((p)[1] == 0 && (p)[0] == c) +#define LITTLE2_IS_NAME_CHAR_MINBPC(enc, p) \ + UCS2_GET_NAMING(namePages, (unsigned char)p[1], (unsigned char)p[0]) +#define LITTLE2_IS_NMSTRT_CHAR_MINBPC(enc, p) \ + UCS2_GET_NAMING(nmstrtPages, (unsigned char)p[1], (unsigned char)p[0]) + +#ifdef XML_MIN_SIZE + +static +int little2_byteType(const ENCODING *enc, const char *p) +{ + return LITTLE2_BYTE_TYPE(enc, p); +} + +static +int little2_byteToAscii(const ENCODING *enc, const char *p) +{ + return LITTLE2_BYTE_TO_ASCII(enc, p); +} + +static +int little2_charMatches(const ENCODING *enc, const char *p, int c) +{ + return LITTLE2_CHAR_MATCHES(enc, p, c); +} + +static +int little2_isNameMin(const ENCODING *enc, const char *p) +{ + return LITTLE2_IS_NAME_CHAR_MINBPC(enc, p); +} + +static +int little2_isNmstrtMin(const ENCODING *enc, const char *p) +{ + return LITTLE2_IS_NMSTRT_CHAR_MINBPC(enc, p); +} + +#undef VTABLE +#define VTABLE VTABLE1, little2_toUtf8, little2_toUtf16 + +#else /* not XML_MIN_SIZE */ + +#undef PREFIX +#define PREFIX(ident) little2_ ## ident +#define MINBPC(enc) 2 +/* CHAR_MATCHES is guaranteed to have MINBPC bytes available. */ +#define BYTE_TYPE(enc, p) LITTLE2_BYTE_TYPE(enc, p) +#define BYTE_TO_ASCII(enc, p) LITTLE2_BYTE_TO_ASCII(enc, p) +#define CHAR_MATCHES(enc, p, c) LITTLE2_CHAR_MATCHES(enc, p, c) +#define IS_NAME_CHAR(enc, p, n) 0 +#define IS_NAME_CHAR_MINBPC(enc, p) LITTLE2_IS_NAME_CHAR_MINBPC(enc, p) +#define IS_NMSTRT_CHAR(enc, p, n) (0) +#define IS_NMSTRT_CHAR_MINBPC(enc, p) LITTLE2_IS_NMSTRT_CHAR_MINBPC(enc, p) + +#include "xmltok_impl.c" + +#undef MINBPC +#undef BYTE_TYPE +#undef BYTE_TO_ASCII +#undef CHAR_MATCHES +#undef IS_NAME_CHAR +#undef IS_NAME_CHAR_MINBPC +#undef IS_NMSTRT_CHAR +#undef IS_NMSTRT_CHAR_MINBPC +#undef IS_INVALID_CHAR + +#endif /* not XML_MIN_SIZE */ + +#ifdef XML_NS + +static const struct normal_encoding little2_encoding_ns = { + { VTABLE, 2, 0, +#if XML_BYTE_ORDER == 12 + 1 +#else + 0 +#endif + }, + { +#include "asciitab.h" +#include "latin1tab.h" + }, + STANDARD_VTABLE(little2_) +}; + +#endif + +static const struct normal_encoding little2_encoding = { + { VTABLE, 2, 0, +#if XML_BYTE_ORDER == 12 + 1 +#else + 0 +#endif + }, + { +#define BT_COLON BT_NMSTRT +#include "asciitab.h" +#undef BT_COLON +#include "latin1tab.h" + }, + STANDARD_VTABLE(little2_) +}; + +#if XML_BYTE_ORDER != 21 + +#ifdef XML_NS + +static const struct normal_encoding internal_little2_encoding_ns = { + { VTABLE, 2, 0, 1 }, + { +#include "iasciitab.h" +#include "latin1tab.h" + }, + STANDARD_VTABLE(little2_) +}; + +#endif + +static const struct normal_encoding internal_little2_encoding = { + { VTABLE, 2, 0, 1 }, + { +#define BT_COLON BT_NMSTRT +#include "iasciitab.h" +#undef BT_COLON +#include "latin1tab.h" + }, + STANDARD_VTABLE(little2_) +}; + +#endif + + +#define BIG2_BYTE_TYPE(enc, p) \ + ((p)[0] == 0 \ + ? ((struct normal_encoding *)(enc))->type[(unsigned char)(p)[1]] \ + : unicode_byte_type((p)[0], (p)[1])) +#define BIG2_BYTE_TO_ASCII(enc, p) ((p)[0] == 0 ? (p)[1] : -1) +#define BIG2_CHAR_MATCHES(enc, p, c) ((p)[0] == 0 && (p)[1] == c) +#define BIG2_IS_NAME_CHAR_MINBPC(enc, p) \ + UCS2_GET_NAMING(namePages, (unsigned char)p[0], (unsigned char)p[1]) +#define BIG2_IS_NMSTRT_CHAR_MINBPC(enc, p) \ + UCS2_GET_NAMING(nmstrtPages, (unsigned char)p[0], (unsigned char)p[1]) + +#ifdef XML_MIN_SIZE + +static +int big2_byteType(const ENCODING *enc, const char *p) +{ + return BIG2_BYTE_TYPE(enc, p); +} + +static +int big2_byteToAscii(const ENCODING *enc, const char *p) +{ + return BIG2_BYTE_TO_ASCII(enc, p); +} + +static +int big2_charMatches(const ENCODING *enc, const char *p, int c) +{ + return BIG2_CHAR_MATCHES(enc, p, c); +} + +static +int big2_isNameMin(const ENCODING *enc, const char *p) +{ + return BIG2_IS_NAME_CHAR_MINBPC(enc, p); +} + +static +int big2_isNmstrtMin(const ENCODING *enc, const char *p) +{ + return BIG2_IS_NMSTRT_CHAR_MINBPC(enc, p); +} + +#undef VTABLE +#define VTABLE VTABLE1, big2_toUtf8, big2_toUtf16 + +#else /* not XML_MIN_SIZE */ + +#undef PREFIX +#define PREFIX(ident) big2_ ## ident +#define MINBPC(enc) 2 +/* CHAR_MATCHES is guaranteed to have MINBPC bytes available. */ +#define BYTE_TYPE(enc, p) BIG2_BYTE_TYPE(enc, p) +#define BYTE_TO_ASCII(enc, p) BIG2_BYTE_TO_ASCII(enc, p) +#define CHAR_MATCHES(enc, p, c) BIG2_CHAR_MATCHES(enc, p, c) +#define IS_NAME_CHAR(enc, p, n) 0 +#define IS_NAME_CHAR_MINBPC(enc, p) BIG2_IS_NAME_CHAR_MINBPC(enc, p) +#define IS_NMSTRT_CHAR(enc, p, n) (0) +#define IS_NMSTRT_CHAR_MINBPC(enc, p) BIG2_IS_NMSTRT_CHAR_MINBPC(enc, p) + +#include "xmltok_impl.c" + +#undef MINBPC +#undef BYTE_TYPE +#undef BYTE_TO_ASCII +#undef CHAR_MATCHES +#undef IS_NAME_CHAR +#undef IS_NAME_CHAR_MINBPC +#undef IS_NMSTRT_CHAR +#undef IS_NMSTRT_CHAR_MINBPC +#undef IS_INVALID_CHAR + +#endif /* not XML_MIN_SIZE */ + +#ifdef XML_NS + +static const struct normal_encoding big2_encoding_ns = { + { VTABLE, 2, 0, +#if XML_BYTE_ORDER == 21 + 1 +#else + 0 +#endif + }, + { +#include "asciitab.h" +#include "latin1tab.h" + }, + STANDARD_VTABLE(big2_) +}; + +#endif + +static const struct normal_encoding big2_encoding = { + { VTABLE, 2, 0, +#if XML_BYTE_ORDER == 21 + 1 +#else + 0 +#endif + }, + { +#define BT_COLON BT_NMSTRT +#include "asciitab.h" +#undef BT_COLON +#include "latin1tab.h" + }, + STANDARD_VTABLE(big2_) +}; + +#if XML_BYTE_ORDER != 12 + +#ifdef XML_NS + +static const struct normal_encoding internal_big2_encoding_ns = { + { VTABLE, 2, 0, 1 }, + { +#include "iasciitab.h" +#include "latin1tab.h" + }, + STANDARD_VTABLE(big2_) +}; + +#endif + +static const struct normal_encoding internal_big2_encoding = { + { VTABLE, 2, 0, 1 }, + { +#define BT_COLON BT_NMSTRT +#include "iasciitab.h" +#undef BT_COLON +#include "latin1tab.h" + }, + STANDARD_VTABLE(big2_) +}; + +#endif + +#undef PREFIX + +static +int streqci(const char *s1, const char *s2) +{ + for (;;) { + char c1 = *s1++; + char c2 = *s2++; + if (ASCII_a <= c1 && c1 <= ASCII_z) + c1 += ASCII_A - ASCII_a; + if (ASCII_a <= c2 && c2 <= ASCII_z) + c2 += ASCII_A - ASCII_a; + if (c1 != c2) + return 0; + if (!c1) + break; + } + return 1; +} + +static +void initUpdatePosition(const ENCODING *enc, const char *ptr, + const char *end, POSITION *pos) +{ + normal_updatePosition(&utf8_encoding.enc, ptr, end, pos); +} + +static +int toAscii(const ENCODING *enc, const char *ptr, const char *end) +{ + char buf[1]; + char *p = buf; + XmlUtf8Convert(enc, &ptr, end, &p, p + 1); + if (p == buf) + return -1; + else + return buf[0]; +} + +static +int isSpace(int c) +{ + switch (c) { + case 0x20: + case 0xD: + case 0xA: + case 0x9: + return 1; + } + return 0; +} + +/* Return 1 if there's just optional white space +or there's an S followed by name=val. */ +static +int parsePseudoAttribute(const ENCODING *enc, + const char *ptr, + const char *end, + const char **namePtr, + const char **nameEndPtr, + const char **valPtr, + const char **nextTokPtr) +{ + int c; + char open; + if (ptr == end) { + *namePtr = 0; + return 1; + } + if (!isSpace(toAscii(enc, ptr, end))) { + *nextTokPtr = ptr; + return 0; + } + do { + ptr += enc->minBytesPerChar; + } while (isSpace(toAscii(enc, ptr, end))); + if (ptr == end) { + *namePtr = 0; + return 1; + } + *namePtr = ptr; + for (;;) { + c = toAscii(enc, ptr, end); + if (c == -1) { + *nextTokPtr = ptr; + return 0; + } + if (c == ASCII_EQUALS) { + *nameEndPtr = ptr; + break; + } + if (isSpace(c)) { + *nameEndPtr = ptr; + do { + ptr += enc->minBytesPerChar; + } while (isSpace(c = toAscii(enc, ptr, end))); + if (c != ASCII_EQUALS) { + *nextTokPtr = ptr; + return 0; + } + break; + } + ptr += enc->minBytesPerChar; + } + if (ptr == *namePtr) { + *nextTokPtr = ptr; + return 0; + } + ptr += enc->minBytesPerChar; + c = toAscii(enc, ptr, end); + while (isSpace(c)) { + ptr += enc->minBytesPerChar; + c = toAscii(enc, ptr, end); + } + if (c != ASCII_QUOT && c != ASCII_APOS) { + *nextTokPtr = ptr; + return 0; + } + open = c; + ptr += enc->minBytesPerChar; + *valPtr = ptr; + for (;; ptr += enc->minBytesPerChar) { + c = toAscii(enc, ptr, end); + if (c == open) + break; + if (!(ASCII_a <= c && c <= ASCII_z) + && !(ASCII_A <= c && c <= ASCII_Z) + && !(ASCII_0 <= c && c <= ASCII_9) + && c != ASCII_PERIOD + && c != ASCII_MINUS + && c != ASCII_UNDERSCORE) { + *nextTokPtr = ptr; + return 0; + } + } + *nextTokPtr = ptr + enc->minBytesPerChar; + return 1; +} + +static const char KW_version[] = { + ASCII_v, ASCII_e, ASCII_r, ASCII_s, ASCII_i, ASCII_o, ASCII_n, '\0' +}; + +static const char KW_encoding[] = { + ASCII_e, ASCII_n, ASCII_c, ASCII_o, ASCII_d, ASCII_i, ASCII_n, ASCII_g, '\0' +}; + +static const char KW_standalone[] = { + ASCII_s, ASCII_t, ASCII_a, ASCII_n, ASCII_d, ASCII_a, ASCII_l, ASCII_o, ASCII_n, ASCII_e, '\0' +}; + +static const char KW_yes[] = { + ASCII_y, ASCII_e, ASCII_s, '\0' +}; + +static const char KW_no[] = { + ASCII_n, ASCII_o, '\0' +}; + +static +int doParseXmlDecl(const ENCODING *(*encodingFinder)(const ENCODING *, + const char *, + const char *), + int isGeneralTextEntity, + const ENCODING *enc, + const char *ptr, + const char *end, + const char **badPtr, + const char **versionPtr, + const char **versionEndPtr, + const char **encodingName, + const ENCODING **encoding, + int *standalone) +{ + const char *val = 0; + const char *name = 0; + const char *nameEnd = 0; + ptr += 5 * enc->minBytesPerChar; + end -= 2 * enc->minBytesPerChar; + if (!parsePseudoAttribute(enc, ptr, end, &name, &nameEnd, &val, &ptr) || !name) { + *badPtr = ptr; + return 0; + } + if (!XmlNameMatchesAscii(enc, name, nameEnd, KW_version)) { + if (!isGeneralTextEntity) { + *badPtr = name; + return 0; + } + } + else { + if (versionPtr) + *versionPtr = val; + if (versionEndPtr) + *versionEndPtr = ptr; + if (!parsePseudoAttribute(enc, ptr, end, &name, &nameEnd, &val, &ptr)) { + *badPtr = ptr; + return 0; + } + if (!name) { + if (isGeneralTextEntity) { + /* a TextDecl must have an EncodingDecl */ + *badPtr = ptr; + return 0; + } + return 1; + } + } + if (XmlNameMatchesAscii(enc, name, nameEnd, KW_encoding)) { + int c = toAscii(enc, val, end); + if (!(ASCII_a <= c && c <= ASCII_z) && !(ASCII_A <= c && c <= ASCII_Z)) { + *badPtr = val; + return 0; + } + if (encodingName) + *encodingName = val; + if (encoding) + *encoding = encodingFinder(enc, val, ptr - enc->minBytesPerChar); + if (!parsePseudoAttribute(enc, ptr, end, &name, &nameEnd, &val, &ptr)) { + *badPtr = ptr; + return 0; + } + if (!name) + return 1; + } + if (!XmlNameMatchesAscii(enc, name, nameEnd, KW_standalone) || isGeneralTextEntity) { + *badPtr = name; + return 0; + } + if (XmlNameMatchesAscii(enc, val, ptr - enc->minBytesPerChar, KW_yes)) { + if (standalone) + *standalone = 1; + } + else if (XmlNameMatchesAscii(enc, val, ptr - enc->minBytesPerChar, KW_no)) { + if (standalone) + *standalone = 0; + } + else { + *badPtr = val; + return 0; + } + while (isSpace(toAscii(enc, ptr, end))) + ptr += enc->minBytesPerChar; + if (ptr != end) { + *badPtr = ptr; + return 0; + } + return 1; +} + +static +int checkCharRefNumber(int result) +{ + switch (result >> 8) { + case 0xD8: case 0xD9: case 0xDA: case 0xDB: + case 0xDC: case 0xDD: case 0xDE: case 0xDF: + return -1; + case 0: + if (latin1_encoding.type[result] == BT_NONXML) + return -1; + break; + case 0xFF: + if (result == 0xFFFE || result == 0xFFFF) + return -1; + break; + } + return result; +} + +int XmlUtf8Encode(int c, char *buf) +{ + enum { + /* minN is minimum legal resulting value for N byte sequence */ + min2 = 0x80, + min3 = 0x800, + min4 = 0x10000 + }; + + if (c < 0) + return 0; + if (c < min2) { + buf[0] = (c | UTF8_cval1); + return 1; + } + if (c < min3) { + buf[0] = ((c >> 6) | UTF8_cval2); + buf[1] = ((c & 0x3f) | 0x80); + return 2; + } + if (c < min4) { + buf[0] = ((c >> 12) | UTF8_cval3); + buf[1] = (((c >> 6) & 0x3f) | 0x80); + buf[2] = ((c & 0x3f) | 0x80); + return 3; + } + if (c < 0x110000) { + buf[0] = ((c >> 18) | UTF8_cval4); + buf[1] = (((c >> 12) & 0x3f) | 0x80); + buf[2] = (((c >> 6) & 0x3f) | 0x80); + buf[3] = ((c & 0x3f) | 0x80); + return 4; + } + return 0; +} + +int XmlUtf16Encode(int charNum, unsigned short *buf) +{ + if (charNum < 0) + return 0; + if (charNum < 0x10000) { + buf[0] = charNum; + return 1; + } + if (charNum < 0x110000) { + charNum -= 0x10000; + buf[0] = (charNum >> 10) + 0xD800; + buf[1] = (charNum & 0x3FF) + 0xDC00; + return 2; + } + return 0; +} + +struct unknown_encoding { + struct normal_encoding normal; + int (*convert)(void *userData, const char *p); + void *userData; + unsigned short utf16[256]; + char utf8[256][4]; +}; + +int XmlSizeOfUnknownEncoding(void) +{ + return sizeof(struct unknown_encoding); +} + +static +int unknown_isName(const ENCODING *enc, const char *p) +{ + int c = ((const struct unknown_encoding *)enc) + ->convert(((const struct unknown_encoding *)enc)->userData, p); + if (c & ~0xFFFF) + return 0; + return UCS2_GET_NAMING(namePages, c >> 8, c & 0xFF); +} + +static +int unknown_isNmstrt(const ENCODING *enc, const char *p) +{ + int c = ((const struct unknown_encoding *)enc) + ->convert(((const struct unknown_encoding *)enc)->userData, p); + if (c & ~0xFFFF) + return 0; + return UCS2_GET_NAMING(nmstrtPages, c >> 8, c & 0xFF); +} + +static +int unknown_isInvalid(const ENCODING *enc, const char *p) +{ + int c = ((const struct unknown_encoding *)enc) + ->convert(((const struct unknown_encoding *)enc)->userData, p); + return (c & ~0xFFFF) || checkCharRefNumber(c) < 0; +} + +static +void unknown_toUtf8(const ENCODING *enc, + const char **fromP, const char *fromLim, + char **toP, const char *toLim) +{ + char buf[XML_UTF8_ENCODE_MAX]; + for (;;) { + const char *utf8; + int n; + if (*fromP == fromLim) + break; + utf8 = ((const struct unknown_encoding *)enc)->utf8[(unsigned char)**fromP]; + n = *utf8++; + if (n == 0) { + int c = ((const struct unknown_encoding *)enc) + ->convert(((const struct unknown_encoding *)enc)->userData, *fromP); + n = XmlUtf8Encode(c, buf); + if (n > toLim - *toP) + break; + utf8 = buf; + *fromP += ((const struct normal_encoding *)enc)->type[(unsigned char)**fromP] + - (BT_LEAD2 - 2); + } + else { + if (n > toLim - *toP) + break; + (*fromP)++; + } + do { + *(*toP)++ = *utf8++; + } while (--n != 0); + } +} + +static +void unknown_toUtf16(const ENCODING *enc, + const char **fromP, const char *fromLim, + unsigned short **toP, const unsigned short *toLim) +{ + while (*fromP != fromLim && *toP != toLim) { + unsigned short c + = ((const struct unknown_encoding *)enc)->utf16[(unsigned char)**fromP]; + if (c == 0) { + c = (unsigned short)((const struct unknown_encoding *)enc) + ->convert(((const struct unknown_encoding *)enc)->userData, *fromP); + *fromP += ((const struct normal_encoding *)enc)->type[(unsigned char)**fromP] + - (BT_LEAD2 - 2); + } + else + (*fromP)++; + *(*toP)++ = c; + } +} + +ENCODING * +XmlInitUnknownEncoding(void *mem, + int *table, + int (*convert)(void *userData, const char *p), + void *userData) +{ + int i; + struct unknown_encoding *e = mem; + for (i = 0; i < (int)sizeof(struct normal_encoding); i++) + ((char *)mem)[i] = ((char *)&latin1_encoding)[i]; + for (i = 0; i < 128; i++) + if (latin1_encoding.type[i] != BT_OTHER + && latin1_encoding.type[i] != BT_NONXML + && table[i] != i) + return 0; + for (i = 0; i < 256; i++) { + int c = table[i]; + if (c == -1) { + e->normal.type[i] = BT_MALFORM; + /* This shouldn't really get used. */ + e->utf16[i] = 0xFFFF; + e->utf8[i][0] = 1; + e->utf8[i][1] = 0; + } + else if (c < 0) { + if (c < -4) + return 0; + e->normal.type[i] = BT_LEAD2 - (c + 2); + e->utf8[i][0] = 0; + e->utf16[i] = 0; + } + else if (c < 0x80) { + if (latin1_encoding.type[c] != BT_OTHER + && latin1_encoding.type[c] != BT_NONXML + && c != i) + return 0; + e->normal.type[i] = latin1_encoding.type[c]; + e->utf8[i][0] = 1; + e->utf8[i][1] = (char)c; + e->utf16[i] = c == 0 ? 0xFFFF : c; + } + else if (checkCharRefNumber(c) < 0) { + e->normal.type[i] = BT_NONXML; + /* This shouldn't really get used. */ + e->utf16[i] = 0xFFFF; + e->utf8[i][0] = 1; + e->utf8[i][1] = 0; + } + else { + if (c > 0xFFFF) + return 0; + if (UCS2_GET_NAMING(nmstrtPages, c >> 8, c & 0xff)) + e->normal.type[i] = BT_NMSTRT; + else if (UCS2_GET_NAMING(namePages, c >> 8, c & 0xff)) + e->normal.type[i] = BT_NAME; + else + e->normal.type[i] = BT_OTHER; + e->utf8[i][0] = (char)XmlUtf8Encode(c, e->utf8[i] + 1); + e->utf16[i] = c; + } + } + e->userData = userData; + e->convert = convert; + if (convert) { + e->normal.isName2 = unknown_isName; + e->normal.isName3 = unknown_isName; + e->normal.isName4 = unknown_isName; + e->normal.isNmstrt2 = unknown_isNmstrt; + e->normal.isNmstrt3 = unknown_isNmstrt; + e->normal.isNmstrt4 = unknown_isNmstrt; + e->normal.isInvalid2 = unknown_isInvalid; + e->normal.isInvalid3 = unknown_isInvalid; + e->normal.isInvalid4 = unknown_isInvalid; + } + e->normal.enc.utf8Convert = unknown_toUtf8; + e->normal.enc.utf16Convert = unknown_toUtf16; + return &(e->normal.enc); +} + +/* If this enumeration is changed, getEncodingIndex and encodings +must also be changed. */ +enum { + UNKNOWN_ENC = -1, + ISO_8859_1_ENC = 0, + US_ASCII_ENC, + UTF_8_ENC, + UTF_16_ENC, + UTF_16BE_ENC, + UTF_16LE_ENC, + /* must match encodingNames up to here */ + NO_ENC +}; + +static const char KW_ISO_8859_1[] = { + ASCII_I, ASCII_S, ASCII_O, ASCII_MINUS, ASCII_8, ASCII_8, ASCII_5, ASCII_9, ASCII_MINUS, ASCII_1, '\0' +}; +static const char KW_US_ASCII[] = { + ASCII_U, ASCII_S, ASCII_MINUS, ASCII_A, ASCII_S, ASCII_C, ASCII_I, ASCII_I, '\0' +}; +static const char KW_UTF_8[] = { + ASCII_U, ASCII_T, ASCII_F, ASCII_MINUS, ASCII_8, '\0' +}; +static const char KW_UTF_16[] = { + ASCII_U, ASCII_T, ASCII_F, ASCII_MINUS, ASCII_1, ASCII_6, '\0' +}; +static const char KW_UTF_16BE[] = { + ASCII_U, ASCII_T, ASCII_F, ASCII_MINUS, ASCII_1, ASCII_6, ASCII_B, ASCII_E, '\0' +}; +static const char KW_UTF_16LE[] = { + ASCII_U, ASCII_T, ASCII_F, ASCII_MINUS, ASCII_1, ASCII_6, ASCII_L, ASCII_E, '\0' +}; + +static +int getEncodingIndex(const char *name) +{ + static const char *encodingNames[] = { + KW_ISO_8859_1, + KW_US_ASCII, + KW_UTF_8, + KW_UTF_16, + KW_UTF_16BE, + KW_UTF_16LE, + }; + int i; + if (name == 0) + return NO_ENC; + for (i = 0; i < (int)(sizeof(encodingNames)/sizeof(encodingNames[0])); i++) + if (streqci(name, encodingNames[i])) + return i; + return UNKNOWN_ENC; +} + +/* For binary compatibility, we store the index of the encoding specified +at initialization in the isUtf16 member. */ + +#define INIT_ENC_INDEX(enc) ((int)(enc)->initEnc.isUtf16) +#define SET_INIT_ENC_INDEX(enc, i) ((enc)->initEnc.isUtf16 = (char)i) + +/* This is what detects the encoding. +encodingTable maps from encoding indices to encodings; +INIT_ENC_INDEX(enc) is the index of the external (protocol) specified encoding; +state is XML_CONTENT_STATE if we're parsing an external text entity, +and XML_PROLOG_STATE otherwise. +*/ + + +static +int initScan(const ENCODING **encodingTable, + const INIT_ENCODING *enc, + int state, + const char *ptr, + const char *end, + const char **nextTokPtr) +{ + const ENCODING **encPtr; + + if (ptr == end) + return XML_TOK_NONE; + encPtr = enc->encPtr; + if (ptr + 1 == end) { + /* only a single byte available for auto-detection */ +#ifndef XML_DTD /* FIXME */ + /* a well-formed document entity must have more than one byte */ + if (state != XML_CONTENT_STATE) + return XML_TOK_PARTIAL; +#endif + /* so we're parsing an external text entity... */ + /* if UTF-16 was externally specified, then we need at least 2 bytes */ + switch (INIT_ENC_INDEX(enc)) { + case UTF_16_ENC: + case UTF_16LE_ENC: + case UTF_16BE_ENC: + return XML_TOK_PARTIAL; + } + switch ((unsigned char)*ptr) { + case 0xFE: + case 0xFF: + case 0xEF: /* possibly first byte of UTF-8 BOM */ + if (INIT_ENC_INDEX(enc) == ISO_8859_1_ENC + && state == XML_CONTENT_STATE) + break; + /* fall through */ + case 0x00: + case 0x3C: + return XML_TOK_PARTIAL; + } + } + else { + switch (((unsigned char)ptr[0] << 8) | (unsigned char)ptr[1]) { + case 0xFEFF: + if (INIT_ENC_INDEX(enc) == ISO_8859_1_ENC + && state == XML_CONTENT_STATE) + break; + *nextTokPtr = ptr + 2; + *encPtr = encodingTable[UTF_16BE_ENC]; + return XML_TOK_BOM; + /* 00 3C is handled in the default case */ + case 0x3C00: + if ((INIT_ENC_INDEX(enc) == UTF_16BE_ENC + || INIT_ENC_INDEX(enc) == UTF_16_ENC) + && state == XML_CONTENT_STATE) + break; + *encPtr = encodingTable[UTF_16LE_ENC]; + return XmlTok(*encPtr, state, ptr, end, nextTokPtr); + case 0xFFFE: + if (INIT_ENC_INDEX(enc) == ISO_8859_1_ENC + && state == XML_CONTENT_STATE) + break; + *nextTokPtr = ptr + 2; + *encPtr = encodingTable[UTF_16LE_ENC]; + return XML_TOK_BOM; + case 0xEFBB: + /* Maybe a UTF-8 BOM (EF BB BF) */ + /* If there's an explicitly specified (external) encoding + of ISO-8859-1 or some flavour of UTF-16 + and this is an external text entity, + don't look for the BOM, + because it might be a legal data. */ + if (state == XML_CONTENT_STATE) { + int e = INIT_ENC_INDEX(enc); + if (e == ISO_8859_1_ENC || e == UTF_16BE_ENC || e == UTF_16LE_ENC || e == UTF_16_ENC) + break; + } + if (ptr + 2 == end) + return XML_TOK_PARTIAL; + if ((unsigned char)ptr[2] == 0xBF) { + *encPtr = encodingTable[UTF_8_ENC]; + return XML_TOK_BOM; + } + break; + default: + if (ptr[0] == '\0') { + /* 0 isn't a legal data character. Furthermore a document entity can only + start with ASCII characters. So the only way this can fail to be big-endian + UTF-16 if it it's an external parsed general entity that's labelled as + UTF-16LE. */ + if (state == XML_CONTENT_STATE && INIT_ENC_INDEX(enc) == UTF_16LE_ENC) + break; + *encPtr = encodingTable[UTF_16BE_ENC]; + return XmlTok(*encPtr, state, ptr, end, nextTokPtr); + } + else if (ptr[1] == '\0') { + /* We could recover here in the case: + - parsing an external entity + - second byte is 0 + - no externally specified encoding + - no encoding declaration + by assuming UTF-16LE. But we don't, because this would mean when + presented just with a single byte, we couldn't reliably determine + whether we needed further bytes. */ + if (state == XML_CONTENT_STATE) + break; + *encPtr = encodingTable[UTF_16LE_ENC]; + return XmlTok(*encPtr, state, ptr, end, nextTokPtr); + } + break; + } + } + *encPtr = encodingTable[INIT_ENC_INDEX(enc)]; + return XmlTok(*encPtr, state, ptr, end, nextTokPtr); +} + + +#define NS(x) x +#define ns(x) x +#include "xmltok_ns.c" +#undef NS +#undef ns + +#ifdef XML_NS + +#define NS(x) x ## NS +#define ns(x) x ## _ns + +#include "xmltok_ns.c" + +#undef NS +#undef ns + +ENCODING * +XmlInitUnknownEncodingNS(void *mem, + int *table, + int (*convert)(void *userData, const char *p), + void *userData) +{ + ENCODING *enc = XmlInitUnknownEncoding(mem, table, convert, userData); + if (enc) + ((struct normal_encoding *)enc)->type[ASCII_COLON] = BT_COLON; + return enc; +} + +#endif /* XML_NS */ diff --git a/Code/BF2/External/expat/xmltok.h b/Code/BF2/External/expat/xmltok.h new file mode 100644 index 000000000..8b02324c3 --- /dev/null +++ b/Code/BF2/External/expat/xmltok.h @@ -0,0 +1,299 @@ +/* +Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd +See the file COPYING for copying permission. +*/ + +#ifndef XmlTok_INCLUDED +#define XmlTok_INCLUDED 1 + +#ifdef __cplusplus +extern "C" { +#endif + +/* The following token may be returned by XmlContentTok */ +#define XML_TOK_TRAILING_RSQB -5 /* ] or ]] at the end of the scan; might be start of + illegal ]]> sequence */ +/* The following tokens may be returned by both XmlPrologTok and XmlContentTok */ +#define XML_TOK_NONE -4 /* The string to be scanned is empty */ +#define XML_TOK_TRAILING_CR -3 /* A CR at the end of the scan; + might be part of CRLF sequence */ +#define XML_TOK_PARTIAL_CHAR -2 /* only part of a multibyte sequence */ +#define XML_TOK_PARTIAL -1 /* only part of a token */ +#define XML_TOK_INVALID 0 + +/* The following tokens are returned by XmlContentTok; some are also + returned by XmlAttributeValueTok, XmlEntityTok, XmlCdataSectionTok */ + +#define XML_TOK_START_TAG_WITH_ATTS 1 +#define XML_TOK_START_TAG_NO_ATTS 2 +#define XML_TOK_EMPTY_ELEMENT_WITH_ATTS 3 /* empty element tag */ +#define XML_TOK_EMPTY_ELEMENT_NO_ATTS 4 +#define XML_TOK_END_TAG 5 +#define XML_TOK_DATA_CHARS 6 +#define XML_TOK_DATA_NEWLINE 7 +#define XML_TOK_CDATA_SECT_OPEN 8 +#define XML_TOK_ENTITY_REF 9 +#define XML_TOK_CHAR_REF 10 /* numeric character reference */ + +/* The following tokens may be returned by both XmlPrologTok and XmlContentTok */ +#define XML_TOK_PI 11 /* processing instruction */ +#define XML_TOK_XML_DECL 12 /* XML decl or text decl */ +#define XML_TOK_COMMENT 13 +#define XML_TOK_BOM 14 /* Byte order mark */ + +/* The following tokens are returned only by XmlPrologTok */ +#define XML_TOK_PROLOG_S 15 +#define XML_TOK_DECL_OPEN 16 /* */ +#define XML_TOK_NAME 18 +#define XML_TOK_NMTOKEN 19 +#define XML_TOK_POUND_NAME 20 /* #name */ +#define XML_TOK_OR 21 /* | */ +#define XML_TOK_PERCENT 22 +#define XML_TOK_OPEN_PAREN 23 +#define XML_TOK_CLOSE_PAREN 24 +#define XML_TOK_OPEN_BRACKET 25 +#define XML_TOK_CLOSE_BRACKET 26 +#define XML_TOK_LITERAL 27 +#define XML_TOK_PARAM_ENTITY_REF 28 +#define XML_TOK_INSTANCE_START 29 + +/* The following occur only in element type declarations */ +#define XML_TOK_NAME_QUESTION 30 /* name? */ +#define XML_TOK_NAME_ASTERISK 31 /* name* */ +#define XML_TOK_NAME_PLUS 32 /* name+ */ +#define XML_TOK_COND_SECT_OPEN 33 /* */ +#define XML_TOK_CLOSE_PAREN_QUESTION 35 /* )? */ +#define XML_TOK_CLOSE_PAREN_ASTERISK 36 /* )* */ +#define XML_TOK_CLOSE_PAREN_PLUS 37 /* )+ */ +#define XML_TOK_COMMA 38 + +/* The following token is returned only by XmlAttributeValueTok */ +#define XML_TOK_ATTRIBUTE_VALUE_S 39 + +/* The following token is returned only by XmlCdataSectionTok */ +#define XML_TOK_CDATA_SECT_CLOSE 40 + +/* With namespace processing this is returned by XmlPrologTok + for a name with a colon. */ +#define XML_TOK_PREFIXED_NAME 41 + +#ifdef XML_DTD +#define XML_TOK_IGNORE_SECT 42 +#endif /* XML_DTD */ + +#ifdef XML_DTD +#define XML_N_STATES 4 +#else /* not XML_DTD */ +#define XML_N_STATES 3 +#endif /* not XML_DTD */ + +#define XML_PROLOG_STATE 0 +#define XML_CONTENT_STATE 1 +#define XML_CDATA_SECTION_STATE 2 +#ifdef XML_DTD +#define XML_IGNORE_SECTION_STATE 3 +#endif /* XML_DTD */ + +#define XML_N_LITERAL_TYPES 2 +#define XML_ATTRIBUTE_VALUE_LITERAL 0 +#define XML_ENTITY_VALUE_LITERAL 1 + +/* The size of the buffer passed to XmlUtf8Encode must be at least this. */ +#define XML_UTF8_ENCODE_MAX 4 +/* The size of the buffer passed to XmlUtf16Encode must be at least this. */ +#define XML_UTF16_ENCODE_MAX 2 + +typedef struct position { + /* first line and first column are 0 not 1 */ + unsigned long lineNumber; + unsigned long columnNumber; +} POSITION; + +typedef struct { + const char *name; + const char *valuePtr; + const char *valueEnd; + char normalized; +} ATTRIBUTE; + +struct encoding; +typedef struct encoding ENCODING; + +struct encoding { + int (*scanners[XML_N_STATES])(const ENCODING *, + const char *, + const char *, + const char **); + int (*literalScanners[XML_N_LITERAL_TYPES])(const ENCODING *, + const char *, + const char *, + const char **); + int (*sameName)(const ENCODING *, + const char *, const char *); + int (*nameMatchesAscii)(const ENCODING *, + const char *, const char *, const char *); + int (*nameLength)(const ENCODING *, const char *); + const char *(*skipS)(const ENCODING *, const char *); + int (*getAtts)(const ENCODING *enc, const char *ptr, + int attsMax, ATTRIBUTE *atts); + int (*charRefNumber)(const ENCODING *enc, const char *ptr); + int (*predefinedEntityName)(const ENCODING *, const char *, const char *); + void (*updatePosition)(const ENCODING *, + const char *ptr, + const char *end, + POSITION *); + int (*isPublicId)(const ENCODING *enc, const char *ptr, const char *end, + const char **badPtr); + void (*utf8Convert)(const ENCODING *enc, + const char **fromP, + const char *fromLim, + char **toP, + const char *toLim); + void (*utf16Convert)(const ENCODING *enc, + const char **fromP, + const char *fromLim, + unsigned short **toP, + const unsigned short *toLim); + int minBytesPerChar; + char isUtf8; + char isUtf16; +}; + +/* +Scan the string starting at ptr until the end of the next complete token, +but do not scan past eptr. Return an integer giving the type of token. + +Return XML_TOK_NONE when ptr == eptr; nextTokPtr will not be set. + +Return XML_TOK_PARTIAL when the string does not contain a complete token; +nextTokPtr will not be set. + +Return XML_TOK_INVALID when the string does not start a valid token; nextTokPtr +will be set to point to the character which made the token invalid. + +Otherwise the string starts with a valid token; nextTokPtr will be set to point +to the character following the end of that token. + +Each data character counts as a single token, but adjacent data characters +may be returned together. Similarly for characters in the prolog outside +literals, comments and processing instructions. +*/ + + +#define XmlTok(enc, state, ptr, end, nextTokPtr) \ + (((enc)->scanners[state])(enc, ptr, end, nextTokPtr)) + +#define XmlPrologTok(enc, ptr, end, nextTokPtr) \ + XmlTok(enc, XML_PROLOG_STATE, ptr, end, nextTokPtr) + +#define XmlContentTok(enc, ptr, end, nextTokPtr) \ + XmlTok(enc, XML_CONTENT_STATE, ptr, end, nextTokPtr) + +#define XmlCdataSectionTok(enc, ptr, end, nextTokPtr) \ + XmlTok(enc, XML_CDATA_SECTION_STATE, ptr, end, nextTokPtr) + +#ifdef XML_DTD + +#define XmlIgnoreSectionTok(enc, ptr, end, nextTokPtr) \ + XmlTok(enc, XML_IGNORE_SECTION_STATE, ptr, end, nextTokPtr) + +#endif /* XML_DTD */ + +/* This is used for performing a 2nd-level tokenization on +the content of a literal that has already been returned by XmlTok. */ + +#define XmlLiteralTok(enc, literalType, ptr, end, nextTokPtr) \ + (((enc)->literalScanners[literalType])(enc, ptr, end, nextTokPtr)) + +#define XmlAttributeValueTok(enc, ptr, end, nextTokPtr) \ + XmlLiteralTok(enc, XML_ATTRIBUTE_VALUE_LITERAL, ptr, end, nextTokPtr) + +#define XmlEntityValueTok(enc, ptr, end, nextTokPtr) \ + XmlLiteralTok(enc, XML_ENTITY_VALUE_LITERAL, ptr, end, nextTokPtr) + +#define XmlSameName(enc, ptr1, ptr2) (((enc)->sameName)(enc, ptr1, ptr2)) + +#define XmlNameMatchesAscii(enc, ptr1, end1, ptr2) \ + (((enc)->nameMatchesAscii)(enc, ptr1, end1, ptr2)) + +#define XmlNameLength(enc, ptr) \ + (((enc)->nameLength)(enc, ptr)) + +#define XmlSkipS(enc, ptr) \ + (((enc)->skipS)(enc, ptr)) + +#define XmlGetAttributes(enc, ptr, attsMax, atts) \ + (((enc)->getAtts)(enc, ptr, attsMax, atts)) + +#define XmlCharRefNumber(enc, ptr) \ + (((enc)->charRefNumber)(enc, ptr)) + +#define XmlPredefinedEntityName(enc, ptr, end) \ + (((enc)->predefinedEntityName)(enc, ptr, end)) + +#define XmlUpdatePosition(enc, ptr, end, pos) \ + (((enc)->updatePosition)(enc, ptr, end, pos)) + +#define XmlIsPublicId(enc, ptr, end, badPtr) \ + (((enc)->isPublicId)(enc, ptr, end, badPtr)) + +#define XmlUtf8Convert(enc, fromP, fromLim, toP, toLim) \ + (((enc)->utf8Convert)(enc, fromP, fromLim, toP, toLim)) + +#define XmlUtf16Convert(enc, fromP, fromLim, toP, toLim) \ + (((enc)->utf16Convert)(enc, fromP, fromLim, toP, toLim)) + +typedef struct { + ENCODING initEnc; + const ENCODING **encPtr; +} INIT_ENCODING; + +int XmlParseXmlDecl(int isGeneralTextEntity, + const ENCODING *enc, + const char *ptr, + const char *end, + const char **badPtr, + const char **versionPtr, + const char **versionEndPtr, + const char **encodingNamePtr, + const ENCODING **namedEncodingPtr, + int *standalonePtr); + +int XmlInitEncoding(INIT_ENCODING *, const ENCODING **, const char *name); +const ENCODING *XmlGetUtf8InternalEncoding(void); +const ENCODING *XmlGetUtf16InternalEncoding(void); +int XmlUtf8Encode(int charNumber, char *buf); +int XmlUtf16Encode(int charNumber, unsigned short *buf); + +int XmlSizeOfUnknownEncoding(void); +ENCODING * +XmlInitUnknownEncoding(void *mem, + int *table, + int (*conv)(void *userData, const char *p), + void *userData); + +int XmlParseXmlDeclNS(int isGeneralTextEntity, + const ENCODING *enc, + const char *ptr, + const char *end, + const char **badPtr, + const char **versionPtr, + const char **versionEndPtr, + const char **encodingNamePtr, + const ENCODING **namedEncodingPtr, + int *standalonePtr); +int XmlInitEncodingNS(INIT_ENCODING *, const ENCODING **, const char *name); +const ENCODING *XmlGetUtf8InternalEncodingNS(void); +const ENCODING *XmlGetUtf16InternalEncodingNS(void); +ENCODING * +XmlInitUnknownEncodingNS(void *mem, + int *table, + int (*conv)(void *userData, const char *p), + void *userData); +#ifdef __cplusplus +} +#endif + +#endif /* not XmlTok_INCLUDED */ diff --git a/Code/BF2/External/expat/xmltok_impl.c b/Code/BF2/External/expat/xmltok_impl.c new file mode 100644 index 000000000..73617f74c --- /dev/null +++ b/Code/BF2/External/expat/xmltok_impl.c @@ -0,0 +1,1765 @@ +/* +Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd +See the file COPYING for copying permission. +*/ + +#ifndef IS_INVALID_CHAR +#define IS_INVALID_CHAR(enc, ptr, n) (0) +#endif + +#define INVALID_LEAD_CASE(n, ptr, nextTokPtr) \ + case BT_LEAD ## n: \ + if (end - ptr < n) \ + return XML_TOK_PARTIAL_CHAR; \ + if (IS_INVALID_CHAR(enc, ptr, n)) { \ + *(nextTokPtr) = (ptr); \ + return XML_TOK_INVALID; \ + } \ + ptr += n; \ + break; + +#define INVALID_CASES(ptr, nextTokPtr) \ + INVALID_LEAD_CASE(2, ptr, nextTokPtr) \ + INVALID_LEAD_CASE(3, ptr, nextTokPtr) \ + INVALID_LEAD_CASE(4, ptr, nextTokPtr) \ + case BT_NONXML: \ + case BT_MALFORM: \ + case BT_TRAIL: \ + *(nextTokPtr) = (ptr); \ + return XML_TOK_INVALID; + +#define CHECK_NAME_CASE(n, enc, ptr, end, nextTokPtr) \ + case BT_LEAD ## n: \ + if (end - ptr < n) \ + return XML_TOK_PARTIAL_CHAR; \ + if (!IS_NAME_CHAR(enc, ptr, n)) { \ + *nextTokPtr = ptr; \ + return XML_TOK_INVALID; \ + } \ + ptr += n; \ + break; + +#define CHECK_NAME_CASES(enc, ptr, end, nextTokPtr) \ + case BT_NONASCII: \ + if (!IS_NAME_CHAR_MINBPC(enc, ptr)) { \ + *nextTokPtr = ptr; \ + return XML_TOK_INVALID; \ + } \ + case BT_NMSTRT: \ + case BT_HEX: \ + case BT_DIGIT: \ + case BT_NAME: \ + case BT_MINUS: \ + ptr += MINBPC(enc); \ + break; \ + CHECK_NAME_CASE(2, enc, ptr, end, nextTokPtr) \ + CHECK_NAME_CASE(3, enc, ptr, end, nextTokPtr) \ + CHECK_NAME_CASE(4, enc, ptr, end, nextTokPtr) + +#define CHECK_NMSTRT_CASE(n, enc, ptr, end, nextTokPtr) \ + case BT_LEAD ## n: \ + if (end - ptr < n) \ + return XML_TOK_PARTIAL_CHAR; \ + if (!IS_NMSTRT_CHAR(enc, ptr, n)) { \ + *nextTokPtr = ptr; \ + return XML_TOK_INVALID; \ + } \ + ptr += n; \ + break; + +#define CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr) \ + case BT_NONASCII: \ + if (!IS_NMSTRT_CHAR_MINBPC(enc, ptr)) { \ + *nextTokPtr = ptr; \ + return XML_TOK_INVALID; \ + } \ + case BT_NMSTRT: \ + case BT_HEX: \ + ptr += MINBPC(enc); \ + break; \ + CHECK_NMSTRT_CASE(2, enc, ptr, end, nextTokPtr) \ + CHECK_NMSTRT_CASE(3, enc, ptr, end, nextTokPtr) \ + CHECK_NMSTRT_CASE(4, enc, ptr, end, nextTokPtr) + +#ifndef PREFIX +#define PREFIX(ident) ident +#endif + +/* ptr points to character following " */ + switch (BYTE_TYPE(enc, ptr + MINBPC(enc))) { + case BT_S: case BT_CR: case BT_LF: case BT_PERCNT: + *nextTokPtr = ptr; + return XML_TOK_INVALID; + } + /* fall through */ + case BT_S: case BT_CR: case BT_LF: + *nextTokPtr = ptr; + return XML_TOK_DECL_OPEN; + case BT_NMSTRT: + case BT_HEX: + ptr += MINBPC(enc); + break; + default: + *nextTokPtr = ptr; + return XML_TOK_INVALID; + } + } + return XML_TOK_PARTIAL; +} + +static +int PREFIX(checkPiTarget)(const ENCODING *enc, const char *ptr, const char *end, int *tokPtr) +{ + int upper = 0; + *tokPtr = XML_TOK_PI; + if (end - ptr != MINBPC(enc)*3) + return 1; + switch (BYTE_TO_ASCII(enc, ptr)) { + case ASCII_x: + break; + case ASCII_X: + upper = 1; + break; + default: + return 1; + } + ptr += MINBPC(enc); + switch (BYTE_TO_ASCII(enc, ptr)) { + case ASCII_m: + break; + case ASCII_M: + upper = 1; + break; + default: + return 1; + } + ptr += MINBPC(enc); + switch (BYTE_TO_ASCII(enc, ptr)) { + case ASCII_l: + break; + case ASCII_L: + upper = 1; + break; + default: + return 1; + } + if (upper) + return 0; + *tokPtr = XML_TOK_XML_DECL; + return 1; +} + +/* ptr points to character following " 1) { + size_t n = end - ptr; + if (n & (MINBPC(enc) - 1)) { + n &= ~(MINBPC(enc) - 1); + if (n == 0) + return XML_TOK_PARTIAL; + end = ptr + n; + } + } + switch (BYTE_TYPE(enc, ptr)) { + case BT_RSQB: + ptr += MINBPC(enc); + if (ptr == end) + return XML_TOK_PARTIAL; + if (!CHAR_MATCHES(enc, ptr, ASCII_RSQB)) + break; + ptr += MINBPC(enc); + if (ptr == end) + return XML_TOK_PARTIAL; + if (!CHAR_MATCHES(enc, ptr, ASCII_GT)) { + ptr -= MINBPC(enc); + break; + } + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_CDATA_SECT_CLOSE; + case BT_CR: + ptr += MINBPC(enc); + if (ptr == end) + return XML_TOK_PARTIAL; + if (BYTE_TYPE(enc, ptr) == BT_LF) + ptr += MINBPC(enc); + *nextTokPtr = ptr; + return XML_TOK_DATA_NEWLINE; + case BT_LF: + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_DATA_NEWLINE; + INVALID_CASES(ptr, nextTokPtr) + default: + ptr += MINBPC(enc); + break; + } + while (ptr != end) { + switch (BYTE_TYPE(enc, ptr)) { +#define LEAD_CASE(n) \ + case BT_LEAD ## n: \ + if (end - ptr < n || IS_INVALID_CHAR(enc, ptr, n)) { \ + *nextTokPtr = ptr; \ + return XML_TOK_DATA_CHARS; \ + } \ + ptr += n; \ + break; + LEAD_CASE(2) LEAD_CASE(3) LEAD_CASE(4) +#undef LEAD_CASE + case BT_NONXML: + case BT_MALFORM: + case BT_TRAIL: + case BT_CR: + case BT_LF: + case BT_RSQB: + *nextTokPtr = ptr; + return XML_TOK_DATA_CHARS; + default: + ptr += MINBPC(enc); + break; + } + } + *nextTokPtr = ptr; + return XML_TOK_DATA_CHARS; +} + +/* ptr points to character following " 1) { + size_t n = end - ptr; + if (n & (MINBPC(enc) - 1)) { + n &= ~(MINBPC(enc) - 1); + if (n == 0) + return XML_TOK_PARTIAL; + end = ptr + n; + } + } + switch (BYTE_TYPE(enc, ptr)) { + case BT_LT: + return PREFIX(scanLt)(enc, ptr + MINBPC(enc), end, nextTokPtr); + case BT_AMP: + return PREFIX(scanRef)(enc, ptr + MINBPC(enc), end, nextTokPtr); + case BT_CR: + ptr += MINBPC(enc); + if (ptr == end) + return XML_TOK_TRAILING_CR; + if (BYTE_TYPE(enc, ptr) == BT_LF) + ptr += MINBPC(enc); + *nextTokPtr = ptr; + return XML_TOK_DATA_NEWLINE; + case BT_LF: + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_DATA_NEWLINE; + case BT_RSQB: + ptr += MINBPC(enc); + if (ptr == end) + return XML_TOK_TRAILING_RSQB; + if (!CHAR_MATCHES(enc, ptr, ASCII_RSQB)) + break; + ptr += MINBPC(enc); + if (ptr == end) + return XML_TOK_TRAILING_RSQB; + if (!CHAR_MATCHES(enc, ptr, ASCII_GT)) { + ptr -= MINBPC(enc); + break; + } + *nextTokPtr = ptr; + return XML_TOK_INVALID; + INVALID_CASES(ptr, nextTokPtr) + default: + ptr += MINBPC(enc); + break; + } + while (ptr != end) { + switch (BYTE_TYPE(enc, ptr)) { +#define LEAD_CASE(n) \ + case BT_LEAD ## n: \ + if (end - ptr < n || IS_INVALID_CHAR(enc, ptr, n)) { \ + *nextTokPtr = ptr; \ + return XML_TOK_DATA_CHARS; \ + } \ + ptr += n; \ + break; + LEAD_CASE(2) LEAD_CASE(3) LEAD_CASE(4) +#undef LEAD_CASE + case BT_RSQB: + if (ptr + MINBPC(enc) != end) { + if (!CHAR_MATCHES(enc, ptr + MINBPC(enc), ASCII_RSQB)) { + ptr += MINBPC(enc); + break; + } + if (ptr + 2*MINBPC(enc) != end) { + if (!CHAR_MATCHES(enc, ptr + 2*MINBPC(enc), ASCII_GT)) { + ptr += MINBPC(enc); + break; + } + *nextTokPtr = ptr + 2*MINBPC(enc); + return XML_TOK_INVALID; + } + } + /* fall through */ + case BT_AMP: + case BT_LT: + case BT_NONXML: + case BT_MALFORM: + case BT_TRAIL: + case BT_CR: + case BT_LF: + *nextTokPtr = ptr; + return XML_TOK_DATA_CHARS; + default: + ptr += MINBPC(enc); + break; + } + } + *nextTokPtr = ptr; + return XML_TOK_DATA_CHARS; +} + +/* ptr points to character following "%" */ + +static +int PREFIX(scanPercent)(const ENCODING *enc, const char *ptr, const char *end, + const char **nextTokPtr) +{ + if (ptr == end) + return XML_TOK_PARTIAL; + switch (BYTE_TYPE(enc, ptr)) { + CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr) + case BT_S: case BT_LF: case BT_CR: case BT_PERCNT: + *nextTokPtr = ptr; + return XML_TOK_PERCENT; + default: + *nextTokPtr = ptr; + return XML_TOK_INVALID; + } + while (ptr != end) { + switch (BYTE_TYPE(enc, ptr)) { + CHECK_NAME_CASES(enc, ptr, end, nextTokPtr) + case BT_SEMI: + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_PARAM_ENTITY_REF; + default: + *nextTokPtr = ptr; + return XML_TOK_INVALID; + } + } + return XML_TOK_PARTIAL; +} + +static +int PREFIX(scanPoundName)(const ENCODING *enc, const char *ptr, const char *end, + const char **nextTokPtr) +{ + if (ptr == end) + return XML_TOK_PARTIAL; + switch (BYTE_TYPE(enc, ptr)) { + CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr) + default: + *nextTokPtr = ptr; + return XML_TOK_INVALID; + } + while (ptr != end) { + switch (BYTE_TYPE(enc, ptr)) { + CHECK_NAME_CASES(enc, ptr, end, nextTokPtr) + case BT_CR: case BT_LF: case BT_S: + case BT_RPAR: case BT_GT: case BT_PERCNT: case BT_VERBAR: + *nextTokPtr = ptr; + return XML_TOK_POUND_NAME; + default: + *nextTokPtr = ptr; + return XML_TOK_INVALID; + } + } + return -XML_TOK_POUND_NAME; +} + +static +int PREFIX(scanLit)(int open, const ENCODING *enc, + const char *ptr, const char *end, + const char **nextTokPtr) +{ + while (ptr != end) { + int t = BYTE_TYPE(enc, ptr); + switch (t) { + INVALID_CASES(ptr, nextTokPtr) + case BT_QUOT: + case BT_APOS: + ptr += MINBPC(enc); + if (t != open) + break; + if (ptr == end) + return -XML_TOK_LITERAL; + *nextTokPtr = ptr; + switch (BYTE_TYPE(enc, ptr)) { + case BT_S: case BT_CR: case BT_LF: + case BT_GT: case BT_PERCNT: case BT_LSQB: + return XML_TOK_LITERAL; + default: + return XML_TOK_INVALID; + } + default: + ptr += MINBPC(enc); + break; + } + } + return XML_TOK_PARTIAL; +} + +static +int PREFIX(prologTok)(const ENCODING *enc, const char *ptr, const char *end, + const char **nextTokPtr) +{ + int tok; + if (ptr == end) + return XML_TOK_NONE; + if (MINBPC(enc) > 1) { + size_t n = end - ptr; + if (n & (MINBPC(enc) - 1)) { + n &= ~(MINBPC(enc) - 1); + if (n == 0) + return XML_TOK_PARTIAL; + end = ptr + n; + } + } + switch (BYTE_TYPE(enc, ptr)) { + case BT_QUOT: + return PREFIX(scanLit)(BT_QUOT, enc, ptr + MINBPC(enc), end, nextTokPtr); + case BT_APOS: + return PREFIX(scanLit)(BT_APOS, enc, ptr + MINBPC(enc), end, nextTokPtr); + case BT_LT: + { + ptr += MINBPC(enc); + if (ptr == end) + return XML_TOK_PARTIAL; + switch (BYTE_TYPE(enc, ptr)) { + case BT_EXCL: + return PREFIX(scanDecl)(enc, ptr + MINBPC(enc), end, nextTokPtr); + case BT_QUEST: + return PREFIX(scanPi)(enc, ptr + MINBPC(enc), end, nextTokPtr); + case BT_NMSTRT: + case BT_HEX: + case BT_NONASCII: + case BT_LEAD2: + case BT_LEAD3: + case BT_LEAD4: + *nextTokPtr = ptr - MINBPC(enc); + return XML_TOK_INSTANCE_START; + } + *nextTokPtr = ptr; + return XML_TOK_INVALID; + } + case BT_CR: + if (ptr + MINBPC(enc) == end) + return -XML_TOK_PROLOG_S; + /* fall through */ + case BT_S: case BT_LF: + for (;;) { + ptr += MINBPC(enc); + if (ptr == end) + break; + switch (BYTE_TYPE(enc, ptr)) { + case BT_S: case BT_LF: + break; + case BT_CR: + /* don't split CR/LF pair */ + if (ptr + MINBPC(enc) != end) + break; + /* fall through */ + default: + *nextTokPtr = ptr; + return XML_TOK_PROLOG_S; + } + } + *nextTokPtr = ptr; + return XML_TOK_PROLOG_S; + case BT_PERCNT: + return PREFIX(scanPercent)(enc, ptr + MINBPC(enc), end, nextTokPtr); + case BT_COMMA: + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_COMMA; + case BT_LSQB: + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_OPEN_BRACKET; + case BT_RSQB: + ptr += MINBPC(enc); + if (ptr == end) + return -XML_TOK_CLOSE_BRACKET; + if (CHAR_MATCHES(enc, ptr, ASCII_RSQB)) { + if (ptr + MINBPC(enc) == end) + return XML_TOK_PARTIAL; + if (CHAR_MATCHES(enc, ptr + MINBPC(enc), ASCII_GT)) { + *nextTokPtr = ptr + 2*MINBPC(enc); + return XML_TOK_COND_SECT_CLOSE; + } + } + *nextTokPtr = ptr; + return XML_TOK_CLOSE_BRACKET; + case BT_LPAR: + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_OPEN_PAREN; + case BT_RPAR: + ptr += MINBPC(enc); + if (ptr == end) + return -XML_TOK_CLOSE_PAREN; + switch (BYTE_TYPE(enc, ptr)) { + case BT_AST: + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_CLOSE_PAREN_ASTERISK; + case BT_QUEST: + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_CLOSE_PAREN_QUESTION; + case BT_PLUS: + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_CLOSE_PAREN_PLUS; + case BT_CR: case BT_LF: case BT_S: + case BT_GT: case BT_COMMA: case BT_VERBAR: + case BT_RPAR: + *nextTokPtr = ptr; + return XML_TOK_CLOSE_PAREN; + } + *nextTokPtr = ptr; + return XML_TOK_INVALID; + case BT_VERBAR: + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_OR; + case BT_GT: + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_DECL_CLOSE; + case BT_NUM: + return PREFIX(scanPoundName)(enc, ptr + MINBPC(enc), end, nextTokPtr); +#define LEAD_CASE(n) \ + case BT_LEAD ## n: \ + if (end - ptr < n) \ + return XML_TOK_PARTIAL_CHAR; \ + if (IS_NMSTRT_CHAR(enc, ptr, n)) { \ + ptr += n; \ + tok = XML_TOK_NAME; \ + break; \ + } \ + if (IS_NAME_CHAR(enc, ptr, n)) { \ + ptr += n; \ + tok = XML_TOK_NMTOKEN; \ + break; \ + } \ + *nextTokPtr = ptr; \ + return XML_TOK_INVALID; + LEAD_CASE(2) LEAD_CASE(3) LEAD_CASE(4) +#undef LEAD_CASE + case BT_NMSTRT: + case BT_HEX: + tok = XML_TOK_NAME; + ptr += MINBPC(enc); + break; + case BT_DIGIT: + case BT_NAME: + case BT_MINUS: +#ifdef XML_NS + case BT_COLON: +#endif + tok = XML_TOK_NMTOKEN; + ptr += MINBPC(enc); + break; + case BT_NONASCII: + if (IS_NMSTRT_CHAR_MINBPC(enc, ptr)) { + ptr += MINBPC(enc); + tok = XML_TOK_NAME; + break; + } + if (IS_NAME_CHAR_MINBPC(enc, ptr)) { + ptr += MINBPC(enc); + tok = XML_TOK_NMTOKEN; + break; + } + /* fall through */ + default: + *nextTokPtr = ptr; + return XML_TOK_INVALID; + } + while (ptr != end) { + switch (BYTE_TYPE(enc, ptr)) { + CHECK_NAME_CASES(enc, ptr, end, nextTokPtr) + case BT_GT: case BT_RPAR: case BT_COMMA: + case BT_VERBAR: case BT_LSQB: case BT_PERCNT: + case BT_S: case BT_CR: case BT_LF: + *nextTokPtr = ptr; + return tok; +#ifdef XML_NS + case BT_COLON: + ptr += MINBPC(enc); + switch (tok) { + case XML_TOK_NAME: + if (ptr == end) + return XML_TOK_PARTIAL; + tok = XML_TOK_PREFIXED_NAME; + switch (BYTE_TYPE(enc, ptr)) { + CHECK_NAME_CASES(enc, ptr, end, nextTokPtr) + default: + tok = XML_TOK_NMTOKEN; + break; + } + break; + case XML_TOK_PREFIXED_NAME: + tok = XML_TOK_NMTOKEN; + break; + } + break; +#endif + case BT_PLUS: + if (tok == XML_TOK_NMTOKEN) { + *nextTokPtr = ptr; + return XML_TOK_INVALID; + } + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_NAME_PLUS; + case BT_AST: + if (tok == XML_TOK_NMTOKEN) { + *nextTokPtr = ptr; + return XML_TOK_INVALID; + } + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_NAME_ASTERISK; + case BT_QUEST: + if (tok == XML_TOK_NMTOKEN) { + *nextTokPtr = ptr; + return XML_TOK_INVALID; + } + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_NAME_QUESTION; + default: + *nextTokPtr = ptr; + return XML_TOK_INVALID; + } + } + return -tok; +} + +static +int PREFIX(attributeValueTok)(const ENCODING *enc, const char *ptr, const char *end, + const char **nextTokPtr) +{ + const char *start; + if (ptr == end) + return XML_TOK_NONE; + start = ptr; + while (ptr != end) { + switch (BYTE_TYPE(enc, ptr)) { +#define LEAD_CASE(n) \ + case BT_LEAD ## n: ptr += n; break; + LEAD_CASE(2) LEAD_CASE(3) LEAD_CASE(4) +#undef LEAD_CASE + case BT_AMP: + if (ptr == start) + return PREFIX(scanRef)(enc, ptr + MINBPC(enc), end, nextTokPtr); + *nextTokPtr = ptr; + return XML_TOK_DATA_CHARS; + case BT_LT: + /* this is for inside entity references */ + *nextTokPtr = ptr; + return XML_TOK_INVALID; + case BT_LF: + if (ptr == start) { + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_DATA_NEWLINE; + } + *nextTokPtr = ptr; + return XML_TOK_DATA_CHARS; + case BT_CR: + if (ptr == start) { + ptr += MINBPC(enc); + if (ptr == end) + return XML_TOK_TRAILING_CR; + if (BYTE_TYPE(enc, ptr) == BT_LF) + ptr += MINBPC(enc); + *nextTokPtr = ptr; + return XML_TOK_DATA_NEWLINE; + } + *nextTokPtr = ptr; + return XML_TOK_DATA_CHARS; + case BT_S: + if (ptr == start) { + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_ATTRIBUTE_VALUE_S; + } + *nextTokPtr = ptr; + return XML_TOK_DATA_CHARS; + default: + ptr += MINBPC(enc); + break; + } + } + *nextTokPtr = ptr; + return XML_TOK_DATA_CHARS; +} + +static +int PREFIX(entityValueTok)(const ENCODING *enc, const char *ptr, const char *end, + const char **nextTokPtr) +{ + const char *start; + if (ptr == end) + return XML_TOK_NONE; + start = ptr; + while (ptr != end) { + switch (BYTE_TYPE(enc, ptr)) { +#define LEAD_CASE(n) \ + case BT_LEAD ## n: ptr += n; break; + LEAD_CASE(2) LEAD_CASE(3) LEAD_CASE(4) +#undef LEAD_CASE + case BT_AMP: + if (ptr == start) + return PREFIX(scanRef)(enc, ptr + MINBPC(enc), end, nextTokPtr); + *nextTokPtr = ptr; + return XML_TOK_DATA_CHARS; + case BT_PERCNT: + if (ptr == start) + return PREFIX(scanPercent)(enc, ptr + MINBPC(enc), end, nextTokPtr); + *nextTokPtr = ptr; + return XML_TOK_DATA_CHARS; + case BT_LF: + if (ptr == start) { + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_DATA_NEWLINE; + } + *nextTokPtr = ptr; + return XML_TOK_DATA_CHARS; + case BT_CR: + if (ptr == start) { + ptr += MINBPC(enc); + if (ptr == end) + return XML_TOK_TRAILING_CR; + if (BYTE_TYPE(enc, ptr) == BT_LF) + ptr += MINBPC(enc); + *nextTokPtr = ptr; + return XML_TOK_DATA_NEWLINE; + } + *nextTokPtr = ptr; + return XML_TOK_DATA_CHARS; + default: + ptr += MINBPC(enc); + break; + } + } + *nextTokPtr = ptr; + return XML_TOK_DATA_CHARS; +} + +#ifdef XML_DTD + +static +int PREFIX(ignoreSectionTok)(const ENCODING *enc, const char *ptr, const char *end, + const char **nextTokPtr) +{ + int level = 0; + if (MINBPC(enc) > 1) { + size_t n = end - ptr; + if (n & (MINBPC(enc) - 1)) { + n &= ~(MINBPC(enc) - 1); + end = ptr + n; + } + } + while (ptr != end) { + switch (BYTE_TYPE(enc, ptr)) { + INVALID_CASES(ptr, nextTokPtr) + case BT_LT: + if ((ptr += MINBPC(enc)) == end) + return XML_TOK_PARTIAL; + if (CHAR_MATCHES(enc, ptr, ASCII_EXCL)) { + if ((ptr += MINBPC(enc)) == end) + return XML_TOK_PARTIAL; + if (CHAR_MATCHES(enc, ptr, ASCII_LSQB)) { + ++level; + ptr += MINBPC(enc); + } + } + break; + case BT_RSQB: + if ((ptr += MINBPC(enc)) == end) + return XML_TOK_PARTIAL; + if (CHAR_MATCHES(enc, ptr, ASCII_RSQB)) { + if ((ptr += MINBPC(enc)) == end) + return XML_TOK_PARTIAL; + if (CHAR_MATCHES(enc, ptr, ASCII_GT)) { + ptr += MINBPC(enc); + if (level == 0) { + *nextTokPtr = ptr; + return XML_TOK_IGNORE_SECT; + } + --level; + } + } + break; + default: + ptr += MINBPC(enc); + break; + } + } + return XML_TOK_PARTIAL; +} + +#endif /* XML_DTD */ + +static +int PREFIX(isPublicId)(const ENCODING *enc, const char *ptr, const char *end, + const char **badPtr) +{ + ptr += MINBPC(enc); + end -= MINBPC(enc); + for (; ptr != end; ptr += MINBPC(enc)) { + switch (BYTE_TYPE(enc, ptr)) { + case BT_DIGIT: + case BT_HEX: + case BT_MINUS: + case BT_APOS: + case BT_LPAR: + case BT_RPAR: + case BT_PLUS: + case BT_COMMA: + case BT_SOL: + case BT_EQUALS: + case BT_QUEST: + case BT_CR: + case BT_LF: + case BT_SEMI: + case BT_EXCL: + case BT_AST: + case BT_PERCNT: + case BT_NUM: +#ifdef XML_NS + case BT_COLON: +#endif + break; + case BT_S: + if (CHAR_MATCHES(enc, ptr, ASCII_TAB)) { + *badPtr = ptr; + return 0; + } + break; + case BT_NAME: + case BT_NMSTRT: + if (!(BYTE_TO_ASCII(enc, ptr) & ~0x7f)) + break; + default: + switch (BYTE_TO_ASCII(enc, ptr)) { + case 0x24: /* $ */ + case 0x40: /* @ */ + break; + default: + *badPtr = ptr; + return 0; + } + break; + } + } + return 1; +} + +/* This must only be called for a well-formed start-tag or empty element tag. +Returns the number of attributes. Pointers to the first attsMax attributes +are stored in atts. */ + +static +int PREFIX(getAtts)(const ENCODING *enc, const char *ptr, + int attsMax, ATTRIBUTE *atts) +{ + enum { other, inName, inValue } state = inName; + int nAtts = 0; + int open = 0; /* defined when state == inValue; + initialization just to shut up compilers */ + + for (ptr += MINBPC(enc);; ptr += MINBPC(enc)) { + switch (BYTE_TYPE(enc, ptr)) { +#define START_NAME \ + if (state == other) { \ + if (nAtts < attsMax) { \ + atts[nAtts].name = ptr; \ + atts[nAtts].normalized = 1; \ + } \ + state = inName; \ + } +#define LEAD_CASE(n) \ + case BT_LEAD ## n: START_NAME ptr += (n - MINBPC(enc)); break; + LEAD_CASE(2) LEAD_CASE(3) LEAD_CASE(4) +#undef LEAD_CASE + case BT_NONASCII: + case BT_NMSTRT: + case BT_HEX: + START_NAME + break; +#undef START_NAME + case BT_QUOT: + if (state != inValue) { + if (nAtts < attsMax) + atts[nAtts].valuePtr = ptr + MINBPC(enc); + state = inValue; + open = BT_QUOT; + } + else if (open == BT_QUOT) { + state = other; + if (nAtts < attsMax) + atts[nAtts].valueEnd = ptr; + nAtts++; + } + break; + case BT_APOS: + if (state != inValue) { + if (nAtts < attsMax) + atts[nAtts].valuePtr = ptr + MINBPC(enc); + state = inValue; + open = BT_APOS; + } + else if (open == BT_APOS) { + state = other; + if (nAtts < attsMax) + atts[nAtts].valueEnd = ptr; + nAtts++; + } + break; + case BT_AMP: + if (nAtts < attsMax) + atts[nAtts].normalized = 0; + break; + case BT_S: + if (state == inName) + state = other; + else if (state == inValue + && nAtts < attsMax + && atts[nAtts].normalized + && (ptr == atts[nAtts].valuePtr + || BYTE_TO_ASCII(enc, ptr) != ASCII_SPACE + || BYTE_TO_ASCII(enc, ptr + MINBPC(enc)) == ASCII_SPACE + || BYTE_TYPE(enc, ptr + MINBPC(enc)) == open)) + atts[nAtts].normalized = 0; + break; + case BT_CR: case BT_LF: + /* This case ensures that the first attribute name is counted + Apart from that we could just change state on the quote. */ + if (state == inName) + state = other; + else if (state == inValue && nAtts < attsMax) + atts[nAtts].normalized = 0; + break; + case BT_GT: + case BT_SOL: + if (state != inValue) + return nAtts; + break; + default: + break; + } + } + /* not reached */ +} + +static +int PREFIX(charRefNumber)(const ENCODING *enc, const char *ptr) +{ + int result = 0; + /* skip &# */ + ptr += 2*MINBPC(enc); + if (CHAR_MATCHES(enc, ptr, ASCII_x)) { + for (ptr += MINBPC(enc); !CHAR_MATCHES(enc, ptr, ASCII_SEMI); ptr += MINBPC(enc)) { + int c = BYTE_TO_ASCII(enc, ptr); + switch (c) { + case ASCII_0: case ASCII_1: case ASCII_2: case ASCII_3: case ASCII_4: + case ASCII_5: case ASCII_6: case ASCII_7: case ASCII_8: case ASCII_9: + result <<= 4; + result |= (c - ASCII_0); + break; + case ASCII_A: case ASCII_B: case ASCII_C: case ASCII_D: case ASCII_E: case ASCII_F: + result <<= 4; + result += 10 + (c - ASCII_A); + break; + case ASCII_a: case ASCII_b: case ASCII_c: case ASCII_d: case ASCII_e: case ASCII_f: + result <<= 4; + result += 10 + (c - ASCII_a); + break; + } + if (result >= 0x110000) + return -1; + } + } + else { + for (; !CHAR_MATCHES(enc, ptr, ASCII_SEMI); ptr += MINBPC(enc)) { + int c = BYTE_TO_ASCII(enc, ptr); + result *= 10; + result += (c - ASCII_0); + if (result >= 0x110000) + return -1; + } + } + return checkCharRefNumber(result); +} + +static +int PREFIX(predefinedEntityName)(const ENCODING *enc, const char *ptr, const char *end) +{ + switch ((end - ptr)/MINBPC(enc)) { + case 2: + if (CHAR_MATCHES(enc, ptr + MINBPC(enc), ASCII_t)) { + switch (BYTE_TO_ASCII(enc, ptr)) { + case ASCII_l: + return ASCII_LT; + case ASCII_g: + return ASCII_GT; + } + } + break; + case 3: + if (CHAR_MATCHES(enc, ptr, ASCII_a)) { + ptr += MINBPC(enc); + if (CHAR_MATCHES(enc, ptr, ASCII_m)) { + ptr += MINBPC(enc); + if (CHAR_MATCHES(enc, ptr, ASCII_p)) + return ASCII_AMP; + } + } + break; + case 4: + switch (BYTE_TO_ASCII(enc, ptr)) { + case ASCII_q: + ptr += MINBPC(enc); + if (CHAR_MATCHES(enc, ptr, ASCII_u)) { + ptr += MINBPC(enc); + if (CHAR_MATCHES(enc, ptr, ASCII_o)) { + ptr += MINBPC(enc); + if (CHAR_MATCHES(enc, ptr, ASCII_t)) + return ASCII_QUOT; + } + } + break; + case ASCII_a: + ptr += MINBPC(enc); + if (CHAR_MATCHES(enc, ptr, ASCII_p)) { + ptr += MINBPC(enc); + if (CHAR_MATCHES(enc, ptr, ASCII_o)) { + ptr += MINBPC(enc); + if (CHAR_MATCHES(enc, ptr, ASCII_s)) + return ASCII_APOS; + } + } + break; + } + } + return 0; +} + +static +int PREFIX(sameName)(const ENCODING *enc, const char *ptr1, const char *ptr2) +{ + for (;;) { + switch (BYTE_TYPE(enc, ptr1)) { +#define LEAD_CASE(n) \ + case BT_LEAD ## n: \ + if (*ptr1++ != *ptr2++) \ + return 0; + LEAD_CASE(4) LEAD_CASE(3) LEAD_CASE(2) +#undef LEAD_CASE + /* fall through */ + if (*ptr1++ != *ptr2++) + return 0; + break; + case BT_NONASCII: + case BT_NMSTRT: +#ifdef XML_NS + case BT_COLON: +#endif + case BT_HEX: + case BT_DIGIT: + case BT_NAME: + case BT_MINUS: + if (*ptr2++ != *ptr1++) + return 0; + if (MINBPC(enc) > 1) { + if (*ptr2++ != *ptr1++) + return 0; + if (MINBPC(enc) > 2) { + if (*ptr2++ != *ptr1++) + return 0; + if (MINBPC(enc) > 3) { + if (*ptr2++ != *ptr1++) + return 0; + } + } + } + break; + default: + if (MINBPC(enc) == 1 && *ptr1 == *ptr2) + return 1; + switch (BYTE_TYPE(enc, ptr2)) { + case BT_LEAD2: + case BT_LEAD3: + case BT_LEAD4: + case BT_NONASCII: + case BT_NMSTRT: +#ifdef XML_NS + case BT_COLON: +#endif + case BT_HEX: + case BT_DIGIT: + case BT_NAME: + case BT_MINUS: + return 0; + default: + return 1; + } + } + } + /* not reached */ +} + +static +int PREFIX(nameMatchesAscii)(const ENCODING *enc, const char *ptr1, + const char *end1, const char *ptr2) +{ + for (; *ptr2; ptr1 += MINBPC(enc), ptr2++) { + if (ptr1 == end1) + return 0; + if (!CHAR_MATCHES(enc, ptr1, *ptr2)) + return 0; + } + return ptr1 == end1; +} + +static +int PREFIX(nameLength)(const ENCODING *enc, const char *ptr) +{ + const char *start = ptr; + for (;;) { + switch (BYTE_TYPE(enc, ptr)) { +#define LEAD_CASE(n) \ + case BT_LEAD ## n: ptr += n; break; + LEAD_CASE(2) LEAD_CASE(3) LEAD_CASE(4) +#undef LEAD_CASE + case BT_NONASCII: + case BT_NMSTRT: +#ifdef XML_NS + case BT_COLON: +#endif + case BT_HEX: + case BT_DIGIT: + case BT_NAME: + case BT_MINUS: + ptr += MINBPC(enc); + break; + default: + return ptr - start; + } + } +} + +static +const char *PREFIX(skipS)(const ENCODING *enc, const char *ptr) +{ + for (;;) { + switch (BYTE_TYPE(enc, ptr)) { + case BT_LF: + case BT_CR: + case BT_S: + ptr += MINBPC(enc); + break; + default: + return ptr; + } + } +} + +static +void PREFIX(updatePosition)(const ENCODING *enc, + const char *ptr, + const char *end, + POSITION *pos) +{ + while (ptr != end) { + switch (BYTE_TYPE(enc, ptr)) { +#define LEAD_CASE(n) \ + case BT_LEAD ## n: \ + ptr += n; \ + break; + LEAD_CASE(2) LEAD_CASE(3) LEAD_CASE(4) +#undef LEAD_CASE + case BT_LF: + pos->columnNumber = (unsigned)-1; + pos->lineNumber++; + ptr += MINBPC(enc); + break; + case BT_CR: + pos->lineNumber++; + ptr += MINBPC(enc); + if (ptr != end && BYTE_TYPE(enc, ptr) == BT_LF) + ptr += MINBPC(enc); + pos->columnNumber = (unsigned)-1; + break; + default: + ptr += MINBPC(enc); + break; + } + pos->columnNumber++; + } +} + +#undef DO_LEAD_CASE +#undef MULTIBYTE_CASES +#undef INVALID_CASES +#undef CHECK_NAME_CASE +#undef CHECK_NAME_CASES +#undef CHECK_NMSTRT_CASE +#undef CHECK_NMSTRT_CASES diff --git a/Code/BF2/External/expat/xmltok_impl.h b/Code/BF2/External/expat/xmltok_impl.h new file mode 100644 index 000000000..da0ea60a6 --- /dev/null +++ b/Code/BF2/External/expat/xmltok_impl.h @@ -0,0 +1,46 @@ +/* +Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd +See the file COPYING for copying permission. +*/ + +enum { + BT_NONXML, + BT_MALFORM, + BT_LT, + BT_AMP, + BT_RSQB, + BT_LEAD2, + BT_LEAD3, + BT_LEAD4, + BT_TRAIL, + BT_CR, + BT_LF, + BT_GT, + BT_QUOT, + BT_APOS, + BT_EQUALS, + BT_QUEST, + BT_EXCL, + BT_SOL, + BT_SEMI, + BT_NUM, + BT_LSQB, + BT_S, + BT_NMSTRT, + BT_COLON, + BT_HEX, + BT_DIGIT, + BT_NAME, + BT_MINUS, + BT_OTHER, /* known not to be a name or name start character */ + BT_NONASCII, /* might be a name or name start character */ + BT_PERCNT, + BT_LPAR, + BT_RPAR, + BT_AST, + BT_PLUS, + BT_COMMA, + BT_VERBAR +}; + +#include diff --git a/Code/BF2/External/expat/xmltok_ns.c b/Code/BF2/External/expat/xmltok_ns.c new file mode 100644 index 000000000..21859738a --- /dev/null +++ b/Code/BF2/External/expat/xmltok_ns.c @@ -0,0 +1,98 @@ +const ENCODING *NS(XmlGetUtf8InternalEncoding)(void) +{ + return &ns(internal_utf8_encoding).enc; +} + +const ENCODING *NS(XmlGetUtf16InternalEncoding)(void) +{ +#if XML_BYTE_ORDER == 12 + return &ns(internal_little2_encoding).enc; +#elif XML_BYTE_ORDER == 21 + return &ns(internal_big2_encoding).enc; +#else + const short n = 1; + return *(const char *)&n ? &ns(internal_little2_encoding).enc : &ns(internal_big2_encoding).enc; +#endif +} + +static +const ENCODING *NS(encodings)[] = { + &ns(latin1_encoding).enc, + &ns(ascii_encoding).enc, + &ns(utf8_encoding).enc, + &ns(big2_encoding).enc, + &ns(big2_encoding).enc, + &ns(little2_encoding).enc, + &ns(utf8_encoding).enc /* NO_ENC */ +}; + +static +int NS(initScanProlog)(const ENCODING *enc, const char *ptr, const char *end, + const char **nextTokPtr) +{ + return initScan(NS(encodings), (const INIT_ENCODING *)enc, XML_PROLOG_STATE, ptr, end, nextTokPtr); +} + +static +int NS(initScanContent)(const ENCODING *enc, const char *ptr, const char *end, + const char **nextTokPtr) +{ + return initScan(NS(encodings), (const INIT_ENCODING *)enc, XML_CONTENT_STATE, ptr, end, nextTokPtr); +} + +int NS(XmlInitEncoding)(INIT_ENCODING *p, const ENCODING **encPtr, const char *name) +{ + int i = getEncodingIndex(name); + if (i == UNKNOWN_ENC) + return 0; + SET_INIT_ENC_INDEX(p, i); + p->initEnc.scanners[XML_PROLOG_STATE] = NS(initScanProlog); + p->initEnc.scanners[XML_CONTENT_STATE] = NS(initScanContent); + p->initEnc.updatePosition = initUpdatePosition; + p->encPtr = encPtr; + *encPtr = &(p->initEnc); + return 1; +} + +static +const ENCODING *NS(findEncoding)(const ENCODING *enc, const char *ptr, const char *end) +{ +#define ENCODING_MAX 128 + char buf[ENCODING_MAX]; + char *p = buf; + int i; + XmlUtf8Convert(enc, &ptr, end, &p, p + ENCODING_MAX - 1); + if (ptr != end) + return 0; + *p = 0; + if (streqci(buf, KW_UTF_16) && enc->minBytesPerChar == 2) + return enc; + i = getEncodingIndex(buf); + if (i == UNKNOWN_ENC) + return 0; + return NS(encodings)[i]; +} + +int NS(XmlParseXmlDecl)(int isGeneralTextEntity, + const ENCODING *enc, + const char *ptr, + const char *end, + const char **badPtr, + const char **versionPtr, + const char **versionEndPtr, + const char **encodingName, + const ENCODING **encoding, + int *standalone) +{ + return doParseXmlDecl(NS(findEncoding), + isGeneralTextEntity, + enc, + ptr, + end, + badPtr, + versionPtr, + versionEndPtr, + encodingName, + encoding, + standalone); +} diff --git a/Code/BF2/External/ffmpeg-bink/COPYING.LGPLv2.1 b/Code/BF2/External/ffmpeg-bink/COPYING.LGPLv2.1 new file mode 100644 index 000000000..58af0d378 --- /dev/null +++ b/Code/BF2/External/ffmpeg-bink/COPYING.LGPLv2.1 @@ -0,0 +1,502 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +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 and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, 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 library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete 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 distribute a copy of this License along with the +Library. + + 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 Library or any portion +of it, thus forming a work based on the Library, 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) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +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 Library, 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 Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you 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. + + If distribution of 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 satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be 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. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library 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. + + 9. 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 Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +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 with +this License. + + 11. 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 Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library 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 Library. + +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. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library 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. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser 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 Library +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 Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +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 + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "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 +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. 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 LIBRARY 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 +LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), 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 Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. 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 library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/Code/BF2/External/ffmpeg-bink/LICENSE.md b/Code/BF2/External/ffmpeg-bink/LICENSE.md new file mode 100644 index 000000000..613070e1b --- /dev/null +++ b/Code/BF2/External/ffmpeg-bink/LICENSE.md @@ -0,0 +1,129 @@ +# License + +Most files in FFmpeg are under the GNU Lesser General Public License version 2.1 +or later (LGPL v2.1+). Read the file `COPYING.LGPLv2.1` for details. Some other +files have MIT/X11/BSD-style licenses. In combination the LGPL v2.1+ applies to +FFmpeg. + +Some optional parts of FFmpeg are licensed under the GNU General Public License +version 2 or later (GPL v2+). See the file `COPYING.GPLv2` for details. None of +these parts are used by default, you have to explicitly pass `--enable-gpl` to +configure to activate them. In this case, FFmpeg's license changes to GPL v2+. + +Specifically, the GPL parts of FFmpeg are: + +- libpostproc +- optional x86 optimization in the files + - `libavcodec/x86/flac_dsp_gpl.asm` + - `libavcodec/x86/idct_mmx.c` + - `libavfilter/x86/vf_removegrain.asm` +- the following building and testing tools + - `compat/solaris/make_sunver.pl` + - `doc/t2h.pm` + - `doc/texi2pod.pl` + - `libswresample/tests/swresample.c` + - `tests/checkasm/*` + - `tests/tiny_ssim.c` +- the following filters in libavfilter: + - `signature_lookup.c` + - `vf_blackframe.c` + - `vf_boxblur.c` + - `vf_colormatrix.c` + - `vf_cover_rect.c` + - `vf_cropdetect.c` + - `vf_delogo.c` + - `vf_eq.c` + - `vf_find_rect.c` + - `vf_fspp.c` + - `vf_histeq.c` + - `vf_hqdn3d.c` + - `vf_kerndeint.c` + - `vf_lensfun.c` (GPL version 3 or later) + - `vf_mcdeint.c` + - `vf_mpdecimate.c` + - `vf_nnedi.c` + - `vf_owdenoise.c` + - `vf_perspective.c` + - `vf_phase.c` + - `vf_pp.c` + - `vf_pp7.c` + - `vf_pullup.c` + - `vf_repeatfields.c` + - `vf_sab.c` + - `vf_signature.c` + - `vf_smartblur.c` + - `vf_spp.c` + - `vf_stereo3d.c` + - `vf_super2xsai.c` + - `vf_tinterlace.c` + - `vf_uspp.c` + - `vf_vaguedenoiser.c` + - `vsrc_mptestsrc.c` + +Should you, for whatever reason, prefer to use version 3 of the (L)GPL, then +the configure parameter `--enable-version3` will activate this licensing option +for you. Read the file `COPYING.LGPLv3` or, if you have enabled GPL parts, +`COPYING.GPLv3` to learn the exact legal terms that apply in this case. + +There are a handful of files under other licensing terms, namely: + +* The files `libavcodec/jfdctfst.c`, `libavcodec/jfdctint_template.c` and + `libavcodec/jrevdct.c` are taken from libjpeg, see the top of the files for + licensing details. Specifically note that you must credit the IJG in the + documentation accompanying your program if you only distribute executables. + You must also indicate any changes including additions and deletions to + those three files in the documentation. +* `tests/reference.pnm` is under the expat license. + + +## External libraries + +FFmpeg can be combined with a number of external libraries, which sometimes +affect the licensing of binaries resulting from the combination. + +### Compatible libraries + +The following libraries are under GPL version 2: +- avisynth +- frei0r +- libcdio +- libdavs2 +- librubberband +- libvidstab +- libx264 +- libx265 +- libxavs +- libxavs2 +- libxvid + +When combining them with FFmpeg, FFmpeg needs to be licensed as GPL as well by +passing `--enable-gpl` to configure. + +The following libraries are under LGPL version 3: +- gmp +- libaribb24 +- liblensfun + +When combining them with FFmpeg, use the configure option `--enable-version3` to +upgrade FFmpeg to the LGPL v3. + +The VMAF, mbedTLS, RK MPI, OpenCORE and VisualOn libraries are under the Apache License +2.0. That license is incompatible with the LGPL v2.1 and the GPL v2, but not with +version 3 of those licenses. So to combine these libraries with FFmpeg, the +license version needs to be upgraded by passing `--enable-version3` to configure. + +The smbclient library is under the GPL v3, to combine it with FFmpeg, +the options `--enable-gpl` and `--enable-version3` have to be passed to +configure to upgrade FFmpeg to the GPL v3. + +### Incompatible libraries + +There are certain libraries you can combine with FFmpeg whose licenses are not +compatible with the GPL and/or the LGPL. If you wish to enable these +libraries, even in circumstances that their license may be incompatible, pass +`--enable-nonfree` to configure. This will cause the resulting binary to be +unredistributable. + +The Fraunhofer FDK AAC and OpenSSL libraries are under licenses which are +incompatible with the GPLv2 and v3. To the best of our knowledge, they are +compatible with the LGPL. diff --git a/Code/BF2/External/ffmpeg-bink/README.md b/Code/BF2/External/ffmpeg-bink/README.md new file mode 100644 index 000000000..f566c79bc --- /dev/null +++ b/Code/BF2/External/ffmpeg-bink/README.md @@ -0,0 +1,115 @@ +# FFmpeg Bink decoders (vendored subset) + +The macOS client and the Windows x64 client play Battlefield 2's Bink 1 movies +(`mods/*/Movies/*.bik`) with FFmpeg's Bink video and Bink audio (DCT) decoders, linked +statically: into `bf2_client` on macOS, into `RendDX9.dll` on Windows x64 +(`Code/Build/renddx9.cmd x64`). Windows x86 keeps RAD Game Tools' `binkw32.dll` and compiles +nothing in this directory. Owner decisions 2026-11-01 (macOS) and 2026-11-07 (x64); the +integration and the validation are summarised below. + +## How the game uses it + +All Bink calls are in `Code/BF2/GeomMisc/MenuRend/Video.cpp` (renderer image), declared in +`Code/RendDX9Abi/Bink.h`. `Video::open` calls `BinkOpen` for each path-list entry and +`BinkGetSummary`; `Video::doFrame` runs `BinkWait`, `BinkDoFrame`, lock, +`BinkCopyToBuffer(BINKSURFACE32 | BINKCOPYALL)`, unlock, `BinkNextFrame` once per frame. A menu +movie loops because `FrameNum` wraps to 1. Intro movies (`FSMoviePlayer`) set the sound system; +the menu background movie (SwiffRender's `?` fill) does not, so it plays silent, as on retail. + +Windows x86 links RAD's `binkw32.dll` (unchanged). macOS and Windows x64 define +`BF2_BINK_PORT` and link the `[CHOSEN, not recovered]` stand-in: `Code/RendDX9Abi/BinkFFmpeg.cpp` +(container, decode, clock, colour conversion) plus `BinkAudioCoreAudio.cpp` (AudioQueue, macOS) +or `BinkAudioDirectSound.cpp` (x64). Its behaviour was measured black-box against retail +`binkw32.dll` (binkw32 was never decompiled; only its export names and call semantics are used): + +- Colour: nearest chroma, integer tables (luma `floor`, chroma `trunc`), BT.601 limited range; + bit-exact against retail on 36 frames of all seven shipped movies. The two menu movies are grey + (header flag 0x20000, zero chroma planes): retail shows them grey (R = G = B), and so does the port. +- Clock: wall clock from the first `BinkWait`. With sound, a late picture catches up; a starved + sound restarts with a silent gap. Without sound, a frame more than about two periods late drops + the lag. `BinkPause(0)` makes the current frame due 1.25 periods later. +- Audio is decoded with its frame and restarts with the loop. `[CHOSEN]` pause with sound: the + port resumes cleanly where retail skips about 0.8 s of sound (owner decision 2026-11-07). + +## Validation + +- Decoder: `bf2_bink_decode_test video []`, `... loop ` and + `... audio ` compare against references made with the `ffmpeg` CLI from the + read-only install, for example + `ffmpeg -i menu_loggedin.bik -vf "select=eq(n\,299)" -frames:v 1 -f rawvideo -pix_fmt yuv420p f300.yuv` + and `ffmpeg -i Dice.bik -map 0:a:0 -f f32le -c:a pcm_f32le Dice.f32le`. Game-derived frames and + audio stay outside the repository. +- Black-box harness: `Code/Tests/movies/bink_harness.cpp`, one source with two builds. The retail + build is a 32-bit Windows program that loads `binkw32.dll` and drives it like `Video.cpp` with a + fake `IDirectSound` whose play cursor runs on the wall clock; the port build links + `BinkFFmpeg.cpp` with the same ideal card (`--sysaudio` uses the real backend). Options stall, + pause, delay and loop the playback. Windows builds: `Code/Tests/movies/bink_harness.cmd`; macOS + port: the `bf2_bink_harness` CMake target. Analysis tools are in `tools/bink/` (`timing.py`, + `bink_av.cpp`, `colour.py`, `fit_colour.py`). + +## Provenance + +- FFmpeg 7.1.1, the official release tarball from ffmpeg.org + (`ffmpeg-7.1.1.tar.xz`, SHA-256 + `733984395e0dbbe5c046abda2dc49a5544e7e0e1e2366bba849222ae9e3a03b1`). +- Files taken, byte-for-byte unmodified (SHA-256 of each copy): + +| File | SHA-256 | +| --- | --- | +| `libavcodec/bink.c` | `e132ee588345c9f7675c3fa0f58b3b40eb1a355839734188ab2be49e9f63b2d0` | +| `libavcodec/binkaudio.c` | `031808c16afec24009a5b47f74d2ff00eb52406b0bb4e85544b0ad44354258e6` | +| `libavcodec/binkdata.h` | `e549d4f3df3debd0de047593db32ce9d671de210475c76aefd1a741b815b4080` | +| `libavcodec/binkdsp.c` | `2e23cb9d22c5353aa8a1d37dbaf5844cb4a2bac9bee2d42a321ed31db7c3b604` | +| `libavcodec/binkdsp.h` | `f5cc98c60913a070fbd3f4674153b92db271ce1235066ae1228b23e4aad894ff` | +| `libavcodec/wma_freqs.c` | `c8992e806736dd708015c2121bf1773e4c4bbf3201840cbdf7f6c5f3754ee46c` | +| `libavcodec/wma_freqs.h` | `aeef407a065e961f18176fb17918c403f69686e6eb84d717bd688b1511789a56` | +| `COPYING.LGPLv2.1` | `b634ab5640e258563c536e658cad87080553df6f34f62269a21d554844e58bfe` | +| `LICENSE.md` | `cb48bf09a11f5fb576cddb0431c8f5ed0a60157a9ec942adffc13907cbe083f2` | + +Local changes to FFmpeg files: none. FFmpeg's build system, configure script, assembly and the +rest of libavutil/libavcodec/libavformat are not included. + +## The shim (OpenBF2 port code) + +`shim/` is written for OpenBF2, not taken from FFmpeg. It replaces the FFmpeg infrastructure the +two decoders include: + +- One-line forwarders with FFmpeg's header names (`avcodec.h`, `get_bits.h`, `libavutil/tx.h`, + ...) to `shim/ffbink_shim.h`, so the FFmpeg sources compile unmodified. +- `ffbink_shim.h` / `ffbink_shim.c`: a little-endian checked bit reader, single-level LE VLC + tables, refcounted frames and buffers, the C block/pixel helpers bink.c selects (`clear_block`, + `fill_block`, `put_pixels8/16`), logging, aligned allocation, and the inverse DCT + (DCT-III, an FFT-based implementation scaled like FFmpeg's `AV_TX_FLOAT_DCT`). +- `ffbink.h`: a small C interface (open/decode/flush/close for video and audio) used by + `Code/RendDX9Abi/BinkFFmpeg.cpp`, which implements the Bink API calls the game makes and reads + the `.bik` container itself. +- Compiler portability (2026-11-07): GCC/clang attributes on macOS; on MSVC `__forceinline`, + `_BitScanReverse`, `__declspec(align)`, `__declspec(noreturn)`, `_USE_MATH_DEFINES`, and on + Windows `InitOnceExecuteOnce` for `ff_thread_once` and `_aligned_malloc`/`_aligned_free`. + MSVC compiles the FFmpeg files as C11 (`/std:c11 /O2`). + +Not included: the Bink audio RDFT variant (`binkaudio_rdft`). `av_tx_init` refuses +`AV_TX_FLOAT_RDFT`, so such a track stops at a named `[FRONTIER]` in `BinkOpen`. No shipped +Battlefield 2 movie has one (all audio tracks are `binkaudio_dct`). Bink 2 (`KB2`) files are +refused by `BinkOpen`, as FFmpeg's demuxer also does not decode them. + +## Licence + +The FFmpeg files are licensed under the GNU Lesser General Public License, version 2.1 or (at +your option) any later version; see `COPYING.LGPLv2.1` and `LICENSE.md` and the notice at the top +of each file. Copyright remains with the FFmpeg authors named there (Konstantin Shishkov, Peter +Ross, Daniel Verkamp and others). None of the files is under one of FFmpeg's GPL-only parts. + +The OpenBF2 repository as a whole is GPL-3; LGPL-2.1-or-later code may be combined with it and +linked statically (LGPL 2.1 section 3 lets the code be used under the GPL). This holds for both +images that link these files: the macOS `bf2_client` and the Windows x64 `RendDX9.dll`. Anyone +distributing either binary must also provide the corresponding source for these files (and, +since the whole is then GPL-3, for the program), which this repository does; keep +`COPYING.LGPLv2.1` and `LICENSE.md` with the distribution. The Windows x86 build does not +contain them. The shim files are OpenBF2 code under the repository's licence. + +## Updating + +Copy the same seven files from a newer FFmpeg release, update the hashes above, and run +`bf2_bink_decode_test` and the black-box harness (see "Validation" above), and build `renddx9.cmd x64` with MSVC. If a decoder starts to use more of libavutil or +libavcodec, extend the shim; do not edit the FFmpeg files. diff --git a/Code/BF2/External/ffmpeg-bink/libavcodec/bink.c b/Code/BF2/External/ffmpeg-bink/libavcodec/bink.c new file mode 100644 index 000000000..04fd90aa1 --- /dev/null +++ b/Code/BF2/External/ffmpeg-bink/libavcodec/bink.c @@ -0,0 +1,1433 @@ +/* + * Bink video decoder + * Copyright (c) 2009 Konstantin Shishkov + * Copyright (C) 2011 Peter Ross + * + * This file is part of FFmpeg. + * + * FFmpeg is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * FFmpeg is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with FFmpeg; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "libavutil/attributes.h" +#include "libavutil/emms.h" +#include "libavutil/imgutils.h" +#include "libavutil/mem.h" +#include "libavutil/mem_internal.h" +#include "libavutil/thread.h" + +#define BITSTREAM_READER_LE +#include "avcodec.h" +#include "binkdata.h" +#include "binkdsp.h" +#include "blockdsp.h" +#include "codec_internal.h" +#include "decode.h" +#include "get_bits.h" +#include "hpeldsp.h" + +#define BINK_FLAG_ALPHA 0x00100000 +#define BINK_FLAG_GRAY 0x00020000 + +static VLC bink_trees[16]; + +/** + * IDs for different data types used in old version of Bink video codec + */ +enum OldSources { + BINKB_SRC_BLOCK_TYPES = 0, ///< 8x8 block types + BINKB_SRC_COLORS, ///< pixel values used for different block types + BINKB_SRC_PATTERN, ///< 8-bit values for 2-colour pattern fill + BINKB_SRC_X_OFF, ///< X components of motion value + BINKB_SRC_Y_OFF, ///< Y components of motion value + BINKB_SRC_INTRA_DC, ///< DC values for intrablocks with DCT + BINKB_SRC_INTER_DC, ///< DC values for interblocks with DCT + BINKB_SRC_INTRA_Q, ///< quantizer values for intrablocks with DCT + BINKB_SRC_INTER_Q, ///< quantizer values for interblocks with DCT + BINKB_SRC_INTER_COEFS, ///< number of coefficients for residue blocks + + BINKB_NB_SRC +}; + +static const uint8_t binkb_bundle_sizes[BINKB_NB_SRC] = { + 4, 8, 8, 5, 5, 11, 11, 4, 4, 7 +}; + +static const uint8_t binkb_bundle_signed[BINKB_NB_SRC] = { + 0, 0, 0, 1, 1, 0, 1, 0, 0, 0 +}; + +static int32_t binkb_intra_quant[16][64]; +static int32_t binkb_inter_quant[16][64]; + +/** + * IDs for different data types used in Bink video codec + */ +enum Sources { + BINK_SRC_BLOCK_TYPES = 0, ///< 8x8 block types + BINK_SRC_SUB_BLOCK_TYPES, ///< 16x16 block types (a subset of 8x8 block types) + BINK_SRC_COLORS, ///< pixel values used for different block types + BINK_SRC_PATTERN, ///< 8-bit values for 2-colour pattern fill + BINK_SRC_X_OFF, ///< X components of motion value + BINK_SRC_Y_OFF, ///< Y components of motion value + BINK_SRC_INTRA_DC, ///< DC values for intrablocks with DCT + BINK_SRC_INTER_DC, ///< DC values for interblocks with DCT + BINK_SRC_RUN, ///< run lengths for special fill block + + BINK_NB_SRC +}; + +/** + * data needed to decode 4-bit Huffman-coded value + */ +typedef struct Tree { + int vlc_num; ///< tree number (in bink_trees[]) + uint8_t syms[16]; ///< leaf value to symbol mapping +} Tree; + +#define GET_HUFF(gb, tree) (tree).syms[get_vlc2(gb, bink_trees[(tree).vlc_num].table,\ + bink_trees[(tree).vlc_num].bits, 1)] + +/** + * data structure used for decoding single Bink data type + */ +typedef struct Bundle { + int len; ///< length of number of entries to decode (in bits) + Tree tree; ///< Huffman tree-related data + uint8_t *data; ///< buffer for decoded symbols + uint8_t *data_end; ///< buffer end + uint8_t *cur_dec; ///< pointer to the not yet decoded part of the buffer + uint8_t *cur_ptr; ///< pointer to the data that is not read from buffer yet +} Bundle; + +/* + * Decoder context + */ +typedef struct BinkContext { + AVCodecContext *avctx; + BlockDSPContext bdsp; + op_pixels_func put_pixels_tab; + BinkDSPContext binkdsp; + AVFrame *last; + int version; ///< internal Bink file version + int has_alpha; + int swap_planes; + unsigned frame_num; + + Bundle bundle[BINKB_NB_SRC]; ///< bundles for decoding all data types + Tree col_high[16]; ///< trees for decoding high nibble in "colours" data type + int col_lastval; ///< value of last decoded high nibble in "colours" data type +} BinkContext; + +/** + * Bink video block types + */ +enum BlockTypes { + SKIP_BLOCK = 0, ///< skipped block + SCALED_BLOCK, ///< block has size 16x16 + MOTION_BLOCK, ///< block is copied from previous frame with some offset + RUN_BLOCK, ///< block is composed from runs of colours with custom scan order + RESIDUE_BLOCK, ///< motion block with some difference added + INTRA_BLOCK, ///< intra DCT block + FILL_BLOCK, ///< block is filled with single colour + INTER_BLOCK, ///< motion block with DCT applied to the difference + PATTERN_BLOCK, ///< block is filled with two colours following custom pattern + RAW_BLOCK, ///< uncoded 8x8 block +}; + +/** + * Initialize length in all bundles. + * + * @param c decoder context + * @param width plane width + * @param bw plane width in 8x8 blocks + */ +static void init_lengths(BinkContext *c, int width, int bw) +{ + width = FFALIGN(width, 8); + + c->bundle[BINK_SRC_BLOCK_TYPES].len = av_log2((width >> 3) + 511) + 1; + + c->bundle[BINK_SRC_SUB_BLOCK_TYPES].len = av_log2((width >> 4) + 511) + 1; + + c->bundle[BINK_SRC_COLORS].len = av_log2(bw*64 + 511) + 1; + + c->bundle[BINK_SRC_INTRA_DC].len = + c->bundle[BINK_SRC_INTER_DC].len = + c->bundle[BINK_SRC_X_OFF].len = + c->bundle[BINK_SRC_Y_OFF].len = av_log2((width >> 3) + 511) + 1; + + c->bundle[BINK_SRC_PATTERN].len = av_log2((bw << 3) + 511) + 1; + + c->bundle[BINK_SRC_RUN].len = av_log2(bw*48 + 511) + 1; +} + +/** + * Allocate memory for bundles. + * + * @param c decoder context + */ +static av_cold int init_bundles(BinkContext *c) +{ + int bw, bh, blocks; + uint8_t *tmp; + int i; + + bw = (c->avctx->width + 7) >> 3; + bh = (c->avctx->height + 7) >> 3; + blocks = bw * bh; + + tmp = av_calloc(blocks, 64 * BINKB_NB_SRC); + if (!tmp) + return AVERROR(ENOMEM); + for (i = 0; i < BINKB_NB_SRC; i++) { + c->bundle[i].data = tmp; + tmp += blocks * 64; + c->bundle[i].data_end = tmp; + } + + return 0; +} + +/** + * Free memory used by bundles. + * + * @param c decoder context + */ +static av_cold void free_bundles(BinkContext *c) +{ + av_freep(&c->bundle[0].data); +} + +/** + * Merge two consequent lists of equal size depending on bits read. + * + * @param gb context for reading bits + * @param dst buffer where merged list will be written to + * @param src pointer to the head of the first list (the second lists starts at src+size) + * @param size input lists size + */ +static void merge(GetBitContext *gb, uint8_t *dst, uint8_t *src, int size) +{ + uint8_t *src2 = src + size; + int size2 = size; + + do { + if (!get_bits1(gb)) { + *dst++ = *src++; + size--; + } else { + *dst++ = *src2++; + size2--; + } + } while (size && size2); + + while (size--) + *dst++ = *src++; + while (size2--) + *dst++ = *src2++; +} + +/** + * Read information about Huffman tree used to decode data. + * + * @param gb context for reading bits + * @param tree pointer for storing tree data + */ +static int read_tree(GetBitContext *gb, Tree *tree) +{ + uint8_t tmp1[16] = { 0 }, tmp2[16], *in = tmp1, *out = tmp2; + int i, t, len; + + if (get_bits_left(gb) < 4) + return AVERROR_INVALIDDATA; + + tree->vlc_num = get_bits(gb, 4); + if (!tree->vlc_num) { + for (i = 0; i < 16; i++) + tree->syms[i] = i; + return 0; + } + if (get_bits1(gb)) { + len = get_bits(gb, 3); + for (i = 0; i <= len; i++) { + tree->syms[i] = get_bits(gb, 4); + tmp1[tree->syms[i]] = 1; + } + for (i = 0; i < 16 && len < 16 - 1; i++) + if (!tmp1[i]) + tree->syms[++len] = i; + } else { + len = get_bits(gb, 2); + for (i = 0; i < 16; i++) + in[i] = i; + for (i = 0; i <= len; i++) { + int size = 1 << i; + for (t = 0; t < 16; t += size << 1) + merge(gb, out + t, in + t, size); + FFSWAP(uint8_t*, in, out); + } + memcpy(tree->syms, in, 16); + } + return 0; +} + +/** + * Prepare bundle for decoding data. + * + * @param gb context for reading bits + * @param c decoder context + * @param bundle_num number of the bundle to initialize + */ +static int read_bundle(GetBitContext *gb, BinkContext *c, int bundle_num) +{ + int i; + + if (bundle_num == BINK_SRC_COLORS) { + for (i = 0; i < 16; i++) { + int ret = read_tree(gb, &c->col_high[i]); + if (ret < 0) + return ret; + } + c->col_lastval = 0; + } + if (bundle_num != BINK_SRC_INTRA_DC && bundle_num != BINK_SRC_INTER_DC) { + int ret = read_tree(gb, &c->bundle[bundle_num].tree); + if (ret < 0) + return ret; + } + c->bundle[bundle_num].cur_dec = + c->bundle[bundle_num].cur_ptr = c->bundle[bundle_num].data; + + return 0; +} + +/** + * common check before starting decoding bundle data + * + * @param gb context for reading bits + * @param b bundle + * @param t variable where number of elements to decode will be stored + */ +#define CHECK_READ_VAL(gb, b, t) \ + if (!b->cur_dec || (b->cur_dec > b->cur_ptr)) \ + return 0; \ + t = get_bits(gb, b->len); \ + if (!t) { \ + b->cur_dec = NULL; \ + return 0; \ + } \ + +static int read_runs(AVCodecContext *avctx, GetBitContext *gb, Bundle *b) +{ + int t, v; + const uint8_t *dec_end; + + CHECK_READ_VAL(gb, b, t); + dec_end = b->cur_dec + t; + if (dec_end > b->data_end) { + av_log(avctx, AV_LOG_ERROR, "Run value went out of bounds\n"); + return AVERROR_INVALIDDATA; + } + if (get_bits_left(gb) < 1) + return AVERROR_INVALIDDATA; + if (get_bits1(gb)) { + v = get_bits(gb, 4); + memset(b->cur_dec, v, t); + b->cur_dec += t; + } else { + while (b->cur_dec < dec_end) + *b->cur_dec++ = GET_HUFF(gb, b->tree); + } + return 0; +} + +static int read_motion_values(AVCodecContext *avctx, GetBitContext *gb, Bundle *b) +{ + int t, sign, v; + const uint8_t *dec_end; + + CHECK_READ_VAL(gb, b, t); + dec_end = b->cur_dec + t; + if (dec_end > b->data_end) { + av_log(avctx, AV_LOG_ERROR, "Too many motion values\n"); + return AVERROR_INVALIDDATA; + } + if (get_bits_left(gb) < 1) + return AVERROR_INVALIDDATA; + if (get_bits1(gb)) { + v = get_bits(gb, 4); + if (v) { + sign = -get_bits1(gb); + v = (v ^ sign) - sign; + } + memset(b->cur_dec, v, t); + b->cur_dec += t; + } else { + while (b->cur_dec < dec_end) { + v = GET_HUFF(gb, b->tree); + if (v) { + sign = -get_bits1(gb); + v = (v ^ sign) - sign; + } + *b->cur_dec++ = v; + } + } + return 0; +} + +static const uint8_t bink_rlelens[4] = { 4, 8, 12, 32 }; + +static int read_block_types(AVCodecContext *avctx, GetBitContext *gb, Bundle *b) +{ + BinkContext * const c = avctx->priv_data; + int t, v; + int last = 0; + const uint8_t *dec_end; + + CHECK_READ_VAL(gb, b, t); + if (c->version == 'k') { + t ^= 0xBBu; + if (t == 0) { + b->cur_dec = NULL; + return 0; + } + } + dec_end = b->cur_dec + t; + if (dec_end > b->data_end) { + av_log(avctx, AV_LOG_ERROR, "Too many block type values\n"); + return AVERROR_INVALIDDATA; + } + if (get_bits_left(gb) < 1) + return AVERROR_INVALIDDATA; + if (get_bits1(gb)) { + v = get_bits(gb, 4); + memset(b->cur_dec, v, t); + b->cur_dec += t; + } else { + while (b->cur_dec < dec_end) { + v = GET_HUFF(gb, b->tree); + if (v < 12) { + last = v; + *b->cur_dec++ = v; + } else { + int run = bink_rlelens[v - 12]; + + if (dec_end - b->cur_dec < run) + return AVERROR_INVALIDDATA; + memset(b->cur_dec, last, run); + b->cur_dec += run; + } + } + } + return 0; +} + +static int read_patterns(AVCodecContext *avctx, GetBitContext *gb, Bundle *b) +{ + int t, v; + const uint8_t *dec_end; + + CHECK_READ_VAL(gb, b, t); + dec_end = b->cur_dec + t; + if (dec_end > b->data_end) { + av_log(avctx, AV_LOG_ERROR, "Too many pattern values\n"); + return AVERROR_INVALIDDATA; + } + while (b->cur_dec < dec_end) { + if (get_bits_left(gb) < 2) + return AVERROR_INVALIDDATA; + v = GET_HUFF(gb, b->tree); + v |= GET_HUFF(gb, b->tree) << 4; + *b->cur_dec++ = v; + } + + return 0; +} + +static int read_colors(GetBitContext *gb, Bundle *b, BinkContext *c) +{ + int t, sign, v; + const uint8_t *dec_end; + + CHECK_READ_VAL(gb, b, t); + dec_end = b->cur_dec + t; + if (dec_end > b->data_end) { + av_log(c->avctx, AV_LOG_ERROR, "Too many color values\n"); + return AVERROR_INVALIDDATA; + } + if (get_bits_left(gb) < 1) + return AVERROR_INVALIDDATA; + if (get_bits1(gb)) { + c->col_lastval = GET_HUFF(gb, c->col_high[c->col_lastval]); + v = GET_HUFF(gb, b->tree); + v = (c->col_lastval << 4) | v; + if (c->version < 'i') { + sign = ((int8_t) v) >> 7; + v = ((v & 0x7F) ^ sign) - sign; + v += 0x80; + } + memset(b->cur_dec, v, t); + b->cur_dec += t; + } else { + while (b->cur_dec < dec_end) { + if (get_bits_left(gb) < 2) + return AVERROR_INVALIDDATA; + c->col_lastval = GET_HUFF(gb, c->col_high[c->col_lastval]); + v = GET_HUFF(gb, b->tree); + v = (c->col_lastval << 4) | v; + if (c->version < 'i') { + sign = ((int8_t) v) >> 7; + v = ((v & 0x7F) ^ sign) - sign; + v += 0x80; + } + *b->cur_dec++ = v; + } + } + return 0; +} + +/** number of bits used to store first DC value in bundle */ +#define DC_START_BITS 11 + +static int read_dcs(AVCodecContext *avctx, GetBitContext *gb, Bundle *b, + int start_bits, int has_sign) +{ + int i, j, len, len2, bsize, sign, v, v2; + int16_t *dst = (int16_t*)b->cur_dec; + int16_t *dst_end = (int16_t*)b->data_end; + + CHECK_READ_VAL(gb, b, len); + if (get_bits_left(gb) < start_bits - has_sign) + return AVERROR_INVALIDDATA; + v = get_bits(gb, start_bits - has_sign); + if (v && has_sign) { + sign = -get_bits1(gb); + v = (v ^ sign) - sign; + } + if (dst_end - dst < 1) + return AVERROR_INVALIDDATA; + *dst++ = v; + len--; + for (i = 0; i < len; i += 8) { + len2 = FFMIN(len - i, 8); + if (dst_end - dst < len2) + return AVERROR_INVALIDDATA; + bsize = get_bits(gb, 4); + if (bsize) { + for (j = 0; j < len2; j++) { + v2 = get_bits(gb, bsize); + if (v2) { + sign = -get_bits1(gb); + v2 = (v2 ^ sign) - sign; + } + v += v2; + *dst++ = v; + if (v < -32768 || v > 32767) { + av_log(avctx, AV_LOG_ERROR, "DC value went out of bounds: %d\n", v); + return AVERROR_INVALIDDATA; + } + } + } else { + for (j = 0; j < len2; j++) + *dst++ = v; + } + } + + b->cur_dec = (uint8_t*)dst; + return 0; +} + +/** + * Retrieve next value from bundle. + * + * @param c decoder context + * @param bundle bundle number + */ +static inline int get_value(BinkContext *c, int bundle) +{ + int ret; + + if (bundle < BINK_SRC_X_OFF || bundle == BINK_SRC_RUN) + return *c->bundle[bundle].cur_ptr++; + if (bundle == BINK_SRC_X_OFF || bundle == BINK_SRC_Y_OFF) + return (int8_t)*c->bundle[bundle].cur_ptr++; + ret = *(int16_t*)c->bundle[bundle].cur_ptr; + c->bundle[bundle].cur_ptr += 2; + return ret; +} + +static av_cold void binkb_init_bundle(BinkContext *c, int bundle_num) +{ + c->bundle[bundle_num].cur_dec = + c->bundle[bundle_num].cur_ptr = c->bundle[bundle_num].data; + c->bundle[bundle_num].len = 13; +} + +static av_cold void binkb_init_bundles(BinkContext *c) +{ + int i; + for (i = 0; i < BINKB_NB_SRC; i++) + binkb_init_bundle(c, i); +} + +static int binkb_read_bundle(BinkContext *c, GetBitContext *gb, int bundle_num) +{ + const int bits = binkb_bundle_sizes[bundle_num]; + const int mask = 1 << (bits - 1); + const int issigned = binkb_bundle_signed[bundle_num]; + Bundle *b = &c->bundle[bundle_num]; + int i, len; + + CHECK_READ_VAL(gb, b, len); + if (b->data_end - b->cur_dec < len * (1 + (bits > 8))) + return AVERROR_INVALIDDATA; + if (bits <= 8) { + if (!issigned) { + for (i = 0; i < len; i++) + *b->cur_dec++ = get_bits(gb, bits); + } else { + for (i = 0; i < len; i++) + *b->cur_dec++ = get_bits(gb, bits) - mask; + } + } else { + int16_t *dst = (int16_t*)b->cur_dec; + + if (!issigned) { + for (i = 0; i < len; i++) + *dst++ = get_bits(gb, bits); + } else { + for (i = 0; i < len; i++) + *dst++ = get_bits(gb, bits) - mask; + } + b->cur_dec = (uint8_t*)dst; + } + return 0; +} + +static inline int binkb_get_value(BinkContext *c, int bundle_num) +{ + int16_t ret; + const int bits = binkb_bundle_sizes[bundle_num]; + + if (bits <= 8) { + int val = *c->bundle[bundle_num].cur_ptr++; + return binkb_bundle_signed[bundle_num] ? (int8_t)val : val; + } + ret = *(int16_t*)c->bundle[bundle_num].cur_ptr; + c->bundle[bundle_num].cur_ptr += 2; + return ret; +} + +/** + * Read 8x8 block of DCT coefficients. + * + * @param gb context for reading bits + * @param block place for storing coefficients + * @param scan scan order table + * @param quant_matrices quantization matrices + * @return 0 for success, negative value in other cases + */ +static int read_dct_coeffs(BinkContext *c, GetBitContext *gb, int32_t block[64], + const uint8_t *scan, int *coef_count_, + int coef_idx[64], int q) +{ + int coef_list[128]; + int mode_list[128]; + int i, t, bits, ccoef, mode, sign; + int list_start = 64, list_end = 64, list_pos; + int coef_count = 0; + int quant_idx; + + if (get_bits_left(gb) < 4) + return AVERROR_INVALIDDATA; + + coef_list[list_end] = 4; mode_list[list_end++] = 0; + coef_list[list_end] = 24; mode_list[list_end++] = 0; + coef_list[list_end] = 44; mode_list[list_end++] = 0; + coef_list[list_end] = 1; mode_list[list_end++] = 3; + coef_list[list_end] = 2; mode_list[list_end++] = 3; + coef_list[list_end] = 3; mode_list[list_end++] = 3; + + for (bits = get_bits(gb, 4) - 1; bits >= 0; bits--) { + list_pos = list_start; + while (list_pos < list_end) { + if (!(mode_list[list_pos] | coef_list[list_pos]) || !get_bits1(gb)) { + list_pos++; + continue; + } + ccoef = coef_list[list_pos]; + mode = mode_list[list_pos]; + switch (mode) { + case 0: + coef_list[list_pos] = ccoef + 4; + mode_list[list_pos] = 1; + case 2: + if (mode == 2) { + coef_list[list_pos] = 0; + mode_list[list_pos++] = 0; + } + for (i = 0; i < 4; i++, ccoef++) { + if (get_bits1(gb)) { + coef_list[--list_start] = ccoef; + mode_list[ list_start] = 3; + } else { + if (!bits) { + t = 1 - (get_bits1(gb) << 1); + } else { + t = get_bits(gb, bits) | 1 << bits; + sign = -get_bits1(gb); + t = (t ^ sign) - sign; + } + block[scan[ccoef]] = t; + coef_idx[coef_count++] = ccoef; + } + } + break; + case 1: + mode_list[list_pos] = 2; + for (i = 0; i < 3; i++) { + ccoef += 4; + coef_list[list_end] = ccoef; + mode_list[list_end++] = 2; + } + break; + case 3: + if (!bits) { + t = 1 - (get_bits1(gb) << 1); + } else { + t = get_bits(gb, bits) | 1 << bits; + sign = -get_bits1(gb); + t = (t ^ sign) - sign; + } + block[scan[ccoef]] = t; + coef_idx[coef_count++] = ccoef; + coef_list[list_pos] = 0; + mode_list[list_pos++] = 0; + break; + } + } + } + + if (q == -1) { + quant_idx = get_bits(gb, 4); + } else { + quant_idx = q; + if (quant_idx > 15U) { + av_log(c->avctx, AV_LOG_ERROR, "quant_index %d out of range\n", quant_idx); + return AVERROR_INVALIDDATA; + } + } + + *coef_count_ = coef_count; + + return quant_idx; +} + +static void unquantize_dct_coeffs(int32_t block[64], const uint32_t quant[64], + int coef_count, int coef_idx[64], + const uint8_t *scan) +{ + int i; + block[0] = (int)(block[0] * quant[0]) >> 11; + for (i = 0; i < coef_count; i++) { + int idx = coef_idx[i]; + block[scan[idx]] = (int)(block[scan[idx]] * quant[idx]) >> 11; + } +} + +/** + * Read 8x8 block with residue after motion compensation. + * + * @param gb context for reading bits + * @param block place to store read data + * @param masks_count number of masks to decode + * @return 0 on success, negative value in other cases + */ +static int read_residue(GetBitContext *gb, int16_t block[64], int masks_count) +{ + int coef_list[128]; + int mode_list[128]; + int i, sign, mask, ccoef, mode; + int list_start = 64, list_end = 64, list_pos; + int nz_coeff[64]; + int nz_coeff_count = 0; + + coef_list[list_end] = 4; mode_list[list_end++] = 0; + coef_list[list_end] = 24; mode_list[list_end++] = 0; + coef_list[list_end] = 44; mode_list[list_end++] = 0; + coef_list[list_end] = 0; mode_list[list_end++] = 2; + + for (mask = 1 << get_bits(gb, 3); mask; mask >>= 1) { + for (i = 0; i < nz_coeff_count; i++) { + if (!get_bits1(gb)) + continue; + if (block[nz_coeff[i]] < 0) + block[nz_coeff[i]] -= mask; + else + block[nz_coeff[i]] += mask; + masks_count--; + if (masks_count < 0) + return 0; + } + list_pos = list_start; + while (list_pos < list_end) { + if (!(coef_list[list_pos] | mode_list[list_pos]) || !get_bits1(gb)) { + list_pos++; + continue; + } + ccoef = coef_list[list_pos]; + mode = mode_list[list_pos]; + switch (mode) { + case 0: + coef_list[list_pos] = ccoef + 4; + mode_list[list_pos] = 1; + case 2: + if (mode == 2) { + coef_list[list_pos] = 0; + mode_list[list_pos++] = 0; + } + for (i = 0; i < 4; i++, ccoef++) { + if (get_bits1(gb)) { + coef_list[--list_start] = ccoef; + mode_list[ list_start] = 3; + } else { + nz_coeff[nz_coeff_count++] = bink_scan[ccoef]; + sign = -get_bits1(gb); + block[bink_scan[ccoef]] = (mask ^ sign) - sign; + masks_count--; + if (masks_count < 0) + return 0; + } + } + break; + case 1: + mode_list[list_pos] = 2; + for (i = 0; i < 3; i++) { + ccoef += 4; + coef_list[list_end] = ccoef; + mode_list[list_end++] = 2; + } + break; + case 3: + nz_coeff[nz_coeff_count++] = bink_scan[ccoef]; + sign = -get_bits1(gb); + block[bink_scan[ccoef]] = (mask ^ sign) - sign; + coef_list[list_pos] = 0; + mode_list[list_pos++] = 0; + masks_count--; + if (masks_count < 0) + return 0; + break; + } + } + } + + return 0; +} + +/** + * Copy 8x8 block from source to destination, where src and dst may be overlapped + */ +static inline void put_pixels8x8_overlapped(uint8_t *dst, uint8_t *src, int stride) +{ + uint8_t tmp[64]; + int i; + for (i = 0; i < 8; i++) + memcpy(tmp + i*8, src + i*stride, 8); + for (i = 0; i < 8; i++) + memcpy(dst + i*stride, tmp + i*8, 8); +} + +static int binkb_decode_plane(BinkContext *c, AVFrame *frame, GetBitContext *gb, + int plane_idx, int is_key, int is_chroma) +{ + int blk, ret; + int i, j, bx, by; + uint8_t *dst, *ref, *ref_start, *ref_end; + int v, col[2]; + const uint8_t *scan; + int xoff, yoff; + LOCAL_ALIGNED_32(int16_t, block, [64]); + LOCAL_ALIGNED_16(int32_t, dctblock, [64]); + int coordmap[64]; + int ybias = is_key ? -15 : 0; + int qp, quant_idx, coef_count, coef_idx[64]; + + const int stride = frame->linesize[plane_idx]; + int bw = is_chroma ? (c->avctx->width + 15) >> 4 : (c->avctx->width + 7) >> 3; + int bh = is_chroma ? (c->avctx->height + 15) >> 4 : (c->avctx->height + 7) >> 3; + + binkb_init_bundles(c); + ref_start = frame->data[plane_idx]; + ref_end = frame->data[plane_idx] + ((bh - 1) * frame->linesize[plane_idx] + bw - 1) * 8; + + for (i = 0; i < 64; i++) + coordmap[i] = (i & 7) + (i >> 3) * stride; + + for (by = 0; by < bh; by++) { + for (i = 0; i < BINKB_NB_SRC; i++) { + if ((ret = binkb_read_bundle(c, gb, i)) < 0) + return ret; + } + + dst = frame->data[plane_idx] + 8*by*stride; + for (bx = 0; bx < bw; bx++, dst += 8) { + blk = binkb_get_value(c, BINKB_SRC_BLOCK_TYPES); + switch (blk) { + case 0: + break; + case 1: + scan = bink_patterns[get_bits(gb, 4)]; + i = 0; + do { + int mode, run; + + mode = get_bits1(gb); + run = get_bits(gb, binkb_runbits[i]) + 1; + + i += run; + if (i > 64) { + av_log(c->avctx, AV_LOG_ERROR, "Run went out of bounds\n"); + return AVERROR_INVALIDDATA; + } + if (mode) { + v = binkb_get_value(c, BINKB_SRC_COLORS); + for (j = 0; j < run; j++) + dst[coordmap[*scan++]] = v; + } else { + for (j = 0; j < run; j++) + dst[coordmap[*scan++]] = binkb_get_value(c, BINKB_SRC_COLORS); + } + } while (i < 63); + if (i == 63) + dst[coordmap[*scan++]] = binkb_get_value(c, BINKB_SRC_COLORS); + break; + case 2: + memset(dctblock, 0, sizeof(*dctblock) * 64); + dctblock[0] = binkb_get_value(c, BINKB_SRC_INTRA_DC); + qp = binkb_get_value(c, BINKB_SRC_INTRA_Q); + if ((quant_idx = read_dct_coeffs(c, gb, dctblock, bink_scan, &coef_count, coef_idx, qp)) < 0) + return quant_idx; + unquantize_dct_coeffs(dctblock, binkb_intra_quant[quant_idx], coef_count, coef_idx, bink_scan); + c->binkdsp.idct_put(dst, stride, dctblock); + break; + case 3: + xoff = binkb_get_value(c, BINKB_SRC_X_OFF); + yoff = binkb_get_value(c, BINKB_SRC_Y_OFF) + ybias; + ref = dst + xoff + yoff * stride; + if (ref < ref_start || ref > ref_end) { + av_log(c->avctx, AV_LOG_WARNING, "Reference block is out of bounds\n"); + } else if (ref + 8*stride < dst || ref >= dst + 8*stride) { + c->put_pixels_tab(dst, ref, stride, 8); + } else { + put_pixels8x8_overlapped(dst, ref, stride); + } + c->bdsp.clear_block(block); + v = binkb_get_value(c, BINKB_SRC_INTER_COEFS); + read_residue(gb, block, v); + c->binkdsp.add_pixels8(dst, block, stride); + break; + case 4: + xoff = binkb_get_value(c, BINKB_SRC_X_OFF); + yoff = binkb_get_value(c, BINKB_SRC_Y_OFF) + ybias; + ref = dst + xoff + yoff * stride; + if (ref < ref_start || ref > ref_end) { + av_log(c->avctx, AV_LOG_WARNING, "Reference block is out of bounds\n"); + } else if (ref + 8*stride < dst || ref >= dst + 8*stride) { + c->put_pixels_tab(dst, ref, stride, 8); + } else { + put_pixels8x8_overlapped(dst, ref, stride); + } + memset(dctblock, 0, sizeof(*dctblock) * 64); + dctblock[0] = binkb_get_value(c, BINKB_SRC_INTER_DC); + qp = binkb_get_value(c, BINKB_SRC_INTER_Q); + if ((quant_idx = read_dct_coeffs(c, gb, dctblock, bink_scan, &coef_count, coef_idx, qp)) < 0) + return quant_idx; + unquantize_dct_coeffs(dctblock, binkb_inter_quant[quant_idx], coef_count, coef_idx, bink_scan); + c->binkdsp.idct_add(dst, stride, dctblock); + break; + case 5: + v = binkb_get_value(c, BINKB_SRC_COLORS); + c->bdsp.fill_block_tab[1](dst, v, stride, 8); + break; + case 6: + for (i = 0; i < 2; i++) + col[i] = binkb_get_value(c, BINKB_SRC_COLORS); + for (i = 0; i < 8; i++) { + v = binkb_get_value(c, BINKB_SRC_PATTERN); + for (j = 0; j < 8; j++, v >>= 1) + dst[i*stride + j] = col[v & 1]; + } + break; + case 7: + xoff = binkb_get_value(c, BINKB_SRC_X_OFF); + yoff = binkb_get_value(c, BINKB_SRC_Y_OFF) + ybias; + ref = dst + xoff + yoff * stride; + if (ref < ref_start || ref > ref_end) { + av_log(c->avctx, AV_LOG_WARNING, "Reference block is out of bounds\n"); + } else if (ref + 8*stride < dst || ref >= dst + 8*stride) { + c->put_pixels_tab(dst, ref, stride, 8); + } else { + put_pixels8x8_overlapped(dst, ref, stride); + } + break; + case 8: + for (i = 0; i < 8; i++) + memcpy(dst + i*stride, c->bundle[BINKB_SRC_COLORS].cur_ptr + i*8, 8); + c->bundle[BINKB_SRC_COLORS].cur_ptr += 64; + break; + default: + av_log(c->avctx, AV_LOG_ERROR, "Unknown block type %d\n", blk); + return AVERROR_INVALIDDATA; + } + } + } + if (get_bits_count(gb) & 0x1F) //next plane data starts at 32-bit boundary + skip_bits_long(gb, 32 - (get_bits_count(gb) & 0x1F)); + + return 0; +} + +static int bink_put_pixels(BinkContext *c, + uint8_t *dst, uint8_t *prev, int stride, + uint8_t *ref_start, + uint8_t *ref_end) +{ + int xoff = get_value(c, BINK_SRC_X_OFF); + int yoff = get_value(c, BINK_SRC_Y_OFF); + uint8_t *ref = prev + xoff + yoff * stride; + if (ref < ref_start || ref > ref_end) { + av_log(c->avctx, AV_LOG_ERROR, "Copy out of bounds @%d, %d\n", + xoff, yoff); + return AVERROR_INVALIDDATA; + } + c->put_pixels_tab(dst, ref, stride, 8); + + return 0; +} + +static int bink_decode_plane(BinkContext *c, AVFrame *frame, GetBitContext *gb, + int plane_idx, int is_chroma) +{ + int blk, ret; + int i, j, bx, by; + uint8_t *dst, *prev, *ref_start, *ref_end; + int v, col[2]; + const uint8_t *scan; + LOCAL_ALIGNED_32(int16_t, block, [64]); + LOCAL_ALIGNED_16(uint8_t, ublock, [64]); + LOCAL_ALIGNED_16(int32_t, dctblock, [64]); + int coordmap[64], quant_idx, coef_count, coef_idx[64]; + + const int stride = frame->linesize[plane_idx]; + int bw = is_chroma ? (c->avctx->width + 15) >> 4 : (c->avctx->width + 7) >> 3; + int bh = is_chroma ? (c->avctx->height + 15) >> 4 : (c->avctx->height + 7) >> 3; + int width = c->avctx->width >> is_chroma; + int height = c->avctx->height >> is_chroma; + + if (c->version == 'k' && get_bits1(gb)) { + int fill = get_bits(gb, 8); + + dst = frame->data[plane_idx]; + + for (i = 0; i < height; i++) + memset(dst + i * stride, fill, width); + goto end; + } + + init_lengths(c, FFMAX(width, 8), bw); + for (i = 0; i < BINK_NB_SRC; i++) { + ret = read_bundle(gb, c, i); + if (ret < 0) + return ret; + } + + ref_start = c->last->data[plane_idx] ? c->last->data[plane_idx] + : frame->data[plane_idx]; + ref_end = ref_start + + (bw - 1 + c->last->linesize[plane_idx] * (bh - 1)) * 8; + + for (i = 0; i < 64; i++) + coordmap[i] = (i & 7) + (i >> 3) * stride; + + for (by = 0; by < bh; by++) { + if ((ret = read_block_types(c->avctx, gb, &c->bundle[BINK_SRC_BLOCK_TYPES])) < 0) + return ret; + if ((ret = read_block_types(c->avctx, gb, &c->bundle[BINK_SRC_SUB_BLOCK_TYPES])) < 0) + return ret; + if ((ret = read_colors(gb, &c->bundle[BINK_SRC_COLORS], c)) < 0) + return ret; + if ((ret = read_patterns(c->avctx, gb, &c->bundle[BINK_SRC_PATTERN])) < 0) + return ret; + if ((ret = read_motion_values(c->avctx, gb, &c->bundle[BINK_SRC_X_OFF])) < 0) + return ret; + if ((ret = read_motion_values(c->avctx, gb, &c->bundle[BINK_SRC_Y_OFF])) < 0) + return ret; + if ((ret = read_dcs(c->avctx, gb, &c->bundle[BINK_SRC_INTRA_DC], DC_START_BITS, 0)) < 0) + return ret; + if ((ret = read_dcs(c->avctx, gb, &c->bundle[BINK_SRC_INTER_DC], DC_START_BITS, 1)) < 0) + return ret; + if ((ret = read_runs(c->avctx, gb, &c->bundle[BINK_SRC_RUN])) < 0) + return ret; + + dst = frame->data[plane_idx] + 8*by*stride; + prev = (c->last->data[plane_idx] ? c->last->data[plane_idx] + : frame->data[plane_idx]) + 8*by*stride; + for (bx = 0; bx < bw; bx++, dst += 8, prev += 8) { + blk = get_value(c, BINK_SRC_BLOCK_TYPES); + // 16x16 block type on odd line means part of the already decoded block, so skip it + if (((by & 1) || (bx & 1)) && blk == SCALED_BLOCK) { + bx++; + dst += 8; + prev += 8; + continue; + } + switch (blk) { + case SKIP_BLOCK: + c->put_pixels_tab(dst, prev, stride, 8); + break; + case SCALED_BLOCK: + blk = get_value(c, BINK_SRC_SUB_BLOCK_TYPES); + switch (blk) { + case RUN_BLOCK: + if (get_bits_left(gb) < 4) + return AVERROR_INVALIDDATA; + scan = bink_patterns[get_bits(gb, 4)]; + i = 0; + do { + int run = get_value(c, BINK_SRC_RUN) + 1; + + i += run; + if (i > 64) { + av_log(c->avctx, AV_LOG_ERROR, "Run went out of bounds\n"); + return AVERROR_INVALIDDATA; + } + if (get_bits1(gb)) { + v = get_value(c, BINK_SRC_COLORS); + for (j = 0; j < run; j++) + ublock[*scan++] = v; + } else { + for (j = 0; j < run; j++) + ublock[*scan++] = get_value(c, BINK_SRC_COLORS); + } + } while (i < 63); + if (i == 63) + ublock[*scan++] = get_value(c, BINK_SRC_COLORS); + break; + case INTRA_BLOCK: + memset(dctblock, 0, sizeof(*dctblock) * 64); + dctblock[0] = get_value(c, BINK_SRC_INTRA_DC); + if ((quant_idx = read_dct_coeffs(c, gb, dctblock, bink_scan, &coef_count, coef_idx, -1)) < 0) + return quant_idx; + unquantize_dct_coeffs(dctblock, bink_intra_quant[quant_idx], coef_count, coef_idx, bink_scan); + c->binkdsp.idct_put(ublock, 8, dctblock); + break; + case FILL_BLOCK: + v = get_value(c, BINK_SRC_COLORS); + c->bdsp.fill_block_tab[0](dst, v, stride, 16); + break; + case PATTERN_BLOCK: + for (i = 0; i < 2; i++) + col[i] = get_value(c, BINK_SRC_COLORS); + for (j = 0; j < 8; j++) { + v = get_value(c, BINK_SRC_PATTERN); + for (i = 0; i < 8; i++, v >>= 1) + ublock[i + j*8] = col[v & 1]; + } + break; + case RAW_BLOCK: + for (j = 0; j < 8; j++) + for (i = 0; i < 8; i++) + ublock[i + j*8] = get_value(c, BINK_SRC_COLORS); + break; + default: + av_log(c->avctx, AV_LOG_ERROR, "Incorrect 16x16 block type %d\n", blk); + return AVERROR_INVALIDDATA; + } + if (blk != FILL_BLOCK) + c->binkdsp.scale_block(ublock, dst, stride); + bx++; + dst += 8; + prev += 8; + break; + case MOTION_BLOCK: + ret = bink_put_pixels(c, dst, prev, stride, + ref_start, ref_end); + if (ret < 0) + return ret; + break; + case RUN_BLOCK: + scan = bink_patterns[get_bits(gb, 4)]; + i = 0; + do { + int run = get_value(c, BINK_SRC_RUN) + 1; + + i += run; + if (i > 64) { + av_log(c->avctx, AV_LOG_ERROR, "Run went out of bounds\n"); + return AVERROR_INVALIDDATA; + } + if (get_bits1(gb)) { + v = get_value(c, BINK_SRC_COLORS); + for (j = 0; j < run; j++) + dst[coordmap[*scan++]] = v; + } else { + for (j = 0; j < run; j++) + dst[coordmap[*scan++]] = get_value(c, BINK_SRC_COLORS); + } + } while (i < 63); + if (i == 63) + dst[coordmap[*scan++]] = get_value(c, BINK_SRC_COLORS); + break; + case RESIDUE_BLOCK: + ret = bink_put_pixels(c, dst, prev, stride, + ref_start, ref_end); + if (ret < 0) + return ret; + c->bdsp.clear_block(block); + v = get_bits(gb, 7); + read_residue(gb, block, v); + c->binkdsp.add_pixels8(dst, block, stride); + break; + case INTRA_BLOCK: + memset(dctblock, 0, sizeof(*dctblock) * 64); + dctblock[0] = get_value(c, BINK_SRC_INTRA_DC); + if ((quant_idx = read_dct_coeffs(c, gb, dctblock, bink_scan, &coef_count, coef_idx, -1)) < 0) + return quant_idx; + unquantize_dct_coeffs(dctblock, bink_intra_quant[quant_idx], coef_count, coef_idx, bink_scan); + c->binkdsp.idct_put(dst, stride, dctblock); + break; + case FILL_BLOCK: + v = get_value(c, BINK_SRC_COLORS); + c->bdsp.fill_block_tab[1](dst, v, stride, 8); + break; + case INTER_BLOCK: + ret = bink_put_pixels(c, dst, prev, stride, + ref_start, ref_end); + if (ret < 0) + return ret; + memset(dctblock, 0, sizeof(*dctblock) * 64); + dctblock[0] = get_value(c, BINK_SRC_INTER_DC); + if ((quant_idx = read_dct_coeffs(c, gb, dctblock, bink_scan, &coef_count, coef_idx, -1)) < 0) + return quant_idx; + unquantize_dct_coeffs(dctblock, bink_inter_quant[quant_idx], coef_count, coef_idx, bink_scan); + c->binkdsp.idct_add(dst, stride, dctblock); + break; + case PATTERN_BLOCK: + for (i = 0; i < 2; i++) + col[i] = get_value(c, BINK_SRC_COLORS); + for (i = 0; i < 8; i++) { + v = get_value(c, BINK_SRC_PATTERN); + for (j = 0; j < 8; j++, v >>= 1) + dst[i*stride + j] = col[v & 1]; + } + break; + case RAW_BLOCK: + for (i = 0; i < 8; i++) + memcpy(dst + i*stride, c->bundle[BINK_SRC_COLORS].cur_ptr + i*8, 8); + c->bundle[BINK_SRC_COLORS].cur_ptr += 64; + break; + default: + av_log(c->avctx, AV_LOG_ERROR, "Unknown block type %d\n", blk); + return AVERROR_INVALIDDATA; + } + } + } + +end: + if (get_bits_count(gb) & 0x1F) //next plane data starts at 32-bit boundary + skip_bits_long(gb, 32 - (get_bits_count(gb) & 0x1F)); + + return 0; +} + +static int decode_frame(AVCodecContext *avctx, AVFrame *frame, + int *got_frame, AVPacket *pkt) +{ + BinkContext * const c = avctx->priv_data; + GetBitContext gb; + int plane, plane_idx, ret; + int bits_count = pkt->size << 3; + + if (c->version > 'b') { + if ((ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF)) < 0) + return ret; + } else { + if ((ret = ff_reget_buffer(avctx, c->last, 0)) < 0) + return ret; + if ((ret = av_frame_ref(frame, c->last)) < 0) + return ret; + } + + init_get_bits(&gb, pkt->data, bits_count); + if (c->has_alpha) { + if (c->version >= 'i') + skip_bits_long(&gb, 32); + if ((ret = bink_decode_plane(c, frame, &gb, 3, 0)) < 0) + return ret; + } + if (c->version >= 'i') + skip_bits_long(&gb, 32); + + c->frame_num++; + + for (plane = 0; plane < 3; plane++) { + plane_idx = (!plane || !c->swap_planes) ? plane : (plane ^ 3); + + if (c->version > 'b') { + if ((ret = bink_decode_plane(c, frame, &gb, plane_idx, !!plane)) < 0) + return ret; + } else { + if ((ret = binkb_decode_plane(c, frame, &gb, plane_idx, + c->frame_num == 1, !!plane)) < 0) + return ret; + } + if (get_bits_count(&gb) >= bits_count) + break; + } + emms_c(); + + if (c->version > 'b') { + if ((ret = av_frame_replace(c->last, frame)) < 0) + return ret; + } + + *got_frame = 1; + + /* always report that the buffer was completely consumed */ + return pkt->size; +} + +static av_cold void bink_init_vlcs(void) +{ + for (int i = 0, offset = 0; i < 16; i++) { + static VLCElem table[976]; + const int maxbits = bink_tree_lens[i][15]; + bink_trees[i].table = table + offset; + bink_trees[i].table_allocated = 1 << maxbits; + offset += bink_trees[i].table_allocated; + vlc_init(&bink_trees[i], maxbits, 16, + bink_tree_lens[i], 1, 1, + bink_tree_bits[i], 1, 1, VLC_INIT_USE_STATIC | VLC_INIT_LE); + } +} + +/** + * Calculate quantization tables for version b + */ +static av_cold void binkb_calc_quant(void) +{ + uint8_t inv_bink_scan[64]; + static const int s[64]={ + 1073741824,1489322693,1402911301,1262586814,1073741824, 843633538, 581104888, 296244703, + 1489322693,2065749918,1945893874,1751258219,1489322693,1170153332, 806015634, 410903207, + 1402911301,1945893874,1832991949,1649649171,1402911301,1102260336, 759250125, 387062357, + 1262586814,1751258219,1649649171,1484645031,1262586814, 992008094, 683307060, 348346918, + 1073741824,1489322693,1402911301,1262586814,1073741824, 843633538, 581104888, 296244703, + 843633538,1170153332,1102260336, 992008094, 843633538, 662838617, 456571181, 232757969, + 581104888, 806015634, 759250125, 683307060, 581104888, 456571181, 314491699, 160326478, + 296244703, 410903207, 387062357, 348346918, 296244703, 232757969, 160326478, 81733730, + }; + int i, j; +#define C (1LL<<30) + for (i = 0; i < 64; i++) + inv_bink_scan[bink_scan[i]] = i; + + for (j = 0; j < 16; j++) { + for (i = 0; i < 64; i++) { + int k = inv_bink_scan[i]; + binkb_intra_quant[j][k] = binkb_intra_seed[i] * (int64_t)s[i] * + binkb_num[j]/(binkb_den[j] * (C>>12)); + binkb_inter_quant[j][k] = binkb_inter_seed[i] * (int64_t)s[i] * + binkb_num[j]/(binkb_den[j] * (C>>12)); + } + } +} + +static av_cold int decode_init(AVCodecContext *avctx) +{ + static AVOnce init_static_once = AV_ONCE_INIT; + BinkContext * const c = avctx->priv_data; + HpelDSPContext hdsp; + int ret; + int flags; + + c->version = avctx->codec_tag >> 24; + if (avctx->extradata_size < 4) { + av_log(avctx, AV_LOG_ERROR, "Extradata missing or too short\n"); + return AVERROR_INVALIDDATA; + } + flags = AV_RL32(avctx->extradata); + c->has_alpha = flags & BINK_FLAG_ALPHA; + c->swap_planes = c->version >= 'h'; + c->avctx = avctx; + + if ((ret = av_image_check_size(avctx->width, avctx->height, 0, avctx)) < 0) + return ret; + + c->last = av_frame_alloc(); + if (!c->last) + return AVERROR(ENOMEM); + + avctx->pix_fmt = c->has_alpha ? AV_PIX_FMT_YUVA420P : AV_PIX_FMT_YUV420P; + avctx->color_range = c->version == 'k' ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG; + + ff_blockdsp_init(&c->bdsp); + ff_hpeldsp_init(&hdsp, avctx->flags); + c->put_pixels_tab = hdsp.put_pixels_tab[1][0]; + ff_binkdsp_init(&c->binkdsp); + + if ((ret = init_bundles(c)) < 0) + return ret; + + if (c->version == 'b') { + static AVOnce binkb_init_once = AV_ONCE_INIT; + ff_thread_once(&binkb_init_once, binkb_calc_quant); + } + ff_thread_once(&init_static_once, bink_init_vlcs); + + return 0; +} + +static av_cold int decode_end(AVCodecContext *avctx) +{ + BinkContext * const c = avctx->priv_data; + + av_frame_free(&c->last); + + free_bundles(c); + return 0; +} + +static void flush(AVCodecContext *avctx) +{ + BinkContext * const c = avctx->priv_data; + + c->frame_num = 0; +} + +const FFCodec ff_bink_decoder = { + .p.name = "binkvideo", + CODEC_LONG_NAME("Bink video"), + .p.type = AVMEDIA_TYPE_VIDEO, + .p.id = AV_CODEC_ID_BINKVIDEO, + .priv_data_size = sizeof(BinkContext), + .init = decode_init, + .close = decode_end, + FF_CODEC_DECODE_CB(decode_frame), + .flush = flush, + .p.capabilities = AV_CODEC_CAP_DR1, + .caps_internal = FF_CODEC_CAP_INIT_CLEANUP, +}; diff --git a/Code/BF2/External/ffmpeg-bink/libavcodec/binkaudio.c b/Code/BF2/External/ffmpeg-bink/libavcodec/binkaudio.c new file mode 100644 index 000000000..265f93a82 --- /dev/null +++ b/Code/BF2/External/ffmpeg-bink/libavcodec/binkaudio.c @@ -0,0 +1,397 @@ +/* + * Bink Audio decoder + * Copyright (c) 2007-2011 Peter Ross (pross@xvid.org) + * Copyright (c) 2009 Daniel Verkamp (daniel@drv.nu) + * + * This file is part of FFmpeg. + * + * FFmpeg is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * FFmpeg is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with FFmpeg; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/** + * @file + * Bink Audio decoder + * + * Technical details here: + * http://wiki.multimedia.cx/index.php?title=Bink_Audio + */ + +#include "config_components.h" + +#include "libavutil/channel_layout.h" +#include "libavutil/intfloat.h" +#include "libavutil/mem_internal.h" +#include "libavutil/tx.h" + +#define BITSTREAM_READER_LE +#include "avcodec.h" +#include "decode.h" +#include "get_bits.h" +#include "codec_internal.h" +#include "internal.h" +#include "wma_freqs.h" + +#define MAX_DCT_CHANNELS 6 +#define MAX_CHANNELS 2 +#define BINK_BLOCK_MAX_SIZE (MAX_CHANNELS << 11) + +typedef struct BinkAudioContext { + GetBitContext gb; + int version_b; ///< Bink version 'b' + int first; + int channels; + int ch_offset; + int frame_len; ///< transform size (samples) + int overlap_len; ///< overlap size (samples) + int block_size; + int num_bands; + float root; + unsigned int bands[26]; + float previous[MAX_DCT_CHANNELS][BINK_BLOCK_MAX_SIZE / 16]; ///< coeffs from previous audio block + float quant_table[96]; + AVPacket *pkt; + AVTXContext *tx; + av_tx_fn tx_fn; +} BinkAudioContext; + + +static av_cold int decode_init(AVCodecContext *avctx) +{ + BinkAudioContext *s = avctx->priv_data; + int sample_rate = avctx->sample_rate; + int sample_rate_half; + int i, ret; + int frame_len_bits; + int max_channels = avctx->codec->id == AV_CODEC_ID_BINKAUDIO_RDFT ? MAX_CHANNELS : MAX_DCT_CHANNELS; + int channels = avctx->ch_layout.nb_channels; + + /* determine frame length */ + if (avctx->sample_rate < 22050) { + frame_len_bits = 9; + } else if (avctx->sample_rate < 44100) { + frame_len_bits = 10; + } else { + frame_len_bits = 11; + } + + if (channels < 1 || channels > max_channels) { + av_log(avctx, AV_LOG_ERROR, "invalid number of channels: %d\n", channels); + return AVERROR_INVALIDDATA; + } + av_channel_layout_uninit(&avctx->ch_layout); + av_channel_layout_default(&avctx->ch_layout, channels); + + s->version_b = avctx->extradata_size >= 4 && avctx->extradata[3] == 'b'; + + if (avctx->codec->id == AV_CODEC_ID_BINKAUDIO_RDFT) { + // audio is already interleaved for the RDFT format variant + avctx->sample_fmt = AV_SAMPLE_FMT_FLT; + if (sample_rate > INT_MAX / channels) + return AVERROR_INVALIDDATA; + sample_rate *= channels; + s->channels = 1; + if (!s->version_b) + frame_len_bits += av_log2(channels); + } else { + s->channels = channels; + avctx->sample_fmt = AV_SAMPLE_FMT_FLTP; + } + + s->frame_len = 1 << frame_len_bits; + s->overlap_len = s->frame_len / 16; + s->block_size = (s->frame_len - s->overlap_len) * FFMIN(MAX_CHANNELS, s->channels); + sample_rate_half = (sample_rate + 1LL) / 2; + if (avctx->codec->id == AV_CODEC_ID_BINKAUDIO_RDFT) + s->root = 2.0 / (sqrt(s->frame_len) * 32768.0); + else + s->root = s->frame_len / (sqrt(s->frame_len) * 32768.0); + for (i = 0; i < 96; i++) { + /* constant is result of 0.066399999/log10(M_E) */ + s->quant_table[i] = expf(i * 0.15289164787221953823f) * s->root; + } + + /* calculate number of bands */ + for (s->num_bands = 1; s->num_bands < 25; s->num_bands++) + if (sample_rate_half <= ff_wma_critical_freqs[s->num_bands - 1]) + break; + + /* populate bands data */ + s->bands[0] = 2; + for (i = 1; i < s->num_bands; i++) + s->bands[i] = (ff_wma_critical_freqs[i - 1] * s->frame_len / sample_rate_half) & ~1; + s->bands[s->num_bands] = s->frame_len; + + s->first = 1; + + if (CONFIG_BINKAUDIO_RDFT_DECODER && avctx->codec->id == AV_CODEC_ID_BINKAUDIO_RDFT) { + float scale = 0.5; + ret = av_tx_init(&s->tx, &s->tx_fn, AV_TX_FLOAT_RDFT, 1, 1 << frame_len_bits, &scale, 0); + } else if (CONFIG_BINKAUDIO_DCT_DECODER) { + float scale = 1.0 / (1 << frame_len_bits); + ret = av_tx_init(&s->tx, &s->tx_fn, AV_TX_FLOAT_DCT, 1, 1 << (frame_len_bits - 1), &scale, 0); + } else { + av_assert0(0); + } + if (ret < 0) + return ret; + + s->pkt = avctx->internal->in_pkt; + + return 0; +} + +static float get_float(GetBitContext *gb) +{ + int power = get_bits(gb, 5); + float f = ldexpf(get_bits(gb, 23), power - 23); + if (get_bits1(gb)) + f = -f; + return f; +} + +static const uint8_t rle_length_tab[16] = { + 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 32, 64 +}; + +/** + * Decode Bink Audio block + * @param[out] out Output buffer (must contain s->block_size elements) + * @return 0 on success, negative error code on failure + */ +static int decode_block(BinkAudioContext *s, float **out, int use_dct, + int channels, int ch_offset) +{ + int ch, i, j, k; + float q, quant[25]; + int width, coeff; + GetBitContext *gb = &s->gb; + LOCAL_ALIGNED_32(float, coeffs, [4098]); + + if (use_dct) + skip_bits(gb, 2); + + for (ch = 0; ch < channels; ch++) { + if (s->version_b) { + if (get_bits_left(gb) < 64) + return AVERROR_INVALIDDATA; + coeffs[0] = av_int2float(get_bits_long(gb, 32)) * s->root; + coeffs[1] = av_int2float(get_bits_long(gb, 32)) * s->root; + } else { + if (get_bits_left(gb) < 58) + return AVERROR_INVALIDDATA; + coeffs[0] = get_float(gb) * s->root; + coeffs[1] = get_float(gb) * s->root; + } + + if (get_bits_left(gb) < s->num_bands * 8) + return AVERROR_INVALIDDATA; + for (i = 0; i < s->num_bands; i++) { + int value = get_bits(gb, 8); + quant[i] = s->quant_table[FFMIN(value, 95)]; + } + + k = 0; + q = quant[0]; + + // parse coefficients + i = 2; + while (i < s->frame_len) { + if (s->version_b) { + j = i + 16; + } else { + int v = get_bits1(gb); + if (v) { + v = get_bits(gb, 4); + j = i + rle_length_tab[v] * 8; + } else { + j = i + 8; + } + } + + j = FFMIN(j, s->frame_len); + + width = get_bits(gb, 4); + if (width == 0) { + memset(coeffs + i, 0, (j - i) * sizeof(*coeffs)); + i = j; + while (s->bands[k] < i) + q = quant[k++]; + } else { + while (i < j) { + if (s->bands[k] == i) + q = quant[k++]; + coeff = get_bits(gb, width); + if (coeff) { + int v; + v = get_bits1(gb); + if (v) + coeffs[i] = -q * coeff; + else + coeffs[i] = q * coeff; + } else { + coeffs[i] = 0.0f; + } + i++; + } + } + } + + if (CONFIG_BINKAUDIO_DCT_DECODER && use_dct) { + coeffs[0] /= 0.5; + s->tx_fn(s->tx, out[ch + ch_offset], coeffs, sizeof(float)); + } else if (CONFIG_BINKAUDIO_RDFT_DECODER) { + for (int i = 2; i < s->frame_len; i += 2) + coeffs[i + 1] *= -1; + + coeffs[s->frame_len + 0] = coeffs[1]; + coeffs[s->frame_len + 1] = coeffs[1] = 0; + s->tx_fn(s->tx, out[ch + ch_offset], coeffs, sizeof(AVComplexFloat)); + } + } + + for (ch = 0; ch < channels; ch++) { + int j; + int count = s->overlap_len * channels; + if (!s->first) { + j = ch; + for (i = 0; i < s->overlap_len; i++, j += channels) + out[ch + ch_offset][i] = (s->previous[ch + ch_offset][i] * (count - j) + + out[ch + ch_offset][i] * j) / count; + } + memcpy(s->previous[ch + ch_offset], &out[ch + ch_offset][s->frame_len - s->overlap_len], + s->overlap_len * sizeof(*s->previous[ch + ch_offset])); + } + + s->first = 0; + + return 0; +} + +static av_cold int decode_end(AVCodecContext *avctx) +{ + BinkAudioContext * s = avctx->priv_data; + av_tx_uninit(&s->tx); + return 0; +} + +static void get_bits_align32(GetBitContext *s) +{ + int n = (-get_bits_count(s)) & 31; + if (n) skip_bits(s, n); +} + +static int binkaudio_receive_frame(AVCodecContext *avctx, AVFrame *frame) +{ + BinkAudioContext *s = avctx->priv_data; + GetBitContext *gb = &s->gb; + int new_pkt, ret; + +again: + new_pkt = !s->pkt->data; + if (!s->pkt->data) { + ret = ff_decode_get_packet(avctx, s->pkt); + if (ret < 0) { + s->ch_offset = 0; + return ret; + } + + if (s->pkt->size < 4) { + av_log(avctx, AV_LOG_ERROR, "Packet is too small\n"); + ret = AVERROR_INVALIDDATA; + goto fail; + } + + ret = init_get_bits8(gb, s->pkt->data, s->pkt->size); + if (ret < 0) + goto fail; + + /* skip reported size */ + skip_bits_long(gb, 32); + } + + /* get output buffer */ + if (s->ch_offset == 0) { + frame->nb_samples = s->frame_len; + if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) + goto fail; + if (!new_pkt) + frame->pts = AV_NOPTS_VALUE; + } + + if (decode_block(s, (float **)frame->extended_data, + avctx->codec->id == AV_CODEC_ID_BINKAUDIO_DCT, + FFMIN(MAX_CHANNELS, s->channels - s->ch_offset), s->ch_offset)) { + av_log(avctx, AV_LOG_ERROR, "Incomplete packet\n"); + ret = AVERROR_INVALIDDATA; + goto fail; + } + s->ch_offset += MAX_CHANNELS; + get_bits_align32(gb); + if (!get_bits_left(gb)) { + memset(gb, 0, sizeof(*gb)); + av_packet_unref(s->pkt); + } + if (s->ch_offset >= s->channels) { + s->ch_offset = 0; + } else { + goto again; + } + + frame->nb_samples = s->block_size / FFMIN(avctx->ch_layout.nb_channels, MAX_CHANNELS); + + return 0; +fail: + s->ch_offset = 0; + av_packet_unref(s->pkt); + return ret; +} + +static void decode_flush(AVCodecContext *avctx) +{ + BinkAudioContext *const s = avctx->priv_data; + + /* s->pkt coincides with avctx->internal->in_pkt + * and is unreferenced generically when flushing. */ + s->first = 1; + s->ch_offset = 0; +} + +const FFCodec ff_binkaudio_rdft_decoder = { + .p.name = "binkaudio_rdft", + CODEC_LONG_NAME("Bink Audio (RDFT)"), + .p.type = AVMEDIA_TYPE_AUDIO, + .p.id = AV_CODEC_ID_BINKAUDIO_RDFT, + .priv_data_size = sizeof(BinkAudioContext), + .init = decode_init, + .flush = decode_flush, + .close = decode_end, + FF_CODEC_RECEIVE_FRAME_CB(binkaudio_receive_frame), + .p.capabilities = AV_CODEC_CAP_DR1, + .caps_internal = FF_CODEC_CAP_INIT_CLEANUP, +}; + +const FFCodec ff_binkaudio_dct_decoder = { + .p.name = "binkaudio_dct", + CODEC_LONG_NAME("Bink Audio (DCT)"), + .p.type = AVMEDIA_TYPE_AUDIO, + .p.id = AV_CODEC_ID_BINKAUDIO_DCT, + .priv_data_size = sizeof(BinkAudioContext), + .init = decode_init, + .flush = decode_flush, + .close = decode_end, + FF_CODEC_RECEIVE_FRAME_CB(binkaudio_receive_frame), + .p.capabilities = AV_CODEC_CAP_DR1, + .caps_internal = FF_CODEC_CAP_INIT_CLEANUP, +}; diff --git a/Code/BF2/External/ffmpeg-bink/libavcodec/binkdata.h b/Code/BF2/External/ffmpeg-bink/libavcodec/binkdata.h new file mode 100644 index 000000000..57619beee --- /dev/null +++ b/Code/BF2/External/ffmpeg-bink/libavcodec/binkdata.h @@ -0,0 +1,655 @@ +/* + * Bink video decoder + * Copyright (C) 2009 Konstantin Shishkov + * + * This file is part of FFmpeg. + * + * FFmpeg is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * FFmpeg is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with FFmpeg; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef AVCODEC_BINKDATA_H +#define AVCODEC_BINKDATA_H + +#include + +/** Bink DCT and residue 8x8 block scan order */ +static const uint8_t bink_scan[64] = { + 0, 1, 8, 9, 2, 3, 10, 11, + 4, 5, 12, 13, 6, 7, 14, 15, + 20, 21, 28, 29, 22, 23, 30, 31, + 16, 17, 24, 25, 32, 33, 40, 41, + 34, 35, 42, 43, 48, 49, 56, 57, + 50, 51, 58, 59, 18, 19, 26, 27, + 36, 37, 44, 45, 38, 39, 46, 47, + 52, 53, 60, 61, 54, 55, 62, 63 +}; + +static const uint8_t bink_tree_bits[16][16] = { + { + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, + }, + { + 0x00, 0x01, 0x03, 0x05, 0x07, 0x09, 0x0B, 0x0D, + 0x0F, 0x13, 0x15, 0x17, 0x19, 0x1B, 0x1D, 0x1F, + }, + { + 0x00, 0x02, 0x01, 0x09, 0x05, 0x15, 0x0D, 0x1D, + 0x03, 0x13, 0x0B, 0x1B, 0x07, 0x17, 0x0F, 0x1F, + }, + { + 0x00, 0x02, 0x06, 0x01, 0x09, 0x05, 0x0D, 0x1D, + 0x03, 0x13, 0x0B, 0x1B, 0x07, 0x17, 0x0F, 0x1F, + }, + { + 0x00, 0x04, 0x02, 0x06, 0x01, 0x09, 0x05, 0x0D, + 0x03, 0x13, 0x0B, 0x1B, 0x07, 0x17, 0x0F, 0x1F, + }, + { + 0x00, 0x04, 0x02, 0x0A, 0x06, 0x0E, 0x01, 0x09, + 0x05, 0x0D, 0x03, 0x0B, 0x07, 0x17, 0x0F, 0x1F, + }, + { + 0x00, 0x02, 0x0A, 0x06, 0x0E, 0x01, 0x09, 0x05, + 0x0D, 0x03, 0x0B, 0x1B, 0x07, 0x17, 0x0F, 0x1F, + }, + { + 0x00, 0x01, 0x05, 0x03, 0x13, 0x0B, 0x1B, 0x3B, + 0x07, 0x27, 0x17, 0x37, 0x0F, 0x2F, 0x1F, 0x3F, + }, + { + 0x00, 0x01, 0x03, 0x13, 0x0B, 0x2B, 0x1B, 0x3B, + 0x07, 0x27, 0x17, 0x37, 0x0F, 0x2F, 0x1F, 0x3F, + }, + { + 0x00, 0x01, 0x05, 0x0D, 0x03, 0x13, 0x0B, 0x1B, + 0x07, 0x27, 0x17, 0x37, 0x0F, 0x2F, 0x1F, 0x3F, + }, + { + 0x00, 0x02, 0x01, 0x05, 0x0D, 0x03, 0x13, 0x0B, + 0x1B, 0x07, 0x17, 0x37, 0x0F, 0x2F, 0x1F, 0x3F, + }, + { + 0x00, 0x01, 0x09, 0x05, 0x0D, 0x03, 0x13, 0x0B, + 0x1B, 0x07, 0x17, 0x37, 0x0F, 0x2F, 0x1F, 0x3F, + }, + { + 0x00, 0x02, 0x01, 0x03, 0x13, 0x0B, 0x1B, 0x3B, + 0x07, 0x27, 0x17, 0x37, 0x0F, 0x2F, 0x1F, 0x3F, + }, + { + 0x00, 0x01, 0x05, 0x03, 0x07, 0x27, 0x17, 0x37, + 0x0F, 0x4F, 0x2F, 0x6F, 0x1F, 0x5F, 0x3F, 0x7F, + }, + { + 0x00, 0x01, 0x05, 0x03, 0x07, 0x17, 0x37, 0x77, + 0x0F, 0x4F, 0x2F, 0x6F, 0x1F, 0x5F, 0x3F, 0x7F, + }, + { + 0x00, 0x02, 0x01, 0x05, 0x03, 0x07, 0x27, 0x17, + 0x37, 0x0F, 0x2F, 0x6F, 0x1F, 0x5F, 0x3F, 0x7F, + }, +}; + +static const uint8_t bink_tree_lens[16][16] = { + { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 }, + { 1, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }, + { 2, 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }, + { 2, 3, 3, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }, + { 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5 }, + { 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5 }, + { 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5 }, + { 1, 3, 3, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6 }, + { 1, 2, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6 }, + { 1, 3, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6 }, + { 2, 2, 3, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6 }, + { 1, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6 }, + { 2, 2, 2, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6 }, + { 1, 3, 3, 3, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7 }, + { 1, 3, 3, 3, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, + { 2, 2, 3, 3, 3, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7 }, +}; + +static const uint8_t bink_patterns[16][64] = { + { + 0x00, 0x08, 0x10, 0x18, 0x20, 0x28, 0x30, 0x38, + 0x39, 0x31, 0x29, 0x21, 0x19, 0x11, 0x09, 0x01, + 0x02, 0x0A, 0x12, 0x1A, 0x22, 0x2A, 0x32, 0x3A, + 0x3B, 0x33, 0x2B, 0x23, 0x1B, 0x13, 0x0B, 0x03, + 0x04, 0x0C, 0x14, 0x1C, 0x24, 0x2C, 0x34, 0x3C, + 0x3D, 0x35, 0x2D, 0x25, 0x1D, 0x15, 0x0D, 0x05, + 0x06, 0x0E, 0x16, 0x1E, 0x26, 0x2E, 0x36, 0x3E, + 0x3F, 0x37, 0x2F, 0x27, 0x1F, 0x17, 0x0F, 0x07, + }, + { + 0x3B, 0x3A, 0x39, 0x38, 0x30, 0x31, 0x32, 0x33, + 0x2B, 0x2A, 0x29, 0x28, 0x20, 0x21, 0x22, 0x23, + 0x1B, 0x1A, 0x19, 0x18, 0x10, 0x11, 0x12, 0x13, + 0x0B, 0x0A, 0x09, 0x08, 0x00, 0x01, 0x02, 0x03, + 0x04, 0x05, 0x06, 0x07, 0x0F, 0x0E, 0x0D, 0x0C, + 0x14, 0x15, 0x16, 0x17, 0x1F, 0x1E, 0x1D, 0x1C, + 0x24, 0x25, 0x26, 0x27, 0x2F, 0x2E, 0x2D, 0x2C, + 0x34, 0x35, 0x36, 0x37, 0x3F, 0x3E, 0x3D, 0x3C, + }, + { + 0x19, 0x11, 0x12, 0x1A, 0x1B, 0x13, 0x0B, 0x03, + 0x02, 0x0A, 0x09, 0x01, 0x00, 0x08, 0x10, 0x18, + 0x20, 0x28, 0x30, 0x38, 0x39, 0x31, 0x29, 0x2A, + 0x32, 0x3A, 0x3B, 0x33, 0x2B, 0x23, 0x22, 0x21, + 0x1D, 0x15, 0x16, 0x1E, 0x1F, 0x17, 0x0F, 0x07, + 0x06, 0x0E, 0x0D, 0x05, 0x04, 0x0C, 0x14, 0x1C, + 0x24, 0x2C, 0x34, 0x3C, 0x3D, 0x35, 0x2D, 0x2E, + 0x36, 0x3E, 0x3F, 0x37, 0x2F, 0x27, 0x26, 0x25, + }, + { + 0x03, 0x0B, 0x02, 0x0A, 0x01, 0x09, 0x00, 0x08, + 0x10, 0x18, 0x11, 0x19, 0x12, 0x1A, 0x13, 0x1B, + 0x23, 0x2B, 0x22, 0x2A, 0x21, 0x29, 0x20, 0x28, + 0x30, 0x38, 0x31, 0x39, 0x32, 0x3A, 0x33, 0x3B, + 0x3C, 0x34, 0x3D, 0x35, 0x3E, 0x36, 0x3F, 0x37, + 0x2F, 0x27, 0x2E, 0x26, 0x2D, 0x25, 0x2C, 0x24, + 0x1C, 0x14, 0x1D, 0x15, 0x1E, 0x16, 0x1F, 0x17, + 0x0F, 0x07, 0x0E, 0x06, 0x0D, 0x05, 0x0C, 0x04, + }, + { + 0x18, 0x19, 0x10, 0x11, 0x08, 0x09, 0x00, 0x01, + 0x02, 0x03, 0x0A, 0x0B, 0x12, 0x13, 0x1A, 0x1B, + 0x1C, 0x1D, 0x14, 0x15, 0x0C, 0x0D, 0x04, 0x05, + 0x06, 0x07, 0x0E, 0x0F, 0x16, 0x17, 0x1E, 0x1F, + 0x27, 0x26, 0x2F, 0x2E, 0x37, 0x36, 0x3F, 0x3E, + 0x3D, 0x3C, 0x35, 0x34, 0x2D, 0x2C, 0x25, 0x24, + 0x23, 0x22, 0x2B, 0x2A, 0x33, 0x32, 0x3B, 0x3A, + 0x39, 0x38, 0x31, 0x30, 0x29, 0x28, 0x21, 0x20, + }, + { + 0x00, 0x01, 0x02, 0x03, 0x08, 0x09, 0x0A, 0x0B, + 0x10, 0x11, 0x12, 0x13, 0x18, 0x19, 0x1A, 0x1B, + 0x20, 0x21, 0x22, 0x23, 0x28, 0x29, 0x2A, 0x2B, + 0x30, 0x31, 0x32, 0x33, 0x38, 0x39, 0x3A, 0x3B, + 0x04, 0x05, 0x06, 0x07, 0x0C, 0x0D, 0x0E, 0x0F, + 0x14, 0x15, 0x16, 0x17, 0x1C, 0x1D, 0x1E, 0x1F, + 0x24, 0x25, 0x26, 0x27, 0x2C, 0x2D, 0x2E, 0x2F, + 0x34, 0x35, 0x36, 0x37, 0x3C, 0x3D, 0x3E, 0x3F, + }, + { + 0x06, 0x07, 0x0F, 0x0E, 0x0D, 0x05, 0x0C, 0x04, + 0x03, 0x0B, 0x02, 0x0A, 0x09, 0x01, 0x00, 0x08, + 0x10, 0x18, 0x11, 0x19, 0x12, 0x1A, 0x13, 0x1B, + 0x14, 0x1C, 0x15, 0x1D, 0x16, 0x1E, 0x17, 0x1F, + 0x27, 0x2F, 0x26, 0x2E, 0x25, 0x2D, 0x24, 0x2C, + 0x23, 0x2B, 0x22, 0x2A, 0x21, 0x29, 0x20, 0x28, + 0x31, 0x30, 0x38, 0x39, 0x3A, 0x32, 0x3B, 0x33, + 0x3C, 0x34, 0x3D, 0x35, 0x36, 0x37, 0x3F, 0x3E, + }, + { + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x0F, 0x0E, 0x0D, 0x0C, 0x0B, 0x0A, 0x09, 0x08, + 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, + 0x1F, 0x1E, 0x1D, 0x1C, 0x1B, 0x1A, 0x19, 0x18, + 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, + 0x2F, 0x2E, 0x2D, 0x2C, 0x2B, 0x2A, 0x29, 0x28, + 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, + 0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38, + }, + { + 0x00, 0x08, 0x09, 0x01, 0x02, 0x03, 0x0B, 0x0A, + 0x12, 0x13, 0x1B, 0x1A, 0x19, 0x11, 0x10, 0x18, + 0x20, 0x28, 0x29, 0x21, 0x22, 0x23, 0x2B, 0x2A, + 0x32, 0x31, 0x30, 0x38, 0x39, 0x3A, 0x3B, 0x33, + 0x34, 0x3C, 0x3D, 0x3E, 0x3F, 0x37, 0x36, 0x35, + 0x2D, 0x2C, 0x24, 0x25, 0x26, 0x2E, 0x2F, 0x27, + 0x1F, 0x17, 0x16, 0x1E, 0x1D, 0x1C, 0x14, 0x15, + 0x0D, 0x0C, 0x04, 0x05, 0x06, 0x0E, 0x0F, 0x07, + }, + { + 0x18, 0x19, 0x10, 0x11, 0x08, 0x09, 0x00, 0x01, + 0x02, 0x03, 0x0A, 0x0B, 0x12, 0x13, 0x1A, 0x1B, + 0x1C, 0x1D, 0x14, 0x15, 0x0C, 0x0D, 0x04, 0x05, + 0x06, 0x07, 0x0E, 0x0F, 0x16, 0x17, 0x1E, 0x1F, + 0x26, 0x27, 0x2E, 0x2F, 0x36, 0x37, 0x3E, 0x3F, + 0x3C, 0x3D, 0x34, 0x35, 0x2C, 0x2D, 0x24, 0x25, + 0x22, 0x23, 0x2A, 0x2B, 0x32, 0x33, 0x3A, 0x3B, + 0x38, 0x39, 0x30, 0x31, 0x28, 0x29, 0x20, 0x21, + }, + { + 0x00, 0x08, 0x01, 0x09, 0x02, 0x0A, 0x03, 0x0B, + 0x13, 0x1B, 0x12, 0x1A, 0x11, 0x19, 0x10, 0x18, + 0x20, 0x28, 0x21, 0x29, 0x22, 0x2A, 0x23, 0x2B, + 0x33, 0x3B, 0x32, 0x3A, 0x31, 0x39, 0x30, 0x38, + 0x3C, 0x34, 0x3D, 0x35, 0x3E, 0x36, 0x3F, 0x37, + 0x2F, 0x27, 0x2E, 0x26, 0x2D, 0x25, 0x2C, 0x24, + 0x1F, 0x17, 0x1E, 0x16, 0x1D, 0x15, 0x1C, 0x14, + 0x0C, 0x04, 0x0D, 0x05, 0x0E, 0x06, 0x0F, 0x07, + }, + { + 0x00, 0x08, 0x10, 0x18, 0x19, 0x1A, 0x1B, 0x13, + 0x0B, 0x03, 0x02, 0x01, 0x09, 0x11, 0x12, 0x0A, + 0x04, 0x0C, 0x14, 0x1C, 0x1D, 0x1E, 0x1F, 0x17, + 0x0F, 0x07, 0x06, 0x05, 0x0D, 0x15, 0x16, 0x0E, + 0x24, 0x2C, 0x34, 0x3C, 0x3D, 0x3E, 0x3F, 0x37, + 0x2F, 0x27, 0x26, 0x25, 0x2D, 0x35, 0x36, 0x2E, + 0x20, 0x28, 0x30, 0x38, 0x39, 0x3A, 0x3B, 0x33, + 0x2B, 0x23, 0x22, 0x21, 0x29, 0x31, 0x32, 0x2A, + }, + { + 0x00, 0x08, 0x09, 0x01, 0x02, 0x03, 0x0B, 0x0A, + 0x13, 0x1B, 0x1A, 0x12, 0x11, 0x10, 0x18, 0x19, + 0x21, 0x20, 0x28, 0x29, 0x2A, 0x22, 0x23, 0x2B, + 0x33, 0x3B, 0x3A, 0x32, 0x31, 0x39, 0x38, 0x30, + 0x34, 0x3C, 0x3D, 0x35, 0x36, 0x3E, 0x3F, 0x37, + 0x2F, 0x27, 0x26, 0x2E, 0x2D, 0x2C, 0x24, 0x25, + 0x1D, 0x1C, 0x14, 0x15, 0x16, 0x1E, 0x1F, 0x17, + 0x0E, 0x0F, 0x07, 0x06, 0x05, 0x0D, 0x0C, 0x04, + }, + { + 0x18, 0x10, 0x08, 0x00, 0x01, 0x02, 0x03, 0x0B, + 0x13, 0x1B, 0x1A, 0x19, 0x11, 0x0A, 0x09, 0x12, + 0x1C, 0x14, 0x0C, 0x04, 0x05, 0x06, 0x07, 0x0F, + 0x17, 0x1F, 0x1E, 0x1D, 0x15, 0x0E, 0x0D, 0x16, + 0x3C, 0x34, 0x2C, 0x24, 0x25, 0x26, 0x27, 0x2F, + 0x37, 0x3F, 0x3E, 0x3D, 0x35, 0x2E, 0x2D, 0x36, + 0x38, 0x30, 0x28, 0x20, 0x21, 0x22, 0x23, 0x2B, + 0x33, 0x3B, 0x3A, 0x39, 0x31, 0x2A, 0x29, 0x32, + }, + { + 0x00, 0x08, 0x09, 0x01, 0x02, 0x0A, 0x12, 0x11, + 0x10, 0x18, 0x19, 0x1A, 0x1B, 0x13, 0x0B, 0x03, + 0x07, 0x06, 0x0E, 0x0F, 0x17, 0x16, 0x15, 0x0D, + 0x05, 0x04, 0x0C, 0x14, 0x1C, 0x1D, 0x1E, 0x1F, + 0x3F, 0x3E, 0x36, 0x37, 0x2F, 0x2E, 0x2D, 0x35, + 0x3D, 0x3C, 0x34, 0x2C, 0x24, 0x25, 0x26, 0x27, + 0x38, 0x30, 0x31, 0x39, 0x3A, 0x32, 0x2A, 0x29, + 0x28, 0x20, 0x21, 0x22, 0x23, 0x2B, 0x33, 0x3B, + }, + { + 0x00, 0x01, 0x08, 0x09, 0x10, 0x11, 0x18, 0x19, + 0x20, 0x21, 0x28, 0x29, 0x30, 0x31, 0x38, 0x39, + 0x3A, 0x3B, 0x32, 0x33, 0x2A, 0x2B, 0x22, 0x23, + 0x1A, 0x1B, 0x12, 0x13, 0x0A, 0x0B, 0x02, 0x03, + 0x04, 0x05, 0x0C, 0x0D, 0x14, 0x15, 0x1C, 0x1D, + 0x24, 0x25, 0x2C, 0x2D, 0x34, 0x35, 0x3C, 0x3D, + 0x3E, 0x3F, 0x36, 0x37, 0x2E, 0x2F, 0x26, 0x27, + 0x1E, 0x1F, 0x16, 0x17, 0x0E, 0x0F, 0x06, 0x07, + } +}; + +static const int32_t bink_intra_quant[16][64] = { +{ + 0x010000, 0x016315, 0x01E83D, 0x02A535, 0x014E7B, 0x016577, 0x02F1E6, 0x02724C, + 0x010000, 0x00EEDA, 0x024102, 0x017F9B, 0x00BE80, 0x00611E, 0x01083C, 0x00A552, + 0x021F88, 0x01DC53, 0x027FAD, 0x01F697, 0x014819, 0x00A743, 0x015A31, 0x009688, + 0x02346F, 0x030EE5, 0x01FBFA, 0x02C096, 0x01D000, 0x028396, 0x019247, 0x01F9AA, + 0x02346F, 0x01FBFA, 0x01DC53, 0x0231B8, 0x012F12, 0x01E06C, 0x00CB10, 0x0119A8, + 0x01C48C, 0x019748, 0x014E86, 0x0122AF, 0x02C628, 0x027F20, 0x0297B5, 0x023F32, + 0x025000, 0x01AB6B, 0x01D122, 0x0159B3, 0x012669, 0x008D43, 0x00EE1F, 0x0075ED, + 0x01490C, 0x010288, 0x00F735, 0x00EF51, 0x00E0F1, 0x0072AD, 0x00A4D8, 0x006517, +}, +{ + 0x015555, 0x01D971, 0x028AFC, 0x0386F1, 0x01BDF9, 0x01DC9F, 0x03ED33, 0x034311, + 0x015555, 0x013E78, 0x030158, 0x01FF7A, 0x00FE00, 0x00817D, 0x01604F, 0x00DC6D, + 0x02D4B5, 0x027B19, 0x0354E7, 0x029E1F, 0x01B577, 0x00DF04, 0x01CD96, 0x00C8B6, + 0x02F095, 0x0413DC, 0x02A54E, 0x03AB73, 0x026AAB, 0x035A1E, 0x02185E, 0x02A238, + 0x02F095, 0x02A54E, 0x027B19, 0x02ECF5, 0x019418, 0x028090, 0x010EC0, 0x01778A, + 0x025B66, 0x021F0B, 0x01BE09, 0x018394, 0x03B2E0, 0x03542A, 0x0374F1, 0x02FEEE, + 0x031555, 0x0239E4, 0x026C2D, 0x01CCEE, 0x01888C, 0x00BC59, 0x013D7E, 0x009D3C, + 0x01B6BB, 0x0158B5, 0x01499C, 0x013F17, 0x012BEC, 0x0098E6, 0x00DBCB, 0x0086C9, +}, +{ + 0x01AAAB, 0x024FCE, 0x032DBB, 0x0468AD, 0x022D78, 0x0253C7, 0x04E87F, 0x0413D5, + 0x01AAAB, 0x018E16, 0x03C1AE, 0x027F58, 0x013D80, 0x00A1DC, 0x01B863, 0x011388, + 0x0389E2, 0x0319DF, 0x042A21, 0x0345A7, 0x0222D4, 0x0116C5, 0x0240FC, 0x00FAE3, + 0x03ACBA, 0x0518D3, 0x034EA1, 0x04964F, 0x030555, 0x0430A5, 0x029E76, 0x034AC5, + 0x03ACBA, 0x034EA1, 0x0319DF, 0x03A833, 0x01F91E, 0x0320B4, 0x015270, 0x01D56D, + 0x02F23F, 0x02A6CE, 0x022D8B, 0x01E479, 0x049F98, 0x042935, 0x04522D, 0x03BEA9, + 0x03DAAB, 0x02C85D, 0x030738, 0x02402A, 0x01EAAF, 0x00EB6F, 0x018CDE, 0x00C48A, + 0x022469, 0x01AEE2, 0x019C02, 0x018EDD, 0x0176E7, 0x00BF20, 0x0112BE, 0x00A87B, +}, +{ + 0x020000, 0x02C62A, 0x03D07A, 0x054A69, 0x029CF6, 0x02CAEF, 0x05E3CC, 0x04E499, + 0x020000, 0x01DDB4, 0x048204, 0x02FF36, 0x017D01, 0x00C23C, 0x021077, 0x014AA3, + 0x043F0F, 0x03B8A6, 0x04FF5A, 0x03ED2E, 0x029032, 0x014E86, 0x02B461, 0x012D11, + 0x0468DF, 0x061DCA, 0x03F7F5, 0x05812C, 0x03A000, 0x05072C, 0x03248D, 0x03F353, + 0x0468DF, 0x03F7F5, 0x03B8A6, 0x046370, 0x025E24, 0x03C0D8, 0x019620, 0x02334F, + 0x038919, 0x032E91, 0x029D0D, 0x02455E, 0x058C50, 0x04FE3F, 0x052F69, 0x047E65, + 0x04A000, 0x0356D6, 0x03A243, 0x02B365, 0x024CD2, 0x011A85, 0x01DC3E, 0x00EBD9, + 0x029218, 0x020510, 0x01EE69, 0x01DEA2, 0x01C1E2, 0x00E559, 0x0149B0, 0x00CA2D, +}, +{ + 0x02AAAB, 0x03B2E3, 0x0515F8, 0x070DE2, 0x037BF2, 0x03B93E, 0x07DA65, 0x068621, + 0x02AAAB, 0x027CF0, 0x0602B1, 0x03FEF3, 0x01FC01, 0x0102FA, 0x02C09F, 0x01B8DA, + 0x05A96A, 0x04F632, 0x06A9CE, 0x053C3E, 0x036AED, 0x01BE09, 0x039B2D, 0x01916B, + 0x05E129, 0x0827B8, 0x054A9C, 0x0756E5, 0x04D555, 0x06B43B, 0x0430BC, 0x05446F, + 0x05E129, 0x054A9C, 0x04F632, 0x05D9EB, 0x032830, 0x050121, 0x021D80, 0x02EF14, + 0x04B6CC, 0x043E16, 0x037C11, 0x030728, 0x0765C0, 0x06A855, 0x06E9E2, 0x05FDDB, + 0x062AAB, 0x0473C8, 0x04D85A, 0x0399DC, 0x031118, 0x0178B2, 0x027AFD, 0x013A77, + 0x036D76, 0x02B16A, 0x029337, 0x027E2E, 0x0257D8, 0x0131CC, 0x01B796, 0x010D91, +}, +{ + 0x038000, 0x04DACA, 0x06ACD5, 0x094238, 0x0492AE, 0x04E322, 0x0A4EA5, 0x08900C, + 0x038000, 0x0343FB, 0x07E388, 0x053E9F, 0x029AC1, 0x0153E8, 0x039CD0, 0x02429E, + 0x076E5B, 0x068322, 0x08BEDE, 0x06DF11, 0x047C57, 0x02496B, 0x04BBAB, 0x020EDD, + 0x07B786, 0x0AB421, 0x06F1ED, 0x09A20D, 0x065800, 0x08CC8E, 0x057FF7, 0x06E9D2, + 0x07B786, 0x06F1ED, 0x068322, 0x07AE04, 0x0424BF, 0x06917B, 0x02C6B8, 0x03D9CB, + 0x062FEB, 0x05917D, 0x0492D7, 0x03F964, 0x09B58C, 0x08BCEF, 0x0912F8, 0x07DD30, + 0x081800, 0x05D7F7, 0x065BF6, 0x04B9F1, 0x040670, 0x01EE69, 0x03416C, 0x019CBC, + 0x047FAA, 0x0388DC, 0x036138, 0x03459C, 0x03134C, 0x01915C, 0x0240F5, 0x0161CF, +}, +{ + 0x040000, 0x058C54, 0x07A0F4, 0x0A94D3, 0x0539EC, 0x0595DD, 0x0BC798, 0x09C932, + 0x040000, 0x03BB68, 0x090409, 0x05FE6D, 0x02FA01, 0x018477, 0x0420EE, 0x029547, + 0x087E1F, 0x07714C, 0x09FEB5, 0x07DA5D, 0x052064, 0x029D0D, 0x0568C3, 0x025A21, + 0x08D1BE, 0x0C3B94, 0x07EFEA, 0x0B0258, 0x074000, 0x0A0E59, 0x06491A, 0x07E6A7, + 0x08D1BE, 0x07EFEA, 0x07714C, 0x08C6E0, 0x04BC48, 0x0781B1, 0x032C3F, 0x04669F, + 0x071232, 0x065D22, 0x053A1A, 0x048ABC, 0x0B18A0, 0x09FC7F, 0x0A5ED3, 0x08FCC9, + 0x094000, 0x06ADAC, 0x074487, 0x0566CA, 0x0499A5, 0x02350B, 0x03B87B, 0x01D7B3, + 0x052430, 0x040A20, 0x03DCD3, 0x03BD45, 0x0383C5, 0x01CAB3, 0x029361, 0x01945A, +}, +{ + 0x050000, 0x06EF69, 0x098931, 0x0D3A07, 0x068867, 0x06FB55, 0x0EB97E, 0x0C3B7E, + 0x050000, 0x04AA42, 0x0B450B, 0x077E08, 0x03B881, 0x01E595, 0x05292A, 0x033A99, + 0x0A9DA7, 0x094D9F, 0x0C7E62, 0x09D0F4, 0x06687D, 0x034450, 0x06C2F4, 0x02F0AA, + 0x0B062D, 0x0F4A78, 0x09EBE4, 0x0DC2EE, 0x091000, 0x0C91EF, 0x07DB61, 0x09E050, + 0x0B062D, 0x09EBE4, 0x094D9F, 0x0AF898, 0x05EB59, 0x09621D, 0x03F74F, 0x058046, + 0x08D6BE, 0x07F46A, 0x0688A0, 0x05AD6B, 0x0DDEC8, 0x0C7B9F, 0x0CF687, 0x0B3BFB, + 0x0B9000, 0x085917, 0x0915A8, 0x06C07D, 0x05C00E, 0x02C24D, 0x04A69A, 0x024D9F, + 0x066D3C, 0x050CA7, 0x04D407, 0x04AC96, 0x0464B6, 0x023D5F, 0x033839, 0x01F971, +}, +{ + 0x060000, 0x08527E, 0x0B716E, 0x0FDF3C, 0x07D6E1, 0x0860CC, 0x11AB63, 0x0EADCB, + 0x060000, 0x05991C, 0x0D860D, 0x08FDA3, 0x047702, 0x0246B3, 0x063165, 0x03DFEA, + 0x0CBD2E, 0x0B29F1, 0x0EFE0F, 0x0BC78B, 0x07B096, 0x03EB93, 0x081D24, 0x038732, + 0x0D3A9C, 0x12595D, 0x0BE7DF, 0x108384, 0x0AE000, 0x0F1585, 0x096DA8, 0x0BD9FA, + 0x0D3A9C, 0x0BE7DF, 0x0B29F1, 0x0D2A50, 0x071A6B, 0x0B4289, 0x04C25F, 0x0699EE, + 0x0A9B4A, 0x098BB2, 0x07D727, 0x06D01A, 0x10A4F0, 0x0EFABE, 0x0F8E3C, 0x0D7B2E, + 0x0DE000, 0x0A0482, 0x0AE6CA, 0x081A2F, 0x06E677, 0x034F90, 0x0594B9, 0x02C38C, + 0x07B649, 0x060F2F, 0x05CB3C, 0x059BE7, 0x0545A7, 0x02B00C, 0x03DD11, 0x025E87, +}, +{ + 0x080000, 0x0B18A8, 0x0F41E8, 0x1529A5, 0x0A73D7, 0x0B2BBB, 0x178F2F, 0x139264, + 0x080000, 0x0776CF, 0x120812, 0x0BFCD9, 0x05F402, 0x0308EF, 0x0841DC, 0x052A8E, + 0x10FC3E, 0x0EE297, 0x13FD69, 0x0FB4B9, 0x0A40C8, 0x053A1A, 0x0AD186, 0x04B442, + 0x11A37B, 0x187727, 0x0FDFD4, 0x1604B0, 0x0E8000, 0x141CB1, 0x0C9235, 0x0FCD4D, + 0x11A37B, 0x0FDFD4, 0x0EE297, 0x118DC0, 0x09788F, 0x0F0362, 0x06587F, 0x08CD3D, + 0x0E2463, 0x0CBA43, 0x0A7434, 0x091577, 0x163140, 0x13F8FE, 0x14BDA5, 0x11F992, + 0x128000, 0x0D5B58, 0x0E890D, 0x0ACD94, 0x093349, 0x046A15, 0x0770F7, 0x03AF65, + 0x0A4861, 0x08143F, 0x07B9A6, 0x077A89, 0x070789, 0x039565, 0x0526C2, 0x0328B4, +}, +{ + 0x0C0000, 0x10A4FD, 0x16E2DB, 0x1FBE78, 0x0FADC3, 0x10C198, 0x2356C7, 0x1D5B96, + 0x0C0000, 0x0B3237, 0x1B0C1A, 0x11FB46, 0x08EE03, 0x048D66, 0x0C62CA, 0x07BFD5, + 0x197A5D, 0x1653E3, 0x1DFC1E, 0x178F16, 0x0F612C, 0x07D727, 0x103A49, 0x070E64, + 0x1A7539, 0x24B2BB, 0x17CFBD, 0x210709, 0x15C000, 0x1E2B0A, 0x12DB4F, 0x17B3F4, + 0x1A7539, 0x17CFBD, 0x1653E3, 0x1A54A0, 0x0E34D7, 0x168513, 0x0984BE, 0x0D33DC, + 0x153695, 0x131765, 0x0FAE4E, 0x0DA033, 0x2149E1, 0x1DF57D, 0x1F1C78, 0x1AF65B, + 0x1BC000, 0x140904, 0x15CD94, 0x10345E, 0x0DCCEE, 0x069F20, 0x0B2972, 0x058718, + 0x0F6C91, 0x0C1E5E, 0x0B9678, 0x0B37CE, 0x0A8B4E, 0x056018, 0x07BA22, 0x04BD0E, +}, +{ + 0x110000, 0x179466, 0x206C0C, 0x2CF87F, 0x16362A, 0x17BCED, 0x321044, 0x299714, + 0x110000, 0x0FDC79, 0x265125, 0x19794E, 0x0CA685, 0x0672FB, 0x118BF4, 0x0AFA6D, + 0x241804, 0x1FA181, 0x2A7A80, 0x21600A, 0x15C9A9, 0x0B1B77, 0x16FD3C, 0x09FF0D, + 0x257B66, 0x33FD33, 0x21BBA2, 0x2EC9F7, 0x1ED000, 0x2ABCF9, 0x1AB6B0, 0x219444, + 0x257B66, 0x21BBA2, 0x1FA181, 0x254D38, 0x142030, 0x1FE730, 0x0D7C0E, 0x12B423, + 0x1E0D52, 0x1B0BCF, 0x1636EE, 0x134D9E, 0x2F28A9, 0x2A711B, 0x2C12FF, 0x263256, + 0x275000, 0x1C621B, 0x1EE33C, 0x16F4DB, 0x138CFB, 0x09616E, 0x0FD00C, 0x07D4B7, + 0x15D9CE, 0x112B06, 0x106A80, 0x0FE464, 0x0EF004, 0x079D77, 0x0AF25B, 0x06B67F, +}, +{ + 0x160000, 0x1E83CF, 0x29F53D, 0x3A3286, 0x1CBE90, 0x1EB842, 0x40C9C2, 0x35D293, + 0x160000, 0x1486BA, 0x319630, 0x20F756, 0x105F06, 0x085891, 0x16B51E, 0x0E3506, + 0x2EB5AA, 0x28EF20, 0x36F8E1, 0x2B30FE, 0x1C3225, 0x0E5FC7, 0x1DC030, 0x0CEFB7, + 0x308193, 0x4347AC, 0x2BA786, 0x3C8CE5, 0x27E000, 0x374EE7, 0x229212, 0x2B7494, + 0x308193, 0x2BA786, 0x28EF20, 0x3045D0, 0x1A0B89, 0x29494D, 0x11735D, 0x183469, + 0x26E410, 0x230039, 0x1CBF8F, 0x18FB09, 0x3D0771, 0x36ECBA, 0x390986, 0x316E52, + 0x32E000, 0x24BB33, 0x27F8E4, 0x1DB557, 0x194D09, 0x0C23BB, 0x1476A6, 0x0A2256, + 0x1C470A, 0x1637AD, 0x153E87, 0x1490FA, 0x1354B9, 0x09DAD6, 0x0E2A94, 0x08AFF0, +}, +{ + 0x1C0000, 0x26D64D, 0x3566AA, 0x4A11C2, 0x249572, 0x27190E, 0x527525, 0x44805E, + 0x1C0000, 0x1A1FD6, 0x3F1C3E, 0x29F4F9, 0x14D607, 0x0A9F44, 0x1CE683, 0x1214F0, + 0x3B72D9, 0x341911, 0x45F6F0, 0x36F889, 0x23E2BB, 0x124B5B, 0x25DD54, 0x1076E9, + 0x3DBC30, 0x55A109, 0x378F64, 0x4D1069, 0x32C000, 0x46646C, 0x2BFFB9, 0x374E8E, + 0x3DBC30, 0x378F64, 0x341911, 0x3D7020, 0x2125F5, 0x348BD6, 0x1635BC, 0x1ECE57, + 0x317F5B, 0x2C8BEB, 0x2496B6, 0x1FCB22, 0x4DAC61, 0x45E778, 0x4897C2, 0x3EE97F, + 0x40C000, 0x2EBFB5, 0x32DFAE, 0x25CF86, 0x203380, 0x0F734B, 0x1A0B5F, 0x0CE5E2, + 0x23FD53, 0x1C46DC, 0x1B09C4, 0x1A2CE1, 0x189A60, 0x0C8AE2, 0x1207A5, 0x0B0E77, +}, +{ + 0x220000, 0x2F28CC, 0x40D818, 0x59F0FE, 0x2C6C53, 0x2F79DA, 0x642089, 0x532E29, + 0x220000, 0x1FB8F1, 0x4CA24B, 0x32F29C, 0x194D09, 0x0CE5F7, 0x2317E8, 0x15F4DB, + 0x483007, 0x3F4303, 0x54F4FF, 0x42C014, 0x2B9351, 0x1636EE, 0x2DFA79, 0x13FE1A, + 0x4AF6CC, 0x67FA67, 0x437743, 0x5D93EE, 0x3DA000, 0x5579F1, 0x356D61, 0x432888, + 0x4AF6CC, 0x437743, 0x3F4303, 0x4A9A70, 0x284060, 0x3FCE60, 0x1AF81B, 0x256845, + 0x3C1AA5, 0x36179D, 0x2C6DDD, 0x269B3C, 0x5E5152, 0x54E237, 0x5825FE, 0x4C64AD, + 0x4EA000, 0x38C437, 0x3DC678, 0x2DE9B5, 0x2719F7, 0x12C2DB, 0x1FA018, 0x0FA96E, + 0x2BB39B, 0x22560C, 0x20D500, 0x1FC8C8, 0x1DE007, 0x0F3AEE, 0x15E4B7, 0x0D6CFE, +}, +{ + 0x2C0000, 0x3D079E, 0x53EA79, 0x74650C, 0x397D20, 0x3D7083, 0x819383, 0x6BA525, + 0x2C0000, 0x290D75, 0x632C61, 0x41EEAC, 0x20BE0C, 0x10B121, 0x2D6A3B, 0x1C6A0C, + 0x5D6B54, 0x51DE40, 0x6DF1C2, 0x5661FB, 0x38644B, 0x1CBF8F, 0x3B8060, 0x19DF6D, + 0x610326, 0x868F57, 0x574F0B, 0x7919CA, 0x4FC000, 0x6E9DCE, 0x452423, 0x56E928, + 0x610326, 0x574F0B, 0x51DE40, 0x608BA0, 0x341713, 0x52929A, 0x22E6BA, 0x3068D2, + 0x4DC821, 0x460071, 0x397F1E, 0x31F611, 0x7A0EE2, 0x6DD974, 0x72130C, 0x62DCA3, + 0x65C000, 0x497665, 0x4FF1C9, 0x3B6AAE, 0x329A12, 0x184776, 0x28ED4D, 0x1444AC, + 0x388E14, 0x2C6F5A, 0x2A7D0F, 0x2921F4, 0x26A973, 0x13B5AD, 0x1C5528, 0x115FDF, +}, +}; + +static const int32_t bink_inter_quant[16][64] = { +{ + 0x010000, 0x017946, 0x01A5A9, 0x0248DC, 0x016363, 0x0152A7, 0x0243EC, 0x0209EA, + 0x012000, 0x00E248, 0x01BBDA, 0x015CBC, 0x00A486, 0x0053E0, 0x00F036, 0x008095, + 0x01B701, 0x016959, 0x01B0B9, 0x0153FD, 0x00F8E7, 0x007EE4, 0x00EA30, 0x007763, + 0x01B701, 0x0260EB, 0x019DE9, 0x023E1B, 0x017000, 0x01FE6E, 0x012DB5, 0x01A27B, + 0x01E0D1, 0x01B0B9, 0x018A33, 0x01718D, 0x00D87A, 0x014449, 0x007B9A, 0x00AB71, + 0x013178, 0x0112EA, 0x00AD08, 0x009BB9, 0x023D97, 0x020437, 0x021CCC, 0x01E6B4, + 0x018000, 0x012DB5, 0x0146D9, 0x0100CE, 0x00CFD2, 0x006E5C, 0x00B0E4, 0x005A2D, + 0x00E9CC, 0x00B7B1, 0x00846F, 0x006B85, 0x008337, 0x0042E5, 0x004A10, 0x002831, +}, +{ + 0x015555, 0x01F708, 0x023237, 0x030BD0, 0x01D9D9, 0x01C389, 0x03053B, 0x02B7E3, + 0x018000, 0x012DB5, 0x024FCE, 0x01D0FA, 0x00DB5D, 0x006FD5, 0x014048, 0x00AB71, + 0x024957, 0x01E1CC, 0x0240F7, 0x01C551, 0x014BDE, 0x00A92F, 0x013840, 0x009F2F, + 0x024957, 0x032BE4, 0x0227E1, 0x02FD7A, 0x01EAAB, 0x02A893, 0x019247, 0x022DF9, + 0x028116, 0x0240F7, 0x020D99, 0x01ECBC, 0x0120A3, 0x01B061, 0x00A4CE, 0x00E497, + 0x01974B, 0x016E8E, 0x00E6B5, 0x00CFA2, 0x02FCC9, 0x02B04A, 0x02D110, 0x0288F1, + 0x020000, 0x019247, 0x01B3CC, 0x015668, 0x011518, 0x009325, 0x00EBDA, 0x00783D, + 0x0137BB, 0x00F4ED, 0x00B093, 0x008F5C, 0x00AEF4, 0x005931, 0x0062BF, 0x003597, +}, +{ + 0x01AAAB, 0x0274CB, 0x02BEC4, 0x03CEC4, 0x02504F, 0x02346C, 0x03C689, 0x0365DC, + 0x01E000, 0x017922, 0x02E3C1, 0x024539, 0x011235, 0x008BCA, 0x01905A, 0x00D64D, + 0x02DBAD, 0x025A40, 0x02D134, 0x0236A5, 0x019ED6, 0x00D37B, 0x018650, 0x00C6FB, + 0x02DBAD, 0x03F6DD, 0x02B1D9, 0x03BCD8, 0x026555, 0x0352B8, 0x01F6D8, 0x02B977, + 0x03215C, 0x02D134, 0x029100, 0x0267EB, 0x0168CC, 0x021C7A, 0x00CE01, 0x011DBD, + 0x01FD1E, 0x01CA31, 0x012062, 0x01038A, 0x03BBFB, 0x035C5C, 0x038554, 0x032B2D, + 0x028000, 0x01F6D8, 0x0220C0, 0x01AC02, 0x015A5E, 0x00B7EF, 0x0126D1, 0x00964C, + 0x0185A9, 0x013228, 0x00DCB8, 0x00B333, 0x00DAB2, 0x006F7D, 0x007B6F, 0x0042FC, +}, +{ + 0x020000, 0x02F28D, 0x034B52, 0x0491B8, 0x02C6C5, 0x02A54E, 0x0487D8, 0x0413D5, + 0x024000, 0x01C48F, 0x0377B5, 0x02B977, 0x01490C, 0x00A7BF, 0x01E06C, 0x01012A, + 0x036E03, 0x02D2B3, 0x036172, 0x02A7FA, 0x01F1CE, 0x00FDC7, 0x01D460, 0x00EEC7, + 0x036E03, 0x04C1D6, 0x033BD1, 0x047C37, 0x02E000, 0x03FCDD, 0x025B6A, 0x0344F5, + 0x03C1A1, 0x036172, 0x031466, 0x02E31B, 0x01B0F5, 0x028892, 0x00F735, 0x0156E2, + 0x0262F1, 0x0225D5, 0x015A10, 0x013772, 0x047B2D, 0x04086E, 0x043998, 0x03CD69, + 0x030000, 0x025B6A, 0x028DB3, 0x02019B, 0x019FA3, 0x00DCB8, 0x0161C7, 0x00B45B, + 0x01D398, 0x016F63, 0x0108DD, 0x00D70A, 0x01066F, 0x0085C9, 0x00941F, 0x005062, +}, +{ + 0x02AAAB, 0x03EE11, 0x04646D, 0x0617A0, 0x03B3B2, 0x038713, 0x060A75, 0x056FC6, + 0x030000, 0x025B6A, 0x049F9B, 0x03A1F4, 0x01B6BB, 0x00DFAA, 0x028090, 0x0156E2, + 0x0492AE, 0x03C399, 0x0481ED, 0x038AA2, 0x0297BD, 0x01525F, 0x027080, 0x013E5E, + 0x0492AE, 0x0657C8, 0x044FC1, 0x05FAF4, 0x03D555, 0x055126, 0x03248D, 0x045BF2, + 0x05022D, 0x0481ED, 0x041B33, 0x03D979, 0x024147, 0x0360C3, 0x01499C, 0x01C92E, + 0x032E96, 0x02DD1C, 0x01CD6A, 0x019F43, 0x05F991, 0x056093, 0x05A220, 0x0511E1, + 0x040000, 0x03248D, 0x036799, 0x02ACCF, 0x022A2F, 0x01264B, 0x01D7B5, 0x00F079, + 0x026F75, 0x01E9D9, 0x016127, 0x011EB8, 0x015DE9, 0x00B262, 0x00C57F, 0x006B2D, +}, +{ + 0x038000, 0x052876, 0x05C3CF, 0x07FF02, 0x04DBD9, 0x04A148, 0x07EDBA, 0x0722B4, + 0x03F000, 0x0317FB, 0x06117C, 0x04C491, 0x023FD5, 0x01258F, 0x0348BD, 0x01C209, + 0x060085, 0x04F0B9, 0x05EA87, 0x04A5F5, 0x036728, 0x01BC1C, 0x0333A8, 0x01A1DB, + 0x060085, 0x085336, 0x05A8AE, 0x07D960, 0x050800, 0x06FA82, 0x041FF9, 0x05B8AE, + 0x0692DA, 0x05EA87, 0x0563B2, 0x050D6E, 0x02F5AD, 0x046F00, 0x01B09C, 0x02580C, + 0x042D25, 0x03C235, 0x025D9B, 0x022108, 0x07D78F, 0x070EC1, 0x0764CA, 0x06A777, + 0x054000, 0x041FF9, 0x0477F9, 0x0382D0, 0x02D75E, 0x018242, 0x026B1D, 0x013B9F, + 0x03324A, 0x0282ED, 0x01CF83, 0x017851, 0x01CB42, 0x00EA21, 0x010336, 0x008CAC, +}, +{ + 0x040000, 0x05E519, 0x0696A4, 0x092370, 0x058D8A, 0x054A9C, 0x090FB0, 0x0827AA, + 0x048000, 0x03891F, 0x06EF69, 0x0572EE, 0x029218, 0x014F7E, 0x03C0D8, 0x020254, + 0x06DC05, 0x05A565, 0x06C2E4, 0x054FF3, 0x03E39B, 0x01FB8E, 0x03A8C0, 0x01DD8D, + 0x06DC05, 0x0983AC, 0x0677A2, 0x08F86E, 0x05C000, 0x07F9B9, 0x04B6D4, 0x0689EB, + 0x078343, 0x06C2E4, 0x0628CC, 0x05C635, 0x0361EA, 0x051124, 0x01EE69, 0x02ADC5, + 0x04C5E1, 0x044BAA, 0x02B41F, 0x026EE5, 0x08F65A, 0x0810DD, 0x087330, 0x079AD1, + 0x060000, 0x04B6D4, 0x051B65, 0x040337, 0x033F47, 0x01B970, 0x02C38F, 0x0168B6, + 0x03A730, 0x02DEC6, 0x0211BA, 0x01AE14, 0x020CDD, 0x010B93, 0x01283E, 0x00A0C4, +}, +{ + 0x050000, 0x075E60, 0x083C4D, 0x0B6C4C, 0x06F0ED, 0x069D43, 0x0B539C, 0x0A3194, + 0x05A000, 0x046B67, 0x08AB44, 0x06CFAA, 0x03369E, 0x01A35E, 0x04B10F, 0x0282E8, + 0x089307, 0x070EBF, 0x08739C, 0x06A3F0, 0x04DC82, 0x027A72, 0x0492F0, 0x0254F0, + 0x089307, 0x0BE497, 0x08158B, 0x0B3689, 0x073000, 0x09F827, 0x05E489, 0x082C66, + 0x096413, 0x08739C, 0x07B2FF, 0x0737C2, 0x043A64, 0x06556D, 0x026A04, 0x035936, + 0x05F75A, 0x055E94, 0x036127, 0x030A9E, 0x0B33F1, 0x0A1514, 0x0A8FFC, 0x098186, + 0x078000, 0x05E489, 0x06623F, 0x050405, 0x040F19, 0x0227CC, 0x037473, 0x01C2E3, + 0x0490FC, 0x039677, 0x029629, 0x021999, 0x029015, 0x014E78, 0x01724E, 0x00C8F5, +}, +{ + 0x060000, 0x08D7A6, 0x09E1F6, 0x0DB528, 0x085450, 0x07EFEA, 0x0D9788, 0x0C3B7E, + 0x06C000, 0x054DAE, 0x0A671E, 0x082C66, 0x03DB24, 0x01F73E, 0x05A145, 0x03037D, + 0x0A4A08, 0x087818, 0x0A2455, 0x07F7ED, 0x05D569, 0x02F955, 0x057D20, 0x02CC54, + 0x0A4A08, 0x0E4582, 0x09B373, 0x0D74A5, 0x08A000, 0x0BF696, 0x07123E, 0x09CEE0, + 0x0B44E4, 0x0A2455, 0x093D32, 0x08A950, 0x0512DF, 0x0799B6, 0x02E59E, 0x0404A7, + 0x0728D2, 0x06717F, 0x040E2F, 0x03A657, 0x0D7187, 0x0C194B, 0x0CACC8, 0x0B683A, + 0x090000, 0x07123E, 0x07A918, 0x0604D2, 0x04DEEA, 0x029629, 0x042556, 0x021D11, + 0x057AC8, 0x044E28, 0x031A97, 0x02851E, 0x03134C, 0x01915C, 0x01BC5D, 0x00F126, +}, +{ + 0x080000, 0x0BCA33, 0x0D2D48, 0x1246E0, 0x0B1B15, 0x0A9538, 0x121F5F, 0x104F53, + 0x090000, 0x07123E, 0x0DDED2, 0x0AE5DD, 0x052430, 0x029EFD, 0x0781B1, 0x0404A7, + 0x0DB80B, 0x0B4ACB, 0x0D85C7, 0x0A9FE7, 0x07C736, 0x03F71D, 0x075180, 0x03BB1A, + 0x0DB80B, 0x130757, 0x0CEF44, 0x11F0DC, 0x0B8000, 0x0FF372, 0x096DA8, 0x0D13D6, + 0x0F0686, 0x0D85C7, 0x0C5198, 0x0B8C6A, 0x06C3D4, 0x0A2248, 0x03DCD3, 0x055B8A, + 0x098BC3, 0x089754, 0x05683E, 0x04DDC9, 0x11ECB4, 0x1021B9, 0x10E661, 0x0F35A3, + 0x0C0000, 0x096DA8, 0x0A36CB, 0x08066E, 0x067E8E, 0x0372E1, 0x05871E, 0x02D16B, + 0x074E60, 0x05BD8B, 0x042374, 0x035C28, 0x0419BB, 0x021726, 0x02507C, 0x014188, +}, +{ + 0x0C0000, 0x11AF4C, 0x13C3EC, 0x1B6A50, 0x10A89F, 0x0FDFD4, 0x1B2F0F, 0x1876FD, + 0x0D8000, 0x0A9B5D, 0x14CE3C, 0x1058CB, 0x07B649, 0x03EE7B, 0x0B4289, 0x0606FB, + 0x149410, 0x10F030, 0x1448AB, 0x0FEFDA, 0x0BAAD2, 0x05F2AB, 0x0AFA40, 0x0598A7, + 0x149410, 0x1C8B03, 0x1366E6, 0x1AE949, 0x114000, 0x17ED2B, 0x0E247C, 0x139DC1, + 0x1689C8, 0x1448AB, 0x127A63, 0x11529F, 0x0A25BE, 0x0F336D, 0x05CB3C, 0x08094E, + 0x0E51A4, 0x0CE2FE, 0x081C5D, 0x074CAE, 0x1AE30E, 0x183296, 0x195991, 0x16D074, + 0x120000, 0x0E247C, 0x0F5230, 0x0C09A5, 0x09BDD5, 0x052C51, 0x084AAC, 0x043A21, + 0x0AF590, 0x089C51, 0x06352E, 0x050A3B, 0x062698, 0x0322B9, 0x0378BA, 0x01E24D, +}, +{ + 0x110000, 0x190DAC, 0x1C0039, 0x26D69C, 0x17998C, 0x167D16, 0x2682AB, 0x22A891, + 0x132000, 0x0F06C3, 0x1D797F, 0x172876, 0x0AECE7, 0x0591D9, 0x0FF398, 0x0889E3, + 0x1D2717, 0x17FEEF, 0x1CBC47, 0x1693CA, 0x108754, 0x086D1D, 0x0F8D30, 0x07ED98, + 0x1D2717, 0x286F9A, 0x1B7C71, 0x261FD3, 0x187000, 0x21E552, 0x140904, 0x1BCA27, + 0x1FEDDC, 0x1CBC47, 0x1A2D62, 0x188A62, 0x0E6022, 0x1588DA, 0x083540, 0x0B6284, + 0x1448FE, 0x124192, 0x0B7D84, 0x0A574B, 0x2616FF, 0x2247AA, 0x23E98D, 0x2051FA, + 0x198000, 0x140904, 0x15B46F, 0x110DAA, 0x0DCCEE, 0x07541E, 0x0BBF1F, 0x05FD04, + 0x0F868B, 0x0C32C8, 0x08CB57, 0x0723D4, 0x08B6AD, 0x047130, 0x04EB08, 0x02AB42, +}, +{ + 0x160000, 0x206C0C, 0x243C86, 0x3242E8, 0x1E8A79, 0x1D1A59, 0x31D646, 0x2CDA25, + 0x18C000, 0x13722A, 0x2624C3, 0x1DF820, 0x0E2385, 0x073537, 0x14A4A7, 0x0B0CCC, + 0x25BA1D, 0x1F0DAE, 0x252FE4, 0x1D37BB, 0x1563D6, 0x0AE78E, 0x142021, 0x0A4288, + 0x25BA1D, 0x345430, 0x2391FB, 0x31565C, 0x1FA000, 0x2BDD7A, 0x19ED8D, 0x23F68C, + 0x2951EF, 0x252FE4, 0x21E061, 0x1FC224, 0x129A87, 0x1BDE47, 0x0A9F44, 0x0EBBBA, + 0x1A4058, 0x17A026, 0x0EDEAB, 0x0D61E9, 0x314AEF, 0x2C5CBE, 0x2E798A, 0x29D380, + 0x210000, 0x19ED8D, 0x1C16AE, 0x1611AE, 0x11DC06, 0x097BEA, 0x0F3391, 0x07BFE7, + 0x141787, 0x0FC93E, 0x0B617F, 0x093D6D, 0x0B46C1, 0x05BFA8, 0x065D55, 0x037437, +}, +{ + 0x1C0000, 0x2943B2, 0x2E1E7C, 0x3FF810, 0x26DEC9, 0x250A43, 0x3F6DCE, 0x3915A3, + 0x1F8000, 0x18BFD8, 0x308BE1, 0x262485, 0x11FEA9, 0x092C75, 0x1A45EB, 0x0E1049, + 0x300425, 0x2785C6, 0x2F5439, 0x252FA8, 0x1B393F, 0x0DE0E4, 0x199D41, 0x0D0EDC, + 0x300425, 0x4299B2, 0x2D456E, 0x3ECB00, 0x284000, 0x37D40F, 0x20FFCB, 0x2DC56D, + 0x3496D3, 0x2F5439, 0x2B1D93, 0x286B74, 0x17AD66, 0x2377FE, 0x0D84E2, 0x12C062, + 0x21692A, 0x1E11A5, 0x12ECDA, 0x110840, 0x3EBC76, 0x387608, 0x3B2652, 0x353BBA, + 0x2A0000, 0x20FFCB, 0x23BFC6, 0x1C1681, 0x16BAF1, 0x0C1213, 0x1358E8, 0x09DCF8, + 0x19924F, 0x141767, 0x0E7C16, 0x0BC28A, 0x0E5A0D, 0x075104, 0x0819B2, 0x04655D, +}, +{ + 0x220000, 0x321B58, 0x380072, 0x4DAD38, 0x2F3318, 0x2CFA2D, 0x4D0556, 0x455122, + 0x264000, 0x1E0D86, 0x3AF2FE, 0x2E50EB, 0x15D9CE, 0x0B23B2, 0x1FE730, 0x1113C7, + 0x3A4E2D, 0x2FFDDF, 0x39788E, 0x2D2795, 0x210EA8, 0x10DA39, 0x1F1A61, 0x0FDB2F, + 0x3A4E2D, 0x50DF33, 0x36F8E1, 0x4C3FA5, 0x30E000, 0x43CAA5, 0x281209, 0x37944D, + 0x3FDBB7, 0x39788E, 0x345AC4, 0x3114C3, 0x1CC044, 0x2B11B4, 0x106A80, 0x16C509, + 0x2891FC, 0x248324, 0x16FB08, 0x14AE97, 0x4C2DFD, 0x448F54, 0x47D31B, 0x40A3F5, + 0x330000, 0x281209, 0x2B68DF, 0x221B53, 0x1B99DB, 0x0EA83B, 0x177E3E, 0x0BFA09, + 0x1F0D17, 0x18658F, 0x1196AE, 0x0E47A8, 0x116D5A, 0x08E260, 0x09D60F, 0x055684, +}, +{ + 0x2C0000, 0x40D818, 0x48790C, 0x6485D0, 0x3D14F2, 0x3A34B2, 0x63AC8D, 0x59B44A, + 0x318000, 0x26E454, 0x4C4986, 0x3BF03F, 0x1C470A, 0x0E6A6E, 0x29494D, 0x161998, + 0x4B743A, 0x3E1B5C, 0x4A5FC7, 0x3A6F75, 0x2AC7AC, 0x15CF1D, 0x284041, 0x148510, + 0x4B743A, 0x68A861, 0x4723F6, 0x62ACB8, 0x3F4000, 0x57BAF3, 0x33DB1A, 0x47ED19, + 0x52A3DE, 0x4A5FC7, 0x43C0C2, 0x3F8448, 0x25350D, 0x37BC8E, 0x153E87, 0x1D7775, + 0x3480B0, 0x2F404C, 0x1DBD56, 0x1AC3D2, 0x6295DE, 0x58B97B, 0x5CF313, 0x53A701, + 0x420000, 0x33DB1A, 0x382D5C, 0x2C235D, 0x23B80D, 0x12F7D4, 0x1E6723, 0x0F7FCF, + 0x282F0E, 0x1F927D, 0x16C2FF, 0x127AD9, 0x168D83, 0x0B7F50, 0x0CBAAA, 0x06E86E, +}, +}; + +static const uint8_t binkb_runbits[64] = { + 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, + 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, + 4, 4, 4, 4, 4, 4, 4, 4, + 3, 3, 3, 3, 2, 2, 1, 0, +}; + +static const uint8_t binkb_intra_seed[64] = { + 16, 16, 16, 19, 16, 19, 22, 22, + 22, 22, 26, 24, 26, 22, 22, 27, + 27, 27, 26, 26, 26, 29, 29, 29, + 27, 27, 27, 26, 34, 34, 34, 29, + 29, 29, 27, 27, 37, 34, 34, 32, + 32, 29, 29, 38, 37, 35, 35, 34, + 35, 40, 40, 40, 38, 38, 48, 48, + 46, 46, 58, 56, 56, 69, 69, 83, +}; + +static const uint8_t binkb_inter_seed[64] = { + 16, 17, 17, 18, 18, 18, 19, 19, + 19, 19, 20, 20, 20, 20, 20, 21, + 21, 21, 21, 21, 21, 22, 22, 22, + 22, 22, 22, 22, 23, 23, 23, 23, + 23, 23, 23, 23, 24, 24, 24, 25, + 24, 24, 24, 25, 26, 26, 26, 26, + 25, 27, 27, 27, 27, 27, 28, 28, + 28, 28, 30, 30, 30, 31, 31, 33, +}; + +static const uint8_t binkb_num[16] = { + 1, 4, 5, 2, 7, 8, 3, 7, 4, 9, 5, 6, 7, 8, 9, 10 +}; + +static const uint8_t binkb_den[16] = { + 1, 3, 3, 1, 3, 3, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1 +}; + +#endif /* AVCODEC_BINKDATA_H */ diff --git a/Code/BF2/External/ffmpeg-bink/libavcodec/binkdsp.c b/Code/BF2/External/ffmpeg-bink/libavcodec/binkdsp.c new file mode 100644 index 000000000..166dca1ba --- /dev/null +++ b/Code/BF2/External/ffmpeg-bink/libavcodec/binkdsp.c @@ -0,0 +1,158 @@ +/* + * Bink DSP routines + * Copyright (c) 2009 Konstantin Shishkov + * + * This file is part of FFmpeg. + * + * FFmpeg is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * FFmpeg is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with FFmpeg; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/** + * @file + * Bink DSP routines + */ + +#include "libavutil/attributes.h" +#include "binkdsp.h" + +#define A1 2896 /* (1/sqrt(2))<<12 */ +#define A2 2217 +#define A3 3784 +#define A4 -5352 + +#define MUL(X,Y) ((int)((unsigned)(X) * (Y)) >> 11) + +#define IDCT_TRANSFORM(dest,s0,s1,s2,s3,s4,s5,s6,s7,d0,d1,d2,d3,d4,d5,d6,d7,munge,src) {\ + const int a0 = (src)[s0] + (src)[s4]; \ + const int a1 = (src)[s0] - (src)[s4]; \ + const int a2 = (src)[s2] + (src)[s6]; \ + const int a3 = MUL(A1, (src)[s2] - (src)[s6]); \ + const int a4 = (src)[s5] + (src)[s3]; \ + const int a5 = (src)[s5] - (src)[s3]; \ + const int a6 = (src)[s1] + (src)[s7]; \ + const int a7 = (src)[s1] - (src)[s7]; \ + const int b0 = a4 + a6; \ + const int b1 = MUL(A3, a5 + a7); \ + const int b2 = MUL(A4, a5) - b0 + b1; \ + const int b3 = MUL(A1, a6 - a4) - b2; \ + const int b4 = MUL(A2, a7) + b3 - b1; \ + (dest)[d0] = munge(a0+a2 +b0); \ + (dest)[d1] = munge(a1+a3-a2+b2); \ + (dest)[d2] = munge(a1-a3+a2+b3); \ + (dest)[d3] = munge(a0-a2 -b4); \ + (dest)[d4] = munge(a0-a2 +b4); \ + (dest)[d5] = munge(a1-a3+a2-b3); \ + (dest)[d6] = munge(a1+a3-a2-b2); \ + (dest)[d7] = munge(a0+a2 -b0); \ +} +/* end IDCT_TRANSFORM macro */ + +#define MUNGE_NONE(x) (x) +#define IDCT_COL(dest,src) IDCT_TRANSFORM(dest,0,8,16,24,32,40,48,56,0,8,16,24,32,40,48,56,MUNGE_NONE,src) + +#define MUNGE_ROW(x) (((x) + 0x7F)>>8) +#define IDCT_ROW(dest,src) IDCT_TRANSFORM(dest,0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7,MUNGE_ROW,src) + +static inline void bink_idct_col(int *dest, const int32_t *src) +{ + if ((src[8]|src[16]|src[24]|src[32]|src[40]|src[48]|src[56])==0) { + dest[0] = + dest[8] = + dest[16] = + dest[24] = + dest[32] = + dest[40] = + dest[48] = + dest[56] = src[0]; + } else { + IDCT_COL(dest, src); + } +} + +static void bink_idct_c(int32_t *block) +{ + int i; + int temp[64]; + + for (i = 0; i < 8; i++) + bink_idct_col(&temp[i], &block[i]); + for (i = 0; i < 8; i++) { + IDCT_ROW( (&block[8*i]), (&temp[8*i]) ); + } +} + +static void bink_idct_add_c(uint8_t *dest, int linesize, int32_t *block) +{ + int i, j; + + bink_idct_c(block); + for (i = 0; i < 8; i++, dest += linesize, block += 8) + for (j = 0; j < 8; j++) + dest[j] += block[j]; +} + +static void bink_idct_put_c(uint8_t *dest, int linesize, int32_t *block) +{ + int i; + int temp[64]; + for (i = 0; i < 8; i++) + bink_idct_col(&temp[i], &block[i]); + for (i = 0; i < 8; i++) { + IDCT_ROW( (&dest[i*linesize]), (&temp[8*i]) ); + } +} + +static void scale_block_c(const uint8_t src[64]/*align 8*/, uint8_t *dst/*align 8*/, int linesize) +{ + int i, j; + uint16_t *dst1 = (uint16_t *) dst; + uint16_t *dst2 = (uint16_t *)(dst + linesize); + + for (j = 0; j < 8; j++) { + for (i = 0; i < 8; i++) { + dst1[i] = dst2[i] = src[i] * 0x0101; + } + src += 8; + dst1 += linesize; + dst2 += linesize; + } +} + +static void add_pixels8_c(uint8_t *restrict pixels, int16_t *block, + int line_size) +{ + int i; + + for (i = 0; i < 8; i++) { + pixels[0] += block[0]; + pixels[1] += block[1]; + pixels[2] += block[2]; + pixels[3] += block[3]; + pixels[4] += block[4]; + pixels[5] += block[5]; + pixels[6] += block[6]; + pixels[7] += block[7]; + pixels += line_size; + block += 8; + } +} + +av_cold void ff_binkdsp_init(BinkDSPContext *c) +{ + c->idct_add = bink_idct_add_c; + c->idct_put = bink_idct_put_c; + c->scale_block = scale_block_c; + c->add_pixels8 = add_pixels8_c; +} diff --git a/Code/BF2/External/ffmpeg-bink/libavcodec/binkdsp.h b/Code/BF2/External/ffmpeg-bink/libavcodec/binkdsp.h new file mode 100644 index 000000000..8f084ec25 --- /dev/null +++ b/Code/BF2/External/ffmpeg-bink/libavcodec/binkdsp.h @@ -0,0 +1,41 @@ +/* + * Bink DSP routines + * Copyright (c) 2009 Konstantin Shishkov + * + * This file is part of FFmpeg. + * + * FFmpeg is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * FFmpeg is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with FFmpeg; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/** + * @file + * Bink DSP routines + */ + +#ifndef AVCODEC_BINKDSP_H +#define AVCODEC_BINKDSP_H + +#include + +typedef struct BinkDSPContext { + void (*idct_put)(uint8_t *dest/*align 8*/, int line_size, int32_t *block/*align 16*/); + void (*idct_add)(uint8_t *dest/*align 8*/, int line_size, int32_t *block/*align 16*/); + void (*scale_block)(const uint8_t src[64]/*align 8*/, uint8_t *dst/*align 8*/, int linesize); + void (*add_pixels8)(uint8_t *restrict pixels, int16_t *block, int line_size); +} BinkDSPContext; + +void ff_binkdsp_init(BinkDSPContext *c); + +#endif /* AVCODEC_BINKDSP_H */ diff --git a/Code/BF2/External/ffmpeg-bink/libavcodec/wma_freqs.c b/Code/BF2/External/ffmpeg-bink/libavcodec/wma_freqs.c new file mode 100644 index 000000000..03a283fca --- /dev/null +++ b/Code/BF2/External/ffmpeg-bink/libavcodec/wma_freqs.c @@ -0,0 +1,28 @@ +/* + * This file is part of FFmpeg. + * + * FFmpeg is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * FFmpeg is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with FFmpeg; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include + +#include "wma_freqs.h" + +const uint16_t ff_wma_critical_freqs[25] = { + 100, 200, 300, 400, 510, 630, 770, 920, + 1080, 1270, 1480, 1720, 2000, 2320, 2700, 3150, + 3700, 4400, 5300, 6400, 7700, 9500, 12000, 15500, + 24500, +}; diff --git a/Code/BF2/External/ffmpeg-bink/libavcodec/wma_freqs.h b/Code/BF2/External/ffmpeg-bink/libavcodec/wma_freqs.h new file mode 100644 index 000000000..6fd93e4ef --- /dev/null +++ b/Code/BF2/External/ffmpeg-bink/libavcodec/wma_freqs.h @@ -0,0 +1,26 @@ +/* + * This file is part of FFmpeg. + * + * FFmpeg is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * FFmpeg is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with FFmpeg; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef AVCODEC_WMA_FREQS_H +#define AVCODEC_WMA_FREQS_H + +#include + +extern const uint16_t ff_wma_critical_freqs[25]; + +#endif /* AVCODEC_WMA_FREQS_H */ diff --git a/Code/BF2/External/ffmpeg-bink/shim/avcodec.h b/Code/BF2/External/ffmpeg-bink/shim/avcodec.h new file mode 100644 index 000000000..2748e70c7 --- /dev/null +++ b/Code/BF2/External/ffmpeg-bink/shim/avcodec.h @@ -0,0 +1,2 @@ +/* [CHOSEN, not recovered] OpenBF2 forwarder: see ffbink_shim.h. */ +#include "ffbink_shim.h" diff --git a/Code/BF2/External/ffmpeg-bink/shim/blockdsp.h b/Code/BF2/External/ffmpeg-bink/shim/blockdsp.h new file mode 100644 index 000000000..2748e70c7 --- /dev/null +++ b/Code/BF2/External/ffmpeg-bink/shim/blockdsp.h @@ -0,0 +1,2 @@ +/* [CHOSEN, not recovered] OpenBF2 forwarder: see ffbink_shim.h. */ +#include "ffbink_shim.h" diff --git a/Code/BF2/External/ffmpeg-bink/shim/codec_internal.h b/Code/BF2/External/ffmpeg-bink/shim/codec_internal.h new file mode 100644 index 000000000..2748e70c7 --- /dev/null +++ b/Code/BF2/External/ffmpeg-bink/shim/codec_internal.h @@ -0,0 +1,2 @@ +/* [CHOSEN, not recovered] OpenBF2 forwarder: see ffbink_shim.h. */ +#include "ffbink_shim.h" diff --git a/Code/BF2/External/ffmpeg-bink/shim/config_components.h b/Code/BF2/External/ffmpeg-bink/shim/config_components.h new file mode 100644 index 000000000..681051d52 --- /dev/null +++ b/Code/BF2/External/ffmpeg-bink/shim/config_components.h @@ -0,0 +1,3 @@ +/* [CHOSEN, not recovered] OpenBF2: the decoders this vendored subset builds. */ +#define CONFIG_BINKAUDIO_DCT_DECODER 1 +#define CONFIG_BINKAUDIO_RDFT_DECODER 1 diff --git a/Code/BF2/External/ffmpeg-bink/shim/decode.h b/Code/BF2/External/ffmpeg-bink/shim/decode.h new file mode 100644 index 000000000..2748e70c7 --- /dev/null +++ b/Code/BF2/External/ffmpeg-bink/shim/decode.h @@ -0,0 +1,2 @@ +/* [CHOSEN, not recovered] OpenBF2 forwarder: see ffbink_shim.h. */ +#include "ffbink_shim.h" diff --git a/Code/BF2/External/ffmpeg-bink/shim/ffbink.h b/Code/BF2/External/ffmpeg-bink/shim/ffbink.h new file mode 100644 index 000000000..8b8fe2c08 --- /dev/null +++ b/Code/BF2/External/ffmpeg-bink/shim/ffbink.h @@ -0,0 +1,55 @@ +/* + * [CHOSEN, not recovered] OpenBF2 macOS port: a small C interface over the vendored FFmpeg Bink + * decoders, used by Code/RendDX9Abi/BinkFFmpeg.cpp (the Bink API subset BF2 calls). Container + * parsing stays on the C++ side; this layer turns one frame's video bytes into YUV planes and one + * audio-track packet into float samples. Port code, not FFmpeg code. + */ +#ifndef FFBINK_H +#define FFBINK_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Bytes of zeroed slack every packet buffer handed to the decoders must carry after its data. */ +#define FFBINK_PACKET_PADDING 64 + +typedef struct FFBinkVideo FFBinkVideo; +typedef struct FFBinkAudio FFBinkAudio; + +typedef struct FFBinkPicture { + const uint8_t *plane[4]; /* Y, U, V, A (A only for alpha movies) */ + int linesize[4]; + int width, height; + int has_alpha; + int full_range; /* 1 for 'k' revisions (JPEG range), else MPEG range */ +} FFBinkPicture; + +/* codec_tag: the file's first four bytes as a little-endian dword ("BIKi" -> 'B'|'I'<<8|...). + * video_flags: the header dword at offset 40 (FFmpeg's video extradata). Returns NULL on failure. */ +FFBinkVideo *ffbink_video_open(uint32_t codec_tag, uint32_t video_flags, int width, int height); +/* Decodes one frame's video packet (data must carry FFBINK_PACKET_PADDING zeros past size). + * The picture stays valid until the next decode or close. Returns 0 or a negative error. */ +int ffbink_video_decode(FFBinkVideo *v, const uint8_t *data, int size, FFBinkPicture *out); +/* Restarts the frame counter, as FFmpeg's flush does when playback seeks to the first frame. */ +void ffbink_video_flush(FFBinkVideo *v); +void ffbink_video_close(FFBinkVideo *v); + +/* use_dct: header track flag 0x1000; channels 1 or 2. Returns NULL on failure (an RDFT track is + * reported and refused; see README.md). */ +FFBinkAudio *ffbink_audio_open(uint32_t codec_tag, int sample_rate, int channels, int use_dct); +/* Decodes one audio-track packet (the bytes after its size dword, starting with the reported + * decoded size). sink receives planar float samples, [-1, 1] nominal, per decoded block. + * Returns the number of samples per channel produced, or a negative error. */ +typedef void (*ffbink_audio_sink)(void *user, const float *const *planes, int channels, int samples); +int ffbink_audio_decode(FFBinkAudio *a, const uint8_t *data, int size, ffbink_audio_sink sink, void *user); +void ffbink_audio_flush(FFBinkAudio *a); +void ffbink_audio_close(FFBinkAudio *a); + +#ifdef __cplusplus +} +#endif + +#endif /* FFBINK_H */ diff --git a/Code/BF2/External/ffmpeg-bink/shim/ffbink_shim.c b/Code/BF2/External/ffmpeg-bink/shim/ffbink_shim.c new file mode 100644 index 000000000..c35a5d878 --- /dev/null +++ b/Code/BF2/External/ffmpeg-bink/shim/ffbink_shim.c @@ -0,0 +1,632 @@ +/* + * [CHOSEN, not recovered] OpenBF2 macOS port: implementations behind ffbink_shim.h (the + * libavutil/libavcodec services the vendored FFmpeg Bink decoders call) and the ffbink.h + * interface. Port code written for OpenBF2, not taken from FFmpeg; see ../README.md. + */ +#include "ffbink_shim.h" +#include "ffbink.h" + +#include +#include + +extern const FFCodec ff_bink_decoder; +extern const FFCodec ff_binkaudio_dct_decoder; +extern const FFCodec ff_binkaudio_rdft_decoder; + +/* ---- logging, assertions, memory ---------------------------------------------------------- */ + +void av_log(void *avcl, int level, const char *fmt, ...) +{ + (void)avcl; + static int verbose = -1; + if (verbose < 0) + verbose = getenv("BF2_BINK_VERBOSE") != NULL; + if (level > AV_LOG_WARNING && !verbose) + return; + va_list ap; + va_start(ap, fmt); + fputs("[bink] ", stderr); + vfprintf(stderr, fmt, ap); + va_end(ap); +} + +void ffbink_assert_fail(const char *what, const char *file, int line) +{ + fprintf(stderr, "[bink] assertion %s failed at %s:%d\n", what, file, line); + abort(); +} + +#if defined(_WIN32) +#include +#include + +void *av_malloc(size_t size) { return _aligned_malloc(size ? size : 1, 64); } +static void ffbink_free(void *p) { _aligned_free(p); } + +static BOOL CALLBACK ffbink_once_cb(PINIT_ONCE once, PVOID routine, PVOID *ctx) +{ + (void)once; (void)ctx; + ((void (*)(void))routine)(); + return TRUE; +} + +int ffbink_once(AVOnce *control, void (*routine)(void)) +{ + return InitOnceExecuteOnce((PINIT_ONCE)control, ffbink_once_cb, (PVOID)routine, NULL) ? 0 : -1; +} +#else +void *av_malloc(size_t size) +{ + void *p = NULL; + if (posix_memalign(&p, 64, size ? size : 1)) + return NULL; + return p; +} +static void ffbink_free(void *p) { free(p); } +#endif + +void *av_mallocz(size_t size) +{ + void *p = av_malloc(size); + if (p) + memset(p, 0, size); + return p; +} + +void *av_calloc(size_t nmemb, size_t size) +{ + if (size && nmemb > SIZE_MAX / size) + return NULL; + return av_mallocz(nmemb * size); +} + +void av_free(void *ptr) { ffbink_free(ptr); } + +void av_freep(void *arg) +{ + void **p = (void **)arg; + ffbink_free(*p); + *p = NULL; +} + +int av_image_check_size(unsigned int w, unsigned int h, int log_offset, void *log_ctx) +{ + (void)log_offset; (void)log_ctx; + if (w > 0 && h > 0 && (w + 128) * (uint64_t)(h + 128) < INT_MAX / 8) + return 0; + return AVERROR(EINVAL); +} + +/* ---- packets and frames ------------------------------------------------------------------- */ + +void av_packet_unref(AVPacket *pkt) +{ + pkt->data = NULL; + pkt->size = 0; +} + +struct FFBinkBuffer { + int refs; + uint8_t *mem; +}; + +static FFBinkBuffer *buffer_new(size_t size) +{ + FFBinkBuffer *b = (FFBinkBuffer *)calloc(1, sizeof(*b)); + if (!b) + return NULL; + b->mem = (uint8_t *)av_mallocz(size); + if (!b->mem) { + free(b); + return NULL; + } + b->refs = 1; + return b; +} + +static void buffer_unref(FFBinkBuffer *b) +{ + if (b && --b->refs == 0) { + av_free(b->mem); + free(b); + } +} + +AVFrame *av_frame_alloc(void) +{ + return (AVFrame *)calloc(1, sizeof(AVFrame)); +} + +void av_frame_unref(AVFrame *frame) +{ + buffer_unref(frame->buf); + memset(frame, 0, sizeof(*frame)); +} + +void av_frame_free(AVFrame **frame) +{ + if (!*frame) + return; + av_frame_unref(*frame); + free(*frame); + *frame = NULL; +} + +int av_frame_ref(AVFrame *dst, const AVFrame *src) +{ + if (dst == src) + return 0; + *dst = *src; + dst->extended_data = dst->data; + if (dst->buf) + dst->buf->refs++; + return 0; +} + +int av_frame_replace(AVFrame *dst, const AVFrame *src) +{ + if (dst == src) + return 0; + FFBinkBuffer *old = dst->buf; + if (src->buf) + src->buf->refs++; + *dst = *src; + dst->extended_data = dst->data; + buffer_unref(old); + return 0; +} + +/* Video planes are padded to 32x32 luma blocks and 64-byte strides, like FFmpeg's default + * allocator; audio gets one plane per channel (planar) or one interleaved plane. */ +int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags) +{ + (void)flags; + const int nb_samples = frame->nb_samples; /* binkaudio sets it before asking */ + av_frame_unref(frame); + frame->nb_samples = nb_samples; + if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) { + const int w = FFALIGN(avctx->width, 32), h = FFALIGN(avctx->height, 32); + const int ly = FFALIGN(w, 64), lc = FFALIGN(w / 2, 64); + const int alpha = avctx->pix_fmt == AV_PIX_FMT_YUVA420P; + const size_t sy = (size_t)ly * h, sc = (size_t)lc * (h / 2); + FFBinkBuffer *b = buffer_new(sy * (alpha ? 2 : 1) + 2 * sc); + if (!b) + return AVERROR(ENOMEM); + frame->buf = b; + frame->data[0] = b->mem; + frame->data[1] = b->mem + sy; + frame->data[2] = b->mem + sy + sc; + frame->linesize[0] = ly; + frame->linesize[1] = lc; + frame->linesize[2] = lc; + if (alpha) { + frame->data[3] = b->mem + sy + 2 * sc; + frame->linesize[3] = ly; + } + frame->width = avctx->width; + frame->height = avctx->height; + frame->format = avctx->pix_fmt; + } else { + const int ch = avctx->ch_layout.nb_channels; + const int planar = avctx->sample_fmt == AV_SAMPLE_FMT_FLTP; + const int planes = planar ? ch : 1; + const size_t per = (size_t)FFMAX(nb_samples, 0) * (planar ? 1 : ch); + if (planes < 1 || planes > 8) + return AVERROR(EINVAL); + FFBinkBuffer *b = buffer_new(per * sizeof(float) * planes); + if (!b) + return AVERROR(ENOMEM); + frame->buf = b; + for (int i = 0; i < planes; i++) { + frame->data[i] = b->mem + i * per * sizeof(float); + frame->linesize[i] = (int)(per * sizeof(float)); + } + frame->format = avctx->sample_fmt; + } + frame->extended_data = frame->data; + frame->pts = AV_NOPTS_VALUE; + return 0; +} + +/* bink.c's revision-'b' path decodes in place into the reference frame. */ +int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame, int flags) +{ + if (!frame->buf) + return ff_get_buffer(avctx, frame, flags); + if (frame->buf->refs == 1) + return 0; + AVFrame copy = { { 0 } }; + int ret = ff_get_buffer(avctx, ©, flags); + if (ret < 0) + return ret; + for (int p = 0; p < 4 && frame->data[p]; p++) { + const int rows = (p == 1 || p == 2) ? FFALIGN(avctx->height, 32) / 2 : FFALIGN(avctx->height, 32); + memcpy(copy.data[p], frame->data[p], (size_t)frame->linesize[p] * rows); + } + av_frame_unref(frame); + *frame = copy; + frame->extended_data = frame->data; + return 0; +} + +int ff_decode_get_packet(AVCodecContext *avctx, AVPacket *pkt) +{ + AVCodecInternal *in = avctx->internal; + if (!in->pending.data) + return AVERROR(EAGAIN); + *pkt = in->pending; + av_packet_unref(&in->pending); + return 0; +} + +/* ---- blockdsp / hpeldsp: the C reference behaviour of the routines bink.c selects ---------- */ + +static void clear_block_c(int16_t *block) { memset(block, 0, sizeof(int16_t) * 64); } + +static void fill_block16_c(uint8_t *block, uint8_t value, ptrdiff_t line_size, int h) +{ + for (int i = 0; i < h; i++, block += line_size) + memset(block, value, 16); +} + +static void fill_block8_c(uint8_t *block, uint8_t value, ptrdiff_t line_size, int h) +{ + for (int i = 0; i < h; i++, block += line_size) + memset(block, value, 8); +} + +void ff_blockdsp_init(BlockDSPContext *c) +{ + c->clear_block = clear_block_c; + c->fill_block_tab[0] = fill_block16_c; + c->fill_block_tab[1] = fill_block8_c; +} + +static void put_pixels16_c(uint8_t *block, const uint8_t *pixels, ptrdiff_t line_size, int h) +{ + for (int i = 0; i < h; i++, block += line_size, pixels += line_size) + memmove(block, pixels, 16); +} + +static void put_pixels8_c(uint8_t *block, const uint8_t *pixels, ptrdiff_t line_size, int h) +{ + for (int i = 0; i < h; i++, block += line_size, pixels += line_size) + memmove(block, pixels, 8); +} + +void ff_hpeldsp_init(HpelDSPContext *c, int flags) +{ + (void)flags; + memset(c, 0, sizeof(*c)); + c->put_pixels_tab[0][0] = put_pixels16_c; + c->put_pixels_tab[1][0] = put_pixels8_c; +} + +/* ---- VLC: single-level little-endian tables --------------------------------------------- */ + +/* With VLC_INIT_LE a code is read LSB-first, so every table index whose low `len` bits equal + * the code maps to that symbol (FFmpeg's vlc.c: OUTPUT_LE, inc = 1 << len). */ +int ffbink_vlc_init(VLC *vlc, int nb_bits, int nb_codes, const uint8_t *lens, int lens_wrap, + int lens_size, const uint8_t *codes, int codes_wrap, int codes_size, int flags) +{ + if (lens_wrap != 1 || lens_size != 1 || codes_wrap != 1 || codes_size != 1 || + (flags & VLC_INIT_LE) != VLC_INIT_LE || !(flags & VLC_INIT_USE_STATIC) || + nb_bits < 1 || nb_bits > 15 || vlc->table_allocated < (1 << nb_bits)) { + av_log(NULL, AV_LOG_ERROR, "unsupported vlc_init form\n"); + return AVERROR(EINVAL); + } + const int size = 1 << nb_bits; + for (int j = 0; j < size; j++) { + vlc->table[j].sym = 0; + vlc->table[j].len = 0; + } + for (int i = 0; i < nb_codes; i++) { + const int len = lens[i]; + const int code = codes[i]; + if (!len) + continue; + if (len > nb_bits || code >= (1 << len)) { + av_log(NULL, AV_LOG_ERROR, "invalid vlc code %d/%d\n", code, len); + return AVERROR(EINVAL); + } + for (int j = code; j < size; j += 1 << len) { + if (vlc->table[j].len) { + av_log(NULL, AV_LOG_ERROR, "incorrect codes\n"); + return AVERROR_INVALIDDATA; + } + vlc->table[j].sym = (VLCBaseType)i; + vlc->table[j].len = (VLCBaseType)len; + } + } + vlc->bits = nb_bits; + vlc->table_size = size; + return 0; +} + +/* ---- tx: the inverse DCT (DCT-III) binkaudio_dct uses ----------------------------------- */ + +struct AVTXContext { + int n; /* transform length (frame_len) */ + float scale; + AVComplexFloat *buf; /* n */ + AVComplexFloat *tw; /* n/2 inverse-FFT twiddles e^{+2 pi i k / n} */ + AVComplexFloat *pre; /* n pre-rotation e^{+i pi k / 2n} */ + int *rev; /* n bit reversal */ +}; + +static void tx_ifft(AVTXContext *s) +{ + const int n = s->n; + AVComplexFloat *z = s->buf; + for (int i = 0; i < n; i++) { + const int r = s->rev[i]; + if (r > i) { + AVComplexFloat t = z[i]; + z[i] = z[r]; + z[r] = t; + } + } + for (int len = 2; len <= n; len <<= 1) { + const int half = len >> 1, step = n / len; + for (int i = 0; i < n; i += len) { + for (int k = 0; k < half; k++) { + const AVComplexFloat w = s->tw[k * step]; + AVComplexFloat *a = &z[i + k], *b = &z[i + k + half]; + const float tr = b->re * w.re - b->im * w.im; + const float ti = b->re * w.im + b->im * w.re; + b->re = a->re - tr; + b->im = a->im - ti; + a->re += tr; + a->im += ti; + } + } + } +} + +/* out[m] = scale * (X[0] + 2 sum_{k=1}^{n-1} X[k] cos(pi k (2m + 1) / 2n)), m = 0..n-1: the + * values of FFmpeg's inverse AV_TX_FLOAT_DCT (DCT-III), computed with one n-point complex + * inverse FFT: V[k] = (X[k] - i X[n-k]) e^{i pi k / 2n} (X[n] = 0), v = IFFT(V) unnormalised, + * out[2j] = scale Re v[j], out[2j+1] = scale Re v[n-1-j]. bf2_bink_decode_test checks the + * result against the ffmpeg CLI's decode of the shipped movies. */ +static void tx_dct3(AVTXContext *s, void *_out, void *_in, ptrdiff_t stride) +{ + (void)stride; + const int n = s->n; + const float *x = (const float *)_in; + float *out = (float *)_out; + for (int k = 0; k < n; k++) { + const float a = x[k], b = k ? -x[n - k] : 0.0f; + const AVComplexFloat p = s->pre[k]; + s->buf[k].re = a * p.re - b * p.im; + s->buf[k].im = a * p.im + b * p.re; + } + tx_ifft(s); + const float h = s->scale; + for (int j = 0; j < n / 2; j++) { + out[2 * j] = s->buf[j].re * h; + out[2 * j + 1] = s->buf[n - 1 - j].re * h; + } +} + +int av_tx_init(AVTXContext **ctx, av_tx_fn *tx, enum AVTXType type, int inv, int len, + const void *scale, uint64_t flags) +{ + (void)flags; + *ctx = NULL; + if (type != AV_TX_FLOAT_DCT || !inv) { + /* [FRONTIER] binkaudio_rdft (and forward transforms) are not part of this subset: no + * Battlefield 2 movie carries an RDFT track. ffbink_audio_open reports the refusal. */ + return AVERROR(ENOSYS); + } + const int n = len * 2; /* the inverse DCT runs at twice the requested length, as in FFmpeg */ + if (n < 4 || (n & (n - 1))) + return AVERROR(EINVAL); + AVTXContext *s = (AVTXContext *)calloc(1, sizeof(*s)); + if (!s) + return AVERROR(ENOMEM); + s->n = n; + s->scale = *(const float *)scale; + s->buf = (AVComplexFloat *)av_malloc(sizeof(AVComplexFloat) * n); + s->tw = (AVComplexFloat *)av_malloc(sizeof(AVComplexFloat) * (n / 2)); + s->pre = (AVComplexFloat *)av_malloc(sizeof(AVComplexFloat) * n); + s->rev = (int *)av_malloc(sizeof(int) * n); + if (!s->buf || !s->tw || !s->pre || !s->rev) { + av_tx_uninit(&s); + return AVERROR(ENOMEM); + } + const int bits = av_log2((unsigned)n); + for (int i = 0; i < n; i++) { + int r = 0; + for (int b = 0; b < bits; b++) + r |= ((i >> b) & 1) << (bits - 1 - b); + s->rev[i] = r; + s->pre[i].re = (float)cos(M_PI * i / (2.0 * n)); + s->pre[i].im = (float)sin(M_PI * i / (2.0 * n)); + } + for (int k = 0; k < n / 2; k++) { + s->tw[k].re = (float)cos(2.0 * M_PI * k / n); + s->tw[k].im = (float)sin(2.0 * M_PI * k / n); + } + *ctx = s; + *tx = tx_dct3; + return 0; +} + +void av_tx_uninit(AVTXContext **ctx) +{ + AVTXContext *s = *ctx; + if (!s) + return; + av_free(s->buf); + av_free(s->tw); + av_free(s->pre); + av_free(s->rev); + free(s); + *ctx = NULL; +} + +/* ---- ffbink.h ------------------------------------------------------------------------------ */ + +typedef struct FFBinkCodec { + const FFCodec *codec; + AVCodecContext ctx; + AVCodecInternal internal; + AVPacket in_pkt; + AVFrame *frame; + uint8_t extradata[4 + AV_INPUT_BUFFER_PADDING_SIZE]; + int opened; +} FFBinkCodec; + +static void codec_close(FFBinkCodec *c) +{ + if (c->opened && c->codec->close) + c->codec->close(&c->ctx); + av_frame_free(&c->frame); + free(c->ctx.priv_data); + c->ctx.priv_data = NULL; + c->opened = 0; +} + +static int codec_open(FFBinkCodec *c, const FFCodec *codec, uint32_t extradata) +{ + memset(c, 0, sizeof(*c)); + c->codec = codec; + c->ctx.codec = &codec->p; + c->ctx.internal = &c->internal; + c->internal.in_pkt = &c->in_pkt; + c->extradata[0] = (uint8_t)extradata; + c->extradata[1] = (uint8_t)(extradata >> 8); + c->extradata[2] = (uint8_t)(extradata >> 16); + c->extradata[3] = (uint8_t)(extradata >> 24); + c->ctx.extradata = c->extradata; + c->ctx.extradata_size = 4; + c->ctx.priv_data = calloc(1, (size_t)codec->priv_data_size); + c->frame = av_frame_alloc(); + if (!c->ctx.priv_data || !c->frame) + return AVERROR(ENOMEM); + return 0; +} + +static int codec_init(FFBinkCodec *c) +{ + const int ret = c->codec->init(&c->ctx); + c->opened = 1; /* FF_CODEC_CAP_INIT_CLEANUP: close runs after a failed init too */ + return ret; +} + +struct FFBinkVideo { FFBinkCodec c; }; +struct FFBinkAudio { FFBinkCodec c; }; + +FFBinkVideo *ffbink_video_open(uint32_t codec_tag, uint32_t video_flags, int width, int height) +{ + FFBinkVideo *v = (FFBinkVideo *)calloc(1, sizeof(*v)); + if (!v) + return NULL; + if (codec_open(&v->c, &ff_bink_decoder, video_flags) < 0) + goto fail; + v->c.ctx.codec_tag = codec_tag; + v->c.ctx.width = width; + v->c.ctx.height = height; + if (codec_init(&v->c) < 0) + goto fail; + return v; +fail: + ffbink_video_close(v); + return NULL; +} + +int ffbink_video_decode(FFBinkVideo *v, const uint8_t *data, int size, FFBinkPicture *out) +{ + AVPacket pkt = { data, size }; + int got = 0; + av_frame_unref(v->c.frame); + const int ret = v->c.codec->cb.decode(&v->c.ctx, v->c.frame, &got, &pkt); + if (ret < 0) + return ret; + if (!got) + return AVERROR_INVALIDDATA; + const AVFrame *f = v->c.frame; + for (int p = 0; p < 4; p++) { + out->plane[p] = f->data[p]; + out->linesize[p] = f->linesize[p]; + } + out->width = v->c.ctx.width; + out->height = v->c.ctx.height; + out->has_alpha = v->c.ctx.pix_fmt == AV_PIX_FMT_YUVA420P; + out->full_range = v->c.ctx.color_range == AVCOL_RANGE_JPEG; + return 0; +} + +void ffbink_video_flush(FFBinkVideo *v) +{ + if (v->c.codec->flush) + v->c.codec->flush(&v->c.ctx); +} + +void ffbink_video_close(FFBinkVideo *v) +{ + if (!v) + return; + codec_close(&v->c); + free(v); +} + +FFBinkAudio *ffbink_audio_open(uint32_t codec_tag, int sample_rate, int channels, int use_dct) +{ + FFBinkAudio *a = (FFBinkAudio *)calloc(1, sizeof(*a)); + if (!a) + return NULL; + /* FFmpeg's demuxer hands the audio decoder the file tag as extradata (version_b test). */ + if (codec_open(&a->c, use_dct ? &ff_binkaudio_dct_decoder : &ff_binkaudio_rdft_decoder, + codec_tag) < 0) + goto fail; + a->c.ctx.sample_rate = sample_rate; + av_channel_layout_default(&a->c.ctx.ch_layout, channels); + if (codec_init(&a->c) < 0) { + if (!use_dct) + av_log(NULL, AV_LOG_ERROR, "[FRONTIER] Bink RDFT audio is not in the vendored subset\n"); + goto fail; + } + return a; +fail: + ffbink_audio_close(a); + return NULL; +} + +int ffbink_audio_decode(FFBinkAudio *a, const uint8_t *data, int size, ffbink_audio_sink sink, void *user) +{ + int total = 0; + a->c.internal.pending.data = data; + a->c.internal.pending.size = size; + for (;;) { + const int ret = a->c.codec->cb.receive_frame(&a->c.ctx, a->c.frame); + if (ret == AVERROR(EAGAIN)) + break; + if (ret < 0) { + av_packet_unref(&a->c.internal.pending); + av_packet_unref(&a->c.in_pkt); + return total ? total : ret; + } + const int ch = a->c.ctx.ch_layout.nb_channels; + if (sink) + sink(user, (const float *const *)a->c.frame->extended_data, ch, a->c.frame->nb_samples); + total += a->c.frame->nb_samples; + } + return total; +} + +void ffbink_audio_flush(FFBinkAudio *a) +{ + av_packet_unref(&a->c.internal.pending); + av_packet_unref(&a->c.in_pkt); + if (a->c.codec->flush) + a->c.codec->flush(&a->c.ctx); +} + +void ffbink_audio_close(FFBinkAudio *a) +{ + if (!a) + return; + codec_close(&a->c); + free(a); +} diff --git a/Code/BF2/External/ffmpeg-bink/shim/ffbink_shim.h b/Code/BF2/External/ffmpeg-bink/shim/ffbink_shim.h new file mode 100644 index 000000000..54ce703e3 --- /dev/null +++ b/Code/BF2/External/ffmpeg-bink/shim/ffbink_shim.h @@ -0,0 +1,336 @@ +/* + * [CHOSEN, not recovered] OpenBF2 macOS / Windows x64 port: the minimal libavutil/libavcodec surface that the + * unmodified FFmpeg 7.1.1 Bink decoders (../libavcodec/bink.c, binkaudio.c) compile against. + * This file is OpenBF2 port code, not FFmpeg code: it declares only what those two decoders + * reach and implements it in ffbink_shim.c. Every libavutil/libavcodec header name the decoders + * include (avcodec.h, get_bits.h, libavutil/tx.h, ...) is a one-line forwarder to this file. + * See ../README.md for the provenance and licence notes. + */ +#ifndef FFBINK_SHIM_H +#define FFBINK_SHIM_H + +#if defined(_MSC_VER) && !defined(_USE_MATH_DEFINES) +#define _USE_MATH_DEFINES /* M_PI in */ +#endif +#include +#include +#include +#include +#include +#include +#include + +/* ---- compiler portability (OpenBF2): GCC/clang on macOS, MSVC on Windows x64 --------------- */ +#if defined(_MSC_VER) && !defined(__clang__) +#include +#define FFBINK_INLINE __forceinline +#define FFBINK_UNUSED +#define FFBINK_PRINTF(f, a) +#define FFBINK_NORETURN __declspec(noreturn) +#define FFBINK_ALIGN(n) __declspec(align(n)) +static __forceinline int ffbink_clz(unsigned v) { unsigned long i; _BitScanReverse(&i, v); return 31 - (int)i; } +#else +#define FFBINK_INLINE inline __attribute__((always_inline)) +#define FFBINK_UNUSED __attribute__((unused)) +#define FFBINK_PRINTF(f, a) __attribute__((format(printf, f, a))) +#define FFBINK_NORETURN +#define FFBINK_ALIGN(n) +#define ffbink_clz(v) __builtin_clz(v) +#endif + +/* ---- libavutil/attributes.h, common.h, macros.h ------------------------------------------- */ +#define av_cold +#define av_always_inline FFBINK_INLINE +#define av_unused FFBINK_UNUSED +#define FFMIN(a, b) ((a) > (b) ? (b) : (a)) +#define FFMAX(a, b) ((a) > (b) ? (a) : (b)) +#define FFALIGN(x, a) (((x) + (a) - 1) & ~((a) - 1)) +#define FFSWAP(type, a, b) do { type SWAP_tmp = b; b = a; a = SWAP_tmp; } while (0) +#define FF_ARRAY_ELEMS(a) (sizeof(a) / sizeof((a)[0])) +#define MKTAG(a, b, c, d) ((unsigned)(a) | ((unsigned)(b) << 8) | ((unsigned)(c) << 16) | ((unsigned)(d) << 24)) + +static inline int av_log2(unsigned v) +{ + return v ? 31 - ffbink_clz(v) : 0; +} + +static inline uint32_t AV_RL32(const void *p) +{ + const uint8_t *b = (const uint8_t *)p; + return (uint32_t)b[0] | ((uint32_t)b[1] << 8) | ((uint32_t)b[2] << 16) | ((uint32_t)b[3] << 24); +} + +static inline uint64_t ffbink_rl64(const uint8_t *b) +{ + uint64_t v; + memcpy(&v, b, sizeof(v)); +#if defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ + v = __builtin_bswap64(v); +#endif + return v; +} + +/* ---- libavutil/intfloat.h --------------------------------------------------------------- */ +static inline float av_int2float(uint32_t i) +{ + float f; + memcpy(&f, &i, sizeof(f)); + return f; +} + +/* ---- libavutil/error.h, log.h, avassert.h, emms.h --------------------------------------- */ +#define AVERROR(e) (-(e)) +#define AVERROR_INVALIDDATA (-(int)MKTAG('I', 'N', 'D', 'A')) +#define AVERROR_EOF (-(int)MKTAG('E', 'O', 'F', ' ')) +#define AV_LOG_ERROR 16 +#define AV_LOG_WARNING 24 +void av_log(void *avcl, int level, const char *fmt, ...) FFBINK_PRINTF(3, 4); +#define av_assert0(cond) do { if (!(cond)) ffbink_assert_fail(#cond, __FILE__, __LINE__); } while (0) +#if defined(_MSC_VER) && !defined(__clang__) +FFBINK_NORETURN void ffbink_assert_fail(const char *what, const char *file, int line); +#else +void ffbink_assert_fail(const char *what, const char *file, int line) __attribute__((noreturn)); +#endif +#define emms_c() ((void)0) + +/* ---- libavutil/mem.h, mem_internal.h ---------------------------------------------------- */ +void *av_malloc(size_t size); +void *av_mallocz(size_t size); +void *av_calloc(size_t nmemb, size_t size); +void av_free(void *ptr); +void av_freep(void *ptr); +#if defined(_MSC_VER) && !defined(__clang__) +#define LOCAL_ALIGNED_16(t, v, ...) __declspec(align(16)) t v __VA_ARGS__ +#define LOCAL_ALIGNED_32(t, v, ...) __declspec(align(32)) t v __VA_ARGS__ +#define DECLARE_ALIGNED(n, t, v) __declspec(align(n)) t v +#else +#define LOCAL_ALIGNED_16(t, v, ...) t __attribute__((aligned(16))) v __VA_ARGS__ +#define LOCAL_ALIGNED_32(t, v, ...) t __attribute__((aligned(32))) v __VA_ARGS__ +#define DECLARE_ALIGNED(n, t, v) t __attribute__((aligned(n))) v +#endif + +/* ---- libavutil/thread.h ----------------------------------------------------------------- */ +#if defined(_WIN32) +/* Windows: InitOnceExecuteOnce in ffbink_shim.c (AVOnce has INIT_ONCE's layout, one pointer). */ +typedef struct AVOnce { void *ptr; } AVOnce; +#define AV_ONCE_INIT { 0 } +int ffbink_once(AVOnce *control, void (*routine)(void)); +#define ff_thread_once(control, routine) ffbink_once(control, routine) +#else +#include +typedef pthread_once_t AVOnce; +#define AV_ONCE_INIT PTHREAD_ONCE_INIT +#define ff_thread_once(control, routine) pthread_once(control, routine) +#endif + +/* ---- libavutil/pixfmt.h, samplefmt.h, channel_layout.h, avutil.h ----------------------- */ +enum AVMediaType { AVMEDIA_TYPE_VIDEO = 0, AVMEDIA_TYPE_AUDIO = 1 }; +enum AVPixelFormat { AV_PIX_FMT_NONE = -1, AV_PIX_FMT_YUV420P = 0, AV_PIX_FMT_YUVA420P = 33 }; +enum AVColorRange { AVCOL_RANGE_UNSPECIFIED = 0, AVCOL_RANGE_MPEG = 1, AVCOL_RANGE_JPEG = 2 }; +enum AVSampleFormat { AV_SAMPLE_FMT_NONE = -1, AV_SAMPLE_FMT_FLT = 3, AV_SAMPLE_FMT_FLTP = 8 }; +#define AV_NOPTS_VALUE ((int64_t)UINT64_C(0x8000000000000000)) +typedef struct AVChannelLayout { int nb_channels; } AVChannelLayout; +static inline void av_channel_layout_uninit(AVChannelLayout *l) { l->nb_channels = 0; } +static inline void av_channel_layout_default(AVChannelLayout *l, int n) { l->nb_channels = n; } + +/* ---- libavutil/imgutils.h --------------------------------------------------------------- */ +int av_image_check_size(unsigned int w, unsigned int h, int log_offset, void *log_ctx); + +/* ---- libavcodec/codec_id.h, packet.h, frame.h ------------------------------------------- */ +enum AVCodecID { + AV_CODEC_ID_NONE = 0, + AV_CODEC_ID_BINKVIDEO, + AV_CODEC_ID_BINKAUDIO_RDFT, + AV_CODEC_ID_BINKAUDIO_DCT, +}; +#define AV_INPUT_BUFFER_PADDING_SIZE 64 + +typedef struct AVPacket { + const uint8_t *data; /* borrowed; the caller pads it with AV_INPUT_BUFFER_PADDING_SIZE zeros */ + int size; +} AVPacket; +void av_packet_unref(AVPacket *pkt); + +typedef struct FFBinkBuffer FFBinkBuffer; +typedef struct AVFrame { + uint8_t *data[8]; + int linesize[8]; + uint8_t **extended_data; + int width, height; + int nb_samples; + int format; + int64_t pts; + FFBinkBuffer *buf; /* one refcounted allocation backs every plane */ +} AVFrame; +AVFrame *av_frame_alloc(void); +void av_frame_free(AVFrame **frame); +void av_frame_unref(AVFrame *frame); +int av_frame_ref(AVFrame *dst, const AVFrame *src); +int av_frame_replace(AVFrame *dst, const AVFrame *src); + +/* ---- libavcodec/avcodec.h, codec.h, codec_internal.h, internal.h, decode.h -------------- */ +#define AV_CODEC_CAP_DR1 (1 << 1) +#define FF_CODEC_CAP_INIT_CLEANUP (1 << 1) +#define AV_GET_BUFFER_FLAG_REF (1 << 0) + +typedef struct AVCodec { + const char *name; + const char *long_name; + enum AVMediaType type; + enum AVCodecID id; + int capabilities; +} AVCodec; + +typedef struct AVCodecInternal { + AVPacket *in_pkt; /* the packet binkaudio keeps between receive_frame calls */ + AVPacket pending; /* the packet the next ff_decode_get_packet hands out */ + FFBinkBuffer *spare; /* one recycled video buffer */ +} AVCodecInternal; + +typedef struct AVCodecContext { + const AVCodec *codec; + void *priv_data; + AVCodecInternal *internal; + unsigned int codec_tag; + const uint8_t *extradata; + int extradata_size; + int width, height; + int flags; + enum AVPixelFormat pix_fmt; + enum AVColorRange color_range; + int sample_rate; + AVChannelLayout ch_layout; + enum AVSampleFormat sample_fmt; +} AVCodecContext; + +struct AVCodecContext; +typedef struct FFCodec { + AVCodec p; + int priv_data_size; + int (*init)(struct AVCodecContext *); + int (*close)(struct AVCodecContext *); + void (*flush)(struct AVCodecContext *); + int caps_internal; + struct { + int (*decode)(struct AVCodecContext *, AVFrame *, int *, AVPacket *); + int (*receive_frame)(struct AVCodecContext *, AVFrame *); + } cb; +} FFCodec; +#define CODEC_LONG_NAME(str) .p.long_name = (str) +#define FF_CODEC_DECODE_CB(func) .cb.decode = (func) +#define FF_CODEC_RECEIVE_FRAME_CB(func) .cb.receive_frame = (func) + +int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags); +int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame, int flags); +int ff_decode_get_packet(AVCodecContext *avctx, AVPacket *pkt); + +/* ---- libavcodec/blockdsp.h, hpeldsp.h --------------------------------------------------- */ +typedef struct BlockDSPContext { + void (*clear_block)(int16_t *block); + void (*fill_block_tab[2])(uint8_t *block, uint8_t value, ptrdiff_t line_size, int h); +} BlockDSPContext; +void ff_blockdsp_init(BlockDSPContext *c); + +typedef void (*op_pixels_func)(uint8_t *block, const uint8_t *pixels, ptrdiff_t line_size, int h); +typedef struct HpelDSPContext { + op_pixels_func put_pixels_tab[4][4]; +} HpelDSPContext; +void ff_hpeldsp_init(HpelDSPContext *c, int flags); + +/* ---- libavcodec/vlc.h ------------------------------------------------------------------- */ +typedef int16_t VLCBaseType; +typedef struct VLCElem { VLCBaseType sym, len; } VLCElem; +typedef struct VLC { + int bits; + VLCElem *table; + int table_size, table_allocated; +} VLC; +#define VLC_INIT_USE_STATIC 1 +#define VLC_INIT_INPUT_LE 4 +#define VLC_INIT_OUTPUT_LE 8 +#define VLC_INIT_LE (VLC_INIT_INPUT_LE | VLC_INIT_OUTPUT_LE) +/* Only the single-level, byte-wide lens/codes, LE, static form bink.c uses. */ +int ffbink_vlc_init(VLC *vlc, int nb_bits, int nb_codes, const uint8_t *lens, int lens_wrap, + int lens_size, const uint8_t *codes, int codes_wrap, int codes_size, int flags); +#define vlc_init ffbink_vlc_init + +/* ---- libavcodec/get_bits.h (little-endian reader only) ---------------------------------- */ +typedef struct GetBitContext { + const uint8_t *buffer; + int index; + int size_in_bits; + int size_in_bits_plus8; +} GetBitContext; + +static inline int init_get_bits(GetBitContext *s, const uint8_t *buffer, int bit_size) +{ + int ret = 0; + if (bit_size >= INT_MAX - 64 * 8 || bit_size < 0 || !buffer) { + bit_size = 0; + buffer = NULL; + ret = AVERROR_INVALIDDATA; + } + s->buffer = buffer; + s->size_in_bits = bit_size; + s->size_in_bits_plus8 = bit_size + 8; + s->index = 0; + return ret; +} + +static inline int init_get_bits8(GetBitContext *s, const uint8_t *buffer, int byte_size) +{ + if (byte_size > INT_MAX / 8 || byte_size < 0) + byte_size = -1; + return init_get_bits(s, buffer, byte_size * 8); +} + +static inline int get_bits_count(const GetBitContext *s) { return s->index; } +static inline int get_bits_left(const GetBitContext *s) { return s->size_in_bits - s->index; } + +/* Peeks up to 32 bits LSB-first. The caller's padding keeps the 8-byte load inside the buffer. */ +static inline unsigned ffbink_show(const GetBitContext *s, int n) +{ + if (n <= 0 || !s->buffer) + return 0; + const uint64_t v = ffbink_rl64(s->buffer + (s->index >> 3)) >> (s->index & 7); + return (unsigned)(v & ((n >= 32) ? 0xFFFFFFFFull : ((1ull << n) - 1))); +} + +static inline void skip_bits_long(GetBitContext *s, int n) +{ + /* the checked reader clamps the index to [0, size_in_bits + 8] */ + long long idx = (long long)s->index + n; + if (idx < 0) idx = 0; + if (idx > s->size_in_bits_plus8) idx = s->size_in_bits_plus8; + s->index = (int)idx; +} +static inline void skip_bits(GetBitContext *s, int n) { skip_bits_long(s, n); } + +static inline unsigned get_bits(GetBitContext *s, int n) +{ + const unsigned v = ffbink_show(s, n); + skip_bits_long(s, n); + return v; +} +static inline unsigned get_bits_long(GetBitContext *s, int n) { return get_bits(s, n); } +static inline unsigned get_bits1(GetBitContext *s) { return get_bits(s, 1); } +static inline unsigned show_bits(const GetBitContext *s, int n) { return ffbink_show(s, n); } + +static inline int get_vlc2(GetBitContext *s, const VLCElem *table, int bits, int max_depth) +{ + (void)max_depth; /* bink.c's trees are single-level */ + const VLCElem e = table[ffbink_show(s, bits)]; + skip_bits_long(s, e.len); + return e.sym; +} + +/* ---- libavutil/tx.h --------------------------------------------------------------------- */ +enum AVTXType { AV_TX_FLOAT_RDFT = 6, AV_TX_FLOAT_DCT = 9 }; +typedef struct AVTXContext AVTXContext; +typedef void (*av_tx_fn)(AVTXContext *s, void *out, void *in, ptrdiff_t stride); +typedef struct AVComplexFloat { float re, im; } AVComplexFloat; +int av_tx_init(AVTXContext **ctx, av_tx_fn *tx, enum AVTXType type, int inv, int len, + const void *scale, uint64_t flags); +void av_tx_uninit(AVTXContext **ctx); + +#endif /* FFBINK_SHIM_H */ diff --git a/Code/BF2/External/ffmpeg-bink/shim/get_bits.h b/Code/BF2/External/ffmpeg-bink/shim/get_bits.h new file mode 100644 index 000000000..2748e70c7 --- /dev/null +++ b/Code/BF2/External/ffmpeg-bink/shim/get_bits.h @@ -0,0 +1,2 @@ +/* [CHOSEN, not recovered] OpenBF2 forwarder: see ffbink_shim.h. */ +#include "ffbink_shim.h" diff --git a/Code/BF2/External/ffmpeg-bink/shim/hpeldsp.h b/Code/BF2/External/ffmpeg-bink/shim/hpeldsp.h new file mode 100644 index 000000000..2748e70c7 --- /dev/null +++ b/Code/BF2/External/ffmpeg-bink/shim/hpeldsp.h @@ -0,0 +1,2 @@ +/* [CHOSEN, not recovered] OpenBF2 forwarder: see ffbink_shim.h. */ +#include "ffbink_shim.h" diff --git a/Code/BF2/External/ffmpeg-bink/shim/internal.h b/Code/BF2/External/ffmpeg-bink/shim/internal.h new file mode 100644 index 000000000..2748e70c7 --- /dev/null +++ b/Code/BF2/External/ffmpeg-bink/shim/internal.h @@ -0,0 +1,2 @@ +/* [CHOSEN, not recovered] OpenBF2 forwarder: see ffbink_shim.h. */ +#include "ffbink_shim.h" diff --git a/Code/BF2/External/ffmpeg-bink/shim/libavutil/attributes.h b/Code/BF2/External/ffmpeg-bink/shim/libavutil/attributes.h new file mode 100644 index 000000000..4b60835bc --- /dev/null +++ b/Code/BF2/External/ffmpeg-bink/shim/libavutil/attributes.h @@ -0,0 +1,2 @@ +/* [CHOSEN, not recovered] OpenBF2 forwarder: see ffbink_shim.h. */ +#include "../ffbink_shim.h" diff --git a/Code/BF2/External/ffmpeg-bink/shim/libavutil/channel_layout.h b/Code/BF2/External/ffmpeg-bink/shim/libavutil/channel_layout.h new file mode 100644 index 000000000..4b60835bc --- /dev/null +++ b/Code/BF2/External/ffmpeg-bink/shim/libavutil/channel_layout.h @@ -0,0 +1,2 @@ +/* [CHOSEN, not recovered] OpenBF2 forwarder: see ffbink_shim.h. */ +#include "../ffbink_shim.h" diff --git a/Code/BF2/External/ffmpeg-bink/shim/libavutil/emms.h b/Code/BF2/External/ffmpeg-bink/shim/libavutil/emms.h new file mode 100644 index 000000000..4b60835bc --- /dev/null +++ b/Code/BF2/External/ffmpeg-bink/shim/libavutil/emms.h @@ -0,0 +1,2 @@ +/* [CHOSEN, not recovered] OpenBF2 forwarder: see ffbink_shim.h. */ +#include "../ffbink_shim.h" diff --git a/Code/BF2/External/ffmpeg-bink/shim/libavutil/imgutils.h b/Code/BF2/External/ffmpeg-bink/shim/libavutil/imgutils.h new file mode 100644 index 000000000..4b60835bc --- /dev/null +++ b/Code/BF2/External/ffmpeg-bink/shim/libavutil/imgutils.h @@ -0,0 +1,2 @@ +/* [CHOSEN, not recovered] OpenBF2 forwarder: see ffbink_shim.h. */ +#include "../ffbink_shim.h" diff --git a/Code/BF2/External/ffmpeg-bink/shim/libavutil/intfloat.h b/Code/BF2/External/ffmpeg-bink/shim/libavutil/intfloat.h new file mode 100644 index 000000000..4b60835bc --- /dev/null +++ b/Code/BF2/External/ffmpeg-bink/shim/libavutil/intfloat.h @@ -0,0 +1,2 @@ +/* [CHOSEN, not recovered] OpenBF2 forwarder: see ffbink_shim.h. */ +#include "../ffbink_shim.h" diff --git a/Code/BF2/External/ffmpeg-bink/shim/libavutil/mem.h b/Code/BF2/External/ffmpeg-bink/shim/libavutil/mem.h new file mode 100644 index 000000000..4b60835bc --- /dev/null +++ b/Code/BF2/External/ffmpeg-bink/shim/libavutil/mem.h @@ -0,0 +1,2 @@ +/* [CHOSEN, not recovered] OpenBF2 forwarder: see ffbink_shim.h. */ +#include "../ffbink_shim.h" diff --git a/Code/BF2/External/ffmpeg-bink/shim/libavutil/mem_internal.h b/Code/BF2/External/ffmpeg-bink/shim/libavutil/mem_internal.h new file mode 100644 index 000000000..4b60835bc --- /dev/null +++ b/Code/BF2/External/ffmpeg-bink/shim/libavutil/mem_internal.h @@ -0,0 +1,2 @@ +/* [CHOSEN, not recovered] OpenBF2 forwarder: see ffbink_shim.h. */ +#include "../ffbink_shim.h" diff --git a/Code/BF2/External/ffmpeg-bink/shim/libavutil/thread.h b/Code/BF2/External/ffmpeg-bink/shim/libavutil/thread.h new file mode 100644 index 000000000..4b60835bc --- /dev/null +++ b/Code/BF2/External/ffmpeg-bink/shim/libavutil/thread.h @@ -0,0 +1,2 @@ +/* [CHOSEN, not recovered] OpenBF2 forwarder: see ffbink_shim.h. */ +#include "../ffbink_shim.h" diff --git a/Code/BF2/External/ffmpeg-bink/shim/libavutil/tx.h b/Code/BF2/External/ffmpeg-bink/shim/libavutil/tx.h new file mode 100644 index 000000000..4b60835bc --- /dev/null +++ b/Code/BF2/External/ffmpeg-bink/shim/libavutil/tx.h @@ -0,0 +1,2 @@ +/* [CHOSEN, not recovered] OpenBF2 forwarder: see ffbink_shim.h. */ +#include "../ffbink_shim.h" diff --git a/Code/BF2/External/gameswf/GAMESWF_DIVERGENCES.md b/Code/BF2/External/gameswf/GAMESWF_DIVERGENCES.md index d6a8cb10d..2ffb80efa 100644 --- a/Code/BF2/External/gameswf/GAMESWF_DIVERGENCES.md +++ b/Code/BF2/External/gameswf/GAMESWF_DIVERGENCES.md @@ -1,62 +1,33 @@ -# gameswf and base local adaptations - -The upstream base is Thatcher Ulrich's tu-testbed snapshot of 27 February 2006. -The vendored libraries are adapted for BF2's menu movies and the SwiffPlayer -host. Keep upstream notices intact; the source files retain their original -licensing declarations. - -Local changes use two searchable source markers: - -- `[BUILD-FIX SwiffPlayer: ...]` for build integration changes. -- `[DICE-MOD SwiffPlayer: ...]` for menu-runtime and host compatibility changes. - -Run `rg "BUILD-FIX SwiffPlayer|DICE-MOD SwiffPlayer" Code/BF2/External` -from the repository root to locate the affected code. - -## Integration - -Keep `gameswf/` and `base/` as siblings, with their parent directory on the -include path. `compatibility_include.h` supplies the integrator configuration. -The engine-specific wrapper lives in `SwiffPlayer/`. - -Build the image with -[swiffplayer.cmd](../../../Build/swiffplayer.cmd). A dedicated-server build does -not validate this library. The wrapper uses typed gameswf calls and maps renderer -operations by function; raw vtable positions are not portable between library -versions. - -## Adaptation map - -| Area | Main files | Behavior to preserve | -| --- | --- | --- | -| Build configuration | `gameswf_shape.cpp`, build manifest | Disable the optional OpenGL shape-debug path. Exclude the inactive XMLSocket translation unit, whose unconditional SDL include is unavailable in this build. | -| Host access and images | `gameswf.h`, `gameswf_action.*`, `gameswf_impl.*`, `gameswf_render.*` | Global-object access, named bitmap exports, external bitmap creation policy, texture loading, and background-color readback. Exported names must own their string storage. | -| ActionScript objects | `gameswf_action.*`, `gameswf_string.cpp` | Properties and prototype accessors, class registration, object literals, inheritance, constructor dispatch, `this`/`super`, array/string methods, enumeration, and object conversion. | -| VM state | `gameswf_action.*` | Tolerant stack underflow, timeline variables, caller register banks, and function register save/restore. | -| Timers | `gameswf_timers.*`, `gameswf_impl.cpp` | Global timer registration, object-method callbacks, and millisecond intervals. | -| Sprite lifetime and timelines | `gameswf_impl.*`, `gameswf_dlist.*` | Deferred removals, dead-clip access, construct/load ordering, label and numeric goto behavior, timeline state changes, and action-queue draining before execution. | -| Drawing and bounds | `gameswf_shape.*`, `gameswf_styles.h`, `gameswf_impl.*` | Runtime shapes, image clips, owned runtime definitions, local clip extents, and scale-aware width/height updates. | -| Text and localization | `gameswf_text.cpp`, `gameswf_font.h`, `gameswf_string.cpp`, render interfaces | Renderer-managed text lines, editing/focus/selection, independent narrow and wide values, and font-leading terms for caret and auto-height. | -| Mouse input | `gameswf_impl.*`, `gameswf_button.*`, `gameswf_text.cpp` | Per-character dispatch, capture across press/release, handler names, and capture release when a containing sprite is hidden. | - -## Constraints for changes - -Function calls borrow the caller's register bank while name lookup keeps the -defining environment. Function2 calls save and restore registers 0 through 9; -higher registers remain shared. Keep this distinction when changing nested calls -or constructor dispatch. - -Text fields keep narrow and wide values independently. A wide-only string can -provide display text while converting to an empty narrow string. Keep the -renderer selection result as a Boolean; equal or uninitialized selection -endpoints do not replace it. - -Numeric gotos are queued; label gotos apply immediately. Action queues remove a -buffer before executing it so reentrant navigation cannot execute the same -buffer twice. Runtime-created definitions must remain alive through deferred -display-list removal. - -This integration is incomplete. Examples include solid-color fallback for -gradient fills, unsupported custom array-sort comparators, and remaining -timeline/lifetime differences documented at their source boundaries. Preserve -those markers and validate the affected menu flows when changing these areas. +# gameswf platform choices + +The gameswf/base sources began with Thatcher Ulrich's tu-testbed snapshot of +27 February 2006. S3 supplies recovered bodies where recorded in the ledger; +S4 removes the unused upstream +features and retires the old DICE-MOD patch annotations. Existing upstream +copyright and licensing notices remain in the retained files. + +This file lists only retained platform adaptations and owner decisions. Each is +`[CHOSEN, not recovered]`. Retail instructions and their addresses belong beside +the implementation and in the [track ledger](../../../../docs/tracks/swf/ledger.csv). +The S4 work recorded removals, evidence, +validation and unfinished recovery. Retirement of a patch annotation does not +certify a whole function or remove a named frontier. + +| Choice | Contract and limits | +| --- | --- | +| Native rebuilt ABI ([issue #7](https://github.com/B2BF/OpenBF2/issues/7)) | Native C++ interfaces, member-based containers, strings, virtual bases, type-adjustment helpers and allocation replace the VC7.1 x86 representation. Shared register storage and separately owned character arguments adapt fixed/embedded retail storage. Strong function/class/prototype links and function-property object adapters remain explicit in source. These choices apply to rebuilt images on every host; they are not retail object-layout claims. | +| Native value/host adapters (issue #7) | Existing NULLTYPE-to-tag-zero mapping, tolerant operand storage, the checked movie cast where retail adjusts a found script object to its character unchecked (StartDrag 0x10092E68), native receiver/environment adapters, definition-bounds providers and text extent/character conversions remain where their callers still need them. Text CRT conversion keeps the recovered C-locale byte widening; the non-C POSIX locale/wchar_t adapter retains native conversion and error semantics. | +| Native widths and build integration (issue #7 and the owner-requested macOS port) | Hash entries retain the functor's full `size_t` hash; object/function identity strings retain full pointers. x86-64/AArch64 are known little-endian targets. Supported C++ libraries supply math declarations; obsolete OS X math macros stay disabled. `tu_util` comparison helpers and qualified `::hash` friends avoid standard-library collisions. Debug breaks use the supported compiler primitive. Standard-library headers precede compatibility macros. | +| Native movie lifetime and collector (issue #7; owner decision 2026-11-09) | Reference counting and the script-object registry stay active. Last-player teardown clears interval records, script graph edges and library class bindings, releases the player's references and resets action globals. With another live player, global teardown is skipped and logged. Movie libraries stay cached. The five collector rows remain `chosen`: `0x10077700`, `0x1008D950`, `0x1007B320`, `0x1008A160` and the GC portion of `0x1007AED0`. No direct-deletion sweep is activated or claimed recovered, and the collector-list link that retail performs when the VM or action_init creates an object (common slot +0xC, e.g. NewObject 0x10093714, NewMethod 0x100944FF, action_init 0x10091030) is not performed. | +| Renderer and input platform seams (owner-requested macOS port; issue #7) | Metal/Cocoa replace Win32 rendering/input services at their host boundaries. Generated RGBA/A8 pixels are retained and uploaded once per live handler registry, with weak cached-definition registry links and fresh RGBA copies because RendDX9 swaps channels in place. Handler/descriptor destruction releases uploads. The native asynchronous key callback supplies the platform input state; the retail Enter predicate itself is shared code. | +| Expat substitute (owner decision) | Official Expat R_1_95_0 and C callback adapters stand in for the unidentified retail parser revision. The vendored files remain unchanged. Unicode classification and parser internals can differ; see [provenance](../expat/README.md). The DICE XML wrapper is separately recovered; a passing XML fixture does not certify parser equivalence. | +| Numeric and CRT edges (owner decision 2026-11-09) | The 13 designated numeric/CRT rows retain standard math and native CRT behavior without x87 emulation. Last-bit results, inherited precision/rounding, nonfinite/range behavior, formatting, locale and errors can differ. Other native x87/storage adapters retain their documented limits; ordinary-input agreement is not an equivalence claim. | +| Hash-capacity mode binding (owner decision) | Native policy selects the normal client 24-bit/nearest mode. The integer capacity results for that mode are recovered, including early large transitions, no minimum-16 clamp and the exponent-32 masked shift. Nonpositive requests retain the native clear adapter until each old dangling-word/new null-word template variant is attributed. Entry widths/ownership remain native. Alternate inherited FP modes are not emulated. See `Code/BF2/External/base/hash_capacity.h`. | +| Unattributed inventory (owner decision 2026-11-09) | All 104 category-(d) rows retain `unattributed, no recorded reference` as their final inventory disposition. This neither recovers a body nor proves runtime unreachability. No source owner, signature or callable implementation is invented. | + +Build the client movie image through CMake or +[swiffplayer.cmd](../../../Build/swiffplayer.cmd); the manifests list the same +remaining gameswf/base sources. The standalone 2006 SDL Makefiles and tools are +removed. Keep `gameswf/` and `base/` as siblings and their parent on the include +path. `compatibility_include.h` remains the integrator configuration and heap +seam. A dedicated-server build alone does not validate this library. diff --git a/Code/BF2/External/gameswf/Makefile b/Code/BF2/External/gameswf/Makefile deleted file mode 100644 index 14b0b8479..000000000 --- a/Code/BF2/External/gameswf/Makefile +++ /dev/null @@ -1,275 +0,0 @@ -# Makefile -- Thatcher Ulrich 2003 - -# This source code has been donated to the Public Domain. Do -# whatever you want with it. - -# Makefile for gameswf library & tests. - -TOP = .. -include $(TOP)/config - -INCLUDE_PATHS := $(ENGINE_INCLUDE) $(ZLIB_INCLUDE) $(SDL_MIXER_INCLUDE) $(LIBMAD_INCLUDE) # $(XML2_INCLUDE) - -CFLAGS := $(CFLAGS) $(INCLUDE_PATHS) $(CC_DEBUG_FLAGS) -LDFLAGS := $(SDL_LDFLAGS) $(LIB_DEBUG_FLAGS) $(LDFLAGS) - -LIB_OUT = $(LIB_PRE)gameswf.$(LIB_EXT) -EXE_OUT = gameswf_test_ogl$(EXE_EXT) -PARSER_OUT = gameswf_parser$(EXE_EXT) -PROCESSOR_OUT = gameswf_processor$(EXE_EXT) - -LIBS := $(LIB_OUT) $(BASE_LIB) $(LIBS) $(JPEGLIB) $(ZLIB) $(SDL_MIXER_LIB) $(LIBMAD_LIB) # $(XML2LIB) - -all: base_lib $(LIB_OUT) $(EXE_OUT) $(PARSER_OUT) $(PROCESSOR_OUT) - - -LIB_OBJS = \ - gameswf_action.$(OBJ_EXT) \ - gameswf_button.$(OBJ_EXT) \ - gameswf_dlist.$(OBJ_EXT) \ - gameswf_font.$(OBJ_EXT) \ - gameswf_fontlib.$(OBJ_EXT) \ - gameswf_impl.$(OBJ_EXT) \ - gameswf_log.$(OBJ_EXT) \ - gameswf_morph2.$(OBJ_EXT) \ - gameswf_movie.$(OBJ_EXT) \ - gameswf_render.$(OBJ_EXT) \ - gameswf_shape.$(OBJ_EXT) \ - gameswf_sound.$(OBJ_EXT) \ - gameswf_stream.$(OBJ_EXT) \ - gameswf_string.$(OBJ_EXT) \ - gameswf_styles.$(OBJ_EXT) \ - gameswf_tesselate.$(OBJ_EXT) \ - gameswf_text.$(OBJ_EXT) \ - gameswf_textformat.$(OBJ_EXT) \ - gameswf_timers.$(OBJ_EXT) \ - gameswf_types.$(OBJ_EXT) \ - gameswf_xml.$(OBJ_EXT) \ - gameswf_xmlsocket.$(OBJ_EXT) - -TEST_PROGRAM_OBJS = \ - gameswf_test_ogl.$(OBJ_EXT) \ - gameswf_render_handler_ogl.$(OBJ_EXT) \ - gameswf_sound_handler_sdl.$(OBJ_EXT) \ - gameswf_sound_handler_mp3.$(OBJ_EXT) - -PARSER_OBJS = \ - gameswf_parser.$(OBJ_EXT) - -PROCESSOR_OBJS = \ - gameswf_processor.$(OBJ_EXT) - -OBJS = $(LIB_OBJS) $(TEST_PROGRAM_OBJS) $(PARSER_OBJS) $(PROCESSOR_OBJS) - -gameswf_impl.$(OBJ_EXT): gameswf.h gameswf_impl.h gameswf_types.h - -$(LIB_OUT): $(LIB_OBJS) - $(AR) $(LIB_OUT_FLAG)$@ $^ - - -$(EXE_OUT): $(TEST_PROGRAM_OBJS) $(LIB_OUT) $(BASE_LIB) - $(CC) -o $@ $(TEST_PROGRAM_OBJS) $(LIBS) $(LDFLAGS) - - -$(PARSER_OUT): $(PARSER_OBJS) $(LIB_OUT) $(BASE_LIB) - $(CC) -o $@ $(PARSER_OBJS) $(LIBS) $(LDFLAGS) - - -$(PROCESSOR_OUT): $(PROCESSOR_OBJS) $(LIB_OUT) $(BASE_LIB) - $(CC) -o $@ $(PROCESSOR_OBJS) $(LIBS) $(LDFLAGS) - - -clean: - make -C $(TOP)/base clean - -rm $(OBJS) $(LIB_OUT) $(EXE_OUT) $(PARSER_OUT) $(PROCESSOR_OUT) - -depend: - makedepend -Y -I.. -f Makefile *.cpp - -fresh: clean all -# DO NOT DELETE - -gameswf_action.o: gameswf_action.h gameswf.h gameswf_types.h -gameswf_action.o: ../gameswf/gameswf.h ../base/tu_types.h ../base/tu_config.h -gameswf_action.o: ../compatibility_include.h ../base/dlmalloc.h -gameswf_action.o: ../base/container.h ../base/utility.h ../base/tu_math.h -gameswf_action.o: ../base/tu_swap.h gameswf_impl.h gameswf_log.h -gameswf_action.o: ../base/smart_ptr.h gameswf_stream.h ../base/tu_random.h -gameswf_action.o: gameswf_string.h gameswf_movie.h gameswf_timers.h -gameswf_action.o: ../base/tu_timer.h gameswf_textformat.h gameswf_sound.h -gameswf_button.o: gameswf_button.h gameswf_impl.h gameswf.h gameswf_action.h -gameswf_button.o: gameswf_types.h ../gameswf/gameswf.h ../base/tu_types.h -gameswf_button.o: ../base/tu_config.h ../compatibility_include.h -gameswf_button.o: ../base/dlmalloc.h ../base/container.h ../base/utility.h -gameswf_button.o: ../base/tu_math.h ../base/tu_swap.h gameswf_log.h -gameswf_button.o: ../base/smart_ptr.h gameswf_sound.h gameswf_render.h -gameswf_button.o: ../base/image.h gameswf_stream.h -gameswf_dlist.o: gameswf_dlist.h ../base/container.h ../base/tu_config.h -gameswf_dlist.o: ../compatibility_include.h ../base/dlmalloc.h -gameswf_dlist.o: ../base/utility.h ../base/tu_math.h ../base/tu_types.h -gameswf_dlist.o: ../base/tu_swap.h gameswf_types.h ../gameswf/gameswf.h -gameswf_dlist.o: gameswf_impl.h gameswf.h gameswf_action.h gameswf_log.h -gameswf_dlist.o: ../base/smart_ptr.h gameswf_render.h ../base/image.h -gameswf_font.o: gameswf_font.h ../base/container.h ../base/tu_config.h -gameswf_font.o: ../compatibility_include.h ../base/dlmalloc.h -gameswf_font.o: ../base/utility.h ../base/tu_math.h ../base/tu_types.h -gameswf_font.o: ../base/tu_swap.h gameswf.h gameswf_types.h -gameswf_font.o: ../gameswf/gameswf.h gameswf_impl.h gameswf_action.h -gameswf_font.o: gameswf_log.h ../base/smart_ptr.h gameswf_stream.h -gameswf_font.o: gameswf_shape.h gameswf_styles.h ../base/tu_file.h -gameswf_fontlib.o: ../base/container.h ../base/tu_config.h -gameswf_fontlib.o: ../compatibility_include.h ../base/dlmalloc.h -gameswf_fontlib.o: ../base/utility.h ../base/tu_math.h ../base/tu_types.h -gameswf_fontlib.o: ../base/tu_swap.h ../base/tu_file.h gameswf.h -gameswf_fontlib.o: gameswf_font.h gameswf_types.h ../gameswf/gameswf.h -gameswf_fontlib.o: gameswf_impl.h gameswf_action.h gameswf_log.h -gameswf_fontlib.o: ../base/smart_ptr.h gameswf_render.h ../base/image.h -gameswf_fontlib.o: gameswf_shape.h gameswf_styles.h gameswf_tesselate.h -gameswf_impl.o: ../base/tu_file.h ../base/tu_config.h -gameswf_impl.o: ../compatibility_include.h ../base/dlmalloc.h -gameswf_impl.o: ../base/tu_types.h ../base/tu_swap.h ../base/utility.h -gameswf_impl.o: ../base/tu_math.h gameswf_action.h gameswf.h gameswf_types.h -gameswf_impl.o: ../gameswf/gameswf.h ../base/container.h gameswf_button.h -gameswf_impl.o: gameswf_impl.h gameswf_log.h ../base/smart_ptr.h -gameswf_impl.o: gameswf_sound.h gameswf_font.h gameswf_fontlib.h -gameswf_impl.o: gameswf_morph2.h gameswf_shape.h gameswf_styles.h -gameswf_impl.o: gameswf_render.h ../base/image.h gameswf_stream.h -gameswf_impl.o: gameswf_dlist.h gameswf_timers.h ../base/tu_timer.h -gameswf_impl.o: ../base/jpeg.h ../base/zlib_adapter.h -gameswf_log.o: gameswf_log.h gameswf.h -gameswf_morph2.o: gameswf_morph2.h gameswf_shape.h gameswf_styles.h -gameswf_morph2.o: gameswf_impl.h gameswf.h gameswf_action.h gameswf_types.h -gameswf_morph2.o: ../gameswf/gameswf.h ../base/tu_types.h ../base/tu_config.h -gameswf_morph2.o: ../compatibility_include.h ../base/dlmalloc.h -gameswf_morph2.o: ../base/container.h ../base/utility.h ../base/tu_math.h -gameswf_morph2.o: ../base/tu_swap.h gameswf_log.h ../base/smart_ptr.h -gameswf_morph2.o: gameswf_stream.h -gameswf_morph.o: gameswf_morph.h gameswf_shape.h gameswf_styles.h -gameswf_morph.o: gameswf_impl.h gameswf.h gameswf_action.h gameswf_types.h -gameswf_morph.o: ../gameswf/gameswf.h ../base/tu_types.h ../base/tu_config.h -gameswf_morph.o: ../compatibility_include.h ../base/dlmalloc.h -gameswf_morph.o: ../base/container.h ../base/utility.h ../base/tu_math.h -gameswf_morph.o: ../base/tu_swap.h gameswf_log.h ../base/smart_ptr.h -gameswf_morph.o: gameswf_tesselate.h gameswf_stream.h ../base/tu_file.h -gameswf_morph.o: gameswf_render.h ../base/image.h -gameswf_movie.o: gameswf_movie.h gameswf_log.h gameswf_action.h gameswf.h -gameswf_movie.o: gameswf_types.h ../gameswf/gameswf.h ../base/tu_types.h -gameswf_movie.o: ../base/tu_config.h ../compatibility_include.h -gameswf_movie.o: ../base/dlmalloc.h ../base/container.h ../base/utility.h -gameswf_movie.o: ../base/tu_math.h ../base/tu_swap.h gameswf_impl.h -gameswf_movie.o: ../base/smart_ptr.h ../base/tu_file.h ../base/image.h -gameswf_movie.o: gameswf_render.h -gameswf_parser.o: ../base/tu_file.h ../base/tu_config.h -gameswf_parser.o: ../compatibility_include.h ../base/dlmalloc.h -gameswf_parser.o: ../base/tu_types.h ../base/tu_swap.h ../base/zlib_adapter.h -gameswf_parser.o: ../base/image.h ../base/jpeg.h gameswf_stream.h -gameswf_parser.o: ../base/container.h ../base/utility.h ../base/tu_math.h -gameswf_parser.o: gameswf_log.h gameswf.h -gameswf_processor.o: ../base/tu_file.h ../base/tu_config.h -gameswf_processor.o: ../compatibility_include.h ../base/dlmalloc.h -gameswf_processor.o: ../base/tu_types.h ../base/tu_swap.h ../base/container.h -gameswf_processor.o: ../base/utility.h ../base/tu_math.h gameswf.h -gameswf_render.o: gameswf_render.h gameswf_types.h ../gameswf/gameswf.h -gameswf_render.o: ../base/tu_types.h ../base/tu_config.h -gameswf_render.o: ../compatibility_include.h ../base/dlmalloc.h gameswf.h -gameswf_render.o: ../base/image.h gameswf_log.h -gameswf_render_handler_ogl.o: gameswf.h gameswf_types.h ../gameswf/gameswf.h -gameswf_render_handler_ogl.o: ../base/tu_types.h ../base/tu_config.h -gameswf_render_handler_ogl.o: ../compatibility_include.h ../base/dlmalloc.h -gameswf_render_handler_ogl.o: ../base/image.h ../base/ogl.h -gameswf_render_handler_ogl.o: ../base/tu_opengl_includes.h ../base/utility.h -gameswf_render_handler_ogl.o: ../base/tu_math.h ../base/tu_swap.h -gameswf_shape.o: gameswf_shape.h gameswf_styles.h gameswf_impl.h gameswf.h -gameswf_shape.o: gameswf_action.h gameswf_types.h ../gameswf/gameswf.h -gameswf_shape.o: ../base/tu_types.h ../base/tu_config.h -gameswf_shape.o: ../compatibility_include.h ../base/dlmalloc.h -gameswf_shape.o: ../base/container.h ../base/utility.h ../base/tu_math.h -gameswf_shape.o: ../base/tu_swap.h gameswf_log.h ../base/smart_ptr.h -gameswf_shape.o: gameswf_render.h ../base/image.h gameswf_stream.h -gameswf_shape.o: gameswf_tesselate.h ../base/tu_file.h ../base/ogl.h -gameswf_shape.o: ../base/tu_opengl_includes.h -gameswf_sound.o: gameswf_sound.h gameswf_impl.h gameswf.h gameswf_action.h -gameswf_sound.o: gameswf_types.h ../gameswf/gameswf.h ../base/tu_types.h -gameswf_sound.o: ../base/tu_config.h ../compatibility_include.h -gameswf_sound.o: ../base/dlmalloc.h ../base/container.h ../base/utility.h -gameswf_sound.o: ../base/tu_math.h ../base/tu_swap.h gameswf_log.h -gameswf_sound.o: ../base/smart_ptr.h gameswf_stream.h -gameswf_sound_handler_sdl.o: ../gameswf/gameswf.h ../base/container.h -gameswf_sound_handler_sdl.o: ../base/tu_config.h ../compatibility_include.h -gameswf_sound_handler_sdl.o: ../base/dlmalloc.h ../base/utility.h -gameswf_sound_handler_sdl.o: ../base/tu_math.h ../base/tu_types.h -gameswf_sound_handler_sdl.o: ../base/tu_swap.h ../gameswf/gameswf_log.h -gameswf_sound_handler_sdl.o: ../gameswf/gameswf_types.h -gameswf_stream.o: gameswf_stream.h ../base/container.h ../base/tu_config.h -gameswf_stream.o: ../compatibility_include.h ../base/dlmalloc.h -gameswf_stream.o: ../base/utility.h ../base/tu_math.h ../base/tu_types.h -gameswf_stream.o: ../base/tu_swap.h gameswf_log.h gameswf_types.h -gameswf_stream.o: ../gameswf/gameswf.h ../base/tu_file.h -gameswf_string.o: gameswf_string.h gameswf_log.h gameswf_action.h gameswf.h -gameswf_string.o: gameswf_types.h ../gameswf/gameswf.h ../base/tu_types.h -gameswf_string.o: ../base/tu_config.h ../compatibility_include.h -gameswf_string.o: ../base/dlmalloc.h ../base/container.h ../base/utility.h -gameswf_string.o: ../base/tu_math.h ../base/tu_swap.h gameswf_impl.h -gameswf_string.o: ../base/smart_ptr.h -gameswf_styles.o: gameswf_styles.h gameswf_impl.h gameswf.h gameswf_action.h -gameswf_styles.o: gameswf_types.h ../gameswf/gameswf.h ../base/tu_types.h -gameswf_styles.o: ../base/tu_config.h ../compatibility_include.h -gameswf_styles.o: ../base/dlmalloc.h ../base/container.h ../base/utility.h -gameswf_styles.o: ../base/tu_math.h ../base/tu_swap.h gameswf_log.h -gameswf_styles.o: ../base/smart_ptr.h gameswf_render.h ../base/image.h -gameswf_styles.o: gameswf_stream.h -gameswf_tesselate.o: gameswf_tesselate.h gameswf.h gameswf_types.h -gameswf_tesselate.o: ../gameswf/gameswf.h ../base/tu_types.h -gameswf_tesselate.o: ../base/tu_config.h ../compatibility_include.h -gameswf_tesselate.o: ../base/dlmalloc.h ../base/utility.h ../base/tu_math.h -gameswf_tesselate.o: ../base/tu_swap.h ../base/container.h -gameswf_test_ogl.o: gameswf.h ../base/ogl.h ../base/tu_config.h -gameswf_test_ogl.o: ../compatibility_include.h ../base/dlmalloc.h -gameswf_test_ogl.o: ../base/tu_opengl_includes.h ../base/utility.h -gameswf_test_ogl.o: ../base/tu_math.h ../base/tu_types.h ../base/tu_swap.h -gameswf_test_ogl.o: ../base/container.h ../base/tu_file.h -gameswf_text.o: ../base/utf8.h ../base/tu_types.h ../base/tu_config.h -gameswf_text.o: ../compatibility_include.h ../base/dlmalloc.h -gameswf_text.o: ../base/utility.h ../base/tu_math.h ../base/tu_swap.h -gameswf_text.o: gameswf_impl.h gameswf.h gameswf_action.h gameswf_types.h -gameswf_text.o: ../gameswf/gameswf.h ../base/container.h gameswf_log.h -gameswf_text.o: ../base/smart_ptr.h gameswf_shape.h gameswf_styles.h -gameswf_text.o: gameswf_stream.h gameswf_font.h gameswf_fontlib.h -gameswf_text.o: gameswf_render.h ../base/image.h gameswf_textformat.h -gameswf_textformat.o: gameswf_log.h gameswf_textformat.h gameswf_action.h -gameswf_textformat.o: gameswf.h gameswf_types.h ../gameswf/gameswf.h -gameswf_textformat.o: ../base/tu_types.h ../base/tu_config.h -gameswf_textformat.o: ../compatibility_include.h ../base/dlmalloc.h -gameswf_textformat.o: ../base/container.h ../base/utility.h ../base/tu_math.h -gameswf_textformat.o: ../base/tu_swap.h gameswf_impl.h ../base/smart_ptr.h -gameswf_timers.o: gameswf_log.h gameswf_action.h gameswf.h gameswf_types.h -gameswf_timers.o: ../gameswf/gameswf.h ../base/tu_types.h ../base/tu_config.h -gameswf_timers.o: ../compatibility_include.h ../base/dlmalloc.h -gameswf_timers.o: ../base/container.h ../base/utility.h ../base/tu_math.h -gameswf_timers.o: ../base/tu_swap.h gameswf_impl.h ../base/smart_ptr.h -gameswf_timers.o: gameswf_timers.h ../base/tu_timer.h gameswf_xml.h -gameswf_timers.o: gameswf_xmlsocket.h -gameswf_tools.o: ../base/tu_file.h ../base/tu_config.h -gameswf_tools.o: ../compatibility_include.h ../base/dlmalloc.h -gameswf_tools.o: ../base/tu_types.h ../base/tu_swap.h ../base/utility.h -gameswf_tools.o: ../base/tu_math.h ../base/zlib_adapter.h gameswf.h -gameswf_tools.o: gameswf_log.h gameswf_stream.h ../base/container.h -gameswf_tools.o: gameswf_types.h ../gameswf/gameswf.h -gameswf_types.o: gameswf_types.h ../gameswf/gameswf.h ../base/tu_types.h -gameswf_types.o: ../base/tu_config.h ../compatibility_include.h -gameswf_types.o: ../base/dlmalloc.h gameswf_log.h gameswf_stream.h -gameswf_types.o: ../base/container.h ../base/utility.h ../base/tu_math.h -gameswf_types.o: ../base/tu_swap.h gameswf_render.h gameswf.h ../base/image.h -gameswf_xml.o: gameswf_log.h gameswf_action.h gameswf.h gameswf_types.h -gameswf_xml.o: ../gameswf/gameswf.h ../base/tu_types.h ../base/tu_config.h -gameswf_xml.o: ../compatibility_include.h ../base/dlmalloc.h -gameswf_xml.o: ../base/container.h ../base/utility.h ../base/tu_math.h -gameswf_xml.o: ../base/tu_swap.h gameswf_impl.h ../base/smart_ptr.h -gameswf_xml.o: gameswf_string.h -gameswf_xmlsocket.o: gameswf_log.h gameswf_xml.h gameswf_action.h gameswf.h -gameswf_xmlsocket.o: gameswf_types.h ../gameswf/gameswf.h ../base/tu_types.h -gameswf_xmlsocket.o: ../base/tu_config.h ../compatibility_include.h -gameswf_xmlsocket.o: ../base/dlmalloc.h ../base/container.h ../base/utility.h -gameswf_xmlsocket.o: ../base/tu_math.h ../base/tu_swap.h gameswf_impl.h -gameswf_xmlsocket.o: ../base/smart_ptr.h gameswf_xmlsocket.h gameswf_timers.h -gameswf_xmlsocket.o: ../base/tu_timer.h diff --git a/Code/BF2/External/gameswf/SwiffPlayer/OfflineConnectPopup.h b/Code/BF2/External/gameswf/SwiffPlayer/OfflineConnectPopup.h new file mode 100644 index 000000000..e6648d7b4 --- /dev/null +++ b/Code/BF2/External/gameswf/SwiffPlayer/OfflineConnectPopup.h @@ -0,0 +1,73 @@ +// [CHOSEN, not recovered] Owner-approved offline LAN dialog policy. +// Shared by every rebuilt client platform. +#ifndef BF2_SWIFFPLAYER_OFFLINECONNECTPOPUP_H +#define BF2_SWIFFPLAYER_OFFLINECONNECTPOPUP_H + +#include +#include +#include "../gameswf_impl.h" + +namespace dice { namespace hfe { namespace ui { + +// Only an explicit, visible main-menu request from an offline profile is eligible. +// A null popupName represents an absent or non-string selection. +inline bool shouldOpenOfflineConnectPopup(bool liveMainMenu, double loginStatus, + const char* popupName, bool visible) +{ + return liveMainMenu && loginStatus == 1.0 && visible && + popupName && std::strcmp(popupName, "connecttoip") == 0; +} + +// Missing menu content declines quietly (owner decision, 2026-11-13). This matches what +// retail does offline. The authored popups.flush gate (sprite 457, +0x1AF..+0x1C2) exits +// while the cached loginStatus is below 2, and the native side never navigates, so AVM1 +// leaves the selection in place and no dialog appears. A decline is logged once per +// process; it is not a stop. +inline bool declineOfflineConnectPopup(const char* reason) +{ + static bool logged = false; + if (!logged) + { + logged = true; + std::fprintf(stderr, "[SwiffPlayer] offline connecttoip declined: %s\n", reason); + std::fflush(stderr); + } + return false; +} + +// Complete the authored request after movie actions and before display. The movie +// keeps its offline status, callbacks, flushObject, selectedPopup and close flow. +// Returns true only when this pass actually selects the dialog frame; any missing piece of +// the authored content answers false, with no dialog. +inline bool openOfflineConnectPopup(gameswf::movie* root, bool liveMainMenu) +{ + if (!liveMainMenu || !root) return false; + gameswf::as_value status, selection; + root->get_member("loginStatus", &status); + root->get_member("selectedPopup", &selection); + const char* name = selection.get_type() == gameswf::as_value::STRING + ? selection.to_string() : nullptr; + if (!shouldOpenOfflineConnectPopup(true, + status.get_type() == gameswf::as_value::NUMBER ? status.to_number() : 0.0, + name, true)) return false; + + gameswf::as_value popup, visible; + if (!root->get_member("popups", &popup) || !popup.to_object() || !popup.to_object()->to_movie()) + return declineOfflineConnectPopup("main-menu popups clip absent"); + gameswf::movie* clip = popup.to_object()->to_movie(); + if (!clip->get_member("_visible", &visible) || !visible.to_bool()) return false; + + int frame = -1; + auto* definition = static_cast(clip->get_movie_definition()); + if (!definition || !definition->get_labeled_frame("connecttoip", &frame)) + return declineOfflineConnectPopup("popups connecttoip frame absent"); + // Do not restart the dialog or its editable fields on subsequent updates. + if (clip->get_current_frame() == frame) return false; + if (!clip->goto_labeled_frame("connecttoip")) + return declineOfflineConnectPopup("popups connecttoip navigation failed"); + clip->set_play_state(gameswf::movie_interface::STOP); + return true; +} + +} } } +#endif diff --git a/Code/BF2/External/gameswf/SwiffPlayer/SwiffBitmapCache.h b/Code/BF2/External/gameswf/SwiffPlayer/SwiffBitmapCache.h new file mode 100644 index 000000000..f07dcb691 --- /dev/null +++ b/Code/BF2/External/gameswf/SwiffPlayer/SwiffBitmapCache.h @@ -0,0 +1,104 @@ +// [CHOSEN, not recovered] Cached native movie images retain CPU pixels and bind +// separately in each player's texture registry. Native cache lifetime follows +// issue #7. No retail layout is exposed. +#ifndef BF2_SWIFF_BITMAP_CACHE_H +#define BF2_SWIFF_BITMAP_CACHE_H + +#include +#include +#include +#include + +#include "../../../Menu/ISwiffRender.h" +#include "base/image.h" +#include "gameswf/gameswf.h" + +namespace dice { namespace hfe { namespace ui { + +class SwiffBitmapRegistry; + +// The saved pixels precede the renderer's destructive RGBA channel conversion. +struct SwiffBitmapPixels : gameswf::bitmap_info::render_resource +{ + enum Format { Alpha, Rgba }; + Format format; + int width, height, pitch; + std::vector bytes; + std::vector > registries; + + SwiffBitmapPixels(Format f, int w, int h, int p, const unsigned char* data) + : format(f), width(w), height(h), pitch(p), bytes(data, data + p * h) {} + ~SwiffBitmapPixels() override; +}; + +// A player owns this lease; cached descriptors keep only weak references to it. +// Retaining the renderer keeps its registry valid through menu-disable ordering. +class SwiffBitmapRegistry +{ + ISwiffRender* m_renderer; + std::map m_handles; + +public: + explicit SwiffBitmapRegistry(ISwiffRender* renderer) : m_renderer(renderer) + { + m_renderer->addRef(); + } + SwiffBitmapRegistry(const SwiffBitmapRegistry&) = delete; + SwiffBitmapRegistry& operator=(const SwiffBitmapRegistry&) = delete; + ~SwiffBitmapRegistry() + { + for (const auto& entry : m_handles) + m_renderer->releaseTexture(entry.second); + m_renderer->release(); + } + + void erase(const SwiffBitmapPixels* pixels) + { + const auto found = m_handles.find(pixels); + if (found != m_handles.end()) + { + m_renderer->releaseTexture(found->second); + m_handles.erase(found); + } + } + + // A failed upload remains -1 for this lease, just like the retail descriptor. + static void bind(gameswf::bitmap_info* bitmap, + const std::shared_ptr& registry) + { + if (!bitmap || !bitmap->m_render_resource) + return; + SwiffBitmapPixels& pixels = static_cast(*bitmap->m_render_resource); + auto found = registry->m_handles.find(&pixels); + if (found == registry->m_handles.end()) + { + int handle; + if (pixels.format == SwiffBitmapPixels::Alpha) + handle = registry->m_renderer->uploadAlpha(pixels.width, pixels.height, pixels.bytes.data()); + else + { + // RendDX9's RGBA upload swaps R/B in place. Every registry must + // receive the original RGBA bytes, including after a reload. + std::vector upload(pixels.bytes); + image::image_base image(upload.data(), pixels.width, pixels.height, pixels.pitch); + handle = registry->m_renderer->uploadRgba(reinterpret_cast(&image)); + } + found = registry->m_handles.emplace(&pixels, handle).first; + auto& owners = pixels.registries; + owners.erase(std::remove_if(owners.begin(), owners.end(), + [](const std::weak_ptr& owner) { return owner.expired(); }), owners.end()); + owners.push_back(registry); + } + bitmap->m_texture_id = static_cast(found->second); + } +}; + +inline SwiffBitmapPixels::~SwiffBitmapPixels() +{ + for (const auto& owner : registries) + if (const auto registry = owner.lock()) + registry->erase(this); +} + +} } } +#endif diff --git a/Code/BF2/External/gameswf/SwiffPlayer/SwiffCrashLog.cpp b/Code/BF2/External/gameswf/SwiffPlayer/SwiffCrashLog.cpp index 2678ca924..6f02ff89c 100644 --- a/Code/BF2/External/gameswf/SwiffPlayer/SwiffCrashLog.cpp +++ b/Code/BF2/External/gameswf/SwiffPlayer/SwiffCrashLog.cpp @@ -3,13 +3,28 @@ // Frame-chain tracing requires frame pointers; stack scans can include stale return addresses. // [RETIRE-WHEN: RW-89] Remove with the other SwiffPlayer tracers. -#define WIN32_LEAN_AND_MEAN -#define NOMINMAX -#include #include #include #include "../../../../RendDX9Abi/Frontier.h" +#if !defined(_WIN32) +// [CHOSEN, not recovered] Native POSIX ports: the logger is built on Windows' vectored exception +// handling and x86 CONTEXT registers, and is not available. Asking for it reports that once, so a +// tester does not wait for a crash log that cannot come; nothing is installed. +void swiffCrashLogInstall() +{ + static bool reported = false; + const char* e = getenv("BF2_SWIFFPLAYER_CRASHLOG"); + if (reported || !e || !*e || *e == '0') return; + reported = true; + ::renddx9abi::logf("[crash] BF2_SWIFFPLAYER_CRASHLOG is set, but the first-fault logger exists " + "only on Windows; nothing installed"); +} +#else +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include + namespace { bool moduleOf(const void* addr, char* name, size_t nameCap, unsigned* rva) @@ -62,9 +77,11 @@ LONG WINAPI crashHandler(EXCEPTION_POINTERS* ep) (void*)ep->ExceptionRecord->ExceptionInformation[1]); const CONTEXT* c = ep->ContextRecord; +#if defined(_M_IX86) ::renddx9abi::logf("[crash] eax=%08X ebx=%08X ecx=%08X edx=%08X esi=%08X edi=%08X ebp=%08X esp=%08X", (unsigned)c->Eax, (unsigned)c->Ebx, (unsigned)c->Ecx, (unsigned)c->Edx, (unsigned)c->Esi, (unsigned)c->Edi, (unsigned)c->Ebp, (unsigned)c->Esp); + const uintptr_t stackPointer = (uintptr_t)c->Esp; // EBP chain. const void* const* frame = (const void* const*)c->Ebp; @@ -80,13 +97,23 @@ LONG WINAPI crashHandler(EXCEPTION_POINTERS* ep) if (next <= frame) break; frame = next; } +#else + // [CHOSEN, not recovered] x64: the 64-bit registers; x64 code keeps no frame-pointer chain, so + // only the return-address scan below runs. + ::renddx9abi::logf("[crash] rax=%016llX rbx=%016llX rcx=%016llX rdx=%016llX rsi=%016llX rdi=%016llX", + (unsigned long long)c->Rax, (unsigned long long)c->Rbx, (unsigned long long)c->Rcx, + (unsigned long long)c->Rdx, (unsigned long long)c->Rsi, (unsigned long long)c->Rdi); + ::renddx9abi::logf("[crash] rbp=%016llX rsp=%016llX rip=%016llX", + (unsigned long long)c->Rbp, (unsigned long long)c->Rsp, (unsigned long long)c->Rip); + const uintptr_t stackPointer = (uintptr_t)c->Rsp; +#endif // Return-address scan (frame-pointer independent; includes stale entries). - const void* const* sp = (const void* const*)((uintptr_t)c->Esp & ~(uintptr_t)3); + const void* const* sp = (const void* const*)(stackPointer & ~(uintptr_t)(sizeof(void*) - 1)); int hits = 0; for (int i = 0; i < 4096 && hits < 80; ++i, ++sp) { - if (!readable(sp, 4)) break; + if (!readable(sp, sizeof(void*))) break; const void* v = *sp; if (!moduleOf(v, mod, sizeof mod, &rva)) continue; if (_strnicmp(mod, "SwiffPlayer", 11) != 0 && _strnicmp(mod, "RendDX9", 7) != 0 @@ -125,3 +152,4 @@ void swiffCrashLogInstall() ::atexit(&swiffCrashLogUninstall); ::renddx9abi::logf("[crash] logger installed (BF2_SWIFFPLAYER_CRASHLOG)"); } +#endif // _WIN32 diff --git a/Code/BF2/External/gameswf/SwiffPlayer/SwiffNativesRecovered.inl b/Code/BF2/External/gameswf/SwiffPlayer/SwiffNativesRecovered.inl new file mode 100644 index 000000000..03b1f563a --- /dev/null +++ b/Code/BF2/External/gameswf/SwiffPlayer/SwiffNativesRecovered.inl @@ -0,0 +1,4611 @@ +// =================================================================================================== +// c-swiff-natives: the retail natives the port had not registered. +// SwiffPlayer.dll 1.50 (base 0x10000000); every body below was read instruction by instruction with +// objdump. Calling convention of the shipped callbacks: ecx = the result as_value, [ebp+8] = the +// argument vector, [ebp+0x10] = first_arg; argument n is element first_arg - n (fn.arg(n) here); the +// int3 after the bounds test is the debug assert and has no counterpart. Result writes build a +// temporary as_value (type 1 string, 2 number, 3 Boolean) and assign it through sub_10009920. +// =================================================================================================== + +// ---- dice.bf2.Profile -------------------------------------------------------------------------- + +// sub_1005D050 "getMinimumAge": the shipped body is a bare `ret 0Ch`. +// The AS result is left untouched (undefined). +void as_profile_getMinimumAge(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_getMinimumAge"); +} + +// sub_1005D080 "clearComparePlayer": player host +0x218 setPendingRecord(0, "") with a constructed +// empty string (0x100D7835). No AS result. +void as_profile_clearComparePlayer(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_clearComparePlayer"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const std::string empty(""); + h->setPendingRecord(0, empty); // +0x218 +} + +// sub_1005D110 "setNamePrefix": GlobalSettings by name first, then arg 0 to_string (sub_1008D0F0) +// into a std::string, copied by value into GlobalSettings +0x2C setNamePrefix. No AS result. +void as_profile_setNamePrefix(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_setNamePrefix"); + IBase* gs = classManager->getSingleton(renddx9abi::HostString("GlobalSettings")); + const std::string prefix(fn.arg(0).to_string()); + static_cast(gs)->setNamePrefix(prefix); // +0x2C +} + +// sub_1005D190 "setSelectedAge": arg 0 to_number (sub_1008B570) and the value popped (fstp st0). +// Nothing is stored and no AS result is written. +void as_profile_setSelectedAge(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_setSelectedAge"); + (void) fn.arg(0).to_number(); +} + +// sub_1005D220 "setUseAdvancedServerBrowser": GeneralSettings by name, then arg 0 to_bool +// (sub_1008B6B0), GeneralSettings +0xA4. No AS result. +void as_profile_setUseAdvancedServerBrowser(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_setUseAdvancedServerBrowser"); + IBase* gs = classManager->getSingleton(renddx9abi::HostString("GeneralSettings")); + const bool value = fn.arg(0).to_bool(); + static_cast(gs)->setUseAdvancedServerBrowser(value); // +0xA4 +} + +// sub_1005D350 "setComparePlayer": the host first, then ProfileManager +0x44 isLoggedIn. Logged out: +// host +0x244 handleProfileTransition("connection to profile server lost") and return. Otherwise +// id = (int) arg 0 (fistp, truncating control word); a zero id does nothing. A non-zero id takes +// arg 1 to_string, host +0x218 setPendingRecord(id, name), host +0x220 setSelectedPlayerId(id). +void as_profile_setComparePlayer(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_setComparePlayer"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + IBase* pm = classManager->getSingleton(renddx9abi::HostString("ProfileManager")); + if (!static_cast(pm)->isLoggedIn()) // +0x44 + { + h->handleProfileTransition(std::string("connection to profile server lost")); // +0x244 + return; + } + const int id = bf2x87::toIntTruncate(fn.arg(0).to_number()); + if (id == 0) + return; + const std::string name(fn.arg(1).to_string()); + h->setPendingRecord(id, name); // +0x218 + h->setSelectedPlayerId(id); // +0x220 +} + +// sub_1005D5B0 "getSelectedAge": the constant 13.0 (0x100DDEC8) as a number. +void as_profile_getSelectedAge(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_getSelectedAge"); + fn.result->set_double(13.0); +} + +// sub_1005D800 "deleteCurrentProfile": inside the registry SwiffHost's busy cursor (sub_10013520); +// player host, LocalProfileManager, ProfileManager. Logged out (+0x44): host +0x244 with "connection +// to profile server lost" and Boolean false. Logged in: ProfileManager +0x30 getProfileId(out) (its +// Boolean ignored) is compared with host +0x21C getSelectedPlayerId; a mismatch posts message +// {type 1, code 0, "you can only delete your active profile"} through host +0x1E4 and answers false. +// A match calls ProfileManager +0x38 deleteProfile: false answers false; true reads +0x34 +// getUniqueNick(out) into an empty string, LocalProfileManager +0x68 setGamespyNick(it), +0x40 +// saveCurrentProfile, and answers true. +void as_profile_deleteCurrentProfile(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_deleteCurrentProfile"); + BusyHost busy = busyOpen(); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + IBase* lpm = classManager->getSingleton(renddx9abi::HostString("LocalProfileManager")); + IBase* pmBase = classManager->getSingleton(renddx9abi::HostString("ProfileManager")); + IProfileManager* pm = static_cast(pmBase); + if (!pm->isLoggedIn()) // +0x44 + { + h->handleProfileTransition(std::string("connection to profile server lost")); // +0x244 + fn.result->set_bool(false); + busyClose(busy); + return; + } + int profileId; // uninitialised in the shipped frame as well + (void) pm->getProfileId(profileId); // +0x30 + if (h->getSelectedPlayerId() != profileId) // +0x21C + { + const std::string text("you can only delete your active profile"); + SwiffHostMessage message; + message.type = 1; + message.code = 0; + message.text = text; + (void) h->postMessage(message); // +0x1E4 + fn.result->set_bool(false); + busyClose(busy); + return; + } + if (!pm->deleteProfile()) // +0x38 + { + fn.result->set_bool(false); + busyClose(busy); + return; + } + std::string nick; + (void) pm->getUniqueNick(nick); // +0x34 + static_cast(lpm)->setGamespyNick(nick); // +0x68 + (void) static_cast(lpm)->saveCurrentProfile(); // +0x40 + fn.result->set_bool(true); + busyClose(busy); +} + +// sub_1005DA70 "newGamespyProfile": inside the busy cursor; player host, LocalProfileManager, +// ProfileManager. Logged out: host +0x244 "connection to profile server lost", Boolean false. +// Logged in: nick = arg 0, country = arg 1 (both to_string); ProfileManager +0x20 +// createProfile(nick, country). Refused: +0x4C requestNickSuggestions(nick), Boolean false. +// Created: LocalProfileManager +0x68 setGamespyNick(nick), +0x40 saveCurrentProfile, Boolean true. +void as_profile_newGamespyProfile(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_newGamespyProfile"); + BusyHost busy = busyOpen(); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + IBase* lpm = classManager->getSingleton(renddx9abi::HostString("LocalProfileManager")); + IProfileManager* pm = static_cast( + classManager->getSingleton(renddx9abi::HostString("ProfileManager"))); + if (!pm->isLoggedIn()) // +0x44 + { + h->handleProfileTransition(std::string("connection to profile server lost")); // +0x244 + fn.result->set_bool(false); + busyClose(busy); + return; + } + const std::string nick(fn.arg(0).to_string()); + const std::string country(fn.arg(1).to_string()); + if (!pm->createProfile(nick, country)) // +0x20 + { + (void) pm->requestNickSuggestions(nick); // +0x4C + fn.result->set_bool(false); + busyClose(busy); + return; + } + static_cast(lpm)->setGamespyNick(nick); // +0x68 + (void) static_cast(lpm)->saveCurrentProfile(); // +0x40 + fn.result->set_bool(true); + busyClose(busy); +} + +// sub_1005DCE0 "deleteLocalProfile": inside the busy cursor; the player host is fetched and +// discarded; LocalProfileManager; index = (int) arg 0; Boolean of +0x28 deleteProfile(index). +void as_profile_deleteLocalProfile(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_deleteLocalProfile"); + BusyHost busy = busyOpen(); + (void) g_swiffPlayerInstance->getSwiffHost(); + IBase* lpm = classManager->getSingleton(renddx9abi::HostString("LocalProfileManager")); + const int index = bf2x87::toIntTruncate(fn.arg(0).to_number()); + const bool deleted = static_cast(lpm)->deleteProfile(index); // +0x28 + fn.result->set_bool(deleted); + busyClose(busy); +} + +// sub_1005DDD0 "getUseAdvancedServerBrowser": Boolean of GeneralSettings +0xA0. +void as_profile_getUseAdvancedServerBrowser(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_getUseAdvancedServerBrowser"); + IBase* gs = classManager->getSingleton(renddx9abi::HostString("GeneralSettings")); + fn.result->set_bool(static_cast(gs)->getUseAdvancedServerBrowser()); // +0xA0 +} + +// sub_1005E100 "getStatPlayer": host +0x21C getSelectedPlayerId as a number. +void as_profile_getStatPlayer(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_getStatPlayer"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + fn.result->set_double(static_cast(h->getSelectedPlayerId())); // +0x21C +} + +// sub_1005E2A0 "searchPlayer" / sub_10060D80 "searchUniquePlayer": inside the busy cursor; the +// player host, arg 0 to_string. An empty name or one whose first byte is ' ' fails. Otherwise host +// +0x3C getSearchForPlayer() +0x10 search(name, unique, false). searchPlayer answers that Boolean +// (false on the early refusal). searchUniquePlayer answers a number: -1.0 (0x100D8868) on a refusal +// or an empty result, else the first row's profile id from a second getSearchForPlayer() +0x18 +// getPlayers(rows) (its Boolean ignored). +static bool searchNameUsable(const std::string& name) +{ + return !name.empty() && name.c_str()[0] != ' '; +} +void as_profile_searchPlayer(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_searchPlayer"); + BusyHost busy = busyOpen(); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const std::string name(fn.arg(0).to_string()); + if (searchNameUsable(name) + && static_cast(h->getSearchForPlayer())->search(name, false, false)) // +0x3C, +0x10 + fn.result->set_bool(true); + else + fn.result->set_bool(false); + busyClose(busy); +} +void as_profile_searchUniquePlayer(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_searchUniquePlayer"); + BusyHost busy = busyOpen(); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const std::string name(fn.arg(0).to_string()); + if (searchNameUsable(name) + && static_cast(h->getSearchForPlayer())->search(name, true, false)) // +0x3C, +0x10 + { + std::vector rows; + (void) static_cast(h->getSearchForPlayer())->getPlayers(rows); // +0x3C, +0x18 + if (rows.empty()) + fn.result->set_double(-1.0); + else + fn.result->set_double(static_cast(rows[0].profileId)); + } + else + fn.result->set_double(-1.0); + busyClose(busy); +} + +// sub_1005F4A0 "getSprint": team = (int) arg 0, kit = (int) arg 1 (both converted before the lookup), +// MenuTeamManager by name, +0x30 getTeam(team), kits[kit] (no bounds test, 108-byte rows, +0x58): +// the number 1.0f (0x100D7EA0) - sprintStaminaDissipationFactor, evaluated on the x87 stack. +void as_profile_getSprint(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_getSprint"); + const int team = bf2x87::toIntTruncate(fn.arg(0).to_number()); + const int kit = bf2x87::toIntTruncate(fn.arg(1).to_number()); + IMenuTeamManager* tm = static_cast( + classManager->getSingleton(renddx9abi::HostString("MenuTeamManager"))); + MenuTeam* row = tm->getTeam(static_cast(team)); // +0x30 + const double factor = static_cast(row->kits[kit].sprintStaminaDissipationFactor); + fn.result->set_double(1.0 - factor); +} + +// sub_1005FD90 "getNumOnlineProfiles" / sub_1005FEE0 "getNumOfflineProfiles": LocalProfileManager by +// name; absent: the number 0. Present: +0x48 getLocalProfiles(rows, true) (Boolean ignored) and the +// count of rows whose gamespyNick (+0x54) is != "" (online, operator!=) or == "" (offline, operator==). +static void countLocalProfiles(const gameswf::fn_call& fn, bool online) +{ + IBase* lpm = classManager->getSingleton(renddx9abi::HostString("LocalProfileManager")); + if (!lpm) + { + fn.result->set_double(0.0); + return; + } + std::vector rows; + (void) static_cast(lpm)->getLocalProfiles(rows, true); // +0x48 + int count = 0; + for (unsigned int i = 0; i < rows.size(); ++i) + if (online ? (rows[i].gamespyNick != "") : (rows[i].gamespyNick == "")) + ++count; + fn.result->set_double(static_cast(count)); +} +void as_profile_getNumOnlineProfiles(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_getNumOnlineProfiles"); + countLocalProfiles(fn, true); +} +void as_profile_getNumOfflineProfiles(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_getNumOfflineProfiles"); + countLocalProfiles(fn, false); +} + +// ---- dice.bf2.Multiplay ------------------------------------------------------------------------ + +// The player host's current browser list: host +0x134 getServerListKind() (a temporary that dies +// after the call) handed to +0x7C getServerList. Every Multiplay row below that touches the +// browser starts this way. +static IServerBrowser* currentServerList(ISwiffHost* h) +{ + return h->getServerList(h->getServerListKind()); // +0x134, +0x7C +} + +// sub_10050B70 "refreshBrowser": the current list; when present, +0x2C requeueRecords (Boolean +// ignored). No AS result. +void as_multiplay_refreshBrowser(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_refreshBrowser"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + IServerBrowser* list = currentServerList(h); + if (list) + (void) list->requeueRecords(); // +0x2C +} + +// sub_10050C10 "stopDownloadDemo": host +0x44 getDemoLibrary() +0x3C cancelDownload (Boolean +// ignored). No AS result. +void as_multiplay_stopDownloadDemo(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_stopDownloadDemo"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + (void) static_cast(h->getDemoLibrary())->cancelDownload(); // +0x44, +0x3C +} + +// sub_10050C80 "clearHistory": inside the busy cursor, the player host (discarded) and +// GeneralSettings +0x154 clearServerHistory. No AS result. +void as_multiplay_clearHistory(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_clearHistory"); + BusyHost busy = busyOpen(); + (void) g_swiffPlayerInstance->getSwiffHost(); + IBase* gs = classManager->getSingleton(renddx9abi::HostString("GeneralSettings")); + static_cast(gs)->clearServerHistory(); // +0x154 + busyClose(busy); +} + +// sub_10051480 "setHighestPing": the current list; when present, (int) arg 0 into +0x5C setMaxPing. +// An absent list leaves the argument unread. No AS result. +void as_multiplay_setHighestPing(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_setHighestPing"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + IServerBrowser* list = currentServerList(h); + if (list) + list->setMaxPing(bf2x87::toIntTruncate(fn.arg(0).to_number())); // +0x5C +} + +// sub_100519C0 "setFilter": the player host is fetched and discarded; arg 0 to_string is assigned to +// the DLL-global free-text clause (unk_100F8810). No AS result. +void as_multiplay_setFilter(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_setFilter"); + (void) g_swiffPlayerInstance->getSwiffHost(); + const std::string text(fn.arg(0).to_string()); + s_textFilter = text; +} + +// sub_10051A20 "sort": inside the busy cursor; the player host; key = arg 0 to_string, ascending = +// arg 1 to_bool, mode = (int) arg 2, all converted before the list is fetched; then the current +// list's +0x38 sort(key, ascending, mode), no null test. No AS result. +void as_multiplay_sort(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_sort"); + BusyHost busy = busyOpen(); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const std::string key(fn.arg(0).to_string()); + const bool ascending = fn.arg(1).to_bool(); + const int mode = bf2x87::toIntTruncate(fn.arg(2).to_number()); + currentServerList(h)->sort(key, ascending, mode); // +0x38 + busyClose(busy); +} + +// sub_10051F00 "deleteDemo": the player host first, then (int) arg 0, host +0x44 getDemoLibrary() +// +0x20 removeEntry(index) (Boolean ignored). No AS result. +void as_multiplay_deleteDemo(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_deleteDemo"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const int index = bf2x87::toIntTruncate(fn.arg(0).to_number()); + (void) static_cast(h->getDemoLibrary())->removeEntry(static_cast(index)); // +0x20 +} + +// sub_100523E0 "hasDemoDownloadFailed": Boolean of host +0x44 getDemoLibrary() +0x4C. +void as_multiplay_hasDemoDownloadFailed(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_hasDemoDownloadFailed"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + fn.result->set_bool(static_cast(h->getDemoLibrary())->hasDownloadFailed()); // +0x4C +} + +// sub_10052450 "getScrollFadeSpeed": host +0x314 (the credits scroller's fade speed) as a number. +void as_multiplay_getScrollFadeSpeed(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_getScrollFadeSpeed"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + fn.result->set_double(static_cast(h->getIntF08())); // +0x314 +} + +// sub_100526A0 "isServerBrowserBusy": Boolean of the current list's +0x1C isBrowsing, no null test. +void as_multiplay_isServerBrowserBusy(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_isServerBrowserBusy"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const bool busy = currentServerList(h)->isBrowsing(); // +0x1C + fn.result->set_bool(busy); +} + +// sub_100528A0 "validateIp": arg 0 to_string, Boolean of host +0x250 isDottedQuad. +void as_multiplay_validateIp(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_validateIp"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const std::string address(fn.arg(0).to_string()); + fn.result->set_bool(h->isDottedQuad(address)); // +0x250 +} + +// sub_10052AF0 "playNow": the player host; both in-game server-info keys cleared (sub_100136B0: +// unk_100F7040 = "", dword_100F3240 = 0; sub_100626D0: unk_100F8B14 = "", dword_100F88CC = 0); host +// +0xB8 isGameRunning(&running) with running pre-set false. A running game returns with the AS +// result untouched. Otherwise, inside the busy cursor, the Boolean of host +0x16C playNow. +void as_multiplay_playNow(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_playNow"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + s_ingameAddressA = ""; s_ingamePortA = 0; + s_ingameAddressB = ""; s_ingamePortB = 0; + bool running = false; + (void) h->isGameRunning(&running); // +0xB8 + if (running) + return; + BusyHost busy = busyOpen(); + fn.result->set_bool(h->playNow()); // +0x16C + busyClose(busy); +} + +// "%s %d" (0x100DD398) of a GeneralSettings row's address and query port, the key the favourites +// and history rows are matched by, case-insensitively (sub_10003870: _stricmp(row, key) == 0). +static bool serverEntryMatches(const GeneralServerEntry* e, const std::string& key) +{ + const std::string rowKey = swiffFormatString("%s %d", e->address.c_str(), e->queryPort); + return ::_stricmp(rowKey.c_str(), key.c_str()) == 0; +} +// The message the favourites rows post: type 1, code 0, the text assigned into a default record. +static void postMenuMessage(ISwiffHost* h, const char* literal) +{ + const std::string text(literal); + SwiffHostMessage message; + message.type = 1; + message.code = 0; + message.text = text; + (void) h->postMessage(message); // +0x1E4 +} + +// sub_10052C80 "addFavourite": the player host, GeneralSettings, then the busy cursor; name = arg 0, +// address = arg 1 (to_string), port = (int) arg 2; key = "%s %d"(address, port). Host +0x250 +// isDottedQuad(address) false posts "Not a valid ip" and answers false. Otherwise a favourite whose +// key matches posts "Server already in favorites" and answers false; none: GeneralSettings +0x11C +// addFavouriteServer(address, port, name) and true. +void as_multiplay_addFavourite(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_addFavourite"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + IGeneralSettings* gs = static_cast( + classManager->getSingleton(renddx9abi::HostString("GeneralSettings"))); + BusyHost busy = busyOpen(); + const std::string name(fn.arg(0).to_string()); + const std::string address(fn.arg(1).to_string()); + const int port = bf2x87::toIntTruncate(fn.arg(2).to_number()); + const std::string key = swiffFormatString("%s %d", address.c_str(), port); + if (!h->isDottedQuad(address)) // +0x250 + { + postMenuMessage(h, "Not a valid ip"); + fn.result->set_bool(false); + busyClose(busy); + return; + } + for (unsigned int i = 0; i < static_cast(gs->getNumFavouriteServers()); ++i) // +0x120 + { + if (serverEntryMatches(gs->getFavouriteServer(i), key)) // +0x124 + { + postMenuMessage(h, "Server already in favorites"); + fn.result->set_bool(false); + busyClose(busy); + return; + } + } + gs->addFavouriteServer(address, port, name); // +0x11C + fn.result->set_bool(true); + busyClose(busy); +} + +// sub_10053060 "removeFavourite": the player host (discarded), GeneralSettings, then the busy cursor; +// key = arg 0. The first favourite whose "%s %d" key matches is removed through +0x12C +// removeFavouriteServerEntry(index) (Boolean ignored) and the answer is true; no match answers false. +void as_multiplay_removeFavourite(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_removeFavourite"); + (void) g_swiffPlayerInstance->getSwiffHost(); + IGeneralSettings* gs = static_cast( + classManager->getSingleton(renddx9abi::HostString("GeneralSettings"))); + BusyHost busy = busyOpen(); + const std::string key(fn.arg(0).to_string()); + for (unsigned int i = 0; i < static_cast(gs->getNumFavouriteServers()); ++i) // +0x120 + { + if (serverEntryMatches(gs->getFavouriteServer(i), key)) // +0x124 + { + (void) gs->removeFavouriteServerEntry(i); // +0x12C + fn.result->set_bool(true); + busyClose(busy); + return; + } + } + fn.result->set_bool(false); + busyClose(busy); +} + +// sub_10053230 "addHistoryToFavourites": the busy cursor, the player host, GeneralSettings; key = +// arg 0. No history row (+0x13C count, +0x140 row) with that key answers false. For the first match, +// a favourite with the same key posts "Server allready in favourites" [sic] and answers false; +// otherwise +0x11C addFavouriteServer(row address, row query port, row name) and true. +void as_multiplay_addHistoryToFavourites(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_addHistoryToFavourites"); + BusyHost busy = busyOpen(); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + IGeneralSettings* gs = static_cast( + classManager->getSingleton(renddx9abi::HostString("GeneralSettings"))); + const std::string key(fn.arg(0).to_string()); + GeneralServerEntry* row = 0; + for (unsigned int i = 0; i < static_cast(gs->getServerHistoryCount()); ++i) // +0x13C + { + GeneralServerEntry* e = gs->getServerHistory(i); // +0x140 + if (serverEntryMatches(e, key)) { row = e; break; } + } + if (!row) + { + fn.result->set_bool(false); + busyClose(busy); + return; + } + for (unsigned int i = 0; i < static_cast(gs->getNumFavouriteServers()); ++i) // +0x120 + { + if (serverEntryMatches(gs->getFavouriteServer(i), key)) // +0x124 + { + postMenuMessage(h, "Server allready in favourites"); + fn.result->set_bool(false); + busyClose(busy); + return; + } + } + gs->addFavouriteServer(row->address, row->queryPort, row->name); // +0x11C + fn.result->set_bool(true); + busyClose(busy); +} + +// sub_10053540 "removeHistory": the busy cursor, the player host (discarded), GeneralSettings; key = +// arg 0. The first history row whose key matches is removed through +0x148 removeServerHistoryEntry +// (Boolean ignored), answering true; no match answers false. +void as_multiplay_removeHistory(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_removeHistory"); + BusyHost busy = busyOpen(); + (void) g_swiffPlayerInstance->getSwiffHost(); + IGeneralSettings* gs = static_cast( + classManager->getSingleton(renddx9abi::HostString("GeneralSettings"))); + const std::string key(fn.arg(0).to_string()); + for (unsigned int i = 0; i < static_cast(gs->getServerHistoryCount()); ++i) // +0x13C + { + if (serverEntryMatches(gs->getServerHistory(i), key)) // +0x140 + { + (void) gs->removeServerHistoryEntry(i); // +0x148 + fn.result->set_bool(true); + busyClose(busy); + return; + } + } + fn.result->set_bool(false); + busyClose(busy); +} + +// sub_10053E50 "getNumDemoBookmarks": LocalProfileManager +0xA8 as a number (fild, signed). +void as_multiplay_getNumDemoBookmarks(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_getNumDemoBookmarks"); + IBase* lpm = classManager->getSingleton(renddx9abi::HostString("LocalProfileManager")); + const int count = static_cast(static_cast(lpm)->getNumDemoBookmarks()); // +0xA8 + fn.result->set_double(static_cast(count)); +} + +// sub_10053EE0 "isDownloadingDemo": Boolean of host +0x44 getDemoLibrary() +0x28 isDownloading. +void as_multiplay_isDownloadingDemo(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_isDownloadingDemo"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + fn.result->set_bool(static_cast(h->getDemoLibrary())->isDownloading()); // +0x28 +} + +// sub_10053F50 "getDownloadingHostname" / sub_10053FE0 "getDownloadingUrl" / sub_10054070 +// "getDownloadingDate": host +0x44 getDemoLibrary() +0x2C / +0x30 / +0x34 (const std::string&), +// copied, published as a string. +void as_multiplay_getDownloadingHostname(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_getDownloadingHostname"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const std::string value(static_cast(h->getDemoLibrary())->getDownloadName()); // +0x2C + fn.result->set_tu_string(tu_string(value.c_str())); +} +void as_multiplay_getDownloadingUrl(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_getDownloadingUrl"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const std::string value(static_cast(h->getDemoLibrary())->getDownloadUrl()); // +0x30 + fn.result->set_tu_string(tu_string(value.c_str())); +} +void as_multiplay_getDownloadingDate(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_getDownloadingDate"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const std::string value(static_cast(h->getDemoLibrary())->getDownloadDescription()); // +0x34 + fn.result->set_tu_string(tu_string(value.c_str())); +} + +// sub_10054100 "getDownloadingProgress": host +0x44 getDemoLibrary() +0x38 (float) as a number. +void as_multiplay_getDownloadingProgress(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_getDownloadingProgress"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + fn.result->set_double(static_cast( + static_cast(h->getDemoLibrary())->getDownloadProgress())); // +0x38 +} + +// sub_10054160 "downloadDemo": the busy cursor, the player host, LocalProfileManager; index = +// (int) arg 0; +0xAC getDemoBookmark(index). None answers false. Otherwise host +0x44 +// getDemoLibrary() +0x48 setPendingBookmark(index), then (fetched again) +0x14 download(bookmark +// +0x00, +0x38, +0x54) with its Boolean ignored, and the answer is true. +void as_multiplay_downloadDemo(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_downloadDemo"); + BusyHost busy = busyOpen(); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + IBase* lpm = classManager->getSingleton(renddx9abi::HostString("LocalProfileManager")); + const int index = bf2x87::toIntTruncate(fn.arg(0).to_number()); + LocalDemoBookmark* bookmark = + static_cast(lpm)->getDemoBookmark(static_cast(index)); // +0xAC + if (!bookmark) + { + fn.result->set_bool(false); + busyClose(busy); + return; + } + static_cast(h->getDemoLibrary())->setPendingBookmark(index); // +0x48 + (void) static_cast(h->getDemoLibrary())->download( + bookmark->field00, bookmark->field38, bookmark->field54); // +0x14 + fn.result->set_bool(true); + busyClose(busy); +} + +// sub_100542C0 "deleteDemoBookmark": the busy cursor, the player host (discarded), +// LocalProfileManager; Boolean of +0xB0 removeDemoBookmark((int) arg 0). +void as_multiplay_deleteDemoBookmark(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_deleteDemoBookmark"); + BusyHost busy = busyOpen(); + (void) g_swiffPlayerInstance->getSwiffHost(); + IBase* lpm = classManager->getSingleton(renddx9abi::HostString("LocalProfileManager")); + const int index = bf2x87::toIntTruncate(fn.arg(0).to_number()); + fn.result->set_bool(static_cast(lpm)->removeDemoBookmark( + static_cast(index))); // +0xB0 + busyClose(busy); +} + +// sub_10054940 "addFavouriteServer": the busy cursor, GeneralSettings, the player host; the row id +// "%s %d %d" (0x100D99BC: address, query port, host port; the same unbounded %s as joinServer, +// bounded here the same way [CHOSEN, not recovered]). A favourite already at (address, query port) +// (+0x134 findFavouriteServer) answers false. Otherwise the current list's +0x3C getRecord(address, +// queryPort, false, false): none answers false; a record is added as +0x11C addFavouriteServer( +// entry.address, entry.queryPort, entry.hostName) and the answer is true. +void as_multiplay_addFavouriteServer(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_addFavouriteServer"); + BusyHost busy = busyOpen(); + IGeneralSettings* gs = static_cast( + classManager->getSingleton(renddx9abi::HostString("GeneralSettings"))); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const std::string id(fn.arg(0).to_string()); + std::string address; + char buf[260] = {0}; + int queryPort = 0, hostPort = 0; + ::sscanf(id.c_str(), "%259s %d %d", buf, &queryPort, &hostPort); + address = buf; + if (gs->findFavouriteServer(address, queryPort)) // +0x134 + { + fn.result->set_bool(false); + busyClose(busy); + return; + } + ServerBrowserRecord* rec = currentServerList(h)->getRecord(address, queryPort, false, false); // +0x3C + if (!rec) + fn.result->set_bool(false); + else + { + gs->addFavouriteServer(rec->entry.address, rec->entry.queryPort, rec->entry.hostName); // +0x11C + fn.result->set_bool(true); + } + busyClose(busy); +} + +// sub_10054B20 "removeFavouriteServer": the busy cursor, the player host and GeneralSettings are +// fetched, and the answer is false. The shipped body removes nothing. +void as_multiplay_removeFavouriteServer(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_removeFavouriteServer"); + BusyHost busy = busyOpen(); + (void) g_swiffPlayerInstance->getSwiffHost(); + (void) classManager->getSingleton(renddx9abi::HostString("GeneralSettings")); + fn.result->set_bool(false); + busyClose(busy); +} + +// sub_10055350 "getSelectedServerFilterGameMode" / sub_100555E0 "getSelectedFilterGameModeId": host +// +0x120 getModInfo() +0x1C getCurrentMod(); an empty gameModes vector (Mod +0x10C) answers "". The +// Id row publishes gameModes[0]; the other publishes ModInfo +0x4C getNameFromGameMode(gameModes[0]). +void as_multiplay_getSelectedServerFilterGameMode(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_getSelectedServerFilterGameMode"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const IModInfo::Mod* mod = static_cast(h->getModInfo())->getCurrentMod(); // +0x120, +0x1C + if (mod->gameModes.empty()) + { + fn.result->set_tu_string(tu_string("")); + return; + } + const std::string first(mod->gameModes[0]); + const std::string name = static_cast(h->getModInfo())->getNameFromGameMode(first); // +0x4C + fn.result->set_tu_string(tu_string(name.c_str())); +} +void as_multiplay_getSelectedFilterGameModeId(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_getSelectedFilterGameModeId"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const IModInfo::Mod* mod = static_cast(h->getModInfo())->getCurrentMod(); // +0x120, +0x1C + if (mod->gameModes.empty()) + { + fn.result->set_tu_string(tu_string("")); + return; + } + const std::string first(mod->gameModes[0]); + fn.result->set_tu_string(tu_string(first.c_str())); +} + +// sub_100563B0 "getMapPathFromName": name = arg 0; every mod of host +0x120 getModInfo() +0x14 +// getModList() (re-fetched each step) and every map of it is searched for map.name == name +// (operator==). No match publishes the name itself. A match builds a string as_value from the map's +// path and destroys it without assigning it (100564D6..100564F2: sub_10007680, then sub_1008A2F0, +// no sub_10009920): the AS result stays untouched. Observed shipped defect, preserved. +void as_multiplay_getMapPathFromName(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_getMapPathFromName"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const std::string name(fn.arg(0).to_string()); + for (unsigned int m = 0; m < static_cast(h->getModInfo())->getModList()->size(); ++m) // +0x14 + { + const IModInfo::Mod& mod = (*static_cast(h->getModInfo())->getModList())[m]; + for (unsigned int i = 0; i < mod.maps.size(); ++i) + { + if (mod.maps[i].name == name) + { + const tu_string discarded(mod.maps[i].path.c_str()); // built, never assigned + (void) discarded; + return; + } + } + } + fn.result->set_tu_string(tu_string(name.c_str())); +} + +// sub_10057310 "playDemo": the busy cursor, the player host, (int) arg 0; host +0x44 +// getDemoLibrary() +0x1C getEntry(index). None: nothing. An entry queues menu event 12 with the +// entry's path (+0x20) as its only argument through host +0x2C pushEvent. No AS result. +void as_multiplay_playDemo(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_playDemo"); + BusyHost busy = busyOpen(); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const int index = bf2x87::toIntTruncate(fn.arg(0).to_number()); + DemoLibraryEntry* entry = + static_cast(h->getDemoLibrary())->getEntry(static_cast(index)); // +0x1C + if (entry) + { + const std::string path(entry->path); + MenuEvent event; + event.type = 12; + event.args.push_back(path); + (void) h->pushEvent(event); // +0x2C + } + busyClose(busy); +} + +// sub_10057450 "getMapName": index = (int) arg 0; host +0xFC getServerEntries(rows). False answers +// the number 0. Otherwise the row at index publishes its map (+0); an index past the end answers "". +void as_multiplay_getMapName(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_getMapName"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const int index = bf2x87::toIntTruncate(fn.arg(0).to_number()); + std::vector rows; + if (!h->getServerEntries(rows)) // +0xFC + { + fn.result->set_double(0.0); + return; + } + for (unsigned int i = 0; i < rows.size(); ++i) + { + if (i == static_cast(index)) + { + fn.result->set_tu_string(tu_string(rows[i].map.c_str())); + return; + } + } + fn.result->set_tu_string(tu_string("")); +} + +// ---- dice.bf2.Sound (the VoIP rows) ----------------------------------------------------------- + +// byte_100F8B4C: "VoIP initialised". Only voipInitialize's client arm (0x1006913F) raises it. +static bool s_voipInitialized = false; +// flt_100EC92C (s_voipThreshold, SwiffPlayer.cpp): the menu's capture threshold, kept while a voice +// test overrides the client's. +// dword_100F8B50: the profile name voipInitialize last pushed the AudioSettings voice values for. +static std::string s_voipInitializedProfile; + +// Every VoIP row reads the player (dword_100F2F20) and its +0x8C getBf2VoipClient, the BF2.exe voice +// client SwiffPlayer reached through getSingleton("Bf2VoipClient") (Game/VoipClient/BF2VoipClient.h; +// virtual slots only, plus VoipClient's header-inline setLocalLoopback, as the DLL links its copy). +static BF2VoipClient* voipPlayerClient(SwiffPlayer* player) +{ + return player ? static_cast(player->getBf2VoipClient()) : 0; // player +0x8C +} +static IAudioSettings* voipAudioSettings() +{ + return static_cast(classManager->getSingleton(renddx9abi::HostString("AudioSettings"))); +} + +// sub_10069010 "voipInitialize": needs the client and the LocalProfileManager. A client that is neither +// in a session nor testing starts the local test (quality 3, mixer); failing that answers false. Then +// the player's VoIP tick is armed and the row is initialised; the first call for a profile pushes the +// AudioSettings voice values (playback, capture, boost, threshold) into the client. True. +void as_sound_voipInitialize(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_sound_voipInitialize"); + SwiffPlayer* player = g_swiffPlayerInstance; + BF2VoipClient* client = voipPlayerClient(player); + if (!client) + { + fn.result->set_bool(false); // 0x1006925B + return; + } + IBase* lpm = classManager->getSingleton(renddx9abi::HostString("LocalProfileManager")); + if (!lpm) + { + fn.result->set_bool(false); // 0x1006906A + return; + } + const std::string profile = static_cast(lpm)->getName(); // +0x7C + if (client->isActive() || client->isTesting()) // +0x38 +0x34 + { + player->setVoipUpdateFlag(1); // +0x90 + s_voipInitialized = true; + if (profile == s_voipInitializedProfile) + { + fn.result->set_bool(true); + return; + } + } + else if (!client->startTest(3, true)) // +0x30 + { + fn.result->set_bool(false); + return; + } + IAudioSettings* as = voipAudioSettings(); + if (!as) + { + fn.result->set_bool(false); + return; + } + s_voipInitializedProfile = profile; + client->setPlaybackVolume(as->getVoipPlaybackVolume()); // +0x1C, as +0x40 + client->setCaptureVolume(as->getVoipCaptureVolume()); // +0x20, as +0x48 + client->mixerSetBoost(as->getVoipBoostEnabled()); // +0xCC, as +0x58 + s_voipThreshold = as->getVoipCaptureThreshold(); // as +0x50 + client->setCaptureThreshold(s_voipThreshold); // +0x14 + player->setVoipUpdateFlag(1); + s_voipInitialized = true; + fn.result->set_bool(true); +} + +// sub_100692B0 "voipSetEnable": stores the AudioSettings flag and enables or disables the client's user +// switch (+0x98 takes "disabled"). True. No player, AudioSettings, initialisation or client: no result. +void as_sound_voipSetEnable(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_sound_voipSetEnable"); + SwiffPlayer* player = g_swiffPlayerInstance; + IAudioSettings* as = voipAudioSettings(); + if (!player || !as || !s_voipInitialized || !voipPlayerClient(player)) + return; + if (fn.arg(0).to_bool()) + { + as->setVoipEnabled(true); // +0x3C + voipPlayerClient(player)->setUserDisabled(false); // +0x98 + } + else + { + as->setVoipEnabled(false); + voipPlayerClient(player)->setUserDisabled(true); + } + fn.result->set_bool(true); +} + +// sub_100693C0 "voipGetEnable": VoIP not initialised answers false; otherwise AudioSettings by name, +// absent answers false, present answers the Boolean of +0x38 getVoipEnabled. No client involved. +void as_sound_voipGetEnable(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_sound_voipGetEnable"); + if (!s_voipInitialized) + { + fn.result->set_bool(false); + return; + } + IBase* as = classManager->getSingleton(renddx9abi::HostString("AudioSettings")); + if (!as) + { + fn.result->set_bool(false); + return; + } + fn.result->set_bool(audioSettingsOf(as)->getVoipEnabled()); // +0x38 +} + +// The rows that read the player, the client and AudioSettings: an absent AudioSettings answers false; +// the remaining null exits leave the result untouched. +#define VOIP_ROW_PROLOGUE(row) \ + SWF_AS_TRACE("as_sound_" #row); \ + SwiffPlayer* player = g_swiffPlayerInstance; \ + BF2VoipClient* client = voipPlayerClient(player); \ + if (!client) \ + return; \ + IAudioSettings* as = voipAudioSettings(); \ + if (!as) \ + { \ + fn.result->set_bool(false); \ + return; \ + } + +// sub_100694E0 "voipStartTest": only with a session or test running. Marks the test (byte_100F8B4D), +// mutes sound groups 0..3 through the host (+0x18C), loops capture back to playback and opens the gate +// (threshold 0). No result; a client with neither answers false. +void as_sound_voipStartTest(const gameswf::fn_call& fn) +{ + VOIP_ROW_PROLOGUE(voipStartTest) + (void) as; + if (!client->isTesting() && !client->isActive()) + { + fn.result->set_bool(false); + return; + } + s_voipTestRunning = true; + player->getSwiffHost()->slot18C(1); // +0x5C, +0x18C + client->setLocalLoopback(true); // 0x100BC8B0 + client->setCaptureThreshold(0.0f); // +0x14 +} + +// sub_10069750 / sub_100698C0 "voipSetTransmitVolume" / "voipSetRecieveVolume": once initialised, the +// number goes to the client and to AudioSettings (capture +0x20/+0x4C, playback +0x1C/+0x44). +void as_sound_voipSetTransmitVolume(const gameswf::fn_call& fn) +{ + VOIP_ROW_PROLOGUE(voipSetTransmitVolume) + if (!s_voipInitialized) + return; + const float volume = static_cast(fn.arg(0).to_number()); + client->setCaptureVolume(volume); + as->setVoipCaptureVolume(volume); +} +void as_sound_voipSetRecieveVolume(const gameswf::fn_call& fn) +{ + VOIP_ROW_PROLOGUE(voipSetRecieveVolume) + if (!s_voipInitialized) + return; + const float volume = static_cast(fn.arg(0).to_number()); + client->setPlaybackVolume(volume); + as->setVoipPlaybackVolume(volume); +} + +// sub_10069A30 "voipSetThresholdVolume": the menu value is always kept; outside a voice test it also +// reaches the client and AudioSettings (+0x14, +0x54). +void as_sound_voipSetThresholdVolume(const gameswf::fn_call& fn) +{ + VOIP_ROW_PROLOGUE(voipSetThresholdVolume) + if (!s_voipInitialized) + return; + const float threshold = static_cast(fn.arg(0).to_number()); + s_voipThreshold = threshold; + if (s_voipTestRunning) + return; + client->setCaptureThreshold(threshold); + as->setVoipCaptureThreshold(threshold); +} + +// sub_10069BA0 "voipSetBoost": AudioSettings follows only when the mixer accepted the boost (+0xCC). +void as_sound_voipSetBoost(const gameswf::fn_call& fn) +{ + VOIP_ROW_PROLOGUE(voipSetBoost) + if (!s_voipInitialized) + return; + const bool boost = fn.arg(0).to_bool(); + if (client->mixerSetBoost(boost)) + as->setVoipBoostEnabled(boost); // +0x5C +} + +// sub_10069E10 "voipSetUsePushToTalk": not initialised answers false; otherwise the client and +// AudioSettings take the flag (+0xAC, +0x64), with no result. +void as_sound_voipSetUsePushToTalk(const gameswf::fn_call& fn) +{ + VOIP_ROW_PROLOGUE(voipSetUsePushToTalk) + if (!s_voipInitialized) + { + fn.result->set_bool(false); + return; + } + const bool enabled = fn.arg(0).to_bool(); + client->setPushToTalkEnabled(enabled); + as->setVoipUsePushToTalk(enabled); +} +#undef VOIP_ROW_PROLOGUE + +// The getters: player and client first, null exits leave the result untouched. +// sub_10069840 / sub_100699B0: once initialised, the client's capture / playback volume (+0x24/+0x28). +void as_sound_voipGetTransmitVolume(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_sound_voipGetTransmitVolume"); + BF2VoipClient* client = voipPlayerClient(g_swiffPlayerInstance); + if (client && s_voipInitialized) + fn.result->set_double(client->getCaptureVolume()); +} +void as_sound_voipGetRecieveVolume(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_sound_voipGetRecieveVolume"); + BF2VoipClient* client = voipPlayerClient(g_swiffPlayerInstance); + if (client && s_voipInitialized) + fn.result->set_double(client->getPlaybackVolume()); +} +// sub_10069B30: the kept menu threshold, as a number. +void as_sound_voipGetThresholdVolume(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_sound_voipGetThresholdVolume"); + BF2VoipClient* client = voipPlayerClient(g_swiffPlayerInstance); + if (client && s_voipInitialized) + fn.result->set_double(s_voipThreshold); +} +// sub_10069CA0: not initialised answers false; otherwise the mixer's boost (+0xD4). +void as_sound_voipGetBoost(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_sound_voipGetBoost"); + BF2VoipClient* client = voipPlayerClient(g_swiffPlayerInstance); + if (!client) + return; + if (!s_voipInitialized) + { + fn.result->set_bool(false); + return; + } + bool boost = false; + client->mixerGetBoost(&boost); + fn.result->set_bool(boost); +} +// sub_10069D80 / sub_10069F50: the mixer's boost support (+0xC8) / the push-to-talk flag (+0xA8), +// false while not initialised. +void as_sound_voipIsBoostEnabled(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_sound_voipIsBoostEnabled"); + BF2VoipClient* client = voipPlayerClient(g_swiffPlayerInstance); + if (client) + fn.result->set_bool(s_voipInitialized ? client->mixerHasBoost() : false); +} +void as_sound_voipGetUsePushToTalk(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_sound_voipGetUsePushToTalk"); + BF2VoipClient* client = voipPlayerClient(g_swiffPlayerInstance); + if (client) + fn.result->set_bool(s_voipInitialized ? client->getPushToTalkEnabled() : false); +} + +// sub_10069FE0 "voipSendingVoice": Boolean false first. Once initialised: the capture level against the +// menu threshold. At or above it the answer is true and loopback plays back; below it false and the +// loopback stays silent (client +0x95, written directly). +void as_sound_voipSendingVoice(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_sound_voipSendingVoice"); + fn.result->set_bool(false); + BF2VoipClient* client = voipPlayerClient(g_swiffPlayerInstance); + if (!client) + return; + bool sending = false; + if (s_voipInitialized) + { + double level = 0.0; + client->getCaptureLevel(&level); // +0x3C + if (static_cast(s_voipThreshold) <= level) + { + client->m_loopbackSilent = false; + sending = true; + } + else + { + client->m_loopbackSilent = true; + } + } + fn.result->set_bool(sending); +} + +// sub_1006A0F0 "voipGetSendingVoiceVolume": the number 0 first; once initialised, the capture level +// while the client reports capturing, else 0. +void as_sound_voipGetSendingVoiceVolume(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_sound_voipGetSendingVoiceVolume"); + fn.result->set_double(0.0); + BF2VoipClient* client = voipPlayerClient(g_swiffPlayerInstance); + if (!client || !s_voipInitialized) + return; + double level = 0.0; + fn.result->set_double(client->getCaptureLevel(&level) ? level : 0.0); +} + +// ---- dice.bf2.Mod ------------------------------------------------------------------------------ + +// dword_100EC604: the mod row the Mod page selected, -1 at load (.data initialiser), written only by +// Mod.selectMod. +static int s_selectedModIndex = -1; + +// sub_1004F630 "getNumMods": host +0x190 getModCount(&n), n pre-set 0; false answers 0, true n. +void as_mod_getNumMods(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_mod_getNumMods"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + int count = 0; + if (!h->getModCount(&count)) // +0x190 + fn.result->set_double(0.0); + else + fn.result->set_double(static_cast(count)); +} + +// sub_1004F6E0 "browseHomepage" / sub_1004F750 "activateMod": with a selection, a default Mod record +// (sub_100224E0 / sub_10022580) filled by host +0x194 getModAt(selection, &mod); a filled record is +// handed to +0x19C requestBrowseModHomepage / +0x198 requestActivateMod (Booleans ignored). No AS +// result. requestActivateMod's parameter is the record itself, whose first member is the path. +void as_mod_browseHomepage(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_mod_browseHomepage"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const int index = s_selectedModIndex; + if (index == -1) + return; + IModInfo::Mod mod; + if (h->getModAt(index, &mod)) // +0x194 + (void) h->requestBrowseModHomepage(&mod); // +0x19C +} +void as_mod_activateMod(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_mod_activateMod"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const int index = s_selectedModIndex; + if (index == -1) + return; + IModInfo::Mod mod; + if (h->getModAt(index, &mod)) // +0x194 + (void) h->requestActivateMod(&mod.path); // +0x198 +} + +// sub_1004F800 "selectMod": (int) arg 0 into dword_100EC604 (fistp straight to the global). No AS +// result and no player access. +void as_mod_selectMod(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_mod_selectMod"); + s_selectedModIndex = bf2x87::toIntTruncate(fn.arg(0).to_number()); +} + +// sub_1004F840 "activateModAndJoinServer": the player host; mod = "mods/" + arg 0, address = arg 1, +// port = (int) arg 2; host +0x368(mod, address, port), Boolean ignored (BF2.exe 0x626200 is `mov al, +// 1; ret 0Ch`). No AS result. +void as_mod_activateModAndJoinServer(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_mod_activateModAndJoinServer"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + std::string mod(fn.arg(0).to_string()); + mod = std::string("mods/") + mod; + const std::string address(fn.arg(1).to_string()); + const int port = bf2x87::toIntTruncate(fn.arg(2).to_number()); + (void) h->slot368(mod, address, port); // +0x368 +} + +// sub_1004FA00 "getModTitle" / sub_1004FB60 "getModDesc": the player host, then a dice String +// object (0x64 bytes, sub_1009BB10). No selection, or getModAt refusing: narrow "" with the wide side +// cleared. A record: the title (+0x38) / desc (+0x54) key localised through host +0xA8 +// (sub_1004F5E0) into the wide side, the narrow side "". +static void publishModLocalised(const gameswf::fn_call& fn, std::string IModInfo::Mod::* field) +{ + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + gameswf::as_object_interface* text = gameswf::create_dice_string_object(0, 0); + const int index = s_selectedModIndex; + if (index == -1) + { + gameswf::assign_dice_string_object_narrow(text, ""); + fn.result->set_as_object_interface(text); + return; + } + IModInfo::Mod mod; + if (!h->getModAt(index, &mod)) // +0x194 + gameswf::assign_dice_string_object_narrow(text, ""); + else + { + std::wstring wide; + (void) g_swiffPlayerInstance->getSwiffHost()->getLocalizedString(wide, mod.*field); // +0xA8 + gameswf::assign_dice_string_object_wide(text, BF2_DICE_UTF16(wide.c_str())); + } + fn.result->set_as_object_interface(text); +} +void as_mod_getModTitle(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_mod_getModTitle"); + publishModLocalised(fn, &IModInfo::Mod::title); +} +void as_mod_getModDesc(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_mod_getModDesc"); + publishModLocalised(fn, &IModInfo::Mod::desc); +} + +// sub_1004FCC0 "getModPath", sub_1004FFE0 "getModUrl", sub_10050120 "getModLogo", sub_10050260 +// "getModVersion": no selection or getModAt refusing answers ""; a record publishes its path (+0x00), +// url (+0x70), logo (+0xA8) or version (+0xE0) as a plain string. +static void publishModField(const gameswf::fn_call& fn, std::string IModInfo::Mod::* field) +{ + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + if (s_selectedModIndex == -1) + { + fn.result->set_tu_string(tu_string("")); + return; + } + IModInfo::Mod mod; + if (!h->getModAt(s_selectedModIndex, &mod)) // +0x194 + fn.result->set_tu_string(tu_string("")); + else + fn.result->set_tu_string(tu_string((mod.*field).c_str())); +} +void as_mod_getModPath(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_mod_getModPath"); publishModField(fn, &IModInfo::Mod::path); } +void as_mod_getModUrl(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_mod_getModUrl"); publishModField(fn, &IModInfo::Mod::url); } +void as_mod_getModLogo(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_mod_getModLogo"); publishModField(fn, &IModInfo::Mod::logo); } +void as_mod_getModVersion(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_mod_getModVersion"); publishModField(fn, &IModInfo::Mod::version); } + +// sub_1004FE00 "getModPathShort": as getModPath, but only the characters after the first '/' or '\' +// of the path, appended one at a time (operator+= char) to an empty string. +void as_mod_getModPathShort(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_mod_getModPathShort"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + if (s_selectedModIndex == -1) + { + fn.result->set_tu_string(tu_string("")); + return; + } + IModInfo::Mod mod; + if (!h->getModAt(s_selectedModIndex, &mod)) // +0x194 + { + fn.result->set_tu_string(tu_string("")); + return; + } + std::string tail(""); + bool past = false; + for (unsigned int i = 0; i < mod.path.size(); ++i) + { + if (!past) + { + if (mod.path[i] == '/' || mod.path[i] == '\\') + past = true; + } + else + tail += mod.path[i]; + } + fn.result->set_tu_string(tu_string(tail.c_str())); +} + +// ---- dice.bf2.Logic ---------------------------------------------------------------------------- + +// sub_1004C950 "cacheCredits": the player host (discarded), player +0x28 getRender() +0xF4 +// preloadCredits (answer ignored). No AS result. +void as_logic_cacheCredits(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_logic_cacheCredits"); + (void) g_swiffPlayerInstance->getSwiffHost(); + (void) g_swiffPlayerInstance->getRender()->preloadCredits(); // +0x28, +0xF4 +} + +// sub_1004CA70 "quit": inside the busy cursor; the player host, LocalProfileManager; with a current +// profile (+0x44) +0x40 saveCurrentProfile, otherwise +0xC4 saveGlobalSettings (Booleans ignored); +// then host +0xB0 requestQuit. No AS result. +void as_logic_quit(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_logic_quit"); + BusyHost busy = busyOpen(); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + ILocalProfileManager* lpm = static_cast( + classManager->getSingleton(renddx9abi::HostString("LocalProfileManager"))); + if (lpm->getCurrentProfile()) // +0x44 + (void) lpm->saveCurrentProfile(); // +0x40 + else + (void) lpm->saveGlobalSettings(); // +0xC4 + (void) h->requestQuit(); // +0xB0 + busyClose(busy); +} + +// sub_1004CB60 "assert": the shipped body is a bare `ret 0Ch`. +void as_logic_assert(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_logic_assert"); +} + +// sub_1004CB70 "setActivateReason": host +0xC0 setMessageId((int) arg 0). No AS result. +void as_logic_setActivateReason(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_logic_setActivateReason"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + h->setMessageId(bf2x87::toIntTruncate(fn.arg(0).to_number())); // +0xC0 +} + +// sub_1004CF80 "setScrollSpeed": host +0x32C with arg 0 as a float (fstp dword). No AS result. +void as_logic_setScrollSpeed(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_logic_setScrollSpeed"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + h->setFloatF0C(static_cast(fn.arg(0).to_number())); // +0x32C +} + +// sub_1004CFD0 "setCommandLine": host +0x2C0 with (int) arg 0 (the port names the slot setPage). +void as_logic_setCommandLine(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_logic_setCommandLine"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + h->setPage(bf2x87::toIntTruncate(fn.arg(0).to_number())); // +0x2C0 +} + +// sub_1004D350 "getRandomCreditsTexture": the player host (discarded), player +0x28 getRender() +// +0x100 getRandomCreditsName, published as a string. +void as_logic_getRandomCreditsTexture(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_logic_getRandomCreditsTexture"); + (void) g_swiffPlayerInstance->getSwiffHost(); + const std::string name = g_swiffPlayerInstance->getRender()->getRandomCreditsName(); // +0x28, +0x100 + fn.result->set_tu_string(tu_string(name.c_str())); +} + +// sub_1004D810 "getCommandlineServer" / sub_1004D890 "getCommandlineServerPassword": host +0xDC +// getJoinAddressSetting / +0xE0 getPasswordSetting (GSJoinAddress / GSPassword), as strings. +void as_logic_getCommandlineServer(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_logic_getCommandlineServer"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const std::string value = h->getJoinAddressSetting(); // +0xDC + fn.result->set_tu_string(tu_string(value.c_str())); +} +void as_logic_getCommandlineServerPassword(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_logic_getCommandlineServerPassword"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const std::string value = h->getPasswordSetting(); // +0xE0 + fn.result->set_tu_string(tu_string(value.c_str())); +} + +// sub_1004DAA0 "getAbsoluteFileName": host +0x234 resolveMenuPath(arg 0), as a string. +void as_logic_getAbsoluteFileName(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_logic_getAbsoluteFileName"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const std::string path(fn.arg(0).to_string()); + const std::string value = h->resolveMenuPath(path); // +0x234 + fn.result->set_tu_string(tu_string(value.c_str())); +} + +// sub_1004DE30 "restartExe": menu event 18 (0x12) with no arguments through host +0x2C pushEvent. +void as_logic_restartExe(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_logic_restartExe"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + MenuEvent event; + event.type = 0x12; + (void) h->pushEvent(event); // +0x2C +} + +// ---- dice.bf2.PlayerStats ---------------------------------------------------------------------- + +// sub_10059E00 "getPreviousRankLevel", sub_10059EE0 "getNextRankLevel", sub_1005A1E0 +// "getRankNotificationLevel": the player host, ProfileManager (+0x30 getProfileId when present, the +// id pre-set 0), a rank record {time(), 0, 0, 0, 0} and host +0x284 getRankInfo(id, &record). False +// answers 0. True answers record.rank through host +0x1B8 getRankB / +0x1BC getRankC, or record.rank +// itself. +static bool currentRankRecord(ISwiffHost* h, IPlayerRankInfo::RankInfo& record) +{ + IBase* pm = classManager->getSingleton(renddx9abi::HostString("ProfileManager")); + int id = 0; + if (pm) + (void) static_cast(pm)->getProfileId(id); // +0x30 + record.timestamp = static_cast(::time(0)); + record.profileId = 0; record.rank = 0; record.change = 0; record.decrease = 0; + return h->getRankInfo(id, &record); // +0x284 +} +void as_playerstats_getPreviousRankLevel(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_playerstats_getPreviousRankLevel"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + IPlayerRankInfo::RankInfo record; + int value = 0; + if (currentRankRecord(h, record)) + value = h->getRankB(record.rank); // +0x1B8 + fn.result->set_double(static_cast(value)); +} +void as_playerstats_getNextRankLevel(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_playerstats_getNextRankLevel"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + IPlayerRankInfo::RankInfo record; + int value = 0; + if (currentRankRecord(h, record)) + value = h->getRankC(record.rank); // +0x1BC + fn.result->set_double(static_cast(value)); +} +void as_playerstats_getRankNotificationLevel(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_playerstats_getRankNotificationLevel"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + IPlayerRankInfo::RankInfo record; + int value = 0; + if (currentRankRecord(h, record)) + value = record.rank; + fn.result->set_double(static_cast(value)); +} + +// sub_1005A3B0 "refreshUnlocks" / sub_1005A490 "refreshStats": Boolean of host +0x1C8 fetchUnlocks / +// +0x1AC fetchPlayerStats((int) arg 0). +void as_playerstats_refreshUnlocks(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_playerstats_refreshUnlocks"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + fn.result->set_bool(h->fetchUnlocks(bf2x87::toIntTruncate(fn.arg(0).to_number()))); // +0x1C8 +} +void as_playerstats_refreshStats(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_playerstats_refreshStats"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + fn.result->set_bool(h->fetchPlayerStats(bf2x87::toIntTruncate(fn.arg(0).to_number()))); // +0x1AC +} + +// sub_1005A9B0 "getUnlocks": id = (int) arg 0; an unlock cache {time(), 0, 0, 0, {}} and the Boolean +// of host +0x1C4 getUnlocks(id, &cache). +void as_playerstats_getUnlocks(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_playerstats_getUnlocks"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const int id = bf2x87::toIntTruncate(fn.arg(0).to_number()); + IPlayerUnlocks::UnlockCache cache; + cache.field0 = static_cast(::time(0)); + cache.field4 = 0; cache.available = 0; cache.selected = 0; + fn.result->set_bool(h->getUnlocks(id, &cache)); // +0x1C4 +} + +// sub_1005BBA0 "getStats": id = (int) arg 0; a default stats record (sub_10020A80) and the Boolean +// of host +0x1B0 getPlayerStatsRecord(id, record). +void as_playerstats_getStats(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_playerstats_getStats"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const int id = bf2x87::toIntTruncate(fn.arg(0).to_number()); + dice::hfe::SwiffPlayerStatsRecord record; + fn.result->set_bool(h->getPlayerStatsRecord(id, record)); // +0x1B0 +} + +// sub_1005B0E0 "getOpponentKills", sub_1005B1A0 "getVictimKills", sub_1005BAE0 "getRoadKills": a +// default stats record, host +0x1B0 getPlayerStatsRecord(+0x21C getSelectedPlayerId, record); false +// answers 0, true the record's vmks (+520), mvks (+484) or vrk (+2672) as a number. +static void publishStatsKills(const gameswf::fn_call& fn, int dice::hfe::SwiffPlayerStatsRecord::* field) +{ + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + dice::hfe::SwiffPlayerStatsRecord record; + if (!h->getPlayerStatsRecord(h->getSelectedPlayerId(), record)) // +0x21C, +0x1B0 + fn.result->set_double(0.0); + else + fn.result->set_double(static_cast(record.*field)); +} +void as_playerstats_getOpponentKills(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_getOpponentKills"); publishStatsKills(fn, &dice::hfe::SwiffPlayerStatsRecord::vmks); } +void as_playerstats_getVictimKills(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_getVictimKills"); publishStatsKills(fn, &dice::hfe::SwiffPlayerStatsRecord::mvks); } +void as_playerstats_getRoadKills(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_getRoadKills"); publishStatsKills(fn, &dice::hfe::SwiffPlayerStatsRecord::vrk); } + +// ---- dice.bf2.ServerInfo ----------------------------------------------------------------------- + +// sub_10062940 "getSponsorText": a default record through the in-game fetch (sub_100627F0), the +// sponsor text (details +160) with every "|" replaced by "\n" (sub_100037D0), as a string. +void as_serverinfo_getSponsorText(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_serverinfo_getSponsorText"); + CachedRecord record; + fetchInGameServerRecord(record); + std::string text(record.details.sponsorText); + for (std::string::size_type at = text.find("|"); at != std::string::npos; at = text.find("|", at + 1)) + text.replace(at, 1, "\n"); + fn.result->set_tu_string(tu_string(text.c_str())); +} + +// sub_10062BA0 "getMapName": the in-game record's map name (entry +144), as a string. +void as_serverinfo_getMapName(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_serverinfo_getMapName"); + CachedRecord record; + fetchInGameServerRecord(record); + fn.result->set_tu_string(tu_string(record.entry.mapName.c_str())); +} + +// sub_10062C50 "getMaxPlayers": the in-game record's max players (entry +100), as a number. +void as_serverinfo_getMaxPlayers(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_serverinfo_getMaxPlayers"); + CachedRecord record; + fetchInGameServerRecord(record); + fn.result->set_double(static_cast(record.entry.maxPlayers)); +} + +// sub_10062CF0 "getGameModeTitle", sub_10062DA0 "getGameModeDescription", sub_10062E50 +// "getBackgroundTitle", sub_10062F00 "getBackgroundDescription": all four publish the in-game +// record's game mode string (entry +108; each reads [ebp-1F0h] with the capacity at [ebp-1DCh]). +// The identical bodies are shipped behaviour. +static void publishInGameGameMode(const gameswf::fn_call& fn) +{ + CachedRecord record; + fetchInGameServerRecord(record); + fn.result->set_tu_string(tu_string(record.entry.gameMode.c_str())); +} +void as_serverinfo_getGameModeTitle(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_serverinfo_getGameModeTitle"); publishInGameGameMode(fn); } +void as_serverinfo_getGameModeDescription(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_serverinfo_getGameModeDescription"); publishInGameGameMode(fn); } +void as_serverinfo_getBackgroundTitle(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_serverinfo_getBackgroundTitle"); publishInGameGameMode(fn); } +void as_serverinfo_getBackgroundDescription(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_serverinfo_getBackgroundDescription"); publishInGameGameMode(fn); } + +// ---- dice.bf2.Singleplay / Shader --------------------------------------------------------------- + +// sub_10068BF0 "getBotSkills" / sub_10068C00 "setBotSkills": the player host is fetched and nothing +// else happens; no AS result. +void as_singleplay_getBotSkills(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_singleplay_getBotSkills"); + (void) g_swiffPlayerInstance->getSwiffHost(); +} +void as_singleplay_setBotSkills(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_singleplay_setBotSkills"); + (void) g_swiffPlayerInstance->getSwiffHost(); +} + +// sub_10068C10 "chooseMission": id = (int) arg 0; host +0xEC getSinglePlayerLevels(rows). True: the +// first row whose index equals id goes to host +0xE8 requestHostServer (Boolean ignored). No AS +// result. +void as_singleplay_chooseMission(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_singleplay_chooseMission"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const int id = bf2x87::toIntTruncate(fn.arg(0).to_number()); + std::vector rows; + if (!h->getSinglePlayerLevels(rows)) // +0xEC + return; + for (unsigned int i = 0; i < rows.size(); ++i) + { + if (rows[i].index == id) + { + (void) h->requestHostServer(&rows[i]); // +0xE8 + return; + } + } +} + +// sub_10068A10 "setShader": the player host (discarded); name = arg 0, technique = (int) arg 1; +// player +0x70 (renderSetPairState -> SwiffRender::setTextureTechnique). No AS result. +void as_shader_setShader(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_shader_setShader"); + (void) g_swiffPlayerInstance->getSwiffHost(); + const std::string name(fn.arg(0).to_string()); + const int technique = bf2x87::toIntTruncate(fn.arg(1).to_number()); +#if defined(_MSC_VER) + g_swiffPlayerInstance->renderSetPairState(reinterpret_cast(&name), technique); // +0x70 +#else + g_swiffPlayerInstance->renderSetPairState(name, technique); // +0x70 +#endif +} + +// ---- dice.bf2.ControlSettings.mapInput --------------------------------------------------------- + +// sub_1000EDA0 "mapInput": the player host; ControlSettings +0x80 activateMouse; the edited map +// selected (sub_1000E250); input = (int) arg 0. Input -1: the selection restored (sub_1000E2E0), +// ControlSettings +0x84 deactivateMouse, Boolean true. Otherwise alternate = arg 1, second = arg 2 +// (to_bool), arg 3 to_bool and dropped; gameInput = (unk_100F3138 == "_defaultGameControlMap"); +// ControlSettings +0x30 mapNextInput(input, alternate, 0, second, gameInput). Answer 1: restore, +// deactivateMouse, post {3, 0, "dup" + getMappedInputName (+0x90)} through host +0x1E4, Boolean false. +// Answer 2: restore, deactivateMouse, false. Any other answer: restore, deactivateMouse, true. +// BF2.exe's +0x30 (0x4B2CA0) returns the manager's full EAX (+0x38), compared here with 1 and 2; +// both are declared int. The port's manager capture is a CHOSEN-STUB answering 0, so only the last +// arm is reachable until the capture routine (ELF 0x8497AC0) is recovered. +void as_controlsettings_mapInput(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_controlsettings_mapInput"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + controlSettingsOf(controlSettingsSingleton())->activateMouse(); // +0x80 + selectEditedControlMap(); + const int input = bf2x87::toIntTruncate(fn.arg(0).to_number()); + if (input != -1) + { + const bool alternate = fn.arg(1).to_bool(); + const bool second = fn.arg(2).to_bool(); + (void) fn.arg(3).to_bool(); + const bool gameInput = (s_editedControlMap == "_defaultGameControlMap"); + const int answer = controlSettingsOf(controlSettingsSingleton())->mapNextInput( + input, alternate, 0, second, gameInput); // +0x30 + if (answer == 1) + { + restoreControlMapSelection(); + controlSettingsOf(controlSettingsSingleton())->deactivateMouse(); // +0x84 + const std::string mapped = controlSettingsOf(controlSettingsSingleton())->getMappedInputName(); // +0x90 + const std::string dup("dup"); + const std::string text = std::string(dup) + mapped; + SwiffHostMessage message; + message.type = 3; + message.code = 0; + message.text = text; + (void) h->postMessage(message); // +0x1E4 + fn.result->set_bool(false); + return; + } + if (answer == 2) + { + restoreControlMapSelection(); + controlSettingsOf(controlSettingsSingleton())->deactivateMouse(); // +0x84 + fn.result->set_bool(false); + return; + } + } + restoreControlMapSelection(); + controlSettingsOf(controlSettingsSingleton())->deactivateMouse(); // +0x84 + fn.result->set_bool(true); +} + +// The registrations, in the shipped registrars' order within each namespace (address of the +// name push; the callback address is the sub_ named in each body above). +static void registerRecoveredNatives(SwiffAsNamespace** ns, const char* const* names, int count) +{ + for (int i = 0; i < count; ++i) + { + const char* n = names[i]; + if (::strcmp(n, "ControlSettings") == 0) + { + ns[i]->registerNativeCompatibleMethod("mapInput"); // 1000F163 -> sub_1000EDA0 + } + else if (::strcmp(n, "Logic") == 0) + { + ns[i]->registerNativeCompatibleMethod("quit"); // 1004DF60 -> sub_1004CA70 + ns[i]->registerNativeCompatibleMethod("assert"); // 1004E0CB -> sub_1004CB60 + ns[i]->registerNativeCompatibleMethod("setActivateReason"); // 1004E17B -> sub_1004CB70 + ns[i]->registerNativeCompatibleMethod("getAbsoluteFileName"); // 1004E2DB -> sub_1004DAA0 + ns[i]->registerNativeCompatibleMethod("getCommandlineServer"); // 1004E5F3 -> sub_1004D810 + ns[i]->registerNativeCompatibleMethod("getCommandlineServerPassword"); // 1004E64B -> sub_1004D890 + ns[i]->registerNativeCompatibleMethod("setCommandLine"); // 1004E90B -> sub_1004CFD0 + ns[i]->registerNativeCompatibleMethod("restartExe"); // 1004E9BB -> sub_1004DE30 + ns[i]->registerNativeCompatibleMethod("setScrollSpeed"); // 1004EA6B -> sub_1004CF80 + ns[i]->registerNativeCompatibleMethod("cacheCredits"); // 1004EB1B -> sub_1004C950 + ns[i]->registerNativeCompatibleMethod("getRandomCreditsTexture"); // 1004EB73 -> sub_1004D350 + } + else if (::strcmp(n, "Mod") == 0) + { + ns[i]->registerNativeCompatibleMethod("getNumMods"); // 10050410 -> sub_1004F630 + ns[i]->registerNativeCompatibleMethod("browseHomepage"); // 10050473 -> sub_1004F6E0 + ns[i]->registerNativeCompatibleMethod("activateMod"); // 100504CB -> sub_1004F750 + ns[i]->registerNativeCompatibleMethod("selectMod"); // 10050523 -> sub_1004F800 + ns[i]->registerNativeCompatibleMethod("getModTitle"); // 1005057B -> sub_1004FA00 + ns[i]->registerNativeCompatibleMethod("getModDesc"); // 100505D3 -> sub_1004FB60 + ns[i]->registerNativeCompatibleMethod("getModPath"); // 1005062B -> sub_1004FCC0 + ns[i]->registerNativeCompatibleMethod("getModPathShort"); // 10050683 -> sub_1004FE00 + ns[i]->registerNativeCompatibleMethod("getModUrl"); // 100506DB -> sub_1004FFE0 + ns[i]->registerNativeCompatibleMethod("getModLogo"); // 10050733 -> sub_10050120 + ns[i]->registerNativeCompatibleMethod("getModVersion"); // 1005078B -> sub_10050260 + ns[i]->registerNativeCompatibleMethod("activateModAndJoinServer"); // 1005083B -> sub_1004F840 + } + else if (::strcmp(n, "Multiplay") == 0) + { + ns[i]->registerNativeCompatibleMethod("addFavouriteServer"); // 10057B7B -> sub_10054940 + ns[i]->registerNativeCompatibleMethod("removeFavouriteServer"); // 10057BD3 -> sub_10054B20 + ns[i]->registerNativeCompatibleMethod("getMapName"); // 10057C83 -> sub_10057450 + ns[i]->registerNativeCompatibleMethod("setFilter"); // 10057FF3 -> sub_100519C0 + ns[i]->registerNativeCompatibleMethod("sort"); // 1005804B -> sub_10051A20 + ns[i]->registerNativeCompatibleMethod("refreshBrowser"); // 100580FB -> sub_10050B70 + ns[i]->registerNativeCompatibleMethod("setHighestPing"); // 10058203 -> sub_10051480 + ns[i]->registerNativeCompatibleMethod("isDownloadingDemo"); // 1005830B -> sub_10053EE0 + ns[i]->registerNativeCompatibleMethod("getDownloadingHostname"); // 10058363 -> sub_10053F50 + ns[i]->registerNativeCompatibleMethod("getDownloadingUrl"); // 100583BB -> sub_10053FE0 + ns[i]->registerNativeCompatibleMethod("getDownloadingDate"); // 10058413 -> sub_10054070 + ns[i]->registerNativeCompatibleMethod("getDownloadingProgress"); // 1005846B -> sub_10054100 + ns[i]->registerNativeCompatibleMethod("downloadDemo"); // 100584C3 -> sub_10054160 + ns[i]->registerNativeCompatibleMethod("deleteDemoBookmark"); // 1005851B -> sub_100542C0 + ns[i]->registerNativeCompatibleMethod("getNumDemoBookmarks"); // 10058573 -> sub_10053E50 + ns[i]->registerNativeCompatibleMethod("playDemo"); // 100585CB -> sub_10057310 + ns[i]->registerNativeCompatibleMethod("clearHistory"); // 10058BA3 -> sub_10050C80 + ns[i]->registerNativeCompatibleMethod("addHistoryToFavourites"); // 10058BFB -> sub_10053230 + ns[i]->registerNativeCompatibleMethod("removeHistory"); // 10058C53 -> sub_10053540 + ns[i]->registerNativeCompatibleMethod("removeFavourite"); // 10058CAB -> sub_10053060 + ns[i]->registerNativeCompatibleMethod("addFavourite"); // 10058D03 -> sub_10052C80 + ns[i]->registerNativeCompatibleMethod("validateIp"); // 10058D5B -> sub_100528A0 + ns[i]->registerNativeCompatibleMethod("playNow"); // 10058E0B -> sub_10052AF0 + ns[i]->registerNativeCompatibleMethod("getSelectedFilterGameModeId"); // 10059123 -> sub_100555E0 + ns[i]->registerNativeCompatibleMethod("getMapPathFromName"); // 10059283 -> sub_100563B0 + ns[i]->registerNativeCompatibleMethod("getSelectedServerFilterGameMode"); // 100592DB -> sub_10055350 + ns[i]->registerNativeCompatibleMethod("isServerBrowserBusy"); // 10059333 -> sub_100526A0 + ns[i]->registerNativeCompatibleMethod("getScrollFadeSpeed"); // 10059543 -> sub_10052450 + ns[i]->registerNativeCompatibleMethod("stopDownloadDemo"); // 1005959B -> sub_10050C10 + ns[i]->registerNativeCompatibleMethod("deleteDemo"); // 100595F3 -> sub_10051F00 + ns[i]->registerNativeCompatibleMethod("hasDemoDownloadFailed"); // 1005964B -> sub_100523E0 + } + else if (::strcmp(n, "PlayerStats") == 0) + { + ns[i]->registerNativeCompatibleMethod("getStats"); // 1005C2C0 -> sub_1005BBA0 + ns[i]->registerNativeCompatibleMethod("refreshStats"); // 1005C323 -> sub_1005A490 + ns[i]->registerNativeCompatibleMethod("getUnlocks"); // 1005C37B -> sub_1005A9B0 + ns[i]->registerNativeCompatibleMethod("refreshUnlocks"); // 1005C3D3 -> sub_1005A3B0 + ns[i]->registerNativeCompatibleMethod("getRankNotificationLevel"); // 1005C743 -> sub_1005A1E0 + ns[i]->registerNativeCompatibleMethod("getPreviousRankLevel"); // 1005C79B -> sub_10059E00 + ns[i]->registerNativeCompatibleMethod("getNextRankLevel"); // 1005C7F3 -> sub_10059EE0 + ns[i]->registerNativeCompatibleMethod("getRoadKills"); // 1005C8FB -> sub_1005BAE0 + ns[i]->registerNativeCompatibleMethod("getOpponentKills"); // 1005CB0B -> sub_1005B0E0 + ns[i]->registerNativeCompatibleMethod("getVictimKills"); // 1005CC13 -> sub_1005B1A0 + } + else if (::strcmp(n, "Profile") == 0) + { + ns[i]->registerNativeCompatibleMethod("searchUniquePlayer"); // 1006158B -> sub_10060D80 + ns[i]->registerNativeCompatibleMethod("searchPlayer"); // 100615E3 -> sub_1005E2A0 + ns[i]->registerNativeCompatibleMethod("setComparePlayer"); // 1006163B -> sub_1005D350 + ns[i]->registerNativeCompatibleMethod("clearComparePlayer"); // 10061693 -> sub_1005D080 + ns[i]->registerNativeCompatibleMethod("getStatPlayer"); // 10061743 -> sub_1005E100 + ns[i]->registerNativeCompatibleMethod("getUseAdvancedServerBrowser"); // 1006184B -> sub_1005DDD0 + ns[i]->registerNativeCompatibleMethod("setUseAdvancedServerBrowser"); // 100618A3 -> sub_1005D220 + ns[i]->registerNativeCompatibleMethod("deleteLocalProfile"); // 10061AB3 -> sub_1005DCE0 + ns[i]->registerNativeCompatibleMethod("getSprint"); // 10061C6B -> sub_1005F4A0 + ns[i]->registerNativeCompatibleMethod("newGamespyProfile"); // 10061F83 -> sub_1005DA70 + ns[i]->registerNativeCompatibleMethod("deleteCurrentProfile"); // 10061FDB -> sub_1005D800 + ns[i]->registerNativeCompatibleMethod("getSelectedAge"); // 100621EB -> sub_1005D5B0 + ns[i]->registerNativeCompatibleMethod("setSelectedAge"); // 10062243 -> sub_1005D190 + ns[i]->registerNativeCompatibleMethod("getMinimumAge"); // 1006229B -> sub_1005D050 + ns[i]->registerNativeCompatibleMethod("getNumOnlineProfiles"); // 1006234B -> sub_1005FD90 + ns[i]->registerNativeCompatibleMethod("getNumOfflineProfiles"); // 100623A3 -> sub_1005FEE0 + ns[i]->registerNativeCompatibleMethod("setNamePrefix"); // 10062453 -> sub_1005D110 + } + else if (::strcmp(n, "ServerInfo") == 0) + { + ns[i]->registerNativeCompatibleMethod("getSponsorText"); // 100631E0 -> sub_10062940 + ns[i]->registerNativeCompatibleMethod("getMapName"); // 100632F3 -> sub_10062BA0 + ns[i]->registerNativeCompatibleMethod("getMaxPlayers"); // 1006334C -> sub_10062C50 + ns[i]->registerNativeCompatibleMethod("getGameModeTitle"); // 100633A5 -> sub_10062CF0 + ns[i]->registerNativeCompatibleMethod("getGameModeDescription"); // 100633FE -> sub_10062DA0 + ns[i]->registerNativeCompatibleMethod("getBackgroundTitle"); // 10063457 -> sub_10062E50 + ns[i]->registerNativeCompatibleMethod("getBackgroundDescription"); // 100634B0 -> sub_10062F00 + } + else if (::strcmp(n, "Shader") == 0) + { + ns[i]->registerNativeCompatibleMethod("setShader"); // 10068B16 -> sub_10068A10 + } + else if (::strcmp(n, "Singleplay") == 0) + { + ns[i]->registerNativeCompatibleMethod("chooseMission"); // 10068DDA -> sub_10068C10 + ns[i]->registerNativeCompatibleMethod("getBotSkills"); // 10068E3F -> sub_10068BF0 + ns[i]->registerNativeCompatibleMethod("setBotSkills"); // 10068E9C -> sub_10068C00 + } + else if (::strcmp(n, "Sound") == 0) + { + ns[i]->registerNativeCompatibleMethod("voipInitialize"); // 1006A313 -> sub_10069010 + ns[i]->registerNativeCompatibleMethod("voipSetEnable"); // 1006A36B -> sub_100692B0 + ns[i]->registerNativeCompatibleMethod("voipGetEnable"); // 1006A3C3 -> sub_100693C0 + ns[i]->registerNativeCompatibleMethod("voipSetBoost"); // 1006A41B -> sub_10069BA0 + ns[i]->registerNativeCompatibleMethod("voipGetBoost"); // 1006A473 -> sub_10069CA0 + ns[i]->registerNativeCompatibleMethod("voipStartTest"); // 1006A4CB -> sub_100694E0 + ns[i]->registerNativeCompatibleMethod("voipSetTransmitVolume"); // 1006A57B -> sub_10069750 + ns[i]->registerNativeCompatibleMethod("voipGetTransmitVolume"); // 1006A5D3 -> sub_10069840 + ns[i]->registerNativeCompatibleMethod("voipSetRecieveVolume"); // 1006A62B -> sub_100698C0 + ns[i]->registerNativeCompatibleMethod("voipGetRecieveVolume"); // 1006A683 -> sub_100699B0 + ns[i]->registerNativeCompatibleMethod("voipSetThresholdVolume"); // 1006A6DB -> sub_10069A30 + ns[i]->registerNativeCompatibleMethod("voipGetThresholdVolume"); // 1006A733 -> sub_10069B30 + ns[i]->registerNativeCompatibleMethod("voipIsBoostEnabled"); // 1006A83B -> sub_10069D80 + ns[i]->registerNativeCompatibleMethod("voipSendingVoice"); // 1006A893 -> sub_10069FE0 + ns[i]->registerNativeCompatibleMethod("voipGetSendingVoiceVolume"); // 1006A8EB -> sub_1006A0F0 + ns[i]->registerNativeCompatibleMethod("voipSetUsePushToTalk"); // 1006A943 -> sub_10069E10 + ns[i]->registerNativeCompatibleMethod("voipGetUsePushToTalk"); // 1006A99B -> sub_10069F50 + } + } +} + +// ---- dice.bf2.HapticSettings (the Falcon force-feedback page) ------------------------------------ +// 265 rows, registered by the HapticSettings registrar (0x10044590). The rows fall into 31 code +// shapes; each shape was read once in full and the per-row constants (vtable slots, components) +// extracted from every row by comparing the rows of a shape constant by constant. +// IHapticSettings' slot order (Game/HapticSettings.h, 505 slots, +0x10 first) matches every +// "+XX" annotation there; the slot each row calls is named in its body. + +// dword_100F8530: the page the recoil rows read (0 infantry weapons, otherwise vehicle weapons). +static int s_hapticSettingsPage = 0; + +static IHapticSettings* hapticSettings() +{ + return static_cast(classManager->getSingleton(renddx9abi::HostString("HapticSettings"))); +} + +// unk_100F3870: the three threshold names (static initialiser 0x100D5D40). The setters search the +// three (`cmp edi, 54h`); the getters' loop bound is 0x16C, thirteen 28-byte slots, so a name that is +// none of the three walks into the adjacent DLL globals (0x100F38C4..) in the shipped image. +// [CHOSEN, not recovered] The port searches the three for both and answers -1 for anything else, +// which is what the setters do. +static int hapticThresholdLevel(const std::string& key) +{ + static const char* const kNames[3] = { + "BFHQ_physicsthresholdlow", "BFHQ_physicsthresholdmedium", "BFHQ_physicsthresholdhigh" }; + for (int i = 0; i < 3; ++i) + if (key.compare(kNames[i]) == 0) + return i; + return -1; +} + +// The two weapon-name tables (static initialiser 0x100D5D80 / 0x100D5E60): unk_100F6C70, the 13 +// infantry names (0x16C bytes), and unk_100F3310, the 7 vehicle names (0xC4 bytes). The +// getWeaponInitial rows read single slots of them (0x100F6C70 [0], 0x100F3310 [0], 0x100F3348 [2], +// 0x100F3364 [3]). +static const char* const kHapticInfantryWeapons[13] = { + "BFHQ_assaultrifles", "BFHQ_grenadelauncher", "BFHQ_carbines", "BFHQ_lightmachineguns", + "BFHQ_sniperrifles", "BFHQ_pistols", "BFHQ_ataa", "BFHQ_submachineguns", "BFHQ_shotguns", + "BFHQ_knife", "BFHQ_defibrillator", "BFHQ_explosives", "BFHQ_handgrenade" }; +static const char* const kHapticVehicleWeapons[7] = { + "BFHQ_v_lightmachineguns", "BFHQ_v_heavymachineguns", "BFHQ_v_helicopterguns", + "BFHQ_v_airplaneguns", "BFHQ_v_missiles", "BFHQ_v_tankcannons", "BFHQ_v_tankmachineguns" }; + +// The recoil rows' weapon class: page 0 searches the 13 infantry names and answers the index; +// another page searches the 7 vehicle names and answers index + 100 (0x64). No match answers -1. +static int hapticWeaponClass(const std::string& key) +{ + if (s_hapticSettingsPage == 0) + { + for (int i = 0; i < 13; ++i) + if (key.compare(kHapticInfantryWeapons[i]) == 0) + return i; + return -1; + } + for (int i = 0; i < 7; ++i) + if (key.compare(kHapticVehicleWeapons[i]) == 0) + return i + 100; + return -1; +} + +// The two list builders are declared with the other getListEntries branches inside SwiffPlayer.cpp's +// anonymous namespace; their definitions join it. +namespace { + +// One selector row (both branches): the row keyed by the table name (sub_1001C770), its localised +// text as a dice String column (sub_10013600 + sub_1001CB80), and "selected" = 1 on the first row +// only (sub_10019970). The running count starts at 0 (edi, stored over the third argument at +// 0x1002289C) and is the published totalCount (sub_10019B00). +static void pushHapticSelectRow(ListResult& r, ListHost h, const char* name, int& count) +{ + r.beginRowStr(name); + pushLocalised(r, h, name); + if (count == 0) + r.setInt("selected", 1); + ++count; +} + +// General.getListEntries "weaponselect" (0x10030F66..0x1003136F): the rows follow the page +// (dword_100F8530, jump table 0x100316B0). 0: the 13 infantry names. 1 (land): the vehicle names +// except [2] helicopter and [3] airplane guns. 2 (air): [3] airplane guns and [4] missiles. +// 3 (heli): [2] helicopter guns and [4] missiles. 4 (sea): [0] alone. Any other page: no row. +static void listHapticWeaponSelect(const gameswf::fn_call& fn, ListResult& r, ListHost h) +{ + r.begin(); + int count = 0; + switch (s_hapticSettingsPage) + { + case 0: + for (int i = 0; i < 13; ++i) + pushHapticSelectRow(r, h, kHapticInfantryWeapons[i], count); + break; + case 1: + for (int i = 0; i < 7; ++i) + if (i != 2 && i != 3) + pushHapticSelectRow(r, h, kHapticVehicleWeapons[i], count); + break; + case 2: + for (int i = 0; i < 7; ++i) + if (i == 3 || i == 4) + pushHapticSelectRow(r, h, kHapticVehicleWeapons[i], count); + break; + case 3: + for (int i = 0; i < 7; ++i) + if (i == 2 || i == 4) + pushHapticSelectRow(r, h, kHapticVehicleWeapons[i], count); + break; + case 4: + pushHapticSelectRow(r, h, kHapticVehicleWeapons[0], count); + break; + default: + break; + } + r.setTotalCount(count); + fn.result->set_as_object_interface(r.arr.get_ptr()); +} + +// General.getListEntries "thresholdselect" (0x10031374..0x1003147B): the three threshold names +// (unk_100F3870), the first selected; every page. +static void listHapticThresholdSelect(const gameswf::fn_call& fn, ListResult& r, ListHost h) +{ + static const char* const kNames[3] = { + "BFHQ_physicsthresholdlow", "BFHQ_physicsthresholdmedium", "BFHQ_physicsthresholdhigh" }; + r.begin(); + int count = 0; + for (int i = 0; i < 3; ++i) + pushHapticSelectRow(r, h, kNames[i], count); + r.setTotalCount(count); + fn.result->set_as_object_interface(r.arr.get_ptr()); +} + +} // namespace + +// apply / reset tail (0x10035176..0x100351B4): LocalProfileManager by name; present with a current +// profile (+0x44): +0x40 saveCurrentProfile. +static void hapticSaveCurrentProfile() +{ + IBase* lpm = classManager->getSingleton(renddx9abi::HostString("LocalProfileManager")); + if (lpm && static_cast(lpm)->getCurrentProfile()) + (void) static_cast(lpm)->saveCurrentProfile(); +} + +// The selection page state: two DLL-global std::strings, default-constructed empty by the static +// initialisers 0x100D6250 / 0x100D6270 and touched by no other code. setWeaponSelect* stores the +// name into the first (0x100F8550, text at +4 = unk_100F8554); setThresholdSelect* into the second +// (0x100F8534, text unk_100F8538). All five categories share each string. +static std::string s_hapticWeaponSelect; // 0x100F8550 +static std::string s_hapticThresholdSelect; // 0x100F8534 + +// getWeaponInitial* (sub_10036D10 and its four twins): arg 0 to_number, fistp under a chop control +// word; 1 publishes the table name as a plain string (as_value type 1), anything else the name's +// dice String through sub_10036B70 - a third copy of the localised-String helper the VideoSettings +// rows use (sub_1006B310): the player's host first, an empty key's narrow String, otherwise the +0xA8 +// localisation in a wide one. +static void publishHapticInitialName(const gameswf::fn_call& fn, const char* name) +{ + if (bf2x87::toIntTruncate(fn.arg(0).to_number()) == 1) + fn.result->set_tu_string(tu_string(name)); + else + fn.result->set_as_object_interface(videoSettingsLocalisedString(renddx9abi::HostString(name))); +} + +// setThresholdSelect* (sub_10036DF0 and its four twins): arg 0 to_string; the result is the bool +// _stricmp(name, "BFHQ_physicsthresholdhigh") == 0, published before the name is stored. +static void storeHapticThresholdSelect(const gameswf::fn_call& fn) +{ + const std::string name(fn.arg(0).to_string()); + fn.result->set_bool(::_stricmp(name.c_str(), "BFHQ_physicsthresholdhigh") == 0); + s_hapticThresholdSelect = name; +} + +typedef Vec3 (IHapticSettings::*HapticVecGetter)(); +typedef void (IHapticSettings::*HapticVecSetter)(float x, float y, float z); + +// One vector store, the block every setter runs once for its own slot and, on a match, once more +// for the generic slot: HapticSettings by name three times, the getter twice (a, b), then the setter +// with the new value in its component and the rest taken from a and b: X (v, b.y, a.z), +// Y (b.x, v, a.z), Z (b.x, a.y, v). The mirror passes of the vehicle rows reach the singleton through +// sub_10035100, the same lookup. +static void hapticStoreComponent(HapticVecGetter get, HapticVecSetter set, int component, float value) +{ + IHapticSettings* first = hapticSettings(); + IHapticSettings* second = hapticSettings(); + IHapticSettings* target = hapticSettings(); + const Vec3 a = (first->*get)(); + const Vec3 b = (second->*get)(); + if (component == 0) + (target->*set)(value, b.y, a.z); + else if (component == 1) + (target->*set)(b.x, value, a.z); + else + (target->*set)(b.x, a.y, value); +} + +// The local player's vehicle category the vehicle rows compare against (template +0x22C, the +// IPlayerControlObjectTemplate base, slot +0x24): LAND 0 (test eax, eax), SEA 1, AIR 2, HELI 3. +// SOLDIER rows test "on foot" instead. +enum HapticMirrorCategory { kHapticSoldier = -1, kHapticLand = 0, kHapticSea = 1, kHapticAir = 2, kHapticHeli = 3 }; + +// The 75 vector setters (sub_1003C5F0 .. sub_100436B0, one shape; constants per row checked against +// every row's disassembly): arg 0 to_number stored as float into the category slot, then +// playerManager +0x30 getLocalHumanPlayer. +// * SOLDIER rows: no local player, or the player on foot (+0x44 getVehicle == +0xA0 +// getDefaultVehicle): the value is mirrored into the generic slot. In a vehicle: nothing more. +// * Vehicle rows: no local player: nothing more. Otherwise the vehicle's template field (+0x14) is +// read before the on-foot test, on foot ends the row, and a vehicle whose template is taken as +// a PlayerControlObjectTemplate with no check (the shipped add 0x22C) and whose +// getVehicleCategory equals the row's category gets the mirror (port guard: see the body). +static void hapticVectorSetter(const gameswf::fn_call& fn, HapticVecGetter get, HapticVecSetter set, + int component, int category, + HapticVecGetter mirrorGet, HapticVecSetter mirrorSet) +{ + const float value = static_cast(fn.arg(0).to_number()); + hapticStoreComponent(get, set, component, value); + world::IPlayer* player = reinterpret_cast(playerManager)->getLocalHumanPlayer(); // +0x30 + if (category == kHapticSoldier) + { + if (player && player->getVehicle() != player->getDefaultVehicle()) // +0x44 / +0xA0 + return; + hapticStoreComponent(mirrorGet, mirrorSet, component, value); + return; + } + if (!player) + return; + world::IObject* vehicle = player->getVehicle(); // +0x44 + // [CHOSEN, not recovered] Retail reads the template field (+0x14) here with no null test and, + // after the on-foot test, takes template + 0x22C as the IPlayerControlObjectTemplate base with + // no type test. A dead player's vehicle is the free camera (template MultiPlayerFreeCamera, a + // FreeCameraTemplate of 0x188 bytes): retail's +0x22C read lands past that object in whatever + // heap memory follows; the 64-bit port's layout puts a non-canonical pointer there (GP fault + // in the owner's in-game APPLY while dead, 2026-11-02). Neither out-of-bounds value can be + // reproduced, so the port asks the template for the interface (as SupplyObjectTemplate:: + // testVehicleType does) and treats a missing vehicle, a missing template or a template that is + // not a PlayerControlObjectTemplate as "category does not match": no mirror. The MSVC x86 + // build keeps the shipped code (byte-identical goal); only non-x86 builds take the guard. +#if defined(_MSC_VER) && defined(_M_IX86) + // Shipped x86 path, unchanged (no null or type test). + const world::IObjectTemplate* tmpl = vehicle->getTemplate(); // +0x14 + if (vehicle == player->getDefaultVehicle()) // +0xA0 + return; + const world::IPlayerControlObjectTemplate* pco = + static_cast(tmpl); // +0x22C + if (pco->getVehicleCategory() != category) // +0x24 + return; +#else + if (!vehicle) + return; + const world::IObjectTemplate* tmpl = vehicle->getTemplate(); // +0x14 + if (vehicle == player->getDefaultVehicle()) // +0xA0 + return; + const world::IPlayerControlObjectTemplate* pco = tmpl + ? static_cast( + tmpl->queryInterface(world::IID_IPlayerControlObjectTemplate)) // retail: +0x22C + : 0; + if (!pco || pco->getVehicleCategory() != category) // +0x24 + return; +#endif + hapticStoreComponent(mirrorGet, mirrorSet, component, value); +} + +// sub_10035140 "apply": HapticSettings +0x18, then LocalProfileManager by name: present with a current profile (+0x44), +0x40 saveCurrentProfile. +void as_hapticsettings_apply(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_apply"); + (void) hapticSettings()->apply(); // +0x18 + hapticSaveCurrentProfile(); +} + +// sub_100351C0 "reset": HapticSettings +0x20, then LocalProfileManager by name: present with a current profile (+0x44), +0x40 saveCurrentProfile. +void as_hapticsettings_reset(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_reset"); + hapticSettings()->setDefaultValues(); // +0x20 + hapticSaveCurrentProfile(); +} + +// sub_10035240 "cancel": HapticSettings +0x24 loadCurrentProfileFile. +void as_hapticsettings_cancel(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_cancel"); + hapticSettings()->loadCurrentProfileFile(); // +0x24 +} + +// sub_10037AB0 "getControlBoxLengthSOLDIER_X": HapticSettings by name, +0x54 getControlBoxLengthSOLDIER() by value, component x as a number. +void as_hapticsettings_getControlBoxLengthSOLDIER_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxLengthSOLDIER_X"); + const Vec3 v = hapticSettings()->getControlBoxLengthSOLDIER(); // +0x54 (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10037B30 "getControlBoxStiffnessSOLDIER_X": HapticSettings by name, +0x5C getControlBoxStiffnessSOLDIER() by value, component x as a number. +void as_hapticsettings_getControlBoxStiffnessSOLDIER_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxStiffnessSOLDIER_X"); + const Vec3 v = hapticSettings()->getControlBoxStiffnessSOLDIER(); // +0x5C (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10037BB0 "getControlBoxLengthLAND_X": HapticSettings by name, +0x84 getControlBoxLengthLAND() by value, component x as a number. +void as_hapticsettings_getControlBoxLengthLAND_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxLengthLAND_X"); + const Vec3 v = hapticSettings()->getControlBoxLengthLAND(); // +0x84 (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10037C40 "getControlBoxStiffnessLAND_X": HapticSettings by name, +0x8C getControlBoxStiffnessLAND() by value, component x as a number. +void as_hapticsettings_getControlBoxStiffnessLAND_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxStiffnessLAND_X"); + const Vec3 v = hapticSettings()->getControlBoxStiffnessLAND(); // +0x8C (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10037CD0 "getControlBoxLengthAIR_X": HapticSettings by name, +0x64 getControlBoxLengthAIR() by value, component x as a number. +void as_hapticsettings_getControlBoxLengthAIR_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxLengthAIR_X"); + const Vec3 v = hapticSettings()->getControlBoxLengthAIR(); // +0x64 (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10037D50 "getControlBoxStiffnessAIR_X": HapticSettings by name, +0x6C getControlBoxStiffnessAIR() by value, component x as a number. +void as_hapticsettings_getControlBoxStiffnessAIR_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxStiffnessAIR_X"); + const Vec3 v = hapticSettings()->getControlBoxStiffnessAIR(); // +0x6C (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10037DD0 "getControlBoxLengthHELI_X": HapticSettings by name, +0x74 getControlBoxLengthHELI() by value, component x as a number. +void as_hapticsettings_getControlBoxLengthHELI_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxLengthHELI_X"); + const Vec3 v = hapticSettings()->getControlBoxLengthHELI(); // +0x74 (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10037E50 "getControlBoxStiffnessHELI_X": HapticSettings by name, +0x7C getControlBoxStiffnessHELI() by value, component x as a number. +void as_hapticsettings_getControlBoxStiffnessHELI_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxStiffnessHELI_X"); + const Vec3 v = hapticSettings()->getControlBoxStiffnessHELI(); // +0x7C (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10037ED0 "getControlBoxLengthSEA_X": HapticSettings by name, +0x94 getControlBoxLengthSEA() by value, component x as a number. +void as_hapticsettings_getControlBoxLengthSEA_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxLengthSEA_X"); + const Vec3 v = hapticSettings()->getControlBoxLengthSEA(); // +0x94 (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10037F60 "getControlBoxStiffnessSEA_X": HapticSettings by name, +0x9C getControlBoxStiffnessSEA() by value, component x as a number. +void as_hapticsettings_getControlBoxStiffnessSEA_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxStiffnessSEA_X"); + const Vec3 v = hapticSettings()->getControlBoxStiffnessSEA(); // +0x9C (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10037FF0 "getControlBoxLengthSOLDIER_Y": HapticSettings by name, +0x54 getControlBoxLengthSOLDIER() by value, component y as a number. +void as_hapticsettings_getControlBoxLengthSOLDIER_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxLengthSOLDIER_Y"); + const Vec3 v = hapticSettings()->getControlBoxLengthSOLDIER(); // +0x54 (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10038070 "getControlBoxStiffnessSOLDIER_Y": HapticSettings by name, +0x5C getControlBoxStiffnessSOLDIER() by value, component y as a number. +void as_hapticsettings_getControlBoxStiffnessSOLDIER_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxStiffnessSOLDIER_Y"); + const Vec3 v = hapticSettings()->getControlBoxStiffnessSOLDIER(); // +0x5C (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_100380F0 "getControlBoxLengthLAND_Y": HapticSettings by name, +0x84 getControlBoxLengthLAND() by value, component y as a number. +void as_hapticsettings_getControlBoxLengthLAND_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxLengthLAND_Y"); + const Vec3 v = hapticSettings()->getControlBoxLengthLAND(); // +0x84 (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10038180 "getControlBoxStiffnessLAND_Y": HapticSettings by name, +0x8C getControlBoxStiffnessLAND() by value, component y as a number. +void as_hapticsettings_getControlBoxStiffnessLAND_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxStiffnessLAND_Y"); + const Vec3 v = hapticSettings()->getControlBoxStiffnessLAND(); // +0x8C (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10038210 "getControlBoxLengthAIR_Y": HapticSettings by name, +0x64 getControlBoxLengthAIR() by value, component y as a number. +void as_hapticsettings_getControlBoxLengthAIR_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxLengthAIR_Y"); + const Vec3 v = hapticSettings()->getControlBoxLengthAIR(); // +0x64 (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10038290 "getControlBoxStiffnessAIR_Y": HapticSettings by name, +0x6C getControlBoxStiffnessAIR() by value, component y as a number. +void as_hapticsettings_getControlBoxStiffnessAIR_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxStiffnessAIR_Y"); + const Vec3 v = hapticSettings()->getControlBoxStiffnessAIR(); // +0x6C (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10038310 "getControlBoxLengthHELI_Y": HapticSettings by name, +0x74 getControlBoxLengthHELI() by value, component y as a number. +void as_hapticsettings_getControlBoxLengthHELI_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxLengthHELI_Y"); + const Vec3 v = hapticSettings()->getControlBoxLengthHELI(); // +0x74 (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10038390 "getControlBoxStiffnessHELI_Y": HapticSettings by name, +0x7C getControlBoxStiffnessHELI() by value, component y as a number. +void as_hapticsettings_getControlBoxStiffnessHELI_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxStiffnessHELI_Y"); + const Vec3 v = hapticSettings()->getControlBoxStiffnessHELI(); // +0x7C (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10038410 "getControlBoxLengthSEA_Y": HapticSettings by name, +0x94 getControlBoxLengthSEA() by value, component y as a number. +void as_hapticsettings_getControlBoxLengthSEA_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxLengthSEA_Y"); + const Vec3 v = hapticSettings()->getControlBoxLengthSEA(); // +0x94 (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_100384A0 "getControlBoxStiffnessSEA_Y": HapticSettings by name, +0x9C getControlBoxStiffnessSEA() by value, component y as a number. +void as_hapticsettings_getControlBoxStiffnessSEA_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxStiffnessSEA_Y"); + const Vec3 v = hapticSettings()->getControlBoxStiffnessSEA(); // +0x9C (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10038530 "getControlBoxLengthSOLDIER_Z": HapticSettings by name, +0x54 getControlBoxLengthSOLDIER() by value, component z as a number. +void as_hapticsettings_getControlBoxLengthSOLDIER_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxLengthSOLDIER_Z"); + const Vec3 v = hapticSettings()->getControlBoxLengthSOLDIER(); // +0x54 (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_100385B0 "getControlBoxStiffnessSOLDIER_Z": HapticSettings by name, +0x5C getControlBoxStiffnessSOLDIER() by value, component z as a number. +void as_hapticsettings_getControlBoxStiffnessSOLDIER_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxStiffnessSOLDIER_Z"); + const Vec3 v = hapticSettings()->getControlBoxStiffnessSOLDIER(); // +0x5C (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_10038630 "getControlBoxLengthLAND_Z": HapticSettings by name, +0x84 getControlBoxLengthLAND() by value, component z as a number. +void as_hapticsettings_getControlBoxLengthLAND_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxLengthLAND_Z"); + const Vec3 v = hapticSettings()->getControlBoxLengthLAND(); // +0x84 (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_100386C0 "getControlBoxStiffnessLAND_Z": HapticSettings by name, +0x8C getControlBoxStiffnessLAND() by value, component z as a number. +void as_hapticsettings_getControlBoxStiffnessLAND_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxStiffnessLAND_Z"); + const Vec3 v = hapticSettings()->getControlBoxStiffnessLAND(); // +0x8C (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_10038750 "getControlBoxLengthAIR_Z": HapticSettings by name, +0x64 getControlBoxLengthAIR() by value, component z as a number. +void as_hapticsettings_getControlBoxLengthAIR_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxLengthAIR_Z"); + const Vec3 v = hapticSettings()->getControlBoxLengthAIR(); // +0x64 (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_100387D0 "getControlBoxStiffnessAIR_Z": HapticSettings by name, +0x6C getControlBoxStiffnessAIR() by value, component z as a number. +void as_hapticsettings_getControlBoxStiffnessAIR_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxStiffnessAIR_Z"); + const Vec3 v = hapticSettings()->getControlBoxStiffnessAIR(); // +0x6C (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_10038850 "getControlBoxLengthHELI_Z": HapticSettings by name, +0x74 getControlBoxLengthHELI() by value, component z as a number. +void as_hapticsettings_getControlBoxLengthHELI_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxLengthHELI_Z"); + const Vec3 v = hapticSettings()->getControlBoxLengthHELI(); // +0x74 (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_100388D0 "getControlBoxStiffnessHELI_Z": HapticSettings by name, +0x7C getControlBoxStiffnessHELI() by value, component z as a number. +void as_hapticsettings_getControlBoxStiffnessHELI_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxStiffnessHELI_Z"); + const Vec3 v = hapticSettings()->getControlBoxStiffnessHELI(); // +0x7C (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_10038950 "getControlBoxLengthSEA_Z": HapticSettings by name, +0x94 getControlBoxLengthSEA() by value, component z as a number. +void as_hapticsettings_getControlBoxLengthSEA_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxLengthSEA_Z"); + const Vec3 v = hapticSettings()->getControlBoxLengthSEA(); // +0x94 (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_100389E0 "getControlBoxStiffnessSEA_Z": HapticSettings by name, +0x9C getControlBoxStiffnessSEA() by value, component z as a number. +void as_hapticsettings_getControlBoxStiffnessSEA_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxStiffnessSEA_Z"); + const Vec3 v = hapticSettings()->getControlBoxStiffnessSEA(); // +0x9C (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_10038A70 "getAimSensitivitySOLDIER_X": HapticSettings by name, +0xBC getAimSensitivitySOLDIER() by value, component x as a number. +void as_hapticsettings_getAimSensitivitySOLDIER_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivitySOLDIER_X"); + const Vec3 v = hapticSettings()->getAimSensitivitySOLDIER(); // +0xBC (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10038B00 "getAimSensitivityLengthSOLDIER_X": HapticSettings by name, +0xC4 getAimSensitivityLengthSOLDIER() by value, component x as a number. +void as_hapticsettings_getAimSensitivityLengthSOLDIER_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLengthSOLDIER_X"); + const Vec3 v = hapticSettings()->getAimSensitivityLengthSOLDIER(); // +0xC4 (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10038B90 "getTurnSensitivitySOLDIER_X": HapticSettings by name, +0xCC getTurnSensitivitySOLDIER() by value, component x as a number. +void as_hapticsettings_getTurnSensitivitySOLDIER_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getTurnSensitivitySOLDIER_X"); + const Vec3 v = hapticSettings()->getTurnSensitivitySOLDIER(); // +0xCC (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10038C20 "getAimSensitivityLAND_X": HapticSettings by name, +0x104 getAimSensitivityLAND() by value, component x as a number. +void as_hapticsettings_getAimSensitivityLAND_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLAND_X"); + const Vec3 v = hapticSettings()->getAimSensitivityLAND(); // +0x104 (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10038CB0 "getAimSensitivityLengthLAND_X": HapticSettings by name, +0x10C getAimSensitivityLengthLAND() by value, component x as a number. +void as_hapticsettings_getAimSensitivityLengthLAND_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLengthLAND_X"); + const Vec3 v = hapticSettings()->getAimSensitivityLengthLAND(); // +0x10C (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10038D40 "getTurnSensitivityLAND_X": HapticSettings by name, +0x114 getTurnSensitivityLAND() by value, component x as a number. +void as_hapticsettings_getTurnSensitivityLAND_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getTurnSensitivityLAND_X"); + const Vec3 v = hapticSettings()->getTurnSensitivityLAND(); // +0x114 (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10038DD0 "getAimSensitivityAIR_X": HapticSettings by name, +0xD4 getAimSensitivityAIR() by value, component x as a number. +void as_hapticsettings_getAimSensitivityAIR_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityAIR_X"); + const Vec3 v = hapticSettings()->getAimSensitivityAIR(); // +0xD4 (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10038E60 "getAimSensitivityLengthAIR_X": HapticSettings by name, +0xDC getAimSensitivityLengthAIR() by value, component x as a number. +void as_hapticsettings_getAimSensitivityLengthAIR_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLengthAIR_X"); + const Vec3 v = hapticSettings()->getAimSensitivityLengthAIR(); // +0xDC (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10038EF0 "getTurnSensitivityAIR_X": HapticSettings by name, +0xE4 getTurnSensitivityAIR() by value, component x as a number. +void as_hapticsettings_getTurnSensitivityAIR_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getTurnSensitivityAIR_X"); + const Vec3 v = hapticSettings()->getTurnSensitivityAIR(); // +0xE4 (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10038F80 "getAimSensitivityHELI_X": HapticSettings by name, +0xEC getAimSensitivityHELI() by value, component x as a number. +void as_hapticsettings_getAimSensitivityHELI_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityHELI_X"); + const Vec3 v = hapticSettings()->getAimSensitivityHELI(); // +0xEC (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10039010 "getAimSensitivityLengthHELI_X": HapticSettings by name, +0xF4 getAimSensitivityLengthHELI() by value, component x as a number. +void as_hapticsettings_getAimSensitivityLengthHELI_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLengthHELI_X"); + const Vec3 v = hapticSettings()->getAimSensitivityLengthHELI(); // +0xF4 (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_100390A0 "getTurnSensitivityHELI_X": HapticSettings by name, +0xFC getTurnSensitivityHELI() by value, component x as a number. +void as_hapticsettings_getTurnSensitivityHELI_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getTurnSensitivityHELI_X"); + const Vec3 v = hapticSettings()->getTurnSensitivityHELI(); // +0xFC (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10039130 "getAimSensitivitySEA_X": HapticSettings by name, +0x11C getAimSensitivitySEA() by value, component x as a number. +void as_hapticsettings_getAimSensitivitySEA_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivitySEA_X"); + const Vec3 v = hapticSettings()->getAimSensitivitySEA(); // +0x11C (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_100391C0 "getAimSensitivityLengthSEA_X": HapticSettings by name, +0x124 getAimSensitivityLengthSEA() by value, component x as a number. +void as_hapticsettings_getAimSensitivityLengthSEA_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLengthSEA_X"); + const Vec3 v = hapticSettings()->getAimSensitivityLengthSEA(); // +0x124 (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10039250 "getTurnSensitivitySEA_X": HapticSettings by name, +0x12C getTurnSensitivitySEA() by value, component x as a number. +void as_hapticsettings_getTurnSensitivitySEA_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getTurnSensitivitySEA_X"); + const Vec3 v = hapticSettings()->getTurnSensitivitySEA(); // +0x12C (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_100392E0 "getAimSensitivitySOLDIER_Y": HapticSettings by name, +0xBC getAimSensitivitySOLDIER() by value, component y as a number. +void as_hapticsettings_getAimSensitivitySOLDIER_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivitySOLDIER_Y"); + const Vec3 v = hapticSettings()->getAimSensitivitySOLDIER(); // +0xBC (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10039370 "getAimSensitivityLengthSOLDIER_Y": HapticSettings by name, +0xC4 getAimSensitivityLengthSOLDIER() by value, component y as a number. +void as_hapticsettings_getAimSensitivityLengthSOLDIER_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLengthSOLDIER_Y"); + const Vec3 v = hapticSettings()->getAimSensitivityLengthSOLDIER(); // +0xC4 (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10039400 "getTurnSensitivitySOLDIER_Y": HapticSettings by name, +0xCC getTurnSensitivitySOLDIER() by value, component y as a number. +void as_hapticsettings_getTurnSensitivitySOLDIER_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getTurnSensitivitySOLDIER_Y"); + const Vec3 v = hapticSettings()->getTurnSensitivitySOLDIER(); // +0xCC (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10039490 "getAimSensitivityLAND_Y": HapticSettings by name, +0x104 getAimSensitivityLAND() by value, component y as a number. +void as_hapticsettings_getAimSensitivityLAND_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLAND_Y"); + const Vec3 v = hapticSettings()->getAimSensitivityLAND(); // +0x104 (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10039520 "getAimSensitivityLengthLAND_Y": HapticSettings by name, +0x10C getAimSensitivityLengthLAND() by value, component y as a number. +void as_hapticsettings_getAimSensitivityLengthLAND_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLengthLAND_Y"); + const Vec3 v = hapticSettings()->getAimSensitivityLengthLAND(); // +0x10C (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_100395B0 "getTurnSensitivityLAND_Y": HapticSettings by name, +0x114 getTurnSensitivityLAND() by value, component y as a number. +void as_hapticsettings_getTurnSensitivityLAND_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getTurnSensitivityLAND_Y"); + const Vec3 v = hapticSettings()->getTurnSensitivityLAND(); // +0x114 (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10039640 "getAimSensitivityAIR_Y": HapticSettings by name, +0xD4 getAimSensitivityAIR() by value, component y as a number. +void as_hapticsettings_getAimSensitivityAIR_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityAIR_Y"); + const Vec3 v = hapticSettings()->getAimSensitivityAIR(); // +0xD4 (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_100396D0 "getAimSensitivityLengthAIR_Y": HapticSettings by name, +0xDC getAimSensitivityLengthAIR() by value, component y as a number. +void as_hapticsettings_getAimSensitivityLengthAIR_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLengthAIR_Y"); + const Vec3 v = hapticSettings()->getAimSensitivityLengthAIR(); // +0xDC (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10039760 "getTurnSensitivityAIR_Y": HapticSettings by name, +0xE4 getTurnSensitivityAIR() by value, component y as a number. +void as_hapticsettings_getTurnSensitivityAIR_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getTurnSensitivityAIR_Y"); + const Vec3 v = hapticSettings()->getTurnSensitivityAIR(); // +0xE4 (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_100397F0 "getAimSensitivityHELI_Y": HapticSettings by name, +0xEC getAimSensitivityHELI() by value, component y as a number. +void as_hapticsettings_getAimSensitivityHELI_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityHELI_Y"); + const Vec3 v = hapticSettings()->getAimSensitivityHELI(); // +0xEC (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10039880 "getAimSensitivityLengthHELI_Y": HapticSettings by name, +0xF4 getAimSensitivityLengthHELI() by value, component y as a number. +void as_hapticsettings_getAimSensitivityLengthHELI_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLengthHELI_Y"); + const Vec3 v = hapticSettings()->getAimSensitivityLengthHELI(); // +0xF4 (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10039910 "getTurnSensitivityHELI_Y": HapticSettings by name, +0xFC getTurnSensitivityHELI() by value, component y as a number. +void as_hapticsettings_getTurnSensitivityHELI_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getTurnSensitivityHELI_Y"); + const Vec3 v = hapticSettings()->getTurnSensitivityHELI(); // +0xFC (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_100399A0 "getAimSensitivitySEA_Y": HapticSettings by name, +0x11C getAimSensitivitySEA() by value, component y as a number. +void as_hapticsettings_getAimSensitivitySEA_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivitySEA_Y"); + const Vec3 v = hapticSettings()->getAimSensitivitySEA(); // +0x11C (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10039A30 "getAimSensitivityLengthSEA_Y": HapticSettings by name, +0x124 getAimSensitivityLengthSEA() by value, component y as a number. +void as_hapticsettings_getAimSensitivityLengthSEA_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLengthSEA_Y"); + const Vec3 v = hapticSettings()->getAimSensitivityLengthSEA(); // +0x124 (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10039AC0 "getTurnSensitivitySEA_Y": HapticSettings by name, +0x12C getTurnSensitivitySEA() by value, component y as a number. +void as_hapticsettings_getTurnSensitivitySEA_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getTurnSensitivitySEA_Y"); + const Vec3 v = hapticSettings()->getTurnSensitivitySEA(); // +0x12C (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10039B50 "getAimSensitivitySOLDIER_Z": HapticSettings by name, +0xBC getAimSensitivitySOLDIER() by value, component z as a number. +void as_hapticsettings_getAimSensitivitySOLDIER_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivitySOLDIER_Z"); + const Vec3 v = hapticSettings()->getAimSensitivitySOLDIER(); // +0xBC (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_10039BE0 "getAimSensitivityLengthSOLDIER_Z": HapticSettings by name, +0xC4 getAimSensitivityLengthSOLDIER() by value, component z as a number. +void as_hapticsettings_getAimSensitivityLengthSOLDIER_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLengthSOLDIER_Z"); + const Vec3 v = hapticSettings()->getAimSensitivityLengthSOLDIER(); // +0xC4 (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_10039C70 "getTurnSensitivitySOLDIER_Z": HapticSettings by name, +0xCC getTurnSensitivitySOLDIER() by value, component z as a number. +void as_hapticsettings_getTurnSensitivitySOLDIER_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getTurnSensitivitySOLDIER_Z"); + const Vec3 v = hapticSettings()->getTurnSensitivitySOLDIER(); // +0xCC (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_10039D00 "getAimSensitivityLAND_Z": HapticSettings by name, +0x104 getAimSensitivityLAND() by value, component z as a number. +void as_hapticsettings_getAimSensitivityLAND_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLAND_Z"); + const Vec3 v = hapticSettings()->getAimSensitivityLAND(); // +0x104 (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_10039D90 "getAimSensitivityLengthLAND_Z": HapticSettings by name, +0x10C getAimSensitivityLengthLAND() by value, component z as a number. +void as_hapticsettings_getAimSensitivityLengthLAND_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLengthLAND_Z"); + const Vec3 v = hapticSettings()->getAimSensitivityLengthLAND(); // +0x10C (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_10039E20 "getTurnSensitivityLAND_Z": HapticSettings by name, +0x114 getTurnSensitivityLAND() by value, component z as a number. +void as_hapticsettings_getTurnSensitivityLAND_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getTurnSensitivityLAND_Z"); + const Vec3 v = hapticSettings()->getTurnSensitivityLAND(); // +0x114 (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_10039EB0 "getAimSensitivityAIR_Z": HapticSettings by name, +0xD4 getAimSensitivityAIR() by value, component z as a number. +void as_hapticsettings_getAimSensitivityAIR_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityAIR_Z"); + const Vec3 v = hapticSettings()->getAimSensitivityAIR(); // +0xD4 (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_10039F40 "getAimSensitivityLengthAIR_Z": HapticSettings by name, +0xDC getAimSensitivityLengthAIR() by value, component z as a number. +void as_hapticsettings_getAimSensitivityLengthAIR_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLengthAIR_Z"); + const Vec3 v = hapticSettings()->getAimSensitivityLengthAIR(); // +0xDC (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_10039FD0 "getTurnSensitivityAIR_Z": HapticSettings by name, +0xE4 getTurnSensitivityAIR() by value, component z as a number. +void as_hapticsettings_getTurnSensitivityAIR_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getTurnSensitivityAIR_Z"); + const Vec3 v = hapticSettings()->getTurnSensitivityAIR(); // +0xE4 (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_1003A060 "getAimSensitivityHELI_Z": HapticSettings by name, +0xEC getAimSensitivityHELI() by value, component z as a number. +void as_hapticsettings_getAimSensitivityHELI_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityHELI_Z"); + const Vec3 v = hapticSettings()->getAimSensitivityHELI(); // +0xEC (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_1003A0F0 "getAimSensitivityLengthHELI_Z": HapticSettings by name, +0xF4 getAimSensitivityLengthHELI() by value, component z as a number. +void as_hapticsettings_getAimSensitivityLengthHELI_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLengthHELI_Z"); + const Vec3 v = hapticSettings()->getAimSensitivityLengthHELI(); // +0xF4 (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_1003A180 "getTurnSensitivityHELI_Z": HapticSettings by name, +0xFC getTurnSensitivityHELI() by value, component z as a number. +void as_hapticsettings_getTurnSensitivityHELI_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getTurnSensitivityHELI_Z"); + const Vec3 v = hapticSettings()->getTurnSensitivityHELI(); // +0xFC (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_1003A210 "getAimSensitivitySEA_Z": HapticSettings by name, +0x11C getAimSensitivitySEA() by value, component z as a number. +void as_hapticsettings_getAimSensitivitySEA_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivitySEA_Z"); + const Vec3 v = hapticSettings()->getAimSensitivitySEA(); // +0x11C (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_1003A2A0 "getAimSensitivityLengthSEA_Z": HapticSettings by name, +0x124 getAimSensitivityLengthSEA() by value, component z as a number. +void as_hapticsettings_getAimSensitivityLengthSEA_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLengthSEA_Z"); + const Vec3 v = hapticSettings()->getAimSensitivityLengthSEA(); // +0x124 (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_1003A330 "getTurnSensitivitySEA_Z": HapticSettings by name, +0x12C getTurnSensitivitySEA() by value, component z as a number. +void as_hapticsettings_getTurnSensitivitySEA_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getTurnSensitivitySEA_Z"); + const Vec3 v = hapticSettings()->getTurnSensitivitySEA(); // +0x12C (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_1003A3C0 "getPhysicsSOLDIERScale_X": HapticSettings by name, +0x134 getPhysicsSOLDIERScale() by value, component x as a number. +void as_hapticsettings_getPhysicsSOLDIERScale_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsSOLDIERScale_X"); + const Vec3 v = hapticSettings()->getPhysicsSOLDIERScale(); // +0x134 (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_1003A450 "getPhysicsSOLDIERScale_Y": HapticSettings by name, +0x134 getPhysicsSOLDIERScale() by value, component y as a number. +void as_hapticsettings_getPhysicsSOLDIERScale_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsSOLDIERScale_Y"); + const Vec3 v = hapticSettings()->getPhysicsSOLDIERScale(); // +0x134 (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_1003A4E0 "getPhysicsSOLDIERScale_Z": HapticSettings by name, +0x134 getPhysicsSOLDIERScale() by value, component z as a number. +void as_hapticsettings_getPhysicsSOLDIERScale_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsSOLDIERScale_Z"); + const Vec3 v = hapticSettings()->getPhysicsSOLDIERScale(); // +0x134 (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_1003A570 "getPhysicsSOLDIERTransition": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x184 getPhysicsSOLDIERTransitionValue(level) as a number. +void as_hapticsettings_getPhysicsSOLDIERTransition(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsSOLDIERTransition"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsSOLDIERTransitionValue(level))); // +0x184 +} + +// sub_1003A670 "getPhysicsSOLDIERSmoothTime_X": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x19C getPhysicsSOLDIERSmoothTimeX(level) as a number. +void as_hapticsettings_getPhysicsSOLDIERSmoothTime_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsSOLDIERSmoothTime_X"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsSOLDIERSmoothTimeX(level))); // +0x19C +} + +// sub_1003A770 "getPhysicsSOLDIERSmoothTime_Y": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x1A4 getPhysicsSOLDIERSmoothTimeY(level) as a number. +void as_hapticsettings_getPhysicsSOLDIERSmoothTime_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsSOLDIERSmoothTime_Y"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsSOLDIERSmoothTimeY(level))); // +0x1A4 +} + +// sub_1003A870 "getPhysicsSOLDIERSmoothTime_Z": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x1AC getPhysicsSOLDIERSmoothTimeZ(level) as a number. +void as_hapticsettings_getPhysicsSOLDIERSmoothTime_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsSOLDIERSmoothTime_Z"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsSOLDIERSmoothTimeZ(level))); // +0x1AC +} + +// sub_1003A970 "getPhysicsLANDScale_X": HapticSettings by name, +0x1FC getPhysicsLANDScale() by value, component x as a number. +void as_hapticsettings_getPhysicsLANDScale_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsLANDScale_X"); + const Vec3 v = hapticSettings()->getPhysicsLANDScale(); // +0x1FC (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_1003AA00 "getPhysicsLANDScale_Y": HapticSettings by name, +0x1FC getPhysicsLANDScale() by value, component y as a number. +void as_hapticsettings_getPhysicsLANDScale_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsLANDScale_Y"); + const Vec3 v = hapticSettings()->getPhysicsLANDScale(); // +0x1FC (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_1003AA90 "getPhysicsLANDScale_Z": HapticSettings by name, +0x1FC getPhysicsLANDScale() by value, component z as a number. +void as_hapticsettings_getPhysicsLANDScale_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsLANDScale_Z"); + const Vec3 v = hapticSettings()->getPhysicsLANDScale(); // +0x1FC (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_1003AB20 "getPhysicsLANDTransition": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x24C getPhysicsLANDTransitionValue(level) as a number. +void as_hapticsettings_getPhysicsLANDTransition(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsLANDTransition"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsLANDTransitionValue(level))); // +0x24C +} + +// sub_1003AC20 "getPhysicsLANDSmoothTime_X": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x264 getPhysicsLANDSmoothTimeX(level) as a number. +void as_hapticsettings_getPhysicsLANDSmoothTime_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsLANDSmoothTime_X"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsLANDSmoothTimeX(level))); // +0x264 +} + +// sub_1003AD20 "getPhysicsLANDSmoothTime_Y": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x26C getPhysicsLANDSmoothTimeY(level) as a number. +void as_hapticsettings_getPhysicsLANDSmoothTime_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsLANDSmoothTime_Y"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsLANDSmoothTimeY(level))); // +0x26C +} + +// sub_1003AE20 "getPhysicsLANDSmoothTime_Z": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x274 getPhysicsLANDSmoothTimeZ(level) as a number. +void as_hapticsettings_getPhysicsLANDSmoothTime_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsLANDSmoothTime_Z"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsLANDSmoothTimeZ(level))); // +0x274 +} + +// sub_1003AF20 "getPhysicsAIRScale_X": HapticSettings by name, +0x2C4 getPhysicsAIRScale() by value, component x as a number. +void as_hapticsettings_getPhysicsAIRScale_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsAIRScale_X"); + const Vec3 v = hapticSettings()->getPhysicsAIRScale(); // +0x2C4 (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_1003AFB0 "getPhysicsAIRScale_Y": HapticSettings by name, +0x2C4 getPhysicsAIRScale() by value, component y as a number. +void as_hapticsettings_getPhysicsAIRScale_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsAIRScale_Y"); + const Vec3 v = hapticSettings()->getPhysicsAIRScale(); // +0x2C4 (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_1003B040 "getPhysicsAIRScale_Z": HapticSettings by name, +0x2C4 getPhysicsAIRScale() by value, component z as a number. +void as_hapticsettings_getPhysicsAIRScale_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsAIRScale_Z"); + const Vec3 v = hapticSettings()->getPhysicsAIRScale(); // +0x2C4 (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_1003B0D0 "getPhysicsAIRTransition": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x314 getPhysicsAIRTransitionValue(level) as a number. +void as_hapticsettings_getPhysicsAIRTransition(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsAIRTransition"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsAIRTransitionValue(level))); // +0x314 +} + +// sub_1003B1D0 "getPhysicsAIRSmoothTime_X": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x32C getPhysicsAIRSmoothTimeX(level) as a number. +void as_hapticsettings_getPhysicsAIRSmoothTime_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsAIRSmoothTime_X"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsAIRSmoothTimeX(level))); // +0x32C +} + +// sub_1003B2D0 "getPhysicsAIRSmoothTime_Y": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x334 getPhysicsAIRSmoothTimeY(level) as a number. +void as_hapticsettings_getPhysicsAIRSmoothTime_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsAIRSmoothTime_Y"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsAIRSmoothTimeY(level))); // +0x334 +} + +// sub_1003B3D0 "getPhysicsAIRSmoothTime_Z": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x33C getPhysicsAIRSmoothTimeZ(level) as a number. +void as_hapticsettings_getPhysicsAIRSmoothTime_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsAIRSmoothTime_Z"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsAIRSmoothTimeZ(level))); // +0x33C +} + +// sub_1003B4D0 "getPhysicsHELIScale_X": HapticSettings by name, +0x38C getPhysicsHELIScale() by value, component x as a number. +void as_hapticsettings_getPhysicsHELIScale_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsHELIScale_X"); + const Vec3 v = hapticSettings()->getPhysicsHELIScale(); // +0x38C (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_1003B560 "getPhysicsHELIScale_Y": HapticSettings by name, +0x38C getPhysicsHELIScale() by value, component y as a number. +void as_hapticsettings_getPhysicsHELIScale_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsHELIScale_Y"); + const Vec3 v = hapticSettings()->getPhysicsHELIScale(); // +0x38C (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_1003B5F0 "getPhysicsHELIScale_Z": HapticSettings by name, +0x38C getPhysicsHELIScale() by value, component z as a number. +void as_hapticsettings_getPhysicsHELIScale_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsHELIScale_Z"); + const Vec3 v = hapticSettings()->getPhysicsHELIScale(); // +0x38C (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_1003B680 "getPhysicsHELITransition": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x3DC getPhysicsHELITransitionValue(level) as a number. +void as_hapticsettings_getPhysicsHELITransition(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsHELITransition"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsHELITransitionValue(level))); // +0x3DC +} + +// sub_1003B780 "getPhysicsHELISmoothTime_X": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x3F4 getPhysicsHELISmoothTimeX(level) as a number. +void as_hapticsettings_getPhysicsHELISmoothTime_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsHELISmoothTime_X"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsHELISmoothTimeX(level))); // +0x3F4 +} + +// sub_1003B880 "getPhysicsHELISmoothTime_Y": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x3FC getPhysicsHELISmoothTimeY(level) as a number. +void as_hapticsettings_getPhysicsHELISmoothTime_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsHELISmoothTime_Y"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsHELISmoothTimeY(level))); // +0x3FC +} + +// sub_1003B980 "getPhysicsHELISmoothTime_Z": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x404 getPhysicsHELISmoothTimeZ(level) as a number. +void as_hapticsettings_getPhysicsHELISmoothTime_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsHELISmoothTime_Z"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsHELISmoothTimeZ(level))); // +0x404 +} + +// sub_1003BA80 "getPhysicsSEAScale_X": HapticSettings by name, +0x454 getPhysicsSEAScale() by value, component x as a number. +void as_hapticsettings_getPhysicsSEAScale_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsSEAScale_X"); + const Vec3 v = hapticSettings()->getPhysicsSEAScale(); // +0x454 (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_1003BB10 "getPhysicsSEAScale_Y": HapticSettings by name, +0x454 getPhysicsSEAScale() by value, component y as a number. +void as_hapticsettings_getPhysicsSEAScale_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsSEAScale_Y"); + const Vec3 v = hapticSettings()->getPhysicsSEAScale(); // +0x454 (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_1003BBA0 "getPhysicsSEAScale_Z": HapticSettings by name, +0x454 getPhysicsSEAScale() by value, component z as a number. +void as_hapticsettings_getPhysicsSEAScale_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsSEAScale_Z"); + const Vec3 v = hapticSettings()->getPhysicsSEAScale(); // +0x454 (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_1003BC30 "getPhysicsSEATransition": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x4A4 getPhysicsSEATransitionValue(level) as a number. +void as_hapticsettings_getPhysicsSEATransition(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsSEATransition"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsSEATransitionValue(level))); // +0x4A4 +} + +// sub_1003BD30 "getPhysicsSEASmoothTime_X": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x4BC getPhysicsSEASmoothTimeX(level) as a number. +void as_hapticsettings_getPhysicsSEASmoothTime_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsSEASmoothTime_X"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsSEASmoothTimeX(level))); // +0x4BC +} + +// sub_1003BE30 "getPhysicsSEASmoothTime_Y": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x4C4 getPhysicsSEASmoothTimeY(level) as a number. +void as_hapticsettings_getPhysicsSEASmoothTime_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsSEASmoothTime_Y"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsSEASmoothTimeY(level))); // +0x4C4 +} + +// sub_1003BF30 "getPhysicsSEASmoothTime_Z": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x4CC getPhysicsSEASmoothTimeZ(level) as a number. +void as_hapticsettings_getPhysicsSEASmoothTime_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsSEASmoothTime_Z"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsSEASmoothTimeZ(level))); // +0x4CC +} + +// sub_1003C030 "getDamageScale": HapticSettings by name, +0x51C as a number. +void as_hapticsettings_getDamageScale(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getDamageScale"); + fn.result->set_double(static_cast(hapticSettings()->getDamageScale())); // +0x51C +} + +// sub_1003C0B0 "getRecoilPunchScale": arg 0 to_string mapped to a weapon class (the page selects the infantry or the vehicle names), HapticSettings by name, +0x524 getRecoilPunchScale(class) as a number. +void as_hapticsettings_getRecoilPunchScale(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getRecoilPunchScale"); + const std::string key(fn.arg(0).to_string()); + const int weaponClass = hapticWeaponClass(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getRecoilPunchScale(weaponClass))); // +0x524 +} + +// sub_1003C200 "getRecoilPunchTime": arg 0 to_string mapped to a weapon class (the page selects the infantry or the vehicle names), HapticSettings by name, +0x52C getRecoilPunchTime(class) as a number. +void as_hapticsettings_getRecoilPunchTime(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getRecoilPunchTime"); + const std::string key(fn.arg(0).to_string()); + const int weaponClass = hapticWeaponClass(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getRecoilPunchTime(weaponClass))); // +0x52C +} + +// sub_1003C350 "getRecoilYawScale": arg 0 to_string mapped to a weapon class (the page selects the infantry or the vehicle names), HapticSettings by name, +0x534 getRecoilYawScale(class) as a number. +void as_hapticsettings_getRecoilYawScale(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getRecoilYawScale"); + const std::string key(fn.arg(0).to_string()); + const int weaponClass = hapticWeaponClass(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getRecoilYawScale(weaponClass))); // +0x534 +} + +// sub_1003C4A0 "getRecoilPitchScale": arg 0 to_string mapped to a weapon class (the page selects the infantry or the vehicle names), HapticSettings by name, +0x53C getRecoilPitchScale(class) as a number. +void as_hapticsettings_getRecoilPitchScale(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getRecoilPitchScale"); + const std::string key(fn.arg(0).to_string()); + const int weaponClass = hapticWeaponClass(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getRecoilPitchScale(weaponClass))); // +0x53C +} + +// sub_10043820 "setPhysicsSOLDIERScale_X": arg 0 as a float, three HapticSettings lookups, +0x134 twice, +0x138(value, second.y, first.z). +void as_hapticsettings_setPhysicsSOLDIERScale_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsSOLDIERScale_X"); + const float value = static_cast(fn.arg(0).to_number()); + IHapticSettings* a = hapticSettings(); + IHapticSettings* b = hapticSettings(); + IHapticSettings* c = hapticSettings(); + const Vec3 first = a->getPhysicsSOLDIERScale(); + const Vec3 second = b->getPhysicsSOLDIERScale(); + c->setPhysicsSOLDIERScale(value, second.y, first.z); // +0x138 +} + +// sub_10043900 "setPhysicsSOLDIERScale_Y": arg 0 as a float, three HapticSettings lookups, +0x134 twice, +0x138(second.x, value, first.z). +void as_hapticsettings_setPhysicsSOLDIERScale_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsSOLDIERScale_Y"); + const float value = static_cast(fn.arg(0).to_number()); + IHapticSettings* a = hapticSettings(); + IHapticSettings* b = hapticSettings(); + IHapticSettings* c = hapticSettings(); + const Vec3 first = a->getPhysicsSOLDIERScale(); + const Vec3 second = b->getPhysicsSOLDIERScale(); + c->setPhysicsSOLDIERScale(second.x, value, first.z); // +0x138 +} + +// sub_100439E0 "setPhysicsSOLDIERScale_Z": arg 0 as a float, three HapticSettings lookups, +0x134 twice, +0x138(second.x, first.y, value). +void as_hapticsettings_setPhysicsSOLDIERScale_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsSOLDIERScale_Z"); + const float value = static_cast(fn.arg(0).to_number()); + IHapticSettings* a = hapticSettings(); + IHapticSettings* b = hapticSettings(); + IHapticSettings* c = hapticSettings(); + const Vec3 first = a->getPhysicsSOLDIERScale(); + const Vec3 second = b->getPhysicsSOLDIERScale(); + c->setPhysicsSOLDIERScale(second.x, first.y, value); // +0x138 +} + +// sub_10035380 "setPhysicsSOLDIERTransition": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x188 setPhysicsSOLDIERTransitionValue(level, value). +void as_hapticsettings_setPhysicsSOLDIERTransition(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsSOLDIERTransition"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsSOLDIERTransitionValue(level, value); // +0x188 +} + +// sub_10035460 "setPhysicsSOLDIERSmoothTime_X": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x1A0 setPhysicsSOLDIERSmoothTimeX(level, (int) value). +void as_hapticsettings_setPhysicsSOLDIERSmoothTime_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsSOLDIERSmoothTime_X"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsSOLDIERSmoothTimeX(level, bf2x87::toIntTruncate(static_cast(value))); // +0x1A0 +} + +// sub_10035550 "setPhysicsSOLDIERSmoothTime_Y": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x1A8 setPhysicsSOLDIERSmoothTimeY(level, (int) value). +void as_hapticsettings_setPhysicsSOLDIERSmoothTime_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsSOLDIERSmoothTime_Y"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsSOLDIERSmoothTimeY(level, bf2x87::toIntTruncate(static_cast(value))); // +0x1A8 +} + +// sub_10035640 "setPhysicsSOLDIERSmoothTime_Z": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x1B0 setPhysicsSOLDIERSmoothTimeZ(level, (int) value). +void as_hapticsettings_setPhysicsSOLDIERSmoothTime_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsSOLDIERSmoothTime_Z"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsSOLDIERSmoothTimeZ(level, bf2x87::toIntTruncate(static_cast(value))); // +0x1B0 +} + +// sub_10043AC0 "setPhysicsLANDScale_X": arg 0 as a float, three HapticSettings lookups, +0x1FC twice, +0x200(value, second.y, first.z). +void as_hapticsettings_setPhysicsLANDScale_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsLANDScale_X"); + const float value = static_cast(fn.arg(0).to_number()); + IHapticSettings* a = hapticSettings(); + IHapticSettings* b = hapticSettings(); + IHapticSettings* c = hapticSettings(); + const Vec3 first = a->getPhysicsLANDScale(); + const Vec3 second = b->getPhysicsLANDScale(); + c->setPhysicsLANDScale(value, second.y, first.z); // +0x200 +} + +// sub_10043BA0 "setPhysicsLANDScale_Y": arg 0 as a float, three HapticSettings lookups, +0x1FC twice, +0x200(second.x, value, first.z). +void as_hapticsettings_setPhysicsLANDScale_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsLANDScale_Y"); + const float value = static_cast(fn.arg(0).to_number()); + IHapticSettings* a = hapticSettings(); + IHapticSettings* b = hapticSettings(); + IHapticSettings* c = hapticSettings(); + const Vec3 first = a->getPhysicsLANDScale(); + const Vec3 second = b->getPhysicsLANDScale(); + c->setPhysicsLANDScale(second.x, value, first.z); // +0x200 +} + +// sub_10043C80 "setPhysicsLANDScale_Z": arg 0 as a float, three HapticSettings lookups, +0x1FC twice, +0x200(second.x, first.y, value). +void as_hapticsettings_setPhysicsLANDScale_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsLANDScale_Z"); + const float value = static_cast(fn.arg(0).to_number()); + IHapticSettings* a = hapticSettings(); + IHapticSettings* b = hapticSettings(); + IHapticSettings* c = hapticSettings(); + const Vec3 first = a->getPhysicsLANDScale(); + const Vec3 second = b->getPhysicsLANDScale(); + c->setPhysicsLANDScale(second.x, first.y, value); // +0x200 +} + +// sub_10035730 "setPhysicsLANDTransition": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x250 setPhysicsLANDTransitionValue(level, value). +void as_hapticsettings_setPhysicsLANDTransition(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsLANDTransition"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsLANDTransitionValue(level, value); // +0x250 +} + +// sub_10035810 "setPhysicsLANDSmoothTime_X": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x268 setPhysicsLANDSmoothTimeX(level, (int) value). +void as_hapticsettings_setPhysicsLANDSmoothTime_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsLANDSmoothTime_X"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsLANDSmoothTimeX(level, bf2x87::toIntTruncate(static_cast(value))); // +0x268 +} + +// sub_10035900 "setPhysicsLANDSmoothTime_Y": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x270 setPhysicsLANDSmoothTimeY(level, (int) value). +void as_hapticsettings_setPhysicsLANDSmoothTime_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsLANDSmoothTime_Y"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsLANDSmoothTimeY(level, bf2x87::toIntTruncate(static_cast(value))); // +0x270 +} + +// sub_100359F0 "setPhysicsLANDSmoothTime_Z": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x278 setPhysicsLANDSmoothTimeZ(level, (int) value). +void as_hapticsettings_setPhysicsLANDSmoothTime_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsLANDSmoothTime_Z"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsLANDSmoothTimeZ(level, bf2x87::toIntTruncate(static_cast(value))); // +0x278 +} + +// sub_10043D60 "setPhysicsAIRScale_X": arg 0 as a float, three HapticSettings lookups, +0x2C4 twice, +0x2C8(value, second.y, first.z). +void as_hapticsettings_setPhysicsAIRScale_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsAIRScale_X"); + const float value = static_cast(fn.arg(0).to_number()); + IHapticSettings* a = hapticSettings(); + IHapticSettings* b = hapticSettings(); + IHapticSettings* c = hapticSettings(); + const Vec3 first = a->getPhysicsAIRScale(); + const Vec3 second = b->getPhysicsAIRScale(); + c->setPhysicsAIRScale(value, second.y, first.z); // +0x2C8 +} + +// sub_10043E40 "setPhysicsAIRScale_Y": arg 0 as a float, three HapticSettings lookups, +0x2C4 twice, +0x2C8(second.x, value, first.z). +void as_hapticsettings_setPhysicsAIRScale_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsAIRScale_Y"); + const float value = static_cast(fn.arg(0).to_number()); + IHapticSettings* a = hapticSettings(); + IHapticSettings* b = hapticSettings(); + IHapticSettings* c = hapticSettings(); + const Vec3 first = a->getPhysicsAIRScale(); + const Vec3 second = b->getPhysicsAIRScale(); + c->setPhysicsAIRScale(second.x, value, first.z); // +0x2C8 +} + +// sub_10043F20 "setPhysicsAIRScale_Z": arg 0 as a float, three HapticSettings lookups, +0x2C4 twice, +0x2C8(second.x, first.y, value). +void as_hapticsettings_setPhysicsAIRScale_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsAIRScale_Z"); + const float value = static_cast(fn.arg(0).to_number()); + IHapticSettings* a = hapticSettings(); + IHapticSettings* b = hapticSettings(); + IHapticSettings* c = hapticSettings(); + const Vec3 first = a->getPhysicsAIRScale(); + const Vec3 second = b->getPhysicsAIRScale(); + c->setPhysicsAIRScale(second.x, first.y, value); // +0x2C8 +} + +// sub_10035AE0 "setPhysicsAIRTransition": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x318 setPhysicsAIRTransitionValue(level, value). +void as_hapticsettings_setPhysicsAIRTransition(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsAIRTransition"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsAIRTransitionValue(level, value); // +0x318 +} + +// sub_10035BC0 "setPhysicsAIRSmoothTime_X": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x330 setPhysicsAIRSmoothTimeX(level, (int) value). +void as_hapticsettings_setPhysicsAIRSmoothTime_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsAIRSmoothTime_X"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsAIRSmoothTimeX(level, bf2x87::toIntTruncate(static_cast(value))); // +0x330 +} + +// sub_10035CB0 "setPhysicsAIRSmoothTime_Y": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x338 setPhysicsAIRSmoothTimeY(level, (int) value). +void as_hapticsettings_setPhysicsAIRSmoothTime_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsAIRSmoothTime_Y"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsAIRSmoothTimeY(level, bf2x87::toIntTruncate(static_cast(value))); // +0x338 +} + +// sub_10035DA0 "setPhysicsAIRSmoothTime_Z": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x340 setPhysicsAIRSmoothTimeZ(level, (int) value). +void as_hapticsettings_setPhysicsAIRSmoothTime_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsAIRSmoothTime_Z"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsAIRSmoothTimeZ(level, bf2x87::toIntTruncate(static_cast(value))); // +0x340 +} + +// sub_10044000 "setPhysicsHELIScale_X": arg 0 as a float, three HapticSettings lookups, +0x38C twice, +0x390(value, second.y, first.z). +void as_hapticsettings_setPhysicsHELIScale_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsHELIScale_X"); + const float value = static_cast(fn.arg(0).to_number()); + IHapticSettings* a = hapticSettings(); + IHapticSettings* b = hapticSettings(); + IHapticSettings* c = hapticSettings(); + const Vec3 first = a->getPhysicsHELIScale(); + const Vec3 second = b->getPhysicsHELIScale(); + c->setPhysicsHELIScale(value, second.y, first.z); // +0x390 +} + +// sub_100440E0 "setPhysicsHELIScale_Y": arg 0 as a float, three HapticSettings lookups, +0x38C twice, +0x390(second.x, value, first.z). +void as_hapticsettings_setPhysicsHELIScale_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsHELIScale_Y"); + const float value = static_cast(fn.arg(0).to_number()); + IHapticSettings* a = hapticSettings(); + IHapticSettings* b = hapticSettings(); + IHapticSettings* c = hapticSettings(); + const Vec3 first = a->getPhysicsHELIScale(); + const Vec3 second = b->getPhysicsHELIScale(); + c->setPhysicsHELIScale(second.x, value, first.z); // +0x390 +} + +// sub_100441C0 "setPhysicsHELIScale_Z": arg 0 as a float, three HapticSettings lookups, +0x38C twice, +0x390(second.x, first.y, value). +void as_hapticsettings_setPhysicsHELIScale_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsHELIScale_Z"); + const float value = static_cast(fn.arg(0).to_number()); + IHapticSettings* a = hapticSettings(); + IHapticSettings* b = hapticSettings(); + IHapticSettings* c = hapticSettings(); + const Vec3 first = a->getPhysicsHELIScale(); + const Vec3 second = b->getPhysicsHELIScale(); + c->setPhysicsHELIScale(second.x, first.y, value); // +0x390 +} + +// sub_10035E90 "setPhysicsHELITransition": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x3E0 setPhysicsHELITransitionValue(level, value). +void as_hapticsettings_setPhysicsHELITransition(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsHELITransition"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsHELITransitionValue(level, value); // +0x3E0 +} + +// sub_10035F70 "setPhysicsHELISmoothTime_X": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x3F8 setPhysicsHELISmoothTimeX(level, (int) value). +void as_hapticsettings_setPhysicsHELISmoothTime_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsHELISmoothTime_X"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsHELISmoothTimeX(level, bf2x87::toIntTruncate(static_cast(value))); // +0x3F8 +} + +// sub_10036060 "setPhysicsHELISmoothTime_Y": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x400 setPhysicsHELISmoothTimeY(level, (int) value). +void as_hapticsettings_setPhysicsHELISmoothTime_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsHELISmoothTime_Y"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsHELISmoothTimeY(level, bf2x87::toIntTruncate(static_cast(value))); // +0x400 +} + +// sub_10036150 "setPhysicsHELISmoothTime_Z": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x408 setPhysicsHELISmoothTimeZ(level, (int) value). +void as_hapticsettings_setPhysicsHELISmoothTime_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsHELISmoothTime_Z"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsHELISmoothTimeZ(level, bf2x87::toIntTruncate(static_cast(value))); // +0x408 +} + +// sub_100442A0 "setPhysicsSEAScale_X": arg 0 as a float, three HapticSettings lookups, +0x454 twice, +0x458(value, second.y, first.z). +void as_hapticsettings_setPhysicsSEAScale_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsSEAScale_X"); + const float value = static_cast(fn.arg(0).to_number()); + IHapticSettings* a = hapticSettings(); + IHapticSettings* b = hapticSettings(); + IHapticSettings* c = hapticSettings(); + const Vec3 first = a->getPhysicsSEAScale(); + const Vec3 second = b->getPhysicsSEAScale(); + c->setPhysicsSEAScale(value, second.y, first.z); // +0x458 +} + +// sub_10044380 "setPhysicsSEAScale_Y": arg 0 as a float, three HapticSettings lookups, +0x454 twice, +0x458(second.x, value, first.z). +void as_hapticsettings_setPhysicsSEAScale_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsSEAScale_Y"); + const float value = static_cast(fn.arg(0).to_number()); + IHapticSettings* a = hapticSettings(); + IHapticSettings* b = hapticSettings(); + IHapticSettings* c = hapticSettings(); + const Vec3 first = a->getPhysicsSEAScale(); + const Vec3 second = b->getPhysicsSEAScale(); + c->setPhysicsSEAScale(second.x, value, first.z); // +0x458 +} + +// sub_10044460 "setPhysicsSEAScale_Z": arg 0 as a float, three HapticSettings lookups, +0x454 twice, +0x458(second.x, first.y, value). +void as_hapticsettings_setPhysicsSEAScale_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsSEAScale_Z"); + const float value = static_cast(fn.arg(0).to_number()); + IHapticSettings* a = hapticSettings(); + IHapticSettings* b = hapticSettings(); + IHapticSettings* c = hapticSettings(); + const Vec3 first = a->getPhysicsSEAScale(); + const Vec3 second = b->getPhysicsSEAScale(); + c->setPhysicsSEAScale(second.x, first.y, value); // +0x458 +} + +// sub_10036240 "setPhysicsSEATransition": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x4A8 setPhysicsSEATransitionValue(level, value). +void as_hapticsettings_setPhysicsSEATransition(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsSEATransition"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsSEATransitionValue(level, value); // +0x4A8 +} + +// sub_10036320 "setPhysicsSEASmoothTime_X": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x4C0 setPhysicsSEASmoothTimeX(level, (int) value). +void as_hapticsettings_setPhysicsSEASmoothTime_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsSEASmoothTime_X"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsSEASmoothTimeX(level, bf2x87::toIntTruncate(static_cast(value))); // +0x4C0 +} + +// sub_10036410 "setPhysicsSEASmoothTime_Y": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x4C8 setPhysicsSEASmoothTimeY(level, (int) value). +void as_hapticsettings_setPhysicsSEASmoothTime_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsSEASmoothTime_Y"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsSEASmoothTimeY(level, bf2x87::toIntTruncate(static_cast(value))); // +0x4C8 +} + +// sub_10036500 "setPhysicsSEASmoothTime_Z": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x4D0 setPhysicsSEASmoothTimeZ(level, (int) value). +void as_hapticsettings_setPhysicsSEASmoothTime_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsSEASmoothTime_Z"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsSEASmoothTimeZ(level, bf2x87::toIntTruncate(static_cast(value))); // +0x4D0 +} + +// sub_100365F0 "setDamageScale": arg 0 as a float, then HapticSettings by name, +0x520. +void as_hapticsettings_setDamageScale(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setDamageScale"); + const float value = static_cast(fn.arg(0).to_number()); + hapticSettings()->setDamageScale(value); // +0x520 +} + +// sub_10036660 "setRecoilPunchScale": arg 0 to_string, arg 1 as a float, the weapon class, HapticSettings by name, +0x528 setRecoilPunchScale(class, value). +void as_hapticsettings_setRecoilPunchScale(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setRecoilPunchScale"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int weaponClass = hapticWeaponClass(key); + IHapticSettings* hs = hapticSettings(); + hs->setRecoilPunchScale(weaponClass, value); // +0x528 +} + +// sub_10036790 "setRecoilPunchTime": arg 0 to_string, arg 1 as a float, the weapon class, HapticSettings by name, +0x530 setRecoilPunchTime(class, value). +void as_hapticsettings_setRecoilPunchTime(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setRecoilPunchTime"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int weaponClass = hapticWeaponClass(key); + IHapticSettings* hs = hapticSettings(); + hs->setRecoilPunchTime(weaponClass, value); // +0x530 +} + +// sub_100368C0 "setRecoilYawScale": arg 0 to_string, arg 1 as a float, the weapon class, HapticSettings by name, +0x538 setRecoilYawScale(class, value). +void as_hapticsettings_setRecoilYawScale(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setRecoilYawScale"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int weaponClass = hapticWeaponClass(key); + IHapticSettings* hs = hapticSettings(); + hs->setRecoilYawScale(weaponClass, value); // +0x538 +} + +// sub_100369F0 "setRecoilPitchScale": arg 0 to_string, arg 1 as a float, the weapon class, HapticSettings by name, +0x540 setRecoilPitchScale(class, value). +void as_hapticsettings_setRecoilPitchScale(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setRecoilPitchScale"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int weaponClass = hapticWeaponClass(key); + IHapticSettings* hs = hapticSettings(); + hs->setRecoilPitchScale(weaponClass, value); // +0x540 +} + +// sub_10036B20 "setHapticSettingsPage": (int) arg 0 into dword_100F8530. +void as_hapticsettings_setHapticSettingsPage(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setHapticSettingsPage"); + s_hapticSettingsPage = bf2x87::toIntTruncate(fn.arg(0).to_number()); +} + +// sub_10044540 "getHapticSettingsPage": dword_100F8530 as a number. +void as_hapticsettings_getHapticSettingsPage(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getHapticSettingsPage"); + fn.result->set_double(static_cast(s_hapticSettingsPage)); +} + +// sub_1003C5F0 "setControlBoxLengthSOLDIER_X": vector setter, component x: +0x54 getControlBoxLengthSOLDIER / +0x58 setControlBoxLengthSOLDIER; mirror +0x54 getControlBoxLengthSOLDIER / +0x48 setControlBoxLength (on foot or no local player). +void as_hapticsettings_setControlBoxLengthSOLDIER_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxLengthSOLDIER_X"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxLengthSOLDIER, &IHapticSettings::setControlBoxLengthSOLDIER, 0, kHapticSoldier, + &IHapticSettings::getControlBoxLengthSOLDIER, &IHapticSettings::setControlBoxLength); +} + +// sub_1003C7D0 "setControlBoxStiffnessSOLDIER_X": vector setter, component x: +0x5C getControlBoxStiffnessSOLDIER / +0x60 setControlBoxStiffnessSOLDIER; mirror +0x5C getControlBoxStiffnessSOLDIER / +0x50 setControlBoxStiffness (on foot or no local player). +void as_hapticsettings_setControlBoxStiffnessSOLDIER_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxStiffnessSOLDIER_X"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxStiffnessSOLDIER, &IHapticSettings::setControlBoxStiffnessSOLDIER, 0, kHapticSoldier, + &IHapticSettings::getControlBoxStiffnessSOLDIER, &IHapticSettings::setControlBoxStiffness); +} + +// sub_1003D130 "setControlBoxLengthLAND_X": vector setter, component x: +0x84 getControlBoxLengthLAND / +0x88 setControlBoxLengthLAND; mirror +0x84 getControlBoxLengthLAND / +0x48 setControlBoxLength (vehicle category kHapticLand). +void as_hapticsettings_setControlBoxLengthLAND_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxLengthLAND_X"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxLengthLAND, &IHapticSettings::setControlBoxLengthLAND, 0, kHapticLand, + &IHapticSettings::getControlBoxLengthLAND, &IHapticSettings::setControlBoxLength); +} + +// sub_1003D2A0 "setControlBoxStiffnessLAND_X": vector setter, component x: +0x8C getControlBoxStiffnessLAND / +0x90 setControlBoxStiffnessLAND; mirror +0x8C getControlBoxStiffnessLAND / +0x50 setControlBoxStiffness (vehicle category kHapticLand). +void as_hapticsettings_setControlBoxStiffnessLAND_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxStiffnessLAND_X"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxStiffnessLAND, &IHapticSettings::setControlBoxStiffnessLAND, 0, kHapticLand, + &IHapticSettings::getControlBoxStiffnessLAND, &IHapticSettings::setControlBoxStiffness); +} + +// sub_1003D9D0 "setControlBoxLengthAIR_X": vector setter, component x: +0x64 getControlBoxLengthAIR / +0x68 setControlBoxLengthAIR; mirror +0x64 getControlBoxLengthAIR / +0x48 setControlBoxLength (vehicle category kHapticAir). +void as_hapticsettings_setControlBoxLengthAIR_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxLengthAIR_X"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxLengthAIR, &IHapticSettings::setControlBoxLengthAIR, 0, kHapticAir, + &IHapticSettings::getControlBoxLengthAIR, &IHapticSettings::setControlBoxLength); +} + +// sub_1003DB30 "setControlBoxStiffnessAIR_X": vector setter, component x: +0x6C getControlBoxStiffnessAIR / +0x70 setControlBoxStiffnessAIR; mirror +0x6C getControlBoxStiffnessAIR / +0x50 setControlBoxStiffness (vehicle category kHapticAir). +void as_hapticsettings_setControlBoxStiffnessAIR_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxStiffnessAIR_X"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxStiffnessAIR, &IHapticSettings::setControlBoxStiffnessAIR, 0, kHapticAir, + &IHapticSettings::getControlBoxStiffnessAIR, &IHapticSettings::setControlBoxStiffness); +} + +// sub_1003E210 "setControlBoxLengthHELI_X": vector setter, component x: +0x74 getControlBoxLengthHELI / +0x78 setControlBoxLengthHELI; mirror +0x74 getControlBoxLengthHELI / +0x48 setControlBoxLength (vehicle category kHapticHeli). +void as_hapticsettings_setControlBoxLengthHELI_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxLengthHELI_X"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxLengthHELI, &IHapticSettings::setControlBoxLengthHELI, 0, kHapticHeli, + &IHapticSettings::getControlBoxLengthHELI, &IHapticSettings::setControlBoxLength); +} + +// sub_1003E370 "setControlBoxStiffnessHELI_X": vector setter, component x: +0x7C getControlBoxStiffnessHELI / +0x80 setControlBoxStiffnessHELI; mirror +0x7C getControlBoxStiffnessHELI / +0x50 setControlBoxStiffness (vehicle category kHapticHeli). +void as_hapticsettings_setControlBoxStiffnessHELI_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxStiffnessHELI_X"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxStiffnessHELI, &IHapticSettings::setControlBoxStiffnessHELI, 0, kHapticHeli, + &IHapticSettings::getControlBoxStiffnessHELI, &IHapticSettings::setControlBoxStiffness); +} + +// sub_1003EA50 "setControlBoxLengthSEA_X": vector setter, component x: +0x94 getControlBoxLengthSEA / +0x98 setControlBoxLengthSEA; mirror +0x94 getControlBoxLengthSEA / +0x48 setControlBoxLength (vehicle category kHapticSea). +void as_hapticsettings_setControlBoxLengthSEA_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxLengthSEA_X"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxLengthSEA, &IHapticSettings::setControlBoxLengthSEA, 0, kHapticSea, + &IHapticSettings::getControlBoxLengthSEA, &IHapticSettings::setControlBoxLength); +} + +// sub_1003EBC0 "setControlBoxStiffnessSEA_X": vector setter, component x: +0x9C getControlBoxStiffnessSEA / +0xA0 setControlBoxStiffnessSEA; mirror +0x9C getControlBoxStiffnessSEA / +0x50 setControlBoxStiffness (vehicle category kHapticSea). +void as_hapticsettings_setControlBoxStiffnessSEA_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxStiffnessSEA_X"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxStiffnessSEA, &IHapticSettings::setControlBoxStiffnessSEA, 0, kHapticSea, + &IHapticSettings::getControlBoxStiffnessSEA, &IHapticSettings::setControlBoxStiffness); +} + +// sub_1003C9B0 "setControlBoxLengthSOLDIER_Y": vector setter, component y: +0x54 getControlBoxLengthSOLDIER / +0x58 setControlBoxLengthSOLDIER; mirror +0x54 getControlBoxLengthSOLDIER / +0x48 setControlBoxLength (on foot or no local player). +void as_hapticsettings_setControlBoxLengthSOLDIER_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxLengthSOLDIER_Y"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxLengthSOLDIER, &IHapticSettings::setControlBoxLengthSOLDIER, 1, kHapticSoldier, + &IHapticSettings::getControlBoxLengthSOLDIER, &IHapticSettings::setControlBoxLength); +} + +// sub_1003CB90 "setControlBoxStiffnessSOLDIER_Y": vector setter, component y: +0x5C getControlBoxStiffnessSOLDIER / +0x60 setControlBoxStiffnessSOLDIER; mirror +0x5C getControlBoxStiffnessSOLDIER / +0x50 setControlBoxStiffness (on foot or no local player). +void as_hapticsettings_setControlBoxStiffnessSOLDIER_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxStiffnessSOLDIER_Y"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxStiffnessSOLDIER, &IHapticSettings::setControlBoxStiffnessSOLDIER, 1, kHapticSoldier, + &IHapticSettings::getControlBoxStiffnessSOLDIER, &IHapticSettings::setControlBoxStiffness); +} + +// sub_1003D410 "setControlBoxLengthLAND_Y": vector setter, component y: +0x84 getControlBoxLengthLAND / +0x88 setControlBoxLengthLAND; mirror +0x84 getControlBoxLengthLAND / +0x48 setControlBoxLength (vehicle category kHapticLand). +void as_hapticsettings_setControlBoxLengthLAND_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxLengthLAND_Y"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxLengthLAND, &IHapticSettings::setControlBoxLengthLAND, 1, kHapticLand, + &IHapticSettings::getControlBoxLengthLAND, &IHapticSettings::setControlBoxLength); +} + +// sub_1003D580 "setControlBoxStiffnessLAND_Y": vector setter, component y: +0x8C getControlBoxStiffnessLAND / +0x90 setControlBoxStiffnessLAND; mirror +0x8C getControlBoxStiffnessLAND / +0x50 setControlBoxStiffness (vehicle category kHapticLand). +void as_hapticsettings_setControlBoxStiffnessLAND_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxStiffnessLAND_Y"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxStiffnessLAND, &IHapticSettings::setControlBoxStiffnessLAND, 1, kHapticLand, + &IHapticSettings::getControlBoxStiffnessLAND, &IHapticSettings::setControlBoxStiffness); +} + +// sub_1003DC90 "setControlBoxLengthAIR_Y": vector setter, component y: +0x64 getControlBoxLengthAIR / +0x68 setControlBoxLengthAIR; mirror +0x64 getControlBoxLengthAIR / +0x48 setControlBoxLength (vehicle category kHapticAir). +void as_hapticsettings_setControlBoxLengthAIR_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxLengthAIR_Y"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxLengthAIR, &IHapticSettings::setControlBoxLengthAIR, 1, kHapticAir, + &IHapticSettings::getControlBoxLengthAIR, &IHapticSettings::setControlBoxLength); +} + +// sub_1003DDF0 "setControlBoxStiffnessAIR_Y": vector setter, component y: +0x6C getControlBoxStiffnessAIR / +0x70 setControlBoxStiffnessAIR; mirror +0x6C getControlBoxStiffnessAIR / +0x50 setControlBoxStiffness (vehicle category kHapticAir). +void as_hapticsettings_setControlBoxStiffnessAIR_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxStiffnessAIR_Y"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxStiffnessAIR, &IHapticSettings::setControlBoxStiffnessAIR, 1, kHapticAir, + &IHapticSettings::getControlBoxStiffnessAIR, &IHapticSettings::setControlBoxStiffness); +} + +// sub_1003E4D0 "setControlBoxLengthHELI_Y": vector setter, component y: +0x74 getControlBoxLengthHELI / +0x78 setControlBoxLengthHELI; mirror +0x74 getControlBoxLengthHELI / +0x48 setControlBoxLength (vehicle category kHapticHeli). +void as_hapticsettings_setControlBoxLengthHELI_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxLengthHELI_Y"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxLengthHELI, &IHapticSettings::setControlBoxLengthHELI, 1, kHapticHeli, + &IHapticSettings::getControlBoxLengthHELI, &IHapticSettings::setControlBoxLength); +} + +// sub_1003E630 "setControlBoxStiffnessHELI_Y": vector setter, component y: +0x7C getControlBoxStiffnessHELI / +0x80 setControlBoxStiffnessHELI; mirror +0x7C getControlBoxStiffnessHELI / +0x50 setControlBoxStiffness (vehicle category kHapticHeli). +void as_hapticsettings_setControlBoxStiffnessHELI_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxStiffnessHELI_Y"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxStiffnessHELI, &IHapticSettings::setControlBoxStiffnessHELI, 1, kHapticHeli, + &IHapticSettings::getControlBoxStiffnessHELI, &IHapticSettings::setControlBoxStiffness); +} + +// sub_1003ED30 "setControlBoxLengthSEA_Y": vector setter, component y: +0x94 getControlBoxLengthSEA / +0x98 setControlBoxLengthSEA; mirror +0x94 getControlBoxLengthSEA / +0x48 setControlBoxLength (vehicle category kHapticSea). +void as_hapticsettings_setControlBoxLengthSEA_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxLengthSEA_Y"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxLengthSEA, &IHapticSettings::setControlBoxLengthSEA, 1, kHapticSea, + &IHapticSettings::getControlBoxLengthSEA, &IHapticSettings::setControlBoxLength); +} + +// sub_1003EEA0 "setControlBoxStiffnessSEA_Y": vector setter, component y: +0x9C getControlBoxStiffnessSEA / +0xA0 setControlBoxStiffnessSEA; mirror +0x9C getControlBoxStiffnessSEA / +0x50 setControlBoxStiffness (vehicle category kHapticSea). +void as_hapticsettings_setControlBoxStiffnessSEA_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxStiffnessSEA_Y"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxStiffnessSEA, &IHapticSettings::setControlBoxStiffnessSEA, 1, kHapticSea, + &IHapticSettings::getControlBoxStiffnessSEA, &IHapticSettings::setControlBoxStiffness); +} + +// sub_1003CD70 "setControlBoxLengthSOLDIER_Z": vector setter, component z: +0x54 getControlBoxLengthSOLDIER / +0x58 setControlBoxLengthSOLDIER; mirror +0x54 getControlBoxLengthSOLDIER / +0x48 setControlBoxLength (on foot or no local player). +void as_hapticsettings_setControlBoxLengthSOLDIER_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxLengthSOLDIER_Z"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxLengthSOLDIER, &IHapticSettings::setControlBoxLengthSOLDIER, 2, kHapticSoldier, + &IHapticSettings::getControlBoxLengthSOLDIER, &IHapticSettings::setControlBoxLength); +} + +// sub_1003CF50 "setControlBoxStiffnessSOLDIER_Z": vector setter, component z: +0x5C getControlBoxStiffnessSOLDIER / +0x60 setControlBoxStiffnessSOLDIER; mirror +0x5C getControlBoxStiffnessSOLDIER / +0x50 setControlBoxStiffness (on foot or no local player). +void as_hapticsettings_setControlBoxStiffnessSOLDIER_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxStiffnessSOLDIER_Z"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxStiffnessSOLDIER, &IHapticSettings::setControlBoxStiffnessSOLDIER, 2, kHapticSoldier, + &IHapticSettings::getControlBoxStiffnessSOLDIER, &IHapticSettings::setControlBoxStiffness); +} + +// sub_1003D6F0 "setControlBoxLengthLAND_Z": vector setter, component z: +0x84 getControlBoxLengthLAND / +0x88 setControlBoxLengthLAND; mirror +0x84 getControlBoxLengthLAND / +0x48 setControlBoxLength (vehicle category kHapticLand). +void as_hapticsettings_setControlBoxLengthLAND_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxLengthLAND_Z"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxLengthLAND, &IHapticSettings::setControlBoxLengthLAND, 2, kHapticLand, + &IHapticSettings::getControlBoxLengthLAND, &IHapticSettings::setControlBoxLength); +} + +// sub_1003D860 "setControlBoxStiffnessLAND_Z": vector setter, component z: +0x8C getControlBoxStiffnessLAND / +0x90 setControlBoxStiffnessLAND; mirror +0x8C getControlBoxStiffnessLAND / +0x50 setControlBoxStiffness (vehicle category kHapticLand). +void as_hapticsettings_setControlBoxStiffnessLAND_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxStiffnessLAND_Z"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxStiffnessLAND, &IHapticSettings::setControlBoxStiffnessLAND, 2, kHapticLand, + &IHapticSettings::getControlBoxStiffnessLAND, &IHapticSettings::setControlBoxStiffness); +} + +// sub_1003DF50 "setControlBoxLengthAIR_Z": vector setter, component z: +0x64 getControlBoxLengthAIR / +0x68 setControlBoxLengthAIR; mirror +0x64 getControlBoxLengthAIR / +0x48 setControlBoxLength (vehicle category kHapticAir). +void as_hapticsettings_setControlBoxLengthAIR_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxLengthAIR_Z"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxLengthAIR, &IHapticSettings::setControlBoxLengthAIR, 2, kHapticAir, + &IHapticSettings::getControlBoxLengthAIR, &IHapticSettings::setControlBoxLength); +} + +// sub_1003E0B0 "setControlBoxStiffnessAIR_Z": vector setter, component z: +0x6C getControlBoxStiffnessAIR / +0x70 setControlBoxStiffnessAIR; mirror +0x6C getControlBoxStiffnessAIR / +0x50 setControlBoxStiffness (vehicle category kHapticAir). +void as_hapticsettings_setControlBoxStiffnessAIR_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxStiffnessAIR_Z"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxStiffnessAIR, &IHapticSettings::setControlBoxStiffnessAIR, 2, kHapticAir, + &IHapticSettings::getControlBoxStiffnessAIR, &IHapticSettings::setControlBoxStiffness); +} + +// sub_1003E790 "setControlBoxLengthHELI_Z": vector setter, component z: +0x74 getControlBoxLengthHELI / +0x78 setControlBoxLengthHELI; mirror +0x74 getControlBoxLengthHELI / +0x48 setControlBoxLength (vehicle category kHapticHeli). +void as_hapticsettings_setControlBoxLengthHELI_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxLengthHELI_Z"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxLengthHELI, &IHapticSettings::setControlBoxLengthHELI, 2, kHapticHeli, + &IHapticSettings::getControlBoxLengthHELI, &IHapticSettings::setControlBoxLength); +} + +// sub_1003E8F0 "setControlBoxStiffnessHELI_Z": vector setter, component z: +0x7C getControlBoxStiffnessHELI / +0x80 setControlBoxStiffnessHELI; mirror +0x7C getControlBoxStiffnessHELI / +0x50 setControlBoxStiffness (vehicle category kHapticHeli). +void as_hapticsettings_setControlBoxStiffnessHELI_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxStiffnessHELI_Z"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxStiffnessHELI, &IHapticSettings::setControlBoxStiffnessHELI, 2, kHapticHeli, + &IHapticSettings::getControlBoxStiffnessHELI, &IHapticSettings::setControlBoxStiffness); +} + +// sub_1003F010 "setControlBoxLengthSEA_Z": vector setter, component z: +0x94 getControlBoxLengthSEA / +0x98 setControlBoxLengthSEA; mirror +0x94 getControlBoxLengthSEA / +0x48 setControlBoxLength (vehicle category kHapticSea). +void as_hapticsettings_setControlBoxLengthSEA_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxLengthSEA_Z"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxLengthSEA, &IHapticSettings::setControlBoxLengthSEA, 2, kHapticSea, + &IHapticSettings::getControlBoxLengthSEA, &IHapticSettings::setControlBoxLength); +} + +// sub_1003F180 "setControlBoxStiffnessSEA_Z": vector setter, component z: +0x9C getControlBoxStiffnessSEA / +0xA0 setControlBoxStiffnessSEA; mirror +0x9C getControlBoxStiffnessSEA / +0x50 setControlBoxStiffness (vehicle category kHapticSea). +void as_hapticsettings_setControlBoxStiffnessSEA_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxStiffnessSEA_Z"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxStiffnessSEA, &IHapticSettings::setControlBoxStiffnessSEA, 2, kHapticSea, + &IHapticSettings::getControlBoxStiffnessSEA, &IHapticSettings::setControlBoxStiffness); +} + +// sub_1003F2F0 "setAimSensitivitySOLDIER_X": vector setter, component x: +0xBC getAimSensitivitySOLDIER / +0xC0 setAimSensitivitySOLDIER; mirror +0xBC getAimSensitivitySOLDIER / +0xA8 setAimSensitivity (on foot or no local player). +void as_hapticsettings_setAimSensitivitySOLDIER_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivitySOLDIER_X"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivitySOLDIER, &IHapticSettings::setAimSensitivitySOLDIER, 0, kHapticSoldier, + &IHapticSettings::getAimSensitivitySOLDIER, &IHapticSettings::setAimSensitivity); +} + +// sub_1003F4E0 "setAimSensitivityLengthSOLDIER_X": vector setter, component x: +0xC4 getAimSensitivityLengthSOLDIER / +0xC8 setAimSensitivityLengthSOLDIER; mirror +0xBC getAimSensitivitySOLDIER / +0xB0 setAimSensitivityLength (on foot or no local player). The mirror reads the other two components through +0xBC getAimSensitivitySOLDIER, not +0xC4 (retail; the Y and Z rows use +0xC4). +void as_hapticsettings_setAimSensitivityLengthSOLDIER_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLengthSOLDIER_X"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLengthSOLDIER, &IHapticSettings::setAimSensitivityLengthSOLDIER, 0, kHapticSoldier, + &IHapticSettings::getAimSensitivitySOLDIER, &IHapticSettings::setAimSensitivityLength); +} + +// sub_1003F6D0 "setTurnSensitivitySOLDIER_X": vector setter, component x: +0xCC getTurnSensitivitySOLDIER / +0xD0 setTurnSensitivitySOLDIER; mirror +0xCC getTurnSensitivitySOLDIER / +0xB8 setTurnSensitivity (on foot or no local player). +void as_hapticsettings_setTurnSensitivitySOLDIER_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setTurnSensitivitySOLDIER_X"); + hapticVectorSetter(fn, &IHapticSettings::getTurnSensitivitySOLDIER, &IHapticSettings::setTurnSensitivitySOLDIER, 0, kHapticSoldier, + &IHapticSettings::getTurnSensitivitySOLDIER, &IHapticSettings::setTurnSensitivity); +} + +// sub_10040460 "setAimSensitivityLAND_X": vector setter, component x: +0x104 getAimSensitivityLAND / +0x108 setAimSensitivityLAND; mirror +0x104 getAimSensitivityLAND / +0xA8 setAimSensitivity (vehicle category kHapticLand). +void as_hapticsettings_setAimSensitivityLAND_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLAND_X"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLAND, &IHapticSettings::setAimSensitivityLAND, 0, kHapticLand, + &IHapticSettings::getAimSensitivityLAND, &IHapticSettings::setAimSensitivity); +} + +// sub_100405D0 "setAimSensitivityLengthLAND_X": vector setter, component x: +0x10C getAimSensitivityLengthLAND / +0x110 setAimSensitivityLengthLAND; mirror +0x10C getAimSensitivityLengthLAND / +0xB0 setAimSensitivityLength (vehicle category kHapticLand). +void as_hapticsettings_setAimSensitivityLengthLAND_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLengthLAND_X"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLengthLAND, &IHapticSettings::setAimSensitivityLengthLAND, 0, kHapticLand, + &IHapticSettings::getAimSensitivityLengthLAND, &IHapticSettings::setAimSensitivityLength); +} + +// sub_10040740 "setTurnSensitivityLAND_X": vector setter, component x: +0x114 getTurnSensitivityLAND / +0x118 setTurnSensitivityLAND; mirror +0x114 getTurnSensitivityLAND / +0xB8 setTurnSensitivity (vehicle category kHapticLand). +void as_hapticsettings_setTurnSensitivityLAND_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setTurnSensitivityLAND_X"); + hapticVectorSetter(fn, &IHapticSettings::getTurnSensitivityLAND, &IHapticSettings::setTurnSensitivityLAND, 0, kHapticLand, + &IHapticSettings::getTurnSensitivityLAND, &IHapticSettings::setTurnSensitivity); +} + +// sub_10041150 "setAimSensitivityAIR_X": vector setter, component x: +0xD4 getAimSensitivityAIR / +0xD8 setAimSensitivityAIR; mirror +0xD4 getAimSensitivityAIR / +0xA8 setAimSensitivity (vehicle category kHapticAir). +void as_hapticsettings_setAimSensitivityAIR_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityAIR_X"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityAIR, &IHapticSettings::setAimSensitivityAIR, 0, kHapticAir, + &IHapticSettings::getAimSensitivityAIR, &IHapticSettings::setAimSensitivity); +} + +// sub_100412C0 "setAimSensitivityLengthAIR_X": vector setter, component x: +0xDC getAimSensitivityLengthAIR / +0xE0 setAimSensitivityLengthAIR; mirror +0xDC getAimSensitivityLengthAIR / +0xB0 setAimSensitivityLength (vehicle category kHapticAir). +void as_hapticsettings_setAimSensitivityLengthAIR_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLengthAIR_X"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLengthAIR, &IHapticSettings::setAimSensitivityLengthAIR, 0, kHapticAir, + &IHapticSettings::getAimSensitivityLengthAIR, &IHapticSettings::setAimSensitivityLength); +} + +// sub_10041430 "setTurnSensitivityAIR_X": vector setter, component x: +0xE4 getTurnSensitivityAIR / +0xE8 setTurnSensitivityAIR; mirror +0xE4 getTurnSensitivityAIR / +0xB8 setTurnSensitivity (vehicle category kHapticAir). +void as_hapticsettings_setTurnSensitivityAIR_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setTurnSensitivityAIR_X"); + hapticVectorSetter(fn, &IHapticSettings::getTurnSensitivityAIR, &IHapticSettings::setTurnSensitivityAIR, 0, kHapticAir, + &IHapticSettings::getTurnSensitivityAIR, &IHapticSettings::setTurnSensitivity); +} + +// sub_10041E40 "setAimSensitivityHELI_X": vector setter, component x: +0xEC getAimSensitivityHELI / +0xF0 setAimSensitivityHELI; mirror +0xEC getAimSensitivityHELI / +0xA8 setAimSensitivity (vehicle category kHapticHeli). +void as_hapticsettings_setAimSensitivityHELI_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityHELI_X"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityHELI, &IHapticSettings::setAimSensitivityHELI, 0, kHapticHeli, + &IHapticSettings::getAimSensitivityHELI, &IHapticSettings::setAimSensitivity); +} + +// sub_10041FB0 "setAimSensitivityLengthHELI_X": vector setter, component x: +0xF4 getAimSensitivityLengthHELI / +0xF8 setAimSensitivityLengthHELI; mirror +0xF4 getAimSensitivityLengthHELI / +0xB0 setAimSensitivityLength (vehicle category kHapticHeli). +void as_hapticsettings_setAimSensitivityLengthHELI_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLengthHELI_X"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLengthHELI, &IHapticSettings::setAimSensitivityLengthHELI, 0, kHapticHeli, + &IHapticSettings::getAimSensitivityLengthHELI, &IHapticSettings::setAimSensitivityLength); +} + +// sub_10042120 "setTurnSensitivityHELI_X": vector setter, component x: +0xFC getTurnSensitivityHELI / +0x100 setTurnSensitivityHELI; mirror +0xFC getTurnSensitivityHELI / +0xB8 setTurnSensitivity (vehicle category kHapticHeli). +void as_hapticsettings_setTurnSensitivityHELI_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setTurnSensitivityHELI_X"); + hapticVectorSetter(fn, &IHapticSettings::getTurnSensitivityHELI, &IHapticSettings::setTurnSensitivityHELI, 0, kHapticHeli, + &IHapticSettings::getTurnSensitivityHELI, &IHapticSettings::setTurnSensitivity); +} + +// sub_10042B30 "setAimSensitivitySEA_X": vector setter, component x: +0x11C getAimSensitivitySEA / +0x120 setAimSensitivitySEA; mirror +0x11C getAimSensitivitySEA / +0xA8 setAimSensitivity (vehicle category kHapticSea). +void as_hapticsettings_setAimSensitivitySEA_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivitySEA_X"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivitySEA, &IHapticSettings::setAimSensitivitySEA, 0, kHapticSea, + &IHapticSettings::getAimSensitivitySEA, &IHapticSettings::setAimSensitivity); +} + +// sub_10042CA0 "setAimSensitivityLengthSEA_X": vector setter, component x: +0x124 getAimSensitivityLengthSEA / +0x128 setAimSensitivityLengthSEA; mirror +0x124 getAimSensitivityLengthSEA / +0xB0 setAimSensitivityLength (vehicle category kHapticSea). +void as_hapticsettings_setAimSensitivityLengthSEA_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLengthSEA_X"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLengthSEA, &IHapticSettings::setAimSensitivityLengthSEA, 0, kHapticSea, + &IHapticSettings::getAimSensitivityLengthSEA, &IHapticSettings::setAimSensitivityLength); +} + +// sub_10042E10 "setTurnSensitivitySEA_X": vector setter, component x: +0x12C getTurnSensitivitySEA / +0x130 setTurnSensitivitySEA; mirror +0x12C getTurnSensitivitySEA / +0xB8 setTurnSensitivity (vehicle category kHapticSea). +void as_hapticsettings_setTurnSensitivitySEA_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setTurnSensitivitySEA_X"); + hapticVectorSetter(fn, &IHapticSettings::getTurnSensitivitySEA, &IHapticSettings::setTurnSensitivitySEA, 0, kHapticSea, + &IHapticSettings::getTurnSensitivitySEA, &IHapticSettings::setTurnSensitivity); +} + +// sub_1003F8C0 "setAimSensitivitySOLDIER_Y": vector setter, component y: +0xBC getAimSensitivitySOLDIER / +0xC0 setAimSensitivitySOLDIER; mirror +0xBC getAimSensitivitySOLDIER / +0xA8 setAimSensitivity (on foot or no local player). +void as_hapticsettings_setAimSensitivitySOLDIER_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivitySOLDIER_Y"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivitySOLDIER, &IHapticSettings::setAimSensitivitySOLDIER, 1, kHapticSoldier, + &IHapticSettings::getAimSensitivitySOLDIER, &IHapticSettings::setAimSensitivity); +} + +// sub_1003FAB0 "setAimSensitivityLengthSOLDIER_Y": vector setter, component y: +0xC4 getAimSensitivityLengthSOLDIER / +0xC8 setAimSensitivityLengthSOLDIER; mirror +0xC4 getAimSensitivityLengthSOLDIER / +0xB0 setAimSensitivityLength (on foot or no local player). +void as_hapticsettings_setAimSensitivityLengthSOLDIER_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLengthSOLDIER_Y"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLengthSOLDIER, &IHapticSettings::setAimSensitivityLengthSOLDIER, 1, kHapticSoldier, + &IHapticSettings::getAimSensitivityLengthSOLDIER, &IHapticSettings::setAimSensitivityLength); +} + +// sub_1003FCA0 "setTurnSensitivitySOLDIER_Y": vector setter, component y: +0xCC getTurnSensitivitySOLDIER / +0xD0 setTurnSensitivitySOLDIER; mirror +0xCC getTurnSensitivitySOLDIER / +0xB8 setTurnSensitivity (on foot or no local player). +void as_hapticsettings_setTurnSensitivitySOLDIER_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setTurnSensitivitySOLDIER_Y"); + hapticVectorSetter(fn, &IHapticSettings::getTurnSensitivitySOLDIER, &IHapticSettings::setTurnSensitivitySOLDIER, 1, kHapticSoldier, + &IHapticSettings::getTurnSensitivitySOLDIER, &IHapticSettings::setTurnSensitivity); +} + +// sub_100408B0 "setAimSensitivityLAND_Y": vector setter, component y: +0x104 getAimSensitivityLAND / +0x108 setAimSensitivityLAND; mirror +0x104 getAimSensitivityLAND / +0xA8 setAimSensitivity (vehicle category kHapticLand). +void as_hapticsettings_setAimSensitivityLAND_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLAND_Y"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLAND, &IHapticSettings::setAimSensitivityLAND, 1, kHapticLand, + &IHapticSettings::getAimSensitivityLAND, &IHapticSettings::setAimSensitivity); +} + +// sub_10040A20 "setAimSensitivityLengthLAND_Y": vector setter, component y: +0x10C getAimSensitivityLengthLAND / +0x110 setAimSensitivityLengthLAND; mirror +0x10C getAimSensitivityLengthLAND / +0xB0 setAimSensitivityLength (vehicle category kHapticLand). +void as_hapticsettings_setAimSensitivityLengthLAND_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLengthLAND_Y"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLengthLAND, &IHapticSettings::setAimSensitivityLengthLAND, 1, kHapticLand, + &IHapticSettings::getAimSensitivityLengthLAND, &IHapticSettings::setAimSensitivityLength); +} + +// sub_10040B90 "setTurnSensitivityLAND_Y": vector setter, component y: +0x114 getTurnSensitivityLAND / +0x118 setTurnSensitivityLAND; mirror +0x114 getTurnSensitivityLAND / +0xB8 setTurnSensitivity (vehicle category kHapticLand). +void as_hapticsettings_setTurnSensitivityLAND_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setTurnSensitivityLAND_Y"); + hapticVectorSetter(fn, &IHapticSettings::getTurnSensitivityLAND, &IHapticSettings::setTurnSensitivityLAND, 1, kHapticLand, + &IHapticSettings::getTurnSensitivityLAND, &IHapticSettings::setTurnSensitivity); +} + +// sub_100415A0 "setAimSensitivityAIR_Y": vector setter, component y: +0xD4 getAimSensitivityAIR / +0xD8 setAimSensitivityAIR; mirror +0xD4 getAimSensitivityAIR / +0xA8 setAimSensitivity (vehicle category kHapticAir). +void as_hapticsettings_setAimSensitivityAIR_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityAIR_Y"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityAIR, &IHapticSettings::setAimSensitivityAIR, 1, kHapticAir, + &IHapticSettings::getAimSensitivityAIR, &IHapticSettings::setAimSensitivity); +} + +// sub_10041710 "setAimSensitivityLengthAIR_Y": vector setter, component y: +0xDC getAimSensitivityLengthAIR / +0xE0 setAimSensitivityLengthAIR; mirror +0xDC getAimSensitivityLengthAIR / +0xB0 setAimSensitivityLength (vehicle category kHapticAir). +void as_hapticsettings_setAimSensitivityLengthAIR_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLengthAIR_Y"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLengthAIR, &IHapticSettings::setAimSensitivityLengthAIR, 1, kHapticAir, + &IHapticSettings::getAimSensitivityLengthAIR, &IHapticSettings::setAimSensitivityLength); +} + +// sub_10041880 "setTurnSensitivityAIR_Y": vector setter, component y: +0xE4 getTurnSensitivityAIR / +0xE8 setTurnSensitivityAIR; mirror +0xE4 getTurnSensitivityAIR / +0xB8 setTurnSensitivity (vehicle category kHapticAir). +void as_hapticsettings_setTurnSensitivityAIR_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setTurnSensitivityAIR_Y"); + hapticVectorSetter(fn, &IHapticSettings::getTurnSensitivityAIR, &IHapticSettings::setTurnSensitivityAIR, 1, kHapticAir, + &IHapticSettings::getTurnSensitivityAIR, &IHapticSettings::setTurnSensitivity); +} + +// sub_10042290 "setAimSensitivityHELI_Y": vector setter, component y: +0xEC getAimSensitivityHELI / +0xF0 setAimSensitivityHELI; mirror +0xEC getAimSensitivityHELI / +0xA8 setAimSensitivity (vehicle category kHapticHeli). +void as_hapticsettings_setAimSensitivityHELI_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityHELI_Y"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityHELI, &IHapticSettings::setAimSensitivityHELI, 1, kHapticHeli, + &IHapticSettings::getAimSensitivityHELI, &IHapticSettings::setAimSensitivity); +} + +// sub_10042400 "setAimSensitivityLengthHELI_Y": vector setter, component y: +0xF4 getAimSensitivityLengthHELI / +0xF8 setAimSensitivityLengthHELI; mirror +0xF4 getAimSensitivityLengthHELI / +0xB0 setAimSensitivityLength (vehicle category kHapticHeli). +void as_hapticsettings_setAimSensitivityLengthHELI_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLengthHELI_Y"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLengthHELI, &IHapticSettings::setAimSensitivityLengthHELI, 1, kHapticHeli, + &IHapticSettings::getAimSensitivityLengthHELI, &IHapticSettings::setAimSensitivityLength); +} + +// sub_10042570 "setTurnSensitivityHELI_Y": vector setter, component y: +0xFC getTurnSensitivityHELI / +0x100 setTurnSensitivityHELI; mirror +0xFC getTurnSensitivityHELI / +0xB8 setTurnSensitivity (vehicle category kHapticHeli). +void as_hapticsettings_setTurnSensitivityHELI_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setTurnSensitivityHELI_Y"); + hapticVectorSetter(fn, &IHapticSettings::getTurnSensitivityHELI, &IHapticSettings::setTurnSensitivityHELI, 1, kHapticHeli, + &IHapticSettings::getTurnSensitivityHELI, &IHapticSettings::setTurnSensitivity); +} + +// sub_10042F80 "setAimSensitivitySEA_Y": vector setter, component y: +0x11C getAimSensitivitySEA / +0x120 setAimSensitivitySEA; mirror +0x11C getAimSensitivitySEA / +0xA8 setAimSensitivity (vehicle category kHapticSea). +void as_hapticsettings_setAimSensitivitySEA_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivitySEA_Y"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivitySEA, &IHapticSettings::setAimSensitivitySEA, 1, kHapticSea, + &IHapticSettings::getAimSensitivitySEA, &IHapticSettings::setAimSensitivity); +} + +// sub_100430F0 "setAimSensitivityLengthSEA_Y": vector setter, component y: +0x124 getAimSensitivityLengthSEA / +0x128 setAimSensitivityLengthSEA; mirror +0x124 getAimSensitivityLengthSEA / +0xB0 setAimSensitivityLength (vehicle category kHapticSea). +void as_hapticsettings_setAimSensitivityLengthSEA_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLengthSEA_Y"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLengthSEA, &IHapticSettings::setAimSensitivityLengthSEA, 1, kHapticSea, + &IHapticSettings::getAimSensitivityLengthSEA, &IHapticSettings::setAimSensitivityLength); +} + +// sub_10043260 "setTurnSensitivitySEA_Y": vector setter, component y: +0x12C getTurnSensitivitySEA / +0x130 setTurnSensitivitySEA; mirror +0x12C getTurnSensitivitySEA / +0xB8 setTurnSensitivity (vehicle category kHapticSea). +void as_hapticsettings_setTurnSensitivitySEA_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setTurnSensitivitySEA_Y"); + hapticVectorSetter(fn, &IHapticSettings::getTurnSensitivitySEA, &IHapticSettings::setTurnSensitivitySEA, 1, kHapticSea, + &IHapticSettings::getTurnSensitivitySEA, &IHapticSettings::setTurnSensitivity); +} + +// sub_1003FE90 "setAimSensitivitySOLDIER_Z": vector setter, component z: +0xBC getAimSensitivitySOLDIER / +0xC0 setAimSensitivitySOLDIER; mirror +0xBC getAimSensitivitySOLDIER / +0xA8 setAimSensitivity (on foot or no local player). +void as_hapticsettings_setAimSensitivitySOLDIER_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivitySOLDIER_Z"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivitySOLDIER, &IHapticSettings::setAimSensitivitySOLDIER, 2, kHapticSoldier, + &IHapticSettings::getAimSensitivitySOLDIER, &IHapticSettings::setAimSensitivity); +} + +// sub_10040080 "setAimSensitivityLengthSOLDIER_Z": vector setter, component z: +0xC4 getAimSensitivityLengthSOLDIER / +0xC8 setAimSensitivityLengthSOLDIER; mirror +0xC4 getAimSensitivityLengthSOLDIER / +0xB0 setAimSensitivityLength (on foot or no local player). +void as_hapticsettings_setAimSensitivityLengthSOLDIER_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLengthSOLDIER_Z"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLengthSOLDIER, &IHapticSettings::setAimSensitivityLengthSOLDIER, 2, kHapticSoldier, + &IHapticSettings::getAimSensitivityLengthSOLDIER, &IHapticSettings::setAimSensitivityLength); +} + +// sub_10040270 "setTurnSensitivitySOLDIER_Z": vector setter, component z: +0xCC getTurnSensitivitySOLDIER / +0xD0 setTurnSensitivitySOLDIER; mirror +0xCC getTurnSensitivitySOLDIER / +0xB8 setTurnSensitivity (on foot or no local player). +void as_hapticsettings_setTurnSensitivitySOLDIER_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setTurnSensitivitySOLDIER_Z"); + hapticVectorSetter(fn, &IHapticSettings::getTurnSensitivitySOLDIER, &IHapticSettings::setTurnSensitivitySOLDIER, 2, kHapticSoldier, + &IHapticSettings::getTurnSensitivitySOLDIER, &IHapticSettings::setTurnSensitivity); +} + +// sub_10040D00 "setAimSensitivityLAND_Z": vector setter, component z: +0x104 getAimSensitivityLAND / +0x108 setAimSensitivityLAND; mirror +0x104 getAimSensitivityLAND / +0xA8 setAimSensitivity (vehicle category kHapticLand). +void as_hapticsettings_setAimSensitivityLAND_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLAND_Z"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLAND, &IHapticSettings::setAimSensitivityLAND, 2, kHapticLand, + &IHapticSettings::getAimSensitivityLAND, &IHapticSettings::setAimSensitivity); +} + +// sub_10040E70 "setAimSensitivityLengthLAND_Z": vector setter, component z: +0x10C getAimSensitivityLengthLAND / +0x110 setAimSensitivityLengthLAND; mirror +0x10C getAimSensitivityLengthLAND / +0xB0 setAimSensitivityLength (vehicle category kHapticLand). +void as_hapticsettings_setAimSensitivityLengthLAND_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLengthLAND_Z"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLengthLAND, &IHapticSettings::setAimSensitivityLengthLAND, 2, kHapticLand, + &IHapticSettings::getAimSensitivityLengthLAND, &IHapticSettings::setAimSensitivityLength); +} + +// sub_10040FE0 "setTurnSensitivityLAND_Z": vector setter, component z: +0x114 getTurnSensitivityLAND / +0x118 setTurnSensitivityLAND; mirror +0x114 getTurnSensitivityLAND / +0xB8 setTurnSensitivity (vehicle category kHapticLand). +void as_hapticsettings_setTurnSensitivityLAND_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setTurnSensitivityLAND_Z"); + hapticVectorSetter(fn, &IHapticSettings::getTurnSensitivityLAND, &IHapticSettings::setTurnSensitivityLAND, 2, kHapticLand, + &IHapticSettings::getTurnSensitivityLAND, &IHapticSettings::setTurnSensitivity); +} + +// sub_100419F0 "setAimSensitivityAIR_Z": vector setter, component z: +0xD4 getAimSensitivityAIR / +0xD8 setAimSensitivityAIR; mirror +0xD4 getAimSensitivityAIR / +0xA8 setAimSensitivity (vehicle category kHapticAir). +void as_hapticsettings_setAimSensitivityAIR_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityAIR_Z"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityAIR, &IHapticSettings::setAimSensitivityAIR, 2, kHapticAir, + &IHapticSettings::getAimSensitivityAIR, &IHapticSettings::setAimSensitivity); +} + +// sub_10041B60 "setAimSensitivityLengthAIR_Z": vector setter, component z: +0xDC getAimSensitivityLengthAIR / +0xE0 setAimSensitivityLengthAIR; mirror +0xDC getAimSensitivityLengthAIR / +0xB0 setAimSensitivityLength (vehicle category kHapticAir). +void as_hapticsettings_setAimSensitivityLengthAIR_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLengthAIR_Z"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLengthAIR, &IHapticSettings::setAimSensitivityLengthAIR, 2, kHapticAir, + &IHapticSettings::getAimSensitivityLengthAIR, &IHapticSettings::setAimSensitivityLength); +} + +// sub_10041CD0 "setTurnSensitivityAIR_Z": vector setter, component z: +0xE4 getTurnSensitivityAIR / +0xE8 setTurnSensitivityAIR; mirror +0xE4 getTurnSensitivityAIR / +0xB8 setTurnSensitivity (vehicle category kHapticAir). +void as_hapticsettings_setTurnSensitivityAIR_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setTurnSensitivityAIR_Z"); + hapticVectorSetter(fn, &IHapticSettings::getTurnSensitivityAIR, &IHapticSettings::setTurnSensitivityAIR, 2, kHapticAir, + &IHapticSettings::getTurnSensitivityAIR, &IHapticSettings::setTurnSensitivity); +} + +// sub_100426E0 "setAimSensitivityHELI_Z": vector setter, component z: +0xEC getAimSensitivityHELI / +0xF0 setAimSensitivityHELI; mirror +0xEC getAimSensitivityHELI / +0xA8 setAimSensitivity (vehicle category kHapticHeli). +void as_hapticsettings_setAimSensitivityHELI_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityHELI_Z"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityHELI, &IHapticSettings::setAimSensitivityHELI, 2, kHapticHeli, + &IHapticSettings::getAimSensitivityHELI, &IHapticSettings::setAimSensitivity); +} + +// sub_10042850 "setAimSensitivityLengthHELI_Z": vector setter, component z: +0xF4 getAimSensitivityLengthHELI / +0xF8 setAimSensitivityLengthHELI; mirror +0xF4 getAimSensitivityLengthHELI / +0xB0 setAimSensitivityLength (vehicle category kHapticHeli). +void as_hapticsettings_setAimSensitivityLengthHELI_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLengthHELI_Z"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLengthHELI, &IHapticSettings::setAimSensitivityLengthHELI, 2, kHapticHeli, + &IHapticSettings::getAimSensitivityLengthHELI, &IHapticSettings::setAimSensitivityLength); +} + +// sub_100429C0 "setTurnSensitivityHELI_Z": vector setter, component z: +0xFC getTurnSensitivityHELI / +0x100 setTurnSensitivityHELI; mirror +0xFC getTurnSensitivityHELI / +0xB8 setTurnSensitivity (vehicle category kHapticHeli). +void as_hapticsettings_setTurnSensitivityHELI_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setTurnSensitivityHELI_Z"); + hapticVectorSetter(fn, &IHapticSettings::getTurnSensitivityHELI, &IHapticSettings::setTurnSensitivityHELI, 2, kHapticHeli, + &IHapticSettings::getTurnSensitivityHELI, &IHapticSettings::setTurnSensitivity); +} + +// sub_100433D0 "setAimSensitivitySEA_Z": vector setter, component z: +0x11C getAimSensitivitySEA / +0x120 setAimSensitivitySEA; mirror +0x11C getAimSensitivitySEA / +0xA8 setAimSensitivity (vehicle category kHapticSea). +void as_hapticsettings_setAimSensitivitySEA_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivitySEA_Z"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivitySEA, &IHapticSettings::setAimSensitivitySEA, 2, kHapticSea, + &IHapticSettings::getAimSensitivitySEA, &IHapticSettings::setAimSensitivity); +} + +// sub_10043540 "setAimSensitivityLengthSEA_Z": vector setter, component z: +0x124 getAimSensitivityLengthSEA / +0x128 setAimSensitivityLengthSEA; mirror +0x124 getAimSensitivityLengthSEA / +0xB0 setAimSensitivityLength (vehicle category kHapticSea). +void as_hapticsettings_setAimSensitivityLengthSEA_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLengthSEA_Z"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLengthSEA, &IHapticSettings::setAimSensitivityLengthSEA, 2, kHapticSea, + &IHapticSettings::getAimSensitivityLengthSEA, &IHapticSettings::setAimSensitivityLength); +} + +// sub_100436B0 "setTurnSensitivitySEA_Z": vector setter, component z: +0x12C getTurnSensitivitySEA / +0x130 setTurnSensitivitySEA; mirror +0x12C getTurnSensitivitySEA / +0xB8 setTurnSensitivity (vehicle category kHapticSea). +void as_hapticsettings_setTurnSensitivitySEA_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setTurnSensitivitySEA_Z"); + hapticVectorSetter(fn, &IHapticSettings::getTurnSensitivitySEA, &IHapticSettings::setTurnSensitivitySEA, 2, kHapticSea, + &IHapticSettings::getTurnSensitivitySEA, &IHapticSettings::setTurnSensitivity); +} + +// sub_10035290 "setWeaponSelectSOLDIER": arg 0 to_string stored into the shared weapon selection (0x100F8550). +void as_hapticsettings_setWeaponSelectSOLDIER(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setWeaponSelectSOLDIER"); + s_hapticWeaponSelect = fn.arg(0).to_string(); +} + +// sub_10036CA0 "getWeaponSelectSOLDIER": the shared weapon selection (unk_100F8554) as a plain string. +void as_hapticsettings_getWeaponSelectSOLDIER(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getWeaponSelectSOLDIER"); + fn.result->set_tu_string(tu_string(s_hapticWeaponSelect.c_str())); +} + +// sub_10036D10 "getWeaponInitialSOLDIER": arg 0 == 1 -> the name at 0x100F6C70 as a plain string, else its localised dice String (sub_10036B70). +void as_hapticsettings_getWeaponInitialSOLDIER(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getWeaponInitialSOLDIER"); + publishHapticInitialName(fn, kHapticInfantryWeapons[0]); +} + +// sub_10036DF0 "setThresholdSelectSOLDIER": arg 0 to_string; result _stricmp(name, "BFHQ_physicsthresholdhigh") == 0, then the name stored into the shared threshold selection (0x100F8534). +void as_hapticsettings_setThresholdSelectSOLDIER(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setThresholdSelectSOLDIER"); + storeHapticThresholdSelect(fn); +} + +// sub_10036EB0 "getThresholdSelectSOLDIER": the shared threshold selection (unk_100F8538) as a plain string. +void as_hapticsettings_getThresholdSelectSOLDIER(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getThresholdSelectSOLDIER"); + fn.result->set_tu_string(tu_string(s_hapticThresholdSelect.c_str())); +} + +// sub_10036F20 "getThresholdInitialSOLDIER": the localised dice String (sub_10036B70) of unk_100F3870, "BFHQ_physicsthresholdlow"; no argument read. +void as_hapticsettings_getThresholdInitialSOLDIER(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getThresholdInitialSOLDIER"); + fn.result->set_as_object_interface(videoSettingsLocalisedString(renddx9abi::HostString("BFHQ_physicsthresholdlow"))); +} + +// sub_100352C0 "setWeaponSelectLAND": arg 0 to_string stored into the shared weapon selection (0x100F8550). +void as_hapticsettings_setWeaponSelectLAND(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setWeaponSelectLAND"); + s_hapticWeaponSelect = fn.arg(0).to_string(); +} + +// sub_10036F70 "getWeaponSelectLAND": the shared weapon selection (unk_100F8554) as a plain string. +void as_hapticsettings_getWeaponSelectLAND(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getWeaponSelectLAND"); + fn.result->set_tu_string(tu_string(s_hapticWeaponSelect.c_str())); +} + +// sub_10036FE0 "getWeaponInitialLAND": arg 0 == 1 -> the name at 0x100F3310 as a plain string, else its localised dice String (sub_10036B70). +void as_hapticsettings_getWeaponInitialLAND(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getWeaponInitialLAND"); + publishHapticInitialName(fn, kHapticVehicleWeapons[0]); +} + +// sub_100370C0 "setThresholdSelectLAND": arg 0 to_string; result _stricmp(name, "BFHQ_physicsthresholdhigh") == 0, then the name stored into the shared threshold selection (0x100F8534). +void as_hapticsettings_setThresholdSelectLAND(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setThresholdSelectLAND"); + storeHapticThresholdSelect(fn); +} + +// sub_10037180 "getThresholdSelectLAND": the shared threshold selection (unk_100F8538) as a plain string. +void as_hapticsettings_getThresholdSelectLAND(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getThresholdSelectLAND"); + fn.result->set_tu_string(tu_string(s_hapticThresholdSelect.c_str())); +} + +// sub_100371F0 "getThresholdInitialLAND": the localised dice String (sub_10036B70) of unk_100F3870, "BFHQ_physicsthresholdlow"; no argument read. +void as_hapticsettings_getThresholdInitialLAND(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getThresholdInitialLAND"); + fn.result->set_as_object_interface(videoSettingsLocalisedString(renddx9abi::HostString("BFHQ_physicsthresholdlow"))); +} + +// sub_100352F0 "setWeaponSelectAIR": arg 0 to_string stored into the shared weapon selection (0x100F8550). +void as_hapticsettings_setWeaponSelectAIR(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setWeaponSelectAIR"); + s_hapticWeaponSelect = fn.arg(0).to_string(); +} + +// sub_10037240 "getWeaponSelectAIR": the shared weapon selection (unk_100F8554) as a plain string. +void as_hapticsettings_getWeaponSelectAIR(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getWeaponSelectAIR"); + fn.result->set_tu_string(tu_string(s_hapticWeaponSelect.c_str())); +} + +// sub_100372B0 "getWeaponInitialAIR": arg 0 == 1 -> the name at 0x100F3364 as a plain string, else its localised dice String (sub_10036B70). +void as_hapticsettings_getWeaponInitialAIR(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getWeaponInitialAIR"); + publishHapticInitialName(fn, kHapticVehicleWeapons[3]); +} + +// sub_10037390 "setThresholdSelectAIR": arg 0 to_string; result _stricmp(name, "BFHQ_physicsthresholdhigh") == 0, then the name stored into the shared threshold selection (0x100F8534). +void as_hapticsettings_setThresholdSelectAIR(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setThresholdSelectAIR"); + storeHapticThresholdSelect(fn); +} + +// sub_10037450 "getThresholdSelectAIR": the shared threshold selection (unk_100F8538) as a plain string. +void as_hapticsettings_getThresholdSelectAIR(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getThresholdSelectAIR"); + fn.result->set_tu_string(tu_string(s_hapticThresholdSelect.c_str())); +} + +// sub_100374C0 "getThresholdInitialAIR": the localised dice String (sub_10036B70) of unk_100F3870, "BFHQ_physicsthresholdlow"; no argument read. +void as_hapticsettings_getThresholdInitialAIR(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getThresholdInitialAIR"); + fn.result->set_as_object_interface(videoSettingsLocalisedString(renddx9abi::HostString("BFHQ_physicsthresholdlow"))); +} + +// sub_10035320 "setWeaponSelectHELI": arg 0 to_string stored into the shared weapon selection (0x100F8550). +void as_hapticsettings_setWeaponSelectHELI(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setWeaponSelectHELI"); + s_hapticWeaponSelect = fn.arg(0).to_string(); +} + +// sub_10037510 "getWeaponSelectHELI": the shared weapon selection (unk_100F8554) as a plain string. +void as_hapticsettings_getWeaponSelectHELI(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getWeaponSelectHELI"); + fn.result->set_tu_string(tu_string(s_hapticWeaponSelect.c_str())); +} + +// sub_10037580 "getWeaponInitialHELI": arg 0 == 1 -> the name at 0x100F3348 as a plain string, else its localised dice String (sub_10036B70). +void as_hapticsettings_getWeaponInitialHELI(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getWeaponInitialHELI"); + publishHapticInitialName(fn, kHapticVehicleWeapons[2]); +} + +// sub_10037660 "setThresholdSelectHELI": arg 0 to_string; result _stricmp(name, "BFHQ_physicsthresholdhigh") == 0, then the name stored into the shared threshold selection (0x100F8534). +void as_hapticsettings_setThresholdSelectHELI(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setThresholdSelectHELI"); + storeHapticThresholdSelect(fn); +} + +// sub_10037720 "getThresholdSelectHELI": the shared threshold selection (unk_100F8538) as a plain string. +void as_hapticsettings_getThresholdSelectHELI(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getThresholdSelectHELI"); + fn.result->set_tu_string(tu_string(s_hapticThresholdSelect.c_str())); +} + +// sub_10037790 "getThresholdInitialHELI": the localised dice String (sub_10036B70) of unk_100F3870, "BFHQ_physicsthresholdlow"; no argument read. +void as_hapticsettings_getThresholdInitialHELI(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getThresholdInitialHELI"); + fn.result->set_as_object_interface(videoSettingsLocalisedString(renddx9abi::HostString("BFHQ_physicsthresholdlow"))); +} + +// sub_10035350 "setWeaponSelectSEA": arg 0 to_string stored into the shared weapon selection (0x100F8550). +void as_hapticsettings_setWeaponSelectSEA(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setWeaponSelectSEA"); + s_hapticWeaponSelect = fn.arg(0).to_string(); +} + +// sub_100377E0 "getWeaponSelectSEA": the shared weapon selection (unk_100F8554) as a plain string. +void as_hapticsettings_getWeaponSelectSEA(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getWeaponSelectSEA"); + fn.result->set_tu_string(tu_string(s_hapticWeaponSelect.c_str())); +} + +// sub_10037850 "getWeaponInitialSEA": arg 0 == 1 -> the name at 0x100F3310 as a plain string, else its localised dice String (sub_10036B70). +void as_hapticsettings_getWeaponInitialSEA(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getWeaponInitialSEA"); + publishHapticInitialName(fn, kHapticVehicleWeapons[0]); +} + +// sub_10037930 "setThresholdSelectSEA": arg 0 to_string; result _stricmp(name, "BFHQ_physicsthresholdhigh") == 0, then the name stored into the shared threshold selection (0x100F8534). +void as_hapticsettings_setThresholdSelectSEA(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setThresholdSelectSEA"); + storeHapticThresholdSelect(fn); +} + +// sub_100379F0 "getThresholdSelectSEA": the shared threshold selection (unk_100F8538) as a plain string. +void as_hapticsettings_getThresholdSelectSEA(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getThresholdSelectSEA"); + fn.result->set_tu_string(tu_string(s_hapticThresholdSelect.c_str())); +} + +// sub_10037A60 "getThresholdInitialSEA": the localised dice String (sub_10036B70) of unk_100F3870, "BFHQ_physicsthresholdlow"; no argument read. +void as_hapticsettings_getThresholdInitialSEA(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getThresholdInitialSEA"); + fn.result->set_as_object_interface(videoSettingsLocalisedString(renddx9abi::HostString("BFHQ_physicsthresholdlow"))); +} + + +static void registerHapticNatives(SwiffAsNamespace** ns, const char* const* names, int count) +{ + for (int i = 0; i < count; ++i) + { + if (::strcmp(names[i], "HapticSettings") != 0) + continue; + ns[i]->registerNativeCompatibleMethod("apply"); // 1004460F + ns[i]->registerNativeCompatibleMethod("reset"); // 10044676 + ns[i]->registerNativeCompatibleMethod("cancel"); // 100446CE + ns[i]->registerNativeCompatibleMethod("getControlBoxLengthSOLDIER_X"); // 10044744 + ns[i]->registerNativeCompatibleMethod("getControlBoxStiffnessSOLDIER_X"); // 100447B4 + ns[i]->registerNativeCompatibleMethod("getControlBoxLengthLAND_X"); // 10044830 + ns[i]->registerNativeCompatibleMethod("getControlBoxStiffnessLAND_X"); // 100448AC + ns[i]->registerNativeCompatibleMethod("getControlBoxLengthAIR_X"); // 10044928 + ns[i]->registerNativeCompatibleMethod("getControlBoxStiffnessAIR_X"); // 100449A4 + ns[i]->registerNativeCompatibleMethod("getControlBoxLengthHELI_X"); // 10044A20 + ns[i]->registerNativeCompatibleMethod("getControlBoxStiffnessHELI_X"); // 10044A9C + ns[i]->registerNativeCompatibleMethod("getControlBoxLengthSEA_X"); // 10044B18 + ns[i]->registerNativeCompatibleMethod("getControlBoxStiffnessSEA_X"); // 10044B94 + ns[i]->registerNativeCompatibleMethod("getControlBoxLengthSOLDIER_Y"); // 10044C10 + ns[i]->registerNativeCompatibleMethod("getControlBoxStiffnessSOLDIER_Y"); // 10044C8C + ns[i]->registerNativeCompatibleMethod("getControlBoxLengthLAND_Y"); // 10044D08 + ns[i]->registerNativeCompatibleMethod("getControlBoxStiffnessLAND_Y"); // 10044D84 + ns[i]->registerNativeCompatibleMethod("getControlBoxLengthAIR_Y"); // 10044E00 + ns[i]->registerNativeCompatibleMethod("getControlBoxStiffnessAIR_Y"); // 10044E7C + ns[i]->registerNativeCompatibleMethod("getControlBoxLengthHELI_Y"); // 10044EF8 + ns[i]->registerNativeCompatibleMethod("getControlBoxStiffnessHELI_Y"); // 10044F74 + ns[i]->registerNativeCompatibleMethod("getControlBoxLengthSEA_Y"); // 10044FF0 + ns[i]->registerNativeCompatibleMethod("getControlBoxStiffnessSEA_Y"); // 1004506C + ns[i]->registerNativeCompatibleMethod("getControlBoxLengthSOLDIER_Z"); // 100450E8 + ns[i]->registerNativeCompatibleMethod("getControlBoxStiffnessSOLDIER_Z"); // 10045164 + ns[i]->registerNativeCompatibleMethod("getControlBoxLengthLAND_Z"); // 100451E0 + ns[i]->registerNativeCompatibleMethod("getControlBoxStiffnessLAND_Z"); // 1004525C + ns[i]->registerNativeCompatibleMethod("getControlBoxLengthAIR_Z"); // 100452D8 + ns[i]->registerNativeCompatibleMethod("getControlBoxStiffnessAIR_Z"); // 10045354 + ns[i]->registerNativeCompatibleMethod("getControlBoxLengthHELI_Z"); // 100453D0 + ns[i]->registerNativeCompatibleMethod("getControlBoxStiffnessHELI_Z"); // 1004544C + ns[i]->registerNativeCompatibleMethod("getControlBoxLengthSEA_Z"); // 100454C8 + ns[i]->registerNativeCompatibleMethod("getControlBoxStiffnessSEA_Z"); // 10045544 + ns[i]->registerNativeCompatibleMethod("getAimSensitivitySOLDIER_X"); // 100455C0 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLengthSOLDIER_X"); // 1004563C + ns[i]->registerNativeCompatibleMethod("getTurnSensitivitySOLDIER_X"); // 100456B8 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLAND_X"); // 10045734 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLengthLAND_X"); // 100457B0 + ns[i]->registerNativeCompatibleMethod("getTurnSensitivityLAND_X"); // 1004582C + ns[i]->registerNativeCompatibleMethod("getAimSensitivityAIR_X"); // 100458A8 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLengthAIR_X"); // 10045924 + ns[i]->registerNativeCompatibleMethod("getTurnSensitivityAIR_X"); // 100459A0 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityHELI_X"); // 10045A1C + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLengthHELI_X"); // 10045A98 + ns[i]->registerNativeCompatibleMethod("getTurnSensitivityHELI_X"); // 10045B14 + ns[i]->registerNativeCompatibleMethod("getAimSensitivitySEA_X"); // 10045B90 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLengthSEA_X"); // 10045C0C + ns[i]->registerNativeCompatibleMethod("getTurnSensitivitySEA_X"); // 10045C88 + ns[i]->registerNativeCompatibleMethod("getAimSensitivitySOLDIER_Y"); // 10045D04 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLengthSOLDIER_Y"); // 10045D80 + ns[i]->registerNativeCompatibleMethod("getTurnSensitivitySOLDIER_Y"); // 10045DFC + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLAND_Y"); // 10045E78 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLengthLAND_Y"); // 10045EF4 + ns[i]->registerNativeCompatibleMethod("getTurnSensitivityLAND_Y"); // 10045F70 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityAIR_Y"); // 10045FEC + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLengthAIR_Y"); // 10046068 + ns[i]->registerNativeCompatibleMethod("getTurnSensitivityAIR_Y"); // 100460E4 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityHELI_Y"); // 10046160 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLengthHELI_Y"); // 100461DC + ns[i]->registerNativeCompatibleMethod("getTurnSensitivityHELI_Y"); // 10046258 + ns[i]->registerNativeCompatibleMethod("getAimSensitivitySEA_Y"); // 100462D4 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLengthSEA_Y"); // 10046350 + ns[i]->registerNativeCompatibleMethod("getTurnSensitivitySEA_Y"); // 100463CC + ns[i]->registerNativeCompatibleMethod("getAimSensitivitySOLDIER_Z"); // 10046448 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLengthSOLDIER_Z"); // 100464C4 + ns[i]->registerNativeCompatibleMethod("getTurnSensitivitySOLDIER_Z"); // 10046540 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLAND_Z"); // 100465BC + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLengthLAND_Z"); // 10046638 + ns[i]->registerNativeCompatibleMethod("getTurnSensitivityLAND_Z"); // 100466B4 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityAIR_Z"); // 10046730 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLengthAIR_Z"); // 100467AC + ns[i]->registerNativeCompatibleMethod("getTurnSensitivityAIR_Z"); // 10046828 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityHELI_Z"); // 100468A4 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLengthHELI_Z"); // 10046920 + ns[i]->registerNativeCompatibleMethod("getTurnSensitivityHELI_Z"); // 1004699C + ns[i]->registerNativeCompatibleMethod("getAimSensitivitySEA_Z"); // 10046A18 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLengthSEA_Z"); // 10046A94 + ns[i]->registerNativeCompatibleMethod("getTurnSensitivitySEA_Z"); // 10046B10 + ns[i]->registerNativeCompatibleMethod("getPhysicsSOLDIERScale_X"); // 10046B8C + ns[i]->registerNativeCompatibleMethod("getPhysicsSOLDIERScale_Y"); // 10046C08 + ns[i]->registerNativeCompatibleMethod("getPhysicsSOLDIERScale_Z"); // 10046C84 + ns[i]->registerNativeCompatibleMethod("getPhysicsSOLDIERTransition"); // 10046D00 + ns[i]->registerNativeCompatibleMethod("getPhysicsSOLDIERSmoothTime_X"); // 10046D7C + ns[i]->registerNativeCompatibleMethod("getPhysicsSOLDIERSmoothTime_Y"); // 10046DF8 + ns[i]->registerNativeCompatibleMethod("getPhysicsSOLDIERSmoothTime_Z"); // 10046E74 + ns[i]->registerNativeCompatibleMethod("getPhysicsLANDScale_X"); // 10046EF0 + ns[i]->registerNativeCompatibleMethod("getPhysicsLANDScale_Y"); // 10046F6C + ns[i]->registerNativeCompatibleMethod("getPhysicsLANDScale_Z"); // 10046FE8 + ns[i]->registerNativeCompatibleMethod("getPhysicsLANDTransition"); // 10047064 + ns[i]->registerNativeCompatibleMethod("getPhysicsLANDSmoothTime_X"); // 100470E0 + ns[i]->registerNativeCompatibleMethod("getPhysicsLANDSmoothTime_Y"); // 1004715C + ns[i]->registerNativeCompatibleMethod("getPhysicsLANDSmoothTime_Z"); // 100471D8 + ns[i]->registerNativeCompatibleMethod("getPhysicsAIRScale_X"); // 10047254 + ns[i]->registerNativeCompatibleMethod("getPhysicsAIRScale_Y"); // 100472D0 + ns[i]->registerNativeCompatibleMethod("getPhysicsAIRScale_Z"); // 1004734C + ns[i]->registerNativeCompatibleMethod("getPhysicsAIRTransition"); // 100473C8 + ns[i]->registerNativeCompatibleMethod("getPhysicsAIRSmoothTime_X"); // 10047444 + ns[i]->registerNativeCompatibleMethod("getPhysicsAIRSmoothTime_Y"); // 100474C0 + ns[i]->registerNativeCompatibleMethod("getPhysicsAIRSmoothTime_Z"); // 1004753C + ns[i]->registerNativeCompatibleMethod("getPhysicsHELIScale_X"); // 100475B8 + ns[i]->registerNativeCompatibleMethod("getPhysicsHELIScale_Y"); // 10047634 + ns[i]->registerNativeCompatibleMethod("getPhysicsHELIScale_Z"); // 100476B0 + ns[i]->registerNativeCompatibleMethod("getPhysicsHELITransition"); // 1004772C + ns[i]->registerNativeCompatibleMethod("getPhysicsHELISmoothTime_X"); // 100477A8 + ns[i]->registerNativeCompatibleMethod("getPhysicsHELISmoothTime_Y"); // 10047824 + ns[i]->registerNativeCompatibleMethod("getPhysicsHELISmoothTime_Z"); // 100478A0 + ns[i]->registerNativeCompatibleMethod("getPhysicsSEAScale_X"); // 1004791C + ns[i]->registerNativeCompatibleMethod("getPhysicsSEAScale_Y"); // 10047998 + ns[i]->registerNativeCompatibleMethod("getPhysicsSEAScale_Z"); // 10047A14 + ns[i]->registerNativeCompatibleMethod("getPhysicsSEATransition"); // 10047A90 + ns[i]->registerNativeCompatibleMethod("getPhysicsSEASmoothTime_X"); // 10047B0C + ns[i]->registerNativeCompatibleMethod("getPhysicsSEASmoothTime_Y"); // 10047B88 + ns[i]->registerNativeCompatibleMethod("getPhysicsSEASmoothTime_Z"); // 10047C04 + ns[i]->registerNativeCompatibleMethod("getDamageScale"); // 10047C80 + ns[i]->registerNativeCompatibleMethod("getRecoilPunchScale"); // 10047CFC + ns[i]->registerNativeCompatibleMethod("getRecoilPunchTime"); // 10047D78 + ns[i]->registerNativeCompatibleMethod("getRecoilYawScale"); // 10047DF4 + ns[i]->registerNativeCompatibleMethod("getRecoilPitchScale"); // 10047E70 + ns[i]->registerNativeCompatibleMethod("setControlBoxLengthSOLDIER_X"); // 10047EEC + ns[i]->registerNativeCompatibleMethod("setControlBoxStiffnessSOLDIER_X"); // 10047F68 + ns[i]->registerNativeCompatibleMethod("setControlBoxLengthLAND_X"); // 10047FE4 + ns[i]->registerNativeCompatibleMethod("setControlBoxStiffnessLAND_X"); // 10048060 + ns[i]->registerNativeCompatibleMethod("setControlBoxLengthAIR_X"); // 100480DC + ns[i]->registerNativeCompatibleMethod("setControlBoxStiffnessAIR_X"); // 10048158 + ns[i]->registerNativeCompatibleMethod("setControlBoxLengthHELI_X"); // 100481D4 + ns[i]->registerNativeCompatibleMethod("setControlBoxStiffnessHELI_X"); // 10048250 + ns[i]->registerNativeCompatibleMethod("setControlBoxLengthSEA_X"); // 100482CC + ns[i]->registerNativeCompatibleMethod("setControlBoxStiffnessSEA_X"); // 10048348 + ns[i]->registerNativeCompatibleMethod("setControlBoxLengthSOLDIER_Y"); // 100483C4 + ns[i]->registerNativeCompatibleMethod("setControlBoxStiffnessSOLDIER_Y"); // 10048440 + ns[i]->registerNativeCompatibleMethod("setControlBoxLengthLAND_Y"); // 100484BC + ns[i]->registerNativeCompatibleMethod("setControlBoxStiffnessLAND_Y"); // 10048538 + ns[i]->registerNativeCompatibleMethod("setControlBoxLengthAIR_Y"); // 100485B4 + ns[i]->registerNativeCompatibleMethod("setControlBoxStiffnessAIR_Y"); // 10048630 + ns[i]->registerNativeCompatibleMethod("setControlBoxLengthHELI_Y"); // 100486AC + ns[i]->registerNativeCompatibleMethod("setControlBoxStiffnessHELI_Y"); // 10048728 + ns[i]->registerNativeCompatibleMethod("setControlBoxLengthSEA_Y"); // 100487A4 + ns[i]->registerNativeCompatibleMethod("setControlBoxStiffnessSEA_Y"); // 10048820 + ns[i]->registerNativeCompatibleMethod("setControlBoxLengthSOLDIER_Z"); // 1004889C + ns[i]->registerNativeCompatibleMethod("setControlBoxStiffnessSOLDIER_Z"); // 10048918 + ns[i]->registerNativeCompatibleMethod("setControlBoxLengthLAND_Z"); // 10048994 + ns[i]->registerNativeCompatibleMethod("setControlBoxStiffnessLAND_Z"); // 10048A10 + ns[i]->registerNativeCompatibleMethod("setControlBoxLengthAIR_Z"); // 10048A8C + ns[i]->registerNativeCompatibleMethod("setControlBoxStiffnessAIR_Z"); // 10048B08 + ns[i]->registerNativeCompatibleMethod("setControlBoxLengthHELI_Z"); // 10048B84 + ns[i]->registerNativeCompatibleMethod("setControlBoxStiffnessHELI_Z"); // 10048C00 + ns[i]->registerNativeCompatibleMethod("setControlBoxLengthSEA_Z"); // 10048C7C + ns[i]->registerNativeCompatibleMethod("setControlBoxStiffnessSEA_Z"); // 10048CF8 + ns[i]->registerNativeCompatibleMethod("setAimSensitivitySOLDIER_X"); // 10048D74 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLengthSOLDIER_X"); // 10048DF0 + ns[i]->registerNativeCompatibleMethod("setTurnSensitivitySOLDIER_X"); // 10048E6C + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLAND_X"); // 10048EE8 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLengthLAND_X"); // 10048F64 + ns[i]->registerNativeCompatibleMethod("setTurnSensitivityLAND_X"); // 10048FE0 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityAIR_X"); // 1004905C + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLengthAIR_X"); // 100490D8 + ns[i]->registerNativeCompatibleMethod("setTurnSensitivityAIR_X"); // 10049154 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityHELI_X"); // 100491D0 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLengthHELI_X"); // 1004924C + ns[i]->registerNativeCompatibleMethod("setTurnSensitivityHELI_X"); // 100492C8 + ns[i]->registerNativeCompatibleMethod("setAimSensitivitySEA_X"); // 10049344 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLengthSEA_X"); // 100493C0 + ns[i]->registerNativeCompatibleMethod("setTurnSensitivitySEA_X"); // 1004943C + ns[i]->registerNativeCompatibleMethod("setAimSensitivitySOLDIER_Y"); // 100494B8 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLengthSOLDIER_Y"); // 10049534 + ns[i]->registerNativeCompatibleMethod("setTurnSensitivitySOLDIER_Y"); // 100495B0 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLAND_Y"); // 1004962C + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLengthLAND_Y"); // 100496A8 + ns[i]->registerNativeCompatibleMethod("setTurnSensitivityLAND_Y"); // 10049724 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityAIR_Y"); // 100497A0 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLengthAIR_Y"); // 1004981C + ns[i]->registerNativeCompatibleMethod("setTurnSensitivityAIR_Y"); // 10049898 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityHELI_Y"); // 10049914 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLengthHELI_Y"); // 10049990 + ns[i]->registerNativeCompatibleMethod("setTurnSensitivityHELI_Y"); // 10049A0C + ns[i]->registerNativeCompatibleMethod("setAimSensitivitySEA_Y"); // 10049A88 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLengthSEA_Y"); // 10049B04 + ns[i]->registerNativeCompatibleMethod("setTurnSensitivitySEA_Y"); // 10049B80 + ns[i]->registerNativeCompatibleMethod("setAimSensitivitySOLDIER_Z"); // 10049BFC + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLengthSOLDIER_Z"); // 10049C78 + ns[i]->registerNativeCompatibleMethod("setTurnSensitivitySOLDIER_Z"); // 10049CF4 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLAND_Z"); // 10049D70 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLengthLAND_Z"); // 10049DEC + ns[i]->registerNativeCompatibleMethod("setTurnSensitivityLAND_Z"); // 10049E68 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityAIR_Z"); // 10049EE4 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLengthAIR_Z"); // 10049F60 + ns[i]->registerNativeCompatibleMethod("setTurnSensitivityAIR_Z"); // 10049FDC + ns[i]->registerNativeCompatibleMethod("setAimSensitivityHELI_Z"); // 1004A058 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLengthHELI_Z"); // 1004A0D4 + ns[i]->registerNativeCompatibleMethod("setTurnSensitivityHELI_Z"); // 1004A150 + ns[i]->registerNativeCompatibleMethod("setAimSensitivitySEA_Z"); // 1004A1CC + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLengthSEA_Z"); // 1004A248 + ns[i]->registerNativeCompatibleMethod("setTurnSensitivitySEA_Z"); // 1004A2C4 + ns[i]->registerNativeCompatibleMethod("setPhysicsSOLDIERScale_X"); // 1004A340 + ns[i]->registerNativeCompatibleMethod("setPhysicsSOLDIERScale_Y"); // 1004A3BC + ns[i]->registerNativeCompatibleMethod("setPhysicsSOLDIERScale_Z"); // 1004A438 + ns[i]->registerNativeCompatibleMethod("setPhysicsSOLDIERTransition"); // 1004A4B4 + ns[i]->registerNativeCompatibleMethod("setPhysicsSOLDIERSmoothTime_X"); // 1004A530 + ns[i]->registerNativeCompatibleMethod("setPhysicsSOLDIERSmoothTime_Y"); // 1004A5AC + ns[i]->registerNativeCompatibleMethod("setPhysicsSOLDIERSmoothTime_Z"); // 1004A628 + ns[i]->registerNativeCompatibleMethod("setPhysicsLANDScale_X"); // 1004A6A4 + ns[i]->registerNativeCompatibleMethod("setPhysicsLANDScale_Y"); // 1004A720 + ns[i]->registerNativeCompatibleMethod("setPhysicsLANDScale_Z"); // 1004A79C + ns[i]->registerNativeCompatibleMethod("setPhysicsLANDTransition"); // 1004A818 + ns[i]->registerNativeCompatibleMethod("setPhysicsLANDSmoothTime_X"); // 1004A894 + ns[i]->registerNativeCompatibleMethod("setPhysicsLANDSmoothTime_Y"); // 1004A910 + ns[i]->registerNativeCompatibleMethod("setPhysicsLANDSmoothTime_Z"); // 1004A98C + ns[i]->registerNativeCompatibleMethod("setPhysicsAIRScale_X"); // 1004AA08 + ns[i]->registerNativeCompatibleMethod("setPhysicsAIRScale_Y"); // 1004AA84 + ns[i]->registerNativeCompatibleMethod("setPhysicsAIRScale_Z"); // 1004AB00 + ns[i]->registerNativeCompatibleMethod("setPhysicsAIRTransition"); // 1004AB7C + ns[i]->registerNativeCompatibleMethod("setPhysicsAIRSmoothTime_X"); // 1004ABF8 + ns[i]->registerNativeCompatibleMethod("setPhysicsAIRSmoothTime_Y"); // 1004AC74 + ns[i]->registerNativeCompatibleMethod("setPhysicsAIRSmoothTime_Z"); // 1004ACF0 + ns[i]->registerNativeCompatibleMethod("setPhysicsHELIScale_X"); // 1004AD6C + ns[i]->registerNativeCompatibleMethod("setPhysicsHELIScale_Y"); // 1004ADE8 + ns[i]->registerNativeCompatibleMethod("setPhysicsHELIScale_Z"); // 1004AE64 + ns[i]->registerNativeCompatibleMethod("setPhysicsHELITransition"); // 1004AEE0 + ns[i]->registerNativeCompatibleMethod("setPhysicsHELISmoothTime_X"); // 1004AF5C + ns[i]->registerNativeCompatibleMethod("setPhysicsHELISmoothTime_Y"); // 1004AFD8 + ns[i]->registerNativeCompatibleMethod("setPhysicsHELISmoothTime_Z"); // 1004B054 + ns[i]->registerNativeCompatibleMethod("setPhysicsSEAScale_X"); // 1004B0D0 + ns[i]->registerNativeCompatibleMethod("setPhysicsSEAScale_Y"); // 1004B14C + ns[i]->registerNativeCompatibleMethod("setPhysicsSEAScale_Z"); // 1004B1C8 + ns[i]->registerNativeCompatibleMethod("setPhysicsSEATransition"); // 1004B244 + ns[i]->registerNativeCompatibleMethod("setPhysicsSEASmoothTime_X"); // 1004B2C0 + ns[i]->registerNativeCompatibleMethod("setPhysicsSEASmoothTime_Y"); // 1004B33C + ns[i]->registerNativeCompatibleMethod("setPhysicsSEASmoothTime_Z"); // 1004B3B8 + ns[i]->registerNativeCompatibleMethod("setDamageScale"); // 1004B434 + ns[i]->registerNativeCompatibleMethod("setRecoilPunchScale"); // 1004B4B0 + ns[i]->registerNativeCompatibleMethod("setRecoilPunchTime"); // 1004B52C + ns[i]->registerNativeCompatibleMethod("setRecoilYawScale"); // 1004B5A8 + ns[i]->registerNativeCompatibleMethod("setRecoilPitchScale"); // 1004B624 + ns[i]->registerNativeCompatibleMethod("setWeaponSelectSOLDIER"); // 1004B6A0 + ns[i]->registerNativeCompatibleMethod("getWeaponSelectSOLDIER"); // 1004B71C + ns[i]->registerNativeCompatibleMethod("getWeaponInitialSOLDIER"); // 1004B798 + ns[i]->registerNativeCompatibleMethod("setThresholdSelectSOLDIER"); // 1004B814 + ns[i]->registerNativeCompatibleMethod("getThresholdSelectSOLDIER"); // 1004B890 + ns[i]->registerNativeCompatibleMethod("getThresholdInitialSOLDIER"); // 1004B90C + ns[i]->registerNativeCompatibleMethod("setWeaponSelectLAND"); // 1004B988 + ns[i]->registerNativeCompatibleMethod("getWeaponSelectLAND"); // 1004BA04 + ns[i]->registerNativeCompatibleMethod("getWeaponInitialLAND"); // 1004BA80 + ns[i]->registerNativeCompatibleMethod("setThresholdSelectLAND"); // 1004BAFC + ns[i]->registerNativeCompatibleMethod("getThresholdSelectLAND"); // 1004BB78 + ns[i]->registerNativeCompatibleMethod("getThresholdInitialLAND"); // 1004BBF4 + ns[i]->registerNativeCompatibleMethod("setWeaponSelectAIR"); // 1004BC70 + ns[i]->registerNativeCompatibleMethod("getWeaponSelectAIR"); // 1004BCEC + ns[i]->registerNativeCompatibleMethod("getWeaponInitialAIR"); // 1004BD68 + ns[i]->registerNativeCompatibleMethod("setThresholdSelectAIR"); // 1004BDE4 + ns[i]->registerNativeCompatibleMethod("getThresholdSelectAIR"); // 1004BE60 + ns[i]->registerNativeCompatibleMethod("getThresholdInitialAIR"); // 1004BEDC + ns[i]->registerNativeCompatibleMethod("setWeaponSelectHELI"); // 1004BF58 + ns[i]->registerNativeCompatibleMethod("getWeaponSelectHELI"); // 1004BFD4 + ns[i]->registerNativeCompatibleMethod("getWeaponInitialHELI"); // 1004C050 + ns[i]->registerNativeCompatibleMethod("setThresholdSelectHELI"); // 1004C0CC + ns[i]->registerNativeCompatibleMethod("getThresholdSelectHELI"); // 1004C148 + ns[i]->registerNativeCompatibleMethod("getThresholdInitialHELI"); // 1004C1C4 + ns[i]->registerNativeCompatibleMethod("setWeaponSelectSEA"); // 1004C240 + ns[i]->registerNativeCompatibleMethod("getWeaponSelectSEA"); // 1004C2BC + ns[i]->registerNativeCompatibleMethod("getWeaponInitialSEA"); // 1004C338 + ns[i]->registerNativeCompatibleMethod("setThresholdSelectSEA"); // 1004C3B4 + ns[i]->registerNativeCompatibleMethod("getThresholdSelectSEA"); // 1004C430 + ns[i]->registerNativeCompatibleMethod("getThresholdInitialSEA"); // 1004C4AC + ns[i]->registerNativeCompatibleMethod("setHapticSettingsPage"); // 1004C528 + ns[i]->registerNativeCompatibleMethod("getHapticSettingsPage"); // 1004C5A4 + } +} diff --git a/Code/BF2/External/gameswf/SwiffPlayer/SwiffPlayer.cpp b/Code/BF2/External/gameswf/SwiffPlayer/SwiffPlayer.cpp index 564174978..c393d222c 100644 --- a/Code/BF2/External/gameswf/SwiffPlayer/SwiffPlayer.cpp +++ b/Code/BF2/External/gameswf/SwiffPlayer/SwiffPlayer.cpp @@ -1,15 +1,57 @@ // SwiffPlayer lifecycle, movie pipeline, renderer adapter, and ActionScript bindings. // [CHOSEN, not recovered] Rebuilt client/plugin ABI only: https://github.com/B2BF/OpenBF2/issues/7. -// Internal fixed-layout storage and unresolved host frontiers remain in place. +// Internal records use native std containers; unresolved host frontiers remain in place. #ifdef BF2_IMAGE_SWIFFPLAYER +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../../../Platform/X87Compat.h" // [CHOSEN, not recovered] x87 conversion results, including invalid inputs. #include "SwiffPlayer.h" +#include "SwiffBitmapCache.h" +#include "OfflineConnectPopup.h" +#include "../../../Core/MsvcCrtCompat.h" // [CHOSEN, not recovered] sprintf_s, __time32_t/_time32, _time64 outside MSVC +#if defined(__APPLE__) +#include "../../../Platform/macOS/CocoaHost.h" +// [CHOSEN, not recovered] macOS: the two user32 calls the ActionScript bindings make, on the Cocoa +// host. SetCursor takes the host's cursor tokens (SwiffHost::getCursor) and answers the previous +// one; GetKeyState is called only for VK_CAPITAL (20), whose toggle bit is the Caps Lock state. +static void* SetCursor(void* cursor) +{ + static void* s_current = 0; + void* const previous = s_current; + s_current = cursor; + ::dice::hfe::macos::CocoaHost::instance().setCursor(cursor); + return previous; +} +// SwiffPlayer.dll calls GetKeyState once, with VK_CAPITAL (0x1004D457 pushes 0x14), so the macOS +// shim is that one query: the Caps Lock toggle bit. +static short capsLockKeyState() +{ + return (::dice::hfe::macos::CocoaHost::instance().modifierFlags() & ::dice::hfe::macos::HostModCapsLock) ? 1 : 0; +} +#endif #include "../../../../RendDX9Abi/BfMemory.h" #include "../../../../RendDX9Abi/HfeAbi.h" -#include "../../../../RendDX9Abi/Vc71String.h" // retained fixed-layout internal strings -#include "../../../../RendDX9Abi/Vc71Vector.h" // the +1104 queued-mouse vector +#if !defined(_MSC_VER) +// [CHOSEN, not recovered] Use the renderer's shared native slots and signatures. +#include "../../../../SwiffPlayerAbi/NativeRenderCalls.h" +#else +#include "../../../Menu/ISwiffRender.h" // the typed render calls of the dice.bf2.Logic credits natives +#endif #include "../../../Menu/ISwiffHost.h" // native storage calls share the owner's std::string ABI #include "../../../Menu/IServerBrowser.h" // stopBrowser's list handle (+0x30 stopUpdate) @@ -21,25 +63,28 @@ #include "../../../Game/VideoSettings.h" // native: IVideoSettings, the dice.bf2.VideoSettings rows' owner #include "../../../Game/ControlSettings.h" // native: IControlSettings, the dice.bf2.ControlSettings rows' owner #include "../../../Game/AudioSettings.h" // native: IAudioSettings, the dice.bf2.AudioSettings rows' owner +#include "../../../Game/VoipClient/BF2VoipClient.h" // the "Bf2VoipClient" singleton's slots (BF2.exe vtable 0x89C1A8) #include "../../../Game/GameServerSettings.h" // native: IGameServerSettings::setTeamRatio / setNoVehicles #include "../../../Game/HudInformationLayer.h" // native: eorsinfo publishes the joined server through +0x8C #include "../../../Game/Persistence/PlayerUnlockInfo.h" // native: IPlayerUnlockInfo::getItems, the names selectFirstUnlock resolves #include "../../../Game/DemoRecorder/DemoLibrary.h" // native: Multiplay's bookmark flag pair #include "../../../Menu/IMenuTeamManager.h" // native: the typed team -> kit -> equipment walk behind getEquipmentName & co #include "../../../Menu/ServerLogoManager.h" // native: the typed logo cache behind Multiplay.downloadServerLogo +#include "../../../Game/Persistence/SearchForPlayer.h" // native: Profile.searchPlayer / searchUniquePlayer (host +0x3C) +#include "../../../Game/HapticSettings.h" // native: IHapticSettings, the dice.bf2.HapticSettings rows +#include "../../../Scene/Object/PlayerManager.h" // native: the HapticSettings vector setters' local player (+0x30) +#include "../../../Game/Objects/IPlayer.h" // native: getVehicle / getDefaultVehicle (PE +0x44 / +0xA0) +#include "../../../Game/Objects/IObject.h" // native: the vehicle's template field (+0x14) +#include "../../../Game/Objects/PlayerControlObjectTemplate.h" // native: getVehicleCategory (PE base +0x22C, slot +0x24) +#include "../../../Core/Ids.h" // native: IID_IPlayerControlObjectTemplate (the port guard in the haptic vector setters) #include "base/tu_file.h" // the file_opener_callback return type #include "base/image.h" // image::rgb / image::rgba (create_bitmap_info_rgb/rgba read w/h) #include "gameswf_action.h" // as_object / as_value / get_global_object - the AS-bridge graph build +#include "gameswf_impl.h" // existing movie frame navigation used by the offline popup policy +#include "gameswf_render.h" +#include "gameswf_log.h" // [TEMP] c-swf-disconnect: SWF_LIST_TRACE -#include -#include -#include -#include // memset, memcpy -#include // time(): the stamp the host records carry -#include // getenv (the AS-diagnostic gate) -#include // va_list: swiffFormatString (sub_10003320) behind Logic.setDecimals -#include // unk_100F882C: the server-browser filter clauses, keyed by bit namespace dice { namespace hfe { @@ -49,18 +94,27 @@ namespace hfe { // engine VFS the file opener reads SWFs through. extern IClassManager* classManager; extern IBase* fileManager; +// playerManager (dword_100EFEE0, "PlayerManager" stored by initDll): the HapticSettings vector +// setters ask it for the local human player (+0x30). Typed IBase* as PluginEntry.cpp keeps it. +extern IBase* playerManager; +// settings (dword_100EFE90, "SettingsRepostitory" stored by initDll): the log callback's +// "swiffDebug" read. +extern IBase* settings; namespace ui { -// The internal object layout remains fixed while the rebuilt client and gameswf share it. -// Reject an accidental reorder or added member at compile time. - -static_assert(sizeof(SwiffPlayer) == 1120, "SwiffPlayer must be 0x460 bytes (IDB dice_hfe_SwiffPlayer_BF2)"); - // dword_100F2F20 in the shipped image - the ctor stores `this` here. Read by the fscommand sink to // find the live player. File-scope, one instance, matching the shipped global. static SwiffPlayer* g_swiffPlayerInstance = 0; +// [CHOSEN, not recovered] issue #7: the players constructed and not yet destroyed. The movie +// teardown's global steps (SwiffPlayer::releaseMovie) run only when the dying player is the last. +static int s_livePlayers = 0; + +// [CHOSEN, not recovered] Owner-approved offline popup policy, without player +// layout or virtual-slot changes. releaseMovie removes the borrowed instance. +// No script callback is replaced or retained. +static std::set s_mainMenus; // The gameswf modifier-key latches the shipped image keeps as file-scope bytes (byte_100F8EE8/9/A/B), // NOT as object members - notifyChar/notifyKeyState/resetModifierState touch these. @@ -125,13 +179,35 @@ static tu_file* swiffFileOpener(const char* urlOrPath) swiffFileSeekToEnd, swiffFileTell, swiffFileGetEof, swiffFileClose); } -static void swiffFsCommand(gameswf::movie_interface* /*movie*/, const char* /*command*/, - const char* /*arg*/) +// SwiffPlayer.dll 0x10005160, the gameswf log callback the ctor registers (0x1009AF40). With the +// "swiffDebug" setting at 1 it keeps the first line of each log message (up to 0x1FE characters) in +// a static buffer; a message without a newline is ignored. Nothing in the DLL reads the buffer. +namespace { +char s_swiffDebugLine[0x200]; // 0x100F2F28 +class SettingsIntView : public IBase // SettingsRepostitory +0x10 +{ +public: + virtual const int& intGet(const renddx9abi::HostString& name, const int& fallback) = 0; +protected: + ~SettingsIntView() {} +}; +} + +static void swiffLogCallback(bool /*error*/, const char* message) { - // [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: swiff-native-as-host] - ::fprintf(stderr, "[FRONTIER] dice::hfe::ui::swiffFsCommand reached (native settings/debug sink unresolved)\n"); - ::fflush(stderr); - ::abort(); + const int fallback = 0; + const bool debug = static_cast(::dice::hfe::settings)->intGet( + renddx9abi::HostString("swiffDebug"), fallback) == 1; + if (!debug) + return; + const char* const end = std::strchr(message, '\n'); + if (!end) + return; + std::size_t length = static_cast(end - message); + if (length > 0x1FE) + length = 0x1FE; + std::memcpy(s_swiffDebugLine, message, length); + s_swiffDebugLine[length] = '\0'; } @@ -153,6 +229,20 @@ static bool asLogEnabled() return s_on != 0; } +static bool inputLogEnabled() +{ + const char* value = ::getenv("BF2_SWIFFPLAYER_INPUTLOG"); + return value && value[0] == '1' && value[1] == '\0'; +} + +static bool mouseLogEnabled() { return asLogEnabled() || inputLogEnabled(); } + +static void swiffInputLogCb(bool, const char* message) +{ + if (message && ::strncmp(message, "[mouse]", 7) == 0) + ::renddx9abi::logf("%s", message); +} + // [TEMP] [CHOSEN, not recovered] BF2_SWIFFPLAYER_STREAMLOG=N traces player inputs and displays. // Logs the first N displays, then every 100th; disabled unless configured. @@ -289,6 +379,29 @@ struct SwfAsTraceScope const char* name; SwfAsTraceScope(const gameswf::fn_call& f, const char* n) : fn(f), name(n) { +#if !defined(_MSC_VER) + // [TEMP] c-swf-disconnect: menu -> engine calls for the [swf-list] tracer, one line each + // with the first arguments. Outside a mouse pass a name is logged 20 times, then muted + // (per-frame polls); inside a mouse pass every call is logged. + if (gameswf::swf_list_trace_on()) + { + static std::map s_counts; + int& count = s_counts[name]; + if (gameswf::g_swf_mouse_pass_depth > 0 || count < 20) + { + char args[200]; + int len = 0; + args[0] = '\0'; + for (int i = 0; i < fn.nargs && i < 4 && len < (int)sizeof(args) - 1; ++i) + { + const char* a = fn.arg(i).to_string(); + len += ::snprintf(args + len, sizeof(args) - len, "%s\"%.40s\"", i ? "," : "", a ? a : ""); + } + SWF_LIST_TRACE("as %s(%s)%s", name, args, count == 19 && gameswf::g_swf_mouse_pass_depth == 0 ? " [muted from now on outside mouse passes]" : ""); + } + count++; + } +#endif if (!asLogEnabled()) return; ::renddx9abi::logf("[as] enter %s (nargs=%d)", name, fn.nargs); for (int i = 0; i < fn.nargs; ++i) @@ -299,6 +412,20 @@ struct SwfAsTraceScope } ~SwfAsTraceScope() { +#if !defined(_MSC_VER) + // [TEMP] c-swf-disconnect: a result that differs from this call's previous one (messages + // and states the menu polls), always inside a mouse pass. + if (gameswf::swf_list_trace_on()) + { + static std::map s_last; + const char* r = fn.result ? fn.result->to_string() : 0; + std::string now = r ? r : ""; + std::string& last = s_last[name]; + if (now != last || gameswf::g_swf_mouse_pass_depth > 0) + SWF_LIST_TRACE("as %s -> \"%.80s\"", name, now.c_str()); + last = now; + } +#endif if (!asLogEnabled()) return; const char* s = fn.result ? fn.result->to_string() : 0; ::renddx9abi::logf("[as] leave %s -> \"%s\"", name, s ? s : ""); @@ -324,7 +451,7 @@ void as_cursor_setCursor(const gameswf::fn_call& fn) SWF_AS_TRACE("as_cursor_setCursor"); ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); const std::string name(fn.arg(0).to_string()); - (void) h->setPlayerRenderCapability0(static_cast(reinterpret_cast(&name))); // +0x68 + (void) h->setPlayerRenderCapability0(reinterpret_cast(&name)); // +0x68 } // Requests the cursor name through a preconstructed string. Returns the string, or the @@ -334,7 +461,7 @@ void as_cursor_getCursor(const gameswf::fn_call& fn) SWF_AS_TRACE("as_cursor_getCursor"); ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); std::string out; - const bool ok = h->setPlayerRenderCapability1(static_cast(reinterpret_cast(&out))); // +0x70 + const bool ok = h->setPlayerRenderCapability1(reinterpret_cast(&out)); // +0x70 fn.result->set_tu_string(tu_string(ok ? out.c_str() : "undefined")); } @@ -486,33 +613,6 @@ void as_profile_getLoginStatus(const gameswf::fn_call& fn) fn.result->set_double(status); } -// The original VC7.1 LocalProfileManager vector: the allocator word first, then first/last/end -// (sub_10060030 zeroes the three words after a one-word head and reads the count from them). A -// three-word layout put the callee's writes one slot off: retail runs R..AA counted 0 profiles and -// the movie took the first-time "newbie" page instead of "login". -struct Vc71Vector { int alloc; char* first; char* last; char* end; }; - -// One local profile record (176 bytes): six VC7.1 std::strings, destroyed in the shipped order by -// sub_1001DC10 (+140, +112, +84, +56, +28, +0), then the vector buffer goes back to the engine heap -// (sub_1001FE70 -> bf_free). The retained vc71::string storage now uses the shared native CRT. -// Fields the original list bodies read: [0] the profile id GlobalSettings compares, -// [1] profileName, [2] the offline display name, [3] the GameSpy nick (empty = offline), [5] password. -struct LocalProfileRecord { vc71::string s[6]; char tail[8]; }; -static_assert(sizeof(LocalProfileRecord) == 176, "LocalProfileRecord must be 176 bytes (sub_10015040)"); - -static void destroyLocalProfiles(Vc71Vector& v) -{ - if (!v.first) return; - const int n = static_cast((v.last - v.first) / 176); - for (int i = 0; i < n; ++i) - { - LocalProfileRecord* r = reinterpret_cast(v.first + 176 * i); - for (int k = 5; k >= 0; --k) r->s[k].~string(); - } - ::renddx9abi::engineFree(v.first); - v.first = v.last = v.end = 0; -} - // unguarded registry lookup; absent singleton -> numeric 0. // A present owner fills an empty vector with validOnly=true, return ignored. // Its signed count is assigned before record strings and vector storage die. @@ -530,6 +630,7 @@ void as_profile_getNumLocalProfiles(const gameswf::fn_call& fn) // Forward declarations of the SwiffHost dispatch helpers used by the AS bodies below; they are // defined further down, beside the other rc*/host* raw-vtable helpers. +#if defined(_MSC_VER) inline bool hostIsGameRunning(void* h, bool* out); inline int hostGetActivateReason(void* h); inline void hostSetActivateReason(void* h, int v); @@ -553,6 +654,7 @@ inline void hostSetIndexedInt(void* h, int index, int value); inline void* hostGetServerLogoManager(void* h); inline void hostGetJoinPassword(void* h, void* outStr); inline void hostSetJoinPassword(void* h, const void* str); +#endif // Logic callbacks dispatch through the player's ISwiffHost. @@ -632,7 +734,7 @@ void as_locale_getString(const gameswf::fn_call& fn) renddx9abi::HostString ids(fn.arg(0).to_string()); std::wstring out; h->getLocalizedString(out, ids); - gameswf::assign_dice_string_object_wide(text, reinterpret_cast(out.c_str())); + gameswf::assign_dice_string_object_wide(text, BF2_DICE_UTF16(out.c_str())); fn.result->set_as_object_interface(text); } @@ -671,7 +773,11 @@ void as_logic_setDecimals(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_logic_setDecimals"); const float value = static_cast(fn.arg(0).to_number()); +#if defined(__APPLE__) + const int decimals = bf2x87::toIntTruncate(fn.arg(1).to_number()); +#else const int decimals = static_cast(fn.arg(1).to_number()); +#endif const std::string format = swiffFormatString("%%.%df", decimals); const std::string text = swiffFormatString(format.c_str(), static_cast(value)); fn.result->set_tu_string(tu_string(text.c_str())); @@ -760,6 +866,12 @@ struct ListResult gameswf::array_object_push(arr.get_ptr(), gameswf::as_value(row.get_ptr())); ++rows; } + // sub_1001C920 - a row whose id is a vsprintf result (the shipped 0x100F70F0 buffer). + void beginRowFormatted(const char* fmt, int v) + { + char buf[64]; ::sprintf(buf, fmt, v); + beginRowStr(buf); + } void setInt(const char* key, int v) { char buf[16]; ::sprintf(buf, "%d", v); @@ -769,7 +881,7 @@ struct ListResult void pushWide(const wchar_t* w, int n) { gameswf::array_object_push(row.get_ptr(), - gameswf::as_value(gameswf::create_dice_string_object(reinterpret_cast(w), n))); + gameswf::as_value(gameswf::create_dice_string_object(BF2_DICE_UTF16(w), n))); } void pushNarrow(const char* v) { gameswf::array_object_push(row.get_ptr(), gameswf::as_value(tu_string(v ? v : ""))); } // sub_1001CC50 - an int column: "%d" through the shipped 256-byte global (byte_100F78F0), then @@ -780,7 +892,7 @@ struct ListResult void setWide(const char* key, const wchar_t* w, int n) { rowObj->set_member(key, gameswf::as_value( - gameswf::create_dice_string_object(reinterpret_cast(w), n))); + gameswf::create_dice_string_object(BF2_DICE_UTF16(w), n))); } void setTotalCount(int n) { @@ -800,6 +912,32 @@ static void hostLocalise(ISwiffHost* h, const char* key, HostWide& out) h->getLocalizedString(out, renddx9abi::HostString(key)); } +// sub_10013740 - whether the mod holds a map whose path or display name equals `map`, compared with +// _stricmp after every '_' became a space. The shipped helper rewrites the caller's string in place +// first (both callers pass a temporary), then compares copies of each map's display name, then its +// path; the first equal map answers true. Neither the mod nor the map list is null-tested. +static void underscoresToSpaces(std::string& s) +{ + for (std::string::size_type i = 0; i < s.size(); ++i) + if (s[i] == '_') + s[i] = ' '; +} + +static bool modHasMap(const IModInfo::Mod* mod, std::string& map) +{ + underscoresToSpaces(map); + for (unsigned int i = 0; i < mod->maps.size(); ++i) + { + std::string name = mod->maps[i].name; // PE +0x1C, copied first + std::string path = mod->maps[i].path; // PE +0x00 + underscoresToSpaces(name); + underscoresToSpaces(path); + if (::_stricmp(name.c_str(), map.c_str()) == 0 || ::_stricmp(path.c_str(), map.c_str()) == 0) + return true; + } + return false; +} + // dice.bf2.EndOfRound - the current-map surface read by endOfRound.swf's loading and briefing // frames. These eight bodies are the complete PE rows at 100102D0 / 100107E0..10010B9D / @@ -858,7 +996,7 @@ void as_endofround_getMapDescription(const gameswf::fn_call& fn) const std::string& key = !map->briefingLocId.empty() ? map->briefingLocId : map->briefing; HostWide wide; g_swiffPlayerInstance->getSwiffHost()->getLocalizedString(wide, key); - gameswf::assign_dice_string_object_wide(text, reinterpret_cast(wide.c_str())); + gameswf::assign_dice_string_object_wide(text, BF2_DICE_UTF16(wide.c_str())); } fn.result->set_as_object_interface(text); } @@ -902,7 +1040,7 @@ void as_endofround_getMapGameModeDescription(const gameswf::fn_call& fn) const std::string& key = !mt->locId.empty() ? mt->locId : mt->description; HostWide wide; g_swiffPlayerInstance->getSwiffHost()->getLocalizedString(wide, key); - gameswf::assign_dice_string_object_wide(text, reinterpret_cast(wide.c_str())); + gameswf::assign_dice_string_object_wide(text, BF2_DICE_UTF16(wide.c_str())); found = true; break; } @@ -953,7 +1091,11 @@ void as_endofround_getTeamName(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_endofround_getTeamName"); ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); +#if defined(__APPLE__) + const int team = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int team = (int) fn.arg(0).to_number(); +#endif const std::string name = h->getTeamName(team); // +0x17C fn.result->set_tu_string(tu_string(name.c_str())); } @@ -964,7 +1106,11 @@ void as_endofround_getNumVictories(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_endofround_getNumVictories"); ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); +#if defined(__APPLE__) + const int team = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int team = (int) fn.arg(0).to_number(); +#endif SwiffEndOfRoundSummary summary; (void) h->getEndOfRoundSummary(summary); // +0x1A4 fn.result->set_double((double) summary.teams[team].roundsWon); // team unchecked @@ -991,7 +1137,11 @@ void as_endofround_getTicketHistorySum(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_endofround_getTicketHistorySum"); ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); +#if defined(__APPLE__) + const int team = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int team = (int) fn.arg(0).to_number(); +#endif SwiffEndOfRoundSummary summary; if (!h->getEndOfRoundSummary(summary)) { @@ -1025,7 +1175,11 @@ void as_endofround_getPreviousTeamName(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_endofround_getPreviousTeamName"); ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); +#if defined(__APPLE__) + const int team = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int team = (int) fn.arg(0).to_number(); +#endif fn.result->set_tu_string(tu_string(h->getEndOfRoundInfo()->teams[team].name.c_str())); // team unchecked } @@ -1039,7 +1193,11 @@ void as_endofround_getSquadTeamName(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_endofround_getSquadTeamName"); ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); +#if defined(__APPLE__) + const int team = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int team = (int) fn.arg(0).to_number(); +#endif const SwiffEndOfRoundInfo* rec = h->getEndOfRoundInfo(); gameswf::as_object_interface* text = gameswf::create_dice_string_object(0, 0); HostWide title; @@ -1055,7 +1213,7 @@ void as_endofround_getSquadTeamName(const gameswf::fn_call& fn) const std::string key = std::string("EOR_best") + name + "squad"; hostLocaliseAlways(std::string(key.c_str()), title); } - gameswf::assign_dice_string_object_wide(text, reinterpret_cast(title.c_str())); + gameswf::assign_dice_string_object_wide(text, BF2_DICE_UTF16(title.c_str())); fn.result->set_as_object_interface(text); } @@ -1098,7 +1256,7 @@ void as_endofround_getPreviousMapDescription(const gameswf::fn_call& fn) { HostWide wide; hostLocaliseAlways(map->briefingLocId != "" ? map->briefingLocId : map->briefing, wide); - gameswf::assign_dice_string_object_wide(text, reinterpret_cast(wide.c_str())); + gameswf::assign_dice_string_object_wide(text, BF2_DICE_UTF16(wide.c_str())); } fn.result->set_as_object_interface(text); } @@ -1150,7 +1308,7 @@ void as_endofround_getPreviousMapGameModeDescription(const gameswf::fn_call& fn) if (mt->players != size) continue; HostWide wide; hostLocaliseAlways(mt->locId != "" ? mt->locId : mt->description, wide); - gameswf::assign_dice_string_object_wide(text, reinterpret_cast(wide.c_str())); + gameswf::assign_dice_string_object_wide(text, BF2_DICE_UTF16(wide.c_str())); found = true; break; } @@ -1176,7 +1334,11 @@ void as_endofround_getPreviousMapGameModeName(const gameswf::fn_call& fn) void as_endofround_getKitNameFromId(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_endofround_getKitNameFromId"); +#if defined(__APPLE__) + const int id = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int id = (int) fn.arg(0).to_number(); +#endif const char* name = ""; switch (id) { @@ -1199,7 +1361,11 @@ void as_endofround_getTeamNameOfPlayerAtPosition(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_endofround_getTeamNameOfPlayerAtPosition"); ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); +#if defined(__APPLE__) + const int position = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int position = (int) fn.arg(0).to_number(); +#endif std::string team(""); if (h->getEndOfRoundInfo()->topPlayers[position].name != "") team = h->getEndOfRoundInfo()->topPlayers[position].team; @@ -1483,7 +1649,9 @@ static const char* serverOsIcon(const char* os) // queries use separate caches; sponsors may issue a query on a cache miss. Joining clears // the separate in-game server-info keys. +#if !defined(__APPLE__) extern "C" __declspec(dllimport) void* __stdcall SetCursor(void* cursor); +#endif typedef ServerBrowserRecord CachedRecord; struct RecordCache { @@ -1784,7 +1952,7 @@ static gameswf::as_object_interface* videoSettingsLocalisedString(const renddx9a { (void) h->getLocalizedString(wide, key); // +0xA8 text = gameswf::create_dice_string_object(nullptr, 0); - gameswf::assign_dice_string_object_wide(text, reinterpret_cast(wide.c_str())); + gameswf::assign_dice_string_object_wide(text, BF2_DICE_UTF16(wide.c_str())); } return text; } @@ -1832,7 +2000,11 @@ static void markCustomVideoScheme() static void setVideoIntOwnerFirst(const gameswf::fn_call& fn, VsIntSetter setter) { IVideoSettings* vs = videoSettings(); +#if defined(__APPLE__) + const int value = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int value = static_cast(fn.arg(0).to_number()); +#endif (vs->*setter)(value); markCustomVideoScheme(); } @@ -1843,7 +2015,11 @@ static void setVideoIntOwnerFirst(const gameswf::fn_call& fn, VsIntSetter setter // kept per row. No result. static void setVideoIntArgumentFirst(const gameswf::fn_call& fn, VsIntSetter setter) { +#if defined(__APPLE__) + const int value = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int value = static_cast(fn.arg(0).to_number()); +#endif (videoSettings()->*setter)(value); markCustomVideoScheme(); } @@ -2077,6 +2253,23 @@ static void listLeaderboardPlayers(const gameswf::fn_call& fn, ListResult& r, Li static void listLeaderboardTop(const gameswf::fn_call& fn, ListResult& r, ListHost h); static void listMapList(const gameswf::fn_call& fn, ListResult& r, ListHost h, int start, int end); static void listGameModes(const gameswf::fn_call& fn, ListResult& r, ListHost h, int start, int end, bool withAll); +// The HapticSettings page's two selectors, defined with the HapticSettings rows (SwiffNativesRecovered.inl). +static void listHapticWeaponSelect(const gameswf::fn_call& fn, ListResult& r, ListHost h); +static void listHapticThresholdSelect(const gameswf::fn_call& fn, ListResult& r, ListHost h); +// The remaining shipped branches (frontier batch 12), defined after the team-manager helpers. +static void listMissions(const gameswf::fn_call& fn, ListResult& r, ListHost h, int start, int end); +static void listProfileSearch(const gameswf::fn_call& fn, ListResult& r, ListHost h, int start, int end); +static void listMods(const gameswf::fn_call& fn, ListResult& r, ListHost h, int start, int end); +static void listTeamSummary(const gameswf::fn_call& fn, ListResult& r, ListHost h, const char* word1); +static void listDateOfBirth(const gameswf::fn_call& fn, ListResult& r, const char* word1, int start, int end); +static void listGender(const gameswf::fn_call& fn, ListResult& r); +static void listModFilter(const gameswf::fn_call& fn, ListResult& r, ListHost h); +static void listSuggestedNicks(const gameswf::fn_call& fn, ListResult& r, int start, int end); +static void listUnlockWeapons(const gameswf::fn_call& fn, ListResult& r, ListHost h, int start, int end); +static void listCurrentUnlockStats(const gameswf::fn_call& fn, ListResult& r, ListHost h); +static void listCredits(const gameswf::fn_call& fn, ListResult& r, ListHost h, int start, int end); +static void listAges(const gameswf::fn_call& fn, ListResult& r, int start, int end); +static void listRanks(const gameswf::fn_call& fn, ListResult& r, ListHost h, int start, int end); void as_general_getListEntries(const gameswf::fn_call& fn) { @@ -2112,8 +2305,16 @@ void as_general_getListEntries(const gameswf::fn_call& fn) tok[t++] = tu_string(b, (int)(c - b)); } } +#if defined(__APPLE__) + const int start = bf2x87::toIntTruncate(fn.arg(1).to_number()); +#else const int start = (int) fn.arg(1).to_number(); +#endif +#if defined(__APPLE__) + const int count = bf2x87::toIntTruncate(fn.arg(2).to_number()); +#else const int count = (int) fn.arg(2).to_number(); +#endif const int end = (count == -1) ? start + 99999 : start + count; ListResult r; @@ -2224,7 +2425,7 @@ void as_general_getListEntries(const gameswf::fn_call& fn) int total = 0; int greyed = 0, emittedRows = 0; // diagnostic only, reported under the AS log below int gateNoMod = 0, gateVersion = 0, gateNoMap = 0; - vc71::string firstMod, firstMap; // retained internal diagnostic storage + std::string firstMod, firstMap; // retained internal diagnostic storage IModInfo* modInfo = static_cast(h->getModInfo()); // +0x120 const int count = serverRecordCount(h->getServerList(std::string("inet"))->getRecords()); total = count; @@ -2391,6 +2592,111 @@ void as_general_getListEntries(const gameswf::fn_call& fn) fn.result->set_as_object_interface(r.arr.get_ptr()); return; } + // SwiffPlayer.dll 0x10023EBF..0x10024B00 (favourites pass, then the "history" pass at + // 0x10024AA2): row keys, icon columns and the "-"/"*" columns in the order shown here. + if (tok[0] == "favouriteServers") + { + IGeneralSettings* settings = static_cast( + classManager->getSingleton(renddx9abi::HostString("GeneralSettings"))); + IModInfo* modInfo = static_cast(h->getModInfo()); + r.begin(); + unsigned int emitted = 0; + unsigned int total = 0; + const unsigned int window = static_cast(end - start); + // The history pass deliberately starts at zero, even when start exceeds + // the favourites count. Both passes share the emitted-row budget. + for (int pass = 0; pass != 2; ++pass) + { + const bool favourite = pass == 0; + const char* kind = favourite ? "favourites" : "history"; + const unsigned int count = serverRecordCount(h->getServerList(std::string(kind))->getRecords()); + total += count; + for (unsigned int index = favourite ? static_cast(start) : 0; + index < count && emitted < window; ++index) + { + const ServerBrowserRecordList* records = h->getServerList(std::string(kind))->getRecords(); + if (records->records.empty()) continue; + const ServerBrowserEntry& e = records->records[index].entry; + const IModInfo::Mod* mod = modInfo->getModFromName(e.gameVariant); + const std::string mapPath = modInfo->getMapPathFromMap(mod, e.mapName); + const IModInfo::Map* knownMap = modInfo->findMapFromMod(mod, mapPath); + char id[128]; + ::_snprintf(id, sizeof(id) - 1, "%s %d %d", e.address.c_str(), e.queryPort, e.hostPort); + id[sizeof(id) - 1] = 0; + r.beginRowStr(id); + r.setString("ip", e.address.c_str()); + r.setInt("port", e.queryPort); + r.setInt("pb", e.antiCheat ? 1 : 0); + const std::string ourVersion = h->getVersionStringValue(); + const bool xpack1 = h->getExpansionPack(e.gameVariant) == 1; + const bool xpack2 = h->getExpansionPack(e.gameVariant) == 2; + if (e.maxPlayers <= 0 || (!mod && !xpack1 && !xpack2) + || (mod && (e.gameVersion != ourVersion || !knownMap))) + r.setInt("disabled", 1); + r.setInt("xpack1", xpack1 ? 1 : 0); + r.setInt("xpack2", xpack2 ? 1 : 0); + r.setInt("plasma", e.plasma ? 1 : 0); + if (!knownMap) r.setInt("mapnotinstalled", 1); + if (knownMap) + r.setString("mapName", modInfo->getMapPathFromMap(mod, e.mapName).c_str()); + else + r.setString("mapName", " "); + r.setInt("mapMode", e.maxPlayers); + r.setString("gameMode", e.gameMode.c_str()); + r.setInt("maxPlayers", e.maxPlayers); + r.setInt("mapSize", e.mapSize); + r.pushNarrow(e.fps >= 30.0f ? "images/serverIcons/Serverload_green.png" + : e.fps >= 20.0f ? "images/serverIcons/Serverload_orange.png" + : "images/serverIcons/Serverload_red.png"); + r.pushNarrow(serverOsIcon(e.os.c_str())); + if (mod) + { + const std::string icon = "#" + mod->path + "/" + mod->icon; + r.pushNarrow(icon.c_str()); + } + else r.pushNarrow("images/serverIcons/modNotInstalled.png"); + r.pushNarrow(e.ranked ? "images/serverIcons/ranked.png" : ""); + r.pushNarrow(e.voip ? "images/serverIcons/battlecom.png" : ""); + r.pushNarrow(e.antiCheat ? "images/serverIcons/punkbuster.png" : ""); + r.pushNarrow(e.pure ? "images/serverIcons/PureContent.png" : ""); + r.pushNarrow(e.password ? "images/serverIcons/passwordenabled.png" : ""); + const GeneralServerEntry* saved = favourite + ? settings->findFavouriteServer(e.address, e.queryPort) + : settings->findServerHistory(e.address, e.queryPort); + if (e.maxPlayers == 0) + { + // An unanswered record without a saved entry retains only + // its icon columns, as in the shipped menu bridge. + if (saved) + { + r.pushNarrow(saved->name.c_str()); + r.pushNarrow("-"); r.pushNarrow("-"); r.pushNarrow("-"); + r.pushNarrow(favourite ? "*" : "-"); + } + } + else + { + r.pushNarrow(saved ? saved->name.c_str() : e.hostName.c_str()); + r.pushInt(e.ping); + char players[64]; + ::_snprintf(players, sizeof(players) - 1, "%d/%d (%d)", + e.numPlayers, e.maxPlayers, e.reservedSlots); + players[sizeof(players) - 1] = 0; + r.pushNarrow(players); + r.pushNarrow(e.mapName.c_str()); + if (favourite) r.pushNarrow("*"); + else if (saved) r.pushInt(saved->lastPlayed); + else r.pushNarrow("-"); + } + r.setInt("password", e.password ? 1 : 0); + if (favourite) r.setInt("isFavourite", 1); + ++emitted; + } + } + r.setTotalCount(total); + fn.result->set_as_object_interface(r.arr.get_ptr()); + return; + } if (tok[0] == "installedMaps") { // Lists current-mod maps supporting the selected mode, one row per map size. @@ -3001,18 +3307,102 @@ void as_general_getListEntries(const gameswf::fn_call& fn) // Local-server game modes and browser-filter game modes with an additional All choice. if (tok[0] == "gmodes") { listGameModes(fn, r, h, start, end, false); return; } if (tok[0] == "sfgmodes") { listGameModes(fn, r, h, start, end, true); return; } - if (tok[0] == "cmapbg" || tok[0] == "cmapgm" || tok[0] == "buddiesOnline" || tok[0] == "buddies" - || tok[0] == "buddyRequests" || tok[0] == "buddyMessages" || tok[0] == "gamespyNicknameSuggestions") + // The HapticSettings selectors (10030F66 "weaponselect", 10031374 "thresholdselect"); they read no window. + if (tok[0] == "weaponselect") { listHapticWeaponSelect(fn, r, h); return; } + if (tok[0] == "thresholdselect") { listHapticThresholdSelect(fn, r, h); return; } + // The demo-bookmark list (1002B517..1002B6B4): the LocalProfileManager by name, NOT null-tested, + // its +0xA8 count and +0xAC record per index. Per row inside the window the current mod + // (+0x120 getModInfo, +0x1C getCurrentMod) must hold the bookmark's map, compared by its + // display name (PE +0x3C getMapNameFromMap of field1c); a row that fails is neither listed nor + // counted, while rows outside the window are counted unfiltered, as shipped. Columns: + // field54, field00, the map display name asked a second time. + if (tok[0] == "demobm") { + ILocalProfileManager* lpm = static_cast( + classManager->getSingleton(renddx9abi::HostString("LocalProfileManager"))); r.begin(); - r.setTotalCount(0); + int total = 0; + const unsigned int n = lpm->getNumDemoBookmarks(); // +0xA8 + for (unsigned int i = 0; i < n; ++i) + { + if (i < static_cast(start) || i >= static_cast(end)) + { + ++total; + continue; + } + const LocalDemoBookmark* bm = lpm->getDemoBookmark(i); // +0xAC + const IModInfo::Mod* mod = static_cast(h->getModInfo())->getCurrentMod(); // +0x120, +0x1C + std::string mapName = static_cast(h->getModInfo())->getMapNameFromMap(bm->field1c); // PE +0x3C + if (!modHasMap(mod, mapName)) + continue; + r.beginRow(static_cast(i)); + r.pushNarrow(bm->field54.c_str()); + r.pushNarrow(bm->field00.c_str()); + const std::string shown = static_cast(h->getModInfo())->getMapNameFromMap(bm->field1c); // PE +0x3C + r.pushNarrow(shown.c_str()); + ++total; + } + r.setTotalCount(total); + fn.result->set_as_object_interface(r.arr.get_ptr()); + return; + } + // The recorded-demo list (1002B71B..1002B8B4): host +0x44 getDemoLibrary, its +0x18 count read + // once, then per index inside the window host +0x44 again and +0x1C getEntry. The current mod + // must hold the entry's map, compared on a copy of the raw mapName; failing rows are neither + // listed nor counted, rows outside the window are counted. Columns: dateTime, name, the map + // display name (PE +0x3C getMapNameFromMap); a demo whose version is not 3153 (0xC51, this + // build) gets "disabled" 1. + if (tok[0] == "demos") + { + r.begin(); + int total = 0; + const unsigned int n = static_cast(h->getDemoLibrary())->getNumEntries(); // +0x44, +0x18 + for (unsigned int i = 0; i < n; ++i) + { + if (i < static_cast(start) || i >= static_cast(end)) + { + ++total; + continue; + } + const DemoLibraryEntry* e = static_cast(h->getDemoLibrary())->getEntry(i); // +0x44, +0x1C + const IModInfo::Mod* mod = static_cast(h->getModInfo())->getCurrentMod(); // +0x120, +0x1C + std::string mapName = e->mapName; + if (!modHasMap(mod, mapName)) + continue; + r.beginRow(static_cast(i)); + r.pushNarrow(e->dateTime.c_str()); + r.pushNarrow(e->name.c_str()); + const std::string shown = static_cast(h->getModInfo())->getMapNameFromMap(e->mapName); // PE +0x3C + r.pushNarrow(shown.c_str()); + if (e->version != 0xC51) + r.setInt("disabled", 1); + ++total; + } + r.setTotalCount(total); fn.result->set_as_object_interface(r.arr.get_ptr()); return; } - // [FRONTIER] [RETIRE-WHEN: RW-88] Always reported, not only under the AS log: this row is live - // now, so an unread branch must name itself every time it is reached rather than answer quietly. - ::renddx9abi::logf("[FRONTIER] dice.General.getListEntries: list '%s' not written (sub_10022610 branch unread)", id.c_str()); - fn.result->set_undefined(); + // The branches frontier batch 12 recovered, at their compare addresses in sub_10022610. + if (tok[0] == "missionList") { listMissions(fn, r, h, start, end); return; } // 10023D53 + if (tok[0] == "serverHistory") return; // 1002563C: no result + if (tok[0] == "profileSearch") { listProfileSearch(fn, r, h, start, end); return; } // 100260D5 + if (tok[0] == "mods") { listMods(fn, r, h, start, end); return; } // 1002693F + if (tok[0] == "teamSummary") { listTeamSummary(fn, r, h, tok[1].c_str()); return; } // 100275B1 + if (tok[0] == "dateOfBirth") { listDateOfBirth(fn, r, tok[1].c_str(), start, end); return; } // 10028B52 + if (tok[0] == "gender") { listGender(fn, r); return; } // 10028E93 + if (tok[0] == "modfilter") { listModFilter(fn, r, h); return; } // 1002DD11 + if (tok[0] == "suggestNicks") { listSuggestedNicks(fn, r, start, end); return; } // 1002DEFC + if (tok[0] == "uweapons") { listUnlockWeapons(fn, r, h, start, end); return; } // 10030026 + if (tok[0] == "custats") { listCurrentUnlockStats(fn, r, h); return; } // 100304A7 + if (tok[0] == "credits") { listCredits(fn, r, h, start, end); return; } // 10030A17 + if (tok[0] == "age") { listAges(fn, r, start, end); return; } // 10030B66 + if (tok[0] == "ranklist") { listRanks(fn, r, h, start, end); return; } // 10030BF4 + // loc_1003147D, the chain's shared empty exit: begin, totalCount 0, publish. serverMessage + // (1002776B), cmapbg and cmapgm, the four buddy lists, gamespyNicknameSuggestions and every + // name nothing matches answer this. + r.begin(); + r.setTotalCount(0); + fn.result->set_as_object_interface(r.arr.get_ptr()); } // PE1005FCF0..1005FD82, helper10013520: a guarded registry SwiffHost owns @@ -3021,13 +3411,12 @@ void as_general_getListEntries(const gameswf::fn_call& fn) // The callback reads no arguments and leaves the AS result untouched. struct SwiffHostRequest { - int id; - int alloc; - vc71::string* first; - vc71::string* last; - vc71::string* end; + int id; // +0 + std::vector args; // +4 (retail: a VC7.1 vector of strings) }; +#if !defined(__APPLE__) extern "C" __declspec(dllimport) void* __stdcall SetCursor(void* cursor); +#endif void as_profile_logout(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_profile_logout"); @@ -3051,6 +3440,7 @@ void as_profile_logout(const gameswf::fn_call& fn) } } + void as_logic_disconnectGame(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_logic_disconnectGame"); @@ -3128,10 +3518,18 @@ void as_logic_getCommandLine(const gameswf::fn_call& fn) // Joins the command-line address using the configured game port and query port zero. // Returns numeric 1 or 0, not Boolean; destroys the address before publishing the result. +// SwiffPlayer.dll 0x1004D740: port (+0xE4), address (+0xDC), joinServer (+0x100); nothing else. void as_logic_joinCommandlineServer(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_logic_joinCommandlineServer"); ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + // [CHOSEN, not recovered] Retail drops +password on this path: BF2Engine::joinServer (BF2.exe + // 0x405C10) overwrites GSPassword with the menu's join password (+0x180), which only the in-menu + // password dialog sets, and the shipped menu script never reads getCommandlineServerPassword, so + // a passworded server refused every command-line join (owner decision 2026-11-14: fix it). The + // command-line password (+0xE0, GSPassword) becomes the join password when the menu has none. + if (h->getJoinPassword().empty()) // +0x180 + h->setJoinPassword(h->getPasswordSetting()); // +0x184 <- +0x0E0 const int port = h->getPortSetting(); // +0x0E4 const std::string address = h->getJoinAddressSetting(); // +0x0DC const bool ok = h->joinServer(address, port, 0); // +0x100 @@ -3139,11 +3537,17 @@ void as_logic_joinCommandlineServer(const gameswf::fn_call& fn) } // sub_1004D450 - dice.bf2.Logic.isCapsLockPressed: GetKeyState(VK_CAPITAL) & 1, a boolean. No host. +#if !defined(__APPLE__) extern "C" __declspec(dllimport) short __stdcall GetKeyState(int vkey); +#endif void as_logic_isCapsLockPressed(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_logic_isCapsLockPressed"); +#if defined(__APPLE__) + fn.result->set_bool((capsLockKeyState() & 1) != 0); +#else fn.result->set_bool((GetKeyState(20) & 1) != 0); +#endif } // Returns host GameSpy availability as Boolean. Requires player/host and blocks while @@ -3200,6 +3604,32 @@ void as_logic_setStorageString(const gameswf::fn_call& fn) h->setStorageString(a, b); } +// sub_1004D170 (registered at 0x1004E3E3 as "eraseStorageString", string 0x100DD020): fetch the +// player's host (dword_100F2F20 +0x5C), construct a string from arg 0 (no nargs guard; the +// shipped argument index check is the debug int3), call host +0x240, destroy it. No AS result. +void as_logic_eraseStorageString(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_logic_eraseStorageString"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + renddx9abi::HostString key(fn.arg(0).to_string()); + h->removeStorageString(key); // +0x240 +} + +// sub_1004D5B0 (registered at 0x1004E43B as "getDefaultLevel", string 0x100DD010): fetch the +// player's host, construct an empty string, call host +0xA4 getSpStartupMap(out) and ignore its +// Boolean, then publish the string as the AS result (as_value type 1 built by sub_10007680 from +// c_str()). mainMenu.swf's createDefaultTraining (the welcome page's PLAY SINGLEPLAYER) passes this +// value to Multiplay.addMapToMapList; without the binding the call answered undefined, the empty +// path added no entry, and createServer's hostServer posted "nomapsselected". +void as_logic_getDefaultLevel(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_logic_getDefaultLevel"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + renddx9abi::HostString out; // the host assigns to this already constructed string + (void) h->getSpStartupMap(out); // +0xA4 + fn.result->set_tu_string(tu_string(out.c_str())); +} + } // anonymous namespace // Queues the named engine sound. Host refusal publishes numeric -1; success leaves @@ -3360,7 +3790,11 @@ void as_videosettings_getViewDistanceScale(const gameswf::fn_call& fn) void as_videosettings_setVideoOptionScheme(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_videosettings_setVideoOptionScheme"); +#if defined(__APPLE__) + const int scheme = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int scheme = static_cast(fn.arg(0).to_number()); +#endif videoSettings()->setVideoOptionScheme(scheme); // +0xDC videoSettings()->applyVideoOptionScheme(0); // +0x30 } @@ -3496,6 +3930,7 @@ void as_logic_enableScroller(const gameswf::fn_call& fn) h->setFlagF10(fn.arg(0).to_bool()); } + // Stops updates on the current browser list when it exists. Requires player/host. // Destroys the list-kind string before stopping; writes no AS result. void as_multiplay_stopBrowser(const gameswf::fn_call& fn) @@ -3534,29 +3969,15 @@ void as_multiplay_browse(const gameswf::fn_call& fn) } } -// Stops the VoIP test when its host and client exist. Only the absent-settings -// refusal normally publishes false; early returns leave the ActionScript result alone. -// [FRONTIER] [CHOSEN, not recovered] The unavailable client arm reports and continues -// with that refusal value. Reports retain a hit count and are rate-limited. -// [RETIRE-WHEN: RW-88] Replace the stop-test seam when the client and audio-settings -// calls are implemented and validated through the menu. +// byte_100F8B4D: a voice test is running (voipStartTest raises it, voipStopTest clears it). static bool s_voipTestRunning = false; -static void voipStopTestFrontier() -{ - // Reachable repeatedly once a Bf2VoipClient exists, so it is rate-limited the way this file's - // AS-error log is: the first five, then every thousandth, always carrying the count. - static unsigned s_hits = 0; - ++s_hits; - if (s_hits <= 5 || (s_hits % 1000) == 0) - { - ::renddx9abi::logf("[FRONTIER] dice::hfe::ui::as_sound_voipStopTest: the Bf2VoipClient arm " - "(sub_100BC8B0, the client's +52/+56/+20 and AudioSettings +0x54) is not " - "written; answering the shipped refusal, false. Hit #%u.", s_hits); - ::fprintf(stderr, "[FRONTIER] dice::hfe::ui::as_sound_voipStopTest: the Bf2VoipClient arm is " - "not written; answering false (hit #%u)\n", s_hits); - ::fflush(stderr); - } -} +// flt_100EC92C: the menu's capture threshold (the dice.bf2.Sound VoIP rows, SwiffNativesRecovered.inl). +static float s_voipThreshold = 0.0f; + +// sub_10069620 "voipStopTest": only while a test runs. Unmutes the host's sound groups, then with a +// client and AudioSettings ends the test: loopback off, and with a session or test still running the +// menu threshold goes back to the client and AudioSettings (+0x14, +0x54). An absent AudioSettings +// answers false; the other exits leave the result alone. void as_sound_voipStopTest(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_sound_voipStopTest"); @@ -3564,17 +3985,24 @@ void as_sound_voipStopTest(const gameswf::fn_call& fn) return; if (!g_swiffPlayerInstance) return; - ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); - h->slot18C(0); - if (!g_swiffPlayerInstance->getBf2VoipClient()) // +0x8C; absent in this tree + g_swiffPlayerInstance->getSwiffHost()->slot18C(0); // +0x5C, +0x18C + BF2VoipClient* client = static_cast(g_swiffPlayerInstance->getBf2VoipClient()); // +0x8C + if (!client) return; - if (!classManager->getSingleton(renddx9abi::HostString("AudioSettings"))) + IAudioSettings* as = static_cast( + classManager->getSingleton(renddx9abi::HostString("AudioSettings"))); + if (!as) { fn.result->set_bool(false); // the shipped refusal return; } - voipStopTestFrontier(); - fn.result->set_bool(false); + s_voipTestRunning = false; + client->setLocalLoopback(false); // 0x100BC8B0 + if (client->isTesting() || client->isActive()) // +0x34 / +0x38 + { + client->setCaptureThreshold(s_voipThreshold); // +0x14 + as->setVoipCaptureThreshold(s_voipThreshold); // +0x54 + } } // Logs into the numbered online profile after the disc check and returns Boolean success. @@ -3598,7 +4026,11 @@ void as_profile_loginOnlineAccount(const gameswf::fn_call& fn) bool result = false; if (h->checkDisc()) { +#if defined(__APPLE__) + const int number = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int number = (int) fn.arg(0).to_number(); +#endif const std::string password = fn.arg(1).to_string(); const bool remember = fn.arg(2).to_bool(); if (lpm->login(number, std::string(""), password)) @@ -3699,7 +4131,11 @@ void as_profile_loginOfflineAccount(const gameswf::fn_call& fn) (void) g_swiffPlayerInstance->getSwiffHost(); ILocalProfileManager* lpm = static_cast( classManager->getSingleton(renddx9abi::HostString("LocalProfileManager"))); +#if defined(__APPLE__) + const int number = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int number = (int) fn.arg(0).to_number(); +#endif const std::string password(""); const std::string name(""); fn.result->set_bool(lpm->login(number, name, password)); @@ -3720,7 +4156,7 @@ void as_profile_getFirstCountry(const gameswf::fn_call& fn) std::wstring w; h->getLocalizedString(w, key); tu_string utf8; - tu_string::encode_utf8_from_wchar(&utf8, reinterpret_cast(w.c_str())); + tu_string::encode_utf8_from_wchar(&utf8, BF2_DICE_UTF16(w.c_str())); fn.result->set_tu_string(utf8); } @@ -3745,7 +4181,11 @@ void as_multiplay_setConnectToIpPort(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_multiplay_setConnectToIpPort"); ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); +#if defined(__APPLE__) + h->setConnectToIpPort(bf2x87::toIntTruncate(fn.arg(0).to_number())); // +0x308, truncated +#else h->setConnectToIpPort(static_cast(fn.arg(0).to_number())); // +0x308, truncated +#endif } void as_multiplay_setConnectToIpHost(const gameswf::fn_call& fn) @@ -3768,7 +4208,9 @@ static int hostPlayerId() // The 20-byte rank-change record SwiffHost +644(playerId, record&) fills: {time(now), 0, rank, // promoted, demoted} as sub_10059A80/sub_10059C40 lay it out on their stacks. struct RankChangeRecord { int now; int zero; int rank; int promoted; int demoted; }; +#if !defined(__APPLE__) extern "C" __int64 __cdecl _time64(__int64*); +#endif // ISwiffHost +0x284 (getRankInfo). The native host's IPlayerRankInfo::RankInfo // {timestamp, profileId, rank, change, decrease} is the same five ints in the same order; a record @@ -3784,7 +4226,7 @@ static bool hostRankInfo(void* h, int playerId, RankChangeRecord& r) // ISwiffHost supplies the rank's locale key ("-" when unknown) and next promotion/demotion rank. // Copy the native string result into the retained internal key storage. -static void hostRankKey(void* h, int rankId, vc71::string& key) +static void hostRankKey(void* h, int rankId, std::string& key) { if (!h) return; key = static_cast(h)->getRankName(rankId).c_str(); @@ -3797,7 +4239,7 @@ static int hostNextRank(void* h, int rankId) // Locale.getString through SwiffHost +168 (getLocalizedString) into a wide string - defined with the // PlayerStats favourites below, used by every localising row. -static void hostLocaliseKey(void* h, const vc71::string& key, vc71::wstring& out); +static void hostLocaliseKey(void* h, const std::string& key, std::wstring& out); // sub_10059A80 - dice.bf2.PlayerStats.getPromotedRank(): the record's rank when the host filled it // and promoted >= 1, else 0. @@ -3833,14 +4275,22 @@ void as_playerstats_getNextPromotionRank(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_getNextPromotionRank"); void* h = asHost(); +#if defined(__APPLE__) + const int rank = fn.nargs >= 1 ? bf2x87::toIntTruncate(fn.arg(0).to_number()) : 0; +#else const int rank = fn.nargs >= 1 ? (int) fn.arg(0).to_number() : 0; +#endif fn.result->set_double(h ? (double) hostNextRank(h, rank) : 0.0); } void as_playerstats_getNextDemomotionRank(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_getNextDemomotionRank"); void* h = asHost(); +#if defined(__APPLE__) + const int rank = fn.nargs >= 1 ? bf2x87::toIntTruncate(fn.arg(0).to_number()) : 0; +#else const int rank = fn.nargs >= 1 ? (int) fn.arg(0).to_number() : 0; +#endif fn.result->set_double(h ? (double) hostNextRank(h, rank) : 0.0); } @@ -3851,130 +4301,159 @@ void as_playerstats_getRankString(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_getRankString"); void* h = asHost(); +#if defined(__APPLE__) + const int rank = fn.nargs >= 1 ? bf2x87::toIntTruncate(fn.arg(0).to_number()) : 0; +#else const int rank = fn.nargs >= 1 ? (int) fn.arg(0).to_number() : 0; - vc71::wstring text; +#endif + std::wstring text; if (h) { - vc71::string key; + std::string key; hostRankKey(h, rank, key); hostLocaliseKey(h, key, text); } fn.result->set_as_object_interface( - gameswf::create_dice_string_object(reinterpret_cast(text.c_str()), (int) text.size())); + gameswf::create_dice_string_object(BF2_DICE_UTF16(text.c_str()), (int) text.size())); } -// The player stats record SwiffHost +432(playerId, record&) fills: 3720 bytes, laid out by the -// shipped ctor/dtor pair sub_10020A80 / sub_10020E80 - VC7.1 std::strings at the byte offsets below -// (14 singles, 19 pairs at 528+68k {+0,+40}, 10 at 1820+40k, 7 pairs at 2224+64k {+0,+36}, 13 pairs -// at 2676+68k {+0,+36}, 4 singles), a vector at 3688 (allocator word, first/last/end zeroed), the -// creation time at 3704, every other word zero. Only what the callers read is interpreted: the rank -// id at +160 (getCurrentRankId). The vector at 3688 holds 40-byte elements with a std::string at -// +12 (sub_1001F210 destroys each, then bf_frees the buffer). +// The player stats record SwiffHost +432(playerId, record&) fills, laid out by the shipped +// ctor/dtor pair sub_10020A80 / sub_10020E80 (the +N comments are the retail offsets of its +// 3720-byte VC7.1 layout). Construction zeroes every int, leaves every string empty and stamps the +// creation time. Only what the callers read is interpreted: the rank id at +160 +// (getCurrentRankId), the rows the playerStats lists show, the favourites and the opponent/victim +// pairs. The map rows (+3688) are 40-byte retail elements with a string at +12. struct PlayerStatsRecord { - enum { SIZE = 3720 }; - unsigned char bytes[SIZE]; - static void offsets(int* out, int& n) + struct Weapon // 68 bytes in retail { - static const int singles[] = { 4, 44, 72, 192, 220, 248, 276, 304, 344, 372, 400, 428, 456, 492, 3564, 3596, 3628, 3660 }; - n = 0; - for (int i = 0; i < (int) (sizeof(singles) / sizeof(singles[0])); ++i) out[n++] = singles[i]; - for (int k = 0; k < 19; ++k) { out[n++] = 528 + 68 * k; out[n++] = 528 + 68 * k + 40; } - for (int k = 0; k < 10; ++k) { out[n++] = 1820 + 40 * k; } - for (int k = 0; k < 7; ++k) { out[n++] = 2224 + 64 * k; out[n++] = 2224 + 64 * k + 36; } - for (int k = 0; k < 13; ++k) { out[n++] = 2676 + 68 * k; out[n++] = 2676 + 68 * k + 36; } - } - PlayerStatsRecord() + std::string time; // +0 + int kills = 0; // +28 + int deaths = 0; // +32 + int accuracy = 0; // +36 + std::string kd; // +40 + }; + struct Army // 40 bytes in retail { - ::memset(bytes, 0, SIZE); - int off[128]; int n; offsets(off, n); - for (int i = 0; i < n; ++i) new (bytes + off[i]) vc71::string(""); - *reinterpret_cast(bytes + 3704) = (int) _time64(0); - } - ~PlayerStatsRecord() + std::string time; // +0 + int wins = 0; // +28 + int losses = 0; // +32 + int bestRound = 0; // +36 + }; + struct Kit // 64 bytes in retail { - int off[128]; int n; offsets(off, n); - for (int i = n - 1; i >= 0; --i) reinterpret_cast(bytes + off[i])->~string(); - char* first = *reinterpret_cast(bytes + 3692); - char* last = *reinterpret_cast(bytes + 3696); - if (first) - { - for (char* e = first; e != last; e += 40) reinterpret_cast(e + 12)->~string(); - ::renddx9abi::engineFree(first); - } - } + std::string time; // +0 + int kills = 0; // +28 + int deaths = 0; // +32 + std::string kd; // +36 + }; + struct Vehicle // 68 bytes in retail + { + std::string time; // +0 + int kills = 0; // +28 + int deaths = 0; // +32 + std::string kd; // +36 + int roadKills = 0; // +64 + }; + struct MapRow // 40 bytes in retail + { + int id = 0; // +0 + int wins = 0; // +4 + int losses = 0; // +8 + std::string time; // +12 + }; + + int playerId = 0; // +0 + std::string nick; // +4 + int scor = 0, wins = 0, loss = 0; // +32 +36 +40 + std::string jond, lbtl; // +44 +72 + int twsc = 0, cpcp = 0, cacp = 0, dfcp = 0, kila = 0; // +100..+116 + int heal = 0, rviv = 0, rsup = 0, rpar = 0, tgte = 0; // +120..+136 + int dkas_dsab = 0; // +140 + int unknown144[3] = { 0, 0, 0 }; // +144..+152 no reader + int cdsc = 0, rank = 0; // +156 +160 + int unknown164 = 0; // +164 no reader + int cmsc = 0, kick = 0, ban = 0, kill = 0, deth = 0, suic = 0; // +168..+188 + std::string ospm, klpm, dtpm, klpr, dtpr; // +192..+304 + int bksk = 0, wdsk = 0, bbrs = 0; // +332..+340 + std::string tcdr, tsql, tsqm, tlwf; // +344..+428 + std::string mvns; // +456 + int mvks = 0, mvrs = 0; // +484 +488 + std::string vmns; // +492 + int vmks = 0, vmrs = 0; // +520 +524 + Weapon weapons[19]; // +528 + Army armies[10]; // +1820 + int osaa = 0; // +2220 + Kit kits[7]; // +2224 + int vrk = 0; // +2672 + Vehicle vehicles[13]; // +2676 + int fkit = 0; std::string fkitTime; // +3560 +3564 + int fveh = 0; std::string fvehTime; // +3592 +3596 + int fwea = 0; std::string fweaTime; // +3624 +3628 + int fmap = 0; std::string fmapTime; // +3656 +3660 + std::vector maps; // +3688 + int fetchedAt; // +3704 + int de6 = 0, de7 = 0, de8 = 0; // +3708..+3716 + + PlayerStatsRecord() : fetchedAt((int) _time64(0)) {} }; -// The native host's typed SwiffPlayerStatsRecord (Menu/ISwiffHost.h) laid out into the VC7.1 byte -// image the rows below read: the shipped offsets, each string assigned into the image's -// pre-constructed vc71::string. The map rows go into the image's vector at +3688 (40-byte -// {id, wins, losses, time} elements on the engine heap, which the image's destructor frees) since -// getListEntries("playerStats 16") walks them. +// The native host's typed SwiffPlayerStatsRecord (Menu/ISwiffHost.h) copied into the record the +// rows below read, each string assigned from its c_str(). The map rows go into the record's +// vector since getListEntries("playerStats 16") walks them. static void statsRecordToImage(const dice::hfe::SwiffPlayerStatsRecord& r, PlayerStatsRecord& img) { - unsigned char* b = img.bytes; - struct W - { - static void i(unsigned char* b, int off, int v) { *reinterpret_cast(b + off) = v; } - static void s(unsigned char* b, int off, const std::string& v) { *reinterpret_cast(b + off) = v.c_str(); } - }; - W::i(b, 0, r.playerId); W::s(b, 4, r.nick); W::i(b, 32, r.scor); W::i(b, 36, r.wins); W::i(b, 40, r.loss); - W::s(b, 44, r.jond); W::s(b, 72, r.lbtl); - W::i(b, 100, r.twsc); W::i(b, 104, r.cpcp); W::i(b, 108, r.cacp); W::i(b, 112, r.dfcp); W::i(b, 116, r.kila); - W::i(b, 120, r.heal); W::i(b, 124, r.rviv); W::i(b, 128, r.rsup); W::i(b, 132, r.rpar); W::i(b, 136, r.tgte); - W::i(b, 140, r.dkas_dsab); W::i(b, 156, r.cdsc); W::i(b, 160, r.rank); W::i(b, 168, r.cmsc); W::i(b, 172, r.kick); - W::i(b, 176, r.ban); W::i(b, 180, r.kill); W::i(b, 184, r.deth); W::i(b, 188, r.suic); - W::s(b, 192, r.ospm); W::s(b, 220, r.klpm); W::s(b, 248, r.dtpm); W::s(b, 276, r.klpr); W::s(b, 304, r.dtpr); - W::i(b, 332, r.bksk); W::i(b, 336, r.wdsk); W::i(b, 340, r.bbrs); - W::s(b, 344, r.tcdr); W::s(b, 372, r.tsql); W::s(b, 400, r.tsqm); W::s(b, 428, r.tlwf); - W::s(b, 456, r.mvns); W::i(b, 484, r.mvks); W::i(b, 488, r.mvrs); - W::s(b, 492, r.vmns); W::i(b, 520, r.vmks); W::i(b, 524, r.vmrs); + img.playerId = r.playerId; img.nick = r.nick.c_str(); img.scor = r.scor; img.wins = r.wins; img.loss = r.loss; + img.jond = r.jond.c_str(); img.lbtl = r.lbtl.c_str(); + img.twsc = r.twsc; img.cpcp = r.cpcp; img.cacp = r.cacp; img.dfcp = r.dfcp; img.kila = r.kila; + img.heal = r.heal; img.rviv = r.rviv; img.rsup = r.rsup; img.rpar = r.rpar; img.tgte = r.tgte; + img.dkas_dsab = r.dkas_dsab; img.cdsc = r.cdsc; img.rank = r.rank; img.cmsc = r.cmsc; img.kick = r.kick; + img.ban = r.ban; img.kill = r.kill; img.deth = r.deth; img.suic = r.suic; + img.ospm = r.ospm.c_str(); img.klpm = r.klpm.c_str(); img.dtpm = r.dtpm.c_str(); img.klpr = r.klpr.c_str(); img.dtpr = r.dtpr.c_str(); + img.bksk = r.bksk; img.wdsk = r.wdsk; img.bbrs = r.bbrs; + img.tcdr = r.tcdr.c_str(); img.tsql = r.tsql.c_str(); img.tsqm = r.tsqm.c_str(); img.tlwf = r.tlwf.c_str(); + img.mvns = r.mvns.c_str(); img.mvks = r.mvks; img.mvrs = r.mvrs; + img.vmns = r.vmns.c_str(); img.vmks = r.vmks; img.vmrs = r.vmrs; for (int k = 0; k < 19; k++) { - const int o = 528 + 68 * k; - W::s(b, o, r.weapons[k].time); W::i(b, o + 28, r.weapons[k].kills); W::i(b, o + 32, r.weapons[k].deaths); - W::i(b, o + 36, r.weapons[k].accuracy); W::s(b, o + 40, r.weapons[k].kd); + PlayerStatsRecord::Weapon& o = img.weapons[k]; + o.time = r.weapons[k].time.c_str(); o.kills = r.weapons[k].kills; o.deaths = r.weapons[k].deaths; + o.accuracy = r.weapons[k].accuracy; o.kd = r.weapons[k].kd.c_str(); } for (int k = 0; k < 10; k++) { - const int o = 1820 + 40 * k; - W::s(b, o, r.armies[k].time); W::i(b, o + 28, r.armies[k].wins); W::i(b, o + 32, r.armies[k].losses); - W::i(b, o + 36, r.armies[k].bestRound); + PlayerStatsRecord::Army& o = img.armies[k]; + o.time = r.armies[k].time.c_str(); o.wins = r.armies[k].wins; o.losses = r.armies[k].losses; + o.bestRound = r.armies[k].bestRound; } - W::i(b, 2220, r.osaa); + img.osaa = r.osaa; for (int k = 0; k < 7; k++) { - const int o = 2224 + 64 * k; - W::s(b, o, r.kits[k].time); W::i(b, o + 28, r.kits[k].kills); W::i(b, o + 32, r.kits[k].deaths); - W::s(b, o + 36, r.kits[k].kd); + PlayerStatsRecord::Kit& o = img.kits[k]; + o.time = r.kits[k].time.c_str(); o.kills = r.kits[k].kills; o.deaths = r.kits[k].deaths; + o.kd = r.kits[k].kd.c_str(); } - W::i(b, 2672, r.vrk); + img.vrk = r.vrk; for (int k = 0; k < 13; k++) { - const int o = 2676 + 68 * k; - W::s(b, o, r.vehicles[k].time); W::i(b, o + 28, r.vehicles[k].kills); W::i(b, o + 32, r.vehicles[k].deaths); - W::s(b, o + 36, r.vehicles[k].kd); W::i(b, o + 64, r.vehicles[k].roadKills); + PlayerStatsRecord::Vehicle& o = img.vehicles[k]; + o.time = r.vehicles[k].time.c_str(); o.kills = r.vehicles[k].kills; o.deaths = r.vehicles[k].deaths; + o.kd = r.vehicles[k].kd.c_str(); o.roadKills = r.vehicles[k].roadKills; } - W::i(b, 3560, r.fkit); W::s(b, 3564, r.fkitTime); W::i(b, 3592, r.fveh); W::s(b, 3596, r.fvehTime); - W::i(b, 3624, r.fwea); W::s(b, 3628, r.fweaTime); W::i(b, 3656, r.fmap); W::s(b, 3660, r.fmapTime); - W::i(b, 3704, (int) r.fetchedAt); W::i(b, 3708, r.de6); W::i(b, 3712, r.de7); W::i(b, 3716, r.de8); + img.fkit = r.fkit; img.fkitTime = r.fkitTime.c_str(); img.fveh = r.fveh; img.fvehTime = r.fvehTime.c_str(); + img.fwea = r.fwea; img.fweaTime = r.fweaTime.c_str(); img.fmap = r.fmap; img.fmapTime = r.fmapTime.c_str(); + img.fetchedAt = (int) r.fetchedAt; img.de6 = r.de6; img.de7 = r.de7; img.de8 = r.de8; const unsigned int maps = static_cast(r.maps.size()); if (maps) { - char* first = static_cast(::renddx9abi::engineAlloc(40 * maps)); - if (first) + img.maps.resize(maps); + for (unsigned int k = 0; k < maps; ++k) { - for (unsigned int k = 0; k < maps; ++k) - { - char* e = first + 40 * k; - *reinterpret_cast(e) = r.maps[k].id; - *reinterpret_cast(e + 4) = r.maps[k].wins; - *reinterpret_cast(e + 8) = r.maps[k].losses; - new (e + 12) vc71::string(r.maps[k].time.c_str()); - } - *reinterpret_cast(b + 3692) = first; // {alloc, first, last, end} - *reinterpret_cast(b + 3696) = first + 40 * maps; - *reinterpret_cast(b + 3700) = first + 40 * maps; + PlayerStatsRecord::MapRow& e = img.maps[k]; + e.id = r.maps[k].id; + e.wins = r.maps[k].wins; + e.losses = r.maps[k].losses; + e.time = r.maps[k].time.c_str(); } } } @@ -4008,26 +4487,16 @@ void as_profile_getCurrentRankId(const gameswf::fn_call& fn) const int id = hostSelectedPlayerId(h); PlayerStatsRecord* rec = new PlayerStatsRecord(); (void) hostFillStatsRecord(h, id, *rec); - v = (double) *reinterpret_cast(rec->bytes + 160); + v = (double) rec->rank; delete rec; } fn.result->set_double(v); } -// Retained original message layout: {type, code, text}, with a VC7.1 string. +// Retained original message record: {type, code, text}. // Shipped getLastType/getLastText/getLastCode constructed it before the host filled it. // Active native callbacks exchange the typed SwiffHostMessage instead. -struct HostMessage { int type; int code; vc71::string text; }; - -// The VC7.1 layout of dice::hfe::ProfileInformation (Game/ProfileManager.h): the profile id, six -// 28-byte strings and four ints, 188 bytes - what BF2.exe 4A4AD0 reads and the shipped row builds -// on its stack (sub_1005CEC0 constructs it: id 0, six empty strings; sub_1005D0D0 destroys it). -struct Vc71ProfileInformation -{ - int profileId; - vc71::string nick, uniqueNick, email, firstName, lastName, country; - int sex, birthYear, birthMonth, birthDay; -}; +struct HostMessage { int type; int code; std::string text; }; // Creates an online account and local profile from the movie's twelve account arguments. // Requires initialized host/profile managers. A missing disc, password mismatch or failed @@ -4062,13 +4531,29 @@ void as_profile_createOnlineAccount(const gameswf::fn_call& fn) const bool remember = fn.arg(4).to_bool(); const std::string firstName = fn.arg(5).to_string(); const std::string lastName = fn.arg(6).to_string(); +#if defined(__APPLE__) + const int birthYear = bf2x87::toIntTruncate(fn.arg(7).to_number()); +#else const int birthYear = (int) fn.arg(7).to_number(); +#endif +#if defined(__APPLE__) + const int birthMonth = bf2x87::toIntTruncate(fn.arg(8).to_number()); +#else const int birthMonth = (int) fn.arg(8).to_number(); +#endif +#if defined(__APPLE__) + const int birthDay = bf2x87::toIntTruncate(fn.arg(9).to_number()); +#else const int birthDay = (int) fn.arg(9).to_number(); +#endif std::string country = fn.arg(10).to_string(); if (country == "none") country = "US"; +#if defined(__APPLE__) + const int sex = bf2x87::toIntTruncate(fn.arg(11).to_number()); +#else const int sex = (int) fn.arg(11).to_number(); +#endif if (password != confirm) { (void) h->postMessage(SwiffHostMessage(1, std::string("password does not match"), 0)); @@ -4177,8 +4662,16 @@ void as_messagehandler_raiseMessage(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_messagehandler_raiseMessage"); const std::string text(fn.arg(0).to_string()); +#if defined(__APPLE__) + const int type = bf2x87::toIntTruncate(fn.arg(1).to_number()); +#else const int type = static_cast(fn.arg(1).to_number()); +#endif +#if defined(__APPLE__) + const int code = bf2x87::toIntTruncate(fn.arg(2).to_number()); +#else const int code = static_cast(fn.arg(2).to_number()); +#endif SwiffHostMessage message; message.type = type; @@ -4191,7 +4684,7 @@ void as_messagehandler_raiseMessage(const gameswf::fn_call& fn) // dice.MessageHandler.getPunkBusterMessage(), and // promoted. The global player's host (unguarded), then its +0x354, and the text of the string it // answers published as a string - the VC7.1 small-buffer read `cmp [eax+18h],10h` is exactly -// vc71::string::c_str(). No argument, no check. +0x354 is the slot this tree calls getServerMod +// std::string::c_str(). No argument, no check. +0x354 is the slot this tree calls getServerMod // (BF2.exe 0x489060, `lea eax,[ecx+0F30h]`: the host's +0xF30 string, the one +0x350 assigns); // the shipped reads that same field as the PunkBuster message. [INFERRED] which name is the source's. void as_messagehandler_getPunkBusterMessage(const gameswf::fn_call& fn) @@ -4271,7 +4764,11 @@ void as_profile_setStatPlayer(const gameswf::fn_call& fn) if (pm && pmIsLoggedIn(pm)) { if (fn.nargs < 1) return; +#if defined(__APPLE__) + const int id = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int id = (int) fn.arg(0).to_number(); +#endif static_cast(h)->setSelectedPlayerId(id); // +0x220 return; } @@ -4343,7 +4840,11 @@ void as_profile_isMyProfile(const gameswf::fn_call& fn) bool result = false; if (pm && pmIsLoggedIn(pm)) { +#if defined(__APPLE__) + const int id = fn.nargs >= 1 ? bf2x87::toIntTruncate(fn.arg(0).to_number()) : 0; +#else const int id = fn.nargs >= 1 ? (int) fn.arg(0).to_number() : 0; +#endif for (unsigned i = 0; ; ++i) { OnlineProfile* obj = static_cast(pm)->getCurrentProfile(); // +0x2C, re-fetched per step as shipped @@ -4360,7 +4861,7 @@ void as_profile_isMyProfile(const gameswf::fn_call& fn) // Looks up equipment case-insensitively across teams/kits and copies its localization keys. // Copy native host records into the retained internal key storage. -struct EquipmentKeys { vc71::string name, displayKey, descriptionKey; }; +struct EquipmentKeys { std::string name, displayKey, descriptionKey; }; static bool findEquipmentByName(const char* name, EquipmentKeys& out) { if (!classManager) return false; @@ -4393,11 +4894,11 @@ static bool findEquipmentByName(const char* name, EquipmentKeys& out) // sub_1005CF10 - the shared tail: Locale.getString through SwiffHost +168 (wide out-param, narrow // key) into a dice String object (narrow part empty, as shipped - ledger #38). -static void setLocalisedStringObject(const gameswf::fn_call& fn, const vc71::string& key) +static void setLocalisedStringObject(const gameswf::fn_call& fn, const std::string& key) { - vc71::wstring out; + std::wstring out; hostLocaliseKey(asHost(), key, out); - fn.result->set_as_object_interface(gameswf::create_dice_string_object(reinterpret_cast(out.c_str()), (int) out.size())); + fn.result->set_as_object_interface(gameswf::create_dice_string_object(BF2_DICE_UTF16(out.c_str()), (int) out.size())); } // sub_1005F700 - dice.bf2.Profile.getEquipmentName(name): the equipment record's localised display @@ -4406,7 +4907,7 @@ static void setLocalisedStringObject(const gameswf::fn_call& fn, const vc71::str void as_profile_getEquipmentName(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_profile_getEquipmentName"); - vc71::string name(fn.nargs >= 1 ? fn.arg(0).to_string() : ""); + std::string name(fn.nargs >= 1 ? fn.arg(0).to_string() : ""); EquipmentKeys rec; if (!findEquipmentByName(name.c_str(), rec)) { fn.result->set_as_object_interface(gameswf::create_dice_string_object(0, 0)); return; } setLocalisedStringObject(fn, rec.displayKey.size() ? rec.displayKey : rec.name); @@ -4417,7 +4918,7 @@ void as_profile_getEquipmentName(const gameswf::fn_call& fn) void as_profile_getEquipmentDescription(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_profile_getEquipmentDescription"); - vc71::string name(fn.nargs >= 1 ? fn.arg(0).to_string() : ""); + std::string name(fn.nargs >= 1 ? fn.arg(0).to_string() : ""); EquipmentKeys rec; if (!findEquipmentByName(name.c_str(), rec)) { fn.result->set_as_object_interface(gameswf::create_dice_string_object(0, 0)); return; } setLocalisedStringObject(fn, rec.descriptionKey); @@ -4432,13 +4933,13 @@ void as_multiplay_getBrowser(const gameswf::fn_call& fn) fn.result->set_tu_string(tu_string(kind.c_str())); } -// Keep the original unlock record fields alongside the native host's typed items. +// The original unlock record fields with the native host's typed items as its vector. // The original 32-byte record held {time(now), int, count, int, a VC7.1 vector}; shipped callers // zeroed it, stamped time(), and freed its vector buffer afterwards (sub_1006DBA0 = bf_free). struct UnlockRecord { - int now; int a; int count; int b; Vc71Vector unlocks; - std::vector items; // the typed host's {id, status} list; the legacy field stays empty + int now; int a; int count; int b; + std::vector items; // +16: the typed host's {id, status} list }; // Read the typed host's unlock entries. @@ -4452,8 +4953,7 @@ static int unlockIdAt(const UnlockRecord& rec, int i) } static void releaseUnlockRecord(UnlockRecord& rec) { - if (rec.unlocks.first) ::renddx9abi::engineFree(rec.unlocks.first); - rec.unlocks.first = rec.unlocks.last = rec.unlocks.end = 0; + rec.items.clear(); } // ISwiffHost +0x1C4 (getUnlocks): the ProfileManager's profile id keys the query; @@ -4463,7 +4963,6 @@ static void fillUnlockRecord(void* h, UnlockRecord& rec) { const int id = hostPlayerId(); rec.now = (int) ::time(0); rec.a = 0; rec.count = 0; rec.b = 0; - rec.unlocks.alloc = 0; rec.unlocks.first = rec.unlocks.last = rec.unlocks.end = 0; if (!h) return; IPlayerUnlocks::UnlockCache cache; cache.field0 = rec.now; cache.field4 = 0; cache.available = 0; cache.selected = 0; @@ -4523,7 +5022,7 @@ static bool fetchPlayerStats(void* h, PlayerStatsRecord& rec) } // sub_100598E0 / sub_1005CF10 - Locale.getString through SwiffHost +168 into a wide string. -static void hostLocaliseKey(void* h, const vc71::string& key, vc71::wstring& out) +static void hostLocaliseKey(void* h, const std::string& key, std::wstring& out) { if (!h) return; std::wstring text; @@ -4535,7 +5034,7 @@ static void hostLocaliseKey(void* h, const vc71::string& key, vc71::wstring& out // (getMapFromGameSpyId): {std::string key at +0, std::string name at +28, ...} - getFavouriteId // reads the key, getFavouriteName localises the name. Native reads the typed IModInfo::Map // (path, name - the same two leading strings). -static bool hostMapStrings(void* h, int mapId, vc71::string& key, vc71::string& name) +static bool hostMapStrings(void* h, int mapId, std::string& key, std::string& name) { if (!h) return false; IBase* mm = static_cast(h)->getModInfo(); @@ -4558,29 +5057,32 @@ void as_playerstats_getFavouriteName(const gameswf::fn_call& fn) void* h = asHost(); PlayerStatsRecord* rec = new PlayerStatsRecord(); if (!fetchPlayerStats(h, *rec)) { fn.result->set_double(0.0); delete rec; return; } +#if defined(__APPLE__) + const int kind = fn.nargs >= 1 ? bf2x87::toIntTruncate(fn.arg(0).to_number()) : -1; +#else const int kind = fn.nargs >= 1 ? (int) fn.arg(0).to_number() : -1; - vc71::wstring text(L" "); +#endif + std::wstring text(L" "); bool haveText = true; - const unsigned char* b = rec->bytes; switch (kind) { - case 0: { const int i = *reinterpret_cast(b + 3560); if (i != -1 && i >= 0 && i < 7) hostLocaliseKey(h, vc71::string(kFavouriteKitKeys[i]), text); break; } - case 1: { const int i = *reinterpret_cast(b + 3592); if (i != -1 && i >= 0 && i < 7) hostLocaliseKey(h, vc71::string(kFavouriteVehicleKeys[i]), text); break; } - case 2: { const int i = *reinterpret_cast(b + 3624); if (i != -1 && i >= 0 && i < 13) hostLocaliseKey(h, vc71::string(kFavouriteWeaponKeys[i]), text); break; } + case 0: { const int i = rec->fkit; if (i != -1 && i >= 0 && i < 7) hostLocaliseKey(h, std::string(kFavouriteKitKeys[i]), text); break; } + case 1: { const int i = rec->fveh; if (i != -1 && i >= 0 && i < 7) hostLocaliseKey(h, std::string(kFavouriteVehicleKeys[i]), text); break; } + case 2: { const int i = rec->fwea; if (i != -1 && i >= 0 && i < 13) hostLocaliseKey(h, std::string(kFavouriteWeaponKeys[i]), text); break; } case 3: { - const int i = *reinterpret_cast(b + 3656); + const int i = rec->fmap; if (i != -1) { - vc71::string key, mapName; + std::string key, mapName; if (hostMapStrings(h, i, key, mapName)) hostLocaliseKey(h, mapName, text); - else hostLocaliseKey(h, vc71::string("Unknown Map"), text); + else hostLocaliseKey(h, std::string("Unknown Map"), text); } break; } default: haveText = false; break; } delete rec; fn.result->set_as_object_interface(gameswf::create_dice_string_object( - haveText ? reinterpret_cast(text.c_str()) : 0, haveText ? (int) text.size() : 0)); + haveText ? BF2_DICE_UTF16(text.c_str()) : 0, haveText ? (int) text.size() : 0)); } // sub_1005B680 - dice.bf2.PlayerStats.getFavouriteId(kind): the favourite index printed with "%d" @@ -4592,16 +5094,19 @@ void as_playerstats_getFavouriteId(const gameswf::fn_call& fn) void* h = asHost(); PlayerStatsRecord* rec = new PlayerStatsRecord(); if (!fetchPlayerStats(h, *rec)) { fn.result->set_double(0.0); delete rec; return; } +#if defined(__APPLE__) + const int kind = fn.nargs >= 1 ? bf2x87::toIntTruncate(fn.arg(0).to_number()) : -1; +#else const int kind = fn.nargs >= 1 ? (int) fn.arg(0).to_number() : -1; - const unsigned char* b = rec->bytes; +#endif char num[32]; num[0] = 0; - vc71::string out(""); + std::string out(""); switch (kind) { - case 0: ::sprintf_s(num, "%d", *reinterpret_cast(b + 3560)); out = num; break; - case 1: ::sprintf_s(num, "%d", *reinterpret_cast(b + 3592)); out = num; break; - case 2: ::sprintf_s(num, "%d", *reinterpret_cast(b + 3624)); out = num; break; - case 3: { vc71::string key, mapName; if (hostMapStrings(h, *reinterpret_cast(b + 3656), key, mapName)) out = key; break; } + case 0: ::sprintf_s(num, "%d", rec->fkit); out = num; break; + case 1: ::sprintf_s(num, "%d", rec->fveh); out = num; break; + case 2: ::sprintf_s(num, "%d", rec->fwea); out = num; break; + case 3: { std::string key, mapName; if (hostMapStrings(h, rec->fmap, key, mapName)) out = key; break; } default: break; } delete rec; @@ -4616,17 +5121,22 @@ void as_playerstats_getFavouriteTime(const gameswf::fn_call& fn) void* h = asHost(); PlayerStatsRecord* rec = new PlayerStatsRecord(); if (!fetchPlayerStats(h, *rec)) { fn.result->set_double(0.0); delete rec; return; } +#if defined(__APPLE__) + const int kind = fn.nargs >= 1 ? bf2x87::toIntTruncate(fn.arg(0).to_number()) : -1; +#else const int kind = fn.nargs >= 1 ? (int) fn.arg(0).to_number() : -1; - static const int kTimeOffset[4] = { 3564, 3596, 3628, 3660 }; - vc71::string out(""); - if (kind >= 0 && kind < 4) out = *reinterpret_cast(rec->bytes + kTimeOffset[kind]); +#endif + static std::string PlayerStatsRecord::* const kTime[4] = { + &PlayerStatsRecord::fkitTime, &PlayerStatsRecord::fvehTime, &PlayerStatsRecord::fweaTime, &PlayerStatsRecord::fmapTime }; + std::string out(""); + if (kind >= 0 && kind < 4) out = rec->*kTime[kind]; delete rec; fn.result->set_tu_string(tu_string(out.c_str())); } // The shipped DLL's selected-unlock name (unk_100F8838, a std::string): written by selectFirstUnlock // and selectUnlock, read by getCurrentUnlockDescription and unlock. -static vc71::string s_selectedUnlock(""); +static std::string s_selectedUnlock(""); // bfhq statistics and equipment-list bindings for the selected statistics player. @@ -4637,8 +5147,8 @@ static vc71::string s_selectedUnlock(""); static int s_equipmentIndex = 0; // unk_100F88A8 / unk_100F888C - the equipment names Profile.setSelectedEquipment and // Profile.setSelectedUnlockEquipment store; "wpstats" / "wpunlockstats" read them. -static vc71::string s_selectedEquipment(""); -static vc71::string s_selectedUnlockEquipment(""); +static std::string s_selectedEquipment(""); +static std::string s_selectedUnlockEquipment(""); // sub_10017DC0 - dice.General.setEquipmentIndex(n): arg0 (the trapping accessor) to a number, // stored by `fistp` under a control word forced to chop (fnstcw / or ah,0Ch / fldcw at @@ -4646,7 +5156,11 @@ static vc71::string s_selectedUnlockEquipment(""); void as_general_setEquipmentIndex(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_general_setEquipmentIndex"); +#if defined(__APPLE__) + s_equipmentIndex = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else s_equipmentIndex = (int) fn.arg(0).to_number(); +#endif } // sub_1005D1C0 / sub_1005D1F0 - dice.bf2.Profile.setSelectedEquipment(name) and @@ -4672,9 +5186,6 @@ struct StatsTable { ListResult& r; ListHost h; - const unsigned char* b; - int i(int off) const { return *reinterpret_cast(b + off); } - const char* s(int off) const { return reinterpret_cast(b + off)->c_str(); } void label(int id, const char* key) { r.beginRow(id); @@ -4682,17 +5193,17 @@ struct StatsTable hostLocalise(h, key, w); r.pushWide(w.c_str(), (int) w.size()); } - void intRow(const char* key, int off) { label(0, key); r.pushInt(i(off)); } - void strRow(const char* key, int off) { label(0, key); r.pushNarrow(s(off)); } + void intRow(const char* key, int value) { label(0, key); r.pushInt(value); } + void strRow(const char* key, const std::string& value) { label(0, key); r.pushNarrow(value.c_str()); } // cases 12..15: the favourite index is the row id, "_%d" of it, then its time string. - void favouriteRow(const char* format, int indexOff, int timeOff) + void favouriteRow(const char* format, int index, const std::string& time) { - r.beginRow(i(indexOff)); + r.beginRow(index); char text[64]; - ::_snprintf(text, sizeof(text) - 1, format, i(indexOff)); + ::_snprintf(text, sizeof(text) - 1, format, index); text[sizeof(text) - 1] = 0; r.pushNarrow(text); - r.pushNarrow(s(timeOff)); + r.pushNarrow(time.c_str()); } }; @@ -4704,7 +5215,7 @@ const char* const kArmyFlags[10] = { // sub_10003580 - the shipped in-place lowercase "unlockeq" keys its name map with: the five Latin-1 // capitals Ã… Ä Ö Ü É become Ã¥ ä ö ü é explicitly, every other byte goes through tolower() - which // under the "C" locale changes A-Z only. [INFERRED] the locale: BF2.exe sets none this DLL sees. -void shippedLowercase(const char* src, vc71::string& out) +void shippedLowercase(const char* src, std::string& out) { const unsigned int n = (unsigned int) ::strlen(src); char local[128]; @@ -4742,108 +5253,108 @@ static void listPlayerStats(const gameswf::fn_call& fn, ListResult& r, ListHost const int playerId = hostSelectedPlayerId(h); PlayerStatsRecord* rec = new PlayerStatsRecord(); (void) hostFillStatsRecord(h, playerId, *rec); - StatsTable t = { r, h, rec->bytes }; + StatsTable t = { r, h }; int total = 0; switch (which) { case 0: // the overview - t.intRow("BFHQ_overallscore", 32); - t.intRow("BFHQ_teamworkscore", 100); - t.intRow("BFHQ_combatscore", 168); - t.intRow("BFHQ_commanderscore", 156); - t.strRow("BFHQ_enlisted", 44); - t.strRow("BFHQ_lastbattle", 72); + t.intRow("BFHQ_overallscore", rec->scor); // +32 + t.intRow("BFHQ_teamworkscore", rec->twsc); // +100 + t.intRow("BFHQ_combatscore", rec->cmsc); // +168 + t.intRow("BFHQ_commanderscore", rec->cdsc); // +156 + t.strRow("BFHQ_enlisted", rec->jond); // +44 + t.strRow("BFHQ_lastbattle", rec->lbtl); // +72 total = 6; break; case 1: // teamwork - t.intRow("BFHQ_teamworkscore", 100); - t.intRow("BFHQ_capturecp", 104); - t.intRow("BFHQ_capturecpassist", 108); - t.intRow("BFHQ_defendcp", 112); - t.intRow("BFHQ_killassist", 116); - t.intRow("BFHQ_heal", 120); - t.intRow("BFHQ_revive", 124); - t.intRow("BFHQ_support", 128); - t.intRow("BFHQ_repair", 132); - t.intRow("BFHQ_driverscore", 140); + t.intRow("BFHQ_teamworkscore", rec->twsc); // +100 + t.intRow("BFHQ_capturecp", rec->cpcp); // +104 + t.intRow("BFHQ_capturecpassist", rec->cacp); // +108 + t.intRow("BFHQ_defendcp", rec->dfcp); // +112 + t.intRow("BFHQ_killassist", rec->kila); // +116 + t.intRow("BFHQ_heal", rec->heal); // +120 + t.intRow("BFHQ_revive", rec->rviv); // +124 + t.intRow("BFHQ_support", rec->rsup); // +128 + t.intRow("BFHQ_repair", rec->rpar); // +132 + t.intRow("BFHQ_driverscore", rec->dkas_dsab); // +140 total = 10; break; case 2: // combat - t.intRow("BFHQ_combatscore", 168); - t.intRow("BFHQ_kills", 180); - t.intRow("BFHQ_deaths", 184); - t.strRow("BFHQ_scoreperminute", 192); - t.strRow("BFHQ_killsperminute", 220); - t.strRow("BFHQ_deathsperminute", 248); - t.strRow("BFHQ_killsperround", 276); - t.strRow("BFHQ_deathsperround", 304); - t.intRow("BFHQ_killstreak", 332); - t.intRow("BFHQ_deathstreak", 336); + t.intRow("BFHQ_combatscore", rec->cmsc); // +168 + t.intRow("BFHQ_kills", rec->kill); // +180 + t.intRow("BFHQ_deaths", rec->deth); // +184 + t.strRow("BFHQ_scoreperminute", rec->ospm); // +192 + t.strRow("BFHQ_killsperminute", rec->klpm); // +220 + t.strRow("BFHQ_deathsperminute", rec->dtpm); // +248 + t.strRow("BFHQ_killsperround", rec->klpr); // +276 + t.strRow("BFHQ_deathsperround", rec->dtpr); // +304 + t.intRow("BFHQ_killstreak", rec->bksk); // +332 + t.intRow("BFHQ_deathstreak", rec->wdsk); // +336 total = 10; break; case 3: // the personal panel - t.intRow("BFHQ_STATS_PERSONAL_globalscore", 32); - t.intRow("BFHQ_STATS_PERSONAL_wins", 36); - t.intRow("BFHQ_STATS_PERSONAL_loss", 40); - t.strRow("BFHQ_PROFILES_PLAYERINFO_enlisted", 44); - t.strRow("BFHQ_PROFILES_PLAYERINFO_lastbattle", 72); + t.intRow("BFHQ_STATS_PERSONAL_globalscore", rec->scor); // +32 + t.intRow("BFHQ_STATS_PERSONAL_wins", rec->wins); // +36 + t.intRow("BFHQ_STATS_PERSONAL_loss", rec->loss); // +40 + t.strRow("BFHQ_PROFILES_PLAYERINFO_enlisted", rec->jond); // +44 + t.strRow("BFHQ_PROFILES_PLAYERINFO_lastbattle", rec->lbtl); // +72 total = 5; break; case 4: // global scores - t.intRow("BFHQ_globalscore", 32); - t.intRow("BFHQ_wins", 36); - t.intRow("BFHQ_losses", 40); - t.intRow("BFHQ_teamworkscore", 100); - t.intRow("BFHQ_combatscore", 168); - t.intRow("BFHQ_commanderscore", 156); + t.intRow("BFHQ_globalscore", rec->scor); // +32 + t.intRow("BFHQ_wins", rec->wins); // +36 + t.intRow("BFHQ_losses", rec->loss); // +40 + t.intRow("BFHQ_teamworkscore", rec->twsc); // +100 + t.intRow("BFHQ_combatscore", rec->cmsc); // +168 + t.intRow("BFHQ_commanderscore", rec->cdsc); // +156 total = 6; break; - case 7: // weapons, 68-byte entries at +528 + case 7: // weapons, 68-byte retail entries at +528 for (int k = 0; k < 13; ++k) { - const int w = 528 + 68 * k; + const PlayerStatsRecord::Weapon& w = rec->weapons[k]; t.label(k, kFavouriteWeaponKeys[k]); - r.pushInt(t.i(w + 28)); // kills - r.pushInt(t.i(w + 32)); // deaths + r.pushInt(w.kills); // kills + r.pushInt(w.deaths); // deaths char accuracy[24]; // sub_10003320("%d") + "%" (sub_10001AA0) - ::_snprintf(accuracy, sizeof(accuracy) - 1, "%d%%", t.i(w + 36)); + ::_snprintf(accuracy, sizeof(accuracy) - 1, "%d%%", w.accuracy); accuracy[sizeof(accuracy) - 1] = 0; r.pushNarrow(accuracy); - r.pushNarrow(t.s(w + 40)); // kill/death ratio - r.pushNarrow(t.s(w)); // time + r.pushNarrow(w.kd.c_str()); // kill/death ratio + r.pushNarrow(w.time.c_str()); // time } total = 9; break; - case 8: // vehicles, 68-byte entries at +2676 + case 8: // vehicles, 68-byte retail entries at +2676 for (int k = 0; k < 7; ++k) { if (k == 5) // `cmp esi, 8Ch` - the sixth is skipped, its id kept continue; - const int v = 2676 + 68 * k; + const PlayerStatsRecord::Vehicle& v = rec->vehicles[k]; t.label(k, kFavouriteVehicleKeys[k]); - r.pushInt(t.i(v + 28)); // kills - r.pushInt(t.i(v + 64)); // road kills - r.pushInt(t.i(v + 32)); // deaths - r.pushNarrow(t.s(v + 36)); // kill/death ratio - r.pushNarrow(t.s(v)); // time + r.pushInt(v.kills); // kills + r.pushInt(v.roadKills); // road kills + r.pushInt(v.deaths); // deaths + r.pushNarrow(v.kd.c_str()); // kill/death ratio + r.pushNarrow(v.time.c_str()); // time } total = 6; break; - case 9: // kits, 64-byte entries at +2224 + case 9: // kits, 64-byte retail entries at +2224 for (int k = 0; k < 7; ++k) { - const int kit = 2224 + 64 * k; + const PlayerStatsRecord::Kit& kit = rec->kits[k]; t.label(k, kFavouriteKitKeys[k]); - r.pushInt(t.i(kit + 28)); // kills - r.pushInt(t.i(kit + 32)); // deaths - r.pushNarrow(t.s(kit + 36)); // kill/death ratio - r.pushNarrow(t.s(kit)); // time + r.pushInt(kit.kills); // kills + r.pushInt(kit.deaths); // deaths + r.pushNarrow(kit.kd.c_str()); // kill/death ratio + r.pushNarrow(kit.time.c_str()); // time } total = 7; break; case 10: // armies, per MenuTeamManager team { - // The count is asked once (var_5C); per team: getTeam, the army's 40-byte entry at + // The count is asked once (var_5C); per team: getTeam, the army's 40-byte retail entry at // 1820 + 40 * teamId (unchecked), the row keyed by the team id, localise("") (an empty key // never reaches the host), host +0x124 getModDirectorySetting asked and dropped, the flag // image, localise("") again, the team's name (+8) localised, then time / wins / losses. @@ -4854,7 +5365,7 @@ static void listPlayerStats(const gameswf::fn_call& fn, ListResult& r, ListHost { const MenuTeam* team = tm->getTeam(k); // +0x30 const int teamId = team->teamId; - const int army = 1820 + 40 * teamId; + const PlayerStatsRecord::Army& army = rec->armies[teamId]; r.beginRow(teamId); { HostWide w; hostLocalise(h, "", w); r.pushWide(w.c_str(), (int) w.size()); } (void) h->getModDirectorySetting(); // +0x124 @@ -4864,42 +5375,42 @@ static void listPlayerStats(const gameswf::fn_call& fn, ListResult& r, ListHost r.pushNarrow(flag); { HostWide w; hostLocalise(h, "", w); r.pushWide(w.c_str(), (int) w.size()); } { HostWide w; hostLocalise(h, team->name.c_str(), w); r.pushWide(w.c_str(), (int) w.size()); } - r.pushNarrow(t.s(army)); - r.pushInt(t.i(army + 28)); - r.pushInt(t.i(army + 32)); + r.pushNarrow(army.time.c_str()); + r.pushInt(army.wins); + r.pushInt(army.losses); } total = (int) teams; break; } case 11: // current and next rank { - vc71::string key; + std::string key; t.label(0, "PROFILE_currentrank"); - hostRankKey(h, t.i(160), key); // +0x1B4 with the record's rank + hostRankKey(h, rec->rank, key); // +0x1B4 with the record's rank (+160) r.pushNarrow(key.c_str()); t.label(0, "PROFILE_nextrank"); - hostRankKey(h, t.i(160) + 1, key); + hostRankKey(h, rec->rank + 1, key); r.pushNarrow(key.c_str()); total = 2; break; } - case 12: t.favouriteRow("kit_%d", 3560, 3564); total = 1; break; - case 13: t.favouriteRow("vehicle_%d", 3592, 3596); total = 1; break; - case 14: t.favouriteRow("weapon_%d", 3624, 3628); total = 1; break; - case 15: t.favouriteRow("map_%d", 3656, 3660); total = 1; break; + case 12: t.favouriteRow("kit_%d", rec->fkit, rec->fkitTime); total = 1; break; // +3560 / +3564 + case 13: t.favouriteRow("vehicle_%d", rec->fveh, rec->fvehTime); total = 1; break; // +3592 / +3596 + case 14: t.favouriteRow("weapon_%d", rec->fwea, rec->fweaTime); total = 1; break; // +3624 / +3628 + case 15: t.favouriteRow("map_%d", rec->fmap, rec->fmapTime); total = 1; break; // +3656 / +3660 case 16: // the record's map rows { - // Per 40-byte row {id, wins, losses, time} of the vector at +3688 (its size re-read every + // Per row {id, wins, losses, time} of the vector at +3688 (its size re-read every // pass): host +0x120 getModInfo asked again each time, +0x34 getMapFromGameSpyId(id); rows // whose map the mod does not know are skipped uncounted. A known map inside the window // gives id = the map's gsid (+0x9C), its name (+0x1C), wins, losses, time - and every known // map counts toward totalCount whether shown or not. - const Vc71Vector* rows = reinterpret_cast(rec->bytes + 3688); + const std::vector& rows = rec->maps; unsigned int known = 0; - for (unsigned int k = 0; rows->first && k < (unsigned int) ((rows->last - rows->first) / 40); ++k) + for (unsigned int k = 0; k < (unsigned int) rows.size(); ++k) { - const char* row = rows->first + 40 * k; - const int mapId = *reinterpret_cast(row); + const PlayerStatsRecord::MapRow& row = rows[k]; + const int mapId = row.id; IModInfo* mi = static_cast(h->getModInfo()); const IModInfo::Map* map = mi->getMapFromGameSpyId(mapId); if (!map) @@ -4908,9 +5419,9 @@ static void listPlayerStats(const gameswf::fn_call& fn, ListResult& r, ListHost { r.beginRow(map->gameSpyId); r.pushNarrow(map->name.c_str()); - r.pushInt(*reinterpret_cast(row + 4)); - r.pushInt(*reinterpret_cast(row + 8)); - r.pushNarrow(reinterpret_cast(row + 12)->c_str()); + r.pushInt(row.wins); + r.pushInt(row.losses); + r.pushNarrow(row.time.c_str()); } ++total; ++known; @@ -4918,13 +5429,13 @@ static void listPlayerStats(const gameswf::fn_call& fn, ListResult& r, ListHost break; } case 17: // the summary strip - t.intRow("BFHQ_globalscore", 32); - t.strRow("BFHQ_enlisted", 44); - t.strRow("BFHQ_lastbattle", 72); - t.strRow("BFHQ_timeascommander", 344); - t.strRow("BFHQ_timeassquadleader", 372); - t.strRow("BFHQ_timeassquadmember", 400); - t.strRow("BFHQ_timeaslonewolf", 428); + t.intRow("BFHQ_globalscore", rec->scor); // +32 + t.strRow("BFHQ_enlisted", rec->jond); // +44 + t.strRow("BFHQ_lastbattle", rec->lbtl); // +72 + t.strRow("BFHQ_timeascommander", rec->tcdr); // +344 + t.strRow("BFHQ_timeassquadleader", rec->tsql); // +372 + t.strRow("BFHQ_timeassquadmember", rec->tsqm); // +400 + t.strRow("BFHQ_timeaslonewolf", rec->tlwf); // +428 total = 7; break; default: // 5, 6 and out of range: empty @@ -5015,6 +5526,413 @@ void pushLocalised(ListResult& r, ListHost h, const char* key) r.pushWide(w.c_str(), (int) w.size()); } +// ---- the getListEntries branches recovered in frontier batch 12 (sub_10022610) ---- + +static bool inWindow(unsigned int i, int start, int end) +{ + return i >= static_cast(start) && i < static_cast(end); +} +static void publishList(const gameswf::fn_call& fn, ListResult& r, int total) +{ + r.setTotalCount(total); + fn.result->set_as_object_interface(r.arr.get_ptr()); +} + +// "missionList" (10023D53..10023EBF): host +0xEC getSinglePlayerLevels; a refusal answers the +// number 0. Rows: id "%d" of the level index, its name and mode; every level counts. +static void listMissions(const gameswf::fn_call& fn, ListResult& r, ListHost h, int start, int end) +{ + std::vector levels; + if (!h->getSinglePlayerLevels(levels)) + { + fn.result->set_int(0); + return; + } + r.begin(); + int total = 0; + for (unsigned int i = 0; i < levels.size(); ++i) + { + if (inWindow(i, start, end)) + { + r.beginRowFormatted("%d", levels[i].index); + r.pushNarrow(levels[i].name.c_str()); + r.pushNarrow(levels[i].mode.c_str()); + } + ++total; + } + publishList(fn, r, total); +} + +// "profileSearch" (100260D5..100261EC): host +0x3C getSearchForPlayer, +0x18 getPlayers. A row +// inside the window with an empty nick is neither listed nor counted; rows outside count. +static void listProfileSearch(const gameswf::fn_call& fn, ListResult& r, ListHost h, int start, int end) +{ + r.begin(); + std::vector players; + (void) static_cast(h->getSearchForPlayer())->getPlayers(players); + int total = 0; + for (unsigned int i = 0; i < players.size(); ++i) + { + if (inWindow(i, start, end)) + { + if (players[i].nick.length() == 0) + continue; + r.beginRow(players[i].profileId); + r.pushInt(static_cast(i) + 1); + r.pushNarrow(players[i].nick.c_str()); + } + ++total; + } + publishList(fn, r, total); +} + +// "mods" (1002693F..10026BA5): host +0x190 getModCount, +0x194 getModAt per row inside the window. +// Fields path/logo/url; columns: the path after its first '/' or '\\', the localised title, the +// version. Every index counts, including one getModAt refuses. +static void listMods(const gameswf::fn_call& fn, ListResult& r, ListHost h, int start, int end) +{ + r.begin(); + int count = 0; + h->getModCount(&count); + int total = 0; + for (unsigned int i = 0; i < static_cast(count); ++i) + { + if (inWindow(i, start, end)) + { + IModInfo::Mod mod; + if (h->getModAt(static_cast(i), &mod)) + { + r.beginRow(static_cast(i)); + r.setString("path", mod.path.c_str()); + r.setString("logo", mod.logo.c_str()); + r.setString("url", mod.url.c_str()); + std::string folder(""); + bool slash = false; + for (std::size_t c = 0; c < mod.path.length(); ++c) + { + if (slash) + folder += mod.path[c]; + else if (mod.path[c] == '/' || mod.path[c] == '\\') + slash = true; + } + r.pushNarrow(folder.c_str()); + pushLocalised(r, h, mod.title.c_str()); + r.pushNarrow(mod.version.c_str()); + } + } + ++total; + } + publishList(fn, r, total); +} + +// "teamSummary " (100275B1..10027752): host +0x1A4 getEndOfRoundSummary (refused: an empty +// list); one row keyed by the team's player count with its five column sums. The team is unchecked. +static void listTeamSummary(const gameswf::fn_call& fn, ListResult& r, ListHost h, const char* word1) +{ + const int team = ::atoi(word1); + r.begin(); + SwiffEndOfRoundSummary summary; + if (!h->getEndOfRoundSummary(summary)) + { + publishList(fn, r, 0); + return; + } + const std::vector& players = summary.teams[team].players; + r.beginRow(static_cast(players.size())); + int score = 0, teamScore = 0, kills = 0, deaths = 0, field48 = 0; + for (std::size_t i = 0; i < players.size(); ++i) + { + score += players[i].score; + teamScore += players[i].teamScore; + kills += players[i].kills; + deaths += players[i].deaths; + field48 += players[i].field48; + } + r.pushInt(score); + r.pushInt(teamScore); + r.pushInt(kills); + r.pushInt(deaths); + r.pushInt(field48); + publishList(fn, r, 1); +} + +// "dateOfBirth " (10028B52..10028E7A): 0 the 90 years before this one (GetSystemTime, UTC), +// 1 the months "01".."12", 2 the days 1..31; the first counted row is "selected". Other parts: empty. +static void listDateOfBirth(const gameswf::fn_call& fn, ListResult& r, const char* word1, int start, int end) +{ + r.begin(); + int total = 0; + switch (::atoi(word1)) + { + case 0: + { + const std::time_t now = std::time(0); + const int year = std::gmtime(&now)->tm_year + 1900; + for (unsigned int i = 0; i < 90; ++i) + { + if (inWindow(i, start, end)) + { + const int value = year + static_cast(i) - 90; + char text[16]; ::sprintf(text, "%d", value); + r.beginRow(value); + r.pushNarrow(text); + if (total == 0) + r.setInt("selected", 1); + } + ++total; + } + break; + } + case 1: + { + static const char* const months[12] = { "01", "02", "03", "04", "05", "06", + "07", "08", "09", "10", "11", "12" }; + for (unsigned int i = 0; i < 12; ++i) + { + if (inWindow(i, start, end)) + { + r.beginRow(static_cast(i) + 1); + r.pushNarrow(months[i]); + if (total == 0) + r.setInt("selected", 1); + } + ++total; + } + break; + } + case 2: + for (unsigned int i = 0; i < 31; ++i) + { + if (inWindow(i, start, end)) + { + char text[16]; ::sprintf(text, "%d", static_cast(i) + 1); + r.beginRow(static_cast(i)); + r.pushNarrow(text); + if (total == 0) + r.setInt("selected", 1); + } + ++total; + } + break; + default: + break; + } + publishList(fn, r, total); +} + +// "gender" (10028E93..10028F86): Male (0x500, selected) and Female (0x501). +static void listGender(const gameswf::fn_call& fn, ListResult& r) +{ + r.begin(); + r.beginRow(0x500); + r.pushNarrow("Male"); + r.setInt("selected", 1); + r.beginRow(0x501); + r.pushNarrow("Female"); + publishList(fn, r, 2); +} + +// "modfilter" (1002DD11..1002DEE3): "bf2" always; "xpack" too when the mod directory setting +// (+0x124) is "mods/xpack", case-insensitively. The window is not read. +static void listModFilter(const gameswf::fn_call& fn, ListResult& r, ListHost h) +{ + r.begin(); + r.beginRowStr("bf2"); + pushLocalised(r, h, "MODDESC_BF2_TITLE"); + int total = 1; + const std::string directory = h->getModDirectorySetting(); + if (::_stricmp(directory.c_str(), "mods/xpack") == 0) + { + r.beginRowStr("xpack"); + pushLocalised(r, h, "MODDESC_XP_TITLE"); + total = 2; + } + publishList(fn, r, total); +} + +// "suggestNicks" (1002DEFC..1002E00B): the "ProfileManager" (unguarded) +0x50 getNickSuggestions; +// each nick is both the row id and its column. +static void listSuggestedNicks(const gameswf::fn_call& fn, ListResult& r, int start, int end) +{ + r.begin(); + IProfileManager* pm = static_cast( + classManager->getSingleton(renddx9abi::HostString("ProfileManager"))); + std::vector nicks; + (void) pm->getNickSuggestions(nicks); + int total = 0; + for (std::size_t i = 0; i < nicks.size(); ++i) + { + if (inWindow(static_cast(total), start, end)) + { + r.beginRowStr(nicks[i].c_str()); + r.pushNarrow(nicks[i].c_str()); + } + ++total; + } + publishList(fn, r, total); +} + +// "uweapons" (10030026..1003048E): the profile's unlocks (ProfileManager +0x30, host +0x1C4) against +// the unlock definitions (host +0x48, +0x1C getItems). An unlock without a definition, or one whose +// status is not 0, is neither listed nor counted. Row id: the definition name; "wid" the unlock id, +// "kitId" its kit when exactly one definition carries it (else -1), "selected" for the selected +// unlock (or the first row when none is selected); the column is the equipment's display name +// (MenuTeamManager +0x28), its template name when that is empty. +static void listUnlockWeapons(const gameswf::fn_call& fn, ListResult& r, ListHost h, int start, int end) +{ + r.begin(); + IProfileManager* pm = static_cast( + classManager->getSingleton(renddx9abi::HostString("ProfileManager"))); + int profileId = 0; + if (pm) + (void) pm->getProfileId(profileId); // +0x30 + IPlayerUnlocks::UnlockCache cache; + cache.field0 = static_cast(::time(0)); cache.field4 = 0; cache.available = 0; cache.selected = 0; + (void) h->getUnlocks(profileId, &cache); // +0x1C4 + const std::vector unlocks(cache.items); + std::vector definitions; + (void) static_cast(h->getPlayerUnlockInfo())->getItems(definitions); // +0x48, +0x1C + std::map > kitsById; + for (std::size_t k = 0; k < definitions.size(); ++k) + kitsById[static_cast(definitions[k].id)].push_back(static_cast(definitions[k].kit)); + int total = 0; + for (std::size_t j = 0; j < unlocks.size(); ++j) + { + const int id = unlocks[j].id; + if (kitsById.find(id) == kitsById.end()) + continue; + std::string name; + for (std::size_t k = 0; k < definitions.size(); ++k) + { + if (static_cast(definitions[k].id) == id) + { + name = definitions[k].name; + break; + } + } + if (unlocks[j].status != 0) + continue; + if (inWindow(static_cast(total), start, end)) + { + r.beginRowStr(name.c_str()); + r.setInt("wid", id); + const std::vector& kits = kitsById[id]; + r.setInt("kitId", kits.size() == 1 ? kits[0] : -1); + if (s_selectedUnlock == "" && total == 0) + r.setInt("selected", 1); + else if (::_stricmp(s_selectedUnlock.c_str(), name.c_str()) == 0) + r.setInt("selected", 1); + const MenuEquipment* e = + static_cast(h->getMenuTeamManager())->findEquipment(name); // +0x50, +0x28 + if (e) + pushLocalised(r, h, e->displayName != "" ? e->displayName.c_str() : e->templateName.c_str()); + } + ++total; + } + publishList(fn, r, total); +} + +// "custats" (100304A7..100307E5): the selected unlock's equipment (MenuTeamManager +0x28). When its +// template carries exactly one kit among the unlock definitions, a "KIT" row first; then Damage, +// Accuracy and Rate of fire (stat70/74/78), each "available"; "weapon" on the last row. The total +// is 2 whenever the equipment exists, as shipped; 0 otherwise. +static void listCurrentUnlockStats(const gameswf::fn_call& fn, ListResult& r, ListHost h) +{ + r.begin(); + std::vector definitions; + (void) static_cast(h->getPlayerUnlockInfo())->getItems(definitions); // +0x48, +0x1C + std::map > kitsByName; + for (std::size_t k = 0; k < definitions.size(); ++k) + kitsByName[definitions[k].name].push_back(static_cast(definitions[k].kit)); + int total = 0; + const MenuEquipment* e = + static_cast(h->getMenuTeamManager())->findEquipment(s_selectedUnlock); // +0x50, +0x28 + if (e) + { + std::map >::const_iterator kits = kitsByName.find(e->templateName); + if (kits != kitsByName.end() && kits->second.size() == 1) + { + r.beginRow(0); + r.pushNarrow("KIT"); + r.pushInt(kits->second[0]); + } + r.beginRow(0); + r.pushNarrow("Damage"); + r.pushInt(e->stat70); + r.setInt("available", 1); + r.beginRow(1); + r.pushNarrow("Accuracy"); + r.pushInt(e->stat74); + r.setInt("available", 1); + r.beginRow(2); + r.pushNarrow("Rate of fire"); + r.pushInt(e->stat78); + r.setInt("available", 1); + total = 2; + r.setInt("weapon", e->equipmentType == 0 ? 1 : 0); + } + publishList(fn, r, total); +} + +// "credits" (10030A17..10030B4D): host +0x2DC's text/value rows; each row id 0, the localised text +// and "size" = the value. The window is read against the running count. +static void listCredits(const gameswf::fn_call& fn, ListResult& r, ListHost h, int start, int end) +{ + r.begin(); + const std::vector* entries = h->getEntriesEC8(); + int total = 0; + for (std::size_t i = 0; i < entries->size(); ++i) + { + if (inWindow(static_cast(total), start, end)) + { + r.beginRow(0); + pushLocalised(r, h, (*entries)[i].text.c_str()); + r.setInt("size", (*entries)[i].value); + } + ++total; + } + publishList(fn, r, total); +} + +// "age" (10030B66..10030BDB): 10..98; the total is always 89. +static void listAges(const gameswf::fn_call& fn, ListResult& r, int start, int end) +{ + r.begin(); + for (unsigned int i = 0; i < 89; ++i) + { + if (inWindow(i, start, end)) + { + r.beginRow(static_cast(i) + 10); + r.pushInt(static_cast(i) + 10); + } + } + publishList(fn, r, 89); +} + +// "ranklist" (10030BF4..10030D58): the selected statistics player's record (+0x21C, +0x1B0); per +// rank (+0x1C0, asked every pass) the localised name (+0x1B4), "selected" on the player's rank. +static void listRanks(const gameswf::fn_call& fn, ListResult& r, ListHost h, int start, int end) +{ + r.begin(); + const int playerId = h->getSelectedPlayerId(); + SwiffPlayerStatsRecord stats; + (void) h->getPlayerStatsRecord(playerId, stats); + int total = 0; + for (unsigned int i = 0; i < static_cast(h->getRankCount()); ++i) + { + if (inWindow(i, start, end)) + { + r.beginRow(static_cast(i)); + const std::string name = h->getRankName(static_cast(i)); + pushLocalised(r, h, name.c_str()); + if (static_cast(i) == stats.rank) + r.setInt("selected", 1); + } + ++total; + } + publishList(fn, r, total); +} + // "teams" (100264EA..10026616): "MenuTeamManager" before the builder; the count asked before the // loop and again after every pass (unsigned); a team inside the window is asked for (+0x30) and // gives the row id (its teamId) and its localised name (+8); every team counts. @@ -5137,10 +6055,9 @@ static void listUnlockEquipment(const gameswf::fn_call& fn, ListResult& r, ListH TeamManager tm = teamManager(); UnlockRecord rec; rec.now = (int) ::time(0); rec.a = 0; rec.count = 0; rec.b = 0; - rec.unlocks.alloc = 0; rec.unlocks.first = rec.unlocks.last = rec.unlocks.end = 0; const int teamIdentifier = ::atoi(word1); const int kitPosition = ::atoi(word2); - struct NameId { vc71::string name; int id; }; + struct NameId { std::string name; int id; }; NameId* names = 0; unsigned int nameCount = 0; { @@ -5160,7 +6077,7 @@ static void listUnlockEquipment(const gameswf::fn_call& fn, ListResult& r, ListH names = new NameId[items.size()]; for (std::size_t k = 0; k < items.size(); ++k) { - vc71::string key; + std::string key; shippedLowercase(items[k].name.c_str(), key); unsigned int slot = 0; while (slot < nameCount && ::strcmp(names[slot].name.c_str(), key.c_str()) != 0) ++slot; @@ -5177,7 +6094,7 @@ static void listUnlockEquipment(const gameswf::fn_call& fn, ListResult& r, ListH continue; if (k >= (unsigned int) start && k < (unsigned int) end) { - vc71::string key; + std::string key; shippedLowercase(equipmentTemplate(e), key); r.beginRowStr(key.c_str()); pushLocalised(r, h, equipmentDisplay(e)); @@ -5221,7 +6138,7 @@ static void listWeaponStats(const gameswf::fn_call& fn, ListResult& r, const tu_ { (void) teamManager(); // asked and dropped r.begin(); - vc71::string name(s_selectedEquipment.c_str()); + std::string name(s_selectedEquipment.c_str()); if (which == "wpunlockstats") name = s_selectedUnlockEquipment.c_str(); else if (which == "wpuunlockstats") @@ -5300,7 +6217,11 @@ void as_playerstats_unlock(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_unlock"); void* h = asHost(); +#if defined(__APPLE__) + const int unlockId = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int unlockId = (int) fn.arg(0).to_number(); +#endif const int pid = hostPlayerId(); IBase* unlocks = static_cast(h)->getPlayerUnlocks(); const bool result = static_cast(unlocks)->setUnlocks(pid, unlockId); @@ -5469,12 +6390,20 @@ static void setGeneralBoolArgumentFirst(const gameswf::fn_call& fn, GsBoolSetter static void setGeneralIntOwnerFirst(const gameswf::fn_call& fn, GsIntSetter setter) { IGeneralSettings* gs = generalSettingsOf(generalSettingsSingleton()); +#if defined(__APPLE__) + const int value = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int value = static_cast(fn.arg(0).to_number()); +#endif (gs->*setter)(value); } static void setGeneralIntArgumentFirst(const gameswf::fn_call& fn, GsIntSetter setter) { +#if defined(__APPLE__) + const int value = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int value = static_cast(fn.arg(0).to_number()); +#endif (generalSettingsOf(generalSettingsSingleton())->*setter)(value); } @@ -5567,10 +6496,26 @@ void as_generalsettings_setCrosshairColor(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_generalsettings_setCrosshairColor"); IGeneralSettings* gs = generalSettingsOf(generalSettingsSingleton()); +#if defined(__APPLE__) + const int red = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int red = static_cast(fn.arg(0).to_number()); +#endif +#if defined(__APPLE__) + const int green = bf2x87::toIntTruncate(fn.arg(1).to_number()); +#else const int green = static_cast(fn.arg(1).to_number()); +#endif +#if defined(__APPLE__) + const int blue = bf2x87::toIntTruncate(fn.arg(2).to_number()); +#else const int blue = static_cast(fn.arg(2).to_number()); +#endif +#if defined(__APPLE__) + const int alpha = bf2x87::toIntTruncate(fn.arg(3).to_number()); +#else const int alpha = static_cast(fn.arg(3).to_number()); +#endif gs->setCrosshairColor(red, green, blue, alpha); // +0x54 } @@ -5594,9 +6539,21 @@ void as_generalsettings_getSquadtagColor(const gameswf::fn_call& fn) { SWF_AS_TR static void setGeneralRgb(const gameswf::fn_call& fn, int offset) { IGeneralSettings* gs = generalSettingsOf(generalSettingsSingleton()); +#if defined(__APPLE__) + const int red = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int red = static_cast(fn.arg(0).to_number()); +#endif +#if defined(__APPLE__) + const int green = bf2x87::toIntTruncate(fn.arg(1).to_number()); +#else const int green = static_cast(fn.arg(1).to_number()); +#endif +#if defined(__APPLE__) + const int blue = bf2x87::toIntTruncate(fn.arg(2).to_number()); +#else const int blue = static_cast(fn.arg(2).to_number()); +#endif if (offset == 0x5C) gs->setBuddytagColor(red, green, blue); // +0x5C else gs->setSquadtagColor(red, green, blue); // +0x64 } @@ -5705,8 +6662,7 @@ void as_generalsettings_removeServer(const gameswf::fn_call& fn) // Control settings edit backup maps and restore the prior engine selection afterward. -// mapInput remains unregistered until input capture and its integer status contract are -// implemented; publishing the current Boolean stub would report ineffective rebindings. +// mapInput (sub_1000EDA0) is registered by registerRecoveredNatives (SwiffNativesRecovered.inl). static IBase* controlSettingsSingleton() { @@ -5815,7 +6771,11 @@ void as_controlsettings_setActiveControlMap(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_controlsettings_setActiveControlMap"); (void) g_swiffPlayerInstance->getSwiffHost(); +#if defined(__APPLE__) + const int index = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int index = static_cast(fn.arg(0).to_number()); +#endif s_editedControlMap = kEditedControlMapNames[index]; } @@ -5853,7 +6813,11 @@ void as_controlsettings_resetDefault(const gameswf::fn_call& fn) { SWF_AS_TRACE( void as_controlsettings_getMappedString(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_controlsettings_getMappedString"); +#if defined(__APPLE__) + const int input = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int input = static_cast(fn.arg(0).to_number()); +#endif const bool alternate = fn.arg(1).to_bool(); const bool second = fn.arg(2).to_bool(); renddx9abi::HostString key; @@ -5873,11 +6837,11 @@ void as_controlsettings_getMappedString(const gameswf::fn_call& fn) { HostWide localised; (void) g_swiffPlayerInstance->getSwiffHost()->getLocalizedString(localised, key); // +0xA8 - gameswf::assign_dice_string_object_wide(object, reinterpret_cast(localised.c_str())); + gameswf::assign_dice_string_object_wide(object, BF2_DICE_UTF16(localised.c_str())); } } else - gameswf::assign_dice_string_object_wide(object, reinterpret_cast(text.c_str())); + gameswf::assign_dice_string_object_wide(object, BF2_DICE_UTF16(text.c_str())); restoreControlMapSelection(); } fn.result->set_as_object_interface(object); @@ -6159,7 +7123,11 @@ static void publishServerInt(const gameswf::fn_call& fn, GssIntGetter getter) static void setServerInt(const gameswf::fn_call& fn, GssIntSetter setter) { IGameServerSettings* gss = gameServerSettings(); +#if defined(__APPLE__) + const int value = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int value = static_cast(fn.arg(0).to_number()); +#endif (gss->*setter)(value); } @@ -6202,7 +7170,11 @@ void as_serversettings_setMaxPlayers(const gameswf::fn_call& fn) SWF_AS_TRACE("as_serversettings_setMaxPlayers"); (void) g_swiffPlayerInstance->getSwiffHost(); IGameServerSettings* gss = gameServerSettings(); +#if defined(__APPLE__) + const int value = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int value = static_cast(fn.arg(0).to_number()); +#endif gss->setMaxPlayers(value); // +0x44 (void) gss->apply(); // +0x18 } @@ -6245,12 +7217,20 @@ void as_serversettings_setCoopBotCount(const gameswf::fn_call& fn) IBase* gss = gameServerSettingsSingleton(); if (gs) { +#if defined(__APPLE__) + const int count = bf2x87::toIntTruncate(value); +#else const int count = static_cast(value); +#endif static_cast(gs)->setMaxBots(count); // +0xB4 static_cast(gs)->setCoopBotCount(count); // +0xF4 } if (gss) +#if defined(__APPLE__) + static_cast(gss)->setCoopBotCount(bf2x87::toIntTruncate(value)); // +0x1A4 +#else static_cast(gss)->setCoopBotCount(static_cast(value)); // +0x1A4 +#endif } // AS_ServerSettings_setCoopBotDiff (0x10063AA0): argument zero as a float first; the two lookups; @@ -6572,7 +7552,11 @@ void as_multiplay_addMapToMapList(const gameswf::fn_call& fn) if (!path.empty()) { const std::string mode(fn.arg(1).to_string()); +#if defined(__APPLE__) + const unsigned int size = (unsigned int) bf2x87::toIntTruncate(fn.arg(2).to_number()); +#else const unsigned int size = (unsigned int) (int) fn.arg(2).to_number(); +#endif IBase* gs = classManager->getSingleton(renddx9abi::HostString("GeneralSettings")); if (static_cast(static_cast(gs))->getUseBots()) { @@ -6662,7 +7646,11 @@ void as_multiplay_removeMapfromMapList(const gameswf::fn_call& fn) BusyHost busy = busyOpen(); ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); (void) classManager->getSingleton(renddx9abi::HostString("LocalProfileManager")); +#if defined(__APPLE__) + const int index = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int index = static_cast(fn.arg(0).to_number()); +#endif (void) h->removeServerEntry(static_cast(index)); // +0x12C busyClose(busy); } @@ -6676,7 +7664,11 @@ void as_multiplay_moveMapInList(const gameswf::fn_call& fn) SWF_AS_TRACE("as_multiplay_moveMapInList"); ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); (void) classManager->getSingleton(renddx9abi::HostString("LocalProfileManager")); +#if defined(__APPLE__) + const int index = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int index = static_cast(fn.arg(0).to_number()); +#endif const bool up = fn.arg(1).to_bool(); (void) h->moveServerEntry(static_cast(index), up); // +0x130 fn.result->set_bool(true); @@ -6847,7 +7839,7 @@ void as_multiplay_getMapDescriptionFromId(const gameswf::fn_call& fn) std::wstring out; g_swiffPlayerInstance->getSwiffHost()->getLocalizedString(out, key); // +0xA8 gameswf::as_object_interface* text = gameswf::create_dice_string_object(nullptr, 0); - gameswf::assign_dice_string_object_wide(text, reinterpret_cast(out.c_str())); + gameswf::assign_dice_string_object_wide(text, BF2_DICE_UTF16(out.c_str())); fn.result->set_as_object_interface(text); return; } @@ -7054,7 +8046,11 @@ void as_multiplay_downloadServerLogo(const gameswf::fn_call& fn) void as_multiplay_getTeamName(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_multiplay_getTeamName"); +#if defined(__APPLE__) + const int index = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int index = (int) fn.arg(0).to_number(); +#endif const renddx9abi::HostString name(s_teamNames[index]); fn.result->set_tu_string(tu_string(name.c_str())); } @@ -7159,7 +8155,7 @@ void as_mod_getCurrentModName(const gameswf::fn_call& fn) void as_playerstats_getCurrentUnlockDescription(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_getCurrentUnlockDescription"); - vc71::string name(s_selectedUnlock.c_str()); + std::string name(s_selectedUnlock.c_str()); EquipmentKeys rec; if (!findEquipmentByName(name.c_str(), rec)) { fn.result->set_as_object_interface(gameswf::create_dice_string_object(0, 0)); return; } setLocalisedStringObject(fn, rec.descriptionKey); @@ -7175,13 +8171,13 @@ void as_profile_getCurrentRankString(const gameswf::fn_call& fn) if (!h) { fn.result->set_as_object_interface(gameswf::create_dice_string_object(0, 0)); return; } PlayerStatsRecord* rec = new PlayerStatsRecord(); (void) fetchPlayerStats(h, *rec); - const int rankId = *reinterpret_cast(rec->bytes + 160); + const int rankId = rec->rank; delete rec; - vc71::string key; + std::string key; hostRankKey(h, rankId, key); - vc71::wstring text; + std::wstring text; hostLocaliseKey(h, key, text); - fn.result->set_as_object_interface(gameswf::create_dice_string_object(reinterpret_cast(text.c_str()), (int) text.size())); + fn.result->set_as_object_interface(gameswf::create_dice_string_object(BF2_DICE_UTF16(text.c_str()), (int) text.size())); } // dice.bf2.Logic.beginWaitState(flag), and promoted. @@ -7195,7 +8191,11 @@ void as_logic_beginWaitState(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_logic_beginWaitState"); ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); +#if defined(__APPLE__) + (void) h->setBusy(bf2x87::toIntTruncate(fn.arg(0).to_number())); // +0x2B0 +#else (void) h->setBusy(static_cast(fn.arg(0).to_number())); // +0x2B0 +#endif } // dice.bf2.Logic.endWaitState(), and promoted. No @@ -7222,7 +8222,11 @@ void as_logic_getTeamsConId(const gameswf::fn_call& fn) SWF_AS_TRACE("as_logic_getTeamsConId"); ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); IMenuTeamManager* tm = static_cast(h->getMenuTeamManager()); // +0x50 +#if defined(__APPLE__) + const int id = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int id = (int) fn.arg(0).to_number(); +#endif const MenuTeam* team = tm->findTeamById(id); // +0x34 fn.result->set_double((double) team->teamId); } @@ -7231,12 +8235,13 @@ void as_logic_getTeamsConId(const gameswf::fn_call& fn) // keyed by the same bit mask the checkboxes use. setToggleFilter below writes it; its reader is // Multiplay.updateFilter (PE 10056020 -> 10055700). The shipped map // is constructed and destroyed by the DLL's own static initialiser pair at 100D6290 / 100D6A21. -// The retained vc71::string values are internal storage; this map never crosses the DLL boundary. -static std::map s_filterValues; +// The retained std::string values are internal storage; this map never crosses the DLL boundary. +static std::map s_filterValues; // unk_100F8810 - the DLL-global free-text filter clause, written by Multiplay.setFilter // (PE 100519C0, still unregistered here) and read - and rewritten in place - by the builder below. -static vc71::string s_textFilter; +static std::string s_textFilter; + // Publishes whether any bit in the supplied filter mask is enabled. // Requires GeneralSettings and one numeric argument. @@ -7245,7 +8250,11 @@ void as_multiplay_getToggleFilter(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_multiplay_getToggleFilter"); IBase* gs = classManager->getSingleton(renddx9abi::HostString("GeneralSettings")); +#if defined(__APPLE__) + const int mask = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int mask = (int) fn.arg(0).to_number(); +#endif fn.result->set_bool(static_cast(static_cast(gs))->getToggleFilter(mask)); } // Sets a browser filter bit and its query clause from (mask, on, clause); publishes no result. @@ -7256,9 +8265,13 @@ void as_multiplay_setToggleFilter(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_multiplay_setToggleFilter"); IBase* gs = classManager->getSingleton(renddx9abi::HostString("GeneralSettings")); +#if defined(__APPLE__) + const int mask = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int mask = (int) fn.arg(0).to_number(); +#endif const bool on = fn.arg(1).to_bool(); - vc71::string clause(fn.arg(2).to_string()); + std::string clause(fn.arg(2).to_string()); const bool blank = clause.c_str()[0] == 0 || ::strcmp(clause.c_str(), "%%") == 0; static_cast(static_cast(gs))->setToggleFilter(mask, blank ? false : on); if (blank) @@ -7283,12 +8296,12 @@ static bool isMapSizeFilter(int mask) { return mask == 2048 || mask == 4096 || mask == 8192; } -static void buildFilterString(vc71::string& out) +static void buildFilterString(std::string& out) { IBase* gs = classManager->getSingleton(renddx9abi::HostString("GeneralSettings")); - vc71::string filter; + std::string filter; - typedef std::map::const_iterator Entry; + typedef std::map::const_iterator Entry; unsigned int mapSizeArmed = 0; for (Entry it = s_filterValues.begin(); it != s_filterValues.end(); ++it) if (filterBitOn(gs, it->first) && it->second.c_str()[0] != 0 && isMapSizeFilter(it->first)) @@ -7299,7 +8312,7 @@ static void buildFilterString(vc71::string& out) for (Entry it = s_filterValues.begin(); it != s_filterValues.end(); ++it) { const int mask = it->first; - const vc71::string& clause = it->second; + const std::string& clause = it->second; if (!filterBitOn(gs, mask) || clause.c_str()[0] == 0) continue; if (filter.c_str()[0] == 0) @@ -7349,9 +8362,9 @@ static void buildFilterString(vc71::string& out) // would be a wild copy rather than a throw, so the length tests stop one character // short of that boundary. Every other input is byte-for-byte the shipped result. if (s_textFilter.size() > 4 && ::strncmp(s_textFilter.c_str(), "and", 3) == 0) - s_textFilter = vc71::string(s_textFilter.c_str() + 4, s_textFilter.size() - 4); + s_textFilter = std::string(s_textFilter.c_str() + 4, s_textFilter.size() - 4); if (s_textFilter.size() > 5 && ::strncmp(s_textFilter.c_str(), " and", 4) == 0) - s_textFilter = vc71::string(s_textFilter.c_str() + 5, s_textFilter.size() - 5); + s_textFilter = std::string(s_textFilter.c_str() + 5, s_textFilter.size() - 5); filter = s_textFilter; } else @@ -7371,7 +8384,7 @@ void as_multiplay_updateFilter(const gameswf::fn_call& fn) ISwiffHost* cursorHost = static_cast(cursorBase); if (cursorHost) { SetCursor(cursorHost->getCursor(1)); cursorHost->setBusy(1); } ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); - vc71::string filter; // declared first, so it dies last + std::string filter; // declared first, so it dies last buildFilterString(filter); const std::string kind = h->getServerListKind(); // +0x134 IServerBrowser* list = h->getServerList(kind); // +0x7C @@ -7594,10 +8607,10 @@ static void awardText(const gameswf::fn_call& fn, bool description) AwardView award; if (findAward(id, level, award)) { - vc71::wstring wide; + std::wstring wide; hostLocaliseKey(static_cast(g_swiffPlayerInstance->getSwiffHost()), - vc71::string((description ? award.description : award.name).c_str()), wide); - gameswf::assign_dice_string_object_wide(text, reinterpret_cast(wide.c_str())); + std::string((description ? award.description : award.name).c_str()), wide); + gameswf::assign_dice_string_object_wide(text, BF2_DICE_UTF16(wide.c_str())); } else { @@ -7997,7 +9010,11 @@ void as_multiplay_setLeaderboardId(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_multiplay_setLeaderboardId"); void* h = g_swiffPlayerInstance->getSwiffHost(); +#if defined(__APPLE__) + hostSetLeaderboardId(h, bf2x87::toIntTruncate(fn.arg(0).to_number())); +#else hostSetLeaderboardId(h, static_cast(fn.arg(0).to_number())); +#endif } // Multiplay.getLeaderboardName() / getLeaderboardDescription(), inside the @@ -8015,10 +9032,10 @@ static void leaderboardText(const gameswf::fn_call& fn, bool description) const char* entry = (category >= 0 && category <= 3) ? leaderboardKey(category, board) : 0; if (entry) key = description ? std::string(entry) + "_desc" : std::string(entry); - vc71::wstring wide; - hostLocaliseKey(static_cast(g_swiffPlayerInstance->getSwiffHost()), vc71::string(key.c_str()), wide); + std::wstring wide; + hostLocaliseKey(static_cast(g_swiffPlayerInstance->getSwiffHost()), std::string(key.c_str()), wide); gameswf::as_object_interface* text = gameswf::create_dice_string_object(nullptr, 0); - gameswf::assign_dice_string_object_wide(text, reinterpret_cast(wide.c_str())); + gameswf::assign_dice_string_object_wide(text, BF2_DICE_UTF16(wide.c_str())); fn.result->set_as_object_interface(text); busyClose(busy); } @@ -8075,7 +9092,11 @@ void as_multiplay_goLeaderboardPlayer(const gameswf::fn_call& fn) SWF_AS_TRACE("as_multiplay_goLeaderboardPlayer"); BusyHost busy = busyOpen(); void* h = g_swiffPlayerInstance->getSwiffHost(); +#if defined(__APPLE__) + hostGoLeaderboardPlayer(h, bf2x87::toIntTruncate(fn.arg(0).to_number())); +#else hostGoLeaderboardPlayer(h, static_cast(fn.arg(0).to_number())); +#endif busyClose(busy); } @@ -8087,8 +9108,16 @@ void as_playerstats_getLeaderBoard(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_getLeaderBoard"); void* h = g_swiffPlayerInstance->getSwiffHost(); +#if defined(__APPLE__) + const int id = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int id = static_cast(fn.arg(0).to_number()); +#endif +#if defined(__APPLE__) + const int request = bf2x87::toIntTruncate(fn.arg(1).to_number()); +#else const int request = static_cast(fn.arg(1).to_number()); +#endif HostLeaderboard cache; const bool ok = id ? hostGetLeaderboardPlayer(h, id, cache, request) : hostGetLeaderboard(h, cache, request, 0); fn.result->set_bool(ok); @@ -8098,8 +9127,16 @@ void as_playerstats_refreshLeaderBoard(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_refreshLeaderBoard"); void* h = g_swiffPlayerInstance->getSwiffHost(); +#if defined(__APPLE__) + const int id = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int id = static_cast(fn.arg(0).to_number()); +#endif +#if defined(__APPLE__) + const int request = bf2x87::toIntTruncate(fn.arg(1).to_number()); +#else const int request = static_cast(fn.arg(1).to_number()); +#endif fn.result->set_bool(hostFetchLeaderboard(h, id, request, 0)); } @@ -8387,7 +9424,11 @@ void as_multiplay_setLeaderboardCategoryId(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_multiplay_setLeaderboardCategoryId"); ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); +#if defined(__APPLE__) + h->setLeaderboardCategory(bf2x87::toIntTruncate(fn.arg(0).to_number())); // +0x140 +#else h->setLeaderboardCategory(static_cast(fn.arg(0).to_number())); // +0x140 +#endif } // Returns the first current-mod game mode's display name, or empty for no modes. @@ -8418,8 +9459,8 @@ void as_multiplay_getSelectedLeaderboardCategoryId(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_multiplay_getSelectedLeaderboardCategoryId"); (void) g_swiffPlayerInstance->getSwiffHost(); - const vc71::string key("BFHQ_leaderboardscores"); - vc71::wstring text; + const std::string key("BFHQ_leaderboardscores"); + std::wstring text; ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); std::wstring wide; (void) h->getLocalizedString(wide, std::string(key.c_str())); // +0xA8 @@ -8427,7 +9468,7 @@ void as_multiplay_getSelectedLeaderboardCategoryId(const gameswf::fn_call& fn) // The String's wide side is assigned from the copy's c_str() (10052647..1005264E), so it ends // at the first NUL whatever length the host wrote. fn.result->set_as_object_interface(gameswf::create_dice_string_object( - reinterpret_cast(text.c_str()), (int) ::wcslen(text.c_str()))); + BF2_DICE_UTF16(text.c_str()), (int) ::wcslen(text.c_str()))); } // sub_1005D7A0 - dice.bf2.Profile.getRankProgress(): SwiffHost +716() as a double - a number. @@ -8448,14 +9489,14 @@ void as_profile_getNextRankString(const gameswf::fn_call& fn) if (!h) { fn.result->set_as_object_interface(gameswf::create_dice_string_object(0, 0)); return; } PlayerStatsRecord* rec = new PlayerStatsRecord(); (void) fetchPlayerStats(h, *rec); - const int rankId = *reinterpret_cast(rec->bytes + 160); + const int rankId = rec->rank; delete rec; const int next = hostNextRank(h, rankId); - vc71::string key; + std::string key; hostRankKey(h, next, key); - vc71::wstring text; + std::wstring text; hostLocaliseKey(h, key, text); - fn.result->set_as_object_interface(gameswf::create_dice_string_object(reinterpret_cast(text.c_str()), (int) text.size())); + fn.result->set_as_object_interface(gameswf::create_dice_string_object(BF2_DICE_UTF16(text.c_str()), (int) text.size())); } // sub_1005BA20 - dice.bf2.PlayerStats.getKitAccuracy(): the stats record's int at +2220 as a number @@ -8465,7 +9506,7 @@ void as_playerstats_getKitAccuracy(const gameswf::fn_call& fn) SWF_AS_TRACE("as_playerstats_getKitAccuracy"); PlayerStatsRecord* rec = new PlayerStatsRecord(); const bool ok = fetchPlayerStats(asHost(), *rec); - const double v = ok ? (double) *reinterpret_cast(rec->bytes + 2220) : 0.0; + const double v = ok ? (double) rec->osaa : 0.0; delete rec; fn.result->set_double(v); } @@ -8473,37 +9514,41 @@ void as_playerstats_getKitAccuracy(const gameswf::fn_call& fn) // sub_1005AC60 / sub_1005ADB0 - dice.bf2.PlayerStats.getOpponentName() / getVictimName(): the stats // record's std::string at +492 / +456; empty or a single space becomes "-", and so does a record that // could not be fetched. string. -static void statsNameAt(const gameswf::fn_call& fn, int offset) +static void statsNameAt(const gameswf::fn_call& fn, std::string PlayerStatsRecord::* field) { PlayerStatsRecord* rec = new PlayerStatsRecord(); - vc71::string out("-"); + std::string out("-"); if (fetchPlayerStats(asHost(), *rec)) { - const vc71::string* name = reinterpret_cast(rec->bytes + offset); + const std::string* name = &(rec->*field); if (name->size() != 0 && ::strcmp(name->c_str(), " ") != 0) out = *name; } delete rec; fn.result->set_tu_string(tu_string(out.c_str())); } -void as_playerstats_getOpponentName(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_getOpponentName"); statsNameAt(fn, 492); } -void as_playerstats_getVictimName(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_getVictimName"); statsNameAt(fn, 456); } +void as_playerstats_getOpponentName(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_getOpponentName"); statsNameAt(fn, &PlayerStatsRecord::vmns); } +void as_playerstats_getVictimName(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_getVictimName"); statsNameAt(fn, &PlayerStatsRecord::mvns); } // sub_1005AF00 / sub_1005AFF0 - getOpponentRankId() / getVictimRankId(): the int beside the name // (+524 / +488) as a number; a single-space name or an unfetched record answers -1. -static void statsRankIdAt(const gameswf::fn_call& fn, int nameOffset, int idOffset) +static void statsRankIdAt(const gameswf::fn_call& fn, std::string PlayerStatsRecord::* nameField, + int PlayerStatsRecord::* idField) { PlayerStatsRecord* rec = new PlayerStatsRecord(); double v = -1.0; if (fetchPlayerStats(asHost(), *rec)) { - const vc71::string* name = reinterpret_cast(rec->bytes + nameOffset); - if (::strcmp(name->c_str(), " ") != 0) v = (double) *reinterpret_cast(rec->bytes + idOffset); + const std::string* name = &(rec->*nameField); + if (::strcmp(name->c_str(), " ") != 0) v = (double) (rec->*idField); } delete rec; fn.result->set_double(v); } -void as_playerstats_getOpponentRankId(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_getOpponentRankId"); statsRankIdAt(fn, 492, 524); } -void as_playerstats_getVictimRankId(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_getVictimRankId"); statsRankIdAt(fn, 456, 488); } +void as_playerstats_getOpponentRankId(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_getOpponentRankId"); statsRankIdAt(fn, &PlayerStatsRecord::vmns, &PlayerStatsRecord::vmrs); } +void as_playerstats_getVictimRankId(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_getVictimRankId"); statsRankIdAt(fn, &PlayerStatsRecord::mvns, &PlayerStatsRecord::mvrs); } + +// The retail natives recovered by c-swiff-natives. +#include "SwiffNativesRecovered.inl" static void registerAsMethods(SwiffAsNamespace* general, SwiffAsNamespace** ns, const char* const* names, int count) @@ -8673,7 +9718,7 @@ static void registerAsMethods(SwiffAsNamespace* general, SwiffAsNamespace** ns, else if (::strcmp(n, "ControlSettings") == 0) { // Twenty-one of the shipped registrar 1000F090's twenty-two rows, in its order. - // mapInput (1000EDA0) is withheld on purpose: see the section comment above its siblings. + // mapInput (1000EDA0) is registered by registerRecoveredNatives. ns[i]->registerNativeCompatibleMethod("setActiveControlMap"); ns[i]->registerNativeCompatibleMethod("getMappedString"); ns[i]->registerNativeCompatibleMethod("cancel"); @@ -8999,6 +10044,8 @@ static void registerAsMethods(SwiffAsNamespace* general, SwiffAsNamespace** ns, ns[i]->registerNativeCompatibleMethod("endWaitState"); ns[i]->registerNativeCompatibleMethod("setFrameLabel"); ns[i]->registerNativeCompatibleMethod("enableScroller"); + ns[i]->registerNativeCompatibleMethod("eraseStorageString"); // sub_1004D170, registered at 1004E3E3 + ns[i]->registerNativeCompatibleMethod("getDefaultLevel"); // sub_1004D5B0, registered at 1004E43B ns[i]->registerNativeCompatibleMethod("getIsLoading"); ns[i]->registerNativeCompatibleMethod("setIsLoading"); ns[i]->registerNativeCompatibleMethod("readyToPlay"); @@ -9098,6 +10145,8 @@ static void buildAsGraph() built[i] = addNs(bf2, kNamespaces[i], dotted); } registerAsMethods(general, built, kNamespaces, nsCount); + registerRecoveredNatives(built, kNamespaces, nsCount); // c-swiff-natives: the rows the port lacked + registerHapticNatives(built, kNamespaces, nsCount); ::renddx9abi::logf("[SwiffPlayer] buildAsGraph: _global.dice + dice.bf2.<%d namespaces> built", nsCount); } @@ -9110,6 +10159,9 @@ namespace { inline void** rcVtbl(void* rc) { return *reinterpret_cast(rc); } +#if !defined(_MSC_VER) +using namespace ::dice::hfe::ui::native_render; +#else // bitmap creators (return an int texture handle) inline int rcCreateEmpty(void* rc) // +0x18 slot 6 { return reinterpret_cast(rcVtbl(rc)[0x18/4])(rc); } @@ -9161,7 +10213,7 @@ inline void rcDrawBitmapNull(void* rc, const void* m, int texId, inline void rcBeginMask(void* rc) { reinterpret_cast(rcVtbl(rc)[0x9C/4])(rc); } // +0x9C slot 39 inline void rcEndMask(void* rc) { reinterpret_cast(rcVtbl(rc)[0xA0/4])(rc); } // +0xA0 slot 40 inline void rcDisableMask(void* rc) { reinterpret_cast(rcVtbl(rc)[0xA4/4])(rc); } // +0xA4 slot 41 -// [DICE-MOD SwiffPlayer #36] the text ("font wrapper") slots 26-37, the targets of the shipped +// the text ("font wrapper") slots 26-37, the targets of the shipped // render_handler forwarders 0x10005DC0..0x10005EC0. inline void* rcTextCreate(void* rc, const char* name, int size) { return reinterpret_cast(rcVtbl(rc)[0x68/4])(rc, name, size); } // +0x68 slot 26 createFont inline void rcTextRelease(void* rc, void* line) { reinterpret_cast(rcVtbl(rc)[0x6C/4])(rc, line); } // +0x6C slot 27 @@ -9169,9 +10221,9 @@ inline void rcTextSet(void* rc, void* line, const wchar_t* text) { re inline void rcTextDetach(void* rc, void* line) { reinterpret_cast(rcVtbl(rc)[0x74/4])(rc, line); } // +0x74 slot 29 inline void rcTextDraw(void* rc, void* line, const void* m, unsigned c, int f) { reinterpret_cast(rcVtbl(rc)[0x78/4])(rc, line, m, c, f); } // +0x78 slot 30 drawText inline char rcTextExtent(void* rc, void* line, int n, float* w, float* h) { return reinterpret_cast(rcVtbl(rc)[0x7C/4])(rc, line, n, w, h); } // +0x7C slot 31 -inline char rcTextHit(void* rc, void* line, int* pos, int x, int y) { return reinterpret_cast(rcVtbl(rc)[0x80/4])(rc, line, pos, x, y); } // +0x80 slot 32 +inline char rcTextHit(void* rc, void* line, int* pos, float x, float y) { return reinterpret_cast(rcVtbl(rc)[0x80/4])(rc, line, pos, x, y); } // +0x80 slot 32 - RendDX9 0x10152FF0 fld/fmul's x, y inline int rcTextSelection(void* rc, void* line, int* a, int* b) { return reinterpret_cast(rcVtbl(rc)[0x84/4])(rc, line, a, b); } // +0x84 slot 33 - AL answers "a selection exists" (sub_1009A910 -> sub_10088D60) -inline char rcTextSetSelection(void* rc, void* line, int a, int b, int c, int d) { return reinterpret_cast(rcVtbl(rc)[0x88/4])(rc, line, a, b, c, d); } // +0x88 slot 34 +inline char rcTextSetSelection(void* rc, void* line, float a, float b, float c, float d) { return reinterpret_cast(rcVtbl(rc)[0x88/4])(rc, line, a, b, c, d); } // +0x88 slot 34 - RendDX9 0x10153060 fld/fmul's all four inline void rcTextBlur(void* rc, void* line) { reinterpret_cast(rcVtbl(rc)[0x8C/4])(rc, line); } // +0x8C slot 35 inline void rcTextSetSize(void* rc, void* line, float size, int flag) { reinterpret_cast(rcVtbl(rc)[0x90/4])(rc, line, size, flag); } // +0x90 slot 36 inline void rcTextCaret(void* rc, void* line, int pos) { reinterpret_cast(rcVtbl(rc)[0x94/4])(rc, line, pos); } // +0x94 slot 37 @@ -9182,14 +10234,25 @@ inline void rcSetMovieHeight(void* rc, int h) { reinterpret_cast(rcVtbl(rc)[0xB0/4])(rc, sx, sy); } // +0xB0 slot 44 inline void rcSetBackgroundColor(void* rc, unsigned rgb) { reinterpret_cast(rcVtbl(rc)[0xB4/4])(rc, rgb); } // +0xB4 slot 45 inline void rcSetMouseState(void* rc, int x, int y, int b) { reinterpret_cast(rcVtbl(rc)[0xB8/4])(rc, x, y, b); } // +0xB8 slot 46 -inline char rcCapability0(void* rc, int a) { return reinterpret_cast(rcVtbl(rc)[0xC4/4])(rc, a); } // +0xC4 slot 49 -inline char rcCapability1(void* rc, int a) { return reinterpret_cast(rcVtbl(rc)[0xC8/4])(rc, a); } // +0xC8 slot 50 -inline void rcSetPairState(void* rc, int a, int b) { reinterpret_cast(rcVtbl(rc)[0xD4/4])(rc, a, b); } // +0xD4 slot 53 +inline char rcCapability0(void* rc, intptr_t a) { return reinterpret_cast(rcVtbl(rc)[0xC4/4])(rc, a); } // +0xC4 slot 49 +inline char rcCapability1(void* rc, intptr_t a) { return reinterpret_cast(rcVtbl(rc)[0xC8/4])(rc, a); } // +0xC8 slot 50 +inline void rcSetPairState(void* rc, intptr_t a, int b) { reinterpret_cast(rcVtbl(rc)[0xD4/4])(rc, a, b); } // +0xD4 slot 53 inline void rcUpdateTime(void* rc, unsigned t, float dt) { reinterpret_cast(rcVtbl(rc)[0xD8/4])(rc, t, dt); } // +0xD8 slot 54 +#endif // Movie objects belong to this gameswf build and require its typed API; compatibility // offsets from the older movie interface do not apply. // Host callbacks below retain the separate ISwiffHost ABI. +#if !defined(_MSC_VER) +// [CHOSEN, not recovered] These are the four raw helpers still used by the +// lifecycle. ActionScript already uses typed ISwiffHost calls. Keep obsolete +// PE-only helpers out of the native image, including their manual sret shapes. +inline void hostPreLoad10(void* h) { static_cast(h)->init(); } +inline void hostPreLoad50(void* h) { static_cast(h)->getMenuTeamManager(); } +inline void hostUpdate(void* h) { static_cast(h)->update(); } +inline void hostGetViewportSize(void* h, unsigned* w, unsigned* height) +{ static_cast(h)->getViewportSize(w, height); } +#else inline void hostPreLoad10(void* h) { reinterpret_cast(rcVtbl(h)[0x10/4])(h); } // +0x10 inline void hostPreLoad50(void* h) { reinterpret_cast(rcVtbl(h)[0x50/4])(h); } // +0x50 inline void hostUpdate(void* h) { reinterpret_cast(rcVtbl(h)[0x20/4])(h); } // +0x20 @@ -9240,9 +10303,7 @@ inline void hostSetJoinPassword(void* h, const void* str) { reinterpret_cast(rcVtbl(pm)[88/4])(pm, stdStringOut); } // +0x58 inline void pmClear(void* pm) { reinterpret_cast(rcVtbl(pm)[72/4])(pm); } // +0x48 - -// A queued mouse sample - 12 bytes, the element of the +1104 vc71-shaped vector. -struct MouseState { int x; int y; int buttons; }; +#endif // Reinterpret a float's bits as a dword (updateTime/line_style_width pass floats through dword slots). inline unsigned floatBits(float f) { unsigned d; ::memcpy(&d, &f, 4); return d; } @@ -9284,27 +10345,36 @@ SwiffPlayer::SwiffPlayer() swiff_host = 0; elapsed_time = 0.0f; pad_44d[0] = pad_44d[1] = pad_44d[2] = 0; - queued_mouse_aux = queued_mouse_begin = queued_mouse_end = queued_mouse_capacity = 0; g_swiffPlayerInstance = this; + ++s_livePlayers; // [CHOSEN, not recovered] issue #7, see releaseMovie // The shipped ctor's sub_1006F100(0) sets a gameswf file-scope byte to 0 [UNRESOLVED: which // gameswf setter]. That byte is zero-initialised anyway, so omitting the call is a no-op // equivalent; resolve and reinstate in Stage 3 if the movie path proves it matters. - // The three gameswf registrations (file / fscommand / render), in the shipped - // ctor's order at 10006F79..10006F8F. NO sound handler is registered - - // the shipped ctor registers exactly these three. + // The three gameswf registrations (file opener 0x1006F160, log 0x1009AF40, render 0x1009A3F0), + // in the shipped ctor's order at 10006F79..10006F8F. No fscommand handler is registered (the + // setter 0x1008A1A0 has no caller, and gameswf tests the null handler) and no sound handler. gameswf::register_file_opener_callback(swiffFileOpener); - gameswf::register_fscommand_callback(swiffFsCommand); + gameswf::register_log_callback(swiffLogCallback); gameswf::set_render_handler(&render_handler); - // Off unless BF2_SWIFFPLAYER_ASLOG=1 - see asLogEnabled(). Retail registers no log callback. + // [TEMP] The AS trace replaces the shipped log callback when explicitly selected; + // the separate input diagnostic admits only mouse-prefixed messages. if (asLogEnabled()) gameswf::register_log_callback(swiffAsLogCb); initKeyTranslation(); +#if defined(__APPLE__) + // [CHOSEN, not recovered] Cocoa asynchronous Enter state; independent of + // notifyChar/modifier latches and the gameswf Key listener event table. + gameswf::set_async_key_state_callback([](int) -> unsigned short { + return ::dice::hfe::macos::CocoaHost::instance().consumeAsyncEnterState(); + }); +#endif + // getSingleton("Bf2VoipClient") - the BF2.exe VoIP client (null in the harness). classManager // vslot +0x48. bf2_voip_client = static_cast( @@ -9312,18 +10382,74 @@ SwiffPlayer::SwiffPlayer() } -// Releases movie state, gameswf globals, and queued mouse storage. +// Releases the loaded movie with every script object it created and resets _global, so the next +// player starts from fresh script state, as a freshly mapped SwiffPlayer.dll does. Safe to call +// with no movie loaded. The movie library is kept: later players share its parsed definitions, +// which reference each other and would never be freed once dropped from it. The global steps run +// only when this is the only live player, so no other player's clips or _global are cleared. +// [CHOSEN, not recovered] issue #7 (https://github.com/B2BF/OpenBF2/issues/7): gameswf replaces the +// shipped player, and this teardown is ours. Script values form reference cycles between a movie's +// clips and objects, so dropping the instance alone frees nothing; release_script_objects breaks +// them first. +void SwiffPlayer::releaseMovie() +{ + gameswf::movie_interface* inst = static_cast(movie_instance); + gameswf::movie_definition* def = static_cast(movie_definition); + s_mainMenus.erase(inst); + movie_instance = 0; + movie_definition = 0; + const bool onlyPlayer = s_livePlayers == 1; + if (onlyPlayer) + gameswf::release_script_objects(); + if (inst) + inst->drop_ref(); + if (def) + def->drop_ref(); + if (onlyPlayer) + { + gameswf::action_clear(); + ::renddx9abi::logf("[SwiffPlayer] movie released (script objects and globals cleared)"); + } + else + { + std::fprintf(stderr, "SwiffPlayer: other player alive, globals kept (%d live)\n", s_livePlayers); + std::fflush(stderr); + ::renddx9abi::logf("SwiffPlayer: other player alive, globals kept (%d live)", s_livePlayers); + } +} + +// Releases movie state and gameswf globals; the queued mouse vector is destroyed as a member. SwiffPlayer::~SwiffPlayer() { // Shipped dtor also: sub_10071710 gameswf-global check, drops movie_definition/movie_instance - // via sub_1006F2A0, sub_10077700 gameswf AS/GC teardown, and a LocalProfileManager voip-volume - // save. All are movie/voip-state teardown; with both null here they are no-ops. [Stage 3] + // via sub_1006F2A0 and sub_10077700 gameswf AS/GC teardown; releaseMovie() is this build's movie + // and global teardown ([CHOSEN, not recovered], issue #7). + releaseMovie(); + // 0x10007030..0x100070A3: a voice test still looping back is ended, and the client's capture + // threshold goes back to the stored voice defaults (LocalProfileManager +0xA0, readVoiceSettings; + // threshold seeded 0.1f). + if (bf2_voip_client && static_cast(bf2_voip_client)->m_localLoopback) + { + BF2VoipClient* voip = static_cast(bf2_voip_client); + voip->setLocalLoopback(false); + IBase* lpm = classManager->getSingleton(renddx9abi::HostString("LocalProfileManager")); + if (lpm) + { + float playback, capture; + float threshold = 0.1f; + bool boost = false; + if (static_cast(lpm)->readVoiceSettings(playback, capture, threshold, boost)) + voip->setCaptureThreshold(threshold); // +0x14 + } + } + // [CHOSEN, not recovered] issue #7: cached native definitions can outlive + // this player. Their bitmap destructors must not call its dead handler. + if (gameswf::get_render_handler() == &render_handler) + gameswf::set_render_handler(NULL); + --s_livePlayers; // [CHOSEN, not recovered] issue #7, see releaseMovie voip_update_flag = 0; - if (queued_mouse_begin) - ::renddx9abi::engineFree(queued_mouse_begin); - queued_mouse_begin = queued_mouse_end = queued_mouse_capacity = 0; if (g_swiffPlayerInstance == this) g_swiffPlayerInstance = 0; @@ -9385,7 +10511,14 @@ void SwiffPlayer::initKeyTranslation() // frontier. bool SwiffPlayer::isMovieLoaded() { return movie_instance != 0; } -void SwiffPlayer::setRender(ISwiffRender* r) { render_context = r; } +void SwiffPlayer::setRender(ISwiffRender* r) +{ + // [CHOSEN, not recovered] Drop the old generated-image lease before changing + // registry. Cached descriptors will upload on their next use in this handler. + if (render_context != r) + render_handler.bitmap_registry.reset(); + render_context = r; +} ISwiffRender* SwiffPlayer::getRender() { return render_context; } void SwiffPlayer::setSwiffHost(ISwiffHost* h) { swiff_host = h; } ISwiffHost* SwiffPlayer::getSwiffHost() { return swiff_host; } @@ -9472,10 +10605,8 @@ void SwiffPlayer::setScale(float xScale, float yScale) rcSetScale(render_context, xScale, yScale); } -// loadMovie. Stage 3: parse + instance + push size, real. The bitmap-character walk -// (external images -> loadTexture) and the 27-namespace AS graph read dice-modified gameswf internals -// by raw offset and are deferred to Stage 5; the movie still parses, advances and renders its vector -// shapes without them. +// Parses and instances the movie, resolves its named image descriptors through +// the renderer, then publishes the ActionScript namespaces before advancing. bool SwiffPlayer::loadMovie(const char* movieName) { ISwiffHost* host = getSwiffHost(); @@ -9502,9 +10633,12 @@ bool SwiffPlayer::loadMovie(const char* movieName) rcSetMovieWidth(render_context, static_cast(movie_width)); rcSetMovieHeight(render_context, movie_height); - // DO_NOT_LOAD_BITMAPS - the documented host-texture policy, and the reason the shipped DLL - // links no zlib/jpeglib: menu bitmaps are never decoded, only named and resolved externally. - gameswf::set_default_create_bitmaps(gameswf::DO_NOT_LOAD_BITMAPS); + // SwiffPlayer.dll 0x1007D43A..0x1007D443 constructs with bitmap loading + // enabled. Gradient styles then take 0x100A43EF's generated-image path. + // [RETIRE-WHEN: swf-cached-bitmap-renderer-ownership] Generated descriptors + // now rebind through per-handler leases; retain this acceptance marker until + // real menu gradients and repeated reload/memory runs have been validated. + gameswf::set_default_create_bitmaps(gameswf::DO_LOAD_BITMAPS); gameswf::movie_definition* def = gameswf::create_library_movie(path); movie_definition = def; if (!def) @@ -9513,6 +10647,7 @@ bool SwiffPlayer::loadMovie(const char* movieName) return false; } gameswf::movie_interface* inst = def->create_instance(); + s_mainMenus.erase(static_cast(movie_instance)); movie_instance = inst; if (!inst) { @@ -9520,46 +10655,37 @@ bool SwiffPlayer::loadMovie(const char* movieName) return false; } - // Resolves every bitmap through the renderer using its copied export name, or "" - // for unnamed characters. Copy names from the export hash to avoid dangling c_str pointers. + // SwiffPlayer.dll 0x100062F1..0x1000634C resolves only named descriptors; + // Generated gradient/font descriptors are rebound separately when drawn. { - tu_string names[256]; - gameswf::bitmap_info* infos[256]; - const int n = def->get_exported_bitmaps(256, names, infos); const int total = def->get_bitmap_info_count(); - int resolved = 0, unnamed = 0; + int resolved = 0; for (int i = 0; i < total; ++i) { gameswf::bitmap_info* bi = def->get_bitmap_info(i); - if (!bi) continue; - const char* name = ""; - for (int k = 0; k < n; ++k) - if (infos[k] == bi) { name = names[k].c_str(); break; } - int tw = 0, th = 0; - const int handle = render_context ? rcLoadTexture(render_context, name, &tw, &th) : -1; - if (handle >= 0) - { - // The handle IS the texture; the bitmap_info carries nothing else (no pixels). - bi->m_texture_id = static_cast(handle); - bi->m_original_width = tw; - bi->m_original_height = th; - if (name[0]) ++resolved; else ++unnamed; - } - else if (name[0]) - { - ::renddx9abi::logf("[SwiffPlayer::loadMovie] loadTexture(\"%s\") failed", name); - } + if (!bi->is_named() || !render_context) continue; + gameswf::named_bitmap_info* named = static_cast(bi); + bi->m_texture_id = static_cast(rcLoadTexture(render_context, + named->m_name.c_str(), &bi->m_original_width, &bi->m_original_height)); + ++resolved; } - ::renddx9abi::logf("[SwiffPlayer::loadMovie] bitmaps: %d characters, %d named exports, " - "%d named resolved via loadTexture, %d unnamed given handles", - total, n, resolved, unnamed); + ::renddx9abi::logf("[SwiffPlayer::loadMovie] bitmaps: %d characters, " + "%d named submitted to loadTexture", total, resolved); } // Publish the ActionScript namespace graph before the movie's first advance. // Registration adapts the engine bindings to this gameswf version's fn_call ABI. buildAsGraph(); + // [CHOSEN, not recovered] Only this movie may complete an offline dialog request. + if (movieName && std::strcmp(movieName, "mainMenu.swf") == 0) + { + s_mainMenus.insert(inst); + ::renddx9abi::logf("[SwiffPlayer] offline Connect to IP policy: main-menu instance registered"); + } + ::renddx9abi::logf("[SwiffPlayer::loadMovie] returning true"); + SWF_LIST_TRACE("loadMovie '%s'", movieName ? movieName : ""); // [TEMP] c-swf-disconnect return true; } @@ -9603,7 +10729,7 @@ void SwiffPlayer::update(float deltaTime) // bridge consults before queuing a mouse press (sub_4A2D60/sub_4A2DD0 in BF2.exe); interactive run // drive10 lost every click after the multiplayer tab while mouse moves kept arriving. Logged on // change only, with the display count, so the AS lines around the flip name what set it. - if (swiff_host && asLogEnabled()) + if (swiff_host && mouseLogEnabled()) { static int s_busy = -1; const int busy = reinterpret_cast(rcVtbl(swiff_host)[696/4])(swiff_host); @@ -9620,8 +10746,7 @@ void SwiffPlayer::update(float deltaTime) // Mouse flush: the queued path if there is queued input or the deferred sample is already spent; // otherwise apply the deferred position once and mark it spent. - const bool haveQueued = queued_mouse_begin && - ((static_cast(queued_mouse_end) - static_cast(queued_mouse_begin)) / (int)sizeof(MouseState)) > 0; + const bool haveQueued = !queued_mouse.empty(); if (haveQueued || !deferred_mouse_dirty) { processQueuedMouseState(); // virtual, exactly as the shipped update dispatches it @@ -9635,6 +10760,10 @@ void SwiffPlayer::update(float deltaTime) gameswf::movie_interface* mi = static_cast(movie_instance); mi->set_display_viewport(0, 0, movie_width, movie_height); // typed (2006 4-arg) mi->advance(deltaTime); + // [CHOSEN, not recovered] Observe the authored request after its actions, + // before display. Neither cached loginStatus nor its native getter changes. + if (openOfflineConnectPopup(mi->get_root_movie(), s_mainMenus.count(mi) != 0)) + ::renddx9abi::logf("[SwiffPlayer] offline selectedPopup=connecttoip: selected authored popup frame (loginStatus=1)"); if (traceUpdate) // [TEMP] stream tracer ::renddx9abi::logf("[stream] viewport=(0,0,%d,%d) after advance: frame=%d/%d play=%d mouse=(%d,%d,%d)", movie_width, movie_height, mi->get_current_frame(), @@ -9642,7 +10771,7 @@ void SwiffPlayer::update(float deltaTime) (int)mi->get_play_state(), mouse_x, mouse_y, mouse_buttons); // Propagate the movie background color to the renderer each frame. - // [DICE-MOD] The movie interface exposes the background getter used by this bridge. + // The movie interface exposes the background getter used by this bridge. if (render_context) { const gameswf::rgba bg = mi->get_background_color(); @@ -9651,9 +10780,13 @@ void SwiffPlayer::update(float deltaTime) rcSetBackgroundColor(render_context, bgDword); } + // 0x100060D6..0x100060F1: outside a session the menu ticks the voice client's base frame (+0x64), + // which runs the voice test's loopback. if (voip_update_flag && bf2_voip_client) { - // VoIP tick (Stage 6). The shipped guard: if !voip->isBusy() then voip->tick(). + BF2VoipClient* voip = static_cast(bf2_voip_client); + if (!voip->isActive()) // +0x38 + voip->update(); // +0x64 } } @@ -9679,25 +10812,30 @@ void SwiffPlayer::display() s_streamCounts[7]); } -// push a mouse sample onto the +1104 vc71-shaped vector (grows on the engine heap). +// push a mouse sample onto the queued-mouse vector (+1104 in retail). void SwiffPlayer::queueMouseState(int x, int y, int buttons) { // [TEMP] RW-89 queue tracer (BF2_SWIFFPLAYER_ASLOG): every button change the engine queues and the // queue depth then, plus a depth line every 2000th sample - drive12 showed the host's input-block // flag flat at 0 while no press reached the movie after the multiplayer tab; this says whether the // engine still queues presses (starvation in our drain) or stopped calling (engine-side routing). - if (asLogEnabled()) + if (mouseLogEnabled()) { static int s_lastButtons = 0; static unsigned s_samples = 0; - const int depth = queued_mouse_begin ? (int)((static_cast(queued_mouse_end) - static_cast(queued_mouse_begin)) / (int)sizeof(MouseState)) : 0; + const int depth = (int) queued_mouse.size(); ++s_samples; if (buttons != s_lastButtons || (s_samples % 2000) == 0) - ::renddx9abi::logf("[mouse] queued buttons %d -> %d at (%d,%d) depth=%d sample#%u", s_lastButtons, buttons, x, y, depth, s_samples); + { + unsigned width = 0, height = 0; + if (swiff_host) + hostGetViewportSize(swiff_host, &width, &height); + ::renddx9abi::logf("[mouse] queued buttons %d -> %d at (%d,%d) depth=%d sample#%u hostViewport=%ux%u movie=%dx%d", + s_lastButtons, buttons, x, y, depth, s_samples, width, height, movie_width, movie_height); + } s_lastButtons = buttons; } MouseState ms; ms.x = x; ms.y = y; ms.buttons = buttons; - vc71::vectorRef q(&queued_mouse_aux); - q.push_back(ms); + queued_mouse.push_back(ms); } // text input (Stage 5): these dispatch through the host IME handler + write into a host std::string. @@ -9725,7 +10863,7 @@ static void swiffKeyDownLatch(int vkey) else if (vkey == 17) s_ctrlHeld = 1; else if (vkey == 20) s_capsToggle = (s_capsToggle == 0); // caps is a toggle, not a latch // The "IME handler" of the shipped latch IS the focused text field's +200 interface - // (dword_100F8EE0): its slot 0 takes the virtual key. [DICE-MOD #37] + // (dword_100F8EE0): its slot 0 takes the virtual key. gameswf::set_text_input_modifiers(s_shiftHeld != 0, s_altHeld != 0, s_ctrlHeld != 0, s_capsToggle != 0); if (gameswf::text_input* field = gameswf::get_focused_text_input()) field->on_key(vkey); @@ -9759,7 +10897,7 @@ void SwiffPlayer::notifyKeyState(int code, int down) } // 0x10006DB0 setTextInput: the host hands over clipboard text -> `src`, then the focused field's // paste (slot 2). 0x10006E30 / 0x10006E90 getTextInput0/1: the focused field's copy (slot 3) / cut -// (slot 4), then `src` is assigned into the host's PRE-constructed std::string. [DICE-MOD #37] +// (slot 4), then `src` is assigned into the host's PRE-constructed std::string. void SwiffPlayer::setTextInput(const char* text) { gameswf::text_input_clipboard() = text ? text : ""; @@ -9782,15 +10920,26 @@ void SwiffPlayer::getTextInput1(void* outStdString) } // render capability queries, guarded. -char SwiffPlayer::renderCapability0(int a) { return render_context ? rcCapability0(render_context, a) : 0; } -char SwiffPlayer::renderCapability1(int a) { return render_context ? rcCapability1(render_context, a) : 0; } +char SwiffPlayer::renderCapability0(intptr_t a) { return render_context ? rcCapability0(render_context, a) : 0; } +char SwiffPlayer::renderCapability1(intptr_t a) { return render_context ? rcCapability1(render_context, a) : 0; } // render pair-state, guarded. -void SwiffPlayer::renderSetPairState(int a, int b) +#if defined(_MSC_VER) +void SwiffPlayer::renderSetPairState(intptr_t a, int b) { if (render_context) rcSetPairState(render_context, a, b); } +#else +// [CHOSEN, not recovered] Native spelling of 0x10005F50: `cmp [ecx+0xC],0; je ret 8` else +// `jmp [vtbl+0xD4]` with the caller's two stack arguments, i.e. SwiffRender 0x10154E60 +// setTextureTechnique(const std::string&, int). +void SwiffPlayer::renderSetPairState(const std::string& textureName, int techniqueIndex) +{ + if (render_context) + rcSetPairState(render_context, textureName, techniqueIndex); +} +#endif // notify_mouse. Scales the raw (x,y) from the SwiffHost viewport into movie space, // clamps, feeds the movie and the renderer. @@ -9815,8 +10964,9 @@ void SwiffPlayer::notifyMouse(int x, int y, int buttons) // [TEMP] RW-89 mouse tracer (BF2_SWIFFPLAYER_ASLOG): every button transition the host delivers, // raw and in movie space - interactive run drive6 had an OK click that reached no handler and // the logs could not say whether the press ever arrived. [RETIRE-WHEN: RW-89] - if (asLogEnabled() && buttons != mouse_buttons) - ::renddx9abi::logf("[mouse] buttons %d -> %d at raw=(%d,%d) movie=(%d,%d)", mouse_buttons, buttons, x, y, mx, my); + if (mouseLogEnabled() && buttons != mouse_buttons) + ::renddx9abi::logf("[mouse] buttons %d -> %d at raw=(%d,%d) movie=(%d,%d) hostViewport=%ux%u movieSize=%dx%d", + mouse_buttons, buttons, x, y, mx, my, vpW, vpH, movie_width, movie_height); { // [TEMP] stream tracer: the host viewport the mouse scale is derived from (first 3 + full frames) static int s_n = 0; if (streamLogEnabled() && (++s_n <= 3 || s_streamVerbose)) @@ -9834,19 +10984,12 @@ void SwiffPlayer::notifyMouse(int x, int y, int buttons) // pop the front queued sample and deliver it. No-op when the queue is empty. void SwiffPlayer::processQueuedMouseState() { - if (!queued_mouse_begin) - return; - MouseState* begin = static_cast(queued_mouse_begin); - MouseState* end = static_cast(queued_mouse_end); - const int count = static_cast(end - begin); - if (count <= 0) + if (queued_mouse.empty()) return; - const MouseState front = begin[0]; + const MouseState front = queued_mouse.front(); // erase-front: shift the rest down one and retract end (the shipped sub_10007370). - for (int i = 1; i < count; ++i) - begin[i - 1] = begin[i]; - queued_mouse_end = static_cast(queued_mouse_end) - sizeof(MouseState); + queued_mouse.erase(queued_mouse.begin()); notifyMouse(front.x, front.y, front.buttons); } @@ -9855,9 +10998,37 @@ void SwiffPlayer::processQueuedMouseState() // Forwards gameswf rendering callbacks to the matching SwiffRender operations. // setRender and loadMovie must supply render_context before any callback; no null guards. +// The handler is always SwiffPlayer::render_handler, so its owner sits that member's offset below it. +ISwiffRender* SwiffRenderHandler::renderContext() +{ + SwiffPlayer* const owner = reinterpret_cast( + reinterpret_cast(this) - offsetof(SwiffPlayer, render_handler)); + return owner->render_context; +} + +// [CHOSEN, not recovered] Cached definitions share pixels, never registry IDs. +const std::shared_ptr& SwiffRenderHandler::bitmapRegistry() +{ + if (!bitmap_registry) + bitmap_registry = std::make_shared(renderContext()); + return bitmap_registry; +} + +void SwiffRenderHandler::bindBitmap(const gameswf::bitmap_info* bitmap) +{ + if (bitmap && bitmap->m_render_resource) + SwiffBitmapRegistry::bind(const_cast(bitmap), bitmapRegistry()); +} + +// SwiffPlayer.dll 0x10005CE0: forward to ISwiffRender +0x40 unchanged. +void SwiffRenderHandler::set_depth(int depth) +{ + renderContext()->recordStat(depth); +} + namespace { inline void* rhRc(SwiffRenderHandler* self) -{ return *reinterpret_cast(reinterpret_cast(self) + 8); } +{ return self->renderContext(); } inline unsigned rgbaDword(const gameswf::rgba& c) { unsigned d; ::memcpy(&d, &c, 4); return d; } } // anonymous namespace @@ -9870,38 +11041,44 @@ gameswf::bitmap_info* SwiffRenderHandler::create_bitmap_info_empty() gameswf::bitmap_info* SwiffRenderHandler::create_bitmap_info_alpha(int w, int h, unsigned char* data) { gameswf::bitmap_info* bi = new gameswf::bitmap_info(); - bi->m_texture_id = static_cast(rcUploadAlpha(rhRc(this), (unsigned)w, (unsigned)h, data)); bi->m_original_width = w; bi->m_original_height = h; + // [CHOSEN, not recovered] Preserve generated font pixels for cached reloads. + bi->m_render_resource.reset(new SwiffBitmapPixels(SwiffBitmapPixels::Alpha, w, h, w, data)); + bindBitmap(bi); return bi; } +// 0x10005AE0: a NULL image answers NULL before anything is allocated (0x10005AED..0x10005AFE); +// otherwise the dimensions are stored before the renderer call (0x10005B42..0x10005B4E). gameswf::bitmap_info* SwiffRenderHandler::create_bitmap_info_rgb(image::rgb* im) { + if (!im) + return 0; gameswf::bitmap_info* bi = new gameswf::bitmap_info(); + bi->m_original_width = im->m_width; + bi->m_original_height = im->m_height; bi->m_texture_id = static_cast(rcCreateRgb(rhRc(this), im)); - if (im) { bi->m_original_width = im->m_width; bi->m_original_height = im->m_height; } return bi; } gameswf::bitmap_info* SwiffRenderHandler::create_bitmap_info_rgba(image::rgba* im) { gameswf::bitmap_info* bi = new gameswf::bitmap_info(); - bi->m_texture_id = static_cast(rcUploadRgba(rhRc(this), im)); - if (im) { bi->m_original_width = im->m_width; bi->m_original_height = im->m_height; } + // SwiffPlayer.dll 0x10005BC1..0x10005BD6 stores dimensions before upload. + bi->m_original_width = im->m_width; + bi->m_original_height = im->m_height; + // [CHOSEN, not recovered] Keep canonical RGBA before RendDX9 swaps channels. + bi->m_render_resource.reset(new SwiffBitmapPixels(SwiffBitmapPixels::Rgba, + im->m_width, im->m_height, im->m_pitch, im->m_data)); + bindBitmap(bi); return bi; } -// The shipped slot-5 forwarder: create_bitmap_info_file(path, &w, &h) -> ISwiffRender::loadTexture -// (+0x28). The handle IS the texture; a failed resolve (-1) is "no image", which the loadMovie -// image loader treats as nothing to place. +// SwiffPlayer.dll 0x10005BF0: allocate first, then keep the renderer's handle +// and both dimensions, including a failure handle. The descriptor is returned. gameswf::bitmap_info* SwiffRenderHandler::create_bitmap_info_file(const char* path) { + gameswf::bitmap_info* bi = new (std::nothrow) gameswf::bitmap_info(); int w = 0, h = 0; - const int handle = rcLoadTexture(rhRc(this), path ? path : "", &w, &h); - if (handle < 0) - { - ::renddx9abi::logf("[SwiffPlayer] create_bitmap_info_file(\"%s\") - loadTexture failed", path ? path : ""); - return 0; - } - gameswf::bitmap_info* bi = new gameswf::bitmap_info(); + const int handle = rcLoadTexture(rhRc(this), path, &w, &h); bi->m_texture_id = static_cast(handle); bi->m_original_width = w; bi->m_original_height = h; @@ -9909,9 +11086,8 @@ gameswf::bitmap_info* SwiffRenderHandler::create_bitmap_info_file(const char* pa } void SwiffRenderHandler::delete_bitmap_info(gameswf::bitmap_info* bi) { - // Release the render texture; gameswf's ref-counting frees the bitmap_info object itself. - if (bi) - rcReleaseTexture(rhRc(this), static_cast(bi->m_texture_id)); + // SwiffPlayer.dll 0x10005C80: release the handle without a null guard. + rcReleaseTexture(rhRc(this), static_cast(bi->m_texture_id)); } void SwiffRenderHandler::begin_display(gameswf::rgba background_color, int vx0, int vy0, int vw, int vh, @@ -9986,6 +11162,7 @@ void SwiffRenderHandler::fill_style_color(int fill_side, gameswf::rgba color) void SwiffRenderHandler::fill_style_bitmap(int fill_side, const gameswf::bitmap_info* bi, const gameswf::matrix& m, bitmap_wrap_mode wm) { + bindBitmap(bi); // [CHOSEN, not recovered] The current handler owns the upload. const int texId = bi ? static_cast(bi->m_texture_id) : 0; const int w = bi ? bi->m_original_width : 0; const int h = bi ? bi->m_original_height : 0; @@ -10008,6 +11185,7 @@ void SwiffRenderHandler::draw_bitmap(const gameswf::matrix& m, const gameswf::bi const gameswf::rect& coords, const gameswf::rect& uv_coords, gameswf::rgba color) { + bindBitmap(bi); // [CHOSEN, not recovered] Also covers cached glyph bitmaps. // Shipped forwarder targets SwiffRender +0x64, which is a nullsub - the menu uses the font-wrapper // path (Stage 5) for textured glyphs, not draw_bitmap. Forwarded for fidelity; lands on the no-op. const int texId = bi ? static_cast(bi->m_texture_id) : 0; @@ -10029,7 +11207,7 @@ void SwiffRenderHandler::end_submit_mask() void SwiffRenderHandler::disable_mask() { SPL("[stream] disable_mask"); rcDisableMask(rhRc(this)); } -// [DICE-MOD SwiffPlayer #36] The twelve text slots. Each shipped forwarder is `mov ecx,[ecx+8]; mov +// The twelve text slots. Each shipped forwarder is `mov ecx,[ecx+8]; mov // eax,[ecx]; jmp [eax+off]` except two that convert an out-parameter (0x10005E20 hit test: the // renderer writes the position into a stack copy of the last argument, the forwarder stores it through // the pointer; 0x10005E50 selection: two locals, two stores). @@ -10066,9 +11244,14 @@ bool SwiffRenderHandler::text_extent(void* line, int count, float* w, float* h) SPLA("[stream] text_extent(%p, %d) -> %d w=%.1f h=%.1f", line, count, ok ? 1 : 0, w ? *w : -1.f, h ? *h : -1.f); // [TEMP] RW-89 return ok; } -bool SwiffRenderHandler::text_hit(void* line, int* outPos, int x, int y) +// 0x10005E20: the out slot is the forwarder's own y argument slot (`lea edx,[ebp+0x14]`), so +// it starts as y's bit pattern and is copied to *outPos unconditionally after SwiffRender +0x80 +// (0x10005E3E..0x10005E44). gameswf reads it only on a hit (0x100887DC). +bool SwiffRenderHandler::text_hit(void* line, int* outPos, float x, float y) { - int pos = y; // the shipped forwarder's stack copy of the last argument + int pos; + static_assert(sizeof(pos) == sizeof(y), "the shipped out slot is y's 32-bit stack slot"); + ::memcpy(&pos, &y, sizeof(pos)); const bool hit = rcTextHit(rhRc(this), line, &pos, x, y) != 0; if (outPos) *outPos = pos; return hit; @@ -10080,11 +11263,12 @@ bool SwiffRenderHandler::text_selection(void* line, int* a, int* b) if (a) *a = va; if (b) *b = vb; // The render context's AL is the answer the field's delete_selection (sub_10088D60) tests - // before it deletes [start, end): with "no selection" the outs are meaningless. [DICE-MOD #46] + // before it deletes [start, end): with "no selection" the outs are meaningless. return has; } -bool SwiffRenderHandler::text_set_selection(void* line, int a, int b, int c, int d) -{ return rcTextSetSelection(rhRc(this), line, a, b, c, d) != 0; } +// 0x10005E90 (`jmp [vtbl+0x88]`): the four float dwords pass through unchanged. +bool SwiffRenderHandler::text_set_selection(void* line, float x1, float y1, float x2, float y2) +{ return rcTextSetSelection(rhRc(this), line, x1, y1, x2, y2) != 0; } void SwiffRenderHandler::text_blur(void* line) { rcTextBlur(rhRc(this), line); } void SwiffRenderHandler::text_set_size(void* line, float size, int flag) { diff --git a/Code/BF2/External/gameswf/SwiffPlayer/SwiffPlayer.h b/Code/BF2/External/gameswf/SwiffPlayer/SwiffPlayer.h index 1a608292b..62bb700d6 100644 --- a/Code/BF2/External/gameswf/SwiffPlayer/SwiffPlayer.h +++ b/Code/BF2/External/gameswf/SwiffPlayer/SwiffPlayer.h @@ -6,6 +6,10 @@ #ifdef BF2_IMAGE_SWIFFPLAYER +#include +#include +#include + // gameswf_types.h defines gameswf::rgba (passed BY value in several render_handler methods, so the // overrides' definitions need the complete type) and transitively includes gameswf.h, which brings // gameswf::render_handler - the +4 subobject's base. matrix/cxform/rect/bitmap_info/image::* are used @@ -13,6 +17,10 @@ #include "gameswf/gameswf_types.h" #include "../../../../RendDX9Abi/HfeAbi.h" // dice::hfe::IBase #include "../../../../RendDX9Abi/Frontier.h" +#if !defined(_MSC_VER) +// [CHOSEN, not recovered] One native declaration for host and plugin dispatch. +#include "../../../Menu/ISwiffPlayer.h" +#endif namespace dice { namespace hfe { @@ -37,6 +45,7 @@ enum { CID_Swiff = 870002u, IID_ISwiffPlayer = 870001u }; // layout declaration; SwiffPlayer.cpp provides dispatch and the remaining named frontiers. struct ISwiffRender; struct ISwiffHost; +class SwiffBitmapRegistry; // Embedded renderer adapter forwarding gameswf callbacks through SwiffRender's interface. @@ -46,16 +55,20 @@ struct SwiffRenderHandler : public gameswf::render_handler { SwiffRenderHandler() {} - // NO data members - the subobject is exactly 4 bytes (its vtable ptr), matching the shipped - // layout (object is 1120 bytes). A Stage-3 forwarder reaches render_context the way the shipped - // code does: this subobject sits at object+4 and render_context at object+12, so the owner is - // reinterpret_cast((char*)this - 4). No back-pointer member is stored. + // [CHOSEN, not recovered] Generated textures belong to this player's lease; + // cached definitions retain CPU pixels after the lease is destroyed. + std::shared_ptr bitmap_registry; + const std::shared_ptr& bitmapRegistry(); + void bindBitmap(const gameswf::bitmap_info* bitmap); + + // The owning SwiffPlayer's render_context. + ISwiffRender* renderContext(); virtual gameswf::bitmap_info* create_bitmap_info_empty(); virtual gameswf::bitmap_info* create_bitmap_info_alpha(int w, int h, unsigned char* data); virtual gameswf::bitmap_info* create_bitmap_info_rgb(image::rgb* im); virtual gameswf::bitmap_info* create_bitmap_info_rgba(image::rgba* im); - // [DICE-MOD] the 2004 slot-5 by-name loader, restored on the 2006 base: -> ISwiffRender::loadTexture + // the 2004 slot-5 by-name loader, restored on the 2006 base: -> ISwiffRender::loadTexture virtual gameswf::bitmap_info* create_bitmap_info_file(const char* path); virtual void delete_bitmap_info(gameswf::bitmap_info* bi); virtual void begin_display(gameswf::rgba background_color, @@ -65,6 +78,7 @@ struct SwiffRenderHandler : public gameswf::render_handler virtual void end_display(); virtual void set_matrix(const gameswf::matrix& m); virtual void set_cxform(const gameswf::cxform& cx); + virtual void set_depth(int depth); virtual void draw_mesh_strip(const void* coords, int vertex_count); virtual void draw_line_strip(const void* coords, int vertex_count); virtual void fill_style_disable(int fill_side); @@ -93,9 +107,9 @@ struct SwiffRenderHandler : public gameswf::render_handler virtual void text_detach(void* line); // 24 -> +0x74 virtual void text_draw(void* line, const gameswf::matrix* m, unsigned color, int flags); // 25 -> +0x78 virtual bool text_extent(void* line, int count, float* w, float* h); // 26 -> +0x7C - virtual bool text_hit(void* line, int* outPos, int x, int y); // 27 -> +0x80 + virtual bool text_hit(void* line, int* outPos, float x, float y); // 27 -> +0x80 (0x10005E20: float x/y) virtual bool text_selection(void* line, int* a, int* b); // 28 -> +0x84 (AL = has selection) - virtual bool text_set_selection(void* line, int a, int b, int c, int d); // 29 -> +0x88 + virtual bool text_set_selection(void* line, float x1, float y1, float x2, float y2); // 29 -> +0x88 (0x10005E90: jmp, floats) virtual void text_blur(void* line); // 30 -> +0x8C virtual void text_set_size(void* line, float size, int flag); // 31 -> +0x90 virtual void text_caret(void* line, int pos); // 32 -> +0x94 @@ -107,6 +121,7 @@ struct SwiffRenderHandler : public gameswf::render_handler // BF2.exe dispatches into it by raw byte offset (initMainMenuSwiff), so the declaration order here // must never change. +#if defined(_MSC_VER) class ISwiffPlayer : public IBase { public: @@ -152,15 +167,15 @@ class ISwiffPlayer : public IBase // 23 +0x5C virtual ISwiffHost* getSwiffHost() = 0; // 24 +0x60 - virtual char renderCapability0(int a) = 0; + virtual char renderCapability0(intptr_t a) = 0; // 25 +0x64 - virtual char renderCapability1(int a) = 0; + virtual char renderCapability1(intptr_t a) = 0; // 26 +0x68 virtual int getMovieWidth() = 0; // 27 +0x6C virtual int getMovieHeight() = 0; // 28 +0x70 - virtual void renderSetPairState(int a, int b) = 0; + virtual void renderSetPairState(intptr_t a, int b) = 0; // a: the texture name's address // 29 +0x74 virtual void legacyModeOff() = 0; // 30 +0x78 @@ -181,12 +196,13 @@ class ISwiffPlayer : public IBase protected: ~ISwiffPlayer() {} }; +#endif -// SwiffPlayer - the 1120-byte object. Member order and offsets match the IDB local type -// dice_hfe_SwiffPlayer_BF2 exactly; static_asserts in the .cpp hold the size and the load-bearing -// offsets. The ISwiffPlayer base supplies the +0 vtable; the SwiffRenderHandler member supplies the -// +4 one. +// SwiffPlayer - member order matches the IDB local type dice_hfe_SwiffPlayer_BF2 (the retail object +// is 1120 bytes; the +N comments are its offsets). The queued-mouse storage is a std::vector +// (https://github.com/B2BF/OpenBF2/issues/7), so the native object's size differs from retail. The +// ISwiffPlayer base supplies the +0 vtable; the SwiffRenderHandler member supplies the +4 one. class SwiffPlayer : public ISwiffPlayer { @@ -217,15 +233,28 @@ class SwiffPlayer : public ISwiffPlayer virtual void notifyKeyState(int code, int down); virtual void resetModifierState(); virtual void setTextInput(const char* text); +#if !defined(_MSC_VER) + // [CHOSEN, not recovered] Native images share the host declaration. The + // clipboard bodies keep their opaque storage helpers behind these adapters. + virtual void getTextInput0(std::string& out) override { getTextInput0(static_cast(&out)); } + virtual void getTextInput1(std::string& out) override { getTextInput1(static_cast(&out)); } + void getTextInput0(void* outStdString); + void getTextInput1(void* outStdString); +#else virtual void getTextInput0(void* outStdString); virtual void getTextInput1(void* outStdString); +#endif virtual void setSwiffHost(ISwiffHost* host); virtual ISwiffHost* getSwiffHost(); - virtual char renderCapability0(int a); - virtual char renderCapability1(int a); + virtual char renderCapability0(intptr_t a); + virtual char renderCapability1(intptr_t a); virtual int getMovieWidth(); virtual int getMovieHeight(); - virtual void renderSetPairState(int a, int b); +#if defined(_MSC_VER) + virtual void renderSetPairState(intptr_t a, int b); +#else + virtual void renderSetPairState(const std::string& textureName, int techniqueIndex); +#endif virtual void legacyModeOff(); virtual void legacyModeOn(); virtual char getModeFlag(); @@ -236,8 +265,16 @@ class SwiffPlayer : public ISwiffPlayer virtual void setVoipUpdateFlag(char v); private: + // A queued mouse sample (12 bytes), the element of the queued-mouse vector. + struct MouseState { int x; int y; int buttons; }; + void initKeyTranslation(); // SwiffPlayer_initKeyTranslation 0x10005410 + // Drops the movie instance and definition, every script object and _global. + // [CHOSEN, not recovered] issue #7; see the definition. + void releaseMovie(); + // Offsets below describe retail x86 fields. Native layout is compiler-owned; + // the cached-image lease adds state to the embedded handler. // +4 - the embedded render handler. gameswf holds a pointer to it via set_render_handler. SwiffRenderHandler render_handler; // +8 @@ -281,12 +318,10 @@ class SwiffPlayer : public ISwiffPlayer // +1100 (+3 pad) unsigned char legacy_flag_44c; unsigned char pad_44d[3]; - // +1104..+1116 - the queued-mouse vector (aux/begin/end/capacity), grown on the engine heap. - void* queued_mouse_aux; - void* queued_mouse_begin; - void* queued_mouse_end; - void* queued_mouse_capacity; + // +1104 - the queued mouse samples (retail: a 16-byte VC7.1 vector). + std::vector queued_mouse; + friend struct SwiffRenderHandler; // renderContext() reaches render_context friend IBase* __fastcall RefFactory_ui_SwiffPlayer(unsigned int iid, IBase* parent); }; diff --git a/Code/BF2/External/gameswf/SwiffPlayer/SwiffPlayerModule.cpp b/Code/BF2/External/gameswf/SwiffPlayer/SwiffPlayerModule.cpp index 9edcb912a..c60bde5e4 100644 --- a/Code/BF2/External/gameswf/SwiffPlayer/SwiffPlayerModule.cpp +++ b/Code/BF2/External/gameswf/SwiffPlayer/SwiffPlayerModule.cpp @@ -9,7 +9,6 @@ #include "../../../../RendDX9Abi/HfeAbi.h" #include "../../../../RendDX9Abi/BfMemory.h" -#include "../../../../RendDX9Abi/Vc71Vector.h" namespace dice { namespace hfe { @@ -75,20 +74,39 @@ void SwiffModule::getSingletonList(RD9_HOST_VECTOR_PARAMETER(SingletonRegInfo, / // static_cast(this) yields. namespace { +#if !defined(_MSC_VER) +// [CHOSEN, not recovered] These two ordinals precede EventManager's destructor; +// tools/macos/vtable_audit.py checks them against Clang's provider table. +constexpr unsigned nativeEventRegisterSlot = 11; +constexpr unsigned nativeEventUnregisterSlot = 12; +typedef bool (*EmRegisterFn)(void*, EventCategory, IEventListener*, int); +typedef bool (*EmUnregisterFn)(void*, EventCategory, IEventListener*); +#else typedef int (__thiscall* EmRegisterFn) (void* self, int category, void* handler, int priority); typedef int (__thiscall* EmUnregisterFn)(void* self, int category, void* handler); +#endif inline void eventManagerRegister(int category, void* handler, int priority) { void* em = eventManager; void** vtbl = *reinterpret_cast(em); +#if !defined(_MSC_VER) + reinterpret_cast(vtbl[nativeEventRegisterSlot])( + em, static_cast(category), static_cast(handler), priority); +#else reinterpret_cast(vtbl[0x2C / 4])(em, category, handler, priority); +#endif } inline void eventManagerUnregister(int category, void* handler) { void* em = eventManager; void** vtbl = *reinterpret_cast(em); +#if !defined(_MSC_VER) + reinterpret_cast(vtbl[nativeEventUnregisterSlot])( + em, static_cast(category), static_cast(handler)); +#else reinterpret_cast(vtbl[0x30 / 4])(em, category, handler); +#endif } } // anonymous namespace @@ -142,6 +160,18 @@ IModule* dllmodules[] = 0 }; +#if defined(BF2_STATIC_PLUGINS) +// [CHOSEN, not recovered] The statically linked image's "reload" (Code/StaticPlugins/StaticPlugins.h): +// deinitDll released the module and nulled its slot; a fresh SwiffPlayer.dll mapping would run the +// table's initializer again, so the slot gets a new module before the next initDll. The other image +// statics (gameswf globals, the key-state bytes) are not reset. +extern "C" void bf2_swiffplayer_reloadImage() +{ + if (!dllmodules[0]) + dllmodules[0] = new ui::SwiffModule(); +} +#endif + } // namespace hfe } // namespace dice diff --git a/Code/BF2/External/gameswf/SwiffPlayer/SwiffPlayerModule.h b/Code/BF2/External/gameswf/SwiffPlayer/SwiffPlayerModule.h index 67c91d11b..6a5b8e8a5 100644 --- a/Code/BF2/External/gameswf/SwiffPlayer/SwiffPlayerModule.h +++ b/Code/BF2/External/gameswf/SwiffPlayer/SwiffPlayerModule.h @@ -11,6 +11,10 @@ #ifdef BF2_IMAGE_SWIFFPLAYER #include "../../../../RendDX9Abi/HfeAbi.h" +#if !defined(_MSC_VER) +// [CHOSEN, not recovered] Native callbacks use the host's pointer-sized event arguments. +#include "../../../Game/IEventListener.h" +#endif namespace dice { namespace hfe { @@ -19,9 +23,21 @@ namespace ui { // The one-slot event interface, the same shape RendDX9's ModuleGeom carries (PluginModules.h): the // EventManager pushes four dwords, the handler tests the first two - (category, id). A local copy // rather than a shared one so the SwiffPlayer image does not depend on the RendDX9 module headers. +#if !defined(_MSC_VER) +class ECCoreEventHandler : public ::dice::hfe::IEventListener +#else class ECCoreEventHandler +#endif { public: +#if !defined(_MSC_VER) + // [CHOSEN, not recovered] Both module bodies inspect only category and id. + // Preserve their recovered helper while publishing the actual host callback. + void handleEvent(EventCategory category, unsigned int id, EventNode*, void*) override + { + handleCoreModuleEvent(static_cast(category), static_cast(id), 0, 0); + } +#endif virtual void handleCoreModuleEvent(int category, int id, int a3, int a4) = 0; // +0x00 protected: diff --git a/Code/BF2/External/gameswf/TODO b/Code/BF2/External/gameswf/TODO deleted file mode 100644 index 6f17633e5..000000000 --- a/Code/BF2/External/gameswf/TODO +++ /dev/null @@ -1,384 +0,0 @@ -Bugs -==== - -* there's a pop when transitioning from textured to mesh-rendered - glyphs; probably the texture fonts aren't registered exactly right? - - -Productizing -============ - -Tasks to make gameswf ready for including in real games. - -* pick a version number, post a release - -* reduce small allocs, flatten data structures - -* for data binding, we have: - - gameswf-push (fscommand) - host-push (call_method, set_variable) - host-pull (call_method, get_variable) - - we are missing gameswf-pull. This would be useful for things like - looking up localized text in the game engine's translation table, - among other things. - -* fix/finish precompute_cached_data() - -* flags to strip extraneous stuff from a SWF source stream. - I.e. remove all bitmap data, font shape outlines, etc. This is - useful for apps that precompile the bitmaps into native formats and - hook them up at runtime via get_bitmap_info()->... . Lets the - stripped stream be used for parsing the rest of the movie info, - without taking up extra space/bandwidth. - -* fontlib support, for explicitly letting the host define global fonts - that all SWF's can use - -* put a FAQ on the web - -General -======= - -* implement host-app driven text rendering functions - -* implement some or all of the HTML-like layout tags in dynamic text - fields - -* sprites as button characters are not working. (Maybe they are - now??) - -* host-to-gameswf data transfer: - - * DONE set_variable - - * maybe augment this with array element parsing, and more data types? - - * Should the whole ActionScript API be available to the host? - I.e. let C++ host code and ActionScript code call back and forth? - Might be really hot for translating slow prototype ActionScripts - into C++. Prototype in Flash on a fast machine, convert the - scripts and deliver a blazing fast executable. - -* Helpers for arbitrary tag-processing - -* Would be good if one of the log options produced a nice usable - human-readable parsing of the file. Or even a SSWF equivalent? - -* write GAMESWF_FONT_GLYPH_FINAL_SIZE into the font cache data, and - check it on read to make sure it matches. If no match, log error - (and ignore data???) If these mismatch, then glyphs get rendered - with the wrong size, and it's non-obvious why. - -* User request: implement SWF files recursively calling other SWF - files. Low priority; there are workarounds. - -ActionScript -============ - -* bug: - - onEnterFrame should get called even when sprite is stopped - -* bug: - - // e.g. declared inside main movie frame 1, - // and we have a movie clip w/ instance named "instance" - function instance.some_method() - { - // "this" must refer to "instance", not the main movie! - // currently gameswf refers to the main movie. - this._visible = false; - } - -* bug: - - // In single-frame movies, the frame 1 actions should execute only once. - // The same actions in a two-frame movie should execute continuously. - -* bug: - - // If we have a dynamic text instance "inst" that contains a string, - // doing to_string() or to_tu_string() on it should return its string - // contents, not "" or whatever we do now. - -* bug: - - // In Flash, _visible property returns "true" or "false" when - // converted to string. gameswf returns "0" or "1". In general, - // gameswf probably needs a specific as_value::BOOL type, instead - // of using as_value::NUMBER for booleans. - -* all event hooks - -* arrays, object constructors - -* sprites can receive button events! Like mouse down/up, etc. So - need the appropriate machinery for watching the mouse. - -* make sure the frame semantics are correct. I'm not 100% clear on - the semantics of frame transitions. I think that "being on frame N" - means that N's tags and actions have been executed. - -* collect a canonical set of test movies and check them into CVS - -* generate or collect some game-gui-like movies - -* will need some good test programs to make sure VM is doing the right - thing. SET UP AUTOMATED REGRESSION TESTS -- can be a shell script - that runs test movies in verbose mode and compares ActionScript - logging against expected output. - -* implement remaining opcodes and library functions - -* _global - - -Renderer -======== - -* fix the few tesselator glitches - -* optimize tesselator (not super-high priority, caching works pretty - well) - - * improve naive (mis)use of array<>; use a more statically-allocated - array to hold intermediate results. - - * examine use of qsort; should probably use pointers to stuff in - some situations, instead of raw copies - - * coarse clip/cull - - * better tesselation; look at Shewchuck's constrained delaunay stuff - or the improved trapezoid tesselator that doesn't cut across the - whole shape - -* real lines (low priority) - - I think the way to handle this is to take advantage of a (mipmapped) - circle texture, say 16x16, and actually draw rectangles. But then - it still doesn't seem too easy to get right. Needs more thinking. - Not a super high priority; doesn't seem to be a critical feature for - most movies. - - Update: designers do use lines. (But Flash MX does have a feature - that turns lines into shapes.) The circle texture, connected by - polys seems like the way to go. The interior of acute angles is - still tricky though. But it can definitely be done. Something like - this: - - ----- - -/ \- <--- edge of circle texture - / use \ - /\ circle /\ - / \ tex / \ - / \ here/ \ - / \ / \ - / \ / \ - / o \ - / | \ o - / | \ - / use | use \ - / tris for /\ tris for \ - / this / \ this \ - / / \ \ - / / \ \ - / / \ \ - / \ \ - / \ \ - / \ \ - - -* Idea for antialiasing. I really miss antialiasing; it sure would be - nice to have it. (But this is low priority for productizing; it - should be easy enough for designers to work around gameswf's - limitations.) So here's the idea: - - * do full-blown expensive cached tesselation, to generate a "fringe - mesh" around the outside edges of shapes. We know the range of - desired rendering sizes (in pixels), so we can make a fringe mesh - that will range from 1 to 2 pixels in width when rendered. I - believe this involves shrinking the interior of the mesh by the - equivalent of a half-pixel. - - * render the mesh using the dual-textured modulate thing, to fade - the edge. Adjust the U coordinates of the outer edge of the - fringe according to the actual size in pixels of the fringe; - i.e. if the fringe is being rendered at 1.27 pixels in size, - adjust U so that the alpha fades to exactly 0 when the fringe is - 1.0 pixel from the interior; the excess fringe has alpha == 0 so - doesn't render. - - This sounds pretty foolproof to me. It's expensive in terms of - precomputation, but then we have all this precomputation machinery - anyway, so no big deal. There could possibly be a pop when - tesselations switch, although I don't think it would be any worse - than existing pops, and I haven't noticed any objectionable popping - with our existing shape rendering. - - Self-intersection of the expanded/shrunk mesh is a bitch. - E.g. concave vertices, and tiny holes (like in minified text). - - Reasons not to mess with this: - - * sounds like a bunch of work - - * non-antialiased rendering on Xbox does not look that bad. - - * hardware keeps getting better; could just turn on multisample - rendering - - * artists can work around it - -* Instead of using textured lines we could compute the antialiasing - gradients analitically, although it requires a simple fragment - program and some per-edge computations: - - http://graphics.csail.mit.edu/~ericchan/articles/prefilter/ - -* Antialiasing using destination alpha and the edge-coverage alpha - feature that's commonly available: - - * turn on edge antialiasing; basically this causes the rasterizer to - generate a source alpha value corresponding to the coverage of the - primitive on each pixel. So, edge pixels get a fractional alpha - value. - - (This feature has been around for a long time on various different - hardware, under GL_POLYGON_SMOOTH; the big problem with it is that - the obvious blend mode (SRC_ALPHA, ONE_MINUS_SRC_ALPHA) doesn't - work right. Internal edges are slightly transparent, and that - just looks like crap. A common hack is to draw an opaque version - of the mesh over the antialiased version; the problem with that - trick is it overdraws the darker 50% of the antialiasing, so it - only looks somewhat better -- still fairly jaggy. The Red book - mentions (GL_SRC_ALPHA_SATURATE, GL_ONE) which works correctly if - you're drawing opaque, sorted front-to-back. But for transparency - effects, we must draw back-to-front, so this is incompatible.) - - * Clear destination alpha, then draw into destination alpha only, - using an additive blend. This makes a nice antialiased mask of - our shape. - - * Draw a quad over the shape bounding box, with the desired fill - mode, using (DST_ALPHA, ONE_MINUS_DST_ALPA). The parts with - non-zero alpha will get filled/blended with the shape fill. - - This works; there's a proof-of-concept (but artifacty) implemention, - #ifdef'd out in gameswf_render_handler_ogl.cpp - - NOTE: this makes thick/thin line drawing much easier, since overdraw - can be tolerated -- just draw quads for the edges, and circles (or - semicircles) for the verts, all into the alpha buffer. Overdraw of - the quads on the interior of angles is no problem, since things - drawn multiple times just saturate. Then fill the bounding box, - modulating with dest alpha, as usual. - -* Idea: alternative polygon rendering method, without requiring any - true poly triangulation: use two-sided lighting to repeatedly - add/subtract signed-area triangles into the stencil buffer. - - OK, in more words: the idea is a procedure similar to the polygon - signed-area test, where you pick an arbitrary reference point in the - plane, and for each edge in the polygon, compute the signed area of - the triangle formed by the reference point and the edge. Total up - the signed areas, and that gives you the polygon area. For a - general polygon, some of the edges are "back-facing" with respect to - the reference point; those triangles subtract out the extra area - added by the triangles that are "front-facing" with respect to the - reference point. - - So anyway, we exploit that same idea, but render the triangles - instead of computing their area. Front-facing triangles add into - the stencil buffer, while back-facing triangles subtract from the - stencil buffer. The result should be 1's in the stencil buffer - where the poly should be filled, and 0's where is shouldn't. - - NOTES: - - * Stencil overflow, for very convoluted polys, should not matter. - You can overflow as much as you want, but the final result will - always be in the range [0,1]. So as long as you have modulo - arithmetic, and at least one bit of stencil, you're OK. Correct? - - * Those very convoluted polys mentioned above could create excessive - overdraw. E.g. let's say you have a very thin line that spirals - around dozens of times, surrounding a big empty area. Could be - murderous on fill rate. One possibility here would be to somehow - recognize bad cases, and subdivide the poly, and render each piece - independently with a local reference point. Recognizing the bad - case could be difficult. Maybe do some kind of - cheap/partial/sloppy convex decomposition of the poly, to get the - parts. - - * In theory, this would work fantastically great in combination with - the edge-antialiasing thing mentioned above, IF there were a way - to do the alpha blending using values in the stencil buffer (could - always copy stencil to alpha, but that starts to sound - expensive!), OR some way to enable modulo arithmetic in - destination alpha, and a way to pass a negative alpha values (for - the negative-area triangles). - - * I'm sure someone has mentioned this idea somewhere, need to look - for more info. - -* Idea: render filled quadratic beziers DIRECTLY, without any - tesselation, nor any subdividing of curves. This works essentially - the same way as the above signed-area thing for poly rendering, plus - a special rendering of the curved segments: - - * take a reference point x - - * for each quadratic bezier curved segment (a0, c, a1) (the a's are - "anchor" points; the c is a "control" point), we render the signed - triangle (x, a0, a1) as above. We also render (a0, c, a1) with a - special shader (this can also be done easily in the fixed-function - pipe with a square alpha texture made up of a quarter-circle). - The texture or shader function looks like: - - a1 c - +---------------------+ - ...... 0 out here | - | .... | - | ... | - | .. | - | . | - | .. | - | . | - | . | - | 1 in here . | - | . | - | . | - | .| - | .| - o--------------------.+ a0 - - So this quarter-circular texture (or simple shader function) - determines the stencil/alpha value to add into the render target. - We get 1's inside the shape, and 0's outside the shape. The 1's - have to be turned into -1's if (a0, c, a1) is backfacing. - - The sum in the render target should be exactly the filled curved - shape, so then we can do a stencil-masked fill of the bounding - box, or whatever. - - This might even get us edge antialiasing in the bargain! I.e the - texels on the boundary of the circle will be between 0 and 1, so - they're feathered. - - ISSUE: will mip-mapping foul this up in case of very acute or - obtuse triangles? We probably want mip-mapping for two reasons: - 1) for performance, and 2) if we're trying for antialiasing, we - want the footprint of the soft texture edge to be about one - rendered pixel wide. (I suspect the scaling issues will be - similar to rendering glyphs using textures.) - - * see similar idea explored much more thoroughly by Loop and Blinn - in this paper: - http://research.microsoft.com/~cloop/LoopBlinn05.pdf - - (Actually they explore the math etc for the curve outline, - including cubic curves, but not the signed-area idea; instead they - do some funky extra tesselation to avoid overlaps.) diff --git a/Code/BF2/External/gameswf/extract_as_from_fla.cpp b/Code/BF2/External/gameswf/extract_as_from_fla.cpp deleted file mode 100644 index d1115c644..000000000 --- a/Code/BF2/External/gameswf/extract_as_from_fla.cpp +++ /dev/null @@ -1,35 +0,0 @@ -// extract_as_from_fla.cpp -- Thatcher Ulrich 2005 - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - -// Try to extract ActionScript source out of a .fla file. -// -// Flash seems to store text as UCS-16, so basically we can try -// removing 0 characters. - - -#include - - -int main() -{ - int char_count = 0; - for (; !feof(stdin); ) - { - int c = fgetc(stdin); - char_count++; - if (c == 0) - { - // ignore -// printf("zero"); - } - else - { -// fputc(c, stdout); - } -// fflush(stdout); - } - - printf("%d chars\n", char_count); -} diff --git a/Code/BF2/External/gameswf/gameswf.h b/Code/BF2/External/gameswf/gameswf.h index 148aca28c..92be4af5c 100644 --- a/Code/BF2/External/gameswf/gameswf.h +++ b/Code/BF2/External/gameswf/gameswf.h @@ -11,8 +11,11 @@ #define GAMESWF_H +#include +#include +#include #include // for poxy wchar_t -#include // for va_list arg to movie_interface::call_method_args() +#include class tu_file; class render_handler; @@ -32,6 +35,7 @@ namespace gameswf { // Forward declarations. struct action_buffer; + struct as_environment; struct as_value; struct bitmap_info; struct character; @@ -55,6 +59,10 @@ namespace gameswf // Control verbosity of specific categories. void set_verbose_action(bool verbose); void set_verbose_parse(bool verbose); + void set_verbose_debug(bool verbose); + // [INFERRED] names of the separate retail loader and live-count log switches. + void set_verbose_loader(bool verbose); + void set_verbose_gc(bool verbose); // Get and set the render handler. This is one of the first // things you should do to initialise the player (assuming you @@ -85,10 +93,6 @@ namespace gameswf typedef tu_file* (*file_opener_callback)(const char* url_or_path); void register_file_opener_callback(file_opener_callback opener); - // Register a callback for displaying SWF load progress. - typedef void (*progress_callback)(unsigned int loaded_bytes, unsigned int total_bytes); - void register_progress_callback(progress_callback progress_handle); - // ActionScripts embedded in a movie can use the built-in // fscommand() function to send data back to the host // application. If you are interested in this data, register @@ -107,18 +111,20 @@ namespace gameswf void set_curve_max_pixel_error(float pixel_error); float get_curve_max_pixel_error(); - // Some helpers that may or may not be compiled into your - // version of the library, depending on platform etc. - render_handler* create_render_handler_xbox(); - render_handler* create_render_handler_ogl(); - sound_handler* create_sound_handler_sdl(); - - // For stuff that's tricky to keep track of w/r/t ownership & cleanup. struct ref_counted { ref_counted(); + // SwiffPlayer.dll 0x100A4850 / 0x100A0180: implicit copy construction + // and assignment copy count and proxy without retaining the proxy. + ref_counted(const ref_counted&) = default; + ref_counted& operator=(const ref_counted&) = default; virtual ~ref_counted(); + // [CHOSEN, not recovered] issue #7: retail script interfaces carry a + // "reference counted" query in slot 0 and add_ref in slot +4 (characters: + // 0x1007EDA0 true / 0x1007EFE0; intermediate stage 0x1007DF50 false; plain + // objects 0x10008EE0 false), tested before each value-construction add_ref + // (e.g. 0x10091048-0x10091055). Native objects are always reference counted. void add_ref() const; void drop_ref() const; int get_ref_count() const { return m_ref_count; } @@ -133,15 +139,24 @@ namespace gameswf struct font; struct character_def; struct bitmap_character_def; + struct rect; struct sound_sample; // An interface for casting to different types of // resources. - struct resource : public ref_counted + // SwiffPlayer.dll: ref_counted is a VIRTUAL base, shared by the resource/character_def and the + // movie_definition sides (sprite_definition ctor 0x1007B5A0 keeps one copy at +0x40 behind the + // vbtables 0x100E01D4 / 0x100E01CC; movie_def_impl ctor 0x10077FB0 at +0x90 behind 0x100DFD24). + struct resource : virtual public ref_counted { - virtual ~resource() {} + // SwiffPlayer.dll 0x10071460 / 0x10073020: only the reference-counted + // base has state; 0x10072FF0 is the compiler's deleting wrapper. + resource() = default; + virtual ~resource() = default; // Override in derived classes that implement corresponding interfaces. + // SwiffPlayer.dll 0x1006EC20 / 0x1006EC30 / 0x1006EC40 + // (resource table 0x100DF258); [INFERRED] source-level names. virtual font* cast_to_font() { return 0; } virtual character_def* cast_to_character_def() { return 0; } virtual sound_sample* cast_to_sound_sample() { return 0; } @@ -149,23 +164,50 @@ namespace gameswf struct as_object; + struct as_object_interface; + + // The registry of live script objects, kept by as_object_interface's constructors and + // destructor so the movie teardown (release_script_objects) also reaches objects that only + // reference each other. [CHOSEN, not recovered] issue #7 + // (https://github.com/B2BF/OpenBF2/issues/7). + void register_script_object(as_object_interface* obj); + void unregister_script_object(as_object_interface* obj); + // Shared generation read by the retail script graph's mark visitors. + std::uint32_t get_gc_mark_generation(); + std::uint32_t get_gc_release_generation(); // This is the base class for all ActionScript-able objects // ("as_" stands for ActionScript). struct as_object_interface : public resource { - virtual ~as_object_interface() {} - - // [DICE-MOD SwiffPlayer: a SAFE downcast to as_object, following the cast_to_font / + // SwiffPlayer.dll 0x1007ECC2 / 0x1009A1C7 initializes the common + // list links to null. Collection owns insertion; construction does not. + as_object_interface* m_gc_previous = NULL; + as_object_interface* m_gc_next = NULL; + // [CHOSEN, not recovered] S3 bridge: native state for retail's secondary + // interface generation field; this does not reproduce its x86 base layout. + std::uint32_t m_gc_generation = 0; + + // [CHOSEN, not recovered] issue #7: registration, see register_script_object. + as_object_interface() { register_script_object(this); } + as_object_interface(const as_object_interface& other) : resource(other) { register_script_object(this); } + virtual ~as_object_interface() { unregister_script_object(this); } + + // [CHOSEN, not recovered] issue #7: a safe downcast for the movie teardown; character + // answers itself. movie declares the same slot (gameswf_impl.h). + virtual character* cast_to_character() { return 0; } + + // [CHOSEN, not recovered] Native type adjustment (issue #7), following the cast_to_font / // cast_to_character_def pattern above. Needed by the AS2 `addProperty` builtin, whose // fn.this_ptr is an as_object_interface* that may in fact be a sprite_instance - a - // static_cast would silently misinterpret those. See GAMESWF_DIVERGENCES.md.] + // static_cast would silently misinterpret those. See GAMESWF_DIVERGENCES.md. virtual as_object* cast_to_as_object() { return 0; } // So that text_character's can return something reasonable. + // SwiffPlayer.dll 0x1007DF10, movie secondary tables +0x18. virtual const char* get_text_value() const { return 0; } - // [DICE-MOD SwiffPlayer #38] the wide payload of DICE's String object (the shipped + // [CHOSEN, not recovered] Native accessor for the recovered wide payload (the shipped // tu_string_as_object carries a std::wstring at +60 beside the narrow tu_string at +44). The // text field's `text` setter (sub_10089440) routes a value carrying one to its wide store; // every other object answers NULL. See GAMESWF_DIVERGENCES.md. @@ -174,6 +216,23 @@ namespace gameswf virtual void set_member(const tu_stringi& name, const as_value& val) = 0; virtual bool get_member(const tu_stringi& name, as_value* val) = 0; virtual movie* to_movie() = 0; + + // SwiffPlayer.dll 0x1007DB80 / 0x1007DB70: leaf visitors only update + // the shared generation, and do nothing when it already matches. + virtual void gc_mark() + { + const std::uint32_t generation = get_gc_mark_generation(); + if (m_gc_generation != generation) m_gc_generation = generation; + } + virtual void gc_release() + { + const std::uint32_t generation = get_gc_release_generation(); + if (m_gc_generation != generation) m_gc_generation = generation; + } + + // SwiffPlayer.dll 0x10008F50, movie tables 0x100E08B4/0x100E0C3C + // +0x28: movies contribute no enumeration names. + virtual void enumerate(as_environment* env) {} }; @@ -206,44 +265,64 @@ namespace gameswf character_def() : m_id(-1), - m_registered_class(0) // [DICE-MOD SwiffPlayer] + m_registered_class(0) // { } + // SwiffPlayer.dll 0x1006EDB0 reads the definition ID, as does 0x100759C9. + // [CHOSEN, not recovered] S3 bridge: the native loader assigns it separately + // from an instance's placement ID. Root and runtime definitions use zero. + int get_character_id() const { return m_id; } + void set_character_id(int id) { m_id = id; } + + // Compiler deleting wrapper: SwiffPlayer.dll 0x100730C0. This forwards + // to the destructor before conditional deletion; its base lifetime is separate. virtual ~character_def() { - if (m_registered_class) m_registered_class->drop_ref(); // [DICE-MOD SwiffPlayer] + // [CHOSEN, not recovered] S3 bridge: native definitions own registered + // classes. Retail 0x1006ED80/0x1006EF50 only change base vtables here. + if (m_registered_class) m_registered_class->drop_ref(); } + // SwiffPlayer.dll 0x1006EDD0; definition tables +0x10. virtual void display(character* instance_info) {} + // SwiffPlayer.dll 0x1006EDE0 (release default). virtual bool point_test_local(float x, float y) { return false; } + // SwiffPlayer.dll 0x1006EDF0 / 0x1006EE00 return positive zero. virtual float get_height_local() { return 0.0f; } virtual float get_width_local() { return 0.0f; } + // SwiffPlayer.dll character_def table 0x100DF268 +0x20 is _purecall: every concrete definition + // answers its rectangle (shape and morph 0x10099290, text 0x100853E0, edit text 0x10086B40, + // bitmap 0x100739E0, sprite 0x1007B670, button 0x100A1F90). Callers dispatch through it + // directly (generic character 0x1007F240 via its definition, button bounds 0x100A1F90). + virtual rect get_bound_copy() const = 0; // Should stick the result in a smart_ptr immediately. virtual character* create_character_instance(movie* parent, int id); // default is to make a generic_character // From resource interface. + // SwiffPlayer.dll 0x1006EE10 returns its receiver. virtual character_def* cast_to_character_def() { return this; } - // [DICE-MOD SwiffPlayer: safe downcast to a bitmap character, same pattern as the casts + // [CHOSEN, not recovered] Native bitmap type adjustment, same pattern as the casts // above. Used by movie_definition::get_exported_bitmaps to tell an exported bitmap from any - // other exported character. Overridden in bitmap_character_def. See GAMESWF_DIVERGENCES.md.] + // other exported character. Overridden in bitmap_character_def. See GAMESWF_DIVERGENCES.md. virtual bitmap_character_def* cast_to_bitmap_character_def() { return 0; } - // [DICE-MOD SwiffPlayer: the AS2 class bound to this definition by Object.registerClass + // the AS2 class bound to this definition by Object.registerClass // (symbol, Class). The shipped character_def carries it at +12 (sub_100997B0 stores the // function there after get_exported_resource(symbol)); a sprite instanced from such a // definition gets __proto__ = Class.prototype and its constructor run at load // (sub_10081870). A raw ref_counted pointer, as shipped, because as_as_function is opaque - // to this header; it is always an as_as_function, add_ref'd by registerClass and released - // by the destructor. Stock 2006 has no registerClass. See GAMESWF_DIVERGENCES.md.] + // to this header. Native registerClass and teardown retain/release it through + // the existing S3 ownership bridge. Stock 2006 has no registerClass. ref_counted* m_registered_class; // // Caching. // + // SwiffPlayer.dll 0x1006EE20 / 0x1006EE30: release-image defaults. virtual void output_cached_data(tu_file* out, const cache_options& options) {} virtual void input_cached_data(tu_file* in) {} }; @@ -253,8 +332,15 @@ namespace gameswf // This is the client program's interface to the definition of // a movie (i.e. the shared constant source info). // - struct movie_definition : public character_def + // SwiffPlayer.dll: a movie definition is NOT a character definition. movie_definition derives only + // from the shared virtual ref_counted (movie_def_impl ctor 0x10077FB0: primary table 0x100DFC90, + // whose +0x20 is visit_imported_movies, not the bounds slot). Sprite definitions add character_def + // as a second base. + struct movie_definition : virtual public ref_counted { + // Compiler deleting wrapper: SwiffPlayer.dll 0x10071680. Native bases + // retain their ownership adapters; this certifies the wrapper only. + ~movie_definition() override = default; virtual int get_version() const = 0; virtual float get_width_pixels() const = 0; virtual float get_height_pixels() const = 0; @@ -330,7 +416,7 @@ namespace gameswf // my_bitmap_info_subclass* bi = (my_bitmap_info_subclass*) my_def->get_bitmap_info(i); // bi->set_internal_texture_reference(my_precomputed_textures[i]); // } - // [DICE-MOD SwiffPlayer: enumerate the bitmaps that ExportAssets gave a NAME. + // enumerate the bitmaps that ExportAssets gave a NAME. // // This is the missing half of the documented host-driven texture API above. BF2's menu SWFs // carry each menu bitmap as an undecoded DefineBitsLossless character whose ExportAssets @@ -343,7 +429,7 @@ namespace gameswf // tu_string array: the export hash's iterator hands its key back BY VALUE (container.h // get_key()), so a `const char*` taken from it dangled and read back as "" or garbage once // the heap block was reused - which is exactly what retail showed (2026-09-02: 1 of 12 - // exports resolved, names empty). See GAMESWF_DIVERGENCES.md.] + // exports resolved, names empty). See GAMESWF_DIVERGENCES.md. virtual int get_exported_bitmaps(int max, tu_string* names, bitmap_info** infos) const { return 0; } @@ -358,6 +444,8 @@ namespace gameswf // struct movie_interface : public as_object_interface { + // Compiler deleting wrapper: SwiffPlayer.dll 0x10073100; base lifetime is separate. + ~movie_interface() override = default; virtual movie_definition* get_movie_definition() = 0; // Frame counts in this API are 0-based (unlike ActionScript) @@ -380,12 +468,12 @@ namespace gameswf virtual play_state get_play_state() const = 0; virtual void set_background_color(const rgba& bg_color) = 0; - // [DICE-MOD SwiffPlayer: the getter the shipped SwiffPlayer::update reads every frame - + // the getter the shipped SwiffPlayer::update reads every frame - // movie_interface vslot +48 in SwiffPlayer.dll (2).i64 is sub_100736C0, `return this+32`, the // address of movie_root::m_background_color - and pushes to ISwiffRender::setBackgroundColor // (verified on retail 2026-09-02: 0xFF666666 after every updateTime). Stock 2006 has only the // setter. movie_root answers with its m_background_color; movie (gameswf_impl.h) carries the - // no-background default, next to its set_background_color stub. See GAMESWF_DIVERGENCES.md.] + // no-background default, next to its set_background_color stub. See GAMESWF_DIVERGENCES.md. virtual rgba get_background_color() const = 0; // Set to 0 if you don't want the movie to render its @@ -419,41 +507,11 @@ namespace gameswf virtual const char* get_variable(const char* path_to_var) const = 0; // @@ do we want a version that returns a number? - // ActionScript method call. Return value points to a - // static string buffer with the result; caller should - // use the value immediately before making more calls - // to gameswf. NOT THREAD SAFE!!! - // - // method_name is the name of the method (possibly namespaced). - // - // method_arg_fmt is a printf-style declaration of - // the method call, where the arguments are - // represented by { %d, %s, %f, %ls }, followed by the - // vararg list of actual arguments. - // - // E.g. - // - // m->call_method("path.to.method_name", "%d, %s, %f", i, "hello", 2.7f); - // - // The format args are a small subset of printf, namely: - // - // %d -- integer arg - // %s -- 0-terminated char* string arg - // %ls -- 0-terminated wchar_t* string arg - // %f -- float/double arg - // - // Whitespace and commas in the format string are ignored. - // - // This is not an ActionScript language parser, it - // doesn't recognize expressions or anything tricky. -#ifdef __GNUC__ - // use the following to catch errors: (only with gcc) - virtual const char* call_method(const char* method_name, const char* method_arg_fmt, ...) - __attribute__((format (printf, 3, 4))) = 0; // "this" is an implied param, so fmt is 3 and ... is 4! -#else // not __GNUC__ - virtual const char* call_method(const char* method_name, const char* method_arg_fmt, ...) = 0; -#endif // not __GNUC__ - virtual const char* call_method_args(const char* method_name, const char* method_arg_fmt, va_list args) = 0; + // Executes a command containing a method name and quoted or numeric arguments. + // The wide form takes UTF-16 units. The result is shared, ephemeral text. + virtual const char* call_method(const unsigned short* expression) = 0; + virtual const char* call_method(const char* expression) = 0; + // Make the movie visible/invisible. An invisible @@ -467,16 +525,6 @@ namespace gameswf virtual void *get_userdata() = 0; virtual void set_userdata(void *) = 0; - // Display callbacks, for client rendering. Callback - // is called after rendering the object it's attached - // to. - // - // Attach NULL to disable the callback. - virtual void attach_display_callback(const char* path_to_object, void (*callback)(void* user_ptr), void* user_ptr) = 0; - - virtual int add_interval_timer(void *timer) = 0; - virtual void clear_interval_timer(int x) = 0; - // for external movies virtual movie* get_root_movie() = 0; }; @@ -552,20 +600,10 @@ namespace gameswf create_bitmaps_flag cbf, create_font_shapes_flag cfs); - // [DICE-MOD SwiffPlayer: choose the bitmap policy for movies made by create_movie / - // create_library_movie, which hardcode DO_LOAD_BITMAPS and expose no way to change it. - // - // BF2's menu is exactly the case the DO_NOT_LOAD_BITMAPS comment above describes - "you have - // pre-processed bitmaps stored externally somewhere, and you plan to install them via - // get_bitmap_info()". Every menu bitmap is an undecoded DefineBitsLossless character whose - // ExportAssets symbol is its external file path, resolved through ISwiffRender::loadTexture. - // - // Under DO_LOAD_BITMAPS the lossless loader with TU_CONFIG_LINK_TO_ZLIB 0 logs an error and - // RETURNS BEFORE add_bitmap_character, so the character never exists and can never be exported - // or named; under DO_NOT_LOAD_BITMAPS it takes the documented else-arm - an empty bitmap_info, - // character registered - and no decoder is needed. That is why the shipped SwiffPlayer.dll links - // neither zlib nor jpeglib. Default is unchanged (DO_LOAD_BITMAPS). - // See GAMESWF_DIVERGENCES.md.] + // [CHOSEN, not recovered] Legacy native factory-policy adapter. The + // SwiffPlayer keeps generation disabled until cached generated textures can + // rebind to a new renderer (swf-cached-bitmap-renderer-ownership). Retail's + // factory enables generation; image tags still construct named descriptors. void set_default_create_bitmaps(create_bitmaps_flag cbf); // Create a gameswf::movie_definition from the given file name. @@ -766,6 +804,7 @@ namespace gameswf { float m_x, m_y; + // SwiffPlayer.dll 0x1006EB70. point() : m_x(0), m_y(0) {} point(float x, float y) : m_x(x), m_y(y) {} @@ -795,12 +834,19 @@ namespace gameswf void print() const; bool point_test(float x, float y) const; void expand_to_point(float x, float y); + // SwiffPlayer.dll 0x1006EBA0 / 0x1006EBB0. float width() const { return m_x_max-m_x_min; } float height() const { return m_y_max-m_y_min; } point get_corner(int i) const; void enclose_transformed_rect(const matrix& m, const rect& r); + // Transforms only the minimum and maximum corners, without sorting them. + // [INFERRED] Source-level name; SwiffPlayer.dll 0x1009E410. + void transform(const matrix& m); + // Includes the other rectangle's minimum corner, then its maximum corner. + // [INFERRED] Source-level name; SwiffPlayer.dll 0x1009E780. + void expand_to_rect(const rect& r); void set_lerp(const rect& a, const rect& b, float t); }; @@ -835,6 +881,15 @@ namespace gameswf // using textures. struct bitmap_info : public ref_counted { + // [CHOSEN, not recovered] Native cached images may outlive their GPU + // registry (issue #7). Such images own their release/rebinding state. + struct render_resource { virtual ~render_resource() {} }; + std::unique_ptr m_render_resource; + + // [INFERRED] name: primary slot 0 distinguishes named descriptors. + // SwiffPlayer.dll 0x10004EB0, consumed at 0x10006311. + virtual bool is_named() const { return false; } + virtual ~bitmap_info(); unsigned int m_texture_id; // nuke? int m_original_width; // nuke? int m_original_height; // nuke? @@ -848,14 +903,28 @@ namespace gameswf } }; + // A movie bitmap whose ExportAssets symbol names its external texture. + // SwiffPlayer.dll 0x10071930; destruction 0x10073B40/0x10073B10 destroys + // the string before the bitmap_info base notifies the renderer. + struct named_bitmap_info : public bitmap_info + { + // SwiffPlayer.dll 0x100719A0. + bool is_named() const override { return true; } + // [RETIRE-WHEN: swf-native-bitmap-name] Storage is now descriptor-owned; + // maintainer exported-menu-image/reload acceptance remains required. + std::string m_name; + }; + // You must define a subclass of render_handler, and pass an // instance to set_render_handler(). - // [DICE-MOD SwiffPlayer #37: the focused text field's keyboard/clipboard surface - the shipped + // the focused text field's keyboard/clipboard surface - the shipped // +200 interface of DICE's edit_text_character, the object dword_100F8EE0 points at. SwiffPlayer's - // key latch, notifyChar, setTextInput and getTextInput0/1 dispatch into it (slots 0..4).] + // key latch, notifyChar, setTextInput and getTextInput0/1 dispatch into it (slots 0..4). struct text_input { - virtual ~text_input() {} + // Implicit vptr construction: SwiffPlayer.dll 0x10084D80. + // Destruction clears focus after the field's members: 0x10084D90. + virtual ~text_input(); virtual void on_key(int vkey) = 0; virtual void on_char(int character) = 0; virtual void paste() = 0; @@ -875,24 +944,25 @@ namespace gameswf virtual bitmap_info* create_bitmap_info_alpha(int w, int h, unsigned char* data) = 0; virtual bitmap_info* create_bitmap_info_rgb(image::rgb* im) = 0; virtual bitmap_info* create_bitmap_info_rgba(image::rgba* im) = 0; - // [DICE-MOD SwiffPlayer: the 2004 base's fifth slot, dropped by 2006 - a bitmap resolved BY + // the 2004 base's fifth slot, dropped by 2006 - a bitmap resolved BY // FILE NAME through the host (BF2: ISwiffRender::loadTexture). The sprite `loadMovie` // image loader (gameswf_sprite_loadmovie -> render::create_bitmap_info_file, sub_1009A620) - // hangs every `loadImg` on it. Returns NULL when the host cannot resolve the name.] + // hangs every `loadImg` on it. The native handler keeps failed texture handles. virtual bitmap_info* create_bitmap_info_file(const char* path) { return NULL; } - // [DICE-MOD SwiffPlayer #36: the twelve text slots DICE's edit_text_character drives - a + // the twelve text slots DICE's edit_text_character drives - a // renderer-side text LINE object per laid-out line. Defaults do nothing (no renderer, no text), - // the SwiffPlayer handler forwards them to ISwiffRender. See GAMESWF_DIVERGENCES.md.] + // the SwiffPlayer handler forwards them to ISwiffRender. See GAMESWF_DIVERGENCES.md. virtual void* text_create(const char* /*font_name*/, int /*height_px*/) { return NULL; } virtual void text_release(void* /*line*/) {} virtual void text_set(void* /*line*/, const wchar_t* /*text*/) {} virtual void text_detach(void* /*line*/) {} virtual void text_draw(void* /*line*/, const matrix* /*m*/, unsigned /*color*/, int /*flags*/) {} virtual bool text_extent(void* /*line*/, int /*count*/, float* /*w*/, float* /*h*/) { return false; } - virtual bool text_hit(void* /*line*/, int* /*out_pos*/, int /*x*/, int /*y*/) { return false; } - virtual bool text_selection(void* /*line*/, int* a, int* b) { if (a) *a = 0; if (b) *b = 0; return false; } // [DICE-MOD SwiffPlayer #46] true = a selection exists - virtual bool text_set_selection(void* /*line*/, int, int, int, int) { return false; } + // float coordinates: SwiffPlayer.dll 0x100887A5..0x100887D7 / 0x10088823..0x1008883B + virtual bool text_hit(void* /*line*/, int* /*out_pos*/, float /*x*/, float /*y*/) { return false; } + virtual bool text_selection(void* /*line*/, int* a, int* b) { if (a) *a = 0; if (b) *b = 0; return false; } // true = a selection exists + virtual bool text_set_selection(void* /*line*/, float, float, float, float) { return false; } virtual void text_blur(void* /*line*/) {} virtual void text_set_size(void* /*line*/, float /*size*/, int /*flag*/) {} virtual void text_caret(void* /*line*/, int /*pos*/) {} @@ -912,6 +982,9 @@ namespace gameswf // Geometric and color transforms for mesh and line_strip rendering. virtual void set_matrix(const matrix& m) = 0; virtual void set_cxform(const cxform& cx) = 0; + // Submit the display-list depth before mesh and line callbacks. + // SwiffRenderHandler (SwiffPlayer.h) is the one backend; every handler supplies depth. + virtual void set_depth(int depth) = 0; // Draw triangles using the current fill-style 0. // Clears the style list after rendering. @@ -961,6 +1034,12 @@ namespace gameswf }; // Keyboard handling + // [CHOSEN, not recovered] Native input adapter. Query consumes the low press + // bit and returns the Win32 asynchronous high/low bit representation. + typedef unsigned short (*async_key_state_callback)(int key_code); + void set_async_key_state_callback(async_key_state_callback callback); + bool is_key_down(int key_code); + namespace key { enum code { @@ -1073,33 +1152,6 @@ namespace gameswf void notify_key_event(key::code k, bool down); - // Some optional helpers. - namespace tools - { - struct process_options - { - bool m_zip_whole_file; // @@ not implemented yet (low priority?) - bool m_remove_image_data; // removes existing image data; leaves minimal placeholder tags - bool m_remove_font_glyph_shapes; - - process_options() - : - m_zip_whole_file(false), - m_remove_image_data(false), - m_remove_font_glyph_shapes(false) - { - } - }; - - // Copy tags from *in to *out, applying the given - // options. *in should be a SWF-format stream. The - // output will be a SWF-format stream. - // - // Returns 0 on success, or a non-zero error-code on - // failure. - int process_swf(tu_file* swf_out, tu_file* swf_in, const process_options& options); - } - } // namespace gameswf diff --git a/Code/BF2/External/gameswf/gameswf_action.cpp b/Code/BF2/External/gameswf/gameswf_action.cpp index ea848e5bf..b1c6a1995 100644 --- a/Code/BF2/External/gameswf/gameswf_action.cpp +++ b/Code/BF2/External/gameswf/gameswf_action.cpp @@ -6,30 +6,30 @@ // Implementation and helpers for SWF actions. +// [CHOSEN, not recovered] issue #7: the script-object registry. Included before the gameswf headers: +// MSVC's pulls in , whose isfinite template the fake isfinite() macro of +// base/tu_math.h would otherwise rename. +#include +#include +#include +#include "../../Platform/X87Compat.h" #include "gameswf_action.h" -// [TEMP] RW-89 diagnostic: the last member name ActionGetMember read, so the two 'invalid object' -// errors below can say WHICH member came back undefined. Remove with the tracers. -static tu_string s_last_member_name; #include "gameswf_impl.h" #include "gameswf_log.h" +#include "gameswf_profile.h" #include "gameswf_stream.h" #include "base/tu_random.h" +#if defined(_WIN32) +extern "C" __declspec(dllimport) short __stdcall GetAsyncKeyState(int vkey); +#endif + #include "gameswf_string.h" -#include "gameswf_movie.h" #include "gameswf_timers.h" -#include "gameswf_textformat.h" #include "gameswf_sound.h" - -#ifdef HAVE_LIBXML #include "gameswf_xml.h" -#include "gameswf_xmlsocket.h" -#endif -#ifdef _WIN32 -#define snprintf _snprintf -#endif // _WIN32 // NOTES: // @@ -63,7 +63,6 @@ static tu_string s_last_member_name; // gotoAndPlay() // nextFrame() // startDrag() -// getURL() // getBytesLoaded() // getBytesTotal() @@ -98,152 +97,224 @@ namespace gameswf // action stuff // - // [DICE-MOD SwiffPlayer #40] the Number and Boolean wrapper objects the shipped action_init - // (sub_10090FF0) registers beside String/Array/Object (sub_1008C520: a 68-byte object holding - // the double at +48; sub_1008C4D0: a 60-byte object holding the bool at +44; each constructor - // takes an optional first argument and answers the object). Their text value is the value's - // own string form, which is what to_number()/to_tu_string() read from an object - so - // `new Number(row.selected) > 0` in the DICE ColumnList's fill compares the number, where - // stock 2006 (no Number constructor) yielded undefined and never preselected a row. + static void number_value_of(const fn_call& fn); + static void number_to_string(const fn_call& fn); + static void boolean_value_of(const fn_call& fn); + static void boolean_to_string(const fn_call& fn); + // SwiffPlayer.dll 0x100F982C; source-level name [INFERRED]. + static Uint32 s_object_live_count = 0; + struct number_object : public as_object { double m_value; - tu_string m_text; - number_object(double v) : m_value(v) { m_text = as_value(v).to_tu_string(); } - virtual const char* get_text_value() const { return m_text.c_str(); } + number_object() + { + // SwiffPlayer.dll 0x100A9AD0: toString before valueOf. + // The numeric field stays unwritten until the factory receives an argument. + set_member("toString", &number_to_string); + set_member("valueOf", &number_value_of); + } + // SwiffPlayer.dll 0x100A9BE0: only base destruction before deletion. + ~number_object() override = default; + // SwiffPlayer.dll 0x100A99C0: direct concrete forwarder. + void set_member(const tu_stringi& name, const as_value& value) override + { + as_object::set_member(name, value); + } + // SwiffPlayer.dll 0x100A99D0: direct concrete forwarder. + bool get_member(const tu_stringi& name, as_value* value) override + { + return as_object::get_member(name, value); + } + virtual const char* get_text_value() const + { + // SwiffPlayer.dll 0x100A99E0: every Number shares one %f buffer. + // [CHOSEN, not recovered] S3 bridge: native buffer capacity and CRT. + static char text[512]; + sprintf(text, "%f", m_value); + return text; + } }; struct boolean_object : public as_object { bool m_value; - boolean_object(bool v) : m_value(v) {} - virtual const char* get_text_value() const { return m_value ? "true" : "false"; } + boolean_object() : m_value(false) + { + // SwiffPlayer.dll 0x100A9880: false, then valueOf before toString. + set_member("valueOf", &boolean_value_of); + set_member("toString", &boolean_to_string); + } + // SwiffPlayer.dll 0x100A9990: only base destruction before deletion. + ~boolean_object() override = default; + // SwiffPlayer.dll vtable 0x100E3698 +0x18 -> 0x1000B390 returns null. + // Inherit as_object's null text slot; use toString for Boolean text. }; + + static void number_value_of(const fn_call& fn) + { + // SwiffPlayer.dll 0x100A9A10 reads before releasing the result's old value. + const double value = static_cast(fn.this_ptr)->m_value; + fn.result->set_double(value); + } + + static void number_to_string(const fn_call& fn) + { + // SwiffPlayer.dll 0x100A9A40 constructs before reading the receiver. + as_object_interface* text = create_dice_string_object(NULL, 0); + const as_value value(static_cast(fn.this_ptr)->m_value); + assign_dice_string_object_narrow(text, value.to_string()); + fn.result->set_as_object_interface(text); + } + + static void boolean_value_of(const fn_call& fn) + { + // SwiffPlayer.dll 0x100A97E0: Boolean result, not a numeric result. + const bool value = static_cast(fn.this_ptr)->m_value; + fn.result->set_bool(value); + } + + static void boolean_to_string(const fn_call& fn) + { + // SwiffPlayer.dll 0x100A9820 constructs before reading the receiver. + as_object_interface* text = create_dice_string_object(NULL, 0); + assign_dice_string_object_narrow(text, + static_cast(fn.this_ptr)->m_value ? "true" : "false"); + fn.result->set_as_object_interface(text); + } + void as_global_number_ctor(const fn_call& fn) { - number_object* obj = new number_object(fn.nargs > 0 ? fn.arg(0).to_number() : 0.0); + // SwiffPlayer.dll 0x1008C520 registers methods before argument conversion. + number_object* obj = new number_object; + if (fn.nargs != 0) obj->m_value = fn.arg(0).to_number(); fn.result->set_as_object_interface(obj); } void as_global_boolean_ctor(const fn_call& fn) { - boolean_object* obj = new boolean_object(fn.nargs > 0 ? fn.arg(0).to_bool() : false); + // SwiffPlayer.dll 0x1008C4D0 registers methods before argument conversion. + boolean_object* obj = new boolean_object; + if (fn.nargs != 0) obj->m_value = fn.arg(0).to_bool(); fn.result->set_as_object_interface(obj); } void action_init(); + // Native factory for the separately published retail String class object. + as_object* create_dice_string_class(); // Statics. bool s_inited = false; smart_ptr s_global; - fscommand_callback s_fscommand_handler = NULL; - - -#define EXTERN_MOVIE - -#ifdef EXTERN_MOVIE - void attach_extern_movie(const char* url, const movie* target, const movie* root_movie) + // SwiffPlayer.dll 0x100F94CC: modules are separate from the global object's members. + // [CHOSEN, not recovered] S3 bridge: module values use the native object bags. + static stringi_hash s_modules; + // SwiffPlayer.dll 0x100F9358 / initialized release sentinel 0x100ECE68. + static Uint32 s_gc_mark_generation = 0; + Uint32 get_gc_mark_generation() { return s_gc_mark_generation; } + Uint32 get_gc_release_generation() { return 0xFEEDBEEFu; } + void advance_gc_mark_generation() { ++s_gc_mark_generation; } + + void gc_mark_value(const as_value& value) { - tu_string infile = get_workdir(); - infile += url; - - movie_definition_sub* md = create_library_movie_sub(infile.c_str()); - if (md == NULL) + // SwiffPlayer.dll 0x1000B520: functions and objects take distinct paths. + if (value.get_type() == as_value::AS_FUNCTION) { - log_error("can't create movie_definition_sub for %s\n", infile.c_str()); - return; + if (as_as_function* function = value.to_as_function()) function->gc_mark(); } + else if (value.get_type() == as_value::OBJECT) + { + if (as_object_interface* object = value.to_object()) object->gc_mark(); + } + } - gameswf::movie_interface* extern_movie; - - if (target == root_movie) + void gc_mark_modules() + { + // SwiffPlayer.dll 0x1008C570 advances twice after a non-null function. + // Do not merge this branch into gc_mark_value and lose the skipped entry. + for (stringi_hash::iterator it = s_modules.begin(); it != s_modules.end(); ++it) { - extern_movie = create_library_movie_inst_sub(md); - if (extern_movie == NULL) + if (it->second.get_type() == as_value::AS_FUNCTION && it->second.to_as_function()) { - log_error("can't create extern root movie_interface for %s\n", infile.c_str()); - return; + it->second.to_as_function()->gc_mark(); + ++it; } - set_current_root(extern_movie); - movie* m = extern_movie->get_root_movie(); - - m->on_event(event_id::LOAD); - } - else - { - extern_movie = md->create_instance(); - if (extern_movie == NULL) + else if (it->second.get_type() == as_value::OBJECT && it->second.to_object()) { - log_error("can't create extern movie_interface for %s\n", infile.c_str()); - return; + it->second.to_object()->gc_mark(); } - - save_extern_movie(extern_movie); - - character* tar = (character*)target; - const char* name = tar->get_name(); - Uint16 depth = tar->get_depth(); - bool use_cxform = false; - cxform color_transform = tar->get_cxform(); - bool use_matrix = false; - matrix mat = tar->get_matrix(); - float ratio = tar->get_ratio(); - Uint16 clip_depth = tar->get_clip_depth(); - - movie* parent = tar->get_parent(); - movie* new_movie = extern_movie->get_root_movie(); - - assert(parent != NULL); - - ((character*)new_movie)->set_parent(parent); - - parent->replace_display_object( - (character*) new_movie, - name, - depth, - use_cxform, - color_transform, - use_matrix, - mat, - ratio, - clip_depth); - } - } -#endif // EXTERN_MOVIE - - void register_fscommand_callback(fscommand_callback handler) - // External interface. + } + } + // SwiffPlayer.dll 0x100D6500 registers this table's exit destructor; + // 0x100D6E60 destroys its entries/storage. NewObject factories at 0x100F94C8 + // are independent of modules + // and writable _global members (registration 0x1009124C-0x100913F5). + static stringi_hash s_constructors; + fscommand_callback s_fscommand_handler = NULL; + // SwiffPlayer.dll 0x100925B4/0x100925C1 publishes the currently executing environment. + static as_environment* s_current_environment = NULL; + // SwiffPlayer.dll 0x100F9828: member lookup supplies the next call's superclass. + static as_as_function* s_call_super = NULL; + void set_call_super(as_as_function* constructor) { s_call_super = constructor; } + void set_environment_super(as_environment* env) { env->m_super_ctor = s_call_super; } + + static as_object_interface* lookup_global_object() { - s_fscommand_handler = handler; + // SwiffPlayer.dll 0x1008E4D0: lookup only; no implicit initialization. + as_value global; + if (!s_modules.get("_global", &global)) return NULL; + return global.get_type() == as_value::OBJECT ? global.m_object_value : NULL; } + static void set_global_member(const char* name, const as_value& value) + { + // SwiffPlayer.dll 0x1008E5E0: a missing module skips name construction; + // a present non-object module still reaches the unguarded virtual call. + as_value global; + if (s_modules.get("_global", &global)) + { + as_object_interface* object = global.get_type() == as_value::OBJECT + ? global.m_object_value : NULL; + const tu_stringi member(name); + object->set_member(member, value); + } + } - - static bool string_to_number(double* result, const char* str) - // Utility. Try to convert str to a number. If successful, - // put the result in *result, and return true. If not - // successful, put 0 in *result, and return false. + static void register_global_function(const char* name, as_c_function_ptr function) { - char* tail = 0; - *result = strtod(str, &tail); - if (tail == str || *tail != 0) + // SwiffPlayer.dll 0x1008E6E0: lookup, name, function value, virtual write. + as_value global; + if (s_modules.get("_global", &global)) { - // Failed conversion to Number. - return false; + as_object_interface* object = global.get_type() == as_value::OBJECT + ? global.m_object_value : NULL; + const tu_stringi member(name); + const as_value value(function); + object->set_member(member, value); } - return true; + } + + static void register_constructor(const char* name, as_c_function_ptr constructor) + { + // SwiffPlayer.dll 0x1008E830: add to the private factory table. + const tu_stringi key(name); + s_constructors.add(key, constructor); } + void register_fscommand_callback(fscommand_callback handler) + // External interface. + { + // SwiffPlayer.dll 0x1008A1A0 replaces the callback, including NULL. + s_fscommand_handler = handler; + } + + + // // array object // - // [DICE-MOD SwiffPlayer: the AS Array methods. Stock 2006 had NONE (its constructor was commented - // out, "array methods not implemented yet"), and the menu's list code stops at its first `push` - // (retail 2026-09-02). The shipped array object (sub_1009CB20, 68 bytes) registers concat, join, - // pop, push, reverse, shift, slice, sort, splice, toString, unshift on every instance; `length` - // is live. Elements keep the stock member-per-index representation ("0", "1", ...), with a - // tracked length so holes and explicit `length` writes behave.] + // Array methods are registered on each instance; indexed values have separate dense storage. void array_push(const fn_call& fn); void array_pop(const fn_call& fn); void array_shift(const fn_call& fn); @@ -256,17 +327,15 @@ namespace gameswf void array_concat(const fn_call& fn); void array_sort(const fn_call& fn); - // [DICE-MOD SwiffPlayer #49] sub_10099CB0 - see the declaration in gameswf_action.h. The - // prototype is reached the way the two enumerate opcodes always cast it; then the own members, - // filtered on the value's type exactly as the shipped loop tests `1 <= type <= 4` (its enum is - // STRING 1, NUMBER 2, BOOLEAN 3, OBJECT 4, C_FUNCTION 5, AS_FUNCTION 6; null is an OBJECT there, - // so this port's NULLTYPE passes too). + // SwiffPlayer.dll 0x10099CB0: virtual prototype enumeration precedes own + // members, filtered on the shipped value types 1 through 4. + // [CHOSEN, not recovered] S3 bridge: the retained 2006 NULLTYPE passes too; + // retail Push null instead constructs a STRING "NULL" (0x10094F66). void as_object::enumerate(as_environment* env) { - as_object* proto = m_prototype ? m_prototype->cast_to_as_object() : NULL; - if (proto) + if (m_prototype) { - proto->enumerate(env); + m_prototype->enumerate(env); } for (stringi_hash::const_iterator it = m_members.begin(); it != m_members.end(); ++it) { @@ -279,34 +348,62 @@ namespace gameswf } } + // Destructor body SwiffPlayer.dll 0x1007CDB0 (called by 0x1009D1C0): member + // hash at +0x38, then weak-proxy release. [CHOSEN, not recovered] issue #7: + // native member containers and weak proxies perform the same releases. struct as_array_object : public as_object { - int m_length; + // Compiler deleting wrapper: SwiffPlayer.dll 0x1009D1C0; it delegates + // to the Array lifetime body before conditional deletion. + // 0x10077F50 destroys dense values before the object base's live-count + // decrement, accessor keys, constructor and ordinary members. + ~as_array_object() override = default; + virtual void gc_mark() + { + // SwiffPlayer.dll 0x1009CF50 marks the inherited object first, then + // only OBJECT elements. Functions in dense storage are not visited. + if (m_gc_generation == get_gc_mark_generation()) return; + as_object::gc_mark(); + for (int i = 0; i < m_elements.size(); ++i) + if (m_elements[i].get_type() == as_value::OBJECT && m_elements[i].to_object()) + m_elements[i].to_object()->gc_mark(); + } + virtual void gc_release() + { + // SwiffPlayer.dll 0x1009CFC0: inherited members before OBJECT + // elements, then clear dense storage. No function traversal. + if (m_gc_generation == get_gc_release_generation()) return; + as_object::gc_release(); + for (int i = 0; i < m_elements.size(); ++i) + if (m_elements[i].get_type() == as_value::OBJECT && m_elements[i].to_object()) + m_elements[i].to_object()->gc_release(); + m_elements.clear(); + } + + // [CHOSEN, not recovered] S3 bridge: retain the native as_object interface and + // ownership policy. Indexed storage and the Array operations below follow retail. + array m_elements; as_array_object() - : - m_length(0) { - this->set_member("push", &array_push); - this->set_member("pop", &array_pop); - this->set_member("shift", &array_shift); - this->set_member("unshift", &array_unshift); + // SwiffPlayer.dll 0x1009CB20: preserve builtin registration order. this->set_member("join", &array_join); - this->set_member("toString", &array_to_string); + this->set_member("concat", &array_concat); this->set_member("reverse", &array_reverse); + this->set_member("toString", &array_to_string); + this->set_member("pop", &array_pop); + this->set_member("push", &array_push); + this->set_member("shift", &array_shift); this->set_member("slice", &array_slice); - this->set_member("splice", &array_splice); - this->set_member("concat", &array_concat); this->set_member("sort", &array_sort); + this->set_member("splice", &array_splice); + this->set_member("unshift", &array_unshift); } - // [DICE-MOD SwiffPlayer #49] sub_1009D020 - the array's own enumerate: the element indices - // "0".."length-1" and nothing else. Neither the prototype nor m_members (where this port keeps - // push/pop/... and the elements themselves) is visited, so `for (k in group)` in mainMenu.swf's - // Radio.toggleCheck sees only its sibling buttons. + // SwiffPlayer.dll 0x1009D020 enumerates only indices, including undefined holes. virtual void enumerate(as_environment* env) { - for (int i = 0; i < m_length; i++) + for (int i = 0; i < m_elements.size(); i++) { char buf[16]; sprintf(buf, "%d", i); @@ -314,66 +411,60 @@ namespace gameswf } } - static tu_stringi index_name(int i) - { - as_value k; - k.set_int(i); - return tu_stringi(k.to_string()); - } - - as_value get_element(int i) - { - as_value v; - as_object::get_member(index_name(i), &v); - return v; - } + const as_value& get_element(int i) const { return m_elements[i]; } void set_element(int i, const as_value& v) { - as_object::set_member(index_name(i), v); - if (i >= m_length) - { - m_length = i + 1; - } + if (i >= m_elements.size()) m_elements.resize(i + 1); + m_elements[i] = v; } virtual bool get_member(const tu_stringi& name, as_value* val) { - if (name == "length") + if (strcmp(name.c_str(), "length") == 0) { - val->set_int(m_length); + // 0x1009C215/0x1009C21C release the result twice before writing it. + const int size = m_elements.size(); + val->set_int(size); return true; } + // SwiffPlayer.dll 0x1009C1F0 accepts a digit prefix followed by '.' or NUL. + const char* text = name.c_str(); + if (*text) + { + const char* end = text; + while (*end >= '0' && *end <= '9') ++end; + if (*end == 0 || *end == '.') + { + const int index = atoi(text); + if (index >= m_elements.size()) return false; + *val = get_element(index); + return true; + } + } return as_object::get_member(name, val); } virtual void set_member(const tu_stringi& name, const as_value& val) { - if (name == "length") - { - int n = (int) val.to_number(); - if (n < 0) n = 0; - for (int i = n; i < m_length; i++) - { - as_object::set_member(index_name(i), as_value()); - } - m_length = n; - return; - } + // SwiffPlayer.dll 0x1009C560 accepts only a nonempty, all-digit index. + // Other names, including length and decimal suffixes, use the object bag. const char* s = name.c_str(); - if (s[0] >= '0' && s[0] <= '9') + if (*s) { - const int idx = atoi(s); - if (idx >= m_length) + const char* end = s; + while (*end >= '0' && *end <= '9') ++end; + if (*end == 0) { - m_length = idx + 1; + set_element(atoi(s), val); + return; } } as_object::set_member(name, val); } }; - // [DICE-MOD SwiffPlayer #31] see gameswf_action.h. + // see gameswf_action.h. as_object* create_array_object() { return new as_array_object; @@ -382,226 +473,187 @@ namespace gameswf void array_object_push(as_object* arr, const as_value& v) { as_array_object* a = static_cast(arr); - a->set_element(a->m_length, v); + a->m_elements.push_back(v); + } + + const array& array_object_values(as_object_interface* arr) + { + return static_cast(arr)->m_elements; } static as_array_object* array_this(const fn_call& fn) { - as_object* o = fn.this_ptr ? fn.this_ptr->cast_to_as_object() : NULL; - // The shipped bodies take `this` for an array unconditionally; so does this cast. - return o ? static_cast(o) : NULL; + // [CHOSEN, not recovered] S3 bridge: adjust the native interface to array storage. + return static_cast(fn.this_ptr->cast_to_as_object()); } void array_push(const fn_call& fn) { + // SwiffPlayer.dll 0x1009C8B0. as_array_object* a = array_this(fn); - if (a == NULL) return; for (int i = 0; i < fn.nargs; i++) { - a->set_element(a->m_length, fn.arg(i)); + a->m_elements.push_back(fn.arg(i)); } - fn.result->set_int(a->m_length); + fn.result->set_int(a->m_elements.size()); } void array_pop(const fn_call& fn) { + // SwiffPlayer.dll 0x1009C880: empty arrays leave the result untouched. as_array_object* a = array_this(fn); - if (a == NULL || a->m_length <= 0) { *fn.result = as_value(); return; } - *fn.result = a->get_element(a->m_length - 1); - as_object* base = a; - base->set_member(as_array_object::index_name(a->m_length - 1), as_value()); - a->m_length--; + if (a->m_elements.size() == 0) return; + *fn.result = a->m_elements.back(); + a->m_elements.pop_back(); } void array_shift(const fn_call& fn) { + // SwiffPlayer.dll 0x1009C940: empty arrays leave the result untouched. as_array_object* a = array_this(fn); - if (a == NULL || a->m_length <= 0) { *fn.result = as_value(); return; } + if (a->m_elements.size() == 0) return; *fn.result = a->get_element(0); - for (int i = 1; i < a->m_length; i++) - { - a->set_element(i - 1, a->get_element(i)); - } - as_object* base = a; - base->set_member(as_array_object::index_name(a->m_length - 1), as_value()); - a->m_length--; + a->m_elements.remove(0); } void array_unshift(const fn_call& fn) { + // SwiffPlayer.dll 0x1009CAB0 inserts successive arguments at successive indices. as_array_object* a = array_this(fn); - if (a == NULL) return; const int n = fn.nargs; - for (int i = a->m_length - 1; i >= 0; i--) - { - a->set_element(i + n, a->get_element(i)); - } for (int i = 0; i < n; i++) { - a->set_element(i, fn.arg(i)); + a->m_elements.insert(i, fn.arg(i)); } - fn.result->set_int(a->m_length); + fn.result->set_int(a->m_elements.size()); + } + + // [CHOSEN, not recovered] S3 bridge to the current String factory. + static void array_string_result(as_value* result, const tu_string& text) + { + as_object_interface* string = create_dice_string_object(NULL, 0); + assign_dice_string_object_narrow(string, text.c_str()); + result->set_as_object_interface(string); } - static void array_join_impl(as_array_object* a, const char* sep, as_value* result) + static void array_join_impl(as_array_object* a, const char* sep, as_value* result, bool trailing_separator) { tu_string s; - for (int i = 0; i < a->m_length; i++) + for (int i = 0; i < a->m_elements.size(); i++) { - if (i > 0) s += sep; + if (!trailing_separator && i > 0) s += sep; s += a->get_element(i).to_tu_string(); + if (trailing_separator) s += sep; } - result->set_tu_string(s); + array_string_result(result, s); } void array_join(const fn_call& fn) { + // SwiffPlayer.dll 0x1009C2C0 appends a separator after every element. as_array_object* a = array_this(fn); - if (a == NULL) return; tu_string sep = ","; if (fn.nargs > 0) sep = fn.arg(0).to_tu_string(); - array_join_impl(a, sep.c_str(), fn.result); + array_join_impl(a, sep.c_str(), fn.result, true); } void array_to_string(const fn_call& fn) { + // SwiffPlayer.dll 0x1009C4C0 inserts commas only between elements. as_array_object* a = array_this(fn); - if (a == NULL) return; - array_join_impl(a, ",", fn.result); + array_join_impl(a, ",", fn.result, false); } void array_reverse(const fn_call& fn) { + // SwiffPlayer.dll 0x1009C5F0 mutates in place without assigning a result. as_array_object* a = array_this(fn); - if (a == NULL) return; - for (int i = 0, j = a->m_length - 1; i < j; i++, j--) + for (int i = 0, j = a->m_elements.size() - 1; i < j; i++, j--) { as_value t = a->get_element(i); a->set_element(i, a->get_element(j)); a->set_element(j, t); } - fn.result->set_as_object_interface(a); } void array_slice(const fn_call& fn) { + // SwiffPlayer.dll 0x1009D0A0: even the default end excludes the last element. as_array_object* a = array_this(fn); - if (a == NULL) return; - int start = fn.nargs > 0 ? (int) fn.arg(0).to_number() : 0; - int end = fn.nargs > 1 ? (int) fn.arg(1).to_number() : a->m_length; - if (start < 0) start += a->m_length; - if (end < 0) end += a->m_length; - if (start < 0) start = 0; - if (end > a->m_length) end = a->m_length; + int start = 0; + int end = a->m_elements.size() - 1; + if (fn.nargs != 0) + { + start = bf2x87::toIntTruncate(fn.arg(0).to_number()); + if (fn.nargs > 1) + { + end = bf2x87::toIntTruncate(fn.arg(1).to_number()); + if (end < 0) end += a->m_elements.size(); + if (end >= a->m_elements.size()) end = a->m_elements.size() - 1; + } + } smart_ptr r = new as_array_object; for (int i = start; i < end; i++) { - r->set_element(r->m_length, a->get_element(i)); + r->m_elements.push_back(a->get_element(i)); } fn.result->set_as_object_interface(r.get_ptr()); } void array_splice(const fn_call& fn) { - as_array_object* a = array_this(fn); - if (a == NULL) return; - int start = fn.nargs > 0 ? (int) fn.arg(0).to_number() : 0; - if (start < 0) start += a->m_length; - if (start < 0) start = 0; - if (start > a->m_length) start = a->m_length; - int del = fn.nargs > 1 ? (int) fn.arg(1).to_number() : a->m_length - start; - if (del < 0) del = 0; - if (start + del > a->m_length) del = a->m_length - start; - const int ins = fn.nargs > 2 ? fn.nargs - 2 : 0; - - smart_ptr removed = new as_array_object; - for (int i = 0; i < del; i++) - { - removed->set_element(i, a->get_element(start + i)); - } - // Shift the tail by (ins - del). - const int old_len = a->m_length; - const int tail = old_len - (start + del); - if (ins > del) - { - for (int i = tail - 1; i >= 0; i--) - { - a->set_element(start + ins + i, a->get_element(start + del + i)); - } - } - else if (ins < del) + // SwiffPlayer.dll 0x1009C960 mutates the array and leaves the result untouched. + if (fn.nargs < 2) { - for (int i = 0; i < tail; i++) - { - a->set_element(start + ins + i, a->get_element(start + del + i)); - } - as_object* base = a; - for (int i = old_len - (del - ins); i < old_len; i++) - { - base->set_member(as_array_object::index_name(i), as_value()); - } - a->m_length = old_len - (del - ins); - } - for (int i = 0; i < ins; i++) - { - a->set_element(start + i, fn.arg(2 + i)); + log_error("Array::splice needs atleast two arguments\n"); + return; } - fn.result->set_as_object_interface(removed.get_ptr()); + as_array_object* a = array_this(fn); + int start = bf2x87::toIntTruncate(fn.arg(0).to_number()); + if (start >= a->m_elements.size()) start = a->m_elements.size() - 1; + int count = bf2x87::toIntTruncate(fn.arg(1).to_number()); + // LEA at 0x1009C9E2 adds in a 32-bit register before the signed comparison. + const Uint32 end_bits = static_cast(start) + static_cast(count); + int end; + memcpy(&end, &end_bits, sizeof(end)); + if (end > a->m_elements.size()) + count = bf2x87::lowWord(static_cast(a->m_elements.size()) - start); + for (int i = 0; i < count; ++i) a->m_elements.remove(start); + for (int i = 2; i < fn.nargs; ++i) a->m_elements.insert(start++, fn.arg(i)); } void array_concat(const fn_call& fn) { + // SwiffPlayer.dll 0x1009C770 expects an Array receiver and Array arguments. as_array_object* a = array_this(fn); - if (a == NULL) return; + IF_VERBOSE_ACTION(log_msg("-- Array join \n")); smart_ptr r = new as_array_object; - for (int i = 0; i < a->m_length; i++) + for (int k = 0; k < fn.nargs + 1; ++k) { - r->set_element(r->m_length, a->get_element(i)); - } - for (int k = 0; k < fn.nargs; k++) - { - as_object* o = fn.arg(k).to_object() ? fn.arg(k).to_object()->cast_to_as_object() : NULL; - as_value len; - if (o && o->get_member("length", &len) && len.get_type() == as_value::NUMBER - && o->get_member("push", &len)) - { - // another array: flatten one level - as_array_object* b = static_cast(o); - for (int i = 0; i < b->m_length; i++) - { - r->set_element(r->m_length, b->get_element(i)); - } - } - else - { - r->set_element(r->m_length, fn.arg(k)); - } + as_array_object* source = a; + if (k != 0) source = static_cast( + fn.arg(k - 1).get_type() == as_value::OBJECT ? fn.arg(k - 1).m_object_value : NULL); + for (int i = 0; i < source->m_elements.size(); ++i) + r->m_elements.push_back(source->get_element(i)); } fn.result->set_as_object_interface(r.get_ptr()); } + static int array_compare(const void* left, const void* right) + { + // SwiffPlayer.dll 0x1009C1A0 converts the right operand first. + const char* rhs = static_cast(right)->to_string(); + const char* lhs = static_cast(left)->to_string(); + // [CHOSEN, not recovered] S3 bridge: native CRT case mapping/locale remains in use. + return _stricmp(lhs, rhs); + } + void array_sort(const fn_call& fn) { + // SwiffPlayer.dll 0x1009C1D0 ignores arguments and leaves the result untouched. as_array_object* a = array_this(fn); - if (a == NULL) return; - if (fn.nargs > 0 && (fn.arg(0).to_as_function() || fn.arg(0).to_c_function())) - { - log_error("Array.sort: a compare function is not supported yet; sorting as strings\n"); - } - // Insertion sort on the string forms (the AS default ordering). - for (int i = 1; i < a->m_length; i++) - { - as_value key = a->get_element(i); - const tu_string ks = key.to_tu_string(); - int j = i - 1; - while (j >= 0 && a->get_element(j).to_tu_string() > ks) - { - a->set_element(j + 1, a->get_element(j)); - j--; - } - a->set_element(j + 1, key); - } - fn.result->set_as_object_interface(a); + qsort(a->m_elements.size() ? &a->m_elements[0] : NULL, + a->m_elements.size(), sizeof(as_value), array_compare); } @@ -609,80 +661,107 @@ namespace gameswf // as_as_function // - void as_as_function::operator()(const fn_call& fn) - // Dispatch. + // [CHOSEN, not recovered] S3 bridge: functions are not native object-interface + // subclasses. This adapter exposes retail's separate static bag and prototype. + struct function_properties : public as_object { - as_environment* our_env = m_env; - if (our_env == NULL) + function_properties() { - our_env = fn.env; + m_members.clear(); + m_instance_prototype = new as_object; + m_instance_prototype->add_ref(); } - assert(our_env); - // [DICE-MOD SwiffPlayer: bind `this` and `super` for this call. `this` is the object the - // caller passed (the shipped dispatch, sub_10095840, preloads its a3 argument), falling - // back to the target movie only when none was given. `super` is this function's own - // superclass constructor - the __constructor__ that ActionExtends left on its prototype - - // which is what the shipped CallMethod hands the callee when a function value is called - // directly (super()). Both live in the environment for the duration of the call, restored - // on every exit path.] - as_object_interface* this_obj = fn.this_ptr ? fn.this_ptr : static_cast(our_env->m_target); - as_as_function* super_fn = NULL; - if (m_properties) - { - // A class constructor: its own prototype carries the __constructor__ ActionExtends left. - as_value proto_val; - m_properties->get_member("prototype", &proto_val); - as_object_interface* proto = proto_val.to_object(); - if (proto) + virtual bool get_member(const tu_stringi& name, as_value* val) + { + // SwiffPlayer.dll 0x1008E8E0: static members precede prototype lookup. + if (strcmp(name.c_str(), "prototype") == 0) { - as_value ctor_val; - if (proto->get_member("__constructor__", &ctor_val)) - { - super_fn = ctor_val.to_as_function(); - } + val->set_as_object_interface(m_instance_prototype); + return true; } + stringi_hash::const_iterator member = m_members.find(name); + if (member != m_members.end()) + { + if (val) *val = member.get_value().m_value; + return true; + } + return m_instance_prototype && m_instance_prototype->get_member(name, val); } - if (super_fn == NULL && m_home_object != NULL) + + virtual void set_member(const tu_stringi& name, const as_value& val) { - // [DICE-MOD SwiffPlayer #30] A method: the prototype it was defined on knows its parent. - as_value ctor_val; - as_member own; - if (m_home_object->m_members.get("__constructor__", &own)) + // SwiffPlayer.dll 0x10091CA0 accepts only OBJECT for a new prototype. + if (strcmp(name.c_str(), "prototype") == 0) { - super_fn = own.get_member_value().to_as_function(); + as_object_interface* proto = val.get_type() == as_value::OBJECT ? val.m_object_value : NULL; + // [CHOSEN, not recovered] S3 bridge: retain native ownership of this link. + if (proto) proto->add_ref(); + if (m_instance_prototype) m_instance_prototype->drop_ref(); + m_instance_prototype = proto; + return; } + m_members.set(name, as_member(val)); } - struct call_binding_scope + }; + + as_as_function::as_as_function(action_buffer* ab, as_environment* env, int start, + const array& with_stack) + : m_action_buffer(ab), m_env(env), m_with_stack(with_stack), m_start_pc(start), + m_length(0), m_is_function2(false), m_local_register_count(0), m_function2_flags(0), + m_properties(new function_properties) + { + // SwiffPlayer.dll 0x1008E870 eagerly creates the prototype object. + // [CHOSEN, not recovered] S3 bridge: m_properties includes the function adapter. + m_properties->add_ref(); + assert(m_action_buffer); + } + + void as_as_function::lazy_create_properties() + { + // [CHOSEN, not recovered] S3 bridge for existing native callers; construction + // now creates the retail prototype eagerly. Never recreate a script-cleared prototype. + assert(m_properties); + } + + void as_as_function::set_function2_flags(uint16 flags) + { + // SwiffPlayer.dll 0x10094BDD-0x10094D80 builds this map in declaration order. + // The native setter adapts the retained flags interface to that storage. + assert(m_is_function2); + m_function2_flags = flags; + m_preload_registers.clear(); + int reg = 1; + if (flags & 0x01) m_preload_registers.set(reg++, tu_string("this")); + if (flags & 0x04) m_preload_registers.set(reg++, tu_string("arguments")); + if (flags & 0x10) m_preload_registers.set(reg++, tu_string("super")); + if (flags & 0x40) m_preload_registers.set(reg++, tu_string("_root")); + if (flags & 0x80) m_preload_registers.set(reg++, tu_string("_parent")); + if (flags & 0x100) m_preload_registers.set(reg++, tu_string("_global")); + } + + void as_as_function::operator()(const fn_call& fn) + // Dispatch. + { + as_environment* our_env = m_env; + if (our_env == NULL) { - as_environment* m_e; - as_object_interface* m_saved_this; - as_as_function* m_saved_super; - ~call_binding_scope() { m_e->m_this_object = m_saved_this; m_e->m_super_ctor = m_saved_super; } - }; - call_binding_scope binding_scope = { our_env, our_env->m_this_object, our_env->m_super_ctor }; - our_env->m_this_object = this_obj; - our_env->m_super_ctor = super_fn; + our_env = fn.env; + } + assert(our_env); - // Set up local stack frame, for parameters and locals. + // SwiffPlayer.dll 0x10095790 / 0x10095840 binds the exact receiver. Super + // belongs to call_method's saved environment slot, not to the function's first owner. + as_object_interface* this_obj = fn.this_ptr; + // SwiffPlayer.dll 0x10095840 does not add a local frame for function2. int local_stack_top = our_env->get_local_frame_top(); - our_env->add_function_barrier(); // [DICE-MOD SwiffPlayer #41] a marked barrier - see in_function_frame() - - // [DICE-MOD SwiffPlayer #57] The register bank a call borrows is the CALLER's. The shipped - // DefineFunction2 and DefineFunction (execute cases 142 / 155) construct every function with a - // NULL environment (0x10094AEA pushes 0 as the ctor's env; sub_1008E870 stores it at +0x10), - // and the dispatch (sub_10095840) runs the body in that m_env or, when it is NULL, in the - // environment the caller passed - so every function runs in its caller's environment, on the - // caller's registers. This port keeps the DEFINING environment for scope (the stock 2006 - // model; the open item under #55 in GAMESWF_DIVERGENCES.md) and borrows only the calling - // chain's bank for the call. Without it every class method - defined by the root's DoInitAction - // code - ran on the ROOT's bank: the `dice.UI` constructor (mainMenu.swf sprite 5, - // `function UI(cancelInit)`, cancelInit in r3) is called by the load path with no argument in - // the new clip's own environment (sub_10081870 -> sub_1008EAA0(this + 288, ...)), where r3 is - // undefined; here it read whatever root code had left in r3, and a truthy value skipped - // init/draw/attachChildren/arrange/setEvents - the component kept its grey authoring box - // (mcBoundingBox) and never built its parts (the owner's login page, 2026-09-29: grey bars for - // PREFIX, the password rows and the LOG IN button). + // The ordinary dispatch at 0x10095790 also appends arguments without a barrier. + + // [CHOSEN, not recovered] S3 bridge: explicitly captured native functions still borrow + // the calling register bank. Declarations at 0x10094AEA/0x100952C9 capture no environment. + // [RETIRE-WHEN: swf-s3-call-environment] Replace the native capture/register-bank + // and per-tree-root adapters with the recovered owners, then validate nested + // menu calls, LAN CREATE callbacks and registers through real movie execution. as_environment* call_bank = (fn.env ? fn.env : our_env)->register_bank(); struct register_bank_scope { @@ -693,7 +772,7 @@ namespace gameswf register_bank_scope bank_scope = { our_env, our_env->m_register_env }; our_env->m_register_env = (call_bank == our_env) ? NULL : call_bank; - // [DICE-MOD SwiffPlayer #55] A DefineFunction2 call borrows the environment's register bank + // A DefineFunction2 call borrows the environment's register bank // instead of pushing fresh registers. The shipped dispatch (sub_10095840) copies r0..r9 aside // (a fixed ten, whatever the function's RegisterCount), writes each declared argument the // caller actually passed into its register, writes the preloads, runs the body, and copies @@ -730,126 +809,57 @@ namespace gameswf else { // function2: most args go in registers; any others get pushed. - // [DICE-MOD SwiffPlayer #55] no fresh registers - the environment's bank, saved above. + // no fresh registers - the environment's bank, saved above. - // Handle the explicit args. [DICE-MOD #55: the shipped loop writes each declared argument + // Handle the explicit args. the shipped loop writes each declared argument // the caller passed into ITS register, register 0 included - it never makes a named local - // of a function2 argument. No stock movie declares one without a register.] + // of a function2 argument. No stock movie declares one without a register. int args_to_pass = imin(fn.nargs, m_args.size()); for (int i = 0; i < args_to_pass; i++) { *(our_env->register_ptr(m_args[i].m_register)) = fn.arg(i); } - // Handle the implicit args. - int current_reg = 1; - if (m_function2_flags & 0x01) - { - // preload 'this' into a register. [DICE-MOD: the bound this-object, see above] - (*(our_env->register_ptr(current_reg))).set_as_object_interface(this_obj); - current_reg++; - } - - if (m_function2_flags & 0x02) + // SwiffPlayer.dll 0x100958FB-0x10096136 visits the register/name hash. + for (hash::const_iterator it = m_preload_registers.begin(); + it != m_preload_registers.end(); ++it) { - // Don't put 'this' into a local var. - } - else - { - // Put 'this' in a local var. [DICE-MOD: the bound this-object, see above] - our_env->add_local("this", as_value(this_obj)); - } - - // Init arguments array, if it's going to be needed. - smart_ptr arg_array; - if ((m_function2_flags & 0x04) || ! (m_function2_flags & 0x08)) - { - arg_array = new as_array_object; - - as_value index_number; - for (int i = 0; i < fn.nargs; i++) + const int reg = it.get_key(); + const tu_string name = it.get_value(); + if (name == "this") + *our_env->register_ptr(reg) = as_value(this_obj); + else if (name == "arguments") + *our_env->register_ptr(reg) = as_value("arguments unimplemented"); + else if (name == "super") + *our_env->register_ptr(reg) = as_value(our_env->m_super_ctor); + else if (name == "_root") { - index_number.set_int(i); - arg_array->set_member(index_number.to_string(), fn.arg(i)); + // SwiffPlayer.dll 0x10095D59 publishes even a null OBJECT. + *our_env->register_ptr(reg) = as_value(get_global_root_movie()); } - } - - if (m_function2_flags & 0x04) - { - // preload 'arguments' into a register. - (*(our_env->register_ptr(current_reg))).set_as_object_interface(arg_array.get_ptr()); - current_reg++; - } - - if (m_function2_flags & 0x08) - { - // Don't put 'arguments' in a local var. - } - else - { - // Put 'arguments' in a local var. - our_env->add_local("arguments", as_value(arg_array.get_ptr())); - } - - if (m_function2_flags & 0x10) - { - // Put 'super' in a register. [DICE-MOD: the superclass constructor bound above - - // the shipped dispatch preloads its env slot +8216 as an AS_FUNCTION value] - if (super_fn) - { - (*(our_env->register_ptr(current_reg))) = as_value(super_fn); - } - else + else if (name == "_parent") + *our_env->register_ptr(reg) = as_value("_parent unimplemented"); + else if (name == "_global") { - (*(our_env->register_ptr(current_reg))) = as_value(); + as_value global; + s_modules.get("_global", &global); + *our_env->register_ptr(reg) = global; } - current_reg++; - } - - if (m_function2_flags & 0x20) - { - // Don't put 'super' in a local var. - } - else - { - // Put 'super' in a local var. [DICE-MOD: see above] - our_env->add_local("super", super_fn ? as_value(super_fn) : as_value()); - } - - if (m_function2_flags & 0x40) - { - // Put '_root' in a register. - (*(our_env->register_ptr(current_reg))).set_as_object_interface( - our_env->m_target->get_root_movie()); - current_reg++; - } - - if (m_function2_flags & 0x80) - { - // Put '_parent' in a register. - array dummy; - as_value parent = our_env->get_variable("_parent", dummy); - (*(our_env->register_ptr(current_reg))) = parent; - current_reg++; - } - - if (m_function2_flags & 0x100) - { - // Put '_global' in a register. - (*(our_env->register_ptr(current_reg))).set_as_object_interface(s_global.get_ptr()); - current_reg++; } } // Execute the actions. + as_object_interface* saved_this = our_env->m_this_object; + our_env->m_this_object = this_obj; m_action_buffer->execute(our_env, m_start_pc, m_length, fn.result, m_with_stack, m_is_function2); // Clean up stack frame. - our_env->set_local_frame_top(local_stack_top); + if (!m_is_function2) our_env->set_local_frame_top(local_stack_top); + our_env->m_this_object = saved_this; if (m_is_function2) { - // [DICE-MOD SwiffPlayer #55] r0..r9 back as they were before the call - the shipped + // r0..r9 back as they were before the call - the shipped // dispatch's closing copy. Registers the body wrote above r9 stay written. for (int r = 0; r < 10; r++) { @@ -874,6 +884,11 @@ namespace gameswf // Subsequent arguments are at *lower* indices. E.g. if first_arg_bottom_index = 7, // then arg1 is at env->bottom(7), arg2 is at env->bottom(6), etc. { + // SwiffPlayer.dll 0x1008E990 installs the lookup's context for this call, + // restoring the environment slot before copying the result to the caller. + // [CHOSEN, not recovered] S3 bridge: native Key listeners still allow a null environment. + as_as_function* saved_super = env ? env->m_super_ctor : NULL; + if (env) env->m_super_ctor = s_call_super; as_value val; as_c_function_ptr func = method.to_c_function(); @@ -892,6 +907,7 @@ namespace gameswf log_error("error in call_method(): method is not a function\n"); } + if (env) env->m_super_ctor = saved_super; return val; } @@ -901,200 +917,87 @@ namespace gameswf as_environment* env, as_object_interface* this_ptr) { + // SwiffPlayer.dll 0x1008EAA0: zero arguments, first index is the operand count. return call_method(method, env, this_ptr, 0, env->get_top_index() + 1); } - const char* call_method_parsed( - as_environment* env, - as_object_interface* this_ptr, - const char* method_name, - const char* method_arg_fmt, - va_list args) - // Printf-like vararg interface for calling ActionScript. - // Handy for external binding. + const char* call_method_expression(as_environment* env, as_object_interface* receiver, + const char* expression) { - log_msg("FIXME(%d): %s\n", __LINE__, __FUNCTION__); - -#if 0 - static const int BUFSIZE = 1000; - char buffer[BUFSIZE]; - array tokens; - - // Brutal crap parsing. Basically null out any - // delimiter characters, so that the method name and - // args sit in the buffer as null-terminated C - // strings. Leave an intial ' character as the first - // char in a string argument. - // Don't verify parens or matching quotes or anything. - { - strncpy(buffer, method_call, BUFSIZE); - buffer[BUFSIZE - 1] = 0; - char* p = buffer; - - char in_quote = 0; - bool in_arg = false; - for (;; p++) + // SwiffPlayer.dll 0x10092220: tokenization precedes lookup and argument pushes. + char text[1000]; + strncpy(text, expression, sizeof(text)); + text[sizeof(text) - 1] = 0; + array tokens; + char quote = 0; + bool in_token = false; + for (char* cursor = text; *cursor; ++cursor) + { + const char c = *cursor; + if (c == quote) { - char c = *p; - if (c == 0) - { - // End of string. - break; - } - else if (c == in_quote) + *cursor = 0; + quote = 0; + in_token = false; + } + else if (in_token) + { + if (quote == 0 && (c == ')' || c == '(' || c == ',' || c == ' ')) { - // End of quotation. - assert(in_arg); - *p = 0; - in_quote = 0; - in_arg = false; - } - else if (in_arg) - { - if (in_quote == 0) - { - if (c == ')' || c == '(' || c == ',' || c == ' ') - { - // End of arg. - *p = 0; - in_arg = false; - } - } - } - else - { - // Not in arg. Watch for start of arg. - assert(in_quote == 0); - if (c == '\'' || c == '\"') - { - // Start of quote. - in_quote = c; - in_arg = true; - *p = '\''; // ' at the start of the arg, so later we know this is a string. - tokens.push_back(p); - } - else if (c == ' ' || c == ',') - { - // Non-arg junk, null it out. - *p = 0; - } - else - { - // Must be the start of a numeric arg. - in_arg = true; - tokens.push_back(p); - } + *cursor = 0; + in_token = false; } } - } -#endif // 0 - - - // Parse va_list args - int starting_index = env->get_top_index(); - const char* p = method_arg_fmt; - for (;; p++) - { - char c = *p; - if (c == 0) + else if (c == '\'' || c == '"') { - // End of args. - break; + quote = c; + *cursor = '\''; + tokens.push_back(cursor); + in_token = true; } - else if (c == '%') + else if (c == ' ' || c == ',') { - p++; - c = *p; - // Here's an arg. - if (c == 'd') - { - // Integer. - env->push(va_arg(args, int)); - } - else if (c == 'f') - { - // Double - env->push(va_arg(args, double)); - } - else if (c == 's') - { - // String - env->push(va_arg(args, const char *)); - } - else if (c == 'l') - { - p++; - c = *p; - if (c == 's') - { - // Wide string. - env->push(va_arg(args, const wchar_t *)); - } - else - { - log_error("call_method_parsed('%s','%s') -- invalid fmt '%%l%c'\n", - method_name, - method_arg_fmt, - c); - } - } - else - { - // Invalid fmt, warn. - log_error("call_method_parsed('%s','%s') -- invalid fmt '%%%c'\n", - method_name, - method_arg_fmt, - c); - } + *cursor = 0; } else { - // Ignore whitespace and commas. - if (c == ' ' || c == '\t' || c == ',') - { - // OK - } - else - { - // Invalid arg; warn. - log_error("call_method_parsed('%s','%s') -- invalid char '%c'\n", - method_name, - method_arg_fmt, - c); - } + tokens.push_back(cursor); + in_token = true; } } - array dummy_with_stack; - as_value method = env->get_variable(method_name, dummy_with_stack); - - // check method - - // Reverse the order of pushed args - int nargs = env->get_top_index() - starting_index; - for (int i = 0; i < (nargs >> 1); i++) + array with_stack; + as_value method = env->get_variable(tu_string(tokens[0]), with_stack); + const int nargs = tokens.size() - 1; + for (int i = nargs; i > 0; --i) { - int i0 = starting_index + 1 + i; - int i1 = starting_index + nargs - i; - assert(i0 < i1); - - swap(&(env->bottom(i0)), &(env->bottom(i1))); + const char* argument = tokens[i]; + if (*argument == '\'') env->push(argument + 1); + else env->push(atof(argument)); } - - // Do the call. - as_value result = call_method(method, env, this_ptr, nargs, env->get_top_index()); + as_value result = call_method(method, env, receiver, nargs, env->get_top_index()); env->drop(nargs); + static tu_string result_text; + result_text = result.to_tu_string(); + return result_text.c_str(); + } - // Return pointer to static string for return value. - static tu_string s_retval; - s_retval = result.to_tu_string(); - return s_retval.c_str(); + const char* call_method_expression(as_environment* env, as_object_interface* receiver, + const Uint16* expression) + { + // SwiffPlayer.dll 0x100924F0 converts UTF-16 before calling the narrow parser. + tu_string narrow(expression); + return call_method_expression(env, receiver, narrow.c_str()); } // // sound object // + // The three method bodies below exist in SwiffPlayer.dll (0x1008A1B0, + // 0x1008A1F0, 0x1008C6E0) but nothing in the image references them: retail + // registers no Sound class (action_init 0x10090FF0), so scripts cannot reach + // them. They are kept as recovered bodies, equally unreferenced here. struct sound_as_object : public as_object { @@ -1102,26 +1005,24 @@ namespace gameswf int sound_id; }; - void movie_load() - { - IF_VERBOSE_ACTION(log_msg("-- start movie \n")); - } void sound_start(const fn_call& fn) { + // SwiffPlayer.dll 0x1008A1B0: handler lookup/guard precedes receiver access. IF_VERBOSE_ACTION(log_msg("-- start sound \n")); sound_handler* s = get_sound_handler(); if (s != NULL) { sound_as_object* so = (sound_as_object*) (as_object*) fn.this_ptr; assert(so); - s->play_sound(so->sound_id, 0); + s->play_sound(so->sound_id, 1); } } void sound_stop(const fn_call& fn) { + // SwiffPlayer.dll 0x1008A1F0: arguments and result are untouched. IF_VERBOSE_ACTION(log_msg("-- stop sound \n")); sound_handler* s = get_sound_handler(); if (s != NULL) @@ -1134,6 +1035,8 @@ namespace gameswf void sound_attach(const fn_call& fn) { + // SwiffPlayer.dll 0x1008C6E0: refusal precedes name conversion/import lookup; + // only a sound resource changes sound_id, and the result slot is untouched. IF_VERBOSE_ACTION(log_msg("-- attach sound \n")); if (fn.nargs < 1) { @@ -1146,7 +1049,8 @@ namespace gameswf so->sound = fn.arg(0).to_tu_string(); - // check the import. + // [CHOSEN, not recovered] S3 bridge: resolve the process-global root read + // at 0x1008C733 through this native movie tree instead. movie_definition_sub* def = (movie_definition_sub*) fn.env->get_target()->get_root_movie()->get_movie_definition(); assert(def); @@ -1204,18 +1108,48 @@ namespace gameswf } #endif - MATH_WRAP_FUNC1(fabs); - MATH_WRAP_FUNC1(acos); - MATH_WRAP_FUNC1(asin); - MATH_WRAP_FUNC1(atan); - MATH_WRAP_FUNC1(ceil); - MATH_WRAP_FUNC1(cos); - MATH_WRAP_FUNC1(exp); - MATH_WRAP_FUNC1(floor); - MATH_WRAP_FUNC1(log); - MATH_WRAP_FUNC1(sin); - MATH_WRAP_FUNC1(sqrt); - MATH_WRAP_FUNC1(tan); + MATH_WRAP_FUNC1(fabs); // SwiffPlayer.dll 0x1008C7D0. + MATH_WRAP_FUNC1(acos); // SwiffPlayer.dll 0x1008C830. + MATH_WRAP_FUNC1(asin); // SwiffPlayer.dll 0x1008C890. + MATH_WRAP_FUNC1(atan); // SwiffPlayer.dll 0x1008C8F0. + MATH_WRAP_FUNC1(ceil); // SwiffPlayer.dll 0x1008C950. + MATH_WRAP_FUNC1(floor); // SwiffPlayer.dll 0x1008CA90. + MATH_WRAP_FUNC1(log); // SwiffPlayer.dll 0x1008CB00. + MATH_WRAP_FUNC1(sqrt); // SwiffPlayer.dll 0x1008CBC0. + MATH_WRAP_FUNC1(tan); // SwiffPlayer.dll 0x1008CC20. + + void math_cos(const fn_call& fn) + { + // SwiffPlayer.dll 0x1008C9C0: FCOS leaves finite |x| >= 2^63 unchanged. + const double arg = fn.arg(0).to_number(); + // [CHOSEN, not recovered] S3 bridge: retain the native math library for + // in-range arguments; its argument reduction/rounding is not x87-exact. + const double result = isfinite(arg) && fabs(arg) >= 9223372036854775808.0 + ? arg : cos(arg); + fn.result->set_double(result); + } + + void math_exp(const fn_call& fn) + { + // SwiffPlayer.dll 0x1008CA20: the x87 reduction subtracts infinity from + // itself, so either infinity produces NaN rather than exp's limit value. + const double arg = fn.arg(0).to_number(); + // [CHOSEN, not recovered] S3 bridge: finite results still use the native + // math library rather than the retail F2XM1/FSCALE precision contract. + const double result = isfinite(arg) ? exp(arg) : arg - arg; + fn.result->set_double(result); + } + + void math_sin(const fn_call& fn) + { + // SwiffPlayer.dll 0x1008CB60: FSIN leaves finite |x| >= 2^63 unchanged. + const double arg = fn.arg(0).to_number(); + // [CHOSEN, not recovered] S3 bridge: retain the native math library for + // in-range arguments; its argument reduction/rounding is not x87-exact. + const double result = isfinite(arg) && fabs(arg) >= 9223372036854775808.0 + ? arg : sin(arg); + fn.result->set_double(result); + } #if 0 // Two-argument functions. @@ -1236,19 +1170,20 @@ namespace gameswf fn.result->set_double(expr); \ } #endif - MATH_WRAP_FUNC2_EXP(atan2, (atan2(arg0, arg1))); - MATH_WRAP_FUNC2_EXP(max, (arg0 > arg1 ? arg0 : arg1)); - MATH_WRAP_FUNC2_EXP(min, (arg0 < arg1 ? arg0 : arg1)); - MATH_WRAP_FUNC2_EXP(pow, (pow(arg0, arg1))); + MATH_WRAP_FUNC2_EXP(atan2, (atan2(arg0, arg1))); // SwiffPlayer.dll 0x1008CC80. + MATH_WRAP_FUNC2_EXP(max, (arg0 > arg1 ? arg0 : arg1)); // SwiffPlayer.dll 0x1008CCF0. + MATH_WRAP_FUNC2_EXP(min, (arg0 < arg1 ? arg0 : arg1)); // SwiffPlayer.dll 0x1008CD70. + MATH_WRAP_FUNC2_EXP(pow, (pow(arg0, arg1))); // SwiffPlayer.dll 0x1008CDF0. // A couple of oddballs. void math_random(const fn_call& fn) { - // Random number between 0 and 1. - fn.result->set_double(tu_random::next_random() / double(Uint32(0x0FFFFFFFF))); + // SwiffPlayer.dll 0x1008AB80 multiplies the unsigned generator result. + fn.result->set_double(double(tu_random::next_random()) * 2.3283064370807974e-10); } void math_round(const fn_call& fn) { + // SwiffPlayer.dll 0x1008CE70. // round argument to nearest int. double arg0 = fn.arg(0).to_number(); fn.result->set_double(floor(arg0 + 0.5)); @@ -1256,7 +1191,8 @@ namespace gameswf void math_init() { - // Create built-in math object. + // SwiffPlayer.dll 0x1008EB30: constants and methods in registration order. + // [CHOSEN, not recovered] Native object storage for the module value. as_object* math_obj = new as_object; // constant @@ -1290,13 +1226,10 @@ namespace gameswf math_obj->set_member("min", &math_min); math_obj->set_member("pow", &math_pow); - s_global->set_member("math", math_obj); + // SwiffPlayer.dll 0x1008F7ED publishes into the module table. + s_modules.set("math", as_value(math_obj)); } - void event_test(const fn_call& fn) - { - log_msg("FIXME: %s\n", __FUNCTION__); - } // // key object @@ -1305,14 +1238,22 @@ namespace gameswf struct key_as_object : public as_object { + // SwiffPlayer.dll 0x1008F900/0x1008FAB0 accepts codes 0 through 223. + enum { RETAIL_KEY_COUNT = 224 }; Uint8 m_keymap[key::KEYCOUNT / 8 + 1]; // bit-array array > m_listeners; int m_last_key_pressed; + // SwiffPlayer.dll 0x10092580 destroys listeners before members; + // 0x10092550 is its deleting veneer. [CHOSEN, not recovered] S3 bridge: + // implicit destruction uses the native weak listeners and as_object base. key_as_object() : m_last_key_pressed(0) { + // SwiffPlayer.dll 0x1008F850: empty listeners, key bitmap and last key. + // [CHOSEN, not recovered] S3 bridge: native weak-listener storage and + // the legacy bitmap capacity; only codes 0..223 are notified by retail. memset(m_keymap, 0, sizeof(m_keymap)); } @@ -1338,7 +1279,9 @@ namespace gameswf void set_key_down(int code) { - if (code < 0 || code >= key::KEYCOUNT) return; + // SwiffPlayer.dll 0x1008F900: update state before visiting the saved count. + // [CHOSEN, not recovered] S3 bridge: native weak/strong listener ownership. + if (code < 0 || code >= RETAIL_KEY_COUNT) return; m_last_key_pressed = code; @@ -1367,7 +1310,9 @@ namespace gameswf void set_key_up(int code) { - if (code < 0 || code >= key::KEYCOUNT) return; + // SwiffPlayer.dll 0x1008FAB0: release does not change the last pressed code. + // [CHOSEN, not recovered] S3 bridge: native weak/strong listener ownership. + if (code < 0 || code >= RETAIL_KEY_COUNT) return; int byte_index = code >> 3; int bit_index = code - (byte_index << 3); @@ -1396,6 +1341,7 @@ namespace gameswf // we use weak_ptr's, listeners can disappear without // notice.) { + // SwiffPlayer.dll 0x1008D700: remove expired entries backwards. for (int i = m_listeners.size() - 1; i >= 0; i--) { if (m_listeners[i] == NULL) @@ -1407,6 +1353,7 @@ namespace gameswf void add_listener(as_object_interface* listener) { + // SwiffPlayer.dll 0x1008D760: clean, reject duplicates, then append weakly. cleanup_listeners(); for (int i = 0, n = m_listeners.size(); i < n; i++) @@ -1423,6 +1370,7 @@ namespace gameswf void remove_listener(as_object_interface* listener) { + // SwiffPlayer.dll 0x1008D840: clean, then erase every match backwards. cleanup_listeners(); for (int i = m_listeners.size() - 1; i >= 0; i--) @@ -1434,6 +1382,7 @@ namespace gameswf } } + // SwiffPlayer.dll 0x1008A270. int get_last_key_pressed() const { return m_last_key_pressed; } }; @@ -1443,13 +1392,15 @@ namespace gameswf // Listeners will have "onKeyDown" and "onKeyUp" methods // called on them when a key changes state. { + // SwiffPlayer.dll 0x1008D8B0 accepts OBJECT only, not script functions. if (fn.nargs < 1) { log_error("key_add_listener needs one argument (the listener object)\n"); return; } - as_object_interface* listener = fn.arg(0).to_object(); + as_object_interface* listener = fn.arg(0).get_type() == as_value::OBJECT + ? fn.arg(0).m_object_value : NULL; if (listener == NULL) { log_error("key_add_listener passed a NULL object; ignored\n"); @@ -1465,6 +1416,7 @@ namespace gameswf void key_get_ascii(const fn_call& fn) // Return the ascii value of the last key pressed. { + // SwiffPlayer.dll 0x1008B2F0. key_as_object* ko = (key_as_object*) (as_object*) fn.this_ptr; assert(ko); @@ -1485,6 +1437,7 @@ namespace gameswf void key_get_code(const fn_call& fn) // Returns the keycode of the last key pressed. + // SwiffPlayer.dll 0x1008AC00. { key_as_object* ko = (key_as_object*) (as_object*) fn.this_ptr; assert(ko); @@ -1492,8 +1445,30 @@ namespace gameswf fn.result->set_int(ko->get_last_key_pressed()); } + static async_key_state_callback s_async_key_state_callback = NULL; + + void set_async_key_state_callback(async_key_state_callback callback) + { + s_async_key_state_callback = callback; + } + + // SwiffPlayer.dll 0x1008A230. Only Enter queries (and consumes) OS state. + bool is_key_down(int code) + { + if (code < 0 || code >= 224 || code != 13) return false; + if (s_async_key_state_callback) return s_async_key_state_callback(code) == 0x8001; +#if defined(_WIN32) + return static_cast(GetAsyncKeyState(code)) == 0x8001; +#else + // [CHOSEN, not recovered] Outside Windows the key state comes only from the host adapter, + // which SwiffPlayer installs when it initializes (the macOS client is the one POSIX client + // that builds SwiffPlayer). With no adapter installed (a bare test harness) Enter reads up. + return false; +#endif + } + void key_is_down(const fn_call& fn) - // Return true if the specified (first arg keycode) key is pressed. + // Publishes whether Enter is held with a press since the previous query. { if (fn.nargs < 1) { @@ -1501,32 +1476,31 @@ namespace gameswf return; } - int code = (int) fn.arg(0).to_number(); - - key_as_object* ko = (key_as_object*) (as_object*) fn.this_ptr; - assert(ko); - - fn.result->set_bool(ko->is_key_down(code)); + // SwiffPlayer.dll 0x1008CEE0: FISTP truncation, then Enter edge query. + const int code = bf2x87::toIntTruncate(fn.arg(0).to_number()); + fn.result->set_bool(is_key_down(code)); } void key_is_toggled(const fn_call& fn) // Given the keycode of NUM_LOCK or CAPSLOCK, returns true if // the associated state is on. { - // @@ TODO + // SwiffPlayer.dll 0x1008AC10 always publishes false. fn.result->set_bool(false); } void key_remove_listener(const fn_call& fn) // Remove a previously-added listener. { + // SwiffPlayer.dll 0x1008D900 accepts OBJECT only, not script functions. if (fn.nargs < 1) { log_error("key_remove_listener needs one argument (the listener object)\n"); return; } - as_object_interface* listener = fn.arg(0).to_object(); + as_object_interface* listener = fn.arg(0).get_type() == as_value::OBJECT + ? fn.arg(0).m_object_value : NULL; if (listener == NULL) { log_error("key_remove_listener passed a NULL object; ignored\n"); @@ -1542,7 +1516,8 @@ namespace gameswf void key_init() { - // Create built-in key object. + // SwiffPlayer.dll 0x1008FC50: constants and methods in registration order. + // [CHOSEN, not recovered] S3 bridge: use the current native Key/global bags. as_object* key_obj = new key_as_object; // constants @@ -1565,6 +1540,16 @@ namespace gameswf KEY_CONST(SPACE); KEY_CONST(TAB); KEY_CONST(UP); + KEY_CONST(_0); + KEY_CONST(_1); + KEY_CONST(_2); + KEY_CONST(_3); + KEY_CONST(_4); + KEY_CONST(_5); + KEY_CONST(_6); + KEY_CONST(_7); + KEY_CONST(_8); + KEY_CONST(_9); // methods key_obj->set_member("addListener", &key_add_listener); @@ -1574,7 +1559,48 @@ namespace gameswf key_obj->set_member("isToggled", &key_is_toggled); key_obj->set_member("removeListener", &key_remove_listener); - s_global->set_member("Key", key_obj); + // SwiffPlayer.dll 0x10090CA1 publishes into the module table. + s_modules.set("Key", as_value(key_obj)); + } + + void add_key_listener(as_object_interface* listener) + { + // SwiffPlayer.dll 0x10090D00: hold the module value through the call; OBJECT only. + static const tu_string name("Key"); + as_value module; + s_modules.get(name, &module); + if (module.get_type() == as_value::OBJECT) + { + // [CHOSEN, not recovered] S3 bridge: adjust the native object interface. + static_cast(module.m_object_value->cast_to_as_object())->add_listener(listener); + } + } + + void remove_key_listener(as_object_interface* listener) + { + // SwiffPlayer.dll 0x10090DF0: no initialization or fallback to _global.Key. + static const tu_string name("Key"); + as_value module; + s_modules.get(name, &module); + if (module.get_type() == as_value::OBJECT) + { + // [CHOSEN, not recovered] S3 bridge: adjust the native object interface. + static_cast(module.m_object_value->cast_to_as_object())->remove_listener(listener); + } + } + + int get_last_key_pressed() + { + // SwiffPlayer.dll 0x10090EE0: absent/non-OBJECT module yields zero. + static const tu_string name("Key"); + as_value module; + s_modules.get(name, &module); + if (module.get_type() == as_value::OBJECT) + { + // [CHOSEN, not recovered] S3 bridge: adjust the native object interface. + return static_cast(module.m_object_value->cast_to_as_object())->get_last_key_pressed(); + } + return 0; } @@ -1586,7 +1612,8 @@ namespace gameswf static tu_string key_obj_name("Key"); as_value kval; - s_global->get_member(key_obj_name, &kval); + // SwiffPlayer.dll 0x10091D40 reads the module, independent of _global.Key. + s_modules.get(key_obj_name, &kval); if (kval.get_type() == as_value::OBJECT) { key_as_object* ko = (key_as_object*) kval.to_object(); @@ -1607,53 +1634,9 @@ namespace gameswf // - void as_global_trace(const fn_call& fn) - { - assert(fn.nargs >= 1); - - // Special case for objects: try the toString() method. - if (fn.arg(0).get_type() == as_value::OBJECT) - { - as_object_interface* obj = fn.arg(0).to_object(); - assert(obj); - - as_value method; - if (obj->get_member("toString", &method) - && method.is_function()) - { - as_value result = call_method0(method, fn.env, obj); - log_msg("%s\n", result.to_string()); - - return; - } - } - - // Log our argument. - // - // @@ what if we get extra args? - // - // @@ Array gets special treatment. - const char* arg0 = fn.arg(0).to_string(); - log_msg("%s\n", arg0); - } - - - void as_global_sound_ctor(const fn_call& fn) - // Constructor for ActionScript class Sound. - { - smart_ptr sound_obj(new sound_as_object); - - // methods - sound_obj->set_member("attachSound", &sound_attach); - sound_obj->set_member("start", &sound_start); - sound_obj->set_member("stop", &sound_stop); - - fn.result->set_as_object_interface(sound_obj.get_ptr()); - } - - void as_global_object_ctor(const fn_call& fn) // Constructor for ActionScript class Object. + // SwiffPlayer.dll 0x1008B180; native storage is the existing as_object bridge. { fn.result->set_as_object_interface(new as_object); } @@ -1661,270 +1644,136 @@ namespace gameswf void as_global_array_ctor(const fn_call& fn) // Constructor for ActionScript class Array. { - smart_ptr ao = new as_array_object; - - if (fn.nargs == 0) - { - // Empty array. - } - else if (fn.nargs == 1 - && fn.arg(0).get_type() == as_value::NUMBER) - { - // Create an empty array with the given number of undefined elements. - // [DICE-MOD: the length is live now] - ao->m_length = (int) fn.arg(0).to_number(); - if (ao->m_length < 0) ao->m_length = 0; - } - else - { - // Use the arguments as initializers. - as_value index_number; - for (int i = 0; i < fn.nargs; i++) - { - index_number.set_int(i); - ao->set_member(index_number.to_string(), fn.arg(i)); - } - - // @@ TODO set length property - } - + // SwiffPlayer.dll 0x1008B1C0: arguments are ignored, unlike array literal 0x42. + // [CHOSEN, not recovered] S3 bridge: retain the native factory/interface convention. + smart_ptr ao(new as_array_object); fn.result->set_as_object_interface(ao.get_ptr()); } - void as_global_assetpropflags(const fn_call& fn) - // ASSetPropFlags function + // SwiffPlayer.dll 0x1008A280 is RET; 0x10090FF0 binds it as ASSetPropFlags. + // It neither inspects arguments nor writes a result or property flags. + void as_global_assetpropflags(const fn_call&) { - const int version = fn.env->get_target()->get_movie_definition()->get_version(); - - // Check the arguments - assert(fn.nargs == 3 || fn.nargs == 4); - assert((version == 5) ? (fn.nargs == 3) : true); - - // object - as_object_interface* const obj = fn.arg(0).to_object(); - assert(obj != NULL); - - // list of child names - as_object_interface* props = fn.arg(1).to_object(); - if (props == NULL) { - // tulrich: this fires in test_ASSetPropFlags -- is it correct? - assert(fn.arg(1).get_type() == as_value::NULLTYPE); - } - - // a number which represents three bitwise flags which - // are used to determine whether the list of child names should be hidden, - // un-hidden, protected from over-write, un-protected from over-write, - // protected from deletion and un-protected from deletion - int set_true = int(fn.arg(2).to_number()) & as_prop_flags::as_prop_flags_mask; - - // Is another integer bitmask that works like set_true, - // except it sets the attributes to false. The - // set_false bitmask is applied before set_true is applied - - // ASSetPropFlags was exposed in Flash 5, however the fourth argument 'set_false' - // was not required as it always defaulted to the value '~0'. - int set_false = (fn.nargs == 3 ? - (version == 5 ? ~0 : 0) : int(fn.arg(3).to_number())) - & as_prop_flags::as_prop_flags_mask; - - // Evan: it seems that if set_true == 0 and set_false == 0, this function - // acts as if the parameters where (object, null, 0x1, 0) ... - if (set_false == 0 && set_true == 0) - { - props = NULL; - set_false = 0; - set_true = 0x1; - } - - if (props == NULL) - { - // Take all the members of the object - - as_object* object = (as_object*) obj; - - stringi_hash::const_iterator it = object->m_members.begin(); - while (it != object->m_members.end()) - { - as_member member = it.get_value(); - - as_prop_flags f = member.get_member_flags(); - const int oldflags = f.get_flags(); - const int newflags = f.set_flags(set_true, set_false); - member.set_member_flags(f); - - object->m_members.set(it.get_key(), member); - - ++it; - } - - // [DICE-MOD SwiffPlayer #29: STOCK 2006 BUG REMOVED. With a null property list the stock - // body went on to walk object->m_prototype and copied every member of the PROTOTYPE down - // into the object, overwriting the object's own members of the same name. Every DICE class - // ends its init action with `ASSetPropFlags(Class.prototype, null, 1)`, so each subclass - // prototype had its own init/draw/createChildren/arrange replaced by the parent's - the - // whole UI ran UIObject's empty draw and never created a child clip (harness X, 2026-09-02: - // profilesList's prototype 038C4E44 stored draw=04257424, the binding read 04250F24). - // Flash's ASSetPropFlags(obj, null, flags) changes the flags of obj's OWN properties only.] - } else { - as_object* object = (as_object*) obj; - as_object* object_props = (as_object*) props; - - stringi_hash::iterator it = object_props->m_members.begin(); - while(it != object_props->m_members.end()) - { - const tu_stringi key = (it.get_value()).get_member_value().to_string(); - stringi_hash::iterator it2 = object->m_members.find(key); - - if (it2 != object->m_members.end()) - { - as_member member = it2.get_value(); - - as_prop_flags f = member.get_member_flags(); - const int oldflags = f.get_flags(); - const int newflags = f.set_flags(set_true, set_false); - member.set_member_flags(f); - - object->m_members.set((it.get_value()).get_member_value().to_string(), member); - } - - ++it; - } - } } - // ============================================================================================= - // [DICE-MOD SwiffPlayer: the AS2 `Color` class - absent from stock 2006 gameswf, present in the - // shipped DICE build, and called by BF2's menu (`new Color(mc).setRGB(rgb)`). On stock gameswf - // that logged "can't create object with unknown class 'Color'" and the tinted clips kept their - // authored colours: retail 2026-09-02, the login panel drew its 0x844D00 orange where the golden - // run (shipped player, same renderer) drew 0x464646 grey. - // - // Recovered from SwiffPlayer.dll (2).i64: - // * the constructor c_function (sub_1008B280): a 44-byte as_object whose ctor (sub_100A96A0) - // registers getRGB = sub_100A9570 and setRGB = gameswf_color_set_rgb as PER-INSTANCE - // members; +24 rgb = 0; +28 target = the first argument iff it is an OBJECT, else null; - // * setRGB (gameswf_color_set_rgb): exactly one argument, else log "Color:setRGB needs one - // argument"; with a target: rgb = to_number(arg0); copy the target character's cxform - // (character +124 in the 2004 layout); r/g/b mult = 0, add = the rgb bytes; the alpha pair - // is copied through untouched; push it through the character's set_cxform; - // * getRGB (sub_100A9570): the stored rgb as a NUMBER. - // No setTransform/getTransform - the shipped ctor registers only those two. The shipped bodies - // take `this` as a Color without checking; ours refuses a foreign `this` via cast_to_as_object.] - // ============================================================================================= + // Color instances expose their stored RGB value and a target color transform. + void color_get_rgb(const fn_call& fn); + void color_set_rgb(const fn_call& fn); + struct as_color : public as_object { + // Compiler deleting wrapper: SwiffPlayer.dll 0x100A97B0 forwards + // to the object and reference-counted bases before conditional deletion. + // Native target ownership remains the separate S3 bridge below. + ~as_color() override = default; int m_rgb; // +24 in the shipped object + // [CHOSEN, not recovered] S3 bridge: retain native strong target ownership. smart_ptr m_target; // +28 (a raw pointer in the shipped object) - as_color() : m_rgb(0) {} + as_color() + { + // SwiffPlayer.dll 0x100A96A0: getRGB before setRGB; factory sets the fields. + // [CHOSEN, not recovered] S3 bridge: native parent/interface storage. + set_member("getRGB", as_value(color_get_rgb)); + set_member("setRGB", as_value(color_set_rgb)); + } }; void color_set_rgb(const fn_call& fn) { + // SwiffPlayer.dll 0x100A95A0: exact arity; leave the result untouched. if (fn.nargs != 1) { log_error("Color:setRGB needs one argument\n"); return; } - as_color* c = fn.this_ptr ? static_cast(fn.this_ptr->cast_to_as_object()) : NULL; - if (c == NULL || c->m_target == NULL) + as_color* c = static_cast(fn.this_ptr); + if (c->m_target == NULL) { return; } - c->m_rgb = (int) fn.arg(0).to_number(); + c->m_rgb = bf2x87::toIntTruncate(fn.arg(0).to_number()); - movie* mv = c->m_target->to_movie(); + cxform cx; + // [CHOSEN, not recovered] S3 bridge: adjust the native target interface + // instead of retail's fixed character-subobject subtraction. Reload after + // numeric conversion; an invalid/cleared target still faults on the copy. + as_object_interface* target = c->m_target.get_ptr(); + movie* mv = target ? target->to_movie() : NULL; character* ch = mv ? mv->cast_to_character() : NULL; - if (ch == NULL) - { - return; - } - cxform cx = ch->get_cxform(); - cx.m_[0][0] = 0.0f; cx.m_[0][1] = (float) ((c->m_rgb >> 16) & 0xFF); - cx.m_[1][0] = 0.0f; cx.m_[1][1] = (float) ((c->m_rgb >> 8) & 0xFF); - cx.m_[2][0] = 0.0f; cx.m_[2][1] = (float) (c->m_rgb & 0xFF); + const Uint32 rgb = static_cast(c->m_rgb); + cx = ch->get_cxform(); + cx.m_[0][0] = 0.0f; cx.m_[0][1] = (float) ((rgb >> 16) & 0xFF); + cx.m_[1][0] = 0.0f; cx.m_[1][1] = (float) ((rgb >> 8) & 0xFF); + cx.m_[2][0] = 0.0f; cx.m_[2][1] = (float) (rgb & 0xFF); // cx.m_[3][*] (alpha) stays as copied - the shipped body leaves it alone. + // Retail character tables share the eight-float copy at 0x1007EDB0. ch->set_cxform(cx); } void color_get_rgb(const fn_call& fn) { - as_color* c = fn.this_ptr ? static_cast(fn.this_ptr->cast_to_as_object()) : NULL; - fn.result->set_double(c ? (double) c->m_rgb : 0.0); + // SwiffPlayer.dll 0x100A9570: read first, then release the old result twice. + const int rgb = static_cast(fn.this_ptr)->m_rgb; + fn.result->set_int(rgb); } void color_ctor(const fn_call& fn) { + // SwiffPlayer.dll 0x1008B280: register methods, clear target/RGB, inspect arg0. as_color* c = new as_color; - c->set_member("getRGB", as_value(color_get_rgb)); - c->set_member("setRGB", as_value(color_set_rgb)); - if (fn.nargs > 0 && fn.arg(0).get_type() == as_value::OBJECT) + c->m_target = NULL; + c->m_rgb = 0; + if (fn.nargs != 0) { - c->m_target = fn.arg(0).to_object(); + c->m_target = fn.arg(0).get_type() == as_value::OBJECT + ? fn.arg(0).m_object_value : NULL; } fn.result->set_as_object_interface(c); } - // ============================================================================================= - // [DICE-MOD SwiffPlayer: Object.registerClass(symbolName, Class) - the AS2 idiom that binds a - // library symbol to a component class, absent from stock 2006 (which only knows methods on the - // String constructor and logs "method call on unknown c function" for everything else - BF2's - // menu makes 18 such calls before its first frame, one per UI component class). - // - // Recovered from SwiffPlayer.dll (2).i64: DICE's `Object` is a class object whose ctor - // (sub_1009A190) registers registerClass = sub_100997B0; that body needs exactly two arguments - // ("Object::registerClass need two arguments"), converts arg0 to a string and arg1 to a - // function, asks the root movie's definition for get_exported_resource(name), and stores the - // function in the resulting character_def (+12). The bound class is applied when a sprite of - // that definition loads - see sprite_instance::bind_registered_class (gameswf_impl.cpp). - // Here `Object` stays the stock C function; the CallMethod handler routes the one method the - // shipped object carries to this body. See GAMESWF_DIVERGENCES.md.] - // ============================================================================================= + // Binds an exported symbol to the class applied when its sprite loads. + // The Object module publishes this method; definitions retain native class links. void object_register_class(const fn_call& fn) { + // SwiffPlayer.dll 0x100997B0 leaves the result untouched, including refusal. if (fn.nargs != 2) { log_error("Object::registerClass need two arguments\n"); return; } - const tu_string symbol = fn.arg(0).to_tu_string(); + // 0x100997DF..0x100997F7 borrows the converted text, captures the + // function, then copies that text for the export lookup. + const char* symbol_text = fn.arg(0).to_string(); as_as_function* cls = fn.arg(1).to_as_function(); + const tu_string symbol(symbol_text); - movie* target = fn.env->get_target(); - movie* root = target ? target->get_root_movie() : NULL; - movie_definition* def = root ? root->get_movie_definition() : NULL; - if (def == NULL || cls == NULL) - { - fn.result->set_bool(false); - return; - } + // SwiffPlayer.dll 0x100997FC uses the published root, independently + // of the calling environment's target. + movie_definition* def = get_global_root_movie()->get_movie_definition(); // Every movie_definition in this tree is a movie_definition_sub (movie_def_impl, // sprite_definition), which is where the export table lives. smart_ptr res = static_cast(def)->get_exported_resource(symbol); character_def* cdef = res.get_ptr() ? res->cast_to_character_def() : NULL; - if (cdef == NULL) - { - log_error("Object::registerClass: no exported character '%s'\n", symbol.c_str()); - fn.result->set_bool(false); - return; - } - cls->add_ref(); + // [CHOSEN, not recovered] S3 bridge: native definitions own their class + // references until release_library_classes; retail stores this pointer raw. + if (cls) cls->add_ref(); if (cdef->m_registered_class) { cdef->m_registered_class->drop_ref(); } cdef->m_registered_class = cls; - fn.result->set_bool(true); } - // [DICE-MOD SwiffPlayer: the shipped action_init (sub_10090FF0) registers "MovieClip" as a + // the shipped action_init (sub_10090FF0) registers "MovieClip" as a // no-op C function (nullsub_10). Its only job is to exist: `class X extends MovieClip` then // resolves a superclass that is not a script function, and the extends handler leaves the - // subclass prototype's __proto__ empty - exactly what the shipped handler does with it.] + // subclass prototype's __proto__ empty - exactly what the shipped handler does with it. void as_global_movieclip_ctor(const fn_call& fn) + // SwiffPlayer.dll 0x1008A150 is RET, bound by 0x10090FF0. { (void) fn; } @@ -1937,90 +1786,259 @@ namespace gameswf { s_inited = true; - // @@ s_global should really be a - // client-visible player object, which - // contains one or more actual movie - // instances. We're currently just hacking it - // in as an app-global mutable object :( + // SwiffPlayer.dll 0x10091012-0x10091021: the module table's _global is the + // empty common object 0x1000B320, without as_object's own members. + // [CHOSEN, not recovered] S3 bridge: the native type is as_object with its + // member bag emptied (its object live count is native bookkeeping). + // 0x10091030/0x100910E4/0x10091198 also link each module into the + // collector list (slot +0xC); owner decision 2026-11-09 keeps it inactive. assert(s_global == NULL); s_global = new as_object; - s_global->set_member("trace", as_value(as_global_trace)); - s_global->set_member("Object", as_value(as_global_object_ctor)); - s_global->set_member("Sound", as_value(as_global_sound_ctor)); - s_global->set_member("Array", as_value(as_global_array_ctor)); - - s_global->set_member("TextFormat", as_value(textformat_new)); -#ifdef HAVE_LIBXML - s_global->set_member("XML", as_value(xml_new)); - //s_global->set_member("XML", as_value(xmlsocket_xml_new)); - s_global->set_member("XMLSocket", as_value(xmlsocket_new)); -#endif // HAVE_LIBXML - s_global->set_member("MovieClipLoader", as_value(moviecliploader_new)); - s_global->set_member("String", as_value(string_ctor)); - s_global->set_member("Number", as_value(as_global_number_ctor)); // [DICE-MOD #40] sub_1008C520 - s_global->set_member("Boolean", as_value(as_global_boolean_ctor)); // [DICE-MOD #40] sub_1008C4D0 + s_global->m_members.clear(); + // SwiffPlayer.dll 0x10091072 publishes _global before registering modules. + s_modules.set("_global", as_value(s_global.get_ptr())); + // SwiffPlayer.dll 0x10091126 / 0x100911DA publishes String then Object, + // before global functions, constructor factories, Math and Key. + s_modules.set("String", as_value(create_dice_string_class())); + // [CHOSEN, not recovered] S3 bridge: flatten the retail Object class + // into the native bag; its common base interface remains shared with as_object. + as_object* object_class = new as_object; + object_class->m_members.clear(); + object_class->m_members.set("registerClass", as_member(as_value(object_register_class))); + s_modules.set("Object", as_value(object_class)); + + // SwiffPlayer.dll 0x10090FF0 publishes no Sound class: the image has no + // "attachSound" name, no Sound constructor and no reference to the + // three method bodies 0x1008A1B0 / 0x1008A1F0 / 0x1008C6E0. // ASSetPropFlags - s_global->set_member("ASSetPropFlags", as_global_assetpropflags); - - // [DICE-MOD SwiffPlayer: register setInterval/clearInterval in _global. gameswf 2006 - // IMPLEMENTS both (gameswf_timers.cpp timer_setinterval / timer_clearinterval) but - // action_init never publishes them, so every script call reports "'setInterval' is not a - // function" and the movie's timed callbacks never run. menu.swf calls setInterval. - // DICE's build exposes the same pair (as_global_setinterval / ...clearinterval in the - // shipped image). See GAMESWF_DIVERGENCES.md.] - s_global->set_member("setInterval", as_value(timer_setinterval)); - s_global->set_member("clearInterval", as_value(timer_clearinterval)); - - // [DICE-MOD SwiffPlayer: the Color class (color_ctor above). The shipped action_init - // (sub_10090FF0) registers "Color" alongside String/Object/XML/Array/Boolean/Number.] - s_global->set_member("Color", as_value(color_ctor)); - s_global->set_member("MovieClip", as_value(as_global_movieclip_ctor)); + register_global_function("ASSetPropFlags", as_global_assetpropflags); + // SwiffPlayer.dll 0x10091238 / 0x10091247 registers MovieClip next. + register_global_function("MovieClip", as_global_movieclip_ctor); + + // SwiffPlayer.dll 0x1009124C-0x100913F5: the two XML factories + // precede String and use the independently recovered Expat-backed objects. + register_constructor("XML", xml_new); + register_constructor("XMLNode", xmlnode_new); + register_constructor("String", string_ctor); + register_constructor("Array", as_global_array_ctor); + register_constructor("Boolean", as_global_boolean_ctor); + register_constructor("Number", as_global_number_ctor); + register_constructor("Color", color_ctor); + register_constructor("Object", as_global_object_ctor); math_init(); key_init(); + } } - // ============================================================================================= - // [DICE-MOD SwiffPlayer: AS2 getter/setter properties - `Object.addProperty(name, get, set)`. - // - // Stock 2006 gameswf has no property support; menu.swf calls addProperty 36 times in its onLoad, - // and DICE's own AS object class registers exactly this one method. A name registered here - // SHADOWS a plain member of the same name: reading it calls the getter, writing it calls the - // setter. See gameswf_action.h and GAMESWF_DIVERGENCES.md. - // - // The getter/setter are invoked through call_method, which needs an as_environment to carry the - // arguments; property access has none of its own, so a file-scope scratch environment is used. - // It is only ever entered one call deep from here, and each use leaves it as it found it. - // ============================================================================================= + // Accessors shadow ordinary data members. Script calls use the current VM + // environment; native host access retains the explicit environment adapter. static as_environment s_property_env; + static as_environment* property_environment(as_object_interface* self) + // Retail objects store their environment at +0x24 (as_object constructor + // 0x1009A36B) and return it from vtable slot +0x2C (0x10077DC0). + // [CHOSEN, not recovered] issue #7: native objects store no environment. + { + // SwiffPlayer.dll 0x10099F23/0x10099DF3 uses the environment published by execute. + if (s_current_environment) return s_current_environment; + // [CHOSEN, not recovered] S3 bridge for native host reads/writes outside execute. + // Use the receiver's movie environment where the current interface exposes one. + movie* target = self->to_movie(); + if (target) return target->get_action_environment(); + return &s_property_env; + } + + static as_value call_property(const as_value& method, as_environment* env, + as_object_interface* self, const as_value& argument) + { + // SwiffPlayer.dll 0x1008EAD0 passes one value for getters as well as setters. + { + const as_value value(argument); + env->push_val(value); + } + as_value result = call_method(method, env, self, 1, env->get_top_index()); + return result; + } + void as_object::add_property(const tu_stringi& name, const as_value& getter, const as_value& setter) { - m_getters.set(name, getter); - m_setters.set(name, setter); + // SwiffPlayer.dll 0x1009A0F0 / 0x100999C0: append both borrowed + // pointers, including nulls. Duplicate names occupy distinct entries. + const property_accessors accessors = { getter.to_as_function(), setter.to_as_function() }; + m_accessors.add(name, accessors); + } + void as_object::gc_mark_members() + { + // SwiffPlayer.dll 0x1000B4B0 visits only the ordinary member bag. + if (m_gc_generation == get_gc_mark_generation()) return; + m_gc_generation = get_gc_mark_generation(); + for (stringi_hash::iterator it = m_members.begin(); it != m_members.end(); ++it) + gc_mark_value(it->second.m_value); + } + + void as_object::gc_mark() + { + // SwiffPlayer.dll 0x10077DD0: base members, explicit prototype, + // constructor, instance prototype, in that order. Accessors are not marked. + if (m_gc_generation == get_gc_mark_generation()) return; + gc_mark_members(); + if (m_prototype) m_prototype->gc_mark(); + if (m_constructor != NULL) m_constructor->gc_mark(); + if (m_instance_prototype) m_instance_prototype->gc_mark(); + } + + void as_object::gc_release() + { + // SwiffPlayer.dll 0x1000B6B0: visit OBJECT members, then clear the bag. + // Prototype, constructor and accessor storage is left alone. + if (m_gc_generation == get_gc_release_generation()) return; + m_gc_generation = get_gc_release_generation(); + for (stringi_hash::iterator it = m_members.begin(); it != m_members.end(); ++it) + if (it->second.m_value.get_type() == as_value::OBJECT && it->second.m_value.to_object()) + it->second.m_value.to_object()->gc_release(); + m_members.clear(); } - static bool is_callable(const as_value& v) + void as_as_function::gc_mark() { - return v.get_type() == as_value::C_FUNCTION || v.get_type() == as_value::AS_FUNCTION; + // SwiffPlayer.dll 0x1008C620 has no function generation/cycle guard. + // [CHOSEN, not recovered] S3 bridge: m_properties carries the separate + // retail function prototype and static-member storage in the native graph. + if (!m_properties) return; + if (m_properties->m_instance_prototype) m_properties->m_instance_prototype->gc_mark(); + for (stringi_hash::iterator it = m_properties->m_members.begin(); + it != m_properties->m_members.end(); ++it) + gc_mark_value(it->second.m_value); + } + + as_object::as_object() : m_instance_prototype(NULL), m_prototype(NULL) + { + // SwiffPlayer.dll 0x1009A190 / 0x1009A320 registers both own members. + // [CHOSEN, not recovered] S3 bridge: native interface/refcount storage and + // separate accessor maps replace the original base classes and pair hash. + m_members.set("registerClass", as_member(as_value(object_register_class))); + // SwiffPlayer.dll 0x1009A376 increments after the base's registerClass + // write, before registering the instance's addProperty method. + ++s_object_live_count; + m_members.set("addProperty", as_member(as_value(as_object_addproperty))); + } + + as_object::as_object(as_object_interface* proto) : as_object() + { + // SwiffPlayer.dll 0x100936C8 / 0x100944FC installs the instance's prototype link. + m_instance_prototype = proto; + // [CHOSEN, not recovered] S3 bridge: native links retain their objects. + if (m_instance_prototype) m_instance_prototype->add_ref(); + } + + as_object::~as_object() + { + // SwiffPlayer.dll 0x10077D88 and Array's inline copy at 0x10077F72 + // decrement before accessor, constructor and member destruction. + --s_object_live_count; + // [CHOSEN, not recovered] S3 bridge: release the native strong prototype links. + // 0x10077D70 then destroys accessor keys, the retained constructor and + // ordinary members. Their reverse declaration order supplies that sequence. + if (m_instance_prototype) m_instance_prototype->drop_ref(); + if (m_prototype) m_prototype->drop_ref(); + } + + void as_object::clear() + { + // [CHOSEN, not recovered] issue #7: clear both native prototype links and + // the constructor while release_script_objects holds its registry snapshot. + m_members.clear(); + m_constructor = NULL; + if (m_instance_prototype) + { + m_instance_prototype->drop_ref(); + m_instance_prototype = NULL; + } + if (m_prototype) + { + m_prototype->drop_ref(); + m_prototype = NULL; + } + } + + void as_object::set_member(const tu_stringi& name, const as_value& val) + { + // SwiffPlayer.dll 0x1009A2A0: accessors precede the two special writes. + if (set_property(name, val)) return; + if (strcmp(name.c_str(), "__proto__") == 0) + { + as_object_interface* proto = val.get_type() == as_value::OBJECT ? val.m_object_value : NULL; + // [CHOSEN, not recovered] S3 bridge: retain native ownership of the raw retail link. + if (proto) proto->add_ref(); + if (m_prototype) m_prototype->drop_ref(); + m_prototype = proto; + } + else if (strcmp(name.c_str(), "__constructor__") == 0) + { + m_constructor = val.to_as_function(); + } + else + { + m_members.set(name, as_member(val)); + } + } + + bool as_object::get_member(const tu_stringi& name, as_value* val) + { + // SwiffPlayer.dll 0x10099FE0: accessors, special links, own bag, then both links. + if (get_property(name, val)) + { + s_call_super = m_constructor.get_ptr(); + return true; + } + if (strcmp(name.c_str(), "prototype") == 0) + { + val->set_as_object_interface(m_instance_prototype); + return true; + } + if (strcmp(name.c_str(), "__proto__") == 0) + { + val->set_as_object_interface(m_prototype); + return true; + } + if (strcmp(name.c_str(), "__constructor__") == 0) + { + *val = as_value(m_constructor.get_ptr()); + return true; + } + stringi_hash::const_iterator member = m_members.find(name); + if (member != m_members.end()) + { + *val = member.get_value().m_value; + s_call_super = m_constructor.get_ptr(); + return true; + } + if (m_instance_prototype && m_instance_prototype->get_member(name, val)) return true; + if (m_prototype && m_prototype->get_member(name, val)) return true; + return false; } - // [DICE-MOD SwiffPlayer #28] Walk this object and its prototype chain for a getter / setter. + // [CHOSEN, not recovered] S3 bridge for sprite callers outside this file. + // These lookup-only helpers use the same unbounded prototype walk as the accessors. bool as_object::find_getter(const tu_stringi& name, as_value* getter, int depth) { - if (m_getters.get(name, getter) && is_callable(*getter)) + (void) depth; + property_accessors accessors; + if (m_accessors.get(name, &accessors) && accessors.getter) { + *getter = as_value(accessors.getter); return true; } - if (depth < 32 && m_prototype != NULL) + if (m_prototype != NULL) { as_object* proto = m_prototype->cast_to_as_object(); if (proto) { - return proto->find_getter(name, getter, depth + 1); + return proto->find_getter(name, getter); } } return false; @@ -2028,109 +2046,137 @@ namespace gameswf bool as_object::find_setter(const tu_stringi& name, as_value* setter, int depth) { - if (m_setters.get(name, setter) && is_callable(*setter)) + (void) depth; + property_accessors accessors; + if (m_accessors.get(name, &accessors) && accessors.setter) { + *setter = as_value(accessors.setter); return true; } - if (depth < 32 && m_prototype != NULL) + if (m_prototype != NULL) { as_object* proto = m_prototype->cast_to_as_object(); if (proto) { - return proto->find_setter(name, setter, depth + 1); + return proto->find_setter(name, setter); } } return false; } - // [DICE-MOD SwiffPlayer #30] The first object a function is stored on is its home (see the - // m_home_object comment in the header). - void as_object::note_function_home(const as_value& fn) - { - as_as_function* f = fn.to_as_function(); - if (f && f->m_home_object == NULL) - { - f->m_home_object = this; - } - } - - as_value as_object::invoke_getter(const as_value& getter, as_object_interface* self) + as_value as_object::invoke_getter(const as_value& getter, as_object_interface* self, + const as_value& argument) { - return call_method0(getter, &s_property_env, self); + as_environment* env = property_environment(self); + as_value result = call_property(getter, env, self, argument); + env->drop(1); + return result; } void as_object::invoke_setter(const as_value& setter, as_object_interface* self, const as_value& val) { - // One argument, passed the way fn_call::arg() reads it: bottom(first_arg_bottom_index - n). - s_property_env.push(val); - call_method(setter, &s_property_env, self, 1, s_property_env.get_top_index()); - s_property_env.drop(1); + as_environment* env = property_environment(self); + call_property(setter, env, self, val); + env->drop(1); } - bool as_object::get_property(const tu_stringi& name, as_value* val) + bool as_object::get_property(const tu_stringi& name, as_value* val, as_object_interface* receiver) { - as_value getter; - if (find_getter(name, &getter) == false) + // SwiffPlayer.dll 0x10099EB0: only a non-null script getter handles the name. + if (!receiver) receiver = this; + property_accessors accessors; + if (m_accessors.get(name, &accessors) && accessors.getter) { - return false; + const as_value getter(accessors.getter); + *val = invoke_getter(getter, receiver, *val); + return true; } - *val = invoke_getter(getter, this); - return true; + for (as_object_interface* link = m_prototype; link; ) + { + // [CHOSEN, not recovered] S3 bridge: adjust the native object interface. + as_object* proto = link->cast_to_as_object(); + // A movie clip on the chain ends the walk "not found". Retail reads the accessor table + // and link at the script-object offsets of the clip's secondary interface, where a + // movie keeps unrelated empty state; retail 1.50 finds no getter there and does not + // fault (docs/tracks/game/swf-proto-retail-probe.md, v2 test 2 red, tests 1/5 likewise). + // get_member still finds the clip's ordinary members afterwards (test 1 green). + if (!proto) return false; + if (proto->get_property(name, val, receiver)) return true; + link = proto->m_prototype; + } + return false; } - bool as_object::set_property(const tu_stringi& name, const as_value& val) + bool as_object::set_property(const tu_stringi& name, const as_value& val, as_object_interface* receiver) { - as_value setter; - if (find_setter(name, &setter) == false) + // SwiffPlayer.dll 0x10099D80: preserve receiver through the recursive/outer walks. + if (!receiver) receiver = this; + property_accessors accessors; + if (m_accessors.get(name, &accessors) && accessors.setter) { - return false; + const as_value setter(accessors.setter); + invoke_setter(setter, receiver, val); + return true; } - invoke_setter(setter, this, val); - return true; + for (as_object_interface* link = m_prototype; link; ) + { + as_object* proto = link->cast_to_as_object(); + // A movie clip on the chain ends the walk "not found", as in get_property: no setter + // runs (probe v2 test 3 red) and set_member stores an own member (test 6 green). + if (!proto) return false; + if (proto->set_property(name, val, receiver)) return true; + link = proto->m_prototype; + } + return false; } // The builtin itself. `this_ptr` is an as_object_interface* that need not be an as_object (a // sprite_instance is not), hence the virtual cast_to_as_object rather than a static_cast. void as_object_addproperty(const fn_call& fn) { - if (fn.nargs < 3 || fn.this_ptr == NULL) + // SwiffPlayer.dll 0x1009A0F0: exact arity, no result assignment on either arm. + if (fn.nargs != 3) { - log_error("error: addProperty needs three arguments\n"); - fn.result->set_bool(false); + log_error("Object::addProperty needs three arguments\n"); return; } + // [CHOSEN, not recovered] S3 bridge: adjust the native object interface. as_object* obj = fn.this_ptr->cast_to_as_object(); - if (obj == NULL) - { - log_error("error: addProperty called on a non-object\n"); - fn.result->set_bool(false); - return; - } - obj->add_property(fn.arg(0).to_tu_string().to_tu_stringi(), fn.arg(1), fn.arg(2)); - fn.result->set_bool(true); + // [CHOSEN, not recovered] A movie-clip receiver accepts the call and keeps nothing. + // Retail writes the pair into the accessor table at the clip's secondary-interface offset, + // where no lookup ever finds it: no fault, the getter is never found (probe v2 test 5). + if (obj == NULL) return; + // 0x1009A126 / 0x1009A136 capture the borrowed functions before + // converting the name. Do not create retaining as_value temporaries. + const as_object::property_accessors accessors = { + fn.arg(1).to_as_function(), fn.arg(2).to_as_function() + }; + const tu_stringi name(fn.arg(0).to_string()); + obj->m_accessors.add(name, accessors); } - // [/DICE-MOD] - // [DICE-MOD SwiffPlayer: expose _global for the AS-bridge graph build, evidence loadMovie - // sub_1008E4D0 fetches _global before advance. Stock gameswf keeps s_global file-scope with no - // accessor and inits it lazily; DICE replaced the whole mechanism with a module hash and forced - // init up-front. This is the minimal stock-gameswf equivalent: force action_init (so s_global - // exists before the first advance) and hand back the object so the wrapper can hang dice.* off it. - // Indexed in Code/BF2/External/gameswf/GAMESWF_DIVERGENCES.md.] + // [CHOSEN, not recovered] S3 bridge: the native host graph needs initialization + // before the first advance. Retail's lookup_global_object itself never initializes. as_object* get_global_object() { action_init(); - return s_global.get_ptr(); + as_object_interface* global = lookup_global_object(); + return global ? global->cast_to_as_object() : NULL; } - // [/DICE-MOD] void action_clear() { + // [CHOSEN, not recovered] S3 bridge to issue #7: a native movie reset + // invalidates the borrowed lookup context just as unloading the DLL would. + s_call_super = NULL; if (s_inited) { s_inited = false; + // [CHOSEN, not recovered] issue #7: release native module references too. + s_modules.clear(); + s_constructors.clear(); s_global->clear(); s_global = NULL; } @@ -2141,6 +2187,8 @@ namespace gameswf // properties by number // + // SwiffPlayer.dll 0x100D6520 / 0x100D6DE0: construct these 22 names + // in order and destroy them in reverse. The quality placeholder is literal. static const tu_string s_property_names[] = { tu_string("_x"), @@ -2169,6 +2217,7 @@ namespace gameswf static as_value get_property(as_object_interface* obj, int prop_number) + // SwiffPlayer.dll 0x1008CF60. { as_value val; if (prop_number >= 0 && prop_number < int(sizeof(s_property_names)/sizeof(s_property_names[0]))) @@ -2184,6 +2233,7 @@ namespace gameswf static void set_property(as_object_interface* obj, int prop_number, const as_value& val) { + // SwiffPlayer.dll 0x1008A290: signed bounds check, then one virtual write. if (prop_number >= 0 && prop_number < int(sizeof(s_property_names)/sizeof(s_property_names[0]))) { obj->set_member(s_property_names[prop_number], val); @@ -2203,33 +2253,40 @@ namespace gameswf // Thin wrapper around action_buffer. struct do_action : public execute_tag { + // SwiffPlayer.dll 0x10091420 constructs the embedded action_buffer. action_buffer m_buf; + // SwiffPlayer.dll 0x10091490 destroys the buffer before the execute_tag base. + virtual ~do_action() = default; void read(stream* in) { + // SwiffPlayer.dll 0x1008D9D0. m_buf.read(in); } virtual void execute(movie* m) { + // SwiffPlayer.dll 0x10091450 queues the buffer on the movie. m->add_action_buffer(&m_buf); } - // Don't override because actions should not be replayed when seeking the movie. - //void execute_state(movie* m) {} + // SwiffPlayer.dll 0x10091470: actions are not replayed when seeking. + virtual void execute_state(movie*) {} virtual bool is_action_tag() const // Tell the caller that we are an action tag. { + // SwiffPlayer.dll 0x10091480. return true; } }; void do_action_loader(stream* in, int tag_type, movie_definition_sub* m) { - IF_VERBOSE_PARSE(log_msg("tag %d: do_action_loader\n", tag_type)); + // SwiffPlayer.dll 0x10091E50: read the new buffer, then publish the tag. + if (s_verbose_loader) log_msg("tag %d: do_action_loader\n", tag_type); - IF_VERBOSE_ACTION(log_msg("-- actions in frame %d\n", m->get_loading_frame())); + IF_VERBOSE_PARSE(log_msg("-- actions in frame %d\n", m->get_loading_frame())); assert(in); assert(tag_type == 12); @@ -2241,24 +2298,35 @@ namespace gameswf m->add_execute_tag(da); } + void execute_init_action(execute_tag* tag, as_environment* env) + { + // SwiffPlayer.dll 0x100818A3 calls action_buffer::execute (0x100961E0) + // directly. [CHOSEN, not recovered] S3 bridge: the native definition + // stores an execute_tag wrapper instead of the retail init-action record. + static_cast(tag)->m_buf.execute(env); + } + // // do_init_action // + // SwiffPlayer.dll 0x1006FB10: resolve the ID before allocating the buffer; + // append remains definition-wide, independently of the unused lookup result. void do_init_action_loader(stream* in, int tag_type, movie_definition_sub* m) { assert(tag_type == 59); int sprite_character_id = in->read_u16(); + m->get_character_def(sprite_character_id); - IF_VERBOSE_PARSE(log_msg(" tag %d: do_init_action_loader\n", tag_type)); - IF_VERBOSE_ACTION(log_msg(" -- init actions for sprite %d\n", sprite_character_id)); + if (s_verbose_loader) log_msg("tag %d: do_init_action_loader\n", tag_type); + IF_VERBOSE_PARSE(log_msg("-- init actions in sprite %d\n", sprite_character_id)); do_action* da = new do_action; da->read(in); - m->add_init_action(sprite_character_id, da); + m->add_init_action(da); } @@ -2269,14 +2337,19 @@ namespace gameswf // Disassemble one instruction to the log. static void log_disasm(const unsigned char* instruction_data); + // SwiffPlayer.dll 0x1008A070; [INFERRED] source-level helper name. + static double floor_float(float value) { return floor(double(value)); } + action_buffer::action_buffer() : m_decl_dict_processed_at(-1) { + // SwiffPlayer.dll 0x1008D9E0: empty bytes/dictionary, unprocessed dictionary. } void action_buffer::read(stream* in) + // SwiffPlayer.dll 0x1008D010. { // Read action bytes. for (;;) @@ -2301,7 +2374,7 @@ namespace gameswf } } - IF_VERBOSE_ACTION(log_msg("%4d\t", pc); log_disasm(&m_buffer[instruction_start]); ); + IF_VERBOSE_PARSE(log_msg("%4d\t", pc); log_disasm(&m_buffer[instruction_start]); ); if (action_id == 0) { @@ -2313,6 +2386,7 @@ namespace gameswf void action_buffer::process_decl_dict(int start_pc, int stop_pc) + // SwiffPlayer.dll 0x1008B350. // Interpret the decl_dict opcode. Don't read stop_pc or // later. A dictionary is some static strings embedded in the // action buffer; there should only be one dictionary per @@ -2401,13 +2475,9 @@ namespace gameswf // them in the given environment. Execute our whole buffer, // without any arguments passed in. { - int local_stack_top = env->get_local_frame_top(); - env->add_frame_barrier(); - + // SwiffPlayer.dll 0x100961E0 adds no local-frame barrier. array empty_with_stack; execute(env, 0, m_buffer.size(), NULL, empty_with_stack, false /* not function2 */); - - env->set_local_frame_top(local_stack_top); } @@ -2423,18 +2493,25 @@ namespace gameswf // stack frame (it may have passed its arguments in via the // local stack frame). // - // [DICE-MOD SwiffPlayer #55] is_function2 no longer selects a register set: every register + // is_function2 no longer selects a register set: every register // operand addresses the environment's one bank, as in the shipped execute (0x100925A0). { (void)is_function2; action_init(); // @@ stick this somewhere else; need some global static init function + // 0x100925B4/0x1009553B/0x10095562: save the caller's publication. + as_environment* previous_environment = s_current_environment; + s_current_environment = env; assert(env); + // SwiffPlayer.dll 0x100925CD/0x10095541: preserve the entry operand count. + const int original_stack_size = env->m_stack.size(); - array with_stack(initial_with_stack); + // SwiffPlayer.dll 0x100925D6: each execution starts with an empty with stack. + // The retained native signature still accepts the 2006 capture argument. + (void)initial_with_stack; + array with_stack; - // Some corner case behaviors depend on the SWF file version. - int version = env->get_target()->get_movie_definition()->get_version(); + // SwiffPlayer.dll 0x100925A0 does not query the movie version at entry. #if 0 // Check the time @@ -2473,15 +2550,30 @@ namespace gameswf break; case 0x00: // end of actions. + // 0x1009555F: END restores operands but does not restore the target. + s_current_environment = previous_environment; + if (env->m_stack.size() != original_stack_size) + { + env->m_stack.resize(original_stack_size); + } return; case 0x04: // next frame. - env->get_target()->goto_frame(env->get_target()->get_current_frame() + 1); + { + // SwiffPlayer.dll 0x10092670: capture the selected receiver + // across its frame query and dispatch the immediate numeric entry. + movie* target = env->get_target(); + target->apply_goto_frame(target->get_current_frame() + 1); break; + } case 0x05: // prev frame. - env->get_target()->goto_frame(env->get_target()->get_current_frame() - 1); + { + // SwiffPlayer.dll 0x10092691 uses the same immediate entry. + movie* target = env->get_target(); + target->apply_goto_frame(target->get_current_frame() - 1); break; + } case 0x06: // action play env->get_target()->set_play_state(movie::PLAY); @@ -2521,13 +2613,17 @@ namespace gameswf } case 0x0E: // equal { - env->top(1).set_bool(env->top(1) == env->top(0)); + // SwiffPlayer.dll 0x100927B2 caches the destination before comparison. + as_value& left = env->top(1); + left.set_bool(left == env->top(0)); env->drop(1); break; } case 0x0F: // less than { - env->top(1).set_bool(env->top(1) < env->top(0)); + // SwiffPlayer.dll 0x100927EF caches the destination before comparison. + as_value& left = env->top(1); + left.set_bool(left < env->top(0)); env->drop(1); break; } @@ -2539,6 +2635,7 @@ namespace gameswf } case 0x11: // logical or { + // SwiffPlayer.dll 0x1009285B: shipped OR repeats the AND operation. env->top(1).set_bool(env->top(1).to_bool() && env->top(0).to_bool()); env->drop(1); break; @@ -2550,20 +2647,30 @@ namespace gameswf } case 0x13: // string equal { - env->top(1).set_bool(env->top(1).to_tu_string() == env->top(0).to_tu_string()); + // SwiffPlayer.dll 0x100928FB/0x10092903 converts right before left. + as_value& destination = env->top(1); + const tu_string& right = env->top(0).to_tu_string(); + const tu_string& left = destination.to_tu_string(); + destination.set_bool(left == right); env->drop(1); break; } case 0x14: // string length { - env->top(0).set_int(env->top(0).to_tu_string_versioned(version).utf8_length()); + // SwiffPlayer.dll 0x1009292E counts narrow bytes, not UTF-8 characters. + const int length = env->top(0).to_tu_string().length(); + env->top(0).set_int(length); break; } case 0x15: // substring { - int size = int(env->top(0).to_number()); - int base = int(env->top(1).to_number()) - 1; // 1-based indices - const tu_string& str = env->top(2).to_tu_string_versioned(version); + // SwiffPlayer.dll 0x1009296C computes a temporary substring, then + // discards it: only the length and starting-index operands are dropped. + int size = bf2x87::toIntTruncate(env->top(0).to_number()); + const Uint32 base_bits = static_cast(bf2x87::toIntTruncate(env->top(1).to_number())) - 1u; + int base; + memcpy(&base, &base_bits, sizeof(base)); + const tu_string& str = env->top(2).to_tu_string(); // Keep base within range. base = iclamp(base, 0, str.length()); @@ -2577,7 +2684,6 @@ namespace gameswf new_string.resize(size); env->drop(2); - env->top(0).set_tu_string(new_string); break; } @@ -2588,68 +2694,65 @@ namespace gameswf } case 0x18: // int { - env->top(0).set_int(int(floor(env->top(0).to_number()))); + // SwiffPlayer.dll 0x10092A7D: floor followed by signed dword FISTP. + as_value& value = env->top(0); + value.set_int(bf2x87::toIntTruncate(floor(value.to_number()))); break; } case 0x1C: // get variable { + // SwiffPlayer.dll 0x10092AD4-0x10092AFA: the lookup result + // goes directly to the by-value push, with no retained result local. as_value var_name = env->pop(); - tu_string var_string = var_name.to_tu_string(); - - as_value variable = env->get_variable(var_string, with_stack); - env->push(variable); - if (variable.to_object() == NULL) { - IF_VERBOSE_ACTION(log_msg("-- get var: %s=%s\n", - var_string.c_str(), - variable.to_tu_string().c_str())); - } else { - IF_VERBOSE_ACTION(log_msg("-- get var: %s=%s at %p\n", - var_string.c_str(), - variable.to_tu_string().c_str(), variable.to_object())); - } - + env->push_val(env->get_variable(var_name.to_tu_string(), with_stack)); + IF_VERBOSE_ACTION( + // 0x10092B14/0x10092B2A converts the result before the name. + const char* value = env->top(0).to_tu_string().c_str(); + const char* name = var_name.to_tu_string().c_str(); + log_msg("-- get var: %s=%s \n", name, value)); break; } case 0x1D: // set variable { - env->set_variable(env->top(1).to_tu_string(), env->top(0), with_stack); - IF_VERBOSE_ACTION(log_msg("-- set var: %s \n", - env->top(1).to_tu_string().c_str())); + // SwiffPlayer.dll 0x10092B5F-0x10092B99: no verbose conversion. + const as_value& value = env->top(0); + const tu_string& name = env->top(1).to_tu_string(); + env->set_variable(name, value, with_stack); env->drop(2); break; } case 0x20: // set target expression { - as_object_interface* target_object = env->top(0).to_object(); - - IF_VERBOSE_ACTION(log_msg("-- ActionSetTarget2: %s (%d)", - ((character *) target_object)->m_name.c_str(), - ((character *) target_object)->m_id)); - - movie* target = env->find_target(target_object); - env->set_target (target); + // SwiffPlayer.dll 0x10092B9C leaves both target and stack unchanged. + log_error("todo opcode: %02X\n", action_id); break; } case 0x21: // string concat { - env->top(1).convert_to_string_versioned(version); - env->top(1).string_concat(env->top(0).to_tu_string_versioned(version)); + // SwiffPlayer.dll 0x10092BB6 has no version-dependent conversion. + as_value& left = env->top(1); + left.string_concat(env->top(0).to_tu_string()); env->drop(1); break; } case 0x22: // get property { - movie* target = env->find_target(env->top(1)); + as_object_interface* target = env->find_target(env->top(1)); if (target) { - env->top(1) = get_property(target, (int) env->top(0).to_number()); + // SwiffPlayer.dll 0x10092C38 uses a signed dword FISTP. + // 0x10092C0C caches the destination before conversion and dispatch. + as_value& result = env->top(1); + const int property = bf2x87::toIntTruncate(env->top(0).to_number()); + result = get_property(target, property); } else { - env->top(1) = as_value(); + // SwiffPlayer.dll 0x10092C6C: failed target lookup yields NUMBER 0. + env->top(1).set_double(0.0); } env->drop(1); break; @@ -2658,10 +2761,13 @@ namespace gameswf case 0x23: // set property { - movie* target = env->find_target(env->top(2)); + as_object_interface* target = env->find_target(env->top(2)); if (target) { - set_property(target, (int) env->top(1).to_number(), env->top(0)); + // SwiffPlayer.dll 0x10092D0D uses the same dword conversion. + const as_value& value = env->top(0); + const int property = bf2x87::toIntTruncate(env->top(1).to_number()); + set_property(target, property, value); } env->drop(3); break; @@ -2669,23 +2775,31 @@ namespace gameswf case 0x24: // duplicate clip (sprite?) { - env->get_target()->clone_display_object( - env->top(2).to_tu_string(), - env->top(1).to_tu_string(), - (int) env->top(0).to_number()); + // SwiffPlayer.dll 0x10092D6C-0x10092DB5: capture target, + // convert depth, new name, then old name, before the clone call. + movie* target = env->get_target(); + const Uint16 depth = static_cast(bf2x87::toInt64Truncate(env->top(0).to_number())); + const tu_string& newname = env->top(1).to_tu_string(); + const tu_string& name = env->top(2).to_tu_string(); + target->clone_display_object(name, newname, depth); env->drop(3); break; } case 0x25: // remove clip - env->get_target()->remove_display_object(env->top(0).to_tu_string()); + { + // SwiffPlayer.dll 0x10092DD7 captures the target before conversion. + movie* target = env->get_target(); + const tu_string& name = env->top(0).to_tu_string(); + target->remove_display_object(name); env->drop(1); break; + } case 0x26: // trace { - // Log the stack val. - as_global_trace(fn_call(&env->top(0), NULL, env, 1, env->get_top_index())); + // SwiffPlayer.dll 0x10092E0B converts directly; it never calls toString. + log_msg("%s\n", env->top(0).to_string()); env->drop(1); break; } @@ -2694,7 +2808,14 @@ namespace gameswf { movie::drag_state st; - st.m_character = env->find_target(env->top(0)); + // SwiffPlayer.dll 0x10092E5B-0x10092E91: a missing target logs the + // error and continues with a null character. + // [CHOSEN, not recovered] issue #7 native type adjustment: retail + // subtracts 8 from any found interface without a type check + // (0x10092E68), so a non-movie OBJECT would be used as a character; + // the native cast treats it as an invalid target instead. + as_object_interface* drag_target = env->find_target(env->top(0)); + st.m_character = drag_target ? drag_target->to_movie() : NULL; if (st.m_character == NULL) { log_error("error: start_drag of invalid target '%s'.\n", @@ -2702,19 +2823,43 @@ namespace gameswf } st.m_lock_center = env->top(1).to_bool(); + // SwiffPlayer.dll 0x10092EBF..0x10092F40 captures the mouse + // offset before converting the bounds or removing any operands. + if (!st.m_lock_center && st.m_character != NULL) + { + int x, y, buttons; + get_global_root_movie()->get_mouse_state(&x, &y, &buttons); + matrix world = st.m_character->get_world_matrix(); + point local; + const float world_x = bf2x87::store(bf2x87::mul(bf2x87::Real(x), bf2x87::Real(20.0f))); + const float world_y = bf2x87::store(bf2x87::mul(bf2x87::Real(y), bf2x87::Real(20.0f))); + world.transform_by_inverse(&local, point(world_x, world_y)); + st.m_offset_x = local.m_x; + st.m_offset_y = local.m_y; + } st.m_bound = env->top(2).to_bool(); if (st.m_bound) { - st.m_bound_x0 = (float) env->top(6).to_number(); - st.m_bound_y0 = (float) env->top(5).to_number(); - st.m_bound_x1 = (float) env->top(4).to_number(); - st.m_bound_y1 = (float) env->top(3).to_number(); + // 0x10092F75..0x10093058 fetches the parent matrix once, + // converts Y before X, and transforms each pair immediately. + matrix parent_world = st.m_character->cast_to_character()->get_parent()->get_world_matrix(); + float y0 = bf2x87::store(bf2x87::mul(bf2x87::Real(env->top(5).to_number()), bf2x87::Real(20.0f))); + float x0 = bf2x87::store(bf2x87::mul(bf2x87::Real(env->top(6).to_number()), bf2x87::Real(20.0f))); + point bound; + parent_world.transform(&bound, point(x0, y0)); + st.m_bound_x0 = bound.m_x; + st.m_bound_y0 = bound.m_y; + float y1 = bf2x87::store(bf2x87::mul(bf2x87::Real(env->top(3).to_number()), bf2x87::Real(20.0f))); + float x1 = bf2x87::store(bf2x87::mul(bf2x87::Real(env->top(4).to_number()), bf2x87::Real(20.0f))); + parent_world.transform(&bound, point(x1, y1)); + st.m_bound_x1 = bound.m_x; + st.m_bound_y1 = bound.m_y; env->drop(4); } env->drop(3); - movie* root_movie = env->get_target()->get_root_movie(); - assert(root_movie); + // SwiffPlayer.dll 0x10093071 re-reads the global after conversions. + movie* root_movie = get_global_root_movie(); if (root_movie && st.m_character) { @@ -2726,54 +2871,28 @@ namespace gameswf case 0x28: // stop drag movie { - movie* root_movie = env->get_target()->get_root_movie(); - assert(root_movie); - - root_movie->stop_drag(); + // SwiffPlayer.dll 0x100930B4: unchecked published-root dispatch. + get_global_root_movie()->stop_drag(); break; } case 0x29: // string less than { - env->top(1).set_bool(env->top(1).to_tu_string() < env->top(0).to_tu_string()); - break; - } - - case 0x2A: // throw - { - log_error("todo opcode: %02X\n", action_id); - break; - } - - case 0x2B: // cast_object - { - // TODO - // - // Pop o1, pop s2 - // Make sure o1 is an instance of s2. - // If the cast succeeds, push o1, else push NULL. - // - // The cast doesn't appear to coerce at all, it's more - // like a dynamic_cast<> in C++ I think. - log_error("todo opcode: %02X\n", action_id); - break; - } - - case 0x2C: // implements - { - // Declare that a class s1 implements one or more - // interfaces (i2 == number of interfaces, s3..sn are the names - // of the interfaces). - log_error("todo opcode: %02X\n", action_id); + // SwiffPlayer.dll 0x100930E1/0x100930E9: right before left. + as_value& destination = env->top(1); + const tu_string& right = env->top(0).to_tu_string(); + const tu_string& left = destination.to_tu_string(); + destination.set_bool(left < right); break; } case 0x30: // random { - int max = int(env->top(0).to_number()); + // SwiffPlayer.dll 0x10093127/0x1009314D: signed FISTP, then unsigned DIV. + int max = bf2x87::toIntTruncate(env->top(0).to_number()); if (max < 1) max = 1; - env->top(0).set_int(tu_random::next_random() % max); + env->top(0).set_double(double(tu_random::next_random() % static_cast(max))); break; } case 0x31: // mb length @@ -2784,22 +2903,28 @@ namespace gameswf } case 0x32: // ord { - // ASCII code of first character - env->top(0).set_int(env->top(0).to_string()[0]); + // SwiffPlayer.dll 0x100931A2 sign-extends the first narrow byte. + as_value& value = env->top(0); + value.set_int(static_cast(value.to_string()[0])); break; } case 0x33: // chr { char buf[2]; - buf[0] = int(env->top(0).to_number()); + // SwiffPlayer.dll 0x100931C7: _ftol's 64-bit result, then AL. + const unsigned char byte = static_cast( + bf2x87::toInt64Truncate(env->top(0).to_number())); + memcpy(&buf[0], &byte, sizeof(byte)); buf[1] = 0; env->top(0).set_string(buf); break; } case 0x34: // get timer - // Push milliseconds since we started playing. - env->push(floorf(env->m_target->get_timer() * 1000.0f)); + // SwiffPlayer.dll 0x100931F1..0x10093214 stores the product + // as float before the double floor wrapper at 0x1008A070. + env->push(float(floor_float(bf2x87::store(bf2x87::mul( + bf2x87::Real(env->m_target->get_timer()), bf2x87::Real(1000.0f)))))); break; case 0x35: // mb substring @@ -2826,13 +2951,9 @@ namespace gameswf } case 0x3B: // delete2 { - // @@ tulrich: delete is not valid here! Do we actually just want to - // NULL out the object pointer in the environment (to drop the ref)? - // Should at least check the ref count before deleting anything!!! -// as_value obj_name = env->pop(); + // SwiffPlayer.dll 0x1009326A-0x100932A5: perform the raw + // lookup, report, then release the result without changing the stack. as_value obj_ptr = env->get_variable_raw(env->top(0).to_tu_string(), with_stack); -///x delete obj_ptr.to_object(); -// log_error("%08X\n", obj_ptr.to_object()); log_error("todo opcode: %02X\n", action_id); break; } @@ -2848,34 +2969,21 @@ namespace gameswf case 0x3D: // call function { as_value function; - // [DICE-MOD SwiffPlayer #26: a function resolved through a `with` scope runs with + // a function resolved through a `with` scope runs with // THAT object as `this`. mainMenu.swf's ScrollBar.createChildren does // with (this.m_mcScrollVertical) { attachMovie("arrowUp", "arrowUp", getNextHighestDepth()); ... } // Stock 2006 passed this_ptr = NULL, so the sprite builtins fell back to the // environment's target - the root, when the method chain was started from a root-level // init action - and the arrows were attached to _root at depth 259+ with an identity - // transform (retail run L). The shipped player attaches them to the with-object.] - as_object_interface* with_this = NULL; + // transform (retail run L). The shipped player attaches them to the with-object. + // SwiffPlayer.dll 0x10093308 / 0x1009153B: lookup returns + // the first with-scope value and its receiver, callable or not. + as_object_interface* with_this = env->m_this_object; if (env->top(0).get_type() == as_value::STRING) { // Function is a string; lookup the function. const tu_string& function_name = env->top(0).to_tu_string(); - for (int wi = with_stack.size() - 1; wi >= 0; wi--) - { - as_object_interface* wo = with_stack[wi].m_object.get_ptr(); - as_value wv; - if (wo && wo->get_member(tu_stringi(function_name.c_str()), &wv) - && (wv.get_type() == as_value::C_FUNCTION || wv.get_type() == as_value::AS_FUNCTION)) - { - function = wv; - with_this = wo; - break; - } - } - if (with_this == NULL) - { - function = env->get_variable(function_name, with_stack); - } + function = env->get_variable(function_name, with_stack, &with_this); if (function.get_type() != as_value::C_FUNCTION && function.get_type() != as_value::AS_FUNCTION) @@ -2889,7 +2997,8 @@ namespace gameswf // Hopefully the actual function object is here. function = env->top(0); } - int nargs = (int) env->top(1).to_number(); + int nargs = bf2x87::toIntTruncate(env->top(1).to_number()); + if (with_this == NULL) with_this = env->m_target; as_value result = call_method(function, env, with_this, nargs, env->get_top_index() - 2); env->drop(nargs + 1); env->top(0) = result; @@ -2928,96 +3037,46 @@ namespace gameswf case 0x40: // new { as_value classname = env->pop(); - IF_VERBOSE_ACTION(log_msg("---new object: %s\n", - classname.to_tu_string().c_str())); - int nargs = (int) env->pop().to_number(); - // [DICE-MOD SwiffPlayer: the shipped NewObject (interpreter sub_100925A0, case - // 0x40) consults its BUILTIN CONSTRUCTOR TABLE first - the eight names its - // action_init registers through sub_1008DDE0: XML, XMLNode, String, Array, - // Boolean, Number, Color, Object - and only then get_variable(). Stock 2006 goes - // through the variable lookup alone, where a sprite child or variable of the same - // name shadows the builtin. Reproduced for exactly those eight names.] - as_value constructor; - { - static const char* s_builtin_ctors[] = - { "XML", "XMLNode", "String", "Array", "Boolean", "Number", "Color", "Object" }; - bool builtin = false; - for (int bi = 0; bi < (int) (sizeof(s_builtin_ctors) / sizeof(s_builtin_ctors[0])); bi++) - { - if (classname.to_tu_string() == s_builtin_ctors[bi]) - { - as_value ctor_val; - if (s_global->get_member(classname.to_tu_stringi(), &ctor_val) - && ctor_val.get_type() == as_value::C_FUNCTION) - { - constructor = ctor_val; - builtin = true; - } - break; - } - } - if (!builtin) - { - constructor = env->get_variable(classname.to_tu_string(), with_stack); - } - } + int nargs = bf2x87::toIntTruncate(env->pop().to_number()); + // SwiffPlayer.dll 0x100935D1-0x10093674: look up the private + // factory table before resolving a script constructor. + as_c_function_ptr factory = NULL; as_value new_obj; - if (constructor.get_type() == as_value::C_FUNCTION) - { - // C function is responsible for creating the new object and setting members. - (constructor.to_c_function())(fn_call(&new_obj, NULL, env, nargs, env->get_top_index())); - } - else if (as_as_function* ctor_as_func = constructor.to_as_function()) + if (s_constructors.get(classname.to_tu_stringi(), &factory)) { - // This function is being used as a constructor; make sure - // it has a prototype object. - ctor_as_func->lazy_create_properties(); - assert(ctor_as_func->m_properties); - - // Set up the prototype. - as_value proto; - ctor_as_func->m_properties->get_member("prototype", &proto); - - assert(proto.to_object() != NULL); - - // Create an empty object, with a ref to the constructor's prototype. - smart_ptr new_obj_ptr(new as_object(proto.to_object())); - - // Set up the constructor member. - new_obj_ptr->set_member("constructor", constructor); - new_obj_ptr->set_member_flags("constructor", 1); - - new_obj.set_as_object_interface(new_obj_ptr.get_ptr()); - - // Call the actual constructor function; new_obj is its 'this'. - // We don't need the function result. - call_method(constructor, env, new_obj_ptr.get_ptr(), nargs, env->get_top_index()); + as_value factory_result; + factory(fn_call(&factory_result, NULL, env, nargs, env->get_top_index())); + new_obj.set_as_object_interface(factory_result.get_type() == as_value::OBJECT + ? factory_result.m_object_value : NULL); } else { - if (classname != "String") { - log_error("can't create object with unknown class '%s'\n", - classname.to_tu_string().c_str()); - { // [TEMP] SwiffPlayer diagnostic: what did the lookup return, and what does _global hold? - as_value g; - const bool in_global = s_global->get_member(classname.to_tu_stringi(), &g); - as_object_interface* o = constructor.to_object(); - log_error("[TEMP] new %s: lookup type=%d%s; _global.%s %s type=%d\n", - classname.to_tu_string().c_str(), (int) constructor.get_type(), - (o && o->to_movie()) ? " (a movie clip)" : "", - classname.to_tu_string().c_str(), in_global ? "present" : "absent", - in_global ? (int) g.get_type() : -1); - } - } else { - log_msg("Created special String class\n"); + as_value constructor = env->get_variable(classname.to_tu_string(), with_stack); + if (as_as_function* ctor_as_func = constructor.to_as_function()) + { + // SwiffPlayer.dll 0x100936C8/0x100936DE: install the + // instance prototype, then call directly without a result slot. + as_object_interface* proto = ctor_as_func->m_properties->m_instance_prototype; + smart_ptr instance(new as_object(proto)); + new_obj.set_as_object_interface(instance.get_ptr()); + (*ctor_as_func)(fn_call(NULL, instance.get_ptr(), env, nargs, env->get_top_index())); + } + else + { + // SwiffPlayer.dll 0x100936E3/0x1009373E: even a + // failed construction pushes an OBJECT with a null pointer. + log_error("can't create unregistered object '%s'\n", classname.to_string()); + new_obj.set_as_object_interface(NULL); } } + // SwiffPlayer.dll 0x10093714-0x10093730: a result other than the + // published root's object is linked into the collector list (common + // slot +0xC, 0x10008F10) before the drop/push. + // [CHOSEN, not recovered] owner decision 2026-11-09 (issue #7): the + // collector list stays inactive; native reference counting owns it. env->drop(nargs); env->push(new_obj); -#if 0 - log_msg("new object %s at %p\n", classname.to_tu_string().c_str(), new_obj); -#endif break; } case 0x41: // declare local @@ -3029,52 +3088,35 @@ namespace gameswf } case 0x42: // init array { - int array_size = (int) env->pop().to_number(); - - //log_msg("xxx init array: size = %d, top of stack = %d\n", - // // array_size, env->get_top_index());//xxxxx - -// // Call the array constructor, to create an empty array. -// as_value result; -// as_global_array_ctor(fn_call(&result, NULL, env, 0, env->get_top_index())); - -// as_object_interface* ao = result.to_object(); -// assert(ao); - -// // @@ TODO Set array size. -// // ao->set_length(whatever); or something - -// // Fill the elements with the initial values from the stack. -// as_value index_number; -// for (int i = 0; i < array_size; i++) -// { -// // @@ TODO a set_member that takes an int or as_value? -// index_number.set_int(i); -// ao->set_member(index_number.to_string(), env->pop()); -// } - -// env->push(result); - -// //log_msg("xxx init array end: top of stack = %d, trace(top(0)) =", -// // env->get_top_index());//xxxxxxx - as_global_trace(fn_call(NULL, NULL, env, 1, env->get_top_index())); //xxxx - + // SwiffPlayer.dll 0x1009378A: pop count, then elements in index order. + smart_ptr obj(new as_array_object); + int array_size = bf2x87::toIntTruncate(env->pop().to_number()); + for (int i = 0; i < array_size; ++i) + { + char name[20]; + _snprintf(name, sizeof(name), "%d", i); + // SwiffPlayer.dll 0x10093823-0x10093865 constructs the + // name before popping, then releases the value before the name. + const tu_stringi member_name(name); + const as_value value = env->pop(); + obj->set_member(member_name, value); + } + env->push(as_value(static_cast(obj.get_ptr()))); break; } case 0x43: // declare object (ActionInitObject) { - // [DICE-MOD SwiffPlayer: implement the object literal `{k1:v1, k2:v2}`. Stock - // 2006 gameswf logs "todo opcode: 43" and leaves the operands on the stack, so - // every AS2 object literal both loses its value and unbalances the stack. - // menu.swf uses one. Per the SWF spec the stack is - // value1, name1, ... valueN, nameN, numProps (numProps on top) - // and the result is the new object. See GAMESWF_DIVERGENCES.md.] - int num_props = (int) env->pop().to_number(); + // SwiffPlayer.dll 0x100938AE: object literal, count then value/name pairs. smart_ptr obj(new as_object); + int num_props = bf2x87::toIntTruncate(env->pop().to_number()); for (int i = 0; i < num_props; i++) { - const tu_stringi name = env->pop().to_tu_string().to_tu_stringi(); const as_value value = env->pop(); + // SwiffPlayer.dll 0x1009391F/0x1009392D: value before name. + // 0x1009392D-0x10093990 keeps the popped name alive + // through the member write and name-string destruction. + const as_value name_value = env->pop(); + const tu_stringi name = name_value.to_tu_string().to_tu_stringi(); obj->set_member(name, value); } as_value result; @@ -3082,100 +3124,65 @@ namespace gameswf env->push(result); break; } + // SwiffPlayer.dll 0x100939AF / 0x100939C7 / 0x100939DF. case 0x44: // type of - { - switch(env->top(0).get_type()) - { - case as_value::UNDEFINED: - env->top(0).set_string("undefined"); - break; - case as_value::STRING: - env->top(0).set_string("string"); - break; - case as_value::NUMBER: - env->top(0).set_string("number"); - break; - case as_value::BOOLEAN: - env->top(0).set_string("boolean"); - break; - case as_value::OBJECT: - env->top(0).set_string("object"); - break; - case as_value::NULLTYPE: - env->top(0).set_string("null"); - break; - case as_value::AS_FUNCTION: - case as_value::C_FUNCTION: - env->top(0).set_string("function"); - break; - default: - log_error("typeof unknown type: %02X\n", env->top(0).get_type()); - break; - } - break; - } case 0x45: // get target + case 0x46: // enumerate { - // @@ TODO log_error("todo opcode: %02X\n", action_id); break; } - case 0x46: // enumerate + case 0x47: // add_t (typed) { - as_value var_name = env->pop(); - const tu_string& var_string = var_name.to_tu_string(); - - as_value variable = env->get_variable(var_string, with_stack); - - if (variable.to_object() == NULL) + // SwiffPlayer.dll 0x100939F7: only two numbers add numerically. + // [CHOSEN, not recovered] S3 bridge: retain the 2006 NULLTYPE + // alongside UNDEFINED as its native representation of retail tag zero. + const as_value::type left = env->top(1).get_type(); + const as_value::type right = env->top(0).get_type(); + if (left == as_value::NUMBER && right == as_value::NUMBER) { - break; + env->top(1) += env->top(0); } - const as_object* object = (as_object*) (variable.to_object()); - - // The end of the enumeration - as_value nullvalue; - nullvalue.set_null(); - env->push(nullvalue); - IF_VERBOSE_ACTION(log_msg("---enumerate - push: NULL\n")); - - // [DICE-MOD SwiffPlayer #49] the object's own enumerate (arrays: indices only). - const_cast(object)->enumerate(env); - - break; - } - case 0x47: // add_t (typed) - { - if (env->top(0).get_type() == as_value::STRING - || env->top(1).get_type() == as_value::STRING) + else if (left == as_value::NUMBER && (right == as_value::UNDEFINED || right == as_value::NULLTYPE)) { - env->top(1).convert_to_string_versioned(version); - env->top(1).string_concat(env->top(0).to_tu_string_versioned(version)); + env->top(1) = env->top(1); + } + else if ((left == as_value::UNDEFINED || left == as_value::NULLTYPE) && right == as_value::NUMBER) + { + env->top(1) = env->top(0); } else { - env->top(1) += env->top(0); + // SwiffPlayer.dll 0x10093A94-0x10093AAB: capture the + // destination before the right operand's conversion callback. + as_value& destination = env->top(1); + destination.string_concat(env->top(0).to_tu_string()); } env->drop(1); break; } case 0x48: // less than (typed) { - if (env->top(1).get_type() == as_value::STRING) + as_value& destination = env->top(1); + if (destination.get_type() == as_value::STRING) { - env->top(1).set_bool(env->top(1).to_tu_string() < env->top(0).to_tu_string()); + // SwiffPlayer.dll 0x10093AE2/0x10093AEA: right before left. + const tu_string& right = env->top(0).to_tu_string(); + const tu_string& left = destination.to_tu_string(); + destination.set_bool(left < right); } else { - env->top(1).set_bool(env->top(1) < env->top(0)); + destination.set_bool(destination < env->top(0)); } env->drop(1); break; } case 0x49: // equal (typed) { - // @@ identical to untyped equal, as far as I can tell... - env->top(1).set_bool(env->top(1) == env->top(0)); + // SwiffPlayer.dll shares 0x100927AA with opcode 0x0E. + as_value& left = env->top(1); + left.set_bool(left == env->top(0)); env->drop(1); break; } @@ -3186,7 +3193,7 @@ namespace gameswf } case 0x4B: // to string { - env->top(0).convert_to_string_versioned(version); + env->top(0).convert_to_string(); break; } case 0x4C: // dup @@ -3202,32 +3209,42 @@ namespace gameswf } case 0x4E: // get member { - s_last_member_name = env->top(0).to_tu_string(); // [TEMP] RW-89 diagnostic + // SwiffPlayer.dll 0x10093C3C-0x10093C4A: a null script-function + // receiver survives unchanged; only its member-name operand is dropped. + if (env->top(1).get_type() == as_value::AS_FUNCTION + && env->top(1).to_as_function() == NULL) + { + env->drop(1); + break; + } as_object_interface* obj = env->top(1).to_object(); // Special case: String has a member "length" - if (obj == NULL - && env->top(1).get_type() == as_value::STRING - && env->top(0).to_tu_stringi() == "length") + // SwiffPlayer.dll 0x10093CEF: an unknown primitive-string + // member leaves the string operand unchanged. + if (obj == NULL && env->top(1).get_type() == as_value::STRING) { - int len = env->top(1).to_tu_string_versioned(version).utf8_length(); - env->top(1).set_int(len); + if (env->top(0).to_tu_stringi() == "length") + { + // SwiffPlayer.dll 0x10093D23 -> 0x1008B100 -> 0x1006E490 + // counts UTF-8 characters, unlike opcode 0x14's byte length. + int len = env->top(1).to_tu_string().utf8_length(); + env->top(1).set_int(len); + } } else { env->top(1).set_undefined(); // int nargs = (int) env->top(1).to_number(); if (obj) { - obj->get_member(env->top(0).to_tu_string(), &(env->top(1))); - if (env->top(1).to_object() == NULL) { - IF_VERBOSE_ACTION(log_msg("-- get_member %s=%s\n", - env->top(0).to_tu_string().c_str(), - env->top(1).to_tu_string().c_str())); - } else { - IF_VERBOSE_ACTION(log_msg("-- get_member %s=%s at %p\n", - env->top(0).to_tu_string().c_str(), - env->top(1).to_tu_string().c_str(), env->top(1).to_object())); - } + // SwiffPlayer.dll 0x10093D43/0x10093D87: get into a + // temporary, then reacquire the operand after the accessor call. + as_value member_value; + obj->get_member(env->top(0).to_tu_string(), &member_value); + env->top(1) = member_value; + // 0x10093DAD/0x10093DC5 logs the temporary result only. + IF_VERBOSE_ACTION(log_msg("-- get member: %s\n", + member_value.to_tu_string().c_str())); } else { @@ -3240,25 +3257,27 @@ namespace gameswf } case 0x4F: // set member { - as_object_interface* obj = env->top(2).to_object(); + // SwiffPlayer.dll 0x10093DEA-0x10093E3B dispatches OBJECT and + // AS_FUNCTION separately; the function arm has no null-pointer guard. + as_object_interface* obj = NULL; + if (env->top(2).get_type() == as_value::OBJECT) + obj = env->top(2).m_object_value; + else if (env->top(2).get_type() == as_value::AS_FUNCTION) + obj = env->top(2).to_as_function()->m_properties; if (obj) { - obj->set_member(env->top(1).to_tu_string(), env->top(0)); - IF_VERBOSE_ACTION( - log_msg("-- set_member %s.%s=%s\n", - env->top(2).to_tu_string().c_str(), - env->top(1).to_tu_string().c_str(), - env->top(0).to_tu_string().c_str())); - } - else - { - // Invalid object, can't set. - IF_VERBOSE_ACTION( - log_msg("-- set_member %s.%s=%s on invalid object!\n", - env->top(2).to_tu_string().c_str(), - env->top(1).to_tu_string().c_str(), - env->top(0).to_tu_string().c_str())); + // 0x10093DFD caches the value before converting the name. + const as_value& value = env->top(0); + const tu_string& name = env->top(1).to_tu_string(); + obj->set_member(name, value); } + // SwiffPlayer.dll 0x10093E3E-0x10093EA8 also logs invalid + // receivers, converting value, name, then receiver in that order. + IF_VERBOSE_ACTION( + const char* value = env->top(0).to_tu_string().c_str(); + const char* name = env->top(1).to_tu_string().c_str(); + const char* receiver = env->top(2).to_tu_string().c_str(); + log_msg("-- set member: %s.%s=%s\n", receiver, name, value)); env->drop(3); break; } @@ -3270,32 +3289,61 @@ namespace gameswf break; case 0x52: // call method { - int nargs = (int) env->top(2).to_number(); + // SwiffPlayer.dll 0x10093F62-0x10093FCE: capture the OBJECT + // receiver before arity conversion, then borrow the name string. + as_object_interface* obj = env->top(1).get_type() == as_value::OBJECT + ? env->top(1).m_object_value : NULL; + int nargs = bf2x87::toIntTruncate(env->top(2).to_number()); as_value result; const tu_string& method_name = env->top(0).to_tu_string(); - as_object_interface* obj = env->top(1).to_object(); - // [DICE-MOD SwiffPlayer: a DIRECT call of a function value - the method name is - // undefined/empty and the "object" operand is the function itself: `super(args)`, - // and `f(args)` on a function-valued expression. The shipped CallMethod (interpreter - // sub_100925A0, case 0x52) tests for the "undefined" name first and calls the function - // with the CURRENT this (env+8212). Stock 2006 fell through to "call_method - // 'undefined' on invalid object", so no class constructor ever reached its base.] - const bool direct_call = env->top(0).get_type() == as_value::UNDEFINED - || method_name.length() == 0; - if (direct_call - && (env->top(1).get_type() == as_value::AS_FUNCTION - || env->top(1).get_type() == as_value::C_FUNCTION)) + s_call_super = NULL; + // SwiffPlayer.dll 0x10094113 compares the converted name with + // the literal "undefined"; the direct call keeps the current receiver. + const bool direct_call = method_name == "undefined"; + if (!obj && env->top(1).get_type() == as_value::AS_FUNCTION) { - as_object_interface* current_this = env->m_this_object - ? env->m_this_object : static_cast(env->m_target); - result = call_method(env->top(1), env, current_this, nargs, env->get_top_index() - 3); - } - else if (direct_call && env->top(1).get_type() == as_value::UNDEFINED) - { - // super() in a class whose superclass is not a script function: DICE's - // `MovieClip` is a no-op C function, so ActionExtends leaves __constructor__ - // undefined and the call has nothing to run. Quietly nothing, as in the - // shipped player. + as_as_function* receiver = env->top(1).to_as_function(); + if (direct_call) + { + // SwiffPlayer.dll 0x10094120-0x10094141: copy the operand and + // call only a non-null script function (super() of a class whose + // superclass is not a script function runs nothing). + as_value function = env->top(1); + if (function.to_as_function()) + { + // 0x10094147-0x100941DF: the next super context comes from + // that function's prototype when a current receiver exists. + as_object_interface* proto = receiver->m_properties->m_instance_prototype; + if (proto && env->m_this_object) + { + as_value constructor; + if (proto->get_member("__constructor__", &constructor)) + s_call_super = constructor.to_as_function(); + } + result = call_method(function, env, env->m_this_object, nargs, env->get_top_index() - 3); + } + } + else + { + // SwiffPlayer.dll 0x1009423A-0x10094250: member lookup on the + // function object itself, without a null-function guard. + as_value function; + if (receiver->m_properties->get_member(method_name, &function)) + { + if (function.get_type() == as_value::C_FUNCTION + || function.get_type() == as_value::AS_FUNCTION) + { + // 0x100942BF: the call keeps the current receiver. + result = call_method(function, env, env->m_this_object, nargs, env->get_top_index() - 3); + } + else + { + // 0x1009426B-0x100942A7 gates the error on verbose actions. + IF_VERBOSE_ACTION(log_error("error: call_method: '%s' is not a method\n", + method_name.c_str())); + } + } + } } else if (obj) { @@ -3305,77 +3353,23 @@ namespace gameswf if (method.get_type() != as_value::C_FUNCTION && method.get_type() != as_value::AS_FUNCTION) { - log_error("error: call_method: '%s' is not a method\n", - method_name.c_str()); + // SwiffPlayer.dll 0x10094083/0x100940B7 gates errors. + IF_VERBOSE_ACTION(log_error("error: call_method: '%s' is not a method\n", + method_name.c_str())); } else { - // [DICE-MOD SwiffPlayer #30: `super.method(args)`. The `super` value is - // the parent class's constructor FUNCTION; as an object that is its - // properties object, whose prototype chain reaches the parent's - // methods. A method found through that chain runs with the CURRENT - // `this` (Flash's super call), while a function's OWN member (a static - // method, Class.helper()) keeps the function object as `this`.] - as_object_interface* call_this = obj; - if (env->top(1).get_type() == as_value::AS_FUNCTION) - { - as_object* props = obj->cast_to_as_object(); - as_member own; - if (props == NULL || props->m_members.get(method_name, &own) == false) - { - call_this = env->m_this_object - ? env->m_this_object : static_cast(env->m_target); - } - } result = call_method( method, env, - call_this, + obj, nargs, env->get_top_index() - 3); } } else { - log_error("error: call_method can't find method %s (last member read: '%s')\n", method_name.c_str(), s_last_member_name.c_str()); - } - } - else if (env->top(1).get_type() == as_value::STRING) - { - // Handle methods on literal strings. - string_method( - fn_call(&result, NULL, env, nargs, env->get_top_index() - 3), - method_name.to_tu_stringi(), - env->top(1).to_tu_string_versioned(version)); - } - else if (env->top(1).get_type() == as_value::C_FUNCTION) - { - // Catch method calls on String - // constructor. There may be a cleaner - // way to do this. Perhaps we call the - // constructor function with a special flag, to - // indicate that it's a method call? - if (env->top(1).to_c_function() == string_ctor) - { - tu_string dummy; - string_method( - fn_call(&result, NULL, env, nargs, env->get_top_index() - 3), - method_name.to_tu_stringi(), - dummy); - } - else if (env->top(1).to_c_function() == as_global_object_ctor - && method_name == "registerClass") - { - // [DICE-MOD SwiffPlayer: Object.registerClass - see object_register_class.] - object_register_class( - fn_call(&result, NULL, env, nargs, env->get_top_index() - 3)); - } - else - { - log_error("error: method call on unknown c function.\n"); - // [TEMP] SwiffPlayer diagnostic: which method on which builtin? - log_error("[TEMP] c-function method call: %s on %s\n", method_name.c_str(), - env->top(1).to_c_function() == as_global_object_ctor ? "Object" : ""); + IF_VERBOSE_ACTION(log_error("error: call_method can't find method %s\n", method_name.c_str())); } } else @@ -3388,7 +3382,8 @@ namespace gameswf } else { - log_error("error: call_method '%s' on invalid object (last member read: '%s').\n", method_name.c_str(), s_last_member_name.c_str()); + // SwiffPlayer.dll 0x1009433A-0x1009435B. + IF_VERBOSE_ACTION(log_error("error: call_method '%s'op on invalid object.\n", method_name.c_str())); } } env->drop(nargs + 2); @@ -3397,55 +3392,46 @@ namespace gameswf } case 0x53: // new method { - // [DICE-MOD SwiffPlayer: ActionNewMethod - `new obj.Class(args)`. Stock 2006 logged - // "todo opcode: 53" and left the operands on the stack. Per the SWF spec the stack - // is `args..., nargs, object, name` (name on top); the constructor is object.name, - // or the object itself when the name is empty/undefined. The shipped handler - // (interpreter sub_100925A0, case 0x53) then does what its NewObject does: a fresh - // object whose __proto__ is Class.prototype, constructor run with it as `this`. - // Same shape as ActionNewObject (0x40) above.] - as_value method_name = env->pop(); - as_value obj_val = env->pop(); - int nargs = (int) env->pop().to_number(); - - as_value constructor; - if (method_name.get_type() == as_value::UNDEFINED - || method_name.to_tu_string().length() == 0) + // SwiffPlayer.dll 0x10094398-0x1009455C: consume name, receiver + // and count first; failed lookup leaves the arguments and pushes no result. + tu_string method_name; { - constructor = obj_val; + // 0x10094398-0x100943BC: copy the converted name, then + // release the popped value before fetching the receiver. + as_value method_value = env->pop(); + method_name = method_value.to_tu_string(); } - else + as_object_interface* receiver; { - as_object_interface* o = obj_val.to_object(); - if (o) - { - o->get_member(method_name.to_tu_stringi(), &constructor); - } + // 0x100943C1-0x100943E1: the named-member form keeps + // only a raw OBJECT pointer, releasing before arity conversion. + as_value obj_val = env->pop(); + receiver = obj_val.get_type() == as_value::OBJECT ? obj_val.m_object_value : NULL; } + int nargs = bf2x87::toIntTruncate(env->pop().to_number()); + + as_value constructor; + if (!receiver || !receiver->get_member(method_name.to_tu_stringi(), &constructor)) break; as_value new_obj; - if (constructor.get_type() == as_value::C_FUNCTION) - { - (constructor.to_c_function())(fn_call(&new_obj, NULL, env, nargs, env->get_top_index())); - } - else if (as_as_function* ctor_as_func = constructor.to_as_function()) + if (constructor.get_type() == as_value::C_FUNCTION + || constructor.get_type() == as_value::AS_FUNCTION) { - ctor_as_func->lazy_create_properties(); - as_value proto; - if (ctor_as_func->m_properties) - { - ctor_as_func->m_properties->get_member("prototype", &proto); - } - smart_ptr new_obj_ptr(new as_object(proto.to_object())); - new_obj_ptr->set_member("constructor", constructor); - new_obj_ptr->set_member_flags("constructor", 1); + // SwiffPlayer.dll 0x100944D1 / 0x100944F5: a C function + // leaves the script pointer null and still reads its prototype. + as_as_function* ctor_as_func = constructor.to_as_function(); + as_object_interface* proto = ctor_as_func->m_properties->m_instance_prototype; + smart_ptr new_obj_ptr(new as_object(proto)); new_obj.set_as_object_interface(new_obj_ptr.get_ptr()); + // SwiffPlayer.dll 0x100944FF links the new object into the collector + // list (slot +0xC) before the call. [CHOSEN, not recovered] owner + // decision 2026-11-09 (issue #7): that list stays inactive. call_method(constructor, env, new_obj_ptr.get_ptr(), nargs, env->get_top_index()); } else { - log_error("error: new method: '%s' is not a constructor\n", - method_name.to_tu_string().c_str()); + IF_VERBOSE_ACTION(log_error("error: call_method: '%s' is not a method\n", method_name.c_str())); + break; } env->drop(nargs); @@ -3456,33 +3442,19 @@ namespace gameswf // @@ TODO log_error("todo opcode: %02X\n", action_id); break; - case 0x55: // enumerate2 [DICE-MOD SwiffPlayer #43] + case 0x55: // enumerate2 { - // [DICE-MOD SwiffPlayer #43] ActionEnumerate2 (SWF 6): the object itself is on the - // stack (Enumerate, 0x46, takes a variable NAME). Stock 2006 logged "todo opcode: 55" - // and pushed nothing - not even the null terminator - so a for-in loop read garbage - // below the stack and never ended: mainMenu.swf's sort-button toggleCheck() spins - // through its sibling group with it, and the client hung on the multiplayer tab - // (interactive run drive3). A non-object still gets the terminator. + // SwiffPlayer.dll 0x1009457D-0x100945BD: save/pop the value, + // push the sentinel, then dispatch +0x28 without a null guard. as_value variable = env->pop(); - - if (variable.to_object() == NULL) - { - as_value nullvalue; - nullvalue.set_null(); - env->push(nullvalue); - break; - } - const as_object* object = (as_object*) (variable.to_object()); + as_object_interface* object = variable.to_object_raw(); // The end of the enumeration - as_value nullvalue; - nullvalue.set_null(); - env->push(nullvalue); - IF_VERBOSE_ACTION(log_msg("---enumerate - push: NULL\n")); + // SwiffPlayer.dll 0x100945AC constructs the STRING "NULL" sentinel. + env->push("NULL"); - // [DICE-MOD SwiffPlayer #49] the object's own enumerate (arrays: indices only). - const_cast(object)->enumerate(env); + // the object's own enumerate (arrays: indices only). + object->enumerate(env); break; } @@ -3511,93 +3483,67 @@ namespace gameswf env->drop(1); break; case 0x66: // strict equal - if (env->top(1).get_type() != env->top(0).get_type()) + { + // SwiffPlayer.dll 0x1009470F retains the left destination + // across the equality helper when the tags match. + as_value& left = env->top(1); + if (left.get_type() != env->top(0).get_type()) { // Types don't match. - env->top(1).set_bool(false); + left.set_bool(false); env->drop(1); } else { - env->top(1).set_bool(env->top(1) == env->top(0)); + left.set_bool(left == env->top(0)); env->drop(1); } break; + } case 0x67: // gt (typed) + { if (env->top(1).get_type() == as_value::STRING) { - env->top(1).set_bool(env->top(1).to_tu_string() > env->top(0).to_tu_string()); + // SwiffPlayer.dll 0x1009476D/0x10094775: right before left. + as_value& destination = env->top(1); + const tu_string& right = env->top(0).to_tu_string(); + const tu_string& left = destination.to_tu_string(); + destination.set_bool(left > right); } else { - env->top(1).set_bool(env->top(1).to_number() > env->top(0).to_number()); + // SwiffPlayer.dll 0x100947AC/0x100947B6: left before right. + const double left = env->top(1).to_number(); + const double right = env->top(0).to_number(); + env->top(1).set_bool(left > right); } env->drop(1); break; + } case 0x68: // string gt - env->top(1).set_bool(env->top(1).to_tu_string() > env->top(0).to_tu_string()); + { + // SwiffPlayer.dll 0x10094803/0x1009480B: right before left. + as_value& destination = env->top(1); + const tu_string& right = env->top(0).to_tu_string(); + const tu_string& left = destination.to_tu_string(); + destination.set_bool(left > right); env->drop(1); break; + } case 0x69: // extends (ActionExtends) { - // [DICE-MOD SwiffPlayer: implement AS2 class inheritance. Stock 2006 gameswf - // logs "todo opcode: 69" and leaves BOTH operands on the stack; menu.swf runs it - // three times, so three subclasses lose their prototype chain (their inherited - // methods then resolve to undefined) and the stack is left 6 deep. - // - // Modelled on the shipped handler (SwiffPlayer.dll (2).i64, interpreter - // sub_100925A0 case 0x69): the SUPERCLASS is popped first (it is on top of the - // stack), then the subclass; both are converted to functions; then - // subclass.prototype.__constructor__ = superclass; - // subclass.prototype.__proto__ = superclass.prototype; - // on the subclass's EXISTING prototype object (nothing is replaced), and a - // superclass that is not a script function - DICE's `MovieClip` is a no-op C - // function - simply leaves the chain empty, with no error. The first cut of - // this divergence popped in the wrong order, which inverted every chain and - // flagged `extends MovieClip` as "subclass is not an object or function" - // (retail 2026-09-02). gameswf's as_object prototype pointer IS its __proto__ - // chain (set_member/get_member "__proto__" reach m_prototype). See - // GAMESWF_DIVERGENCES.md.] - as_value superclass = env->pop(); - as_value subclass = env->pop(); - - as_as_function* sub_fn = subclass.to_as_function(); - as_as_function* super_fn = superclass.to_as_function(); - if (sub_fn == NULL) - { - log_error("error: extends: subclass is not a function\n"); - break; - } - - sub_fn->lazy_create_properties(); - as_value sub_proto_val; - if (sub_fn->m_properties) - { - sub_fn->m_properties->get_member("prototype", &sub_proto_val); - } - as_object_interface* sub_proto = sub_proto_val.to_object(); - if (sub_proto == NULL) - { - log_error("error: extends: subclass has no prototype object\n"); - break; - } - - as_value super_proto_val; - if (super_fn) - { - super_fn->lazy_create_properties(); - if (super_fn->m_properties) - { - super_fn->m_properties->get_member("prototype", &super_proto_val); - } - } - sub_proto->set_member("__constructor__", super_fn ? as_value(super_fn) : as_value()); - // This 2006 as_object keeps its __proto__ chain under the member name "prototype" - // (set_member/get_member "prototype" ARE m_prototype; a member literally named - // "__proto__" would be an inert plain member - the first cut of this handler set - // that and no inherited method ever resolved). - sub_proto->set_member("prototype", super_proto_val); + // SwiffPlayer.dll 0x1009481C-0x100948F6: discard each popped + // value before reading the next; neither subclass nor prototype is guarded. + as_as_function* super_fn = env->pop().to_as_function(); + as_as_function* sub_fn = env->pop().to_as_function(); + as_object_interface* sub_proto = sub_fn->m_properties->m_instance_prototype; + sub_proto->set_member("__constructor__", as_value(super_fn)); + // 0x100948AC/0x100948BA: a non-script superclass supplies OBJECT null. + as_object_interface* super_proto = super_fn + ? super_fn->m_properties->m_instance_prototype : NULL; + // 0x100948CF reloads after the first virtual write, which can run script. + sub_fn->m_properties->m_instance_prototype->set_member("__proto__", as_value(super_proto)); break; } @@ -3647,24 +3593,6 @@ namespace gameswf (*s_fscommand_handler)(env->get_target()->get_root_interface(), url + 10, target); } } - else - { -#ifdef EXTERN_MOVIE -// log_error("get url: target=%s, url=%s\n", target, url); - - tu_string tu_target = target; - movie* target_movie = env->find_target(tu_target); - if (target_movie != NULL) - { - movie* root_movie = env->get_target()->get_root_movie(); - attach_extern_movie(url, target_movie, root_movie); - } - else - { - log_error("get url: target %s not found\n", target); - } -#endif // EXTERN_MOVIE - } break; } @@ -3673,7 +3601,7 @@ namespace gameswf { int reg = m_buffer[pc + 3]; // Save top of stack in specified register. - // [DICE-MOD SwiffPlayer #55] the environment's bank, for timeline code and function + // the environment's bank, for timeline code and function // bodies alike - the shipped case 0x87 assigns env+0x10+32*reg (a byte operand). *(env->register_ptr(reg)) = env->top(0); @@ -3698,10 +3626,8 @@ namespace gameswf case 0x8A: // wait for frame { - // If we haven't loaded a specified frame yet, then we're supposed to skip - // some specified number of actions. - // - // Since we don't load incrementally, just ignore this opcode. + // SwiffPlayer.dll 0x10094A78 reports the unsupported action. + log_error("todo opcode: %02X\n", action_id); break; } @@ -3720,24 +3646,24 @@ namespace gameswf case 0x8C: // go to labeled frame, goto_frame_lbl { char* frame_label = (char*) &m_buffer[pc + 3]; - env->get_target()->goto_labeled_frame(frame_label); + // SwiffPlayer.dll 0x10094AAD: queue the label, then stop. + // [CHOSEN, not recovered] S3 bridge: the native character + // interface exposes the separate queued-label virtual. + env->get_target()->cast_to_character()->queue_goto_labeled_frame(frame_label); + env->get_target()->set_play_state(movie::STOP); break; } case 0x8D: // wait for frame expression (?) { - // Pop the frame number to wait for; if it's not loaded skip the - // specified number of actions. - // - // Since we don't support incremental loading, pop our arg and - // don't do anything. - env->drop(1); + // SwiffPlayer.dll's extended-opcode table selects the default arm. break; } case 0x8E: // function2 { - as_as_function* func = new as_as_function(this, env, next_pc, with_stack); + // SwiffPlayer.dll 0x10094AEA: declarations use the caller's environment. + as_as_function* func = new as_as_function(this, NULL, next_pc, array()); func->set_is_function2(); int i = pc; @@ -3760,7 +3686,6 @@ namespace gameswf // Flags, for controlling register assignment of implicit args. uint16 flags = m_buffer[i] | (m_buffer[i + 1] << 8); i += 2; - func->set_function2_flags(flags); // Get the register assignments and names of the arguments. for (int n = 0; n < nargs; n++) @@ -3769,10 +3694,19 @@ namespace gameswf i++; // @@ security: watch out for possible missing terminator here! - func->add_arg(arg_register, (const char*) &m_buffer[i]); - i += func->m_args.back().m_name.length() + 1; + // SwiffPlayer.dll 0x10094B72-0x10094BD4 parses a temporary + // name but stores only the register number, even for register zero. + const tu_string argument_name((const char*) &m_buffer[i]); + i += argument_name.length() + 1; + // [CHOSEN, not recovered] S3 bridge: native function classes + // share an argument record; function2 does not retain its name. + func->add_arg(arg_register, ""); } + // SwiffPlayer.dll 0x10094BDD installs preloads after parsing + // and discarding every argument name, before reading body length. + func->set_function2_flags(flags); + // Get the length of the actual function code. int length = m_buffer[i] | (m_buffer[i + 1] << 8); i += 2; @@ -3786,11 +3720,10 @@ namespace gameswf as_value function_value(func); if (name.length() > 0) { - // @@ NOTE: should this be m_target->set_variable()??? - env->set_member(name, function_value); + // SwiffPlayer.dll 0x10094DF5: function2 publishes on the movie. + env->get_target()->set_member(name, function_value); } - - // Also leave it on the stack. + // 0x10094E0F: function2 pushes named functions too. env->push_val(function_value); break; @@ -3798,14 +3731,15 @@ namespace gameswf case 0x94: // with { - int frame = m_buffer[pc + 3] | (m_buffer[pc + 4] << 8); - UNUSED(frame); - IF_VERBOSE_ACTION(log_msg("-------------- with block start: stack size is %d\n", with_stack.size())); if (with_stack.size() < 8) { int block_length = m_buffer[pc + 3] | (m_buffer[pc + 4] << 8); int block_end = next_pc + block_length; - as_object_interface* with_obj = env->top(0).to_object(); + // SwiffPlayer.dll 0x10094E82: only OBJECT supplies a scope; + // script functions do not expose their property bag here. + as_object_interface* with_obj = env->top(0).get_type() == as_value::OBJECT + ? env->top(0).m_object_value : NULL; + // 0x10094E8E-0x10094EA4 appends a borrowed scope record. with_stack.push_back(with_stack_entry(with_obj, block_end)); } env->drop(1); @@ -3846,9 +3780,8 @@ namespace gameswf } else if (type == 2) { - as_value nullvalue; - nullvalue.set_null(); - env->push(nullvalue); + // SwiffPlayer.dll 0x10094F66/0x100098C0: STRING "NULL". + env->push("NULL"); IF_VERBOSE_ACTION(log_msg("-------------- pushed NULL\n")); } @@ -3863,7 +3796,7 @@ namespace gameswf // contents of register int reg = m_buffer[3 + i]; i++; - // [DICE-MOD SwiffPlayer #55] the environment's bank for all code - the + // the environment's bank for all code - the // shipped push type 4 reads env+0x10+32*reg. env->push(*(env->register_ptr(reg))); IF_VERBOSE_ACTION( @@ -3907,10 +3840,14 @@ namespace gameswf else if (type == 7) { // int32 - Sint32 val = m_buffer[3 + i] - | (m_buffer[3 + i + 1] << 8) - | (m_buffer[3 + i + 2] << 16) - | (m_buffer[3 + i + 3] << 24); + // SwiffPlayer.dll 0x100950F1-0x1009511A builds a dword + // from unsigned bytes, then passes it as a signed integer. + const Uint32 bits = Uint32(m_buffer[3 + i]) + | (Uint32(m_buffer[3 + i + 1]) << 8) + | (Uint32(m_buffer[3 + i + 2]) << 16) + | (Uint32(m_buffer[3 + i + 3]) << 24); + Sint32 val; + memcpy(&val, &bits, sizeof(val)); i += 4; env->push(val); @@ -3931,7 +3868,7 @@ namespace gameswf { log_error("error: dict_lookup(%d) is out of bounds!\n", id); env->push(0); - IF_VERBOSE_ACTION(log_msg("-------------- pushed 0\n")); + IF_VERBOSE_ACTION(log_msg("-------------- pushed 0 @@\n")); } } else if (type == 9) @@ -3948,7 +3885,7 @@ namespace gameswf log_error("error: dict_lookup(%d) is out of bounds!\n", id); env->push(0); - IF_VERBOSE_ACTION(log_msg("-------------- pushed 0")); + IF_VERBOSE_ACTION(log_msg("-------------- pushed 0 @@")); } } } @@ -3971,31 +3908,14 @@ namespace gameswf const char* url = env->top(1).to_string(); // If the url starts with "FSCommand:", then this is - // a message for the host app. - if (strncmp(url, "FSCommand:", 10) == 0) - { - if (s_fscommand_handler) - { - // Call into the app. - (*s_fscommand_handler)(env->get_target()->get_root_interface(), url + 10, target); - } - } - else - { -#ifdef EXTERN_MOVIE -// log_error("get url2: target=%s, url=%s\n", target, url); - - movie* target_movie = env->find_target(env->top(0)); - if (target_movie != NULL) - { - movie* root_movie = env->get_target()->get_root_movie(); - attach_extern_movie(url, target_movie, root_movie); - } - else + // a message for the host app. + if (strncmp(url, "FSCommand:", 10) == 0) + { + if (s_fscommand_handler) { - log_error("get url2: target %s not found\n", target); + // Call into the app. + (*s_fscommand_handler)(env->get_target()->get_root_interface(), url + 10, target); } -#endif // EXTERN_MOVIE } env->drop(2); break; @@ -4003,7 +3923,8 @@ namespace gameswf case 0x9B: // declare function { - as_as_function* func = new as_as_function(this, env, next_pc, with_stack); + // SwiffPlayer.dll 0x100952C9: no defining environment or with capture. + as_as_function* func = new as_as_function(this, NULL, next_pc, array()); int i = pc; i += 3; @@ -4021,7 +3942,7 @@ namespace gameswf for (int n = 0; n < nargs; n++) { // @@ security: watch out for possible missing terminator here! - func->add_arg(0, (const char*) &m_buffer[i]); + func->add_arg((const char*) &m_buffer[i]); i += func->m_args.back().m_name.length() + 1; } @@ -4042,8 +3963,11 @@ namespace gameswf env->set_member(name, function_value); } - // Also leave it on the stack. - env->push_val(function_value); + else + { + // 0x100953D8: the anonymous branch alone pushes the function. + env->push_val(function_value); + } break; } @@ -4079,70 +4003,21 @@ namespace gameswf case 0x9F: // goto frame expression, goto_frame_exp { - // From Alexi's SWF ref: - // - // Pop a value or a string and jump to the specified - // frame. When a string is specified, it can include a - // path to a sprite as in: - // - // /Test:55 - // - // When f_play is ON, the action is to play as soon as - // that frame is reached. Otherwise, the - // frame is shown in stop mode. - + // SwiffPlayer.dll 0x1009549A: strings use the immediate label + // entry; every other type is numeric. Set play state even if + // label lookup fails, without trying the string as a number. unsigned char play_flag = m_buffer[pc + 3]; movie::play_state state = play_flag ? movie::PLAY : movie::STOP; - movie* target = env->get_target(); - bool success = false; - - if (env->top(0).get_type() == as_value::UNDEFINED) - { - // No-op. - } - else if (env->top(0).get_type() == as_value::STRING) - { - // @@ TODO: parse possible sprite path... - - // Also, if the frame spec is actually a number (not a label), then - // we need to do the conversion... - - const char* frame_label = env->top(0).to_string(); - if (target->goto_labeled_frame(frame_label)) - { - success = true; - } - else - { - // Couldn't find the label. Try converting to a number. - double num; - if (string_to_number(&num, env->top(0).to_string())) - { - int frame_number = int(num); - target->goto_frame(frame_number); - success = true; - } - // else no-op. - } - } - else if (env->top(0).get_type() == as_value::OBJECT) - { - // This is a no-op; see test_goto_frame.swf - } - else if (env->top(0).get_type() == as_value::NUMBER) + if (env->top(0).get_type() == as_value::STRING) { - // Frame numbers appear to be 0-based! @@ Verify. - int frame_number = int(env->top(0).to_number()); - target->goto_frame(frame_number); - success = true; + target->goto_labeled_frame(env->top(0).to_string()); } - - if (success) + else { - target->set_play_state(state); + target->apply_goto_frame(bf2x87::toIntTruncate(env->top(0).to_number())); } - + env->get_target()->set_play_state(state); env->drop(1); break; @@ -4154,6 +4029,12 @@ namespace gameswf } env->set_target(original_target); + s_current_environment = previous_environment; + // SwiffPlayer.dll 0x10095541: falling off the buffer and RETURN restore depth. + if (env->m_stack.size() != original_stack_size) + { + env->m_stack.resize(original_stack_size); + } } @@ -4167,6 +4048,8 @@ namespace gameswf m_type(OBJECT), m_object_value(obj) { + // SwiffPlayer.dll 0x1008AC50: OBJECT tag and nullable object payload. + // [CHOSEN, not recovered] S3 bridge: native objects use one refcount interface. if (m_object_value) { m_object_value->add_ref(); @@ -4179,6 +4062,7 @@ namespace gameswf m_type(AS_FUNCTION), m_as_function_value(func) { + // SwiffPlayer.dll 0x10080E70: type 6 and a conditional function retain. if (m_as_function_value) { m_as_function_value->add_ref(); @@ -4188,6 +4072,7 @@ namespace gameswf const char* as_value::to_string() const // Conversion to string. + // SwiffPlayer.dll 0x1008D0F0. { return to_tu_string().c_str(); } @@ -4195,6 +4080,7 @@ namespace gameswf const tu_stringi& as_value::to_tu_stringi() const { + // SwiffPlayer.dll 0x1008D110 shares the to_tu_string entry. return reinterpret_cast(to_tu_string()); } @@ -4202,14 +4088,24 @@ namespace gameswf const tu_string& as_value::to_tu_string() const // Conversion to const tu_string&. { + // SwiffPlayer.dll 0x1008B430; the native CRT/ownership adapters stay separate. if (m_type == STRING) { /* don't need to do anything */ } else if (m_type == NUMBER) { // @@ Moock says if value is a NAN, then result is "NaN" // INF goes to "Infinity" // -INF goes to "-Infinity" - char buffer[50]; - snprintf(buffer, 50, "%.14g", m_number_value); + // 0x1008B459: _gcvt(value, 30), followed by removal of a final period. + static char buffer[128]; +#if defined(_WIN32) + _gcvt(m_number_value, 30, buffer); +#else + // [CHOSEN, not recovered] POSIX CRT bridge: Darwin has no gcvt. + // MSVCR71 digit/locale equivalence, including nonfinite spelling, is open. + _snprintf(buffer, sizeof(buffer), "%.30g", m_number_value); +#endif + const size_t length = strlen(buffer); + if (length && buffer[length - 1] == '.') buffer[length - 1] = 0; m_string_value = buffer; } else if (m_type == UNDEFINED) @@ -4257,14 +4153,17 @@ namespace gameswf // // TODO: we need an environment in order to call toString()! - // [DICE-MOD SwiffPlayer #50] The shipped to_tu_string (gameswf_as_value_to_tu_string, + // The shipped to_tu_string (gameswf_as_value_to_tu_string, // 0x1008B430, the OBJECT arm): an object with no text value converts to // "" carrying its own address (a 50-byte _snprintf), never to // "[object Object]" - which is what makes the shipped operator== tell two clips // apart. The function arms format "" / "" the // same way there; they are not on any measured path and stay stock here. + // [CHOSEN, not recovered] x64 (https://github.com/B2BF/OpenBF2/issues/7): %zX prints the + // whole address, so two objects never alias through their low 32 bits; on x86 it is + // the shipped %X of the 32-bit address. The three function/object arms share this. char buf[52]; - _snprintf(buf, 50, "", (unsigned int) (uintptr_t) m_object_value); + _snprintf(buf, 50, "", (size_t) (uintptr_t) m_object_value); buf[50] = 0; m_string_value = buf; } @@ -4272,13 +4171,13 @@ namespace gameswf else if (m_type == C_FUNCTION) { char buffer[50]; - snprintf(buffer, 50, "", (unsigned) m_c_function_value); + _snprintf(buffer, 50, "", (size_t) (uintptr_t) m_c_function_value); m_string_value = buffer; } else if (m_type == AS_FUNCTION) { char buffer[50]; - snprintf(buffer, 50, "", (unsigned) m_as_function_value); + _snprintf(buffer, 50, "", (size_t) (uintptr_t) m_as_function_value); m_string_value = buffer; } else @@ -4313,19 +4212,29 @@ namespace gameswf double as_value::to_number() const // Conversion to double. + // SwiffPlayer.dll 0x1008B570. { if (m_type == STRING) { - // @@ Moock says the rule here is: if the - // string is a valid float literal, then it - // gets converted; otherwise it is set to NaN. - // - // Also, "Infinity", "-Infinity", and "NaN" - // are recognized. - if (! string_to_number(&m_number_value, m_string_value.c_str())) + const char* text = m_string_value.c_str(); + if (text[0] == '0' && text[1] == 'x') + { + m_number_value = 0.0; + for (text += 2; *text; ++text) + { + // Retail multiplies before validating the next digit. + m_number_value *= 16.0; + int digit; + if (*text >= '0' && *text <= '9') digit = *text - '0'; + else if (*text >= 'a' && *text <= 'f') digit = *text - 'a' + 10; + else if (*text >= 'A' && *text <= 'F') digit = *text - 'A' + 10; + else break; + m_number_value += digit; + } + } + else { - // Failed conversion to Number. - m_number_value = 0.0; // TODO should be NaN + m_number_value = atof(text); } return m_number_value; } @@ -4353,13 +4262,7 @@ namespace gameswf // Text characters with var names could get in // here. - const char* textval = m_object_value->get_text_value(); - if (textval) - { - return atof(textval); - } - - return 0.0; + return atof(m_object_value->get_text_value()); } else { @@ -4370,6 +4273,7 @@ namespace gameswf bool as_value::to_bool() const // Conversion to boolean. + // SwiffPlayer.dll 0x1008B6B0; NaN remains truthy. { // From Moock if (m_type == STRING) @@ -4415,12 +4319,17 @@ namespace gameswf } else { - assert(m_type == UNDEFINED || m_type == NULLTYPE); return false; } } + as_object_interface* as_value::to_object_raw() const + { + // SwiffPlayer.dll 0x1008A2C0 accepts only type 4, including a null payload. + return m_type == OBJECT ? m_object_value : NULL; + } + as_object_interface* as_value::to_object() const // Return value as an object. { @@ -4431,6 +4340,9 @@ namespace gameswf } else if (m_type == AS_FUNCTION && m_as_function_value != NULL) { + // [CHOSEN, not recovered] S3 bridge: retained native consumers + // access function properties through an object adapter. Recovered type-4 + // extraction uses to_object_raw, never this additional conversion. // Make sure this as_function has properties & // a prototype object attached to it, since those // may be about to be referenced. @@ -4450,6 +4362,7 @@ namespace gameswf // Return value as a C function ptr. Returns NULL if value is // not a C function. { + // SwiffPlayer.dll 0x1008A2D0: no coercion or retained ownership. if (m_type == C_FUNCTION) { // OK. @@ -4465,6 +4378,7 @@ namespace gameswf // Return value as an ActionScript function. Returns NULL if value is // not an ActionScript function. { + // SwiffPlayer.dll 0x1008A2E0: no coercion or retained ownership. if (m_type == AS_FUNCTION) { // OK. @@ -4479,6 +4393,7 @@ namespace gameswf void as_value::convert_to_number() // Force type to number. + // SwiffPlayer.dll 0x1008B770. { set_double(to_number()); } @@ -4487,6 +4402,8 @@ namespace gameswf void as_value::convert_to_string() // Force type to string. { + // SwiffPlayer.dll 0x1008B7C0 releases the old reference before conversion. + drop_refs(); to_tu_string(); // init our string data. m_type = STRING; // force type. } @@ -4502,15 +4419,14 @@ namespace gameswf void as_value::set_as_object_interface(as_object_interface* obj) { - if (m_type != OBJECT || m_object_value != obj) + // SwiffPlayer.dll 0x1008ACA0 releases even when assigning the same pointer. + // [CHOSEN, not recovered] S3 bridge: native objects share one refcount interface. + drop_refs(); + m_type = OBJECT; + m_object_value = obj; + if (m_object_value) { - drop_refs(); - m_type = OBJECT; - m_object_value = obj; - if (m_object_value) - { - m_object_value->add_ref(); - } + m_object_value->add_ref(); } } @@ -4531,7 +4447,7 @@ namespace gameswf bool as_value::operator==(const as_value& v) const // Return true if operands are equal. - // [DICE-MOD SwiffPlayer #50] The shipped as_value::operator== (sub_1008B800), arm by arm on + // SwiffPlayer.dll 0x1008B800, arm by arm on // THIS operand's type: a string compares with the other's string conversion; a number with the // other's to_number; a boolean by both sides' to_bool; an OBJECT by the two string conversions // (a text-less object converts to "" with its own address - see to_tu_string - so @@ -4540,19 +4456,11 @@ namespace gameswf // equal exactly when the types match. Stock 2006 answered `m_type == v.m_type` for objects, so // every clip equalled every other: mainMenu.swf's Radio.toggleCheck skipped all its siblings // as `other != this` was never true, and the difficulty radios could all be lit at once. - // The shipped player has ONE type for null and undefined (its enum has no null; `Push null` and - // the enumerate terminator are both type 0), so null == null and null == undefined hold there - // through the type-match arm. This port keeps two types, so stock 2006's null/undefined arm - // stays in front to give the same answers; the one shipped quirk it does not reproduce is a - // STRING "undefined" comparing equal to an undefined value. + // [CHOSEN, not recovered] S3 bridge: the 2006 NULLTYPE maps to retail's type 0 + // for comparison. Dispatch still depends only on the left operand's type. { - bool this_nulltype = (m_type == UNDEFINED || m_type == NULLTYPE); - bool v_nulltype = (v.get_type() == UNDEFINED || v.get_type() == NULLTYPE); - if (this_nulltype || v_nulltype) - { - return this_nulltype == v_nulltype; - } - else if (m_type == STRING) + if (v.m_type == NULLTYPE) return *this == as_value(); + if (m_type == STRING) { return m_string_value == v.to_tu_string(); } @@ -4576,7 +4484,9 @@ namespace gameswf } else { - return m_type == v.m_type; + const type left = m_type == NULLTYPE ? UNDEFINED : m_type; + const type right = v.m_type == NULLTYPE ? UNDEFINED : v.m_type; + return left == right; } } @@ -4587,32 +4497,130 @@ namespace gameswf return ! (*this == v); } + // SwiffPlayer.dll 0x1008C020: convert the left operand before the right. + bool as_value::operator<(const as_value& v) const + { + const double left = to_number(); + const double right = v.to_number(); + return left < right; + } + + // SwiffPlayer.dll 0x1008C060: ADD converts the right operand first. + void as_value::operator+=(const as_value& v) + { + const double right = v.to_number(); + const double left = to_number(); + set_double(left + right); + } + + // SwiffPlayer.dll 0x1008C0C0: SUB converts the left operand first. + void as_value::operator-=(const as_value& v) + { + const double left = to_number(); + const double right = v.to_number(); + set_double(left - right); + } + + // SwiffPlayer.dll 0x1008C120: MUL converts the right operand first. + void as_value::operator*=(const as_value& v) + { + const double right = v.to_number(); + const double left = to_number(); + set_double(left * right); + } + + // SwiffPlayer.dll 0x1008C180: DIV converts the left operand first, with no zero guard. + void as_value::operator/=(const as_value& v) + { + const double left = to_number(); + const double right = v.to_number(); + set_double(left / right); + } + void as_value::string_concat(const tu_string& str) // Sets *this to this string plus the given string. { + // SwiffPlayer.dll 0x1008B8F0: release, convert, set type, append. + drop_refs(); to_tu_string(); // make sure our m_string_value is initialized m_type = STRING; m_string_value += str; } + // SwiffPlayer.dll 0x1008C1E0: convert the right operand first, using signed FISTP. + void as_value::operator&=(const as_value& v) + { + const int right = bf2x87::toIntTruncate(v.to_number()); + const int left = bf2x87::toIntTruncate(to_number()); + set_int(left & right); + } + + // SwiffPlayer.dll 0x1008C240. + void as_value::operator|=(const as_value& v) + { + const int right = bf2x87::toIntTruncate(v.to_number()); + const int left = bf2x87::toIntTruncate(to_number()); + set_int(left | right); + } + + // SwiffPlayer.dll 0x1008C2A0. + void as_value::operator^=(const as_value& v) + { + const int right = bf2x87::toIntTruncate(v.to_number()); + const int left = bf2x87::toIntTruncate(to_number()); + set_int(left ^ right); + } + + // SwiffPlayer.dll 0x1008C300: x86 masks the shift count to five bits. + void as_value::shl(const as_value& v) + { + const unsigned int count = bf2x87::toIntTruncate(v.to_number()) & 31; + const Uint32 left = static_cast(bf2x87::toIntTruncate(to_number())); + const Uint32 bits = left << count; + int result; + memcpy(&result, &bits, sizeof(result)); + set_int(result); + } + + // SwiffPlayer.dll 0x1008C360: SAR sign-extends the signed dword. + void as_value::asr(const as_value& v) + { + const unsigned int count = bf2x87::toIntTruncate(v.to_number()) & 31; + const int left = bf2x87::toIntTruncate(to_number()); + Uint32 bits = static_cast(left) >> count; + if (left < 0 && count != 0) bits |= ~Uint32(0) << (32 - count); + int result; + memcpy(&result, &bits, sizeof(result)); + set_int(result); + } + + // SwiffPlayer.dll 0x1008C3C0: SHR returns the unsigned dword as a NUMBER. + void as_value::lsr(const as_value& v) + { + const unsigned int count = bf2x87::toIntTruncate(v.to_number()) & 31; + const Uint32 left = static_cast(bf2x87::toIntTruncate(to_number())); + set_double(static_cast(left >> count)); + } + void as_value::drop_refs() // Drop any ref counts we have; this happens prior to changing our value. { + // SwiffPlayer.dll 0x1008A2F0 leaves the type and payload bits untouched. if (m_type == AS_FUNCTION) { if (m_as_function_value) { m_as_function_value->drop_ref(); - m_as_function_value = 0; } } else if (m_type == OBJECT) { + // [CHOSEN, not recovered] S3 bridge: native interfaces own their object + // references directly; retail's separate ownership-discriminator byte is absent. if (m_object_value) { m_object_value->drop_ref(); - m_object_value = 0; } } } @@ -4623,18 +4631,17 @@ namespace gameswf // - as_value as_environment::get_variable(const tu_string& varname, const array& with_stack) const + as_value as_environment::get_variable(const tu_string& varname, const array& with_stack, + as_object_interface** receiver) const // Return the value of the given var, if it's defined. + // SwiffPlayer.dll 0x10091EF0 leaves receiver untouched for a parsed path. { // Path lookup rigamarole. tu_string path; tu_string var; if (parse_path(varname, &path, &var)) { - // [DICE-MOD SwiffPlayer: resolve the path through objects too, not only sprite - // children - see find_object_path. The shipped get_variable (sub_10091EF0) yields the - // NUMBER 0, not undefined, when the path still fails; reproduced.] - as_object_interface* target = find_object_path(path, NULL); // @@ Use with_stack here too??? Need to test. + as_object_interface* target = find_object_path(path, NULL); if (target) { as_value val; @@ -4649,29 +4656,28 @@ namespace gameswf } else { - return this->get_variable_raw(varname, with_stack); + return this->get_variable_raw(varname, with_stack, receiver); } } as_value as_environment::get_variable_raw( const tu_string& varname, - const array& with_stack) const + const array& with_stack, + as_object_interface** receiver) const // varname must be a plain variable name; no path parsing. + // SwiffPlayer.dll 0x100914C0: with, locals, this, target, modules, root, global. { - - assert(strchr(varname.c_str(), ':') == NULL); - assert(strchr(varname.c_str(), '/') == NULL); - assert(strchr(varname.c_str(), '.') == NULL); - as_value val; // Check the with-stack. for (int i = with_stack.size() - 1; i >= 0; i--) { - as_object_interface* obj = with_stack[i].m_object.get_ptr(); + as_object_interface* obj = with_stack[i].m_object; if (obj && obj->get_member(varname, &val)) { + // SwiffPlayer.dll 0x1009153B writes this even for a non-function. + if (receiver) *receiver = obj; // Found the var in this context. return val; } @@ -4688,22 +4694,15 @@ namespace gameswf // Looking for "this"? if (varname == "this") { - // [DICE-MOD: the bound this-object of the running function, else the target movie] + // the bound this-object of the running function, else the target movie val.set_as_object_interface(m_this_object ? m_this_object : static_cast(m_target)); return val; } - // [DICE-MOD SwiffPlayer: `super` is the running function's superclass constructor (the - // shipped env slot +8216); undefined outside a class constructor.] - if (varname == "super") - { - return m_super_ctor ? as_value(m_super_ctor) : as_value(); - } - - // [DICE-MOD SwiffPlayer: the bound this-object's members come before the target movie's - - // the shipped get_variable_raw (sub_100914C0) consults env+8212 first.] - if (m_this_object && m_this_object != static_cast(m_target) - && m_this_object->get_member(varname, &val)) + // the bound this-object's members come before the target movie's - + // the shipped get_variable_raw (sub_100914C0) consults env+8212 first. + // SwiffPlayer.dll 0x10091652 repeats the target lookup even when it is this. + if (m_this_object && m_this_object->get_member(varname, &val)) { return val; } @@ -4717,16 +4716,23 @@ namespace gameswf // Check built-in constants. if (varname == "_root" || varname == "_level0") { - return as_value(m_target->get_root_movie()); + // SwiffPlayer.dll 0x1009182C: return the published root as OBJECT. + return as_value(get_global_root_movie()); } - if (varname == "_global") + if (s_modules.get(varname, &val)) { - return as_value(s_global.get_ptr()); + return val; } - if (s_global->get_member(varname, &val)) + // SwiffPlayer.dll 0x100916EA / 0x10091708: the receiver output uses + // a second root read, since the member lookup can replace the publication. + if (get_global_root_movie()->get_member(varname, &val)) { + if (receiver) *receiver = get_global_root_movie(); return val; } + as_value global; + if (s_modules.get("_global", &global) && global.to_object()->get_member(varname, &val)) + return val; // Fallback. IF_VERBOSE_ACTION(log_msg("get_variable_raw(\"%s\") failed, returning UNDEFINED.\n", varname.c_str())); @@ -4739,6 +4745,7 @@ namespace gameswf const as_value& val, const array& with_stack) // Given a path to variable, set its value. + // SwiffPlayer.dll 0x10092060: a failed path leaves storage untouched. { IF_VERBOSE_ACTION(log_msg("-------------- %s = %s\n", varname.c_str(), val.to_string()));//xxxxxxxxxx @@ -4747,7 +4754,7 @@ namespace gameswf tu_string var; if (parse_path(varname, &path, &var)) { - // [DICE-MOD SwiffPlayer: through objects too - see find_object_path.] + // through objects too - see find_object_path. as_object_interface* target = find_object_path(path, NULL); if (target) { @@ -4766,11 +4773,12 @@ namespace gameswf const as_value& val, const array& with_stack) // No path rigamarole. + // SwiffPlayer.dll 0x1008DA00: with members, then locals, then this/target. { // Check the with-stack. for (int i = with_stack.size() - 1; i >= 0; i--) { - as_object_interface* obj = with_stack[i].m_object.get_ptr(); + as_object_interface* obj = with_stack[i].m_object; as_value dummy; if (obj && obj->get_member(varname, &dummy)) { @@ -4789,39 +4797,22 @@ namespace gameswf return; } + if (varname == "this") + { + if (val.get_type() == as_value::OBJECT) m_this_object = val.to_object(); + return; + } + assert(m_target); m_target->set_member(varname, val); } - // [DICE-MOD SwiffPlayer #41] A `var` at TIMELINE level (a frame script, no function frame active) - // is a property of the clip in Flash - later code reads it through `this`, including functions - // the same script defines. Stock 2006 pushed it onto the environment's local stack, below the - // barrier every function call adds, so a function of the same clip never saw it: - // mainMenu.swf's login page declares `var subPage = Logic.getStorageString("loginSubPage", - // "unselected")` in its frame script, and its selectProfile() (the account list's callback) - // tests `subPage != "unselected"` first - it read undefined and returned, so the page never - // jumped to its "online"/"offline" state (retail run AE). Inside a function frame nothing - // changes. - bool as_environment::in_function_frame() const - { - for (int i = m_local_frames.size() - 1; i >= 0; i--) - { - const frame_slot& slot = m_local_frames[i]; - if (slot.m_name.length() == 0 && slot.m_value.get_type() == as_value::BOOLEAN) return true; // a function barrier - } - return false; - } - void as_environment::set_local(const tu_string& varname, const as_value& val) // Set/initialize the value of the local variable. + // SwiffPlayer.dll 0x1008DB70: timeline locals use the same storage as function locals. { - if (!in_function_frame() && m_target) // [DICE-MOD SwiffPlayer #41] timeline `var` - { - m_target->set_member(varname, val); - return; - } // Is it in the current frame already? int index = find_local(varname); if (index < 0) @@ -4844,6 +4835,7 @@ namespace gameswf // current local frame. Use this when you know the var // doesn't exist yet, since it's faster than set_local(); // e.g. when setting up args for a function. + // SwiffPlayer.dll 0x1008DC20. { assert(varname.length() > 0); m_local_frames.push_back(frame_slot(varname, val)); @@ -4852,16 +4844,8 @@ namespace gameswf void as_environment::declare_local(const tu_string& varname) // Create the specified local var if it doesn't exist already. + // SwiffPlayer.dll 0x1008DCF0. { - if (!in_function_frame() && m_target) // [DICE-MOD SwiffPlayer #41] timeline `var x;` - { - as_value existing; - if (!m_target->get_member(varname, &existing)) - { - m_target->set_member(varname, as_value()); - } - return; - } // Is it in the current frame already? int index = find_local(varname); if (index < 0) @@ -4878,23 +4862,37 @@ namespace gameswf bool as_environment::get_member(const tu_stringi& varname, as_value* val) const + // SwiffPlayer.dll 0x10091890: locals precede the environment's member hash. { + int index = find_local(tu_string(varname.c_str())); + if (index >= 0) + { + *val = m_local_frames[index].m_value; + return true; + } return m_variables.get(varname, val); } void as_environment::set_member(const tu_stringi& varname, const as_value& val) + // SwiffPlayer.dll 0x10092130: update a local before creating a hash member. { + int index = find_local(tu_string(varname.c_str())); + if (index >= 0) + { + m_local_frames[index].m_value = val; + return; + } m_variables.set(varname, val); } as_value* as_environment::register_ptr(int reg) - // [DICE-MOD SwiffPlayer #55] The environment's register `reg`. The shipped as_environment holds + // The environment's register `reg`. The shipped as_environment holds // 256 of them inline (ctor 0x10077D00 constructs 256 undefined values at +0x10) and every // register operand is a byte, so any operand names a live slot; the bank is allocated here on // first use instead, which reads the same (an untouched register is undefined). Numbering is // direct from r0 - the zero-based numbering #43 introduced for the old per-call stack. - // [DICE-MOD SwiffPlayer #57] ...in the bank register_bank() names: the calling chain's while one + // ...in the bank register_bank() names: the calling chain's while one // of this environment's functions runs for another environment - see as_as_function::operator(). { as_environment* bank = register_bank(); @@ -4906,33 +4904,170 @@ namespace gameswf } + void as_environment::release_values(array* held) + // [CHOSEN, not recovered] issue #7: movie teardown, see release_script_objects. Only this + // environment's own storage is emptied; m_target, m_this_object, m_super_ctor and + // m_register_env hold no references. + { + for (int i = 0; i < m_stack.size(); i++) + { + hold_script_value(held, m_stack[i]); + } + m_stack.resize(0); + for (int i = 0; i < m_registers.size(); i++) + { + hold_script_value(held, m_registers[i]); + } + m_registers.resize(0); + for (stringi_hash::iterator it = m_variables.begin(); it != m_variables.end(); ++it) + { + hold_script_value(held, it->second); + } + m_variables.clear(); + for (int i = 0; i < m_local_frames.size(); i++) + { + hold_script_value(held, m_local_frames[i].m_value); + } + m_local_frames.resize(0); + } + + + // [CHOSEN, not recovered] issue #7: the live script objects, by address. Allocated on first + // use and never freed, so objects destroyed during static destruction still find it. + static std::unordered_set* s_script_objects = NULL; + // SwiffPlayer.dll 0x100F9350; source-level name [INFERRED]. The native + // registry remains issue #7's ownership bridge, separate from the retail sweep. + static Uint32 s_common_live_count = 0; + // SwiffPlayer.dll 0x100F935C; [INFERRED] source-level name. The retail + // collector's list is separate from issue #7's native ownership registry. + static as_object_interface* s_gc_list_head = NULL; + + void register_script_object(as_object_interface* obj) + { + if (s_script_objects == NULL) + { + s_script_objects = new std::unordered_set; + } + s_script_objects->insert(obj); + // Inlined common construction in 0x1007EC60 / 0x1009A190 increments + // before the derived character/object initializes its own members. + ++s_common_live_count; + } + + void unregister_script_object(as_object_interface* obj) + { + if (s_script_objects != NULL) + { + s_script_objects->erase(obj); + } + // SwiffPlayer.dll 0x1007DFD2..0x1007E001, inlined in text destruction + // at 0x1008A032..0x1008A061: next, previous, head, then live count. + if (obj->m_gc_next) obj->m_gc_next->m_gc_previous = obj->m_gc_previous; + if (obj->m_gc_previous) obj->m_gc_previous->m_gc_next = obj->m_gc_next; + if (s_gc_list_head == obj) s_gc_list_head = obj->m_gc_next; + --s_common_live_count; + } + + + void release_script_objects() + // [CHOSEN, not recovered] issue #7 (https://github.com/B2BF/OpenBF2/issues/7). A movie's clips + // and objects reference each other from script state - `this` and `_parent` left in a register + // bank, a clip stored in another clip's variable or in a class's static property, a prototype + // and its constructor, a clip removed from its parent while its own scripts still reference + // it - so dropping the movie's last reference freed nothing. `held` keeps every registered + // object alive while the edges are cleared, so the registry does not change under the loop; + // its destruction then drops the last references to objects that no longer reference each + // other. Objects nobody counts (a zero reference count: s_sprite_builtins, stack temporaries) + // are left alone. + { + // [CHOSEN, not recovered] S3 bridge: no borrowed constructor may outlive + // the native script graph whose references are about to be cleared. + s_call_super = NULL; + // [CHOSEN, not recovered] S3 bridge to issue #7's last-player teardown: + // discard globally borrowed timer receivers/environments before the graph. + clear_interval_registry(); + release_library_classes(); + if (s_script_objects == NULL) + { + return; + } + array held; + for (std::unordered_set::iterator it = s_script_objects->begin(); it != s_script_objects->end(); ++it) + { + if ((*it)->get_ref_count() > 0) + { + held.push_back(as_value(*it)); + } + } + for (int i = 0, n = held.size(); i < n; i++) + { + as_object_interface* obj = held[i].to_object(); + if (obj == NULL) + { + continue; + } + if (character* ch = obj->cast_to_character()) + { + ch->release_script_values(&held); + } + else if (as_object* ao = obj->cast_to_as_object()) + { + // [CHOSEN, not recovered] issue #7 / S3 bridge: XML factories + // now publish native strong graph edges; clear them while held owns + // every registered object, before ordinary members and accessors. + release_xml_script_references(ao); + // [CHOSEN, not recovered] issue #7: dense Array values also own script + // references. Clear them while the registry snapshot holds every object. + if (as_array_object* array = dynamic_cast(ao)) + { + array->m_elements.clear(); + } + ao->clear(); + ao->m_accessors.clear(); + } + } + } + + + as_environment::~as_environment() + { + // SwiffPlayer.dll 0x100778B0: locals, members, registers 255..0, operands. + m_local_frames.clear(); + m_variables.clear(); + // [CHOSEN, not recovered] S3 bridge: free the native bank allocation + // after reverse value destruction; retail's bank is embedded storage. + m_registers.clear_reverse(); + m_stack.clear(); + } + int as_environment::find_local(const tu_string& varname) const // Search the active frame for the named var; return its index // in the m_local_frames stack if found. // // Otherwise return -1. { - // Linear search sucks, but is probably fine for - // typical use of local vars in script. There could - // be pathological breakdowns if a function has tons - // of locals though. The ActionScript bytecode does - // not help us much by using strings to index locals. - + // SwiffPlayer.dll 0x1008D120 registers even with profiling disabled, + // and always reads the ending clock and updates the counter. + static profile_record counter("find_local"); + if (s_profiling) counter.begin(); + int result = -1; for (int i = m_local_frames.size() - 1; i >= 0; i--) { const frame_slot& slot = m_local_frames[i]; if (slot.m_name.length() == 0) { // End of local frame; stop looking. - return -1; + break; } else if (slot.m_name == varname) { // Found it. - return i; + result = i; + break; } } - return -1; + counter.end(); + return result; } @@ -4953,6 +5088,7 @@ namespace gameswf // // If no colon, returns false and leaves *path & *var alone. { + // SwiffPlayer.dll 0x1008B940: first colon, otherwise last dot; trim one slash. // Search for colon. int colon_index = 0; int var_path_length = var_path.length(); @@ -5002,25 +5138,17 @@ namespace gameswf } - movie* as_environment::find_target(const as_value& val) const - // Find the sprite/movie represented by the given value. The - // value might be a reference to the object itself, or a - // string giving a relative path name to the object. + as_object_interface* as_environment::find_target(const as_value& val) const + // Resolve an object value or string path to its common ActionScript interface. { + // SwiffPlayer.dll 0x100921D0 returns OBJECT directly, without a movie cast. if (val.get_type() == as_value::OBJECT) { - if (val.to_object() != NULL) - { - return val.to_object()->to_movie(); - } - else - { - return NULL; - } + return val.m_object_value; } else if (val.get_type() == as_value::STRING) { - return find_target(val.to_tu_string()); + return find_object_path(val.to_tu_string(), NULL); } else { @@ -5034,6 +5162,7 @@ namespace gameswf // Search for next '.' or '/' character in this word. Return // a pointer to it, or to NULL if it wasn't found. { + // SwiffPlayer.dll 0x1008A320 skips paired dots before testing a delimiter. for (const char* p = word; *p; p++) { if (*p == '.' && p[1] == '.') @@ -5053,82 +5182,18 @@ namespace gameswf movie* as_environment::find_target(const tu_string& path) const // Find the sprite/movie referenced by the given path. { - if (path.length() <= 0) - { - return m_target; - } - - assert(path.length() > 0); - - movie* env = m_target; - assert(env); - - const char* p = path.c_str(); - tu_string subpart; - - if (*p == '/') - { - // Absolute path. Start at the root. - env = env->get_relative_target("_level0"); - p++; - } - - for (;;) - { - const char* next_slash = next_slash_or_dot(p); - subpart = p; - if (next_slash == p) - { - log_error("error: invalid path '%s'\n", path.c_str()); - break; - } - else if (next_slash) - { - // Cut off the slash and everything after it. - subpart.resize(next_slash - p); - } - - env = env->get_relative_target(subpart); - //@@ _level0 --> root, .. --> parent, . --> this, other == character - - if (env == NULL || next_slash == NULL) - { - break; - } - - p = next_slash + 1; - } - return env; + // [CHOSEN, not recovered] S3 bridge: retain the 2006 movie-returning API + // while every string path uses the common retail walk at 0x10091960. + as_object_interface* target = find_object_path(path, NULL); + return target ? target->to_movie() : NULL; } - // [DICE-MOD SwiffPlayer: dotted-path resolution through OBJECT members. - // - // Stock 2006 resolves the path part of "a.b.c" (get_variable/set_variable's "path lookup - // rigamarole") only through movie::get_relative_target, i.e. sprite CHILDREN; a plain object's - // member is invisible to it. BF2's menu is an AS2 class framework whose fully qualified class - // names ("dice.UIs.Commons.Button", "dice.UpdateManager", ...) the compiler emits as dotted - // GetVariable/SetVariable strings, so on stock gameswf every one of them fails with - // find_target("dice.UIs.Commons") failed, the framework never builds, and the root movie stays - // stopped on frame 0 (retail 2026-09-02, ~20 such failures before the first frame). - // - // The shipped DICE gameswf resolves them (SwiffPlayer.dll (2).i64): - // * as_environment::find_target (sub_10091960) walks each path element through the VIRTUAL - // get_relative_target of whatever the current element is (as_object_interface vslot +28); - // * as_object::get_relative_target (sub_1000B3B0): "." / "this" -> self; ".." / "_level0" / - // "_root" -> null; anything else -> get_member(name).to_object(); - // * when the walk dies it RE-RESOLVES the whole path from the _global object (unless it - // started there) - which is how "dice.*" resolves from a sprite's own script; - // * get_variable (sub_10091EF0) yields the NUMBER 0, not undefined, when that still fails. - // This is that behaviour on the stock 2006 types: a sprite resolves its children first (its own - // get_relative_target), then its members; a plain object resolves members. See - // GAMESWF_DIVERGENCES.md.] + // SwiffPlayer.dll 0x1000B3B0 resolves plain-object relative targets. + // [CHOSEN, not recovered] S3 bridge: adapt retail's common virtual to the + // native movie/get_member interfaces; sprite dispatch remains a separate recovery. static as_object_interface* resolve_path_element(as_object_interface* env, const tu_string& name) { - if (env == NULL) - { - return NULL; - } movie* mv = env->to_movie(); if (mv) { @@ -5159,24 +5224,19 @@ namespace gameswf as_object_interface* as_environment::find_object_path(const tu_string& path, as_object_interface* start) const { + // SwiffPlayer.dll 0x10091960: empty paths return the target, even with start. as_object_interface* env = start ? start : m_target; if (path.length() <= 0) { return m_target; } - if (env == NULL) - { - return NULL; - } - const char* p = path.c_str(); tu_string subpart; if (*p == '/') { // Absolute path. Start at the root. - movie* mv = env->to_movie(); - env = mv ? mv->get_relative_target("_level0") : NULL; + env = resolve_path_element(env, tu_string("_level0")); p++; } @@ -5209,8 +5269,10 @@ namespace gameswf { // The shipped fallback: resolve the whole path again from _global, unless that is // where this walk started. - as_object_interface* global = s_global.get_ptr(); - if (global && start != global) + as_value global_value; + as_object_interface* global = s_modules.get("_global", &global_value) + ? global_value.to_object() : NULL; + if (global && (start ? start : m_target) != global) { return find_object_path(path, global); } @@ -5223,53 +5285,23 @@ namespace gameswf // event_id // - // [DICE-MOD SwiffPlayer #51] the shipped table (sub_1008BA90) spells onReleaseOutside, onRollOver, + // the shipped table (sub_1008BA90) spells onReleaseOutside, onRollOver, // onRollOut, onDragOver and onDragOut without stock 2006's underscores - a sprite's on_event looks // its member handler up by this name, so the stock spellings never found one - and ends in // onDoublePress. const tu_string& event_id::get_function_name() const { - static tu_string s_function_names[EVENT_COUNT] = - { - "INVALID", // INVALID - "onPress", // PRESS - "onRelease", // RELEASE - "onReleaseOutside", // RELEASE_OUTSIDE - "onRollOver", // ROLL_OVER - "onRollOut", // ROLL_OUT - "onDragOver", // DRAG_OVER - "onDragOut", // DRAG_OUT - "onKeyPress", // KEY_PRESS - "onInitialize", // INITIALIZE - - "onLoad", // LOAD - "onUnload", // UNLOAD - "onEnterFrame", // ENTER_FRAME - "onMouseDown", // MOUSE_DOWN - "onMouseUp", // MOUSE_UP - "onMouseMove", // MOUSE_MOVE - "onKeyDown", // KEY_DOWN - "onKeyUp", // KEY_UP - "onData", // DATA - // These are for the MoveClipLoader ActionScript only - "onLoadStart", // LOAD_START - "onLoadError", // LOAD_ERROR - "onLoadProgress", // LOAD_PROGRESS - "onLoadInit", // LOAD_INIT - // These are for the XMLSocket ActionScript only - "onSockClose", // CLOSE - "onSockConnect", // CONNECT - "onSockXML", // XML - // These are for the XML ActionScript only - "onXMLLoad", // XML_LOAD - "onXMLData", // XML_DATA - "onTimer", // setInterval Timer expired - "onConstruct", // CONSTRUCT [DICE-MOD SwiffPlayer #27] - "onDoublePress", // DOUBLE_PRESS [DICE-MOD SwiffPlayer #51] + // SwiffPlayer.dll 0x1008BA90: construct all 22 names in table order. + static const tu_string retail_names[] = + { + "INVALID", "onPress", "onRelease", "onReleaseOutside", "onRollOver", + "onRollOut", "onDragOver", "onDragOut", "onKeyPress", "onInitialize", + "onLoad", "onUnload", "onEnterFrame", "onMouseDown", "onMouseUp", + "onMouseMove", "onKeyDown", "onKeyUp", "onData", "reserved", + "onConstruct", "onDoublePress" }; - assert(m_id > INVALID && m_id < EVENT_COUNT); - return s_function_names[m_id]; + return retail_names[m_id]; } @@ -5307,7 +5339,6 @@ namespace gameswf s_standard_member_map.add("_ymouse", M_YMOUSE); s_standard_member_map.add("_parent", M_PARENT); s_standard_member_map.add("text", M_TEXT); - s_standard_member_map.add("textWidth", M_TEXTWIDTH); s_standard_member_map.add("textColor", M_TEXTCOLOR); s_standard_member_map.add("onLoad", M_ONLOAD); } @@ -5339,6 +5370,7 @@ namespace gameswf void log_disasm(const unsigned char* instruction_data) // Disassemble one instruction to the log. { + // SwiffPlayer.dll 0x1008A350 and instruction metadata at 0x100EC9E8. enum arg_format { ARG_NONE = 0, ARG_STR, @@ -5347,8 +5379,7 @@ namespace gameswf ARG_U16, ARG_S16, ARG_PUSH_DATA, - ARG_DECL_DICT, - ARG_FUNCTION2 + ARG_DECL_DICT }; struct inst_info { @@ -5391,7 +5422,6 @@ namespace gameswf { 0x27, "start_drag", ARG_NONE }, { 0x28, "stop_drag", ARG_NONE }, { 0x29, "str_lt", ARG_NONE }, - { 0x2B, "cast_object", ARG_NONE }, { 0x30, "random", ARG_NONE }, { 0x31, "mb_length", ARG_NONE }, { 0x32, "ord", ARG_NONE }, @@ -5437,6 +5467,7 @@ namespace gameswf { 0x66, "eq_strict", ARG_NONE }, { 0x67, "gt_t", ARG_NONE }, { 0x68, "gt_str", ARG_NONE }, + { 0x69, "extends", ARG_NONE }, { 0x81, "goto_frame", ARG_U16 }, { 0x83, "get_url", ARG_STR }, @@ -5446,7 +5477,7 @@ namespace gameswf { 0x8B, "set_target", ARG_STR }, { 0x8C, "goto_frame_lbl", ARG_STR }, { 0x8D, "wait_for_fr_exp", ARG_HEX }, - { 0x8E, "function2", ARG_FUNCTION2 }, + { 0x8E, "func2", ARG_HEX }, { 0x94, "with", ARG_U16 }, { 0x96, "push_data", ARG_PUSH_DATA }, { 0x99, "goto", ARG_S16 }, @@ -5663,68 +5694,7 @@ namespace gameswf i++; } } - else if (fmt == ARG_FUNCTION2) - { - // Signature info for a function2 opcode. - int i = 0; - const char* function_name = (const char*) &instruction_data[3 + i]; - i += strlen(function_name) + 1; - - int arg_count = instruction_data[3 + i] | (instruction_data[3 + i + 1] << 8); - i += 2; - - int reg_count = instruction_data[3 + i]; - i++; - - log_msg("\n\t\tname = '%s', arg_count = %d, reg_count = %d\n", - function_name, arg_count, reg_count); - - uint16 flags = (instruction_data[3 + i]) | (instruction_data[3 + i + 1] << 8); - i += 2; - // @@ What is the difference between "super" and "_parent"? - - bool preload_global = (flags & 0x100) != 0; - bool preload_parent = (flags & 0x80) != 0; - bool preload_root = (flags & 0x40) != 0; - bool suppress_super = (flags & 0x20) != 0; - bool preload_super = (flags & 0x10) != 0; - bool suppress_args = (flags & 0x08) != 0; - bool preload_args = (flags & 0x04) != 0; - bool suppress_this = (flags & 0x02) != 0; - bool preload_this = (flags & 0x01) != 0; - - log_msg("\t\t pg = %d\n" - "\t\t pp = %d\n" - "\t\t pr = %d\n" - "\t\tss = %d, ps = %d\n" - "\t\tsa = %d, pa = %d\n" - "\t\tst = %d, pt = %d\n", - int(preload_global), - int(preload_parent), - int(preload_root), - int(suppress_super), - int(preload_super), - int(suppress_args), - int(preload_args), - int(suppress_this), - int(preload_this)); - - for (int argi = 0; argi < arg_count; argi++) - { - int arg_register = instruction_data[3 + i]; - i++; - const char* arg_name = (const char*) &instruction_data[3 + i]; - i += strlen(arg_name) + 1; - - log_msg("\t\targ[%d] - reg[%d] - '%s'\n", argi, arg_register, arg_name); - } - - int function_length = instruction_data[3 + i] | (instruction_data[3 + i + 1] << 8); - i += 2; - - log_msg("\t\tfunction length = %d\n", function_length); - } } else { diff --git a/Code/BF2/External/gameswf/gameswf_action.h b/Code/BF2/External/gameswf/gameswf_action.h index b0c101dbd..4578d96b9 100644 --- a/Code/BF2/External/gameswf/gameswf_action.h +++ b/Code/BF2/External/gameswf/gameswf_action.h @@ -10,10 +10,10 @@ #define GAMESWF_ACTION_H -#include "gameswf.h" -#include "gameswf_types.h" #include +#include "gameswf.h" +#include "gameswf_types.h" #include "base/container.h" #include "base/smart_ptr.h" @@ -27,17 +27,60 @@ namespace gameswf struct as_as_function; void log_error(const char* fmt, ...); // [TEMP] RW-89 trace support (gameswf_log.h) struct as_object; - // [DICE-MOD SwiffPlayer #31] a fresh Array and its push, for String.split (the array type lives in + // a fresh Array and its push, for String.split (the array type lives in // gameswf_action.cpp; the String unit only needs these two). as_object* create_array_object(); - // [DICE-MOD SwiffPlayer #38] DICE's String object from wide text (gameswf_string.cpp). + // DICE's String object from wide text (gameswf_string.cpp). as_object_interface* create_dice_string_object(const Uint16* wide, int count); - // [DICE-MOD SwiffPlayer #38] Assign the wide payload of an existing factory object. + // Assign the wide payload of an existing factory object. void assign_dice_string_object_wide(as_object_interface* object, const Uint16* wide); - // [DICE-MOD SwiffPlayer #38] the narrow twin: Mod.getCurrentModName (sub_1004F950) assigns the + // the narrow twin: Mod.getCurrentModName (sub_1004F950) assigns the // +44 tu_string from a plain host string and CLEARS the +60 wide side, the mirror of the above. void assign_dice_string_object_narrow(as_object_interface* object, const char* text); + +#if !defined(_WIN32) + // [CHOSEN, not recovered] gameswf and DICE's String object keep text as 16-bit Windows + // wchar_t units (Uint16). The host's std::wstring/wchar_t is 32 bits on POSIX, so the + // shipped `reinterpret_cast(wide)` handed over 'W',0,'e',0,... and every + // localized menu string ended after its first character. dice_utf16 converts one wchar_t + // to one Uint16 (count-preserving; above U+FFFF becomes U+FFFD). The temporary lives to + // the end of the full expression that names it. + struct dice_utf16 + { + explicit dice_utf16(const wchar_t* wide) + { + if (!wide) { m_null = true; return; } + for (; *wide; ++wide) m_units.push_back(unit(*wide)); + m_units.push_back(0); + } + operator const Uint16*() const { return m_null ? 0 : &m_units[0]; } + private: + static Uint16 unit(wchar_t c) { return (unsigned int) c > 0xFFFFu ? (Uint16) 0xFFFD : (Uint16) c; } + array m_units; + bool m_null = false; + }; + // The opposite boundary: Uint16 text to the renderer's native wchar_t (text_set). + struct dice_wide + { + explicit dice_wide(const Uint16* units) + { + if (units) for (; *units; ++units) m_chars.push_back((wchar_t) *units); + m_chars.push_back(0); + } + operator const wchar_t*() const { return &m_chars[0]; } + private: + array m_chars; + }; +#define BF2_DICE_UTF16(wide) ((const Uint16*) ::gameswf::dice_utf16(wide)) +#define BF2_DICE_WIDE(units) ((const wchar_t*) ::gameswf::dice_wide(units)) +#else +#define BF2_DICE_UTF16(wide) (reinterpret_cast(wide)) +#define BF2_DICE_WIDE(units) ((const wchar_t*) (units)) +#endif void array_object_push(as_object* arr, const as_value& v); + // [CHOSEN, not recovered] S3 bridge for retail's direct Array storage reads. + // The caller must supply an Array object; no member lookup or conversion runs. + const array& array_object_values(as_object_interface* arr); // @@ -74,33 +117,15 @@ namespace gameswf KEY_UP, DATA, - // These are for the MoveClipLoader ActionScript only - LOAD_START, - LOAD_ERROR, - LOAD_PROGRESS, - LOAD_INIT, - - // These are for the XMLSocket ActionScript only - SOCK_CLOSE, - SOCK_CONNECT, - SOCK_DATA, - SOCK_XML, - - // These are for the XML ActionScript only - XML_LOAD, - XML_DATA, - - // This is for setInterval - TIMER, - - // [DICE-MOD SwiffPlayer #27: the SWF 7 `construct` clip event (PlaceObject2 flag bit 18, + // the SWF 7 `construct` clip event (PlaceObject2 flag bit 18, // 0x40000). Flash fires it right after instantiation and BEFORE a registered class's // constructor; it is how the authoring tool bakes component-inspector parameters into the // movie (`__authorMode = false`, `callbackFrequency = 0`, ...). mainMenu.swf carries 1,178 // of them. Stock 2006 gameswf had no such event, so every DICE component kept its - // authoring-mode default and drew its IDE placeholder rectangle - the grey-box menu.] + // authoring-mode default and drew its IDE placeholder rectangle - the grey-box menu. + RESERVED, // Retail event-name table entry 19. CONSTRUCT, - // [DICE-MOD SwiffPlayer #51] the shipped table's 22nd event, "onDoublePress": a press the + // the shipped table's 22nd event, "onDoublePress": a press the // host reports with the mouse buttons as 2 (the sprite mouse pass, sub_10080010). DOUBLE_PRESS, EVENT_COUNT @@ -111,6 +136,7 @@ namespace gameswf event_id() : m_id(INVALID), m_key_code(key::INVALID) {} + // SwiffPlayer.dll 0x1006ED10. event_id(id_code id, key::code c = key::INVALID) : m_id((unsigned char) id), @@ -122,6 +148,7 @@ namespace gameswf || (m_key_code != key::INVALID && (m_id == KEY_PRESS))); } + // SwiffPlayer.dll 0x1006ED30 compares the event byte before the key byte. bool operator==(const event_id& id) const { return m_id == id.m_id && m_key_code == id.m_key_code; } // Return the name of a method-handler function corresponding to this event. @@ -135,7 +162,11 @@ namespace gameswf struct with_stack_entry { - smart_ptr m_object; + // SwiffPlayer.dll 0x10094E8E/0x1008BD83: scope records borrow the + // receiver. Append, expiry and 0x10082180 cleanup never retain/release it. + // Cleanup veneer 0x1008BD60 shares that body. Native array destruction + // frees storage after zeroing its count/capacity; record destruction is trivial. + as_object_interface* m_object; int m_block_end_pc; with_stack_entry() @@ -158,6 +189,9 @@ namespace gameswf struct action_buffer { action_buffer(); + // SwiffPlayer.dll 0x100766E0: dictionary, then byte storage; + // 0x100A2650 is the compiler's deleting wrapper. + ~action_buffer() = default; void read(stream* in); void execute(as_environment* env); void execute( @@ -193,6 +227,9 @@ namespace gameswf struct fn_call; + // Execute a definition initialization tag without draining the movie's timeline queue. + // The tag must have been produced by do_init_action_loader. + void execute_init_action(execute_tag* tag, as_environment* env); typedef void (*as_c_function_ptr)(const fn_call& fn); @@ -275,7 +312,11 @@ namespace gameswf // way to do it. Everything else just // continues to work. -#if (WCHAR_MAX != MAXINT) +#if !defined(_WIN32) && (WCHAR_MAX > 0xFFFF) + // [CHOSEN, not recovered] MAXINT is undefined here, so the stock test below picked + // the 16-bit decoder for the 32-bit POSIX wchar_t. Decode native characters. + tu_string::encode_utf8_from_wchar(&m_string_value, (const uint32 *)wstr); +#elif (WCHAR_MAX != MAXINT) tu_string::encode_utf8_from_wchar(&m_string_value, (const uint16 *)wstr); #else # if (WCHAR_MAX != MAXSHORT) @@ -346,6 +387,8 @@ namespace gameswf double to_number() const; bool to_bool() const; as_object_interface* to_object() const; + // Extract an OBJECT payload without the native function-property adapter. + as_object_interface* to_object_raw() const; as_c_function_ptr to_c_function() const; as_as_function* to_as_function() const; @@ -357,10 +400,12 @@ namespace gameswf // in preference to generic overloaded set(). You are // more likely to get a warning/error if misused. void set_tu_string(const tu_string& str) { drop_refs(); m_type = STRING; m_string_value = str; } + // SwiffPlayer.dll 0x1008B130: release before replacing the string payload. void set_string(const char* str) { drop_refs(); m_type = STRING; m_string_value = str; } void set_double(double val) { drop_refs(); m_type = NUMBER; m_number_value = val; } void set_bool(bool val) { drop_refs(); m_type = BOOLEAN; m_boolean_value = val; } - void set_int(int val) { set_double(val); } + // SwiffPlayer.dll 0x1006ECB0 repeats the release in set_double; preserve both calls. + void set_int(int val) { drop_refs(); set_double(val); } void set_as_object_interface(as_object_interface* obj); void set_as_c_function_ptr(as_c_function_ptr func) { @@ -384,17 +429,17 @@ namespace gameswf bool operator==(const as_value& v) const; bool operator!=(const as_value& v) const; - bool operator<(const as_value& v) const { return to_number() < v.to_number(); } - void operator+=(const as_value& v) { set_double(this->to_number() + v.to_number()); } - void operator-=(const as_value& v) { set_double(this->to_number() - v.to_number()); } - void operator*=(const as_value& v) { set_double(this->to_number() * v.to_number()); } - void operator/=(const as_value& v) { set_double(this->to_number() / v.to_number()); } // @@ check for div/0 - void operator&=(const as_value& v) { set_int(int(this->to_number()) & int(v.to_number())); } - void operator|=(const as_value& v) { set_int(int(this->to_number()) | int(v.to_number())); } - void operator^=(const as_value& v) { set_int(int(this->to_number()) ^ int(v.to_number())); } - void shl(const as_value& v) { set_int(int(this->to_number()) << int(v.to_number())); } - void asr(const as_value& v) { set_int(int(this->to_number()) >> int(v.to_number())); } - void lsr(const as_value& v) { set_int((Uint32(this->to_number()) >> int(v.to_number()))); } + bool operator<(const as_value& v) const; + void operator+=(const as_value& v); + void operator-=(const as_value& v); + void operator*=(const as_value& v); + void operator/=(const as_value& v); + void operator&=(const as_value& v); + void operator|=(const as_value& v); + void operator^=(const as_value& v); + void shl(const as_value& v); + void asr(const as_value& v); + void lsr(const as_value& v); void string_concat(const tu_string& str); @@ -536,26 +581,33 @@ namespace gameswf // // A generic bag of attributes. Base-class for ActionScript // script-defined objects. - // [DICE-MOD SwiffPlayer: the AS2 `Object.addProperty(name, getter, setter)` builtin. Stock 2006 + // the AS2 `Object.addProperty(name, getter, setter)` builtin. Stock 2006 // gameswf has no getter/setter properties at all, and menu.swf calls addProperty 36 times in its // onLoad (measured with BF2_SWIFFPLAYER_ASLOG=1). DICE hit the same gap: their 56-byte AS object // class registers exactly one method, "addProperty" (sub_1009A320 -> gameswf_as_object_addproperty). - // Defined in gameswf_action.cpp. See GAMESWF_DIVERGENCES.md.] + // Defined in gameswf_action.cpp. See GAMESWF_DIVERGENCES.md. void as_object_addproperty(const fn_call& fn); struct as_object : public as_object_interface { stringi_hash m_members; + // Instance construction and explicit inheritance use different links. + as_object_interface* m_instance_prototype; as_object_interface* m_prototype; + smart_ptr m_constructor; - // [DICE-MOD SwiffPlayer: addProperty storage - the getter/setter function per property name. - // A name present in m_getters/m_setters shadows any plain member of the same name.] - stringi_hash m_getters; - stringi_hash m_setters; + // SwiffPlayer.dll 0x1009A0F0 stores a pair of borrowed script functions; + // 0x100749D0 destroys keys without releasing either function. + struct property_accessors + { + as_as_function* getter; + as_as_function* setter; + }; + stringi_hash m_accessors; virtual as_object* cast_to_as_object() { return this; } - // [DICE-MOD SwiffPlayer #49] The shipped as_object vtable slot +0x28 (sub_10099CB0): push the + // The shipped as_object vtable slot +0x28 (sub_10099CB0): push the // names a `for (k in obj)` loop visits - the prototype chain first (virtual, so it recurses // base-most first), then this object's own members whose VALUE is a string, number, boolean // or object (shipped types 1..4); undefined and both function types are skipped, and the @@ -564,118 +616,36 @@ namespace gameswf // call this after pushing the null terminator; stock 2006 walked m_members inline, methods // included, so a for-in over an Array met its own push/pop/... C functions. virtual void enumerate(as_environment* env); + virtual void gc_mark(); + virtual void gc_release(); + void gc_mark_members(); - // Declared here, defined in gameswf_action.cpp (they need call_method to invoke the - // getter/setter, and a scratch as_environment to pass its arguments through). + // Accessors keep the original receiver while searching explicit inheritance links. void add_property(const tu_stringi& name, const as_value& getter, const as_value& setter); - bool get_property(const tu_stringi& name, as_value* val); // true if a getter handled it - bool set_property(const tu_stringi& name, const as_value& val); // true if a setter handled it - // [DICE-MOD SwiffPlayer #28: a getter/setter registered on a CLASS PROTOTYPE applies to every + bool get_property(const tu_stringi& name, as_value* val, as_object_interface* receiver = NULL); + bool set_property(const tu_stringi& name, const as_value& val, as_object_interface* receiver = NULL); + // a getter/setter registered on a CLASS PROTOTYPE applies to every // instance, called with the instance as `this`. mainMenu.swf registers 177 of them on the // component prototypes (`UIObject.prototype.addProperty("__authorMode", __get__..., __set__...)`) // and the construct handlers then assign `__authorMode = false` on the instance. The lookup - // walks the prototype chain; the call keeps the original receiver.] + // walks the prototype chain; the call keeps the original receiver. bool find_getter(const tu_stringi& name, as_value* getter, int depth = 0); bool find_setter(const tu_stringi& name, as_value* setter, int depth = 0); - void note_function_home(const as_value& fn); // [DICE-MOD #30] out of line: as_as_function is incomplete here - static as_value invoke_getter(const as_value& getter, as_object_interface* self); + static as_value invoke_getter(const as_value& getter, as_object_interface* self, + const as_value& argument = as_value()); static void invoke_setter(const as_value& setter, as_object_interface* self, const as_value& val); - as_object() : m_prototype(NULL) { } - as_object(as_object_interface* proto) : m_prototype(proto) - { - if (m_prototype) - { - m_prototype->add_ref(); - } - } - - virtual ~as_object() - { - if (m_prototype) - { - m_prototype->drop_ref(); - } - } + as_object(); + as_object(as_object_interface* proto); + // Compiler deleting wrapper: SwiffPlayer.dll 0x1007CD80. Native base + // and member ownership remain separate from this forwarding/deletion sequence. + virtual ~as_object(); virtual const char* get_text_value() const { return NULL; } - virtual void set_member(const tu_stringi& name, const as_value& val ) { - //printf("SET MEMBER: %s at %p for object %p\n", name.c_str(), val.to_object(), this); - // [DICE-MOD SwiffPlayer #30: remember where a function was first stored (see m_home_object).] - if (val.get_type() == as_value::AS_FUNCTION && name != "prototype" && name != "__constructor__") - { - note_function_home(val); - } - if (name == "prototype") - { - if (m_prototype) m_prototype->drop_ref(); - m_prototype = val.to_object(); - if (m_prototype) m_prototype->add_ref(); - } - else if (set_property(name, val)) // [DICE-MOD] an addProperty setter takes precedence - { - } - else - { - stringi_hash::const_iterator it = this->m_members.find(name); - - if ( it != this->m_members.end() ) { - - const as_prop_flags flags = (it.get_value()).get_member_flags(); - - // is the member read-only ? - if (!flags.get_read_only()) { - m_members.set(name, as_member(val, flags)); - } - - } else { - m_members.set(name, as_member(val)); - } - } - } - - virtual bool get_member(const tu_stringi& name, as_value* val) - { - //printf("GET MEMBER: %s at %p for object %p\n", name.c_str(), val, this); - if (name == "prototype") - { - val->set_as_object_interface(m_prototype); - return true; - } - else if (get_property(name, val)) // [DICE-MOD] an addProperty getter takes precedence - { - return true; - } - else { - as_member m; - - if (m_members.get(name, &m) == false) - { - if (m_prototype != NULL) - { - if (m_prototype->get_member(name, val)) - { - return true; - } - } - // [DICE-MOD SwiffPlayer: expose the AS2 `addProperty` builtin on every object, - // as the real player does via Object.prototype. Checked LAST, so a real member - // or a prototype member of the same name still wins.] - if (name == "addProperty") - { - val->set_as_c_function_ptr(as_object_addproperty); - return true; - } - return false; - } else { - *val=m.get_member_value(); - return true; - } - } - return true; - } + virtual void set_member(const tu_stringi& name, const as_value& val); + virtual bool get_member(const tu_stringi& name, as_value* val); virtual bool get_member(const tu_stringi& name, as_member* member) const { @@ -706,15 +676,7 @@ namespace gameswf return NULL; } - void clear() - { - m_members.clear(); - if (m_prototype) - { - m_prototype->drop_ref(); - m_prototype = NULL; - } - } + void clear(); }; @@ -738,44 +700,38 @@ namespace gameswf array m_args; bool m_is_function2; uint8 m_local_register_count; // parsed; sizes nothing since #55 (the shipped call saves a fixed r0..r9) - uint16 m_function2_flags; // used by function2 to control implicit arg register assignments + uint16 m_function2_flags; // retained for the native declaration interface + // SwiffPlayer.dll 0x10091C20 / 0x100958FB: register number to preload name. + hash m_preload_registers; - // ActionScript functions have a property namespace! - // Typically used for class constructors, for "prototype", "constructor", - // and class properties. + // [CHOSEN, not recovered] S3 bridge: native object-interface adapter for the + // function's static properties and its eagerly created prototype object. as_object* m_properties; - // [DICE-MOD SwiffPlayer #30: the object this function was first stored on as a member - for a - // class method, the class PROTOTYPE. `super` inside a method is the parent of the class the - // method was DEFINED on (that prototype's __constructor__, left there by ActionExtends), not - // anything derived from `this`, or a two-level chain would loop. Stock 2006 gameswf set the - // function2 super register to nothing ("TODO: implement 'super'"), so every subclass - // init/draw/arrange's super.xxx() call died on an undefined object once the real subclass - // methods ran. Raw pointer, unowned: prototypes outlive the movie's functions.] - as_object* m_home_object; // NULL environment is allowed -- if so, then // functions will be executed in the caller's // environment, rather than the environment where they // were defined. - as_as_function(action_buffer* ab, as_environment* env, int start, const array& with_stack) - : - m_action_buffer(ab), - m_env(env), - m_with_stack(with_stack), - m_start_pc(start), - m_length(0), - m_is_function2(false), - m_local_register_count(0), - m_function2_flags(0), - m_properties(NULL), - m_home_object(NULL) + as_as_function(action_buffer* ab, as_environment* env, int start, const array& with_stack); + + // SwiffPlayer.dll 0x10091BB0 / 0x10091BE0 destroys static members before + // arguments; 0x10091C60 destroys the separate function2 storage first. + // [CHOSEN, not recovered] S3 bridge: this combined native type owns the + // property adapter and preload map. Release its property reference for + // issue #7 (https://github.com/B2BF/OpenBF2/issues/7). + ~as_as_function() { - assert(m_action_buffer); + if (m_properties) + { + m_properties->drop_ref(); + } } + // SwiffPlayer.dll 0x10091C20 starts with empty preload/argument storage. + // [CHOSEN, not recovered] S3 bridge: the native type combines both function classes. void set_is_function2() { m_is_function2 = true; } void set_local_register_count(uint8 ct) { assert(m_is_function2); m_local_register_count = ct; } - void set_function2_flags(uint16 flags) { assert(m_is_function2); m_function2_flags = flags; } + void set_function2_flags(uint16 flags); void add_arg(int arg_register, const char* name) { @@ -785,28 +741,22 @@ namespace gameswf m_args.back().m_name = name; } + void add_arg(const char* name) + { + // SwiffPlayer.dll 0x1008D610 copies the name before growing the array. + // [CHOSEN, not recovered] S3 bridge: the native argument record also + // carries the register used by the separate function2 class. + const arg_spec argument = { 0, tu_string(name) }; + m_args.push_back(argument); + } + void set_length(int len) { assert(len >= 0); m_length = len; } // Dispatch. void operator()(const fn_call& fn); - void lazy_create_properties() - // This ensures that this as_function has a valid - // prototype in its properties. This is done lazily - // so that functions/methods which are not used as - // constructors don't carry along extra unnecessary - // baggage. - { - if (m_properties == NULL) - { - m_properties = new as_object(); - m_properties->add_ref(); - - // Create new empty prototype - as_value proto(new as_object()); - m_properties->set_member("prototype", proto); - } - } + void lazy_create_properties(); + void gc_mark(); }; @@ -814,14 +764,15 @@ namespace gameswf struct as_environment { array m_stack; - // [DICE-MOD SwiffPlayer #55] ONE register bank per environment, 256 slots, shared by timeline + // ONE register bank per environment, 256 slots, shared by timeline // code and every function body that executes in this environment - the shipped // as_environment carries `as_value registers[256]` at +0x10 (ctor 0x10077D00), and // StoreRegister / the push-register operand address env+0x10+32*reg for all code (execute // 0x100925A0, case 0x87 and push type 4). Stock 2006 kept four timeline registers plus a // FRESH stack of local registers per DefineFunction2 call, so an argument the caller did not // pass read undefined; in the shipped player it reads whatever the environment's register - // already held (see as_as_function::operator()). Sized to 256 on first use. + // already held (see as_as_function::operator()). Constructed with 256 entries. + // [CHOSEN, not recovered] S3 bridge: native array storage for the fixed bank. array m_registers; movie* m_target; stringi_hash m_variables; @@ -833,25 +784,30 @@ namespace gameswf as_value m_value; frame_slot() {} + // SwiffPlayer.dll 0x10071420: implicit destruction releases the + // value before the name, including when a local-frame resize shrinks. + // SwiffPlayer.dll 0x1008C460: copy the name, then the value. frame_slot(const tu_string& name, const as_value& val) : m_name(name), m_value(val) {} + // SwiffPlayer.dll 0x1008BDA0: the implicit copy follows the same member order. }; array m_local_frames; - // [DICE-MOD SwiffPlayer: the running function's bound `this` object and its superclass + // the running function's bound `this` object and its superclass // constructor (`super`). The shipped as_environment keeps them at +8212 (checked by // get_variable_raw before the target movie's members, used as `this` by CallMethod's // direct-call arm) and +8216 (preloaded into the `super` register/local at function entry). // Stock 2006 bound `this` to the target MOVIE for every call and never implemented `super`, // so a class constructor run on a plain object or another sprite acted on the wrong object - // and super() went nowhere. Non-owning; saved/restored around each call.] + // and super() went nowhere. Non-owning; saved/restored around each call. as_object_interface* m_this_object; as_as_function* m_super_ctor; - // [DICE-MOD SwiffPlayer #57] While a function body defined in this environment runs for + // While a function body defined in this environment runs for // ANOTHER environment, that caller's register bank; NULL otherwise (this environment's own). // Set and restored around each call by as_as_function::operator(). Non-owning. as_environment* m_register_env; + // SwiffPlayer.dll 0x10077D00 constructs all 256 register values eagerly. as_environment() : m_target(0), @@ -859,40 +815,56 @@ namespace gameswf m_super_ctor(0), m_register_env(0) { + m_registers.resize(256); } + ~as_environment(); + // SwiffPlayer.dll 0x1008A110; native movie pointer adjusts the secondary interface. movie* get_target() { return m_target; } + // SwiffPlayer.dll 0x1006ECE0 writes the target after the fixed register bank. void set_target(movie* target) { m_target = target; } + // SwiffPlayer.dll 0x1008A120 / 0x1008A140; names [INFERRED]. + void set_this_object(as_object_interface* object) { m_this_object = object; } + as_as_function* get_super_constructor() const { return m_super_ctor; } // stack access/manipulation // @@ TODO do more checking on these + // SwiffPlayer.dll push helpers: 0x1008E0F0 (string), 0x1008E180 (double), + // 0x1008E200 (float), 0x1008E3C0 (Boolean), 0x1008E450 (signed integer). + // 0x1008E280 / 0x1008E320 also construct an OBJECT before growing storage. + // 0x100A8CC0 constructs a narrow C-string value before resize/assignment; + // XML enumeration inlines the same sequence at 0x100A8D83..0x100A8DD1. + // [INFERRED] C-string instantiation of this template; native string storage. + // [CHOSEN, not recovered] S3 bridge: native objects share one refcount interface. + // Construct the value before growing the operand storage, then append a copy. template - void push(T val) { push_val(as_value(val)); } - void push_val(const as_value& val) { m_stack.push_back(val); } - // [DICE-MOD SwiffPlayer: MAKE THE VALUE STACK UNDERFLOW-TOLERANT, as the real Flash player is. - // - // menu.swf contains stray `Pop` (0x17) opcodes: at one site the bytecode is - // Push'_global'; GetVariable; Push'dice'; GetMember; Not; Not; BranchIfTrue +24 - // [157..180: Push'_global'; GetVariable; Push'dice',0,'Object'; New; SetMember] - // 181: Pop - // Every one of those opcodes has its SPEC-CORRECT stack effect in this gameswf (verified by - // instrumenting the VM with a depth-tracking opcode ring), and BOTH the taken and the - // fall-through path reach pc=181 with an EMPTY stack - so the Pop has nothing to pop. The - // movie is simply unbalanced there; ~20 such sites execute in its onLoad. - // - // The real Flash player - and DICE's gameswf, which ran this exact movie - absorb that: a pop - // on an empty stack yields `undefined` and execution continues. Stock gameswf instead indexes - // the array out of bounds (`m_stack.back()` at index -1) or resizes it NEGATIVE, and the - // negative resize destructs from a negative index -> ~as_value on garbage -> CRASH. That crash, - // not the SWF, is the defect. - // - // So: pop/top/bottom/drop all clamp and yield undefined rather than fault. This is FAITHFUL - // behaviour (matching the shipped player), not a workaround for our own integration. - // Indexed in Code/BF2/External/gameswf/GAMESWF_DIVERGENCES.md.] + void push(T val) + { + const as_value value(val); + m_stack.push_back(value); + } + void push_val(as_value val) + { + // SwiffPlayer.dll 0x10077640 copies its by-value argument into a local + // before resizing. Both copies stay alive through the appended assignment. + as_value copy; + copy = val; + m_stack.push_back(copy); + } + // [CHOSEN, not recovered] S3 bridge: retain the native menu integration's + // tolerant operand accesses while the VM/base boundary remains incomplete. + // Retail top (0x1008AB50), pop (0x10076600) and drop (0x1008C4A0) do not + // clamp; the shared resize helper (0x1000B980) traps on a negative size. + // [RETIRE-WHEN: swf-s3-operand-underflow] Reconcile native/retail operand + // effects with the base tag and validate menu initialization, callbacks and + // malformed stacks before replacing these guards. Empty accesses currently + // reached by the native menus are not proof of retail underflow behavior. static as_value& underflow_slot() { static as_value s_undef; s_undef.set_undefined(); return s_undef; } as_value pop() { + // SwiffPlayer.dll 0x10076600 copies the top before shrinking; + // the empty-stack return is the native tolerance bridge above. if (m_stack.size() <= 0) return as_value(); // undefined as_value result = m_stack.back(); m_stack.pop_back(); return result; } @@ -907,16 +879,17 @@ namespace gameswf if (index < 0 || index >= m_stack.size()) return underflow_slot(); return m_stack[index]; } - // [DICE-MOD SwiffPlayer: clamp instead of resizing NEGATIVE - see the underflow note above - // pop()/top(). This is the site that actually crashed: resize(negative) destructs from a - // negative index.] + // Keep an excessive drop within the native operand storage; see the bridge above. void drop(int count) { int n = m_stack.size() - count; if (n < 0) n = 0; m_stack.resize(n); } int get_top_index() const { return m_stack.size() - 1; } - as_value get_variable(const tu_string& varname, const array& with_stack) const; + // A successful with-scope lookup also writes its object to receiver, when supplied. + as_value get_variable(const tu_string& varname, const array& with_stack, + as_object_interface** receiver = NULL) const; // no path stuff: - as_value get_variable_raw(const tu_string& varname, const array& with_stack) const; + as_value get_variable_raw(const tu_string& varname, const array& with_stack, + as_object_interface** receiver = NULL) const; void set_variable(const tu_string& path, const as_value& val, const array& with_stack); // no path stuff: @@ -930,33 +903,62 @@ namespace gameswf void set_member(const tu_stringi& varname, const as_value& val); // Parameter/local stack frame management. + // SwiffPlayer.dll 0x1008AB70 returns the local-frame count. int get_local_frame_top() const { return m_local_frames.size(); } - // [DICE-MOD SwiffPlayer #41] true while a function frame (an empty-named barrier slot) is active. - bool in_function_frame() const; + // SwiffPlayer.dll 0x1008C4C0 forwards to the local-frame resize helper. void set_local_frame_top(int t) { assert(t <= m_local_frames.size()); m_local_frames.resize(t); } void add_frame_barrier() { m_local_frames.push_back(frame_slot()); } - // [DICE-MOD SwiffPlayer #41] the barrier a FUNCTION call pushes, marked (a BOOLEAN value) so a - // frame script's own barrier (an undefined value, pushed by the plain execute overload) can be - // told apart: a `var` declared above a function barrier is a timeline var, a clip property. - void add_function_barrier() { m_local_frames.push_back(frame_slot(tu_string(""), as_value(true))); } - // [DICE-MOD SwiffPlayer #55] the environment's register `reg` (the operand is a byte, so + // the environment's register `reg` (the operand is a byte, so // 0..255 is always a valid slot). Never NULL. as_value* register_ptr(int reg); - // [DICE-MOD SwiffPlayer #57] the environment whose bank register operands address here. + // the environment whose bank register operands address here. as_environment* register_bank() { return m_register_env ? m_register_env : this; } // Internal. int find_local(const tu_string& varname) const; bool parse_path(const tu_string& var_path, tu_string* path, tu_string* var) const; movie* find_target(const tu_string& path) const; - movie* find_target(const as_value& val) const; - // [DICE-MOD SwiffPlayer: dotted-path resolution through OBJECT members, with the shipped - // _global fallback - the resolver get_variable/set_variable use. See the .cpp.] + as_object_interface* find_target(const as_value& val) const; + // dotted-path resolution through OBJECT members, with the shipped + // _global fallback - the resolver get_variable/set_variable use. See the .cpp. as_object_interface* find_object_path(const tu_string& path, as_object_interface* start) const; + + // Movie teardown: appends every object or function held on the stack, in the registers, + // the variables and the local frames to *held, then empties them. + // [CHOSEN, not recovered] issue #7; see release_script_objects. + void release_values(array* held); }; + // Appends v to *held when it is an object or an ActionScript function, the only values that + // can keep another object alive. A helper of the movie teardown (release_script_objects). + // [CHOSEN, not recovered] issue #7. + inline void hold_script_value(array* held, const as_value& v) + { + if (v.get_type() == as_value::OBJECT || v.get_type() == as_value::AS_FUNCTION) + { + held->push_back(v); + } + } + + // Breaks every script reference cycle between the live script objects, so plain reference + // counting can free them once their owners let go. Every registered clip and object (see + // register_script_object), reachable from the movie or not, is cleared: a clip's environment, + // event handlers and children (without UNLOAD events), an object's members, accessors and + // prototype. Runs no ActionScript. Afterwards every script object is unusable and _global is + // empty: call it only when the whole player is going away, right before its movie's last + // reference is dropped and _global is reset, and only when no other player is alive + // (SwiffPlayer::releaseMovie counts them), so nothing still in use is cleared. + // [CHOSEN, not recovered] issue #7 (https://github.com/B2BF/OpenBF2/issues/7): our gameswf + // replaces the shipped player, whose own teardown is not recovered. + void release_script_objects(); + + // Drops the Object.registerClass bindings of every library definition (gameswf_impl.cpp). + // Part of release_script_objects. [CHOSEN, not recovered] issue #7. + void release_library_classes(); + + // Parameters/environment for C functions callable from ActionScript. struct fn_call { @@ -991,6 +993,16 @@ namespace gameswf // Clean up any stray heap stuff we've allocated. void action_clear(); + // [CHOSEN, not recovered] S3 bridge for the borrowed constructor context + // used by the separately compiled timer dispatcher. + void set_call_super(as_as_function* constructor); + void set_environment_super(as_environment* env); + void gc_mark_value(const as_value& value); + void gc_mark_modules(); + // [CHOSEN, not recovered] S3 bridge: expose mark traversal independently + // while XML edges, host roots and native strong ownership block the sweep. + // This advances only the generation; it never claims to collect objects. + void advance_gc_mark_generation(); // Dispatching methods from C++. as_value call_method0(const as_value& method, as_environment* env, as_object_interface* this_ptr); @@ -1005,12 +1017,19 @@ namespace gameswf const as_value& arg0, const as_value& arg1, const as_value& arg2); - const char* call_method_parsed( - as_environment* env, - as_object_interface* this_ptr, - const char* method_name, - const char* method_arg_fmt, - va_list args); + // Calls an expression containing a method name and quoted or numeric arguments. + // Returns shared string storage overwritten by the next expression call. + // The environment must have a target and the expression at least one token. + // Parsing uses at most 999 bytes. + const char* call_method_expression(as_environment* env, as_object_interface* receiver, + const char* expression); + const char* call_method_expression(as_environment* env, as_object_interface* receiver, + const Uint16* expression); + + // Access the independent Key module without initializing it. Missing modules are ignored. + void add_key_listener(as_object_interface* listener); + void remove_key_listener(as_object_interface* listener); + int get_last_key_pressed(); // tulrich: don't use this! To register a class constructor, // just assign the classname to the constructor function. E.g.: @@ -1019,9 +1038,9 @@ namespace gameswf // //void register_as_object(const char* object_name, as_c_function_ptr handler); - // [DICE-MOD SwiffPlayer: accessor for the _global object, so the SwiffPlayer AS bridge can hang + // accessor for the _global object, so the SwiffPlayer AS bridge can hang // the dice.* namespace graph off it before the first advance. Forces action_init(). See - // gameswf_action.cpp and GAMESWF_DIVERGENCES.md.] + // gameswf_action.cpp and GAMESWF_DIVERGENCES.md. as_object* get_global_object(); // Numerical indices for standard member names. Can use this @@ -1053,7 +1072,6 @@ namespace gameswf M_YMOUSE, M_PARENT, M_TEXT, - M_TEXTWIDTH, M_TEXTCOLOR, M_ONLOAD, diff --git a/Code/BF2/External/gameswf/gameswf_button.cpp b/Code/BF2/External/gameswf/gameswf_button.cpp index 1389c03a4..c7a4ef487 100644 --- a/Code/BF2/External/gameswf/gameswf_button.cpp +++ b/Code/BF2/External/gameswf/gameswf_button.cpp @@ -7,6 +7,7 @@ #include "gameswf_button.h" +#include "gameswf_log.h" #include "gameswf_action.h" #include "gameswf_render.h" @@ -144,7 +145,10 @@ frame loop: namespace gameswf { - // [DICE-MOD SwiffPlayer #51] generate_mouse_button_events (and the RW-89 tracer that lived in it) +#if !defined(_MSC_VER) + const char* swf_list_trace_path(character* ch); // [TEMP] gameswf_impl.cpp +#endif + // generate_mouse_button_events (and the RW-89 tracer that lived in it) // are gone: the shipped player has no root-level dispatcher, every character runs its own mouse // pass - for buttons, button_character_instance::mouse_update below. @@ -172,11 +176,26 @@ namespace gameswf OVER }; e_mouse_state m_mouse_state; - // [DICE-MOD SwiffPlayer #51] the shipped button's +216 first-frame latch and +217 held press; + // the shipped button's +216 first-frame latch and +217 held press; // m_last_mouse_flags / m_mouse_flags above are its +220 / +224 (bit 0 inside, bit 1 down). bool m_first_mouse_frame; bool m_mouse_pressed; + // [CHOSEN, not recovered] issue #7: movie teardown, see release_script_objects. The state + // characters are walked too; the button keeps owning them. + virtual void release_script_values(array* held) + { + character::release_script_values(held); + for (int i = 0; i < m_record_character.size(); i++) + { + if (m_record_character[i] != NULL) + { + held->push_back(as_value(m_record_character[i].get_ptr())); + } + } + } + + // SwiffPlayer.dll 0x100A2C50; native layout and tree-root ownership are retained. button_character_instance(button_character_definition* def, movie* parent, int id) : character(parent, id), @@ -217,13 +236,27 @@ namespace gameswf } } + // Compiler deleting wrapper: SwiffPlayer.dll 0x100A3BF0; the lifetime + // body at 0x100A3C30 remains separate from forwarding and conditional deletion. ~button_character_instance() { + // SwiffPlayer.dll 0x100A3C30 releases this button's capture before + // record characters. Re-read the publication after the capture query. + if (get_global_root_movie() != NULL + && get_global_root_movie()->get_active_mouse_entity() == this) + { + get_global_root_movie()->set_active_mouse_entity(NULL); + } } + // SwiffPlayer.dll 0x100A2E20 delegates to the immediate parent's root. movie_root* get_root() { return get_parent()->get_root(); } movie* get_root_movie() { return get_parent()->get_root_movie(); } + // SwiffPlayer.dll 0x100A2E30 forwards to the definition bounds slot. + rect get_bound_copy() const override { return m_def->get_bound_copy(); } + + // SwiffPlayer.dll 0x100A2EA0 leaves the first-frame and held-press latches alone. void restart() { m_last_mouse_flags = IDLE; @@ -242,7 +275,6 @@ namespace gameswf // Implement mouse-drag. character::do_mouse_drag(); - matrix mat = get_world_matrix(); // Advance our relevant characters. {for (int i = 0; i < m_def->m_button_records.size(); i++) @@ -254,6 +286,9 @@ namespace gameswf } // Matrix + // SwiffPlayer.dll 0x100A2EE0 + // fetches the world matrix once per non-null record, before testing state. + matrix mat = get_world_matrix(); matrix sub_matrix = mat; sub_matrix.concatenate(rec.m_button_matrix); @@ -268,6 +303,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x100A2FB0. void display() { for (int i = 0; i < m_def->m_button_records.size(); i++) @@ -285,7 +321,6 @@ namespace gameswf } } - do_display_callback(); } inline int transition(int a, int b) const @@ -295,7 +330,7 @@ namespace gameswf } - // [DICE-MOD SwiffPlayer #51] sub_100A3020 (1109 bytes, read in full 2026-09-13) - the button's + // sub_100A3020 (1109 bytes, read in full 2026-09-13) - the button's // mouse pass, vtable slot 4: stock's generate_mouse_button_events + on_button_event fused into // the same shape as the sprite's. A per-frame (inside, down) state against the previous frame, // run only while nobody else holds the pointer; inside means one of the definition's hit-test @@ -307,7 +342,9 @@ namespace gameswf // actions never keeps the pointer captured. virtual bool mouse_update(bool consumed) { - movie* root = get_root_movie(); + // [CHOSEN, not recovered] S2 bridge: tree ownership replaces the retail + // global root; 0x100A3020 uses the immediate parent for capture/input. + movie* root = get_parent(); if (root == NULL) { return false; @@ -455,15 +492,22 @@ namespace gameswf - // [DICE-MOD SwiffPlayer #51] the tail of sub_100A3020 for one transition (a button_action + // the tail of sub_100A3020 for one transition (a button_action // condition bit): the transition sound - the definition's sound records are indexed 0 roll // out, 1 roll over, 2 press, 3 release - the capture dropped when the definition has no // actions at all, the record restart, then the definition's actions whose conditions include - // the bit. Stock's on_button_event did the same from an event id. The actions still go through - // the parent's queue as stock did; the shipped runs them at once through the root - // [UNRESOLVED: whether that ordering is observable]. + // the bit. SwiffPlayer.dll 0x100A3410..0x100A3436 executes actions immediately + // in the parent's environment. void fire_transition(int c) { +#if !defined(_MSC_VER) + // [TEMP] c-swf-disconnect: a button transition. + if (swf_list_trace_on()) + { + SWF_LIST_TRACE("button cond=0x%x on '%s' (%d action records)", c, swf_list_trace_path(this), + m_def->m_button_actions.size()); + } +#endif if (m_def->m_sound != NULL) { sound_handler* s = get_sound_handler(); @@ -505,7 +549,7 @@ namespace gameswf // restart the characters of the new state. restart_characters(c); - // Add appropriate actions to the movie's execute list... + // Execute the matching transition actions. {for (int i = 0; i < m_def->m_button_actions.size(); i++) { if (m_def->m_button_actions[i].m_conditions & c) @@ -513,7 +557,9 @@ namespace gameswf // Matching action. for (int j = 0; j < m_def->m_button_actions[i].m_actions.size(); j++) { - get_parent()->add_action_buffer(m_def->m_button_actions[i].m_actions[j]); + // [CHOSEN, not recovered] S2 bridge to retail's + // parent secondary +0x2C -> action_buffer::execute (0x100961E0). + m_def->m_button_actions[i].m_actions[j]->execute(get_parent()->get_action_environment()); } } }} @@ -522,30 +568,11 @@ namespace gameswf void restart_characters(int condition) { - // Restart our relevant characters + // SwiffPlayer.dll 0x100A34A0: + // restart every non-null record, including transitions with condition zero. for (int i = 0; i < m_def->m_button_records.size(); i++) { - bool restart = false; - button_record* rec = &m_def->m_button_records[i]; - - switch (m_mouse_state) - { - case OVER: - { - if ((rec->m_over) && (condition & button_action::IDLE_TO_OVER_UP)) - { - restart = true; - } - break; - } - // @@ Hm, are there other cases where we restart stuff? - default: - { - break; - } - } - - if (restart == true) + if (m_record_character[i] != NULL) { m_record_character[i]->restart(); } @@ -558,6 +585,11 @@ namespace gameswf get_parent()->get_mouse_state(x, y, buttons); } + // [CHOSEN, not recovered] S2 bridge: tree root replaces the retail global + // accessed by 0x100A2E70/0x100A2E80. It owns the same shared capture state. + virtual movie* get_active_mouse_entity() { return get_root_movie()->get_active_mouse_entity(); } + virtual void set_active_mouse_entity(movie* m) { get_root_movie()->set_active_mouse_entity(m); } + // // ActionScript overrides @@ -565,88 +597,48 @@ namespace gameswf virtual void set_member(const tu_stringi& name, const as_value& val) { - // TODO: pull these up into a base class, to - // share as much as possible with sprite_instance. - as_standard_member std_member = get_standard_member(name); - switch (std_member) - { - default: - case M_INVALID_MEMBER: - break; - case M_VISIBLE: // _visible - { - m_visible = val.to_bool(); + // SwiffPlayer.dll 0x100A34E0. + // Retail compares these names case-sensitively and has no width/height arm. + const char* key = name.c_str(); + if (strcmp(key, "_x") == 0 || strcmp(key, "_y") == 0) + { + matrix m = get_matrix(); + m.m_[strcmp(key, "_x") == 0 ? 0 : 1][2] = float(val.to_number() * 20.0); + set_matrix(m); return; } - case M_ALPHA: // _alpha - { - // Set alpha modulate, in percent. - cxform cx = get_cxform(); - cx.m_[3][0] = float(val.to_number()) / 100.f; - set_cxform(cx); - //m_accept_anim_moves = false; + if (strcmp(key, "_xscale") == 0) + { + matrix m = get_matrix(); + const float scale = float(val.to_number() * 0.01f); + const float y_scale = m.get_y_scale(); + const float rotation = m.get_rotation(); + m.set_scale_rotation(scale, y_scale, rotation); + set_matrix(m); return; } - case M_X: // _x - { - matrix m = get_matrix(); // @@ get_world_matrix()??? - m.m_[0][2] = float(PIXELS_TO_TWIPS(val.to_number())); - this->set_matrix(m); + if (strcmp(key, "_yscale") == 0) + { + matrix m = get_matrix(); + const float x_scale = m.get_x_scale(); + const float scale = float(val.to_number() * 0.01f); + const float rotation = m.get_rotation(); + m.set_scale_rotation(x_scale, scale, rotation); + set_matrix(m); return; } - case M_Y: // _y + if (strcmp(key, "_alpha") == 0) { - matrix m = get_matrix(); // @@ get_world_matrix()??? - m.m_[1][2] = float(PIXELS_TO_TWIPS(val.to_number())); - this->set_matrix(m); - return; - } -// evan : need set_width and set_height function for struct character -#if 0 - case M_WIDTH: // _width - { - for (int i = 0; i < m_def->m_button_records.size(); i++) - { - button_record& rec = m_def->m_button_records[i]; - if (m_record_character[i] == NULL) - { - continue; - } - if ((m_mouse_state == UP && rec.m_up) - || (m_mouse_state == DOWN && rec.m_down) - || (m_mouse_state == OVER && rec.m_over)) - { - m_record_character[i]->set_width(val.to_number); - // @@ evan: should we return here? - return; - } - } - + cxform cx = get_cxform(); + cx.m_[3][0] = float(val.to_number() * 0.01f); + set_cxform(cx); return; } - case M_HEIGHT: // _height + if (strcmp(key, "_visible") == 0) { - for (int i = 0; i < m_def->m_button_records.size(); i++) - { - button_record& rec = m_def->m_button_records[i]; - if (m_record_character[i] == NULL) - { - continue; - } - if ((m_mouse_state == UP && rec.m_up) - || (m_mouse_state == DOWN && rec.m_down) - || (m_mouse_state == OVER && rec.m_over)) - { - m_record_character[i]->set_height(val.to_number); - // @@ evan: should we return here? - return; - } - } - + m_visible = val.to_bool(); return; } -#endif - } log_error("error: button_character_instance::set_member('%s', '%s') not implemented yet\n", name.c_str(), @@ -655,85 +647,32 @@ namespace gameswf virtual bool get_member(const tu_stringi& name, as_value* val) { - // TODO: pull these up into a base class, to - // share as much as possible with sprite_instance. - as_standard_member std_member = get_standard_member(name); - switch (std_member) + // SwiffPlayer.dll 0x100A37D0. + const char* key = name.c_str(); + if (strcmp(key, "_x") == 0 || strcmp(key, "_y") == 0) { - default: - case M_INVALID_MEMBER: - break; - case M_VISIBLE: // _visible - { - val->set_bool(this->get_visible()); + matrix m = get_matrix(); + val->set_double(double(m.m_[strcmp(key, "_x") == 0 ? 0 : 1][2]) * double(0.05f)); return true; } - case M_ALPHA: // _alpha + if (strcmp(key, "_xscale") == 0 || strcmp(key, "_yscale") == 0) { - // @@ TODO this should be generic to struct character! - // Alpha units are in percent. - val->set_double(get_cxform().m_[3][0] * 100.f); + matrix m = get_matrix(); + const float scale = strcmp(key, "_xscale") == 0 ? m.get_x_scale() : m.get_y_scale(); + val->set_double(double(scale) * 100.0); return true; } - case M_X: // _x + if (strcmp(key, "_alpha") == 0) { - matrix m = get_matrix(); // @@ get_world_matrix()??? - val->set_double(TWIPS_TO_PIXELS(m.m_[0][2])); + val->set_double(double(get_cxform().m_[3][0]) * 100.0); return true; } - case M_Y: // _y + if (strcmp(key, "_visible") == 0) { - matrix m = get_matrix(); // @@ get_world_matrix()??? - val->set_double(TWIPS_TO_PIXELS(m.m_[1][2])); + val->set_bool(m_visible); return true; } - case M_WIDTH: // _width - { - for (int i = 0; i < m_def->m_button_records.size(); i++) - { - button_record& rec = m_def->m_button_records[i]; - if (m_record_character[i] == NULL) - { - continue; - } - if ((m_mouse_state == UP && rec.m_up) - || (m_mouse_state == DOWN && rec.m_down) - || (m_mouse_state == OVER && rec.m_over)) - { - val->set_double(TWIPS_TO_PIXELS(m_record_character[i]->get_width())); - // @@ evan: should we return here? - return true; - } - } - - // from the experiments with macromedia flash player - val->set_double(0); - return true; - } - case M_HEIGHT: // _height - { - for (int i = 0; i < m_def->m_button_records.size(); i++) - { - button_record& rec = m_def->m_button_records[i]; - if (m_record_character[i] == NULL) - { - continue; - } - if ((m_mouse_state == UP && rec.m_up) - || (m_mouse_state == DOWN && rec.m_down) - || (m_mouse_state == OVER && rec.m_over)) - { - val->set_double(TWIPS_TO_PIXELS(m_record_character[i]->get_height())); - // @@ evan: should we return here? - return true; - } - } - - // from the experiments with macromedia flash player - val->set_double(0); - return true; - } - } + log_error("error: button_character_instance::get_member('%s') not implemented yet\n", key); return false; } @@ -747,6 +686,7 @@ namespace gameswf // button_record // + // SwiffPlayer.dll 0x100A1BE0. bool button_record::read(stream* in, int tag_type, movie_definition_sub* m) // Return true if we read a record; false if this is a null record. { @@ -779,6 +719,7 @@ namespace gameswf // + // SwiffPlayer.dll 0x100A2710. button_action::~button_action() { for (int i = 0, n = m_actions.size(); i < n; i++) @@ -788,6 +729,7 @@ namespace gameswf m_actions.resize(0); } + // SwiffPlayer.dll 0x100A2580. void button_action::read(stream* in, int tag_type) { // Read condition flags. @@ -813,6 +755,7 @@ namespace gameswf // button_character_definition // + // SwiffPlayer.dll 0x100A3A60; the tree assigns character IDs separately. button_character_definition::button_character_definition() : m_sound(NULL) @@ -820,12 +763,43 @@ namespace gameswf { } + // SwiffPlayer.dll 0x100A3AF0; compiler deleting wrapper 0x100A3CB0. button_character_definition::~button_character_definition() { delete m_sound; } + // SwiffPlayer.dll 0x100A2010. + // Keep equal-layer insertion and the shipped halving search order. + int button_character_definition::find_record_index(int layer) const + { + const int count = m_button_records.size(); + if (count == 0) return 0; + int index = count >> 1; + int step = index; + for (;;) + { + step >>= 1; + if (step < 1) step = 1; + const int current = m_button_records[index].m_button_layer; + if (layer > current) + { + if (index == count - 1) return count; + index += step; + } + else + { + if (layer == current || index == 0 || m_button_records[index - 1].m_button_layer < layer) + { + return index; + } + index -= step; + } + } + } + + // SwiffPlayer.dll 0x100A22D0. void button_character_definition::sound_info::read(stream* in) { m_in_point = m_out_point = m_loop_count = 0; @@ -869,6 +843,25 @@ namespace gameswf + // SwiffPlayer.dll 0x100A1F90. Retail does not initialize this accumulator, + // even for nonempty buttons; preserve that defect rather than inventing a seed. + rect button_character_definition::get_bound_copy() const + { + rect bounds; + for (int i = 0, n = m_button_records.size(); i < n; ++i) + { + character_def* definition = m_button_records[i].m_character_def; + if (definition) + { + rect child = definition->get_bound_copy(); // +0x20 + child.transform(m_button_records[i].m_button_matrix); + bounds.expand_to_rect(child); + } + } + return bounds; + } + + // SwiffPlayer.dll 0x100A2960. void button_character_definition::read(stream* in, int tag_type, movie_definition_sub* m) // Initialize from the given stream. { @@ -887,7 +880,8 @@ namespace gameswf // Null record; marks the end of button records. break; } - m_button_records.push_back(r); + // SwiffPlayer.dll 0x100A2960. + m_button_records.insert(find_record_index(r.m_button_layer), r); } // Read actions. @@ -932,7 +926,8 @@ namespace gameswf // Null record; marks the end of button records. break; } - m_button_records.push_back(r); + // SwiffPlayer.dll 0x100A2960. + m_button_records.insert(find_record_index(r.m_button_layer), r); } if (button_2_action_offset > 0) @@ -963,6 +958,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x100A3B70. character* button_character_definition::create_character_instance(movie* parent, int id) // Create a mutable instance of our definition. { diff --git a/Code/BF2/External/gameswf/gameswf_button.h b/Code/BF2/External/gameswf/gameswf_button.h index 925579353..edd8c932b 100644 --- a/Code/BF2/External/gameswf/gameswf_button.h +++ b/Code/BF2/External/gameswf/gameswf_button.h @@ -39,7 +39,7 @@ namespace gameswf } }; - // [DICE-MOD SwiffPlayer #51] generate_mouse_button_events is gone: the shipped player has no + // generate_mouse_button_events is gone: the shipped player has no // root-level dispatcher, every character runs its own mouse pass (movie::mouse_update). The // state record stays for its m_active_entity, the root's mouse capture. @@ -56,6 +56,8 @@ namespace gameswf struct button_record { + // Implicit construction: SwiffPlayer.dll 0x100A1C70 initializes the + // matrix then cxform; flags, ID, definition and layer remain unwritten. bool m_hit_test; bool m_down; bool m_over; @@ -85,8 +87,11 @@ namespace gameswf OVER_DOWN_TO_IDLE = 1 << 8, }; int m_conditions; + // SwiffPlayer.dll 0x100A2560: implicit construction initializes only the array. array m_actions; + // SwiffPlayer.dll 0x100A2840: deleting wrapper invokes this destructor + // before the conditional object free. ~button_action(); void read(stream* in, int tag_type); }; @@ -103,6 +108,8 @@ namespace gameswf struct sound_info { + // SwiffPlayer.dll 0x100A2610 / 0x100A2600: implicit construction + // and destruction affect only the envelope array; scalars stay uninitialized. void read(stream* in); bool m_no_multiple; @@ -119,6 +126,8 @@ namespace gameswf struct button_sound_info { + // SwiffPlayer.dll 0x100A2640 / 0x100A2630: sound_info supplies + // the only member lifetime work; the ID and sample pointer stay uninitialized. Uint16 m_sound_id; sound_sample_impl* m_sam; sound_info m_sound_style; @@ -127,6 +136,9 @@ namespace gameswf struct button_sound_def { void read(stream* in, movie_definition_sub* m); + // SwiffPlayer.dll 0x100A26E0 / 0x100A2680: construct four envelope + // arrays, then destroy them in reverse order; scalar fields stay uninitialized. + // The deleting wrapper at 0x100A2810 destroys them before freeing the object. button_sound_info m_button_sounds[4]; }; @@ -138,9 +150,14 @@ namespace gameswf button_character_definition(); virtual ~button_character_definition(); + // Retail leaves the accumulator unwritten before including its records. + // The returned rectangle is indeterminate for an empty button as well. + rect get_bound_copy() const override; character* create_character_instance(movie* parent, int id); void read(stream* in, int tag_type, movie_definition_sub* m); + // SwiffPlayer.dll 0x100A2010: find the insertion point in layer order. + int find_record_index(int layer) const; }; }; // end namespace gameswf diff --git a/Code/BF2/External/gameswf/gameswf_dlist.cpp b/Code/BF2/External/gameswf/gameswf_dlist.cpp index 7f3615e3b..3f1142544 100644 --- a/Code/BF2/External/gameswf/gameswf_dlist.cpp +++ b/Code/BF2/External/gameswf/gameswf_dlist.cpp @@ -17,6 +17,7 @@ namespace gameswf { + // SwiffPlayer.dll 0x100A7800: signed depth comparison yields -1, 0 or 1. /*static*/ int display_object_info::compare(const void* _a, const void* _b) { display_object_info* a = (display_object_info*) _a; @@ -42,65 +43,50 @@ namespace gameswf // matching the given depth. Failing that, return the index // of the first object with a larger depth. { - int size = m_display_object_array.size(); - if (size == 0) - { - return 0; - } - - // Binary search. - int jump = size >> 1; - int index = jump; + // SwiffPlayer.dll 0x100A7820. On an + // equal depth retail keeps the binary-search hit if referenced, otherwise + // searches the equal-depth run for a referenced entry before using the hit. + const int size = m_display_object_array.size(); + if (size == 0) return 0; + int jump = size >> 1; + int index = jump; for (;;) { jump >>= 1; if (jump < 1) jump = 1; - - if (depth > m_display_object_array[index].m_character->get_depth()) + const int current = m_display_object_array[index].m_character->get_depth(); + if (depth > current) { - if (index == size - 1) - { - index = size; - break; - } + if (index == size - 1) return size; index += jump; } - else if (depth < m_display_object_array[index].m_character->get_depth()) + else if (depth < current) { - if (index == 0 - || depth > m_display_object_array[index - 1].m_character->get_depth()) - { - break; - } + if (index == 0 || m_display_object_array[index - 1].m_character->get_depth() < depth) return index; index -= jump; } else { - // match -- scan backward to make sure this is the first entry with this depth. - // - // Linear. But multiple objects with the same depth are only allowed for - // very old SWF's, so we don't really care. - for (;;) + if (m_display_object_array[index].m_ref) return index; + int candidate = index; + while (candidate != 0 && m_display_object_array[candidate].m_character->get_depth() == depth) { - if (index == 0 - || m_display_object_array[index - 1].m_character->get_depth() < depth) - { - break; - } - index--; + if (m_display_object_array[candidate].m_ref) return candidate; + candidate--; } - assert(m_display_object_array[index].m_character->get_depth() == depth); - assert(index == 0 || m_display_object_array[index - 1].m_character->get_depth() < depth); - break; + if (m_display_object_array[candidate].m_character->get_depth() != depth) candidate++; + for (; candidate < size; candidate++) + { + if (m_display_object_array[candidate].m_character->get_depth() != depth) return index; + if (m_display_object_array[candidate].m_ref) return candidate; + } + return index; } } - - assert(index >= 0 && index <= size); - - return index; } + // SwiffPlayer.dll 0x100A78F0. int display_list::get_display_index(int depth) // Like the above, but looks for an exact match, and returns -1 if failed. { @@ -115,6 +101,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x100A7920. character* display_list::get_character_at_depth(int depth) { int index = get_display_index(depth); @@ -131,6 +118,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x100A7D10 visits referenced entries in display-list order. character* display_list::get_character_by_name(const tu_string& name) { // See if we have a match on the display list. @@ -164,6 +152,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x100A8080. void display_list::add_display_object( character* ch, Uint16 depth, @@ -177,34 +166,22 @@ namespace gameswf assert(ch); - int size = m_display_object_array.size(); + // [CHOSEN, not recovered] S3 bridge: retain the 2006 argument at + // callers; retail always unreferences an equal-depth occupant. + (void) replace_if_depth_is_occupied; int index = find_display_index(depth); - - if (replace_if_depth_is_occupied) + if (index >= 0 && index < m_display_object_array.size()) { - // Eliminate an existing object if it's in the way. - if (index >= 0 && index < size) + display_object_info& old = m_display_object_array[index]; + if (old.m_character->get_depth() == depth) { - display_object_info & dobj = m_display_object_array[index]; - - if (dobj.m_character->get_depth() == depth) - { - dobj.set_character(NULL); - m_display_object_array.remove(index); - } + old.m_ref = false; + old.m_character->release_mouse_capture_within(); + // SwiffPlayer.dll 0x100A80F6: a surviving old occupant is detached. + old.m_character->set_parent(NULL); + old.m_character->mark_dead(); } } - else - { - // Caller wants us to allow multiple objects - // with the same depth. find_display_index() - // returns the first matching depth, if there - // are any, so the new character will get - // inserted before all the others with the - // same depth. This matches the semantics - // described by Alexi's SWF ref. (This is all - // for legacy SWF compatibility anyway.) - } ch->set_depth(depth); @@ -217,9 +194,8 @@ namespace gameswf di.m_character->set_ratio(ratio); di.m_character->set_clip_depth(clip_depth); - // Insert into the display list... - assert(index == find_display_index(depth)); - + // Retail searches again after setting the new character's properties. + index = find_display_index(depth); m_display_object_array.insert(index, di); // do the frame1 actions (if applicable) and the "onClipEvent (load)" event. @@ -227,6 +203,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x100A7960: clip_depth is not changed by a move. void display_list::move_display_object( Uint16 depth, bool use_cxform, @@ -291,6 +268,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x100A81B0. void display_list::replace_display_object( character* ch, Uint16 depth, @@ -362,8 +340,8 @@ namespace gameswf } - // [DICE-MOD SwiffPlayer #32] raw entries below: the character may already be unreferenced. - void display_list::remove_display_object(Uint16 depth, int id) + // raw entries below: the character may already be unreferenced. + void display_list::remove_display_object(Uint16 depth) // Removes the object at the specified depth. { // IF_VERBOSE_DEBUG(log_msg("dl::remove(%d)\n", depth));//xxxxx @@ -388,41 +366,39 @@ namespace gameswf assert(m_display_object_array[index].m_character.get_ptr()->get_depth() == depth); - if (id != -1) - { - // Caller specifies a specific id; scan forward til we find it. - for (;;) - { - if (m_display_object_array[index].m_character.get_ptr()->get_id() == id) - { - break; - } - if (index + 1 >= size - || m_display_object_array[index + 1].m_character.get_ptr()->get_depth() != depth) - { - // Didn't find a match! - log_error("remove_display_object: no character at depth %d with id %d\n", depth, id); - return; - } - index++; - } - assert(index < size); - assert(m_display_object_array[index].m_character.get_ptr()->get_depth() == depth); - assert(m_display_object_array[index].m_character.get_ptr()->get_id() == id); - } + // SwiffPlayer.dll 0x100A7A20 takes only depth. // Removing the character at get_display_object(index). display_object_info& di = m_display_object_array[index]; // Remove reference only. di.m_ref = false; - if (di.m_character.get_ptr()) di.m_character->mark_dead(); // [DICE-MOD SwiffPlayer #42] dead from the removal on + // 0x100A7A20 (0x100A7A67..0x100A7AAA): a removed character that + // holds the root's mouse capture, or contains its holder, releases it. The holder took it on + // its press (#51) and gives it back only in its own release transition, which a character + // off the list never runs again; every other state machine stays gated off. mainMenu.swf's + // CREATE ACCOUNT button: its onPress runs createOffline, which on success jumps the root + // from the account page (frame 19) to the main menu (49) and removes the pressed button, so + // after an SP account creation no click reached the menu. + if (di.m_character.get_ptr()) di.m_character->release_mouse_capture_within(); + // SwiffPlayer.dll 0x100A7AB5: detached script references must not retain + // a borrowed parent that can be destroyed before the next timer callback. + di.m_character->set_parent(NULL); + if (di.m_character.get_ptr()) di.m_character->mark_dead(); // dead from the removal on } + // SwiffPlayer.dll 0x100A7F10 snapshots the count, sends UNLOAD to every + // stored character (including unreferenced entries), then clears storage. void display_list::clear() // clear the display list. { +#if !defined(_MSC_VER) + if (g_swf_mouse_pass_depth > 0) + { + SWF_LIST_TRACE("clear list %p (size %d, sprite destroyed)", (void*) this, m_display_object_array.size()); + } +#endif int i, n = m_display_object_array.size(); for (i = 0; i < n; i++) { @@ -433,8 +409,25 @@ namespace gameswf m_display_object_array.clear(); } - - + + + void display_list::release_characters(array* held) + // [CHOSEN, not recovered] issue #7: movie teardown, see release_script_objects. Unlike clear(), + // no UNLOAD: the movie is being destroyed with its scripts already disconnected. + { + for (int i = 0, n = m_display_object_array.size(); i < n; i++) + { + character* ch = m_display_object_array[i].m_character.get_ptr(); + if (ch != NULL) + { + held->push_back(as_value(ch)); + } + } + m_display_object_array.clear(); + } + + + // SwiffPlayer.dll 0x100A7AE0. void display_list::reset() // reset the references to the display list. { @@ -447,6 +440,8 @@ namespace gameswf } + // SwiffPlayer.dll 0x100A7F50: backwards sweep, release the character before + // removing its entry; the final removal frees the array. No list-storage hold. void display_list::update() // remove unreferenced objects. { @@ -466,6 +461,14 @@ namespace gameswf r++; } } +#if !defined(_MSC_VER) + // [TEMP] c-swf-disconnect: a sweep inside a mouse pass (the owner is named by the goto line). + if (r > 0 && g_swf_mouse_pass_depth > 0) + { + SWF_LIST_TRACE("sweep list %p removed %d, %d left%s", (void*) this, r, m_display_object_array.size(), + m_display_object_array.size() == 0 ? " - EMPTY (buffer freed)" : ""); + } +#endif //printf("### removed characters: %4d active characters: %4d\n", r, m_display_object_array.size()); } @@ -474,50 +477,28 @@ namespace gameswf void display_list::advance(float delta_time) // advance referenced characters. { - int n = m_display_object_array.size(); + // SwiffPlayer.dll 0x100A82A0 snapshots pointers to referenced entries, + // then rechecks their reference flags before dispatch. It holds no characters. + array entries; + const int n = m_display_object_array.size(); for (int i = 0; i < n; i++) { - // @@@@ TODO FIX: If array changes size due to - // character actions, the iteration may not be - // correct! - // - // What's the correct thing to do here? Options: - // - // * copy the display list at the beginning, - // iterate through the copy - // - // * use (or emulate) a linked list instead of - // an array (still has problems; e.g. what - // happens if the next or current object gets - // removed from the dlist?) - // - // * iterate through current array in depth - // order. Always find the next object using a - // search of current array (but optimize the - // common case where nothing has changed). - // - // * ??? - // - // Need to test to see what Flash does. - if (n != m_display_object_array.size()) + if (m_display_object_array[i].m_ref == true) { - log_error("gameswf bug: dlist size changed due to character actions, bailing on update!\n"); - break; + entries.push_back(&m_display_object_array[i]); } - - display_object_info & dobj = m_display_object_array[i]; - - if (dobj.m_ref == true) + } + for (int i = 0, count = entries.size(); i < count; i++) + { + if (entries[i]->m_ref) { - character* ch = dobj.m_character.get_ptr(); - assert(ch); - - ch->advance(delta_time); + entries[i]->m_character->advance(delta_time); } } } + // SwiffPlayer.dll 0x100A7B00: visibility and mask-only gates precede masking. void display_list::display() // Display the referenced characters. Lower depths // are obscured by higher depths. @@ -533,16 +514,15 @@ namespace gameswf character* ch = dobj.m_character.get_ptr(); assert(ch); - if (ch->get_visible() == false) { // Don't display. continue; } - // [DICE-MOD SwiffPlayer: a setMask() mask is drawn only inside its target's mask + // a setMask() mask is drawn only inside its target's mask // sandwich (the shipped display_list::display, sub_100A7B00, skips characters whose - // +196 byte is set).] + // +196 byte is set). if (ch->m_is_mask_only) { continue; @@ -574,7 +554,7 @@ namespace gameswf if (ch->m_mask != NULL) { - // [DICE-MOD SwiffPlayer: the setMask() sandwich, exactly as sub_100A7B00 does it.] + // the setMask() sandwich, exactly as sub_100A7B00 does it. render::begin_submit_mask(); ch->m_mask->display(); render::end_submit_mask(); diff --git a/Code/BF2/External/gameswf/gameswf_dlist.h b/Code/BF2/External/gameswf/gameswf_dlist.h index eecb2e9f8..be13446b9 100644 --- a/Code/BF2/External/gameswf/gameswf_dlist.h +++ b/Code/BF2/External/gameswf/gameswf_dlist.h @@ -24,12 +24,14 @@ namespace gameswf bool m_ref; smart_ptr m_character; // state is held in here + // SwiffPlayer.dll 0x10071500: unreferenced, null character. display_object_info() : m_ref(false) { } + // SwiffPlayer.dll 0x100A7EB0: copy the flag before acquiring the character. display_object_info(const display_object_info& di) : m_ref(false) @@ -37,16 +39,19 @@ namespace gameswf *this = di; } + // SwiffPlayer.dll 0x10071510 releases only the held character. ~display_object_info() { } + // SwiffPlayer.dll 0x100A7C80: write the flag before replacing the character. void operator=(const display_object_info& di) { m_ref = di.m_ref; m_character = di.m_character; } + // SwiffPlayer.dll 0x100A7CD0. void set_character(character* ch) { m_character = ch; @@ -89,7 +94,7 @@ namespace gameswf const matrix& mat, float ratio, Uint16 clip_depth); - void remove_display_object(Uint16 depth, int id); + void remove_display_object(Uint16 depth); // clear the display list. void clear(); @@ -97,6 +102,11 @@ namespace gameswf // reset the references to the display list. void reset(); + // Movie teardown (release_script_objects): appends every character, removed ones included, to + // *held and empties the list without sending UNLOAD, so no ActionScript runs. + // [CHOSEN, not recovered] issue #7. + void release_characters(array* held); + // remove unreferenced objects. void update(); @@ -107,13 +117,15 @@ namespace gameswf void display(); void display(const display_info& di); - int get_character_count() { return m_display_object_array.size(); } - // [DICE-MOD SwiffPlayer #32: a character whose reference flag is cleared - removed by AS or a + // [INFERRED] Source-level constness of the native read-only accessors. + int get_character_count() const { return m_display_object_array.size(); } + // a character whose reference flag is cleared - removed by AS or a // RemoveObject tag, awaiting the next sweep - is INVISIBLE here, exactly as the shipped // display_list::get_character (sub_10071550: `m_ref ? m_character : 0`). Stock 2006 returned // it, so a `removeMovieClip` + `attachMovie` of the same name resolved the dead clip by name - // for the rest of the frame (the login list's `contents`). Walks must null-check.] - character* get_character(int index) + // for the rest of the frame (the login list's `contents`). Walks must null-check. + // SwiffPlayer.dll 0x10071550. + character* get_character(int index) const { const display_object_info& di = m_display_object_array[index]; return di.m_ref ? di.m_character.get_ptr() : NULL; diff --git a/Code/BF2/External/gameswf/gameswf_font.cpp b/Code/BF2/External/gameswf/gameswf_font.cpp index bfa49501f..c329804dd 100644 --- a/Code/BF2/External/gameswf/gameswf_font.cpp +++ b/Code/BF2/External/gameswf/gameswf_font.cpp @@ -16,6 +16,8 @@ namespace gameswf { + // SwiffPlayer.dll 0x100A14D0. [CHOSEN, not recovered] S3 bridge: + // retain the existing native resource/container layout. font::font() : m_texture_glyph_nominal_size(96), // Default is not important; gets overridden during glyph generation @@ -33,6 +35,7 @@ namespace gameswf { } + // SwiffPlayer.dll 0x100A1580; deleting entry 0x100A1BB0. font::~font() { m_glyphs.resize(0); @@ -45,6 +48,7 @@ namespace gameswf } } + // SwiffPlayer.dll 0x100A0700. shape_character_def* font::get_glyph(int index) const { if (index >= 0 && index < m_glyphs.size()) @@ -58,6 +62,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x100A0E00. const texture_glyph& font::get_texture_glyph(int glyph_index) const // Return a pointer to a texture_glyph struct corresponding to // the given glyph_index, if we have one. Otherwise return NULL. @@ -72,6 +77,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x100A13B0. void font::add_texture_glyph(int glyph_index, const texture_glyph& glyph) // Register some texture info for the glyph at the specified // index. The texture_glyph can be used later to render the @@ -87,6 +93,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x100A0F00. void font::wipe_texture_glyphs() // Delete all our texture glyph info. { @@ -101,6 +108,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x100A1610 (DefineFont and DefineFont2). void font::read(stream* in, int tag_type, movie_definition_sub* m) { assert(tag_type == 10 || tag_type == 48); @@ -290,6 +298,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x100A13D0; both tag 13 and tag 62 call this reader unchanged. void font::read_font_info(stream* in) // Read additional information about this font, from a // DefineFontInfo tag. The caller has already read the tag @@ -298,7 +307,6 @@ namespace gameswf if (m_name) { delete m_name; - m_name = NULL; } m_name = in->read_string_with_length(); @@ -315,6 +323,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x100A0F80. void font::read_code_table(stream* in) // Read the table that maps from glyph indices to character // codes. @@ -341,6 +350,7 @@ namespace gameswf } } + // SwiffPlayer.dll 0x100A1450. int font::get_glyph_index(Uint16 code) const { int glyph_index; @@ -351,29 +361,17 @@ namespace gameswf return -1; } + // SwiffPlayer.dll 0x100A0720; an empty table reports on every call. float font::get_advance(int glyph_index) const { - if (glyph_index == -1) - { - // Default advance. - return 512.0f; - } - if (m_advance_table.size() == 0) { - // No layout info for this font!!! - static bool s_logged = false; - if (s_logged == false) - { - s_logged = true; - log_error("error: empty advance table in font %s\n", get_name()); - } + log_error("error: empty advance table in font\n"); return 0; } if (glyph_index < m_advance_table.size()) { - assert(glyph_index >= 0); return m_advance_table[glyph_index]; } else @@ -385,6 +383,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x100A1480. float font::get_kerning_adjustment(int last_code, int code) const // Return the adjustment in advance between the given two // characters. Normally this will be 0; i.e. the @@ -401,6 +400,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x100A01A0; cached shape output is disabled in retail too. void font::output_cached_data(tu_file* out, const cache_options& options) // Dump our cached data into the given stream. { @@ -423,6 +423,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x100A01B0; cached shape input is disabled in retail too. void font::input_cached_data(tu_file* in) // Read our cached data from the given stream. { diff --git a/Code/BF2/External/gameswf/gameswf_font.h b/Code/BF2/External/gameswf/gameswf_font.h index e20c02f70..0972e0f1f 100644 --- a/Code/BF2/External/gameswf/gameswf_font.h +++ b/Code/BF2/External/gameswf/gameswf_font.h @@ -32,18 +32,27 @@ namespace gameswf rect m_uv_bounds; point m_uv_origin; // the origin of the glyph box, in uv coords + // SwiffPlayer.dll 0x100A0670: retain uninitialized UV bounds and zero the origin. texture_glyph() : m_bitmap_info(NULL) {} + // SwiffPlayer.dll 0x100A4FB0: implicit copy constructs the ref-counted + // base, retains the bitmap, then copies bounds and origin. + // SwiffPlayer.dll 0x100A0690; deleting entry 0x100A06C0. ~texture_glyph() { } + // SwiffPlayer.dll 0x100A0E80: base, bitmap, rectangle, then origin assignment. + texture_glyph& operator=(const texture_glyph&) = default; + + // SwiffPlayer.dll 0x100A4F60. bool is_renderable() const // Return true if this can be used for rendering. { return m_bitmap_info != NULL; } + // SwiffPlayer.dll 0x100A5BB0: identity check, release old, store, retain. void set_bitmap_info(bitmap_info* bi) { m_bitmap_info = bi; @@ -57,6 +66,7 @@ namespace gameswf ~font(); // override from resource. + // SwiffPlayer.dll 0x100A1570. virtual font* cast_to_font() { return this; } int get_glyph_count() const { return m_glyphs.size(); } @@ -75,6 +85,7 @@ namespace gameswf const texture_glyph& get_texture_glyph(int glyph_index) const; void add_texture_glyph(int glyph_index, const texture_glyph& glyph); + // SwiffPlayer.dll 0x100A47C0 / 0x100A47E0. void set_texture_glyph_nominal_size(int size) { m_texture_glyph_nominal_size = imax(1, size); } int get_texture_glyph_nominal_size() const { return m_texture_glyph_nominal_size; } @@ -83,8 +94,9 @@ namespace gameswf float get_kerning_adjustment(int last_code, int this_code) const; // The shipped font stores the DefineFont2 layout triple at +0x38 ascent, +0x3C descent, // +0x40 leading, in that read order (100A1A7D..100A1AAB) - the same order as these three - // members. [DICE-MOD SwiffPlayer #47] corrected the caret, which reads +0x40 (the LEADING); + // members. corrected the caret, which reads +0x40 (the LEADING); // #37 had called that offset the ascent. + // SwiffPlayer.dll 0x10084D60 / 0x10084D70; the fields retain their native offsets. float get_leading() const { return m_leading; } // shipped font +0x40; the text field's caret uses it float get_descent() const { return m_descent; } // shipped font +0x3C float get_ascent() const { return m_ascent; } // shipped font +0x38 @@ -114,6 +126,7 @@ namespace gameswf struct simple_code_hash // Dummy hash functor. { + // SwiffPlayer.dll 0x100A0540 (Uint16 specialization). size_t operator()(const T& data) const { return data; } }; hash > m_code_table; @@ -131,6 +144,7 @@ namespace gameswf { Uint16 m_char0, m_char1; + // SwiffPlayer.dll 0x100A0150. bool operator==(const kerning_pair& k) const { return m_char0 == k.m_char0 && m_char1 == k.m_char1; diff --git a/Code/BF2/External/gameswf/gameswf_fontlib.cpp b/Code/BF2/External/gameswf/gameswf_fontlib.cpp index 16629f616..4895486a0 100644 --- a/Code/BF2/External/gameswf/gameswf_fontlib.cpp +++ b/Code/BF2/External/gameswf/gameswf_fontlib.cpp @@ -6,6 +6,7 @@ // A module to take care of all of gameswf's loaded fonts. +#include #include "base/container.h" #include "base/tu_file.h" #include "gameswf.h" @@ -14,6 +15,7 @@ #include "gameswf_log.h" #include "gameswf_render.h" #include "gameswf_shape.h" +#include "../../Platform/X87Compat.h" #include "gameswf_styles.h" #include "gameswf_tesselate.h" #include "gameswf_render.h" @@ -64,6 +66,7 @@ namespace fontlib static int s_glyph_render_size = s_glyph_nominal_size << OVERSAMPLE_BITS; + // SwiffPlayer.dll 0x100A47F0. void set_nominal_glyph_pixel_size(int pixel_size) { static const int MIN_SIZE = 4; @@ -71,9 +74,11 @@ namespace fontlib if (pixel_size < MIN_SIZE) { - log_error("set_nominal_glyph_pixel_size(%d) too small, clamping to %d\n", - pixel_size, - MIN_SIZE); + // Retail supplies only 4 for the two conversions on this branch. + // Preserve the missing argument; the callback must be disabled to + // exercise this clamp without the shipped formatter's unchecked read. + void (*report)(const char*, ...) = log_error; + report("set_nominal_glyph_pixel_size(%d) too small, clamping to %d\n", MIN_SIZE); pixel_size = MIN_SIZE; } else if (pixel_size > MAX_SIZE) @@ -105,6 +110,10 @@ namespace fontlib int m_glyph_index; texture_glyph m_texture_glyph; + // SwiffPlayer.dll 0x100A64C0: source font, index, then texture glyph. + pending_glyph_info& operator=(const pending_glyph_info&) = default; + + // SwiffPlayer.dll 0x100A4F70; implicit member destruction at 0x100A52B0. pending_glyph_info() : m_source_font(NULL), @@ -128,6 +137,7 @@ namespace fontlib { int m_x_min, m_x_max, m_y_min, m_y_max; + // SwiffPlayer.dll 0x100A4870: four ordered integer stores. recti(int x0 = 0, int x1 = 0, int y0 = 0, int y1 = 0) : m_x_min(x0), @@ -174,6 +184,7 @@ namespace fontlib { int m_x, m_y; + // SwiffPlayer.dll 0x100A48F0. pointi(int x = 0, int y = 0) : m_x(x), @@ -181,6 +192,7 @@ namespace fontlib { } + // SwiffPlayer.dll 0x100A4910. bool operator<(const pointi& p) const // For sorting anchor points. { @@ -197,6 +209,7 @@ namespace fontlib static tu_file* s_file = NULL; + // SwiffPlayer.dll 0x100A66F0. static void ensure_cache_image_available() { if (s_pending_glyphs.size() == 0) @@ -216,6 +229,7 @@ namespace fontlib } + // SwiffPlayer.dll 0x100A6BE0. void finish_current_texture(movie_definition_sub* owner) { if (s_pending_glyphs.size() == 0) @@ -296,6 +310,7 @@ namespace fontlib } + // SwiffPlayer.dll 0x100A5020: reject overflow, then strict rectangle overlaps. bool is_rect_available(const recti& r) // Return true if the given rect can be packed into the // currently active texture. @@ -325,6 +340,7 @@ namespace fontlib } + // SwiffPlayer.dll 0x100A6800. void add_cover_rect(const recti& r) // Add the given rect to our list. Eliminate any anchor // points that are disqualified by this new rect. @@ -344,6 +360,7 @@ namespace fontlib } + // SwiffPlayer.dll 0x100A68C0. void add_anchor_point(const pointi& p) // Add point to our list of anchors. Keep the list sorted. { @@ -367,6 +384,7 @@ namespace fontlib } + // SwiffPlayer.dll 0x100A6950. bool pack_rectangle(int* px, int* py, int width, int height) // Find a spot for the rectangle in the current cache image. // Return true if there's a spot; false if there's no room. @@ -441,6 +459,7 @@ namespace fontlib float m_offset_x; float m_offset_y; + // SwiffPlayer.dll 0x100A4940. rendered_glyph_info() : m_source_font(0), @@ -454,6 +473,7 @@ namespace fontlib }; + // SwiffPlayer.dll 0x100A5140. static void software_trapezoid( float y0, float y1, float xl0, float xl1, @@ -462,18 +482,24 @@ namespace fontlib { assert(s_render_buffer); - int iy0 = (int) ceilf(y0); - int iy1 = (int) ceilf(y1); - float dy = y1 - y0; + int iy0 = bf2x87::toIntTruncate(std::ceil(double(y0))); + int iy1 = bf2x87::toIntTruncate(std::ceil(double(y1))); + float dy = bf2x87::store(bf2x87::sub(bf2x87::Real(y1), bf2x87::Real(y0))); for (int y = iy0; y < iy1; y++) { if (y < 0) continue; if (y >= s_glyph_render_size) return; - float f = (y - y0) / dy; - int xl = (int) ceilf(flerp(xl0, xl1, f)); - int xr = (int) ceilf(flerp(xr0, xr1, f)); + float f = bf2x87::store(bf2x87::div( + bf2x87::sub(bf2x87::Real(y), bf2x87::Real(y0)), bf2x87::Real(dy))); + // Each interpolated edge is stored as double for CRT ceil, not float. + const double left = bf2x87::storeDouble(bf2x87::add(bf2x87::mul( + bf2x87::sub(bf2x87::Real(xl1), bf2x87::Real(xl0)), bf2x87::Real(f)), bf2x87::Real(xl0))); + int xl = bf2x87::toIntTruncate(std::ceil(left)); + const double right = bf2x87::storeDouble(bf2x87::add(bf2x87::mul( + bf2x87::sub(bf2x87::Real(xr1), bf2x87::Real(xr0)), bf2x87::Real(f)), bf2x87::Real(xr0))); + int xr = bf2x87::toIntTruncate(std::ceil(right)); xl = iclamp(xl, 0, s_glyph_render_size - 1); xr = iclamp(xr, 0, s_glyph_render_size - 1); @@ -488,11 +514,13 @@ namespace fontlib } + // Implicit vptr-only constructor: SwiffPlayer.dll 0x100A50A0. struct draw_into_software_buffer : tesselate::trapezoid_accepter // A trapezoid accepter that does B&W rendering into our // software buffer. { // Overrides from trapezoid_accepter + // SwiffPlayer.dll 0x100A50B0: transform right edges before left edges and Y. virtual void accept_trapezoid(int style, const tesselate::trapezoid& tr) { // Transform the coords. @@ -501,17 +529,18 @@ namespace fontlib float x_offset = s_render_matrix.m_[0][2]; float y_offset = s_render_matrix.m_[1][2]; - float y0 = tr.m_y0 * y_scale + y_offset; - float y1 = tr.m_y1 * y_scale + y_offset; - float lx0 = tr.m_lx0 * x_scale + x_offset; - float lx1 = tr.m_lx1 * x_scale + x_offset; - float rx0 = tr.m_rx0 * x_scale + x_offset; - float rx1 = tr.m_rx1 * x_scale + x_offset; + float rx1 = bf2x87::store(bf2x87::add(bf2x87::mul(bf2x87::Real(tr.m_rx1), bf2x87::Real(x_scale)), bf2x87::Real(x_offset))); + float rx0 = bf2x87::store(bf2x87::add(bf2x87::mul(bf2x87::Real(tr.m_rx0), bf2x87::Real(x_scale)), bf2x87::Real(x_offset))); + float lx1 = bf2x87::store(bf2x87::add(bf2x87::mul(bf2x87::Real(tr.m_lx1), bf2x87::Real(x_scale)), bf2x87::Real(x_offset))); + float lx0 = bf2x87::store(bf2x87::add(bf2x87::mul(bf2x87::Real(tr.m_lx0), bf2x87::Real(x_scale)), bf2x87::Real(x_offset))); + float y1 = bf2x87::store(bf2x87::add(bf2x87::mul(bf2x87::Real(tr.m_y1), bf2x87::Real(y_scale)), bf2x87::Real(y_offset))); + float y0 = bf2x87::store(bf2x87::add(bf2x87::mul(bf2x87::Real(tr.m_y0), bf2x87::Real(y_scale)), bf2x87::Real(y_offset))); // Draw into the software buffer. software_trapezoid(y0, y1, lx0, lx1, rx0, rx1); } + // SwiffPlayer.dll 0x100A52A0: release builds discard glyph outlines' line strips. virtual void accept_line_strip(int style, const point coords[], int coord_count) { assert(0); // Shape glyphs should not contain lines. @@ -519,6 +548,7 @@ namespace fontlib }; + // SwiffPlayer.dll 0x100A5C20. static bool render_glyph(rendered_glyph_info* rgi, const shape_character_def* sh) // Render the given outline shape into a cached font texture. // Return true if the glyph is not empty; false if it's @@ -554,12 +584,14 @@ namespace fontlib } s_render_matrix.set_identity(); - s_render_matrix.concatenate_scale(s_glyph_render_size / s_rendering_box); + s_render_matrix.concatenate_scale(bf2x87::store(bf2x87::div( + bf2x87::Real(s_glyph_render_size), bf2x87::Real(s_rendering_box)))); s_render_matrix.concatenate_translation(offset_x, offset_y); // Tesselate & draw the shape. draw_into_software_buffer accepter; - sh->tesselate(s_rendering_box / s_glyph_render_size * 0.5f, &accepter); + sh->tesselate(bf2x87::store(bf2x87::mul(bf2x87::div( + bf2x87::Real(s_rendering_box), bf2x87::Real(s_glyph_render_size)), bf2x87::Real(0.5f))), &accepter); // // Process the results of rendering. @@ -607,8 +639,9 @@ namespace fontlib { // Fill in rendered_glyph_info. rgi->m_image = new image::alpha(max_x - min_x + 1, max_y - min_y + 1); - rgi->m_offset_x = offset_x / s_rendering_box * s_glyph_nominal_size - min_x; - rgi->m_offset_y = offset_y / s_rendering_box * s_glyph_nominal_size - min_y; + const bf2x87::Real scale = bf2x87::div(bf2x87::Real(s_glyph_nominal_size), bf2x87::Real(s_rendering_box)); + rgi->m_offset_x = bf2x87::store(bf2x87::sub(bf2x87::mul(bf2x87::Real(offset_x), scale), bf2x87::Real(min_x))); + rgi->m_offset_y = bf2x87::store(bf2x87::sub(bf2x87::mul(scale, bf2x87::Real(offset_y)), bf2x87::Real(min_y))); // Copy the rendered glyph into the new image. {for (int j = 0, n = rgi->m_image->m_height; j < n; j++) @@ -634,6 +667,7 @@ namespace fontlib + // SwiffPlayer.dll 0x100A6D60. bool try_to_reuse_previous_image( const rendered_glyph_info& rgi, const hash& image_hash) @@ -743,6 +777,7 @@ namespace fontlib } + // SwiffPlayer.dll 0x100A6F30. void pack_and_assign_glyphs(array* glyph_info, movie_definition_sub* owner) // Pack the given glyphs into textures, and push the // texture_glyph info into the source fonts. @@ -753,6 +788,7 @@ namespace fontlib // Sort the glyphs by size (biggest first). struct sorter { + // SwiffPlayer.dll 0x100A4960; images are bounded by the glyph cache size. static int sort_by_size(const void* a, const void* b) // For qsort. { @@ -875,6 +911,7 @@ namespace fontlib } + // SwiffPlayer.dll 0x100A6A40. static void generate_font_bitmaps(array* glyph_info, font* f, movie_definition_sub* owner) // Render images for each of the font's glyphs, and put the // info about them in the given array. @@ -918,12 +955,16 @@ namespace fontlib } + // SwiffPlayer.dll 0x100A4980: divide the nominal size before multiplying by 1024. float get_texture_glyph_max_height(const font* f) { - return 1024.0f / s_rendering_box * f->get_texture_glyph_nominal_size(); // s_glyph_nominal_size; + return bf2x87::store(bf2x87::mul( + bf2x87::div(bf2x87::Real(f->get_texture_glyph_nominal_size()), + bf2x87::Real(s_rendering_box)), bf2x87::Real(1024.0f))); } + // SwiffPlayer.dll 0x100A52E0. static void wipe_font_textures(const array& fonts) { for (int i = 0, n = fonts.size(); i < n; i++) @@ -939,6 +980,7 @@ namespace fontlib // + // SwiffPlayer.dll 0x100A7300. void generate_font_bitmaps(const array& fonts, movie_definition_sub* owner) // Build cached textures from glyph outlines. { @@ -982,6 +1024,7 @@ namespace fontlib } + // SwiffPlayer.dll 0x100A7480. void output_cached_data( tu_file* out, const array& fonts, @@ -1088,6 +1131,8 @@ namespace fontlib } + // SwiffPlayer.dll 0x100A5ED0. [CHOSEN, not recovered] S3 bridge: + // use the native tu_file and typed bitmap/font containers for the retail records. void input_cached_data(tu_file* in, const array& fonts, movie_definition_sub* owner) // Load a stream containing previously-saved font glyph textures. { @@ -1199,18 +1244,7 @@ namespace fontlib tg.m_uv_origin.m_x = in->read_float32(); tg.m_uv_origin.m_y = in->read_float32(); - if (glyph_index < 0 || glyph_index >= fnt->get_glyph_count()) - { - // Cached data doesn't match this font! - log_error("error: invalid glyph index %d in cached font data, limit is %d, font is '%s'\n", - glyph_index, - fnt->get_glyph_count(), - fnt->get_name()); - } - else - { - fnt->add_texture_glyph(glyph_index, tg); - } + fnt->add_texture_glyph(glyph_index, tg); } // Load cached shape data. @@ -1223,6 +1257,7 @@ namespace fontlib } + // SwiffPlayer.dll 0x100A6AE0. void clear() // Release all the fonts we know about. { @@ -1230,6 +1265,7 @@ namespace fontlib } + // SwiffPlayer.dll 0x100A5310. int get_font_count() // Return the number of fonts in our library. { @@ -1237,6 +1273,7 @@ namespace fontlib } + // SwiffPlayer.dll 0x100A5320. font* get_font(int index) // Retrieve one of our fonts, by index. { @@ -1249,6 +1286,7 @@ namespace fontlib } + // SwiffPlayer.dll 0x100A5340: live array bound, null entries skipped, strcmp. font* get_font(const char* name) // Return the named font. { @@ -1268,6 +1306,7 @@ namespace fontlib } + // SwiffPlayer.dll 0x100A49C0. const char* get_font_name(const font* f) // Return the name of the given font. (This basically exists // so that font* can be opaque to the host app). @@ -1280,6 +1319,7 @@ namespace fontlib } + // SwiffPlayer.dll 0x100A6AF0; push_back constructs a temporary strong pointer. void add_font(font* f) // Add the given font to our library. { @@ -1297,6 +1337,7 @@ namespace fontlib } + // SwiffPlayer.dll 0x100A53C0. void draw_glyph(const matrix& mat, const texture_glyph& tg, rgba color, int nominal_glyph_height) // Draw the given texture glyph using the given transform, in // the given color. @@ -1306,19 +1347,20 @@ namespace fontlib // @@ worth it to precompute these bounds? rect bounds = tg.m_uv_bounds; - bounds.m_x_min -= tg.m_uv_origin.m_x; - bounds.m_x_max -= tg.m_uv_origin.m_x; - bounds.m_y_min -= tg.m_uv_origin.m_y; - bounds.m_y_max -= tg.m_uv_origin.m_y; + const bf2x87::Real x_min = bf2x87::sub(bf2x87::Real(bounds.m_x_min), bf2x87::Real(tg.m_uv_origin.m_x)); + const bf2x87::Real x_max = bf2x87::sub(bf2x87::Real(bounds.m_x_max), bf2x87::Real(tg.m_uv_origin.m_x)); + bounds.m_y_min = bf2x87::store(bf2x87::sub(bf2x87::Real(bounds.m_y_min), bf2x87::Real(tg.m_uv_origin.m_y))); + bounds.m_y_max = bf2x87::store(bf2x87::sub(bf2x87::Real(bounds.m_y_max), bf2x87::Real(tg.m_uv_origin.m_y))); // Scale from uv coords to the 1024x1024 glyph square. // @@ need to factor this out! - static float s_scale = GLYPH_CACHE_TEXTURE_SIZE * s_rendering_box / nominal_glyph_height; + static float s_scale = bf2x87::store(bf2x87::div(bf2x87::mul( + bf2x87::Real(s_rendering_box), bf2x87::Real(float(GLYPH_CACHE_TEXTURE_SIZE))), bf2x87::Real(nominal_glyph_height))); - bounds.m_x_min *= s_scale; - bounds.m_x_max *= s_scale; - bounds.m_y_min *= s_scale; - bounds.m_y_max *= s_scale; + bounds.m_x_min = bf2x87::store(bf2x87::mul(bf2x87::Real(s_scale), x_min)); + bounds.m_x_max = bf2x87::store(bf2x87::mul(bf2x87::Real(s_scale), x_max)); + bounds.m_y_min = bf2x87::store(bf2x87::mul(bf2x87::Real(s_scale), bf2x87::Real(bounds.m_y_min))); + bounds.m_y_max = bf2x87::store(bf2x87::mul(bf2x87::Real(s_scale), bf2x87::Real(bounds.m_y_max))); render::draw_bitmap(mat, tg.m_bitmap_info.get_ptr(), bounds, tg.m_uv_bounds, color); } diff --git a/Code/BF2/External/gameswf/gameswf_impl.cpp b/Code/BF2/External/gameswf/gameswf_impl.cpp index 79d582c23..ada9df36c 100644 --- a/Code/BF2/External/gameswf/gameswf_impl.cpp +++ b/Code/BF2/External/gameswf/gameswf_impl.cpp @@ -13,7 +13,13 @@ // @@ Need to break this file into pieces +#include +#include +#include + #include "base/tu_file.h" +#include "../../Core/MsvcCrtCompat.h" // [CHOSEN, not recovered] _snprintf_s/_TRUNCATE outside MSVC +#include "../../Platform/X87Compat.h" #include "base/utility.h" #include "gameswf_action.h" #include "gameswf_button.h" @@ -21,6 +27,7 @@ #include "gameswf_font.h" #include "gameswf_fontlib.h" #include "gameswf_log.h" +#include "gameswf_profile.h" #include "gameswf_morph2.h" #include "gameswf_render.h" #include "gameswf_shape.h" @@ -30,21 +37,83 @@ #include "gameswf_timers.h" #include "base/image.h" #include "base/jpeg.h" -#include "base/zlib_adapter.h" -#include // for memset -#include -#include +#include "base/tu_timer.h" -#if TU_CONFIG_LINK_TO_ZLIB -#include -#endif // TU_CONFIG_LINK_TO_ZLIB namespace gameswf { + // SwiffPlayer.dll 0x100F8CAC; source-level name [INFERRED]. + static smart_ptr s_global_root_movie; + + movie* get_global_root_movie() + { + // SwiffPlayer.dll 0x10071710: borrow the published sprite, without lookup. + return s_global_root_movie.get_ptr(); + } + + void set_global_root_movie(movie* root) + { + // SwiffPlayer.dll 0x100738A0: identity check, release, store, retain. + s_global_root_movie = root; + } + + // SwiffPlayer.dll 0x100F8B78; source-level name [INFERRED]. + static Uint32 s_character_live_count = 0; + + character::character(movie* parent, int id) + : + m_arguments(create_array_object()), + m_id(id), + m_parent(parent), + m_depth(-1), + m_ratio(0.0f), + m_clip_depth(0), + m_visible(true), + m_is_mask_only(false), + m_mouse_enabled(false) + { + assert((parent == NULL && m_id == -1) + || (parent != NULL && m_id >= 0)); + // SwiffPlayer.dll 0x1007EC60 increments after initializing character + // members. Common/embedded-Array construction retains the native S3 bridges. + ++s_character_live_count; + } + + character::~character() + { + // SwiffPlayer.dll 0x1007F0A0 and its inline copy in 0x10089D50 + // decrement before event-handler, name and embedded-Array destruction. + // Native mask/Array ownership and common lifetime remain S3 bridges. + --s_character_live_count; + } + bool s_verbose_action = false; bool s_verbose_parse = false; + // SwiffPlayer.dll 0x1006F120 / 0x1006F130; source-level names [INFERRED]. + bool s_verbose_loader = false; + bool s_verbose_gc = false; + void set_verbose_loader(bool verbose) { s_verbose_loader = verbose; } + void set_verbose_gc(bool verbose) { s_verbose_gc = verbose; } + // SwiffPlayer.dll 0x1006F110 writes the mouse-event verbosity switch. + // No retail caller is known. The event dispatcher reads it at 0x10081650. + static bool s_verbose_mouse_events = false; + void set_verbose_mouse_events(bool verbose) { s_verbose_mouse_events = verbose; } + // SwiffPlayer.dll 0x1006F140; [INFERRED] source-level names. + bool s_profiling = false; + void set_profiling(bool enabled) { s_profiling = enabled; } + + // [INFERRED] source-level type and field names. The registry borrows the + // static records; destroying a record releases its name, without unregistering. + static array s_profile_records; + profile_record::profile_record(const char* name) + : m_count(0), m_ticks(0), m_name(name) + { + s_profile_records.push_back(this); + } + + const array& get_profile_records() { return s_profile_records; } #ifndef NDEBUG bool s_verbose_debug = true; @@ -56,6 +125,7 @@ namespace gameswf void set_verbose_action(bool verbose) // Enable/disable log messages re: actions. { + // SwiffPlayer.dll 0x1006F0F0. s_verbose_action = verbose; } @@ -63,16 +133,21 @@ namespace gameswf void set_verbose_parse(bool verbose) // Enable/disable log messages re: parsing the movie. { + // SwiffPlayer.dll 0x1006F100. s_verbose_parse = verbose; } + // SwiffPlayer.dll 0x1006F0E0; [INFERRED] native name of the placement/removal gate. + void set_verbose_debug(bool verbose) { s_verbose_debug = verbose; } + static bool s_use_cache_files = true; void set_use_cache_files(bool use_cache) // Enable/disable attempts to read cache files when loading // movies. { + // SwiffPlayer.dll 0x1006F150 stores the initially true byte; name [INFERRED]. s_use_cache_files = use_cache; } @@ -80,6 +155,7 @@ namespace gameswf // Keep a table of loader functions for the different tag types. static hash s_tag_loaders; + // SwiffPlayer.dll 0x10073220. void register_tag_loader(int tag_type, loader_function lf) // Associate the specified tag type with the given tag loader // function. @@ -101,31 +177,20 @@ namespace gameswf // Host calls this to register a function for opening files, // for loading movies. { + // SwiffPlayer.dll 0x1006F160; 0x1006F386 / 0x1007D3C6 use this opener. s_opener_function = opener; } - // - // progress callback stuff (from Vitaly) - // - - static progress_callback s_progress_function = NULL; - - void register_progress_callback(progress_callback progress_handle) - // Host calls this to register a function for progress bar handling - // during loading movies. - { - s_progress_function = progress_handle; - } - // // some utility stuff // - // [DICE-MOD SwiffPlayer #48] execute_actions (index walk over the live list) is gone: its + // execute_actions (index walk over the live list) is gone: its // only caller, sprite_instance::do_actions, now drains the list the way the shipped body does. + // SwiffPlayer.dll 0x1006F170. static void dump_tag_bytes(stream* in) // Log the contents of the current tag, in hex. { @@ -167,6 +232,8 @@ namespace gameswf } + // SwiffPlayer.dll 0x1007F2C0. [CHOSEN, not recovered] S3 bridge: + // the native factory hands its borrowed raw result to the caller's smart_ptr. character* character_def::create_character_instance(movie* parent, int id) // Default. Make a generic_character. { @@ -179,6 +246,7 @@ namespace gameswf // + // SwiffPlayer.dll 0x1006F240. ref_counted::ref_counted() : m_ref_count(0), @@ -186,6 +254,7 @@ namespace gameswf { } + // SwiffPlayer.dll 0x1006F260; deleting entry 0x10071570. ref_counted::~ref_counted() { assert(m_ref_count == 0); @@ -197,12 +266,14 @@ namespace gameswf } } + // SwiffPlayer.dll 0x1006F290. void ref_counted::add_ref() const { assert(m_ref_count >= 0); m_ref_count++; } + // SwiffPlayer.dll 0x1006F2A0; character secondary entry 0x1007EFF0. void ref_counted::drop_ref() const { assert(m_ref_count > 0); @@ -214,6 +285,7 @@ namespace gameswf } } + // SwiffPlayer.dll 0x1006F2C0: allocate and retain one proxy on first request. weak_proxy* ref_counted::get_weak_proxy() const { assert(m_ref_count > 0); // By rights, somebody should be holding a ref to us. @@ -236,50 +308,47 @@ namespace gameswf void character::do_mouse_drag() // Implement mouse-dragging for this movie. { - drag_state st; + // SwiffPlayer.dll 0x10073250. + drag_state st; get_drag_state(&st); if (this == st.m_character) { - // We're being dragged! - int x, y, buttons; + int x, y, buttons; get_root_movie()->get_mouse_state(&x, &y, &buttons); - - point world_mouse(PIXELS_TO_TWIPS(x), PIXELS_TO_TWIPS(y)); - if (st.m_bound) - { - // Clamp mouse coords within a defined rect. - world_mouse.m_x = - fclamp(world_mouse.m_x, st.m_bound_x0, st.m_bound_x1); - world_mouse.m_y = - fclamp(world_mouse.m_y, st.m_bound_y0, st.m_bound_y1); - } - + point world_mouse(float(x) * 20.0f, float(y) * 20.0f); + matrix parent_world; if (st.m_lock_center) { - matrix world_mat = get_world_matrix(); - point local_mouse; - world_mat.transform_by_inverse(&local_mouse, world_mouse); - - matrix parent_world_mat; - if (m_parent) + if (st.m_bound) { - parent_world_mat = m_parent->get_world_matrix(); + world_mouse.m_x = fclamp(world_mouse.m_x, st.m_bound_x0, st.m_bound_x1); + world_mouse.m_y = fclamp(world_mouse.m_y, st.m_bound_y0, st.m_bound_y1); } - - point parent_mouse; - parent_world_mat.transform_by_inverse(&parent_mouse, world_mouse); - - // Place our origin so that it coincides with the mouse coords - // in our parent frame. - matrix local = get_matrix(); - local.m_[0][2] = parent_mouse.m_x; - local.m_[1][2] = parent_mouse.m_y; - set_matrix(local); + matrix world = get_world_matrix(); + point local_mouse; + world.transform_by_inverse(&local_mouse, world_mouse); + if (m_parent) parent_world = m_parent->get_world_matrix(); } else { - // Implement relative drag... + matrix world = get_world_matrix(); + point local_mouse; + world.transform_by_inverse(&local_mouse, world_mouse); + if (m_parent) parent_world = m_parent->get_world_matrix(); + world_mouse.m_x -= st.m_offset_x; + world_mouse.m_y -= st.m_offset_y; + if (st.m_bound) + { + world_mouse.m_x = fclamp(world_mouse.m_x, st.m_bound_x0, st.m_bound_x1); + world_mouse.m_y = fclamp(world_mouse.m_y, st.m_bound_y0, st.m_bound_y1); + } } + point parent_mouse; + parent_world.transform_by_inverse(&parent_mouse, world_mouse); + matrix local = get_matrix(); + local.m_[0][2] = parent_mouse.m_x; + local.m_[1][2] = parent_mouse.m_y; + set_matrix(local); } } @@ -327,9 +396,13 @@ namespace gameswf hash > m_bitmap_characters; hash > m_sound_samples; array > m_playlist; // A list of movie control events for each frame. - array > m_init_action_list; // Init actions for each frame. + array m_init_action_list; + // [CHOSEN, not recovered] S3 bridge: retail stores the pending bit + // in each action_buffer; the native do_action wrapper owns that buffer. + array m_init_action_pending; stringi_hash m_named_frames; // 0-based frame #'s stringi_hash > m_exports; + hash m_export_names; // Items we import. array m_imports; @@ -349,11 +422,16 @@ namespace gameswf int m_frame_count; int m_version; int m_loading_frame; + // [UNRESOLVED] Retail +0x88 starts at 1000 (0x1007807D), separately + // from the file header's length. [INFERRED] word name and unsigned type. + Uint32 m_retail_word_88; uint32 m_file_length; jpeg::input* m_jpeg_in; + // SwiffPlayer.dll 0x10077FB0; native containers/virtual bases supply + // the empty inherited and owned storage without retail x86 offsets. movie_def_impl(create_bitmaps_flag cbf, create_font_shapes_flag cfs) : m_create_bitmaps(cbf), @@ -362,12 +440,23 @@ namespace gameswf m_frame_count(0), m_version(0), m_loading_frame(0), + m_retail_word_88(1000), m_jpeg_in(0) { + // SwiffPlayer.dll 0x10077FB0 zeroes +0x08..+0x34. A movie definition has no definition ID + // (it is not a character_def); see sprite_definition_of for the reads that land there. } ~movie_def_impl() { + // SwiffPlayer.dll 0x1007CE20 (deleting entry 0x1007CDE0) + // deletes init actions before frame tags, rechecking the init count. + // [CHOSEN, not recovered] S3 bridge: native execute_tag wrappers own the buffers. + {for (int i = 0; i < m_init_action_list.size(); i++) + { + delete m_init_action_list[i]; + }} + // Release our playlist data. {for (int i = 0, n = m_playlist.size(); i < n; i++) { @@ -377,15 +466,6 @@ namespace gameswf } }} - // Release init action data. - {for (int i = 0, n = m_init_action_list.size(); i < n; i++) - { - for (int j = 0, m = m_init_action_list[i].size(); j < m; j++) - { - delete m_init_action_list[i][j]; - } - }} - assert(m_jpeg_in == NULL); // It's supposed to be cleaned up in read() } @@ -393,18 +473,34 @@ namespace gameswf movie_interface* create_instance(); // ... + // SwiffPlayer.dll 0x100780A0. int get_frame_count() const { return m_frame_count; } + // SwiffPlayer.dll 0x100780B0. float get_frame_rate() const { return m_frame_rate; } - float get_width_pixels() const { return ceilf(TWIPS_TO_PIXELS(m_frame_size.width())); } - float get_height_pixels() const { return ceilf(TWIPS_TO_PIXELS(m_frame_size.height())); } + // SwiffPlayer.dll 0x100780C0. + float get_width_pixels() const + { + return static_cast(ceil(bf2x87::storeDouble(bf2x87::mul( + bf2x87::sub(bf2x87::Real(m_frame_size.m_x_max), bf2x87::Real(m_frame_size.m_x_min)), + bf2x87::Real(0.05f))))); + } + // SwiffPlayer.dll 0x100780E0. + float get_height_pixels() const + { + return static_cast(ceil(bf2x87::storeDouble(bf2x87::mul( + bf2x87::sub(bf2x87::Real(m_frame_size.m_y_max), bf2x87::Real(m_frame_size.m_y_min)), + bf2x87::Real(0.05f))))); + } + // SwiffPlayer.dll 0x10078100. virtual int get_version() const { return m_version; } + // SwiffPlayer.dll 0x10078110. virtual int get_loading_frame() const { return m_loading_frame; } uint32 get_file_bytes() const { return m_file_length; } - /* movie_def_impl */ + // SwiffPlayer.dll 0x10078120. virtual create_bitmaps_flag get_create_bitmaps() const // Returns DO_CREATE_BITMAPS if we're supposed to // initialize our bitmap infos, or DO_NOT_INIT_BITMAPS @@ -415,7 +511,7 @@ namespace gameswf return m_create_bitmaps; } - /* movie_def_impl */ + // SwiffPlayer.dll 0x10078130. virtual create_font_shapes_flag get_create_font_shapes() const // Returns DO_LOAD_FONT_SHAPES if we're supposed to // initialize our font shape info, or @@ -426,6 +522,7 @@ namespace gameswf return m_create_font_shapes; } + // SwiffPlayer.dll 0x100781B0. virtual void add_bitmap_info(bitmap_info* bi) // All bitmap_info's used by this movie should be // registered with this API. @@ -434,9 +531,9 @@ namespace gameswf } - // [DICE-MOD SwiffPlayer: walk m_exports, keeping the entries whose resource is a bitmap + // walk m_exports, keeping the entries whose resource is a bitmap // character. The NAME is the ExportAssets symbol, which for BF2's menu bitmaps is the - // external image path. See gameswf.h and GAMESWF_DIVERGENCES.md.] + // external image path. See gameswf.h and GAMESWF_DIVERGENCES.md. virtual int get_exported_bitmaps(int max, tu_string* names, gameswf::bitmap_info** infos) const { @@ -458,40 +555,43 @@ namespace gameswf return n; } - // [DICE-MOD SwiffPlayer #37] see gameswf_impl.h. + // SwiffPlayer.dll 0x10078260, definition vtable +0x3C. + virtual bool get_export_name(int id, tu_string* out) + { + return m_export_names.get(id, out); + } + + // [CHOSEN, not recovered] S3 bridge: legacy pointer-to-ID query, + // retained until the swf-text-font-id menu validation gate. virtual bool get_exported_font_name(const font* f, tu_string* out) { - if (f == NULL || f->get_name() == NULL) return false; - for (stringi_hash >::const_iterator it = m_exports.begin(); - it != m_exports.end(); ++it) + for (hash >::const_iterator it = m_fonts.begin(); + it != m_fonts.end(); ++it) { - resource* res = it.get_value().get_ptr(); - if (res == NULL) continue; - font* ef = res->cast_to_font(); - if (ef == NULL || ef->get_name() == NULL) continue; - if (strcmp(ef->get_name(), f->get_name()) == 0) - { - *out = it.get_key(); - return true; - } + if (it->second.get_ptr() == f) return get_export_name(it->first, out); } return false; } + // SwiffPlayer.dll 0x10078170. virtual int get_bitmap_info_count() const { return m_bitmap_list.size(); } + // SwiffPlayer.dll 0x10078180. virtual bitmap_info* get_bitmap_info(int i) const { return m_bitmap_list[i].get_ptr(); } - virtual void export_resource(const tu_string& symbol, resource* res) + // SwiffPlayer.dll 0x10079FF0 stores both symbol-to-resource and ID-to-name. + virtual void export_resource(int id, const tu_string& symbol, resource* res) // Expose one of our resources under the given symbol, // for export. Other movies can import it. { // SWF sometimes exports the same thing more than once! m_exports.set(symbol, res); + m_export_names.set(id, symbol); } + // SwiffPlayer.dll 0x10079D50. virtual smart_ptr get_exported_resource(const tu_string& symbol) // Get the named exported resource, if we expose it. // Otherwise return NULL. @@ -501,6 +601,24 @@ namespace gameswf return res; } + virtual void release_registered_classes() + // [CHOSEN, not recovered] issue #7: Object.registerClass binds through the exports only. + { + for (stringi_hash >::iterator it = m_exports.begin(); it != m_exports.end(); ++it) + { + character_def* cdef = it->second != NULL ? it->second->cast_to_character_def() : NULL; + if (cdef != NULL && cdef->m_registered_class != NULL) + { + cdef->m_registered_class->drop_ref(); + cdef->m_registered_class = NULL; + } + } + // [CHOSEN, not recovered] issue #7: the cached definition must + // initialize the next movie's script classes after action_clear(). + for (int i = 0; i < m_init_action_pending.size(); ++i) m_init_action_pending[i] = true; + } + + // SwiffPlayer.dll 0x100794C0. virtual void add_import(const char* source_url, int id, const char* symbol) // Adds an entry to a table of resources that need to // be imported from other movies. Client code must @@ -527,6 +645,8 @@ namespace gameswf return false; } + // SwiffPlayer.dll 0x1007A480: snapshot the count, visit once per URL, + // and record the URL only after its callback returns. virtual void visit_imported_movies(import_visitor* visitor) // Calls back the visitor for each movie that we // import symbols from. @@ -545,6 +665,7 @@ namespace gameswf } } + // SwiffPlayer.dll 0x10079560 removes matching imports even on refusal. virtual void resolve_import(const char* source_url, movie_definition* source_movie) // Grabs the stuff we want from the source movie. { @@ -598,12 +719,14 @@ namespace gameswf } } + // SwiffPlayer.dll 0x100782A0. void add_character(int character_id, character_def* c) { assert(c); m_characters.add(character_id, c); } + // SwiffPlayer.dll 0x100784F0, definition vtable +0x40. character_def* get_character_def(int character_id) { #ifndef NDEBUG @@ -621,18 +744,21 @@ namespace gameswf return ch.get_ptr(); } + // SwiffPlayer.dll 0x10079F20. bool get_labeled_frame(const char* label, int* frame_number) // Returns 0-based frame # { return m_named_frames.get(label, frame_number); } + // SwiffPlayer.dll 0x100785E0. void add_font(int font_id, font* f) { assert(f); m_fonts.add(font_id, f); } + // SwiffPlayer.dll 0x10078830. font* get_font(int font_id) { #ifndef NDEBUG @@ -650,6 +776,7 @@ namespace gameswf return f.get_ptr(); } + // SwiffPlayer.dll 0x10078920. bitmap_character_def* get_bitmap_character(int character_id) { smart_ptr ch; @@ -658,6 +785,7 @@ namespace gameswf return ch.get_ptr(); } + // SwiffPlayer.dll 0x10078A10. void add_bitmap_character(int character_id, bitmap_character_def* ch) { assert(ch); @@ -666,6 +794,7 @@ namespace gameswf add_bitmap_info(ch->get_bitmap_info()); } + // SwiffPlayer.dll 0x10078C20. sound_sample* get_sound_sample(int character_id) { smart_ptr ch; @@ -674,28 +803,29 @@ namespace gameswf return ch.get_ptr(); } + // SwiffPlayer.dll 0x10078D50. virtual void add_sound_sample(int character_id, sound_sample* sam) { assert(sam); m_sound_samples.add(character_id, sam); } + // SwiffPlayer.dll 0x10078F50. void add_execute_tag(execute_tag* e) { assert(e); m_playlist[m_loading_frame].push_back(e); } - void add_init_action(int sprite_id, execute_tag* e) - // Need to execute the given tag before entering the - // currently-loading frame for the first time. - // - // @@ AFAIK, the sprite_id is totally pointless -- correct? + // SwiffPlayer.dll 0x10078F90 appends to one definition-wide list. + void add_init_action(execute_tag* e) { assert(e); - m_init_action_list[m_loading_frame].push_back(e); + m_init_action_list.push_back(e); + m_init_action_pending.push_back(true); } + // SwiffPlayer.dll 0x10079F90. void add_frame_name(const char* name) // Labels the frame currently being loaded with the // given name. A copy of the name string is made and @@ -708,6 +838,7 @@ namespace gameswf m_named_frames.add(n, m_loading_frame); // stores 0-based frame # } + // SwiffPlayer.dll 0x10078140. void set_jpeg_loader(jpeg::input* j_in) // Set an input object for later loading DefineBits // images (JPEG images without the table info). @@ -716,6 +847,7 @@ namespace gameswf m_jpeg_in = j_in; } + // SwiffPlayer.dll 0x10078150. jpeg::input* get_jpeg_loader() // Get the jpeg input loader, to load a DefineBits // image (one without table info). @@ -724,15 +856,16 @@ namespace gameswf } + // SwiffPlayer.dll 0x10078190. virtual const array& get_playlist(int frame_number) { return m_playlist[frame_number]; } - /* movie_def_impl */ + // SwiffPlayer.dll 0x10078160 returns the entire init-action list. virtual const array* get_init_actions(int frame_number) { - return &m_init_action_list[frame_number]; + return &m_init_action_list; } - /* movie_def_impl */ + // SwiffPlayer.dll 0x1007AA80. Font-name aliases are built after all tags. void read(tu_file* in) // Read a .SWF movie. { @@ -753,24 +886,11 @@ namespace gameswf IF_VERBOSE_PARSE(log_msg("version = %d, file_length = %d\n", m_version, m_file_length)); - tu_file* original_in = NULL; if (compressed) { -#if TU_CONFIG_LINK_TO_ZLIB == 0 log_error("movie_def_impl::read(): unable to read zipped SWF data; TU_CONFIG_LINK_TO_ZLIB is 0\n"); return; -#endif - - IF_VERBOSE_PARSE(log_msg("file is compressed.\n")); - original_in = in; - - // Uncompress the input as we read it. - in = zlib_adapter::make_inflater(original_in); - // Subtract the size of the 8-byte header, since - // it's not included in the compressed - // stream length. - file_end_pos = m_file_length - 8; } stream str(in); @@ -780,7 +900,6 @@ namespace gameswf m_frame_count = str.read_u16(); m_playlist.resize(m_frame_count); - m_init_action_list.resize(m_frame_count); IF_VERBOSE_PARSE(m_frame_size.print()); IF_VERBOSE_PARSE(log_msg("frame rate = %f, frames = %d\n", m_frame_rate, m_frame_count)); @@ -789,17 +908,11 @@ namespace gameswf { int tag_type = str.open_tag(); - if (s_progress_function != NULL) - { - s_progress_function((Uint32) str.get_position(), file_end_pos); - } - loader_function lf = NULL; - //IF_VERBOSE_PARSE(log_msg("tag_type = %d\n", tag_type)); + IF_VERBOSE_PARSE(log_msg("tag_type = %d\n", tag_type)); if (tag_type == 1) { // show frame tag -- advance to the next frame. - IF_VERBOSE_PARSE(log_msg(" show_frame\n")); m_loading_frame++; } else if (s_tag_loaders.get(tag_type, &lf)) @@ -829,28 +942,45 @@ namespace gameswf } } + stringi_hash exported_font_ids; + for (hash >::iterator it = m_fonts.begin(); + it != m_fonts.end(); ++it) + { + tu_string name; + if (get_export_name(it->first, &name)) + { + exported_font_ids.set(it->second->get_name(), it->first); + } + } + for (hash >::iterator it = m_fonts.begin(); + it != m_fonts.end(); ++it) + { + tu_string name; + if (!get_export_name(it->first, &name)) + { + int exported_id; + if (exported_font_ids.get(it->second->get_name(), &exported_id)) + { + get_export_name(exported_id, &name); + m_export_names.set(it->first, name); + } + } + } + if (m_jpeg_in) { delete m_jpeg_in; m_jpeg_in = NULL; } - if (original_in) - { - // Done with the zlib_adapter. - delete in; - } } - /* movie_def_impl */ + // SwiffPlayer.dll 0x100798E0 appends owned fonts in dictionary order. void get_owned_fonts(array* fonts) // Fill up *fonts with fonts that we own. { assert(fonts); - fonts->resize(0); - - array font_ids; for (hash >::iterator it = m_fonts.begin(); it != m_fonts.end(); @@ -859,28 +989,13 @@ namespace gameswf font* f = it->second.get_ptr(); if (f->get_owning_movie() == this) { - // Sort by character id, so the ordering is - // consistent for cache read/write. - int id = it->first; - - // Insert in correct place. - int insert; - for (insert = 0; insert < font_ids.size(); insert++) - { - if (font_ids[insert] > id) - { - // We want to insert here. - break; - } - } - fonts->insert(insert, f); - font_ids.insert(insert, id); + fonts->push_back(f); } } } - /* movie_def_impl */ + // SwiffPlayer.dll 0x100797E0. void generate_font_bitmaps() // Generate bitmaps for our fonts, if necessary. { @@ -892,10 +1007,11 @@ namespace gameswf // Increment this when the cache data format changes. - #define CACHE_FILE_VERSION 4 + // SwiffPlayer.dll 0x100799BA and 0x10079C0F use version 3. + #define CACHE_FILE_VERSION 3 - /* movie_def_impl */ + // SwiffPlayer.dll 0x10079990. void output_cached_data(tu_file* out, const cache_options& options) // Dump our cached data into the given stream. { @@ -925,7 +1041,7 @@ namespace gameswf } - /* movie_def_impl */ + // SwiffPlayer.dll 0x10079BD0. void input_cached_data(tu_file* in) // Read in cached data and use it to prime our loaded characters. { @@ -991,6 +1107,10 @@ namespace gameswf // Global, shared root state for a movie and all its characters. // + // SwiffPlayer.dll 0x10073560 / 0x10075370. [CHOSEN, not recovered] + // S3 bridge: the native root owns its movie per tree, in place of the retail + // global. Userdata and initialized drag offsets + // remain native extensions; this class does not reproduce the x86 layout. struct movie_root : public movie_interface { smart_ptr m_def; @@ -1004,14 +1124,11 @@ namespace gameswf void * m_userdata; movie::drag_state m_drag_state; // @@ fold this into m_mouse_button_state? mouse_button_state m_mouse_button_state; + // SwiffPlayer.dll: non-owning +0x34 + // capture pointer (0x10073560, 0x1007FBF0, 0x1007FC00). + movie* m_active_mouse_entity = NULL; bool m_on_event_load_called; - // Flags for event handlers - bool m_on_event_xmlsocket_ondata_called; - bool m_on_event_xmlsocket_onxml_called; - bool m_on_event_load_progress_called; - array m_interval_timers; - movie_root(movie_def_impl* def) : m_def(def), @@ -1027,19 +1144,27 @@ namespace gameswf m_mouse_y(0), m_mouse_buttons(0), m_userdata(NULL), - m_on_event_load_called(false), - m_on_event_xmlsocket_ondata_called(false), - m_on_event_xmlsocket_onxml_called(false), - m_on_event_load_progress_called(false) + m_on_event_load_called(false) { assert(m_def != NULL); - set_display_viewport(0, 0, (int) m_def->get_width_pixels(), (int) m_def->get_height_pixels()); + // SwiffPlayer.dll 0x10073560 reads height before width, with + // truncating dword conversions before setting the viewport. + movie_def_impl* const definition = m_def.get_ptr(); + const int height = bf2x87::toIntTruncate(definition->get_height_pixels()); + const int width = bf2x87::toIntTruncate(definition->get_width_pixels()); + set_display_viewport(0, 0, width, height); } + // SwiffPlayer.dll 0x10075370 / deleting entry 0x10075340: + // release the movie before the definition, through the native owners above. ~movie_root() { assert(m_def != NULL); + // [CHOSEN, not recovered] S3 bridge to issue #7: the native + // wrapper also owns its sprite. Drop the published root before that + // wrapper dies, without clearing a newer movie's publication. + if (get_global_root_movie() == m_movie.get_ptr()) set_global_root_movie(NULL); m_movie = NULL; m_def = NULL; } @@ -1056,6 +1181,7 @@ namespace gameswf assert(m_movie != NULL); } + // SwiffPlayer.dll 0x100716B0. void set_display_viewport(int x0, int y0, int w, int h) { m_viewport_x0 = x0; @@ -1064,12 +1190,17 @@ namespace gameswf m_viewport_height = h; // Recompute pixel scale. - float scale_x = m_viewport_width / TWIPS_TO_PIXELS(m_def->m_frame_size.width()); - float scale_y = m_viewport_height / TWIPS_TO_PIXELS(m_def->m_frame_size.height()); - m_pixel_scale = fmax(scale_x, scale_y); + const bf2x87::Real scale_x = bf2x87::div(bf2x87::Real(m_viewport_width), + bf2x87::mul(bf2x87::sub(bf2x87::Real(m_def->m_frame_size.m_x_max), + bf2x87::Real(m_def->m_frame_size.m_x_min)), bf2x87::Real(0.05f))); + const float scale_y = bf2x87::store(bf2x87::div(bf2x87::Real(m_viewport_height), + bf2x87::mul(bf2x87::sub(bf2x87::Real(m_def->m_frame_size.m_y_max), + bf2x87::Real(m_def->m_frame_size.m_y_min)), bf2x87::Real(0.05f)))); + m_pixel_scale = bf2x87::less(scale_x, bf2x87::Real(scale_y)) ? scale_y : bf2x87::store(scale_x); } + // SwiffPlayer.dll 0x10073670. void notify_mouse_state(int x, int y, int buttons) // The host app uses this to tell the movie where the // user's mouse pointer is. @@ -1079,6 +1210,7 @@ namespace gameswf m_mouse_buttons = buttons; } + // SwiffPlayer.dll 0x10073690. virtual void get_mouse_state(int* x, int* y, int* buttons) // Use this to retrieve the last state of the mouse, as set via // notify_mouse_state(). Coordinates are in PIXELS, NOT TWIPS. @@ -1092,20 +1224,22 @@ namespace gameswf *buttons = m_mouse_buttons; } - // [DICE-MOD SwiffPlayer #51] the shipped root's +0xB4 / +0xB8: the character holding the - // pointer since its press. A weak reference, as the stock active entity was. - movie* get_active_entity() { smart_ptr p(m_mouse_button_state.m_active_entity); return p.get_ptr(); } - void set_active_entity(movie* m) { m_mouse_button_state.m_active_entity = m; } + // Capture since the press. Retail 0x1007FBF0/0x1007FC00 reads/writes a raw + // pointer in movie_root. + movie* get_active_entity() { return m_active_mouse_entity; } + void set_active_entity(movie* m) { m_active_mouse_entity = m; } movie* get_root_movie() { return m_movie.get_ptr(); } + // SwiffPlayer.dll 0x1007FD00 reaches this record through the sprite's root. void stop_drag() { m_drag_state.m_character = NULL; } + // SwiffPlayer.dll 0x10073770; native per-tree root delegate. movie_definition* get_movie_definition() { return m_movie->get_movie_definition(); } uint32 get_file_bytes() const @@ -1113,29 +1247,12 @@ namespace gameswf return m_def->get_file_bytes(); } - virtual int add_interval_timer(void *timer) - { - Timer *ptr = static_cast(timer); - - m_interval_timers.push_back(ptr); - return m_interval_timers.size(); - } - - virtual void clear_interval_timer(int x) - { - m_interval_timers.remove(x-1); - //m_interval_timers[x]->clearInterval(); - } - - virtual void do_something(void *timer) - { - log_msg("FIXME: %s: unimplemented\n", __FUNCTION__); - } - + // SwiffPlayer.dll 0x10073780. // 0-based!! int get_current_frame() const { return m_movie->get_current_frame(); } float get_frame_rate() const { return m_def->get_frame_rate(); } + // SwiffPlayer.dll 0x100736B0. virtual float get_pixel_scale() const // Return the size of a logical movie pixel as // displayed on-screen, with the current device @@ -1150,34 +1267,40 @@ namespace gameswf return m_movie->get_character(character_id); } + // SwiffPlayer.dll 0x100736D0. void set_background_color(const rgba& color) { m_background_color = color; } - // [DICE-MOD SwiffPlayer: the shipped getter (sub_100736C0) - see gameswf.h.] + // SwiffPlayer.dll 0x100736C0; the native API copies the stored color. rgba get_background_color() const { return m_background_color; } + // SwiffPlayer.dll 0x100736E0. void set_background_alpha(float alpha) { - m_background_color.m_a = iclamp(frnd(alpha * 255.0f), 0, 255); + const float rounded = bf2x87::store(bf2x87::add( + bf2x87::mul(bf2x87::Real(alpha), bf2x87::Real(255.0f)), bf2x87::Real(0.5f))); + m_background_color.m_a = iclamp(bf2x87::toIntTruncate(rounded), 0, 255); } + // SwiffPlayer.dll 0x10073720. float get_background_alpha() const { - return m_background_color.m_a / 255.0f; + return m_background_color.m_a * (1.0f / 255.0f); } float get_timer() const { return m_timer; } + // SwiffPlayer.dll 0x10073790. Root delegates use the native per-tree + // owner in place of retail's global root [CHOSEN, not recovered] S3 bridge. void restart() { m_movie->restart(); } void advance(float delta_time) { - int i; if (m_on_event_load_called == false) { // Must do loading events. For child sprites this is @@ -1186,53 +1309,44 @@ namespace gameswf m_on_event_load_called = true; m_movie->on_event_load(); } -#if 0 - // Must check the socket connection for data - if (m_on_event_xmlsocket_ondata_called == true) { - m_movie->on_event_xmlsocket_ondata(); - } - - if (m_on_event_xmlsocket_onxml_called == true) { - m_movie->on_event_xmlsocket_onxml(); - } - - - // Must check the progress of the MovieClip being loaded - if (m_on_event_load_progress_called == true) { - m_movie->on_event_load_progress(); - } -#endif - if (m_interval_timers.size() > 0) { - for (i=0; iexpired()) { - // printf("FIXME: Interval Timer Expired!\n"); - //m_movie->on_event_interval_timer(); - m_movie->do_something(m_interval_timers[i]); - // clear_interval_timer(m_interval_timers[i]->getIntervalID()); // FIXME: we shouldn't really disable the timer here - } - } + // SwiffPlayer.dll 0x1007AED0 calls 0x10077910 before mouse input + // and before adding delta_time to the movie clock. + if (s_profiling) + { + static profile_record counter("updateIntervals"); + counter.begin(); + update_intervals(m_timer); + counter.end(); } + else update_intervals(m_timer); - m_timer += delta_time; // @@ TODO handle multi-frame catch-up stuff // here, and make it optional. Make // movie::advance() a fixed framerate w/ no // dt. - // Handle the mouse. [DICE-MOD SwiffPlayer #51] one recursive pass down the tree, every + // Handle the mouse. one recursive pass down the tree, every // character its own state machine (sprite 0x10080010, text 0x10088650, button 0x100A3020). // Stock 2006 picked a single "topmost entity" here and fed generate_mouse_button_events. m_movie->mouse_update(false); + // SwiffPlayer.dll 0x1007AED0 calls the + // mouse pass before incrementing the movie clock, then advances the timeline. + m_timer += delta_time; m_movie->advance(delta_time); } // 0-based!! - void goto_frame(int target_frame_number) { m_movie->goto_frame(target_frame_number); } + // SwiffPlayer.dll 0x100737A0 calls primary +0x18 (0x100822A0), + // distinct from the sprite's secondary numeric queue entry. + void goto_frame(int target_frame_number); + // SwiffPlayer.dll 0x100737B0. virtual bool has_looped() const { return m_movie->has_looped(); } + // SwiffPlayer.dll 0x10075160. The per-tree movie is the existing + // [CHOSEN, not recovered] S3 bridge for retail's global root. void display() { if (m_movie->get_visible() == false) @@ -1248,72 +1362,90 @@ namespace gameswf m_def->m_frame_size.m_x_min, m_def->m_frame_size.m_x_max, m_def->m_frame_size.m_y_min, m_def->m_frame_size.m_y_max); - m_movie->display(); + if (s_profiling) + { + static profile_record counter("display"); + // The timer abstraction uses QueryPerformanceCounter on Windows, + // as retail 0x100D0BA0 does. Its existing POSIX clock backend is + // [CHOSEN, not recovered] platform policy; counters stay in ticks. + counter.m_start = tu_timer::get_profile_ticks(); + m_movie->display(); + counter.m_ticks += tu_timer::get_profile_ticks() - counter.m_start; + ++counter.m_count; + } + else + { + m_movie->display(); + } gameswf::render::end_display(); } virtual bool goto_labeled_frame(const char* label) { - // [DICE-MOD SwiffPlayer #45] a label applies at once on the root sprite too (the - // numeric goto_frame above is the deferred form). - return m_movie->goto_labeled_frame(label); + // SwiffPlayer.dll 0x100737C0 resolves against the root definition. + int frame = -1; + if (m_def->get_labeled_frame(label, &frame)) + { + goto_frame(frame); + return true; + } + log_error("error: movie_impl::goto_labeled_frame('%s') unknown label\n", label); + return false; } + // SwiffPlayer.dll 0x10073810. virtual void set_play_state(play_state s) { m_movie->set_play_state(s); } + // SwiffPlayer.dll 0x10073820. virtual play_state get_play_state() const { return m_movie->get_play_state(); } /* movie_root */ + // SwiffPlayer.dll 0x10073830. virtual void set_variable(const char* path_to_var, const char* new_value) { m_movie->set_variable(path_to_var, new_value); } /* movie_root */ + // SwiffPlayer.dll 0x10073840. virtual void set_variable(const char* path_to_var, const wchar_t* new_value) { m_movie->set_variable(path_to_var, new_value); } + // SwiffPlayer.dll 0x10073850. virtual const char* get_variable(const char* path_to_var) const { return m_movie->get_variable(path_to_var); } /*movie_root*/ - // For ActionScript interfacing convenience. - virtual const char* call_method(const char* method_name, const char* method_arg_fmt, ...) + // SwiffPlayer.dll 0x10073870 / 0x10073860 forward one command string. + // [CHOSEN, not recovered] S3 bridge: the native instance owns its root + // instead of dispatching through retail's process-global root pointer. + const char* call_method(const Uint16* expression) override { - assert(m_movie != NULL); - - va_list args; - va_start(args, method_arg_fmt); - const char* result = m_movie->call_method_args(method_name, method_arg_fmt, args); - va_end(args); - - return result; + return m_movie->call_method(expression); } - - /*movie_root*/ - virtual const char* call_method_args(const char* method_name, const char* method_arg_fmt, va_list args) + const char* call_method(const char* expression) override { - assert(m_movie != NULL); - return m_movie->call_method_args(method_name, method_arg_fmt, args); + return m_movie->call_method(expression); } + // SwiffPlayer.dll 0x10073880 / 0x10073890. virtual void set_visible(bool visible) { m_movie->set_visible(visible); } virtual bool get_visible() const { return m_movie->get_visible(); } + // SwiffPlayer.dll 0x10073750 / 0x10073760. virtual void * get_userdata() { return m_userdata; } virtual void set_userdata(void * ud ) { m_userdata = ud; } - virtual void attach_display_callback(const char* path_to_object, void (*callback)(void* user_ptr), void* user_ptr) - { - m_movie->attach_display_callback(path_to_object, callback, user_ptr); - } }; + static void define_font_info_2_loader(stream* in, int tag_type, movie_definition_sub* m); + + // SwiffPlayer.dll 0x1007CF60. static void ensure_loaders_registered() { static bool s_registered = false; @@ -1325,7 +1457,6 @@ namespace gameswf register_tag_loader(0, end_loader); register_tag_loader(2, define_shape_loader); register_tag_loader(4, place_object_2_loader); - register_tag_loader(5, remove_object_2_loader); register_tag_loader(6, define_bits_jpeg_loader); register_tag_loader(7, button_character_loader); register_tag_loader(8, jpeg_tables_loader); @@ -1356,11 +1487,14 @@ namespace gameswf register_tag_loader(56, export_loader); register_tag_loader(57, import_loader); register_tag_loader(59, do_init_action_loader); + register_tag_loader(62, define_font_info_2_loader); } } + // SwiffPlayer.dll 0x1006F380. + // [CHOSEN, not recovered] The host still uses the extra native tag-count output. void get_movie_info( const char* filename, int* version, @@ -1407,22 +1541,10 @@ namespace gameswf } bool compressed = (header & 255) == 'C'; - tu_file* original_in = NULL; if (compressed) { -#if TU_CONFIG_LINK_TO_ZLIB == 0 log_error("get_movie_info(): can't read zipped SWF data; TU_CONFIG_LINK_TO_ZLIB is 0!\n"); return; -#endif - original_in = in; - - // Uncompress the input as we read it. - in = zlib_adapter::make_inflater(original_in); - - // Subtract the size of the 8-byte header, since - // it's not included in the compressed - // stream length. - file_length -= 8; } stream str(in); @@ -1434,8 +1556,12 @@ namespace gameswf int local_frame_count = str.read_u16(); if (version) *version = local_version; - if (width) *width = int(frame_size.width() / 20.0f + 0.5f); - if (height) *height = int(frame_size.height() / 20.0f + 0.5f); + if (width) *width = bf2x87::toIntTruncate( + bf2x87::add(bf2x87::mul(bf2x87::sub(bf2x87::Real(frame_size.m_x_max), + bf2x87::Real(frame_size.m_x_min)), bf2x87::Real(0.05f)), bf2x87::Real(0.5f))); + if (height) *height = bf2x87::toIntTruncate( + bf2x87::add(bf2x87::mul(bf2x87::sub(bf2x87::Real(frame_size.m_y_max), + bf2x87::Real(frame_size.m_y_min)), bf2x87::Real(0.05f)), bf2x87::Real(0.5f))); if (frames_per_second) *frames_per_second = local_frame_rate; if (frame_count) *frame_count = local_frame_count; @@ -1453,12 +1579,11 @@ namespace gameswf } delete in; - delete original_in; } - // [DICE-MOD SwiffPlayer: see gameswf.h. Default preserves stock behaviour.] + // see gameswf.h. Default preserves stock behaviour. static create_bitmaps_flag s_default_create_bitmaps = DO_LOAD_BITMAPS; void set_default_create_bitmaps(create_bitmaps_flag cbf) @@ -1466,6 +1591,7 @@ namespace gameswf s_default_create_bitmaps = cbf; } + // SwiffPlayer.dll 0x1007E010: tail entry to create_movie_sub. movie_definition* create_movie(const char* filename) // Create the movie definition from the specified .swf file. { @@ -1473,6 +1599,8 @@ namespace gameswf } + // SwiffPlayer.dll 0x1007D3C0. The default bitmap policy remains a native + // [CHOSEN, not recovered] S3 bridge; retail constructs both load flags as zero. movie_definition_sub* create_movie_sub(const char* filename) { if (s_opener_function == NULL) @@ -1497,7 +1625,7 @@ namespace gameswf ensure_loaders_registered(); - // [DICE-MOD SwiffPlayer: was hardcoded DO_LOAD_BITMAPS - see set_default_create_bitmaps.] + // was hardcoded DO_LOAD_BITMAPS - see set_default_create_bitmaps. movie_def_impl* m = new movie_def_impl(s_default_create_bitmaps, DO_LOAD_FONT_SHAPES); m->read(in); @@ -1515,7 +1643,8 @@ namespace gameswf // Can't open cache file; don't sweat it. IF_VERBOSE_PARSE(log_msg("note: couldn't open cache file '%s'\n", cache_filename.c_str())); - m->generate_font_bitmaps(); // can't read cache, so generate font texture data. + // SwiffPlayer.dll 0x1007D4BA..0x1007D4DC only reports a + // missing cache; it does not generate font textures here. } else { @@ -1534,6 +1663,7 @@ namespace gameswf static bool s_no_recurse_while_loading = false; // @@ TODO get rid of this; make it the normal mode. + // SwiffPlayer.dll 0x1007D520. movie_definition* create_movie_no_recurse( tu_file* in, create_bitmaps_flag cbf, @@ -1565,6 +1695,8 @@ namespace gameswf // For built-in sprite ActionScript methods. as_object* s_sprite_builtins = 0; // shared among all sprites. + // SwiffPlayer.dll 0x1007FB20 / 0x10084B60; source-level name [INFERRED]. + static Uint32 s_sprite_live_count = 0; static void sprite_builtins_init(); static void sprite_builtins_clear(); @@ -1591,6 +1723,21 @@ namespace gameswf static tu_string s_workdir; + void release_library_classes() + // [CHOSEN, not recovered] issue #7: movie teardown, see release_script_objects. The library + // keeps its definitions for the next player; their class bindings belong to the released + // movie, and a stale class's constructor would run in an environment that no longer exists. + { + for (stringi_hash< smart_ptr >::iterator it = s_movie_library.begin(); it != s_movie_library.end(); ++it) + { + if (it->second != NULL) + { + it->second->release_registered_classes(); + } + } + } + + // SwiffPlayer.dll 0x10075440 appends a borrowed external-movie pointer. void save_extern_movie(movie_interface* m) { s_extern_sprites.push_back(m); @@ -1615,18 +1762,23 @@ namespace gameswf } //#endif // 0 + // SwiffPlayer.dll 0x1006F560. movie_interface* get_current_root() { assert(s_current_root != NULL); return s_current_root; } + // SwiffPlayer.dll 0x1006F570. void set_current_root(movie_interface* m) { assert(m != NULL); s_current_root = m; } + // SwiffPlayer.dll 0x1006F580 / 0x1006F590. + // [CHOSEN, not recovered] S3 bridge: native string storage replaces the + // retail fixed buffer; callers still borrow it until the next assignment. const char* get_workdir() { return s_workdir.c_str(); @@ -1642,6 +1794,7 @@ namespace gameswf // Drop all library references to movie_definitions, so they // can be cleaned up. { + // SwiffPlayer.dll 0x10076700 clears definitions before instances. s_movie_library.clear(); s_movie_library_inst.clear(); } @@ -1681,6 +1834,7 @@ namespace gameswf // } + // SwiffPlayer.dll 0x1007E020: tail entry to create_library_movie_sub. movie_definition* create_library_movie(const char* filename) // Try to load a movie from the given url, if we haven't // loaded it already. Add it to our library on success, and @@ -1690,6 +1844,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x1007D580. movie_definition_sub* create_library_movie_sub(const char* filename) { tu_string fn(filename); @@ -1729,6 +1884,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x10075470; forwarding entry 0x10076720. movie_interface* create_library_movie_inst_sub(movie_definition_sub* md) { // Is the movie instance already in the library? @@ -1762,6 +1918,8 @@ namespace gameswf } + // SwiffPlayer.dll 0x10071720; the handler save/restore helpers are + // 0x1006F5B0 / 0x1006F5E0. void precompute_cached_data(movie_definition* movie_def) // Fill in cached data in movie_def. // @@@@ NEEDS TESTING -- MIGHT BE BROKEN!!! @@ -1778,6 +1936,7 @@ namespace gameswf render_handler* m_original_rh; sound_handler* m_original_sh; + // SwiffPlayer.dll 0x1006F5B0. save_stuff() { // Save. @@ -1787,6 +1946,7 @@ namespace gameswf set_sound_handler(NULL); } + // SwiffPlayer.dll 0x1006F5E0. ~save_stuff() { // Restore. @@ -1825,7 +1985,9 @@ namespace gameswf m->advance(0.010f); m->display(); - if (m->get_current_frame() == movie_def->get_frame_count() - 1) + // SwiffPlayer.dll 0x100717A5 / 0x10071839 queries the definition first. + const int frame_count = movie_def->get_frame_count(); + if (m->get_current_frame() == frame_count - 1) { // Done. break; @@ -1866,11 +2028,13 @@ namespace gameswf // + // SwiffPlayer.dll 0x1006F600 is an empty tag loader. void null_loader(stream* in, int tag_type, movie_definition_sub* m) // Silently ignore the contents of this tag. { } + // SwiffPlayer.dll 0x1006F610. void frame_label_loader(stream* in, int tag_type, movie_definition_sub* m) // Label the current frame of m with the name from the stream. { @@ -1881,30 +2045,36 @@ namespace gameswf struct set_background_color : public execute_tag { + // SwiffPlayer.dll 0x10071900: implicit destruction has no owned members. + // SwiffPlayer.dll 0x10071890: implicit rgba construction sets every component to 255. rgba m_color; + // SwiffPlayer.dll 0x100718B0 stores once after multiply and add, + // then truncates the float argument and keeps its low byte. void execute(movie* m) { float current_alpha = m->get_background_alpha(); - m_color.m_a = frnd(current_alpha * 255.0f); + const float rounded = bf2x87::store(bf2x87::add( + bf2x87::mul(bf2x87::Real(current_alpha), bf2x87::Real(255.0f)), bf2x87::Real(0.5f))); + m_color.m_a = static_cast(bf2x87::toIntTruncate(rounded)); m->set_background_color(m_color); } + // SwiffPlayer.dll 0x100718F0. void execute_state(movie* m) { execute(m); } + // SwiffPlayer.dll 0x1006F640. void read(stream* in) { m_color.read_rgb(in); - - IF_VERBOSE_PARSE(log_msg(" set_background_color: (%d %d %d)\n", - m_color.m_r, m_color.m_g, m_color.m_b)); } }; + // SwiffPlayer.dll 0x100738F0. void set_background_color_loader(stream* in, int tag_type, movie_definition_sub* m) { assert(tag_type == 9); @@ -1952,21 +2122,31 @@ namespace gameswf }; #endif + // SwiffPlayer.dll 0x1006F660 is empty in the shipped JPEG-disabled build. void jpeg_tables_loader(stream* in, int tag_type, movie_definition_sub* m) // Load JPEG compression tables that can be used to load // images further along in the stream. { assert(tag_type == 8); -#if TU_CONFIG_LINK_TO_JPEGLIB - jpeg::input* j_in = jpeg::input::create_swf_jpeg2_header_only(in->get_underlying_stream()); - assert(j_in); - - m->set_jpeg_loader(j_in); -#endif // TU_CONFIG_LINK_TO_JPEGLIB } + // SwiffPlayer.dll 0x10073A50/0x10073B80/0x10073C60/0x10073D40. + // These loaders create a named-host-image descriptor without decoding payloads. + static bitmap_character* make_movie_bitmap_character(int id) + { + named_bitmap_info* bi = new named_bitmap_info; + bi->m_texture_id = static_cast(-1); + bi->m_original_width = 256; + bi->m_original_height = 256; + bitmap_character* ch = new bitmap_character(bi); + // [CHOSEN, not recovered] S3 bridge: native constructor ID adapter. + ch->set_character_id(id); + return ch; + } + + // SwiffPlayer.dll 0x10073A50. void define_bits_jpeg_loader(stream* in, int tag_type, movie_definition_sub* m) // A JPEG image without included tables; those should be in an // existing jpeg::input object stored in the movie. @@ -1975,131 +2155,26 @@ namespace gameswf Uint16 character_id = in->read_u16(); - // - // Read the image data. - // - bitmap_info* bi = NULL; - - if (m->get_create_bitmaps() == DO_LOAD_BITMAPS) - { -#if TU_CONFIG_LINK_TO_JPEGLIB - jpeg::input* j_in = m->get_jpeg_loader(); - assert(j_in); - j_in->discard_partial_buffer(); - - image::rgb* im = image::read_swf_jpeg2_with_tables(j_in); - bi = render::create_bitmap_info_rgb(im); - delete im; -#else - log_error("gameswf is not linked to jpeglib -- can't load jpeg image data!\n"); - bi = render::create_bitmap_info_empty(); -#endif - } - else - { - bi = render::create_bitmap_info_empty(); - } - - assert(bi->get_ref_count() == 0); - - bitmap_character* ch = new bitmap_character(bi); - - m->add_bitmap_character(character_id, ch); + m->add_bitmap_character(character_id, make_movie_bitmap_character(character_id)); } + // SwiffPlayer.dll 0x10073B80. void define_bits_jpeg2_loader(stream* in, int tag_type, movie_definition_sub* m) { assert(tag_type == 21); Uint16 character_id = in->read_u16(); - IF_VERBOSE_PARSE(log_msg(" define_bits_jpeg2_loader: charid = %d pos = 0x%x\n", character_id, in->get_position())); - - // - // Read the image data. - // - - bitmap_info* bi = NULL; - - if (m->get_create_bitmaps() == DO_LOAD_BITMAPS) - { -#if TU_CONFIG_LINK_TO_JPEGLIB - image::rgb* im = image::read_swf_jpeg2(in->get_underlying_stream()); - bi = render::create_bitmap_info_rgb(im); - delete im; -#else - log_error("gameswf is not linked to jpeglib -- can't load jpeg image data!\n"); - bi = render::create_bitmap_info_empty(); -#endif - } - else - { - bi = render::create_bitmap_info_empty(); - } - - assert(bi->get_ref_count() == 0); - - bitmap_character* ch = new bitmap_character(bi); + IF_VERBOSE_PARSE(log_msg("define_bits_jpeg2_loader: charid = %d pos = 0x%x\n", character_id, in->get_position())); - m->add_bitmap_character(character_id, ch); + m->add_bitmap_character(character_id, make_movie_bitmap_character(character_id)); } -#if TU_CONFIG_LINK_TO_ZLIB - void inflate_wrapper(tu_file* in, void* buffer, int buffer_bytes) - // Wrapper function -- uses Zlib to uncompress in_bytes worth - // of data from the input file into buffer_bytes worth of data - // into *buffer. - { - assert(in); - assert(buffer); - assert(buffer_bytes > 0); - - int err; - z_stream d_stream; /* decompression stream */ - - d_stream.zalloc = (alloc_func)0; - d_stream.zfree = (free_func)0; - d_stream.opaque = (voidpf)0; - - d_stream.next_in = 0; - d_stream.avail_in = 0; - - d_stream.next_out = (Byte*) buffer; - d_stream.avail_out = (uInt) buffer_bytes; - - err = inflateInit(&d_stream); - if (err != Z_OK) { - log_error("error: inflate_wrapper() inflateInit() returned %d\n", err); - return; - } - - Uint8 buf[1]; - - for (;;) { - // Fill a one-byte (!) buffer. - buf[0] = in->read_byte(); - d_stream.next_in = &buf[0]; - d_stream.avail_in = 1; - - err = inflate(&d_stream, Z_SYNC_FLUSH); - if (err == Z_STREAM_END) break; - if (err != Z_OK) - { - log_error("error: inflate_wrapper() inflate() returned %d\n", err); - } - } - - err = inflateEnd(&d_stream); - if (err != Z_OK) - { - log_error("error: inflate_wrapper() inflateEnd() return %d\n", err); - } - } -#endif // TU_CONFIG_LINK_TO_ZLIB + // SwiffPlayer.dll 0x10073C60. void define_bits_jpeg3_loader(stream* in, int tag_type, movie_definition_sub* m) // loads a define_bits_jpeg3 tag. This is a jpeg file with an alpha // channel using zlib compression. @@ -2108,339 +2183,60 @@ namespace gameswf Uint16 character_id = in->read_u16(); - IF_VERBOSE_PARSE(log_msg(" define_bits_jpeg3_loader: charid = %d pos = 0x%x\n", character_id, in->get_position())); - - Uint32 jpeg_size = in->read_u32(); - Uint32 alpha_position = in->get_position() + jpeg_size; - - bitmap_info* bi = NULL; - - if (m->get_create_bitmaps() == DO_LOAD_BITMAPS) - { -#if TU_CONFIG_LINK_TO_JPEGLIB == 0 || TU_CONFIG_LINK_TO_ZLIB == 0 - log_error("gameswf is not linked to jpeglib/zlib -- can't load jpeg/zipped image data!\n"); - bi = render::create_bitmap_info_empty(); -#else - // - // Read the image data. - // - - // Read rgb data. - image::rgba* im = image::read_swf_jpeg3(in->get_underlying_stream()); - - // Read alpha channel. - in->set_position(alpha_position); - - int buffer_bytes = im->m_width * im->m_height; - Uint8* buffer = new Uint8[buffer_bytes]; - - inflate_wrapper(in->get_underlying_stream(), buffer, buffer_bytes); - - for (int i = 0; i < buffer_bytes; i++) - { - im->m_data[4*i+3] = buffer[i]; - } - - delete [] buffer; - - bi = render::create_bitmap_info_rgba(im); - - delete im; -#endif - - } - else - { - bi = render::create_bitmap_info_empty(); - } - - // Create bitmap character. - bitmap_character* ch = new bitmap_character(bi); + IF_VERBOSE_PARSE(log_msg("define_bits_jpeg3_loader: charid = %d pos = 0x%x\n", character_id, in->get_position())); - m->add_bitmap_character(character_id, ch); + m->add_bitmap_character(character_id, make_movie_bitmap_character(character_id)); } + // SwiffPlayer.dll 0x10073D40. void define_bits_lossless_2_loader(stream* in, int tag_type, movie_definition_sub* m) { assert(tag_type == 20 || tag_type == 36); Uint16 character_id = in->read_u16(); - Uint8 bitmap_format = in->read_u8(); // 3 == 8 bit, 4 == 16 bit, 5 == 32 bit - Uint16 width = in->read_u16(); - Uint16 height = in->read_u16(); - - IF_VERBOSE_PARSE(log_msg(" defbitslossless2: tag_type = %d, id = %d, fmt = %d, w = %d, h = %d\n", - tag_type, - character_id, - bitmap_format, - width, - height)); - - bitmap_info* bi = NULL; - if (m->get_create_bitmaps() == DO_LOAD_BITMAPS) - { -#if TU_CONFIG_LINK_TO_ZLIB == 0 - log_error("gameswf is not linked to zlib -- can't load zipped image data!\n"); - return; -#else - if (tag_type == 20) - { - // RGB image data. - image::rgb* image = image::create_rgb(width, height); + m->add_bitmap_character(character_id, make_movie_bitmap_character(character_id)); + } - if (bitmap_format == 3) - { - // 8-bit data, preceded by a palette. - const int bytes_per_pixel = 1; - int color_table_size = in->read_u8(); - color_table_size += 1; // !! SWF stores one less than the actual size + // SwiffPlayer.dll 0x1006F670. + void define_shape_loader(stream* in, int tag_type, movie_definition_sub* m) + { + assert(tag_type == 2 + || tag_type == 22 + || tag_type == 32); - int pitch = (width * bytes_per_pixel + 3) & ~3; + Uint16 character_id = in->read_u16(); + shape_character_def* ch = new shape_character_def; + // [CHOSEN, not recovered] S3 bridge: the native constructor has + // no ID argument; retain retail's definition ID before reading. + ch->set_character_id(character_id); + ch->read(in, tag_type, true, m); - int buffer_bytes = color_table_size * 3 + pitch * height; - Uint8* buffer = new Uint8[buffer_bytes]; + IF_VERBOSE_PARSE(log_msg("shape_loader: id = %d, rect ", character_id); ch->get_bound().print()); - inflate_wrapper(in->get_underlying_stream(), buffer, buffer_bytes); - assert(in->get_position() <= in->get_tag_end_position()); + m->add_character(character_id, ch); + } - Uint8* color_table = buffer; + // SwiffPlayer.dll 0x1006F700. + void define_shape_morph_loader(stream* in, int tag_type, movie_definition_sub* m) + { + assert(tag_type == 46); + Uint16 character_id = in->read_u16(); + IF_VERBOSE_PARSE(log_msg("shape_morph_loader: id = %d\n", character_id)); + morph2_character_def* morph = new morph2_character_def; + // [CHOSEN, not recovered] S3 bridge: constructor ID adapter, as above. + morph->set_character_id(character_id); + morph->read(in, tag_type, true, m); + m->add_character(character_id, morph); + } - for (int j = 0; j < height; j++) - { - Uint8* image_in_row = buffer + color_table_size * 3 + j * pitch; - Uint8* image_out_row = image::scanline(image, j); - for (int i = 0; i < width; i++) - { - Uint8 pixel = image_in_row[i * bytes_per_pixel]; - image_out_row[i * 3 + 0] = color_table[pixel * 3 + 0]; - image_out_row[i * 3 + 1] = color_table[pixel * 3 + 1]; - image_out_row[i * 3 + 2] = color_table[pixel * 3 + 2]; - } - } - - delete [] buffer; - } - else if (bitmap_format == 4) - { - // 16 bits / pixel - const int bytes_per_pixel = 2; - int pitch = (width * bytes_per_pixel + 3) & ~3; - - int buffer_bytes = pitch * height; - Uint8* buffer = new Uint8[buffer_bytes]; - - inflate_wrapper(in->get_underlying_stream(), buffer, buffer_bytes); - assert(in->get_position() <= in->get_tag_end_position()); - - for (int j = 0; j < height; j++) - { - Uint8* image_in_row = buffer + j * pitch; - Uint8* image_out_row = image::scanline(image, j); - for (int i = 0; i < width; i++) - { - Uint16 pixel = image_in_row[i * 2] | (image_in_row[i * 2 + 1] << 8); - - // @@ How is the data packed??? I'm just guessing here that it's 565! - image_out_row[i * 3 + 0] = (pixel >> 8) & 0xF8; // red - image_out_row[i * 3 + 1] = (pixel >> 3) & 0xFC; // green - image_out_row[i * 3 + 2] = (pixel << 3) & 0xF8; // blue - } - } - - delete [] buffer; - } - else if (bitmap_format == 5) - { - // 32 bits / pixel, input is ARGB format (???) - const int bytes_per_pixel = 4; - int pitch = width * bytes_per_pixel; - - int buffer_bytes = pitch * height; - Uint8* buffer = new Uint8[buffer_bytes]; - - inflate_wrapper(in->get_underlying_stream(), buffer, buffer_bytes); - assert(in->get_position() <= in->get_tag_end_position()); - - // Need to re-arrange ARGB into RGB. - for (int j = 0; j < height; j++) - { - Uint8* image_in_row = buffer + j * pitch; - Uint8* image_out_row = image::scanline(image, j); - for (int i = 0; i < width; i++) - { - Uint8 a = image_in_row[i * 4 + 0]; - Uint8 r = image_in_row[i * 4 + 1]; - Uint8 g = image_in_row[i * 4 + 2]; - Uint8 b = image_in_row[i * 4 + 3]; - image_out_row[i * 3 + 0] = r; - image_out_row[i * 3 + 1] = g; - image_out_row[i * 3 + 2] = b; - a = a; // Inhibit warning. - } - } - - delete [] buffer; - } - -// bitmap_character* ch = new bitmap_character(image); - bi = render::create_bitmap_info_rgb(image); - delete image; - -// // add image to movie, under character id. -// m->add_bitmap_character(character_id, ch); - } - else - { - // RGBA image data. - assert(tag_type == 36); - - image::rgba* image = image::create_rgba(width, height); - - if (bitmap_format == 3) - { - // 8-bit data, preceded by a palette. - - const int bytes_per_pixel = 1; - int color_table_size = in->read_u8(); - color_table_size += 1; // !! SWF stores one less than the actual size - - int pitch = (width * bytes_per_pixel + 3) & ~3; - - int buffer_bytes = color_table_size * 4 + pitch * height; - Uint8* buffer = new Uint8[buffer_bytes]; - - inflate_wrapper(in->get_underlying_stream(), buffer, buffer_bytes); - assert(in->get_position() <= in->get_tag_end_position()); - - Uint8* color_table = buffer; - - for (int j = 0; j < height; j++) - { - Uint8* image_in_row = buffer + color_table_size * 4 + j * pitch; - Uint8* image_out_row = image::scanline(image, j); - for (int i = 0; i < width; i++) - { - Uint8 pixel = image_in_row[i * bytes_per_pixel]; - image_out_row[i * 4 + 0] = color_table[pixel * 4 + 0]; - image_out_row[i * 4 + 1] = color_table[pixel * 4 + 1]; - image_out_row[i * 4 + 2] = color_table[pixel * 4 + 2]; - image_out_row[i * 4 + 3] = color_table[pixel * 4 + 3]; - } - } - - delete [] buffer; - } - else if (bitmap_format == 4) - { - // 16 bits / pixel - const int bytes_per_pixel = 2; - int pitch = (width * bytes_per_pixel + 3) & ~3; - - int buffer_bytes = pitch * height; - Uint8* buffer = new Uint8[buffer_bytes]; - - inflate_wrapper(in->get_underlying_stream(), buffer, buffer_bytes); - assert(in->get_position() <= in->get_tag_end_position()); - - for (int j = 0; j < height; j++) - { - Uint8* image_in_row = buffer + j * pitch; - Uint8* image_out_row = image::scanline(image, j); - for (int i = 0; i < width; i++) - { - Uint16 pixel = image_in_row[i * 2] | (image_in_row[i * 2 + 1] << 8); - - // @@ How is the data packed??? I'm just guessing here that it's 565! - image_out_row[i * 4 + 0] = 255; // alpha - image_out_row[i * 4 + 1] = (pixel >> 8) & 0xF8; // red - image_out_row[i * 4 + 2] = (pixel >> 3) & 0xFC; // green - image_out_row[i * 4 + 3] = (pixel << 3) & 0xF8; // blue - } - } - - delete [] buffer; - } - else if (bitmap_format == 5) - { - // 32 bits / pixel, input is ARGB format - - inflate_wrapper(in->get_underlying_stream(), image->m_data, width * height * 4); - assert(in->get_position() <= in->get_tag_end_position()); - - // Need to re-arrange ARGB into RGBA. - for (int j = 0; j < height; j++) - { - Uint8* image_row = image::scanline(image, j); - for (int i = 0; i < width; i++) - { - Uint8 a = image_row[i * 4 + 0]; - Uint8 r = image_row[i * 4 + 1]; - Uint8 g = image_row[i * 4 + 2]; - Uint8 b = image_row[i * 4 + 3]; - image_row[i * 4 + 0] = r; - image_row[i * 4 + 1] = g; - image_row[i * 4 + 2] = b; - image_row[i * 4 + 3] = a; - } - } - } - - bi = render::create_bitmap_info_rgba(image); -// bitmap_character* ch = new bitmap_character(image); - delete image; - -// // add image to movie, under character id. -// m->add_bitmap_character(character_id, ch); - } -#endif // TU_CONFIG_LINK_TO_ZLIB - } - else - { - bi = render::create_bitmap_info_empty(); - } - assert(bi->get_ref_count() == 0); - - bitmap_character* ch = new bitmap_character(bi); - - // add image to movie, under character id. - m->add_bitmap_character(character_id, ch); - } - - - void define_shape_loader(stream* in, int tag_type, movie_definition_sub* m) - { - assert(tag_type == 2 - || tag_type == 22 - || tag_type == 32); - - Uint16 character_id = in->read_u16(); - IF_VERBOSE_PARSE(log_msg(" shape_loader: id = %d\n", character_id)); - - shape_character_def* ch = new shape_character_def; - ch->read(in, tag_type, true, m); - - IF_VERBOSE_PARSE(log_msg(" bound rect:"); ch->get_bound().print()); - - m->add_character(character_id, ch); - } - - void define_shape_morph_loader(stream* in, int tag_type, movie_definition_sub* m) - { - assert(tag_type == 46); - Uint16 character_id = in->read_u16(); - IF_VERBOSE_PARSE(log_msg(" shape_morph_loader: id = %d\n", character_id)); - morph2_character_def* morph = new morph2_character_def; - morph->read(in, tag_type, true, m); - m->add_character(character_id, morph); - } - - // - // font loaders - // + // + // font loaders + // + // SwiffPlayer.dll 0x1006F780. void define_font_loader(stream* in, int tag_type, movie_definition_sub* m) // Load a DefineFont or DefineFont2 tag. { @@ -2460,6 +2256,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x1006F7E0. void define_font_info_loader(stream* in, int tag_type, movie_definition_sub* m) // Load a DefineFontInfo tag. This adds information to an // existing font. @@ -2479,6 +2276,23 @@ namespace gameswf } } + // SwiffPlayer.dll 0x1006F820 uses the same reader as tag 13, including + // its lack of a separate language-byte read for DefineFontInfo2. + static void define_font_info_2_loader(stream* in, int tag_type, movie_definition_sub* m) + { + assert(tag_type == 62); + const Uint16 font_id = in->read_u16(); + font* f = m->get_font(font_id); + if (f) + { + f->read_font_info(in); + } + else + { + log_error("define_font_info_2_loader: can't find font w/ id %d\n", font_id); + } + } + // // swf_event @@ -2501,11 +2315,13 @@ namespace gameswf { } + // SwiffPlayer.dll 0x1007B470; event IDs retain the S2 mapping. void attach_to(character* ch) const { ch->set_event_handler(m_event, m_method); } + // SwiffPlayer.dll 0x10073E00. void read(stream* in, Uint32 flags) { assert(flags != 0); @@ -2519,9 +2335,9 @@ namespace gameswf "unexpected! flags = 0x%x\n", flags); } - // 14 bits reserved, 18 bits used - - static const event_id s_code_bits[19] = + // [CHOSEN, not recovered] S2 bridge: native event IDs differ; + // retain the shipped 21-entry bit mapping using the native names. + static const event_id s_code_bits[21] = { event_id::LOAD, event_id::ENTER_FRAME, @@ -2541,7 +2357,9 @@ namespace gameswf event_id::DRAG_OVER, event_id::DRAG_OUT, event_id::KEY_PRESS, // bit 17 (still unhandled below) - event_id::CONSTRUCT, // bit 18 [DICE-MOD SwiffPlayer #27] + event_id::CONSTRUCT, // bit 18 + event_id::DOUBLE_PRESS, + event_id::INVALID, }; for (int i = 0, mask = 1; i < int(sizeof(s_code_bits)/sizeof(s_code_bits[0])); i++, mask <<= 1) @@ -2576,6 +2394,8 @@ namespace gameswf // Create a function to execute the actions. array empty_with_stack; + // [CHOSEN, not recovered] S3 bridge: the native function + // constructor carries the extra (empty) with-stack parameter. as_as_function* func = new as_as_function(&m_action_buffer, NULL, 0, empty_with_stack); func->set_length(m_action_buffer.get_length()); @@ -2595,6 +2415,8 @@ namespace gameswf struct place_object_2 : public execute_tag { + // [CHOSEN, not recovered] S3 bridge for 2006 reverse-tag APIs; + // retail 0x10076760 does not retain the input tag number. int m_tag_type; char* m_name; float m_ratio; @@ -2613,6 +2435,7 @@ namespace gameswf array m_event_handlers; + // SwiffPlayer.dll 0x100755E0; m_tag_type is the native bridge above. place_object_2() : m_tag_type(0), @@ -2627,6 +2450,7 @@ namespace gameswf { } + // SwiffPlayer.dll 0x1007B4C0; deleting veneer 0x1007B490. ~place_object_2() { delete [] m_name; @@ -2639,6 +2463,7 @@ namespace gameswf m_event_handlers.resize(0); } + // SwiffPlayer.dll 0x10076760. void read(stream* in, int tag_type, int movie_version) { assert(tag_type == 4 || tag_type == 26); @@ -2652,18 +2477,9 @@ namespace gameswf m_depth = in->read_u16(); m_matrix.read(in); - IF_VERBOSE_PARSE( - log_msg(" char_id = %d\n" - " depth = %d\n" - " mat = \n", - m_character_id, - m_depth); - m_matrix.print()); - if (in->get_position() < in->get_tag_end_position()) { m_color_transform.read_rgb(in); - IF_VERBOSE_PARSE(log_msg(" cxform:\n"); m_color_transform.print()); } } else if (tag_type == 26) @@ -2680,36 +2496,30 @@ namespace gameswf bool flag_move = in->read_uint(1) ? true : false; m_depth = in->read_u16(); - IF_VERBOSE_PARSE(log_msg(" depth = %d\n", m_depth)); if (has_char) { m_character_id = in->read_u16(); - IF_VERBOSE_PARSE(log_msg(" char id = %d\n", m_character_id)); } if (has_matrix) { m_has_matrix = true; m_matrix.read(in); - IF_VERBOSE_PARSE(log_msg(" mat:\n"); m_matrix.print()); } if (has_cxform) { m_has_cxform = true; m_color_transform.read_rgba(in); - IF_VERBOSE_PARSE(log_msg(" cxform:\n"); m_color_transform.print()); } if (has_ratio) { - m_ratio = (float)in->read_u16() / (float)65535; - IF_VERBOSE_PARSE(log_msg(" ratio: %f\n", m_ratio)); + m_ratio = in->read_u16() * (1.0f / 65535.0f); } if (has_name) { m_name = in->read_string(); - IF_VERBOSE_PARSE(log_msg(" name = %s\n", m_name ? m_name : "")); } if (has_clip_bracket) { m_clip_depth = in->read_u16(); - IF_VERBOSE_PARSE(log_msg(" clip_depth = %d\n", m_clip_depth)); + IF_VERBOSE_PARSE(log_msg("HAS CLIP BRACKET!\n")); } if (has_actions) { @@ -2729,8 +2539,6 @@ namespace gameswf } UNUSED(all_flags); - IF_VERBOSE_PARSE(log_msg(" actions: flags = 0x%X\n", all_flags)); - // Read swf_events. for (;;) { @@ -2777,11 +2585,13 @@ namespace gameswf m_place_type = PLACE; } - //log_msg("place object at depth %i\n", m_depth); + IF_VERBOSE_PARSE(log_msg("po2r: name = %s\n", m_name)); + IF_VERBOSE_PARSE(log_msg("po2r: char id = %d, mat:\n", m_character_id); m_matrix.print()); } } + // SwiffPlayer.dll 0x10075640. void execute(movie* m) // Place/move/whatever our object in the given movie. { @@ -2798,6 +2608,7 @@ namespace gameswf m_matrix, m_ratio, m_clip_depth); + IF_VERBOSE_DEBUG(log_msg(">>>>>>>>> character (%s) placed at %d\n", m_name, m_depth)); break; case MOVE: @@ -2809,6 +2620,7 @@ namespace gameswf m_matrix, m_ratio, m_clip_depth); + IF_VERBOSE_DEBUG(log_msg(">>>>>>>>> character (%s) moved at %d\n", m_name, m_depth)); break; case REPLACE: @@ -2822,18 +2634,22 @@ namespace gameswf m_matrix, m_ratio, m_clip_depth); + IF_VERBOSE_DEBUG(log_msg(">>>>>>>>> character (%s) replaced at %d\n", m_name, m_depth)); break; } } + // SwiffPlayer.dll 0x10075770 delegates to execute. void execute_state(movie* m) { execute(m); } - // [DICE-MOD SwiffPlayer #45] see execute_tag::execute_goto: the goto pass does nothing + // see execute_tag::execute_goto: the goto pass does nothing // with a place (0x10075760 is a nullsub); the state builder reads its depth and kind. + // SwiffPlayer.dll 0x10075760. void execute_goto(movie* /*m*/) {} + // SwiffPlayer.dll 0x10075630. bool is_place_tag() const { return true; } int get_tag_depth() const { return m_depth; } int get_place_type() const { return (int) m_place_type; } @@ -2844,7 +2660,7 @@ namespace gameswf { case PLACE: // reverse of add is remove - m->remove_display_object(m_depth, m_tag_type == 4 ? m_character_id : -1); + m->remove_display_object(m_depth); break; case MOVE: @@ -2901,12 +2717,11 @@ namespace gameswf + // SwiffPlayer.dll 0x10076A30. void place_object_2_loader(stream* in, int tag_type, movie_definition_sub* m) { assert(tag_type == 4 || tag_type == 26); - IF_VERBOSE_PARSE(log_msg(" place_object_2\n")); - place_object_2* ch = new place_object_2; ch->read(in, tag_type, m->get_version()); @@ -2930,22 +2745,30 @@ namespace gameswf // and displayed in the parent movie's display list. - struct sprite_definition : public movie_definition_sub + // SwiffPlayer.dll ctor 0x1007B5A0: movie_definition_sub at +0 (table 0x100E0138) and character_def at + // +8 (table 0x100E0108), sharing the virtual ref_counted at +0x40. + struct sprite_definition : public movie_definition_sub, public character_def { movie_definition_sub* m_movie_def; // parent movie. array > m_playlist; // movie control events for each frame. + array m_init_action_list; stringi_hash m_named_frames; // stores 0-based frame #'s int m_frame_count; int m_loading_frame; - sprite_definition(movie_definition_sub* m) + sprite_definition(movie_definition_sub* m, int character_id = 0) : m_movie_def(m), m_frame_count(0), m_loading_frame(0) { + // SwiffPlayer.dll 0x1007B5A0. + set_character_id(character_id); assert(m_movie_def); } + // SwiffPlayer.dll 0x1007D730 (deleting entry 0x1007D700): + // delete playlist tags in frame order; + // member destruction releases labels, init storage, then playlist storage. ~sprite_definition() { // Release our playlist data. @@ -2959,53 +2782,100 @@ namespace gameswf } // overloads from movie_definition + // SwiffPlayer.dll 0x1006F970: definitions do not display their timelines. + virtual void display(character* instance_info) {} + + // SwiffPlayer.dll 0x1007B670 returns four zero floats even for a nonempty + // sprite definition; live sprite bounds come from its display list. + rect get_bound_copy() const override + { + rect bounds; + bounds.m_x_min = 0.0f; + bounds.m_x_max = 0.0f; + bounds.m_y_min = 0.0f; + bounds.m_y_max = 0.0f; + return bounds; + } + + // SwiffPlayer.dll 0x1007B6A0. virtual float get_width_pixels() const { return 1; } + // SwiffPlayer.dll 0x1007B6B0. virtual float get_height_pixels() const { return 1; } + // SwiffPlayer.dll 0x1007B6C0. virtual int get_frame_count() const { return m_frame_count; } + // SwiffPlayer.dll 0x1007B6D0. virtual float get_frame_rate() const { return m_movie_def->get_frame_rate(); } + // SwiffPlayer.dll 0x1007B6E0. virtual int get_loading_frame() const { return m_loading_frame; } + // SwiffPlayer.dll 0x1007B6F0. virtual int get_version() const { return m_movie_def->get_version(); } + // SwiffPlayer.dll 0x1007B700. virtual void add_character(int id, character_def* ch) { log_error("add_character tag appears in sprite tags!\n"); } + // SwiffPlayer.dll 0x1007B710. virtual void add_font(int id, font* ch) { log_error("add_font tag appears in sprite tags!\n"); } + // SwiffPlayer.dll 0x1007B720. virtual font* get_font(int id) { return m_movie_def->get_font(id); } + // SwiffPlayer.dll 0x1007B730. virtual void set_jpeg_loader(jpeg::input* j_in) { assert(0); } + // SwiffPlayer.dll 0x1007B740. virtual jpeg::input* get_jpeg_loader() { return NULL; } + // SwiffPlayer.dll 0x1007B750. virtual bitmap_character_def* get_bitmap_character(int id) { return m_movie_def->get_bitmap_character(id); } + // SwiffPlayer.dll 0x1007B760. virtual void add_bitmap_character(int id, bitmap_character_def* ch) { log_error("add_bc appears in sprite tags!\n"); } + // SwiffPlayer.dll 0x1007B770. virtual sound_sample* get_sound_sample(int id) { return m_movie_def->get_sound_sample(id); } + // SwiffPlayer.dll 0x1007B780. virtual void add_sound_sample(int id, sound_sample* sam) { log_error("add sam appears in sprite tags!\n"); } // @@ would be nicer to not inherit these... + // SwiffPlayer.dll 0x1007B790. virtual create_bitmaps_flag get_create_bitmaps() const { assert(0); return DO_LOAD_BITMAPS; } + // SwiffPlayer.dll 0x1007B7A0. virtual create_font_shapes_flag get_create_font_shapes() const { assert(0); return DO_LOAD_FONT_SHAPES; } + // SwiffPlayer.dll 0x1007B7B0. virtual int get_bitmap_info_count() const { assert(0); return 0; } + // SwiffPlayer.dll 0x1007B7C0. virtual bitmap_info* get_bitmap_info(int i) const { assert(0); return NULL; } + // SwiffPlayer.dll 0x1007B7D0. virtual void add_bitmap_info(bitmap_info* bi) { assert(0); } - virtual void export_resource(const tu_string& symbol, resource* res) { log_error("can't export from sprite\n"); } + // SwiffPlayer.dll 0x1007B7E0. + virtual void export_resource(int id, const tu_string& symbol, resource* res) { log_error("can't export from sprite\n"); } + // SwiffPlayer.dll 0x1007B7F0. + virtual bool get_export_name(int id, tu_string* out) { return m_movie_def->get_export_name(id, out); } + // SwiffPlayer.dll 0x1007B8B0. virtual smart_ptr get_exported_resource(const tu_string& sym) { return m_movie_def->get_exported_resource(sym); } - virtual bool get_exported_font_name(const font* f, tu_string* out) { return m_movie_def->get_exported_font_name(f, out); } // [DICE-MOD #37] + virtual bool get_exported_font_name(const font* f, tu_string* out) { return m_movie_def->get_exported_font_name(f, out); } // + // SwiffPlayer.dll 0x1007B800. virtual void add_import(const char* source_url, int id, const char* symbol) { assert(0); } + // SwiffPlayer.dll 0x1007B810. virtual void visit_imported_movies(import_visitor* v) { assert(0); } + // SwiffPlayer.dll 0x1007B820. virtual void resolve_import(const char* source_url, movie_definition* d) { assert(0); } + // SwiffPlayer.dll 0x1007B830. virtual character_def* get_character_def(int id) { return m_movie_def->get_character_def(id); } + // SwiffPlayer.dll 0x1007B840. virtual void generate_font_bitmaps() { assert(0); } + // SwiffPlayer.dll 0x1007B850; secondary-interface thunk 0x1007B890. virtual void output_cached_data(tu_file* out, const cache_options& options) { // Nothing to do. return; } + // SwiffPlayer.dll 0x1007B860; secondary-interface thunk 0x1007B8A0. virtual void input_cached_data(tu_file* in) { // Nothing to do. return; } + // SwiffPlayer.dll 0x1007B870. virtual movie_interface* create_instance() { return NULL; @@ -3016,19 +2886,19 @@ namespace gameswf /* sprite_definition */ + // SwiffPlayer.dll 0x1007B8F0. virtual void add_execute_tag(execute_tag* c) { m_playlist[m_loading_frame].push_back(c); } - /* sprite_definition */ - virtual void add_init_action(int sprite_id, execute_tag* c) + // SwiffPlayer.dll 0x10071630 ignores init actions inside a sprite. + virtual void add_init_action(execute_tag* c) { - // Sprite def's should not have do_init_action tags in them! (@@ correct?) - log_error("sprite_definition::add_init_action called! Ignored.\n"); } /* sprite_definition */ + // SwiffPlayer.dll 0x1007B990. virtual void add_frame_name(const char* name) // Labels the frame currently being loaded with the // given name. A copy of the name string is made and @@ -3049,44 +2919,37 @@ namespace gameswf } /* sprite_definition */ + // SwiffPlayer.dll 0x1007B920. bool get_labeled_frame(const char* label, int* frame_number) // Returns 0-based frame # { return m_named_frames.get(label, frame_number); } + // SwiffPlayer.dll 0x1007B8D0. const array& get_playlist(int frame_number) // frame_number is 0-based { return m_playlist[frame_number]; } - /* sprite_definition */ + // SwiffPlayer.dll 0x1007B880 returns the empty sprite init-action list. virtual const array* get_init_actions(int frame_number) { - // Sprites do not have init actions in their - // playlists! Only the root movie - // (movie_def_impl) does (@@ correct?) - return NULL; + return &m_init_action_list; } - /* sprite_definition */ + // SwiffPlayer.dll 0x100777C0. void read(stream* in) // Read the sprite info. Consists of a series of tags. { int tag_end = in->get_tag_end_position(); m_frame_count = in->read_u16(); - // ALEX: some SWF files have been seen that have 0-frame sprites. - // The Macromedia player behaves as if they have 1 frame. - if (m_frame_count < 1) - { - m_frame_count = 1; - } m_playlist.resize(m_frame_count); // need a playlist for each frame - IF_VERBOSE_PARSE(log_msg(" frames = %d\n", m_frame_count)); + IF_VERBOSE_PARSE(log_msg("sprite: frames = %d\n", m_frame_count)); m_loading_frame = 0; @@ -3097,7 +2960,6 @@ namespace gameswf if (tag_type == 1) { // show frame tag -- advance to the next frame. - IF_VERBOSE_PARSE(log_msg(" show_frame (sprite)\n")); m_loading_frame++; } else if (s_tag_loaders.get(tag_type, &lf)) @@ -3115,7 +2977,6 @@ namespace gameswf in->close_tag(); } - IF_VERBOSE_PARSE(log_msg(" -- sprite END --\n")); } }; @@ -3124,6 +2985,26 @@ namespace gameswf // sprite_instance // + // SwiffPlayer.dll 0x10080590/0x10083A20 compare built-in property + // spellings exactly. Keep the 2006 enum as a local dispatch adapter. + static as_standard_member sprite_standard_member(const tu_stringi& name) + { + static const char* const names[] = { + "_x", "_y", "_xscale", "_yscale", "_currentframe", "_totalframes", + "_alpha", "_visible", "_width", "_height", "_rotation", "_target", + "_framesloaded", "_name", "_droptarget", "_url", "_highquality", + "_focusrect", "_soundbuftime", "_xmouse", "_ymouse", "_parent" + }; + for (int i = 0; i < ARRAYSIZE(names); ++i) + { + if (strcmp(name.c_str(), names[i]) == 0) + { + return static_cast(i); + } + } + return M_INVALID_MEMBER; + } + // [TEMP] RW-88 navigation tracer: a clip's dotted path, walked up to the root. The existing // attachMovie line prints get_name() alone, which is empty for every clip the components build, @@ -3153,11 +3034,52 @@ namespace gameswf // [TEMP] RW-89 mouse tracer: the press/release lines the interactive drives read, in the format // of the stock-era tracer that lived beside generate_mouse_button_events. [RETIRE-WHEN: RW-89] +#if !defined(_MSC_VER) + // [TEMP] [CHOSEN, not recovered] BF2_SWF_EMPTY_LIST_GUARD=1 ends a sprite's mouse child + // pass when a handler emptied its list; off by default. Retail 0x10080270 has no guard. + // [RETIRE-WHEN: swf-empty-list-trigger] Remove after the maintainer identifies the + // emptying handler and validates the retail-equivalent path with this flag unset. + static bool swf_empty_list_guard() + { + static int s_on = -1; + if (s_on < 0) + { + const char* v = getenv("BF2_SWF_EMPTY_LIST_GUARD"); + s_on = (v && v[0] == '1') ? 1 : 0; + } + return s_on != 0; + } + + // [TEMP] c-swf-disconnect: the tracer's path, for the other gameswf files. + const char* swf_list_trace_path(character* ch) { return swf_trace_path(ch); } +#endif + static void swf_trace_mouse(const char* what, character* ch) { log_error("[mouse] %s -> %s\n", what, swf_trace_path(ch)); } + // [TEMP] [CHOSEN, not recovered] Input-only diagnostics never inspect script values. + // [RETIRE-WHEN: ea-popup-input] Remove after live login/Close input is verified. + static bool swf_trace_input_enabled() + { + const char* value = ::getenv("BF2_SWIFFPLAYER_INPUTLOG"); + return value && value[0] == '1' && value[1] == '\0'; + } + static bool s_trace_mouse_pass = false; + + // [CHOSEN, not recovered] The root-definition reads. Retail keeps a sprite's definition as the + // character_def pointer at sprite +0xC8 and reads the ID (+0x10, duplicateMovieClip 0x100759CF) and + // the registered class (+0x14, on_event_load 0x10081911) through it even for a ROOT sprite, whose + // definition is a movie_def_impl and no character_def. Those offsets are movie_def_impl members: + // 0x10077FB0 zeroes them (ID 0, no class), and once the movie has loaded they may hold container + // state, which retail then reads as an ID or a class - undefined. The native types do not overlap, + // so a root sprite answers the constructor's values: no sprite_definition, ID 0, no class. + static sprite_definition* sprite_definition_of(movie_definition_sub* def) + { + return dynamic_cast(def); + } + struct sprite_instance : public character { smart_ptr m_def; @@ -3168,14 +3090,20 @@ namespace gameswf play_state m_play_state; int m_current_frame; + int m_next_frame; float m_time_remainder; bool m_update_frame; + bool m_force_frame_update; + bool m_first_frame_initialized; bool m_has_looped; bool m_accept_anim_moves; // once we've been moved by ActionScript, don't accept moves from anim tags. - array m_init_actions_executed; // a bit-array class would be ideal for this as_environment m_as_environment; + // [CHOSEN, not recovered] S2 bridge; SwiffPlayer.dll 0x1007FB60 + // returns this sprite's environment through its secondary interface. + virtual as_environment* get_action_environment() { return &m_as_environment; } + enum mouse_state { UP = 0, @@ -3184,32 +3112,40 @@ namespace gameswf }; mouse_state m_mouse_state; - // [DICE-MOD SwiffPlayer: Object.registerClass support - the class prototype this instance - // chains to (its __proto__) and whether the class constructor has run. See - // bind_registered_class() and gameswf.h character_def::m_registered_class.] - smart_ptr m_class_proto; - bool m_class_bound; - bool m_class_ctor_run; // [DICE-MOD SwiffPlayer #27] the constructor half of the binding + // SwiffPlayer.dll 0x10081870 creates a private script object for a bound class. + // [CHOSEN, not recovered] S3 bridge: native as_object storage and strong + // ownership replace the retail secondary-interface object at +0x104. + // [RETIRE-WHEN: swf-native-script-object] Retire after common script-object + // integration resolves movie-valued constructor/accessor prototypes and + // native GC ownership, and class accessors/events pass menu and reload gates. + smart_ptr m_script_object; - // [DICE-MOD SwiffPlayer: getNextHighestDepth's counter (the shipped sprite keeps one at - // +220, returned then incremented; ours also clears every depth already in use).] + // SwiffPlayer.dll 0x1007F3AB initializes the postincrement depth counter to 1000. int m_next_highest_depth; - - // [DICE-MOD SwiffPlayer: the drawing-API canvas - the shape definition behind the - // `_____defaultShape` child the shipped sub_1007C0D0 creates at depth 0 on first use.] + // SwiffPlayer.dll 0x1007F433; a negative index is absent from member lookup. + int m_tab_index; + // [UNRESOLVED] The constructor stores 1000 at primary +0x114 in + // addition to the depth counter at +0xDC. Keep the separate word; + // its meaning is not established by the inspected consumers. + Uint32 m_retail_word_114; + + // the drawing-API canvas - the shape definition behind the + // `_____defaultShape` child the shipped sub_1007C0D0 creates at depth 0 on first use. smart_ptr m_canvas; - // [DICE-MOD SwiffPlayer #45] numeric gotos waiting for advance() (the shipped sprite's + // numeric gotos waiting for advance() (the shipped sprite's // pending_goto_frames array at +264, drained by 0x10081CF0). array m_pending_goto_frames; - // [DICE-MOD SwiffPlayer #51] the shipped sprite's mouse state (+0x2150 previous, +0x2154 current: + // the shipped sprite's mouse state (+0x2150 previous, +0x2154 current: // bit 0 inside, bit 1 a button down), its first-frame latch (+255) and whether it took the // press it still holds (+256). int m_mouse_flags, m_prev_mouse_flags; bool m_first_mouse_frame; bool m_mouse_pressed; + // SwiffPlayer.dll 0x1007F310. Native character/definition/environment + // storage uses their existing [CHOSEN, not recovered] S3 ownership bridges. sprite_instance(movie_definition_sub* def, movie_root* r, movie* parent, int id) : character(parent, id), @@ -3217,8 +3153,11 @@ namespace gameswf m_root(r), m_play_state(PLAY), m_current_frame(0), + m_next_frame(0), m_time_remainder(0), m_update_frame(true), + m_force_frame_update(false), + m_first_frame_initialized(false), m_has_looped(false), m_accept_anim_moves(true), m_mouse_state(UP), @@ -3226,192 +3165,188 @@ namespace gameswf m_prev_mouse_flags(0), m_first_mouse_frame(true), m_mouse_pressed(false), - m_class_bound(false), - m_class_ctor_run(false), - m_next_highest_depth(0), - m_dead(false), // [DICE-MOD SwiffPlayer #42] - m_first_frame_actions_pending(false) // [DICE-MOD SwiffPlayer #53] + m_next_highest_depth(1000), + m_tab_index(-1), + m_retail_word_114(1000), + m_dead(false) // { assert(m_def != NULL); assert(m_root != NULL); //m_root->add_ref(); // @@ circular! m_as_environment.set_target(this); + // SwiffPlayer.dll 0x1007F310 preloads these undefined environment members. + // Class handlers precede the environment in get_member (0x10080590). + static const char* const event_names[] = { + "onPress", "onDoublePress", "onRelease", "onReleaseOutside", + "onRollOver", "onRollOut", "onDragOver", "onDragOut", "onKeyPress", + "onInitialize", "onLoad", "onUnload", "onEnterFrame", "onMouseDown", + "onMouseUp", "onMouseMove", "onKeyDown", "onKeyUp", "onData" + }; + for (int i = 0; i < ARRAYSIZE(event_names); ++i) + { + m_as_environment.set_member(event_names[i], as_value()); + } sprite_builtins_init(); - - // Initialize the flags for init action executed. - m_init_actions_executed.resize(m_def->get_frame_count()); - memset(&m_init_actions_executed[0], 0, - sizeof(m_init_actions_executed[0]) * m_init_actions_executed.size()); + ++s_sprite_live_count; } - // sprite instance of add_interval_handler() - virtual int add_interval_timer(void *timer) + bool m_dead; // see character::mark_dead + virtual void mark_dead() { m_dead = true; } + + virtual void gc_mark() { - // log_msg("FIXME: %s:\n", __FUNCTION__); - return m_root->add_interval_timer(timer); + // SwiffPlayer.dll 0x10080F90: locals, members, referenced children, + // private script object. Registers, operands and handlers are omitted. + if (m_gc_generation == get_gc_mark_generation()) return; + m_gc_generation = get_gc_mark_generation(); + for (int i = 0; i < m_as_environment.m_local_frames.size(); ++i) + gc_mark_value(m_as_environment.m_local_frames[i].m_value); + for (stringi_hash::iterator it = m_as_environment.m_variables.begin(); + it != m_as_environment.m_variables.end(); ++it) + gc_mark_value(it->second); + const int count = m_display_list.get_character_count(); + for (int i = 0; i < count; ++i) + if (character* child = m_display_list.get_character(i)) child->gc_mark(); + if (m_script_object != NULL) m_script_object->gc_mark(); } - virtual void clear_interval_timer(int x) + virtual void gc_release() { - // log_msg("FIXME: %s:\n", __FUNCTION__); - m_root->clear_interval_timer(x); + // SwiffPlayer.dll 0x10081BB0: referenced children, OBJECT members, + // member-bag clear, private script object. Locals are retained. + if (m_gc_generation == get_gc_release_generation()) return; + m_gc_generation = get_gc_release_generation(); + const int count = m_display_list.get_character_count(); + for (int i = 0; i < count; ++i) + if (character* child = m_display_list.get_character(i)) child->gc_release(); + for (stringi_hash::iterator it = m_as_environment.m_variables.begin(); + it != m_as_environment.m_variables.end(); ++it) + if (it->second.get_type() == as_value::OBJECT && it->second.to_object()) + it->second.to_object()->gc_release(); + m_as_environment.m_variables.clear(); + if (m_script_object != NULL) m_script_object->gc_release(); } - - /* sprite_instance */ - virtual void do_something(void *timer) + // [CHOSEN, not recovered] issue #7: movie teardown, see release_script_objects. Adds the + // environment, the private script object and every child to the base character's values. + virtual void release_script_values(array* held) { - as_value val; - as_object_interface *obj, *this_ptr; // [DICE-MOD: the tick's this may be a sprite] - as_environment *as_env; - - //printf("FIXME: %s:\n", __FUNCTION__); - Timer *ptr = (Timer *)timer; - //log_msg("INTERVAL ID is %d\n", ptr->getIntervalID()); - - const as_value& timer_method = ptr->getASFunction(); - as_env = ptr->getASEnvironment(); - this_ptr = ptr->getASObject(); - obj = ptr->getObject(); - //m_as_environment.push(obj); - - as_c_function_ptr cfunc = timer_method.to_c_function(); - if (cfunc) { - // It's a C function. Call it. - //log_msg("Calling C function for interval timer\n"); - //(*cfunc)(&val, obj, as_env, 0, 0); - (*cfunc)(fn_call(&val, obj, &m_as_environment, 0, 0)); - - } else if (as_as_function* as_func = timer_method.to_as_function()) { - // It's an ActionScript function. Call it. - as_value method; - //log_msg("Calling ActionScript function for interval timer\n"); - (*as_func)(fn_call(&val, (as_object_interface *)this_ptr, as_env, 0, 0)); - //(*as_func)(&val, (as_object_interface *)this_ptr, &m_as_environment, 1, 1); - } else { - log_error("error in call_method(): method is not a function\n"); - } - } - - bool m_dead; // [DICE-MOD SwiffPlayer #42] see character::mark_dead - virtual void mark_dead() { m_dead = true; } - - // [DICE-MOD SwiffPlayer #53] frame 0's DoAction tags, queued by on_event_load's - // execute_frame_tags(0), are NOT run at placement: the shipped on_event_load - // (sub_10081870) frees the action list (+224) right after the tags, and the script runs - // when the sprite's first advance re-executes frame 0 - AFTER the parent's own frame - // script. This flag is that "frame 0's script still owed" state; advance_pass drains it. - bool m_first_frame_actions_pending; + character::release_script_values(held); + m_as_environment.release_values(held); + if (m_script_object != NULL) + { + held->push_back(as_value(m_script_object.get_ptr())); + m_script_object = NULL; + } + m_display_list.release_characters(held); + } + // SwiffPlayer.dll 0x10084B60; deleting wrapper 0x10084B20. + // Native definition/environment/base ownership retains its S3 bridges. virtual ~sprite_instance() { - // [TEMP] [CHOSEN, not recovered] RW-89: a child still referenced from ActionScript when its - // parent clip is destroyed (a page torn down by a frame change while a script callback - // keeps its objects) keeps a RAW m_parent in stock 2006, and the next get_world_matrix() - // through it faulted retail (interactive run drive1: a component's label field re-laid - // out from a callback after the login page was left). Until the shipped handling of such - // survivors is read, name the survivor and hand it the root as parent - it is in no - // display list, so nothing draws through that matrix. [RETIRE-WHEN: RW-88] + // SwiffPlayer.dll 0x10084B60 decrements before touching children. + --s_sprite_live_count; + // 0x10084B92..0x10084BB8 releases capture held by this sprite. + movie* owner = get_global_root_movie(); + if (owner && owner->get_active_mouse_entity() == this) { - movie* root = m_root ? m_root->get_root_movie() : NULL; - for (int i = 0, n = m_display_list.get_character_count(); i < n; i++) + get_global_root_movie()->set_active_mouse_entity(NULL); + } + // 0x10084BC5..0x10084C05: sweep pending removals, then detach + // each remaining child before dropping its display-list reference. + m_display_list.update(); + while (m_display_list.get_character_count() != 0) + { + character* child = m_display_list.get_character(0); + if (child) { - character* ch = m_display_list.get_character(i); - if (ch && ch->get_ref_count() > 1) - { - log_error("[orphan] child '%s' of destroyed sprite '%s' survives (refs=%d)" "\n", - ch->get_name().c_str(), get_name().c_str(), ch->get_ref_count()); - if (root && root != this) ch->m_parent = root; - ch->mark_dead(); - } + m_display_list.remove_display_object(child->get_depth()); + m_display_list.update(); } } m_display_list.clear(); //m_root->drop_ref(); } + // SwiffPlayer.dll 0x1007FB80 / 0x1007FB70. movie_interface* get_root_interface() { return m_root; } movie_root* get_root() { return m_root; } movie* get_root_movie() { return m_root->get_root_movie(); } + // SwiffPlayer.dll 0x100803F0 copies presentation state before definition/root. + virtual void copy_display_state(character* target) const + { + character::copy_display_state(target); + sprite_instance* sprite = static_cast(target); + sprite->m_def = m_def; + sprite->m_root = m_root; + } + + // SwiffPlayer.dll 0x1007FDC0. movie_definition* get_movie_definition() { return m_def.get_ptr(); } - float get_width() + // SwiffPlayer.dll 0x1007FDD0: referenced children only, snapshot count, + // local matrix copied before the child virtual; first child seeds the union. + rect get_bound_copy() const override { - float w = 0; - int i, n = m_display_list.get_character_count(); - character* ch; - for (i = 0; i < n; i++) + rect bounds = { 0, 0, 0, 0 }; + bool first = true; + for (int i = 0, n = m_display_list.get_character_count(); i < n; ++i) { - ch = m_display_list.get_character(i); - if (ch != NULL) - { - float ch_w = ch->get_width(); - if (ch_w > w) - { - w = ch_w; - } - } + character* child = m_display_list.get_character(i); + if (child == NULL) continue; + const matrix transform = child->get_matrix(); + rect current = child->get_bound_copy(); + current.enclose_transformed_rect(transform, current); + if (first) { bounds = current; first = false; } + else bounds.expand_to_rect(current); } - - return w; + return bounds; } + // SwiffPlayer.dll 0x10081150: registration and ending clock/count are + // unconditional, while only the starting clock is gated on profiling. + float get_width() + { + static profile_record counter("sprite_get_width"); + if (s_profiling) counter.begin(); + const rect bounds = get_bound_copy(); + const float width = (float)(((long double)bounds.m_x_max - bounds.m_x_min) * 0.05f); + counter.end(); + return width; + } - - float get_height() + // SwiffPlayer.dll 0x10081230, including the same profiling quirk. + float get_height() { - float h = 0; - int i, n = m_display_list.get_character_count(); - character* ch; - for (i=0; i < n; i++) - { - ch = m_display_list.get_character(i); - if (ch != NULL) - { - float ch_h = ch->get_height(); - if (ch_h > h) - { - h = ch_h; - } - } - } - return h; + static profile_record counter("sprite_get_height"); + if (s_profiling) counter.begin(); + const rect bounds = get_bound_copy(); + const float height = (float)(((long double)bounds.m_y_max - bounds.m_y_min) * 0.05f); + counter.end(); + return height; } - // [DICE-MOD SwiffPlayer #39] the clip's unscaled local extent: the largest child extent, each - // child measured in this clip's space (its local extent times its own scale). get_width() - // above carries the WORLD scale and stays for the stock callers. + // [CHOSEN, not recovered] S3 bridge: the retained 2006 local-extent API + // returns twips; the retail pixel accessors above use the same rectangle. virtual float get_local_width() { - float w = 0; - for (int i = 0, n = m_display_list.get_character_count(); i < n; i++) - { - character* ch = m_display_list.get_character(i); - if (ch == NULL) continue; - const float cw = ch->get_local_width() * ch->get_matrix().m_[0][0]; - if (cw > w) w = cw; - } - return w; + return get_bound_copy().width(); } virtual float get_local_height() { - float h = 0; - for (int i = 0, n = m_display_list.get_character_count(); i < n; i++) - { - character* ch = m_display_list.get_character(i); - if (ch == NULL) continue; - const float chh = ch->get_local_height() * ch->get_matrix().m_[1][1]; - if (chh > h) h = chh; - } - return h; + return get_bound_copy().height(); } + // SwiffPlayer.dll 0x1007FB90. int get_current_frame() const { return m_current_frame; } + // SwiffPlayer.dll 0x100719E0. int get_frame_count() const { return m_def->get_frame_count(); } + // SwiffPlayer.dll 0x1007FF30. void set_play_state(play_state s) // Stop or play the sprite. { @@ -3421,10 +3356,17 @@ namespace gameswf } m_play_state = s; + if (s == STOP) + { + m_next_frame = m_current_frame + 1; + if (m_next_frame >= m_def->get_frame_count()) m_next_frame = 0; + } } + // SwiffPlayer.dll 0x1007FBA0. play_state get_play_state() const { return m_play_state; } + // SwiffPlayer.dll 0x1007FBB0: no character-ID lookup on a live sprite. character* get_character(int character_id) { // return m_def->get_character_def(character_id); @@ -3432,12 +3374,33 @@ namespace gameswf return NULL; } + // SwiffPlayer.dll 0x1007FD60: snapshot the child count, skip deferred + // removals, and forward the same index without updating child sprites' members. + virtual void set_tab_index(int index) + { + for (int i = 0, n = m_display_list.get_character_count(); i < n; ++i) + { + character* ch = m_display_list.get_character(i); + if (ch) ch->set_tab_index(index); + } + } + + // SwiffPlayer.dll 0x1007FB40: inherit a parent's index only for the + // propagation interface; get_member("tabIndex") tests this clip's own value. + virtual int get_tab_index() const + { + if (m_tab_index >= 0) return m_tab_index; + return m_parent ? m_parent->get_tab_index() : -1; + } + + // SwiffPlayer.dll 0x1007FBC0. float get_background_alpha() const { // @@ this doesn't seem right... return m_root->get_background_alpha(); } + // SwiffPlayer.dll 0x1007FBD0. float get_pixel_scale() const { return m_root->get_pixel_scale(); } virtual void get_mouse_state(int* x, int* y, int* buttons) @@ -3445,28 +3408,34 @@ namespace gameswf m_root->get_mouse_state(x, y, buttons); } + // SwiffPlayer.dll 0x1007FC20. + rgba get_background_color() const { return m_root->get_background_color(); } + + // SwiffPlayer.dll 0x1007FC30. void set_background_color(const rgba& color) { m_root->set_background_color(color); } + // SwiffPlayer.dll 0x1007FC40. float get_timer() const { return m_root->get_timer(); } + // SwiffPlayer.dll 0x1007FC50 resets timeline and first-mouse state only. void restart() { + m_first_mouse_frame = true; m_current_frame = 0; + m_next_frame = 0; m_time_remainder = 0; m_update_frame = true; m_has_looped = false; - m_play_state = PLAY; - - execute_frame_tags(m_current_frame); - m_display_list.update(); } + // SwiffPlayer.dll 0x1007FC80. virtual bool has_looped() const { return m_has_looped; } + // SwiffPlayer.dll 0x1007FC90. virtual bool get_accept_anim_moves() const { return m_accept_anim_moves; } inline int transition(int a, int b) const @@ -3476,7 +3445,7 @@ namespace gameswf } - // [DICE-MOD SwiffPlayer #51] sub_1007FF90 - does this sprite cover the world-space point: any + // sub_1007FF90 - does this sprite cover the world-space point: any // referenced, visible child that does, in display-list order. An invisible sprite covers nothing. virtual bool point_test_world(float x, float y) { @@ -3496,11 +3465,11 @@ namespace gameswf return false; } - // [DICE-MOD SwiffPlayer #51] the root's mouse capture, kept on the movie_root. + // the root's mouse capture, kept on the movie_root. virtual movie* get_active_mouse_entity() { return m_root->get_active_entity(); } virtual void set_active_mouse_entity(movie* m) { m_root->set_active_entity(m); } - // [DICE-MOD SwiffPlayer #51] sub_10080010 (709 instructions, read in full 2026-09-13) - the + // sub_10080010 (709 instructions, read in full 2026-09-13) - the // sprite's mouse pass, vtable slot 4. Stock 2006 had none of this: movie_root picked ONE // "topmost entity" through get_topmost_mouse_entity (the first hit walking each display list // from the top, a bare shape included) and generate_mouse_button_events fed it. That is why a @@ -3509,8 +3478,8 @@ namespace gameswf // // The shipped pass, per frame, per sprite: // - // 1. its own state machine runs only while nobody holds the pointer or this sprite does (the - // root's active entity). `consumed` - a sibling above already claimed the point - leaves + // 1. its own state machine runs while this sprite holds the pointer, or while nobody does + // and this is not the root movie. `consumed` - a sibling above claimed the point - leaves // both state bits clear, so the sprite sees "up, outside"; otherwise bit 1 is a button // down and bit 0 is point_test_world on the pointer in world twips; // 2. the first frame only latches, and nothing fires unless m_mouse_enabled; @@ -3524,18 +3493,37 @@ namespace gameswf // this sprite holds the capture, in which case the children are skipped; // 5. the answer: consumed by a child, or inside-and-enabled here. // - // The world matrix the shipped body fetches first is never read; it is not fetched here. The - // [mouse] press/release lines are the RW-89 tracer the interactive drives read [TEMP]. + // The [mouse] press/release lines are the RW-89 tracer the interactive drives read [TEMP]. virtual bool mouse_update(bool consumed) { - // Keep this (particularly m_as_environment) alive during any method calls! - smart_ptr this_ptr(this); + // SwiffPlayer.dll 0x10080010 holds + // neither a self reference nor a reference to display-list storage. +#if !defined(_MSC_VER) + // [TEMP] c-swf-disconnect: nesting of mouse passes for the [swf-list] tracer. + struct pass_depth { pass_depth() { g_swf_mouse_pass_depth++; } ~pass_depth() { g_swf_mouse_pass_depth--; } } depth_scope; +#endif movie* active = m_root->get_active_entity(); - if (active == this || active == NULL) + const bool trace_root = this == m_root->get_root_movie() && swf_trace_input_enabled(); + if (trace_root) + { + static int previous_buttons = -1; + int x, y, buttons; + m_root->get_mouse_state(&x, &y, &buttons); + s_trace_mouse_pass = buttons != previous_buttons; + previous_buttons = buttons; + if (s_trace_mouse_pass) + log_error("[mouse] dispatch at=(%d,%d) buttons=%d capture=%s\n", x, y, buttons, + active ? swf_trace_path(active->cast_to_character()) : "none"); + } + if (active == this || (active == NULL && this != m_root->get_root_movie())) { m_prev_mouse_flags = m_mouse_flags; m_mouse_flags = 0; + // SwiffPlayer.dll 0x10080068's virtual + // world-matrix fetch. Its result is unused; retain the call and its order. + matrix world = get_world_matrix(); + (void) world; int mx = 0, my = 0, mb = 0; m_root->get_mouse_state(&mx, &my, &mb); if (!consumed) @@ -3554,6 +3542,10 @@ namespace gameswf m_prev_mouse_flags = m_mouse_flags; m_first_mouse_frame = false; } + if (s_trace_mouse_pass && (m_mouse_flags & 1) && m_mouse_enabled) + log_error("[mouse] hit %s id=%d depth=%d frame=%d flags=%u previous=%u dead=%d\n", + swf_trace_path(this), get_id(), get_depth(), get_current_frame(), + m_mouse_flags, m_prev_mouse_flags, m_dead); if (m_mouse_enabled && m_mouse_flags != m_prev_mouse_flags) { switch (m_mouse_flags | (m_prev_mouse_flags << 2)) @@ -3621,14 +3613,48 @@ namespace gameswf { for (int i = m_display_list.get_character_count() - 1; i >= 0; i--) { +#if !defined(_MSC_VER) + // [TEMP] c-swf-disconnect: the shipped loop (0x10080265..0x100802A2) caches the + // count and re-reads the buffer; an emptied list leaves the buffer NULL and the + // next read faults, in the shipped DLL as well. BF2_SWF_EMPTY_LIST_GUARD=1 (off by + // default; not shipped behaviour) ends the pass there instead. + if (m_display_list.get_character_count() <= i) + { + SWF_LIST_TRACE("loop '%s' i=%d past size %d%s", swf_trace_path(this), i, + m_display_list.get_character_count(), + m_display_list.get_character_count() == 0 ? " - EMPTY, buffer freed, next read faults" : " (stale slot)"); + if (m_display_list.get_character_count() == 0 && swf_empty_list_guard()) + { + break; + } + } +#endif const display_object_info& dobj = m_display_list.get_display_object(i); character* ch = dobj.m_ref ? dobj.m_character.get_ptr() : NULL; if (ch != NULL && ch->get_visible()) { +#if !defined(_MSC_VER) + const int trace_before = m_display_list.get_character_count(); +#endif + const bool was_consumed = consumed; consumed = ch->mouse_update(consumed) || consumed; + if (s_trace_mouse_pass && consumed && !was_consumed) + log_error("[mouse] consumed by %s id=%d depth=%d\n", + swf_trace_path(ch), ch->get_id(), ch->get_depth()); +#if !defined(_MSC_VER) + if (m_display_list.get_character_count() != trace_before && swf_list_trace_on()) + { + char child_name[96]; + snprintf(child_name, sizeof(child_name), "%s", ch->get_name().c_str()); + SWF_LIST_TRACE("dlist CHANGED '%s' %d -> %d inside the child pass, after child #%d '%s'", + swf_trace_path(this), trace_before, + m_display_list.get_character_count(), i, child_name); + } +#endif } } } + if (trace_root) s_trace_mouse_pass = false; return consumed || ((m_mouse_flags & 1) != 0 && m_mouse_enabled); } @@ -3652,106 +3678,69 @@ namespace gameswf } } - /* sprite_instance */ + // SwiffPlayer.dll 0x10081CF0. A queued goto consumes the incoming + // delta; each pass sweeps and advances children after the parent's actions. virtual void advance(float delta_time) { - // Keep this (particularly m_as_environment) alive during execution! - smart_ptr this_ptr(this); - - // [DICE-MOD SwiffPlayer #45] The shipped advance (0x10081CF0) first drains the - // deferred goto queue: each entry is applied, the duplicates right behind it are - // dropped, and the frame pass runs with a ZERO delta - once per applied goto. The pass - // runs once with the real delta only when nothing was queued. - if (m_pending_goto_frames.size() == 0) - { - advance_pass(delta_time); - return; - } + smart_ptr this_ptr(this); do { - const int target = m_pending_goto_frames[0]; - m_pending_goto_frames.remove(0); - apply_goto_frame(target); - while (m_pending_goto_frames.size() > 0 && m_pending_goto_frames[0] == target) + if (m_pending_goto_frames.size() > 0) { + const int target = m_pending_goto_frames[0]; m_pending_goto_frames.remove(0); - } - advance_pass(0.0f); - } - while (m_pending_goto_frames.size() > 0); - } - - // The 2006 frame pass, unchanged but for the #53 drain at its head. - void advance_pass(float delta_time) - { - assert(m_def != NULL && m_root != NULL); - - // [DICE-MOD SwiffPlayer #53] the first advance owes frame 0's script - see - // on_event_load. Only the DoAction tags are re-executed (queued in tag order) and the - // queue drained, before this sprite's own children advance: the shipped first pass - // is execute_frame_tags(0) -> onEnterFrame -> do_actions -> display_list::advance. - if (m_first_frame_actions_pending) - { - m_first_frame_actions_pending = false; - const array& playlist = m_def->get_playlist(0); - for (int i = 0; i < playlist.size(); i++) - { - execute_tag* e = playlist[i]; - if (e->is_action_tag()) + apply_goto_frame(target); + while (m_pending_goto_frames.size() > 0 && m_pending_goto_frames[0] == target) { - e->execute(this); + m_pending_goto_frames.remove(0); } + delta_time = 0.0f; } - do_actions(); - } - - // Advance everything in the display list. - m_display_list.advance(delta_time); - - // mouse drag. - character::do_mouse_drag(); - - m_time_remainder += delta_time; - - const float frame_time = 1.0f / m_root->get_frame_rate(); // @@ cache this - // Check for the end of frame - if (m_time_remainder >= frame_time) - { - m_time_remainder -= frame_time; - - // Update current and next frames. - if (m_play_state == PLAY) + character::do_mouse_drag(); + if (m_play_state != STOP) m_time_remainder += delta_time; + const float frame_time = 1.0f / m_root->get_frame_rate(); + const bool single_frame_movie = m_def->get_frame_count() == 1; + if (m_time_remainder >= frame_time) { - int current_frame0 = m_current_frame; - increment_frame_and_check_for_loop(); - - // Execute the current frame's tags. - if (m_current_frame != current_frame0) + m_update_frame = true; + m_time_remainder -= frame_time; + } + m_update_frame = m_update_frame || (m_play_state != STOP && m_force_frame_update); + if (m_update_frame) + { + m_current_frame = m_next_frame; + m_update_frame = false; + m_next_frame = m_current_frame + 1; + if (m_play_state == PLAY) { - execute_frame_tags(m_current_frame); + if (!single_frame_movie || !m_first_frame_initialized) + { + execute_frame_tags(m_current_frame); + m_first_frame_initialized = true; + } + on_event(event_id::ENTER_FRAME); + do_actions(); } } - - // Dispatch onEnterFrame event. - on_event(event_id::ENTER_FRAME); - - do_actions(); - - // Clean up display list (remove dead objects). m_display_list.update(); + m_display_list.advance(delta_time); + if (m_next_frame >= m_def->get_frame_count()) + { + m_next_frame = 0; + m_has_looped = true; + } + if (m_time_remainder >= frame_time) + { + m_update_frame = true; + m_time_remainder -= frame_time; + } } - - // Skip excess time. TODO root caller should - // loop to prevent this happening; probably - // only root should keep m_time_remainder, and - // advance(dt) should be a discrete tick() - // with no dt. - m_time_remainder = fmod(m_time_remainder, frame_time); + while (m_pending_goto_frames.size() > 0); } - /*sprite_instance*/ - void execute_frame_tags(int frame, bool state_only = false) + // SwiffPlayer.dll 0x10081B10: state dispatch takes precedence over goto dispatch. + void execute_frame_tags(int frame, bool state_only = false, bool goto_only = false) // Execute the tags associated with the specified frame. // frame is 0-based { @@ -3761,37 +3750,6 @@ namespace gameswf assert(frame >= 0); assert(frame < m_def->get_frame_count()); - // Execute this frame's init actions, if necessary. - if (m_init_actions_executed[frame] == false) - { - const array* init_actions = m_def->get_init_actions(frame); - if (init_actions && init_actions->size() > 0) - { - // Need to execute these actions. - for (int i= 0; i < init_actions->size(); i++) - { - execute_tag* e = (*init_actions)[i]; - e->execute(this); - } - - // [DICE-MOD SwiffPlayer: run them NOW. A DoInitAction is loaded as a plain - // do_action, whose execute() only QUEUES its buffer for do_actions() - so stock - // 2006 ran every "init" action after this frame's placements, in the same batch - // as the frame script. Flash runs init actions before the frame's other tags, - // and the shipped load path (sub_10081870) executes the pending init actions - // before execute_frame_tags(0). mainMenu.swf depends on it: frame 0 places its - // components first and carries the 52 class definitions + 18 - // Object.registerClass calls as DoInitAction tags after them, so on stock order - // every component was instanced before its class existed (retail 2026-09-02: - // "can't find method loadImg/setValue" ahead of the registerClass calls).] - do_actions(); - - // Mark this frame done, so we never execute these init actions - // again. - m_init_actions_executed[frame] = true; - } - } - const array& playlist = m_def->get_playlist(frame); for (int i = 0; i < playlist.size(); i++) { @@ -3800,6 +3758,10 @@ namespace gameswf { e->execute_state(this); } + else if (goto_only) + { + e->execute_goto(this); + } else { e->execute(this); @@ -3880,7 +3842,7 @@ namespace gameswf // Keep m_as_environment alive during any method calls! smart_ptr this_ptr(this); - // [DICE-MOD SwiffPlayer #48] The shipped do_actions (sub_10081480, the loop at + // The shipped do_actions (sub_10081480, the loop at // 0x100814C0) is a queue DRAIN: while the list is non-empty it takes the FRONT buffer, // removes it (sub_10081550 = remove(0)) and only THEN executes it (sub_100961E0 = // execute(&m_as_environment)); the storage is released afterwards. Stock 2006 walked @@ -3899,6 +3861,8 @@ namespace gameswf m_action_list.remove(0); buf->execute(&m_as_environment); } + // SwiffPlayer.dll 0x100814DE clears the action storage. + m_action_list.clear(); } @@ -3907,25 +3871,35 @@ namespace gameswf // Set the sprite state at the specified frame number. // 0-based frame numbers!! (in contrast to ActionScript and Flash MX) { - // [DICE-MOD SwiffPlayer #45] A numeric goto is DEFERRED. The shipped goto_frame (sprite + // A numeric goto is DEFERRED. The shipped goto_frame (sprite // vtable +168, sub_10081310) only appends the target to a per-sprite queue; advance() // (0x10081CF0) drains it before its frame pass, applying each entry through // apply_goto_frame (vtable +24) with the duplicates right behind it dropped, and runs // the pass with a zero delta. The label form (goto_labeled_frame, vtable +28) applies // at once. Stock 2006 replayed the timeline inline here. m_pending_goto_frames.push_back(target_frame_number); +#if !defined(_MSC_VER) + if (g_swf_mouse_pass_depth > 0) + { + SWF_LIST_TRACE("gotoFrame queued '%s' -> %d", swf_trace_path(this), target_frame_number); + } +#endif - // goto_frame stops by default. - m_play_state = STOP; + // SwiffPlayer.dll 0x10081310 only enqueues; it does not change play state. } - // [DICE-MOD SwiffPlayer #45] The depth -> [placing tag, move tags...] state in effect after + // The depth -> [placing tag, move tags...] state in effect after // frames 0..frame inclusive, as the shipped sub_100832F0 builds it: PLACE and REPLACE start // a depth's list, MOVE appends to an existing one (a move with no placement is dropped) and // REMOVE leaves an EMPTY list, so a removed depth is distinguishable from an unused one. void build_timeline_state(int frame, hash >* out) { - frame = iclamp(frame, 0, m_def->get_frame_count() - 1); + // SwiffPlayer.dll 0x100832F0 clamps only the upper bound, + // calling the definition again on that arm; a negative frame visits no tags. + if (m_def->get_frame_count() <= frame) + { + frame = m_def->get_frame_count() - 1; + } for (int f = 0; f <= frame; f++) { const array& playlist = m_def->get_playlist(f); @@ -3960,7 +3934,7 @@ namespace gameswf } } - // [DICE-MOD SwiffPlayer #45] The shipped goto (sprite vtable +24, sub_100822A0) is a + // The shipped goto (sprite vtable +24, sub_100822A0) is a // TIMELINE DIFF, not a tag replay. Both directions build the depth state after the current // and after the target frame, mark every referenced child by depth, and walk the target // state: a depth with no list (removed), no current placement, or a DIFFERENT placing tag @@ -3977,17 +3951,25 @@ namespace gameswf // removing every page a long jump passes: FORGOT PASSWORD jumped the root 9 -> 259 through // ten pages, and their scripts reached rows the native client gates - and replayed a // backward jump in reverse, re-adding then removing then re-placing the same list twice - // (RETRIEVE ACCOUNT -> MANAGE ACCOUNTS lost its rows). The queued lists run in depth order; - // the shipped walks its own hash [CHOSEN, not recovered - unobservable]. - void apply_goto_frame(int target_frame_number) - { - // Keep this (particularly m_as_environment) alive during execution! - smart_ptr this_ptr(this); - - // [DICE-MOD SwiffPlayer #53] a goto applied before the first pass takes the owed - // frame-0 script with it: the target frame's actions are what runs from here on. - const bool frame0_owed = m_first_frame_actions_pending; - m_first_frame_actions_pending = false; + // (RETRIEVE ACCOUNT -> MANAGE ACCOUNTS lost its rows). + // [CHOSEN, not recovered] S3 bridge: use the native base hash's traversal. + // [RETIRE-WHEN: swf-core-goto-hash-order] Certify its iteration/insertion + // policy after wave-3 base recovery and reentrant navigation/menu/reload gates. + void apply_goto_frame(int target_frame_number) override + { +#if !defined(_MSC_VER) + // [TEMP] c-swf-disconnect: gotos inside a mouse pass, or any that change the list size. + const int trace_dl0 = m_display_list.get_character_count(); + const int trace_from = m_current_frame; +#define SWF_TRACE_GOTO_SWEPT() \ + if (swf_list_trace_on() && (g_swf_mouse_pass_depth > 0 || m_display_list.get_character_count() != trace_dl0)) \ + { \ + SWF_LIST_TRACE("goto '%s' frame %d -> %d dlist %d -> %d", swf_trace_path(this), trace_from, \ + target_frame_number, trace_dl0, m_display_list.get_character_count()); \ + } +#else +#define SWF_TRACE_GOTO_SWEPT() +#endif target_frame_number = iclamp(target_frame_number, 0, m_def->get_frame_count() - 1); // [TEMP] RW-88 nav tracer: which clip navigates where, and from what. @@ -3997,40 +3979,20 @@ namespace gameswf if (target_frame_number == m_current_frame) { - // [DICE-MOD SwiffPlayer #56] The shipped same-frame arm (sub_100822A0's third - // branch): a goto to frame 0 while frame 0 has never run (+258 - // first_frame_initialized clear) executes frame 0's tags, marks it run, and takes - // the common tail - current 0 / next 1, the time remainder and the update flag - // cleared, the sweep, ENTER_FRAME, the queued actions. Any other same-frame goto - // returns with nothing done. Under #53 a placed sprite's frame 0 has NOT run until - // its first advance, so this arm is live here: mainMenu.swf's `gotoPage` opens - // with `clearModalMessageTrigger()` -> `messageHandler.gotoAndStop("noMessage")` - // (frame 0) before the root-placed messageHandler's first advance. Dropping the - // owed script instead left `checkForMessages` undefined, the UpdateManager's first - // poll missed it ("can't find method checkForMessages"), unregistered the falsy - // callback, and no host message reached the screen for the rest of the session - - // the CREATE LOCAL page's STARTING SERVER modal stayed up over a "nomapsselected" - // the owner never saw (2026-09-29). As in #53's drain, only frame 0's ACTION tags - // are re-run: the shipped replay of its placements finds their live - // on_event_load occupants (same id and name, still referenced) and does nothing - // (sub_100837E0 - see the #44/#53 correction in GAMESWF_DIVERGENCES.md). - if (target_frame_number != 0 || !frame0_owed) + // SwiffPlayer.dll 0x10082AB1: frame zero is replayed once, + // including display tags, before taking the common goto tail. + if (target_frame_number != 0 || m_first_frame_initialized) { return; } - const array& playlist = m_def->get_playlist(0); - for (int i = 0; i < playlist.size(); i++) - { - execute_tag* e = playlist[i]; - if (e->is_action_tag()) - { - e->execute(this); - } - } + execute_frame_tags(0); + m_first_frame_initialized = true; m_current_frame = 0; + m_next_frame = 1; m_time_remainder = 0; m_update_frame = false; m_display_list.update(); + SWF_TRACE_GOTO_SWEPT(); on_event(event_id::ENTER_FRAME); do_actions(); return; @@ -4054,26 +4016,12 @@ namespace gameswf build_timeline_state(m_current_frame, ¤t_state); build_timeline_state(target_frame_number, &target_state); - array depths; - for (hash >::iterator it = target_state.begin(); it != target_state.end(); ++it) - { - const int d = it->first; - int pos = depths.size(); - depths.push_back(d); - while (pos > 0 && depths[pos - 1] > d) - { - depths[pos] = depths[pos - 1]; - pos--; - } - depths[pos] = d; - } - array< array > queued; - for (int di = 0; di < depths.size(); di++) + // SwiffPlayer.dll 0x10082381 / 0x100827A7: visit target hash entries directly. + for (hash >::iterator it = target_state.begin(); it != target_state.end(); ++it) { - const int depth = depths[di]; - array list; - target_state.get(depth, &list); + const int depth = it->first; + array list = it->second; if (list.size() == 0) { continue; // removed at the target: stays marked, removed below. @@ -4091,7 +4039,7 @@ namespace gameswf if (backward) { character* ch = m_display_list.get_character_at_depth(depth); - if (ch && placing->is_place_tag()) + if (ch) { place_object_2* p = static_cast(placing); if (ch->get_accept_anim_moves() && p->m_has_matrix) @@ -4128,7 +4076,7 @@ namespace gameswf { if (it->second) { - m_display_list.remove_display_object((Uint16) it->first, -1); + m_display_list.remove_display_object((Uint16) it->first); } } @@ -4145,6 +4093,9 @@ namespace gameswf // The target frame's own playlist through the goto slot (+12): actions queue, the // display tags do nothing, anything else executes. { + // SwiffPlayer.dll 0x100826BC / 0x10082A45: retain the receiver only + // around execute_goto, after placement execution and before the common tail. + smart_ptr this_ptr(this); const array& playlist = m_def->get_playlist(target_frame_number); for (int i = 0; i < playlist.size(); i++) { @@ -4153,31 +4104,52 @@ namespace gameswf } m_current_frame = target_frame_number; + m_next_frame = target_frame_number + 1; m_time_remainder = 0; m_update_frame = false; m_display_list.update(); + SWF_TRACE_GOTO_SWEPT(); on_event(event_id::ENTER_FRAME); do_actions(); } - + + // SwiffPlayer.dll 0x1007FED0: ActionScript navigation queues the label. + void queue_goto_labeled_frame(const char* label) override + { + int target_frame = -1; + if (m_def->get_labeled_frame(label, &target_frame)) + { + goto_frame(target_frame); + } + else + { + log_error("error: movie_impl::goto_labeled_frame('%s') unknown label\n", label); + } + } + bool goto_labeled_frame(const char* label) // Look up the labeled frame, and jump to it. { int target_frame = -1; if (m_def->get_labeled_frame(label, &target_frame)) { - // [DICE-MOD SwiffPlayer #45] applied at once, as the shipped +28 (0x100802E0) - // dispatches straight to +24; the 2006 stop-by-default is kept for the callers - // that rely on it (the AS methods set their own state right after). + // applied at once, as the shipped +28 (0x100802E0) + // dispatches straight to +24 and preserves the play state. ActionScript + // gotoAndStop/gotoAndPlay use the separate queued-label entry above. +#if !defined(_MSC_VER) + if (g_swf_mouse_pass_depth > 0) + { + SWF_LIST_TRACE("gotoLabel '%s' -> '%s'", swf_trace_path(this), label); + } +#endif apply_goto_frame(target_frame); - m_play_state = STOP; return true; } else { - IF_VERBOSE_ACTION( - log_error("error: movie_impl::goto_labeled_frame('%s') unknown label\n", label)); + // SwiffPlayer.dll 0x1008031F logs every failed lookup. + log_error("error: movie_impl::goto_labeled_frame('%s') unknown label\n", label); return false; } } @@ -4194,7 +4166,7 @@ namespace gameswf m_display_list.display(); - do_display_callback(); + // SwiffPlayer.dll 0x1007FCA0 ends after displaying the list. } /*sprite_instance*/ @@ -4219,19 +4191,20 @@ namespace gameswf return NULL; } - // [DICE-MOD SwiffPlayer #44] No "same character already on this plane -> move it - // instead" shortcut. Stock 2006 turned a PLACE whose depth already held the same id (and - // name) into a move_display_object, which re-references the occupant. Flash MX 2004 - // encodes a new keyframe instance of the same symbol as RemoveObject2 + PlaceObject2 on - // one depth in one frame (mainMenu.swf: 337 such sites, none placing over a live - // occupant; e.g. the login container, sprite 402, frame 29 "manage": depths 3 - // profilesList, 46, 48), so the shortcut resurrected the instance the same frame had - // just removed - unmoved, because a script-touched clip rejects anim moves - and the - // login page's list and buttons stayed drawn under the Account Management page. The - // shipped sprite::add_display_object (sub_1007BA80) instantiates unconditionally, and - // its display_list::add_display_object (sub_100A8080) unreferences whatever holds the - // depth (drops the focus if it was inside it, nulls its parent) before inserting; neither - // compares ids or names. + // SwiffPlayer.dll 0x100837E0 keeps an exact referenced occupant, + // without applying the new placement's transforms or handlers. + const int index = m_display_list.find_display_index(depth); + if (index >= 0 && index < m_display_list.get_character_count()) + { + const display_object_info existing = m_display_list.get_display_object(index); + character* old = existing.m_character.get_ptr(); + if (existing.m_ref && old->get_depth() == depth && old->get_id() == character_id + && (name == NULL ? old->get_name().length() == 0 + : strcmp(old->get_name().c_str(), name) == 0)) + { + return old; + } + } assert(cdef); smart_ptr ch = cdef->create_character_instance(this, character_id); @@ -4260,15 +4233,21 @@ namespace gameswf return ch.get_ptr(); } - // [DICE-MOD SwiffPlayer: add an instance of an ARBITRARY definition (an exported symbol for - // attachMovie, a fresh anonymous sprite for createEmptyMovieClip) - the tail of - // add_display_object without the character-id lookup. The shipped player's own - // add_display_object (sub_1007BA80) takes the definition pointer directly.] + // Instantiates a runtime definition without a dictionary lookup. + // SwiffPlayer.dll 0x1007BA80; the native helper supplies default transforms + // and keeps the definition alive through deferred display-list removal. character* add_display_object_def( character_def* cdef, const char* name, Uint16 depth) { + // SwiffPlayer.dll 0x1007BA80 checks the definition before the factory. + if (cdef == NULL) + { + // Retail's diagnostic has an unmatched conversion; retain its format. + log_error("sprite::add_display_object(): cdef = NULL%d\n"); + return NULL; + } assert(cdef); smart_ptr ch = cdef->create_character_instance(this, 0); if (ch == NULL) @@ -4291,12 +4270,12 @@ namespace gameswf true, cxform::identity, matrix::identity, - 0.0f, + 1.0f, 0); return ch.get_ptr(); } - // [DICE-MOD SwiffPlayer: the highest depth in use, -1 when empty - for getNextHighestDepth.] + // the highest depth in use, -1 when empty - for getNextHighestDepth. int get_highest_depth_in_use() { int highest = -1; @@ -4311,54 +4290,55 @@ namespace gameswf return highest; } - // [DICE-MOD SwiffPlayer: the shipped getNextHighestDepth/loadMovie counter semantics - - // return the current value, bump past everything in use.] + // SwiffPlayer.dll 0x1006F960 / 0x1006F9F0 / 0x1007BBF0: + // postincrement without a depth scan. int take_next_highest_depth() { - int d = m_next_highest_depth; - const int in_use = get_highest_depth_in_use() + 1; - if (d < in_use) - { - d = in_use; - } - m_next_highest_depth = d + 1; - return d; + return m_next_highest_depth++; } - // [DICE-MOD SwiffPlayer: the drawing-API canvas (sub_1007C0D0): a `_____defaultShape` child - // at depth 0 over a fresh shape definition, created on first use, mutated by - // lineStyle/moveTo/lineTo/beginFill/endFill.] + // SwiffPlayer.dll 0x1007C0D0 resolves the named canvas through member + // lookup on every call, and creates it at depth zero only when absent. shape_character_def* get_canvas_def() { - if (m_canvas == NULL) + if (this == NULL) return NULL; + as_value canvas; + if (!get_member("_____defaultShape", &canvas)) { m_canvas = new shape_character_def; + m_canvas->set_character_id(0); add_display_object_def(m_canvas.get_ptr(), "_____defaultShape", 0); } + else + { + // [CHOSEN, not recovered] S3 bridge: the native generic + // character carries the definition directly instead of retail +0xC8. + generic_character* ch = static_cast(canvas.to_object()->to_movie()); + m_canvas = static_cast(ch->m_def.get_ptr()); + } return m_canvas.get_ptr(); } - // [DICE-MOD SwiffPlayer: remove every child - the first thing the shipped loadMovie does.] + // remove every child - the first thing the shipped loadMovie does. void remove_all_display_objects() { - array depths; - for (int i = 0, n = m_display_list.get_character_count(); i < n; i++) + // SwiffPlayer.dll 0x1007BC07 walks the live referenced entries. + for (int i = 0; i < m_display_list.get_character_count(); i++) { character* ch = m_display_list.get_character(i); if (ch) { - depths.push_back(ch->get_depth()); + m_display_list.remove_display_object((Uint16) ch->get_depth()); } } - for (int i = 0; i < depths.size(); i++) - { - m_display_list.remove_display_object((Uint16) depths[i], -1); - } + // [CHOSEN, not recovered] S3 bridge: the native canvas owner + // drops its handle after removal; each child still owns its definition. m_canvas = NULL; } /*sprite_instance*/ + // SwiffPlayer.dll 0x1007FCC0. void move_display_object( Uint16 depth, bool use_cxform, @@ -4375,6 +4355,7 @@ namespace gameswf /*sprite_instance*/ + // SwiffPlayer.dll 0x10080490. void replace_display_object( Uint16 character_id, const char* name, @@ -4417,6 +4398,7 @@ namespace gameswf /*sprite_instance*/ + // SwiffPlayer.dll 0x10080540. void replace_display_object( character* ch, const char* name, @@ -4449,15 +4431,16 @@ namespace gameswf /*sprite_instance*/ - void remove_display_object(Uint16 depth, int id) + // SwiffPlayer.dll 0x1007FCD0. + void remove_display_object(Uint16 depth) // Remove the object at the specified depth. // If id != -1, then only remove the object at depth with matching id. { - m_display_list.remove_display_object(depth, id); + m_display_list.remove_display_object(depth); } - /*sprite_instance*/ + // SwiffPlayer.dll 0x10081340. void add_action_buffer(action_buffer* a) // Add the given action buffer to the list of action // buffers to be processed at the end of the next @@ -4490,21 +4473,11 @@ namespace gameswf /* sprite_instance */ + // SwiffPlayer.dll 0x10081F50 has no null-argument refusal path. virtual void set_variable(const char* path_to_var, const char* new_value) { assert(m_parent == NULL); // should only be called on the root movie. - if (path_to_var == NULL) - { - log_error("error: NULL path_to_var passed to set_variable()\n"); - return; - } - if (new_value == NULL) - { - log_error("error: NULL passed to set_variable('%s', NULL)\n", path_to_var); - return; - } - array empty_with_stack; tu_string path(path_to_var); as_value val(new_value); @@ -4513,13 +4486,9 @@ namespace gameswf } /* sprite_instance */ + // SwiffPlayer.dll 0x100820C0 refuses only a null wide value. virtual void set_variable(const char* path_to_var, const wchar_t* new_value) { - if (path_to_var == NULL) - { - log_error("error: NULL path_to_var passed to set_variable()\n"); - return; - } if (new_value == NULL) { log_error("error: NULL passed to set_variable('%s', NULL)\n", path_to_var); @@ -4536,6 +4505,7 @@ namespace gameswf } /* sprite_instance */ + // SwiffPlayer.dll 0x100821D0 returns the shared static value's string storage. virtual const char* get_variable(const char* path_to_var) const { assert(m_parent == NULL); // should only be called on the root movie. @@ -4557,34 +4527,48 @@ namespace gameswf /* sprite_instance */ virtual void set_member(const tu_stringi& name, const as_value& val) - // Set the named member to the value. Return true if we have - // that member; false otherwise. - { - if (m_dead) return; // [DICE-MOD SwiffPlayer #42] - // [DICE-MOD SwiffPlayer #51] sub_10083A20's first act: an "on" member whose name is - // one of the eleven mouse handlers marks the sprite mouse-enabled (its name table, built once: - // onDragOut, onDragOver, onMouseDown, onMouseMove, onMouseUp, onPress, onDoublePress, - // onRelease, onReleaseOutside, onRollOut, onRollOver). The value is not inspected. + // Assign an accessor, display property, matching text field or script member. + { + // SwiffPlayer.dll 0x10083A20, secondary interface 0x100E0C3C +0x20. + // SwiffPlayer.dll 0x10083A49 tries the script object's setter + // before handler detection or built-ins. [CHOSEN, not recovered] + // S3 bridge: adjust the native accessor receiver to the sprite. + if (m_script_object != NULL) + { + if (m_script_object->set_property(name, val, this)) + { + return; + } + } + // The handler-name table is initialized only after the prefix test; + // assigning even an undefined value makes mouse participation sticky. if (!m_mouse_enabled) { const char* s = name.c_str(); if (s[0] == 'o' && s[1] == 'n' && s[2] >= 'A' && s[2] <= 'Z') { - static const char* MOUSE_HANDLER_NAMES[] = { - "onDragOut", "onDragOver", "onMouseDown", "onMouseMove", "onMouseUp", "onPress", - "onDoublePress", "onRelease", "onReleaseOutside", "onRollOut", "onRollOver", - }; - for (int i = 0; i < ARRAYSIZE(MOUSE_HANDLER_NAMES); i++) + static string_hash mouse_handlers; + static bool initialized = false; + if (!initialized) { - if (strcmp(s, MOUSE_HANDLER_NAMES[i]) == 0) - { - m_mouse_enabled = true; - break; - } + static const char* const names[] = { + "onDragOut", "onDragOver", "onMouseDown", "onMouseMove", "onMouseUp", "onPress", + "onDoublePress", "onRelease", "onReleaseOutside", "onRollOut", "onRollOver", + }; + for (int i = 0; i < ARRAYSIZE(names); ++i) + mouse_handlers.set(names[i], true); + initialized = true; } + if (mouse_handlers.get(name.c_str(), NULL)) m_mouse_enabled = true; } } - as_standard_member std_member = get_standard_member(name); + // SwiffPlayer.dll 0x10083F19 controls forced per-pass playback. + if (strcmp(name.c_str(), "maxFPS") == 0) + { + m_force_frame_update = val.to_bool(); + return; + } + as_standard_member std_member = sprite_standard_member(name); switch (std_member) { default: @@ -4594,7 +4578,8 @@ namespace gameswf //if (name == "_x") { matrix m = get_matrix(); - m.m_[0][2] = (float) PIXELS_TO_TWIPS(val.to_number()); + // SwiffPlayer.dll 0x10083FA5: convert before the float store. + m.m_[0][2] = bf2x87::store(bf2x87::mul(bf2x87::Real(val.to_number()), bf2x87::Real(20.0f))); set_matrix(m); m_accept_anim_moves = false; @@ -4605,7 +4590,8 @@ namespace gameswf //else if (name == "_y") { matrix m = get_matrix(); - m.m_[1][2] = (float) PIXELS_TO_TWIPS(val.to_number()); + // SwiffPlayer.dll 0x1008401C. + m.m_[1][2] = bf2x87::store(bf2x87::mul(bf2x87::Real(val.to_number()), bf2x87::Real(20.0f))); set_matrix(m); m_accept_anim_moves = false; @@ -4618,7 +4604,8 @@ namespace gameswf matrix m = get_matrix(); // Decompose matrix and insert the desired value. - float x_scale = (float) val.to_number() / 100.f; // input is in percent + // SwiffPlayer.dll 0x10084094 multiplies by the stored float reciprocal. + float x_scale = bf2x87::store(bf2x87::mul(bf2x87::Real(val.to_number()), bf2x87::Real(0.01f))); float y_scale = m.get_y_scale(); float rotation = m.get_rotation(); m.set_scale_rotation(x_scale, y_scale, rotation); @@ -4634,7 +4621,8 @@ namespace gameswf // Decompose matrix and insert the desired value. float x_scale = m.get_x_scale(); - float y_scale = (float) val.to_number() / 100.f; // input is in percent + // SwiffPlayer.dll 0x1008410E. + float y_scale = bf2x87::store(bf2x87::mul(bf2x87::Real(val.to_number()), bf2x87::Real(0.01f))); float rotation = m.get_rotation(); m.set_scale_rotation(x_scale, y_scale, rotation); @@ -4647,7 +4635,8 @@ namespace gameswf { // Set alpha modulate, in percent. cxform cx = get_cxform(); - cx.m_[3][0] = float(val.to_number()) / 100.f; + // SwiffPlayer.dll 0x100841D4. + cx.m_[3][0] = bf2x87::store(bf2x87::mul(bf2x87::Real(val.to_number()), bf2x87::Real(0.01f))); set_cxform(cx); m_accept_anim_moves = false; return; @@ -4655,42 +4644,40 @@ namespace gameswf case M_VISIBLE: //else if (name == "_visible") { - log_error("[_visible] '%s' = %d\n", swf_trace_path(this), val.to_bool() ? 1 : 0); // [TEMP] RW-88 - set_visible(val.to_bool()); + const bool visible = val.to_bool(); + log_error("[_visible] '%s' = %d\n", swf_trace_path(this), visible ? 1 : 0); // [TEMP] RW-88 + set_visible(visible); m_accept_anim_moves = false; return; } case M_WIDTH: //else if (name == "_width") { - // [DICE-MOD SwiffPlayer #39] Flash: own x-scale = value / the clip's unscaled local extent - // (absolute). Stock divided PIXELS_TO_TWIPS(value) by the WORLD-scaled get_width(), which - // compounded every set by the scale in play: the DICE components read `_width` back and - // hand it to their label fields, so the text layout widths came out up to 3.3x too wide - // (retail run Z vs the golden: version field 208 vs 156, LOGIN 1286 vs 388). A clip - // without extent keeps its scale (stock left it PIXELS_TO_TWIPS(value) - the 1200x - // image clip). See GAMESWF_DIVERGENCES.md #39. - const float local = get_local_width(); - if (fabsf(local) > 1e-6f) + // SwiffPlayer.dll 0x10084261-0x100842F2 repeats conversion and + // extent dispatch; only the division's numerator narrows to float. + matrix m = get_matrix(); + if (val.to_number() == 0.0 || get_width() == 0.0f) m.m_[0][0] = 0.0f; + else { - matrix m = get_matrix(); - m.m_[0][0] = float(PIXELS_TO_TWIPS(val.to_number())) / local; - set_matrix(m); + const float numerator = (float)val.to_number(); + m.m_[0][0] = bf2x87::store(bf2x87::div(bf2x87::Real(numerator), bf2x87::Real(get_width()))); } + set_matrix(m); m_accept_anim_moves = false; return; } case M_HEIGHT: //else if (name == "_height") { - // [DICE-MOD SwiffPlayer #39] as M_WIDTH (stock also divided by get_WIDTH here). - const float local = get_local_height(); - if (fabsf(local) > 1e-6f) + // SwiffPlayer.dll 0x10084320-0x100843A8. + matrix m = get_matrix(); + if (val.to_number() == 0.0 || get_height() == 0.0f) m.m_[1][1] = 0.0f; + else { - matrix m = get_matrix(); - m.m_[1][1] = float(PIXELS_TO_TWIPS(val.to_number())) / local; - set_matrix(m); + const float numerator = (float)val.to_number(); + m.m_[1][1] = bf2x87::store(bf2x87::div(bf2x87::Real(numerator), bf2x87::Real(get_height()))); } + set_matrix(m); m_accept_anim_moves = false; return; } @@ -4702,7 +4689,8 @@ namespace gameswf // Decompose matrix and insert the desired value. float x_scale = m.get_x_scale(); float y_scale = m.get_y_scale(); - float rotation = (float) val.to_number() * float(M_PI) / 180.f; // input is in degrees + // SwiffPlayer.dll 0x10084185 uses the float radians-per-degree constant. + float rotation = bf2x87::store(bf2x87::mul(bf2x87::Real(val.to_number()), bf2x87::Real(0.017453292f))); m.set_scale_rotation(x_scale, y_scale, rotation); set_matrix(m); @@ -4734,6 +4722,15 @@ namespace gameswf } } // end switch + // SwiffPlayer.dll 0x10084421: qword truncation, low dword store, then + // the recursive tab-order dispatch. It does not disable animation moves. + if (strcmp(name.c_str(), "tabIndex") == 0) + { + m_tab_index = bf2x87::lowWord(bf2x87::toInt64Truncate(bf2x87::Real(val.to_number()))); + set_tab_index(m_tab_index); + return; + } + // Not a built-in property. See if we have a // matching edit_text character in our display // list. @@ -4741,15 +4738,15 @@ namespace gameswf || val.get_type() == as_value::NUMBER; if (text_val) { + // SwiffPlayer.dll 0x1008447D converts once before reading the list count. + const char* text = val.to_string(); bool success = false; for (int i = 0, n = m_display_list.get_character_count(); i < n; i++) { character* ch = m_display_list.get_character(i); - // CASE INSENSITIVE compare. In ActionScript 2.0, this - // changes to CASE SENSITIVE!!! - if (ch && name == ch->get_text_name()) + // SwiffPlayer.dll 0x100844B0 compares text names exactly. + if (ch && strcmp(name.c_str(), ch->get_text_name()) == 0) { - const char* text = val.to_string(); ch->set_text_value(text); success = true; } @@ -4757,21 +4754,10 @@ namespace gameswf if (success) return; } - // [DICE-MOD SwiffPlayer #28: a setter on the registered class's prototype chain runs with - // this sprite as `this` - the construct handlers' `__authorMode = false` lands in - // UIObject's __set____authorMode, which stores m_inAuthorMode on the instance.] - if (m_class_proto != NULL) - { - as_object* proto = m_class_proto->cast_to_as_object(); - as_value setter; - if (proto && proto->find_setter(name, &setter)) - { - as_object::invoke_setter(setter, this, val); - return; - } - } - // If that didn't work, set a variable within this environment. - m_as_environment.set_member(name, val); + // SwiffPlayer.dll 0x100844FD writes into the private script object + // when present; only an unbound sprite writes into its environment. + if (m_script_object != NULL) m_script_object->set_member(name, val); + else m_as_environment.set_member(name, val); } @@ -4781,8 +4767,25 @@ namespace gameswf // return true, if we have the named member. // Otherwise leave *val alone and return false. { - if (m_dead) return false; // [DICE-MOD SwiffPlayer #42] a removed clip answers undefined - as_standard_member std_member = get_standard_member(name); + // SwiffPlayer.dll 0x10080590, secondary interface 0x100E0C3C +0x24. + // SwiffPlayer.dll 0x10080590 tests these names before object dispatch. + if (strcmp(name.c_str(), "prototype") == 0) + { + // SwiffPlayer.dll 0x100805C8 retains a temporary before output cleanup. + *val = as_value(m_script_object.get_ptr()); + return true; + } + if (strcmp(name.c_str(), "super") == 0) + { + // SwiffPlayer.dll 0x10080625 uses the same temporary-value assignment. + *val = as_value(m_as_environment.m_super_ctor); + return true; + } + // 0x10080676 calls the private object's member virtual once. + // Its accessor receiver is the private object, unlike the setter's + // explicit sprite receiver. The ordinary lookup also publishes super. + if (m_script_object != NULL && m_script_object->get_member(name, val)) return true; + as_standard_member std_member = sprite_standard_member(name); switch (std_member) { default: @@ -4792,14 +4795,16 @@ namespace gameswf //if (name == "_x") { matrix m = get_matrix(); - val->set_double(TWIPS_TO_PIXELS(m.m_[0][2])); + // SwiffPlayer.dll 0x100806D5 publishes directly as double. + val->set_double(double(m.m_[0][2]) * double(0.05f)); return true; } case M_Y: //else if (name == "_y") { matrix m = get_matrix(); - val->set_double(TWIPS_TO_PIXELS(m.m_[1][2])); + // SwiffPlayer.dll 0x10080737 has no intermediate float store for Y. + val->set_double(double(m.m_[1][2]) * double(0.05f)); return true; } case M_XSCALE: @@ -4807,7 +4812,7 @@ namespace gameswf { matrix m = get_matrix(); // @@ or get_world_matrix()? Test this. float xscale = m.get_x_scale(); - val->set_double(xscale * 100); // result in percent + val->set_double(double(xscale) * 100.0); return true; } case M_YSCALE: @@ -4815,7 +4820,7 @@ namespace gameswf { matrix m = get_matrix(); // @@ or get_world_matrix()? Test this. float yscale = m.get_y_scale(); - val->set_double(yscale * 100); // result in percent + val->set_double(double(yscale) * 100.0); return true; } case M_CURRENTFRAME: @@ -4835,7 +4840,7 @@ namespace gameswf //else if (name == "_alpha") { // Alpha units are in percent. - val->set_double(get_cxform().m_[3][0] * 100.f); + val->set_double(double(get_cxform().m_[3][0]) * 100.0); return true; } case M_VISIBLE: @@ -4847,16 +4852,18 @@ namespace gameswf case M_WIDTH: //else if (name == "_width") { - // [DICE-MOD SwiffPlayer #39] Flash: the clip's unscaled local extent times its own - // x-scale, in pixels - independent of ancestors. Stock measured through the world - // matrix twice (get_width() carries it, enclose_transformed_rect applied it again). - val->set_double(TWIPS_TO_PIXELS(get_local_width() * get_matrix().m_[0][0])); + // SwiffPlayer.dll 0x100808DD snapshots the local matrix before + // the rectangle-based pixel extent and publishes the product as double. + const matrix m = get_matrix(); + val->set_double(bf2x87::storeDouble(bf2x87::mul(bf2x87::Real(get_width()), bf2x87::Real(m.m_[0][0])))); return true; } case M_HEIGHT: //else if (name == "_height") { - val->set_double(TWIPS_TO_PIXELS(get_local_height() * get_matrix().m_[1][1])); + // SwiffPlayer.dll 0x10080936, same ordering for height. + const matrix m = get_matrix(); + val->set_double(bf2x87::storeDouble(bf2x87::mul(bf2x87::Real(get_height()), bf2x87::Real(m.m_[1][1])))); return true; } case M_ROTATION: @@ -4866,9 +4873,8 @@ namespace gameswf float angle = get_matrix().get_rotation(); // Result is CLOCKWISE DEGREES, [-180,180] - angle *= 180.0f / float(M_PI); - - val->set_double(angle); + // SwiffPlayer.dll 0x1008099D publishes the product directly as double. + val->set_double(double(angle) * double(57.29578f)); return true; } case M_TARGET: @@ -4936,12 +4942,18 @@ namespace gameswf matrix m = get_world_matrix(); - point a(PIXELS_TO_TWIPS(x), PIXELS_TO_TWIPS(y)); + // SwiffPlayer.dll 0x10080B9F..0x10080BCD converts the integer + // coordinates before multiplying, then stores each result as float. + point a( + bf2x87::store(bf2x87::mul(bf2x87::Real(x), bf2x87::Real(20.0f))), + bf2x87::store(bf2x87::mul(bf2x87::Real(y), bf2x87::Real(20.0f)))); point b; m.transform_by_inverse(&b, a); - val->set_double(TWIPS_TO_PIXELS(b.m_x)); + // 0x10080BD5 -> 0x10080737 multiplies by the float reciprocal + // and publishes directly as double, without a float result store. + val->set_double(double(b.m_x) * double(0.05f)); return true; } case M_YMOUSE: @@ -4954,71 +4966,56 @@ namespace gameswf matrix m = get_world_matrix(); - point a(PIXELS_TO_TWIPS(x), PIXELS_TO_TWIPS(y)); + // SwiffPlayer.dll 0x10080C21..0x10080C4F, as for _xmouse. + point a( + bf2x87::store(bf2x87::mul(bf2x87::Real(x), bf2x87::Real(20.0f))), + bf2x87::store(bf2x87::mul(bf2x87::Real(y), bf2x87::Real(20.0f)))); point b; m.transform_by_inverse(&b, a); - val->set_double(TWIPS_TO_PIXELS(b.m_y)); + // 0x10080C57 -> 0x10080737 has the same double publication. + val->set_double(double(b.m_y) * double(0.05f)); return true; } case M_PARENT: { + // SwiffPlayer.dll 0x10080CB7 jumps to the null-OBJECT result at 0x10080D75. val->set_as_object_interface(static_cast(m_parent)); return true; } - case M_ONLOAD: + } // end switch + + // SwiffPlayer.dll 0x10080C79: absent tab order leaves the output alone. + if (strcmp(name.c_str(), "tabIndex") == 0) { - if (m_as_environment.get_member(name, val)) - { - return true; - } - // Optimization: if no hit, don't bother looking in the display list, etc. - return false; + if (m_tab_index < 0) return false; + val->set_int(m_tab_index); + return true; } - } // end switch - // Try variables. - if (m_as_environment.get_member(name, val)) + // SwiffPlayer.dll 0x10080CEE returns the character's persistent Array. + if (strcmp(name.c_str(), "arguments") == 0) { + val->set_as_object_interface(m_arguments.get_ptr()); return true; } - // [DICE-MOD SwiffPlayer: the registered class's prototype chain, after the instance's - // own members and before children/builtins - the shipped sprite object resolves its own - // members, then `prototype`, then `__proto__` (sub_10099FE0).] - if (m_class_proto != NULL) + if (strcmp(name.c_str(), "_global") == 0) { - if (name == "__proto__") - { - val->set_as_object_interface(m_class_proto.get_ptr()); - return true; - } - // [DICE-MOD SwiffPlayer #28: a getter on the class prototype chain, with this sprite - // as `this` (a plain prototype lookup would run it with the prototype as `this`).] - { - as_object* proto = m_class_proto->cast_to_as_object(); - as_value getter; - if (proto && proto->find_getter(name, &getter)) - { - *val = as_object::invoke_getter(getter, this); - return true; - } - } - if (m_class_proto->get_member(name, val)) - { - return true; - } + val->set_as_object_interface(get_global_object()); + return true; + } + if (strcmp(name.c_str(), "_root") == 0) + { + // [CHOSEN, not recovered] S3 bridge for retail's global root. + val->set_as_object_interface(get_root_movie()); + return true; } // Not a built-in property. Check items on our // display list. - // [DICE-MOD SwiffPlayer: CASE-SENSITIVE child lookup. Stock 2006 used the _i (case- - // insensitive) variant; the shipped sprite get_member (sub_10080590) walks the display - // list with strcmp, which is the SWF 7 rule BF2's menus (version 7) are written to. With - // the insensitive lookup a child instance named "color" shadowed the Color class, so - // `new Color(mc)` got a movie clip back (retail 2026-09-02, probe: "lookup type=OBJECT (a - // movie clip); _global.Color present"). See GAMESWF_DIVERGENCES.md.] + // SwiffPlayer.dll 0x10080590 compares child names case-sensitively. character* ch = m_display_list.get_character_by_name(tu_string(name.c_str())); if (ch) { @@ -5027,6 +5024,8 @@ namespace gameswf return true; } + // SwiffPlayer.dll 0x10080E1B: environment lookup follows child lookup. + if (m_as_environment.get_member(name, val)) return true; // Try static builtin functions. assert(s_sprite_builtins); if (s_sprite_builtins->get_member(name, val)) @@ -5039,6 +5038,8 @@ namespace gameswf /* sprite_instance */ + // SwiffPlayer.dll 0x10080EA0. The per-tree root is the existing + // [CHOSEN, not recovered] S3 bridge for retail's global root. virtual movie* get_relative_target(const tu_string& name) // Find the movie which is one degree removed from us, // given the relative pathname. @@ -5079,6 +5080,8 @@ namespace gameswf /* sprite_instance */ + // SwiffPlayer.dll 0x10081370 drains all pending actions after each tag, + // including a non-action tag, before inspecting the next playlist entry. virtual void call_frame_actions(const as_value& frame_spec) // Execute the actions for the specified frame. The // frame_spec could be an integer or a string. @@ -5091,13 +5094,14 @@ namespace gameswf if (m_def->get_labeled_frame(frame_spec.to_string(), &frame_number) == false) { // Try converting to integer. - frame_number = (int) frame_spec.to_number(); + frame_number = bf2x87::toIntTruncate(frame_spec.to_number()); } } else { // convert from 1-based to 0-based - frame_number = (int) frame_spec.to_number() - 1; + const Sint32 converted = bf2x87::toIntTruncate(frame_spec.to_number()); + frame_number = bf2x87::lowWord(static_cast(converted) - 1); } if (frame_number < 0 || frame_number >= m_def->get_frame_count()) @@ -5107,8 +5111,6 @@ namespace gameswf return; } - int top_action = m_action_list.size(); - // Execute the actions. const array& playlist = m_def->get_playlist(frame_number); for (int i = 0; i < playlist.size(); i++) @@ -5118,22 +5120,16 @@ namespace gameswf { e->execute(this); } + do_actions(); } - - // Execute any new actions triggered by the tag, - // leaving existing actions to be executed. - while (m_action_list.size() > top_action) - { - m_action_list[top_action]->execute(&m_as_environment); - m_action_list.remove(top_action); - } - assert(m_action_list.size() == top_action); } /* sprite_instance */ virtual void set_drag_state(const drag_state& st) { + // SwiffPlayer.dll 0x1007FCE0 copies the completed record. + // [CHOSEN, not recovered] S3 bridge: use the native per-tree root. m_root->m_drag_state = st; } @@ -5153,6 +5149,8 @@ namespace gameswf } + // SwiffPlayer.dll 0x100815A0; dictionary placement copies transform, + // ratio and clip depth, with no cloned script state or event handlers. void clone_display_object(const tu_string& name, const tu_string& newname, Uint16 depth) // Duplicate the object with the specified name and add it with a new name // at a new depth. @@ -5178,6 +5176,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x1007FD30 performs an exact-name lookup then depth removal. void remove_display_object(const tu_string& name) // Remove the object with the specified name. { @@ -5186,7 +5185,7 @@ namespace gameswf { // @@ TODO: should only remove movies that were created via clone_display_object -- // apparently original movies, placed by anim events, are immune to this. - remove_display_object(ch->get_depth(), ch->get_id()); + remove_display_object(ch->get_depth()); } } @@ -5199,8 +5198,23 @@ namespace gameswf smart_ptr this_ptr(this); bool called = false; + // SwiffPlayer.dll 0x10081620's + // temporary action verbosity for mouse down/up, double press, press/release. + // Event IDs follow the retail event-name table. + const bool enable_verbose = s_verbose_mouse_events && !s_verbose_action + && (id == event_id::MOUSE_DOWN || id == event_id::MOUSE_UP + || id == event_id::DOUBLE_PRESS || id == event_id::PRESS || id == event_id::RELEASE); + if (enable_verbose) s_verbose_action = true; +#if !defined(_MSC_VER) + // [TEMP] c-swf-disconnect: the events a mouse pass fires (press, release, roll over/out). + if (g_swf_mouse_pass_depth > 0 && swf_list_trace_on()) + { + SWF_LIST_TRACE("event %d/%s on '%s' dlist=%d", (int) id.m_id, id.get_function_name().c_str(), + swf_trace_path(this), m_display_list.get_character_count()); + } +#endif - // [DICE-MOD SwiffPlayer #51] sub_10081620: the clip-event handler when there is one, ELSE + // sub_10081620: the clip-event handler when there is one, ELSE // the member of that name, and only a defined one. Stock 2006 called both when both existed. { as_value method; @@ -5225,147 +5239,116 @@ namespace gameswf } } } +#if !defined(_MSC_VER) + if (called && g_swf_mouse_pass_depth > 0 && swf_list_trace_on()) + { + SWF_LIST_TRACE("event %d/%s done on '%s' dlist=%d", (int) id.m_id, id.get_function_name().c_str(), + swf_trace_path(this), m_display_list.get_character_count()); + } +#endif + // SwiffPlayer.dll 0x10081808 restores verbosity before releasing this_ptr. + if (enable_verbose) s_verbose_action = false; return called; } /*sprite_instance*/ virtual void on_event_load() - // Do the events that (appear to) happen as the movie - // loads. frame1 tags and actions are executed (even - // before advance() is called). Then the onLoad event - // is triggered. + // Run definition initialization and frame-zero placement, then bind a class. { - execute_frame_tags(0); - // [DICE-MOD SwiffPlayer #53] The shipped on_event_load (sub_10081870, sprite vtable - // slot 51, called by display_list::add_display_object right after the insert) runs - // the pending init actions, executes frame 0's tags (sub_10081B10 - the placements - // happen now) and then FREES the action list at +224: the frame-0 DoAction buffers - // that execute_frame_tags just queued are dropped. The script runs when the sprite's - // first advance (0x10081CF0: next_frame 0, `first_frame_initialized` false) executes - // frame 0 again and drains the queue - and that advance comes AFTER the placing - // parent's own frame script, because the shipped pass advances its display list - // (sub_100A82A0) after its execute_frame_tags / do_actions. Stock 2006 drained the - // queue right here, so a child's frame-0 script ran BEFORE the parent's frame script - // of the same frame. mainMenu.swf's JOIN INTERNET page depends on the shipped order: - // the page's frame script defines getIsBrowsed / setIsBrowsed and the refresh modal - // placed on that frame calls them from its own frame-0 script; on the stock order - // they were "can't find method", the modal's setIsBrowsed was lost, and the modal - // started a SECOND browse when its script ran again (the owner's "server list loads - // twice", 2026-09-14). [CHOSEN, not recovered]: the shipped re-executes frame 0's - // PLACEMENTS too on that first advance (replacing the instances made here); this port - // keeps the instances and re-runs only the DoAction tags - see advance_pass. - m_action_list.clear(); - m_first_frame_actions_pending = true; - // [DICE-MOD SwiffPlayer #27: after the frame-0 tags, before onLoad - prototype, the - // construct handlers (component parameters), the class constructor, initialize, load.] - bind_class_prototype(); - on_event(event_id::CONSTRUCT); - run_class_constructor(); - on_event(event_id::INITIALIZE); - on_event(event_id::LOAD); - } - - // [DICE-MOD SwiffPlayer: Object.registerClass support. The shipped load path - // (sub_10081870) does, for an instance whose definition carries a registered class: - // instance.__proto__ = Class.prototype (the function's +40 prototype object) - // instance.__constructor__ = Class - // Class.call(instance) (the constructor runs with the sprite as - // `this`, in the sprite's own environment) - // once, right after the frame-0 tags. Stock 2006 sprites have no prototype chain at all, so - // every attached UI component stayed a bare MovieClip (retail 2026-09-02: "can't find - // method loadImg/setValue/registerCallback" on every menu component, timeline parked).] - // [DICE-MOD SwiffPlayer #27] The binding comes in two halves. The prototype is attached - // first, so the `construct` clip handlers (component-inspector parameters such as - // `__authorMode = false`) reach the class's addProperty setters; the constructor runs after - // them, as Flash 7 orders it (construct -> constructor -> initialize -> load). - void bind_class_prototype() - { - if (m_class_bound || m_def == NULL || m_def->m_registered_class == NULL) + // SwiffPlayer.dll 0x10081870 executes pending definition-wide + // init actions before frame zero and clears each bit after execution. + const array* init_actions = m_def->get_init_actions(0); + for (int i = 0; i < init_actions->size(); ++i) { - return; + if (m_root->m_def->m_init_action_pending[i]) + { + execute_init_action((*init_actions)[i], &m_as_environment); + m_root->m_def->m_init_action_pending[i] = false; + } } - m_class_bound = true; - - as_as_function* cls = static_cast(m_def->m_registered_class); - cls->lazy_create_properties(); - as_value proto; - if (cls->m_properties) + execute_frame_tags(0); + // SwiffPlayer.dll 0x10081870 discards frame-zero actions here; + // advance replays the complete playlist after the parent's actions. + m_action_list.clear(); + // SwiffPlayer.dll 0x10081870 sends CONSTRUCT only when a sprite other + // than the published global root has a class prototype. It sends + // neither INITIALIZE nor LOAD. + // 0x1008191D captures the registered function once. CONSTRUCT can + // replace the definition binding; the subsequent call still uses this one. + // [CHOSEN, not recovered] S3 bridge: hold the native function alive + // across callbacks, since native definitions own their class bindings. + smart_ptr cls; + // 0x10081911 compares directly with the global publication, even + // when another movie has replaced this sprite's own tree root. + if (this != get_global_root_movie()) { - cls->m_properties->get_member("prototype", &proto); + sprite_definition* sprite_def = sprite_definition_of(m_def.get_ptr()); + cls = sprite_def ? static_cast(sprite_def->m_registered_class) : NULL; } - m_class_proto = proto.to_object(); - m_as_environment.set_member("__constructor__", as_value(cls)); - } - - void run_class_constructor() - { - if (m_class_ctor_run || !m_class_bound || m_def == NULL || m_def->m_registered_class == NULL) + if (cls != NULL && cls->m_properties->m_instance_prototype != NULL) { - return; + bind_class_prototype(cls.get_ptr()); + on_event(event_id::CONSTRUCT); + const as_value constructor(cls.get_ptr()); + call_method0(constructor, &m_as_environment, this); } - m_class_ctor_run = true; - as_value ctor(static_cast(m_def->m_registered_class)); - call_method0(ctor, &m_as_environment, this); } - void bind_registered_class() + // Read the current prototype's constructor without script-visible lookup. + as_as_function* class_prototype_constructor(as_as_function* cls) { - bind_class_prototype(); - run_class_constructor(); + // SwiffPlayer.dll 0x10081A12 / 0x10081A7E read concrete fields, + // without a script-visible "prototype" or "__constructor__" lookup. + as_object* class_proto = cls->m_properties->m_instance_prototype->cast_to_as_object(); + // [CHOSEN, not recovered] A movie clip as class prototype supplies no constructor. + // Retail reads the field at the clip's secondary-interface offset, unrelated movie + // state, and publishes it as __constructor__ and the super target; only super() would + // use it. Retail 1.50 binds the instance, runs the registered class once and links the + // clip as its __proto__ (probe v2 tests 4, 7, 8 green; no fault). + if (class_proto == NULL) return NULL; + return class_proto->m_constructor.get_ptr(); } - // Do the events that happen when there is XML data waiting - // on the XML socket connection. - virtual void on_event_xmlsocket_onxml() + void bind_class_prototype(as_as_function* cls) { - log_msg("FIXME: %s: unimplemented\n", __FUNCTION__); - on_event(event_id::SOCK_XML); - } - - // Do the events that (appear to) happen on a specified interval. - virtual void on_event_interval_timer() - { - log_msg("FIXME: %s: unimplemented\n", __FUNCTION__); - on_event(event_id::TIMER); + // SwiffPlayer.dll 0x10081870 owns an instance bag, links its prototype + // and records its movie owner before running construct/constructor. + m_script_object = new as_object; + m_script_object->set_member("_____owner", as_value(this)); + m_script_object->set_member("__proto__", as_value(cls->m_properties->m_instance_prototype)); + m_script_object->set_member("__constructor__", + as_value(class_prototype_constructor(cls))); + // SwiffPlayer.dll 0x10081A84 reads the prototype again after the + // member write, then publishes its borrowed constructor before CONSTRUCT. + set_call_super(class_prototype_constructor(cls)); } - // Do the events that happen as a MovieClip (swf 7 only) loads. - virtual void on_event_load_progress() + // SwiffPlayer.dll 0x10080390 / 0x10080330 retain the receiver through + // the parser and drop that reference before returning its shared text. + const char* call_method(const Uint16* expression) override { - log_msg("FIXME: %s: unimplemented\n", __FUNCTION__); - on_event(event_id::LOAD_PROGRESS); + smart_ptr receiver(this); + return call_method_expression(&m_as_environment, this, expression); } - - /*sprite_instance*/ - virtual const char* call_method_args(const char* method_name, const char* method_arg_fmt, va_list args) + const char* call_method(const char* expression) override { - // Keep m_as_environment alive during any method calls! - smart_ptr this_ptr(this); - - return call_method_parsed(&m_as_environment, this, method_name, method_arg_fmt, args); + smart_ptr receiver(this); + return call_method_expression(&m_as_environment, this, expression); } /* sprite_instance */ - virtual void attach_display_callback(const char* path_to_object, void (*callback)(void*), void* user_ptr) - { - assert(m_parent == NULL); // should only be called on the root movie. - - array dummy; - as_value obj = m_as_environment.get_variable(tu_string(path_to_object), dummy); - as_object_interface* as_obj = obj.to_object(); - if (as_obj) - { - movie* m = as_obj->to_movie(); - if (m) - { - m->set_display_callback(callback, user_ptr); - } - } - } }; + // SwiffPlayer.dll 0x100737A0; the native root always owns a sprite instance. + void movie_root::goto_frame(int target_frame_number) + { + static_cast(m_movie.get_ptr())->apply_goto_frame(target_frame_number); + } + + // SwiffPlayer.dll 0x100849A0; the native factory returns a borrowed raw + // pointer instead of retail's smart_ptr result [CHOSEN, not recovered] S3 bridge. character* sprite_definition::create_character_instance(movie* parent, int id) // Create a (mutable) instance of our definition. The // instance is created to live (temporarily) on some level on @@ -5377,6 +5360,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x10084A30. movie_interface* movie_def_impl::create_instance() // Create a playable movie instance from a def. { @@ -5387,6 +5371,10 @@ namespace gameswf assert(root_movie); root_movie->set_name("_root"); + // 0x10084A85..0x10084AC3 publishes after naming and before retaining + // the returned wrapper. Its inline assignment matches 0x100738A0. + set_global_root_movie(root_movie); + // [CHOSEN, not recovered] S3 bridge: the native wrapper also owns its sprite. m->set_root_movie(root_movie); m->add_ref(); @@ -5394,17 +5382,18 @@ namespace gameswf } + // SwiffPlayer.dll 0x1007BB50. void sprite_loader(stream* in, int tag_type, movie_definition_sub* m) // Create and initialize a sprite, and add it to the movie. { assert(tag_type == 39); + IF_VERBOSE_PARSE(log_msg("sprite\n")); int character_id = in->read_u16(); - IF_VERBOSE_PARSE(log_msg(" sprite\n char id = %d\n", character_id)); - - sprite_definition* ch = new sprite_definition(m); // @@ combine sprite_definition with movie_def_impl + sprite_definition* ch = new sprite_definition(m, character_id); ch->read(in); + IF_VERBOSE_PARSE(log_msg("sprite: char id = %d\n", character_id)); m->add_character(character_id, ch); } @@ -5415,7 +5404,7 @@ namespace gameswf // // ============================================================================================= - // [DICE-MOD SwiffPlayer: the MovieClip methods the shipped sprite builtins object + // the MovieClip methods the shipped sprite builtins object // (gameswf_standard_method_map_init, dword_100F8C98) carries and stock 2006 lacks. BF2's menu // class framework builds every component with them. Each is reconstructed from the named // shipped body: @@ -5425,15 +5414,16 @@ namespace gameswf // attachMovie(symbol, name, depth) gameswf_sprite_attach_movie - the root definition's // exported symbol, instanced at `depth`; three or more args. // getNextHighestDepth() gameswf_sprite_getNextHighestDepth - a per-sprite counter - // returned then incremented (+220); ours also skips depths - // the timeline already occupies. + // returned then incremented (+220). // removeMovieClip() gameswf_sprite_remove_movieclip - parent->remove(depth). // setMask(mc) gameswf_sprite_set_mask - mask stored on the character, // mask flagged mask-only (+192/+196); one argument. - // See GAMESWF_DIVERGENCES.md.] + // See GAMESWF_DIVERGENCES.md. // ============================================================================================= static sprite_instance* sprite_this(const fn_call& fn) { + // [CHOSEN, not recovered] S3 bridge: the 2006 native-call API can + // omit this_ptr; its environment target supplies the retail receiver. sprite_instance* sprite = (sprite_instance*) fn.this_ptr; if (sprite == NULL) { @@ -5444,6 +5434,7 @@ namespace gameswf return sprite; } + // SwiffPlayer.dll 0x1007BFD0; sprite_this supplies the native receiver bridge. void sprite_create_empty_movieclip(const fn_call& fn) { if (fn.nargs != 2) @@ -5451,22 +5442,16 @@ namespace gameswf log_error("error: create_empty_movieclip needs two args\n"); return; } + const tu_string name = fn.arg(0).to_tu_string(); + const int depth = bf2x87::toIntTruncate(fn.arg(1).to_number()); sprite_instance* sprite = sprite_this(fn); if (sprite == NULL) { return; } - const tu_string name = fn.arg(0).to_tu_string(); - const int depth = (int) fn.arg(1).to_number(); - - movie* root = sprite->get_root_movie(); - movie_definition_sub* root_def = root - ? static_cast(root->get_movie_definition()) : NULL; - if (root_def == NULL) - { - fn.result->set_as_object_interface(NULL); - return; - } + // [CHOSEN, not recovered] S3 bridge: per-tree root replaces the + // retail global movie root, through the native typed interface. + movie_definition_sub* root_def = static_cast(sprite->get_root()->get_movie_definition()); // A one-frame, empty sprite definition owned by the instance (its m_def smart_ptr). sprite_definition* def = new sprite_definition(root_def); def->m_frame_count = 1; @@ -5478,6 +5463,7 @@ namespace gameswf fn.result->set_as_object_interface(ch); } + // SwiffPlayer.dll 0x10075A40 uses the exported definition's dictionary ID. void sprite_attach_movie(const fn_call& fn) { if (fn.nargs < 3) @@ -5485,32 +5471,32 @@ namespace gameswf log_error("error: attach_movie needs atleast three args\n"); return; } + const tu_string symbol = fn.arg(0).to_tu_string(); + const tu_string name = fn.arg(1).to_tu_string(); + const int depth = bf2x87::toIntTruncate(fn.arg(2).to_number()); sprite_instance* sprite = sprite_this(fn); if (sprite == NULL) { return; } - const tu_string symbol = fn.arg(0).to_tu_string(); - const tu_string name = fn.arg(1).to_tu_string(); - const int depth = (int) fn.arg(2).to_number(); - - movie* root = sprite->get_root_movie(); - movie_definition_sub* root_def = root - ? static_cast(root->get_movie_definition()) : NULL; - smart_ptr res = root_def ? root_def->get_exported_resource(symbol) : smart_ptr(); - character_def* cdef = res.get_ptr() ? res->cast_to_character_def() : NULL; - if (cdef == NULL) + // [CHOSEN, not recovered] S3 bridge: native per-tree root accessor. + movie_definition_sub* root_def = static_cast(sprite->get_root()->get_movie_definition()); + smart_ptr res = root_def->get_exported_resource(symbol); + if (res == NULL) { - log_error("error: attachMovie: no exported symbol '%s'\n", symbol.c_str()); *fn.result = as_value(); return; } - character* ch = sprite->add_display_object_def(cdef, name.c_str(), (Uint16) depth); + character_def* cdef = res->cast_to_character_def(); + array handlers; + character* ch = sprite->add_display_object(cdef->get_character_id(), name.c_str(), handlers, + static_cast(depth), true, cxform::identity, matrix::identity, 1.0f, 0); // [TEMP] RW-89 target trace. Remove with the tracers. log_error("[attachMovie] on '%s' symbol='%s' -> '%s' depth=%d ch=%p\n", swf_trace_path(sprite), symbol.c_str(), name.c_str(), depth, ch); fn.result->set_as_object_interface(ch); } + // SwiffPlayer.dll 0x1006F9F0; sprite_this is the existing native receiver bridge. void sprite_get_next_highest_depth(const fn_call& fn) { sprite_instance* sprite = sprite_this(fn); @@ -5518,16 +5504,32 @@ namespace gameswf { return; } - int d = sprite->m_next_highest_depth; - const int in_use = sprite->get_highest_depth_in_use() + 1; - if (d < in_use) + fn.result->set_int(sprite->take_next_highest_depth()); + } + + // SwiffPlayer.dll 0x10075950 copies only the definition, transform and ratio, + // placing in the root at the supplied depth plus 100. It ignores extra arguments. + void sprite_duplicate_movieclip(const fn_call& fn) + { + if (fn.nargs < 2) { - d = in_use; + log_error("error: duplicate_movie_clip needs atleast two args\n"); + return; } - sprite->m_next_highest_depth = d + 1; - fn.result->set_int(d); + const tu_string name = fn.arg(0).to_tu_string(); + const Uint32 depth = static_cast(bf2x87::toIntTruncate(fn.arg(1).to_number())) + 100u; + // [CHOSEN, not recovered] S3 bridge: typed receiver and per-tree root + // replace the secondary-interface receiver and retail global root. + sprite_instance* sprite = sprite_this(fn); + sprite_instance* root = static_cast(sprite->get_root_movie()); + array handlers; + sprite_definition* sprite_def = sprite_definition_of(sprite->m_def.get_ptr()); // root: ID 0 + character* ch = root->add_display_object(sprite_def ? sprite_def->get_character_id() : 0, name.c_str(), handlers, + static_cast(depth), true, sprite->get_cxform(), sprite->get_matrix(), sprite->get_ratio(), 0); + fn.result->set_as_object_interface(ch); } + // SwiffPlayer.dll 0x1006F9C0 only requests deferred removal from the parent. void sprite_remove_movieclip(const fn_call& fn) { sprite_instance* sprite = sprite_this(fn); @@ -5538,18 +5540,63 @@ namespace gameswf movie* parent = sprite->get_parent(); log_error("[removeMovieClip] '%s' depth=%d parent=%p\n", // [TEMP] RW-88 nav tracer swf_trace_path(sprite), sprite->get_depth(), parent); + SWF_LIST_TRACE("removeMovieClip '%s' depth=%d", swf_trace_path(sprite), sprite->get_depth()); if (parent) { - // Keep the instance alive across its own removal - the caller may still be running - // one of its methods. - smart_ptr keep(sprite); - parent->remove_display_object((Uint16) sprite->get_depth(), -1); + parent->remove_display_object((Uint16) sprite->get_depth()); + } + } + + // SwiffPlayer.dll 0x10071A30. sprite_this and the per-tree root adapt + // retail's secondary receiver and global root [CHOSEN, not recovered] S3 bridge. + void sprite_start_drag(const fn_call& fn) + { + sprite_instance* sprite = sprite_this(fn); + movie::drag_state st; + st.m_character = sprite; + if (fn.nargs > 0) st.m_lock_center = fn.arg(0).to_bool(); + if (!st.m_lock_center) + { + int x, y, buttons; + sprite->get_root_movie()->get_mouse_state(&x, &y, &buttons); + matrix world = sprite->get_world_matrix(); + point local; + const float world_x = bf2x87::store(bf2x87::mul(bf2x87::Real(x), bf2x87::Real(20.0f))); + const float world_y = bf2x87::store(bf2x87::mul(bf2x87::Real(y), bf2x87::Real(20.0f))); + world.transform_by_inverse(&local, point(world_x, world_y)); + st.m_offset_x = local.m_x; + st.m_offset_y = local.m_y; + } + if (fn.nargs == 5) + { + st.m_bound = true; + st.m_bound_x0 = bf2x87::store(bf2x87::mul(bf2x87::Real(fn.arg(1).to_number()), bf2x87::Real(20.0f))); + st.m_bound_y0 = bf2x87::store(bf2x87::mul(bf2x87::Real(fn.arg(2).to_number()), bf2x87::Real(20.0f))); + st.m_bound_x1 = bf2x87::store(bf2x87::mul(bf2x87::Real(fn.arg(3).to_number()), bf2x87::Real(20.0f))); + st.m_bound_y1 = bf2x87::store(bf2x87::mul(bf2x87::Real(fn.arg(4).to_number()), bf2x87::Real(20.0f))); + } + if (sprite != NULL) + { + sprite->set_drag_state(st); } } + // SwiffPlayer.dll 0x10071B90: a clip stops only its own drag. + void sprite_stop_drag(const fn_call& fn) + { + // [CHOSEN, not recovered] S3 bridge: native receiver/per-tree root. + sprite_instance* sprite = sprite_this(fn); + movie_root* root = sprite->get_root(); + movie::drag_state st; + root->get_root_movie()->get_drag_state(&st); + if (st.m_character == sprite) root->stop_drag(); + } + + // SwiffPlayer.dll 0x10071C00. [CHOSEN, not recovered] S3 bridge: + // the native mask remains owning for issue #7 teardown; retail writes a raw pointer. void sprite_set_mask(const fn_call& fn) { - if (fn.nargs < 1) + if (fn.nargs == 0) { log_error("error: set_mask needs one arg\n"); return; @@ -5562,15 +5609,11 @@ namespace gameswf as_object_interface* o = fn.arg(0).to_object(); movie* mv = o ? o->to_movie() : NULL; character* mask = mv ? mv->cast_to_character() : NULL; - sprite->m_mask = mask; - if (mask) - { - mask->m_is_mask_only = true; - } + sprite->set_mask(mask); } // ============================================================================================= - // [DICE-MOD SwiffPlayer: the DRAWING API and the IMAGE LOADER of the shipped sprite builtins, + // the DRAWING API and the IMAGE LOADER of the shipped sprite builtins, // reconstructed from the named bodies (coordinates in script pixels, x20 to twips): // lineStyle(thickness, rgb, alpha) gameswf_sprite_line_style - width = thickness*20, never 0 // (20 when unset), colour from rgb + alpha*2.55 (255 when @@ -5586,9 +5629,8 @@ namespace gameswf // fill0 = that style. // endFill() gameswf_sprite_end_fill - closes the current path back to // its start when the pen is elsewhere; bound recomputed. - // beginGradientFill(...) gameswf_sprite_begin_gradient_fill - NOT transcribed - // (a 1.4 KB gradient-matrix builder); logged, falls back to - // a solid fill of the first colour. + // beginGradientFill(...) gameswf_sprite_begin_gradient_fill - five arguments, + // box matrix, linear/radial bitmap and two new paths. // loadMovie(url) gameswf_sprite_loadmovie - removes every child, resolves // the image by name (render::create_bitmap_info_file), and // places a `_____image` sprite at the next depth holding a @@ -5597,12 +5639,15 @@ namespace gameswf // the golden run's 320x240 background strip // (setTexture id=24 320x240 clamp=0 m=[0.05 0 0|0 0.05 0]). // A path's pen position and style inheritance follow the shipped "new path" helper - // (sub_10076A80): the new path copies fill0/fill1/line and starts at the last anchor.] + // (sub_10076A80): the new path copies fill0/fill1/line and starts at the last anchor. // ============================================================================================= static rgba rgba_from_script(double rgb, double alpha_pct, bool has_alpha) { - const int c = (int) rgb; - const Uint8 a = has_alpha ? (Uint8) (int) (alpha_pct * 2.55) : 255; + // SwiffPlayer.dll 0x1007C318/0x1007C9B1 uses a dword for RGB; + // alpha uses a qword conversion and keeps its low byte. + const int c = bf2x87::toIntTruncate(rgb); + const Uint8 a = has_alpha ? static_cast(bf2x87::toInt64Truncate( + bf2x87::mul(bf2x87::Real(alpha_pct), bf2x87::Real(2.55)))) : 255; return rgba((Uint8) ((c >> 16) & 0xFF), (Uint8) ((c >> 8) & 0xFF), (Uint8) (c & 0xFF), a); } @@ -5624,87 +5669,107 @@ namespace gameswf } } - // The shipped "new path" (sub_10076A80): inherit the current styles, start at the pen. + // SwiffPlayer.dll 0x10076A80: copy the current path, clear its edges, + // and start at its final anchor. An empty canvas receives a marker first. static path* canvas_new_path(shape_character_def* def) { path np; const path* cur = def->current_path(); if (cur) { - np.m_fill0 = cur->m_fill0; - np.m_fill1 = cur->m_fill1; - np.m_line = cur->m_line; + np = *cur; + np.m_edges.clear(); canvas_pen(cur, &np.m_ax, &np.m_ay); } - return def->add_path(np); + else + { + path marker; + marker.m_new_shape = true; + def->append_path(marker); + } + def->append_path(np); + return def->current_path(); } + // SwiffPlayer.dll 0x1007C930. With no arguments the shipped body still + // assigns line slot one, even when no style has been appended. void sprite_line_style(const fn_call& fn) { sprite_instance* sprite = sprite_this(fn); if (sprite == NULL) return; shape_character_def* def = sprite->get_canvas_def(); - int idx = 0; + int idx = 1; if (fn.nargs > 0) { - int width = (int) (fn.arg(0).to_number() * 20.0); + Uint16 width = static_cast(bf2x87::toInt64Truncate( + bf2x87::mul(bf2x87::Real(fn.arg(0).to_number()), bf2x87::Real(20.0)))); if (width == 0) width = 20; rgba color(0, 0, 0, 255); if (fn.nargs > 1) { - color = rgba_from_script(fn.arg(1).to_number(), fn.nargs > 2 ? fn.arg(2).to_number() : 100.0, fn.nargs > 2); + const double rgb = fn.arg(1).to_number(); + const double alpha = fn.nargs > 2 ? fn.arg(2).to_number() : 100.0; + color = rgba_from_script(rgb, alpha, fn.nargs > 2); } - line_style ls; - ls.set((Uint16) width, color); - idx = def->add_line_style(ls); + idx = def->add_line_style(color, width) + 1; } canvas_new_path(def)->m_line = idx; } + // SwiffPlayer.dll 0x1007CB60 creates/resolves the canvas even on bad arity. void sprite_move_to(const fn_call& fn) { + sprite_instance* sprite = sprite_this(fn); + if (sprite == NULL) return; + shape_character_def* def = sprite->get_canvas_def(); if (fn.nargs != 2) { log_error("error: move_to needs two args\n"); return; } - sprite_instance* sprite = sprite_this(fn); - if (sprite == NULL) return; - shape_character_def* def = sprite->get_canvas_def(); const float x = (float) (fn.arg(0).to_number() * 20.0); const float y = (float) (fn.arg(1).to_number() * 20.0); path* cur = def->current_path(); - if (cur == NULL || cur->m_edges.size() > 0) + if (cur != NULL && cur->m_edges.size() == 0) { - cur = canvas_new_path(def); + cur->m_ay = y; + cur->m_ax = x; + return; } - cur->m_ax = x; - cur->m_ay = y; + // 0x1007CBED stores only Y into the new path's X start. Preserve + // this shipped defect; the inherited Y start is left alone. + canvas_new_path(def)->m_ax = y; } + // SwiffPlayer.dll 0x1007CA20 stores the X delta as float before computing Y. void sprite_line_to(const fn_call& fn) { + sprite_instance* sprite = sprite_this(fn); + if (sprite == NULL) return; + shape_character_def* def = sprite->get_canvas_def(); if (fn.nargs != 2) { log_error("error: line_to needs two args\n"); return; } - sprite_instance* sprite = sprite_this(fn); - if (sprite == NULL) return; - shape_character_def* def = sprite->get_canvas_def(); path* cur = def->current_path(); - if (cur == NULL) - { - cur = canvas_new_path(def); - } float px, py; canvas_pen(cur, &px, &py); - const float x = (float) (fn.arg(0).to_number() * 20.0); - const float y = (float) (fn.arg(1).to_number() * 20.0); - cur->m_edges.push_back(edge(px + (x - px) * 0.5f, py + (y - py) * 0.5f, x, y)); - def->refresh_bound(); + const float dx = bf2x87::store(bf2x87::sub( + bf2x87::mul(bf2x87::Real(fn.arg(0).to_number()), bf2x87::Real(20.0)), bf2x87::Real(px))); + const bf2x87::Real dy = bf2x87::sub( + bf2x87::mul(bf2x87::Real(fn.arg(1).to_number()), bf2x87::Real(20.0)), bf2x87::Real(py)); + cur->m_edges.push_back(edge( + bf2x87::store(bf2x87::add(bf2x87::mul(bf2x87::Real(dx), bf2x87::Real(0.5f)), bf2x87::Real(px))), + bf2x87::store(bf2x87::add(bf2x87::mul(dy, bf2x87::Real(0.5f)), bf2x87::Real(py))), + bf2x87::store(bf2x87::add(bf2x87::Real(dx), bf2x87::Real(px))), + bf2x87::store(bf2x87::add(bf2x87::Real(py), dy)))); + rect bound; + def->compute_bound(&bound); + def->set_bound(bound); } + // SwiffPlayer.dll 0x1007C1D0. void sprite_end_fill(const fn_call& fn) { sprite_instance* sprite = sprite_this(fn); @@ -5715,15 +5780,23 @@ namespace gameswf { float px, py; canvas_pen(cur, &px, &py); - if (px != cur->m_ax || py != cur->m_ay) + const bf2x87::Real dx = bf2x87::sub(bf2x87::Real(cur->m_ax), bf2x87::Real(px)); + const bf2x87::Real dy = bf2x87::sub(bf2x87::Real(cur->m_ay), bf2x87::Real(py)); + if (dx != bf2x87::Real(0) || dy != bf2x87::Real(0)) { - cur->m_edges.push_back(edge(px + (cur->m_ax - px) * 0.5f, py + (cur->m_ay - py) * 0.5f, - cur->m_ax, cur->m_ay)); + cur->m_edges.push_back(edge( + bf2x87::store(bf2x87::add(bf2x87::mul(dx, bf2x87::Real(0.5f)), bf2x87::Real(px))), + bf2x87::store(bf2x87::add(bf2x87::mul(dy, bf2x87::Real(0.5f)), bf2x87::Real(py))), + bf2x87::store(bf2x87::add(dx, bf2x87::Real(px))), + bf2x87::store(bf2x87::add(dy, bf2x87::Real(py))))); } } - def->refresh_bound(); + rect bound; + def->compute_bound(&bound); + def->set_bound(bound); } + // SwiffPlayer.dll 0x1007C2C0 appends a marker and a fresh fill-only path. void sprite_begin_fill(const fn_call& fn) { sprite_end_fill(fn); @@ -5733,55 +5806,120 @@ namespace gameswf int idx = 0; if (fn.nargs > 0) { - fill_style fs; - fs.set_solid(rgba_from_script(fn.arg(0).to_number(), fn.nargs > 1 ? fn.arg(1).to_number() : 100.0, fn.nargs > 1)); - idx = def->add_fill_style(fs); + const double rgb = fn.arg(0).to_number(); + const double alpha = fn.nargs > 1 ? fn.arg(1).to_number() : 100.0; + idx = def->add_fill_style(rgba_from_script(rgb, alpha, fn.nargs > 1)) + 1; } // the shipped pair: a "new shape" marker path, then the path that carries the fill path marker; marker.m_new_shape = true; - def->add_path(marker); + def->append_path(marker); path p; p.m_fill0 = idx; - def->add_path(p); + def->append_path(p); } + // SwiffPlayer.dll 0x1007C3B0. void sprite_begin_gradient_fill(const fn_call& fn) { - log_error("beginGradientFill: gradients are not transcribed yet - filling with the first colour\n"); - sprite_end_fill(fn); - sprite_instance* sprite = sprite_this(fn); - if (sprite == NULL) return; - shape_character_def* def = sprite->get_canvas_def(); - int idx = 0; - if (fn.nargs >= 2) + if (fn.nargs != 5) { - // arg1 is the colours array; take its first element - as_object_interface* colors = fn.arg(1).to_object(); - as_value first; - if (colors) colors->get_member("0", &first); - fill_style fs; - fs.set_solid(rgba_from_script(first.to_number(), 100.0, false)); - idx = def->add_fill_style(fs); + log_error("error: line_to needs five args\n"); + return; } - path marker; - marker.m_new_shape = true; - def->add_path(marker); - path p; - p.m_fill0 = idx; - def->add_path(p); + as_object_interface* box = fn.arg(4).get_type() == as_value::OBJECT + ? fn.arg(4).m_object_value : NULL; + as_value value; + matrix input; + if (!box->get_member("matrixType", &value) + || std::strcmp(value.to_string(), "box") != 0) return; + box->get_member("x", &value); + const float x = (float)value.to_number(); + box->get_member("y", &value); + const float y = (float)value.to_number(); + box->get_member("w", &value); + const float width = (float)value.to_number(); + box->get_member("h", &value); + const float height = (float)value.to_number(); + box->get_member("r", &value); + const float rotation = (float)value.to_number(); + input.m_[0][2] = (float)(((long double)width * 0.5f + x) * 20.0f); + input.m_[1][2] = (float)(((long double)height * 0.5f + y) * 20.0f); + input.m_[0][0] = (float)(1.0L / (32768.0f / ((long double)width * 20.0f))); + input.m_[1][1] = (float)(1.0L / (32768.0f / ((long double)height * 20.0f))); + + fill_style style; + matrix gradient; + const tu_string kind(fn.arg(0).to_string()); + int type = style.get_type(); + if (kind == "linear") + { + gradient.set_identity(); + gradient.m_[0][2] = 128.0f; + gradient.m_[1][2] = 0.0f; + gradient.set_scale_rotation(1.0f / 128.0f, 1.0f / 128.0f, -rotation); + type = 0x10; + } + else if (kind == "radial") + { + gradient.set_identity(); + gradient.concatenate_translation(32.0f, 32.0f); + gradient.concatenate_scale(1.0f / 512.0f); + type = 0x12; + } + matrix inverse; + inverse.set_inverse(input); + gradient.concatenate(inverse); + style.set_gradient(type, gradient); + + // [CHOSEN, not recovered] S3 bridge to typed native Array storage. + const auto object_arg = [&fn](int index) -> as_object_interface* + { + const as_value& argument = fn.arg(index); + return argument.get_type() == as_value::OBJECT ? argument.m_object_value : NULL; + }; + const array& colors = array_object_values(object_arg(1)); + const array& alphas = array_object_values(object_arg(2)); + const array& ratios = array_object_values(object_arg(3)); + for (int i = 0; i < colors.size(); ++i) + { + const int rgb = bf2x87::toIntTruncate(colors[i].to_number()); + const float alpha = (float)alphas[i].to_number(); + const Uint8 ratio = (Uint8)bf2x87::toInt64Truncate(ratios[i].to_number()); + // The PE multiplies by 2.56f and retains the low byte, without clamping. + const Uint8 opacity = (Uint8)bf2x87::toInt64Truncate((long double)alpha * 2.56f); + gradient_record record; + record.m_ratio = ratio; + record.m_color = rgba((Uint8)(rgb >> 16), (Uint8)(rgb >> 8), (Uint8)rgb, opacity); + style.append_gradient(record); + } + sprite_instance* sprite = sprite_this(fn); + // [CHOSEN, not recovered] S3 bridge: the native bitmap owner is per-tree. + style.generate_gradient_bitmap(sprite->get_root()->m_def.get_ptr()); + shape_character_def* def = sprite->get_canvas_def(); + const int fill = def->append_fill_style(style) + 1; + path p; + p.m_new_shape = true; + def->append_path(p); + p.m_new_shape = false; + p.m_fill0 = fill; + p.m_fill1 = 0; + p.m_line = 0; + def->append_path(p); } + // SwiffPlayer.dll 0x1007BBF0. Runtime-definition ownership and the native + // receiver/root accessors retain the S3 bridges described below. void sprite_load_movie(const fn_call& fn) { + sprite_instance* sprite = sprite_this(fn); + if (sprite == NULL) return; + sprite->remove_all_display_objects(); if (fn.nargs < 1) { log_error("error: sprite_load_movie needs atleast one arg\n"); return; } - sprite_instance* sprite = sprite_this(fn); - if (sprite == NULL) return; - // [TEMP] RW-89 target trace: which clip loads which image, where it sits. Remove with the tracers. { const matrix wm = sprite->get_world_matrix(); @@ -5792,8 +5930,6 @@ namespace gameswf sprite->get_depth(), par ? par->get_name().c_str() : ""); } - sprite->remove_all_display_objects(); - const tu_string url = fn.arg(0).to_tu_string(); smart_ptr bi = render::create_bitmap_info_file(url.c_str()); if (bi == NULL) @@ -5802,6 +5938,8 @@ namespace gameswf } const int w = bi->m_original_width; const int h = bi->m_original_height; + smart_ptr bc = new bitmap_character(bi.get_ptr()); + bc->set_character_id(0); movie* root = sprite->get_root_movie(); movie_definition_sub* root_def = root @@ -5823,41 +5961,42 @@ namespace gameswf } // Its `_____image_shape`: one tiled bitmap fill over the texture-sized quad. - smart_ptr bc = new bitmap_character(bi.get_ptr()); smart_ptr sh = new shape_character_def; + sh->set_character_id(0); fill_style fs; matrix bm; bm.set_identity(); bm.m_[0][0] = 0.05f; bm.m_[1][1] = 0.05f; fs.set_bitmap(bc.get_ptr(), bm, false); - const int idx = sh->add_fill_style(fs); + const int idx = sh->append_fill_style(fs) + 1; path marker; marker.m_new_shape = true; - sh->add_path(marker); + sh->append_path(marker); path p(0.0f, 0.0f, idx, 0, 0); const float w20 = (float) w * 20.0f; const float h20 = (float) h * 20.0f; - p.m_edges.push_back(edge(w20 * 0.5f, 0.0f, w20, 0.0f)); - p.m_edges.push_back(edge(w20, h20 * 0.5f, w20, h20)); - p.m_edges.push_back(edge(w20 * 0.5f, h20, 0.0f, h20)); - p.m_edges.push_back(edge(0.0f, h20 * 0.5f, 0.0f, 0.0f)); - sh->add_path(p); - sh->refresh_bound(); - - // OWNERSHIP: generic_character::m_def is a RAW pointer in this gameswf (instances never own - // their definitions; the movie's character table does). A runtime-built definition therefore - // needs an owner that outlives the child, or the child dangles the moment this local dies - - // retail run I/J died exactly so, in the next frame's mouse hit test, calling slot 5 of a - // destroyed def (the bare ref_counted vtable + 5 = fontlib's accept_trapezoid). The image - // sprite's canvas slot is that owner, the same one the drawing API's `_____defaultShape` uses; - // remove_all_display_objects() releases both together. [CHOSEN, not recovered: DICE's owner - // for the image shape is not attested; only that the child is named `_____image_shape`.] + p.m_edges.push_back(edge(0.0f, 0.0f, w20, 0.0f)); + p.m_edges.push_back(edge(w20, h20, w20, h20)); + p.m_edges.push_back(edge(0.0f, h20, 0.0f, h20)); + p.m_edges.push_back(edge(0.0f, 0.0f, 0.0f, 0.0f)); + sh->append_path(p); + rect bound; + sh->compute_bound(&bound); + sh->set_bound(bound); + + // [CHOSEN, not recovered] S3 bridge: retain the image sprite's canvas + // alias while the native image/canvas integration awaits its runtime gates. + // The placed generic character also retains its definition (0x1007F130). + // [RETIRE-WHEN: swf-runtime-image-owner] Retire when native character/definition + // ownership follows the recovered lifetime and repeated image/remove/reload gates pass. img_sprite->m_canvas = sh.get_ptr(); img_sprite->add_display_object_def(sh.get_ptr(), "_____image_shape", 0); } + // SwiffPlayer.dll 0x1006F980. + // [CHOSEN, not recovered] S3 bridge: borrow the native VM target without this_ptr. void sprite_play(const fn_call& fn) { sprite_instance* sprite = (sprite_instance*) fn.this_ptr; @@ -5869,6 +6008,8 @@ namespace gameswf sprite->set_play_state(movie_interface::PLAY); } + // SwiffPlayer.dll 0x1006F9A0. + // [CHOSEN, not recovered] S3 bridge: borrow the native VM target without this_ptr. void sprite_stop(const fn_call& fn) { sprite_instance* sprite = (sprite_instance*) fn.this_ptr; @@ -5880,8 +6021,12 @@ namespace gameswf sprite->set_play_state(movie_interface::STOP); } + // SwiffPlayer.dll 0x10075780: the numeric arm subtracts one before a + // truncating qword conversion and passes its low dword (0x10075808). void sprite_goto_and_play(const fn_call& fn) { + // [CHOSEN, not recovered] S2 bridge: the 2006 VM can omit this_ptr; + // borrow its target. Retail's native-call ABI supplies the receiver directly. sprite_instance* sprite = (sprite_instance*) fn.this_ptr; if (sprite == NULL) { @@ -5895,21 +6040,24 @@ namespace gameswf return; } - // [DICE-MOD SwiffPlayer: label or number, as gameswf_sprite_goto_and_play - see gotoAndStop.] + // SwiffPlayer.dll 0x10075827 calls the queued-label slot, not +0x1C. if (fn.arg(0).get_type() == as_value::STRING) { - sprite->goto_labeled_frame(fn.arg(0).to_string()); + sprite->queue_goto_labeled_frame(fn.arg(0).to_string()); } - else + else if (fn.arg(0).get_type() == as_value::NUMBER) { - int target_frame = int(fn.arg(0).to_number() - 1); // Convert to 0-based + const int target_frame = bf2x87::lowWord(bf2x87::toInt64Truncate( + bf2x87::sub(bf2x87::Real(fn.arg(0).to_number()), bf2x87::Real(1)))); sprite->goto_frame(target_frame); } sprite->set_play_state(movie_interface::PLAY); } + // SwiffPlayer.dll 0x10075860; qword conversion at 0x100758E5. void sprite_goto_and_stop(const fn_call& fn) { + // [CHOSEN, not recovered] S2 bridge: see sprite_goto_and_play's receiver. sprite_instance* sprite = (sprite_instance*) fn.this_ptr; if (sprite == NULL) { @@ -5923,22 +6071,23 @@ namespace gameswf return; } - // [DICE-MOD SwiffPlayer: a frame LABEL is accepted, as the shipped gameswf_sprite_goto_and_stop - // does (STRING -> goto_labeled_frame, NUMBER -> goto_frame(n-1), then the play state either - // way). Stock 2006 converted the argument to a number, so the menu's gotoAndStop(label) from - // getFrameLabel() went to frame -1 and the root never left frame 0 (retail 2026-09-02).] + // SwiffPlayer.dll 0x10075904 calls queued-label slot +0xAC. The queue + // drains in advance, after the mouse pass has finished walking the children. if (fn.arg(0).get_type() == as_value::STRING) { - sprite->goto_labeled_frame(fn.arg(0).to_string()); + sprite->queue_goto_labeled_frame(fn.arg(0).to_string()); } - else + else if (fn.arg(0).get_type() == as_value::NUMBER) { - int target_frame = int(fn.arg(0).to_number() - 1); // Convert to 0-based + const int target_frame = bf2x87::lowWord(bf2x87::toInt64Truncate( + bf2x87::sub(bf2x87::Real(fn.arg(0).to_number()), bf2x87::Real(1)))); sprite->goto_frame(target_frame); } sprite->set_play_state(movie_interface::STOP); } + // SwiffPlayer.dll 0x100719F0 applies nextFrame immediately, then stops. + // [CHOSEN, not recovered] S3 bridge: borrow the native VM target without this_ptr. void sprite_next_frame(const fn_call& fn) { sprite_instance* sprite = (sprite_instance*) fn.this_ptr; @@ -5952,53 +6101,12 @@ namespace gameswf int current_frame = sprite->get_current_frame(); if (current_frame < frame_count) { - sprite->goto_frame(current_frame + 1); - } - sprite->set_play_state(movie_interface::STOP); - } - - void sprite_prev_frame(const fn_call& fn) - { - sprite_instance* sprite = (sprite_instance*) fn.this_ptr; - if (sprite == NULL) - { - sprite = (sprite_instance*) fn.env->get_target(); - } - assert(sprite); - - int current_frame = sprite->get_current_frame(); - if (current_frame > 0) - { - sprite->goto_frame(current_frame - 1); + sprite->apply_goto_frame(current_frame + 1); } sprite->set_play_state(movie_interface::STOP); } - void sprite_get_bytes_loaded(const fn_call& fn) - { - sprite_instance* sprite = (sprite_instance*) fn.this_ptr; - if (sprite == NULL) - { - sprite = (sprite_instance*) fn.env->get_target(); - } - assert(sprite); - - fn.result->set_int(sprite->get_root()->get_file_bytes()); - } - - void sprite_get_bytes_total(const fn_call& fn) - { - sprite_instance* sprite = (sprite_instance*) fn.this_ptr; - if (sprite == NULL) - { - sprite = (sprite_instance*) fn.env->get_target(); - } - assert(sprite); - - fn.result->set_int(sprite->get_root()->get_file_bytes()); - } - - + // SwiffPlayer.dll 0x1007E2D0: lazy registration, in the shipped order. static void sprite_builtins_init() { if (s_sprite_builtins) @@ -6012,30 +6120,29 @@ namespace gameswf s_sprite_builtins->set_member("gotoAndStop", &sprite_goto_and_stop); s_sprite_builtins->set_member("gotoAndPlay", &sprite_goto_and_play); s_sprite_builtins->set_member("nextFrame", &sprite_next_frame); - s_sprite_builtins->set_member("prevFrame", &sprite_prev_frame); - s_sprite_builtins->set_member("getBytesLoaded", &sprite_get_bytes_loaded); - s_sprite_builtins->set_member("getBytesTotal", &sprite_get_bytes_loaded); - // [DICE-MOD SwiffPlayer: the shipped builtins the menu framework needs - see the bodies above.] - s_sprite_builtins->set_member("createEmptyMovieClip", &sprite_create_empty_movieclip); - s_sprite_builtins->set_member("attachMovie", &sprite_attach_movie); - s_sprite_builtins->set_member("getNextHighestDepth", &sprite_get_next_highest_depth); + s_sprite_builtins->set_member("loadMovie", &sprite_load_movie); + s_sprite_builtins->set_member("startDrag", &sprite_start_drag); + s_sprite_builtins->set_member("stopDrag", &sprite_stop_drag); + s_sprite_builtins->set_member("duplicateMovieClip", &sprite_duplicate_movieclip); s_sprite_builtins->set_member("removeMovieClip", &sprite_remove_movieclip); + s_sprite_builtins->set_member("attachMovie", &sprite_attach_movie); s_sprite_builtins->set_member("setMask", &sprite_set_mask); - s_sprite_builtins->set_member("lineStyle", &sprite_line_style); - s_sprite_builtins->set_member("moveTo", &sprite_move_to); + s_sprite_builtins->set_member("getNextHighestDepth", &sprite_get_next_highest_depth); + // [CHOSEN, not recovered] S3 bridge: retain the native timer owner. + // The timer subsystem owns recovery of 0x1007E030 / 0x1007E210. + s_sprite_builtins->set_member("setInterval", &timer_setinterval); + s_sprite_builtins->set_member("clearInterval", &timer_clearinterval); + s_sprite_builtins->set_member("createEmptyMovieClip", &sprite_create_empty_movieclip); s_sprite_builtins->set_member("lineTo", &sprite_line_to); + s_sprite_builtins->set_member("moveTo", &sprite_move_to); s_sprite_builtins->set_member("beginFill", &sprite_begin_fill); - s_sprite_builtins->set_member("endFill", &sprite_end_fill); s_sprite_builtins->set_member("beginGradientFill", &sprite_begin_gradient_fill); - s_sprite_builtins->set_member("loadMovie", &sprite_load_movie); + s_sprite_builtins->set_member("endFill", &sprite_end_fill); + s_sprite_builtins->set_member("lineStyle", &sprite_line_style); - // @TODO -// s_sprite_builtins->set_member("startDrag", &sprite_start_drag); -// s_sprite_builtins->set_member("stopDrag", &sprite_stop_drag); -// s_sprite_builtins->set_member("getURL", &sprite_get_url); -// s_sprite_builtins->set_member("swapDepths", &sprite_swap_depths); } + // SwiffPlayer.dll 0x1006FA40 deletes the shared object directly. static void sprite_builtins_clear() { if (s_sprite_builtins) @@ -6055,6 +6162,7 @@ namespace gameswf // end_tag doesn't actually need to exist. + // SwiffPlayer.dll 0x1006FA70 is empty in the release image. void end_loader(stream* in, int tag_type, movie_definition_sub* m) { assert(tag_type == 0); @@ -6069,29 +6177,26 @@ namespace gameswf struct remove_object_2 : public execute_tag { - int m_depth, m_id; + // SwiffPlayer.dll 0x100719B0: implicit destruction has no owned members. + int m_depth; - remove_object_2() : m_depth(-1), m_id(-1) {} + // SwiffPlayer.dll 0x1006F860. + remove_object_2() : m_depth(-1) {} - void read(stream* in, int tag_type) + // SwiffPlayer.dll 0x1006F870. + void read(stream* in) { - assert(tag_type == 5 || tag_type == 28); - - if (tag_type == 5) - { - // Older SWF's allow multiple objects at the same depth; - // this m_id disambiguates. Later SWF's just use one - // object per depth. - m_id = in->read_u16(); - } m_depth = in->read_u16(); } + // SwiffPlayer.dll 0x1006F890. virtual void execute(movie* m) { - m->remove_display_object(m_depth, m_id); + m->remove_display_object(m_depth); + IF_VERBOSE_DEBUG(log_msg(">>>>>>>>> character removed at %d\n", m_depth)); } + // SwiffPlayer.dll 0x1006F8D0. virtual void execute_state(movie* m) { execute(m); @@ -6100,7 +6205,7 @@ namespace gameswf virtual void execute_state_reverse(movie* m, int frame) { // reverse of remove is to re-add the previous object. - execute_tag* last_add = m->find_previous_replace_or_add_tag(frame, m_depth, m_id); + execute_tag* last_add = m->find_previous_replace_or_add_tag(frame, m_depth, -1); if (last_add) { last_add->execute_state(m); @@ -6113,28 +6218,32 @@ namespace gameswf } } + // SwiffPlayer.dll 0x1006F8F0. virtual bool is_remove_tag() const { return true; } - // [DICE-MOD SwiffPlayer #45] the goto pass does nothing with a remove (0x1006F8E0 is a + // the goto pass does nothing with a remove (0x1006F8E0 is a // nullsub); the state builder reads its depth. + // SwiffPlayer.dll 0x1006F8E0. virtual void execute_goto(movie* /*m*/) {} virtual int get_tag_depth() const { return m_depth; } }; + // SwiffPlayer.dll 0x1006F900. void remove_object_2_loader(stream* in, int tag_type, movie_definition_sub* m) { - assert(tag_type == 5 || tag_type == 28); + assert(tag_type == 28); remove_object_2* t = new remove_object_2; - t->read(in, tag_type); + t->read(in); - IF_VERBOSE_PARSE(log_msg(" remove_object_2(%d)\n", t->m_depth)); + IF_VERBOSE_PARSE(log_msg("remove_object_2(%d)\n", t->m_depth)); m->add_execute_tag(t); } + // SwiffPlayer.dll 0x1006FA80. void button_sound_loader(stream* in, int tag_type, movie_definition_sub* m) { assert(tag_type == 17); @@ -6147,15 +6256,16 @@ namespace gameswf } + // SwiffPlayer.dll 0x1006FAB0. void button_character_loader(stream* in, int tag_type, movie_definition_sub* m) { assert(tag_type == 7 || tag_type == 34); int character_id = in->read_u16(); - IF_VERBOSE_PARSE(log_msg(" button character loader: char_id = %d\n", character_id)); - button_character_definition* ch = new button_character_definition; + // [CHOSEN, not recovered] S3 bridge: the S2 native constructor has no ID argument. + ch->set_character_id(character_id); ch->read(in, tag_type, m); m->add_character(character_id, ch); @@ -6167,6 +6277,7 @@ namespace gameswf // + // SwiffPlayer.dll 0x10074030: font, character, sound, then bitmap lookup. void export_loader(stream* in, int tag_type, movie_definition_sub* m) // Load an export tag (for exposing internal resources of m) { @@ -6174,30 +6285,30 @@ namespace gameswf int count = in->read_u16(); - IF_VERBOSE_PARSE(log_msg(" export: count = %d\n", count)); + IF_VERBOSE_PARSE(log_msg("export: count = %d\n", count)); // Read the exports. for (int i = 0; i < count; i++) { Uint16 id = in->read_u16(); char* symbol_name = in->read_string(); - IF_VERBOSE_PARSE(log_msg(" export: id = %d, name = %s\n", id, symbol_name)); + IF_VERBOSE_PARSE(log_msg("export: id = %d, name = %s\n", id, symbol_name)); if (font* f = m->get_font(id)) { // Expose this font for export. - m->export_resource(tu_string(symbol_name), f); + m->export_resource(id, tu_string(symbol_name), f); } else if (character_def* ch = m->get_character_def(id)) { // Expose this movie/button/whatever for export. - m->export_resource(tu_string(symbol_name), ch); + m->export_resource(id, tu_string(symbol_name), ch); } else if (sound_sample* ch = m->get_sound_sample(id)) { - m->export_resource(tu_string(symbol_name), ch); + m->export_resource(id, tu_string(symbol_name), ch); } - // [DICE-MOD SwiffPlayer: export BITMAP characters too. + // export BITMAP characters too. // // Bitmap characters live in a SEPARATE map (m_bitmap_characters, filled by // add_bitmap_character) and are NOT in m_characters, so the get_character_def branch @@ -6209,10 +6320,12 @@ namespace gameswf // ("images/UIcomponents/button-bkg-7.png"), which the host resolves through // ISwiffRender::loadTexture. Measured on mainMenu.swf: 12 image-named exports, all 12 // DefineBits characters, 0 reachable before this branch existed. - // See GAMESWF_DIVERGENCES.md.] + // See GAMESWF_DIVERGENCES.md. else if (bitmap_character_def* bch = m->get_bitmap_character(id)) { - m->export_resource(tu_string(symbol_name), bch); + // SwiffPlayer.dll 0x1007417E: the descriptor owns the name. + static_cast(bch->get_bitmap_info())->m_name = symbol_name; + m->export_resource(id, tu_string(symbol_name), bch); } else { @@ -6230,6 +6343,8 @@ namespace gameswf // + // SwiffPlayer.dll 0x1007D830; font/character import dispatch and the + // no-recurse recording path retain their shipped ordering and ownership. void import_loader(stream* in, int tag_type, movie_definition_sub* m) // Load an import tag (for pulling in external resources) { @@ -6238,7 +6353,7 @@ namespace gameswf char* source_url = in->read_string(); int count = in->read_u16(); - IF_VERBOSE_PARSE(log_msg(" import: source_url = %s, count = %d\n", source_url, count)); + IF_VERBOSE_PARSE(log_msg("import: source_url = %s, count = %d\n", source_url, count)); // Try to load the source movie into the movie library. movie_definition_sub* source_movie = NULL; @@ -6259,7 +6374,7 @@ namespace gameswf { Uint16 id = in->read_u16(); char* symbol_name = in->read_string(); - IF_VERBOSE_PARSE(log_msg(" import: id = %d, name = %s\n", id, symbol_name)); + IF_VERBOSE_PARSE(log_msg("import: id = %d, name = %s\n", id, symbol_name)); if (s_no_recurse_while_loading) { diff --git a/Code/BF2/External/gameswf/gameswf_impl.h b/Code/BF2/External/gameswf/gameswf_impl.h index 3774b155d..d304ecaa4 100644 --- a/Code/BF2/External/gameswf/gameswf_impl.h +++ b/Code/BF2/External/gameswf/gameswf_impl.h @@ -14,6 +14,7 @@ #include "gameswf_action.h" #include "gameswf_types.h" #include "gameswf_log.h" +#include "../../Platform/X87Compat.h" #include #include "base/container.h" #include "base/utility.h" @@ -37,26 +38,43 @@ namespace gameswf struct movie_root; struct sound_sample : public resource //virtual public ref_counted { + // SwiffPlayer.dll 0x1009E860 constructs only the inherited resource; + // 0x1009E8D0 / 0x1009F200 and deleting wrapper 0x1009F1D0 destroy it. + // resource carries the shared virtual ref_counted base, as retail (game-frontier C1). + // SwiffPlayer.dll 0x1009E8C0; resource table 0x100E2B88 +0x08. virtual sound_sample* cast_to_sound_sample() { return this; } }; struct stream; struct swf_event; void save_extern_movie(movie_interface* m); + // SwiffPlayer.dll 0x1006F110; [INFERRED] name of the mouse-event verbosity switch. + void set_verbose_mouse_events(bool verbose); + // Enables movie and renderer timing. Counters retain their individual retail gates. + // SwiffPlayer.dll 0x1006F140; [INFERRED] source-level name. + void set_profiling(bool enabled); // Extra internal interfaces added to movie_definition struct movie_definition_sub : public movie_definition { + // Compiler deleting wrapper: SwiffPlayer.dll 0x10073530; base lifetime is separate. + ~movie_definition_sub() override = default; virtual const array& get_playlist(int frame_number) = 0; virtual const array* get_init_actions(int frame_number) = 0; virtual smart_ptr get_exported_resource(const tu_string& symbol) = 0; - // [DICE-MOD SwiffPlayer #37: the name a text field's font reaches the renderer under. The - // shipped field asks its movie definition (vslot +60) for a font NAME by id, and the golden - // stream shows every line of the login page created as "StandardTextBold" - the EXPORT name - // (ExportAssets) of the font whose face name the field's font shares. [INFERRED: the slot's - // body is not located; the rule reproduces the golden.] False when no exported font matches.] + // SwiffPlayer.dll 0x10078260: looks up the exported name by resource ID. + // A null output pointer tests presence without copying the name. + virtual bool get_export_name(int id, tu_string* out) = 0; + // [CHOSEN, not recovered] S3 bridge: retained legacy pointer-to-ID query. + // Text construction now uses get_export_name with the declared font ID. + // [RETIRE-WHEN: swf-text-font-id] Remove this unused native virtual after + // exported/aliased fonts pass the maintainers' menu gates. virtual bool get_exported_font_name(const font* f, tu_string* out) { return false; } virtual character_def* get_character_def(int id) = 0; + // Movie teardown: drops the classes Object.registerClass bound to this definition's + // exports, so a definition kept in the library for the next player holds no function of + // the released movie. [CHOSEN, not recovered] issue #7; see release_script_objects. + virtual void release_registered_classes() {} virtual bool get_labeled_frame(const char* label, int* frame_number) = 0; @@ -66,7 +84,8 @@ namespace gameswf virtual void add_font(int id, font* ch) = 0; virtual font* get_font(int id) = 0; virtual void add_execute_tag(execute_tag* c) = 0; - virtual void add_init_action(int sprite_id, execute_tag* c) = 0; + // SwiffPlayer.dll 0x10078F90 / 0x10071630: definition-wide append or refusal. + virtual void add_init_action(execute_tag* c) = 0; virtual void add_frame_name(const char* name) = 0; virtual void set_jpeg_loader(jpeg::input* j_in) = 0; virtual jpeg::input* get_jpeg_loader() = 0; @@ -74,7 +93,7 @@ namespace gameswf virtual void add_bitmap_character(int character_id, bitmap_character_def* ch) = 0; virtual sound_sample* get_sound_sample(int character_id) = 0; virtual void add_sound_sample(int character_id, sound_sample* sam) = 0; - virtual void export_resource(const tu_string& symbol, resource* res) = 0; + virtual void export_resource(int id, const tu_string& symbol, resource* res) = 0; virtual void add_import(const char* source_url, int id, const char* symbol_name) = 0; virtual void add_bitmap_info(bitmap_info* ch) = 0; @@ -92,26 +111,39 @@ namespace gameswf movie_interface* create_library_movie_inst(movie_definition* md); movie_interface* get_current_root(); void set_current_root(movie_interface* m); + // The currently published root sprite, or null. + // This is independent of the external-movie interface selected above. + movie* get_global_root_movie(); + // Replaces the retained root; an identical pointer leaves ownership unchanged. + void set_global_root_movie(movie* root); const char* get_workdir(); void set_workdir(const char* dir); void delete_unused_root(); struct movie : public movie_interface { + // [CHOSEN, not recovered] S2 bridge for the retail secondary-interface + // environment lookup, expressed through the native movie interface. + virtual as_environment* get_action_environment() = 0; + // SwiffPlayer.dll 0x1007DB90 / 0x1007DBA0 (release defaults). virtual void set_extern_movie(movie_interface* m) { } virtual movie_interface* get_extern_movie() { return NULL; } + // SwiffPlayer.dll 0x1007DBC0 / 0x1007DBE0 / 0x1007DBD0 (release defaults). virtual movie_definition* get_movie_definition() { return NULL; } virtual movie_root* get_root() { return NULL; } virtual movie_interface* get_root_interface() { return NULL; } virtual movie* get_root_movie() { return NULL; } + // SwiffPlayer.dll 0x1007DBF0. virtual float get_pixel_scale() const { return 1.0f; } + // SwiffPlayer.dll 0x1007DC00 (release default). virtual character* get_character(int id) { return NULL; } - // [DICE-MOD SwiffPlayer: a SAFE downcast to character, the cast_to_font / cast_to_as_object - // pattern. The Color builtin's setRGB needs its target's cxform (see gameswf_action.cpp).] + // a SAFE downcast to character, the cast_to_font / cast_to_as_object + // pattern. The Color builtin's setRGB needs its target's cxform (see gameswf_action.cpp). virtual character* cast_to_character() { return NULL; } + // SwiffPlayer.dll 0x1007DC10 / 0x1007DC60. virtual matrix get_world_matrix() const { return matrix::identity; } virtual cxform get_world_cxform() const { return cxform::identity; } @@ -124,6 +156,7 @@ namespace gameswf return NULL; } + // SwiffPlayer.dll 0x1007DC80 returns NULL without examining its arguments. virtual character* add_display_object( Uint16 character_id, const char* name, @@ -138,6 +171,7 @@ namespace gameswf return NULL; } + // SwiffPlayer.dll 0x1007DC90 is empty. virtual void move_display_object( Uint16 depth, bool use_cxform, @@ -149,6 +183,7 @@ namespace gameswf { } + // SwiffPlayer.dll 0x1007DCA0 / 0x1007DCB0 are empty overloads. virtual void replace_display_object( Uint16 character_id, const char* name, @@ -175,28 +210,45 @@ namespace gameswf { } - virtual void remove_display_object(Uint16 depth, int id) {} + // SwiffPlayer.dll 0x1007DCC0 is empty; the native ID argument is + // retained for tag 5 [CHOSEN, not recovered] S3 bridge. + virtual void remove_display_object(Uint16 depth) {} + // SwiffPlayer.dll 0x1007DD00 / 0x1007DCD0: empty setter and transparent black. virtual void set_background_color(const rgba& color) {} - virtual rgba get_background_color() const { return rgba(); } // [DICE-MOD SwiffPlayer: see gameswf.h] + virtual rgba get_background_color() const { return rgba(0, 0, 0, 0); } + // SwiffPlayer.dll 0x1007DD10 / 0x1007DD20. virtual void set_background_alpha(float alpha) {} virtual float get_background_alpha() const { return 1.0f; } + // SwiffPlayer.dll 0x1007DD30 is empty. virtual void set_display_viewport(int x0, int y0, int width, int height) {} + // SwiffPlayer.dll 0x1007DD40 is empty in the release image. virtual void add_action_buffer(action_buffer* a) { assert(0); } + // SwiffPlayer.dll 0x1007DD50 is empty in the release image. virtual void goto_frame(int target_frame_number) { assert(0); } + // SwiffPlayer.dll 0x1007DD70: immediate numeric navigation is separate + // from queued goto_frame. The release movie default does nothing. + virtual void apply_goto_frame(int target_frame_number) {} + // SwiffPlayer.dll 0x1007DD60; sprites override the queued label entry. + virtual void queue_goto_labeled_frame(const char* label) {} + // SwiffPlayer.dll 0x1007DD80 is empty; the native Boolean result is an + // existing [CHOSEN, not recovered] S3 bridge for the 2006 interface. virtual bool goto_labeled_frame(const char* label) { assert(0); return false; } + // SwiffPlayer.dll 0x1007DD90 / 0x1007DDA0 (release defaults). virtual void set_play_state(play_state s) {} virtual play_state get_play_state() const { assert(0); return STOP; } + // SwiffPlayer.dll 0x1007DDB0 is empty. virtual void notify_mouse_state(int x, int y, int buttons) // The host app uses this to tell the movie where the // user's mouse pointer is. { } + // SwiffPlayer.dll 0x1007DDC0 leaves all three outputs alone. virtual void get_mouse_state(int* x, int* y, int* buttons) // Use this to retrieve the last state of the mouse, as set via // notify_mouse_state(). @@ -213,7 +265,13 @@ namespace gameswf float m_bound_y0; float m_bound_x1; float m_bound_y1; + // [CHOSEN, not recovered] S2 bridge fields for retail's float drag offsets + // (+0x18/+0x1C in the x86 record). 0x10092F3A/0x10092F40 write them, + // 0x100733E5/0x100733EE read them. Publishers provide completed records. + float m_offset_x = 0; + float m_offset_y = 0; + // SwiffPlayer.dll 0x1006ED60 initializes the six original fields only. drag_state() : m_character(0), m_lock_center(0), m_bound(0), @@ -221,23 +279,30 @@ namespace gameswf { } }; + // SwiffPlayer.dll 0x1007DDF0 / 0x1007DE30 / 0x1007DE40. + // [CHOSEN, not recovered] S3 bridge: the native record initializes its + // offset fields; the retail default copies uninitialized trailing words. virtual void get_drag_state(drag_state* st) { assert(0); *st = drag_state(); } + // Publish completed world-twip bounds and drag-local offsets without conversion. virtual void set_drag_state(const drag_state& st) { assert(0); } virtual void stop_drag() { assert(0); } + // SwiffPlayer.dll 0x1007DE50 is empty. // External virtual void set_variable(const char* path_to_var, const char* new_value) { assert(0); } + // SwiffPlayer.dll 0x1007DE60 is empty. // External virtual void set_variable(const char* path_to_var, const wchar_t* new_value) { assert(0); } + // SwiffPlayer.dll 0x1007DE70 returns the empty string. // External virtual const char* get_variable(const char* path_to_var) const { @@ -245,10 +310,12 @@ namespace gameswf return ""; } + // SwiffPlayer.dll 0x1007DE80 / 0x1007DE90 (release defaults). virtual void * get_userdata() { assert(0); return NULL; } virtual void set_userdata(void *) { assert(0); } // External + // SwiffPlayer.dll 0x1007DEA0. virtual bool has_looped() const { return true; } @@ -256,7 +323,7 @@ namespace gameswf // Mouse/Button interface. // - // [DICE-MOD SwiffPlayer #51] The shipped player has no "topmost mouse entity" pass. Every + // The shipped player has no "topmost mouse entity" pass. Every // character runs its own per-frame mouse state machine (vtable slot 4, mouse_update): the root // sprite is asked once per advance, a sprite handles itself and then every visible child from // the top down, and a child's answer - "I consumed the pointer" - is what the children below it @@ -266,10 +333,12 @@ namespace gameswf // still reaches the button under its list mask. Slot 61, point_test_world, is the geometric // half: does this character cover the world-space point (twips). The character defaults are // the shipped 0x1007EEF0 / 0x1007EF00, both false. + // SwiffPlayer.dll 0x1007EEF0 / 0x1007EF00. virtual bool mouse_update(bool consumed) { return false; } virtual bool point_test_world(float x, float y) { return false; } // The root's mouse capture (the shipped movie_root's +0xB4 / +0xB8): the character that took a // press holds the pointer until it releases. Sprites forward to their movie_root. + // SwiffPlayer.dll 0x1007DDD0 / 0x1007DDE0. virtual movie* get_active_mouse_entity() { return NULL; } virtual void set_active_mouse_entity(movie* m) {} virtual bool get_track_as_menu() const { return false; } @@ -280,6 +349,7 @@ namespace gameswf // + // SwiffPlayer.dll 0x1007DEB0, movie secondary tables +0x1C. virtual movie* get_relative_target(const tu_string& name) { assert(0); @@ -287,79 +357,41 @@ namespace gameswf } // ActionScript event handler. Returns true if a handler was called. + // SwiffPlayer.dll 0x1007DEC0. virtual bool on_event(event_id id) { return false; } - int add_interval_timer(void *timer) - { - log_msg("FIXME: %s: unimplemented\n", __FUNCTION__); - return -1; // ??? - } - - void clear_interval_timer(int x) - { - log_msg("FIXME: %s: unimplemented\n", __FUNCTION__); - } - - virtual void do_something(void *timer) - { - log_msg("FIXME: %s: unimplemented\n", __FUNCTION__); - } - // Special event handler; sprites also execute their frame1 actions on this event. + // SwiffPlayer.dll 0x1007DED0; native event IDs map LOAD to retail 10. virtual void on_event_load() { on_event(event_id::LOAD); } -#if 0 - // tulrich: @@ is there a good reason these are in the - // vtable? I.e. can the caller just call - // on_event(event_id::SOCK_DATA) instead of - // on_event_xmlsocket_ondata()? - virtual void on_event_xmlsocket_ondata() { on_event(event_id::SOCK_DATA); } - virtual void on_event_xmlsocket_onxml() { on_event(event_id::SOCK_XML); } - virtual void on_event_interval_timer() { on_event(event_id::TIMER); } - virtual void on_event_load_progress() { on_event(event_id::LOAD_PROGRESS); } -#endif // as_object_interface stuff + // SwiffPlayer.dll 0x1007DEF0 / 0x1007DF00 (release defaults). virtual void set_member(const tu_stringi& name, const as_value& val) { assert(0); } virtual bool get_member(const tu_stringi& name, as_value* val) { assert(0); return false; } + // SwiffPlayer.dll 0x1007DF20 is empty in the release image. virtual void call_frame_actions(const as_value& frame_spec) { assert(0); } + // SwiffPlayer.dll 0x1007DF30 / 0x1007DF40. virtual float get_timer() const { return 0.0f; } virtual movie* to_movie() { return this; } + // SwiffPlayer.dll 0x1007DF60 / 0x1007DF70 (release defaults). virtual void clone_display_object(const tu_string& name, const tu_string& newname, Uint16 depth) { assert(0); } virtual void remove_display_object(const tu_string& name) { assert(0); } - // Forward vararg call to version taking va_list. - virtual const char* call_method(const char* method_name, const char* method_arg_fmt, ...) - { - va_list args; - va_start(args, method_arg_fmt); - const char* result = call_method_args(method_name, method_arg_fmt, args); - va_end(args); - - return result; - } - - virtual const char* call_method_args(const char* method_name, const char* method_arg_fmt, va_list args) - // Override this if you implement call_method. - { - assert(0); - return NULL; - } + // SwiffPlayer.dll 0x1007EFC0 / 0x1007EFB0; characters without + // a script environment return null for either command width. + virtual const char* call_method(const Uint16* expression) { return NULL; } + virtual const char* call_method(const char* expression) { return NULL; } virtual void execute_frame_tags(int frame, bool state_only = false) {} - // External. - virtual void attach_display_callback(const char* path_to_object, void (*callback)(void*), void* user_ptr) - { - assert(0); - } - - virtual void set_display_callback(void (*callback)(void*), void* user_ptr) - // Override me to provide this functionality. - { - } + // SwiffPlayer.dll 0x1007ED80: characters without editable text ignore this. + // Sprites forward it to referenced children; text fields update tab order. + virtual void set_tab_index(int index) {} + // SwiffPlayer.dll 0x1007DBB0: absent outside sprites. + virtual int get_tab_index() const { return -1; } }; @@ -399,6 +431,14 @@ namespace gameswf // It represents a single active element in a movie. struct character : public movie { + // Compiler deleting wrapper: SwiffPlayer.dll 0x10084AE0. The character + // lifetime body at 0x1007F0A0 remains a separate recovery boundary. + ~character() override; + // SwiffPlayer.dll 0x1007EC60 constructs an Array at character +0x1C; + // 0x10080CEE exposes it through the movie's "arguments" member. + // [CHOSEN, not recovered] S3 bridge: own the native Array separately + // instead of reproducing the embedded x86 object and virtual bases. + smart_ptr m_arguments; int m_id; movie* m_parent; tu_string m_name; @@ -409,72 +449,109 @@ namespace gameswf Uint16 m_clip_depth; bool m_visible; hash m_event_handlers; - void (*m_display_callback)(void*); - void* m_display_callback_user_ptr; - // [DICE-MOD SwiffPlayer: MovieClip.setMask. The shipped character keeps the mask clip at + // MovieClip.setMask. The shipped character keeps the mask clip at // +192 and a "mask only" byte at +196 (gameswf_sprite_set_mask); display_list::display // draws a masked character as begin_submit_mask / mask / end_submit_mask / character / - // disable_mask, and never draws a mask-only character on its own.] + // disable_mask, and never draws a mask-only character on its own. smart_ptr m_mask; bool m_is_mask_only; - // [DICE-MOD SwiffPlayer #51] the shipped +197: set once a mouse handler is attached (a clip + // the shipped +197: set once a mouse handler is attached (a clip // event through set_event_handler, an on... member through the sprite's set_member), read by // the sprite mouse pass, never cleared (gameswf_character_ctor zeroes it). bool m_mouse_enabled; - // [DICE-MOD SwiffPlayer] a runtime-built character keeps its own definition alive (see - // generic_character::m_def_owner); a sprite already owns its definition through m_def. + // [CHOSEN, not recovered] S3 bridge for runtime placement callers; + // generic characters and sprites retain their definitions through m_def. virtual void hold_definition(character_def* /*def*/) {} - character(movie* parent, int id) - : - m_id(id), - m_parent(parent), - m_depth(-1), - m_ratio(0.0f), - m_clip_depth(0), - m_visible(true), - m_display_callback(NULL), - m_display_callback_user_ptr(NULL), - m_is_mask_only(false), - m_mouse_enabled(false) + // Movie teardown (release_script_objects): appends every object or function this character + // references from script state (event handlers, the mask; overrides add their environment + // and children) to *held, then clears its own references, so clips of a released movie no + // longer keep each other alive. Runs no ActionScript. + // [CHOSEN, not recovered] issue #7 (https://github.com/B2BF/OpenBF2/issues/7). + virtual void release_script_values(array* held) { - assert((parent == NULL && m_id == -1) - || (parent != NULL && m_id >= 0)); + for (hash::iterator it = m_event_handlers.begin(); it != m_event_handlers.end(); ++it) + { + hold_script_value(held, it->second); + } + m_event_handlers.clear(); + if (m_mask != NULL) + { + held->push_back(as_value(m_mask.get_ptr())); + m_mask = NULL; + } } + character(movie* parent, int id); + // Accessors for basic display info. - virtual character* cast_to_character() { return this; } // [DICE-MOD SwiffPlayer: see movie] + virtual character* cast_to_character() { return this; } // see movie int get_id() const { return m_id; } + // SwiffPlayer.dll 0x1006EE40. movie* get_parent() const { return m_parent; } void set_parent(movie* parent) { m_parent = parent; } // for extern movie + // SwiffPlayer.dll 0x1006EE50 / 0x1006EE60. int get_depth() const { return m_depth; } void set_depth(int d) { m_depth = d; } + // SwiffPlayer.dll 0x1006EE70 / 0x1006EE80. const matrix& get_matrix() const { return m_matrix; } void set_matrix(const matrix& m) { assert(m.is_valid()); m_matrix = m; } + // SwiffPlayer.dll 0x1006EEC0. const cxform& get_cxform() const { return m_color_transform; } - void set_cxform(const cxform& cx) { m_color_transform = cx; } + // SwiffPlayer.dll 0x1007EDB0 copies all eight transform components. + virtual void set_cxform(const cxform& cx) { m_color_transform = cx; } void concatenate_cxform(const cxform& cx) { m_color_transform.concatenate(cx); } void concatenate_matrix(const matrix& m) { m_matrix.concatenate(m); } + // SwiffPlayer.dll 0x1006EED0 / 0x1006EEE0. float get_ratio() const { return m_ratio; } void set_ratio(float f) { m_ratio = f; } Uint16 get_clip_depth() const { return m_clip_depth; } + // SwiffPlayer.dll 0x1006EF00. void set_clip_depth(Uint16 d) { m_clip_depth = d; } + // SwiffPlayer.dll 0x100A7730 / 0x100A7740 / 0x1006EF20. + // [CHOSEN, not recovered] S3 bridge: the native mask remains an owning handle. + character* get_mask() const { return m_mask.get_ptr(); } + bool is_mask_only() const { return m_is_mask_only; } + void set_mask_only(bool value) { m_is_mask_only = value; } + // SwiffPlayer.dll 0x100714A0 leaves a previous mask's flag set. + // [CHOSEN, not recovered] S3 bridge: retain the native owning handle. + void set_mask(character* mask) + { + m_mask = mask; + if (mask) mask->m_is_mask_only = true; + } void set_name(const char* name) { m_name = name; } const tu_string& get_name() const { return m_name; } + // SwiffPlayer.dll 0x10073490. Copy presentation state to an existing character; + // its ID, parent, event handlers and script state are retained. + // [INFERRED] Source-level name; when the source is a sprite, target must be a sprite. + virtual void copy_display_state(character* target) const + { + target->set_cxform(m_color_transform); + target->m_name = m_name.c_str(); + target->m_depth = m_depth; + target->m_matrix = m_matrix; + target->m_ratio = m_ratio; + target->m_clip_depth = m_clip_depth; + target->set_visible(get_visible()); + } + // For edit_text support (Flash 5). More correct way // is to do "text_character.text = whatever", via // set_member(). + // SwiffPlayer.dll 0x1007EDD0 / 0x1007EDE0 (release defaults). virtual const char* get_text_name() const { return ""; } virtual void set_text_value(const char* new_text) { assert(0); } + // SwiffPlayer.dll 0x1007EDF0. virtual matrix get_world_matrix() const // Get our concatenated matrix (all our ancestor transforms, times our matrix). Maps // from our local space into "world" space (i.e. root movie space). @@ -489,6 +566,7 @@ namespace gameswf return m; } + // SwiffPlayer.dll 0x1007EE80. virtual cxform get_world_cxform() const // Get our concatenated color transform (all our ancestor transforms, // times our cxform). Maps from our local space into normal color space. @@ -510,9 +588,10 @@ namespace gameswf } void set_event_handler(event_id id, const as_value& method) { - // [DICE-MOD SwiffPlayer #51] sub_10077E10: a mouse handler marks the character mouse-enabled + // SwiffPlayer.dll 0x10077E10; native event IDs use the S2 mapping. + // sub_10077E10: a mouse handler marks the character mouse-enabled // before it is stored - the eleven ids the shipped body tests. - switch (id.m_id) + switch (id.m_key_code == key::INVALID ? id.m_id : event_id::INVALID) { case event_id::PRESS: case event_id::RELEASE: @@ -534,35 +613,45 @@ namespace gameswf } // Movie interfaces. By default do nothing. sprite_instance and some others override these. + // SwiffPlayer.dll 0x1007EEE0 / 0x1007EF10 / 0x1007EF20. virtual void display() {} virtual float get_height() { return 0; } virtual float get_width() { return 0; } - // [DICE-MOD SwiffPlayer #39] the character's UNSCALED local extent (twips, its own space). + // the character's UNSCALED local extent (twips, its own space). // Flash's `_width`/`_height` are this times the own matrix scale, and their setters divide by // it - absolute, independent of ancestors. See GAMESWF_DIVERGENCES.md #39. virtual float get_local_height() { return 0; } virtual float get_local_width() { return 0; } - // [DICE-MOD SwiffPlayer #42] Flash's dead reference: a clip removed from its parent's display - // list (RemoveObject2, removeMovieClip, the parent's own destruction) answers undefined for - // every member from then on, so a script callback that still holds it finds nothing to call - // and the movie's UpdateManager - which keeps a callback only while it returns true - drops - // it after one tick. Stock 2006 left the object fully alive: the manage-accounts page's - // callback kept running against a removed clip 524,100 times in one retail drive. + // [CHOSEN, not recovered] S3 bridge for the retained removal/orphan + // tracer. Sprite member get/set do not consult this flag: retail + // 0x10080590 / 0x10083A20 have no dead-reference guard. virtual void mark_dead() {} virtual movie* get_root_movie() { return m_parent->get_root_movie(); } + // SwiffPlayer.dll 0x1007F010 forwards to the parent's environment, or NULL. + virtual as_environment* get_action_environment() + { + return m_parent != NULL ? m_parent->get_action_environment() : NULL; + } + // SwiffPlayer.dll 0x1007EF30 / 0x1007EF40 (release defaults). virtual int get_current_frame() const { assert(0); return 0; } virtual bool has_looped() const { assert(0); return false; } + // SwiffPlayer.dll 0x1007EF50 / 0x1007EF60 are empty. virtual void restart() { /*assert(0);*/ } virtual void advance(float delta_time) {} // for buttons and sprites + // SwiffPlayer.dll 0x1007EF70, primary character table +0x18. + void apply_goto_frame(int target_frame) override {} + // Native queued navigation default; distinct from the immediate retail entry. virtual void goto_frame(int target_frame) {} + // SwiffPlayer.dll 0x1007EF80. virtual bool get_accept_anim_moves() const { return true; } - virtual void get_drag_state(drag_state* st) { assert(m_parent); m_parent->get_drag_state(st); } + // SwiffPlayer.dll 0x1007EF90 leaves the output alone without a parent. + virtual void get_drag_state(drag_state* st) { if (m_parent) m_parent->get_drag_state(st); } - // [DICE-MOD SwiffPlayer #54] sub_1007F030 (character vtable +88, read in full 2026-09-28) - + // sub_1007F030 (character vtable +88, read in full 2026-09-28) - // hiding a character RELEASES THE ROOT'S MOUSE CAPTURE when the capture holder is this // character or lies anywhere beneath it. The holder took the capture on its press (#51) and // drops it only in its own release transition, but a hidden character's mouse pass never @@ -579,28 +668,30 @@ namespace gameswf // walk from active up through the parents, each of which must be a character; reaching // this -> set_active_mouse_entity(NULL) (the root sprite's +0xB8) // - // [CHOSEN, not recovered] The shipped asks the GLOBAL root sprite (dword_100F8CAC, the "_root" - // movie_def_impl::create_instance 0x10084A30 stores, released at 0x100753AD); this port keeps - // no such global for the main movie (s_current_root is only set for an external movie), so it - // asks the nearest sprite of this character's own tree, which forwards to the same movie_root - // - one object while one movie is up. It does not use get_root_movie, whose character body - // dereferences the parent unguarded. [INFERRED] the shipped per-parent test (slot 0 of the +8 + // The published root sprite is independent of the caller's tree. [INFERRED] + // the shipped per-parent test (slot 0 of the +8 // subobject's table, `mov al, 1` for sprites and buttons alike) is "is a character": // cast_to_character here. The BUTTON's `_visible` setter writes the byte directly in both // players (sub_100A34E0, gameswf_button.cpp), so hiding a button releases nothing. virtual void set_visible(bool visible) { + // SwiffPlayer.dll 0x1007F030. m_visible = visible; if (visible) { return; } - movie* owner = this; // the nearest sprite: only a sprite answers get_root() - while (owner != NULL && owner->get_root() == NULL) - { - character* c = owner->cast_to_character(); - owner = c != NULL ? c->get_parent() : NULL; - } + release_mouse_capture_within(); + } + + // The capture walk set_visible ends with (sub_1007F030), also inlined by the display list's + // remove_display_object (0x100A7A20: 0x100A7A67..0x100A7AAA) and replace_display_object + // (0x100A8080: 0x100A80B3..0x100A80ED) for the character leaving the list: when the root's + // active entity is this character or lies beneath it, the capture is dropped. Both list + // bodies fetch the published root through 0x10071710. + void release_mouse_capture_within() + { + movie* owner = get_global_root_movie(); if (owner == NULL) { return; @@ -620,40 +711,30 @@ namespace gameswf } m = parent; } - owner->set_active_mouse_entity(NULL); + // 0x1007F086 / 0x100A7A9F / 0x100A80E2 re-read after callbacks. + get_global_root_movie()->set_active_mouse_entity(NULL); } + // SwiffPlayer.dll 0x1007EFD0. virtual bool get_visible() const { return m_visible; } - virtual void set_display_callback(void (*callback)(void*), void* user_ptr) - { - m_display_callback = callback; - m_display_callback_user_ptr = user_ptr; - } - - virtual void do_display_callback() - { - if (m_display_callback) - { - (*m_display_callback)(m_display_callback_user_ptr); - } - } - virtual void get_mouse_state(int* x, int* y, int* buttons) { get_parent()->get_mouse_state(x, y, buttons); } // Utility. void do_mouse_drag(); + // SwiffPlayer.dll character slot +0xF0. Native declaration order differs; + // all calls use typed dispatch. [INFERRED] source-level name/constness. + virtual rect get_bound_copy() const = 0; }; // For characters that don't store unusual state in their instances. struct generic_character : public character { - character_def* m_def; - // [DICE-MOD SwiffPlayer] set only for runtime-built definitions (drawing canvas, loadMovie - // image shape) - see sprite_instance::add_display_object_def. Timeline characters keep the - // stock raw pointer into the movie's character table. - smart_ptr m_def_owner; + // SwiffPlayer.dll 0x1007F130 retains the definition for every instance; + // 0x10084CA0 releases it before destroying the character base. + smart_ptr m_def; + // SwiffPlayer.dll 0x1007F130. generic_character(character_def* def, movie* parent, int id) : character(parent, id), @@ -662,37 +743,43 @@ namespace gameswf assert(m_def); } - virtual void hold_definition(character_def* def) { m_def_owner = def; } + // [CHOSEN, not recovered] S3 bridge for the native placement API. + virtual void hold_definition(character_def* def) { m_def = def; } + + // SwiffPlayer.dll 0x1007F240 forwards to the definition rectangle provider. + rect get_bound_copy() const override { return m_def->get_bound_copy(); } // the definition's +0x20 virtual void display() { + // SwiffPlayer.dll 0x1007F1D0 delegates to the definition. m_def->display(this); // pass in transform info - do_display_callback(); } // @@ tulrich: these are used for finding bounds; TODO // need to do this using enclose_transformed_rect(), // not by scaling the local height/width! + // SwiffPlayer.dll 0x1007F260 returns pixels after applying world scale. virtual float get_height() { matrix m = get_world_matrix(); - float h = m_def->get_height_local() * m.m_[1][1]; - return h; + return bf2x87::store(bf2x87::mul(bf2x87::mul( + bf2x87::Real(m_def->get_height_local()), bf2x87::Real(m.m_[1][1])), bf2x87::Real(0.05f))); } + // SwiffPlayer.dll 0x1007F290 returns pixels after applying world scale. virtual float get_width() { matrix m = get_world_matrix(); - float w = m_def->get_width_local() * m.m_[0][0]; - return w; + return bf2x87::store(bf2x87::mul(bf2x87::mul( + bf2x87::Real(m_def->get_width_local()), bf2x87::Real(m.m_[0][0])), bf2x87::Real(0.05f))); } - // [DICE-MOD SwiffPlayer #39] the definition's local extent, unscaled. + // the definition's local extent, unscaled. virtual float get_local_height() { return m_def->get_height_local(); } virtual float get_local_width() { return m_def->get_width_local(); } - // [DICE-MOD SwiffPlayer #51] sub_1007F1E0: the world-space point brought into the shape's own + // sub_1007F1E0: the world-space point brought into the shape's own // space through the inverse of its world matrix, then the definition's local test. virtual bool point_test_world(float x, float y) { @@ -708,9 +795,9 @@ namespace gameswf { virtual gameswf::bitmap_info* get_bitmap_info() = 0; - // [DICE-MOD SwiffPlayer: safe downcast, same pattern as resource::cast_to_font. Lets the + // safe downcast, same pattern as resource::cast_to_font. Lets the // exported-bitmap enumeration below tell a bitmap character from any other exported - // character_def without a static_cast. See GAMESWF_DIVERGENCES.md.] + // character_def without a static_cast. See GAMESWF_DIVERGENCES.md. virtual bitmap_character_def* cast_to_bitmap_character_def() { return this; } }; @@ -718,6 +805,12 @@ namespace gameswf // Bitmap character struct bitmap_character : public bitmap_character_def { + // SwiffPlayer.dll 0x100755A0 / 0x10075570: release the bitmap member, + // then the definition/ref-counted bases; the latter entry also deletes. + ~bitmap_character() override = default; + // SwiffPlayer.dll 0x10073940 retains the bitmap after initializing + // the definition. [CHOSEN, not recovered] S3 bridge: native callers + // assign the constructor's retail ID separately with set_character_id. bitmap_character(bitmap_info* bi) : m_bitmap_info(bi) @@ -740,11 +833,25 @@ namespace gameswf // m_bitmap_info = gameswf::render::create_bitmap_info_rgba(image); // } + // SwiffPlayer.dll 0x10073A40 returns the held bitmap descriptor. gameswf::bitmap_info* get_bitmap_info() { return m_bitmap_info.get_ptr(); } + // SwiffPlayer.dll 0x100739E0: definition bounds in twips, without a null guard. + rect get_bound_copy() const override + { + rect bounds; + bounds.m_x_min = 0.0f; + bounds.m_x_max = bf2x87::store(bf2x87::mul( + bf2x87::Real(m_bitmap_info->m_original_width), bf2x87::Real(20.0f))); + bounds.m_y_min = 0.0f; + bounds.m_y_max = bf2x87::store(bf2x87::mul( + bf2x87::Real(m_bitmap_info->m_original_height), bf2x87::Real(20.0f))); + return bounds; + } + private: smart_ptr m_bitmap_info; }; @@ -756,15 +863,19 @@ namespace gameswf // with a frame. struct execute_tag { + // SwiffPlayer.dll 0x1006EF80 / 0x1006F650 construct only the vptr; 0x1006EFF0 + // is the compiler deleting destructor. Table 0x100DF29C fixes these slots. virtual ~execute_tag() {} + // SwiffPlayer.dll 0x1006EF90 / 0x1006EFA0 leave the movie untouched. virtual void execute(movie* m) {} virtual void execute_state(movie* m) {} virtual void execute_state_reverse(movie* m, int frame) { execute_state(m); } + // SwiffPlayer.dll 0x1006EFC0 / 0x1006EFD0 return false. virtual bool is_remove_tag() const { return false; } virtual bool is_action_tag() const { return false; } virtual uint32 get_depth_id_of_replace_or_add_tag() const { return static_cast(-1); } - // [DICE-MOD SwiffPlayer #45] The shipped execute_tag's third execution slot (vtable +12, + // The shipped execute_tag's third execution slot (vtable +12, // base 0x1006EFB0): what a tag does when a goto replays the TARGET frame's playlist after // the timeline-state diff has already placed, moved and removed everything. The base runs // execute(), so a do_action (which leaves the slot at the base) queues its actions, while @@ -773,6 +884,7 @@ namespace gameswf // identified a tag: is_place_tag (vtable +24), then the place tag's depth (+70) and kind // (+76, place_object_2::place_type), or the remove tag's depth (+4). virtual void execute_goto(movie* m) { execute(m); } + // SwiffPlayer.dll 0x1006EFE0 returns false. virtual bool is_place_tag() const { return false; } virtual int get_tag_depth() const { return -1; } virtual int get_place_type() const { return -1; } diff --git a/Code/BF2/External/gameswf/gameswf_log.cpp b/Code/BF2/External/gameswf/gameswf_log.cpp index 58c8556ff..ee4300bf9 100644 --- a/Code/BF2/External/gameswf/gameswf_log.cpp +++ b/Code/BF2/External/gameswf/gameswf_log.cpp @@ -6,11 +6,16 @@ // Helpers for logging messages & errors. -#include "gameswf_log.h" -#include "gameswf.h" - #include #include +#include +#if !defined(_MSC_VER) +#include +#include +#include +#endif +#include "gameswf_log.h" +#include "gameswf.h" namespace gameswf @@ -23,6 +28,7 @@ namespace gameswf static char s_buffer[BUFFER_SIZE]; + // SwiffPlayer.dll 0x1009AF40 replaces the callback, including null. void register_log_callback(void (*callback)(bool error, const char* message)) // The host app can use this to install a function to receive log // & error messages from gameswf. @@ -33,16 +39,23 @@ namespace gameswf } -#ifdef _WIN32 -#define vsnprintf _vsnprintf -#endif // _WIN32 - -#define FORMAT_INTO_BUFFER(fmt) \ - va_list ap; \ - va_start(ap, fmt); \ - vsnprintf(s_buffer, BUFFER_SIZE, fmt, ap); \ - va_end(ap); + static void format_into_buffer(const char* fmt, va_list ap) + { +#if defined(_WIN32) + _vsnprintf(s_buffer, BUFFER_SIZE, fmt, ap); +#else + // [CHOSEN, not recovered] POSIX CRT bridge: native formatting, with + // MSVCR71's full-buffer nontermination. Locale, nonfinite spelling and + // invalid-format effects remain native CRT policy, not recovered parity. + char formatted[BUFFER_SIZE + 1]; + memcpy(formatted, s_buffer, BUFFER_SIZE); + const int count = vsnprintf(formatted, sizeof(formatted), fmt, ap); + const int bytes = count >= 0 && count < BUFFER_SIZE ? count + 1 : BUFFER_SIZE; + memcpy(s_buffer, formatted, bytes); +#endif + } + // SwiffPlayer.dll 0x1009AF50. void log_msg(const char* fmt, ...) // Printf-style informational log. { @@ -51,12 +64,16 @@ namespace gameswf return; } - FORMAT_INTO_BUFFER(fmt); + va_list ap; + va_start(ap, fmt); + format_into_buffer(fmt, ap); + va_end(ap); s_log_callback(false, s_buffer); } + // SwiffPlayer.dll 0x1009AF90. void log_error(const char* fmt, ...) // Printf-style error log. { @@ -65,10 +82,58 @@ namespace gameswf return; } - FORMAT_INTO_BUFFER(fmt); + va_list ap; + va_start(ap, fmt); + format_into_buffer(fmt, ap); + va_end(ap); s_log_callback(true, s_buffer); } + +#if !defined(_MSC_VER) + int g_swf_mouse_pass_depth = 0; + + bool swf_list_trace_on() + { + static int s_on = -1; + if (s_on < 0) + { + const char* v = getenv("BF2_SWF_LIST_TRACE"); + s_on = (v && v[0] >= '1' && v[0] <= '9') ? 1 : 0; + } + return s_on != 0; + } + + void swf_list_trace(const char* fmt, ...) + { + static char s_last[512]; + static int s_repeats = 0; + char line[512]; + va_list ap; + va_start(ap, fmt); + vsnprintf(line, sizeof(line), fmt, ap); + va_end(ap); + if (strcmp(line, s_last) == 0) + { + s_repeats++; + return; + } + struct timeval tv; + gettimeofday(&tv, NULL); + struct tm tmv; + localtime_r(&tv.tv_sec, &tmv); + if (s_repeats > 0) + { + fprintf(stderr, "[swf-list] (previous line x%d more)\n", s_repeats); + } + fprintf(stderr, "%02d:%02d:%02d.%03d [swf-list] %s%s\n", tmv.tm_hour, tmv.tm_min, tmv.tm_sec, + (int) (tv.tv_usec / 1000), g_swf_mouse_pass_depth > 0 ? "[mouse] " : "", line); + fflush(stderr); + strncpy(s_last, line, sizeof(s_last) - 1); + s_last[sizeof(s_last) - 1] = '\0'; + s_repeats = 0; + } +#endif } diff --git a/Code/BF2/External/gameswf/gameswf_log.h b/Code/BF2/External/gameswf/gameswf_log.h index 2037ea4fe..5cdd42b77 100644 --- a/Code/BF2/External/gameswf/gameswf_log.h +++ b/Code/BF2/External/gameswf/gameswf_log.h @@ -23,6 +23,19 @@ namespace gameswf void log_error(const char* fmt, ...); #endif // not __GNUC__ + +#if !defined(_MSC_VER) + // [TEMP] c-swf-disconnect display-list tracer, off unless + // BF2_SWF_LIST_TRACE=1. One flushed stderr line per event, prefixed "[swf-list]"; a line + // identical to the previous one is counted, not repeated. g_swf_mouse_pass_depth is the + // nesting of sprite mouse passes, so a line can say whether it ran inside one. + bool swf_list_trace_on(); + void swf_list_trace(const char* fmt, ...) __attribute__((format (printf, 1, 2))); + extern int g_swf_mouse_pass_depth; +#define SWF_LIST_TRACE(...) do { if (gameswf::swf_list_trace_on()) gameswf::swf_list_trace(__VA_ARGS__); } while (0) +#else +#define SWF_LIST_TRACE(...) do { } while (0) +#endif } diff --git a/Code/BF2/External/gameswf/gameswf_morph.cpp b/Code/BF2/External/gameswf/gameswf_morph.cpp deleted file mode 100644 index cf4699ed2..000000000 --- a/Code/BF2/External/gameswf/gameswf_morph.cpp +++ /dev/null @@ -1,468 +0,0 @@ -// gameswf_morph.cpp -// -- Thatcher Ulrich , Mike Shaver 2003 - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - -// Loading and rendering of morphing shapes. - -#include "gameswf_morph.h" - -#include "gameswf_impl.h" -#include "gameswf_log.h" -#include "gameswf_stream.h" - -#include "base/tu_file.h" -#include "gameswf_render.h" - -#include - -#define SHAPE_LOG 0 - -namespace gameswf { - - shape_morph_def::shape_morph_def() : - m_last_ratio(-1.0f), m_last_mesh(0) - { - } - - shape_morph_def::~shape_morph_def() - { - delete m_last_mesh; - } - - void shape_morph_def::display(character *inst) - { - float ratio = inst->m_ratio; - IF_VERBOSE_ACTION(log_msg("smd: displaying %d at ratio %g\n", - inst->m_id, ratio)); - matrix mat = inst->get_world_matrix(); - cxform cx = inst->get_world_cxform(); - - float max_error = 20.0f / mat.get_max_scale() / - inst->get_parent()->get_pixel_scale(); - if (ratio != m_last_ratio) { - delete m_last_mesh; - m_last_ratio = ratio; - morph_tesselating_shape mts(this, ratio); - m_last_mesh = new mesh_set(&mts, max_error * 0.75f); - } - m_last_mesh->display(mat, cx, m_fill_styles, m_line_styles, ratio); - } - - /* virtual */ void shape_morph_def::tesselate(float error_tolerance, - tesselate::trapezoid_accepter *accepter, - float ratio) - const - { - IF_VERBOSE_ACTION(log_msg("smd: tesselating at ratio %g\n", - ratio)); - - // XXX sharing - tesselate::begin_shape(accepter, error_tolerance); - for (int i = 0; i < m_paths.size(); i++) { - if (m_paths[i].m_new_shape) { - tesselate::end_shape(); - tesselate::begin_shape(accepter, error_tolerance); - } else { - m_paths[i].tesselate(ratio); - } - } - tesselate::end_shape(); - } - - void shape_morph_def::read(stream *in, int tag_type, bool with_style, - movie_definition_sub *m) - { - assert(tag_type == 46); - int pos = in->get_underlying_stream()->get_position(); - IF_VERBOSE_PARSE(log_msg("smd: initial pos %d\n", pos)); - m_bound_orig.read(in); - m_bound_target.read(in); - - IF_VERBOSE_PARSE(log_msg("smd: orig bounds "); - m_bound_orig.print(); - log_msg("smd: target bounds "); - m_bound_target.print()); - - int offset = in->read_u32(); - UNUSED(offset); - pos = in->get_underlying_stream()->get_position(); - - int fill_style_count = in->read_variable_count(); - - IF_VERBOSE_PARSE(log_msg("smd: fsc = %d\n", fill_style_count)); - for (int i = 0; i < fill_style_count; i++) { - m_fill_styles.push_back(morph_fill_style(in, m)); - } - - int line_style_count = in->read_variable_count(); - - IF_VERBOSE_PARSE(log_msg("smd: lsc = %d\n", line_style_count)); - {for (int i = 0; i < line_style_count; i++) { - m_line_styles.push_back(morph_line_style(in)); - }} - - int edges1 = read_shape_record(in, m, true); - IF_VERBOSE_PARSE(log_msg("morph: read %d edges for shape 1\n", - edges1)); - - int pos2 = in->get_underlying_stream()->get_position(); - assert(pos + offset == pos2); - - int edges2 = read_shape_record(in, m, false); - IF_VERBOSE_PARSE(log_msg("morph: read %d edges for shape 2\n", - edges2)); - - assert(edges1 == edges2); - pos2 = in->get_underlying_stream()->get_position(); - IF_VERBOSE_PARSE(log_msg("smd: final pos %d\n", pos2)); - - } - - void shape_morph_def::read_edge(stream* in, edge& e, float& x, float& y) - { - int edge_type = in->read_uint(1); - int bits = 2 + in->read_uint(4); - if (edge_type == 0) { // curved - e.m_cx = x + in->read_sint(bits); - e.m_cy = y + in->read_sint(bits); - x = e.m_ax = e.m_cx + in->read_sint(bits); - y = e.m_ay = e.m_cy + in->read_sint(bits); - if (SHAPE_LOG) IF_VERBOSE_PARSE(log_msg("smd::re: curved edge = %4g %4g - %4g %4g - %4g %4g\n", x, y, e.m_cx, e.m_cy, e.m_ax, e.m_ay)); - return; - } - - // straight edge - int line_flag = in->read_uint(1); - float dx = 0, dy = 0; - if (line_flag) { // general line - dx = float(in->read_sint(bits)); - dy = float(in->read_sint(bits)); - } else { - int vert_flag = in->read_uint(1); - if (vert_flag) { // vertical line - dy = float(in->read_sint(bits)); - } else { - dx = float(in->read_sint(bits)); - } - } - - e.m_cx = x + dx / 2; - e.m_cy = y + dy / 2; - x = e.m_ax = x + dx; - y = e.m_ay = y + dy; - if (SHAPE_LOG) IF_VERBOSE_PARSE(log_msg("smd::re: straight edge = %4g %4g - %4g %4g\n", x - dx, y - dy, x, y)); - } - - int shape_morph_def::read_shape_record(stream* in, - movie_definition_sub* m, - bool start) - { - morph_path current_path; - edge e; - float x = 0, y = 0; - int fill_base = 0, line_base = 0; - int pathidx = 0, edgeidx = 0; - int edge_count = 0; - - in->align(); - int fill_bits = in->read_uint(4); - int line_bits = in->read_uint(4); - IF_VERBOSE_PARSE(log_msg("smd: bits %d/%d\n", - fill_bits, line_bits)); - - if (!start) { - for (int i = 0; i < m_paths.size(); i++) { - int len = m_paths[i].m_edges[0].size(); - m_paths[i].m_edges[1].resize(len); - } - } - - for (;;) { - int type_flag = in->read_uint(1); - if (type_flag == 1) { - // EDGERECORD - read_edge(in, e, x, y); - edge_count++; - if (start) { - current_path.m_edges[0].push_back(e); - continue; - } - array &edges = m_paths[pathidx].m_edges[1]; - edges[edgeidx] = e; - edgeidx++; - while (edgeidx == edges.size()) { - pathidx++; - if (pathidx < m_paths.size()) { - m_paths[pathidx].m_ax[1] = x; - m_paths[pathidx].m_ay[1] = y; - } - edgeidx = 0; - } - - continue; - } - - if (start) { - if (!current_path.is_empty()) { - m_paths.push_back(current_path); - current_path.m_edges[0].resize(0); - } - } else { - if (edgeidx) { - pathidx++; - if (pathidx < m_paths.size()) { - m_paths[pathidx].m_ax[1] = x; - m_paths[pathidx].m_ay[1] = y; - } - edgeidx = 0; - } - } - - int flags = in->read_uint(5); - if (flags == 0) return edge_count; - - if (flags & 0x01) { // MOVETO - int num_move_bits = in->read_uint(5); - x = float(in->read_sint(num_move_bits)); - y = float(in->read_sint(num_move_bits)); - if (SHAPE_LOG) IF_VERBOSE_PARSE(log_msg("morph: MOVETO %g,%g (%d)\n", x, y, num_move_bits)); - } - - // If we're starting a new path, it starts at the - // end (x,y) of the last edge we pushed (possibly - // overridden by a MOVETO record). - if (start) { - current_path.m_ax[0] = x; - current_path.m_ay[0] = y; - } else { - m_paths[pathidx].m_ax[1] = x; - m_paths[pathidx].m_ay[1] = y; - } - - if ((flags & 0x02) && fill_bits) { // FILL0 - assert(start); - int style = in->read_uint(fill_bits); - if (style > 0) style += fill_base; - current_path.m_fill0 = style; - if (SHAPE_LOG) IF_VERBOSE_PARSE(log_msg("morph: fill0 = %d\n", current_path.m_fill0)); - } - - if ((flags & 0x04) && fill_bits) { // FILL1 - assert(start); - int style = in->read_uint(fill_bits); - if (style > 0) style += fill_base; - current_path.m_fill1 = style; - if (SHAPE_LOG) IF_VERBOSE_PARSE(log_msg("morph: fill1 = %d\n", current_path.m_fill1)); - } - - if ((flags & 0x08) && line_bits) { // LINE - assert(start); - int style = in->read_uint(line_bits); - if (style > 0) style += line_base; - current_path.m_line = style; - if (SHAPE_LOG) IF_VERBOSE_PARSE(log_msg("scr: line = %d\n", current_path.m_line)); - } - - if (flags & 0x10) { // NEWSTYLES - assert(start); - // Clear styles. - current_path.m_fill0 = current_path.m_fill1 = - current_path.m_line = -1; - - // Empty path signalling new shape. - // XXX should we start a whole new shape here? - m_paths.push_back(morph_path()); - m_paths.back().m_new_shape = true; - - fill_base = m_fill_styles.size(); - line_base = m_line_styles.size(); - - int count = in->read_variable_count(); - for (int i = 0; i < count; i++) { - m_fill_styles.push_back(morph_fill_style(in, m)); - } - - count = in->read_variable_count(); - {for (int i = 0; i < count; i++) { - m_line_styles.push_back(morph_line_style(in)); - }} - - fill_bits = in->read_uint(4); - fill_bits = in->read_uint(4); - - if (SHAPE_LOG) IF_VERBOSE_PARSE(log_msg("morph: read %d/%d new styles (bits now %d/%d)\n", m_fill_styles.size() - fill_base, m_line_styles.size() - line_base, fill_bits, line_bits)); - - } - } - } - - morph_fill_style::morph_fill_style() - : - m_type(0), - m_bitmap_character(0) - { - } - - morph_fill_style::morph_fill_style(stream* in, movie_definition_sub *m) - : - m_bitmap_character(0) - { - read(in, m); - } - - morph_fill_style::~morph_fill_style() - { - } - - void morph_fill_style::read(stream* in, movie_definition_sub* m) - { - m_type = in->read_u8(); - switch(m_type) { - case 0x00: { - m_color[0].read_rgba(in); - m_color[1].read_rgba(in); - IF_VERBOSE_PARSE(log_msg("fsr: color1 "); - m_color[0].print(); - log_msg("fsr: color2 "); - m_color[1].print()); - return; - } - case 0x10: { // linear gradient fill - m_gradient_matrix[0].set_identity(); - m_gradient_matrix[1].set_identity(); - m_gradient_matrix[0].concatenate_translation(128.f,0.f); - m_gradient_matrix[1].concatenate_translation(128.f,0.f); - m_gradient_matrix[0].concatenate_scale(1.0f / 128.0f); - m_gradient_matrix[1].concatenate_scale(1.0f / 128.0f); - goto read_gradients; - case 0x12: // radial gradient fill - m_gradient_matrix[0].set_identity(); - m_gradient_matrix[1].set_identity(); - m_gradient_matrix[0].concatenate_translation(32.f,32.f); - m_gradient_matrix[1].concatenate_translation(32.f,32.f); - m_gradient_matrix[0].concatenate_scale(1.0f / 512.0f); - m_gradient_matrix[1].concatenate_scale(1.0f / 512.0f); - - read_gradients: - matrix input_matrix, m; - - input_matrix.read(in); - m.set_inverse(input_matrix); - m_gradient_matrix[0].concatenate(m); - - m.set_inverse(input_matrix); - input_matrix.read(in); - m_gradient_matrix[1].concatenate(m); - - // GRADIENT - int num_gradients = in->read_u8(); - IF_VERBOSE_PARSE(log_msg("fsr: num_gradients: %d\n", - num_gradients)); - assert(num_gradients > 0 && num_gradients < 9); - m_gradients[0].resize(num_gradients); - m_gradients[1].resize(num_gradients); - while(num_gradients--) { - m_gradients[0][num_gradients].read(in, 46); - m_gradients[1][num_gradients].read(in, 46); - } - - // @@ hack. - m_color[0] = m_gradients[0][0].m_color; - m_color[1] = m_gradients[1][0].m_color; - return; - } - case 0x40: { // tiled bitmap fill - case 0x41: // clipped bitmap fill - int char_id = in->read_u16(); - IF_VERBOSE_PARSE(log_msg("fsr: bitmap_char = %d\n", - char_id)); - m_bitmap_character = m->get_bitmap_character(char_id); - - matrix m; - - // For some reason, it looks like they store the inverse - // of the TWIPS-to-texcoords matrix. - m.read(in); - m_bitmap_matrix[0].set_inverse(m); - m.read(in); - m_bitmap_matrix[1].set_inverse(m); - return; - } - default: - assert(0); - break; - } - } - - void morph_fill_style::apply(int fill_side, float ratio) const - { - assert(m_type == 0x00); - rgba color; - color.set_lerp(m_color[0], m_color[1], ratio); - gameswf::render::fill_style_color(fill_side, color); - } - - morph_line_style::morph_line_style() - { - m_width[0] = m_width[1] = 0; - } - - morph_line_style::morph_line_style(stream* in) - { - read(in); - } - - void morph_line_style::read(stream* in) - { - m_width[0] = in->read_u16(); - m_width[1] = in->read_u16(); - - m_color[0].read_rgba(in); - m_color[1].read_rgba(in); - - IF_VERBOSE_PARSE(log_msg("mls 1: width %d color ", m_width[0]); - m_color[0].print(); - log_msg("mls 2: width %d color ", m_width[1]); - m_color[1].print()); - } - - void morph_line_style::apply(float ratio) const - { - rgba color; - color.set_lerp(m_color[0], m_color[1], ratio); - gameswf::render::line_style_color(color); - - gameswf::render::line_style_width(flerp(m_width[0], m_width[1], ratio)); - } - - morph_path::morph_path() : - m_fill0(0), m_fill1(0), m_line(0), m_new_shape(false) - { } - - void morph_path::tesselate(float ratio) const - { - tesselate::begin_path(m_fill0 - 1, m_fill1 - 1, m_line - 1, - flerp(m_ax[0], m_ax[1], ratio), - flerp(m_ay[0], m_ay[1], ratio)); - assert(m_edges[0].size() == m_edges[1].size()); - for (int i = 0; i < m_edges[0].size(); i++) { - const edge &e0 = m_edges[0][i], &e1 = m_edges[1][i]; - tesselate::add_curve_segment(flerp(e0.m_cx, e1.m_cx, ratio), - flerp(e0.m_cy, e1.m_cy, ratio), - flerp(e0.m_ax, e1.m_ax, ratio), - flerp(e0.m_ay, e1.m_ay, ratio)); - } - tesselate::end_path(); - } - -} - - -// Local Variables: -// mode: C++ -// c-basic-offset: 8 -// tab-width: 8 -// indent-tabs-mode: t -// End: diff --git a/Code/BF2/External/gameswf/gameswf_morph.h b/Code/BF2/External/gameswf/gameswf_morph.h deleted file mode 100644 index bc838c374..000000000 --- a/Code/BF2/External/gameswf/gameswf_morph.h +++ /dev/null @@ -1,77 +0,0 @@ -// gameswf_morph.h -- Mike Shaver 2003 - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. -// -// Morph directives for shape tweening. - -#ifndef GAMESWF_MORPH_H -#define GAMESWF_MORPH_H - -#include "gameswf_shape.h" -#include "gameswf_styles.h" -#include "gameswf_tesselate.h" - -namespace gameswf -{ - struct morph_path - { - morph_path(); - morph_path(float ax, float ay, int fill0, int fill1, int line); - bool is_empty() const { return m_edges[0].size() == 0; } - void tesselate(float ratio) const; - - int m_fill0, m_fill1, m_line; - float m_ax[2], m_ay[2]; - array m_edges[2]; - bool m_new_shape; - }; - - struct shape_morph_def : public character_def - { - shape_morph_def(); - virtual ~shape_morph_def(); - virtual void display(character *instance_info); - void read(stream* in, int tag_type, bool with_style, - movie_definition_sub* m); - virtual void tesselate(float error_tolerance, tesselate::trapezoid_accepter *accepter, float ratio) const; - - private: - void read_edge(stream* in, edge& e, float& x, float& y); - int read_shape_record(stream* in, movie_definition_sub* m, - bool start); - - rect m_bound_orig, m_bound_target; - array m_fill_styles; - array m_line_styles; - array m_paths; - - float m_last_ratio; - mesh_set *m_last_mesh; - }; - - struct morph_tesselating_shape : public tesselate::tesselating_shape - { - morph_tesselating_shape(shape_morph_def *sh, float ratio) : - m_sh(sh), m_ratio(ratio) { } - virtual void tesselate(float error_tolerance, tesselate::trapezoid_accepter *accepter) const - { - m_sh->tesselate(error_tolerance, accepter, m_ratio); - } - - - private: - shape_morph_def *m_sh; - float m_ratio; - }; - - -} - -#endif /* GAMESWF_MORPH_H */ -// Local Variables: -// mode: C++ -// c-basic-offset: 8 -// tab-width: 8 -// indent-tabs-mode: t -// End: diff --git a/Code/BF2/External/gameswf/gameswf_morph2.cpp b/Code/BF2/External/gameswf/gameswf_morph2.cpp index 6b759e599..83af4b662 100644 --- a/Code/BF2/External/gameswf/gameswf_morph2.cpp +++ b/Code/BF2/External/gameswf/gameswf_morph2.cpp @@ -8,10 +8,35 @@ #include "gameswf_morph2.h" #include "gameswf_stream.h" +#include "../../Platform/X87Compat.h" + +#include namespace gameswf { + // [INFERRED] helper name; inlined in SwiffPlayer.dll 0x1009FE78-0x1009FE98. + static Uint16 morph_line_width(Uint16 start, Uint16 end, float ratio) + { + bf2x87::Real width1(start); + bf2x87::Real width2(end); + bf2x87::Real width = bf2x87::add( + bf2x87::mul(bf2x87::sub(width2, width1), bf2x87::Real(ratio)), width1); + return static_cast(bf2x87::toInt64Truncate( + bf2x87::add(width, bf2x87::Real(0.5f)))); + } + + // [INFERRED] inline-operation helper; SwiffPlayer.dll 0x1009FF1D-0x100A0024 + // stores each coordinate only after subtraction, multiplication and addition. + static float morph_coordinate(float start, float end, float ratio) + { + return bf2x87::store(bf2x87::add(bf2x87::mul( + bf2x87::sub(bf2x87::Real(end), bf2x87::Real(start)), bf2x87::Real(ratio)), + bf2x87::Real(start))); + } + + // SwiffPlayer.dll 0x1009F5D0. + // [CHOSEN, not recovered] S3 bridge: the loader assigns the native definition ID separately. morph2_character_def::morph2_character_def(): m_last_ratio(-1.0f), m_mesh(0) { @@ -20,12 +45,14 @@ namespace gameswf } + // SwiffPlayer.dll 0x1009F680 (deleting veneer 0x1009F710) does not delete m_mesh. morph2_character_def::~morph2_character_def() { delete m_shape2; delete m_shape1; } + // SwiffPlayer.dll 0x1009FDB0. void morph2_character_def::display(character* inst) { int i; @@ -33,7 +60,9 @@ namespace gameswf // bounds rect new_bound; - new_bound.set_lerp(m_shape1->get_bound(), m_shape2->get_bound(), ratio); + rect bound2 = m_shape2->get_bound_copy(); + rect bound1 = m_shape1->get_bound_copy(); + new_bound.set_lerp(bound1, bound2, ratio); set_bound(new_bound); // fill styles @@ -53,7 +82,9 @@ namespace gameswf line_style& ls = m_line_styles[i]; const line_style& ls1 = m_shape1->get_line_styles()[i]; const line_style& ls2 = m_shape2->get_line_styles()[i]; - ls.m_width = (Uint16)frnd(flerp(ls1.get_width(), ls2.get_width(), ratio)); + // SwiffPlayer.dll 0x1009FE78-0x1009FE98: no float store before qword _ftol; + // add 0.5, truncate, then keep AX, including for negative/non-finite inputs. + ls.m_width = morph_line_width(ls1.get_width(), ls2.get_width(), ratio); ls.m_color.set_lerp(ls1.get_color(), ls2.get_color(), ratio); } @@ -75,8 +106,8 @@ namespace gameswf p.m_line = p1.m_line; - p.m_ax = flerp(p1.m_ax, m_shape2->get_paths()[n].m_ax, ratio); - p.m_ay = flerp(p1.m_ay, m_shape2->get_paths()[n].m_ay, ratio); + p.m_ax = morph_coordinate(p1.m_ax, m_shape2->get_paths()[n].m_ax, ratio); + p.m_ay = morph_coordinate(p1.m_ay, m_shape2->get_paths()[n].m_ay, ratio); // edges; int len = p1.m_edges.size(); @@ -84,10 +115,10 @@ namespace gameswf for (int j=0; j < p.m_edges.size(); j++) { - p.m_edges[j].m_cx = flerp(p1.m_edges[j].m_cx, m_shape2->get_paths()[n].m_edges[k].m_cx, ratio); - p.m_edges[j].m_cy = flerp(p1.m_edges[j].m_cy, m_shape2->get_paths()[n].m_edges[k].m_cy, ratio); - p.m_edges[j].m_ax = flerp(p1.m_edges[j].m_ax, m_shape2->get_paths()[n].m_edges[k].m_ax, ratio); - p.m_edges[j].m_ay = flerp(p1.m_edges[j].m_ay, m_shape2->get_paths()[n].m_edges[k].m_ay, ratio); + p.m_edges[j].m_cx = morph_coordinate(p1.m_edges[j].m_cx, m_shape2->get_paths()[n].m_edges[k].m_cx, ratio); + p.m_edges[j].m_cy = morph_coordinate(p1.m_edges[j].m_cy, m_shape2->get_paths()[n].m_edges[k].m_cy, ratio); + p.m_edges[j].m_ax = morph_coordinate(p1.m_edges[j].m_ax, m_shape2->get_paths()[n].m_edges[k].m_ax, ratio); + p.m_edges[j].m_ay = morph_coordinate(p1.m_edges[j].m_ay, m_shape2->get_paths()[n].m_edges[k].m_ay, ratio); k++; if (m_shape2->get_paths()[n].m_edges.size() <= k) { @@ -100,17 +131,21 @@ namespace gameswf matrix mat = inst->get_world_matrix(); cxform cx = inst->get_world_cxform(); - float max_error = 20.0f / mat.get_max_scale() / inst->get_parent()->get_pixel_scale(); + // SwiffPlayer.dll 0x100A00A2-0x100A00BA stores after each division. + float max_error = bf2x87::store(bf2x87::div(bf2x87::Real(20.0f), shape_matrix_max_scale(mat))); + max_error /= inst->get_parent()->get_pixel_scale(); if (ratio != m_last_ratio) { delete m_mesh; m_last_ratio = ratio; - m_mesh = new mesh_set(this, max_error * 0.75f); + // SwiffPlayer.dll 0x100A0100-0x100A0120 retains null on allocation failure. + m_mesh = new (std::nothrow) mesh_set(this, max_error * 0.75f); } - m_mesh->display(mat, cx, m_fill_styles, m_line_styles); + m_mesh->display(mat, cx, m_fill_styles, m_line_styles, inst->get_depth()); } + // SwiffPlayer.dll 0x1009F780. void morph2_character_def::read(stream* in, int tag_type, bool with_style, movie_definition_sub* md) { UNUSED(tag_type); diff --git a/Code/BF2/External/gameswf/gameswf_movie.cpp b/Code/BF2/External/gameswf/gameswf_movie.cpp deleted file mode 100644 index 75e0eeb8e..000000000 --- a/Code/BF2/External/gameswf/gameswf_movie.cpp +++ /dev/null @@ -1,605 +0,0 @@ -// gameswf_xml.h -- Rob Savoye 2005 - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - - -#include "base/tu_config.h" -#include -#include - -#ifdef HAVE_LIBXML -// TODO: http and sockets and such ought to be factored out into an -// abstract driver, like we do for file access. -#include -#ifdef HAVE_WINSOCK -# include -# include -# include -#else -# include -# include -#endif -#endif -#include "gameswf_movie.h" -#include "gameswf_log.h" -#include "base/tu_file.h" -#include "base/image.h" -#include "gameswf_render.h" -#include "gameswf_impl.h" - - -namespace gameswf -{ - - - MovieClipLoader::MovieClipLoader() - // : character(0, 0) -{ - log_msg("%s: \n", __FUNCTION__); - _mcl.bytes_loaded = 0; - _mcl.bytes_total = 0; -} - -MovieClipLoader::~MovieClipLoader() -{ - log_msg("%s: \n", __FUNCTION__); -} - -void -MovieClipLoader::load(const tu_string& filespec) -{ - log_msg("%s: \n", __FUNCTION__); -} - -// progress of the downloaded file(s). -struct mcl * -MovieClipLoader::getProgress(as_object *ao) -{ - //log_msg("%s: \n", __FUNCTION__); - - return &_mcl; -} - - -bool -MovieClipLoader::loadClip(const tu_string& str, void *) -{ - log_msg("%s: \n", __FUNCTION__); - - return false; -} - -void -MovieClipLoader::unloadClip(void *) -{ - log_msg("%s: \n", __FUNCTION__); -} - - -void -MovieClipLoader::addListener(void *) -{ - log_msg("%s: \n", __FUNCTION__); -} - - -void -MovieClipLoader::removeListener(void *) -{ - log_msg("%s: \n", __FUNCTION__); -} - - -// Callbacks -void -MovieClipLoader::onLoadStart(void *) -{ - log_msg("%s: \n", __FUNCTION__); -} - -void -MovieClipLoader::onLoadProgress(void *) -{ - log_msg("%s: \n", __FUNCTION__); -} - -void -MovieClipLoader::onLoadInit(void *) -{ - log_msg("%s: \n", __FUNCTION__); -} - -void -MovieClipLoader::onLoadComplete(void *) -{ - log_msg("%s: \n", __FUNCTION__); -} - -void -MovieClipLoader::onLoadError(void *) -{ - log_msg("%s: \n", __FUNCTION__); -} - -void -MovieClipLoader::on_button_event(event_id event) -{ - log_msg("%s: \n", __FUNCTION__); - - // Set our mouse state (so we know how to render). - switch (event.m_id) - { - case event_id::ROLL_OUT: - case event_id::RELEASE_OUTSIDE: - _mouse_state = MOUSE_UP; - break; - - case event_id::RELEASE: - case event_id::ROLL_OVER: - case event_id::DRAG_OUT: - _mouse_state = MOUSE_OVER; - break; - - case event_id::PRESS: - case event_id::DRAG_OVER: - _mouse_state = MOUSE_DOWN; - break; - - default: - assert(0); // missed a case? - break; - }; - - // @@ eh, should just be a lookup table. -#if 0 - // Add appropriate actions to the movie's execute list... - for (int i = 0; i < m_def->m_button_actions.size(); i++) { - if (m_def->m_button_actions[i].m_conditions & c) { - // Matching action. - for (int j = 0; j < m_def->m_button_actions[i].m_actions.size(); j++) { - get_parent()->add_action_buffer(m_def->m_button_actions[i].m_actions[j]); - } - } - } -#endif - // Call conventional attached method. - // @@ TODO -} - -void moviecliploader_loadclip(const fn_call& fn) -{ -#ifdef HAVE_LIBXML - //as_value* result = fn.result; - //as_object_interface* this_ptr = fn.this_ptr; - //int nargs = fn.nargs; - //int first_arg = fn.first_arg_bottom_index; - //as_environment* env = fn.env; - - as_value val, method; - struct stat stats; - int fd; - - fn.result->set(true); // FIXME: - log_msg("%s: FIXME: this function disabled for memory leak testing.\n", __FUNCTION__); - return; // FIXME: - - log_msg("%s: nargs = %d\n", __FUNCTION__, fn.nargs); - moviecliploader_as_object* ptr = (moviecliploader_as_object*) (as_object*) fn.this_ptr; - - tu_string url = fn.env->bottom(fn.first_arg_bottom_index).to_string(); - as_object *target = (as_object *)fn.env->bottom(fn.first_arg_bottom_index-1).to_object(); - log_msg("load clip: %s, target is: %p\n", url.c_str(), target); - - xmlNanoHTTPInit(); // This doesn't do much for now, but in the - // future it might, so here it is... - - if (url.utf8_substring(0, 4) == "file") { - url = url.utf8_substring(19, url.length()); - // If the file doesn't exist, don't try to do anything. - if (stat(url.c_str(), &stats) < 0) { - fprintf(stderr, "ERROR: doesn't exist: %s\n", url.c_str()); - fn.result->set(false); - return; - } - } - - if (target == NULL) { - //log_error("target doesn't exist:\n"); - fn.result->set(false); - return; - } - - // Grab the filename off the end of the URL, and use the same name - // as the disk file when something is fetched. Store files in /tmp/. - // If the file exists, libxml properly replaces it. - char *filename = strrchr(url.c_str(), '/'); - tu_string filespec = "/tmp"; - filespec += filename; - - // fetch resource from URL - xmlNanoHTTPFetch(url.c_str(), filespec.c_str(), NULL); - - // Call the callback since we've started loading the file - if (fn.this_ptr->get_member("onLoadStart", &method)) { - //log_msg("FIXME: Found onLoadStart!\n"); - as_c_function_ptr func = method.to_c_function(); - fn.env->set_variable("success", true, 0); - if (func) - { - // It's a C function. Call it. - //log_msg("Calling C function for onLoadStart\n"); - (*func)(fn_call(&val, fn.this_ptr, fn.env, 0, 0)); - } - else if (as_as_function* as_func = method.to_as_function()) - { - // It's an ActionScript function. Call it. - //log_msg("Calling ActionScript function for onLoadStart\n"); - (*as_func)(fn_call(&val, fn.this_ptr, fn.env, 0, 0)); - } - else - { - log_error("error in call_method(): method is not a function\n"); - } - } else { - log_error("Couldn't find onLoadStart!\n"); - } - xmlNanoHTTPCleanup(); - - // See if the file exists - if (stat(filespec.c_str(), &stats) < 0) { - log_error("Clip doesn't exist: %s\n", filespec.c_str()); - fn.result->set(false); - return; - } - - tu_string suffix = filespec.utf8_substring(filespec.length() - 4, filespec.length()); - //log_msg("File suffix to load is: %s\n", suffix.c_str()); - - if (suffix == ".swf") { - movie_definition_sub* md = create_library_movie_sub(filespec.c_str()); - if (md == NULL) { - log_error("can't create movie_definition_sub for %s\n", filespec.c_str()); - return; - } - gameswf::movie_interface* extern_movie; - extern_movie = md->create_instance(); - if (extern_movie == NULL) { - log_error("can't create extern movie_interface for %s\n", filespec.c_str()); - return; - } - - save_extern_movie(extern_movie); - - character* tar = (character*)target; - const char* name = tar->get_name(); - Uint16 depth = tar->get_depth(); - bool use_cxform = false; - cxform color_transform = tar->get_cxform(); - bool use_matrix = false; - matrix mat = tar->get_matrix(); - float ratio = tar->get_ratio(); - Uint16 clip_depth = tar->get_clip_depth(); - - movie* parent = tar->get_parent(); - movie* new_movie = static_cast(extern_movie)->get_root_movie(); - - assert(parent != NULL); - - ((character*)new_movie)->set_parent(parent); - - parent->replace_display_object((character*) new_movie, - name, - depth, - use_cxform, - color_transform, - use_matrix, - mat, - ratio, - clip_depth); - } else if (suffix == ".jpg") { - // Just case the filespec suffix claims it's a jpeg, we have to check, - // since when grabbing an image from a web server that doesn't exist, - // we don't get an error, we get a short HTML page containing a 404. - if ((fd = open(filespec.c_str(), O_RDONLY)) > 0) { - unsigned char buf[5]; - memset(buf, 0, 5); - if (read(fd, buf, 4)) { - close(fd); // we don't need this anymore - // This is the magic number for any JPEG format file - if ((buf[0] == 0xff) && (buf[1] == 0xd8) && (buf[2] == 0xff)) { - //log_msg("File is a JPEG!\n"); - } else { - //log_error("File is not a JPEG!\n"); - unlink(filespec.c_str()); - fn.result->set(false); - return; - } - } else { - log_error("Can't read image header!\n"); - unlink(filespec.c_str()); - fn.result->set(false); - return; - } - } else { - log_error("Can't open image!\n"); - unlink(filespec.c_str()); - fn.result->set(false); - return; - } - - bitmap_info* bi = NULL; - image::rgb* im = image::read_jpeg(filespec.c_str()); - if (im != NULL) { - bi = render::create_bitmap_info_rgb(im); - delete im; - } else { - log_error("Can't read jpeg: %s\n", filespec.c_str()); - } - - //bitmap_character* ch = new bitmap_character(bi); - - movie *mov = target->to_movie(); - //movie_definition *def = mov->get_movie_definition(); - //movie_definition_sub *m = (movie_definition_sub *)mov; - //target->add_bitmap_info(bi); - - character* tar = (character*)mov; - const char* name = tar->get_name(); - Uint16 id = tar->get_id(); - //log_msg("Target name is: %s, ID: %d\n", name, id); - - // FIXME: none of this works yet - - //movie_definition *md = create_library_movie(filespec.c_str()); - // add image to movie, under character id. - //m->add_bitmap_character(666, ch); - -// #if 1 - tu_string swfm = filespec.utf8_substring(0, filespec.length() - 3); - swfm += "swf"; - - movie_definition_sub *ms = create_movie_sub(swfm.c_str()); - // The file may not exist. - if (ms) { - movie_interface* extern_movie = create_library_movie_inst_sub(ms); - character * newchar = ms->create_character_instance(tar->get_parent(), id); - } - - //save_extern_movie(extern_movie); - //movie* new_movie = static_cast(extern_movie)->get_root_movie(); - -// #else -// movie_definition_sub *ms; -// ms->add_bitmap_info(bi); -// #endif - //movie* m = mov->get_root_movie(); - //set_current_root(extern_movie); - //movie* m = static_cast(extern_movie)->get_root_movie(); - mov->on_event(event_id::LOAD); - //add_display_object(); - - //Uint16 depth = tar->get_depth(); - bool use_cxform = false; - //cxform color_transform = tar->get_cxform(); - bool use_matrix = false; - matrix mat = tar->get_matrix(); - //float ratio = tar->get_ratio(); - //Uint16 clip_depth = tar->get_clip_depth(); - array dummy_event_handlers; - movie* parent = tar->get_parent(); - - character *newch = new character(parent, id); - -#if 0 - parent->clone_display_object(name, "album_image", depth); - parent->add_display_object((Uint16)id, - name, - dummy_event_handlers, - tar->get_depth(), - true, - tar->get_cxform(), - tar->get_matrix(), - tar->get_ratio(), - tar->get_clip_depth()); -#endif - - parent->replace_display_object(newch, - name, - tar->get_depth(), - use_cxform, - tar->get_cxform(), - use_matrix, - tar->get_matrix(), - tar->get_ratio(), - tar->get_clip_depth()); - } - - struct mcl *mcl_data = ptr->mov_obj.getProgress(target); - - // the callback since we're done loading the file - // FIXME: these both probably shouldn't be set to the same value - mcl_data->bytes_loaded = stats.st_size; - mcl_data->bytes_total = stats.st_size; - - fn.env->set_member("target_mc", target); - //env->push(as_value(target)); - //moviecliploader_onload_complete(result, this_ptr, env, 0, 0); - moviecliploader_onload_complete(fn); - //env->pop(); - - fn.result->set(true); - - //unlink(filespec.c_str()); - - //xmlNanoHTTPCleanup(); - -#endif // HAVE_LIBXML -} - -void -moviecliploader_unloadclip(const fn_call& fn) -{ - const tu_string filespec = fn.arg(0).to_string(); - log_msg("%s: FIXME: Load Movie Clip: %s\n", __FUNCTION__, filespec.c_str()); - -} - -void -moviecliploader_new(const fn_call& fn) -{ - - log_msg("%s: args=%d\n", __FUNCTION__, fn.nargs); - - const tu_string filespec = fn.arg(0).to_string(); - - as_object* mov_obj = new moviecliploader_as_object; - //log_msg("\tCreated New MovieClipLoader object at %p\n", mov_obj); - - mov_obj->set_member("loadClip", - &moviecliploader_loadclip); - mov_obj->set_member("unloadClip", - &moviecliploader_unloadclip); - mov_obj->set_member("getProgress", - &moviecliploader_getprogress); - -#if 0 - // Load the default event handlers. These should really never - // be called directly, as to be useful they are redefined - // within the SWF script. These get called if there is a problem - // Setup the event handlers - mov_obj->set_event_handler(event_id::LOAD_INIT, - (as_c_function_ptr)&event_test); - mov_obj->set_event_handler(event_id::LOAD_START, - (as_c_function_ptr)&event_test); - mov_obj->set_event_handler(event_id::LOAD_PROGRESS, - (as_c_function_ptr)&event_test); - mov_obj->set_event_handler(event_id::LOAD_ERROR, - (as_c_function_ptr)&event_test); -#endif - - fn.result->set_as_object_interface(mov_obj); -} - -void -moviecliploader_onload_init(const fn_call& fn) -{ - log_msg("%s: FIXME: Default event handler, you shouldn't be here!\n", __FUNCTION__); -} - -// Invoked when a call to MovieClipLoader.loadClip() has successfully -// begun to download a file. -void -moviecliploader_onload_start(const fn_call& fn) -{ - log_msg("%s: FIXME: Default event handler, you shouldn't be here!\n", __FUNCTION__); -} - -// Invoked every time the loading content is written to disk during -// the loading process. -void -moviecliploader_getprogress(const fn_call& fn) -{ - //log_msg("%s: nargs = %d\n", __FUNCTION__, nargs); - - moviecliploader_as_object* ptr = (moviecliploader_as_object*) (as_object*) fn.this_ptr; - assert(ptr); - - as_object *target = (as_object*) fn.arg(0).to_object(); - - struct mcl *mcl_data = ptr->mov_obj.getProgress(target); - - mcl_as_object *mcl_obj = (mcl_as_object *)new mcl_as_object; - - mcl_obj->set_member("bytesLoaded", mcl_data->bytes_loaded); - mcl_obj->set_member("bytesTotal", mcl_data->bytes_total); - - fn.result->set_as_object_interface(mcl_obj); -} - -// Invoked when a file loaded with MovieClipLoader.loadClip() has -// completely downloaded. -void -moviecliploader_onload_complete(const fn_call& fn) -{ - as_value val, method; - //log_msg("%s: FIXME: nargs = %d\n", __FUNCTION__, nargs); - //moviecliploader_as_object* ptr = (moviecliploader_as_object*) (as_object*) this_ptr; - - tu_string url = fn.arg(0).to_string(); - //as_object *target = (as_object *)env->bottom(first_arg-1).to_object(); - //log_msg("load clip: %s, target is: %p\n", url.c_str(), target); - - //log_msg("%s: FIXME: Default event handler, you shouldn't be here!\n", __FUNCTION__); - if (fn.this_ptr->get_member("onLoadComplete", &method)) { - //log_msg("FIXME: Found onLoadComplete!\n"); - as_c_function_ptr func = method.to_c_function(); - fn.env->set_variable("success", true, 0); - if (func) - { - // It's a C function. Call it. - //log_msg("Calling C function for onLoadComplete\n"); - (*func)(fn_call(&val, fn.this_ptr, fn.env, 0, 0)); - } - else if (as_as_function* as_func = method.to_as_function()) - { - // It's an ActionScript function. Call it. - //log_msg("Calling ActionScript function for onLoadComplete\n"); - (*as_func)(fn_call(&val, fn.this_ptr, fn.env, 0, 0)); - } - else - { - log_error("error in call_method(): method is not a function\n"); - } - } else { - log_error("Couldn't find onLoadComplete!\n"); - } -} - -// Invoked when a file loaded with MovieClipLoader.loadClip() has failed to load. -void -moviecliploader_onload_error(const fn_call& fn) -{ - //log_msg("%s: FIXME: Default event handler, you shouldn't be here!\n", __FUNCTION__); - as_value val, method; - log_msg("%s: FIXME: nargs = %d\n", __FUNCTION__, fn.nargs); - //moviecliploader_as_object* ptr = (moviecliploader_as_object*) (as_object*) this_ptr; - - tu_string url = fn.arg(0).to_string(); - as_object *target = (as_object*) fn.arg(1).to_object(); - log_msg("load clip: %s, target is: %p\n", url.c_str(), target); - - //log_msg("%s: FIXME: Default event handler, you shouldn't be here!\n", __FUNCTION__); - if (fn.this_ptr->get_member("onLoadError", &method)) { - //log_msg("FIXME: Found onLoadError!\n"); - as_c_function_ptr func = method.to_c_function(); - fn.env->set_variable("success", true, 0); - if (func) - { - // It's a C function. Call it. - log_msg("Calling C function for onLoadError\n"); - (*func)(fn_call(&val, fn.this_ptr, fn.env, 0, 0)); - } - else if (as_as_function* as_func = method.to_as_function()) - { - // It's an ActionScript function. Call it. - log_msg("Calling ActionScript function for onLoadError\n"); - (*as_func)(fn_call(&val, fn.this_ptr, fn.env, 0, 0)); - } - else - { - log_error("error in call_method(): method is not a function\n"); - } - } else { - log_error("Couldn't find onLoadError!\n"); - } -} - -// This is the default event handler. To wind up here is an error. -void -moviecliploader_default(const fn_call& fn) -{ - log_msg("%s: FIXME: Default event handler, you shouldn't be here!\n", __FUNCTION__); -} - -} // end of gameswf namespace diff --git a/Code/BF2/External/gameswf/gameswf_movie.h b/Code/BF2/External/gameswf/gameswf_movie.h deleted file mode 100644 index 2c8929e80..000000000 --- a/Code/BF2/External/gameswf/gameswf_movie.h +++ /dev/null @@ -1,83 +0,0 @@ -#ifndef __MOVIE_H__ -#define __MOVIE_H__ - -#include "gameswf_button.h" -#include "gameswf_log.h" -#include "gameswf_action.h" -#include "gameswf_impl.h" - -namespace gameswf -{ - struct mcl { - int bytes_loaded; - int bytes_total; - }; - -#if 0 -struct MovieClipLoader : public character -{ - MovieClipLoader(movie* parent, int id) : - character(parent, id) - { - log_msg("%s: \n", __FUNCTION__); - } -#else - class MovieClipLoader - { -#endif - public: - MovieClipLoader(); - - ~MovieClipLoader(); - - void load(const tu_string& filespec); - - struct mcl *getProgress(as_object *ao); - - bool loadClip(const tu_string& str, void *); - void unloadClip(void *); - void addListener(void *); - void removeListener(void *); - - void on_button_event(event_id event); - // Callbacks - void onLoadStart(void *); - void onLoadProgress(void *); - void onLoadInit(void *); - void onLoadComplete(void *); - void onLoadError(void *); - private: - bool _started; - bool _completed; - tu_string _filespec; - int _progress; - bool _error; - struct mcl _mcl; - mouse_state _mouse_state; -}; - -struct moviecliploader_as_object : public gameswf::as_object -{ - MovieClipLoader mov_obj; -}; - -struct mcl_as_object : public gameswf::as_object -{ - struct mcl data; -}; - -void moviecliploader_loadclip(const fn_call& fn); -void moviecliploader_unloadclip(const fn_call& fn); -void moviecliploader_getprogress(const fn_call& fn); -void moviecliploader_new(const fn_call& fn); -void moviecliploader_onload_init(const fn_call& fn); -void moviecliploader_onload_start(const fn_call& fn); -void moviecliploader_onload_progress(const fn_call& fn); -void moviecliploader_onload_complete(const fn_call& fn); -void moviecliploader_onload_error(const fn_call& fn); -void moviecliploader_default(const fn_call& fn); - -} // end of gameswf namespace - -// __MOVIE_H__ -#endif diff --git a/Code/BF2/External/gameswf/gameswf_parser.cpp b/Code/BF2/External/gameswf/gameswf_parser.cpp deleted file mode 100644 index 85e8f1cb0..000000000 --- a/Code/BF2/External/gameswf/gameswf_parser.cpp +++ /dev/null @@ -1,613 +0,0 @@ -// gameswf_parser.cpp -- Willem Kokke 2003 - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - -// A program to parse SWF files into text output. - -#include "base/tu_file.h" -#include "base/zlib_adapter.h" -#include "base/image.h" -#include "base/jpeg.h" - -#include "gameswf_stream.h" -#include "gameswf_log.h" -#include "gameswf.h" - -#define TWIPS_TO_PIXELS(x) ((x) / 20.f) -#define PIXELS_TO_TWIPS(x) ((x) * 20.f) - -using gameswf::stream; -using gameswf::log_msg; - -namespace parser -{ - static int ident = 0; - static int current_frame = 0; - tu_file* out; - - typedef void (*loader_function)(stream* input, int tag_type); - static hash tag_loaders; - - void register_tag_loader(int tag_type, loader_function lf) - { - assert(tag_loaders.get(tag_type, NULL) == false); - assert(lf != NULL); - tag_loaders.add(tag_type, lf); - } - - void log_callback(bool error, const char* message) - { - static char buf[512]; - - strcpy(buf,""); - - for (int i=0; iwrite_string(buf); - fputs(buf,stdout); - } - - // parse a matrix - struct matrix - { - static float m_[2][3]; - static bool has_scale, has_rotate; - static void parse(stream* in) - { - in->align(); - - memset(&m_[0], 0, sizeof(m_)); - m_[0][0] = 1; - m_[1][1] = 1; - - int has_scale = in->read_uint(1); - if (has_scale) - { - int scale_nbits = in->read_uint(5); - m_[0][0] = in->read_sint(scale_nbits) / 65536.0f; - m_[1][1] = in->read_sint(scale_nbits) / 65536.0f; - } - int has_rotate = in->read_uint(1); - if (has_rotate) - { - int rotate_nbits = in->read_uint(5); - m_[1][0] = in->read_sint(rotate_nbits) / 65536.0f; - m_[0][1] = in->read_sint(rotate_nbits) / 65536.0f; - } - - int translate_nbits = in->read_uint(5); - if (translate_nbits > 0) - { - m_[0][2] = (float) in->read_sint(translate_nbits); - m_[1][2] = (float) in->read_sint(translate_nbits); - } - } - static void write() - { - ident++; - log_msg("has_scale = %d, has_rotate = %d\n", has_scale, has_rotate); - log_msg("| %4.4f %4.4f %4.4f |\n", m_[0][0], m_[0][1], TWIPS_TO_PIXELS(m_[0][2])); - log_msg("| %4.4f %4.4f %4.4f |\n", m_[1][0], m_[1][1], TWIPS_TO_PIXELS(m_[1][2])); - ident--; - } - - }; - float matrix::m_[2][3]; - bool matrix::has_scale, matrix::has_rotate; - - struct rect - { - static Uint32 x_min,x_max,y_min,y_max; - static void parse(stream* in) - { - in->align(); - int nbits = in->read_uint(5); - x_min = in->read_sint(nbits); - x_max = in->read_sint(nbits); - y_min = in->read_sint(nbits); - y_max = in->read_sint(nbits); - } - static void write() - { - ident++; - log_msg("x_min: %i, x_max: %i, width: %i twips, %4.0f pixels\n", x_min, x_max, x_max - x_min, TWIPS_TO_PIXELS(x_max - x_min)); - log_msg("y_min: %i, y_max: %i, height: %i twips, %4.0f pixels\n", y_min, y_max, y_max - y_min, TWIPS_TO_PIXELS(y_max - y_min)); - ident--; - } - }; - Uint32 rect::x_min; - Uint32 rect::y_min; - Uint32 rect::x_max; - Uint32 rect::y_max; - - struct rgb - { - static Uint8 m_r, m_g, m_b; - static void parse(stream* in) - { - m_r = in->read_u8(); - m_g = in->read_u8(); - m_b = in->read_u8(); - } - static void write() - { - ident++; - log_msg("rgb: %d %d %d \n", m_r, m_g, m_b); - ident--; - } - }; - Uint8 rgb::m_r; - Uint8 rgb::m_g; - Uint8 rgb::m_b; - - struct rgba - { - static Uint8 m_r, m_g, m_b, m_a; - static void parse(stream* in) - { - m_r = in->read_u8(); - m_g = in->read_u8(); - m_b = in->read_u8(); - m_a = in->read_u8(); - } - static void write() - { - ident++; - log_msg("rgba: %d %d %d %d\n", m_r, m_g, m_b, m_a); - ident--; - } - }; - Uint8 rgba::m_r; - Uint8 rgba::m_g; - Uint8 rgba::m_b; - Uint8 rgba::m_a; - - struct cxform - { - static float m_[4][2]; - static bool has_add, has_mult; - - static void parse_rgb(stream* in) - { - in->align(); - - int has_add = in->read_uint(1); - int has_mult = in->read_uint(1); - int nbits = in->read_uint(4); - - if (has_mult) { - m_[0][0] = in->read_sint(nbits) / 255.0f; - m_[1][0] = in->read_sint(nbits) / 255.0f; - m_[2][0] = in->read_sint(nbits) / 255.0f; - m_[3][0] = 1; - } - else { - for (int i = 0; i < 4; i++) { m_[i][0] = 1; } - } - if (has_add) { - m_[0][1] = (float) in->read_sint(nbits); - m_[1][1] = (float) in->read_sint(nbits); - m_[2][1] = (float) in->read_sint(nbits); - m_[3][1] = 1; - } - else { - for (int i = 0; i < 4; i++) { m_[i][1] = 0; } - } - } - static void parse_rgba(stream* in) - { - in->align(); - - int has_add = in->read_uint(1); - int has_mult = in->read_uint(1); - int nbits = in->read_uint(4); - - if (has_mult) { - m_[0][0] = in->read_sint(nbits) / 255.0f; - m_[1][0] = in->read_sint(nbits) / 255.0f; - m_[2][0] = in->read_sint(nbits) / 255.0f; - m_[3][0] = in->read_sint(nbits) / 255.0f; - } - else { - for (int i = 0; i < 4; i++) { m_[i][0] = 1; } - } - if (has_add) { - m_[0][1] = (float) in->read_sint(nbits); - m_[1][1] = (float) in->read_sint(nbits); - m_[2][1] = (float) in->read_sint(nbits); - m_[3][1] = (float) in->read_sint(nbits); - } - else { - for (int i = 0; i < 4; i++) { m_[i][1] = 0; } - } - } - static void write() - { - ident++; - log_msg("cxform:\n"); - log_msg("has_add = %d, has_mult = %d\n", has_add, has_mult); - log_msg("| %4.4f %4.4f |\n", m_[0][0], m_[0][1]); - log_msg("| %4.4f %4.4f |\n", m_[1][0], m_[1][1]); - log_msg("| %4.4f %4.4f |\n", m_[2][0], m_[2][1]); - log_msg("| %4.4f %4.4f |\n", m_[3][0], m_[3][1]); - ident--; - } - }; - float cxform::m_[4][2]; - bool cxform::has_add; - bool cxform::has_mult; - - // tag 0 - void parse_end_movie(stream* input, int tag_type) - { - assert(tag_type == 0); - ident--; - log_msg("\n"); - log_msg("Movie ended\n\n"); - } - - // tag 1 - void parse_show_frame(stream* input, int tag_type) - { - assert(tag_type == 1); - ident--; - current_frame++; - log_msg("\n"); - log_msg("show frame %i\n\n", current_frame); - ident++; - } - - // tag 2, 22, 32 - void parse_define_shape123(stream* input, int tag_type) - { - assert(tag_type == 2 || tag_type == 22 || tag_type == 32); - if(tag_type == 2) - log_msg("define_shape:\n"); - if(tag_type == 22) - log_msg("define_shape2:\n"); - if(tag_type == 32) - log_msg("define_shape3:\n"); - ident++; - log_msg("character ID: %i\n", input->read_u16()); - ident--; - } - - // tag 4, 26 - void parse_place_object12(stream* input, int tag_type) - { - assert(tag_type == 4 || tag_type == 26); - - if (tag_type == 4) - { - log_msg("place_object:\n"); - ident++; - log_msg("character ID: %i\n",input->read_u16()); - log_msg("depth: %i\n",input->read_u16()); - log_msg("matrix:\n"); - matrix::parse(input); - matrix::write(); - - if (input->get_position() < input->get_tag_end_position()) - { - log_msg("color transform:\n"); - cxform::parse_rgb(input); - cxform::write(); - } - ident--; - } - else if (tag_type == 26) - { - input->align(); - - log_msg("place_object2:\n"); - ident++; - - bool has_actions = input->read_uint(1) ? true : false; - bool has_clip_depth = input->read_uint(1) ? true : false; - bool has_name = input->read_uint(1) ? true : false; - bool has_ratio = input->read_uint(1) ? true : false; - bool has_cxform = input->read_uint(1) ? true : false; - bool has_matrix = input->read_uint(1) ? true : false; - bool has_char = input->read_uint(1) ? true : false; - bool flag_move = input->read_uint(1) ? true : false; - - UNUSED(has_actions); - - log_msg("depth: %i\n",input->read_u16()); - - if (has_char) { - log_msg("character ID: %i\n",input->read_u16()); - } - if (has_matrix) { - log_msg("matrix:\n"); - matrix::parse(input); - matrix::write(); - } - if (has_cxform) { - log_msg("color transform:"); - cxform::parse_rgba(input); - cxform::write(); - } - if (has_ratio) { - log_msg("ratio: %i\n",input->read_u16()); - } - if (has_name) { - log_msg("name: %s\n",input->read_string()); - } - if (has_clip_depth) { - log_msg("clipdepth: %i\n",input->read_u16()); - } - if (has_clip_depth) { - log_msg("has_actions: to be implemented\n"); - } - - if (has_char == true && flag_move == true) - { - log_msg("replacing a character previously at this depth\n"); - } - else if (has_char == false && flag_move == true) - { - log_msg("moving a character previously at this depth\n"); - } - else if (has_char == true && flag_move == false) - { - log_msg("placing a character first time at this depth\n"); - } - - ident--; - } - } - - // tag 5, 28 - void parse_remove_object12(stream* input, int tag_type) - { - assert(tag_type == 5 || tag_type == 28); - if (tag_type==5) - { - log_msg("remove_object\n"); - ident++; - log_msg("character ID: %i\n", input->read_u16()); - log_msg("depth: %i\n", input->read_u16()); - ident--; - } - if (tag_type==28) - { - log_msg("remove_object_2\n"); - ident++; - log_msg("depth: %i\n", input->read_u16()); - ident--; - } - } - - // tag 46 - void parse_define_shape_morph(stream *input, int tag_type) - { - assert(tag_type == 46); - log_msg("define_shape_morph\n"); - ident++; - log_msg("character ID: %i\n", input->read_u16()); - ident--; - } - - // tag 6 - void parse_define_bits(stream* input, int tag_type) - { - assert(tag_type==6); - log_msg("define jpeg bits\n"); - ident++; - log_msg("character ID: %i\n", input->read_u16()); - ident--; - } - - void parse_jpeg_tables(stream* input, int tag_type) - { - assert(tag_type==8); - log_msg("define jpeg table\n\n"); - } - - void parse_set_background_color(stream* input, int tag_type) - { - assert(tag_type==9); - rgb::parse(input); - log_msg("set background color to:\n"); - rgb::write(); - } - - void parse_do_action(stream* input, int tag_type) - { - assert(tag_type==12); - log_msg("do action:\n"); - ident++; - log_msg("to be implemented\n"); - ident--; - } - - void parse_define_sprite(stream* input, int tag_type) - { - assert(tag_type==39); - log_msg("define a new sprite:\n"); - ident++; - int tag_end = input->get_tag_end_position(); - Uint32 char_id = input->read_u16(); - Uint32 sprite_frame_count = input->read_u16(); - log_msg("character ID: %i\n", char_id); - log_msg("frame count of sprite: %i\n", sprite_frame_count); - Uint32 old_current_frame = current_frame; - current_frame = 0; - - ident++; - log_msg("\n"); - log_msg("starting frame 0\n\n"); - ident++; - - while ((Uint32) input->get_position() < (Uint32) tag_end) - { - int tag_type = input->open_tag(); - loader_function lf = NULL; - - if (tag_type == 0) - { - ident--; - ident--; - ident--; - log_msg("end of sprite definition\n\n"); - } - else if (tag_loaders.get(tag_type, &lf)) - { - (*lf)(input, tag_type); - } - else - { - log_msg("warning: no tag loader for tag_type %d\n", tag_type); - } - input->close_tag(); - } - current_frame = old_current_frame; - } - - void parse_set_framelabel(stream* input, int tag_type) - { - assert(tag_type==43); - log_msg("current framelabel:\n"); - ident++; - char* str = input->read_string(); - log_msg("%s\n",str); - delete str; - - if (input->get_position() < input->get_tag_end_position()) - { - //TODOm_color_transform.read_rgb(in); - } - ident--; - } - - void parse_swf(tu_file* file) - { - register_tag_loader(0,parse_end_movie); - register_tag_loader(1,parse_show_frame); - register_tag_loader(2,parse_define_shape123); - register_tag_loader(4,parse_place_object12); - register_tag_loader(5,parse_remove_object12); - register_tag_loader(6,parse_define_bits); - register_tag_loader(8,parse_jpeg_tables); - register_tag_loader(9,parse_set_background_color); - register_tag_loader(12,parse_do_action); - register_tag_loader(22,parse_define_shape123); - register_tag_loader(26,parse_place_object12); - register_tag_loader(28,parse_remove_object12); - register_tag_loader(32,parse_define_shape123); - register_tag_loader(39,parse_define_sprite); - register_tag_loader(43,parse_set_framelabel); - register_tag_loader(46,parse_define_shape_morph); - - ident = 1; - - Uint32 header = file->read_le32(); - Uint32 file_length = file->read_le32(); - - Uint32 version = (header >> 24) & 255; - if ((header & 0x0FFFFFF) != 0x00535746 && (header & 0x0FFFFFF) != 0x00535743) - { - log_msg("\nNo valid SWF file, header is incorrect!\n"); - return; - } - - bool compressed = (header & 255) == 'C'; - - tu_file* original_file = NULL; - - log_msg("\nSWF version %i, file length = %i bytes\n", version, file_length); - - if (compressed) - { - log_msg("file is compressed.\n"); - original_file = file; - file = zlib_adapter::make_inflater(original_file); - file_length -= 8; - } - - stream str(file); - - rect::parse(&str); - float frame_rate = str.read_u16() / 256.0f; - int frame_count = str.read_u16(); - - log_msg("viewport:\n"); - rect::write(); - log_msg("frame rate = %f, number of frames = %d\n", frame_rate, frame_count); - - log_msg("\n"); - log_msg("starting frame 0\n\n"); - ident++; - - while ((Uint32) str.get_position() < file_length) - { - int tag_type = str.open_tag(); - - loader_function lf = NULL; - - if (tag_loaders.get(tag_type, &lf)) - { - (*lf)(&str, tag_type); - - } else - { - log_msg("warning: no tag loader for tag_type %d\n", tag_type); - } - - str.close_tag(); - - if (tag_type == 0) - { - if ((unsigned int)str.get_position() != file_length) - { - log_msg("warning: end of file tag found, while not at the end of the file, aborting\n"); - break; - } - } - } - - if (out) - { - delete out; - } - if (original_file) - { - delete file; - } - exit(0); - } -} - -int main(int argc, char *argv[]) -{ - const char* infile = argv[1]; - gameswf::register_log_callback(parser::log_callback); - - if (infile == NULL) - { - log_msg("pass a filename as a parameter"); - exit(1); - } - - tu_file* in = new tu_file(infile, "rb"); - if (in->get_error()) - { - log_msg("can't open '%s' for input\n", infile); - delete in; - exit(1); - } - parser::parse_swf(in); - return(0); -} - -// Local Variables: -// mode: C++ -// c-basic-offset: 8 -// tab-width: 8 -// indent-tabs-mode: t -// End: diff --git a/Code/BF2/External/gameswf/gameswf_parser.exe b/Code/BF2/External/gameswf/gameswf_parser.exe deleted file mode 100644 index 9a463338e..000000000 Binary files a/Code/BF2/External/gameswf/gameswf_parser.exe and /dev/null differ diff --git a/Code/BF2/External/gameswf/gameswf_processor.cpp b/Code/BF2/External/gameswf/gameswf_processor.cpp deleted file mode 100644 index 0922f096f..000000000 --- a/Code/BF2/External/gameswf/gameswf_processor.cpp +++ /dev/null @@ -1,318 +0,0 @@ -// gameswf_processor.cpp -- Thatcher Ulrich 2003 - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - -// A SWF preprocessor for the gameswf library. Loads a set of SWF -// files and generates precomputed data such as font bitmaps and shape -// tesselation meshes. The precomputed data can be appended to the -// original SWF files, so that gameswf can more rapidly load those SWF -// files later. - - -#include "base/tu_file.h" -#include "base/container.h" -#include "gameswf.h" - - -static bool s_verbose = false; - - -static void message_log(const char* message) -// Process a log message. -{ - if (s_verbose) - { - fputs(message, stdout); - //flush(stdout); // needed on osx for some reason - } -} - - -static void log_callback(bool error, const char* message) -// Error callback for handling gameswf messages. -{ - if (error) - { - // Log, and also print to stderr. - message_log(message); - fputs(message, stderr); - } - else - { - message_log(message); - } -} - - -static tu_file* file_opener(const char* url) -// Callback function. This opens files for the gameswf library. -{ - return new tu_file(url, "rb"); -} - - -static void print_usage() -{ - printf( - "gameswf_processor -- a SWF preprocessor for gameswf.\n" - "\n" - "This program has been donated to the Public Domain.\n" - "See http://tulrich.com/geekstuff/gameswf.html for more info.\n" - "\n" - "usage: gameswf_processor [options] [swf files to process...]\n" - "\n" - "Preprocesses the given SWF movie files. Optionally write preprocessed shape\n" - "and font data to cache files, so the associated SWF files can be loaded\n" - "faster by gameswf.\n" - "\n" - "options:\n" - "\n" - " -h Print this info.\n" - " -w Write a .gsc file with preprocessed info, for each input file.\n" - " -v Be verbose; i.e. print log messages to stdout\n" - " -vp Be verbose about movie parsing\n" - " -va Be verbose about ActionScript\n" - ); -} - - -struct movie_data -{ - gameswf::movie_definition* m_movie; - tu_string m_filename; -}; - - -static gameswf::movie_definition* play_movie(const char* filename); -static int write_cache_file(const movie_data& md); - - -static bool s_do_output = false; -static bool s_stop_on_errors = true; - - -int main(int argc, char *argv[]) -{ - assert(tu_types_validate()); - - array infiles; - - for (int arg = 1; arg < argc; arg++) - { - if (argv[arg][0] == '-') - { - // Looks like an option. - - if (argv[arg][1] == 'h') - { - // Help. - print_usage(); - exit(1); - } - else if (argv[arg][1] == 'w') - { - // Write cache files. - s_do_output = true; - } - else if (argv[arg][1] == 'v') - { - // Be verbose; i.e. print log messages to stdout. - s_verbose = true; - - if (argv[arg][2] == 'a') - { - // Enable spew re: action. - gameswf::set_verbose_action(true); - } - else if (argv[arg][2] == 'p') - { - // Enable parse spew. - gameswf::set_verbose_parse(true); - } - // ... - } - } - else - { - infiles.push_back(argv[arg]); - } - } - - if (infiles.size() == 0) - { - printf("no input files\n"); - print_usage(); - exit(1); - } - - gameswf::register_file_opener_callback(file_opener); - gameswf::register_log_callback(log_callback); - gameswf::set_use_cache_files(false); // don't load old cache files! - - array data; - - // Play through all the movies. - for (int i = 0, n = infiles.size(); i < n; i++) - { - gameswf::movie_definition* m = play_movie(infiles[i]); - if (m == NULL) - { - if (s_stop_on_errors) - { - // Fail. - fprintf(stderr, "error playing through movie '%s', quitting\n", infiles[i]); - exit(1); - } - } - - movie_data md; - md.m_movie = m; - md.m_filename = infiles[i]; - data.push_back(md); - } - - // Now append processed data. - if (s_do_output) - { - for (int i = 0, n = data.size(); i < n; i++) - { - int error = write_cache_file(data[i]); - if (error) - { - if (s_stop_on_errors) - { - // Fail. - fprintf(stderr, "error processing movie '%s', quitting\n", data[i].m_filename.c_str()); - exit(1); - } - } - } - } - - return 0; -} - - -gameswf::movie_definition* play_movie(const char* filename) -// Load the named movie, make an instance, and play it, virtually. -// I.e. run through and render all the frames, even though we are not -// actually doing any output (our output handlers are disabled). -// -// What this does is warm up all the cached data in the movie, so that -// if we save that data for later, we won't have to tesselate shapes -// or build font textures again. -// -// Return the movie definition. -{ - gameswf::movie_definition* md = gameswf::create_library_movie(filename); - if (md == NULL) - { - fprintf(stderr, "error: can't play movie '%s'\n", filename); - exit(1); - } - gameswf::movie_interface* m = md->create_instance(); - if (m == NULL) - { - fprintf(stderr, "error: can't create instance of movie '%s'\n", filename); - exit(1); - } - - int kick_count = 0; - - // Run through the movie. - for (;;) - { - // @@ do we also have to run through all sprite frames - // as well? - // - // @@ also, ActionScript can rescale things - // dynamically -- we can't really do much about that I - // guess? - // - // @@ Maybe we should allow the user to specify some - // safety margin on scaled shapes. - - int last_frame = m->get_current_frame(); - m->advance(0.010f); - m->display(); - - if (m->get_current_frame() == md->get_frame_count() - 1) - { - // Done. - break; - } - - if (m->get_play_state() == gameswf::movie_interface::STOP) - { - // Kick the movie. - printf("kicking movie, kick ct = %d\n", kick_count); - m->goto_frame(last_frame + 1); - m->set_play_state(gameswf::movie_interface::PLAY); - kick_count++; - - if (kick_count > 10) - { - printf("movie is stalled; giving up on playing it through.\n"); - break; - } - } - else if (m->get_current_frame() < last_frame) - { - // Hm, apparently we looped back. Skip ahead... - printf("loop back; jumping to frame %d\n", last_frame); - m->goto_frame(last_frame + 1); - } - else - { - kick_count = 0; - } - } - - return md; -} - - -int write_cache_file(const movie_data& md) -// Write a cache file for the given movie. -{ - // Open cache file. - tu_string cache_filename(md.m_filename); - cache_filename += ".gsc"; - tu_file out(cache_filename.c_str(), "wb"); // "gsc" == "gameswf cache" - if (out.get_error() == TU_FILE_NO_ERROR) - { - // Write out the data. - gameswf::cache_options opt; - md.m_movie->output_cached_data(&out, opt); - if (out.get_error() == TU_FILE_NO_ERROR) - { - printf( - "wrote '%s'\n", - cache_filename.c_str()); - } - else - { - fprintf(stderr, "error: write failure to '%s'\n", cache_filename.c_str()); - } - } - else - { - fprintf(stderr, "error: can't open '%s' for cache file output\n", cache_filename.c_str()); - return 1; - } - - // // xxx temp debug code: dump cached data to stdout - // tu_file tu_stdout(stdout, false); - // tu_stdout.copy_from(&cached_data); - - return 0; -} - - -// Local Variables: -// mode: C++ -// c-basic-offset: 8 -// tab-width: 8 -// indent-tabs-mode: t -// End: diff --git a/Code/BF2/External/gameswf/gameswf_processor.exe b/Code/BF2/External/gameswf/gameswf_processor.exe deleted file mode 100644 index e3787c0c2..000000000 Binary files a/Code/BF2/External/gameswf/gameswf_processor.exe and /dev/null differ diff --git a/Code/BF2/External/gameswf/gameswf_profile.h b/Code/BF2/External/gameswf/gameswf_profile.h new file mode 100644 index 000000000..399a7dae9 --- /dev/null +++ b/Code/BF2/External/gameswf/gameswf_profile.h @@ -0,0 +1,40 @@ +// Shared counters for the movie, ActionScript and renderer profiling sites. +#ifndef GAMESWF_PROFILE_H +#define GAMESWF_PROFILE_H + +#include "base/container.h" +#include "base/tu_timer.h" + +namespace gameswf +{ + // [INFERRED] Source-level names; SwiffPlayer.dll 0x1006F140 controls this flag. + extern bool s_profiling; + + // The registry borrows static records. Destruction releases only the name. + struct profile_record + { + Uint32 m_count; + uint64 m_ticks; + uint64 m_start; + tu_string m_name; + + // SwiffPlayer.dll 0x10075230; each caller initializes its own start time. + explicit profile_record(const char* name); + // SwiffPlayer.dll 0x10084CF0: only the name has destruction work. + ~profile_record() = default; + + // SwiffPlayer.dll 0x10084D10, also inlined at the other profiling sites. + void begin() { m_start = tu_timer::get_profile_ticks(); } + void end() + { + m_ticks += tu_timer::get_profile_ticks() - m_start; + ++m_count; + } + }; + + // [CHOSEN, not recovered] S3 bridge to the native registry representation. + // Used by the report reader without transferring ownership of the records. + const array& get_profile_records(); +} + +#endif diff --git a/Code/BF2/External/gameswf/gameswf_render.cpp b/Code/BF2/External/gameswf/gameswf_render.cpp index 286893305..789af7e35 100644 --- a/Code/BF2/External/gameswf/gameswf_render.cpp +++ b/Code/BF2/External/gameswf/gameswf_render.cpp @@ -6,19 +6,35 @@ // Interface to back-end renderer. +#include +#include +#include #include "gameswf_render.h" #include "gameswf_log.h" +#include "gameswf_profile.h" namespace gameswf { static render_handler* s_render_handler; + // SwiffPlayer.dll 0x100963A0: notify the currently installed handler. + bitmap_info::~bitmap_info() + { + // [CHOSEN, not recovered] Cached generated images release through their + // own registry leases, never the currently installed player's handler. + if (!m_render_resource) + render::delete_bitmap_info(this); + } + + + // SwiffPlayer.dll 0x1009A3F0. void set_render_handler(render_handler* r) { s_render_handler = r; } + // SwiffPlayer.dll 0x1009A400. render_handler* get_render_handler() { return s_render_handler; @@ -27,44 +43,50 @@ namespace gameswf namespace render { + // SwiffPlayer.dll 0x1009A410: the no-handler bitmap has zero texture and dimensions. + // [CHOSEN, not recovered] S3 bridge: native bitmap_info/ref_counted layout. struct bogus_bi : public bitmap_info { + // The base destructor sends the notification once (0x1009AA50). }; + // SwiffPlayer.dll 0x1009A9D0. bitmap_info* create_bitmap_info_empty() { if (s_render_handler) return s_render_handler->create_bitmap_info_empty(); - else return new bogus_bi; + else return new (std::nothrow) bogus_bi; } + // SwiffPlayer.dll 0x1009A470. bitmap_info* create_bitmap_info_alpha(int w, int h, unsigned char* data) { if (s_render_handler) return s_render_handler->create_bitmap_info_alpha(w, h, data); - else return new bogus_bi; + else return new (std::nothrow) bogus_bi; } + // SwiffPlayer.dll 0x1009A500. bitmap_info* create_bitmap_info_rgb(image::rgb* im) { if (s_render_handler) return s_render_handler->create_bitmap_info_rgb(im); - else return new bogus_bi; + else return new (std::nothrow) bogus_bi; } + // SwiffPlayer.dll 0x1009A590. bitmap_info* create_bitmap_info_rgba(image::rgba* im) { if (s_render_handler) return s_render_handler->create_bitmap_info_rgba(im); - else return new bogus_bi; + else return new (std::nothrow) bogus_bi; } - // [DICE-MOD SwiffPlayer: the by-name loader (sub_1009A620 - handler slot, else a bogus - // 32-byte bitmap_info). Unlike the others a NULL from the handler stays NULL: the loader - // callers treat it as "no image".] + // SwiffPlayer.dll 0x1009A620: handler slot 5; preserve its null result. bitmap_info* create_bitmap_info_file(const char* path) { if (s_render_handler) return s_render_handler->create_bitmap_info_file(path); - else return new bogus_bi; + else return new (std::nothrow) bogus_bi; } + // SwiffPlayer.dll 0x1009A6B0. void delete_bitmap_info(bitmap_info* bi) { if (s_render_handler) s_render_handler->delete_bitmap_info(bi); @@ -73,6 +95,7 @@ namespace gameswf // Bracket the displaying of a frame from a movie. // Fill the background color, and set up default // transforms, etc. + // SwiffPlayer.dll 0x1009AA80. void begin_display( rgba background_color, int viewport_x0, int viewport_y0, @@ -81,6 +104,16 @@ namespace gameswf { if (s_render_handler) { + if (s_profiling) + { + static profile_record counter("beginDisplay"); + counter.begin(); + s_render_handler->begin_display( + background_color, viewport_x0, viewport_y0, + viewport_width, viewport_height, x0, x1, y0, y1); + counter.end(); + return; + } s_render_handler->begin_display( background_color, viewport_x0, viewport_y0, viewport_width, viewport_height, @@ -93,31 +126,64 @@ namespace gameswf } + // SwiffPlayer.dll 0x1009AB60. void end_display() { - if (s_render_handler) s_render_handler->end_display(); + if (s_render_handler) + { + if (s_profiling) + { + static profile_record counter("endDisplay"); + counter.begin(); + s_render_handler->end_display(); + counter.end(); + } + else s_render_handler->end_display(); + } } // Geometric and color transforms for mesh and line_strip rendering. + // SwiffPlayer.dll 0x1009A6D0. void set_matrix(const matrix& m) { if (s_render_handler) s_render_handler->set_matrix(m); } + // SwiffPlayer.dll 0x1009A6F0. void set_cxform(const cxform& cx) { if (s_render_handler) s_render_handler->set_cxform(cx); } + // SwiffPlayer.dll 0x1009A710 guards the handler and forwards its integer. + void set_depth(int depth) + { + if (s_render_handler) + { + s_render_handler->set_depth(depth); + } + } + // Draw triangles using the current fill-style 0. // Clears the style list after rendering. // // coords is a list of (x,y) coordinate pairs, in // triangle-strip order. The type of the array should // be float[vertex_count*2] + // SwiffPlayer.dll 0x1009ABF0. void draw_mesh_strip(const Sint16 coords[], int vertex_count) { - if (s_render_handler) s_render_handler->draw_mesh_strip(coords, vertex_count); + if (s_render_handler) + { + if (s_profiling) + { + static profile_record counter("drawMeshStrip"); + counter.begin(); + s_render_handler->draw_mesh_strip(coords, vertex_count); + counter.end(); + } + else s_render_handler->draw_mesh_strip(coords, vertex_count); + } } // Draw a line-strip using the current line style. @@ -125,9 +191,20 @@ namespace gameswf // // Coords is a list of (x,y) coordinate pairs, in // sequence. + // SwiffPlayer.dll 0x1009AC90. void draw_line_strip(const Sint16 coords[], int vertex_count) { - if (s_render_handler) s_render_handler->draw_line_strip(coords, vertex_count); + if (s_render_handler) + { + if (s_profiling) + { + static profile_record counter("drawLineStrip"); + counter.begin(); + s_render_handler->draw_line_strip(coords, vertex_count); + counter.end(); + } + else s_render_handler->draw_line_strip(coords, vertex_count); + } } // // Set line and fill styles for mesh & line_strip @@ -138,102 +215,138 @@ namespace gameswf // WRAP_CLAMP // }; + // SwiffPlayer.dll 0x1009A730. void fill_style_disable(int fill_side) { if (s_render_handler) s_render_handler->fill_style_disable(fill_side); } + // SwiffPlayer.dll 0x1009A750. void fill_style_color(int fill_side, rgba color) { if (s_render_handler) s_render_handler->fill_style_color(fill_side, color); } + // SwiffPlayer.dll 0x1009A770. void fill_style_bitmap(int fill_side, const bitmap_info* bi, const matrix& m, render_handler::bitmap_wrap_mode wm) { if (s_render_handler) s_render_handler->fill_style_bitmap(fill_side, bi, m, wm); } + // SwiffPlayer.dll 0x1009A7A0. void line_style_disable() { if (s_render_handler) s_render_handler->line_style_disable(); } + // SwiffPlayer.dll 0x1009A7B0. void line_style_color(rgba color) { if (s_render_handler) s_render_handler->line_style_color(color); } + // SwiffPlayer.dll 0x1009A7D0. void line_style_width(float width) { if (s_render_handler) s_render_handler->line_style_width(width); } + // SwiffPlayer.dll 0x1009A7F0. void begin_submit_mask() { if (s_render_handler) s_render_handler->begin_submit_mask(); } + // SwiffPlayer.dll 0x1009A810. void end_submit_mask() { if (s_render_handler) s_render_handler->end_submit_mask(); } + // SwiffPlayer.dll 0x1009A830. void disable_mask() { if (s_render_handler) s_render_handler->disable_mask(); } - // [DICE-MOD SwiffPlayer #36] the text-line slots; each shipped forwarder guards on the handler - // exactly like these (the profiler wrappers around setText/drawText are not reproduced). + // the text-line slots; each shipped forwarder guards on the handler + // exactly like these. + // SwiffPlayer.dll 0x1009A850. void* text_create(const char* font_name, int height_px) { return s_render_handler ? s_render_handler->text_create(font_name, height_px) : NULL; } + // SwiffPlayer.dll 0x1009A890. void text_release(void* line) { if (s_render_handler) s_render_handler->text_release(line); } + // SwiffPlayer.dll 0x1009ADF0; native wchar_t text is the existing host bridge. void text_set(void* line, const wchar_t* text) { - if (s_render_handler) s_render_handler->text_set(line, text); + if (s_render_handler) + { + if (s_profiling) + { + static profile_record counter("setText"); + counter.begin(); + s_render_handler->text_set(line, text); + counter.end(); + } + else s_render_handler->text_set(line, text); + } } + // SwiffPlayer.dll 0x1009A870. void text_detach(void* line) { if (s_render_handler) s_render_handler->text_detach(line); } + // SwiffPlayer.dll 0x1009AE90. void text_draw(void* line, const matrix* m, unsigned color, int flags) { - if (s_render_handler) s_render_handler->text_draw(line, m, color, flags); + if (s_render_handler) + { + if (s_profiling) + { + static profile_record counter("drawText"); + counter.begin(); + s_render_handler->text_draw(line, m, color, flags); + counter.end(); + } + else s_render_handler->text_draw(line, m, color, flags); + } } + // SwiffPlayer.dll 0x1009A8B0. bool text_extent(void* line, int count, float* w, float* h) { return s_render_handler ? s_render_handler->text_extent(line, count, w, h) : false; } - bool text_hit(void* line, int* out_pos, int x, int y) + // 0x1009A8E0: ecx = line, edx = out_pos, the two float dwords passed on to handler +0x6C. + bool text_hit(void* line, int* out_pos, float x, float y) { return s_render_handler ? s_render_handler->text_hit(line, out_pos, x, y) : false; } + // SwiffPlayer.dll 0x1009A910: without a handler the outputs are untouched. bool text_selection(void* line, int* a, int* b) { - // [DICE-MOD SwiffPlayer #46] the handler's Boolean (sub_1009A910 returns the - // render_handler +112 answer) says whether a selection exists at all. - if (s_render_handler) return s_render_handler->text_selection(line, a, b); - if (a) *a = 0; - if (b) *b = 0; - return false; + return s_render_handler ? s_render_handler->text_selection(line, a, b) : false; } - bool text_set_selection(void* line, int a, int b, int c, int d) + // 0x1009A940: the four float dwords passed on to handler +0x74. + bool text_set_selection(void* line, float x1, float y1, float x2, float y2) { - return s_render_handler ? s_render_handler->text_set_selection(line, a, b, c, d) : false; + return s_render_handler ? s_render_handler->text_set_selection(line, x1, y1, x2, y2) : false; } + // SwiffPlayer.dll 0x1009A970. void text_blur(void* line) { if (s_render_handler) s_render_handler->text_blur(line); } + // SwiffPlayer.dll 0x1009A990. void text_set_size(void* line, float size, int flag) { if (s_render_handler) s_render_handler->text_set_size(line, size, flag); } + // SwiffPlayer.dll 0x1009A9B0. void text_caret(void* line, int pos) { if (s_render_handler) s_render_handler->text_caret(line, pos); @@ -242,10 +355,19 @@ namespace gameswf // Special function to draw a rectangular bitmap; // intended for textured glyph rendering. Ignores // current transforms. + // SwiffPlayer.dll 0x1009AD30. void draw_bitmap(const matrix& m, const bitmap_info* bi, const rect& coords, const rect& uv_coords, rgba color) { if (s_render_handler) { + if (s_profiling) + { + static profile_record counter("drawBitmap"); + counter.begin(); + s_render_handler->draw_bitmap(m, bi, coords, uv_coords, color); + counter.end(); + return; + } s_render_handler->draw_bitmap( m, bi, coords, uv_coords, color); } diff --git a/Code/BF2/External/gameswf/gameswf_render.h b/Code/BF2/External/gameswf/gameswf_render.h index 77b08a460..15b06b59e 100644 --- a/Code/BF2/External/gameswf/gameswf_render.h +++ b/Code/BF2/External/gameswf/gameswf_render.h @@ -25,7 +25,7 @@ namespace gameswf bitmap_info* create_bitmap_info_alpha(int w, int h, unsigned char* data); bitmap_info* create_bitmap_info_rgb(image::rgb* im); bitmap_info* create_bitmap_info_rgba(image::rgba* im); - bitmap_info* create_bitmap_info_file(const char* path); // [DICE-MOD SwiffPlayer: see gameswf.h] + bitmap_info* create_bitmap_info_file(const char* path); // see gameswf.h void delete_bitmap_info(bitmap_info* bi); // Bracket the displaying of a frame from a movie. @@ -41,6 +41,9 @@ namespace gameswf // Geometric and color transforms for mesh and line_strip rendering. void set_matrix(const matrix& m); void set_cxform(const cxform& cx); + // Submit the display-list depth before this shape's meshes and lines. + // An absent handler has no effect; otherwise use its typed depth callback. + void set_depth(int depth); // Draw triangles using the current fill-style 0. // Clears the style list after rendering. @@ -69,7 +72,7 @@ namespace gameswf void end_submit_mask(); void disable_mask(); - // [DICE-MOD SwiffPlayer #36] the text-line slots (shipped render:: forwarders 0x1009A850.. + // the text-line slots (shipped render:: forwarders 0x1009A850.. // 0x1009AE90), see render_handler in gameswf.h. void* text_create(const char* font_name, int height_px); void text_release(void* line); @@ -77,9 +80,10 @@ namespace gameswf void text_detach(void* line); void text_draw(void* line, const matrix* m, unsigned color, int flags); bool text_extent(void* line, int count, float* w, float* h); - bool text_hit(void* line, int* out_pos, int x, int y); - bool text_selection(void* line, int* a, int* b); // [DICE-MOD SwiffPlayer #46] true = a selection exists - bool text_set_selection(void* line, int a, int b, int c, int d); + // float coordinates: SwiffPlayer.dll 0x100887A5..0x100887D7 / 0x10088823..0x1008883B + bool text_hit(void* line, int* out_pos, float x, float y); + bool text_selection(void* line, int* a, int* b); // true = a selection exists + bool text_set_selection(void* line, float x1, float y1, float x2, float y2); void text_blur(void* line); void text_set_size(void* line, float size, int flag); void text_caret(void* line, int pos); diff --git a/Code/BF2/External/gameswf/gameswf_render_handler_d3d.cpp b/Code/BF2/External/gameswf/gameswf_render_handler_d3d.cpp deleted file mode 100644 index 81adb7dc5..000000000 --- a/Code/BF2/External/gameswf/gameswf_render_handler_d3d.cpp +++ /dev/null @@ -1,1342 +0,0 @@ -// gameswf_render_handler_d3d.cpp Paul Kelly & Bob Ives, 2006 - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - -// A gameswf::render_handler that uses DX8 or DX9. -// Based on the xbox code by Thatcher Ulrich 2003 - - -#include -#include -#include "gameswf.h" -#include "gameswf/gameswf_log.h" -#include "gameswf_types.h" -#include "base/image.h" -#include "base/container.h" - -//#define _DX8 - -#if defined (_DX8) -# include -#else -# include -#endif - -#if DIRECT3D_VERSION < 0x0900 -# include -# include - typedef IDirect3D8 IDirect3D; - typedef IDirect3DDevice8 IDirect3DDevice; - typedef IDirect3DTexture8 IDirect3DTexture; - typedef IDirect3DBaseTexture8 IDirect3DBaseTexture; - typedef IDirect3DSurface8 IDirect3DSurface; - typedef IDirect3DVertexBuffer8 IDirect3DVertexBuffer; - typedef D3DVIEWPORT8 D3DVIEWPORT; - typedef BYTE tLock; -#else -# include -# include - typedef IDirect3D9 IDirect3D; - typedef IDirect3DDevice9 IDirect3DDevice; - typedef IDirect3DTexture9 IDirect3DTexture; - typedef IDirect3DBaseTexture9 IDirect3DBaseTexture; - typedef IDirect3DSurface9 IDirect3DSurface; - typedef IDirect3DVertexBuffer9 IDirect3DVertexBuffer; - typedef D3DVIEWPORT9 D3DVIEWPORT; - typedef void tLock; -#endif - -#include - -#define INIT_SIZE_VERTEX_BUFFER 128 - -#define Z_DEPTH 1.0f - - -// A structure for our custom vertex type. We added texture coordinates -struct CUSTOMVERTEX -{ - float x,y,z; // transformed position for the vertex -}; - -// Our custom FVF, which describes our custom vertex structure -#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ) - -struct CUSTOMVERTEX2 -{ - float x,y,z; // position - float tu, tv; // texture coordinates -}; - -#define D3DFVF_CUSTOMVERTEX2 (D3DFVF_XYZ|D3DFVF_TEX1) - - -static inline float clamp( float x,float min,float max ) { - union { float f; int hex; }; - f = x - min; - hex &= ~hex>>31; - f += min - max; - hex &= hex>>31; - f += max; - return f; -} - - -// bitmap_info_d3d declaration -struct bitmap_info_d3d : public gameswf::bitmap_info -{ - bitmap_info_d3d(); - void convert_to_argb(image::rgba* im); - bitmap_info_d3d(image::rgb* im); - bitmap_info_d3d(image::rgba* im); - bitmap_info_d3d(int width, int height, Uint8* data); -}; - - -struct render_handler_d3d : public gameswf::render_handler -{ - // Some renderer state. - - gameswf::matrix m_current_matrix; - gameswf::cxform m_current_cxform; - - IDirect3DVertexBuffer* m_pVB; // Buffer to hold vertices - IDirect3DVertexBuffer* m_pVB2; // Buffer to hold vertices - DWORD m_nMaxVertices; // Max Vertices held in m_pVB - D3DVIEWPORT m_origVP; - - static IDirect3DDevice* m_pd3dDevice; // Our rendering device - static D3DFORMAT m_FormatRGB; - static D3DFORMAT m_FormatRGBA; - static D3DFORMAT m_FormatA; - static D3DXMATRIX m_ModelViewMatrix; - static D3DXMATRIX m_ProjMatrix; - static array m_d3d_textures; - - void set_antialiased(bool enable) - { - // not supported - } - - static void make_next_miplevel(int* width, int* height, Uint8* data) - // Utility. Mutates *width, *height and *data to create the - // next mip level. - { - assert(width); - assert(height); - assert(data); - - int new_w = *width >> 1; - int new_h = *height >> 1; - if (new_w < 1) new_w = 1; - if (new_h < 1) new_h = 1; - - if (new_w * 2 != *width || new_h * 2 != *height) - { - // Image can't be shrunk along (at least) one - // of its dimensions, so don't bother - // resampling. Technically we should, but - // it's pretty useless at this point. Just - // change the image dimensions and leave the - // existing pixels. - } - else - { - // Resample. Simple average 2x2 --> 1, in-place. - for (int j = 0; j < new_h; j++) { - Uint8* out = ((Uint8*) data) + j * new_w; - Uint8* in = ((Uint8*) data) + (j << 1) * *width; - for (int i = 0; i < new_w; i++) { - int a; - a = (*(in + 0) + *(in + 1) + *(in + 0 + *width) + *(in + 1 + *width)); - *(out) = (Uint8) (a >> 2); - out++; - in += 2; - } - } - } - - // Munge parameters to reflect the shrunken image. - *width = new_w; - *height = new_h; - } - - struct fill_style - { - enum mode - { - INVALID, - COLOR, - BITMAP_WRAP, - BITMAP_CLAMP, - LINEAR_GRADIENT, - RADIAL_GRADIENT, - }; - mode m_mode; - gameswf::rgba m_color; - const gameswf::bitmap_info* m_bitmap_info; - gameswf::matrix m_bitmap_matrix; - gameswf::cxform m_bitmap_color_transform; - bool m_has_nonzero_bitmap_additive_color; - - fill_style() - : - m_mode(INVALID), - m_has_nonzero_bitmap_additive_color(false) - { - } - - void apply(const gameswf::matrix& current_matrix) const - // Push our style into D3D. - { - assert(m_mode != INVALID); - - if (m_mode == COLOR) - { - apply_color(m_color); - m_pd3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG2); - m_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG2); - } - else if (m_mode == BITMAP_WRAP - || m_mode == BITMAP_CLAMP) - { - assert(m_bitmap_info != NULL); - - apply_color(m_color); - - if (m_bitmap_info == NULL) - { - assert(0); - m_pd3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG2); - m_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG2); - } - else - { - - // Set up the texture for rendering. - - // Do the modulate part of the color - // transform in the first pass. The - // additive part, if any, needs to - // happen in a second pass. - - m_pd3dDevice->SetTexture(0, m_d3d_textures[m_bitmap_info->m_texture_id]); - m_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE ); - m_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE ); - - if (m_mode == BITMAP_CLAMP) - { -#if DIRECT3D_VERSION >= 0x0900 - m_pd3dDevice->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP); - m_pd3dDevice->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP); -#else - m_pd3dDevice->SetTextureStageState(0, D3DTSS_ADDRESSU, D3DTADDRESS_CLAMP); - m_pd3dDevice->SetTextureStageState(0, D3DTSS_ADDRESSV, D3DTADDRESS_CLAMP); -#endif - } - else - { - assert(m_mode == BITMAP_WRAP); -#if DIRECT3D_VERSION >= 0x0900 - m_pd3dDevice->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP); - m_pd3dDevice->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP); -#else - m_pd3dDevice->SetTextureStageState(0, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP); - m_pd3dDevice->SetTextureStageState(0, D3DTSS_ADDRESSV, D3DTADDRESS_WRAP); -#endif - } - - // Set up the bitmap matrix for texgen. - float inv_width = 1.0f / m_bitmap_info->m_original_width; - float inv_height = 1.0f / m_bitmap_info->m_original_height; - - gameswf::matrix m = m_bitmap_matrix; - gameswf::matrix m_cm_inv; - m_cm_inv.set_inverse(current_matrix); - m.concatenate(m_cm_inv); - - D3DXMATRIXA16 mat; - D3DXMatrixIdentity(&mat); - - mat._11 = m.m_[0][0] * inv_width; mat._12 = m.m_[1][0] * inv_height; mat._13 = 0.00f; mat._14 = 0.00f; - mat._21 = m.m_[0][1] * inv_width; mat._22 = m.m_[1][1] * inv_height; mat._23 = 0.00f; mat._24 = 0.00f; - mat._31 = 0.00f; mat._32 = 0.00f; mat._33 = 0.00f; mat._34 = 0.00f; - mat._41 = m.m_[0][2] * inv_width; mat._42 = m.m_[1][2] * inv_height; mat._43 = 0.00f; mat._44 = 1.00f; - - m_pd3dDevice->SetTransform( D3DTS_TEXTURE0, &mat ); - m_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2 ); - m_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEPOSITION); - } - } - } - - - bool needs_second_pass() const - // Return true if we need to do a second pass to make - // a valid color. This is for cxforms with additive - // parts. - { - if (m_mode == BITMAP_WRAP - || m_mode == BITMAP_CLAMP) - { - return m_has_nonzero_bitmap_additive_color; - } - else - { - return false; - } - } - - void apply_second_pass() const - // Set D3D state for a necessary second pass. - { - assert(needs_second_pass()); - - // Additive color. - apply_color(gameswf::rgba( - Uint8(m_bitmap_color_transform.m_[0][1]), - Uint8(m_bitmap_color_transform.m_[1][1]), - Uint8(m_bitmap_color_transform.m_[2][1]), - Uint8(m_bitmap_color_transform.m_[3][1]))); - - m_pd3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG2); - m_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG2); - - m_pd3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE ); - m_pd3dDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE ); - } - - void cleanup_second_pass() const - { - m_pd3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); - m_pd3dDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); - } - - - void disable() { m_mode = INVALID; } - void set_color(gameswf::rgba color) - { - m_mode = COLOR; - m_color = color; - } - void set_bitmap(const gameswf::bitmap_info* bi, const gameswf::matrix& m, bitmap_wrap_mode wm, const gameswf::cxform& color_transform) - { - m_mode = (wm == WRAP_REPEAT) ? BITMAP_WRAP : BITMAP_CLAMP; - m_bitmap_info = bi; - m_bitmap_matrix = m; - - m_bitmap_color_transform.m_[0][0] = clamp(color_transform.m_[0][0], 0, 1); - m_bitmap_color_transform.m_[1][0] = clamp(color_transform.m_[1][0], 0, 1); - m_bitmap_color_transform.m_[2][0] = clamp(color_transform.m_[2][0], 0, 1); - m_bitmap_color_transform.m_[3][0] = clamp(color_transform.m_[3][0], 0, 1); - - m_bitmap_color_transform.m_[0][1] = clamp(color_transform.m_[0][1], -255.0f, 255.0f); - m_bitmap_color_transform.m_[1][1] = clamp(color_transform.m_[1][1], -255.0f, 255.0f); - m_bitmap_color_transform.m_[2][1] = clamp(color_transform.m_[2][1], -255.0f, 255.0f); - m_bitmap_color_transform.m_[3][1] = clamp(color_transform.m_[3][1], -255.0f, 255.0f); - - m_color = gameswf::rgba( - Uint8(m_bitmap_color_transform.m_[0][0]*255.0f), - Uint8(m_bitmap_color_transform.m_[1][0]*255.0f), - Uint8(m_bitmap_color_transform.m_[2][0]*255.0f), - Uint8(m_bitmap_color_transform.m_[3][0]*255.0f)); - - if (m_bitmap_color_transform.m_[0][1] > 1.0f - || m_bitmap_color_transform.m_[1][1] > 1.0f - || m_bitmap_color_transform.m_[2][1] > 1.0f - || m_bitmap_color_transform.m_[3][1] > 1.0f) - { - m_has_nonzero_bitmap_additive_color = true; - } - else - { - m_has_nonzero_bitmap_additive_color = false; - } - } - bool is_valid() const { return m_mode != INVALID; } - }; - - // Constructor. - render_handler_d3d(IDirect3DDevice* device) - : m_pVB(NULL) - , m_pVB2(NULL) - , m_nMaxVertices(INIT_SIZE_VERTEX_BUFFER) - { - HRESULT hr; - - m_pd3dDevice = device; - m_pd3dDevice->AddRef(); - - hr = m_pd3dDevice->CreateVertexBuffer( m_nMaxVertices*sizeof(CUSTOMVERTEX) - , D3DUSAGE_WRITEONLY | D3DUSAGE_DYNAMIC, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &m_pVB -#if DIRECT3D_VERSION >= 0x0900 - , NULL -#endif - ); - assert(hr==S_OK); - - hr = m_pd3dDevice->CreateVertexBuffer( 4*sizeof(CUSTOMVERTEX2) - , D3DUSAGE_WRITEONLY | D3DUSAGE_DYNAMIC, D3DFVF_CUSTOMVERTEX2, D3DPOOL_DEFAULT, &m_pVB2 -#if DIRECT3D_VERSION >= 0x0900 - , NULL -#endif - ); - assert(hr==S_OK); - - // Determine texture formats - IDirect3D* l_pD3D; - hr = m_pd3dDevice->GetDirect3D( &l_pD3D ); - assert(hr==S_OK); - -#if DIRECT3D_VERSION < 0x0900 - D3DCAPS8 l_DeviceCaps; -#else - D3DCAPS9 l_DeviceCaps; -#endif - ZeroMemory( &l_DeviceCaps, sizeof(l_DeviceCaps) ); - hr = m_pd3dDevice->GetDeviceCaps( &l_DeviceCaps ); - assert(hr==S_OK); - - D3DDISPLAYMODE l_DisplayMode; - hr = m_pd3dDevice->GetDisplayMode( -#if DIRECT3D_VERSION >= 0x0900 - 0, -#endif - &l_DisplayMode ); - - if (SUCCEEDED(l_pD3D->CheckDeviceFormat(l_DeviceCaps.AdapterOrdinal, l_DeviceCaps.DeviceType, l_DisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT1))) - m_FormatRGB = D3DFMT_DXT1; - else if (SUCCEEDED(l_pD3D->CheckDeviceFormat(l_DeviceCaps.AdapterOrdinal, l_DeviceCaps.DeviceType, l_DisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_R8G8B8))) - m_FormatRGB = D3DFMT_R8G8B8; - else - m_FormatRGB = D3DFMT_A8R8G8B8; - - if (SUCCEEDED(l_pD3D->CheckDeviceFormat(l_DeviceCaps.AdapterOrdinal, l_DeviceCaps.DeviceType, l_DisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT5))) - m_FormatRGBA = D3DFMT_DXT5; - else - m_FormatRGBA = D3DFMT_A8R8G8B8; - - if (SUCCEEDED(l_pD3D->CheckDeviceFormat(l_DeviceCaps.AdapterOrdinal, l_DeviceCaps.DeviceType, l_DisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_A8))) - m_FormatA = D3DFMT_A8; - else if (SUCCEEDED(l_pD3D->CheckDeviceFormat(l_DeviceCaps.AdapterOrdinal, l_DeviceCaps.DeviceType, l_DisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_A8L8))) - m_FormatA = D3DFMT_A8L8; - else if (SUCCEEDED(l_pD3D->CheckDeviceFormat(l_DeviceCaps.AdapterOrdinal, l_DeviceCaps.DeviceType, l_DisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_A8P8))) - m_FormatA = D3DFMT_A8P8; - else - m_FormatA = D3DFMT_A8R8G8B8; - - } - - ~render_handler_d3d() - // Destructor. - { - for (int i = 0; i < m_d3d_textures.size(); i++) - { - if( m_d3d_textures[i] ) - { - m_d3d_textures[i]->Release(); - m_d3d_textures[i] = 0; - } - } - - - if (m_pVB) - { - m_pVB->Release(); - m_pVB = 0; - } - - if (m_pVB2) - { - m_pVB2->Release(); - m_pVB2 = 0; - } - - if (m_pd3dDevice) - m_pd3dDevice->Release(); - - } - - // Style state. - enum style_index - { - LEFT_STYLE = 0, - RIGHT_STYLE, - LINE_STYLE, - - STYLE_COUNT - }; - fill_style m_current_styles[STYLE_COUNT]; - - gameswf::bitmap_info* create_bitmap_info_alpha(int w, int h, unsigned char* data) - { - return new bitmap_info_d3d(w, h, data); - } - - - gameswf::bitmap_info* create_bitmap_info_rgb(image::rgb* im) - // Given an image, returns a pointer to a bitmap_info struct - // that can later be passed to fill_styleX_bitmap(), to set a - // bitmap fill style. - { - return new bitmap_info_d3d(im); - } - - - gameswf::bitmap_info* create_bitmap_info_rgba(image::rgba* im) - // Given an image, returns a pointer to a bitmap_info struct - // that can later be passed to fill_style_bitmap(), to set a - // bitmap fill style. - // - // This version takes an image with an alpha channel. - { - return new bitmap_info_d3d(im); - } - - - gameswf::bitmap_info* create_bitmap_info_empty() - // Creates and returns an empty bitmap_info structure. Image data - // can be bound to this info later, via set_alpha_image(). - { - assert(0); //pk this function not implemented. - //pk return new bitmap_info_d3d(gameswf::bitmap_info::empty); - return NULL; - } - - - void set_alpha_image(gameswf::bitmap_info* bi, int w, int h, Uint8* data) - // Set the specified bitmap_info so that it contains an alpha - // texture with the given data (1 byte per texel). - // - // Munges *data (in order to make mipmaps)!! - { - assert(bi); - assert(0); // not tested - - //pk bi->set_alpha_image(w, h, data); - } - - - void delete_bitmap_info(gameswf::bitmap_info* bi) - // Delete the given bitmap info struct. - { - delete bi; - } - - void prepare_vertex_buffer(const Sint16* coords, int vertex_count) - { - HRESULT hr; - - if( vertex_count>(int)m_nMaxVertices ) - { - // resize mesh - m_pVB->Release(); - m_nMaxVertices = vertex_count; - hr = m_pd3dDevice->CreateVertexBuffer( m_nMaxVertices*sizeof(CUSTOMVERTEX), D3DUSAGE_WRITEONLY|D3DUSAGE_DYNAMIC - , D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &m_pVB -#if DIRECT3D_VERSION >= 0x0900 - , NULL -#endif - ); - assert(hr==S_OK); - } - - CUSTOMVERTEX* verts; - hr = m_pVB->Lock( 0, 0, (tLock**)&verts, D3DLOCK_DISCARD ); - assert(hr==S_OK); - int coord_count = vertex_count * 2; - for(int i=0; ix = coords[i]; - verts->y = coords[i+1]; - verts->z = Z_DEPTH; - verts++; - } - hr = m_pVB->Unlock(); - assert(hr==S_OK); - - hr = m_pd3dDevice->SetStreamSource( 0, m_pVB, -#if DIRECT3D_VERSION >= 0x0900 - 0, -#endif - sizeof(CUSTOMVERTEX) ); - assert(hr==S_OK); - -#if DIRECT3D_VERSION < 0x0900 - hr = m_pd3dDevice->SetVertexShader(D3DFVF_CUSTOMVERTEX); -#else - hr = m_pd3dDevice->SetFVF(D3DFVF_CUSTOMVERTEX); -#endif - assert(hr==S_OK); - } - - void begin_display( - gameswf::rgba background_color, - int viewport_x0, int viewport_y0, - int viewport_width, int viewport_height, - float x0, float x1, float y0, float y1) - // Set up to render a full frame from a movie and fills the - // background. Sets up necessary transforms, to scale the - // movie to fit within the given dimensions. Call - // end_display() when you're done. - // - // The rectangle (viewport_x0, viewport_y0, viewport_x0 + - // viewport_width, viewport_y0 + viewport_height) defines the - // window coordinates taken up by the movie. - // - // The rectangle (x0, y0, x1, y1) defines the pixel - // coordinates of the movie that correspond to the viewport - // bounds. - { - HRESULT hr; - - D3DXMatrixIdentity(&m_ModelViewMatrix); - D3DXMatrixIdentity(&m_ProjMatrix); - - // invert coordinate system from lower left to upper left - - float gsWidthDiv = 1.0f / viewport_width; - float gsHeightDiv = 1.0f / viewport_height; - - m_ModelViewMatrix._11 = 2.0f / (x1 - x0); - m_ModelViewMatrix._22 = -2.0f / (y1 - y0); - m_ModelViewMatrix._41 = -((x1 + x0) / (x1 - x0)); - m_ModelViewMatrix._42 = ((y1 + y0) / (y1 - y0)); - - m_ProjMatrix._11 = viewport_width * gsWidthDiv; - m_ProjMatrix._22 = viewport_height * gsHeightDiv; - m_ProjMatrix._41 = -1.0f + viewport_x0 * 2.0f * gsWidthDiv + viewport_width * gsWidthDiv; - m_ProjMatrix._42 = 1.0f - viewport_y0 * 2.0f * gsHeightDiv - viewport_height * gsHeightDiv; - - // Matrix setup - D3DXMATRIX ident; - D3DXMatrixIdentity(&ident); - m_pd3dDevice->SetTransform(D3DTS_PROJECTION, &m_ModelViewMatrix); - - m_pd3dDevice->SetTransform(D3DTS_VIEW, &m_ProjMatrix); - m_pd3dDevice->SetTransform(D3DTS_WORLD, &ident); - - // turn on alpha bending. - m_pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE); - - if( NULL == m_pd3dDevice ) - { - assert(0); - return; - } - - - m_pd3dDevice->SetRenderState( D3DRS_LIGHTING, FALSE); - - // Viewport. - hr = m_pd3dDevice->GetViewport(&m_origVP); - assert(SUCCEEDED(hr)); // pure device? - - D3DVIEWPORT vp; - vp.X = viewport_x0; - vp.Y = viewport_y0; - vp.Width = viewport_width; - vp.Height = viewport_height; - vp.MinZ = 0.0f; - vp.MaxZ = 1.0f; // minZ = maxZ = 0 forces all polys to be in foreground - m_pd3dDevice->SetViewport(&vp); - - // Matrix to map from SWF movie (TWIPs) coords to - // viewport coordinates. - // Clear the backbuffer to a blue color - // m_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0,0,255), 1.0f, 0 ); - - if( FAILED( m_pd3dDevice->BeginScene() ) ) - { - // Rendering of scene objects can happen here - - // End the scene - m_pd3dDevice->EndScene(); - assert(0); - } - - - // Blending renderstates - //pk not sure if we need these. - m_pd3dDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA ); - m_pd3dDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA ); - m_pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE ); - m_pd3dDevice->SetRenderState( D3DRS_BLENDOP, D3DBLENDOP_ADD ); - - - m_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE); - m_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); - m_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_TFACTOR); - m_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_TFACTOR); - - // Textures off by default. - m_pd3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG2); - m_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG2); - - // @@ for sanity's sake, let's turn of backface culling... - m_pd3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);//xxxxx - m_pd3dDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS); //xxxxx - - // Vertex format. -#if DIRECT3D_VERSION >= 0x0900 - m_pd3dDevice->SetVertexShader(NULL); -#endif - - // No pixel shader. - m_pd3dDevice->SetPixelShader(NULL); - - // Clear the background, if background color has alpha > 0. - if (background_color.m_a > 0) - { - if( background_color.m_a==255 ) - { - D3DRECT rect = {LONG(x0),LONG(y0),LONG(x1),LONG(y1)}; - m_pd3dDevice->Clear(1, &rect,D3DCLEAR_TARGET, - D3DCOLOR_XRGB(background_color.m_r, background_color.m_g, background_color.m_b), - 0.0f, 0 ); - } - else - { - const Sint16 backgroundCoords[] = { - (Sint16)x0,(Sint16)y0, - (Sint16)x1,(Sint16)y0, - (Sint16)x0,(Sint16)y1, - (Sint16)x1,(Sint16)y1}; - apply_color(background_color); - set_matrix(gameswf::matrix::identity); - apply_matrix(m_current_matrix); - prepare_vertex_buffer(backgroundCoords, 4); - HRESULT hr = m_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2); - assert(hr==S_OK); - } - } - } - - - void end_display() - // Clean up after rendering a frame. Client program is still - // responsible for calling glSwapBuffers() or whatever. - { - // End the scene - m_pd3dDevice->EndScene(); - - // Present the backbuffer contents to the display - D3DXMATRIX mat; - D3DXMatrixIdentity( &mat ); - m_pd3dDevice->SetTransform(D3DTS_VIEW, &mat); - m_pd3dDevice->SetTransform(D3DTS_WORLD, &mat); - -#if DIRECT3D_VERSION >= 0x0900 - m_pd3dDevice->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP); - m_pd3dDevice->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP); -#else - m_pd3dDevice->SetTextureStageState(0, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP); - m_pd3dDevice->SetTextureStageState(0, D3DTSS_ADDRESSV, D3DTADDRESS_WRAP); -#endif - - m_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_CURRENT); - m_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_CURRENT); - m_pd3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE); - m_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1); - m_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE ); - m_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_PASSTHRU ); - - m_pd3dDevice->SetViewport(&m_origVP); - } - - - void set_matrix(const gameswf::matrix& m) - // Set the current transform for mesh & line-strip rendering. - { - m_current_matrix = m; - } - - - void set_cxform(const gameswf::cxform& cx) - // Set the current color transform for mesh & line-strip rendering. - { - m_current_cxform = cx; - } - - void apply_matrix(const gameswf::matrix& m) - // Set the given transformation matrix. - { - D3DXMATRIX mat; - D3DXMatrixIdentity( &mat ); - // row 0 - mat._11 = m.m_[0][0]; mat._12 = m.m_[1][0]; mat._13 = 0.00f; mat._14 = 0.00f; - mat._21 = m.m_[0][1]; mat._22 = m.m_[1][1]; mat._23 = 0.00f; mat._24 = 0.00f; - mat._31 = 0.00f; mat._32 = 0.00f; mat._33 = 1.00f; mat._34 = 0.00f; - mat._41 = m.m_[0][2]; mat._42 = m.m_[1][2]; mat._43 = 0.00f; mat._44 = 1.00f; - - m_pd3dDevice->SetTransform(D3DTS_WORLD, &mat); - } - - static void apply_color(const gameswf::rgba& c) - // Set the given color. - { - HRESULT hr = m_pd3dDevice->SetRenderState( D3DRS_TEXTUREFACTOR, D3DCOLOR_ARGB(c.m_a, c.m_r, c.m_g, c.m_b)); - assert(hr==S_OK); - } - - void fill_style_disable(int fill_side) - // Don't fill on the {0 == left, 1 == right} side of a path. - { - assert(fill_side >= 0 && fill_side < 2); - - m_current_styles[fill_side].disable(); - } - - - void line_style_disable() - // Don't draw a line on this path. - { - m_current_styles[LINE_STYLE].disable(); - } - - - void fill_style_color(int fill_side, gameswf::rgba color) - // Set fill style for the left interior of the shape. If - // enable is false, turn off fill for the left interior. - { - assert(fill_side >= 0 && fill_side < 2); - - m_current_styles[fill_side].set_color(m_current_cxform.transform(color)); - } - - - void line_style_color(gameswf::rgba color) - // Set the line style of the shape. If enable is false, turn - // off lines for following curve segments. - { - m_current_styles[LINE_STYLE].set_color(m_current_cxform.transform(color)); - } - - - void fill_style_bitmap(int fill_side, const gameswf::bitmap_info* bi, const gameswf::matrix& m, bitmap_wrap_mode wm) - { - assert(fill_side >= 0 && fill_side < 2); - m_current_styles[fill_side].set_bitmap(bi, m, wm, m_current_cxform); - } - - void line_style_width(float width) - { - // WK: what to do here??? - } - - - void draw_mesh_strip(const void* coords, int vertex_count) - { - // Set up current style. - m_current_styles[LEFT_STYLE].apply(m_current_matrix); - - apply_matrix(m_current_matrix); - prepare_vertex_buffer((Sint16*)coords, vertex_count); - HRESULT hr = m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0, vertex_count - 2); - assert(hr==S_OK); - - if (m_current_styles[LEFT_STYLE].needs_second_pass()) - { - // 2nd pass, if necessary. - m_current_styles[LEFT_STYLE].apply_second_pass(); - hr = m_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, vertex_count-2); - assert(hr==S_OK); - m_current_styles[LEFT_STYLE].cleanup_second_pass(); - } - } - - - void draw_line_strip(const void* coords, int vertex_count) - // Draw the line strip formed by the sequence of points. - { - // Set up current style. - m_current_styles[LINE_STYLE].apply(m_current_matrix); - - apply_matrix(m_current_matrix); - prepare_vertex_buffer((Sint16*)coords, vertex_count); - HRESULT hr = m_pd3dDevice->DrawPrimitive( D3DPT_LINESTRIP, 0, vertex_count-1); - assert(hr==S_OK); - } - - - void draw_bitmap( - const gameswf::matrix& m, - const gameswf::bitmap_info* bi, - const gameswf::rect& coords, - const gameswf::rect& uv_coords, - gameswf::rgba color) - // Draw a rectangle textured with the given bitmap, with the - // given color. Apply given transform; ignore any currently - // set transforms. - // - // Intended for textured glyph rendering. - { - assert(bi); - - apply_color(color); - D3DXMATRIX mat; - D3DXMatrixIdentity(&mat); - m_pd3dDevice->SetTransform(D3DTS_WORLD, &mat); - - gameswf::point a, b, c, d; - m.transform(&a, gameswf::point(coords.m_x_min, coords.m_y_min)); - m.transform(&b, gameswf::point(coords.m_x_max, coords.m_y_min)); - m.transform(&c, gameswf::point(coords.m_x_min, coords.m_y_max)); - d.m_x = b.m_x + c.m_x - a.m_x; - d.m_y = b.m_y + c.m_y - a.m_y; - - // Set texture. - m_pd3dDevice->SetTexture(0, m_d3d_textures[bi->m_texture_id]); - m_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG2); - m_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1); - - m_pd3dDevice->SetRenderState(D3DRS_SRCBLEND,D3DBLEND_SRCALPHA); - m_pd3dDevice->SetRenderState(D3DRS_DESTBLEND,D3DBLEND_INVSRCALPHA); - - // No texgen; just pass through. - m_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE ); - m_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_PASSTHRU ); - - // Draw the quad. - - //pk - CUSTOMVERTEX2 *pVertices; - HRESULT result; - - if( FAILED( m_pVB2->Lock( 0, 0, (tLock**)&pVertices, D3DLOCK_DISCARD ) ) ) - { - assert(0); - } - - pVertices[0].x = a.m_x ; - pVertices[0].y = a.m_y ; - pVertices[0].z = Z_DEPTH; - pVertices[0].tu = uv_coords.m_x_min ; - pVertices[0].tv = uv_coords.m_y_min ; - - pVertices[1].x = b.m_x ; - pVertices[1].y = b.m_y ; - pVertices[1].z = Z_DEPTH; - pVertices[1].tu = uv_coords.m_x_max ; - pVertices[1].tv = uv_coords.m_y_min ; - - pVertices[2].x = c.m_x ; - pVertices[2].y = c.m_y ; - pVertices[2].z = Z_DEPTH; - pVertices[2].tu = uv_coords.m_x_min ; - pVertices[2].tv = uv_coords.m_y_max ; - - pVertices[3].x = d.m_x ; - pVertices[3].y = d.m_y ; - pVertices[3].z = Z_DEPTH; - pVertices[3].tu = uv_coords.m_x_max ; - pVertices[3].tv = uv_coords.m_y_max ; - - m_pVB2->Unlock(); - - // Render the vertex buffer contents - m_pd3dDevice->SetStreamSource( 0, m_pVB2, -#if DIRECT3D_VERSION >= 0x0900 - 0, -#endif - sizeof(CUSTOMVERTEX2) ); -#if DIRECT3D_VERSION < 0x0900 - m_pd3dDevice->SetVertexShader(D3DFVF_CUSTOMVERTEX2); -#else - m_pd3dDevice->SetFVF(D3DFVF_CUSTOMVERTEX2); -#endif - result = m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0, 2 ); - assert(result==S_OK); - } - - void begin_submit_mask() - { - - m_pd3dDevice->SetRenderState( - D3DRS_ZWRITEENABLE, - FALSE ); - - // Enable stencil testing - m_pd3dDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE); - - //m_pd3dDevice->SetRenderState( - // D3DRS_ZWRITEENABLE, - // FALSE, false ); - - - // Clear stencil buffer values to zero - m_pd3dDevice->Clear(0, NULL, D3DCLEAR_STENCIL, 0, 1.0f, 0); - - // Specify the stencil comparison function - m_pd3dDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS ); - - // Set the comparison reference value - m_pd3dDevice->SetRenderState(D3DRS_STENCILREF, 1); - - // Specify a stencil mask - m_pd3dDevice->SetRenderState(D3DRS_STENCILMASK, 0x1); - - // A write mask controls what is written - m_pd3dDevice->SetRenderState(D3DRS_STENCILWRITEMASK, 0x1); - - m_pd3dDevice->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_KEEP); - - m_pd3dDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_REPLACE); - - m_pd3dDevice->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_KEEP); - -#if 0 - glEnable(GL_STENCIL_TEST); - glClearStencil(0); - glClear(GL_STENCIL_BUFFER_BIT); - glColorMask(0,0,0,0); // disable framebuffer writes - glEnable(GL_STENCIL_TEST); // enable stencil buffer for "marking" the mask - glStencilFunc(GL_ALWAYS, 1, 1); // always passes, 1 bit plane, 1 as mask - glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); // we set the stencil buffer to 1 where we draw any polygon - // keep if test fails, keep if test passes but buffer test fails - // replace if test passes -#endif // 0 - } - - void end_submit_mask() - { - - // Specify when to write stencil data - m_pd3dDevice->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_KEEP); - - m_pd3dDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_KEEP); - - m_pd3dDevice->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_KEEP); - - // Specify the stencil comparison function - m_pd3dDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_EQUAL); - - m_pd3dDevice->SetRenderState(D3DRS_ZWRITEENABLE,TRUE); - -#if 0 - glColorMask(1,1,1,1); // enable framebuffer writes - glStencilFunc(GL_EQUAL, 1, 1); // we draw only where the stencil is 1 (where the mask was drawn) - glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); // don't change the stencil buffer -#endif // 0 - } - - void disable_mask() - { - m_pd3dDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE); - -#if 0 - glDisable(GL_STENCIL_TEST); -#endif // 0 - } - -}; // end struct render_handler_d3d - - -// bitmap_info_d3d implementation - - -bitmap_info_d3d::bitmap_info_d3d() -//bitmap_info_d3d::bitmap_info_d3d(create_empty e) -{ - // A null texture. Needs to be initialized later. - m_texture_id = 0; - m_original_width = 0; - m_original_height = 0; -} - - -bitmap_info_d3d::bitmap_info_d3d(image::rgb* im) -// Image with no alpha. -{ - assert(im); - - // Rescale. - m_original_width = im->m_width; - m_original_height = im->m_height; - - int w = 1; while (w < im->m_width) { w <<= 1; } - int h = 1; while (h < im->m_height) { h <<= 1; } - - // Need to insert a dummy alpha byte in the image data, for - // D3DXLoadSurfaceFromMemory. - // @@ this sucks :( - Uint8* expanded_data = new Uint8[m_original_width * m_original_height * 4]; - Uint8* pdata = expanded_data; - for (int y = 0; y < m_original_height; y++) - { - Uint8* scanline = image::scanline(im, y); - for (int x = 0; x < m_original_width; x++) - { - *pdata++ = scanline[x * 3 + 2]; // blue - *pdata++ = scanline[x * 3 + 1]; // green - *pdata++ = scanline[x * 3 + 0]; // red - *pdata++ = 255; // alpha - } - } - - // Create the texture. - render_handler_d3d::m_d3d_textures.push_back(NULL); - m_texture_id = render_handler_d3d::m_d3d_textures.size() - 1; - - IDirect3DTexture* tex; - HRESULT result = render_handler_d3d::m_pd3dDevice->CreateTexture( - w, h, 1, 0, // Usage - render_handler_d3d::m_FormatRGB, // Format - D3DPOOL_MANAGED, &tex -#if DIRECT3D_VERSION >= 0x0900 - , NULL -#endif - ); - - if (render_handler_d3d::m_FormatRGB!=D3DFMT_A8R8G8B8 && result != S_OK) - { - result = render_handler_d3d::m_pd3dDevice->CreateTexture( - w, h, 1, 0, // Usage - D3DFMT_A8R8G8B8, // Format - D3DPOOL_MANAGED, &tex -#if DIRECT3D_VERSION >= 0x0900 - , NULL -#endif - ); - } - if (result != S_OK) - { - gameswf::log_error("error: can't create texture\n"); - return; - } - assert(tex); - render_handler_d3d::m_d3d_textures.back() = tex; - - IDirect3DSurface* surf = NULL; - result = tex->GetSurfaceLevel(0, &surf); - if (result != S_OK) - { - gameswf::log_error("error: can't get surface\n"); - return; - } - assert(surf); - - RECT source_rect; - source_rect.left = 0; - source_rect.top = 0; - source_rect.right = m_original_width; - source_rect.bottom = m_original_height; - result = D3DXLoadSurfaceFromMemory( surf, NULL, NULL, expanded_data, - D3DFMT_A8R8G8B8, m_original_width * 4, NULL, &source_rect, D3DX_DEFAULT, 0 ); - - // test - //D3DXSaveSurfaceToFile( "image.png", D3DXIFF_PNG, surf, NULL, NULL ); - - delete [] expanded_data; - if (result != S_OK) - gameswf::log_error("error: can't load surface from memory, result = %d\n", result); - - surf->Release(); -} - -typedef struct -{ - Uint8 r; - Uint8 g; - Uint8 b; - Uint8 a; -} RGBA; - -void bitmap_info_d3d::convert_to_argb(image::rgba* im) -{ - for (int h = 0; h < im->m_height; h++) - { - for (int w = 0; w < im->m_width; w++) - { - RGBA c; - c.r = im->m_data[((h * im->m_width) + w ) * 4]; - c.g = im->m_data[(((h * im->m_width) + w ) * 4) + 1]; - c.b = im->m_data[(((h * im->m_width) + w ) * 4) + 2]; - c.a = im->m_data[(((h * im->m_width) + w ) * 4) + 3]; - im->m_data[((h * im->m_width) + w ) * 4 + 3] = c.a; - im->m_data[(((h * im->m_width) + w ) * 4) + 2] = c.r; - im->m_data[(((h * im->m_width) + w ) * 4) + 1] = c.g; - im->m_data[(((h * im->m_width) + w ) * 4) + 0] = c.b; - } - } -} - -bitmap_info_d3d::bitmap_info_d3d(image::rgba* im) -// Version of the constructor that takes an image with alpha. -{ - assert(im); - -#if DIRECT3D_VERSION < 0x0900 - convert_to_argb(im); -#endif - - m_original_width = im->m_width; - m_original_height = im->m_height; - - int w = 1; while (w < im->m_width) { w <<= 1; } - int h = 1; while (h < im->m_height) { h <<= 1; } - - // Create the texture. - render_handler_d3d::m_d3d_textures.push_back(NULL); - m_texture_id = render_handler_d3d::m_d3d_textures.size() - 1; - - IDirect3DTexture* tex; - HRESULT result = render_handler_d3d::m_pd3dDevice->CreateTexture( - w, h, 1, 0, // Usage - render_handler_d3d::m_FormatRGBA, // Format - D3DPOOL_MANAGED, &tex -#if DIRECT3D_VERSION >= 0x0900 - , NULL -#endif - ); - - if (render_handler_d3d::m_FormatRGBA!=D3DFMT_A8R8G8B8 && result != S_OK) - { - result = render_handler_d3d::m_pd3dDevice->CreateTexture( - w, h, 1, 0, // Usage - D3DFMT_A8R8G8B8, // Format - D3DPOOL_MANAGED, &tex -#if DIRECT3D_VERSION >= 0x0900 - , NULL -#endif - ); - } - - if (result != S_OK) - { - gameswf::log_error("error: can't create texture\n"); - return; - } - assert(tex); - render_handler_d3d::m_d3d_textures.back() = tex; - - IDirect3DSurface* surf = NULL; - result = tex->GetSurfaceLevel(0, &surf); - if (result != S_OK) - { - gameswf::log_error("error: can't get surface\n"); - return; - } - assert(surf); - - RECT source_rect; - source_rect.left = 0; - source_rect.top = 0; - source_rect.right = m_original_width; - source_rect.bottom = m_original_height; - - // Set the actual data. - result = D3DXLoadSurfaceFromMemory( surf, NULL, NULL, im->m_data, -#if DIRECT3D_VERSION < 0x0900 - D3DFMT_A8R8G8B8, -#else - D3DFMT_A8B8G8R8, -#endif - im->m_pitch, NULL, &source_rect, D3DX_DEFAULT, 0); - - if (result != S_OK) - gameswf::log_error("error: can't load surface from memory, result = %d\n", result); - - surf->Release(); -} - - -bitmap_info_d3d::bitmap_info_d3d(int width, int height, Uint8* data) -// Initialize this bitmap_info to an alpha image -// containing the specified data (1 byte per texel). -// -// !! Munges *data in order to create mipmaps !! -{ - assert(data); - - // Create the texture. - m_original_width = width; - m_original_height = height; - - // You must use power-of-two dimensions!! - int w = 1; while (w < width) { w <<= 1; } - int h = 1; while (h < height) { h <<= 1; } - - render_handler_d3d::m_d3d_textures.push_back(NULL); - m_texture_id = render_handler_d3d::m_d3d_textures.size() - 1; - - IDirect3DTexture* tex; - HRESULT result = render_handler_d3d::m_pd3dDevice->CreateTexture( - w, h, 1, 0, // Usage - render_handler_d3d::m_FormatA, // Format - D3DPOOL_MANAGED, &tex -#if DIRECT3D_VERSION >= 0x0900 - , NULL -#endif - ); - - if (result != S_OK) - { - gameswf::log_error("error: can't create texture\n"); - return; - } - assert(tex); - render_handler_d3d::m_d3d_textures.back() = tex; - - IDirect3DSurface* surf = NULL; - - result = tex->GetSurfaceLevel(0, &surf); - if (result != S_OK) - { - gameswf::log_error("error: can't get surface\n"); - return; - } - assert(surf); - - RECT source_rect; - source_rect.left = 0; - source_rect.top = 0; - source_rect.right = width; - source_rect.bottom = height; - result = D3DXLoadSurfaceFromMemory( surf, NULL, NULL, data, - D3DFMT_A8, width, NULL, &source_rect, D3DX_DEFAULT, 0); - - if (result != S_OK) - gameswf::log_error("error: can't load surface from memory, result = %d\n", result); - - surf->Release(); - - // glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, data); - - // // Build mips. - // int level = 1; - // while (width > 1 || height > 1) - // { - // render_handler_d3d::make_next_miplevel(&width, &height, data); - // glTexImage2D(GL_TEXTURE_2D, level, GL_ALPHA, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, data); - // level++; - // } -} - -IDirect3DDevice* render_handler_d3d::m_pd3dDevice; -D3DFORMAT render_handler_d3d::m_FormatRGB; -D3DFORMAT render_handler_d3d::m_FormatRGBA; -D3DFORMAT render_handler_d3d::m_FormatA; -D3DXMATRIX render_handler_d3d::m_ModelViewMatrix; -D3DXMATRIX render_handler_d3d::m_ProjMatrix; -array render_handler_d3d::m_d3d_textures; - -gameswf::render_handler* gameswf::create_render_handler_d3d(IDirect3DDevice* device) -// Factory. -{ - render_handler_d3d *hndlr = new render_handler_d3d( device ); - return hndlr; -} - -// Local Variables: -// mode: C++ -// c-basic-offset: 8 -// tab-width: 8 -// indent-tabs-mode: t -// End: - - - - - diff --git a/Code/BF2/External/gameswf/gameswf_render_handler_ogl.cpp b/Code/BF2/External/gameswf/gameswf_render_handler_ogl.cpp deleted file mode 100644 index deaa705f1..000000000 --- a/Code/BF2/External/gameswf/gameswf_render_handler_ogl.cpp +++ /dev/null @@ -1,1175 +0,0 @@ -// gameswf_render_handler_ogl.cpp -- Willem Kokke 2003 - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - -// A gameswf::render_handler that uses SDL & OpenGL - - -#include "gameswf.h" -#include "gameswf_types.h" -#include "base/image.h" -#include "base/ogl.h" -#include "base/utility.h" - -#include // for memset() - - -// choose the resampling method: -// 1 = hardware (experimental, should be fast, somewhat buggy) -// 2 = fast software bilinear (default) -// 3 = use image::resample(), slow software resampling -#define RESAMPLE_METHOD 2 - - -// Determines whether to generate mipmaps for smoother rendering of -// minified textures. It actually tends to look OK to not use -// mipmaps, though it is potentially a performance hit if you use big -// textures. -// -// TODO: need to code mipmap LOD bias adjustment, to keep mipmaps from -// looking too blurry. (Also applies to text rendering.) -#define GENERATE_MIPMAPS 0 - -// bitmap_info_ogl declaration -struct bitmap_info_ogl : public gameswf::bitmap_info -{ - bitmap_info_ogl(); - bitmap_info_ogl(int width, int height, Uint8* data); - bitmap_info_ogl(image::rgb* im); - bitmap_info_ogl(image::rgba* im); - - ~bitmap_info_ogl() - { - if (m_texture_id > 0) - { - glDeleteTextures(1, (GLuint*) &m_texture_id); - } - } -}; - -struct render_handler_ogl : public gameswf::render_handler -{ - // Some renderer state. - - // Enable/disable antialiasing. - bool m_enable_antialias; - - // Output size. - float m_display_width; - float m_display_height; - - gameswf::matrix m_current_matrix; - gameswf::cxform m_current_cxform; - void set_antialiased(bool enable) - { - m_enable_antialias = enable; - } - - static void make_next_miplevel(int* width, int* height, Uint8* data) - // Utility. Mutates *width, *height and *data to create the - // next mip level. - { - assert(width); - assert(height); - assert(data); - - int new_w = *width >> 1; - int new_h = *height >> 1; - if (new_w < 1) new_w = 1; - if (new_h < 1) new_h = 1; - - if (new_w * 2 != *width || new_h * 2 != *height) - { - // Image can't be shrunk along (at least) one - // of its dimensions, so don't bother - // resampling. Technically we should, but - // it's pretty useless at this point. Just - // change the image dimensions and leave the - // existing pixels. - } - else - { - // Resample. Simple average 2x2 --> 1, in-place. - for (int j = 0; j < new_h; j++) { - Uint8* out = ((Uint8*) data) + j * new_w; - Uint8* in = ((Uint8*) data) + (j << 1) * *width; - for (int i = 0; i < new_w; i++) { - int a; - a = (*(in + 0) + *(in + 1) + *(in + 0 + *width) + *(in + 1 + *width)); - *(out) = a >> 2; - out++; - in += 2; - } - } - } - - // Munge parameters to reflect the shrunken image. - *width = new_w; - *height = new_h; - } - - struct fill_style - { - enum mode - { - INVALID, - COLOR, - BITMAP_WRAP, - BITMAP_CLAMP, - LINEAR_GRADIENT, - RADIAL_GRADIENT, - }; - mode m_mode; - gameswf::rgba m_color; - const gameswf::bitmap_info* m_bitmap_info; - gameswf::matrix m_bitmap_matrix; - gameswf::cxform m_bitmap_color_transform; - bool m_has_nonzero_bitmap_additive_color; - - fill_style() - : - m_mode(INVALID), - m_has_nonzero_bitmap_additive_color(false) - { - } - - void apply(/*const matrix& current_matrix*/) const - // Push our style into OpenGL. - { - assert(m_mode != INVALID); - - if (m_mode == COLOR) - { - apply_color(m_color); - glDisable(GL_TEXTURE_2D); - } - else if (m_mode == BITMAP_WRAP - || m_mode == BITMAP_CLAMP) - { - assert(m_bitmap_info != NULL); - - apply_color(m_color); - - if (m_bitmap_info == NULL) - { - glDisable(GL_TEXTURE_2D); - } - else - { - // Set up the texture for rendering. - { - // Do the modulate part of the color - // transform in the first pass. The - // additive part, if any, needs to - // happen in a second pass. - glColor4f(m_bitmap_color_transform.m_[0][0], - m_bitmap_color_transform.m_[1][0], - m_bitmap_color_transform.m_[2][0], - m_bitmap_color_transform.m_[3][0] - ); - } - - glBindTexture(GL_TEXTURE_2D, m_bitmap_info->m_texture_id); - glEnable(GL_TEXTURE_2D); - glEnable(GL_TEXTURE_GEN_S); - glEnable(GL_TEXTURE_GEN_T); - - if (m_mode == BITMAP_CLAMP) - { - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - } - else - { - assert(m_mode == BITMAP_WRAP); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - } - - // Set up the bitmap matrix for texgen. - - float inv_width = 1.0f / m_bitmap_info->m_original_width; - float inv_height = 1.0f / m_bitmap_info->m_original_height; - - const gameswf::matrix& m = m_bitmap_matrix; - glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); - float p[4] = { 0, 0, 0, 0 }; - p[0] = m.m_[0][0] * inv_width; - p[1] = m.m_[0][1] * inv_width; - p[3] = m.m_[0][2] * inv_width; - glTexGenfv(GL_S, GL_OBJECT_PLANE, p); - - glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); - p[0] = m.m_[1][0] * inv_height; - p[1] = m.m_[1][1] * inv_height; - p[3] = m.m_[1][2] * inv_height; - glTexGenfv(GL_T, GL_OBJECT_PLANE, p); - } - } - } - - - bool needs_second_pass() const - // Return true if we need to do a second pass to make - // a valid color. This is for cxforms with additive - // parts; this is the simplest way (that we know of) - // to implement an additive color with stock OpenGL. - { - if (m_mode == BITMAP_WRAP - || m_mode == BITMAP_CLAMP) - { - return m_has_nonzero_bitmap_additive_color; - } - else - { - return false; - } - } - - void apply_second_pass() const - // Set OpenGL state for a necessary second pass. - { - assert(needs_second_pass()); - - // The additive color also seems to be modulated by the texture. So, - // maybe we can fake this in one pass using using the mean value of - // the colors: c0*t+c1*t = ((c0+c1)/2) * t*2 - // I don't know what the alpha component of the color is for. - //glDisable(GL_TEXTURE_2D); - - glColor4f( - m_bitmap_color_transform.m_[0][1] / 255.0f, - m_bitmap_color_transform.m_[1][1] / 255.0f, - m_bitmap_color_transform.m_[2][1] / 255.0f, - m_bitmap_color_transform.m_[3][1] / 255.0f - ); - - glBlendFunc(GL_ONE, GL_ONE); - } - - void cleanup_second_pass() const - { - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - } - - - void disable() { m_mode = INVALID; } - void set_color(gameswf::rgba color) { m_mode = COLOR; m_color = color; } - void set_bitmap(const gameswf::bitmap_info* bi, const gameswf::matrix& m, bitmap_wrap_mode wm, const gameswf::cxform& color_transform) - { - m_mode = (wm == WRAP_REPEAT) ? BITMAP_WRAP : BITMAP_CLAMP; - m_bitmap_info = bi; - m_bitmap_matrix = m; - m_bitmap_color_transform = color_transform; - m_bitmap_color_transform.clamp(); - - m_color = gameswf::rgba( - Uint8(m_bitmap_color_transform.m_[0][0] * 255.0f), - Uint8(m_bitmap_color_transform.m_[1][0] * 255.0f), - Uint8(m_bitmap_color_transform.m_[2][0] * 255.0f), - Uint8(m_bitmap_color_transform.m_[3][0] * 255.0f)); - - if (m_bitmap_color_transform.m_[0][1] > 1.0f - || m_bitmap_color_transform.m_[1][1] > 1.0f - || m_bitmap_color_transform.m_[2][1] > 1.0f - || m_bitmap_color_transform.m_[3][1] > 1.0f) - { - m_has_nonzero_bitmap_additive_color = true; - } - else - { - m_has_nonzero_bitmap_additive_color = false; - } - } - bool is_valid() const { return m_mode != INVALID; } - }; - - - // Style state. - enum style_index - { - LEFT_STYLE = 0, - RIGHT_STYLE, - LINE_STYLE, - - STYLE_COUNT - }; - fill_style m_current_styles[STYLE_COUNT]; - - - gameswf::bitmap_info* create_bitmap_info_rgb(image::rgb* im) - // Given an image, returns a pointer to a bitmap_info struct - // that can later be passed to fill_styleX_bitmap(), to set a - // bitmap fill style. - { - return new bitmap_info_ogl(im); - } - - - gameswf::bitmap_info* create_bitmap_info_rgba(image::rgba* im) - // Given an image, returns a pointer to a bitmap_info struct - // that can later be passed to fill_style_bitmap(), to set a - // bitmap fill style. - // - // This version takes an image with an alpha channel. - { - return new bitmap_info_ogl(im); - } - - - gameswf::bitmap_info* create_bitmap_info_empty() - // Create a placeholder bitmap_info. Used when - // DO_NOT_LOAD_BITMAPS is set; then later on the host program - // can use movie_definition::get_bitmap_info_count() and - // movie_definition::get_bitmap_info() to stuff precomputed - // textures into these bitmap infos. - { - return new bitmap_info_ogl; - } - - gameswf::bitmap_info* create_bitmap_info_alpha(int w, int h, Uint8* data) - // Create a bitmap_info so that it contains an alpha texture - // with the given data (1 byte per texel). - // - // Munges *data (in order to make mipmaps)!! - { - return new bitmap_info_ogl(w, h, data); - } - - - void delete_bitmap_info(gameswf::bitmap_info* bi) - // Delete the given bitmap info struct. - { - delete bi; - } - - - ~render_handler_ogl() - { - } - - - void begin_display( - gameswf::rgba background_color, - int viewport_x0, int viewport_y0, - int viewport_width, int viewport_height, - float x0, float x1, float y0, float y1) - // Set up to render a full frame from a movie and fills the - // background. Sets up necessary transforms, to scale the - // movie to fit within the given dimensions. Call - // end_display() when you're done. - // - // The rectangle (viewport_x0, viewport_y0, viewport_x0 + - // viewport_width, viewport_y0 + viewport_height) defines the - // window coordinates taken up by the movie. - // - // The rectangle (x0, y0, x1, y1) defines the pixel - // coordinates of the movie that correspond to the viewport - // bounds. - { - m_display_width = fabsf(x1 - x0); - m_display_height = fabsf(y1 - y0); - - glViewport(viewport_x0, viewport_y0, viewport_width, viewport_height); - - glMatrixMode(GL_MODELVIEW); - glPushMatrix(); - glOrtho(x0, x1, y0, y1, -1, 1); - - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - - glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); // GL_MODULATE - - glDisable(GL_TEXTURE_2D); - - // Clear the background, if background color has alpha > 0. - if (background_color.m_a > 0) - { - // Draw a big quad. - apply_color(background_color); - glBegin(GL_QUADS); - glVertex2f(x0, y0); - glVertex2f(x1, y0); - glVertex2f(x1, y1); - glVertex2f(x0, y1); - glEnd(); - } - - // Old unused code. Might get revived someday. - #if 0 - // See if we want to, and can, use multitexture - // antialiasing. - s_multitexture_antialias = false; - if (m_enable_antialias) - { - int tex_units = 0; - glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, &tex_units); - if (tex_units >= 2) - { - s_multitexture_antialias = true; - } - - // Make sure we have an edge texture available. - if (s_multitexture_antialias == true - && s_edge_texture_id == 0) - { - // Very simple texture: 2 texels wide, 1 texel high. - // Both texels are white; left texel is all clear, right texel is all opaque. - unsigned char edge_data[8] = { 255, 255, 255, 0, 255, 255, 255, 255 }; - - ogl::active_texture(GL_TEXTURE1_ARB); - glEnable(GL_TEXTURE_2D); - glGenTextures(1, &s_edge_texture_id); - glBindTexture(GL_TEXTURE_2D, s_edge_texture_id); - - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 2, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, edge_data); - - glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); // @@ should we use a 1D texture??? - - glDisable(GL_TEXTURE_2D); - ogl::active_texture(GL_TEXTURE0_ARB); - glDisable(GL_TEXTURE_2D); - } - } - #endif // 0 - } - - - void end_display() - // Clean up after rendering a frame. Client program is still - // responsible for calling glSwapBuffers() or whatever. - { - glMatrixMode(GL_MODELVIEW); - glPopMatrix(); - } - - - void set_matrix(const gameswf::matrix& m) - // Set the current transform for mesh & line-strip rendering. - { - m_current_matrix = m; - } - - - void set_cxform(const gameswf::cxform& cx) - // Set the current color transform for mesh & line-strip rendering. - { - m_current_cxform = cx; - } - - static void apply_matrix(const gameswf::matrix& m) - // multiply current matrix with opengl matrix - { - float mat[16]; - memset(&mat[0], 0, sizeof(mat)); - mat[0] = m.m_[0][0]; - mat[1] = m.m_[1][0]; - mat[4] = m.m_[0][1]; - mat[5] = m.m_[1][1]; - mat[10] = 1; - mat[12] = m.m_[0][2]; - mat[13] = m.m_[1][2]; - mat[15] = 1; - glMultMatrixf(mat); - } - - static void apply_color(const gameswf::rgba& c) - // Set the given color. - { - glColor4ub(c.m_r, c.m_g, c.m_b, c.m_a); - } - - void fill_style_disable(int fill_side) - // Don't fill on the {0 == left, 1 == right} side of a path. - { - assert(fill_side >= 0 && fill_side < 2); - - m_current_styles[fill_side].disable(); - } - - - void line_style_disable() - // Don't draw a line on this path. - { - m_current_styles[LINE_STYLE].disable(); - } - - - void fill_style_color(int fill_side, gameswf::rgba color) - // Set fill style for the left interior of the shape. If - // enable is false, turn off fill for the left interior. - { - assert(fill_side >= 0 && fill_side < 2); - - m_current_styles[fill_side].set_color(m_current_cxform.transform(color)); - } - - - void line_style_color(gameswf::rgba color) - // Set the line style of the shape. If enable is false, turn - // off lines for following curve segments. - { - m_current_styles[LINE_STYLE].set_color(m_current_cxform.transform(color)); - } - - - void fill_style_bitmap(int fill_side, const gameswf::bitmap_info* bi, const gameswf::matrix& m, bitmap_wrap_mode wm) - { - assert(fill_side >= 0 && fill_side < 2); - m_current_styles[fill_side].set_bitmap(bi, m, wm, m_current_cxform); - } - - void line_style_width(float width) - { - // WK: what to do here??? - } - - - void draw_mesh_strip(const void* coords, int vertex_count) - { -#define NORMAL_RENDERING -//#define MULTIPASS_ANTIALIASING - -#ifdef NORMAL_RENDERING - // Set up current style. - m_current_styles[LEFT_STYLE].apply(); - - glMatrixMode(GL_MODELVIEW); - glPushMatrix(); - apply_matrix(m_current_matrix); - - // Send the tris to OpenGL - glEnableClientState(GL_VERTEX_ARRAY); - glVertexPointer(2, GL_SHORT, sizeof(Sint16) * 2, coords); - glDrawArrays(GL_TRIANGLE_STRIP, 0, vertex_count); - - if (m_current_styles[LEFT_STYLE].needs_second_pass()) - { - m_current_styles[LEFT_STYLE].apply_second_pass(); - glDrawArrays(GL_TRIANGLE_STRIP, 0, vertex_count); - m_current_styles[LEFT_STYLE].cleanup_second_pass(); - } - - glDisableClientState(GL_VERTEX_ARRAY); - - glPopMatrix(); -#endif // NORMAL_RENDERING - -#ifdef MULTIPASS_ANTIALIASING - // So this approach basically works. This - // implementation is not totally finished; two pass - // materials (i.e. w/ additive color) aren't correct, - // and there are some texture etc issues because I'm - // just hosing state uncarefully here. It needs the - // optimization of only filling the bounding box of - // the shape. You must have destination alpha. - // - // It doesn't look quite perfect on my GF4. For one - // thing, you kinda want to crank down the max curve - // subdivision error, because suddenly you can see - // sub-pixel shape much better. For another thing, - // the antialiasing isn't quite perfect, to my eye. - // It could be limited alpha precision, imperfections - // GL_POLYGON_SMOOTH, and/or my imagination. - - glDisable(GL_TEXTURE_2D); - - glEnable(GL_POLYGON_SMOOTH); - glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST); // GL_NICEST, GL_FASTEST, GL_DONT_CARE - - // Clear destination alpha. - // - // @@ TODO Instead of drawing this huge screen-filling - // quad, we should take a bounding-box param from the - // caller, and draw the box (after apply_matrix; - // i.e. the box is in object space). The point being, - // to only fill the part of the screen that the shape - // is in. - glBlendFunc(GL_ZERO, GL_SRC_COLOR); - glColor4f(1, 1, 1, 0); - glBegin(GL_QUADS); - glVertex2f(0, 0); - glVertex2f(100000, 0); - glVertex2f(100000, 100000); - glVertex2f(0, 100000); - glEnd(); - - // Set mode for drawing alpha mask. - glBlendFunc(GL_ONE, GL_ONE); // additive blending - glColor4f(0, 0, 0, m_current_styles[LEFT_STYLE].m_color.m_a / 255.0f); - - glMatrixMode(GL_MODELVIEW); - glPushMatrix(); - apply_matrix(m_current_matrix); - - // Send the tris to OpenGL. This produces an - // antialiased alpha mask of the mesh shape, in the - // destination alpha channel. - glEnableClientState(GL_VERTEX_ARRAY); - glVertexPointer(2, GL_SHORT, sizeof(Sint16) * 2, coords); - glDrawArrays(GL_TRIANGLE_STRIP, 0, vertex_count); - glDisableClientState(GL_VERTEX_ARRAY); - - glPopMatrix(); - - // Set up desired fill style. - m_current_styles[LEFT_STYLE].apply(); - - // Apply fill, modulated with alpha mask. - // - // @@ TODO see note above about filling bounding box only. - glBlendFunc(GL_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA); - glBegin(GL_QUADS); - glVertex2f(0, 0); - glVertex2f(100000, 0); - glVertex2f(100000, 100000); - glVertex2f(0, 100000); - glEnd(); - -// xxxxx ??? Hm, is our mask still intact, or did we just erase it? -// if (m_current_styles[LEFT_STYLE].needs_second_pass()) -// { -// m_current_styles[LEFT_STYLE].apply_second_pass(); -// glDrawArrays(GL_TRIANGLE_STRIP, 0, vertex_count); -// m_current_styles[LEFT_STYLE].cleanup_second_pass(); -// } - - // @@ hm, there is perhaps more state that needs - // fixing here, or setting elsewhere. - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); -#endif // MULTIPASS_ANTIALIASING - } - - - void draw_line_strip(const void* coords, int vertex_count) - // Draw the line strip formed by the sequence of points. - { - // Set up current style. - m_current_styles[LINE_STYLE].apply(); - - glMatrixMode(GL_MODELVIEW); - glPushMatrix(); - apply_matrix(m_current_matrix); - - // Send the line-strip to OpenGL - glEnableClientState(GL_VERTEX_ARRAY); - glVertexPointer(2, GL_SHORT, sizeof(Sint16) * 2, coords); - glDrawArrays(GL_LINE_STRIP, 0, vertex_count); - glDisableClientState(GL_VERTEX_ARRAY); - - glPopMatrix(); - } - - - void draw_bitmap( - const gameswf::matrix& m, - const gameswf::bitmap_info* bi, - const gameswf::rect& coords, - const gameswf::rect& uv_coords, - gameswf::rgba color) - // Draw a rectangle textured with the given bitmap, with the - // given color. Apply given transform; ignore any currently - // set transforms. - // - // Intended for textured glyph rendering. - { - assert(bi); - - apply_color(color); - - gameswf::point a, b, c, d; - m.transform(&a, gameswf::point(coords.m_x_min, coords.m_y_min)); - m.transform(&b, gameswf::point(coords.m_x_max, coords.m_y_min)); - m.transform(&c, gameswf::point(coords.m_x_min, coords.m_y_max)); - d.m_x = b.m_x + c.m_x - a.m_x; - d.m_y = b.m_y + c.m_y - a.m_y; - - glBindTexture(GL_TEXTURE_2D, bi->m_texture_id); - glEnable(GL_TEXTURE_2D); - glDisable(GL_TEXTURE_GEN_S); - glDisable(GL_TEXTURE_GEN_T); - - glBegin(GL_TRIANGLE_STRIP); - - glTexCoord2f(uv_coords.m_x_min, uv_coords.m_y_min); - glVertex2f(a.m_x, a.m_y); - - glTexCoord2f(uv_coords.m_x_max, uv_coords.m_y_min); - glVertex2f(b.m_x, b.m_y); - - glTexCoord2f(uv_coords.m_x_min, uv_coords.m_y_max); - glVertex2f(c.m_x, c.m_y); - - glTexCoord2f(uv_coords.m_x_max, uv_coords.m_y_max); - glVertex2f(d.m_x, d.m_y); - - glEnd(); - } - - void begin_submit_mask() - { - glEnable(GL_STENCIL_TEST); - glClearStencil(0); - glClear(GL_STENCIL_BUFFER_BIT); - glColorMask(0,0,0,0); // disable framebuffer writes - glEnable(GL_STENCIL_TEST); // enable stencil buffer for "marking" the mask - glStencilFunc(GL_ALWAYS, 1, 1); // always passes, 1 bit plane, 1 as mask - glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); // we set the stencil buffer to 1 where we draw any polygon - // keep if test fails, keep if test passes but buffer test fails - // replace if test passes - } - - void end_submit_mask() - { - glColorMask(1,1,1,1); // enable framebuffer writes - glStencilFunc(GL_EQUAL, 1, 1); // we draw only where the stencil is 1 (where the mask was drawn) - glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); // don't change the stencil buffer - } - - void disable_mask() - { - glDisable(GL_STENCIL_TEST); - } - -}; // end struct render_handler_ogl - - -// bitmap_info_ogl implementation - - - -void hardware_resample(int bytes_per_pixel, int src_width, int src_height, uint8* src_data, int dst_width, int dst_height) -// Code from Alex Streit -// -// Sets the current texture to a resampled/expanded version of the -// given image data. -{ - assert(bytes_per_pixel == 3 || bytes_per_pixel == 4); - - unsigned int in_format = bytes_per_pixel == 3 ? GL_RGB : GL_RGBA; - unsigned int out_format = bytes_per_pixel == 3 ? GL_RGB : GL_RGBA; - - // alex: use the hardware to resample the image - // issue: does not work when image > allocated window size! - glMatrixMode(GL_PROJECTION); - glPushMatrix(); - glMatrixMode(GL_MODELVIEW); - glPushMatrix(); - glPushAttrib(GL_TEXTURE_BIT | GL_ENABLE_BIT); - { - char* temp = new char[dst_width * dst_height * bytes_per_pixel]; - //memset(temp,255,w*h*3); - glTexImage2D(GL_TEXTURE_2D, 0, in_format, dst_width, dst_height, 0, out_format, GL_UNSIGNED_BYTE, temp); - glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, src_width, src_height, out_format, GL_UNSIGNED_BYTE, src_data); - - glLoadIdentity(); - glViewport(0, 0, dst_width, dst_height); - glOrtho(0, dst_width, 0, dst_height, 0.9, 1.1); - glColor3f(1, 1, 1); - glNormal3f(0, 0, 1); - glBegin(GL_QUADS); - { - glTexCoord2f(0, (float) src_height / dst_height); - glVertex3f(0, 0, -1); - glTexCoord2f( (float) src_width / dst_width, (float) src_height / dst_height); - glVertex3f((float) dst_width, 0, -1); - glTexCoord2f( (float) src_width / dst_width, 0); - glVertex3f((float) dst_width, (float) dst_height, -1); - glTexCoord2f(0, 0); - glVertex3f(0, (float) dst_height, -1); - } - glEnd(); - glCopyTexImage2D(GL_TEXTURE_2D, 0, out_format, 0,0, dst_width, dst_height, 0); - delete temp; - } - glPopAttrib(); - glPopMatrix(); - glPopMatrix(); -} - - -void generate_mipmaps(unsigned int internal_format, unsigned int input_format, int bytes_per_pixel, image::image_base* im) -// DESTRUCTIVELY generate mipmaps of the given image. The image data -// and width/height of im are munged in this process. -{ - int level = 1; - while (im->m_width > 1 || im->m_height > 1) - { - if (bytes_per_pixel == 3) - { - image::make_next_miplevel((image::rgb*) im); - } - else - { - image::make_next_miplevel((image::rgba*) im); - } - - glTexImage2D(GL_TEXTURE_2D, level, internal_format, im->m_width, im->m_height, 0, - input_format, GL_UNSIGNED_BYTE, im->m_data); - level++; - } -} - - -void software_resample( - int bytes_per_pixel, - int src_width, - int src_height, - int src_pitch, - uint8* src_data, - int dst_width, - int dst_height) -// Code from Alex Streit -// -// Creates an OpenGL texture of the specified dst dimensions, from a -// resampled version of the given src image. Does a bilinear -// resampling to create the dst image. -{ - assert(bytes_per_pixel == 3 || bytes_per_pixel == 4); - - assert(dst_width >= src_width); - assert(dst_height >= src_height); - - unsigned int internal_format = bytes_per_pixel == 3 ? GL_RGB : GL_RGBA; - unsigned int input_format = bytes_per_pixel == 3 ? GL_RGB : GL_RGBA; - - // FAST bi-linear filtering - // the code here is designed to be fast, not readable - Uint8* rescaled = new Uint8[dst_width * dst_height * bytes_per_pixel]; - float Uf, Vf; // fractional parts - float Ui, Vi; // integral parts - float w1, w2, w3, w4; // weighting - Uint8* psrc; - Uint8* pdst = rescaled; - // i1,i2,i3,i4 are the offsets of the surrounding 4 pixels - const int i1 = 0; - const int i2 = bytes_per_pixel; - int i3 = src_pitch; - int i4 = src_pitch + bytes_per_pixel; - // change in source u and v - float dv = (float)(src_height-2) / dst_height; - float du = (float)(src_width-2) / dst_width; - // source u and source v - float U; - float V=0; - -#define BYTE_SAMPLE(offset) \ - (Uint8) (w1 * psrc[i1 + (offset)] + w2 * psrc[i2 + (offset)] + w3 * psrc[i3 + (offset)] + w4 * psrc[i4 + (offset)]) - - if (bytes_per_pixel == 3) - { - for (int v = 0; v < dst_height; ++v) - { - Vf = modff(V, &Vi); - V+=dv; - U=0; - - for (int u = 0; u < dst_width; ++u) - { - Uf = modff(U, &Ui); - U+=du; - - w1 = (1 - Uf) * (1 - Vf); - w2 = Uf * (1 - Vf); - w3 = (1 - Uf) * Vf; - w4 = Uf * Vf; - psrc = &src_data[(int) (Vi * src_pitch) + (int) (Ui * bytes_per_pixel)]; - - *pdst++ = BYTE_SAMPLE(0); // red - *pdst++ = BYTE_SAMPLE(1); // green - *pdst++ = BYTE_SAMPLE(2); // blue - - psrc += 3; - } - } - -#ifdef DEBUG_WRITE_TEXTURES_TO_PPM - static int s_image_sequence = 0; - char temp[256]; - sprintf(temp, "image%d.ppm", s_image_sequence++); - FILE* f = fopen(temp, "wb"); - if (f) - { - fprintf(f, "P6\n# test code\n%d %d\n255\n", dst_width, dst_height); - fwrite(rescaled, dst_width * dst_height * 3, 1, f); - fclose(f); - } -#endif - } - else - { - assert(bytes_per_pixel == 4); - - for (int v = 0; v < dst_height; ++v) - { - Vf = modff(V, &Vi); - V+=dv; - U=0; - - for (int u = 0; u < dst_width; ++u) - { - Uf = modff(U, &Ui); - U+=du; - - w1 = (1 - Uf) * (1 - Vf); - w2 = Uf * (1 - Vf); - w3 = (1 - Uf) * Vf; - w4 = Uf * Vf; - psrc = &src_data[(int) (Vi * src_pitch) + (int) (Ui * bytes_per_pixel)]; - - *pdst++ = BYTE_SAMPLE(0); // red - *pdst++ = BYTE_SAMPLE(1); // green - *pdst++ = BYTE_SAMPLE(2); // blue - *pdst++ = BYTE_SAMPLE(3); // alpha - - psrc += 4; - } - } - } - - glTexImage2D(GL_TEXTURE_2D, 0, internal_format, dst_width, dst_height, 0, input_format, GL_UNSIGNED_BYTE, rescaled); - -#if GENERATE_MIPMAPS - // Build mipmaps. - image::image_base im(rescaled, dst_width, dst_height, dst_width * bytes_per_pixel); - generate_mipmaps(internal_format, input_format, bytes_per_pixel, &im); -#endif // GENERATE_MIPMAPS - - delete [] rescaled; -} - - -bitmap_info_ogl::bitmap_info_ogl() -// Make a placeholder bitmap_info. Must be filled in later before -// using. -{ - m_texture_id = 0; - m_original_width = 0; - m_original_height = 0; -} - - -bitmap_info_ogl::bitmap_info_ogl(int width, int height, Uint8* data) -// Initialize this bitmap_info to an alpha image -// containing the specified data (1 byte per texel). -// -// !! Munges *data in order to create mipmaps !! -{ - assert(width > 0); - assert(height > 0); - assert(data); - - m_texture_id = 0; - - // Create the texture. - - glEnable(GL_TEXTURE_2D); - glGenTextures(1, (GLuint*)&m_texture_id); - glBindTexture(GL_TEXTURE_2D, m_texture_id); - - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // GL_NEAREST ? - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); - - m_original_width = width; - m_original_height = height; - - #ifndef NDEBUG - // You must use power-of-two dimensions!! - int w = 1; while (w < width) { w <<= 1; } - int h = 1; while (h < height) { h <<= 1; } - assert(w == width); - assert(h == height); - #endif // not NDEBUG - - glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, data); - - // Build mips. - int level = 1; - while (width > 1 || height > 1) - { - render_handler_ogl::make_next_miplevel(&width, &height, data); - glTexImage2D(GL_TEXTURE_2D, level, GL_ALPHA, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, data); - level++; - } -} - - -bitmap_info_ogl::bitmap_info_ogl(image::rgb* im) -// NOTE: This function destroys im's data in the process of making mipmaps. -{ - assert(im); - - // Create the texture. - - glEnable(GL_TEXTURE_2D); - glGenTextures(1, (GLuint*)&m_texture_id); - glBindTexture(GL_TEXTURE_2D, m_texture_id); - - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); -#if GENERATE_MIPMAPS - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); -#else - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); -#endif - - m_original_width = im->m_width; - m_original_height = im->m_height; - - int w = 1; while (w < im->m_width) { w <<= 1; } - int h = 1; while (h < im->m_height) { h <<= 1; } - - if (w != im->m_width - || h != im->m_height) - { -#if (RESAMPLE_METHOD == 1) - int viewport_dim[2] = { 0, 0 }; - glGetIntegerv(GL_MAX_VIEWPORT_DIMS, &viewport_dim[0]); - if (w > viewport_dim[0] - || h > viewport_dim[1] - || im->m_width * 3 != im->m_pitch) - { - // Can't use hardware resample. Either frame - // buffer isn't big enough to fit the source - // texture, or the source data isn't padded - // quite right. - software_resample(3, im->m_width, im->m_height, im->m_pitch, im->m_data, w, h); - } - else - { - hardware_resample(3, im->m_width, im->m_height, im->m_data, w, h); - } -#elif (RESAMPLE_METHOD == 2) - { - // Faster/simpler software bilinear rescale. - software_resample(3, im->m_width, im->m_height, im->m_pitch, im->m_data, w, h); - } -#else - { - // Fancy but slow software resampling. - image::rgb* rescaled = image::create_rgb(w, h); - image::resample(rescaled, 0, 0, w - 1, h - 1, - im, 0, 0, (float) im->m_width, (float) im->m_height); - - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, rescaled->m_data); -#if GENERATE_MIPMAPS - generate_mipmaps(GL_RGB, GL_RGB, 3, rescaled); -#endif // GENERATE_MIPMAPS - - delete rescaled; - } -#endif - } - else - { - // Use original image directly. - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, im->m_data); -#if GENERATE_MIPMAPS - generate_mipmaps(GL_RGB, GL_RGB, 3, im); -#endif // GENERATE_MIPMAPS - } -} - - -bitmap_info_ogl::bitmap_info_ogl(image::rgba* im) -// Version of the constructor that takes an image with alpha. -// NOTE: This function destroys im's data in the process of making mipmaps. -{ - assert(im); - - // Create the texture. - - glEnable(GL_TEXTURE_2D); - glGenTextures(1, (GLuint*)&m_texture_id); - glBindTexture(GL_TEXTURE_2D, m_texture_id); - - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // GL_NEAREST ? -#if GENERATE_MIPMAPS - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); -#else - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); -#endif - - m_original_width = im->m_width; - m_original_height = im->m_height; - - int w = 1; while (w < im->m_width) { w <<= 1; } - int h = 1; while (h < im->m_height) { h <<= 1; } - - if (w != im->m_width - || h != im->m_height) - { -#if (RESAMPLE_METHOD == 1) - int viewport_dim[2] = { 0, 0 }; - glGetIntegerv(GL_MAX_VIEWPORT_DIMS, &viewport_dim[0]); - if (w > viewport_dim[0] - || h > viewport_dim[1] - || im->m_width * 4 != im->m_pitch) - { - // Can't use hardware resample. Either frame - // buffer isn't big enough to fit the source - // texture, or the source data isn't padded - // quite right. - software_resample(4, im->m_width, im->m_height, im->m_pitch, im->m_data, w, h); - } - else - { - hardware_resample(4, im->m_width, im->m_height, im->m_data, w, h); - } -#elif (RESAMPLE_METHOD == 2) - { - // Faster/simpler software bilinear rescale. - software_resample(4, im->m_width, im->m_height, im->m_pitch, im->m_data, w, h); - } -#else - { - // Fancy but slow software resampling. - image::rgba* rescaled = image::create_rgba(w, h); - image::resample(rescaled, 0, 0, w - 1, h - 1, - im, 0, 0, (float) im->m_width, (float) im->m_height); - - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, rescaled->m_data); -#if GENERATE_MIPMAPS - generate_mipmaps(GL_RGBA, GL_RGBA, 4, rescaled); -#endif // GENERATE_MIPMAPS - - delete rescaled; - } -#endif - } - else - { - // Use original image directly. - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, im->m_data); -#if GENERATE_MIPMAPS - generate_mipmaps(GL_RGBA, GL_RGBA, 4, im); -#endif // GENERATE_MIPMAPS - } -} - - -gameswf::render_handler* gameswf::create_render_handler_ogl() -// Factory. -{ - return new render_handler_ogl; -} - - -// Local Variables: -// mode: C++ -// c-basic-offset: 8 -// tab-width: 8 -// indent-tabs-mode: t -// End: diff --git a/Code/BF2/External/gameswf/gameswf_render_handler_xbox.cpp b/Code/BF2/External/gameswf/gameswf_render_handler_xbox.cpp deleted file mode 100644 index 444c955e5..000000000 --- a/Code/BF2/External/gameswf/gameswf_render_handler_xbox.cpp +++ /dev/null @@ -1,1205 +0,0 @@ -// gameswf_render_handler_xbox.cpp -- Thatcher Ulrich 2003 - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - -// A gameswf::render_handler that uses Xbox API's - - -#ifdef _XBOX - -#include "gameswf.h" -#include "gameswf/gameswf_log.h" -#include "gameswf_types.h" -#include "base/image.h" -#include "base/container.h" - -#include -#include - -#include - - -namespace -{ - array s_d3d_textures; - DWORD s_vshader_handle = 0; - - // Our vertex coords consist of two signed 16-bit integers, for (x,y) position only. - DWORD s_vshader_decl[] = - { - D3DVSD_STREAM(0), - D3DVSD_REG(0, D3DVSDT_SHORT2), - 0xFFFFFFFF - }; - - - void init_vshader() - // Initialize the vshader we use for SWF mesh rendering. - { - if (s_vshader_handle == 0) - { - HRESULT result; - - /* Shader source: - - xvs.1.1 - #pragma screenspace - mov oD0, v3 - dp4 oPos.x, v0, c[0] // Transform position - dp4 oPos.y, v0, c[1] - dp4 oPos.z, v0, c[2] - dp4 oPos.w, v0, c[3] - dp4 oT0.x, v0, c[4] // texgen - dp4 oT0.y, v0, c[5] - - Compile that with xsasm -h sometmp.vsh, and insert the contents of sometmp.h below: - */ - static const DWORD s_compiled_shader[] = - { - 0x00072078, - 0x00000000, 0x0020061b, 0x0836106c, 0x2070f818, - 0x00000000, 0x00ec001b, 0x0836186c, 0x20708800, - 0x00000000, 0x00ec201b, 0x0836186c, 0x20704800, - 0x00000000, 0x00ec401b, 0x0836186c, 0x20702800, - 0x00000000, 0x00ec601b, 0x0836186c, 0x20701800, - 0x00000000, 0x00ec801b, 0x0836186c, 0x20708848, - 0x00000000, 0x00eca01b, 0x0836186c, 0x20704849 - }; - - result = IDirect3DDevice8::CreateVertexShader( - s_vshader_decl, - s_compiled_shader, - &s_vshader_handle, - D3DUSAGE_PERSISTENTDIFFUSE); - if (result != S_OK) - { - gameswf::log_error("error: can't create Xbox vshader; error code = %d\n", result); - return; - } - } - } -}; - - -// bitmap_info_xbox declaration -struct bitmap_info_xbox : public gameswf::bitmap_info -{ - bitmap_info_xbox(create_empty e); - bitmap_info_xbox(image::rgb* im); - bitmap_info_xbox(image::rgba* im); - virtual void set_alpha_image(int width, int height, Uint8* data); -}; - - -struct render_handler_xbox : public gameswf::render_handler -{ - // Some renderer state. - - gameswf::matrix m_viewport_matrix; - gameswf::matrix m_current_matrix; - gameswf::cxform m_current_cxform; - - void set_antialiased(bool enable) - { - // not supported - } - - static void make_next_miplevel(int* width, int* height, Uint8* data) - // Utility. Mutates *width, *height and *data to create the - // next mip level. - { - assert(width); - assert(height); - assert(data); - - int new_w = *width >> 1; - int new_h = *height >> 1; - if (new_w < 1) new_w = 1; - if (new_h < 1) new_h = 1; - - if (new_w * 2 != *width || new_h * 2 != *height) - { - // Image can't be shrunk along (at least) one - // of its dimensions, so don't bother - // resampling. Technically we should, but - // it's pretty useless at this point. Just - // change the image dimensions and leave the - // existing pixels. - } - else - { - // Resample. Simple average 2x2 --> 1, in-place. - for (int j = 0; j < new_h; j++) { - Uint8* out = ((Uint8*) data) + j * new_w; - Uint8* in = ((Uint8*) data) + (j << 1) * *width; - for (int i = 0; i < new_w; i++) { - int a; - a = (*(in + 0) + *(in + 1) + *(in + 0 + *width) + *(in + 1 + *width)); - *(out) = (Uint8) (a >> 2); - out++; - in += 2; - } - } - } - - // Munge parameters to reflect the shrunken image. - *width = new_w; - *height = new_h; - } - - struct fill_style - { - enum mode - { - INVALID, - COLOR, - BITMAP_WRAP, - BITMAP_CLAMP, - LINEAR_GRADIENT, - RADIAL_GRADIENT, - }; - mode m_mode; - gameswf::rgba m_color; - const gameswf::bitmap_info* m_bitmap_info; - gameswf::matrix m_bitmap_matrix; - gameswf::cxform m_bitmap_color_transform; - bool m_has_nonzero_bitmap_additive_color; - - fill_style() - : - m_mode(INVALID), - m_has_nonzero_bitmap_additive_color(false) - { - } - - void apply(/*const matrix& current_matrix*/) const - // Push our style into D3D. - { - assert(m_mode != INVALID); - - if (m_mode == COLOR) - { - apply_color(m_color); - IDirect3DDevice8::SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_DISABLE); - //IDirect3DDevice8::SetRenderState(state, value); -// glDisable(GL_TEXTURE_2D); - } - else if (m_mode == BITMAP_WRAP - || m_mode == BITMAP_CLAMP) - { - assert(m_bitmap_info != NULL); - - apply_color(m_color); - - if (m_bitmap_info == NULL) - { - IDirect3DDevice8::SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_DISABLE); - //glDisable(GL_TEXTURE_2D); - } - else - { - // Set up the texture for rendering. - - { - // Do the modulate part of the color - // transform in the first pass. The - // additive part, if any, needs to - // happen in a second pass. -// glColor4f(m_bitmap_color_transform.m_[0][0], -// m_bitmap_color_transform.m_[1][0], -// m_bitmap_color_transform.m_[2][0], -// m_bitmap_color_transform.m_[3][0] -// ); - IDirect3DDevice8::SetVertexData4f( - D3DVSDE_DIFFUSE, - m_bitmap_color_transform.m_[0][0], - m_bitmap_color_transform.m_[1][0], - m_bitmap_color_transform.m_[2][0], - m_bitmap_color_transform.m_[3][0]); - } - -// glBindTexture(GL_TEXTURE_2D, m_bitmap_info->m_texture_id); -// glEnable(GL_TEXTURE_2D); -// glEnable(GL_TEXTURE_GEN_S); -// glEnable(GL_TEXTURE_GEN_T); - IDirect3DDevice8::SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE); - IDirect3DDevice8::SetTexture(0, s_d3d_textures[m_bitmap_info->m_texture_id]); - - if (m_mode == BITMAP_CLAMP) - { -// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); -// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - IDirect3DDevice8::SetTextureStageState(0, D3DTSS_ADDRESSU, D3DTADDRESS_CLAMP); - IDirect3DDevice8::SetTextureStageState(0, D3DTSS_ADDRESSV, D3DTADDRESS_CLAMP); - } - else - { - assert(m_mode == BITMAP_WRAP); -// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); -// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - IDirect3DDevice8::SetTextureStageState(0, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP); - IDirect3DDevice8::SetTextureStageState(0, D3DTSS_ADDRESSV, D3DTADDRESS_WRAP); - } - - // Set up the bitmap matrix for texgen. - float inv_width = 1.0f / m_bitmap_info->m_original_width; - float inv_height = 1.0f / m_bitmap_info->m_original_height; - - const gameswf::matrix& m = m_bitmap_matrix; -// glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); - float p[4] = { 0, 0, 0, 0 }; - p[0] = m.m_[0][0] * inv_width; - p[1] = m.m_[0][1] * inv_width; - p[3] = m.m_[0][2] * inv_width; -// glTexGenfv(GL_S, GL_OBJECT_PLANE, p); - IDirect3DDevice8::SetVertexShaderConstant(4, p, 1); - - -// glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); - p[0] = m.m_[1][0] * inv_height; - p[1] = m.m_[1][1] * inv_height; - p[3] = m.m_[1][2] * inv_height; -// glTexGenfv(GL_T, GL_OBJECT_PLANE, p); - IDirect3DDevice8::SetVertexShaderConstant(5, p, 1); - } - } - } - - - bool needs_second_pass() const - // Return true if we need to do a second pass to make - // a valid color. This is for cxforms with additive - // parts. - { - if (m_mode == BITMAP_WRAP - || m_mode == BITMAP_CLAMP) - { - return m_has_nonzero_bitmap_additive_color; - } - else - { - return false; - } - } - - void apply_second_pass() const - // Set D3D state for a necessary second pass. - { - assert(needs_second_pass()); - - // Additive color. - IDirect3DDevice8::SetVertexData4f( - D3DVSDE_DIFFUSE, - m_bitmap_color_transform.m_[0][1] / 255.0f, - m_bitmap_color_transform.m_[1][1] / 255.0f, - m_bitmap_color_transform.m_[2][1] / 255.0f, - m_bitmap_color_transform.m_[3][1] / 255.0f - ); - - IDirect3DDevice8::SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE); - IDirect3DDevice8::SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE); - -#if 0 - glDisable(GL_TEXTURE_2D); - glColor4f( - m_bitmap_color_transform.m_[0][1] / 255.0f, - m_bitmap_color_transform.m_[1][1] / 255.0f, - m_bitmap_color_transform.m_[2][1] / 255.0f, - m_bitmap_color_transform.m_[3][1] / 255.0f - ); - - glBlendFunc(GL_ONE, GL_ONE); -#endif // 0 - } - - void cleanup_second_pass() const - { - IDirect3DDevice8::SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); - IDirect3DDevice8::SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); - -#if 0 - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); -#endif // 0 - } - - - void disable() { m_mode = INVALID; } - void set_color(gameswf::rgba color) { m_mode = COLOR; m_color = color; } - void set_bitmap(const gameswf::bitmap_info* bi, const gameswf::matrix& m, bitmap_wrap_mode wm, const gameswf::cxform& color_transform) - { - m_mode = (wm == WRAP_REPEAT) ? BITMAP_WRAP : BITMAP_CLAMP; - m_color = gameswf::rgba(); - m_bitmap_info = bi; - m_bitmap_matrix = m; - m_bitmap_color_transform = color_transform; - - if (m_bitmap_color_transform.m_[0][1] > 1.0f - || m_bitmap_color_transform.m_[1][1] > 1.0f - || m_bitmap_color_transform.m_[2][1] > 1.0f - || m_bitmap_color_transform.m_[3][1] > 1.0f) - { - m_has_nonzero_bitmap_additive_color = true; - } - else - { - m_has_nonzero_bitmap_additive_color = false; - } - } - bool is_valid() const { return m_mode != INVALID; } - }; - - - render_handler_xbox() - // Constructor. - { - init_vshader(); - } - - - // Style state. - enum style_index - { - LEFT_STYLE = 0, - RIGHT_STYLE, - LINE_STYLE, - - STYLE_COUNT - }; - fill_style m_current_styles[STYLE_COUNT]; - - - gameswf::bitmap_info* create_bitmap_info(image::rgb* im) - // Given an image, returns a pointer to a bitmap_info struct - // that can later be passed to fill_styleX_bitmap(), to set a - // bitmap fill style. - { - return new bitmap_info_xbox(im); - } - - - gameswf::bitmap_info* create_bitmap_info(image::rgba* im) - // Given an image, returns a pointer to a bitmap_info struct - // that can later be passed to fill_style_bitmap(), to set a - // bitmap fill style. - // - // This version takes an image with an alpha channel. - { - return new bitmap_info_xbox(im); - } - - - gameswf::bitmap_info* create_bitmap_info_blank() - // Creates and returns an empty bitmap_info structure. Image data - // can be bound to this info later, via set_alpha_image(). - { - return new bitmap_info_xbox(gameswf::bitmap_info::empty); - } - - - void set_alpha_image(gameswf::bitmap_info* bi, int w, int h, Uint8* data) - // Set the specified bitmap_info so that it contains an alpha - // texture with the given data (1 byte per texel). - // - // Munges *data (in order to make mipmaps)!! - { - assert(bi); - - bi->set_alpha_image(w, h, data); - } - - - void delete_bitmap_info(gameswf::bitmap_info* bi) - // Delete the given bitmap info struct. - { - delete bi; - } - - - void begin_display( - gameswf::rgba background_color, - int viewport_x0, int viewport_y0, - int viewport_width, int viewport_height, - float x0, float x1, float y0, float y1) - // Set up to render a full frame from a movie and fills the - // background. Sets up necessary transforms, to scale the - // movie to fit within the given dimensions. Call - // end_display() when you're done. - // - // The rectangle (viewport_x0, viewport_y0, viewport_x0 + - // viewport_width, viewport_y0 + viewport_height) defines the - // window coordinates taken up by the movie. - // - // The rectangle (x0, y0, x1, y1) defines the pixel - // coordinates of the movie that correspond to the viewport - // bounds. - { -// // Matrix setup -// D3DXMATRIX ortho; -// D3DXMatrixOrthoOffCenterRH(&ortho, x0, x1, y0, y1, 0.0f, 1.0f); -// IDirect3DDevice8::SetTransform(D3DTS_PROJECTION, &ortho); - -// D3DXMATRIX ident; -// D3DXMatrixIdentity(&ident); -// IDirect3DDevice8::SetTransform(D3DTS_VIEW, &ident); -// // IDirect3DDevice8::SetTransform(D3DTS_WORLD, &ident); -// // etc.? - - // Viewport. - D3DVIEWPORT8 vp; - vp.X = viewport_x0; - vp.Y = viewport_y0; - vp.Width = viewport_width; - vp.Height = viewport_height; - vp.MinZ = 0.0f; - vp.MaxZ = 0.0f; - IDirect3DDevice8::SetViewport(&vp); - - // Matrix to map from SWF movie (TWIPs) coords to - // viewport coordinates. - float dx = x1 - x0; - float dy = y1 - y0; - if (dx < 1) { dx = 1; } - if (dy < 1) { dy = 1; } - m_viewport_matrix.set_identity(); - m_viewport_matrix.m_[0][0] = viewport_width / dx; - m_viewport_matrix.m_[1][1] = viewport_height / dy; - m_viewport_matrix.m_[0][2] = viewport_x0 - m_viewport_matrix.m_[0][0] * x0; - m_viewport_matrix.m_[1][2] = viewport_y0 - m_viewport_matrix.m_[1][1] * y0; - - // Blending renderstates - IDirect3DDevice8::SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); - IDirect3DDevice8::SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); - IDirect3DDevice8::SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); - - // Textures off by default. - IDirect3DDevice8::SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_DISABLE); - - // @@ for sanity's sake, let's turn of backface culling... - IDirect3DDevice8::SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);//xxxxx - IDirect3DDevice8::SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS); //xxxxx - - // Vertex format. - IDirect3DDevice8::SetVertexShader(s_vshader_handle); - - // No pixel shader. - IDirect3DDevice8::SetPixelShaderProgram(NULL); - -#if 0 - glViewport(viewport_x0, viewport_y0, viewport_width, viewport_height); - - glMatrixMode(GL_MODELVIEW); - glPushMatrix(); - glOrtho(x0, x1, y0, y1, -1, 1); - - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - - glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); // GL_MODULATE - - glDisable(GL_TEXTURE_2D); -#endif // 0 - - // Clear the background, if background color has alpha > 0. - if (background_color.m_a > 0) - { - // @@ for testing - static int bobo = 0; - IDirect3DDevice8::Clear( - 0, - NULL, - D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL, - bobo += 5, - 0.0f, - 0); - - // Draw a big quad. - apply_color(background_color); - set_matrix(gameswf::matrix::identity); - apply_matrix(m_current_matrix); - - IDirect3DDevice8::Begin(D3DPT_TRIANGLESTRIP); - IDirect3DDevice8::SetVertexData2f(D3DVSDE_POSITION, x0, y0); - IDirect3DDevice8::SetVertexData2f(D3DVSDE_POSITION, x1, y0); - IDirect3DDevice8::SetVertexData2f(D3DVSDE_POSITION, x1, y1); - IDirect3DDevice8::SetVertexData2f(D3DVSDE_POSITION, x0, y1); - IDirect3DDevice8::End(); - -#if 0 - glBegin(GL_QUADS); - glVertex2f(x0, y0); - glVertex2f(x1, y0); - glVertex2f(x1, y1); - glVertex2f(x0, y1); - glEnd(); -#endif // 0 - } - } - - - void end_display() - // Clean up after rendering a frame. Client program is still - // responsible for calling glSwapBuffers() or whatever. - { -#if 0 - glMatrixMode(GL_MODELVIEW); - glPopMatrix(); -#endif // 0 - } - - - void set_matrix(const gameswf::matrix& m) - // Set the current transform for mesh & line-strip rendering. - { - m_current_matrix = m; - } - - - void set_cxform(const gameswf::cxform& cx) - // Set the current color transform for mesh & line-strip rendering. - { - m_current_cxform = cx; - } - - void apply_matrix(const gameswf::matrix& mat_in) - // Set the given transformation matrix. - { - gameswf::matrix m(m_viewport_matrix); - m.concatenate(mat_in); - - float row0[4]; - float row1[4]; - row0[0] = m.m_[0][0]; - row0[1] = m.m_[0][1]; - row0[2] = 0; - row0[3] = m.m_[0][2]; - - row1[0] = m.m_[1][0]; - row1[1] = m.m_[1][1]; - row1[2] = 0; - row1[3] = m.m_[1][2]; - -// glMultMatrixf(mat); -// IDirect3DDevice8::SetTransform(D3DTS_VIEW, (D3DMATRIX*) &mat[0]); - IDirect3DDevice8::SetVertexShaderConstant(0, row0, 1); - IDirect3DDevice8::SetVertexShaderConstant(1, row1, 1); - } - - static void apply_color(const gameswf::rgba& c) - // Set the given color. - { -// glColor4ub(c.m_r, c.m_g, c.m_b, c.m_a); - IDirect3DDevice8::SetVertexData4ub(D3DVSDE_DIFFUSE, c.m_r, c.m_g, c.m_b, c.m_a); - } - - void fill_style_disable(int fill_side) - // Don't fill on the {0 == left, 1 == right} side of a path. - { - assert(fill_side >= 0 && fill_side < 2); - - m_current_styles[fill_side].disable(); - } - - - void line_style_disable() - // Don't draw a line on this path. - { - m_current_styles[LINE_STYLE].disable(); - } - - - void fill_style_color(int fill_side, gameswf::rgba color) - // Set fill style for the left interior of the shape. If - // enable is false, turn off fill for the left interior. - { - assert(fill_side >= 0 && fill_side < 2); - - m_current_styles[fill_side].set_color(m_current_cxform.transform(color)); - } - - - void line_style_color(gameswf::rgba color) - // Set the line style of the shape. If enable is false, turn - // off lines for following curve segments. - { - m_current_styles[LINE_STYLE].set_color(m_current_cxform.transform(color)); - } - - - void fill_style_bitmap(int fill_side, const gameswf::bitmap_info* bi, const gameswf::matrix& m, bitmap_wrap_mode wm) - { - assert(fill_side >= 0 && fill_side < 2); - m_current_styles[fill_side].set_bitmap(bi, m, wm, m_current_cxform); - } - - void line_style_width(float width) - { - // WK: what to do here??? - } - - - void draw_mesh_strip(const void* coords, int vertex_count) - { - // Set up current style. - m_current_styles[LEFT_STYLE].apply(); - - apply_matrix(m_current_matrix); - - // @@ we'd like to use a VB instead, and use DrawPrimitive(). - - // Draw the mesh. - IDirect3DDevice8::DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, vertex_count - 2, coords, sizeof(Sint16) * 2); - - if (m_current_styles[LEFT_STYLE].needs_second_pass()) - { - // 2nd pass, if necessary. - m_current_styles[LEFT_STYLE].apply_second_pass(); - IDirect3DDevice8::DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, vertex_count - 2, coords, sizeof(Sint16) * 2); - m_current_styles[LEFT_STYLE].cleanup_second_pass(); - } - -#if 0 - glMatrixMode(GL_MODELVIEW); - glPushMatrix(); - apply_matrix(m_current_matrix); - - // Send the tris to OpenGL - glEnableClientState(GL_VERTEX_ARRAY); - glVertexPointer(2, GL_SHORT, sizeof(Sint16) * 2, coords); - glDrawArrays(GL_TRIANGLE_STRIP, 0, vertex_count); - - if (m_current_styles[LEFT_STYLE].needs_second_pass()) - { - m_current_styles[LEFT_STYLE].apply_second_pass(); - glDrawArrays(GL_TRIANGLE_STRIP, 0, vertex_count); - m_current_styles[LEFT_STYLE].cleanup_second_pass(); - } - - glDisableClientState(GL_VERTEX_ARRAY); - - glPopMatrix(); -#endif // 0 - } - - - void draw_line_strip(const void* coords, int vertex_count) - // Draw the line strip formed by the sequence of points. - { - // Set up current style. - m_current_styles[LINE_STYLE].apply(); - - apply_matrix(m_current_matrix); - - IDirect3DDevice8::DrawPrimitiveUP(D3DPT_LINESTRIP, vertex_count - 1, coords, sizeof(Sint16) * 2); - } - - - void draw_bitmap( - const gameswf::matrix& m, - const gameswf::bitmap_info* bi, - const gameswf::rect& coords, - const gameswf::rect& uv_coords, - gameswf::rgba color) - // Draw a rectangle textured with the given bitmap, with the - // given color. Apply given transform; ignore any currently - // set transforms. - // - // Intended for textured glyph rendering. - { - assert(bi); - - apply_color(color); - - gameswf::point a, b, c, d; - m.transform(&a, gameswf::point(coords.m_x_min, coords.m_y_min)); - m.transform(&b, gameswf::point(coords.m_x_max, coords.m_y_min)); - m.transform(&c, gameswf::point(coords.m_x_min, coords.m_y_max)); - d.m_x = b.m_x + c.m_x - a.m_x; - d.m_y = b.m_y + c.m_y - a.m_y; - - // Set texture. - IDirect3DDevice8::SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE); - IDirect3DDevice8::SetTexture(0, s_d3d_textures[bi->m_texture_id]); - - // @@ TODO this is wrong; needs fixing! Options: - // - // * compute texgen parameters for the bitmap - // - // * change to a vshader which passes the texcoords through - - // No texgen; just pass through. - float row0[4] = { 1, 0, 0, 0 }; - float row1[4] = { 0, 1, 0, 0 }; - IDirect3DDevice8::SetVertexShaderConstant(4, row0, 1); - IDirect3DDevice8::SetVertexShaderConstant(5, row1, 1); - - // Draw the quad. - IDirect3DDevice8::Begin(D3DPT_TRIANGLESTRIP); - - IDirect3DDevice8::SetVertexData2f(D3DVSDE_TEXCOORD0, uv_coords.m_x_min, uv_coords.m_y_min); - IDirect3DDevice8::SetVertexData4f(D3DVSDE_VERTEX, a.m_x, a.m_y, 0, 1); - - IDirect3DDevice8::SetVertexData2f(D3DVSDE_TEXCOORD0, uv_coords.m_x_max, uv_coords.m_y_min); - IDirect3DDevice8::SetVertexData4f(D3DVSDE_VERTEX, b.m_x, b.m_y, 0, 1); - - IDirect3DDevice8::SetVertexData2f(D3DVSDE_TEXCOORD0, uv_coords.m_x_min, uv_coords.m_y_max); - IDirect3DDevice8::SetVertexData4f(D3DVSDE_VERTEX, c.m_x, c.m_y, 0, 1); - - IDirect3DDevice8::SetVertexData2f(D3DVSDE_TEXCOORD0, uv_coords.m_x_max, uv_coords.m_y_max); - IDirect3DDevice8::SetVertexData4f(D3DVSDE_VERTEX, d.m_x, d.m_y, 0, 1); - - IDirect3DDevice8::End(); - -#if 0 - glBindTexture(GL_TEXTURE_2D, bi->m_texture_id); - glEnable(GL_TEXTURE_2D); - glDisable(GL_TEXTURE_GEN_S); - glDisable(GL_TEXTURE_GEN_T); - - glBegin(GL_TRIANGLE_STRIP); - - glTexCoord2f(uv_coords.m_x_min, uv_coords.m_y_min); - glVertex2f(a.m_x, a.m_y); - - glTexCoord2f(uv_coords.m_x_max, uv_coords.m_y_min); - glVertex2f(b.m_x, b.m_y); - - glTexCoord2f(uv_coords.m_x_min, uv_coords.m_y_max); - glVertex2f(c.m_x, c.m_y); - - glTexCoord2f(uv_coords.m_x_max, uv_coords.m_y_max); - glVertex2f(d.m_x, d.m_y); - - glEnd(); -#endif // 0 - } - - void begin_submit_mask() - { -#if 0 - glEnable(GL_STENCIL_TEST); - glClearStencil(0); - glClear(GL_STENCIL_BUFFER_BIT); - glColorMask(0,0,0,0); // disable framebuffer writes - glEnable(GL_STENCIL_TEST); // enable stencil buffer for "marking" the mask - glStencilFunc(GL_ALWAYS, 1, 1); // always passes, 1 bit plane, 1 as mask - glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); // we set the stencil buffer to 1 where we draw any polygon - // keep if test fails, keep if test passes but buffer test fails - // replace if test passes -#endif // 0 - } - - void end_submit_mask() - { -#if 0 - glColorMask(1,1,1,1); // enable framebuffer writes - glStencilFunc(GL_EQUAL, 1, 1); // we draw only where the stencil is 1 (where the mask was drawn) - glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); // don't change the stencil buffer -#endif // 0 - } - - void disable_mask() - { -#if 0 - glDisable(GL_STENCIL_TEST); -#endif // 0 - } - -}; // end struct render_handler_xbox - - -// bitmap_info_xbox implementation - - -bitmap_info_xbox::bitmap_info_xbox(create_empty e) -{ - // A null texture. Needs to be initialized later. -} - - -bitmap_info_xbox::bitmap_info_xbox(image::rgb* im) -// Image with no alpha. -{ - assert(im); - - // Rescale. - m_original_width = im->m_width; - m_original_height = im->m_height; - - int w = 1; while (w < im->m_width) { w <<= 1; } - int h = 1; while (h < im->m_height) { h <<= 1; } - - image::rgb* rescaled = image::create_rgb(w, h); - image::resample(rescaled, 0, 0, w - 1, h - 1, - im, 0, 0, (float) im->m_width, (float) im->m_height); - - // Need to insert a dummy alpha byte in the image data, for - // D3DXLoadSurfaceFromMemory. - // @@ this sucks :( - int pixel_count = w * h; - Uint8* expanded_data = new Uint8[pixel_count * 4]; - for (int y = 0; y < h; y++) - { - Uint8* scanline = image::scanline(rescaled, y); - for (int x = 0; x < w; x++) - { - expanded_data[((y * w) + x) * 4 + 0] = scanline[x * 3 + 0]; // red - expanded_data[((y * w) + x) * 4 + 1] = scanline[x * 3 + 1]; // green - expanded_data[((y * w) + x) * 4 + 2] = scanline[x * 3 + 2]; // blue - expanded_data[((y * w) + x) * 4 + 3] = 255; // alpha - } - } - - // Create the texture. - s_d3d_textures.push_back(NULL); - m_texture_id = s_d3d_textures.size() - 1; - - IDirect3DTexture8* tex; - HRESULT result = IDirect3DDevice8::CreateTexture( - w, - h, - 0, - D3DUSAGE_BORDERSOURCE_TEXTURE, - D3DFMT_DXT1, - NULL, - &tex); - if (result != S_OK) - { - gameswf::log_error("error: can't create texture\n"); - return; - } - s_d3d_textures.back() = tex; - - IDirect3DSurface8* surf = NULL; - result = tex->GetSurfaceLevel(0, &surf); - if (result != S_OK) - { - gameswf::log_error("error: can't get surface\n"); - return; - } - assert(surf); - - RECT source_rect; - source_rect.left = 0; - source_rect.top = 0; - source_rect.right = w; - source_rect.bottom = h; - result = D3DXLoadSurfaceFromMemory( - surf, - NULL, - NULL, - expanded_data, - D3DFMT_LIN_A8B8G8R8, - w * 4, - NULL, - &source_rect, - D3DX_FILTER_POINT, - 0); - delete [] expanded_data; - if (result != S_OK) - { - gameswf::log_error("error: can't load surface from memory, result = %d\n", result); - return; - } - - if (surf) { surf->Release(); } -#if 0 - glEnable(GL_TEXTURE_2D); - glGenTextures(1, (GLuint*)&m_texture_id); - glBindTexture(GL_TEXTURE_2D, m_texture_id); - - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST /* LINEAR_MIPMAP_LINEAR */); - - m_original_width = im->m_width; - m_original_height = im->m_height; - - int w = 1; while (w < im->m_width) { w <<= 1; } - int h = 1; while (h < im->m_height) { h <<= 1; } - - image::rgb* rescaled = image::create_rgb(w, h); - image::resample(rescaled, 0, 0, w - 1, h - 1, - im, 0, 0, (float) im->m_width, (float) im->m_height); - - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, rescaled->m_data); - glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, rescaled->m_width, rescaled->m_height, GL_RGB, GL_UNSIGNED_BYTE, rescaled->m_data); - - delete [] rescaled; -#endif // 0 -} - - -bitmap_info_xbox::bitmap_info_xbox(image::rgba* im) -// Version of the constructor that takes an image with alpha. -{ - assert(im); - - m_original_width = im->m_width; - m_original_height = im->m_height; - - int w = 1; while (w < im->m_width) { w <<= 1; } - int h = 1; while (h < im->m_height) { h <<= 1; } - - // Create the texture. - s_d3d_textures.push_back(NULL); - m_texture_id = s_d3d_textures.size() - 1; - - IDirect3DTexture8* tex; - HRESULT result = IDirect3DDevice8::CreateTexture( - w, - h, - 0, - D3DUSAGE_BORDERSOURCE_TEXTURE, - D3DFMT_DXT1, - NULL, - &tex); - if (result != S_OK) - { - gameswf::log_error("error: can't create texture\n"); - return; - } - s_d3d_textures.back() = tex; - - IDirect3DSurface8* surf = NULL; - result = tex->GetSurfaceLevel(0, &surf); - if (result != S_OK) - { - gameswf::log_error("error: can't get surface\n"); - return; - } - assert(surf); - - RECT source_rect; - source_rect.left = 0; - source_rect.top = 0; - source_rect.right = w; - source_rect.bottom = h; - - // Set the actual data. - if (w != im->m_width - || h != im->m_height) - { - image::rgba* rescaled = image::create_rgba(w, h); - image::resample(rescaled, 0, 0, w - 1, h - 1, - im, 0, 0, (float) im->m_width, (float) im->m_height); - - result = D3DXLoadSurfaceFromMemory( - surf, - NULL, - NULL, - rescaled->m_data, - D3DFMT_LIN_A8B8G8R8, - rescaled->m_pitch, - NULL, - &source_rect, - D3DX_FILTER_POINT, - 0); - if (result != S_OK) - { - gameswf::log_error("error: can't load surface from memory, result = %d\n", result); - return; - } -// glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, rescaled->m_data); - - delete [] rescaled; - } - else - { - // Use original image directly. - result = D3DXLoadSurfaceFromMemory( - surf, - NULL, - NULL, - im->m_data, - D3DFMT_LIN_A8B8G8R8, - im->m_pitch, - NULL, - &source_rect, - D3DX_FILTER_POINT, - 0); - if (result != S_OK) - { - gameswf::log_error("error: can't load surface from memory, result = %d\n", result); - return; - } -// glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, im->m_data); - } - - if (surf) { surf->Release(); } - -#if 0 - // Create the texture. - - glEnable(GL_TEXTURE_2D); - glGenTextures(1, (GLuint*)&m_texture_id); - glBindTexture(GL_TEXTURE_2D, m_texture_id); - - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // GL_NEAREST ? - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST /* LINEAR_MIPMAP_LINEAR */); - - m_original_width = im->m_width; - m_original_height = im->m_height; - - int w = 1; while (w < im->m_width) { w <<= 1; } - int h = 1; while (h < im->m_height) { h <<= 1; } - - if (w != im->m_width - || h != im->m_height) - { - image::rgba* rescaled = image::create_rgba(w, h); - image::resample(rescaled, 0, 0, w - 1, h - 1, - im, 0, 0, (float) im->m_width, (float) im->m_height); - - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, rescaled->m_data); - - delete [] rescaled; - } - else - { - // Use original image directly. - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, im->m_data); - } -#endif // 0 -} - - -void bitmap_info_xbox::set_alpha_image(int width, int height, Uint8* data) -// Initialize this bitmap_info to an alpha image -// containing the specified data (1 byte per texel). -// -// !! Munges *data in order to create mipmaps !! -{ - assert(m_texture_id == 0); // only call this on an empty bitmap_info - assert(data); - - // Create the texture. - - m_original_width = width; - m_original_height = height; - - #ifndef NDEBUG - // You must use power-of-two dimensions!! - int w = 1; while (w < width) { w <<= 1; } - int h = 1; while (h < height) { h <<= 1; } - assert(w == width); - assert(h == height); - #endif // not NDEBUG - - s_d3d_textures.push_back(NULL); - m_texture_id = s_d3d_textures.size() - 1; - - IDirect3DTexture8* tex; - HRESULT result = IDirect3DDevice8::CreateTexture( - width, - height, - 0, - D3DUSAGE_BORDERSOURCE_TEXTURE, - D3DFMT_A8, - NULL, - &tex); - if (result != S_OK) - { - gameswf::log_error("error: can't create texture\n"); - return; - } - s_d3d_textures.back() = tex; - - IDirect3DSurface8* surf = NULL; - result = tex->GetSurfaceLevel(0, &surf); - if (result != S_OK) - { - gameswf::log_error("error: can't get surface\n"); - return; - } - assert(surf); - - RECT source_rect; - source_rect.left = 0; - source_rect.top = 0; - source_rect.right = width; - source_rect.bottom = height; - result = D3DXLoadSurfaceFromMemory( - surf, - NULL, - NULL, - data, - D3DFMT_LIN_A8, - width, - NULL, - &source_rect, - D3DX_FILTER_POINT, - 0); - if (result != S_OK) - { - gameswf::log_error("error: can't load surface from memory, result = %d\n", result); - return; - } - - if (surf) { surf->Release(); } - -// glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, data); - -// // Build mips. -// int level = 1; -// while (width > 1 || height > 1) -// { -// render_handler_xbox::make_next_miplevel(&width, &height, data); -// glTexImage2D(GL_TEXTURE_2D, level, GL_ALPHA, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, data); -// level++; -// } - -#if 0 - glEnable(GL_TEXTURE_2D); - glGenTextures(1, (GLuint*)&m_texture_id); - glBindTexture(GL_TEXTURE_2D, m_texture_id); - - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // GL_NEAREST ? - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); - - m_original_width = width; - m_original_height = height; - - #ifndef NDEBUG - // You must use power-of-two dimensions!! - int w = 1; while (w < width) { w <<= 1; } - int h = 1; while (h < height) { h <<= 1; } - assert(w == width); - assert(h == height); - #endif // not NDEBUG - - glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, data); - - // Build mips. - int level = 1; - while (width > 1 || height > 1) - { - render_handler_xbox::make_next_miplevel(&width, &height, data); - glTexImage2D(GL_TEXTURE_2D, level, GL_ALPHA, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, data); - level++; - } -#endif // 0 -} - - -gameswf::render_handler* gameswf::create_render_handler_xbox() -// Factory. -{ - return new render_handler_xbox; -} - - -#endif // _XBOX - - -// Local Variables: -// mode: C++ -// c-basic-offset: 8 -// tab-width: 8 -// indent-tabs-mode: t -// End: diff --git a/Code/BF2/External/gameswf/gameswf_shape.cpp b/Code/BF2/External/gameswf/gameswf_shape.cpp index ca6a5dbd2..317c9d443 100644 --- a/Code/BF2/External/gameswf/gameswf_shape.cpp +++ b/Code/BF2/External/gameswf/gameswf_shape.cpp @@ -6,6 +6,9 @@ // Quadratic bezier outline shapes, the basis for most SWF rendering. +#include +#include + #include "gameswf_shape.h" #include "gameswf_impl.h" @@ -15,24 +18,9 @@ #include "gameswf_tesselate.h" #include "base/tu_file.h" - -#include +#include "../../Platform/X87Compat.h" -// [BUILD-FIX SwiffPlayer: the unconditional #define pulls base/ogl.h and 8 OpenGL calls -// (debug_display_shape_paths / show_fill_number) into the link. The shipped SwiffPlayer.dll imports -// NO opengl32 (dumpbin /dependents), so DICE's build had this debug-only path OFF; linking opengl32 -// instead would add a dependent the shipped image does not have. gameswf_debug_show_paths is a -// runtime flag defaulting to false, so the path is never taken - only its OpenGL references are the -// problem. Disabled to match the shipped image. Evidence: no opengl32 in SwiffPlayer.dll dependents. -// Indexed in Code/BF2/External/gameswf/GAMESWF_DIVERGENCES.md.] -//#define DEBUG_DISPLAY_SHAPE_PATHS -#ifdef DEBUG_DISPLAY_SHAPE_PATHS - // For debugging only! - bool gameswf_debug_show_paths = false; -#endif // DEBUG_DISPLAY_SHAPE_PATHS -// [/BUILD-FIX] - namespace gameswf { @@ -84,6 +72,7 @@ namespace gameswf // + // SwiffPlayer.dll 0x10097D20. path::path() : m_new_shape(false) @@ -91,6 +80,7 @@ namespace gameswf reset(0, 0, 0, 0, 0); } + // SwiffPlayer.dll 0x10097D50 leaves m_new_shape untouched. path::path(float ax, float ay, int fill0, int fill1, int line) { reset(ax, ay, fill0, fill1, line); @@ -350,11 +340,19 @@ namespace gameswf // + // SwiffPlayer.dll 0x10097D90. mesh::mesh() { } + // SwiffPlayer.dll 0x100977A0 and 0x10097DC0 keep AX after qword _ftol. + static Sint16 shape_coord(float value) + { + return bf2x87::lowShort(bf2x87::toInt64Truncate(bf2x87::Real(value))); + } + + // SwiffPlayer.dll 0x100977A0 (adjacent dependency). void mesh::set_tri_strip(const point pts[], int count) { m_triangle_strip.resize(count * 2); // 2 coords per point @@ -362,8 +360,8 @@ namespace gameswf // convert to ints. for (int i = 0; i < count; i++) { - m_triangle_strip[i * 2] = Sint16(pts[i].m_x); - m_triangle_strip[i * 2 + 1] = Sint16(pts[i].m_y); + m_triangle_strip[i * 2] = shape_coord(pts[i].m_x); + m_triangle_strip[i * 2 + 1] = shape_coord(pts[i].m_y); } // m_triangle_strip.resize(count); @@ -401,6 +399,7 @@ namespace gameswf // + // SwiffPlayer.dll 0x10097DA0. line_strip::line_strip() // Default constructor, for array<>. : @@ -408,6 +407,7 @@ namespace gameswf {} + // SwiffPlayer.dll 0x10097DC0. line_strip::line_strip(int style, const point coords[], int coord_count) // Construct the line strip (polyline) made up of the given sequence of points. : @@ -424,8 +424,8 @@ namespace gameswf // convert to ints. for (int i = 0; i < coord_count; i++) { - m_coords[i * 2] = Sint16(coords[i].m_x); - m_coords[i * 2 + 1] = Sint16(coords[i].m_y); + m_coords[i * 2] = shape_coord(coords[i].m_x); + m_coords[i * 2 + 1] = shape_coord(coords[i].m_y); } } @@ -462,16 +462,19 @@ namespace gameswf // tesselator. struct tri_stripper { + // Implicit strip-array destruction: SwiffPlayer.dll 0x10098AA0 (deleting veneer). // A set of strips; we'll join them together into one // strip during the flush. array< array > m_strips; int m_last_strip_used; + // SwiffPlayer.dll 0x100985B0. tri_stripper() : m_last_strip_used(-1) { } + // SwiffPlayer.dll 0x10098090. void add_trapezoid(const point& l0, const point& r0, const point& l1, const point& r1) // Add two triangles to our strip. { @@ -530,6 +533,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x100988C0. void flush(mesh_set* m, int style) const // Join sub-strips together, and push the whole thing into the given mesh_set, // under the given style. @@ -583,6 +587,7 @@ namespace gameswf // + // SwiffPlayer.dll 0x10098A80. mesh_set::mesh_set() : // m_last_frame_rendered(-1), @@ -590,6 +595,7 @@ namespace gameswf { } + // SwiffPlayer.dll 0x100992F0. mesh_set::mesh_set(const tesselate::tesselating_shape* sh, float error_tolerance) // Tesselate the shape's paths into a different mesh for each fill style. : @@ -598,15 +604,18 @@ namespace gameswf { struct collect_traps : public tesselate::trapezoid_accepter { + // Implicit hash destruction: SwiffPlayer.dll 0x10097E60 / 0x10097E70. mesh_set* m; // the mesh_set that receives trapezoids. // strips-in-progress. hash m_strips; + // SwiffPlayer.dll 0x10097E40. collect_traps(mesh_set* set) : m(set) {} virtual ~collect_traps() {} // Overrides from trapezoid_accepter + // SwiffPlayer.dll 0x100985D0. virtual void accept_trapezoid(int style, const tesselate::trapezoid& tr) { // Add trapezoid to appropriate stripper. @@ -626,12 +635,14 @@ namespace gameswf point(tr.m_rx1, tr.m_y1)); } + // SwiffPlayer.dll 0x10099110. virtual void accept_line_strip(int style, const point coords[], int coord_count) // Remember this line strip in our mesh set. { m->add_line_strip(style, coords, coord_count); } + // SwiffPlayer.dll 0x10099120. void flush() const // Push our strips into the mesh set. { @@ -660,11 +671,16 @@ namespace gameswf // void mesh_set::set_last_frame_rendered(int frame_counter) { m_last_frame_rendered = frame_counter; } + // SwiffPlayer.dll 0x10098B30; member arrays destroy lines before meshes. + mesh_set::~mesh_set() = default; + + // SwiffPlayer.dll 0x10096D60. void mesh_set::display( const matrix& mat, const cxform& cx, const array& fills, - const array& line_styles) const + const array& line_styles, + int depth) const // Throw our meshes at the renderer. { assert(m_error_tolerance > 0); @@ -672,6 +688,7 @@ namespace gameswf // Setup transforms. render::set_matrix(mat); render::set_cxform(cx); + render::set_depth(depth); // Dump meshes into renderer, one mesh per style. for (int i = 0; i < m_meshes.size(); i++) @@ -687,12 +704,13 @@ namespace gameswf }} } + // SwiffPlayer.dll 0x10096E20. void mesh_set::display( const matrix& mat, const cxform& cx, const array& fills, const array& line_styles, - float ratio) const + float ratio, int depth) const // Throw our meshes at the renderer. { assert(m_error_tolerance > 0); @@ -700,6 +718,7 @@ namespace gameswf // Setup transforms. render::set_matrix(mat); render::set_cxform(cx); + render::set_depth(depth); // Dump meshes into renderer, one mesh per style. for (int i = 0; i < m_meshes.size(); i++) @@ -715,6 +734,7 @@ namespace gameswf }} } + // SwiffPlayer.dll 0x100986A0. void mesh_set::set_tri_strip(int style, const point pts[], int count) // Set mesh associated with the given fill style to the // specified triangle strip. @@ -732,6 +752,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x10098AD0. void mesh_set::add_line_strip(int style, const point coords[], int coord_count) // Add the specified line strip to our list of things to render. { @@ -765,6 +786,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x100986E0. void mesh_set::input_cached_data(tu_file* in) // Grab our data from the input stream. { @@ -791,6 +813,7 @@ namespace gameswf // + // SwiffPlayer.dll 0x10097840. static void read_fill_styles(array* styles, stream* in, int tag_type, movie_definition_sub* m) // Read fill styles, and push them onto the given style array. { @@ -806,7 +829,7 @@ namespace gameswf } } - IF_VERBOSE_PARSE(log_msg(" read_fill_styles: count = %d\n", fill_style_count)); + IF_VERBOSE_PARSE(log_msg("rfs: fsc = %d\n", fill_style_count)); // Read the styles. for (int i = 0; i < fill_style_count; i++) @@ -817,13 +840,14 @@ namespace gameswf } + // SwiffPlayer.dll 0x100978C0. static void read_line_styles(array* styles, stream* in, int tag_type) // Read line styles and push them onto the back of the given array. { // Get the count. int line_style_count = in->read_u8(); - IF_VERBOSE_PARSE(log_msg(" read_line_styles: count = %d\n", line_style_count)); + IF_VERBOSE_PARSE(log_msg("rls: lsc = %d\n", line_style_count)); // @@ does the 0xFF flag apply to all tag types? // if (tag_type > 2) @@ -831,9 +855,9 @@ namespace gameswf if (line_style_count == 0xFF) { line_style_count = in->read_u16(); - IF_VERBOSE_PARSE(log_msg(" read_line_styles: count2 = %d\n", line_style_count)); } // } + IF_VERBOSE_PARSE(log_msg("rls: lsc2 = %d\n", line_style_count)); // Read the styles. for (int i = 0; i < line_style_count; i++) @@ -849,11 +873,14 @@ namespace gameswf // + // SwiffPlayer.dll 0x100991E0. + // [CHOSEN, not recovered] S3 bridge: native loaders assign definition IDs separately. shape_character_def::shape_character_def() { } + // SwiffPlayer.dll 0x10099350; deleting veneer 0x10099670. shape_character_def::~shape_character_def() { // Free our mesh_sets. @@ -864,6 +891,48 @@ namespace gameswf } + // SwiffPlayer.dll 0x10097940. + int shape_character_def::add_fill_style(const rgba& color) + { + int index = m_fill_styles.size(); + m_fill_styles.resize(index + 1); + m_fill_styles[index].set_solid(color); + return index; + } + + + // SwiffPlayer.dll 0x10097980. + int shape_character_def::add_line_style(const rgba& color, Uint16 width) + { + int index = m_line_styles.size(); + m_line_styles.resize(index + 1); + m_line_styles[index].set(width, color); + return index; + } + + // SwiffPlayer.dll 0x100987B0. + int shape_character_def::append_fill_style(const fill_style& style) + { + int index = m_fill_styles.size(); + m_fill_styles.resize(index + 1); + m_fill_styles[index] = style; + return index; + } + + // SwiffPlayer.dll 0x100990F0 calls array::push_back at 0x10098850. + void shape_character_def::append_path(const path& p) + { + m_paths.push_back(p); + } + + // SwiffPlayer.dll 0x10099290. + rect shape_character_def::get_bound_copy() const + { + return m_bound; + } + + + // SwiffPlayer.dll 0x10098B50. void shape_character_def::read(stream* in, int tag_type, bool with_style, movie_definition_sub* m) { if (with_style) @@ -879,7 +948,7 @@ namespace gameswf int num_fill_bits = in->read_uint(4); int num_line_bits = in->read_uint(4); - IF_VERBOSE_PARSE(log_msg(" shape_character read: nfillbits = %d, nlinebits = %d\n", num_fill_bits, num_line_bits)); + IF_VERBOSE_PARSE(log_msg("scr: nfb = %d, nlb = %d\n", num_fill_bits, num_line_bits)); // These are state variables that keep the // current position & style of the shape @@ -997,7 +1066,7 @@ namespace gameswf if (flags & 0x10) { assert(tag_type >= 22); - IF_VERBOSE_PARSE(log_msg(" shape_character read: more fill styles\n")); + IF_VERBOSE_PARSE(log_msg("scr: more fill styles\n")); // Store the current path if any. if (! current_path.is_empty()) @@ -1070,7 +1139,7 @@ namespace gameswf if (SHAPE_LOG) IF_VERBOSE_PARSE(log_msg(" shape_character_read: straight edge = %4g %4g - %4g %4g\n", x, y, x + dx, y + dy)); - current_path.m_edges.push_back(edge(x + dx, y + dy, x + dx, y + dy)); + current_path.m_edges.push_back(edge(x + dx * 0.5f, y + dy * 0.5f, x + dx, y + dy)); x += dx; y += dy; @@ -1080,232 +1149,85 @@ namespace gameswf } + // SwiffPlayer.dll 0x10099600. void shape_character_def::display(character* inst) // Draw the shape using our own inherent styles. { matrix mat = inst->get_world_matrix(); cxform cx = inst->get_world_cxform(); - float pixel_scale = inst->get_parent()->get_pixel_scale(); - display(mat, cx, pixel_scale, m_fill_styles, m_line_styles); - } - - -#ifdef DEBUG_DISPLAY_SHAPE_PATHS - -#include "base/ogl.h" - - - static void point_normalize(point* p) - { - float mag2 = p->m_x * p->m_x + p->m_y * p->m_y; - if (mag2 < 1e-9f) - { - // Very short vector. - // @@ log error - - // Arbitrary unit vector. - p->m_x = 1; - p->m_y = 0; - } - - float inv_mag = 1.0f / sqrtf(mag2); - p->m_x *= inv_mag; - p->m_y *= inv_mag; + movie* parent = inst->get_parent(); + float pixel_scale = parent ? parent->get_pixel_scale() : 1.0f; + display(mat, cx, pixel_scale, m_fill_styles, m_line_styles, inst->get_depth()); } - static void show_fill_number(const point& p, int fill_number) - { - // We're inside a glBegin(GL_LINES) - - // Eh, let's do it in binary, least sig four bits... - float x = p.m_x; - float y = p.m_y; - - int mask = 8; - while (mask) - { - if (mask & fill_number) - { - // Vert line --> 1. - glVertex2f(x, y - 40.0f); - glVertex2f(x, y + 40.0f); - } - else - { - // Rectangle --> 0. - glVertex2f(x - 10.0f, y - 40.0f); - glVertex2f(x + 10.0f, y - 40.0f); - - glVertex2f(x + 10.0f, y - 40.0f); - glVertex2f(x + 10.0f, y + 40.0f); - - glVertex2f(x - 10.0f, y + 40.0f); - glVertex2f(x + 10.0f, y + 40.0f); - - glVertex2f(x - 10.0f, y - 40.0f); - glVertex2f(x - 10.0f, y + 40.0f); - } - x += 40.0f; - mask >>= 1; - } - } - - - static void debug_display_shape_paths( - const matrix& mat, - float object_space_max_error, - const array& paths, - const array& fill_styles, - const array& line_styles) - { - for (int i = 0; i < paths.size(); i++) - { -// if (i > 0) break;//xxxxxxxx - const path& p = paths[i]; - - if (p.m_fill0 == 0 && p.m_fill1 == 0) - { - continue; - } - - gameswf::render::set_matrix(mat); - - // Color the line according to which side has - // fills. - if (p.m_fill0 == 0) glColor4f(1, 0, 0, 0.5); - else if (p.m_fill1 == 0) glColor4f(0, 1, 0, 0.5); - else glColor4f(0, 0, 1, 0.5); - - // Offset according to which loop we are. - float offset_x = (i & 1) * 80.0f; - float offset_y = ((i & 2) >> 1) * 80.0f; - glMatrixMode(GL_MODELVIEW); - glPushMatrix(); - glTranslatef(offset_x, offset_y, 0.f); - - point pt; - - glBegin(GL_LINE_STRIP); - - mat.transform(&pt, point(p.m_ax, p.m_ay)); - glVertex2f(pt.m_x, pt.m_y); - - for (int j = 0; j < p.m_edges.size(); j++) - { - mat.transform(&pt, point(p.m_edges[j].m_cx, p.m_edges[j].m_cy)); - glVertex2f(pt.m_x, pt.m_y); - mat.transform(&pt, point(p.m_edges[j].m_ax, p.m_edges[j].m_ay)); - glVertex2f(pt.m_x, pt.m_y); - } - - glEnd(); - - // Draw arrowheads. - point dir, right, p0, p1; - glBegin(GL_LINES); - {for (int j = 0; j < p.m_edges.size(); j++) - { - mat.transform(&p0, point(p.m_edges[j].m_cx, p.m_edges[j].m_cy)); - mat.transform(&p1, point(p.m_edges[j].m_ax, p.m_edges[j].m_ay)); - dir = point(p1.m_x - p0.m_x, p1.m_y - p0.m_y); - point_normalize(&dir); - right = point(-dir.m_y, dir.m_x); // perpendicular - - const float ARROW_MAG = 60.f; // TWIPS? - if (p.m_fill0 != 0) - { - glColor4f(0, 1, 0, 0.5); - glVertex2f(p0.m_x, - p0.m_y); - glVertex2f(p0.m_x - dir.m_x * ARROW_MAG - right.m_x * ARROW_MAG, - p0.m_y - dir.m_y * ARROW_MAG - right.m_y * ARROW_MAG); - - show_fill_number(point(p0.m_x - right.m_x * ARROW_MAG * 4, - p0.m_y - right.m_y * ARROW_MAG * 4), - p.m_fill0); - } - if (p.m_fill1 != 0) - { - glColor4f(1, 0, 0, 0.5); - glVertex2f(p0.m_x, - p0.m_y); - glVertex2f(p0.m_x - dir.m_x * ARROW_MAG + right.m_x * ARROW_MAG, - p0.m_y - dir.m_y * ARROW_MAG + right.m_y * ARROW_MAG); - - show_fill_number(point(p0.m_x + right.m_x * ARROW_MAG * 4, - p0.m_y + right.m_y * ARROW_MAG * 4), - p.m_fill1); - } - }} - glEnd(); - - glPopMatrix(); - } - } -#endif // DEBUG_DISPLAY_SHAPE_PATHS + // SwiffPlayer.dll 0x10099460. void shape_character_def::display( const matrix& mat, const cxform& cx, float pixel_scale, const array& fill_styles, - const array& line_styles) const + const array& line_styles, + int depth) const // Display our shape. Use the fill_styles arg to // override our default set of fill styles (e.g. when // rendering text). { // Compute the error tolerance in object-space. - float max_scale = mat.get_max_scale(); - if (fabsf(max_scale) < 1e-6f) + bf2x87::Real max_scale = shape_matrix_max_scale(mat); + // SwiffPlayer.dll 0x10099460: only an exactly zero scale is substituted. + if (max_scale == bf2x87::Real(0.0f)) { - // Scale is essentially zero. - return; + max_scale = bf2x87::Real(0.001f); } - float object_space_max_error = 20.0f / max_scale / pixel_scale * s_curve_max_pixel_error; - -#ifdef DEBUG_DISPLAY_SHAPE_PATHS - // Render a debug view of shape path outlines, instead - // of the tesselated shapes themselves. - if (gameswf_debug_show_paths) - { - debug_display_shape_paths(mat, object_space_max_error, m_paths, fill_styles, line_styles); + float object_space_max_error = bf2x87::store(bf2x87::mul( + bf2x87::div(bf2x87::div(bf2x87::Real(1.0f), bf2x87::Real(pixel_scale)), max_scale), + bf2x87::Real(20.0f))); - return; - } -#endif // DEBUG_DISPLAY_SHAPE_PATHS // See if we have an acceptable mesh available; if so then render with it. for (int i = 0, n = m_cached_meshes.size(); i < n; i++) { const mesh_set* candidate = m_cached_meshes[i]; - if (object_space_max_error > candidate->get_error_tolerance() * 3.0f) + if (bf2x87::less(bf2x87::mul(bf2x87::Real(candidate->get_error_tolerance()), + bf2x87::Real(3.0f)), bf2x87::Real(object_space_max_error))) { // Mesh is too high-res; the remaining meshes are higher res, // so stop searching and build an appropriately scaled mesh. break; } - if (object_space_max_error > candidate->get_error_tolerance()) + if (bf2x87::less(bf2x87::Real(candidate->get_error_tolerance()), + bf2x87::Real(object_space_max_error))) { // Do it. - candidate->display(mat, cx, fill_styles, line_styles); + candidate->display(mat, cx, fill_styles, line_styles, depth); return; } } // Construct a new mesh to handle this error tolerance. - mesh_set* m = new mesh_set(this, object_space_max_error * 0.75f); + // SwiffPlayer.dll 0x100994F0-0x1009957B appends null on allocation failure. + mesh_set* m = new (std::nothrow) mesh_set(this, object_space_max_error * 0.75f); m_cached_meshes.push_back(m); - m->display(mat, cx, fill_styles, line_styles); + m->display(mat, cx, fill_styles, line_styles, depth); sort_and_clean_meshes(); } + // [CHOSEN, not recovered] S3 bridge for the retained 2006 glyph renderer. + void shape_character_def::display(const matrix& mat, const cxform& cx, + float pixel_scale, const array& fills, + const array& lines) const + { + display(mat, cx, pixel_scale, fills, lines, 0); + } + static int sort_by_decreasing_error(const void* A, const void* B) { @@ -1376,26 +1298,10 @@ namespace gameswf } + // SwiffPlayer.dll 0x10096470 tests the definition rectangle only. bool shape_character_def::point_test_local(float x, float y) - // Return true if the specified point is on the interior of our shape. - // Incoming coords are local coords. { - if (m_bound.point_test(x, y) == false) - { - // Early out. - return false; - } - - // Try each of the paths. - for (int i = 0; i < m_paths.size(); i++) - { - if (m_paths[i].point_test(x, y)) - { - return true; - } - } - - return false; + return m_bound.point_test(x, y); } @@ -1445,6 +1351,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x10099070. void shape_character_def::input_cached_data(tu_file* in) // Initialize our mesh data from the given stream. { @@ -1454,7 +1361,7 @@ namespace gameswf for (int i = 0; i < n; i++) { - mesh_set* ms = new mesh_set(); + mesh_set* ms = new (std::nothrow) mesh_set(); ms->input_cached_data(in); m_cached_meshes[i] = ms; } diff --git a/Code/BF2/External/gameswf/gameswf_shape.h b/Code/BF2/External/gameswf/gameswf_shape.h index b6cab0734..01cc1f5e7 100644 --- a/Code/BF2/External/gameswf/gameswf_shape.h +++ b/Code/BF2/External/gameswf/gameswf_shape.h @@ -11,16 +11,32 @@ #include "gameswf_styles.h" +#include "../../Platform/X87Compat.h" namespace gameswf { + // [CHOSEN, not recovered] S3 bridge: the legacy matrix getter returns float. + // Keep the wide return consumed by shape/morph until that shared API migrates. + // Arithmetic/stores are from SwiffPlayer.dll 0x1009DC40; helper name [INFERRED]. + inline bf2x87::Real shape_matrix_max_scale(const matrix& m) + { + using namespace bf2x87; + Real basis0 = add(mul(Real(m.m_[0][0]), Real(m.m_[0][0])), + mul(Real(m.m_[0][1]), Real(m.m_[0][1]))); + float basis1 = store(add(mul(Real(m.m_[1][0]), Real(m.m_[1][0])), + mul(Real(m.m_[1][1]), Real(m.m_[1][1])))); + if (less(basis0, Real(basis1))) basis0 = Real(basis1); + return squareRoot(basis0); + } + struct character; struct stream; struct shape_character_def; namespace tesselate { struct trapezoid_accepter; struct tesselating_shape { + // Implicit vptr-only construction: SwiffPlayer.dll 0x10096420. virtual void tesselate(float error_tolerance, trapezoid_accepter *accepter) const = 0; }; @@ -47,8 +63,11 @@ namespace gameswf // A subset of a shape -- a series of edges sharing a single set // of styles. { + // SwiffPlayer.dll 0x10075BD0: implicit assignment copies style/start + // fields, deep-copies the edges and copies the new-shape flag last. path(); path(float ax, float ay, int fill0, int fill1, int line); + // Implicit edge-array destruction: SwiffPlayer.dll 0x10098060 (deleting veneer). void reset(float ax, float ay, int fill0, int fill1, int line); bool is_empty() const; @@ -69,6 +88,7 @@ namespace gameswf // For holding a pre-tesselated shape. { mesh(); + // Implicit coordinate-array destruction: SwiffPlayer.dll 0x10097FF0 (deleting veneer). void set_tri_strip(const point pts[], int count); @@ -86,6 +106,8 @@ namespace gameswf { line_strip(); line_strip(int style, const point coords[], int coord_count); + // Implicit style/coordinate copy constructor: SwiffPlayer.dll 0x10097B60. + // Implicit coordinate-array destruction: SwiffPlayer.dll 0x10097EA0 / 0x10098020. void display(const base_line_style& style, float ratio) const; @@ -104,6 +126,8 @@ namespace gameswf mesh_set(); mesh_set(const tesselate::tesselating_shape* sh, float error_tolerance); + // SwiffPlayer.dll 0x10098B30; deleting veneer 0x100992C0. + ~mesh_set(); // int get_last_frame_rendered() const; // void set_last_frame_rendered(int frame_counter); @@ -113,14 +137,17 @@ namespace gameswf const matrix& m, const cxform& cx, const array& fills, - const array& line_styles) const; + const array& line_styles, + int depth) const; void display( const matrix& m, const cxform& cx, const array& fills, const array& line_styles, - float ratio) const; + // [CHOSEN, not recovered] S3 bridge for excluded gameswf_morph.cpp, + // whose 2006 caller carries no depth. Recovered callers pass it explicitly. + float ratio, int depth = 0) const; void set_tri_strip(int style, const point pts[], int count); void add_line_strip(int style, const point coords[], int coord_count); @@ -155,14 +182,24 @@ namespace gameswf const cxform& cx, float pixel_scale, const array& fill_styles, - const array& line_styles) const; + const array& line_styles, + int depth) const; + // [CHOSEN, not recovered] S3 bridge for legacy font-outline callers. + // Retail text uses host-rendered lines; the 2006 glyph API carries no depth. + void display(const matrix& mat, const cxform& cx, float pixel_scale, + const array& fills, const array& lines) const; virtual void tesselate(float error_tolerance, tesselate::trapezoid_accepter* accepter) const; + // SwiffPlayer.dll 0x10099290; return value consumed at 0x1009FDDC / 0x1009FDE8. + // The copy getter's name is [INFERRED] while the legacy reference API remains. + rect get_bound_copy() const override; + // [CHOSEN, not recovered] S3 bridge: existing callers borrow the bounds. const rect& get_bound() const { return m_bound; } void compute_bound(rect* r) const; // @@ what's the difference between this and get_bound? void output_cached_data(tu_file* out, const cache_options& options); void input_cached_data(tu_file* in); + // SwiffPlayer.dll 0x1009F580, 0x1009F590 and 0x1009F5A0. const array& get_fill_styles() const { return m_fill_styles; } const array& get_line_styles() const { return m_line_styles; } const array& get_paths() const { return m_paths; } @@ -170,11 +207,20 @@ namespace gameswf // morph uses this void set_bound(const rect& r) { m_bound = r; /* should do some verifying */ } - // [DICE-MOD SwiffPlayer: the mutation surface the drawing API and the loadMovie image + // the mutation surface the drawing API and the loadMovie image // loader need on a runtime-built shape (the shipped canvas is a `_____defaultShape` child // whose definition gameswf_sprite_line_style/move_to/line_to/begin_fill/end_fill mutate: // styles appended and referenced 1-based, paths appended, the bound recomputed after every - // edge). The tesselation cache is thrown away on every change so display() re-tesselates.] + // edge). The tesselation cache is thrown away on every change so display() re-tesselates. + // SwiffPlayer.dll 0x10097940 and 0x10097980 return zero-based style indices. + int add_fill_style(const rgba& color); + int add_line_style(const rgba& color, Uint16 width); + // Append copies without invalidating cached meshes. The style index is zero-based. + // SwiffPlayer.dll 0x100987B0 and 0x100990F0; names [INFERRED]. + int append_fill_style(const fill_style& style); + void append_path(const path& p); + // [CHOSEN, not recovered] S3 bridge: existing 2006 canvas callers use full styles, + // one-based IDs and explicit mesh invalidation. Retain until the canvas is recovered. int add_fill_style(const fill_style& f) { m_fill_styles.push_back(f); clear_cached_meshes(); return m_fill_styles.size(); } int add_line_style(const line_style& l) { m_line_styles.push_back(l); clear_cached_meshes(); return m_line_styles.size(); } path* current_path() { return m_paths.size() > 0 ? &m_paths[m_paths.size() - 1] : NULL; } diff --git a/Code/BF2/External/gameswf/gameswf_sound.cpp b/Code/BF2/External/gameswf/gameswf_sound.cpp index dd6baebfb..bc05c978c 100644 --- a/Code/BF2/External/gameswf/gameswf_sound.cpp +++ b/Code/BF2/External/gameswf/gameswf_sound.cpp @@ -19,6 +19,7 @@ namespace gameswf static sound_handler* s_sound_handler = 0; + // SwiffPlayer.dll 0x1009E8F0. void set_sound_handler(sound_handler* s) // Called by host, to set a handler for all sounds. // Can pass in 0 to disable sound. @@ -27,12 +28,14 @@ namespace gameswf } + // SwiffPlayer.dll 0x1009E900. sound_handler* get_sound_handler() { return s_sound_handler; } + // SwiffPlayer.dll 0x1009E910; deleting veneer 0x1009F530. sound_sample_impl::~sound_sample_impl() { if (s_sound_handler) @@ -50,6 +53,7 @@ namespace gameswf bool stereo); + // SwiffPlayer.dll 0x1009F220. void define_sound_loader(stream* in, int tag_type, movie_definition_sub* m) // Load a DefineSound tag. { @@ -126,10 +130,12 @@ namespace gameswf struct start_sound_tag : public execute_tag { + // Implicit destructor: SwiffPlayer.dll 0x1009F440 (deleting veneer). Uint16 m_handler_id; int m_loop_count; bool m_stop_playback; + // SwiffPlayer.dll 0x1009F3F0. start_sound_tag() : m_handler_id(0), @@ -139,6 +145,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x1009E960: envelope/no-multiple flags are read and discarded. void read(stream* in, int tag_type, movie_definition_sub* m, const sound_sample_impl* sam) // Initialize this StartSound tag from the stream & given sample. // Insert ourself into the movie. @@ -168,6 +175,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x1009F410. void execute(movie* m) { if (s_sound_handler) @@ -185,6 +193,7 @@ namespace gameswf }; + // SwiffPlayer.dll 0x1009F470. void start_sound_loader(stream* in, int tag_type, movie_definition_sub* m) // Load a StartSound tag. { @@ -362,6 +371,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x1009EA10: 4096-frame blocks, 2-5-bit codes, interleaved stereo. void adpcm_expand( void* out_data_void, stream* in, diff --git a/Code/BF2/External/gameswf/gameswf_sound_handler_mp3.cpp b/Code/BF2/External/gameswf/gameswf_sound_handler_mp3.cpp deleted file mode 100644 index a4068f01f..000000000 --- a/Code/BF2/External/gameswf/gameswf_sound_handler_mp3.cpp +++ /dev/null @@ -1,211 +0,0 @@ -/* - * gameswf_sound_handler_mp3.cpp -- tbp, 2003 - * - * This source code has been donated to the Public Domain. - * Do whatever you want with it. - * - * Some brain damaged helpers to decode mp3 streams for use in - * a gameswf::sound_handler that uses SDL_mixer for output. - * (even comments are cut&paste compliant) - * - */ - - -#ifdef GAMESWF_MP3_SUPPORT - -#include "gameswf.h" -#include "base/container.h" - -// @@ These macros are internal to gameswf; maybe should expose them for -// use by external handler code like this... -#ifndef IF_VERBOSE_PARSE -#define IF_VERBOSE_PARSE(x) -#endif - -#ifndef log_error -#define log_error(x,y) /* ? */ -#endif - -#include - -#include -#ifdef _MSC_VER - #pragma comment(lib, "libmad") - #define snprintf _snprintf -#endif - -namespace mad_helpers { - static const char *parse_layer(const mad_header *h) { - switch(h->layer) { - case MAD_LAYER_I: return "I"; - case MAD_LAYER_II: return "II"; - case MAD_LAYER_III: return "III"; - default: return "bogus"; - } - } - static const char *parse_channel_mode(const mad_header *h) { - switch (h->mode) { - case MAD_MODE_SINGLE_CHANNEL: return "single channel"; - case MAD_MODE_DUAL_CHANNEL: return "dual channel"; - case MAD_MODE_JOINT_STEREO: return "joint (MS/intensity) stereo"; - case MAD_MODE_STEREO: return "normal LR stereo"; - default: return "bogus"; - } - } - static const char *parse_emphasis(const mad_header *h) { - switch (h->emphasis) { - case MAD_EMPHASIS_NONE: return "none"; - case MAD_EMPHASIS_50_15_US: return "50/15 us"; - case MAD_EMPHASIS_CCITT_J_17: return "CCITT J.17"; - default: return "bogus"; - } - } - - static void parse_frame_info(char *buf, const unsigned int len, const mad_header *h) { - snprintf(buf, len, "%lu kb/s audio mpeg layer %s stream crc [%s] mode '%s' with '%s' emphasis at %u Hz sample rate", - h->bitrate, parse_layer(h), (h->flags&MAD_FLAG_PROTECTION)?"X":" ", parse_channel_mode(h), parse_emphasis(h), h->samplerate); - buf[len-1] = 0; - } - - template static void pcm_fixed_to_native(const mad_fixed_t *src, Sint16 *dst, const unsigned int count) { - assert(count > 0); - unsigned int - dec = count, - idx = 0; - do { - dst[idx*stride] = src[idx] >> (MAD_F_FRACBITS-15); // no fancy dithering... - ++idx; - } while (--dec); - } - -}; - -// some intermediary buffer to hold a frame worth of samples -// fugly. -struct pcm_buff_t { - //enum { frame_payload = 1152 }; - Sint16 *samples; - unsigned int count; - - ~pcm_buff_t() { - delete samples; - } - - // from mad fixed point to native 16 bits in a temp. buffer - unsigned int transmogrify(const mad_synth &synth, const bool stereo) { - count = synth.pcm.length; - if (stereo) { - samples = new Sint16[count*2]; - mad_helpers::pcm_fixed_to_native<2>(&synth.pcm.samples[0][0], &samples[0], count); - mad_helpers::pcm_fixed_to_native<2>(&synth.pcm.samples[1][0], &samples[1], count); - return count * 2; - } - else { - samples = new Sint16[count]; - mad_helpers::pcm_fixed_to_native<1>(&synth.pcm.samples[0][0], samples, count); - return count; - } - } - - void *collate(void *p, const bool stereo) const - { - const unsigned int bytes = count * (stereo ? 2 : 1) * sizeof(Sint16); - memcpy(p, samples, bytes); - return (void *) (((char *)p) + bytes); // geez - } -}; - -// there's quite some (useless) copying around since there's no infrastructure for streaming and we need to decode it all at once -void convert_mp3_data(Sint16 **adjusted_data, int *adjusted_size, void *data, const int sample_count, const int sample_size, const int sample_rate, const bool stereo) -{ - //log_msg("convert_mp3_data sample count %d rate %d stereo %s\n", sample_count, sample_rate, stereo?"yes":"no"); - - mad_stream stream; - mad_frame frame; - mad_synth synth; - mad_timer_t timer; - - mad_stream_init(&stream); - mad_frame_init(&frame); - mad_synth_init(&synth); - mad_timer_reset(&timer); - - // decode stream - mad_stream_buffer(&stream, (const unsigned char *)data, sample_count); - stream.error = MAD_ERROR_NONE; - - // decode frames - unsigned int fc = 0, total = 0; - array out; // holds decoded frames - - while (true) - { - if (mad_frame_decode(&frame, &stream)) { - // there's always some garbage in front of the buffer - // so i guess, it's not so garbagish. anyway, skip. - if (fc == 0 && stream.error == MAD_ERROR_LOSTSYNC) - { - continue; - } - else - { - // kludge as we stop decoding on LOSTSYNC. - if (stream.error != MAD_ERROR_LOSTSYNC) - { - log_error("** MP3 frame error: %s\n", mad_stream_errorstr(&stream)); - } - break; - } - } - - if (fc == 0) - { - // verbose - IF_VERBOSE_PARSE( - char buf[1024]; - mad_helpers::parse_frame_info(buf, sizeof(buf), &frame.header); - printf("%s\n",buf); - ); - } - - ++fc; - mad_timer_add(&timer,frame.header.duration); - - mad_synth_frame(&synth,&frame); - pcm_buff_t *pcm = new pcm_buff_t; - total += pcm->transmogrify(synth, stereo); - out.push_back(pcm); - } - - if (total == 0) goto cleanup; // yay - - IF_VERBOSE_PARSE(log_msg("decoded frames %d bytes %d(diff %d) -- original rate %d\n\n", fc, total, total - sample_count, sample_rate)); - - // assemble together all decoded frames. another round of memcpy. - { - void *p = new Sint16[total]; - *adjusted_data = (Sint16*) p; - *adjusted_size = total * sizeof(Sint16); - // stuff all that crap together - {for (int i=0; icollate(p,stereo); - } - } - -cleanup: - {for (int i=0; i m_samples; - - #define SAMPLE_RATE 44100 - #define MIX_CHANNELS 8 - #define CHANNELS 2 //stereo - 2, mono - 1 - #define BUFSIZE 4096 // for 44100 bufsize 1024 is small - - SDL_sound_handler() - : - m_opened(false), - m_stereo(false), - m_sample_rate(0), - m_format(0) - { - // !!! some drivers on Linux always open audio with channels=2 - if (Mix_OpenAudio(SAMPLE_RATE, AUDIO_S16SYS, CHANNELS, BUFSIZE) != 0) - { - gameswf::log_error("can't open SDL_mixer: %s\n", Mix_GetError()); - } - else - { - m_opened = true; - Mix_AllocateChannels(MIX_CHANNELS); - Mix_Volume(-1, MIX_MAX_VOLUME); - - // get and print the audio format in use - int channels; - int num_times_opened = Mix_QuerySpec(&m_sample_rate, &m_format, &channels); - UNUSED(num_times_opened); - m_stereo = channels == 2 ? true : false; - - const char *format_str = "Unknown"; - switch (m_format) - { - case AUDIO_U8: format_str = "U8"; break; - case AUDIO_S8: format_str = "S8"; break; - case AUDIO_U16LSB: format_str = "U16LSB"; break; - case AUDIO_S16LSB: format_str = "S16LSB"; break; - case AUDIO_U16MSB: format_str = "U16MSB"; break; - case AUDIO_S16MSB: format_str = "S16MSB"; break; - } - - // @@ Usually I don't care about this. Need a IF_VERBOSE_SOUND or something. - // IF_VERBOSE_DEBUG( - // gameswf::log_msg("SDL_mixer: opened %d times, frequency=%dHz, format=%s, stereo=%s\n", - // num_times_opened, - // m_sample_rate, - // format_str, - // m_stereo ? "yes" : "no")); - // char name[32]; - // IF_VERBOSE_DEBUG( - // gameswf::log_msg("Using audio driver: %s\n", SDL_AudioDriverName(name, 32))); - } - } - - ~SDL_sound_handler() - { - if (m_opened) - { - Mix_CloseAudio(); - for (int i = 0, n = m_samples.size(); i < n; i++) - { - if (m_samples[i]) - { - Mix_FreeChunk(m_samples[i]); - } - } - } - else - { - assert(m_samples.size() == 0); - } - } - - - virtual int create_sound( - void* data, - int data_bytes, - int sample_count, - format_type format, - int sample_rate, - bool stereo) - // Called by gameswf to create a sample. We'll return a sample ID that gameswf - // can use for playing it. - { - if (m_opened == false) - { - return 0; - } - - Sint16* adjusted_data = 0; - int adjusted_size = 0; - Mix_Chunk* sample = 0; - - switch (format) - { - case FORMAT_RAW: - convert_raw_data(&adjusted_data, &adjusted_size, data, sample_count, 1, sample_rate, stereo); - break; - - case FORMAT_NATIVE16: - convert_raw_data(&adjusted_data, &adjusted_size, data, sample_count, 2, sample_rate, stereo); - break; - - case FORMAT_MP3: -#ifdef GAMESWF_MP3_SUPPORT - extern void convert_mp3_data(Sint16 **adjusted_data, int *adjusted_size, void *data, const int sample_count, const int sample_size, const int sample_rate, const bool stereo); - if (1) { - Sint16* x_adjusted_data = 0; - int x_adjusted_size = 0; - Mix_Chunk* x_sample = 0; - convert_mp3_data(&x_adjusted_data, &x_adjusted_size, data, sample_count, 0, sample_rate, stereo); - /* convert_mp3_data doesn't ACTUALLY convert - samplerate, so... */ - convert_raw_data(&adjusted_data, &adjusted_size, x_adjusted_data, sample_count, 0, sample_rate, stereo); - if (x_adjusted_data) { - delete x_adjusted_data; - } - } else { - convert_mp3_data(&adjusted_data, &adjusted_size, data, sample_count, 0, sample_rate, stereo); - } -#else - IF_VERBOSE_DEBUG(gameswf::log_error("mp3 format sound requested; this demo does not handle mp3\n")); -#endif - break; - - default: - // Unhandled format. - IF_VERBOSE_DEBUG(gameswf::log_error("unknown format sound requested; this demo does not handle it\n")); - break; - } - - if (adjusted_data) - { - sample = Mix_QuickLoad_RAW((unsigned char*) adjusted_data, adjusted_size); - Mix_VolumeChunk(sample, MIX_MAX_VOLUME); // full volume by default - } - - m_samples.push_back(sample); - return m_samples.size() - 1; - } - - - virtual void play_sound(int sound_handle, int loop_count /* other params */) - // Play the index'd sample. - { - if (sound_handle >= 0 && sound_handle < m_samples.size()) - { - if (m_samples[sound_handle]) - { - // Play this sample on the first available channel. - Mix_PlayChannel(-1, m_samples[sound_handle], loop_count); - } - } - } - - - virtual void stop_sound(int sound_handle) - { - if (sound_handle < 0 || sound_handle >= m_samples.size()) - { - // Invalid handle. - return; - } - - for (int i = 0; i < MIX_CHANNELS; i++) - { - Mix_Chunk* playing_chunk = Mix_GetChunk(i); - if (Mix_Playing(i) - && playing_chunk == m_samples[sound_handle]) - { - // Stop this channel. - Mix_HaltChannel(i); - } - } - } - - - virtual void delete_sound(int sound_handle) - // gameswf calls this when it's done with a sample. - { - if (sound_handle >= 0 && sound_handle < m_samples.size()) - { - Mix_Chunk* chunk = m_samples[sound_handle]; - if (chunk) - { - delete [] (chunk->abuf); - Mix_FreeChunk(chunk); - m_samples[sound_handle] = 0; - } - } - } - - virtual void convert_raw_data( - Sint16** adjusted_data, - int* adjusted_size, - void* data, - int sample_count, - int sample_size, - int sample_rate, - bool stereo) - // VERY crude sample-rate & sample-size conversion. Converts - // input data to the SDL_mixer output format (SAMPLE_RATE, - // stereo, 16-bit native endianness) - { -// // xxxxx debug pass-thru -// { -// int output_sample_count = sample_count * (stereo ? 2 : 1); -// Sint16* out_data = new Sint16[output_sample_count]; -// *adjusted_data = out_data; -// *adjusted_size = output_sample_count * 2; // 2 bytes per sample -// memcpy(out_data, data, *adjusted_size); -// return; -// } -// // xxxxx - - // simple hack to handle dup'ing mono to stereo - if ( !stereo && m_stereo) - { - sample_rate >>= 1; - } - - // simple hack to lose half the samples to get mono from stereo - if ( stereo && !m_stereo) - { - sample_rate <<= 1; - } - - // Brain-dead sample-rate conversion: duplicate or - // skip input samples an integral number of times. - int inc = 1; // increment - int dup = 1; // duplicate - if (sample_rate > m_sample_rate) - { - inc = sample_rate / m_sample_rate; - } - else if (sample_rate < m_sample_rate) - { - dup = m_sample_rate / sample_rate; - } - - int output_sample_count = (sample_count * dup) / inc; - Sint16* out_data = new Sint16[output_sample_count]; - *adjusted_data = out_data; - *adjusted_size = output_sample_count * 2; // 2 bytes per sample - - if (sample_size == 1) - { - // Expand from 8 bit to 16 bit. - Uint8* in = (Uint8*) data; - for (int i = 0; i < output_sample_count; i++) - { - Uint8 val = *in; - for (int j = 0; j < dup; j++) - { - *out_data++ = (int(val) - 128); - } - in += inc; - } - } - else - { - // 16-bit to 16-bit conversion. - Sint16* in = (Sint16*) data; - for (int i = 0; i < output_sample_count; i += dup) - { - Sint16 val = *in; - for (int j = 0; j < dup; j++) - { - *out_data++ = val; - } - in += inc; - } - } - } - -}; - - -gameswf::sound_handler* gameswf::create_sound_handler_sdl() -// Factory. -{ - return new SDL_sound_handler; -} - - -// Local Variables: -// mode: C++ -// c-basic-offset: 8 -// tab-width: 8 -// indent-tabs-mode: t -// End: diff --git a/Code/BF2/External/gameswf/gameswf_stream.cpp b/Code/BF2/External/gameswf/gameswf_stream.cpp index 7edb8f5e5..8939be79c 100644 --- a/Code/BF2/External/gameswf/gameswf_stream.cpp +++ b/Code/BF2/External/gameswf/gameswf_stream.cpp @@ -17,7 +17,10 @@ namespace gameswf { + // [CHOSEN, not recovered] S3 bridge: the retail input callback record is + // represented by the existing tu_file API; byte order stays little-endian. + // SwiffPlayer.dll 0x1009D670. stream::stream(tu_file* input) : m_input(input), @@ -27,6 +30,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x1009D690; the tag stack owns its storage. stream::~stream() { } @@ -51,6 +55,7 @@ namespace gameswf // } + // SwiffPlayer.dll 0x1009D360. int stream::read_uint(int bitcount) // Reads a bit-packed unsigned integer from the stream // and returns it. The given bitcount determines the @@ -66,7 +71,7 @@ namespace gameswf if (m_unused_bits) { if (bits_needed >= m_unused_bits) { // Consume all the unused bits. - value |= (m_current_byte << (bits_needed - m_unused_bits)); + value |= Uint32(m_current_byte) << ((bits_needed - m_unused_bits) & 31); bits_needed -= m_unused_bits; @@ -97,6 +102,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x1009D410. x86 masks both shift counts, including 0 and 32. int stream::read_sint(int bitcount) // Reads a bit-packed little-endian signed integer // from the stream. The given bitcount determines the @@ -104,19 +110,20 @@ namespace gameswf { assert(bitcount <= 32 && bitcount >= 0); - Sint32 value = (Sint32) read_uint(bitcount); + Uint32 value = Uint32(read_uint(bitcount)); // Sign extend... - if (value & (1 << (bitcount - 1))) { - value |= -1 << bitcount; + if (value & (Uint32(1) << ((bitcount - 1) & 31))) { + value |= ~Uint32(0) << (bitcount & 31); } // IF_DEBUG(log_msg("stream::read_sint(%d) == %d\n", bitcount, value)); - return value; + return Sint32(value); } + // SwiffPlayer.dll 0x1009D210; only the unused-bit count is cleared. float stream::read_fixed() { m_unused_bits = 0; @@ -124,10 +131,14 @@ namespace gameswf return (float) val / 65536.0f; } + // SwiffPlayer.dll 0x1009D240. void stream::align() { m_unused_bits = 0; m_current_byte = 0; } + // SwiffPlayer.dll 0x1009D440. Uint8 stream::read_u8() { align(); return m_input->read_byte(); } + // SwiffPlayer.dll 0x1009D470. Sint8 stream::read_s8() { align(); return m_input->read_byte(); } + // SwiffPlayer.dll 0x1009D250. Uint16 stream::read_u16() { align(); @@ -136,16 +147,20 @@ namespace gameswf // IF_DEBUG(log_msg("val = 0x%X\n", val)); return val; } + // SwiffPlayer.dll 0x1009D280. Sint16 stream::read_s16() { align(); return m_input->read_le16(); } + // SwiffPlayer.dll 0x1009D2B0. Uint32 stream::read_u32() { align(); Uint32 val = m_input->read_le32(); return val; } + // SwiffPlayer.dll 0x1009D2E0. Sint32 stream::read_s32() { align(); return m_input->read_le32(); } + // SwiffPlayer.dll 0x1009D6A0. char* stream::read_string() // Reads *and new[]'s* the string from the given file. // Ownership passes to the caller; caller must delete[] the @@ -173,6 +188,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x1009D4A0. char* stream::read_string_with_length() // Reads *and new[]'s* the string from the given file. // Ownership passes to the caller; caller must delete[] the @@ -200,6 +216,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x1009D310. int stream::get_position() // Return our current (byte) position in the input stream. { @@ -207,6 +224,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x1009D540. void stream::set_position(int pos) // Set the file position to the given value. { @@ -226,6 +244,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x1009D560. int stream::get_tag_end_position() // Return the file position of the end of the current tag. { @@ -235,6 +254,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x1009D5B0. int stream::open_tag() // Return the tag type. { @@ -257,6 +277,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x1009D640; retain the current byte when discarding its bits. void stream::close_tag() // Seek to the end of the most-recently-opened tag. { diff --git a/Code/BF2/External/gameswf/gameswf_stream.h b/Code/BF2/External/gameswf/gameswf_stream.h index 4ce42c61d..75f91ce3c 100644 --- a/Code/BF2/External/gameswf/gameswf_stream.h +++ b/Code/BF2/External/gameswf/gameswf_stream.h @@ -33,6 +33,7 @@ namespace gameswf Sint16 read_s16(); Uint32 read_u32(); Sint32 read_s32(); + // SwiffPlayer.dll 0x1009F5B0: 0xFF extends the count to an unsigned word. int read_variable_count() { int count = read_u8(); diff --git a/Code/BF2/External/gameswf/gameswf_string.cpp b/Code/BF2/External/gameswf/gameswf_string.cpp index 8502147b3..0e78568b5 100644 --- a/Code/BF2/External/gameswf/gameswf_string.cpp +++ b/Code/BF2/External/gameswf/gameswf_string.cpp @@ -6,223 +6,151 @@ // Implementation of ActionScript String class. +#include "../../Platform/X87Compat.h" #include "base/tu_config.h" #include "gameswf_string.h" #include "gameswf_log.h" +#include "base/utf8.h" #include "base/smart_ptr.h" +#include namespace gameswf { + struct tu_string_as_object; + static void register_string_methods(tu_string_as_object* str); + static void set_string_result(as_value* result, const tu_string& text); + static void string_slice_result(const fn_call& fn, const tu_stringi& method, const tu_string& text); + static void string_case_result(const fn_call& fn, const tu_string& text, bool upper); + void string_method(const fn_call& fn, const tu_stringi& method_name, const tu_string& this_string) - // Executes the string method named by method_name. + // Dispatches String builtins; failed argument checks leave the result untouched. { - if (method_name == "charCodeAt") + if (method_name == "charAt" || method_name == "charCodeAt") { - int index = (int) fn.arg(0).to_number(); - if (index >= 0 && index < this_string.utf8_length()) + // SwiffPlayer.dll 0x1009B350 / 0x1009B410: byte offsets, index zero refused. + if (fn.nargs != 1) { - fn.result->set_double(this_string.utf8_char_at(index)); + log_error("String::%s needs one argument\n", method_name.c_str()); return; } - - fn.result->set_double(0); // FIXME: according to docs, we're supposed to return "NaN" - return; - } - else if (method_name == "charAt") - { - int index = (int) fn.arg(0).to_number(); - if (index >= 0 && index < this_string.utf8_length()) + const int index = bf2x87::toIntTruncate(fn.arg(0).to_number()); + if (index > 0 && index <= this_string.length()) { - tu_string result; - result += this_string.utf8_char_at(index); - fn.result->set_tu_string(result); + const char* p = this_string.c_str() + index; + if (method_name == "charAt") + { + const char text[2] = { *p, 0 }; + set_string_result(fn.result, tu_string(text)); + } + else + { + fn.result->set_double(utf8::decode_next_unicode_character(&p)); + } } - - fn.result->set_string(""); return; } else if (method_name == "fromCharCode") { - // Takes a variable number of args. Each arg - // is a numeric character code. Construct the - // string from the character codes. - - tu_string result; - - for (int i = 0; i < fn.nargs; i++) + // SwiffPlayer.dll 0x1009AFE0: only the first argument is encoded. + if (fn.nargs == 0) { - uint32 c = (uint32) fn.arg(i).to_number(); - result.append_wide_char(c); + log_error("String::fromCharCode needs one argument\n"); + return; } - - fn.result->set_tu_string(result); - return; - } - else if (method_name == "toUpperCase") - { - fn.result->set_tu_string(this_string.utf8_to_upper()); + // 0x1009B00A-0x1009B02F: construct/register before argument conversion. + as_object_interface* result = create_dice_string_object(NULL, 0); + const int code = bf2x87::toIntTruncate(fn.arg(0).to_number()); + char text[8]; + int offset = 0; + utf8::encode_unicode_character(text, &offset, static_cast(code)); + text[offset] = 0; + assign_dice_string_object_narrow(result, text); + fn.result->set_as_object_interface(result); return; } - else if (method_name == "toLowerCase") + else if (method_name == "toUpperCase" || method_name == "toLowerCase") { - fn.result->set_tu_string(this_string.utf8_to_lower()); + string_case_result(fn, this_string, method_name == "toUpperCase"); return; } - else if (method_name == "indexOf") + else if (method_name == "indexOf" || method_name == "lastIndexOf") { - if (fn.nargs < 1) + // SwiffPlayer.dll 0x1009B570 / 0x1009B640: forward search from an unchecked offset. + if (fn.nargs == 0) { - fn.result->set_double(-1); + log_error("String::%s needs atleast one argument\n", method_name.c_str()); return; } - else + const char* needle = fn.arg(0).to_string(); + int start = 0; + if (fn.nargs > 1) start = bf2x87::toIntTruncate(fn.arg(1).to_number()); + const char* text = this_string.c_str(); + const char* found = strstr(text + start, needle); + if (method_name == "lastIndexOf") { - int start_index = 0; - if (fn.nargs > 1) + const char* last = NULL; + while (found) { - start_index = (int) fn.arg(1).to_number(); + last = found; + found = strstr(found + 1, needle); } - const char* str = this_string.c_str(); - const char* p = strstr( - str + start_index, // FIXME: not UTF-8 correct! - fn.arg(0).to_string()); - if (p == NULL) - { - fn.result->set_double(-1); - return; - } - - fn.result->set_double(tu_string::utf8_char_count(str, p - str)); - return; - } - } - else if (method_name == "substring") - { - // Pull a slice out of this_string. - int start = 0; - int utf8_len = this_string.utf8_length(); - int end = utf8_len; - if (fn.nargs >= 1) - { - start = (int) fn.arg(0).to_number(); - start = iclamp(start, 0, utf8_len); - } - if (fn.nargs >= 2) - { - end = (int) fn.arg(1).to_number(); - end = iclamp(end, 0, utf8_len); + found = last; } - - if (end < start) swap(&start, &end); // dumb, but that's what the docs say - assert(end >= start); - - fn.result->set_tu_string(this_string.utf8_substring(start, end)); + fn.result->set_int(found ? static_cast(found - text) : -1); return; } - // [DICE-MOD SwiffPlayer #31: the rest of the String method set the shipped String object - // registers (sub_1009BB10: split, charAt, charCodeAt, concat, indexOf, lastIndexOf, slice, - // toLowerCase, toUpperCase, substr, substring, toString). Stock 2006 stopped at the TODO - // list that stood here; the login page's column lists split their construct parameters.] else if (method_name == "concat") { - tu_string result = this_string; - for (int i = 0; i < fn.nargs; i++) + // SwiffPlayer.dll 0x1009B4C0 returns a fresh narrow String object. + if (fn.nargs == 0) { - result += fn.arg(i).to_tu_string(); + log_error("String::concat needs atleast one argument\n"); + return; } - fn.result->set_tu_string(result); + tu_string text = this_string; + for (int i = 0; i < fn.nargs; ++i) text += fn.arg(i).to_string(); + set_string_result(fn.result, text); return; } - else if (method_name == "lastIndexOf") + else if (method_name == "split") { + // SwiffPlayer.dll 0x1009B110: empty fields consume an index but are not stored. + IF_VERBOSE_ACTION(log_msg("-- String split \n")); if (fn.nargs < 1) { - fn.result->set_double(-1); + log_error("String::split needs atleast one argument\n"); return; } - const tu_string needle = fn.arg(0).to_tu_string(); - const char* str = this_string.c_str(); - int best = -1; - if (needle.length() > 0) + const tu_string delimiter = fn.arg(0).to_tu_string(); + int limit = 0x7fffffff; + if (fn.nargs > 1) limit = bf2x87::toIntTruncate(fn.arg(1).to_number()); + smart_ptr result(create_array_object()); + const char* text = this_string.c_str(); + for (int index = 0; index < limit; ++index) { - for (const char* p = strstr(str, needle.c_str()); p != NULL; p = strstr(p + 1, needle.c_str())) + const char* found = strstr(text, delimiter.c_str()); + const int count = found ? static_cast(found - text) : static_cast(strlen(text)); + if (count != 0) { - best = tu_string::utf8_char_count(str, p - str); + char name[20]; + snprintf(name, sizeof(name), "%d", index); + result->set_member(name, as_value(tu_string(text, count).c_str())); } + if (!found) break; + text = found + delimiter.length(); } - fn.result->set_double(best); + fn.result->set_as_object_interface(result.get_ptr()); return; } else if (method_name == "length") { - fn.result->set_int(this_string.utf8_length()); + fn.result->set_int(this_string.length()); return; } - else if (method_name == "slice" || method_name == "substr") + else if (method_name == "slice" || method_name == "substr" || method_name == "substring") { - const int utf8_len = this_string.utf8_length(); - int start = fn.nargs >= 1 ? (int) fn.arg(0).to_number() : 0; - if (start < 0) start += utf8_len; - start = iclamp(start, 0, utf8_len); - int end = utf8_len; - if (fn.nargs >= 2) - { - if (method_name == "slice") - { - end = (int) fn.arg(1).to_number(); - if (end < 0) end += utf8_len; - } - else - { - end = start + (int) fn.arg(1).to_number(); - } - end = iclamp(end, 0, utf8_len); - } - if (end < start) end = start; - fn.result->set_tu_string(this_string.utf8_substring(start, end)); - return; - } - else if (method_name == "split") - { - as_object* arr = create_array_object(); - smart_ptr keep(arr); - if (fn.nargs < 1 || fn.arg(0).get_type() == as_value::UNDEFINED) - { - array_object_push(arr, as_value(this_string.c_str())); - } - else - { - const tu_string delim = fn.arg(0).to_tu_string(); - if (delim.length() == 0) - { - // An empty delimiter splits into single characters. - const int n = this_string.utf8_length(); - for (int i = 0; i < n; i++) - { - tu_string c; - c += this_string.utf8_char_at(i); - array_object_push(arr, as_value(c.c_str())); - } - } - else - { - const char* s = this_string.c_str(); - for (;;) - { - const char* p = strstr(s, delim.c_str()); - if (p == NULL) - { - array_object_push(arr, as_value(s)); - break; - } - tu_string piece(s, (int) (p - s)); - array_object_push(arr, as_value(piece.c_str())); - s = p + delim.length(); - } - } - } - fn.result->set_as_object_interface(arr); + string_slice_result(fn, method_name, this_string); return; } else if (method_name == "toString") @@ -230,7 +158,6 @@ namespace gameswf fn.result->set_tu_string(this_string); return; } - fn.result->set_undefined(); } @@ -239,18 +166,29 @@ namespace gameswf struct tu_string_as_object : public gameswf::as_object { tu_string m_string; - // [DICE-MOD SwiffPlayer #38] the shipped object's std::wstring at +60: set only when the object + // the shipped object's std::wstring at +60: set only when the object // is built from wide text (Locale.getString), a terminating 0 included; empty otherwise. array m_wide; + // SwiffPlayer.dll 0x1009C140 / 0x1009C110 destroys wide text, narrow + // text, then the object base. [CHOSEN, not recovered] S3 bridge: + // implicit destruction keeps the native wide array and object ownership. + + tu_string_as_object() + { + // SwiffPlayer.dll 0x1009BB10: empty narrow/wide values and builtin methods. + // [CHOSEN, not recovered] S3 bridge: native strings and parent interface. + register_string_methods(this); + } - // [DICE-MOD SwiffPlayer #31] `length` on a String object, as on a string value. + // `length` on a String object, as on a string value. // [#38] the shipped getter (sub_1009B090) answers the WIDE size first (+80) and falls back to // the narrow length only when no wide text is set. virtual bool get_member(const tu_stringi& name, as_value* val) { if (name == "length") { - val->set_int(m_wide.size() > 1 ? m_wide.size() - 1 : m_string.utf8_length()); + // SwiffPlayer.dll 0x1009B090: narrow length is measured in bytes. + val->set_int(m_wide.size() > 1 ? m_wide.size() - 1 : m_string.length()); return true; } return as_object::get_member(name, val); @@ -261,10 +199,17 @@ namespace gameswf // built from wide text keeps its narrow copy EMPTY (the shipped Locale.getString never fills // it), so string contexts see "" for a translation - a shipped quirk, preserved. virtual const char* get_text_value() const { return m_string.c_str(); } - virtual const Uint16* get_wide_text_value() const { return m_wide.size() > 1 ? &m_wide[0] : 0; } + // [#38] Never null for a String object: the shipped text setter (sub_10089440, 0x10089553) + // takes the object's std::wstring c_str(), which MSVC never returns null, so a String object + // always goes through the wide setter (vslot +0x110), an empty one included. + virtual const Uint16* get_wide_text_value() const + { + static const Uint16 s_empty = 0; + return m_wide.size() > 1 ? &m_wide[0] : &s_empty; + } }; - // [DICE-MOD SwiffPlayer #31] the forwarders for the methods the shipped String object registers. + // the forwarders for the methods the shipped String object registers. #define SWF_STRING_FORWARDER(fn_name, method) \ void fn_name(const fn_call& fn) \ { \ @@ -300,16 +245,8 @@ namespace gameswf void string_from_char_code(const fn_call& fn) { - tu_string_as_object* this_string_ptr = (tu_string_as_object*) fn.this_ptr; - assert(this_string_ptr); - - // tulrich: Ugh! The caller has done hash.get() on - // the method name to find the method, and now we're - // going to construct a new method name and run it - // through a big if-else. - // - // TODO do this more efficiently. - string_method(fn, tu_stringi("fromCharCode"), this_string_ptr->m_string); + // SwiffPlayer.dll 0x1009AFE0 never reads its receiver; the class has no payload. + string_method(fn, tu_stringi("fromCharCode"), tu_string()); } @@ -330,34 +267,105 @@ namespace gameswf void string_to_string(const fn_call& fn) { - tu_string_as_object* this_string_ptr = (tu_string_as_object*) fn.this_ptr; - assert(this_string_ptr); - - fn.result->set_tu_string(this_string_ptr->m_string); + // SwiffPlayer.dll 0x1009AFD0 returns the same object, including its wide payload. + fn.result->set_as_object_interface(fn.this_ptr); } - // [DICE-MOD SwiffPlayer #31/#38] the twelve methods the shipped String object registers on - // itself (sub_1009BB10), plus stock's fromCharCode - shared by the AS `String` constructor and - // the wide factory below. + as_object* create_dice_string_class() + { + // SwiffPlayer.dll 0x1009BA20: an object with fromCharCode, no text payload. + // [CHOSEN, not recovered] S3 bridge to the native parent/interface storage. + as_object* object = new as_object; + object->set_member("fromCharCode", &string_from_char_code); + return object; + } + + // SwiffPlayer.dll 0x1009BA20 registers fromCharCode in the base; 0x1009BB10 + // registers the instance methods in the order below. static void register_string_methods(tu_string_as_object* str) { - str->set_member("toString", &string_to_string); str->set_member("fromCharCode", &string_from_char_code); - str->set_member("charCodeAt", &string_char_code_at); - str->set_member("lastIndexOf", &string_last_index_of); str->set_member("split", &string_split); str->set_member("charAt", &string_char_at); + str->set_member("charCodeAt", &string_char_code_at); str->set_member("concat", &string_concat); str->set_member("indexOf", &string_index_of); + str->set_member("lastIndexOf", &string_last_index_of); str->set_member("slice", &string_slice); str->set_member("toLowerCase", &string_to_lower_case); str->set_member("toUpperCase", &string_to_upper_case); str->set_member("substr", &string_substr); str->set_member("substring", &string_substring); + str->set_member("toString", &string_to_string); + } + + // [CHOSEN, not recovered] S3 bridge to the current String storage and factory. + // Retail builtin results construct 0x1009BB10, then assign only the narrow payload. + static void set_string_result(as_value* result, const tu_string& text) + { + smart_ptr str(new tu_string_as_object); + str->m_string = text; + result->set_as_object_interface(str.get_ptr()); + } + + static void string_slice_result(const fn_call& fn, const tu_stringi& method, const tu_string& text) + { + // SwiffPlayer.dll 0x1009B730 / 0x1009B910 / 0x1009BFB0 preserve distinct + // length/conversion order. All allocate the result before copying the suffix. + if (fn.nargs == 0) + { + log_error("String::%s needs atleast one argument\n", method.c_str()); + return; + } + int length = 0; + if (method == "substr") length = text.length(); + int start = bf2x87::toIntTruncate(fn.arg(0).to_number()); + if (method == "substr" && start < 0) start += length; + if (method == "substring" && start < 0) start = 0; + if (method == "substring") length = text.length(); + int end = method == "substr" ? length - start : length; + if (fn.nargs > 1) + { + end = bf2x87::toIntTruncate(fn.arg(1).to_number()); + if (method == "substring" && end < 0) end = 0; + } + if (method == "slice") length = text.length(); + smart_ptr result(new tu_string_as_object); + if (start >= 0 && start < length) + { + result->m_string = text.c_str() + start; + // Retail forwards negative resize lengths too. The base tag owns the + // unresolved resize contract at 0x1006E3B0; no clamp belongs here. + if (method == "substr") result->m_string.resize(end); + else if (end < length) result->m_string.resize(end - start); + } + fn.result->set_as_object_interface(result.get_ptr()); } - // [DICE-MOD SwiffPlayer #38] DICE's String object built from wide text - what the shipped + static void string_case_result(const fn_call& fn, const tu_string& text, bool upper) + { + // SwiffPlayer.dll 0x1009B830 / 0x1009B8A0: construct, copy the narrow + // bytes, call the CRT's in-place case conversion, then publish the object. + smart_ptr result(new tu_string_as_object); + result->m_string = text; + char* bytes = const_cast(result->m_string.c_str()); +#if defined(_WIN32) + if (upper) _strupr(bytes); + else _strlwr(bytes); +#else + // [CHOSEN, not recovered] POSIX CRT bridge: bytewise native locale + // mapping, without UTF-8 decoding. MSVCR71 locale equivalence is unverified. + for (char* p = bytes; *p; ++p) + { + const unsigned char c = static_cast(*p); + *p = static_cast(upper ? std::toupper(c) : std::tolower(c)); + } +#endif + fn.result->set_as_object_interface(result.get_ptr()); + } + + // DICE's String object built from wide text - what the shipped // Locale.getString (sub_1004C650) returns: the wide payload set, the methods registered, the // narrow copy left empty (see get_text_value above). as_object_interface* create_dice_string_object(const Uint16* wide, int count) @@ -368,11 +376,10 @@ namespace gameswf str->m_wide.push_back(wide[i]); } str->m_wide.push_back(0); - register_string_methods(str); return str; } - // [DICE-MOD SwiffPlayer #38] Locale.getString1004C650 constructs its String + // Locale.getString1004C650 constructs its String // before the host lookup, then assigns out.c_str() at1004C6DE and clears the // narrow side at1004C6EC. This helper preserves that order without new slots. void assign_dice_string_object_wide(as_object_interface* object, const Uint16* wide) @@ -387,7 +394,7 @@ namespace gameswf str->m_string = ""; } - // [DICE-MOD SwiffPlayer #38] The narrow twin. Mod.getCurrentModName (sub_1004F950) builds the same + // The narrow twin. Mod.getCurrentModName (sub_1004F950) builds the same // object the other way round: it assigns the +44 tu_string from the host's plain mod name and // CLEARS the +60 wide side, so get_text_value answers the narrow copy and the length getter // falls through to it. Same object, opposite field. @@ -400,6 +407,7 @@ namespace gameswf void string_ctor(const fn_call& fn) { + // SwiffPlayer.dll 0x1008D670: construct/register before converting the argument. smart_ptr str = new tu_string_as_object; if (fn.nargs > 0) @@ -407,8 +415,6 @@ namespace gameswf str->m_string = fn.arg(0).to_tu_string(); } - register_string_methods(str.get_ptr()); - fn.result->set_as_object_interface(str.get_ptr()); } diff --git a/Code/BF2/External/gameswf/gameswf_styles.cpp b/Code/BF2/External/gameswf/gameswf_styles.cpp index 894d71e4e..147272e4b 100644 --- a/Code/BF2/External/gameswf/gameswf_styles.cpp +++ b/Code/BF2/External/gameswf/gameswf_styles.cpp @@ -19,6 +19,7 @@ namespace gameswf // gradient_record // + // SwiffPlayer.dll 0x100A3D10. gradient_record::gradient_record() : m_ratio(0) @@ -26,6 +27,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x100A3D30. void gradient_record::read(stream* in, int tag_type) { m_ratio = in->read_u8(); @@ -38,6 +40,7 @@ namespace gameswf // + // SwiffPlayer.dll 0x100A46C0. fill_style::fill_style() : m_type(0), @@ -48,15 +51,17 @@ namespace gameswf } + // SwiffPlayer.dll 0x100A4710; deleting veneer 0x100A4750. fill_style::~fill_style() { } + // SwiffPlayer.dll 0x100A41F0. void fill_style::read(stream* in, int tag_type, movie_definition_sub* md) { m_type = in->read_u8(); - IF_VERBOSE_PARSE(log_msg(" fill_style read type = 0x%X\n", m_type)); + IF_VERBOSE_PARSE(log_msg("fsr type = 0x%X\n", m_type)); if (m_type == 0x00) { @@ -67,7 +72,7 @@ namespace gameswf m_color.read_rgba(in); } - IF_VERBOSE_PARSE(log_msg(" color: "); + IF_VERBOSE_PARSE(log_msg("fsr color: "); m_color.print()); } else if (m_type == 0x10 || m_type == 0x12) @@ -105,7 +110,7 @@ namespace gameswf m_gradients[i].read(in, tag_type); } - IF_VERBOSE_PARSE(log_msg(" gradients: num_gradients = %d\n", num_gradients)); + IF_VERBOSE_PARSE(log_msg("fsr: num_gradients = %d\n", num_gradients)); // @@ hack. if (num_gradients > 0) @@ -131,7 +136,7 @@ namespace gameswf // 0x41: clipped bitmap fill int bitmap_char_id = in->read_u16(); - IF_VERBOSE_PARSE(log_msg(" bitmap_char = %d\n", bitmap_char_id)); + IF_VERBOSE_PARSE(log_msg("fsr: bitmap_char = %d\n", bitmap_char_id)); // Look up the bitmap character. m_bitmap_character = md->get_bitmap_character(bitmap_char_id); @@ -147,6 +152,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x100A3EE0. rgba fill_style::sample_gradient(int ratio) const // Return the color at the specified ratio into our gradient. // Ratio is in [0, 255]. @@ -178,6 +184,7 @@ namespace gameswf return m_gradients.back().m_color; } + // SwiffPlayer.dll 0x100A3FB0. gameswf::bitmap_info* fill_style::create_gradient_bitmap() const // Make a bitmap_info* corresponding to our gradient. // We can use this to set the gradient fill style. @@ -227,6 +234,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x100A4480. void fill_style::apply(int fill_side, float ratio) const // Push our style parameters into the renderer. { @@ -285,6 +293,15 @@ namespace gameswf } + // SwiffPlayer.dll 0x100A4520; method name [INFERRED]. + void fill_style::generate_gradient_bitmap(movie_definition_sub* md) + { + m_gradient_bitmap_info = create_gradient_bitmap(); + md->add_bitmap_info(m_gradient_bitmap_info.get_ptr()); + } + + + // SwiffPlayer.dll 0x100A4580. void fill_style::set_lerp(const fill_style& a, const fill_style& b, float t) // Sets this style to a blend of a and b. t = [0,1] { @@ -331,6 +348,7 @@ namespace gameswf // + // SwiffPlayer.dll 0x100A4140. line_style::line_style() : m_width(0) @@ -338,6 +356,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x100A3DB0. void line_style::read(stream* in, int tag_type) { m_width = in->read_u16(); @@ -345,11 +364,12 @@ namespace gameswf } + // SwiffPlayer.dll 0x100A3DE0. void line_style::apply(float ratio) const { UNUSED(ratio); gameswf::render::line_style_color(m_color); - gameswf::render::line_style_width(m_width); + gameswf::render::line_style_width(m_width * 0.05f); } } diff --git a/Code/BF2/External/gameswf/gameswf_styles.h b/Code/BF2/External/gameswf/gameswf_styles.h index d6e4b21fa..b7b89e9bb 100644 --- a/Code/BF2/External/gameswf/gameswf_styles.h +++ b/Code/BF2/External/gameswf/gameswf_styles.h @@ -30,6 +30,7 @@ namespace gameswf struct base_fill_style { + // Implicit vptr-only constructor: SwiffPlayer.dll 0x100A3D60. virtual void apply(int fill_side, float ratio) const = 0; }; @@ -38,20 +39,27 @@ namespace gameswf { fill_style(); virtual ~fill_style(); + // Implicit member assignment: SwiffPlayer.dll 0x10086550 copies type, + // color, gradient matrix/records, both held images, then bitmap matrix. void read(stream* in, int tag_type, movie_definition_sub* m); rgba sample_gradient(int ratio) const; gameswf::bitmap_info* create_gradient_bitmap() const; + // Regenerate the gradient and register its bitmap with the owning movie. + void generate_gradient_bitmap(movie_definition_sub* m); virtual void apply(int fill_side, float ratio) const; + // SwiffPlayer.dll 0x100A3CF0. rgba get_color() const { return m_color; } void set_color(rgba new_color) { m_color = new_color; } + // SwiffPlayer.dll 0x100A3D00. int get_type() const { return m_type; } - // [DICE-MOD SwiffPlayer: runtime-built fills. The drawing API (beginFill) needs a solid + // runtime-built fills. The drawing API (beginFill) needs a solid // style and the loadMovie image loader a tiled bitmap fill (type 0x40, the shipped loader's - // `v33 = 64`, matrix scale 0.05); the parser-only 2006 class had no way to build either.] - void set_solid(rgba color) { m_type = 0x00; m_color = color; } + // `v33 = 64`, matrix scale 0.05); the parser-only 2006 class had no way to build either. + // Store order in SwiffPlayer.dll 0x10097940. + void set_solid(rgba color) { m_color = color; m_type = 0x00; } void set_bitmap(bitmap_character_def* bc, const matrix& m, bool clamp) { m_type = clamp ? 0x41 : 0x40; @@ -59,6 +67,11 @@ namespace gameswf m_bitmap_matrix = m; } + // [CHOSEN, not recovered] S3 bridge exposing the fields written by + // SwiffPlayer.dll 0x1007C3B0 without exposing the native object layout. + void set_gradient(int type, const matrix& m) { m_type = type; m_gradient_matrix = m; } + void append_gradient(const gradient_record& record) { m_gradients.push_back(record); } + // For shape morphing void set_lerp(const fill_style& a, const fill_style& b, float t); @@ -99,6 +112,7 @@ namespace gameswf struct base_line_style { + // Implicit vptr-only constructor: SwiffPlayer.dll 0x100A3DA0. virtual void apply(float ratio) const = 0; }; @@ -110,9 +124,14 @@ namespace gameswf virtual void apply(float ratio) const; Uint16 get_width() const { return m_width; } + // SwiffPlayer.dll 0x10096250 / 0x10096260; [INFERRED] source-level names. + void set_width(Uint16 width) { m_width = width; } + void set_color(const rgba& color) { m_color = color; } + // SwiffPlayer.dll 0x1009F570; implicit member assignment at 0x1009F6F0. const rgba& get_color() const { return m_color; } - // [DICE-MOD SwiffPlayer: runtime-built line styles for the drawing API (lineStyle).] - void set(Uint16 width_twips, const rgba& color) { m_width = width_twips; m_color = color; } + // runtime-built line styles for the drawing API (lineStyle). + // Store order in SwiffPlayer.dll 0x10097980. + void set(Uint16 width_twips, const rgba& color) { m_color = color; m_width = width_twips; } private: friend struct morph2_character_def; diff --git a/Code/BF2/External/gameswf/gameswf_tesselate.cpp b/Code/BF2/External/gameswf/gameswf_tesselate.cpp index c48141a0f..a05403068 100644 --- a/Code/BF2/External/gameswf/gameswf_tesselate.cpp +++ b/Code/BF2/External/gameswf/gameswf_tesselate.cpp @@ -76,6 +76,7 @@ #include "gameswf_types.h" #include "base/utility.h" #include "base/container.h" +#include "../../Platform/X87Compat.h" #include @@ -93,8 +94,10 @@ namespace tesselate point m_end; int m_left_style, m_right_style, m_line_style; + // SwiffPlayer.dll 0x100A9E40: new array elements zero both points only. fill_segment() {} + // SwiffPlayer.dll 0x100A9F80: downward edges exchange endpoints and fills. fill_segment( const point& a, const point& b, @@ -120,19 +123,12 @@ namespace tesselate void flip() // Exchange end points, and reverse fill sides. { + // SwiffPlayer.dll 0x100A9E10; the line style is unchanged. swap(&m_begin, &m_end); // swap fill styles... swap(&m_left_style, &m_right_style); } - - float get_height() const - // Return segment height. - { - assert(m_end.m_y >= m_begin.m_y); - - return m_end.m_y - m_begin.m_y; - } }; @@ -152,18 +148,13 @@ namespace tesselate void begin_shape(trapezoid_accepter* accepter, float curve_error_tolerance) { - assert(accepter); + // SwiffPlayer.dll 0x100A9FF0: replace all shape state without guards. s_accepter = accepter; - // ensure we're not already in a shape or path. - // make sure our shape state is cleared out. - assert(s_current_segments.size() == 0); s_current_segments.resize(0); - assert(s_current_path.size() == 0); s_current_path.resize(0); - assert(curve_error_tolerance > 0); if (curve_error_tolerance > 0) { s_tolerance = curve_error_tolerance; @@ -184,6 +175,7 @@ namespace tesselate static int compare_segment_y(const void* a, const void* b) // For sorting segments by m_begin.m_y, and then by height. { + // SwiffPlayer.dll 0x100A9C40: heights stay in x87 registers, without a float store. const fill_segment* A = (const fill_segment*) a; const fill_segment* B = (const fill_segment*) b; @@ -196,8 +188,8 @@ namespace tesselate } else if (ay0 == by0) { - const float ah = A->get_height(); - const float bh = B->get_height(); + const bf2x87::Real ah = bf2x87::sub(bf2x87::Real(A->m_end.m_y), bf2x87::Real(ay0)); + const bf2x87::Real bh = bf2x87::sub(bf2x87::Real(B->m_end.m_y), bf2x87::Real(by0)); if (ah < bh) { @@ -222,6 +214,7 @@ namespace tesselate static int compare_segment_x(const void* a, const void* b) // For sorting segments by m_begin.m_x, and then by m_end.m_x. { + // SwiffPlayer.dll 0x100A9CA0: begin x, then end x; unordered compares return 1. const fill_segment* A = (const fill_segment*) a; const fill_segment* B = (const fill_segment*) b; @@ -260,6 +253,7 @@ namespace tesselate void output_current_segments() // Draw our shapes and lines, then clear the segment list. { + // SwiffPlayer.dll 0x100AA570: peel successive y intervals in place. if (s_shape_has_fill) { // @@ -268,7 +262,7 @@ namespace tesselate // sort by begining y (smaller first), then by height (shorter first) qsort( - &s_current_segments[0], + s_current_segments.size() ? &s_current_segments[0] : NULL, s_current_segments.size(), sizeof(s_current_segments[0]), compare_segment_y); @@ -315,7 +309,6 @@ namespace tesselate else { float ybottom = s_current_segments[next_base].m_begin.m_y; - assert(ybottom > ytop); peel_off_and_emit(base, next_base, ytop, ybottom); // don't update base; it's still active. @@ -332,7 +325,7 @@ namespace tesselate // s_current_segments[i0 through (i1-1)] and emit the clipped // trapezoids. Modifies the values in s_current_segments. { - assert(i0 < i1); + // SwiffPlayer.dll 0x100AA0F0: EDX is i0, ECX is i1 at both callers. if (y0 == y1) { @@ -345,20 +338,23 @@ namespace tesselate for (int i = i0; i < i1; i++) { fill_segment* f = &s_current_segments[i]; - assert(f->m_begin.m_y == y0); - assert(f->m_end.m_y >= y1); - float dy = f->m_end.m_y - f->m_begin.m_y; - float t = 1.0f; + // SwiffPlayer.dll 0x100AA150/0x100AA184: dy and intersection x + // are float stores; the quotient and interpolation stay in registers. + float dy = bf2x87::store(bf2x87::sub(bf2x87::Real(f->m_end.m_y), bf2x87::Real(f->m_begin.m_y))); + bf2x87::Real t = bf2x87::Real(1.0f); if (dy > 0) { - t = (y1 - f->m_begin.m_y) / dy; + t = bf2x87::div(bf2x87::sub(bf2x87::Real(y1), bf2x87::Real(f->m_begin.m_y)), bf2x87::Real(dy)); } point intersection; intersection.m_y = y1; - intersection.m_x = f->m_begin.m_x + (f->m_end.m_x - f->m_begin.m_x) * t; + intersection.m_x = bf2x87::store(bf2x87::add( + bf2x87::mul(bf2x87::sub(bf2x87::Real(f->m_end.m_x), bf2x87::Real(f->m_begin.m_x)), t), + bf2x87::Real(f->m_begin.m_x))); // Peel off. + // SwiffPlayer.dll 0x100AA0B0/0x100A9D40: resize-copy, then last element. slab.push_back(*f); slab.back().m_end = intersection; @@ -367,7 +363,7 @@ namespace tesselate } // Sort by x. - qsort(&slab[0], slab.size(), sizeof(slab[0]), compare_segment_x); + qsort(slab.size() ? &slab[0] : NULL, slab.size(), sizeof(slab[0]), compare_segment_x); // Emit the trapezoids in this slab. if (slab.size() > 0 @@ -412,11 +408,10 @@ namespace tesselate void end_shape() { + // SwiffPlayer.dll 0x100AA6E0: output, then clear only the accepter. output_current_segments(); s_accepter = NULL; - - s_current_path.release(); } @@ -429,6 +424,7 @@ namespace tesselate // Pass in -1 for styles that you want to disable. Otherwise pass in // the integral ID of the style for filling, to the left or right. { + // SwiffPlayer.dll 0x100AA2D0: flags accumulate across paths in a shape. s_current_left_style = style_left; s_current_right_style = style_right; s_current_line_style = line_style; @@ -436,7 +432,6 @@ namespace tesselate s_last_point.m_x = ax; s_last_point.m_y = ay; - assert(s_current_path.size() == 0); s_current_path.resize(0); s_current_path.push_back(s_last_point); @@ -457,6 +452,7 @@ namespace tesselate // Add a line running from the previous anchor point to the // given new anchor point. { + // SwiffPlayer.dll 0x100AA360: append the fill edge, update the pen, append the path point. point p(ax, ay); // s_current_segments is used for filling shapes. @@ -477,43 +473,36 @@ namespace tesselate static void curve(float p0x, float p0y, float p1x, float p1y, float p2x, float p2y) // Recursive routine to generate bezier curve within tolerance. { -#ifndef NDEBUG - static int recursion_count = 0; - recursion_count++; - if (recursion_count > 500) + // SwiffPlayer.dll 0x100AA410: recurse on the first half, loop on the second. + for (;;) { - assert(0); // probably a bug! - } -#endif // not NDEBUG - - // @@ use struct point in here? - - // Midpoint on line between two endpoints. - float midx = (p0x + p2x) * 0.5f; - float midy = (p0y + p2y) * 0.5f; - - // Midpoint on the curve. - float qx = (midx + p1x) * 0.5f; - float qy = (midy + p1y) * 0.5f; + const bf2x87::Real half = bf2x87::Real(0.5f); + const bf2x87::Real midx = bf2x87::mul(bf2x87::add(bf2x87::Real(p0x), bf2x87::Real(p2x)), half); + const bf2x87::Real midy = bf2x87::mul(bf2x87::add(bf2x87::Real(p0y), bf2x87::Real(p2y)), half); + + // SwiffPlayer.dll 0x100AA439/0x100AA447: only the curve midpoint is stored. + const float qx = bf2x87::store(bf2x87::mul(bf2x87::add(midx, bf2x87::Real(p1x)), half)); + const float qy = bf2x87::store(bf2x87::mul(bf2x87::add(bf2x87::Real(p1y), midy), half)); + const bf2x87::Real dist = bf2x87::add( + bf2x87::abs(bf2x87::sub(midx, bf2x87::Real(qx))), + bf2x87::abs(bf2x87::sub(midy, bf2x87::Real(qy)))); + if (dist < bf2x87::Real(s_tolerance)) + { + add_line_segment(p2x, p2y); + return; + } - float dist = fabsf(midx - qx) + fabsf(midy - qy); + // SwiffPlayer.dll 0x100AA48D/0x100AA49D: recursive arguments are floats. + const float c0y = bf2x87::store(bf2x87::mul(bf2x87::add(bf2x87::Real(p0y), bf2x87::Real(p1y)), half)); + const float c0x = bf2x87::store(bf2x87::mul(bf2x87::add(bf2x87::Real(p0x), bf2x87::Real(p1x)), half)); + curve(p0x, p0y, c0x, c0y, qx, qy); - if (dist < s_tolerance) - { - // Emit edge. -// add_line_segment(qx, qy); - add_line_segment(p2x, p2y); + // SwiffPlayer.dll 0x100AA4BF/0x100AA4CE: second-half controls are stored too. + p0x = qx; + p0y = qy; + p1y = bf2x87::store(bf2x87::mul(bf2x87::add(bf2x87::Real(p1y), bf2x87::Real(p2y)), half)); + p1x = bf2x87::store(bf2x87::mul(bf2x87::add(bf2x87::Real(p1x), bf2x87::Real(p2x)), half)); } - else - { - // Error is too large; subdivide. - curve(p0x, p0y, (p0x + p1x) * 0.5f, (p0y + p1y) * 0.5f, qx, qy); - curve(qx, qy, (p1x + p2x) * 0.5f, (p1y + p2y) * 0.5f, p2x, p2y); - } - -#ifndef NDEBUG - recursion_count--; -#endif // not NDEBUG } @@ -523,6 +512,7 @@ namespace tesselate // the given new anchor point (ax, ay), with (cx, cy) acting // as the control point in between. { + // SwiffPlayer.dll 0x100AA540: use the current pen as the first anchor. // Subdivide, and add line segments... curve(s_last_point.m_x, s_last_point.m_y, cx, cy, ax, ay); } @@ -531,6 +521,7 @@ namespace tesselate void end_path() // Mark the end of a set of edges that all use the same styles. { + // SwiffPlayer.dll 0x100AA060: accepter slot +4, then resize the path to zero. if (s_current_line_style >= 0 && s_current_path.size() > 1) { // diff --git a/Code/BF2/External/gameswf/gameswf_tesselate.h b/Code/BF2/External/gameswf/gameswf_tesselate.h index 931c918b4..81cb254a9 100644 --- a/Code/BF2/External/gameswf/gameswf_tesselate.h +++ b/Code/BF2/External/gameswf/gameswf_tesselate.h @@ -29,6 +29,7 @@ namespace gameswf // trapezoidation. struct trapezoid_accepter { + // Implicit vptr-only construction: SwiffPlayer.dll 0x10096410. virtual void accept_trapezoid(int style, const trapezoid& tr) = 0; virtual void accept_line_strip(int style, const point coords[], int coord_count) = 0; }; @@ -39,6 +40,7 @@ namespace gameswf // // The error tolerance tells the tesselator how much // geometric error is allowed along curve edges. + // SwiffPlayer.dll 0x100A9FF0 uses 1.0 for nonpositive or unordered tolerance. void begin_shape(trapezoid_accepter* accepter, float curve_error_tolerance); void end_shape(); diff --git a/Code/BF2/External/gameswf/gameswf_test_ogl.cpp b/Code/BF2/External/gameswf/gameswf_test_ogl.cpp deleted file mode 100644 index afe5571ce..000000000 --- a/Code/BF2/External/gameswf/gameswf_test_ogl.cpp +++ /dev/null @@ -1,920 +0,0 @@ -// gameswf_test_ogl.cpp -- Thatcher Ulrich 2003 -*- coding: utf-8;-*- - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - -// A minimal test player app for the gameswf library. - - -#include "SDL.h" -#include "SDL_thread.h" - -#include "gameswf.h" -#include -#include -#include "base/ogl.h" -#include "base/utility.h" -#include "base/container.h" -#include "base/tu_file.h" -#include "base/tu_types.h" -#include "gameswf_xmlsocket.h" - - -#ifdef HAVE_LIBXML -extern int xml_fd; // FIXME: this is the file descriptor - // from XMLSocket::connect(). This - // needs to be propogated up through - // the layers properly, but first I - // want to make sure it all works. -#endif // HAVE_LIBXML - - -void print_usage() -// Brief instructions. -{ - printf( - "gameswf_test_ogl -- a test player for the gameswf library.\n" - "\n" - "This program has been donated to the Public Domain.\n" - "See http://tulrich.com/geekstuff/gameswf.html for more info.\n" - "\n" - "usage: gameswf_test_ogl [options] movie_file.swf\n" - "\n" - "Plays a SWF (Shockwave Flash) movie, using OpenGL and the\n" - "gameswf library.\n" - "\n" - "options:\n" - "\n" - " -h Print this info.\n" - " -s Scale the movie up/down by the specified factor\n" - " -c Produce a core file instead of letting SDL trap it\n" - " -d num Number of milli-seconds to delay in main loop\n" - " -a Turn antialiasing on/off. (obsolete)\n" - " -v Be verbose; i.e. print log messages to stdout\n" - " -va Be verbose about movie Actions\n" - " -vp Be verbose about parsing the movie\n" - " -ml Specify the texture LOD bias (float, default is -1)\n" - " -p Run full speed (no sleep) and log frame rate\n" - " -e Use SDL Event thread\n" - " -1 Play once; exit when/if movie reaches the last frame\n" - " -r <0|1|2> 0 disables renderering & sound (good for batch tests)\n" - " 1 enables rendering & sound (default setting)\n" - " 2 enables rendering & disables sound\n" - " -t Timeout and exit after the specified number of seconds\n" - " -b Bit depth of output window (16 or 32, default is 16)\n" - "\n" - "keys:\n" - " CTRL-Q Quit/Exit\n" - " CTRL-W Quit/Exit\n" - " ESC Quit/Exit\n" - " CTRL-P Toggle Pause\n" - " CTRL-R Restart the movie\n" - " CTRL-[ or kp- Step back one frame\n" - " CTRL-] or kp+ Step forward one frame\n" - " CTRL-A Toggle antialiasing (doesn't work)\n" - " CTRL-T Debug. Test the set_variable() function\n" - " CTRL-G Debug. Test the get_variable() function\n" - " CTRL-M Debug. Test the call_method() function\n" - " CTRL-B Toggle background color\n" - ); -} - - -#define OVERSIZE 1.0f - -static int runThread(void *nothing); -static int doneYet = 0; - -static float s_scale = 1.0f; -static bool s_antialiased = false; -static int s_bit_depth = 16; -static bool s_verbose = false; -static bool s_background = true; -static bool s_measure_performance = false; -static bool s_event_thread = false; - -static void message_log(const char* message) -// Process a log message. -{ - if (s_verbose) - { - fputs(message, stdout); - fflush(stdout); // needed on osx for some reason - } -} - - -static void log_callback(bool error, const char* message) -// Error callback for handling gameswf messages. -{ - if (error) - { - // Log, and also print to stderr. - message_log(message); - fputs(message, stderr); - } - else - { - message_log(message); - } -} - - -static tu_file* file_opener(const char* url) -// Callback function. This opens files for the gameswf library. -{ - return new tu_file(url, "rb"); -} - - -static void fs_callback(gameswf::movie_interface* movie, const char* command, const char* args) -// For handling notification callbacks from ActionScript. -{ - message_log("fs_callback: '"); - message_log(command); - message_log("' '"); - message_log(args); - message_log("'\n"); -} - - -static void key_event(SDLKey key, bool down) -// For forwarding SDL key events to gameswf. -{ - gameswf::key::code c(gameswf::key::INVALID); - - if (key >= SDLK_a && key <= SDLK_z) - { - c = (gameswf::key::code) ((key - SDLK_a) + gameswf::key::A); - } - else if (key >= SDLK_F1 && key <= SDLK_F15) - { - c = (gameswf::key::code) ((key - SDLK_F1) + gameswf::key::F1); - } - else if (key >= SDLK_KP0 && key <= SDLK_KP9) - { - c = (gameswf::key::code) ((key - SDLK_KP0) + gameswf::key::KP_0); - } - else - { - // many keys don't correlate, so just use a look-up table. - struct - { - SDLKey sdlk; - gameswf::key::code gs; - } table[] = - { - { SDLK_RETURN, gameswf::key::ENTER }, - { SDLK_ESCAPE, gameswf::key::ESCAPE }, - { SDLK_LEFT, gameswf::key::LEFT }, - { SDLK_UP, gameswf::key::UP }, - { SDLK_RIGHT, gameswf::key::RIGHT }, - { SDLK_DOWN, gameswf::key::DOWN }, - // @@ TODO fill this out some more - { SDLK_UNKNOWN, gameswf::key::INVALID } - }; - - for (int i = 0; table[i].sdlk != SDLK_UNKNOWN; i++) - { - if (key == table[i].sdlk) - { - c = table[i].gs; - break; - } - } - } - - if (c != gameswf::key::INVALID) - { - gameswf::notify_key_event(c, down); - } -} - - - - -int main(int argc, char *argv[]) -{ - assert(tu_types_validate()); - - const char* infile = NULL; - - float exit_timeout = 0; - bool do_render = true; - bool do_sound = true; - bool do_loop = true; - bool sdl_abort = true; - int delay = 31; - float tex_lod_bias; - - // -1.0 tends to look good. - tex_lod_bias = -1.2f; - - for (int arg = 1; arg < argc; arg++) - { - if (argv[arg][0] == '-') - { - // Looks like an option. - - if (argv[arg][1] == 'h') - { - // Help. - print_usage(); - exit(1); - } - if (argv[arg][1] == 'c') - { - sdl_abort = false; - } - else if (argv[arg][1] == 's') - { - // Scale. - arg++; - if (arg < argc) - { - s_scale = fclamp((float) atof(argv[arg]), 0.01f, 100.f); - } - else - { - fprintf(stderr, "-s arg must be followed by a scale value\n"); - print_usage(); - exit(1); - } - } - else if (argv[arg][1] == 'a') - { - // Set antialiasing on or off. - arg++; - if (arg < argc) - { - s_antialiased = atoi(argv[arg]) ? true : false; - } - else - { - fprintf(stderr, "-a arg must be followed by 0 or 1 to disable/enable antialiasing\n"); - print_usage(); - exit(1); - } - } - else if (argv[arg][1] == 'b') - { - // Set default bit depth. - arg++; - if (arg < argc) - { - s_bit_depth = atoi(argv[arg]); - if (s_bit_depth != 16 && s_bit_depth != 32) - { - fprintf(stderr, "Command-line supplied bit depth %d, but it must be 16 or 32", s_bit_depth); - print_usage(); - exit(1); - } - } - else - { - fprintf(stderr, "-b arg must be followed by 16 or 32 to set bit depth\n"); - print_usage(); - exit(1); - } - } - else if (argv[arg][1] == 'd') - { - // Set a delay - arg++; - if (arg < argc) - { - delay = atoi(argv[arg]); - } - else - { - fprintf(stderr, "-d arg must be followed by number of milli-seconds to del in the main loop\n"); - print_usage(); - exit(1); - } - } - else if (argv[arg][1] == 'p') - { - // Enable frame-rate/performance logging. - s_measure_performance = true; - } - else if (argv[arg][1] == 'e') - { - // Use an SDL thread to handle events - s_event_thread = true; - } - else if (argv[arg][1] == '1') - { - // Play once; don't loop. - do_loop = false; - } - else if (argv[arg][1] == 'r') - { - // Set rendering on/off. - arg++; - if (arg < argc) - { - const int render_arg = atoi(argv[arg]); - switch (render_arg) { - case 0: - // Disable both - do_render = false; - do_sound = false; - break; - case 1: - // Enable both - do_render = true; - do_sound = true; - break; - case 2: - // Disable just sound - do_render = true; - do_sound = false; - break; - default: - fprintf(stderr, "-r must be followed by 0, 1 or 2 (%d is invalid)\n", - render_arg); - print_usage(); - exit(1); - break; - } - } else { - fprintf(stderr, "-r must be followed by 0 an argument to disable/enable rendering\n"); - print_usage(); - exit(1); - } - } - else if (argv[arg][1] == 't') - { - // Set timeout. - arg++; - if (arg < argc) - { - exit_timeout = (float) atof(argv[arg]); - } - else - { - fprintf(stderr, "-t must be followed by an exit timeout, in seconds\n"); - print_usage(); - exit(1); - } - } - else if (argv[arg][1] == 'v') - { - // Be verbose; i.e. print log messages to stdout. - s_verbose = true; - - if (argv[arg][2] == 'a') - { - // Enable spew re: action. - gameswf::set_verbose_action(true); - } - else if (argv[arg][2] == 'p') - { - // Enable parse spew. - gameswf::set_verbose_parse(true); - } - // ... - } - else if (argv[arg][1] == 'm') - { - if (argv[arg][2] == 'l') { - arg++; - tex_lod_bias = (float) atof(argv[arg]); - //printf("Texture LOD Bais is no %f\n", tex_lod_bias); - } - else - { - fprintf(stderr, "unknown variant of -m arg\n"); - print_usage(); - exit(1); - } - } - } - else - { - infile = argv[arg]; - } - } - - if (infile == NULL) - { - printf("no input file\n"); - print_usage(); - exit(1); - } - - gameswf::register_file_opener_callback(file_opener); - gameswf::register_fscommand_callback(fs_callback); - if (s_verbose == true) { - gameswf::register_log_callback(log_callback); - } - //gameswf::set_antialiased(s_antialiased); - - gameswf::sound_handler* sound = NULL; - gameswf::render_handler* render = NULL; - if (do_render) - { - if (do_sound) { - sound = gameswf::create_sound_handler_sdl(); - gameswf::set_sound_handler(sound); - } - render = gameswf::create_render_handler_ogl(); - gameswf::set_render_handler(render); - } - - // Get info about the width & height of the movie. - int movie_version = 0; - int movie_width = 0; - int movie_height = 0; - float movie_fps = 30.0f; - gameswf::get_movie_info(infile, &movie_version, &movie_width, &movie_height, &movie_fps, NULL, NULL); - if (movie_version == 0) - { - fprintf(stderr, "error: can't get info about %s\n", infile); - exit(1); - } - - int width = int(movie_width * s_scale); - int height = int(movie_height * s_scale); - - if (do_render) - { - // Initialize the SDL subsystems we're using. Linux - // and Darwin use Pthreads for SDL threads, Win32 - // doesn't. Otherwise the SDL event loop just polls. - if (sdl_abort) { - // Other flags are SDL_INIT_JOYSTICK | SDL_INIT_CDROM -#ifdef _WIN32 - if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO)) -#else - if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_EVENTTHREAD )) -#endif - { - fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError()); - exit(1); - } - } else { - fprintf(stderr, "warning: SDL won't trap core dumps \n"); -#ifdef _WIN32 - if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_NOPARACHUTE | SDL_INIT_EVENTTHREAD)) -#else - if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_NOPARACHUTE)) -#endif - { - fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError()); - exit(1); - } - } - - atexit(SDL_Quit); - - SDL_EnableKeyRepeat(250, 33); - - - if (s_bit_depth == 16) - { - // 16-bit color, surface creation is likely to succeed. - SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5); - SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5); - SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5); - SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 15); - SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); - SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1); - } - else - { - assert(s_bit_depth == 32); - - // 32-bit color etc, for getting dest alpha, - // for MULTIPASS_ANTIALIASING (see - // gameswf_render_handler_ogl.cpp). - SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); - SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); - SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); - SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8); - SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); - SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); - SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1); - } - - // Change the LOD BIAS values to tweak blurriness. - if (tex_lod_bias != 0.0f) { -#ifdef FIX_I810_LOD_BIAS - // If 2D textures weren't previously enabled, enable - // them now and force the driver to notice the update, - // then disable them again. - if (!glIsEnabled(GL_TEXTURE_2D)) { - // Clearing a mask of zero *should* have no - // side effects, but coupled with enbling - // GL_TEXTURE_2D it works around a segmentation - // fault in the driver for the Intel 810 chip. - glEnable(GL_TEXTURE_2D); - glClear(0); - glDisable(GL_TEXTURE_2D); - } -#endif // FIX_I810_LOD_BIAS - glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, tex_lod_bias); - } - - // Set the video mode. - if (SDL_SetVideoMode(width, height, s_bit_depth, SDL_OPENGL) == 0) - { - fprintf(stderr, "SDL_SetVideoMode() failed."); - exit(1); - } - - ogl::open(); - - // Turn on alpha blending. - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - - // Turn on line smoothing. Antialiased lines can be used to - // smooth the outsides of shapes. - glEnable(GL_LINE_SMOOTH); - glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); // GL_NICEST, GL_FASTEST, GL_DONT_CARE - - glMatrixMode(GL_PROJECTION); - glOrtho(-OVERSIZE, OVERSIZE, OVERSIZE, -OVERSIZE, -1, 1); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - - // We don't need lighting effects - glDisable(GL_LIGHTING); - // glColorPointer(4, GL_UNSIGNED_BYTE, 0, *); - // glInterleavedArrays(GL_T2F_N3F_V3F, 0, *) - glPushAttrib (GL_ALL_ATTRIB_BITS); - } - - // Load the actual movie. - gameswf::movie_definition* md = gameswf::create_library_movie(infile); - if (md == NULL) - { - fprintf(stderr, "error: can't create a movie from '%s'\n", infile); - exit(1); - } - gameswf::movie_interface* m = create_library_movie_inst(md); - if (m == NULL) - { - fprintf(stderr, "error: can't create movie instance\n"); - exit(1); - } - gameswf::set_current_root(m); - - // Mouse state. - int mouse_x = 0; - int mouse_y = 0; - int mouse_buttons = 0; - - float speed_scale = 1.0f; - Uint32 start_ticks = 0; - if (do_render) - { - start_ticks = SDL_GetTicks(); - - } - Uint32 last_ticks = start_ticks; - int frame_counter = 0; - int last_logged_fps = last_ticks; - - - SDL_Thread *thread = NULL; - if (s_event_thread) { - thread = SDL_CreateThread(runThread, NULL); - if ( thread == NULL) { - fprintf(stderr, "Unable to create thread: %s\n", SDL_GetError()); - } - } - - - for (;;) - { - Uint32 ticks; - if (do_render) - { - ticks = SDL_GetTicks(); - } - else - { - // Simulate time. - ticks = last_ticks + (Uint32) (1000.0f / movie_fps); - } - int delta_ticks = ticks - last_ticks; - float delta_t = delta_ticks / 1000.f; - last_ticks = ticks; - - // Check auto timeout counter. - if (exit_timeout > 0 - && ticks - start_ticks > (Uint32) (exit_timeout * 1000)) - { - // Auto exit now. - break; - } - - bool ret = true; - if (do_render) - { - SDL_Event event; - // Handle input. - while (ret) - { -#ifdef HAVE_LIBXML - if (s_event_thread && xml_fd > 0) { - ret = SDL_WaitEvent(&event) ? true : false; - } else { - ret = SDL_PollEvent(&event) ? true : false; - } -#else - ret = SDL_PollEvent(&event) ? true : false; -#endif - - //printf("EVENT Type is %d\n", event.type); - switch (event.type) - { - case SDL_USEREVENT: - //printf("SDL_USER_EVENT at %s, code %d%d\n", __FUNCTION__, __LINE__, event.user.code); - ret = false; - break; - case SDL_KEYDOWN: - { - SDLKey key = event.key.keysym.sym; - bool ctrl = (event.key.keysym.mod & KMOD_CTRL) != 0; - - if (key == SDLK_ESCAPE - || (ctrl && key == SDLK_q) - || (ctrl && key == SDLK_w)) - { - goto done; - } - else if (ctrl && key == SDLK_p) - { - // Toggle paused state. - if (m->get_play_state() == gameswf::movie_interface::STOP) - { - m->set_play_state(gameswf::movie_interface::PLAY); - } - else - { - m->set_play_state(gameswf::movie_interface::STOP); - } - } - else if (ctrl && key == SDLK_r) - { - // Restart the movie. - m->restart(); - } - else if (ctrl && (key == SDLK_LEFTBRACKET || key == SDLK_KP_MINUS)) - { - m->goto_frame(m->get_current_frame()-1); - } - else if (ctrl && (key == SDLK_RIGHTBRACKET || key == SDLK_KP_PLUS)) - { - m->goto_frame(m->get_current_frame()+1); - } - else if (ctrl && key == SDLK_a) - { - // Toggle antialiasing. - s_antialiased = !s_antialiased; - //gameswf::set_antialiased(s_antialiased); - } - else if (ctrl && key == SDLK_t) - { - // test text replacement / variable setting: - m->set_variable("test.text", "set_edit_text was here...\nanother line of text for you to see in the text box\nSome UTF-8: ñö£ç°ÄÀÔ¿"); - } - else if (ctrl && key == SDLK_g) - { - // test get_variable. - message_log("testing get_variable: '"); - message_log(m->get_variable("test.text")); - message_log("'\n"); - } - else if (ctrl && key == SDLK_m) - { - // Test call_method. - const char* result = m->call_method( - "test_call", - "%d, %f, %s, %ls", - 200, - 1.0f, - "Test string", - L"Test long string"); - - if (result) - { - message_log("call_method: result = "); - message_log(result); - message_log("\n"); - } - else - { - message_log("call_method: null result\n"); - } - } - else if (ctrl && key == SDLK_b) - { - // toggle background color. - s_background = !s_background; - } - else if (ctrl && key == SDLK_f) //xxxxxx - { - extern bool gameswf_debug_show_paths; - gameswf_debug_show_paths = !gameswf_debug_show_paths; - } - else if (ctrl && key == SDLK_EQUALS) - { - float f = gameswf::get_curve_max_pixel_error(); - f *= 1.1f; - gameswf::set_curve_max_pixel_error(f); - printf("curve error tolerance = %f\n", f); - } - else if (ctrl && key == SDLK_MINUS) - { - float f = gameswf::get_curve_max_pixel_error(); - f *= 0.9f; - gameswf::set_curve_max_pixel_error(f); - printf("curve error tolerance = %f\n", f); - } - - key_event(key, true); - - break; - } - - case SDL_KEYUP: - { - SDLKey key = event.key.keysym.sym; - key_event(key, false); - break; - } - - case SDL_MOUSEMOTION: - mouse_x = (int) (event.motion.x / s_scale); - mouse_y = (int) (event.motion.y / s_scale); - break; - - case SDL_MOUSEBUTTONDOWN: - case SDL_MOUSEBUTTONUP: - { - int mask = 1 << (event.button.button - 1); - if (event.button.state == SDL_PRESSED) - { - mouse_buttons |= mask; - } - else - { - mouse_buttons &= ~mask; - } - break; - } - - case SDL_QUIT: - goto done; - break; - - default: - break; - } - } - } - - m = gameswf::get_current_root(); - gameswf::delete_unused_root(); - - m->set_display_viewport(0, 0, width, height); - m->set_background_alpha(s_background ? 1.0f : 0.05f); - - m->notify_mouse_state(mouse_x, mouse_y, mouse_buttons); - - m->advance(delta_t * speed_scale); - - if (do_render) - { - glDisable(GL_DEPTH_TEST); // Disable depth testing. - glDrawBuffer(GL_BACK); - } - m->display(); - frame_counter++; - - if (do_render) - { - SDL_GL_SwapBuffers(); - //glPopAttrib (); - - if (s_measure_performance == false) - { - // Don't hog the CPU. - SDL_Delay(delay); - } - else - { - // Log the frame rate every second or so. - if (last_ticks - last_logged_fps > 1000) - { - float delta = (last_ticks - last_logged_fps) / 1000.f; - - if (delta > 0) - { - printf("fps = %3.1f\n", frame_counter / delta); - } - else - { - printf("fps = *inf*\n"); - } - - last_logged_fps = last_ticks; - frame_counter = 0; - } - } - } - - // See if we should exit. - if (do_loop == false - && m->get_current_frame() + 1 == md->get_frame_count()) - { - // We're reached the end of the movie; exit. - break; - } - } - -done: - doneYet = 1; - SDL_KillThread(thread); // kill the network read thread - //SDL_Quit(); - - if (md) md->drop_ref(); - if (m) m->drop_ref(); - delete sound; - delete render; - - // For testing purposes, throw some keypresses into gameswf, - // to make sure the key handler is properly using weak - // references to listeners. - gameswf::notify_key_event(gameswf::key::A, true); - gameswf::notify_key_event(gameswf::key::B, true); - gameswf::notify_key_event(gameswf::key::C, true); - - // Clean up gameswf as much as possible, so valgrind will help find actual leaks. - gameswf::clear(); - - return 0; -} - -static int -runThread(void *nothing) -{ -#ifdef HAVE_LIBXML - - //int i = 123; - int val; - int count = 0; - SDL_Event *ptr; -#if 1 - SDL_Event ev; - ev.type = SDL_USEREVENT; - ev.user.code = 0; - ev.user.data1 = 0; - ev.user.data2 = 0; - ptr = &ev; -#else - ptr = (SDL_Event *)ev_ptr; - ptr->type = SDL_USEREVENT; - ptr->user.code = 0; - ptr->user.data1 = 0; - ptr->user.data2 = 0; -#endif - - printf("Initializing event thread...\n"); - - while (!doneYet) { - //ptr->user.data1 = (void *)i; - // FIXME: this file descriptor is hardcoded so this - // doesn't work under GDB right now. - if ((val = gameswf::check_sockets(xml_fd)) == -1) { - sleep(100); - continue; - } - s_event_thread = true; - // Don't push an event if there is already one in the - // queue. XMLSocket::onData() will come around and get - // the data anyway. - count = SDL_PeepEvents(ptr, 1, SDL_PEEKEVENT, SDL_USEREVENT); - // printf("%d User Events in queue\n", count); - if ((count == 0) && (val >= 0)) { - //printf("Pushing User Event on queue\n"); - SDL_PushEvent(ptr); - SDL_Delay(300); - } - } -#endif // HAVE_LIBXML - - return 0; -} - - -// Local Variables: -// mode: C++ -// c-basic-offset: 8 -// tab-width: 8 -// indent-tabs-mode: t -// End: diff --git a/Code/BF2/External/gameswf/gameswf_test_ogl.exe b/Code/BF2/External/gameswf/gameswf_test_ogl.exe deleted file mode 100644 index f81e53a68..000000000 Binary files a/Code/BF2/External/gameswf/gameswf_test_ogl.exe and /dev/null differ diff --git a/Code/BF2/External/gameswf/gameswf_text.cpp b/Code/BF2/External/gameswf/gameswf_text.cpp index 73cfbc5f5..c6171ced8 100644 --- a/Code/BF2/External/gameswf/gameswf_text.cpp +++ b/Code/BF2/External/gameswf/gameswf_text.cpp @@ -6,16 +6,21 @@ // Code for the text tags. +#include +#include +#include +#include #include "base/utf8.h" +#include "../../Platform/X87Compat.h" #include "base/utility.h" #include "gameswf_impl.h" #include "gameswf_shape.h" #include "gameswf_stream.h" #include "gameswf_log.h" +#include "gameswf_profile.h" #include "gameswf_font.h" #include "gameswf_fontlib.h" #include "gameswf_render.h" -#include "gameswf_textformat.h" namespace gameswf { @@ -36,6 +41,7 @@ namespace gameswf bool m_has_x_offset; bool m_has_y_offset; + // SwiffPlayer.dll 0x10084DB0. text_style() : m_font_id(-1), @@ -75,6 +81,14 @@ namespace gameswf text_style m_style; array m_glyphs; + // SwiffPlayer.dll 0x100864E0 / 0x10086520; deleting entry 0x10086640. + // Native members own their storage. + text_glyph_record() = default; + ~text_glyph_record() = default; + // SwiffPlayer.dll 0x10085E80: style assignment followed by a deep glyph-array copy. + text_glyph_record& operator=(const text_glyph_record&) = default; + + // SwiffPlayer.dll 0x10085990. void read(stream* in, int glyph_count, int glyph_bits, int advance_bits) { m_glyphs.resize(glyph_count); @@ -219,6 +233,8 @@ namespace gameswf matrix m_matrix; array m_text_glyph_records; + // SwiffPlayer.dll 0x10086AB0. [CHOSEN, not recovered] S3 bridge: + // the loader publishes the native resource ID separately. text_character_def(movie_definition_sub* root_def) : m_root_def(root_def) @@ -226,6 +242,18 @@ namespace gameswf assert(m_root_def); } + // SwiffPlayer.dll 0x100875A0; deleting entry 0x10087570. + // Array cleanup precedes the resource base. + ~text_character_def() = default; + + // SwiffPlayer.dll 0x10086B40. + // [CHOSEN, not recovered] S3 bridge: + // retained out-parameter adapter for the native text callers. + rect* get_text_bounds(rect* out) const { *out = m_rect; return out; } + // SwiffPlayer.dll 0x10086B40, exposed through native typed dispatch. + rect get_bound_copy() const override { return m_rect; } + + // SwiffPlayer.dll 0x100867A0. void read(stream* in, int tag_type, movie_definition_sub* m) { assert(m != NULL); @@ -239,8 +267,6 @@ namespace gameswf IF_VERBOSE_PARSE(log_msg("begin text records\n")); - bool last_record_was_style_change = false; - text_style style; for (;;) { @@ -253,14 +279,10 @@ namespace gameswf break; } - // Style changes and glyph records just alternate. - // (Contrary to what most SWF references say!) - if (last_record_was_style_change == false) + if ((first_byte & 0x80) != 0) { // This is a style change. - last_record_was_style_change = true; - bool has_font = (first_byte >> 3) & 1; bool has_color = (first_byte >> 2) & 1; bool has_y_offset = (first_byte >> 1) & 1; @@ -319,15 +341,7 @@ namespace gameswf { // Read the glyph record. - last_record_was_style_change = false; - - int glyph_count = first_byte; - -// if (! last_record_was_style_change) -// { -// glyph_count &= 0x7F; -// } -// // else { Don't mask the top bit; the first record is allowed to have > 127 glyphs. } + int glyph_count = first_byte & 0x7F; m_text_glyph_records.resize(m_text_glyph_records.size() + 1); m_text_glyph_records.back().m_style = style; @@ -339,14 +353,16 @@ namespace gameswf } - void display(character* inst) - // Draw the string. + // SwiffPlayer.dll 0x10086B70, definition table 0x100E1154 +0x10. + // The shipped static-text definition has no drawing effects. + void display(character* /*inst*/) { - display_glyph_records(m_matrix, inst, m_text_glyph_records, m_root_def); } }; + // SwiffPlayer.dll 0x10086B80. [CHOSEN, not recovered] S3 bridge: + // the native factory assigns the resource ID when publishing the definition. void define_text_loader(stream* in, int tag_type, movie_definition_sub* m) // Read a DefineText tag. { @@ -376,7 +392,6 @@ namespace gameswf movie_definition_sub* m_root_def; rect m_rect; tu_string m_default_name; - text_format m_format; bool m_word_wrap; bool m_multiline; bool m_password; // show asterisks instead of actual characters @@ -435,6 +450,9 @@ namespace gameswf float m_leading; // extra space between lines (in addition to default font line spacing) tu_string m_default_text; + // SwiffPlayer.dll 0x10085300 initializes the flags, font/layout and colors. + // [CHOSEN, not recovered] S3 bridge: the loader assigns the native resource + // ID separately. edit_text_character_def(movie_definition_sub* root_def) : m_root_def(root_def), @@ -450,7 +468,7 @@ namespace gameswf m_font_id(-1), m_font(NULL), m_text_height(1.0f), - m_max_length(0), + m_max_length(1024), m_alignment(ALIGN_LEFT), m_left_margin(0.0f), m_right_margin(0.0f), @@ -462,20 +480,29 @@ namespace gameswf m_color.set(0, 0, 0, 255); } - // Set the format of the text - void set_format(text_format &format) - { - m_format = format; - } - + // SwiffPlayer.dll 0x10085C70; deleting entry 0x10085C40. ~edit_text_character_def() { } + // SwiffPlayer.dll 0x100853E0. + // [CHOSEN, not recovered] S3 bridge: + // retained out-parameter adapter for the native text callers. + rect* get_text_bounds(rect* out) const { *out = m_rect; return out; } + // SwiffPlayer.dll 0x100853E0, exposed through native typed dispatch. + rect get_bound_copy() const override { return m_rect; } + + // SwiffPlayer.dll 0x10085410 / 0x10085420. + virtual float get_height_local() { return m_rect.height(); } + virtual float get_width_local() { return m_rect.width(); } + // SwiffPlayer.dll 0x10085430, forwarding to rect::point_test at 0x1009E320. + virtual bool point_test_local(float x, float y) { return m_rect.point_test(x, y); } + character* create_character_instance(movie* parent, int id); + // SwiffPlayer.dll 0x10085A00. void read(stream* in, int tag_type, movie_definition_sub* m) { assert(m != NULL); @@ -549,7 +576,7 @@ namespace gameswf // - // [DICE-MOD SwiffPlayer #37: DICE's text field. The shipped SwiffPlayer replaced gameswf's + // DICE's text field. The shipped SwiffPlayer replaced gameswf's // edit_text_character with a field that lays its text out through RENDERER-SIDE text-line objects // (render::text_* - one "font wrapper" per laid-out line, filled a character at a time so the // renderer can measure for word wrap), draws them at device size, and is the game's keyboard @@ -558,13 +585,85 @@ namespace gameswf // display sub_100882F0, mouse sub_10088650, key sub_10088ED0, insert sub_10088A70, delete // sub_10088DB0, focus sub_10087AC0, members sub_10089440 / sub_10087C60, notify paths // SwiffPlayer_notifyChar / setTextInput / getTextInput0/1. The stock glyph layout stays as the - // fallback the shipped keeps (sub_10086C00) for a field whose font has no renderer name.] + // fallback the shipped keeps (sub_10086C00) for a field whose font has no renderer name. struct edit_text_character; static edit_text_character* s_focused_field = NULL; // dword_100F8EE0 + // SwiffPlayer.dll 0x100D6C80 -> 0x10072300 destroys this borrowed-pointer array. static array s_tab_table; // dword_100F8CB4 / dword_100F8CB8 + + // SwiffPlayer.dll 0x10085950; the caller supplies a valid Tab index. + static void register_text_tab(int index, edit_text_character* field) + { + if (s_tab_table.size() <= index) + { + s_tab_table.resize(index + 1); + } + s_tab_table[index] = field; + } static tu_string s_text_clipboard; // `src` static bool s_mod_shift = false, s_mod_alt = false, s_mod_ctrl = false, s_mod_caps = false; // byte_100F8EE8..EB + // Convert narrow text into a bounded UTF-16 buffer. Return the unit count + // excluding a copied terminator, or size_t(-1) on decoding failure. Do not + // repair or terminate the buffer after failure or capacity exhaustion. + static size_t text_mbstowcs(Uint16* destination, const char* source, size_t capacity) + { + // MSVCR71 7.10.3052 mbstowcs 0x7C3550C3 -> 0x7C354FC8: + // the C locale widens unsigned bytes, including bytes above 0x7F. + const char* locale = std::setlocale(LC_CTYPE, NULL); + if (strcmp(locale, "C") == 0 || strcmp(locale, "POSIX") == 0) + { + size_t count = 0; + while (count < capacity) + { + destination[count] = static_cast(source[count]); + if (source[count] == 0) return count; + ++count; + } + return count; + } +#if defined(_WIN32) + static_assert(sizeof(wchar_t) == sizeof(Uint16), "Windows text uses UTF-16"); + return std::mbstowcs(reinterpret_cast(destination), source, capacity); +#else + // [CHOSEN, not recovered] POSIX locale/wchar_t adapter for the macOS + // port: native multibyte decoding, encoded as UTF-16. Its locale names, + // code pages and error-prefix writes are not MSVCR71 emulation. + std::mbstate_t state = {}; + size_t count = 0; + while (count < capacity) + { + wchar_t character; + const size_t bytes = std::mbrtowc(&character, source, MB_CUR_MAX, &state); + if (bytes == static_cast(-1) || bytes == static_cast(-2)) + { + errno = EILSEQ; + return static_cast(-1); + } + if (bytes == 0) + { + destination[count] = 0; + return count; + } + const Uint32 codepoint = static_cast(character); + if (codepoint > 0x10FFFFu) + { + errno = EILSEQ; + return static_cast(-1); + } + if (codepoint <= 0xFFFFu) destination[count++] = static_cast(codepoint); + else + { + if (capacity - count < 2) return count; + destination[count++] = static_cast(0xD800u + ((codepoint - 0x10000u) >> 10)); + destination[count++] = static_cast(0xDC00u + ((codepoint - 0x10000u) & 0x3FFu)); + } + source += bytes; + } + return count; +#endif + } + // The digit-row keymap byte_100EC988 (three entries per key code 48..57: plain, shifted, AltGr). // A Swedish layout: shift-2 is ", shift-4 is ¤, AltGr-2 is @, AltGr-7 is {. static const unsigned char s_digit_keymap[30] = @@ -579,12 +678,9 @@ namespace gameswf array m_text_glyph_records; array m_dummy_style; // used to pass a color on to shape_character::display() array m_dummy_line_style; - rect m_text_bounding_box; // bounds of dynamic text, as laid out tu_string m_text; // +300 // DICE's members (shipped offsets in the comments). - array m_lines; // +8696/+8700: the renderer text-line objects, one per laid-out line - tu_string m_font_name; // +8680 array m_wide_text; // +316 (a std::wstring): set through a wide String object; empty -> m_text bool m_border; // +264 bool m_background; // +269 @@ -596,16 +692,26 @@ namespace gameswf bool m_first_mouse_frame; // +288 bool m_dragging; // +289 float m_drag_x, m_drag_y; // +292 / +296 (twips, local) - Uint16 m_sel_start, m_sel_end, m_caret; // +244 / +246 / +248 + Sint16 m_caret_x, m_caret_y; // +244 / +246: glyph-layout caret coordinates + Uint16 m_caret; // +248: character index, independent of renderer selection float m_blink_time; // +252: advance() accumulates, display blinks on (int)(t*3)&1, edits reset bool m_lines_dirty; // +344 bool m_password; // +345 int m_tab_index; // +348 int m_max_chars; // +352 + // +368 (0x170): the last height sub_10084DE0 was asked for + // (0x10084E01 stores its int argument before the scale test), i.e. formatText's laid-out + // height in pixels. `textHeight` answers it (vslot 0x10C = 0x10087A90, `mov eax,[ecx+170h]`); + // the constructor seeds 666 (0x1008772C). + int m_text_height_px; tu_string m_restrict; // +356/+360 as_value m_on_changed; // +376 as_value m_on_set_focus; // +408 as_environment m_as_environment; // +440 + // SwiffPlayer.dll 0x10089E16..0x10089E58 destroys the font name, + // environment and focus handler in that order after releasing lines. + tu_string m_font_name; // +8680 + array m_lines; // +8696/+8700: renderer text lines edit_text_character(movie* parent, edit_text_character_def* def, int id) : @@ -621,13 +727,16 @@ namespace gameswf m_first_mouse_frame(true), m_dragging(false), m_drag_x(0), m_drag_y(0), - m_sel_start(0), m_sel_end(0), m_caret(0), + m_caret_x(0), m_caret_y(0), m_caret(0), m_blink_time(0), m_lines_dirty(false), m_password(false), m_tab_index(-1), - m_max_chars(0) + m_max_chars(0), + m_text_height_px(666) { + // SwiffPlayer.dll 0x100875C0. Native character/Array/environment + // ownership uses the S3 bridges declared on those types. assert(parent); assert(m_def); m_as_environment.set_target(this); @@ -637,56 +746,91 @@ namespace gameswf m_border = m_def->m_border; m_background = m_def->m_border; m_text_color = m_def->m_color; + // 0x10087815 appends the initial fill style before the parent Tab + // query and renderer callbacks, even for empty text. + m_dummy_style.push_back(fill_style()); m_password = m_def->m_password; m_max_chars = m_def->m_max_length; - // The Tab index the parent hands out (shipped: parent vslot +112). [INFERRED: the - // character id - the value the shipped call returns is not attested beyond "an int >= 0".] - set_tab_index(id); + // SwiffPlayer.dll 0x10087879 calls parent +0x70, the inherited Tab + // index (sprite target 0x1007FB40), independently of placement ID. + if (parent) set_tab_index(parent->get_tab_index()); - // The renderer font: when the movie resolves the def's font to a NAME (the export name of - // the font sharing its face - "StandardTextBold" for the login page's TradeGothic fields, - // see get_exported_font_name), the first text line is created now (height in pixels); - // without one the field keeps the stock glyph layout and draws no text - as the shipped - // does for a face the archive has no file for. - if (m_def->m_font && m_def->m_root_def) + // 0x100878AC..0x100878F4 resolves the definition's font ID, calls + // the renderer even for an empty exported name, and appends its + // result even when null. [CHOSEN, not recovered] S3 bridge: the + // definition's native dictionary replaces retail's current-root owner. + if (m_def->m_root_def->get_export_name(m_def->m_font_id, &m_font_name)) { - tu_string exported; - if (m_def->m_root_def->get_exported_font_name(m_def->m_font, &exported) && exported.length() > 0) - { - m_font_name = exported; - void* line = render::text_create(m_font_name.c_str(), (int) (m_def->m_text_height * 0.05f)); - if (line) - { - m_lines.push_back(line); - } - } + const int height = bf2x87::toIntTruncate(bf2x87::mul( + bf2x87::Real(m_def->m_text_height), bf2x87::Real(0.05f))); + m_lines.push_back(render::text_create(m_font_name.c_str(), height)); } set_text_value(m_def->m_default_text.c_str()); - m_dummy_style.push_back(fill_style()); - reset_bounding_box(0, 0); } + // SwiffPlayer.dll 0x10089D50; deleting wrapper 0x10089D10. The member + // and base destructors supply the inspected release sequence below. + // [CHOSEN, not recovered] S3 bridge: the separately owned arguments + // Array can outlive this field, unlike retail's embedded Array. Native + // mask/prototype ownership and issue #7 graph teardown remain in use. ~edit_text_character() { - // sub_10089D50: release the renderer lines, leave the Tab table and the focus. + // SwiffPlayer.dll 0x10089D50 removes Tab before renderer callbacks. + // Members then release in declaration-reverse order; text_input + // destruction clears focus before the character base is destroyed. + if (m_tab_index >= 0 && m_tab_index < s_tab_table.size() && s_tab_table[m_tab_index] == this) + { + s_tab_table[m_tab_index] = NULL; + } for (int i = 0; i < m_lines.size(); i++) { if (m_lines[i]) render::text_release(m_lines[i]); } m_lines.resize(0); - if (m_tab_index >= 0 && m_tab_index < s_tab_table.size() && s_tab_table[m_tab_index] == this) - { - s_tab_table[m_tab_index] = NULL; - } - if (s_focused_field == this) + } + + // [CHOSEN, not recovered] issue #7: movie teardown, see release_script_objects. Adds the + // field's environment and its two handler values to the base character's values. + virtual void release_script_values(array* held) + { + character::release_script_values(held); + m_as_environment.release_values(held); + hold_script_value(held, m_on_changed); + m_on_changed.set_undefined(); + hold_script_value(held, m_on_set_focus); + m_on_set_focus.set_undefined(); + } + + // SwiffPlayer.dll 0x100881A0: inspect members without stamping this field. + virtual void gc_mark() + { + if (m_gc_generation == get_gc_mark_generation()) return; + for (stringi_hash::iterator it = m_as_environment.m_variables.begin(); + it != m_as_environment.m_variables.end(); ++it) + gc_mark_value(it->second); + } + + // SwiffPlayer.dll 0x10088250: release OBJECT members, then clear the bag. + virtual void gc_release() + { + if (m_gc_generation == get_gc_release_generation()) return; + for (stringi_hash::iterator it = m_as_environment.m_variables.begin(); + it != m_as_environment.m_variables.end(); ++it) { - s_focused_field = NULL; + if (it->second.get_type() == as_value::OBJECT) + { + as_object_interface* object = it->second.to_object_raw(); + if (object) object->gc_release(); + } } + m_as_environment.m_variables.clear(); } - void set_tab_index(int index) // sub_10087B50 + // SwiffPlayer.dll 0x10087B50. [CHOSEN, not recovered] S3 bridge: + // retain the existing native pointer-array storage. + void set_tab_index(int index) { if (m_tab_index >= 0 && m_tab_index < s_tab_table.size() && s_tab_table[m_tab_index] == this) { @@ -695,13 +839,7 @@ namespace gameswf m_tab_index = index; if (index >= 0) { - if (index >= s_tab_table.size()) - { - const int old = s_tab_table.size(); - s_tab_table.resize(index + 1); - for (int i = old; i < s_tab_table.size(); i++) s_tab_table[i] = NULL; - } - s_tab_table[index] = this; + register_text_tab(index, this); } } @@ -710,25 +848,43 @@ namespace gameswf // pixels here scaled every label clip (whose only child is its field) twenty-fold (retail run X, // 1640 px line widths, no wrapping). The shipped vslot 252 is in pixels; the AS-visible `_width` // stays in pixels through the conversions at the use sites below. - virtual float get_width() { return m_def->m_rect.width(); } - virtual float get_height() { return m_def->m_rect.height(); } - // [DICE-MOD SwiffPlayer #39] the unscaled local extent Flash's `_width`/`_height` build on. + // SwiffPlayer.dll 0x10087A60 / 0x10087A30. + // [CHOSEN, not recovered] S3 bridge: + // native extent virtuals return twips; their consumers convert to retail pixels. + virtual float get_width() { rect bounds; return get_text_bounds(&bounds)->width(); } + virtual float get_height() { rect bounds; return get_text_bounds(&bounds)->height(); } + // [CHOSEN, not recovered] S3 bridge from native twip-returning extent + // virtuals to retail pixel consumers, without another float store. + bf2x87::Real extent_pixels(bool width) + { + return bf2x87::mul(bf2x87::Real(width ? get_width() : get_height()), bf2x87::Real(0.05f)); + } + // the unscaled local extent Flash's `_width`/`_height` build on. virtual float get_local_width() { return m_def->m_rect.width(); } virtual float get_local_height() { return m_def->m_rect.height(); } + // SwiffPlayer.dll 0x10087C20. virtual const char* get_text_name() const { return m_def->m_default_name.c_str(); } + // SwiffPlayer.dll 0x10087970. + // [CHOSEN, not recovered] S3 bridge: + // retained out-parameter adapter for the native text callers. + rect* get_text_bounds(rect* out) const { m_def->get_text_bounds(out); return out; } + // SwiffPlayer.dll 0x10087970 forwards the definition rectangle. + rect get_bound_copy() const override { return m_def->get_bound_copy(); } - void reset_bounding_box(float x, float y) - // Reset our text bounding box to the given point. + // SwiffPlayer.dll 0x10087990. + bool point_test_text_local(float x, float y) const { - m_text_bounding_box.m_x_min = x; - m_text_bounding_box.m_x_max = x; - m_text_bounding_box.m_y_min = y; - m_text_bounding_box.m_y_max = y; + rect bounds; + return get_text_bounds(&bounds)->point_test(x, y); } + // SwiffPlayer.dll 0x10087A90. + virtual int get_text_height() const { return m_text_height_px; } + + // SwiffPlayer.dll 0x10087510. virtual void set_text_value(const char* new_text) // Set our text to the given string. sub_10087510: same text -> nothing; the field's own // maxChars clamps; then the layout. The WIDE store is NOT touched: the two stores are @@ -752,11 +908,13 @@ namespace gameswf // The wide setter (shipped vslot +272, sub_100893E0): a String object carrying UTF-16 text. // Same text -> nothing; else the wide store alone is replaced (the narrow one at +300 is NOT // synced), clamped to maxChars, and the layout runs. + // SwiffPlayer.dll 0x100893E0. [CHOSEN, not recovered] S3 bridge: + // store UTF-16 in the existing array, including its terminator. void set_wide_text_value(const Uint16* wide) { int n = 0; for (const Uint16* p = wide; p && *p; ++p) n++; - if (m_wide_text.size() == n + 1) + if (m_wide_text.size() == n + 1 || (n == 0 && m_wide_text.size() == 0)) { bool same = true; for (int i = 0; i < n; i++) { if (m_wide_text[i] != wide[i]) { same = false; break; } } @@ -775,6 +933,7 @@ namespace gameswf format_text(); } + // SwiffPlayer.dll 0x10087C40. virtual const char* get_text_value() const { return m_text.c_str(); @@ -786,7 +945,7 @@ namespace gameswf { // @@ TODO need to inherit basic stuff like _x, _y, _xscale, _yscale etc - if (dice_set_member(name, val)) // [DICE-MOD #37] the shipped member surface, sub_10089440 + if (dice_set_member(name, val)) // the shipped member surface, sub_10089440 { return; } @@ -845,7 +1004,12 @@ namespace gameswf //else if (name == "textColor") { // The arg is 0xRRGGBB format. +#if defined(__APPLE__) + // [CHOSEN, not recovered] Keep the x86 wrap of a negative number (arm64 saturates to 0). + Uint32 rgb = bf2x87::lowUInt32(val.to_number()); +#else Uint32 rgb = (Uint32) val.to_number(); +#endif cxform cx = get_cxform(); cx.m_[0][0] = fclamp(((rgb >> 16) & 255) / 255.0f, 0, 1); @@ -862,10 +1026,15 @@ namespace gameswf bool get_member(const tu_stringi& name, as_value* val) { - if (dice_get_member(name, val)) // [DICE-MOD #37] the shipped member surface, sub_10087C60 + if (dice_get_member(name, val)) // the shipped member surface, sub_10087C60 { return true; } + // SwiffPlayer.dll 0x10087C60 compares member names case-sensitively. + // Route the four remaining shared properties through the native switch. + const tu_string& exact_name = name.to_tu_string(); + if (exact_name != "_x" && exact_name != "_y" && exact_name != "_visible" + && exact_name != "_alpha") return false; as_standard_member std_member = get_standard_member(name); switch (std_member) { @@ -937,37 +1106,21 @@ namespace gameswf val->set_double(TWIPS_TO_PIXELS(transformed_rect.height())); return true; } - case M_TEXTWIDTH: - //else if (name == "textWidth") - { - // Return the width, in pixels, of the text as laid out. - // (I.e. the actual text content, not our defined - // bounding box.) - // - // In local coords. Verified against Macromedia Flash. - val->set_double(TWIPS_TO_PIXELS(m_text_bounding_box.width())); - - return true; - } } // end switch return false; } - // @@ WIDTH_FUDGE is a total fudge to make it match the Flash player! Maybe - // we have a bug? - #define WIDTH_FUDGE 80.0f - - + // SwiffPlayer.dll 0x10085440. [CHOSEN, not recovered] S3 bridge: + // get_width already returns twips in the current character interface. void align_line(edit_text_character_def::alignment align, int last_line_start_record, float x) // Does LEFT/CENTER/RIGHT alignment on the records in // m_text_glyph_records[], starting with // last_line_start_record and going through the end of // m_text_glyph_records. { - float extra_space = (m_def->m_rect.width() - m_def->m_right_margin) - x - WIDTH_FUDGE; - assert(extra_space >= 0.0f); + float extra_space = (get_width() - m_def->m_right_margin) - x; float shift_right = 0.0f; @@ -1001,7 +1154,7 @@ namespace gameswf // Convert the characters in m_text into a series of // text_glyph_records to be rendered. - // [DICE-MOD #37] sub_10086C00: with renderer lines the renderer lays the text out, otherwise the + // sub_10086C00: with renderer lines the renderer lays the text out, otherwise the // stock glyph layout below runs (the shipped keeps both). void format_text() { @@ -1013,7 +1166,8 @@ namespace gameswf format_text_glyphs(); } - // sub_10085F50: put `text` on line `index`, creating the line when it is the next one. + // SwiffPlayer.dll 0x10085F50. [CHOSEN, not recovered] S3 bridge: + // keep UTF-16 in the native array and widen only at the renderer boundary. void set_line_text(int index, float width_px, const array& text) { if (index >= m_lines.size()) @@ -1025,7 +1179,7 @@ namespace gameswf render::text_set_size(line, width_px, (int) m_def->m_alignment); if (!m_password) { - render::text_set(line, (const wchar_t*) &text[0]); + render::text_set(line, BF2_DICE_WIDE(&text[0])); // [CHOSEN, not recovered] POSIX: widen, see dice_wide return; } // A password field shows one asterisk per character (the shipped fills a 512-wide buffer). @@ -1038,47 +1192,53 @@ namespace gameswf int n = 0; while (text[n]) n++; if (n > 511) n = 511; - render::text_set(line, (const wchar_t*) &s_asterisks[511 - n]); + render::text_set(line, BF2_DICE_WIDE(&s_asterisks[511 - n])); } // sub_10084DE0: grow the field's y scale so at least `height_px` is visible (auto-size). - void set_height_at_least(float height_px) + // SwiffPlayer.dll 0x10084DE0. [CHOSEN, not recovered] S3 bridge: + // the current character extent API returns twips rather than retail pixels. + void set_height_at_least(int height_px) { + m_text_height_px = height_px; matrix m = get_matrix(); - const float h = TWIPS_TO_PIXELS(get_height()); - if (h * m.m_[1][1] < height_px && h > 0) + if (TWIPS_TO_PIXELS(get_height()) * m.m_[1][1] < height_px) { - m.m_[1][1] = height_px / h; + m.m_[1][1] = height_px / TWIPS_TO_PIXELS(get_height()); set_matrix(m); } } - // sub_10086080 - formatText: the renderer-line layout. + // SwiffPlayer.dll 0x10086080. + // [CHOSEN, not recovered] S3 bridge: native UTF-16 storage. Non-C + // POSIX conversion follows the explicit native-locale adapter above. void format_text_lines() { - if (m_font_name.length() == 0) - { - return; - } - - // The wide source: the wide copy when one was set, else the narrow text widened byte by - // byte (the shipped mbstowcs of +300). - array wide; + static profile_record counter("formatTextObjects"); + if (s_profiling) counter.begin(); + // Borrow the wide payload, or allocate the narrow byte count including + // its terminator. Retail ignores the conversion result and does not + // initialize the remaining buffer after conversion failure. + Uint16* converted = NULL; + size_t converted_bytes = 0; + const Uint16* text; if (m_wide_text.size() > 1) { - wide = m_wide_text; + text = &m_wide_text[0]; } else { - for (int i = 0; i < m_text.length(); i++) wide.push_back((Uint16) (unsigned char) m_text[i]); - wide.push_back(0); + const size_t count = static_cast(m_text.length()) + 1; + converted_bytes = count * sizeof(Uint16); + converted = static_cast(tu_malloc(converted_bytes)); + text_mbstowcs(converted, m_text.c_str(), count); + text = converted; } const matrix world = get_world_matrix(); - const float width_px = TWIPS_TO_PIXELS(get_width()) * world.m_[0][0]; - const float height_limit = get_height() * world.m_[1][1]; // twips - const float line_height = m_def->m_leading + m_def->m_text_height; // twips (+100 + +72) - const float wrap_limit = width_px - m_def->m_right_margin * 0.05f; + const float width_px = bf2x87::store(bf2x87::mul(extent_pixels(true), bf2x87::Real(world.m_[0][0]))); + const float height_limit = bf2x87::store(bf2x87::mul( + bf2x87::mul(extent_pixels(false), bf2x87::Real(20.0f)), bf2x87::Real(world.m_[1][1]))); array buf; buf.push_back(0); @@ -1087,10 +1247,11 @@ namespace gameswf int last_space = -1; bool overflowed = false; int i = 0; + Uint16 c; for (;;) { - const Uint16 c = wide[i++]; - if (y > height_limit) + c = text[i++]; + if (bf2x87::greater(bf2x87::Real(y), bf2x87::Real(height_limit))) { overflowed = true; break; @@ -1100,7 +1261,8 @@ namespace gameswf set_line_text(line++, width_px, buf); buf.resize(0); buf.push_back(0); - y += line_height; + y = bf2x87::store(bf2x87::add(bf2x87::add(bf2x87::Real(m_def->m_leading), + bf2x87::Real(m_def->m_text_height)), bf2x87::Real(y))); } else { @@ -1115,7 +1277,9 @@ namespace gameswf { float w = 0, h = 0; render::text_extent(m_lines[line], buf.size() - 1, &w, &h); - if (wrap_limit > w) + const bf2x87::Real wrap_limit = bf2x87::sub(bf2x87::Real(width_px), + bf2x87::mul(bf2x87::Real(m_def->m_right_margin), bf2x87::Real(0.05f))); + if (!bf2x87::lessEqual(wrap_limit, bf2x87::Real(w))) { // fits } @@ -1128,7 +1292,8 @@ namespace gameswf buf.resize(0); buf.push_back(c); buf.push_back(0); - y += line_height; + y = bf2x87::store(bf2x87::add(bf2x87::add(bf2x87::Real(m_def->m_leading), + bf2x87::Real(m_def->m_text_height)), bf2x87::Real(y))); } else { @@ -1140,7 +1305,8 @@ namespace gameswf set_line_text(line++, width_px, buf); buf = tail; last_space = -1; - y += line_height; + y = bf2x87::store(bf2x87::add(bf2x87::add(bf2x87::Real(m_def->m_leading), + bf2x87::Real(m_def->m_text_height)), bf2x87::Real(y))); } } } @@ -1153,10 +1319,11 @@ namespace gameswf { line--; } - else if (buf.size() <= 1) + if ((!overflowed || c == 0) && buf.size() <= 1) { line--; } + if (converted) tu_free(converted, converted_bytes); const int count = m_lines.size(); if (line >= count && line > 0) @@ -1176,27 +1343,29 @@ namespace gameswf m_lines.resize(line + 1); } - // [DICE-MOD SwiffPlayer #52] sub_10086080's tail (0x10086433..0x10086495): the height the + // sub_10086080's tail (0x10086433..0x10086495): the height the // field must show is the font's LEADING (+0x40, the same term as the caret's, #47) plus the // definition's text height, plus the laid-out y for word-wrapped fields or the definition's // leading otherwise, in pixels. Until 2026-09-13 this port added the font's ASCENT instead, // which grew every input field's y scale three to four times: the caret and text sat low // in the box and the field's hit rectangle reached two rows down, so a click on the e-mail // field still belonged to ACCOUNT NAME (owner's report, the CREATE ACCOUNT page). - const float leading = m_def->m_font ? m_def->m_font->get_leading() : 0.0f; - float height_px; + const float leading = m_def->m_font->get_leading(); + bf2x87::Real height; if (m_def->m_word_wrap) { - height_px = (leading + m_def->m_text_height + y) * 0.05f; + height = bf2x87::add(bf2x87::add(bf2x87::Real(leading), bf2x87::Real(m_def->m_text_height)), bf2x87::Real(y)); } else { - height_px = (leading + m_def->m_leading + m_def->m_text_height) * 0.05f; + height = bf2x87::add(bf2x87::add(bf2x87::Real(leading), bf2x87::Real(m_def->m_leading)), bf2x87::Real(m_def->m_text_height)); } - set_height_at_least((float) (int) height_px); + set_height_at_least(bf2x87::toIntTruncate(bf2x87::mul(height, bf2x87::Real(0.05f)))); m_lines_dirty = true; + counter.end(); } + // SwiffPlayer.dll 0x10086C00, glyph fallback arm. void format_text_glyphs() { m_text_glyph_records.resize(0); @@ -1205,6 +1374,8 @@ namespace gameswf { return; } + static profile_record counter("formatText"); + if (s_profiling) counter.begin(); // @@ mostly for debugging // Font substitution -- if the font has no @@ -1237,52 +1408,54 @@ namespace gameswf } - float scale = m_def->m_text_height / 1024.0f; // the EM square is 1024 x 1024 + float scale = bf2x87::store(bf2x87::mul(bf2x87::Real(m_def->m_text_height), bf2x87::Real(1.0f / 1024.0f))); text_glyph_record rec; // one to work on rec.m_style.m_font = m_def->m_font; - rec.m_style.m_color = m_def->m_color; - rec.m_style.m_x_offset = fmax(0, m_def->m_left_margin + m_def->m_indent); - rec.m_style.m_y_offset = m_def->m_text_height - + (m_def->m_font->get_leading() - m_def->m_font->get_descent()) * scale; + rec.m_style.m_color = m_text_color; + const bf2x87::Real indent = bf2x87::add(bf2x87::Real(m_def->m_indent), bf2x87::Real(m_def->m_left_margin)); + rec.m_style.m_x_offset = bf2x87::greater(indent, bf2x87::Real(0)) ? bf2x87::store(indent) : 0.0f; + rec.m_style.m_y_offset = bf2x87::store(bf2x87::add( + bf2x87::mul(bf2x87::sub(bf2x87::Real(m_def->m_font->get_leading()), + bf2x87::Real(m_def->m_font->get_descent())), bf2x87::Real(scale)), bf2x87::Real(m_def->m_text_height))); rec.m_style.m_text_height = m_def->m_text_height; rec.m_style.m_has_x_offset = true; rec.m_style.m_has_y_offset = true; + rect bounds; + get_text_bounds(&bounds); + rec.m_style.m_x_offset += bounds.get_corner(0).m_x; + rec.m_style.m_y_offset += bounds.get_corner(0).m_y; float x = rec.m_style.m_x_offset; float y = rec.m_style.m_y_offset; + m_caret_x = text_coord(x); + m_caret_y = text_coord(bf2x87::add(bf2x87::add(bf2x87::mul(bf2x87::Real(scale), + bf2x87::Real(m_def->m_font->get_descent())), bf2x87::Real(y)), bf2x87::Real(40.0f))); - // Start the bbox at the upper-left corner of the first glyph. - reset_bounding_box(x, y - m_def->m_font->get_descent() * scale + m_def->m_text_height); - - float leading = m_def->m_leading; - leading += m_def->m_font->get_leading() * scale; + float leading = bf2x87::store(bf2x87::add(bf2x87::mul(bf2x87::Real(scale), + bf2x87::Real(m_def->m_font->get_leading())), bf2x87::Real(m_def->m_leading))); int last_code = -1; int last_space_glyph = -1; int last_line_start_record = 0; - const char* text = &m_text[0]; + const char* text_start = m_text.c_str(); + const char* text = text_start; while (Uint32 code = utf8::decode_next_unicode_character(&text)) { -// @@ try to truncate overflow text?? -#if 0 - if (y + m_def->m_font->get_descent() * scale > m_def->m_rect.height()) + // 0x10086E33..0x10086E60 clips the unfinished line at the height limit. + const float baseline = bf2x87::store(bf2x87::add(bf2x87::mul( + bf2x87::Real(m_def->m_font->get_descent()), bf2x87::Real(scale)), bf2x87::Real(y))); + if (bf2x87::less(bf2x87::mul(extent_pixels(false), bf2x87::Real(20.0f)), bf2x87::Real(baseline))) { - // Text goes below the bottom of our bounding box. rec.m_glyphs.resize(0); break; } -#endif // 0 - - //Uint16 code = m_text[j]; - x += m_def->m_font->get_kerning_adjustment(last_code, (int) code) * scale; + x = bf2x87::store(bf2x87::add(bf2x87::mul(bf2x87::Real(m_def->m_font->get_kerning_adjustment(last_code, (int) code)), + bf2x87::Real(scale)), bf2x87::Real(x))); last_code = (int) code; - // Expand the bounding-box to the lower-right corner of each glyph as - // we generate it. - m_text_bounding_box.expand_to_point(x, y + m_def->m_font->get_descent() * scale); if (code == 13 || code == 10) { @@ -1297,8 +1470,9 @@ namespace gameswf m_text_glyph_records.push_back(rec); align_line(m_def->m_alignment, last_line_start_record, x); - x = fmax(0, m_def->m_left_margin + m_def->m_indent); // new paragraphs get the indent. - y += m_def->m_text_height + leading; + const bf2x87::Real paragraph_indent = bf2x87::add(bf2x87::Real(m_def->m_indent), bf2x87::Real(m_def->m_left_margin)); + x = bf2x87::greater(paragraph_indent, bf2x87::Real(0)) ? bf2x87::store(paragraph_indent) : 0.0f; + y = bf2x87::store(bf2x87::add(bf2x87::add(bf2x87::Real(leading), bf2x87::Real(m_def->m_text_height)), bf2x87::Real(y))); // Start a new record on the next line. rec.m_glyphs.resize(0); @@ -1316,32 +1490,6 @@ namespace gameswf continue; } - if (code == 8) - { - // backspace (ASCII BS). - - // This is a limited hack to enable overstrike effects. - // It backs the cursor up by one character and then continues - // the layout. E.g. you can use this to display an underline - // cursor inside a simulated text-entry box. - // - // ActionScript understands the '\b' escape sequence - // for inserting a BS character. - // - // ONLY WORKS FOR BACKSPACING OVER ONE CHARACTER, WON'T BS - // OVER NEWLINES, ETC. - - if (rec.m_glyphs.size() > 0) - { - // Peek at the previous glyph, and zero out its advance - // value, so the next char overwrites it. - float advance = rec.m_glyphs.back().m_glyph_advance; - x -= advance; // maintain formatting - rec.m_glyphs.back().m_glyph_advance = 0; // do the BS effect - } - continue; - } - // Remember where word breaks occur. if (code == 32) { @@ -1365,8 +1513,8 @@ namespace gameswf m_def->m_font->get_name()); } - // Drop through and use index == -1; this will display - // using the empty-box glyph + // SwiffPlayer.dll 0x10086EB4..0x10086EE5 skips missing glyphs. + continue; } text_glyph_record::glyph_entry ge; ge.m_glyph_index = index; @@ -1377,7 +1525,9 @@ namespace gameswf x += ge.m_glyph_advance; - if (x >= m_def->m_rect.width() - m_def->m_right_margin - WIDTH_FUDGE) + // SwiffPlayer.dll 0x10086F2B..0x10086F4C. + if (bf2x87::lessEqual(bf2x87::sub(bf2x87::mul(extent_pixels(true), bf2x87::Real(20.0f)), + bf2x87::Real(m_def->m_right_margin)), bf2x87::Real(x))) { // Whoops, we just exceeded the box width. Do word-wrap. @@ -1388,7 +1538,7 @@ namespace gameswf float previous_x = x; x = m_def->m_left_margin; - y += m_def->m_text_height + leading; + y = bf2x87::store(bf2x87::add(bf2x87::add(bf2x87::Real(leading), bf2x87::Real(m_def->m_text_height)), bf2x87::Real(y))); // Start a new record on the next line. rec.m_glyphs.resize(0); @@ -1401,12 +1551,27 @@ namespace gameswf rec.m_style.m_has_y_offset = true; text_glyph_record& last_line = m_text_glyph_records.back(); - if (last_space_glyph == -1) + if (!m_def->m_word_wrap) + { + // 0x10087207: discard overflow and scan through the next newline. + if (last_line.m_glyphs.size() > 0) + { + last_line.m_glyphs.resize(last_line.m_glyphs.size() - 1); + } + do { code = utf8::decode_next_unicode_character(&text); } + while (code != 0 && code != 13 && code != 10); + if (code == 0) break; + } + else if (last_space_glyph == -1) { // Pull the previous glyph down onto the // new line. if (last_line.m_glyphs.size() > 0) { + if ((Uint16) (text - text_start - 1) == m_caret) + { + set_glyph_caret(x, y, scale, (int) code, (int) code); + } rec.m_glyphs.push_back(last_line.m_glyphs.back()); x += last_line.m_glyphs.back().m_glyph_advance; previous_x -= last_line.m_glyphs.back().m_glyph_advance; @@ -1415,15 +1580,24 @@ namespace gameswf } else { - // Move the previous word down onto the next line. - + // The removed space contributes to the old line's aligned width. previous_x -= last_line.m_glyphs[last_space_glyph].m_glyph_advance; + const int byte_start = (int) (text - text_start) - last_line.m_glyphs.size(); + if (byte_start + last_space_glyph + 1 == m_caret) + { + set_glyph_caret(x, y, scale, (int) code, (int) code); + } + // Move the previous word down onto the next line. for (int i = last_space_glyph + 1; i < last_line.m_glyphs.size(); i++) { rec.m_glyphs.push_back(last_line.m_glyphs[i]); x += last_line.m_glyphs[i].m_glyph_advance; previous_x -= last_line.m_glyphs[i].m_glyph_advance; + if (byte_start + i + 1 == m_caret) + { + set_glyph_caret(x, y, scale, (int) code, (int) code); + } } last_line.m_glyphs.resize(last_space_glyph); } @@ -1433,6 +1607,10 @@ namespace gameswf last_space_glyph = -1; last_line_start_record = m_text_glyph_records.size(); } + if ((Uint16) (text - text_start) == m_caret) + { + set_glyph_caret(x, y, scale, last_code, (int) code); + } // TODO: HTML markup } @@ -1440,10 +1618,23 @@ namespace gameswf // Add this line to our output. m_text_glyph_records.push_back(rec); align_line(m_def->m_alignment, last_line_start_record, x); + counter.end(); + } + + // SwiffPlayer.dll 0x100872A6..0x100872E8 and the wrap branches. + void set_glyph_caret(float x, float y, float scale, int previous, int code) + { + m_caret_x = text_coord(bf2x87::add(bf2x87::mul(bf2x87::Real(m_def->m_font->get_kerning_adjustment(previous, code)), + bf2x87::Real(scale)), bf2x87::Real(x))); + m_caret_y = text_coord(bf2x87::add(bf2x87::add(bf2x87::mul(bf2x87::Real(scale), + bf2x87::Real(m_def->m_font->get_descent())), bf2x87::Real(y)), bf2x87::Real(40.0f))); } - // [DICE-MOD #37] sub_100882F0 - display: refresh dirty lines, the world matrix with its SCALE + // SwiffPlayer.dll 0x100882F0. + // [CHOSEN, not recovered] S3 bridge: + // read the definition rectangle through the current native field. + // display: refresh dirty lines, the world matrix with its SCALE // reset to one (text is drawn at device size, translation only), background quad and border, // the blinking caret when focused, then every line through render::text_draw with the y // advanced by leading + height. The stock glyph records are never drawn (the shipped does not). @@ -1465,23 +1656,25 @@ namespace gameswf render::set_cxform(get_world_cxform()); point coords[4]; - coords[0] = m_def->m_rect.get_corner(0); - coords[1] = m_def->m_rect.get_corner(1); - coords[2] = m_def->m_rect.get_corner(3); - coords[3] = m_def->m_rect.get_corner(2); + rect bounds; + get_text_bounds(&bounds); + coords[0] = bounds.get_corner(0); + coords[1] = bounds.get_corner(1); + coords[2] = bounds.get_corner(3); + coords[3] = bounds.get_corner(2); Sint16 icoords[18] = { // strip (fill in) - (Sint16) coords[0].m_x, (Sint16) coords[0].m_y, - (Sint16) coords[1].m_x, (Sint16) coords[1].m_y, - (Sint16) coords[2].m_x, (Sint16) coords[2].m_y, - (Sint16) coords[3].m_x, (Sint16) coords[3].m_y, + text_coord(coords[0].m_x), text_coord(coords[0].m_y), + text_coord(coords[1].m_x), text_coord(coords[1].m_y), + text_coord(coords[2].m_x), text_coord(coords[2].m_y), + text_coord(coords[3].m_x), text_coord(coords[3].m_y), // outline - (Sint16) coords[0].m_x, (Sint16) coords[0].m_y, - (Sint16) coords[1].m_x, (Sint16) coords[1].m_y, - (Sint16) coords[3].m_x, (Sint16) coords[3].m_y, - (Sint16) coords[2].m_x, (Sint16) coords[2].m_y, - (Sint16) coords[0].m_x, (Sint16) coords[0].m_y, + text_coord(coords[0].m_x), text_coord(coords[0].m_y), + text_coord(coords[1].m_x), text_coord(coords[1].m_y), + text_coord(coords[3].m_x), text_coord(coords[3].m_y), + text_coord(coords[2].m_x), text_coord(coords[2].m_y), + text_coord(coords[0].m_x), text_coord(coords[0].m_y), }; if (m_background) { @@ -1500,12 +1693,12 @@ namespace gameswf const float em = m_def->m_text_height * (1.0f / 1024.0f); if (s_focused_field == this) { - if (((int) (m_blink_time * 3.0f) & 1) == 0) + if ((bf2x87::toIntTruncate(m_blink_time * 3.0f) & 1) == 0) { float w = 0, h = 0; render::text_extent(m_lines[0], m_caret, &w, &h); const float x = w * 20.0f; - // [DICE-MOD SwiffPlayer #47] The font term is the font's LEADING, not its + // The font term is the font's LEADING, not its // ascent. 100885 8B..9E reads def+0x44 (the font) and multiplies em by // FONT+0x40, and font::read fills +0x38/+0x3C/+0x40 with ascent/descent/ // leading in that order (100A1A7D..100A1AAB), so +0x40 is the third of the @@ -1517,8 +1710,8 @@ namespace gameswf const float fontLeading = m_def->m_font->get_leading(); Sint16 caret[4] = { - (Sint16) x, 0, - (Sint16) x, (Sint16) (em * fontLeading + m_def->m_leading + m_def->m_text_height), + text_coord(x), 0, + text_coord(x), text_coord(em * fontLeading + m_def->m_leading + m_def->m_text_height), }; render::line_style_color(m_text_color); render::line_style_width(1.0f); @@ -1527,7 +1720,7 @@ namespace gameswf } float left = m_def->m_indent + m_def->m_left_margin; - if (left < 0) left = 0; + if (!(left > 0)) left = 0; mat.m_[0][2] += left + 40.0f; mat.m_[1][2] += 30.0f; for (int i = 0; i < m_lines.size(); i++) @@ -1537,10 +1730,17 @@ namespace gameswf } } - do_display_callback(); + // SwiffPlayer.dll 0x10088649 returns after drawing the last renderer line. } - virtual void advance(float delta_time) // sub_10087AA0 + // SwiffPlayer.dll 0x100883F5..0x10088463: _ftol then the low word. + static Sint16 text_coord(bf2x87::Real value) + { + return bf2x87::lowShort(bf2x87::toInt64Truncate(value)); + } + + // SwiffPlayer.dll 0x10087AA0. + virtual void advance(float delta_time) { m_blink_time += delta_time; } @@ -1553,13 +1753,17 @@ namespace gameswf void call_callback(as_value& fn) // sub_1008EAA0: the field's AS object is `this` { - if (fn.is_function()) + // SwiffPlayer.dll 0x10087B01 / 0x10088E6E tests only undefined. + // [CHOSEN, not recovered] S3 bridge to the native call wrapper. + if (fn.get_type() != as_value::UNDEFINED) { call_method0(fn, &m_as_environment, this); } } - void focus() // sub_10087AC0 + // SwiffPlayer.dll 0x10087AC0. [CHOSEN, not recovered] S3 bridge: + // tolerate the current factory's absence of renderer lines. + void focus() { s_focused_field = this; m_caret = (Uint16) m_text.length(); @@ -1571,25 +1775,27 @@ namespace gameswf call_callback(m_on_set_focus); } - static bool focus_next(int from) // sub_100891E0: the next Tab index with a field, wrapping + // SwiffPlayer.dll 0x100891E0; from is the registered Tab index. + static bool focus_next(int from) { const int n = s_tab_table.size(); for (int i = from + 1; i < n; i++) { if (s_tab_table[i]) { s_tab_table[i]->focus(); return true; } } - for (int i = 0; i < from && i < n; i++) + for (int i = 0; i < from; i++) { if (s_tab_table[i]) { s_tab_table[i]->focus(); return true; } } return false; } - static bool focus_prev(int from) // sub_10089230 + // SwiffPlayer.dll 0x10089230; from is the registered Tab index. + static bool focus_prev(int from) { const int n = s_tab_table.size(); for (int i = from - 1; i >= 0; i--) { - if (i < n && s_tab_table[i]) { s_tab_table[i]->focus(); return true; } + if (s_tab_table[i]) { s_tab_table[i]->focus(); return true; } } for (int i = n - 1; i > from; i--) { @@ -1598,21 +1804,22 @@ namespace gameswf return false; } - // [DICE-MOD SwiffPlayer #51] sub_100879C0: the world-space point through the inverse world - // matrix, then the definition's rectangle. [INFERRED: the rectangle the shipped body fetches - // through slot 60 is the definition's.] + // SwiffPlayer.dll 0x100879C0: inverse world transform, then the local rectangle. virtual bool point_test_world(float x, float y) { matrix world = get_world_matrix(); point p; world.transform_by_inverse(&p, point(x, y)); - return m_def->m_rect.point_test(p.m_x, p.m_y); + return point_test_text_local(p.m_x, p.m_y); } - // sub_10088650 - the mouse: per-frame state machine on (inside, button) against the previous + // SwiffPlayer.dll 0x10088650. + // [CHOSEN, not recovered] S3 bridge: + // definition rectangles and optional renderer lines use the native interfaces. + // The mouse: per-frame state machine on (inside, button) against the previous // frame; a press inside starts a drag/selection, its release focuses the field, a press // outside a focused field blurs it. [INFERRED: the selection arguments the hit test takes.] - // [DICE-MOD SwiffPlayer #51] This is the text field's mouse pass (vtable slot 4): it ignores + // This is the text field's mouse pass (vtable slot 4): it ignores // what the siblings above consumed - the argument is unread by the shipped body - so a click // reaches the field through any decoration drawn over it, and it answers "inside" (the state's // bit 0) for the siblings below. Read-only fields, and every field but the focused one while @@ -1624,20 +1831,20 @@ namespace gameswf { return false; } + matrix world = get_world_matrix(); + get_parent()->get_active_mouse_entity(); if (s_focused_field != NULL && s_focused_field != this) { return false; } int mx = 0, my = 0, mb = 0; - movie* root = get_root_movie(); - if (root) root->get_mouse_state(&mx, &my, &mb); + get_parent()->get_mouse_state(&mx, &my, &mb); m_prev_mouse_state = m_mouse_state; - m_mouse_state = (mb & 1) ? 2 : 0; - matrix world = get_world_matrix(); + m_mouse_state = mb ? 2 : 0; point p; world.transform_by_inverse(&p, point((float) mx * 20.0f, (float) my * 20.0f)); - if (m_def->m_rect.point_test(p.m_x, p.m_y)) + if (point_test_text_local(p.m_x, p.m_y)) { m_mouse_state |= 1; } @@ -1655,41 +1862,43 @@ namespace gameswf float x1 = m_drag_x * 0.05f, y1 = m_drag_y * 0.05f; float x2 = p.m_x * 0.05f, y2 = p.m_y * 0.05f; int pos = 0; - if (render::text_hit(m_lines[0], &pos, (int) x2, (int) y2)) + // 0x100887A5..0x100887D7: x2/y2 are fstp'd floats pushed unconverted (no fistp). + if (render::text_hit(m_lines[0], &pos, x2, y2)) { m_caret = (Uint16) pos; } m_blink_time = 0; if (x1 > x2) { float t = x1; x1 = x2; x2 = t; } if (y1 > y2) { float t = y1; y1 = y2; y2 = t; } - render::text_set_selection(m_lines[0], (int) x1, (int) y1, (int) x2, (int) y2); + // 0x10088823..0x1008883B: the sorted floats are pushed as raw dwords. + render::text_set_selection(m_lines[0], x1, y1, x2, y2); } - const bool result = (m_mouse_state & 1) != 0; if (m_mouse_state == m_prev_mouse_state) { - return result; + return (m_mouse_state & 1) != 0; } + world.transform_by_inverse(&p, point((float) mx * 20.0f, (float) my * 20.0f)); switch (m_mouse_state | (m_prev_mouse_state << 2)) { case 12: case 13: // released after a press inside: focus m_dragging = false; - if (s_focused_field == this) return result; + if (s_focused_field == this) return (m_mouse_state & 1) != 0; focus_from_click(); - return result; + return (m_mouse_state & 1) != 0; case 8: - if (!m_dragging) return result; + if (!m_dragging) return (m_mouse_state & 1) != 0; m_dragging = false; - if (s_focused_field == this) return result; + if (s_focused_field == this) return (m_mouse_state & 1) != 0; focus_from_click(); - return result; + return (m_mouse_state & 1) != 0; case 7: // pressed inside - m_drag_x = p.m_x; m_drag_y = p.m_y; m_dragging = true; - return result; + m_drag_x = p.m_x; + return (m_mouse_state & 1) != 0; case 2: // pressed outside: blur if (s_focused_field == this) @@ -1700,11 +1909,13 @@ namespace gameswf render::text_caret(m_lines[0], 0); render::text_blur(m_lines[0]); } - s_focused_field = NULL; + // 0x100889A0 rechecks focus after the renderer calls. + if (s_focused_field == this) s_focused_field = NULL; } - return result; + return (m_mouse_state & 1) != 0; } - return result; + // 0x10088A40 reads the state after focus callbacks have returned. + return (m_mouse_state & 1) != 0; } void focus_from_click() { @@ -1724,13 +1935,14 @@ namespace gameswf { *start = 0; *end = 0; if (m_lines.size() == 0) return false; - // [DICE-MOD SwiffPlayer #46] the RENDERER answers whether a selection exists: the + // the RENDERER answers whether a selection exists: the // shipped delete_selection (sub_10088D60) tests the Boolean of render::text_selection // (sub_1009A910 -> render_handler +112) and only then deletes [start, end). The port's // former `start != end` test read the forwarder's scratch start value as a selection // whenever the renderer had none, so Backspace and Delete deleted nothing (2026-09-12). return render::text_selection(m_lines[0], start, end); } + // SwiffPlayer.dll 0x10088DB0; endpoints are used in the supplied order. void delete_range(int new_length, int end, bool relayout) { if (new_length == end || new_length < 0) return; @@ -1747,32 +1959,34 @@ namespace gameswf call_callback(m_on_changed); if (m_lines.size() > 0) render::text_blur(m_lines[0]); } + // SwiffPlayer.dll 0x10088D60. [CHOSEN, not recovered] S3 bridge: + // get_selection permits fields with no native renderer line. bool delete_selection(bool relayout) { int s = 0, e = 0; if (!get_selection(&s, &e)) return false; - if (s > e) { int t = s; s = e; e = t; } delete_range(s, e, relayout); return true; } + // SwiffPlayer.dll 0x10088A70. void insert_text(const char* str) { delete_selection(false); tu_string ins(str); if (m_restrict.length() > 0) { - tu_string kept; + int kept = 0; for (int i = 0; i < ins.length(); i++) { for (int k = 0; k < m_restrict.length(); k++) { - if (ins[i] == m_restrict[k]) { kept += ins[i]; break; } + if (str[i] == m_restrict[k]) { ins[kept++] = str[i]; break; } } } - if (kept.length() == 0) return; - ins = kept; + if (kept == 0) return; + ins[kept] = 0; + ins.resize(kept); } - if (m_caret > m_text.length()) m_caret = (Uint16) m_text.length(); tu_string t = m_text; t.resize(m_caret); t += ins; @@ -1791,7 +2005,8 @@ namespace gameswf } // ---- text_input (the shipped +200 interface) ---- - virtual void on_key(int vkey) // sub_10088ED0 + // SwiffPlayer.dll 0x10088ED0. + virtual void on_key(int vkey) { if (vkey == 9 && m_tab_index > 0) { @@ -1806,6 +2021,7 @@ namespace gameswf return; } char ch = 0; + bool insert_char = true; if (vkey >= 65 && vkey <= 90) { ch = (char) (vkey + (s_mod_shift ? 0 : 0x20)); @@ -1837,26 +2053,32 @@ namespace gameswf { case 46: // Delete if (s_mod_alt) return; + insert_char = false; if (!delete_selection(true)) delete_range(m_caret, m_caret + 1, true); break; case 8: // Backspace if (s_mod_alt) return; + insert_char = false; if (!delete_selection(true)) delete_range(m_caret - 1, m_caret, true); break; case 37: // Left + insert_char = false; m_caret = (Uint16) (m_caret > 0 ? m_caret - 1 : 0); format_text(); break; case 39: // Right + insert_char = false; m_caret = (Uint16) (m_caret + 1 < m_text.length() ? m_caret + 1 : m_text.length()); format_text(); break; case 36: // Home + insert_char = false; m_caret = 0; render::text_caret(m_lines[0], 0); render::text_blur(m_lines[0]); break; case 35: // End + insert_char = false; m_caret = (Uint16) m_text.length(); render::text_caret(m_lines[0], m_caret); render::text_blur(m_lines[0]); @@ -1873,7 +2095,7 @@ namespace gameswf return; } } - if (ch) + if (insert_char) { char s[2] = { ch, 0 }; insert_text(s); @@ -1881,12 +2103,15 @@ namespace gameswf m_blink_time = 0; if (m_lines.size() > 0) render::text_blur(m_lines[0]); } - virtual void on_char(int character) // sub_10088A50 + // SwiffPlayer.dll 0x10088A50. + virtual void on_char(int character) { char s[2] = { (char) character, 0 }; insert_text(s); } - virtual void paste() // sub_10089280 + // SwiffPlayer.dll 0x10089280. [CHOSEN, not recovered] S3 bridge: + // retain the native no-renderer-line case at the blur boundary. + virtual void paste() { tu_string text; if (m_def->m_multiline) @@ -1903,17 +2128,17 @@ namespace gameswf if (text.length() > 0) insert_text(text.c_str()); if (m_lines.size() > 0) render::text_blur(m_lines[0]); } - virtual void copy() // sub_10087BB0 (guarded by a byte at character+153 [INFERRED: password]) + // SwiffPlayer.dll 0x10087BB0; the renderer owns endpoint order and validity. + virtual void copy() { if (m_password) return; int s = 0, e = 0; if (!get_selection(&s, &e)) return; - if (s > e) { int t = s; s = e; e = t; } - if (e > m_text.length()) e = m_text.length(); s_text_clipboard = m_text.c_str() + s; s_text_clipboard.resize(e - s); } - virtual void cut() // sub_100893C0 + // SwiffPlayer.dll 0x100893C0. + virtual void cut() { if (m_password) return; copy(); @@ -1921,14 +2146,25 @@ namespace gameswf } // ---- the AS member surface (sub_10089440 set, sub_10087C60 get) ---- - bool dice_set_member(const tu_stringi& name, const as_value& val) + // SwiffPlayer.dll 0x10089440 uses the exact comparison at 0x100858F0. + // [CHOSEN, not recovered] S3 bridge: the public native key is still tu_stringi. + bool dice_set_member(const tu_stringi& member_name, const as_value& val) { + const tu_string& name = member_name.to_tu_string(); + if (name == "_x" || name == "_y") + { + matrix m = get_matrix(); + m.m_[name == "_x" ? 0 : 1][2] = bf2x87::store(bf2x87::mul( + bf2x87::Real(val.to_number()), bf2x87::Real(20.0))); + set_matrix(m); + return true; + } if (name == "text") { - // sub_10089440: a value that is an object goes by its payload - the wide text when - // it carries one (DICE's String object from Locale.getString), else its narrow text - // value; a plain value goes narrow through to_string(). - as_object_interface* obj = val.to_object(); + // sub_10089440: a DICE String object always goes through the wide setter with its + // wide text, empty when it carries none (the shipped narrow arm at 0x10089599 is + // unreachable: it needs a null std::wstring c_str()); any other value goes narrow. + as_object_interface* obj = val.to_object_raw(); if (obj) { const Uint16* wide = obj->get_wide_text_value(); @@ -1948,9 +2184,21 @@ namespace gameswf } return true; } + if (name == "_visible") { set_visible(val.to_bool()); return true; } + if (name == "_alpha") + { + cxform cx = get_cxform(); + const bf2x87::Real alpha = bf2x87::mul(bf2x87::Real(val.to_number()), bf2x87::Real(0.01f)); + // Retail selects one for unordered input, then narrows before max. + const float upper = alpha < bf2x87::Real(1.0f) ? bf2x87::store(alpha) : 1.0f; + cx.m_[3][0] = tu_util::fmax(0.0f, upper); + set_cxform(cx); + return true; + } if (name == "textColor") { - const Uint32 rgb = (Uint32) val.to_number(); + // 0x100896D0 uses a signed dword FISTP, including integer indefinite. + const Uint32 rgb = (Uint32) bf2x87::toIntTruncate(val.to_number()); const Uint32 cur = ((Uint32) m_text_color.m_r << 16) | ((Uint32) m_text_color.m_g << 8) | m_text_color.m_b; if (rgb != cur) { @@ -1962,25 +2210,45 @@ namespace gameswf if (name == "_width" || name == "_height") { const bool is_w = name == "_width"; - const float cur = TWIPS_TO_PIXELS(is_w ? get_width() : get_height()); const double v = val.to_number(); - if (v == cur) return true; + const bf2x87::Real cur = extent_pixels(is_w); + if (bf2x87::Real(v) == cur) return true; matrix m = get_matrix(); float& s = is_w ? m.m_[0][0] : m.m_[1][1]; - s = (v == 0.0 || cur == 0.0f) ? 0.0f : (float) (v / cur); + // 0x1008977E..0x100897CE / 0x10089852..0x100898A2: + // repeat the conversions and extent calls, narrowing the numerator to float. + if (val.to_number() == 0.0 || extent_pixels(is_w) == bf2x87::Real(0.0f)) + { + s = 0.0f; + } + else + { + const float numerator = (float) val.to_number(); + s = bf2x87::store(bf2x87::div(bf2x87::Real(numerator), extent_pixels(is_w))); + } set_matrix(m); format_text(); return true; } if (name == "border") { m_border = val.to_bool(); return true; } - if (name == "borderColor") { const Uint32 c = (Uint32) val.to_number(); m_border_color = rgba((c >> 16) & 255, (c >> 8) & 255, c & 255, 255); return true; } + // 0x10089915 / 0x10089999 use the same signed dword conversion. + if (name == "borderColor") { const Uint32 c = (Uint32) bf2x87::toIntTruncate(val.to_number()); m_border_color = rgba((c >> 16) & 255, (c >> 8) & 255, c & 255, 255); return true; } if (name == "background") { m_background = val.to_bool(); return true; } - if (name == "backgroundColor") { const Uint32 c = (Uint32) val.to_number(); m_background_color = rgba((c >> 16) & 255, (c >> 8) & 255, c & 255, 255); return true; } + if (name == "backgroundColor") { const Uint32 c = (Uint32) bf2x87::toIntTruncate(val.to_number()); m_background_color = rgba((c >> 16) & 255, (c >> 8) & 255, c & 255, 255); return true; } if (name == "password") { m_password = val.to_bool(); return true; } - if (name == "tabIndex") { set_tab_index((int) val.to_number()); return true; } + if (name == "tabIndex") + { + // Unregister before conversion: an object conversion can run code. + if (m_tab_index >= 0 && m_tab_index < s_tab_table.size() && s_tab_table[m_tab_index] == this) + s_tab_table[m_tab_index] = NULL; + m_tab_index = bf2x87::lowWord(bf2x87::toInt64Truncate(bf2x87::Real(val.to_number()))); + // As in 0x10089A3B, negative/invalid indices are unchecked here. + register_text_tab(m_tab_index, this); + return true; + } if (name == "onChanged") { m_on_changed = val; return true; } if (name == "onSetFocus") { m_on_set_focus = val; return true; } - if (name == "maxChars") { m_max_chars = (int) val.to_number(); return true; } + if (name == "maxChars") { m_max_chars = bf2x87::toIntTruncate(val.to_number()); return true; } if (name == "restrict") { m_restrict = ""; @@ -2010,50 +2278,80 @@ namespace gameswf } return true; } - if (name == "_x" || name == "_y" || name == "_visible" || name == "_alpha") - { - return false; // the stock switch below handles these four the same way - } // Anything else lives in the field's own environment (the shipped falls through to it). m_as_environment.set_member(name, val); return true; } - bool dice_get_member(const tu_stringi& name, as_value* val) + // SwiffPlayer.dll 0x10087C60; exact names, then the environment bag. + // [CHOSEN, not recovered] S3 bridge: native keys remain tu_stringi and + // native extent virtuals return twips, converted at their consumers. + bool dice_get_member(const tu_stringi& member_name, as_value* val) { - if (name == "text") { val->set_tu_string(m_text); return true; } + const tu_string& name = member_name.to_tu_string(); + if (name == "_x" || name == "_y") + { + const matrix m = get_matrix(); + // Both coordinates publish the product directly as double. + val->set_double(double(bf2x87::mul( + bf2x87::Real(m.m_[name == "_x" ? 0 : 1][2]), bf2x87::Real(0.05f)))); + return true; + } + if (name == "text") + { + // The caller may supply a String object to fill in place. Retail + // extracts OBJECT only and does not validate its concrete type. + if (as_object_interface* string = val->to_object_raw()) + assign_dice_string_object_narrow(string, m_text.c_str()); + else val->set_tu_string(m_text); + return true; + } + if (name == "_visible") { val->set_bool(get_visible()); return true; } + if (name == "_alpha") + { + val->set_double(double(bf2x87::mul(bf2x87::Real(get_cxform().m_[3][0]), bf2x87::Real(100.0f)))); + return true; + } if (name == "textColor") { - val->set_double((double) (int) (((Uint32) m_text_color.m_a << 24) | ((Uint32) m_text_color.m_r << 16) | ((Uint32) m_text_color.m_g << 8) | m_text_color.m_b)); + const int color = (int) (((Uint32) m_text_color.m_a << 24) | ((Uint32) m_text_color.m_r << 16) | ((Uint32) m_text_color.m_g << 8) | m_text_color.m_b); + val->set_int(color); return true; } - if (name == "_width") { val->set_double(TWIPS_TO_PIXELS(get_width())); return true; } - if (name == "_height") { val->set_double(TWIPS_TO_PIXELS(get_height())); return true; } - if (name == "textHeight") { val->set_double((double) (int) (m_def->m_text_height * 0.05f)); return true; } + if (name == "_width") { val->set_double(double(extent_pixels(true))); return true; } + if (name == "_height") { val->set_double(double(extent_pixels(false))); return true; } + // sub_10087C60: `textHeight` is vslot 0x10C, the laid-out height formatText + // last requested (m_text_height_px), not the font size. The loading screen's label + // component sets `_height = textHeight`; with the font size every multi-line field shrank + // to one line and the next formatText stopped after the first wrap. + if (name == "textHeight") { val->set_int(get_text_height()); return true; } if (name == "border") { val->set_bool(m_border); return true; } - if (name == "borderColor") { val->set_double((double) (int) (((Uint32) m_border_color.m_a << 24) | ((Uint32) m_border_color.m_r << 16) | ((Uint32) m_border_color.m_g << 8) | m_border_color.m_b)); return true; } + if (name == "borderColor") { val->set_int((int) (((Uint32) m_border_color.m_a << 24) | ((Uint32) m_border_color.m_r << 16) | ((Uint32) m_border_color.m_g << 8) | m_border_color.m_b)); return true; } if (name == "background") { val->set_bool(m_background); return true; } - if (name == "backgroundColor") { val->set_double((double) (int) (((Uint32) m_background_color.m_a << 24) | ((Uint32) m_background_color.m_r << 16) | ((Uint32) m_background_color.m_g << 8) | m_background_color.m_b)); return true; } + if (name == "backgroundColor") { val->set_int((int) (((Uint32) m_background_color.m_a << 24) | ((Uint32) m_background_color.m_r << 16) | ((Uint32) m_background_color.m_g << 8) | m_background_color.m_b)); return true; } if (name == "password") { val->set_bool(m_password); return true; } if (name == "tabIndex") { if (m_tab_index < 0) return false; val->set_int(m_tab_index); return true; } if (name == "onChanged") { *val = m_on_changed; return true; } if (name == "onSetFocus") { *val = m_on_set_focus; return true; } - if (name == "maxChars") { val->set_int(m_max_chars); return true; } - if (name == "restrict") { val->set_string(""); return true; } + if (name == "maxChars") { *val = as_value(m_max_chars); return true; } + if (name == "restrict") { *val = as_value(""); return true; } if (name == "_focus") { val->set_bool(s_focused_field == this); return true; } if (name == "_parent") { val->set_as_object_interface(get_parent() ? static_cast(get_parent()) : NULL); return true; } - if (name == "_x" || name == "_y" || name == "_visible" || name == "_alpha") - { - return false; // the stock switch below - } return m_as_environment.get_member(name, val); } }; - // [DICE-MOD #37] the focused-field surface SwiffPlayer's key/char/clipboard entries use. + // SwiffPlayer.dll 0x10084D90; the native focus stores the field owner rather + // than its secondary interface, so compare the adjusted interface pointer. + text_input::~text_input() + { + if (get_focused_text_input() == this) s_focused_field = NULL; + } + + // the focused-field surface SwiffPlayer's key/char/clipboard entries use. text_input* get_focused_text_input() { return s_focused_field; @@ -2071,6 +2369,9 @@ namespace gameswf } + // SwiffPlayer.dll 0x10089C50. + // [CHOSEN, not recovered] S3 bridge: + // native factories return raw storage instead of a smart-pointer result. character* edit_text_character_def::create_character_instance(movie* parent, int id) { if (m_font == NULL) @@ -2089,6 +2390,8 @@ namespace gameswf } + // SwiffPlayer.dll 0x10085CE0. [CHOSEN, not recovered] S3 bridge: + // the native factory assigns the resource ID when publishing the definition. void define_edit_text_loader(stream* in, int tag_type, movie_definition_sub* m) // Read a DefineText tag. { diff --git a/Code/BF2/External/gameswf/gameswf_textformat.cpp b/Code/BF2/External/gameswf/gameswf_textformat.cpp deleted file mode 100644 index 4c4066859..000000000 --- a/Code/BF2/External/gameswf/gameswf_textformat.cpp +++ /dev/null @@ -1,217 +0,0 @@ -// gameswf_xml.h -- Rob Savoye 2005 - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - -#include "gameswf_log.h" -#include "gameswf_textformat.h" - -namespace gameswf -{ - - text_format::text_format() : - _underline(false), - _bold(false), - _italic(false), - _bullet(false), - _block_indent(-1), - _color(0), - _indent(-1), - _leading(-1), - _left_margin(-1), - _right_margin(-1), - _point_size(-1), - _tab_stops(-1), - _target(-1) -{ - //log_msg("%s: \n", __FUNCTION__); -} - -text_format::~text_format() -{ - // don't need to clean up anything -} - -// Copy one text_format object to another. -text_format * -text_format::operator = (text_format &format) -{ - log_msg("%s: \n", __FUNCTION__); - - _underline = format._underline; - _bold = format._bold; - _italic = format._italic; - _bullet = format._bullet; - - _align = format._align; - _block_indent = format._block_indent; - _color = format._color; - _font = format._font; - _indent = format._indent; - _leading = format._leading; - _left_margin = format._left_margin; - _right_margin = format._right_margin; - _point_size = format._point_size; - _tab_stops = format._tab_stops; - _target = format._target; - _url = format._url; - - return this; -} - -// In a paragraph, change the format of a range of characters. -void -text_format::setTextFormat (text_format &format) -{ - //log_msg("%s: \n", __FUNCTION__); -} - -void -text_format::setTextFormat (int index, text_format &format) -{ - //log_msg("%s: \n", __FUNCTION__); -} - -void -text_format::setTextFormat (int start, int end, text_format &format) -{ - //log_msg("%s: \n", __FUNCTION__); -} - -#if 0 -text_format & -text_format::getTextFormat () -{ - log_msg("%s: \n", __FUNCTION__); -} - -text_format & -text_format::getTextFormat (int index) -{ - log_msg("%s: \n", __FUNCTION__); -} - -text_format & -text_format::getTextFormat (int start, int end) -{ - log_msg("%s: \n", __FUNCTION__); -} -#endif - -void textformat_new(const fn_call& fn) -{ - //log_msg("%s: args=%d\n", __FUNCTION__, nargs); - - textformat_as_object* text_obj = new textformat_as_object; - log_msg("\tCreated New TextFormat object at %p. Not fully implmented yet!\n", text_obj); - - // tulrich: this looks like it's inserting a method into our - // caller's env. setTextFormat is a method on TextField. So here - // we're hoping our caller is a text field... scary. - // - // TODO we should handle setTextFormat as a method on TextField, - // instead of doing this. - fn.env->set_variable("setTextFormat", &textformat_setformat, 0); - - fn.result->set_as_object_interface(text_obj); -} - - -void textformat_setformat(const fn_call& fn) -{ - as_value method; - //log_msg("%s: args=%d at %p\n", __FUNCTION__, nargs, this_ptr); -#if 0 - // FIXME: these are only commented out to eliminate compilation warnings. - textformat_as_object* ptr = (textformat_as_object*) fn.this_ptr; // tulrich: TODO fix this unsafe cast; see textformat_new(). - assert(ptr); - double start = fn.arg(0).to_number(); - double end = fn.arg(1).to_number(); -#endif - textformat_as_object *obj = (textformat_as_object*) fn.arg(2).to_object(); // tulrich: TODO fix this unsafe cast. (need cast_to_textformat()) - assert(obj); - - //log_msg("Change from %f for %f characters for object at %p\n", start, end, obj); - - // Check for the flags that could be set - if (obj->get_member("underline", &method)) { - //log_msg("Underline exists and is set to %d\n", method.to_bool()); - obj->obj.underlinedSet(method.to_bool()); - } - - if (obj->get_member("italic", &method)) { - //log_msg("Italic exists and is set to %d\n", method.to_bool()); - obj->obj.italicedSet(method.to_bool()); - } - - if (obj->get_member("bold", &method)) { - //log_msg("Bold exists and is set to %d\n", method.to_bool()); - obj->obj.boldSet(method.to_bool()); - } - - if (obj->get_member("bullet", &method)) { - //log_msg("Bullet exists and is set to %d\n", method.to_bool()); - obj->obj.bulletSet(method.to_bool()); - } - - if (obj->get_member("color", &method)) { - //log_msg("Color exists and is set to %f\n", method.to_number()); - obj->obj.colorSet((uint32)method.to_number()); - } - - if (obj->get_member("indent", &method)) { - //log_msg("Indent exists and is set to %f\n", method.to_number()); - obj->obj.indentSet(float(method.to_number())); - } - - if (obj->get_member("align", &method)) { - //log_msg("Align exists and is set to %s\n", method.to_string()); - obj->obj.alignSet(method.to_tu_string()); - } - - if (obj->get_member("blockIndent", &method)) { - //log_msg("BlockIndent exists and is set to %f\n", method.to_number()); - obj->obj.blockIndentSet(float(method.to_number())); - } - - if (obj->get_member("leading", &method)) { - //log_msg("Leading exists and is set to %f\n", method.to_number()); - obj->obj.leadingSet(float(method.to_number())); - } - - if (obj->get_member("leftMargin", &method)) { - //log_msg("LeftMargin exists and is set to %f\n", method.to_number()); - obj->obj.leftMarginSet(float(method.to_number())); - } - - if (obj->get_member("RightMargin", &method)) { - //log_msg("RightMargin exists and is set to %f\n", method.to_number()); - obj->obj.rightMarginSet(float(method.to_number())); - } - - if (obj->get_member("size", &method)) { - //log_msg("Size exists and is set to %f\n", method.to_number()); - obj->obj.sizeSet(float(method.to_number())); - } - - //ptr->obj.setTextFormat(start, end, obj->obj); - //result->set_bool(true); -} -#if 0 - void - textformat_getformat(gameswf::as_value* result, gameswf::as_object_interface* this_ptr, gameswf::as_environment* env, int nargs, int first_arg) -{ - log_msg("%s: args=%d unfinished implementation\n", __FUNCTION__, nargs); - textformat_as_object* ptr = (textformat_as_object*)this_ptr; - assert(ptr); - double start = env->bottom(first_arg).to_number(); - double end = env->bottom(first_arg-1).to_number(); - textformat_as_object *obj = (textformat_as_object *)env->bottom(first_arg-2).to_object(); - assert(obj); - - ptr->obj = ptr->obj.getTextFormat(); - result->set_bool(true); -} -#endif - -} // end of gameswf namespace diff --git a/Code/BF2/External/gameswf/gameswf_textformat.h b/Code/BF2/External/gameswf/gameswf_textformat.h deleted file mode 100644 index 58e9bcfd3..000000000 --- a/Code/BF2/External/gameswf/gameswf_textformat.h +++ /dev/null @@ -1,114 +0,0 @@ -// gameswf_xml.h -- Rob Savoye 2005 - -// This source code has been donated to the Public Domain. Do whatever -// you want with it. - -#ifndef __TEXTFORMAT_H__ -#define __TEXTFORMAT_H__ - - -#include "gameswf_log.h" -#include "gameswf_action.h" -#include "gameswf_impl.h" - - -namespace gameswf -{ - -class text_format -{ -public: - // new text_format([font, [size, [color, [bold, [italic, [underline, [url, [target, [align, - // [leftMargin, [rightMargin, [indent, [leading]]]]]]]]]]]]]) - - text_format(); - // tulrich: TODO need to take const ref! - text_format(tu_string font); - text_format(tu_string font, int size); - text_format(tu_string font, int size, int color); - ~text_format(); - - bool underlined() { return _underline; } - bool italiced() { return _italic; } - bool bold() { return _bold; } - bool bullet() { return _bullet; } - uint32 color() const { return _color; } - float indent() const { return _indent; } - const tu_string& align() const { return _align; } - float blockIndent() { return _block_indent; } - float leading() { return _leading; } - float leftMargin() { return _left_margin; } - float RightMargin() { return _right_margin; } - float size() { return _point_size; } - - void underlinedSet(bool x) { _underline = x; } - void italicedSet(bool x) { _italic = x; } - void boldSet(bool x) { _bold = x; } - void bulletSet(bool x) { _bullet = x; } - void colorSet(uint32 x) { _color = x; } - void indentSet(float x) { _indent = x; } - void alignSet(tu_string x) { _align = x; } - void blockIndentSet(float x) { _block_indent = x; } - void leadingSet(float x) { _leading = x; } - void leftMarginSet(float x) { _left_margin = x; } - void rightMarginSet(float x) { _right_margin = x; } - void sizeSet(float x) { _point_size = x; } - - // In a paragraph, change the format of a range of characters. - void setTextFormat (text_format &format); - void setTextFormat (int index, text_format &format); - void setTextFormat (int start, int end, text_format &format); - - text_format &getTextFormat (); - text_format &getTextFormat (int index); - text_format &getTextFormat (int start, int end); - - int getTextExtant(); - text_format *operator = (text_format &format); - - private: - bool _underline; // A Boolean value that indicates whether the text is underlined. - bool _bold; // A Boolean value that indicates whether the text is boldface. - bool _italic; // A Boolean value that indicates whether the text is italicized. - bool _bullet; // - - tu_string _align; // The alignment of the paragraph, represented as a string. - // If "left", the paragraph is left-aligned. If "center", the - // paragraph is centered. If "right", the paragraph is - // right-aligned. - float _block_indent; // - uint32 _color; // The color of text using this text format. A number - // containing three 8-bit RGB components; for example, - // 0xFF0000 is red, 0x00FF00 is green. - tu_string _font; // The name of a font for text as a string. - float _indent; // An integer that indicates the indentation from the left - // margin to the first character in the paragraph - float _leading; // A number that indicates the amount of leading vertical - // space between lines. - float _left_margin; // Indicates the left margin of the paragraph, in points. - float _right_margin; // Indicates the right margin of the paragraph, in points. - float _point_size; // An integer that indicates the point size. - int _tab_stops; // - int _target; // The target window where the hyperlink is displayed. If the - // target window is an empty string, the text is displayed in - // the default target window _self. If the url parameter is - // set to an empty string or to the value null, you can get - // or set this property, but the property will have no effect. - tu_string _url; // The URL to which the text in this text format hyperlinks. - // If url is an empty string, the text does not have a hyperlink -}; - -struct textformat_as_object : public gameswf::as_object -{ - text_format obj; -}; - -void textformat_new(const fn_call& fn); - -void textformat_setformat(const fn_call& fn); - -void textformat_getformat(const fn_call& fn); - -} // end of gameswf namespace - -#endif // __TEXTFORMAT_H__ diff --git a/Code/BF2/External/gameswf/gameswf_timers.cpp b/Code/BF2/External/gameswf/gameswf_timers.cpp index 63b4b61b7..b2d6c824b 100644 --- a/Code/BF2/External/gameswf/gameswf_timers.cpp +++ b/Code/BF2/External/gameswf/gameswf_timers.cpp @@ -3,236 +3,139 @@ // This source code has been donated to the Public Domain. Do // whatever you want with it. +#include "../../Platform/X87Compat.h" #include "gameswf_log.h" #include "gameswf_action.h" #include "gameswf_impl.h" -#include "gameswf_log.h" #include "base/smart_ptr.h" #include "gameswf_timers.h" -#include "gameswf_xml.h" -using namespace std; namespace gameswf { - Timer::Timer() : - _which(0), - _interval(0.0), - _start(0.0), - _object(0), - _env(0) - { - } - - Timer::Timer(as_value *obj, int ms) - { - setInterval(*obj, ms); - start(); - } - - Timer::~Timer() - { - log_msg("%s: \n", __FUNCTION__); - } - - int - Timer::setInterval(as_value obj, int ms) - { - _function = obj; - _interval = ms * 0.001; // [DICE-MOD SwiffPlayer: milliseconds. The stock 0.01 made every interval ten times too long; the shipped timer keeps the raw ms.] - // _interval = ms * 0.000001; - start(); - - return 0; - } - - int - Timer::setInterval(as_value obj, int ms, as_environment *en) - { - _function = obj; - _interval = ms * 0.001; // [DICE-MOD SwiffPlayer: milliseconds. The stock 0.01 made every interval ten times too long; the shipped timer keeps the raw ms.] - _env = en; - // _interval = ms * 0.000001; - start(); - - return 0; - } - int - Timer::setInterval(as_value obj, int ms, array *locals) + // SwiffPlayer.dll 0x100774C0 copies borrowed pointers, then the method string, + // argument array and float timing fields. 0x10075E30 assigns in the same order. + // [INFERRED] Source-level type and field names; native pointer/container widths. + struct interval_record { - _function = obj; - _interval = ms * 0.001; // [DICE-MOD SwiffPlayer: milliseconds. The stock 0.01 made every interval ten times too long; the shipped timer keeps the raw ms.] - _locals = locals; - // _interval = ms * 0.000001; - start(); - - return 0; - } - - int - Timer::setInterval(as_value obj, int ms, as_object_interface *this_ptr, as_environment *en) + // Implicit construction/destruction: 0x10077B80 / 0x10077BA0 initializes + // only method/arguments, then destroys arguments before method. + as_environment* environment; + as_object_interface* receiver; + as_object_interface* target; + tu_string method; + ::array arguments; + float milliseconds; + float last_fire; + }; + + // SwiffPlayer.dll 0x100F8CC0, destructor 0x1007DA60 / veneer 0x1007EB10. + // Entry copy/construct/clear: 0x10077CA0 / 0x10077CD0 / 0x1007CD50. + // The records own only + // their method names and arguments; object/environment pointers are borrowed. + static ::hash s_intervals; + static Uint32 s_next_interval = 0; + + void clear_interval_registry() { s_intervals.clear(); } + + // [CHOSEN, not recovered] S3 bridge for the native combined movie interface; + // retail calls the receiver's environment slot directly. + static as_environment* interval_environment(as_object_interface* receiver) { - _function = obj; - _interval = ms * 0.001; // [DICE-MOD SwiffPlayer: milliseconds. The stock 0.01 made every interval ten times too long; the shipped timer keeps the raw ms.] - _env = en; - _object = this_ptr; - // _interval = ms * 0.000001; - start(); - - return 0; + movie* target = receiver->to_movie(); + return target ? target->get_action_environment() : NULL; } - void - Timer::clearInterval() - { - _interval = 0.0; - _start = 0.0; - } - - void - Timer::start() - { - uint64 ticks = tu_timer::get_profile_ticks(); - _start = tu_timer::profile_ticks_to_seconds(ticks); - } - - - bool - Timer::expired() + // SwiffPlayer.dll 0x10077910. Keep the live record and iterator across calls: + // retail neither snapshots nor protects them against callback invalidation. + void update_intervals(float movie_time) { - if (_start > 0.0) { - uint64 ticks = tu_timer::get_profile_ticks(); - double now = tu_timer::profile_ticks_to_seconds(ticks); - //printf("FIXME: %s: now is %f, start time is %f, interval is %f\n", __FUNCTION__, now, _start, _interval); - if (now > _start + _interval) { - _start = now; // reset the timer - //log_msg("Timer expired! \n"); - return true; - } - // FIXME: Sometimes, "now" and "_start" have bad values. - // I don't know why, but this works around the problem.. - else if (now < _start) { - log_msg( "Timer::expired - now (%lf) is before start (%lf)!\n" - " Expiring right now.\n", - now, _start); - _start = now; - return true; + for (::hash::iterator it = s_intervals.begin(); + it != s_intervals.end(); ++it) + { + interval_record& record = it->second; + if ((long double)record.milliseconds * 0.001f < (long double)movie_time - record.last_fire + || record.last_fire == 0.0f) + { + record.last_fire = movie_time; + if (record.receiver == NULL) continue; + set_call_super(NULL); + as_value method; + if (record.receiver->get_member(record.method.to_tu_stringi(), &method) + && (method.get_type() == as_value::C_FUNCTION || method.get_type() == as_value::AS_FUNCTION)) + { + for (int i = 0; i < record.arguments.size(); ++i) + record.environment->push_val(record.arguments[i]); + as_value result; + if (as_as_function* function = method.to_as_function()) + { + as_environment* env = interval_environment(record.receiver); + if (env) env = interval_environment(record.receiver); + else env = record.environment; + set_environment_super(env); + (*function)(fn_call(&result, record.receiver, env, + record.arguments.size(), record.environment->get_top_index())); + } + for (int i = 0; i < record.arguments.size(); ++i) + record.environment->pop(); + } } } - - // log_msg("Timer not enabled! \n"); - return false; } void timer_setinterval(const fn_call& fn) { - int i; - as_value method; - log_msg("%s: args=%d\n", __FUNCTION__, fn.nargs); - - timer_as_object *ptr = new timer_as_object; - - // action_buffer m_action_buffer; - //timer_as_object* ptr = (timer_as_object*) (as_object*) this_ptr; - assert(ptr); - - movie* mov = fn.env->get_target()->get_root_movie(); - // [DICE-MOD SwiffPlayer: both AS2 forms. The shipped gameswf_as_global_setinterval branches on - // whether arg0 converts to an object: setInterval(object, "methodName", ms, args...) resolves - // the method on that object and ticks with it as `this`; otherwise setInterval(function, ms, - // args...). Stock 2006 knew only the function form and, handed an object, stored the OBJECT as - // the "function" - every tick then logged "error in call_method(): method is not a function" - // (retail 2026-09-02: once per frame, from the menu's update manager).] - as_value val; - as_object_interface* target = NULL; - int ms = 0; + // SwiffPlayer.dll 0x1007E030: argument refusal precedes timer allocation. + if (fn.nargs < 2) { - const as_value& first = fn.env->bottom(fn.first_arg_bottom_index); - if (first.to_as_function() == NULL && first.to_object() != NULL && fn.nargs >= 3) - { - target = first.to_object(); - const tu_string method_name = fn.env->bottom(fn.first_arg_bottom_index - 1).to_tu_string(); - target->get_member(tu_stringi(method_name.c_str()), &val); - ms = (int) fn.env->bottom(fn.first_arg_bottom_index - 2).to_number(); - } - else - { - as_as_function *as_func = (as_as_function *)first.to_as_function(); - val = as_value(as_func); - ms = (int) fn.env->bottom(fn.first_arg_bottom_index - 1).to_number(); - } + log_error("error: set_interval needs atleast two args\n"); + return; } - - // [TEMP] RW-89 timer trace. Remove with the tracers. - log_error("[setInterval] form=%s method_type=%d ms=%d target=%p\n", - target ? "object" : "function", (int) val.get_type(), ms, target); - - tu_string local_name; - as_value local_val; - array dummy_with_stack; - - fn.env->add_frame_barrier(); - //method = env->get_variable("loopvar", dummy_with_stack); - -#if 1 - // FIXME: This is pretty gross, but something is broke elsewhere and it doesn't - // seem to effect anything else. When a function is called from a executing - // function, like calling setInterval() from within the callback to - // XMLSocket::onConnect(), the local variables of the parent function need to - // be propogated to the local stack as regular variables (not locals) or - // they can't be found in the scope of the executing chld function. There is - // probably a better way to do this... but at least this works. - for (i=0; i< fn.env->get_local_frame_top(); i++) { - if (fn.env->m_local_frames[i].m_name.size()) { - //method = env->get_variable(env->m_local_frames[i].m_name, dummy_with_stack); - //if (method.get_type() != as_value::UNDEFINED) - { - local_name = fn.env->m_local_frames[i].m_name; - local_val = fn.env->m_local_frames[i].m_value; - fn.env->set_variable(local_name, local_val, 0); - } - } + interval_record record; + record.last_fire = 0.0f; + record.environment = fn.env; + record.target = fn.env->get_target(); + const as_value& first = fn.arg(0); + record.receiver = first.get_type() == as_value::OBJECT ? first.m_object_value : NULL; + int extra; + if (record.receiver == NULL) + { + record.method = first.to_string(); + record.milliseconds = (float)fn.arg(1).to_number(); + extra = 2; } -#endif - // ptr->obj.setInterval(val, ms, (as_object *)ptr, env); - - //Ptr->obj.setInterval(val, ms); - ptr->obj.setInterval(val, ms, target ? target : (as_object_interface *)(as_object *)ptr, fn.env); - - fn.result->set_int(mov->add_interval_timer(&ptr->obj)); - } - - void - timer_expire(const fn_call& fn) - { - //log_msg("%s:\n", __FUNCTION__); - - timer_as_object* ptr = (timer_as_object*) (as_object*) fn.this_ptr; - assert(ptr); - const as_value& val = ptr->obj.getASFunction(); - - if (as_as_function* as_func = val.to_as_function()) { - // It's an ActionScript function. Call it. - log_msg("Calling ActionScript function for setInterval Timer\n"); - (*as_func)(fn_call(fn.result, fn.this_ptr, fn.env, 0, 0)); - } else { - log_error("FIXME: Couldn't find setInterval Timer!\n"); + else + { + record.method = fn.arg(1).to_string(); + if (fn.nargs < 3) + { + log_error("error: set_interval needs atleast three args\n"); + return; + } + record.milliseconds = (float)fn.arg(2).to_number(); + extra = 3; } + for (int i = extra; i < fn.nargs; ++i) + record.arguments.push_back(fn.arg(i)); + const Uint32 id = s_next_interval; + s_intervals.set(id, record); + ++s_next_interval; + fn.result->set_int(bf2x87::lowWord(id)); } void timer_clearinterval(const fn_call& fn) { - //log_msg("%s: nargs = %d\n", __FUNCTION__, nargs); - - double id = fn.env->bottom(fn.first_arg_bottom_index).to_number(); - - movie* mov = fn.env->get_target()->get_root_movie(); - // [TEMP] RW-89 timer trace. Remove with the tracers. - log_error("[clearInterval] id=%g\n", id); - mov->clear_interval_timer((int)id); - fn.result->set_bool(true); + // SwiffPlayer.dll 0x1007E210: the shipped typo names set_interval here too. + if (fn.nargs == 0) + { + log_error("error: set_interval needs one arg\n"); + return; + } + const Uint32 id = (Uint32)bf2x87::toIntTruncate(fn.arg(0).to_number()); + interval_record copy; + if (s_intervals.get(id, ©)) s_intervals.invalidate(id); } } diff --git a/Code/BF2/External/gameswf/gameswf_timers.h b/Code/BF2/External/gameswf/gameswf_timers.h index 0d2a2a615..5d3a69f5c 100644 --- a/Code/BF2/External/gameswf/gameswf_timers.h +++ b/Code/BF2/External/gameswf/gameswf_timers.h @@ -4,80 +4,23 @@ // whatever you want with it. #ifndef __TIMERS_H__ -#define __TIMERS_H_ +#define __TIMERS_H__ -#include "gameswf_log.h" #include "gameswf_action.h" -#include "gameswf_impl.h" -#include "gameswf_log.h" - -#include "base/tu_timer.h" namespace gameswf { - struct variable { - tu_string name; - as_value value; - }; - - class Timer - { - public: - Timer(); - Timer(as_value *obj, int ms); - Timer(as_value method, int ms); - ~Timer(); - int setInterval(as_value obj, int ms); - int setInterval(as_value obj, int ms, as_object_interface *this_ptr, as_environment *env); // [DICE-MOD: any object, a sprite included] - int setInterval(as_value obj, int ms, as_environment *env); - int setInterval(as_value obj, int ms, array *locals); - void setInterval(int ms) - { - _interval = ms * 0.000001; - } - - void clearInterval(); - void start(); - bool expired(); - void setObject(as_object_interface *ao) { _object = ao; } - as_object_interface *getObject() { return _object; } - - // Accessors - const as_value& getASFunction() { return _function; } - as_environment *getASEnvironment() { return _env; } - as_object_interface *getASObject() { return _object; } - array *getLocals() { return _locals; } - int getIntervalID() { return _which; } - void add_local(tu_string name, as_value value) { - struct variable *var = new struct variable; - var->name = name; - var->value = value; - _locals->push_back(var); - } - - - private: - tu_string _method; - int _which; // Which timer - double _interval; - double _start; - as_value _function; - as_object_interface *_object; // [DICE-MOD] the `this` of the tick: a plain object OR a sprite - as_environment *_env; - array *_locals; - - }; - - struct timer_as_object : public gameswf::as_object - { - Timer obj; - }; - void timer_setinterval(const fn_call& fn); void timer_clearinterval(const fn_call& fn); - void timer_expire(const fn_call& fn); + + // Dispatches the global interval table against the root's pre-advance clock. + // Receivers/environments are borrowed; callbacks may mutate the same table. + // [INFERRED] Native entry name for SwiffPlayer.dll 0x10077910. + void update_intervals(float movie_time); + // [CHOSEN, not recovered] S3 bridge to the last native player's teardown. + void clear_interval_registry(); } // end of namespace gameswf diff --git a/Code/BF2/External/gameswf/gameswf_tools.cpp b/Code/BF2/External/gameswf/gameswf_tools.cpp deleted file mode 100644 index b6d392527..000000000 --- a/Code/BF2/External/gameswf/gameswf_tools.cpp +++ /dev/null @@ -1,323 +0,0 @@ -// gameswf_tools.cpp -- Thatcher Ulrich 2004 - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - -// Some optional helper code. - - -#include "base/tu_file.h" -#include "base/utility.h" -#include "base/zlib_adapter.h" -#include "gameswf.h" -#include "gameswf_log.h" -#include "gameswf_stream.h" -#include "gameswf_types.h" - - -#if TU_CONFIG_LINK_TO_ZLIB -//#include // for compress() -#endif // TU_CONFIG_LINK_TO_ZLIB - - -namespace gameswf { namespace tools -{ - // This struct tracks an input stream. When you call - // do_copy(), it writes all the data that has been read from - // the input stream into the output stream. (Basically it - // goes by the input file position, not by the *actual* read - // calls.) - // - // The copying can be optionally cancelled. - struct copy_helper - { - tu_file* m_in; - tu_file* m_out; - int m_initial_in_pos; - bool m_done_copy; - - copy_helper(tu_file* in, tu_file* out) - : - m_in(in), - m_out(out), - m_initial_in_pos(in->get_position()), - m_done_copy(false) - { - assert(m_in && m_in->get_error() == TU_FILE_NO_ERROR); - assert(m_out && m_out->get_error() == TU_FILE_NO_ERROR); - } - - - bool do_copy() - // Copy the data. Return true on success, false on failure. - { - if (m_done_copy) - { - assert(0); - log_error("gameswf::tools::copy_helper() already done copy\n"); - return false; - } - - m_done_copy = true; - - int current_in_pos = m_in->get_position(); - int bytes_to_copy = current_in_pos - m_initial_in_pos; - if (bytes_to_copy > 0) - { - m_in->set_position(m_initial_in_pos); - int bytes_copied = m_out->copy_bytes(m_in, bytes_to_copy); - - if (bytes_copied != bytes_to_copy) - { - m_in->set_position(current_in_pos); // fixup - return false; - } - assert(m_in->get_position() == current_in_pos); - - return true; - } - else - { - log_error("gameswf::tools::copy_helper asked to copy %d bytes\n", - bytes_to_copy); - return false; - } - } - }; - - - void write_placeholder_bitmap(tu_file* out, Uint16 character_id) - // Write a minimal bitmap character tag into the given stream, - // with the given character_id. - { - out->write_le16((20 << 6) | 0x3F); // tag header: tag type = 20, size = from next u32 - int tag_size_pos = out->get_position(); - out->write_le32(0); // placeholder for tag size. - - out->write_le16(character_id); - out->write_byte(4); // code for 16 bits/pixel - out->write_le16(2); // width, min pitch = 4 bytes/row - out->write_le16(1); // height - - // This is zlib-compressed data representing four 0 bytes. - static const int COMP_SIZE = 12; - unsigned char compressed_data[COMP_SIZE] = - { - 0x78, - 0x9c, - 0x63, - 0x60, - 0x60, - 0x60, - 0x00, - 0x00, - 0x00, - 0x04, - 0x00, - 0x01, - }; - out->write_bytes(compressed_data, COMP_SIZE); - -// Here's some code to compute that at run-time. -#if 0 -#ifdef TU_CONFIG_LINK_TO_ZLIB - int buffer_bytes = 4; // width * height * bytes/pix - unsigned char buffer[4] = { 0, 0, 0, 0 }; - - static const int COMPBUFSIZE = 200; - unsigned char compressed_buffer[COMPBUFSIZE]; - - // Deflate our little dummy bitmap. - unsigned long compressed_size = COMPBUFSIZE; - int err = compress(compressed_buffer, &compressed_size, buffer, sizeof(buffer)); - if (err != Z_OK) - { - assert(0); // There's no good reason for this to fail. - log_error("write_placeholder_bitmap(): compress() failed.\n"); - } - else - { - // Dump the compressed data into the output. - out->write_bytes(compressed_buffer, compressed_size); - } -#endif // TU_CONFIG_LINK_TO_ZLIB -#endif // 0 - - // Write the actual tag size in the slot at the beginning. - int end_pos = out->get_position(); - int size = end_pos - tag_size_pos - 4; - out->set_position(tag_size_pos); - out->write_le32(size); - out->set_position(end_pos); - } - -}} // end namespace gameswf::tools - - -int gameswf::tools::process_swf(tu_file* swf_out, tu_file* in, const process_options& options) -{ - assert(in && in->get_error() == TU_FILE_NO_ERROR); - assert(swf_out && swf_out->get_error() == TU_FILE_NO_ERROR); - - // @@ Copied & adapted from movie_def_impl::read() - // @@ TODO share this wrapper code somehow (also with gameswf_parser) - - Uint32 file_start_pos = in->get_position(); - Uint32 header = in->read_le32(); - Uint32 file_length = in->read_le32(); - Uint32 file_end_pos = file_start_pos + file_length; - - int version = (header >> 24) & 255; - if ((header & 0x0FFFFFF) != 0x00535746 - && (header & 0x0FFFFFF) != 0x00535743) - { - // ERROR - log_error("gameswf::movie_def_impl::read() -- file does not start with a SWF header!\n"); - return 1; - } - bool compressed = (header & 255) == 'C'; - - IF_VERBOSE_PARSE(log_msg("version = %d, file_length = %d\n", version, file_length)); - - tu_file* original_in = NULL; - if (compressed) - { -#if TU_CONFIG_LINK_TO_ZLIB == 0 - log_error("gameswf can't read zipped SWF data; TU_CONFIG_LINK_TO_ZLIB is 0!\n"); - return -1; -#endif - - IF_VERBOSE_PARSE(log_msg("file is compressed.\n")); - original_in = in; - - // Uncompress the input as we read it. - in = zlib_adapter::make_inflater(original_in); - - // Subtract the size of the 8-byte header, since - // it's not included in the compressed - // stream length. - file_end_pos = file_length - 8; - } - - stream str(in); - - if (options.m_zip_whole_file) - { - // @@ TODO not implemented yet. - log_error("gameswf::tools::process_swf(): options.m_zip_whole_file is not implemented! Output will not be zipped.\n"); - } - - // - // Start the output file - // - - int output_file_start_pos = swf_out->get_position(); - swf_out->write_le32(0x06535746); // Flash 6 header, uncompressed - - // File length (need to overwrite later with the actual value. - int output_file_length_pos = swf_out->get_position(); - swf_out->write_le32(0); - - float frame_rate = 30.f; - int frame_count = 0; - { - copy_helper cp(in, swf_out); // copies everything that's read in this scope. - - rect dummy_frame_size; - dummy_frame_size.read(&str); - frame_rate = str.read_u16() / 256.0f; - frame_count = str.read_u16(); - - str.align(); - - bool success = cp.do_copy(); - if (!success) - { - // Error! - log_error("gameswf::tools::process_swf() -- unable to copy header data!\n"); - return 1; - } - } - -// m_playlist.resize(m_frame_count); - -// IF_VERBOSE_PARSE(m_frame_size.print()); - IF_VERBOSE_PARSE(log_msg("frame rate = %f, frames = %d\n", frame_rate, frame_count)); - - while ((Uint32) str.get_position() < file_end_pos) - { - copy_helper cp(in, swf_out); - - int tag_type = str.open_tag(); - if (options.m_remove_image_data - && tag_type == 8) - { - // Don't need no stinkin jpeg tables. - str.close_tag(); - } - else if (options.m_remove_image_data - && (tag_type == 6 - || tag_type == 20 - || tag_type == 21 - || tag_type == 35 - || tag_type == 36)) - { - // Some type of bitmap character tag; replace it with a minimal stand-in. - Uint16 cid = str.read_u16(); - str.close_tag(); - - // Insert substitute tag. - write_placeholder_bitmap(swf_out, cid); - } - else - { - // Leave this tag as-is. - str.close_tag(); - str.align(); - - // Copy into output. - bool success = cp.do_copy(); - if (!success) - { - // Error! - log_error("gameswf::tools::process_swf() -- error copying tag!\n"); - return 1; - } - } - - if (tag_type == 0) - { - if ((unsigned int) str.get_position() != file_end_pos) - { - // Safety break, so we don't read past the end of the - // movie. - log_msg("warning: process_swf() hit stream-end tag, but not at the " - "end of the file yet; stopping for safety\n"); - break; - } - } - } - - if (original_in) - { - // Done with the zlib_adapter. - delete in; - } - - // Go back and write the file size. - int current_pos = swf_out->get_position(); - swf_out->set_position(output_file_length_pos); - swf_out->write_le32(current_pos - output_file_start_pos); - swf_out->set_position(current_pos); - - return 0; // OK -} - - - -// Local Variables: -// mode: C++ -// c-basic-offset: 8 -// tab-width: 8 -// indent-tabs-mode: t -// End: diff --git a/Code/BF2/External/gameswf/gameswf_types.cpp b/Code/BF2/External/gameswf/gameswf_types.cpp index 2d80d2d4b..4f2166436 100644 --- a/Code/BF2/External/gameswf/gameswf_types.cpp +++ b/Code/BF2/External/gameswf/gameswf_types.cpp @@ -5,6 +5,7 @@ // Some basic types for gameswf. +#include "../../Platform/X87Compat.h" #include "gameswf_types.h" #include "gameswf_log.h" @@ -22,6 +23,7 @@ namespace gameswf // + // SwiffPlayer.dll 0x1009D800. bool point::bitwise_equal(const point& p) const // Bitwise comparison; return true if *this is bitwise // identical to p. @@ -36,6 +38,7 @@ namespace gameswf matrix matrix::identity; + // SwiffPlayer.dll 0x1009E5F0. matrix::matrix() { // Default to identity. @@ -54,6 +57,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x1009D820. void matrix::set_identity() // Set the matrix to identity. { @@ -63,23 +67,29 @@ namespace gameswf } + // SwiffPlayer.dll 0x1009E620: six float temporaries before copying the result. void matrix::concatenate(const matrix& m) // Concatenate m's transform onto ours. When // transforming points, m happens first, then our // original xform. { + using bf2x87::Real; + using bf2x87::mul; + using bf2x87::add; + using bf2x87::store; matrix t; - t.m_[0][0] = m_[0][0] * m.m_[0][0] + m_[0][1] * m.m_[1][0]; - t.m_[1][0] = m_[1][0] * m.m_[0][0] + m_[1][1] * m.m_[1][0]; - t.m_[0][1] = m_[0][0] * m.m_[0][1] + m_[0][1] * m.m_[1][1]; - t.m_[1][1] = m_[1][0] * m.m_[0][1] + m_[1][1] * m.m_[1][1]; - t.m_[0][2] = m_[0][0] * m.m_[0][2] + m_[0][1] * m.m_[1][2] + m_[0][2]; - t.m_[1][2] = m_[1][0] * m.m_[0][2] + m_[1][1] * m.m_[1][2] + m_[1][2]; + t.m_[0][0] = store(add(mul(Real(m.m_[0][0]), Real(m_[0][0])), mul(Real(m_[0][1]), Real(m.m_[1][0])))); + t.m_[1][0] = store(add(mul(Real(m_[1][0]), Real(m.m_[0][0])), mul(Real(m_[1][1]), Real(m.m_[1][0])))); + t.m_[0][1] = store(add(mul(Real(m.m_[0][1]), Real(m_[0][0])), mul(Real(m.m_[1][1]), Real(m_[0][1])))); + t.m_[1][1] = store(add(mul(Real(m.m_[1][1]), Real(m_[1][1])), mul(Real(m.m_[0][1]), Real(m_[1][0])))); + t.m_[0][2] = store(add(add(mul(Real(m.m_[0][2]), Real(m_[0][0])), mul(Real(m.m_[1][2]), Real(m_[0][1]))), Real(m_[0][2]))); + t.m_[1][2] = store(add(add(mul(Real(m.m_[1][2]), Real(m_[1][1])), mul(Real(m.m_[0][2]), Real(m_[1][0]))), Real(m_[1][2]))); *this = t; } + // SwiffPlayer.dll 0x1009D850. void matrix::concatenate_translation(float tx, float ty) // Concatenate a translation onto the front of our // matrix. When transforming points, the translation @@ -90,6 +100,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x1009D880. void matrix::concatenate_scale(float scale) // Concatenate a uniform scale onto the front of our // matrix. When transforming points, the scale @@ -102,6 +113,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x1009D8B0. void matrix::set_lerp(const matrix& m1, const matrix& m2, float t) // Set this matrix to a blend of m1 and m2, parameterized by t. { @@ -114,6 +126,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x1009D930. void matrix::set_scale_rotation(float x_scale, float y_scale, float angle) // Set the scale & rotation part of the matrix. // angle in radians. @@ -127,6 +140,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x1009D960. void matrix::read(stream* in) // Initialize from the stream. { @@ -156,10 +170,11 @@ namespace gameswf m_[1][2] = (float) in->read_sint(translate_nbits); } - //IF_VERBOSE_PARSE(log_msg(" mat: has_scale = %d, has_rotate = %d\n", has_scale, has_rotate)); + IF_VERBOSE_PARSE(log_msg("has_scale = %d, has_rotate = %d\n", has_scale, has_rotate)); } + // SwiffPlayer.dll 0x1009DA80. void matrix::print() const // Debug log. { @@ -167,6 +182,7 @@ namespace gameswf log_msg("| %4.4f %4.4f %4.4f |\n", m_[1][0], m_[1][1], TWIPS_TO_PIXELS(m_[1][2])); } + // SwiffPlayer.dll 0x1009DAE0. void matrix::transform(point* result, const point& p) const // Transform point 'p' by our matrix. Put the result in // *result. @@ -177,6 +193,7 @@ namespace gameswf result->m_y = m_[1][0] * p.m_x + m_[1][1] * p.m_y + m_[1][2]; } + // SwiffPlayer.dll 0x1009DB20. void matrix::transform_vector(point* result, const point& v) const // Transform vector 'v' by our matrix. Doesn't apply translation. // Put the result in *result. @@ -187,16 +204,25 @@ namespace gameswf result->m_y = m_[1][0] * v.m_x + m_[1][1] * v.m_y; } + // SwiffPlayer.dll 0x1009E6D0: build the inverse before reading the point; + // each coordinate narrows once, and aliased input sees the first output store. void matrix::transform_by_inverse(point* result, const point& p) const // Transform point 'p' by the inverse of our matrix. Put result in *result. { // @@ TODO optimize this! matrix m; m.set_inverse(*this); - m.transform(result, p); + using bf2x87::Real; + using bf2x87::mul; + using bf2x87::add; + result->m_x = bf2x87::store(add(add(mul(Real(m.m_[0][0]), Real(p.m_x)), + mul(Real(m.m_[0][1]), Real(p.m_y))), Real(m.m_[0][2]))); + result->m_y = bf2x87::store(add(add(mul(Real(m.m_[1][0]), Real(p.m_x)), + mul(Real(m.m_[1][1]), Real(p.m_y))), Real(m.m_[1][2]))); } + // SwiffPlayer.dll 0x1009DB50. void matrix::set_inverse(const matrix& m) // Set this matrix to the inverse of the given matrix. { @@ -228,6 +254,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x1009DC00. bool matrix::does_flip() const // Return true if this matrix reverses handedness. { @@ -237,6 +264,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x1009DC30. float matrix::get_determinant() const // Return the determinant of the 2x2 rotation/scale part only. { @@ -244,6 +272,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x1009DC40. float matrix::get_max_scale() const // Return the maximum scale factor that this transform // applies. For assessing scale, when determining acceptable @@ -254,10 +283,11 @@ namespace gameswf // length of the two basis vectors. float basis0_length2 = m_[0][0] * m_[0][0] + m_[0][1] * m_[0][1]; float basis1_length2 = m_[1][0] * m_[1][0] + m_[1][1] * m_[1][1]; - float max_length2 = fmax(basis0_length2, basis1_length2); + float max_length2 = tu_util::fmax(basis0_length2, basis1_length2); return sqrtf(max_length2); } + // SwiffPlayer.dll 0x1009DC90. float matrix::get_x_scale() const { float scale = sqrtf(m_[0][0] * m_[0][0] + m_[0][1] * m_[0][1]); @@ -271,11 +301,13 @@ namespace gameswf return scale; } + // SwiffPlayer.dll 0x1009DCD0. float matrix::get_y_scale() const { return sqrtf(m_[1][1] * m_[1][1] + m_[1][0] * m_[1][0]); } + // SwiffPlayer.dll 0x1009DCF0. float matrix::get_rotation() const { if (get_determinant() < 0.f) @@ -303,6 +335,7 @@ namespace gameswf cxform cxform::identity; + // SwiffPlayer.dll 0x1009DD20. cxform::cxform() // Initialize to identity transform. { @@ -316,6 +349,7 @@ namespace gameswf m_[3][1] = 0; } + // SwiffPlayer.dll 0x1009DD50. void cxform::concatenate(const cxform& c) // Concatenate c's transform onto ours. When // transforming colors, c's transform is applied @@ -333,6 +367,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x1009DDB0. rgba cxform::transform(const rgba in) const // Apply our transform to the given color; return the result. { @@ -347,6 +382,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x1009DF10; the additive alpha term is one when present. void cxform::read_rgb(stream* in) { in->align(); @@ -375,6 +411,7 @@ namespace gameswf } } + // SwiffPlayer.dll 0x1009E010. void cxform::read_rgba(stream* in) { in->align(); @@ -433,6 +470,7 @@ namespace gameswf // rgba // + // SwiffPlayer.dll 0x1009E7B0. void rgba::read(stream* in, int tag_type) { if (tag_type <= 22) @@ -445,12 +483,14 @@ namespace gameswf } } + // SwiffPlayer.dll 0x1009E740: RGB (including opaque alpha), then the alpha byte. void rgba::read_rgba(stream* in) { read_rgb(in); m_a = in->read_u8(); } + // SwiffPlayer.dll 0x1009E130. void rgba::read_rgb(stream* in) { m_r = in->read_u8(); @@ -459,6 +499,7 @@ namespace gameswf m_a = 0x0FF; } + // SwiffPlayer.dll 0x1009E170. void rgba::print() // For debugging. { @@ -466,12 +507,13 @@ namespace gameswf } + // SwiffPlayer.dll 0x1009E1A0: interpolate, add 0.5, truncate and keep the low byte. void rgba::set_lerp(const rgba& a, const rgba& b, float f) { - m_r = (Uint8) frnd(flerp(a.m_r, b.m_r, f)); - m_g = (Uint8) frnd(flerp(a.m_g, b.m_g, f)); - m_b = (Uint8) frnd(flerp(a.m_b, b.m_b, f)); - m_a = (Uint8) frnd(flerp(a.m_a, b.m_a, f)); + m_r = (Uint8) bf2x87::toInt64Truncate(a.m_r + ((long double) b.m_r - a.m_r) * f + 0.5L); + m_g = (Uint8) bf2x87::toInt64Truncate(a.m_g + ((long double) b.m_g - a.m_g) * f + 0.5L); + m_b = (Uint8) bf2x87::toInt64Truncate(a.m_b + ((long double) b.m_b - a.m_b) * f + 0.5L); + m_a = (Uint8) bf2x87::toInt64Truncate(a.m_a + ((long double) b.m_a - a.m_a) * f + 0.5L); } @@ -480,6 +522,7 @@ namespace gameswf // + // SwiffPlayer.dll 0x1009E260. void rect::read(stream* in) { in->align(); @@ -492,6 +535,7 @@ namespace gameswf // IF_DEBUG(log_msg("rect::read() nbits = %d\n", nbits)); } + // SwiffPlayer.dll 0x1009E2D0. void rect::print() const // Debug spew. { @@ -503,6 +547,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x1009E320: inclusive edges; unordered comparisons pass. bool rect::point_test(float x, float y) const // Return true if the specified point is inside this rect. { @@ -520,16 +565,43 @@ namespace gameswf } + // SwiffPlayer.dll 0x1009E370: minima select the input on equality/unordered; + // maxima keep their existing value on equality/unordered. void rect::expand_to_point(float x, float y) // Expand this rectangle to enclose the given point. { - m_x_min = fmin(m_x_min, x); - m_y_min = fmin(m_y_min, y); - m_x_max = fmax(m_x_max, x); - m_y_max = fmax(m_y_max, y); + m_x_min = tu_util::fmin(m_x_min, x); + m_y_min = tu_util::fmin(m_y_min, y); + m_x_max = m_x_max < x ? x : m_x_max; + m_y_max = m_y_max < y ? y : m_y_max; + } + + // SwiffPlayer.dll 0x1009E780. + void rect::expand_to_rect(const rect& r) + { + expand_to_point(r.m_x_min, r.m_y_min); + expand_to_point(r.m_x_max, r.m_y_max); + } + + // SwiffPlayer.dll 0x1009E410; the maximum corner is stored first. + void rect::transform(const matrix& m) + { + const long double x0 = (long double)m.m_[0][0] * m_x_min + + (long double)m.m_[0][1] * m_y_min + m.m_[0][2]; + const long double y0 = (long double)m.m_[1][0] * m_x_min + + (long double)m.m_[1][1] * m_y_min + m.m_[1][2]; + const long double x1 = (long double)m.m_[0][0] * m_x_max + + (long double)m.m_[0][1] * m_y_max + m.m_[0][2]; + const long double y1 = (long double)m.m_[1][0] * m_x_max + + (long double)m.m_[1][1] * m_y_max + m.m_[1][2]; + m_x_max = (float)x1; + m_y_max = (float)y1; + m_x_min = (float)x0; + m_y_min = (float)y0; } + // SwiffPlayer.dll 0x1009E3D0. point rect::get_corner(int i) const // Get one of the rect verts. { @@ -540,6 +612,7 @@ namespace gameswf } + // SwiffPlayer.dll 0x1009E490: transform all four corners before writing the result. void rect::enclose_transformed_rect(const matrix& m, const rect& r) // Set ourself to bound a rectangle that has been transformed // by m. This is an axial bound of an oriented (and/or @@ -560,13 +633,14 @@ namespace gameswf } + // SwiffPlayer.dll 0x1009E580; coordinate write order is xmin, ymin, xmax, ymax. void rect::set_lerp(const rect& a, const rect& b, float t) // Set this to the lerp of a and b. { - m_x_min = flerp(a.m_x_min, b.m_x_min, t); - m_y_min = flerp(a.m_y_min, b.m_y_min, t); - m_x_max = flerp(a.m_x_max, b.m_x_max, t); - m_y_max = flerp(a.m_y_max, b.m_y_max, t); + m_x_min = (float)(a.m_x_min + ((long double)b.m_x_min - a.m_x_min) * t); + m_y_min = (float)(a.m_y_min + ((long double)b.m_y_min - a.m_y_min) * t); + m_x_max = (float)(a.m_x_max + ((long double)b.m_x_max - a.m_x_max) * t); + m_y_max = (float)(a.m_y_max + ((long double)b.m_y_max - a.m_y_max) * t); } diff --git a/Code/BF2/External/gameswf/gameswf_types.h b/Code/BF2/External/gameswf/gameswf_types.h index 21bb4b618..d21d18f19 100644 --- a/Code/BF2/External/gameswf/gameswf_types.h +++ b/Code/BF2/External/gameswf/gameswf_types.h @@ -19,6 +19,8 @@ namespace gameswf extern bool s_verbose_action; extern bool s_verbose_parse; extern bool s_verbose_debug; + extern bool s_verbose_loader; + extern bool s_verbose_gc; }; #define IF_VERBOSE_ACTION(exp) if (gameswf::s_verbose_action) { exp; } @@ -38,6 +40,7 @@ namespace gameswf { Uint8 m_r, m_g, m_b, m_a; + // SwiffPlayer.dll 0x1006EBD0. rgba() : m_r(255), m_g(255), m_b(255), m_a(255) {} rgba(Uint8 r, Uint8 g, Uint8 b, Uint8 a) @@ -50,6 +53,7 @@ namespace gameswf void read_rgba(stream* in); void read_rgb(stream* in); + // SwiffPlayer.dll 0x10084D40. void set(Uint8 r, Uint8 g, Uint8 b, Uint8 a) { m_r = r; diff --git a/Code/BF2/External/gameswf/gameswf_xml.cpp b/Code/BF2/External/gameswf/gameswf_xml.cpp index 9903bb6aa..5837df6c5 100644 --- a/Code/BF2/External/gameswf/gameswf_xml.cpp +++ b/Code/BF2/External/gameswf/gameswf_xml.cpp @@ -1,905 +1,428 @@ -// gameswf_xml.h -- Rob Savoye 2005 +// gameswf_xml.h -- Rob Savoye 2005 +// This source code has been donated to the Public Domain. Do whatever you want with it. -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - - -#include -#include - -#include "gameswf_log.h" -#include "gameswf_action.h" -#include "gameswf_impl.h" -#include "gameswf_log.h" -#include "base/smart_ptr.h" -#include "gameswf_string.h" -#include "base/tu_config.h" - -#ifdef HAVE_LIBXML - -#include +#include +#include +#include +#include #include "gameswf_xml.h" -#include -#include -#include +#include "gameswf_log.h" +#include "base/tu_file.h" +#include "expat/expat.h" namespace gameswf { - - //#define DEBUG_MEMORY_ALLOCATION 1 - -array _xmlobjs; // FIXME: hack alert - -XMLAttr::XMLAttr() -{ -#ifdef DEBUG_MEMORY_ALLOCATION - log_msg("\t\tCreating XMLAttr data at %p \n", this); -#endif - _name = 0; - _value = 0; -} - -XMLAttr::~XMLAttr() -{ -#ifdef DEBUG_MEMORY_ALLOCATION - log_msg("\t\tDeleting XMLAttr data %s at %p \n", this->_name, this); -#endif - //log_msg("%s: %p \n", __FUNCTION__, this); - if (_name) { - delete _name; - } - if (_value) { - delete _value; - } -} - -XMLNode::XMLNode() -{ - //log_msg("%s: %p \n", __FUNCTION__, this); -#ifdef DEBUG_MEMORY_ALLOCATION - log_msg("\tCreating XMLNode data at %p \n", this); -#endif - _name = 0; - _value = 0; -} - -XMLNode::~XMLNode() -{ - int i; - //log_msg("%s: %p \n", __FUNCTION__, this); -#ifdef DEBUG_MEMORY_ALLOCATION - log_msg("\tDeleting XMLNode data %s at %p\n", this->_name, this); -#endif - - for (i=0; i<_children.size(); i++) { -// if (_children[i]->_name) { -// delete _children[i]->_name; -// } -// if (_children[i]->_value) { -// delete _children[i]->_value; -// } - delete _children[i]; - } - - for (i=0; i<_attributes.size(); i++) { - // if (_attributes[i]->_name) { -// delete _attributes[i]->_name; -// } -// if (_attributes[i]->_value) { -// delete _attributes[i]->_value; -// } - delete _attributes[i]; - } - - _children.clear(); - _attributes.clear(); - - if (_name) { - delete _name; - } - if (_value) { - delete _value; - } - // _value.set_undefined(); -} - -XML::XML() -{ -#ifdef DEBUG_MEMORY_ALLOCATION - log_msg("Creating XML data at %p \n", this); -#endif - //log_msg("%s: %p \n", __FUNCTION__, this); - _loaded = false; - _nodename = 0; -} - - -// Parse the ASCII XML string into memory -XML::XML(tu_string xml_in) -{ -#ifdef DEBUG_MEMORY_ALLOCATION - log_msg("Creating XML data at %p \n", this); -#endif - //log_msg("%s: %p \n", __FUNCTION__, this); - //memset(&_nodes, 0, sizeof(XMLNode)); - parseXML(xml_in); -} + namespace + { + // [INFERRED] Name/placement of the small C++ parser facade used by XML. + // [CHOSEN, not recovered] The native facade has only the used methods; + // it does not reproduce the retail parser's 30-slot vtable or x86 layout. + class dice_xml_parser + { + public: + static dice_xml_parser* create(const char* encoding) + { + // SwiffPlayer.dll 0x100AF2B0: allocate, construct, init; release + // on init failure. Allocation size follows the native adapter. + void* storage = std::malloc(sizeof(dice_xml_parser)); + if (!storage) return NULL; + dice_xml_parser* parser = new (storage) dice_xml_parser; + if (!parser->init(encoding)) { parser->release(); return NULL; } + return parser; + } + + void set_element_handler(xml_document* handler) + { + // SwiffPlayer.dll 0x100AA7E0 stores the element receiver only. + m_element_handler = handler; + } + + void set_character_data_handler(xml_document* handler) + { + // SwiffPlayer.dll 0x100AA7F0 stores the character-data receiver. + m_character_data_handler = handler; + } + + int parse(const char* text, int length, int final) + { + // [CHOSEN, not recovered] C-API adapter, not the retail parser body. + return XML_Parse(m_parser, text, length, final); + } + + void release() + { + // SwiffPlayer.dll 0x100AD520 destroys then frees the allocation. + // [CHOSEN, not recovered] C-API cleanup replaces internal pools. + XML_ParserFree(m_parser); + this->~dice_xml_parser(); + std::free(this); + } + + private: + dice_xml_parser() + : m_parser(NULL), m_element_handler(NULL), m_character_data_handler(NULL) + { + // SwiffPlayer.dll 0x100AC230 initializes parser-owned storage. + // [CHOSEN, not recovered] That storage belongs to the C parser; + // retain only its handle and the two observed handler receivers. + } + + bool init(const char* encoding) + { + // SwiffPlayer.dll 0x100AF070 clears handlers/state, initializes + // encoding and storage, and reports allocation failure. + // [CHOSEN, not recovered] XML_ParserCreate owns those internals + // in the approved substitute; no retail pools are reconstructed. + m_parser = XML_ParserCreate(encoding); + if (!m_parser) return false; + XML_SetUserData(m_parser, this); + XML_SetElementHandler(m_parser, start_element, end_element); + XML_SetCharacterDataHandler(m_parser, character_data); + return true; + } + + // [CHOSEN, not recovered] C callbacks adapt retail's C++ handler + // receivers to the existing native XML document methods. + static void start_element(void* receiver, const char* name, const char** attributes) + { + dice_xml_parser* parser = static_cast(receiver); + if (parser->m_element_handler) + parser->m_element_handler->start_element(name, attributes); + } + static void end_element(void* receiver, const char* name) + { + dice_xml_parser* parser = static_cast(receiver); + if (parser->m_element_handler) parser->m_element_handler->end_element(name); + } + static void character_data(void* receiver, const char* text, int length) + { + dice_xml_parser* parser = static_cast(receiver); + if (parser->m_character_data_handler) + parser->m_character_data_handler->character_data(text, length); + } + + XML_Parser m_parser; + xml_document* m_element_handler; + xml_document* m_character_data_handler; + }; + } -XML::XML(struct node *childNode) -{ -#ifdef DEBUG_MEMORY_ALLOCATION - log_msg("\tCreating XML data at %p \n", this); -#endif - //log_msg("%s: %p \n", __FUNCTION__, this); -} + // [CHOSEN, not recovered] S3 bridge to the existing VM dispatcher, whose + // one-argument convenience wrapper is declared but not defined in this tree. + as_value call_method(const as_value& method, as_environment* env, + as_object_interface* receiver, int nargs, int first); + static void xml_set_int(as_value* result, int number) + { + // [CHOSEN, not recovered] S3 bridge: native values own one reference; + // they lack retail's ownership-discriminator byte. set_int preserves + // two retail release calls, so retain one extra native reference first. + if (result->get_type() == as_value::OBJECT && result->m_object_value) + result->m_object_value->add_ref(); + else if (result->get_type() == as_value::AS_FUNCTION && result->m_as_function_value) + result->m_as_function_value->add_ref(); + result->set_int(number); + } -XML::~XML() -{ -#ifdef DEBUG_MEMORY_ALLOCATION - if (this->_nodes) { - log_msg("\tDeleting XML top level node %s at %p \n", this->_nodes->_name, this); - } else { - log_msg("\tDeleting XML top level node at %p \n", this); - } -#endif - - //log_msg("%s: %p \n", __FUNCTION__, this); - delete _nodes; -} + static void xml_call_method1(const as_value& method, as_environment* env, + as_object_interface* receiver, const as_value& argument) + { + // [CHOSEN, not recovered] S3 bridge: use native stack/dispatch operations. + // The retail 0x1008EAD0 wrapper leaves its appended argument on the stack. + env->push(argument); + call_method(method, env, receiver, 1, env->get_top_index()); + } -// Dispatch event handler(s), if any. -bool -XML::on_event(event_id id) -{ - // Keep m_as_environment alive during any method calls! - // smart_ptr this_ptr(this); - -#if 0 - // First, check for built-in event handler. - as_value method; - if (get_event_handler(event_id(id), &method)) - {/ - // Dispatch. - call_method0(method, &m_as_environment, this); - return true; + static void xml_has_child_nodes(const fn_call& fn) + { + // SwiffPlayer.dll 0x100A83A0 reads the child link before replacing result. + const bool present = static_cast(fn.this_ptr)->m_first_child.get_ptr() != NULL; + fn.result->set_bool(present); } - - // Check for member function. - // In ActionScript 2.0, event method names are CASE SENSITIVE. - // In ActionScript 1.0, event method names are CASE INSENSITIVE. - const tu_string& method_name = id.get_function_name(); - if (method_name.length() > 0)hostByNameGet + + static void xml_append_child(const fn_call& fn) { - as_value method; - if (get_member(method_name, &method)) + // SwiffPlayer.dll 0x100A8470: no arity/type check, detach or result assignment. + xml_node* self = static_cast(fn.this_ptr); + xml_node* child = static_cast(fn.env->bottom(fn.first_arg_bottom_index).to_object()); + child->m_parent = self; + xml_node* tail = self->m_first_child.get_ptr(); + if (tail) { - call_method0(method, &m_as_environment, this); - return true; + while (tail->m_next_sibling.get_ptr()) tail = tail->m_next_sibling.get_ptr(); + tail->insert_sibling(child); } + else self->m_first_child = child; } -#endif - return false; -} -void -XML::on_event_load() -{ - // Do the events that (appear to) happen as the movie - // loads. frame1 tags and actions are executed (even - // before advance() is called). Then the onLoad event - // is triggered. - { - on_event(event_id::LOAD); - } -} + static void xml_create_element(const fn_call& fn) + { + // SwiffPlayer.dll 0x100A84C0 allocates before converting the first argument. + // [CHOSEN, not recovered] S3 bridge to native allocation/construction. + void* storage = ::operator new(sizeof(xml_node)); + const char* name = fn.env->bottom(fn.first_arg_bottom_index).to_string(); + xml_node* node = new (storage) xml_node(name, 1, NULL); + fn.result->set_as_object_interface(node); + } -XMLNode* -XML::extractNode(xmlNodePtr node, bool mem) -{ - xmlAttrPtr attr; - xmlNodePtr childnode; - xmlChar *ptr = NULL; - XMLNode *element, *child; - int len; - - element = new XMLNode; - - //log_msg("Created new element for %s at %p\n", node->name, element); - memset(element, 0, sizeof (XMLNode)); - - //log_msg("%s: extracting node %s\n", __FUNCTION__, node->name); - - // See if we have any Attributes (properties) - attr = node->properties; - while (attr != NULL) { - //log_msg("extractNode %s has property %s, value is %s\n", - // node->name, attr->name, attr->children->content); - XMLAttr *attrib = new XMLAttr; - len = memadjust(strlen(reinterpret_cast(attr->name))+1); - attrib->_name = (char *)new char[len]; - memset(attrib->_name, 0, len); - strcpy(attrib->_name, reinterpret_cast(attr->name)); - len = memadjust(strlen(reinterpret_cast(attr->children->content))+1); - attrib->_value = (char *)new char[len]; - memset(attrib->_value, 0, len); - strcpy(attrib->_value, reinterpret_cast(attr->children->content)); - //log_msg("\tPushing attribute %s for element %s has value %s\n", - // attr->name, node->name, attr->children->content); - element->_attributes.push_back(attrib); - attr = attr->next; - } - - len = memadjust(strlen(reinterpret_cast(node->name))+1); - element->_name = (char *)new char[len]; - memset(element->_name, 0, len); - strcpy(element->_name, reinterpret_cast(node->name)); - //element->_name = reinterpret_cast(node->name); - if (node->children) { - //ptr = node->children->content; - ptr = xmlNodeGetContent(node->children); - if (ptr != NULL) { - if ((strchr((const char *)ptr, '\n') == 0) && (ptr[0] != 0)) - { - if (node->children->content == NULL) { - //log_msg("Node %s has no contents\n", node->name); - } else { - //log_msg("extractChildNode from text for %s has contents %s\n", node->name, ptr); - len = memadjust(strlen(reinterpret_cast(ptr))+1); - element->_value = (char *)new char[len]; - memset(element->_value, 0, len); - strcpy(element->_value, reinterpret_cast(ptr)); - //element->_value = reinterpret_cast(ptr); + xml_node::xml_node(const char* name, int type, xml_node* parent) + : m_node_value(create_dice_string_object(NULL, 0)), + m_node_name(create_dice_string_object(NULL, 0)), + m_attributes(new as_object), + m_parent(NULL), m_previous_sibling(NULL) + { + // SwiffPlayer.dll 0x100A8EB0: value, name, attributes; raw links cleared; + // hasChildNodes, appendChild, createElement installed before linking parent. + m_node_type = type; + if (name) assign_dice_string_object_narrow(m_node_name.get_ptr(), name); + as_object::set_member("hasChildNodes", &xml_has_child_nodes); + as_object::set_member("appendChild", &xml_append_child); + as_object::set_member("createElement", &xml_create_element); + if (parent) + { + m_parent = parent; + xml_node* tail = parent->m_first_child.get_ptr(); + if (tail) + { + while (tail->m_next_sibling.get_ptr()) tail = tail->m_next_sibling.get_ptr(); + tail->m_next_sibling = this; + m_previous_sibling = tail; + } + else parent->m_first_child = this; } - } - xmlFree(ptr); - } - } - - // See if we have any data (content) - childnode = node->children; - - while (childnode != NULL) { - if (childnode->type == XML_ELEMENT_NODE) { - //log_msg("\t\t extracting node %s\n", childnode->name); - child = extractNode(childnode, mem); - //if (child->_value.get_type() != as_value::UNDEFINED) { - if (child->_value != 0) { - //log_msg("\tPushing childNode %s, value %s on element %p\n", child->_name.c_str(), child->_value.to_string(), element); - } else { - //log_msg("\tPushing childNode %s on element %p\n", child->_name.c_str(), element); - } - element->_children.push_back(child); } - childnode = childnode->next; - } - return element; -} - -// Read in an XML document from the specified source -bool -XML::parseDoc(xmlDocPtr document, bool mem) -{ - XMLNode *top; - xmlNodePtr cur; - - if (document == 0) { - log_error("Can't load XML file!\n"); - return false; - } - - cur = xmlDocGetRootElement(document); - - if (cur != NULL) { - top = extractNode(cur, mem); - //_nodes->_name = reinterpret_cast(cur->name); - _nodes = top; - //_node_data.push_back(top); - //cur = cur->next; - } - - _loaded = true; - return true; -} - -// This reads in an XML file from disk and parses into into a memory resident -// tree which can be walked through later. -bool -XML::parseXML(tu_string xml_in) -{ - bool ret = true; - //log_msg("Parse XML from memory: %s\n", xml_in.c_str()); - - if (xml_in.size() == 0) { - log_error("XML data is empty!\n"); - return false; - } - -#ifndef USE_DMALLOC - //dump_memory_stats(__FUNCTION__, __LINE__, "before xmlParseMemory"); -#endif - -#ifdef USE_XMLREADER - XMLNode *node = 0; - xmlTextReaderPtr reader; - - reader = xmlReaderForMemory(xml_in.c_str(), xml_in.size(), NULL, NULL, 0); - if (reader != NULL) { - ret = true; - while (ret) { - ret = xmlTextReaderRead(reader); - node = processNode(reader, node); - } - xmlFreeTextReader(reader); - if (ret != false) { - log_error("%s : couldn't parse\n", xml_in.c_str()); - return false; + void xml_node::clear_children() + { + // SwiffPlayer.dll 0x100A8350 clears only the head link. + m_first_child = NULL; } - } else { - log_error("Unable to open %s\n", xml_in.c_str()); - return false; - } - xmlCleanupParser(); - return true; -#else -#ifdef USE_DOM - xmlInitParser(); - - _doc = xmlParseMemory(xml_in.c_str(), xml_in.size()); - if (_doc == 0) { - log_error("Can't parse XML data!\n"); - return false; - } - ret = parseDoc(_doc, true); - xmlCleanupParser(); - xmlFreeDoc(_doc); - xmlMemoryDump(); -#endif -#ifndef USE_DMALLOC - //dump_memory_stats(__FUNCTION__, __LINE__, "after xmlParseMemory"); -#endif - - return ret; -#endif - -} -// XML_READER_TYPE_NONE = 0 -// XML_READER_TYPE_ELEMENT = 1, -// XML_READER_TYPE_ATTRIBUTE = 2, -// XML_READER_TYPE_TEXT = 3, -// XML_READER_TYPE_COMMENT = 8, -// XML_READER_TYPE_SIGNIFICANT_WHITESPACE = 14, -// XML_READER_TYPE_END_ELEMENT = 15, -// -// processNode: -// 2 1 IP 0 -// processNode: -// 3 3 #text 0 192.168.2.50 -// processNode: -// 2 15 IP 0 -// processNode: -// 2 14 #text 0 -const char *tabs[] = { - "", - "\t", - "\t\t", - "\t\t\t", - "\t\t\t", - "\t\t\t\t", -}; - -#ifdef USE_XMLREADER -// This is an xmlReader (SAX) based parser. For some reason it core dumps -// when compiled with GCC 3.x, but works just fine with GCC 4.x. -XMLNode* -XML::processNode(xmlTextReaderPtr reader, XMLNode *node) -{ - //log_msg("%s: node is %p\n", __FUNCTION__, node); - static XMLNode *parent[10]; - xmlChar *name, *value; - int depth; - XMLNode *element; - //static int previous_depth = 0; - xmlReaderTypes type; - - if (node == 0) { - memset(parent, 0, sizeof(XMLNode *)); - } - type = (xmlReaderTypes)xmlTextReaderNodeType(reader); - depth = xmlTextReaderDepth(reader); - value = xmlTextReaderValue(reader); - name = xmlTextReaderName(reader); - - if (name == NULL) - name = xmlStrdup(BAD_CAST "--"); - -#if 0 - printf("%d %d %s %d\n", - depth, - (int)type, - name, - xmlTextReaderIsEmptyElement(reader)); -#endif - - - //child = node->_children[0]; - switch(xmlTextReaderNodeType(reader)) { - case XML_READER_TYPE_NONE: - break; - case XML_READER_TYPE_SIGNIFICANT_WHITESPACE: // This is an empty text node - //log_msg("\tWhitespace at depth %d\n", depth); - break; - case XML_READER_TYPE_END_ELEMENT: - if (depth == 0) { // This is the last node in the file - element = node; - break; - } - parent[depth]->_children.push_back(element); -// log_msg("Pushing element %s on node %s\n", node->_name, parent[depth]->_name); -// log_msg("End element at depth %d is %s for parent %s %p\n", depth, name, -// parent[depth]->_name, parent[depth]); - element = parent[depth]; - break; - case XML_READER_TYPE_ELEMENT: - element = new XMLNode; -// log_msg("%sElement at depth %d is %s for node at %p\n", tabs[depth], depth, name, element); - element->_name = (char *)new char[strlen(reinterpret_cast(name))+1]; - memset(element->_name, 0, strlen(reinterpret_cast(name))+1); - strcpy(element->_name, reinterpret_cast(name)); - if (node == 0) { - _nodes = element; - parent[0] = element; - } else { - parent[depth] = node; - parent[depth+1] = node; - } - // xmlTextReaderAttributeCount(reader); - if (xmlTextReaderHasAttributes(reader)) { - // log_msg("Has Attributes!\n"); - xmlTextReaderMoveToFirstAttribute(reader); - processNode(reader, element); - while(xmlTextReaderMoveToNextAttribute(reader)) { - processNode(reader, element); - } + void xml_node::insert_sibling(xml_node* node) + { + // SwiffPlayer.dll 0x100A8360 / XML override 0x100A8420. + if (m_next_sibling.get_ptr()) + { + m_next_sibling->m_previous_sibling = node; + node->m_next_sibling = m_next_sibling; + } + m_next_sibling = node; + node->m_previous_sibling = this; } - break; - case XML_READER_TYPE_TEXT: - element = node; -// log_msg("%sValue at depth %d is \"%s\" for node at %p\n", tabs[depth], depth, value, element); - element->_value = (char *)new char[strlen(reinterpret_cast(value))+1]; - memset(element->_value, 0, strlen(reinterpret_cast(value))+1); - strcpy(element->_value, reinterpret_cast(value)); - break; - case XML_READER_TYPE_ATTRIBUTE: - element = node; - XMLAttr *attrib = new XMLAttr; - attrib->_name = (char *)new char[strlen(reinterpret_cast(name))+1]; - memset(attrib->_name, 0, strlen(reinterpret_cast(name))+1); - strcpy(attrib->_name, reinterpret_cast(name)); - attrib->_value = (char *)new char[strlen(reinterpret_cast(value))+1]; - memset(attrib->_value, 0, strlen(reinterpret_cast(value))+1); - strcpy(attrib->_value, reinterpret_cast(value)); -// log_msg("%sPushing attribute %s, value \"%s\" for node %s\n", tabs[depth], name, value, element->_name); - element->_attributes.push_back(attrib); - break; - default: // FIXME: why does this break GCC 3.3.3 but not 3.4.3 ? - log_error("Unsupported XML type %d\n!", type); - break; - }; - - xmlFree(name); - if (value != NULL) { - xmlFree(value); - } - //previous_depth = depth; - return element; -} -#endif -// This reads in an XML file from disk and parses into into a memory resident -// tree which can be walked through later. -bool -XML::load(const char *filespec) -{ - bool ret = true; - log_msg("Load disk XML file: %s\n", filespec); - - //log_msg("%s: mem is %d\n", __FUNCTION__, mem); - -#ifdef USE_XMLREADER - XMLNode *node = 0; - xmlTextReaderPtr reader; - - reader = xmlNewTextReaderFilename(filespec); - if (reader != NULL) { - ret = true; - while (ret) { - ret = xmlTextReaderRead(reader); - node = processNode(reader, node); - } - xmlFreeTextReader(reader); - if (ret != false) { - log_error("%s : couldn't parse\n", filespec); - return false; + bool xml_node::get_member(const tu_stringi& name, as_value* value) + { + // SwiffPlayer.dll 0x100A8920. Builtin names are case sensitive; + // absent links and nodeType zero fall through to the ordinary object bag. + const char* text = name.c_str(); + if (*text) + { + const char* end = text; + while (*end >= '0' && *end <= '9') ++end; + if (!*end) + { + int index = std::atoi(text); + xml_node* child = m_first_child.get_ptr(); + while (index && child) { --index; child = child->m_next_sibling.get_ptr(); } + if (child) value->set_as_object_interface(child); + else value->set_undefined(); + return true; + } + } + if (std::strcmp(text, "childNodes") == 0) + { + // [CHOSEN, not recovered] S3 bridge to the action layer's private Array type. + smart_ptr children = create_array_object(); + for (xml_node* child = m_first_child.get_ptr(); child; child = child->m_next_sibling.get_ptr()) + array_object_push(children.get_ptr(), as_value(child)); + value->set_as_object_interface(children.get_ptr()); + return true; + } + if (std::strcmp(text, "attributes") == 0) value->set_as_object_interface(m_attributes.get_ptr()); + else if (std::strcmp(text, "nodeValue") == 0) value->set_as_object_interface(m_node_value.get_ptr()); + else if (std::strcmp(text, "nodeName") == 0) value->set_as_object_interface(m_node_name.get_ptr()); + else if (std::strcmp(text, "nodeType") == 0 && m_node_type) xml_set_int(value, m_node_type); + else if (std::strcmp(text, "parentNode") == 0 && m_parent) value->set_as_object_interface(m_parent); + else if (std::strcmp(text, "lastChild") == 0 && m_first_child.get_ptr()) + { + xml_node* child = m_first_child.get_ptr(); + while (child->m_next_sibling.get_ptr()) child = child->m_next_sibling.get_ptr(); + value->set_as_object_interface(child); + } + else if (std::strcmp(text, "firstChild") == 0 && m_first_child.get_ptr()) + value->set_as_object_interface(m_first_child.get_ptr()); + else if (std::strcmp(text, "nextSibiling") == 0 && m_next_sibling.get_ptr()) + value->set_as_object_interface(m_next_sibling.get_ptr()); + else if (std::strcmp(text, "previousSibiling") == 0 && m_previous_sibling) + value->set_as_object_interface(m_previous_sibling); + else return as_object::get_member(name, value); + return true; } - } else { - log_error("Unable to open %s\n", filespec); - return false; - } - xmlCleanupParser(); - return true; -#else -#ifdef USE_DOM - xmlInitParser(); - _doc = xmlParseFile(filespec); - if (_doc == 0) { - log_error("Can't load XML file: %s!\n", filespec); - return false; - } - ret = parseDoc(_doc, false); - xmlCleanupParser(); - xmlFreeDoc(_doc); - xmlMemoryDump(); - return true; -#else -#error "You have to enable either a DOM or an xmlReader XML parser" -#endif -#endif -} -bool -XML::onLoad() -{ - log_msg("%s: FIXME: onLoad Default event handler\n", __FUNCTION__); - - return(_loaded); -} + void xml_node::enumerate(as_environment* env) + { + // SwiffPlayer.dll 0x100A8D50 enumerates only child indices as strings. + int index = 0; + for (xml_node* child = m_first_child.get_ptr(); child; child = child->m_next_sibling.get_ptr()) + { + char name[32]; + std::sprintf(name, "%d", index++); + env->push(as_value(name)); + } + } -XMLNode * -XML::operator [] (int x) { - log_msg("%s:\n", __FUNCTION__); + xml_document::xml_document() : m_current(this), m_ignore_white(false), m_status(-1) + { + // SwiffPlayer.dll 0x100A9160 builds an unnamed type-zero XMLNode; + // installs load then onData. It does not parse constructor arguments. + set_member("load", &xml_load); + set_member("onData", &xml_ondata); + } - return _nodes->_children[x]; -} + void xml_document::set_member(const tu_stringi& name, const as_value& value) + { + // SwiffPlayer.dll 0x100A8530: ignoreWhite uses normal Boolean conversion. + if (std::strcmp(name.c_str(), "ignoreWhite") == 0) m_ignore_white = value.to_bool(); + else as_object::set_member(name, value); + } -void -XML::cleanupStackFrames(XMLNode *xml) -{ -} + bool xml_document::get_member(const tu_stringi& name, as_value* value) + { + // SwiffPlayer.dll 0x100A8BE0 tests the parser cursor, not status, for loaded. + if (std::strcmp(name.c_str(), "loaded") == 0) value->set_bool(m_current != NULL); + else if (std::strcmp(name.c_str(), "status") == 0) xml_set_int(value, m_status); + else if (std::strcmp(name.c_str(), "ignoreWhite") == 0) value->set_bool(m_ignore_white); + else return xml_node::get_member(name, value); + return true; + } -as_object * -XML::setupFrame(as_object *obj, XMLNode *xml, bool mem) -{ - int child, i; - const char *nodename; - //const char *nodevalue; - //AS_value nodevalue; - int length; - as_value inum; - XMLNode *childnode; - xmlnode_as_object *xmlchildnode_obj; - xmlattr_as_object* attr_obj; - - //log_msg("\t%s: processing node %s for object %p, mem is %d\n", __FUNCTION__, xml->_name, obj, mem); - - // Get the data for this node - nodename = xml->_name; - //nodename = xml->_name.c_str(); - //nodevalue = xml->_value; - length = xml->length(); - - // Set these members in the top level object passed in. This are used - // primarily by the disk based XML parser, where at least in all my current - // test cases this is referenced with firstChild first, then nodeName and - // childNodes. - obj->set_member("nodeName", nodename); - obj->set_member("length", length); - if (xml->_value != 0) { - obj->set_member("nodeValue", xml->_value); - //log_msg("\tnodevalue for %s is: %s\n", nodename, xml->_value); - } else { - obj->set_member("nodeValue", as_value::UNDEFINED); - } - -// if (nodevalue.get_type() != as_value::UNDEFINED) { -// obj->set_member("nodeValue", nodevalue.to_string()); -// log_msg("\tnodevalue for %s is: %s\n", nodename, nodevalue.to_string()); -// } else { -// // If there is no value, we want to define it as an empty -// // string. -// obj->set_member("nodeValue", ""); -// } - - - // Process the attributes, if any - if (xml->_attributes.size() == 0) { - //log_msg("\t\tNo attributes for node %s, created empty object at %p\n", nodename, attr_obj); -// log_msg("\t\tNo attributes for node %s\n", nodename); - } else { - attr_obj = new xmlattr_as_object; - for (i=0; i_attributes.size(); i++) { - attr_obj->set_member(xml->_attributes[i]->_name, xml->_attributes[i]->_value); -// log_msg("\t\tAdding attribute as member %s, value is %s to node %s (%p)\n", -// xml->_attributes[i]->_name, -// xml->_attributes[i]->_value, nodename, obj); + void xml_document::clear_children() + { + // SwiffPlayer.dll 0x100A8400 clears children and restores the document cursor. + m_first_child = NULL; + m_current = this; } - obj->set_member("attributes", attr_obj); - } - - //xml->_attributes.resize(0); - //obj->set_member("attributes", attr_obj); - - // Process the children, if there are any - if (length) { - //log_msg("\tProcessing %d children nodes for %s\n", length, nodename); - inum = 0; - for (child=0; childset_member(inum.to_string(), obj); - //inum += 1; - //childnode = xml->_children[child]; - } else { - childnode = xml->_children[child]; - } - setupFrame(xmlchildnode_obj, childnode, false); // setup child node - obj->set_member(inum.to_string(), xmlchildnode_obj); - inum += 1; + + void xml_document::start_element(const char* name, const char** attributes) + { + // SwiffPlayer.dll 0x100A93E0 creates and links before reading attributes. + m_current = new xml_node(name, 1, m_current); + for (const char** attribute = attributes; *attribute; attribute += 2) + m_current->m_attributes->set_member(*attribute, as_value(attribute[1])); } - } else { - //log_msg("\tNode %s has no children\n", nodename); - } - return obj; -} - -// -// Callbacks. These are the wrappers for the C++ functions so they'll work as -// callbacks from within gameswf. -// -void -xml_load(const fn_call& fn) -{ - as_value method; - as_value val; - bool ret; - struct stat stats; - - - //log_msg("%s:\n", __FUNCTION__); - - xml_as_object *xml_obj = (xml_as_object*)fn.this_ptr; - - assert(ptr); - const tu_string filespec = fn.env->bottom(fn.first_arg_bottom_index).to_string(); - - // If the file doesn't exist, don't try to do anything. - if (stat(filespec.c_str(), &stats) < 0) { - fprintf(stderr, "ERROR: doesn't exist.%s\n", filespec.c_str()); - fn.result->set(false); - return; - } - - // Set the argument to the function event handler based on whether the load - // was successful or failed. - ret = xml_obj->obj.load(filespec); - fn.result->set(ret); - - if (ret == false) { - return; - } - - //env->bottom(first_arg) = ret; - array with_stack; - array dummy_stack; - // struct node *first_node = ptr->obj.firstChildGet(); - - //const char *name = ptr->obj.nodeNameGet(); - - if (xml_obj->obj.hasChildNodes() == false) { - log_error("%s: No child nodes!\n", __FUNCTION__); - } - xml_obj->obj.setupFrame(xml_obj, xml_obj->obj.firstChild(), false); - -#if 1 - if (fn.this_ptr->get_member("onLoad", &method)) { - // log_msg("FIXME: Found onLoad!\n"); - fn.env->set_variable("success", true, 0); - fn.env->bottom(fn.first_arg_bottom_index) = true; - as_c_function_ptr func = method.to_c_function(); - if (func) - { - // It's a C function. Call it. - log_msg("Calling C function for onLoad\n"); - (*func)(fn_call(&val, xml_obj, fn.env, fn.nargs, fn.first_arg_bottom_index)); // was this_ptr instead of node - } - else if (as_as_function* as_func = method.to_as_function()) - { - // It's an ActionScript function. Call it. - log_msg("Calling ActionScript function for onLoad\n"); - (*as_func)(fn_call(&val, xml_obj, fn.env, fn.nargs, fn.first_arg_bottom_index)); // was this_ptr instead of node - } else { - log_error("error in call_method(): method is not a function\n"); - } - } else { - log_msg("Couldn't find onLoad event handler, setting up callback\n"); - // ptr->set_event_handler(event_id::XML_LOAD, (as_c_function_ptr)&xml_onload); - } -#else - xml_obj->set_event_handler(event_id::XML_LOAD, &xml_onload); - -#endif - - fn.result->set(true); -} + void xml_document::end_element(const char* name) + { + // SwiffPlayer.dll 0x100A8460 discards the closing name and follows parent. + (void) name; + m_current = m_current->m_parent; + } -// This executes the event handler for XML::XML_LOAD if it's been defined, -// and the XML file has loaded sucessfully. -void -xml_onload(const fn_call& fn) -{ - //log_msg("%s:\n", __FUNCTION__); - - as_value method; - as_value val; - static bool first = true; // This event handler should only be executed once. - array empty_with_stack; - xml_as_object* ptr = (xml_as_object*) (as_object*) fn.this_ptr; - assert(ptr); - - if ((ptr->obj.loaded()) && (first)) { - // env->set_variable("success", true, 0); - //as_value bo(true); - //env->push_val(bo); - - first = false; - log_msg("The XML file has been loaded successfully!\n"); - // ptr->on_event(event_id::XML_LOAD); - //env->set_variable("success", true, 0); - //env->bottom(0) = true; - - if (fn.this_ptr->get_member("onLoad", &method)) { - // log_msg("FIXME: Found onLoad!\n"); - as_c_function_ptr func = method.to_c_function(); - if (func) - { - // It's a C function. Call it. - log_msg("Calling C function for onLoad\n"); - (*func)(fn_call(&val, fn.this_ptr, fn.env, 0, 0)); - } - else if (as_as_function* as_func = method.to_as_function()) + void xml_document::character_data(const char* text, int length) + { + // SwiffPlayer.dll 0x100A92F0 always drops all-CR/LF/tab fragments. + // With ignoreWhite it also drops all-space/CR/LF/tab fragments; it does + // not trim mixed text, merge fragments, or discard spaces by default. + int i = 0; + while (i < length && (text[i] == '\n' || text[i] == '\r' || text[i] == '\t')) ++i; + if (i == length) return; + if (m_ignore_white) { - // It's an ActionScript function. Call it. - log_msg("Calling ActionScript function for onLoad\n"); - (*as_func)(fn_call(&val, fn.this_ptr, fn.env, 0, 0)); + i = 0; + while (i < length && (text[i] == ' ' || text[i] == '\n' || text[i] == '\r' || text[i] == '\t')) ++i; + if (i == length) return; } - else - { - log_error("error in call_method(): method is not a function\n"); - } - } else { - log_msg("FIXME: Couldn't find onLoad!\n"); + m_current = new xml_node(NULL, 3, m_current); + const tu_string fragment(text, length); + // [CHOSEN, not recovered] S3 bridge: String's native assignment API is + // NUL-terminated. XML character data cannot contain a NUL byte. + assign_dice_string_object_narrow(m_current->m_node_value.get_ptr(), fragment.c_str()); + m_current = m_current->m_parent; } - } - - fn.result->set(&val); -} -// This is the default event handler, and is usually redefined in the SWF script -void -xml_ondata(const fn_call& fn) -{ - log_msg("%s:\n", __FUNCTION__); - - as_value method; - as_value val; - static bool first = true; // FIXME: ugly hack! - - xml_as_object* ptr = (xml_as_object*)fn.this_ptr; - assert(ptr); - - if ((ptr->obj.loaded()) && (first)) { - if (fn.this_ptr->get_member("onData", &method)) { - log_msg("FIXME: Found onData!\n"); - as_c_function_ptr func = method.to_c_function(); - fn.env->set_variable("success", true, 0); - if (func) - { - // It's a C function. Call it. - log_msg("Calling C function for onData\n"); - (*func)(fn_call(&val, fn.this_ptr, fn.env, 0, 0)); - } - else if (as_as_function* as_func = method.to_as_function()) + void xml_ondata(const fn_call& fn) + { + // SwiffPlayer.dll 0x100A87F0 calls onLoad with argument-definedness; + // there is no parse step here and the caller's result is untouched. + as_value method; + if (fn.this_ptr->get_member("onLoad", &method) && method.get_type() != as_value::UNDEFINED) { - // It's an ActionScript function. Call it. - log_msg("Calling ActionScript function for onData\n"); - (*as_func)(fn_call(&val, fn.this_ptr, fn.env, 0, 0)); + const as_value argument = fn.env->bottom(fn.first_arg_bottom_index); + xml_call_method1(method, fn.env, fn.this_ptr, as_value(argument.get_type() != as_value::UNDEFINED)); } - else - { - log_error("error in call_method(): method is not a function\n"); - } - } else { - log_msg("FIXME: Couldn't find onData!\n"); } - } - fn.result->set(&val); -} + bool xml_document::parse(const char* text, int length) + { + // [CHOSEN, not recovered] S3 bridge factoring the parser sequence from + // SwiffPlayer.dll 0x100A8610-0x100A8658. Retail passes isFinal=0 and + // maps exactly result 1 to status 0, all other results to -1. + dice_xml_parser* parser = dice_xml_parser::create(NULL); + parser->set_element_handler(this); + parser->set_character_data_handler(this); + const int result = parser->parse(text, length, 0); + m_status = result == 1 ? 0 : -1; + parser->release(); + return result == 1; + } -void -xml_new(const fn_call& fn) -{ - as_value inum; - xml_as_object *xml_obj; - //const char *data; - - //log_msg("%s: nargs=%d\n", __FUNCTION__, nargs); - - if (fn.nargs > 0) { - if (fn.env->top(0).get_type() == as_value::STRING) { - xml_obj = new xml_as_object; - //log_msg("\tCreated New XML object at %p\n", xml_obj); - tu_string datain = fn.env->top(0).to_tu_string(); - xml_obj->obj.parseXML(datain); - //log_msg("*** Start setting up the stack frames ***\n"); - xml_obj->obj.setupFrame(xml_obj, xml_obj->obj.firstChild(), true); - //xml_obj->obj.clear(); - //delete xml_obj->obj.firstChild(); - } else { - xml_as_object* xml_obj = (xml_as_object*)fn.env->top(0).to_object(); - //log_msg("\tCloned the XML object at %p\n", xml_obj); - //result->set(xml_obj); - fn.result->set_as_object_interface(xml_obj); - return; + void xml_load(const fn_call& fn) + { + // SwiffPlayer.dll 0x100A8570: clear first, synchronous rb read, no arity + // guard or result assignment; open failure sends undefined to onData. + xml_document* document = static_cast(fn.this_ptr); + IF_VERBOSE_ACTION(log_msg("-- load xml \n")); + document->clear_children(); + const tu_string filename(fn.env->bottom(fn.first_arg_bottom_index).to_string()); + tu_file file(filename.c_str(), "rb"); + smart_ptr source; + if (file.get_error() == TU_FILE_NO_ERROR) + { + file.go_to_end(); + const int length = file.get_position(); + file.set_position(0); + array bytes; + bytes.resize(length + 1); + file.read_bytes(&bytes[0], length); + bytes[length] = 0; + document->parse(&bytes[0], length); + source = create_dice_string_object(NULL, 0); + assign_dice_string_object_narrow(source.get_ptr(), &bytes[0]); + } + else document->m_status = -1; + as_value method; + if (document->get_member("onData", &method) && method.get_type() != as_value::UNDEFINED) + xml_call_method1(method, fn.env, document, + source.get_ptr() ? as_value(source.get_ptr()) : as_value()); } - } else { - xml_obj = new xml_as_object; - //log_msg("\tCreated New XML object at %p\n", xml_obj); - xml_obj->set_member("load", &xml_load); - xml_obj->set_member("loaded", &xml_loaded); - } - - fn.result->set_as_object_interface(xml_obj); -} -// -// SWF Property of this class. These are "accessors" into the private data -// of the class. -// + void xml_new(const fn_call& fn) + { + // SwiffPlayer.dll 0x1008B240 ignores all constructor arguments. + fn.result->set_as_object_interface(new xml_document); + } -// determines whether the document-loading process initiated by the XML.load() -// call has completed. If the process completes successfully, the method -// returns true; otherwise, it returns false. -void -xml_loaded(const fn_call& fn) -{ - as_value method; - as_value val; - - log_msg("%s:\n", __FUNCTION__); - - xml_as_object* ptr = (xml_as_object*) (as_object*) fn.this_ptr; - assert(ptr); - tu_string filespec = fn.env->bottom(fn.first_arg_bottom_index).to_string(); - fn.result->set(ptr->obj.loaded()); -} + void xmlnode_new(const fn_call& fn) + { + // SwiffPlayer.dll 0x1008B200 ignores all constructor arguments. + fn.result->set_as_object_interface(new xml_node); + } -int -memadjust(int x) -{ - return (x + (4 - x % 4)); + void release_xml_script_references(as_object* object) + { + // [CHOSEN, not recovered] issue #7 / S3 bridge: the native registry + // snapshot replaces retail's mark/clear traversal (0x100A9120). Clear + // strong XML edges while that snapshot holds all referenced objects. + xml_node* node = dynamic_cast(object); + if (!node) return; + node->m_first_child = NULL; + node->m_next_sibling = NULL; + node->m_parent = NULL; + node->m_previous_sibling = NULL; + node->m_node_value = NULL; + node->m_node_name = NULL; + node->m_attributes = NULL; + xml_document* document = dynamic_cast(node); + if (document) document->m_current = NULL; + } } - - -} // end of gameswf namespace - - -// HAVE_LIBXML -#endif diff --git a/Code/BF2/External/gameswf/gameswf_xml.h b/Code/BF2/External/gameswf/gameswf_xml.h index 0e6222624..1bf4bce34 100644 --- a/Code/BF2/External/gameswf/gameswf_xml.h +++ b/Code/BF2/External/gameswf/gameswf_xml.h @@ -1,381 +1,70 @@ -#ifndef __XML_H__ -#define __XML_H__ +// gameswf_xml.h -- Rob Savoye 2005 +// This source code has been donated to the Public Domain. -//#define DEBUG_MEMORY_ALLOCATION 1 +#ifndef GAMESWF_XML_H +#define GAMESWF_XML_H -#include "base/tu_config.h" -#include "gameswf_log.h" #include "gameswf_action.h" -#include "gameswf_impl.h" -#include "gameswf_log.h" - -#ifdef HAVE_LIBXML - -#include -#include -#include namespace gameswf { - -class XMLAttr { - public: - XMLAttr(); - ~XMLAttr(); - - char *_name; - char *_value; - - XMLAttr *operator = (XMLAttr node) { - log_msg("\t\tCopying XMLAttr object at %p\n", this); - - _name = new char[strlen(node._name)+2]; - memset(_name, 0, strlen(node._name)+2); - strcpy(_name, node._name); - - _value = new char[strlen(node._value)+2]; - memset(_value, 0, strlen(node._value)+2); - strcpy(_value, node._value); - - return this; - } -}; - -struct xmlattr_as_object : public gameswf::as_object -{ - //XMLAttr obj; - int padding; -#ifdef DEBUG_MEMORY_ALLOCATION - xmlattr_as_object() - { - log_msg("\t\tCreating xmlattr_as_object at %p\n", this); - }; - ~xmlattr_as_object() - { - log_msg("\tDeleting xmlattr_as_object at %p \n", this); - }; -#endif -}; - -class XMLNode -{ -public: - XMLNode(); - ~XMLNode(); - - int length() { return _children.size(); } - tu_string nodeName() - { - return _name; - } - - char *nodeValue() - { - return _value; - } - - // nodeType XML.nodeType - - bool hasChildNodes() - { - if (_children.size() > 0) { - return true; - } - return false; - } - - XMLNode *firstChild() - { - return _children[0]; - } - - arraychildNodes() - { - return _children; - } - - XMLNode *operator [] (int x) - { - gameswf::log_msg("%s: get element %d\n", __FUNCTION__, x); - - return _children[x]; - } - - XMLNode *operator = (XMLNode &node) - { - _name = node._name; - _value = node._value; - _children = node._children; - _attributes = node._attributes; - return this; - } - - XMLNode *operator = (XMLNode *node) - { - _name = node->_name; - _value = node->_value; - _children = node->_children; - _attributes = node->_attributes; - return this; - } - - void appendChild(XMLNode *node) - { - node->_children.push_back(node); - } - - void change_stack_frame(int frame, gameswf::as_object *xml, gameswf::as_environment *env); - - -#if 0 -appendChild() XML.appendChild() -attributes XML.attributes -childNodes XML.childNodes -cloneNode() XML.cloneNode() -insertBefore() XML.insertBefore() -lastChild XML.lastChild -nextSibling XML.nextSibling -nodeType XML.nodeType -parentNode XML.parentNode -previousSibling XML.previousSibling -removeNode() XML.removeNode() -toString() XML.toString() -#endif - char *_name; - char *_value; - array _children; - array _attributes; -}; - -struct xmlnode_as_object : public gameswf::as_object -{ - //XMLNode obj; - int _padding; - -#ifdef DEBUG_MEMORY_ALLOCATION - xmlnode_as_object() - { - log_msg("\tCreating xmlnode_as_object at %p \n", this); - }; - ~xmlnode_as_object() - { - log_msg("\tDeleting xmlnode_as_object at %p \n", this); - }; -#endif - virtual bool get_member(const tu_stringi& name, as_value* val) - { - //printf("GET XMLNode MEMBER: %s at %p for object %p\n", name.c_str(), val, this); - - if ((name == "firstChild") || (name == "childNodes")) { - //printf("Returning a self reference for %s for object at %p\n", name.c_str(), this); - val->set(this); - return true; - } - - if (m_members.get(name, val) == false) { - if (m_prototype != NULL) { - return m_prototype->get_member(name, val); - } - return false; - } - return true; - } -}; - -class XML { - public: - XML(); - XML(tu_string xml_in); - XML(struct node * childNode); - virtual ~XML(); - - // Methods - bool parseDoc(xmlDocPtr document, bool mem); // This is the base method used by both parseXML() and load(). - bool parseXML(tu_string xml_in); // Parses an XML document into the specified XML object tree. - bool load(const char *filespec); // Loads a document (specified by - // the XML object) from a URL. - - bool onLoad(); // An event handler that returns a - // Boolean value indicating whether - // the XML object was successfully - // loaded with XML.load() or - // XML.sendAndLoad(). - - // Appends a node to the end of the specified object's child list. - void appendChild(XMLNode *node) - { - _nodes->_children.push_back(node); - } - - virtual bool on_event(gameswf::event_id id); - virtual void on_event_load(); - bool loaded() { return _loaded; } - - XMLNode *firstChild() - { - return _nodes; - //return _node_data[0]; - } - - void clear() - { - delete _nodes; - } - - array childNodes() - { - return _nodes->_children; - } - - // Returns true if the specified node has child nodes; otherwise, returns false. - bool hasChildNodes() - { - return _nodes->_children.size(); - } - - XMLNode *extractNode(xmlNodePtr node, bool mem); - XMLNode *processNode(xmlTextReaderPtr reader, XMLNode *node); - - void change_stack_frame(int frame, gameswf::as_object *xml, gameswf::as_environment *env); - void setupStackFrames(gameswf::as_object *xml, gameswf::as_environment *env); - void cleanupStackFrames( XMLNode *data); - as_object *setupFrame(gameswf::as_object *xml, XMLNode *data, bool src); - - const char *nodeNameGet() + // [INFERRED] Native names and placement for DICE's XML builtins. + // [CHOSEN, not recovered] S3 bridge: typed native objects replace the + // retail embedded String/attribute objects and garbage-collected raw child links. + // These declarations do not reproduce the retail x86 object layout. + struct xml_node : public as_object { - return _nodename; - } - - int length() { return _nodes->length(); } - -#if 0 - void addRequestHeader(); // Adds or changes HTTP headers for POST - // operations. - void appendChild(); // Appends a node to the end of - // the specified object's child - // list. - void cloneNode(); // Clones the specified node and, - // optionally, recursively clones - // all children. - void createElement(); // Creates a new XML element. - void createTextNode(); //Creates a new XML text node. - void getBytesLoaded(); // Returns the number of bytes loaded for the specified XML document. - void getBytesTotal(); // Returns the size of the XML document, in bytes. - void insertBefore();// Inserts a node in front of an existing node in the specified node's child list. - void removeNode();// Removes the specified node from its parent. - void send(); // Sends the specified XML object to a URL. - void sendAndLoad(); // Sends the specified XML object to a URL and loads the server response into another XML object.void - gameswf::tu_string toString(); // Converts the specified node and - // any children to XML text. -#endif - virtual void on_xml_event(gameswf::event_id id) { on_event(id); } - - // Special event handler; - void on_event_close() { on_event(gameswf::event_id::SOCK_CLOSE); } - - XMLNode *operator [] (int x); -#if 0 - XMLNode *operator = (XMLNode &node) - { - gameswf::log_msg("%s: copy element %s\n", __FUNCTION__, node._name.c_str()); - _nodes = node; - } - -#endif - XML *operator = (XMLNode *node) - { - _nodes = node; - return this; - } - - private: - //bool _on_event_loaded; - xmlDocPtr _doc; - xmlNodePtr _firstChild; - - // Properties - bool _loaded; // Read-only; checks if - // the specified XML object has loaded. - const char *_nodename; // The node name of an XML object. - XMLNode *_nodes; - // array _node_data; - // hash _event_handlers; -#if 0 - array _childNodes; // Read-only; returns an array containing - // references to the child - // nodes of the specified - // node. - contentType; // Indicates the MIME type transmitted to the server. - docTypeDecl; // Sets and returns information about an XML document's DOCTYPE declaration. - firstChild; // Read-only; references the first child in the list for the specified node. - bool ignoreWhite; // When set to true, text nodes that contain only white space are discarded during the parsing process. - lastChild; // References the last child in the list for the specified node. - nextSibling; // Read-only; references the next sibling in the parent node's child list. - tu_string nodeType; // The type of the specified node (XML element or text node). - nodeValue; // The text of the specified node if the node is a text node. - parentNode; // Read-only; references the parent node of the specified node. - previousSibling; // Read-only; references the previous sibling in the parent node's child list. - status; // A numeric status code indicating the success or failure of an XML document parsing operation. - xmlDecl; // Specifies information about a document's XML declaration. - - // Collections data - attributes; // Returns an associative array containing all of the attributes of the specified node. - // Event Handlers - onData; // An event handler that is invoked when XML text has been - // completely downloaded from the server, or when an error - // occurs downloading XML text from a server. -#endif -}; + xml_node(const char* name = NULL, int type = 0, xml_node* parent = NULL); + // SwiffPlayer.dll 0x100A8E20 destroys attributes, name, then value before + // the object base; deleting wrappers 0x100A94F0 (xml_node) and 0x100A9530 + // (xml_document). The reverse declaration order below gives the same order; + // the native child/sibling links additionally release their nodes. + virtual bool get_member(const tu_stringi& name, as_value* value); + virtual void enumerate(as_environment* env); + virtual void clear_children(); + virtual void insert_sibling(xml_node* node); + + int m_node_type; + smart_ptr m_node_value; + smart_ptr m_node_name; + smart_ptr m_attributes; + xml_node* m_parent; + xml_node* m_previous_sibling; + smart_ptr m_next_sibling; + smart_ptr m_first_child; + }; + + struct xml_document : public xml_node + { + xml_document(); + virtual void set_member(const tu_stringi& name, const as_value& value); + virtual bool get_member(const tu_stringi& name, as_value* value); + virtual void clear_children(); + + // Parser callbacks keep one node per character-data callback. + void start_element(const char* name, const char** attributes); + void end_element(const char* name); + void character_data(const char* text, int length); + + // [CHOSEN, not recovered] S3 bridge exposing the load path's parser + // sequence to native callers. Does not clear children or finalize input. + // Returns true exactly when the parser returns 1; updates status. + bool parse(const char* text, int length); + + xml_node* m_current; + bool m_ignore_white; + int m_status; + }; + + void xml_new(const fn_call& fn); + void xmlnode_new(const fn_call& fn); + void xml_load(const fn_call& fn); + void xml_ondata(const fn_call& fn); + + // [CHOSEN, not recovered] issue #7 / S3 bridge. Call while the existing + // release_script_objects registry snapshot holds every live object. + // Required before publishing the factories in the action layer. + void release_xml_script_references(as_object* object); +} -struct xml_as_object : public gameswf::as_object -{ - XML obj; -#ifdef DEBUG_MEMORY_ALLOCATION - xml_as_object() - { - log_msg("\tCreating xml_as_object at %p\n", this); - }; - ~xml_as_object() - { - log_msg("\tDeleting xml_as_object at %p\n", this); - }; #endif - virtual bool get_member(const tu_stringi& name, as_value* val) - { - //printf("GET XML MEMBER: %s at %p for object %p\n", name.c_str(), val, this); - - if ((name == "firstChild") || (name == "childNodes")) { - //printf("Returning a self reference for %s for object at %p\n", name.c_str(), this); - val->set(this); - return true; - } - - if (m_members.get(name, val) == false) { - if (m_prototype != NULL) { - return m_prototype->get_member(name, val); - } - return false; - } - return true; - } -}; - - -void xml_load(const fn_call& fn); -void xml_set_current(const fn_call& fn); -void xml_new(const fn_call& fn); - -// These are the event handlers called for this object -void xml_onload(const fn_call& fn); -void xml_ondata(const fn_call& fn); -void xml_loaded(const fn_call& fn); - -int memadjust(int x); - -} // end namespace gameswf - - -#endif // HAVE_LIBXML - -#endif // __XML_H__ - diff --git a/Code/BF2/External/gameswf/gameswf_xmlsocket.cpp b/Code/BF2/External/gameswf/gameswf_xmlsocket.cpp deleted file mode 100644 index 63c544f20..000000000 --- a/Code/BF2/External/gameswf/gameswf_xmlsocket.cpp +++ /dev/null @@ -1,798 +0,0 @@ -// gameswf_xml.h -- Rob Savoye 2005 - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - -#include - -#include "base/utility.h" -#include "gameswf_log.h" -#include "gameswf_xml.h" -#include "gameswf_xmlsocket.h" -#include "gameswf_timers.h" - -#ifdef HAVE_LIBXML - -#include -#ifdef HAVE_WINSOCK -# include -# include -# include -# include -# include -#else -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -#endif - -#ifndef MAXHOSTNAMELEN -#define MAXHOSTNAMELEN 256 -#endif - -int xml_fd = 0; // FIXME: This file descriptor is used by - // XML::checkSocket() when called from the main - // processing loop. - -namespace gameswf -{ -const int SOCKET_DATA = 1; - -const int INBUF = 10000; - -XMLSocket::XMLSocket() -{ - //log_msg("%s: \n", __FUNCTION__); - _data = false; - _xmldata = false; - _closed = false; - _connect = false; - _processing = false; - _port = 0; - _sockfd = 0; - xml_fd = 0; -} - -XMLSocket::~XMLSocket() -{ - //log_msg("%s: \n", __FUNCTION__); -} - -bool -XMLSocket::connect(const char *host, int port) -{ - struct sockaddr_in sock_in; - fd_set fdset; - struct timeval tval; - int ret; - int retries; - char thishostname[MAXHOSTNAMELEN]; - struct protoent *proto; - - if (port < 1024) { - log_error("Can't connect to priviledged port #%d!\n", port); - _connect = false; - return false; - } - - log_msg("%s: to host %s at port %d\n", __FUNCTION__, host, port); - - memset(&sock_in, 0, sizeof(struct sockaddr_in)); - memset(&thishostname, 0, MAXHOSTNAMELEN); - if (strlen(host) == 0) { - if (gethostname(thishostname, MAXHOSTNAMELEN) == 0) { - log_msg("The hostname for this machine is %s.\n", thishostname); - } else { - log_msg("Couldn't get the hostname for this machine!\n"); - return false; - } - } - const struct hostent *hent = ::gethostbyname(host); - if (hent > 0) { - ::memcpy(&sock_in.sin_addr, hent->h_addr, hent->h_length); - } - sock_in.sin_family = AF_INET; - sock_in.sin_port = ntohs(static_cast(port)); - -#if 0 - char ascip[32]; - inet_ntop(AF_INET, &sock_in.sin_addr.s_addr, ascip, INET_ADDRSTRLEN); - log_msg("The IP address for this client socket is %s\n", ascip); -#endif - - proto = ::getprotobyname("TCP"); - - _sockfd = ::socket(PF_INET, SOCK_STREAM, proto->p_proto); - if (_sockfd < 0) - { - log_error("unable to create socket : %s\n", strerror(errno)); - _sockfd = -1; - return false; - } - - retries = 2; - while (retries-- > 0) { - // We use select to wait for the read file descriptor to be - // active, which means there is a client waiting to connect. - FD_ZERO(&fdset); - FD_SET(_sockfd, &fdset); - - // Reset the timeout value, since select modifies it on return. To - // block, set the timeout to zero. - tval.tv_sec = 5; - tval.tv_usec = 0; - - ret = ::select(_sockfd+1, &fdset, NULL, NULL, &tval); - - // If interupted by a system call, try again - if (ret == -1 && errno == EINTR) - { - log_msg("The connect() socket for fd #%d was interupted by a system call!\n", - _sockfd); - continue; - } - - if (ret == -1) - { - log_msg("The connect() socket for fd #%d never was available for writing!\n", - _sockfd); -#ifdef HAVE_WINSOCK - ::shutdown(_sockfd, SHUT_BOTH); -#else - ::shutdown(_sockfd, SHUT_RDWR); -#endif - _sockfd = -1; - return false; - } - if (ret == 0) { - log_error("The connect() socket for fd #%d timed out waiting to write!\n", - _sockfd); - continue; - } - - if (ret > 0) { - ret = ::connect(_sockfd, reinterpret_cast(&sock_in), sizeof(sock_in)); - if (ret == 0) { - log_msg("\tport %d at IP %s for fd #%d\n", port, - ::inet_ntoa(sock_in.sin_addr), _sockfd); - _connect = true; - return true; - } - if (ret == -1) { - log_msg("The connect() socket for fd #%d never was available for writing!\n", - _sockfd); - _sockfd = -1; - return false; - } - } - } - // ::close(_sockfd); - // return false; - - printf("\tConnected at port %d on IP %s for fd #%d\n", port, - ::inet_ntoa(sock_in.sin_addr), _sockfd); - -#ifndef HAVE_WINSOCK - fcntl(_sockfd, F_SETFL, O_NONBLOCK); -#endif - - xml_fd = _sockfd; // FIXME: This file descriptor is used by - // XML::checkSocket() when called from - // the main processing loop. - _connect = true; - return true; -} - -void -XMLSocket::close() -{ - log_msg("%s: \n", __FUNCTION__); - // Since the return code from close() doesn't get used by Shockwave, - // we don't care either. - if (_sockfd > 0) { - ::close(_sockfd); - } -} - -// Return true if there is data in the socket, otherwise return false. -bool -XMLSocket::anydata(char **msgs) -{ - //printf("%s: \n", __FUNCTION__); - return anydata(_sockfd, msgs); -} - -bool XMLSocket::processingData() -{ - //printf("%s: processing flags is is %d\n", __FUNCTION__, _processing); - return _processing; -} - -void XMLSocket::processing(bool x) -{ - //printf("%s: set processing flag to %d\n", __FUNCTION__, x); - _processing = x; -} - -bool -XMLSocket::anydata(int fd, char **msgs) -{ - fd_set fdset; - struct timeval tval; - int ret = 0; - char buf[INBUF]; - char *packet; - int retries = 10; - char *ptr, *eom; - int pos; - int cr, index = 0; - static char *leftover = 0; - int adjusted_size; - - //log_msg("%s: \n", __FUNCTION__); - - if (fd <= 0) { - return false; - } - - //msgs = (char **)realloc(msgs, sizeof(char *)); - - while (retries-- > 0) { - FD_ZERO(&fdset); - FD_SET(fd, &fdset); - - tval.tv_sec = 1; - tval.tv_usec = 10; - - ret = ::select(fd+1, &fdset, NULL, NULL, &tval); - - // If interupted by a system call, try again - if (ret == -1 && errno == EINTR) { - log_msg("The socket for fd #%d was interupted by a system call!\n", - fd); - continue; - } - if (ret == -1) { - log_error("The socket for fd #%d never was available!\n", fd); - return false; - } - if (ret == 0) { - //log_msg("There is no data in the socket for fd #%d!\n", fd); - return false; - } - if (ret > 0) { - //log_msg("There is data in the socket for fd #%d!\n", fd); - //break; - } - memset(buf, 0, INBUF); - ret = ::read(_sockfd, buf, INBUF-2); - cr = strlen(buf); - //log_msg("%s: read %d bytes, first msg terminates at %d\n", __FUNCTION__, ret, cr); - //log_msg("%s: read (%d,%d) %s\n", __FUNCTION__, buf[0], buf[1], buf); - ptr = buf; - // If we get a single XML message, do less work - if (ret == cr + 1) { - adjusted_size = memadjust(ret + 1); - packet = new char[adjusted_size]; - //printf("Packet size is %d at %p\n", ret + 1, packet); - memset(packet, 0, adjusted_size); - strcpy(packet, ptr); - eom = strrchr(packet, '\n'); // drop the CR off the end if there is one - if (eom) { - *eom = 0; - } - //data.push_back(packet); - msgs[index] = packet; - msgs[index+1] = 0; - //printf("%d: Pushing Packet of size %d at %p\n", __LINE__, strlen(packet), packet); - processing(false); - return true; - } - - // If we get multiple messages in a single transmission, break the buffer - // into separate messages. - while (strchr(ptr, '\n') > 0) { - if (leftover) { - processing(false); - //printf("%s: The remainder is: \"%s\"\n", __FUNCTION__, leftover); - //printf("%s: The rest of the message is: \"%s\"\n", __FUNCTION__, ptr); - adjusted_size = memadjust(cr + strlen(leftover) + 1); - packet = new char[adjusted_size]; - memset(packet, 0, adjusted_size); - strcpy(packet, leftover); - strcat(packet, ptr); - eom = strrchr(packet, '\n'); // drop the CR off the end there is one - if (eom) { - *eom = 0; - } - //printf("%s: The whole message is: \"%s\"\n", __FUNCTION__, packet); - ptr = strchr(ptr, '\n') + 2; // messages are delimited by a "\n\0" - delete leftover; - leftover = 0; - } else { - adjusted_size = memadjust(cr + 1); - packet = new char[adjusted_size]; - memset(packet, 0, adjusted_size); - strcpy(packet, ptr); - ptr += cr + 1; - } // end of if remainder - if (*packet == '<') { - //printf("%d: Pushing Packet #%d of size %d at %p: %s\n", __LINE__, - // data.size(), strlen(packet), packet, packet); - eom = strrchr(packet, '\n'); // drop the CR off the end there is one - if (eom) { - *eom = 0; - } - //printf("Allocating new packet at %p\n", packet); - //data.push_back(packet); - msgs[index++] = packet; - } else { - log_error("Throwing out partial packet %s\n", packet); - } - - //log_msg("%d messages in array now\n", data.size()); - cr = strlen(ptr); - } // end of while (cr) - - if (strlen(ptr) > 0) { - leftover = new char[strlen(ptr) + 1]; - strcpy(leftover, ptr); - processing(true); - //printf("%s: Adding remainder: \"%s\"\n", __FUNCTION__, leftover); - } - - processing(false); - printf("Returning %d messages\n", index); - return true; - - } // end of while (retires) - - return true; -} - -bool -XMLSocket::send(tu_string str) -{ - //log_msg("%s: \n", __FUNCTION__); - //str += tu_string( "\0", 1); - str += '\0'; - int ret = write(_sockfd, str.c_str(), str.size()); - - //log_msg("%s: sent %d bytes, data was %s\n", __FUNCTION__, ret, str.c_str()); - if (ret == str.size()) { - return true; - } else { - return false; - } -} - -// Callbacks - -void -XMLSocket::onClose(tu_string str) -{ - log_msg("%s: \n", __FUNCTION__); -} - -void -XMLSocket::onConnect(tu_string str) -{ - log_msg("%s: \n", __FUNCTION__); -} - -void -XMLSocket::onData(tu_string str) -{ - log_msg("%s: \n", __FUNCTION__); -} - -void -XMLSocket::onXML(tu_string str) -{ - log_msg("%s: \n", __FUNCTION__); -} - -void -XMLSocket::push(as_object_interface *obj) -{ - _nodes.push_back(obj); -} - -void -XMLSocket::clear() -{ - int i; - for (i=0; i< _nodes.size(); i++) { - delete _nodes[i]; - } -} - -int -XMLSocket::count() -{ - return _nodes.size(); -} - -int -XMLSocket::checkSockets(void) -{ - return checkSockets(_sockfd); -} - -int -XMLSocket::checkSockets(int fd) -{ - fd_set fdset; - int ret = 0; - struct timeval tval; - - //log_msg("%s:\n", __FUNCTION__); - - FD_ZERO(&fdset); - FD_SET(fd, &fdset); - - tval.tv_sec = 2; - tval.tv_usec = 10; - - ret = ::select(fd+1, &fdset, NULL, NULL, &tval); // &tval - - // If interupted by a system call, try again - if (ret == -1 && errno == EINTR) { - log_msg("The socket for fd #%d was interupted by a system call in this thread!\n", - fd); - } - if (ret == -1) { - log_error("The socket for fd #%d never was available!\n", fd); - } - if (ret == 0) { - printf("There is no data in the socket for fd #%d!\n", fd); - } - if (ret > 0) { - //printf("There is data in the socket for fd #%d!\n", fd); - } - - return ret; -} - -void -xmlsocket_connect(const fn_call& fn) -{ - as_value method; - as_value val; - static bool first = true; // This event handler should only be executed once. - bool ret; - const array with_stack; - - if (!first) { - fn.result->set(true); - return; - } - - log_msg("%s: nargs=%d\n", __FUNCTION__, fn.nargs); - xmlsocket_as_object* ptr = (xmlsocket_as_object*) (as_object*) fn.this_ptr; - assert(ptr); - const tu_string host = fn.env->bottom(fn.first_arg_bottom_index).to_string(); - tu_string port_str = fn.env->bottom(fn.first_arg_bottom_index-1).to_tu_string(); - double port = atof(port_str.c_str()); - ret = ptr->obj.connect(host, static_cast(port)); - -#if 0 - // Push result onto stack for onConnect - if (ret) { - fn.env->push(as_value(true)); - } - else { - fn.env->push(as_value(false)); - } -#endif - fn.env->push(as_value(true)); - if (fn.this_ptr->get_member("onConnect", &method)) { - // log_msg("FIXME: Found onConnect!\n"); - as_c_function_ptr func = method.to_c_function(); - first = false; - //env->set_variable("success", true, 0); - - if (func) { - // It's a C function. Call it. - log_msg("Calling C function for onConnect\n"); - (*func)(fn_call(&val, fn.this_ptr, fn.env, 0, 0)); - } - else if (as_as_function* as_func = method.to_as_function()) { - // It's an ActionScript function. Call it. - log_msg("Calling ActionScript function for onConnect\n"); - (*as_func)(fn_call(&val, fn.this_ptr, fn.env, 2, 2)); - } else { - log_error("error in call_method(): method is not a function\n"); - } - } else { - //ptr->set_event_handler(event_id::SOCK_CONNECT, (as_c_function_ptr)&xmlsocket_event_connect); - } - -#if 1 - movie* mov = fn.env->get_target()->get_root_movie(); - Timer *timer = new Timer; - as_c_function_ptr ondata_handler = - (as_c_function_ptr)&xmlsocket_event_ondata; - timer->setInterval(ondata_handler, 50, ptr, fn.env); - timer->setObject(ptr); - mov->add_interval_timer(timer); -#endif - - fn.env->pop(); - - fn.result->set(true); -} - - -void -xmlsocket_send(const fn_call& fn) -{ - as_value method; - as_value val; - - xmlsocket_as_object* ptr = (xmlsocket_as_object*) (as_object*) fn.this_ptr; - assert(ptr); - const tu_string object = fn.env->bottom( fn.first_arg_bottom_index).to_string(); - // log_msg("%s: host=%s, port=%g\n", __FUNCTION__, host, port); - fn.result->set(ptr->obj.send(object)); -} - -void -xmlsocket_close(const fn_call& fn) -{ - as_value method; - as_value val; - - xmlsocket_as_object* ptr = (xmlsocket_as_object*) (as_object*) fn.this_ptr; - assert(ptr); - // Since the return code from close() doesn't get used by Shockwave, - // we don't care either. - ptr->obj.close(); -} - -void -xmlsocket_xml_new(const fn_call& fn) -{ - //log_msg("%s: nargs=%d\n", __FUNCTION__, nargs); - - xml_new(fn); -} - -void -xmlsocket_new(const fn_call& fn) -{ - //log_msg("%s: nargs=%d\n", __FUNCTION__, nargs); - - as_object* xmlsock_obj = new xmlsocket_as_object; - //log_msg("\tCreated New XMLSocket object at 0x%X\n", (unsigned int)xmlsock_obj); - xmlsock_obj->set_member("connect", &xmlsocket_connect); - xmlsock_obj->set_member("send", &xmlsocket_send); - xmlsock_obj->set_member("close", &xmlsocket_close); - xmlsock_obj->set_member("Connected", true); - // swf_event* ev = new swf_event; - // m_event_handlers.push_back(ev); - // Setup event handlers -#if 0 - xmlsock_obj->set_event_handler(event_id::SOCK_DATA, - (as_c_function_ptr)&xmlsocket_event_ondata); - xmlsock_obj->set_event_handler(event_id::SOCK_CLOSE, - (as_c_function_ptr)&xmlsocket_event_close); - // xmlsock_obj->set_event_handler(event_id::SOCK_CONNECT, - // (as_c_function_ptr)&xmlsocket_event_connect); - xmlsock_obj->set_event_handler(event_id::SOCK_XML, - (as_c_function_ptr)&xmlsocket_event_xml); -#endif - //periodic_events.set_event_handler(xmlsock_obj); - - -#if 1 - //as_c_function_ptr int_handler = (as_c_function_ptr)&timer_setinterval; - //env->set_member("setInterval", int_handler); - fn.env->set_member("setInterval", timer_setinterval); - - //as_c_function_ptr clr_handler = timer_clearinterval; - fn.env->set_member("clearInterval", timer_clearinterval); - //env->set_variable("setInterval", int_handler, 0); - //xmlsock_obj->set_event_handler(event_id::TIMER, - // (as_c_function_ptr)&timer_expire); -#if 0 - Timer *timer = new Timer; - as_c_function_ptr ondata_handler = - (as_c_function_ptr)&xmlsocket_event_ondata; - timer->setInterval(ondata_handler, 10); - timer->setObject(xmlsock_obj); - current_movie->add_interval_timer(timer); -#endif - - fn.result->set(xmlsock_obj); - - // Tune malloc for the best performance - //mallopt(M_MMAP_MAX,0); - //mallopt(M_TRIM_THRESHOLD,-1); - //mallopt(M_MMAP_THRESHOLD,16); - -#endif -} - - -void -xmlsocket_event_ondata(const fn_call& fn) -{ - //log_msg("%s: nargs is %d\n", __FUNCTION__, nargs); - - as_value method; - as_value val; - as_value datain; - array msgs; - char *messages[200]; - int i; - as_c_function_ptr func; - as_as_function* as_func; - tu_string data; - - xmlsocket_as_object* ptr = (xmlsocket_as_object*)fn.this_ptr; - assert(ptr); - if (ptr->obj.processingData()) { - log_msg("Still processing data!\n"); - fn.result->set(false); - return; - } - - memset(messages, 0, sizeof(char *)*200); - -#ifndef USE_DMALLOC - //dump_memory_stats(__FUNCTION__, __LINE__, "memory checkpoint"); -#endif - - if (ptr->obj.anydata(messages)) { - if (fn.this_ptr->get_member("onData", &method)) { - func = method.to_c_function(); - as_func = method.to_as_function(); - //log_msg("Got %d messages from XMLsocket\n", msgs.size()); - // for (i=0; ipush(datain); -#ifndef USE_DMALLOC - //dump_memory_stats(__FUNCTION__, __LINE__, "start"); -#endif - as_environment *env = new as_environment; - env->push(datain); - if (func) { - // It's a C function. Call it. - //log_msg("Calling C function for onData\n"); - (*func)(fn_call(&val, fn.this_ptr, env, 1, 0)); - } else if (as_func) { - // It's an ActionScript function. Call it. - //log_msg("Calling ActionScript function for onData, processing msg %d\n", i); - (*as_func)(fn_call(&val, fn.this_ptr, env, 1, 0)); - } else { - log_error("error in call_method(): method is not a function\n"); - } - env->pop(); - delete env; -#ifndef USE_DMALLOC - //dump_memory_stats(__FUNCTION__, __LINE__, "end"); -#endif - //log_msg("Deleting message #%d at %p\n", i, messages[i]); - //delete messages[i]; - //fn.env->pop(); - datain.set_undefined(); - } - ptr->obj.processing(false); - } else { - log_error("Couldn't find onData!\n"); - } - // Delete this in a batch for now so we can track memory allocation - for (i=0; messages[i] != 0; i++) { - //log_msg("Deleting message #%d at %p\n", i, messages[i]); - delete messages[i]; - } - } - - //malloc_trim(0); - - //result->set(&data); - fn.result->set(true); -} - -void -xmlsocket_event_close(const fn_call& fn) -{ -#if 0 - as_value* result = fn.result; - as_object_interface* this_ptr = fn.this_ptr; - int nargs = fn.nargs; - int first_arg = fn.first_arg_bottom_index; -#else - log_error("%s: unimplemented!\n", __FUNCTION__); -#endif -} - -void -xmlsocket_event_connect(const fn_call& fn) -{ - as_value method; - as_value val; - tu_string data; - static bool first = true; // This event handler should only be executed once. - - if (!first) { - fn.result->set(true); - return; - } - - xmlsocket_as_object* ptr = (xmlsocket_as_object*) (as_object*) fn.this_ptr; - assert(ptr); - - log_msg("%s: connected = %d\n", __FUNCTION__, ptr->obj.connected()); - if ((ptr->obj.connected()) && (first)) { - first = false; - //env->set_variable("success", true, 0); - //env->bottom(0) = true; - - if (fn.this_ptr->get_member("onConnect", &method)) { - as_c_function_ptr func = method.to_c_function(); - if (func) - { - // It's a C function. Call it. - //log_msg("Calling C function for onConnect\n"); - (*func)(fn_call(&val, fn.this_ptr, fn.env, 0, 0)); - } - else if (as_as_function* as_func = method.to_as_function()) - { - // It's an ActionScript function. Call it. - //log_msg("Calling ActionScript function for onConnect\n"); - (*as_func)(fn_call(&val, fn.this_ptr, fn.env, 0, 0)); - } - else - { - log_error("error in call_method(): method is not a function\n"); - } - } else { - log_msg("FIXME: Couldn't find onConnect!\n"); - } - } - - fn.result->set(&val); -} -void -xmlsocket_event_xml(const fn_call& fn) -{ -#if 0 - as_value* result = fn.result; - as_object_interface* this_ptr = fn.this_ptr; - int nargs = fn.nargs; - int first_arg = fn.first_arg_bottom_index; -#else - log_error("%s: unimplemented!\n", __FUNCTION__); -#endif -} - -static XMLSocket xs; - -int -check_sockets(int x) -{ - //log_msg("%s unimplemented\n", __FUNCTION__); - if (xml_fd == 0) { - return -1; - } - - return xs.checkSockets(x); -} - -} // end of gameswf namespace - -// HAVE_LIBXML -#endif diff --git a/Code/BF2/External/gameswf/gameswf_xmlsocket.h b/Code/BF2/External/gameswf/gameswf_xmlsocket.h deleted file mode 100644 index 0705ab222..000000000 --- a/Code/BF2/External/gameswf/gameswf_xmlsocket.h +++ /dev/null @@ -1,100 +0,0 @@ -// gameswf_xml.h -- Rob Savoye 2005 - -// This source code has been donated to the Public Domain. Do -// whatever you want with it. - -#ifndef __XMLSOCKET_H__ -#define __XMLSOCKET_H__ - - -#include "base/tu_config.h" -#include "gameswf_xml.h" -#include "gameswf_impl.h" -#include "gameswf_log.h" -#include "base/container.h" - -#ifdef HAVE_LIBXML - -namespace gameswf { - -extern const int SOCKET_DATA; - -class XMLSocket { - public: - XMLSocket(); - ~XMLSocket(); - - bool connect(const char *host, int port); - bool send(tu_string str); - void close(); - - - bool anydata(char **msgs); - bool anydata(int sockfd, char **msgs); - bool connected() { return _connect; }; - bool fdclosed() { return _closed; } - bool xmlmsg() { return _xmldata; } - - void messagesClear() { _messages.clear(); } - void messageRemove(int x) { _messages.remove(x); } - int messagesCount() { return _messages.size(); } - tu_string operator [] (int x) { return _messages[x]; } - - bool processingData(); - void processing(bool x); - - // Event Handlers - void onClose(tu_string); - void onConnect(tu_string); - void onData(tu_string); - void onXML(tu_string); - - // These handle the array of XML nodes - void push(as_object_interface *obj); - void clear(); - int count(); - - int XMLSocket::checkSockets(void); - int XMLSocket::checkSockets(int x); - - private: - tu_string _host; - short _port; - int _sockfd; - bool _data; - bool _xmldata; - bool _closed; - bool _connect; - bool _processing; - array _messages; - array _nodes; -}; - - -struct xmlsocket_as_object : public gameswf::as_object -{ - XMLSocket obj; -}; - -void xmlsocket_connect(const fn_call& fn); -void xmlsocket_send(const fn_call& fn); -void xmlsocket_xml_new(const fn_call& fn); -void xmlsocket_new(const fn_call& fn); -void xmlsocket_close(const fn_call& fn); - -// These are the event handlers called for this object -void xmlsocket_event_ondata(const fn_call& fn); -void xmlsocket_event_close(const fn_call& fn); -void xmlsocket_event_connect(const fn_call& fn); -void xmlsocket_event_xml(const fn_call& fn); - -int check_sockets(int fd); - -} // end of gameswf namespace - -// HAVE_LIBXML -#endif - -// __XMLSOCKETSOCKET_H__ -#endif - diff --git a/Code/BF2/External/meshoptimizer/LICENSE.md b/Code/BF2/External/meshoptimizer/LICENSE.md new file mode 100644 index 000000000..468827f4b --- /dev/null +++ b/Code/BF2/External/meshoptimizer/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016-2026 Arseny Kapoulkine + +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/Code/BF2/External/meshoptimizer/meshoptimizer.h b/Code/BF2/External/meshoptimizer/meshoptimizer.h new file mode 100644 index 000000000..ff69785b5 --- /dev/null +++ b/Code/BF2/External/meshoptimizer/meshoptimizer.h @@ -0,0 +1,1724 @@ +/** + * meshoptimizer - version 1.3 + * + * Copyright (C) 2016-2026, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com) + * Report bugs and download new versions at https://github.com/zeux/meshoptimizer + * + * This library is distributed under the MIT License. See notice at the end of this file. + */ +#pragma once + +#include +#include + +/* Version macro; major * 1000 + minor * 10 + patch */ +#define MESHOPTIMIZER_VERSION 1030 /* 1.3 */ + +/* If no API is defined, assume default */ +#ifndef MESHOPTIMIZER_API +#define MESHOPTIMIZER_API +#endif + +/* Set the calling-convention for alloc/dealloc function pointers */ +#ifndef MESHOPTIMIZER_ALLOC_CALLCONV +#ifdef _MSC_VER +#define MESHOPTIMIZER_ALLOC_CALLCONV __cdecl +#else +#define MESHOPTIMIZER_ALLOC_CALLCONV +#endif +#endif + +/* Experimental APIs have unstable interface and might have implementation that's not fully tested or optimized */ +#ifndef MESHOPTIMIZER_EXPERIMENTAL +#define MESHOPTIMIZER_EXPERIMENTAL MESHOPTIMIZER_API +#endif + +/* C interface */ +#ifdef __cplusplus +extern "C" +{ +#endif + +/** + * Vertex attribute stream + * Each element takes size bytes, beginning at data, with stride controlling the spacing between successive elements (stride >= size). + */ +struct meshopt_Stream +{ + const void* data; + size_t size; + size_t stride; +}; + +/** + * Generates a vertex remap table from the vertex buffer and an optional index buffer and returns number of unique vertices + * As a result, all vertices that are binary equivalent map to the same (new) location, with no gaps in the resulting sequence. + * Resulting remap table maps old vertices to new vertices and can be used in meshopt_remapVertexBuffer/meshopt_remapIndexBuffer. + * Note that binary equivalence considers all vertex_size bytes, including padding which should be zero-initialized. + * + * destination must contain enough space for the resulting remap table (vertex_count elements) + * indices can be NULL if the input is unindexed + */ +MESHOPTIMIZER_API size_t meshopt_generateVertexRemap(unsigned int* destination, const unsigned int* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size); + +/** + * Generates a vertex remap table from multiple vertex streams and an optional index buffer and returns number of unique vertices + * As a result, all vertices that are binary equivalent map to the same (new) location, with no gaps in the resulting sequence. + * Resulting remap table maps old vertices to new vertices and can be used in meshopt_remapVertexBuffer/meshopt_remapIndexBuffer. + * To remap vertex buffers, you will need to call meshopt_remapVertexBuffer for each vertex stream. + * Note that binary equivalence considers all size bytes in each stream, including padding which should be zero-initialized. + * + * destination must contain enough space for the resulting remap table (vertex_count elements) + * indices can be NULL if the input is unindexed + * stream_count must be <= 16 + */ +MESHOPTIMIZER_API size_t meshopt_generateVertexRemapMulti(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count, const struct meshopt_Stream* streams, size_t stream_count); + +/** + * Generates a vertex remap table from the vertex buffer and an optional index buffer and returns number of unique vertices + * As a result, all vertices that are equivalent map to the same (new) location, with no gaps in the resulting sequence. + * Equivalence is checked in two steps: vertex positions are compared for equality, and then the user-specified equality function is called (if provided). + * Resulting remap table maps old vertices to new vertices and can be used in meshopt_remapVertexBuffer/meshopt_remapIndexBuffer. + * + * destination must contain enough space for the resulting remap table (vertex_count elements) + * indices can be NULL if the input is unindexed + * vertex_positions should have float3 position in the first 12 bytes of each vertex + * callback can be NULL if no additional equality check is needed; otherwise, it should return 1 if vertices with specified indices are equivalent and 0 if they are not + */ +MESHOPTIMIZER_API size_t meshopt_generateVertexRemapCustom(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, int (*callback)(void*, unsigned int, unsigned int), void* context); + +/** + * Generates vertex buffer from the source vertex buffer and remap table generated by meshopt_generateVertexRemap + * + * destination must contain enough space for the resulting vertex buffer (unique_vertex_count elements, returned by meshopt_generateVertexRemap) + * vertex_count should be the initial vertex count and not the value returned by meshopt_generateVertexRemap + */ +MESHOPTIMIZER_API void meshopt_remapVertexBuffer(void* destination, const void* vertices, size_t vertex_count, size_t vertex_size, const unsigned int* remap); + +/** + * Generate index buffer from the source index buffer and remap table generated by meshopt_generateVertexRemap + * + * destination must contain enough space for the resulting index buffer (index_count elements) + * indices can be NULL if the input is unindexed + */ +MESHOPTIMIZER_API void meshopt_remapIndexBuffer(unsigned int* destination, const unsigned int* indices, size_t index_count, const unsigned int* remap); + +/** + * Filter out redundant triangles from the index buffer and return the number of remaining indices + * Triangles are considered redundant if they are degenerate (two vertices have the same vertex key) or duplicate (matching triangle was present earlier). + * First vertex_size bytes of every vertex are compared for equality; typically vertex_size should be set to the size of the position attribute. + * Note that duplicate triangles with opposite windings are preserved, as they may be needed for double-sided rendering. + * + * destination must contain enough space for the resulting index buffer (index_count elements) + */ +MESHOPTIMIZER_API size_t meshopt_filterIndexBuffer(unsigned int* destination, const unsigned int* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size, size_t vertex_stride); + +/** + * Filter out redundant triangles from the index buffer and return the number of remaining indices + * Triangles are considered redundant if they are degenerate (two vertices have the same vertex key) or duplicate (matching triangle was present earlier). + * All bytes in specified streams are compared for equality; streams should include attributes relevant for position transform (e.g. bone influences). + * Note that duplicate triangles with opposite windings are preserved, as they may be needed for double-sided rendering. + * + * destination must contain enough space for the resulting index buffer (index_count elements) + * stream_count must be <= 16 + */ +MESHOPTIMIZER_API size_t meshopt_filterIndexBufferMulti(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count, const struct meshopt_Stream* streams, size_t stream_count); + +/** + * Generate index buffer that can be used for more efficient rendering when only a subset of the vertex attributes is necessary + * All vertices that are binary equivalent (wrt first vertex_size bytes) map to the first vertex in the original vertex buffer. + * This makes it possible to use the index buffer for Z pre-pass or shadowmap rendering, while using the original index buffer for regular rendering. + * Note that binary equivalence considers all vertex_size bytes, including padding which should be zero-initialized. + * + * destination must contain enough space for the resulting index buffer (index_count elements) + */ +MESHOPTIMIZER_API void meshopt_generateShadowIndexBuffer(unsigned int* destination, const unsigned int* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size, size_t vertex_stride); + +/** + * Generate index buffer that can be used for more efficient rendering when only a subset of the vertex attributes is necessary + * All vertices that are binary equivalent (wrt specified streams) map to the first vertex in the original vertex buffer. + * This makes it possible to use the index buffer for Z pre-pass or shadowmap rendering, while using the original index buffer for regular rendering. + * Note that binary equivalence considers all size bytes in each stream, including padding which should be zero-initialized. + * + * destination must contain enough space for the resulting index buffer (index_count elements) + * stream_count must be <= 16 + */ +MESHOPTIMIZER_API void meshopt_generateShadowIndexBufferMulti(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count, const struct meshopt_Stream* streams, size_t stream_count); + +/** + * Generates a remap table that maps all vertices with the same position to the same (existing) index. + * Similarly to meshopt_generateShadowIndexBuffer, this can be helpful to pre-process meshes for position-only rendering. + * This can also be used to implement algorithms that require positional-only connectivity, such as hierarchical simplification. + * + * destination must contain enough space for the resulting remap table (vertex_count elements) + * vertex_positions should have float3 position in the first 12 bytes of each vertex + */ +MESHOPTIMIZER_API void meshopt_generatePositionRemap(unsigned int* destination, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride); + +/** + * Generate index buffer that can be used as a geometry shader input with triangle adjacency topology + * Each triangle is converted into a 6-vertex patch with the following layout: + * - 0, 2, 4: original triangle vertices + * - 1, 3, 5: vertices adjacent to edges 02, 24 and 40 + * The resulting patch can be rendered with geometry shaders using e.g. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY. + * This can be used to implement algorithms like silhouette detection/expansion and other forms of GS-driven rendering. + * + * destination must contain enough space for the resulting index buffer (index_count*2 elements) + * vertex_positions should have float3 position in the first 12 bytes of each vertex + */ +MESHOPTIMIZER_API void meshopt_generateAdjacencyIndexBuffer(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride); + +/** + * Generate index buffer that can be used for PN-AEN tessellation with crack-free displacement + * Each triangle is converted into a 12-vertex patch with the following layout: + * - 0, 1, 2: original triangle vertices + * - 3, 4: opposing edge for edge 0, 1 + * - 5, 6: opposing edge for edge 1, 2 + * - 7, 8: opposing edge for edge 2, 0 + * - 9, 10, 11: dominant vertices for corners 0, 1, 2 + * The resulting patch can be rendered with hardware tessellation using PN-AEN and displacement mapping. + * See "Tessellation on Any Budget" (John McDonald, GDC 2011) for implementation details. + * + * destination must contain enough space for the resulting index buffer (index_count*4 elements) + * vertex_positions should have float3 position in the first 12 bytes of each vertex + */ +MESHOPTIMIZER_API void meshopt_generateTessellationIndexBuffer(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride); + +/** + * Generate index buffer that can be used for visibility buffer rendering and returns the size of the reorder table + * Each triangle's provoking vertex index is equal to primitive id; this allows passing it to the fragment shader using flat/nointerpolation attribute. + * This is important for performance on hardware where primitive id can't be accessed efficiently in fragment shader. + * The reorder table stores the original vertex id for each vertex in the new index buffer, and should be used in the vertex shader to load vertex data. + * The provoking vertex is assumed to be the first vertex in the triangle; if this is not the case (OpenGL), rotate each triangle (abc -> bca) before rendering. + * For maximum efficiency the input index buffer should be optimized for vertex cache first. + * + * destination must contain enough space for the resulting index buffer (index_count elements) + * reorder must contain enough space for the worst case reorder table (vertex_count + index_count/3 elements) + */ +MESHOPTIMIZER_API size_t meshopt_generateProvokingIndexBuffer(unsigned int* destination, unsigned int* reorder, const unsigned int* indices, size_t index_count, size_t vertex_count); + +/** + * Vertex transform cache optimizer + * Reorders indices to reduce the number of GPU vertex shader invocations + * If index buffer contains multiple ranges for multiple draw calls, this function needs to be called on each range individually. + * + * destination must contain enough space for the resulting index buffer (index_count elements) + */ +MESHOPTIMIZER_API void meshopt_optimizeVertexCache(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count); + +/** + * Vertex transform cache optimizer for strip-like caches + * Produces inferior results to meshopt_optimizeVertexCache from the GPU vertex cache perspective + * However, the resulting index order is more optimal if the goal is to reduce the triangle strip length or improve compression efficiency + * + * destination must contain enough space for the resulting index buffer (index_count elements) + */ +MESHOPTIMIZER_API void meshopt_optimizeVertexCacheStrip(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count); + +/** + * Vertex transform cache optimizer for FIFO caches + * Reorders indices to reduce the number of GPU vertex shader invocations + * Generally takes ~3x less time to optimize meshes but produces inferior results compared to meshopt_optimizeVertexCache + * If index buffer contains multiple ranges for multiple draw calls, this function needs to be called on each range individually. + * + * destination must contain enough space for the resulting index buffer (index_count elements) + * cache_size should be less than the actual GPU cache size to avoid cache thrashing + */ +MESHOPTIMIZER_API void meshopt_optimizeVertexCacheFifo(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count, unsigned int cache_size); + +/** + * Overdraw optimizer + * Reorders indices to reduce the number of GPU vertex shader invocations and the pixel overdraw + * If index buffer contains multiple ranges for multiple draw calls, this function needs to be called on each range individually. + * + * destination must contain enough space for the resulting index buffer (index_count elements) + * indices must contain index data that is the result of meshopt_optimizeVertexCache (*not* the original mesh indices!) + * vertex_positions should have float3 position in the first 12 bytes of each vertex + * threshold indicates how much the overdraw optimizer can degrade vertex cache efficiency (1.05 = up to 5%) to reduce overdraw more efficiently + */ +MESHOPTIMIZER_API void meshopt_optimizeOverdraw(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float threshold); + +/** + * Vertex fetch cache optimizer + * Reorders vertices and changes indices to reduce the amount of GPU memory fetches during vertex processing + * Returns the number of unique vertices, which is the same as input vertex count unless some vertices are unused + * This function works for a single vertex stream; for multiple vertex streams, use meshopt_optimizeVertexFetchRemap + meshopt_remapVertexBuffer for each stream. + * + * destination must contain enough space for the resulting vertex buffer (vertex_count elements) + * indices is used both as an input and as an output index buffer + */ +MESHOPTIMIZER_API size_t meshopt_optimizeVertexFetch(void* destination, unsigned int* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size); + +/** + * Vertex fetch cache optimizer + * Generates vertex remap to reduce the amount of GPU memory fetches during vertex processing + * Returns the number of unique vertices, which is the same as input vertex count unless some vertices are unused + * The resulting remap table should be used to reorder vertex/index buffers using meshopt_remapVertexBuffer/meshopt_remapIndexBuffer + * + * destination must contain enough space for the resulting remap table (vertex_count elements) + */ +MESHOPTIMIZER_API size_t meshopt_optimizeVertexFetchRemap(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count); + +/** + * Index buffer encoder + * Encodes index data into an array of bytes that is generally much smaller (<1.5 bytes/triangle) and compresses better (<1 bytes/triangle) compared to original. + * Input index buffer must represent a triangle list. + * Returns encoded data size on success, 0 on error; the only error condition is if buffer doesn't have enough space + * For maximum efficiency the index buffer being encoded has to be optimized for vertex cache and vertex fetch first. + * + * buffer must contain enough space for the encoded index buffer (use meshopt_encodeIndexBufferBound to compute worst case size) + */ +MESHOPTIMIZER_API size_t meshopt_encodeIndexBuffer(unsigned char* buffer, size_t buffer_size, const unsigned int* indices, size_t index_count); +MESHOPTIMIZER_API size_t meshopt_encodeIndexBufferBound(size_t index_count, size_t vertex_count); + +/** + * Set index encoder format version (defaults to 1) + * This function is not thread safe and must not be called concurrently with meshopt_encodeIndexBuffer/meshopt_encodeIndexSequence. + * + * version must specify the data format version to encode; valid values are 0 (decodable by all library versions) and 1 (decodable by 0.14+) + */ +MESHOPTIMIZER_API void meshopt_encodeIndexVersion(int version); + +/** + * Index buffer decoder + * Decodes index data from an array of bytes generated by meshopt_encodeIndexBuffer + * Returns 0 if decoding was successful, and an error code otherwise + * The decoder is safe to use for untrusted input, but it may produce garbage data (e.g. out of range indices). + * + * destination must contain enough space for the resulting index buffer (index_count elements) + */ +MESHOPTIMIZER_API int meshopt_decodeIndexBuffer(void* destination, size_t index_count, size_t index_size, const unsigned char* buffer, size_t buffer_size); + +/** + * Get encoded index format version + * Returns format version of the encoded index buffer/sequence, or -1 if the buffer header is invalid + * Note that a non-negative value doesn't guarantee that the buffer will be decoded correctly if the input is malformed. + */ +MESHOPTIMIZER_API int meshopt_decodeIndexVersion(const unsigned char* buffer, size_t buffer_size); + +/** + * Index sequence encoder + * Encodes index sequence into an array of bytes that is generally smaller and compresses better compared to original. + * Input index sequence can represent arbitrary topology; for triangle lists meshopt_encodeIndexBuffer is likely to be better. + * Returns encoded data size on success, 0 on error; the only error condition is if buffer doesn't have enough space + * + * buffer must contain enough space for the encoded index sequence (use meshopt_encodeIndexSequenceBound to compute worst case size) + */ +MESHOPTIMIZER_API size_t meshopt_encodeIndexSequence(unsigned char* buffer, size_t buffer_size, const unsigned int* indices, size_t index_count); +MESHOPTIMIZER_API size_t meshopt_encodeIndexSequenceBound(size_t index_count, size_t vertex_count); + +/** + * Index sequence decoder + * Decodes index data from an array of bytes generated by meshopt_encodeIndexSequence + * Returns 0 if decoding was successful, and an error code otherwise + * The decoder is safe to use for untrusted input, but it may produce garbage data (e.g. out of range indices). + * + * destination must contain enough space for the resulting index sequence (index_count elements) + */ +MESHOPTIMIZER_API int meshopt_decodeIndexSequence(void* destination, size_t index_count, size_t index_size, const unsigned char* buffer, size_t buffer_size); + +/** + * Meshlet encoder + * Encodes meshlet data into an array of bytes that is generally smaller and compresses better compared to original. + * Returns encoded data size on success, 0 on error; the only error condition is if buffer doesn't have enough space + * This function encodes a single meshlet; when encoding multiple meshlets, additional headers may be necessary to store vertex/triangle count and encoded size. + * For maximum efficiency the meshlet being encoded should be optimized using meshopt_optimizeMeshletLevel with level 1+ (3 recommended); additionally, vertex reference data should be optimized for locality (fetch). + * + * buffer must contain enough space for the encoded meshlet (use meshopt_encodeMeshletBound to compute worst case size) + * vertices may be NULL, in which case vertex_count must be 0 and only triangle data is encoded + * vertex_count and triangle_count must be <= 256. + */ +MESHOPTIMIZER_API size_t meshopt_encodeMeshlet(unsigned char* buffer, size_t buffer_size, const unsigned int* vertices, size_t vertex_count, const unsigned char* triangles, size_t triangle_count); +MESHOPTIMIZER_API size_t meshopt_encodeMeshletBound(size_t max_vertices, size_t max_triangles); + +/** + * Meshlet decoder + * Decodes meshlet data from an array of bytes generated by meshopt_encodeMeshlet + * Returns 0 if decoding was successful, and an error code otherwise + * The decoder is safe to use for untrusted input, but it may produce garbage data. + * + * vertices must contain enough space for the resulting vertex data, aligned to 4 bytes (align(vertex_count * vertex_size, 4) bytes) + * vertex_size must be 2 (16-bit vertex references) or 4 (32-bit vertex references) + * triangles must contain enough space for the resulting triangle data, aligned to 4 bytes (align(triangle_count * triangle_size, 4) bytes) + * triangle_size must be 3 (8-bit triangle indices) or 4 (32-bit packed triangles, stored as (a) | (b << 8) | (c << 16)) + * vertex_count, triangle_count match those used during encoding exactly; buffer_size must be equal to the encoded size returned by meshopt_encodeMeshlet. + * vertices may be NULL, in which case vertex_count must be 0 and the meshlet must contain just triangle data + * + * When using "raw" decoding (meshopt_decodeMeshletRaw), both vertices and triangles should have available space further aligned to 16 bytes for efficient SIMD decoding. + */ +MESHOPTIMIZER_API int meshopt_decodeMeshlet(void* vertices, size_t vertex_count, size_t vertex_size, void* triangles, size_t triangle_count, size_t triangle_size, const unsigned char* buffer, size_t buffer_size); +MESHOPTIMIZER_API int meshopt_decodeMeshletRaw(unsigned int* vertices, size_t vertex_count, unsigned int* triangles, size_t triangle_count, const unsigned char* buffer, size_t buffer_size); + +/** + * Vertex buffer encoder + * Encodes vertex data into an array of bytes that is generally smaller and compresses better compared to original. + * Returns encoded data size on success, 0 on error; the only error condition is if buffer doesn't have enough space + * This function works for a single vertex stream; for multiple vertex streams, call meshopt_encodeVertexBuffer for each stream. + * Note that all vertex_size bytes of each vertex are encoded verbatim, including padding which should be zero-initialized. + * For maximum efficiency the vertex buffer being encoded has to be quantized and optimized for locality of reference (cache/fetch) first. + * + * buffer must contain enough space for the encoded vertex buffer (use meshopt_encodeVertexBufferBound to compute worst case size) + * vertex_size must be a multiple of 4 (and <= 256) + */ +MESHOPTIMIZER_API size_t meshopt_encodeVertexBuffer(unsigned char* buffer, size_t buffer_size, const void* vertices, size_t vertex_count, size_t vertex_size); +MESHOPTIMIZER_API size_t meshopt_encodeVertexBufferBound(size_t vertex_count, size_t vertex_size); + +/** + * Vertex buffer encoder + * Encodes vertex data just like meshopt_encodeVertexBuffer, but allows to override compression level. + * For compression level to take effect, the vertex encoding version must be set to 1. + * The default compression level implied by meshopt_encodeVertexBuffer is 2. + * + * buffer must contain enough space for the encoded vertex buffer (use meshopt_encodeVertexBufferBound to compute worst case size) + * vertex_size must be a multiple of 4 (and <= 256) + * level should be in the range [0, 3] with 0 being the fastest and 3 being the slowest and producing the best compression ratio. + * version should be -1 to use the default version (specified via meshopt_encodeVertexVersion), or 0/1 to override the version; per above, level won't take effect if version is 0. + */ +MESHOPTIMIZER_API size_t meshopt_encodeVertexBufferLevel(unsigned char* buffer, size_t buffer_size, const void* vertices, size_t vertex_count, size_t vertex_size, int level, int version); + +/** + * Set vertex encoder format version (defaults to 1) + * This function is not thread safe and must not be called concurrently with meshopt_encodeVertexBuffer/meshopt_encodeVertexBufferLevel. + * + * version must specify the data format version to encode; valid values are 0 (decodable by all library versions) and 1 (decodable by 0.23+) + */ +MESHOPTIMIZER_API void meshopt_encodeVertexVersion(int version); + +/** + * Vertex buffer decoder + * Decodes vertex data from an array of bytes generated by meshopt_encodeVertexBuffer + * Returns 0 if decoding was successful, and an error code otherwise + * The decoder is safe to use for untrusted input, but it may produce garbage data. + * + * destination must contain enough space for the resulting vertex buffer (vertex_count * vertex_size bytes) + * vertex_size must be a multiple of 4 (and <= 256) + */ +MESHOPTIMIZER_API int meshopt_decodeVertexBuffer(void* destination, size_t vertex_count, size_t vertex_size, const unsigned char* buffer, size_t buffer_size); + +/** + * Get encoded vertex format version + * Returns format version of the encoded vertex buffer, or -1 if the buffer header is invalid + * Note that a non-negative value doesn't guarantee that the buffer will be decoded correctly if the input is malformed. + */ +MESHOPTIMIZER_API int meshopt_decodeVertexVersion(const unsigned char* buffer, size_t buffer_size); + +/** + * Vertex buffer filters + * These functions can be used to filter output of meshopt_decodeVertexBuffer in-place. + * + * meshopt_decodeFilterOct decodes octahedral encoding of a unit vector with K-bit signed X/Y as an input; Z must store 1.0f. + * Each component is stored as an 8-bit or 16-bit normalized integer; stride must be equal to 4 or 8. W is preserved as is. + * + * meshopt_decodeFilterQuat decodes 3-component quaternion encoding with K-bit component encoding and a 2-bit component index indicating which component to reconstruct. + * Each component is stored as a 16-bit integer; stride must be equal to 8. + * + * meshopt_decodeFilterExp decodes exponential encoding of floating-point data with 8-bit exponent and 24-bit integer mantissa as 2^E*M. + * Each 32-bit component is decoded in isolation; stride must be divisible by 4. + * + * meshopt_decodeFilterColor decodes RGBA colors from YCoCg (+A) color encoding where RGB is converted to YCoCg space with K-bit component encoding, and A is stored using K-1 bits. + * Each component is stored as an 8-bit or 16-bit normalized integer; stride must be equal to 4 or 8. + */ +MESHOPTIMIZER_API void meshopt_decodeFilterOct(void* buffer, size_t count, size_t stride); +MESHOPTIMIZER_API void meshopt_decodeFilterQuat(void* buffer, size_t count, size_t stride); +MESHOPTIMIZER_API void meshopt_decodeFilterExp(void* buffer, size_t count, size_t stride); +MESHOPTIMIZER_API void meshopt_decodeFilterColor(void* buffer, size_t count, size_t stride); + +/** + * Vertex buffer filter encoders + * These functions can be used to encode data in a format that meshopt_decodeFilter can decode + * + * meshopt_encodeFilterOct encodes unit vectors with K-bit (2 <= K <= 16) signed X/Y as an output. + * Each component is stored as an 8-bit or 16-bit normalized integer; stride must be equal to 4 (K <= 8) or 8 (K <= 16). Z will store 1.0f, W is preserved as is. + * Input data must contain 4 floats for every vector (count*4 total). + * + * meshopt_encodeFilterQuat encodes unit quaternions with K-bit (4 <= K <= 16) component encoding. + * Each component is stored as a 16-bit integer; stride must be equal to 8. + * Input data must contain 4 floats for every quaternion (count*4 total). + * + * meshopt_encodeFilterExp encodes arbitrary (finite) floating-point data with 8-bit exponent and K-bit integer mantissa (1 <= K <= 24). + * Exponent can be shared between all components of a given vector as defined by stride or all values of a given component; stride must be divisible by 4 (and <= 256). + * Input data must contain stride/4 floats for every vector (count*stride/4 total). + * + * meshopt_encodeFilterColor encodes RGBA color data by converting RGB to YCoCg color space with K-bit (2 <= K <= 16) component encoding; A is stored using K-1 bits. + * Each component is stored as an 8-bit or 16-bit integer; stride must be equal to 4 (K <= 8) or 8 (K <= 16). + * Input data must contain 4 floats for every color (count*4 total). + */ +enum meshopt_EncodeExpMode +{ + /* When encoding exponents, use separate values for each component (maximum quality) */ + meshopt_EncodeExpSeparate, + /* When encoding exponents, use shared value for all components of each vector (better compression) */ + meshopt_EncodeExpSharedVector, + /* When encoding exponents, use shared value for each component of all vectors (best compression) */ + meshopt_EncodeExpSharedComponent, + /* When encoding exponents, use separate values for each component, but clamp to 0 (good quality if very small values are not important) */ + meshopt_EncodeExpClamped, +}; + +MESHOPTIMIZER_API void meshopt_encodeFilterOct(void* destination, size_t count, size_t stride, int bits, const float* data); +MESHOPTIMIZER_API void meshopt_encodeFilterQuat(void* destination, size_t count, size_t stride, int bits, const float* data); +MESHOPTIMIZER_API void meshopt_encodeFilterExp(void* destination, size_t count, size_t stride, int bits, const float* data, enum meshopt_EncodeExpMode mode); +MESHOPTIMIZER_API void meshopt_encodeFilterColor(void* destination, size_t count, size_t stride, int bits, const float* data); + +/** + * Simplification options + */ +enum +{ + /* Do not move vertices that are located on the topological border (vertices on triangle edges that don't have a paired triangle). Useful for simplifying portions of the larger mesh. */ + meshopt_SimplifyLockBorder = 1 << 0, + /* Improve simplification performance assuming input indices are a sparse subset of the mesh. Note that error becomes relative to subset extents. */ + meshopt_SimplifySparse = 1 << 1, + /* Treat error limit and resulting error as absolute instead of relative to mesh extents. */ + meshopt_SimplifyErrorAbsolute = 1 << 2, + /* Remove disconnected parts of the mesh during simplification incrementally, regardless of the topological restrictions inside components. */ + meshopt_SimplifyPrune = 1 << 3, + /* Produce more regular triangle sizes and shapes during simplification, at some cost to geometric and attribute quality. */ + meshopt_SimplifyRegularize = 1 << 4, + /* Allow collapses across attribute discontinuities, except for vertices that are tagged with meshopt_SimplifyVertex_Protect in vertex_lock. */ + meshopt_SimplifyPermissive = 1 << 5, + /* Produce more regular triangle sizes and shapes during simplification, at a small cost to geometric and attribute quality. */ + meshopt_SimplifyRegularizeLight = 1 << 6, + /* Experimental: Try to preserve fold lines between opposite-facing triangles, at a small performance cost. */ + meshopt_SimplifyPreserveFolds = 1 << 7, + /* Experimental: Clamp attribute error to match position error scale and avoid extreme error values in areas with high attribute variance. */ + meshopt_SimplifyErrorClamped = 1 << 8, +}; + +/** + * Simplification vertex flags/locks, for use in `vertex_lock` arrays in simplification APIs + */ +enum +{ + /* Do not move this vertex. */ + meshopt_SimplifyVertex_Lock = 1 << 0, + /* Protect attribute discontinuity at this vertex; must be used together with meshopt_SimplifyPermissive option. */ + meshopt_SimplifyVertex_Protect = 1 << 1, + /* Increase priority for this vertex, making it more likely that it's preserved during simplification. */ + meshopt_SimplifyVertex_Priority = 1 << 2, +}; + +/** + * Mesh simplifier + * Reduces the number of triangles in the mesh, attempting to preserve mesh appearance as much as possible + * The algorithm tries to preserve mesh topology and can stop short of the target goal based on topology constraints or target error. + * If not all attributes from the input mesh are needed, it's recommended to reindex the mesh without them prior to simplification. + * Returns the number of indices after simplification, with destination containing new index data + * + * The resulting index buffer references vertices from the original vertex buffer. + * If the original vertex data isn't needed, creating a compact vertex buffer using meshopt_optimizeVertexFetch is recommended. + * + * destination must contain enough space for the target index buffer, worst case is index_count elements (*not* target_index_count)! + * vertex_positions should have float3 position in the first 12 bytes of each vertex + * target_error represents the error relative to mesh extents that can be tolerated, e.g. 0.01 = 1% deformation (unless absolute error option is used) + * options must be a bitmask composed of meshopt_SimplifyX options; 0 is a safe default + * result_error can be NULL; when it's not NULL, it will contain the resulting (relative/absolute) error after simplification + */ +MESHOPTIMIZER_API size_t meshopt_simplify(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t target_index_count, float target_error, unsigned int options, float* result_error); + +/** + * Mesh simplifier with attribute metric + * Reduces the number of triangles in the mesh, attempting to preserve mesh appearance as much as possible. + * Similar to meshopt_simplify, but incorporates attribute values into the error metric used to prioritize simplification order. + * The algorithm tries to preserve mesh topology and can stop short of the target goal based on topology constraints or target error. + * If not all attributes from the input mesh are needed, it's recommended to reindex the mesh without them prior to simplification. + * Returns the number of indices after simplification, with destination containing new index data + * + * The resulting index buffer references vertices from the original vertex buffer. + * If the original vertex data isn't needed, creating a compact vertex buffer using meshopt_optimizeVertexFetch is recommended. + * Note that the number of attributes with non-zero weights affects memory requirements and running time. + * + * destination must contain enough space for the target index buffer, worst case is index_count elements (*not* target_index_count)! + * vertex_positions should have float3 position in the first 12 bytes of each vertex + * vertex_attributes should have attribute_count floats for each vertex + * attribute_weights should have attribute_count floats in total; the weights determine relative priority of attributes between each other and wrt position + * attribute_count must be <= 32 + * vertex_lock can be NULL; when it's not NULL, it should have a value for each vertex composed of meshopt_SimplifyVertex_* flags + * target_error represents the error relative to mesh extents that can be tolerated, e.g. 0.01 = 1% deformation (unless absolute error option is used) + * options must be a bitmask composed of meshopt_SimplifyX options; 0 is a safe default + * result_error can be NULL; when it's not NULL, it will contain the resulting (relative/absolute) error after simplification + */ +MESHOPTIMIZER_API size_t meshopt_simplifyWithAttributes(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, const float* vertex_attributes, size_t vertex_attributes_stride, const float* attribute_weights, size_t attribute_count, const unsigned char* vertex_lock, size_t target_index_count, float target_error, unsigned int options, float* result_error); + +/** + * Mesh simplifier with position/attribute update + * Reduces the number of triangles in the mesh, attempting to preserve mesh appearance as much as possible. + * Similar to meshopt_simplifyWithAttributes, but destructively updates positions and attribute values for optimal appearance. + * The algorithm tries to preserve mesh topology and can stop short of the target goal based on topology constraints or target error. + * If not all attributes from the input mesh are needed, it's recommended to reindex the mesh without them prior to simplification. + * Returns the number of indices after simplification, indices are destructively updated with new index data + * + * The updated index buffer references vertices from the original vertex buffer, however the vertex positions and attributes are updated in-place. + * Creating a compact vertex buffer using meshopt_optimizeVertexFetch is recommended; if the original vertex data is needed, it should be copied before simplification. + * Note that the number of attributes with non-zero weights affects memory requirements and running time. Attributes with zero weights are not updated. + * + * vertex_positions should have float3 position in the first 12 bytes of each vertex + * vertex_attributes should have attribute_count floats for each vertex + * attribute_weights should have attribute_count floats in total; the weights determine relative priority of attributes between each other and wrt position + * attribute_count must be <= 32 + * vertex_lock can be NULL; when it's not NULL, it should have a value for each vertex composed of meshopt_SimplifyVertex_* flags + * target_error represents the error relative to mesh extents that can be tolerated, e.g. 0.01 = 1% deformation (unless absolute error option is used) + * options must be a bitmask composed of meshopt_SimplifyX options; 0 is a safe default + * result_error can be NULL; when it's not NULL, it will contain the resulting (relative/absolute) error after simplification + */ +MESHOPTIMIZER_API size_t meshopt_simplifyWithUpdate(unsigned int* indices, size_t index_count, float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float* vertex_attributes, size_t vertex_attributes_stride, const float* attribute_weights, size_t attribute_count, const unsigned char* vertex_lock, size_t target_index_count, float target_error, unsigned int options, float* result_error); + +/** + * Mesh simplifier (sloppy) + * Reduces the number of triangles in the mesh, sacrificing mesh appearance for simplification performance + * The algorithm doesn't preserve mesh topology but can stop short of the target goal based on target error. + * Returns the number of indices after simplification, with destination containing new index data + * The resulting index buffer references vertices from the original vertex buffer. + * If the original vertex data isn't needed, creating a compact vertex buffer using meshopt_optimizeVertexFetch is recommended. + * + * destination must contain enough space for the target index buffer, worst case is index_count elements (*not* target_index_count)! + * vertex_positions should have float3 position in the first 12 bytes of each vertex + * vertex_lock can be NULL; when it's not NULL, it should have a value for each vertex; vertices that can't be moved should set 1 consistently for all indices with the same position + * target_error represents the error relative to mesh extents that can be tolerated, e.g. 0.01 = 1% deformation; value range [0..1] + * result_error can be NULL; when it's not NULL, it will contain the resulting (relative) error after simplification + */ +MESHOPTIMIZER_API size_t meshopt_simplifySloppy(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, const unsigned char* vertex_lock, size_t target_index_count, float target_error, float* result_error); + +/** + * Mesh simplifier (pruner) + * Reduces the number of triangles in the mesh by removing small isolated parts of the mesh + * Returns the number of indices after simplification, with destination containing new index data + * The resulting index buffer references vertices from the original vertex buffer. + * If the original vertex data isn't needed, creating a compact vertex buffer using meshopt_optimizeVertexFetch is recommended. + * + * destination must contain enough space for the target index buffer, worst case is index_count elements + * vertex_positions should have float3 position in the first 12 bytes of each vertex + * target_error represents the error relative to mesh extents that can be tolerated, e.g. 0.01 = 1% deformation; value range [0..1] + */ +MESHOPTIMIZER_API size_t meshopt_simplifyPrune(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float target_error); + +/** + * Point cloud simplifier + * Reduces the number of points in the cloud to reach the given target + * Returns the number of points after simplification, with destination containing new index data + * The resulting index buffer references vertices from the original vertex buffer. + * If the original vertex data isn't needed, creating a compact vertex buffer using meshopt_optimizeVertexFetch is recommended. + * + * destination must contain enough space for the target index buffer (target_vertex_count elements) + * vertex_positions should have float3 position in the first 12 bytes of each vertex + * vertex_colors can be NULL; when it's not NULL, it should have float3 color in the first 12 bytes of each vertex + * color_weight determines relative priority of color wrt position; 1.0 is a safe default + */ +MESHOPTIMIZER_API size_t meshopt_simplifyPoints(unsigned int* destination, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, const float* vertex_colors, size_t vertex_colors_stride, float color_weight, size_t target_vertex_count); + +/** + * Returns the error scaling factor used by the simplifier to convert between absolute and relative extents + * + * Absolute error must be *divided* by the scaling factor before passing it to meshopt_simplify as target_error + * Relative error returned by meshopt_simplify via result_error must be *multiplied* by the scaling factor to get absolute error. + */ +MESHOPTIMIZER_API float meshopt_simplifyScale(const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride); + +/** + * Mesh stripifier + * Converts a previously vertex cache optimized triangle list to triangle strip, stitching strips using restart index or degenerate triangles + * Returns the number of indices in the resulting strip, with destination containing new index data + * For maximum efficiency the index buffer being converted has to be optimized for vertex cache first. + * Using restart indices can result in ~10% smaller index buffers, but on some GPUs restart indices may result in decreased performance. + * + * destination must contain enough space for the target index buffer, worst case can be computed with meshopt_stripifyBound + * restart_index should be 0xffff or 0xffffffff depending on index size, or 0 to use degenerate triangles + */ +MESHOPTIMIZER_API size_t meshopt_stripify(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count, unsigned int restart_index); +MESHOPTIMIZER_API size_t meshopt_stripifyBound(size_t index_count); + +/** + * Mesh unstripifier + * Converts a triangle strip to a triangle list + * Returns the number of indices in the resulting list, with destination containing new index data + * + * destination must contain enough space for the target index buffer, worst case can be computed with meshopt_unstripifyBound + */ +MESHOPTIMIZER_API size_t meshopt_unstripify(unsigned int* destination, const unsigned int* indices, size_t index_count, unsigned int restart_index); +MESHOPTIMIZER_API size_t meshopt_unstripifyBound(size_t index_count); + +struct meshopt_VertexCacheStatistics +{ + unsigned int vertices_transformed; + unsigned int warps_executed; + float acmr; /* transformed vertices / triangle count; best case 0.5, worst case 3.0, optimum depends on topology */ + float atvr; /* transformed vertices / vertex count; best case 1.0, worst case 6.0, optimum is 1.0 (each vertex is transformed once) */ +}; + +/** + * Vertex transform cache analyzer + * Returns cache hit statistics using a simplified FIFO model + * Results may not match actual GPU performance + */ +MESHOPTIMIZER_API struct meshopt_VertexCacheStatistics meshopt_analyzeVertexCache(const unsigned int* indices, size_t index_count, size_t vertex_count, unsigned int cache_size, unsigned int warp_size, unsigned int primgroup_size); + +struct meshopt_VertexFetchStatistics +{ + unsigned int bytes_fetched; + float overfetch; /* fetched bytes / vertex buffer size; best case 1.0 (each byte is fetched once) */ +}; + +/** + * Vertex fetch cache analyzer + * Returns cache hit statistics using a simplified direct mapped model + * Results may not match actual GPU performance + */ +MESHOPTIMIZER_API struct meshopt_VertexFetchStatistics meshopt_analyzeVertexFetch(const unsigned int* indices, size_t index_count, size_t vertex_count, size_t vertex_size); + +struct meshopt_OverdrawStatistics +{ + unsigned int pixels_covered; + unsigned int pixels_shaded; + float overdraw; /* shaded pixels / covered pixels; best case 1.0 */ +}; + +/** + * Overdraw analyzer + * Returns overdraw statistics using a software rasterizer + * Results may not match actual GPU performance + * + * vertex_positions should have float3 position in the first 12 bytes of each vertex + */ +MESHOPTIMIZER_API struct meshopt_OverdrawStatistics meshopt_analyzeOverdraw(const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride); + +struct meshopt_CoverageStatistics +{ + float coverage[3]; + float extent; /* viewport size in mesh coordinates */ +}; + +/** + * Coverage analyzer + * Returns coverage statistics (ratio of viewport pixels covered from each axis) using a software rasterizer + * + * vertex_positions should have float3 position in the first 12 bytes of each vertex + */ +MESHOPTIMIZER_API struct meshopt_CoverageStatistics meshopt_analyzeCoverage(const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride); + +/** + * Meshlet is a small mesh cluster (subset) that consists of: + * - triangles, an 8-bit micro triangle (index) buffer, that for each triangle specifies three local vertices to use; + * - vertices, a 32-bit vertex indirection buffer, that for each local vertex specifies which mesh vertex to fetch vertex attributes from. + * + * For efficiency, meshlet triangles and vertices are packed into two large arrays; this structure contains offsets and counts to access the data. + */ +struct meshopt_Meshlet +{ + /* offsets within meshlet_vertices and meshlet_triangles arrays with meshlet data */ + unsigned int vertex_offset; + unsigned int triangle_offset; + + /* number of vertices and triangles used in the meshlet; data is stored in consecutive range [offset..offset+count) for vertices and [offset..offset+count*3) for triangles */ + unsigned int vertex_count; + unsigned int triangle_count; +}; + +/** + * Meshlet builder + * Splits the mesh into a set of meshlets where each meshlet has a micro index buffer indexing into meshlet vertices that refer to the original vertex buffer + * The resulting data can be used to render meshes using NVidia programmable mesh shading pipeline, or in other cluster-based renderers. + * When targeting mesh shading hardware, for maximum efficiency meshlets should be further optimized using meshopt_optimizeMeshlet. + * When using buildMeshlets, vertex positions need to be provided to minimize the size of the resulting clusters. + * When using buildMeshletsScan, for maximum efficiency the index buffer being converted has to be optimized for vertex cache first. + * + * meshlets must contain enough space for all meshlets, worst case size can be computed with meshopt_buildMeshletsBound + * meshlet_vertices must contain enough space for all meshlets, worst case is index_count elements (*not* vertex_count!) + * meshlet_triangles must contain enough space for all meshlets, worst case is index_count elements + * vertex_positions should have float3 position in the first 12 bytes of each vertex + * max_vertices and max_triangles must not exceed implementation limits (max_vertices <= 256, max_triangles <= 512) + * cone_weight should be set to 0 when cone culling is not used, and a value between 0 and 1 otherwise to balance between cluster size and cone culling efficiency + */ +MESHOPTIMIZER_API size_t meshopt_buildMeshlets(struct meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t max_vertices, size_t max_triangles, float cone_weight); +MESHOPTIMIZER_API size_t meshopt_buildMeshletsScan(struct meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const unsigned int* indices, size_t index_count, size_t vertex_count, size_t max_vertices, size_t max_triangles); +MESHOPTIMIZER_API size_t meshopt_buildMeshletsBound(size_t index_count, size_t max_vertices, size_t max_triangles); + +/** + * Meshlet builder with flexible cluster sizes + * Splits the mesh into a set of meshlets, similarly to meshopt_buildMeshlets, but allows to specify minimum and maximum number of triangles per meshlet. + * Clusters between min and max triangle counts are split when the cluster size would have exceeded the expected cluster size by more than split_factor. + * + * meshlets must contain enough space for all meshlets, worst case size can be computed with meshopt_buildMeshletsBound using min_triangles (*not* max!) + * meshlet_vertices must contain enough space for all meshlets, worst case is index_count elements (*not* vertex_count!) + * meshlet_triangles must contain enough space for all meshlets, worst case is index_count elements + * vertex_positions should have float3 position in the first 12 bytes of each vertex + * max_vertices, min_triangles and max_triangles must not exceed implementation limits (max_vertices <= 256, max_triangles <= 512; min_triangles <= max_triangles) + * cone_weight should be set to 0 when cone culling is not used, and a value between 0 and 1 otherwise to balance between cluster size and cone culling efficiency + * split_factor should be set to a non-negative value; when greater than 0, clusters that have large bounds may be split unless they are under the min_triangles threshold + */ +MESHOPTIMIZER_API size_t meshopt_buildMeshletsFlex(struct meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t max_vertices, size_t min_triangles, size_t max_triangles, float cone_weight, float split_factor); + +/** + * Meshlet builder that produces clusters optimized for raytracing + * Splits the mesh into a set of meshlets, similarly to meshopt_buildMeshlets, but optimizes cluster subdivision for raytracing and allows to specify minimum and maximum number of triangles per meshlet. + * + * meshlets must contain enough space for all meshlets, worst case size can be computed with meshopt_buildMeshletsBound using min_triangles (*not* max!) + * meshlet_vertices must contain enough space for all meshlets, worst case is index_count elements (*not* vertex_count!) + * meshlet_triangles must contain enough space for all meshlets, worst case is index_count elements + * vertex_positions should have float3 position in the first 12 bytes of each vertex + * max_vertices, min_triangles and max_triangles must not exceed implementation limits (max_vertices <= 256, max_triangles <= 512; min_triangles <= max_triangles) + * fill_weight allows to prioritize clusters that are closer to maximum size at some cost to SAH quality; 0.5 is a safe default + */ +MESHOPTIMIZER_API size_t meshopt_buildMeshletsSpatial(struct meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t max_vertices, size_t min_triangles, size_t max_triangles, float fill_weight); + +/** + * Meshlet optimizer + * Reorders meshlet vertices and triangles to maximize locality which can improve rasterizer throughput or ray tracing performance when using fast-build modes. + * + * meshlet_triangles and meshlet_vertices must refer to meshlet data; when buildMeshlets* is used, these need to be computed from meshlet's vertex_offset and triangle_offset + * triangle_count and vertex_count must not exceed implementation limits (vertex_count <= 256, triangle_count <= 512) + */ +MESHOPTIMIZER_API void meshopt_optimizeMeshlet(unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, size_t triangle_count, size_t vertex_count); + +/** + * Meshlet optimizer + * Reorders meshlet vertices and triangles to maximize locality, with higher levels resulting in smaller compressed size at the cost of optimization time. + * At level 0 the result is equivalent to meshopt_optimizeMeshlet; levels >= 1 may rotate triangle corners to improve compression (which can change provoking vertex and affect OMM data). + * + * level should be in the range [0, 9] with 0 equivalent to meshopt_optimizeMeshlet and 9 being the slowest; the sweet spot for compression ratio is around 3 + */ +MESHOPTIMIZER_API void meshopt_optimizeMeshletLevel(unsigned int* meshlet_vertices, size_t vertex_count, unsigned char* meshlet_triangles, size_t triangle_count, int level); + +struct meshopt_Bounds +{ + /* bounding sphere, useful for frustum and occlusion culling */ + float center[3]; + float radius; + + /* normal cone, useful for backface culling */ + float cone_apex[3]; + float cone_axis[3]; + float cone_cutoff; /* = cos(angle/2) */ + + /* normal cone axis and cutoff, stored in 8-bit SNORM format; decode using x/127.0 */ + signed char cone_axis_s8[3]; + signed char cone_cutoff_s8; +}; + +/** + * Cluster bounds generator + * Creates bounding volumes that can be used for frustum, backface and occlusion culling. + * + * For backface culling with orthographic projection, use the following formula to reject backfacing clusters: + * dot(view, cone_axis) >= cone_cutoff + * + * For perspective projection, you can use the formula that needs cone apex in addition to axis & cutoff: + * dot(normalize(cone_apex - camera_position), cone_axis) >= cone_cutoff + * + * Alternatively, you can use the formula that doesn't need cone apex and uses bounding sphere instead: + * dot(normalize(center - camera_position), cone_axis) >= cone_cutoff + radius / length(center - camera_position) + * or an equivalent formula that doesn't have a singularity at center = camera_position: + * dot(center - camera_position, cone_axis) >= cone_cutoff * length(center - camera_position) + radius + * + * The formula that uses the apex is slightly more accurate but needs the apex; if you are already using bounding sphere + * to do frustum/occlusion culling, the formula that doesn't use the apex may be preferable (for derivation see + * Real-Time Rendering 4th Edition, section 19.3). + * + * vertex_positions should have float3 position in the first 12 bytes of each vertex + * vertex_count should specify the number of vertices in the entire mesh, not cluster or meshlet + * indices should have at most 256 unique vertex indices + * index_count/3 and triangle_count must not exceed implementation limits (<= 512) + */ +MESHOPTIMIZER_API struct meshopt_Bounds meshopt_computeClusterBounds(const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride); +MESHOPTIMIZER_API struct meshopt_Bounds meshopt_computeMeshletBounds(const unsigned int* meshlet_vertices, const unsigned char* meshlet_triangles, size_t triangle_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride); + +/** + * Sphere bounds generator + * Creates bounding sphere around a set of points or a set of spheres; returns the center and radius of the sphere, with other fields of the result set to 0. + * + * positions should have float3 position in the first 12 bytes of each element + * radii can be NULL; when it's not NULL, it should have a non-negative float radius in the first 4 bytes of each element + */ +MESHOPTIMIZER_API struct meshopt_Bounds meshopt_computeSphereBounds(const float* positions, size_t count, size_t positions_stride, const float* radii, size_t radii_stride); + +/** + * Extract meshlet-local vertex and triangle indices from absolute cluster indices. + * Fills triangles[] and vertices[] such that vertices[triangles[i]] == indices[i], and returns the number of unique vertices. + * + * vertices must contain enough space for the resulting references (up to 256 elements) + * triangles must contain enough space for local indices (index_count elements) + * indices should have at most 256 unique vertex indices + * index_count/3 must not exceed implementation limits (<= 512) + */ +MESHOPTIMIZER_API size_t meshopt_extractMeshletIndices(unsigned int* vertices, unsigned char* triangles, const unsigned int* indices, size_t index_count); + +/** + * Cluster partitioner + * Partitions clusters into groups of similar size, prioritizing grouping clusters that share vertices or are close to each other. + * When vertex positions are not provided, only clusters that share vertices will be grouped together, which may result in small partitions for some inputs. + * + * destination must contain enough space for the resulting partition data (cluster_count elements) + * destination[i] will contain the partition id for cluster i, with the total number of partitions returned by the function + * cluster_indices should have the vertex indices referenced by each cluster, stored sequentially + * cluster_index_counts should have the number of indices in each cluster; sum of all cluster_index_counts must be equal to total_index_count + * vertex_positions can be NULL; when it's not NULL, it should have float3 position in the first 12 bytes of each vertex + * target_partition_size is a target size for each partition, in clusters; the resulting partitions may be smaller or larger (up to target + target/3) + */ +MESHOPTIMIZER_API size_t meshopt_partitionClusters(unsigned int* destination, const unsigned int* cluster_indices, size_t total_index_count, const unsigned int* cluster_index_counts, size_t cluster_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t target_partition_size); + +/** + * Spatial sorter + * Generates a remap table that can be used to reorder points for spatial locality. + * Resulting remap table maps old vertices to new vertices and can be used in meshopt_remapVertexBuffer. + * + * destination must contain enough space for the resulting remap table (vertex_count elements) + * vertex_positions should have float3 position in the first 12 bytes of each vertex + */ +MESHOPTIMIZER_API void meshopt_spatialSortRemap(unsigned int* destination, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride); + +/** + * Spatial sorter + * Reorders triangles for spatial locality, and generates a new index buffer. The resulting index buffer can be used with other functions like optimizeVertexCache. + * + * destination must contain enough space for the resulting index buffer (index_count elements) + * vertex_positions should have float3 position in the first 12 bytes of each vertex + */ +MESHOPTIMIZER_API void meshopt_spatialSortTriangles(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride); + +/** + * Spatial clusterizer + * Reorders points into clusters optimized for spatial locality, and generates a new index buffer. + * Ensures the output can be split into cluster_size chunks where each chunk has good positional locality. Only the last chunk will be smaller than cluster_size. + * + * destination must contain enough space for the resulting index buffer (vertex_count elements) + * vertex_positions should have float3 position in the first 12 bytes of each vertex + */ +MESHOPTIMIZER_API void meshopt_spatialClusterPoints(unsigned int* destination, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t cluster_size); + +/** + * Opacity micromap generator (measure) + * Computes a subdivision level for each input triangle, as well as deduplicating the triangles that reference the same UVs to reduce rasterization requests. + * Returns the number of OMM entries. + * + * levels and sources must contain enough space for the worst case output (index_count/3 elements, one per resulting OMM entry) + * levels[i] will contain the subdivision level for entry i, with the total number of entries returned by the function; each entry should be rasterized from triangle index sources[i] + * omm_indices must contain enough space for the resulting OMM indices (index_count/3 elements, one per triangle) + * vertex_uvs should have float2 texture coordinate in the first 8 bytes of each vertex + * max_level specifies the maximum subdivision level (0..12) + * target_edge can be 0; when >0, triangle subdivision is adaptive and targets target_edge^2 texel area + */ +MESHOPTIMIZER_API size_t meshopt_opacityMapMeasure(unsigned char* levels, unsigned int* sources, int* omm_indices, const unsigned int* indices, size_t index_count, const float* vertex_uvs, size_t vertex_count, size_t vertex_uvs_stride, unsigned int texture_width, unsigned int texture_height, int max_level, float target_edge); + +/** + * Opacity micromap generator (rasterize) + * Rasterizes opacity state for a single triangle entry by sampling the alpha texture, using bilinear filtering and 0.5 alpha cutoff. + * + * result should contain enough space for the output opacity data (which can be computed using meshopt_opacityMapEntrySize) + * level specifies the subdivision level (0..12) + * states should be 2 for 2-state format (opaque/transparent) and 4 for 4-state format (opaque/transparent/unknown) + * uv0/uv1/uv2 should refer to a float2 texture coordinate for each triangle corner; note that micromap data is sensitive to the corner order + * texture_data should point to the alpha channel of the first pixel, encoded as UNORM8 + * texture_stride specifies the distance in bytes between consecutive pixels, e.g. 4 for RGBA input + * texture_pitch specifies the distance in bytes between consecutive rows, e.g. 4*texture_width for tightly packed RGBA input + */ +MESHOPTIMIZER_API void meshopt_opacityMapRasterize(unsigned char* result, int level, int states, const float* uv0, const float* uv1, const float* uv2, const unsigned char* texture_data, size_t texture_stride, size_t texture_pitch, unsigned int texture_width, unsigned int texture_height); +MESHOPTIMIZER_API size_t meshopt_opacityMapEntrySize(int level, int states); + +/** + * Opacity micromap generator (compact) + * Compacts and deduplicates opacity data, merging identical micromap entries and replacing micromap states with special indices (-4..-1) when possible. + * Returns the number of OMM entries after compaction; the data array should be trimmed using the last offset/size. + * + * data should contain opacity data for all input/output entries + * levels should contain subdivision levels for all input/output entries + * offsets should contain offset into data[] for each entry + * levels[i] and offsets[i] will be updated with post-compaction level/offset for entry i, with the total number of entries returned by the function + * omm_indices should contain indices into the original OMM data, and will be updated with a new index or a special index (-4..-1) when possible + * states should be 2 for 2-state format (opaque/transparent) and 4 for 4-state format (opaque/transparent/unknown) + */ +MESHOPTIMIZER_API size_t meshopt_opacityMapCompact(unsigned char* data, size_t data_size, unsigned char* levels, unsigned int* offsets, size_t omm_count, int* omm_indices, size_t triangle_count, int states); + +/** + * Tangent generation options + */ +enum +{ + /* Produce tangents compatible with MikkTSpace (same weighting and fallbacks) at the cost of reduced quality. Not recommended unless normal maps are baked. */ + meshopt_TangentCompatible = 1 << 0, + /* For vertices only connected to degenerate triangles, output zero tangents instead of an arbitrary fallback. */ + meshopt_TangentZeroFallback = 1 << 1, +}; + +/** + * Tangent space generator + * Computes per-corner tangent vectors; for each corner, computes normalized tangent vector (xyz) and orientation (w, +/-1). + * Bitangent can be reconstructed via cross(normal, tangent.xyz) * tangent.w. + * To apply tangents to the mesh, either deindex and reindex it with the tangent stream, or copy tangents to existing vertex data while duplicating + * vertices with different tangent vectors (e.g. on UV mirror seams). + * Input can be indexed or unindexed (indices=NULL); this does not affect the resulting tangents, but indexed inputs are faster to process. + * + * result must contain enough space for the output tangent data (index_count*4 elements) + * indices can be NULL if the input is unindexed + * vertex_positions should have float3 position in the first 12 bytes of each vertex + * vertex_normals should have unit float3 normal in the first 12 bytes of each vertex + * vertex_uvs should have float2 texture coordinate in the first 8 bytes of each vertex + */ +MESHOPTIMIZER_API void meshopt_generateTangents(float* result, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, const float* vertex_normals, size_t vertex_normals_stride, const float* vertex_uvs, size_t vertex_uvs_stride, unsigned int options); + +/** + * Experimental: Normal generator + * Computes per-corner normal vectors; normals are averaged across soft edges, using crease angle to determine which edges are hard. + * To apply normals to the mesh, either deindex and reindex it with the normal stream, or copy normals to existing vertex data while duplicating + * vertices with different normal vectors (on normal seams). + * Input can be indexed or unindexed (indices=NULL); this does not affect the resulting normals, but indexed inputs are faster to process. + * + * result must contain enough space for the output normal data (index_count*3 elements) + * indices can be NULL if the input is unindexed + * vertex_positions should have float3 position in the first 12 bytes of each vertex + * crease_angle specifies the angle in radians below which normals are averaged across edges + * smoothing specifies the amount of smoothing to apply to resulting normals as a post-process; larger smoothing values take longer, with the recommended range being [0..5]. + */ +MESHOPTIMIZER_EXPERIMENTAL void meshopt_generateNormals(float* result, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float crease_angle, float smoothing); + +/** + * Experimental: Remeshing flags + */ +enum +{ + /* Produce a two-sided shell that wraps around surfaces of the original mesh, instead of a solid mesh. */ + meshopt_RemeshShell = 1 << 0, + /* Compute optimal output positions that approximate the original surface as closely as possible. */ + meshopt_RemeshSolve = 1 << 1, +}; + +/** + * Experimental: Voxel remesher + * Generates a new mesh that approximates or refines the original mesh, attempting to preserve mesh appearance at a given voxel resolution. + * The original topology is not preserved; features that are closer than the voxel size may be merged, and small gaps in the original mesh may be closed. + * Returns the number of triangles in the new mesh, with destination containing a vertex position for each triangle corner. + * + * destination can be NULL; when it's not NULL, it must contain enough space for the resulting triangle buffer (max_triangle_count * 3 vertices, 3 floats per vertex) + * max_triangle_count is the number of triangles that can be written; when destination is NULL or insufficiently large, the returned value is an upper bound on the number of triangles + * vertex_positions should have float3 position in the first 12 bytes of each vertex + * resolution is the dimension of the internal voxel grid and should be in the range [4, 256] + * options must be a bitmask composed of meshopt_RemeshX options; 0 is a safe default + */ +MESHOPTIMIZER_EXPERIMENTAL size_t meshopt_remesh(float* destination, size_t max_triangle_count, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, int resolution, unsigned int options); + +/** + * Quantize a float into half-precision (as defined by IEEE-754 fp16) floating point value + * Generates +-inf for overflow, preserves NaN, flushes denormals to zero, rounds to nearest + * Representable magnitude range: [6e-5; 65504] + * Maximum relative reconstruction error: 5e-4 + */ +MESHOPTIMIZER_API unsigned short meshopt_quantizeHalf(float v); + +/** + * Quantize a float into a floating point value with a limited number of significant mantissa bits, preserving the IEEE-754 fp32 binary representation + * Preserves infinities/NaN, flushes denormals to zero, rounds to nearest + * Assumes N is in a valid mantissa precision range, which is 1..23 + */ +MESHOPTIMIZER_API float meshopt_quantizeFloat(float v, int N); + +/** + * Reverse quantization of a half-precision (as defined by IEEE-754 fp16) floating point value + * Preserves Inf/NaN, flushes denormals to zero + */ +MESHOPTIMIZER_API float meshopt_dequantizeHalf(unsigned short h); + +/** + * Compute shared exponent suitable for mesh/cluster position quantization + * Given mesh or cluster bounds, compute a shared exponent that can be used to quantize any position inside the bounds to a 24-bit integer grid. + * The resulting output can be stored as a compact bit-stream to be decoded directly in shaders, or to be used as an input to RT BVH builders, + * for example via D3D12_VERTEX_FORMAT_COMPRESSED1 in DXR2 (max_bits=16). + * + * To quantize positions, compute: + * scale = pow(2, exponent) + * iv = int(round(v / scale)) + * The resulting integer can be stored as signed 24-bit, or as an unsigned offset from a signed 24-bit anchor value, shared between all positions. + * + * minv/maxv specify the axis-aligned bounding box of the mesh or cluster; each should refer to a float3 value + * min_exp specifies the minimum value for the returned exponent, limiting precision to reduce size; e.g. min_exp = -10 limits precision to 1mm given metric units + * max_bits specifies the maximum allowed number of bits for the quantized integer range (offset from anchor is an unsigned integer up to 2^max_bits-1) + */ +MESHOPTIMIZER_API int meshopt_computePositionExponent(const float* minv, const float* maxv, int min_exp, int max_bits); + +/** + * Set allocation callbacks + * These callbacks will be used instead of the default operator new/operator delete for all temporary allocations in the library. + * Note that all algorithms only allocate memory for temporary use. + * allocate/deallocate are always called in a stack-like order - last pointer to be allocated is deallocated first. + * This function is not thread safe and must not be called concurrently with any other meshopt_ function. + * + * In shared library builds, allocations from templated index wrappers in this header will only be redirected if MESHOPTIMIZER_ALLOC_EXPORT is defined. + */ +MESHOPTIMIZER_API void meshopt_setAllocator(void* (MESHOPTIMIZER_ALLOC_CALLCONV* allocate)(size_t), void (MESHOPTIMIZER_ALLOC_CALLCONV* deallocate)(void*)); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +/* Quantization into fixed point normalized formats; these are only available as inline C++ functions */ +#ifdef __cplusplus +/** + * Quantize a float in [0..1] range into an N-bit fixed point unorm value + * Assumes reconstruction function (q / (2^N-1)), which is the case for fixed-function normalized fixed point conversion + * Maximum reconstruction error: 1/2^(N+1) + */ +inline int meshopt_quantizeUnorm(float v, int N); + +/** + * Quantize a float in [-1..1] range into an N-bit fixed point snorm value + * Assumes reconstruction function (q / (2^(N-1)-1)), which is the case for fixed-function normalized fixed point conversion (except early OpenGL versions) + * Maximum reconstruction error: 1/2^N + */ +inline int meshopt_quantizeSnorm(float v, int N); +#endif + +/** + * C++ template interface + * + * These functions mirror the C interface the library provides, providing template-based overloads so that + * the caller can use an arbitrary type for the index data, both for input and output. + * When the supplied type is the same size as that of unsigned int, the wrappers are zero-cost; when it's not, + * the wrappers end up allocating memory and copying index data to convert from one type to another. + */ +#if defined(__cplusplus) && !defined(MESHOPTIMIZER_NO_WRAPPERS) +template +inline size_t meshopt_generateVertexRemap(unsigned int* destination, const T* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size); +template +inline size_t meshopt_generateVertexRemapMulti(unsigned int* destination, const T* indices, size_t index_count, size_t vertex_count, const meshopt_Stream* streams, size_t stream_count); +template +inline size_t meshopt_generateVertexRemapCustom(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, F callback); +template +inline size_t meshopt_generateVertexRemapCustom(unsigned int* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, F callback); +template +inline void meshopt_remapIndexBuffer(T* destination, const T* indices, size_t index_count, const unsigned int* remap); +template +inline size_t meshopt_filterIndexBuffer(T* destination, const T* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size, size_t vertex_stride); +template +inline size_t meshopt_filterIndexBufferMulti(T* destination, const T* indices, size_t index_count, size_t vertex_count, const struct meshopt_Stream* streams, size_t stream_count); +template +inline void meshopt_generateShadowIndexBuffer(T* destination, const T* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size, size_t vertex_stride); +template +inline void meshopt_generateShadowIndexBufferMulti(T* destination, const T* indices, size_t index_count, size_t vertex_count, const meshopt_Stream* streams, size_t stream_count); +template +inline void meshopt_generateAdjacencyIndexBuffer(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride); +template +inline void meshopt_generateTessellationIndexBuffer(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride); +template +inline size_t meshopt_generateProvokingIndexBuffer(T* destination, unsigned int* reorder, const T* indices, size_t index_count, size_t vertex_count); +template +inline void meshopt_optimizeVertexCache(T* destination, const T* indices, size_t index_count, size_t vertex_count); +template +inline void meshopt_optimizeVertexCacheStrip(T* destination, const T* indices, size_t index_count, size_t vertex_count); +template +inline void meshopt_optimizeVertexCacheFifo(T* destination, const T* indices, size_t index_count, size_t vertex_count, unsigned int cache_size); +template +inline void meshopt_optimizeOverdraw(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float threshold); +template +inline size_t meshopt_optimizeVertexFetchRemap(unsigned int* destination, const T* indices, size_t index_count, size_t vertex_count); +template +inline size_t meshopt_optimizeVertexFetch(void* destination, T* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size); +template +inline size_t meshopt_encodeIndexBuffer(unsigned char* buffer, size_t buffer_size, const T* indices, size_t index_count); +template +inline int meshopt_decodeIndexBuffer(T* destination, size_t index_count, const unsigned char* buffer, size_t buffer_size); +template +inline size_t meshopt_encodeIndexSequence(unsigned char* buffer, size_t buffer_size, const T* indices, size_t index_count); +template +inline int meshopt_decodeIndexSequence(T* destination, size_t index_count, const unsigned char* buffer, size_t buffer_size); +template +inline int meshopt_decodeMeshlet(V* vertices, size_t vertex_count, T* triangles, size_t triangle_count, const unsigned char* buffer, size_t buffer_size); +inline size_t meshopt_encodeVertexBufferLevel(unsigned char* buffer, size_t buffer_size, const void* vertices, size_t vertex_count, size_t vertex_size, int level); +template +inline size_t meshopt_simplify(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t target_index_count, float target_error, unsigned int options = 0, float* result_error = NULL); +template +inline size_t meshopt_simplifyWithAttributes(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, const float* vertex_attributes, size_t vertex_attributes_stride, const float* attribute_weights, size_t attribute_count, const unsigned char* vertex_lock, size_t target_index_count, float target_error, unsigned int options = 0, float* result_error = NULL); +template +inline size_t meshopt_simplifyWithUpdate(T* indices, size_t index_count, float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float* vertex_attributes, size_t vertex_attributes_stride, const float* attribute_weights, size_t attribute_count, const unsigned char* vertex_lock, size_t target_index_count, float target_error, unsigned int options = 0, float* result_error = NULL); +template +inline size_t meshopt_simplifySloppy(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t target_index_count, float target_error, float* result_error = NULL); +template +inline size_t meshopt_simplifySloppy(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, const unsigned char* vertex_lock, size_t target_index_count, float target_error, float* result_error = NULL); +template +inline size_t meshopt_simplifyPrune(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float target_error); +template +inline size_t meshopt_stripify(T* destination, const T* indices, size_t index_count, size_t vertex_count, T restart_index); +template +inline size_t meshopt_unstripify(T* destination, const T* indices, size_t index_count, T restart_index); +template +inline meshopt_VertexCacheStatistics meshopt_analyzeVertexCache(const T* indices, size_t index_count, size_t vertex_count, unsigned int cache_size, unsigned int warp_size, unsigned int primgroup_size); +template +inline meshopt_VertexFetchStatistics meshopt_analyzeVertexFetch(const T* indices, size_t index_count, size_t vertex_count, size_t vertex_size); +template +inline meshopt_OverdrawStatistics meshopt_analyzeOverdraw(const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride); +template +inline meshopt_CoverageStatistics meshopt_analyzeCoverage(const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride); +template +inline size_t meshopt_buildMeshlets(meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t max_vertices, size_t max_triangles, float cone_weight); +template +inline size_t meshopt_buildMeshletsScan(meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const T* indices, size_t index_count, size_t vertex_count, size_t max_vertices, size_t max_triangles); +template +inline size_t meshopt_buildMeshletsFlex(meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t max_vertices, size_t min_triangles, size_t max_triangles, float cone_weight, float split_factor); +template +inline size_t meshopt_buildMeshletsSpatial(meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t max_vertices, size_t min_triangles, size_t max_triangles, float fill_weight); +template +inline meshopt_Bounds meshopt_computeClusterBounds(const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride); +template +inline size_t meshopt_partitionClusters(unsigned int* destination, const T* cluster_indices, size_t total_index_count, const unsigned int* cluster_index_counts, size_t cluster_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t target_partition_size); +template +inline void meshopt_spatialSortTriangles(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride); +template +inline void meshopt_generateTangents(float* result, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, const float* vertex_normals, size_t vertex_normals_stride, const float* vertex_uvs, size_t vertex_uvs_stride, unsigned int options = 0); +template +inline void meshopt_generateNormals(float* result, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float crease_angle, float smoothing = 0.f); +template +inline size_t meshopt_remesh(float* destination, size_t max_triangle_count, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, int resolution, unsigned int options = 0); +#endif + +/* Inline implementation */ +#ifdef __cplusplus +inline int meshopt_quantizeUnorm(float v, int N) +{ + const float scale = float((1 << N) - 1); + + v = (v >= 0) ? v : 0; + v = (v <= 1) ? v : 1; + + return int(v * scale + 0.5f); +} + +inline int meshopt_quantizeSnorm(float v, int N) +{ + const float scale = float((1 << (N - 1)) - 1); + + float round = (v >= 0 ? 0.5f : -0.5f); + + v = (v >= -1) ? v : -1; + v = (v <= +1) ? v : +1; + + return int(v * scale + round); +} +#endif + +/* Internal implementation helpers */ +#ifdef __cplusplus +class meshopt_Allocator +{ +public: + struct Storage + { + void* (MESHOPTIMIZER_ALLOC_CALLCONV* allocate)(size_t); + void (MESHOPTIMIZER_ALLOC_CALLCONV* deallocate)(void*); + }; + +#ifdef MESHOPTIMIZER_ALLOC_EXPORT + MESHOPTIMIZER_API static Storage& storage(); +#else + static Storage& storage() + { + static Storage s = {::operator new, ::operator delete }; + return s; + } +#endif + + meshopt_Allocator() + : blocks() + , count(0) + { + } + + ~meshopt_Allocator() + { + for (size_t i = count; i > 0; --i) + storage().deallocate(blocks[i - 1]); + } + + template + T* allocate(size_t size) + { + assert(count < sizeof(blocks) / sizeof(blocks[0])); + T* result = static_cast(storage().allocate(size > size_t(-1) / sizeof(T) ? size_t(-1) : size * sizeof(T))); + blocks[count++] = result; + return result; + } + + void deallocate(void* ptr) + { + assert(count > 0 && blocks[count - 1] == ptr); + storage().deallocate(ptr); + count--; + } + +private: + void* blocks[24]; + size_t count; +}; +#endif + +/* Inline implementation for C++ templated wrappers */ +#if defined(__cplusplus) && !defined(MESHOPTIMIZER_NO_WRAPPERS) +template +struct meshopt_IndexAdapter; + +template +struct meshopt_IndexAdapter +{ + T* result; + unsigned int* data; + size_t count; + + meshopt_IndexAdapter(T* result_, const T* input, size_t count_) + : result(result_) + , data(NULL) + , count(count_) + { + size_t size = count > size_t(-1) / sizeof(unsigned int) ? size_t(-1) : count * sizeof(unsigned int); + + data = static_cast(meshopt_Allocator::storage().allocate(size)); + + if (input) + { + for (size_t i = 0; i < count; ++i) + data[i] = input[i]; + } + } + + ~meshopt_IndexAdapter() + { + if (result) + { + for (size_t i = 0; i < count; ++i) + result[i] = T(data[i]); + } + + meshopt_Allocator::storage().deallocate(data); + } +}; + +template +struct meshopt_IndexAdapter +{ + unsigned int* data; + + meshopt_IndexAdapter(T* result, const T* input, size_t) + : data(reinterpret_cast(result ? result : const_cast(input))) + { + } +}; + +template +inline size_t meshopt_generateVertexRemap(unsigned int* destination, const T* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size) +{ + meshopt_IndexAdapter in(NULL, indices, indices ? index_count : 0); + + return meshopt_generateVertexRemap(destination, indices ? in.data : NULL, index_count, vertices, vertex_count, vertex_size); +} + +template +inline size_t meshopt_generateVertexRemapMulti(unsigned int* destination, const T* indices, size_t index_count, size_t vertex_count, const meshopt_Stream* streams, size_t stream_count) +{ + meshopt_IndexAdapter in(NULL, indices, indices ? index_count : 0); + + return meshopt_generateVertexRemapMulti(destination, indices ? in.data : NULL, index_count, vertex_count, streams, stream_count); +} + +template +inline size_t meshopt_generateVertexRemapCustom(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, F callback) +{ + struct Call + { + static int compare(void* context, unsigned int lhs, unsigned int rhs) { return (*static_cast(context))(lhs, rhs) ? 1 : 0; } + }; + + return meshopt_generateVertexRemapCustom(destination, indices, index_count, vertex_positions, vertex_count, vertex_positions_stride, &Call::compare, &callback); +} + +template +inline size_t meshopt_generateVertexRemapCustom(unsigned int* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, F callback) +{ + struct Call + { + static int compare(void* context, unsigned int lhs, unsigned int rhs) { return (*static_cast(context))(lhs, rhs) ? 1 : 0; } + }; + + meshopt_IndexAdapter in(NULL, indices, indices ? index_count : 0); + + return meshopt_generateVertexRemapCustom(destination, indices ? in.data : NULL, index_count, vertex_positions, vertex_count, vertex_positions_stride, &Call::compare, &callback); +} + +template +inline void meshopt_remapIndexBuffer(T* destination, const T* indices, size_t index_count, const unsigned int* remap) +{ + meshopt_IndexAdapter in(NULL, indices, indices ? index_count : 0); + meshopt_IndexAdapter out(destination, NULL, index_count); + + meshopt_remapIndexBuffer(out.data, indices ? in.data : NULL, index_count, remap); +} + +template +inline size_t meshopt_filterIndexBuffer(T* destination, const T* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size, size_t vertex_stride) +{ + meshopt_IndexAdapter in(NULL, indices, index_count); + meshopt_IndexAdapter out(destination, NULL, index_count); + + return meshopt_filterIndexBuffer(out.data, in.data, index_count, vertices, vertex_count, vertex_size, vertex_stride); +} + +template +inline size_t meshopt_filterIndexBufferMulti(T* destination, const T* indices, size_t index_count, size_t vertex_count, const struct meshopt_Stream* streams, size_t stream_count) +{ + meshopt_IndexAdapter in(NULL, indices, index_count); + meshopt_IndexAdapter out(destination, NULL, index_count); + + return meshopt_filterIndexBufferMulti(out.data, in.data, index_count, vertex_count, streams, stream_count); +} + +template +inline void meshopt_generateShadowIndexBuffer(T* destination, const T* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size, size_t vertex_stride) +{ + meshopt_IndexAdapter in(NULL, indices, index_count); + meshopt_IndexAdapter out(destination, NULL, index_count); + + meshopt_generateShadowIndexBuffer(out.data, in.data, index_count, vertices, vertex_count, vertex_size, vertex_stride); +} + +template +inline void meshopt_generateShadowIndexBufferMulti(T* destination, const T* indices, size_t index_count, size_t vertex_count, const meshopt_Stream* streams, size_t stream_count) +{ + meshopt_IndexAdapter in(NULL, indices, index_count); + meshopt_IndexAdapter out(destination, NULL, index_count); + + meshopt_generateShadowIndexBufferMulti(out.data, in.data, index_count, vertex_count, streams, stream_count); +} + +template +inline void meshopt_generateAdjacencyIndexBuffer(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride) +{ + meshopt_IndexAdapter in(NULL, indices, index_count); + meshopt_IndexAdapter out(destination, NULL, index_count * 2); + + meshopt_generateAdjacencyIndexBuffer(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride); +} + +template +inline void meshopt_generateTessellationIndexBuffer(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride) +{ + meshopt_IndexAdapter in(NULL, indices, index_count); + meshopt_IndexAdapter out(destination, NULL, index_count * 4); + + meshopt_generateTessellationIndexBuffer(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride); +} + +template +inline size_t meshopt_generateProvokingIndexBuffer(T* destination, unsigned int* reorder, const T* indices, size_t index_count, size_t vertex_count) +{ + meshopt_IndexAdapter in(NULL, indices, index_count); + meshopt_IndexAdapter out(destination, NULL, index_count); + + size_t bound = vertex_count + (index_count / 3); + assert(bound == 0 || size_t(T(bound - 1)) == bound - 1); // bound - 1 must fit in T + (void)bound; + + return meshopt_generateProvokingIndexBuffer(out.data, reorder, in.data, index_count, vertex_count); +} + +template +inline void meshopt_optimizeVertexCache(T* destination, const T* indices, size_t index_count, size_t vertex_count) +{ + meshopt_IndexAdapter in(NULL, indices, index_count); + meshopt_IndexAdapter out(destination, NULL, index_count); + + meshopt_optimizeVertexCache(out.data, in.data, index_count, vertex_count); +} + +template +inline void meshopt_optimizeVertexCacheStrip(T* destination, const T* indices, size_t index_count, size_t vertex_count) +{ + meshopt_IndexAdapter in(NULL, indices, index_count); + meshopt_IndexAdapter out(destination, NULL, index_count); + + meshopt_optimizeVertexCacheStrip(out.data, in.data, index_count, vertex_count); +} + +template +inline void meshopt_optimizeVertexCacheFifo(T* destination, const T* indices, size_t index_count, size_t vertex_count, unsigned int cache_size) +{ + meshopt_IndexAdapter in(NULL, indices, index_count); + meshopt_IndexAdapter out(destination, NULL, index_count); + + meshopt_optimizeVertexCacheFifo(out.data, in.data, index_count, vertex_count, cache_size); +} + +template +inline void meshopt_optimizeOverdraw(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float threshold) +{ + meshopt_IndexAdapter in(NULL, indices, index_count); + meshopt_IndexAdapter out(destination, NULL, index_count); + + meshopt_optimizeOverdraw(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, threshold); +} + +template +inline size_t meshopt_optimizeVertexFetchRemap(unsigned int* destination, const T* indices, size_t index_count, size_t vertex_count) +{ + meshopt_IndexAdapter in(NULL, indices, index_count); + + return meshopt_optimizeVertexFetchRemap(destination, in.data, index_count, vertex_count); +} + +template +inline size_t meshopt_optimizeVertexFetch(void* destination, T* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size) +{ + meshopt_IndexAdapter inout(indices, indices, index_count); + + return meshopt_optimizeVertexFetch(destination, inout.data, index_count, vertices, vertex_count, vertex_size); +} + +template +inline size_t meshopt_encodeIndexBuffer(unsigned char* buffer, size_t buffer_size, const T* indices, size_t index_count) +{ + meshopt_IndexAdapter in(NULL, indices, index_count); + + return meshopt_encodeIndexBuffer(buffer, buffer_size, in.data, index_count); +} + +template +inline int meshopt_decodeIndexBuffer(T* destination, size_t index_count, const unsigned char* buffer, size_t buffer_size) +{ + char index_size_valid[sizeof(T) == 2 || sizeof(T) == 4 ? 1 : -1]; + (void)index_size_valid; + + return meshopt_decodeIndexBuffer(destination, index_count, sizeof(T), buffer, buffer_size); +} + +template +inline size_t meshopt_encodeIndexSequence(unsigned char* buffer, size_t buffer_size, const T* indices, size_t index_count) +{ + meshopt_IndexAdapter in(NULL, indices, index_count); + + return meshopt_encodeIndexSequence(buffer, buffer_size, in.data, index_count); +} + +template +inline int meshopt_decodeIndexSequence(T* destination, size_t index_count, const unsigned char* buffer, size_t buffer_size) +{ + char index_size_valid[sizeof(T) == 2 || sizeof(T) == 4 ? 1 : -1]; + (void)index_size_valid; + + return meshopt_decodeIndexSequence(destination, index_count, sizeof(T), buffer, buffer_size); +} + +template +inline int meshopt_decodeMeshlet(V* vertices, size_t vertex_count, T* triangles, size_t triangle_count, const unsigned char* buffer, size_t buffer_size) +{ + char types_valid[(sizeof(V) == 2 || sizeof(V) == 4) && (sizeof(T) == 1 || sizeof(T) == 4) ? 1 : -1]; + (void)types_valid; + + return meshopt_decodeMeshlet(vertices, vertex_count, sizeof(V), triangles, triangle_count, sizeof(T) == 1 ? 3 : 4, buffer, buffer_size); +} + +inline size_t meshopt_encodeVertexBufferLevel(unsigned char* buffer, size_t buffer_size, const void* vertices, size_t vertex_count, size_t vertex_size, int level) +{ + return meshopt_encodeVertexBufferLevel(buffer, buffer_size, vertices, vertex_count, vertex_size, level, -1); +} + +template +inline size_t meshopt_simplify(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t target_index_count, float target_error, unsigned int options, float* result_error) +{ + meshopt_IndexAdapter in(NULL, indices, index_count); + meshopt_IndexAdapter out(destination, NULL, index_count); + + return meshopt_simplify(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, target_index_count, target_error, options, result_error); +} + +template +inline size_t meshopt_simplifyWithAttributes(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, const float* vertex_attributes, size_t vertex_attributes_stride, const float* attribute_weights, size_t attribute_count, const unsigned char* vertex_lock, size_t target_index_count, float target_error, unsigned int options, float* result_error) +{ + meshopt_IndexAdapter in(NULL, indices, index_count); + meshopt_IndexAdapter out(destination, NULL, index_count); + + return meshopt_simplifyWithAttributes(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, vertex_attributes, vertex_attributes_stride, attribute_weights, attribute_count, vertex_lock, target_index_count, target_error, options, result_error); +} + +template +inline size_t meshopt_simplifyWithUpdate(T* indices, size_t index_count, float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float* vertex_attributes, size_t vertex_attributes_stride, const float* attribute_weights, size_t attribute_count, const unsigned char* vertex_lock, size_t target_index_count, float target_error, unsigned int options, float* result_error) +{ + meshopt_IndexAdapter inout(indices, indices, index_count); + + return meshopt_simplifyWithUpdate(inout.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, vertex_attributes, vertex_attributes_stride, attribute_weights, attribute_count, vertex_lock, target_index_count, target_error, options, result_error); +} + +template +inline size_t meshopt_simplifySloppy(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t target_index_count, float target_error, float* result_error) +{ + meshopt_IndexAdapter in(NULL, indices, index_count); + meshopt_IndexAdapter out(destination, NULL, index_count); + + return meshopt_simplifySloppy(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, NULL, target_index_count, target_error, result_error); +} + +template +inline size_t meshopt_simplifySloppy(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, const unsigned char* vertex_lock, size_t target_index_count, float target_error, float* result_error) +{ + meshopt_IndexAdapter in(NULL, indices, index_count); + meshopt_IndexAdapter out(destination, NULL, index_count); + + return meshopt_simplifySloppy(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, vertex_lock, target_index_count, target_error, result_error); +} + +template +inline size_t meshopt_simplifyPrune(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float target_error) +{ + meshopt_IndexAdapter in(NULL, indices, index_count); + meshopt_IndexAdapter out(destination, NULL, index_count); + + return meshopt_simplifyPrune(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, target_error); +} + +template +inline size_t meshopt_stripify(T* destination, const T* indices, size_t index_count, size_t vertex_count, T restart_index) +{ + meshopt_IndexAdapter in(NULL, indices, index_count); + meshopt_IndexAdapter out(destination, NULL, (index_count / 3) * 5); + + return meshopt_stripify(out.data, in.data, index_count, vertex_count, unsigned(restart_index)); +} + +template +inline size_t meshopt_unstripify(T* destination, const T* indices, size_t index_count, T restart_index) +{ + meshopt_IndexAdapter in(NULL, indices, index_count); + meshopt_IndexAdapter out(destination, NULL, index_count == 0 ? 0 : (index_count - 2) * 3); + + return meshopt_unstripify(out.data, in.data, index_count, unsigned(restart_index)); +} + +template +inline meshopt_VertexCacheStatistics meshopt_analyzeVertexCache(const T* indices, size_t index_count, size_t vertex_count, unsigned int cache_size, unsigned int warp_size, unsigned int primgroup_size) +{ + meshopt_IndexAdapter in(NULL, indices, index_count); + + return meshopt_analyzeVertexCache(in.data, index_count, vertex_count, cache_size, warp_size, primgroup_size); +} + +template +inline meshopt_VertexFetchStatistics meshopt_analyzeVertexFetch(const T* indices, size_t index_count, size_t vertex_count, size_t vertex_size) +{ + meshopt_IndexAdapter in(NULL, indices, index_count); + + return meshopt_analyzeVertexFetch(in.data, index_count, vertex_count, vertex_size); +} + +template +inline meshopt_OverdrawStatistics meshopt_analyzeOverdraw(const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride) +{ + meshopt_IndexAdapter in(NULL, indices, index_count); + + return meshopt_analyzeOverdraw(in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride); +} + +template +inline meshopt_CoverageStatistics meshopt_analyzeCoverage(const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride) +{ + meshopt_IndexAdapter in(NULL, indices, index_count); + + return meshopt_analyzeCoverage(in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride); +} + +template +inline size_t meshopt_buildMeshlets(meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t max_vertices, size_t max_triangles, float cone_weight) +{ + meshopt_IndexAdapter in(NULL, indices, index_count); + + return meshopt_buildMeshlets(meshlets, meshlet_vertices, meshlet_triangles, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, max_vertices, max_triangles, cone_weight); +} + +template +inline size_t meshopt_buildMeshletsScan(meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const T* indices, size_t index_count, size_t vertex_count, size_t max_vertices, size_t max_triangles) +{ + meshopt_IndexAdapter in(NULL, indices, index_count); + + return meshopt_buildMeshletsScan(meshlets, meshlet_vertices, meshlet_triangles, in.data, index_count, vertex_count, max_vertices, max_triangles); +} + +template +inline size_t meshopt_buildMeshletsFlex(meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t max_vertices, size_t min_triangles, size_t max_triangles, float cone_weight, float split_factor) +{ + meshopt_IndexAdapter in(NULL, indices, index_count); + + return meshopt_buildMeshletsFlex(meshlets, meshlet_vertices, meshlet_triangles, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, max_vertices, min_triangles, max_triangles, cone_weight, split_factor); +} + +template +inline size_t meshopt_buildMeshletsSpatial(meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t max_vertices, size_t min_triangles, size_t max_triangles, float fill_weight) +{ + meshopt_IndexAdapter in(NULL, indices, index_count); + + return meshopt_buildMeshletsSpatial(meshlets, meshlet_vertices, meshlet_triangles, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, max_vertices, min_triangles, max_triangles, fill_weight); +} + +template +inline meshopt_Bounds meshopt_computeClusterBounds(const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride) +{ + meshopt_IndexAdapter in(NULL, indices, index_count); + + return meshopt_computeClusterBounds(in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride); +} + +template +inline size_t meshopt_partitionClusters(unsigned int* destination, const T* cluster_indices, size_t total_index_count, const unsigned int* cluster_index_counts, size_t cluster_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t target_partition_size) +{ + meshopt_IndexAdapter in(NULL, cluster_indices, total_index_count); + + return meshopt_partitionClusters(destination, in.data, total_index_count, cluster_index_counts, cluster_count, vertex_positions, vertex_count, vertex_positions_stride, target_partition_size); +} + +template +inline void meshopt_spatialSortTriangles(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride) +{ + meshopt_IndexAdapter in(NULL, indices, index_count); + meshopt_IndexAdapter out(destination, NULL, index_count); + + meshopt_spatialSortTriangles(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride); +} + +template +inline void meshopt_generateTangents(float* result, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, const float* vertex_normals, size_t vertex_normals_stride, const float* vertex_uvs, size_t vertex_uvs_stride, unsigned int options) +{ + meshopt_IndexAdapter in(NULL, indices, indices ? index_count : 0); + + meshopt_generateTangents(result, indices ? in.data : NULL, index_count, vertex_positions, vertex_count, vertex_positions_stride, vertex_normals, vertex_normals_stride, vertex_uvs, vertex_uvs_stride, options); +} + +template +inline void meshopt_generateNormals(float* result, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float crease_angle, float smoothing) +{ + meshopt_IndexAdapter in(NULL, indices, indices ? index_count : 0); + + meshopt_generateNormals(result, indices ? in.data : NULL, index_count, vertex_positions, vertex_count, vertex_positions_stride, crease_angle, smoothing); +} + +template +inline size_t meshopt_remesh(float* destination, size_t max_triangle_count, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, int resolution, unsigned int options) +{ + meshopt_IndexAdapter in(NULL, indices, index_count); + + return meshopt_remesh(destination, max_triangle_count, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, resolution, options); +} +#endif + +/** + * Copyright (c) 2016-2026 Arseny Kapoulkine + * + * 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/Code/BF2/External/meshoptimizer/stripifier.cpp b/Code/BF2/External/meshoptimizer/stripifier.cpp new file mode 100644 index 000000000..4043195ae --- /dev/null +++ b/Code/BF2/External/meshoptimizer/stripifier.cpp @@ -0,0 +1,296 @@ +// This file is part of meshoptimizer library; see meshoptimizer.h for version/license details +#include "meshoptimizer.h" + +#include +#include +#include + +// This work is based on: +// Francine Evans, Steven Skiena and Amitabh Varshney. Optimizing Triangle Strips for Fast Rendering. 1996 +namespace meshopt +{ + +static unsigned int findStripFirst(const unsigned int buffer[][3], unsigned int buffer_size, const unsigned char* valence) +{ + unsigned int index = 0; + unsigned int iv = ~0u; + + for (size_t i = 0; i < buffer_size; ++i) + { + unsigned char va = valence[buffer[i][0]], vb = valence[buffer[i][1]], vc = valence[buffer[i][2]]; + unsigned int v = (va < vb && va < vc) ? va : (vb < vc ? vb : vc); + + if (v < iv) + { + index = unsigned(i); + iv = v; + } + } + + return index; +} + +static int findStripNext(const unsigned int buffer[][3], unsigned int buffer_size, unsigned int e0, unsigned int e1) +{ + for (size_t i = 0; i < buffer_size; ++i) + { + unsigned int a = buffer[i][0], b = buffer[i][1], c = buffer[i][2]; + + if (e0 == a && e1 == b) + return (int(i) << 2) | 2; + else if (e0 == b && e1 == c) + return (int(i) << 2) | 0; + else if (e0 == c && e1 == a) + return (int(i) << 2) | 1; + } + + return -1; +} + +} // namespace meshopt + +size_t meshopt_stripify(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count, unsigned int restart_index) +{ + assert(destination != indices); + assert(index_count % 3 == 0); + + using namespace meshopt; + + meshopt_Allocator allocator; + + const size_t buffer_capacity = 8; + + unsigned int buffer[buffer_capacity][3] = {}; + unsigned int buffer_size = 0; + + size_t index_offset = 0; + + unsigned int strip[2] = {}; + unsigned int parity = 0; + + size_t strip_size = 0; + + // compute vertex valence; this is used to prioritize starting triangle for strips + // note: we use 8-bit counters for performance; for outlier vertices the valence is incorrect but that just affects the heuristic + unsigned char* valence = allocator.allocate(vertex_count); + memset(valence, 0, vertex_count); + + for (size_t i = 0; i < index_count; ++i) + { + unsigned int index = indices[i]; + assert(index < vertex_count); + + valence[index]++; + } + + int next = -1; + + while (buffer_size > 0 || index_offset < index_count) + { + assert(next < 0 || (size_t(next >> 2) < buffer_size && (next & 3) < 3)); + + // fill triangle buffer + while (buffer_size < buffer_capacity && index_offset < index_count) + { + buffer[buffer_size][0] = indices[index_offset + 0]; + buffer[buffer_size][1] = indices[index_offset + 1]; + buffer[buffer_size][2] = indices[index_offset + 2]; + + buffer_size++; + index_offset += 3; + } + + assert(buffer_size > 0); + + if (next >= 0) + { + unsigned int i = next >> 2; + unsigned int a = buffer[i][0], b = buffer[i][1], c = buffer[i][2]; + unsigned int v = buffer[i][next & 3]; + + // ordered removal from the buffer + memmove(buffer[i], buffer[i + 1], (buffer_size - i - 1) * sizeof(buffer[0])); + buffer_size--; + + // update vertex valences for strip start heuristic + valence[a]--; + valence[b]--; + valence[c]--; + + // find next triangle (note that edge order flips on every iteration) + // in some cases we need to perform a swap to pick a different outgoing triangle edge + // for [a b c], the default strip edge is [b c], but we might want to use [a c] + int cont = findStripNext(buffer, buffer_size, parity ? strip[1] : v, parity ? v : strip[1]); + int swap = cont < 0 ? findStripNext(buffer, buffer_size, parity ? v : strip[0], parity ? strip[0] : v) : -1; + + if (cont < 0 && swap >= 0) + { + // [a b c] => [a b a c] + destination[strip_size++] = strip[0]; + destination[strip_size++] = v; + + // next strip has same winding + // ? a b => b a v + strip[1] = v; + + next = swap; + } + else + { + // emit the next vertex in the strip + destination[strip_size++] = v; + + // next strip has flipped winding + strip[0] = strip[1]; + strip[1] = v; + parity ^= 1; + + next = cont; + } + } + else + { + // if we didn't find anything, we need to find the next new triangle + // we use a heuristic to maximize the strip length + unsigned int i = findStripFirst(buffer, buffer_size, valence); + unsigned int a = buffer[i][0], b = buffer[i][1], c = buffer[i][2]; + + // ordered removal from the buffer + memmove(buffer[i], buffer[i + 1], (buffer_size - i - 1) * sizeof(buffer[0])); + buffer_size--; + + // update vertex valences for strip start heuristic + valence[a]--; + valence[b]--; + valence[c]--; + + // we need to pre-rotate the triangle so that we will find a match in the existing buffer on the next iteration + int ea = findStripNext(buffer, buffer_size, c, b); + int eb = findStripNext(buffer, buffer_size, a, c); + int ec = findStripNext(buffer, buffer_size, b, a); + + // in some cases we can have several matching edges; since we can pick any edge, we pick the one with the smallest + // triangle index in the buffer. this reduces the effect of stripification on ACMR and additionally - for unclear + // reasons - slightly improves the stripification efficiency + int mine = INT_MAX; + mine = (ea >= 0 && mine > ea) ? ea : mine; + mine = (eb >= 0 && mine > eb) ? eb : mine; + mine = (ec >= 0 && mine > ec) ? ec : mine; + + if (ea == mine) + { + // keep abc + next = ea; + } + else if (eb == mine) + { + // abc -> bca + unsigned int t = a; + a = b, b = c, c = t; + + next = eb; + } + else if (ec == mine) + { + // abc -> cab + unsigned int t = c; + c = b, b = a, a = t; + + next = ec; + } + + if (restart_index) + { + if (strip_size) + destination[strip_size++] = restart_index; + + destination[strip_size++] = a; + destination[strip_size++] = b; + destination[strip_size++] = c; + + // new strip always starts with the same edge winding + strip[0] = b; + strip[1] = c; + parity = 1; + } + else + { + if (strip_size) + { + // connect last strip using degenerate triangles + destination[strip_size++] = strip[1]; + destination[strip_size++] = a; + } + + // note that we may need to flip the emitted triangle based on parity + // we always end up with outgoing edge "cb" in the end + unsigned int e0 = parity ? c : b; + unsigned int e1 = parity ? b : c; + + destination[strip_size++] = a; + destination[strip_size++] = e0; + destination[strip_size++] = e1; + + strip[0] = e0; + strip[1] = e1; + parity ^= 1; + } + } + } + + return strip_size; +} + +size_t meshopt_stripifyBound(size_t index_count) +{ + assert(index_count % 3 == 0); + + // worst case without restarts is 2 degenerate indices and 3 indices per triangle + // worst case with restarts is 1 restart index and 3 indices per triangle + return (index_count / 3) * 5; +} + +size_t meshopt_unstripify(unsigned int* destination, const unsigned int* indices, size_t index_count, unsigned int restart_index) +{ + assert(destination != indices); + + size_t offset = 0; + size_t start = 0; + + for (size_t i = 0; i < index_count; ++i) + { + if (restart_index && indices[i] == restart_index) + { + start = i + 1; + } + else if (i - start >= 2) + { + unsigned int a = indices[i - 2], b = indices[i - 1], c = indices[i]; + + // flip winding for odd triangles + if ((i - start) & 1) + { + unsigned int t = a; + a = b, b = t; + } + + // although we use restart indices, strip swaps still produce degenerate triangles, so skip them + if (a != b && a != c && b != c) + { + destination[offset + 0] = a; + destination[offset + 1] = b; + destination[offset + 2] = c; + offset += 3; + } + } + } + + return offset; +} + +size_t meshopt_unstripifyBound(size_t index_count) +{ + assert(index_count == 0 || index_count >= 3); + + return (index_count == 0) ? 0 : (index_count - 2) * 3; +} diff --git a/Code/BF2/External/python-embedded/linux/CMakeLists.txt b/Code/BF2/External/python-embedded/linux/CMakeLists.txt index 85cc6b212..dfa5812e1 100644 --- a/Code/BF2/External/python-embedded/linux/CMakeLists.txt +++ b/Code/BF2/External/python-embedded/linux/CMakeLists.txt @@ -28,18 +28,34 @@ if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR) project(dice_py LANGUAGES C CXX) endif() -if(NOT CMAKE_SYSTEM_NAME STREQUAL "Linux") +# [CHOSEN, not recovered] The same description also builds libdice_py.dylib for the macOS port. +# Only the configure output differs: ../macos/pyconfig.h is the vendored configure's answer on +# Darwin (see ../macos/README.md); config.c, the source list and every flag are shared. +if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + set(DICE_PY_MACOS OFF) + set(DICE_PY_PYCONFIG_DIR "${CMAKE_CURRENT_SOURCE_DIR}") + if(NOT CMAKE_SIZEOF_VOID_P EQUAL 8 OR NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64)$") + message(FATAL_ERROR + "dice_py/linux: pyconfig.h here is configure's output for Linux x86-64 (LP64, " + "little-endian, 16-byte fpos_t); this is ${CMAKE_SYSTEM_PROCESSOR} with " + "${CMAKE_SIZEOF_VOID_P}-byte pointers. Regenerate pyconfig.h for the platform first - " + "README.md says how.") + endif() +elseif(CMAKE_SYSTEM_NAME STREQUAL "Darwin") + set(DICE_PY_MACOS ON) + get_filename_component(DICE_PY_PYCONFIG_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../macos" ABSOLUTE) + # The Darwin pyconfig.h holds for both x86_64 and arm64 (LP64, little-endian, same libSystem + # sizes); see ../macos/README.md. [CHOSEN, not recovered] Universal builds use the + # compiler's per-slice architecture macros for the va_list override, not the CMake host. + if(NOT CMAKE_SIZEOF_VOID_P EQUAL 8) + message(FATAL_ERROR "dice_py/macos: only 64-bit macOS is supported.") + endif() +else() message(FATAL_ERROR - "dice_py/linux: this directory builds libdice_py.so for Linux only (this is " - "${CMAKE_SYSTEM_NAME}). The Windows dice_py.dll is built by " + "dice_py/linux: this directory builds libdice_py.so for Linux and libdice_py.dylib for " + "macOS only (this is ${CMAKE_SYSTEM_NAME}). The Windows dice_py.dll is built by " "Code/Build/python/build_python.cmd.") endif() -if(NOT CMAKE_SIZEOF_VOID_P EQUAL 8 OR NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64)$") - message(FATAL_ERROR - "dice_py/linux: pyconfig.h here is configure's output for Linux x86-64 (LP64, little-endian, " - "16-byte fpos_t); this is ${CMAKE_SYSTEM_PROCESSOR} with ${CMAKE_SIZEOF_VOID_P}-byte " - "pointers. Regenerate pyconfig.h for the platform first - README.md says how.") -endif() # Where libdice_py.so and dice_py_check land. The root project points this at the `bf2` directory. if(NOT DEFINED BF2_DICE_PY_OUTPUT_DIR) @@ -163,7 +179,7 @@ set_target_properties(dice_py PROPERTIES ) target_include_directories(dice_py PUBLIC - "${CMAKE_CURRENT_SOURCE_DIR}" # pyconfig.h (configure's output, see README.md) + "${DICE_PY_PYCONFIG_DIR}" # pyconfig.h (configure's output, see README.md) "${DICE_PY_SRC}/Include" PRIVATE "${DICE_PY_ZLIB}" # zlib.h for Modules/zlibmodule.c @@ -211,11 +227,24 @@ endforeach() # build never is. PYTHONPATH/PLATFORM say linux2 where this kernel's configure says linux6: # [CHOSEN, not recovered] sys.platform is the retail-era value, the only one 2004 scripts could # have tested; see README.md. +# [CHOSEN, not recovered] macOS keeps "linux2" too: the game's Python scripts were only ever run +# on win32 and linux2, so reporting the retail Linux value keeps their platform tests on the +# path the retail Linux server took. See ../macos/README.md. set_source_files_properties("${DICE_PY_SRC}/Modules/getpath.c" PROPERTIES COMPILE_DEFINITIONS "PREFIX=\"/usr/local\";EXEC_PREFIX=\"/usr/local\";VERSION=\"2.3\";VPATH=\"\";PYTHONPATH=\":plat-linux2:lib-tk\"") set_source_files_properties("${DICE_PY_SRC}/Python/getplatform.c" PROPERTIES COMPILE_DEFINITIONS "PLATFORM=\"linux2\"") +# [CHOSEN, not recovered] macOS: Modules/_localemodule.c's __APPLE__ branch includes Mac/Include's +# macglue.h and calls PyMac_getscript from Python/mactoolboxglue.c, the Carbon toolbox glue that +# upstream links only into a framework build. That glue is not part of this build, so the unit is +# compiled as the generic POSIX module it is on Linux: setlocale/localeconv/nl_langinfo, and no +# _getdefaultlocale (locale.py then reads the LANG/LC_* environment, as on the Linux server). +if(DICE_PY_MACOS) + set_property(SOURCE "${DICE_PY_SRC}/Modules/_localemodule.c" APPEND PROPERTY COMPILE_OPTIONS + "-U__APPLE__") +endif() + # System libraries: libm (mathmodule, timemodule), libdl (dynload_shlib), pthreads (thread.c) and, # where glibc still ships it separately (before 2.34), libutil for posixmodule's openpty/forkpty. set(THREADS_PREFER_PTHREAD_FLAG ON) @@ -229,7 +258,10 @@ if(NOT DICE_PY_OPENPTY_IN_LIBC) endif() # A shared object links even with unresolved symbols; refuse that, so a missing system library or # a module compiled without its dependency fails HERE rather than when `bf2` first dlopens it. -target_link_options(dice_py PRIVATE -Wl,--no-undefined) +# ld64 (macOS) already rejects undefined symbols in a dylib by default and has no --no-undefined. +if(NOT DICE_PY_MACOS) + target_link_options(dice_py PRIVATE -Wl,--no-undefined) +endif() # ------------------------------------------------------------------------------------------------- # The runtime check: the same pycheck.cpp the Windows build runs, linked against libdice_py.so and @@ -239,10 +271,15 @@ add_executable(dice_py_check "${DICE_PY_CHECK_SOURCE}") target_link_libraries(dice_py_check PRIVATE dice_py) target_compile_definitions(dice_py_check PRIVATE DEDICATED=1) target_compile_options(dice_py_check PRIVATE "-include${DICE_PY_BUILDCONFIG_H}") +if(DICE_PY_MACOS) + set(DICE_PY_RPATH "@loader_path") # the Mach-O spelling of $ORIGIN +else() + set(DICE_PY_RPATH "\$ORIGIN") +endif() set_target_properties(dice_py_check PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${BF2_DICE_PY_OUTPUT_DIR}" - BUILD_RPATH "\$ORIGIN" - INSTALL_RPATH "\$ORIGIN" + BUILD_RPATH "${DICE_PY_RPATH}" + INSTALL_RPATH "${DICE_PY_RPATH}" BUILD_WITH_INSTALL_RPATH TRUE CXX_STANDARD 14 # the engine's standard; Python.h is consumed from C++14 CXX_STANDARD_REQUIRED ON diff --git a/Code/BF2/External/python-embedded/linux/README.md b/Code/BF2/External/python-embedded/linux/README.md index dd0bbd4f6..3fbfa6030 100644 --- a/Code/BF2/External/python-embedded/linux/README.md +++ b/Code/BF2/External/python-embedded/linux/README.md @@ -2,7 +2,8 @@ This directory builds CPython 2.3.4 and the vendored zlib 1.2.3 as `libdice_py.so` for Linux x86-64. It supports a standalone interpreter check and -the root engine build. See the public +the root engine build. The same description builds `libdice_py.dylib` for the +macOS port with the Darwin `pyconfig.h` from [../macos](../macos/README.md). See the public [build guide](../../../../../docs/building.md#linux-and-wsl) for the engine targets. ## Build and check @@ -85,3 +86,8 @@ upstream release. Keep the [upstream Python license](../py-src-2.3.4/LICENSE) and source notices with the interpreter. + +[CHOSEN, not recovered] The owner-requested macOS N1 fix bounds +`Modules/socketmodule.c:socket_inet_ntop`'s POSIX buffer initialization to +`sizeof(ip)`, removing the one-byte stack overwrite from `sizeof(ip) + 1`. +The Windows branch stays unchanged. Preserve this correction on source updates. diff --git a/Code/BF2/External/python-embedded/macos/README.md b/Code/BF2/External/python-embedded/macos/README.md new file mode 100644 index 000000000..5f219dd0f --- /dev/null +++ b/Code/BF2/External/python-embedded/macos/README.md @@ -0,0 +1,65 @@ +# macOS embedded Python + +This directory holds the Darwin `pyconfig.h` for `libdice_py.dylib`, the embedded +CPython 2.3.4 of the macOS dedicated-server port. The port is an intentional, +owner-requested platform change, `[CHOSEN, not recovered]`: there was no retail +macOS server. The build description itself is shared with Linux and lives in +[../linux/CMakeLists.txt](../linux/CMakeLists.txt); it selects this directory's +`pyconfig.h` when CMake runs on Darwin. See +[docs/macos-port.md](../../../../../docs/macos-port.md) for the port as a whole. + +## Build and check + +From the repository root, the root project builds the library beside `bf2`: + +```sh +cmake --preset macos-x64 +cmake --build out/build/macos-x64 --target dice_py dice_py_check_run +``` + +For both slices, use `cmake --preset macos-universal` and build +`out/build/macos-universal` instead. This `[CHOSEN, not recovered]` preset passes +`CMAKE_OSX_ARCHITECTURES="arm64;x86_64"`. The `VA_LIST_IS_ARRAY` override is selected +by compiler architecture macros separately for each slice; it does not depend on +the configure host. Native arm64 execution still requires the owner's M2 run. + +Standalone, as on Linux: + +```sh +cmake -S Code/BF2/External/python-embedded/linux -B out/build/dice_py-macos \ + -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCMAKE_OSX_SYSROOT=macosx +cmake --build out/build/dice_py-macos --target dice_py_check_run +``` + +The library's install name is `@rpath/libdice_py.dylib`; `bf2` and `dice_py_check` +carry an `@loader_path` runtime search path, the Mach-O equivalent of `$ORIGIN`. + +## Differences from the Linux build + +| Item | macOS | Reason | +| --- | --- | --- | +| `pyconfig.h` | Vendored configure output for Darwin x86_64, plus two marked overrides | See the provenance block at the top of `pyconfig.h`. | +| `HAVE_BROKEN_POSIX_SEMAPHORES` | Defined by hand | Darwin defines `_POSIX_SEMAPHORES` as `-1` and `sem_init` fails with `ENOSYS`; the 2.3 thread module would otherwise build every lock on it. | +| `VA_LIST_IS_ARRAY` | Undefined on arm64 only | arm64 Darwin's `va_list` is a pointer. Untested: the reference machine is x86_64. | +| `Modules/_localemodule.c` | Compiled with `-U__APPLE__` | Its Apple branch needs `macglue.h` and the Carbon toolbox glue from a framework build. Without it the module is the generic POSIX one used on Linux. | +| `sys.platform` | `linux2`, as on Linux | The game's scripts were written for `win32` and `linux2`; keeping the Linux value keeps them on the retail Linux server's paths. | +| `--no-undefined` | Not passed | `ld64` already rejects undefined symbols in a dylib. | +| SDK sysroot | `CMAKE_OSX_SYSROOT=macosx` in the preset | Apple clang otherwise searches `/usr/local/include` (Homebrew) first; configure was run with the same sysroot. | + +`dice_py_check_run` passes on macOS 15.7 x86_64: initialization, 64-bit pointer +round trip, 40 builtin modules, zlib and loopback UDP. Prefix-search warnings appear +as on Linux, because the engine sets `sys.path` itself. + +## POSIX publication (S2.10) + +[CHOSEN, not recovered] `Python/ceval.c` uses C11 atomics for pending-call queue indices, +the work flag and its producer try-lock. A failed try-lock returns the existing refusal (-1), +including in a nested signal handler. Sequential consistency publishes the queue entries +before the consumer reads them and retires an entry before a producer reuses it. +Every POSIX `_Py_Ticker` access in `ceval.c` and `Objects/longobject.c` uses `__atomic`; +its exported scalar declaration stays intact. `Objects/obmalloc.c` publishes the arena +vector before its count using C11 atomics; old vectors remain deliberately retained as +upstream requires. These changes apply on Linux too. Windows branches remain unchanged. + +The focused check in `Code/Tests/s2_10_threads` drives four concurrent producers and +40,000 callbacks against the real library. diff --git a/Code/BF2/External/python-embedded/macos/pyconfig.h b/Code/BF2/External/python-embedded/macos/pyconfig.h new file mode 100644 index 000000000..5cd00489d --- /dev/null +++ b/Code/BF2/External/python-embedded/macos/pyconfig.h @@ -0,0 +1,974 @@ +/* ================================================================================================= + * BF2Rebuilt: pyconfig.h for libdice_py.dylib - the macOS build of the embedded CPython 2.3.4. + * [CHOSEN, not recovered]: there was no retail macOS server; this file serves the macOS port. + * + * PROVENANCE. Everything between this comment block and the "macOS overrides" block at the end of + * the file is the VERBATIM output of the vendored py-src-2.3.4/configure (GNU Autoconf 2.57), run in a scratch + * copy of py-src-2.3.4 on macOS 15.7.7 (Darwin 24.6.0, x86_64) with Apple clang 17.0.0 (Command + * Line Tools) on 2026-10-21 as + * + * CC="clang -std=gnu89 -isysroot $(xcrun --show-sdk-path) \ + * -Wno-error=implicit-function-declaration -Wno-error=implicit-int \ + * -Wno-error=int-conversion -Wno-error=incompatible-function-pointer-types" ./configure + * + * with no other option, matching ../linux/pyconfig.h's upstream default configuration (UCS-2 + * unicode, pymalloc, threads, IPv6). Why the extra flags: + * -std=gnu89 and the -Wno-error= set: Apple clang turns implicit function declarations into + * errors even in gnu89 mode, and Autoconf 2.57's probes call exit() without . Without + * the demotions every AC_TRY_RUN probe fails and configure silently reports SIZEOF_OFF_T 0, + * WORDS_BIGENDIAN and SIGNED_RIGHT_SHIFT_ZERO_FILLS - the same failure ../linux/pyconfig.h + * records for GCC 14. + * -isysroot: Apple clang otherwise searches /usr/local/include first, so Homebrew headers + * (libintl.h from gettext, GNU readline) leak into the probes. CMake passes the same SDK + * sysroot to every compile, so configure and build now see the same headers. + * + * The configure part is NOT HAND-EDITED. Differences from the Linux configure output are configure's honest answers on + * Darwin, for example: SIZEOF_FPOS_T 8 (Darwin's fpos_t is an off_t), HAVE_SOCKADDR_SA_LEN, + * no HAVE_STAT_TV_NSEC (Darwin spells it st_mtimespec), no HAVE_GETHOSTBYNAME_R, no + * HAVE_LIBINTL_H. USE_TOOLBOX_OBJECT_GLUE and WITH_DYLD are set by configure's Darwin case; the + * units that read them (Python/mactoolboxglue.c, Python/dynload_next.c) are not in the build - + * dynload_shlib.c (dlopen) is the loader on both POSIX ports. A few probes (chroot, flock, + * getpagesize, inet_aton, hstrerror, setgroups, fdatasync) report absent because their 2003 + * probe programs do not compile against the current SDK; posixmodule then simply omits those + * functions, which the game's scripts do not call. + * MACHDEP is darwin; ../linux/CMakeLists.txt passes the retail-era "linux2" platform string on + * macOS too (documented there and in README.md beside this file). + * + * To regenerate: copy py-src-2.3.4 somewhere scratch (never configure the vendored tree), run the + * command above there, copy its pyconfig.h over the configure part of this file, and keep this + * block and the macOS overrides block. + * ============================================================================================= */ +/* pyconfig.h. Generated by configure. */ +/* pyconfig.h.in. Generated from configure.in by autoheader. */ + + +#ifndef Py_PYCONFIG_H +#define Py_PYCONFIG_H + + +/* Define for AIX if your compiler is a genuine IBM xlC/xlC_r and you want + support for AIX C++ shared extension modules. */ +/* #undef AIX_GENUINE_CPLUSPLUS */ + +/* Define this if you have AtheOS threads. */ +/* #undef ATHEOS_THREADS */ + +/* Define if your contains bad prototypes for exec*() (as it does + on SGI IRIX 4.x) */ +/* #undef BAD_EXEC_PROTOTYPES */ + +/* Define this if you have BeOS threads. */ +/* #undef BEOS_THREADS */ + +/* Define if you have the Mach cthreads package */ +/* #undef C_THREADS */ + +/* Define if --enable-ipv6 is specified */ +#define ENABLE_IPV6 1 + +/* Define if getpgrp() must be called as getpgrp(0). */ +/* #undef GETPGRP_HAVE_ARG */ + +/* Define if gettimeofday() does not have second (timezone) argument This is + the case on Motorola V4 (R40V4.2) */ +/* #undef GETTIMEOFDAY_NO_TZ */ + +/* struct addrinfo (netdb.h) */ +#define HAVE_ADDRINFO 1 + +/* Define to 1 if you have the `alarm' function. */ +#define HAVE_ALARM 1 + +/* Define this if your time.h defines altzone. */ +/* #undef HAVE_ALTZONE */ + +/* Define if nice() returns success/failure instead of the new priority. */ +/* #undef HAVE_BROKEN_NICE */ + +/* Define if poll() sets errno on invalid file descriptors. */ +/* #undef HAVE_BROKEN_POLL */ + +/* Define if the Posix semaphores do not work on your system */ +/* #undef HAVE_BROKEN_POSIX_SEMAPHORES */ + +/* Define if pthread_sigmask() does not work on your system. */ +/* #undef HAVE_BROKEN_PTHREAD_SIGMASK */ + +/* Define to 1 if you have the `chown' function. */ +#define HAVE_CHOWN 1 + +/* Define if you have the 'chroot' function. */ +/* #undef HAVE_CHROOT */ + +/* Define to 1 if you have the `clock' function. */ +#define HAVE_CLOCK 1 + +/* Define to 1 if you have the `confstr' function. */ +#define HAVE_CONFSTR 1 + +/* Define to 1 if you have the `ctermid' function. */ +#define HAVE_CTERMID 1 + +/* Define if you have the 'ctermid_r' function. */ +/* #undef HAVE_CTERMID_R */ + +/* Define to 1 if you have the device macros. */ +/* #undef HAVE_DEVICE_MACROS */ + +/* Define if we have /dev/ptc. */ +/* #undef HAVE_DEV_PTC */ + +/* Define if we have /dev/ptmx. */ +#define HAVE_DEV_PTMX 1 + +/* Define to 1 if you have the header file, and it defines `DIR'. + */ +#define HAVE_DIRENT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_DLFCN_H 1 + +/* Define to 1 if you have the `dlopen' function. */ +#define HAVE_DLOPEN 1 + +/* Define to 1 if you have the `dup2' function. */ +#define HAVE_DUP2 1 + +/* Defined when any dynamic module loading is enabled. */ +#define HAVE_DYNAMIC_LOADING 1 + +/* Define to 1 if you have the `execv' function. */ +#define HAVE_EXECV 1 + +/* Define if you have the 'fchdir' function. */ +#define HAVE_FCHDIR 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_FCNTL_H 1 + +/* Define if you have the 'fdatasync' function. */ +/* #undef HAVE_FDATASYNC */ + +/* Define if you have the 'flock' function. */ +/* #undef HAVE_FLOCK */ + +/* Define to 1 if you have the `fork' function. */ +#define HAVE_FORK 1 + +/* Define to 1 if you have the `forkpty' function. */ +#define HAVE_FORKPTY 1 + +/* Define to 1 if you have the `fpathconf' function. */ +#define HAVE_FPATHCONF 1 + +/* Define to 1 if you have the `fseek64' function. */ +/* #undef HAVE_FSEEK64 */ + +/* Define to 1 if you have the `fseeko' function. */ +#define HAVE_FSEEKO 1 + +/* Define to 1 if you have the `fstatvfs' function. */ +#define HAVE_FSTATVFS 1 + +/* Define if you have the 'fsync' function. */ +#define HAVE_FSYNC 1 + +/* Define to 1 if you have the `ftell64' function. */ +/* #undef HAVE_FTELL64 */ + +/* Define to 1 if you have the `ftello' function. */ +#define HAVE_FTELLO 1 + +/* Define to 1 if you have the `ftime' function. */ +#define HAVE_FTIME 1 + +/* Define to 1 if you have the `ftruncate' function. */ +#define HAVE_FTRUNCATE 1 + +/* Define to 1 if you have the `gai_strerror' function. */ +#define HAVE_GAI_STRERROR 1 + +/* Define if you have the getaddrinfo function. */ +#define HAVE_GETADDRINFO 1 + +/* Define to 1 if you have the `getcwd' function. */ +#define HAVE_GETCWD 1 + +/* Define this if you have flockfile(), getc_unlocked(), and funlockfile() */ +#define HAVE_GETC_UNLOCKED 1 + +/* Define to 1 if you have the `getgroups' function. */ +#define HAVE_GETGROUPS 1 + +/* Define to 1 if you have the `gethostbyname' function. */ +#define HAVE_GETHOSTBYNAME 1 + +/* Define this if you have some version of gethostbyname_r() */ +/* #undef HAVE_GETHOSTBYNAME_R */ + +/* Define this if you have the 3-arg version of gethostbyname_r(). */ +/* #undef HAVE_GETHOSTBYNAME_R_3_ARG */ + +/* Define this if you have the 5-arg version of gethostbyname_r(). */ +/* #undef HAVE_GETHOSTBYNAME_R_5_ARG */ + +/* Define this if you have the 6-arg version of gethostbyname_r(). */ +/* #undef HAVE_GETHOSTBYNAME_R_6_ARG */ + +/* Define to 1 if you have the `getloadavg' function. */ +#define HAVE_GETLOADAVG 1 + +/* Define to 1 if you have the `getlogin' function. */ +#define HAVE_GETLOGIN 1 + +/* Define to 1 if you have the `getnameinfo' function. */ +#define HAVE_GETNAMEINFO 1 + +/* Define if you have the 'getpagesize' function. */ +/* #undef HAVE_GETPAGESIZE */ + +/* Define to 1 if you have the `getpeername' function. */ +#define HAVE_GETPEERNAME 1 + +/* Define to 1 if you have the `getpgid' function. */ +#define HAVE_GETPGID 1 + +/* Define to 1 if you have the `getpgrp' function. */ +#define HAVE_GETPGRP 1 + +/* Define to 1 if you have the `getpid' function. */ +#define HAVE_GETPID 1 + +/* Define to 1 if you have the `getpriority' function. */ +#define HAVE_GETPRIORITY 1 + +/* Define to 1 if you have the `getpwent' function. */ +#define HAVE_GETPWENT 1 + +/* Define to 1 if you have the `gettimeofday' function. */ +#define HAVE_GETTIMEOFDAY 1 + +/* Define to 1 if you have the `getwd' function. */ +#define HAVE_GETWD 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_GRP_H 1 + +/* Define if you have the 'hstrerror' function. */ +/* #undef HAVE_HSTRERROR */ + +/* Define to 1 if you have the `hypot' function. */ +#define HAVE_HYPOT 1 + +/* Define if you have the 'inet_aton' function. */ +/* #undef HAVE_INET_ATON */ + +/* Define if you have the 'inet_pton' function. */ +#define HAVE_INET_PTON 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_INTTYPES_H 1 + +/* Define to 1 if you have the `kill' function. */ +#define HAVE_KILL 1 + +/* Define to 1 if you have the `killpg' function. */ +#define HAVE_KILLPG 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_LANGINFO_H 1 + +/* Defined to enable large file support when an off_t is bigger than a long + and long long is available and at least as big as an off_t. You may need to + add some flags for configuration and compilation to enable this mode. (For + Solaris and Linux, the necessary defines are already defined.) */ +/* #undef HAVE_LARGEFILE_SUPPORT */ + +/* Define to 1 if you have the `lchown' function. */ +#define HAVE_LCHOWN 1 + +/* Define to 1 if you have the `dl' library (-ldl). */ +#define HAVE_LIBDL 1 + +/* Define to 1 if you have the `dld' library (-ldld). */ +/* #undef HAVE_LIBDLD */ + +/* Define to 1 if you have the `ieee' library (-lieee). */ +/* #undef HAVE_LIBIEEE */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_LIBINTL_H */ + +/* Define to 1 if you have the `resolv' library (-lresolv). */ +/* #undef HAVE_LIBRESOLV */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_LIBUTIL_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_LIMITS_H 1 + +/* Define if you have the 'link' function. */ +#define HAVE_LINK 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_LOCALE_H 1 + +/* Define this if you have the type long long. */ +#define HAVE_LONG_LONG 1 + +/* Define to 1 if you have the `lstat' function. */ +#define HAVE_LSTAT 1 + +/* Define this if you have the makedev macro. */ +/* #undef HAVE_MAKEDEV */ + +/* Define to 1 if you have the `memmove' function. */ +#define HAVE_MEMMOVE 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_MEMORY_H 1 + +/* Define to 1 if you have the `mkfifo' function. */ +#define HAVE_MKFIFO 1 + +/* Define to 1 if you have the `mknod' function. */ +#define HAVE_MKNOD 1 + +/* Define to 1 if you have the `mktime' function. */ +#define HAVE_MKTIME 1 + +/* Define to 1 if you have the `mremap' function. */ +/* #undef HAVE_MREMAP */ + +/* Define to 1 if you have the header file. */ +#define HAVE_NCURSES_H 1 + +/* Define to 1 if you have the header file, and it defines `DIR'. */ +/* #undef HAVE_NDIR_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_NETPACKET_PACKET_H */ + +/* Define to 1 if you have the `nice' function. */ +#define HAVE_NICE 1 + +/* Define to 1 if you have the `openpty' function. */ +#define HAVE_OPENPTY 1 + +/* Define to 1 if you have the `pathconf' function. */ +#define HAVE_PATHCONF 1 + +/* Define to 1 if you have the `pause' function. */ +#define HAVE_PAUSE 1 + +/* Define to 1 if you have the `plock' function. */ +/* #undef HAVE_PLOCK */ + +/* Define to 1 if you have the `poll' function. */ +#define HAVE_POLL 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_POLL_H 1 + +/* Define if your compiler supports function prototype */ +#define HAVE_PROTOTYPES 1 + +/* Define if you have GNU PTH threads. */ +/* #undef HAVE_PTH */ + +/* Defined for Solaris 2.6 bug in pthread header. */ +/* #undef HAVE_PTHREAD_DESTRUCTOR */ + +/* Define to 1 if you have the header file. */ +#define HAVE_PTHREAD_H 1 + +/* Define to 1 if you have the `pthread_init' function. */ +/* #undef HAVE_PTHREAD_INIT */ + +/* Define to 1 if you have the `pthread_sigmask' function. */ +#define HAVE_PTHREAD_SIGMASK 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_PTY_H */ + +/* Define to 1 if you have the `putenv' function. */ +#define HAVE_PUTENV 1 + +/* Define to 1 if you have the `readlink' function. */ +#define HAVE_READLINK 1 + +/* Define to 1 if you have the `realpath' function. */ +#define HAVE_REALPATH 1 + +/* Define if you have readline 2.2 */ +#define HAVE_RL_COMPLETION_APPEND_CHARACTER 1 + +/* Define if you have readline 4.2 */ +#define HAVE_RL_COMPLETION_MATCHES 1 + +/* Define if you have readline 4.0 */ +#define HAVE_RL_PRE_INPUT_HOOK 1 + +/* Define to 1 if you have the `select' function. */ +#define HAVE_SELECT 1 + +/* Define to 1 if you have the `setegid' function. */ +#define HAVE_SETEGID 1 + +/* Define to 1 if you have the `seteuid' function. */ +#define HAVE_SETEUID 1 + +/* Define to 1 if you have the `setgid' function. */ +#define HAVE_SETGID 1 + +/* Define if you have the 'setgroups' function. */ +/* #undef HAVE_SETGROUPS */ + +/* Define to 1 if you have the `setlocale' function. */ +#define HAVE_SETLOCALE 1 + +/* Define to 1 if you have the `setpgid' function. */ +#define HAVE_SETPGID 1 + +/* Define to 1 if you have the `setpgrp' function. */ +#define HAVE_SETPGRP 1 + +/* Define to 1 if you have the `setregid' function. */ +#define HAVE_SETREGID 1 + +/* Define to 1 if you have the `setreuid' function. */ +#define HAVE_SETREUID 1 + +/* Define to 1 if you have the `setsid' function. */ +#define HAVE_SETSID 1 + +/* Define to 1 if you have the `setuid' function. */ +#define HAVE_SETUID 1 + +/* Define to 1 if you have the `setvbuf' function. */ +#define HAVE_SETVBUF 1 + +/* Define to 1 if you have the `sigaction' function. */ +#define HAVE_SIGACTION 1 + +/* Define to 1 if you have the `siginterrupt' function. */ +#define HAVE_SIGINTERRUPT 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SIGNAL_H 1 + +/* Define to 1 if you have the `sigrelse' function. */ +#define HAVE_SIGRELSE 1 + +/* Define to 1 if you have the `snprintf' function. */ +#define HAVE_SNPRINTF 1 + +/* Define if sockaddr has sa_len member */ +#define HAVE_SOCKADDR_SA_LEN 1 + +/* struct sockaddr_storage (sys/socket.h) */ +#define HAVE_SOCKADDR_STORAGE 1 + +/* Define to 1 if you have the `statvfs' function. */ +#define HAVE_STATVFS 1 + +/* Define if you have struct stat.st_mtim.tv_nsec */ +/* #undef HAVE_STAT_TV_NSEC */ + +/* Define to 1 if you have the header file. */ +#define HAVE_STDARG_H 1 + +/* Define if your compiler supports variable length function prototypes (e.g. + void fprintf(FILE *, char *, ...);) *and* */ +#define HAVE_STDARG_PROTOTYPES 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDDEF_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDINT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDLIB_H 1 + +/* Define to 1 if you have the `strdup' function. */ +#define HAVE_STRDUP 1 + +/* Define to 1 if you have the `strerror' function. */ +#define HAVE_STRERROR 1 + +/* Define to 1 if you have the `strftime' function. */ +#define HAVE_STRFTIME 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRINGS_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRING_H 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_STROPTS_H */ + +/* Define to 1 if you have the `strptime' function. */ +#define HAVE_STRPTIME 1 + +/* Define to 1 if `st_blksize' is member of `struct stat'. */ +#define HAVE_STRUCT_STAT_ST_BLKSIZE 1 + +/* Define to 1 if `st_blocks' is member of `struct stat'. */ +#define HAVE_STRUCT_STAT_ST_BLOCKS 1 + +/* Define to 1 if `st_rdev' is member of `struct stat'. */ +#define HAVE_STRUCT_STAT_ST_RDEV 1 + +/* Define to 1 if `tm_zone' is member of `struct tm'. */ +#define HAVE_STRUCT_TM_TM_ZONE 1 + +/* Define to 1 if your `struct stat' has `st_blocks'. Deprecated, use + `HAVE_STRUCT_STAT_ST_BLOCKS' instead. */ +#define HAVE_ST_BLOCKS 1 + +/* Define if you have the 'symlink' function. */ +#define HAVE_SYMLINK 1 + +/* Define to 1 if you have the `sysconf' function. */ +#define HAVE_SYSCONF 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYSEXITS_H 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_AUDIOIO_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_BSDTTY_H */ + +/* Define to 1 if you have the header file, and it defines `DIR'. + */ +/* #undef HAVE_SYS_DIR_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_FILE_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_LOCK_H 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_MKDEV_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_MODEM_H */ + +/* Define to 1 if you have the header file, and it defines `DIR'. + */ +/* #undef HAVE_SYS_NDIR_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_PARAM_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_POLL_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_RESOURCE_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_SELECT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_SOCKET_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_STAT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_TIMES_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_TIME_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_TYPES_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_UN_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_UTSNAME_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_WAIT_H 1 + +/* Define to 1 if you have the `tcgetpgrp' function. */ +#define HAVE_TCGETPGRP 1 + +/* Define to 1 if you have the `tcsetpgrp' function. */ +#define HAVE_TCSETPGRP 1 + +/* Define to 1 if you have the `tempnam' function. */ +#define HAVE_TEMPNAM 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_TERMIOS_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_TERM_H 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_THREAD_H */ + +/* Define to 1 if you have the `timegm' function. */ +#define HAVE_TIMEGM 1 + +/* Define to 1 if you have the `times' function. */ +#define HAVE_TIMES 1 + +/* Define to 1 if you have the `tmpfile' function. */ +#define HAVE_TMPFILE 1 + +/* Define to 1 if you have the `tmpnam' function. */ +#define HAVE_TMPNAM 1 + +/* Define to 1 if you have the `tmpnam_r' function. */ +/* #undef HAVE_TMPNAM_R */ + +/* Define to 1 if your `struct tm' has `tm_zone'. Deprecated, use + `HAVE_STRUCT_TM_TM_ZONE' instead. */ +#define HAVE_TM_ZONE 1 + +/* Define to 1 if you have the `truncate' function. */ +#define HAVE_TRUNCATE 1 + +/* Define to 1 if you don't have `tm_zone' but do have the external array + `tzname'. */ +/* #undef HAVE_TZNAME */ + +/* Define this if you have tcl and TCL_UTF_MAX==6 */ +/* #undef HAVE_UCS4_TCL */ + +/* Define this if you have the type uintptr_t. */ +/* #undef HAVE_UINTPTR_T */ + +/* Define to 1 if you have the `uname' function. */ +#define HAVE_UNAME 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_UNISTD_H 1 + +/* Define to 1 if you have the `unsetenv' function. */ +#define HAVE_UNSETENV 1 + +/* Define if you have a useable wchar_t type defined in wchar.h; useable means + wchar_t must be 16-bit unsigned type. (see Include/unicodeobject.h). */ +/* #undef HAVE_USABLE_WCHAR_T */ + +/* Define to 1 if you have the `utimes' function. */ +#define HAVE_UTIMES 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_UTIME_H 1 + +/* Define to 1 if you have the `waitpid' function. */ +#define HAVE_WAITPID 1 + +/* Define if the compiler provides a wchar.h header file. */ +#define HAVE_WCHAR_H 1 + +/* Define to 1 if you have the `wcscoll' function. */ +#define HAVE_WCSCOLL 1 + +/* Define if tzset() actually switches the local timezone in a meaningful way. + */ +#define HAVE_WORKING_TZSET 1 + +/* Define to 1 if you have the `_getpty' function. */ +/* #undef HAVE__GETPTY */ + +/* Define if you are using Mach cthreads directly under /include */ +/* #undef HURD_C_THREADS */ + +/* Define if you are using Mach cthreads under mach / */ +/* #undef MACH_C_THREADS */ + +/* Define to 1 if `major', `minor', and `makedev' are declared in . + */ +/* #undef MAJOR_IN_MKDEV */ + +/* Define to 1 if `major', `minor', and `makedev' are declared in + . */ +/* #undef MAJOR_IN_SYSMACROS */ + +/* Define if mvwdelch in curses.h is an expression. */ +#define MVWDELCH_IS_EXPRESSION 1 + +/* Define to the address where bug reports for this package should be sent. */ +/* #undef PACKAGE_BUGREPORT */ + +/* Define to the full name of this package. */ +/* #undef PACKAGE_NAME */ + +/* Define to the full name and version of this package. */ +/* #undef PACKAGE_STRING */ + +/* Define to the one symbol short name of this package. */ +/* #undef PACKAGE_TARNAME */ + +/* Define to the version of this package. */ +/* #undef PACKAGE_VERSION */ + +/* Defined if PTHREAD_SCOPE_SYSTEM supported. */ +#define PTHREAD_SYSTEM_SCHED_SUPPORTED 1 + +/* Define as the integral type used for Unicode representation. */ +#define PY_UNICODE_TYPE unsigned short + +/* Define if you want to build an interpreter with many run-time checks. */ +/* #undef Py_DEBUG */ + +/* Defined if Python is built as a shared library. */ +/* #undef Py_ENABLE_SHARED */ + +/* Define as the size of the unicode type. */ +#define Py_UNICODE_SIZE 2 + +/* Define if you want to have a Unicode type. */ +#define Py_USING_UNICODE 1 + +/* Define as the return type of signal handlers (`int' or `void'). */ +#define RETSIGTYPE void + +/* Define if setpgrp() must be called as setpgrp(0, 0). */ +/* #undef SETPGRP_HAVE_ARG */ + +/* Define if i>>j for signed int i does not extend the sign bit when i < 0 */ +/* #undef SIGNED_RIGHT_SHIFT_ZERO_FILLS */ + +/* The size of a `char', as computed by sizeof. */ +#define SIZEOF_CHAR 1 + +/* The size of a `double', as computed by sizeof. */ +#define SIZEOF_DOUBLE 8 + +/* The size of a `float', as computed by sizeof. */ +#define SIZEOF_FLOAT 4 + +/* The size of a `fpos_t', as computed by sizeof. */ +#define SIZEOF_FPOS_T 8 + +/* The size of a `int', as computed by sizeof. */ +#define SIZEOF_INT 4 + +/* The size of a `long', as computed by sizeof. */ +#define SIZEOF_LONG 8 + +/* The size of a `long long', as computed by sizeof. */ +#define SIZEOF_LONG_LONG 8 + +/* The number of bytes in an off_t. */ +#define SIZEOF_OFF_T 8 + +/* The number of bytes in a pthread_t. */ +#define SIZEOF_PTHREAD_T 8 + +/* The size of a `short', as computed by sizeof. */ +#define SIZEOF_SHORT 2 + +/* The number of bytes in a time_t. */ +#define SIZEOF_TIME_T 8 + +/* The size of a `uintptr_t', as computed by sizeof. */ +/* #undef SIZEOF_UINTPTR_T */ + +/* The size of a `void *', as computed by sizeof. */ +#define SIZEOF_VOID_P 8 + +/* The size of a `wchar_t', as computed by sizeof. */ +#define SIZEOF_WCHAR_T 4 + +/* Define to 1 if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* Define if you can safely include both and + (which you can't on SCO ODT 3.0). */ +#define SYS_SELECT_WITH_SYS_TIME 1 + +/* Define to 1 if you can safely include both and . */ +#define TIME_WITH_SYS_TIME 1 + +/* Define to 1 if your declares `struct tm'. */ +/* #undef TM_IN_SYS_TIME */ + +/* Define if you want to use MacPython modules on MacOSX in unix-Python. */ +#define USE_TOOLBOX_OBJECT_GLUE 1 + +/* Define if a va_list is an array of some kind */ +#define VA_LIST_IS_ARRAY 1 + +/* Define if you want SIGFPE handled (see Include/pyfpe.h). */ +/* #undef WANT_SIGFPE_HANDLER */ + +/* Define if you want wctype.h functions to be used instead of the one + supplied by Python itself. (see Include/unicodectype.h). */ +/* #undef WANT_WCTYPE_FUNCTIONS */ + +/* Define if WINDOW in curses.h offers a field _flags. */ +/* #undef WINDOW_HAS_FLAGS */ + +/* Define if you want to emulate SGI (IRIX 4) dynamic linking. This is + rumoured to work on VAX (Ultrix), Sun3 (SunOS 3.4), Sequent Symmetry + (Dynix), and Atari ST. This requires the 'dl-dld' library, + ftp://ftp.cwi.nl/pub/dynload/dl-dld-1.1.tar.Z, as well as the 'GNU dld' + library, ftp://ftp.cwi.nl/pub/dynload/dld-3.2.3.tar.Z. Do not bother on + SunOS 4 or 5, they already have dynamic linking using shared libraries. */ +/* #undef WITH_DL_DLD */ + +/* Define if you want documentation strings in extension modules */ +#define WITH_DOC_STRINGS 1 + +/* Define if you want to use the new-style (Openstep, Rhapsody, MacOS) dynamic + linker (dyld) instead of the old-style (NextStep) dynamic linker (rld). + Dyld is necessary to support frameworks. */ +#define WITH_DYLD 1 + +/* Define to 1 if libintl is needed for locale functions. */ +/* #undef WITH_LIBINTL */ + +/* Define if you want to produce an OpenStep/Rhapsody framework (shared + library plus accessory files). */ +/* #undef WITH_NEXT_FRAMEWORK */ + +/* Define if you want to compile in Python-specific mallocs */ +#define WITH_PYMALLOC 1 + +/* Define if you want to use SGI (IRIX 4) dynamic linking. This requires the + "dl" library by Jack Jansen, ftp://ftp.cwi.nl/pub/dynload/dl-1.6.tar.Z. Do + not bother on IRIX 5, it already has dynamic linking using SunOS style + shared libraries */ +/* #undef WITH_SGI_DL */ + +/* Define if you want to compile in rudimentary thread support */ +#define WITH_THREAD 1 + +/* Define if you want to read files with foreign newlines. */ +#define WITH_UNIVERSAL_NEWLINES 1 + +/* Define to 1 if your processor stores words with the most significant byte + first (like Motorola and SPARC, unlike Intel and VAX). */ +/* #undef WORDS_BIGENDIAN */ + +/* Define to 1 if on AIX 3. + System headers sometimes define this. + We just want to avoid a redefinition error message. */ +#ifndef _ALL_SOURCE +/* # undef _ALL_SOURCE */ +#endif + +/* This must be set to 64 on some systems to enable large file support. */ +#define _FILE_OFFSET_BITS 64 + +/* Define on Linux to activate all library features */ +#define _GNU_SOURCE 1 + +/* This must be defined on some systems to enable large file support. */ +#define _LARGEFILE_SOURCE 1 + +/* Define to 1 if on MINIX. */ +/* #undef _MINIX */ + +/* Define on NetBSD to activate all library features */ +#define _NETBSD_SOURCE 1 + +/* Define _OSF_SOURCE to get the makedev macro. */ +/* #undef _OSF_SOURCE */ + +/* Define to 2 if the system does not provide POSIX.1 features except with + this defined. */ +/* #undef _POSIX_1_SOURCE */ + +/* Define to activate features from IEEE Stds 1003.1-2001 */ +#define _POSIX_C_SOURCE 200112L + +/* Define to 1 if you need to in order for `stat' and other things to work. */ +/* #undef _POSIX_SOURCE */ + +/* Define if you have POSIX threads, and your system does not define that. */ +/* #undef _POSIX_THREADS */ + +/* Define to force use of thread-safe errno, h_errno, and other functions */ +#define _REENTRANT 1 + +/* Define to the level of X/Open that your system supports */ +#define _XOPEN_SOURCE 600 + +/* Define to activate Unix95-and-earlier features */ +#define _XOPEN_SOURCE_EXTENDED 1 + +/* Define on FreeBSD to activate all library features */ +#define __BSD_VISIBLE 1 + +/* Define to 1 if type `char' is unsigned and you are not using gcc. */ +#ifndef __CHAR_UNSIGNED__ +/* # undef __CHAR_UNSIGNED__ */ +#endif + +/* Defined on Solaris to see additional function prototypes. */ +/* #undef __EXTENSIONS__ */ + +/* Define to 'long' if doesn't define. */ +/* #undef clock_t */ + +/* Define to empty if `const' does not conform to ANSI C. */ +/* #undef const */ + +/* Define to `int' if doesn't define. */ +/* #undef gid_t */ + +/* Define to `int' if does not define. */ +/* #undef mode_t */ + +/* Define to `long' if does not define. */ +/* #undef off_t */ + +/* Define to `int' if does not define. */ +/* #undef pid_t */ + +/* Define to empty if the keyword does not work. */ +/* #undef signed */ + +/* Define to `unsigned' if does not define. */ +/* #undef size_t */ + +/* Define to `int' if does not define. */ +/* #undef socklen_t */ + +/* Define to `int' if doesn't define. */ +/* #undef uid_t */ + +/* Define to empty if the keyword does not work. */ +/* #undef volatile */ + + +/* Define the macros needed if on a UnixWare 7.x system. */ +#if defined(__USLC__) && defined(__SCO_VERSION__) +#define STRICT_SYSV_CURSES /* Don't use ncurses extensions */ +#endif + +/* ---- macOS overrides: the only hand-written lines in this file. ---- */ + +/* [CHOSEN, not recovered] Darwin's defines _POSIX_SEMAPHORES as -1 ("not supported"): + * sem_init/sem_destroy fail with ENOSYS and only named semaphores exist. Python/thread_pthread.h + * tests the macro with #ifdef, so without this it builds every lock on sem_init and every lock + * operation fails. HAVE_BROKEN_POSIX_SEMAPHORES is the switch upstream already provides for such + * platforms (configure.in sets it for SunOS 5.8); it selects the mutex + condition-variable locks. */ +#define HAVE_BROKEN_POSIX_SEMAPHORES 1 + +/* [CHOSEN, not recovered] arm64 (Apple silicon). The configure run above was x86_64, where va_list + * is an array type. On arm64 Darwin va_list is a plain char*, so Py_VA_COPY must assign rather than + * memcpy through it. Every other value above holds for arm64 macOS too (LP64, little-endian, the + * same libSystem). This override is untested: the port's reference machine is x86_64. */ +#if defined(__arm64__) || defined(__aarch64__) +#undef VA_LIST_IS_ARRAY +#endif + +#endif /*Py_PYCONFIG_H*/ diff --git a/Code/BF2/External/python-embedded/py-src-2.3.4/Modules/socketmodule.c b/Code/BF2/External/python-embedded/py-src-2.3.4/Modules/socketmodule.c index e9375faa9..98865aa7c 100644 --- a/Code/BF2/External/python-embedded/py-src-2.3.4/Modules/socketmodule.c +++ b/Code/BF2/External/python-embedded/py-src-2.3.4/Modules/socketmodule.c @@ -3024,7 +3024,12 @@ socket_inet_ntop(PyObject *self, PyObject *args) #endif /* Guarantee NUL-termination for PyString_FromString() below */ +#ifdef MS_WINDOWS memset((void *) &ip[0], '\0', sizeof(ip) + 1); +#else + /* [CHOSEN, not recovered] Bound initialization to the actual POSIX buffer. */ + memset((void *) &ip[0], '\0', sizeof(ip)); +#endif if (!PyArg_ParseTuple(args, "is#:inet_ntop", &af, &packed, &len)) { return NULL; diff --git a/Code/BF2/External/python-embedded/py-src-2.3.4/Objects/longobject.c b/Code/BF2/External/python-embedded/py-src-2.3.4/Objects/longobject.c index f246bd232..7f36161f5 100644 --- a/Code/BF2/External/python-embedded/py-src-2.3.4/Objects/longobject.c +++ b/Code/BF2/External/python-embedded/py-src-2.3.4/Objects/longobject.c @@ -28,11 +28,20 @@ static PyLongObject *muladd1(PyLongObject *, wdigit, wdigit); static PyLongObject *divrem1(PyLongObject *, digit, digit *); static PyObject *long_format(PyObject *aa, int base, int addL); +#if !defined(MS_WINDOWS) && (defined(__APPLE__) || defined(__linux__)) +/* [CHOSEN, not recovered] Match ceval.c's atomic ticker accesses on POSIX. */ +#define SIGCHECK(PyTryBlock) \ + if (__atomic_sub_fetch(&_Py_Ticker, 1, __ATOMIC_SEQ_CST) < 0) { \ + __atomic_store_n(&_Py_Ticker, _Py_CheckInterval, __ATOMIC_SEQ_CST); \ + if (PyErr_CheckSignals()) { PyTryBlock; } \ + } +#else #define SIGCHECK(PyTryBlock) \ if (--_Py_Ticker < 0) { \ _Py_Ticker = _Py_CheckInterval; \ if (PyErr_CheckSignals()) { PyTryBlock; } \ } +#endif /* Normalize (remove leading zeros from) a long int object. Doesn't attempt to free the storage--in most cases, due to the nature diff --git a/Code/BF2/External/python-embedded/py-src-2.3.4/Objects/obmalloc.c b/Code/BF2/External/python-embedded/py-src-2.3.4/Objects/obmalloc.c index 7e5fd4a8e..7ad6e18b2 100644 --- a/Code/BF2/External/python-embedded/py-src-2.3.4/Objects/obmalloc.c +++ b/Code/BF2/External/python-embedded/py-src-2.3.4/Objects/obmalloc.c @@ -409,8 +409,15 @@ static poolp freepools = NULL; /* free list for cached pools */ * and only grows by appending at the end. For now we never return an arena * to the OS. */ +#if !defined(MS_WINDOWS) && (defined(__APPLE__) || defined(__linux__)) +/* [CHOSEN, not recovered] POSIX: publish the vector before its count, including to + frees without the GIL (see new_arena). C11 implicit accesses are sequentially consistent. */ +static _Atomic(uptr *) arenas = NULL; +static _Atomic uint narenas = 0; +#else static uptr *volatile arenas = NULL; /* the pointer itself is volatile */ static volatile uint narenas = 0; +#endif static uint maxarenas = 0; /* Number of pools still available to be allocated in the current arena. */ diff --git a/Code/BF2/External/python-embedded/py-src-2.3.4/Python/ceval.c b/Code/BF2/External/python-embedded/py-src-2.3.4/Python/ceval.c index 035520a59..03abb7f00 100644 --- a/Code/BF2/External/python-embedded/py-src-2.3.4/Python/ceval.c +++ b/Code/BF2/External/python-embedded/py-src-2.3.4/Python/ceval.c @@ -429,21 +429,40 @@ static struct { int (*func)(void *); void *arg; } pendingcalls[NPENDINGCALLS]; +#if !defined(MS_WINDOWS) && (defined(__APPLE__) || defined(__linux__)) +#include +/* [CHOSEN, not recovered] POSIX pending-call publication must order the queue slots. + C11 atomics are used in this C runtime; the Windows implementation is retained below. */ +static _Atomic int pendingfirst = 0; +static _Atomic int pendinglast = 0; +static _Atomic int things_to_do = 0; +#else static volatile int pendingfirst = 0; static volatile int pendinglast = 0; static volatile int things_to_do = 0; +#endif int Py_AddPendingCall(int (*func)(void *), void *arg) { +#if !defined(MS_WINDOWS) && (defined(__APPLE__) || defined(__linux__)) + /* A failed try-lock refuses nested/simultaneous producers without blocking a signal handler. */ + static _Atomic int busy = 0; +#else static int busy = 0; +#endif int i, j; /* XXX Begin critical section */ /* XXX If you want this to be safe against nested XXX asynchronous calls, you'll have to work harder! */ +#if !defined(MS_WINDOWS) && (defined(__APPLE__) || defined(__linux__)) + if (atomic_exchange_explicit(&busy, 1, memory_order_seq_cst)) + return -1; +#else if (busy) return -1; busy = 1; +#endif i = pendinglast; j = (i + 1) % NPENDINGCALLS; if (j == pendingfirst) { @@ -454,7 +473,11 @@ Py_AddPendingCall(int (*func)(void *), void *arg) pendingcalls[i].arg = arg; pendinglast = j; +#if !defined(MS_WINDOWS) && (defined(__APPLE__) || defined(__linux__)) + __atomic_store_n(&_Py_Ticker, 0, __ATOMIC_SEQ_CST); +#else _Py_Ticker = 0; +#endif things_to_do = 1; /* Signal main loop */ busy = 0; /* XXX End critical section */ @@ -772,13 +795,22 @@ eval_frame(PyFrameObject *f) async I/O handler); see Py_AddPendingCall() and Py_MakePendingCalls() above. */ +#if !defined(MS_WINDOWS) && (defined(__APPLE__) || defined(__linux__)) + /* [CHOSEN, not recovered] May be reset by Py_AddPendingCall without the GIL. */ + if (__atomic_sub_fetch(&_Py_Ticker, 1, __ATOMIC_SEQ_CST) < 0) { +#else if (--_Py_Ticker < 0) { +#endif if (*next_instr == SETUP_FINALLY) { /* Make the last opcode before a try: finally: block uninterruptable. */ goto fast_next_opcode; } +#if !defined(MS_WINDOWS) && (defined(__APPLE__) || defined(__linux__)) + __atomic_store_n(&_Py_Ticker, _Py_CheckInterval, __ATOMIC_SEQ_CST); +#else _Py_Ticker = _Py_CheckInterval; +#endif tstate->tick_counter++; if (things_to_do) { if (Py_MakePendingCalls() < 0) { diff --git a/Code/BF2/External/speex-1.0.5/AUTHORS b/Code/BF2/External/speex-1.0.5/AUTHORS new file mode 100644 index 000000000..b3fd7f53b --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/AUTHORS @@ -0,0 +1,15 @@ +Jean-Marc Valin + All the code except the following + +David Rowe via VoiceTronix + lsp.c lsp.h + Also ideas and feedback + +John Francis Edwards: + wave_out.[ch], some #ifdefs for windows port and MSVC project files + +Atsuhiko Yamanaka : + Patch to speexenc.c to add Vorbis comment format + +Radim Kolar : + Patch to speexenc.c for supporting more input formats diff --git a/Code/BF2/External/speex-1.0.5/COPYING b/Code/BF2/External/speex-1.0.5/COPYING new file mode 100644 index 000000000..37beceff7 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/COPYING @@ -0,0 +1,26 @@ +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +- Neither the name of the Xiph.org Foundation nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Code/BF2/External/speex-1.0.5/ChangeLog b/Code/BF2/External/speex-1.0.5/ChangeLog new file mode 100644 index 000000000..10db29871 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/ChangeLog @@ -0,0 +1,6 @@ +2002/03/27 Jean-Marc Valin: +Working encoder and decoder for both narrowband and wideband. + +2002/02/27 Jean-Marc Valin: +Got the basic encoder working as a demo with quantization only on some +parameters. diff --git a/Code/BF2/External/speex-1.0.5/INSTALL b/Code/BF2/External/speex-1.0.5/INSTALL new file mode 100644 index 000000000..15f2e5f44 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/INSTALL @@ -0,0 +1,8 @@ +Installing Speex is as easy as: + +% ./configure [--prefix=] +% make +% make install + +Note that if you are using the code from CVS, you will need to run "autogen.sh" +instead of "configure". diff --git a/Code/BF2/External/speex-1.0.5/LOCAL_CHANGES.md b/Code/BF2/External/speex-1.0.5/LOCAL_CHANGES.md new file mode 100644 index 000000000..187236528 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/LOCAL_CHANGES.md @@ -0,0 +1,42 @@ +# Speex 1.0.5: local changes + +## Provenance + +- Source: the official Xiph.Org release tarball `speex-1.0.5.tar.gz` from + `https://downloads.xiph.org/releases/speex/`, downloaded 2026-11-13. +- SHA-256 `fce83e97a795d87db84118ec45cea42691474949264e6978bc5a25482ea983b5`, matching Xiph's published + `SHA256SUMS.txt` in the same directory. +- Licence: BSD-style, see `COPYING`. +- Why this version: it is the version the GameSpy Voice SDK pins (Voice2 `changelog.txt`, 2.07.02: + "Fixed all VC6 projects to use Speex 1.0.5"; `Voice2/libspeex/libspeex.vcxproj` lists + `..\speex-1.0.5\libspeex\*.c`). It is also the version BF2.exe links statically: every libspeex + 1.0.5 data table found in BF2.exe matches byte for byte (20 of 21 tables). That includes `cdbk_nb` + at file offset 0x57B8B0, the `exc_*`, `gain_cdbk_*`, `hexc_*`, `high_lsp_cdbk*` and `cdbk_nb_*` + codebooks, and the sub-band QMF filters `h0`/`h1`. The 21st table is explained below. + +## Source changes + +None. Every file is byte-identical to the tarball. `LOCAL_CHANGES.md` is the only added file. + +## Build + +- The OpenBF2 build compiles only the libspeex codec files GameSpy Voice2 needs (see the CMake and + MSVC lists). The tarball's own build scripts (`configure`, `Makefile.*`, `win32/`) are kept as + shipped and never run. +- **No `SLOW_TRIG` define.** In 1.0.5, `math_approx.c` compiles `cos_sin[102]` and `speex_cos()` + only under `#ifdef SLOW_TRIG`, and `nb_celp.c` maps `cos` to `speex_cos` only under the same + guard. Nothing in the tarball or in GameSpy's project defines it. +- Retail is the same default build. BF2.exe has no `cos_sin` table, and its Speex code calls CRT + `cos` as inline x87 `fcos` (MSVC `/Oi` intrinsic), at 12 sites in 0x738000..0x752000. Two examples: + - `0x73D021` is `nb_encoder_init`'s analysis window, `.54 - .46*cos(M_PI*i/part1)`. Its constants + are 0.54 at `0x921AD8`, 0.46 at `0x921AE0` and pi at `0x921AE8`, stored to `st->window[i]`. + - `0x73EAB9` is `nb_encode`: `lsp_enforce_margin(..., 0.05f)` at `0x73EA9F`, then + `interp_lsp[i] = cos(interp_lsp[i])` in place. + +## Standard-math note + +Native builds call the platform libm `cos` (SSE2 on x64, NEON/scalar on arm64), while retail uses +x87 `fcos`. The two can differ in the last bits of a float (window coefficients and the +interpolated LSPs). This follows the owner's standard-math policy for numeric/CRT edge rows +(2026-11-09): CRT behaviour is kept, not emulated. The Speex +bitstream format is unaffected, so frames still interoperate with retail clients and servers. diff --git a/Code/BF2/External/speex-1.0.5/Makefile.am b/Code/BF2/External/speex-1.0.5/Makefile.am new file mode 100644 index 000000000..d12d1aa4e --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/Makefile.am @@ -0,0 +1,19 @@ +## Process this file with automake to produce Makefile.in. -*-Makefile-*- + +# Disable automatic dependency tracking if using other tools than gcc and gmake +#AUTOMAKE_OPTIONS = no-dependencies + +m4datadir = $(datadir)/aclocal +m4data_DATA = speex.m4 + +pkgconfigdir = $(libdir)/pkgconfig +pkgconfig_DATA = speex.pc + +EXTRA_DIST = Speex.spec Speex.spec.in speex.m4 speex.pc.in + +SUBDIRS = libspeex include @src@ doc win32 + +DIST_SUBDIRS = libspeex include src doc win32 + +rpm: dist + rpmbuild -ta ${PACKAGE}-${VERSION}.tar.gz diff --git a/Code/BF2/External/speex-1.0.5/Makefile.in b/Code/BF2/External/speex-1.0.5/Makefile.in new file mode 100644 index 000000000..89055ddb3 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/Makefile.in @@ -0,0 +1,645 @@ +# Makefile.in generated by automake 1.8.5 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004 Free Software Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# Disable automatic dependency tracking if using other tools than gcc and gmake +#AUTOMAKE_OPTIONS = no-dependencies + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +top_builddir = . +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +INSTALL = @INSTALL@ +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +host_triplet = @host@ +DIST_COMMON = README $(am__configure_deps) $(srcdir)/Makefile.am \ + $(srcdir)/Makefile.in $(srcdir)/Speex.spec.in \ + $(srcdir)/speex.pc.in $(top_srcdir)/configure AUTHORS COPYING \ + ChangeLog INSTALL NEWS TODO config.guess config.sub depcomp \ + install-sh ltmain.sh missing mkinstalldirs +subdir = . +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ + $(top_srcdir)/configure.in +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +am__CONFIG_DISTCLEAN_FILES = config.status config.cache config.log \ + configure.lineno configure.status.lineno +mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs +CONFIG_CLEAN_FILES = Speex.spec speex.pc +SOURCES = +DIST_SOURCES = +RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \ + html-recursive info-recursive install-data-recursive \ + install-exec-recursive install-info-recursive \ + install-recursive installcheck-recursive installdirs-recursive \ + pdf-recursive ps-recursive uninstall-info-recursive \ + uninstall-recursive +am__installdirs = "$(DESTDIR)$(m4datadir)" "$(DESTDIR)$(pkgconfigdir)" +m4dataDATA_INSTALL = $(INSTALL_DATA) +pkgconfigDATA_INSTALL = $(INSTALL_DATA) +DATA = $(m4data_DATA) $(pkgconfig_DATA) +ETAGS = etags +CTAGS = ctags +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +distdir = $(PACKAGE)-$(VERSION) +top_distdir = $(distdir) +am__remove_distdir = \ + { test ! -d $(distdir) \ + || { find $(distdir) -type d ! -perm -200 -exec chmod u+w {} ';' \ + && rm -fr $(distdir); }; } +DIST_ARCHIVES = $(distdir).tar.gz +GZIP_ENV = --best +distuninstallcheck_listfiles = find . -type f -print +distcleancheck_listfiles = find . -type f -print +ACLOCAL = @ACLOCAL@ +AMDEP_FALSE = @AMDEP_FALSE@ +AMDEP_TRUE = @AMDEP_TRUE@ +AMTAR = @AMTAR@ +AR = @AR@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +ECHO = @ECHO@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +F77 = @F77@ +FFLAGS = @FFLAGS@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +LDFLAGS = @LDFLAGS@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +MAINT = @MAINT@ +MAINTAINER_MODE_FALSE = @MAINTAINER_MODE_FALSE@ +MAINTAINER_MODE_TRUE = @MAINTAINER_MODE_TRUE@ +MAKEINFO = @MAKEINFO@ +OBJEXT = @OBJEXT@ +OGG_INCLUDES = @OGG_INCLUDES@ +OGG_LDFLAGS = @OGG_LDFLAGS@ +OGG_LIBS = @OGG_LIBS@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +RANLIB = @RANLIB@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SPEEX_LT_AGE = @SPEEX_LT_AGE@ +SPEEX_LT_CURRENT = @SPEEX_LT_CURRENT@ +SPEEX_LT_REVISION = @SPEEX_LT_REVISION@ +SPEEX_VERSION = @SPEEX_VERSION@ +STRIP = @STRIP@ +VERSION = @VERSION@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_CXX = @ac_ct_CXX@ +ac_ct_F77 = @ac_ct_F77@ +ac_ct_RANLIB = @ac_ct_RANLIB@ +ac_ct_STRIP = @ac_ct_STRIP@ +am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ +am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ +am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ +am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +datadir = @datadir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +src = @src@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +m4datadir = $(datadir)/aclocal +m4data_DATA = speex.m4 +pkgconfigdir = $(libdir)/pkgconfig +pkgconfig_DATA = speex.pc +EXTRA_DIST = Speex.spec Speex.spec.in speex.m4 speex.pc.in +SUBDIRS = libspeex include @src@ doc win32 +DIST_SUBDIRS = libspeex include src doc win32 +all: all-recursive + +.SUFFIXES: +am--refresh: + @: +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + echo ' cd $(srcdir) && $(AUTOMAKE) --gnu '; \ + cd $(srcdir) && $(AUTOMAKE) --gnu \ + && exit 0; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu Makefile'; \ + cd $(top_srcdir) && \ + $(AUTOMAKE) --gnu Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + echo ' $(SHELL) ./config.status'; \ + $(SHELL) ./config.status;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + $(SHELL) ./config.status --recheck + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(srcdir) && $(AUTOCONF) +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + cd $(srcdir) && $(ACLOCAL) $(ACLOCAL_AMFLAGS) +Speex.spec: $(top_builddir)/config.status $(srcdir)/Speex.spec.in + cd $(top_builddir) && $(SHELL) ./config.status $@ +speex.pc: $(top_builddir)/config.status $(srcdir)/speex.pc.in + cd $(top_builddir) && $(SHELL) ./config.status $@ + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +distclean-libtool: + -rm -f libtool +uninstall-info-am: +install-m4dataDATA: $(m4data_DATA) + @$(NORMAL_INSTALL) + test -z "$(m4datadir)" || $(mkdir_p) "$(DESTDIR)$(m4datadir)" + @list='$(m4data_DATA)'; for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + f="`echo $$p | sed -e 's|^.*/||'`"; \ + echo " $(m4dataDATA_INSTALL) '$$d$$p' '$(DESTDIR)$(m4datadir)/$$f'"; \ + $(m4dataDATA_INSTALL) "$$d$$p" "$(DESTDIR)$(m4datadir)/$$f"; \ + done + +uninstall-m4dataDATA: + @$(NORMAL_UNINSTALL) + @list='$(m4data_DATA)'; for p in $$list; do \ + f="`echo $$p | sed -e 's|^.*/||'`"; \ + echo " rm -f '$(DESTDIR)$(m4datadir)/$$f'"; \ + rm -f "$(DESTDIR)$(m4datadir)/$$f"; \ + done +install-pkgconfigDATA: $(pkgconfig_DATA) + @$(NORMAL_INSTALL) + test -z "$(pkgconfigdir)" || $(mkdir_p) "$(DESTDIR)$(pkgconfigdir)" + @list='$(pkgconfig_DATA)'; for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + f="`echo $$p | sed -e 's|^.*/||'`"; \ + echo " $(pkgconfigDATA_INSTALL) '$$d$$p' '$(DESTDIR)$(pkgconfigdir)/$$f'"; \ + $(pkgconfigDATA_INSTALL) "$$d$$p" "$(DESTDIR)$(pkgconfigdir)/$$f"; \ + done + +uninstall-pkgconfigDATA: + @$(NORMAL_UNINSTALL) + @list='$(pkgconfig_DATA)'; for p in $$list; do \ + f="`echo $$p | sed -e 's|^.*/||'`"; \ + echo " rm -f '$(DESTDIR)$(pkgconfigdir)/$$f'"; \ + rm -f "$(DESTDIR)$(pkgconfigdir)/$$f"; \ + done + +# This directory's subdirectories are mostly independent; you can cd +# into them and run `make' without going through this Makefile. +# To change the values of `make' variables: instead of editing Makefiles, +# (1) if the variable is set in `config.status', edit `config.status' +# (which will cause the Makefiles to be regenerated when you run `make'); +# (2) otherwise, pass the desired values on the `make' command line. +$(RECURSIVE_TARGETS): + @set fnord $$MAKEFLAGS; amf=$$2; \ + dot_seen=no; \ + target=`echo $@ | sed s/-recursive//`; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + dot_seen=yes; \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || case "$$amf" in *=*) exit 1;; *k*) fail=yes;; *) exit 1;; esac; \ + done; \ + if test "$$dot_seen" = "no"; then \ + $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ + fi; test -z "$$fail" + +mostlyclean-recursive clean-recursive distclean-recursive \ +maintainer-clean-recursive: + @set fnord $$MAKEFLAGS; amf=$$2; \ + dot_seen=no; \ + case "$@" in \ + distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ + *) list='$(SUBDIRS)' ;; \ + esac; \ + rev=''; for subdir in $$list; do \ + if test "$$subdir" = "."; then :; else \ + rev="$$subdir $$rev"; \ + fi; \ + done; \ + rev="$$rev ."; \ + target=`echo $@ | sed s/-recursive//`; \ + for subdir in $$rev; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || case "$$amf" in *=*) exit 1;; *k*) fail=yes;; *) exit 1;; esac; \ + done && test -z "$$fail" +tags-recursive: + list='$(SUBDIRS)'; for subdir in $$list; do \ + test "$$subdir" = . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \ + done +ctags-recursive: + list='$(SUBDIRS)'; for subdir in $$list; do \ + test "$$subdir" = . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \ + done + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + tags=; \ + here=`pwd`; \ + if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ + include_option=--etags-include; \ + empty_fix=.; \ + else \ + include_option=--include; \ + empty_fix=; \ + fi; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test ! -f $$subdir/TAGS || \ + tags="$$tags $$include_option=$$here/$$subdir/TAGS"; \ + fi; \ + done; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$tags $$unique; \ + fi +ctags: CTAGS +CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + tags=; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + test -z "$(CTAGS_ARGS)$$tags$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$tags $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && cd $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) $$here + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + $(am__remove_distdir) + mkdir $(distdir) + $(mkdir_p) $(distdir)/. + @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ + list='$(DISTFILES)'; for file in $$list; do \ + case $$file in \ + $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ + $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ + esac; \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test "$$dir" != "$$file" && test "$$dir" != "."; then \ + dir="/$$dir"; \ + $(mkdir_p) "$(distdir)$$dir"; \ + else \ + dir=''; \ + fi; \ + if test -d $$d/$$file; then \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + fi; \ + cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + else \ + test -f $(distdir)/$$file \ + || cp -p $$d/$$file $(distdir)/$$file \ + || exit 1; \ + fi; \ + done + list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test -d "$(distdir)/$$subdir" \ + || mkdir "$(distdir)/$$subdir" \ + || exit 1; \ + (cd $$subdir && \ + $(MAKE) $(AM_MAKEFLAGS) \ + top_distdir="../$(top_distdir)" \ + distdir="../$(distdir)/$$subdir" \ + distdir) \ + || exit 1; \ + fi; \ + done + -find $(distdir) -type d ! -perm -777 -exec chmod a+rwx {} \; -o \ + ! -type d ! -perm -444 -links 1 -exec chmod a+r {} \; -o \ + ! -type d ! -perm -400 -exec chmod a+r {} \; -o \ + ! -type d ! -perm -444 -exec $(SHELL) $(install_sh) -c -m a+r {} {} \; \ + || chmod -R a+r $(distdir) +dist-gzip: distdir + $(AMTAR) chof - $(distdir) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz + $(am__remove_distdir) + +dist-bzip2: distdir + $(AMTAR) chof - $(distdir) | bzip2 -9 -c >$(distdir).tar.bz2 + $(am__remove_distdir) + +dist-tarZ: distdir + $(AMTAR) chof - $(distdir) | compress -c >$(distdir).tar.Z + $(am__remove_distdir) + +dist-shar: distdir + shar $(distdir) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).shar.gz + $(am__remove_distdir) + +dist-zip: distdir + -rm -f $(distdir).zip + zip -rq $(distdir).zip $(distdir) + $(am__remove_distdir) + +dist dist-all: distdir + $(AMTAR) chof - $(distdir) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz + $(am__remove_distdir) + +# This target untars the dist file and tries a VPATH configuration. Then +# it guarantees that the distribution is self-contained by making another +# tarfile. +distcheck: dist + case '$(DIST_ARCHIVES)' in \ + *.tar.gz*) \ + GZIP=$(GZIP_ENV) gunzip -c $(distdir).tar.gz | $(AMTAR) xf - ;;\ + *.tar.bz2*) \ + bunzip2 -c $(distdir).tar.bz2 | $(AMTAR) xf - ;;\ + *.tar.Z*) \ + uncompress -c $(distdir).tar.Z | $(AMTAR) xf - ;;\ + *.shar.gz*) \ + GZIP=$(GZIP_ENV) gunzip -c $(distdir).shar.gz | unshar ;;\ + *.zip*) \ + unzip $(distdir).zip ;;\ + esac + chmod -R a-w $(distdir); chmod a+w $(distdir) + mkdir $(distdir)/_build + mkdir $(distdir)/_inst + chmod a-w $(distdir) + dc_install_base=`$(am__cd) $(distdir)/_inst && pwd | sed -e 's,^[^:\\/]:[\\/],/,'` \ + && dc_destdir="$${TMPDIR-/tmp}/am-dc-$$$$/" \ + && cd $(distdir)/_build \ + && ../configure --srcdir=.. --prefix="$$dc_install_base" \ + $(DISTCHECK_CONFIGURE_FLAGS) \ + && $(MAKE) $(AM_MAKEFLAGS) \ + && $(MAKE) $(AM_MAKEFLAGS) dvi \ + && $(MAKE) $(AM_MAKEFLAGS) check \ + && $(MAKE) $(AM_MAKEFLAGS) install \ + && $(MAKE) $(AM_MAKEFLAGS) installcheck \ + && $(MAKE) $(AM_MAKEFLAGS) uninstall \ + && $(MAKE) $(AM_MAKEFLAGS) distuninstallcheck_dir="$$dc_install_base" \ + distuninstallcheck \ + && chmod -R a-w "$$dc_install_base" \ + && ({ \ + (cd ../.. && umask 077 && mkdir "$$dc_destdir") \ + && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" install \ + && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" uninstall \ + && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" \ + distuninstallcheck_dir="$$dc_destdir" distuninstallcheck; \ + } || { rm -rf "$$dc_destdir"; exit 1; }) \ + && rm -rf "$$dc_destdir" \ + && $(MAKE) $(AM_MAKEFLAGS) dist \ + && rm -rf $(DIST_ARCHIVES) \ + && $(MAKE) $(AM_MAKEFLAGS) distcleancheck + $(am__remove_distdir) + @(echo "$(distdir) archives ready for distribution: "; \ + list='$(DIST_ARCHIVES)'; for i in $$list; do echo $$i; done) | \ + sed -e '1{h;s/./=/g;p;x;}' -e '$${p;x;}' +distuninstallcheck: + @cd $(distuninstallcheck_dir) \ + && test `$(distuninstallcheck_listfiles) | wc -l` -le 1 \ + || { echo "ERROR: files left after uninstall:" ; \ + if test -n "$(DESTDIR)"; then \ + echo " (check DESTDIR support)"; \ + fi ; \ + $(distuninstallcheck_listfiles) ; \ + exit 1; } >&2 +distcleancheck: distclean + @if test '$(srcdir)' = . ; then \ + echo "ERROR: distcleancheck can only run from a VPATH build" ; \ + exit 1 ; \ + fi + @test `$(distcleancheck_listfiles) | wc -l` -eq 0 \ + || { echo "ERROR: files left in build directory after distclean:" ; \ + $(distcleancheck_listfiles) ; \ + exit 1; } >&2 +check-am: all-am +check: check-recursive +all-am: Makefile $(DATA) +installdirs: installdirs-recursive +installdirs-am: + for dir in "$(DESTDIR)$(m4datadir)" "$(DESTDIR)$(pkgconfigdir)"; do \ + test -z "$$dir" || $(mkdir_p) "$$dir"; \ + done +install: install-recursive +install-exec: install-exec-recursive +install-data: install-data-recursive +uninstall: uninstall-recursive + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-recursive +install-strip: + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + `test -z '$(STRIP)' || \ + echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -rm -f $(CONFIG_CLEAN_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-recursive + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-recursive + -rm -f $(am__CONFIG_DISTCLEAN_FILES) + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-libtool \ + distclean-tags + +dvi: dvi-recursive + +dvi-am: + +html: html-recursive + +info: info-recursive + +info-am: + +install-data-am: install-m4dataDATA install-pkgconfigDATA + +install-exec-am: + +install-info: install-info-recursive + +install-man: + +installcheck-am: + +maintainer-clean: maintainer-clean-recursive + -rm -f $(am__CONFIG_DISTCLEAN_FILES) + -rm -rf $(top_srcdir)/autom4te.cache + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-recursive + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-recursive + +pdf-am: + +ps: ps-recursive + +ps-am: + +uninstall-am: uninstall-info-am uninstall-m4dataDATA \ + uninstall-pkgconfigDATA + +uninstall-info: uninstall-info-recursive + +.PHONY: $(RECURSIVE_TARGETS) CTAGS GTAGS all all-am am--refresh check \ + check-am clean clean-generic clean-libtool clean-recursive \ + ctags ctags-recursive dist dist-all dist-bzip2 dist-gzip \ + dist-shar dist-tarZ dist-zip distcheck distclean \ + distclean-generic distclean-libtool distclean-recursive \ + distclean-tags distcleancheck distdir distuninstallcheck dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-exec install-exec-am \ + install-info install-info-am install-m4dataDATA install-man \ + install-pkgconfigDATA install-strip installcheck \ + installcheck-am installdirs installdirs-am maintainer-clean \ + maintainer-clean-generic maintainer-clean-recursive \ + mostlyclean mostlyclean-generic mostlyclean-libtool \ + mostlyclean-recursive pdf pdf-am ps ps-am tags tags-recursive \ + uninstall uninstall-am uninstall-info-am uninstall-m4dataDATA \ + uninstall-pkgconfigDATA + + +rpm: dist + rpmbuild -ta ${PACKAGE}-${VERSION}.tar.gz +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/Code/BF2/External/speex-1.0.5/NEWS b/Code/BF2/External/speex-1.0.5/NEWS new file mode 100644 index 000000000..9a9952914 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/NEWS @@ -0,0 +1 @@ +2002/02/13: Creation of the "Speex" project diff --git a/Code/BF2/External/speex-1.0.5/README b/Code/BF2/External/speex-1.0.5/README new file mode 100644 index 000000000..84fe74adb --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/README @@ -0,0 +1,9 @@ +See INSTALL file for instruction on how to install Speex. + +The Speex is a patent-free, Open Source/Free Software voice codec. Unlike other codecs like MP3 and Ogg Vorbis, Speex is designed to compress voice at bitrates in the 2-45 kbps range. Possible applications include VoIP, internet audio streaming, archiving of speech data (e.g. voice mail), and audio books. In some sense, it is meant to be complementary to the Ogg Vorbis codec. + +To use the Speex command line tools: + +% speexenc [options] input_file.wav compressed_file.spx + +% speexdec [options] compressed_file.spx output_file.wav diff --git a/Code/BF2/External/speex-1.0.5/Speex.spec b/Code/BF2/External/speex-1.0.5/Speex.spec new file mode 100644 index 000000000..980202b01 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/Speex.spec @@ -0,0 +1,71 @@ +%define name speex +%define ver 1.0.5 +%define rel 1 + +Summary: An open-source, patent-free speech codec +Name: %name +Version: %ver +Release: %rel +Copyright: BSD +Group: Application/Devel +Source: http://www.speex.org/download/%{name}-%{ver}.tar.gz +URL: http://www.speex.org/ +Vendor: Speex +Packager: Jean-Marc Valin (jean-marc.valin@hermes.usherb.ca) +BuildRoot: /var/tmp/%{name}-build-root +Docdir: /usr/share/doc + +%description +Speex is a patent-free audio codec designed especially for voice (unlike +Vorbis which targets general audio) signals and providing good narrowband +and wideband quality. This project aims to be complementary to the Vorbis +codec. + +%package devel +Summary: Speex development files +Group: Development/Libraries +Requires: %{name} = %{version} + +%description devel +Speex development files. + +%changelog +* Thu Oct 03 2002 Jean-Marc Valin +- Added devel package inspired from PLD spec file + +* Tue Jul 30 2002 Fredrik Rambris 0.5.2 +- Added buildroot and docdir and ldconfig. Makes it builadble by non-roots + and also doesn't write to actual library paths when building. + +%prep +%setup + +%build +export CFLAGS='-O3 -DRELEASE' +./configure --prefix=/usr --enable-shared --enable-static +make + +%install +rm -rf $RPM_BUILD_ROOT +make DESTDIR=$RPM_BUILD_ROOT install + +%post -p /sbin/ldconfig +%postun -p /sbin/ldconfig + +%files +%defattr(644,root,root,755) +%doc COPYING AUTHORS ChangeLog NEWS README +%doc doc/manual.pdf +/usr/share/man/man1/speexenc.1* +/usr/share/man/man1/speexdec.1* +%attr(755,root,root) %{_bindir}/speex* +%attr(755,root,root) %{_libdir}/libspeex*.so* + +%files devel +%defattr(644,root,root,755) +%attr(755,root,root) %{_libdir}/libspeex*.la +%{_includedir}/speex*.h +%{_includedir}/speex/speex*.h +/usr/share/aclocal/speex.m4 +%{_libdir}/pkgconfig/speex.pc +%{_libdir}/libspeex*.a diff --git a/Code/BF2/External/speex-1.0.5/Speex.spec.in b/Code/BF2/External/speex-1.0.5/Speex.spec.in new file mode 100644 index 000000000..c2c9db25f --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/Speex.spec.in @@ -0,0 +1,71 @@ +%define name @PACKAGE@ +%define ver @VERSION@ +%define rel 1 + +Summary: An open-source, patent-free speech codec +Name: %name +Version: %ver +Release: %rel +Copyright: BSD +Group: Application/Devel +Source: http://www.speex.org/download/%{name}-%{ver}.tar.gz +URL: http://www.speex.org/ +Vendor: Speex +Packager: Jean-Marc Valin (jean-marc.valin@hermes.usherb.ca) +BuildRoot: /var/tmp/%{name}-build-root +Docdir: /usr/share/doc + +%description +Speex is a patent-free audio codec designed especially for voice (unlike +Vorbis which targets general audio) signals and providing good narrowband +and wideband quality. This project aims to be complementary to the Vorbis +codec. + +%package devel +Summary: Speex development files +Group: Development/Libraries +Requires: %{name} = %{version} + +%description devel +Speex development files. + +%changelog +* Thu Oct 03 2002 Jean-Marc Valin +- Added devel package inspired from PLD spec file + +* Tue Jul 30 2002 Fredrik Rambris 0.5.2 +- Added buildroot and docdir and ldconfig. Makes it builadble by non-roots + and also doesn't write to actual library paths when building. + +%prep +%setup + +%build +export CFLAGS='-O3 -DRELEASE' +./configure --prefix=/usr --enable-shared --enable-static +make + +%install +rm -rf $RPM_BUILD_ROOT +make DESTDIR=$RPM_BUILD_ROOT install + +%post -p /sbin/ldconfig +%postun -p /sbin/ldconfig + +%files +%defattr(644,root,root,755) +%doc COPYING AUTHORS ChangeLog NEWS README +%doc doc/manual.pdf +/usr/share/man/man1/speexenc.1* +/usr/share/man/man1/speexdec.1* +%attr(755,root,root) %{_bindir}/speex* +%attr(755,root,root) %{_libdir}/libspeex*.so* + +%files devel +%defattr(644,root,root,755) +%attr(755,root,root) %{_libdir}/libspeex*.la +%{_includedir}/speex*.h +%{_includedir}/speex/speex*.h +/usr/share/aclocal/speex.m4 +%{_libdir}/pkgconfig/speex.pc +%{_libdir}/libspeex*.a diff --git a/Code/BF2/External/speex-1.0.5/TODO b/Code/BF2/External/speex-1.0.5/TODO new file mode 100644 index 000000000..12a1a535f --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/TODO @@ -0,0 +1,18 @@ +Features +-Add maximum/minimum bit-rate control for VBR +-Get the encoder to use the rate of packet loss (more conservative pitch gains) + +Long-term quality improvements +-Improve perceptual enhancement (including wideband) + +Standards +*Complete Speex RTP profile +-MIME type registration +-MS ACM wrapper + +*required for 1.0 + +ideas: +Peelable stream (double codebook, higher bands, stereo) +LPC from spectral domain +Better psycho-acoustics? Masking curve from Vorbis diff --git a/Code/BF2/External/speex-1.0.5/acinclude.m4 b/Code/BF2/External/speex-1.0.5/acinclude.m4 new file mode 100644 index 000000000..8efb6599e --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/acinclude.m4 @@ -0,0 +1,84 @@ +AC_DEFUN(AC_FIND_FILE, +[ +$3=NONE +for i in $2; +do + for j in $1; + do + if test -r "$i/$j"; then + $3=$i + break 2 + fi + done +done +]) + +AC_DEFUN(AC_PATH_LIBOGG, +[ +OGG_LIBS="-logg" + +AC_MSG_CHECKING([for libogg]) + +ac_ogg_includes=NONE ac_ogg_libraries=NONE ac_ogg_bindir=NONE +ogg_libraries="" +ogg_includes="" +AC_ARG_WITH(ogg-dir, + [ --with-ogg-dir=DIR where the root of OGG is installed ], + [ ac_ogg_includes="$withval"/include + ac_ogg_libraries="$withval"/lib + ]) + +AC_ARG_WITH(ogg-includes, + [ --with-ogg-includes=DIR where the OGG includes are. ], + [ + ac_ogg_includes="$withval" + ]) + +ogg_libs_given=no + +AC_ARG_WITH(ogg-libraries, + [ --with-ogg-libraries=DIR where the OGG library is installed.], + [ ac_ogg_libraries="$withval" + ogg_libs_given=yes + ]) + +ogg_incdirs="/usr/include /usr/lib/ogg/include /opt/include /usr/local/ogg/include /usr/include/ogg /usr/include /usr/local/include" +if test ! "$ac_ogg_includes" = "NONE"; then + ogg_incdirs="$ac_ogg_includes $ac_ogg_includes/.. $ogg_incdirs" +fi +AC_FIND_FILE(ogg/ogg.h, $ogg_incdirs, ogg_incdir) +echo "Ogg includes in $ogg_incdir" + + +ogg_libdirs="$ac_ogg_libraries /usr/lib/ogg/lib /usr/lib /opt/lib /usr/local/ogg/lib /usr/local/lib /usr/lib/ogg /usr/local/lib" +test -n "$OGGDIR" && ogg_libdirs="$OGGDIR/lib $OGGDIR $ogg_libdirs" +if test ! "$ac_ogg_libraries" = "NONE"; then + ogg_libdirs="$ac_ogg_libraries $ogg_libdirs" +fi + +test=NONE +ogg_libdir=NONE +for dir in $ogg_libdirs; do + try="ls -1 $dir/libogg*" + if test=`eval $try 2> /dev/null`; then ogg_libdir=$dir; break; else echo "tried $dir" >&AC_FD_CC ; fi +done + +echo "Ogg libraries in $ogg_libdir" + +if test "$ogg_libdir" = "NONE" || test "$ogg_incdir" = "NONE"; then + have_libogg=no +else + have_libogg=yes + AC_DEFINE(HAVE_LIBOGG) +fi + +OGG_INCLUDES="-I$ogg_incdir" +OGG_LDFLAGS="-L$ogg_libdir" + + +AC_SUBST(OGG_LIBS) +AC_SUBST(OGG_INCLUDES) +AC_SUBST(OGG_LDFLAGS) + +]) + diff --git a/Code/BF2/External/speex-1.0.5/aclocal.m4 b/Code/BF2/External/speex-1.0.5/aclocal.m4 new file mode 100644 index 000000000..b4a2432ec --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/aclocal.m4 @@ -0,0 +1,6865 @@ +# generated automatically by aclocal 1.8.5 -*- Autoconf -*- + +# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004 +# Free Software Foundation, Inc. +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +# libtool.m4 - Configure libtool for the host system. -*-Autoconf-*- + +# serial 47 AC_PROG_LIBTOOL +# Debian $Rev: 214 $ + + +# AC_PROVIDE_IFELSE(MACRO-NAME, IF-PROVIDED, IF-NOT-PROVIDED) +# ----------------------------------------------------------- +# If this macro is not defined by Autoconf, define it here. +m4_ifdef([AC_PROVIDE_IFELSE], + [], + [m4_define([AC_PROVIDE_IFELSE], + [m4_ifdef([AC_PROVIDE_$1], + [$2], [$3])])]) + + +# AC_PROG_LIBTOOL +# --------------- +AC_DEFUN([AC_PROG_LIBTOOL], +[AC_REQUIRE([_AC_PROG_LIBTOOL])dnl +dnl If AC_PROG_CXX has already been expanded, run AC_LIBTOOL_CXX +dnl immediately, otherwise, hook it in at the end of AC_PROG_CXX. + AC_PROVIDE_IFELSE([AC_PROG_CXX], + [AC_LIBTOOL_CXX], + [define([AC_PROG_CXX], defn([AC_PROG_CXX])[AC_LIBTOOL_CXX + ])]) +dnl And a similar setup for Fortran 77 support + AC_PROVIDE_IFELSE([AC_PROG_F77], + [AC_LIBTOOL_F77], + [define([AC_PROG_F77], defn([AC_PROG_F77])[AC_LIBTOOL_F77 +])]) + +dnl Quote A][M_PROG_GCJ so that aclocal doesn't bring it in needlessly. +dnl If either AC_PROG_GCJ or A][M_PROG_GCJ have already been expanded, run +dnl AC_LIBTOOL_GCJ immediately, otherwise, hook it in at the end of both. + AC_PROVIDE_IFELSE([AC_PROG_GCJ], + [AC_LIBTOOL_GCJ], + [AC_PROVIDE_IFELSE([A][M_PROG_GCJ], + [AC_LIBTOOL_GCJ], + [AC_PROVIDE_IFELSE([LT_AC_PROG_GCJ], + [AC_LIBTOOL_GCJ], + [ifdef([AC_PROG_GCJ], + [define([AC_PROG_GCJ], defn([AC_PROG_GCJ])[AC_LIBTOOL_GCJ])]) + ifdef([A][M_PROG_GCJ], + [define([A][M_PROG_GCJ], defn([A][M_PROG_GCJ])[AC_LIBTOOL_GCJ])]) + ifdef([LT_AC_PROG_GCJ], + [define([LT_AC_PROG_GCJ], + defn([LT_AC_PROG_GCJ])[AC_LIBTOOL_GCJ])])])]) +])])# AC_PROG_LIBTOOL + + +# _AC_PROG_LIBTOOL +# ---------------- +AC_DEFUN([_AC_PROG_LIBTOOL], +[AC_REQUIRE([AC_LIBTOOL_SETUP])dnl +AC_BEFORE([$0],[AC_LIBTOOL_CXX])dnl +AC_BEFORE([$0],[AC_LIBTOOL_F77])dnl +AC_BEFORE([$0],[AC_LIBTOOL_GCJ])dnl + +# This can be used to rebuild libtool when needed +LIBTOOL_DEPS="$ac_aux_dir/ltmain.sh" + +# Always use our own libtool. +LIBTOOL='$(SHELL) $(top_builddir)/libtool' +AC_SUBST(LIBTOOL)dnl + +# Prevent multiple expansion +define([AC_PROG_LIBTOOL], []) +])# _AC_PROG_LIBTOOL + + +# AC_LIBTOOL_SETUP +# ---------------- +AC_DEFUN([AC_LIBTOOL_SETUP], +[AC_PREREQ(2.50)dnl +AC_REQUIRE([AC_ENABLE_SHARED])dnl +AC_REQUIRE([AC_ENABLE_STATIC])dnl +AC_REQUIRE([AC_ENABLE_FAST_INSTALL])dnl +AC_REQUIRE([AC_CANONICAL_HOST])dnl +AC_REQUIRE([AC_CANONICAL_BUILD])dnl +AC_REQUIRE([AC_PROG_CC])dnl +AC_REQUIRE([AC_PROG_LD])dnl +AC_REQUIRE([AC_PROG_LD_RELOAD_FLAG])dnl +AC_REQUIRE([AC_PROG_NM])dnl + +AC_REQUIRE([AC_PROG_LN_S])dnl +AC_REQUIRE([AC_DEPLIBS_CHECK_METHOD])dnl +# Autoconf 2.13's AC_OBJEXT and AC_EXEEXT macros only works for C compilers! +AC_REQUIRE([AC_OBJEXT])dnl +AC_REQUIRE([AC_EXEEXT])dnl +dnl + +AC_LIBTOOL_SYS_MAX_CMD_LEN +AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE +AC_LIBTOOL_OBJDIR + +AC_REQUIRE([_LT_AC_SYS_COMPILER])dnl +_LT_AC_PROG_ECHO_BACKSLASH + +case $host_os in +aix3*) + # AIX sometimes has problems with the GCC collect2 program. For some + # reason, if we set the COLLECT_NAMES environment variable, the problems + # vanish in a puff of smoke. + if test "X${COLLECT_NAMES+set}" != Xset; then + COLLECT_NAMES= + export COLLECT_NAMES + fi + ;; +esac + +# Sed substitution that helps us do robust quoting. It backslashifies +# metacharacters that are still active within double-quoted strings. +Xsed='sed -e s/^X//' +[sed_quote_subst='s/\([\\"\\`$\\\\]\)/\\\1/g'] + +# Same as above, but do not quote variable references. +[double_quote_subst='s/\([\\"\\`\\\\]\)/\\\1/g'] + +# Sed substitution to delay expansion of an escaped shell variable in a +# double_quote_subst'ed string. +delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g' + +# Sed substitution to avoid accidental globbing in evaled expressions +no_glob_subst='s/\*/\\\*/g' + +# Constants: +rm="rm -f" + +# Global variables: +default_ofile=libtool +can_build_shared=yes + +# All known linkers require a `.a' archive for static linking (except M$VC, +# which needs '.lib'). +libext=a +ltmain="$ac_aux_dir/ltmain.sh" +ofile="$default_ofile" +with_gnu_ld="$lt_cv_prog_gnu_ld" + +AC_CHECK_TOOL(AR, ar, false) +AC_CHECK_TOOL(RANLIB, ranlib, :) +AC_CHECK_TOOL(STRIP, strip, :) + +old_CC="$CC" +old_CFLAGS="$CFLAGS" + +# Set sane defaults for various variables +test -z "$AR" && AR=ar +test -z "$AR_FLAGS" && AR_FLAGS=cru +test -z "$AS" && AS=as +test -z "$CC" && CC=cc +test -z "$LTCC" && LTCC=$CC +test -z "$DLLTOOL" && DLLTOOL=dlltool +test -z "$LD" && LD=ld +test -z "$LN_S" && LN_S="ln -s" +test -z "$MAGIC_CMD" && MAGIC_CMD=file +test -z "$NM" && NM=nm +test -z "$SED" && SED=sed +test -z "$OBJDUMP" && OBJDUMP=objdump +test -z "$RANLIB" && RANLIB=: +test -z "$STRIP" && STRIP=: +test -z "$ac_objext" && ac_objext=o + +# Determine commands to create old-style static archives. +old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs$old_deplibs' +old_postinstall_cmds='chmod 644 $oldlib' +old_postuninstall_cmds= + +if test -n "$RANLIB"; then + case $host_os in + openbsd*) + old_postinstall_cmds="\$RANLIB -t \$oldlib~$old_postinstall_cmds" + ;; + *) + old_postinstall_cmds="\$RANLIB \$oldlib~$old_postinstall_cmds" + ;; + esac + old_archive_cmds="$old_archive_cmds~\$RANLIB \$oldlib" +fi + +# Only perform the check for file, if the check method requires it +case $deplibs_check_method in +file_magic*) + if test "$file_magic_cmd" = '$MAGIC_CMD'; then + AC_PATH_MAGIC + fi + ;; +esac + +AC_PROVIDE_IFELSE([AC_LIBTOOL_DLOPEN], enable_dlopen=yes, enable_dlopen=no) +AC_PROVIDE_IFELSE([AC_LIBTOOL_WIN32_DLL], +enable_win32_dll=yes, enable_win32_dll=no) + +AC_ARG_ENABLE([libtool-lock], + [AC_HELP_STRING([--disable-libtool-lock], + [avoid locking (might break parallel builds)])]) +test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes + +AC_ARG_WITH([pic], + [AC_HELP_STRING([--with-pic], + [try to use only PIC/non-PIC objects @<:@default=use both@:>@])], + [pic_mode="$withval"], + [pic_mode=default]) +test -z "$pic_mode" && pic_mode=default + +# Use C for the default configuration in the libtool script +tagname= +AC_LIBTOOL_LANG_C_CONFIG +_LT_AC_TAGCONFIG +])# AC_LIBTOOL_SETUP + + +# _LT_AC_SYS_COMPILER +# ------------------- +AC_DEFUN([_LT_AC_SYS_COMPILER], +[AC_REQUIRE([AC_PROG_CC])dnl + +# If no C compiler was specified, use CC. +LTCC=${LTCC-"$CC"} + +# Allow CC to be a program name with arguments. +compiler=$CC +])# _LT_AC_SYS_COMPILER + + +# _LT_AC_SYS_LIBPATH_AIX +# ---------------------- +# Links a minimal program and checks the executable +# for the system default hardcoded library path. In most cases, +# this is /usr/lib:/lib, but when the MPI compilers are used +# the location of the communication and MPI libs are included too. +# If we don't find anything, use the default library path according +# to the aix ld manual. +AC_DEFUN([_LT_AC_SYS_LIBPATH_AIX], +[AC_LINK_IFELSE(AC_LANG_PROGRAM,[ +aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; } +}'` +# Check for a 64-bit object if we didn't find anything. +if test -z "$aix_libpath"; then aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; } +}'`; fi],[]) +if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi +])# _LT_AC_SYS_LIBPATH_AIX + + +# _LT_AC_SHELL_INIT(ARG) +# ---------------------- +AC_DEFUN([_LT_AC_SHELL_INIT], +[ifdef([AC_DIVERSION_NOTICE], + [AC_DIVERT_PUSH(AC_DIVERSION_NOTICE)], + [AC_DIVERT_PUSH(NOTICE)]) +$1 +AC_DIVERT_POP +])# _LT_AC_SHELL_INIT + + +# _LT_AC_PROG_ECHO_BACKSLASH +# -------------------------- +# Add some code to the start of the generated configure script which +# will find an echo command which doesn't interpret backslashes. +AC_DEFUN([_LT_AC_PROG_ECHO_BACKSLASH], +[_LT_AC_SHELL_INIT([ +# Check that we are running under the correct shell. +SHELL=${CONFIG_SHELL-/bin/sh} + +case X$ECHO in +X*--fallback-echo) + # Remove one level of quotation (which was required for Make). + ECHO=`echo "$ECHO" | sed 's,\\\\\[$]\\[$]0,'[$]0','` + ;; +esac + +echo=${ECHO-echo} +if test "X[$]1" = X--no-reexec; then + # Discard the --no-reexec flag, and continue. + shift +elif test "X[$]1" = X--fallback-echo; then + # Avoid inline document here, it may be left over + : +elif test "X`($echo '\t') 2>/dev/null`" = 'X\t' ; then + # Yippee, $echo works! + : +else + # Restart under the correct shell. + exec $SHELL "[$]0" --no-reexec ${1+"[$]@"} +fi + +if test "X[$]1" = X--fallback-echo; then + # used as fallback echo + shift + cat </dev/null && + echo_test_string="`eval $cmd`" && + (test "X$echo_test_string" = "X$echo_test_string") 2>/dev/null + then + break + fi + done +fi + +if test "X`($echo '\t') 2>/dev/null`" = 'X\t' && + echo_testing_string=`($echo "$echo_test_string") 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + : +else + # The Solaris, AIX, and Digital Unix default echo programs unquote + # backslashes. This makes it impossible to quote backslashes using + # echo "$something" | sed 's/\\/\\\\/g' + # + # So, first we look for a working echo in the user's PATH. + + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR + for dir in $PATH /usr/ucb; do + IFS="$lt_save_ifs" + if (test -f $dir/echo || test -f $dir/echo$ac_exeext) && + test "X`($dir/echo '\t') 2>/dev/null`" = 'X\t' && + echo_testing_string=`($dir/echo "$echo_test_string") 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + echo="$dir/echo" + break + fi + done + IFS="$lt_save_ifs" + + if test "X$echo" = Xecho; then + # We didn't find a better echo, so look for alternatives. + if test "X`(print -r '\t') 2>/dev/null`" = 'X\t' && + echo_testing_string=`(print -r "$echo_test_string") 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + # This shell has a builtin print -r that does the trick. + echo='print -r' + elif (test -f /bin/ksh || test -f /bin/ksh$ac_exeext) && + test "X$CONFIG_SHELL" != X/bin/ksh; then + # If we have ksh, try running configure again with it. + ORIGINAL_CONFIG_SHELL=${CONFIG_SHELL-/bin/sh} + export ORIGINAL_CONFIG_SHELL + CONFIG_SHELL=/bin/ksh + export CONFIG_SHELL + exec $CONFIG_SHELL "[$]0" --no-reexec ${1+"[$]@"} + else + # Try using printf. + echo='printf %s\n' + if test "X`($echo '\t') 2>/dev/null`" = 'X\t' && + echo_testing_string=`($echo "$echo_test_string") 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + # Cool, printf works + : + elif echo_testing_string=`($ORIGINAL_CONFIG_SHELL "[$]0" --fallback-echo '\t') 2>/dev/null` && + test "X$echo_testing_string" = 'X\t' && + echo_testing_string=`($ORIGINAL_CONFIG_SHELL "[$]0" --fallback-echo "$echo_test_string") 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + CONFIG_SHELL=$ORIGINAL_CONFIG_SHELL + export CONFIG_SHELL + SHELL="$CONFIG_SHELL" + export SHELL + echo="$CONFIG_SHELL [$]0 --fallback-echo" + elif echo_testing_string=`($CONFIG_SHELL "[$]0" --fallback-echo '\t') 2>/dev/null` && + test "X$echo_testing_string" = 'X\t' && + echo_testing_string=`($CONFIG_SHELL "[$]0" --fallback-echo "$echo_test_string") 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + echo="$CONFIG_SHELL [$]0 --fallback-echo" + else + # maybe with a smaller string... + prev=: + + for cmd in 'echo test' 'sed 2q "[$]0"' 'sed 10q "[$]0"' 'sed 20q "[$]0"' 'sed 50q "[$]0"'; do + if (test "X$echo_test_string" = "X`eval $cmd`") 2>/dev/null + then + break + fi + prev="$cmd" + done + + if test "$prev" != 'sed 50q "[$]0"'; then + echo_test_string=`eval $prev` + export echo_test_string + exec ${ORIGINAL_CONFIG_SHELL-${CONFIG_SHELL-/bin/sh}} "[$]0" ${1+"[$]@"} + else + # Oops. We lost completely, so just stick with echo. + echo=echo + fi + fi + fi + fi +fi +fi + +# Copy echo and quote the copy suitably for passing to libtool from +# the Makefile, instead of quoting the original, which is used later. +ECHO=$echo +if test "X$ECHO" = "X$CONFIG_SHELL [$]0 --fallback-echo"; then + ECHO="$CONFIG_SHELL \\\$\[$]0 --fallback-echo" +fi + +AC_SUBST(ECHO) +])])# _LT_AC_PROG_ECHO_BACKSLASH + + +# _LT_AC_LOCK +# ----------- +AC_DEFUN([_LT_AC_LOCK], +[AC_ARG_ENABLE([libtool-lock], + [AC_HELP_STRING([--disable-libtool-lock], + [avoid locking (might break parallel builds)])]) +test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes + +# Some flags need to be propagated to the compiler or linker for good +# libtool support. +case $host in +ia64-*-hpux*) + # Find out which ABI we are using. + echo 'int i;' > conftest.$ac_ext + if AC_TRY_EVAL(ac_compile); then + case `/usr/bin/file conftest.$ac_objext` in + *ELF-32*) + HPUX_IA64_MODE="32" + ;; + *ELF-64*) + HPUX_IA64_MODE="64" + ;; + esac + fi + rm -rf conftest* + ;; +*-*-irix6*) + # Find out which ABI we are using. + echo '[#]line __oline__ "configure"' > conftest.$ac_ext + if AC_TRY_EVAL(ac_compile); then + if test "$lt_cv_prog_gnu_ld" = yes; then + case `/usr/bin/file conftest.$ac_objext` in + *32-bit*) + LD="${LD-ld} -melf32bsmip" + ;; + *N32*) + LD="${LD-ld} -melf32bmipn32" + ;; + *64-bit*) + LD="${LD-ld} -melf64bmip" + ;; + esac + else + case `/usr/bin/file conftest.$ac_objext` in + *32-bit*) + LD="${LD-ld} -32" + ;; + *N32*) + LD="${LD-ld} -n32" + ;; + *64-bit*) + LD="${LD-ld} -64" + ;; + esac + fi + fi + rm -rf conftest* + ;; + +x86_64-*linux*|ppc*-*linux*|powerpc*-*linux*|s390*-*linux*|sparc*-*linux*) + # Find out which ABI we are using. + echo 'int i;' > conftest.$ac_ext + if AC_TRY_EVAL(ac_compile); then + case "`/usr/bin/file conftest.o`" in + *32-bit*) + case $host in + x86_64-*linux*) + LD="${LD-ld} -m elf_i386" + ;; + ppc64-*linux*|powerpc64-*linux*) + LD="${LD-ld} -m elf32ppclinux" + ;; + s390x-*linux*) + LD="${LD-ld} -m elf_s390" + ;; + sparc64-*linux*) + LD="${LD-ld} -m elf32_sparc" + ;; + esac + ;; + *64-bit*) + case $host in + x86_64-*linux*) + LD="${LD-ld} -m elf_x86_64" + ;; + ppc*-*linux*|powerpc*-*linux*) + LD="${LD-ld} -m elf64ppc" + ;; + s390*-*linux*) + LD="${LD-ld} -m elf64_s390" + ;; + sparc*-*linux*) + LD="${LD-ld} -m elf64_sparc" + ;; + esac + ;; + esac + fi + rm -rf conftest* + ;; + +*-*-sco3.2v5*) + # On SCO OpenServer 5, we need -belf to get full-featured binaries. + SAVE_CFLAGS="$CFLAGS" + CFLAGS="$CFLAGS -belf" + AC_CACHE_CHECK([whether the C compiler needs -belf], lt_cv_cc_needs_belf, + [AC_LANG_PUSH(C) + AC_TRY_LINK([],[],[lt_cv_cc_needs_belf=yes],[lt_cv_cc_needs_belf=no]) + AC_LANG_POP]) + if test x"$lt_cv_cc_needs_belf" != x"yes"; then + # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf + CFLAGS="$SAVE_CFLAGS" + fi + ;; +AC_PROVIDE_IFELSE([AC_LIBTOOL_WIN32_DLL], +[*-*-cygwin* | *-*-mingw* | *-*-pw32*) + AC_CHECK_TOOL(DLLTOOL, dlltool, false) + AC_CHECK_TOOL(AS, as, false) + AC_CHECK_TOOL(OBJDUMP, objdump, false) + ;; + ]) +esac + +need_locks="$enable_libtool_lock" + +])# _LT_AC_LOCK + + +# AC_LIBTOOL_COMPILER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS, +# [OUTPUT-FILE], [ACTION-SUCCESS], [ACTION-FAILURE]) +# ---------------------------------------------------------------- +# Check whether the given compiler option works +AC_DEFUN([AC_LIBTOOL_COMPILER_OPTION], +[AC_REQUIRE([LT_AC_PROG_SED]) +AC_CACHE_CHECK([$1], [$2], + [$2=no + ifelse([$4], , [ac_outfile=conftest.$ac_objext], [ac_outfile=$4]) + printf "$lt_simple_compile_test_code" > conftest.$ac_ext + lt_compiler_flag="$3" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + # The option is referenced via a variable to avoid confusing sed. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}? :&$lt_compiler_flag :; t' \ + -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:__oline__: $lt_compile\"" >&AS_MESSAGE_LOG_FD) + (eval "$lt_compile" 2>conftest.err) + ac_status=$? + cat conftest.err >&AS_MESSAGE_LOG_FD + echo "$as_me:__oline__: \$? = $ac_status" >&AS_MESSAGE_LOG_FD + if (exit $ac_status) && test -s "$ac_outfile"; then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings + if test ! -s conftest.err; then + $2=yes + fi + fi + $rm conftest* +]) + +if test x"[$]$2" = xyes; then + ifelse([$5], , :, [$5]) +else + ifelse([$6], , :, [$6]) +fi +])# AC_LIBTOOL_COMPILER_OPTION + + +# AC_LIBTOOL_LINKER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS, +# [ACTION-SUCCESS], [ACTION-FAILURE]) +# ------------------------------------------------------------ +# Check whether the given compiler option works +AC_DEFUN([AC_LIBTOOL_LINKER_OPTION], +[AC_CACHE_CHECK([$1], [$2], + [$2=no + save_LDFLAGS="$LDFLAGS" + LDFLAGS="$LDFLAGS $3" + printf "$lt_simple_link_test_code" > conftest.$ac_ext + if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings + if test -s conftest.err; then + # Append any errors to the config.log. + cat conftest.err 1>&AS_MESSAGE_LOG_FD + else + $2=yes + fi + fi + $rm conftest* + LDFLAGS="$save_LDFLAGS" +]) + +if test x"[$]$2" = xyes; then + ifelse([$4], , :, [$4]) +else + ifelse([$5], , :, [$5]) +fi +])# AC_LIBTOOL_LINKER_OPTION + + +# AC_LIBTOOL_SYS_MAX_CMD_LEN +# -------------------------- +AC_DEFUN([AC_LIBTOOL_SYS_MAX_CMD_LEN], +[# find the maximum length of command line arguments +AC_MSG_CHECKING([the maximum length of command line arguments]) +AC_CACHE_VAL([lt_cv_sys_max_cmd_len], [dnl + i=0 + teststring="ABCD" + + case $build_os in + msdosdjgpp*) + # On DJGPP, this test can blow up pretty badly due to problems in libc + # (any single argument exceeding 2000 bytes causes a buffer overrun + # during glob expansion). Even if it were fixed, the result of this + # check would be larger than it should be. + lt_cv_sys_max_cmd_len=12288; # 12K is about right + ;; + + gnu*) + # Under GNU Hurd, this test is not required because there is + # no limit to the length of command line arguments. + # Libtool will interpret -1 as no limit whatsoever + lt_cv_sys_max_cmd_len=-1; + ;; + + cygwin* | mingw*) + # On Win9x/ME, this test blows up -- it succeeds, but takes + # about 5 minutes as the teststring grows exponentially. + # Worse, since 9x/ME are not pre-emptively multitasking, + # you end up with a "frozen" computer, even though with patience + # the test eventually succeeds (with a max line length of 256k). + # Instead, let's just punt: use the minimum linelength reported by + # all of the supported platforms: 8192 (on NT/2K/XP). + lt_cv_sys_max_cmd_len=8192; + ;; + + amigaos*) + # On AmigaOS with pdksh, this test takes hours, literally. + # So we just punt and use a minimum line length of 8192. + lt_cv_sys_max_cmd_len=8192; + ;; + + *) + # If test is not a shell built-in, we'll probably end up computing a + # maximum length that is only half of the actual maximum length, but + # we can't tell. + while (test "X"`$CONFIG_SHELL [$]0 --fallback-echo "X$teststring" 2>/dev/null` \ + = "XX$teststring") >/dev/null 2>&1 && + new_result=`expr "X$teststring" : ".*" 2>&1` && + lt_cv_sys_max_cmd_len=$new_result && + test $i != 17 # 1/2 MB should be enough + do + i=`expr $i + 1` + teststring=$teststring$teststring + done + teststring= + # Add a significant safety factor because C++ compilers can tack on massive + # amounts of additional arguments before passing them to the linker. + # It appears as though 1/2 is a usable value. + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2` + ;; + esac +]) +if test -n $lt_cv_sys_max_cmd_len ; then + AC_MSG_RESULT($lt_cv_sys_max_cmd_len) +else + AC_MSG_RESULT(none) +fi +])# AC_LIBTOOL_SYS_MAX_CMD_LEN + + +# _LT_AC_CHECK_DLFCN +# -------------------- +AC_DEFUN([_LT_AC_CHECK_DLFCN], +[AC_CHECK_HEADERS(dlfcn.h)dnl +])# _LT_AC_CHECK_DLFCN + + +# _LT_AC_TRY_DLOPEN_SELF (ACTION-IF-TRUE, ACTION-IF-TRUE-W-USCORE, +# ACTION-IF-FALSE, ACTION-IF-CROSS-COMPILING) +# ------------------------------------------------------------------ +AC_DEFUN([_LT_AC_TRY_DLOPEN_SELF], +[AC_REQUIRE([_LT_AC_CHECK_DLFCN])dnl +if test "$cross_compiling" = yes; then : + [$4] +else + lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 + lt_status=$lt_dlunknown + cat > conftest.$ac_ext < +#endif + +#include + +#ifdef RTLD_GLOBAL +# define LT_DLGLOBAL RTLD_GLOBAL +#else +# ifdef DL_GLOBAL +# define LT_DLGLOBAL DL_GLOBAL +# else +# define LT_DLGLOBAL 0 +# endif +#endif + +/* We may have to define LT_DLLAZY_OR_NOW in the command line if we + find out it does not work in some platform. */ +#ifndef LT_DLLAZY_OR_NOW +# ifdef RTLD_LAZY +# define LT_DLLAZY_OR_NOW RTLD_LAZY +# else +# ifdef DL_LAZY +# define LT_DLLAZY_OR_NOW DL_LAZY +# else +# ifdef RTLD_NOW +# define LT_DLLAZY_OR_NOW RTLD_NOW +# else +# ifdef DL_NOW +# define LT_DLLAZY_OR_NOW DL_NOW +# else +# define LT_DLLAZY_OR_NOW 0 +# endif +# endif +# endif +# endif +#endif + +#ifdef __cplusplus +extern "C" void exit (int); +#endif + +void fnord() { int i=42;} +int main () +{ + void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); + int status = $lt_dlunknown; + + if (self) + { + if (dlsym (self,"fnord")) status = $lt_dlno_uscore; + else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; + /* dlclose (self); */ + } + + exit (status); +}] +EOF + if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext} 2>/dev/null; then + (./conftest; exit; ) 2>/dev/null + lt_status=$? + case x$lt_status in + x$lt_dlno_uscore) $1 ;; + x$lt_dlneed_uscore) $2 ;; + x$lt_unknown|x*) $3 ;; + esac + else : + # compilation failed + $3 + fi +fi +rm -fr conftest* +])# _LT_AC_TRY_DLOPEN_SELF + + +# AC_LIBTOOL_DLOPEN_SELF +# ------------------- +AC_DEFUN([AC_LIBTOOL_DLOPEN_SELF], +[AC_REQUIRE([_LT_AC_CHECK_DLFCN])dnl +if test "x$enable_dlopen" != xyes; then + enable_dlopen=unknown + enable_dlopen_self=unknown + enable_dlopen_self_static=unknown +else + lt_cv_dlopen=no + lt_cv_dlopen_libs= + + case $host_os in + beos*) + lt_cv_dlopen="load_add_on" + lt_cv_dlopen_libs= + lt_cv_dlopen_self=yes + ;; + + mingw* | pw32*) + lt_cv_dlopen="LoadLibrary" + lt_cv_dlopen_libs= + ;; + + cygwin*) + lt_cv_dlopen="dlopen" + lt_cv_dlopen_libs= + ;; + + darwin*) + # if libdl is installed we need to link against it + AC_CHECK_LIB([dl], [dlopen], + [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"],[ + lt_cv_dlopen="dyld" + lt_cv_dlopen_libs= + lt_cv_dlopen_self=yes + ]) + ;; + + *) + AC_CHECK_FUNC([shl_load], + [lt_cv_dlopen="shl_load"], + [AC_CHECK_LIB([dld], [shl_load], + [lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-dld"], + [AC_CHECK_FUNC([dlopen], + [lt_cv_dlopen="dlopen"], + [AC_CHECK_LIB([dl], [dlopen], + [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"], + [AC_CHECK_LIB([svld], [dlopen], + [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld"], + [AC_CHECK_LIB([dld], [dld_link], + [lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-dld"]) + ]) + ]) + ]) + ]) + ]) + ;; + esac + + if test "x$lt_cv_dlopen" != xno; then + enable_dlopen=yes + else + enable_dlopen=no + fi + + case $lt_cv_dlopen in + dlopen) + save_CPPFLAGS="$CPPFLAGS" + test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H" + + save_LDFLAGS="$LDFLAGS" + eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\" + + save_LIBS="$LIBS" + LIBS="$lt_cv_dlopen_libs $LIBS" + + AC_CACHE_CHECK([whether a program can dlopen itself], + lt_cv_dlopen_self, [dnl + _LT_AC_TRY_DLOPEN_SELF( + lt_cv_dlopen_self=yes, lt_cv_dlopen_self=yes, + lt_cv_dlopen_self=no, lt_cv_dlopen_self=cross) + ]) + + if test "x$lt_cv_dlopen_self" = xyes; then + LDFLAGS="$LDFLAGS $link_static_flag" + AC_CACHE_CHECK([whether a statically linked program can dlopen itself], + lt_cv_dlopen_self_static, [dnl + _LT_AC_TRY_DLOPEN_SELF( + lt_cv_dlopen_self_static=yes, lt_cv_dlopen_self_static=yes, + lt_cv_dlopen_self_static=no, lt_cv_dlopen_self_static=cross) + ]) + fi + + CPPFLAGS="$save_CPPFLAGS" + LDFLAGS="$save_LDFLAGS" + LIBS="$save_LIBS" + ;; + esac + + case $lt_cv_dlopen_self in + yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;; + *) enable_dlopen_self=unknown ;; + esac + + case $lt_cv_dlopen_self_static in + yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;; + *) enable_dlopen_self_static=unknown ;; + esac +fi +])# AC_LIBTOOL_DLOPEN_SELF + + +# AC_LIBTOOL_PROG_CC_C_O([TAGNAME]) +# --------------------------------- +# Check to see if options -c and -o are simultaneously supported by compiler +AC_DEFUN([AC_LIBTOOL_PROG_CC_C_O], +[AC_REQUIRE([_LT_AC_SYS_COMPILER])dnl +AC_CACHE_CHECK([if $compiler supports -c -o file.$ac_objext], + [_LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1)], + [_LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1)=no + $rm -r conftest 2>/dev/null + mkdir conftest + cd conftest + mkdir out + printf "$lt_simple_compile_test_code" > conftest.$ac_ext + + lt_compiler_flag="-o out/conftest2.$ac_objext" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}? :&$lt_compiler_flag :; t' \ + -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:__oline__: $lt_compile\"" >&AS_MESSAGE_LOG_FD) + (eval "$lt_compile" 2>out/conftest.err) + ac_status=$? + cat out/conftest.err >&AS_MESSAGE_LOG_FD + echo "$as_me:__oline__: \$? = $ac_status" >&AS_MESSAGE_LOG_FD + if (exit $ac_status) && test -s out/conftest2.$ac_objext + then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings + if test ! -s out/conftest.err; then + _LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes + fi + fi + chmod u+w . + $rm conftest* + # SGI C++ compiler will create directory out/ii_files/ for + # template instantiation + test -d out/ii_files && $rm out/ii_files/* && rmdir out/ii_files + $rm out/* && rmdir out + cd .. + rmdir conftest + $rm conftest* +]) +])# AC_LIBTOOL_PROG_CC_C_O + + +# AC_LIBTOOL_SYS_HARD_LINK_LOCKS([TAGNAME]) +# ----------------------------------------- +# Check to see if we can do hard links to lock some files if needed +AC_DEFUN([AC_LIBTOOL_SYS_HARD_LINK_LOCKS], +[AC_REQUIRE([_LT_AC_LOCK])dnl + +hard_links="nottested" +if test "$_LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1)" = no && test "$need_locks" != no; then + # do not overwrite the value of need_locks provided by the user + AC_MSG_CHECKING([if we can lock with hard links]) + hard_links=yes + $rm conftest* + ln conftest.a conftest.b 2>/dev/null && hard_links=no + touch conftest.a + ln conftest.a conftest.b 2>&5 || hard_links=no + ln conftest.a conftest.b 2>/dev/null && hard_links=no + AC_MSG_RESULT([$hard_links]) + if test "$hard_links" = no; then + AC_MSG_WARN([`$CC' does not support `-c -o', so `make -j' may be unsafe]) + need_locks=warn + fi +else + need_locks=no +fi +])# AC_LIBTOOL_SYS_HARD_LINK_LOCKS + + +# AC_LIBTOOL_OBJDIR +# ----------------- +AC_DEFUN([AC_LIBTOOL_OBJDIR], +[AC_CACHE_CHECK([for objdir], [lt_cv_objdir], +[rm -f .libs 2>/dev/null +mkdir .libs 2>/dev/null +if test -d .libs; then + lt_cv_objdir=.libs +else + # MS-DOS does not allow filenames that begin with a dot. + lt_cv_objdir=_libs +fi +rmdir .libs 2>/dev/null]) +objdir=$lt_cv_objdir +])# AC_LIBTOOL_OBJDIR + + +# AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH([TAGNAME]) +# ---------------------------------------------- +# Check hardcoding attributes. +AC_DEFUN([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH], +[AC_MSG_CHECKING([how to hardcode library paths into programs]) +_LT_AC_TAGVAR(hardcode_action, $1)= +if test -n "$_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)" || \ + test -n "$_LT_AC_TAGVAR(runpath_var $1)" || \ + test "X$_LT_AC_TAGVAR(hardcode_automatic, $1)"="Xyes" ; then + + # We can hardcode non-existant directories. + if test "$_LT_AC_TAGVAR(hardcode_direct, $1)" != no && + # If the only mechanism to avoid hardcoding is shlibpath_var, we + # have to relink, otherwise we might link with an installed library + # when we should be linking with a yet-to-be-installed one + ## test "$_LT_AC_TAGVAR(hardcode_shlibpath_var, $1)" != no && + test "$_LT_AC_TAGVAR(hardcode_minus_L, $1)" != no; then + # Linking always hardcodes the temporary library directory. + _LT_AC_TAGVAR(hardcode_action, $1)=relink + else + # We can link without hardcoding, and we can hardcode nonexisting dirs. + _LT_AC_TAGVAR(hardcode_action, $1)=immediate + fi +else + # We cannot hardcode anything, or else we can only hardcode existing + # directories. + _LT_AC_TAGVAR(hardcode_action, $1)=unsupported +fi +AC_MSG_RESULT([$_LT_AC_TAGVAR(hardcode_action, $1)]) + +if test "$_LT_AC_TAGVAR(hardcode_action, $1)" = relink; then + # Fast installation is not supported + enable_fast_install=no +elif test "$shlibpath_overrides_runpath" = yes || + test "$enable_shared" = no; then + # Fast installation is not necessary + enable_fast_install=needless +fi +])# AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH + + +# AC_LIBTOOL_SYS_LIB_STRIP +# ------------------------ +AC_DEFUN([AC_LIBTOOL_SYS_LIB_STRIP], +[striplib= +old_striplib= +AC_MSG_CHECKING([whether stripping libraries is possible]) +if test -n "$STRIP" && $STRIP -V 2>&1 | grep "GNU strip" >/dev/null; then + test -z "$old_striplib" && old_striplib="$STRIP --strip-debug" + test -z "$striplib" && striplib="$STRIP --strip-unneeded" + AC_MSG_RESULT([yes]) +else +# FIXME - insert some real tests, host_os isn't really good enough + case $host_os in + darwin*) + if test -n "$STRIP" ; then + striplib="$STRIP -x" + AC_MSG_RESULT([yes]) + else + AC_MSG_RESULT([no]) +fi + ;; + *) + AC_MSG_RESULT([no]) + ;; + esac +fi +])# AC_LIBTOOL_SYS_LIB_STRIP + + +# AC_LIBTOOL_SYS_DYNAMIC_LINKER +# ----------------------------- +# PORTME Fill in your ld.so characteristics +AC_DEFUN([AC_LIBTOOL_SYS_DYNAMIC_LINKER], +[AC_MSG_CHECKING([dynamic linker characteristics]) +library_names_spec= +libname_spec='lib$name' +soname_spec= +shrext_cmds=".so" +postinstall_cmds= +postuninstall_cmds= +finish_cmds= +finish_eval= +shlibpath_var= +shlibpath_overrides_runpath=unknown +version_type=none +dynamic_linker="$host_os ld.so" +sys_lib_dlsearch_path_spec="/lib /usr/lib" +if test "$GCC" = yes; then + sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"` + if echo "$sys_lib_search_path_spec" | grep ';' >/dev/null ; then + # if the path contains ";" then we assume it to be the separator + # otherwise default to the standard path separator (i.e. ":") - it is + # assumed that no part of a normal pathname contains ";" but that should + # okay in the real world where ";" in dirpaths is itself problematic. + sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` + else + sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` + fi +else + sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" +fi +need_lib_prefix=unknown +hardcode_into_libs=no + +# when you set need_version to no, make sure it does not cause -set_version +# flags to be left without arguments +need_version=unknown + +case $host_os in +aix3*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a' + shlibpath_var=LIBPATH + + # AIX 3 has no versioning support, so we append a major version to the name. + soname_spec='${libname}${release}${shared_ext}$major' + ;; + +aix4* | aix5*) + version_type=linux + need_lib_prefix=no + need_version=no + hardcode_into_libs=yes + if test "$host_cpu" = ia64; then + # AIX 5 supports IA64 + library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + else + # With GCC up to 2.95.x, collect2 would create an import file + # for dependence libraries. The import file would start with + # the line `#! .'. This would cause the generated library to + # depend on `.', always an invalid library. This was fixed in + # development snapshots of GCC prior to 3.0. + case $host_os in + aix4 | aix4.[[01]] | aix4.[[01]].*) + if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' + echo ' yes ' + echo '#endif'; } | ${CC} -E - | grep yes > /dev/null; then + : + else + can_build_shared=no + fi + ;; + esac + # AIX (on Power*) has no versioning support, so currently we can not hardcode correct + # soname into executable. Probably we can add versioning support to + # collect2, so additional links can be useful in future. + if test "$aix_use_runtimelinking" = yes; then + # If using run time linking (on AIX 4.2 or later) use lib.so + # instead of lib.a to let people know that these are not + # typical AIX shared libraries. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + else + # We preserve .a as extension for shared libraries through AIX4.2 + # and later when we are not doing run time linking. + library_names_spec='${libname}${release}.a $libname.a' + soname_spec='${libname}${release}${shared_ext}$major' + fi + shlibpath_var=LIBPATH + fi + ;; + +amigaos*) + library_names_spec='$libname.ixlibrary $libname.a' + # Create ${libname}_ixlibrary.a entries in /sys/libs. + finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`$echo "X$lib" | $Xsed -e '\''s%^.*/\([[^/]]*\)\.ixlibrary$%\1%'\''`; test $rm /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' + ;; + +beos*) + library_names_spec='${libname}${shared_ext}' + dynamic_linker="$host_os ld.so" + shlibpath_var=LIBRARY_PATH + ;; + +bsdi4*) + version_type=linux + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' + shlibpath_var=LD_LIBRARY_PATH + sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" + sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" + # the default ld.so.conf also contains /usr/contrib/lib and + # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow + # libtool to hard-code these into programs + ;; + +cygwin* | mingw* | pw32*) + version_type=windows + shrext_cmds=".dll" + need_version=no + need_lib_prefix=no + + case $GCC,$host_os in + yes,cygwin* | yes,mingw* | yes,pw32*) + library_names_spec='$libname.dll.a' + # DLL is installed to $(libdir)/../bin by postinstall_cmds + postinstall_cmds='base_file=`basename \${file}`~ + dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i;echo \$dlname'\''`~ + dldir=$destdir/`dirname \$dlpath`~ + test -d \$dldir || mkdir -p \$dldir~ + $install_prog $dir/$dlname \$dldir/$dlname' + postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ + dlpath=$dir/\$dldll~ + $rm \$dlpath' + shlibpath_overrides_runpath=yes + + case $host_os in + cygwin*) + # Cygwin DLLs use 'cyg' prefix rather than 'lib' + soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}' + sys_lib_search_path_spec="/usr/lib /lib/w32api /lib /usr/local/lib" + ;; + mingw*) + # MinGW DLLs use traditional 'lib' prefix + soname_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}' + sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"` + if echo "$sys_lib_search_path_spec" | [grep ';[c-zC-Z]:/' >/dev/null]; then + # It is most probably a Windows format PATH printed by + # mingw gcc, but we are running on Cygwin. Gcc prints its search + # path with ; separators, and with drive letters. We can handle the + # drive letters (cygwin fileutils understands them), so leave them, + # especially as we might pass files found there to a mingw objdump, + # which wouldn't understand a cygwinified path. Ahh. + sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` + else + sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` + fi + ;; + pw32*) + # pw32 DLLs use 'pw' prefix rather than 'lib' + library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' + ;; + esac + ;; + + *) + library_names_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext} $libname.lib' + ;; + esac + dynamic_linker='Win32 ld.exe' + # FIXME: first we should search . and the directory the executable is in + shlibpath_var=PATH + ;; + +darwin* | rhapsody*) + dynamic_linker="$host_os dyld" + version_type=darwin + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${versuffix}$shared_ext ${libname}${release}${major}$shared_ext ${libname}$shared_ext' + soname_spec='${libname}${release}${major}$shared_ext' + shlibpath_overrides_runpath=yes + shlibpath_var=DYLD_LIBRARY_PATH + shrext_cmds='$(test .$module = .yes && echo .so || echo .dylib)' + # Apple's gcc prints 'gcc -print-search-dirs' doesn't operate the same. + if test "$GCC" = yes; then + sys_lib_search_path_spec=`$CC -print-search-dirs | tr "\n" "$PATH_SEPARATOR" | sed -e 's/libraries:/@libraries:/' | tr "@" "\n" | grep "^libraries:" | sed -e "s/^libraries://" -e "s,=/,/,g" -e "s,$PATH_SEPARATOR, ,g" -e "s,.*,& /lib /usr/lib /usr/local/lib,g"` + else + sys_lib_search_path_spec='/lib /usr/lib /usr/local/lib' + fi + sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' + ;; + +dgux*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +freebsd1*) + dynamic_linker=no + ;; + +kfreebsd*-gnu) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + dynamic_linker='GNU ld.so' + ;; + +freebsd*) + objformat=`test -x /usr/bin/objformat && /usr/bin/objformat || echo aout` + version_type=freebsd-$objformat + case $version_type in + freebsd-elf*) + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' + need_version=no + need_lib_prefix=no + ;; + freebsd-*) + library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix' + need_version=yes + ;; + esac + shlibpath_var=LD_LIBRARY_PATH + case $host_os in + freebsd2*) + shlibpath_overrides_runpath=yes + ;; + freebsd3.[01]* | freebsdelf3.[01]*) + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + *) # from 3.2 on + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + esac + ;; + +gnu*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + hardcode_into_libs=yes + ;; + +hpux9* | hpux10* | hpux11*) + # Give a soname corresponding to the major version so that dld.sl refuses to + # link against other versions. + version_type=sunos + need_lib_prefix=no + need_version=no + case "$host_cpu" in + ia64*) + shrext_cmds='.so' + hardcode_into_libs=yes + dynamic_linker="$host_os dld.so" + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + if test "X$HPUX_IA64_MODE" = X32; then + sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" + else + sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" + fi + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + ;; + hppa*64*) + shrext_cmds='.sl' + hardcode_into_libs=yes + dynamic_linker="$host_os dld.sl" + shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH + shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + ;; + *) + shrext_cmds='.sl' + dynamic_linker="$host_os dld.sl" + shlibpath_var=SHLIB_PATH + shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + ;; + esac + # HP-UX runs *really* slowly unless shared libraries are mode 555. + postinstall_cmds='chmod 555 $lib' + ;; + +irix5* | irix6* | nonstopux*) + case $host_os in + nonstopux*) version_type=nonstopux ;; + *) + if test "$lt_cv_prog_gnu_ld" = yes; then + version_type=linux + else + version_type=irix + fi ;; + esac + need_lib_prefix=no + need_version=no + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}' + case $host_os in + irix5* | nonstopux*) + libsuff= shlibsuff= + ;; + *) + case $LD in # libtool.m4 will add one of these switches to LD + *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") + libsuff= shlibsuff= libmagic=32-bit;; + *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") + libsuff=32 shlibsuff=N32 libmagic=N32;; + *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") + libsuff=64 shlibsuff=64 libmagic=64-bit;; + *) libsuff= shlibsuff= libmagic=never-match;; + esac + ;; + esac + shlibpath_var=LD_LIBRARY${shlibsuff}_PATH + shlibpath_overrides_runpath=no + sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" + sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" + hardcode_into_libs=yes + ;; + +# No shared lib support for Linux oldld, aout, or coff. +linux*oldld* | linux*aout* | linux*coff*) + dynamic_linker=no + ;; + +# This must be Linux ELF. +linux*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + # This implies no fast_install, which is unacceptable. + # Some rework will be needed to allow for fast_install + # before this can be enabled. + hardcode_into_libs=yes + + # Append ld.so.conf contents to the search path + if test -f /etc/ld.so.conf; then + lt_ld_extra=`$SED -e 's/[:,\t]/ /g;s/=[^=]*$//;s/=[^= ]* / /g' /etc/ld.so.conf | tr '\n' ' '` + sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" + fi + + # We used to test for /lib/ld.so.1 and disable shared libraries on + # powerpc, because MkLinux only supported shared libraries with the + # GNU dynamic linker. Since this was broken with cross compilers, + # most powerpc-linux boxes support dynamic linking these days and + # people can always --disable-shared, the test was removed, and we + # assume the GNU/Linux dynamic linker is in use. + dynamic_linker='GNU/Linux ld.so' + ;; + +netbsdelf*-gnu) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + dynamic_linker='NetBSD ld.elf_so' + ;; + +knetbsd*-gnu) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + dynamic_linker='GNU ld.so' + ;; + +netbsd*) + version_type=sunos + need_lib_prefix=no + need_version=no + if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' + dynamic_linker='NetBSD (a.out) ld.so' + else + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + dynamic_linker='NetBSD ld.elf_so' + fi + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + +newsos6) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + ;; + +nto-qnx*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + ;; + +openbsd*) + version_type=sunos + need_lib_prefix=no + need_version=yes + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' + shlibpath_var=LD_LIBRARY_PATH + if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + case $host_os in + openbsd2.[[89]] | openbsd2.[[89]].*) + shlibpath_overrides_runpath=no + ;; + *) + shlibpath_overrides_runpath=yes + ;; + esac + else + shlibpath_overrides_runpath=yes + fi + ;; + +os2*) + libname_spec='$name' + shrext_cmds=".dll" + need_lib_prefix=no + library_names_spec='$libname${shared_ext} $libname.a' + dynamic_linker='OS/2 ld.exe' + shlibpath_var=LIBPATH + ;; + +osf3* | osf4* | osf5*) + version_type=osf + need_lib_prefix=no + need_version=no + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" + sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec" + ;; + +sco3.2v5*) + version_type=osf + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + ;; + +solaris*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + # ldd complains unless libraries are executable + postinstall_cmds='chmod +x $lib' + ;; + +sunos4*) + version_type=sunos + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + if test "$with_gnu_ld" = yes; then + need_lib_prefix=no + fi + need_version=yes + ;; + +sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + case $host_vendor in + sni) + shlibpath_overrides_runpath=no + need_lib_prefix=no + export_dynamic_flag_spec='${wl}-Blargedynsym' + runpath_var=LD_RUN_PATH + ;; + siemens) + need_lib_prefix=no + ;; + motorola) + need_lib_prefix=no + need_version=no + shlibpath_overrides_runpath=no + sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' + ;; + esac + ;; + +sysv4*MP*) + if test -d /usr/nec ;then + version_type=linux + library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}' + soname_spec='$libname${shared_ext}.$major' + shlibpath_var=LD_LIBRARY_PATH + fi + ;; + +uts4*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +*) + dynamic_linker=no + ;; +esac +AC_MSG_RESULT([$dynamic_linker]) +test "$dynamic_linker" = no && can_build_shared=no +])# AC_LIBTOOL_SYS_DYNAMIC_LINKER + + +# _LT_AC_TAGCONFIG +# ---------------- +AC_DEFUN([_LT_AC_TAGCONFIG], +[AC_ARG_WITH([tags], + [AC_HELP_STRING([--with-tags@<:@=TAGS@:>@], + [include additional configurations @<:@automatic@:>@])], + [tagnames="$withval"]) + +if test -f "$ltmain" && test -n "$tagnames"; then + if test ! -f "${ofile}"; then + AC_MSG_WARN([output file `$ofile' does not exist]) + fi + + if test -z "$LTCC"; then + eval "`$SHELL ${ofile} --config | grep '^LTCC='`" + if test -z "$LTCC"; then + AC_MSG_WARN([output file `$ofile' does not look like a libtool script]) + else + AC_MSG_WARN([using `LTCC=$LTCC', extracted from `$ofile']) + fi + fi + + # Extract list of available tagged configurations in $ofile. + # Note that this assumes the entire list is on one line. + available_tags=`grep "^available_tags=" "${ofile}" | $SED -e 's/available_tags=\(.*$\)/\1/' -e 's/\"//g'` + + lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," + for tagname in $tagnames; do + IFS="$lt_save_ifs" + # Check whether tagname contains only valid characters + case `$echo "X$tagname" | $Xsed -e 's:[[-_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890,/]]::g'` in + "") ;; + *) AC_MSG_ERROR([invalid tag name: $tagname]) + ;; + esac + + if grep "^# ### BEGIN LIBTOOL TAG CONFIG: $tagname$" < "${ofile}" > /dev/null + then + AC_MSG_ERROR([tag name \"$tagname\" already exists]) + fi + + # Update the list of available tags. + if test -n "$tagname"; then + echo appending configuration tag \"$tagname\" to $ofile + + case $tagname in + CXX) + if test -n "$CXX" && test "X$CXX" != "Xno"; then + AC_LIBTOOL_LANG_CXX_CONFIG + else + tagname="" + fi + ;; + + F77) + if test -n "$F77" && test "X$F77" != "Xno"; then + AC_LIBTOOL_LANG_F77_CONFIG + else + tagname="" + fi + ;; + + GCJ) + if test -n "$GCJ" && test "X$GCJ" != "Xno"; then + AC_LIBTOOL_LANG_GCJ_CONFIG + else + tagname="" + fi + ;; + + RC) + AC_LIBTOOL_LANG_RC_CONFIG + ;; + + *) + AC_MSG_ERROR([Unsupported tag name: $tagname]) + ;; + esac + + # Append the new tag name to the list of available tags. + if test -n "$tagname" ; then + available_tags="$available_tags $tagname" + fi + fi + done + IFS="$lt_save_ifs" + + # Now substitute the updated list of available tags. + if eval "sed -e 's/^available_tags=.*\$/available_tags=\"$available_tags\"/' \"$ofile\" > \"${ofile}T\""; then + mv "${ofile}T" "$ofile" + chmod +x "$ofile" + else + rm -f "${ofile}T" + AC_MSG_ERROR([unable to update list of available tagged configurations.]) + fi +fi +])# _LT_AC_TAGCONFIG + + +# AC_LIBTOOL_DLOPEN +# ----------------- +# enable checks for dlopen support +AC_DEFUN([AC_LIBTOOL_DLOPEN], + [AC_BEFORE([$0],[AC_LIBTOOL_SETUP]) +])# AC_LIBTOOL_DLOPEN + + +# AC_LIBTOOL_WIN32_DLL +# -------------------- +# declare package support for building win32 dll's +AC_DEFUN([AC_LIBTOOL_WIN32_DLL], +[AC_BEFORE([$0], [AC_LIBTOOL_SETUP]) +])# AC_LIBTOOL_WIN32_DLL + + +# AC_ENABLE_SHARED([DEFAULT]) +# --------------------------- +# implement the --enable-shared flag +# DEFAULT is either `yes' or `no'. If omitted, it defaults to `yes'. +AC_DEFUN([AC_ENABLE_SHARED], +[define([AC_ENABLE_SHARED_DEFAULT], ifelse($1, no, no, yes))dnl +AC_ARG_ENABLE([shared], + [AC_HELP_STRING([--enable-shared@<:@=PKGS@:>@], + [build shared libraries @<:@default=]AC_ENABLE_SHARED_DEFAULT[@:>@])], + [p=${PACKAGE-default} + case $enableval in + yes) enable_shared=yes ;; + no) enable_shared=no ;; + *) + enable_shared=no + # Look at the argument we got. We use all the common list separators. + lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," + for pkg in $enableval; do + IFS="$lt_save_ifs" + if test "X$pkg" = "X$p"; then + enable_shared=yes + fi + done + IFS="$lt_save_ifs" + ;; + esac], + [enable_shared=]AC_ENABLE_SHARED_DEFAULT) +])# AC_ENABLE_SHARED + + +# AC_DISABLE_SHARED +# ----------------- +#- set the default shared flag to --disable-shared +AC_DEFUN([AC_DISABLE_SHARED], +[AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl +AC_ENABLE_SHARED(no) +])# AC_DISABLE_SHARED + + +# AC_ENABLE_STATIC([DEFAULT]) +# --------------------------- +# implement the --enable-static flag +# DEFAULT is either `yes' or `no'. If omitted, it defaults to `yes'. +AC_DEFUN([AC_ENABLE_STATIC], +[define([AC_ENABLE_STATIC_DEFAULT], ifelse($1, no, no, yes))dnl +AC_ARG_ENABLE([static], + [AC_HELP_STRING([--enable-static@<:@=PKGS@:>@], + [build static libraries @<:@default=]AC_ENABLE_STATIC_DEFAULT[@:>@])], + [p=${PACKAGE-default} + case $enableval in + yes) enable_static=yes ;; + no) enable_static=no ;; + *) + enable_static=no + # Look at the argument we got. We use all the common list separators. + lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," + for pkg in $enableval; do + IFS="$lt_save_ifs" + if test "X$pkg" = "X$p"; then + enable_static=yes + fi + done + IFS="$lt_save_ifs" + ;; + esac], + [enable_static=]AC_ENABLE_STATIC_DEFAULT) +])# AC_ENABLE_STATIC + + +# AC_DISABLE_STATIC +# ----------------- +# set the default static flag to --disable-static +AC_DEFUN([AC_DISABLE_STATIC], +[AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl +AC_ENABLE_STATIC(no) +])# AC_DISABLE_STATIC + + +# AC_ENABLE_FAST_INSTALL([DEFAULT]) +# --------------------------------- +# implement the --enable-fast-install flag +# DEFAULT is either `yes' or `no'. If omitted, it defaults to `yes'. +AC_DEFUN([AC_ENABLE_FAST_INSTALL], +[define([AC_ENABLE_FAST_INSTALL_DEFAULT], ifelse($1, no, no, yes))dnl +AC_ARG_ENABLE([fast-install], + [AC_HELP_STRING([--enable-fast-install@<:@=PKGS@:>@], + [optimize for fast installation @<:@default=]AC_ENABLE_FAST_INSTALL_DEFAULT[@:>@])], + [p=${PACKAGE-default} + case $enableval in + yes) enable_fast_install=yes ;; + no) enable_fast_install=no ;; + *) + enable_fast_install=no + # Look at the argument we got. We use all the common list separators. + lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," + for pkg in $enableval; do + IFS="$lt_save_ifs" + if test "X$pkg" = "X$p"; then + enable_fast_install=yes + fi + done + IFS="$lt_save_ifs" + ;; + esac], + [enable_fast_install=]AC_ENABLE_FAST_INSTALL_DEFAULT) +])# AC_ENABLE_FAST_INSTALL + + +# AC_DISABLE_FAST_INSTALL +# ----------------------- +# set the default to --disable-fast-install +AC_DEFUN([AC_DISABLE_FAST_INSTALL], +[AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl +AC_ENABLE_FAST_INSTALL(no) +])# AC_DISABLE_FAST_INSTALL + + +# AC_LIBTOOL_PICMODE([MODE]) +# -------------------------- +# implement the --with-pic flag +# MODE is either `yes' or `no'. If omitted, it defaults to `both'. +AC_DEFUN([AC_LIBTOOL_PICMODE], +[AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl +pic_mode=ifelse($#,1,$1,default) +])# AC_LIBTOOL_PICMODE + + +# AC_PROG_EGREP +# ------------- +# This is predefined starting with Autoconf 2.54, so this conditional +# definition can be removed once we require Autoconf 2.54 or later. +m4_ifndef([AC_PROG_EGREP], [AC_DEFUN([AC_PROG_EGREP], +[AC_CACHE_CHECK([for egrep], [ac_cv_prog_egrep], + [if echo a | (grep -E '(a|b)') >/dev/null 2>&1 + then ac_cv_prog_egrep='grep -E' + else ac_cv_prog_egrep='egrep' + fi]) + EGREP=$ac_cv_prog_egrep + AC_SUBST([EGREP]) +])]) + + +# AC_PATH_TOOL_PREFIX +# ------------------- +# find a file program which can recognise shared library +AC_DEFUN([AC_PATH_TOOL_PREFIX], +[AC_REQUIRE([AC_PROG_EGREP])dnl +AC_MSG_CHECKING([for $1]) +AC_CACHE_VAL(lt_cv_path_MAGIC_CMD, +[case $MAGIC_CMD in +[[\\/*] | ?:[\\/]*]) + lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path. + ;; +*) + lt_save_MAGIC_CMD="$MAGIC_CMD" + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR +dnl $ac_dummy forces splitting on constant user-supplied paths. +dnl POSIX.2 word splitting is done only on the output of word expansions, +dnl not every word. This closes a longstanding sh security hole. + ac_dummy="ifelse([$2], , $PATH, [$2])" + for ac_dir in $ac_dummy; do + IFS="$lt_save_ifs" + test -z "$ac_dir" && ac_dir=. + if test -f $ac_dir/$1; then + lt_cv_path_MAGIC_CMD="$ac_dir/$1" + if test -n "$file_magic_test_file"; then + case $deplibs_check_method in + "file_magic "*) + file_magic_regex="`expr \"$deplibs_check_method\" : \"file_magic \(.*\)\"`" + MAGIC_CMD="$lt_cv_path_MAGIC_CMD" + if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | + $EGREP "$file_magic_regex" > /dev/null; then + : + else + cat <&2 + +*** Warning: the command libtool uses to detect shared libraries, +*** $file_magic_cmd, produces output that libtool cannot recognize. +*** The result is that libtool may fail to recognize shared libraries +*** as such. This will affect the creation of libtool libraries that +*** depend on shared libraries, but programs linked with such libtool +*** libraries will work regardless of this problem. Nevertheless, you +*** may want to report the problem to your system manager and/or to +*** bug-libtool@gnu.org + +EOF + fi ;; + esac + fi + break + fi + done + IFS="$lt_save_ifs" + MAGIC_CMD="$lt_save_MAGIC_CMD" + ;; +esac]) +MAGIC_CMD="$lt_cv_path_MAGIC_CMD" +if test -n "$MAGIC_CMD"; then + AC_MSG_RESULT($MAGIC_CMD) +else + AC_MSG_RESULT(no) +fi +])# AC_PATH_TOOL_PREFIX + + +# AC_PATH_MAGIC +# ------------- +# find a file program which can recognise a shared library +AC_DEFUN([AC_PATH_MAGIC], +[AC_PATH_TOOL_PREFIX(${ac_tool_prefix}file, /usr/bin$PATH_SEPARATOR$PATH) +if test -z "$lt_cv_path_MAGIC_CMD"; then + if test -n "$ac_tool_prefix"; then + AC_PATH_TOOL_PREFIX(file, /usr/bin$PATH_SEPARATOR$PATH) + else + MAGIC_CMD=: + fi +fi +])# AC_PATH_MAGIC + + +# AC_PROG_LD +# ---------- +# find the pathname to the GNU or non-GNU linker +AC_DEFUN([AC_PROG_LD], +[AC_ARG_WITH([gnu-ld], + [AC_HELP_STRING([--with-gnu-ld], + [assume the C compiler uses GNU ld @<:@default=no@:>@])], + [test "$withval" = no || with_gnu_ld=yes], + [with_gnu_ld=no]) +AC_REQUIRE([LT_AC_PROG_SED])dnl +AC_REQUIRE([AC_PROG_CC])dnl +AC_REQUIRE([AC_CANONICAL_HOST])dnl +AC_REQUIRE([AC_CANONICAL_BUILD])dnl +ac_prog=ld +if test "$GCC" = yes; then + # Check if gcc -print-prog-name=ld gives a path. + AC_MSG_CHECKING([for ld used by $CC]) + case $host in + *-*-mingw*) + # gcc leaves a trailing carriage return which upsets mingw + ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; + *) + ac_prog=`($CC -print-prog-name=ld) 2>&5` ;; + esac + case $ac_prog in + # Accept absolute paths. + [[\\/]]* | ?:[[\\/]]*) + re_direlt='/[[^/]][[^/]]*/\.\./' + # Canonicalize the pathname of ld + ac_prog=`echo $ac_prog| $SED 's%\\\\%/%g'` + while echo $ac_prog | grep "$re_direlt" > /dev/null 2>&1; do + ac_prog=`echo $ac_prog| $SED "s%$re_direlt%/%"` + done + test -z "$LD" && LD="$ac_prog" + ;; + "") + # If it fails, then pretend we aren't using GCC. + ac_prog=ld + ;; + *) + # If it is relative, then search for the first ld in PATH. + with_gnu_ld=unknown + ;; + esac +elif test "$with_gnu_ld" = yes; then + AC_MSG_CHECKING([for GNU ld]) +else + AC_MSG_CHECKING([for non-GNU ld]) +fi +AC_CACHE_VAL(lt_cv_path_LD, +[if test -z "$LD"; then + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR + for ac_dir in $PATH; do + IFS="$lt_save_ifs" + test -z "$ac_dir" && ac_dir=. + if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then + lt_cv_path_LD="$ac_dir/$ac_prog" + # Check to see if the program is GNU ld. I'd rather use --version, + # but apparently some GNU ld's only accept -v. + # Break only if it was the GNU/non-GNU ld that we prefer. + case `"$lt_cv_path_LD" -v 2>&1 &1 /dev/null; then + case $host_cpu in + i*86 ) + # Not sure whether the presence of OpenBSD here was a mistake. + # Let's accept both of them until this is cleared up. + lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD)/i[[3-9]]86 (compact )?demand paged shared library' + lt_cv_file_magic_cmd=/usr/bin/file + lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*` + ;; + esac + else + lt_cv_deplibs_check_method=pass_all + fi + ;; + +gnu*) + lt_cv_deplibs_check_method=pass_all + ;; + +hpux10.20* | hpux11*) + lt_cv_file_magic_cmd=/usr/bin/file + case "$host_cpu" in + ia64*) + lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|ELF-[[0-9]][[0-9]]) shared object file - IA64' + lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so + ;; + hppa*64*) + [lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - PA-RISC [0-9].[0-9]'] + lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl + ;; + *) + lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|PA-RISC[[0-9]].[[0-9]]) shared library' + lt_cv_file_magic_test_file=/usr/lib/libc.sl + ;; + esac + ;; + +irix5* | irix6* | nonstopux*) + case $LD in + *-32|*"-32 ") libmagic=32-bit;; + *-n32|*"-n32 ") libmagic=N32;; + *-64|*"-64 ") libmagic=64-bit;; + *) libmagic=never-match;; + esac + lt_cv_deplibs_check_method=pass_all + ;; + +# This must be Linux ELF. +linux*) + lt_cv_deplibs_check_method=pass_all + ;; + +netbsd* | netbsdelf*-gnu | knetbsd*-gnu) + if echo __ELF__ | $CC -E - | grep __ELF__ > /dev/null; then + lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$' + else + lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|_pic\.a)$' + fi + ;; + +newos6*) + lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (executable|dynamic lib)' + lt_cv_file_magic_cmd=/usr/bin/file + lt_cv_file_magic_test_file=/usr/lib/libnls.so + ;; + +nto-qnx*) + lt_cv_deplibs_check_method=unknown + ;; + +openbsd*) + lt_cv_file_magic_cmd=/usr/bin/file + lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*` + if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB shared object' + else + lt_cv_deplibs_check_method='file_magic OpenBSD.* shared library' + fi + ;; + +osf3* | osf4* | osf5*) + lt_cv_deplibs_check_method=pass_all + ;; + +sco3.2v5*) + lt_cv_deplibs_check_method=pass_all + ;; + +solaris*) + lt_cv_deplibs_check_method=pass_all + ;; + +sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*) + case $host_vendor in + motorola) + lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib) M[[0-9]][[0-9]]* Version [[0-9]]' + lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*` + ;; + ncr) + lt_cv_deplibs_check_method=pass_all + ;; + sequent) + lt_cv_file_magic_cmd='/bin/file' + lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB (shared object|dynamic lib )' + ;; + sni) + lt_cv_file_magic_cmd='/bin/file' + lt_cv_deplibs_check_method="file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB dynamic lib" + lt_cv_file_magic_test_file=/lib/libc.so + ;; + siemens) + lt_cv_deplibs_check_method=pass_all + ;; + esac + ;; + +sysv5OpenUNIX8* | sysv5UnixWare7* | sysv5uw[[78]]* | unixware7* | sysv4*uw2*) + lt_cv_deplibs_check_method=pass_all + ;; +esac +]) +file_magic_cmd=$lt_cv_file_magic_cmd +deplibs_check_method=$lt_cv_deplibs_check_method +test -z "$deplibs_check_method" && deplibs_check_method=unknown +])# AC_DEPLIBS_CHECK_METHOD + + +# AC_PROG_NM +# ---------- +# find the pathname to a BSD-compatible name lister +AC_DEFUN([AC_PROG_NM], +[AC_CACHE_CHECK([for BSD-compatible nm], lt_cv_path_NM, +[if test -n "$NM"; then + # Let the user override the test. + lt_cv_path_NM="$NM" +else + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR + for ac_dir in $PATH /usr/ccs/bin /usr/ucb /bin; do + IFS="$lt_save_ifs" + test -z "$ac_dir" && ac_dir=. + tmp_nm="$ac_dir/${ac_tool_prefix}nm" + if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then + # Check to see if the nm accepts a BSD-compat flag. + # Adding the `sed 1q' prevents false positives on HP-UX, which says: + # nm: unknown option "B" ignored + # Tru64's nm complains that /dev/null is an invalid object file + case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in + */dev/null* | *'Invalid file or object type'*) + lt_cv_path_NM="$tmp_nm -B" + break + ;; + *) + case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in + */dev/null*) + lt_cv_path_NM="$tmp_nm -p" + break + ;; + *) + lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but + continue # so that we can try to find one that supports BSD flags + ;; + esac + esac + fi + done + IFS="$lt_save_ifs" + test -z "$lt_cv_path_NM" && lt_cv_path_NM=nm +fi]) +NM="$lt_cv_path_NM" +])# AC_PROG_NM + + +# AC_CHECK_LIBM +# ------------- +# check for math library +AC_DEFUN([AC_CHECK_LIBM], +[AC_REQUIRE([AC_CANONICAL_HOST])dnl +LIBM= +case $host in +*-*-beos* | *-*-cygwin* | *-*-pw32* | *-*-darwin*) + # These system don't have libm, or don't need it + ;; +*-ncr-sysv4.3*) + AC_CHECK_LIB(mw, _mwvalidcheckl, LIBM="-lmw") + AC_CHECK_LIB(m, cos, LIBM="$LIBM -lm") + ;; +*) + AC_CHECK_LIB(m, cos, LIBM="-lm") + ;; +esac +])# AC_CHECK_LIBM + + +# AC_LIBLTDL_CONVENIENCE([DIRECTORY]) +# ----------------------------------- +# sets LIBLTDL to the link flags for the libltdl convenience library and +# LTDLINCL to the include flags for the libltdl header and adds +# --enable-ltdl-convenience to the configure arguments. Note that LIBLTDL +# and LTDLINCL are not AC_SUBSTed, nor is AC_CONFIG_SUBDIRS called. If +# DIRECTORY is not provided, it is assumed to be `libltdl'. LIBLTDL will +# be prefixed with '${top_builddir}/' and LTDLINCL will be prefixed with +# '${top_srcdir}/' (note the single quotes!). If your package is not +# flat and you're not using automake, define top_builddir and +# top_srcdir appropriately in the Makefiles. +AC_DEFUN([AC_LIBLTDL_CONVENIENCE], +[AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl + case $enable_ltdl_convenience in + no) AC_MSG_ERROR([this package needs a convenience libltdl]) ;; + "") enable_ltdl_convenience=yes + ac_configure_args="$ac_configure_args --enable-ltdl-convenience" ;; + esac + LIBLTDL='${top_builddir}/'ifelse($#,1,[$1],['libltdl'])/libltdlc.la + LTDLINCL='-I${top_srcdir}/'ifelse($#,1,[$1],['libltdl']) + # For backwards non-gettext consistent compatibility... + INCLTDL="$LTDLINCL" +])# AC_LIBLTDL_CONVENIENCE + + +# AC_LIBLTDL_INSTALLABLE([DIRECTORY]) +# ----------------------------------- +# sets LIBLTDL to the link flags for the libltdl installable library and +# LTDLINCL to the include flags for the libltdl header and adds +# --enable-ltdl-install to the configure arguments. Note that LIBLTDL +# and LTDLINCL are not AC_SUBSTed, nor is AC_CONFIG_SUBDIRS called. If +# DIRECTORY is not provided and an installed libltdl is not found, it is +# assumed to be `libltdl'. LIBLTDL will be prefixed with '${top_builddir}/' +# and LTDLINCL will be prefixed with '${top_srcdir}/' (note the single +# quotes!). If your package is not flat and you're not using automake, +# define top_builddir and top_srcdir appropriately in the Makefiles. +# In the future, this macro may have to be called after AC_PROG_LIBTOOL. +AC_DEFUN([AC_LIBLTDL_INSTALLABLE], +[AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl + AC_CHECK_LIB(ltdl, lt_dlinit, + [test x"$enable_ltdl_install" != xyes && enable_ltdl_install=no], + [if test x"$enable_ltdl_install" = xno; then + AC_MSG_WARN([libltdl not installed, but installation disabled]) + else + enable_ltdl_install=yes + fi + ]) + if test x"$enable_ltdl_install" = x"yes"; then + ac_configure_args="$ac_configure_args --enable-ltdl-install" + LIBLTDL='${top_builddir}/'ifelse($#,1,[$1],['libltdl'])/libltdl.la + LTDLINCL='-I${top_srcdir}/'ifelse($#,1,[$1],['libltdl']) + else + ac_configure_args="$ac_configure_args --enable-ltdl-install=no" + LIBLTDL="-lltdl" + LTDLINCL= + fi + # For backwards non-gettext consistent compatibility... + INCLTDL="$LTDLINCL" +])# AC_LIBLTDL_INSTALLABLE + + +# AC_LIBTOOL_CXX +# -------------- +# enable support for C++ libraries +AC_DEFUN([AC_LIBTOOL_CXX], +[AC_REQUIRE([_LT_AC_LANG_CXX]) +])# AC_LIBTOOL_CXX + + +# _LT_AC_LANG_CXX +# --------------- +AC_DEFUN([_LT_AC_LANG_CXX], +[AC_REQUIRE([AC_PROG_CXX]) +AC_REQUIRE([AC_PROG_CXXCPP]) +_LT_AC_SHELL_INIT([tagnames=${tagnames+${tagnames},}CXX]) +])# _LT_AC_LANG_CXX + + +# AC_LIBTOOL_F77 +# -------------- +# enable support for Fortran 77 libraries +AC_DEFUN([AC_LIBTOOL_F77], +[AC_REQUIRE([_LT_AC_LANG_F77]) +])# AC_LIBTOOL_F77 + + +# _LT_AC_LANG_F77 +# --------------- +AC_DEFUN([_LT_AC_LANG_F77], +[AC_REQUIRE([AC_PROG_F77]) +_LT_AC_SHELL_INIT([tagnames=${tagnames+${tagnames},}F77]) +])# _LT_AC_LANG_F77 + + +# AC_LIBTOOL_GCJ +# -------------- +# enable support for GCJ libraries +AC_DEFUN([AC_LIBTOOL_GCJ], +[AC_REQUIRE([_LT_AC_LANG_GCJ]) +])# AC_LIBTOOL_GCJ + + +# _LT_AC_LANG_GCJ +# --------------- +AC_DEFUN([_LT_AC_LANG_GCJ], +[AC_PROVIDE_IFELSE([AC_PROG_GCJ],[], + [AC_PROVIDE_IFELSE([A][M_PROG_GCJ],[], + [AC_PROVIDE_IFELSE([LT_AC_PROG_GCJ],[], + [ifdef([AC_PROG_GCJ],[AC_REQUIRE([AC_PROG_GCJ])], + [ifdef([A][M_PROG_GCJ],[AC_REQUIRE([A][M_PROG_GCJ])], + [AC_REQUIRE([A][C_PROG_GCJ_OR_A][M_PROG_GCJ])])])])])]) +_LT_AC_SHELL_INIT([tagnames=${tagnames+${tagnames},}GCJ]) +])# _LT_AC_LANG_GCJ + + +# AC_LIBTOOL_RC +# -------------- +# enable support for Windows resource files +AC_DEFUN([AC_LIBTOOL_RC], +[AC_REQUIRE([LT_AC_PROG_RC]) +_LT_AC_SHELL_INIT([tagnames=${tagnames+${tagnames},}RC]) +])# AC_LIBTOOL_RC + + +# AC_LIBTOOL_LANG_C_CONFIG +# ------------------------ +# Ensure that the configuration vars for the C compiler are +# suitably defined. Those variables are subsequently used by +# AC_LIBTOOL_CONFIG to write the compiler configuration to `libtool'. +AC_DEFUN([AC_LIBTOOL_LANG_C_CONFIG], [_LT_AC_LANG_C_CONFIG]) +AC_DEFUN([_LT_AC_LANG_C_CONFIG], +[lt_save_CC="$CC" +AC_LANG_PUSH(C) + +# Source file extension for C test sources. +ac_ext=c + +# Object file extension for compiled C test sources. +objext=o +_LT_AC_TAGVAR(objext, $1)=$objext + +# Code to be used in simple compile tests +lt_simple_compile_test_code="int some_variable = 0;\n" + +# Code to be used in simple link tests +lt_simple_link_test_code='int main(){return(0);}\n' + +_LT_AC_SYS_COMPILER + +# +# Check for any special shared library compilation flags. +# +_LT_AC_TAGVAR(lt_prog_cc_shlib, $1)= +if test "$GCC" = no; then + case $host_os in + sco3.2v5*) + _LT_AC_TAGVAR(lt_prog_cc_shlib, $1)='-belf' + ;; + esac +fi +if test -n "$_LT_AC_TAGVAR(lt_prog_cc_shlib, $1)"; then + AC_MSG_WARN([`$CC' requires `$_LT_AC_TAGVAR(lt_prog_cc_shlib, $1)' to build shared libraries]) + if echo "$old_CC $old_CFLAGS " | grep "[[ ]]$_LT_AC_TAGVAR(lt_prog_cc_shlib, $1)[[ ]]" >/dev/null; then : + else + AC_MSG_WARN([add `$_LT_AC_TAGVAR(lt_prog_cc_shlib, $1)' to the CC or CFLAGS env variable and reconfigure]) + _LT_AC_TAGVAR(lt_cv_prog_cc_can_build_shared, $1)=no + fi +fi + + +# +# Check to make sure the static flag actually works. +# +AC_LIBTOOL_LINKER_OPTION([if $compiler static flag $_LT_AC_TAGVAR(lt_prog_compiler_static, $1) works], + _LT_AC_TAGVAR(lt_prog_compiler_static_works, $1), + $_LT_AC_TAGVAR(lt_prog_compiler_static, $1), + [], + [_LT_AC_TAGVAR(lt_prog_compiler_static, $1)=]) + + +AC_LIBTOOL_PROG_COMPILER_NO_RTTI($1) +AC_LIBTOOL_PROG_COMPILER_PIC($1) +AC_LIBTOOL_PROG_CC_C_O($1) +AC_LIBTOOL_SYS_HARD_LINK_LOCKS($1) +AC_LIBTOOL_PROG_LD_SHLIBS($1) +AC_LIBTOOL_SYS_DYNAMIC_LINKER($1) +AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH($1) +AC_LIBTOOL_SYS_LIB_STRIP +AC_LIBTOOL_DLOPEN_SELF($1) + +# Report which librarie types wil actually be built +AC_MSG_CHECKING([if libtool supports shared libraries]) +AC_MSG_RESULT([$can_build_shared]) + +AC_MSG_CHECKING([whether to build shared libraries]) +test "$can_build_shared" = "no" && enable_shared=no + +# On AIX, shared libraries and static libraries use the same namespace, and +# are all built from PIC. +case "$host_os" in +aix3*) + test "$enable_shared" = yes && enable_static=no + if test -n "$RANLIB"; then + archive_cmds="$archive_cmds~\$RANLIB \$lib" + postinstall_cmds='$RANLIB $lib' + fi + ;; + +aix4* | aix5*) + if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then + test "$enable_shared" = yes && enable_static=no + fi + ;; + darwin* | rhapsody*) + if test "$GCC" = yes; then + _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no + case "$host_os" in + rhapsody* | darwin1.[[012]]) + _LT_AC_TAGVAR(allow_undefined_flag, $1)='-undefined suppress' + ;; + *) # Darwin 1.3 on + if test -z ${MACOSX_DEPLOYMENT_TARGET} ; then + _LT_AC_TAGVAR(allow_undefined_flag, $1)='-flat_namespace -undefined suppress' + else + case ${MACOSX_DEPLOYMENT_TARGET} in + 10.[[012]]) + _LT_AC_TAGVAR(allow_undefined_flag, $1)='-flat_namespace -undefined suppress' + ;; + 10.*) + _LT_AC_TAGVAR(allow_undefined_flag, $1)='-undefined dynamic_lookup' + ;; + esac + fi + ;; + esac + output_verbose_link_cmd='echo' + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs$compiler_flags -install_name $rpath/$soname $verstring' + _LT_AC_TAGVAR(module_cmds, $1)='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags' + # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin ld's + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs$compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + _LT_AC_TAGVAR(module_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + _LT_AC_TAGVAR(hardcode_direct, $1)=no + _LT_AC_TAGVAR(hardcode_automatic, $1)=yes + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=unsupported + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='-all_load $convenience' + _LT_AC_TAGVAR(link_all_deplibs, $1)=yes + else + _LT_AC_TAGVAR(ld_shlibs, $1)=no + fi + ;; +esac +AC_MSG_RESULT([$enable_shared]) + +AC_MSG_CHECKING([whether to build static libraries]) +# Make sure either enable_shared or enable_static is yes. +test "$enable_shared" = yes || enable_static=yes +AC_MSG_RESULT([$enable_static]) + +AC_LIBTOOL_CONFIG($1) + +AC_LANG_POP +CC="$lt_save_CC" +])# AC_LIBTOOL_LANG_C_CONFIG + + +# AC_LIBTOOL_LANG_CXX_CONFIG +# -------------------------- +# Ensure that the configuration vars for the C compiler are +# suitably defined. Those variables are subsequently used by +# AC_LIBTOOL_CONFIG to write the compiler configuration to `libtool'. +AC_DEFUN([AC_LIBTOOL_LANG_CXX_CONFIG], [_LT_AC_LANG_CXX_CONFIG(CXX)]) +AC_DEFUN([_LT_AC_LANG_CXX_CONFIG], +[AC_LANG_PUSH(C++) +AC_REQUIRE([AC_PROG_CXX]) +AC_REQUIRE([AC_PROG_CXXCPP]) + +_LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no +_LT_AC_TAGVAR(allow_undefined_flag, $1)= +_LT_AC_TAGVAR(always_export_symbols, $1)=no +_LT_AC_TAGVAR(archive_expsym_cmds, $1)= +_LT_AC_TAGVAR(export_dynamic_flag_spec, $1)= +_LT_AC_TAGVAR(hardcode_direct, $1)=no +_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)= +_LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)= +_LT_AC_TAGVAR(hardcode_libdir_separator, $1)= +_LT_AC_TAGVAR(hardcode_minus_L, $1)=no +_LT_AC_TAGVAR(hardcode_automatic, $1)=no +_LT_AC_TAGVAR(module_cmds, $1)= +_LT_AC_TAGVAR(module_expsym_cmds, $1)= +_LT_AC_TAGVAR(link_all_deplibs, $1)=unknown +_LT_AC_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds +_LT_AC_TAGVAR(no_undefined_flag, $1)= +_LT_AC_TAGVAR(whole_archive_flag_spec, $1)= +_LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1)=no + +# Dependencies to place before and after the object being linked: +_LT_AC_TAGVAR(predep_objects, $1)= +_LT_AC_TAGVAR(postdep_objects, $1)= +_LT_AC_TAGVAR(predeps, $1)= +_LT_AC_TAGVAR(postdeps, $1)= +_LT_AC_TAGVAR(compiler_lib_search_path, $1)= + +# Source file extension for C++ test sources. +ac_ext=cc + +# Object file extension for compiled C++ test sources. +objext=o +_LT_AC_TAGVAR(objext, $1)=$objext + +# Code to be used in simple compile tests +lt_simple_compile_test_code="int some_variable = 0;\n" + +# Code to be used in simple link tests +lt_simple_link_test_code='int main(int, char *[]) { return(0); }\n' + +# ltmain only uses $CC for tagged configurations so make sure $CC is set. +_LT_AC_SYS_COMPILER + +# Allow CC to be a program name with arguments. +lt_save_CC=$CC +lt_save_LD=$LD +lt_save_GCC=$GCC +GCC=$GXX +lt_save_with_gnu_ld=$with_gnu_ld +lt_save_path_LD=$lt_cv_path_LD +if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then + lt_cv_prog_gnu_ld=$lt_cv_prog_gnu_ldcxx +else + unset lt_cv_prog_gnu_ld +fi +if test -n "${lt_cv_path_LDCXX+set}"; then + lt_cv_path_LD=$lt_cv_path_LDCXX +else + unset lt_cv_path_LD +fi +test -z "${LDCXX+set}" || LD=$LDCXX +CC=${CXX-"c++"} +compiler=$CC +_LT_AC_TAGVAR(compiler, $1)=$CC +cc_basename=`$echo X"$compiler" | $Xsed -e 's%^.*/%%'` + +# We don't want -fno-exception wen compiling C++ code, so set the +# no_builtin_flag separately +if test "$GXX" = yes; then + _LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin' +else + _LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)= +fi + +if test "$GXX" = yes; then + # Set up default GNU C++ configuration + + AC_PROG_LD + + # Check if GNU C++ uses GNU ld as the underlying linker, since the + # archiving commands below assume that GNU ld is being used. + if test "$with_gnu_ld" = yes; then + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath ${wl}$libdir' + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' + + # If archive_cmds runs LD, not CC, wlarc should be empty + # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to + # investigate it a little bit more. (MM) + wlarc='${wl}' + + # ancient GNU ld didn't support --whole-archive et. al. + if eval "`$CC -print-prog-name=ld` --help 2>&1" | \ + grep 'no-whole-archive' > /dev/null; then + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' + else + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)= + fi + else + with_gnu_ld=no + wlarc= + + # A generic and very simple default shared library creation + # command for GNU C++ for the case where it uses the native + # linker, instead of GNU ld. If possible, this setting should + # overridden to take advantage of the native linker features on + # the platform it is being used on. + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib' + fi + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "\-L"' + +else + GXX=no + with_gnu_ld=no + wlarc= +fi + +# PORTME: fill in a description of your system's C++ link characteristics +AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries]) +_LT_AC_TAGVAR(ld_shlibs, $1)=yes +case $host_os in + aix3*) + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + aix4* | aix5*) + if test "$host_cpu" = ia64; then + # On IA64, the linker does run time linking by default, so we don't + # have to do anything special. + aix_use_runtimelinking=no + exp_sym_flag='-Bexport' + no_entry_flag="" + else + aix_use_runtimelinking=no + + # Test if we are trying to use run time linking or normal + # AIX style linking. If -brtl is somewhere in LDFLAGS, we + # need to do runtime linking. + case $host_os in aix4.[[23]]|aix4.[[23]].*|aix5*) + for ld_flag in $LDFLAGS; do + case $ld_flag in + *-brtl*) + aix_use_runtimelinking=yes + break + ;; + esac + done + esac + + exp_sym_flag='-bexport' + no_entry_flag='-bnoentry' + fi + + # When large executables or shared objects are built, AIX ld can + # have problems creating the table of contents. If linking a library + # or program results in "error TOC overflow" add -mminimal-toc to + # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not + # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. + + _LT_AC_TAGVAR(archive_cmds, $1)='' + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=':' + _LT_AC_TAGVAR(link_all_deplibs, $1)=yes + + if test "$GXX" = yes; then + case $host_os in aix4.[012]|aix4.[012].*) + # We only want to do this on AIX 4.2 and lower, the check + # below for broken collect2 doesn't work under 4.3+ + collect2name=`${CC} -print-prog-name=collect2` + if test -f "$collect2name" && \ + strings "$collect2name" | grep resolve_lib_name >/dev/null + then + # We have reworked collect2 + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + else + # We have old collect2 + _LT_AC_TAGVAR(hardcode_direct, $1)=unsupported + # It fails to find uninstalled libraries when the uninstalled + # path is not listed in the libpath. Setting hardcode_minus_L + # to unsupported forces relinking + _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)= + fi + esac + shared_flag='-shared' + else + # not using gcc + if test "$host_cpu" = ia64; then + # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release + # chokes on -Wl,-G. The following line is correct: + shared_flag='-G' + else + if test "$aix_use_runtimelinking" = yes; then + shared_flag='${wl}-G' + else + shared_flag='${wl}-bM:SRE' + fi + fi + fi + + # It seems that -bexpall does not export symbols beginning with + # underscore (_), so it is better to generate a list of symbols to export. + _LT_AC_TAGVAR(always_export_symbols, $1)=yes + if test "$aix_use_runtimelinking" = yes; then + # Warning - without using the other runtime loading flags (-brtl), + # -berok will link without error, but may produce a broken library. + _LT_AC_TAGVAR(allow_undefined_flag, $1)='-berok' + # Determine the default libpath from the value encoded in an empty executable. + _LT_AC_SYS_LIBPATH_AIX + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath" + + _LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$no_entry_flag \${wl}$exp_sym_flag:\$export_symbols $shared_flag" + else + if test "$host_cpu" = ia64; then + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib' + _LT_AC_TAGVAR(allow_undefined_flag, $1)="-z nodefs" + _LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$no_entry_flag \${wl}$exp_sym_flag:\$export_symbols" + else + # Determine the default libpath from the value encoded in an empty executable. + _LT_AC_SYS_LIBPATH_AIX + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath" + # Warning - without using the other run time loading flags, + # -berok will link without error, but may produce a broken library. + _LT_AC_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok' + _LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok' + # -bexpall does not export symbols beginning with underscore (_) + _LT_AC_TAGVAR(always_export_symbols, $1)=yes + # Exported symbols can be pulled into shared objects from archives + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)=' ' + _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=yes + # This is similar to how AIX traditionally builds it's shared libraries. + _LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags ${wl}-bE:$export_symbols ${wl}-bnoentry${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' + fi + fi + ;; + chorus*) + case $cc_basename in + *) + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + esac + ;; + + cygwin* | mingw* | pw32*) + # _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless, + # as there is no search path for DLLs. + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_AC_TAGVAR(allow_undefined_flag, $1)=unsupported + _LT_AC_TAGVAR(always_export_symbols, $1)=no + _LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1)=yes + + if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--image-base=0x10000000 ${wl}--out-implib,$lib' + # If the export-symbols file already is a .def file (1st line + # is EXPORTS), use it as is; otherwise, prepend... + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then + cp $export_symbols $output_objdir/$soname.def; + else + echo EXPORTS > $output_objdir/$soname.def; + cat $export_symbols >> $output_objdir/$soname.def; + fi~ + $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--image-base=0x10000000 ${wl}--out-implib,$lib' + else + _LT_AC_TAGVAR(ld_shlibs, $1)=no + fi + ;; + + darwin* | rhapsody*) + if test "$GXX" = yes; then + _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no + case "$host_os" in + rhapsody* | darwin1.[[012]]) + _LT_AC_TAGVAR(allow_undefined_flag, $1)='-undefined suppress' + ;; + *) # Darwin 1.3 on + if test -z ${MACOSX_DEPLOYMENT_TARGET} ; then + _LT_AC_TAGVAR(allow_undefined_flag, $1)='-flat_namespace -undefined suppress' + else + case ${MACOSX_DEPLOYMENT_TARGET} in + 10.[[012]]) + _LT_AC_TAGVAR(allow_undefined_flag, $1)='-flat_namespace -undefined suppress' + ;; + 10.*) + _LT_AC_TAGVAR(allow_undefined_flag, $1)='-undefined dynamic_lookup' + ;; + esac + fi + ;; + esac + lt_int_apple_cc_single_mod=no + output_verbose_link_cmd='echo' + if $CC -dumpspecs 2>&1 | grep 'single_module' >/dev/null ; then + lt_int_apple_cc_single_mod=yes + fi + if test "X$lt_int_apple_cc_single_mod" = Xyes ; then + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -dynamiclib -single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring' + else + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -r ${wl}-bind_at_load -keep_private_externs -nostdlib -o ${lib}-master.o $libobjs~$CC -dynamiclib $allow_undefined_flag -o $lib ${lib}-master.o $deplibs $compiler_flags -install_name $rpath/$soname $verstring' + fi + _LT_AC_TAGVAR(module_cmds, $1)='$CC ${wl}-bind_at_load $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags' + + # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin ld's + if test "X$lt_int_apple_cc_single_mod" = Xyes ; then + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -dynamiclib -single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + else + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -r ${wl}-bind_at_load -keep_private_externs -nostdlib -o ${lib}-master.o $libobjs~$CC -dynamiclib $allow_undefined_flag -o $lib ${lib}-master.o $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + fi + _LT_AC_TAGVAR(module_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + _LT_AC_TAGVAR(hardcode_direct, $1)=no + _LT_AC_TAGVAR(hardcode_automatic, $1)=yes + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=unsupported + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='-all_load $convenience' + _LT_AC_TAGVAR(link_all_deplibs, $1)=yes + else + _LT_AC_TAGVAR(ld_shlibs, $1)=no + fi + ;; + + dgux*) + case $cc_basename in + ec++) + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + ghcx) + # Green Hills C++ Compiler + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + *) + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + esac + ;; + freebsd[12]*) + # C++ shared libraries reported to be fairly broken before switch to ELF + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + freebsd-elf*) + _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no + ;; + freebsd* | kfreebsd*-gnu) + # FreeBSD 3 and later use GNU C++ and GNU ld with standard ELF + # conventions + _LT_AC_TAGVAR(ld_shlibs, $1)=yes + ;; + gnu*) + ;; + hpux9*) + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH, + # but as the default + # location of the library. + + case $cc_basename in + CC) + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + aCC) + _LT_AC_TAGVAR(archive_cmds, $1)='$rm $output_objdir/$soname~$CC -b ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | grep "[-]L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list' + ;; + *) + if test "$GXX" = yes; then + _LT_AC_TAGVAR(archive_cmds, $1)='$rm $output_objdir/$soname~$CC -shared -nostdlib -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + else + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + fi + ;; + esac + ;; + hpux10*|hpux11*) + if test $with_gnu_ld = no; then + case "$host_cpu" in + hppa*64*) + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' + _LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)='+b $libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + ;; + ia64*) + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + ;; + *) + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' + ;; + esac + fi + case "$host_cpu" in + hppa*64*) + _LT_AC_TAGVAR(hardcode_direct, $1)=no + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + ia64*) + _LT_AC_TAGVAR(hardcode_direct, $1)=no + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH, + # but as the default + # location of the library. + ;; + *) + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH, + # but as the default + # location of the library. + ;; + esac + + case $cc_basename in + CC) + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + aCC) + case "$host_cpu" in + hppa*64*|ia64*) + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -b +h $soname -o $lib $linker_flags $libobjs $deplibs' + ;; + *) + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + esac + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | grep "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list' + ;; + *) + if test "$GXX" = yes; then + if test $with_gnu_ld = no; then + case "$host_cpu" in + ia64*|hppa*64*) + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -b +h $soname -o $lib $linker_flags $libobjs $deplibs' + ;; + *) + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + esac + fi + else + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + fi + ;; + esac + ;; + irix5* | irix6*) + case $cc_basename in + CC) + # SGI C++ + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${objdir}/so_locations -o $lib' + + # Archives containing C++ object files must be created using + # "CC -ar", where "CC" is the IRIX C++ compiler. This is + # necessary to make sure instantiated templates are included + # in the archive. + _LT_AC_TAGVAR(old_archive_cmds, $1)='$CC -ar -WR,-u -o $oldlib $oldobjs' + ;; + *) + if test "$GXX" = yes; then + if test "$with_gnu_ld" = no; then + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${objdir}/so_locations -o $lib' + else + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` -o $lib' + fi + fi + _LT_AC_TAGVAR(link_all_deplibs, $1)=yes + ;; + esac + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + ;; + linux*) + case $cc_basename in + KCC) + # Kuck and Associates, Inc. (KAI) C++ Compiler + + # KCC will only create a shared library if the output file + # ends with ".so" (or ".sl" for HP-UX), so rename the library + # to its proper name (with version) after linking. + _LT_AC_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib ${wl}-retain-symbols-file,$export_symbols; mv \$templib $lib' + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | grep "ld"`; rm -f libconftest$shared_ext; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list' + + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath,$libdir' + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' + + # Archives containing C++ object files must be created using + # "CC -Bstatic", where "CC" is the KAI C++ compiler. + _LT_AC_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs' + ;; + icpc) + # Intel C++ + with_gnu_ld=yes + _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive' + ;; + cxx) + # Compaq C++ + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib ${wl}-retain-symbols-file $wl$export_symbols' + + runpath_var=LD_RUN_PATH + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "ld"`; templist=`echo $templist | $SED "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list' + ;; + esac + ;; + lynxos*) + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + m88k*) + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + mvs*) + case $cc_basename in + cxx) + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + *) + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + esac + ;; + netbsd* | netbsdelf*-gnu | knetbsd*-gnu) + if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $predep_objects $libobjs $deplibs $postdep_objects $linker_flags' + wlarc= + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + fi + # Workaround some broken pre-1.5 toolchains + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep conftest.$objext | $SED -e "s:-lgcc -lc -lgcc::"' + ;; + osf3*) + case $cc_basename in + KCC) + # Kuck and Associates, Inc. (KAI) C++ Compiler + + # KCC will only create a shared library if the output file + # ends with ".so" (or ".sl" for HP-UX), so rename the library + # to its proper name (with version) after linking. + _LT_AC_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' + + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + + # Archives containing C++ object files must be created using + # "CC -Bstatic", where "CC" is the KAI C++ compiler. + _LT_AC_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs' + + ;; + RCC) + # Rational C++ 2.4.1 + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + cxx) + _LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && echo ${wl}-set_version $verstring` -update_registry ${objdir}/so_locations -o $lib' + + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "ld" | grep -v "ld:"`; templist=`echo $templist | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list' + ;; + *) + if test "$GXX" = yes && test "$with_gnu_ld" = no; then + _LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${objdir}/so_locations -o $lib' + + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "\-L"' + + else + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + fi + ;; + esac + ;; + osf4* | osf5*) + case $cc_basename in + KCC) + # Kuck and Associates, Inc. (KAI) C++ Compiler + + # KCC will only create a shared library if the output file + # ends with ".so" (or ".sl" for HP-UX), so rename the library + # to its proper name (with version) after linking. + _LT_AC_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' + + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + + # Archives containing C++ object files must be created using + # the KAI C++ compiler. + _LT_AC_TAGVAR(old_archive_cmds, $1)='$CC -o $oldlib $oldobjs' + ;; + RCC) + # Rational C++ 2.4.1 + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + cxx) + _LT_AC_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${objdir}/so_locations -o $lib' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~ + echo "-hidden">> $lib.exp~ + $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname -Wl,-input -Wl,$lib.exp `test -n "$verstring" && echo -set_version $verstring` -update_registry $objdir/so_locations -o $lib~ + $rm $lib.exp' + + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "ld" | grep -v "ld:"`; templist=`echo $templist | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list' + ;; + *) + if test "$GXX" = yes && test "$with_gnu_ld" = no; then + _LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${objdir}/so_locations -o $lib' + + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "\-L"' + + else + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + fi + ;; + esac + ;; + psos*) + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + sco*) + _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no + case $cc_basename in + CC) + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + *) + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + esac + ;; + sunos4*) + case $cc_basename in + CC) + # Sun C++ 4.x + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + lcc) + # Lucid + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + *) + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + esac + ;; + solaris*) + case $cc_basename in + CC) + # Sun C++ 4.2, 5.x and Centerline C++ + _LT_AC_TAGVAR(no_undefined_flag, $1)=' -zdefs' + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -nolib -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~ + $CC -G${allow_undefined_flag} -nolib ${wl}-M ${wl}$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$rm $lib.exp' + + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + case $host_os in + solaris2.[0-5] | solaris2.[0-5].*) ;; + *) + # The C++ compiler is used as linker so we must use $wl + # flag to pass the commands to the underlying system + # linker. + # Supported since Solaris 2.6 (maybe 2.5.1?) + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' + ;; + esac + _LT_AC_TAGVAR(link_all_deplibs, $1)=yes + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`$CC -G $CFLAGS -v conftest.$objext 2>&1 | grep "\-[[LR]]"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list' + + # Archives containing C++ object files must be created using + # "CC -xar", where "CC" is the Sun C++ compiler. This is + # necessary to make sure instantiated templates are included + # in the archive. + _LT_AC_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs' + ;; + gcx) + # Green Hills C++ Compiler + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' + + # The C++ compiler must be used to create the archive. + _LT_AC_TAGVAR(old_archive_cmds, $1)='$CC $LDFLAGS -archive -o $oldlib $oldobjs' + ;; + *) + # GNU C++ compiler with Solaris linker + if test "$GXX" = yes && test "$with_gnu_ld" = no; then + _LT_AC_TAGVAR(no_undefined_flag, $1)=' ${wl}-z ${wl}defs' + if $CC --version | grep -v '^2\.7' > /dev/null; then + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~ + $CC -shared -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$rm $lib.exp' + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + output_verbose_link_cmd="$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep \"\-L\"" + else + # g++ 2.7 appears to require `-G' NOT `-shared' on this + # platform. + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -G -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~ + $CC -G -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$rm $lib.exp' + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + output_verbose_link_cmd="$CC -G $CFLAGS -v conftest.$objext 2>&1 | grep \"\-L\"" + fi + + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $wl$libdir' + fi + ;; + esac + ;; + sysv5OpenUNIX8* | sysv5UnixWare7* | sysv5uw[[78]]* | unixware7*) + _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no + ;; + tandem*) + case $cc_basename in + NCC) + # NonStop-UX NCC 3.20 + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + *) + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + esac + ;; + vxworks*) + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + *) + # FIXME: insert proper C++ library support + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; +esac +AC_MSG_RESULT([$_LT_AC_TAGVAR(ld_shlibs, $1)]) +test "$_LT_AC_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no + +_LT_AC_TAGVAR(GCC, $1)="$GXX" +_LT_AC_TAGVAR(LD, $1)="$LD" + +AC_LIBTOOL_POSTDEP_PREDEP($1) +AC_LIBTOOL_PROG_COMPILER_PIC($1) +AC_LIBTOOL_PROG_CC_C_O($1) +AC_LIBTOOL_SYS_HARD_LINK_LOCKS($1) +AC_LIBTOOL_PROG_LD_SHLIBS($1) +AC_LIBTOOL_SYS_DYNAMIC_LINKER($1) +AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH($1) +AC_LIBTOOL_SYS_LIB_STRIP +AC_LIBTOOL_DLOPEN_SELF($1) + +AC_LIBTOOL_CONFIG($1) + +AC_LANG_POP +CC=$lt_save_CC +LDCXX=$LD +LD=$lt_save_LD +GCC=$lt_save_GCC +with_gnu_ldcxx=$with_gnu_ld +with_gnu_ld=$lt_save_with_gnu_ld +lt_cv_path_LDCXX=$lt_cv_path_LD +lt_cv_path_LD=$lt_save_path_LD +lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld +lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld +])# AC_LIBTOOL_LANG_CXX_CONFIG + +# AC_LIBTOOL_POSTDEP_PREDEP([TAGNAME]) +# ------------------------ +# Figure out "hidden" library dependencies from verbose +# compiler output when linking a shared library. +# Parse the compiler output and extract the necessary +# objects, libraries and library flags. +AC_DEFUN([AC_LIBTOOL_POSTDEP_PREDEP],[ +dnl we can't use the lt_simple_compile_test_code here, +dnl because it contains code intended for an executable, +dnl not a library. It's possible we should let each +dnl tag define a new lt_????_link_test_code variable, +dnl but it's only used here... +ifelse([$1],[],[cat > conftest.$ac_ext < conftest.$ac_ext < conftest.$ac_ext < conftest.$ac_ext <> "$cfgfile" +ifelse([$1], [], +[#! $SHELL + +# `$echo "$cfgfile" | sed 's%^.*/%%'` - Provide generalized library-building support services. +# Generated automatically by $PROGRAM (GNU $PACKAGE $VERSION$TIMESTAMP) +# NOTE: Changes made to this file will be lost: look at ltmain.sh. +# +# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001 +# Free Software Foundation, Inc. +# +# This file is part of GNU Libtool: +# Originally by Gordon Matzigkeit , 1996 +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +# +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + +# A sed program that does not truncate output. +SED=$lt_SED + +# Sed that helps us avoid accidentally triggering echo(1) options like -n. +Xsed="$SED -e s/^X//" + +# The HP-UX ksh and POSIX shell print the target directory to stdout +# if CDPATH is set. +if test "X\${CDPATH+set}" = Xset; then CDPATH=:; export CDPATH; fi + +# The names of the tagged configurations supported by this script. +available_tags= + +# ### BEGIN LIBTOOL CONFIG], +[# ### BEGIN LIBTOOL TAG CONFIG: $tagname]) + +# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`: + +# Shell to use when invoking shell scripts. +SHELL=$lt_SHELL + +# Whether or not to build shared libraries. +build_libtool_libs=$enable_shared + +# Whether or not to build static libraries. +build_old_libs=$enable_static + +# Whether or not to add -lc for building shared libraries. +build_libtool_need_lc=$_LT_AC_TAGVAR(archive_cmds_need_lc, $1) + +# Whether or not to disallow shared libs when runtime libs are static +allow_libtool_libs_with_static_runtimes=$_LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1) + +# Whether or not to optimize for fast installation. +fast_install=$enable_fast_install + +# The host system. +host_alias=$host_alias +host=$host + +# An echo program that does not interpret backslashes. +echo=$lt_echo + +# The archiver. +AR=$lt_AR +AR_FLAGS=$lt_AR_FLAGS + +# A C compiler. +LTCC=$lt_LTCC + +# A language-specific compiler. +CC=$lt_[]_LT_AC_TAGVAR(compiler, $1) + +# Is the compiler the GNU C compiler? +with_gcc=$_LT_AC_TAGVAR(GCC, $1) + +# An ERE matcher. +EGREP=$lt_EGREP + +# The linker used to build libraries. +LD=$lt_[]_LT_AC_TAGVAR(LD, $1) + +# Whether we need hard or soft links. +LN_S=$lt_LN_S + +# A BSD-compatible nm program. +NM=$lt_NM + +# A symbol stripping program +STRIP=$lt_STRIP + +# Used to examine libraries when file_magic_cmd begins "file" +MAGIC_CMD=$MAGIC_CMD + +# Used on cygwin: DLL creation program. +DLLTOOL="$DLLTOOL" + +# Used on cygwin: object dumper. +OBJDUMP="$OBJDUMP" + +# Used on cygwin: assembler. +AS="$AS" + +# The name of the directory that contains temporary libtool files. +objdir=$objdir + +# How to create reloadable object files. +reload_flag=$lt_reload_flag +reload_cmds=$lt_reload_cmds + +# How to pass a linker flag through the compiler. +wl=$lt_[]_LT_AC_TAGVAR(lt_prog_compiler_wl, $1) + +# Object file suffix (normally "o"). +objext="$ac_objext" + +# Old archive suffix (normally "a"). +libext="$libext" + +# Shared library suffix (normally ".so"). +shrext_cmds='$shrext_cmds' + +# Executable file suffix (normally ""). +exeext="$exeext" + +# Additional compiler flags for building library objects. +pic_flag=$lt_[]_LT_AC_TAGVAR(lt_prog_compiler_pic, $1) +pic_mode=$pic_mode + +# What is the maximum length of a command? +max_cmd_len=$lt_cv_sys_max_cmd_len + +# Does compiler simultaneously support -c and -o options? +compiler_c_o=$lt_[]_LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1) + +# Must we lock files when doing compilation ? +need_locks=$lt_need_locks + +# Do we need the lib prefix for modules? +need_lib_prefix=$need_lib_prefix + +# Do we need a version for libraries? +need_version=$need_version + +# Whether dlopen is supported. +dlopen_support=$enable_dlopen + +# Whether dlopen of programs is supported. +dlopen_self=$enable_dlopen_self + +# Whether dlopen of statically linked programs is supported. +dlopen_self_static=$enable_dlopen_self_static + +# Compiler flag to prevent dynamic linking. +link_static_flag=$lt_[]_LT_AC_TAGVAR(lt_prog_compiler_static, $1) + +# Compiler flag to turn off builtin functions. +no_builtin_flag=$lt_[]_LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1) + +# Compiler flag to allow reflexive dlopens. +export_dynamic_flag_spec=$lt_[]_LT_AC_TAGVAR(export_dynamic_flag_spec, $1) + +# Compiler flag to generate shared objects directly from archives. +whole_archive_flag_spec=$lt_[]_LT_AC_TAGVAR(whole_archive_flag_spec, $1) + +# Compiler flag to generate thread-safe objects. +thread_safe_flag_spec=$lt_[]_LT_AC_TAGVAR(thread_safe_flag_spec, $1) + +# Library versioning type. +version_type=$version_type + +# Format of library name prefix. +libname_spec=$lt_libname_spec + +# List of archive names. First name is the real one, the rest are links. +# The last name is the one that the linker finds with -lNAME. +library_names_spec=$lt_library_names_spec + +# The coded name of the library, if different from the real name. +soname_spec=$lt_soname_spec + +# Commands used to build and install an old-style archive. +RANLIB=$lt_RANLIB +old_archive_cmds=$lt_[]_LT_AC_TAGVAR(old_archive_cmds, $1) +old_postinstall_cmds=$lt_old_postinstall_cmds +old_postuninstall_cmds=$lt_old_postuninstall_cmds + +# Create an old-style archive from a shared archive. +old_archive_from_new_cmds=$lt_[]_LT_AC_TAGVAR(old_archive_from_new_cmds, $1) + +# Create a temporary old-style archive to link instead of a shared archive. +old_archive_from_expsyms_cmds=$lt_[]_LT_AC_TAGVAR(old_archive_from_expsyms_cmds, $1) + +# Commands used to build and install a shared archive. +archive_cmds=$lt_[]_LT_AC_TAGVAR(archive_cmds, $1) +archive_expsym_cmds=$lt_[]_LT_AC_TAGVAR(archive_expsym_cmds, $1) +postinstall_cmds=$lt_postinstall_cmds +postuninstall_cmds=$lt_postuninstall_cmds + +# Commands used to build a loadable module (assumed same as above if empty) +module_cmds=$lt_[]_LT_AC_TAGVAR(module_cmds, $1) +module_expsym_cmds=$lt_[]_LT_AC_TAGVAR(module_expsym_cmds, $1) + +# Commands to strip libraries. +old_striplib=$lt_old_striplib +striplib=$lt_striplib + +# Dependencies to place before the objects being linked to create a +# shared library. +predep_objects=$lt_[]_LT_AC_TAGVAR(predep_objects, $1) + +# Dependencies to place after the objects being linked to create a +# shared library. +postdep_objects=$lt_[]_LT_AC_TAGVAR(postdep_objects, $1) + +# Dependencies to place before the objects being linked to create a +# shared library. +predeps=$lt_[]_LT_AC_TAGVAR(predeps, $1) + +# Dependencies to place after the objects being linked to create a +# shared library. +postdeps=$lt_[]_LT_AC_TAGVAR(postdeps, $1) + +# The library search path used internally by the compiler when linking +# a shared library. +compiler_lib_search_path=$lt_[]_LT_AC_TAGVAR(compiler_lib_search_path, $1) + +# Method to check whether dependent libraries are shared objects. +deplibs_check_method=$lt_deplibs_check_method + +# Command to use when deplibs_check_method == file_magic. +file_magic_cmd=$lt_file_magic_cmd + +# Flag that allows shared libraries with undefined symbols to be built. +allow_undefined_flag=$lt_[]_LT_AC_TAGVAR(allow_undefined_flag, $1) + +# Flag that forces no undefined symbols. +no_undefined_flag=$lt_[]_LT_AC_TAGVAR(no_undefined_flag, $1) + +# Commands used to finish a libtool library installation in a directory. +finish_cmds=$lt_finish_cmds + +# Same as above, but a single script fragment to be evaled but not shown. +finish_eval=$lt_finish_eval + +# Take the output of nm and produce a listing of raw symbols and C names. +global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe + +# Transform the output of nm in a proper C declaration +global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl + +# Transform the output of nm in a C name address pair +global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address + +# This is the shared library runtime path variable. +runpath_var=$runpath_var + +# This is the shared library path variable. +shlibpath_var=$shlibpath_var + +# Is shlibpath searched before the hard-coded library search path? +shlibpath_overrides_runpath=$shlibpath_overrides_runpath + +# How to hardcode a shared library path into an executable. +hardcode_action=$_LT_AC_TAGVAR(hardcode_action, $1) + +# Whether we should hardcode library paths into libraries. +hardcode_into_libs=$hardcode_into_libs + +# Flag to hardcode \$libdir into a binary during linking. +# This must work even if \$libdir does not exist. +hardcode_libdir_flag_spec=$lt_[]_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1) + +# If ld is used when linking, flag to hardcode \$libdir into +# a binary during linking. This must work even if \$libdir does +# not exist. +hardcode_libdir_flag_spec_ld=$lt_[]_LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1) + +# Whether we need a single -rpath flag with a separated argument. +hardcode_libdir_separator=$lt_[]_LT_AC_TAGVAR(hardcode_libdir_separator, $1) + +# Set to yes if using DIR/libNAME${shared_ext} during linking hardcodes DIR into the +# resulting binary. +hardcode_direct=$_LT_AC_TAGVAR(hardcode_direct, $1) + +# Set to yes if using the -LDIR flag during linking hardcodes DIR into the +# resulting binary. +hardcode_minus_L=$_LT_AC_TAGVAR(hardcode_minus_L, $1) + +# Set to yes if using SHLIBPATH_VAR=DIR during linking hardcodes DIR into +# the resulting binary. +hardcode_shlibpath_var=$_LT_AC_TAGVAR(hardcode_shlibpath_var, $1) + +# Set to yes if building a shared library automatically hardcodes DIR into the library +# and all subsequent libraries and executables linked against it. +hardcode_automatic=$_LT_AC_TAGVAR(hardcode_automatic, $1) + +# Variables whose values should be saved in libtool wrapper scripts and +# restored at relink time. +variables_saved_for_relink="$variables_saved_for_relink" + +# Whether libtool must link a program against all its dependency libraries. +link_all_deplibs=$_LT_AC_TAGVAR(link_all_deplibs, $1) + +# Compile-time system search path for libraries +sys_lib_search_path_spec=$lt_sys_lib_search_path_spec + +# Run-time system search path for libraries +sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec + +# Fix the shell variable \$srcfile for the compiler. +fix_srcfile_path="$_LT_AC_TAGVAR(fix_srcfile_path, $1)" + +# Set to yes if exported symbols are required. +always_export_symbols=$_LT_AC_TAGVAR(always_export_symbols, $1) + +# The commands to list exported symbols. +export_symbols_cmds=$lt_[]_LT_AC_TAGVAR(export_symbols_cmds, $1) + +# The commands to extract the exported symbol list from a shared archive. +extract_expsyms_cmds=$lt_extract_expsyms_cmds + +# Symbols that should not be listed in the preloaded symbols. +exclude_expsyms=$lt_[]_LT_AC_TAGVAR(exclude_expsyms, $1) + +# Symbols that must always be exported. +include_expsyms=$lt_[]_LT_AC_TAGVAR(include_expsyms, $1) + +ifelse([$1],[], +[# ### END LIBTOOL CONFIG], +[# ### END LIBTOOL TAG CONFIG: $tagname]) + +__EOF__ + +ifelse([$1],[], [ + case $host_os in + aix3*) + cat <<\EOF >> "$cfgfile" + +# AIX sometimes has problems with the GCC collect2 program. For some +# reason, if we set the COLLECT_NAMES environment variable, the problems +# vanish in a puff of smoke. +if test "X${COLLECT_NAMES+set}" != Xset; then + COLLECT_NAMES= + export COLLECT_NAMES +fi +EOF + ;; + esac + + # We use sed instead of cat because bash on DJGPP gets confused if + # if finds mixed CR/LF and LF-only lines. Since sed operates in + # text mode, it properly converts lines to CR/LF. This bash problem + # is reportedly fixed, but why not run on old versions too? + sed '$q' "$ltmain" >> "$cfgfile" || (rm -f "$cfgfile"; exit 1) + + mv -f "$cfgfile" "$ofile" || \ + (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile") + chmod +x "$ofile" +]) +else + # If there is no Makefile yet, we rely on a make rule to execute + # `config.status --recheck' to rerun these tests and create the + # libtool script then. + ltmain_in=`echo $ltmain | sed -e 's/\.sh$/.in/'` + if test -f "$ltmain_in"; then + test -f Makefile && make "$ltmain" + fi +fi +])# AC_LIBTOOL_CONFIG + + +# AC_LIBTOOL_PROG_COMPILER_NO_RTTI([TAGNAME]) +# ------------------------------------------- +AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_NO_RTTI], +[AC_REQUIRE([_LT_AC_SYS_COMPILER])dnl + +_LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)= + +if test "$GCC" = yes; then + _LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin' + + AC_LIBTOOL_COMPILER_OPTION([if $compiler supports -fno-rtti -fno-exceptions], + lt_cv_prog_compiler_rtti_exceptions, + [-fno-rtti -fno-exceptions], [], + [_LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)="$_LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1) -fno-rtti -fno-exceptions"]) +fi +])# AC_LIBTOOL_PROG_COMPILER_NO_RTTI + + +# AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE +# --------------------------------- +AC_DEFUN([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE], +[AC_REQUIRE([AC_CANONICAL_HOST]) +AC_REQUIRE([AC_PROG_NM]) +AC_REQUIRE([AC_OBJEXT]) +# Check for command to grab the raw symbol name followed by C symbol from nm. +AC_MSG_CHECKING([command to parse $NM output from $compiler object]) +AC_CACHE_VAL([lt_cv_sys_global_symbol_pipe], +[ +# These are sane defaults that work on at least a few old systems. +# [They come from Ultrix. What could be older than Ultrix?!! ;)] + +# Character class describing NM global symbol codes. +symcode='[[BCDEGRST]]' + +# Regexp to match symbols that can be accessed directly from C. +sympat='\([[_A-Za-z]][[_A-Za-z0-9]]*\)' + +# Transform the above into a raw symbol and a C symbol. +symxfrm='\1 \2\3 \3' + +# Transform an extracted symbol line into a proper C declaration +lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^. .* \(.*\)$/extern int \1;/p'" + +# Transform an extracted symbol line into symbol name and symbol address +lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([[^ ]]*\) $/ {\\\"\1\\\", (lt_ptr) 0},/p' -e 's/^$symcode \([[^ ]]*\) \([[^ ]]*\)$/ {\"\2\", (lt_ptr) \&\2},/p'" + +# Define system-specific variables. +case $host_os in +aix*) + symcode='[[BCDT]]' + ;; +cygwin* | mingw* | pw32*) + symcode='[[ABCDGISTW]]' + ;; +hpux*) # Its linker distinguishes data from code symbols + if test "$host_cpu" = ia64; then + symcode='[[ABCDEGRST]]' + fi + lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'" + lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([[^ ]]*\) $/ {\\\"\1\\\", (lt_ptr) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/ {\"\2\", (lt_ptr) \&\2},/p'" + ;; +irix* | nonstopux*) + symcode='[[BCDEGRST]]' + ;; +osf*) + symcode='[[BCDEGQRST]]' + ;; +solaris* | sysv5*) + symcode='[[BDRT]]' + ;; +sysv4) + symcode='[[DFNSTU]]' + ;; +esac + +# Handle CRLF in mingw tool chain +opt_cr= +case $build_os in +mingw*) + opt_cr=`echo 'x\{0,1\}' | tr x '\015'` # option cr in regexp + ;; +esac + +# If we're using GNU nm, then use its standard symbol codes. +case `$NM -V 2>&1` in +*GNU* | *'with BFD'*) + symcode='[[ABCDGIRSTW]]' ;; +esac + +# Try without a prefix undercore, then with it. +for ac_symprfx in "" "_"; do + + # Write the raw and C identifiers. + lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[[ ]]\($symcode$symcode*\)[[ ]][[ ]]*\($ac_symprfx\)$sympat$opt_cr$/$symxfrm/p'" + + # Check to see that the pipe works correctly. + pipe_works=no + + rm -f conftest* + cat > conftest.$ac_ext < $nlist) && test -s "$nlist"; then + # Try sorting and uniquifying the output. + if sort "$nlist" | uniq > "$nlist"T; then + mv -f "$nlist"T "$nlist" + else + rm -f "$nlist"T + fi + + # Make sure that we snagged all the symbols we need. + if grep ' nm_test_var$' "$nlist" >/dev/null; then + if grep ' nm_test_func$' "$nlist" >/dev/null; then + cat < conftest.$ac_ext +#ifdef __cplusplus +extern "C" { +#endif + +EOF + # Now generate the symbol file. + eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | grep -v main >> conftest.$ac_ext' + + cat <> conftest.$ac_ext +#if defined (__STDC__) && __STDC__ +# define lt_ptr_t void * +#else +# define lt_ptr_t char * +# define const +#endif + +/* The mapping between symbol names and symbols. */ +const struct { + const char *name; + lt_ptr_t address; +} +lt_preloaded_symbols[[]] = +{ +EOF + $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/ {\"\2\", (lt_ptr_t) \&\2},/" < "$nlist" | grep -v main >> conftest.$ac_ext + cat <<\EOF >> conftest.$ac_ext + {0, (lt_ptr_t) 0} +}; + +#ifdef __cplusplus +} +#endif +EOF + # Now try linking the two files. + mv conftest.$ac_objext conftstm.$ac_objext + lt_save_LIBS="$LIBS" + lt_save_CFLAGS="$CFLAGS" + LIBS="conftstm.$ac_objext" + CFLAGS="$CFLAGS$_LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)" + if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext}; then + pipe_works=yes + fi + LIBS="$lt_save_LIBS" + CFLAGS="$lt_save_CFLAGS" + else + echo "cannot find nm_test_func in $nlist" >&AS_MESSAGE_LOG_FD + fi + else + echo "cannot find nm_test_var in $nlist" >&AS_MESSAGE_LOG_FD + fi + else + echo "cannot run $lt_cv_sys_global_symbol_pipe" >&AS_MESSAGE_LOG_FD + fi + else + echo "$progname: failed program was:" >&AS_MESSAGE_LOG_FD + cat conftest.$ac_ext >&5 + fi + rm -f conftest* conftst* + + # Do not use the global_symbol_pipe unless it works. + if test "$pipe_works" = yes; then + break + else + lt_cv_sys_global_symbol_pipe= + fi +done +]) +if test -z "$lt_cv_sys_global_symbol_pipe"; then + lt_cv_sys_global_symbol_to_cdecl= +fi +if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then + AC_MSG_RESULT(failed) +else + AC_MSG_RESULT(ok) +fi +]) # AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE + + +# AC_LIBTOOL_PROG_COMPILER_PIC([TAGNAME]) +# --------------------------------------- +AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_PIC], +[_LT_AC_TAGVAR(lt_prog_compiler_wl, $1)= +_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)= +_LT_AC_TAGVAR(lt_prog_compiler_static, $1)= + +AC_MSG_CHECKING([for $compiler option to produce PIC]) + ifelse([$1],[CXX],[ + # C++ specific cases for pic, static, wl, etc. + if test "$GXX" = yes; then + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-static' + + case $host_os in + aix*) + # All AIX code is PIC. + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + fi + ;; + amigaos*) + # FIXME: we need at least 68020 code to build shared libraries, but + # adding the `-m68020' flag to GCC prevents building anything better, + # like `-m68040'. + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4' + ;; + beos* | cygwin* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) + # PIC is the default for these OSes. + ;; + mingw* | os2* | pw32*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT' + ;; + darwin* | rhapsody*) + # PIC is the default on this platform + # Common symbols not allowed in MH_DYLIB files + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common' + ;; + *djgpp*) + # DJGPP does not support shared libraries at all + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)= + ;; + sysv4*MP*) + if test -d /usr/nec; then + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic + fi + ;; + hpux*) + # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but + # not for PA HP-UX. + case "$host_cpu" in + hppa*64*|ia64*) + ;; + *) + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + ;; + esac + ;; + *) + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + ;; + esac + else + case $host_os in + aix4* | aix5*) + # All AIX code is PIC. + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + else + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp' + fi + ;; + chorus*) + case $cc_basename in + cxch68) + # Green Hills C++ Compiler + # _LT_AC_TAGVAR(lt_prog_compiler_static, $1)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a" + ;; + esac + ;; + dgux*) + case $cc_basename in + ec++) + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + ;; + ghcx) + # Green Hills C++ Compiler + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-pic' + ;; + *) + ;; + esac + ;; + freebsd* | kfreebsd*-gnu) + # FreeBSD uses GNU C++ + ;; + hpux9* | hpux10* | hpux11*) + case $cc_basename in + CC) + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)="${ac_cv_prog_cc_wl}-a ${ac_cv_prog_cc_wl}archive" + if test "$host_cpu" != ia64; then + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='+Z' + fi + ;; + aCC) + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)="${ac_cv_prog_cc_wl}-a ${ac_cv_prog_cc_wl}archive" + case "$host_cpu" in + hppa*64*|ia64*) + # +Z the default + ;; + *) + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='+Z' + ;; + esac + ;; + *) + ;; + esac + ;; + irix5* | irix6* | nonstopux*) + case $cc_basename in + CC) + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' + # CC pic flag -KPIC is the default. + ;; + *) + ;; + esac + ;; + linux*) + case $cc_basename in + KCC) + # KAI C++ Compiler + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,' + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + ;; + icpc) + # Intel C++ + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-static' + ;; + cxx) + # Compaq C++ + # Make sure the PIC flag is empty. It appears that all Alpha + # Linux and Compaq Tru64 Unix objects are PIC. + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)= + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' + ;; + *) + ;; + esac + ;; + lynxos*) + ;; + m88k*) + ;; + mvs*) + case $cc_basename in + cxx) + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-W c,exportall' + ;; + *) + ;; + esac + ;; + netbsd* | netbsdelf*-gnu | knetbsd*-gnu) + ;; + osf3* | osf4* | osf5*) + case $cc_basename in + KCC) + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,' + ;; + RCC) + # Rational C++ 2.4.1 + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-pic' + ;; + cxx) + # Digital/Compaq C++ + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + # Make sure the PIC flag is empty. It appears that all Alpha + # Linux and Compaq Tru64 Unix objects are PIC. + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)= + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' + ;; + *) + ;; + esac + ;; + psos*) + ;; + sco*) + case $cc_basename in + CC) + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + ;; + *) + ;; + esac + ;; + solaris*) + case $cc_basename in + CC) + # Sun C++ 4.2, 5.x and Centerline C++ + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' + ;; + gcx) + # Green Hills C++ Compiler + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-PIC' + ;; + *) + ;; + esac + ;; + sunos4*) + case $cc_basename in + CC) + # Sun C++ 4.x + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-pic' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + lcc) + # Lucid + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-pic' + ;; + *) + ;; + esac + ;; + tandem*) + case $cc_basename in + NCC) + # NonStop-UX NCC 3.20 + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + ;; + *) + ;; + esac + ;; + unixware*) + ;; + vxworks*) + ;; + *) + _LT_AC_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no + ;; + esac + fi +], +[ + if test "$GCC" = yes; then + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-static' + + case $host_os in + aix*) + # All AIX code is PIC. + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + fi + ;; + + amigaos*) + # FIXME: we need at least 68020 code to build shared libraries, but + # adding the `-m68020' flag to GCC prevents building anything better, + # like `-m68040'. + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4' + ;; + + beos* | cygwin* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) + # PIC is the default for these OSes. + ;; + + mingw* | pw32* | os2*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT' + ;; + + darwin* | rhapsody*) + # PIC is the default on this platform + # Common symbols not allowed in MH_DYLIB files + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common' + ;; + + msdosdjgpp*) + # Just because we use GCC doesn't mean we suddenly get shared libraries + # on systems that don't support them. + _LT_AC_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no + enable_shared=no + ;; + + sysv4*MP*) + if test -d /usr/nec; then + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic + fi + ;; + + hpux*) + # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but + # not for PA HP-UX. + case "$host_cpu" in + hppa*64*|ia64*) + # +Z the default + ;; + *) + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + ;; + esac + ;; + + *) + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + ;; + esac + else + # PORTME Check for flag to pass linker flags through the system compiler. + case $host_os in + aix*) + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + else + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp' + fi + ;; + + mingw* | pw32* | os2*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT' + ;; + + hpux9* | hpux10* | hpux11*) + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but + # not for PA HP-UX. + case "$host_cpu" in + hppa*64*|ia64*) + # +Z the default + ;; + *) + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='+Z' + ;; + esac + # Is there a better lt_prog_compiler_static that works with the bundled CC? + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive' + ;; + + irix5* | irix6* | nonstopux*) + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + # PIC (with -KPIC) is the default. + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' + ;; + + newsos6) + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + + linux*) + case $CC in + icc* | ecc*) + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-static' + ;; + ccc*) + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + # All Alpha code is PIC. + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' + ;; + esac + ;; + + osf3* | osf4* | osf5*) + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + # All OSF/1 code is PIC. + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' + ;; + + sco3.2v5*) + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-Kpic' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-dn' + ;; + + solaris*) + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + + sunos4*) + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-PIC' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + + sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*) + _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + + sysv4*MP*) + if test -d /usr/nec ;then + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-Kconform_pic' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + fi + ;; + + uts4*) + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-pic' + _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + + *) + _LT_AC_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no + ;; + esac + fi +]) +AC_MSG_RESULT([$_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)]) + +# +# Check to make sure the PIC flag actually works. +# +if test -n "$_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)"; then + AC_LIBTOOL_COMPILER_OPTION([if $compiler PIC flag $_LT_AC_TAGVAR(lt_prog_compiler_pic, $1) works], + _LT_AC_TAGVAR(lt_prog_compiler_pic_works, $1), + [$_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)ifelse([$1],[],[ -DPIC],[ifelse([$1],[CXX],[ -DPIC],[])])], [], + [case $_LT_AC_TAGVAR(lt_prog_compiler_pic, $1) in + "" | " "*) ;; + *) _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=" $_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)" ;; + esac], + [_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)= + _LT_AC_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no]) +fi +case "$host_os" in + # For platforms which do not support PIC, -DPIC is meaningless: + *djgpp*) + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)= + ;; + *) + _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)="$_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)ifelse([$1],[],[ -DPIC],[ifelse([$1],[CXX],[ -DPIC],[])])" + ;; +esac +]) + + +# AC_LIBTOOL_PROG_LD_SHLIBS([TAGNAME]) +# ------------------------------------ +# See if the linker supports building shared libraries. +AC_DEFUN([AC_LIBTOOL_PROG_LD_SHLIBS], +[AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries]) +ifelse([$1],[CXX],[ + _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' + case $host_os in + aix4* | aix5*) + # If we're using GNU nm, then we don't want the "-C" option. + # -C means demangle to AIX nm, but means don't demangle with GNU nm + if $NM -V 2>&1 | grep 'GNU' > /dev/null; then + _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\[$]2 == "T") || (\[$]2 == "D") || (\[$]2 == "B")) && ([substr](\[$]3,1,1) != ".")) { print \[$]3 } }'\'' | sort -u > $export_symbols' + else + _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\[$]2 == "T") || (\[$]2 == "D") || (\[$]2 == "B")) && ([substr](\[$]3,1,1) != ".")) { print \[$]3 } }'\'' | sort -u > $export_symbols' + fi + ;; + pw32*) + _LT_AC_TAGVAR(export_symbols_cmds, $1)="$ltdll_cmds" + ;; + cygwin* | mingw*) + _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGS]] /s/.* \([[^ ]]*\)/\1 DATA/'\'' | $SED -e '\''/^[[AITW]] /s/.* //'\'' | sort | uniq > $export_symbols' + ;; + linux*) + _LT_AC_TAGVAR(link_all_deplibs, $1)=no + ;; + *) + _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' + ;; + esac +],[ + runpath_var= + _LT_AC_TAGVAR(allow_undefined_flag, $1)= + _LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1)=no + _LT_AC_TAGVAR(archive_cmds, $1)= + _LT_AC_TAGVAR(archive_expsym_cmds, $1)= + _LT_AC_TAGVAR(old_archive_From_new_cmds, $1)= + _LT_AC_TAGVAR(old_archive_from_expsyms_cmds, $1)= + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)= + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)= + _LT_AC_TAGVAR(thread_safe_flag_spec, $1)= + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)= + _LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)= + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)= + _LT_AC_TAGVAR(hardcode_direct, $1)=no + _LT_AC_TAGVAR(hardcode_minus_L, $1)=no + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=unsupported + _LT_AC_TAGVAR(link_all_deplibs, $1)=unknown + _LT_AC_TAGVAR(hardcode_automatic, $1)=no + _LT_AC_TAGVAR(module_cmds, $1)= + _LT_AC_TAGVAR(module_expsym_cmds, $1)= + _LT_AC_TAGVAR(always_export_symbols, $1)=no + _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' + # include_expsyms should be a list of space-separated symbols to be *always* + # included in the symbol list + _LT_AC_TAGVAR(include_expsyms, $1)= + # exclude_expsyms can be an extended regexp of symbols to exclude + # it will be wrapped by ` (' and `)$', so one must not match beginning or + # end of line. Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc', + # as well as any symbol that contains `d'. + _LT_AC_TAGVAR(exclude_expsyms, $1)="_GLOBAL_OFFSET_TABLE_" + # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out + # platforms (ab)use it in PIC code, but their linkers get confused if + # the symbol is explicitly referenced. Since portable code cannot + # rely on this symbol name, it's probably fine to never include it in + # preloaded symbol tables. + extract_expsyms_cmds= + + case $host_os in + cygwin* | mingw* | pw32*) + # FIXME: the MSVC++ port hasn't been tested in a loooong time + # When not using gcc, we currently assume that we are using + # Microsoft Visual C++. + if test "$GCC" != yes; then + with_gnu_ld=no + fi + ;; + openbsd*) + with_gnu_ld=no + ;; + esac + + _LT_AC_TAGVAR(ld_shlibs, $1)=yes + if test "$with_gnu_ld" = yes; then + # If archive_cmds runs LD, not CC, wlarc should be empty + wlarc='${wl}' + + # See if GNU ld supports shared libraries. + case $host_os in + aix3* | aix4* | aix5*) + # On AIX/PPC, the GNU linker is very broken + if test "$host_cpu" != ia64; then + _LT_AC_TAGVAR(ld_shlibs, $1)=no + cat <&2 + +*** Warning: the GNU linker, at least up to release 2.9.1, is reported +*** to be unable to reliably create shared libraries on AIX. +*** Therefore, libtool is disabling shared libraries support. If you +*** really care for shared libraries, you may want to modify your PATH +*** so that a non-GNU linker is found, and then restart. + +EOF + fi + ;; + + amigaos*) + _LT_AC_TAGVAR(archive_cmds, $1)='$rm $output_objdir/a2ixlibrary.data~$echo "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes + + # Samuel A. Falvo II reports + # that the semantics of dynamic libraries on AmigaOS, at least up + # to version 4, is to share data among multiple programs linked + # with the same dynamic library. Since this doesn't match the + # behavior of shared libraries on other platforms, we can't use + # them. + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + + beos*) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + _LT_AC_TAGVAR(allow_undefined_flag, $1)=unsupported + # Joseph Beckenbach says some releases of gcc + # support --undefined. This deserves some investigation. FIXME + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + else + _LT_AC_TAGVAR(ld_shlibs, $1)=no + fi + ;; + + cygwin* | mingw* | pw32*) + # _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless, + # as there is no search path for DLLs. + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_AC_TAGVAR(allow_undefined_flag, $1)=unsupported + _LT_AC_TAGVAR(always_export_symbols, $1)=no + _LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1)=yes + _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGS]] /s/.* \([[^ ]]*\)/\1 DATA/'\'' | $SED -e '\''/^[[AITW]] /s/.* //'\'' | sort | uniq > $export_symbols' + + if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--image-base=0x10000000 ${wl}--out-implib,$lib' + # If the export-symbols file already is a .def file (1st line + # is EXPORTS), use it as is; otherwise, prepend... + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then + cp $export_symbols $output_objdir/$soname.def; + else + echo EXPORTS > $output_objdir/$soname.def; + cat $export_symbols >> $output_objdir/$soname.def; + fi~ + $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--image-base=0x10000000 ${wl}--out-implib,$lib' + else + ld_shlibs=no + fi + ;; + + netbsd* | netbsdelf*-gnu | knetbsd*-gnu) + if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib' + wlarc= + else + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + fi + ;; + + solaris* | sysv5*) + if $LD -v 2>&1 | grep 'BFD 2\.8' > /dev/null; then + _LT_AC_TAGVAR(ld_shlibs, $1)=no + cat <&2 + +*** Warning: The releases 2.8.* of the GNU linker cannot reliably +*** create shared libraries on Solaris systems. Therefore, libtool +*** is disabling shared libraries support. We urge you to upgrade GNU +*** binutils to release 2.9.1 or newer. Another option is to modify +*** your PATH or compiler configuration so that the native linker is +*** used, and then restart. + +EOF + elif $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + else + _LT_AC_TAGVAR(ld_shlibs, $1)=no + fi + ;; + + sunos4*) + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags' + wlarc= + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + linux*) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + tmp_archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + _LT_AC_TAGVAR(archive_cmds, $1)="$tmp_archive_cmds" + supports_anon_versioning=no + case `$LD -v 2>/dev/null` in + *\ [01].* | *\ 2.[[0-9]].* | *\ 2.10.*) ;; # catch versions < 2.11 + *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ... + *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ... + *\ 2.11.*) ;; # other 2.11 versions + *) supports_anon_versioning=yes ;; + esac + if test $supports_anon_versioning = yes; then + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$echo "{ global:" > $output_objdir/$libname.ver~ +cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ +$echo "local: *; };" >> $output_objdir/$libname.ver~ + $CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib' + else + _LT_AC_TAGVAR(archive_expsym_cmds, $1)="$tmp_archive_cmds" + fi + _LT_AC_TAGVAR(link_all_deplibs, $1)=no + else + _LT_AC_TAGVAR(ld_shlibs, $1)=no + fi + ;; + + *) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + else + _LT_AC_TAGVAR(ld_shlibs, $1)=no + fi + ;; + esac + + if test "$_LT_AC_TAGVAR(ld_shlibs, $1)" = yes; then + runpath_var=LD_RUN_PATH + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath ${wl}$libdir' + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' + # ancient GNU ld didn't support --whole-archive et. al. + if $LD --help 2>&1 | grep 'no-whole-archive' > /dev/null; then + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' + else + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)= + fi + fi + else + # PORTME fill in a description of your system's linker (not GNU ld) + case $host_os in + aix3*) + _LT_AC_TAGVAR(allow_undefined_flag, $1)=unsupported + _LT_AC_TAGVAR(always_export_symbols, $1)=yes + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname' + # Note: this linker hardcodes the directories in LIBPATH if there + # are no directories specified by -L. + _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes + if test "$GCC" = yes && test -z "$link_static_flag"; then + # Neither direct hardcoding nor static linking is supported with a + # broken collect2. + _LT_AC_TAGVAR(hardcode_direct, $1)=unsupported + fi + ;; + + aix4* | aix5*) + if test "$host_cpu" = ia64; then + # On IA64, the linker does run time linking by default, so we don't + # have to do anything special. + aix_use_runtimelinking=no + exp_sym_flag='-Bexport' + no_entry_flag="" + else + # If we're using GNU nm, then we don't want the "-C" option. + # -C means demangle to AIX nm, but means don't demangle with GNU nm + if $NM -V 2>&1 | grep 'GNU' > /dev/null; then + _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\[$]2 == "T") || (\[$]2 == "D") || (\[$]2 == "B")) && ([substr](\[$]3,1,1) != ".")) { print \[$]3 } }'\'' | sort -u > $export_symbols' + else + _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\[$]2 == "T") || (\[$]2 == "D") || (\[$]2 == "B")) && ([substr](\[$]3,1,1) != ".")) { print \[$]3 } }'\'' | sort -u > $export_symbols' + fi + aix_use_runtimelinking=no + + # Test if we are trying to use run time linking or normal + # AIX style linking. If -brtl is somewhere in LDFLAGS, we + # need to do runtime linking. + case $host_os in aix4.[[23]]|aix4.[[23]].*|aix5*) + for ld_flag in $LDFLAGS; do + if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then + aix_use_runtimelinking=yes + break + fi + done + esac + + exp_sym_flag='-bexport' + no_entry_flag='-bnoentry' + fi + + # When large executables or shared objects are built, AIX ld can + # have problems creating the table of contents. If linking a library + # or program results in "error TOC overflow" add -mminimal-toc to + # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not + # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. + + _LT_AC_TAGVAR(archive_cmds, $1)='' + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=':' + _LT_AC_TAGVAR(link_all_deplibs, $1)=yes + + if test "$GCC" = yes; then + case $host_os in aix4.[012]|aix4.[012].*) + # We only want to do this on AIX 4.2 and lower, the check + # below for broken collect2 doesn't work under 4.3+ + collect2name=`${CC} -print-prog-name=collect2` + if test -f "$collect2name" && \ + strings "$collect2name" | grep resolve_lib_name >/dev/null + then + # We have reworked collect2 + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + else + # We have old collect2 + _LT_AC_TAGVAR(hardcode_direct, $1)=unsupported + # It fails to find uninstalled libraries when the uninstalled + # path is not listed in the libpath. Setting hardcode_minus_L + # to unsupported forces relinking + _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)= + fi + esac + shared_flag='-shared' + else + # not using gcc + if test "$host_cpu" = ia64; then + # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release + # chokes on -Wl,-G. The following line is correct: + shared_flag='-G' + else + if test "$aix_use_runtimelinking" = yes; then + shared_flag='${wl}-G' + else + shared_flag='${wl}-bM:SRE' + fi + fi + fi + + # It seems that -bexpall does not export symbols beginning with + # underscore (_), so it is better to generate a list of symbols to export. + _LT_AC_TAGVAR(always_export_symbols, $1)=yes + if test "$aix_use_runtimelinking" = yes; then + # Warning - without using the other runtime loading flags (-brtl), + # -berok will link without error, but may produce a broken library. + _LT_AC_TAGVAR(allow_undefined_flag, $1)='-berok' + # Determine the default libpath from the value encoded in an empty executable. + _LT_AC_SYS_LIBPATH_AIX + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath" + _LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$no_entry_flag \${wl}$exp_sym_flag:\$export_symbols $shared_flag" + else + if test "$host_cpu" = ia64; then + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib' + _LT_AC_TAGVAR(allow_undefined_flag, $1)="-z nodefs" + _LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$no_entry_flag \${wl}$exp_sym_flag:\$export_symbols" + else + # Determine the default libpath from the value encoded in an empty executable. + _LT_AC_SYS_LIBPATH_AIX + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath" + # Warning - without using the other run time loading flags, + # -berok will link without error, but may produce a broken library. + _LT_AC_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok' + _LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok' + # -bexpall does not export symbols beginning with underscore (_) + _LT_AC_TAGVAR(always_export_symbols, $1)=yes + # Exported symbols can be pulled into shared objects from archives + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)=' ' + _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=yes + # This is similar to how AIX traditionally builds it's shared libraries. + _LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags ${wl}-bE:$export_symbols ${wl}-bnoentry${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' + fi + fi + ;; + + amigaos*) + _LT_AC_TAGVAR(archive_cmds, $1)='$rm $output_objdir/a2ixlibrary.data~$echo "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes + # see comment about different semantics on the GNU ld section + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + + bsdi4*) + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=-rdynamic + ;; + + cygwin* | mingw* | pw32*) + # When not using gcc, we currently assume that we are using + # Microsoft Visual C++. + # hardcode_libdir_flag_spec is actually meaningless, as there is + # no search path for DLLs. + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=' ' + _LT_AC_TAGVAR(allow_undefined_flag, $1)=unsupported + # Tell ltmain to make .lib files, not .a files. + libext=lib + # Tell ltmain to make .dll files, not .so files. + shrext_cmds=".dll" + # FIXME: Setting linknames here is a bad hack. + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -o $lib $libobjs $compiler_flags `echo "$deplibs" | $SED -e '\''s/ -lc$//'\''` -link -dll~linknames=' + # The linker will automatically build a .lib file if we build a DLL. + _LT_AC_TAGVAR(old_archive_From_new_cmds, $1)='true' + # FIXME: Should let the user specify the lib program. + _LT_AC_TAGVAR(old_archive_cmds, $1)='lib /OUT:$oldlib$oldobjs$old_deplibs' + fix_srcfile_path='`cygpath -w "$srcfile"`' + _LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1)=yes + ;; + + darwin* | rhapsody*) + if test "$GXX" = yes ; then + _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no + case "$host_os" in + rhapsody* | darwin1.[[012]]) + _LT_AC_TAGVAR(allow_undefined_flag, $1)='-undefined suppress' + ;; + *) # Darwin 1.3 on + if test -z ${MACOSX_DEPLOYMENT_TARGET} ; then + _LT_AC_TAGVAR(allow_undefined_flag, $1)='-flat_namespace -undefined suppress' + else + case ${MACOSX_DEPLOYMENT_TARGET} in + 10.[[012]]) + _LT_AC_TAGVAR(allow_undefined_flag, $1)='-flat_namespace -undefined suppress' + ;; + 10.*) + _LT_AC_TAGVAR(allow_undefined_flag, $1)='-undefined dynamic_lookup' + ;; + esac + fi + ;; + esac + lt_int_apple_cc_single_mod=no + output_verbose_link_cmd='echo' + if $CC -dumpspecs 2>&1 | grep 'single_module' >/dev/null ; then + lt_int_apple_cc_single_mod=yes + fi + if test "X$lt_int_apple_cc_single_mod" = Xyes ; then + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -dynamiclib -single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring' + else + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -r ${wl}-bind_at_load -keep_private_externs -nostdlib -o ${lib}-master.o $libobjs~$CC -dynamiclib $allow_undefined_flag -o $lib ${lib}-master.o $deplibs $compiler_flags -install_name $rpath/$soname $verstring' + fi + _LT_AC_TAGVAR(module_cmds, $1)='$CC ${wl}-bind_at_load $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags' + # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin ld's + if test "X$lt_int_apple_cc_single_mod" = Xyes ; then + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -dynamiclib -single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + else + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -r ${wl}-bind_at_load -keep_private_externs -nostdlib -o ${lib}-master.o $libobjs~$CC -dynamiclib $allow_undefined_flag -o $lib ${lib}-master.o $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + fi + _LT_AC_TAGVAR(module_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + _LT_AC_TAGVAR(hardcode_direct, $1)=no + _LT_AC_TAGVAR(hardcode_automatic, $1)=yes + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=unsupported + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='-all_load $convenience' + _LT_AC_TAGVAR(link_all_deplibs, $1)=yes + else + _LT_AC_TAGVAR(ld_shlibs, $1)=no + fi + ;; + + dgux*) + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + freebsd1*) + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + + # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor + # support. Future versions do this automatically, but an explicit c++rt0.o + # does not break anything, and helps significantly (at the cost of a little + # extra space). + freebsd2.2*) + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o' + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + # Unfortunately, older versions of FreeBSD 2 do not have this feature. + freebsd2*) + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + # FreeBSD 3 and greater uses gcc -shared to do shared libraries. + freebsd* | kfreebsd*-gnu) + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -o $lib $libobjs $deplibs $compiler_flags' + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + hpux9*) + if test "$GCC" = yes; then + _LT_AC_TAGVAR(archive_cmds, $1)='$rm $output_objdir/$soname~$CC -shared -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + else + _LT_AC_TAGVAR(archive_cmds, $1)='$rm $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + fi + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' + ;; + + hpux10* | hpux11*) + if test "$GCC" = yes -a "$with_gnu_ld" = no; then + case "$host_cpu" in + hppa*64*|ia64*) + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + *) + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' + ;; + esac + else + case "$host_cpu" in + hppa*64*|ia64*) + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -b +h $soname -o $lib $libobjs $deplibs $linker_flags' + ;; + *) + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' + ;; + esac + fi + if test "$with_gnu_ld" = no; then + case "$host_cpu" in + hppa*64*) + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' + _LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)='+b $libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + _LT_AC_TAGVAR(hardcode_direct, $1)=no + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + ia64*) + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_AC_TAGVAR(hardcode_direct, $1)=no + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes + ;; + *) + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes + ;; + esac + fi + ;; + + irix5* | irix6* | nonstopux*) + if test "$GCC" = yes; then + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + else + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -shared $libobjs $deplibs $linker_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib' + _LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)='-rpath $libdir' + fi + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + _LT_AC_TAGVAR(link_all_deplibs, $1)=yes + ;; + + netbsd* | netbsdelf*-gnu | knetbsd*-gnu) + if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out + else + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF + fi + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + newsos6) + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + openbsd*) + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' + else + case $host_os in + openbsd[[01]].* | openbsd2.[[0-7]] | openbsd2.[[0-7]].*) + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' + ;; + *) + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' + ;; + esac + fi + ;; + + os2*) + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes + _LT_AC_TAGVAR(allow_undefined_flag, $1)=unsupported + _LT_AC_TAGVAR(archive_cmds, $1)='$echo "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$echo "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~$echo DATA >> $output_objdir/$libname.def~$echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~$echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def' + _LT_AC_TAGVAR(old_archive_From_new_cmds, $1)='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def' + ;; + + osf3*) + if test "$GCC" = yes; then + _LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + else + _LT_AC_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib' + fi + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + ;; + + osf4* | osf5*) # as osf3* with the addition of -msym flag + if test "$GCC" = yes; then + _LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' + else + _LT_AC_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -msym -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; echo "-hidden">> $lib.exp~ + $LD -shared${allow_undefined_flag} -input $lib.exp $linker_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${objdir}/so_locations -o $lib~$rm $lib.exp' + + # Both c and cxx compiler support -rpath directly + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' + fi + _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=: + ;; + + sco3.2v5*) + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport' + runpath_var=LD_RUN_PATH + hardcode_runpath_var=yes + ;; + + solaris*) + _LT_AC_TAGVAR(no_undefined_flag, $1)=' -z text' + if test "$GCC" = yes; then + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~ + $CC -shared ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$rm $lib.exp' + else + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~ + $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$rm $lib.exp' + fi + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + case $host_os in + solaris2.[[0-5]] | solaris2.[[0-5]].*) ;; + *) # Supported since Solaris 2.6 (maybe 2.5.1?) + _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract' ;; + esac + _LT_AC_TAGVAR(link_all_deplibs, $1)=yes + ;; + + sunos4*) + if test "x$host_vendor" = xsequent; then + # Use $CC to link under sequent, because it throws in some extra .o + # files that make .init and .fini sections work. + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags' + else + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags' + fi + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + sysv4) + case $host_vendor in + sni) + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_AC_TAGVAR(hardcode_direct, $1)=yes # is this really true??? + ;; + siemens) + ## LD is ld it makes a PLAMLIB + ## CC just makes a GrossModule. + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -o $lib $libobjs $deplibs $linker_flags' + _LT_AC_TAGVAR(reload_cmds, $1)='$CC -r -o $output$reload_objs' + _LT_AC_TAGVAR(hardcode_direct, $1)=no + ;; + motorola) + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_AC_TAGVAR(hardcode_direct, $1)=no #Motorola manual says yes, but my tests say they lie + ;; + esac + runpath_var='LD_RUN_PATH' + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + sysv4.3*) + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='-Bexport' + ;; + + sysv4*MP*) + if test -d /usr/nec; then + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + runpath_var=LD_RUN_PATH + hardcode_runpath_var=yes + _LT_AC_TAGVAR(ld_shlibs, $1)=yes + fi + ;; + + sysv4.2uw2*) + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -o $lib $libobjs $deplibs $linker_flags' + _LT_AC_TAGVAR(hardcode_direct, $1)=yes + _LT_AC_TAGVAR(hardcode_minus_L, $1)=no + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + hardcode_runpath_var=yes + runpath_var=LD_RUN_PATH + ;; + + sysv5OpenUNIX8* | sysv5UnixWare7* | sysv5uw[[78]]* | unixware7*) + _LT_AC_TAGVAR(no_undefined_flag, $1)='${wl}-z ${wl}text' + if test "$GCC" = yes; then + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + else + _LT_AC_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + fi + runpath_var='LD_RUN_PATH' + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + sysv5*) + _LT_AC_TAGVAR(no_undefined_flag, $1)=' -z text' + # $CC -shared without GNU ld will not create a library from C++ + # object files and a static libstdc++, better avoid it by now + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~ + $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$rm $lib.exp' + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)= + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + runpath_var='LD_RUN_PATH' + ;; + + uts4*) + _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + *) + _LT_AC_TAGVAR(ld_shlibs, $1)=no + ;; + esac + fi +]) +AC_MSG_RESULT([$_LT_AC_TAGVAR(ld_shlibs, $1)]) +test "$_LT_AC_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no + +variables_saved_for_relink="PATH $shlibpath_var $runpath_var" +if test "$GCC" = yes; then + variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" +fi + +# +# Do we need to explicitly link libc? +# +case "x$_LT_AC_TAGVAR(archive_cmds_need_lc, $1)" in +x|xyes) + # Assume -lc should be added + _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=yes + + if test "$enable_shared" = yes && test "$GCC" = yes; then + case $_LT_AC_TAGVAR(archive_cmds, $1) in + *'~'*) + # FIXME: we may have to deal with multi-command sequences. + ;; + '$CC '*) + # Test whether the compiler implicitly links with -lc since on some + # systems, -lgcc has to come before -lc. If gcc already passes -lc + # to ld, don't add -lc before -lgcc. + AC_MSG_CHECKING([whether -lc should be explicitly linked in]) + $rm conftest* + printf "$lt_simple_compile_test_code" > conftest.$ac_ext + + if AC_TRY_EVAL(ac_compile) 2>conftest.err; then + soname=conftest + lib=conftest + libobjs=conftest.$ac_objext + deplibs= + wl=$_LT_AC_TAGVAR(lt_prog_compiler_wl, $1) + compiler_flags=-v + linker_flags=-v + verstring= + output_objdir=. + libname=conftest + lt_save_allow_undefined_flag=$_LT_AC_TAGVAR(allow_undefined_flag, $1) + _LT_AC_TAGVAR(allow_undefined_flag, $1)= + if AC_TRY_EVAL(_LT_AC_TAGVAR(archive_cmds, $1) 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1) + then + _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no + else + _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=yes + fi + _LT_AC_TAGVAR(allow_undefined_flag, $1)=$lt_save_allow_undefined_flag + else + cat conftest.err 1>&5 + fi + $rm conftest* + AC_MSG_RESULT([$_LT_AC_TAGVAR(archive_cmds_need_lc, $1)]) + ;; + esac + fi + ;; +esac +])# AC_LIBTOOL_PROG_LD_SHLIBS + + +# _LT_AC_FILE_LTDLL_C +# ------------------- +# Be careful that the start marker always follows a newline. +AC_DEFUN([_LT_AC_FILE_LTDLL_C], [ +# /* ltdll.c starts here */ +# #define WIN32_LEAN_AND_MEAN +# #include +# #undef WIN32_LEAN_AND_MEAN +# #include +# +# #ifndef __CYGWIN__ +# # ifdef __CYGWIN32__ +# # define __CYGWIN__ __CYGWIN32__ +# # endif +# #endif +# +# #ifdef __cplusplus +# extern "C" { +# #endif +# BOOL APIENTRY DllMain (HINSTANCE hInst, DWORD reason, LPVOID reserved); +# #ifdef __cplusplus +# } +# #endif +# +# #ifdef __CYGWIN__ +# #include +# DECLARE_CYGWIN_DLL( DllMain ); +# #endif +# HINSTANCE __hDllInstance_base; +# +# BOOL APIENTRY +# DllMain (HINSTANCE hInst, DWORD reason, LPVOID reserved) +# { +# __hDllInstance_base = hInst; +# return TRUE; +# } +# /* ltdll.c ends here */ +])# _LT_AC_FILE_LTDLL_C + + +# _LT_AC_TAGVAR(VARNAME, [TAGNAME]) +# --------------------------------- +AC_DEFUN([_LT_AC_TAGVAR], [ifelse([$2], [], [$1], [$1_$2])]) + + +# old names +AC_DEFUN([AM_PROG_LIBTOOL], [AC_PROG_LIBTOOL]) +AC_DEFUN([AM_ENABLE_SHARED], [AC_ENABLE_SHARED($@)]) +AC_DEFUN([AM_ENABLE_STATIC], [AC_ENABLE_STATIC($@)]) +AC_DEFUN([AM_DISABLE_SHARED], [AC_DISABLE_SHARED($@)]) +AC_DEFUN([AM_DISABLE_STATIC], [AC_DISABLE_STATIC($@)]) +AC_DEFUN([AM_PROG_LD], [AC_PROG_LD]) +AC_DEFUN([AM_PROG_NM], [AC_PROG_NM]) + +# This is just to silence aclocal about the macro not being used +ifelse([AC_DISABLE_FAST_INSTALL]) + +AC_DEFUN([LT_AC_PROG_GCJ], +[AC_CHECK_TOOL(GCJ, gcj, no) + test "x${GCJFLAGS+set}" = xset || GCJFLAGS="-g -O2" + AC_SUBST(GCJFLAGS) +]) + +AC_DEFUN([LT_AC_PROG_RC], +[AC_CHECK_TOOL(RC, windres, no) +]) + +# NOTE: This macro has been submitted for inclusion into # +# GNU Autoconf as AC_PROG_SED. When it is available in # +# a released version of Autoconf we should remove this # +# macro and use it instead. # +# LT_AC_PROG_SED +# -------------- +# Check for a fully-functional sed program, that truncates +# as few characters as possible. Prefer GNU sed if found. +AC_DEFUN([LT_AC_PROG_SED], +[AC_MSG_CHECKING([for a sed that does not truncate output]) +AC_CACHE_VAL(lt_cv_path_SED, +[# Loop through the user's path and test for sed and gsed. +# Then use that list of sed's as ones to test for truncation. +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for lt_ac_prog in sed gsed; do + for ac_exec_ext in '' $ac_executable_extensions; do + if $as_executable_p "$as_dir/$lt_ac_prog$ac_exec_ext"; then + lt_ac_sed_list="$lt_ac_sed_list $as_dir/$lt_ac_prog$ac_exec_ext" + fi + done + done +done +lt_ac_max=0 +lt_ac_count=0 +# Add /usr/xpg4/bin/sed as it is typically found on Solaris +# along with /bin/sed that truncates output. +for lt_ac_sed in $lt_ac_sed_list /usr/xpg4/bin/sed; do + test ! -f $lt_ac_sed && break + cat /dev/null > conftest.in + lt_ac_count=0 + echo $ECHO_N "0123456789$ECHO_C" >conftest.in + # Check for GNU sed and select it if it is found. + if "$lt_ac_sed" --version 2>&1 < /dev/null | grep 'GNU' > /dev/null; then + lt_cv_path_SED=$lt_ac_sed + break + fi + while true; do + cat conftest.in conftest.in >conftest.tmp + mv conftest.tmp conftest.in + cp conftest.in conftest.nl + echo >>conftest.nl + $lt_ac_sed -e 's/a$//' < conftest.nl >conftest.out || break + cmp -s conftest.out conftest.nl || break + # 10000 chars as input seems more than enough + test $lt_ac_count -gt 10 && break + lt_ac_count=`expr $lt_ac_count + 1` + if test $lt_ac_count -gt $lt_ac_max; then + lt_ac_max=$lt_ac_count + lt_cv_path_SED=$lt_ac_sed + fi + done +done +SED=$lt_cv_path_SED +]) +AC_MSG_RESULT([$SED]) +]) + +# -*- Autoconf -*- +# Copyright (C) 2002, 2003 Free Software Foundation, Inc. +# Generated from amversion.in; do not edit by hand. + +# 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, or (at your option) +# any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + +# AM_AUTOMAKE_VERSION(VERSION) +# ---------------------------- +# Automake X.Y traces this macro to ensure aclocal.m4 has been +# generated from the m4 files accompanying Automake X.Y. +AC_DEFUN([AM_AUTOMAKE_VERSION], [am__api_version="1.8"]) + +# AM_SET_CURRENT_AUTOMAKE_VERSION +# ------------------------------- +# Call AM_AUTOMAKE_VERSION so it can be traced. +# This function is AC_REQUIREd by AC_INIT_AUTOMAKE. +AC_DEFUN([AM_SET_CURRENT_AUTOMAKE_VERSION], + [AM_AUTOMAKE_VERSION([1.8.5])]) + +# AM_AUX_DIR_EXPAND + +# Copyright (C) 2001, 2003 Free Software Foundation, Inc. + +# 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, or (at your option) +# any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA +# 02111-1307, USA. + +# For projects using AC_CONFIG_AUX_DIR([foo]), Autoconf sets +# $ac_aux_dir to `$srcdir/foo'. In other projects, it is set to +# `$srcdir', `$srcdir/..', or `$srcdir/../..'. +# +# Of course, Automake must honor this variable whenever it calls a +# tool from the auxiliary directory. The problem is that $srcdir (and +# therefore $ac_aux_dir as well) can be either absolute or relative, +# depending on how configure is run. This is pretty annoying, since +# it makes $ac_aux_dir quite unusable in subdirectories: in the top +# source directory, any form will work fine, but in subdirectories a +# relative path needs to be adjusted first. +# +# $ac_aux_dir/missing +# fails when called from a subdirectory if $ac_aux_dir is relative +# $top_srcdir/$ac_aux_dir/missing +# fails if $ac_aux_dir is absolute, +# fails when called from a subdirectory in a VPATH build with +# a relative $ac_aux_dir +# +# The reason of the latter failure is that $top_srcdir and $ac_aux_dir +# are both prefixed by $srcdir. In an in-source build this is usually +# harmless because $srcdir is `.', but things will broke when you +# start a VPATH build or use an absolute $srcdir. +# +# So we could use something similar to $top_srcdir/$ac_aux_dir/missing, +# iff we strip the leading $srcdir from $ac_aux_dir. That would be: +# am_aux_dir='\$(top_srcdir)/'`expr "$ac_aux_dir" : "$srcdir//*\(.*\)"` +# and then we would define $MISSING as +# MISSING="\${SHELL} $am_aux_dir/missing" +# This will work as long as MISSING is not called from configure, because +# unfortunately $(top_srcdir) has no meaning in configure. +# However there are other variables, like CC, which are often used in +# configure, and could therefore not use this "fixed" $ac_aux_dir. +# +# Another solution, used here, is to always expand $ac_aux_dir to an +# absolute PATH. The drawback is that using absolute paths prevent a +# configured tree to be moved without reconfiguration. + +AC_DEFUN([AM_AUX_DIR_EXPAND], +[dnl Rely on autoconf to set up CDPATH properly. +AC_PREREQ([2.50])dnl +# expand $ac_aux_dir to an absolute path +am_aux_dir=`cd $ac_aux_dir && pwd` +]) + +# AM_CONDITIONAL -*- Autoconf -*- + +# Copyright (C) 1997, 2000, 2001, 2003 Free Software Foundation, Inc. + +# 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, or (at your option) +# any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA +# 02111-1307, USA. + +# serial 6 + +# AM_CONDITIONAL(NAME, SHELL-CONDITION) +# ------------------------------------- +# Define a conditional. +AC_DEFUN([AM_CONDITIONAL], +[AC_PREREQ(2.52)dnl + ifelse([$1], [TRUE], [AC_FATAL([$0: invalid condition: $1])], + [$1], [FALSE], [AC_FATAL([$0: invalid condition: $1])])dnl +AC_SUBST([$1_TRUE]) +AC_SUBST([$1_FALSE]) +if $2; then + $1_TRUE= + $1_FALSE='#' +else + $1_TRUE='#' + $1_FALSE= +fi +AC_CONFIG_COMMANDS_PRE( +[if test -z "${$1_TRUE}" && test -z "${$1_FALSE}"; then + AC_MSG_ERROR([conditional "$1" was never defined. +Usually this means the macro was only invoked conditionally.]) +fi])]) + +# serial 7 -*- Autoconf -*- + +# Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004 +# Free Software Foundation, Inc. + +# 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, or (at your option) +# any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA +# 02111-1307, USA. + + +# There are a few dirty hacks below to avoid letting `AC_PROG_CC' be +# written in clear, in which case automake, when reading aclocal.m4, +# will think it sees a *use*, and therefore will trigger all it's +# C support machinery. Also note that it means that autoscan, seeing +# CC etc. in the Makefile, will ask for an AC_PROG_CC use... + + + +# _AM_DEPENDENCIES(NAME) +# ---------------------- +# See how the compiler implements dependency checking. +# NAME is "CC", "CXX", "GCJ", or "OBJC". +# We try a few techniques and use that to set a single cache variable. +# +# We don't AC_REQUIRE the corresponding AC_PROG_CC since the latter was +# modified to invoke _AM_DEPENDENCIES(CC); we would have a circular +# dependency, and given that the user is not expected to run this macro, +# just rely on AC_PROG_CC. +AC_DEFUN([_AM_DEPENDENCIES], +[AC_REQUIRE([AM_SET_DEPDIR])dnl +AC_REQUIRE([AM_OUTPUT_DEPENDENCY_COMMANDS])dnl +AC_REQUIRE([AM_MAKE_INCLUDE])dnl +AC_REQUIRE([AM_DEP_TRACK])dnl + +ifelse([$1], CC, [depcc="$CC" am_compiler_list=], + [$1], CXX, [depcc="$CXX" am_compiler_list=], + [$1], OBJC, [depcc="$OBJC" am_compiler_list='gcc3 gcc'], + [$1], GCJ, [depcc="$GCJ" am_compiler_list='gcc3 gcc'], + [depcc="$$1" am_compiler_list=]) + +AC_CACHE_CHECK([dependency style of $depcc], + [am_cv_$1_dependencies_compiler_type], +[if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then + # We make a subdir and do the tests there. Otherwise we can end up + # making bogus files that we don't know about and never remove. For + # instance it was reported that on HP-UX the gcc test will end up + # making a dummy file named `D' -- because `-MD' means `put the output + # in D'. + mkdir conftest.dir + # Copy depcomp to subdir because otherwise we won't find it if we're + # using a relative directory. + cp "$am_depcomp" conftest.dir + cd conftest.dir + # We will build objects and dependencies in a subdirectory because + # it helps to detect inapplicable dependency modes. For instance + # both Tru64's cc and ICC support -MD to output dependencies as a + # side effect of compilation, but ICC will put the dependencies in + # the current directory while Tru64 will put them in the object + # directory. + mkdir sub + + am_cv_$1_dependencies_compiler_type=none + if test "$am_compiler_list" = ""; then + am_compiler_list=`sed -n ['s/^#*\([a-zA-Z0-9]*\))$/\1/p'] < ./depcomp` + fi + for depmode in $am_compiler_list; do + # Setup a source with many dependencies, because some compilers + # like to wrap large dependency lists on column 80 (with \), and + # we should not choose a depcomp mode which is confused by this. + # + # We need to recreate these files for each test, as the compiler may + # overwrite some of them when testing with obscure command lines. + # This happens at least with the AIX C compiler. + : > sub/conftest.c + for i in 1 2 3 4 5 6; do + echo '#include "conftst'$i'.h"' >> sub/conftest.c + # Using `: > sub/conftst$i.h' creates only sub/conftst1.h with + # Solaris 8's {/usr,}/bin/sh. + touch sub/conftst$i.h + done + echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf + + case $depmode in + nosideeffect) + # after this tag, mechanisms are not by side-effect, so they'll + # only be used when explicitly requested + if test "x$enable_dependency_tracking" = xyes; then + continue + else + break + fi + ;; + none) break ;; + esac + # We check with `-c' and `-o' for the sake of the "dashmstdout" + # mode. It turns out that the SunPro C++ compiler does not properly + # handle `-M -o', and we need to detect this. + if depmode=$depmode \ + source=sub/conftest.c object=sub/conftest.${OBJEXT-o} \ + depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ + $SHELL ./depcomp $depcc -c -o sub/conftest.${OBJEXT-o} sub/conftest.c \ + >/dev/null 2>conftest.err && + grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && + grep sub/conftest.${OBJEXT-o} sub/conftest.Po > /dev/null 2>&1 && + ${MAKE-make} -s -f confmf > /dev/null 2>&1; then + # icc doesn't choke on unknown options, it will just issue warnings + # or remarks (even with -Werror). So we grep stderr for any message + # that says an option was ignored or not supported. + # When given -MP, icc 7.0 and 7.1 complain thusly: + # icc: Command line warning: ignoring option '-M'; no argument required + # The diagnosis changed in icc 8.0: + # icc: Command line remark: option '-MP' not supported + if (grep 'ignoring option' conftest.err || + grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else + am_cv_$1_dependencies_compiler_type=$depmode + break + fi + fi + done + + cd .. + rm -rf conftest.dir +else + am_cv_$1_dependencies_compiler_type=none +fi +]) +AC_SUBST([$1DEPMODE], [depmode=$am_cv_$1_dependencies_compiler_type]) +AM_CONDITIONAL([am__fastdep$1], [ + test "x$enable_dependency_tracking" != xno \ + && test "$am_cv_$1_dependencies_compiler_type" = gcc3]) +]) + + +# AM_SET_DEPDIR +# ------------- +# Choose a directory name for dependency files. +# This macro is AC_REQUIREd in _AM_DEPENDENCIES +AC_DEFUN([AM_SET_DEPDIR], +[AC_REQUIRE([AM_SET_LEADING_DOT])dnl +AC_SUBST([DEPDIR], ["${am__leading_dot}deps"])dnl +]) + + +# AM_DEP_TRACK +# ------------ +AC_DEFUN([AM_DEP_TRACK], +[AC_ARG_ENABLE(dependency-tracking, +[ --disable-dependency-tracking speeds up one-time build + --enable-dependency-tracking do not reject slow dependency extractors]) +if test "x$enable_dependency_tracking" != xno; then + am_depcomp="$ac_aux_dir/depcomp" + AMDEPBACKSLASH='\' +fi +AM_CONDITIONAL([AMDEP], [test "x$enable_dependency_tracking" != xno]) +AC_SUBST([AMDEPBACKSLASH]) +]) + +# Generate code to set up dependency tracking. -*- Autoconf -*- + +# Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004 Free Software Foundation, Inc. + +# 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, or (at your option) +# any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA +# 02111-1307, USA. + +#serial 2 + +# _AM_OUTPUT_DEPENDENCY_COMMANDS +# ------------------------------ +AC_DEFUN([_AM_OUTPUT_DEPENDENCY_COMMANDS], +[for mf in $CONFIG_FILES; do + # Strip MF so we end up with the name of the file. + mf=`echo "$mf" | sed -e 's/:.*$//'` + # Check whether this is an Automake generated Makefile or not. + # We used to match only the files named `Makefile.in', but + # some people rename them; so instead we look at the file content. + # Grep'ing the first line is not enough: some people post-process + # each Makefile.in and add a new line on top of each file to say so. + # So let's grep whole file. + if grep '^#.*generated by automake' $mf > /dev/null 2>&1; then + dirpart=`AS_DIRNAME("$mf")` + else + continue + fi + grep '^DEP_FILES *= *[[^ @%:@]]' < "$mf" > /dev/null || continue + # Extract the definition of DEP_FILES from the Makefile without + # running `make'. + DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"` + test -z "$DEPDIR" && continue + # When using ansi2knr, U may be empty or an underscore; expand it + U=`sed -n 's/^U = //p' < "$mf"` + test -d "$dirpart/$DEPDIR" || mkdir "$dirpart/$DEPDIR" + # We invoke sed twice because it is the simplest approach to + # changing $(DEPDIR) to its actual value in the expansion. + for file in `sed -n ' + /^DEP_FILES = .*\\\\$/ { + s/^DEP_FILES = // + :loop + s/\\\\$// + p + n + /\\\\$/ b loop + p + } + /^DEP_FILES = / s/^DEP_FILES = //p' < "$mf" | \ + sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g' -e 's/\$U/'"$U"'/g'`; do + # Make sure the directory exists. + test -f "$dirpart/$file" && continue + fdir=`AS_DIRNAME(["$file"])` + AS_MKDIR_P([$dirpart/$fdir]) + # echo "creating $dirpart/$file" + echo '# dummy' > "$dirpart/$file" + done +done +])# _AM_OUTPUT_DEPENDENCY_COMMANDS + + +# AM_OUTPUT_DEPENDENCY_COMMANDS +# ----------------------------- +# This macro should only be invoked once -- use via AC_REQUIRE. +# +# This code is only required when automatic dependency tracking +# is enabled. FIXME. This creates each `.P' file that we will +# need in order to bootstrap the dependency handling code. +AC_DEFUN([AM_OUTPUT_DEPENDENCY_COMMANDS], +[AC_CONFIG_COMMANDS([depfiles], + [test x"$AMDEP_TRUE" != x"" || _AM_OUTPUT_DEPENDENCY_COMMANDS], + [AMDEP_TRUE="$AMDEP_TRUE" ac_aux_dir="$ac_aux_dir"]) +]) + +# Do all the work for Automake. -*- Autoconf -*- + +# This macro actually does too much some checks are only needed if +# your package does certain things. But this isn't really a big deal. + +# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003 +# Free Software Foundation, Inc. + +# 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, or (at your option) +# any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA +# 02111-1307, USA. + +# serial 11 + +# AM_INIT_AUTOMAKE(PACKAGE, VERSION, [NO-DEFINE]) +# AM_INIT_AUTOMAKE([OPTIONS]) +# ----------------------------------------------- +# The call with PACKAGE and VERSION arguments is the old style +# call (pre autoconf-2.50), which is being phased out. PACKAGE +# and VERSION should now be passed to AC_INIT and removed from +# the call to AM_INIT_AUTOMAKE. +# We support both call styles for the transition. After +# the next Automake release, Autoconf can make the AC_INIT +# arguments mandatory, and then we can depend on a new Autoconf +# release and drop the old call support. +AC_DEFUN([AM_INIT_AUTOMAKE], +[AC_PREREQ([2.58])dnl +dnl Autoconf wants to disallow AM_ names. We explicitly allow +dnl the ones we care about. +m4_pattern_allow([^AM_[A-Z]+FLAGS$])dnl +AC_REQUIRE([AM_SET_CURRENT_AUTOMAKE_VERSION])dnl +AC_REQUIRE([AC_PROG_INSTALL])dnl +# test to see if srcdir already configured +if test "`cd $srcdir && pwd`" != "`pwd`" && + test -f $srcdir/config.status; then + AC_MSG_ERROR([source directory already configured; run "make distclean" there first]) +fi + +# test whether we have cygpath +if test -z "$CYGPATH_W"; then + if (cygpath --version) >/dev/null 2>/dev/null; then + CYGPATH_W='cygpath -w' + else + CYGPATH_W=echo + fi +fi +AC_SUBST([CYGPATH_W]) + +# Define the identity of the package. +dnl Distinguish between old-style and new-style calls. +m4_ifval([$2], +[m4_ifval([$3], [_AM_SET_OPTION([no-define])])dnl + AC_SUBST([PACKAGE], [$1])dnl + AC_SUBST([VERSION], [$2])], +[_AM_SET_OPTIONS([$1])dnl + AC_SUBST([PACKAGE], ['AC_PACKAGE_TARNAME'])dnl + AC_SUBST([VERSION], ['AC_PACKAGE_VERSION'])])dnl + +_AM_IF_OPTION([no-define],, +[AC_DEFINE_UNQUOTED(PACKAGE, "$PACKAGE", [Name of package]) + AC_DEFINE_UNQUOTED(VERSION, "$VERSION", [Version number of package])])dnl + +# Some tools Automake needs. +AC_REQUIRE([AM_SANITY_CHECK])dnl +AC_REQUIRE([AC_ARG_PROGRAM])dnl +AM_MISSING_PROG(ACLOCAL, aclocal-${am__api_version}) +AM_MISSING_PROG(AUTOCONF, autoconf) +AM_MISSING_PROG(AUTOMAKE, automake-${am__api_version}) +AM_MISSING_PROG(AUTOHEADER, autoheader) +AM_MISSING_PROG(MAKEINFO, makeinfo) +AM_MISSING_PROG(AMTAR, tar) +AM_PROG_INSTALL_SH +AM_PROG_INSTALL_STRIP +AC_REQUIRE([AM_PROG_MKDIR_P])dnl +# We need awk for the "check" target. The system "awk" is bad on +# some platforms. +AC_REQUIRE([AC_PROG_AWK])dnl +AC_REQUIRE([AC_PROG_MAKE_SET])dnl +AC_REQUIRE([AM_SET_LEADING_DOT])dnl + +_AM_IF_OPTION([no-dependencies],, +[AC_PROVIDE_IFELSE([AC_PROG_CC], + [_AM_DEPENDENCIES(CC)], + [define([AC_PROG_CC], + defn([AC_PROG_CC])[_AM_DEPENDENCIES(CC)])])dnl +AC_PROVIDE_IFELSE([AC_PROG_CXX], + [_AM_DEPENDENCIES(CXX)], + [define([AC_PROG_CXX], + defn([AC_PROG_CXX])[_AM_DEPENDENCIES(CXX)])])dnl +]) +]) + + +# When config.status generates a header, we must update the stamp-h file. +# This file resides in the same directory as the config header +# that is generated. The stamp files are numbered to have different names. + +# Autoconf calls _AC_AM_CONFIG_HEADER_HOOK (when defined) in the +# loop where config.status creates the headers, so we can generate +# our stamp files there. +AC_DEFUN([_AC_AM_CONFIG_HEADER_HOOK], +[# Compute $1's index in $config_headers. +_am_stamp_count=1 +for _am_header in $config_headers :; do + case $_am_header in + $1 | $1:* ) + break ;; + * ) + _am_stamp_count=`expr $_am_stamp_count + 1` ;; + esac +done +echo "timestamp for $1" >`AS_DIRNAME([$1])`/stamp-h[]$_am_stamp_count]) + +# AM_PROG_INSTALL_SH +# ------------------ +# Define $install_sh. + +# Copyright (C) 2001, 2003 Free Software Foundation, Inc. + +# 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, or (at your option) +# any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA +# 02111-1307, USA. + +AC_DEFUN([AM_PROG_INSTALL_SH], +[AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl +install_sh=${install_sh-"$am_aux_dir/install-sh"} +AC_SUBST(install_sh)]) + +# -*- Autoconf -*- +# Copyright (C) 2003 Free Software Foundation, Inc. + +# 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, or (at your option) +# any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA +# 02111-1307, USA. + +# serial 1 + +# Check whether the underlying file-system supports filenames +# with a leading dot. For instance MS-DOS doesn't. +AC_DEFUN([AM_SET_LEADING_DOT], +[rm -rf .tst 2>/dev/null +mkdir .tst 2>/dev/null +if test -d .tst; then + am__leading_dot=. +else + am__leading_dot=_ +fi +rmdir .tst 2>/dev/null +AC_SUBST([am__leading_dot])]) + +# Add --enable-maintainer-mode option to configure. +# From Jim Meyering + +# Copyright (C) 1996, 1998, 2000, 2001, 2002, 2003, 2004 +# Free Software Foundation, Inc. + +# 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, or (at your option) +# any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA +# 02111-1307, USA. + +# serial 3 + +AC_DEFUN([AM_MAINTAINER_MODE], +[AC_MSG_CHECKING([whether to enable maintainer-specific portions of Makefiles]) + dnl maintainer-mode is disabled by default + AC_ARG_ENABLE(maintainer-mode, +[ --enable-maintainer-mode enable make rules and dependencies not useful + (and sometimes confusing) to the casual installer], + USE_MAINTAINER_MODE=$enableval, + USE_MAINTAINER_MODE=no) + AC_MSG_RESULT([$USE_MAINTAINER_MODE]) + AM_CONDITIONAL(MAINTAINER_MODE, [test $USE_MAINTAINER_MODE = yes]) + MAINT=$MAINTAINER_MODE_TRUE + AC_SUBST(MAINT)dnl +] +) + +AU_DEFUN([jm_MAINTAINER_MODE], [AM_MAINTAINER_MODE]) + +# Check to see how 'make' treats includes. -*- Autoconf -*- + +# Copyright (C) 2001, 2002, 2003 Free Software Foundation, Inc. + +# 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, or (at your option) +# any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA +# 02111-1307, USA. + +# serial 2 + +# AM_MAKE_INCLUDE() +# ----------------- +# Check to see how make treats includes. +AC_DEFUN([AM_MAKE_INCLUDE], +[am_make=${MAKE-make} +cat > confinc << 'END' +am__doit: + @echo done +.PHONY: am__doit +END +# If we don't find an include directive, just comment out the code. +AC_MSG_CHECKING([for style of include used by $am_make]) +am__include="#" +am__quote= +_am_result=none +# First try GNU make style include. +echo "include confinc" > confmf +# We grep out `Entering directory' and `Leaving directory' +# messages which can occur if `w' ends up in MAKEFLAGS. +# In particular we don't look at `^make:' because GNU make might +# be invoked under some other name (usually "gmake"), in which +# case it prints its new name instead of `make'. +if test "`$am_make -s -f confmf 2> /dev/null | grep -v 'ing directory'`" = "done"; then + am__include=include + am__quote= + _am_result=GNU +fi +# Now try BSD make style include. +if test "$am__include" = "#"; then + echo '.include "confinc"' > confmf + if test "`$am_make -s -f confmf 2> /dev/null`" = "done"; then + am__include=.include + am__quote="\"" + _am_result=BSD + fi +fi +AC_SUBST([am__include]) +AC_SUBST([am__quote]) +AC_MSG_RESULT([$_am_result]) +rm -f confinc confmf +]) + +# -*- Autoconf -*- + + +# Copyright (C) 1997, 1999, 2000, 2001, 2003 Free Software Foundation, Inc. + +# 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, or (at your option) +# any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA +# 02111-1307, USA. + +# serial 3 + +# AM_MISSING_PROG(NAME, PROGRAM) +# ------------------------------ +AC_DEFUN([AM_MISSING_PROG], +[AC_REQUIRE([AM_MISSING_HAS_RUN]) +$1=${$1-"${am_missing_run}$2"} +AC_SUBST($1)]) + + +# AM_MISSING_HAS_RUN +# ------------------ +# Define MISSING if not defined so far and test if it supports --run. +# If it does, set am_missing_run to use it, otherwise, to nothing. +AC_DEFUN([AM_MISSING_HAS_RUN], +[AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl +test x"${MISSING+set}" = xset || MISSING="\${SHELL} $am_aux_dir/missing" +# Use eval to expand $SHELL +if eval "$MISSING --run true"; then + am_missing_run="$MISSING --run " +else + am_missing_run= + AC_MSG_WARN([`missing' script is too old or missing]) +fi +]) + +# AM_PROG_MKDIR_P +# --------------- +# Check whether `mkdir -p' is supported, fallback to mkinstalldirs otherwise. + +# Copyright (C) 2003, 2004 Free Software Foundation, Inc. + +# 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, or (at your option) +# any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA +# 02111-1307, USA. + +# Automake 1.8 used `mkdir -m 0755 -p --' to ensure that directories +# created by `make install' are always world readable, even if the +# installer happens to have an overly restrictive umask (e.g. 077). +# This was a mistake. There are at least two reasons why we must not +# use `-m 0755': +# - it causes special bits like SGID to be ignored, +# - it may be too restrictive (some setups expect 775 directories). +# +# Do not use -m 0755 and let people choose whatever they expect by +# setting umask. +# +# We cannot accept any implementation of `mkdir' that recognizes `-p'. +# Some implementations (such as Solaris 8's) are not thread-safe: if a +# parallel make tries to run `mkdir -p a/b' and `mkdir -p a/c' +# concurrently, both version can detect that a/ is missing, but only +# one can create it and the other will error out. Consequently we +# restrict ourselves to GNU make (using the --version option ensures +# this.) +AC_DEFUN([AM_PROG_MKDIR_P], +[if mkdir -p --version . >/dev/null 2>&1 && test ! -d ./--version; then + # Keeping the `.' argument allows $(mkdir_p) to be used without + # argument. Indeed, we sometimes output rules like + # $(mkdir_p) $(somedir) + # where $(somedir) is conditionally defined. + # (`test -n '$(somedir)' && $(mkdir_p) $(somedir)' is a more + # expensive solution, as it forces Make to start a sub-shell.) + mkdir_p='mkdir -p -- .' +else + # On NextStep and OpenStep, the `mkdir' command does not + # recognize any option. It will interpret all options as + # directories to create, and then abort because `.' already + # exists. + for d in ./-p ./--version; + do + test -d $d && rmdir $d + done + # $(mkinstalldirs) is defined by Automake if mkinstalldirs exists. + if test -f "$ac_aux_dir/mkinstalldirs"; then + mkdir_p='$(mkinstalldirs)' + else + mkdir_p='$(install_sh) -d' + fi +fi +AC_SUBST([mkdir_p])]) + +# Helper functions for option handling. -*- Autoconf -*- + +# Copyright (C) 2001, 2002, 2003 Free Software Foundation, Inc. + +# 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, or (at your option) +# any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA +# 02111-1307, USA. + +# serial 2 + +# _AM_MANGLE_OPTION(NAME) +# ----------------------- +AC_DEFUN([_AM_MANGLE_OPTION], +[[_AM_OPTION_]m4_bpatsubst($1, [[^a-zA-Z0-9_]], [_])]) + +# _AM_SET_OPTION(NAME) +# ------------------------------ +# Set option NAME. Presently that only means defining a flag for this option. +AC_DEFUN([_AM_SET_OPTION], +[m4_define(_AM_MANGLE_OPTION([$1]), 1)]) + +# _AM_SET_OPTIONS(OPTIONS) +# ---------------------------------- +# OPTIONS is a space-separated list of Automake options. +AC_DEFUN([_AM_SET_OPTIONS], +[AC_FOREACH([_AM_Option], [$1], [_AM_SET_OPTION(_AM_Option)])]) + +# _AM_IF_OPTION(OPTION, IF-SET, [IF-NOT-SET]) +# ------------------------------------------- +# Execute IF-SET if OPTION is set, IF-NOT-SET otherwise. +AC_DEFUN([_AM_IF_OPTION], +[m4_ifset(_AM_MANGLE_OPTION([$1]), [$2], [$3])]) + +# +# Check to make sure that the build environment is sane. +# + +# Copyright (C) 1996, 1997, 2000, 2001, 2003 Free Software Foundation, Inc. + +# 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, or (at your option) +# any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA +# 02111-1307, USA. + +# serial 3 + +# AM_SANITY_CHECK +# --------------- +AC_DEFUN([AM_SANITY_CHECK], +[AC_MSG_CHECKING([whether build environment is sane]) +# Just in case +sleep 1 +echo timestamp > conftest.file +# Do `set' in a subshell so we don't clobber the current shell's +# arguments. Must try -L first in case configure is actually a +# symlink; some systems play weird games with the mod time of symlinks +# (eg FreeBSD returns the mod time of the symlink's containing +# directory). +if ( + set X `ls -Lt $srcdir/configure conftest.file 2> /dev/null` + if test "$[*]" = "X"; then + # -L didn't work. + set X `ls -t $srcdir/configure conftest.file` + fi + rm -f conftest.file + if test "$[*]" != "X $srcdir/configure conftest.file" \ + && test "$[*]" != "X conftest.file $srcdir/configure"; then + + # If neither matched, then we have a broken ls. This can happen + # if, for instance, CONFIG_SHELL is bash and it inherits a + # broken ls alias from the environment. This has actually + # happened. Such a system could not be considered "sane". + AC_MSG_ERROR([ls -t appears to fail. Make sure there is not a broken +alias in your environment]) + fi + + test "$[2]" = conftest.file + ) +then + # Ok. + : +else + AC_MSG_ERROR([newly created file is older than distributed files! +Check your system clock]) +fi +AC_MSG_RESULT(yes)]) + +# AM_PROG_INSTALL_STRIP + +# Copyright (C) 2001, 2003 Free Software Foundation, Inc. + +# 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, or (at your option) +# any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA +# 02111-1307, USA. + +# One issue with vendor `install' (even GNU) is that you can't +# specify the program used to strip binaries. This is especially +# annoying in cross-compiling environments, where the build's strip +# is unlikely to handle the host's binaries. +# Fortunately install-sh will honor a STRIPPROG variable, so we +# always use install-sh in `make install-strip', and initialize +# STRIPPROG with the value of the STRIP variable (set by the user). +AC_DEFUN([AM_PROG_INSTALL_STRIP], +[AC_REQUIRE([AM_PROG_INSTALL_SH])dnl +# Installed binaries are usually stripped using `strip' when the user +# run `make install-strip'. However `strip' might not be the right +# tool to use in cross-compilation environments, therefore Automake +# will honor the `STRIP' environment variable to overrule this program. +dnl Don't test for $cross_compiling = yes, because it might be `maybe'. +if test "$cross_compiling" != no; then + AC_CHECK_TOOL([STRIP], [strip], :) +fi +INSTALL_STRIP_PROGRAM="\${SHELL} \$(install_sh) -c -s" +AC_SUBST([INSTALL_STRIP_PROGRAM])]) + +m4_include([acinclude.m4]) diff --git a/Code/BF2/External/speex-1.0.5/config.guess b/Code/BF2/External/speex-1.0.5/config.guess new file mode 100755 index 000000000..51fab4770 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/config.guess @@ -0,0 +1,1459 @@ +#! /bin/sh +# Attempt to guess a canonical system name. +# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, +# 2000, 2001, 2002, 2003 Free Software Foundation, Inc. + +timestamp='2004-03-12' + +# This file is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +# +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + +# Originally written by Per Bothner . +# Please send patches to . Submit a context +# diff and a properly formatted ChangeLog entry. +# +# This script attempts to guess a canonical system name similar to +# config.sub. If it succeeds, it prints the system name on stdout, and +# exits with 0. Otherwise, it exits with 1. +# +# The plan is that this can be called by configure scripts if you +# don't specify an explicit build system type. + +me=`echo "$0" | sed -e 's,.*/,,'` + +usage="\ +Usage: $0 [OPTION] + +Output the configuration name of the system \`$me' is run on. + +Operation modes: + -h, --help print this help, then exit + -t, --time-stamp print date of last modification, then exit + -v, --version print version number, then exit + +Report bugs and patches to ." + +version="\ +GNU config.guess ($timestamp) + +Originally written by Per Bothner. +Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001 +Free Software Foundation, Inc. + +This is free software; see the source for copying conditions. There is NO +warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." + +help=" +Try \`$me --help' for more information." + +# Parse command line +while test $# -gt 0 ; do + case $1 in + --time-stamp | --time* | -t ) + echo "$timestamp" ; exit 0 ;; + --version | -v ) + echo "$version" ; exit 0 ;; + --help | --h* | -h ) + echo "$usage"; exit 0 ;; + -- ) # Stop option processing + shift; break ;; + - ) # Use stdin as input. + break ;; + -* ) + echo "$me: invalid option $1$help" >&2 + exit 1 ;; + * ) + break ;; + esac +done + +if test $# != 0; then + echo "$me: too many arguments$help" >&2 + exit 1 +fi + +trap 'exit 1' 1 2 15 + +# CC_FOR_BUILD -- compiler used by this script. Note that the use of a +# compiler to aid in system detection is discouraged as it requires +# temporary files to be created and, as you can see below, it is a +# headache to deal with in a portable fashion. + +# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still +# use `HOST_CC' if defined, but it is deprecated. + +# Portable tmp directory creation inspired by the Autoconf team. + +set_cc_for_build=' +trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ; +trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ; +: ${TMPDIR=/tmp} ; + { tmp=`(umask 077 && mktemp -d -q "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } || + { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } || + { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } || + { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ; +dummy=$tmp/dummy ; +tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ; +case $CC_FOR_BUILD,$HOST_CC,$CC in + ,,) echo "int x;" > $dummy.c ; + for c in cc gcc c89 c99 ; do + if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then + CC_FOR_BUILD="$c"; break ; + fi ; + done ; + if test x"$CC_FOR_BUILD" = x ; then + CC_FOR_BUILD=no_compiler_found ; + fi + ;; + ,,*) CC_FOR_BUILD=$CC ;; + ,*,*) CC_FOR_BUILD=$HOST_CC ;; +esac ;' + +# This is needed to find uname on a Pyramid OSx when run in the BSD universe. +# (ghazi@noc.rutgers.edu 1994-08-24) +if (test -f /.attbin/uname) >/dev/null 2>&1 ; then + PATH=$PATH:/.attbin ; export PATH +fi + +UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown +UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown +UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown +UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown + +# Note: order is significant - the case branches are not exclusive. + +case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in + *:NetBSD:*:*) + # NetBSD (nbsd) targets should (where applicable) match one or + # more of the tupples: *-*-netbsdelf*, *-*-netbsdaout*, + # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently + # switched to ELF, *-*-netbsd* would select the old + # object file format. This provides both forward + # compatibility and a consistent mechanism for selecting the + # object file format. + # + # Note: NetBSD doesn't particularly care about the vendor + # portion of the name. We always set it to "unknown". + sysctl="sysctl -n hw.machine_arch" + UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \ + /usr/sbin/$sysctl 2>/dev/null || echo unknown)` + case "${UNAME_MACHINE_ARCH}" in + armeb) machine=armeb-unknown ;; + arm*) machine=arm-unknown ;; + sh3el) machine=shl-unknown ;; + sh3eb) machine=sh-unknown ;; + *) machine=${UNAME_MACHINE_ARCH}-unknown ;; + esac + # The Operating System including object format, if it has switched + # to ELF recently, or will in the future. + case "${UNAME_MACHINE_ARCH}" in + arm*|i386|m68k|ns32k|sh3*|sparc|vax) + eval $set_cc_for_build + if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \ + | grep __ELF__ >/dev/null + then + # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout). + # Return netbsd for either. FIX? + os=netbsd + else + os=netbsdelf + fi + ;; + *) + os=netbsd + ;; + esac + # The OS release + # Debian GNU/NetBSD machines have a different userland, and + # thus, need a distinct triplet. However, they do not need + # kernel version information, so it can be replaced with a + # suitable tag, in the style of linux-gnu. + case "${UNAME_VERSION}" in + Debian*) + release='-gnu' + ;; + *) + release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'` + ;; + esac + # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM: + # contains redundant information, the shorter form: + # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used. + echo "${machine}-${os}${release}" + exit 0 ;; + amd64:OpenBSD:*:*) + echo x86_64-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + amiga:OpenBSD:*:*) + echo m68k-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + arc:OpenBSD:*:*) + echo mipsel-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + cats:OpenBSD:*:*) + echo arm-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + hp300:OpenBSD:*:*) + echo m68k-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + mac68k:OpenBSD:*:*) + echo m68k-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + macppc:OpenBSD:*:*) + echo powerpc-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + mvme68k:OpenBSD:*:*) + echo m68k-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + mvme88k:OpenBSD:*:*) + echo m88k-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + mvmeppc:OpenBSD:*:*) + echo powerpc-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + pegasos:OpenBSD:*:*) + echo powerpc-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + pmax:OpenBSD:*:*) + echo mipsel-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + sgi:OpenBSD:*:*) + echo mipseb-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + sun3:OpenBSD:*:*) + echo m68k-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + wgrisc:OpenBSD:*:*) + echo mipsel-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + *:OpenBSD:*:*) + echo ${UNAME_MACHINE}-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + *:ekkoBSD:*:*) + echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE} + exit 0 ;; + macppc:MirBSD:*:*) + echo powerppc-unknown-mirbsd${UNAME_RELEASE} + exit 0 ;; + *:MirBSD:*:*) + echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE} + exit 0 ;; + alpha:OSF1:*:*) + case $UNAME_RELEASE in + *4.0) + UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'` + ;; + *5.*) + UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'` + ;; + esac + # According to Compaq, /usr/sbin/psrinfo has been available on + # OSF/1 and Tru64 systems produced since 1995. I hope that + # covers most systems running today. This code pipes the CPU + # types through head -n 1, so we only detect the type of CPU 0. + ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1` + case "$ALPHA_CPU_TYPE" in + "EV4 (21064)") + UNAME_MACHINE="alpha" ;; + "EV4.5 (21064)") + UNAME_MACHINE="alpha" ;; + "LCA4 (21066/21068)") + UNAME_MACHINE="alpha" ;; + "EV5 (21164)") + UNAME_MACHINE="alphaev5" ;; + "EV5.6 (21164A)") + UNAME_MACHINE="alphaev56" ;; + "EV5.6 (21164PC)") + UNAME_MACHINE="alphapca56" ;; + "EV5.7 (21164PC)") + UNAME_MACHINE="alphapca57" ;; + "EV6 (21264)") + UNAME_MACHINE="alphaev6" ;; + "EV6.7 (21264A)") + UNAME_MACHINE="alphaev67" ;; + "EV6.8CB (21264C)") + UNAME_MACHINE="alphaev68" ;; + "EV6.8AL (21264B)") + UNAME_MACHINE="alphaev68" ;; + "EV6.8CX (21264D)") + UNAME_MACHINE="alphaev68" ;; + "EV6.9A (21264/EV69A)") + UNAME_MACHINE="alphaev69" ;; + "EV7 (21364)") + UNAME_MACHINE="alphaev7" ;; + "EV7.9 (21364A)") + UNAME_MACHINE="alphaev79" ;; + esac + # A Pn.n version is a patched version. + # A Vn.n version is a released version. + # A Tn.n version is a released field test version. + # A Xn.n version is an unreleased experimental baselevel. + # 1.2 uses "1.2" for uname -r. + echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + exit 0 ;; + Alpha*:OpenVMS:*:*) + echo alpha-hp-vms + exit 0 ;; + Alpha\ *:Windows_NT*:*) + # How do we know it's Interix rather than the generic POSIX subsystem? + # Should we change UNAME_MACHINE based on the output of uname instead + # of the specific Alpha model? + echo alpha-pc-interix + exit 0 ;; + 21064:Windows_NT:50:3) + echo alpha-dec-winnt3.5 + exit 0 ;; + Amiga*:UNIX_System_V:4.0:*) + echo m68k-unknown-sysv4 + exit 0;; + *:[Aa]miga[Oo][Ss]:*:*) + echo ${UNAME_MACHINE}-unknown-amigaos + exit 0 ;; + *:[Mm]orph[Oo][Ss]:*:*) + echo ${UNAME_MACHINE}-unknown-morphos + exit 0 ;; + *:OS/390:*:*) + echo i370-ibm-openedition + exit 0 ;; + *:OS400:*:*) + echo powerpc-ibm-os400 + exit 0 ;; + arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*) + echo arm-acorn-riscix${UNAME_RELEASE} + exit 0;; + SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*) + echo hppa1.1-hitachi-hiuxmpp + exit 0;; + Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*) + # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE. + if test "`(/bin/universe) 2>/dev/null`" = att ; then + echo pyramid-pyramid-sysv3 + else + echo pyramid-pyramid-bsd + fi + exit 0 ;; + NILE*:*:*:dcosx) + echo pyramid-pyramid-svr4 + exit 0 ;; + DRS?6000:unix:4.0:6*) + echo sparc-icl-nx6 + exit 0 ;; + DRS?6000:UNIX_SV:4.2*:7*) + case `/usr/bin/uname -p` in + sparc) echo sparc-icl-nx7 && exit 0 ;; + esac ;; + sun4H:SunOS:5.*:*) + echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit 0 ;; + sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*) + echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit 0 ;; + i86pc:SunOS:5.*:*) + echo i386-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit 0 ;; + sun4*:SunOS:6*:*) + # According to config.sub, this is the proper way to canonicalize + # SunOS6. Hard to guess exactly what SunOS6 will be like, but + # it's likely to be more like Solaris than SunOS4. + echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit 0 ;; + sun4*:SunOS:*:*) + case "`/usr/bin/arch -k`" in + Series*|S4*) + UNAME_RELEASE=`uname -v` + ;; + esac + # Japanese Language versions have a version number like `4.1.3-JL'. + echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'` + exit 0 ;; + sun3*:SunOS:*:*) + echo m68k-sun-sunos${UNAME_RELEASE} + exit 0 ;; + sun*:*:4.2BSD:*) + UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null` + test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3 + case "`/bin/arch`" in + sun3) + echo m68k-sun-sunos${UNAME_RELEASE} + ;; + sun4) + echo sparc-sun-sunos${UNAME_RELEASE} + ;; + esac + exit 0 ;; + aushp:SunOS:*:*) + echo sparc-auspex-sunos${UNAME_RELEASE} + exit 0 ;; + # The situation for MiNT is a little confusing. The machine name + # can be virtually everything (everything which is not + # "atarist" or "atariste" at least should have a processor + # > m68000). The system name ranges from "MiNT" over "FreeMiNT" + # to the lowercase version "mint" (or "freemint"). Finally + # the system name "TOS" denotes a system which is actually not + # MiNT. But MiNT is downward compatible to TOS, so this should + # be no problem. + atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit 0 ;; + atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit 0 ;; + *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit 0 ;; + milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*) + echo m68k-milan-mint${UNAME_RELEASE} + exit 0 ;; + hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*) + echo m68k-hades-mint${UNAME_RELEASE} + exit 0 ;; + *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*) + echo m68k-unknown-mint${UNAME_RELEASE} + exit 0 ;; + m68k:machten:*:*) + echo m68k-apple-machten${UNAME_RELEASE} + exit 0 ;; + powerpc:machten:*:*) + echo powerpc-apple-machten${UNAME_RELEASE} + exit 0 ;; + RISC*:Mach:*:*) + echo mips-dec-mach_bsd4.3 + exit 0 ;; + RISC*:ULTRIX:*:*) + echo mips-dec-ultrix${UNAME_RELEASE} + exit 0 ;; + VAX*:ULTRIX*:*:*) + echo vax-dec-ultrix${UNAME_RELEASE} + exit 0 ;; + 2020:CLIX:*:* | 2430:CLIX:*:*) + echo clipper-intergraph-clix${UNAME_RELEASE} + exit 0 ;; + mips:*:*:UMIPS | mips:*:*:RISCos) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c +#ifdef __cplusplus +#include /* for printf() prototype */ + int main (int argc, char *argv[]) { +#else + int main (argc, argv) int argc; char *argv[]; { +#endif + #if defined (host_mips) && defined (MIPSEB) + #if defined (SYSTYPE_SYSV) + printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0); + #endif + #if defined (SYSTYPE_SVR4) + printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0); + #endif + #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD) + printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0); + #endif + #endif + exit (-1); + } +EOF + $CC_FOR_BUILD -o $dummy $dummy.c \ + && $dummy `echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` \ + && exit 0 + echo mips-mips-riscos${UNAME_RELEASE} + exit 0 ;; + Motorola:PowerMAX_OS:*:*) + echo powerpc-motorola-powermax + exit 0 ;; + Motorola:*:4.3:PL8-*) + echo powerpc-harris-powermax + exit 0 ;; + Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*) + echo powerpc-harris-powermax + exit 0 ;; + Night_Hawk:Power_UNIX:*:*) + echo powerpc-harris-powerunix + exit 0 ;; + m88k:CX/UX:7*:*) + echo m88k-harris-cxux7 + exit 0 ;; + m88k:*:4*:R4*) + echo m88k-motorola-sysv4 + exit 0 ;; + m88k:*:3*:R3*) + echo m88k-motorola-sysv3 + exit 0 ;; + AViiON:dgux:*:*) + # DG/UX returns AViiON for all architectures + UNAME_PROCESSOR=`/usr/bin/uname -p` + if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ] + then + if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \ + [ ${TARGET_BINARY_INTERFACE}x = x ] + then + echo m88k-dg-dgux${UNAME_RELEASE} + else + echo m88k-dg-dguxbcs${UNAME_RELEASE} + fi + else + echo i586-dg-dgux${UNAME_RELEASE} + fi + exit 0 ;; + M88*:DolphinOS:*:*) # DolphinOS (SVR3) + echo m88k-dolphin-sysv3 + exit 0 ;; + M88*:*:R3*:*) + # Delta 88k system running SVR3 + echo m88k-motorola-sysv3 + exit 0 ;; + XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3) + echo m88k-tektronix-sysv3 + exit 0 ;; + Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD) + echo m68k-tektronix-bsd + exit 0 ;; + *:IRIX*:*:*) + echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'` + exit 0 ;; + ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX. + echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id + exit 0 ;; # Note that: echo "'`uname -s`'" gives 'AIX ' + i*86:AIX:*:*) + echo i386-ibm-aix + exit 0 ;; + ia64:AIX:*:*) + if [ -x /usr/bin/oslevel ] ; then + IBM_REV=`/usr/bin/oslevel` + else + IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} + fi + echo ${UNAME_MACHINE}-ibm-aix${IBM_REV} + exit 0 ;; + *:AIX:2:3) + if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #include + + main() + { + if (!__power_pc()) + exit(1); + puts("powerpc-ibm-aix3.2.5"); + exit(0); + } +EOF + $CC_FOR_BUILD -o $dummy $dummy.c && $dummy && exit 0 + echo rs6000-ibm-aix3.2.5 + elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then + echo rs6000-ibm-aix3.2.4 + else + echo rs6000-ibm-aix3.2 + fi + exit 0 ;; + *:AIX:*:[45]) + IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'` + if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then + IBM_ARCH=rs6000 + else + IBM_ARCH=powerpc + fi + if [ -x /usr/bin/oslevel ] ; then + IBM_REV=`/usr/bin/oslevel` + else + IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} + fi + echo ${IBM_ARCH}-ibm-aix${IBM_REV} + exit 0 ;; + *:AIX:*:*) + echo rs6000-ibm-aix + exit 0 ;; + ibmrt:4.4BSD:*|romp-ibm:BSD:*) + echo romp-ibm-bsd4.4 + exit 0 ;; + ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and + echo romp-ibm-bsd${UNAME_RELEASE} # 4.3 with uname added to + exit 0 ;; # report: romp-ibm BSD 4.3 + *:BOSX:*:*) + echo rs6000-bull-bosx + exit 0 ;; + DPX/2?00:B.O.S.:*:*) + echo m68k-bull-sysv3 + exit 0 ;; + 9000/[34]??:4.3bsd:1.*:*) + echo m68k-hp-bsd + exit 0 ;; + hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*) + echo m68k-hp-bsd4.4 + exit 0 ;; + 9000/[34678]??:HP-UX:*:*) + HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` + case "${UNAME_MACHINE}" in + 9000/31? ) HP_ARCH=m68000 ;; + 9000/[34]?? ) HP_ARCH=m68k ;; + 9000/[678][0-9][0-9]) + if [ -x /usr/bin/getconf ]; then + sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null` + sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null` + case "${sc_cpu_version}" in + 523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0 + 528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1 + 532) # CPU_PA_RISC2_0 + case "${sc_kernel_bits}" in + 32) HP_ARCH="hppa2.0n" ;; + 64) HP_ARCH="hppa2.0w" ;; + '') HP_ARCH="hppa2.0" ;; # HP-UX 10.20 + esac ;; + esac + fi + if [ "${HP_ARCH}" = "" ]; then + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + + #define _HPUX_SOURCE + #include + #include + + int main () + { + #if defined(_SC_KERNEL_BITS) + long bits = sysconf(_SC_KERNEL_BITS); + #endif + long cpu = sysconf (_SC_CPU_VERSION); + + switch (cpu) + { + case CPU_PA_RISC1_0: puts ("hppa1.0"); break; + case CPU_PA_RISC1_1: puts ("hppa1.1"); break; + case CPU_PA_RISC2_0: + #if defined(_SC_KERNEL_BITS) + switch (bits) + { + case 64: puts ("hppa2.0w"); break; + case 32: puts ("hppa2.0n"); break; + default: puts ("hppa2.0"); break; + } break; + #else /* !defined(_SC_KERNEL_BITS) */ + puts ("hppa2.0"); break; + #endif + default: puts ("hppa1.0"); break; + } + exit (0); + } +EOF + (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy` + test -z "$HP_ARCH" && HP_ARCH=hppa + fi ;; + esac + if [ ${HP_ARCH} = "hppa2.0w" ] + then + # avoid double evaluation of $set_cc_for_build + test -n "$CC_FOR_BUILD" || eval $set_cc_for_build + if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E -) | grep __LP64__ >/dev/null + then + HP_ARCH="hppa2.0w" + else + HP_ARCH="hppa64" + fi + fi + echo ${HP_ARCH}-hp-hpux${HPUX_REV} + exit 0 ;; + ia64:HP-UX:*:*) + HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` + echo ia64-hp-hpux${HPUX_REV} + exit 0 ;; + 3050*:HI-UX:*:*) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #include + int + main () + { + long cpu = sysconf (_SC_CPU_VERSION); + /* The order matters, because CPU_IS_HP_MC68K erroneously returns + true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct + results, however. */ + if (CPU_IS_PA_RISC (cpu)) + { + switch (cpu) + { + case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break; + case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break; + case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break; + default: puts ("hppa-hitachi-hiuxwe2"); break; + } + } + else if (CPU_IS_HP_MC68K (cpu)) + puts ("m68k-hitachi-hiuxwe2"); + else puts ("unknown-hitachi-hiuxwe2"); + exit (0); + } +EOF + $CC_FOR_BUILD -o $dummy $dummy.c && $dummy && exit 0 + echo unknown-hitachi-hiuxwe2 + exit 0 ;; + 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* ) + echo hppa1.1-hp-bsd + exit 0 ;; + 9000/8??:4.3bsd:*:*) + echo hppa1.0-hp-bsd + exit 0 ;; + *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*) + echo hppa1.0-hp-mpeix + exit 0 ;; + hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* ) + echo hppa1.1-hp-osf + exit 0 ;; + hp8??:OSF1:*:*) + echo hppa1.0-hp-osf + exit 0 ;; + i*86:OSF1:*:*) + if [ -x /usr/sbin/sysversion ] ; then + echo ${UNAME_MACHINE}-unknown-osf1mk + else + echo ${UNAME_MACHINE}-unknown-osf1 + fi + exit 0 ;; + parisc*:Lites*:*:*) + echo hppa1.1-hp-lites + exit 0 ;; + C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*) + echo c1-convex-bsd + exit 0 ;; + C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*) + if getsysinfo -f scalar_acc + then echo c32-convex-bsd + else echo c2-convex-bsd + fi + exit 0 ;; + C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*) + echo c34-convex-bsd + exit 0 ;; + C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*) + echo c38-convex-bsd + exit 0 ;; + C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*) + echo c4-convex-bsd + exit 0 ;; + CRAY*Y-MP:*:*:*) + echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit 0 ;; + CRAY*[A-Z]90:*:*:*) + echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \ + | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \ + -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \ + -e 's/\.[^.]*$/.X/' + exit 0 ;; + CRAY*TS:*:*:*) + echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit 0 ;; + CRAY*T3E:*:*:*) + echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit 0 ;; + CRAY*SV1:*:*:*) + echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit 0 ;; + *:UNICOS/mp:*:*) + echo nv1-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit 0 ;; + F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*) + FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` + FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'` + echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" + exit 0 ;; + 5000:UNIX_System_V:4.*:*) + FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` + FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'` + echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" + exit 0 ;; + i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*) + echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE} + exit 0 ;; + sparc*:BSD/OS:*:*) + echo sparc-unknown-bsdi${UNAME_RELEASE} + exit 0 ;; + *:BSD/OS:*:*) + echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE} + exit 0 ;; + *:FreeBSD:*:*) + # Determine whether the default compiler uses glibc. + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #include + #if __GLIBC__ >= 2 + LIBC=gnu + #else + LIBC= + #endif +EOF + eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep ^LIBC=` + # GNU/KFreeBSD systems have a "k" prefix to indicate we are using + # FreeBSD's kernel, but not the complete OS. + case ${LIBC} in gnu) kernel_only='k' ;; esac + echo ${UNAME_MACHINE}-unknown-${kernel_only}freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`${LIBC:+-$LIBC} + exit 0 ;; + i*:CYGWIN*:*) + echo ${UNAME_MACHINE}-pc-cygwin + exit 0 ;; + i*:MINGW*:*) + echo ${UNAME_MACHINE}-pc-mingw32 + exit 0 ;; + i*:PW*:*) + echo ${UNAME_MACHINE}-pc-pw32 + exit 0 ;; + x86:Interix*:[34]*) + echo i586-pc-interix${UNAME_RELEASE}|sed -e 's/\..*//' + exit 0 ;; + [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*) + echo i${UNAME_MACHINE}-pc-mks + exit 0 ;; + i*:Windows_NT*:* | Pentium*:Windows_NT*:*) + # How do we know it's Interix rather than the generic POSIX subsystem? + # It also conflicts with pre-2.0 versions of AT&T UWIN. Should we + # UNAME_MACHINE based on the output of uname instead of i386? + echo i586-pc-interix + exit 0 ;; + i*:UWIN*:*) + echo ${UNAME_MACHINE}-pc-uwin + exit 0 ;; + p*:CYGWIN*:*) + echo powerpcle-unknown-cygwin + exit 0 ;; + prep*:SunOS:5.*:*) + echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit 0 ;; + *:GNU:*:*) + # the GNU system + echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'` + exit 0 ;; + *:GNU/*:*:*) + # other systems with GNU libc and userland + echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-gnu + exit 0 ;; + i*86:Minix:*:*) + echo ${UNAME_MACHINE}-pc-minix + exit 0 ;; + arm*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit 0 ;; + cris:Linux:*:*) + echo cris-axis-linux-gnu + exit 0 ;; + ia64:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit 0 ;; + m32r*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit 0 ;; + m68*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit 0 ;; + mips:Linux:*:*) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #undef CPU + #undef mips + #undef mipsel + #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) + CPU=mipsel + #else + #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) + CPU=mips + #else + CPU= + #endif + #endif +EOF + eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep ^CPU=` + test x"${CPU}" != x && echo "${CPU}-unknown-linux-gnu" && exit 0 + ;; + mips64:Linux:*:*) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #undef CPU + #undef mips64 + #undef mips64el + #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) + CPU=mips64el + #else + #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) + CPU=mips64 + #else + CPU= + #endif + #endif +EOF + eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep ^CPU=` + test x"${CPU}" != x && echo "${CPU}-unknown-linux-gnu" && exit 0 + ;; + ppc:Linux:*:*) + echo powerpc-unknown-linux-gnu + exit 0 ;; + ppc64:Linux:*:*) + echo powerpc64-unknown-linux-gnu + exit 0 ;; + alpha:Linux:*:*) + case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in + EV5) UNAME_MACHINE=alphaev5 ;; + EV56) UNAME_MACHINE=alphaev56 ;; + PCA56) UNAME_MACHINE=alphapca56 ;; + PCA57) UNAME_MACHINE=alphapca56 ;; + EV6) UNAME_MACHINE=alphaev6 ;; + EV67) UNAME_MACHINE=alphaev67 ;; + EV68*) UNAME_MACHINE=alphaev68 ;; + esac + objdump --private-headers /bin/sh | grep ld.so.1 >/dev/null + if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi + echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC} + exit 0 ;; + parisc:Linux:*:* | hppa:Linux:*:*) + # Look for CPU level + case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in + PA7*) echo hppa1.1-unknown-linux-gnu ;; + PA8*) echo hppa2.0-unknown-linux-gnu ;; + *) echo hppa-unknown-linux-gnu ;; + esac + exit 0 ;; + parisc64:Linux:*:* | hppa64:Linux:*:*) + echo hppa64-unknown-linux-gnu + exit 0 ;; + s390:Linux:*:* | s390x:Linux:*:*) + echo ${UNAME_MACHINE}-ibm-linux + exit 0 ;; + sh64*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit 0 ;; + sh*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit 0 ;; + sparc:Linux:*:* | sparc64:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit 0 ;; + x86_64:Linux:*:*) + echo x86_64-unknown-linux-gnu + exit 0 ;; + i*86:Linux:*:*) + # The BFD linker knows what the default object file format is, so + # first see if it will tell us. cd to the root directory to prevent + # problems with other programs or directories called `ld' in the path. + # Set LC_ALL=C to ensure ld outputs messages in English. + ld_supported_targets=`cd /; LC_ALL=C ld --help 2>&1 \ + | sed -ne '/supported targets:/!d + s/[ ][ ]*/ /g + s/.*supported targets: *// + s/ .*// + p'` + case "$ld_supported_targets" in + elf32-i386) + TENTATIVE="${UNAME_MACHINE}-pc-linux-gnu" + ;; + a.out-i386-linux) + echo "${UNAME_MACHINE}-pc-linux-gnuaout" + exit 0 ;; + coff-i386) + echo "${UNAME_MACHINE}-pc-linux-gnucoff" + exit 0 ;; + "") + # Either a pre-BFD a.out linker (linux-gnuoldld) or + # one that does not give us useful --help. + echo "${UNAME_MACHINE}-pc-linux-gnuoldld" + exit 0 ;; + esac + # Determine whether the default compiler is a.out or elf + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #include + #ifdef __ELF__ + # ifdef __GLIBC__ + # if __GLIBC__ >= 2 + LIBC=gnu + # else + LIBC=gnulibc1 + # endif + # else + LIBC=gnulibc1 + # endif + #else + #ifdef __INTEL_COMPILER + LIBC=gnu + #else + LIBC=gnuaout + #endif + #endif + #ifdef __dietlibc__ + LIBC=dietlibc + #endif +EOF + eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep ^LIBC=` + test x"${LIBC}" != x && echo "${UNAME_MACHINE}-pc-linux-${LIBC}" && exit 0 + test x"${TENTATIVE}" != x && echo "${TENTATIVE}" && exit 0 + ;; + i*86:DYNIX/ptx:4*:*) + # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. + # earlier versions are messed up and put the nodename in both + # sysname and nodename. + echo i386-sequent-sysv4 + exit 0 ;; + i*86:UNIX_SV:4.2MP:2.*) + # Unixware is an offshoot of SVR4, but it has its own version + # number series starting with 2... + # I am not positive that other SVR4 systems won't match this, + # I just have to hope. -- rms. + # Use sysv4.2uw... so that sysv4* matches it. + echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION} + exit 0 ;; + i*86:OS/2:*:*) + # If we were able to find `uname', then EMX Unix compatibility + # is probably installed. + echo ${UNAME_MACHINE}-pc-os2-emx + exit 0 ;; + i*86:XTS-300:*:STOP) + echo ${UNAME_MACHINE}-unknown-stop + exit 0 ;; + i*86:atheos:*:*) + echo ${UNAME_MACHINE}-unknown-atheos + exit 0 ;; + i*86:syllable:*:*) + echo ${UNAME_MACHINE}-pc-syllable + exit 0 ;; + i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.0*:*) + echo i386-unknown-lynxos${UNAME_RELEASE} + exit 0 ;; + i*86:*DOS:*:*) + echo ${UNAME_MACHINE}-pc-msdosdjgpp + exit 0 ;; + i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*) + UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'` + if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then + echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL} + else + echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL} + fi + exit 0 ;; + i*86:*:5:[78]*) + case `/bin/uname -X | grep "^Machine"` in + *486*) UNAME_MACHINE=i486 ;; + *Pentium) UNAME_MACHINE=i586 ;; + *Pent*|*Celeron) UNAME_MACHINE=i686 ;; + esac + echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION} + exit 0 ;; + i*86:*:3.2:*) + if test -f /usr/options/cb.name; then + UNAME_REL=`sed -n 's/.*Version //p' /dev/null >/dev/null ; then + UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')` + (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486 + (/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \ + && UNAME_MACHINE=i586 + (/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \ + && UNAME_MACHINE=i686 + (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \ + && UNAME_MACHINE=i686 + echo ${UNAME_MACHINE}-pc-sco$UNAME_REL + else + echo ${UNAME_MACHINE}-pc-sysv32 + fi + exit 0 ;; + pc:*:*:*) + # Left here for compatibility: + # uname -m prints for DJGPP always 'pc', but it prints nothing about + # the processor, so we play safe by assuming i386. + echo i386-pc-msdosdjgpp + exit 0 ;; + Intel:Mach:3*:*) + echo i386-pc-mach3 + exit 0 ;; + paragon:*:*:*) + echo i860-intel-osf1 + exit 0 ;; + i860:*:4.*:*) # i860-SVR4 + if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then + echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4 + else # Add other i860-SVR4 vendors below as they are discovered. + echo i860-unknown-sysv${UNAME_RELEASE} # Unknown i860-SVR4 + fi + exit 0 ;; + mini*:CTIX:SYS*5:*) + # "miniframe" + echo m68010-convergent-sysv + exit 0 ;; + mc68k:UNIX:SYSTEM5:3.51m) + echo m68k-convergent-sysv + exit 0 ;; + M680?0:D-NIX:5.3:*) + echo m68k-diab-dnix + exit 0 ;; + M68*:*:R3V[567]*:*) + test -r /sysV68 && echo 'm68k-motorola-sysv' && exit 0 ;; + 3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0) + OS_REL='' + test -r /etc/.relid \ + && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && echo i486-ncr-sysv4.3${OS_REL} && exit 0 + /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ + && echo i586-ncr-sysv4.3${OS_REL} && exit 0 ;; + 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*) + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && echo i486-ncr-sysv4 && exit 0 ;; + m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*) + echo m68k-unknown-lynxos${UNAME_RELEASE} + exit 0 ;; + mc68030:UNIX_System_V:4.*:*) + echo m68k-atari-sysv4 + exit 0 ;; + TSUNAMI:LynxOS:2.*:*) + echo sparc-unknown-lynxos${UNAME_RELEASE} + exit 0 ;; + rs6000:LynxOS:2.*:*) + echo rs6000-unknown-lynxos${UNAME_RELEASE} + exit 0 ;; + PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.0*:*) + echo powerpc-unknown-lynxos${UNAME_RELEASE} + exit 0 ;; + SM[BE]S:UNIX_SV:*:*) + echo mips-dde-sysv${UNAME_RELEASE} + exit 0 ;; + RM*:ReliantUNIX-*:*:*) + echo mips-sni-sysv4 + exit 0 ;; + RM*:SINIX-*:*:*) + echo mips-sni-sysv4 + exit 0 ;; + *:SINIX-*:*:*) + if uname -p 2>/dev/null >/dev/null ; then + UNAME_MACHINE=`(uname -p) 2>/dev/null` + echo ${UNAME_MACHINE}-sni-sysv4 + else + echo ns32k-sni-sysv + fi + exit 0 ;; + PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort + # says + echo i586-unisys-sysv4 + exit 0 ;; + *:UNIX_System_V:4*:FTX*) + # From Gerald Hewes . + # How about differentiating between stratus architectures? -djm + echo hppa1.1-stratus-sysv4 + exit 0 ;; + *:*:*:FTX*) + # From seanf@swdc.stratus.com. + echo i860-stratus-sysv4 + exit 0 ;; + *:VOS:*:*) + # From Paul.Green@stratus.com. + echo hppa1.1-stratus-vos + exit 0 ;; + mc68*:A/UX:*:*) + echo m68k-apple-aux${UNAME_RELEASE} + exit 0 ;; + news*:NEWS-OS:6*:*) + echo mips-sony-newsos6 + exit 0 ;; + R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*) + if [ -d /usr/nec ]; then + echo mips-nec-sysv${UNAME_RELEASE} + else + echo mips-unknown-sysv${UNAME_RELEASE} + fi + exit 0 ;; + BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only. + echo powerpc-be-beos + exit 0 ;; + BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only. + echo powerpc-apple-beos + exit 0 ;; + BePC:BeOS:*:*) # BeOS running on Intel PC compatible. + echo i586-pc-beos + exit 0 ;; + SX-4:SUPER-UX:*:*) + echo sx4-nec-superux${UNAME_RELEASE} + exit 0 ;; + SX-5:SUPER-UX:*:*) + echo sx5-nec-superux${UNAME_RELEASE} + exit 0 ;; + SX-6:SUPER-UX:*:*) + echo sx6-nec-superux${UNAME_RELEASE} + exit 0 ;; + Power*:Rhapsody:*:*) + echo powerpc-apple-rhapsody${UNAME_RELEASE} + exit 0 ;; + *:Rhapsody:*:*) + echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE} + exit 0 ;; + *:Darwin:*:*) + case `uname -p` in + *86) UNAME_PROCESSOR=i686 ;; + powerpc) UNAME_PROCESSOR=powerpc ;; + esac + echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE} + exit 0 ;; + *:procnto*:*:* | *:QNX:[0123456789]*:*) + UNAME_PROCESSOR=`uname -p` + if test "$UNAME_PROCESSOR" = "x86"; then + UNAME_PROCESSOR=i386 + UNAME_MACHINE=pc + fi + echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE} + exit 0 ;; + *:QNX:*:4*) + echo i386-pc-qnx + exit 0 ;; + NSR-?:NONSTOP_KERNEL:*:*) + echo nsr-tandem-nsk${UNAME_RELEASE} + exit 0 ;; + *:NonStop-UX:*:*) + echo mips-compaq-nonstopux + exit 0 ;; + BS2000:POSIX*:*:*) + echo bs2000-siemens-sysv + exit 0 ;; + DS/*:UNIX_System_V:*:*) + echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE} + exit 0 ;; + *:Plan9:*:*) + # "uname -m" is not consistent, so use $cputype instead. 386 + # is converted to i386 for consistency with other x86 + # operating systems. + if test "$cputype" = "386"; then + UNAME_MACHINE=i386 + else + UNAME_MACHINE="$cputype" + fi + echo ${UNAME_MACHINE}-unknown-plan9 + exit 0 ;; + *:TOPS-10:*:*) + echo pdp10-unknown-tops10 + exit 0 ;; + *:TENEX:*:*) + echo pdp10-unknown-tenex + exit 0 ;; + KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*) + echo pdp10-dec-tops20 + exit 0 ;; + XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*) + echo pdp10-xkl-tops20 + exit 0 ;; + *:TOPS-20:*:*) + echo pdp10-unknown-tops20 + exit 0 ;; + *:ITS:*:*) + echo pdp10-unknown-its + exit 0 ;; + SEI:*:*:SEIUX) + echo mips-sei-seiux${UNAME_RELEASE} + exit 0 ;; + *:DragonFly:*:*) + echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` + exit 0 ;; +esac + +#echo '(No uname command or uname output not recognized.)' 1>&2 +#echo "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" 1>&2 + +eval $set_cc_for_build +cat >$dummy.c < +# include +#endif +main () +{ +#if defined (sony) +#if defined (MIPSEB) + /* BFD wants "bsd" instead of "newsos". Perhaps BFD should be changed, + I don't know.... */ + printf ("mips-sony-bsd\n"); exit (0); +#else +#include + printf ("m68k-sony-newsos%s\n", +#ifdef NEWSOS4 + "4" +#else + "" +#endif + ); exit (0); +#endif +#endif + +#if defined (__arm) && defined (__acorn) && defined (__unix) + printf ("arm-acorn-riscix"); exit (0); +#endif + +#if defined (hp300) && !defined (hpux) + printf ("m68k-hp-bsd\n"); exit (0); +#endif + +#if defined (NeXT) +#if !defined (__ARCHITECTURE__) +#define __ARCHITECTURE__ "m68k" +#endif + int version; + version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`; + if (version < 4) + printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version); + else + printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version); + exit (0); +#endif + +#if defined (MULTIMAX) || defined (n16) +#if defined (UMAXV) + printf ("ns32k-encore-sysv\n"); exit (0); +#else +#if defined (CMU) + printf ("ns32k-encore-mach\n"); exit (0); +#else + printf ("ns32k-encore-bsd\n"); exit (0); +#endif +#endif +#endif + +#if defined (__386BSD__) + printf ("i386-pc-bsd\n"); exit (0); +#endif + +#if defined (sequent) +#if defined (i386) + printf ("i386-sequent-dynix\n"); exit (0); +#endif +#if defined (ns32000) + printf ("ns32k-sequent-dynix\n"); exit (0); +#endif +#endif + +#if defined (_SEQUENT_) + struct utsname un; + + uname(&un); + + if (strncmp(un.version, "V2", 2) == 0) { + printf ("i386-sequent-ptx2\n"); exit (0); + } + if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */ + printf ("i386-sequent-ptx1\n"); exit (0); + } + printf ("i386-sequent-ptx\n"); exit (0); + +#endif + +#if defined (vax) +# if !defined (ultrix) +# include +# if defined (BSD) +# if BSD == 43 + printf ("vax-dec-bsd4.3\n"); exit (0); +# else +# if BSD == 199006 + printf ("vax-dec-bsd4.3reno\n"); exit (0); +# else + printf ("vax-dec-bsd\n"); exit (0); +# endif +# endif +# else + printf ("vax-dec-bsd\n"); exit (0); +# endif +# else + printf ("vax-dec-ultrix\n"); exit (0); +# endif +#endif + +#if defined (alliant) && defined (i860) + printf ("i860-alliant-bsd\n"); exit (0); +#endif + + exit (1); +} +EOF + +$CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && $dummy && exit 0 + +# Apollos put the system type in the environment. + +test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit 0; } + +# Convex versions that predate uname can use getsysinfo(1) + +if [ -x /usr/convex/getsysinfo ] +then + case `getsysinfo -f cpu_type` in + c1*) + echo c1-convex-bsd + exit 0 ;; + c2*) + if getsysinfo -f scalar_acc + then echo c32-convex-bsd + else echo c2-convex-bsd + fi + exit 0 ;; + c34*) + echo c34-convex-bsd + exit 0 ;; + c38*) + echo c38-convex-bsd + exit 0 ;; + c4*) + echo c4-convex-bsd + exit 0 ;; + esac +fi + +cat >&2 < in order to provide the needed +information to handle your system. + +config.guess timestamp = $timestamp + +uname -m = `(uname -m) 2>/dev/null || echo unknown` +uname -r = `(uname -r) 2>/dev/null || echo unknown` +uname -s = `(uname -s) 2>/dev/null || echo unknown` +uname -v = `(uname -v) 2>/dev/null || echo unknown` + +/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null` +/bin/uname -X = `(/bin/uname -X) 2>/dev/null` + +hostinfo = `(hostinfo) 2>/dev/null` +/bin/universe = `(/bin/universe) 2>/dev/null` +/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null` +/bin/arch = `(/bin/arch) 2>/dev/null` +/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null` +/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null` + +UNAME_MACHINE = ${UNAME_MACHINE} +UNAME_RELEASE = ${UNAME_RELEASE} +UNAME_SYSTEM = ${UNAME_SYSTEM} +UNAME_VERSION = ${UNAME_VERSION} +EOF + +exit 1 + +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "timestamp='" +# time-stamp-format: "%:y-%02m-%02d" +# time-stamp-end: "'" +# End: diff --git a/Code/BF2/External/speex-1.0.5/config.sub b/Code/BF2/External/speex-1.0.5/config.sub new file mode 100755 index 000000000..ba331039b --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/config.sub @@ -0,0 +1,1549 @@ +#! /bin/sh +# Configuration validation subroutine script. +# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, +# 2000, 2001, 2002, 2003 Free Software Foundation, Inc. + +timestamp='2004-03-12' + +# This file is (in principle) common to ALL GNU software. +# The presence of a machine in this file suggests that SOME GNU software +# can handle that machine. It does not imply ALL GNU software can. +# +# This file is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, +# Boston, MA 02111-1307, USA. + +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + +# Please send patches to . Submit a context +# diff and a properly formatted ChangeLog entry. +# +# Configuration subroutine to validate and canonicalize a configuration type. +# Supply the specified configuration type as an argument. +# If it is invalid, we print an error message on stderr and exit with code 1. +# Otherwise, we print the canonical config type on stdout and succeed. + +# This file is supposed to be the same for all GNU packages +# and recognize all the CPU types, system types and aliases +# that are meaningful with *any* GNU software. +# Each package is responsible for reporting which valid configurations +# it does not support. The user should be able to distinguish +# a failure to support a valid configuration from a meaningless +# configuration. + +# The goal of this file is to map all the various variations of a given +# machine specification into a single specification in the form: +# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM +# or in some cases, the newer four-part form: +# CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM +# It is wrong to echo any other type of specification. + +me=`echo "$0" | sed -e 's,.*/,,'` + +usage="\ +Usage: $0 [OPTION] CPU-MFR-OPSYS + $0 [OPTION] ALIAS + +Canonicalize a configuration name. + +Operation modes: + -h, --help print this help, then exit + -t, --time-stamp print date of last modification, then exit + -v, --version print version number, then exit + +Report bugs and patches to ." + +version="\ +GNU config.sub ($timestamp) + +Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001 +Free Software Foundation, Inc. + +This is free software; see the source for copying conditions. There is NO +warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." + +help=" +Try \`$me --help' for more information." + +# Parse command line +while test $# -gt 0 ; do + case $1 in + --time-stamp | --time* | -t ) + echo "$timestamp" ; exit 0 ;; + --version | -v ) + echo "$version" ; exit 0 ;; + --help | --h* | -h ) + echo "$usage"; exit 0 ;; + -- ) # Stop option processing + shift; break ;; + - ) # Use stdin as input. + break ;; + -* ) + echo "$me: invalid option $1$help" + exit 1 ;; + + *local*) + # First pass through any local machine types. + echo $1 + exit 0;; + + * ) + break ;; + esac +done + +case $# in + 0) echo "$me: missing argument$help" >&2 + exit 1;; + 1) ;; + *) echo "$me: too many arguments$help" >&2 + exit 1;; +esac + +# Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any). +# Here we must recognize all the valid KERNEL-OS combinations. +maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'` +case $maybe_os in + nto-qnx* | linux-gnu* | linux-dietlibc | linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | \ + kfreebsd*-gnu* | knetbsd*-gnu* | netbsd*-gnu* | storm-chaos* | os2-emx* | rtmk-nova*) + os=-$maybe_os + basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'` + ;; + *) + basic_machine=`echo $1 | sed 's/-[^-]*$//'` + if [ $basic_machine != $1 ] + then os=`echo $1 | sed 's/.*-/-/'` + else os=; fi + ;; +esac + +### Let's recognize common machines as not being operating systems so +### that things like config.sub decstation-3100 work. We also +### recognize some manufacturers as not being operating systems, so we +### can provide default operating systems below. +case $os in + -sun*os*) + # Prevent following clause from handling this invalid input. + ;; + -dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \ + -att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \ + -unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \ + -convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\ + -c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \ + -harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \ + -apple | -axis) + os= + basic_machine=$1 + ;; + -sim | -cisco | -oki | -wec | -winbond) + os= + basic_machine=$1 + ;; + -scout) + ;; + -wrs) + os=-vxworks + basic_machine=$1 + ;; + -chorusos*) + os=-chorusos + basic_machine=$1 + ;; + -chorusrdb) + os=-chorusrdb + basic_machine=$1 + ;; + -hiux*) + os=-hiuxwe2 + ;; + -sco5) + os=-sco3.2v5 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco4) + os=-sco3.2v4 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco3.2.[4-9]*) + os=`echo $os | sed -e 's/sco3.2./sco3.2v/'` + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco3.2v[4-9]*) + # Don't forget version if it is 3.2v4 or newer. + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco*) + os=-sco3.2v2 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -udk*) + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -isc) + os=-isc2.2 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -clix*) + basic_machine=clipper-intergraph + ;; + -isc*) + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -lynx*) + os=-lynxos + ;; + -ptx*) + basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'` + ;; + -windowsnt*) + os=`echo $os | sed -e 's/windowsnt/winnt/'` + ;; + -psos*) + os=-psos + ;; + -mint | -mint[0-9]*) + basic_machine=m68k-atari + os=-mint + ;; +esac + +# Decode aliases for certain CPU-COMPANY combinations. +case $basic_machine in + # Recognize the basic CPU types without company name. + # Some are omitted here because they have special meanings below. + 1750a | 580 \ + | a29k \ + | alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \ + | alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \ + | am33_2.0 \ + | arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr \ + | c4x | clipper \ + | d10v | d30v | dlx | dsp16xx \ + | fr30 | frv \ + | h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \ + | i370 | i860 | i960 | ia64 \ + | ip2k | iq2000 \ + | m32r | m32rle | m68000 | m68k | m88k | mcore \ + | mips | mipsbe | mipseb | mipsel | mipsle \ + | mips16 \ + | mips64 | mips64el \ + | mips64vr | mips64vrel \ + | mips64orion | mips64orionel \ + | mips64vr4100 | mips64vr4100el \ + | mips64vr4300 | mips64vr4300el \ + | mips64vr5000 | mips64vr5000el \ + | mipsisa32 | mipsisa32el \ + | mipsisa32r2 | mipsisa32r2el \ + | mipsisa64 | mipsisa64el \ + | mipsisa64r2 | mipsisa64r2el \ + | mipsisa64sb1 | mipsisa64sb1el \ + | mipsisa64sr71k | mipsisa64sr71kel \ + | mipstx39 | mipstx39el \ + | mn10200 | mn10300 \ + | msp430 \ + | ns16k | ns32k \ + | openrisc | or32 \ + | pdp10 | pdp11 | pj | pjl \ + | powerpc | powerpc64 | powerpc64le | powerpcle | ppcbe \ + | pyramid \ + | sh | sh[1234] | sh[23]e | sh[34]eb | shbe | shle | sh[1234]le | sh3ele \ + | sh64 | sh64le \ + | sparc | sparc64 | sparc86x | sparclet | sparclite | sparcv8 | sparcv9 | sparcv9b \ + | strongarm \ + | tahoe | thumb | tic4x | tic80 | tron \ + | v850 | v850e \ + | we32k \ + | x86 | xscale | xstormy16 | xtensa \ + | z8k) + basic_machine=$basic_machine-unknown + ;; + m6811 | m68hc11 | m6812 | m68hc12) + # Motorola 68HC11/12. + basic_machine=$basic_machine-unknown + os=-none + ;; + m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k) + ;; + + # We use `pc' rather than `unknown' + # because (1) that's what they normally are, and + # (2) the word "unknown" tends to confuse beginning users. + i*86 | x86_64) + basic_machine=$basic_machine-pc + ;; + # Object if more than one company name word. + *-*-*) + echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 + exit 1 + ;; + # Recognize the basic CPU types with company name. + 580-* \ + | a29k-* \ + | alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \ + | alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \ + | alphapca5[67]-* | alpha64pca5[67]-* | arc-* \ + | arm-* | armbe-* | armle-* | armeb-* | armv*-* \ + | avr-* \ + | bs2000-* \ + | c[123]* | c30-* | [cjt]90-* | c4x-* | c54x-* | c55x-* | c6x-* \ + | clipper-* | cydra-* \ + | d10v-* | d30v-* | dlx-* \ + | elxsi-* \ + | f30[01]-* | f700-* | fr30-* | frv-* | fx80-* \ + | h8300-* | h8500-* \ + | hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \ + | i*86-* | i860-* | i960-* | ia64-* \ + | ip2k-* | iq2000-* \ + | m32r-* | m32rle-* \ + | m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \ + | m88110-* | m88k-* | mcore-* \ + | mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \ + | mips16-* \ + | mips64-* | mips64el-* \ + | mips64vr-* | mips64vrel-* \ + | mips64orion-* | mips64orionel-* \ + | mips64vr4100-* | mips64vr4100el-* \ + | mips64vr4300-* | mips64vr4300el-* \ + | mips64vr5000-* | mips64vr5000el-* \ + | mipsisa32-* | mipsisa32el-* \ + | mipsisa32r2-* | mipsisa32r2el-* \ + | mipsisa64-* | mipsisa64el-* \ + | mipsisa64r2-* | mipsisa64r2el-* \ + | mipsisa64sb1-* | mipsisa64sb1el-* \ + | mipsisa64sr71k-* | mipsisa64sr71kel-* \ + | mipstx39-* | mipstx39el-* \ + | msp430-* \ + | none-* | np1-* | nv1-* | ns16k-* | ns32k-* \ + | orion-* \ + | pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \ + | powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* | ppcbe-* \ + | pyramid-* \ + | romp-* | rs6000-* \ + | sh-* | sh[1234]-* | sh[23]e-* | sh[34]eb-* | shbe-* \ + | shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \ + | sparc-* | sparc64-* | sparc86x-* | sparclet-* | sparclite-* \ + | sparcv8-* | sparcv9-* | sparcv9b-* | strongarm-* | sv1-* | sx?-* \ + | tahoe-* | thumb-* \ + | tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \ + | tron-* \ + | v850-* | v850e-* | vax-* \ + | we32k-* \ + | x86-* | x86_64-* | xps100-* | xscale-* | xstormy16-* \ + | xtensa-* \ + | ymp-* \ + | z8k-*) + ;; + # Recognize the various machine names and aliases which stand + # for a CPU type and a company and sometimes even an OS. + 386bsd) + basic_machine=i386-unknown + os=-bsd + ;; + 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc) + basic_machine=m68000-att + ;; + 3b*) + basic_machine=we32k-att + ;; + a29khif) + basic_machine=a29k-amd + os=-udi + ;; + abacus) + basic_machine=abacus-unknown + ;; + adobe68k) + basic_machine=m68010-adobe + os=-scout + ;; + alliant | fx80) + basic_machine=fx80-alliant + ;; + altos | altos3068) + basic_machine=m68k-altos + ;; + am29k) + basic_machine=a29k-none + os=-bsd + ;; + amd64) + basic_machine=x86_64-pc + ;; + amd64-*) + basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + amdahl) + basic_machine=580-amdahl + os=-sysv + ;; + amiga | amiga-*) + basic_machine=m68k-unknown + ;; + amigaos | amigados) + basic_machine=m68k-unknown + os=-amigaos + ;; + amigaunix | amix) + basic_machine=m68k-unknown + os=-sysv4 + ;; + apollo68) + basic_machine=m68k-apollo + os=-sysv + ;; + apollo68bsd) + basic_machine=m68k-apollo + os=-bsd + ;; + aux) + basic_machine=m68k-apple + os=-aux + ;; + balance) + basic_machine=ns32k-sequent + os=-dynix + ;; + c90) + basic_machine=c90-cray + os=-unicos + ;; + convex-c1) + basic_machine=c1-convex + os=-bsd + ;; + convex-c2) + basic_machine=c2-convex + os=-bsd + ;; + convex-c32) + basic_machine=c32-convex + os=-bsd + ;; + convex-c34) + basic_machine=c34-convex + os=-bsd + ;; + convex-c38) + basic_machine=c38-convex + os=-bsd + ;; + cray | j90) + basic_machine=j90-cray + os=-unicos + ;; + cr16c) + basic_machine=cr16c-unknown + os=-elf + ;; + crds | unos) + basic_machine=m68k-crds + ;; + cris | cris-* | etrax*) + basic_machine=cris-axis + ;; + crx) + basic_machine=crx-unknown + os=-elf + ;; + da30 | da30-*) + basic_machine=m68k-da30 + ;; + decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn) + basic_machine=mips-dec + ;; + decsystem10* | dec10*) + basic_machine=pdp10-dec + os=-tops10 + ;; + decsystem20* | dec20*) + basic_machine=pdp10-dec + os=-tops20 + ;; + delta | 3300 | motorola-3300 | motorola-delta \ + | 3300-motorola | delta-motorola) + basic_machine=m68k-motorola + ;; + delta88) + basic_machine=m88k-motorola + os=-sysv3 + ;; + dpx20 | dpx20-*) + basic_machine=rs6000-bull + os=-bosx + ;; + dpx2* | dpx2*-bull) + basic_machine=m68k-bull + os=-sysv3 + ;; + ebmon29k) + basic_machine=a29k-amd + os=-ebmon + ;; + elxsi) + basic_machine=elxsi-elxsi + os=-bsd + ;; + encore | umax | mmax) + basic_machine=ns32k-encore + ;; + es1800 | OSE68k | ose68k | ose | OSE) + basic_machine=m68k-ericsson + os=-ose + ;; + fx2800) + basic_machine=i860-alliant + ;; + genix) + basic_machine=ns32k-ns + ;; + gmicro) + basic_machine=tron-gmicro + os=-sysv + ;; + go32) + basic_machine=i386-pc + os=-go32 + ;; + h3050r* | hiux*) + basic_machine=hppa1.1-hitachi + os=-hiuxwe2 + ;; + h8300hms) + basic_machine=h8300-hitachi + os=-hms + ;; + h8300xray) + basic_machine=h8300-hitachi + os=-xray + ;; + h8500hms) + basic_machine=h8500-hitachi + os=-hms + ;; + harris) + basic_machine=m88k-harris + os=-sysv3 + ;; + hp300-*) + basic_machine=m68k-hp + ;; + hp300bsd) + basic_machine=m68k-hp + os=-bsd + ;; + hp300hpux) + basic_machine=m68k-hp + os=-hpux + ;; + hp3k9[0-9][0-9] | hp9[0-9][0-9]) + basic_machine=hppa1.0-hp + ;; + hp9k2[0-9][0-9] | hp9k31[0-9]) + basic_machine=m68000-hp + ;; + hp9k3[2-9][0-9]) + basic_machine=m68k-hp + ;; + hp9k6[0-9][0-9] | hp6[0-9][0-9]) + basic_machine=hppa1.0-hp + ;; + hp9k7[0-79][0-9] | hp7[0-79][0-9]) + basic_machine=hppa1.1-hp + ;; + hp9k78[0-9] | hp78[0-9]) + # FIXME: really hppa2.0-hp + basic_machine=hppa1.1-hp + ;; + hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893) + # FIXME: really hppa2.0-hp + basic_machine=hppa1.1-hp + ;; + hp9k8[0-9][13679] | hp8[0-9][13679]) + basic_machine=hppa1.1-hp + ;; + hp9k8[0-9][0-9] | hp8[0-9][0-9]) + basic_machine=hppa1.0-hp + ;; + hppa-next) + os=-nextstep3 + ;; + hppaosf) + basic_machine=hppa1.1-hp + os=-osf + ;; + hppro) + basic_machine=hppa1.1-hp + os=-proelf + ;; + i370-ibm* | ibm*) + basic_machine=i370-ibm + ;; +# I'm not sure what "Sysv32" means. Should this be sysv3.2? + i*86v32) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-sysv32 + ;; + i*86v4*) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-sysv4 + ;; + i*86v) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-sysv + ;; + i*86sol2) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-solaris2 + ;; + i386mach) + basic_machine=i386-mach + os=-mach + ;; + i386-vsta | vsta) + basic_machine=i386-unknown + os=-vsta + ;; + iris | iris4d) + basic_machine=mips-sgi + case $os in + -irix*) + ;; + *) + os=-irix4 + ;; + esac + ;; + isi68 | isi) + basic_machine=m68k-isi + os=-sysv + ;; + m88k-omron*) + basic_machine=m88k-omron + ;; + magnum | m3230) + basic_machine=mips-mips + os=-sysv + ;; + merlin) + basic_machine=ns32k-utek + os=-sysv + ;; + mingw32) + basic_machine=i386-pc + os=-mingw32 + ;; + miniframe) + basic_machine=m68000-convergent + ;; + *mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*) + basic_machine=m68k-atari + os=-mint + ;; + mips3*-*) + basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'` + ;; + mips3*) + basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown + ;; + mmix*) + basic_machine=mmix-knuth + os=-mmixware + ;; + monitor) + basic_machine=m68k-rom68k + os=-coff + ;; + morphos) + basic_machine=powerpc-unknown + os=-morphos + ;; + msdos) + basic_machine=i386-pc + os=-msdos + ;; + mvs) + basic_machine=i370-ibm + os=-mvs + ;; + ncr3000) + basic_machine=i486-ncr + os=-sysv4 + ;; + netbsd386) + basic_machine=i386-unknown + os=-netbsd + ;; + netwinder) + basic_machine=armv4l-rebel + os=-linux + ;; + news | news700 | news800 | news900) + basic_machine=m68k-sony + os=-newsos + ;; + news1000) + basic_machine=m68030-sony + os=-newsos + ;; + news-3600 | risc-news) + basic_machine=mips-sony + os=-newsos + ;; + necv70) + basic_machine=v70-nec + os=-sysv + ;; + next | m*-next ) + basic_machine=m68k-next + case $os in + -nextstep* ) + ;; + -ns2*) + os=-nextstep2 + ;; + *) + os=-nextstep3 + ;; + esac + ;; + nh3000) + basic_machine=m68k-harris + os=-cxux + ;; + nh[45]000) + basic_machine=m88k-harris + os=-cxux + ;; + nindy960) + basic_machine=i960-intel + os=-nindy + ;; + mon960) + basic_machine=i960-intel + os=-mon960 + ;; + nonstopux) + basic_machine=mips-compaq + os=-nonstopux + ;; + np1) + basic_machine=np1-gould + ;; + nv1) + basic_machine=nv1-cray + os=-unicosmp + ;; + nsr-tandem) + basic_machine=nsr-tandem + ;; + op50n-* | op60c-*) + basic_machine=hppa1.1-oki + os=-proelf + ;; + or32 | or32-*) + basic_machine=or32-unknown + os=-coff + ;; + os400) + basic_machine=powerpc-ibm + os=-os400 + ;; + OSE68000 | ose68000) + basic_machine=m68000-ericsson + os=-ose + ;; + os68k) + basic_machine=m68k-none + os=-os68k + ;; + pa-hitachi) + basic_machine=hppa1.1-hitachi + os=-hiuxwe2 + ;; + paragon) + basic_machine=i860-intel + os=-osf + ;; + pbd) + basic_machine=sparc-tti + ;; + pbb) + basic_machine=m68k-tti + ;; + pc532 | pc532-*) + basic_machine=ns32k-pc532 + ;; + pentium | p5 | k5 | k6 | nexgen | viac3) + basic_machine=i586-pc + ;; + pentiumpro | p6 | 6x86 | athlon | athlon_*) + basic_machine=i686-pc + ;; + pentiumii | pentium2 | pentiumiii | pentium3) + basic_machine=i686-pc + ;; + pentium4) + basic_machine=i786-pc + ;; + pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*) + basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentiumpro-* | p6-* | 6x86-* | athlon-*) + basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*) + basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentium4-*) + basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pn) + basic_machine=pn-gould + ;; + power) basic_machine=power-ibm + ;; + ppc) basic_machine=powerpc-unknown + ;; + ppc-*) basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ppcle | powerpclittle | ppc-le | powerpc-little) + basic_machine=powerpcle-unknown + ;; + ppcle-* | powerpclittle-*) + basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ppc64) basic_machine=powerpc64-unknown + ;; + ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ppc64le | powerpc64little | ppc64-le | powerpc64-little) + basic_machine=powerpc64le-unknown + ;; + ppc64le-* | powerpc64little-*) + basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ps2) + basic_machine=i386-ibm + ;; + pw32) + basic_machine=i586-unknown + os=-pw32 + ;; + rom68k) + basic_machine=m68k-rom68k + os=-coff + ;; + rm[46]00) + basic_machine=mips-siemens + ;; + rtpc | rtpc-*) + basic_machine=romp-ibm + ;; + s390 | s390-*) + basic_machine=s390-ibm + ;; + s390x | s390x-*) + basic_machine=s390x-ibm + ;; + sa29200) + basic_machine=a29k-amd + os=-udi + ;; + sb1) + basic_machine=mipsisa64sb1-unknown + ;; + sb1el) + basic_machine=mipsisa64sb1el-unknown + ;; + sei) + basic_machine=mips-sei + os=-seiux + ;; + sequent) + basic_machine=i386-sequent + ;; + sh) + basic_machine=sh-hitachi + os=-hms + ;; + sh64) + basic_machine=sh64-unknown + ;; + sparclite-wrs | simso-wrs) + basic_machine=sparclite-wrs + os=-vxworks + ;; + sps7) + basic_machine=m68k-bull + os=-sysv2 + ;; + spur) + basic_machine=spur-unknown + ;; + st2000) + basic_machine=m68k-tandem + ;; + stratus) + basic_machine=i860-stratus + os=-sysv4 + ;; + sun2) + basic_machine=m68000-sun + ;; + sun2os3) + basic_machine=m68000-sun + os=-sunos3 + ;; + sun2os4) + basic_machine=m68000-sun + os=-sunos4 + ;; + sun3os3) + basic_machine=m68k-sun + os=-sunos3 + ;; + sun3os4) + basic_machine=m68k-sun + os=-sunos4 + ;; + sun4os3) + basic_machine=sparc-sun + os=-sunos3 + ;; + sun4os4) + basic_machine=sparc-sun + os=-sunos4 + ;; + sun4sol2) + basic_machine=sparc-sun + os=-solaris2 + ;; + sun3 | sun3-*) + basic_machine=m68k-sun + ;; + sun4) + basic_machine=sparc-sun + ;; + sun386 | sun386i | roadrunner) + basic_machine=i386-sun + ;; + sv1) + basic_machine=sv1-cray + os=-unicos + ;; + symmetry) + basic_machine=i386-sequent + os=-dynix + ;; + t3e) + basic_machine=alphaev5-cray + os=-unicos + ;; + t90) + basic_machine=t90-cray + os=-unicos + ;; + tic54x | c54x*) + basic_machine=tic54x-unknown + os=-coff + ;; + tic55x | c55x*) + basic_machine=tic55x-unknown + os=-coff + ;; + tic6x | c6x*) + basic_machine=tic6x-unknown + os=-coff + ;; + tx39) + basic_machine=mipstx39-unknown + ;; + tx39el) + basic_machine=mipstx39el-unknown + ;; + toad1) + basic_machine=pdp10-xkl + os=-tops20 + ;; + tower | tower-32) + basic_machine=m68k-ncr + ;; + tpf) + basic_machine=s390x-ibm + os=-tpf + ;; + udi29k) + basic_machine=a29k-amd + os=-udi + ;; + ultra3) + basic_machine=a29k-nyu + os=-sym1 + ;; + v810 | necv810) + basic_machine=v810-nec + os=-none + ;; + vaxv) + basic_machine=vax-dec + os=-sysv + ;; + vms) + basic_machine=vax-dec + os=-vms + ;; + vpp*|vx|vx-*) + basic_machine=f301-fujitsu + ;; + vxworks960) + basic_machine=i960-wrs + os=-vxworks + ;; + vxworks68) + basic_machine=m68k-wrs + os=-vxworks + ;; + vxworks29k) + basic_machine=a29k-wrs + os=-vxworks + ;; + w65*) + basic_machine=w65-wdc + os=-none + ;; + w89k-*) + basic_machine=hppa1.1-winbond + os=-proelf + ;; + xps | xps100) + basic_machine=xps100-honeywell + ;; + ymp) + basic_machine=ymp-cray + os=-unicos + ;; + z8k-*-coff) + basic_machine=z8k-unknown + os=-sim + ;; + none) + basic_machine=none-none + os=-none + ;; + +# Here we handle the default manufacturer of certain CPU types. It is in +# some cases the only manufacturer, in others, it is the most popular. + w89k) + basic_machine=hppa1.1-winbond + ;; + op50n) + basic_machine=hppa1.1-oki + ;; + op60c) + basic_machine=hppa1.1-oki + ;; + romp) + basic_machine=romp-ibm + ;; + rs6000) + basic_machine=rs6000-ibm + ;; + vax) + basic_machine=vax-dec + ;; + pdp10) + # there are many clones, so DEC is not a safe bet + basic_machine=pdp10-unknown + ;; + pdp11) + basic_machine=pdp11-dec + ;; + we32k) + basic_machine=we32k-att + ;; + sh3 | sh4 | sh[34]eb | sh[1234]le | sh[23]ele) + basic_machine=sh-unknown + ;; + sh64) + basic_machine=sh64-unknown + ;; + sparc | sparcv8 | sparcv9 | sparcv9b) + basic_machine=sparc-sun + ;; + cydra) + basic_machine=cydra-cydrome + ;; + orion) + basic_machine=orion-highlevel + ;; + orion105) + basic_machine=clipper-highlevel + ;; + mac | mpw | mac-mpw) + basic_machine=m68k-apple + ;; + pmac | pmac-mpw) + basic_machine=powerpc-apple + ;; + *-unknown) + # Make sure to match an already-canonicalized machine name. + ;; + *) + echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 + exit 1 + ;; +esac + +# Here we canonicalize certain aliases for manufacturers. +case $basic_machine in + *-digital*) + basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'` + ;; + *-commodore*) + basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'` + ;; + *) + ;; +esac + +# Decode manufacturer-specific aliases for certain operating systems. + +if [ x"$os" != x"" ] +then +case $os in + # First match some system type aliases + # that might get confused with valid system types. + # -solaris* is a basic system type, with this one exception. + -solaris1 | -solaris1.*) + os=`echo $os | sed -e 's|solaris1|sunos4|'` + ;; + -solaris) + os=-solaris2 + ;; + -svr4*) + os=-sysv4 + ;; + -unixware*) + os=-sysv4.2uw + ;; + -gnu/linux*) + os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'` + ;; + # First accept the basic system types. + # The portable systems comes first. + # Each alternative MUST END IN A *, to match a version number. + # -sysv* is not here because it comes later, after sysvr4. + -gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \ + | -*vms* | -sco* | -esix* | -isc* | -aix* | -sunos | -sunos[34]*\ + | -hpux* | -unos* | -osf* | -luna* | -dgux* | -solaris* | -sym* \ + | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \ + | -aos* \ + | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \ + | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \ + | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* | -openbsd* \ + | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \ + | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \ + | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \ + | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \ + | -chorusos* | -chorusrdb* \ + | -cygwin* | -pe* | -psos* | -moss* | -proelf* | -rtems* \ + | -mingw32* | -linux-gnu* | -linux-uclibc* | -uxpv* | -beos* | -mpeix* | -udk* \ + | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \ + | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \ + | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \ + | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \ + | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \ + | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly*) + # Remember, each alternative MUST END IN *, to match a version number. + ;; + -qnx*) + case $basic_machine in + x86-* | i*86-*) + ;; + *) + os=-nto$os + ;; + esac + ;; + -nto-qnx*) + ;; + -nto*) + os=`echo $os | sed -e 's|nto|nto-qnx|'` + ;; + -sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \ + | -windows* | -osx | -abug | -netware* | -os9* | -beos* \ + | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*) + ;; + -mac*) + os=`echo $os | sed -e 's|mac|macos|'` + ;; + -linux-dietlibc) + os=-linux-dietlibc + ;; + -linux*) + os=`echo $os | sed -e 's|linux|linux-gnu|'` + ;; + -sunos5*) + os=`echo $os | sed -e 's|sunos5|solaris2|'` + ;; + -sunos6*) + os=`echo $os | sed -e 's|sunos6|solaris3|'` + ;; + -opened*) + os=-openedition + ;; + -os400*) + os=-os400 + ;; + -wince*) + os=-wince + ;; + -osfrose*) + os=-osfrose + ;; + -osf*) + os=-osf + ;; + -utek*) + os=-bsd + ;; + -dynix*) + os=-bsd + ;; + -acis*) + os=-aos + ;; + -atheos*) + os=-atheos + ;; + -syllable*) + os=-syllable + ;; + -386bsd) + os=-bsd + ;; + -ctix* | -uts*) + os=-sysv + ;; + -nova*) + os=-rtmk-nova + ;; + -ns2 ) + os=-nextstep2 + ;; + -nsk*) + os=-nsk + ;; + # Preserve the version number of sinix5. + -sinix5.*) + os=`echo $os | sed -e 's|sinix|sysv|'` + ;; + -sinix*) + os=-sysv4 + ;; + -tpf*) + os=-tpf + ;; + -triton*) + os=-sysv3 + ;; + -oss*) + os=-sysv3 + ;; + -svr4) + os=-sysv4 + ;; + -svr3) + os=-sysv3 + ;; + -sysvr4) + os=-sysv4 + ;; + # This must come after -sysvr4. + -sysv*) + ;; + -ose*) + os=-ose + ;; + -es1800*) + os=-ose + ;; + -xenix) + os=-xenix + ;; + -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) + os=-mint + ;; + -aros*) + os=-aros + ;; + -kaos*) + os=-kaos + ;; + -none) + ;; + *) + # Get rid of the `-' at the beginning of $os. + os=`echo $os | sed 's/[^-]*-//'` + echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2 + exit 1 + ;; +esac +else + +# Here we handle the default operating systems that come with various machines. +# The value should be what the vendor currently ships out the door with their +# machine or put another way, the most popular os provided with the machine. + +# Note that if you're going to try to match "-MANUFACTURER" here (say, +# "-sun"), then you have to tell the case statement up towards the top +# that MANUFACTURER isn't an operating system. Otherwise, code above +# will signal an error saying that MANUFACTURER isn't an operating +# system, and we'll never get to this point. + +case $basic_machine in + *-acorn) + os=-riscix1.2 + ;; + arm*-rebel) + os=-linux + ;; + arm*-semi) + os=-aout + ;; + c4x-* | tic4x-*) + os=-coff + ;; + # This must come before the *-dec entry. + pdp10-*) + os=-tops20 + ;; + pdp11-*) + os=-none + ;; + *-dec | vax-*) + os=-ultrix4.2 + ;; + m68*-apollo) + os=-domain + ;; + i386-sun) + os=-sunos4.0.2 + ;; + m68000-sun) + os=-sunos3 + # This also exists in the configure program, but was not the + # default. + # os=-sunos4 + ;; + m68*-cisco) + os=-aout + ;; + mips*-cisco) + os=-elf + ;; + mips*-*) + os=-elf + ;; + or32-*) + os=-coff + ;; + *-tti) # must be before sparc entry or we get the wrong os. + os=-sysv3 + ;; + sparc-* | *-sun) + os=-sunos4.1.1 + ;; + *-be) + os=-beos + ;; + *-ibm) + os=-aix + ;; + *-wec) + os=-proelf + ;; + *-winbond) + os=-proelf + ;; + *-oki) + os=-proelf + ;; + *-hp) + os=-hpux + ;; + *-hitachi) + os=-hiux + ;; + i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent) + os=-sysv + ;; + *-cbm) + os=-amigaos + ;; + *-dg) + os=-dgux + ;; + *-dolphin) + os=-sysv3 + ;; + m68k-ccur) + os=-rtu + ;; + m88k-omron*) + os=-luna + ;; + *-next ) + os=-nextstep + ;; + *-sequent) + os=-ptx + ;; + *-crds) + os=-unos + ;; + *-ns) + os=-genix + ;; + i370-*) + os=-mvs + ;; + *-next) + os=-nextstep3 + ;; + *-gould) + os=-sysv + ;; + *-highlevel) + os=-bsd + ;; + *-encore) + os=-bsd + ;; + *-sgi) + os=-irix + ;; + *-siemens) + os=-sysv4 + ;; + *-masscomp) + os=-rtu + ;; + f30[01]-fujitsu | f700-fujitsu) + os=-uxpv + ;; + *-rom68k) + os=-coff + ;; + *-*bug) + os=-coff + ;; + *-apple) + os=-macos + ;; + *-atari*) + os=-mint + ;; + *) + os=-none + ;; +esac +fi + +# Here we handle the case where we know the os, and the CPU type, but not the +# manufacturer. We pick the logical manufacturer. +vendor=unknown +case $basic_machine in + *-unknown) + case $os in + -riscix*) + vendor=acorn + ;; + -sunos*) + vendor=sun + ;; + -aix*) + vendor=ibm + ;; + -beos*) + vendor=be + ;; + -hpux*) + vendor=hp + ;; + -mpeix*) + vendor=hp + ;; + -hiux*) + vendor=hitachi + ;; + -unos*) + vendor=crds + ;; + -dgux*) + vendor=dg + ;; + -luna*) + vendor=omron + ;; + -genix*) + vendor=ns + ;; + -mvs* | -opened*) + vendor=ibm + ;; + -os400*) + vendor=ibm + ;; + -ptx*) + vendor=sequent + ;; + -tpf*) + vendor=ibm + ;; + -vxsim* | -vxworks* | -windiss*) + vendor=wrs + ;; + -aux*) + vendor=apple + ;; + -hms*) + vendor=hitachi + ;; + -mpw* | -macos*) + vendor=apple + ;; + -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) + vendor=atari + ;; + -vos*) + vendor=stratus + ;; + esac + basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"` + ;; +esac + +echo $basic_machine$os +exit 0 + +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "timestamp='" +# time-stamp-format: "%:y-%02m-%02d" +# time-stamp-end: "'" +# End: diff --git a/Code/BF2/External/speex-1.0.5/configure b/Code/BF2/External/speex-1.0.5/configure new file mode 100755 index 000000000..6836bf608 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/configure @@ -0,0 +1,20988 @@ +#! /bin/sh +# Guess values for system-dependent variables and create Makefiles. +# Generated by GNU Autoconf 2.59. +# +# Copyright (C) 2003 Free Software Foundation, Inc. +# This configure script is free software; the Free Software Foundation +# gives unlimited permission to copy, distribute and modify it. +## --------------------- ## +## M4sh Initialization. ## +## --------------------- ## + +# Be Bourne compatible +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then + emulate sh + NULLCMD=: + # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' +elif test -n "${BASH_VERSION+set}" && (set -o posix) >/dev/null 2>&1; then + set -o posix +fi +DUALCASE=1; export DUALCASE # for MKS sh + +# Support unset when possible. +if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then + as_unset=unset +else + as_unset=false +fi + + +# Work around bugs in pre-3.0 UWIN ksh. +$as_unset ENV MAIL MAILPATH +PS1='$ ' +PS2='> ' +PS4='+ ' + +# NLS nuisances. +for as_var in \ + LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \ + LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \ + LC_TELEPHONE LC_TIME +do + if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then + eval $as_var=C; export $as_var + else + $as_unset $as_var + fi +done + +# Required to use basename. +if expr a : '\(a\)' >/dev/null 2>&1; then + as_expr=expr +else + as_expr=false +fi + +if (basename /) >/dev/null 2>&1 && test "X`basename / 2>&1`" = "X/"; then + as_basename=basename +else + as_basename=false +fi + + +# Name of the executable. +as_me=`$as_basename "$0" || +$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ + X"$0" : 'X\(//\)$' \| \ + X"$0" : 'X\(/\)$' \| \ + . : '\(.\)' 2>/dev/null || +echo X/"$0" | + sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/; q; } + /^X\/\(\/\/\)$/{ s//\1/; q; } + /^X\/\(\/\).*/{ s//\1/; q; } + s/.*/./; q'` + + +# PATH needs CR, and LINENO needs CR and PATH. +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits + +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + echo "#! /bin/sh" >conf$$.sh + echo "exit 0" >>conf$$.sh + chmod +x conf$$.sh + if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then + PATH_SEPARATOR=';' + else + PATH_SEPARATOR=: + fi + rm -f conf$$.sh +fi + + + as_lineno_1=$LINENO + as_lineno_2=$LINENO + as_lineno_3=`(expr $as_lineno_1 + 1) 2>/dev/null` + test "x$as_lineno_1" != "x$as_lineno_2" && + test "x$as_lineno_3" = "x$as_lineno_2" || { + # Find who we are. Look in the path if we contain no path at all + # relative or not. + case $0 in + *[\\/]* ) as_myself=$0 ;; + *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break +done + + ;; + esac + # We did not find ourselves, most probably we were run as `sh COMMAND' + # in which case we are not to be found in the path. + if test "x$as_myself" = x; then + as_myself=$0 + fi + if test ! -f "$as_myself"; then + { echo "$as_me: error: cannot find myself; rerun with an absolute path" >&2 + { (exit 1); exit 1; }; } + fi + case $CONFIG_SHELL in + '') + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for as_base in sh bash ksh sh5; do + case $as_dir in + /*) + if ("$as_dir/$as_base" -c ' + as_lineno_1=$LINENO + as_lineno_2=$LINENO + as_lineno_3=`(expr $as_lineno_1 + 1) 2>/dev/null` + test "x$as_lineno_1" != "x$as_lineno_2" && + test "x$as_lineno_3" = "x$as_lineno_2" ') 2>/dev/null; then + $as_unset BASH_ENV || test "${BASH_ENV+set}" != set || { BASH_ENV=; export BASH_ENV; } + $as_unset ENV || test "${ENV+set}" != set || { ENV=; export ENV; } + CONFIG_SHELL=$as_dir/$as_base + export CONFIG_SHELL + exec "$CONFIG_SHELL" "$0" ${1+"$@"} + fi;; + esac + done +done +;; + esac + + # Create $as_me.lineno as a copy of $as_myself, but with $LINENO + # uniformly replaced by the line number. The first 'sed' inserts a + # line-number line before each line; the second 'sed' does the real + # work. The second script uses 'N' to pair each line-number line + # with the numbered line, and appends trailing '-' during + # substitution so that $LINENO is not a special case at line end. + # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the + # second 'sed' script. Blame Lee E. McMahon for sed's syntax. :-) + sed '=' <$as_myself | + sed ' + N + s,$,-, + : loop + s,^\(['$as_cr_digits']*\)\(.*\)[$]LINENO\([^'$as_cr_alnum'_]\),\1\2\1\3, + t loop + s,-$,, + s,^['$as_cr_digits']*\n,, + ' >$as_me.lineno && + chmod +x $as_me.lineno || + { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2 + { (exit 1); exit 1; }; } + + # Don't try to exec as it changes $[0], causing all sort of problems + # (the dirname of $[0] is not the place where we might find the + # original and so on. Autoconf is especially sensible to this). + . ./$as_me.lineno + # Exit status is that of the last command. + exit +} + + +case `echo "testing\c"; echo 1,2,3`,`echo -n testing; echo 1,2,3` in + *c*,-n*) ECHO_N= ECHO_C=' +' ECHO_T=' ' ;; + *c*,* ) ECHO_N=-n ECHO_C= ECHO_T= ;; + *) ECHO_N= ECHO_C='\c' ECHO_T= ;; +esac + +if expr a : '\(a\)' >/dev/null 2>&1; then + as_expr=expr +else + as_expr=false +fi + +rm -f conf$$ conf$$.exe conf$$.file +echo >conf$$.file +if ln -s conf$$.file conf$$ 2>/dev/null; then + # We could just check for DJGPP; but this test a) works b) is more generic + # and c) will remain valid once DJGPP supports symlinks (DJGPP 2.04). + if test -f conf$$.exe; then + # Don't use ln at all; we don't have any links + as_ln_s='cp -p' + else + as_ln_s='ln -s' + fi +elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln +else + as_ln_s='cp -p' +fi +rm -f conf$$ conf$$.exe conf$$.file + +if mkdir -p . 2>/dev/null; then + as_mkdir_p=: +else + test -d ./-p && rmdir ./-p + as_mkdir_p=false +fi + +as_executable_p="test -f" + +# Sed expression to map a string onto a valid CPP name. +as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" + +# Sed expression to map a string onto a valid variable name. +as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" + + +# IFS +# We need space, tab and new line, in precisely that order. +as_nl=' +' +IFS=" $as_nl" + +# CDPATH. +$as_unset CDPATH + + + +# Check that we are running under the correct shell. +SHELL=${CONFIG_SHELL-/bin/sh} + +case X$ECHO in +X*--fallback-echo) + # Remove one level of quotation (which was required for Make). + ECHO=`echo "$ECHO" | sed 's,\\\\\$\\$0,'$0','` + ;; +esac + +echo=${ECHO-echo} +if test "X$1" = X--no-reexec; then + # Discard the --no-reexec flag, and continue. + shift +elif test "X$1" = X--fallback-echo; then + # Avoid inline document here, it may be left over + : +elif test "X`($echo '\t') 2>/dev/null`" = 'X\t' ; then + # Yippee, $echo works! + : +else + # Restart under the correct shell. + exec $SHELL "$0" --no-reexec ${1+"$@"} +fi + +if test "X$1" = X--fallback-echo; then + # used as fallback echo + shift + cat </dev/null && + echo_test_string="`eval $cmd`" && + (test "X$echo_test_string" = "X$echo_test_string") 2>/dev/null + then + break + fi + done +fi + +if test "X`($echo '\t') 2>/dev/null`" = 'X\t' && + echo_testing_string=`($echo "$echo_test_string") 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + : +else + # The Solaris, AIX, and Digital Unix default echo programs unquote + # backslashes. This makes it impossible to quote backslashes using + # echo "$something" | sed 's/\\/\\\\/g' + # + # So, first we look for a working echo in the user's PATH. + + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR + for dir in $PATH /usr/ucb; do + IFS="$lt_save_ifs" + if (test -f $dir/echo || test -f $dir/echo$ac_exeext) && + test "X`($dir/echo '\t') 2>/dev/null`" = 'X\t' && + echo_testing_string=`($dir/echo "$echo_test_string") 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + echo="$dir/echo" + break + fi + done + IFS="$lt_save_ifs" + + if test "X$echo" = Xecho; then + # We didn't find a better echo, so look for alternatives. + if test "X`(print -r '\t') 2>/dev/null`" = 'X\t' && + echo_testing_string=`(print -r "$echo_test_string") 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + # This shell has a builtin print -r that does the trick. + echo='print -r' + elif (test -f /bin/ksh || test -f /bin/ksh$ac_exeext) && + test "X$CONFIG_SHELL" != X/bin/ksh; then + # If we have ksh, try running configure again with it. + ORIGINAL_CONFIG_SHELL=${CONFIG_SHELL-/bin/sh} + export ORIGINAL_CONFIG_SHELL + CONFIG_SHELL=/bin/ksh + export CONFIG_SHELL + exec $CONFIG_SHELL "$0" --no-reexec ${1+"$@"} + else + # Try using printf. + echo='printf %s\n' + if test "X`($echo '\t') 2>/dev/null`" = 'X\t' && + echo_testing_string=`($echo "$echo_test_string") 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + # Cool, printf works + : + elif echo_testing_string=`($ORIGINAL_CONFIG_SHELL "$0" --fallback-echo '\t') 2>/dev/null` && + test "X$echo_testing_string" = 'X\t' && + echo_testing_string=`($ORIGINAL_CONFIG_SHELL "$0" --fallback-echo "$echo_test_string") 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + CONFIG_SHELL=$ORIGINAL_CONFIG_SHELL + export CONFIG_SHELL + SHELL="$CONFIG_SHELL" + export SHELL + echo="$CONFIG_SHELL $0 --fallback-echo" + elif echo_testing_string=`($CONFIG_SHELL "$0" --fallback-echo '\t') 2>/dev/null` && + test "X$echo_testing_string" = 'X\t' && + echo_testing_string=`($CONFIG_SHELL "$0" --fallback-echo "$echo_test_string") 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + echo="$CONFIG_SHELL $0 --fallback-echo" + else + # maybe with a smaller string... + prev=: + + for cmd in 'echo test' 'sed 2q "$0"' 'sed 10q "$0"' 'sed 20q "$0"' 'sed 50q "$0"'; do + if (test "X$echo_test_string" = "X`eval $cmd`") 2>/dev/null + then + break + fi + prev="$cmd" + done + + if test "$prev" != 'sed 50q "$0"'; then + echo_test_string=`eval $prev` + export echo_test_string + exec ${ORIGINAL_CONFIG_SHELL-${CONFIG_SHELL-/bin/sh}} "$0" ${1+"$@"} + else + # Oops. We lost completely, so just stick with echo. + echo=echo + fi + fi + fi + fi +fi +fi + +# Copy echo and quote the copy suitably for passing to libtool from +# the Makefile, instead of quoting the original, which is used later. +ECHO=$echo +if test "X$ECHO" = "X$CONFIG_SHELL $0 --fallback-echo"; then + ECHO="$CONFIG_SHELL \\\$\$0 --fallback-echo" +fi + + + + +tagnames=${tagnames+${tagnames},}CXX + +tagnames=${tagnames+${tagnames},}F77 + +# Name of the host. +# hostname on some systems (SVR3.2, Linux) returns a bogus exit status, +# so uname gets run too. +ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` + +exec 6>&1 + +# +# Initializations. +# +ac_default_prefix=/usr/local +ac_config_libobj_dir=. +cross_compiling=no +subdirs= +MFLAGS= +MAKEFLAGS= +SHELL=${CONFIG_SHELL-/bin/sh} + +# Maximum number of lines to put in a shell here document. +# This variable seems obsolete. It should probably be removed, and +# only ac_max_sed_lines should be used. +: ${ac_max_here_lines=38} + +# Identity of this package. +PACKAGE_NAME= +PACKAGE_TARNAME= +PACKAGE_VERSION= +PACKAGE_STRING= +PACKAGE_BUGREPORT= + +ac_unique_file="libspeex/nb_celp.c" +# Factoring default headers for most tests. +ac_includes_default="\ +#include +#if HAVE_SYS_TYPES_H +# include +#endif +#if HAVE_SYS_STAT_H +# include +#endif +#if STDC_HEADERS +# include +# include +#else +# if HAVE_STDLIB_H +# include +# endif +#endif +#if HAVE_STRING_H +# if !STDC_HEADERS && HAVE_MEMORY_H +# include +# endif +# include +#endif +#if HAVE_STRINGS_H +# include +#endif +#if HAVE_INTTYPES_H +# include +#else +# if HAVE_STDINT_H +# include +# endif +#endif +#if HAVE_UNISTD_H +# include +#endif" + +ac_subst_vars='SHELL PATH_SEPARATOR PACKAGE_NAME PACKAGE_TARNAME PACKAGE_VERSION PACKAGE_STRING PACKAGE_BUGREPORT exec_prefix prefix program_transform_name bindir sbindir libexecdir datadir sysconfdir sharedstatedir localstatedir libdir includedir oldincludedir infodir mandir build_alias host_alias target_alias DEFS ECHO_C ECHO_N ECHO_T LIBS SPEEX_LT_CURRENT SPEEX_LT_REVISION SPEEX_LT_AGE SPEEX_VERSION INSTALL_PROGRAM INSTALL_SCRIPT INSTALL_DATA CYGPATH_W PACKAGE VERSION ACLOCAL AUTOCONF AUTOMAKE AUTOHEADER MAKEINFO AMTAR install_sh STRIP ac_ct_STRIP INSTALL_STRIP_PROGRAM mkdir_p AWK SET_MAKE am__leading_dot MAINTAINER_MODE_TRUE MAINTAINER_MODE_FALSE MAINT build build_cpu build_vendor build_os host host_cpu host_vendor host_os CC CFLAGS LDFLAGS CPPFLAGS ac_ct_CC EXEEXT OBJEXT DEPDIR am__include am__quote AMDEP_TRUE AMDEP_FALSE AMDEPBACKSLASH CCDEPMODE am__fastdepCC_TRUE am__fastdepCC_FALSE EGREP LN_S ECHO AR ac_ct_AR RANLIB ac_ct_RANLIB CPP CXX CXXFLAGS ac_ct_CXX CXXDEPMODE am__fastdepCXX_TRUE am__fastdepCXX_FALSE CXXCPP F77 FFLAGS ac_ct_F77 LIBTOOL OGG_LIBS OGG_INCLUDES OGG_LDFLAGS src LIBOBJS LTLIBOBJS' +ac_subst_files='' + +# Initialize some variables set by options. +ac_init_help= +ac_init_version=false +# The variables have the same names as the options, with +# dashes changed to underlines. +cache_file=/dev/null +exec_prefix=NONE +no_create= +no_recursion= +prefix=NONE +program_prefix=NONE +program_suffix=NONE +program_transform_name=s,x,x, +silent= +site= +srcdir= +verbose= +x_includes=NONE +x_libraries=NONE + +# Installation directory options. +# These are left unexpanded so users can "make install exec_prefix=/foo" +# and all the variables that are supposed to be based on exec_prefix +# by default will actually change. +# Use braces instead of parens because sh, perl, etc. also accept them. +bindir='${exec_prefix}/bin' +sbindir='${exec_prefix}/sbin' +libexecdir='${exec_prefix}/libexec' +datadir='${prefix}/share' +sysconfdir='${prefix}/etc' +sharedstatedir='${prefix}/com' +localstatedir='${prefix}/var' +libdir='${exec_prefix}/lib' +includedir='${prefix}/include' +oldincludedir='/usr/include' +infodir='${prefix}/info' +mandir='${prefix}/man' + +ac_prev= +for ac_option +do + # If the previous option needs an argument, assign it. + if test -n "$ac_prev"; then + eval "$ac_prev=\$ac_option" + ac_prev= + continue + fi + + ac_optarg=`expr "x$ac_option" : 'x[^=]*=\(.*\)'` + + # Accept the important Cygnus configure options, so we can diagnose typos. + + case $ac_option in + + -bindir | --bindir | --bindi | --bind | --bin | --bi) + ac_prev=bindir ;; + -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*) + bindir=$ac_optarg ;; + + -build | --build | --buil | --bui | --bu) + ac_prev=build_alias ;; + -build=* | --build=* | --buil=* | --bui=* | --bu=*) + build_alias=$ac_optarg ;; + + -cache-file | --cache-file | --cache-fil | --cache-fi \ + | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c) + ac_prev=cache_file ;; + -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \ + | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*) + cache_file=$ac_optarg ;; + + --config-cache | -C) + cache_file=config.cache ;; + + -datadir | --datadir | --datadi | --datad | --data | --dat | --da) + ac_prev=datadir ;; + -datadir=* | --datadir=* | --datadi=* | --datad=* | --data=* | --dat=* \ + | --da=*) + datadir=$ac_optarg ;; + + -disable-* | --disable-*) + ac_feature=`expr "x$ac_option" : 'x-*disable-\(.*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_feature" : ".*[^-_$as_cr_alnum]" >/dev/null && + { echo "$as_me: error: invalid feature name: $ac_feature" >&2 + { (exit 1); exit 1; }; } + ac_feature=`echo $ac_feature | sed 's/-/_/g'` + eval "enable_$ac_feature=no" ;; + + -enable-* | --enable-*) + ac_feature=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_feature" : ".*[^-_$as_cr_alnum]" >/dev/null && + { echo "$as_me: error: invalid feature name: $ac_feature" >&2 + { (exit 1); exit 1; }; } + ac_feature=`echo $ac_feature | sed 's/-/_/g'` + case $ac_option in + *=*) ac_optarg=`echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"`;; + *) ac_optarg=yes ;; + esac + eval "enable_$ac_feature='$ac_optarg'" ;; + + -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ + | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ + | --exec | --exe | --ex) + ac_prev=exec_prefix ;; + -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \ + | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \ + | --exec=* | --exe=* | --ex=*) + exec_prefix=$ac_optarg ;; + + -gas | --gas | --ga | --g) + # Obsolete; use --with-gas. + with_gas=yes ;; + + -help | --help | --hel | --he | -h) + ac_init_help=long ;; + -help=r* | --help=r* | --hel=r* | --he=r* | -hr*) + ac_init_help=recursive ;; + -help=s* | --help=s* | --hel=s* | --he=s* | -hs*) + ac_init_help=short ;; + + -host | --host | --hos | --ho) + ac_prev=host_alias ;; + -host=* | --host=* | --hos=* | --ho=*) + host_alias=$ac_optarg ;; + + -includedir | --includedir | --includedi | --included | --include \ + | --includ | --inclu | --incl | --inc) + ac_prev=includedir ;; + -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \ + | --includ=* | --inclu=* | --incl=* | --inc=*) + includedir=$ac_optarg ;; + + -infodir | --infodir | --infodi | --infod | --info | --inf) + ac_prev=infodir ;; + -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*) + infodir=$ac_optarg ;; + + -libdir | --libdir | --libdi | --libd) + ac_prev=libdir ;; + -libdir=* | --libdir=* | --libdi=* | --libd=*) + libdir=$ac_optarg ;; + + -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \ + | --libexe | --libex | --libe) + ac_prev=libexecdir ;; + -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \ + | --libexe=* | --libex=* | --libe=*) + libexecdir=$ac_optarg ;; + + -localstatedir | --localstatedir | --localstatedi | --localstated \ + | --localstate | --localstat | --localsta | --localst \ + | --locals | --local | --loca | --loc | --lo) + ac_prev=localstatedir ;; + -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \ + | --localstate=* | --localstat=* | --localsta=* | --localst=* \ + | --locals=* | --local=* | --loca=* | --loc=* | --lo=*) + localstatedir=$ac_optarg ;; + + -mandir | --mandir | --mandi | --mand | --man | --ma | --m) + ac_prev=mandir ;; + -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*) + mandir=$ac_optarg ;; + + -nfp | --nfp | --nf) + # Obsolete; use --without-fp. + with_fp=no ;; + + -no-create | --no-create | --no-creat | --no-crea | --no-cre \ + | --no-cr | --no-c | -n) + no_create=yes ;; + + -no-recursion | --no-recursion | --no-recursio | --no-recursi \ + | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) + no_recursion=yes ;; + + -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \ + | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \ + | --oldin | --oldi | --old | --ol | --o) + ac_prev=oldincludedir ;; + -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \ + | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \ + | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*) + oldincludedir=$ac_optarg ;; + + -prefix | --prefix | --prefi | --pref | --pre | --pr | --p) + ac_prev=prefix ;; + -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*) + prefix=$ac_optarg ;; + + -program-prefix | --program-prefix | --program-prefi | --program-pref \ + | --program-pre | --program-pr | --program-p) + ac_prev=program_prefix ;; + -program-prefix=* | --program-prefix=* | --program-prefi=* \ + | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*) + program_prefix=$ac_optarg ;; + + -program-suffix | --program-suffix | --program-suffi | --program-suff \ + | --program-suf | --program-su | --program-s) + ac_prev=program_suffix ;; + -program-suffix=* | --program-suffix=* | --program-suffi=* \ + | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*) + program_suffix=$ac_optarg ;; + + -program-transform-name | --program-transform-name \ + | --program-transform-nam | --program-transform-na \ + | --program-transform-n | --program-transform- \ + | --program-transform | --program-transfor \ + | --program-transfo | --program-transf \ + | --program-trans | --program-tran \ + | --progr-tra | --program-tr | --program-t) + ac_prev=program_transform_name ;; + -program-transform-name=* | --program-transform-name=* \ + | --program-transform-nam=* | --program-transform-na=* \ + | --program-transform-n=* | --program-transform-=* \ + | --program-transform=* | --program-transfor=* \ + | --program-transfo=* | --program-transf=* \ + | --program-trans=* | --program-tran=* \ + | --progr-tra=* | --program-tr=* | --program-t=*) + program_transform_name=$ac_optarg ;; + + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil) + silent=yes ;; + + -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) + ac_prev=sbindir ;; + -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ + | --sbi=* | --sb=*) + sbindir=$ac_optarg ;; + + -sharedstatedir | --sharedstatedir | --sharedstatedi \ + | --sharedstated | --sharedstate | --sharedstat | --sharedsta \ + | --sharedst | --shareds | --shared | --share | --shar \ + | --sha | --sh) + ac_prev=sharedstatedir ;; + -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \ + | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \ + | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \ + | --sha=* | --sh=*) + sharedstatedir=$ac_optarg ;; + + -site | --site | --sit) + ac_prev=site ;; + -site=* | --site=* | --sit=*) + site=$ac_optarg ;; + + -srcdir | --srcdir | --srcdi | --srcd | --src | --sr) + ac_prev=srcdir ;; + -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*) + srcdir=$ac_optarg ;; + + -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \ + | --syscon | --sysco | --sysc | --sys | --sy) + ac_prev=sysconfdir ;; + -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \ + | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*) + sysconfdir=$ac_optarg ;; + + -target | --target | --targe | --targ | --tar | --ta | --t) + ac_prev=target_alias ;; + -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*) + target_alias=$ac_optarg ;; + + -v | -verbose | --verbose | --verbos | --verbo | --verb) + verbose=yes ;; + + -version | --version | --versio | --versi | --vers | -V) + ac_init_version=: ;; + + -with-* | --with-*) + ac_package=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_package" : ".*[^-_$as_cr_alnum]" >/dev/null && + { echo "$as_me: error: invalid package name: $ac_package" >&2 + { (exit 1); exit 1; }; } + ac_package=`echo $ac_package| sed 's/-/_/g'` + case $ac_option in + *=*) ac_optarg=`echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"`;; + *) ac_optarg=yes ;; + esac + eval "with_$ac_package='$ac_optarg'" ;; + + -without-* | --without-*) + ac_package=`expr "x$ac_option" : 'x-*without-\(.*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_package" : ".*[^-_$as_cr_alnum]" >/dev/null && + { echo "$as_me: error: invalid package name: $ac_package" >&2 + { (exit 1); exit 1; }; } + ac_package=`echo $ac_package | sed 's/-/_/g'` + eval "with_$ac_package=no" ;; + + --x) + # Obsolete; use --with-x. + with_x=yes ;; + + -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \ + | --x-incl | --x-inc | --x-in | --x-i) + ac_prev=x_includes ;; + -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \ + | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*) + x_includes=$ac_optarg ;; + + -x-libraries | --x-libraries | --x-librarie | --x-librari \ + | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l) + ac_prev=x_libraries ;; + -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \ + | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) + x_libraries=$ac_optarg ;; + + -*) { echo "$as_me: error: unrecognized option: $ac_option +Try \`$0 --help' for more information." >&2 + { (exit 1); exit 1; }; } + ;; + + *=*) + ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` + # Reject names that are not valid shell variable names. + expr "x$ac_envvar" : ".*[^_$as_cr_alnum]" >/dev/null && + { echo "$as_me: error: invalid variable name: $ac_envvar" >&2 + { (exit 1); exit 1; }; } + ac_optarg=`echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` + eval "$ac_envvar='$ac_optarg'" + export $ac_envvar ;; + + *) + # FIXME: should be removed in autoconf 3.0. + echo "$as_me: WARNING: you should use --build, --host, --target" >&2 + expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && + echo "$as_me: WARNING: invalid host type: $ac_option" >&2 + : ${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option} + ;; + + esac +done + +if test -n "$ac_prev"; then + ac_option=--`echo $ac_prev | sed 's/_/-/g'` + { echo "$as_me: error: missing argument to $ac_option" >&2 + { (exit 1); exit 1; }; } +fi + +# Be sure to have absolute paths. +for ac_var in exec_prefix prefix +do + eval ac_val=$`echo $ac_var` + case $ac_val in + [\\/$]* | ?:[\\/]* | NONE | '' ) ;; + *) { echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2 + { (exit 1); exit 1; }; };; + esac +done + +# Be sure to have absolute paths. +for ac_var in bindir sbindir libexecdir datadir sysconfdir sharedstatedir \ + localstatedir libdir includedir oldincludedir infodir mandir +do + eval ac_val=$`echo $ac_var` + case $ac_val in + [\\/$]* | ?:[\\/]* ) ;; + *) { echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2 + { (exit 1); exit 1; }; };; + esac +done + +# There might be people who depend on the old broken behavior: `$host' +# used to hold the argument of --host etc. +# FIXME: To remove some day. +build=$build_alias +host=$host_alias +target=$target_alias + +# FIXME: To remove some day. +if test "x$host_alias" != x; then + if test "x$build_alias" = x; then + cross_compiling=maybe + echo "$as_me: WARNING: If you wanted to set the --build type, don't use --host. + If a cross compiler is detected then cross compile mode will be used." >&2 + elif test "x$build_alias" != "x$host_alias"; then + cross_compiling=yes + fi +fi + +ac_tool_prefix= +test -n "$host_alias" && ac_tool_prefix=$host_alias- + +test "$silent" = yes && exec 6>/dev/null + + +# Find the source files, if location was not specified. +if test -z "$srcdir"; then + ac_srcdir_defaulted=yes + # Try the directory containing this script, then its parent. + ac_confdir=`(dirname "$0") 2>/dev/null || +$as_expr X"$0" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$0" : 'X\(//\)[^/]' \| \ + X"$0" : 'X\(//\)$' \| \ + X"$0" : 'X\(/\)' \| \ + . : '\(.\)' 2>/dev/null || +echo X"$0" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; } + /^X\(\/\/\)[^/].*/{ s//\1/; q; } + /^X\(\/\/\)$/{ s//\1/; q; } + /^X\(\/\).*/{ s//\1/; q; } + s/.*/./; q'` + srcdir=$ac_confdir + if test ! -r $srcdir/$ac_unique_file; then + srcdir=.. + fi +else + ac_srcdir_defaulted=no +fi +if test ! -r $srcdir/$ac_unique_file; then + if test "$ac_srcdir_defaulted" = yes; then + { echo "$as_me: error: cannot find sources ($ac_unique_file) in $ac_confdir or .." >&2 + { (exit 1); exit 1; }; } + else + { echo "$as_me: error: cannot find sources ($ac_unique_file) in $srcdir" >&2 + { (exit 1); exit 1; }; } + fi +fi +(cd $srcdir && test -r ./$ac_unique_file) 2>/dev/null || + { echo "$as_me: error: sources are in $srcdir, but \`cd $srcdir' does not work" >&2 + { (exit 1); exit 1; }; } +srcdir=`echo "$srcdir" | sed 's%\([^\\/]\)[\\/]*$%\1%'` +ac_env_build_alias_set=${build_alias+set} +ac_env_build_alias_value=$build_alias +ac_cv_env_build_alias_set=${build_alias+set} +ac_cv_env_build_alias_value=$build_alias +ac_env_host_alias_set=${host_alias+set} +ac_env_host_alias_value=$host_alias +ac_cv_env_host_alias_set=${host_alias+set} +ac_cv_env_host_alias_value=$host_alias +ac_env_target_alias_set=${target_alias+set} +ac_env_target_alias_value=$target_alias +ac_cv_env_target_alias_set=${target_alias+set} +ac_cv_env_target_alias_value=$target_alias +ac_env_CC_set=${CC+set} +ac_env_CC_value=$CC +ac_cv_env_CC_set=${CC+set} +ac_cv_env_CC_value=$CC +ac_env_CFLAGS_set=${CFLAGS+set} +ac_env_CFLAGS_value=$CFLAGS +ac_cv_env_CFLAGS_set=${CFLAGS+set} +ac_cv_env_CFLAGS_value=$CFLAGS +ac_env_LDFLAGS_set=${LDFLAGS+set} +ac_env_LDFLAGS_value=$LDFLAGS +ac_cv_env_LDFLAGS_set=${LDFLAGS+set} +ac_cv_env_LDFLAGS_value=$LDFLAGS +ac_env_CPPFLAGS_set=${CPPFLAGS+set} +ac_env_CPPFLAGS_value=$CPPFLAGS +ac_cv_env_CPPFLAGS_set=${CPPFLAGS+set} +ac_cv_env_CPPFLAGS_value=$CPPFLAGS +ac_env_CPP_set=${CPP+set} +ac_env_CPP_value=$CPP +ac_cv_env_CPP_set=${CPP+set} +ac_cv_env_CPP_value=$CPP +ac_env_CXX_set=${CXX+set} +ac_env_CXX_value=$CXX +ac_cv_env_CXX_set=${CXX+set} +ac_cv_env_CXX_value=$CXX +ac_env_CXXFLAGS_set=${CXXFLAGS+set} +ac_env_CXXFLAGS_value=$CXXFLAGS +ac_cv_env_CXXFLAGS_set=${CXXFLAGS+set} +ac_cv_env_CXXFLAGS_value=$CXXFLAGS +ac_env_CXXCPP_set=${CXXCPP+set} +ac_env_CXXCPP_value=$CXXCPP +ac_cv_env_CXXCPP_set=${CXXCPP+set} +ac_cv_env_CXXCPP_value=$CXXCPP +ac_env_F77_set=${F77+set} +ac_env_F77_value=$F77 +ac_cv_env_F77_set=${F77+set} +ac_cv_env_F77_value=$F77 +ac_env_FFLAGS_set=${FFLAGS+set} +ac_env_FFLAGS_value=$FFLAGS +ac_cv_env_FFLAGS_set=${FFLAGS+set} +ac_cv_env_FFLAGS_value=$FFLAGS + +# +# Report the --help message. +# +if test "$ac_init_help" = "long"; then + # Omit some internal or obsolete options to make the list less imposing. + # This message is too long to be a string in the A/UX 3.1 sh. + cat <<_ACEOF +\`configure' configures this package to adapt to many kinds of systems. + +Usage: $0 [OPTION]... [VAR=VALUE]... + +To assign environment variables (e.g., CC, CFLAGS...), specify them as +VAR=VALUE. See below for descriptions of some of the useful variables. + +Defaults for the options are specified in brackets. + +Configuration: + -h, --help display this help and exit + --help=short display options specific to this package + --help=recursive display the short help of all the included packages + -V, --version display version information and exit + -q, --quiet, --silent do not print \`checking...' messages + --cache-file=FILE cache test results in FILE [disabled] + -C, --config-cache alias for \`--cache-file=config.cache' + -n, --no-create do not create output files + --srcdir=DIR find the sources in DIR [configure dir or \`..'] + +_ACEOF + + cat <<_ACEOF +Installation directories: + --prefix=PREFIX install architecture-independent files in PREFIX + [$ac_default_prefix] + --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX + [PREFIX] + +By default, \`make install' will install all the files in +\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify +an installation prefix other than \`$ac_default_prefix' using \`--prefix', +for instance \`--prefix=\$HOME'. + +For better control, use the options below. + +Fine tuning of the installation directories: + --bindir=DIR user executables [EPREFIX/bin] + --sbindir=DIR system admin executables [EPREFIX/sbin] + --libexecdir=DIR program executables [EPREFIX/libexec] + --datadir=DIR read-only architecture-independent data [PREFIX/share] + --sysconfdir=DIR read-only single-machine data [PREFIX/etc] + --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] + --localstatedir=DIR modifiable single-machine data [PREFIX/var] + --libdir=DIR object code libraries [EPREFIX/lib] + --includedir=DIR C header files [PREFIX/include] + --oldincludedir=DIR C header files for non-gcc [/usr/include] + --infodir=DIR info documentation [PREFIX/info] + --mandir=DIR man documentation [PREFIX/man] +_ACEOF + + cat <<\_ACEOF + +Program names: + --program-prefix=PREFIX prepend PREFIX to installed program names + --program-suffix=SUFFIX append SUFFIX to installed program names + --program-transform-name=PROGRAM run sed PROGRAM on installed program names + +System types: + --build=BUILD configure for building on BUILD [guessed] + --host=HOST cross-compile to build programs to run on HOST [BUILD] +_ACEOF +fi + +if test -n "$ac_init_help"; then + + cat <<\_ACEOF + +Optional Features: + --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) + --enable-FEATURE[=ARG] include FEATURE [ARG=yes] + --enable-maintainer-mode enable make rules and dependencies not useful + (and sometimes confusing) to the casual installer + --enable-shared[=PKGS] + build shared libraries [default=yes] + --enable-static[=PKGS] + build static libraries [default=yes] + --enable-fast-install[=PKGS] + optimize for fast installation [default=yes] + --disable-dependency-tracking speeds up one-time build + --enable-dependency-tracking do not reject slow dependency extractors + --disable-libtool-lock avoid locking (might break parallel builds) + --enable-ogg=yes/no Turn on or off the use of ogg +libraries default=yes + --enable-sse enable SSE support + +Optional Packages: + --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] + --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) + --with-gnu-ld assume the C compiler uses GNU ld [default=no] + --with-pic try to use only PIC/non-PIC objects [default=use + both] + --with-tags[=TAGS] + include additional configurations [automatic] + --with-ogg-dir=DIR where the root of OGG is installed + --with-ogg-includes=DIR where the OGG includes are. + --with-ogg-libraries=DIR where the OGG library is installed. + +Some influential environment variables: + CC C compiler command + CFLAGS C compiler flags + LDFLAGS linker flags, e.g. -L if you have libraries in a + nonstandard directory + CPPFLAGS C/C++ preprocessor flags, e.g. -I if you have + headers in a nonstandard directory + CPP C preprocessor + CXX C++ compiler command + CXXFLAGS C++ compiler flags + CXXCPP C++ preprocessor + F77 Fortran 77 compiler command + FFLAGS Fortran 77 compiler flags + +Use these variables to override the choices made by `configure' or to help +it to find libraries and programs with nonstandard names/locations. + +_ACEOF +fi + +if test "$ac_init_help" = "recursive"; then + # If there are subdirs, report their specific --help. + ac_popdir=`pwd` + for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue + test -d $ac_dir || continue + ac_builddir=. + +if test "$ac_dir" != .; then + ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'` + # A "../" for each directory in $ac_dir_suffix. + ac_top_builddir=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,../,g'` +else + ac_dir_suffix= ac_top_builddir= +fi + +case $srcdir in + .) # No --srcdir option. We are building in place. + ac_srcdir=. + if test -z "$ac_top_builddir"; then + ac_top_srcdir=. + else + ac_top_srcdir=`echo $ac_top_builddir | sed 's,/$,,'` + fi ;; + [\\/]* | ?:[\\/]* ) # Absolute path. + ac_srcdir=$srcdir$ac_dir_suffix; + ac_top_srcdir=$srcdir ;; + *) # Relative path. + ac_srcdir=$ac_top_builddir$srcdir$ac_dir_suffix + ac_top_srcdir=$ac_top_builddir$srcdir ;; +esac + +# Do not use `cd foo && pwd` to compute absolute paths, because +# the directories may not exist. +case `pwd` in +.) ac_abs_builddir="$ac_dir";; +*) + case "$ac_dir" in + .) ac_abs_builddir=`pwd`;; + [\\/]* | ?:[\\/]* ) ac_abs_builddir="$ac_dir";; + *) ac_abs_builddir=`pwd`/"$ac_dir";; + esac;; +esac +case $ac_abs_builddir in +.) ac_abs_top_builddir=${ac_top_builddir}.;; +*) + case ${ac_top_builddir}. in + .) ac_abs_top_builddir=$ac_abs_builddir;; + [\\/]* | ?:[\\/]* ) ac_abs_top_builddir=${ac_top_builddir}.;; + *) ac_abs_top_builddir=$ac_abs_builddir/${ac_top_builddir}.;; + esac;; +esac +case $ac_abs_builddir in +.) ac_abs_srcdir=$ac_srcdir;; +*) + case $ac_srcdir in + .) ac_abs_srcdir=$ac_abs_builddir;; + [\\/]* | ?:[\\/]* ) ac_abs_srcdir=$ac_srcdir;; + *) ac_abs_srcdir=$ac_abs_builddir/$ac_srcdir;; + esac;; +esac +case $ac_abs_builddir in +.) ac_abs_top_srcdir=$ac_top_srcdir;; +*) + case $ac_top_srcdir in + .) ac_abs_top_srcdir=$ac_abs_builddir;; + [\\/]* | ?:[\\/]* ) ac_abs_top_srcdir=$ac_top_srcdir;; + *) ac_abs_top_srcdir=$ac_abs_builddir/$ac_top_srcdir;; + esac;; +esac + + cd $ac_dir + # Check for guested configure; otherwise get Cygnus style configure. + if test -f $ac_srcdir/configure.gnu; then + echo + $SHELL $ac_srcdir/configure.gnu --help=recursive + elif test -f $ac_srcdir/configure; then + echo + $SHELL $ac_srcdir/configure --help=recursive + elif test -f $ac_srcdir/configure.ac || + test -f $ac_srcdir/configure.in; then + echo + $ac_configure --help + else + echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 + fi + cd "$ac_popdir" + done +fi + +test -n "$ac_init_help" && exit 0 +if $ac_init_version; then + cat <<\_ACEOF + +Copyright (C) 2003 Free Software Foundation, Inc. +This configure script is free software; the Free Software Foundation +gives unlimited permission to copy, distribute and modify it. +_ACEOF + exit 0 +fi +exec 5>config.log +cat >&5 <<_ACEOF +This file contains any messages produced by compilers while +running configure, to aid debugging if configure makes a mistake. + +It was created by $as_me, which was +generated by GNU Autoconf 2.59. Invocation command line was + + $ $0 $@ + +_ACEOF +{ +cat <<_ASUNAME +## --------- ## +## Platform. ## +## --------- ## + +hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` +uname -m = `(uname -m) 2>/dev/null || echo unknown` +uname -r = `(uname -r) 2>/dev/null || echo unknown` +uname -s = `(uname -s) 2>/dev/null || echo unknown` +uname -v = `(uname -v) 2>/dev/null || echo unknown` + +/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` +/bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` + +/bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` +/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` +/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` +hostinfo = `(hostinfo) 2>/dev/null || echo unknown` +/bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` +/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` +/bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` + +_ASUNAME + +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + echo "PATH: $as_dir" +done + +} >&5 + +cat >&5 <<_ACEOF + + +## ----------- ## +## Core tests. ## +## ----------- ## + +_ACEOF + + +# Keep a trace of the command line. +# Strip out --no-create and --no-recursion so they do not pile up. +# Strip out --silent because we don't want to record it for future runs. +# Also quote any args containing shell meta-characters. +# Make two passes to allow for proper duplicate-argument suppression. +ac_configure_args= +ac_configure_args0= +ac_configure_args1= +ac_sep= +ac_must_keep_next=false +for ac_pass in 1 2 +do + for ac_arg + do + case $ac_arg in + -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil) + continue ;; + *" "*|*" "*|*[\[\]\~\#\$\^\&\*\(\)\{\}\\\|\;\<\>\?\"\']*) + ac_arg=`echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + case $ac_pass in + 1) ac_configure_args0="$ac_configure_args0 '$ac_arg'" ;; + 2) + ac_configure_args1="$ac_configure_args1 '$ac_arg'" + if test $ac_must_keep_next = true; then + ac_must_keep_next=false # Got value, back to normal. + else + case $ac_arg in + *=* | --config-cache | -C | -disable-* | --disable-* \ + | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ + | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ + | -with-* | --with-* | -without-* | --without-* | --x) + case "$ac_configure_args0 " in + "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; + esac + ;; + -* ) ac_must_keep_next=true ;; + esac + fi + ac_configure_args="$ac_configure_args$ac_sep'$ac_arg'" + # Get rid of the leading space. + ac_sep=" " + ;; + esac + done +done +$as_unset ac_configure_args0 || test "${ac_configure_args0+set}" != set || { ac_configure_args0=; export ac_configure_args0; } +$as_unset ac_configure_args1 || test "${ac_configure_args1+set}" != set || { ac_configure_args1=; export ac_configure_args1; } + +# When interrupted or exit'd, cleanup temporary files, and complete +# config.log. We remove comments because anyway the quotes in there +# would cause problems or look ugly. +# WARNING: Be sure not to use single quotes in there, as some shells, +# such as our DU 5.0 friend, will then `close' the trap. +trap 'exit_status=$? + # Save into config.log some information that might help in debugging. + { + echo + + cat <<\_ASBOX +## ---------------- ## +## Cache variables. ## +## ---------------- ## +_ASBOX + echo + # The following way of writing the cache mishandles newlines in values, +{ + (set) 2>&1 | + case `(ac_space='"'"' '"'"'; set | grep ac_space) 2>&1` in + *ac_space=\ *) + sed -n \ + "s/'"'"'/'"'"'\\\\'"'"''"'"'/g; + s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='"'"'\\2'"'"'/p" + ;; + *) + sed -n \ + "s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1=\\2/p" + ;; + esac; +} + echo + + cat <<\_ASBOX +## ----------------- ## +## Output variables. ## +## ----------------- ## +_ASBOX + echo + for ac_var in $ac_subst_vars + do + eval ac_val=$`echo $ac_var` + echo "$ac_var='"'"'$ac_val'"'"'" + done | sort + echo + + if test -n "$ac_subst_files"; then + cat <<\_ASBOX +## ------------- ## +## Output files. ## +## ------------- ## +_ASBOX + echo + for ac_var in $ac_subst_files + do + eval ac_val=$`echo $ac_var` + echo "$ac_var='"'"'$ac_val'"'"'" + done | sort + echo + fi + + if test -s confdefs.h; then + cat <<\_ASBOX +## ----------- ## +## confdefs.h. ## +## ----------- ## +_ASBOX + echo + sed "/^$/d" confdefs.h | sort + echo + fi + test "$ac_signal" != 0 && + echo "$as_me: caught signal $ac_signal" + echo "$as_me: exit $exit_status" + } >&5 + rm -f core *.core && + rm -rf conftest* confdefs* conf$$* $ac_clean_files && + exit $exit_status + ' 0 +for ac_signal in 1 2 13 15; do + trap 'ac_signal='$ac_signal'; { (exit 1); exit 1; }' $ac_signal +done +ac_signal=0 + +# confdefs.h avoids OS command line length limits that DEFS can exceed. +rm -rf conftest* confdefs.h +# AIX cpp loses on an empty file, so make sure it contains at least a newline. +echo >confdefs.h + +# Predefined preprocessor variables. + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_NAME "$PACKAGE_NAME" +_ACEOF + + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_TARNAME "$PACKAGE_TARNAME" +_ACEOF + + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_VERSION "$PACKAGE_VERSION" +_ACEOF + + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_STRING "$PACKAGE_STRING" +_ACEOF + + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" +_ACEOF + + +# Let the site file select an alternate cache file if it wants to. +# Prefer explicitly selected file to automatically selected ones. +if test -z "$CONFIG_SITE"; then + if test "x$prefix" != xNONE; then + CONFIG_SITE="$prefix/share/config.site $prefix/etc/config.site" + else + CONFIG_SITE="$ac_default_prefix/share/config.site $ac_default_prefix/etc/config.site" + fi +fi +for ac_site_file in $CONFIG_SITE; do + if test -r "$ac_site_file"; then + { echo "$as_me:$LINENO: loading site script $ac_site_file" >&5 +echo "$as_me: loading site script $ac_site_file" >&6;} + sed 's/^/| /' "$ac_site_file" >&5 + . "$ac_site_file" + fi +done + +if test -r "$cache_file"; then + # Some versions of bash will fail to source /dev/null (special + # files actually), so we avoid doing that. + if test -f "$cache_file"; then + { echo "$as_me:$LINENO: loading cache $cache_file" >&5 +echo "$as_me: loading cache $cache_file" >&6;} + case $cache_file in + [\\/]* | ?:[\\/]* ) . $cache_file;; + *) . ./$cache_file;; + esac + fi +else + { echo "$as_me:$LINENO: creating cache $cache_file" >&5 +echo "$as_me: creating cache $cache_file" >&6;} + >$cache_file +fi + +# Check that the precious variables saved in the cache have kept the same +# value. +ac_cache_corrupted=false +for ac_var in `(set) 2>&1 | + sed -n 's/^ac_env_\([a-zA-Z_0-9]*\)_set=.*/\1/p'`; do + eval ac_old_set=\$ac_cv_env_${ac_var}_set + eval ac_new_set=\$ac_env_${ac_var}_set + eval ac_old_val="\$ac_cv_env_${ac_var}_value" + eval ac_new_val="\$ac_env_${ac_var}_value" + case $ac_old_set,$ac_new_set in + set,) + { echo "$as_me:$LINENO: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 +echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} + ac_cache_corrupted=: ;; + ,set) + { echo "$as_me:$LINENO: error: \`$ac_var' was not set in the previous run" >&5 +echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} + ac_cache_corrupted=: ;; + ,);; + *) + if test "x$ac_old_val" != "x$ac_new_val"; then + { echo "$as_me:$LINENO: error: \`$ac_var' has changed since the previous run:" >&5 +echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} + { echo "$as_me:$LINENO: former value: $ac_old_val" >&5 +echo "$as_me: former value: $ac_old_val" >&2;} + { echo "$as_me:$LINENO: current value: $ac_new_val" >&5 +echo "$as_me: current value: $ac_new_val" >&2;} + ac_cache_corrupted=: + fi;; + esac + # Pass precious variables to config.status. + if test "$ac_new_set" = set; then + case $ac_new_val in + *" "*|*" "*|*[\[\]\~\#\$\^\&\*\(\)\{\}\\\|\;\<\>\?\"\']*) + ac_arg=$ac_var=`echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; + *) ac_arg=$ac_var=$ac_new_val ;; + esac + case " $ac_configure_args " in + *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. + *) ac_configure_args="$ac_configure_args '$ac_arg'" ;; + esac + fi +done +if $ac_cache_corrupted; then + { echo "$as_me:$LINENO: error: changes in the environment can compromise the build" >&5 +echo "$as_me: error: changes in the environment can compromise the build" >&2;} + { { echo "$as_me:$LINENO: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&5 +echo "$as_me: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&2;} + { (exit 1); exit 1; }; } +fi + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + + + + + + + + + + + + + + + + + + + +SPEEX_MAJOR_VERSION=1 +SPEEX_MINOR_VERSION=0 +SPEEX_MICRO_VERSION=5 +SPEEX_EXTRA_VERSION= +SPEEX_VERSION=$SPEEX_MAJOR_VERSION.$SPEEX_MINOR_VERSION.$SPEEX_MICRO_VERSION$SPEEX_EXTRA_VERSION + +SPEEX_LT_CURRENT=4 +SPEEX_LT_REVISION=0 +SPEEX_LT_AGE=3 + + + + + +# For automake. +VERSION=$SPEEX_VERSION +PACKAGE=speex + + + +am__api_version="1.8" +ac_aux_dir= +for ac_dir in $srcdir $srcdir/.. $srcdir/../..; do + if test -f $ac_dir/install-sh; then + ac_aux_dir=$ac_dir + ac_install_sh="$ac_aux_dir/install-sh -c" + break + elif test -f $ac_dir/install.sh; then + ac_aux_dir=$ac_dir + ac_install_sh="$ac_aux_dir/install.sh -c" + break + elif test -f $ac_dir/shtool; then + ac_aux_dir=$ac_dir + ac_install_sh="$ac_aux_dir/shtool install -c" + break + fi +done +if test -z "$ac_aux_dir"; then + { { echo "$as_me:$LINENO: error: cannot find install-sh or install.sh in $srcdir $srcdir/.. $srcdir/../.." >&5 +echo "$as_me: error: cannot find install-sh or install.sh in $srcdir $srcdir/.. $srcdir/../.." >&2;} + { (exit 1); exit 1; }; } +fi +ac_config_guess="$SHELL $ac_aux_dir/config.guess" +ac_config_sub="$SHELL $ac_aux_dir/config.sub" +ac_configure="$SHELL $ac_aux_dir/configure" # This should be Cygnus configure. + +# Find a good install program. We prefer a C program (faster), +# so one script is as good as another. But avoid the broken or +# incompatible versions: +# SysV /etc/install, /usr/sbin/install +# SunOS /usr/etc/install +# IRIX /sbin/install +# AIX /bin/install +# AmigaOS /C/install, which installs bootblocks on floppy discs +# AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag +# AFS /usr/afsws/bin/install, which mishandles nonexistent args +# SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff" +# OS/2's system install, which has a completely different semantic +# ./install, which can be erroneously created by make from ./install.sh. +echo "$as_me:$LINENO: checking for a BSD-compatible install" >&5 +echo $ECHO_N "checking for a BSD-compatible install... $ECHO_C" >&6 +if test -z "$INSTALL"; then +if test "${ac_cv_path_install+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + # Account for people who put trailing slashes in PATH elements. +case $as_dir/ in + ./ | .// | /cC/* | \ + /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \ + ?:\\/os2\\/install\\/* | ?:\\/OS2\\/INSTALL\\/* | \ + /usr/ucb/* ) ;; + *) + # OSF1 and SCO ODT 3.0 have their own names for install. + # Don't use installbsd from OSF since it installs stuff as root + # by default. + for ac_prog in ginstall scoinst install; do + for ac_exec_ext in '' $ac_executable_extensions; do + if $as_executable_p "$as_dir/$ac_prog$ac_exec_ext"; then + if test $ac_prog = install && + grep dspmsg "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then + # AIX install. It has an incompatible calling convention. + : + elif test $ac_prog = install && + grep pwplus "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then + # program-specific install script used by HP pwplus--don't use. + : + else + ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c" + break 3 + fi + fi + done + done + ;; +esac +done + + +fi + if test "${ac_cv_path_install+set}" = set; then + INSTALL=$ac_cv_path_install + else + # As a last resort, use the slow shell script. We don't cache a + # path for INSTALL within a source directory, because that will + # break other packages using the cache if that directory is + # removed, or if the path is relative. + INSTALL=$ac_install_sh + fi +fi +echo "$as_me:$LINENO: result: $INSTALL" >&5 +echo "${ECHO_T}$INSTALL" >&6 + +# Use test -z because SunOS4 sh mishandles braces in ${var-val}. +# It thinks the first close brace ends the variable substitution. +test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}' + +test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}' + +test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644' + +echo "$as_me:$LINENO: checking whether build environment is sane" >&5 +echo $ECHO_N "checking whether build environment is sane... $ECHO_C" >&6 +# Just in case +sleep 1 +echo timestamp > conftest.file +# Do `set' in a subshell so we don't clobber the current shell's +# arguments. Must try -L first in case configure is actually a +# symlink; some systems play weird games with the mod time of symlinks +# (eg FreeBSD returns the mod time of the symlink's containing +# directory). +if ( + set X `ls -Lt $srcdir/configure conftest.file 2> /dev/null` + if test "$*" = "X"; then + # -L didn't work. + set X `ls -t $srcdir/configure conftest.file` + fi + rm -f conftest.file + if test "$*" != "X $srcdir/configure conftest.file" \ + && test "$*" != "X conftest.file $srcdir/configure"; then + + # If neither matched, then we have a broken ls. This can happen + # if, for instance, CONFIG_SHELL is bash and it inherits a + # broken ls alias from the environment. This has actually + # happened. Such a system could not be considered "sane". + { { echo "$as_me:$LINENO: error: ls -t appears to fail. Make sure there is not a broken +alias in your environment" >&5 +echo "$as_me: error: ls -t appears to fail. Make sure there is not a broken +alias in your environment" >&2;} + { (exit 1); exit 1; }; } + fi + + test "$2" = conftest.file + ) +then + # Ok. + : +else + { { echo "$as_me:$LINENO: error: newly created file is older than distributed files! +Check your system clock" >&5 +echo "$as_me: error: newly created file is older than distributed files! +Check your system clock" >&2;} + { (exit 1); exit 1; }; } +fi +echo "$as_me:$LINENO: result: yes" >&5 +echo "${ECHO_T}yes" >&6 +test "$program_prefix" != NONE && + program_transform_name="s,^,$program_prefix,;$program_transform_name" +# Use a double $ so make ignores it. +test "$program_suffix" != NONE && + program_transform_name="s,\$,$program_suffix,;$program_transform_name" +# Double any \ or $. echo might interpret backslashes. +# By default was `s,x,x', remove it if useless. +cat <<\_ACEOF >conftest.sed +s/[\\$]/&&/g;s/;s,x,x,$// +_ACEOF +program_transform_name=`echo $program_transform_name | sed -f conftest.sed` +rm conftest.sed + +# expand $ac_aux_dir to an absolute path +am_aux_dir=`cd $ac_aux_dir && pwd` + +test x"${MISSING+set}" = xset || MISSING="\${SHELL} $am_aux_dir/missing" +# Use eval to expand $SHELL +if eval "$MISSING --run true"; then + am_missing_run="$MISSING --run " +else + am_missing_run= + { echo "$as_me:$LINENO: WARNING: \`missing' script is too old or missing" >&5 +echo "$as_me: WARNING: \`missing' script is too old or missing" >&2;} +fi + +if mkdir -p --version . >/dev/null 2>&1 && test ! -d ./--version; then + # Keeping the `.' argument allows $(mkdir_p) to be used without + # argument. Indeed, we sometimes output rules like + # $(mkdir_p) $(somedir) + # where $(somedir) is conditionally defined. + # (`test -n '$(somedir)' && $(mkdir_p) $(somedir)' is a more + # expensive solution, as it forces Make to start a sub-shell.) + mkdir_p='mkdir -p -- .' +else + # On NextStep and OpenStep, the `mkdir' command does not + # recognize any option. It will interpret all options as + # directories to create, and then abort because `.' already + # exists. + for d in ./-p ./--version; + do + test -d $d && rmdir $d + done + # $(mkinstalldirs) is defined by Automake if mkinstalldirs exists. + if test -f "$ac_aux_dir/mkinstalldirs"; then + mkdir_p='$(mkinstalldirs)' + else + mkdir_p='$(install_sh) -d' + fi +fi + +for ac_prog in gawk mawk nawk awk +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 +if test "${ac_cv_prog_AWK+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$AWK"; then + ac_cv_prog_AWK="$AWK" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_AWK="$ac_prog" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done + +fi +fi +AWK=$ac_cv_prog_AWK +if test -n "$AWK"; then + echo "$as_me:$LINENO: result: $AWK" >&5 +echo "${ECHO_T}$AWK" >&6 +else + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 +fi + + test -n "$AWK" && break +done + +echo "$as_me:$LINENO: checking whether ${MAKE-make} sets \$(MAKE)" >&5 +echo $ECHO_N "checking whether ${MAKE-make} sets \$(MAKE)... $ECHO_C" >&6 +set dummy ${MAKE-make}; ac_make=`echo "$2" | sed 'y,:./+-,___p_,'` +if eval "test \"\${ac_cv_prog_make_${ac_make}_set+set}\" = set"; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.make <<\_ACEOF +all: + @echo 'ac_maketemp="$(MAKE)"' +_ACEOF +# GNU make sometimes prints "make[1]: Entering...", which would confuse us. +eval `${MAKE-make} -f conftest.make 2>/dev/null | grep temp=` +if test -n "$ac_maketemp"; then + eval ac_cv_prog_make_${ac_make}_set=yes +else + eval ac_cv_prog_make_${ac_make}_set=no +fi +rm -f conftest.make +fi +if eval "test \"`echo '$ac_cv_prog_make_'${ac_make}_set`\" = yes"; then + echo "$as_me:$LINENO: result: yes" >&5 +echo "${ECHO_T}yes" >&6 + SET_MAKE= +else + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 + SET_MAKE="MAKE=${MAKE-make}" +fi + +rm -rf .tst 2>/dev/null +mkdir .tst 2>/dev/null +if test -d .tst; then + am__leading_dot=. +else + am__leading_dot=_ +fi +rmdir .tst 2>/dev/null + +# test to see if srcdir already configured +if test "`cd $srcdir && pwd`" != "`pwd`" && + test -f $srcdir/config.status; then + { { echo "$as_me:$LINENO: error: source directory already configured; run \"make distclean\" there first" >&5 +echo "$as_me: error: source directory already configured; run \"make distclean\" there first" >&2;} + { (exit 1); exit 1; }; } +fi + +# test whether we have cygpath +if test -z "$CYGPATH_W"; then + if (cygpath --version) >/dev/null 2>/dev/null; then + CYGPATH_W='cygpath -w' + else + CYGPATH_W=echo + fi +fi + + +# Define the identity of the package. + PACKAGE=$PACKAGE + VERSION=$VERSION + + +# Some tools Automake needs. + +ACLOCAL=${ACLOCAL-"${am_missing_run}aclocal-${am__api_version}"} + + +AUTOCONF=${AUTOCONF-"${am_missing_run}autoconf"} + + +AUTOMAKE=${AUTOMAKE-"${am_missing_run}automake-${am__api_version}"} + + +AUTOHEADER=${AUTOHEADER-"${am_missing_run}autoheader"} + + +MAKEINFO=${MAKEINFO-"${am_missing_run}makeinfo"} + + +AMTAR=${AMTAR-"${am_missing_run}tar"} + +install_sh=${install_sh-"$am_aux_dir/install-sh"} + +# Installed binaries are usually stripped using `strip' when the user +# run `make install-strip'. However `strip' might not be the right +# tool to use in cross-compilation environments, therefore Automake +# will honor the `STRIP' environment variable to overrule this program. +if test "$cross_compiling" != no; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args. +set dummy ${ac_tool_prefix}strip; ac_word=$2 +echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 +if test "${ac_cv_prog_STRIP+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$STRIP"; then + ac_cv_prog_STRIP="$STRIP" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_STRIP="${ac_tool_prefix}strip" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done + +fi +fi +STRIP=$ac_cv_prog_STRIP +if test -n "$STRIP"; then + echo "$as_me:$LINENO: result: $STRIP" >&5 +echo "${ECHO_T}$STRIP" >&6 +else + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 +fi + +fi +if test -z "$ac_cv_prog_STRIP"; then + ac_ct_STRIP=$STRIP + # Extract the first word of "strip", so it can be a program name with args. +set dummy strip; ac_word=$2 +echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 +if test "${ac_cv_prog_ac_ct_STRIP+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$ac_ct_STRIP"; then + ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_STRIP="strip" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done + + test -z "$ac_cv_prog_ac_ct_STRIP" && ac_cv_prog_ac_ct_STRIP=":" +fi +fi +ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP +if test -n "$ac_ct_STRIP"; then + echo "$as_me:$LINENO: result: $ac_ct_STRIP" >&5 +echo "${ECHO_T}$ac_ct_STRIP" >&6 +else + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 +fi + + STRIP=$ac_ct_STRIP +else + STRIP="$ac_cv_prog_STRIP" +fi + +fi +INSTALL_STRIP_PROGRAM="\${SHELL} \$(install_sh) -c -s" + +# We need awk for the "check" target. The system "awk" is bad on +# some platforms. + + + +echo "$as_me:$LINENO: checking whether to enable maintainer-specific portions of Makefiles" >&5 +echo $ECHO_N "checking whether to enable maintainer-specific portions of Makefiles... $ECHO_C" >&6 + # Check whether --enable-maintainer-mode or --disable-maintainer-mode was given. +if test "${enable_maintainer_mode+set}" = set; then + enableval="$enable_maintainer_mode" + USE_MAINTAINER_MODE=$enableval +else + USE_MAINTAINER_MODE=no +fi; + echo "$as_me:$LINENO: result: $USE_MAINTAINER_MODE" >&5 +echo "${ECHO_T}$USE_MAINTAINER_MODE" >&6 + + +if test $USE_MAINTAINER_MODE = yes; then + MAINTAINER_MODE_TRUE= + MAINTAINER_MODE_FALSE='#' +else + MAINTAINER_MODE_TRUE='#' + MAINTAINER_MODE_FALSE= +fi + + MAINT=$MAINTAINER_MODE_TRUE + + + +# Make sure we can run config.sub. +$ac_config_sub sun4 >/dev/null 2>&1 || + { { echo "$as_me:$LINENO: error: cannot run $ac_config_sub" >&5 +echo "$as_me: error: cannot run $ac_config_sub" >&2;} + { (exit 1); exit 1; }; } + +echo "$as_me:$LINENO: checking build system type" >&5 +echo $ECHO_N "checking build system type... $ECHO_C" >&6 +if test "${ac_cv_build+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_cv_build_alias=$build_alias +test -z "$ac_cv_build_alias" && + ac_cv_build_alias=`$ac_config_guess` +test -z "$ac_cv_build_alias" && + { { echo "$as_me:$LINENO: error: cannot guess build type; you must specify one" >&5 +echo "$as_me: error: cannot guess build type; you must specify one" >&2;} + { (exit 1); exit 1; }; } +ac_cv_build=`$ac_config_sub $ac_cv_build_alias` || + { { echo "$as_me:$LINENO: error: $ac_config_sub $ac_cv_build_alias failed" >&5 +echo "$as_me: error: $ac_config_sub $ac_cv_build_alias failed" >&2;} + { (exit 1); exit 1; }; } + +fi +echo "$as_me:$LINENO: result: $ac_cv_build" >&5 +echo "${ECHO_T}$ac_cv_build" >&6 +build=$ac_cv_build +build_cpu=`echo $ac_cv_build | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\1/'` +build_vendor=`echo $ac_cv_build | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\2/'` +build_os=`echo $ac_cv_build | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\3/'` + + +echo "$as_me:$LINENO: checking host system type" >&5 +echo $ECHO_N "checking host system type... $ECHO_C" >&6 +if test "${ac_cv_host+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_cv_host_alias=$host_alias +test -z "$ac_cv_host_alias" && + ac_cv_host_alias=$ac_cv_build_alias +ac_cv_host=`$ac_config_sub $ac_cv_host_alias` || + { { echo "$as_me:$LINENO: error: $ac_config_sub $ac_cv_host_alias failed" >&5 +echo "$as_me: error: $ac_config_sub $ac_cv_host_alias failed" >&2;} + { (exit 1); exit 1; }; } + +fi +echo "$as_me:$LINENO: result: $ac_cv_host" >&5 +echo "${ECHO_T}$ac_cv_host" >&6 +host=$ac_cv_host +host_cpu=`echo $ac_cv_host | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\1/'` +host_vendor=`echo $ac_cv_host | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\2/'` +host_os=`echo $ac_cv_host | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\3/'` + + +# Check whether --enable-shared or --disable-shared was given. +if test "${enable_shared+set}" = set; then + enableval="$enable_shared" + p=${PACKAGE-default} + case $enableval in + yes) enable_shared=yes ;; + no) enable_shared=no ;; + *) + enable_shared=no + # Look at the argument we got. We use all the common list separators. + lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," + for pkg in $enableval; do + IFS="$lt_save_ifs" + if test "X$pkg" = "X$p"; then + enable_shared=yes + fi + done + IFS="$lt_save_ifs" + ;; + esac +else + enable_shared=yes +fi; + +# Check whether --enable-static or --disable-static was given. +if test "${enable_static+set}" = set; then + enableval="$enable_static" + p=${PACKAGE-default} + case $enableval in + yes) enable_static=yes ;; + no) enable_static=no ;; + *) + enable_static=no + # Look at the argument we got. We use all the common list separators. + lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," + for pkg in $enableval; do + IFS="$lt_save_ifs" + if test "X$pkg" = "X$p"; then + enable_static=yes + fi + done + IFS="$lt_save_ifs" + ;; + esac +else + enable_static=yes +fi; + +# Check whether --enable-fast-install or --disable-fast-install was given. +if test "${enable_fast_install+set}" = set; then + enableval="$enable_fast_install" + p=${PACKAGE-default} + case $enableval in + yes) enable_fast_install=yes ;; + no) enable_fast_install=no ;; + *) + enable_fast_install=no + # Look at the argument we got. We use all the common list separators. + lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," + for pkg in $enableval; do + IFS="$lt_save_ifs" + if test "X$pkg" = "X$p"; then + enable_fast_install=yes + fi + done + IFS="$lt_save_ifs" + ;; + esac +else + enable_fast_install=yes +fi; + +DEPDIR="${am__leading_dot}deps" + + ac_config_commands="$ac_config_commands depfiles" + + +am_make=${MAKE-make} +cat > confinc << 'END' +am__doit: + @echo done +.PHONY: am__doit +END +# If we don't find an include directive, just comment out the code. +echo "$as_me:$LINENO: checking for style of include used by $am_make" >&5 +echo $ECHO_N "checking for style of include used by $am_make... $ECHO_C" >&6 +am__include="#" +am__quote= +_am_result=none +# First try GNU make style include. +echo "include confinc" > confmf +# We grep out `Entering directory' and `Leaving directory' +# messages which can occur if `w' ends up in MAKEFLAGS. +# In particular we don't look at `^make:' because GNU make might +# be invoked under some other name (usually "gmake"), in which +# case it prints its new name instead of `make'. +if test "`$am_make -s -f confmf 2> /dev/null | grep -v 'ing directory'`" = "done"; then + am__include=include + am__quote= + _am_result=GNU +fi +# Now try BSD make style include. +if test "$am__include" = "#"; then + echo '.include "confinc"' > confmf + if test "`$am_make -s -f confmf 2> /dev/null`" = "done"; then + am__include=.include + am__quote="\"" + _am_result=BSD + fi +fi + + +echo "$as_me:$LINENO: result: $_am_result" >&5 +echo "${ECHO_T}$_am_result" >&6 +rm -f confinc confmf + +# Check whether --enable-dependency-tracking or --disable-dependency-tracking was given. +if test "${enable_dependency_tracking+set}" = set; then + enableval="$enable_dependency_tracking" + +fi; +if test "x$enable_dependency_tracking" != xno; then + am_depcomp="$ac_aux_dir/depcomp" + AMDEPBACKSLASH='\' +fi + + +if test "x$enable_dependency_tracking" != xno; then + AMDEP_TRUE= + AMDEP_FALSE='#' +else + AMDEP_TRUE='#' + AMDEP_FALSE= +fi + + + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. +set dummy ${ac_tool_prefix}gcc; ac_word=$2 +echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 +if test "${ac_cv_prog_CC+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_CC="${ac_tool_prefix}gcc" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + echo "$as_me:$LINENO: result: $CC" >&5 +echo "${ECHO_T}$CC" >&6 +else + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 +fi + +fi +if test -z "$ac_cv_prog_CC"; then + ac_ct_CC=$CC + # Extract the first word of "gcc", so it can be a program name with args. +set dummy gcc; ac_word=$2 +echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 +if test "${ac_cv_prog_ac_ct_CC+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_CC="gcc" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done + +fi +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 +echo "${ECHO_T}$ac_ct_CC" >&6 +else + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 +fi + + CC=$ac_ct_CC +else + CC="$ac_cv_prog_CC" +fi + +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. +set dummy ${ac_tool_prefix}cc; ac_word=$2 +echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 +if test "${ac_cv_prog_CC+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_CC="${ac_tool_prefix}cc" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + echo "$as_me:$LINENO: result: $CC" >&5 +echo "${ECHO_T}$CC" >&6 +else + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 +fi + +fi +if test -z "$ac_cv_prog_CC"; then + ac_ct_CC=$CC + # Extract the first word of "cc", so it can be a program name with args. +set dummy cc; ac_word=$2 +echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 +if test "${ac_cv_prog_ac_ct_CC+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_CC="cc" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done + +fi +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 +echo "${ECHO_T}$ac_ct_CC" >&6 +else + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 +fi + + CC=$ac_ct_CC +else + CC="$ac_cv_prog_CC" +fi + +fi +if test -z "$CC"; then + # Extract the first word of "cc", so it can be a program name with args. +set dummy cc; ac_word=$2 +echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 +if test "${ac_cv_prog_CC+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else + ac_prog_rejected=no +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then + ac_prog_rejected=yes + continue + fi + ac_cv_prog_CC="cc" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done + +if test $ac_prog_rejected = yes; then + # We found a bogon in the path, so make sure we never use it. + set dummy $ac_cv_prog_CC + shift + if test $# != 0; then + # We chose a different compiler from the bogus one. + # However, it has the same basename, so the bogon will be chosen + # first if we set CC to just the basename; use the full file name. + shift + ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" + fi +fi +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + echo "$as_me:$LINENO: result: $CC" >&5 +echo "${ECHO_T}$CC" >&6 +else + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 +fi + +fi +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + for ac_prog in cl + do + # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. +set dummy $ac_tool_prefix$ac_prog; ac_word=$2 +echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 +if test "${ac_cv_prog_CC+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_CC="$ac_tool_prefix$ac_prog" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + echo "$as_me:$LINENO: result: $CC" >&5 +echo "${ECHO_T}$CC" >&6 +else + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 +fi + + test -n "$CC" && break + done +fi +if test -z "$CC"; then + ac_ct_CC=$CC + for ac_prog in cl +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 +if test "${ac_cv_prog_ac_ct_CC+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_CC="$ac_prog" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done + +fi +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 +echo "${ECHO_T}$ac_ct_CC" >&6 +else + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 +fi + + test -n "$ac_ct_CC" && break +done + + CC=$ac_ct_CC +fi + +fi + + +test -z "$CC" && { { echo "$as_me:$LINENO: error: no acceptable C compiler found in \$PATH +See \`config.log' for more details." >&5 +echo "$as_me: error: no acceptable C compiler found in \$PATH +See \`config.log' for more details." >&2;} + { (exit 1); exit 1; }; } + +# Provide some information about the compiler. +echo "$as_me:$LINENO:" \ + "checking for C compiler version" >&5 +ac_compiler=`set X $ac_compile; echo $2` +{ (eval echo "$as_me:$LINENO: \"$ac_compiler --version &5\"") >&5 + (eval $ac_compiler --version &5) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } +{ (eval echo "$as_me:$LINENO: \"$ac_compiler -v &5\"") >&5 + (eval $ac_compiler -v &5) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } +{ (eval echo "$as_me:$LINENO: \"$ac_compiler -V &5\"") >&5 + (eval $ac_compiler -V &5) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } + +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +ac_clean_files_save=$ac_clean_files +ac_clean_files="$ac_clean_files a.out a.exe b.out" +# Try to create an executable without -o first, disregard a.out. +# It will help us diagnose broken compilers, and finding out an intuition +# of exeext. +echo "$as_me:$LINENO: checking for C compiler default output file name" >&5 +echo $ECHO_N "checking for C compiler default output file name... $ECHO_C" >&6 +ac_link_default=`echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` +if { (eval echo "$as_me:$LINENO: \"$ac_link_default\"") >&5 + (eval $ac_link_default) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + # Find the output, starting from the most likely. This scheme is +# not robust to junk in `.', hence go to wildcards (a.*) only as a last +# resort. + +# Be careful to initialize this variable, since it used to be cached. +# Otherwise an old cache value of `no' led to `EXEEXT = no' in a Makefile. +ac_cv_exeext= +# b.out is created by i960 compilers. +for ac_file in a_out.exe a.exe conftest.exe a.out conftest a.* conftest.* b.out +do + test -f "$ac_file" || continue + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.o | *.obj ) + ;; + conftest.$ac_ext ) + # This is the source file. + ;; + [ab].out ) + # We found the default executable, but exeext='' is most + # certainly right. + break;; + *.* ) + ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` + # FIXME: I believe we export ac_cv_exeext for Libtool, + # but it would be cool to find out if it's true. Does anybody + # maintain Libtool? --akim. + export ac_cv_exeext + break;; + * ) + break;; + esac +done +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +{ { echo "$as_me:$LINENO: error: C compiler cannot create executables +See \`config.log' for more details." >&5 +echo "$as_me: error: C compiler cannot create executables +See \`config.log' for more details." >&2;} + { (exit 77); exit 77; }; } +fi + +ac_exeext=$ac_cv_exeext +echo "$as_me:$LINENO: result: $ac_file" >&5 +echo "${ECHO_T}$ac_file" >&6 + +# Check the compiler produces executables we can run. If not, either +# the compiler is broken, or we cross compile. +echo "$as_me:$LINENO: checking whether the C compiler works" >&5 +echo $ECHO_N "checking whether the C compiler works... $ECHO_C" >&6 +# FIXME: These cross compiler hacks should be removed for Autoconf 3.0 +# If not cross compiling, check that we can run a simple program. +if test "$cross_compiling" != yes; then + if { ac_try='./$ac_file' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + cross_compiling=no + else + if test "$cross_compiling" = maybe; then + cross_compiling=yes + else + { { echo "$as_me:$LINENO: error: cannot run C compiled programs. +If you meant to cross compile, use \`--host'. +See \`config.log' for more details." >&5 +echo "$as_me: error: cannot run C compiled programs. +If you meant to cross compile, use \`--host'. +See \`config.log' for more details." >&2;} + { (exit 1); exit 1; }; } + fi + fi +fi +echo "$as_me:$LINENO: result: yes" >&5 +echo "${ECHO_T}yes" >&6 + +rm -f a.out a.exe conftest$ac_cv_exeext b.out +ac_clean_files=$ac_clean_files_save +# Check the compiler produces executables we can run. If not, either +# the compiler is broken, or we cross compile. +echo "$as_me:$LINENO: checking whether we are cross compiling" >&5 +echo $ECHO_N "checking whether we are cross compiling... $ECHO_C" >&6 +echo "$as_me:$LINENO: result: $cross_compiling" >&5 +echo "${ECHO_T}$cross_compiling" >&6 + +echo "$as_me:$LINENO: checking for suffix of executables" >&5 +echo $ECHO_N "checking for suffix of executables... $ECHO_C" >&6 +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + # If both `conftest.exe' and `conftest' are `present' (well, observable) +# catch `conftest.exe'. For instance with Cygwin, `ls conftest' will +# work properly (i.e., refer to `conftest.exe'), while it won't with +# `rm'. +for ac_file in conftest.exe conftest conftest.*; do + test -f "$ac_file" || continue + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.o | *.obj ) ;; + *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` + export ac_cv_exeext + break;; + * ) break;; + esac +done +else + { { echo "$as_me:$LINENO: error: cannot compute suffix of executables: cannot compile and link +See \`config.log' for more details." >&5 +echo "$as_me: error: cannot compute suffix of executables: cannot compile and link +See \`config.log' for more details." >&2;} + { (exit 1); exit 1; }; } +fi + +rm -f conftest$ac_cv_exeext +echo "$as_me:$LINENO: result: $ac_cv_exeext" >&5 +echo "${ECHO_T}$ac_cv_exeext" >&6 + +rm -f conftest.$ac_ext +EXEEXT=$ac_cv_exeext +ac_exeext=$EXEEXT +echo "$as_me:$LINENO: checking for suffix of object files" >&5 +echo $ECHO_N "checking for suffix of object files... $ECHO_C" >&6 +if test "${ac_cv_objext+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.o conftest.obj +if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + for ac_file in `(ls conftest.o conftest.obj; ls conftest.*) 2>/dev/null`; do + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg ) ;; + *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` + break;; + esac +done +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +{ { echo "$as_me:$LINENO: error: cannot compute suffix of object files: cannot compile +See \`config.log' for more details." >&5 +echo "$as_me: error: cannot compute suffix of object files: cannot compile +See \`config.log' for more details." >&2;} + { (exit 1); exit 1; }; } +fi + +rm -f conftest.$ac_cv_objext conftest.$ac_ext +fi +echo "$as_me:$LINENO: result: $ac_cv_objext" >&5 +echo "${ECHO_T}$ac_cv_objext" >&6 +OBJEXT=$ac_cv_objext +ac_objext=$OBJEXT +echo "$as_me:$LINENO: checking whether we are using the GNU C compiler" >&5 +echo $ECHO_N "checking whether we are using the GNU C compiler... $ECHO_C" >&6 +if test "${ac_cv_c_compiler_gnu+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ +#ifndef __GNUC__ + choke me +#endif + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest.$ac_objext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_compiler_gnu=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_compiler_gnu=no +fi +rm -f conftest.err conftest.$ac_objext conftest.$ac_ext +ac_cv_c_compiler_gnu=$ac_compiler_gnu + +fi +echo "$as_me:$LINENO: result: $ac_cv_c_compiler_gnu" >&5 +echo "${ECHO_T}$ac_cv_c_compiler_gnu" >&6 +GCC=`test $ac_compiler_gnu = yes && echo yes` +ac_test_CFLAGS=${CFLAGS+set} +ac_save_CFLAGS=$CFLAGS +CFLAGS="-g" +echo "$as_me:$LINENO: checking whether $CC accepts -g" >&5 +echo $ECHO_N "checking whether $CC accepts -g... $ECHO_C" >&6 +if test "${ac_cv_prog_cc_g+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest.$ac_objext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_prog_cc_g=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_cv_prog_cc_g=no +fi +rm -f conftest.err conftest.$ac_objext conftest.$ac_ext +fi +echo "$as_me:$LINENO: result: $ac_cv_prog_cc_g" >&5 +echo "${ECHO_T}$ac_cv_prog_cc_g" >&6 +if test "$ac_test_CFLAGS" = set; then + CFLAGS=$ac_save_CFLAGS +elif test $ac_cv_prog_cc_g = yes; then + if test "$GCC" = yes; then + CFLAGS="-g -O2" + else + CFLAGS="-g" + fi +else + if test "$GCC" = yes; then + CFLAGS="-O2" + else + CFLAGS= + fi +fi +echo "$as_me:$LINENO: checking for $CC option to accept ANSI C" >&5 +echo $ECHO_N "checking for $CC option to accept ANSI C... $ECHO_C" >&6 +if test "${ac_cv_prog_cc_stdc+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_cv_prog_cc_stdc=no +ac_save_CC=$CC +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +#include +#include +#include +/* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ +struct buf { int x; }; +FILE * (*rcsopen) (struct buf *, struct stat *, int); +static char *e (p, i) + char **p; + int i; +{ + return p[i]; +} +static char *f (char * (*g) (char **, int), char **p, ...) +{ + char *s; + va_list v; + va_start (v,p); + s = g (p, va_arg (v,int)); + va_end (v); + return s; +} + +/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has + function prototypes and stuff, but not '\xHH' hex character constants. + These don't provoke an error unfortunately, instead are silently treated + as 'x'. The following induces an error, until -std1 is added to get + proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an + array size at least. It's necessary to write '\x00'==0 to get something + that's true only with -std1. */ +int osf4_cc_array ['\x00' == 0 ? 1 : -1]; + +int test (int i, double x); +struct s1 {int (*f) (int a);}; +struct s2 {int (*f) (double a);}; +int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); +int argc; +char **argv; +int +main () +{ +return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; + ; + return 0; +} +_ACEOF +# Don't try gcc -ansi; that turns off useful extensions and +# breaks some systems' header files. +# AIX -qlanglvl=ansi +# Ultrix and OSF/1 -std1 +# HP-UX 10.20 and later -Ae +# HP-UX older versions -Aa -D_HPUX_SOURCE +# SVR4 -Xc -D__EXTENSIONS__ +for ac_arg in "" -qlanglvl=ansi -std1 -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" +do + CC="$ac_save_CC $ac_arg" + rm -f conftest.$ac_objext +if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest.$ac_objext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_prog_cc_stdc=$ac_arg +break +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +fi +rm -f conftest.err conftest.$ac_objext +done +rm -f conftest.$ac_ext conftest.$ac_objext +CC=$ac_save_CC + +fi + +case "x$ac_cv_prog_cc_stdc" in + x|xno) + echo "$as_me:$LINENO: result: none needed" >&5 +echo "${ECHO_T}none needed" >&6 ;; + *) + echo "$as_me:$LINENO: result: $ac_cv_prog_cc_stdc" >&5 +echo "${ECHO_T}$ac_cv_prog_cc_stdc" >&6 + CC="$CC $ac_cv_prog_cc_stdc" ;; +esac + +# Some people use a C++ compiler to compile C. Since we use `exit', +# in C++ we need to declare it. In case someone uses the same compiler +# for both compiling C and C++ we need to have the C++ compiler decide +# the declaration of exit, since it's the most demanding environment. +cat >conftest.$ac_ext <<_ACEOF +#ifndef __cplusplus + choke me +#endif +_ACEOF +rm -f conftest.$ac_objext +if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest.$ac_objext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + for ac_declaration in \ + '' \ + 'extern "C" void std::exit (int) throw (); using std::exit;' \ + 'extern "C" void std::exit (int); using std::exit;' \ + 'extern "C" void exit (int) throw ();' \ + 'extern "C" void exit (int);' \ + 'void exit (int);' +do + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_declaration +#include +int +main () +{ +exit (42); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest.$ac_objext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + : +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +continue +fi +rm -f conftest.err conftest.$ac_objext conftest.$ac_ext + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_declaration +int +main () +{ +exit (42); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest.$ac_objext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + break +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +fi +rm -f conftest.err conftest.$ac_objext conftest.$ac_ext +done +rm -f conftest* +if test -n "$ac_declaration"; then + echo '#ifdef __cplusplus' >>confdefs.h + echo $ac_declaration >>confdefs.h + echo '#endif' >>confdefs.h +fi + +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +fi +rm -f conftest.err conftest.$ac_objext conftest.$ac_ext +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + +depcc="$CC" am_compiler_list= + +echo "$as_me:$LINENO: checking dependency style of $depcc" >&5 +echo $ECHO_N "checking dependency style of $depcc... $ECHO_C" >&6 +if test "${am_cv_CC_dependencies_compiler_type+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then + # We make a subdir and do the tests there. Otherwise we can end up + # making bogus files that we don't know about and never remove. For + # instance it was reported that on HP-UX the gcc test will end up + # making a dummy file named `D' -- because `-MD' means `put the output + # in D'. + mkdir conftest.dir + # Copy depcomp to subdir because otherwise we won't find it if we're + # using a relative directory. + cp "$am_depcomp" conftest.dir + cd conftest.dir + # We will build objects and dependencies in a subdirectory because + # it helps to detect inapplicable dependency modes. For instance + # both Tru64's cc and ICC support -MD to output dependencies as a + # side effect of compilation, but ICC will put the dependencies in + # the current directory while Tru64 will put them in the object + # directory. + mkdir sub + + am_cv_CC_dependencies_compiler_type=none + if test "$am_compiler_list" = ""; then + am_compiler_list=`sed -n 's/^#*\([a-zA-Z0-9]*\))$/\1/p' < ./depcomp` + fi + for depmode in $am_compiler_list; do + # Setup a source with many dependencies, because some compilers + # like to wrap large dependency lists on column 80 (with \), and + # we should not choose a depcomp mode which is confused by this. + # + # We need to recreate these files for each test, as the compiler may + # overwrite some of them when testing with obscure command lines. + # This happens at least with the AIX C compiler. + : > sub/conftest.c + for i in 1 2 3 4 5 6; do + echo '#include "conftst'$i'.h"' >> sub/conftest.c + # Using `: > sub/conftst$i.h' creates only sub/conftst1.h with + # Solaris 8's {/usr,}/bin/sh. + touch sub/conftst$i.h + done + echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf + + case $depmode in + nosideeffect) + # after this tag, mechanisms are not by side-effect, so they'll + # only be used when explicitly requested + if test "x$enable_dependency_tracking" = xyes; then + continue + else + break + fi + ;; + none) break ;; + esac + # We check with `-c' and `-o' for the sake of the "dashmstdout" + # mode. It turns out that the SunPro C++ compiler does not properly + # handle `-M -o', and we need to detect this. + if depmode=$depmode \ + source=sub/conftest.c object=sub/conftest.${OBJEXT-o} \ + depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ + $SHELL ./depcomp $depcc -c -o sub/conftest.${OBJEXT-o} sub/conftest.c \ + >/dev/null 2>conftest.err && + grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && + grep sub/conftest.${OBJEXT-o} sub/conftest.Po > /dev/null 2>&1 && + ${MAKE-make} -s -f confmf > /dev/null 2>&1; then + # icc doesn't choke on unknown options, it will just issue warnings + # or remarks (even with -Werror). So we grep stderr for any message + # that says an option was ignored or not supported. + # When given -MP, icc 7.0 and 7.1 complain thusly: + # icc: Command line warning: ignoring option '-M'; no argument required + # The diagnosis changed in icc 8.0: + # icc: Command line remark: option '-MP' not supported + if (grep 'ignoring option' conftest.err || + grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else + am_cv_CC_dependencies_compiler_type=$depmode + break + fi + fi + done + + cd .. + rm -rf conftest.dir +else + am_cv_CC_dependencies_compiler_type=none +fi + +fi +echo "$as_me:$LINENO: result: $am_cv_CC_dependencies_compiler_type" >&5 +echo "${ECHO_T}$am_cv_CC_dependencies_compiler_type" >&6 +CCDEPMODE=depmode=$am_cv_CC_dependencies_compiler_type + + + +if + test "x$enable_dependency_tracking" != xno \ + && test "$am_cv_CC_dependencies_compiler_type" = gcc3; then + am__fastdepCC_TRUE= + am__fastdepCC_FALSE='#' +else + am__fastdepCC_TRUE='#' + am__fastdepCC_FALSE= +fi + + +echo "$as_me:$LINENO: checking for a sed that does not truncate output" >&5 +echo $ECHO_N "checking for a sed that does not truncate output... $ECHO_C" >&6 +if test "${lt_cv_path_SED+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + # Loop through the user's path and test for sed and gsed. +# Then use that list of sed's as ones to test for truncation. +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for lt_ac_prog in sed gsed; do + for ac_exec_ext in '' $ac_executable_extensions; do + if $as_executable_p "$as_dir/$lt_ac_prog$ac_exec_ext"; then + lt_ac_sed_list="$lt_ac_sed_list $as_dir/$lt_ac_prog$ac_exec_ext" + fi + done + done +done +lt_ac_max=0 +lt_ac_count=0 +# Add /usr/xpg4/bin/sed as it is typically found on Solaris +# along with /bin/sed that truncates output. +for lt_ac_sed in $lt_ac_sed_list /usr/xpg4/bin/sed; do + test ! -f $lt_ac_sed && break + cat /dev/null > conftest.in + lt_ac_count=0 + echo $ECHO_N "0123456789$ECHO_C" >conftest.in + # Check for GNU sed and select it if it is found. + if "$lt_ac_sed" --version 2>&1 < /dev/null | grep 'GNU' > /dev/null; then + lt_cv_path_SED=$lt_ac_sed + break + fi + while true; do + cat conftest.in conftest.in >conftest.tmp + mv conftest.tmp conftest.in + cp conftest.in conftest.nl + echo >>conftest.nl + $lt_ac_sed -e 's/a$//' < conftest.nl >conftest.out || break + cmp -s conftest.out conftest.nl || break + # 10000 chars as input seems more than enough + test $lt_ac_count -gt 10 && break + lt_ac_count=`expr $lt_ac_count + 1` + if test $lt_ac_count -gt $lt_ac_max; then + lt_ac_max=$lt_ac_count + lt_cv_path_SED=$lt_ac_sed + fi + done +done +SED=$lt_cv_path_SED + +fi + +echo "$as_me:$LINENO: result: $SED" >&5 +echo "${ECHO_T}$SED" >&6 + +echo "$as_me:$LINENO: checking for egrep" >&5 +echo $ECHO_N "checking for egrep... $ECHO_C" >&6 +if test "${ac_cv_prog_egrep+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if echo a | (grep -E '(a|b)') >/dev/null 2>&1 + then ac_cv_prog_egrep='grep -E' + else ac_cv_prog_egrep='egrep' + fi +fi +echo "$as_me:$LINENO: result: $ac_cv_prog_egrep" >&5 +echo "${ECHO_T}$ac_cv_prog_egrep" >&6 + EGREP=$ac_cv_prog_egrep + + + +# Check whether --with-gnu-ld or --without-gnu-ld was given. +if test "${with_gnu_ld+set}" = set; then + withval="$with_gnu_ld" + test "$withval" = no || with_gnu_ld=yes +else + with_gnu_ld=no +fi; +ac_prog=ld +if test "$GCC" = yes; then + # Check if gcc -print-prog-name=ld gives a path. + echo "$as_me:$LINENO: checking for ld used by $CC" >&5 +echo $ECHO_N "checking for ld used by $CC... $ECHO_C" >&6 + case $host in + *-*-mingw*) + # gcc leaves a trailing carriage return which upsets mingw + ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; + *) + ac_prog=`($CC -print-prog-name=ld) 2>&5` ;; + esac + case $ac_prog in + # Accept absolute paths. + [\\/]* | ?:[\\/]*) + re_direlt='/[^/][^/]*/\.\./' + # Canonicalize the pathname of ld + ac_prog=`echo $ac_prog| $SED 's%\\\\%/%g'` + while echo $ac_prog | grep "$re_direlt" > /dev/null 2>&1; do + ac_prog=`echo $ac_prog| $SED "s%$re_direlt%/%"` + done + test -z "$LD" && LD="$ac_prog" + ;; + "") + # If it fails, then pretend we aren't using GCC. + ac_prog=ld + ;; + *) + # If it is relative, then search for the first ld in PATH. + with_gnu_ld=unknown + ;; + esac +elif test "$with_gnu_ld" = yes; then + echo "$as_me:$LINENO: checking for GNU ld" >&5 +echo $ECHO_N "checking for GNU ld... $ECHO_C" >&6 +else + echo "$as_me:$LINENO: checking for non-GNU ld" >&5 +echo $ECHO_N "checking for non-GNU ld... $ECHO_C" >&6 +fi +if test "${lt_cv_path_LD+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -z "$LD"; then + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR + for ac_dir in $PATH; do + IFS="$lt_save_ifs" + test -z "$ac_dir" && ac_dir=. + if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then + lt_cv_path_LD="$ac_dir/$ac_prog" + # Check to see if the program is GNU ld. I'd rather use --version, + # but apparently some GNU ld's only accept -v. + # Break only if it was the GNU/non-GNU ld that we prefer. + case `"$lt_cv_path_LD" -v 2>&1 &5 +echo "${ECHO_T}$LD" >&6 +else + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 +fi +test -z "$LD" && { { echo "$as_me:$LINENO: error: no acceptable ld found in \$PATH" >&5 +echo "$as_me: error: no acceptable ld found in \$PATH" >&2;} + { (exit 1); exit 1; }; } +echo "$as_me:$LINENO: checking if the linker ($LD) is GNU ld" >&5 +echo $ECHO_N "checking if the linker ($LD) is GNU ld... $ECHO_C" >&6 +if test "${lt_cv_prog_gnu_ld+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + # I'd rather use --version here, but apparently some GNU ld's only accept -v. +case `$LD -v 2>&1 &5 +echo "${ECHO_T}$lt_cv_prog_gnu_ld" >&6 +with_gnu_ld=$lt_cv_prog_gnu_ld + + +echo "$as_me:$LINENO: checking for $LD option to reload object files" >&5 +echo $ECHO_N "checking for $LD option to reload object files... $ECHO_C" >&6 +if test "${lt_cv_ld_reload_flag+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + lt_cv_ld_reload_flag='-r' +fi +echo "$as_me:$LINENO: result: $lt_cv_ld_reload_flag" >&5 +echo "${ECHO_T}$lt_cv_ld_reload_flag" >&6 +reload_flag=$lt_cv_ld_reload_flag +case $reload_flag in +"" | " "*) ;; +*) reload_flag=" $reload_flag" ;; +esac +reload_cmds='$LD$reload_flag -o $output$reload_objs' + +echo "$as_me:$LINENO: checking for BSD-compatible nm" >&5 +echo $ECHO_N "checking for BSD-compatible nm... $ECHO_C" >&6 +if test "${lt_cv_path_NM+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$NM"; then + # Let the user override the test. + lt_cv_path_NM="$NM" +else + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR + for ac_dir in $PATH /usr/ccs/bin /usr/ucb /bin; do + IFS="$lt_save_ifs" + test -z "$ac_dir" && ac_dir=. + tmp_nm="$ac_dir/${ac_tool_prefix}nm" + if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then + # Check to see if the nm accepts a BSD-compat flag. + # Adding the `sed 1q' prevents false positives on HP-UX, which says: + # nm: unknown option "B" ignored + # Tru64's nm complains that /dev/null is an invalid object file + case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in + */dev/null* | *'Invalid file or object type'*) + lt_cv_path_NM="$tmp_nm -B" + break + ;; + *) + case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in + */dev/null*) + lt_cv_path_NM="$tmp_nm -p" + break + ;; + *) + lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but + continue # so that we can try to find one that supports BSD flags + ;; + esac + esac + fi + done + IFS="$lt_save_ifs" + test -z "$lt_cv_path_NM" && lt_cv_path_NM=nm +fi +fi +echo "$as_me:$LINENO: result: $lt_cv_path_NM" >&5 +echo "${ECHO_T}$lt_cv_path_NM" >&6 +NM="$lt_cv_path_NM" + +echo "$as_me:$LINENO: checking whether ln -s works" >&5 +echo $ECHO_N "checking whether ln -s works... $ECHO_C" >&6 +LN_S=$as_ln_s +if test "$LN_S" = "ln -s"; then + echo "$as_me:$LINENO: result: yes" >&5 +echo "${ECHO_T}yes" >&6 +else + echo "$as_me:$LINENO: result: no, using $LN_S" >&5 +echo "${ECHO_T}no, using $LN_S" >&6 +fi + +echo "$as_me:$LINENO: checking how to recognise dependent libraries" >&5 +echo $ECHO_N "checking how to recognise dependent libraries... $ECHO_C" >&6 +if test "${lt_cv_deplibs_check_method+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + lt_cv_file_magic_cmd='$MAGIC_CMD' +lt_cv_file_magic_test_file= +lt_cv_deplibs_check_method='unknown' +# Need to set the preceding variable on all platforms that support +# interlibrary dependencies. +# 'none' -- dependencies not supported. +# `unknown' -- same as none, but documents that we really don't know. +# 'pass_all' -- all dependencies passed with no checks. +# 'test_compile' -- check by making test program. +# 'file_magic [[regex]]' -- check by looking for files in library path +# which responds to the $file_magic_cmd with a given extended regex. +# If you have `file' or equivalent on your system and you're not sure +# whether `pass_all' will *always* work, you probably want this one. + +case $host_os in +aix4* | aix5*) + lt_cv_deplibs_check_method=pass_all + ;; + +beos*) + lt_cv_deplibs_check_method=pass_all + ;; + +bsdi4*) + lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib)' + lt_cv_file_magic_cmd='/usr/bin/file -L' + lt_cv_file_magic_test_file=/shlib/libc.so + ;; + +cygwin*) + # func_win32_libid is a shell function defined in ltmain.sh + lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' + lt_cv_file_magic_cmd='func_win32_libid' + ;; + +mingw* | pw32*) + # Base MSYS/MinGW do not provide the 'file' command needed by + # func_win32_libid shell function, so use a weaker test based on 'objdump'. + lt_cv_deplibs_check_method='file_magic file format pei*-i386(.*architecture: i386)?' + lt_cv_file_magic_cmd='$OBJDUMP -f' + ;; + +darwin* | rhapsody*) + lt_cv_deplibs_check_method=pass_all + ;; + +freebsd* | kfreebsd*-gnu) + if echo __ELF__ | $CC -E - | grep __ELF__ > /dev/null; then + case $host_cpu in + i*86 ) + # Not sure whether the presence of OpenBSD here was a mistake. + # Let's accept both of them until this is cleared up. + lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD)/i[3-9]86 (compact )?demand paged shared library' + lt_cv_file_magic_cmd=/usr/bin/file + lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*` + ;; + esac + else + lt_cv_deplibs_check_method=pass_all + fi + ;; + +gnu*) + lt_cv_deplibs_check_method=pass_all + ;; + +hpux10.20* | hpux11*) + lt_cv_file_magic_cmd=/usr/bin/file + case "$host_cpu" in + ia64*) + lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - IA64' + lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so + ;; + hppa*64*) + lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - PA-RISC [0-9].[0-9]' + lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl + ;; + *) + lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|PA-RISC[0-9].[0-9]) shared library' + lt_cv_file_magic_test_file=/usr/lib/libc.sl + ;; + esac + ;; + +irix5* | irix6* | nonstopux*) + case $LD in + *-32|*"-32 ") libmagic=32-bit;; + *-n32|*"-n32 ") libmagic=N32;; + *-64|*"-64 ") libmagic=64-bit;; + *) libmagic=never-match;; + esac + lt_cv_deplibs_check_method=pass_all + ;; + +# This must be Linux ELF. +linux*) + lt_cv_deplibs_check_method=pass_all + ;; + +netbsd* | netbsdelf*-gnu | knetbsd*-gnu) + if echo __ELF__ | $CC -E - | grep __ELF__ > /dev/null; then + lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$' + else + lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|_pic\.a)$' + fi + ;; + +newos6*) + lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (executable|dynamic lib)' + lt_cv_file_magic_cmd=/usr/bin/file + lt_cv_file_magic_test_file=/usr/lib/libnls.so + ;; + +nto-qnx*) + lt_cv_deplibs_check_method=unknown + ;; + +openbsd*) + lt_cv_file_magic_cmd=/usr/bin/file + lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*` + if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [LM]SB shared object' + else + lt_cv_deplibs_check_method='file_magic OpenBSD.* shared library' + fi + ;; + +osf3* | osf4* | osf5*) + lt_cv_deplibs_check_method=pass_all + ;; + +sco3.2v5*) + lt_cv_deplibs_check_method=pass_all + ;; + +solaris*) + lt_cv_deplibs_check_method=pass_all + ;; + +sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*) + case $host_vendor in + motorola) + lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib) M[0-9][0-9]* Version [0-9]' + lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*` + ;; + ncr) + lt_cv_deplibs_check_method=pass_all + ;; + sequent) + lt_cv_file_magic_cmd='/bin/file' + lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [LM]SB (shared object|dynamic lib )' + ;; + sni) + lt_cv_file_magic_cmd='/bin/file' + lt_cv_deplibs_check_method="file_magic ELF [0-9][0-9]*-bit [LM]SB dynamic lib" + lt_cv_file_magic_test_file=/lib/libc.so + ;; + siemens) + lt_cv_deplibs_check_method=pass_all + ;; + esac + ;; + +sysv5OpenUNIX8* | sysv5UnixWare7* | sysv5uw[78]* | unixware7* | sysv4*uw2*) + lt_cv_deplibs_check_method=pass_all + ;; +esac + +fi +echo "$as_me:$LINENO: result: $lt_cv_deplibs_check_method" >&5 +echo "${ECHO_T}$lt_cv_deplibs_check_method" >&6 +file_magic_cmd=$lt_cv_file_magic_cmd +deplibs_check_method=$lt_cv_deplibs_check_method +test -z "$deplibs_check_method" && deplibs_check_method=unknown + + + + +# If no C compiler was specified, use CC. +LTCC=${LTCC-"$CC"} + +# Allow CC to be a program name with arguments. +compiler=$CC + + +# Check whether --enable-libtool-lock or --disable-libtool-lock was given. +if test "${enable_libtool_lock+set}" = set; then + enableval="$enable_libtool_lock" + +fi; +test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes + +# Some flags need to be propagated to the compiler or linker for good +# libtool support. +case $host in +ia64-*-hpux*) + # Find out which ABI we are using. + echo 'int i;' > conftest.$ac_ext + if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + case `/usr/bin/file conftest.$ac_objext` in + *ELF-32*) + HPUX_IA64_MODE="32" + ;; + *ELF-64*) + HPUX_IA64_MODE="64" + ;; + esac + fi + rm -rf conftest* + ;; +*-*-irix6*) + # Find out which ABI we are using. + echo '#line 3664 "configure"' > conftest.$ac_ext + if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + if test "$lt_cv_prog_gnu_ld" = yes; then + case `/usr/bin/file conftest.$ac_objext` in + *32-bit*) + LD="${LD-ld} -melf32bsmip" + ;; + *N32*) + LD="${LD-ld} -melf32bmipn32" + ;; + *64-bit*) + LD="${LD-ld} -melf64bmip" + ;; + esac + else + case `/usr/bin/file conftest.$ac_objext` in + *32-bit*) + LD="${LD-ld} -32" + ;; + *N32*) + LD="${LD-ld} -n32" + ;; + *64-bit*) + LD="${LD-ld} -64" + ;; + esac + fi + fi + rm -rf conftest* + ;; + +x86_64-*linux*|ppc*-*linux*|powerpc*-*linux*|s390*-*linux*|sparc*-*linux*) + # Find out which ABI we are using. + echo 'int i;' > conftest.$ac_ext + if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + case "`/usr/bin/file conftest.o`" in + *32-bit*) + case $host in + x86_64-*linux*) + LD="${LD-ld} -m elf_i386" + ;; + ppc64-*linux*|powerpc64-*linux*) + LD="${LD-ld} -m elf32ppclinux" + ;; + s390x-*linux*) + LD="${LD-ld} -m elf_s390" + ;; + sparc64-*linux*) + LD="${LD-ld} -m elf32_sparc" + ;; + esac + ;; + *64-bit*) + case $host in + x86_64-*linux*) + LD="${LD-ld} -m elf_x86_64" + ;; + ppc*-*linux*|powerpc*-*linux*) + LD="${LD-ld} -m elf64ppc" + ;; + s390*-*linux*) + LD="${LD-ld} -m elf64_s390" + ;; + sparc*-*linux*) + LD="${LD-ld} -m elf64_sparc" + ;; + esac + ;; + esac + fi + rm -rf conftest* + ;; + +*-*-sco3.2v5*) + # On SCO OpenServer 5, we need -belf to get full-featured binaries. + SAVE_CFLAGS="$CFLAGS" + CFLAGS="$CFLAGS -belf" + echo "$as_me:$LINENO: checking whether the C compiler needs -belf" >&5 +echo $ECHO_N "checking whether the C compiler needs -belf... $ECHO_C" >&6 +if test "${lt_cv_cc_needs_belf+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + lt_cv_cc_needs_belf=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +lt_cv_cc_needs_belf=no +fi +rm -f conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext + ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + +fi +echo "$as_me:$LINENO: result: $lt_cv_cc_needs_belf" >&5 +echo "${ECHO_T}$lt_cv_cc_needs_belf" >&6 + if test x"$lt_cv_cc_needs_belf" != x"yes"; then + # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf + CFLAGS="$SAVE_CFLAGS" + fi + ;; + +esac + +need_locks="$enable_libtool_lock" + + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +echo "$as_me:$LINENO: checking how to run the C preprocessor" >&5 +echo $ECHO_N "checking how to run the C preprocessor... $ECHO_C" >&6 +# On Suns, sometimes $CPP names a directory. +if test -n "$CPP" && test -d "$CPP"; then + CPP= +fi +if test -z "$CPP"; then + if test "${ac_cv_prog_CPP+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + # Double quotes because CPP needs to be expanded + for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" + do + ac_preproc_ok=false +for ac_c_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # Prefer to if __STDC__ is defined, since + # exists even on freestanding compilers. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#ifdef __STDC__ +# include +#else +# include +#endif + Syntax error +_ACEOF +if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5 + (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } >/dev/null; then + if test -s conftest.err; then + ac_cpp_err=$ac_c_preproc_warn_flag + ac_cpp_err=$ac_cpp_err$ac_c_werror_flag + else + ac_cpp_err= + fi +else + ac_cpp_err=yes +fi +if test -z "$ac_cpp_err"; then + : +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + # Broken: fails on valid input. +continue +fi +rm -f conftest.err conftest.$ac_ext + + # OK, works on sane cases. Now check whether non-existent headers + # can be detected and how. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +_ACEOF +if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5 + (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } >/dev/null; then + if test -s conftest.err; then + ac_cpp_err=$ac_c_preproc_warn_flag + ac_cpp_err=$ac_cpp_err$ac_c_werror_flag + else + ac_cpp_err= + fi +else + ac_cpp_err=yes +fi +if test -z "$ac_cpp_err"; then + # Broken: success on invalid input. +continue +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + # Passes both tests. +ac_preproc_ok=: +break +fi +rm -f conftest.err conftest.$ac_ext + +done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.err conftest.$ac_ext +if $ac_preproc_ok; then + break +fi + + done + ac_cv_prog_CPP=$CPP + +fi + CPP=$ac_cv_prog_CPP +else + ac_cv_prog_CPP=$CPP +fi +echo "$as_me:$LINENO: result: $CPP" >&5 +echo "${ECHO_T}$CPP" >&6 +ac_preproc_ok=false +for ac_c_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # Prefer to if __STDC__ is defined, since + # exists even on freestanding compilers. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#ifdef __STDC__ +# include +#else +# include +#endif + Syntax error +_ACEOF +if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5 + (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } >/dev/null; then + if test -s conftest.err; then + ac_cpp_err=$ac_c_preproc_warn_flag + ac_cpp_err=$ac_cpp_err$ac_c_werror_flag + else + ac_cpp_err= + fi +else + ac_cpp_err=yes +fi +if test -z "$ac_cpp_err"; then + : +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + # Broken: fails on valid input. +continue +fi +rm -f conftest.err conftest.$ac_ext + + # OK, works on sane cases. Now check whether non-existent headers + # can be detected and how. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +_ACEOF +if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5 + (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } >/dev/null; then + if test -s conftest.err; then + ac_cpp_err=$ac_c_preproc_warn_flag + ac_cpp_err=$ac_cpp_err$ac_c_werror_flag + else + ac_cpp_err= + fi +else + ac_cpp_err=yes +fi +if test -z "$ac_cpp_err"; then + # Broken: success on invalid input. +continue +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + # Passes both tests. +ac_preproc_ok=: +break +fi +rm -f conftest.err conftest.$ac_ext + +done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.err conftest.$ac_ext +if $ac_preproc_ok; then + : +else + { { echo "$as_me:$LINENO: error: C preprocessor \"$CPP\" fails sanity check +See \`config.log' for more details." >&5 +echo "$as_me: error: C preprocessor \"$CPP\" fails sanity check +See \`config.log' for more details." >&2;} + { (exit 1); exit 1; }; } +fi + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + +echo "$as_me:$LINENO: checking for ANSI C header files" >&5 +echo $ECHO_N "checking for ANSI C header files... $ECHO_C" >&6 +if test "${ac_cv_header_stdc+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +#include +#include +#include + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest.$ac_objext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_header_stdc=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_cv_header_stdc=no +fi +rm -f conftest.err conftest.$ac_objext conftest.$ac_ext + +if test $ac_cv_header_stdc = yes; then + # SunOS 4.x string.h does not declare mem*, contrary to ANSI. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "memchr" >/dev/null 2>&1; then + : +else + ac_cv_header_stdc=no +fi +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "free" >/dev/null 2>&1; then + : +else + ac_cv_header_stdc=no +fi +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. + if test "$cross_compiling" = yes; then + : +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +#if ((' ' & 0x0FF) == 0x020) +# define ISLOWER(c) ('a' <= (c) && (c) <= 'z') +# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) +#else +# define ISLOWER(c) \ + (('a' <= (c) && (c) <= 'i') \ + || ('j' <= (c) && (c) <= 'r') \ + || ('s' <= (c) && (c) <= 'z')) +# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) +#endif + +#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) +int +main () +{ + int i; + for (i = 0; i < 256; i++) + if (XOR (islower (i), ISLOWER (i)) + || toupper (i) != TOUPPER (i)) + exit(2); + exit (0); +} +_ACEOF +rm -f conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { ac_try='./conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + : +else + echo "$as_me: program exited with status $ac_status" >&5 +echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +( exit $ac_status ) +ac_cv_header_stdc=no +fi +rm -f core *.core gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +fi +fi +fi +echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5 +echo "${ECHO_T}$ac_cv_header_stdc" >&6 +if test $ac_cv_header_stdc = yes; then + +cat >>confdefs.h <<\_ACEOF +#define STDC_HEADERS 1 +_ACEOF + +fi + +# On IRIX 5.3, sys/types and inttypes.h are conflicting. + + + + + + + + + +for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ + inttypes.h stdint.h unistd.h +do +as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` +echo "$as_me:$LINENO: checking for $ac_header" >&5 +echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6 +if eval "test \"\${$as_ac_Header+set}\" = set"; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default + +#include <$ac_header> +_ACEOF +rm -f conftest.$ac_objext +if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest.$ac_objext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + eval "$as_ac_Header=yes" +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +eval "$as_ac_Header=no" +fi +rm -f conftest.err conftest.$ac_objext conftest.$ac_ext +fi +echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5 +echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6 +if test `eval echo '${'$as_ac_Header'}'` = yes; then + cat >>confdefs.h <<_ACEOF +#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +fi + +done + + + +for ac_header in dlfcn.h +do +as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` +if eval "test \"\${$as_ac_Header+set}\" = set"; then + echo "$as_me:$LINENO: checking for $ac_header" >&5 +echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6 +if eval "test \"\${$as_ac_Header+set}\" = set"; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +fi +echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5 +echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6 +else + # Is the header compilable? +echo "$as_me:$LINENO: checking $ac_header usability" >&5 +echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6 +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +#include <$ac_header> +_ACEOF +rm -f conftest.$ac_objext +if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest.$ac_objext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_header_compiler=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_header_compiler=no +fi +rm -f conftest.err conftest.$ac_objext conftest.$ac_ext +echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 +echo "${ECHO_T}$ac_header_compiler" >&6 + +# Is the header present? +echo "$as_me:$LINENO: checking $ac_header presence" >&5 +echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6 +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include <$ac_header> +_ACEOF +if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5 + (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } >/dev/null; then + if test -s conftest.err; then + ac_cpp_err=$ac_c_preproc_warn_flag + ac_cpp_err=$ac_cpp_err$ac_c_werror_flag + else + ac_cpp_err= + fi +else + ac_cpp_err=yes +fi +if test -z "$ac_cpp_err"; then + ac_header_preproc=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_header_preproc=no +fi +rm -f conftest.err conftest.$ac_ext +echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 +echo "${ECHO_T}$ac_header_preproc" >&6 + +# So? What about this header? +case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in + yes:no: ) + { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5 +echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5 +echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;} + ac_header_preproc=yes + ;; + no:yes:* ) + { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5 +echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5 +echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5 +echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5 +echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5 +echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5 +echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;} + ( + cat <<\_ASBOX +## ------------------------------------------ ## +## Report this to the AC_PACKAGE_NAME lists. ## +## ------------------------------------------ ## +_ASBOX + ) | + sed "s/^/$as_me: WARNING: /" >&2 + ;; +esac +echo "$as_me:$LINENO: checking for $ac_header" >&5 +echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6 +if eval "test \"\${$as_ac_Header+set}\" = set"; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + eval "$as_ac_Header=\$ac_header_preproc" +fi +echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5 +echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6 + +fi +if test `eval echo '${'$as_ac_Header'}'` = yes; then + cat >>confdefs.h <<_ACEOF +#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +fi + +done + +ac_ext=cc +ac_cpp='$CXXCPP $CPPFLAGS' +ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_cxx_compiler_gnu +if test -n "$ac_tool_prefix"; then + for ac_prog in $CCC g++ c++ gpp aCC CC cxx cc++ cl FCC KCC RCC xlC_r xlC + do + # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. +set dummy $ac_tool_prefix$ac_prog; ac_word=$2 +echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 +if test "${ac_cv_prog_CXX+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$CXX"; then + ac_cv_prog_CXX="$CXX" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_CXX="$ac_tool_prefix$ac_prog" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done + +fi +fi +CXX=$ac_cv_prog_CXX +if test -n "$CXX"; then + echo "$as_me:$LINENO: result: $CXX" >&5 +echo "${ECHO_T}$CXX" >&6 +else + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 +fi + + test -n "$CXX" && break + done +fi +if test -z "$CXX"; then + ac_ct_CXX=$CXX + for ac_prog in $CCC g++ c++ gpp aCC CC cxx cc++ cl FCC KCC RCC xlC_r xlC +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 +if test "${ac_cv_prog_ac_ct_CXX+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$ac_ct_CXX"; then + ac_cv_prog_ac_ct_CXX="$ac_ct_CXX" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_CXX="$ac_prog" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done + +fi +fi +ac_ct_CXX=$ac_cv_prog_ac_ct_CXX +if test -n "$ac_ct_CXX"; then + echo "$as_me:$LINENO: result: $ac_ct_CXX" >&5 +echo "${ECHO_T}$ac_ct_CXX" >&6 +else + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 +fi + + test -n "$ac_ct_CXX" && break +done +test -n "$ac_ct_CXX" || ac_ct_CXX="g++" + + CXX=$ac_ct_CXX +fi + + +# Provide some information about the compiler. +echo "$as_me:$LINENO:" \ + "checking for C++ compiler version" >&5 +ac_compiler=`set X $ac_compile; echo $2` +{ (eval echo "$as_me:$LINENO: \"$ac_compiler --version &5\"") >&5 + (eval $ac_compiler --version &5) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } +{ (eval echo "$as_me:$LINENO: \"$ac_compiler -v &5\"") >&5 + (eval $ac_compiler -v &5) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } +{ (eval echo "$as_me:$LINENO: \"$ac_compiler -V &5\"") >&5 + (eval $ac_compiler -V &5) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } + +echo "$as_me:$LINENO: checking whether we are using the GNU C++ compiler" >&5 +echo $ECHO_N "checking whether we are using the GNU C++ compiler... $ECHO_C" >&6 +if test "${ac_cv_cxx_compiler_gnu+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ +#ifndef __GNUC__ + choke me +#endif + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_cxx_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest.$ac_objext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_compiler_gnu=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_compiler_gnu=no +fi +rm -f conftest.err conftest.$ac_objext conftest.$ac_ext +ac_cv_cxx_compiler_gnu=$ac_compiler_gnu + +fi +echo "$as_me:$LINENO: result: $ac_cv_cxx_compiler_gnu" >&5 +echo "${ECHO_T}$ac_cv_cxx_compiler_gnu" >&6 +GXX=`test $ac_compiler_gnu = yes && echo yes` +ac_test_CXXFLAGS=${CXXFLAGS+set} +ac_save_CXXFLAGS=$CXXFLAGS +CXXFLAGS="-g" +echo "$as_me:$LINENO: checking whether $CXX accepts -g" >&5 +echo $ECHO_N "checking whether $CXX accepts -g... $ECHO_C" >&6 +if test "${ac_cv_prog_cxx_g+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_cxx_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest.$ac_objext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_prog_cxx_g=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_cv_prog_cxx_g=no +fi +rm -f conftest.err conftest.$ac_objext conftest.$ac_ext +fi +echo "$as_me:$LINENO: result: $ac_cv_prog_cxx_g" >&5 +echo "${ECHO_T}$ac_cv_prog_cxx_g" >&6 +if test "$ac_test_CXXFLAGS" = set; then + CXXFLAGS=$ac_save_CXXFLAGS +elif test $ac_cv_prog_cxx_g = yes; then + if test "$GXX" = yes; then + CXXFLAGS="-g -O2" + else + CXXFLAGS="-g" + fi +else + if test "$GXX" = yes; then + CXXFLAGS="-O2" + else + CXXFLAGS= + fi +fi +for ac_declaration in \ + '' \ + 'extern "C" void std::exit (int) throw (); using std::exit;' \ + 'extern "C" void std::exit (int); using std::exit;' \ + 'extern "C" void exit (int) throw ();' \ + 'extern "C" void exit (int);' \ + 'void exit (int);' +do + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_declaration +#include +int +main () +{ +exit (42); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_cxx_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest.$ac_objext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + : +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +continue +fi +rm -f conftest.err conftest.$ac_objext conftest.$ac_ext + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_declaration +int +main () +{ +exit (42); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_cxx_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest.$ac_objext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + break +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +fi +rm -f conftest.err conftest.$ac_objext conftest.$ac_ext +done +rm -f conftest* +if test -n "$ac_declaration"; then + echo '#ifdef __cplusplus' >>confdefs.h + echo $ac_declaration >>confdefs.h + echo '#endif' >>confdefs.h +fi + +ac_ext=cc +ac_cpp='$CXXCPP $CPPFLAGS' +ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_cxx_compiler_gnu + +depcc="$CXX" am_compiler_list= + +echo "$as_me:$LINENO: checking dependency style of $depcc" >&5 +echo $ECHO_N "checking dependency style of $depcc... $ECHO_C" >&6 +if test "${am_cv_CXX_dependencies_compiler_type+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then + # We make a subdir and do the tests there. Otherwise we can end up + # making bogus files that we don't know about and never remove. For + # instance it was reported that on HP-UX the gcc test will end up + # making a dummy file named `D' -- because `-MD' means `put the output + # in D'. + mkdir conftest.dir + # Copy depcomp to subdir because otherwise we won't find it if we're + # using a relative directory. + cp "$am_depcomp" conftest.dir + cd conftest.dir + # We will build objects and dependencies in a subdirectory because + # it helps to detect inapplicable dependency modes. For instance + # both Tru64's cc and ICC support -MD to output dependencies as a + # side effect of compilation, but ICC will put the dependencies in + # the current directory while Tru64 will put them in the object + # directory. + mkdir sub + + am_cv_CXX_dependencies_compiler_type=none + if test "$am_compiler_list" = ""; then + am_compiler_list=`sed -n 's/^#*\([a-zA-Z0-9]*\))$/\1/p' < ./depcomp` + fi + for depmode in $am_compiler_list; do + # Setup a source with many dependencies, because some compilers + # like to wrap large dependency lists on column 80 (with \), and + # we should not choose a depcomp mode which is confused by this. + # + # We need to recreate these files for each test, as the compiler may + # overwrite some of them when testing with obscure command lines. + # This happens at least with the AIX C compiler. + : > sub/conftest.c + for i in 1 2 3 4 5 6; do + echo '#include "conftst'$i'.h"' >> sub/conftest.c + # Using `: > sub/conftst$i.h' creates only sub/conftst1.h with + # Solaris 8's {/usr,}/bin/sh. + touch sub/conftst$i.h + done + echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf + + case $depmode in + nosideeffect) + # after this tag, mechanisms are not by side-effect, so they'll + # only be used when explicitly requested + if test "x$enable_dependency_tracking" = xyes; then + continue + else + break + fi + ;; + none) break ;; + esac + # We check with `-c' and `-o' for the sake of the "dashmstdout" + # mode. It turns out that the SunPro C++ compiler does not properly + # handle `-M -o', and we need to detect this. + if depmode=$depmode \ + source=sub/conftest.c object=sub/conftest.${OBJEXT-o} \ + depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ + $SHELL ./depcomp $depcc -c -o sub/conftest.${OBJEXT-o} sub/conftest.c \ + >/dev/null 2>conftest.err && + grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && + grep sub/conftest.${OBJEXT-o} sub/conftest.Po > /dev/null 2>&1 && + ${MAKE-make} -s -f confmf > /dev/null 2>&1; then + # icc doesn't choke on unknown options, it will just issue warnings + # or remarks (even with -Werror). So we grep stderr for any message + # that says an option was ignored or not supported. + # When given -MP, icc 7.0 and 7.1 complain thusly: + # icc: Command line warning: ignoring option '-M'; no argument required + # The diagnosis changed in icc 8.0: + # icc: Command line remark: option '-MP' not supported + if (grep 'ignoring option' conftest.err || + grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else + am_cv_CXX_dependencies_compiler_type=$depmode + break + fi + fi + done + + cd .. + rm -rf conftest.dir +else + am_cv_CXX_dependencies_compiler_type=none +fi + +fi +echo "$as_me:$LINENO: result: $am_cv_CXX_dependencies_compiler_type" >&5 +echo "${ECHO_T}$am_cv_CXX_dependencies_compiler_type" >&6 +CXXDEPMODE=depmode=$am_cv_CXX_dependencies_compiler_type + + + +if + test "x$enable_dependency_tracking" != xno \ + && test "$am_cv_CXX_dependencies_compiler_type" = gcc3; then + am__fastdepCXX_TRUE= + am__fastdepCXX_FALSE='#' +else + am__fastdepCXX_TRUE='#' + am__fastdepCXX_FALSE= +fi + + +ac_ext=cc +ac_cpp='$CXXCPP $CPPFLAGS' +ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_cxx_compiler_gnu +echo "$as_me:$LINENO: checking how to run the C++ preprocessor" >&5 +echo $ECHO_N "checking how to run the C++ preprocessor... $ECHO_C" >&6 +if test -z "$CXXCPP"; then + if test "${ac_cv_prog_CXXCPP+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + # Double quotes because CXXCPP needs to be expanded + for CXXCPP in "$CXX -E" "/lib/cpp" + do + ac_preproc_ok=false +for ac_cxx_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # Prefer to if __STDC__ is defined, since + # exists even on freestanding compilers. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#ifdef __STDC__ +# include +#else +# include +#endif + Syntax error +_ACEOF +if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5 + (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } >/dev/null; then + if test -s conftest.err; then + ac_cpp_err=$ac_cxx_preproc_warn_flag + ac_cpp_err=$ac_cpp_err$ac_cxx_werror_flag + else + ac_cpp_err= + fi +else + ac_cpp_err=yes +fi +if test -z "$ac_cpp_err"; then + : +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + # Broken: fails on valid input. +continue +fi +rm -f conftest.err conftest.$ac_ext + + # OK, works on sane cases. Now check whether non-existent headers + # can be detected and how. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +_ACEOF +if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5 + (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } >/dev/null; then + if test -s conftest.err; then + ac_cpp_err=$ac_cxx_preproc_warn_flag + ac_cpp_err=$ac_cpp_err$ac_cxx_werror_flag + else + ac_cpp_err= + fi +else + ac_cpp_err=yes +fi +if test -z "$ac_cpp_err"; then + # Broken: success on invalid input. +continue +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + # Passes both tests. +ac_preproc_ok=: +break +fi +rm -f conftest.err conftest.$ac_ext + +done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.err conftest.$ac_ext +if $ac_preproc_ok; then + break +fi + + done + ac_cv_prog_CXXCPP=$CXXCPP + +fi + CXXCPP=$ac_cv_prog_CXXCPP +else + ac_cv_prog_CXXCPP=$CXXCPP +fi +echo "$as_me:$LINENO: result: $CXXCPP" >&5 +echo "${ECHO_T}$CXXCPP" >&6 +ac_preproc_ok=false +for ac_cxx_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # Prefer to if __STDC__ is defined, since + # exists even on freestanding compilers. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#ifdef __STDC__ +# include +#else +# include +#endif + Syntax error +_ACEOF +if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5 + (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } >/dev/null; then + if test -s conftest.err; then + ac_cpp_err=$ac_cxx_preproc_warn_flag + ac_cpp_err=$ac_cpp_err$ac_cxx_werror_flag + else + ac_cpp_err= + fi +else + ac_cpp_err=yes +fi +if test -z "$ac_cpp_err"; then + : +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + # Broken: fails on valid input. +continue +fi +rm -f conftest.err conftest.$ac_ext + + # OK, works on sane cases. Now check whether non-existent headers + # can be detected and how. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +_ACEOF +if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5 + (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } >/dev/null; then + if test -s conftest.err; then + ac_cpp_err=$ac_cxx_preproc_warn_flag + ac_cpp_err=$ac_cpp_err$ac_cxx_werror_flag + else + ac_cpp_err= + fi +else + ac_cpp_err=yes +fi +if test -z "$ac_cpp_err"; then + # Broken: success on invalid input. +continue +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + # Passes both tests. +ac_preproc_ok=: +break +fi +rm -f conftest.err conftest.$ac_ext + +done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.err conftest.$ac_ext +if $ac_preproc_ok; then + : +else + { { echo "$as_me:$LINENO: error: C++ preprocessor \"$CXXCPP\" fails sanity check +See \`config.log' for more details." >&5 +echo "$as_me: error: C++ preprocessor \"$CXXCPP\" fails sanity check +See \`config.log' for more details." >&2;} + { (exit 1); exit 1; }; } +fi + +ac_ext=cc +ac_cpp='$CXXCPP $CPPFLAGS' +ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_cxx_compiler_gnu + + +ac_ext=f +ac_compile='$F77 -c $FFLAGS conftest.$ac_ext >&5' +ac_link='$F77 -o conftest$ac_exeext $FFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_f77_compiler_gnu +if test -n "$ac_tool_prefix"; then + for ac_prog in g77 f77 xlf frt pgf77 fort77 fl32 af77 f90 xlf90 pgf90 epcf90 f95 fort xlf95 ifc efc pgf95 lf95 gfortran + do + # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. +set dummy $ac_tool_prefix$ac_prog; ac_word=$2 +echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 +if test "${ac_cv_prog_F77+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$F77"; then + ac_cv_prog_F77="$F77" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_F77="$ac_tool_prefix$ac_prog" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done + +fi +fi +F77=$ac_cv_prog_F77 +if test -n "$F77"; then + echo "$as_me:$LINENO: result: $F77" >&5 +echo "${ECHO_T}$F77" >&6 +else + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 +fi + + test -n "$F77" && break + done +fi +if test -z "$F77"; then + ac_ct_F77=$F77 + for ac_prog in g77 f77 xlf frt pgf77 fort77 fl32 af77 f90 xlf90 pgf90 epcf90 f95 fort xlf95 ifc efc pgf95 lf95 gfortran +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 +if test "${ac_cv_prog_ac_ct_F77+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$ac_ct_F77"; then + ac_cv_prog_ac_ct_F77="$ac_ct_F77" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_F77="$ac_prog" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done + +fi +fi +ac_ct_F77=$ac_cv_prog_ac_ct_F77 +if test -n "$ac_ct_F77"; then + echo "$as_me:$LINENO: result: $ac_ct_F77" >&5 +echo "${ECHO_T}$ac_ct_F77" >&6 +else + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 +fi + + test -n "$ac_ct_F77" && break +done + + F77=$ac_ct_F77 +fi + + +# Provide some information about the compiler. +echo "$as_me:5228:" \ + "checking for Fortran 77 compiler version" >&5 +ac_compiler=`set X $ac_compile; echo $2` +{ (eval echo "$as_me:$LINENO: \"$ac_compiler --version &5\"") >&5 + (eval $ac_compiler --version &5) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } +{ (eval echo "$as_me:$LINENO: \"$ac_compiler -v &5\"") >&5 + (eval $ac_compiler -v &5) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } +{ (eval echo "$as_me:$LINENO: \"$ac_compiler -V &5\"") >&5 + (eval $ac_compiler -V &5) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } +rm -f a.out + +# If we don't use `.F' as extension, the preprocessor is not run on the +# input file. (Note that this only needs to work for GNU compilers.) +ac_save_ext=$ac_ext +ac_ext=F +echo "$as_me:$LINENO: checking whether we are using the GNU Fortran 77 compiler" >&5 +echo $ECHO_N "checking whether we are using the GNU Fortran 77 compiler... $ECHO_C" >&6 +if test "${ac_cv_f77_compiler_gnu+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF + program main +#ifndef __GNUC__ + choke me +#endif + + end +_ACEOF +rm -f conftest.$ac_objext +if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_f77_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest.$ac_objext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_compiler_gnu=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_compiler_gnu=no +fi +rm -f conftest.err conftest.$ac_objext conftest.$ac_ext +ac_cv_f77_compiler_gnu=$ac_compiler_gnu + +fi +echo "$as_me:$LINENO: result: $ac_cv_f77_compiler_gnu" >&5 +echo "${ECHO_T}$ac_cv_f77_compiler_gnu" >&6 +ac_ext=$ac_save_ext +ac_test_FFLAGS=${FFLAGS+set} +ac_save_FFLAGS=$FFLAGS +FFLAGS= +echo "$as_me:$LINENO: checking whether $F77 accepts -g" >&5 +echo $ECHO_N "checking whether $F77 accepts -g... $ECHO_C" >&6 +if test "${ac_cv_prog_f77_g+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + FFLAGS=-g +cat >conftest.$ac_ext <<_ACEOF + program main + + end +_ACEOF +rm -f conftest.$ac_objext +if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_f77_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest.$ac_objext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_prog_f77_g=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_cv_prog_f77_g=no +fi +rm -f conftest.err conftest.$ac_objext conftest.$ac_ext + +fi +echo "$as_me:$LINENO: result: $ac_cv_prog_f77_g" >&5 +echo "${ECHO_T}$ac_cv_prog_f77_g" >&6 +if test "$ac_test_FFLAGS" = set; then + FFLAGS=$ac_save_FFLAGS +elif test $ac_cv_prog_f77_g = yes; then + if test "x$ac_cv_f77_compiler_gnu" = xyes; then + FFLAGS="-g -O2" + else + FFLAGS="-g" + fi +else + if test "x$ac_cv_f77_compiler_gnu" = xyes; then + FFLAGS="-O2" + else + FFLAGS= + fi +fi + +G77=`test $ac_compiler_gnu = yes && echo yes` +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + + +# Autoconf 2.13's AC_OBJEXT and AC_EXEEXT macros only works for C compilers! + +# find the maximum length of command line arguments +echo "$as_me:$LINENO: checking the maximum length of command line arguments" >&5 +echo $ECHO_N "checking the maximum length of command line arguments... $ECHO_C" >&6 +if test "${lt_cv_sys_max_cmd_len+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + i=0 + teststring="ABCD" + + case $build_os in + msdosdjgpp*) + # On DJGPP, this test can blow up pretty badly due to problems in libc + # (any single argument exceeding 2000 bytes causes a buffer overrun + # during glob expansion). Even if it were fixed, the result of this + # check would be larger than it should be. + lt_cv_sys_max_cmd_len=12288; # 12K is about right + ;; + + gnu*) + # Under GNU Hurd, this test is not required because there is + # no limit to the length of command line arguments. + # Libtool will interpret -1 as no limit whatsoever + lt_cv_sys_max_cmd_len=-1; + ;; + + cygwin* | mingw*) + # On Win9x/ME, this test blows up -- it succeeds, but takes + # about 5 minutes as the teststring grows exponentially. + # Worse, since 9x/ME are not pre-emptively multitasking, + # you end up with a "frozen" computer, even though with patience + # the test eventually succeeds (with a max line length of 256k). + # Instead, let's just punt: use the minimum linelength reported by + # all of the supported platforms: 8192 (on NT/2K/XP). + lt_cv_sys_max_cmd_len=8192; + ;; + + amigaos*) + # On AmigaOS with pdksh, this test takes hours, literally. + # So we just punt and use a minimum line length of 8192. + lt_cv_sys_max_cmd_len=8192; + ;; + + *) + # If test is not a shell built-in, we'll probably end up computing a + # maximum length that is only half of the actual maximum length, but + # we can't tell. + while (test "X"`$CONFIG_SHELL $0 --fallback-echo "X$teststring" 2>/dev/null` \ + = "XX$teststring") >/dev/null 2>&1 && + new_result=`expr "X$teststring" : ".*" 2>&1` && + lt_cv_sys_max_cmd_len=$new_result && + test $i != 17 # 1/2 MB should be enough + do + i=`expr $i + 1` + teststring=$teststring$teststring + done + teststring= + # Add a significant safety factor because C++ compilers can tack on massive + # amounts of additional arguments before passing them to the linker. + # It appears as though 1/2 is a usable value. + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2` + ;; + esac + +fi + +if test -n $lt_cv_sys_max_cmd_len ; then + echo "$as_me:$LINENO: result: $lt_cv_sys_max_cmd_len" >&5 +echo "${ECHO_T}$lt_cv_sys_max_cmd_len" >&6 +else + echo "$as_me:$LINENO: result: none" >&5 +echo "${ECHO_T}none" >&6 +fi + + + + +# Check for command to grab the raw symbol name followed by C symbol from nm. +echo "$as_me:$LINENO: checking command to parse $NM output from $compiler object" >&5 +echo $ECHO_N "checking command to parse $NM output from $compiler object... $ECHO_C" >&6 +if test "${lt_cv_sys_global_symbol_pipe+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + +# These are sane defaults that work on at least a few old systems. +# [They come from Ultrix. What could be older than Ultrix?!! ;)] + +# Character class describing NM global symbol codes. +symcode='[BCDEGRST]' + +# Regexp to match symbols that can be accessed directly from C. +sympat='\([_A-Za-z][_A-Za-z0-9]*\)' + +# Transform the above into a raw symbol and a C symbol. +symxfrm='\1 \2\3 \3' + +# Transform an extracted symbol line into a proper C declaration +lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^. .* \(.*\)$/extern int \1;/p'" + +# Transform an extracted symbol line into symbol name and symbol address +lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([^ ]*\) $/ {\\\"\1\\\", (lt_ptr) 0},/p' -e 's/^$symcode \([^ ]*\) \([^ ]*\)$/ {\"\2\", (lt_ptr) \&\2},/p'" + +# Define system-specific variables. +case $host_os in +aix*) + symcode='[BCDT]' + ;; +cygwin* | mingw* | pw32*) + symcode='[ABCDGISTW]' + ;; +hpux*) # Its linker distinguishes data from code symbols + if test "$host_cpu" = ia64; then + symcode='[ABCDEGRST]' + fi + lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'" + lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([^ ]*\) $/ {\\\"\1\\\", (lt_ptr) 0},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\)$/ {\"\2\", (lt_ptr) \&\2},/p'" + ;; +irix* | nonstopux*) + symcode='[BCDEGRST]' + ;; +osf*) + symcode='[BCDEGQRST]' + ;; +solaris* | sysv5*) + symcode='[BDRT]' + ;; +sysv4) + symcode='[DFNSTU]' + ;; +esac + +# Handle CRLF in mingw tool chain +opt_cr= +case $build_os in +mingw*) + opt_cr=`echo 'x\{0,1\}' | tr x '\015'` # option cr in regexp + ;; +esac + +# If we're using GNU nm, then use its standard symbol codes. +case `$NM -V 2>&1` in +*GNU* | *'with BFD'*) + symcode='[ABCDGIRSTW]' ;; +esac + +# Try without a prefix undercore, then with it. +for ac_symprfx in "" "_"; do + + # Write the raw and C identifiers. + lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[ ]\($symcode$symcode*\)[ ][ ]*\($ac_symprfx\)$sympat$opt_cr$/$symxfrm/p'" + + # Check to see that the pipe works correctly. + pipe_works=no + + rm -f conftest* + cat > conftest.$ac_ext <&5 + (eval $ac_compile) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + # Now try to grab the symbols. + nlist=conftest.nm + if { (eval echo "$as_me:$LINENO: \"$NM conftest.$ac_objext \| $lt_cv_sys_global_symbol_pipe \> $nlist\"") >&5 + (eval $NM conftest.$ac_objext \| $lt_cv_sys_global_symbol_pipe \> $nlist) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && test -s "$nlist"; then + # Try sorting and uniquifying the output. + if sort "$nlist" | uniq > "$nlist"T; then + mv -f "$nlist"T "$nlist" + else + rm -f "$nlist"T + fi + + # Make sure that we snagged all the symbols we need. + if grep ' nm_test_var$' "$nlist" >/dev/null; then + if grep ' nm_test_func$' "$nlist" >/dev/null; then + cat < conftest.$ac_ext +#ifdef __cplusplus +extern "C" { +#endif + +EOF + # Now generate the symbol file. + eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | grep -v main >> conftest.$ac_ext' + + cat <> conftest.$ac_ext +#if defined (__STDC__) && __STDC__ +# define lt_ptr_t void * +#else +# define lt_ptr_t char * +# define const +#endif + +/* The mapping between symbol names and symbols. */ +const struct { + const char *name; + lt_ptr_t address; +} +lt_preloaded_symbols[] = +{ +EOF + $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/ {\"\2\", (lt_ptr_t) \&\2},/" < "$nlist" | grep -v main >> conftest.$ac_ext + cat <<\EOF >> conftest.$ac_ext + {0, (lt_ptr_t) 0} +}; + +#ifdef __cplusplus +} +#endif +EOF + # Now try linking the two files. + mv conftest.$ac_objext conftstm.$ac_objext + lt_save_LIBS="$LIBS" + lt_save_CFLAGS="$CFLAGS" + LIBS="conftstm.$ac_objext" + CFLAGS="$CFLAGS$lt_prog_compiler_no_builtin_flag" + if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && test -s conftest${ac_exeext}; then + pipe_works=yes + fi + LIBS="$lt_save_LIBS" + CFLAGS="$lt_save_CFLAGS" + else + echo "cannot find nm_test_func in $nlist" >&5 + fi + else + echo "cannot find nm_test_var in $nlist" >&5 + fi + else + echo "cannot run $lt_cv_sys_global_symbol_pipe" >&5 + fi + else + echo "$progname: failed program was:" >&5 + cat conftest.$ac_ext >&5 + fi + rm -f conftest* conftst* + + # Do not use the global_symbol_pipe unless it works. + if test "$pipe_works" = yes; then + break + else + lt_cv_sys_global_symbol_pipe= + fi +done + +fi + +if test -z "$lt_cv_sys_global_symbol_pipe"; then + lt_cv_sys_global_symbol_to_cdecl= +fi +if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then + echo "$as_me:$LINENO: result: failed" >&5 +echo "${ECHO_T}failed" >&6 +else + echo "$as_me:$LINENO: result: ok" >&5 +echo "${ECHO_T}ok" >&6 +fi + +echo "$as_me:$LINENO: checking for objdir" >&5 +echo $ECHO_N "checking for objdir... $ECHO_C" >&6 +if test "${lt_cv_objdir+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + rm -f .libs 2>/dev/null +mkdir .libs 2>/dev/null +if test -d .libs; then + lt_cv_objdir=.libs +else + # MS-DOS does not allow filenames that begin with a dot. + lt_cv_objdir=_libs +fi +rmdir .libs 2>/dev/null +fi +echo "$as_me:$LINENO: result: $lt_cv_objdir" >&5 +echo "${ECHO_T}$lt_cv_objdir" >&6 +objdir=$lt_cv_objdir + + + + + +case $host_os in +aix3*) + # AIX sometimes has problems with the GCC collect2 program. For some + # reason, if we set the COLLECT_NAMES environment variable, the problems + # vanish in a puff of smoke. + if test "X${COLLECT_NAMES+set}" != Xset; then + COLLECT_NAMES= + export COLLECT_NAMES + fi + ;; +esac + +# Sed substitution that helps us do robust quoting. It backslashifies +# metacharacters that are still active within double-quoted strings. +Xsed='sed -e s/^X//' +sed_quote_subst='s/\([\\"\\`$\\\\]\)/\\\1/g' + +# Same as above, but do not quote variable references. +double_quote_subst='s/\([\\"\\`\\\\]\)/\\\1/g' + +# Sed substitution to delay expansion of an escaped shell variable in a +# double_quote_subst'ed string. +delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g' + +# Sed substitution to avoid accidental globbing in evaled expressions +no_glob_subst='s/\*/\\\*/g' + +# Constants: +rm="rm -f" + +# Global variables: +default_ofile=libtool +can_build_shared=yes + +# All known linkers require a `.a' archive for static linking (except M$VC, +# which needs '.lib'). +libext=a +ltmain="$ac_aux_dir/ltmain.sh" +ofile="$default_ofile" +with_gnu_ld="$lt_cv_prog_gnu_ld" + +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}ar", so it can be a program name with args. +set dummy ${ac_tool_prefix}ar; ac_word=$2 +echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 +if test "${ac_cv_prog_AR+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$AR"; then + ac_cv_prog_AR="$AR" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_AR="${ac_tool_prefix}ar" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done + +fi +fi +AR=$ac_cv_prog_AR +if test -n "$AR"; then + echo "$as_me:$LINENO: result: $AR" >&5 +echo "${ECHO_T}$AR" >&6 +else + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 +fi + +fi +if test -z "$ac_cv_prog_AR"; then + ac_ct_AR=$AR + # Extract the first word of "ar", so it can be a program name with args. +set dummy ar; ac_word=$2 +echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 +if test "${ac_cv_prog_ac_ct_AR+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$ac_ct_AR"; then + ac_cv_prog_ac_ct_AR="$ac_ct_AR" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_AR="ar" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done + + test -z "$ac_cv_prog_ac_ct_AR" && ac_cv_prog_ac_ct_AR="false" +fi +fi +ac_ct_AR=$ac_cv_prog_ac_ct_AR +if test -n "$ac_ct_AR"; then + echo "$as_me:$LINENO: result: $ac_ct_AR" >&5 +echo "${ECHO_T}$ac_ct_AR" >&6 +else + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 +fi + + AR=$ac_ct_AR +else + AR="$ac_cv_prog_AR" +fi + +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args. +set dummy ${ac_tool_prefix}ranlib; ac_word=$2 +echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 +if test "${ac_cv_prog_RANLIB+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$RANLIB"; then + ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done + +fi +fi +RANLIB=$ac_cv_prog_RANLIB +if test -n "$RANLIB"; then + echo "$as_me:$LINENO: result: $RANLIB" >&5 +echo "${ECHO_T}$RANLIB" >&6 +else + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 +fi + +fi +if test -z "$ac_cv_prog_RANLIB"; then + ac_ct_RANLIB=$RANLIB + # Extract the first word of "ranlib", so it can be a program name with args. +set dummy ranlib; ac_word=$2 +echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 +if test "${ac_cv_prog_ac_ct_RANLIB+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$ac_ct_RANLIB"; then + ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_RANLIB="ranlib" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done + + test -z "$ac_cv_prog_ac_ct_RANLIB" && ac_cv_prog_ac_ct_RANLIB=":" +fi +fi +ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB +if test -n "$ac_ct_RANLIB"; then + echo "$as_me:$LINENO: result: $ac_ct_RANLIB" >&5 +echo "${ECHO_T}$ac_ct_RANLIB" >&6 +else + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 +fi + + RANLIB=$ac_ct_RANLIB +else + RANLIB="$ac_cv_prog_RANLIB" +fi + +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args. +set dummy ${ac_tool_prefix}strip; ac_word=$2 +echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 +if test "${ac_cv_prog_STRIP+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$STRIP"; then + ac_cv_prog_STRIP="$STRIP" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_STRIP="${ac_tool_prefix}strip" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done + +fi +fi +STRIP=$ac_cv_prog_STRIP +if test -n "$STRIP"; then + echo "$as_me:$LINENO: result: $STRIP" >&5 +echo "${ECHO_T}$STRIP" >&6 +else + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 +fi + +fi +if test -z "$ac_cv_prog_STRIP"; then + ac_ct_STRIP=$STRIP + # Extract the first word of "strip", so it can be a program name with args. +set dummy strip; ac_word=$2 +echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 +if test "${ac_cv_prog_ac_ct_STRIP+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$ac_ct_STRIP"; then + ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_STRIP="strip" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done + + test -z "$ac_cv_prog_ac_ct_STRIP" && ac_cv_prog_ac_ct_STRIP=":" +fi +fi +ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP +if test -n "$ac_ct_STRIP"; then + echo "$as_me:$LINENO: result: $ac_ct_STRIP" >&5 +echo "${ECHO_T}$ac_ct_STRIP" >&6 +else + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 +fi + + STRIP=$ac_ct_STRIP +else + STRIP="$ac_cv_prog_STRIP" +fi + + +old_CC="$CC" +old_CFLAGS="$CFLAGS" + +# Set sane defaults for various variables +test -z "$AR" && AR=ar +test -z "$AR_FLAGS" && AR_FLAGS=cru +test -z "$AS" && AS=as +test -z "$CC" && CC=cc +test -z "$LTCC" && LTCC=$CC +test -z "$DLLTOOL" && DLLTOOL=dlltool +test -z "$LD" && LD=ld +test -z "$LN_S" && LN_S="ln -s" +test -z "$MAGIC_CMD" && MAGIC_CMD=file +test -z "$NM" && NM=nm +test -z "$SED" && SED=sed +test -z "$OBJDUMP" && OBJDUMP=objdump +test -z "$RANLIB" && RANLIB=: +test -z "$STRIP" && STRIP=: +test -z "$ac_objext" && ac_objext=o + +# Determine commands to create old-style static archives. +old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs$old_deplibs' +old_postinstall_cmds='chmod 644 $oldlib' +old_postuninstall_cmds= + +if test -n "$RANLIB"; then + case $host_os in + openbsd*) + old_postinstall_cmds="\$RANLIB -t \$oldlib~$old_postinstall_cmds" + ;; + *) + old_postinstall_cmds="\$RANLIB \$oldlib~$old_postinstall_cmds" + ;; + esac + old_archive_cmds="$old_archive_cmds~\$RANLIB \$oldlib" +fi + +# Only perform the check for file, if the check method requires it +case $deplibs_check_method in +file_magic*) + if test "$file_magic_cmd" = '$MAGIC_CMD'; then + echo "$as_me:$LINENO: checking for ${ac_tool_prefix}file" >&5 +echo $ECHO_N "checking for ${ac_tool_prefix}file... $ECHO_C" >&6 +if test "${lt_cv_path_MAGIC_CMD+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + case $MAGIC_CMD in +[\\/*] | ?:[\\/]*) + lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path. + ;; +*) + lt_save_MAGIC_CMD="$MAGIC_CMD" + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR + ac_dummy="/usr/bin$PATH_SEPARATOR$PATH" + for ac_dir in $ac_dummy; do + IFS="$lt_save_ifs" + test -z "$ac_dir" && ac_dir=. + if test -f $ac_dir/${ac_tool_prefix}file; then + lt_cv_path_MAGIC_CMD="$ac_dir/${ac_tool_prefix}file" + if test -n "$file_magic_test_file"; then + case $deplibs_check_method in + "file_magic "*) + file_magic_regex="`expr \"$deplibs_check_method\" : \"file_magic \(.*\)\"`" + MAGIC_CMD="$lt_cv_path_MAGIC_CMD" + if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | + $EGREP "$file_magic_regex" > /dev/null; then + : + else + cat <&2 + +*** Warning: the command libtool uses to detect shared libraries, +*** $file_magic_cmd, produces output that libtool cannot recognize. +*** The result is that libtool may fail to recognize shared libraries +*** as such. This will affect the creation of libtool libraries that +*** depend on shared libraries, but programs linked with such libtool +*** libraries will work regardless of this problem. Nevertheless, you +*** may want to report the problem to your system manager and/or to +*** bug-libtool@gnu.org + +EOF + fi ;; + esac + fi + break + fi + done + IFS="$lt_save_ifs" + MAGIC_CMD="$lt_save_MAGIC_CMD" + ;; +esac +fi + +MAGIC_CMD="$lt_cv_path_MAGIC_CMD" +if test -n "$MAGIC_CMD"; then + echo "$as_me:$LINENO: result: $MAGIC_CMD" >&5 +echo "${ECHO_T}$MAGIC_CMD" >&6 +else + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 +fi + +if test -z "$lt_cv_path_MAGIC_CMD"; then + if test -n "$ac_tool_prefix"; then + echo "$as_me:$LINENO: checking for file" >&5 +echo $ECHO_N "checking for file... $ECHO_C" >&6 +if test "${lt_cv_path_MAGIC_CMD+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + case $MAGIC_CMD in +[\\/*] | ?:[\\/]*) + lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path. + ;; +*) + lt_save_MAGIC_CMD="$MAGIC_CMD" + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR + ac_dummy="/usr/bin$PATH_SEPARATOR$PATH" + for ac_dir in $ac_dummy; do + IFS="$lt_save_ifs" + test -z "$ac_dir" && ac_dir=. + if test -f $ac_dir/file; then + lt_cv_path_MAGIC_CMD="$ac_dir/file" + if test -n "$file_magic_test_file"; then + case $deplibs_check_method in + "file_magic "*) + file_magic_regex="`expr \"$deplibs_check_method\" : \"file_magic \(.*\)\"`" + MAGIC_CMD="$lt_cv_path_MAGIC_CMD" + if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | + $EGREP "$file_magic_regex" > /dev/null; then + : + else + cat <&2 + +*** Warning: the command libtool uses to detect shared libraries, +*** $file_magic_cmd, produces output that libtool cannot recognize. +*** The result is that libtool may fail to recognize shared libraries +*** as such. This will affect the creation of libtool libraries that +*** depend on shared libraries, but programs linked with such libtool +*** libraries will work regardless of this problem. Nevertheless, you +*** may want to report the problem to your system manager and/or to +*** bug-libtool@gnu.org + +EOF + fi ;; + esac + fi + break + fi + done + IFS="$lt_save_ifs" + MAGIC_CMD="$lt_save_MAGIC_CMD" + ;; +esac +fi + +MAGIC_CMD="$lt_cv_path_MAGIC_CMD" +if test -n "$MAGIC_CMD"; then + echo "$as_me:$LINENO: result: $MAGIC_CMD" >&5 +echo "${ECHO_T}$MAGIC_CMD" >&6 +else + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 +fi + + else + MAGIC_CMD=: + fi +fi + + fi + ;; +esac + +enable_dlopen=no +enable_win32_dll=no + +# Check whether --enable-libtool-lock or --disable-libtool-lock was given. +if test "${enable_libtool_lock+set}" = set; then + enableval="$enable_libtool_lock" + +fi; +test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes + + +# Check whether --with-pic or --without-pic was given. +if test "${with_pic+set}" = set; then + withval="$with_pic" + pic_mode="$withval" +else + pic_mode=default +fi; +test -z "$pic_mode" && pic_mode=default + +# Use C for the default configuration in the libtool script +tagname= +lt_save_CC="$CC" +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + +# Source file extension for C test sources. +ac_ext=c + +# Object file extension for compiled C test sources. +objext=o +objext=$objext + +# Code to be used in simple compile tests +lt_simple_compile_test_code="int some_variable = 0;\n" + +# Code to be used in simple link tests +lt_simple_link_test_code='int main(){return(0);}\n' + + +# If no C compiler was specified, use CC. +LTCC=${LTCC-"$CC"} + +# Allow CC to be a program name with arguments. +compiler=$CC + + +# +# Check for any special shared library compilation flags. +# +lt_prog_cc_shlib= +if test "$GCC" = no; then + case $host_os in + sco3.2v5*) + lt_prog_cc_shlib='-belf' + ;; + esac +fi +if test -n "$lt_prog_cc_shlib"; then + { echo "$as_me:$LINENO: WARNING: \`$CC' requires \`$lt_prog_cc_shlib' to build shared libraries" >&5 +echo "$as_me: WARNING: \`$CC' requires \`$lt_prog_cc_shlib' to build shared libraries" >&2;} + if echo "$old_CC $old_CFLAGS " | grep "[ ]$lt_prog_cc_shlib[ ]" >/dev/null; then : + else + { echo "$as_me:$LINENO: WARNING: add \`$lt_prog_cc_shlib' to the CC or CFLAGS env variable and reconfigure" >&5 +echo "$as_me: WARNING: add \`$lt_prog_cc_shlib' to the CC or CFLAGS env variable and reconfigure" >&2;} + lt_cv_prog_cc_can_build_shared=no + fi +fi + + +# +# Check to make sure the static flag actually works. +# +echo "$as_me:$LINENO: checking if $compiler static flag $lt_prog_compiler_static works" >&5 +echo $ECHO_N "checking if $compiler static flag $lt_prog_compiler_static works... $ECHO_C" >&6 +if test "${lt_prog_compiler_static_works+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + lt_prog_compiler_static_works=no + save_LDFLAGS="$LDFLAGS" + LDFLAGS="$LDFLAGS $lt_prog_compiler_static" + printf "$lt_simple_link_test_code" > conftest.$ac_ext + if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings + if test -s conftest.err; then + # Append any errors to the config.log. + cat conftest.err 1>&5 + else + lt_prog_compiler_static_works=yes + fi + fi + $rm conftest* + LDFLAGS="$save_LDFLAGS" + +fi +echo "$as_me:$LINENO: result: $lt_prog_compiler_static_works" >&5 +echo "${ECHO_T}$lt_prog_compiler_static_works" >&6 + +if test x"$lt_prog_compiler_static_works" = xyes; then + : +else + lt_prog_compiler_static= +fi + + + + +lt_prog_compiler_no_builtin_flag= + +if test "$GCC" = yes; then + lt_prog_compiler_no_builtin_flag=' -fno-builtin' + + +echo "$as_me:$LINENO: checking if $compiler supports -fno-rtti -fno-exceptions" >&5 +echo $ECHO_N "checking if $compiler supports -fno-rtti -fno-exceptions... $ECHO_C" >&6 +if test "${lt_cv_prog_compiler_rtti_exceptions+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + lt_cv_prog_compiler_rtti_exceptions=no + ac_outfile=conftest.$ac_objext + printf "$lt_simple_compile_test_code" > conftest.$ac_ext + lt_compiler_flag="-fno-rtti -fno-exceptions" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + # The option is referenced via a variable to avoid confusing sed. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}? :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:6260: $lt_compile\"" >&5) + (eval "$lt_compile" 2>conftest.err) + ac_status=$? + cat conftest.err >&5 + echo "$as_me:6264: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s "$ac_outfile"; then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings + if test ! -s conftest.err; then + lt_cv_prog_compiler_rtti_exceptions=yes + fi + fi + $rm conftest* + +fi +echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_rtti_exceptions" >&5 +echo "${ECHO_T}$lt_cv_prog_compiler_rtti_exceptions" >&6 + +if test x"$lt_cv_prog_compiler_rtti_exceptions" = xyes; then + lt_prog_compiler_no_builtin_flag="$lt_prog_compiler_no_builtin_flag -fno-rtti -fno-exceptions" +else + : +fi + +fi + +lt_prog_compiler_wl= +lt_prog_compiler_pic= +lt_prog_compiler_static= + +echo "$as_me:$LINENO: checking for $compiler option to produce PIC" >&5 +echo $ECHO_N "checking for $compiler option to produce PIC... $ECHO_C" >&6 + + if test "$GCC" = yes; then + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_static='-static' + + case $host_os in + aix*) + # All AIX code is PIC. + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + lt_prog_compiler_static='-Bstatic' + fi + ;; + + amigaos*) + # FIXME: we need at least 68020 code to build shared libraries, but + # adding the `-m68020' flag to GCC prevents building anything better, + # like `-m68040'. + lt_prog_compiler_pic='-m68020 -resident32 -malways-restore-a4' + ;; + + beos* | cygwin* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) + # PIC is the default for these OSes. + ;; + + mingw* | pw32* | os2*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + lt_prog_compiler_pic='-DDLL_EXPORT' + ;; + + darwin* | rhapsody*) + # PIC is the default on this platform + # Common symbols not allowed in MH_DYLIB files + lt_prog_compiler_pic='-fno-common' + ;; + + msdosdjgpp*) + # Just because we use GCC doesn't mean we suddenly get shared libraries + # on systems that don't support them. + lt_prog_compiler_can_build_shared=no + enable_shared=no + ;; + + sysv4*MP*) + if test -d /usr/nec; then + lt_prog_compiler_pic=-Kconform_pic + fi + ;; + + hpux*) + # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but + # not for PA HP-UX. + case "$host_cpu" in + hppa*64*|ia64*) + # +Z the default + ;; + *) + lt_prog_compiler_pic='-fPIC' + ;; + esac + ;; + + *) + lt_prog_compiler_pic='-fPIC' + ;; + esac + else + # PORTME Check for flag to pass linker flags through the system compiler. + case $host_os in + aix*) + lt_prog_compiler_wl='-Wl,' + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + lt_prog_compiler_static='-Bstatic' + else + lt_prog_compiler_static='-bnso -bI:/lib/syscalls.exp' + fi + ;; + + mingw* | pw32* | os2*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + lt_prog_compiler_pic='-DDLL_EXPORT' + ;; + + hpux9* | hpux10* | hpux11*) + lt_prog_compiler_wl='-Wl,' + # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but + # not for PA HP-UX. + case "$host_cpu" in + hppa*64*|ia64*) + # +Z the default + ;; + *) + lt_prog_compiler_pic='+Z' + ;; + esac + # Is there a better lt_prog_compiler_static that works with the bundled CC? + lt_prog_compiler_static='${wl}-a ${wl}archive' + ;; + + irix5* | irix6* | nonstopux*) + lt_prog_compiler_wl='-Wl,' + # PIC (with -KPIC) is the default. + lt_prog_compiler_static='-non_shared' + ;; + + newsos6) + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + ;; + + linux*) + case $CC in + icc* | ecc*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-static' + ;; + ccc*) + lt_prog_compiler_wl='-Wl,' + # All Alpha code is PIC. + lt_prog_compiler_static='-non_shared' + ;; + esac + ;; + + osf3* | osf4* | osf5*) + lt_prog_compiler_wl='-Wl,' + # All OSF/1 code is PIC. + lt_prog_compiler_static='-non_shared' + ;; + + sco3.2v5*) + lt_prog_compiler_pic='-Kpic' + lt_prog_compiler_static='-dn' + ;; + + solaris*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + ;; + + sunos4*) + lt_prog_compiler_wl='-Qoption ld ' + lt_prog_compiler_pic='-PIC' + lt_prog_compiler_static='-Bstatic' + ;; + + sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + ;; + + sysv4*MP*) + if test -d /usr/nec ;then + lt_prog_compiler_pic='-Kconform_pic' + lt_prog_compiler_static='-Bstatic' + fi + ;; + + uts4*) + lt_prog_compiler_pic='-pic' + lt_prog_compiler_static='-Bstatic' + ;; + + *) + lt_prog_compiler_can_build_shared=no + ;; + esac + fi + +echo "$as_me:$LINENO: result: $lt_prog_compiler_pic" >&5 +echo "${ECHO_T}$lt_prog_compiler_pic" >&6 + +# +# Check to make sure the PIC flag actually works. +# +if test -n "$lt_prog_compiler_pic"; then + +echo "$as_me:$LINENO: checking if $compiler PIC flag $lt_prog_compiler_pic works" >&5 +echo $ECHO_N "checking if $compiler PIC flag $lt_prog_compiler_pic works... $ECHO_C" >&6 +if test "${lt_prog_compiler_pic_works+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + lt_prog_compiler_pic_works=no + ac_outfile=conftest.$ac_objext + printf "$lt_simple_compile_test_code" > conftest.$ac_ext + lt_compiler_flag="$lt_prog_compiler_pic -DPIC" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + # The option is referenced via a variable to avoid confusing sed. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}? :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:6493: $lt_compile\"" >&5) + (eval "$lt_compile" 2>conftest.err) + ac_status=$? + cat conftest.err >&5 + echo "$as_me:6497: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s "$ac_outfile"; then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings + if test ! -s conftest.err; then + lt_prog_compiler_pic_works=yes + fi + fi + $rm conftest* + +fi +echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_works" >&5 +echo "${ECHO_T}$lt_prog_compiler_pic_works" >&6 + +if test x"$lt_prog_compiler_pic_works" = xyes; then + case $lt_prog_compiler_pic in + "" | " "*) ;; + *) lt_prog_compiler_pic=" $lt_prog_compiler_pic" ;; + esac +else + lt_prog_compiler_pic= + lt_prog_compiler_can_build_shared=no +fi + +fi +case "$host_os" in + # For platforms which do not support PIC, -DPIC is meaningless: + *djgpp*) + lt_prog_compiler_pic= + ;; + *) + lt_prog_compiler_pic="$lt_prog_compiler_pic -DPIC" + ;; +esac + +echo "$as_me:$LINENO: checking if $compiler supports -c -o file.$ac_objext" >&5 +echo $ECHO_N "checking if $compiler supports -c -o file.$ac_objext... $ECHO_C" >&6 +if test "${lt_cv_prog_compiler_c_o+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + lt_cv_prog_compiler_c_o=no + $rm -r conftest 2>/dev/null + mkdir conftest + cd conftest + mkdir out + printf "$lt_simple_compile_test_code" > conftest.$ac_ext + + lt_compiler_flag="-o out/conftest2.$ac_objext" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}? :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:6553: $lt_compile\"" >&5) + (eval "$lt_compile" 2>out/conftest.err) + ac_status=$? + cat out/conftest.err >&5 + echo "$as_me:6557: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s out/conftest2.$ac_objext + then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings + if test ! -s out/conftest.err; then + lt_cv_prog_compiler_c_o=yes + fi + fi + chmod u+w . + $rm conftest* + # SGI C++ compiler will create directory out/ii_files/ for + # template instantiation + test -d out/ii_files && $rm out/ii_files/* && rmdir out/ii_files + $rm out/* && rmdir out + cd .. + rmdir conftest + $rm conftest* + +fi +echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_c_o" >&5 +echo "${ECHO_T}$lt_cv_prog_compiler_c_o" >&6 + + +hard_links="nottested" +if test "$lt_cv_prog_compiler_c_o" = no && test "$need_locks" != no; then + # do not overwrite the value of need_locks provided by the user + echo "$as_me:$LINENO: checking if we can lock with hard links" >&5 +echo $ECHO_N "checking if we can lock with hard links... $ECHO_C" >&6 + hard_links=yes + $rm conftest* + ln conftest.a conftest.b 2>/dev/null && hard_links=no + touch conftest.a + ln conftest.a conftest.b 2>&5 || hard_links=no + ln conftest.a conftest.b 2>/dev/null && hard_links=no + echo "$as_me:$LINENO: result: $hard_links" >&5 +echo "${ECHO_T}$hard_links" >&6 + if test "$hard_links" = no; then + { echo "$as_me:$LINENO: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5 +echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;} + need_locks=warn + fi +else + need_locks=no +fi + +echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) supports shared libraries" >&5 +echo $ECHO_N "checking whether the $compiler linker ($LD) supports shared libraries... $ECHO_C" >&6 + + runpath_var= + allow_undefined_flag= + enable_shared_with_static_runtimes=no + archive_cmds= + archive_expsym_cmds= + old_archive_From_new_cmds= + old_archive_from_expsyms_cmds= + export_dynamic_flag_spec= + whole_archive_flag_spec= + thread_safe_flag_spec= + hardcode_libdir_flag_spec= + hardcode_libdir_flag_spec_ld= + hardcode_libdir_separator= + hardcode_direct=no + hardcode_minus_L=no + hardcode_shlibpath_var=unsupported + link_all_deplibs=unknown + hardcode_automatic=no + module_cmds= + module_expsym_cmds= + always_export_symbols=no + export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' + # include_expsyms should be a list of space-separated symbols to be *always* + # included in the symbol list + include_expsyms= + # exclude_expsyms can be an extended regexp of symbols to exclude + # it will be wrapped by ` (' and `)$', so one must not match beginning or + # end of line. Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc', + # as well as any symbol that contains `d'. + exclude_expsyms="_GLOBAL_OFFSET_TABLE_" + # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out + # platforms (ab)use it in PIC code, but their linkers get confused if + # the symbol is explicitly referenced. Since portable code cannot + # rely on this symbol name, it's probably fine to never include it in + # preloaded symbol tables. + extract_expsyms_cmds= + + case $host_os in + cygwin* | mingw* | pw32*) + # FIXME: the MSVC++ port hasn't been tested in a loooong time + # When not using gcc, we currently assume that we are using + # Microsoft Visual C++. + if test "$GCC" != yes; then + with_gnu_ld=no + fi + ;; + openbsd*) + with_gnu_ld=no + ;; + esac + + ld_shlibs=yes + if test "$with_gnu_ld" = yes; then + # If archive_cmds runs LD, not CC, wlarc should be empty + wlarc='${wl}' + + # See if GNU ld supports shared libraries. + case $host_os in + aix3* | aix4* | aix5*) + # On AIX/PPC, the GNU linker is very broken + if test "$host_cpu" != ia64; then + ld_shlibs=no + cat <&2 + +*** Warning: the GNU linker, at least up to release 2.9.1, is reported +*** to be unable to reliably create shared libraries on AIX. +*** Therefore, libtool is disabling shared libraries support. If you +*** really care for shared libraries, you may want to modify your PATH +*** so that a non-GNU linker is found, and then restart. + +EOF + fi + ;; + + amigaos*) + archive_cmds='$rm $output_objdir/a2ixlibrary.data~$echo "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' + hardcode_libdir_flag_spec='-L$libdir' + hardcode_minus_L=yes + + # Samuel A. Falvo II reports + # that the semantics of dynamic libraries on AmigaOS, at least up + # to version 4, is to share data among multiple programs linked + # with the same dynamic library. Since this doesn't match the + # behavior of shared libraries on other platforms, we can't use + # them. + ld_shlibs=no + ;; + + beos*) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + allow_undefined_flag=unsupported + # Joseph Beckenbach says some releases of gcc + # support --undefined. This deserves some investigation. FIXME + archive_cmds='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + else + ld_shlibs=no + fi + ;; + + cygwin* | mingw* | pw32*) + # _LT_AC_TAGVAR(hardcode_libdir_flag_spec, ) is actually meaningless, + # as there is no search path for DLLs. + hardcode_libdir_flag_spec='-L$libdir' + allow_undefined_flag=unsupported + always_export_symbols=no + enable_shared_with_static_runtimes=yes + export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGS] /s/.* \([^ ]*\)/\1 DATA/'\'' | $SED -e '\''/^[AITW] /s/.* //'\'' | sort | uniq > $export_symbols' + + if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then + archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--image-base=0x10000000 ${wl}--out-implib,$lib' + # If the export-symbols file already is a .def file (1st line + # is EXPORTS), use it as is; otherwise, prepend... + archive_expsym_cmds='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then + cp $export_symbols $output_objdir/$soname.def; + else + echo EXPORTS > $output_objdir/$soname.def; + cat $export_symbols >> $output_objdir/$soname.def; + fi~ + $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--image-base=0x10000000 ${wl}--out-implib,$lib' + else + ld_shlibs=no + fi + ;; + + netbsd* | netbsdelf*-gnu | knetbsd*-gnu) + if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then + archive_cmds='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib' + wlarc= + else + archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + fi + ;; + + solaris* | sysv5*) + if $LD -v 2>&1 | grep 'BFD 2\.8' > /dev/null; then + ld_shlibs=no + cat <&2 + +*** Warning: The releases 2.8.* of the GNU linker cannot reliably +*** create shared libraries on Solaris systems. Therefore, libtool +*** is disabling shared libraries support. We urge you to upgrade GNU +*** binutils to release 2.9.1 or newer. Another option is to modify +*** your PATH or compiler configuration so that the native linker is +*** used, and then restart. + +EOF + elif $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + else + ld_shlibs=no + fi + ;; + + sunos4*) + archive_cmds='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags' + wlarc= + hardcode_direct=yes + hardcode_shlibpath_var=no + ;; + + linux*) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + tmp_archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_cmds="$tmp_archive_cmds" + supports_anon_versioning=no + case `$LD -v 2>/dev/null` in + *\ 01.* | *\ 2.[0-9].* | *\ 2.10.*) ;; # catch versions < 2.11 + *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ... + *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ... + *\ 2.11.*) ;; # other 2.11 versions + *) supports_anon_versioning=yes ;; + esac + if test $supports_anon_versioning = yes; then + archive_expsym_cmds='$echo "{ global:" > $output_objdir/$libname.ver~ +cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ +$echo "local: *; };" >> $output_objdir/$libname.ver~ + $CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib' + else + archive_expsym_cmds="$tmp_archive_cmds" + fi + link_all_deplibs=no + else + ld_shlibs=no + fi + ;; + + *) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + else + ld_shlibs=no + fi + ;; + esac + + if test "$ld_shlibs" = yes; then + runpath_var=LD_RUN_PATH + hardcode_libdir_flag_spec='${wl}--rpath ${wl}$libdir' + export_dynamic_flag_spec='${wl}--export-dynamic' + # ancient GNU ld didn't support --whole-archive et. al. + if $LD --help 2>&1 | grep 'no-whole-archive' > /dev/null; then + whole_archive_flag_spec="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' + else + whole_archive_flag_spec= + fi + fi + else + # PORTME fill in a description of your system's linker (not GNU ld) + case $host_os in + aix3*) + allow_undefined_flag=unsupported + always_export_symbols=yes + archive_expsym_cmds='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname' + # Note: this linker hardcodes the directories in LIBPATH if there + # are no directories specified by -L. + hardcode_minus_L=yes + if test "$GCC" = yes && test -z "$link_static_flag"; then + # Neither direct hardcoding nor static linking is supported with a + # broken collect2. + hardcode_direct=unsupported + fi + ;; + + aix4* | aix5*) + if test "$host_cpu" = ia64; then + # On IA64, the linker does run time linking by default, so we don't + # have to do anything special. + aix_use_runtimelinking=no + exp_sym_flag='-Bexport' + no_entry_flag="" + else + # If we're using GNU nm, then we don't want the "-C" option. + # -C means demangle to AIX nm, but means don't demangle with GNU nm + if $NM -V 2>&1 | grep 'GNU' > /dev/null; then + export_symbols_cmds='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$2 == "T") || (\$2 == "D") || (\$2 == "B")) && (substr(\$3,1,1) != ".")) { print \$3 } }'\'' | sort -u > $export_symbols' + else + export_symbols_cmds='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$2 == "T") || (\$2 == "D") || (\$2 == "B")) && (substr(\$3,1,1) != ".")) { print \$3 } }'\'' | sort -u > $export_symbols' + fi + aix_use_runtimelinking=no + + # Test if we are trying to use run time linking or normal + # AIX style linking. If -brtl is somewhere in LDFLAGS, we + # need to do runtime linking. + case $host_os in aix4.[23]|aix4.[23].*|aix5*) + for ld_flag in $LDFLAGS; do + if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then + aix_use_runtimelinking=yes + break + fi + done + esac + + exp_sym_flag='-bexport' + no_entry_flag='-bnoentry' + fi + + # When large executables or shared objects are built, AIX ld can + # have problems creating the table of contents. If linking a library + # or program results in "error TOC overflow" add -mminimal-toc to + # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not + # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. + + archive_cmds='' + hardcode_direct=yes + hardcode_libdir_separator=':' + link_all_deplibs=yes + + if test "$GCC" = yes; then + case $host_os in aix4.012|aix4.012.*) + # We only want to do this on AIX 4.2 and lower, the check + # below for broken collect2 doesn't work under 4.3+ + collect2name=`${CC} -print-prog-name=collect2` + if test -f "$collect2name" && \ + strings "$collect2name" | grep resolve_lib_name >/dev/null + then + # We have reworked collect2 + hardcode_direct=yes + else + # We have old collect2 + hardcode_direct=unsupported + # It fails to find uninstalled libraries when the uninstalled + # path is not listed in the libpath. Setting hardcode_minus_L + # to unsupported forces relinking + hardcode_minus_L=yes + hardcode_libdir_flag_spec='-L$libdir' + hardcode_libdir_separator= + fi + esac + shared_flag='-shared' + else + # not using gcc + if test "$host_cpu" = ia64; then + # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release + # chokes on -Wl,-G. The following line is correct: + shared_flag='-G' + else + if test "$aix_use_runtimelinking" = yes; then + shared_flag='${wl}-G' + else + shared_flag='${wl}-bM:SRE' + fi + fi + fi + + # It seems that -bexpall does not export symbols beginning with + # underscore (_), so it is better to generate a list of symbols to export. + always_export_symbols=yes + if test "$aix_use_runtimelinking" = yes; then + # Warning - without using the other runtime loading flags (-brtl), + # -berok will link without error, but may produce a broken library. + allow_undefined_flag='-berok' + # Determine the default libpath from the value encoded in an empty executable. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + +aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; } +}'` +# Check for a 64-bit object if we didn't find anything. +if test -z "$aix_libpath"; then aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; } +}'`; fi +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +fi +rm -f conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi + + hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath" + archive_expsym_cmds="\$CC"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$no_entry_flag \${wl}$exp_sym_flag:\$export_symbols $shared_flag" + else + if test "$host_cpu" = ia64; then + hardcode_libdir_flag_spec='${wl}-R $libdir:/usr/lib:/lib' + allow_undefined_flag="-z nodefs" + archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$no_entry_flag \${wl}$exp_sym_flag:\$export_symbols" + else + # Determine the default libpath from the value encoded in an empty executable. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + +aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; } +}'` +# Check for a 64-bit object if we didn't find anything. +if test -z "$aix_libpath"; then aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; } +}'`; fi +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +fi +rm -f conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi + + hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath" + # Warning - without using the other run time loading flags, + # -berok will link without error, but may produce a broken library. + no_undefined_flag=' ${wl}-bernotok' + allow_undefined_flag=' ${wl}-berok' + # -bexpall does not export symbols beginning with underscore (_) + always_export_symbols=yes + # Exported symbols can be pulled into shared objects from archives + whole_archive_flag_spec=' ' + archive_cmds_need_lc=yes + # This is similar to how AIX traditionally builds it's shared libraries. + archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags ${wl}-bE:$export_symbols ${wl}-bnoentry${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' + fi + fi + ;; + + amigaos*) + archive_cmds='$rm $output_objdir/a2ixlibrary.data~$echo "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' + hardcode_libdir_flag_spec='-L$libdir' + hardcode_minus_L=yes + # see comment about different semantics on the GNU ld section + ld_shlibs=no + ;; + + bsdi4*) + export_dynamic_flag_spec=-rdynamic + ;; + + cygwin* | mingw* | pw32*) + # When not using gcc, we currently assume that we are using + # Microsoft Visual C++. + # hardcode_libdir_flag_spec is actually meaningless, as there is + # no search path for DLLs. + hardcode_libdir_flag_spec=' ' + allow_undefined_flag=unsupported + # Tell ltmain to make .lib files, not .a files. + libext=lib + # Tell ltmain to make .dll files, not .so files. + shrext_cmds=".dll" + # FIXME: Setting linknames here is a bad hack. + archive_cmds='$CC -o $lib $libobjs $compiler_flags `echo "$deplibs" | $SED -e '\''s/ -lc$//'\''` -link -dll~linknames=' + # The linker will automatically build a .lib file if we build a DLL. + old_archive_From_new_cmds='true' + # FIXME: Should let the user specify the lib program. + old_archive_cmds='lib /OUT:$oldlib$oldobjs$old_deplibs' + fix_srcfile_path='`cygpath -w "$srcfile"`' + enable_shared_with_static_runtimes=yes + ;; + + darwin* | rhapsody*) + if test "$GXX" = yes ; then + archive_cmds_need_lc=no + case "$host_os" in + rhapsody* | darwin1.[012]) + allow_undefined_flag='-undefined suppress' + ;; + *) # Darwin 1.3 on + if test -z ${MACOSX_DEPLOYMENT_TARGET} ; then + allow_undefined_flag='-flat_namespace -undefined suppress' + else + case ${MACOSX_DEPLOYMENT_TARGET} in + 10.[012]) + allow_undefined_flag='-flat_namespace -undefined suppress' + ;; + 10.*) + allow_undefined_flag='-undefined dynamic_lookup' + ;; + esac + fi + ;; + esac + lt_int_apple_cc_single_mod=no + output_verbose_link_cmd='echo' + if $CC -dumpspecs 2>&1 | grep 'single_module' >/dev/null ; then + lt_int_apple_cc_single_mod=yes + fi + if test "X$lt_int_apple_cc_single_mod" = Xyes ; then + archive_cmds='$CC -dynamiclib -single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring' + else + archive_cmds='$CC -r ${wl}-bind_at_load -keep_private_externs -nostdlib -o ${lib}-master.o $libobjs~$CC -dynamiclib $allow_undefined_flag -o $lib ${lib}-master.o $deplibs $compiler_flags -install_name $rpath/$soname $verstring' + fi + module_cmds='$CC ${wl}-bind_at_load $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags' + # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin ld's + if test "X$lt_int_apple_cc_single_mod" = Xyes ; then + archive_expsym_cmds='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -dynamiclib -single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + else + archive_expsym_cmds='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -r ${wl}-bind_at_load -keep_private_externs -nostdlib -o ${lib}-master.o $libobjs~$CC -dynamiclib $allow_undefined_flag -o $lib ${lib}-master.o $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + fi + module_expsym_cmds='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + hardcode_direct=no + hardcode_automatic=yes + hardcode_shlibpath_var=unsupported + whole_archive_flag_spec='-all_load $convenience' + link_all_deplibs=yes + else + ld_shlibs=no + fi + ;; + + dgux*) + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_libdir_flag_spec='-L$libdir' + hardcode_shlibpath_var=no + ;; + + freebsd1*) + ld_shlibs=no + ;; + + # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor + # support. Future versions do this automatically, but an explicit c++rt0.o + # does not break anything, and helps significantly (at the cost of a little + # extra space). + freebsd2.2*) + archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o' + hardcode_libdir_flag_spec='-R$libdir' + hardcode_direct=yes + hardcode_shlibpath_var=no + ;; + + # Unfortunately, older versions of FreeBSD 2 do not have this feature. + freebsd2*) + archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct=yes + hardcode_minus_L=yes + hardcode_shlibpath_var=no + ;; + + # FreeBSD 3 and greater uses gcc -shared to do shared libraries. + freebsd* | kfreebsd*-gnu) + archive_cmds='$CC -shared -o $lib $libobjs $deplibs $compiler_flags' + hardcode_libdir_flag_spec='-R$libdir' + hardcode_direct=yes + hardcode_shlibpath_var=no + ;; + + hpux9*) + if test "$GCC" = yes; then + archive_cmds='$rm $output_objdir/$soname~$CC -shared -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + else + archive_cmds='$rm $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + fi + hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' + hardcode_libdir_separator=: + hardcode_direct=yes + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + hardcode_minus_L=yes + export_dynamic_flag_spec='${wl}-E' + ;; + + hpux10* | hpux11*) + if test "$GCC" = yes -a "$with_gnu_ld" = no; then + case "$host_cpu" in + hppa*64*|ia64*) + archive_cmds='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + *) + archive_cmds='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' + ;; + esac + else + case "$host_cpu" in + hppa*64*|ia64*) + archive_cmds='$LD -b +h $soname -o $lib $libobjs $deplibs $linker_flags' + ;; + *) + archive_cmds='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' + ;; + esac + fi + if test "$with_gnu_ld" = no; then + case "$host_cpu" in + hppa*64*) + hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' + hardcode_libdir_flag_spec_ld='+b $libdir' + hardcode_libdir_separator=: + hardcode_direct=no + hardcode_shlibpath_var=no + ;; + ia64*) + hardcode_libdir_flag_spec='-L$libdir' + hardcode_direct=no + hardcode_shlibpath_var=no + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + hardcode_minus_L=yes + ;; + *) + hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' + hardcode_libdir_separator=: + hardcode_direct=yes + export_dynamic_flag_spec='${wl}-E' + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + hardcode_minus_L=yes + ;; + esac + fi + ;; + + irix5* | irix6* | nonstopux*) + if test "$GCC" = yes; then + archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + else + archive_cmds='$LD -shared $libobjs $deplibs $linker_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib' + hardcode_libdir_flag_spec_ld='-rpath $libdir' + fi + hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator=: + link_all_deplibs=yes + ;; + + netbsd* | netbsdelf*-gnu | knetbsd*-gnu) + if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then + archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out + else + archive_cmds='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF + fi + hardcode_libdir_flag_spec='-R$libdir' + hardcode_direct=yes + hardcode_shlibpath_var=no + ;; + + newsos6) + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct=yes + hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator=: + hardcode_shlibpath_var=no + ;; + + openbsd*) + hardcode_direct=yes + hardcode_shlibpath_var=no + if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' + hardcode_libdir_flag_spec='${wl}-rpath,$libdir' + export_dynamic_flag_spec='${wl}-E' + else + case $host_os in + openbsd[01].* | openbsd2.[0-7] | openbsd2.[0-7].*) + archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' + hardcode_libdir_flag_spec='-R$libdir' + ;; + *) + archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' + hardcode_libdir_flag_spec='${wl}-rpath,$libdir' + ;; + esac + fi + ;; + + os2*) + hardcode_libdir_flag_spec='-L$libdir' + hardcode_minus_L=yes + allow_undefined_flag=unsupported + archive_cmds='$echo "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$echo "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~$echo DATA >> $output_objdir/$libname.def~$echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~$echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def' + old_archive_From_new_cmds='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def' + ;; + + osf3*) + if test "$GCC" = yes; then + allow_undefined_flag=' ${wl}-expect_unresolved ${wl}\*' + archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + else + allow_undefined_flag=' -expect_unresolved \*' + archive_cmds='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib' + fi + hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator=: + ;; + + osf4* | osf5*) # as osf3* with the addition of -msym flag + if test "$GCC" = yes; then + allow_undefined_flag=' ${wl}-expect_unresolved ${wl}\*' + archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' + else + allow_undefined_flag=' -expect_unresolved \*' + archive_cmds='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -msym -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib' + archive_expsym_cmds='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; echo "-hidden">> $lib.exp~ + $LD -shared${allow_undefined_flag} -input $lib.exp $linker_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${objdir}/so_locations -o $lib~$rm $lib.exp' + + # Both c and cxx compiler support -rpath directly + hardcode_libdir_flag_spec='-rpath $libdir' + fi + hardcode_libdir_separator=: + ;; + + sco3.2v5*) + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_shlibpath_var=no + export_dynamic_flag_spec='${wl}-Bexport' + runpath_var=LD_RUN_PATH + hardcode_runpath_var=yes + ;; + + solaris*) + no_undefined_flag=' -z text' + if test "$GCC" = yes; then + archive_cmds='$CC -shared ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~ + $CC -shared ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$rm $lib.exp' + else + archive_cmds='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags' + archive_expsym_cmds='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~ + $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$rm $lib.exp' + fi + hardcode_libdir_flag_spec='-R$libdir' + hardcode_shlibpath_var=no + case $host_os in + solaris2.[0-5] | solaris2.[0-5].*) ;; + *) # Supported since Solaris 2.6 (maybe 2.5.1?) + whole_archive_flag_spec='-z allextract$convenience -z defaultextract' ;; + esac + link_all_deplibs=yes + ;; + + sunos4*) + if test "x$host_vendor" = xsequent; then + # Use $CC to link under sequent, because it throws in some extra .o + # files that make .init and .fini sections work. + archive_cmds='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags' + else + archive_cmds='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags' + fi + hardcode_libdir_flag_spec='-L$libdir' + hardcode_direct=yes + hardcode_minus_L=yes + hardcode_shlibpath_var=no + ;; + + sysv4) + case $host_vendor in + sni) + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct=yes # is this really true??? + ;; + siemens) + ## LD is ld it makes a PLAMLIB + ## CC just makes a GrossModule. + archive_cmds='$LD -G -o $lib $libobjs $deplibs $linker_flags' + reload_cmds='$CC -r -o $output$reload_objs' + hardcode_direct=no + ;; + motorola) + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct=no #Motorola manual says yes, but my tests say they lie + ;; + esac + runpath_var='LD_RUN_PATH' + hardcode_shlibpath_var=no + ;; + + sysv4.3*) + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_shlibpath_var=no + export_dynamic_flag_spec='-Bexport' + ;; + + sysv4*MP*) + if test -d /usr/nec; then + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_shlibpath_var=no + runpath_var=LD_RUN_PATH + hardcode_runpath_var=yes + ld_shlibs=yes + fi + ;; + + sysv4.2uw2*) + archive_cmds='$LD -G -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct=yes + hardcode_minus_L=no + hardcode_shlibpath_var=no + hardcode_runpath_var=yes + runpath_var=LD_RUN_PATH + ;; + + sysv5OpenUNIX8* | sysv5UnixWare7* | sysv5uw[78]* | unixware7*) + no_undefined_flag='${wl}-z ${wl}text' + if test "$GCC" = yes; then + archive_cmds='$CC -shared ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + else + archive_cmds='$CC -G ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + fi + runpath_var='LD_RUN_PATH' + hardcode_shlibpath_var=no + ;; + + sysv5*) + no_undefined_flag=' -z text' + # $CC -shared without GNU ld will not create a library from C++ + # object files and a static libstdc++, better avoid it by now + archive_cmds='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags' + archive_expsym_cmds='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~ + $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$rm $lib.exp' + hardcode_libdir_flag_spec= + hardcode_shlibpath_var=no + runpath_var='LD_RUN_PATH' + ;; + + uts4*) + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_libdir_flag_spec='-L$libdir' + hardcode_shlibpath_var=no + ;; + + *) + ld_shlibs=no + ;; + esac + fi + +echo "$as_me:$LINENO: result: $ld_shlibs" >&5 +echo "${ECHO_T}$ld_shlibs" >&6 +test "$ld_shlibs" = no && can_build_shared=no + +variables_saved_for_relink="PATH $shlibpath_var $runpath_var" +if test "$GCC" = yes; then + variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" +fi + +# +# Do we need to explicitly link libc? +# +case "x$archive_cmds_need_lc" in +x|xyes) + # Assume -lc should be added + archive_cmds_need_lc=yes + + if test "$enable_shared" = yes && test "$GCC" = yes; then + case $archive_cmds in + *'~'*) + # FIXME: we may have to deal with multi-command sequences. + ;; + '$CC '*) + # Test whether the compiler implicitly links with -lc since on some + # systems, -lgcc has to come before -lc. If gcc already passes -lc + # to ld, don't add -lc before -lgcc. + echo "$as_me:$LINENO: checking whether -lc should be explicitly linked in" >&5 +echo $ECHO_N "checking whether -lc should be explicitly linked in... $ECHO_C" >&6 + $rm conftest* + printf "$lt_simple_compile_test_code" > conftest.$ac_ext + + if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } 2>conftest.err; then + soname=conftest + lib=conftest + libobjs=conftest.$ac_objext + deplibs= + wl=$lt_prog_compiler_wl + compiler_flags=-v + linker_flags=-v + verstring= + output_objdir=. + libname=conftest + lt_save_allow_undefined_flag=$allow_undefined_flag + allow_undefined_flag= + if { (eval echo "$as_me:$LINENO: \"$archive_cmds 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1\"") >&5 + (eval $archive_cmds 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } + then + archive_cmds_need_lc=no + else + archive_cmds_need_lc=yes + fi + allow_undefined_flag=$lt_save_allow_undefined_flag + else + cat conftest.err 1>&5 + fi + $rm conftest* + echo "$as_me:$LINENO: result: $archive_cmds_need_lc" >&5 +echo "${ECHO_T}$archive_cmds_need_lc" >&6 + ;; + esac + fi + ;; +esac + +echo "$as_me:$LINENO: checking dynamic linker characteristics" >&5 +echo $ECHO_N "checking dynamic linker characteristics... $ECHO_C" >&6 +library_names_spec= +libname_spec='lib$name' +soname_spec= +shrext_cmds=".so" +postinstall_cmds= +postuninstall_cmds= +finish_cmds= +finish_eval= +shlibpath_var= +shlibpath_overrides_runpath=unknown +version_type=none +dynamic_linker="$host_os ld.so" +sys_lib_dlsearch_path_spec="/lib /usr/lib" +if test "$GCC" = yes; then + sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"` + if echo "$sys_lib_search_path_spec" | grep ';' >/dev/null ; then + # if the path contains ";" then we assume it to be the separator + # otherwise default to the standard path separator (i.e. ":") - it is + # assumed that no part of a normal pathname contains ";" but that should + # okay in the real world where ";" in dirpaths is itself problematic. + sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` + else + sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` + fi +else + sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" +fi +need_lib_prefix=unknown +hardcode_into_libs=no + +# when you set need_version to no, make sure it does not cause -set_version +# flags to be left without arguments +need_version=unknown + +case $host_os in +aix3*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a' + shlibpath_var=LIBPATH + + # AIX 3 has no versioning support, so we append a major version to the name. + soname_spec='${libname}${release}${shared_ext}$major' + ;; + +aix4* | aix5*) + version_type=linux + need_lib_prefix=no + need_version=no + hardcode_into_libs=yes + if test "$host_cpu" = ia64; then + # AIX 5 supports IA64 + library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + else + # With GCC up to 2.95.x, collect2 would create an import file + # for dependence libraries. The import file would start with + # the line `#! .'. This would cause the generated library to + # depend on `.', always an invalid library. This was fixed in + # development snapshots of GCC prior to 3.0. + case $host_os in + aix4 | aix4.[01] | aix4.[01].*) + if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' + echo ' yes ' + echo '#endif'; } | ${CC} -E - | grep yes > /dev/null; then + : + else + can_build_shared=no + fi + ;; + esac + # AIX (on Power*) has no versioning support, so currently we can not hardcode correct + # soname into executable. Probably we can add versioning support to + # collect2, so additional links can be useful in future. + if test "$aix_use_runtimelinking" = yes; then + # If using run time linking (on AIX 4.2 or later) use lib.so + # instead of lib.a to let people know that these are not + # typical AIX shared libraries. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + else + # We preserve .a as extension for shared libraries through AIX4.2 + # and later when we are not doing run time linking. + library_names_spec='${libname}${release}.a $libname.a' + soname_spec='${libname}${release}${shared_ext}$major' + fi + shlibpath_var=LIBPATH + fi + ;; + +amigaos*) + library_names_spec='$libname.ixlibrary $libname.a' + # Create ${libname}_ixlibrary.a entries in /sys/libs. + finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`$echo "X$lib" | $Xsed -e '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $rm /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' + ;; + +beos*) + library_names_spec='${libname}${shared_ext}' + dynamic_linker="$host_os ld.so" + shlibpath_var=LIBRARY_PATH + ;; + +bsdi4*) + version_type=linux + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' + shlibpath_var=LD_LIBRARY_PATH + sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" + sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" + # the default ld.so.conf also contains /usr/contrib/lib and + # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow + # libtool to hard-code these into programs + ;; + +cygwin* | mingw* | pw32*) + version_type=windows + shrext_cmds=".dll" + need_version=no + need_lib_prefix=no + + case $GCC,$host_os in + yes,cygwin* | yes,mingw* | yes,pw32*) + library_names_spec='$libname.dll.a' + # DLL is installed to $(libdir)/../bin by postinstall_cmds + postinstall_cmds='base_file=`basename \${file}`~ + dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i;echo \$dlname'\''`~ + dldir=$destdir/`dirname \$dlpath`~ + test -d \$dldir || mkdir -p \$dldir~ + $install_prog $dir/$dlname \$dldir/$dlname' + postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ + dlpath=$dir/\$dldll~ + $rm \$dlpath' + shlibpath_overrides_runpath=yes + + case $host_os in + cygwin*) + # Cygwin DLLs use 'cyg' prefix rather than 'lib' + soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' + sys_lib_search_path_spec="/usr/lib /lib/w32api /lib /usr/local/lib" + ;; + mingw*) + # MinGW DLLs use traditional 'lib' prefix + soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' + sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"` + if echo "$sys_lib_search_path_spec" | grep ';[c-zC-Z]:/' >/dev/null; then + # It is most probably a Windows format PATH printed by + # mingw gcc, but we are running on Cygwin. Gcc prints its search + # path with ; separators, and with drive letters. We can handle the + # drive letters (cygwin fileutils understands them), so leave them, + # especially as we might pass files found there to a mingw objdump, + # which wouldn't understand a cygwinified path. Ahh. + sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` + else + sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` + fi + ;; + pw32*) + # pw32 DLLs use 'pw' prefix rather than 'lib' + library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/./-/g'`${versuffix}${shared_ext}' + ;; + esac + ;; + + *) + library_names_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext} $libname.lib' + ;; + esac + dynamic_linker='Win32 ld.exe' + # FIXME: first we should search . and the directory the executable is in + shlibpath_var=PATH + ;; + +darwin* | rhapsody*) + dynamic_linker="$host_os dyld" + version_type=darwin + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${versuffix}$shared_ext ${libname}${release}${major}$shared_ext ${libname}$shared_ext' + soname_spec='${libname}${release}${major}$shared_ext' + shlibpath_overrides_runpath=yes + shlibpath_var=DYLD_LIBRARY_PATH + shrext_cmds='$(test .$module = .yes && echo .so || echo .dylib)' + # Apple's gcc prints 'gcc -print-search-dirs' doesn't operate the same. + if test "$GCC" = yes; then + sys_lib_search_path_spec=`$CC -print-search-dirs | tr "\n" "$PATH_SEPARATOR" | sed -e 's/libraries:/@libraries:/' | tr "@" "\n" | grep "^libraries:" | sed -e "s/^libraries://" -e "s,=/,/,g" -e "s,$PATH_SEPARATOR, ,g" -e "s,.*,& /lib /usr/lib /usr/local/lib,g"` + else + sys_lib_search_path_spec='/lib /usr/lib /usr/local/lib' + fi + sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' + ;; + +dgux*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +freebsd1*) + dynamic_linker=no + ;; + +kfreebsd*-gnu) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + dynamic_linker='GNU ld.so' + ;; + +freebsd*) + objformat=`test -x /usr/bin/objformat && /usr/bin/objformat || echo aout` + version_type=freebsd-$objformat + case $version_type in + freebsd-elf*) + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' + need_version=no + need_lib_prefix=no + ;; + freebsd-*) + library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix' + need_version=yes + ;; + esac + shlibpath_var=LD_LIBRARY_PATH + case $host_os in + freebsd2*) + shlibpath_overrides_runpath=yes + ;; + freebsd3.01* | freebsdelf3.01*) + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + *) # from 3.2 on + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + esac + ;; + +gnu*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + hardcode_into_libs=yes + ;; + +hpux9* | hpux10* | hpux11*) + # Give a soname corresponding to the major version so that dld.sl refuses to + # link against other versions. + version_type=sunos + need_lib_prefix=no + need_version=no + case "$host_cpu" in + ia64*) + shrext_cmds='.so' + hardcode_into_libs=yes + dynamic_linker="$host_os dld.so" + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + if test "X$HPUX_IA64_MODE" = X32; then + sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" + else + sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" + fi + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + ;; + hppa*64*) + shrext_cmds='.sl' + hardcode_into_libs=yes + dynamic_linker="$host_os dld.sl" + shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH + shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + ;; + *) + shrext_cmds='.sl' + dynamic_linker="$host_os dld.sl" + shlibpath_var=SHLIB_PATH + shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + ;; + esac + # HP-UX runs *really* slowly unless shared libraries are mode 555. + postinstall_cmds='chmod 555 $lib' + ;; + +irix5* | irix6* | nonstopux*) + case $host_os in + nonstopux*) version_type=nonstopux ;; + *) + if test "$lt_cv_prog_gnu_ld" = yes; then + version_type=linux + else + version_type=irix + fi ;; + esac + need_lib_prefix=no + need_version=no + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}' + case $host_os in + irix5* | nonstopux*) + libsuff= shlibsuff= + ;; + *) + case $LD in # libtool.m4 will add one of these switches to LD + *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") + libsuff= shlibsuff= libmagic=32-bit;; + *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") + libsuff=32 shlibsuff=N32 libmagic=N32;; + *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") + libsuff=64 shlibsuff=64 libmagic=64-bit;; + *) libsuff= shlibsuff= libmagic=never-match;; + esac + ;; + esac + shlibpath_var=LD_LIBRARY${shlibsuff}_PATH + shlibpath_overrides_runpath=no + sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" + sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" + hardcode_into_libs=yes + ;; + +# No shared lib support for Linux oldld, aout, or coff. +linux*oldld* | linux*aout* | linux*coff*) + dynamic_linker=no + ;; + +# This must be Linux ELF. +linux*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + # This implies no fast_install, which is unacceptable. + # Some rework will be needed to allow for fast_install + # before this can be enabled. + hardcode_into_libs=yes + + # Append ld.so.conf contents to the search path + if test -f /etc/ld.so.conf; then + lt_ld_extra=`$SED -e 's/:,\t/ /g;s/=^=*$//;s/=^= * / /g' /etc/ld.so.conf | tr '\n' ' '` + sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" + fi + + # We used to test for /lib/ld.so.1 and disable shared libraries on + # powerpc, because MkLinux only supported shared libraries with the + # GNU dynamic linker. Since this was broken with cross compilers, + # most powerpc-linux boxes support dynamic linking these days and + # people can always --disable-shared, the test was removed, and we + # assume the GNU/Linux dynamic linker is in use. + dynamic_linker='GNU/Linux ld.so' + ;; + +netbsdelf*-gnu) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + dynamic_linker='NetBSD ld.elf_so' + ;; + +knetbsd*-gnu) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + dynamic_linker='GNU ld.so' + ;; + +netbsd*) + version_type=sunos + need_lib_prefix=no + need_version=no + if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' + dynamic_linker='NetBSD (a.out) ld.so' + else + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + dynamic_linker='NetBSD ld.elf_so' + fi + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + +newsos6) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + ;; + +nto-qnx*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + ;; + +openbsd*) + version_type=sunos + need_lib_prefix=no + need_version=yes + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' + shlibpath_var=LD_LIBRARY_PATH + if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + case $host_os in + openbsd2.[89] | openbsd2.[89].*) + shlibpath_overrides_runpath=no + ;; + *) + shlibpath_overrides_runpath=yes + ;; + esac + else + shlibpath_overrides_runpath=yes + fi + ;; + +os2*) + libname_spec='$name' + shrext_cmds=".dll" + need_lib_prefix=no + library_names_spec='$libname${shared_ext} $libname.a' + dynamic_linker='OS/2 ld.exe' + shlibpath_var=LIBPATH + ;; + +osf3* | osf4* | osf5*) + version_type=osf + need_lib_prefix=no + need_version=no + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" + sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec" + ;; + +sco3.2v5*) + version_type=osf + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + ;; + +solaris*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + # ldd complains unless libraries are executable + postinstall_cmds='chmod +x $lib' + ;; + +sunos4*) + version_type=sunos + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + if test "$with_gnu_ld" = yes; then + need_lib_prefix=no + fi + need_version=yes + ;; + +sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + case $host_vendor in + sni) + shlibpath_overrides_runpath=no + need_lib_prefix=no + export_dynamic_flag_spec='${wl}-Blargedynsym' + runpath_var=LD_RUN_PATH + ;; + siemens) + need_lib_prefix=no + ;; + motorola) + need_lib_prefix=no + need_version=no + shlibpath_overrides_runpath=no + sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' + ;; + esac + ;; + +sysv4*MP*) + if test -d /usr/nec ;then + version_type=linux + library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}' + soname_spec='$libname${shared_ext}.$major' + shlibpath_var=LD_LIBRARY_PATH + fi + ;; + +uts4*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +*) + dynamic_linker=no + ;; +esac +echo "$as_me:$LINENO: result: $dynamic_linker" >&5 +echo "${ECHO_T}$dynamic_linker" >&6 +test "$dynamic_linker" = no && can_build_shared=no + +echo "$as_me:$LINENO: checking how to hardcode library paths into programs" >&5 +echo $ECHO_N "checking how to hardcode library paths into programs... $ECHO_C" >&6 +hardcode_action= +if test -n "$hardcode_libdir_flag_spec" || \ + test -n "$runpath_var " || \ + test "X$hardcode_automatic"="Xyes" ; then + + # We can hardcode non-existant directories. + if test "$hardcode_direct" != no && + # If the only mechanism to avoid hardcoding is shlibpath_var, we + # have to relink, otherwise we might link with an installed library + # when we should be linking with a yet-to-be-installed one + ## test "$_LT_AC_TAGVAR(hardcode_shlibpath_var, )" != no && + test "$hardcode_minus_L" != no; then + # Linking always hardcodes the temporary library directory. + hardcode_action=relink + else + # We can link without hardcoding, and we can hardcode nonexisting dirs. + hardcode_action=immediate + fi +else + # We cannot hardcode anything, or else we can only hardcode existing + # directories. + hardcode_action=unsupported +fi +echo "$as_me:$LINENO: result: $hardcode_action" >&5 +echo "${ECHO_T}$hardcode_action" >&6 + +if test "$hardcode_action" = relink; then + # Fast installation is not supported + enable_fast_install=no +elif test "$shlibpath_overrides_runpath" = yes || + test "$enable_shared" = no; then + # Fast installation is not necessary + enable_fast_install=needless +fi + +striplib= +old_striplib= +echo "$as_me:$LINENO: checking whether stripping libraries is possible" >&5 +echo $ECHO_N "checking whether stripping libraries is possible... $ECHO_C" >&6 +if test -n "$STRIP" && $STRIP -V 2>&1 | grep "GNU strip" >/dev/null; then + test -z "$old_striplib" && old_striplib="$STRIP --strip-debug" + test -z "$striplib" && striplib="$STRIP --strip-unneeded" + echo "$as_me:$LINENO: result: yes" >&5 +echo "${ECHO_T}yes" >&6 +else +# FIXME - insert some real tests, host_os isn't really good enough + case $host_os in + darwin*) + if test -n "$STRIP" ; then + striplib="$STRIP -x" + echo "$as_me:$LINENO: result: yes" >&5 +echo "${ECHO_T}yes" >&6 + else + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 +fi + ;; + *) + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 + ;; + esac +fi + +if test "x$enable_dlopen" != xyes; then + enable_dlopen=unknown + enable_dlopen_self=unknown + enable_dlopen_self_static=unknown +else + lt_cv_dlopen=no + lt_cv_dlopen_libs= + + case $host_os in + beos*) + lt_cv_dlopen="load_add_on" + lt_cv_dlopen_libs= + lt_cv_dlopen_self=yes + ;; + + mingw* | pw32*) + lt_cv_dlopen="LoadLibrary" + lt_cv_dlopen_libs= + ;; + + cygwin*) + lt_cv_dlopen="dlopen" + lt_cv_dlopen_libs= + ;; + + darwin*) + # if libdl is installed we need to link against it + echo "$as_me:$LINENO: checking for dlopen in -ldl" >&5 +echo $ECHO_N "checking for dlopen in -ldl... $ECHO_C" >&6 +if test "${ac_cv_lib_dl_dlopen+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldl $LIBS" +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any gcc2 internal prototype to avoid an error. */ +#ifdef __cplusplus +extern "C" +#endif +/* We use char because int might match the return type of a gcc2 + builtin and then its argument prototype would still apply. */ +char dlopen (); +int +main () +{ +dlopen (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_lib_dl_dlopen=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_cv_lib_dl_dlopen=no +fi +rm -f conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +echo "$as_me:$LINENO: result: $ac_cv_lib_dl_dlopen" >&5 +echo "${ECHO_T}$ac_cv_lib_dl_dlopen" >&6 +if test $ac_cv_lib_dl_dlopen = yes; then + lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl" +else + + lt_cv_dlopen="dyld" + lt_cv_dlopen_libs= + lt_cv_dlopen_self=yes + +fi + + ;; + + *) + echo "$as_me:$LINENO: checking for shl_load" >&5 +echo $ECHO_N "checking for shl_load... $ECHO_C" >&6 +if test "${ac_cv_func_shl_load+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +/* Define shl_load to an innocuous variant, in case declares shl_load. + For example, HP-UX 11i declares gettimeofday. */ +#define shl_load innocuous_shl_load + +/* System header to define __stub macros and hopefully few prototypes, + which can conflict with char shl_load (); below. + Prefer to if __STDC__ is defined, since + exists even on freestanding compilers. */ + +#ifdef __STDC__ +# include +#else +# include +#endif + +#undef shl_load + +/* Override any gcc2 internal prototype to avoid an error. */ +#ifdef __cplusplus +extern "C" +{ +#endif +/* We use char because int might match the return type of a gcc2 + builtin and then its argument prototype would still apply. */ +char shl_load (); +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined (__stub_shl_load) || defined (__stub___shl_load) +choke me +#else +char (*f) () = shl_load; +#endif +#ifdef __cplusplus +} +#endif + +int +main () +{ +return f != shl_load; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_func_shl_load=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_cv_func_shl_load=no +fi +rm -f conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +fi +echo "$as_me:$LINENO: result: $ac_cv_func_shl_load" >&5 +echo "${ECHO_T}$ac_cv_func_shl_load" >&6 +if test $ac_cv_func_shl_load = yes; then + lt_cv_dlopen="shl_load" +else + echo "$as_me:$LINENO: checking for shl_load in -ldld" >&5 +echo $ECHO_N "checking for shl_load in -ldld... $ECHO_C" >&6 +if test "${ac_cv_lib_dld_shl_load+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldld $LIBS" +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any gcc2 internal prototype to avoid an error. */ +#ifdef __cplusplus +extern "C" +#endif +/* We use char because int might match the return type of a gcc2 + builtin and then its argument prototype would still apply. */ +char shl_load (); +int +main () +{ +shl_load (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_lib_dld_shl_load=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_cv_lib_dld_shl_load=no +fi +rm -f conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +echo "$as_me:$LINENO: result: $ac_cv_lib_dld_shl_load" >&5 +echo "${ECHO_T}$ac_cv_lib_dld_shl_load" >&6 +if test $ac_cv_lib_dld_shl_load = yes; then + lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-dld" +else + echo "$as_me:$LINENO: checking for dlopen" >&5 +echo $ECHO_N "checking for dlopen... $ECHO_C" >&6 +if test "${ac_cv_func_dlopen+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +/* Define dlopen to an innocuous variant, in case declares dlopen. + For example, HP-UX 11i declares gettimeofday. */ +#define dlopen innocuous_dlopen + +/* System header to define __stub macros and hopefully few prototypes, + which can conflict with char dlopen (); below. + Prefer to if __STDC__ is defined, since + exists even on freestanding compilers. */ + +#ifdef __STDC__ +# include +#else +# include +#endif + +#undef dlopen + +/* Override any gcc2 internal prototype to avoid an error. */ +#ifdef __cplusplus +extern "C" +{ +#endif +/* We use char because int might match the return type of a gcc2 + builtin and then its argument prototype would still apply. */ +char dlopen (); +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined (__stub_dlopen) || defined (__stub___dlopen) +choke me +#else +char (*f) () = dlopen; +#endif +#ifdef __cplusplus +} +#endif + +int +main () +{ +return f != dlopen; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_func_dlopen=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_cv_func_dlopen=no +fi +rm -f conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +fi +echo "$as_me:$LINENO: result: $ac_cv_func_dlopen" >&5 +echo "${ECHO_T}$ac_cv_func_dlopen" >&6 +if test $ac_cv_func_dlopen = yes; then + lt_cv_dlopen="dlopen" +else + echo "$as_me:$LINENO: checking for dlopen in -ldl" >&5 +echo $ECHO_N "checking for dlopen in -ldl... $ECHO_C" >&6 +if test "${ac_cv_lib_dl_dlopen+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldl $LIBS" +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any gcc2 internal prototype to avoid an error. */ +#ifdef __cplusplus +extern "C" +#endif +/* We use char because int might match the return type of a gcc2 + builtin and then its argument prototype would still apply. */ +char dlopen (); +int +main () +{ +dlopen (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_lib_dl_dlopen=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_cv_lib_dl_dlopen=no +fi +rm -f conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +echo "$as_me:$LINENO: result: $ac_cv_lib_dl_dlopen" >&5 +echo "${ECHO_T}$ac_cv_lib_dl_dlopen" >&6 +if test $ac_cv_lib_dl_dlopen = yes; then + lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl" +else + echo "$as_me:$LINENO: checking for dlopen in -lsvld" >&5 +echo $ECHO_N "checking for dlopen in -lsvld... $ECHO_C" >&6 +if test "${ac_cv_lib_svld_dlopen+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lsvld $LIBS" +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any gcc2 internal prototype to avoid an error. */ +#ifdef __cplusplus +extern "C" +#endif +/* We use char because int might match the return type of a gcc2 + builtin and then its argument prototype would still apply. */ +char dlopen (); +int +main () +{ +dlopen (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_lib_svld_dlopen=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_cv_lib_svld_dlopen=no +fi +rm -f conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +echo "$as_me:$LINENO: result: $ac_cv_lib_svld_dlopen" >&5 +echo "${ECHO_T}$ac_cv_lib_svld_dlopen" >&6 +if test $ac_cv_lib_svld_dlopen = yes; then + lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld" +else + echo "$as_me:$LINENO: checking for dld_link in -ldld" >&5 +echo $ECHO_N "checking for dld_link in -ldld... $ECHO_C" >&6 +if test "${ac_cv_lib_dld_dld_link+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldld $LIBS" +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any gcc2 internal prototype to avoid an error. */ +#ifdef __cplusplus +extern "C" +#endif +/* We use char because int might match the return type of a gcc2 + builtin and then its argument prototype would still apply. */ +char dld_link (); +int +main () +{ +dld_link (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_lib_dld_dld_link=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_cv_lib_dld_dld_link=no +fi +rm -f conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +echo "$as_me:$LINENO: result: $ac_cv_lib_dld_dld_link" >&5 +echo "${ECHO_T}$ac_cv_lib_dld_dld_link" >&6 +if test $ac_cv_lib_dld_dld_link = yes; then + lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-dld" +fi + + +fi + + +fi + + +fi + + +fi + + +fi + + ;; + esac + + if test "x$lt_cv_dlopen" != xno; then + enable_dlopen=yes + else + enable_dlopen=no + fi + + case $lt_cv_dlopen in + dlopen) + save_CPPFLAGS="$CPPFLAGS" + test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H" + + save_LDFLAGS="$LDFLAGS" + eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\" + + save_LIBS="$LIBS" + LIBS="$lt_cv_dlopen_libs $LIBS" + + echo "$as_me:$LINENO: checking whether a program can dlopen itself" >&5 +echo $ECHO_N "checking whether a program can dlopen itself... $ECHO_C" >&6 +if test "${lt_cv_dlopen_self+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test "$cross_compiling" = yes; then : + lt_cv_dlopen_self=cross +else + lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 + lt_status=$lt_dlunknown + cat > conftest.$ac_ext < +#endif + +#include + +#ifdef RTLD_GLOBAL +# define LT_DLGLOBAL RTLD_GLOBAL +#else +# ifdef DL_GLOBAL +# define LT_DLGLOBAL DL_GLOBAL +# else +# define LT_DLGLOBAL 0 +# endif +#endif + +/* We may have to define LT_DLLAZY_OR_NOW in the command line if we + find out it does not work in some platform. */ +#ifndef LT_DLLAZY_OR_NOW +# ifdef RTLD_LAZY +# define LT_DLLAZY_OR_NOW RTLD_LAZY +# else +# ifdef DL_LAZY +# define LT_DLLAZY_OR_NOW DL_LAZY +# else +# ifdef RTLD_NOW +# define LT_DLLAZY_OR_NOW RTLD_NOW +# else +# ifdef DL_NOW +# define LT_DLLAZY_OR_NOW DL_NOW +# else +# define LT_DLLAZY_OR_NOW 0 +# endif +# endif +# endif +# endif +#endif + +#ifdef __cplusplus +extern "C" void exit (int); +#endif + +void fnord() { int i=42;} +int main () +{ + void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); + int status = $lt_dlunknown; + + if (self) + { + if (dlsym (self,"fnord")) status = $lt_dlno_uscore; + else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; + /* dlclose (self); */ + } + + exit (status); +} +EOF + if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && test -s conftest${ac_exeext} 2>/dev/null; then + (./conftest; exit; ) 2>/dev/null + lt_status=$? + case x$lt_status in + x$lt_dlno_uscore) lt_cv_dlopen_self=yes ;; + x$lt_dlneed_uscore) lt_cv_dlopen_self=yes ;; + x$lt_unknown|x*) lt_cv_dlopen_self=no ;; + esac + else : + # compilation failed + lt_cv_dlopen_self=no + fi +fi +rm -fr conftest* + + +fi +echo "$as_me:$LINENO: result: $lt_cv_dlopen_self" >&5 +echo "${ECHO_T}$lt_cv_dlopen_self" >&6 + + if test "x$lt_cv_dlopen_self" = xyes; then + LDFLAGS="$LDFLAGS $link_static_flag" + echo "$as_me:$LINENO: checking whether a statically linked program can dlopen itself" >&5 +echo $ECHO_N "checking whether a statically linked program can dlopen itself... $ECHO_C" >&6 +if test "${lt_cv_dlopen_self_static+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test "$cross_compiling" = yes; then : + lt_cv_dlopen_self_static=cross +else + lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 + lt_status=$lt_dlunknown + cat > conftest.$ac_ext < +#endif + +#include + +#ifdef RTLD_GLOBAL +# define LT_DLGLOBAL RTLD_GLOBAL +#else +# ifdef DL_GLOBAL +# define LT_DLGLOBAL DL_GLOBAL +# else +# define LT_DLGLOBAL 0 +# endif +#endif + +/* We may have to define LT_DLLAZY_OR_NOW in the command line if we + find out it does not work in some platform. */ +#ifndef LT_DLLAZY_OR_NOW +# ifdef RTLD_LAZY +# define LT_DLLAZY_OR_NOW RTLD_LAZY +# else +# ifdef DL_LAZY +# define LT_DLLAZY_OR_NOW DL_LAZY +# else +# ifdef RTLD_NOW +# define LT_DLLAZY_OR_NOW RTLD_NOW +# else +# ifdef DL_NOW +# define LT_DLLAZY_OR_NOW DL_NOW +# else +# define LT_DLLAZY_OR_NOW 0 +# endif +# endif +# endif +# endif +#endif + +#ifdef __cplusplus +extern "C" void exit (int); +#endif + +void fnord() { int i=42;} +int main () +{ + void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); + int status = $lt_dlunknown; + + if (self) + { + if (dlsym (self,"fnord")) status = $lt_dlno_uscore; + else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; + /* dlclose (self); */ + } + + exit (status); +} +EOF + if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && test -s conftest${ac_exeext} 2>/dev/null; then + (./conftest; exit; ) 2>/dev/null + lt_status=$? + case x$lt_status in + x$lt_dlno_uscore) lt_cv_dlopen_self_static=yes ;; + x$lt_dlneed_uscore) lt_cv_dlopen_self_static=yes ;; + x$lt_unknown|x*) lt_cv_dlopen_self_static=no ;; + esac + else : + # compilation failed + lt_cv_dlopen_self_static=no + fi +fi +rm -fr conftest* + + +fi +echo "$as_me:$LINENO: result: $lt_cv_dlopen_self_static" >&5 +echo "${ECHO_T}$lt_cv_dlopen_self_static" >&6 + fi + + CPPFLAGS="$save_CPPFLAGS" + LDFLAGS="$save_LDFLAGS" + LIBS="$save_LIBS" + ;; + esac + + case $lt_cv_dlopen_self in + yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;; + *) enable_dlopen_self=unknown ;; + esac + + case $lt_cv_dlopen_self_static in + yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;; + *) enable_dlopen_self_static=unknown ;; + esac +fi + + +# Report which librarie types wil actually be built +echo "$as_me:$LINENO: checking if libtool supports shared libraries" >&5 +echo $ECHO_N "checking if libtool supports shared libraries... $ECHO_C" >&6 +echo "$as_me:$LINENO: result: $can_build_shared" >&5 +echo "${ECHO_T}$can_build_shared" >&6 + +echo "$as_me:$LINENO: checking whether to build shared libraries" >&5 +echo $ECHO_N "checking whether to build shared libraries... $ECHO_C" >&6 +test "$can_build_shared" = "no" && enable_shared=no + +# On AIX, shared libraries and static libraries use the same namespace, and +# are all built from PIC. +case "$host_os" in +aix3*) + test "$enable_shared" = yes && enable_static=no + if test -n "$RANLIB"; then + archive_cmds="$archive_cmds~\$RANLIB \$lib" + postinstall_cmds='$RANLIB $lib' + fi + ;; + +aix4* | aix5*) + if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then + test "$enable_shared" = yes && enable_static=no + fi + ;; + darwin* | rhapsody*) + if test "$GCC" = yes; then + archive_cmds_need_lc=no + case "$host_os" in + rhapsody* | darwin1.[012]) + allow_undefined_flag='-undefined suppress' + ;; + *) # Darwin 1.3 on + if test -z ${MACOSX_DEPLOYMENT_TARGET} ; then + allow_undefined_flag='-flat_namespace -undefined suppress' + else + case ${MACOSX_DEPLOYMENT_TARGET} in + 10.[012]) + allow_undefined_flag='-flat_namespace -undefined suppress' + ;; + 10.*) + allow_undefined_flag='-undefined dynamic_lookup' + ;; + esac + fi + ;; + esac + output_verbose_link_cmd='echo' + archive_cmds='$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs$compiler_flags -install_name $rpath/$soname $verstring' + module_cmds='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags' + # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin ld's + archive_expsym_cmds='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs$compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + module_expsym_cmds='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + hardcode_direct=no + hardcode_automatic=yes + hardcode_shlibpath_var=unsupported + whole_archive_flag_spec='-all_load $convenience' + link_all_deplibs=yes + else + ld_shlibs=no + fi + ;; +esac +echo "$as_me:$LINENO: result: $enable_shared" >&5 +echo "${ECHO_T}$enable_shared" >&6 + +echo "$as_me:$LINENO: checking whether to build static libraries" >&5 +echo $ECHO_N "checking whether to build static libraries... $ECHO_C" >&6 +# Make sure either enable_shared or enable_static is yes. +test "$enable_shared" = yes || enable_static=yes +echo "$as_me:$LINENO: result: $enable_static" >&5 +echo "${ECHO_T}$enable_static" >&6 + +# The else clause should only fire when bootstrapping the +# libtool distribution, otherwise you forgot to ship ltmain.sh +# with your package, and you will get complaints that there are +# no rules to generate ltmain.sh. +if test -f "$ltmain"; then + # See if we are running on zsh, and set the options which allow our commands through + # without removal of \ escapes. + if test -n "${ZSH_VERSION+set}" ; then + setopt NO_GLOB_SUBST + fi + # Now quote all the things that may contain metacharacters while being + # careful not to overquote the AC_SUBSTed values. We take copies of the + # variables and quote the copies for generation of the libtool script. + for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC NM \ + SED SHELL STRIP \ + libname_spec library_names_spec soname_spec extract_expsyms_cmds \ + old_striplib striplib file_magic_cmd finish_cmds finish_eval \ + deplibs_check_method reload_flag reload_cmds need_locks \ + lt_cv_sys_global_symbol_pipe lt_cv_sys_global_symbol_to_cdecl \ + lt_cv_sys_global_symbol_to_c_name_address \ + sys_lib_search_path_spec sys_lib_dlsearch_path_spec \ + old_postinstall_cmds old_postuninstall_cmds \ + compiler \ + CC \ + LD \ + lt_prog_compiler_wl \ + lt_prog_compiler_pic \ + lt_prog_compiler_static \ + lt_prog_compiler_no_builtin_flag \ + export_dynamic_flag_spec \ + thread_safe_flag_spec \ + whole_archive_flag_spec \ + enable_shared_with_static_runtimes \ + old_archive_cmds \ + old_archive_from_new_cmds \ + predep_objects \ + postdep_objects \ + predeps \ + postdeps \ + compiler_lib_search_path \ + archive_cmds \ + archive_expsym_cmds \ + postinstall_cmds \ + postuninstall_cmds \ + old_archive_from_expsyms_cmds \ + allow_undefined_flag \ + no_undefined_flag \ + export_symbols_cmds \ + hardcode_libdir_flag_spec \ + hardcode_libdir_flag_spec_ld \ + hardcode_libdir_separator \ + hardcode_automatic \ + module_cmds \ + module_expsym_cmds \ + lt_cv_prog_compiler_c_o \ + exclude_expsyms \ + include_expsyms; do + + case $var in + old_archive_cmds | \ + old_archive_from_new_cmds | \ + archive_cmds | \ + archive_expsym_cmds | \ + module_cmds | \ + module_expsym_cmds | \ + old_archive_from_expsyms_cmds | \ + export_symbols_cmds | \ + extract_expsyms_cmds | reload_cmds | finish_cmds | \ + postinstall_cmds | postuninstall_cmds | \ + old_postinstall_cmds | old_postuninstall_cmds | \ + sys_lib_search_path_spec | sys_lib_dlsearch_path_spec) + # Double-quote double-evaled strings. + eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$double_quote_subst\" -e \"\$sed_quote_subst\" -e \"\$delay_variable_subst\"\`\\\"" + ;; + *) + eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$sed_quote_subst\"\`\\\"" + ;; + esac + done + + case $lt_echo in + *'\$0 --fallback-echo"') + lt_echo=`$echo "X$lt_echo" | $Xsed -e 's/\\\\\\\$0 --fallback-echo"$/$0 --fallback-echo"/'` + ;; + esac + +cfgfile="${ofile}T" + trap "$rm \"$cfgfile\"; exit 1" 1 2 15 + $rm -f "$cfgfile" + { echo "$as_me:$LINENO: creating $ofile" >&5 +echo "$as_me: creating $ofile" >&6;} + + cat <<__EOF__ >> "$cfgfile" +#! $SHELL + +# `$echo "$cfgfile" | sed 's%^.*/%%'` - Provide generalized library-building support services. +# Generated automatically by $PROGRAM (GNU $PACKAGE $VERSION$TIMESTAMP) +# NOTE: Changes made to this file will be lost: look at ltmain.sh. +# +# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001 +# Free Software Foundation, Inc. +# +# This file is part of GNU Libtool: +# Originally by Gordon Matzigkeit , 1996 +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +# +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + +# A sed program that does not truncate output. +SED=$lt_SED + +# Sed that helps us avoid accidentally triggering echo(1) options like -n. +Xsed="$SED -e s/^X//" + +# The HP-UX ksh and POSIX shell print the target directory to stdout +# if CDPATH is set. +if test "X\${CDPATH+set}" = Xset; then CDPATH=:; export CDPATH; fi + +# The names of the tagged configurations supported by this script. +available_tags= + +# ### BEGIN LIBTOOL CONFIG + +# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`: + +# Shell to use when invoking shell scripts. +SHELL=$lt_SHELL + +# Whether or not to build shared libraries. +build_libtool_libs=$enable_shared + +# Whether or not to build static libraries. +build_old_libs=$enable_static + +# Whether or not to add -lc for building shared libraries. +build_libtool_need_lc=$archive_cmds_need_lc + +# Whether or not to disallow shared libs when runtime libs are static +allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes + +# Whether or not to optimize for fast installation. +fast_install=$enable_fast_install + +# The host system. +host_alias=$host_alias +host=$host + +# An echo program that does not interpret backslashes. +echo=$lt_echo + +# The archiver. +AR=$lt_AR +AR_FLAGS=$lt_AR_FLAGS + +# A C compiler. +LTCC=$lt_LTCC + +# A language-specific compiler. +CC=$lt_compiler + +# Is the compiler the GNU C compiler? +with_gcc=$GCC + +# An ERE matcher. +EGREP=$lt_EGREP + +# The linker used to build libraries. +LD=$lt_LD + +# Whether we need hard or soft links. +LN_S=$lt_LN_S + +# A BSD-compatible nm program. +NM=$lt_NM + +# A symbol stripping program +STRIP=$lt_STRIP + +# Used to examine libraries when file_magic_cmd begins "file" +MAGIC_CMD=$MAGIC_CMD + +# Used on cygwin: DLL creation program. +DLLTOOL="$DLLTOOL" + +# Used on cygwin: object dumper. +OBJDUMP="$OBJDUMP" + +# Used on cygwin: assembler. +AS="$AS" + +# The name of the directory that contains temporary libtool files. +objdir=$objdir + +# How to create reloadable object files. +reload_flag=$lt_reload_flag +reload_cmds=$lt_reload_cmds + +# How to pass a linker flag through the compiler. +wl=$lt_lt_prog_compiler_wl + +# Object file suffix (normally "o"). +objext="$ac_objext" + +# Old archive suffix (normally "a"). +libext="$libext" + +# Shared library suffix (normally ".so"). +shrext_cmds='$shrext_cmds' + +# Executable file suffix (normally ""). +exeext="$exeext" + +# Additional compiler flags for building library objects. +pic_flag=$lt_lt_prog_compiler_pic +pic_mode=$pic_mode + +# What is the maximum length of a command? +max_cmd_len=$lt_cv_sys_max_cmd_len + +# Does compiler simultaneously support -c and -o options? +compiler_c_o=$lt_lt_cv_prog_compiler_c_o + +# Must we lock files when doing compilation ? +need_locks=$lt_need_locks + +# Do we need the lib prefix for modules? +need_lib_prefix=$need_lib_prefix + +# Do we need a version for libraries? +need_version=$need_version + +# Whether dlopen is supported. +dlopen_support=$enable_dlopen + +# Whether dlopen of programs is supported. +dlopen_self=$enable_dlopen_self + +# Whether dlopen of statically linked programs is supported. +dlopen_self_static=$enable_dlopen_self_static + +# Compiler flag to prevent dynamic linking. +link_static_flag=$lt_lt_prog_compiler_static + +# Compiler flag to turn off builtin functions. +no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag + +# Compiler flag to allow reflexive dlopens. +export_dynamic_flag_spec=$lt_export_dynamic_flag_spec + +# Compiler flag to generate shared objects directly from archives. +whole_archive_flag_spec=$lt_whole_archive_flag_spec + +# Compiler flag to generate thread-safe objects. +thread_safe_flag_spec=$lt_thread_safe_flag_spec + +# Library versioning type. +version_type=$version_type + +# Format of library name prefix. +libname_spec=$lt_libname_spec + +# List of archive names. First name is the real one, the rest are links. +# The last name is the one that the linker finds with -lNAME. +library_names_spec=$lt_library_names_spec + +# The coded name of the library, if different from the real name. +soname_spec=$lt_soname_spec + +# Commands used to build and install an old-style archive. +RANLIB=$lt_RANLIB +old_archive_cmds=$lt_old_archive_cmds +old_postinstall_cmds=$lt_old_postinstall_cmds +old_postuninstall_cmds=$lt_old_postuninstall_cmds + +# Create an old-style archive from a shared archive. +old_archive_from_new_cmds=$lt_old_archive_from_new_cmds + +# Create a temporary old-style archive to link instead of a shared archive. +old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds + +# Commands used to build and install a shared archive. +archive_cmds=$lt_archive_cmds +archive_expsym_cmds=$lt_archive_expsym_cmds +postinstall_cmds=$lt_postinstall_cmds +postuninstall_cmds=$lt_postuninstall_cmds + +# Commands used to build a loadable module (assumed same as above if empty) +module_cmds=$lt_module_cmds +module_expsym_cmds=$lt_module_expsym_cmds + +# Commands to strip libraries. +old_striplib=$lt_old_striplib +striplib=$lt_striplib + +# Dependencies to place before the objects being linked to create a +# shared library. +predep_objects=$lt_predep_objects + +# Dependencies to place after the objects being linked to create a +# shared library. +postdep_objects=$lt_postdep_objects + +# Dependencies to place before the objects being linked to create a +# shared library. +predeps=$lt_predeps + +# Dependencies to place after the objects being linked to create a +# shared library. +postdeps=$lt_postdeps + +# The library search path used internally by the compiler when linking +# a shared library. +compiler_lib_search_path=$lt_compiler_lib_search_path + +# Method to check whether dependent libraries are shared objects. +deplibs_check_method=$lt_deplibs_check_method + +# Command to use when deplibs_check_method == file_magic. +file_magic_cmd=$lt_file_magic_cmd + +# Flag that allows shared libraries with undefined symbols to be built. +allow_undefined_flag=$lt_allow_undefined_flag + +# Flag that forces no undefined symbols. +no_undefined_flag=$lt_no_undefined_flag + +# Commands used to finish a libtool library installation in a directory. +finish_cmds=$lt_finish_cmds + +# Same as above, but a single script fragment to be evaled but not shown. +finish_eval=$lt_finish_eval + +# Take the output of nm and produce a listing of raw symbols and C names. +global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe + +# Transform the output of nm in a proper C declaration +global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl + +# Transform the output of nm in a C name address pair +global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address + +# This is the shared library runtime path variable. +runpath_var=$runpath_var + +# This is the shared library path variable. +shlibpath_var=$shlibpath_var + +# Is shlibpath searched before the hard-coded library search path? +shlibpath_overrides_runpath=$shlibpath_overrides_runpath + +# How to hardcode a shared library path into an executable. +hardcode_action=$hardcode_action + +# Whether we should hardcode library paths into libraries. +hardcode_into_libs=$hardcode_into_libs + +# Flag to hardcode \$libdir into a binary during linking. +# This must work even if \$libdir does not exist. +hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec + +# If ld is used when linking, flag to hardcode \$libdir into +# a binary during linking. This must work even if \$libdir does +# not exist. +hardcode_libdir_flag_spec_ld=$lt_hardcode_libdir_flag_spec_ld + +# Whether we need a single -rpath flag with a separated argument. +hardcode_libdir_separator=$lt_hardcode_libdir_separator + +# Set to yes if using DIR/libNAME${shared_ext} during linking hardcodes DIR into the +# resulting binary. +hardcode_direct=$hardcode_direct + +# Set to yes if using the -LDIR flag during linking hardcodes DIR into the +# resulting binary. +hardcode_minus_L=$hardcode_minus_L + +# Set to yes if using SHLIBPATH_VAR=DIR during linking hardcodes DIR into +# the resulting binary. +hardcode_shlibpath_var=$hardcode_shlibpath_var + +# Set to yes if building a shared library automatically hardcodes DIR into the library +# and all subsequent libraries and executables linked against it. +hardcode_automatic=$hardcode_automatic + +# Variables whose values should be saved in libtool wrapper scripts and +# restored at relink time. +variables_saved_for_relink="$variables_saved_for_relink" + +# Whether libtool must link a program against all its dependency libraries. +link_all_deplibs=$link_all_deplibs + +# Compile-time system search path for libraries +sys_lib_search_path_spec=$lt_sys_lib_search_path_spec + +# Run-time system search path for libraries +sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec + +# Fix the shell variable \$srcfile for the compiler. +fix_srcfile_path="$fix_srcfile_path" + +# Set to yes if exported symbols are required. +always_export_symbols=$always_export_symbols + +# The commands to list exported symbols. +export_symbols_cmds=$lt_export_symbols_cmds + +# The commands to extract the exported symbol list from a shared archive. +extract_expsyms_cmds=$lt_extract_expsyms_cmds + +# Symbols that should not be listed in the preloaded symbols. +exclude_expsyms=$lt_exclude_expsyms + +# Symbols that must always be exported. +include_expsyms=$lt_include_expsyms + +# ### END LIBTOOL CONFIG + +__EOF__ + + + case $host_os in + aix3*) + cat <<\EOF >> "$cfgfile" + +# AIX sometimes has problems with the GCC collect2 program. For some +# reason, if we set the COLLECT_NAMES environment variable, the problems +# vanish in a puff of smoke. +if test "X${COLLECT_NAMES+set}" != Xset; then + COLLECT_NAMES= + export COLLECT_NAMES +fi +EOF + ;; + esac + + # We use sed instead of cat because bash on DJGPP gets confused if + # if finds mixed CR/LF and LF-only lines. Since sed operates in + # text mode, it properly converts lines to CR/LF. This bash problem + # is reportedly fixed, but why not run on old versions too? + sed '$q' "$ltmain" >> "$cfgfile" || (rm -f "$cfgfile"; exit 1) + + mv -f "$cfgfile" "$ofile" || \ + (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile") + chmod +x "$ofile" + +else + # If there is no Makefile yet, we rely on a make rule to execute + # `config.status --recheck' to rerun these tests and create the + # libtool script then. + ltmain_in=`echo $ltmain | sed -e 's/\.sh$/.in/'` + if test -f "$ltmain_in"; then + test -f Makefile && make "$ltmain" + fi +fi + + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + +CC="$lt_save_CC" + + +# Check whether --with-tags or --without-tags was given. +if test "${with_tags+set}" = set; then + withval="$with_tags" + tagnames="$withval" +fi; + +if test -f "$ltmain" && test -n "$tagnames"; then + if test ! -f "${ofile}"; then + { echo "$as_me:$LINENO: WARNING: output file \`$ofile' does not exist" >&5 +echo "$as_me: WARNING: output file \`$ofile' does not exist" >&2;} + fi + + if test -z "$LTCC"; then + eval "`$SHELL ${ofile} --config | grep '^LTCC='`" + if test -z "$LTCC"; then + { echo "$as_me:$LINENO: WARNING: output file \`$ofile' does not look like a libtool script" >&5 +echo "$as_me: WARNING: output file \`$ofile' does not look like a libtool script" >&2;} + else + { echo "$as_me:$LINENO: WARNING: using \`LTCC=$LTCC', extracted from \`$ofile'" >&5 +echo "$as_me: WARNING: using \`LTCC=$LTCC', extracted from \`$ofile'" >&2;} + fi + fi + + # Extract list of available tagged configurations in $ofile. + # Note that this assumes the entire list is on one line. + available_tags=`grep "^available_tags=" "${ofile}" | $SED -e 's/available_tags=\(.*$\)/\1/' -e 's/\"//g'` + + lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," + for tagname in $tagnames; do + IFS="$lt_save_ifs" + # Check whether tagname contains only valid characters + case `$echo "X$tagname" | $Xsed -e 's:[-_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890,/]::g'` in + "") ;; + *) { { echo "$as_me:$LINENO: error: invalid tag name: $tagname" >&5 +echo "$as_me: error: invalid tag name: $tagname" >&2;} + { (exit 1); exit 1; }; } + ;; + esac + + if grep "^# ### BEGIN LIBTOOL TAG CONFIG: $tagname$" < "${ofile}" > /dev/null + then + { { echo "$as_me:$LINENO: error: tag name \"$tagname\" already exists" >&5 +echo "$as_me: error: tag name \"$tagname\" already exists" >&2;} + { (exit 1); exit 1; }; } + fi + + # Update the list of available tags. + if test -n "$tagname"; then + echo appending configuration tag \"$tagname\" to $ofile + + case $tagname in + CXX) + if test -n "$CXX" && test "X$CXX" != "Xno"; then + ac_ext=cc +ac_cpp='$CXXCPP $CPPFLAGS' +ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_cxx_compiler_gnu + + + + +archive_cmds_need_lc_CXX=no +allow_undefined_flag_CXX= +always_export_symbols_CXX=no +archive_expsym_cmds_CXX= +export_dynamic_flag_spec_CXX= +hardcode_direct_CXX=no +hardcode_libdir_flag_spec_CXX= +hardcode_libdir_flag_spec_ld_CXX= +hardcode_libdir_separator_CXX= +hardcode_minus_L_CXX=no +hardcode_automatic_CXX=no +module_cmds_CXX= +module_expsym_cmds_CXX= +link_all_deplibs_CXX=unknown +old_archive_cmds_CXX=$old_archive_cmds +no_undefined_flag_CXX= +whole_archive_flag_spec_CXX= +enable_shared_with_static_runtimes_CXX=no + +# Dependencies to place before and after the object being linked: +predep_objects_CXX= +postdep_objects_CXX= +predeps_CXX= +postdeps_CXX= +compiler_lib_search_path_CXX= + +# Source file extension for C++ test sources. +ac_ext=cc + +# Object file extension for compiled C++ test sources. +objext=o +objext_CXX=$objext + +# Code to be used in simple compile tests +lt_simple_compile_test_code="int some_variable = 0;\n" + +# Code to be used in simple link tests +lt_simple_link_test_code='int main(int, char *) { return(0); }\n' + +# ltmain only uses $CC for tagged configurations so make sure $CC is set. + +# If no C compiler was specified, use CC. +LTCC=${LTCC-"$CC"} + +# Allow CC to be a program name with arguments. +compiler=$CC + + +# Allow CC to be a program name with arguments. +lt_save_CC=$CC +lt_save_LD=$LD +lt_save_GCC=$GCC +GCC=$GXX +lt_save_with_gnu_ld=$with_gnu_ld +lt_save_path_LD=$lt_cv_path_LD +if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then + lt_cv_prog_gnu_ld=$lt_cv_prog_gnu_ldcxx +else + unset lt_cv_prog_gnu_ld +fi +if test -n "${lt_cv_path_LDCXX+set}"; then + lt_cv_path_LD=$lt_cv_path_LDCXX +else + unset lt_cv_path_LD +fi +test -z "${LDCXX+set}" || LD=$LDCXX +CC=${CXX-"c++"} +compiler=$CC +compiler_CXX=$CC +cc_basename=`$echo X"$compiler" | $Xsed -e 's%^.*/%%'` + +# We don't want -fno-exception wen compiling C++ code, so set the +# no_builtin_flag separately +if test "$GXX" = yes; then + lt_prog_compiler_no_builtin_flag_CXX=' -fno-builtin' +else + lt_prog_compiler_no_builtin_flag_CXX= +fi + +if test "$GXX" = yes; then + # Set up default GNU C++ configuration + + +# Check whether --with-gnu-ld or --without-gnu-ld was given. +if test "${with_gnu_ld+set}" = set; then + withval="$with_gnu_ld" + test "$withval" = no || with_gnu_ld=yes +else + with_gnu_ld=no +fi; +ac_prog=ld +if test "$GCC" = yes; then + # Check if gcc -print-prog-name=ld gives a path. + echo "$as_me:$LINENO: checking for ld used by $CC" >&5 +echo $ECHO_N "checking for ld used by $CC... $ECHO_C" >&6 + case $host in + *-*-mingw*) + # gcc leaves a trailing carriage return which upsets mingw + ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; + *) + ac_prog=`($CC -print-prog-name=ld) 2>&5` ;; + esac + case $ac_prog in + # Accept absolute paths. + [\\/]* | ?:[\\/]*) + re_direlt='/[^/][^/]*/\.\./' + # Canonicalize the pathname of ld + ac_prog=`echo $ac_prog| $SED 's%\\\\%/%g'` + while echo $ac_prog | grep "$re_direlt" > /dev/null 2>&1; do + ac_prog=`echo $ac_prog| $SED "s%$re_direlt%/%"` + done + test -z "$LD" && LD="$ac_prog" + ;; + "") + # If it fails, then pretend we aren't using GCC. + ac_prog=ld + ;; + *) + # If it is relative, then search for the first ld in PATH. + with_gnu_ld=unknown + ;; + esac +elif test "$with_gnu_ld" = yes; then + echo "$as_me:$LINENO: checking for GNU ld" >&5 +echo $ECHO_N "checking for GNU ld... $ECHO_C" >&6 +else + echo "$as_me:$LINENO: checking for non-GNU ld" >&5 +echo $ECHO_N "checking for non-GNU ld... $ECHO_C" >&6 +fi +if test "${lt_cv_path_LD+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -z "$LD"; then + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR + for ac_dir in $PATH; do + IFS="$lt_save_ifs" + test -z "$ac_dir" && ac_dir=. + if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then + lt_cv_path_LD="$ac_dir/$ac_prog" + # Check to see if the program is GNU ld. I'd rather use --version, + # but apparently some GNU ld's only accept -v. + # Break only if it was the GNU/non-GNU ld that we prefer. + case `"$lt_cv_path_LD" -v 2>&1 &5 +echo "${ECHO_T}$LD" >&6 +else + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 +fi +test -z "$LD" && { { echo "$as_me:$LINENO: error: no acceptable ld found in \$PATH" >&5 +echo "$as_me: error: no acceptable ld found in \$PATH" >&2;} + { (exit 1); exit 1; }; } +echo "$as_me:$LINENO: checking if the linker ($LD) is GNU ld" >&5 +echo $ECHO_N "checking if the linker ($LD) is GNU ld... $ECHO_C" >&6 +if test "${lt_cv_prog_gnu_ld+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + # I'd rather use --version here, but apparently some GNU ld's only accept -v. +case `$LD -v 2>&1 &5 +echo "${ECHO_T}$lt_cv_prog_gnu_ld" >&6 +with_gnu_ld=$lt_cv_prog_gnu_ld + + + + # Check if GNU C++ uses GNU ld as the underlying linker, since the + # archiving commands below assume that GNU ld is being used. + if test "$with_gnu_ld" = yes; then + archive_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + + hardcode_libdir_flag_spec_CXX='${wl}--rpath ${wl}$libdir' + export_dynamic_flag_spec_CXX='${wl}--export-dynamic' + + # If archive_cmds runs LD, not CC, wlarc should be empty + # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to + # investigate it a little bit more. (MM) + wlarc='${wl}' + + # ancient GNU ld didn't support --whole-archive et. al. + if eval "`$CC -print-prog-name=ld` --help 2>&1" | \ + grep 'no-whole-archive' > /dev/null; then + whole_archive_flag_spec_CXX="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' + else + whole_archive_flag_spec_CXX= + fi + else + with_gnu_ld=no + wlarc= + + # A generic and very simple default shared library creation + # command for GNU C++ for the case where it uses the native + # linker, instead of GNU ld. If possible, this setting should + # overridden to take advantage of the native linker features on + # the platform it is being used on. + archive_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib' + fi + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "\-L"' + +else + GXX=no + with_gnu_ld=no + wlarc= +fi + +# PORTME: fill in a description of your system's C++ link characteristics +echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) supports shared libraries" >&5 +echo $ECHO_N "checking whether the $compiler linker ($LD) supports shared libraries... $ECHO_C" >&6 +ld_shlibs_CXX=yes +case $host_os in + aix3*) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + aix4* | aix5*) + if test "$host_cpu" = ia64; then + # On IA64, the linker does run time linking by default, so we don't + # have to do anything special. + aix_use_runtimelinking=no + exp_sym_flag='-Bexport' + no_entry_flag="" + else + aix_use_runtimelinking=no + + # Test if we are trying to use run time linking or normal + # AIX style linking. If -brtl is somewhere in LDFLAGS, we + # need to do runtime linking. + case $host_os in aix4.[23]|aix4.[23].*|aix5*) + for ld_flag in $LDFLAGS; do + case $ld_flag in + *-brtl*) + aix_use_runtimelinking=yes + break + ;; + esac + done + esac + + exp_sym_flag='-bexport' + no_entry_flag='-bnoentry' + fi + + # When large executables or shared objects are built, AIX ld can + # have problems creating the table of contents. If linking a library + # or program results in "error TOC overflow" add -mminimal-toc to + # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not + # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. + + archive_cmds_CXX='' + hardcode_direct_CXX=yes + hardcode_libdir_separator_CXX=':' + link_all_deplibs_CXX=yes + + if test "$GXX" = yes; then + case $host_os in aix4.012|aix4.012.*) + # We only want to do this on AIX 4.2 and lower, the check + # below for broken collect2 doesn't work under 4.3+ + collect2name=`${CC} -print-prog-name=collect2` + if test -f "$collect2name" && \ + strings "$collect2name" | grep resolve_lib_name >/dev/null + then + # We have reworked collect2 + hardcode_direct_CXX=yes + else + # We have old collect2 + hardcode_direct_CXX=unsupported + # It fails to find uninstalled libraries when the uninstalled + # path is not listed in the libpath. Setting hardcode_minus_L + # to unsupported forces relinking + hardcode_minus_L_CXX=yes + hardcode_libdir_flag_spec_CXX='-L$libdir' + hardcode_libdir_separator_CXX= + fi + esac + shared_flag='-shared' + else + # not using gcc + if test "$host_cpu" = ia64; then + # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release + # chokes on -Wl,-G. The following line is correct: + shared_flag='-G' + else + if test "$aix_use_runtimelinking" = yes; then + shared_flag='${wl}-G' + else + shared_flag='${wl}-bM:SRE' + fi + fi + fi + + # It seems that -bexpall does not export symbols beginning with + # underscore (_), so it is better to generate a list of symbols to export. + always_export_symbols_CXX=yes + if test "$aix_use_runtimelinking" = yes; then + # Warning - without using the other runtime loading flags (-brtl), + # -berok will link without error, but may produce a broken library. + allow_undefined_flag_CXX='-berok' + # Determine the default libpath from the value encoded in an empty executable. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_cxx_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + +aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; } +}'` +# Check for a 64-bit object if we didn't find anything. +if test -z "$aix_libpath"; then aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; } +}'`; fi +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +fi +rm -f conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi + + hardcode_libdir_flag_spec_CXX='${wl}-blibpath:$libdir:'"$aix_libpath" + + archive_expsym_cmds_CXX="\$CC"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$no_entry_flag \${wl}$exp_sym_flag:\$export_symbols $shared_flag" + else + if test "$host_cpu" = ia64; then + hardcode_libdir_flag_spec_CXX='${wl}-R $libdir:/usr/lib:/lib' + allow_undefined_flag_CXX="-z nodefs" + archive_expsym_cmds_CXX="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$no_entry_flag \${wl}$exp_sym_flag:\$export_symbols" + else + # Determine the default libpath from the value encoded in an empty executable. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_cxx_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + +aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; } +}'` +# Check for a 64-bit object if we didn't find anything. +if test -z "$aix_libpath"; then aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; } +}'`; fi +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +fi +rm -f conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi + + hardcode_libdir_flag_spec_CXX='${wl}-blibpath:$libdir:'"$aix_libpath" + # Warning - without using the other run time loading flags, + # -berok will link without error, but may produce a broken library. + no_undefined_flag_CXX=' ${wl}-bernotok' + allow_undefined_flag_CXX=' ${wl}-berok' + # -bexpall does not export symbols beginning with underscore (_) + always_export_symbols_CXX=yes + # Exported symbols can be pulled into shared objects from archives + whole_archive_flag_spec_CXX=' ' + archive_cmds_need_lc_CXX=yes + # This is similar to how AIX traditionally builds it's shared libraries. + archive_expsym_cmds_CXX="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags ${wl}-bE:$export_symbols ${wl}-bnoentry${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' + fi + fi + ;; + chorus*) + case $cc_basename in + *) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + esac + ;; + + cygwin* | mingw* | pw32*) + # _LT_AC_TAGVAR(hardcode_libdir_flag_spec, CXX) is actually meaningless, + # as there is no search path for DLLs. + hardcode_libdir_flag_spec_CXX='-L$libdir' + allow_undefined_flag_CXX=unsupported + always_export_symbols_CXX=no + enable_shared_with_static_runtimes_CXX=yes + + if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then + archive_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--image-base=0x10000000 ${wl}--out-implib,$lib' + # If the export-symbols file already is a .def file (1st line + # is EXPORTS), use it as is; otherwise, prepend... + archive_expsym_cmds_CXX='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then + cp $export_symbols $output_objdir/$soname.def; + else + echo EXPORTS > $output_objdir/$soname.def; + cat $export_symbols >> $output_objdir/$soname.def; + fi~ + $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--image-base=0x10000000 ${wl}--out-implib,$lib' + else + ld_shlibs_CXX=no + fi + ;; + + darwin* | rhapsody*) + if test "$GXX" = yes; then + archive_cmds_need_lc_CXX=no + case "$host_os" in + rhapsody* | darwin1.[012]) + allow_undefined_flag_CXX='-undefined suppress' + ;; + *) # Darwin 1.3 on + if test -z ${MACOSX_DEPLOYMENT_TARGET} ; then + allow_undefined_flag_CXX='-flat_namespace -undefined suppress' + else + case ${MACOSX_DEPLOYMENT_TARGET} in + 10.[012]) + allow_undefined_flag_CXX='-flat_namespace -undefined suppress' + ;; + 10.*) + allow_undefined_flag_CXX='-undefined dynamic_lookup' + ;; + esac + fi + ;; + esac + lt_int_apple_cc_single_mod=no + output_verbose_link_cmd='echo' + if $CC -dumpspecs 2>&1 | grep 'single_module' >/dev/null ; then + lt_int_apple_cc_single_mod=yes + fi + if test "X$lt_int_apple_cc_single_mod" = Xyes ; then + archive_cmds_CXX='$CC -dynamiclib -single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring' + else + archive_cmds_CXX='$CC -r ${wl}-bind_at_load -keep_private_externs -nostdlib -o ${lib}-master.o $libobjs~$CC -dynamiclib $allow_undefined_flag -o $lib ${lib}-master.o $deplibs $compiler_flags -install_name $rpath/$soname $verstring' + fi + module_cmds_CXX='$CC ${wl}-bind_at_load $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags' + + # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin ld's + if test "X$lt_int_apple_cc_single_mod" = Xyes ; then + archive_expsym_cmds_CXX='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -dynamiclib -single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + else + archive_expsym_cmds_CXX='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -r ${wl}-bind_at_load -keep_private_externs -nostdlib -o ${lib}-master.o $libobjs~$CC -dynamiclib $allow_undefined_flag -o $lib ${lib}-master.o $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + fi + module_expsym_cmds_CXX='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + hardcode_direct_CXX=no + hardcode_automatic_CXX=yes + hardcode_shlibpath_var_CXX=unsupported + whole_archive_flag_spec_CXX='-all_load $convenience' + link_all_deplibs_CXX=yes + else + ld_shlibs_CXX=no + fi + ;; + + dgux*) + case $cc_basename in + ec++) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + ghcx) + # Green Hills C++ Compiler + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + *) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + esac + ;; + freebsd12*) + # C++ shared libraries reported to be fairly broken before switch to ELF + ld_shlibs_CXX=no + ;; + freebsd-elf*) + archive_cmds_need_lc_CXX=no + ;; + freebsd* | kfreebsd*-gnu) + # FreeBSD 3 and later use GNU C++ and GNU ld with standard ELF + # conventions + ld_shlibs_CXX=yes + ;; + gnu*) + ;; + hpux9*) + hardcode_libdir_flag_spec_CXX='${wl}+b ${wl}$libdir' + hardcode_libdir_separator_CXX=: + export_dynamic_flag_spec_CXX='${wl}-E' + hardcode_direct_CXX=yes + hardcode_minus_L_CXX=yes # Not in the search PATH, + # but as the default + # location of the library. + + case $cc_basename in + CC) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + aCC) + archive_cmds_CXX='$rm $output_objdir/$soname~$CC -b ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | grep "-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list' + ;; + *) + if test "$GXX" = yes; then + archive_cmds_CXX='$rm $output_objdir/$soname~$CC -shared -nostdlib -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + else + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + fi + ;; + esac + ;; + hpux10*|hpux11*) + if test $with_gnu_ld = no; then + case "$host_cpu" in + hppa*64*) + hardcode_libdir_flag_spec_CXX='${wl}+b ${wl}$libdir' + hardcode_libdir_flag_spec_ld_CXX='+b $libdir' + hardcode_libdir_separator_CXX=: + ;; + ia64*) + hardcode_libdir_flag_spec_CXX='-L$libdir' + ;; + *) + hardcode_libdir_flag_spec_CXX='${wl}+b ${wl}$libdir' + hardcode_libdir_separator_CXX=: + export_dynamic_flag_spec_CXX='${wl}-E' + ;; + esac + fi + case "$host_cpu" in + hppa*64*) + hardcode_direct_CXX=no + hardcode_shlibpath_var_CXX=no + ;; + ia64*) + hardcode_direct_CXX=no + hardcode_shlibpath_var_CXX=no + hardcode_minus_L_CXX=yes # Not in the search PATH, + # but as the default + # location of the library. + ;; + *) + hardcode_direct_CXX=yes + hardcode_minus_L_CXX=yes # Not in the search PATH, + # but as the default + # location of the library. + ;; + esac + + case $cc_basename in + CC) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + aCC) + case "$host_cpu" in + hppa*64*|ia64*) + archive_cmds_CXX='$LD -b +h $soname -o $lib $linker_flags $libobjs $deplibs' + ;; + *) + archive_cmds_CXX='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + esac + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | grep "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list' + ;; + *) + if test "$GXX" = yes; then + if test $with_gnu_ld = no; then + case "$host_cpu" in + ia64*|hppa*64*) + archive_cmds_CXX='$LD -b +h $soname -o $lib $linker_flags $libobjs $deplibs' + ;; + *) + archive_cmds_CXX='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + esac + fi + else + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + fi + ;; + esac + ;; + irix5* | irix6*) + case $cc_basename in + CC) + # SGI C++ + archive_cmds_CXX='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${objdir}/so_locations -o $lib' + + # Archives containing C++ object files must be created using + # "CC -ar", where "CC" is the IRIX C++ compiler. This is + # necessary to make sure instantiated templates are included + # in the archive. + old_archive_cmds_CXX='$CC -ar -WR,-u -o $oldlib $oldobjs' + ;; + *) + if test "$GXX" = yes; then + if test "$with_gnu_ld" = no; then + archive_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${objdir}/so_locations -o $lib' + else + archive_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` -o $lib' + fi + fi + link_all_deplibs_CXX=yes + ;; + esac + hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator_CXX=: + ;; + linux*) + case $cc_basename in + KCC) + # Kuck and Associates, Inc. (KAI) C++ Compiler + + # KCC will only create a shared library if the output file + # ends with ".so" (or ".sl" for HP-UX), so rename the library + # to its proper name (with version) after linking. + archive_cmds_CXX='tempext=`echo $shared_ext | $SED -e '\''s/\([^()0-9A-Za-z{}]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' + archive_expsym_cmds_CXX='tempext=`echo $shared_ext | $SED -e '\''s/\([^()0-9A-Za-z{}]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib ${wl}-retain-symbols-file,$export_symbols; mv \$templib $lib' + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | grep "ld"`; rm -f libconftest$shared_ext; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list' + + hardcode_libdir_flag_spec_CXX='${wl}--rpath,$libdir' + export_dynamic_flag_spec_CXX='${wl}--export-dynamic' + + # Archives containing C++ object files must be created using + # "CC -Bstatic", where "CC" is the KAI C++ compiler. + old_archive_cmds_CXX='$CC -Bstatic -o $oldlib $oldobjs' + ;; + icpc) + # Intel C++ + with_gnu_ld=yes + archive_cmds_need_lc_CXX=no + archive_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir' + export_dynamic_flag_spec_CXX='${wl}--export-dynamic' + whole_archive_flag_spec_CXX='${wl}--whole-archive$convenience ${wl}--no-whole-archive' + ;; + cxx) + # Compaq C++ + archive_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib ${wl}-retain-symbols-file $wl$export_symbols' + + runpath_var=LD_RUN_PATH + hardcode_libdir_flag_spec_CXX='-rpath $libdir' + hardcode_libdir_separator_CXX=: + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "ld"`; templist=`echo $templist | $SED "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list' + ;; + esac + ;; + lynxos*) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + m88k*) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + mvs*) + case $cc_basename in + cxx) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + *) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + esac + ;; + netbsd* | netbsdelf*-gnu | knetbsd*-gnu) + if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then + archive_cmds_CXX='$LD -Bshareable -o $lib $predep_objects $libobjs $deplibs $postdep_objects $linker_flags' + wlarc= + hardcode_libdir_flag_spec_CXX='-R$libdir' + hardcode_direct_CXX=yes + hardcode_shlibpath_var_CXX=no + fi + # Workaround some broken pre-1.5 toolchains + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep conftest.$objext | $SED -e "s:-lgcc -lc -lgcc::"' + ;; + osf3*) + case $cc_basename in + KCC) + # Kuck and Associates, Inc. (KAI) C++ Compiler + + # KCC will only create a shared library if the output file + # ends with ".so" (or ".sl" for HP-UX), so rename the library + # to its proper name (with version) after linking. + archive_cmds_CXX='tempext=`echo $shared_ext | $SED -e '\''s/\([^()0-9A-Za-z{}]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' + + hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir' + hardcode_libdir_separator_CXX=: + + # Archives containing C++ object files must be created using + # "CC -Bstatic", where "CC" is the KAI C++ compiler. + old_archive_cmds_CXX='$CC -Bstatic -o $oldlib $oldobjs' + + ;; + RCC) + # Rational C++ 2.4.1 + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + cxx) + allow_undefined_flag_CXX=' ${wl}-expect_unresolved ${wl}\*' + archive_cmds_CXX='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && echo ${wl}-set_version $verstring` -update_registry ${objdir}/so_locations -o $lib' + + hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator_CXX=: + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "ld" | grep -v "ld:"`; templist=`echo $templist | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list' + ;; + *) + if test "$GXX" = yes && test "$with_gnu_ld" = no; then + allow_undefined_flag_CXX=' ${wl}-expect_unresolved ${wl}\*' + archive_cmds_CXX='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${objdir}/so_locations -o $lib' + + hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator_CXX=: + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "\-L"' + + else + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + fi + ;; + esac + ;; + osf4* | osf5*) + case $cc_basename in + KCC) + # Kuck and Associates, Inc. (KAI) C++ Compiler + + # KCC will only create a shared library if the output file + # ends with ".so" (or ".sl" for HP-UX), so rename the library + # to its proper name (with version) after linking. + archive_cmds_CXX='tempext=`echo $shared_ext | $SED -e '\''s/\([^()0-9A-Za-z{}]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' + + hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir' + hardcode_libdir_separator_CXX=: + + # Archives containing C++ object files must be created using + # the KAI C++ compiler. + old_archive_cmds_CXX='$CC -o $oldlib $oldobjs' + ;; + RCC) + # Rational C++ 2.4.1 + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + cxx) + allow_undefined_flag_CXX=' -expect_unresolved \*' + archive_cmds_CXX='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${objdir}/so_locations -o $lib' + archive_expsym_cmds_CXX='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~ + echo "-hidden">> $lib.exp~ + $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname -Wl,-input -Wl,$lib.exp `test -n "$verstring" && echo -set_version $verstring` -update_registry $objdir/so_locations -o $lib~ + $rm $lib.exp' + + hardcode_libdir_flag_spec_CXX='-rpath $libdir' + hardcode_libdir_separator_CXX=: + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "ld" | grep -v "ld:"`; templist=`echo $templist | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list' + ;; + *) + if test "$GXX" = yes && test "$with_gnu_ld" = no; then + allow_undefined_flag_CXX=' ${wl}-expect_unresolved ${wl}\*' + archive_cmds_CXX='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${objdir}/so_locations -o $lib' + + hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator_CXX=: + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "\-L"' + + else + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + fi + ;; + esac + ;; + psos*) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + sco*) + archive_cmds_need_lc_CXX=no + case $cc_basename in + CC) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + *) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + esac + ;; + sunos4*) + case $cc_basename in + CC) + # Sun C++ 4.x + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + lcc) + # Lucid + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + *) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + esac + ;; + solaris*) + case $cc_basename in + CC) + # Sun C++ 4.2, 5.x and Centerline C++ + no_undefined_flag_CXX=' -zdefs' + archive_cmds_CXX='$CC -G${allow_undefined_flag} -nolib -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + archive_expsym_cmds_CXX='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~ + $CC -G${allow_undefined_flag} -nolib ${wl}-M ${wl}$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$rm $lib.exp' + + hardcode_libdir_flag_spec_CXX='-R$libdir' + hardcode_shlibpath_var_CXX=no + case $host_os in + solaris2.0-5 | solaris2.0-5.*) ;; + *) + # The C++ compiler is used as linker so we must use $wl + # flag to pass the commands to the underlying system + # linker. + # Supported since Solaris 2.6 (maybe 2.5.1?) + whole_archive_flag_spec_CXX='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' + ;; + esac + link_all_deplibs_CXX=yes + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`$CC -G $CFLAGS -v conftest.$objext 2>&1 | grep "\-[LR]"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list' + + # Archives containing C++ object files must be created using + # "CC -xar", where "CC" is the Sun C++ compiler. This is + # necessary to make sure instantiated templates are included + # in the archive. + old_archive_cmds_CXX='$CC -xar -o $oldlib $oldobjs' + ;; + gcx) + # Green Hills C++ Compiler + archive_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' + + # The C++ compiler must be used to create the archive. + old_archive_cmds_CXX='$CC $LDFLAGS -archive -o $oldlib $oldobjs' + ;; + *) + # GNU C++ compiler with Solaris linker + if test "$GXX" = yes && test "$with_gnu_ld" = no; then + no_undefined_flag_CXX=' ${wl}-z ${wl}defs' + if $CC --version | grep -v '^2\.7' > /dev/null; then + archive_cmds_CXX='$CC -shared -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' + archive_expsym_cmds_CXX='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~ + $CC -shared -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$rm $lib.exp' + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + output_verbose_link_cmd="$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep \"\-L\"" + else + # g++ 2.7 appears to require `-G' NOT `-shared' on this + # platform. + archive_cmds_CXX='$CC -G -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' + archive_expsym_cmds_CXX='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~ + $CC -G -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$rm $lib.exp' + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + output_verbose_link_cmd="$CC -G $CFLAGS -v conftest.$objext 2>&1 | grep \"\-L\"" + fi + + hardcode_libdir_flag_spec_CXX='${wl}-R $wl$libdir' + fi + ;; + esac + ;; + sysv5OpenUNIX8* | sysv5UnixWare7* | sysv5uw[78]* | unixware7*) + archive_cmds_need_lc_CXX=no + ;; + tandem*) + case $cc_basename in + NCC) + # NonStop-UX NCC 3.20 + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + *) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + esac + ;; + vxworks*) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + *) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; +esac +echo "$as_me:$LINENO: result: $ld_shlibs_CXX" >&5 +echo "${ECHO_T}$ld_shlibs_CXX" >&6 +test "$ld_shlibs_CXX" = no && can_build_shared=no + +GCC_CXX="$GXX" +LD_CXX="$LD" + + +cat > conftest.$ac_ext <&5 + (eval $ac_compile) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + # Parse the compiler output and extract the necessary + # objects, libraries and library flags. + + # Sentinel used to keep track of whether or not we are before + # the conftest object file. + pre_test_object_deps_done=no + + # The `*' in the case matches for architectures that use `case' in + # $output_verbose_cmd can trigger glob expansion during the loop + # eval without this substitution. + output_verbose_link_cmd="`$echo \"X$output_verbose_link_cmd\" | $Xsed -e \"$no_glob_subst\"`" + + for p in `eval $output_verbose_link_cmd`; do + case $p in + + -L* | -R* | -l*) + # Some compilers place space between "-{L,R}" and the path. + # Remove the space. + if test $p = "-L" \ + || test $p = "-R"; then + prev=$p + continue + else + prev= + fi + + if test "$pre_test_object_deps_done" = no; then + case $p in + -L* | -R*) + # Internal compiler library paths should come after those + # provided the user. The postdeps already come after the + # user supplied libs so there is no need to process them. + if test -z "$compiler_lib_search_path_CXX"; then + compiler_lib_search_path_CXX="${prev}${p}" + else + compiler_lib_search_path_CXX="${compiler_lib_search_path_CXX} ${prev}${p}" + fi + ;; + # The "-l" case would never come before the object being + # linked, so don't bother handling this case. + esac + else + if test -z "$postdeps_CXX"; then + postdeps_CXX="${prev}${p}" + else + postdeps_CXX="${postdeps_CXX} ${prev}${p}" + fi + fi + ;; + + *.$objext) + # This assumes that the test object file only shows up + # once in the compiler output. + if test "$p" = "conftest.$objext"; then + pre_test_object_deps_done=yes + continue + fi + + if test "$pre_test_object_deps_done" = no; then + if test -z "$predep_objects_CXX"; then + predep_objects_CXX="$p" + else + predep_objects_CXX="$predep_objects_CXX $p" + fi + else + if test -z "$postdep_objects_CXX"; then + postdep_objects_CXX="$p" + else + postdep_objects_CXX="$postdep_objects_CXX $p" + fi + fi + ;; + + *) ;; # Ignore the rest. + + esac + done + + # Clean up. + rm -f a.out a.exe +else + echo "libtool.m4: error: problem compiling CXX test program" +fi + +$rm -f confest.$objext + +case " $postdeps_CXX " in +*" -lc "*) archive_cmds_need_lc_CXX=no ;; +esac + +lt_prog_compiler_wl_CXX= +lt_prog_compiler_pic_CXX= +lt_prog_compiler_static_CXX= + +echo "$as_me:$LINENO: checking for $compiler option to produce PIC" >&5 +echo $ECHO_N "checking for $compiler option to produce PIC... $ECHO_C" >&6 + + # C++ specific cases for pic, static, wl, etc. + if test "$GXX" = yes; then + lt_prog_compiler_wl_CXX='-Wl,' + lt_prog_compiler_static_CXX='-static' + + case $host_os in + aix*) + # All AIX code is PIC. + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + lt_prog_compiler_static_CXX='-Bstatic' + fi + ;; + amigaos*) + # FIXME: we need at least 68020 code to build shared libraries, but + # adding the `-m68020' flag to GCC prevents building anything better, + # like `-m68040'. + lt_prog_compiler_pic_CXX='-m68020 -resident32 -malways-restore-a4' + ;; + beos* | cygwin* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) + # PIC is the default for these OSes. + ;; + mingw* | os2* | pw32*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + lt_prog_compiler_pic_CXX='-DDLL_EXPORT' + ;; + darwin* | rhapsody*) + # PIC is the default on this platform + # Common symbols not allowed in MH_DYLIB files + lt_prog_compiler_pic_CXX='-fno-common' + ;; + *djgpp*) + # DJGPP does not support shared libraries at all + lt_prog_compiler_pic_CXX= + ;; + sysv4*MP*) + if test -d /usr/nec; then + lt_prog_compiler_pic_CXX=-Kconform_pic + fi + ;; + hpux*) + # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but + # not for PA HP-UX. + case "$host_cpu" in + hppa*64*|ia64*) + ;; + *) + lt_prog_compiler_pic_CXX='-fPIC' + ;; + esac + ;; + *) + lt_prog_compiler_pic_CXX='-fPIC' + ;; + esac + else + case $host_os in + aix4* | aix5*) + # All AIX code is PIC. + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + lt_prog_compiler_static_CXX='-Bstatic' + else + lt_prog_compiler_static_CXX='-bnso -bI:/lib/syscalls.exp' + fi + ;; + chorus*) + case $cc_basename in + cxch68) + # Green Hills C++ Compiler + # _LT_AC_TAGVAR(lt_prog_compiler_static, CXX)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a" + ;; + esac + ;; + dgux*) + case $cc_basename in + ec++) + lt_prog_compiler_pic_CXX='-KPIC' + ;; + ghcx) + # Green Hills C++ Compiler + lt_prog_compiler_pic_CXX='-pic' + ;; + *) + ;; + esac + ;; + freebsd* | kfreebsd*-gnu) + # FreeBSD uses GNU C++ + ;; + hpux9* | hpux10* | hpux11*) + case $cc_basename in + CC) + lt_prog_compiler_wl_CXX='-Wl,' + lt_prog_compiler_static_CXX="${ac_cv_prog_cc_wl}-a ${ac_cv_prog_cc_wl}archive" + if test "$host_cpu" != ia64; then + lt_prog_compiler_pic_CXX='+Z' + fi + ;; + aCC) + lt_prog_compiler_wl_CXX='-Wl,' + lt_prog_compiler_static_CXX="${ac_cv_prog_cc_wl}-a ${ac_cv_prog_cc_wl}archive" + case "$host_cpu" in + hppa*64*|ia64*) + # +Z the default + ;; + *) + lt_prog_compiler_pic_CXX='+Z' + ;; + esac + ;; + *) + ;; + esac + ;; + irix5* | irix6* | nonstopux*) + case $cc_basename in + CC) + lt_prog_compiler_wl_CXX='-Wl,' + lt_prog_compiler_static_CXX='-non_shared' + # CC pic flag -KPIC is the default. + ;; + *) + ;; + esac + ;; + linux*) + case $cc_basename in + KCC) + # KAI C++ Compiler + lt_prog_compiler_wl_CXX='--backend -Wl,' + lt_prog_compiler_pic_CXX='-fPIC' + ;; + icpc) + # Intel C++ + lt_prog_compiler_wl_CXX='-Wl,' + lt_prog_compiler_pic_CXX='-KPIC' + lt_prog_compiler_static_CXX='-static' + ;; + cxx) + # Compaq C++ + # Make sure the PIC flag is empty. It appears that all Alpha + # Linux and Compaq Tru64 Unix objects are PIC. + lt_prog_compiler_pic_CXX= + lt_prog_compiler_static_CXX='-non_shared' + ;; + *) + ;; + esac + ;; + lynxos*) + ;; + m88k*) + ;; + mvs*) + case $cc_basename in + cxx) + lt_prog_compiler_pic_CXX='-W c,exportall' + ;; + *) + ;; + esac + ;; + netbsd* | netbsdelf*-gnu | knetbsd*-gnu) + ;; + osf3* | osf4* | osf5*) + case $cc_basename in + KCC) + lt_prog_compiler_wl_CXX='--backend -Wl,' + ;; + RCC) + # Rational C++ 2.4.1 + lt_prog_compiler_pic_CXX='-pic' + ;; + cxx) + # Digital/Compaq C++ + lt_prog_compiler_wl_CXX='-Wl,' + # Make sure the PIC flag is empty. It appears that all Alpha + # Linux and Compaq Tru64 Unix objects are PIC. + lt_prog_compiler_pic_CXX= + lt_prog_compiler_static_CXX='-non_shared' + ;; + *) + ;; + esac + ;; + psos*) + ;; + sco*) + case $cc_basename in + CC) + lt_prog_compiler_pic_CXX='-fPIC' + ;; + *) + ;; + esac + ;; + solaris*) + case $cc_basename in + CC) + # Sun C++ 4.2, 5.x and Centerline C++ + lt_prog_compiler_pic_CXX='-KPIC' + lt_prog_compiler_static_CXX='-Bstatic' + lt_prog_compiler_wl_CXX='-Qoption ld ' + ;; + gcx) + # Green Hills C++ Compiler + lt_prog_compiler_pic_CXX='-PIC' + ;; + *) + ;; + esac + ;; + sunos4*) + case $cc_basename in + CC) + # Sun C++ 4.x + lt_prog_compiler_pic_CXX='-pic' + lt_prog_compiler_static_CXX='-Bstatic' + ;; + lcc) + # Lucid + lt_prog_compiler_pic_CXX='-pic' + ;; + *) + ;; + esac + ;; + tandem*) + case $cc_basename in + NCC) + # NonStop-UX NCC 3.20 + lt_prog_compiler_pic_CXX='-KPIC' + ;; + *) + ;; + esac + ;; + unixware*) + ;; + vxworks*) + ;; + *) + lt_prog_compiler_can_build_shared_CXX=no + ;; + esac + fi + +echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_CXX" >&5 +echo "${ECHO_T}$lt_prog_compiler_pic_CXX" >&6 + +# +# Check to make sure the PIC flag actually works. +# +if test -n "$lt_prog_compiler_pic_CXX"; then + +echo "$as_me:$LINENO: checking if $compiler PIC flag $lt_prog_compiler_pic_CXX works" >&5 +echo $ECHO_N "checking if $compiler PIC flag $lt_prog_compiler_pic_CXX works... $ECHO_C" >&6 +if test "${lt_prog_compiler_pic_works_CXX+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + lt_prog_compiler_pic_works_CXX=no + ac_outfile=conftest.$ac_objext + printf "$lt_simple_compile_test_code" > conftest.$ac_ext + lt_compiler_flag="$lt_prog_compiler_pic_CXX -DPIC" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + # The option is referenced via a variable to avoid confusing sed. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}? :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:11016: $lt_compile\"" >&5) + (eval "$lt_compile" 2>conftest.err) + ac_status=$? + cat conftest.err >&5 + echo "$as_me:11020: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s "$ac_outfile"; then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings + if test ! -s conftest.err; then + lt_prog_compiler_pic_works_CXX=yes + fi + fi + $rm conftest* + +fi +echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_works_CXX" >&5 +echo "${ECHO_T}$lt_prog_compiler_pic_works_CXX" >&6 + +if test x"$lt_prog_compiler_pic_works_CXX" = xyes; then + case $lt_prog_compiler_pic_CXX in + "" | " "*) ;; + *) lt_prog_compiler_pic_CXX=" $lt_prog_compiler_pic_CXX" ;; + esac +else + lt_prog_compiler_pic_CXX= + lt_prog_compiler_can_build_shared_CXX=no +fi + +fi +case "$host_os" in + # For platforms which do not support PIC, -DPIC is meaningless: + *djgpp*) + lt_prog_compiler_pic_CXX= + ;; + *) + lt_prog_compiler_pic_CXX="$lt_prog_compiler_pic_CXX -DPIC" + ;; +esac + +echo "$as_me:$LINENO: checking if $compiler supports -c -o file.$ac_objext" >&5 +echo $ECHO_N "checking if $compiler supports -c -o file.$ac_objext... $ECHO_C" >&6 +if test "${lt_cv_prog_compiler_c_o_CXX+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + lt_cv_prog_compiler_c_o_CXX=no + $rm -r conftest 2>/dev/null + mkdir conftest + cd conftest + mkdir out + printf "$lt_simple_compile_test_code" > conftest.$ac_ext + + lt_compiler_flag="-o out/conftest2.$ac_objext" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}? :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:11076: $lt_compile\"" >&5) + (eval "$lt_compile" 2>out/conftest.err) + ac_status=$? + cat out/conftest.err >&5 + echo "$as_me:11080: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s out/conftest2.$ac_objext + then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings + if test ! -s out/conftest.err; then + lt_cv_prog_compiler_c_o_CXX=yes + fi + fi + chmod u+w . + $rm conftest* + # SGI C++ compiler will create directory out/ii_files/ for + # template instantiation + test -d out/ii_files && $rm out/ii_files/* && rmdir out/ii_files + $rm out/* && rmdir out + cd .. + rmdir conftest + $rm conftest* + +fi +echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_c_o_CXX" >&5 +echo "${ECHO_T}$lt_cv_prog_compiler_c_o_CXX" >&6 + + +hard_links="nottested" +if test "$lt_cv_prog_compiler_c_o_CXX" = no && test "$need_locks" != no; then + # do not overwrite the value of need_locks provided by the user + echo "$as_me:$LINENO: checking if we can lock with hard links" >&5 +echo $ECHO_N "checking if we can lock with hard links... $ECHO_C" >&6 + hard_links=yes + $rm conftest* + ln conftest.a conftest.b 2>/dev/null && hard_links=no + touch conftest.a + ln conftest.a conftest.b 2>&5 || hard_links=no + ln conftest.a conftest.b 2>/dev/null && hard_links=no + echo "$as_me:$LINENO: result: $hard_links" >&5 +echo "${ECHO_T}$hard_links" >&6 + if test "$hard_links" = no; then + { echo "$as_me:$LINENO: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5 +echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;} + need_locks=warn + fi +else + need_locks=no +fi + +echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) supports shared libraries" >&5 +echo $ECHO_N "checking whether the $compiler linker ($LD) supports shared libraries... $ECHO_C" >&6 + + export_symbols_cmds_CXX='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' + case $host_os in + aix4* | aix5*) + # If we're using GNU nm, then we don't want the "-C" option. + # -C means demangle to AIX nm, but means don't demangle with GNU nm + if $NM -V 2>&1 | grep 'GNU' > /dev/null; then + export_symbols_cmds_CXX='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$2 == "T") || (\$2 == "D") || (\$2 == "B")) && (substr(\$3,1,1) != ".")) { print \$3 } }'\'' | sort -u > $export_symbols' + else + export_symbols_cmds_CXX='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$2 == "T") || (\$2 == "D") || (\$2 == "B")) && (substr(\$3,1,1) != ".")) { print \$3 } }'\'' | sort -u > $export_symbols' + fi + ;; + pw32*) + export_symbols_cmds_CXX="$ltdll_cmds" + ;; + cygwin* | mingw*) + export_symbols_cmds_CXX='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGS] /s/.* \([^ ]*\)/\1 DATA/'\'' | $SED -e '\''/^[AITW] /s/.* //'\'' | sort | uniq > $export_symbols' + ;; + linux*) + link_all_deplibs_CXX=no + ;; + *) + export_symbols_cmds_CXX='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' + ;; + esac + +echo "$as_me:$LINENO: result: $ld_shlibs_CXX" >&5 +echo "${ECHO_T}$ld_shlibs_CXX" >&6 +test "$ld_shlibs_CXX" = no && can_build_shared=no + +variables_saved_for_relink="PATH $shlibpath_var $runpath_var" +if test "$GCC" = yes; then + variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" +fi + +# +# Do we need to explicitly link libc? +# +case "x$archive_cmds_need_lc_CXX" in +x|xyes) + # Assume -lc should be added + archive_cmds_need_lc_CXX=yes + + if test "$enable_shared" = yes && test "$GCC" = yes; then + case $archive_cmds_CXX in + *'~'*) + # FIXME: we may have to deal with multi-command sequences. + ;; + '$CC '*) + # Test whether the compiler implicitly links with -lc since on some + # systems, -lgcc has to come before -lc. If gcc already passes -lc + # to ld, don't add -lc before -lgcc. + echo "$as_me:$LINENO: checking whether -lc should be explicitly linked in" >&5 +echo $ECHO_N "checking whether -lc should be explicitly linked in... $ECHO_C" >&6 + $rm conftest* + printf "$lt_simple_compile_test_code" > conftest.$ac_ext + + if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } 2>conftest.err; then + soname=conftest + lib=conftest + libobjs=conftest.$ac_objext + deplibs= + wl=$lt_prog_compiler_wl_CXX + compiler_flags=-v + linker_flags=-v + verstring= + output_objdir=. + libname=conftest + lt_save_allow_undefined_flag=$allow_undefined_flag_CXX + allow_undefined_flag_CXX= + if { (eval echo "$as_me:$LINENO: \"$archive_cmds_CXX 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1\"") >&5 + (eval $archive_cmds_CXX 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } + then + archive_cmds_need_lc_CXX=no + else + archive_cmds_need_lc_CXX=yes + fi + allow_undefined_flag_CXX=$lt_save_allow_undefined_flag + else + cat conftest.err 1>&5 + fi + $rm conftest* + echo "$as_me:$LINENO: result: $archive_cmds_need_lc_CXX" >&5 +echo "${ECHO_T}$archive_cmds_need_lc_CXX" >&6 + ;; + esac + fi + ;; +esac + +echo "$as_me:$LINENO: checking dynamic linker characteristics" >&5 +echo $ECHO_N "checking dynamic linker characteristics... $ECHO_C" >&6 +library_names_spec= +libname_spec='lib$name' +soname_spec= +shrext_cmds=".so" +postinstall_cmds= +postuninstall_cmds= +finish_cmds= +finish_eval= +shlibpath_var= +shlibpath_overrides_runpath=unknown +version_type=none +dynamic_linker="$host_os ld.so" +sys_lib_dlsearch_path_spec="/lib /usr/lib" +if test "$GCC" = yes; then + sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"` + if echo "$sys_lib_search_path_spec" | grep ';' >/dev/null ; then + # if the path contains ";" then we assume it to be the separator + # otherwise default to the standard path separator (i.e. ":") - it is + # assumed that no part of a normal pathname contains ";" but that should + # okay in the real world where ";" in dirpaths is itself problematic. + sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` + else + sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` + fi +else + sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" +fi +need_lib_prefix=unknown +hardcode_into_libs=no + +# when you set need_version to no, make sure it does not cause -set_version +# flags to be left without arguments +need_version=unknown + +case $host_os in +aix3*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a' + shlibpath_var=LIBPATH + + # AIX 3 has no versioning support, so we append a major version to the name. + soname_spec='${libname}${release}${shared_ext}$major' + ;; + +aix4* | aix5*) + version_type=linux + need_lib_prefix=no + need_version=no + hardcode_into_libs=yes + if test "$host_cpu" = ia64; then + # AIX 5 supports IA64 + library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + else + # With GCC up to 2.95.x, collect2 would create an import file + # for dependence libraries. The import file would start with + # the line `#! .'. This would cause the generated library to + # depend on `.', always an invalid library. This was fixed in + # development snapshots of GCC prior to 3.0. + case $host_os in + aix4 | aix4.[01] | aix4.[01].*) + if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' + echo ' yes ' + echo '#endif'; } | ${CC} -E - | grep yes > /dev/null; then + : + else + can_build_shared=no + fi + ;; + esac + # AIX (on Power*) has no versioning support, so currently we can not hardcode correct + # soname into executable. Probably we can add versioning support to + # collect2, so additional links can be useful in future. + if test "$aix_use_runtimelinking" = yes; then + # If using run time linking (on AIX 4.2 or later) use lib.so + # instead of lib.a to let people know that these are not + # typical AIX shared libraries. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + else + # We preserve .a as extension for shared libraries through AIX4.2 + # and later when we are not doing run time linking. + library_names_spec='${libname}${release}.a $libname.a' + soname_spec='${libname}${release}${shared_ext}$major' + fi + shlibpath_var=LIBPATH + fi + ;; + +amigaos*) + library_names_spec='$libname.ixlibrary $libname.a' + # Create ${libname}_ixlibrary.a entries in /sys/libs. + finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`$echo "X$lib" | $Xsed -e '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $rm /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' + ;; + +beos*) + library_names_spec='${libname}${shared_ext}' + dynamic_linker="$host_os ld.so" + shlibpath_var=LIBRARY_PATH + ;; + +bsdi4*) + version_type=linux + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' + shlibpath_var=LD_LIBRARY_PATH + sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" + sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" + # the default ld.so.conf also contains /usr/contrib/lib and + # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow + # libtool to hard-code these into programs + ;; + +cygwin* | mingw* | pw32*) + version_type=windows + shrext_cmds=".dll" + need_version=no + need_lib_prefix=no + + case $GCC,$host_os in + yes,cygwin* | yes,mingw* | yes,pw32*) + library_names_spec='$libname.dll.a' + # DLL is installed to $(libdir)/../bin by postinstall_cmds + postinstall_cmds='base_file=`basename \${file}`~ + dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i;echo \$dlname'\''`~ + dldir=$destdir/`dirname \$dlpath`~ + test -d \$dldir || mkdir -p \$dldir~ + $install_prog $dir/$dlname \$dldir/$dlname' + postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ + dlpath=$dir/\$dldll~ + $rm \$dlpath' + shlibpath_overrides_runpath=yes + + case $host_os in + cygwin*) + # Cygwin DLLs use 'cyg' prefix rather than 'lib' + soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' + sys_lib_search_path_spec="/usr/lib /lib/w32api /lib /usr/local/lib" + ;; + mingw*) + # MinGW DLLs use traditional 'lib' prefix + soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' + sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"` + if echo "$sys_lib_search_path_spec" | grep ';[c-zC-Z]:/' >/dev/null; then + # It is most probably a Windows format PATH printed by + # mingw gcc, but we are running on Cygwin. Gcc prints its search + # path with ; separators, and with drive letters. We can handle the + # drive letters (cygwin fileutils understands them), so leave them, + # especially as we might pass files found there to a mingw objdump, + # which wouldn't understand a cygwinified path. Ahh. + sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` + else + sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` + fi + ;; + pw32*) + # pw32 DLLs use 'pw' prefix rather than 'lib' + library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/./-/g'`${versuffix}${shared_ext}' + ;; + esac + ;; + + *) + library_names_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext} $libname.lib' + ;; + esac + dynamic_linker='Win32 ld.exe' + # FIXME: first we should search . and the directory the executable is in + shlibpath_var=PATH + ;; + +darwin* | rhapsody*) + dynamic_linker="$host_os dyld" + version_type=darwin + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${versuffix}$shared_ext ${libname}${release}${major}$shared_ext ${libname}$shared_ext' + soname_spec='${libname}${release}${major}$shared_ext' + shlibpath_overrides_runpath=yes + shlibpath_var=DYLD_LIBRARY_PATH + shrext_cmds='$(test .$module = .yes && echo .so || echo .dylib)' + # Apple's gcc prints 'gcc -print-search-dirs' doesn't operate the same. + if test "$GCC" = yes; then + sys_lib_search_path_spec=`$CC -print-search-dirs | tr "\n" "$PATH_SEPARATOR" | sed -e 's/libraries:/@libraries:/' | tr "@" "\n" | grep "^libraries:" | sed -e "s/^libraries://" -e "s,=/,/,g" -e "s,$PATH_SEPARATOR, ,g" -e "s,.*,& /lib /usr/lib /usr/local/lib,g"` + else + sys_lib_search_path_spec='/lib /usr/lib /usr/local/lib' + fi + sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' + ;; + +dgux*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +freebsd1*) + dynamic_linker=no + ;; + +kfreebsd*-gnu) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + dynamic_linker='GNU ld.so' + ;; + +freebsd*) + objformat=`test -x /usr/bin/objformat && /usr/bin/objformat || echo aout` + version_type=freebsd-$objformat + case $version_type in + freebsd-elf*) + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' + need_version=no + need_lib_prefix=no + ;; + freebsd-*) + library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix' + need_version=yes + ;; + esac + shlibpath_var=LD_LIBRARY_PATH + case $host_os in + freebsd2*) + shlibpath_overrides_runpath=yes + ;; + freebsd3.01* | freebsdelf3.01*) + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + *) # from 3.2 on + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + esac + ;; + +gnu*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + hardcode_into_libs=yes + ;; + +hpux9* | hpux10* | hpux11*) + # Give a soname corresponding to the major version so that dld.sl refuses to + # link against other versions. + version_type=sunos + need_lib_prefix=no + need_version=no + case "$host_cpu" in + ia64*) + shrext_cmds='.so' + hardcode_into_libs=yes + dynamic_linker="$host_os dld.so" + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + if test "X$HPUX_IA64_MODE" = X32; then + sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" + else + sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" + fi + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + ;; + hppa*64*) + shrext_cmds='.sl' + hardcode_into_libs=yes + dynamic_linker="$host_os dld.sl" + shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH + shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + ;; + *) + shrext_cmds='.sl' + dynamic_linker="$host_os dld.sl" + shlibpath_var=SHLIB_PATH + shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + ;; + esac + # HP-UX runs *really* slowly unless shared libraries are mode 555. + postinstall_cmds='chmod 555 $lib' + ;; + +irix5* | irix6* | nonstopux*) + case $host_os in + nonstopux*) version_type=nonstopux ;; + *) + if test "$lt_cv_prog_gnu_ld" = yes; then + version_type=linux + else + version_type=irix + fi ;; + esac + need_lib_prefix=no + need_version=no + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}' + case $host_os in + irix5* | nonstopux*) + libsuff= shlibsuff= + ;; + *) + case $LD in # libtool.m4 will add one of these switches to LD + *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") + libsuff= shlibsuff= libmagic=32-bit;; + *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") + libsuff=32 shlibsuff=N32 libmagic=N32;; + *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") + libsuff=64 shlibsuff=64 libmagic=64-bit;; + *) libsuff= shlibsuff= libmagic=never-match;; + esac + ;; + esac + shlibpath_var=LD_LIBRARY${shlibsuff}_PATH + shlibpath_overrides_runpath=no + sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" + sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" + hardcode_into_libs=yes + ;; + +# No shared lib support for Linux oldld, aout, or coff. +linux*oldld* | linux*aout* | linux*coff*) + dynamic_linker=no + ;; + +# This must be Linux ELF. +linux*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + # This implies no fast_install, which is unacceptable. + # Some rework will be needed to allow for fast_install + # before this can be enabled. + hardcode_into_libs=yes + + # Append ld.so.conf contents to the search path + if test -f /etc/ld.so.conf; then + lt_ld_extra=`$SED -e 's/:,\t/ /g;s/=^=*$//;s/=^= * / /g' /etc/ld.so.conf | tr '\n' ' '` + sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" + fi + + # We used to test for /lib/ld.so.1 and disable shared libraries on + # powerpc, because MkLinux only supported shared libraries with the + # GNU dynamic linker. Since this was broken with cross compilers, + # most powerpc-linux boxes support dynamic linking these days and + # people can always --disable-shared, the test was removed, and we + # assume the GNU/Linux dynamic linker is in use. + dynamic_linker='GNU/Linux ld.so' + ;; + +netbsdelf*-gnu) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + dynamic_linker='NetBSD ld.elf_so' + ;; + +knetbsd*-gnu) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + dynamic_linker='GNU ld.so' + ;; + +netbsd*) + version_type=sunos + need_lib_prefix=no + need_version=no + if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' + dynamic_linker='NetBSD (a.out) ld.so' + else + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + dynamic_linker='NetBSD ld.elf_so' + fi + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + +newsos6) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + ;; + +nto-qnx*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + ;; + +openbsd*) + version_type=sunos + need_lib_prefix=no + need_version=yes + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' + shlibpath_var=LD_LIBRARY_PATH + if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + case $host_os in + openbsd2.[89] | openbsd2.[89].*) + shlibpath_overrides_runpath=no + ;; + *) + shlibpath_overrides_runpath=yes + ;; + esac + else + shlibpath_overrides_runpath=yes + fi + ;; + +os2*) + libname_spec='$name' + shrext_cmds=".dll" + need_lib_prefix=no + library_names_spec='$libname${shared_ext} $libname.a' + dynamic_linker='OS/2 ld.exe' + shlibpath_var=LIBPATH + ;; + +osf3* | osf4* | osf5*) + version_type=osf + need_lib_prefix=no + need_version=no + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" + sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec" + ;; + +sco3.2v5*) + version_type=osf + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + ;; + +solaris*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + # ldd complains unless libraries are executable + postinstall_cmds='chmod +x $lib' + ;; + +sunos4*) + version_type=sunos + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + if test "$with_gnu_ld" = yes; then + need_lib_prefix=no + fi + need_version=yes + ;; + +sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + case $host_vendor in + sni) + shlibpath_overrides_runpath=no + need_lib_prefix=no + export_dynamic_flag_spec='${wl}-Blargedynsym' + runpath_var=LD_RUN_PATH + ;; + siemens) + need_lib_prefix=no + ;; + motorola) + need_lib_prefix=no + need_version=no + shlibpath_overrides_runpath=no + sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' + ;; + esac + ;; + +sysv4*MP*) + if test -d /usr/nec ;then + version_type=linux + library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}' + soname_spec='$libname${shared_ext}.$major' + shlibpath_var=LD_LIBRARY_PATH + fi + ;; + +uts4*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +*) + dynamic_linker=no + ;; +esac +echo "$as_me:$LINENO: result: $dynamic_linker" >&5 +echo "${ECHO_T}$dynamic_linker" >&6 +test "$dynamic_linker" = no && can_build_shared=no + +echo "$as_me:$LINENO: checking how to hardcode library paths into programs" >&5 +echo $ECHO_N "checking how to hardcode library paths into programs... $ECHO_C" >&6 +hardcode_action_CXX= +if test -n "$hardcode_libdir_flag_spec_CXX" || \ + test -n "$runpath_var CXX" || \ + test "X$hardcode_automatic_CXX"="Xyes" ; then + + # We can hardcode non-existant directories. + if test "$hardcode_direct_CXX" != no && + # If the only mechanism to avoid hardcoding is shlibpath_var, we + # have to relink, otherwise we might link with an installed library + # when we should be linking with a yet-to-be-installed one + ## test "$_LT_AC_TAGVAR(hardcode_shlibpath_var, CXX)" != no && + test "$hardcode_minus_L_CXX" != no; then + # Linking always hardcodes the temporary library directory. + hardcode_action_CXX=relink + else + # We can link without hardcoding, and we can hardcode nonexisting dirs. + hardcode_action_CXX=immediate + fi +else + # We cannot hardcode anything, or else we can only hardcode existing + # directories. + hardcode_action_CXX=unsupported +fi +echo "$as_me:$LINENO: result: $hardcode_action_CXX" >&5 +echo "${ECHO_T}$hardcode_action_CXX" >&6 + +if test "$hardcode_action_CXX" = relink; then + # Fast installation is not supported + enable_fast_install=no +elif test "$shlibpath_overrides_runpath" = yes || + test "$enable_shared" = no; then + # Fast installation is not necessary + enable_fast_install=needless +fi + +striplib= +old_striplib= +echo "$as_me:$LINENO: checking whether stripping libraries is possible" >&5 +echo $ECHO_N "checking whether stripping libraries is possible... $ECHO_C" >&6 +if test -n "$STRIP" && $STRIP -V 2>&1 | grep "GNU strip" >/dev/null; then + test -z "$old_striplib" && old_striplib="$STRIP --strip-debug" + test -z "$striplib" && striplib="$STRIP --strip-unneeded" + echo "$as_me:$LINENO: result: yes" >&5 +echo "${ECHO_T}yes" >&6 +else +# FIXME - insert some real tests, host_os isn't really good enough + case $host_os in + darwin*) + if test -n "$STRIP" ; then + striplib="$STRIP -x" + echo "$as_me:$LINENO: result: yes" >&5 +echo "${ECHO_T}yes" >&6 + else + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 +fi + ;; + *) + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 + ;; + esac +fi + +if test "x$enable_dlopen" != xyes; then + enable_dlopen=unknown + enable_dlopen_self=unknown + enable_dlopen_self_static=unknown +else + lt_cv_dlopen=no + lt_cv_dlopen_libs= + + case $host_os in + beos*) + lt_cv_dlopen="load_add_on" + lt_cv_dlopen_libs= + lt_cv_dlopen_self=yes + ;; + + mingw* | pw32*) + lt_cv_dlopen="LoadLibrary" + lt_cv_dlopen_libs= + ;; + + cygwin*) + lt_cv_dlopen="dlopen" + lt_cv_dlopen_libs= + ;; + + darwin*) + # if libdl is installed we need to link against it + echo "$as_me:$LINENO: checking for dlopen in -ldl" >&5 +echo $ECHO_N "checking for dlopen in -ldl... $ECHO_C" >&6 +if test "${ac_cv_lib_dl_dlopen+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldl $LIBS" +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any gcc2 internal prototype to avoid an error. */ +#ifdef __cplusplus +extern "C" +#endif +/* We use char because int might match the return type of a gcc2 + builtin and then its argument prototype would still apply. */ +char dlopen (); +int +main () +{ +dlopen (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_cxx_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_lib_dl_dlopen=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_cv_lib_dl_dlopen=no +fi +rm -f conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +echo "$as_me:$LINENO: result: $ac_cv_lib_dl_dlopen" >&5 +echo "${ECHO_T}$ac_cv_lib_dl_dlopen" >&6 +if test $ac_cv_lib_dl_dlopen = yes; then + lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl" +else + + lt_cv_dlopen="dyld" + lt_cv_dlopen_libs= + lt_cv_dlopen_self=yes + +fi + + ;; + + *) + echo "$as_me:$LINENO: checking for shl_load" >&5 +echo $ECHO_N "checking for shl_load... $ECHO_C" >&6 +if test "${ac_cv_func_shl_load+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +/* Define shl_load to an innocuous variant, in case declares shl_load. + For example, HP-UX 11i declares gettimeofday. */ +#define shl_load innocuous_shl_load + +/* System header to define __stub macros and hopefully few prototypes, + which can conflict with char shl_load (); below. + Prefer to if __STDC__ is defined, since + exists even on freestanding compilers. */ + +#ifdef __STDC__ +# include +#else +# include +#endif + +#undef shl_load + +/* Override any gcc2 internal prototype to avoid an error. */ +#ifdef __cplusplus +extern "C" +{ +#endif +/* We use char because int might match the return type of a gcc2 + builtin and then its argument prototype would still apply. */ +char shl_load (); +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined (__stub_shl_load) || defined (__stub___shl_load) +choke me +#else +char (*f) () = shl_load; +#endif +#ifdef __cplusplus +} +#endif + +int +main () +{ +return f != shl_load; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_cxx_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_func_shl_load=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_cv_func_shl_load=no +fi +rm -f conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +fi +echo "$as_me:$LINENO: result: $ac_cv_func_shl_load" >&5 +echo "${ECHO_T}$ac_cv_func_shl_load" >&6 +if test $ac_cv_func_shl_load = yes; then + lt_cv_dlopen="shl_load" +else + echo "$as_me:$LINENO: checking for shl_load in -ldld" >&5 +echo $ECHO_N "checking for shl_load in -ldld... $ECHO_C" >&6 +if test "${ac_cv_lib_dld_shl_load+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldld $LIBS" +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any gcc2 internal prototype to avoid an error. */ +#ifdef __cplusplus +extern "C" +#endif +/* We use char because int might match the return type of a gcc2 + builtin and then its argument prototype would still apply. */ +char shl_load (); +int +main () +{ +shl_load (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_cxx_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_lib_dld_shl_load=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_cv_lib_dld_shl_load=no +fi +rm -f conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +echo "$as_me:$LINENO: result: $ac_cv_lib_dld_shl_load" >&5 +echo "${ECHO_T}$ac_cv_lib_dld_shl_load" >&6 +if test $ac_cv_lib_dld_shl_load = yes; then + lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-dld" +else + echo "$as_me:$LINENO: checking for dlopen" >&5 +echo $ECHO_N "checking for dlopen... $ECHO_C" >&6 +if test "${ac_cv_func_dlopen+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +/* Define dlopen to an innocuous variant, in case declares dlopen. + For example, HP-UX 11i declares gettimeofday. */ +#define dlopen innocuous_dlopen + +/* System header to define __stub macros and hopefully few prototypes, + which can conflict with char dlopen (); below. + Prefer to if __STDC__ is defined, since + exists even on freestanding compilers. */ + +#ifdef __STDC__ +# include +#else +# include +#endif + +#undef dlopen + +/* Override any gcc2 internal prototype to avoid an error. */ +#ifdef __cplusplus +extern "C" +{ +#endif +/* We use char because int might match the return type of a gcc2 + builtin and then its argument prototype would still apply. */ +char dlopen (); +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined (__stub_dlopen) || defined (__stub___dlopen) +choke me +#else +char (*f) () = dlopen; +#endif +#ifdef __cplusplus +} +#endif + +int +main () +{ +return f != dlopen; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_cxx_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_func_dlopen=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_cv_func_dlopen=no +fi +rm -f conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +fi +echo "$as_me:$LINENO: result: $ac_cv_func_dlopen" >&5 +echo "${ECHO_T}$ac_cv_func_dlopen" >&6 +if test $ac_cv_func_dlopen = yes; then + lt_cv_dlopen="dlopen" +else + echo "$as_me:$LINENO: checking for dlopen in -ldl" >&5 +echo $ECHO_N "checking for dlopen in -ldl... $ECHO_C" >&6 +if test "${ac_cv_lib_dl_dlopen+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldl $LIBS" +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any gcc2 internal prototype to avoid an error. */ +#ifdef __cplusplus +extern "C" +#endif +/* We use char because int might match the return type of a gcc2 + builtin and then its argument prototype would still apply. */ +char dlopen (); +int +main () +{ +dlopen (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_cxx_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_lib_dl_dlopen=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_cv_lib_dl_dlopen=no +fi +rm -f conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +echo "$as_me:$LINENO: result: $ac_cv_lib_dl_dlopen" >&5 +echo "${ECHO_T}$ac_cv_lib_dl_dlopen" >&6 +if test $ac_cv_lib_dl_dlopen = yes; then + lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl" +else + echo "$as_me:$LINENO: checking for dlopen in -lsvld" >&5 +echo $ECHO_N "checking for dlopen in -lsvld... $ECHO_C" >&6 +if test "${ac_cv_lib_svld_dlopen+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lsvld $LIBS" +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any gcc2 internal prototype to avoid an error. */ +#ifdef __cplusplus +extern "C" +#endif +/* We use char because int might match the return type of a gcc2 + builtin and then its argument prototype would still apply. */ +char dlopen (); +int +main () +{ +dlopen (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_cxx_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_lib_svld_dlopen=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_cv_lib_svld_dlopen=no +fi +rm -f conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +echo "$as_me:$LINENO: result: $ac_cv_lib_svld_dlopen" >&5 +echo "${ECHO_T}$ac_cv_lib_svld_dlopen" >&6 +if test $ac_cv_lib_svld_dlopen = yes; then + lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld" +else + echo "$as_me:$LINENO: checking for dld_link in -ldld" >&5 +echo $ECHO_N "checking for dld_link in -ldld... $ECHO_C" >&6 +if test "${ac_cv_lib_dld_dld_link+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldld $LIBS" +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any gcc2 internal prototype to avoid an error. */ +#ifdef __cplusplus +extern "C" +#endif +/* We use char because int might match the return type of a gcc2 + builtin and then its argument prototype would still apply. */ +char dld_link (); +int +main () +{ +dld_link (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_cxx_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_lib_dld_dld_link=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_cv_lib_dld_dld_link=no +fi +rm -f conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +echo "$as_me:$LINENO: result: $ac_cv_lib_dld_dld_link" >&5 +echo "${ECHO_T}$ac_cv_lib_dld_dld_link" >&6 +if test $ac_cv_lib_dld_dld_link = yes; then + lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-dld" +fi + + +fi + + +fi + + +fi + + +fi + + +fi + + ;; + esac + + if test "x$lt_cv_dlopen" != xno; then + enable_dlopen=yes + else + enable_dlopen=no + fi + + case $lt_cv_dlopen in + dlopen) + save_CPPFLAGS="$CPPFLAGS" + test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H" + + save_LDFLAGS="$LDFLAGS" + eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\" + + save_LIBS="$LIBS" + LIBS="$lt_cv_dlopen_libs $LIBS" + + echo "$as_me:$LINENO: checking whether a program can dlopen itself" >&5 +echo $ECHO_N "checking whether a program can dlopen itself... $ECHO_C" >&6 +if test "${lt_cv_dlopen_self+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test "$cross_compiling" = yes; then : + lt_cv_dlopen_self=cross +else + lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 + lt_status=$lt_dlunknown + cat > conftest.$ac_ext < +#endif + +#include + +#ifdef RTLD_GLOBAL +# define LT_DLGLOBAL RTLD_GLOBAL +#else +# ifdef DL_GLOBAL +# define LT_DLGLOBAL DL_GLOBAL +# else +# define LT_DLGLOBAL 0 +# endif +#endif + +/* We may have to define LT_DLLAZY_OR_NOW in the command line if we + find out it does not work in some platform. */ +#ifndef LT_DLLAZY_OR_NOW +# ifdef RTLD_LAZY +# define LT_DLLAZY_OR_NOW RTLD_LAZY +# else +# ifdef DL_LAZY +# define LT_DLLAZY_OR_NOW DL_LAZY +# else +# ifdef RTLD_NOW +# define LT_DLLAZY_OR_NOW RTLD_NOW +# else +# ifdef DL_NOW +# define LT_DLLAZY_OR_NOW DL_NOW +# else +# define LT_DLLAZY_OR_NOW 0 +# endif +# endif +# endif +# endif +#endif + +#ifdef __cplusplus +extern "C" void exit (int); +#endif + +void fnord() { int i=42;} +int main () +{ + void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); + int status = $lt_dlunknown; + + if (self) + { + if (dlsym (self,"fnord")) status = $lt_dlno_uscore; + else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; + /* dlclose (self); */ + } + + exit (status); +} +EOF + if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && test -s conftest${ac_exeext} 2>/dev/null; then + (./conftest; exit; ) 2>/dev/null + lt_status=$? + case x$lt_status in + x$lt_dlno_uscore) lt_cv_dlopen_self=yes ;; + x$lt_dlneed_uscore) lt_cv_dlopen_self=yes ;; + x$lt_unknown|x*) lt_cv_dlopen_self=no ;; + esac + else : + # compilation failed + lt_cv_dlopen_self=no + fi +fi +rm -fr conftest* + + +fi +echo "$as_me:$LINENO: result: $lt_cv_dlopen_self" >&5 +echo "${ECHO_T}$lt_cv_dlopen_self" >&6 + + if test "x$lt_cv_dlopen_self" = xyes; then + LDFLAGS="$LDFLAGS $link_static_flag" + echo "$as_me:$LINENO: checking whether a statically linked program can dlopen itself" >&5 +echo $ECHO_N "checking whether a statically linked program can dlopen itself... $ECHO_C" >&6 +if test "${lt_cv_dlopen_self_static+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test "$cross_compiling" = yes; then : + lt_cv_dlopen_self_static=cross +else + lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 + lt_status=$lt_dlunknown + cat > conftest.$ac_ext < +#endif + +#include + +#ifdef RTLD_GLOBAL +# define LT_DLGLOBAL RTLD_GLOBAL +#else +# ifdef DL_GLOBAL +# define LT_DLGLOBAL DL_GLOBAL +# else +# define LT_DLGLOBAL 0 +# endif +#endif + +/* We may have to define LT_DLLAZY_OR_NOW in the command line if we + find out it does not work in some platform. */ +#ifndef LT_DLLAZY_OR_NOW +# ifdef RTLD_LAZY +# define LT_DLLAZY_OR_NOW RTLD_LAZY +# else +# ifdef DL_LAZY +# define LT_DLLAZY_OR_NOW DL_LAZY +# else +# ifdef RTLD_NOW +# define LT_DLLAZY_OR_NOW RTLD_NOW +# else +# ifdef DL_NOW +# define LT_DLLAZY_OR_NOW DL_NOW +# else +# define LT_DLLAZY_OR_NOW 0 +# endif +# endif +# endif +# endif +#endif + +#ifdef __cplusplus +extern "C" void exit (int); +#endif + +void fnord() { int i=42;} +int main () +{ + void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); + int status = $lt_dlunknown; + + if (self) + { + if (dlsym (self,"fnord")) status = $lt_dlno_uscore; + else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; + /* dlclose (self); */ + } + + exit (status); +} +EOF + if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && test -s conftest${ac_exeext} 2>/dev/null; then + (./conftest; exit; ) 2>/dev/null + lt_status=$? + case x$lt_status in + x$lt_dlno_uscore) lt_cv_dlopen_self_static=yes ;; + x$lt_dlneed_uscore) lt_cv_dlopen_self_static=yes ;; + x$lt_unknown|x*) lt_cv_dlopen_self_static=no ;; + esac + else : + # compilation failed + lt_cv_dlopen_self_static=no + fi +fi +rm -fr conftest* + + +fi +echo "$as_me:$LINENO: result: $lt_cv_dlopen_self_static" >&5 +echo "${ECHO_T}$lt_cv_dlopen_self_static" >&6 + fi + + CPPFLAGS="$save_CPPFLAGS" + LDFLAGS="$save_LDFLAGS" + LIBS="$save_LIBS" + ;; + esac + + case $lt_cv_dlopen_self in + yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;; + *) enable_dlopen_self=unknown ;; + esac + + case $lt_cv_dlopen_self_static in + yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;; + *) enable_dlopen_self_static=unknown ;; + esac +fi + + +# The else clause should only fire when bootstrapping the +# libtool distribution, otherwise you forgot to ship ltmain.sh +# with your package, and you will get complaints that there are +# no rules to generate ltmain.sh. +if test -f "$ltmain"; then + # See if we are running on zsh, and set the options which allow our commands through + # without removal of \ escapes. + if test -n "${ZSH_VERSION+set}" ; then + setopt NO_GLOB_SUBST + fi + # Now quote all the things that may contain metacharacters while being + # careful not to overquote the AC_SUBSTed values. We take copies of the + # variables and quote the copies for generation of the libtool script. + for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC NM \ + SED SHELL STRIP \ + libname_spec library_names_spec soname_spec extract_expsyms_cmds \ + old_striplib striplib file_magic_cmd finish_cmds finish_eval \ + deplibs_check_method reload_flag reload_cmds need_locks \ + lt_cv_sys_global_symbol_pipe lt_cv_sys_global_symbol_to_cdecl \ + lt_cv_sys_global_symbol_to_c_name_address \ + sys_lib_search_path_spec sys_lib_dlsearch_path_spec \ + old_postinstall_cmds old_postuninstall_cmds \ + compiler_CXX \ + CC_CXX \ + LD_CXX \ + lt_prog_compiler_wl_CXX \ + lt_prog_compiler_pic_CXX \ + lt_prog_compiler_static_CXX \ + lt_prog_compiler_no_builtin_flag_CXX \ + export_dynamic_flag_spec_CXX \ + thread_safe_flag_spec_CXX \ + whole_archive_flag_spec_CXX \ + enable_shared_with_static_runtimes_CXX \ + old_archive_cmds_CXX \ + old_archive_from_new_cmds_CXX \ + predep_objects_CXX \ + postdep_objects_CXX \ + predeps_CXX \ + postdeps_CXX \ + compiler_lib_search_path_CXX \ + archive_cmds_CXX \ + archive_expsym_cmds_CXX \ + postinstall_cmds_CXX \ + postuninstall_cmds_CXX \ + old_archive_from_expsyms_cmds_CXX \ + allow_undefined_flag_CXX \ + no_undefined_flag_CXX \ + export_symbols_cmds_CXX \ + hardcode_libdir_flag_spec_CXX \ + hardcode_libdir_flag_spec_ld_CXX \ + hardcode_libdir_separator_CXX \ + hardcode_automatic_CXX \ + module_cmds_CXX \ + module_expsym_cmds_CXX \ + lt_cv_prog_compiler_c_o_CXX \ + exclude_expsyms_CXX \ + include_expsyms_CXX; do + + case $var in + old_archive_cmds_CXX | \ + old_archive_from_new_cmds_CXX | \ + archive_cmds_CXX | \ + archive_expsym_cmds_CXX | \ + module_cmds_CXX | \ + module_expsym_cmds_CXX | \ + old_archive_from_expsyms_cmds_CXX | \ + export_symbols_cmds_CXX | \ + extract_expsyms_cmds | reload_cmds | finish_cmds | \ + postinstall_cmds | postuninstall_cmds | \ + old_postinstall_cmds | old_postuninstall_cmds | \ + sys_lib_search_path_spec | sys_lib_dlsearch_path_spec) + # Double-quote double-evaled strings. + eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$double_quote_subst\" -e \"\$sed_quote_subst\" -e \"\$delay_variable_subst\"\`\\\"" + ;; + *) + eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$sed_quote_subst\"\`\\\"" + ;; + esac + done + + case $lt_echo in + *'\$0 --fallback-echo"') + lt_echo=`$echo "X$lt_echo" | $Xsed -e 's/\\\\\\\$0 --fallback-echo"$/$0 --fallback-echo"/'` + ;; + esac + +cfgfile="$ofile" + + cat <<__EOF__ >> "$cfgfile" +# ### BEGIN LIBTOOL TAG CONFIG: $tagname + +# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`: + +# Shell to use when invoking shell scripts. +SHELL=$lt_SHELL + +# Whether or not to build shared libraries. +build_libtool_libs=$enable_shared + +# Whether or not to build static libraries. +build_old_libs=$enable_static + +# Whether or not to add -lc for building shared libraries. +build_libtool_need_lc=$archive_cmds_need_lc_CXX + +# Whether or not to disallow shared libs when runtime libs are static +allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes_CXX + +# Whether or not to optimize for fast installation. +fast_install=$enable_fast_install + +# The host system. +host_alias=$host_alias +host=$host + +# An echo program that does not interpret backslashes. +echo=$lt_echo + +# The archiver. +AR=$lt_AR +AR_FLAGS=$lt_AR_FLAGS + +# A C compiler. +LTCC=$lt_LTCC + +# A language-specific compiler. +CC=$lt_compiler_CXX + +# Is the compiler the GNU C compiler? +with_gcc=$GCC_CXX + +# An ERE matcher. +EGREP=$lt_EGREP + +# The linker used to build libraries. +LD=$lt_LD_CXX + +# Whether we need hard or soft links. +LN_S=$lt_LN_S + +# A BSD-compatible nm program. +NM=$lt_NM + +# A symbol stripping program +STRIP=$lt_STRIP + +# Used to examine libraries when file_magic_cmd begins "file" +MAGIC_CMD=$MAGIC_CMD + +# Used on cygwin: DLL creation program. +DLLTOOL="$DLLTOOL" + +# Used on cygwin: object dumper. +OBJDUMP="$OBJDUMP" + +# Used on cygwin: assembler. +AS="$AS" + +# The name of the directory that contains temporary libtool files. +objdir=$objdir + +# How to create reloadable object files. +reload_flag=$lt_reload_flag +reload_cmds=$lt_reload_cmds + +# How to pass a linker flag through the compiler. +wl=$lt_lt_prog_compiler_wl_CXX + +# Object file suffix (normally "o"). +objext="$ac_objext" + +# Old archive suffix (normally "a"). +libext="$libext" + +# Shared library suffix (normally ".so"). +shrext_cmds='$shrext_cmds' + +# Executable file suffix (normally ""). +exeext="$exeext" + +# Additional compiler flags for building library objects. +pic_flag=$lt_lt_prog_compiler_pic_CXX +pic_mode=$pic_mode + +# What is the maximum length of a command? +max_cmd_len=$lt_cv_sys_max_cmd_len + +# Does compiler simultaneously support -c and -o options? +compiler_c_o=$lt_lt_cv_prog_compiler_c_o_CXX + +# Must we lock files when doing compilation ? +need_locks=$lt_need_locks + +# Do we need the lib prefix for modules? +need_lib_prefix=$need_lib_prefix + +# Do we need a version for libraries? +need_version=$need_version + +# Whether dlopen is supported. +dlopen_support=$enable_dlopen + +# Whether dlopen of programs is supported. +dlopen_self=$enable_dlopen_self + +# Whether dlopen of statically linked programs is supported. +dlopen_self_static=$enable_dlopen_self_static + +# Compiler flag to prevent dynamic linking. +link_static_flag=$lt_lt_prog_compiler_static_CXX + +# Compiler flag to turn off builtin functions. +no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag_CXX + +# Compiler flag to allow reflexive dlopens. +export_dynamic_flag_spec=$lt_export_dynamic_flag_spec_CXX + +# Compiler flag to generate shared objects directly from archives. +whole_archive_flag_spec=$lt_whole_archive_flag_spec_CXX + +# Compiler flag to generate thread-safe objects. +thread_safe_flag_spec=$lt_thread_safe_flag_spec_CXX + +# Library versioning type. +version_type=$version_type + +# Format of library name prefix. +libname_spec=$lt_libname_spec + +# List of archive names. First name is the real one, the rest are links. +# The last name is the one that the linker finds with -lNAME. +library_names_spec=$lt_library_names_spec + +# The coded name of the library, if different from the real name. +soname_spec=$lt_soname_spec + +# Commands used to build and install an old-style archive. +RANLIB=$lt_RANLIB +old_archive_cmds=$lt_old_archive_cmds_CXX +old_postinstall_cmds=$lt_old_postinstall_cmds +old_postuninstall_cmds=$lt_old_postuninstall_cmds + +# Create an old-style archive from a shared archive. +old_archive_from_new_cmds=$lt_old_archive_from_new_cmds_CXX + +# Create a temporary old-style archive to link instead of a shared archive. +old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds_CXX + +# Commands used to build and install a shared archive. +archive_cmds=$lt_archive_cmds_CXX +archive_expsym_cmds=$lt_archive_expsym_cmds_CXX +postinstall_cmds=$lt_postinstall_cmds +postuninstall_cmds=$lt_postuninstall_cmds + +# Commands used to build a loadable module (assumed same as above if empty) +module_cmds=$lt_module_cmds_CXX +module_expsym_cmds=$lt_module_expsym_cmds_CXX + +# Commands to strip libraries. +old_striplib=$lt_old_striplib +striplib=$lt_striplib + +# Dependencies to place before the objects being linked to create a +# shared library. +predep_objects=$lt_predep_objects_CXX + +# Dependencies to place after the objects being linked to create a +# shared library. +postdep_objects=$lt_postdep_objects_CXX + +# Dependencies to place before the objects being linked to create a +# shared library. +predeps=$lt_predeps_CXX + +# Dependencies to place after the objects being linked to create a +# shared library. +postdeps=$lt_postdeps_CXX + +# The library search path used internally by the compiler when linking +# a shared library. +compiler_lib_search_path=$lt_compiler_lib_search_path_CXX + +# Method to check whether dependent libraries are shared objects. +deplibs_check_method=$lt_deplibs_check_method + +# Command to use when deplibs_check_method == file_magic. +file_magic_cmd=$lt_file_magic_cmd + +# Flag that allows shared libraries with undefined symbols to be built. +allow_undefined_flag=$lt_allow_undefined_flag_CXX + +# Flag that forces no undefined symbols. +no_undefined_flag=$lt_no_undefined_flag_CXX + +# Commands used to finish a libtool library installation in a directory. +finish_cmds=$lt_finish_cmds + +# Same as above, but a single script fragment to be evaled but not shown. +finish_eval=$lt_finish_eval + +# Take the output of nm and produce a listing of raw symbols and C names. +global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe + +# Transform the output of nm in a proper C declaration +global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl + +# Transform the output of nm in a C name address pair +global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address + +# This is the shared library runtime path variable. +runpath_var=$runpath_var + +# This is the shared library path variable. +shlibpath_var=$shlibpath_var + +# Is shlibpath searched before the hard-coded library search path? +shlibpath_overrides_runpath=$shlibpath_overrides_runpath + +# How to hardcode a shared library path into an executable. +hardcode_action=$hardcode_action_CXX + +# Whether we should hardcode library paths into libraries. +hardcode_into_libs=$hardcode_into_libs + +# Flag to hardcode \$libdir into a binary during linking. +# This must work even if \$libdir does not exist. +hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec_CXX + +# If ld is used when linking, flag to hardcode \$libdir into +# a binary during linking. This must work even if \$libdir does +# not exist. +hardcode_libdir_flag_spec_ld=$lt_hardcode_libdir_flag_spec_ld_CXX + +# Whether we need a single -rpath flag with a separated argument. +hardcode_libdir_separator=$lt_hardcode_libdir_separator_CXX + +# Set to yes if using DIR/libNAME${shared_ext} during linking hardcodes DIR into the +# resulting binary. +hardcode_direct=$hardcode_direct_CXX + +# Set to yes if using the -LDIR flag during linking hardcodes DIR into the +# resulting binary. +hardcode_minus_L=$hardcode_minus_L_CXX + +# Set to yes if using SHLIBPATH_VAR=DIR during linking hardcodes DIR into +# the resulting binary. +hardcode_shlibpath_var=$hardcode_shlibpath_var_CXX + +# Set to yes if building a shared library automatically hardcodes DIR into the library +# and all subsequent libraries and executables linked against it. +hardcode_automatic=$hardcode_automatic_CXX + +# Variables whose values should be saved in libtool wrapper scripts and +# restored at relink time. +variables_saved_for_relink="$variables_saved_for_relink" + +# Whether libtool must link a program against all its dependency libraries. +link_all_deplibs=$link_all_deplibs_CXX + +# Compile-time system search path for libraries +sys_lib_search_path_spec=$lt_sys_lib_search_path_spec + +# Run-time system search path for libraries +sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec + +# Fix the shell variable \$srcfile for the compiler. +fix_srcfile_path="$fix_srcfile_path_CXX" + +# Set to yes if exported symbols are required. +always_export_symbols=$always_export_symbols_CXX + +# The commands to list exported symbols. +export_symbols_cmds=$lt_export_symbols_cmds_CXX + +# The commands to extract the exported symbol list from a shared archive. +extract_expsyms_cmds=$lt_extract_expsyms_cmds + +# Symbols that should not be listed in the preloaded symbols. +exclude_expsyms=$lt_exclude_expsyms_CXX + +# Symbols that must always be exported. +include_expsyms=$lt_include_expsyms_CXX + +# ### END LIBTOOL TAG CONFIG: $tagname + +__EOF__ + + +else + # If there is no Makefile yet, we rely on a make rule to execute + # `config.status --recheck' to rerun these tests and create the + # libtool script then. + ltmain_in=`echo $ltmain | sed -e 's/\.sh$/.in/'` + if test -f "$ltmain_in"; then + test -f Makefile && make "$ltmain" + fi +fi + + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + +CC=$lt_save_CC +LDCXX=$LD +LD=$lt_save_LD +GCC=$lt_save_GCC +with_gnu_ldcxx=$with_gnu_ld +with_gnu_ld=$lt_save_with_gnu_ld +lt_cv_path_LDCXX=$lt_cv_path_LD +lt_cv_path_LD=$lt_save_path_LD +lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld +lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld + + else + tagname="" + fi + ;; + + F77) + if test -n "$F77" && test "X$F77" != "Xno"; then + +ac_ext=f +ac_compile='$F77 -c $FFLAGS conftest.$ac_ext >&5' +ac_link='$F77 -o conftest$ac_exeext $FFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_f77_compiler_gnu + + +archive_cmds_need_lc_F77=no +allow_undefined_flag_F77= +always_export_symbols_F77=no +archive_expsym_cmds_F77= +export_dynamic_flag_spec_F77= +hardcode_direct_F77=no +hardcode_libdir_flag_spec_F77= +hardcode_libdir_flag_spec_ld_F77= +hardcode_libdir_separator_F77= +hardcode_minus_L_F77=no +hardcode_automatic_F77=no +module_cmds_F77= +module_expsym_cmds_F77= +link_all_deplibs_F77=unknown +old_archive_cmds_F77=$old_archive_cmds +no_undefined_flag_F77= +whole_archive_flag_spec_F77= +enable_shared_with_static_runtimes_F77=no + +# Source file extension for f77 test sources. +ac_ext=f + +# Object file extension for compiled f77 test sources. +objext=o +objext_F77=$objext + +# Code to be used in simple compile tests +lt_simple_compile_test_code=" subroutine t\n return\n end\n" + +# Code to be used in simple link tests +lt_simple_link_test_code=" program t\n end\n" + +# ltmain only uses $CC for tagged configurations so make sure $CC is set. + +# If no C compiler was specified, use CC. +LTCC=${LTCC-"$CC"} + +# Allow CC to be a program name with arguments. +compiler=$CC + + +# Allow CC to be a program name with arguments. +lt_save_CC="$CC" +CC=${F77-"f77"} +compiler=$CC +compiler_F77=$CC +cc_basename=`$echo X"$compiler" | $Xsed -e 's%^.*/%%'` + +echo "$as_me:$LINENO: checking if libtool supports shared libraries" >&5 +echo $ECHO_N "checking if libtool supports shared libraries... $ECHO_C" >&6 +echo "$as_me:$LINENO: result: $can_build_shared" >&5 +echo "${ECHO_T}$can_build_shared" >&6 + +echo "$as_me:$LINENO: checking whether to build shared libraries" >&5 +echo $ECHO_N "checking whether to build shared libraries... $ECHO_C" >&6 +test "$can_build_shared" = "no" && enable_shared=no + +# On AIX, shared libraries and static libraries use the same namespace, and +# are all built from PIC. +case "$host_os" in +aix3*) + test "$enable_shared" = yes && enable_static=no + if test -n "$RANLIB"; then + archive_cmds="$archive_cmds~\$RANLIB \$lib" + postinstall_cmds='$RANLIB $lib' + fi + ;; +aix4* | aix5*) + test "$enable_shared" = yes && enable_static=no + ;; +esac +echo "$as_me:$LINENO: result: $enable_shared" >&5 +echo "${ECHO_T}$enable_shared" >&6 + +echo "$as_me:$LINENO: checking whether to build static libraries" >&5 +echo $ECHO_N "checking whether to build static libraries... $ECHO_C" >&6 +# Make sure either enable_shared or enable_static is yes. +test "$enable_shared" = yes || enable_static=yes +echo "$as_me:$LINENO: result: $enable_static" >&5 +echo "${ECHO_T}$enable_static" >&6 + +test "$ld_shlibs_F77" = no && can_build_shared=no + +GCC_F77="$G77" +LD_F77="$LD" + +lt_prog_compiler_wl_F77= +lt_prog_compiler_pic_F77= +lt_prog_compiler_static_F77= + +echo "$as_me:$LINENO: checking for $compiler option to produce PIC" >&5 +echo $ECHO_N "checking for $compiler option to produce PIC... $ECHO_C" >&6 + + if test "$GCC" = yes; then + lt_prog_compiler_wl_F77='-Wl,' + lt_prog_compiler_static_F77='-static' + + case $host_os in + aix*) + # All AIX code is PIC. + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + lt_prog_compiler_static_F77='-Bstatic' + fi + ;; + + amigaos*) + # FIXME: we need at least 68020 code to build shared libraries, but + # adding the `-m68020' flag to GCC prevents building anything better, + # like `-m68040'. + lt_prog_compiler_pic_F77='-m68020 -resident32 -malways-restore-a4' + ;; + + beos* | cygwin* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) + # PIC is the default for these OSes. + ;; + + mingw* | pw32* | os2*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + lt_prog_compiler_pic_F77='-DDLL_EXPORT' + ;; + + darwin* | rhapsody*) + # PIC is the default on this platform + # Common symbols not allowed in MH_DYLIB files + lt_prog_compiler_pic_F77='-fno-common' + ;; + + msdosdjgpp*) + # Just because we use GCC doesn't mean we suddenly get shared libraries + # on systems that don't support them. + lt_prog_compiler_can_build_shared_F77=no + enable_shared=no + ;; + + sysv4*MP*) + if test -d /usr/nec; then + lt_prog_compiler_pic_F77=-Kconform_pic + fi + ;; + + hpux*) + # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but + # not for PA HP-UX. + case "$host_cpu" in + hppa*64*|ia64*) + # +Z the default + ;; + *) + lt_prog_compiler_pic_F77='-fPIC' + ;; + esac + ;; + + *) + lt_prog_compiler_pic_F77='-fPIC' + ;; + esac + else + # PORTME Check for flag to pass linker flags through the system compiler. + case $host_os in + aix*) + lt_prog_compiler_wl_F77='-Wl,' + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + lt_prog_compiler_static_F77='-Bstatic' + else + lt_prog_compiler_static_F77='-bnso -bI:/lib/syscalls.exp' + fi + ;; + + mingw* | pw32* | os2*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + lt_prog_compiler_pic_F77='-DDLL_EXPORT' + ;; + + hpux9* | hpux10* | hpux11*) + lt_prog_compiler_wl_F77='-Wl,' + # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but + # not for PA HP-UX. + case "$host_cpu" in + hppa*64*|ia64*) + # +Z the default + ;; + *) + lt_prog_compiler_pic_F77='+Z' + ;; + esac + # Is there a better lt_prog_compiler_static that works with the bundled CC? + lt_prog_compiler_static_F77='${wl}-a ${wl}archive' + ;; + + irix5* | irix6* | nonstopux*) + lt_prog_compiler_wl_F77='-Wl,' + # PIC (with -KPIC) is the default. + lt_prog_compiler_static_F77='-non_shared' + ;; + + newsos6) + lt_prog_compiler_pic_F77='-KPIC' + lt_prog_compiler_static_F77='-Bstatic' + ;; + + linux*) + case $CC in + icc* | ecc*) + lt_prog_compiler_wl_F77='-Wl,' + lt_prog_compiler_pic_F77='-KPIC' + lt_prog_compiler_static_F77='-static' + ;; + ccc*) + lt_prog_compiler_wl_F77='-Wl,' + # All Alpha code is PIC. + lt_prog_compiler_static_F77='-non_shared' + ;; + esac + ;; + + osf3* | osf4* | osf5*) + lt_prog_compiler_wl_F77='-Wl,' + # All OSF/1 code is PIC. + lt_prog_compiler_static_F77='-non_shared' + ;; + + sco3.2v5*) + lt_prog_compiler_pic_F77='-Kpic' + lt_prog_compiler_static_F77='-dn' + ;; + + solaris*) + lt_prog_compiler_wl_F77='-Wl,' + lt_prog_compiler_pic_F77='-KPIC' + lt_prog_compiler_static_F77='-Bstatic' + ;; + + sunos4*) + lt_prog_compiler_wl_F77='-Qoption ld ' + lt_prog_compiler_pic_F77='-PIC' + lt_prog_compiler_static_F77='-Bstatic' + ;; + + sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*) + lt_prog_compiler_wl_F77='-Wl,' + lt_prog_compiler_pic_F77='-KPIC' + lt_prog_compiler_static_F77='-Bstatic' + ;; + + sysv4*MP*) + if test -d /usr/nec ;then + lt_prog_compiler_pic_F77='-Kconform_pic' + lt_prog_compiler_static_F77='-Bstatic' + fi + ;; + + uts4*) + lt_prog_compiler_pic_F77='-pic' + lt_prog_compiler_static_F77='-Bstatic' + ;; + + *) + lt_prog_compiler_can_build_shared_F77=no + ;; + esac + fi + +echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_F77" >&5 +echo "${ECHO_T}$lt_prog_compiler_pic_F77" >&6 + +# +# Check to make sure the PIC flag actually works. +# +if test -n "$lt_prog_compiler_pic_F77"; then + +echo "$as_me:$LINENO: checking if $compiler PIC flag $lt_prog_compiler_pic_F77 works" >&5 +echo $ECHO_N "checking if $compiler PIC flag $lt_prog_compiler_pic_F77 works... $ECHO_C" >&6 +if test "${lt_prog_compiler_pic_works_F77+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + lt_prog_compiler_pic_works_F77=no + ac_outfile=conftest.$ac_objext + printf "$lt_simple_compile_test_code" > conftest.$ac_ext + lt_compiler_flag="$lt_prog_compiler_pic_F77" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + # The option is referenced via a variable to avoid confusing sed. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}? :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:13370: $lt_compile\"" >&5) + (eval "$lt_compile" 2>conftest.err) + ac_status=$? + cat conftest.err >&5 + echo "$as_me:13374: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s "$ac_outfile"; then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings + if test ! -s conftest.err; then + lt_prog_compiler_pic_works_F77=yes + fi + fi + $rm conftest* + +fi +echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_works_F77" >&5 +echo "${ECHO_T}$lt_prog_compiler_pic_works_F77" >&6 + +if test x"$lt_prog_compiler_pic_works_F77" = xyes; then + case $lt_prog_compiler_pic_F77 in + "" | " "*) ;; + *) lt_prog_compiler_pic_F77=" $lt_prog_compiler_pic_F77" ;; + esac +else + lt_prog_compiler_pic_F77= + lt_prog_compiler_can_build_shared_F77=no +fi + +fi +case "$host_os" in + # For platforms which do not support PIC, -DPIC is meaningless: + *djgpp*) + lt_prog_compiler_pic_F77= + ;; + *) + lt_prog_compiler_pic_F77="$lt_prog_compiler_pic_F77" + ;; +esac + +echo "$as_me:$LINENO: checking if $compiler supports -c -o file.$ac_objext" >&5 +echo $ECHO_N "checking if $compiler supports -c -o file.$ac_objext... $ECHO_C" >&6 +if test "${lt_cv_prog_compiler_c_o_F77+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + lt_cv_prog_compiler_c_o_F77=no + $rm -r conftest 2>/dev/null + mkdir conftest + cd conftest + mkdir out + printf "$lt_simple_compile_test_code" > conftest.$ac_ext + + lt_compiler_flag="-o out/conftest2.$ac_objext" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}? :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:13430: $lt_compile\"" >&5) + (eval "$lt_compile" 2>out/conftest.err) + ac_status=$? + cat out/conftest.err >&5 + echo "$as_me:13434: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s out/conftest2.$ac_objext + then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings + if test ! -s out/conftest.err; then + lt_cv_prog_compiler_c_o_F77=yes + fi + fi + chmod u+w . + $rm conftest* + # SGI C++ compiler will create directory out/ii_files/ for + # template instantiation + test -d out/ii_files && $rm out/ii_files/* && rmdir out/ii_files + $rm out/* && rmdir out + cd .. + rmdir conftest + $rm conftest* + +fi +echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_c_o_F77" >&5 +echo "${ECHO_T}$lt_cv_prog_compiler_c_o_F77" >&6 + + +hard_links="nottested" +if test "$lt_cv_prog_compiler_c_o_F77" = no && test "$need_locks" != no; then + # do not overwrite the value of need_locks provided by the user + echo "$as_me:$LINENO: checking if we can lock with hard links" >&5 +echo $ECHO_N "checking if we can lock with hard links... $ECHO_C" >&6 + hard_links=yes + $rm conftest* + ln conftest.a conftest.b 2>/dev/null && hard_links=no + touch conftest.a + ln conftest.a conftest.b 2>&5 || hard_links=no + ln conftest.a conftest.b 2>/dev/null && hard_links=no + echo "$as_me:$LINENO: result: $hard_links" >&5 +echo "${ECHO_T}$hard_links" >&6 + if test "$hard_links" = no; then + { echo "$as_me:$LINENO: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5 +echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;} + need_locks=warn + fi +else + need_locks=no +fi + +echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) supports shared libraries" >&5 +echo $ECHO_N "checking whether the $compiler linker ($LD) supports shared libraries... $ECHO_C" >&6 + + runpath_var= + allow_undefined_flag_F77= + enable_shared_with_static_runtimes_F77=no + archive_cmds_F77= + archive_expsym_cmds_F77= + old_archive_From_new_cmds_F77= + old_archive_from_expsyms_cmds_F77= + export_dynamic_flag_spec_F77= + whole_archive_flag_spec_F77= + thread_safe_flag_spec_F77= + hardcode_libdir_flag_spec_F77= + hardcode_libdir_flag_spec_ld_F77= + hardcode_libdir_separator_F77= + hardcode_direct_F77=no + hardcode_minus_L_F77=no + hardcode_shlibpath_var_F77=unsupported + link_all_deplibs_F77=unknown + hardcode_automatic_F77=no + module_cmds_F77= + module_expsym_cmds_F77= + always_export_symbols_F77=no + export_symbols_cmds_F77='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' + # include_expsyms should be a list of space-separated symbols to be *always* + # included in the symbol list + include_expsyms_F77= + # exclude_expsyms can be an extended regexp of symbols to exclude + # it will be wrapped by ` (' and `)$', so one must not match beginning or + # end of line. Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc', + # as well as any symbol that contains `d'. + exclude_expsyms_F77="_GLOBAL_OFFSET_TABLE_" + # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out + # platforms (ab)use it in PIC code, but their linkers get confused if + # the symbol is explicitly referenced. Since portable code cannot + # rely on this symbol name, it's probably fine to never include it in + # preloaded symbol tables. + extract_expsyms_cmds= + + case $host_os in + cygwin* | mingw* | pw32*) + # FIXME: the MSVC++ port hasn't been tested in a loooong time + # When not using gcc, we currently assume that we are using + # Microsoft Visual C++. + if test "$GCC" != yes; then + with_gnu_ld=no + fi + ;; + openbsd*) + with_gnu_ld=no + ;; + esac + + ld_shlibs_F77=yes + if test "$with_gnu_ld" = yes; then + # If archive_cmds runs LD, not CC, wlarc should be empty + wlarc='${wl}' + + # See if GNU ld supports shared libraries. + case $host_os in + aix3* | aix4* | aix5*) + # On AIX/PPC, the GNU linker is very broken + if test "$host_cpu" != ia64; then + ld_shlibs_F77=no + cat <&2 + +*** Warning: the GNU linker, at least up to release 2.9.1, is reported +*** to be unable to reliably create shared libraries on AIX. +*** Therefore, libtool is disabling shared libraries support. If you +*** really care for shared libraries, you may want to modify your PATH +*** so that a non-GNU linker is found, and then restart. + +EOF + fi + ;; + + amigaos*) + archive_cmds_F77='$rm $output_objdir/a2ixlibrary.data~$echo "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' + hardcode_libdir_flag_spec_F77='-L$libdir' + hardcode_minus_L_F77=yes + + # Samuel A. Falvo II reports + # that the semantics of dynamic libraries on AmigaOS, at least up + # to version 4, is to share data among multiple programs linked + # with the same dynamic library. Since this doesn't match the + # behavior of shared libraries on other platforms, we can't use + # them. + ld_shlibs_F77=no + ;; + + beos*) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + allow_undefined_flag_F77=unsupported + # Joseph Beckenbach says some releases of gcc + # support --undefined. This deserves some investigation. FIXME + archive_cmds_F77='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + else + ld_shlibs_F77=no + fi + ;; + + cygwin* | mingw* | pw32*) + # _LT_AC_TAGVAR(hardcode_libdir_flag_spec, F77) is actually meaningless, + # as there is no search path for DLLs. + hardcode_libdir_flag_spec_F77='-L$libdir' + allow_undefined_flag_F77=unsupported + always_export_symbols_F77=no + enable_shared_with_static_runtimes_F77=yes + export_symbols_cmds_F77='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGS] /s/.* \([^ ]*\)/\1 DATA/'\'' | $SED -e '\''/^[AITW] /s/.* //'\'' | sort | uniq > $export_symbols' + + if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then + archive_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--image-base=0x10000000 ${wl}--out-implib,$lib' + # If the export-symbols file already is a .def file (1st line + # is EXPORTS), use it as is; otherwise, prepend... + archive_expsym_cmds_F77='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then + cp $export_symbols $output_objdir/$soname.def; + else + echo EXPORTS > $output_objdir/$soname.def; + cat $export_symbols >> $output_objdir/$soname.def; + fi~ + $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--image-base=0x10000000 ${wl}--out-implib,$lib' + else + ld_shlibs=no + fi + ;; + + netbsd* | netbsdelf*-gnu | knetbsd*-gnu) + if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then + archive_cmds_F77='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib' + wlarc= + else + archive_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + fi + ;; + + solaris* | sysv5*) + if $LD -v 2>&1 | grep 'BFD 2\.8' > /dev/null; then + ld_shlibs_F77=no + cat <&2 + +*** Warning: The releases 2.8.* of the GNU linker cannot reliably +*** create shared libraries on Solaris systems. Therefore, libtool +*** is disabling shared libraries support. We urge you to upgrade GNU +*** binutils to release 2.9.1 or newer. Another option is to modify +*** your PATH or compiler configuration so that the native linker is +*** used, and then restart. + +EOF + elif $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + archive_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + else + ld_shlibs_F77=no + fi + ;; + + sunos4*) + archive_cmds_F77='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags' + wlarc= + hardcode_direct_F77=yes + hardcode_shlibpath_var_F77=no + ;; + + linux*) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + tmp_archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_cmds_F77="$tmp_archive_cmds" + supports_anon_versioning=no + case `$LD -v 2>/dev/null` in + *\ 01.* | *\ 2.[0-9].* | *\ 2.10.*) ;; # catch versions < 2.11 + *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ... + *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ... + *\ 2.11.*) ;; # other 2.11 versions + *) supports_anon_versioning=yes ;; + esac + if test $supports_anon_versioning = yes; then + archive_expsym_cmds_F77='$echo "{ global:" > $output_objdir/$libname.ver~ +cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ +$echo "local: *; };" >> $output_objdir/$libname.ver~ + $CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib' + else + archive_expsym_cmds_F77="$tmp_archive_cmds" + fi + link_all_deplibs_F77=no + else + ld_shlibs_F77=no + fi + ;; + + *) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + archive_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + else + ld_shlibs_F77=no + fi + ;; + esac + + if test "$ld_shlibs_F77" = yes; then + runpath_var=LD_RUN_PATH + hardcode_libdir_flag_spec_F77='${wl}--rpath ${wl}$libdir' + export_dynamic_flag_spec_F77='${wl}--export-dynamic' + # ancient GNU ld didn't support --whole-archive et. al. + if $LD --help 2>&1 | grep 'no-whole-archive' > /dev/null; then + whole_archive_flag_spec_F77="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' + else + whole_archive_flag_spec_F77= + fi + fi + else + # PORTME fill in a description of your system's linker (not GNU ld) + case $host_os in + aix3*) + allow_undefined_flag_F77=unsupported + always_export_symbols_F77=yes + archive_expsym_cmds_F77='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname' + # Note: this linker hardcodes the directories in LIBPATH if there + # are no directories specified by -L. + hardcode_minus_L_F77=yes + if test "$GCC" = yes && test -z "$link_static_flag"; then + # Neither direct hardcoding nor static linking is supported with a + # broken collect2. + hardcode_direct_F77=unsupported + fi + ;; + + aix4* | aix5*) + if test "$host_cpu" = ia64; then + # On IA64, the linker does run time linking by default, so we don't + # have to do anything special. + aix_use_runtimelinking=no + exp_sym_flag='-Bexport' + no_entry_flag="" + else + # If we're using GNU nm, then we don't want the "-C" option. + # -C means demangle to AIX nm, but means don't demangle with GNU nm + if $NM -V 2>&1 | grep 'GNU' > /dev/null; then + export_symbols_cmds_F77='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$2 == "T") || (\$2 == "D") || (\$2 == "B")) && (substr(\$3,1,1) != ".")) { print \$3 } }'\'' | sort -u > $export_symbols' + else + export_symbols_cmds_F77='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$2 == "T") || (\$2 == "D") || (\$2 == "B")) && (substr(\$3,1,1) != ".")) { print \$3 } }'\'' | sort -u > $export_symbols' + fi + aix_use_runtimelinking=no + + # Test if we are trying to use run time linking or normal + # AIX style linking. If -brtl is somewhere in LDFLAGS, we + # need to do runtime linking. + case $host_os in aix4.[23]|aix4.[23].*|aix5*) + for ld_flag in $LDFLAGS; do + if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then + aix_use_runtimelinking=yes + break + fi + done + esac + + exp_sym_flag='-bexport' + no_entry_flag='-bnoentry' + fi + + # When large executables or shared objects are built, AIX ld can + # have problems creating the table of contents. If linking a library + # or program results in "error TOC overflow" add -mminimal-toc to + # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not + # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. + + archive_cmds_F77='' + hardcode_direct_F77=yes + hardcode_libdir_separator_F77=':' + link_all_deplibs_F77=yes + + if test "$GCC" = yes; then + case $host_os in aix4.012|aix4.012.*) + # We only want to do this on AIX 4.2 and lower, the check + # below for broken collect2 doesn't work under 4.3+ + collect2name=`${CC} -print-prog-name=collect2` + if test -f "$collect2name" && \ + strings "$collect2name" | grep resolve_lib_name >/dev/null + then + # We have reworked collect2 + hardcode_direct_F77=yes + else + # We have old collect2 + hardcode_direct_F77=unsupported + # It fails to find uninstalled libraries when the uninstalled + # path is not listed in the libpath. Setting hardcode_minus_L + # to unsupported forces relinking + hardcode_minus_L_F77=yes + hardcode_libdir_flag_spec_F77='-L$libdir' + hardcode_libdir_separator_F77= + fi + esac + shared_flag='-shared' + else + # not using gcc + if test "$host_cpu" = ia64; then + # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release + # chokes on -Wl,-G. The following line is correct: + shared_flag='-G' + else + if test "$aix_use_runtimelinking" = yes; then + shared_flag='${wl}-G' + else + shared_flag='${wl}-bM:SRE' + fi + fi + fi + + # It seems that -bexpall does not export symbols beginning with + # underscore (_), so it is better to generate a list of symbols to export. + always_export_symbols_F77=yes + if test "$aix_use_runtimelinking" = yes; then + # Warning - without using the other runtime loading flags (-brtl), + # -berok will link without error, but may produce a broken library. + allow_undefined_flag_F77='-berok' + # Determine the default libpath from the value encoded in an empty executable. + cat >conftest.$ac_ext <<_ACEOF + program main + + end +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_f77_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + +aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; } +}'` +# Check for a 64-bit object if we didn't find anything. +if test -z "$aix_libpath"; then aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; } +}'`; fi +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +fi +rm -f conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi + + hardcode_libdir_flag_spec_F77='${wl}-blibpath:$libdir:'"$aix_libpath" + archive_expsym_cmds_F77="\$CC"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$no_entry_flag \${wl}$exp_sym_flag:\$export_symbols $shared_flag" + else + if test "$host_cpu" = ia64; then + hardcode_libdir_flag_spec_F77='${wl}-R $libdir:/usr/lib:/lib' + allow_undefined_flag_F77="-z nodefs" + archive_expsym_cmds_F77="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$no_entry_flag \${wl}$exp_sym_flag:\$export_symbols" + else + # Determine the default libpath from the value encoded in an empty executable. + cat >conftest.$ac_ext <<_ACEOF + program main + + end +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_f77_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + +aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; } +}'` +# Check for a 64-bit object if we didn't find anything. +if test -z "$aix_libpath"; then aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; } +}'`; fi +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +fi +rm -f conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi + + hardcode_libdir_flag_spec_F77='${wl}-blibpath:$libdir:'"$aix_libpath" + # Warning - without using the other run time loading flags, + # -berok will link without error, but may produce a broken library. + no_undefined_flag_F77=' ${wl}-bernotok' + allow_undefined_flag_F77=' ${wl}-berok' + # -bexpall does not export symbols beginning with underscore (_) + always_export_symbols_F77=yes + # Exported symbols can be pulled into shared objects from archives + whole_archive_flag_spec_F77=' ' + archive_cmds_need_lc_F77=yes + # This is similar to how AIX traditionally builds it's shared libraries. + archive_expsym_cmds_F77="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags ${wl}-bE:$export_symbols ${wl}-bnoentry${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' + fi + fi + ;; + + amigaos*) + archive_cmds_F77='$rm $output_objdir/a2ixlibrary.data~$echo "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' + hardcode_libdir_flag_spec_F77='-L$libdir' + hardcode_minus_L_F77=yes + # see comment about different semantics on the GNU ld section + ld_shlibs_F77=no + ;; + + bsdi4*) + export_dynamic_flag_spec_F77=-rdynamic + ;; + + cygwin* | mingw* | pw32*) + # When not using gcc, we currently assume that we are using + # Microsoft Visual C++. + # hardcode_libdir_flag_spec is actually meaningless, as there is + # no search path for DLLs. + hardcode_libdir_flag_spec_F77=' ' + allow_undefined_flag_F77=unsupported + # Tell ltmain to make .lib files, not .a files. + libext=lib + # Tell ltmain to make .dll files, not .so files. + shrext_cmds=".dll" + # FIXME: Setting linknames here is a bad hack. + archive_cmds_F77='$CC -o $lib $libobjs $compiler_flags `echo "$deplibs" | $SED -e '\''s/ -lc$//'\''` -link -dll~linknames=' + # The linker will automatically build a .lib file if we build a DLL. + old_archive_From_new_cmds_F77='true' + # FIXME: Should let the user specify the lib program. + old_archive_cmds_F77='lib /OUT:$oldlib$oldobjs$old_deplibs' + fix_srcfile_path='`cygpath -w "$srcfile"`' + enable_shared_with_static_runtimes_F77=yes + ;; + + darwin* | rhapsody*) + if test "$GXX" = yes ; then + archive_cmds_need_lc_F77=no + case "$host_os" in + rhapsody* | darwin1.[012]) + allow_undefined_flag_F77='-undefined suppress' + ;; + *) # Darwin 1.3 on + if test -z ${MACOSX_DEPLOYMENT_TARGET} ; then + allow_undefined_flag_F77='-flat_namespace -undefined suppress' + else + case ${MACOSX_DEPLOYMENT_TARGET} in + 10.[012]) + allow_undefined_flag_F77='-flat_namespace -undefined suppress' + ;; + 10.*) + allow_undefined_flag_F77='-undefined dynamic_lookup' + ;; + esac + fi + ;; + esac + lt_int_apple_cc_single_mod=no + output_verbose_link_cmd='echo' + if $CC -dumpspecs 2>&1 | grep 'single_module' >/dev/null ; then + lt_int_apple_cc_single_mod=yes + fi + if test "X$lt_int_apple_cc_single_mod" = Xyes ; then + archive_cmds_F77='$CC -dynamiclib -single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring' + else + archive_cmds_F77='$CC -r ${wl}-bind_at_load -keep_private_externs -nostdlib -o ${lib}-master.o $libobjs~$CC -dynamiclib $allow_undefined_flag -o $lib ${lib}-master.o $deplibs $compiler_flags -install_name $rpath/$soname $verstring' + fi + module_cmds_F77='$CC ${wl}-bind_at_load $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags' + # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin ld's + if test "X$lt_int_apple_cc_single_mod" = Xyes ; then + archive_expsym_cmds_F77='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -dynamiclib -single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + else + archive_expsym_cmds_F77='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -r ${wl}-bind_at_load -keep_private_externs -nostdlib -o ${lib}-master.o $libobjs~$CC -dynamiclib $allow_undefined_flag -o $lib ${lib}-master.o $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + fi + module_expsym_cmds_F77='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + hardcode_direct_F77=no + hardcode_automatic_F77=yes + hardcode_shlibpath_var_F77=unsupported + whole_archive_flag_spec_F77='-all_load $convenience' + link_all_deplibs_F77=yes + else + ld_shlibs_F77=no + fi + ;; + + dgux*) + archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_libdir_flag_spec_F77='-L$libdir' + hardcode_shlibpath_var_F77=no + ;; + + freebsd1*) + ld_shlibs_F77=no + ;; + + # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor + # support. Future versions do this automatically, but an explicit c++rt0.o + # does not break anything, and helps significantly (at the cost of a little + # extra space). + freebsd2.2*) + archive_cmds_F77='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o' + hardcode_libdir_flag_spec_F77='-R$libdir' + hardcode_direct_F77=yes + hardcode_shlibpath_var_F77=no + ;; + + # Unfortunately, older versions of FreeBSD 2 do not have this feature. + freebsd2*) + archive_cmds_F77='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct_F77=yes + hardcode_minus_L_F77=yes + hardcode_shlibpath_var_F77=no + ;; + + # FreeBSD 3 and greater uses gcc -shared to do shared libraries. + freebsd* | kfreebsd*-gnu) + archive_cmds_F77='$CC -shared -o $lib $libobjs $deplibs $compiler_flags' + hardcode_libdir_flag_spec_F77='-R$libdir' + hardcode_direct_F77=yes + hardcode_shlibpath_var_F77=no + ;; + + hpux9*) + if test "$GCC" = yes; then + archive_cmds_F77='$rm $output_objdir/$soname~$CC -shared -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + else + archive_cmds_F77='$rm $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + fi + hardcode_libdir_flag_spec_F77='${wl}+b ${wl}$libdir' + hardcode_libdir_separator_F77=: + hardcode_direct_F77=yes + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + hardcode_minus_L_F77=yes + export_dynamic_flag_spec_F77='${wl}-E' + ;; + + hpux10* | hpux11*) + if test "$GCC" = yes -a "$with_gnu_ld" = no; then + case "$host_cpu" in + hppa*64*|ia64*) + archive_cmds_F77='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + *) + archive_cmds_F77='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' + ;; + esac + else + case "$host_cpu" in + hppa*64*|ia64*) + archive_cmds_F77='$LD -b +h $soname -o $lib $libobjs $deplibs $linker_flags' + ;; + *) + archive_cmds_F77='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' + ;; + esac + fi + if test "$with_gnu_ld" = no; then + case "$host_cpu" in + hppa*64*) + hardcode_libdir_flag_spec_F77='${wl}+b ${wl}$libdir' + hardcode_libdir_flag_spec_ld_F77='+b $libdir' + hardcode_libdir_separator_F77=: + hardcode_direct_F77=no + hardcode_shlibpath_var_F77=no + ;; + ia64*) + hardcode_libdir_flag_spec_F77='-L$libdir' + hardcode_direct_F77=no + hardcode_shlibpath_var_F77=no + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + hardcode_minus_L_F77=yes + ;; + *) + hardcode_libdir_flag_spec_F77='${wl}+b ${wl}$libdir' + hardcode_libdir_separator_F77=: + hardcode_direct_F77=yes + export_dynamic_flag_spec_F77='${wl}-E' + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + hardcode_minus_L_F77=yes + ;; + esac + fi + ;; + + irix5* | irix6* | nonstopux*) + if test "$GCC" = yes; then + archive_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + else + archive_cmds_F77='$LD -shared $libobjs $deplibs $linker_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib' + hardcode_libdir_flag_spec_ld_F77='-rpath $libdir' + fi + hardcode_libdir_flag_spec_F77='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator_F77=: + link_all_deplibs_F77=yes + ;; + + netbsd* | netbsdelf*-gnu | knetbsd*-gnu) + if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then + archive_cmds_F77='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out + else + archive_cmds_F77='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF + fi + hardcode_libdir_flag_spec_F77='-R$libdir' + hardcode_direct_F77=yes + hardcode_shlibpath_var_F77=no + ;; + + newsos6) + archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct_F77=yes + hardcode_libdir_flag_spec_F77='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator_F77=: + hardcode_shlibpath_var_F77=no + ;; + + openbsd*) + hardcode_direct_F77=yes + hardcode_shlibpath_var_F77=no + if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + archive_cmds_F77='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' + hardcode_libdir_flag_spec_F77='${wl}-rpath,$libdir' + export_dynamic_flag_spec_F77='${wl}-E' + else + case $host_os in + openbsd[01].* | openbsd2.[0-7] | openbsd2.[0-7].*) + archive_cmds_F77='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' + hardcode_libdir_flag_spec_F77='-R$libdir' + ;; + *) + archive_cmds_F77='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' + hardcode_libdir_flag_spec_F77='${wl}-rpath,$libdir' + ;; + esac + fi + ;; + + os2*) + hardcode_libdir_flag_spec_F77='-L$libdir' + hardcode_minus_L_F77=yes + allow_undefined_flag_F77=unsupported + archive_cmds_F77='$echo "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$echo "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~$echo DATA >> $output_objdir/$libname.def~$echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~$echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def' + old_archive_From_new_cmds_F77='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def' + ;; + + osf3*) + if test "$GCC" = yes; then + allow_undefined_flag_F77=' ${wl}-expect_unresolved ${wl}\*' + archive_cmds_F77='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + else + allow_undefined_flag_F77=' -expect_unresolved \*' + archive_cmds_F77='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib' + fi + hardcode_libdir_flag_spec_F77='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator_F77=: + ;; + + osf4* | osf5*) # as osf3* with the addition of -msym flag + if test "$GCC" = yes; then + allow_undefined_flag_F77=' ${wl}-expect_unresolved ${wl}\*' + archive_cmds_F77='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + hardcode_libdir_flag_spec_F77='${wl}-rpath ${wl}$libdir' + else + allow_undefined_flag_F77=' -expect_unresolved \*' + archive_cmds_F77='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -msym -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib' + archive_expsym_cmds_F77='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; echo "-hidden">> $lib.exp~ + $LD -shared${allow_undefined_flag} -input $lib.exp $linker_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${objdir}/so_locations -o $lib~$rm $lib.exp' + + # Both c and cxx compiler support -rpath directly + hardcode_libdir_flag_spec_F77='-rpath $libdir' + fi + hardcode_libdir_separator_F77=: + ;; + + sco3.2v5*) + archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_shlibpath_var_F77=no + export_dynamic_flag_spec_F77='${wl}-Bexport' + runpath_var=LD_RUN_PATH + hardcode_runpath_var=yes + ;; + + solaris*) + no_undefined_flag_F77=' -z text' + if test "$GCC" = yes; then + archive_cmds_F77='$CC -shared ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds_F77='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~ + $CC -shared ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$rm $lib.exp' + else + archive_cmds_F77='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags' + archive_expsym_cmds_F77='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~ + $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$rm $lib.exp' + fi + hardcode_libdir_flag_spec_F77='-R$libdir' + hardcode_shlibpath_var_F77=no + case $host_os in + solaris2.[0-5] | solaris2.[0-5].*) ;; + *) # Supported since Solaris 2.6 (maybe 2.5.1?) + whole_archive_flag_spec_F77='-z allextract$convenience -z defaultextract' ;; + esac + link_all_deplibs_F77=yes + ;; + + sunos4*) + if test "x$host_vendor" = xsequent; then + # Use $CC to link under sequent, because it throws in some extra .o + # files that make .init and .fini sections work. + archive_cmds_F77='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags' + else + archive_cmds_F77='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags' + fi + hardcode_libdir_flag_spec_F77='-L$libdir' + hardcode_direct_F77=yes + hardcode_minus_L_F77=yes + hardcode_shlibpath_var_F77=no + ;; + + sysv4) + case $host_vendor in + sni) + archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct_F77=yes # is this really true??? + ;; + siemens) + ## LD is ld it makes a PLAMLIB + ## CC just makes a GrossModule. + archive_cmds_F77='$LD -G -o $lib $libobjs $deplibs $linker_flags' + reload_cmds_F77='$CC -r -o $output$reload_objs' + hardcode_direct_F77=no + ;; + motorola) + archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct_F77=no #Motorola manual says yes, but my tests say they lie + ;; + esac + runpath_var='LD_RUN_PATH' + hardcode_shlibpath_var_F77=no + ;; + + sysv4.3*) + archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_shlibpath_var_F77=no + export_dynamic_flag_spec_F77='-Bexport' + ;; + + sysv4*MP*) + if test -d /usr/nec; then + archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_shlibpath_var_F77=no + runpath_var=LD_RUN_PATH + hardcode_runpath_var=yes + ld_shlibs_F77=yes + fi + ;; + + sysv4.2uw2*) + archive_cmds_F77='$LD -G -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct_F77=yes + hardcode_minus_L_F77=no + hardcode_shlibpath_var_F77=no + hardcode_runpath_var=yes + runpath_var=LD_RUN_PATH + ;; + + sysv5OpenUNIX8* | sysv5UnixWare7* | sysv5uw[78]* | unixware7*) + no_undefined_flag_F77='${wl}-z ${wl}text' + if test "$GCC" = yes; then + archive_cmds_F77='$CC -shared ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + else + archive_cmds_F77='$CC -G ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + fi + runpath_var='LD_RUN_PATH' + hardcode_shlibpath_var_F77=no + ;; + + sysv5*) + no_undefined_flag_F77=' -z text' + # $CC -shared without GNU ld will not create a library from C++ + # object files and a static libstdc++, better avoid it by now + archive_cmds_F77='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags' + archive_expsym_cmds_F77='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~ + $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$rm $lib.exp' + hardcode_libdir_flag_spec_F77= + hardcode_shlibpath_var_F77=no + runpath_var='LD_RUN_PATH' + ;; + + uts4*) + archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_libdir_flag_spec_F77='-L$libdir' + hardcode_shlibpath_var_F77=no + ;; + + *) + ld_shlibs_F77=no + ;; + esac + fi + +echo "$as_me:$LINENO: result: $ld_shlibs_F77" >&5 +echo "${ECHO_T}$ld_shlibs_F77" >&6 +test "$ld_shlibs_F77" = no && can_build_shared=no + +variables_saved_for_relink="PATH $shlibpath_var $runpath_var" +if test "$GCC" = yes; then + variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" +fi + +# +# Do we need to explicitly link libc? +# +case "x$archive_cmds_need_lc_F77" in +x|xyes) + # Assume -lc should be added + archive_cmds_need_lc_F77=yes + + if test "$enable_shared" = yes && test "$GCC" = yes; then + case $archive_cmds_F77 in + *'~'*) + # FIXME: we may have to deal with multi-command sequences. + ;; + '$CC '*) + # Test whether the compiler implicitly links with -lc since on some + # systems, -lgcc has to come before -lc. If gcc already passes -lc + # to ld, don't add -lc before -lgcc. + echo "$as_me:$LINENO: checking whether -lc should be explicitly linked in" >&5 +echo $ECHO_N "checking whether -lc should be explicitly linked in... $ECHO_C" >&6 + $rm conftest* + printf "$lt_simple_compile_test_code" > conftest.$ac_ext + + if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } 2>conftest.err; then + soname=conftest + lib=conftest + libobjs=conftest.$ac_objext + deplibs= + wl=$lt_prog_compiler_wl_F77 + compiler_flags=-v + linker_flags=-v + verstring= + output_objdir=. + libname=conftest + lt_save_allow_undefined_flag=$allow_undefined_flag_F77 + allow_undefined_flag_F77= + if { (eval echo "$as_me:$LINENO: \"$archive_cmds_F77 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1\"") >&5 + (eval $archive_cmds_F77 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } + then + archive_cmds_need_lc_F77=no + else + archive_cmds_need_lc_F77=yes + fi + allow_undefined_flag_F77=$lt_save_allow_undefined_flag + else + cat conftest.err 1>&5 + fi + $rm conftest* + echo "$as_me:$LINENO: result: $archive_cmds_need_lc_F77" >&5 +echo "${ECHO_T}$archive_cmds_need_lc_F77" >&6 + ;; + esac + fi + ;; +esac + +echo "$as_me:$LINENO: checking dynamic linker characteristics" >&5 +echo $ECHO_N "checking dynamic linker characteristics... $ECHO_C" >&6 +library_names_spec= +libname_spec='lib$name' +soname_spec= +shrext_cmds=".so" +postinstall_cmds= +postuninstall_cmds= +finish_cmds= +finish_eval= +shlibpath_var= +shlibpath_overrides_runpath=unknown +version_type=none +dynamic_linker="$host_os ld.so" +sys_lib_dlsearch_path_spec="/lib /usr/lib" +if test "$GCC" = yes; then + sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"` + if echo "$sys_lib_search_path_spec" | grep ';' >/dev/null ; then + # if the path contains ";" then we assume it to be the separator + # otherwise default to the standard path separator (i.e. ":") - it is + # assumed that no part of a normal pathname contains ";" but that should + # okay in the real world where ";" in dirpaths is itself problematic. + sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` + else + sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` + fi +else + sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" +fi +need_lib_prefix=unknown +hardcode_into_libs=no + +# when you set need_version to no, make sure it does not cause -set_version +# flags to be left without arguments +need_version=unknown + +case $host_os in +aix3*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a' + shlibpath_var=LIBPATH + + # AIX 3 has no versioning support, so we append a major version to the name. + soname_spec='${libname}${release}${shared_ext}$major' + ;; + +aix4* | aix5*) + version_type=linux + need_lib_prefix=no + need_version=no + hardcode_into_libs=yes + if test "$host_cpu" = ia64; then + # AIX 5 supports IA64 + library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + else + # With GCC up to 2.95.x, collect2 would create an import file + # for dependence libraries. The import file would start with + # the line `#! .'. This would cause the generated library to + # depend on `.', always an invalid library. This was fixed in + # development snapshots of GCC prior to 3.0. + case $host_os in + aix4 | aix4.[01] | aix4.[01].*) + if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' + echo ' yes ' + echo '#endif'; } | ${CC} -E - | grep yes > /dev/null; then + : + else + can_build_shared=no + fi + ;; + esac + # AIX (on Power*) has no versioning support, so currently we can not hardcode correct + # soname into executable. Probably we can add versioning support to + # collect2, so additional links can be useful in future. + if test "$aix_use_runtimelinking" = yes; then + # If using run time linking (on AIX 4.2 or later) use lib.so + # instead of lib.a to let people know that these are not + # typical AIX shared libraries. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + else + # We preserve .a as extension for shared libraries through AIX4.2 + # and later when we are not doing run time linking. + library_names_spec='${libname}${release}.a $libname.a' + soname_spec='${libname}${release}${shared_ext}$major' + fi + shlibpath_var=LIBPATH + fi + ;; + +amigaos*) + library_names_spec='$libname.ixlibrary $libname.a' + # Create ${libname}_ixlibrary.a entries in /sys/libs. + finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`$echo "X$lib" | $Xsed -e '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $rm /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' + ;; + +beos*) + library_names_spec='${libname}${shared_ext}' + dynamic_linker="$host_os ld.so" + shlibpath_var=LIBRARY_PATH + ;; + +bsdi4*) + version_type=linux + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' + shlibpath_var=LD_LIBRARY_PATH + sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" + sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" + # the default ld.so.conf also contains /usr/contrib/lib and + # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow + # libtool to hard-code these into programs + ;; + +cygwin* | mingw* | pw32*) + version_type=windows + shrext_cmds=".dll" + need_version=no + need_lib_prefix=no + + case $GCC,$host_os in + yes,cygwin* | yes,mingw* | yes,pw32*) + library_names_spec='$libname.dll.a' + # DLL is installed to $(libdir)/../bin by postinstall_cmds + postinstall_cmds='base_file=`basename \${file}`~ + dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i;echo \$dlname'\''`~ + dldir=$destdir/`dirname \$dlpath`~ + test -d \$dldir || mkdir -p \$dldir~ + $install_prog $dir/$dlname \$dldir/$dlname' + postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ + dlpath=$dir/\$dldll~ + $rm \$dlpath' + shlibpath_overrides_runpath=yes + + case $host_os in + cygwin*) + # Cygwin DLLs use 'cyg' prefix rather than 'lib' + soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' + sys_lib_search_path_spec="/usr/lib /lib/w32api /lib /usr/local/lib" + ;; + mingw*) + # MinGW DLLs use traditional 'lib' prefix + soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' + sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"` + if echo "$sys_lib_search_path_spec" | grep ';[c-zC-Z]:/' >/dev/null; then + # It is most probably a Windows format PATH printed by + # mingw gcc, but we are running on Cygwin. Gcc prints its search + # path with ; separators, and with drive letters. We can handle the + # drive letters (cygwin fileutils understands them), so leave them, + # especially as we might pass files found there to a mingw objdump, + # which wouldn't understand a cygwinified path. Ahh. + sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` + else + sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` + fi + ;; + pw32*) + # pw32 DLLs use 'pw' prefix rather than 'lib' + library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/./-/g'`${versuffix}${shared_ext}' + ;; + esac + ;; + + *) + library_names_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext} $libname.lib' + ;; + esac + dynamic_linker='Win32 ld.exe' + # FIXME: first we should search . and the directory the executable is in + shlibpath_var=PATH + ;; + +darwin* | rhapsody*) + dynamic_linker="$host_os dyld" + version_type=darwin + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${versuffix}$shared_ext ${libname}${release}${major}$shared_ext ${libname}$shared_ext' + soname_spec='${libname}${release}${major}$shared_ext' + shlibpath_overrides_runpath=yes + shlibpath_var=DYLD_LIBRARY_PATH + shrext_cmds='$(test .$module = .yes && echo .so || echo .dylib)' + # Apple's gcc prints 'gcc -print-search-dirs' doesn't operate the same. + if test "$GCC" = yes; then + sys_lib_search_path_spec=`$CC -print-search-dirs | tr "\n" "$PATH_SEPARATOR" | sed -e 's/libraries:/@libraries:/' | tr "@" "\n" | grep "^libraries:" | sed -e "s/^libraries://" -e "s,=/,/,g" -e "s,$PATH_SEPARATOR, ,g" -e "s,.*,& /lib /usr/lib /usr/local/lib,g"` + else + sys_lib_search_path_spec='/lib /usr/lib /usr/local/lib' + fi + sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' + ;; + +dgux*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +freebsd1*) + dynamic_linker=no + ;; + +kfreebsd*-gnu) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + dynamic_linker='GNU ld.so' + ;; + +freebsd*) + objformat=`test -x /usr/bin/objformat && /usr/bin/objformat || echo aout` + version_type=freebsd-$objformat + case $version_type in + freebsd-elf*) + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' + need_version=no + need_lib_prefix=no + ;; + freebsd-*) + library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix' + need_version=yes + ;; + esac + shlibpath_var=LD_LIBRARY_PATH + case $host_os in + freebsd2*) + shlibpath_overrides_runpath=yes + ;; + freebsd3.01* | freebsdelf3.01*) + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + *) # from 3.2 on + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + esac + ;; + +gnu*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + hardcode_into_libs=yes + ;; + +hpux9* | hpux10* | hpux11*) + # Give a soname corresponding to the major version so that dld.sl refuses to + # link against other versions. + version_type=sunos + need_lib_prefix=no + need_version=no + case "$host_cpu" in + ia64*) + shrext_cmds='.so' + hardcode_into_libs=yes + dynamic_linker="$host_os dld.so" + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + if test "X$HPUX_IA64_MODE" = X32; then + sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" + else + sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" + fi + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + ;; + hppa*64*) + shrext_cmds='.sl' + hardcode_into_libs=yes + dynamic_linker="$host_os dld.sl" + shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH + shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + ;; + *) + shrext_cmds='.sl' + dynamic_linker="$host_os dld.sl" + shlibpath_var=SHLIB_PATH + shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + ;; + esac + # HP-UX runs *really* slowly unless shared libraries are mode 555. + postinstall_cmds='chmod 555 $lib' + ;; + +irix5* | irix6* | nonstopux*) + case $host_os in + nonstopux*) version_type=nonstopux ;; + *) + if test "$lt_cv_prog_gnu_ld" = yes; then + version_type=linux + else + version_type=irix + fi ;; + esac + need_lib_prefix=no + need_version=no + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}' + case $host_os in + irix5* | nonstopux*) + libsuff= shlibsuff= + ;; + *) + case $LD in # libtool.m4 will add one of these switches to LD + *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") + libsuff= shlibsuff= libmagic=32-bit;; + *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") + libsuff=32 shlibsuff=N32 libmagic=N32;; + *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") + libsuff=64 shlibsuff=64 libmagic=64-bit;; + *) libsuff= shlibsuff= libmagic=never-match;; + esac + ;; + esac + shlibpath_var=LD_LIBRARY${shlibsuff}_PATH + shlibpath_overrides_runpath=no + sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" + sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" + hardcode_into_libs=yes + ;; + +# No shared lib support for Linux oldld, aout, or coff. +linux*oldld* | linux*aout* | linux*coff*) + dynamic_linker=no + ;; + +# This must be Linux ELF. +linux*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + # This implies no fast_install, which is unacceptable. + # Some rework will be needed to allow for fast_install + # before this can be enabled. + hardcode_into_libs=yes + + # Append ld.so.conf contents to the search path + if test -f /etc/ld.so.conf; then + lt_ld_extra=`$SED -e 's/:,\t/ /g;s/=^=*$//;s/=^= * / /g' /etc/ld.so.conf | tr '\n' ' '` + sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" + fi + + # We used to test for /lib/ld.so.1 and disable shared libraries on + # powerpc, because MkLinux only supported shared libraries with the + # GNU dynamic linker. Since this was broken with cross compilers, + # most powerpc-linux boxes support dynamic linking these days and + # people can always --disable-shared, the test was removed, and we + # assume the GNU/Linux dynamic linker is in use. + dynamic_linker='GNU/Linux ld.so' + ;; + +netbsdelf*-gnu) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + dynamic_linker='NetBSD ld.elf_so' + ;; + +knetbsd*-gnu) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + dynamic_linker='GNU ld.so' + ;; + +netbsd*) + version_type=sunos + need_lib_prefix=no + need_version=no + if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' + dynamic_linker='NetBSD (a.out) ld.so' + else + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + dynamic_linker='NetBSD ld.elf_so' + fi + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + +newsos6) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + ;; + +nto-qnx*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + ;; + +openbsd*) + version_type=sunos + need_lib_prefix=no + need_version=yes + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' + shlibpath_var=LD_LIBRARY_PATH + if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + case $host_os in + openbsd2.[89] | openbsd2.[89].*) + shlibpath_overrides_runpath=no + ;; + *) + shlibpath_overrides_runpath=yes + ;; + esac + else + shlibpath_overrides_runpath=yes + fi + ;; + +os2*) + libname_spec='$name' + shrext_cmds=".dll" + need_lib_prefix=no + library_names_spec='$libname${shared_ext} $libname.a' + dynamic_linker='OS/2 ld.exe' + shlibpath_var=LIBPATH + ;; + +osf3* | osf4* | osf5*) + version_type=osf + need_lib_prefix=no + need_version=no + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" + sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec" + ;; + +sco3.2v5*) + version_type=osf + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + ;; + +solaris*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + # ldd complains unless libraries are executable + postinstall_cmds='chmod +x $lib' + ;; + +sunos4*) + version_type=sunos + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + if test "$with_gnu_ld" = yes; then + need_lib_prefix=no + fi + need_version=yes + ;; + +sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + case $host_vendor in + sni) + shlibpath_overrides_runpath=no + need_lib_prefix=no + export_dynamic_flag_spec='${wl}-Blargedynsym' + runpath_var=LD_RUN_PATH + ;; + siemens) + need_lib_prefix=no + ;; + motorola) + need_lib_prefix=no + need_version=no + shlibpath_overrides_runpath=no + sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' + ;; + esac + ;; + +sysv4*MP*) + if test -d /usr/nec ;then + version_type=linux + library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}' + soname_spec='$libname${shared_ext}.$major' + shlibpath_var=LD_LIBRARY_PATH + fi + ;; + +uts4*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +*) + dynamic_linker=no + ;; +esac +echo "$as_me:$LINENO: result: $dynamic_linker" >&5 +echo "${ECHO_T}$dynamic_linker" >&6 +test "$dynamic_linker" = no && can_build_shared=no + +echo "$as_me:$LINENO: checking how to hardcode library paths into programs" >&5 +echo $ECHO_N "checking how to hardcode library paths into programs... $ECHO_C" >&6 +hardcode_action_F77= +if test -n "$hardcode_libdir_flag_spec_F77" || \ + test -n "$runpath_var F77" || \ + test "X$hardcode_automatic_F77"="Xyes" ; then + + # We can hardcode non-existant directories. + if test "$hardcode_direct_F77" != no && + # If the only mechanism to avoid hardcoding is shlibpath_var, we + # have to relink, otherwise we might link with an installed library + # when we should be linking with a yet-to-be-installed one + ## test "$_LT_AC_TAGVAR(hardcode_shlibpath_var, F77)" != no && + test "$hardcode_minus_L_F77" != no; then + # Linking always hardcodes the temporary library directory. + hardcode_action_F77=relink + else + # We can link without hardcoding, and we can hardcode nonexisting dirs. + hardcode_action_F77=immediate + fi +else + # We cannot hardcode anything, or else we can only hardcode existing + # directories. + hardcode_action_F77=unsupported +fi +echo "$as_me:$LINENO: result: $hardcode_action_F77" >&5 +echo "${ECHO_T}$hardcode_action_F77" >&6 + +if test "$hardcode_action_F77" = relink; then + # Fast installation is not supported + enable_fast_install=no +elif test "$shlibpath_overrides_runpath" = yes || + test "$enable_shared" = no; then + # Fast installation is not necessary + enable_fast_install=needless +fi + +striplib= +old_striplib= +echo "$as_me:$LINENO: checking whether stripping libraries is possible" >&5 +echo $ECHO_N "checking whether stripping libraries is possible... $ECHO_C" >&6 +if test -n "$STRIP" && $STRIP -V 2>&1 | grep "GNU strip" >/dev/null; then + test -z "$old_striplib" && old_striplib="$STRIP --strip-debug" + test -z "$striplib" && striplib="$STRIP --strip-unneeded" + echo "$as_me:$LINENO: result: yes" >&5 +echo "${ECHO_T}yes" >&6 +else +# FIXME - insert some real tests, host_os isn't really good enough + case $host_os in + darwin*) + if test -n "$STRIP" ; then + striplib="$STRIP -x" + echo "$as_me:$LINENO: result: yes" >&5 +echo "${ECHO_T}yes" >&6 + else + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 +fi + ;; + *) + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 + ;; + esac +fi + + + +# The else clause should only fire when bootstrapping the +# libtool distribution, otherwise you forgot to ship ltmain.sh +# with your package, and you will get complaints that there are +# no rules to generate ltmain.sh. +if test -f "$ltmain"; then + # See if we are running on zsh, and set the options which allow our commands through + # without removal of \ escapes. + if test -n "${ZSH_VERSION+set}" ; then + setopt NO_GLOB_SUBST + fi + # Now quote all the things that may contain metacharacters while being + # careful not to overquote the AC_SUBSTed values. We take copies of the + # variables and quote the copies for generation of the libtool script. + for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC NM \ + SED SHELL STRIP \ + libname_spec library_names_spec soname_spec extract_expsyms_cmds \ + old_striplib striplib file_magic_cmd finish_cmds finish_eval \ + deplibs_check_method reload_flag reload_cmds need_locks \ + lt_cv_sys_global_symbol_pipe lt_cv_sys_global_symbol_to_cdecl \ + lt_cv_sys_global_symbol_to_c_name_address \ + sys_lib_search_path_spec sys_lib_dlsearch_path_spec \ + old_postinstall_cmds old_postuninstall_cmds \ + compiler_F77 \ + CC_F77 \ + LD_F77 \ + lt_prog_compiler_wl_F77 \ + lt_prog_compiler_pic_F77 \ + lt_prog_compiler_static_F77 \ + lt_prog_compiler_no_builtin_flag_F77 \ + export_dynamic_flag_spec_F77 \ + thread_safe_flag_spec_F77 \ + whole_archive_flag_spec_F77 \ + enable_shared_with_static_runtimes_F77 \ + old_archive_cmds_F77 \ + old_archive_from_new_cmds_F77 \ + predep_objects_F77 \ + postdep_objects_F77 \ + predeps_F77 \ + postdeps_F77 \ + compiler_lib_search_path_F77 \ + archive_cmds_F77 \ + archive_expsym_cmds_F77 \ + postinstall_cmds_F77 \ + postuninstall_cmds_F77 \ + old_archive_from_expsyms_cmds_F77 \ + allow_undefined_flag_F77 \ + no_undefined_flag_F77 \ + export_symbols_cmds_F77 \ + hardcode_libdir_flag_spec_F77 \ + hardcode_libdir_flag_spec_ld_F77 \ + hardcode_libdir_separator_F77 \ + hardcode_automatic_F77 \ + module_cmds_F77 \ + module_expsym_cmds_F77 \ + lt_cv_prog_compiler_c_o_F77 \ + exclude_expsyms_F77 \ + include_expsyms_F77; do + + case $var in + old_archive_cmds_F77 | \ + old_archive_from_new_cmds_F77 | \ + archive_cmds_F77 | \ + archive_expsym_cmds_F77 | \ + module_cmds_F77 | \ + module_expsym_cmds_F77 | \ + old_archive_from_expsyms_cmds_F77 | \ + export_symbols_cmds_F77 | \ + extract_expsyms_cmds | reload_cmds | finish_cmds | \ + postinstall_cmds | postuninstall_cmds | \ + old_postinstall_cmds | old_postuninstall_cmds | \ + sys_lib_search_path_spec | sys_lib_dlsearch_path_spec) + # Double-quote double-evaled strings. + eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$double_quote_subst\" -e \"\$sed_quote_subst\" -e \"\$delay_variable_subst\"\`\\\"" + ;; + *) + eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$sed_quote_subst\"\`\\\"" + ;; + esac + done + + case $lt_echo in + *'\$0 --fallback-echo"') + lt_echo=`$echo "X$lt_echo" | $Xsed -e 's/\\\\\\\$0 --fallback-echo"$/$0 --fallback-echo"/'` + ;; + esac + +cfgfile="$ofile" + + cat <<__EOF__ >> "$cfgfile" +# ### BEGIN LIBTOOL TAG CONFIG: $tagname + +# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`: + +# Shell to use when invoking shell scripts. +SHELL=$lt_SHELL + +# Whether or not to build shared libraries. +build_libtool_libs=$enable_shared + +# Whether or not to build static libraries. +build_old_libs=$enable_static + +# Whether or not to add -lc for building shared libraries. +build_libtool_need_lc=$archive_cmds_need_lc_F77 + +# Whether or not to disallow shared libs when runtime libs are static +allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes_F77 + +# Whether or not to optimize for fast installation. +fast_install=$enable_fast_install + +# The host system. +host_alias=$host_alias +host=$host + +# An echo program that does not interpret backslashes. +echo=$lt_echo + +# The archiver. +AR=$lt_AR +AR_FLAGS=$lt_AR_FLAGS + +# A C compiler. +LTCC=$lt_LTCC + +# A language-specific compiler. +CC=$lt_compiler_F77 + +# Is the compiler the GNU C compiler? +with_gcc=$GCC_F77 + +# An ERE matcher. +EGREP=$lt_EGREP + +# The linker used to build libraries. +LD=$lt_LD_F77 + +# Whether we need hard or soft links. +LN_S=$lt_LN_S + +# A BSD-compatible nm program. +NM=$lt_NM + +# A symbol stripping program +STRIP=$lt_STRIP + +# Used to examine libraries when file_magic_cmd begins "file" +MAGIC_CMD=$MAGIC_CMD + +# Used on cygwin: DLL creation program. +DLLTOOL="$DLLTOOL" + +# Used on cygwin: object dumper. +OBJDUMP="$OBJDUMP" + +# Used on cygwin: assembler. +AS="$AS" + +# The name of the directory that contains temporary libtool files. +objdir=$objdir + +# How to create reloadable object files. +reload_flag=$lt_reload_flag +reload_cmds=$lt_reload_cmds + +# How to pass a linker flag through the compiler. +wl=$lt_lt_prog_compiler_wl_F77 + +# Object file suffix (normally "o"). +objext="$ac_objext" + +# Old archive suffix (normally "a"). +libext="$libext" + +# Shared library suffix (normally ".so"). +shrext_cmds='$shrext_cmds' + +# Executable file suffix (normally ""). +exeext="$exeext" + +# Additional compiler flags for building library objects. +pic_flag=$lt_lt_prog_compiler_pic_F77 +pic_mode=$pic_mode + +# What is the maximum length of a command? +max_cmd_len=$lt_cv_sys_max_cmd_len + +# Does compiler simultaneously support -c and -o options? +compiler_c_o=$lt_lt_cv_prog_compiler_c_o_F77 + +# Must we lock files when doing compilation ? +need_locks=$lt_need_locks + +# Do we need the lib prefix for modules? +need_lib_prefix=$need_lib_prefix + +# Do we need a version for libraries? +need_version=$need_version + +# Whether dlopen is supported. +dlopen_support=$enable_dlopen + +# Whether dlopen of programs is supported. +dlopen_self=$enable_dlopen_self + +# Whether dlopen of statically linked programs is supported. +dlopen_self_static=$enable_dlopen_self_static + +# Compiler flag to prevent dynamic linking. +link_static_flag=$lt_lt_prog_compiler_static_F77 + +# Compiler flag to turn off builtin functions. +no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag_F77 + +# Compiler flag to allow reflexive dlopens. +export_dynamic_flag_spec=$lt_export_dynamic_flag_spec_F77 + +# Compiler flag to generate shared objects directly from archives. +whole_archive_flag_spec=$lt_whole_archive_flag_spec_F77 + +# Compiler flag to generate thread-safe objects. +thread_safe_flag_spec=$lt_thread_safe_flag_spec_F77 + +# Library versioning type. +version_type=$version_type + +# Format of library name prefix. +libname_spec=$lt_libname_spec + +# List of archive names. First name is the real one, the rest are links. +# The last name is the one that the linker finds with -lNAME. +library_names_spec=$lt_library_names_spec + +# The coded name of the library, if different from the real name. +soname_spec=$lt_soname_spec + +# Commands used to build and install an old-style archive. +RANLIB=$lt_RANLIB +old_archive_cmds=$lt_old_archive_cmds_F77 +old_postinstall_cmds=$lt_old_postinstall_cmds +old_postuninstall_cmds=$lt_old_postuninstall_cmds + +# Create an old-style archive from a shared archive. +old_archive_from_new_cmds=$lt_old_archive_from_new_cmds_F77 + +# Create a temporary old-style archive to link instead of a shared archive. +old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds_F77 + +# Commands used to build and install a shared archive. +archive_cmds=$lt_archive_cmds_F77 +archive_expsym_cmds=$lt_archive_expsym_cmds_F77 +postinstall_cmds=$lt_postinstall_cmds +postuninstall_cmds=$lt_postuninstall_cmds + +# Commands used to build a loadable module (assumed same as above if empty) +module_cmds=$lt_module_cmds_F77 +module_expsym_cmds=$lt_module_expsym_cmds_F77 + +# Commands to strip libraries. +old_striplib=$lt_old_striplib +striplib=$lt_striplib + +# Dependencies to place before the objects being linked to create a +# shared library. +predep_objects=$lt_predep_objects_F77 + +# Dependencies to place after the objects being linked to create a +# shared library. +postdep_objects=$lt_postdep_objects_F77 + +# Dependencies to place before the objects being linked to create a +# shared library. +predeps=$lt_predeps_F77 + +# Dependencies to place after the objects being linked to create a +# shared library. +postdeps=$lt_postdeps_F77 + +# The library search path used internally by the compiler when linking +# a shared library. +compiler_lib_search_path=$lt_compiler_lib_search_path_F77 + +# Method to check whether dependent libraries are shared objects. +deplibs_check_method=$lt_deplibs_check_method + +# Command to use when deplibs_check_method == file_magic. +file_magic_cmd=$lt_file_magic_cmd + +# Flag that allows shared libraries with undefined symbols to be built. +allow_undefined_flag=$lt_allow_undefined_flag_F77 + +# Flag that forces no undefined symbols. +no_undefined_flag=$lt_no_undefined_flag_F77 + +# Commands used to finish a libtool library installation in a directory. +finish_cmds=$lt_finish_cmds + +# Same as above, but a single script fragment to be evaled but not shown. +finish_eval=$lt_finish_eval + +# Take the output of nm and produce a listing of raw symbols and C names. +global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe + +# Transform the output of nm in a proper C declaration +global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl + +# Transform the output of nm in a C name address pair +global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address + +# This is the shared library runtime path variable. +runpath_var=$runpath_var + +# This is the shared library path variable. +shlibpath_var=$shlibpath_var + +# Is shlibpath searched before the hard-coded library search path? +shlibpath_overrides_runpath=$shlibpath_overrides_runpath + +# How to hardcode a shared library path into an executable. +hardcode_action=$hardcode_action_F77 + +# Whether we should hardcode library paths into libraries. +hardcode_into_libs=$hardcode_into_libs + +# Flag to hardcode \$libdir into a binary during linking. +# This must work even if \$libdir does not exist. +hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec_F77 + +# If ld is used when linking, flag to hardcode \$libdir into +# a binary during linking. This must work even if \$libdir does +# not exist. +hardcode_libdir_flag_spec_ld=$lt_hardcode_libdir_flag_spec_ld_F77 + +# Whether we need a single -rpath flag with a separated argument. +hardcode_libdir_separator=$lt_hardcode_libdir_separator_F77 + +# Set to yes if using DIR/libNAME${shared_ext} during linking hardcodes DIR into the +# resulting binary. +hardcode_direct=$hardcode_direct_F77 + +# Set to yes if using the -LDIR flag during linking hardcodes DIR into the +# resulting binary. +hardcode_minus_L=$hardcode_minus_L_F77 + +# Set to yes if using SHLIBPATH_VAR=DIR during linking hardcodes DIR into +# the resulting binary. +hardcode_shlibpath_var=$hardcode_shlibpath_var_F77 + +# Set to yes if building a shared library automatically hardcodes DIR into the library +# and all subsequent libraries and executables linked against it. +hardcode_automatic=$hardcode_automatic_F77 + +# Variables whose values should be saved in libtool wrapper scripts and +# restored at relink time. +variables_saved_for_relink="$variables_saved_for_relink" + +# Whether libtool must link a program against all its dependency libraries. +link_all_deplibs=$link_all_deplibs_F77 + +# Compile-time system search path for libraries +sys_lib_search_path_spec=$lt_sys_lib_search_path_spec + +# Run-time system search path for libraries +sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec + +# Fix the shell variable \$srcfile for the compiler. +fix_srcfile_path="$fix_srcfile_path_F77" + +# Set to yes if exported symbols are required. +always_export_symbols=$always_export_symbols_F77 + +# The commands to list exported symbols. +export_symbols_cmds=$lt_export_symbols_cmds_F77 + +# The commands to extract the exported symbol list from a shared archive. +extract_expsyms_cmds=$lt_extract_expsyms_cmds + +# Symbols that should not be listed in the preloaded symbols. +exclude_expsyms=$lt_exclude_expsyms_F77 + +# Symbols that must always be exported. +include_expsyms=$lt_include_expsyms_F77 + +# ### END LIBTOOL TAG CONFIG: $tagname + +__EOF__ + + +else + # If there is no Makefile yet, we rely on a make rule to execute + # `config.status --recheck' to rerun these tests and create the + # libtool script then. + ltmain_in=`echo $ltmain | sed -e 's/\.sh$/.in/'` + if test -f "$ltmain_in"; then + test -f Makefile && make "$ltmain" + fi +fi + + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + +CC="$lt_save_CC" + + else + tagname="" + fi + ;; + + GCJ) + if test -n "$GCJ" && test "X$GCJ" != "Xno"; then + + + +# Source file extension for Java test sources. +ac_ext=java + +# Object file extension for compiled Java test sources. +objext=o +objext_GCJ=$objext + +# Code to be used in simple compile tests +lt_simple_compile_test_code="class foo {}\n" + +# Code to be used in simple link tests +lt_simple_link_test_code='public class conftest { public static void main(String argv) {}; }\n' + +# ltmain only uses $CC for tagged configurations so make sure $CC is set. + +# If no C compiler was specified, use CC. +LTCC=${LTCC-"$CC"} + +# Allow CC to be a program name with arguments. +compiler=$CC + + +# Allow CC to be a program name with arguments. +lt_save_CC="$CC" +CC=${GCJ-"gcj"} +compiler=$CC +compiler_GCJ=$CC + +# GCJ did not exist at the time GCC didn't implicitly link libc in. +archive_cmds_need_lc_GCJ=no + + +lt_prog_compiler_no_builtin_flag_GCJ= + +if test "$GCC" = yes; then + lt_prog_compiler_no_builtin_flag_GCJ=' -fno-builtin' + + +echo "$as_me:$LINENO: checking if $compiler supports -fno-rtti -fno-exceptions" >&5 +echo $ECHO_N "checking if $compiler supports -fno-rtti -fno-exceptions... $ECHO_C" >&6 +if test "${lt_cv_prog_compiler_rtti_exceptions+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + lt_cv_prog_compiler_rtti_exceptions=no + ac_outfile=conftest.$ac_objext + printf "$lt_simple_compile_test_code" > conftest.$ac_ext + lt_compiler_flag="-fno-rtti -fno-exceptions" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + # The option is referenced via a variable to avoid confusing sed. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}? :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:15475: $lt_compile\"" >&5) + (eval "$lt_compile" 2>conftest.err) + ac_status=$? + cat conftest.err >&5 + echo "$as_me:15479: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s "$ac_outfile"; then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings + if test ! -s conftest.err; then + lt_cv_prog_compiler_rtti_exceptions=yes + fi + fi + $rm conftest* + +fi +echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_rtti_exceptions" >&5 +echo "${ECHO_T}$lt_cv_prog_compiler_rtti_exceptions" >&6 + +if test x"$lt_cv_prog_compiler_rtti_exceptions" = xyes; then + lt_prog_compiler_no_builtin_flag_GCJ="$lt_prog_compiler_no_builtin_flag_GCJ -fno-rtti -fno-exceptions" +else + : +fi + +fi + +lt_prog_compiler_wl_GCJ= +lt_prog_compiler_pic_GCJ= +lt_prog_compiler_static_GCJ= + +echo "$as_me:$LINENO: checking for $compiler option to produce PIC" >&5 +echo $ECHO_N "checking for $compiler option to produce PIC... $ECHO_C" >&6 + + if test "$GCC" = yes; then + lt_prog_compiler_wl_GCJ='-Wl,' + lt_prog_compiler_static_GCJ='-static' + + case $host_os in + aix*) + # All AIX code is PIC. + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + lt_prog_compiler_static_GCJ='-Bstatic' + fi + ;; + + amigaos*) + # FIXME: we need at least 68020 code to build shared libraries, but + # adding the `-m68020' flag to GCC prevents building anything better, + # like `-m68040'. + lt_prog_compiler_pic_GCJ='-m68020 -resident32 -malways-restore-a4' + ;; + + beos* | cygwin* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) + # PIC is the default for these OSes. + ;; + + mingw* | pw32* | os2*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + lt_prog_compiler_pic_GCJ='-DDLL_EXPORT' + ;; + + darwin* | rhapsody*) + # PIC is the default on this platform + # Common symbols not allowed in MH_DYLIB files + lt_prog_compiler_pic_GCJ='-fno-common' + ;; + + msdosdjgpp*) + # Just because we use GCC doesn't mean we suddenly get shared libraries + # on systems that don't support them. + lt_prog_compiler_can_build_shared_GCJ=no + enable_shared=no + ;; + + sysv4*MP*) + if test -d /usr/nec; then + lt_prog_compiler_pic_GCJ=-Kconform_pic + fi + ;; + + hpux*) + # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but + # not for PA HP-UX. + case "$host_cpu" in + hppa*64*|ia64*) + # +Z the default + ;; + *) + lt_prog_compiler_pic_GCJ='-fPIC' + ;; + esac + ;; + + *) + lt_prog_compiler_pic_GCJ='-fPIC' + ;; + esac + else + # PORTME Check for flag to pass linker flags through the system compiler. + case $host_os in + aix*) + lt_prog_compiler_wl_GCJ='-Wl,' + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + lt_prog_compiler_static_GCJ='-Bstatic' + else + lt_prog_compiler_static_GCJ='-bnso -bI:/lib/syscalls.exp' + fi + ;; + + mingw* | pw32* | os2*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + lt_prog_compiler_pic_GCJ='-DDLL_EXPORT' + ;; + + hpux9* | hpux10* | hpux11*) + lt_prog_compiler_wl_GCJ='-Wl,' + # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but + # not for PA HP-UX. + case "$host_cpu" in + hppa*64*|ia64*) + # +Z the default + ;; + *) + lt_prog_compiler_pic_GCJ='+Z' + ;; + esac + # Is there a better lt_prog_compiler_static that works with the bundled CC? + lt_prog_compiler_static_GCJ='${wl}-a ${wl}archive' + ;; + + irix5* | irix6* | nonstopux*) + lt_prog_compiler_wl_GCJ='-Wl,' + # PIC (with -KPIC) is the default. + lt_prog_compiler_static_GCJ='-non_shared' + ;; + + newsos6) + lt_prog_compiler_pic_GCJ='-KPIC' + lt_prog_compiler_static_GCJ='-Bstatic' + ;; + + linux*) + case $CC in + icc* | ecc*) + lt_prog_compiler_wl_GCJ='-Wl,' + lt_prog_compiler_pic_GCJ='-KPIC' + lt_prog_compiler_static_GCJ='-static' + ;; + ccc*) + lt_prog_compiler_wl_GCJ='-Wl,' + # All Alpha code is PIC. + lt_prog_compiler_static_GCJ='-non_shared' + ;; + esac + ;; + + osf3* | osf4* | osf5*) + lt_prog_compiler_wl_GCJ='-Wl,' + # All OSF/1 code is PIC. + lt_prog_compiler_static_GCJ='-non_shared' + ;; + + sco3.2v5*) + lt_prog_compiler_pic_GCJ='-Kpic' + lt_prog_compiler_static_GCJ='-dn' + ;; + + solaris*) + lt_prog_compiler_wl_GCJ='-Wl,' + lt_prog_compiler_pic_GCJ='-KPIC' + lt_prog_compiler_static_GCJ='-Bstatic' + ;; + + sunos4*) + lt_prog_compiler_wl_GCJ='-Qoption ld ' + lt_prog_compiler_pic_GCJ='-PIC' + lt_prog_compiler_static_GCJ='-Bstatic' + ;; + + sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*) + lt_prog_compiler_wl_GCJ='-Wl,' + lt_prog_compiler_pic_GCJ='-KPIC' + lt_prog_compiler_static_GCJ='-Bstatic' + ;; + + sysv4*MP*) + if test -d /usr/nec ;then + lt_prog_compiler_pic_GCJ='-Kconform_pic' + lt_prog_compiler_static_GCJ='-Bstatic' + fi + ;; + + uts4*) + lt_prog_compiler_pic_GCJ='-pic' + lt_prog_compiler_static_GCJ='-Bstatic' + ;; + + *) + lt_prog_compiler_can_build_shared_GCJ=no + ;; + esac + fi + +echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_GCJ" >&5 +echo "${ECHO_T}$lt_prog_compiler_pic_GCJ" >&6 + +# +# Check to make sure the PIC flag actually works. +# +if test -n "$lt_prog_compiler_pic_GCJ"; then + +echo "$as_me:$LINENO: checking if $compiler PIC flag $lt_prog_compiler_pic_GCJ works" >&5 +echo $ECHO_N "checking if $compiler PIC flag $lt_prog_compiler_pic_GCJ works... $ECHO_C" >&6 +if test "${lt_prog_compiler_pic_works_GCJ+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + lt_prog_compiler_pic_works_GCJ=no + ac_outfile=conftest.$ac_objext + printf "$lt_simple_compile_test_code" > conftest.$ac_ext + lt_compiler_flag="$lt_prog_compiler_pic_GCJ" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + # The option is referenced via a variable to avoid confusing sed. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}? :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:15708: $lt_compile\"" >&5) + (eval "$lt_compile" 2>conftest.err) + ac_status=$? + cat conftest.err >&5 + echo "$as_me:15712: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s "$ac_outfile"; then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings + if test ! -s conftest.err; then + lt_prog_compiler_pic_works_GCJ=yes + fi + fi + $rm conftest* + +fi +echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_works_GCJ" >&5 +echo "${ECHO_T}$lt_prog_compiler_pic_works_GCJ" >&6 + +if test x"$lt_prog_compiler_pic_works_GCJ" = xyes; then + case $lt_prog_compiler_pic_GCJ in + "" | " "*) ;; + *) lt_prog_compiler_pic_GCJ=" $lt_prog_compiler_pic_GCJ" ;; + esac +else + lt_prog_compiler_pic_GCJ= + lt_prog_compiler_can_build_shared_GCJ=no +fi + +fi +case "$host_os" in + # For platforms which do not support PIC, -DPIC is meaningless: + *djgpp*) + lt_prog_compiler_pic_GCJ= + ;; + *) + lt_prog_compiler_pic_GCJ="$lt_prog_compiler_pic_GCJ" + ;; +esac + +echo "$as_me:$LINENO: checking if $compiler supports -c -o file.$ac_objext" >&5 +echo $ECHO_N "checking if $compiler supports -c -o file.$ac_objext... $ECHO_C" >&6 +if test "${lt_cv_prog_compiler_c_o_GCJ+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + lt_cv_prog_compiler_c_o_GCJ=no + $rm -r conftest 2>/dev/null + mkdir conftest + cd conftest + mkdir out + printf "$lt_simple_compile_test_code" > conftest.$ac_ext + + lt_compiler_flag="-o out/conftest2.$ac_objext" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}? :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:15768: $lt_compile\"" >&5) + (eval "$lt_compile" 2>out/conftest.err) + ac_status=$? + cat out/conftest.err >&5 + echo "$as_me:15772: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s out/conftest2.$ac_objext + then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings + if test ! -s out/conftest.err; then + lt_cv_prog_compiler_c_o_GCJ=yes + fi + fi + chmod u+w . + $rm conftest* + # SGI C++ compiler will create directory out/ii_files/ for + # template instantiation + test -d out/ii_files && $rm out/ii_files/* && rmdir out/ii_files + $rm out/* && rmdir out + cd .. + rmdir conftest + $rm conftest* + +fi +echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_c_o_GCJ" >&5 +echo "${ECHO_T}$lt_cv_prog_compiler_c_o_GCJ" >&6 + + +hard_links="nottested" +if test "$lt_cv_prog_compiler_c_o_GCJ" = no && test "$need_locks" != no; then + # do not overwrite the value of need_locks provided by the user + echo "$as_me:$LINENO: checking if we can lock with hard links" >&5 +echo $ECHO_N "checking if we can lock with hard links... $ECHO_C" >&6 + hard_links=yes + $rm conftest* + ln conftest.a conftest.b 2>/dev/null && hard_links=no + touch conftest.a + ln conftest.a conftest.b 2>&5 || hard_links=no + ln conftest.a conftest.b 2>/dev/null && hard_links=no + echo "$as_me:$LINENO: result: $hard_links" >&5 +echo "${ECHO_T}$hard_links" >&6 + if test "$hard_links" = no; then + { echo "$as_me:$LINENO: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5 +echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;} + need_locks=warn + fi +else + need_locks=no +fi + +echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) supports shared libraries" >&5 +echo $ECHO_N "checking whether the $compiler linker ($LD) supports shared libraries... $ECHO_C" >&6 + + runpath_var= + allow_undefined_flag_GCJ= + enable_shared_with_static_runtimes_GCJ=no + archive_cmds_GCJ= + archive_expsym_cmds_GCJ= + old_archive_From_new_cmds_GCJ= + old_archive_from_expsyms_cmds_GCJ= + export_dynamic_flag_spec_GCJ= + whole_archive_flag_spec_GCJ= + thread_safe_flag_spec_GCJ= + hardcode_libdir_flag_spec_GCJ= + hardcode_libdir_flag_spec_ld_GCJ= + hardcode_libdir_separator_GCJ= + hardcode_direct_GCJ=no + hardcode_minus_L_GCJ=no + hardcode_shlibpath_var_GCJ=unsupported + link_all_deplibs_GCJ=unknown + hardcode_automatic_GCJ=no + module_cmds_GCJ= + module_expsym_cmds_GCJ= + always_export_symbols_GCJ=no + export_symbols_cmds_GCJ='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' + # include_expsyms should be a list of space-separated symbols to be *always* + # included in the symbol list + include_expsyms_GCJ= + # exclude_expsyms can be an extended regexp of symbols to exclude + # it will be wrapped by ` (' and `)$', so one must not match beginning or + # end of line. Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc', + # as well as any symbol that contains `d'. + exclude_expsyms_GCJ="_GLOBAL_OFFSET_TABLE_" + # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out + # platforms (ab)use it in PIC code, but their linkers get confused if + # the symbol is explicitly referenced. Since portable code cannot + # rely on this symbol name, it's probably fine to never include it in + # preloaded symbol tables. + extract_expsyms_cmds= + + case $host_os in + cygwin* | mingw* | pw32*) + # FIXME: the MSVC++ port hasn't been tested in a loooong time + # When not using gcc, we currently assume that we are using + # Microsoft Visual C++. + if test "$GCC" != yes; then + with_gnu_ld=no + fi + ;; + openbsd*) + with_gnu_ld=no + ;; + esac + + ld_shlibs_GCJ=yes + if test "$with_gnu_ld" = yes; then + # If archive_cmds runs LD, not CC, wlarc should be empty + wlarc='${wl}' + + # See if GNU ld supports shared libraries. + case $host_os in + aix3* | aix4* | aix5*) + # On AIX/PPC, the GNU linker is very broken + if test "$host_cpu" != ia64; then + ld_shlibs_GCJ=no + cat <&2 + +*** Warning: the GNU linker, at least up to release 2.9.1, is reported +*** to be unable to reliably create shared libraries on AIX. +*** Therefore, libtool is disabling shared libraries support. If you +*** really care for shared libraries, you may want to modify your PATH +*** so that a non-GNU linker is found, and then restart. + +EOF + fi + ;; + + amigaos*) + archive_cmds_GCJ='$rm $output_objdir/a2ixlibrary.data~$echo "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' + hardcode_libdir_flag_spec_GCJ='-L$libdir' + hardcode_minus_L_GCJ=yes + + # Samuel A. Falvo II reports + # that the semantics of dynamic libraries on AmigaOS, at least up + # to version 4, is to share data among multiple programs linked + # with the same dynamic library. Since this doesn't match the + # behavior of shared libraries on other platforms, we can't use + # them. + ld_shlibs_GCJ=no + ;; + + beos*) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + allow_undefined_flag_GCJ=unsupported + # Joseph Beckenbach says some releases of gcc + # support --undefined. This deserves some investigation. FIXME + archive_cmds_GCJ='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + else + ld_shlibs_GCJ=no + fi + ;; + + cygwin* | mingw* | pw32*) + # _LT_AC_TAGVAR(hardcode_libdir_flag_spec, GCJ) is actually meaningless, + # as there is no search path for DLLs. + hardcode_libdir_flag_spec_GCJ='-L$libdir' + allow_undefined_flag_GCJ=unsupported + always_export_symbols_GCJ=no + enable_shared_with_static_runtimes_GCJ=yes + export_symbols_cmds_GCJ='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGS] /s/.* \([^ ]*\)/\1 DATA/'\'' | $SED -e '\''/^[AITW] /s/.* //'\'' | sort | uniq > $export_symbols' + + if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then + archive_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--image-base=0x10000000 ${wl}--out-implib,$lib' + # If the export-symbols file already is a .def file (1st line + # is EXPORTS), use it as is; otherwise, prepend... + archive_expsym_cmds_GCJ='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then + cp $export_symbols $output_objdir/$soname.def; + else + echo EXPORTS > $output_objdir/$soname.def; + cat $export_symbols >> $output_objdir/$soname.def; + fi~ + $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--image-base=0x10000000 ${wl}--out-implib,$lib' + else + ld_shlibs=no + fi + ;; + + netbsd* | netbsdelf*-gnu | knetbsd*-gnu) + if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then + archive_cmds_GCJ='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib' + wlarc= + else + archive_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + fi + ;; + + solaris* | sysv5*) + if $LD -v 2>&1 | grep 'BFD 2\.8' > /dev/null; then + ld_shlibs_GCJ=no + cat <&2 + +*** Warning: The releases 2.8.* of the GNU linker cannot reliably +*** create shared libraries on Solaris systems. Therefore, libtool +*** is disabling shared libraries support. We urge you to upgrade GNU +*** binutils to release 2.9.1 or newer. Another option is to modify +*** your PATH or compiler configuration so that the native linker is +*** used, and then restart. + +EOF + elif $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + archive_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + else + ld_shlibs_GCJ=no + fi + ;; + + sunos4*) + archive_cmds_GCJ='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags' + wlarc= + hardcode_direct_GCJ=yes + hardcode_shlibpath_var_GCJ=no + ;; + + linux*) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + tmp_archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_cmds_GCJ="$tmp_archive_cmds" + supports_anon_versioning=no + case `$LD -v 2>/dev/null` in + *\ 01.* | *\ 2.[0-9].* | *\ 2.10.*) ;; # catch versions < 2.11 + *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ... + *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ... + *\ 2.11.*) ;; # other 2.11 versions + *) supports_anon_versioning=yes ;; + esac + if test $supports_anon_versioning = yes; then + archive_expsym_cmds_GCJ='$echo "{ global:" > $output_objdir/$libname.ver~ +cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ +$echo "local: *; };" >> $output_objdir/$libname.ver~ + $CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib' + else + archive_expsym_cmds_GCJ="$tmp_archive_cmds" + fi + link_all_deplibs_GCJ=no + else + ld_shlibs_GCJ=no + fi + ;; + + *) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + archive_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + else + ld_shlibs_GCJ=no + fi + ;; + esac + + if test "$ld_shlibs_GCJ" = yes; then + runpath_var=LD_RUN_PATH + hardcode_libdir_flag_spec_GCJ='${wl}--rpath ${wl}$libdir' + export_dynamic_flag_spec_GCJ='${wl}--export-dynamic' + # ancient GNU ld didn't support --whole-archive et. al. + if $LD --help 2>&1 | grep 'no-whole-archive' > /dev/null; then + whole_archive_flag_spec_GCJ="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' + else + whole_archive_flag_spec_GCJ= + fi + fi + else + # PORTME fill in a description of your system's linker (not GNU ld) + case $host_os in + aix3*) + allow_undefined_flag_GCJ=unsupported + always_export_symbols_GCJ=yes + archive_expsym_cmds_GCJ='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname' + # Note: this linker hardcodes the directories in LIBPATH if there + # are no directories specified by -L. + hardcode_minus_L_GCJ=yes + if test "$GCC" = yes && test -z "$link_static_flag"; then + # Neither direct hardcoding nor static linking is supported with a + # broken collect2. + hardcode_direct_GCJ=unsupported + fi + ;; + + aix4* | aix5*) + if test "$host_cpu" = ia64; then + # On IA64, the linker does run time linking by default, so we don't + # have to do anything special. + aix_use_runtimelinking=no + exp_sym_flag='-Bexport' + no_entry_flag="" + else + # If we're using GNU nm, then we don't want the "-C" option. + # -C means demangle to AIX nm, but means don't demangle with GNU nm + if $NM -V 2>&1 | grep 'GNU' > /dev/null; then + export_symbols_cmds_GCJ='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$2 == "T") || (\$2 == "D") || (\$2 == "B")) && (substr(\$3,1,1) != ".")) { print \$3 } }'\'' | sort -u > $export_symbols' + else + export_symbols_cmds_GCJ='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$2 == "T") || (\$2 == "D") || (\$2 == "B")) && (substr(\$3,1,1) != ".")) { print \$3 } }'\'' | sort -u > $export_symbols' + fi + aix_use_runtimelinking=no + + # Test if we are trying to use run time linking or normal + # AIX style linking. If -brtl is somewhere in LDFLAGS, we + # need to do runtime linking. + case $host_os in aix4.[23]|aix4.[23].*|aix5*) + for ld_flag in $LDFLAGS; do + if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then + aix_use_runtimelinking=yes + break + fi + done + esac + + exp_sym_flag='-bexport' + no_entry_flag='-bnoentry' + fi + + # When large executables or shared objects are built, AIX ld can + # have problems creating the table of contents. If linking a library + # or program results in "error TOC overflow" add -mminimal-toc to + # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not + # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. + + archive_cmds_GCJ='' + hardcode_direct_GCJ=yes + hardcode_libdir_separator_GCJ=':' + link_all_deplibs_GCJ=yes + + if test "$GCC" = yes; then + case $host_os in aix4.012|aix4.012.*) + # We only want to do this on AIX 4.2 and lower, the check + # below for broken collect2 doesn't work under 4.3+ + collect2name=`${CC} -print-prog-name=collect2` + if test -f "$collect2name" && \ + strings "$collect2name" | grep resolve_lib_name >/dev/null + then + # We have reworked collect2 + hardcode_direct_GCJ=yes + else + # We have old collect2 + hardcode_direct_GCJ=unsupported + # It fails to find uninstalled libraries when the uninstalled + # path is not listed in the libpath. Setting hardcode_minus_L + # to unsupported forces relinking + hardcode_minus_L_GCJ=yes + hardcode_libdir_flag_spec_GCJ='-L$libdir' + hardcode_libdir_separator_GCJ= + fi + esac + shared_flag='-shared' + else + # not using gcc + if test "$host_cpu" = ia64; then + # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release + # chokes on -Wl,-G. The following line is correct: + shared_flag='-G' + else + if test "$aix_use_runtimelinking" = yes; then + shared_flag='${wl}-G' + else + shared_flag='${wl}-bM:SRE' + fi + fi + fi + + # It seems that -bexpall does not export symbols beginning with + # underscore (_), so it is better to generate a list of symbols to export. + always_export_symbols_GCJ=yes + if test "$aix_use_runtimelinking" = yes; then + # Warning - without using the other runtime loading flags (-brtl), + # -berok will link without error, but may produce a broken library. + allow_undefined_flag_GCJ='-berok' + # Determine the default libpath from the value encoded in an empty executable. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + +aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; } +}'` +# Check for a 64-bit object if we didn't find anything. +if test -z "$aix_libpath"; then aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; } +}'`; fi +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +fi +rm -f conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi + + hardcode_libdir_flag_spec_GCJ='${wl}-blibpath:$libdir:'"$aix_libpath" + archive_expsym_cmds_GCJ="\$CC"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$no_entry_flag \${wl}$exp_sym_flag:\$export_symbols $shared_flag" + else + if test "$host_cpu" = ia64; then + hardcode_libdir_flag_spec_GCJ='${wl}-R $libdir:/usr/lib:/lib' + allow_undefined_flag_GCJ="-z nodefs" + archive_expsym_cmds_GCJ="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$no_entry_flag \${wl}$exp_sym_flag:\$export_symbols" + else + # Determine the default libpath from the value encoded in an empty executable. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + +aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; } +}'` +# Check for a 64-bit object if we didn't find anything. +if test -z "$aix_libpath"; then aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; } +}'`; fi +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +fi +rm -f conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi + + hardcode_libdir_flag_spec_GCJ='${wl}-blibpath:$libdir:'"$aix_libpath" + # Warning - without using the other run time loading flags, + # -berok will link without error, but may produce a broken library. + no_undefined_flag_GCJ=' ${wl}-bernotok' + allow_undefined_flag_GCJ=' ${wl}-berok' + # -bexpall does not export symbols beginning with underscore (_) + always_export_symbols_GCJ=yes + # Exported symbols can be pulled into shared objects from archives + whole_archive_flag_spec_GCJ=' ' + archive_cmds_need_lc_GCJ=yes + # This is similar to how AIX traditionally builds it's shared libraries. + archive_expsym_cmds_GCJ="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags ${wl}-bE:$export_symbols ${wl}-bnoentry${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' + fi + fi + ;; + + amigaos*) + archive_cmds_GCJ='$rm $output_objdir/a2ixlibrary.data~$echo "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' + hardcode_libdir_flag_spec_GCJ='-L$libdir' + hardcode_minus_L_GCJ=yes + # see comment about different semantics on the GNU ld section + ld_shlibs_GCJ=no + ;; + + bsdi4*) + export_dynamic_flag_spec_GCJ=-rdynamic + ;; + + cygwin* | mingw* | pw32*) + # When not using gcc, we currently assume that we are using + # Microsoft Visual C++. + # hardcode_libdir_flag_spec is actually meaningless, as there is + # no search path for DLLs. + hardcode_libdir_flag_spec_GCJ=' ' + allow_undefined_flag_GCJ=unsupported + # Tell ltmain to make .lib files, not .a files. + libext=lib + # Tell ltmain to make .dll files, not .so files. + shrext_cmds=".dll" + # FIXME: Setting linknames here is a bad hack. + archive_cmds_GCJ='$CC -o $lib $libobjs $compiler_flags `echo "$deplibs" | $SED -e '\''s/ -lc$//'\''` -link -dll~linknames=' + # The linker will automatically build a .lib file if we build a DLL. + old_archive_From_new_cmds_GCJ='true' + # FIXME: Should let the user specify the lib program. + old_archive_cmds_GCJ='lib /OUT:$oldlib$oldobjs$old_deplibs' + fix_srcfile_path='`cygpath -w "$srcfile"`' + enable_shared_with_static_runtimes_GCJ=yes + ;; + + darwin* | rhapsody*) + if test "$GXX" = yes ; then + archive_cmds_need_lc_GCJ=no + case "$host_os" in + rhapsody* | darwin1.[012]) + allow_undefined_flag_GCJ='-undefined suppress' + ;; + *) # Darwin 1.3 on + if test -z ${MACOSX_DEPLOYMENT_TARGET} ; then + allow_undefined_flag_GCJ='-flat_namespace -undefined suppress' + else + case ${MACOSX_DEPLOYMENT_TARGET} in + 10.[012]) + allow_undefined_flag_GCJ='-flat_namespace -undefined suppress' + ;; + 10.*) + allow_undefined_flag_GCJ='-undefined dynamic_lookup' + ;; + esac + fi + ;; + esac + lt_int_apple_cc_single_mod=no + output_verbose_link_cmd='echo' + if $CC -dumpspecs 2>&1 | grep 'single_module' >/dev/null ; then + lt_int_apple_cc_single_mod=yes + fi + if test "X$lt_int_apple_cc_single_mod" = Xyes ; then + archive_cmds_GCJ='$CC -dynamiclib -single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring' + else + archive_cmds_GCJ='$CC -r ${wl}-bind_at_load -keep_private_externs -nostdlib -o ${lib}-master.o $libobjs~$CC -dynamiclib $allow_undefined_flag -o $lib ${lib}-master.o $deplibs $compiler_flags -install_name $rpath/$soname $verstring' + fi + module_cmds_GCJ='$CC ${wl}-bind_at_load $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags' + # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin ld's + if test "X$lt_int_apple_cc_single_mod" = Xyes ; then + archive_expsym_cmds_GCJ='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -dynamiclib -single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + else + archive_expsym_cmds_GCJ='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -r ${wl}-bind_at_load -keep_private_externs -nostdlib -o ${lib}-master.o $libobjs~$CC -dynamiclib $allow_undefined_flag -o $lib ${lib}-master.o $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + fi + module_expsym_cmds_GCJ='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}' + hardcode_direct_GCJ=no + hardcode_automatic_GCJ=yes + hardcode_shlibpath_var_GCJ=unsupported + whole_archive_flag_spec_GCJ='-all_load $convenience' + link_all_deplibs_GCJ=yes + else + ld_shlibs_GCJ=no + fi + ;; + + dgux*) + archive_cmds_GCJ='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_libdir_flag_spec_GCJ='-L$libdir' + hardcode_shlibpath_var_GCJ=no + ;; + + freebsd1*) + ld_shlibs_GCJ=no + ;; + + # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor + # support. Future versions do this automatically, but an explicit c++rt0.o + # does not break anything, and helps significantly (at the cost of a little + # extra space). + freebsd2.2*) + archive_cmds_GCJ='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o' + hardcode_libdir_flag_spec_GCJ='-R$libdir' + hardcode_direct_GCJ=yes + hardcode_shlibpath_var_GCJ=no + ;; + + # Unfortunately, older versions of FreeBSD 2 do not have this feature. + freebsd2*) + archive_cmds_GCJ='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct_GCJ=yes + hardcode_minus_L_GCJ=yes + hardcode_shlibpath_var_GCJ=no + ;; + + # FreeBSD 3 and greater uses gcc -shared to do shared libraries. + freebsd* | kfreebsd*-gnu) + archive_cmds_GCJ='$CC -shared -o $lib $libobjs $deplibs $compiler_flags' + hardcode_libdir_flag_spec_GCJ='-R$libdir' + hardcode_direct_GCJ=yes + hardcode_shlibpath_var_GCJ=no + ;; + + hpux9*) + if test "$GCC" = yes; then + archive_cmds_GCJ='$rm $output_objdir/$soname~$CC -shared -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + else + archive_cmds_GCJ='$rm $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + fi + hardcode_libdir_flag_spec_GCJ='${wl}+b ${wl}$libdir' + hardcode_libdir_separator_GCJ=: + hardcode_direct_GCJ=yes + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + hardcode_minus_L_GCJ=yes + export_dynamic_flag_spec_GCJ='${wl}-E' + ;; + + hpux10* | hpux11*) + if test "$GCC" = yes -a "$with_gnu_ld" = no; then + case "$host_cpu" in + hppa*64*|ia64*) + archive_cmds_GCJ='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + *) + archive_cmds_GCJ='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' + ;; + esac + else + case "$host_cpu" in + hppa*64*|ia64*) + archive_cmds_GCJ='$LD -b +h $soname -o $lib $libobjs $deplibs $linker_flags' + ;; + *) + archive_cmds_GCJ='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' + ;; + esac + fi + if test "$with_gnu_ld" = no; then + case "$host_cpu" in + hppa*64*) + hardcode_libdir_flag_spec_GCJ='${wl}+b ${wl}$libdir' + hardcode_libdir_flag_spec_ld_GCJ='+b $libdir' + hardcode_libdir_separator_GCJ=: + hardcode_direct_GCJ=no + hardcode_shlibpath_var_GCJ=no + ;; + ia64*) + hardcode_libdir_flag_spec_GCJ='-L$libdir' + hardcode_direct_GCJ=no + hardcode_shlibpath_var_GCJ=no + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + hardcode_minus_L_GCJ=yes + ;; + *) + hardcode_libdir_flag_spec_GCJ='${wl}+b ${wl}$libdir' + hardcode_libdir_separator_GCJ=: + hardcode_direct_GCJ=yes + export_dynamic_flag_spec_GCJ='${wl}-E' + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + hardcode_minus_L_GCJ=yes + ;; + esac + fi + ;; + + irix5* | irix6* | nonstopux*) + if test "$GCC" = yes; then + archive_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + else + archive_cmds_GCJ='$LD -shared $libobjs $deplibs $linker_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib' + hardcode_libdir_flag_spec_ld_GCJ='-rpath $libdir' + fi + hardcode_libdir_flag_spec_GCJ='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator_GCJ=: + link_all_deplibs_GCJ=yes + ;; + + netbsd* | netbsdelf*-gnu | knetbsd*-gnu) + if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then + archive_cmds_GCJ='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out + else + archive_cmds_GCJ='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF + fi + hardcode_libdir_flag_spec_GCJ='-R$libdir' + hardcode_direct_GCJ=yes + hardcode_shlibpath_var_GCJ=no + ;; + + newsos6) + archive_cmds_GCJ='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct_GCJ=yes + hardcode_libdir_flag_spec_GCJ='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator_GCJ=: + hardcode_shlibpath_var_GCJ=no + ;; + + openbsd*) + hardcode_direct_GCJ=yes + hardcode_shlibpath_var_GCJ=no + if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + archive_cmds_GCJ='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' + hardcode_libdir_flag_spec_GCJ='${wl}-rpath,$libdir' + export_dynamic_flag_spec_GCJ='${wl}-E' + else + case $host_os in + openbsd[01].* | openbsd2.[0-7] | openbsd2.[0-7].*) + archive_cmds_GCJ='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' + hardcode_libdir_flag_spec_GCJ='-R$libdir' + ;; + *) + archive_cmds_GCJ='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' + hardcode_libdir_flag_spec_GCJ='${wl}-rpath,$libdir' + ;; + esac + fi + ;; + + os2*) + hardcode_libdir_flag_spec_GCJ='-L$libdir' + hardcode_minus_L_GCJ=yes + allow_undefined_flag_GCJ=unsupported + archive_cmds_GCJ='$echo "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$echo "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~$echo DATA >> $output_objdir/$libname.def~$echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~$echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def' + old_archive_From_new_cmds_GCJ='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def' + ;; + + osf3*) + if test "$GCC" = yes; then + allow_undefined_flag_GCJ=' ${wl}-expect_unresolved ${wl}\*' + archive_cmds_GCJ='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + else + allow_undefined_flag_GCJ=' -expect_unresolved \*' + archive_cmds_GCJ='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib' + fi + hardcode_libdir_flag_spec_GCJ='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator_GCJ=: + ;; + + osf4* | osf5*) # as osf3* with the addition of -msym flag + if test "$GCC" = yes; then + allow_undefined_flag_GCJ=' ${wl}-expect_unresolved ${wl}\*' + archive_cmds_GCJ='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + hardcode_libdir_flag_spec_GCJ='${wl}-rpath ${wl}$libdir' + else + allow_undefined_flag_GCJ=' -expect_unresolved \*' + archive_cmds_GCJ='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -msym -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib' + archive_expsym_cmds_GCJ='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; echo "-hidden">> $lib.exp~ + $LD -shared${allow_undefined_flag} -input $lib.exp $linker_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${objdir}/so_locations -o $lib~$rm $lib.exp' + + # Both c and cxx compiler support -rpath directly + hardcode_libdir_flag_spec_GCJ='-rpath $libdir' + fi + hardcode_libdir_separator_GCJ=: + ;; + + sco3.2v5*) + archive_cmds_GCJ='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_shlibpath_var_GCJ=no + export_dynamic_flag_spec_GCJ='${wl}-Bexport' + runpath_var=LD_RUN_PATH + hardcode_runpath_var=yes + ;; + + solaris*) + no_undefined_flag_GCJ=' -z text' + if test "$GCC" = yes; then + archive_cmds_GCJ='$CC -shared ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds_GCJ='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~ + $CC -shared ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$rm $lib.exp' + else + archive_cmds_GCJ='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags' + archive_expsym_cmds_GCJ='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~ + $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$rm $lib.exp' + fi + hardcode_libdir_flag_spec_GCJ='-R$libdir' + hardcode_shlibpath_var_GCJ=no + case $host_os in + solaris2.[0-5] | solaris2.[0-5].*) ;; + *) # Supported since Solaris 2.6 (maybe 2.5.1?) + whole_archive_flag_spec_GCJ='-z allextract$convenience -z defaultextract' ;; + esac + link_all_deplibs_GCJ=yes + ;; + + sunos4*) + if test "x$host_vendor" = xsequent; then + # Use $CC to link under sequent, because it throws in some extra .o + # files that make .init and .fini sections work. + archive_cmds_GCJ='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags' + else + archive_cmds_GCJ='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags' + fi + hardcode_libdir_flag_spec_GCJ='-L$libdir' + hardcode_direct_GCJ=yes + hardcode_minus_L_GCJ=yes + hardcode_shlibpath_var_GCJ=no + ;; + + sysv4) + case $host_vendor in + sni) + archive_cmds_GCJ='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct_GCJ=yes # is this really true??? + ;; + siemens) + ## LD is ld it makes a PLAMLIB + ## CC just makes a GrossModule. + archive_cmds_GCJ='$LD -G -o $lib $libobjs $deplibs $linker_flags' + reload_cmds_GCJ='$CC -r -o $output$reload_objs' + hardcode_direct_GCJ=no + ;; + motorola) + archive_cmds_GCJ='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct_GCJ=no #Motorola manual says yes, but my tests say they lie + ;; + esac + runpath_var='LD_RUN_PATH' + hardcode_shlibpath_var_GCJ=no + ;; + + sysv4.3*) + archive_cmds_GCJ='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_shlibpath_var_GCJ=no + export_dynamic_flag_spec_GCJ='-Bexport' + ;; + + sysv4*MP*) + if test -d /usr/nec; then + archive_cmds_GCJ='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_shlibpath_var_GCJ=no + runpath_var=LD_RUN_PATH + hardcode_runpath_var=yes + ld_shlibs_GCJ=yes + fi + ;; + + sysv4.2uw2*) + archive_cmds_GCJ='$LD -G -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct_GCJ=yes + hardcode_minus_L_GCJ=no + hardcode_shlibpath_var_GCJ=no + hardcode_runpath_var=yes + runpath_var=LD_RUN_PATH + ;; + + sysv5OpenUNIX8* | sysv5UnixWare7* | sysv5uw[78]* | unixware7*) + no_undefined_flag_GCJ='${wl}-z ${wl}text' + if test "$GCC" = yes; then + archive_cmds_GCJ='$CC -shared ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + else + archive_cmds_GCJ='$CC -G ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + fi + runpath_var='LD_RUN_PATH' + hardcode_shlibpath_var_GCJ=no + ;; + + sysv5*) + no_undefined_flag_GCJ=' -z text' + # $CC -shared without GNU ld will not create a library from C++ + # object files and a static libstdc++, better avoid it by now + archive_cmds_GCJ='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags' + archive_expsym_cmds_GCJ='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~ + $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$rm $lib.exp' + hardcode_libdir_flag_spec_GCJ= + hardcode_shlibpath_var_GCJ=no + runpath_var='LD_RUN_PATH' + ;; + + uts4*) + archive_cmds_GCJ='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_libdir_flag_spec_GCJ='-L$libdir' + hardcode_shlibpath_var_GCJ=no + ;; + + *) + ld_shlibs_GCJ=no + ;; + esac + fi + +echo "$as_me:$LINENO: result: $ld_shlibs_GCJ" >&5 +echo "${ECHO_T}$ld_shlibs_GCJ" >&6 +test "$ld_shlibs_GCJ" = no && can_build_shared=no + +variables_saved_for_relink="PATH $shlibpath_var $runpath_var" +if test "$GCC" = yes; then + variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" +fi + +# +# Do we need to explicitly link libc? +# +case "x$archive_cmds_need_lc_GCJ" in +x|xyes) + # Assume -lc should be added + archive_cmds_need_lc_GCJ=yes + + if test "$enable_shared" = yes && test "$GCC" = yes; then + case $archive_cmds_GCJ in + *'~'*) + # FIXME: we may have to deal with multi-command sequences. + ;; + '$CC '*) + # Test whether the compiler implicitly links with -lc since on some + # systems, -lgcc has to come before -lc. If gcc already passes -lc + # to ld, don't add -lc before -lgcc. + echo "$as_me:$LINENO: checking whether -lc should be explicitly linked in" >&5 +echo $ECHO_N "checking whether -lc should be explicitly linked in... $ECHO_C" >&6 + $rm conftest* + printf "$lt_simple_compile_test_code" > conftest.$ac_ext + + if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } 2>conftest.err; then + soname=conftest + lib=conftest + libobjs=conftest.$ac_objext + deplibs= + wl=$lt_prog_compiler_wl_GCJ + compiler_flags=-v + linker_flags=-v + verstring= + output_objdir=. + libname=conftest + lt_save_allow_undefined_flag=$allow_undefined_flag_GCJ + allow_undefined_flag_GCJ= + if { (eval echo "$as_me:$LINENO: \"$archive_cmds_GCJ 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1\"") >&5 + (eval $archive_cmds_GCJ 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } + then + archive_cmds_need_lc_GCJ=no + else + archive_cmds_need_lc_GCJ=yes + fi + allow_undefined_flag_GCJ=$lt_save_allow_undefined_flag + else + cat conftest.err 1>&5 + fi + $rm conftest* + echo "$as_me:$LINENO: result: $archive_cmds_need_lc_GCJ" >&5 +echo "${ECHO_T}$archive_cmds_need_lc_GCJ" >&6 + ;; + esac + fi + ;; +esac + +echo "$as_me:$LINENO: checking dynamic linker characteristics" >&5 +echo $ECHO_N "checking dynamic linker characteristics... $ECHO_C" >&6 +library_names_spec= +libname_spec='lib$name' +soname_spec= +shrext_cmds=".so" +postinstall_cmds= +postuninstall_cmds= +finish_cmds= +finish_eval= +shlibpath_var= +shlibpath_overrides_runpath=unknown +version_type=none +dynamic_linker="$host_os ld.so" +sys_lib_dlsearch_path_spec="/lib /usr/lib" +if test "$GCC" = yes; then + sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"` + if echo "$sys_lib_search_path_spec" | grep ';' >/dev/null ; then + # if the path contains ";" then we assume it to be the separator + # otherwise default to the standard path separator (i.e. ":") - it is + # assumed that no part of a normal pathname contains ";" but that should + # okay in the real world where ";" in dirpaths is itself problematic. + sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` + else + sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` + fi +else + sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" +fi +need_lib_prefix=unknown +hardcode_into_libs=no + +# when you set need_version to no, make sure it does not cause -set_version +# flags to be left without arguments +need_version=unknown + +case $host_os in +aix3*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a' + shlibpath_var=LIBPATH + + # AIX 3 has no versioning support, so we append a major version to the name. + soname_spec='${libname}${release}${shared_ext}$major' + ;; + +aix4* | aix5*) + version_type=linux + need_lib_prefix=no + need_version=no + hardcode_into_libs=yes + if test "$host_cpu" = ia64; then + # AIX 5 supports IA64 + library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + else + # With GCC up to 2.95.x, collect2 would create an import file + # for dependence libraries. The import file would start with + # the line `#! .'. This would cause the generated library to + # depend on `.', always an invalid library. This was fixed in + # development snapshots of GCC prior to 3.0. + case $host_os in + aix4 | aix4.[01] | aix4.[01].*) + if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' + echo ' yes ' + echo '#endif'; } | ${CC} -E - | grep yes > /dev/null; then + : + else + can_build_shared=no + fi + ;; + esac + # AIX (on Power*) has no versioning support, so currently we can not hardcode correct + # soname into executable. Probably we can add versioning support to + # collect2, so additional links can be useful in future. + if test "$aix_use_runtimelinking" = yes; then + # If using run time linking (on AIX 4.2 or later) use lib.so + # instead of lib.a to let people know that these are not + # typical AIX shared libraries. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + else + # We preserve .a as extension for shared libraries through AIX4.2 + # and later when we are not doing run time linking. + library_names_spec='${libname}${release}.a $libname.a' + soname_spec='${libname}${release}${shared_ext}$major' + fi + shlibpath_var=LIBPATH + fi + ;; + +amigaos*) + library_names_spec='$libname.ixlibrary $libname.a' + # Create ${libname}_ixlibrary.a entries in /sys/libs. + finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`$echo "X$lib" | $Xsed -e '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $rm /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' + ;; + +beos*) + library_names_spec='${libname}${shared_ext}' + dynamic_linker="$host_os ld.so" + shlibpath_var=LIBRARY_PATH + ;; + +bsdi4*) + version_type=linux + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' + shlibpath_var=LD_LIBRARY_PATH + sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" + sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" + # the default ld.so.conf also contains /usr/contrib/lib and + # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow + # libtool to hard-code these into programs + ;; + +cygwin* | mingw* | pw32*) + version_type=windows + shrext_cmds=".dll" + need_version=no + need_lib_prefix=no + + case $GCC,$host_os in + yes,cygwin* | yes,mingw* | yes,pw32*) + library_names_spec='$libname.dll.a' + # DLL is installed to $(libdir)/../bin by postinstall_cmds + postinstall_cmds='base_file=`basename \${file}`~ + dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i;echo \$dlname'\''`~ + dldir=$destdir/`dirname \$dlpath`~ + test -d \$dldir || mkdir -p \$dldir~ + $install_prog $dir/$dlname \$dldir/$dlname' + postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ + dlpath=$dir/\$dldll~ + $rm \$dlpath' + shlibpath_overrides_runpath=yes + + case $host_os in + cygwin*) + # Cygwin DLLs use 'cyg' prefix rather than 'lib' + soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' + sys_lib_search_path_spec="/usr/lib /lib/w32api /lib /usr/local/lib" + ;; + mingw*) + # MinGW DLLs use traditional 'lib' prefix + soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' + sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"` + if echo "$sys_lib_search_path_spec" | grep ';[c-zC-Z]:/' >/dev/null; then + # It is most probably a Windows format PATH printed by + # mingw gcc, but we are running on Cygwin. Gcc prints its search + # path with ; separators, and with drive letters. We can handle the + # drive letters (cygwin fileutils understands them), so leave them, + # especially as we might pass files found there to a mingw objdump, + # which wouldn't understand a cygwinified path. Ahh. + sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` + else + sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` + fi + ;; + pw32*) + # pw32 DLLs use 'pw' prefix rather than 'lib' + library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/./-/g'`${versuffix}${shared_ext}' + ;; + esac + ;; + + *) + library_names_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext} $libname.lib' + ;; + esac + dynamic_linker='Win32 ld.exe' + # FIXME: first we should search . and the directory the executable is in + shlibpath_var=PATH + ;; + +darwin* | rhapsody*) + dynamic_linker="$host_os dyld" + version_type=darwin + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${versuffix}$shared_ext ${libname}${release}${major}$shared_ext ${libname}$shared_ext' + soname_spec='${libname}${release}${major}$shared_ext' + shlibpath_overrides_runpath=yes + shlibpath_var=DYLD_LIBRARY_PATH + shrext_cmds='$(test .$module = .yes && echo .so || echo .dylib)' + # Apple's gcc prints 'gcc -print-search-dirs' doesn't operate the same. + if test "$GCC" = yes; then + sys_lib_search_path_spec=`$CC -print-search-dirs | tr "\n" "$PATH_SEPARATOR" | sed -e 's/libraries:/@libraries:/' | tr "@" "\n" | grep "^libraries:" | sed -e "s/^libraries://" -e "s,=/,/,g" -e "s,$PATH_SEPARATOR, ,g" -e "s,.*,& /lib /usr/lib /usr/local/lib,g"` + else + sys_lib_search_path_spec='/lib /usr/lib /usr/local/lib' + fi + sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' + ;; + +dgux*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +freebsd1*) + dynamic_linker=no + ;; + +kfreebsd*-gnu) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + dynamic_linker='GNU ld.so' + ;; + +freebsd*) + objformat=`test -x /usr/bin/objformat && /usr/bin/objformat || echo aout` + version_type=freebsd-$objformat + case $version_type in + freebsd-elf*) + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' + need_version=no + need_lib_prefix=no + ;; + freebsd-*) + library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix' + need_version=yes + ;; + esac + shlibpath_var=LD_LIBRARY_PATH + case $host_os in + freebsd2*) + shlibpath_overrides_runpath=yes + ;; + freebsd3.01* | freebsdelf3.01*) + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + *) # from 3.2 on + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + esac + ;; + +gnu*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + hardcode_into_libs=yes + ;; + +hpux9* | hpux10* | hpux11*) + # Give a soname corresponding to the major version so that dld.sl refuses to + # link against other versions. + version_type=sunos + need_lib_prefix=no + need_version=no + case "$host_cpu" in + ia64*) + shrext_cmds='.so' + hardcode_into_libs=yes + dynamic_linker="$host_os dld.so" + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + if test "X$HPUX_IA64_MODE" = X32; then + sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" + else + sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" + fi + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + ;; + hppa*64*) + shrext_cmds='.sl' + hardcode_into_libs=yes + dynamic_linker="$host_os dld.sl" + shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH + shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + ;; + *) + shrext_cmds='.sl' + dynamic_linker="$host_os dld.sl" + shlibpath_var=SHLIB_PATH + shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + ;; + esac + # HP-UX runs *really* slowly unless shared libraries are mode 555. + postinstall_cmds='chmod 555 $lib' + ;; + +irix5* | irix6* | nonstopux*) + case $host_os in + nonstopux*) version_type=nonstopux ;; + *) + if test "$lt_cv_prog_gnu_ld" = yes; then + version_type=linux + else + version_type=irix + fi ;; + esac + need_lib_prefix=no + need_version=no + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}' + case $host_os in + irix5* | nonstopux*) + libsuff= shlibsuff= + ;; + *) + case $LD in # libtool.m4 will add one of these switches to LD + *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") + libsuff= shlibsuff= libmagic=32-bit;; + *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") + libsuff=32 shlibsuff=N32 libmagic=N32;; + *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") + libsuff=64 shlibsuff=64 libmagic=64-bit;; + *) libsuff= shlibsuff= libmagic=never-match;; + esac + ;; + esac + shlibpath_var=LD_LIBRARY${shlibsuff}_PATH + shlibpath_overrides_runpath=no + sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" + sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" + hardcode_into_libs=yes + ;; + +# No shared lib support for Linux oldld, aout, or coff. +linux*oldld* | linux*aout* | linux*coff*) + dynamic_linker=no + ;; + +# This must be Linux ELF. +linux*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + # This implies no fast_install, which is unacceptable. + # Some rework will be needed to allow for fast_install + # before this can be enabled. + hardcode_into_libs=yes + + # Append ld.so.conf contents to the search path + if test -f /etc/ld.so.conf; then + lt_ld_extra=`$SED -e 's/:,\t/ /g;s/=^=*$//;s/=^= * / /g' /etc/ld.so.conf | tr '\n' ' '` + sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" + fi + + # We used to test for /lib/ld.so.1 and disable shared libraries on + # powerpc, because MkLinux only supported shared libraries with the + # GNU dynamic linker. Since this was broken with cross compilers, + # most powerpc-linux boxes support dynamic linking these days and + # people can always --disable-shared, the test was removed, and we + # assume the GNU/Linux dynamic linker is in use. + dynamic_linker='GNU/Linux ld.so' + ;; + +netbsdelf*-gnu) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + dynamic_linker='NetBSD ld.elf_so' + ;; + +knetbsd*-gnu) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + dynamic_linker='GNU ld.so' + ;; + +netbsd*) + version_type=sunos + need_lib_prefix=no + need_version=no + if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' + dynamic_linker='NetBSD (a.out) ld.so' + else + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + dynamic_linker='NetBSD ld.elf_so' + fi + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + +newsos6) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + ;; + +nto-qnx*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + ;; + +openbsd*) + version_type=sunos + need_lib_prefix=no + need_version=yes + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' + shlibpath_var=LD_LIBRARY_PATH + if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + case $host_os in + openbsd2.[89] | openbsd2.[89].*) + shlibpath_overrides_runpath=no + ;; + *) + shlibpath_overrides_runpath=yes + ;; + esac + else + shlibpath_overrides_runpath=yes + fi + ;; + +os2*) + libname_spec='$name' + shrext_cmds=".dll" + need_lib_prefix=no + library_names_spec='$libname${shared_ext} $libname.a' + dynamic_linker='OS/2 ld.exe' + shlibpath_var=LIBPATH + ;; + +osf3* | osf4* | osf5*) + version_type=osf + need_lib_prefix=no + need_version=no + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" + sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec" + ;; + +sco3.2v5*) + version_type=osf + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + ;; + +solaris*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + # ldd complains unless libraries are executable + postinstall_cmds='chmod +x $lib' + ;; + +sunos4*) + version_type=sunos + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + if test "$with_gnu_ld" = yes; then + need_lib_prefix=no + fi + need_version=yes + ;; + +sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + case $host_vendor in + sni) + shlibpath_overrides_runpath=no + need_lib_prefix=no + export_dynamic_flag_spec='${wl}-Blargedynsym' + runpath_var=LD_RUN_PATH + ;; + siemens) + need_lib_prefix=no + ;; + motorola) + need_lib_prefix=no + need_version=no + shlibpath_overrides_runpath=no + sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' + ;; + esac + ;; + +sysv4*MP*) + if test -d /usr/nec ;then + version_type=linux + library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}' + soname_spec='$libname${shared_ext}.$major' + shlibpath_var=LD_LIBRARY_PATH + fi + ;; + +uts4*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +*) + dynamic_linker=no + ;; +esac +echo "$as_me:$LINENO: result: $dynamic_linker" >&5 +echo "${ECHO_T}$dynamic_linker" >&6 +test "$dynamic_linker" = no && can_build_shared=no + +echo "$as_me:$LINENO: checking how to hardcode library paths into programs" >&5 +echo $ECHO_N "checking how to hardcode library paths into programs... $ECHO_C" >&6 +hardcode_action_GCJ= +if test -n "$hardcode_libdir_flag_spec_GCJ" || \ + test -n "$runpath_var GCJ" || \ + test "X$hardcode_automatic_GCJ"="Xyes" ; then + + # We can hardcode non-existant directories. + if test "$hardcode_direct_GCJ" != no && + # If the only mechanism to avoid hardcoding is shlibpath_var, we + # have to relink, otherwise we might link with an installed library + # when we should be linking with a yet-to-be-installed one + ## test "$_LT_AC_TAGVAR(hardcode_shlibpath_var, GCJ)" != no && + test "$hardcode_minus_L_GCJ" != no; then + # Linking always hardcodes the temporary library directory. + hardcode_action_GCJ=relink + else + # We can link without hardcoding, and we can hardcode nonexisting dirs. + hardcode_action_GCJ=immediate + fi +else + # We cannot hardcode anything, or else we can only hardcode existing + # directories. + hardcode_action_GCJ=unsupported +fi +echo "$as_me:$LINENO: result: $hardcode_action_GCJ" >&5 +echo "${ECHO_T}$hardcode_action_GCJ" >&6 + +if test "$hardcode_action_GCJ" = relink; then + # Fast installation is not supported + enable_fast_install=no +elif test "$shlibpath_overrides_runpath" = yes || + test "$enable_shared" = no; then + # Fast installation is not necessary + enable_fast_install=needless +fi + +striplib= +old_striplib= +echo "$as_me:$LINENO: checking whether stripping libraries is possible" >&5 +echo $ECHO_N "checking whether stripping libraries is possible... $ECHO_C" >&6 +if test -n "$STRIP" && $STRIP -V 2>&1 | grep "GNU strip" >/dev/null; then + test -z "$old_striplib" && old_striplib="$STRIP --strip-debug" + test -z "$striplib" && striplib="$STRIP --strip-unneeded" + echo "$as_me:$LINENO: result: yes" >&5 +echo "${ECHO_T}yes" >&6 +else +# FIXME - insert some real tests, host_os isn't really good enough + case $host_os in + darwin*) + if test -n "$STRIP" ; then + striplib="$STRIP -x" + echo "$as_me:$LINENO: result: yes" >&5 +echo "${ECHO_T}yes" >&6 + else + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 +fi + ;; + *) + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 + ;; + esac +fi + +if test "x$enable_dlopen" != xyes; then + enable_dlopen=unknown + enable_dlopen_self=unknown + enable_dlopen_self_static=unknown +else + lt_cv_dlopen=no + lt_cv_dlopen_libs= + + case $host_os in + beos*) + lt_cv_dlopen="load_add_on" + lt_cv_dlopen_libs= + lt_cv_dlopen_self=yes + ;; + + mingw* | pw32*) + lt_cv_dlopen="LoadLibrary" + lt_cv_dlopen_libs= + ;; + + cygwin*) + lt_cv_dlopen="dlopen" + lt_cv_dlopen_libs= + ;; + + darwin*) + # if libdl is installed we need to link against it + echo "$as_me:$LINENO: checking for dlopen in -ldl" >&5 +echo $ECHO_N "checking for dlopen in -ldl... $ECHO_C" >&6 +if test "${ac_cv_lib_dl_dlopen+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldl $LIBS" +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any gcc2 internal prototype to avoid an error. */ +#ifdef __cplusplus +extern "C" +#endif +/* We use char because int might match the return type of a gcc2 + builtin and then its argument prototype would still apply. */ +char dlopen (); +int +main () +{ +dlopen (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_lib_dl_dlopen=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_cv_lib_dl_dlopen=no +fi +rm -f conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +echo "$as_me:$LINENO: result: $ac_cv_lib_dl_dlopen" >&5 +echo "${ECHO_T}$ac_cv_lib_dl_dlopen" >&6 +if test $ac_cv_lib_dl_dlopen = yes; then + lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl" +else + + lt_cv_dlopen="dyld" + lt_cv_dlopen_libs= + lt_cv_dlopen_self=yes + +fi + + ;; + + *) + echo "$as_me:$LINENO: checking for shl_load" >&5 +echo $ECHO_N "checking for shl_load... $ECHO_C" >&6 +if test "${ac_cv_func_shl_load+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +/* Define shl_load to an innocuous variant, in case declares shl_load. + For example, HP-UX 11i declares gettimeofday. */ +#define shl_load innocuous_shl_load + +/* System header to define __stub macros and hopefully few prototypes, + which can conflict with char shl_load (); below. + Prefer to if __STDC__ is defined, since + exists even on freestanding compilers. */ + +#ifdef __STDC__ +# include +#else +# include +#endif + +#undef shl_load + +/* Override any gcc2 internal prototype to avoid an error. */ +#ifdef __cplusplus +extern "C" +{ +#endif +/* We use char because int might match the return type of a gcc2 + builtin and then its argument prototype would still apply. */ +char shl_load (); +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined (__stub_shl_load) || defined (__stub___shl_load) +choke me +#else +char (*f) () = shl_load; +#endif +#ifdef __cplusplus +} +#endif + +int +main () +{ +return f != shl_load; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_func_shl_load=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_cv_func_shl_load=no +fi +rm -f conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +fi +echo "$as_me:$LINENO: result: $ac_cv_func_shl_load" >&5 +echo "${ECHO_T}$ac_cv_func_shl_load" >&6 +if test $ac_cv_func_shl_load = yes; then + lt_cv_dlopen="shl_load" +else + echo "$as_me:$LINENO: checking for shl_load in -ldld" >&5 +echo $ECHO_N "checking for shl_load in -ldld... $ECHO_C" >&6 +if test "${ac_cv_lib_dld_shl_load+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldld $LIBS" +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any gcc2 internal prototype to avoid an error. */ +#ifdef __cplusplus +extern "C" +#endif +/* We use char because int might match the return type of a gcc2 + builtin and then its argument prototype would still apply. */ +char shl_load (); +int +main () +{ +shl_load (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_lib_dld_shl_load=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_cv_lib_dld_shl_load=no +fi +rm -f conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +echo "$as_me:$LINENO: result: $ac_cv_lib_dld_shl_load" >&5 +echo "${ECHO_T}$ac_cv_lib_dld_shl_load" >&6 +if test $ac_cv_lib_dld_shl_load = yes; then + lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-dld" +else + echo "$as_me:$LINENO: checking for dlopen" >&5 +echo $ECHO_N "checking for dlopen... $ECHO_C" >&6 +if test "${ac_cv_func_dlopen+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +/* Define dlopen to an innocuous variant, in case declares dlopen. + For example, HP-UX 11i declares gettimeofday. */ +#define dlopen innocuous_dlopen + +/* System header to define __stub macros and hopefully few prototypes, + which can conflict with char dlopen (); below. + Prefer to if __STDC__ is defined, since + exists even on freestanding compilers. */ + +#ifdef __STDC__ +# include +#else +# include +#endif + +#undef dlopen + +/* Override any gcc2 internal prototype to avoid an error. */ +#ifdef __cplusplus +extern "C" +{ +#endif +/* We use char because int might match the return type of a gcc2 + builtin and then its argument prototype would still apply. */ +char dlopen (); +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined (__stub_dlopen) || defined (__stub___dlopen) +choke me +#else +char (*f) () = dlopen; +#endif +#ifdef __cplusplus +} +#endif + +int +main () +{ +return f != dlopen; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_func_dlopen=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_cv_func_dlopen=no +fi +rm -f conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +fi +echo "$as_me:$LINENO: result: $ac_cv_func_dlopen" >&5 +echo "${ECHO_T}$ac_cv_func_dlopen" >&6 +if test $ac_cv_func_dlopen = yes; then + lt_cv_dlopen="dlopen" +else + echo "$as_me:$LINENO: checking for dlopen in -ldl" >&5 +echo $ECHO_N "checking for dlopen in -ldl... $ECHO_C" >&6 +if test "${ac_cv_lib_dl_dlopen+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldl $LIBS" +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any gcc2 internal prototype to avoid an error. */ +#ifdef __cplusplus +extern "C" +#endif +/* We use char because int might match the return type of a gcc2 + builtin and then its argument prototype would still apply. */ +char dlopen (); +int +main () +{ +dlopen (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_lib_dl_dlopen=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_cv_lib_dl_dlopen=no +fi +rm -f conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +echo "$as_me:$LINENO: result: $ac_cv_lib_dl_dlopen" >&5 +echo "${ECHO_T}$ac_cv_lib_dl_dlopen" >&6 +if test $ac_cv_lib_dl_dlopen = yes; then + lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl" +else + echo "$as_me:$LINENO: checking for dlopen in -lsvld" >&5 +echo $ECHO_N "checking for dlopen in -lsvld... $ECHO_C" >&6 +if test "${ac_cv_lib_svld_dlopen+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lsvld $LIBS" +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any gcc2 internal prototype to avoid an error. */ +#ifdef __cplusplus +extern "C" +#endif +/* We use char because int might match the return type of a gcc2 + builtin and then its argument prototype would still apply. */ +char dlopen (); +int +main () +{ +dlopen (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_lib_svld_dlopen=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_cv_lib_svld_dlopen=no +fi +rm -f conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +echo "$as_me:$LINENO: result: $ac_cv_lib_svld_dlopen" >&5 +echo "${ECHO_T}$ac_cv_lib_svld_dlopen" >&6 +if test $ac_cv_lib_svld_dlopen = yes; then + lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld" +else + echo "$as_me:$LINENO: checking for dld_link in -ldld" >&5 +echo $ECHO_N "checking for dld_link in -ldld... $ECHO_C" >&6 +if test "${ac_cv_lib_dld_dld_link+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldld $LIBS" +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any gcc2 internal prototype to avoid an error. */ +#ifdef __cplusplus +extern "C" +#endif +/* We use char because int might match the return type of a gcc2 + builtin and then its argument prototype would still apply. */ +char dld_link (); +int +main () +{ +dld_link (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_lib_dld_dld_link=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_cv_lib_dld_dld_link=no +fi +rm -f conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +echo "$as_me:$LINENO: result: $ac_cv_lib_dld_dld_link" >&5 +echo "${ECHO_T}$ac_cv_lib_dld_dld_link" >&6 +if test $ac_cv_lib_dld_dld_link = yes; then + lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-dld" +fi + + +fi + + +fi + + +fi + + +fi + + +fi + + ;; + esac + + if test "x$lt_cv_dlopen" != xno; then + enable_dlopen=yes + else + enable_dlopen=no + fi + + case $lt_cv_dlopen in + dlopen) + save_CPPFLAGS="$CPPFLAGS" + test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H" + + save_LDFLAGS="$LDFLAGS" + eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\" + + save_LIBS="$LIBS" + LIBS="$lt_cv_dlopen_libs $LIBS" + + echo "$as_me:$LINENO: checking whether a program can dlopen itself" >&5 +echo $ECHO_N "checking whether a program can dlopen itself... $ECHO_C" >&6 +if test "${lt_cv_dlopen_self+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test "$cross_compiling" = yes; then : + lt_cv_dlopen_self=cross +else + lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 + lt_status=$lt_dlunknown + cat > conftest.$ac_ext < +#endif + +#include + +#ifdef RTLD_GLOBAL +# define LT_DLGLOBAL RTLD_GLOBAL +#else +# ifdef DL_GLOBAL +# define LT_DLGLOBAL DL_GLOBAL +# else +# define LT_DLGLOBAL 0 +# endif +#endif + +/* We may have to define LT_DLLAZY_OR_NOW in the command line if we + find out it does not work in some platform. */ +#ifndef LT_DLLAZY_OR_NOW +# ifdef RTLD_LAZY +# define LT_DLLAZY_OR_NOW RTLD_LAZY +# else +# ifdef DL_LAZY +# define LT_DLLAZY_OR_NOW DL_LAZY +# else +# ifdef RTLD_NOW +# define LT_DLLAZY_OR_NOW RTLD_NOW +# else +# ifdef DL_NOW +# define LT_DLLAZY_OR_NOW DL_NOW +# else +# define LT_DLLAZY_OR_NOW 0 +# endif +# endif +# endif +# endif +#endif + +#ifdef __cplusplus +extern "C" void exit (int); +#endif + +void fnord() { int i=42;} +int main () +{ + void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); + int status = $lt_dlunknown; + + if (self) + { + if (dlsym (self,"fnord")) status = $lt_dlno_uscore; + else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; + /* dlclose (self); */ + } + + exit (status); +} +EOF + if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && test -s conftest${ac_exeext} 2>/dev/null; then + (./conftest; exit; ) 2>/dev/null + lt_status=$? + case x$lt_status in + x$lt_dlno_uscore) lt_cv_dlopen_self=yes ;; + x$lt_dlneed_uscore) lt_cv_dlopen_self=yes ;; + x$lt_unknown|x*) lt_cv_dlopen_self=no ;; + esac + else : + # compilation failed + lt_cv_dlopen_self=no + fi +fi +rm -fr conftest* + + +fi +echo "$as_me:$LINENO: result: $lt_cv_dlopen_self" >&5 +echo "${ECHO_T}$lt_cv_dlopen_self" >&6 + + if test "x$lt_cv_dlopen_self" = xyes; then + LDFLAGS="$LDFLAGS $link_static_flag" + echo "$as_me:$LINENO: checking whether a statically linked program can dlopen itself" >&5 +echo $ECHO_N "checking whether a statically linked program can dlopen itself... $ECHO_C" >&6 +if test "${lt_cv_dlopen_self_static+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test "$cross_compiling" = yes; then : + lt_cv_dlopen_self_static=cross +else + lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 + lt_status=$lt_dlunknown + cat > conftest.$ac_ext < +#endif + +#include + +#ifdef RTLD_GLOBAL +# define LT_DLGLOBAL RTLD_GLOBAL +#else +# ifdef DL_GLOBAL +# define LT_DLGLOBAL DL_GLOBAL +# else +# define LT_DLGLOBAL 0 +# endif +#endif + +/* We may have to define LT_DLLAZY_OR_NOW in the command line if we + find out it does not work in some platform. */ +#ifndef LT_DLLAZY_OR_NOW +# ifdef RTLD_LAZY +# define LT_DLLAZY_OR_NOW RTLD_LAZY +# else +# ifdef DL_LAZY +# define LT_DLLAZY_OR_NOW DL_LAZY +# else +# ifdef RTLD_NOW +# define LT_DLLAZY_OR_NOW RTLD_NOW +# else +# ifdef DL_NOW +# define LT_DLLAZY_OR_NOW DL_NOW +# else +# define LT_DLLAZY_OR_NOW 0 +# endif +# endif +# endif +# endif +#endif + +#ifdef __cplusplus +extern "C" void exit (int); +#endif + +void fnord() { int i=42;} +int main () +{ + void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); + int status = $lt_dlunknown; + + if (self) + { + if (dlsym (self,"fnord")) status = $lt_dlno_uscore; + else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; + /* dlclose (self); */ + } + + exit (status); +} +EOF + if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && test -s conftest${ac_exeext} 2>/dev/null; then + (./conftest; exit; ) 2>/dev/null + lt_status=$? + case x$lt_status in + x$lt_dlno_uscore) lt_cv_dlopen_self_static=yes ;; + x$lt_dlneed_uscore) lt_cv_dlopen_self_static=yes ;; + x$lt_unknown|x*) lt_cv_dlopen_self_static=no ;; + esac + else : + # compilation failed + lt_cv_dlopen_self_static=no + fi +fi +rm -fr conftest* + + +fi +echo "$as_me:$LINENO: result: $lt_cv_dlopen_self_static" >&5 +echo "${ECHO_T}$lt_cv_dlopen_self_static" >&6 + fi + + CPPFLAGS="$save_CPPFLAGS" + LDFLAGS="$save_LDFLAGS" + LIBS="$save_LIBS" + ;; + esac + + case $lt_cv_dlopen_self in + yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;; + *) enable_dlopen_self=unknown ;; + esac + + case $lt_cv_dlopen_self_static in + yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;; + *) enable_dlopen_self_static=unknown ;; + esac +fi + + +# The else clause should only fire when bootstrapping the +# libtool distribution, otherwise you forgot to ship ltmain.sh +# with your package, and you will get complaints that there are +# no rules to generate ltmain.sh. +if test -f "$ltmain"; then + # See if we are running on zsh, and set the options which allow our commands through + # without removal of \ escapes. + if test -n "${ZSH_VERSION+set}" ; then + setopt NO_GLOB_SUBST + fi + # Now quote all the things that may contain metacharacters while being + # careful not to overquote the AC_SUBSTed values. We take copies of the + # variables and quote the copies for generation of the libtool script. + for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC NM \ + SED SHELL STRIP \ + libname_spec library_names_spec soname_spec extract_expsyms_cmds \ + old_striplib striplib file_magic_cmd finish_cmds finish_eval \ + deplibs_check_method reload_flag reload_cmds need_locks \ + lt_cv_sys_global_symbol_pipe lt_cv_sys_global_symbol_to_cdecl \ + lt_cv_sys_global_symbol_to_c_name_address \ + sys_lib_search_path_spec sys_lib_dlsearch_path_spec \ + old_postinstall_cmds old_postuninstall_cmds \ + compiler_GCJ \ + CC_GCJ \ + LD_GCJ \ + lt_prog_compiler_wl_GCJ \ + lt_prog_compiler_pic_GCJ \ + lt_prog_compiler_static_GCJ \ + lt_prog_compiler_no_builtin_flag_GCJ \ + export_dynamic_flag_spec_GCJ \ + thread_safe_flag_spec_GCJ \ + whole_archive_flag_spec_GCJ \ + enable_shared_with_static_runtimes_GCJ \ + old_archive_cmds_GCJ \ + old_archive_from_new_cmds_GCJ \ + predep_objects_GCJ \ + postdep_objects_GCJ \ + predeps_GCJ \ + postdeps_GCJ \ + compiler_lib_search_path_GCJ \ + archive_cmds_GCJ \ + archive_expsym_cmds_GCJ \ + postinstall_cmds_GCJ \ + postuninstall_cmds_GCJ \ + old_archive_from_expsyms_cmds_GCJ \ + allow_undefined_flag_GCJ \ + no_undefined_flag_GCJ \ + export_symbols_cmds_GCJ \ + hardcode_libdir_flag_spec_GCJ \ + hardcode_libdir_flag_spec_ld_GCJ \ + hardcode_libdir_separator_GCJ \ + hardcode_automatic_GCJ \ + module_cmds_GCJ \ + module_expsym_cmds_GCJ \ + lt_cv_prog_compiler_c_o_GCJ \ + exclude_expsyms_GCJ \ + include_expsyms_GCJ; do + + case $var in + old_archive_cmds_GCJ | \ + old_archive_from_new_cmds_GCJ | \ + archive_cmds_GCJ | \ + archive_expsym_cmds_GCJ | \ + module_cmds_GCJ | \ + module_expsym_cmds_GCJ | \ + old_archive_from_expsyms_cmds_GCJ | \ + export_symbols_cmds_GCJ | \ + extract_expsyms_cmds | reload_cmds | finish_cmds | \ + postinstall_cmds | postuninstall_cmds | \ + old_postinstall_cmds | old_postuninstall_cmds | \ + sys_lib_search_path_spec | sys_lib_dlsearch_path_spec) + # Double-quote double-evaled strings. + eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$double_quote_subst\" -e \"\$sed_quote_subst\" -e \"\$delay_variable_subst\"\`\\\"" + ;; + *) + eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$sed_quote_subst\"\`\\\"" + ;; + esac + done + + case $lt_echo in + *'\$0 --fallback-echo"') + lt_echo=`$echo "X$lt_echo" | $Xsed -e 's/\\\\\\\$0 --fallback-echo"$/$0 --fallback-echo"/'` + ;; + esac + +cfgfile="$ofile" + + cat <<__EOF__ >> "$cfgfile" +# ### BEGIN LIBTOOL TAG CONFIG: $tagname + +# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`: + +# Shell to use when invoking shell scripts. +SHELL=$lt_SHELL + +# Whether or not to build shared libraries. +build_libtool_libs=$enable_shared + +# Whether or not to build static libraries. +build_old_libs=$enable_static + +# Whether or not to add -lc for building shared libraries. +build_libtool_need_lc=$archive_cmds_need_lc_GCJ + +# Whether or not to disallow shared libs when runtime libs are static +allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes_GCJ + +# Whether or not to optimize for fast installation. +fast_install=$enable_fast_install + +# The host system. +host_alias=$host_alias +host=$host + +# An echo program that does not interpret backslashes. +echo=$lt_echo + +# The archiver. +AR=$lt_AR +AR_FLAGS=$lt_AR_FLAGS + +# A C compiler. +LTCC=$lt_LTCC + +# A language-specific compiler. +CC=$lt_compiler_GCJ + +# Is the compiler the GNU C compiler? +with_gcc=$GCC_GCJ + +# An ERE matcher. +EGREP=$lt_EGREP + +# The linker used to build libraries. +LD=$lt_LD_GCJ + +# Whether we need hard or soft links. +LN_S=$lt_LN_S + +# A BSD-compatible nm program. +NM=$lt_NM + +# A symbol stripping program +STRIP=$lt_STRIP + +# Used to examine libraries when file_magic_cmd begins "file" +MAGIC_CMD=$MAGIC_CMD + +# Used on cygwin: DLL creation program. +DLLTOOL="$DLLTOOL" + +# Used on cygwin: object dumper. +OBJDUMP="$OBJDUMP" + +# Used on cygwin: assembler. +AS="$AS" + +# The name of the directory that contains temporary libtool files. +objdir=$objdir + +# How to create reloadable object files. +reload_flag=$lt_reload_flag +reload_cmds=$lt_reload_cmds + +# How to pass a linker flag through the compiler. +wl=$lt_lt_prog_compiler_wl_GCJ + +# Object file suffix (normally "o"). +objext="$ac_objext" + +# Old archive suffix (normally "a"). +libext="$libext" + +# Shared library suffix (normally ".so"). +shrext_cmds='$shrext_cmds' + +# Executable file suffix (normally ""). +exeext="$exeext" + +# Additional compiler flags for building library objects. +pic_flag=$lt_lt_prog_compiler_pic_GCJ +pic_mode=$pic_mode + +# What is the maximum length of a command? +max_cmd_len=$lt_cv_sys_max_cmd_len + +# Does compiler simultaneously support -c and -o options? +compiler_c_o=$lt_lt_cv_prog_compiler_c_o_GCJ + +# Must we lock files when doing compilation ? +need_locks=$lt_need_locks + +# Do we need the lib prefix for modules? +need_lib_prefix=$need_lib_prefix + +# Do we need a version for libraries? +need_version=$need_version + +# Whether dlopen is supported. +dlopen_support=$enable_dlopen + +# Whether dlopen of programs is supported. +dlopen_self=$enable_dlopen_self + +# Whether dlopen of statically linked programs is supported. +dlopen_self_static=$enable_dlopen_self_static + +# Compiler flag to prevent dynamic linking. +link_static_flag=$lt_lt_prog_compiler_static_GCJ + +# Compiler flag to turn off builtin functions. +no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag_GCJ + +# Compiler flag to allow reflexive dlopens. +export_dynamic_flag_spec=$lt_export_dynamic_flag_spec_GCJ + +# Compiler flag to generate shared objects directly from archives. +whole_archive_flag_spec=$lt_whole_archive_flag_spec_GCJ + +# Compiler flag to generate thread-safe objects. +thread_safe_flag_spec=$lt_thread_safe_flag_spec_GCJ + +# Library versioning type. +version_type=$version_type + +# Format of library name prefix. +libname_spec=$lt_libname_spec + +# List of archive names. First name is the real one, the rest are links. +# The last name is the one that the linker finds with -lNAME. +library_names_spec=$lt_library_names_spec + +# The coded name of the library, if different from the real name. +soname_spec=$lt_soname_spec + +# Commands used to build and install an old-style archive. +RANLIB=$lt_RANLIB +old_archive_cmds=$lt_old_archive_cmds_GCJ +old_postinstall_cmds=$lt_old_postinstall_cmds +old_postuninstall_cmds=$lt_old_postuninstall_cmds + +# Create an old-style archive from a shared archive. +old_archive_from_new_cmds=$lt_old_archive_from_new_cmds_GCJ + +# Create a temporary old-style archive to link instead of a shared archive. +old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds_GCJ + +# Commands used to build and install a shared archive. +archive_cmds=$lt_archive_cmds_GCJ +archive_expsym_cmds=$lt_archive_expsym_cmds_GCJ +postinstall_cmds=$lt_postinstall_cmds +postuninstall_cmds=$lt_postuninstall_cmds + +# Commands used to build a loadable module (assumed same as above if empty) +module_cmds=$lt_module_cmds_GCJ +module_expsym_cmds=$lt_module_expsym_cmds_GCJ + +# Commands to strip libraries. +old_striplib=$lt_old_striplib +striplib=$lt_striplib + +# Dependencies to place before the objects being linked to create a +# shared library. +predep_objects=$lt_predep_objects_GCJ + +# Dependencies to place after the objects being linked to create a +# shared library. +postdep_objects=$lt_postdep_objects_GCJ + +# Dependencies to place before the objects being linked to create a +# shared library. +predeps=$lt_predeps_GCJ + +# Dependencies to place after the objects being linked to create a +# shared library. +postdeps=$lt_postdeps_GCJ + +# The library search path used internally by the compiler when linking +# a shared library. +compiler_lib_search_path=$lt_compiler_lib_search_path_GCJ + +# Method to check whether dependent libraries are shared objects. +deplibs_check_method=$lt_deplibs_check_method + +# Command to use when deplibs_check_method == file_magic. +file_magic_cmd=$lt_file_magic_cmd + +# Flag that allows shared libraries with undefined symbols to be built. +allow_undefined_flag=$lt_allow_undefined_flag_GCJ + +# Flag that forces no undefined symbols. +no_undefined_flag=$lt_no_undefined_flag_GCJ + +# Commands used to finish a libtool library installation in a directory. +finish_cmds=$lt_finish_cmds + +# Same as above, but a single script fragment to be evaled but not shown. +finish_eval=$lt_finish_eval + +# Take the output of nm and produce a listing of raw symbols and C names. +global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe + +# Transform the output of nm in a proper C declaration +global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl + +# Transform the output of nm in a C name address pair +global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address + +# This is the shared library runtime path variable. +runpath_var=$runpath_var + +# This is the shared library path variable. +shlibpath_var=$shlibpath_var + +# Is shlibpath searched before the hard-coded library search path? +shlibpath_overrides_runpath=$shlibpath_overrides_runpath + +# How to hardcode a shared library path into an executable. +hardcode_action=$hardcode_action_GCJ + +# Whether we should hardcode library paths into libraries. +hardcode_into_libs=$hardcode_into_libs + +# Flag to hardcode \$libdir into a binary during linking. +# This must work even if \$libdir does not exist. +hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec_GCJ + +# If ld is used when linking, flag to hardcode \$libdir into +# a binary during linking. This must work even if \$libdir does +# not exist. +hardcode_libdir_flag_spec_ld=$lt_hardcode_libdir_flag_spec_ld_GCJ + +# Whether we need a single -rpath flag with a separated argument. +hardcode_libdir_separator=$lt_hardcode_libdir_separator_GCJ + +# Set to yes if using DIR/libNAME${shared_ext} during linking hardcodes DIR into the +# resulting binary. +hardcode_direct=$hardcode_direct_GCJ + +# Set to yes if using the -LDIR flag during linking hardcodes DIR into the +# resulting binary. +hardcode_minus_L=$hardcode_minus_L_GCJ + +# Set to yes if using SHLIBPATH_VAR=DIR during linking hardcodes DIR into +# the resulting binary. +hardcode_shlibpath_var=$hardcode_shlibpath_var_GCJ + +# Set to yes if building a shared library automatically hardcodes DIR into the library +# and all subsequent libraries and executables linked against it. +hardcode_automatic=$hardcode_automatic_GCJ + +# Variables whose values should be saved in libtool wrapper scripts and +# restored at relink time. +variables_saved_for_relink="$variables_saved_for_relink" + +# Whether libtool must link a program against all its dependency libraries. +link_all_deplibs=$link_all_deplibs_GCJ + +# Compile-time system search path for libraries +sys_lib_search_path_spec=$lt_sys_lib_search_path_spec + +# Run-time system search path for libraries +sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec + +# Fix the shell variable \$srcfile for the compiler. +fix_srcfile_path="$fix_srcfile_path_GCJ" + +# Set to yes if exported symbols are required. +always_export_symbols=$always_export_symbols_GCJ + +# The commands to list exported symbols. +export_symbols_cmds=$lt_export_symbols_cmds_GCJ + +# The commands to extract the exported symbol list from a shared archive. +extract_expsyms_cmds=$lt_extract_expsyms_cmds + +# Symbols that should not be listed in the preloaded symbols. +exclude_expsyms=$lt_exclude_expsyms_GCJ + +# Symbols that must always be exported. +include_expsyms=$lt_include_expsyms_GCJ + +# ### END LIBTOOL TAG CONFIG: $tagname + +__EOF__ + + +else + # If there is no Makefile yet, we rely on a make rule to execute + # `config.status --recheck' to rerun these tests and create the + # libtool script then. + ltmain_in=`echo $ltmain | sed -e 's/\.sh$/.in/'` + if test -f "$ltmain_in"; then + test -f Makefile && make "$ltmain" + fi +fi + + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + +CC="$lt_save_CC" + + else + tagname="" + fi + ;; + + RC) + + + +# Source file extension for RC test sources. +ac_ext=rc + +# Object file extension for compiled RC test sources. +objext=o +objext_RC=$objext + +# Code to be used in simple compile tests +lt_simple_compile_test_code='sample MENU { MENUITEM "&Soup", 100, CHECKED }\n' + +# Code to be used in simple link tests +lt_simple_link_test_code="$lt_simple_compile_test_code" + +# ltmain only uses $CC for tagged configurations so make sure $CC is set. + +# If no C compiler was specified, use CC. +LTCC=${LTCC-"$CC"} + +# Allow CC to be a program name with arguments. +compiler=$CC + + +# Allow CC to be a program name with arguments. +lt_save_CC="$CC" +CC=${RC-"windres"} +compiler=$CC +compiler_RC=$CC +lt_cv_prog_compiler_c_o_RC=yes + +# The else clause should only fire when bootstrapping the +# libtool distribution, otherwise you forgot to ship ltmain.sh +# with your package, and you will get complaints that there are +# no rules to generate ltmain.sh. +if test -f "$ltmain"; then + # See if we are running on zsh, and set the options which allow our commands through + # without removal of \ escapes. + if test -n "${ZSH_VERSION+set}" ; then + setopt NO_GLOB_SUBST + fi + # Now quote all the things that may contain metacharacters while being + # careful not to overquote the AC_SUBSTed values. We take copies of the + # variables and quote the copies for generation of the libtool script. + for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC NM \ + SED SHELL STRIP \ + libname_spec library_names_spec soname_spec extract_expsyms_cmds \ + old_striplib striplib file_magic_cmd finish_cmds finish_eval \ + deplibs_check_method reload_flag reload_cmds need_locks \ + lt_cv_sys_global_symbol_pipe lt_cv_sys_global_symbol_to_cdecl \ + lt_cv_sys_global_symbol_to_c_name_address \ + sys_lib_search_path_spec sys_lib_dlsearch_path_spec \ + old_postinstall_cmds old_postuninstall_cmds \ + compiler_RC \ + CC_RC \ + LD_RC \ + lt_prog_compiler_wl_RC \ + lt_prog_compiler_pic_RC \ + lt_prog_compiler_static_RC \ + lt_prog_compiler_no_builtin_flag_RC \ + export_dynamic_flag_spec_RC \ + thread_safe_flag_spec_RC \ + whole_archive_flag_spec_RC \ + enable_shared_with_static_runtimes_RC \ + old_archive_cmds_RC \ + old_archive_from_new_cmds_RC \ + predep_objects_RC \ + postdep_objects_RC \ + predeps_RC \ + postdeps_RC \ + compiler_lib_search_path_RC \ + archive_cmds_RC \ + archive_expsym_cmds_RC \ + postinstall_cmds_RC \ + postuninstall_cmds_RC \ + old_archive_from_expsyms_cmds_RC \ + allow_undefined_flag_RC \ + no_undefined_flag_RC \ + export_symbols_cmds_RC \ + hardcode_libdir_flag_spec_RC \ + hardcode_libdir_flag_spec_ld_RC \ + hardcode_libdir_separator_RC \ + hardcode_automatic_RC \ + module_cmds_RC \ + module_expsym_cmds_RC \ + lt_cv_prog_compiler_c_o_RC \ + exclude_expsyms_RC \ + include_expsyms_RC; do + + case $var in + old_archive_cmds_RC | \ + old_archive_from_new_cmds_RC | \ + archive_cmds_RC | \ + archive_expsym_cmds_RC | \ + module_cmds_RC | \ + module_expsym_cmds_RC | \ + old_archive_from_expsyms_cmds_RC | \ + export_symbols_cmds_RC | \ + extract_expsyms_cmds | reload_cmds | finish_cmds | \ + postinstall_cmds | postuninstall_cmds | \ + old_postinstall_cmds | old_postuninstall_cmds | \ + sys_lib_search_path_spec | sys_lib_dlsearch_path_spec) + # Double-quote double-evaled strings. + eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$double_quote_subst\" -e \"\$sed_quote_subst\" -e \"\$delay_variable_subst\"\`\\\"" + ;; + *) + eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$sed_quote_subst\"\`\\\"" + ;; + esac + done + + case $lt_echo in + *'\$0 --fallback-echo"') + lt_echo=`$echo "X$lt_echo" | $Xsed -e 's/\\\\\\\$0 --fallback-echo"$/$0 --fallback-echo"/'` + ;; + esac + +cfgfile="$ofile" + + cat <<__EOF__ >> "$cfgfile" +# ### BEGIN LIBTOOL TAG CONFIG: $tagname + +# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`: + +# Shell to use when invoking shell scripts. +SHELL=$lt_SHELL + +# Whether or not to build shared libraries. +build_libtool_libs=$enable_shared + +# Whether or not to build static libraries. +build_old_libs=$enable_static + +# Whether or not to add -lc for building shared libraries. +build_libtool_need_lc=$archive_cmds_need_lc_RC + +# Whether or not to disallow shared libs when runtime libs are static +allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes_RC + +# Whether or not to optimize for fast installation. +fast_install=$enable_fast_install + +# The host system. +host_alias=$host_alias +host=$host + +# An echo program that does not interpret backslashes. +echo=$lt_echo + +# The archiver. +AR=$lt_AR +AR_FLAGS=$lt_AR_FLAGS + +# A C compiler. +LTCC=$lt_LTCC + +# A language-specific compiler. +CC=$lt_compiler_RC + +# Is the compiler the GNU C compiler? +with_gcc=$GCC_RC + +# An ERE matcher. +EGREP=$lt_EGREP + +# The linker used to build libraries. +LD=$lt_LD_RC + +# Whether we need hard or soft links. +LN_S=$lt_LN_S + +# A BSD-compatible nm program. +NM=$lt_NM + +# A symbol stripping program +STRIP=$lt_STRIP + +# Used to examine libraries when file_magic_cmd begins "file" +MAGIC_CMD=$MAGIC_CMD + +# Used on cygwin: DLL creation program. +DLLTOOL="$DLLTOOL" + +# Used on cygwin: object dumper. +OBJDUMP="$OBJDUMP" + +# Used on cygwin: assembler. +AS="$AS" + +# The name of the directory that contains temporary libtool files. +objdir=$objdir + +# How to create reloadable object files. +reload_flag=$lt_reload_flag +reload_cmds=$lt_reload_cmds + +# How to pass a linker flag through the compiler. +wl=$lt_lt_prog_compiler_wl_RC + +# Object file suffix (normally "o"). +objext="$ac_objext" + +# Old archive suffix (normally "a"). +libext="$libext" + +# Shared library suffix (normally ".so"). +shrext_cmds='$shrext_cmds' + +# Executable file suffix (normally ""). +exeext="$exeext" + +# Additional compiler flags for building library objects. +pic_flag=$lt_lt_prog_compiler_pic_RC +pic_mode=$pic_mode + +# What is the maximum length of a command? +max_cmd_len=$lt_cv_sys_max_cmd_len + +# Does compiler simultaneously support -c and -o options? +compiler_c_o=$lt_lt_cv_prog_compiler_c_o_RC + +# Must we lock files when doing compilation ? +need_locks=$lt_need_locks + +# Do we need the lib prefix for modules? +need_lib_prefix=$need_lib_prefix + +# Do we need a version for libraries? +need_version=$need_version + +# Whether dlopen is supported. +dlopen_support=$enable_dlopen + +# Whether dlopen of programs is supported. +dlopen_self=$enable_dlopen_self + +# Whether dlopen of statically linked programs is supported. +dlopen_self_static=$enable_dlopen_self_static + +# Compiler flag to prevent dynamic linking. +link_static_flag=$lt_lt_prog_compiler_static_RC + +# Compiler flag to turn off builtin functions. +no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag_RC + +# Compiler flag to allow reflexive dlopens. +export_dynamic_flag_spec=$lt_export_dynamic_flag_spec_RC + +# Compiler flag to generate shared objects directly from archives. +whole_archive_flag_spec=$lt_whole_archive_flag_spec_RC + +# Compiler flag to generate thread-safe objects. +thread_safe_flag_spec=$lt_thread_safe_flag_spec_RC + +# Library versioning type. +version_type=$version_type + +# Format of library name prefix. +libname_spec=$lt_libname_spec + +# List of archive names. First name is the real one, the rest are links. +# The last name is the one that the linker finds with -lNAME. +library_names_spec=$lt_library_names_spec + +# The coded name of the library, if different from the real name. +soname_spec=$lt_soname_spec + +# Commands used to build and install an old-style archive. +RANLIB=$lt_RANLIB +old_archive_cmds=$lt_old_archive_cmds_RC +old_postinstall_cmds=$lt_old_postinstall_cmds +old_postuninstall_cmds=$lt_old_postuninstall_cmds + +# Create an old-style archive from a shared archive. +old_archive_from_new_cmds=$lt_old_archive_from_new_cmds_RC + +# Create a temporary old-style archive to link instead of a shared archive. +old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds_RC + +# Commands used to build and install a shared archive. +archive_cmds=$lt_archive_cmds_RC +archive_expsym_cmds=$lt_archive_expsym_cmds_RC +postinstall_cmds=$lt_postinstall_cmds +postuninstall_cmds=$lt_postuninstall_cmds + +# Commands used to build a loadable module (assumed same as above if empty) +module_cmds=$lt_module_cmds_RC +module_expsym_cmds=$lt_module_expsym_cmds_RC + +# Commands to strip libraries. +old_striplib=$lt_old_striplib +striplib=$lt_striplib + +# Dependencies to place before the objects being linked to create a +# shared library. +predep_objects=$lt_predep_objects_RC + +# Dependencies to place after the objects being linked to create a +# shared library. +postdep_objects=$lt_postdep_objects_RC + +# Dependencies to place before the objects being linked to create a +# shared library. +predeps=$lt_predeps_RC + +# Dependencies to place after the objects being linked to create a +# shared library. +postdeps=$lt_postdeps_RC + +# The library search path used internally by the compiler when linking +# a shared library. +compiler_lib_search_path=$lt_compiler_lib_search_path_RC + +# Method to check whether dependent libraries are shared objects. +deplibs_check_method=$lt_deplibs_check_method + +# Command to use when deplibs_check_method == file_magic. +file_magic_cmd=$lt_file_magic_cmd + +# Flag that allows shared libraries with undefined symbols to be built. +allow_undefined_flag=$lt_allow_undefined_flag_RC + +# Flag that forces no undefined symbols. +no_undefined_flag=$lt_no_undefined_flag_RC + +# Commands used to finish a libtool library installation in a directory. +finish_cmds=$lt_finish_cmds + +# Same as above, but a single script fragment to be evaled but not shown. +finish_eval=$lt_finish_eval + +# Take the output of nm and produce a listing of raw symbols and C names. +global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe + +# Transform the output of nm in a proper C declaration +global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl + +# Transform the output of nm in a C name address pair +global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address + +# This is the shared library runtime path variable. +runpath_var=$runpath_var + +# This is the shared library path variable. +shlibpath_var=$shlibpath_var + +# Is shlibpath searched before the hard-coded library search path? +shlibpath_overrides_runpath=$shlibpath_overrides_runpath + +# How to hardcode a shared library path into an executable. +hardcode_action=$hardcode_action_RC + +# Whether we should hardcode library paths into libraries. +hardcode_into_libs=$hardcode_into_libs + +# Flag to hardcode \$libdir into a binary during linking. +# This must work even if \$libdir does not exist. +hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec_RC + +# If ld is used when linking, flag to hardcode \$libdir into +# a binary during linking. This must work even if \$libdir does +# not exist. +hardcode_libdir_flag_spec_ld=$lt_hardcode_libdir_flag_spec_ld_RC + +# Whether we need a single -rpath flag with a separated argument. +hardcode_libdir_separator=$lt_hardcode_libdir_separator_RC + +# Set to yes if using DIR/libNAME${shared_ext} during linking hardcodes DIR into the +# resulting binary. +hardcode_direct=$hardcode_direct_RC + +# Set to yes if using the -LDIR flag during linking hardcodes DIR into the +# resulting binary. +hardcode_minus_L=$hardcode_minus_L_RC + +# Set to yes if using SHLIBPATH_VAR=DIR during linking hardcodes DIR into +# the resulting binary. +hardcode_shlibpath_var=$hardcode_shlibpath_var_RC + +# Set to yes if building a shared library automatically hardcodes DIR into the library +# and all subsequent libraries and executables linked against it. +hardcode_automatic=$hardcode_automatic_RC + +# Variables whose values should be saved in libtool wrapper scripts and +# restored at relink time. +variables_saved_for_relink="$variables_saved_for_relink" + +# Whether libtool must link a program against all its dependency libraries. +link_all_deplibs=$link_all_deplibs_RC + +# Compile-time system search path for libraries +sys_lib_search_path_spec=$lt_sys_lib_search_path_spec + +# Run-time system search path for libraries +sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec + +# Fix the shell variable \$srcfile for the compiler. +fix_srcfile_path="$fix_srcfile_path_RC" + +# Set to yes if exported symbols are required. +always_export_symbols=$always_export_symbols_RC + +# The commands to list exported symbols. +export_symbols_cmds=$lt_export_symbols_cmds_RC + +# The commands to extract the exported symbol list from a shared archive. +extract_expsyms_cmds=$lt_extract_expsyms_cmds + +# Symbols that should not be listed in the preloaded symbols. +exclude_expsyms=$lt_exclude_expsyms_RC + +# Symbols that must always be exported. +include_expsyms=$lt_include_expsyms_RC + +# ### END LIBTOOL TAG CONFIG: $tagname + +__EOF__ + + +else + # If there is no Makefile yet, we rely on a make rule to execute + # `config.status --recheck' to rerun these tests and create the + # libtool script then. + ltmain_in=`echo $ltmain | sed -e 's/\.sh$/.in/'` + if test -f "$ltmain_in"; then + test -f Makefile && make "$ltmain" + fi +fi + + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + +CC="$lt_save_CC" + + ;; + + *) + { { echo "$as_me:$LINENO: error: Unsupported tag name: $tagname" >&5 +echo "$as_me: error: Unsupported tag name: $tagname" >&2;} + { (exit 1); exit 1; }; } + ;; + esac + + # Append the new tag name to the list of available tags. + if test -n "$tagname" ; then + available_tags="$available_tags $tagname" + fi + fi + done + IFS="$lt_save_ifs" + + # Now substitute the updated list of available tags. + if eval "sed -e 's/^available_tags=.*\$/available_tags=\"$available_tags\"/' \"$ofile\" > \"${ofile}T\""; then + mv "${ofile}T" "$ofile" + chmod +x "$ofile" + else + rm -f "${ofile}T" + { { echo "$as_me:$LINENO: error: unable to update list of available tagged configurations." >&5 +echo "$as_me: error: unable to update list of available tagged configurations." >&2;} + { (exit 1); exit 1; }; } + fi +fi + + + +# This can be used to rebuild libtool when needed +LIBTOOL_DEPS="$ac_aux_dir/ltmain.sh" + +# Always use our own libtool. +LIBTOOL='$(SHELL) $(top_builddir)/libtool' + +# Prevent multiple expansion + + + + + + + + + + + + + + + + + + + + + +echo "$as_me:$LINENO: checking whether byte ordering is bigendian" >&5 +echo $ECHO_N "checking whether byte ordering is bigendian... $ECHO_C" >&6 +if test "${ac_cv_c_bigendian+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + # See if sys/param.h defines the BYTE_ORDER macro. +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +#include + +int +main () +{ +#if !BYTE_ORDER || !BIG_ENDIAN || !LITTLE_ENDIAN + bogus endian macros +#endif + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest.$ac_objext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + # It does; now see whether it defined to BIG_ENDIAN or not. +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +#include + +int +main () +{ +#if BYTE_ORDER != BIG_ENDIAN + not big endian +#endif + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest.$ac_objext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_c_bigendian=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_cv_c_bigendian=no +fi +rm -f conftest.err conftest.$ac_objext conftest.$ac_ext +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +# It does not; compile a test program. +if test "$cross_compiling" = yes; then + # try to guess the endianness by grepping values into an object file + ac_cv_c_bigendian=unknown + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +short ascii_mm[] = { 0x4249, 0x4765, 0x6E44, 0x6961, 0x6E53, 0x7953, 0 }; +short ascii_ii[] = { 0x694C, 0x5454, 0x656C, 0x6E45, 0x6944, 0x6E61, 0 }; +void _ascii () { char *s = (char *) ascii_mm; s = (char *) ascii_ii; } +short ebcdic_ii[] = { 0x89D3, 0xE3E3, 0x8593, 0x95C5, 0x89C4, 0x9581, 0 }; +short ebcdic_mm[] = { 0xC2C9, 0xC785, 0x95C4, 0x8981, 0x95E2, 0xA8E2, 0 }; +void _ebcdic () { char *s = (char *) ebcdic_mm; s = (char *) ebcdic_ii; } +int +main () +{ + _ascii (); _ebcdic (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest.$ac_objext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + if grep BIGenDianSyS conftest.$ac_objext >/dev/null ; then + ac_cv_c_bigendian=yes +fi +if grep LiTTleEnDian conftest.$ac_objext >/dev/null ; then + if test "$ac_cv_c_bigendian" = unknown; then + ac_cv_c_bigendian=no + else + # finding both strings is unlikely to happen, but who knows? + ac_cv_c_bigendian=unknown + fi +fi +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +fi +rm -f conftest.err conftest.$ac_objext conftest.$ac_ext +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +int +main () +{ + /* Are we little or big endian? From Harbison&Steele. */ + union + { + long l; + char c[sizeof (long)]; + } u; + u.l = 1; + exit (u.c[sizeof (long) - 1] == 1); +} +_ACEOF +rm -f conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { ac_try='./conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_c_bigendian=no +else + echo "$as_me: program exited with status $ac_status" >&5 +echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +( exit $ac_status ) +ac_cv_c_bigendian=yes +fi +rm -f core *.core gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +fi +fi +rm -f conftest.err conftest.$ac_objext conftest.$ac_ext +fi +echo "$as_me:$LINENO: result: $ac_cv_c_bigendian" >&5 +echo "${ECHO_T}$ac_cv_c_bigendian" >&6 +case $ac_cv_c_bigendian in + yes) + +cat >>confdefs.h <<\_ACEOF +#define WORDS_BIGENDIAN 1 +_ACEOF + ;; + no) + ;; + *) + { { echo "$as_me:$LINENO: error: unknown endianness +presetting ac_cv_c_bigendian=no (or yes) will help" >&5 +echo "$as_me: error: unknown endianness +presetting ac_cv_c_bigendian=no (or yes) will help" >&2;} + { (exit 1); exit 1; }; } ;; +esac + + + +for ac_header in sys/soundcard.h sys/audioio.h +do +as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` +if eval "test \"\${$as_ac_Header+set}\" = set"; then + echo "$as_me:$LINENO: checking for $ac_header" >&5 +echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6 +if eval "test \"\${$as_ac_Header+set}\" = set"; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +fi +echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5 +echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6 +else + # Is the header compilable? +echo "$as_me:$LINENO: checking $ac_header usability" >&5 +echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6 +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +#include <$ac_header> +_ACEOF +rm -f conftest.$ac_objext +if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest.$ac_objext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_header_compiler=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_header_compiler=no +fi +rm -f conftest.err conftest.$ac_objext conftest.$ac_ext +echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 +echo "${ECHO_T}$ac_header_compiler" >&6 + +# Is the header present? +echo "$as_me:$LINENO: checking $ac_header presence" >&5 +echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6 +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include <$ac_header> +_ACEOF +if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5 + (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } >/dev/null; then + if test -s conftest.err; then + ac_cpp_err=$ac_c_preproc_warn_flag + ac_cpp_err=$ac_cpp_err$ac_c_werror_flag + else + ac_cpp_err= + fi +else + ac_cpp_err=yes +fi +if test -z "$ac_cpp_err"; then + ac_header_preproc=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_header_preproc=no +fi +rm -f conftest.err conftest.$ac_ext +echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 +echo "${ECHO_T}$ac_header_preproc" >&6 + +# So? What about this header? +case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in + yes:no: ) + { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5 +echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5 +echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;} + ac_header_preproc=yes + ;; + no:yes:* ) + { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5 +echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5 +echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5 +echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5 +echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5 +echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5 +echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;} + ( + cat <<\_ASBOX +## ------------------------------------------ ## +## Report this to the AC_PACKAGE_NAME lists. ## +## ------------------------------------------ ## +_ASBOX + ) | + sed "s/^/$as_me: WARNING: /" >&2 + ;; +esac +echo "$as_me:$LINENO: checking for $ac_header" >&5 +echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6 +if eval "test \"\${$as_ac_Header+set}\" = set"; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + eval "$as_ac_Header=\$ac_header_preproc" +fi +echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5 +echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6 + +fi +if test `eval echo '${'$as_ac_Header'}'` = yes; then + cat >>confdefs.h <<_ACEOF +#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +fi + +done + + +# Check whether --enable-ogg or --disable-ogg was given. +if test "${enable_ogg+set}" = set; then + enableval="$enable_ogg" + case "${enableval}" in + yes) useogg=true ;; + no) useogg=false ;; + *) { { echo "$as_me:$LINENO: error: bad value ${enableval} for --enable-ogg" >&5 +echo "$as_me: error: bad value ${enableval} for --enable-ogg" >&2;} + { (exit 1); exit 1; }; } ;; + esac +else + useogg=true +fi; + +if test x$useogg = xtrue; then + +OGG_LIBS="-logg" + +echo "$as_me:$LINENO: checking for libogg" >&5 +echo $ECHO_N "checking for libogg... $ECHO_C" >&6 + +ac_ogg_includes=NONE ac_ogg_libraries=NONE ac_ogg_bindir=NONE +ogg_libraries="" +ogg_includes="" + +# Check whether --with-ogg-dir or --without-ogg-dir was given. +if test "${with_ogg_dir+set}" = set; then + withval="$with_ogg_dir" + ac_ogg_includes="$withval"/include + ac_ogg_libraries="$withval"/lib + +fi; + + +# Check whether --with-ogg-includes or --without-ogg-includes was given. +if test "${with_ogg_includes+set}" = set; then + withval="$with_ogg_includes" + + ac_ogg_includes="$withval" + +fi; + +ogg_libs_given=no + + +# Check whether --with-ogg-libraries or --without-ogg-libraries was given. +if test "${with_ogg_libraries+set}" = set; then + withval="$with_ogg_libraries" + ac_ogg_libraries="$withval" + ogg_libs_given=yes + +fi; + +ogg_incdirs="/usr/include /usr/lib/ogg/include /opt/include /usr/local/ogg/include /usr/include/ogg /usr/include /usr/local/include" +if test ! "$ac_ogg_includes" = "NONE"; then + ogg_incdirs="$ac_ogg_includes $ac_ogg_includes/.. $ogg_incdirs" +fi + +ogg_incdir=NONE +for i in $ogg_incdirs; +do + for j in ogg/ogg.h; + do + if test -r "$i/$j"; then + ogg_incdir=$i + break 2 + fi + done +done + +echo "Ogg includes in $ogg_incdir" + + +ogg_libdirs="$ac_ogg_libraries /usr/lib/ogg/lib /usr/lib /opt/lib /usr/local/ogg/lib /usr/local/lib /usr/lib/ogg /usr/local/lib" +test -n "$OGGDIR" && ogg_libdirs="$OGGDIR/lib $OGGDIR $ogg_libdirs" +if test ! "$ac_ogg_libraries" = "NONE"; then + ogg_libdirs="$ac_ogg_libraries $ogg_libdirs" +fi + +test=NONE +ogg_libdir=NONE +for dir in $ogg_libdirs; do + try="ls -1 $dir/libogg*" + if test=`eval $try 2> /dev/null`; then ogg_libdir=$dir; break; else echo "tried $dir" >&5 ; fi +done + +echo "Ogg libraries in $ogg_libdir" + +if test "$ogg_libdir" = "NONE" || test "$ogg_incdir" = "NONE"; then + have_libogg=no +else + have_libogg=yes + cat >>confdefs.h <<\_ACEOF +#define HAVE_LIBOGG 1 +_ACEOF + +fi + +OGG_INCLUDES="-I$ogg_incdir" +OGG_LDFLAGS="-L$ogg_libdir" + + + + + + + +fi + +if test "$have_libogg" = yes; then + src=src +else + src= +fi + + + +echo "$as_me:$LINENO: checking for sin in -lm" >&5 +echo $ECHO_N "checking for sin in -lm... $ECHO_C" >&6 +if test "${ac_cv_lib_m_sin+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lm $LIBS" +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any gcc2 internal prototype to avoid an error. */ +#ifdef __cplusplus +extern "C" +#endif +/* We use char because int might match the return type of a gcc2 + builtin and then its argument prototype would still apply. */ +char sin (); +int +main () +{ +sin (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_lib_m_sin=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_cv_lib_m_sin=no +fi +rm -f conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +echo "$as_me:$LINENO: result: $ac_cv_lib_m_sin" >&5 +echo "${ECHO_T}$ac_cv_lib_m_sin" >&6 +if test $ac_cv_lib_m_sin = yes; then + cat >>confdefs.h <<_ACEOF +#define HAVE_LIBM 1 +_ACEOF + + LIBS="-lm $LIBS" + +fi + + +echo "$as_me:$LINENO: checking for getopt_long in -lgnugetopt" >&5 +echo $ECHO_N "checking for getopt_long in -lgnugetopt... $ECHO_C" >&6 +if test "${ac_cv_lib_gnugetopt_getopt_long+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lgnugetopt $LIBS" +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any gcc2 internal prototype to avoid an error. */ +#ifdef __cplusplus +extern "C" +#endif +/* We use char because int might match the return type of a gcc2 + builtin and then its argument prototype would still apply. */ +char getopt_long (); +int +main () +{ +getopt_long (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest$ac_exeext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_lib_gnugetopt_getopt_long=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_cv_lib_gnugetopt_getopt_long=no +fi +rm -f conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +echo "$as_me:$LINENO: result: $ac_cv_lib_gnugetopt_getopt_long" >&5 +echo "${ECHO_T}$ac_cv_lib_gnugetopt_getopt_long" >&6 +if test $ac_cv_lib_gnugetopt_getopt_long = yes; then + cat >>confdefs.h <<_ACEOF +#define HAVE_LIBGNUGETOPT 1 +_ACEOF + + LIBS="-lgnugetopt $LIBS" + +fi + + +cat >>confdefs.h <<_ACEOF +#define SPEEX_VERSION "${SPEEX_VERSION}" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define SPEEX_MAJOR_VERSION ${SPEEX_MAJOR_VERSION} +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define SPEEX_MINOR_VERSION ${SPEEX_MINOR_VERSION} +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define SPEEX_MICRO_VERSION ${SPEEX_MICRO_VERSION} +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define SPEEX_EXTRA_VERSION "${SPEEX_EXTRA_VERSION}" +_ACEOF + + + +# Check whether --enable-sse or --disable-sse was given. +if test "${enable_sse+set}" = set; then + enableval="$enable_sse" + if test "$enableval" = yes; then cat >>confdefs.h <<\_ACEOF +#define _USE_SSE 1 +_ACEOF + fi +fi; + + + ac_config_files="$ac_config_files Makefile libspeex/Makefile src/Makefile doc/Makefile Speex.spec include/Makefile include/speex/Makefile speex.pc win32/Makefile win32/libspeex/Makefile win32/speexenc/Makefile win32/speexdec/Makefile" +cat >confcache <<\_ACEOF +# This file is a shell script that caches the results of configure +# tests run on this system so they can be shared between configure +# scripts and configure runs, see configure's option --config-cache. +# It is not useful on other systems. If it contains results you don't +# want to keep, you may remove or edit it. +# +# config.status only pays attention to the cache file if you give it +# the --recheck option to rerun configure. +# +# `ac_cv_env_foo' variables (set or unset) will be overridden when +# loading this file, other *unset* `ac_cv_foo' will be assigned the +# following values. + +_ACEOF + +# The following way of writing the cache mishandles newlines in values, +# but we know of no workaround that is simple, portable, and efficient. +# So, don't put newlines in cache variables' values. +# Ultrix sh set writes to stderr and can't be redirected directly, +# and sets the high bit in the cache file unless we assign to the vars. +{ + (set) 2>&1 | + case `(ac_space=' '; set | grep ac_space) 2>&1` in + *ac_space=\ *) + # `set' does not quote correctly, so add quotes (double-quote + # substitution turns \\\\ into \\, and sed turns \\ into \). + sed -n \ + "s/'/'\\\\''/g; + s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" + ;; + *) + # `set' quotes correctly as required by POSIX, so do not add quotes. + sed -n \ + "s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1=\\2/p" + ;; + esac; +} | + sed ' + t clear + : clear + s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/ + t end + /^ac_cv_env/!s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/ + : end' >>confcache +if diff $cache_file confcache >/dev/null 2>&1; then :; else + if test -w $cache_file; then + test "x$cache_file" != "x/dev/null" && echo "updating cache $cache_file" + cat confcache >$cache_file + else + echo "not updating unwritable cache $cache_file" + fi +fi +rm -f confcache + +test "x$prefix" = xNONE && prefix=$ac_default_prefix +# Let make expand exec_prefix. +test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' + +# VPATH may cause trouble with some makes, so we remove $(srcdir), +# ${srcdir} and @srcdir@ from VPATH if srcdir is ".", strip leading and +# trailing colons and then remove the whole line if VPATH becomes empty +# (actually we leave an empty line to preserve line numbers). +if test "x$srcdir" = x.; then + ac_vpsub='/^[ ]*VPATH[ ]*=/{ +s/:*\$(srcdir):*/:/; +s/:*\${srcdir}:*/:/; +s/:*@srcdir@:*/:/; +s/^\([^=]*=[ ]*\):*/\1/; +s/:*$//; +s/^[^=]*=[ ]*$//; +}' +fi + +# Transform confdefs.h into DEFS. +# Protect against shell expansion while executing Makefile rules. +# Protect against Makefile macro expansion. +# +# If the first sed substitution is executed (which looks for macros that +# take arguments), then we branch to the quote section. Otherwise, +# look for a macro that doesn't take arguments. +cat >confdef2opt.sed <<\_ACEOF +t clear +: clear +s,^[ ]*#[ ]*define[ ][ ]*\([^ (][^ (]*([^)]*)\)[ ]*\(.*\),-D\1=\2,g +t quote +s,^[ ]*#[ ]*define[ ][ ]*\([^ ][^ ]*\)[ ]*\(.*\),-D\1=\2,g +t quote +d +: quote +s,[ `~#$^&*(){}\\|;'"<>?],\\&,g +s,\[,\\&,g +s,\],\\&,g +s,\$,$$,g +p +_ACEOF +# We use echo to avoid assuming a particular line-breaking character. +# The extra dot is to prevent the shell from consuming trailing +# line-breaks from the sub-command output. A line-break within +# single-quotes doesn't work because, if this script is created in a +# platform that uses two characters for line-breaks (e.g., DOS), tr +# would break. +ac_LF_and_DOT=`echo; echo .` +DEFS=`sed -n -f confdef2opt.sed confdefs.h | tr "$ac_LF_and_DOT" ' .'` +rm -f confdef2opt.sed + + +ac_libobjs= +ac_ltlibobjs= +for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue + # 1. Remove the extension, and $U if already installed. + ac_i=`echo "$ac_i" | + sed 's/\$U\././;s/\.o$//;s/\.obj$//'` + # 2. Add them. + ac_libobjs="$ac_libobjs $ac_i\$U.$ac_objext" + ac_ltlibobjs="$ac_ltlibobjs $ac_i"'$U.lo' +done +LIBOBJS=$ac_libobjs + +LTLIBOBJS=$ac_ltlibobjs + + +if test -z "${MAINTAINER_MODE_TRUE}" && test -z "${MAINTAINER_MODE_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"MAINTAINER_MODE\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"MAINTAINER_MODE\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${AMDEP_TRUE}" && test -z "${AMDEP_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"AMDEP\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"AMDEP\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${am__fastdepCC_TRUE}" && test -z "${am__fastdepCC_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"am__fastdepCC\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"am__fastdepCC\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi +if test -z "${am__fastdepCXX_TRUE}" && test -z "${am__fastdepCXX_FALSE}"; then + { { echo "$as_me:$LINENO: error: conditional \"am__fastdepCXX\" was never defined. +Usually this means the macro was only invoked conditionally." >&5 +echo "$as_me: error: conditional \"am__fastdepCXX\" was never defined. +Usually this means the macro was only invoked conditionally." >&2;} + { (exit 1); exit 1; }; } +fi + +: ${CONFIG_STATUS=./config.status} +ac_clean_files_save=$ac_clean_files +ac_clean_files="$ac_clean_files $CONFIG_STATUS" +{ echo "$as_me:$LINENO: creating $CONFIG_STATUS" >&5 +echo "$as_me: creating $CONFIG_STATUS" >&6;} +cat >$CONFIG_STATUS <<_ACEOF +#! $SHELL +# Generated by $as_me. +# Run this file to recreate the current configuration. +# Compiler output produced by configure, useful for debugging +# configure, is in config.log if it exists. + +debug=false +ac_cs_recheck=false +ac_cs_silent=false +SHELL=\${CONFIG_SHELL-$SHELL} +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF +## --------------------- ## +## M4sh Initialization. ## +## --------------------- ## + +# Be Bourne compatible +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then + emulate sh + NULLCMD=: + # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' +elif test -n "${BASH_VERSION+set}" && (set -o posix) >/dev/null 2>&1; then + set -o posix +fi +DUALCASE=1; export DUALCASE # for MKS sh + +# Support unset when possible. +if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then + as_unset=unset +else + as_unset=false +fi + + +# Work around bugs in pre-3.0 UWIN ksh. +$as_unset ENV MAIL MAILPATH +PS1='$ ' +PS2='> ' +PS4='+ ' + +# NLS nuisances. +for as_var in \ + LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \ + LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \ + LC_TELEPHONE LC_TIME +do + if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then + eval $as_var=C; export $as_var + else + $as_unset $as_var + fi +done + +# Required to use basename. +if expr a : '\(a\)' >/dev/null 2>&1; then + as_expr=expr +else + as_expr=false +fi + +if (basename /) >/dev/null 2>&1 && test "X`basename / 2>&1`" = "X/"; then + as_basename=basename +else + as_basename=false +fi + + +# Name of the executable. +as_me=`$as_basename "$0" || +$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ + X"$0" : 'X\(//\)$' \| \ + X"$0" : 'X\(/\)$' \| \ + . : '\(.\)' 2>/dev/null || +echo X/"$0" | + sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/; q; } + /^X\/\(\/\/\)$/{ s//\1/; q; } + /^X\/\(\/\).*/{ s//\1/; q; } + s/.*/./; q'` + + +# PATH needs CR, and LINENO needs CR and PATH. +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits + +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + echo "#! /bin/sh" >conf$$.sh + echo "exit 0" >>conf$$.sh + chmod +x conf$$.sh + if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then + PATH_SEPARATOR=';' + else + PATH_SEPARATOR=: + fi + rm -f conf$$.sh +fi + + + as_lineno_1=$LINENO + as_lineno_2=$LINENO + as_lineno_3=`(expr $as_lineno_1 + 1) 2>/dev/null` + test "x$as_lineno_1" != "x$as_lineno_2" && + test "x$as_lineno_3" = "x$as_lineno_2" || { + # Find who we are. Look in the path if we contain no path at all + # relative or not. + case $0 in + *[\\/]* ) as_myself=$0 ;; + *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break +done + + ;; + esac + # We did not find ourselves, most probably we were run as `sh COMMAND' + # in which case we are not to be found in the path. + if test "x$as_myself" = x; then + as_myself=$0 + fi + if test ! -f "$as_myself"; then + { { echo "$as_me:$LINENO: error: cannot find myself; rerun with an absolute path" >&5 +echo "$as_me: error: cannot find myself; rerun with an absolute path" >&2;} + { (exit 1); exit 1; }; } + fi + case $CONFIG_SHELL in + '') + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for as_base in sh bash ksh sh5; do + case $as_dir in + /*) + if ("$as_dir/$as_base" -c ' + as_lineno_1=$LINENO + as_lineno_2=$LINENO + as_lineno_3=`(expr $as_lineno_1 + 1) 2>/dev/null` + test "x$as_lineno_1" != "x$as_lineno_2" && + test "x$as_lineno_3" = "x$as_lineno_2" ') 2>/dev/null; then + $as_unset BASH_ENV || test "${BASH_ENV+set}" != set || { BASH_ENV=; export BASH_ENV; } + $as_unset ENV || test "${ENV+set}" != set || { ENV=; export ENV; } + CONFIG_SHELL=$as_dir/$as_base + export CONFIG_SHELL + exec "$CONFIG_SHELL" "$0" ${1+"$@"} + fi;; + esac + done +done +;; + esac + + # Create $as_me.lineno as a copy of $as_myself, but with $LINENO + # uniformly replaced by the line number. The first 'sed' inserts a + # line-number line before each line; the second 'sed' does the real + # work. The second script uses 'N' to pair each line-number line + # with the numbered line, and appends trailing '-' during + # substitution so that $LINENO is not a special case at line end. + # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the + # second 'sed' script. Blame Lee E. McMahon for sed's syntax. :-) + sed '=' <$as_myself | + sed ' + N + s,$,-, + : loop + s,^\(['$as_cr_digits']*\)\(.*\)[$]LINENO\([^'$as_cr_alnum'_]\),\1\2\1\3, + t loop + s,-$,, + s,^['$as_cr_digits']*\n,, + ' >$as_me.lineno && + chmod +x $as_me.lineno || + { { echo "$as_me:$LINENO: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&5 +echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2;} + { (exit 1); exit 1; }; } + + # Don't try to exec as it changes $[0], causing all sort of problems + # (the dirname of $[0] is not the place where we might find the + # original and so on. Autoconf is especially sensible to this). + . ./$as_me.lineno + # Exit status is that of the last command. + exit +} + + +case `echo "testing\c"; echo 1,2,3`,`echo -n testing; echo 1,2,3` in + *c*,-n*) ECHO_N= ECHO_C=' +' ECHO_T=' ' ;; + *c*,* ) ECHO_N=-n ECHO_C= ECHO_T= ;; + *) ECHO_N= ECHO_C='\c' ECHO_T= ;; +esac + +if expr a : '\(a\)' >/dev/null 2>&1; then + as_expr=expr +else + as_expr=false +fi + +rm -f conf$$ conf$$.exe conf$$.file +echo >conf$$.file +if ln -s conf$$.file conf$$ 2>/dev/null; then + # We could just check for DJGPP; but this test a) works b) is more generic + # and c) will remain valid once DJGPP supports symlinks (DJGPP 2.04). + if test -f conf$$.exe; then + # Don't use ln at all; we don't have any links + as_ln_s='cp -p' + else + as_ln_s='ln -s' + fi +elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln +else + as_ln_s='cp -p' +fi +rm -f conf$$ conf$$.exe conf$$.file + +if mkdir -p . 2>/dev/null; then + as_mkdir_p=: +else + test -d ./-p && rmdir ./-p + as_mkdir_p=false +fi + +as_executable_p="test -f" + +# Sed expression to map a string onto a valid CPP name. +as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" + +# Sed expression to map a string onto a valid variable name. +as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" + + +# IFS +# We need space, tab and new line, in precisely that order. +as_nl=' +' +IFS=" $as_nl" + +# CDPATH. +$as_unset CDPATH + +exec 6>&1 + +# Open the log real soon, to keep \$[0] and so on meaningful, and to +# report actual input values of CONFIG_FILES etc. instead of their +# values after options handling. Logging --version etc. is OK. +exec 5>>config.log +{ + echo + sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX +## Running $as_me. ## +_ASBOX +} >&5 +cat >&5 <<_CSEOF + +This file was extended by $as_me, which was +generated by GNU Autoconf 2.59. Invocation command line was + + CONFIG_FILES = $CONFIG_FILES + CONFIG_HEADERS = $CONFIG_HEADERS + CONFIG_LINKS = $CONFIG_LINKS + CONFIG_COMMANDS = $CONFIG_COMMANDS + $ $0 $@ + +_CSEOF +echo "on `(hostname || uname -n) 2>/dev/null | sed 1q`" >&5 +echo >&5 +_ACEOF + +# Files that config.status was made for. +if test -n "$ac_config_files"; then + echo "config_files=\"$ac_config_files\"" >>$CONFIG_STATUS +fi + +if test -n "$ac_config_headers"; then + echo "config_headers=\"$ac_config_headers\"" >>$CONFIG_STATUS +fi + +if test -n "$ac_config_links"; then + echo "config_links=\"$ac_config_links\"" >>$CONFIG_STATUS +fi + +if test -n "$ac_config_commands"; then + echo "config_commands=\"$ac_config_commands\"" >>$CONFIG_STATUS +fi + +cat >>$CONFIG_STATUS <<\_ACEOF + +ac_cs_usage="\ +\`$as_me' instantiates files from templates according to the +current configuration. + +Usage: $0 [OPTIONS] [FILE]... + + -h, --help print this help, then exit + -V, --version print version number, then exit + -q, --quiet do not print progress messages + -d, --debug don't remove temporary files + --recheck update $as_me by reconfiguring in the same conditions + --file=FILE[:TEMPLATE] + instantiate the configuration file FILE + +Configuration files: +$config_files + +Configuration commands: +$config_commands + +Report bugs to ." +_ACEOF + +cat >>$CONFIG_STATUS <<_ACEOF +ac_cs_version="\\ +config.status +configured by $0, generated by GNU Autoconf 2.59, + with options \\"`echo "$ac_configure_args" | sed 's/[\\""\`\$]/\\\\&/g'`\\" + +Copyright (C) 2003 Free Software Foundation, Inc. +This config.status script is free software; the Free Software Foundation +gives unlimited permission to copy, distribute and modify it." +srcdir=$srcdir +INSTALL="$INSTALL" +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF +# If no file are specified by the user, then we need to provide default +# value. By we need to know if files were specified by the user. +ac_need_defaults=: +while test $# != 0 +do + case $1 in + --*=*) + ac_option=`expr "x$1" : 'x\([^=]*\)='` + ac_optarg=`expr "x$1" : 'x[^=]*=\(.*\)'` + ac_shift=: + ;; + -*) + ac_option=$1 + ac_optarg=$2 + ac_shift=shift + ;; + *) # This is not an option, so the user has probably given explicit + # arguments. + ac_option=$1 + ac_need_defaults=false;; + esac + + case $ac_option in + # Handling of the options. +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF + -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) + ac_cs_recheck=: ;; + --version | --vers* | -V ) + echo "$ac_cs_version"; exit 0 ;; + --he | --h) + # Conflict between --help and --header + { { echo "$as_me:$LINENO: error: ambiguous option: $1 +Try \`$0 --help' for more information." >&5 +echo "$as_me: error: ambiguous option: $1 +Try \`$0 --help' for more information." >&2;} + { (exit 1); exit 1; }; };; + --help | --hel | -h ) + echo "$ac_cs_usage"; exit 0 ;; + --debug | --d* | -d ) + debug=: ;; + --file | --fil | --fi | --f ) + $ac_shift + CONFIG_FILES="$CONFIG_FILES $ac_optarg" + ac_need_defaults=false;; + --header | --heade | --head | --hea ) + $ac_shift + CONFIG_HEADERS="$CONFIG_HEADERS $ac_optarg" + ac_need_defaults=false;; + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil | --si | --s) + ac_cs_silent=: ;; + + # This is an error. + -*) { { echo "$as_me:$LINENO: error: unrecognized option: $1 +Try \`$0 --help' for more information." >&5 +echo "$as_me: error: unrecognized option: $1 +Try \`$0 --help' for more information." >&2;} + { (exit 1); exit 1; }; } ;; + + *) ac_config_targets="$ac_config_targets $1" ;; + + esac + shift +done + +ac_configure_extra_args= + +if $ac_cs_silent; then + exec 6>/dev/null + ac_configure_extra_args="$ac_configure_extra_args --silent" +fi + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF +if \$ac_cs_recheck; then + echo "running $SHELL $0 " $ac_configure_args \$ac_configure_extra_args " --no-create --no-recursion" >&6 + exec $SHELL $0 $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion +fi + +_ACEOF + +cat >>$CONFIG_STATUS <<_ACEOF +# +# INIT-COMMANDS section. +# + +AMDEP_TRUE="$AMDEP_TRUE" ac_aux_dir="$ac_aux_dir" + +_ACEOF + + + +cat >>$CONFIG_STATUS <<\_ACEOF +for ac_config_target in $ac_config_targets +do + case "$ac_config_target" in + # Handling of arguments. + "Makefile" ) CONFIG_FILES="$CONFIG_FILES Makefile" ;; + "libspeex/Makefile" ) CONFIG_FILES="$CONFIG_FILES libspeex/Makefile" ;; + "src/Makefile" ) CONFIG_FILES="$CONFIG_FILES src/Makefile" ;; + "doc/Makefile" ) CONFIG_FILES="$CONFIG_FILES doc/Makefile" ;; + "Speex.spec" ) CONFIG_FILES="$CONFIG_FILES Speex.spec" ;; + "include/Makefile" ) CONFIG_FILES="$CONFIG_FILES include/Makefile" ;; + "include/speex/Makefile" ) CONFIG_FILES="$CONFIG_FILES include/speex/Makefile" ;; + "speex.pc" ) CONFIG_FILES="$CONFIG_FILES speex.pc" ;; + "win32/Makefile" ) CONFIG_FILES="$CONFIG_FILES win32/Makefile" ;; + "win32/libspeex/Makefile" ) CONFIG_FILES="$CONFIG_FILES win32/libspeex/Makefile" ;; + "win32/speexenc/Makefile" ) CONFIG_FILES="$CONFIG_FILES win32/speexenc/Makefile" ;; + "win32/speexdec/Makefile" ) CONFIG_FILES="$CONFIG_FILES win32/speexdec/Makefile" ;; + "depfiles" ) CONFIG_COMMANDS="$CONFIG_COMMANDS depfiles" ;; + *) { { echo "$as_me:$LINENO: error: invalid argument: $ac_config_target" >&5 +echo "$as_me: error: invalid argument: $ac_config_target" >&2;} + { (exit 1); exit 1; }; };; + esac +done + +# If the user did not use the arguments to specify the items to instantiate, +# then the envvar interface is used. Set only those that are not. +# We use the long form for the default assignment because of an extremely +# bizarre bug on SunOS 4.1.3. +if $ac_need_defaults; then + test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files + test "${CONFIG_COMMANDS+set}" = set || CONFIG_COMMANDS=$config_commands +fi + +# Have a temporary directory for convenience. Make it in the build tree +# simply because there is no reason to put it here, and in addition, +# creating and moving files from /tmp can sometimes cause problems. +# Create a temporary directory, and hook for its removal unless debugging. +$debug || +{ + trap 'exit_status=$?; rm -rf $tmp && exit $exit_status' 0 + trap '{ (exit 1); exit 1; }' 1 2 13 15 +} + +# Create a (secure) tmp directory for tmp files. + +{ + tmp=`(umask 077 && mktemp -d -q "./confstatXXXXXX") 2>/dev/null` && + test -n "$tmp" && test -d "$tmp" +} || +{ + tmp=./confstat$$-$RANDOM + (umask 077 && mkdir $tmp) +} || +{ + echo "$me: cannot create a temporary directory in ." >&2 + { (exit 1); exit 1; } +} + +_ACEOF + +cat >>$CONFIG_STATUS <<_ACEOF + +# +# CONFIG_FILES section. +# + +# No need to generate the scripts if there are no CONFIG_FILES. +# This happens for instance when ./config.status config.h +if test -n "\$CONFIG_FILES"; then + # Protect against being on the right side of a sed subst in config.status. + sed 's/,@/@@/; s/@,/@@/; s/,;t t\$/@;t t/; /@;t t\$/s/[\\\\&,]/\\\\&/g; + s/@@/,@/; s/@@/@,/; s/@;t t\$/,;t t/' >\$tmp/subs.sed <<\\CEOF +s,@SHELL@,$SHELL,;t t +s,@PATH_SEPARATOR@,$PATH_SEPARATOR,;t t +s,@PACKAGE_NAME@,$PACKAGE_NAME,;t t +s,@PACKAGE_TARNAME@,$PACKAGE_TARNAME,;t t +s,@PACKAGE_VERSION@,$PACKAGE_VERSION,;t t +s,@PACKAGE_STRING@,$PACKAGE_STRING,;t t +s,@PACKAGE_BUGREPORT@,$PACKAGE_BUGREPORT,;t t +s,@exec_prefix@,$exec_prefix,;t t +s,@prefix@,$prefix,;t t +s,@program_transform_name@,$program_transform_name,;t t +s,@bindir@,$bindir,;t t +s,@sbindir@,$sbindir,;t t +s,@libexecdir@,$libexecdir,;t t +s,@datadir@,$datadir,;t t +s,@sysconfdir@,$sysconfdir,;t t +s,@sharedstatedir@,$sharedstatedir,;t t +s,@localstatedir@,$localstatedir,;t t +s,@libdir@,$libdir,;t t +s,@includedir@,$includedir,;t t +s,@oldincludedir@,$oldincludedir,;t t +s,@infodir@,$infodir,;t t +s,@mandir@,$mandir,;t t +s,@build_alias@,$build_alias,;t t +s,@host_alias@,$host_alias,;t t +s,@target_alias@,$target_alias,;t t +s,@DEFS@,$DEFS,;t t +s,@ECHO_C@,$ECHO_C,;t t +s,@ECHO_N@,$ECHO_N,;t t +s,@ECHO_T@,$ECHO_T,;t t +s,@LIBS@,$LIBS,;t t +s,@SPEEX_LT_CURRENT@,$SPEEX_LT_CURRENT,;t t +s,@SPEEX_LT_REVISION@,$SPEEX_LT_REVISION,;t t +s,@SPEEX_LT_AGE@,$SPEEX_LT_AGE,;t t +s,@SPEEX_VERSION@,$SPEEX_VERSION,;t t +s,@INSTALL_PROGRAM@,$INSTALL_PROGRAM,;t t +s,@INSTALL_SCRIPT@,$INSTALL_SCRIPT,;t t +s,@INSTALL_DATA@,$INSTALL_DATA,;t t +s,@CYGPATH_W@,$CYGPATH_W,;t t +s,@PACKAGE@,$PACKAGE,;t t +s,@VERSION@,$VERSION,;t t +s,@ACLOCAL@,$ACLOCAL,;t t +s,@AUTOCONF@,$AUTOCONF,;t t +s,@AUTOMAKE@,$AUTOMAKE,;t t +s,@AUTOHEADER@,$AUTOHEADER,;t t +s,@MAKEINFO@,$MAKEINFO,;t t +s,@AMTAR@,$AMTAR,;t t +s,@install_sh@,$install_sh,;t t +s,@STRIP@,$STRIP,;t t +s,@ac_ct_STRIP@,$ac_ct_STRIP,;t t +s,@INSTALL_STRIP_PROGRAM@,$INSTALL_STRIP_PROGRAM,;t t +s,@mkdir_p@,$mkdir_p,;t t +s,@AWK@,$AWK,;t t +s,@SET_MAKE@,$SET_MAKE,;t t +s,@am__leading_dot@,$am__leading_dot,;t t +s,@MAINTAINER_MODE_TRUE@,$MAINTAINER_MODE_TRUE,;t t +s,@MAINTAINER_MODE_FALSE@,$MAINTAINER_MODE_FALSE,;t t +s,@MAINT@,$MAINT,;t t +s,@build@,$build,;t t +s,@build_cpu@,$build_cpu,;t t +s,@build_vendor@,$build_vendor,;t t +s,@build_os@,$build_os,;t t +s,@host@,$host,;t t +s,@host_cpu@,$host_cpu,;t t +s,@host_vendor@,$host_vendor,;t t +s,@host_os@,$host_os,;t t +s,@CC@,$CC,;t t +s,@CFLAGS@,$CFLAGS,;t t +s,@LDFLAGS@,$LDFLAGS,;t t +s,@CPPFLAGS@,$CPPFLAGS,;t t +s,@ac_ct_CC@,$ac_ct_CC,;t t +s,@EXEEXT@,$EXEEXT,;t t +s,@OBJEXT@,$OBJEXT,;t t +s,@DEPDIR@,$DEPDIR,;t t +s,@am__include@,$am__include,;t t +s,@am__quote@,$am__quote,;t t +s,@AMDEP_TRUE@,$AMDEP_TRUE,;t t +s,@AMDEP_FALSE@,$AMDEP_FALSE,;t t +s,@AMDEPBACKSLASH@,$AMDEPBACKSLASH,;t t +s,@CCDEPMODE@,$CCDEPMODE,;t t +s,@am__fastdepCC_TRUE@,$am__fastdepCC_TRUE,;t t +s,@am__fastdepCC_FALSE@,$am__fastdepCC_FALSE,;t t +s,@EGREP@,$EGREP,;t t +s,@LN_S@,$LN_S,;t t +s,@ECHO@,$ECHO,;t t +s,@AR@,$AR,;t t +s,@ac_ct_AR@,$ac_ct_AR,;t t +s,@RANLIB@,$RANLIB,;t t +s,@ac_ct_RANLIB@,$ac_ct_RANLIB,;t t +s,@CPP@,$CPP,;t t +s,@CXX@,$CXX,;t t +s,@CXXFLAGS@,$CXXFLAGS,;t t +s,@ac_ct_CXX@,$ac_ct_CXX,;t t +s,@CXXDEPMODE@,$CXXDEPMODE,;t t +s,@am__fastdepCXX_TRUE@,$am__fastdepCXX_TRUE,;t t +s,@am__fastdepCXX_FALSE@,$am__fastdepCXX_FALSE,;t t +s,@CXXCPP@,$CXXCPP,;t t +s,@F77@,$F77,;t t +s,@FFLAGS@,$FFLAGS,;t t +s,@ac_ct_F77@,$ac_ct_F77,;t t +s,@LIBTOOL@,$LIBTOOL,;t t +s,@OGG_LIBS@,$OGG_LIBS,;t t +s,@OGG_INCLUDES@,$OGG_INCLUDES,;t t +s,@OGG_LDFLAGS@,$OGG_LDFLAGS,;t t +s,@src@,$src,;t t +s,@LIBOBJS@,$LIBOBJS,;t t +s,@LTLIBOBJS@,$LTLIBOBJS,;t t +CEOF + +_ACEOF + + cat >>$CONFIG_STATUS <<\_ACEOF + # Split the substitutions into bite-sized pieces for seds with + # small command number limits, like on Digital OSF/1 and HP-UX. + ac_max_sed_lines=48 + ac_sed_frag=1 # Number of current file. + ac_beg=1 # First line for current file. + ac_end=$ac_max_sed_lines # Line after last line for current file. + ac_more_lines=: + ac_sed_cmds= + while $ac_more_lines; do + if test $ac_beg -gt 1; then + sed "1,${ac_beg}d; ${ac_end}q" $tmp/subs.sed >$tmp/subs.frag + else + sed "${ac_end}q" $tmp/subs.sed >$tmp/subs.frag + fi + if test ! -s $tmp/subs.frag; then + ac_more_lines=false + else + # The purpose of the label and of the branching condition is to + # speed up the sed processing (if there are no `@' at all, there + # is no need to browse any of the substitutions). + # These are the two extra sed commands mentioned above. + (echo ':t + /@[a-zA-Z_][a-zA-Z_0-9]*@/!b' && cat $tmp/subs.frag) >$tmp/subs-$ac_sed_frag.sed + if test -z "$ac_sed_cmds"; then + ac_sed_cmds="sed -f $tmp/subs-$ac_sed_frag.sed" + else + ac_sed_cmds="$ac_sed_cmds | sed -f $tmp/subs-$ac_sed_frag.sed" + fi + ac_sed_frag=`expr $ac_sed_frag + 1` + ac_beg=$ac_end + ac_end=`expr $ac_end + $ac_max_sed_lines` + fi + done + if test -z "$ac_sed_cmds"; then + ac_sed_cmds=cat + fi +fi # test -n "$CONFIG_FILES" + +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF +for ac_file in : $CONFIG_FILES; do test "x$ac_file" = x: && continue + # Support "outfile[:infile[:infile...]]", defaulting infile="outfile.in". + case $ac_file in + - | *:- | *:-:* ) # input from stdin + cat >$tmp/stdin + ac_file_in=`echo "$ac_file" | sed 's,[^:]*:,,'` + ac_file=`echo "$ac_file" | sed 's,:.*,,'` ;; + *:* ) ac_file_in=`echo "$ac_file" | sed 's,[^:]*:,,'` + ac_file=`echo "$ac_file" | sed 's,:.*,,'` ;; + * ) ac_file_in=$ac_file.in ;; + esac + + # Compute @srcdir@, @top_srcdir@, and @INSTALL@ for subdirectories. + ac_dir=`(dirname "$ac_file") 2>/dev/null || +$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$ac_file" : 'X\(//\)[^/]' \| \ + X"$ac_file" : 'X\(//\)$' \| \ + X"$ac_file" : 'X\(/\)' \| \ + . : '\(.\)' 2>/dev/null || +echo X"$ac_file" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; } + /^X\(\/\/\)[^/].*/{ s//\1/; q; } + /^X\(\/\/\)$/{ s//\1/; q; } + /^X\(\/\).*/{ s//\1/; q; } + s/.*/./; q'` + { if $as_mkdir_p; then + mkdir -p "$ac_dir" + else + as_dir="$ac_dir" + as_dirs= + while test ! -d "$as_dir"; do + as_dirs="$as_dir $as_dirs" + as_dir=`(dirname "$as_dir") 2>/dev/null || +$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_dir" : 'X\(//\)[^/]' \| \ + X"$as_dir" : 'X\(//\)$' \| \ + X"$as_dir" : 'X\(/\)' \| \ + . : '\(.\)' 2>/dev/null || +echo X"$as_dir" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; } + /^X\(\/\/\)[^/].*/{ s//\1/; q; } + /^X\(\/\/\)$/{ s//\1/; q; } + /^X\(\/\).*/{ s//\1/; q; } + s/.*/./; q'` + done + test ! -n "$as_dirs" || mkdir $as_dirs + fi || { { echo "$as_me:$LINENO: error: cannot create directory \"$ac_dir\"" >&5 +echo "$as_me: error: cannot create directory \"$ac_dir\"" >&2;} + { (exit 1); exit 1; }; }; } + + ac_builddir=. + +if test "$ac_dir" != .; then + ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'` + # A "../" for each directory in $ac_dir_suffix. + ac_top_builddir=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,../,g'` +else + ac_dir_suffix= ac_top_builddir= +fi + +case $srcdir in + .) # No --srcdir option. We are building in place. + ac_srcdir=. + if test -z "$ac_top_builddir"; then + ac_top_srcdir=. + else + ac_top_srcdir=`echo $ac_top_builddir | sed 's,/$,,'` + fi ;; + [\\/]* | ?:[\\/]* ) # Absolute path. + ac_srcdir=$srcdir$ac_dir_suffix; + ac_top_srcdir=$srcdir ;; + *) # Relative path. + ac_srcdir=$ac_top_builddir$srcdir$ac_dir_suffix + ac_top_srcdir=$ac_top_builddir$srcdir ;; +esac + +# Do not use `cd foo && pwd` to compute absolute paths, because +# the directories may not exist. +case `pwd` in +.) ac_abs_builddir="$ac_dir";; +*) + case "$ac_dir" in + .) ac_abs_builddir=`pwd`;; + [\\/]* | ?:[\\/]* ) ac_abs_builddir="$ac_dir";; + *) ac_abs_builddir=`pwd`/"$ac_dir";; + esac;; +esac +case $ac_abs_builddir in +.) ac_abs_top_builddir=${ac_top_builddir}.;; +*) + case ${ac_top_builddir}. in + .) ac_abs_top_builddir=$ac_abs_builddir;; + [\\/]* | ?:[\\/]* ) ac_abs_top_builddir=${ac_top_builddir}.;; + *) ac_abs_top_builddir=$ac_abs_builddir/${ac_top_builddir}.;; + esac;; +esac +case $ac_abs_builddir in +.) ac_abs_srcdir=$ac_srcdir;; +*) + case $ac_srcdir in + .) ac_abs_srcdir=$ac_abs_builddir;; + [\\/]* | ?:[\\/]* ) ac_abs_srcdir=$ac_srcdir;; + *) ac_abs_srcdir=$ac_abs_builddir/$ac_srcdir;; + esac;; +esac +case $ac_abs_builddir in +.) ac_abs_top_srcdir=$ac_top_srcdir;; +*) + case $ac_top_srcdir in + .) ac_abs_top_srcdir=$ac_abs_builddir;; + [\\/]* | ?:[\\/]* ) ac_abs_top_srcdir=$ac_top_srcdir;; + *) ac_abs_top_srcdir=$ac_abs_builddir/$ac_top_srcdir;; + esac;; +esac + + + case $INSTALL in + [\\/$]* | ?:[\\/]* ) ac_INSTALL=$INSTALL ;; + *) ac_INSTALL=$ac_top_builddir$INSTALL ;; + esac + + # Let's still pretend it is `configure' which instantiates (i.e., don't + # use $as_me), people would be surprised to read: + # /* config.h. Generated by config.status. */ + if test x"$ac_file" = x-; then + configure_input= + else + configure_input="$ac_file. " + fi + configure_input=$configure_input"Generated from `echo $ac_file_in | + sed 's,.*/,,'` by configure." + + # First look for the input files in the build tree, otherwise in the + # src tree. + ac_file_inputs=`IFS=: + for f in $ac_file_in; do + case $f in + -) echo $tmp/stdin ;; + [\\/$]*) + # Absolute (can't be DOS-style, as IFS=:) + test -f "$f" || { { echo "$as_me:$LINENO: error: cannot find input file: $f" >&5 +echo "$as_me: error: cannot find input file: $f" >&2;} + { (exit 1); exit 1; }; } + echo "$f";; + *) # Relative + if test -f "$f"; then + # Build tree + echo "$f" + elif test -f "$srcdir/$f"; then + # Source tree + echo "$srcdir/$f" + else + # /dev/null tree + { { echo "$as_me:$LINENO: error: cannot find input file: $f" >&5 +echo "$as_me: error: cannot find input file: $f" >&2;} + { (exit 1); exit 1; }; } + fi;; + esac + done` || { (exit 1); exit 1; } + + if test x"$ac_file" != x-; then + { echo "$as_me:$LINENO: creating $ac_file" >&5 +echo "$as_me: creating $ac_file" >&6;} + rm -f "$ac_file" + fi +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF + sed "$ac_vpsub +$extrasub +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF +:t +/@[a-zA-Z_][a-zA-Z_0-9]*@/!b +s,@configure_input@,$configure_input,;t t +s,@srcdir@,$ac_srcdir,;t t +s,@abs_srcdir@,$ac_abs_srcdir,;t t +s,@top_srcdir@,$ac_top_srcdir,;t t +s,@abs_top_srcdir@,$ac_abs_top_srcdir,;t t +s,@builddir@,$ac_builddir,;t t +s,@abs_builddir@,$ac_abs_builddir,;t t +s,@top_builddir@,$ac_top_builddir,;t t +s,@abs_top_builddir@,$ac_abs_top_builddir,;t t +s,@INSTALL@,$ac_INSTALL,;t t +" $ac_file_inputs | (eval "$ac_sed_cmds") >$tmp/out + rm -f $tmp/stdin + if test x"$ac_file" != x-; then + mv $tmp/out $ac_file + else + cat $tmp/out + rm -f $tmp/out + fi + +done +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF + +# +# CONFIG_COMMANDS section. +# +for ac_file in : $CONFIG_COMMANDS; do test "x$ac_file" = x: && continue + ac_dest=`echo "$ac_file" | sed 's,:.*,,'` + ac_source=`echo "$ac_file" | sed 's,[^:]*:,,'` + ac_dir=`(dirname "$ac_dest") 2>/dev/null || +$as_expr X"$ac_dest" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$ac_dest" : 'X\(//\)[^/]' \| \ + X"$ac_dest" : 'X\(//\)$' \| \ + X"$ac_dest" : 'X\(/\)' \| \ + . : '\(.\)' 2>/dev/null || +echo X"$ac_dest" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; } + /^X\(\/\/\)[^/].*/{ s//\1/; q; } + /^X\(\/\/\)$/{ s//\1/; q; } + /^X\(\/\).*/{ s//\1/; q; } + s/.*/./; q'` + { if $as_mkdir_p; then + mkdir -p "$ac_dir" + else + as_dir="$ac_dir" + as_dirs= + while test ! -d "$as_dir"; do + as_dirs="$as_dir $as_dirs" + as_dir=`(dirname "$as_dir") 2>/dev/null || +$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_dir" : 'X\(//\)[^/]' \| \ + X"$as_dir" : 'X\(//\)$' \| \ + X"$as_dir" : 'X\(/\)' \| \ + . : '\(.\)' 2>/dev/null || +echo X"$as_dir" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; } + /^X\(\/\/\)[^/].*/{ s//\1/; q; } + /^X\(\/\/\)$/{ s//\1/; q; } + /^X\(\/\).*/{ s//\1/; q; } + s/.*/./; q'` + done + test ! -n "$as_dirs" || mkdir $as_dirs + fi || { { echo "$as_me:$LINENO: error: cannot create directory \"$ac_dir\"" >&5 +echo "$as_me: error: cannot create directory \"$ac_dir\"" >&2;} + { (exit 1); exit 1; }; }; } + + ac_builddir=. + +if test "$ac_dir" != .; then + ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'` + # A "../" for each directory in $ac_dir_suffix. + ac_top_builddir=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,../,g'` +else + ac_dir_suffix= ac_top_builddir= +fi + +case $srcdir in + .) # No --srcdir option. We are building in place. + ac_srcdir=. + if test -z "$ac_top_builddir"; then + ac_top_srcdir=. + else + ac_top_srcdir=`echo $ac_top_builddir | sed 's,/$,,'` + fi ;; + [\\/]* | ?:[\\/]* ) # Absolute path. + ac_srcdir=$srcdir$ac_dir_suffix; + ac_top_srcdir=$srcdir ;; + *) # Relative path. + ac_srcdir=$ac_top_builddir$srcdir$ac_dir_suffix + ac_top_srcdir=$ac_top_builddir$srcdir ;; +esac + +# Do not use `cd foo && pwd` to compute absolute paths, because +# the directories may not exist. +case `pwd` in +.) ac_abs_builddir="$ac_dir";; +*) + case "$ac_dir" in + .) ac_abs_builddir=`pwd`;; + [\\/]* | ?:[\\/]* ) ac_abs_builddir="$ac_dir";; + *) ac_abs_builddir=`pwd`/"$ac_dir";; + esac;; +esac +case $ac_abs_builddir in +.) ac_abs_top_builddir=${ac_top_builddir}.;; +*) + case ${ac_top_builddir}. in + .) ac_abs_top_builddir=$ac_abs_builddir;; + [\\/]* | ?:[\\/]* ) ac_abs_top_builddir=${ac_top_builddir}.;; + *) ac_abs_top_builddir=$ac_abs_builddir/${ac_top_builddir}.;; + esac;; +esac +case $ac_abs_builddir in +.) ac_abs_srcdir=$ac_srcdir;; +*) + case $ac_srcdir in + .) ac_abs_srcdir=$ac_abs_builddir;; + [\\/]* | ?:[\\/]* ) ac_abs_srcdir=$ac_srcdir;; + *) ac_abs_srcdir=$ac_abs_builddir/$ac_srcdir;; + esac;; +esac +case $ac_abs_builddir in +.) ac_abs_top_srcdir=$ac_top_srcdir;; +*) + case $ac_top_srcdir in + .) ac_abs_top_srcdir=$ac_abs_builddir;; + [\\/]* | ?:[\\/]* ) ac_abs_top_srcdir=$ac_top_srcdir;; + *) ac_abs_top_srcdir=$ac_abs_builddir/$ac_top_srcdir;; + esac;; +esac + + + { echo "$as_me:$LINENO: executing $ac_dest commands" >&5 +echo "$as_me: executing $ac_dest commands" >&6;} + case $ac_dest in + depfiles ) test x"$AMDEP_TRUE" != x"" || for mf in $CONFIG_FILES; do + # Strip MF so we end up with the name of the file. + mf=`echo "$mf" | sed -e 's/:.*$//'` + # Check whether this is an Automake generated Makefile or not. + # We used to match only the files named `Makefile.in', but + # some people rename them; so instead we look at the file content. + # Grep'ing the first line is not enough: some people post-process + # each Makefile.in and add a new line on top of each file to say so. + # So let's grep whole file. + if grep '^#.*generated by automake' $mf > /dev/null 2>&1; then + dirpart=`(dirname "$mf") 2>/dev/null || +$as_expr X"$mf" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$mf" : 'X\(//\)[^/]' \| \ + X"$mf" : 'X\(//\)$' \| \ + X"$mf" : 'X\(/\)' \| \ + . : '\(.\)' 2>/dev/null || +echo X"$mf" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; } + /^X\(\/\/\)[^/].*/{ s//\1/; q; } + /^X\(\/\/\)$/{ s//\1/; q; } + /^X\(\/\).*/{ s//\1/; q; } + s/.*/./; q'` + else + continue + fi + grep '^DEP_FILES *= *[^ #]' < "$mf" > /dev/null || continue + # Extract the definition of DEP_FILES from the Makefile without + # running `make'. + DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"` + test -z "$DEPDIR" && continue + # When using ansi2knr, U may be empty or an underscore; expand it + U=`sed -n 's/^U = //p' < "$mf"` + test -d "$dirpart/$DEPDIR" || mkdir "$dirpart/$DEPDIR" + # We invoke sed twice because it is the simplest approach to + # changing $(DEPDIR) to its actual value in the expansion. + for file in `sed -n ' + /^DEP_FILES = .*\\\\$/ { + s/^DEP_FILES = // + :loop + s/\\\\$// + p + n + /\\\\$/ b loop + p + } + /^DEP_FILES = / s/^DEP_FILES = //p' < "$mf" | \ + sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g' -e 's/\$U/'"$U"'/g'`; do + # Make sure the directory exists. + test -f "$dirpart/$file" && continue + fdir=`(dirname "$file") 2>/dev/null || +$as_expr X"$file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$file" : 'X\(//\)[^/]' \| \ + X"$file" : 'X\(//\)$' \| \ + X"$file" : 'X\(/\)' \| \ + . : '\(.\)' 2>/dev/null || +echo X"$file" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; } + /^X\(\/\/\)[^/].*/{ s//\1/; q; } + /^X\(\/\/\)$/{ s//\1/; q; } + /^X\(\/\).*/{ s//\1/; q; } + s/.*/./; q'` + { if $as_mkdir_p; then + mkdir -p $dirpart/$fdir + else + as_dir=$dirpart/$fdir + as_dirs= + while test ! -d "$as_dir"; do + as_dirs="$as_dir $as_dirs" + as_dir=`(dirname "$as_dir") 2>/dev/null || +$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_dir" : 'X\(//\)[^/]' \| \ + X"$as_dir" : 'X\(//\)$' \| \ + X"$as_dir" : 'X\(/\)' \| \ + . : '\(.\)' 2>/dev/null || +echo X"$as_dir" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; } + /^X\(\/\/\)[^/].*/{ s//\1/; q; } + /^X\(\/\/\)$/{ s//\1/; q; } + /^X\(\/\).*/{ s//\1/; q; } + s/.*/./; q'` + done + test ! -n "$as_dirs" || mkdir $as_dirs + fi || { { echo "$as_me:$LINENO: error: cannot create directory $dirpart/$fdir" >&5 +echo "$as_me: error: cannot create directory $dirpart/$fdir" >&2;} + { (exit 1); exit 1; }; }; } + + # echo "creating $dirpart/$file" + echo '# dummy' > "$dirpart/$file" + done +done + ;; + esac +done +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF + +{ (exit 0); exit 0; } +_ACEOF +chmod +x $CONFIG_STATUS +ac_clean_files=$ac_clean_files_save + + +# configure is writing to config.log, and then calls config.status. +# config.status does its own redirection, appending to config.log. +# Unfortunately, on DOS this fails, as config.log is still kept open +# by configure, so config.status won't be able to write to it; its +# output is simply discarded. So we exec the FD to /dev/null, +# effectively closing config.log, so it can be properly (re)opened and +# appended to by config.status. When coming back to configure, we +# need to make the FD available again. +if test "$no_create" != yes; then + ac_cs_success=: + ac_config_status_args= + test "$silent" = yes && + ac_config_status_args="$ac_config_status_args --quiet" + exec 5>/dev/null + $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false + exec 5>>config.log + # Use ||, not &&, to avoid exiting from the if with $? = 1, which + # would make configure fail if this is the last instruction. + $ac_cs_success || { (exit 1); exit 1; } +fi + + +if test "x$src" = "x"; then +echo "You don't seem to have the development package for libogg (libogg-devel) installed. Only the Speex library (libspeex) will be built (no encoder/decoder executable)" +echo "You can download libogg from http://www.vorbis.com/download.psp" +fi + +echo "Type \"make; make install\" to compile and install Speex"; diff --git a/Code/BF2/External/speex-1.0.5/configure.in b/Code/BF2/External/speex-1.0.5/configure.in new file mode 100644 index 000000000..edf5f4c47 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/configure.in @@ -0,0 +1,78 @@ +dnl Process this file with autoconf to produce a configure script. -*-m4-*- + +AC_INIT(libspeex/nb_celp.c) + +SPEEX_MAJOR_VERSION=1 +SPEEX_MINOR_VERSION=0 +SPEEX_MICRO_VERSION=5 +SPEEX_EXTRA_VERSION= +SPEEX_VERSION=$SPEEX_MAJOR_VERSION.$SPEEX_MINOR_VERSION.$SPEEX_MICRO_VERSION$SPEEX_EXTRA_VERSION + +SPEEX_LT_CURRENT=4 +SPEEX_LT_REVISION=0 +SPEEX_LT_AGE=3 + +AC_SUBST(SPEEX_LT_CURRENT) +AC_SUBST(SPEEX_LT_REVISION) +AC_SUBST(SPEEX_LT_AGE) + +# For automake. +VERSION=$SPEEX_VERSION +PACKAGE=speex + +AC_SUBST(SPEEX_VERSION) + +AM_INIT_AUTOMAKE($PACKAGE, $VERSION, no-define) +AM_MAINTAINER_MODE + +AC_CANONICAL_HOST +AM_PROG_LIBTOOL + +AC_C_BIGENDIAN +AC_CHECK_HEADERS(sys/soundcard.h sys/audioio.h) + +AC_ARG_ENABLE(ogg, + [ --enable-ogg=[yes/no] Turn on or off the use of ogg +libraries [default=yes]], + [case "${enableval}" in + yes) useogg=true ;; + no) useogg=false ;; + *) AC_MSG_ERROR(bad value ${enableval} for --enable-ogg) ;; + esac],[useogg=true]) + +if test x$useogg = xtrue; then +AC_PATH_LIBOGG +fi + +if test "$have_libogg" = yes; then + src=src +else + src= +fi +AC_SUBST(src) + +AC_CHECK_LIB(m, sin) +AC_CHECK_LIB(gnugetopt, getopt_long) + +AC_DEFINE_UNQUOTED(SPEEX_VERSION, "${SPEEX_VERSION}") +AC_DEFINE_UNQUOTED(SPEEX_MAJOR_VERSION, ${SPEEX_MAJOR_VERSION}) +AC_DEFINE_UNQUOTED(SPEEX_MINOR_VERSION, ${SPEEX_MINOR_VERSION}) +AC_DEFINE_UNQUOTED(SPEEX_MICRO_VERSION, ${SPEEX_MICRO_VERSION}) +AC_DEFINE_UNQUOTED(SPEEX_EXTRA_VERSION, "${SPEEX_EXTRA_VERSION}") + + +AC_ARG_ENABLE(sse, [ --enable-sse enable SSE support], [if test "$enableval" = yes; then AC_DEFINE(_USE_SSE) fi]) + +dnl Output the makefiles and version.h. + +AC_OUTPUT([Makefile libspeex/Makefile src/Makefile doc/Makefile Speex.spec + include/Makefile include/speex/Makefile speex.pc + win32/Makefile win32/libspeex/Makefile win32/speexenc/Makefile + win32/speexdec/Makefile ]) + +if test "x$src" = "x"; then +echo "You don't seem to have the development package for libogg (libogg-devel) installed. Only the Speex library (libspeex) will be built (no encoder/decoder executable)" +echo "You can download libogg from http://www.vorbis.com/download.psp" +fi + +echo "Type \"make; make install\" to compile and install Speex"; diff --git a/Code/BF2/External/speex-1.0.5/depcomp b/Code/BF2/External/speex-1.0.5/depcomp new file mode 100755 index 000000000..25bdb1889 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/depcomp @@ -0,0 +1,526 @@ +#! /bin/sh +# depcomp - compile a program generating dependencies as side-effects + +scriptversion=2004-04-25.13 + +# Copyright (C) 1999, 2000, 2003, 2004 Free Software Foundation, Inc. + +# 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, or (at your option) +# any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA +# 02111-1307, USA. + +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + +# Originally written by Alexandre Oliva . + +case $1 in + '') + echo "$0: No command. Try \`$0 --help' for more information." 1>&2 + exit 1; + ;; + -h | --h*) + cat <<\EOF +Usage: depcomp [--help] [--version] PROGRAM [ARGS] + +Run PROGRAMS ARGS to compile a file, generating dependencies +as side-effects. + +Environment variables: + depmode Dependency tracking mode. + source Source file read by `PROGRAMS ARGS'. + object Object file output by `PROGRAMS ARGS'. + depfile Dependency file to output. + tmpdepfile Temporary file to use when outputing dependencies. + libtool Whether libtool is used (yes/no). + +Report bugs to . +EOF + exit 0 + ;; + -v | --v*) + echo "depcomp $scriptversion" + exit 0 + ;; +esac + +if test -z "$depmode" || test -z "$source" || test -z "$object"; then + echo "depcomp: Variables source, object and depmode must be set" 1>&2 + exit 1 +fi +# `libtool' can also be set to `yes' or `no'. + +if test -z "$depfile"; then + base=`echo "$object" | sed -e 's,^.*/,,' -e 's,\.\([^.]*\)$,.P\1,'` + dir=`echo "$object" | sed 's,/.*$,/,'` + if test "$dir" = "$object"; then + dir= + fi + # FIXME: should be _deps on DOS. + depfile="$dir.deps/$base" +fi + +tmpdepfile=${tmpdepfile-`echo "$depfile" | sed 's/\.\([^.]*\)$/.T\1/'`} + +rm -f "$tmpdepfile" + +# Some modes work just like other modes, but use different flags. We +# parameterize here, but still list the modes in the big case below, +# to make depend.m4 easier to write. Note that we *cannot* use a case +# here, because this file can only contain one case statement. +if test "$depmode" = hp; then + # HP compiler uses -M and no extra arg. + gccflag=-M + depmode=gcc +fi + +if test "$depmode" = dashXmstdout; then + # This is just like dashmstdout with a different argument. + dashmflag=-xM + depmode=dashmstdout +fi + +case "$depmode" in +gcc3) +## gcc 3 implements dependency tracking that does exactly what +## we want. Yay! Note: for some reason libtool 1.4 doesn't like +## it if -MD -MP comes after the -MF stuff. Hmm. + "$@" -MT "$object" -MD -MP -MF "$tmpdepfile" + stat=$? + if test $stat -eq 0; then : + else + rm -f "$tmpdepfile" + exit $stat + fi + mv "$tmpdepfile" "$depfile" + ;; + +gcc) +## There are various ways to get dependency output from gcc. Here's +## why we pick this rather obscure method: +## - Don't want to use -MD because we'd like the dependencies to end +## up in a subdir. Having to rename by hand is ugly. +## (We might end up doing this anyway to support other compilers.) +## - The DEPENDENCIES_OUTPUT environment variable makes gcc act like +## -MM, not -M (despite what the docs say). +## - Using -M directly means running the compiler twice (even worse +## than renaming). + if test -z "$gccflag"; then + gccflag=-MD, + fi + "$@" -Wp,"$gccflag$tmpdepfile" + stat=$? + if test $stat -eq 0; then : + else + rm -f "$tmpdepfile" + exit $stat + fi + rm -f "$depfile" + echo "$object : \\" > "$depfile" + alpha=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz +## The second -e expression handles DOS-style file names with drive letters. + sed -e 's/^[^:]*: / /' \ + -e 's/^['$alpha']:\/[^:]*: / /' < "$tmpdepfile" >> "$depfile" +## This next piece of magic avoids the `deleted header file' problem. +## The problem is that when a header file which appears in a .P file +## is deleted, the dependency causes make to die (because there is +## typically no way to rebuild the header). We avoid this by adding +## dummy dependencies for each header file. Too bad gcc doesn't do +## this for us directly. + tr ' ' ' +' < "$tmpdepfile" | +## Some versions of gcc put a space before the `:'. On the theory +## that the space means something, we add a space to the output as +## well. +## Some versions of the HPUX 10.20 sed can't process this invocation +## correctly. Breaking it into two sed invocations is a workaround. + sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile" + rm -f "$tmpdepfile" + ;; + +hp) + # This case exists only to let depend.m4 do its work. It works by + # looking at the text of this script. This case will never be run, + # since it is checked for above. + exit 1 + ;; + +sgi) + if test "$libtool" = yes; then + "$@" "-Wp,-MDupdate,$tmpdepfile" + else + "$@" -MDupdate "$tmpdepfile" + fi + stat=$? + if test $stat -eq 0; then : + else + rm -f "$tmpdepfile" + exit $stat + fi + rm -f "$depfile" + + if test -f "$tmpdepfile"; then # yes, the sourcefile depend on other files + echo "$object : \\" > "$depfile" + + # Clip off the initial element (the dependent). Don't try to be + # clever and replace this with sed code, as IRIX sed won't handle + # lines with more than a fixed number of characters (4096 in + # IRIX 6.2 sed, 8192 in IRIX 6.5). We also remove comment lines; + # the IRIX cc adds comments like `#:fec' to the end of the + # dependency line. + tr ' ' ' +' < "$tmpdepfile" \ + | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' | \ + tr ' +' ' ' >> $depfile + echo >> $depfile + + # The second pass generates a dummy entry for each header file. + tr ' ' ' +' < "$tmpdepfile" \ + | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' -e 's/$/:/' \ + >> $depfile + else + # The sourcefile does not contain any dependencies, so just + # store a dummy comment line, to avoid errors with the Makefile + # "include basename.Plo" scheme. + echo "#dummy" > "$depfile" + fi + rm -f "$tmpdepfile" + ;; + +aix) + # The C for AIX Compiler uses -M and outputs the dependencies + # in a .u file. In older versions, this file always lives in the + # current directory. Also, the AIX compiler puts `$object:' at the + # start of each line; $object doesn't have directory information. + # Version 6 uses the directory in both cases. + stripped=`echo "$object" | sed 's/\(.*\)\..*$/\1/'` + tmpdepfile="$stripped.u" + if test "$libtool" = yes; then + "$@" -Wc,-M + else + "$@" -M + fi + stat=$? + + if test -f "$tmpdepfile"; then : + else + stripped=`echo "$stripped" | sed 's,^.*/,,'` + tmpdepfile="$stripped.u" + fi + + if test $stat -eq 0; then : + else + rm -f "$tmpdepfile" + exit $stat + fi + + if test -f "$tmpdepfile"; then + outname="$stripped.o" + # Each line is of the form `foo.o: dependent.h'. + # Do two passes, one to just change these to + # `$object: dependent.h' and one to simply `dependent.h:'. + sed -e "s,^$outname:,$object :," < "$tmpdepfile" > "$depfile" + sed -e "s,^$outname: \(.*\)$,\1:," < "$tmpdepfile" >> "$depfile" + else + # The sourcefile does not contain any dependencies, so just + # store a dummy comment line, to avoid errors with the Makefile + # "include basename.Plo" scheme. + echo "#dummy" > "$depfile" + fi + rm -f "$tmpdepfile" + ;; + +icc) + # Intel's C compiler understands `-MD -MF file'. However on + # icc -MD -MF foo.d -c -o sub/foo.o sub/foo.c + # ICC 7.0 will fill foo.d with something like + # foo.o: sub/foo.c + # foo.o: sub/foo.h + # which is wrong. We want: + # sub/foo.o: sub/foo.c + # sub/foo.o: sub/foo.h + # sub/foo.c: + # sub/foo.h: + # ICC 7.1 will output + # foo.o: sub/foo.c sub/foo.h + # and will wrap long lines using \ : + # foo.o: sub/foo.c ... \ + # sub/foo.h ... \ + # ... + + "$@" -MD -MF "$tmpdepfile" + stat=$? + if test $stat -eq 0; then : + else + rm -f "$tmpdepfile" + exit $stat + fi + rm -f "$depfile" + # Each line is of the form `foo.o: dependent.h', + # or `foo.o: dep1.h dep2.h \', or ` dep3.h dep4.h \'. + # Do two passes, one to just change these to + # `$object: dependent.h' and one to simply `dependent.h:'. + sed "s,^[^:]*:,$object :," < "$tmpdepfile" > "$depfile" + # Some versions of the HPUX 10.20 sed can't process this invocation + # correctly. Breaking it into two sed invocations is a workaround. + sed 's,^[^:]*: \(.*\)$,\1,;s/^\\$//;/^$/d;/:$/d' < "$tmpdepfile" | + sed -e 's/$/ :/' >> "$depfile" + rm -f "$tmpdepfile" + ;; + +tru64) + # The Tru64 compiler uses -MD to generate dependencies as a side + # effect. `cc -MD -o foo.o ...' puts the dependencies into `foo.o.d'. + # At least on Alpha/Redhat 6.1, Compaq CCC V6.2-504 seems to put + # dependencies in `foo.d' instead, so we check for that too. + # Subdirectories are respected. + dir=`echo "$object" | sed -e 's|/[^/]*$|/|'` + test "x$dir" = "x$object" && dir= + base=`echo "$object" | sed -e 's|^.*/||' -e 's/\.o$//' -e 's/\.lo$//'` + + if test "$libtool" = yes; then + # Dependencies are output in .lo.d with libtool 1.4. + # They are output in .o.d with libtool 1.5. + tmpdepfile1="$dir.libs/$base.lo.d" + tmpdepfile2="$dir.libs/$base.o.d" + tmpdepfile3="$dir.libs/$base.d" + "$@" -Wc,-MD + else + tmpdepfile1="$dir$base.o.d" + tmpdepfile2="$dir$base.d" + tmpdepfile3="$dir$base.d" + "$@" -MD + fi + + stat=$? + if test $stat -eq 0; then : + else + rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" + exit $stat + fi + + if test -f "$tmpdepfile1"; then + tmpdepfile="$tmpdepfile1" + elif test -f "$tmpdepfile2"; then + tmpdepfile="$tmpdepfile2" + else + tmpdepfile="$tmpdepfile3" + fi + if test -f "$tmpdepfile"; then + sed -e "s,^.*\.[a-z]*:,$object:," < "$tmpdepfile" > "$depfile" + # That's a tab and a space in the []. + sed -e 's,^.*\.[a-z]*:[ ]*,,' -e 's,$,:,' < "$tmpdepfile" >> "$depfile" + else + echo "#dummy" > "$depfile" + fi + rm -f "$tmpdepfile" + ;; + +#nosideeffect) + # This comment above is used by automake to tell side-effect + # dependency tracking mechanisms from slower ones. + +dashmstdout) + # Important note: in order to support this mode, a compiler *must* + # always write the preprocessed file to stdout, regardless of -o. + "$@" || exit $? + + # Remove the call to Libtool. + if test "$libtool" = yes; then + while test $1 != '--mode=compile'; do + shift + done + shift + fi + + # Remove `-o $object'. + IFS=" " + for arg + do + case $arg in + -o) + shift + ;; + $object) + shift + ;; + *) + set fnord "$@" "$arg" + shift # fnord + shift # $arg + ;; + esac + done + + test -z "$dashmflag" && dashmflag=-M + # Require at least two characters before searching for `:' + # in the target name. This is to cope with DOS-style filenames: + # a dependency such as `c:/foo/bar' could be seen as target `c' otherwise. + "$@" $dashmflag | + sed 's:^[ ]*[^: ][^:][^:]*\:[ ]*:'"$object"'\: :' > "$tmpdepfile" + rm -f "$depfile" + cat < "$tmpdepfile" > "$depfile" + tr ' ' ' +' < "$tmpdepfile" | \ +## Some versions of the HPUX 10.20 sed can't process this invocation +## correctly. Breaking it into two sed invocations is a workaround. + sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile" + rm -f "$tmpdepfile" + ;; + +dashXmstdout) + # This case only exists to satisfy depend.m4. It is never actually + # run, as this mode is specially recognized in the preamble. + exit 1 + ;; + +makedepend) + "$@" || exit $? + # Remove any Libtool call + if test "$libtool" = yes; then + while test $1 != '--mode=compile'; do + shift + done + shift + fi + # X makedepend + shift + cleared=no + for arg in "$@"; do + case $cleared in + no) + set ""; shift + cleared=yes ;; + esac + case "$arg" in + -D*|-I*) + set fnord "$@" "$arg"; shift ;; + # Strip any option that makedepend may not understand. Remove + # the object too, otherwise makedepend will parse it as a source file. + -*|$object) + ;; + *) + set fnord "$@" "$arg"; shift ;; + esac + done + obj_suffix="`echo $object | sed 's/^.*\././'`" + touch "$tmpdepfile" + ${MAKEDEPEND-makedepend} -o"$obj_suffix" -f"$tmpdepfile" "$@" + rm -f "$depfile" + cat < "$tmpdepfile" > "$depfile" + sed '1,2d' "$tmpdepfile" | tr ' ' ' +' | \ +## Some versions of the HPUX 10.20 sed can't process this invocation +## correctly. Breaking it into two sed invocations is a workaround. + sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile" + rm -f "$tmpdepfile" "$tmpdepfile".bak + ;; + +cpp) + # Important note: in order to support this mode, a compiler *must* + # always write the preprocessed file to stdout. + "$@" || exit $? + + # Remove the call to Libtool. + if test "$libtool" = yes; then + while test $1 != '--mode=compile'; do + shift + done + shift + fi + + # Remove `-o $object'. + IFS=" " + for arg + do + case $arg in + -o) + shift + ;; + $object) + shift + ;; + *) + set fnord "$@" "$arg" + shift # fnord + shift # $arg + ;; + esac + done + + "$@" -E | + sed -n '/^# [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' | + sed '$ s: \\$::' > "$tmpdepfile" + rm -f "$depfile" + echo "$object : \\" > "$depfile" + cat < "$tmpdepfile" >> "$depfile" + sed < "$tmpdepfile" '/^$/d;s/^ //;s/ \\$//;s/$/ :/' >> "$depfile" + rm -f "$tmpdepfile" + ;; + +msvisualcpp) + # Important note: in order to support this mode, a compiler *must* + # always write the preprocessed file to stdout, regardless of -o, + # because we must use -o when running libtool. + "$@" || exit $? + IFS=" " + for arg + do + case "$arg" in + "-Gm"|"/Gm"|"-Gi"|"/Gi"|"-ZI"|"/ZI") + set fnord "$@" + shift + shift + ;; + *) + set fnord "$@" "$arg" + shift + shift + ;; + esac + done + "$@" -E | + sed -n '/^#line [0-9][0-9]* "\([^"]*\)"/ s::echo "`cygpath -u \\"\1\\"`":p' | sort | uniq > "$tmpdepfile" + rm -f "$depfile" + echo "$object : \\" > "$depfile" + . "$tmpdepfile" | sed 's% %\\ %g' | sed -n '/^\(.*\)$/ s:: \1 \\:p' >> "$depfile" + echo " " >> "$depfile" + . "$tmpdepfile" | sed 's% %\\ %g' | sed -n '/^\(.*\)$/ s::\1\::p' >> "$depfile" + rm -f "$tmpdepfile" + ;; + +none) + exec "$@" + ;; + +*) + echo "Unknown depmode $depmode" 1>&2 + exit 1 + ;; +esac + +exit 0 + +# Local Variables: +# mode: shell-script +# sh-indentation: 2 +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "scriptversion=" +# time-stamp-format: "%:y-%02m-%02d.%02H" +# time-stamp-end: "$" +# End: diff --git a/Code/BF2/External/speex-1.0.5/doc/Makefile.am b/Code/BF2/External/speex-1.0.5/doc/Makefile.am new file mode 100644 index 000000000..a70a97b31 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/doc/Makefile.am @@ -0,0 +1,5 @@ +docdir=$(prefix)/share/doc/@PACKAGE@-@VERSION@ + +doc_DATA = manual.pdf + +EXTRA_DIST = $(doc_DATA) diff --git a/Code/BF2/External/speex-1.0.5/doc/Makefile.in b/Code/BF2/External/speex-1.0.5/doc/Makefile.in new file mode 100644 index 000000000..c8a143b5c --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/doc/Makefile.in @@ -0,0 +1,343 @@ +# Makefile.in generated by automake 1.8.5 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004 Free Software Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +top_builddir = .. +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +INSTALL = @INSTALL@ +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +host_triplet = @host@ +subdir = doc +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ + $(top_srcdir)/configure.in +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs +CONFIG_CLEAN_FILES = +SOURCES = +DIST_SOURCES = +am__installdirs = "$(DESTDIR)$(docdir)" +docDATA_INSTALL = $(INSTALL_DATA) +DATA = $(doc_DATA) +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMDEP_FALSE = @AMDEP_FALSE@ +AMDEP_TRUE = @AMDEP_TRUE@ +AMTAR = @AMTAR@ +AR = @AR@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +ECHO = @ECHO@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +F77 = @F77@ +FFLAGS = @FFLAGS@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +LDFLAGS = @LDFLAGS@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +MAINT = @MAINT@ +MAINTAINER_MODE_FALSE = @MAINTAINER_MODE_FALSE@ +MAINTAINER_MODE_TRUE = @MAINTAINER_MODE_TRUE@ +MAKEINFO = @MAKEINFO@ +OBJEXT = @OBJEXT@ +OGG_INCLUDES = @OGG_INCLUDES@ +OGG_LDFLAGS = @OGG_LDFLAGS@ +OGG_LIBS = @OGG_LIBS@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +RANLIB = @RANLIB@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SPEEX_LT_AGE = @SPEEX_LT_AGE@ +SPEEX_LT_CURRENT = @SPEEX_LT_CURRENT@ +SPEEX_LT_REVISION = @SPEEX_LT_REVISION@ +SPEEX_VERSION = @SPEEX_VERSION@ +STRIP = @STRIP@ +VERSION = @VERSION@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_CXX = @ac_ct_CXX@ +ac_ct_F77 = @ac_ct_F77@ +ac_ct_RANLIB = @ac_ct_RANLIB@ +ac_ct_STRIP = @ac_ct_STRIP@ +am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ +am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ +am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ +am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +datadir = @datadir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +src = @src@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +docdir = $(prefix)/share/doc/@PACKAGE@-@VERSION@ +doc_DATA = manual.pdf +EXTRA_DIST = $(doc_DATA) +all: all-am + +.SUFFIXES: +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ + && exit 0; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu doc/Makefile'; \ + cd $(top_srcdir) && \ + $(AUTOMAKE) --gnu doc/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +distclean-libtool: + -rm -f libtool +uninstall-info-am: +install-docDATA: $(doc_DATA) + @$(NORMAL_INSTALL) + test -z "$(docdir)" || $(mkdir_p) "$(DESTDIR)$(docdir)" + @list='$(doc_DATA)'; for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + f="`echo $$p | sed -e 's|^.*/||'`"; \ + echo " $(docDATA_INSTALL) '$$d$$p' '$(DESTDIR)$(docdir)/$$f'"; \ + $(docDATA_INSTALL) "$$d$$p" "$(DESTDIR)$(docdir)/$$f"; \ + done + +uninstall-docDATA: + @$(NORMAL_UNINSTALL) + @list='$(doc_DATA)'; for p in $$list; do \ + f="`echo $$p | sed -e 's|^.*/||'`"; \ + echo " rm -f '$(DESTDIR)$(docdir)/$$f'"; \ + rm -f "$(DESTDIR)$(docdir)/$$f"; \ + done +tags: TAGS +TAGS: + +ctags: CTAGS +CTAGS: + + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ + list='$(DISTFILES)'; for file in $$list; do \ + case $$file in \ + $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ + $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ + esac; \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test "$$dir" != "$$file" && test "$$dir" != "."; then \ + dir="/$$dir"; \ + $(mkdir_p) "$(distdir)$$dir"; \ + else \ + dir=''; \ + fi; \ + if test -d $$d/$$file; then \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + fi; \ + cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + else \ + test -f $(distdir)/$$file \ + || cp -p $$d/$$file $(distdir)/$$file \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile $(DATA) +installdirs: + for dir in "$(DESTDIR)$(docdir)"; do \ + test -z "$$dir" || $(mkdir_p) "$$dir"; \ + done +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + `test -z '$(STRIP)' || \ + echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -rm -f $(CONFIG_CLEAN_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-am + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-libtool + +dvi: dvi-am + +dvi-am: + +html: html-am + +info: info-am + +info-am: + +install-data-am: install-docDATA + +install-exec-am: + +install-info: install-info-am + +install-man: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-docDATA uninstall-info-am + +.PHONY: all all-am check check-am clean clean-generic clean-libtool \ + distclean distclean-generic distclean-libtool distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-docDATA install-exec \ + install-exec-am install-info install-info-am install-man \ + install-strip installcheck installcheck-am installdirs \ + maintainer-clean maintainer-clean-generic mostlyclean \ + mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ + uninstall uninstall-am uninstall-docDATA uninstall-info-am + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/Code/BF2/External/speex-1.0.5/doc/manual.pdf b/Code/BF2/External/speex-1.0.5/doc/manual.pdf new file mode 100644 index 000000000..d2988139c Binary files /dev/null and b/Code/BF2/External/speex-1.0.5/doc/manual.pdf differ diff --git a/Code/BF2/External/speex-1.0.5/include/Makefile.am b/Code/BF2/External/speex-1.0.5/include/Makefile.am new file mode 100644 index 000000000..505501cdf --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/include/Makefile.am @@ -0,0 +1,9 @@ + +SUBDIRS = speex + +include_HEADERS = speex.h \ + speex_bits.h \ + speex_header.h \ + speex_callbacks.h \ + speex_stereo.h + diff --git a/Code/BF2/External/speex-1.0.5/include/Makefile.in b/Code/BF2/External/speex-1.0.5/include/Makefile.in new file mode 100644 index 000000000..087633367 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/include/Makefile.in @@ -0,0 +1,493 @@ +# Makefile.in generated by automake 1.8.5 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004 Free Software Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +top_builddir = .. +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +INSTALL = @INSTALL@ +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +host_triplet = @host@ +subdir = include +DIST_COMMON = $(include_HEADERS) $(srcdir)/Makefile.am \ + $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ + $(top_srcdir)/configure.in +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs +CONFIG_CLEAN_FILES = +SOURCES = +DIST_SOURCES = +RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \ + html-recursive info-recursive install-data-recursive \ + install-exec-recursive install-info-recursive \ + install-recursive installcheck-recursive installdirs-recursive \ + pdf-recursive ps-recursive uninstall-info-recursive \ + uninstall-recursive +am__installdirs = "$(DESTDIR)$(includedir)" +includeHEADERS_INSTALL = $(INSTALL_HEADER) +HEADERS = $(include_HEADERS) +ETAGS = etags +CTAGS = ctags +DIST_SUBDIRS = $(SUBDIRS) +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMDEP_FALSE = @AMDEP_FALSE@ +AMDEP_TRUE = @AMDEP_TRUE@ +AMTAR = @AMTAR@ +AR = @AR@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +ECHO = @ECHO@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +F77 = @F77@ +FFLAGS = @FFLAGS@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +LDFLAGS = @LDFLAGS@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +MAINT = @MAINT@ +MAINTAINER_MODE_FALSE = @MAINTAINER_MODE_FALSE@ +MAINTAINER_MODE_TRUE = @MAINTAINER_MODE_TRUE@ +MAKEINFO = @MAKEINFO@ +OBJEXT = @OBJEXT@ +OGG_INCLUDES = @OGG_INCLUDES@ +OGG_LDFLAGS = @OGG_LDFLAGS@ +OGG_LIBS = @OGG_LIBS@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +RANLIB = @RANLIB@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SPEEX_LT_AGE = @SPEEX_LT_AGE@ +SPEEX_LT_CURRENT = @SPEEX_LT_CURRENT@ +SPEEX_LT_REVISION = @SPEEX_LT_REVISION@ +SPEEX_VERSION = @SPEEX_VERSION@ +STRIP = @STRIP@ +VERSION = @VERSION@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_CXX = @ac_ct_CXX@ +ac_ct_F77 = @ac_ct_F77@ +ac_ct_RANLIB = @ac_ct_RANLIB@ +ac_ct_STRIP = @ac_ct_STRIP@ +am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ +am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ +am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ +am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +datadir = @datadir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +src = @src@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +SUBDIRS = speex +include_HEADERS = speex.h \ + speex_bits.h \ + speex_header.h \ + speex_callbacks.h \ + speex_stereo.h + +all: all-recursive + +.SUFFIXES: +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ + && exit 0; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu include/Makefile'; \ + cd $(top_srcdir) && \ + $(AUTOMAKE) --gnu include/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +distclean-libtool: + -rm -f libtool +uninstall-info-am: +install-includeHEADERS: $(include_HEADERS) + @$(NORMAL_INSTALL) + test -z "$(includedir)" || $(mkdir_p) "$(DESTDIR)$(includedir)" + @list='$(include_HEADERS)'; for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + f="`echo $$p | sed -e 's|^.*/||'`"; \ + echo " $(includeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(includedir)/$$f'"; \ + $(includeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(includedir)/$$f"; \ + done + +uninstall-includeHEADERS: + @$(NORMAL_UNINSTALL) + @list='$(include_HEADERS)'; for p in $$list; do \ + f="`echo $$p | sed -e 's|^.*/||'`"; \ + echo " rm -f '$(DESTDIR)$(includedir)/$$f'"; \ + rm -f "$(DESTDIR)$(includedir)/$$f"; \ + done + +# This directory's subdirectories are mostly independent; you can cd +# into them and run `make' without going through this Makefile. +# To change the values of `make' variables: instead of editing Makefiles, +# (1) if the variable is set in `config.status', edit `config.status' +# (which will cause the Makefiles to be regenerated when you run `make'); +# (2) otherwise, pass the desired values on the `make' command line. +$(RECURSIVE_TARGETS): + @set fnord $$MAKEFLAGS; amf=$$2; \ + dot_seen=no; \ + target=`echo $@ | sed s/-recursive//`; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + dot_seen=yes; \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || case "$$amf" in *=*) exit 1;; *k*) fail=yes;; *) exit 1;; esac; \ + done; \ + if test "$$dot_seen" = "no"; then \ + $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ + fi; test -z "$$fail" + +mostlyclean-recursive clean-recursive distclean-recursive \ +maintainer-clean-recursive: + @set fnord $$MAKEFLAGS; amf=$$2; \ + dot_seen=no; \ + case "$@" in \ + distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ + *) list='$(SUBDIRS)' ;; \ + esac; \ + rev=''; for subdir in $$list; do \ + if test "$$subdir" = "."; then :; else \ + rev="$$subdir $$rev"; \ + fi; \ + done; \ + rev="$$rev ."; \ + target=`echo $@ | sed s/-recursive//`; \ + for subdir in $$rev; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || case "$$amf" in *=*) exit 1;; *k*) fail=yes;; *) exit 1;; esac; \ + done && test -z "$$fail" +tags-recursive: + list='$(SUBDIRS)'; for subdir in $$list; do \ + test "$$subdir" = . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \ + done +ctags-recursive: + list='$(SUBDIRS)'; for subdir in $$list; do \ + test "$$subdir" = . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \ + done + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + tags=; \ + here=`pwd`; \ + if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ + include_option=--etags-include; \ + empty_fix=.; \ + else \ + include_option=--include; \ + empty_fix=; \ + fi; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test ! -f $$subdir/TAGS || \ + tags="$$tags $$include_option=$$here/$$subdir/TAGS"; \ + fi; \ + done; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$tags $$unique; \ + fi +ctags: CTAGS +CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + tags=; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + test -z "$(CTAGS_ARGS)$$tags$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$tags $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && cd $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) $$here + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ + list='$(DISTFILES)'; for file in $$list; do \ + case $$file in \ + $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ + $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ + esac; \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test "$$dir" != "$$file" && test "$$dir" != "."; then \ + dir="/$$dir"; \ + $(mkdir_p) "$(distdir)$$dir"; \ + else \ + dir=''; \ + fi; \ + if test -d $$d/$$file; then \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + fi; \ + cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + else \ + test -f $(distdir)/$$file \ + || cp -p $$d/$$file $(distdir)/$$file \ + || exit 1; \ + fi; \ + done + list='$(SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test -d "$(distdir)/$$subdir" \ + || mkdir "$(distdir)/$$subdir" \ + || exit 1; \ + (cd $$subdir && \ + $(MAKE) $(AM_MAKEFLAGS) \ + top_distdir="../$(top_distdir)" \ + distdir="../$(distdir)/$$subdir" \ + distdir) \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-recursive +all-am: Makefile $(HEADERS) +installdirs: installdirs-recursive +installdirs-am: + for dir in "$(DESTDIR)$(includedir)"; do \ + test -z "$$dir" || $(mkdir_p) "$$dir"; \ + done +install: install-recursive +install-exec: install-exec-recursive +install-data: install-data-recursive +uninstall: uninstall-recursive + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-recursive +install-strip: + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + `test -z '$(STRIP)' || \ + echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -rm -f $(CONFIG_CLEAN_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-recursive + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-recursive + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-libtool \ + distclean-tags + +dvi: dvi-recursive + +dvi-am: + +html: html-recursive + +info: info-recursive + +info-am: + +install-data-am: install-includeHEADERS + +install-exec-am: + +install-info: install-info-recursive + +install-man: + +installcheck-am: + +maintainer-clean: maintainer-clean-recursive + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-recursive + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-recursive + +pdf-am: + +ps: ps-recursive + +ps-am: + +uninstall-am: uninstall-includeHEADERS uninstall-info-am + +uninstall-info: uninstall-info-recursive + +.PHONY: $(RECURSIVE_TARGETS) CTAGS GTAGS all all-am check check-am \ + clean clean-generic clean-libtool clean-recursive ctags \ + ctags-recursive distclean distclean-generic distclean-libtool \ + distclean-recursive distclean-tags distdir dvi dvi-am html \ + html-am info info-am install install-am install-data \ + install-data-am install-exec install-exec-am \ + install-includeHEADERS install-info install-info-am \ + install-man install-strip installcheck installcheck-am \ + installdirs installdirs-am maintainer-clean \ + maintainer-clean-generic maintainer-clean-recursive \ + mostlyclean mostlyclean-generic mostlyclean-libtool \ + mostlyclean-recursive pdf pdf-am ps ps-am tags tags-recursive \ + uninstall uninstall-am uninstall-includeHEADERS \ + uninstall-info-am + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/Code/BF2/External/speex-1.0.5/include/speex.h b/Code/BF2/External/speex-1.0.5/include/speex.h new file mode 100644 index 000000000..55e987516 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/include/speex.h @@ -0,0 +1 @@ +#include diff --git a/Code/BF2/External/speex-1.0.5/include/speex/Makefile.am b/Code/BF2/External/speex-1.0.5/include/speex/Makefile.am new file mode 100644 index 000000000..716a5398c --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/include/speex/Makefile.am @@ -0,0 +1,9 @@ +# Disable automatic dependency tracking if using other tools than gcc and gmake +#AUTOMAKE_OPTIONS = no-dependencies + +pkginclude_HEADERS = speex.h \ + speex_bits.h \ + speex_header.h \ + speex_callbacks.h \ + speex_stereo.h + diff --git a/Code/BF2/External/speex-1.0.5/include/speex/Makefile.in b/Code/BF2/External/speex-1.0.5/include/speex/Makefile.in new file mode 100644 index 000000000..1ecc87cde --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/include/speex/Makefile.in @@ -0,0 +1,397 @@ +# Makefile.in generated by automake 1.8.5 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004 Free Software Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# Disable automatic dependency tracking if using other tools than gcc and gmake +#AUTOMAKE_OPTIONS = no-dependencies + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +top_builddir = ../.. +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +INSTALL = @INSTALL@ +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +host_triplet = @host@ +subdir = include/speex +DIST_COMMON = $(pkginclude_HEADERS) $(srcdir)/Makefile.am \ + $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ + $(top_srcdir)/configure.in +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs +CONFIG_CLEAN_FILES = +SOURCES = +DIST_SOURCES = +am__installdirs = "$(DESTDIR)$(pkgincludedir)" +pkgincludeHEADERS_INSTALL = $(INSTALL_HEADER) +HEADERS = $(pkginclude_HEADERS) +ETAGS = etags +CTAGS = ctags +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMDEP_FALSE = @AMDEP_FALSE@ +AMDEP_TRUE = @AMDEP_TRUE@ +AMTAR = @AMTAR@ +AR = @AR@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +ECHO = @ECHO@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +F77 = @F77@ +FFLAGS = @FFLAGS@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +LDFLAGS = @LDFLAGS@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +MAINT = @MAINT@ +MAINTAINER_MODE_FALSE = @MAINTAINER_MODE_FALSE@ +MAINTAINER_MODE_TRUE = @MAINTAINER_MODE_TRUE@ +MAKEINFO = @MAKEINFO@ +OBJEXT = @OBJEXT@ +OGG_INCLUDES = @OGG_INCLUDES@ +OGG_LDFLAGS = @OGG_LDFLAGS@ +OGG_LIBS = @OGG_LIBS@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +RANLIB = @RANLIB@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SPEEX_LT_AGE = @SPEEX_LT_AGE@ +SPEEX_LT_CURRENT = @SPEEX_LT_CURRENT@ +SPEEX_LT_REVISION = @SPEEX_LT_REVISION@ +SPEEX_VERSION = @SPEEX_VERSION@ +STRIP = @STRIP@ +VERSION = @VERSION@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_CXX = @ac_ct_CXX@ +ac_ct_F77 = @ac_ct_F77@ +ac_ct_RANLIB = @ac_ct_RANLIB@ +ac_ct_STRIP = @ac_ct_STRIP@ +am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ +am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ +am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ +am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +datadir = @datadir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +src = @src@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +pkginclude_HEADERS = speex.h \ + speex_bits.h \ + speex_header.h \ + speex_callbacks.h \ + speex_stereo.h + +all: all-am + +.SUFFIXES: +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ + && exit 0; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu include/speex/Makefile'; \ + cd $(top_srcdir) && \ + $(AUTOMAKE) --gnu include/speex/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +distclean-libtool: + -rm -f libtool +uninstall-info-am: +install-pkgincludeHEADERS: $(pkginclude_HEADERS) + @$(NORMAL_INSTALL) + test -z "$(pkgincludedir)" || $(mkdir_p) "$(DESTDIR)$(pkgincludedir)" + @list='$(pkginclude_HEADERS)'; for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + f="`echo $$p | sed -e 's|^.*/||'`"; \ + echo " $(pkgincludeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(pkgincludedir)/$$f'"; \ + $(pkgincludeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(pkgincludedir)/$$f"; \ + done + +uninstall-pkgincludeHEADERS: + @$(NORMAL_UNINSTALL) + @list='$(pkginclude_HEADERS)'; for p in $$list; do \ + f="`echo $$p | sed -e 's|^.*/||'`"; \ + echo " rm -f '$(DESTDIR)$(pkgincludedir)/$$f'"; \ + rm -f "$(DESTDIR)$(pkgincludedir)/$$f"; \ + done + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + tags=; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$tags $$unique; \ + fi +ctags: CTAGS +CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + tags=; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + test -z "$(CTAGS_ARGS)$$tags$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$tags $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && cd $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) $$here + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ + list='$(DISTFILES)'; for file in $$list; do \ + case $$file in \ + $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ + $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ + esac; \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test "$$dir" != "$$file" && test "$$dir" != "."; then \ + dir="/$$dir"; \ + $(mkdir_p) "$(distdir)$$dir"; \ + else \ + dir=''; \ + fi; \ + if test -d $$d/$$file; then \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + fi; \ + cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + else \ + test -f $(distdir)/$$file \ + || cp -p $$d/$$file $(distdir)/$$file \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile $(HEADERS) +installdirs: + for dir in "$(DESTDIR)$(pkgincludedir)"; do \ + test -z "$$dir" || $(mkdir_p) "$$dir"; \ + done +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + `test -z '$(STRIP)' || \ + echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -rm -f $(CONFIG_CLEAN_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-am + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-libtool \ + distclean-tags + +dvi: dvi-am + +dvi-am: + +html: html-am + +info: info-am + +info-am: + +install-data-am: install-pkgincludeHEADERS + +install-exec-am: + +install-info: install-info-am + +install-man: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-info-am uninstall-pkgincludeHEADERS + +.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ + clean-libtool ctags distclean distclean-generic \ + distclean-libtool distclean-tags distdir dvi dvi-am html \ + html-am info info-am install install-am install-data \ + install-data-am install-exec install-exec-am install-info \ + install-info-am install-man install-pkgincludeHEADERS \ + install-strip installcheck installcheck-am installdirs \ + maintainer-clean maintainer-clean-generic mostlyclean \ + mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ + tags uninstall uninstall-am uninstall-info-am \ + uninstall-pkgincludeHEADERS + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/Code/BF2/External/speex-1.0.5/include/speex/speex.h b/Code/BF2/External/speex-1.0.5/include/speex/speex.h new file mode 100644 index 000000000..963ace0f7 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/include/speex/speex.h @@ -0,0 +1,374 @@ +/* Copyright (C) 2002 Jean-Marc Valin*/ +/** + @file speex.h + @brief Describes the different modes of the codec +*/ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +*/ + +#ifndef SPEEX_H +#define SPEEX_H + +#include "speex_bits.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* Values allowed for *ctl() requests */ + +/** Set enhancement on/off (decoder only) */ +#define SPEEX_SET_ENH 0 +/** Get enhancement state (decoder only) */ +#define SPEEX_GET_ENH 1 + +/*Would be SPEEX_SET_FRAME_SIZE, but it's (currently) invalid*/ +/** Obtain frame size used by encoder/decoder */ +#define SPEEX_GET_FRAME_SIZE 3 + +/** Set quality value */ +#define SPEEX_SET_QUALITY 4 +/** Get current quality setting */ +/* #define SPEEX_GET_QUALITY 5 -- Doesn't make much sense, does it? */ + +/** Set sub-mode to use */ +#define SPEEX_SET_MODE 6 +/** Get current sub-mode in use */ +#define SPEEX_GET_MODE 7 + +/** Set low-band sub-mode to use (wideband only)*/ +#define SPEEX_SET_LOW_MODE 8 +/** Get current low-band mode in use (wideband only)*/ +#define SPEEX_GET_LOW_MODE 9 + +/** Set high-band sub-mode to use (wideband only)*/ +#define SPEEX_SET_HIGH_MODE 10 +/** Get current high-band mode in use (wideband only)*/ +#define SPEEX_GET_HIGH_MODE 11 + +/** Set VBR on (1) or off (0) */ +#define SPEEX_SET_VBR 12 +/** Get VBR status (1 for on, 0 for off) */ +#define SPEEX_GET_VBR 13 + +/** Set quality value for VBR encoding (0-10) */ +#define SPEEX_SET_VBR_QUALITY 14 +/** Get current quality value for VBR encoding (0-10) */ +#define SPEEX_GET_VBR_QUALITY 15 + +/** Set complexity of the encoder (0-10) */ +#define SPEEX_SET_COMPLEXITY 16 +/** Get current complexity of the encoder (0-10) */ +#define SPEEX_GET_COMPLEXITY 17 + +/** Set bit-rate used by the encoder (or lower) */ +#define SPEEX_SET_BITRATE 18 +/** Get current bit-rate used by the encoder or decoder */ +#define SPEEX_GET_BITRATE 19 + +/**Define a handler function for in-band Speex request*/ +#define SPEEX_SET_HANDLER 20 + +/**Define a handler function for in-band user-defined request*/ +#define SPEEX_SET_USER_HANDLER 22 + +/** Set sampling rate used in bit-rate computation */ +#define SPEEX_SET_SAMPLING_RATE 24 +/** Get sampling rate used in bit-rate computation */ +#define SPEEX_GET_SAMPLING_RATE 25 + +/** Reset the encoder/decoder memories to zero*/ +#define SPEEX_RESET_STATE 26 + +/** Get VBR info (mostly used internally) */ +#define SPEEX_GET_RELATIVE_QUALITY 29 + +/** Set VAD status (1 for on, 0 for off) */ +#define SPEEX_SET_VAD 30 + +/** Get VAD status (1 for on, 0 for off) */ +#define SPEEX_GET_VAD 31 + +/** Set Average Bit-Rate (ABR) to n bits per seconds */ +#define SPEEX_SET_ABR 32 +/** Get Average Bit-Rate (ABR) setting (in bps) */ +#define SPEEX_GET_ABR 33 + +/** Set DTX status (1 for on, 0 for off) */ +#define SPEEX_SET_DTX 34 +/** Get DTX status (1 for on, 0 for off) */ +#define SPEEX_GET_DTX 35 + +/* 36 and 37 aren't supported in this version */ +#define SPEEX_GET_LOOKAHEAD 39 + + +/* Used internally, not to be used in applications */ +/** Used internally*/ +#define SPEEX_GET_PI_GAIN 100 +/** Used internally*/ +#define SPEEX_GET_EXC 101 +/** Used internally*/ +#define SPEEX_GET_INNOV 102 +/** Used internally*/ +#define SPEEX_GET_DTX_STATUS 103 + + +/* Preserving compatibility:*/ +/** Equivalent to SPEEX_SET_ENH */ +#define SPEEX_SET_PF 0 +/** Equivalent to SPEEX_GET_ENH */ +#define SPEEX_GET_PF 1 + + +/* Values allowed for mode queries */ +/** Query the frame size of a mode */ +#define SPEEX_MODE_FRAME_SIZE 0 + +/** Query the size of an encoded frame for a particular sub-mode */ +#define SPEEX_SUBMODE_BITS_PER_FRAME 1 + +#define SPEEX_LIB_GET_MAJOR_VERSION 1 +#define SPEEX_LIB_GET_MINOR_VERSION 3 +#define SPEEX_LIB_GET_MICRO_VERSION 5 +#define SPEEX_LIB_GET_EXTRA_VERSION 7 +#define SPEEX_LIB_GET_VERSION_STRING 9 + +/** Number of defined modes in Speex */ +#define SPEEX_NB_MODES 3 + +/** modeID for the defined narrowband mode */ +#define SPEEX_MODEID_NB 0 + +/** modeID for the defined wideband mode */ +#define SPEEX_MODEID_WB 1 + +/** modeID for the defined ultra-wideband mode */ +#define SPEEX_MODEID_UWB 2 + +struct SpeexMode; + + +/* Prototypes for mode function pointers */ + +/** Encoder state initialization function */ +typedef void *(*encoder_init_func)(struct SpeexMode *mode); + +/** Encoder state destruction function */ +typedef void (*encoder_destroy_func)(void *st); + +/** Main encoding function */ +typedef int (*encode_func)(void *state, float *in, SpeexBits *bits); + +/** Function for controlling the encoder options */ +typedef int (*encoder_ctl_func)(void *state, int request, void *ptr); + +/** Decoder state initialization function */ +typedef void *(*decoder_init_func)(struct SpeexMode *mode); + +/** Decoder state destruction function */ +typedef void (*decoder_destroy_func)(void *st); + +/** Main decoding function */ +typedef int (*decode_func)(void *state, SpeexBits *bits, float *out); + +/** Function for controlling the decoder options */ +typedef int (*decoder_ctl_func)(void *state, int request, void *ptr); + + +/** Query function for a mode */ +typedef int (*mode_query_func)(void *mode, int request, void *ptr); + +/** Struct defining a Speex mode */ +typedef struct SpeexMode { + /** Pointer to the low-level mode data */ + void *mode; + + /** Pointer to the mode query function */ + mode_query_func query; + + /** The name of the mode (you should not rely on this to identify the mode)*/ + char *modeName; + + /**ID of the mode*/ + int modeID; + + /**Version number of the bitstream (incremented every time we break + bitstream compatibility*/ + int bitstream_version; + + /** Pointer to encoder initialization function */ + encoder_init_func enc_init; + + /** Pointer to encoder destruction function */ + encoder_destroy_func enc_destroy; + + /** Pointer to frame encoding function */ + encode_func enc; + + /** Pointer to decoder initialization function */ + decoder_init_func dec_init; + + /** Pointer to decoder destruction function */ + decoder_destroy_func dec_destroy; + + /** Pointer to frame decoding function */ + decode_func dec; + + /** ioctl-like requests for encoder */ + encoder_ctl_func enc_ctl; + + /** ioctl-like requests for decoder */ + decoder_ctl_func dec_ctl; + +} SpeexMode; + +/** + * Returns a handle to a newly created Speex encoder state structure. For now, + * the "mode" argument can be &nb_mode or &wb_mode . In the future, more modes + * may be added. Note that for now if you have more than one channels to + * encode, you need one state per channel. + * + * @param mode The mode to use (either speex_nb_mode or speex_wb.mode) + * @return A newly created encoder + */ +void *speex_encoder_init(SpeexMode *mode); + +/** Frees all resources associated to an existing Speex encoder state. + * @param state Encoder state to be destroyed */ +void speex_encoder_destroy(void *state); + +/** Uses an existing encoder state to encode one frame of speech pointed to by + "in". The encoded bit-stream is saved in "bits". + @param state Encoder state + @param in Frame that will be encoded with a +-2^16 range + @param bits Bit-stream where the data will be written + */ +int speex_encode(void *state, float *in, SpeexBits *bits); + +/** Uses an existing encoder state to encode one frame of speech pointed to by + "in". The encoded bit-stream is saved in "bits". + @param state Encoder state + @param in Frame that will be encoded with a +-2^16 range + @param bits Bit-stream where the data will be written + */ +int speex_encode_int(void *state, short *in, SpeexBits *bits); + +/** Used like the ioctl function to control the encoder parameters + * + * @param state Encoder state + * @param request ioctl-type request (one of the SPEEX_* macros) + * @param ptr Data exchanged to-from function + * @return 0 if frame needs not be transmitted (DTX only), 1 otherwise + */ +int speex_encoder_ctl(void *state, int request, void *ptr); + + +/** Returns a handle to a newly created decoder state structure. For now, + * the mode argument can be &nb_mode or &wb_mode . In the future, more modes + * may be added. Note that for now if you have more than one channels to + * decode, you need one state per channel. + * + * @param mode Speex mode (one of speex_nb_mode or speex_wb_mode) + * @return A newly created decoder state + */ +void *speex_decoder_init(SpeexMode *mode); + +/** Frees all resources associated to an existing decoder state. + * + * @param state State to be destroyed + */ +void speex_decoder_destroy(void *state); + +/** Uses an existing decoder state to decode one frame of speech from + * bit-stream bits. The output speech is saved written to out. + * + * @param state Decoder state + * @param bits Bit-stream from which to decode the frame (NULL if the packet was lost) + * @param out Where to write the decoded frame + * @return return status (0 for no error, -1 for end of stream, -2 other) + */ + +int speex_decode(void *state, SpeexBits *bits, float *out); +/** Uses an existing decoder state to decode one frame of speech from + * bit-stream bits. The output speech is saved written to out. + * + * @param state Decoder state + * @param bits Bit-stream from which to decode the frame (NULL if the packet was lost) + * @param out Where to write the decoded frame + * @return return status (0 for no error, -1 for end of stream, -2 other) + */ +int speex_decode_int(void *state, SpeexBits *bits, short *out); + +/** Used like the ioctl function to control the encoder parameters + * + * @param state Decoder state + * @param request ioctl-type request (one of the SPEEX_* macros) + * @param ptr Data exchanged to-from function + * @return 0 for no error, 1 if a terminator is reached, 2 for another error + */ +int speex_decoder_ctl(void *state, int request, void *ptr); + + +/** Query function for mode information + * + * @param mode Speex mode + * @param request ioctl-type request (one of the SPEEX_* macros) + * @param ptr Data exchanged to-from function + */ +int speex_mode_query(SpeexMode *mode, int request, void *ptr); + +/** Functions for controlling the behavior of libspeex + * * @param request ioctl-type request (one of the SPEEX_LIB_* macros) + * * @param ptr Data exchanged to-from function + * */ +int speex_lib_ctl(int request, void *ptr); + +/** Default narrowband mode */ +extern SpeexMode speex_nb_mode; + +/** Default wideband mode */ +extern SpeexMode speex_wb_mode; + +/** Default "ultra-wideband" mode */ +extern SpeexMode speex_uwb_mode; + +/** List of all modes available */ +extern SpeexMode *speex_mode_list[SPEEX_NB_MODES]; + +/** Obtain one of the modes available */ +SpeexMode *speex_lib_get_mode (int mode); + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/Code/BF2/External/speex-1.0.5/include/speex/speex_bits.h b/Code/BF2/External/speex-1.0.5/include/speex/speex_bits.h new file mode 100644 index 000000000..b41fdad7e --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/include/speex/speex_bits.h @@ -0,0 +1,154 @@ +/* Copyright (C) 2002 Jean-Marc Valin */ +/** + @file speex_bits.h + @brief Handles bit packing/unpacking +*/ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +*/ + +#ifndef BITS_H +#define BITS_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** Maximum size of the bit-stream (for fixed-size allocation) */ +#define MAX_BYTES_PER_FRAME 2000 + +/** Bit-packing data structure representing (part of) a bit-stream. */ +typedef struct SpeexBits { + char *bytes; /**< "raw" data */ + int nbBits; /**< Total number of bits stored in the stream*/ + int bytePtr; /**< Position of the byte "cursor" */ + int bitPtr; /**< Position of the bit "cursor" within the current byte */ + int owner; /**< Does the struct "own" the "raw" buffer (member "bytes") */ + int overflow;/**< Set to one if we try to read past the valid data */ + int buf_size;/**< Allocated size for buffer */ + int reserved1; /**< Reserved for future use */ + void *reserved2; /**< Reserved for future use */ +} SpeexBits; + +/** Initializes and allocates resources for a SpeexBits struct */ +void speex_bits_init(SpeexBits *bits); + +/** Initializes SpeexBits struct using a pre-allocated buffer*/ +void speex_bits_init_buffer(SpeexBits *bits, void *buff, int buf_size); + +/** Frees all resources associated to a SpeexBits struct. Right now this does nothing since no resources are allocated, but this could change in the future.*/ +void speex_bits_destroy(SpeexBits *bits); + +/** Resets bits to initial value (just after initialization, erasing content)*/ +void speex_bits_reset(SpeexBits *bits); + +/** Rewind the bit-stream to the beginning (ready for read) without erasing the content */ +void speex_bits_rewind(SpeexBits *bits); + +/** Initializes the bit-stream from the data in an area of memory */ +void speex_bits_read_from(SpeexBits *bits, char *bytes, int len); + +/** Append bytes to the bit-stream + * @param bits Bit-stream to operate on + * @param bytes pointer to the bytes what will be appended + * @param len Number of bytes of append + */ +void speex_bits_read_whole_bytes(SpeexBits *bits, char *bytes, int len); + +/** Write the content of a bit-stream to an area of memory */ +int speex_bits_write(SpeexBits *bits, char *bytes, int max_len); + +/** Like speex_bits_write, but writes only the complete bytes in the stream. Also removes the written bytes from the stream */ +int speex_bits_write_whole_bytes(SpeexBits *bits, char *bytes, int max_len); + +/** Append bits to the bit-stream + * @param bits Bit-stream to operate on + * @param data Value to append as integer + * @param nbBits number of bits to consider in "data" + */ +void speex_bits_pack(SpeexBits *bits, int data, int nbBits); + +/** Interpret the next bits in the bit-stream as a signed integer + * + * @param bits Bit-stream to operate on + * @param nbBits Number of bits to interpret + * @return A signed integer represented by the bits read + */ +int speex_bits_unpack_signed(SpeexBits *bits, int nbBits); + +/** Interpret the next bits in the bit-stream as an unsigned integer + * + * @param bits Bit-stream to operate on + * @param nbBits Number of bits to interpret + * @return An unsigned integer represented by the bits read + */ +unsigned int speex_bits_unpack_unsigned(SpeexBits *bits, int nbBits); + +/** Returns the number of bytes in the bit-stream, including the last one even if it is not "full" + * + * @param bits Bit-stream to operate on + * @return Number of bytes in the stream + */ +int speex_bits_nbytes(SpeexBits *bits); + +/** Same as speex_bits_unpack_unsigned, but without modifying the cursor position */ +unsigned int speex_bits_peek_unsigned(SpeexBits *bits, int nbBits); + +/** Get the value of the next bit in the stream, without modifying the + * "cursor" position + * + * @param bits Bit-stream to operate on + */ +int speex_bits_peek(SpeexBits *bits); + +/** Advances the position of the "bit cursor" in the stream + * + * @param bits Bit-stream to operate on + * @param n Number of bits to advance + */ +void speex_bits_advance(SpeexBits *bits, int n); + +/** Returns the number of bits remaining to be read in a stream + * + * @param bits Bit-stream to operate on + */ +int speex_bits_remaining(SpeexBits *bits); + +/** Insert a terminator so that the data can be sent as a packet while auto-detecting + * the number of frames in each packet + * + * @param bits Bit-stream to operate on + */ +void speex_bits_insert_terminator(SpeexBits *bits); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/Code/BF2/External/speex-1.0.5/include/speex/speex_callbacks.h b/Code/BF2/External/speex-1.0.5/include/speex/speex_callbacks.h new file mode 100644 index 000000000..f6334f22a --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/include/speex/speex_callbacks.h @@ -0,0 +1,128 @@ +/* Copyright (C) 2002 Jean-Marc Valin*/ +/** + @file speex_callbacks.h + @brief Describes callback handling and in-band signalling +*/ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +*/ + +#ifndef SPEEX_CALLBACKS_H +#define SPEEX_CALLBACKS_H + +#include "speex.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** Total number of callbacks */ +#define SPEEX_MAX_CALLBACKS 16 + +/* Describes all the in-band requests */ + +/*These are 1-bit requests*/ +/** Request for perceptual enhancement (1 for on, 0 for off) */ +#define SPEEX_INBAND_ENH_REQUEST 0 +/** Reserved */ +#define SPEEX_INBAND_RESERVED1 1 + +/*These are 4-bit requests*/ +/** Request for a mode change */ +#define SPEEX_INBAND_MODE_REQUEST 2 +/** Request for a low mode change */ +#define SPEEX_INBAND_LOW_MODE_REQUEST 3 +/** Request for a high mode change */ +#define SPEEX_INBAND_HIGH_MODE_REQUEST 4 +/** Request for VBR (1 on, 0 off) */ +#define SPEEX_INBAND_VBR_QUALITY_REQUEST 5 +/** Request to be sent acknowledge */ +#define SPEEX_INBAND_ACKNOWLEDGE_REQUEST 6 +/** Request for VBR (1 for on, 0 for off) */ +#define SPEEX_INBAND_VBR_REQUEST 7 + +/*These are 8-bit requests*/ +/** Send a character in-band */ +#define SPEEX_INBAND_CHAR 8 +/** Intensity stereo information */ +#define SPEEX_INBAND_STEREO 9 + +/*These are 16-bit requests*/ +/** Transmit max bit-rate allowed */ +#define SPEEX_INBAND_MAX_BITRATE 10 + +/*These are 32-bit requests*/ +/** Acknowledge packet reception */ +#define SPEEX_INBAND_ACKNOWLEDGE 12 + +/** Callback function type */ +typedef int (*speex_callback_func)(SpeexBits *bits, void *state, void *data); + +/** Callback information */ +typedef struct SpeexCallback { + int callback_id; /**< ID associated to the callback */ + speex_callback_func func; /**< Callback handler function */ + void *data; /**< Data that will be sent to the handler */ + void *reserved1; /**< Reserved for future use */ + int reserved2; /**< Reserved for future use */ +} SpeexCallback; + +/** Handle in-band request */ +int speex_inband_handler(SpeexBits *bits, SpeexCallback *callback_list, void *state); + +/** Standard handler for mode request (change mode, no questions asked) */ +int speex_std_mode_request_handler(SpeexBits *bits, void *state, void *data); + +/** Standard handler for high mode request (change high mode, no questions asked) */ +int speex_std_high_mode_request_handler(SpeexBits *bits, void *state, void *data); + +/** Standard handler for in-band characters (write to stderr) */ +int speex_std_char_handler(SpeexBits *bits, void *state, void *data); + +/** Default handler for user-defined requests: in this case, just ignore */ +int speex_default_user_handler(SpeexBits *bits, void *state, void *data); + + + + +int speex_std_low_mode_request_handler(SpeexBits *bits, void *state, void *data); + +int speex_std_vbr_request_handler(SpeexBits *bits, void *state, void *data); + +int speex_std_enh_request_handler(SpeexBits *bits, void *state, void *data); + +int speex_std_vbr_quality_request_handler(SpeexBits *bits, void *state, void *data); + + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/Code/BF2/External/speex-1.0.5/include/speex/speex_header.h b/Code/BF2/External/speex-1.0.5/include/speex/speex_header.h new file mode 100644 index 000000000..8ded91142 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/include/speex/speex_header.h @@ -0,0 +1,82 @@ +/* Copyright (C) 2002 Jean-Marc Valin */ +/** + @file speex_header.h + @brief Describes the Speex header +*/ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +*/ + + +#ifndef SPEEX_HEADER_H +#define SPEEX_HEADER_H + +#ifdef __cplusplus +extern "C" { +#endif + +struct SpeexMode; + +/** Maximum number of characters for encoding the Speex version number in the header */ +#define SPEEX_HEADER_VERSION_LENGTH 20 + +/** Speex header info for file-based formats */ +typedef struct SpeexHeader { + char speex_string[8]; /**< Identifies a Speex bit-stream, always set to "Speex " */ + char speex_version[SPEEX_HEADER_VERSION_LENGTH]; /**< Speex version */ + int speex_version_id; /**< Version for Speex (for checking compatibility) */ + int header_size; /**< Total size of the header ( sizeof(SpeexHeader) ) */ + int rate; /**< Sampling rate used */ + int mode; /**< Mode used (0 for narrowband, 1 for wideband) */ + int mode_bitstream_version; /**< Version ID of the bit-stream */ + int nb_channels; /**< Number of channels encoded */ + int bitrate; /**< Bit-rate used */ + int frame_size; /**< Size of frames */ + int vbr; /**< 1 for a VBR encoding, 0 otherwise */ + int frames_per_packet; /**< Number of frames stored per Ogg packet */ + int extra_headers; /**< Number of additional headers after the comments */ + int reserved1; /**< Reserved for future use, must be zero */ + int reserved2; /**< Reserved for future use, must be zero */ +} SpeexHeader; + +/** Initializes a SpeexHeader using basic information */ +void speex_init_header(SpeexHeader *header, int rate, int nb_channels, struct SpeexMode *m); + +/** Creates the header packet from the header itself (mostly involves endianness conversion) */ +char *speex_header_to_packet(SpeexHeader *header, int *size); + +/** Creates a SpeexHeader from a packet */ +SpeexHeader *speex_packet_to_header(char *packet, int size); + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/Code/BF2/External/speex-1.0.5/include/speex/speex_stereo.h b/Code/BF2/External/speex-1.0.5/include/speex/speex_stereo.h new file mode 100644 index 000000000..4c2e258d2 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/include/speex/speex_stereo.h @@ -0,0 +1,77 @@ +/* Copyright (C) 2002 Jean-Marc Valin*/ +/** + @file speex_stereo.h + @brief Describes the handling for intensity stereo +*/ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef STEREO_H +#define STEREO_H + +#include "speex_bits.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** State used for decoding (intensity) stereo information */ +typedef struct SpeexStereoState { + float balance; /**< Left/right balance info */ + float e_ratio; /**< Ratio of energies: E(left+right)/[E(left)+E(right)] */ + float smooth_left; /**< Smoothed left channel gain */ + float smooth_right; /**< Smoothed right channel gain */ + float reserved1; /**< Reserved for future use */ + float reserved2; /**< Reserved for future use */ +} SpeexStereoState; + +/** Initialization value for a stereo state */ +#define SPEEX_STEREO_STATE_INIT {1,.5,1,1} + +/** Transforms a stereo frame into a mono frame and stores intensity stereo info in 'bits' */ +void speex_encode_stereo(float *data, int frame_size, SpeexBits *bits); + +/** Transforms a stereo frame into a mono frame and stores intensity stereo info in 'bits' (int version) */ +void speex_encode_stereo_int(short *data, int frame_size, SpeexBits *bits); + +/** Transforms a mono frame into a stereo frame using intensity stereo info */ +void speex_decode_stereo(float *data, int frame_size, SpeexStereoState *stereo); + +/** Transforms a mono frame into a stereo frame using intensity stereo info (int version) */ +void speex_decode_stereo_int(short *data, int frame_size, SpeexStereoState *stereo); + +/** Callback handler for intensity stereo info */ +int speex_std_stereo_request_handler(SpeexBits *bits, void *state, void *data); + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/Code/BF2/External/speex-1.0.5/include/speex_bits.h b/Code/BF2/External/speex-1.0.5/include/speex_bits.h new file mode 100644 index 000000000..767059e59 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/include/speex_bits.h @@ -0,0 +1 @@ +#include diff --git a/Code/BF2/External/speex-1.0.5/include/speex_callbacks.h b/Code/BF2/External/speex-1.0.5/include/speex_callbacks.h new file mode 100644 index 000000000..e92bb1d88 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/include/speex_callbacks.h @@ -0,0 +1 @@ +#include diff --git a/Code/BF2/External/speex-1.0.5/include/speex_header.h b/Code/BF2/External/speex-1.0.5/include/speex_header.h new file mode 100644 index 000000000..6c63f3345 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/include/speex_header.h @@ -0,0 +1 @@ +#include diff --git a/Code/BF2/External/speex-1.0.5/include/speex_stereo.h b/Code/BF2/External/speex-1.0.5/include/speex_stereo.h new file mode 100644 index 000000000..21b6e886c --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/include/speex_stereo.h @@ -0,0 +1 @@ +#include diff --git a/Code/BF2/External/speex-1.0.5/install-sh b/Code/BF2/External/speex-1.0.5/install-sh new file mode 100755 index 000000000..e4160c991 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/install-sh @@ -0,0 +1,325 @@ +#!/bin/sh +# install - install a program, script, or datafile + +scriptversion=2004-04-01.17 + +# This originates from X11R5 (mit/util/scripts/install.sh), which was +# later released in X11R6 (xc/config/util/install.sh) with the +# following copyright and license. +# +# Copyright (C) 1994 X Consortium +# +# 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 +# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN +# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC- +# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +# +# Except as contained in this notice, the name of the X Consortium shall not +# be used in advertising or otherwise to promote the sale, use or other deal- +# ings in this Software without prior written authorization from the X Consor- +# tium. +# +# +# FSF changes to this file are in the public domain. +# +# Calling this script install-sh is preferred over install.sh, to prevent +# `make' implicit rules from creating a file called install from it +# when there is no Makefile. +# +# This script is compatible with the BSD install script, but was written +# from scratch. It can only install one file at a time, a restriction +# shared with many OS's install programs. + +# set DOITPROG to echo to test this script + +# Don't use :- since 4.3BSD and earlier shells don't like it. +doit="${DOITPROG-}" + +# put in absolute paths if you don't have them in your path; or use env. vars. + +mvprog="${MVPROG-mv}" +cpprog="${CPPROG-cp}" +chmodprog="${CHMODPROG-chmod}" +chownprog="${CHOWNPROG-chown}" +chgrpprog="${CHGRPPROG-chgrp}" +stripprog="${STRIPPROG-strip}" +rmprog="${RMPROG-rm}" +mkdirprog="${MKDIRPROG-mkdir}" + +transformbasename= +transform_arg= +instcmd="$mvprog" +chmodcmd="$chmodprog 0755" +chowncmd= +chgrpcmd= +stripcmd= +rmcmd="$rmprog -f" +mvcmd="$mvprog" +src= +dst= +dir_arg= + +usage="Usage: $0 [OPTION]... SRCFILE DSTFILE + or: $0 [OPTION]... SRCFILES... DIRECTORY + or: $0 -d DIRECTORIES... + +In the first form, install SRCFILE to DSTFILE, removing SRCFILE by default. +In the second, create the directory path DIR. + +Options: +-b=TRANSFORMBASENAME +-c copy source (using $cpprog) instead of moving (using $mvprog). +-d create directories instead of installing files. +-g GROUP $chgrp installed files to GROUP. +-m MODE $chmod installed files to MODE. +-o USER $chown installed files to USER. +-s strip installed files (using $stripprog). +-t=TRANSFORM +--help display this help and exit. +--version display version info and exit. + +Environment variables override the default commands: + CHGRPPROG CHMODPROG CHOWNPROG CPPROG MKDIRPROG MVPROG RMPROG STRIPPROG +" + +while test -n "$1"; do + case $1 in + -b=*) transformbasename=`echo $1 | sed 's/-b=//'` + shift + continue;; + + -c) instcmd=$cpprog + shift + continue;; + + -d) dir_arg=true + shift + continue;; + + -g) chgrpcmd="$chgrpprog $2" + shift + shift + continue;; + + --help) echo "$usage"; exit 0;; + + -m) chmodcmd="$chmodprog $2" + shift + shift + continue;; + + -o) chowncmd="$chownprog $2" + shift + shift + continue;; + + -s) stripcmd=$stripprog + shift + continue;; + + -t=*) transformarg=`echo $1 | sed 's/-t=//'` + shift + continue;; + + --version) echo "$0 $scriptversion"; exit 0;; + + *) # When -d is used, all remaining arguments are directories to create. + test -n "$dir_arg" && break + # Otherwise, the last argument is the destination. Remove it from $@. + for arg + do + if test -n "$dstarg"; then + # $@ is not empty: it contains at least $arg. + set fnord "$@" "$dstarg" + shift # fnord + fi + shift # arg + dstarg=$arg + done + break;; + esac +done + +if test -z "$1"; then + if test -z "$dir_arg"; then + echo "$0: no input file specified." >&2 + exit 1 + fi + # It's OK to call `install-sh -d' without argument. + # This can happen when creating conditional directories. + exit 0 +fi + +for src +do + # Protect names starting with `-'. + case $src in + -*) src=./$src ;; + esac + + if test -n "$dir_arg"; then + dst=$src + src= + + if test -d "$dst"; then + instcmd=: + chmodcmd= + else + instcmd=$mkdirprog + fi + else + # Waiting for this to be detected by the "$instcmd $src $dsttmp" command + # might cause directories to be created, which would be especially bad + # if $src (and thus $dsttmp) contains '*'. + if test ! -f "$src" && test ! -d "$src"; then + echo "$0: $src does not exist." >&2 + exit 1 + fi + + if test -z "$dstarg"; then + echo "$0: no destination specified." >&2 + exit 1 + fi + + dst=$dstarg + # Protect names starting with `-'. + case $dst in + -*) dst=./$dst ;; + esac + + # If destination is a directory, append the input filename; won't work + # if double slashes aren't ignored. + if test -d "$dst"; then + dst=$dst/`basename "$src"` + fi + fi + + # This sed command emulates the dirname command. + dstdir=`echo "$dst" | sed -e 's,[^/]*$,,;s,/$,,;s,^$,.,'` + + # Make sure that the destination directory exists. + + # Skip lots of stat calls in the usual case. + if test ! -d "$dstdir"; then + defaultIFS=' + ' + IFS="${IFS-$defaultIFS}" + + oIFS=$IFS + # Some sh's can't handle IFS=/ for some reason. + IFS='%' + set - `echo "$dstdir" | sed -e 's@/@%@g' -e 's@^%@/@'` + IFS=$oIFS + + pathcomp= + + while test $# -ne 0 ; do + pathcomp=$pathcomp$1 + shift + if test ! -d "$pathcomp"; then + $mkdirprog "$pathcomp" || lasterr=$? + # mkdir can fail with a `File exist' error in case several + # install-sh are creating the directory concurrently. This + # is OK. + test ! -d "$pathcomp" && { (exit ${lasterr-1}); exit; } + fi + pathcomp=$pathcomp/ + done + fi + + if test -n "$dir_arg"; then + $doit $instcmd "$dst" \ + && { test -z "$chowncmd" || $doit $chowncmd "$dst"; } \ + && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } \ + && { test -z "$stripcmd" || $doit $stripcmd "$dst"; } \ + && { test -z "$chmodcmd" || $doit $chmodcmd "$dst"; } + + else + # If we're going to rename the final executable, determine the name now. + if test -z "$transformarg"; then + dstfile=`basename "$dst"` + else + dstfile=`basename "$dst" $transformbasename \ + | sed $transformarg`$transformbasename + fi + + # don't allow the sed command to completely eliminate the filename. + test -z "$dstfile" && dstfile=`basename "$dst"` + + # Make a couple of temp file names in the proper directory. + dsttmp=$dstdir/_inst.$$_ + rmtmp=$dstdir/_rm.$$_ + + # Trap to clean up those temp files at exit. + trap 'status=$?; rm -f "$dsttmp" "$rmtmp" && exit $status' 0 + trap '(exit $?); exit' 1 2 13 15 + + # Move or copy the file name to the temp name + $doit $instcmd "$src" "$dsttmp" && + + # and set any options; do chmod last to preserve setuid bits. + # + # If any of these fail, we abort the whole thing. If we want to + # ignore errors from any of these, just make sure not to ignore + # errors from the above "$doit $instcmd $src $dsttmp" command. + # + { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } \ + && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } \ + && { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } \ + && { test -z "$chmodcmd" || $doit $chmodcmd "$dsttmp"; } && + + # Now rename the file to the real destination. + { $doit $mvcmd -f "$dsttmp" "$dstdir/$dstfile" 2>/dev/null \ + || { + # The rename failed, perhaps because mv can't rename something else + # to itself, or perhaps because mv is so ancient that it does not + # support -f. + + # Now remove or move aside any old file at destination location. + # We try this two ways since rm can't unlink itself on some + # systems and the destination file might be busy for other + # reasons. In this case, the final cleanup might fail but the new + # file should still install successfully. + { + if test -f "$dstdir/$dstfile"; then + $doit $rmcmd -f "$dstdir/$dstfile" 2>/dev/null \ + || $doit $mvcmd -f "$dstdir/$dstfile" "$rmtmp" 2>/dev/null \ + || { + echo "$0: cannot unlink or rename $dstdir/$dstfile" >&2 + (exit 1); exit + } + else + : + fi + } && + + # Now rename the file to the real destination. + $doit $mvcmd "$dsttmp" "$dstdir/$dstfile" + } + } + fi || { (exit 1); exit; } +done + +# The final little trick to "correctly" pass the exit status to the exit trap. +{ + (exit 0); exit +} + +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "scriptversion=" +# time-stamp-format: "%:y-%02m-%02d.%02H" +# time-stamp-end: "$" +# End: diff --git a/Code/BF2/External/speex-1.0.5/libspeex/Makefile.am b/Code/BF2/External/speex-1.0.5/libspeex/Makefile.am new file mode 100644 index 000000000..0eb5d4edb --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/Makefile.am @@ -0,0 +1,73 @@ +## Process this file with automake to produce Makefile.in. -*-Makefile-*- + +# $Id: Makefile.am,v 1.49 2003/03/17 22:40:57 jm Exp $ + +# Disable automatic dependency tracking if using other tools than gcc and gmake +#AUTOMAKE_OPTIONS = no-dependencies + +INCLUDES = -I$(top_srcdir)/include + +lib_LTLIBRARIES = libspeex.la + +# Sources for compilation in the library +libspeex_la_SOURCES = nb_celp.c \ + sb_celp.c \ + lpc.c \ + ltp.c \ + lsp.c \ + quant_lsp.c \ + lsp_tables_nb.c \ + gain_table.c \ + gain_table_lbr.c \ + cb_search.c \ + filters.c \ + bits.c \ + modes.c \ + vq.c \ + high_lsp_tables.c \ + vbr.c \ + hexc_table.c \ + exc_5_256_table.c \ + exc_5_64_table.c \ + exc_8_128_table.c \ + exc_10_32_table.c \ + exc_10_16_table.c \ + exc_20_32_table.c \ + hexc_10_32_table.c \ + misc.c \ + speex_header.c \ + speex_callbacks.c \ + math_approx.c \ + stereo.c + + +noinst_HEADERS = lsp.h \ + nb_celp.h \ + lpc.h \ + ltp.h \ + quant_lsp.h \ + cb_search.h \ + filters.h \ + stack_alloc.h \ + vq.h \ + modes.h \ + sb_celp.h \ + vbr.h \ + misc.h \ + ltp_sse.h \ + filters_sse.h \ + math_approx.h + + +libspeex_la_LDFLAGS = -version-info @SPEEX_LT_CURRENT@:@SPEEX_LT_REVISION@:@SPEEX_LT_AGE@ + +noinst_PROGRAMS = testenc testenc_wb testenc_uwb + +testenc_SOURCES = testenc.c +testenc_LDADD = libspeex.la + +testenc_wb_SOURCES = testenc_wb.c +testenc_wb_LDADD = libspeex.la + +testenc_uwb_SOURCES = testenc_uwb.c +testenc_uwb_LDADD = libspeex.la diff --git a/Code/BF2/External/speex-1.0.5/libspeex/Makefile.in b/Code/BF2/External/speex-1.0.5/libspeex/Makefile.in new file mode 100644 index 000000000..b06e246d9 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/Makefile.in @@ -0,0 +1,611 @@ +# Makefile.in generated by automake 1.8.5 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004 Free Software Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# $Id: Makefile.am,v 1.49 2003/03/17 22:40:57 jm Exp $ + +# Disable automatic dependency tracking if using other tools than gcc and gmake +#AUTOMAKE_OPTIONS = no-dependencies + + + +SOURCES = $(libspeex_la_SOURCES) $(testenc_SOURCES) $(testenc_uwb_SOURCES) $(testenc_wb_SOURCES) + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +top_builddir = .. +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +INSTALL = @INSTALL@ +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +host_triplet = @host@ +noinst_PROGRAMS = testenc$(EXEEXT) testenc_wb$(EXEEXT) \ + testenc_uwb$(EXEEXT) +subdir = libspeex +DIST_COMMON = $(noinst_HEADERS) $(srcdir)/Makefile.am \ + $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ + $(top_srcdir)/configure.in +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs +CONFIG_CLEAN_FILES = +am__installdirs = "$(DESTDIR)$(libdir)" +libLTLIBRARIES_INSTALL = $(INSTALL) +LTLIBRARIES = $(lib_LTLIBRARIES) +libspeex_la_LIBADD = +am_libspeex_la_OBJECTS = nb_celp.lo sb_celp.lo lpc.lo ltp.lo lsp.lo \ + quant_lsp.lo lsp_tables_nb.lo gain_table.lo gain_table_lbr.lo \ + cb_search.lo filters.lo bits.lo modes.lo vq.lo \ + high_lsp_tables.lo vbr.lo hexc_table.lo exc_5_256_table.lo \ + exc_5_64_table.lo exc_8_128_table.lo exc_10_32_table.lo \ + exc_10_16_table.lo exc_20_32_table.lo hexc_10_32_table.lo \ + misc.lo speex_header.lo speex_callbacks.lo math_approx.lo \ + stereo.lo +libspeex_la_OBJECTS = $(am_libspeex_la_OBJECTS) +PROGRAMS = $(noinst_PROGRAMS) +am_testenc_OBJECTS = testenc.$(OBJEXT) +testenc_OBJECTS = $(am_testenc_OBJECTS) +testenc_DEPENDENCIES = libspeex.la +am_testenc_uwb_OBJECTS = testenc_uwb.$(OBJEXT) +testenc_uwb_OBJECTS = $(am_testenc_uwb_OBJECTS) +testenc_uwb_DEPENDENCIES = libspeex.la +am_testenc_wb_OBJECTS = testenc_wb.$(OBJEXT) +testenc_wb_OBJECTS = $(am_testenc_wb_OBJECTS) +testenc_wb_DEPENDENCIES = libspeex.la +DEFAULT_INCLUDES = -I. -I$(srcdir) +depcomp = $(SHELL) $(top_srcdir)/depcomp +am__depfiles_maybe = depfiles +@AMDEP_TRUE@DEP_FILES = ./$(DEPDIR)/bits.Plo ./$(DEPDIR)/cb_search.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/exc_10_16_table.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/exc_10_32_table.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/exc_20_32_table.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/exc_5_256_table.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/exc_5_64_table.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/exc_8_128_table.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/filters.Plo ./$(DEPDIR)/gain_table.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/gain_table_lbr.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/hexc_10_32_table.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/hexc_table.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/high_lsp_tables.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/lpc.Plo ./$(DEPDIR)/lsp.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/lsp_tables_nb.Plo ./$(DEPDIR)/ltp.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/math_approx.Plo ./$(DEPDIR)/misc.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/modes.Plo ./$(DEPDIR)/nb_celp.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/quant_lsp.Plo ./$(DEPDIR)/sb_celp.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/speex_callbacks.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/speex_header.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/stereo.Plo ./$(DEPDIR)/testenc.Po \ +@AMDEP_TRUE@ ./$(DEPDIR)/testenc_uwb.Po \ +@AMDEP_TRUE@ ./$(DEPDIR)/testenc_wb.Po ./$(DEPDIR)/vbr.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/vq.Plo +COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ + $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +LTCOMPILE = $(LIBTOOL) --mode=compile $(CC) $(DEFS) \ + $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ + $(AM_CFLAGS) $(CFLAGS) +CCLD = $(CC) +LINK = $(LIBTOOL) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ + $(AM_LDFLAGS) $(LDFLAGS) -o $@ +SOURCES = $(libspeex_la_SOURCES) $(testenc_SOURCES) \ + $(testenc_uwb_SOURCES) $(testenc_wb_SOURCES) +DIST_SOURCES = $(libspeex_la_SOURCES) $(testenc_SOURCES) \ + $(testenc_uwb_SOURCES) $(testenc_wb_SOURCES) +HEADERS = $(noinst_HEADERS) +ETAGS = etags +CTAGS = ctags +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMDEP_FALSE = @AMDEP_FALSE@ +AMDEP_TRUE = @AMDEP_TRUE@ +AMTAR = @AMTAR@ +AR = @AR@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +ECHO = @ECHO@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +F77 = @F77@ +FFLAGS = @FFLAGS@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +LDFLAGS = @LDFLAGS@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +MAINT = @MAINT@ +MAINTAINER_MODE_FALSE = @MAINTAINER_MODE_FALSE@ +MAINTAINER_MODE_TRUE = @MAINTAINER_MODE_TRUE@ +MAKEINFO = @MAKEINFO@ +OBJEXT = @OBJEXT@ +OGG_INCLUDES = @OGG_INCLUDES@ +OGG_LDFLAGS = @OGG_LDFLAGS@ +OGG_LIBS = @OGG_LIBS@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +RANLIB = @RANLIB@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SPEEX_LT_AGE = @SPEEX_LT_AGE@ +SPEEX_LT_CURRENT = @SPEEX_LT_CURRENT@ +SPEEX_LT_REVISION = @SPEEX_LT_REVISION@ +SPEEX_VERSION = @SPEEX_VERSION@ +STRIP = @STRIP@ +VERSION = @VERSION@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_CXX = @ac_ct_CXX@ +ac_ct_F77 = @ac_ct_F77@ +ac_ct_RANLIB = @ac_ct_RANLIB@ +ac_ct_STRIP = @ac_ct_STRIP@ +am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ +am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ +am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ +am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +datadir = @datadir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +src = @src@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +INCLUDES = -I$(top_srcdir)/include +lib_LTLIBRARIES = libspeex.la + +# Sources for compilation in the library +libspeex_la_SOURCES = nb_celp.c \ + sb_celp.c \ + lpc.c \ + ltp.c \ + lsp.c \ + quant_lsp.c \ + lsp_tables_nb.c \ + gain_table.c \ + gain_table_lbr.c \ + cb_search.c \ + filters.c \ + bits.c \ + modes.c \ + vq.c \ + high_lsp_tables.c \ + vbr.c \ + hexc_table.c \ + exc_5_256_table.c \ + exc_5_64_table.c \ + exc_8_128_table.c \ + exc_10_32_table.c \ + exc_10_16_table.c \ + exc_20_32_table.c \ + hexc_10_32_table.c \ + misc.c \ + speex_header.c \ + speex_callbacks.c \ + math_approx.c \ + stereo.c + +noinst_HEADERS = lsp.h \ + nb_celp.h \ + lpc.h \ + ltp.h \ + quant_lsp.h \ + cb_search.h \ + filters.h \ + stack_alloc.h \ + vq.h \ + modes.h \ + sb_celp.h \ + vbr.h \ + misc.h \ + ltp_sse.h \ + filters_sse.h \ + math_approx.h + +libspeex_la_LDFLAGS = -version-info @SPEEX_LT_CURRENT@:@SPEEX_LT_REVISION@:@SPEEX_LT_AGE@ +testenc_SOURCES = testenc.c +testenc_LDADD = libspeex.la +testenc_wb_SOURCES = testenc_wb.c +testenc_wb_LDADD = libspeex.la +testenc_uwb_SOURCES = testenc_uwb.c +testenc_uwb_LDADD = libspeex.la +all: all-am + +.SUFFIXES: +.SUFFIXES: .c .lo .o .obj +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ + && exit 0; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu libspeex/Makefile'; \ + cd $(top_srcdir) && \ + $(AUTOMAKE) --gnu libspeex/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +install-libLTLIBRARIES: $(lib_LTLIBRARIES) + @$(NORMAL_INSTALL) + test -z "$(libdir)" || $(mkdir_p) "$(DESTDIR)$(libdir)" + @list='$(lib_LTLIBRARIES)'; for p in $$list; do \ + if test -f $$p; then \ + f="`echo $$p | sed -e 's|^.*/||'`"; \ + echo " $(LIBTOOL) --mode=install $(libLTLIBRARIES_INSTALL) $(INSTALL_STRIP_FLAG) '$$p' '$(DESTDIR)$(libdir)/$$f'"; \ + $(LIBTOOL) --mode=install $(libLTLIBRARIES_INSTALL) $(INSTALL_STRIP_FLAG) "$$p" "$(DESTDIR)$(libdir)/$$f"; \ + else :; fi; \ + done + +uninstall-libLTLIBRARIES: + @$(NORMAL_UNINSTALL) + @list='$(lib_LTLIBRARIES)'; for p in $$list; do \ + p="`echo $$p | sed -e 's|^.*/||'`"; \ + echo " $(LIBTOOL) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$p'"; \ + $(LIBTOOL) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$p"; \ + done + +clean-libLTLIBRARIES: + -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) + @list='$(lib_LTLIBRARIES)'; for p in $$list; do \ + dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \ + test "$$dir" != "$$p" || dir=.; \ + echo "rm -f \"$${dir}/so_locations\""; \ + rm -f "$${dir}/so_locations"; \ + done +libspeex.la: $(libspeex_la_OBJECTS) $(libspeex_la_DEPENDENCIES) + $(LINK) -rpath $(libdir) $(libspeex_la_LDFLAGS) $(libspeex_la_OBJECTS) $(libspeex_la_LIBADD) $(LIBS) + +clean-noinstPROGRAMS: + @list='$(noinst_PROGRAMS)'; for p in $$list; do \ + f=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ + echo " rm -f $$p $$f"; \ + rm -f $$p $$f ; \ + done +testenc$(EXEEXT): $(testenc_OBJECTS) $(testenc_DEPENDENCIES) + @rm -f testenc$(EXEEXT) + $(LINK) $(testenc_LDFLAGS) $(testenc_OBJECTS) $(testenc_LDADD) $(LIBS) +testenc_uwb$(EXEEXT): $(testenc_uwb_OBJECTS) $(testenc_uwb_DEPENDENCIES) + @rm -f testenc_uwb$(EXEEXT) + $(LINK) $(testenc_uwb_LDFLAGS) $(testenc_uwb_OBJECTS) $(testenc_uwb_LDADD) $(LIBS) +testenc_wb$(EXEEXT): $(testenc_wb_OBJECTS) $(testenc_wb_DEPENDENCIES) + @rm -f testenc_wb$(EXEEXT) + $(LINK) $(testenc_wb_LDFLAGS) $(testenc_wb_OBJECTS) $(testenc_wb_LDADD) $(LIBS) + +mostlyclean-compile: + -rm -f *.$(OBJEXT) + +distclean-compile: + -rm -f *.tab.c + +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/bits.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/cb_search.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/exc_10_16_table.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/exc_10_32_table.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/exc_20_32_table.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/exc_5_256_table.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/exc_5_64_table.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/exc_8_128_table.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/filters.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gain_table.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gain_table_lbr.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/hexc_10_32_table.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/hexc_table.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/high_lsp_tables.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/lpc.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/lsp.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/lsp_tables_nb.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ltp.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/math_approx.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/misc.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/modes.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/nb_celp.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/quant_lsp.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sb_celp.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/speex_callbacks.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/speex_header.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/stereo.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testenc.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testenc_uwb.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testenc_wb.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/vbr.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/vq.Plo@am__quote@ + +.c.o: +@am__fastdepCC_TRUE@ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ +@am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ depfile='$(DEPDIR)/$*.Po' tmpdepfile='$(DEPDIR)/$*.TPo' @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(COMPILE) -c $< + +.c.obj: +@am__fastdepCC_TRUE@ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \ +@am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ depfile='$(DEPDIR)/$*.Po' tmpdepfile='$(DEPDIR)/$*.TPo' @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'` + +.c.lo: +@am__fastdepCC_TRUE@ if $(LTCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ +@am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Plo"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ depfile='$(DEPDIR)/$*.Plo' tmpdepfile='$(DEPDIR)/$*.TPlo' @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(LTCOMPILE) -c -o $@ $< + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +distclean-libtool: + -rm -f libtool +uninstall-info-am: + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + tags=; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$tags $$unique; \ + fi +ctags: CTAGS +CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + tags=; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + test -z "$(CTAGS_ARGS)$$tags$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$tags $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && cd $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) $$here + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ + list='$(DISTFILES)'; for file in $$list; do \ + case $$file in \ + $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ + $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ + esac; \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test "$$dir" != "$$file" && test "$$dir" != "."; then \ + dir="/$$dir"; \ + $(mkdir_p) "$(distdir)$$dir"; \ + else \ + dir=''; \ + fi; \ + if test -d $$d/$$file; then \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + fi; \ + cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + else \ + test -f $(distdir)/$$file \ + || cp -p $$d/$$file $(distdir)/$$file \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile $(LTLIBRARIES) $(PROGRAMS) $(HEADERS) +installdirs: + for dir in "$(DESTDIR)$(libdir)"; do \ + test -z "$$dir" || $(mkdir_p) "$$dir"; \ + done +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + `test -z '$(STRIP)' || \ + echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -rm -f $(CONFIG_CLEAN_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libLTLIBRARIES clean-libtool \ + clean-noinstPROGRAMS mostlyclean-am + +distclean: distclean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +distclean-am: clean-am distclean-compile distclean-generic \ + distclean-libtool distclean-tags + +dvi: dvi-am + +dvi-am: + +html: html-am + +info: info-am + +info-am: + +install-data-am: + +install-exec-am: install-libLTLIBRARIES + +install-info: install-info-am + +install-man: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-compile mostlyclean-generic \ + mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-info-am uninstall-libLTLIBRARIES + +.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ + clean-libLTLIBRARIES clean-libtool clean-noinstPROGRAMS ctags \ + distclean distclean-compile distclean-generic \ + distclean-libtool distclean-tags distdir dvi dvi-am html \ + html-am info info-am install install-am install-data \ + install-data-am install-exec install-exec-am install-info \ + install-info-am install-libLTLIBRARIES install-man \ + install-strip installcheck installcheck-am installdirs \ + maintainer-clean maintainer-clean-generic mostlyclean \ + mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ + pdf pdf-am ps ps-am tags uninstall uninstall-am \ + uninstall-info-am uninstall-libLTLIBRARIES + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/Code/BF2/External/speex-1.0.5/libspeex/bits.c b/Code/BF2/External/speex-1.0.5/libspeex/bits.c new file mode 100644 index 000000000..290b399bb --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/bits.c @@ -0,0 +1,363 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: speex_bits.c + + Handles bit packing/unpacking + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +*/ + +#include +#include "misc.h" + +void speex_bits_init(SpeexBits *bits) +{ + int i; + bits->bytes = (char*)speex_alloc(MAX_BYTES_PER_FRAME); + bits->buf_size = MAX_BYTES_PER_FRAME; + + for (i=0;ibuf_size;i++) + bits->bytes[i]=0; + bits->nbBits=0; + bits->bytePtr=0; + bits->bitPtr=0; + bits->owner=1; + bits->overflow=0; +} + +void speex_bits_init_buffer(SpeexBits *bits, void *buff, int buf_size) +{ + int i; + bits->bytes = (char*)buff; + bits->buf_size = buf_size; + + for (i=0;ibytes[i]=0; + bits->nbBits=0; + bits->bytePtr=0; + bits->bitPtr=0; + bits->owner=0; + bits->overflow=0; +} + +void speex_bits_destroy(SpeexBits *bits) +{ + if (bits->owner) + speex_free(bits->bytes); + /* Will do something once the allocation is dynamic */ +} + +void speex_bits_reset(SpeexBits *bits) +{ + int i; + for (i=0;ibuf_size;i++) + bits->bytes[i]=0; + bits->nbBits=0; + bits->bytePtr=0; + bits->bitPtr=0; + bits->overflow=0; +} + +void speex_bits_rewind(SpeexBits *bits) +{ + bits->bytePtr=0; + bits->bitPtr=0; + bits->overflow=0; +} + +void speex_bits_read_from(SpeexBits *bits, char *bytes, int len) +{ + int i; + if (len > bits->buf_size) + { + speex_warning_int("Packet is larger than allocated buffer: ", len); + if (bits->owner) + { + char *tmp = (char*)speex_realloc(bits->bytes, len); + if (tmp) + { + bits->buf_size=len; + bits->bytes=tmp; + } else { + len=bits->buf_size; + speex_warning("Could not resize input buffer: truncating input"); + } + } else { + speex_warning("Do not own input buffer: truncating input"); + len=bits->buf_size; + } + } + for (i=0;ibytes[i]=bytes[i]; + bits->nbBits=len<<3; + bits->bytePtr=0; + bits->bitPtr=0; + bits->overflow=0; +} + +static void speex_bits_flush(SpeexBits *bits) +{ + int i; + if (bits->bytePtr>0) + { + for (i=bits->bytePtr;i<((bits->nbBits+7)>>3);i++) + bits->bytes[i-bits->bytePtr]=bits->bytes[i]; + } + bits->nbBits -= bits->bytePtr<<3; + bits->bytePtr=0; +} + +void speex_bits_read_whole_bytes(SpeexBits *bits, char *bytes, int len) +{ + int i,pos; + + if ((bits->nbBits>>3)+len+1 > bits->buf_size) + { + speex_warning_int("Packet is larger than allocated buffer: ", len); + if (bits->owner) + { + char *tmp = (char*)speex_realloc(bits->bytes, (bits->nbBits>>3)+len+1); + if (tmp) + { + bits->buf_size=(bits->nbBits>>3)+len+1; + bits->bytes=tmp; + } else { + len=bits->buf_size-(bits->nbBits>>3)-1; + speex_warning("Could not resize input buffer: truncating input"); + } + } else { + speex_warning("Do not own input buffer: truncating input"); + len=bits->buf_size; + } + } + + speex_bits_flush(bits); + pos=bits->nbBits>>3; + for (i=0;ibytes[pos+i]=bytes[i]; + bits->nbBits+=len<<3; +} + +int speex_bits_write(SpeexBits *bits, char *bytes, int max_len) +{ + int i; + int bytePtr, bitPtr, nbBits; + + /* Insert terminator, but save the data so we can put it back after */ + bitPtr=bits->bitPtr; + bytePtr=bits->bytePtr; + nbBits=bits->nbBits; + speex_bits_insert_terminator(bits); + bits->bitPtr=bitPtr; + bits->bytePtr=bytePtr; + bits->nbBits=nbBits; + + if (max_len > ((bits->nbBits+7)>>3)) + max_len = ((bits->nbBits+7)>>3); + for (i=0;ibytes[i]; + return max_len; +} + +int speex_bits_write_whole_bytes(SpeexBits *bits, char *bytes, int max_len) +{ + int i; + if (max_len > ((bits->nbBits)>>3)) + max_len = ((bits->nbBits)>>3); + for (i=0;ibytes[i]; + + if (bits->bitPtr>0) + bits->bytes[0]=bits->bytes[max_len]; + else + bits->bytes[0]=0; + for (i=1;i<((bits->nbBits)>>3)+1;i++) + bits->bytes[i]=0; + bits->bytePtr=0; + bits->nbBits &= 7; + return max_len; +} + + +void speex_bits_pack(SpeexBits *bits, int data, int nbBits) +{ + int i; + unsigned int d=data; + + if (bits->bytePtr+((nbBits+bits->bitPtr)>>3) >= bits->buf_size) + { + speex_warning("Buffer too small to pack bits"); + if (bits->owner) + { + char *tmp = (char*)speex_realloc(bits->bytes, ((bits->buf_size+5)*3)>>1); + if (tmp) + { + for (i=bits->buf_size;i<(((bits->buf_size+5)*3)>>1);i++) + tmp[i]=0; + bits->buf_size=((bits->buf_size+5)*3)>>1; + bits->bytes=tmp; + } else { + speex_warning("Could not resize input buffer: not packing"); + return; + } + } else { + speex_warning("Do not own input buffer: not packing"); + return; + } + } + + while(nbBits) + { + int bit; + bit = (d>>(nbBits-1))&1; + bits->bytes[bits->bytePtr] |= bit<<(7-bits->bitPtr); + bits->bitPtr++; + + if (bits->bitPtr==8) + { + bits->bitPtr=0; + bits->bytePtr++; + } + bits->nbBits++; + nbBits--; + } +} + +int speex_bits_unpack_signed(SpeexBits *bits, int nbBits) +{ + unsigned int d=speex_bits_unpack_unsigned(bits,nbBits); + /* If number is negative */ + if (d>>(nbBits-1)) + { + d |= (-1)<bytePtr<<3)+bits->bitPtr+nbBits>bits->nbBits) + bits->overflow=1; + if (bits->overflow) + return 0; + while(nbBits) + { + d<<=1; + d |= (bits->bytes[bits->bytePtr]>>(7-bits->bitPtr))&1; + bits->bitPtr++; + if (bits->bitPtr==8) + { + bits->bitPtr=0; + bits->bytePtr++; + } + nbBits--; + } + return d; +} + +unsigned int speex_bits_peek_unsigned(SpeexBits *bits, int nbBits) +{ + unsigned int d=0; + int bitPtr, bytePtr; + char *bytes; + + if ((bits->bytePtr<<3)+bits->bitPtr+nbBits>bits->nbBits) + bits->overflow=1; + if (bits->overflow) + return 0; + + bitPtr=bits->bitPtr; + bytePtr=bits->bytePtr; + bytes = bits->bytes; + while(nbBits) + { + d<<=1; + d |= (bytes[bytePtr]>>(7-bitPtr))&1; + bitPtr++; + if (bitPtr==8) + { + bitPtr=0; + bytePtr++; + } + nbBits--; + } + return d; +} + +int speex_bits_peek(SpeexBits *bits) +{ + if ((bits->bytePtr<<3)+bits->bitPtr+1>bits->nbBits) + bits->overflow=1; + if (bits->overflow) + return 0; + return (bits->bytes[bits->bytePtr]>>(7-bits->bitPtr))&1; +} + +void speex_bits_advance(SpeexBits *bits, int n) +{ + int nbytes, nbits; + + if ((bits->bytePtr<<3)+bits->bitPtr+n>bits->nbBits) + bits->overflow=1; + if (bits->overflow) + return; + + nbytes = n >> 3; + nbits = n & 7; + + bits->bytePtr += nbytes; + bits->bitPtr += nbits; + + if (bits->bitPtr>7) + { + bits->bitPtr-=8; + bits->bytePtr++; + } +} + +int speex_bits_remaining(SpeexBits *bits) +{ + if (bits->overflow) + return -1; + else + return bits->nbBits-((bits->bytePtr<<3)+bits->bitPtr); +} + +int speex_bits_nbytes(SpeexBits *bits) +{ + return ((bits->nbBits+7)>>3); +} + +void speex_bits_insert_terminator(SpeexBits *bits) +{ + if (bits->bitPtr<7) + speex_bits_pack(bits, 0, 1); + while (bits->bitPtr<7) + speex_bits_pack(bits, 1, 1); +} diff --git a/Code/BF2/External/speex-1.0.5/libspeex/cb_search.c b/Code/BF2/External/speex-1.0.5/libspeex/cb_search.c new file mode 100644 index 000000000..785bb49b3 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/cb_search.c @@ -0,0 +1,387 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: cb_search.c + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + + +#include "cb_search.h" +#include "filters.h" +#include "stack_alloc.h" +#include "vq.h" +#include "misc.h" + +void split_cb_search_shape_sign( +float target[], /* target vector */ +float ak[], /* LPCs for this subframe */ +float awk1[], /* Weighted LPCs for this subframe */ +float awk2[], /* Weighted LPCs for this subframe */ +void *par, /* Codebook/search parameters*/ +int p, /* number of LPC coeffs */ +int nsf, /* number of samples in subframe */ +float *exc, +float *r, +SpeexBits *bits, +char *stack, +int complexity +) +{ + int i,j,k,m,n,q; + float *resp; + float *t, *e, *E, *r2; + float *tmp; + float *ndist, *odist; + int *itmp; + float **ot, **nt; + int **nind, **oind; + int *ind; + signed char *shape_cb; + int shape_cb_size, subvect_size, nb_subvect; + split_cb_params *params; + int N=2; + int *best_index; + float *best_dist; + int have_sign; + + N=complexity; + if (N>10) + N=10; + + ot=PUSH(stack, N, float*); + nt=PUSH(stack, N, float*); + oind=PUSH(stack, N, int*); + nind=PUSH(stack, N, int*); + + params = (split_cb_params *) par; + subvect_size = params->subvect_size; + nb_subvect = params->nb_subvect; + shape_cb_size = 1<shape_bits; + shape_cb = params->shape_cb; + have_sign = params->have_sign; + resp = PUSH(stack, shape_cb_size*subvect_size, float); + t = PUSH(stack, nsf, float); + e = PUSH(stack, nsf, float); + r2 = PUSH(stack, nsf, float); + E = PUSH(stack, shape_cb_size, float); + ind = PUSH(stack, nb_subvect, int); + + tmp = PUSH(stack, 2*N*nsf, float); + for (i=0;i=shape_cb_size) + { + sign=-1; + rind-=shape_cb_size; + } + res = resp+rind*subvect_size; + if (sign>0) + for (m=0;m=shape_cb_size) + { + sign=-1; + rind-=shape_cb_size; + } + + g=sign*0.03125*shape_cb[rind*subvect_size+m]; + q=subvect_size-m; + for (n=subvect_size*(i+1);nm;n--) + { + for (q=(i+1)*subvect_size;qshape_bits+have_sign); + } + + /* Put everything back together */ + for (i=0;i=shape_cb_size) + { + sign=-1; + rind-=shape_cb_size; + } + + for (j=0;jsubvect_size; + nb_subvect = params->nb_subvect; + shape_cb_size = 1<shape_bits; + shape_cb = params->shape_cb; + have_sign = params->have_sign; + + ind = PUSH(stack, nb_subvect, int); + signs = PUSH(stack, nb_subvect, int); + + /* Decode codewords and gains */ + for (i=0;ishape_bits); + } + /* Compute decoded excitation */ + for (i=0;i + +typedef struct split_cb_params { + int subvect_size; + int nb_subvect; + signed char *shape_cb; + int shape_bits; + int have_sign; +} split_cb_params; + + +void split_cb_search_shape_sign( +float target[], /* target vector */ +float ak[], /* LPCs for this subframe */ +float awk1[], /* Weighted LPCs for this subframe */ +float awk2[], /* Weighted LPCs for this subframe */ +void *par, /* Codebook/search parameters*/ +int p, /* number of LPC coeffs */ +int nsf, /* number of samples in subframe */ +float *exc, +float *r, +SpeexBits *bits, +char *stack, +int complexity +); + +void split_cb_shape_sign_unquant( +float *exc, +void *par, /* non-overlapping codebook */ +int nsf, /* number of samples in subframe */ +SpeexBits *bits, +char *stack +); + + +void noise_codebook_quant( +float target[], /* target vector */ +float ak[], /* LPCs for this subframe */ +float awk1[], /* Weighted LPCs for this subframe */ +float awk2[], /* Weighted LPCs for this subframe */ +void *par, /* Codebook/search parameters*/ +int p, /* number of LPC coeffs */ +int nsf, /* number of samples in subframe */ +float *exc, +float *r, +SpeexBits *bits, +char *stack, +int complexity +); + + +void noise_codebook_unquant( +float *exc, +void *par, /* non-overlapping codebook */ +int nsf, /* number of samples in subframe */ +SpeexBits *bits, +char *stack +); + +#endif diff --git a/Code/BF2/External/speex-1.0.5/libspeex/exc_10_16_table.c b/Code/BF2/External/speex-1.0.5/libspeex/exc_10_16_table.c new file mode 100644 index 000000000..322ef384a --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/exc_10_16_table.c @@ -0,0 +1,50 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: exc_10_16_table.c + Codebook for excitation in narrowband CELP mode (3200 bps) + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + + +signed char exc_10_16_table[160] = { +22,39,14,44,11,35,-2,23,-4,6, +46,-28,13,-27,-23,12,4,20,-5,9, +37,-18,-23,23,0,9,-6,-20,4,-1, +-17,-5,-4,17,0,1,9,-2,1,2, +2,-12,8,-25,39,15,9,16,-55,-11, +9,11,5,10,-2,-60,8,13,-6,11, +-16,27,-47,-12,11,1,16,-7,9,-3, +-29,9,-14,25,-19,34,36,12,40,-10, +-3,-24,-14,-37,-21,-35,-2,-36,3,-6, +67,28,6,-17,-3,-12,-16,-15,-17,-7, +-59,-36,-13,1,7,1,2,10,2,11, +13,10,8,-2,7,3,5,4,2,2, +-3,-8,4,-5,6,7,-42,15,35,-2, +-46,38,28,-20,-9,1,7,-3,0,-2, +0,0,0,0,0,0,0,0,0,0, +-15,-28,52,32,5,-5,-17,-20,-10,-1}; diff --git a/Code/BF2/External/speex-1.0.5/libspeex/exc_10_32_table.c b/Code/BF2/External/speex-1.0.5/libspeex/exc_10_32_table.c new file mode 100644 index 000000000..75a8cb0a6 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/exc_10_32_table.c @@ -0,0 +1,66 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: exc_10_32_table.c + Codebook for excitation in narrowband CELP mode (4000 bps) + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + + +signed char exc_10_32_table[320] = { +7,17,17,27,25,22,12,4,-3,0, +28,-36,39,-24,-15,3,-9,15,-5,10, +31,-28,11,31,-21,9,-11,-11,-2,-7, +-25,14,-22,31,4,-14,19,-12,14,-5, +4,-7,4,-5,9,0,-2,42,-47,-16, +1,8,0,9,23,-57,0,28,-11,6, +-31,55,-45,3,-5,4,2,-2,4,-7, +-3,6,-2,7,-3,12,5,8,54,-10, +8,-7,-8,-24,-25,-27,-14,-5,8,5, +44,23,5,-9,-11,-11,-13,-9,-12,-8, +-29,-8,-22,6,-15,3,-12,-1,-5,-3, +34,-1,29,-16,17,-4,12,2,1,4, +-2,-4,2,-1,11,-3,-52,28,30,-9, +-32,25,44,-20,-24,4,6,-1,0,0, +0,0,0,0,0,0,0,0,0,0, +-25,-10,22,29,13,-13,-22,-13,-4,0, +-4,-16,10,15,-36,-24,28,25,-1,-3, +66,-33,-11,-15,6,0,3,4,-2,5, +24,-20,-47,29,19,-2,-4,-1,0,-1, +-2,3,1,8,-11,5,5,-57,28,28, +0,-16,4,-4,12,-6,-1,2,-20,61, +-9,24,-22,-42,29,6,17,8,4,2, +-65,15,8,10,5,6,5,3,2,-2, +-3,5,-9,4,-5,23,13,23,-3,-63, +3,-5,-4,-6,0,-3,23,-36,-46,9, +5,5,8,4,9,-5,1,-3,10,1, +-6,10,-11,24,-47,31,22,-12,14,-10, +6,11,-7,-7,7,-31,51,-12,-6,7, +6,-17,9,-11,-20,52,-19,3,-6,-6, +-8,-5,23,-41,37,1,-21,10,-14,8, +7,5,-15,-15,23,39,-26,-33,7,2, +-32,-30,-21,-8,4,12,17,15,14,11}; diff --git a/Code/BF2/External/speex-1.0.5/libspeex/exc_20_32_table.c b/Code/BF2/External/speex-1.0.5/libspeex/exc_20_32_table.c new file mode 100644 index 000000000..76b0c94bb --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/exc_20_32_table.c @@ -0,0 +1,66 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: exc_20_32_table.c + Codebook for excitation in narrowband CELP mode (2000 bps) + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + + +signed char exc_20_32_table[640] = { +12,32,25,46,36,33,9,14,-3,6,1,-8,0,-10,-5,-7,-7,-7,-5,-5, +31,-27,24,-32,-4,10,-11,21,-3,19,23,-9,22,24,-10,-1,-10,-13,-7,-11, +42,-33,31,19,-8,0,-10,-16,1,-21,-17,10,-8,14,8,4,11,-2,5,-2, +-33,11,-16,33,11,-4,9,-4,11,2,6,-5,8,-5,11,-4,-6,26,-36,-16, +0,4,-2,-8,12,6,-1,34,-46,-22,9,9,21,9,5,-66,-5,26,2,10, +13,2,19,9,12,-81,3,13,13,0,-14,22,-35,6,-7,-4,6,-6,10,-6, +-31,38,-33,0,-10,-11,5,-12,12,-17,5,0,-6,13,-9,10,8,25,33,2, +-12,8,-6,10,-2,21,7,17,43,5,11,-7,-9,-20,-36,-20,-23,-4,-4,-3, +27,-9,-9,-49,-39,-38,-11,-9,6,5,23,25,5,3,3,4,1,2,-3,-1, +87,39,17,-21,-9,-19,-9,-15,-13,-14,-17,-11,-10,-11,-8,-6,-1,-3,-3,-1, +-54,-34,-27,-8,-11,-4,-5,0,0,4,8,6,9,7,9,7,6,5,5,5, +48,10,19,-10,12,-1,9,-3,2,5,-3,2,-2,-2,0,-2,-26,6,9,-7, +-16,-9,2,7,7,-5,-43,11,22,-11,-9,34,37,-15,-13,-6,1,-1,1,1, +-64,56,52,-11,-27,5,4,3,1,2,1,3,-1,-4,-4,-10,-7,-4,-4,2, +-1,-7,-7,-12,-10,-15,-9,-5,-5,-11,-16,-13,6,16,4,-13,-16,-10,-4,2, +-47,-13,25,47,19,-14,-20,-8,-17,0,-3,-13,1,6,-17,-14,15,1,10,6, +-24,0,-10,19,-69,-8,14,49,17,-5,33,-29,3,-4,0,2,-8,5,-6,2, +120,-56,-12,-47,23,-9,6,-5,1,2,-5,1,-10,4,-1,-1,4,-1,0,-3, +30,-52,-67,30,22,11,-1,-4,3,0,7,2,0,1,-10,-4,-8,-13,5,1, +1,-1,5,13,-9,-3,-10,-62,22,48,-4,-6,2,3,5,1,1,4,1,13, +3,-20,10,-9,13,-2,-4,9,-20,44,-1,20,-32,-67,19,0,28,11,8,2, +-11,15,-19,-53,31,2,34,10,6,-4,-58,8,10,13,14,1,12,2,0,0, +-128,37,-8,44,-9,26,-3,18,2,6,11,-1,9,1,5,3,0,1,1,2, +12,3,-2,-3,7,25,9,18,-6,-37,3,-8,-16,3,-10,-7,17,-34,-44,11, +17,-15,-3,-16,-1,-13,11,-46,-65,-2,8,13,2,4,4,5,15,5,9,6, +0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, +-9,19,-12,12,-28,38,29,-1,12,2,5,23,-10,3,4,-15,21,-4,3,3, +6,17,-9,-4,-8,-20,26,5,-10,6,1,-19,18,-15,-12,47,-6,-2,-7,-9, +-1,-17,-2,-2,-14,30,-14,2,-7,-4,-1,-12,11,-25,16,-3,-12,11,-7,7, +-17,1,19,-28,31,-7,-10,7,-10,3,12,5,-16,6,24,41,-29,-54,0,1, +7,-1,5,-6,13,10,-4,-8,8,-9,-27,-53,-38,-1,10,19,17,16,12,12, +0,3,-7,-4,13,12,-31,-14,6,-5,3,5,17,43,50,25,10,1,-6,-2}; diff --git a/Code/BF2/External/speex-1.0.5/libspeex/exc_5_256_table.c b/Code/BF2/External/speex-1.0.5/libspeex/exc_5_256_table.c new file mode 100644 index 000000000..1ceb2d42c --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/exc_5_256_table.c @@ -0,0 +1,290 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: exc_5_256_table.c + Codebook for excitation in narrowband CELP mode (12800 bps) + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + + +signed char exc_5_256_table[1280] = { +-8,-37,5,-43,5, +73,61,39,12,-3, +-61,-32,2,42,30, +-3,17,-27,9,34, +20,-1,-5,2,23, +-7,-46,26,53,-47, +20,-2,-33,-89,-51, +-64,27,11,15,-34, +-5,-56,25,-9,-1, +-29,1,40,67,-23, +-16,16,33,19,7, +14,85,22,-10,-10, +-12,-7,-1,52,89, +29,11,-20,-37,-46, +-15,17,-24,-28,24, +2,1,0,23,-101, +23,14,-1,-23,-18, +9,5,-13,38,1, +-28,-28,4,27,51, +-26,34,-40,35,47, +54,38,-54,-26,-6, +42,-25,13,-30,-36, +18,41,-4,-33,23, +-32,-7,-4,51,-3, +17,-52,56,-47,36, +-2,-21,36,10,8, +-33,31,19,9,-5, +-40,10,-9,-21,19, +18,-78,-18,-5,0, +-26,-36,-47,-51,-44, +18,40,27,-2,29, +49,-26,2,32,-54, +30,-73,54,3,-5, +36,22,53,10,-1, +-84,-53,-29,-5,3, +-44,53,-51,4,22, +71,-35,-1,33,-5, +-27,-7,36,17,-23, +-39,16,-9,-55,-15, +-20,39,-35,6,-39, +-14,18,48,-64,-17, +-15,9,39,81,37, +-68,37,47,-21,-6, +-104,13,6,9,-2, +35,8,-23,18,42, +45,21,33,-5,-49, +9,-6,-43,-56,39, +2,-16,-25,87,1, +-3,-9,17,-25,-11, +-9,-1,10,2,-14, +-14,4,-1,-10,28, +-23,40,-32,26,-9, +26,4,-27,-23,3, +42,-60,1,49,-3, +27,10,-52,-40,-2, +18,45,-23,17,-44, +3,-3,17,-46,52, +-40,-47,25,75,31, +-49,53,30,-30,-32, +-36,38,-6,-15,-16, +54,-27,-48,3,38, +-29,-32,-22,-14,-4, +-23,-13,32,-39,9, +8,-45,-13,34,-16, +49,40,32,31,28, +23,23,32,47,59, +-68,8,62,44,25, +-14,-24,-65,-16,36, +67,-25,-38,-21,4, +-33,-2,42,5,-63, +40,11,26,-42,-23, +-61,79,-31,23,-20, +10,-32,53,-25,-36, +10,-26,-5,3,0, +-71,5,-10,-37,1, +-24,21,-54,-17,1, +-29,-25,-15,-27,32, +68,45,-16,-37,-18, +-5,1,0,-77,71, +-6,3,-20,71,-67, +29,-35,10,-30,19, +4,16,17,5,0, +-14,19,2,28,26, +59,3,2,24,39, +55,-50,-45,-18,-17, +33,-35,14,-1,1, +8,87,-35,-29,0, +-27,13,-7,23,-13, +37,-40,50,-35,14, +19,-7,-14,49,54, +-5,22,-2,-29,-8, +-27,38,13,27,48, +12,-41,-21,-15,28, +7,-16,-24,-19,-20, +11,-20,9,2,13, +23,-20,11,27,-27, +71,-69,8,2,-6, +22,12,16,16,9, +-16,-8,-17,1,25, +1,40,-37,-33,66, +94,53,4,-22,-25, +-41,-42,25,35,-16, +-15,57,31,-29,-32, +21,16,-60,45,15, +-1,7,57,-26,-47, +-29,11,8,15,19, +-105,-8,54,27,10, +-17,6,-12,-1,-10, +4,0,23,-10,31, +13,11,10,12,-64, +23,-3,-8,-19,16, +52,24,-40,16,10, +40,5,9,0,-13, +-7,-21,-8,-6,-7, +-21,59,16,-53,18, +-60,11,-47,14,-18, +25,-13,-24,4,-39, +16,-28,54,26,-67, +30,27,-20,-52,20, +-12,55,12,18,-16, +39,-14,-6,-26,56, +-88,-55,12,25,26, +-37,6,75,0,-34, +-81,54,-30,1,-7, +49,-23,-14,21,10, +-62,-58,-57,-47,-34, +15,-4,34,-78,31, +25,-11,7,50,-10, +42,-63,14,-36,-4, +57,55,57,53,42, +-42,-1,15,40,37, +15,25,-11,6,1, +31,-2,-6,-1,-7, +-64,34,28,30,-1, +3,21,0,-88,-12, +-56,25,-28,40,8, +-28,-14,9,12,2, +-6,-17,22,49,-6, +-26,14,28,-20,4, +-12,50,35,40,13, +-38,-58,-29,17,30, +22,60,26,-54,-39, +-12,58,-28,-63,10, +-21,-8,-12,26,-62, +6,-10,-11,-22,-6, +-7,4,1,18,2, +-70,11,14,4,13, +19,-24,-34,24,67, +17,51,-21,13,23, +54,-30,48,1,-13, +80,26,-16,-2,13, +-4,6,-30,29,-24, +73,-58,30,-27,20, +-2,-21,41,45,30, +-27,-3,-5,-18,-20, +-49,-3,-35,10,42, +-19,-67,-53,-11,9, +13,-15,-33,-51,-30, +15,7,25,-30,4, +28,-22,-34,54,-29, +39,-46,20,16,34, +-4,47,75,1,-44, +-55,-24,7,-1,9, +-42,50,-8,-36,41, +68,0,-4,-10,-23, +-15,-50,64,36,-9, +-27,12,25,-38,-47, +-37,32,-49,51,-36, +2,-4,69,-26,19, +7,45,67,46,13, +-63,46,15,-47,4, +-41,13,-6,5,-21, +37,26,-55,-7,33, +-1,-28,10,-17,-64, +-14,0,-36,-17,93, +-3,-9,-66,44,-21, +3,-12,38,-6,-13, +-12,19,13,43,-43, +-10,-12,6,-5,9, +-49,32,-5,2,4, +5,15,-16,10,-21, +8,-62,-8,64,8, +79,-1,-66,-49,-18, +5,40,-5,-30,-45, +1,-6,21,-32,93, +-18,-30,-21,32,21, +-18,22,8,5,-41, +-54,80,22,-10,-7, +-8,-23,-64,66,56, +-14,-30,-41,-46,-14, +-29,-37,27,-14,42, +-2,-9,-29,34,14, +33,-14,22,4,10, +26,26,28,32,23, +-72,-32,3,0,-14, +35,-42,-78,-32,6, +29,-18,-45,-5,7, +-33,-45,-3,-22,-34, +8,-8,4,-51,-25, +-9,59,-78,21,-5, +-25,-48,66,-15,-17, +-24,-49,-13,25,-23, +-64,-6,40,-24,-19, +-11,57,-33,-8,1, +10,-52,-54,28,39, +49,34,-11,-61,-41, +-43,10,15,-15,51, +30,15,-51,32,-34, +-2,-34,14,18,16, +1,1,-3,-3,1, +1,-18,6,16,48, +12,-5,-42,7,36, +48,7,-20,-10,7, +12,2,54,39,-38, +37,54,4,-11,-8, +-46,-10,5,-10,-34, +46,-12,29,-37,39, +36,-11,24,56,17, +14,20,25,0,-25, +-28,55,-7,-5,27, +3,9,-26,-8,6, +-24,-10,-30,-31,-34, +18,4,22,21,40, +-1,-29,-37,-8,-21, +92,-29,11,-3,11, +73,23,22,7,4, +-44,-9,-11,21,-13, +11,9,-78,-1,47, +114,-12,-37,-19,-5, +-11,-22,19,12,-30, +7,38,45,-21,-8, +-9,55,-45,56,-21, +7,17,46,-57,-87, +-6,27,31,31,7, +-56,-12,46,21,-5, +-12,36,3,3,-21, +43,19,12,-7,9, +-14,0,-9,-33,-91, +7,26,3,-11,64, +83,-31,-46,25,2, +9,5,2,2,-1, +20,-17,10,-5,-27, +-8,20,8,-19,16, +-21,-13,-31,5,5, +42,24,9,34,-20, +28,-61,22,11,-39, +64,-20,-1,-30,-9, +-20,24,-25,-24,-29, +22,-60,6,-5,41, +-9,-87,14,34,15, +-57,52,69,15,-3, +-102,58,16,3,6, +60,-75,-32,26,7, +-57,-27,-32,-24,-21, +-29,-16,62,-46,31, +30,-27,-15,7,15}; diff --git a/Code/BF2/External/speex-1.0.5/libspeex/exc_5_64_table.c b/Code/BF2/External/speex-1.0.5/libspeex/exc_5_64_table.c new file mode 100644 index 000000000..ec08abfc9 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/exc_5_64_table.c @@ -0,0 +1,98 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: exc_5_64_table.c + Codebook for excitation in narrowband CELP mode (9600 bps) + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + + +signed char exc_5_64_table[320]={ +1,5,-15,49,-66, +-48,-4,50,-44,7, +37,16,-18,25,-26, +-26,-15,19,19,-27, +-47,28,57,5,-17, +-32,-41,68,21,-2, +64,56,8,-16,-13, +-26,-9,-16,11,6, +-39,25,-19,22,-31, +20,-45,55,-43,10, +-16,47,-40,40,-20, +-51,3,-17,-14,-15, +-24,53,-20,-46,46, +27,-68,32,3,-18, +-5,9,-31,16,-9, +-10,-1,-23,48,95, +47,25,-41,-32,-3, +15,-25,-55,36,41, +-27,20,5,13,14, +-22,5,2,-23,18, +46,-15,17,-18,-34, +-5,-8,27,-55,73, +16,2,-1,-17,40, +-78,33,0,2,19, +4,53,-16,-15,-16, +-28,-3,-13,49,8, +-7,-29,27,-13,32, +20,32,-61,16,14, +41,44,40,24,20, +7,4,48,-60,-77, +17,-6,-48,65,-15, +32,-30,-71,-10,-3, +-6,10,-2,-7,-29, +-56,67,-30,7,-5, +86,-6,-10,0,5, +-31,60,34,-38,-3, +24,10,-2,30,23, +24,-41,12,70,-43, +15,-17,6,13,16, +-13,8,30,-15,-8, +5,23,-34,-98,-4, +-13,13,-48,-31,70, +12,31,25,24,-24, +26,-7,33,-16,8, +5,-11,-14,-8,-65, +13,10,-2,-9,0, +-3,-68,5,35,7, +0,-31,-1,-17,-9, +-9,16,-37,-18,-1, +69,-48,-28,22,-21, +-11,5,49,55,23, +-86,-36,16,2,13, +63,-51,30,-11,13, +24,-18,-6,14,-19, +1,41,9,-5,27, +-36,-44,-34,-37,-21, +-26,31,-39,15,43, +5,-8,29,20,-8, +-20,-52,-28,-1,13, +26,-34,-10,-9,27, +-8,8,27,-66,4, +12,-22,49,10,-77, +32,-18,3,-38,12, +-3,-1,2,2,0}; diff --git a/Code/BF2/External/speex-1.0.5/libspeex/exc_8_128_table.c b/Code/BF2/External/speex-1.0.5/libspeex/exc_8_128_table.c new file mode 100644 index 000000000..e812a8d17 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/exc_8_128_table.c @@ -0,0 +1,162 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: exc_8_128_table.c + Codebook for excitation in narrowband CELP mode (7000 bps) + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + + +signed char exc_8_128_table[1024] = { +-14,9,13,-32,2,-10,31,-10, +-8,-8,6,-4,-1,10,-64,23, +6,20,13,6,8,-22,16,34, +7,42,-49,-28,5,26,4,-15, +41,34,41,32,33,24,23,14, +8,40,34,4,-24,-41,-19,-15, +13,-13,33,-54,24,27,-44,33, +27,-15,-15,24,-19,14,-36,14, +-9,24,-12,-4,37,-5,16,-34, +5,10,33,-15,-54,-16,12,25, +12,1,2,0,3,-1,-4,-4, +11,2,-56,54,27,-20,13,-6, +-46,-41,-33,-11,-5,7,12,14, +-14,-5,8,20,6,3,4,-8, +-5,-42,11,8,-14,25,-2,2, +13,11,-22,39,-9,9,5,-45, +-9,7,-9,12,-7,34,-17,-102, +7,2,-42,18,35,-9,-34,11, +-5,-2,3,22,46,-52,-25,-9, +-94,8,11,-5,-5,-5,4,-7, +-35,-7,54,5,-32,3,24,-9, +-22,8,65,37,-1,-12,-23,-6, +-9,-28,55,-33,14,-3,2,18, +-60,41,-17,8,-16,17,-11,0, +-11,29,-28,37,9,-53,33,-14, +-9,7,-25,-7,-11,26,-32,-8, +24,-21,22,-19,19,-10,29,-14, +0,0,0,0,0,0,0,0, +-5,-52,10,41,6,-30,-4,16, +32,22,-27,-22,32,-3,-28,-3, +3,-35,6,17,23,21,8,2, +4,-45,-17,14,23,-4,-31,-11, +-3,14,1,19,-11,2,61,-8, +9,-12,7,-10,12,-3,-24,99, +-48,23,50,-37,-5,-23,0,8, +-14,35,-64,-5,46,-25,13,-1, +-49,-19,-15,9,34,50,25,11, +-6,-9,-16,-20,-32,-33,-32,-27, +10,-8,12,-15,56,-14,-32,33, +3,-9,1,65,-9,-9,-10,-2, +-6,-23,9,17,3,-28,13,-32, +4,-2,-10,4,-16,76,12,-52, +6,13,33,-6,4,-14,-9,-3, +1,-15,-16,28,1,-15,11,16, +9,4,-21,-37,-40,-6,22,12, +-15,-23,-14,-17,-16,-9,-10,-9, +13,-39,41,5,-9,16,-38,25, +46,-47,4,49,-14,17,-2,6, +18,5,-6,-33,-22,44,50,-2, +1,3,-6,7,7,-3,-21,38, +-18,34,-14,-41,60,-13,6,16, +-24,35,19,-13,-36,24,3,-17, +-14,-10,36,44,-44,-29,-3,3, +-54,-8,12,55,26,4,-2,-5, +2,-11,22,-23,2,22,1,-25, +-39,66,-49,21,-8,-2,10,-14, +-60,25,6,10,27,-25,16,5, +-2,-9,26,-13,-20,58,-2,7, +52,-9,2,5,-4,-15,23,-1, +-38,23,8,27,-6,0,-27,-7, +39,-10,-14,26,11,-45,-12,9, +-5,34,4,-35,10,43,-22,-11, +56,-7,20,1,10,1,-26,9, +94,11,-27,-14,-13,1,-11,0, +14,-5,-6,-10,-4,-15,-8,-41, +21,-5,1,-28,-8,22,-9,33, +-23,-4,-4,-12,39,4,-7,3, +-60,80,8,-17,2,-6,12,-5, +1,9,15,27,31,30,27,23, +61,47,26,10,-5,-8,-12,-13, +5,-18,25,-15,-4,-15,-11,12, +-2,-2,-16,-2,-6,24,12,11, +-4,9,1,-9,14,-45,57,12, +20,-35,26,11,-64,32,-10,-10, +42,-4,-9,-16,32,24,7,10, +52,-11,-57,29,0,8,0,-6, +17,-17,-56,-40,7,20,18,12, +-6,16,5,7,-1,9,1,10, +29,12,16,13,-2,23,7,9, +-3,-4,-5,18,-64,13,55,-25, +9,-9,24,14,-25,15,-11,-40, +-30,37,1,-19,22,-5,-31,13, +-2,0,7,-4,16,-67,12,66, +-36,24,-8,18,-15,-23,19,0, +-45,-7,4,3,-13,13,35,5, +13,33,10,27,23,0,-7,-11, +43,-74,36,-12,2,5,-8,6, +-33,11,-16,-14,-5,-7,-3,17, +-34,27,-16,11,-9,15,33,-31, +8,-16,7,-6,-7,63,-55,-17, +11,-1,20,-46,34,-30,6,9, +19,28,-9,5,-24,-8,-23,-2, +31,-19,-16,-5,-15,-18,0,26, +18,37,-5,-15,-2,17,5,-27, +21,-33,44,12,-27,-9,17,11, +25,-21,-31,-7,13,33,-8,-25, +-7,7,-10,4,-6,-9,48,-82, +-23,-8,6,11,-23,3,-3,49, +-29,25,31,4,14,16,9,-4, +-18,10,-26,3,5,-44,-9,9, +-47,-55,15,9,28,1,4,-3, +46,6,-6,-38,-29,-31,-15,-6, +3,0,14,-6,8,-54,-50,33, +-5,1,-14,33,-48,26,-4,-5, +-3,-5,-3,-5,-28,-22,77,55, +-1,2,10,10,-9,-14,-66,-49, +11,-36,-6,-20,10,-10,16,12, +4,-1,-16,45,-44,-50,31,-2, +25,42,23,-32,-22,0,11,20, +-40,-35,-40,-36,-32,-26,-21,-13, +52,-22,6,-24,-20,17,-5,-8, +36,-25,-11,21,-26,6,34,-8, +7,20,-3,5,-25,-8,18,-5, +-9,-4,1,-9,20,20,39,48, +-24,9,5,-65,22,29,4,3, +-43,-11,32,-6,9,19,-27,-10, +-47,-14,24,10,-7,-36,-7,-1, +-4,-5,-5,16,53,25,-26,-29, +-4,-12,45,-58,-34,33,-5,2, +-1,27,-48,31,-15,22,-5,4, +7,7,-25,-3,11,-22,16,-12, +8,-3,7,-11,45,14,-73,-19, +56,-46,24,-20,28,-12,-2,-1, +-36,-3,-33,19,-6,7,2,-15, +5,-31,-45,8,35,13,20,0, +-9,48,-13,-43,-3,-13,2,-5, +72,-68,-27,2,1,-2,-7,5, +36,33,-40,-12,-4,-5,23,19}; diff --git a/Code/BF2/External/speex-1.0.5/libspeex/filters.c b/Code/BF2/External/speex-1.0.5/libspeex/filters.c new file mode 100644 index 000000000..e924ef019 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/filters.c @@ -0,0 +1,292 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: filters.c + Various analysis/synthesis filters + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include "filters.h" +#include "stack_alloc.h" +#include + + +void bw_lpc(float gamma, float *lpc_in, float *lpc_out, int order) +{ + int i; + float tmp=1; + for (i=0;i>1; + for (i=0;ilast_pitch=0; + mem->last_pitch_gain[0]=mem->last_pitch_gain[1]=mem->last_pitch_gain[2]=0; + mem->smooth_gain=1; +} + +void comb_filter( +float *exc, /*decoded excitation*/ +float *new_exc, /*enhanced excitation*/ +float *ak, /*LPC filter coefs*/ +int p, /*LPC order*/ +int nsf, /*sub-frame size*/ +int pitch, /*pitch period*/ +float *pitch_gain, /*pitch gain (3-tap)*/ +float comb_gain, /*gain of comb filter*/ +CombFilterMem *mem +) +{ + int i; + float exc_energy=0, new_exc_energy=0; + float gain; + float step; + float fact; + /*Compute excitation energy prior to enhancement*/ + for (i=0;ilast_pitch_gain[0] + mem->last_pitch_gain[1] + mem->last_pitch_gain[2]); + if (g>1.3) + comb_gain*=1.3/g; + if (g<.5) + comb_gain*=2*g; + } + step = 1.0/nsf; + fact=0; + /*Apply pitch comb-filter (filter out noise between pitch harmonics)*/ + for (i=0;ilast_pitch_gain[0]*exc[i-mem->last_pitch+1] + + mem->last_pitch_gain[1]*exc[i-mem->last_pitch] + + mem->last_pitch_gain[2]*exc[i-mem->last_pitch-1] + ); + } + + mem->last_pitch_gain[0] = pitch_gain[0]; + mem->last_pitch_gain[1] = pitch_gain[1]; + mem->last_pitch_gain[2] = pitch_gain[2]; + mem->last_pitch = pitch; + + /*Gain after enhancement*/ + for (i=0;i1) + gain=1; + + for (i=0;ismooth_gain = .96*mem->smooth_gain + .04*gain; + new_exc[i] *= mem->smooth_gain; + } +} diff --git a/Code/BF2/External/speex-1.0.5/libspeex/filters.h b/Code/BF2/External/speex-1.0.5/libspeex/filters.h new file mode 100644 index 000000000..ad6dc022d --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/filters.h @@ -0,0 +1,79 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: filters.h + Various analysis/synthesis filters + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef FILTERS_H +#define FILTERS_H + + +typedef struct CombFilterMem { + int last_pitch; + float last_pitch_gain[3]; + float smooth_gain; +} CombFilterMem; + + +void qmf_decomp(float *xx, float *aa, float *y1, float *y2, int N, int M, float *mem, char *stack); +void fir_mem_up(float *x, float *a, float *y, int N, int M, float *mem, char *stack); + + +void filter_mem2(float *x, float *num, float *den, float *y, int N, int ord, float *mem); +void fir_mem2(float *x, float *num, float *y, int N, int ord, float *mem); +void iir_mem2(float *x, float *den, float *y, int N, int ord, float *mem); + +/* Apply bandwidth expansion on LPC coef */ +void bw_lpc(float gamma, float *lpc_in, float *lpc_out, int order); + + + +/* FIR filter */ +void fir_decim_mem(float *x, float *a, float *y, int N, int M, float *mem); + +void syn_percep_zero(float *x, float *ak, float *awk1, float *awk2, float *y, int N, int ord, char *stack); + +void residue_percep_zero(float *xx, float *ak, float *awk1, float *awk2, float *y, int N, int ord, char *stack); + +void comp_filter_mem_init (CombFilterMem *mem); + +void comb_filter( +float *exc, /*decoded excitation*/ +float *new_exc, /*enhanced excitation*/ +float *ak, /*LPC filter coefs*/ +int p, /*LPC order*/ +int nsf, /*sub-frame size*/ +int pitch, /*pitch period*/ +float *pitch_gain, /*pitch gain (3-tap)*/ +float comb_gain, /*gain of comb filter*/ +CombFilterMem *mem +); + + +#endif diff --git a/Code/BF2/External/speex-1.0.5/libspeex/filters_sse.h b/Code/BF2/External/speex-1.0.5/libspeex/filters_sse.h new file mode 100644 index 000000000..3fba6c8d6 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/filters_sse.h @@ -0,0 +1,289 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: filters.c + Various analysis/synthesis filters + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +void filter_mem2(float *x, float *_num, float *_den, float *y, int N, int ord, float *_mem) +{ + float __num[20], __den[20], __mem[20]; + float *num, *den, *mem; + int i; + + num = (float*)(((int)(__num+4))&0xfffffff0)-1; + den = (float*)(((int)(__den+4))&0xfffffff0)-1; + mem = (float*)(((int)(__mem+4))&0xfffffff0)-1; + for (i=0;i<=10;i++) + num[i]=den[i]=0; + for (i=0;i<10;i++) + mem[i]=0; + + for (i=0;i x(n) * x(n-i) for all n + * `--' + * for lags between 0 and lag-1, and x == 0 outside 0...n-1 + */ +void _spx_autocorr( + const float * x, /* in: [0...n-1] samples x */ + float *ac, /* out: [0...lag-1] ac values */ + int lag, int n) +{ + float d; int i; + while (lag--) { + for (i = lag, d = 0; i < n; i++) d += x[i] * x[i-lag]; + ac[lag] = d; + } +} diff --git a/Code/BF2/External/speex-1.0.5/libspeex/lpc.h b/Code/BF2/External/speex-1.0.5/libspeex/lpc.h new file mode 100644 index 000000000..e3f70b5a6 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/lpc.h @@ -0,0 +1,50 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: lpc.h + Functions for LPC (Linear Prediction Coefficients) analysis + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef LPC_H +#define LPC_H + +void _spx_autocorr( + const float * x, /* in: [0...n-1] samples x */ + float *ac, /* out: [0...lag-1] ac values */ + int lag, int n); + +float /* returns minimum mean square error */ +wld( + float * lpc, /* [0...p-1] LPC coefficients */ + const float * ac, /* in: [0...p] autocorrelation values */ + float * ref, /* out: [0...p-1] reflection coef's */ + int p + ); + + +#endif diff --git a/Code/BF2/External/speex-1.0.5/libspeex/lsp.c b/Code/BF2/External/speex-1.0.5/libspeex/lsp.c new file mode 100644 index 000000000..1af762cdf --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/lsp.c @@ -0,0 +1,328 @@ +/*---------------------------------------------------------------------------*\ +Original copyright + FILE........: AKSLSPD.C + TYPE........: Turbo C + COMPANY.....: Voicetronix + AUTHOR......: David Rowe + DATE CREATED: 24/2/93 + +Modified by Jean-Marc Valin + + This file contains functions for converting Linear Prediction + Coefficients (LPC) to Line Spectral Pair (LSP) and back. Note that the + LSP coefficients are not in radians format but in the x domain of the + unit circle. + + Speex License: + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include +#include "lsp.h" +#include "stack_alloc.h" + + +#ifndef M_PI +#define M_PI 3.14159265358979323846 /* pi */ +#endif + +#ifndef NULL +#define NULL 0 +#endif + +/*---------------------------------------------------------------------------*\ + + FUNCTION....: cheb_poly_eva() + + AUTHOR......: David Rowe + DATE CREATED: 24/2/93 + + This function evaluates a series of Chebyshev polynomials + +\*---------------------------------------------------------------------------*/ + + + +static float cheb_poly_eva(float *coef,float x,int m,char *stack) +/* float coef[] coefficients of the polynomial to be evaluated */ +/* float x the point where polynomial is to be evaluated */ +/* int m order of the polynomial */ +{ + int i; + float *T,sum; + int m2=m>>1; + + /* Allocate memory for Chebyshev series formulation */ + T=PUSH(stack, m2+1, float); + + /* Initialise values */ + T[0]=1; + T[1]=x; + + /* Evaluate Chebyshev series formulation using iterative approach */ + /* Evaluate polynomial and return value also free memory space */ + sum = coef[m2] + coef[m2-1]*x; + x *= 2; + for(i=2;i<=m2;i++) + { + T[i] = x*T[i-1] - T[i-2]; + sum += coef[m2-i] * T[i]; + } + + return sum; +} + + +/*---------------------------------------------------------------------------*\ + + FUNCTION....: lpc_to_lsp() + + AUTHOR......: David Rowe + DATE CREATED: 24/2/93 + + This function converts LPC coefficients to LSP + coefficients. + +\*---------------------------------------------------------------------------*/ + + +int lpc_to_lsp (float *a,int lpcrdr,float *freq,int nb,float delta, char *stack) +/* float *a lpc coefficients */ +/* int lpcrdr order of LPC coefficients (10) */ +/* float *freq LSP frequencies in the x domain */ +/* int nb number of sub-intervals (4) */ +/* float delta grid spacing interval (0.02) */ + + +{ + + float psuml,psumr,psumm,temp_xr,xl,xr,xm=0; + float temp_psumr/*,temp_qsumr*/; + int i,j,m,flag,k; + float *Q; /* ptrs for memory allocation */ + float *P; + float *px; /* ptrs of respective P'(z) & Q'(z) */ + float *qx; + float *p; + float *q; + float *pt; /* ptr used for cheb_poly_eval() + whether P' or Q' */ + int roots=0; /* DR 8/2/94: number of roots found */ + flag = 1; /* program is searching for a root when, + 1 else has found one */ + m = lpcrdr/2; /* order of P'(z) & Q'(z) polynomials */ + + + /* Allocate memory space for polynomials */ + Q = PUSH(stack, (m+1), float); + P = PUSH(stack, (m+1), float); + + /* determine P'(z)'s and Q'(z)'s coefficients where + P'(z) = P(z)/(1 + z^(-1)) and Q'(z) = Q(z)/(1-z^(-1)) */ + + px = P; /* initialise ptrs */ + qx = Q; + p = px; + q = qx; + *px++ = 1.0; + *qx++ = 1.0; + for(i=1;i<=m;i++){ + *px++ = a[i]+a[lpcrdr+1-i]-*p++; + *qx++ = a[i]-a[lpcrdr+1-i]+*q++; + } + px = P; + qx = Q; + for(i=0;i= -1.0)){ + float dd; + /* Modified by JMV to provide smaller steps around x=+-1 */ + dd=(delta*(1-.9*xl*xl)); + if (fabs(psuml)<.2) + dd *= .5; + + xr = xl - dd; /* interval spacing */ + psumr = cheb_poly_eva(pt,xr,lpcrdr,stack);/* poly(xl-delta_x) */ + temp_psumr = psumr; + temp_xr = xr; + + /* if no sign change increment xr and re-evaluate poly(xr). Repeat til + sign change. + if a sign change has occurred the interval is bisected and then + checked again for a sign change which determines in which + interval the zero lies in. + If there is no sign change between poly(xm) and poly(xl) set interval + between xm and xr else set interval between xl and xr and repeat till + root is located within the specified limits */ + + if((psumr*psuml)<0.0){ + roots++; + + psumm=psuml; + for(k=0;k<=nb;k++){ + xm = (xl+xr)/2; /* bisect the interval */ + psumm=cheb_poly_eva(pt,xm,lpcrdr,stack); + if(psumm*psuml>0.){ + psuml=psumm; + xl=xm; + } + else{ + psumr=psumm; + xr=xm; + } + } + + /* once zero is found, reset initial interval to xr */ + freq[j] = (xm); + xl = xm; + flag = 0; /* reset flag for next search */ + } + else{ + psuml=temp_psumr; + xl=temp_xr; + } + } + } + return(roots); +} + + +/*---------------------------------------------------------------------------*\ + + FUNCTION....: lsp_to_lpc() + + AUTHOR......: David Rowe + DATE CREATED: 24/2/93 + + lsp_to_lpc: This function converts LSP coefficients to LPC + coefficients. + +\*---------------------------------------------------------------------------*/ + + +void lsp_to_lpc(float *freq,float *ak,int lpcrdr, char *stack) +/* float *freq array of LSP frequencies in the x domain */ +/* float *ak array of LPC coefficients */ +/* int lpcrdr order of LPC coefficients */ + + +{ + int i,j; + float xout1,xout2,xin1,xin2; + float *Wp; + float *pw,*n1,*n2,*n3,*n4=NULL; + int m = lpcrdr/2; + + Wp = PUSH(stack, 4*m+2, float); + pw = Wp; + + /* initialise contents of array */ + + for(i=0;i<=4*m+1;i++){ /* set contents of buffer to 0 */ + *pw++ = 0.0; + } + + /* Set pointers up */ + + pw = Wp; + xin1 = 1.0; + xin2 = 1.0; + + /* reconstruct P(z) and Q(z) by cascading second order + polynomials in form 1 - 2xz(-1) +z(-2), where x is the + LSP coefficient */ + + for(j=0;j<=lpcrdr;j++){ + int i2=0; + for(i=0;iM_PI-margin) + lsp[len-1]=M_PI-margin; + for (i=1;ilsp[i+1]-margin) + lsp[i]= .5* (lsp[i] + lsp[i+1]-margin); + } +} diff --git a/Code/BF2/External/speex-1.0.5/libspeex/lsp.h b/Code/BF2/External/speex-1.0.5/libspeex/lsp.h new file mode 100644 index 000000000..1f3b02f69 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/lsp.h @@ -0,0 +1,57 @@ +/*---------------------------------------------------------------------------*\ +Original Copyright + FILE........: AK2LSPD.H + TYPE........: Turbo C header file + COMPANY.....: Voicetronix + AUTHOR......: James Whitehall + DATE CREATED: 21/11/95 + +Modified by Jean-Marc Valin + + This file contains functions for converting Linear Prediction + Coefficients (LPC) to Line Spectral Pair (LSP) and back. Note that the + LSP coefficients are not in radians format but in the x domain of the + unit circle. + +\*---------------------------------------------------------------------------*/ +/* Speex License: + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef __AK2LSPD__ +#define __AK2LSPD__ + +int lpc_to_lsp (float *a, int lpcrdr, float *freq, int nb, float delta, char *stack); +void lsp_to_lpc(float *freq, float *ak, int lpcrdr, char *stack); + +/*Added by JMV*/ +void lsp_enforce_margin(float *lsp, int len, float margin); + + +#endif /* __AK2LSPD__ */ diff --git a/Code/BF2/External/speex-1.0.5/libspeex/lsp_tables_nb.c b/Code/BF2/External/speex-1.0.5/libspeex/lsp_tables_nb.c new file mode 100644 index 000000000..a68ce9944 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/lsp_tables_nb.c @@ -0,0 +1,360 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: lsp_tables_nb.c + Codebooks for LSPs in narrowband CELP mode + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. +*/ + +signed char cdbk_nb[640]={ +30,19,38,34,40,32,46,43,58,43, +5,-18,-25,-40,-33,-55,-52,20,34,28, +-20,-63,-97,-92,61,53,47,49,53,75, +-14,-53,-77,-79,0,-3,-5,19,22,26, +-9,-53,-55,66,90,72,85,68,74,52, +-4,-41,-58,-31,-18,-31,27,32,30,18, +24,3,8,5,-12,-3,26,28,74,63, +-2,-39,-67,-77,-106,-74,59,59,73,65, +44,40,71,72,82,83,98,88,89,60, +-6,-31,-47,-48,-13,-39,-9,7,2,79, +-1,-39,-60,-17,87,81,65,50,45,19, +-21,-67,-91,-87,-41,-50,7,18,39,74, +10,-31,-28,39,24,13,23,5,56,45, +29,10,-5,-13,-11,-35,-18,-8,-10,-8, +-25,-71,-77,-21,2,16,50,63,87,87, +5,-32,-40,-51,-68,0,12,6,54,34, +5,-12,32,52,68,64,69,59,65,45, +14,-16,-31,-40,-65,-67,41,49,47,37, +-11,-52,-75,-84,-4,57,48,42,42,33, +-11,-51,-68,-6,13,0,8,-8,26,32, +-23,-53,0,36,56,76,97,105,111,97, +-1,-28,-39,-40,-43,-54,-44,-40,-18,35, +16,-20,-19,-28,-42,29,47,38,74,45, +3,-29,-48,-62,-80,-104,-33,56,59,59, +10,17,46,72,84,101,117,123,123,106, +-7,-33,-49,-51,-70,-67,-27,-31,70,67, +-16,-62,-85,-20,82,71,86,80,85,74, +-19,-58,-75,-45,-29,-33,-18,-25,45,57, +-12,-42,-5,12,28,36,52,64,81,82, +13,-9,-27,-28,22,3,2,22,26,6, +-6,-44,-51,2,15,10,48,43,49,34, +-19,-62,-84,-89,-102,-24,8,17,61,68, +39,24,23,19,16,-5,12,15,27,15, +-8,-44,-49,-60,-18,-32,-28,52,54,62, +-8,-48,-77,-70,66,101,83,63,61,37, +-12,-50,-75,-64,33,17,13,25,15,77, +1,-42,-29,72,64,46,49,31,61,44, +-8,-47,-54,-46,-30,19,20,-1,-16,0, +16,-12,-18,-9,-26,-27,-10,-22,53,45, +-10,-47,-75,-82,-105,-109,8,25,49,77, +50,65,114,117,124,118,115,96,90,61, +-9,-45,-63,-60,-75,-57,8,11,20,29, +0,-35,-49,-43,40,47,35,40,55,38, +-24,-76,-103,-112,-27,3,23,34,52,75, +8,-29,-43,12,63,38,35,29,24,8, +25,11,1,-15,-18,-43,-7,37,40,21, +-20,-56,-19,-19,-4,-2,11,29,51,63, +-2,-44,-62,-75,-89,30,57,51,74,51, +50,46,68,64,65,52,63,55,65,43, +18,-9,-26,-35,-55,-69,3,6,8,17, +-15,-61,-86,-97,1,86,93,74,78,67, +-1,-38,-66,-48,48,39,29,25,17,-1, +13,13,29,39,50,51,69,82,97,98, +-2,-36,-46,-27,-16,-30,-13,-4,-7,-4, +25,-5,-11,-6,-25,-21,33,12,31,29, +-8,-38,-52,-63,-68,-89,-33,-1,10,74, +-2,-15,59,91,105,105,101,87,84,62, +-7,-33,-50,-35,-54,-47,25,17,82,81, +-13,-56,-83,21,58,31,42,25,72,65, +-24,-66,-91,-56,9,-2,21,10,69,75, +2,-24,11,22,25,28,38,34,48,33, +7,-29,-26,17,15,-1,14,0,-2,0, +-6,-41,-67,6,-2,-9,19,2,85,74, +-22,-67,-84,-71,-50,3,11,-9,2,62}; + +signed char cdbk_nb_low1[320]={ +-34,-52,-15,45,2, +23,21,52,24,-33, +-9,-1,9,-44,-41, +-13,-17,44,22,-17, +-6,-4,-1,22,38, +26,16,2,50,27, +-35,-34,-9,-41,6, +0,-16,-34,51,8, +-14,-31,-49,15,-33, +45,49,33,-11,-37, +-62,-54,45,11,-5, +-72,11,-1,-12,-11, +24,27,-11,-43,46, +43,33,-12,-9,-1, +1,-4,-23,-57,-71, +11,8,16,17,-8, +-20,-31,-41,53,48, +-16,3,65,-24,-8, +-23,-32,-37,-32,-49, +-10,-17,6,38,5, +-9,-17,-46,8,52, +3,6,45,40,39, +-7,-6,-34,-74,31, +8,1,-16,43,68, +-11,-19,-31,4,6, +0,-6,-17,-16,-38, +-16,-30,2,9,-39, +-16,-1,43,-10,48, +3,3,-16,-31,-3, +62,68,43,13,3, +-10,8,20,-56,12, +12,-2,-18,22,-15, +-40,-36,1,7,41, +0,1,46,-6,-62, +-4,-12,-2,-11,-83, +-13,-2,91,33,-10, +0,4,-11,-16,79, +32,37,14,9,51, +-21,-28,-56,-34,0, +21,9,-26,11,28, +-42,-54,-23,-2,-15, +31,30,8,-39,-66, +-39,-36,31,-28,-40, +-46,35,40,22,24, +33,48,23,-34,14, +40,32,17,27,-3, +25,26,-13,-61,-17, +11,4,31,60,-6, +-26,-41,-64,13,16, +-26,54,31,-11,-23, +-9,-11,-34,-71,-21, +-34,-35,55,50,29, +-22,-27,-50,-38,57, +33,42,57,48,26, +11,0,-49,-31,26, +-4,-14,5,78,37, +17,0,-49,-12,-23, +26,14,2,2,-43, +-17,-12,10,-8,-4, +8,18,12,-6,20, +-12,-6,-13,-25,34, +15,40,49,7,8, +13,20,20,-19,-22, +-2,-8,2,51,-51}; + +signed char cdbk_nb_low2[320]={ +-6,53,-21,-24,4, +26,17,-4,-37,25, +17,-36,-13,31,3, +-6,27,15,-10,31, +28,26,-10,-10,-40, +16,-7,15,13,41, +-9,0,-4,50,-6, +-7,14,38,22,0, +-48,2,1,-13,-19, +32,-3,-60,11,-17, +-1,-24,-34,-1,35, +-5,-27,28,44,13, +25,15,42,-11,15, +51,35,-36,20,8, +-4,-12,-29,19,-47, +49,-15,-4,16,-29, +-39,14,-30,4,25, +-9,-5,-51,-14,-3, +-40,-32,38,5,-9, +-8,-4,-1,-22,71, +-3,14,26,-18,-22, +24,-41,-25,-24,6, +23,19,-10,39,-26, +-27,65,45,2,-7, +-26,-8,22,-12,16, +15,16,-35,-5,33, +-21,-8,0,23,33, +34,6,21,36,6, +-7,-22,8,-37,-14, +31,38,11,-4,-3, +-39,-32,-8,32,-23, +-6,-12,16,20,-28, +-4,23,13,-52,-1, +22,6,-33,-40,-6, +4,-62,13,5,-26, +35,39,11,2,57, +-11,9,-20,-28,-33, +52,-5,-6,-2,22, +-14,-16,-48,35,1, +-58,20,13,33,-1, +-74,56,-18,-22,-31, +12,6,-14,4,-2, +-9,-47,10,-3,29, +-17,-5,61,14,47, +-12,2,72,-39,-17, +92,64,-53,-51,-15, +-30,-38,-41,-29,-28, +27,9,36,9,-35, +-42,81,-21,20,25, +-16,-5,-17,-35,21, +15,-28,48,2,-2, +9,-19,29,-40,30, +-18,-18,18,-16,-57, +15,-20,-12,-15,-37, +-15,33,-39,21,-22, +-13,35,11,13,-38, +-63,29,23,-27,32, +18,3,-26,42,33, +-64,-66,-17,16,56, +2,36,3,31,21, +-41,-39,8,-57,14, +37,-2,19,-36,-19, +-23,-29,-16,1,-3, +-8,-10,31,64,-65}; + +signed char cdbk_nb_high1[320]={ +-26,-8,29,21,4, +19,-39,33,-7,-36, +56,54,48,40,29, +-4,-24,-42,-66,-43, +-60,19,-2,37,41, +-10,-37,-60,-64,18, +-22,77,73,40,25, +4,19,-19,-66,-2, +11,5,21,14,26, +-25,-86,-4,18,1, +26,-37,10,37,-1, +24,-12,-59,-11,20, +-6,34,-16,-16,42, +19,-28,-51,53,32, +4,10,62,21,-12, +-34,27,4,-48,-48, +-50,-49,31,-7,-21, +-42,-25,-4,-43,-22, +59,2,27,12,-9, +-6,-16,-8,-32,-58, +-16,-29,-5,41,23, +-30,-33,-46,-13,-10, +-38,52,52,1,-17, +-9,10,26,-25,-6, +33,-20,53,55,25, +-32,-5,-42,23,21, +66,5,-28,20,9, +75,29,-7,-42,-39, +15,3,-23,21,6, +11,1,-29,14,63, +10,54,26,-24,-51, +-49,7,-23,-51,15, +-66,1,60,25,10, +0,-30,-4,-15,17, +19,59,40,4,-5, +33,6,-22,-58,-70, +-5,23,-6,60,44, +-29,-16,-47,-29,52, +-19,50,28,16,35, +31,36,0,-21,6, +21,27,22,42,7, +-66,-40,-8,7,19, +46,0,-4,60,36, +45,-7,-29,-6,-32, +-39,2,6,-9,33, +20,-51,-34,18,-6, +19,6,11,5,-19, +-29,-2,42,-11,-45, +-21,-55,57,37,2, +-14,-67,-16,-27,-38, +69,48,19,2,-17, +20,-20,-16,-34,-17, +-25,-61,10,73,45, +16,-40,-64,-17,-29, +-22,56,17,-39,8, +-11,8,-25,-18,-13, +-19,8,54,57,36, +-17,-26,-4,6,-21, +40,42,-4,20,31, +53,10,-34,-53,31, +-17,35,0,15,-6, +-20,-63,-73,22,25, +29,17,8,-29,-39, +-69,18,15,-15,-5}; + +signed char cdbk_nb_high2[320]={ +11,47,16,-9,-46, +-32,26,-64,34,-5, +38,-7,47,20,2, +-73,-99,-3,-45,20, +70,-52,15,-6,-7, +-82,31,21,47,51, +39,-3,9,0,-41, +-7,-15,-54,2,0, +27,-31,9,-45,-22, +-38,-24,-24,8,-33, +23,5,50,-36,-17, +-18,-51,-2,13,19, +43,12,-15,-12,61, +38,38,7,13,0, +6,-1,3,62,9, +27,22,-33,38,-35, +-9,30,-43,-9,-32, +-1,4,-4,1,-5, +-11,-8,38,31,11, +-10,-42,-21,-37,1, +43,15,-13,-35,-19, +-18,15,23,-26,59, +1,-21,53,8,-41, +-50,-14,-28,4,21, +25,-28,-40,5,-40, +-41,4,51,-33,-8, +-8,1,17,-60,12, +25,-41,17,34,43, +19,45,7,-37,24, +-15,56,-2,35,-10, +48,4,-47,-2,5, +-5,-54,5,-3,-33, +-10,30,-2,-44,-24, +-38,9,-9,42,4, +6,-56,44,-16,9, +-40,-26,18,-20,10, +28,-41,-21,-4,13, +-18,32,-30,-3,37, +15,22,28,50,-40, +3,-29,-64,7,51, +-19,-11,17,-27,-40, +-64,24,-12,-7,-27, +3,37,48,-1,2, +-9,-38,-34,46,1, +27,-6,19,-13,26, +10,34,20,25,40, +50,-6,-7,30,9, +-24,0,-23,71,-61, +22,58,-34,-4,2, +-49,-33,25,30,-8, +-6,-16,77,2,38, +-8,-35,-6,-30,56, +78,31,33,-20,13, +-39,20,22,4,21, +-8,4,-6,10,-83, +-41,9,-25,-43,15, +-7,-12,-34,-39,-37, +-33,19,30,16,-33, +42,-25,25,-68,44, +-15,-11,-4,23,50, +14,4,-39,-43,20, +-30,60,9,-20,7, +16,19,-33,37,29, +16,-35,7,38,-27}; diff --git a/Code/BF2/External/speex-1.0.5/libspeex/ltp.c b/Code/BF2/External/speex-1.0.5/libspeex/ltp.c new file mode 100644 index 000000000..a07e7a167 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/ltp.c @@ -0,0 +1,552 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: ltp.c + Long-Term Prediction functions + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include +#include "misc.h" +#include "ltp.h" +#include "stack_alloc.h" +#include "filters.h" +#include + +#ifdef _USE_SSE +#include "ltp_sse.h" +#else +static float inner_prod(float *x, float *y, int len) +{ + int i; + float sum1=0,sum2=0,sum3=0,sum4=0; + for (i=0;ibest_score[N-1]) + { + float g1, g; + g1 = corr[i-start]/(energy[i-start]+10); + g = sqrt(g1*corr[i-start]/(e0+10)); + if (g>g1) + g=g1; + if (g<0) + g=0; + for (j=0;j best_score[j]) + { + for (k=N-1;k>j;k--) + { + best_score[k]=best_score[k-1]; + pitch[k]=pitch[k-1]; + gain[k] = gain[k-1]; + } + best_score[j]=score[i-start]; + pitch[j]=i; + gain[j]=g; + break; + } + } + } + } + +} + + + + +/** Finds the best quantized 3-tap pitch predictor by analysis by synthesis */ +float pitch_gain_search_3tap( +float target[], /* Target vector */ +float ak[], /* LPCs for this subframe */ +float awk1[], /* Weighted LPCs #1 for this subframe */ +float awk2[], /* Weighted LPCs #2 for this subframe */ +float exc[], /* Excitation */ +void *par, +int pitch, /* Pitch value */ +int p, /* Number of LPC coeffs */ +int nsf, /* Number of samples in subframe */ +SpeexBits *bits, +char *stack, +float *exc2, +float *r, +int *cdbk_index +) +{ + int i,j; + float *tmp, *tmp2; + float *x[3]; + float *e[3]; + float corr[3]; + float A[3][3]; + float gain[3]; + int gain_cdbk_size; + signed char *gain_cdbk; + float err1,err2; + + ltp_params *params; + params = (ltp_params*) par; + gain_cdbk=params->gain_cdbk; + gain_cdbk_size=1<gain_bits; + tmp = PUSH(stack, 3*nsf, float); + tmp2 = PUSH(stack, 3*nsf, float); + + x[0]=tmp; + x[1]=tmp+nsf; + x[2]=tmp+2*nsf; + + e[0]=tmp2; + e[1]=tmp2+nsf; + e[2]=tmp2+2*nsf; + + for (i=2;i>=0;i--) + { + int pp=pitch+1-i; + for (j=0;j0) + tot+=ptr[0]; + if (ptr[2]>0) + tot+=ptr[2]; + if (tot>1) + continue; + } + + if (sum>best_sum || i==0) + { + best_sum=sum; + best_cdbk=i; + } + } + gain[0] = 0.015625*gain_cdbk[best_cdbk*3] + .5; + gain[1] = 0.015625*gain_cdbk[best_cdbk*3+1]+ .5; + gain[2] = 0.015625*gain_cdbk[best_cdbk*3+2]+ .5; + + *cdbk_index=best_cdbk; + } + + for (i=0;i10) + N=10; + + nbest=PUSH(stack, N, int); + gains = PUSH(stack, N, float); + params = (ltp_params*) par; + + if (N==0 || endpitch_bits); + speex_bits_pack(bits, 0, params->gain_bits); + for (i=0;iend-start+1) + N=end-start+1; + open_loop_nbest_pitch(sw, start, end, nsf, nbest, gains, N, stack); + for (i=0;ipitch_bits); + speex_bits_pack(bits, best_gain_index, params->gain_bits); + /*printf ("encode pitch: %d %d\n", best_pitch, best_gain_index);*/ + for (i=0;igain_cdbk; + + pitch = speex_bits_unpack_unsigned(bits, params->pitch_bits); + pitch += start; + gain_index = speex_bits_unpack_unsigned(bits, params->gain_bits); + /*printf ("decode pitch: %d %d\n", pitch, gain_index);*/ + gain[0] = 0.015625*gain_cdbk[gain_index*3]+.5; + gain[1] = 0.015625*gain_cdbk[gain_index*3+1]+.5; + gain[2] = 0.015625*gain_cdbk[gain_index*3+2]+.5; + + if (count_lost && pitch > subframe_offset) + { + float gain_sum; + + if (1) { + float tmp = count_lost < 4 ? last_pitch_gain : 0.4 * last_pitch_gain; + if (tmp>.95) + tmp=.95; + gain_sum = fabs(gain[1]); + if (gain[0]>0) + gain_sum += gain[0]; + else + gain_sum -= .5*gain[0]; + if (gain[2]>0) + gain_sum += gain[2]; + else + gain_sum -= .5*gain[2]; + if (gain_sum > tmp) { + float fact = tmp/gain_sum; + for (i=0;i<3;i++) + gain[i]*=fact; + + } + + } + + if (0) { + gain_sum = fabs(gain[0])+fabs(gain[1])+fabs(gain[2]); + if (gain_sum>.95) { + float fact = .95/gain_sum; + for (i=0;i<3;i++) + gain[i]*=fact; + } + } + } + + *pitch_val = pitch; + /**gain_val = gain[0]+gain[1]+gain[2];*/ + gain_val[0]=gain[0]; + gain_val[1]=gain[1]; + gain_val[2]=gain[2]; + + { + float *e[3]; + float *tmp2; + tmp2=PUSH(stack, 3*nsf, float); + e[0]=tmp2; + e[1]=tmp2+nsf; + e[2]=tmp2+2*nsf; + + for (i=0;i<3;i++) + { + int j; + int pp=pitch+1-i; +#if 0 + for (j=0;jpp) + tmp1=pp; + for (j=0;jpp+pitch) + tmp3=pp+pitch; + for (j=tmp1;j.99) + pitch_coef=.99; + for (i=0;i.99) + pitch_coef=.99; + for (i=0;i + + +typedef struct ltp_params { + signed char *gain_cdbk; + int gain_bits; + int pitch_bits; +} ltp_params; + + +void open_loop_nbest_pitch(float *sw, int start, int end, int len, int *pitch, float *gain, int N, char *stack); + + +/** Finds the best quantized 3-tap pitch predictor by analysis by synthesis */ +int pitch_search_3tap( +float target[], /* Target vector */ +float *sw, +float ak[], /* LPCs for this subframe */ +float awk1[], /* Weighted LPCs #1 for this subframe */ +float awk2[], /* Weighted LPCs #2 for this subframe */ +float exc[], /* Overlapping codebook */ +void *par, +int start, /* Smallest pitch value allowed */ +int end, /* Largest pitch value allowed */ +float pitch_coef, /* Voicing (pitch) coefficient */ +int p, /* Number of LPC coeffs */ +int nsf, /* Number of samples in subframe */ +SpeexBits *bits, +char *stack, +float *exc2, +float *r, +int complexity +); + +/*Unquantize adaptive codebook and update pitch contribution*/ +void pitch_unquant_3tap( +float exc[], /* Excitation */ +int start, /* Smallest pitch value allowed */ +int end, /* Largest pitch value allowed */ +float pitch_coef, /* Voicing (pitch) coefficient */ +void *par, +int nsf, /* Number of samples in subframe */ +int *pitch_val, +float *gain_val, +SpeexBits *bits, +char *stack, +int lost, +int subframe_offset, +float last_pitch_gain +); + +float pitch_gain_search_3tap( +float target[], /* Target vector */ +float ak[], /* LPCs for this subframe */ +float awk1[], /* Weighted LPCs #1 for this subframe */ +float awk2[], /* Weighted LPCs #2 for this subframe */ +float exc[], /* Excitation */ +void *par, +int pitch, /* Pitch value */ +int p, /* Number of LPC coeffs */ +int nsf, /* Number of samples in subframe */ +SpeexBits *bits, +char *stack, +float *exc2, +float *r, +int *cdbk_index +); + + +/** Forced pitch delay and gain */ +int forced_pitch_quant( +float target[], /* Target vector */ +float *sw, +float ak[], /* LPCs for this subframe */ +float awk1[], /* Weighted LPCs #1 for this subframe */ +float awk2[], /* Weighted LPCs #2 for this subframe */ +float exc[], /* Excitation */ +void *par, +int start, /* Smallest pitch value allowed */ +int end, /* Largest pitch value allowed */ +float pitch_coef, /* Voicing (pitch) coefficient */ +int p, /* Number of LPC coeffs */ +int nsf, /* Number of samples in subframe */ +SpeexBits *bits, +char *stack, +float *exc2, +float *r, +int complexity +); + +/** Unquantize forced pitch delay and gain */ +void forced_pitch_unquant( +float exc[], /* Excitation */ +int start, /* Smallest pitch value allowed */ +int end, /* Largest pitch value allowed */ +float pitch_coef, /* Voicing (pitch) coefficient */ +void *par, +int nsf, /* Number of samples in subframe */ +int *pitch_val, +float *gain_val, +SpeexBits *bits, +char *stack, +int lost, +int subframe_offset, +float last_pitch_gain +); diff --git a/Code/BF2/External/speex-1.0.5/libspeex/ltp_sse.h b/Code/BF2/External/speex-1.0.5/libspeex/ltp_sse.h new file mode 100644 index 000000000..c8d484ac6 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/ltp_sse.h @@ -0,0 +1,95 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: ltp.c + Lont-Term Prediction functions + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + + +static float inner_prod(float *a, float *b, int len) +{ + float sum; + __asm__ __volatile__ ( + "\tpush %%eax\n" + "\tpush %%edi\n" + "\tpush %%ecx\n" + "\txorps %%xmm3, %%xmm3\n" + "\txorps %%xmm4, %%xmm4\n" + + "\tsub $20, %%ecx\n" + +".mul20_loop%=:\n" + + "\tmovups (%%eax), %%xmm0\n" + "\tmovups (%%edi), %%xmm1\n" + "\tmulps %%xmm0, %%xmm1\n" + + "\tmovups 16(%%eax), %%xmm5\n" + "\tmovups 16(%%edi), %%xmm6\n" + "\tmulps %%xmm5, %%xmm6\n" + "\taddps %%xmm1, %%xmm3\n" + + "\tmovups 32(%%eax), %%xmm0\n" + "\tmovups 32(%%edi), %%xmm1\n" + "\tmulps %%xmm0, %%xmm1\n" + "\taddps %%xmm6, %%xmm4\n" + + "\tmovups 48(%%eax), %%xmm5\n" + "\tmovups 48(%%edi), %%xmm6\n" + "\tmulps %%xmm5, %%xmm6\n" + "\taddps %%xmm1, %%xmm3\n" + + "\tmovups 64(%%eax), %%xmm0\n" + "\tmovups 64(%%edi), %%xmm1\n" + "\tmulps %%xmm0, %%xmm1\n" + "\taddps %%xmm6, %%xmm4\n" + "\taddps %%xmm1, %%xmm3\n" + + + "\tadd $80, %%eax\n" + "\tadd $80, %%edi\n" + + "\tsub $20, %%ecx\n" + + "\tjae .mul20_loop%=\n" + + "\taddps %%xmm4, %%xmm3\n" + + "\tmovhlps %%xmm3, %%xmm4\n" + "\taddps %%xmm4, %%xmm3\n" + "\tmovaps %%xmm3, %%xmm4\n" + "\tshufps $0x55, %%xmm4, %%xmm4\n" + "\taddss %%xmm4, %%xmm3\n" + "\tmovss %%xmm3, (%%edx)\n" + + "\tpop %%ecx\n" + "\tpop %%edi\n" + "\tpop %%eax\n" + : : "a" (a), "D" (b), "c" (len), "d" (&sum) : "memory"); + return sum; +} diff --git a/Code/BF2/External/speex-1.0.5/libspeex/math_approx.c b/Code/BF2/External/speex-1.0.5/libspeex/math_approx.c new file mode 100644 index 000000000..748d6191f --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/math_approx.c @@ -0,0 +1,105 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: math_approx.c + Various math approximation functions for Speex + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include +#include "math_approx.h" + +#ifdef SLOW_TRIG + +float cos_sin[102] = { + 1.00000000, 0.00000000, + 0.99804751, 0.06245932, + 0.99219767, 0.12467473, + 0.98247331, 0.18640330, + 0.96891242, 0.24740396, + 0.95156795, 0.30743851, + 0.93050762, 0.36627253, + 0.90581368, 0.42367626, + 0.87758256, 0.47942554, + 0.84592450, 0.53330267, + 0.81096312, 0.58509727, + 0.77283495, 0.63460708, + 0.73168887, 0.68163876, + 0.68768556, 0.72600866, + 0.64099686, 0.76754350, + 0.59180508, 0.80608111, + 0.54030231, 0.84147098, + 0.48668967, 0.87357494, + 0.43117652, 0.90226759, + 0.37397963, 0.92743692, + 0.31532236, 0.94898462, + 0.25543377, 0.96682656, + 0.19454771, 0.98089306, + 0.13290194, 0.99112919, + 0.07073720, 0.99749499, + 0.00829623, 0.99996559, + -0.05417714, 0.99853134, + -0.11643894, 0.99319785, + -0.17824606, 0.98398595, + -0.23935712, 0.97093160, + -0.29953351, 0.95408578, + -0.35854022, 0.93351428, + -0.41614684, 0.90929743, + -0.47212841, 0.88152979, + -0.52626633, 0.85031979, + -0.57834920, 0.81578931, + -0.62817362, 0.77807320, + -0.67554504, 0.73731872, + -0.72027847, 0.69368503, + -0.76219923, 0.64734252, + -0.80114362, 0.59847214, + -0.83695955, 0.54726475, + -0.86950718, 0.49392030, + -0.89865940, 0.43864710, + -0.92430238, 0.38166099, + -0.94633597, 0.32318451, + -0.96467415, 0.26344599, + -0.97924529, 0.20267873, + -0.98999250, 0.14112001, + -0.99687381, 0.07901022, + -0.99986235, 0.01659189 +}; + +float speex_cos(float x) +{ + int ind; + float delta; + ind = (int)floor(x*16+.5); + delta = x-0.062500*ind; + ind <<= 1; + return cos_sin[ind] - delta*(cos_sin[ind+1] + + .5*delta*(cos_sin[ind] - + .3333333*delta*cos_sin[ind+1])); +} + +#endif + diff --git a/Code/BF2/External/speex-1.0.5/libspeex/math_approx.h b/Code/BF2/External/speex-1.0.5/libspeex/math_approx.h new file mode 100644 index 000000000..c917ffd71 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/math_approx.h @@ -0,0 +1,39 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: math_approx.c + Various math approximation functions for Speex + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef MATH_APPROX_H +#define MATH_APPROX_H + +float speex_cos(float x); + + +#endif diff --git a/Code/BF2/External/speex-1.0.5/libspeex/misc.c b/Code/BF2/External/speex-1.0.5/libspeex/misc.c new file mode 100644 index 000000000..f84e0f619 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/misc.c @@ -0,0 +1,145 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: mics.c + Various utility routines for Speex + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include "misc.h" +#include +#include +#include + +#ifndef RELEASE +void print_vec(float *vec, int len, char *name) +{ + int i; + printf ("%s ", name); + for (i=0;i>24; + ret += (i>>8)&0x0000ff00; + ret += (i<<8)&0x00ff0000; + ret += (i<<24); +#endif + return ret; +} + +unsigned int le_int(unsigned int i) +{ + unsigned int ret=i; +#ifdef WORDS_BIGENDIAN + ret = i>>24; + ret += (i>>8)&0x0000ff00; + ret += (i<<8)&0x00ff0000; + ret += (i<<24); +#endif + return ret; +} + +unsigned short be_short(unsigned short s) +{ + unsigned short ret=s; +#ifndef WORDS_BIGENDIAN + ret = s>>8; + ret += s<<8; +#endif + return ret; +} + +unsigned short le_short(unsigned short s) +{ + unsigned short ret=s; +#ifdef WORDS_BIGENDIAN + ret = s>>8; + ret += s<<8; +#endif + return ret; +} + +void *speex_alloc (int size) +{ + return calloc(size,1); +} + +void *speex_realloc (void *ptr, int size) +{ + return realloc(ptr, size); +} + +void speex_free (void *ptr) +{ + free(ptr); +} + +void *speex_move (void *dest, void *src, int n) +{ + return memmove(dest,src,n); +} + +void speex_error(char *str) +{ + fprintf (stderr, "Fatal error: %s\n", str); + exit(1); +} + +void speex_warning(char *str) +{ + fprintf (stderr, "warning: %s\n", str); +} + +void speex_warning_int(char *str, int val) +{ + fprintf (stderr, "warning: %s %d\n", str, val); +} + +void speex_rand_vec(float std, float *data, int len) +{ + int i; + for (i=0;i +#include "modes.h" +#include "ltp.h" +#include "quant_lsp.h" +#include "cb_search.h" +#include "sb_celp.h" +#include "nb_celp.h" +#include "vbr.h" +#include "misc.h" + +#ifndef NULL +#define NULL 0 +#endif + +#define MAX_IN_SAMPLES 640 + +SpeexMode *speex_mode_list[SPEEX_NB_MODES] = {&speex_nb_mode, &speex_wb_mode, &speex_uwb_mode}; + +/* Extern declarations for all codebooks we use here */ +extern signed char gain_cdbk_nb[]; +extern signed char gain_cdbk_lbr[]; +extern signed char hexc_table[]; +extern signed char exc_5_256_table[]; +extern signed char exc_5_64_table[]; +extern signed char exc_8_128_table[]; +extern signed char exc_10_32_table[]; +extern signed char exc_10_16_table[]; +extern signed char exc_20_32_table[]; +extern signed char hexc_10_32_table[]; + +static int nb_mode_query(void *mode, int request, void *ptr); +static int wb_mode_query(void *mode, int request, void *ptr); + +/* Parameters for Long-Term Prediction (LTP)*/ +static ltp_params ltp_params_nb = { + gain_cdbk_nb, + 7, + 7 +}; + +/* Parameters for Long-Term Prediction (LTP)*/ +static ltp_params ltp_params_vlbr = { + gain_cdbk_lbr, + 5, + 0 +}; + +/* Parameters for Long-Term Prediction (LTP)*/ +static ltp_params ltp_params_lbr = { + gain_cdbk_lbr, + 5, + 7 +}; + +/* Parameters for Long-Term Prediction (LTP)*/ +static ltp_params ltp_params_med = { + gain_cdbk_lbr, + 5, + 7 +}; + +/* Split-VQ innovation parameters for very low bit-rate narrowband */ +static split_cb_params split_cb_nb_vlbr = { + 10, /*subvect_size*/ + 4, /*nb_subvect*/ + exc_10_16_table, /*shape_cb*/ + 4, /*shape_bits*/ + 0, +}; + +/* Split-VQ innovation parameters for very low bit-rate narrowband */ +static split_cb_params split_cb_nb_ulbr = { + 20, /*subvect_size*/ + 2, /*nb_subvect*/ + exc_20_32_table, /*shape_cb*/ + 5, /*shape_bits*/ + 0, +}; + +/* Split-VQ innovation parameters for low bit-rate narrowband */ +static split_cb_params split_cb_nb_lbr = { + 10, /*subvect_size*/ + 4, /*nb_subvect*/ + exc_10_32_table, /*shape_cb*/ + 5, /*shape_bits*/ + 0, +}; + + +/* Split-VQ innovation parameters narrowband */ +static split_cb_params split_cb_nb = { + 5, /*subvect_size*/ + 8, /*nb_subvect*/ + exc_5_64_table, /*shape_cb*/ + 6, /*shape_bits*/ + 0, +}; + +/* Split-VQ innovation parameters narrowband */ +static split_cb_params split_cb_nb_med = { + 8, /*subvect_size*/ + 5, /*nb_subvect*/ + exc_8_128_table, /*shape_cb*/ + 7, /*shape_bits*/ + 0, +}; + +/* Split-VQ innovation for low-band wideband */ +static split_cb_params split_cb_sb = { + 5, /*subvect_size*/ + 8, /*nb_subvect*/ + exc_5_256_table, /*shape_cb*/ + 8, /*shape_bits*/ + 0, +}; + +/* Split-VQ innovation for high-band wideband */ +static split_cb_params split_cb_high = { + 8, /*subvect_size*/ + 5, /*nb_subvect*/ + hexc_table, /*shape_cb*/ + 7, /*shape_bits*/ + 1, +}; + + +/* Split-VQ innovation for high-band wideband */ +static split_cb_params split_cb_high_lbr = { + 10, /*subvect_size*/ + 4, /*nb_subvect*/ + hexc_10_32_table, /*shape_cb*/ + 5, /*shape_bits*/ + 0, +}; + +/* 2150 bps "vocoder-like" mode for comfort noise */ +static SpeexSubmode nb_submode1 = { + 0, + 1, + 0, + 0, + /* LSP quantization */ + lsp_quant_lbr, + lsp_unquant_lbr, + /* No pitch quantization */ + forced_pitch_quant, + forced_pitch_unquant, + NULL, + /* No innovation quantization (noise only) */ + noise_codebook_quant, + noise_codebook_unquant, + NULL, + .7, .7, -1, + 43 +}; + +/* 3.95 kbps very low bit-rate mode */ +static SpeexSubmode nb_submode8 = { + 0, + 1, + 0, + 0, + /*LSP quantization*/ + lsp_quant_lbr, + lsp_unquant_lbr, + /*No pitch quantization*/ + forced_pitch_quant, + forced_pitch_unquant, + NULL, + /*Innovation quantization*/ + split_cb_search_shape_sign, + split_cb_shape_sign_unquant, + &split_cb_nb_ulbr, + + 0.7, 0.5, .65, + 79 +}; + +/* 5.95 kbps very low bit-rate mode */ +static SpeexSubmode nb_submode2 = { + 0, + 0, + 0, + 0, + /*LSP quantization*/ + lsp_quant_lbr, + lsp_unquant_lbr, + /*No pitch quantization*/ + pitch_search_3tap, + pitch_unquant_3tap, + <p_params_vlbr, + /*Innovation quantization*/ + split_cb_search_shape_sign, + split_cb_shape_sign_unquant, + &split_cb_nb_vlbr, + + 0.7, 0.5, .55, + 119 +}; + +/* 8 kbps low bit-rate mode */ +static SpeexSubmode nb_submode3 = { + -1, + 0, + 1, + 0, + /*LSP quantization*/ + lsp_quant_lbr, + lsp_unquant_lbr, + /*Pitch quantization*/ + pitch_search_3tap, + pitch_unquant_3tap, + <p_params_lbr, + /*Innovation quantization*/ + split_cb_search_shape_sign, + split_cb_shape_sign_unquant, + &split_cb_nb_lbr, + + 0.7, 0.55, .45, + 160 +}; + +/* 11 kbps medium bit-rate mode */ +static SpeexSubmode nb_submode4 = { + -1, + 0, + 1, + 0, + /*LSP quantization*/ + lsp_quant_lbr, + lsp_unquant_lbr, + /*Pitch quantization*/ + pitch_search_3tap, + pitch_unquant_3tap, + <p_params_med, + /*Innovation quantization*/ + split_cb_search_shape_sign, + split_cb_shape_sign_unquant, + &split_cb_nb_med, + + 0.7, 0.63, .35, + 220 +}; + +/* 15 kbps high bit-rate mode */ +static SpeexSubmode nb_submode5 = { + -1, + 0, + 3, + 0, + /*LSP quantization*/ + lsp_quant_nb, + lsp_unquant_nb, + /*Pitch quantization*/ + pitch_search_3tap, + pitch_unquant_3tap, + <p_params_nb, + /*Innovation quantization*/ + split_cb_search_shape_sign, + split_cb_shape_sign_unquant, + &split_cb_nb, + + 0.7, 0.65, .25, + 300 +}; + +/* 18.2 high bit-rate mode */ +static SpeexSubmode nb_submode6 = { + -1, + 0, + 3, + 0, + /*LSP quantization*/ + lsp_quant_nb, + lsp_unquant_nb, + /*Pitch quantization*/ + pitch_search_3tap, + pitch_unquant_3tap, + <p_params_nb, + /*Innovation quantization*/ + split_cb_search_shape_sign, + split_cb_shape_sign_unquant, + &split_cb_sb, + + 0.68, 0.65, .1, + 364 +}; + +/* 24.6 kbps high bit-rate mode */ +static SpeexSubmode nb_submode7 = { + -1, + 0, + 3, + 1, + /*LSP quantization*/ + lsp_quant_nb, + lsp_unquant_nb, + /*Pitch quantization*/ + pitch_search_3tap, + pitch_unquant_3tap, + <p_params_nb, + /*Innovation quantization*/ + split_cb_search_shape_sign, + split_cb_shape_sign_unquant, + &split_cb_nb, + + 0.65, 0.65, -1, + 492 +}; + + +/* Default mode for narrowband */ +static SpeexNBMode nb_mode = { + 160, /*frameSize*/ + 40, /*subframeSize*/ + 10, /*lpcSize*/ + 640, /*bufSize*/ + 17, /*pitchStart*/ + 144, /*pitchEnd*/ + 0.9, /*gamma1*/ + 0.6, /*gamma2*/ + .01, /*lag_factor*/ + 1.0001, /*lpc_floor*/ + 0.0, /*preemph*/ + {NULL, &nb_submode1, &nb_submode2, &nb_submode3, &nb_submode4, &nb_submode5, &nb_submode6, &nb_submode7, + &nb_submode8, NULL, NULL, NULL, NULL, NULL, NULL, NULL}, + 5, + {1, 8, 2, 3, 3, 4, 4, 5, 5, 6, 7} +}; + + +/* Default mode for narrowband */ +SpeexMode speex_nb_mode = { + &nb_mode, + nb_mode_query, + "narrowband", + 0, + 4, + &nb_encoder_init, + &nb_encoder_destroy, + &nb_encode, + &nb_decoder_init, + &nb_decoder_destroy, + &nb_decode, + &nb_encoder_ctl, + &nb_decoder_ctl, +}; + + +/* Wideband part */ + +static SpeexSubmode wb_submode1 = { + 0, + 0, + 1, + 0, + /*LSP quantization*/ + lsp_quant_high, + lsp_unquant_high, + /*Pitch quantization*/ + NULL, + NULL, + NULL, + /*No innovation quantization*/ + NULL, + NULL, + NULL, + + .75, .75, -1, + 36 +}; + + +static SpeexSubmode wb_submode2 = { + 0, + 0, + 1, + 0, + /*LSP quantization*/ + lsp_quant_high, + lsp_unquant_high, + /*Pitch quantization*/ + NULL, + NULL, + NULL, + /*Innovation quantization*/ + split_cb_search_shape_sign, + split_cb_shape_sign_unquant, + &split_cb_high_lbr, + + .85, .6, -1, + 112 +}; + + +static SpeexSubmode wb_submode3 = { + 0, + 0, + 1, + 0, + /*LSP quantization*/ + lsp_quant_high, + lsp_unquant_high, + /*Pitch quantization*/ + NULL, + NULL, + NULL, + /*Innovation quantization*/ + split_cb_search_shape_sign, + split_cb_shape_sign_unquant, + &split_cb_high, + + .75, .7, -1, + 192 +}; + +static SpeexSubmode wb_submode4 = { + 0, + 0, + 1, + 1, + /*LSP quantization*/ + lsp_quant_high, + lsp_unquant_high, + /*Pitch quantization*/ + NULL, + NULL, + NULL, + /*Innovation quantization*/ + split_cb_search_shape_sign, + split_cb_shape_sign_unquant, + &split_cb_high, + + .75, .75, -1, + 352 +}; + + +/* Split-band wideband CELP mode*/ +static SpeexSBMode sb_wb_mode = { + &speex_nb_mode, + 160, /*frameSize*/ + 40, /*subframeSize*/ + 8, /*lpcSize*/ + 640, /*bufSize*/ + .9, /*gamma1*/ + 0.6, /*gamma2*/ + .002, /*lag_factor*/ + 1.0001, /*lpc_floor*/ + 0.0, /*preemph*/ + 0.9, + {NULL, &wb_submode1, &wb_submode2, &wb_submode3, &wb_submode4, NULL, NULL, NULL}, + 3, + {1, 8, 2, 3, 4, 5, 5, 6, 6, 7, 7}, + {1, 1, 1, 1, 1, 1, 2, 2, 3, 3, 4}, + vbr_hb_thresh, + 5 +}; + + +SpeexMode speex_wb_mode = { + &sb_wb_mode, + wb_mode_query, + "wideband (sub-band CELP)", + 1, + 4, + &sb_encoder_init, + &sb_encoder_destroy, + &sb_encode, + &sb_decoder_init, + &sb_decoder_destroy, + &sb_decode, + &sb_encoder_ctl, + &sb_decoder_ctl, +}; + + + +/* "Ultra-wideband" mode stuff */ + + + +/* Split-band "ultra-wideband" (32 kbps) CELP mode*/ +static SpeexSBMode sb_uwb_mode = { + &speex_wb_mode, + 320, /*frameSize*/ + 80, /*subframeSize*/ + 8, /*lpcSize*/ + 1280, /*bufSize*/ + .9, /*gamma1*/ + 0.6, /*gamma2*/ + .002, /*lag_factor*/ + 1.0001, /*lpc_floor*/ + 0.0, /*preemph*/ + 0.7, + {NULL, &wb_submode1, NULL, NULL, NULL, NULL, NULL, NULL}, + 1, + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, + {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, + vbr_uhb_thresh, + 2 +}; + + +SpeexMode speex_uwb_mode = { + &sb_uwb_mode, + wb_mode_query, + "ultra-wideband (sub-band CELP)", + 2, + 4, + &sb_encoder_init, + &sb_encoder_destroy, + &sb_encode, + &sb_decoder_init, + &sb_decoder_destroy, + &sb_decode, + &sb_encoder_ctl, + &sb_decoder_ctl, +}; + + + + +void *speex_encoder_init(SpeexMode *mode) +{ + return mode->enc_init(mode); +} + +void *speex_decoder_init(SpeexMode *mode) +{ + return mode->dec_init(mode); +} + +void speex_encoder_destroy(void *state) +{ + (*((SpeexMode**)state))->enc_destroy(state); +} + +int speex_encode(void *state, float *in, SpeexBits *bits) +{ + return (*((SpeexMode**)state))->enc(state, in, bits); +} + +int speex_encode_int(void *state, short *in, SpeexBits *bits) +{ + int i; + int N; + /* FIXME: Do some dynamic allocation here */ + float float_in[MAX_IN_SAMPLES]; + speex_encoder_ctl(state, SPEEX_GET_FRAME_SIZE, &N); + for (i=0;ienc(state, float_in, bits); +} + +void speex_decoder_destroy(void *state) +{ + (*((SpeexMode**)state))->dec_destroy(state); +} + +int speex_decode(void *state, SpeexBits *bits, float *out) +{ + return (*((SpeexMode**)state))->dec(state, bits, out); +} + +int speex_decode_int(void *state, SpeexBits *bits, short *out) +{ + int i; + int N; + /* FIXME: Do some dynamic allocation here */ + float float_out[MAX_IN_SAMPLES]; + int ret; + speex_decoder_ctl(state, SPEEX_GET_FRAME_SIZE, &N); + ret = (*((SpeexMode**)state))->dec(state, bits, float_out); + for (i=0;i32767.f) + out[i] = 32767; + else if (float_out[i]<-32768.f) + out[i] = -32768; + else + out[i] = (short)floor(.5+float_out[i]); + } + return ret; +} + +int speex_encoder_ctl(void *state, int request, void *ptr) +{ + return (*((SpeexMode**)state))->enc_ctl(state, request, ptr); +} + +int speex_decoder_ctl(void *state, int request, void *ptr) +{ + return (*((SpeexMode**)state))->dec_ctl(state, request, ptr); +} + + + +static int nb_mode_query(void *mode, int request, void *ptr) +{ + SpeexNBMode *m = (SpeexNBMode*)mode; + + switch (request) + { + case SPEEX_MODE_FRAME_SIZE: + *((int*)ptr)=m->frameSize; + break; + case SPEEX_SUBMODE_BITS_PER_FRAME: + if (*((int*)ptr)==0) + *((int*)ptr) = NB_SUBMODE_BITS+1; + else if (m->submodes[*((int*)ptr)]==NULL) + *((int*)ptr) = -1; + else + *((int*)ptr) = m->submodes[*((int*)ptr)]->bits_per_frame; + break; + default: + speex_warning_int("Unknown nb_mode_query request: ", request); + return -1; + } + return 0; +} + +static int wb_mode_query(void *mode, int request, void *ptr) +{ + SpeexSBMode *m = (SpeexSBMode*)mode; + + switch (request) + { + case SPEEX_MODE_FRAME_SIZE: + *((int*)ptr)=2*m->frameSize; + break; + case SPEEX_SUBMODE_BITS_PER_FRAME: + if (*((int*)ptr)==0) + *((int*)ptr) = SB_SUBMODE_BITS+1; + else if (m->submodes[*((int*)ptr)]==NULL) + *((int*)ptr) = -1; + else + *((int*)ptr) = m->submodes[*((int*)ptr)]->bits_per_frame; + break; + default: + speex_warning_int("Unknown wb_mode_query request: ", request); + return -1; + } + return 0; +} + + +int speex_mode_query(SpeexMode *mode, int request, void *ptr) +{ + return mode->query(mode->mode, request, ptr); +} + +int speex_lib_ctl(int request, void *ptr) +{ + switch (request) + { + case SPEEX_LIB_GET_MAJOR_VERSION: + *((int*)ptr) = SPEEX_MAJOR_VERSION; + break; + case SPEEX_LIB_GET_MINOR_VERSION: + *((int*)ptr) = SPEEX_MINOR_VERSION; + break; + case SPEEX_LIB_GET_MICRO_VERSION: + *((int*)ptr) = SPEEX_MICRO_VERSION; + break; + case SPEEX_LIB_GET_EXTRA_VERSION: + *((char**)ptr) = SPEEX_EXTRA_VERSION; + break; + case SPEEX_LIB_GET_VERSION_STRING: + *((char**)ptr) = SPEEX_VERSION; + break; + /*case SPEEX_LIB_SET_ALLOC_FUNC: + break; + case SPEEX_LIB_GET_ALLOC_FUNC: + break; + case SPEEX_LIB_SET_FREE_FUNC: + break; + case SPEEX_LIB_GET_FREE_FUNC: + break;*/ + default: + speex_warning_int("Unknown wb_mode_query request: ", request); + return -1; + break; + } + return 0; +} + +SpeexMode *speex_lib_get_mode (int mode) +{ + if (mode < 0 || mode > SPEEX_NB_MODES) return NULL; + + return speex_mode_list[mode]; +} diff --git a/Code/BF2/External/speex-1.0.5/libspeex/modes.h b/Code/BF2/External/speex-1.0.5/libspeex/modes.h new file mode 100644 index 000000000..dac101e85 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/modes.h @@ -0,0 +1,146 @@ +/* Copyright (C) 2002 Jean-Marc Valin */ +/** + @file modes.h + @brief Describes the different modes of the codec +*/ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +*/ + +#ifndef MODES_H +#define MODES_H + +#include +#include + + +#define NB_SUBMODES 16 +#define NB_SUBMODE_BITS 4 + +#define SB_SUBMODES 8 +#define SB_SUBMODE_BITS 3 + + +/** Quantizes LSPs */ +typedef void (*lsp_quant_func)(float *, float *, int, SpeexBits *); + +/** Decodes quantized LSPs */ +typedef void (*lsp_unquant_func)(float *, int, SpeexBits *); + + +/** Long-term predictor quantization */ +typedef int (*ltp_quant_func)(float *, float *, float *, float *, + float *, float *, void *, int, int, float, + int, int, SpeexBits*, char *, float *, float *, int); + +/** Long-term un-quantize */ +typedef void (*ltp_unquant_func)(float *, int, int, float, void *, int, int *, + float *, SpeexBits*, char*, int, int, float); + + +/** Innovation quantization function */ +typedef void (*innovation_quant_func)(float *, float *, float *, float *, void *, int, int, + float *, float *, SpeexBits *, char *, int); + +/** Innovation unquantization function */ +typedef void (*innovation_unquant_func)(float *, void *, int, SpeexBits*, char *); + +/** Description of a Speex sub-mode (wither narrowband or wideband */ +typedef struct SpeexSubmode { + int lbr_pitch; /**< Set to -1 for "normal" modes, otherwise encode pitch using a global pitch and allowing a +- lbr_pitch variation (for low not-rates)*/ + int forced_pitch_gain; /**< Use the same (forced) pitch gain for all sub-frames */ + int have_subframe_gain; /**< Number of bits to use as sub-frame innovation gain */ + int double_codebook; /**< Apply innovation quantization twice for higher quality (and higher bit-rate)*/ + /*LSP functions*/ + lsp_quant_func lsp_quant; /**< LSP quantization function */ + lsp_unquant_func lsp_unquant; /**< LSP unquantization function */ + + /*Lont-term predictor functions*/ + ltp_quant_func ltp_quant; /**< Long-term predictor (pitch) quantizer */ + ltp_unquant_func ltp_unquant; /**< Long-term predictor (pitch) un-quantizer */ + void *ltp_params; /**< Pitch parameters (options) */ + + /*Quantization of innovation*/ + innovation_quant_func innovation_quant; /**< Innovation quantization */ + innovation_unquant_func innovation_unquant; /**< Innovation un-quantization */ + void *innovation_params; /**< Innovation quantization parameters*/ + + /*Synthesis filter enhancement*/ + float lpc_enh_k1; /**< Enhancer constant */ + float lpc_enh_k2; /**< Enhancer constant */ + float comb_gain; /**< Gain of enhancer comb filter */ + + int bits_per_frame; /**< Number of bits per frame after encoding*/ +} SpeexSubmode; + +/** Struct defining the encoding/decoding mode*/ +typedef struct SpeexNBMode { + int frameSize; /**< Size of frames used for encoding */ + int subframeSize; /**< Size of sub-frames used for encoding */ + int lpcSize; /**< Order of LPC filter */ + int bufSize; /**< Size of signal buffer to use in encoder */ + int pitchStart; /**< Smallest pitch value allowed */ + int pitchEnd; /**< Largest pitch value allowed */ + + float gamma1; /**< Perceptual filter parameter #1 */ + float gamma2; /**< Perceptual filter parameter #2 */ + float lag_factor; /**< Lag-windowing parameter */ + float lpc_floor; /**< Noise floor for LPC analysis */ + float preemph; /**< Pre-emphasis */ + + SpeexSubmode *submodes[NB_SUBMODES]; /**< Sub-mode data for the mode */ + int defaultSubmode; /**< Default sub-mode to use when encoding */ + int quality_map[11]; /**< Mode corresponding to each quality setting */ +} SpeexNBMode; + + +/** Struct defining the encoding/decoding mode for SB-CELP (wideband) */ +typedef struct SpeexSBMode { + SpeexMode *nb_mode; /**< Embedded narrowband mode */ + int frameSize; /**< Size of frames used for encoding */ + int subframeSize; /**< Size of sub-frames used for encoding */ + int lpcSize; /**< Order of LPC filter */ + int bufSize; /**< Signal buffer size in encoder */ + float gamma1; /**< Perceptual filter parameter #1 */ + float gamma2; /**< Perceptual filter parameter #1 */ + float lag_factor; /**< Lag-windowing parameter */ + float lpc_floor; /**< Noise floor for LPC analysis */ + float preemph; /**< Pre-emphasis */ + float folding_gain; + + SpeexSubmode *submodes[SB_SUBMODES]; /**< Sub-mode data for the mode */ + int defaultSubmode; /**< Default sub-mode to use when encoding */ + int low_quality_map[11]; /**< Mode corresponding to each quality setting */ + int quality_map[11]; /**< Mode corresponding to each quality setting */ + float (*vbr_thresh)[11]; + int nb_modes; +} SpeexSBMode; + + +#endif diff --git a/Code/BF2/External/speex-1.0.5/libspeex/nb_celp.c b/Code/BF2/External/speex-1.0.5/libspeex/nb_celp.c new file mode 100644 index 000000000..d1949919e --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/nb_celp.c @@ -0,0 +1,1718 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: nb_celp.c + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include +#include "nb_celp.h" +#include "lpc.h" +#include "lsp.h" +#include "ltp.h" +#include "quant_lsp.h" +#include "cb_search.h" +#include "filters.h" +#include "stack_alloc.h" +#include "vq.h" +#include +#include "vbr.h" +#include "misc.h" +#include + +#ifdef SLOW_TRIG +#include "math_approx.h" +#define cos speex_cos +#endif + +#ifndef M_PI +#define M_PI 3.14159265358979323846 /* pi */ +#endif + +#ifndef NULL +#define NULL 0 +#endif + +#define SUBMODE(x) st->submodes[st->submodeID]->x + +float exc_gain_quant_scal3[8]={-2.794750, -1.810660, -1.169850, -0.848119, -0.587190, -0.329818, -0.063266, 0.282826}; + +float exc_gain_quant_scal1[2]={-0.35, 0.05}; + +#define sqr(x) ((x)*(x)) + +void *nb_encoder_init(SpeexMode *m) +{ + EncState *st; + SpeexNBMode *mode; + int i; + + mode=(SpeexNBMode *)m->mode; + st = (EncState*)speex_alloc(sizeof(EncState)+8000*sizeof(float)); + if (!st) + return NULL; + + st->stack = ((char*)st) + sizeof(EncState); + + st->mode=m; + + st->frameSize = mode->frameSize; + st->windowSize = st->frameSize*3/2; + st->nbSubframes=mode->frameSize/mode->subframeSize; + st->subframeSize=mode->subframeSize; + st->lpcSize = mode->lpcSize; + st->bufSize = mode->bufSize; + st->gamma1=mode->gamma1; + st->gamma2=mode->gamma2; + st->min_pitch=mode->pitchStart; + st->max_pitch=mode->pitchEnd; + st->lag_factor=mode->lag_factor; + st->lpc_floor = mode->lpc_floor; + st->preemph = mode->preemph; + + st->submodes=mode->submodes; + st->submodeID=st->submodeSelect=mode->defaultSubmode; + st->pre_mem=0; + st->pre_mem2=0; + st->bounded_pitch = 1; + + /* Allocating input buffer */ + st->inBuf = PUSH(st->stack, st->bufSize, float); + st->frame = st->inBuf + st->bufSize - st->windowSize; + /* Allocating excitation buffer */ + st->excBuf = PUSH(st->stack, st->bufSize, float); + st->exc = st->excBuf + st->bufSize - st->windowSize; + st->swBuf = PUSH(st->stack, st->bufSize, float); + st->sw = st->swBuf + st->bufSize - st->windowSize; + + st->exc2Buf = PUSH(st->stack, st->bufSize, float); + st->exc2 = st->exc2Buf + st->bufSize - st->windowSize; + + st->innov = PUSH(st->stack, st->frameSize, float); + + /* Asymmetric "pseudo-Hamming" window */ + { + int part1, part2; + part1 = st->subframeSize*7/2; + part2 = st->subframeSize*5/2; + st->window = PUSH(st->stack, st->windowSize, float); + for (i=0;iwindow[i]=.54-.46*cos(M_PI*i/part1); + for (i=0;iwindow[part1+i]=.54+.46*cos(M_PI*i/part2); + } + /* Create the window for autocorrelation (lag-windowing) */ + st->lagWindow = PUSH(st->stack, st->lpcSize+1, float); + for (i=0;ilpcSize+1;i++) + st->lagWindow[i]=exp(-.5*sqr(2*M_PI*st->lag_factor*i)); + + st->autocorr = PUSH(st->stack, st->lpcSize+1, float); + + st->buf2 = PUSH(st->stack, st->windowSize, float); + + st->lpc = PUSH(st->stack, st->lpcSize+1, float); + st->interp_lpc = PUSH(st->stack, st->lpcSize+1, float); + st->interp_qlpc = PUSH(st->stack, st->lpcSize+1, float); + st->bw_lpc1 = PUSH(st->stack, st->lpcSize+1, float); + st->bw_lpc2 = PUSH(st->stack, st->lpcSize+1, float); + + st->lsp = PUSH(st->stack, st->lpcSize, float); + st->qlsp = PUSH(st->stack, st->lpcSize, float); + st->old_lsp = PUSH(st->stack, st->lpcSize, float); + st->old_qlsp = PUSH(st->stack, st->lpcSize, float); + st->interp_lsp = PUSH(st->stack, st->lpcSize, float); + st->interp_qlsp = PUSH(st->stack, st->lpcSize, float); + st->rc = PUSH(st->stack, st->lpcSize, float); + st->first = 1; + for (i=0;ilpcSize;i++) + { + st->lsp[i]=(M_PI*((float)(i+1)))/(st->lpcSize+1); + } + + st->mem_sp = PUSH(st->stack, st->lpcSize, float); + st->mem_sw = PUSH(st->stack, st->lpcSize, float); + st->mem_sw_whole = PUSH(st->stack, st->lpcSize, float); + st->mem_exc = PUSH(st->stack, st->lpcSize, float); + + st->pi_gain = PUSH(st->stack, st->nbSubframes, float); + + st->pitch = PUSH(st->stack, st->nbSubframes, int); + + st->vbr = PUSHS(st->stack, VBRState); + vbr_init(st->vbr); + st->vbr_quality = 8; + st->vbr_enabled = 0; + st->vad_enabled = 0; + st->dtx_enabled = 0; + st->abr_enabled = 0; + st->abr_drift = 0; + + st->complexity=2; + st->sampling_rate=8000; + st->dtx_count=0; + + return st; +} + +void nb_encoder_destroy(void *state) +{ + EncState *st=(EncState *)state; + /* Free all allocated memory */ + + vbr_destroy(st->vbr); + + /*Free state memory... should be last*/ + speex_free(st); +} + +int nb_encode(void *state, float *in, SpeexBits *bits) +{ + EncState *st; + int i, sub, roots; + int ol_pitch; + float ol_pitch_coef; + float ol_gain; + float *res, *target, *mem; + char *stack; + float *syn_resp; + float lsp_dist=0; + float *orig; + + st=(EncState *)state; + stack=st->stack; + + /* Copy new data in input buffer */ + speex_move(st->inBuf, st->inBuf+st->frameSize, (st->bufSize-st->frameSize)*sizeof(float)); + st->inBuf[st->bufSize-st->frameSize] = in[0] - st->preemph*st->pre_mem; + for (i=1;iframeSize;i++) + st->inBuf[st->bufSize-st->frameSize+i] = in[i] - st->preemph*in[i-1]; + st->pre_mem = in[st->frameSize-1]; + + /* Move signals 1 frame towards the past */ + speex_move(st->exc2Buf, st->exc2Buf+st->frameSize, (st->bufSize-st->frameSize)*sizeof(float)); + speex_move(st->excBuf, st->excBuf+st->frameSize, (st->bufSize-st->frameSize)*sizeof(float)); + speex_move(st->swBuf, st->swBuf+st->frameSize, (st->bufSize-st->frameSize)*sizeof(float)); + + + /* Window for analysis */ + for (i=0;iwindowSize;i++) + st->buf2[i] = st->frame[i] * st->window[i]; + + /* Compute auto-correlation */ + _spx_autocorr(st->buf2, st->autocorr, st->lpcSize+1, st->windowSize); + + st->autocorr[0] += 10; /* prevents NANs */ + st->autocorr[0] *= st->lpc_floor; /* Noise floor in auto-correlation domain */ + + /* Lag windowing: equivalent to filtering in the power-spectrum domain */ + for (i=0;ilpcSize+1;i++) + st->autocorr[i] *= st->lagWindow[i]; + + /* Levinson-Durbin */ + wld(st->lpc+1, st->autocorr, st->rc, st->lpcSize); + st->lpc[0]=1; + + /* LPC to LSPs (x-domain) transform */ + roots=lpc_to_lsp (st->lpc, st->lpcSize, st->lsp, 15, 0.2, stack); + /* Check if we found all the roots */ + if (roots==st->lpcSize) + { + /* LSP x-domain to angle domain*/ + for (i=0;ilpcSize;i++) + st->lsp[i] = acos(st->lsp[i]); + } else { + /* Search again if we can afford it */ + if (st->complexity>1) + roots = lpc_to_lsp (st->lpc, st->lpcSize, st->lsp, 11, 0.05, stack); + if (roots==st->lpcSize) + { + /* LSP x-domain to angle domain*/ + for (i=0;ilpcSize;i++) + st->lsp[i] = acos(st->lsp[i]); + } else { + /*If we can't find all LSP's, do some damage control and use previous filter*/ + for (i=0;ilpcSize;i++) + { + st->lsp[i]=st->old_lsp[i]; + } + } + } + + + lsp_dist=0; + for (i=0;ilpcSize;i++) + lsp_dist += (st->old_lsp[i] - st->lsp[i])*(st->old_lsp[i] - st->lsp[i]); + + /* Whole frame analysis (open-loop estimation of pitch and excitation gain) */ + { + if (st->first) + for (i=0;ilpcSize;i++) + st->interp_lsp[i] = st->lsp[i]; + else + for (i=0;ilpcSize;i++) + st->interp_lsp[i] = .375*st->old_lsp[i] + .625*st->lsp[i]; + + lsp_enforce_margin(st->interp_lsp, st->lpcSize, .002); + + /* Compute interpolated LPCs (unquantized) for whole frame*/ + for (i=0;ilpcSize;i++) + st->interp_lsp[i] = cos(st->interp_lsp[i]); + lsp_to_lpc(st->interp_lsp, st->interp_lpc, st->lpcSize,stack); + + + /*Open-loop pitch*/ + if (!st->submodes[st->submodeID] || st->vbr_enabled || st->vad_enabled || SUBMODE(forced_pitch_gain) || + SUBMODE(lbr_pitch) != -1) + { + int nol_pitch[6]; + float nol_pitch_coef[6]; + + bw_lpc(st->gamma1, st->interp_lpc, st->bw_lpc1, st->lpcSize); + bw_lpc(st->gamma2, st->interp_lpc, st->bw_lpc2, st->lpcSize); + + filter_mem2(st->frame, st->bw_lpc1, st->bw_lpc2, st->sw, st->frameSize, st->lpcSize, st->mem_sw_whole); + + open_loop_nbest_pitch(st->sw, st->min_pitch, st->max_pitch, st->frameSize, + nol_pitch, nol_pitch_coef, 6, stack); + ol_pitch=nol_pitch[0]; + ol_pitch_coef = nol_pitch_coef[0]; + /*Try to remove pitch multiples*/ + for (i=1;i<6;i++) + { + if ((nol_pitch_coef[i]>.85*ol_pitch_coef) && + (fabs(nol_pitch[i]-ol_pitch/2.0)<=1 || fabs(nol_pitch[i]-ol_pitch/3.0)<=1 || + fabs(nol_pitch[i]-ol_pitch/4.0)<=1 || fabs(nol_pitch[i]-ol_pitch/5.0)<=1)) + { + /*ol_pitch_coef=nol_pitch_coef[i];*/ + ol_pitch = nol_pitch[i]; + } + } + /*if (ol_pitch>50) + ol_pitch/=2;*/ + /*ol_pitch_coef = sqrt(ol_pitch_coef);*/ + } else { + ol_pitch=0; + ol_pitch_coef=0; + } + /*Compute "real" excitation*/ + fir_mem2(st->frame, st->interp_lpc, st->exc, st->frameSize, st->lpcSize, st->mem_exc); + + /* Compute open-loop excitation gain */ + ol_gain=0; + for (i=0;iframeSize;i++) + ol_gain += st->exc[i]*st->exc[i]; + + ol_gain=sqrt(1+ol_gain/st->frameSize); + } + + /*VBR stuff*/ + if (st->vbr && (st->vbr_enabled||st->vad_enabled)) + { + + if (st->abr_enabled) + { + float qual_change=0; + if (st->abr_drift2 * st->abr_drift > 0) + { + /* Only adapt if long-term and short-term drift are the same sign */ + qual_change = -.00001*st->abr_drift/(1+st->abr_count); + if (qual_change>.05) + qual_change=.05; + if (qual_change<-.05) + qual_change=-.05; + } + st->vbr_quality += qual_change; + if (st->vbr_quality>10) + st->vbr_quality=10; + if (st->vbr_quality<0) + st->vbr_quality=0; + } + + st->relative_quality = vbr_analysis(st->vbr, in, st->frameSize, ol_pitch, ol_pitch_coef); + /*if (delta_qual<0)*/ + /* delta_qual*=.1*(3+st->vbr_quality);*/ + if (st->vbr_enabled) + { + int mode; + int choice=0; + float min_diff=100; + mode = 8; + while (mode) + { + int v1; + float thresh; + v1=(int)floor(st->vbr_quality); + if (v1==10) + thresh = vbr_nb_thresh[mode][v1]; + else + thresh = (st->vbr_quality-v1)*vbr_nb_thresh[mode][v1+1] + (1+v1-st->vbr_quality)*vbr_nb_thresh[mode][v1]; + if (st->relative_quality > thresh && + st->relative_quality-threshrelative_quality-thresh; + } + mode--; + } + mode=choice; + if (mode==0) + { + if (st->dtx_count==0 || lsp_dist>.05 || !st->dtx_enabled || st->dtx_count>20) + { + mode=1; + st->dtx_count=1; + } else { + mode=0; + st->dtx_count++; + } + } else { + st->dtx_count=0; + } + + speex_encoder_ctl(state, SPEEX_SET_MODE, &mode); + + if (st->abr_enabled) + { + int bitrate; + speex_encoder_ctl(state, SPEEX_GET_BITRATE, &bitrate); + st->abr_drift+=(bitrate-st->abr_enabled); + st->abr_drift2 = .95*st->abr_drift2 + .05*(bitrate-st->abr_enabled); + st->abr_count += 1.0; + } + + } else { + /*VAD only case*/ + int mode; + if (st->relative_quality<2) + { + if (st->dtx_count==0 || lsp_dist>.05 || !st->dtx_enabled || st->dtx_count>20) + { + st->dtx_count=1; + mode=1; + } else { + mode=0; + st->dtx_count++; + } + } else { + st->dtx_count = 0; + mode=st->submodeSelect; + } + /*speex_encoder_ctl(state, SPEEX_SET_MODE, &mode);*/ + st->submodeID=mode; + } + } else { + st->relative_quality = -1; + } + + /* First, transmit a zero for narrowband */ + speex_bits_pack(bits, 0, 1); + + /* Transmit the sub-mode we use for this frame */ + speex_bits_pack(bits, st->submodeID, NB_SUBMODE_BITS); + + + /* If null mode (no transmission), just set a couple things to zero*/ + if (st->submodes[st->submodeID] == NULL) + { + for (i=0;iframeSize;i++) + st->exc[i]=st->exc2[i]=st->sw[i]=VERY_SMALL; + + for (i=0;ilpcSize;i++) + st->mem_sw[i]=0; + st->first=1; + st->bounded_pitch = 1; + + /* Final signal synthesis from excitation */ + iir_mem2(st->exc, st->interp_qlpc, st->frame, st->frameSize, st->lpcSize, st->mem_sp); + + in[0] = st->frame[0] + st->preemph*st->pre_mem2; + for (i=1;iframeSize;i++) + in[i]=st->frame[i] + st->preemph*in[i-1]; + st->pre_mem2=in[st->frameSize-1]; + + return 0; + + } + + /* LSP Quantization */ + if (st->first) + { + for (i=0;ilpcSize;i++) + st->old_lsp[i] = st->lsp[i]; + } + + + /*Quantize LSPs*/ +#if 1 /*0 for unquantized*/ + SUBMODE(lsp_quant)(st->lsp, st->qlsp, st->lpcSize, bits); +#else + for (i=0;ilpcSize;i++) + st->qlsp[i]=st->lsp[i]; +#endif + + /*If we use low bit-rate pitch mode, transmit open-loop pitch*/ + if (SUBMODE(lbr_pitch)!=-1) + { + speex_bits_pack(bits, ol_pitch-st->min_pitch, 7); + } + + if (SUBMODE(forced_pitch_gain)) + { + int quant; + quant = (int)floor(.5+15*ol_pitch_coef); + if (quant>15) + quant=15; + if (quant<0) + quant=0; + speex_bits_pack(bits, quant, 4); + ol_pitch_coef=0.066667*quant; + } + + + /*Quantize and transmit open-loop excitation gain*/ + { + int qe = (int)(floor(.5+3.5*log(ol_gain))); + if (qe<0) + qe=0; + if (qe>31) + qe=31; + ol_gain = exp(qe/3.5); + speex_bits_pack(bits, qe, 5); + } + + /* Special case for first frame */ + if (st->first) + { + for (i=0;ilpcSize;i++) + st->old_qlsp[i] = st->qlsp[i]; + } + + /* Filter response */ + res = PUSH(stack, st->subframeSize, float); + /* Target signal */ + target = PUSH(stack, st->subframeSize, float); + syn_resp = PUSH(stack, st->subframeSize, float); + mem = PUSH(stack, st->lpcSize, float); + orig = PUSH(stack, st->frameSize, float); + for (i=0;iframeSize;i++) + orig[i]=st->frame[i]; + + /* Loop on sub-frames */ + for (sub=0;subnbSubframes;sub++) + { + float tmp; + int offset; + float *sp, *sw, *exc, *exc2; + int pitch; + + /* Offset relative to start of frame */ + offset = st->subframeSize*sub; + /* Original signal */ + sp=st->frame+offset; + /* Excitation */ + exc=st->exc+offset; + /* Weighted signal */ + sw=st->sw+offset; + + exc2=st->exc2+offset; + + + /* LSP interpolation (quantized and unquantized) */ + tmp = (1.0 + sub)/st->nbSubframes; + for (i=0;ilpcSize;i++) + st->interp_lsp[i] = (1-tmp)*st->old_lsp[i] + tmp*st->lsp[i]; + for (i=0;ilpcSize;i++) + st->interp_qlsp[i] = (1-tmp)*st->old_qlsp[i] + tmp*st->qlsp[i]; + + /* Make sure the filters are stable */ + lsp_enforce_margin(st->interp_lsp, st->lpcSize, .002); + lsp_enforce_margin(st->interp_qlsp, st->lpcSize, .002); + + /* Compute interpolated LPCs (quantized and unquantized) */ + for (i=0;ilpcSize;i++) + st->interp_lsp[i] = cos(st->interp_lsp[i]); + lsp_to_lpc(st->interp_lsp, st->interp_lpc, st->lpcSize,stack); + + for (i=0;ilpcSize;i++) + st->interp_qlsp[i] = cos(st->interp_qlsp[i]); + lsp_to_lpc(st->interp_qlsp, st->interp_qlpc, st->lpcSize, stack); + + /* Compute analysis filter gain at w=pi (for use in SB-CELP) */ + tmp=1; + st->pi_gain[sub]=0; + for (i=0;i<=st->lpcSize;i++) + { + st->pi_gain[sub] += tmp*st->interp_qlpc[i]; + tmp = -tmp; + } + + /* Compute bandwidth-expanded (unquantized) LPCs for perceptual weighting */ + bw_lpc(st->gamma1, st->interp_lpc, st->bw_lpc1, st->lpcSize); + if (st->gamma2>=0) + bw_lpc(st->gamma2, st->interp_lpc, st->bw_lpc2, st->lpcSize); + else + { + st->bw_lpc2[0]=1; + st->bw_lpc2[1]=-st->preemph; + for (i=2;i<=st->lpcSize;i++) + st->bw_lpc2[i]=0; + } + + /* Compute impulse response of A(z/g1) / ( A(z)*A(z/g2) )*/ + for (i=0;isubframeSize;i++) + exc[i]=VERY_SMALL; + exc[0]=1; + syn_percep_zero(exc, st->interp_qlpc, st->bw_lpc1, st->bw_lpc2, syn_resp, st->subframeSize, st->lpcSize, stack); + + /* Reset excitation */ + for (i=0;isubframeSize;i++) + exc[i]=VERY_SMALL; + for (i=0;isubframeSize;i++) + exc2[i]=VERY_SMALL; + + /* Compute zero response of A(z/g1) / ( A(z/g2) * A(z) ) */ + for (i=0;ilpcSize;i++) + mem[i]=st->mem_sp[i]; + iir_mem2(exc, st->interp_qlpc, exc, st->subframeSize, st->lpcSize, mem); + + for (i=0;ilpcSize;i++) + mem[i]=st->mem_sw[i]; + filter_mem2(exc, st->bw_lpc1, st->bw_lpc2, res, st->subframeSize, st->lpcSize, mem); + + /* Compute weighted signal */ + for (i=0;ilpcSize;i++) + mem[i]=st->mem_sw[i]; + filter_mem2(sp, st->bw_lpc1, st->bw_lpc2, sw, st->subframeSize, st->lpcSize, mem); + + /* Compute target signal */ + for (i=0;isubframeSize;i++) + target[i]=sw[i]-res[i]; + + for (i=0;isubframeSize;i++) + exc[i]=exc2[i]=0; + + /* If we have a long-term predictor (otherwise, something's wrong) */ + if (SUBMODE(ltp_quant)) + { + int pit_min, pit_max; + /* Long-term prediction */ + if (SUBMODE(lbr_pitch) != -1) + { + /* Low bit-rate pitch handling */ + int margin; + margin = SUBMODE(lbr_pitch); + if (margin) + { + if (ol_pitch < st->min_pitch+margin-1) + ol_pitch=st->min_pitch+margin-1; + if (ol_pitch > st->max_pitch-margin) + ol_pitch=st->max_pitch-margin; + pit_min = ol_pitch-margin+1; + pit_max = ol_pitch+margin; + } else { + pit_min=pit_max=ol_pitch; + } + } else { + pit_min = st->min_pitch; + pit_max = st->max_pitch; + } + + /* Force pitch to use only the current frame if needed */ + if (st->bounded_pitch && pit_max>offset) + pit_max=offset; + + /* Perform pitch search */ + pitch = SUBMODE(ltp_quant)(target, sw, st->interp_qlpc, st->bw_lpc1, st->bw_lpc2, + exc, SUBMODE(ltp_params), pit_min, pit_max, ol_pitch_coef, + st->lpcSize, st->subframeSize, bits, stack, + exc2, syn_resp, st->complexity); + + st->pitch[sub]=pitch; + } else { + speex_error ("No pitch prediction, what's wrong"); + } + + /* Update target for adaptive codebook contribution */ + syn_percep_zero(exc, st->interp_qlpc, st->bw_lpc1, st->bw_lpc2, res, st->subframeSize, st->lpcSize, stack); + for (i=0;isubframeSize;i++) + target[i]-=res[i]; + + + /* Quantization of innovation */ + { + float *innov; + float ener=0, ener_1; + + innov = st->innov+sub*st->subframeSize; + for (i=0;isubframeSize;i++) + innov[i]=0; + + residue_percep_zero(target, st->interp_qlpc, st->bw_lpc1, st->bw_lpc2, st->buf2, st->subframeSize, st->lpcSize, stack); + for (i=0;isubframeSize;i++) + ener+=st->buf2[i]*st->buf2[i]; + ener=sqrt(.1+ener/st->subframeSize); + /*for (i=0;isubframeSize;i++) + printf ("%f\n", st->buf2[i]/ener); + */ + + ener /= ol_gain; + + /* Calculate gain correction for the sub-frame (if any) */ + if (SUBMODE(have_subframe_gain)) + { + int qe; + ener=log(ener); + if (SUBMODE(have_subframe_gain)==3) + { + qe = vq_index(&ener, exc_gain_quant_scal3, 1, 8); + speex_bits_pack(bits, qe, 3); + ener=exc_gain_quant_scal3[qe]; + } else { + qe = vq_index(&ener, exc_gain_quant_scal1, 1, 2); + speex_bits_pack(bits, qe, 1); + ener=exc_gain_quant_scal1[qe]; + } + ener=exp(ener); + } else { + ener=1; + } + + ener*=ol_gain; + + /*printf ("%f %f\n", ener, ol_gain);*/ + + ener_1 = 1/ener; + + /* Normalize innovation */ + for (i=0;isubframeSize;i++) + target[i]*=ener_1; + + /* Quantize innovation */ + if (SUBMODE(innovation_quant)) + { + /* Codebook search */ + SUBMODE(innovation_quant)(target, st->interp_qlpc, st->bw_lpc1, st->bw_lpc2, + SUBMODE(innovation_params), st->lpcSize, st->subframeSize, + innov, syn_resp, bits, stack, st->complexity); + + /* De-normalize innovation and update excitation */ + for (i=0;isubframeSize;i++) + innov[i]*=ener; + for (i=0;isubframeSize;i++) + exc[i] += innov[i]; + } else { + speex_error("No fixed codebook"); + } + + /* In some (rare) modes, we do a second search (more bits) to reduce noise even more */ + if (SUBMODE(double_codebook)) { + char *tmp_stack=stack; + float *innov2 = PUSH(tmp_stack, st->subframeSize, float); + for (i=0;isubframeSize;i++) + innov2[i]=0; + for (i=0;isubframeSize;i++) + target[i]*=2.2; + SUBMODE(innovation_quant)(target, st->interp_qlpc, st->bw_lpc1, st->bw_lpc2, + SUBMODE(innovation_params), st->lpcSize, st->subframeSize, + innov2, syn_resp, bits, tmp_stack, st->complexity); + for (i=0;isubframeSize;i++) + innov2[i]*=ener*(1/2.2); + for (i=0;isubframeSize;i++) + exc[i] += innov2[i]; + } + + for (i=0;isubframeSize;i++) + target[i]*=ener; + + } + + /*Keep the previous memory*/ + for (i=0;ilpcSize;i++) + mem[i]=st->mem_sp[i]; + /* Final signal synthesis from excitation */ + iir_mem2(exc, st->interp_qlpc, sp, st->subframeSize, st->lpcSize, st->mem_sp); + + /* Compute weighted signal again, from synthesized speech (not sure it's the right thing) */ + filter_mem2(sp, st->bw_lpc1, st->bw_lpc2, sw, st->subframeSize, st->lpcSize, st->mem_sw); + for (i=0;isubframeSize;i++) + exc2[i]=exc[i]; + } + + /* Store the LSPs for interpolation in the next frame */ + if (st->submodeID>=1) + { + for (i=0;ilpcSize;i++) + st->old_lsp[i] = st->lsp[i]; + for (i=0;ilpcSize;i++) + st->old_qlsp[i] = st->qlsp[i]; + } + + if (st->submodeID==1) + { + if (st->dtx_count) + speex_bits_pack(bits, 15, 4); + else + speex_bits_pack(bits, 0, 4); + } + + /* The next frame will not be the first (Duh!) */ + st->first = 0; + + { + float ener=0, err=0; + float snr; + for (i=0;iframeSize;i++) + { + ener+=st->frame[i]*st->frame[i]; + err += (st->frame[i]-orig[i])*(st->frame[i]-orig[i]); + } + snr = 10*log10((ener+1)/(err+1)); + /*printf ("%f %f %f\n", snr, ener, err);*/ + } + + /* Replace input by synthesized speech */ + in[0] = st->frame[0] + st->preemph*st->pre_mem2; + for (i=1;iframeSize;i++) + in[i]=st->frame[i] + st->preemph*in[i-1]; + st->pre_mem2=in[st->frameSize-1]; + + if (SUBMODE(innovation_quant) == noise_codebook_quant || st->submodeID==0) + st->bounded_pitch = 1; + else + st->bounded_pitch = 0; + + return 1; +} + + +void *nb_decoder_init(SpeexMode *m) +{ + DecState *st; + SpeexNBMode *mode; + int i; + + mode=(SpeexNBMode*)m->mode; + st = (DecState *)speex_alloc(sizeof(DecState)+4000*sizeof(float)); + st->mode=m; + + st->stack = ((char*)st) + sizeof(DecState); + + st->first=1; + /* Codec parameters, should eventually have several "modes"*/ + st->frameSize = mode->frameSize; + st->windowSize = st->frameSize*3/2; + st->nbSubframes=mode->frameSize/mode->subframeSize; + st->subframeSize=mode->subframeSize; + st->lpcSize = mode->lpcSize; + st->bufSize = mode->bufSize; + st->gamma1=mode->gamma1; + st->gamma2=mode->gamma2; + st->min_pitch=mode->pitchStart; + st->max_pitch=mode->pitchEnd; + st->preemph = mode->preemph; + + st->submodes=mode->submodes; + st->submodeID=mode->defaultSubmode; + + st->pre_mem=0; + st->lpc_enh_enabled=0; + + + st->inBuf = PUSH(st->stack, st->bufSize, float); + st->frame = st->inBuf + st->bufSize - st->windowSize; + st->excBuf = PUSH(st->stack, st->bufSize, float); + st->exc = st->excBuf + st->bufSize - st->windowSize; + for (i=0;ibufSize;i++) + st->inBuf[i]=0; + for (i=0;ibufSize;i++) + st->excBuf[i]=0; + st->innov = PUSH(st->stack, st->frameSize, float); + + st->interp_qlpc = PUSH(st->stack, st->lpcSize+1, float); + st->qlsp = PUSH(st->stack, st->lpcSize, float); + st->old_qlsp = PUSH(st->stack, st->lpcSize, float); + st->interp_qlsp = PUSH(st->stack, st->lpcSize, float); + st->mem_sp = PUSH(st->stack, 5*st->lpcSize, float); + st->comb_mem = PUSHS(st->stack, CombFilterMem); + comp_filter_mem_init (st->comb_mem); + + st->pi_gain = PUSH(st->stack, st->nbSubframes, float); + st->last_pitch = 40; + st->count_lost=0; + st->pitch_gain_buf[0] = st->pitch_gain_buf[1] = st->pitch_gain_buf[2] = 0; + st->pitch_gain_buf_idx = 0; + + st->sampling_rate=8000; + st->last_ol_gain = 0; + + st->user_callback.func = &speex_default_user_handler; + st->user_callback.data = NULL; + for (i=0;i<16;i++) + st->speex_callbacks[i].func = NULL; + + st->voc_m1=st->voc_m2=st->voc_mean=0; + st->voc_offset=0; + st->dtx_enabled=0; + return st; +} + +void nb_decoder_destroy(void *state) +{ + DecState *st; + st=(DecState*)state; + + speex_free(state); +} + +#define median3(a, b, c) ((a) < (b) ? ((b) < (c) ? (b) : ((a) < (c) ? (c) : (a))) : ((c) < (b) ? (b) : ((c) < (a) ? (c) : (a)))) + +static void nb_decode_lost(DecState *st, float *out, char *stack) +{ + int i, sub; + float *awk1, *awk2, *awk3; + float pitch_gain, fact, gain_med; + + fact = exp(-.04*st->count_lost*st->count_lost); + gain_med = median3(st->pitch_gain_buf[0], st->pitch_gain_buf[1], st->pitch_gain_buf[2]); + if (gain_med < st->last_pitch_gain) + st->last_pitch_gain = gain_med; + + pitch_gain = st->last_pitch_gain; + if (pitch_gain>.95) + pitch_gain=.95; + + pitch_gain = pitch_gain*fact + VERY_SMALL; + + /* Shift all buffers by one frame */ + speex_move(st->inBuf, st->inBuf+st->frameSize, (st->bufSize-st->frameSize)*sizeof(float)); + speex_move(st->excBuf, st->excBuf+st->frameSize, (st->bufSize-st->frameSize)*sizeof(float)); + + awk1=PUSH(stack, (st->lpcSize+1), float); + awk2=PUSH(stack, (st->lpcSize+1), float); + awk3=PUSH(stack, (st->lpcSize+1), float); + + for (sub=0;subnbSubframes;sub++) + { + int offset; + float *sp, *exc; + /* Offset relative to start of frame */ + offset = st->subframeSize*sub; + /* Original signal */ + sp=st->frame+offset; + /* Excitation */ + exc=st->exc+offset; + /* Excitation after post-filter*/ + + /* Calculate perceptually enhanced LPC filter */ + if (st->lpc_enh_enabled) + { + float r=.9; + + float k1,k2,k3; + if (st->submodes[st->submodeID] != NULL) + { + k1=SUBMODE(lpc_enh_k1); + k2=SUBMODE(lpc_enh_k2); + } else { + k1=k2=.7; + } + k3=(1-(1-r*k1)/(1-r*k2))/r; + if (!st->lpc_enh_enabled) + { + k1=k2; + k3=0; + } + bw_lpc(k1, st->interp_qlpc, awk1, st->lpcSize); + bw_lpc(k2, st->interp_qlpc, awk2, st->lpcSize); + bw_lpc(k3, st->interp_qlpc, awk3, st->lpcSize); + } + + /* Make up a plausible excitation */ + /* THIS CAN BE IMPROVED */ + /*if (pitch_gain>.95) + pitch_gain=.95;*/ + { + float innov_gain=0; + for (i=0;iframeSize;i++) + innov_gain += st->innov[i]*st->innov[i]; + innov_gain=sqrt(innov_gain/st->frameSize); + for (i=0;isubframeSize;i++) + { +#if 0 + exc[i] = pitch_gain * exc[i - st->last_pitch] + fact*sqrt(1-pitch_gain)*st->innov[i+offset]; + /*Just so it give the same lost packets as with if 0*/ + /*rand();*/ +#else + /*exc[i]=pitch_gain*exc[i-st->last_pitch] + fact*st->innov[i+offset];*/ + exc[i]=pitch_gain*(exc[i-st->last_pitch]+VERY_SMALL) + + fact*sqrt(1-pitch_gain)*speex_rand(innov_gain); +#endif + } + } + for (i=0;isubframeSize;i++) + sp[i]=exc[i]+VERY_SMALL; + + /* Signal synthesis */ + if (st->lpc_enh_enabled) + { + filter_mem2(sp, awk2, awk1, sp, st->subframeSize, st->lpcSize, + st->mem_sp+st->lpcSize); + filter_mem2(sp, awk3, st->interp_qlpc, sp, st->subframeSize, st->lpcSize, + st->mem_sp); + } else { + for (i=0;ilpcSize;i++) + st->mem_sp[st->lpcSize+i] = 0; + iir_mem2(sp, st->interp_qlpc, sp, st->subframeSize, st->lpcSize, + st->mem_sp); + } + } + + out[0] = st->frame[0] + st->preemph*st->pre_mem; + for (i=1;iframeSize;i++) + out[i]=st->frame[i] + st->preemph*out[i-1]; + st->pre_mem=out[st->frameSize-1]; + + st->first = 0; + st->count_lost++; + st->pitch_gain_buf[st->pitch_gain_buf_idx++] = pitch_gain; + if (st->pitch_gain_buf_idx > 2) /* rollover */ + st->pitch_gain_buf_idx = 0; +} + +int nb_decode(void *state, SpeexBits *bits, float *out) +{ + DecState *st; + int i, sub; + int pitch; + float pitch_gain[3]; + float ol_gain=0; + int ol_pitch=0; + float ol_pitch_coef=0; + int best_pitch=40; + float best_pitch_gain=0; + int wideband; + int m; + char *stack; + float *awk1, *awk2, *awk3; + float pitch_average=0; + + st=(DecState*)state; + stack=st->stack; + + /* Check if we're in DTX mode*/ + if (!bits && st->dtx_enabled) + { + st->submodeID=0; + } else + { + /* If bits is NULL, consider the packet to be lost (what could we do anyway) */ + if (!bits) + { + nb_decode_lost(st, out, stack); + return 0; + } + + /* Search for next narrowband block (handle requests, skip wideband blocks) */ + do { + wideband = speex_bits_unpack_unsigned(bits, 1); + if (wideband) /* Skip wideband block (for compatibility) */ + { + int submode; + int advance; + advance = submode = speex_bits_unpack_unsigned(bits, SB_SUBMODE_BITS); + speex_mode_query(&speex_wb_mode, SPEEX_SUBMODE_BITS_PER_FRAME, &advance); + if (advance < 0) + { + speex_warning ("Invalid wideband mode encountered. Corrupted stream?"); + return -2; + } + advance -= (SB_SUBMODE_BITS+1); + speex_bits_advance(bits, advance); + wideband = speex_bits_unpack_unsigned(bits, 1); + if (wideband) + { + advance = submode = speex_bits_unpack_unsigned(bits, SB_SUBMODE_BITS); + speex_mode_query(&speex_wb_mode, SPEEX_SUBMODE_BITS_PER_FRAME, &advance); + if (advance < 0) + { + speex_warning ("Invalid wideband mode encountered: corrupted stream?"); + return -2; + } + advance -= (SB_SUBMODE_BITS+1); + speex_bits_advance(bits, advance); + wideband = speex_bits_unpack_unsigned(bits, 1); + if (wideband) + { + speex_warning ("More than to wideband layers found: corrupted stream?"); + return -2; + } + + } + } + + /* FIXME: Check for overflow */ + m = speex_bits_unpack_unsigned(bits, 4); + if (m==15) /* We found a terminator */ + { + return -1; + } else if (m==14) /* Speex in-band request */ + { + int ret = speex_inband_handler(bits, st->speex_callbacks, state); + if (ret) + return ret; + } else if (m==13) /* User in-band request */ + { + int ret = st->user_callback.func(bits, state, st->user_callback.data); + if (ret) + return ret; + } else if (m>8) /* Invalid mode */ + { + speex_warning("Invalid mode encountered: corrupted stream?"); + return -2; + } + + } while (m>8); + + /* Get the sub-mode that was used */ + st->submodeID = m; + + } + + /* Shift all buffers by one frame */ + speex_move(st->inBuf, st->inBuf+st->frameSize, (st->bufSize-st->frameSize)*sizeof(float)); + speex_move(st->excBuf, st->excBuf+st->frameSize, (st->bufSize-st->frameSize)*sizeof(float)); + + /* If null mode (no transmission), just set a couple things to zero*/ + if (st->submodes[st->submodeID] == NULL) + { + float *lpc; + lpc = PUSH(stack,11, float); + bw_lpc(.93, st->interp_qlpc, lpc, 10); + /*for (i=0;iframeSize;i++) + st->exc[i]=0;*/ + { + float innov_gain=0; + float pgain=st->last_pitch_gain; + if (pgain>.6) + pgain=.6; + for (i=0;iframeSize;i++) + innov_gain += st->innov[i]*st->innov[i]; + innov_gain=sqrt(innov_gain/st->frameSize); + for (i=0;iframeSize;i++) + st->exc[i]=0; + speex_rand_vec(innov_gain, st->exc, st->frameSize); + } + + + st->first=1; + + /* Final signal synthesis from excitation */ + iir_mem2(st->exc, lpc, st->frame, st->frameSize, st->lpcSize, st->mem_sp); + + out[0] = st->frame[0] + st->preemph*st->pre_mem; + for (i=1;iframeSize;i++) + out[i]=st->frame[i] + st->preemph*out[i-1]; + st->pre_mem=out[st->frameSize-1]; + st->count_lost=0; + return 0; + } + + /* Unquantize LSPs */ + SUBMODE(lsp_unquant)(st->qlsp, st->lpcSize, bits); + + /*Damp memory if a frame was lost and the LSP changed too much*/ + if (st->count_lost) + { + float lsp_dist=0, fact; + for (i=0;ilpcSize;i++) + lsp_dist += fabs(st->old_qlsp[i] - st->qlsp[i]); + fact = .6*exp(-.2*lsp_dist); + for (i=0;i<2*st->lpcSize;i++) + st->mem_sp[i] *= fact; + } + + + /* Handle first frame and lost-packet case */ + if (st->first || st->count_lost) + { + for (i=0;ilpcSize;i++) + st->old_qlsp[i] = st->qlsp[i]; + } + + /* Get open-loop pitch estimation for low bit-rate pitch coding */ + if (SUBMODE(lbr_pitch)!=-1) + { + ol_pitch = st->min_pitch+speex_bits_unpack_unsigned(bits, 7); + } + + if (SUBMODE(forced_pitch_gain)) + { + int quant; + quant = speex_bits_unpack_unsigned(bits, 4); + ol_pitch_coef=0.066667*quant; + } + + /* Get global excitation gain */ + { + int qe; + qe = speex_bits_unpack_unsigned(bits, 5); + ol_gain = exp(qe/3.5); + } + + awk1=PUSH(stack, st->lpcSize+1, float); + awk2=PUSH(stack, st->lpcSize+1, float); + awk3=PUSH(stack, st->lpcSize+1, float); + + if (st->submodeID==1) + { + int extra; + extra = speex_bits_unpack_unsigned(bits, 4); + + if (extra==15) + st->dtx_enabled=1; + else + st->dtx_enabled=0; + } + if (st->submodeID>1) + st->dtx_enabled=0; + + /*Loop on subframes */ + for (sub=0;subnbSubframes;sub++) + { + int offset; + float *sp, *exc, tmp; + + /* Offset relative to start of frame */ + offset = st->subframeSize*sub; + /* Original signal */ + sp=st->frame+offset; + /* Excitation */ + exc=st->exc+offset; + /* Excitation after post-filter*/ + + /* LSP interpolation (quantized and unquantized) */ + tmp = (1.0 + sub)/st->nbSubframes; + for (i=0;ilpcSize;i++) + st->interp_qlsp[i] = (1-tmp)*st->old_qlsp[i] + tmp*st->qlsp[i]; + + /* Make sure the LSP's are stable */ + lsp_enforce_margin(st->interp_qlsp, st->lpcSize, .002); + + + /* Compute interpolated LPCs (unquantized) */ + for (i=0;ilpcSize;i++) + st->interp_qlsp[i] = cos(st->interp_qlsp[i]); + lsp_to_lpc(st->interp_qlsp, st->interp_qlpc, st->lpcSize, stack); + + /* Compute enhanced synthesis filter */ + if (st->lpc_enh_enabled) + { + float r=.9; + + float k1,k2,k3; + k1=SUBMODE(lpc_enh_k1); + k2=SUBMODE(lpc_enh_k2); + k3=(1-(1-r*k1)/(1-r*k2))/r; + if (!st->lpc_enh_enabled) + { + k1=k2; + k3=0; + } + bw_lpc(k1, st->interp_qlpc, awk1, st->lpcSize); + bw_lpc(k2, st->interp_qlpc, awk2, st->lpcSize); + bw_lpc(k3, st->interp_qlpc, awk3, st->lpcSize); + + } + + /* Compute analysis filter at w=pi */ + tmp=1; + st->pi_gain[sub]=0; + for (i=0;i<=st->lpcSize;i++) + { + st->pi_gain[sub] += tmp*st->interp_qlpc[i]; + tmp = -tmp; + } + + /* Reset excitation */ + for (i=0;isubframeSize;i++) + exc[i]=0; + + /*Adaptive codebook contribution*/ + if (SUBMODE(ltp_unquant)) + { + int pit_min, pit_max; + /* Handle pitch constraints if any */ + if (SUBMODE(lbr_pitch) != -1) + { + int margin; + margin = SUBMODE(lbr_pitch); + if (margin) + { +/* GT - need optimization? + if (ol_pitch < st->min_pitch+margin-1) + ol_pitch=st->min_pitch+margin-1; + if (ol_pitch > st->max_pitch-margin) + ol_pitch=st->max_pitch-margin; + pit_min = ol_pitch-margin+1; + pit_max = ol_pitch+margin; +*/ + pit_min = ol_pitch-margin+1; + if (pit_min < st->min_pitch) + pit_min = st->min_pitch; + pit_max = ol_pitch+margin; + if (pit_max > st->max_pitch) + pit_max = st->max_pitch; + } else { + pit_min = pit_max = ol_pitch; + } + } else { + pit_min = st->min_pitch; + pit_max = st->max_pitch; + } + + /* Pitch synthesis */ + SUBMODE(ltp_unquant)(exc, pit_min, pit_max, ol_pitch_coef, SUBMODE(ltp_params), + st->subframeSize, &pitch, &pitch_gain[0], bits, stack, st->count_lost, offset, st->last_pitch_gain); + + /* If we had lost frames, check energy of last received frame */ + if (st->count_lost && ol_gain < st->last_ol_gain) + { + float fact = ol_gain/(st->last_ol_gain+1); + for (i=0;isubframeSize;i++) + exc[i]*=fact; + } + + tmp = fabs(pitch_gain[0]+pitch_gain[1]+pitch_gain[2]); + tmp = fabs(pitch_gain[1]); + if (pitch_gain[0]>0) + tmp += pitch_gain[0]; + else + tmp -= .5*pitch_gain[0]; + if (pitch_gain[2]>0) + tmp += pitch_gain[2]; + else + tmp -= .5*pitch_gain[0]; + + + pitch_average += tmp; + if (tmp>best_pitch_gain) + { + best_pitch = pitch; + best_pitch_gain = tmp; + /* best_pitch_gain = tmp*.9; + if (best_pitch_gain>.85) + best_pitch_gain=.85;*/ + } + } else { + speex_error("No pitch prediction, what's wrong"); + } + + /* Unquantize the innovation */ + { + int q_energy; + float ener; + float *innov; + + innov = st->innov+sub*st->subframeSize; + for (i=0;isubframeSize;i++) + innov[i]=0; + + /* Decode sub-frame gain correction */ + if (SUBMODE(have_subframe_gain)==3) + { + q_energy = speex_bits_unpack_unsigned(bits, 3); + ener = ol_gain*exp(exc_gain_quant_scal3[q_energy]); + } else if (SUBMODE(have_subframe_gain)==1) + { + q_energy = speex_bits_unpack_unsigned(bits, 1); + ener = ol_gain*exp(exc_gain_quant_scal1[q_energy]); + } else { + ener = ol_gain; + } + + if (SUBMODE(innovation_unquant)) + { + /*Fixed codebook contribution*/ + SUBMODE(innovation_unquant)(innov, SUBMODE(innovation_params), st->subframeSize, bits, stack); + } else { + speex_error("No fixed codebook"); + } + + /* De-normalize innovation and update excitation */ + for (i=0;isubframeSize;i++) + innov[i]*=ener; + + /*Vocoder mode*/ + if (st->submodeID==1) + { + float g=ol_pitch_coef; + + + for (i=0;isubframeSize;i++) + exc[i]=0; + while (st->voc_offsetsubframeSize) + { + if (st->voc_offset>=0) + exc[st->voc_offset]=sqrt(1.0*ol_pitch); + st->voc_offset+=ol_pitch; + } + st->voc_offset -= st->subframeSize; + + g=.5+2*(g-.6); + if (g<0) + g=0; + if (g>1) + g=1; + for (i=0;isubframeSize;i++) + { + float exci=exc[i]; + exc[i]=.8*g*exc[i]*ol_gain + .6*g*st->voc_m1*ol_gain + .5*g*innov[i] - .5*g*st->voc_m2 + (1-g)*innov[i]; + st->voc_m1 = exci; + st->voc_m2=innov[i]; + st->voc_mean = .95*st->voc_mean + .05*exc[i]; + exc[i]-=st->voc_mean; + } + } else { + for (i=0;isubframeSize;i++) + exc[i]+=innov[i]; + } + /* Decode second codebook (only for some modes) */ + if (SUBMODE(double_codebook)) + { + char *tmp_stack=stack; + float *innov2 = PUSH(tmp_stack, st->subframeSize, float); + for (i=0;isubframeSize;i++) + innov2[i]=0; + SUBMODE(innovation_unquant)(innov2, SUBMODE(innovation_params), st->subframeSize, bits, tmp_stack); + for (i=0;isubframeSize;i++) + innov2[i]*=ener*(1/2.2); + for (i=0;isubframeSize;i++) + exc[i] += innov2[i]; + } + + } + + for (i=0;isubframeSize;i++) + sp[i]=exc[i]; + + /* Signal synthesis */ + if (st->lpc_enh_enabled && SUBMODE(comb_gain)>0) + comb_filter(exc, sp, st->interp_qlpc, st->lpcSize, st->subframeSize, + pitch, pitch_gain, SUBMODE(comb_gain), st->comb_mem); + if (st->lpc_enh_enabled) + { + /* Use enhanced LPC filter */ + filter_mem2(sp, awk2, awk1, sp, st->subframeSize, st->lpcSize, + st->mem_sp+st->lpcSize); + filter_mem2(sp, awk3, st->interp_qlpc, sp, st->subframeSize, st->lpcSize, + st->mem_sp); + } else { + /* Use regular filter */ + for (i=0;ilpcSize;i++) + st->mem_sp[st->lpcSize+i] = 0; + iir_mem2(sp, st->interp_qlpc, sp, st->subframeSize, st->lpcSize, + st->mem_sp); + } + } + + /*Copy output signal*/ + out[0] = st->frame[0] + st->preemph*st->pre_mem; + for (i=1;iframeSize;i++) + out[i]=st->frame[i] + st->preemph*out[i-1]; + st->pre_mem=out[st->frameSize-1]; + + + /* Store the LSPs for interpolation in the next frame */ + for (i=0;ilpcSize;i++) + st->old_qlsp[i] = st->qlsp[i]; + + /* The next frame will not be the first (Duh!) */ + st->first = 0; + st->count_lost=0; + st->last_pitch = best_pitch; + st->last_pitch_gain = .25*pitch_average; + st->pitch_gain_buf[st->pitch_gain_buf_idx++] = st->last_pitch_gain; + if (st->pitch_gain_buf_idx > 2) /* rollover */ + st->pitch_gain_buf_idx = 0; + + st->last_ol_gain = ol_gain; + + return 0; +} + +int nb_encoder_ctl(void *state, int request, void *ptr) +{ + EncState *st; + st=(EncState*)state; + switch(request) + { + case SPEEX_GET_FRAME_SIZE: + (*(int*)ptr) = st->frameSize; + break; + case SPEEX_SET_LOW_MODE: + case SPEEX_SET_MODE: + st->submodeSelect = st->submodeID = (*(int*)ptr); + break; + case SPEEX_GET_LOW_MODE: + case SPEEX_GET_MODE: + (*(int*)ptr) = st->submodeID; + break; + case SPEEX_SET_VBR: + st->vbr_enabled = (*(int*)ptr); + break; + case SPEEX_GET_VBR: + (*(int*)ptr) = st->vbr_enabled; + break; + case SPEEX_SET_VAD: + st->vad_enabled = (*(int*)ptr); + break; + case SPEEX_GET_VAD: + (*(int*)ptr) = st->vad_enabled; + break; + case SPEEX_SET_DTX: + st->dtx_enabled = (*(int*)ptr); + break; + case SPEEX_GET_DTX: + (*(int*)ptr) = st->dtx_enabled; + break; + case SPEEX_SET_ABR: + st->abr_enabled = (*(int*)ptr); + st->vbr_enabled = 1; + { + int i=10, rate, target; + float vbr_qual; + target = (*(int*)ptr); + while (i>=0) + { + speex_encoder_ctl(st, SPEEX_SET_QUALITY, &i); + speex_encoder_ctl(st, SPEEX_GET_BITRATE, &rate); + if (rate <= target) + break; + i--; + } + vbr_qual=i; + if (vbr_qual<0) + vbr_qual=0; + speex_encoder_ctl(st, SPEEX_SET_VBR_QUALITY, &vbr_qual); + st->abr_count=0; + st->abr_drift=0; + st->abr_drift2=0; + } + + break; + case SPEEX_GET_ABR: + (*(int*)ptr) = st->abr_enabled; + break; + case SPEEX_SET_VBR_QUALITY: + st->vbr_quality = (*(float*)ptr); + break; + case SPEEX_GET_VBR_QUALITY: + (*(float*)ptr) = st->vbr_quality; + break; + case SPEEX_SET_QUALITY: + { + int quality = (*(int*)ptr); + if (quality < 0) + quality = 0; + if (quality > 10) + quality = 10; + st->submodeSelect = st->submodeID = ((SpeexNBMode*)(st->mode->mode))->quality_map[quality]; + } + break; + case SPEEX_SET_COMPLEXITY: + st->complexity = (*(int*)ptr); + if (st->complexity<1) + st->complexity=1; + break; + case SPEEX_GET_COMPLEXITY: + (*(int*)ptr) = st->complexity; + break; + case SPEEX_SET_BITRATE: + { + int i=10, rate, target; + target = (*(int*)ptr); + while (i>=0) + { + speex_encoder_ctl(st, SPEEX_SET_QUALITY, &i); + speex_encoder_ctl(st, SPEEX_GET_BITRATE, &rate); + if (rate <= target) + break; + i--; + } + } + break; + case SPEEX_GET_BITRATE: + if (st->submodes[st->submodeID]) + (*(int*)ptr) = st->sampling_rate*SUBMODE(bits_per_frame)/st->frameSize; + else + (*(int*)ptr) = st->sampling_rate*(NB_SUBMODE_BITS+1)/st->frameSize; + break; + case SPEEX_SET_SAMPLING_RATE: + st->sampling_rate = (*(int*)ptr); + break; + case SPEEX_GET_SAMPLING_RATE: + (*(int*)ptr)=st->sampling_rate; + break; + case SPEEX_RESET_STATE: + { + int i; + st->bounded_pitch = 1; + st->first = 1; + for (i=0;ilpcSize;i++) + st->lsp[i]=(M_PI*((float)(i+1)))/(st->lpcSize+1); + for (i=0;ilpcSize;i++) + st->mem_sw[i]=st->mem_sw_whole[i]=st->mem_sp[i]=st->mem_exc[i]=0; + for (i=0;ibufSize;i++) + st->excBuf[i]=st->swBuf[i]=st->inBuf[i]=st->exc2Buf[i]=0; + } + break; + case SPEEX_GET_LOOKAHEAD: + (*(int*)ptr)=(st->windowSize-st->frameSize); + break; + case SPEEX_GET_PI_GAIN: + { + int i; + float *g = (float*)ptr; + for (i=0;inbSubframes;i++) + g[i]=st->pi_gain[i]; + } + break; + case SPEEX_GET_EXC: + { + int i; + float *e = (float*)ptr; + for (i=0;iframeSize;i++) + e[i]=st->exc[i]; + } + break; + case SPEEX_GET_INNOV: + { + int i; + float *e = (float*)ptr; + for (i=0;iframeSize;i++) + e[i]=st->innov[i]; + } + break; + case SPEEX_GET_RELATIVE_QUALITY: + (*(float*)ptr)=st->relative_quality; + break; + default: + speex_warning_int("Unknown nb_ctl request: ", request); + return -1; + } + return 0; +} + +int nb_decoder_ctl(void *state, int request, void *ptr) +{ + DecState *st; + st=(DecState*)state; + switch(request) + { + case SPEEX_GET_LOW_MODE: + case SPEEX_GET_MODE: + (*(int*)ptr) = st->submodeID; + break; + case SPEEX_SET_ENH: + st->lpc_enh_enabled = *((int*)ptr); + break; + case SPEEX_GET_ENH: + *((int*)ptr) = st->lpc_enh_enabled; + break; + case SPEEX_GET_FRAME_SIZE: + (*(int*)ptr) = st->frameSize; + break; + case SPEEX_GET_BITRATE: + if (st->submodes[st->submodeID]) + (*(int*)ptr) = st->sampling_rate*SUBMODE(bits_per_frame)/st->frameSize; + else + (*(int*)ptr) = st->sampling_rate*(NB_SUBMODE_BITS+1)/st->frameSize; + break; + case SPEEX_SET_SAMPLING_RATE: + st->sampling_rate = (*(int*)ptr); + break; + case SPEEX_GET_SAMPLING_RATE: + (*(int*)ptr)=st->sampling_rate; + break; + case SPEEX_SET_HANDLER: + { + SpeexCallback *c = (SpeexCallback*)ptr; + st->speex_callbacks[c->callback_id].func=c->func; + st->speex_callbacks[c->callback_id].data=c->data; + st->speex_callbacks[c->callback_id].callback_id=c->callback_id; + } + break; + case SPEEX_SET_USER_HANDLER: + { + SpeexCallback *c = (SpeexCallback*)ptr; + st->user_callback.func=c->func; + st->user_callback.data=c->data; + st->user_callback.callback_id=c->callback_id; + } + break; + case SPEEX_RESET_STATE: + { + int i; + for (i=0;i<2*st->lpcSize;i++) + st->mem_sp[i]=0; + for (i=0;ibufSize;i++) + st->excBuf[i]=st->inBuf[i]=0; + } + break; + case SPEEX_GET_PI_GAIN: + { + int i; + float *g = (float*)ptr; + for (i=0;inbSubframes;i++) + g[i]=st->pi_gain[i]; + } + break; + case SPEEX_GET_EXC: + { + int i; + float *e = (float*)ptr; + for (i=0;iframeSize;i++) + e[i]=st->exc[i]; + } + break; + case SPEEX_GET_INNOV: + { + int i; + float *e = (float*)ptr; + for (i=0;iframeSize;i++) + e[i]=st->innov[i]; + } + break; + case SPEEX_GET_DTX_STATUS: + *((int*)ptr) = st->dtx_enabled; + break; + default: + speex_warning_int("Unknown nb_ctl request: ", request); + return -1; + } + return 0; +} diff --git a/Code/BF2/External/speex-1.0.5/libspeex/nb_celp.h b/Code/BF2/External/speex-1.0.5/libspeex/nb_celp.h new file mode 100644 index 000000000..5deaf4d2f --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/nb_celp.h @@ -0,0 +1,202 @@ +/* Copyright (C) 2002 Jean-Marc Valin */ +/** + @file nb_celp.h + @brief Narrowband CELP encoder/decoder +*/ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +*/ + +#ifndef NB_CELP_H +#define NB_CELP_H + +#include "modes.h" +#include +#include +#include "vbr.h" +#include "filters.h" + +/**Structure representing the full state of the narrowband encoder*/ +typedef struct EncState { + SpeexMode *mode; /**< Mode corresponding to the state */ + int first; /**< Is this the first frame? */ + int frameSize; /**< Size of frames */ + int subframeSize; /**< Size of sub-frames */ + int nbSubframes; /**< Number of sub-frames */ + int windowSize; /**< Analysis (LPC) window length */ + int lpcSize; /**< LPC order */ + int bufSize; /**< Buffer size */ + int min_pitch; /**< Minimum pitch value allowed */ + int max_pitch; /**< Maximum pitch value allowed */ + + int safe_pitch; /**< Don't use too large values for pitch (in case we lose a packet) */ + int bounded_pitch; /**< Next frame should not rely on previous frames for pitch */ + int ol_pitch; /**< Open-loop pitch */ + int ol_voiced; /**< Open-loop voiced/non-voiced decision */ + int *pitch; + float gamma1; /**< Perceptual filter: A(z/gamma1) */ + float gamma2; /**< Perceptual filter: A(z/gamma2) */ + float lag_factor; /**< Lag windowing Gaussian width */ + float lpc_floor; /**< Noise floor multiplier for A[0] in LPC analysis*/ + float preemph; /**< Pre-emphasis: P(z) = 1 - a*z^-1*/ + float pre_mem; /**< 1-element memory for pre-emphasis */ + float pre_mem2; /**< 1-element memory for pre-emphasis */ + char *stack; /**< Pseudo-stack allocation for temporary memory */ + float *inBuf; /**< Input buffer (original signal) */ + float *frame; /**< Start of original frame */ + float *excBuf; /**< Excitation buffer */ + float *exc; /**< Start of excitation frame */ + float *exc2Buf; /**< "Pitch enhanced" excitation */ + float *exc2; /**< "Pitch enhanced" excitation */ + float *swBuf; /**< Weighted signal buffer */ + float *sw; /**< Start of weighted signal frame */ + float *innov; /**< Innovation for the frame */ + float *window; /**< Temporary (Hanning) window */ + float *buf2; /**< 2nd temporary buffer */ + float *autocorr; /**< auto-correlation */ + float *lagWindow; /**< Window applied to auto-correlation */ + float *lpc; /**< LPCs for current frame */ + float *lsp; /**< LSPs for current frame */ + float *qlsp; /**< Quantized LSPs for current frame */ + float *old_lsp; /**< LSPs for previous frame */ + float *old_qlsp; /**< Quantized LSPs for previous frame */ + float *interp_lsp; /**< Interpolated LSPs */ + float *interp_qlsp; /**< Interpolated quantized LSPs */ + float *interp_lpc; /**< Interpolated LPCs */ + float *interp_qlpc; /**< Interpolated quantized LPCs */ + float *bw_lpc1; /**< LPCs after bandwidth expansion by gamma1 for perceptual weighting*/ + float *bw_lpc2; /**< LPCs after bandwidth expansion by gamma2 for perceptual weighting*/ + float *rc; /**< Reflection coefficients */ + float *mem_sp; /**< Filter memory for signal synthesis */ + float *mem_sw; /**< Filter memory for perceptually-weighted signal */ + float *mem_sw_whole; /**< Filter memory for perceptually-weighted signal (whole frame)*/ + float *mem_exc; /**< Filter memory for excitation (whole frame) */ + float *pi_gain; /**< Gain of LPC filter at theta=pi (fe/2) */ + + VBRState *vbr; /**< State of the VBR data */ + float vbr_quality; /**< Quality setting for VBR encoding */ + float relative_quality; /**< Relative quality that will be needed by VBR */ + int vbr_enabled; /**< 1 for enabling VBR, 0 otherwise */ + int vad_enabled; /**< 1 for enabling VAD, 0 otherwise */ + int dtx_enabled; /**< 1 for enabling DTX, 0 otherwise */ + int dtx_count; /**< Number of consecutive DTX frames */ + int abr_enabled; /**< ABR setting (in bps), 0 if off */ + float abr_drift; + float abr_drift2; + float abr_count; + int complexity; /**< Complexity setting (0-10 from least complex to most complex) */ + int sampling_rate; + + SpeexSubmode **submodes; /**< Sub-mode data */ + int submodeID; /**< Activated sub-mode */ + int submodeSelect; /**< Mode chosen by the user (may differ from submodeID if VAD is on) */ +} EncState; + +/**Structure representing the full state of the narrowband decoder*/ +typedef struct DecState { + SpeexMode *mode; /**< Mode corresponding to the state */ + int first; /**< Is this the first frame? */ + int count_lost; /**< Was the last frame lost? */ + int frameSize; /**< Size of frames */ + int subframeSize; /**< Size of sub-frames */ + int nbSubframes; /**< Number of sub-frames */ + int windowSize; /**< Analysis (LPC) window length */ + int lpcSize; /**< LPC order */ + int bufSize; /**< Buffer size */ + int min_pitch; /**< Minimum pitch value allowed */ + int max_pitch; /**< Maximum pitch value allowed */ + int sampling_rate; + float last_ol_gain; /**< Open-loop gain for previous frame */ + + + float gamma1; /**< Perceptual filter: A(z/gamma1) */ + float gamma2; /**< Perceptual filter: A(z/gamma2) */ + float preemph; /**< Pre-emphasis: P(z) = 1 - a*z^-1*/ + float pre_mem; /**< 1-element memory for pre-emphasis */ + char *stack; /**< Pseudo-stack allocation for temporary memory */ + float *inBuf; /**< Input buffer (original signal) */ + float *frame; /**< Start of original frame */ + float *excBuf; /**< Excitation buffer */ + float *exc; /**< Start of excitation frame */ + float *innov; /**< Innovation for the frame */ + float *qlsp; /**< Quantized LSPs for current frame */ + float *old_qlsp; /**< Quantized LSPs for previous frame */ + float *interp_qlsp; /**< Interpolated quantized LSPs */ + float *interp_qlpc; /**< Interpolated quantized LPCs */ + float *mem_sp; /**< Filter memory for synthesis signal */ + float *pi_gain; /**< Gain of LPC filter at theta=pi (fe/2) */ + int last_pitch; /**< Pitch of last correctly decoded frame */ + float last_pitch_gain; /**< Pitch gain of last correctly decoded frame */ + float pitch_gain_buf[3]; /**< Pitch gain of last decoded frames */ + int pitch_gain_buf_idx; /**< Tail of the buffer */ + + SpeexSubmode **submodes; /**< Sub-mode data */ + int submodeID; /**< Activated sub-mode */ + int lpc_enh_enabled; /**< 1 when LPC enhancer is on, 0 otherwise */ + CombFilterMem *comb_mem; + SpeexCallback speex_callbacks[SPEEX_MAX_CALLBACKS]; + + SpeexCallback user_callback; + + /*Vocoder data*/ + float voc_m1; + float voc_m2; + float voc_mean; + int voc_offset; + + int dtx_enabled; +} DecState; + +/** Initializes encoder state*/ +void *nb_encoder_init(SpeexMode *m); + +/** De-allocates encoder state resources*/ +void nb_encoder_destroy(void *state); + +/** Encodes one frame*/ +int nb_encode(void *state, float *in, SpeexBits *bits); + + +/** Initializes decoder state*/ +void *nb_decoder_init(SpeexMode *m); + +/** De-allocates decoder state resources*/ +void nb_decoder_destroy(void *state); + +/** Decodes one frame*/ +int nb_decode(void *state, SpeexBits *bits, float *out); + +/** ioctl-like function for controlling a narrowband encoder */ +int nb_encoder_ctl(void *state, int request, void *ptr); + +/** ioctl-like function for controlling a narrowband decoder */ +int nb_decoder_ctl(void *state, int request, void *ptr); + + +#endif diff --git a/Code/BF2/External/speex-1.0.5/libspeex/quant_lsp.c b/Code/BF2/External/speex-1.0.5/libspeex/quant_lsp.c new file mode 100644 index 000000000..fea955d2a --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/quant_lsp.c @@ -0,0 +1,312 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: quant_lsp.c + LSP vector quantization + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include "quant_lsp.h" +#include + +/* Note: x is modified*/ +static int lsp_quant(float *x, signed char *cdbk, int nbVec, int nbDim) +{ + int i,j; + float dist, tmp; + float best_dist=0; + int best_id=0; + signed char *ptr=cdbk; + for (i=0;i tmp2 ? tmp1 : tmp2; + } + for (i=0;i tmp2 ? tmp1 : tmp2; + } + + for (i=0;i tmp2 ? tmp1 : tmp2; + } + + for (i=0;i + +#define MAX_LSP_SIZE 20 + +#define NB_CDBK_SIZE 64 +#define NB_CDBK_SIZE_LOW1 64 +#define NB_CDBK_SIZE_LOW2 64 +#define NB_CDBK_SIZE_HIGH1 64 +#define NB_CDBK_SIZE_HIGH2 64 + +/*Narrowband codebooks*/ +extern signed char cdbk_nb[]; +extern signed char cdbk_nb_low1[]; +extern signed char cdbk_nb_low2[]; +extern signed char cdbk_nb_high1[]; +extern signed char cdbk_nb_high2[]; + +/* Quantizes narrowband LSPs with 30 bits */ +void lsp_quant_nb(float *lsp, float *qlsp, int order, SpeexBits *bits); + +/* Decodes quantized narrowband LSPs */ +void lsp_unquant_nb(float *lsp, int order, SpeexBits *bits); + +/* Quantizes low bit-rate narrowband LSPs with 18 bits */ +void lsp_quant_lbr(float *lsp, float *qlsp, int order, SpeexBits *bits); + +/* Decodes quantized low bit-rate narrowband LSPs */ +void lsp_unquant_lbr(float *lsp, int order, SpeexBits *bits); + +/* Quantizes high-band LSPs with 12 bits */ +void lsp_quant_high(float *lsp, float *qlsp, int order, SpeexBits *bits); + +/* Decodes high-band LSPs */ +void lsp_unquant_high(float *lsp, int order, SpeexBits *bits); + +#endif diff --git a/Code/BF2/External/speex-1.0.5/libspeex/sb_celp.c b/Code/BF2/External/speex-1.0.5/libspeex/sb_celp.c new file mode 100644 index 000000000..ef1a78772 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/sb_celp.c @@ -0,0 +1,1337 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: sb_celp.c + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + + +#include +#include "sb_celp.h" +#include "stdlib.h" +#include "filters.h" +#include "lpc.h" +#include "lsp.h" +#include "stack_alloc.h" +#include "cb_search.h" +#include "quant_lsp.h" +#include "vq.h" +#include "ltp.h" +#include "misc.h" + +#ifndef M_PI +#define M_PI 3.14159265358979323846 /* pi */ +#endif + +#define sqr(x) ((x)*(x)) + +#define SUBMODE(x) st->submodes[st->submodeID]->x + +#define QMF_ORDER 64 +static float h0[64] = { + 3.596189e-05, -0.0001123515, + -0.0001104587, 0.0002790277, + 0.0002298438, -0.0005953563, + -0.0003823631, 0.00113826, + 0.0005308539, -0.001986177, + -0.0006243724, 0.003235877, + 0.0005743159, -0.004989147, + -0.0002584767, 0.007367171, + -0.0004857935, -0.01050689, + 0.001894714, 0.01459396, + -0.004313674, -0.01994365, + 0.00828756, 0.02716055, + -0.01485397, -0.03764973, + 0.026447, 0.05543245, + -0.05095487, -0.09779096, + 0.1382363, 0.4600981, + 0.4600981, 0.1382363, + -0.09779096, -0.05095487, + 0.05543245, 0.026447, + -0.03764973, -0.01485397, + 0.02716055, 0.00828756, + -0.01994365, -0.004313674, + 0.01459396, 0.001894714, + -0.01050689, -0.0004857935, + 0.007367171, -0.0002584767, + -0.004989147, 0.0005743159, + 0.003235877, -0.0006243724, + -0.001986177, 0.0005308539, + 0.00113826, -0.0003823631, + -0.0005953563, 0.0002298438, + 0.0002790277, -0.0001104587, + -0.0001123515, 3.596189e-05 +}; + +static float h1[64] = { + 3.596189e-05, 0.0001123515, + -0.0001104587, -0.0002790277, + 0.0002298438, 0.0005953563, + -0.0003823631, -0.00113826, + 0.0005308539, 0.001986177, + -0.0006243724, -0.003235877, + 0.0005743159, 0.004989147, + -0.0002584767, -0.007367171, + -0.0004857935, 0.01050689, + 0.001894714, -0.01459396, + -0.004313674, 0.01994365, + 0.00828756, -0.02716055, + -0.01485397, 0.03764973, + 0.026447, -0.05543245, + -0.05095487, 0.09779096, + 0.1382363, -0.4600981, + 0.4600981, -0.1382363, + -0.09779096, 0.05095487, + 0.05543245, -0.026447, + -0.03764973, 0.01485397, + 0.02716055, -0.00828756, + -0.01994365, 0.004313674, + 0.01459396, -0.001894714, + -0.01050689, 0.0004857935, + 0.007367171, 0.0002584767, + -0.004989147, -0.0005743159, + 0.003235877, 0.0006243724, + -0.001986177, -0.0005308539, + 0.00113826, 0.0003823631, + -0.0005953563, -0.0002298438, + 0.0002790277, 0.0001104587, + -0.0001123515, -3.596189e-05 +}; + +void *sb_encoder_init(SpeexMode *m) +{ + int i; + SBEncState *st; + SpeexSBMode *mode; + + st = (SBEncState*)speex_alloc(sizeof(SBEncState)+8000*sizeof(float)); + st->mode = m; + mode = (SpeexSBMode*)m->mode; + + st->stack = ((char*)st) + sizeof(SBEncState); + + st->st_low = speex_encoder_init(mode->nb_mode); + st->full_frame_size = 2*mode->frameSize; + st->frame_size = mode->frameSize; + st->subframeSize = mode->subframeSize; + st->nbSubframes = mode->frameSize/mode->subframeSize; + st->windowSize = st->frame_size*3/2; + st->lpcSize=mode->lpcSize; + st->bufSize=mode->bufSize; + + st->submodes=mode->submodes; + st->submodeSelect = st->submodeID=mode->defaultSubmode; + + i=9; + speex_encoder_ctl(st->st_low, SPEEX_SET_QUALITY, &i); + + st->lag_factor = mode->lag_factor; + st->lpc_floor = mode->lpc_floor; + st->gamma1=mode->gamma1; + st->gamma2=mode->gamma2; + st->first=1; + + st->x0d=PUSH(st->stack, st->frame_size, float); + st->x1d=PUSH(st->stack, st->frame_size, float); + st->high=PUSH(st->stack, st->full_frame_size, float); + st->y0=PUSH(st->stack, st->full_frame_size, float); + st->y1=PUSH(st->stack, st->full_frame_size, float); + + st->h0_mem=PUSH(st->stack, QMF_ORDER, float); + st->h1_mem=PUSH(st->stack, QMF_ORDER, float); + st->g0_mem=PUSH(st->stack, QMF_ORDER, float); + st->g1_mem=PUSH(st->stack, QMF_ORDER, float); + + st->buf=PUSH(st->stack, st->windowSize, float); + st->excBuf=PUSH(st->stack, st->bufSize, float); + st->exc = st->excBuf + st->bufSize - st->windowSize; + + st->res=PUSH(st->stack, st->frame_size, float); + st->sw=PUSH(st->stack, st->frame_size, float); + st->target=PUSH(st->stack, st->frame_size, float); + /*Asymmetric "pseudo-Hamming" window*/ + { + int part1, part2; + part1 = st->subframeSize*7/2; + part2 = st->subframeSize*5/2; + st->window = PUSH(st->stack, st->windowSize, float); + for (i=0;iwindow[i]=.54-.46*cos(M_PI*i/part1); + for (i=0;iwindow[part1+i]=.54+.46*cos(M_PI*i/part2); + } + + st->lagWindow = PUSH(st->stack, st->lpcSize+1, float); + for (i=0;ilpcSize+1;i++) + st->lagWindow[i]=exp(-.5*sqr(2*M_PI*st->lag_factor*i)); + + st->rc = PUSH(st->stack, st->lpcSize, float); + st->autocorr = PUSH(st->stack, st->lpcSize+1, float); + st->lpc = PUSH(st->stack, st->lpcSize+1, float); + st->bw_lpc1 = PUSH(st->stack, st->lpcSize+1, float); + st->bw_lpc2 = PUSH(st->stack, st->lpcSize+1, float); + st->lsp = PUSH(st->stack, st->lpcSize, float); + st->qlsp = PUSH(st->stack, st->lpcSize, float); + st->old_lsp = PUSH(st->stack, st->lpcSize, float); + st->old_qlsp = PUSH(st->stack, st->lpcSize, float); + st->interp_lsp = PUSH(st->stack, st->lpcSize, float); + st->interp_qlsp = PUSH(st->stack, st->lpcSize, float); + st->interp_lpc = PUSH(st->stack, st->lpcSize+1, float); + st->interp_qlpc = PUSH(st->stack, st->lpcSize+1, float); + st->pi_gain = PUSH(st->stack, st->nbSubframes, float); + + st->mem_sp = PUSH(st->stack, st->lpcSize, float); + st->mem_sp2 = PUSH(st->stack, st->lpcSize, float); + st->mem_sw = PUSH(st->stack, st->lpcSize, float); + + st->vbr_quality = 8; + st->vbr_enabled = 0; + st->vad_enabled = 0; + st->abr_enabled = 0; + st->relative_quality=0; + + st->complexity=2; + speex_encoder_ctl(st->st_low, SPEEX_GET_SAMPLING_RATE, &st->sampling_rate); + st->sampling_rate*=2; + + return st; +} + +void sb_encoder_destroy(void *state) +{ + SBEncState *st=(SBEncState*)state; + + speex_encoder_destroy(st->st_low); + + speex_free(st); +} + + +int sb_encode(void *state, float *in, SpeexBits *bits) +{ + SBEncState *st; + int i, roots, sub; + char *stack; + float *mem, *innov, *syn_resp; + float *low_pi_gain, *low_exc, *low_innov; + SpeexSBMode *mode; + int dtx; + + st = (SBEncState*)state; + stack=st->stack; + mode = (SpeexSBMode*)(st->mode->mode); + + /* Compute the two sub-bands by filtering with h0 and h1*/ + qmf_decomp(in, h0, st->x0d, st->x1d, st->full_frame_size, QMF_ORDER, st->h0_mem, stack); + + /* Encode the narrowband part*/ + speex_encode(st->st_low, st->x0d, bits); + + /* High-band buffering / sync with low band */ + for (i=0;iwindowSize-st->frame_size;i++) + st->high[i] = st->high[st->frame_size+i]; + for (i=0;iframe_size;i++) + st->high[st->windowSize-st->frame_size+i]=st->x1d[i]; + + speex_move(st->excBuf, st->excBuf+st->frame_size, (st->bufSize-st->frame_size)*sizeof(float)); + + + low_pi_gain = PUSH(stack, st->nbSubframes, float); + low_exc = PUSH(stack, st->frame_size, float); + low_innov = PUSH(stack, st->frame_size, float); + speex_encoder_ctl(st->st_low, SPEEX_GET_PI_GAIN, low_pi_gain); + speex_encoder_ctl(st->st_low, SPEEX_GET_EXC, low_exc); + speex_encoder_ctl(st->st_low, SPEEX_GET_INNOV, low_innov); + + speex_encoder_ctl(st->st_low, SPEEX_GET_LOW_MODE, &dtx); + + if (dtx==0) + dtx=1; + else + dtx=0; + + /* Start encoding the high-band */ + for (i=0;iwindowSize;i++) + st->buf[i] = st->high[i] * st->window[i]; + + /* Compute auto-correlation */ + _spx_autocorr(st->buf, st->autocorr, st->lpcSize+1, st->windowSize); + + st->autocorr[0] += 1; /* prevents NANs */ + st->autocorr[0] *= st->lpc_floor; /* Noise floor in auto-correlation domain */ + /* Lag windowing: equivalent to filtering in the power-spectrum domain */ + for (i=0;ilpcSize+1;i++) + st->autocorr[i] *= st->lagWindow[i]; + + /* Levinson-Durbin */ + wld(st->lpc+1, st->autocorr, st->rc, st->lpcSize); + st->lpc[0]=1; + + /* LPC to LSPs (x-domain) transform */ + roots=lpc_to_lsp (st->lpc, st->lpcSize, st->lsp, 15, 0.2, stack); + if (roots!=st->lpcSize) + { + roots = lpc_to_lsp (st->lpc, st->lpcSize, st->lsp, 11, 0.02, stack); + if (roots!=st->lpcSize) { + /*If we can't find all LSP's, do some damage control and use a flat filter*/ + for (i=0;ilpcSize;i++) + { + st->lsp[i]=cos(M_PI*((float)(i+1))/(st->lpcSize+1)); + } + } + } + + /* x-domain to angle domain*/ + for (i=0;ilpcSize;i++) + st->lsp[i] = acos(st->lsp[i]); + + /* VBR code */ + if ((st->vbr_enabled || st->vad_enabled) && !dtx) + { + float e_low=0, e_high=0; + float ratio; + if (st->abr_enabled) + { + float qual_change=0; + if (st->abr_drift2 * st->abr_drift > 0) + { + /* Only adapt if long-term and short-term drift are the same sign */ + qual_change = -.00001*st->abr_drift/(1+st->abr_count); + if (qual_change>.1) + qual_change=.1; + if (qual_change<-.1) + qual_change=-.1; + } + st->vbr_quality += qual_change; + if (st->vbr_quality>10) + st->vbr_quality=10; + if (st->vbr_quality<0) + st->vbr_quality=0; + } + + + for (i=0;iframe_size;i++) + { + e_low += st->x0d[i]* st->x0d[i]; + e_high += st->high[i]* st->high[i]; + } + ratio = log((1+e_high)/(1+e_low)); + speex_encoder_ctl(st->st_low, SPEEX_GET_RELATIVE_QUALITY, &st->relative_quality); + if (ratio<-4) + ratio=-4; + if (ratio>2) + ratio=2; + /*if (ratio>-2)*/ + if (st->vbr_enabled) + { + int modeid; + modeid = mode->nb_modes-1; + st->relative_quality+=1.0*(ratio+2); + if (st->relative_quality<-1) + st->relative_quality=-1; + while (modeid) + { + int v1; + float thresh; + v1=(int)floor(st->vbr_quality); + if (v1==10) + thresh = mode->vbr_thresh[modeid][v1]; + else + thresh = (st->vbr_quality-v1) * mode->vbr_thresh[modeid][v1+1] + + (1+v1-st->vbr_quality) * mode->vbr_thresh[modeid][v1]; + if (st->relative_quality >= thresh) + break; + modeid--; + } + speex_encoder_ctl(state, SPEEX_SET_HIGH_MODE, &modeid); + if (st->abr_enabled) + { + int bitrate; + speex_encoder_ctl(state, SPEEX_GET_BITRATE, &bitrate); + st->abr_drift+=(bitrate-st->abr_enabled); + st->abr_drift2 = .95*st->abr_drift2 + .05*(bitrate-st->abr_enabled); + st->abr_count += 1.0; + } + + } else { + /* VAD only */ + int modeid; + if (st->relative_quality<2.0) + modeid=1; + else + modeid=st->submodeSelect; + /*speex_encoder_ctl(state, SPEEX_SET_MODE, &mode);*/ + st->submodeID=modeid; + + } + /*fprintf (stderr, "%f %f\n", ratio, low_qual);*/ + } + + speex_bits_pack(bits, 1, 1); + if (dtx) + speex_bits_pack(bits, 0, SB_SUBMODE_BITS); + else + speex_bits_pack(bits, st->submodeID, SB_SUBMODE_BITS); + + /* If null mode (no transmission), just set a couple things to zero*/ + if (dtx || st->submodes[st->submodeID] == NULL) + { + for (i=0;iframe_size;i++) + st->exc[i]=st->sw[i]=VERY_SMALL; + + for (i=0;ilpcSize;i++) + st->mem_sw[i]=0; + st->first=1; + + /* Final signal synthesis from excitation */ + iir_mem2(st->exc, st->interp_qlpc, st->high, st->subframeSize, st->lpcSize, st->mem_sp); + +#ifndef RELEASE + + /* Reconstruct the original */ + fir_mem_up(st->x0d, h0, st->y0, st->full_frame_size, QMF_ORDER, st->g0_mem, stack); + fir_mem_up(st->high, h1, st->y1, st->full_frame_size, QMF_ORDER, st->g1_mem, stack); + + for (i=0;ifull_frame_size;i++) + in[i]=2*(st->y0[i]-st->y1[i]); +#endif + + if (dtx) + return 0; + else + return 1; + } + + + /* LSP quantization */ + SUBMODE(lsp_quant)(st->lsp, st->qlsp, st->lpcSize, bits); + + if (st->first) + { + for (i=0;ilpcSize;i++) + st->old_lsp[i] = st->lsp[i]; + for (i=0;ilpcSize;i++) + st->old_qlsp[i] = st->qlsp[i]; + } + + mem=PUSH(stack, st->lpcSize, float); + syn_resp=PUSH(stack, st->subframeSize, float); + innov = PUSH(stack, st->subframeSize, float); + + for (sub=0;subnbSubframes;sub++) + { + float *exc, *sp, *res, *target, *sw, tmp, filter_ratio; + int offset; + float rl, rh, eh=0, el=0; + int fold; + + offset = st->subframeSize*sub; + sp=st->high+offset; + exc=st->exc+offset; + res=st->res+offset; + target=st->target+offset; + sw=st->sw+offset; + + /* LSP interpolation (quantized and unquantized) */ + tmp = (1.0 + sub)/st->nbSubframes; + for (i=0;ilpcSize;i++) + st->interp_lsp[i] = (1-tmp)*st->old_lsp[i] + tmp*st->lsp[i]; + for (i=0;ilpcSize;i++) + st->interp_qlsp[i] = (1-tmp)*st->old_qlsp[i] + tmp*st->qlsp[i]; + + lsp_enforce_margin(st->interp_lsp, st->lpcSize, .05); + lsp_enforce_margin(st->interp_qlsp, st->lpcSize, .05); + + /* Compute interpolated LPCs (quantized and unquantized) */ + for (i=0;ilpcSize;i++) + st->interp_lsp[i] = cos(st->interp_lsp[i]); + for (i=0;ilpcSize;i++) + st->interp_qlsp[i] = cos(st->interp_qlsp[i]); + + lsp_to_lpc(st->interp_lsp, st->interp_lpc, st->lpcSize,stack); + lsp_to_lpc(st->interp_qlsp, st->interp_qlpc, st->lpcSize, stack); + + bw_lpc(st->gamma1, st->interp_lpc, st->bw_lpc1, st->lpcSize); + bw_lpc(st->gamma2, st->interp_lpc, st->bw_lpc2, st->lpcSize); + + /* Compute mid-band (4000 Hz for wideband) response of low-band and high-band + filters */ + rl=rh=0; + tmp=1; + st->pi_gain[sub]=0; + for (i=0;i<=st->lpcSize;i++) + { + rh += tmp*st->interp_qlpc[i]; + tmp = -tmp; + st->pi_gain[sub]+=st->interp_qlpc[i]; + } + rl = low_pi_gain[sub]; + rl=1/(fabs(rl)+.01); + rh=1/(fabs(rh)+.01); + /* Compute ratio, will help predict the gain */ + filter_ratio=fabs(.01+rh)/(.01+fabs(rl)); + + fold = filter_ratio<5; + /*printf ("filter_ratio %f\n", filter_ratio);*/ + fold=0; + + /* Compute "real excitation" */ + fir_mem2(sp, st->interp_qlpc, exc, st->subframeSize, st->lpcSize, st->mem_sp2); + /* Compute energy of low-band and high-band excitation */ + for (i=0;isubframeSize;i++) + eh+=sqr(exc[i]); + + if (!SUBMODE(innovation_quant)) {/* 1 for spectral folding excitation, 0 for stochastic */ + float g; + /*speex_bits_pack(bits, 1, 1);*/ + for (i=0;isubframeSize;i++) + el+=sqr(low_innov[offset+i]); + + /* Gain to use if we want to use the low-band excitation for high-band */ + g=eh/(.01+el); + g=sqrt(g); + + g *= filter_ratio; + /*print_vec(&g, 1, "gain factor");*/ + /* Gain quantization */ + { + int quant = (int) floor(.5 + 10 + 8.0 * log((g+.0001))); + /*speex_warning_int("tata", quant);*/ + if (quant<0) + quant=0; + if (quant>31) + quant=31; + speex_bits_pack(bits, quant, 5); + g= .1*exp(quant/9.4); + } + /*printf ("folding gain: %f\n", g);*/ + g /= filter_ratio; + + } else { + float gc, scale, scale_1; + + for (i=0;isubframeSize;i++) + el+=sqr(low_exc[offset+i]); + /*speex_bits_pack(bits, 0, 1);*/ + + gc = sqrt(1+eh)*filter_ratio/sqrt((1+el)*st->subframeSize); + { + int qgc = (int)floor(.5+3.7*(log(gc)+2)); + if (qgc<0) + qgc=0; + if (qgc>15) + qgc=15; + speex_bits_pack(bits, qgc, 4); + gc = exp((1/3.7)*qgc-2); + } + + scale = gc*sqrt(1+el)/filter_ratio; + scale_1 = 1/scale; + + for (i=0;isubframeSize;i++) + exc[i]=0; + exc[0]=1; + syn_percep_zero(exc, st->interp_qlpc, st->bw_lpc1, st->bw_lpc2, syn_resp, st->subframeSize, st->lpcSize, stack); + + /* Reset excitation */ + for (i=0;isubframeSize;i++) + exc[i]=0; + + /* Compute zero response (ringing) of A(z/g1) / ( A(z/g2) * Aq(z) ) */ + for (i=0;ilpcSize;i++) + mem[i]=st->mem_sp[i]; + iir_mem2(exc, st->interp_qlpc, exc, st->subframeSize, st->lpcSize, mem); + + for (i=0;ilpcSize;i++) + mem[i]=st->mem_sw[i]; + filter_mem2(exc, st->bw_lpc1, st->bw_lpc2, res, st->subframeSize, st->lpcSize, mem); + + /* Compute weighted signal */ + for (i=0;ilpcSize;i++) + mem[i]=st->mem_sw[i]; + filter_mem2(sp, st->bw_lpc1, st->bw_lpc2, sw, st->subframeSize, st->lpcSize, mem); + + /* Compute target signal */ + for (i=0;isubframeSize;i++) + target[i]=sw[i]-res[i]; + + for (i=0;isubframeSize;i++) + exc[i]=0; + + + for (i=0;isubframeSize;i++) + target[i]*=scale_1; + + /* Reset excitation */ + for (i=0;isubframeSize;i++) + innov[i]=0; + + /*print_vec(target, st->subframeSize, "\ntarget");*/ + SUBMODE(innovation_quant)(target, st->interp_qlpc, st->bw_lpc1, st->bw_lpc2, + SUBMODE(innovation_params), st->lpcSize, st->subframeSize, + innov, syn_resp, bits, stack, (st->complexity+1)>>1); + /*print_vec(target, st->subframeSize, "after");*/ + + for (i=0;isubframeSize;i++) + exc[i] += innov[i]*scale; + + if (SUBMODE(double_codebook)) { + char *tmp_stack=stack; + float *innov2 = PUSH(tmp_stack, st->subframeSize, float); + for (i=0;isubframeSize;i++) + innov2[i]=0; + for (i=0;isubframeSize;i++) + target[i]*=2.5; + SUBMODE(innovation_quant)(target, st->interp_qlpc, st->bw_lpc1, st->bw_lpc2, + SUBMODE(innovation_params), st->lpcSize, st->subframeSize, + innov2, syn_resp, bits, tmp_stack, (st->complexity+1)>>1); + for (i=0;isubframeSize;i++) + innov2[i]*=scale*(1/2.5); + for (i=0;isubframeSize;i++) + exc[i] += innov2[i]; + } + + } + + /*Keep the previous memory*/ + for (i=0;ilpcSize;i++) + mem[i]=st->mem_sp[i]; + /* Final signal synthesis from excitation */ + iir_mem2(exc, st->interp_qlpc, sp, st->subframeSize, st->lpcSize, st->mem_sp); + + /* Compute weighted signal again, from synthesized speech (not sure it's the right thing) */ + filter_mem2(sp, st->bw_lpc1, st->bw_lpc2, sw, st->subframeSize, st->lpcSize, st->mem_sw); + } + + +#ifndef RELEASE + + /* Reconstruct the original */ + fir_mem_up(st->x0d, h0, st->y0, st->full_frame_size, QMF_ORDER, st->g0_mem, stack); + fir_mem_up(st->high, h1, st->y1, st->full_frame_size, QMF_ORDER, st->g1_mem, stack); + + for (i=0;ifull_frame_size;i++) + in[i]=2*(st->y0[i]-st->y1[i]); +#endif + for (i=0;ilpcSize;i++) + st->old_lsp[i] = st->lsp[i]; + for (i=0;ilpcSize;i++) + st->old_qlsp[i] = st->qlsp[i]; + + st->first=0; + + return 1; +} + + + + + +void *sb_decoder_init(SpeexMode *m) +{ + SBDecState *st; + SpeexSBMode *mode; + st = (SBDecState*)speex_alloc(sizeof(SBDecState)+6000*sizeof(float)); + st->mode = m; + mode=(SpeexSBMode*)m->mode; + + st->stack = ((char*)st) + sizeof(SBDecState); + + + + st->st_low = speex_decoder_init(mode->nb_mode); + st->full_frame_size = 2*mode->frameSize; + st->frame_size = mode->frameSize; + st->subframeSize = mode->subframeSize; + st->nbSubframes = mode->frameSize/mode->subframeSize; + st->lpcSize=8; + speex_decoder_ctl(st->st_low, SPEEX_GET_SAMPLING_RATE, &st->sampling_rate); + st->sampling_rate*=2; + + st->submodes=mode->submodes; + st->submodeID=mode->defaultSubmode; + + st->first=1; + + + st->x0d=PUSH(st->stack, st->frame_size, float); + st->x1d=PUSH(st->stack, st->frame_size, float); + st->high=PUSH(st->stack, st->full_frame_size, float); + st->y0=PUSH(st->stack, st->full_frame_size, float); + st->y1=PUSH(st->stack, st->full_frame_size, float); + + st->h0_mem=PUSH(st->stack, QMF_ORDER, float); + st->h1_mem=PUSH(st->stack, QMF_ORDER, float); + st->g0_mem=PUSH(st->stack, QMF_ORDER, float); + st->g1_mem=PUSH(st->stack, QMF_ORDER, float); + + st->exc=PUSH(st->stack, st->frame_size, float); + + st->qlsp = PUSH(st->stack, st->lpcSize, float); + st->old_qlsp = PUSH(st->stack, st->lpcSize, float); + st->interp_qlsp = PUSH(st->stack, st->lpcSize, float); + st->interp_qlpc = PUSH(st->stack, st->lpcSize+1, float); + + st->pi_gain = PUSH(st->stack, st->nbSubframes, float); + st->mem_sp = PUSH(st->stack, 2*st->lpcSize, float); + + st->lpc_enh_enabled=0; + + return st; +} + +void sb_decoder_destroy(void *state) +{ + SBDecState *st; + st = (SBDecState*)state; + speex_decoder_destroy(st->st_low); + + speex_free(state); +} + +static void sb_decode_lost(SBDecState *st, float *out, int dtx, char *stack) +{ + int i; + float *awk1, *awk2, *awk3; + int saved_modeid=0; + + if (dtx) + { + saved_modeid=st->submodeID; + st->submodeID=1; + } else { + bw_lpc(0.99, st->interp_qlpc, st->interp_qlpc, st->lpcSize); + } + + st->first=1; + + awk1=PUSH(stack, st->lpcSize+1, float); + awk2=PUSH(stack, st->lpcSize+1, float); + awk3=PUSH(stack, st->lpcSize+1, float); + + if (st->lpc_enh_enabled) + { + float r=.9; + + float k1,k2,k3; + if (st->submodes[st->submodeID] != NULL) + { + k1=SUBMODE(lpc_enh_k1); + k2=SUBMODE(lpc_enh_k2); + } else { + k1=k2=.7; + } + k3=(1-(1-r*k1)/(1-r*k2))/r; + k3=k1-k2; + if (!st->lpc_enh_enabled) + { + k1=k2; + k3=0; + } + bw_lpc(k1, st->interp_qlpc, awk1, st->lpcSize); + bw_lpc(k2, st->interp_qlpc, awk2, st->lpcSize); + bw_lpc(k3, st->interp_qlpc, awk3, st->lpcSize); + /*fprintf (stderr, "%f %f %f\n", k1, k2, k3);*/ + } + + + /* Final signal synthesis from excitation */ + if (!dtx) + { + for (i=0;iframe_size;i++) + st->exc[i] *= .9; + } + + for (i=0;iframe_size;i++) + st->high[i]=st->exc[i]; + + if (st->lpc_enh_enabled) + { + /* Use enhanced LPC filter */ + filter_mem2(st->high, awk2, awk1, st->high, st->frame_size, st->lpcSize, + st->mem_sp+st->lpcSize); + filter_mem2(st->high, awk3, st->interp_qlpc, st->high, st->frame_size, st->lpcSize, + st->mem_sp); + } else { + /* Use regular filter */ + for (i=0;ilpcSize;i++) + st->mem_sp[st->lpcSize+i] = 0; + iir_mem2(st->high, st->interp_qlpc, st->high, st->frame_size, st->lpcSize, + st->mem_sp); + } + + /*iir_mem2(st->exc, st->interp_qlpc, st->high, st->frame_size, st->lpcSize, st->mem_sp);*/ + + /* Reconstruct the original */ + fir_mem_up(st->x0d, h0, st->y0, st->full_frame_size, QMF_ORDER, st->g0_mem, stack); + fir_mem_up(st->high, h1, st->y1, st->full_frame_size, QMF_ORDER, st->g1_mem, stack); + + for (i=0;ifull_frame_size;i++) + out[i]=2*(st->y0[i]-st->y1[i]); + + if (dtx) + { + st->submodeID=saved_modeid; + } + + return; +} + +int sb_decode(void *state, SpeexBits *bits, float *out) +{ + int i, sub; + SBDecState *st; + int wideband; + int ret; + char *stack; + float *low_pi_gain, *low_exc, *low_innov; + float *awk1, *awk2, *awk3; + int dtx; + SpeexSBMode *mode; + + st = (SBDecState*)state; + stack=st->stack; + mode = (SpeexSBMode*)(st->mode->mode); + + /* Decode the low-band */ + ret = speex_decode(st->st_low, bits, st->x0d); + + speex_decoder_ctl(st->st_low, SPEEX_GET_DTX_STATUS, &dtx); + + /* If error decoding the narrowband part, propagate error */ + if (ret!=0) + { + return ret; + } + + if (!bits) + { + sb_decode_lost(st, out, dtx, stack); + return 0; + } + + /*Check "wideband bit"*/ + if (speex_bits_remaining(bits)>0) + wideband = speex_bits_peek(bits); + else + wideband = 0; + if (wideband) + { + /*Regular wideband frame, read the submode*/ + wideband = speex_bits_unpack_unsigned(bits, 1); + st->submodeID = speex_bits_unpack_unsigned(bits, SB_SUBMODE_BITS); + } else + { + /*Was a narrowband frame, set "null submode"*/ + st->submodeID = 0; + } + if (st->submodeID != 0 && st->submodes[st->submodeID] == NULL) + { + speex_warning("Invalid mode encountered: corrupted stream?"); + return -2; + } + + /* If null mode (no transmission), just set a couple things to zero*/ + if (st->submodes[st->submodeID] == NULL) + { + if (dtx) + { + sb_decode_lost(st, out, 1, stack); + return 0; + } + + for (i=0;iframe_size;i++) + st->exc[i]=VERY_SMALL; + + st->first=1; + + /* Final signal synthesis from excitation */ + iir_mem2(st->exc, st->interp_qlpc, st->high, st->frame_size, st->lpcSize, st->mem_sp); + + fir_mem_up(st->x0d, h0, st->y0, st->full_frame_size, QMF_ORDER, st->g0_mem, stack); + fir_mem_up(st->high, h1, st->y1, st->full_frame_size, QMF_ORDER, st->g1_mem, stack); + + for (i=0;ifull_frame_size;i++) + out[i]=2*(st->y0[i]-st->y1[i]); + + return 0; + + } + + for (i=0;iframe_size;i++) + st->exc[i]=0; + + low_pi_gain = PUSH(stack, st->nbSubframes, float); + low_exc = PUSH(stack, st->frame_size, float); + low_innov = PUSH(stack, st->frame_size, float); + speex_decoder_ctl(st->st_low, SPEEX_GET_PI_GAIN, low_pi_gain); + speex_decoder_ctl(st->st_low, SPEEX_GET_EXC, low_exc); + speex_decoder_ctl(st->st_low, SPEEX_GET_INNOV, low_innov); + + SUBMODE(lsp_unquant)(st->qlsp, st->lpcSize, bits); + + if (st->first) + { + for (i=0;ilpcSize;i++) + st->old_qlsp[i] = st->qlsp[i]; + } + + awk1=PUSH(stack, st->lpcSize+1, float); + awk2=PUSH(stack, st->lpcSize+1, float); + awk3=PUSH(stack, st->lpcSize+1, float); + + for (sub=0;subnbSubframes;sub++) + { + float *exc, *sp, tmp, filter_ratio, el=0; + int offset; + float rl=0,rh=0; + + offset = st->subframeSize*sub; + sp=st->high+offset; + exc=st->exc+offset; + + /* LSP interpolation */ + tmp = (1.0 + sub)/st->nbSubframes; + for (i=0;ilpcSize;i++) + st->interp_qlsp[i] = (1-tmp)*st->old_qlsp[i] + tmp*st->qlsp[i]; + + lsp_enforce_margin(st->interp_qlsp, st->lpcSize, .05); + + /* LSPs to x-domain */ + for (i=0;ilpcSize;i++) + st->interp_qlsp[i] = cos(st->interp_qlsp[i]); + + /* LSP to LPC */ + lsp_to_lpc(st->interp_qlsp, st->interp_qlpc, st->lpcSize, stack); + + + if (st->lpc_enh_enabled) + { + float r=.9; + + float k1,k2,k3; + k1=SUBMODE(lpc_enh_k1); + k2=SUBMODE(lpc_enh_k2); + k3=(1-(1-r*k1)/(1-r*k2))/r; + k3=k1-k2; + if (!st->lpc_enh_enabled) + { + k1=k2; + k3=0; + } + bw_lpc(k1, st->interp_qlpc, awk1, st->lpcSize); + bw_lpc(k2, st->interp_qlpc, awk2, st->lpcSize); + bw_lpc(k3, st->interp_qlpc, awk3, st->lpcSize); + /*fprintf (stderr, "%f %f %f\n", k1, k2, k3);*/ + } + + + /* Calculate reponse ratio between the low and high filter in the middle + of the band (4000 Hz) */ + + tmp=1; + st->pi_gain[sub]=0; + for (i=0;i<=st->lpcSize;i++) + { + rh += tmp*st->interp_qlpc[i]; + tmp = -tmp; + st->pi_gain[sub]+=st->interp_qlpc[i]; + } + rl = low_pi_gain[sub]; + rl=1/(fabs(rl)+.01); + rh=1/(fabs(rh)+.01); + filter_ratio=fabs(.01+rh)/(.01+fabs(rl)); + + + for (i=0;isubframeSize;i++) + exc[i]=0; + if (!SUBMODE(innovation_unquant)) + { + float g; + int quant; + + for (i=0;isubframeSize;i++) + el+=sqr(low_innov[offset+i]); + quant = speex_bits_unpack_unsigned(bits, 5); + g= exp(((float)quant-10)/8.0); + + /*printf ("unquant folding gain: %f\n", g);*/ + g /= filter_ratio; + + /* High-band excitation using the low-band excitation and a gain */ + for (i=0;isubframeSize;i++) + exc[i]=mode->folding_gain*g*low_innov[offset+i]; + /*speex_rand_vec(mode->folding_gain*g*sqrt(el/st->subframeSize), exc, st->subframeSize);*/ + } else { + float gc, scale; + int qgc = speex_bits_unpack_unsigned(bits, 4); + for (i=0;isubframeSize;i++) + el+=sqr(low_exc[offset+i]); + + + gc = exp((1/3.7)*qgc-2); + + scale = gc*sqrt(1+el)/filter_ratio; + + + SUBMODE(innovation_unquant)(exc, SUBMODE(innovation_params), st->subframeSize, + bits, stack); + for (i=0;isubframeSize;i++) + exc[i]*=scale; + + if (SUBMODE(double_codebook)) { + char *tmp_stack=stack; + float *innov2 = PUSH(tmp_stack, st->subframeSize, float); + for (i=0;isubframeSize;i++) + innov2[i]=0; + SUBMODE(innovation_unquant)(innov2, SUBMODE(innovation_params), st->subframeSize, + bits, tmp_stack); + for (i=0;isubframeSize;i++) + innov2[i]*=scale*(1/2.5); + for (i=0;isubframeSize;i++) + exc[i] += innov2[i]; + } + + } + + for (i=0;isubframeSize;i++) + sp[i]=exc[i]; + if (st->lpc_enh_enabled) + { + /* Use enhanced LPC filter */ + filter_mem2(sp, awk2, awk1, sp, st->subframeSize, st->lpcSize, + st->mem_sp+st->lpcSize); + filter_mem2(sp, awk3, st->interp_qlpc, sp, st->subframeSize, st->lpcSize, + st->mem_sp); + } else { + /* Use regular filter */ + for (i=0;ilpcSize;i++) + st->mem_sp[st->lpcSize+i] = 0; + iir_mem2(sp, st->interp_qlpc, sp, st->subframeSize, st->lpcSize, + st->mem_sp); + } + /*iir_mem2(exc, st->interp_qlpc, sp, st->subframeSize, st->lpcSize, st->mem_sp);*/ + + } + + fir_mem_up(st->x0d, h0, st->y0, st->full_frame_size, QMF_ORDER, st->g0_mem, stack); + fir_mem_up(st->high, h1, st->y1, st->full_frame_size, QMF_ORDER, st->g1_mem, stack); + + for (i=0;ifull_frame_size;i++) + out[i]=2*(st->y0[i]-st->y1[i]); + + for (i=0;ilpcSize;i++) + st->old_qlsp[i] = st->qlsp[i]; + + st->first=0; + + return 0; +} + + +int sb_encoder_ctl(void *state, int request, void *ptr) +{ + SBEncState *st; + st=(SBEncState*)state; + switch(request) + { + case SPEEX_GET_FRAME_SIZE: + (*(int*)ptr) = st->full_frame_size; + break; + case SPEEX_SET_HIGH_MODE: + st->submodeSelect = st->submodeID = (*(int*)ptr); + break; + case SPEEX_SET_LOW_MODE: + speex_encoder_ctl(st->st_low, SPEEX_SET_LOW_MODE, ptr); + break; + case SPEEX_SET_DTX: + speex_encoder_ctl(st->st_low, SPEEX_SET_DTX, ptr); + break; + case SPEEX_GET_DTX: + speex_encoder_ctl(st->st_low, SPEEX_GET_DTX, ptr); + break; + case SPEEX_GET_LOW_MODE: + speex_encoder_ctl(st->st_low, SPEEX_GET_LOW_MODE, ptr); + break; + case SPEEX_SET_MODE: + speex_encoder_ctl(st, SPEEX_SET_QUALITY, ptr); + break; + case SPEEX_SET_VBR: + st->vbr_enabled = (*(int*)ptr); + speex_encoder_ctl(st->st_low, SPEEX_SET_VBR, ptr); + break; + case SPEEX_GET_VBR: + (*(int*)ptr) = st->vbr_enabled; + break; + case SPEEX_SET_VAD: + st->vad_enabled = (*(int*)ptr); + speex_encoder_ctl(st->st_low, SPEEX_SET_VAD, ptr); + break; + case SPEEX_GET_VAD: + (*(int*)ptr) = st->vad_enabled; + break; + case SPEEX_SET_VBR_QUALITY: + { + int q; + float qual = (*(float*)ptr)+.6; + st->vbr_quality = (*(float*)ptr); + if (qual>10) + qual=10; + q=(int)floor(.5+*(float*)ptr); + if (q>10) + q=10; + speex_encoder_ctl(st->st_low, SPEEX_SET_VBR_QUALITY, &qual); + speex_encoder_ctl(state, SPEEX_SET_QUALITY, &q); + break; + } + case SPEEX_SET_ABR: + st->abr_enabled = (*(int*)ptr); + st->vbr_enabled = 1; + speex_encoder_ctl(st->st_low, SPEEX_SET_VBR, &st->vbr_enabled); + { + int i=10, rate, target; + float vbr_qual; + target = (*(int*)ptr); + while (i>=0) + { + speex_encoder_ctl(st, SPEEX_SET_QUALITY, &i); + speex_encoder_ctl(st, SPEEX_GET_BITRATE, &rate); + if (rate <= target) + break; + i--; + } + vbr_qual=i; + if (vbr_qual<0) + vbr_qual=0; + speex_encoder_ctl(st, SPEEX_SET_VBR_QUALITY, &vbr_qual); + st->abr_count=0; + st->abr_drift=0; + st->abr_drift2=0; + } + + break; + case SPEEX_GET_ABR: + (*(int*)ptr) = st->abr_enabled; + break; + case SPEEX_SET_QUALITY: + { + int nb_qual; + int quality = (*(int*)ptr); + if (quality < 0) + quality = 0; + if (quality > 10) + quality = 10; + st->submodeSelect = st->submodeID = ((SpeexSBMode*)(st->mode->mode))->quality_map[quality]; + nb_qual = ((SpeexSBMode*)(st->mode->mode))->low_quality_map[quality]; + speex_encoder_ctl(st->st_low, SPEEX_SET_MODE, &nb_qual); + } + break; + case SPEEX_SET_COMPLEXITY: + speex_encoder_ctl(st->st_low, SPEEX_SET_COMPLEXITY, ptr); + st->complexity = (*(int*)ptr); + if (st->complexity<1) + st->complexity=1; + break; + case SPEEX_GET_COMPLEXITY: + (*(int*)ptr) = st->complexity; + break; + case SPEEX_SET_BITRATE: + { + int i=10, rate, target; + target = (*(int*)ptr); + while (i>=0) + { + speex_encoder_ctl(st, SPEEX_SET_QUALITY, &i); + speex_encoder_ctl(st, SPEEX_GET_BITRATE, &rate); + if (rate <= target) + break; + i--; + } + } + break; + case SPEEX_GET_BITRATE: + speex_encoder_ctl(st->st_low, request, ptr); + /*fprintf (stderr, "before: %d\n", (*(int*)ptr));*/ + if (st->submodes[st->submodeID]) + (*(int*)ptr) += st->sampling_rate*SUBMODE(bits_per_frame)/st->full_frame_size; + else + (*(int*)ptr) += st->sampling_rate*(SB_SUBMODE_BITS+1)/st->full_frame_size; + /*fprintf (stderr, "after: %d\n", (*(int*)ptr));*/ + break; + case SPEEX_SET_SAMPLING_RATE: + { + int tmp=(*(int*)ptr); + st->sampling_rate = tmp; + tmp>>=1; + speex_encoder_ctl(st->st_low, SPEEX_SET_SAMPLING_RATE, &tmp); + } + break; + case SPEEX_GET_SAMPLING_RATE: + (*(int*)ptr)=st->sampling_rate; + break; + case SPEEX_RESET_STATE: + { + int i; + st->first = 1; + for (i=0;ilpcSize;i++) + st->lsp[i]=(M_PI*((float)(i+1)))/(st->lpcSize+1); + for (i=0;ilpcSize;i++) + st->mem_sw[i]=st->mem_sp[i]=st->mem_sp2[i]=0; + for (i=0;ibufSize;i++) + st->excBuf[i]=0; + for (i=0;ih0_mem[i]=st->h1_mem[i]=st->g0_mem[i]=st->g1_mem[i]=0; + } + break; + case SPEEX_GET_LOOKAHEAD: + speex_encoder_ctl(st->st_low, SPEEX_GET_LOOKAHEAD, ptr); + (*(int*)ptr) = 2*(*(int*)ptr) + QMF_ORDER - 1; + break; + case SPEEX_GET_PI_GAIN: + { + int i; + float *g = (float*)ptr; + for (i=0;inbSubframes;i++) + g[i]=st->pi_gain[i]; + } + break; + case SPEEX_GET_EXC: + { + int i; + float *e = (float*)ptr; + for (i=0;ifull_frame_size;i++) + e[i]=0; + for (i=0;iframe_size;i++) + e[2*i]=2*st->exc[i]; + } + break; + case SPEEX_GET_INNOV: + { + int i; + float *e = (float*)ptr; + for (i=0;ifull_frame_size;i++) + e[i]=0; + for (i=0;iframe_size;i++) + e[2*i]=2*st->exc[i]; + } + break; + case SPEEX_GET_RELATIVE_QUALITY: + (*(float*)ptr)=st->relative_quality; + break; + default: + speex_warning_int("Unknown nb_ctl request: ", request); + return -1; + } + return 0; +} + +int sb_decoder_ctl(void *state, int request, void *ptr) +{ + SBDecState *st; + st=(SBDecState*)state; + switch(request) + { + case SPEEX_GET_LOW_MODE: + speex_decoder_ctl(st->st_low, SPEEX_GET_LOW_MODE, ptr); + break; + case SPEEX_GET_FRAME_SIZE: + (*(int*)ptr) = st->full_frame_size; + break; + case SPEEX_SET_ENH: + speex_decoder_ctl(st->st_low, request, ptr); + st->lpc_enh_enabled = *((int*)ptr); + break; + case SPEEX_GET_BITRATE: + speex_decoder_ctl(st->st_low, request, ptr); + if (st->submodes[st->submodeID]) + (*(int*)ptr) += st->sampling_rate*SUBMODE(bits_per_frame)/st->full_frame_size; + else + (*(int*)ptr) += st->sampling_rate*(SB_SUBMODE_BITS+1)/st->full_frame_size; + break; + case SPEEX_SET_SAMPLING_RATE: + { + int tmp=(*(int*)ptr); + st->sampling_rate = tmp; + tmp>>=1; + speex_decoder_ctl(st->st_low, SPEEX_SET_SAMPLING_RATE, &tmp); + } + break; + case SPEEX_GET_SAMPLING_RATE: + (*(int*)ptr)=st->sampling_rate; + break; + case SPEEX_SET_HANDLER: + speex_decoder_ctl(st->st_low, SPEEX_SET_HANDLER, ptr); + break; + case SPEEX_SET_USER_HANDLER: + speex_decoder_ctl(st->st_low, SPEEX_SET_USER_HANDLER, ptr); + break; + case SPEEX_RESET_STATE: + { + int i; + for (i=0;i<2*st->lpcSize;i++) + st->mem_sp[i]=0; + for (i=0;ih0_mem[i]=st->h1_mem[i]=st->g0_mem[i]=st->g1_mem[i]=0; + } + break; + case SPEEX_GET_PI_GAIN: + { + int i; + float *g = (float*)ptr; + for (i=0;inbSubframes;i++) + g[i]=st->pi_gain[i]; + } + break; + case SPEEX_GET_EXC: + { + int i; + float *e = (float*)ptr; + for (i=0;ifull_frame_size;i++) + e[i]=0; + for (i=0;iframe_size;i++) + e[2*i]=2*st->exc[i]; + } + break; + case SPEEX_GET_INNOV: + { + int i; + float *e = (float*)ptr; + for (i=0;ifull_frame_size;i++) + e[i]=0; + for (i=0;iframe_size;i++) + e[2*i]=2*st->exc[i]; + } + break; + case SPEEX_GET_DTX_STATUS: + speex_decoder_ctl(st->st_low, SPEEX_GET_DTX_STATUS, ptr); + break; + default: + speex_warning_int("Unknown nb_ctl request: ", request); + return -1; + } + return 0; +} diff --git a/Code/BF2/External/speex-1.0.5/libspeex/sb_celp.h b/Code/BF2/External/speex-1.0.5/libspeex/sb_celp.h new file mode 100644 index 000000000..385eaf255 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/sb_celp.h @@ -0,0 +1,167 @@ +/* Copyright (C) 2002 Jean-Marc Valin */ +/** + @file sb_celp.h + @brief Sub-band CELP mode used for wideband encoding +*/ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +*/ + +#ifndef SB_CELP_H +#define SB_CELP_H + +#include "modes.h" +#include +#include "nb_celp.h" + +/**Structure representing the full state of the sub-band encoder*/ +typedef struct SBEncState { + SpeexMode *mode; /**< Pointer to the mode (containing for vtable info) */ + void *st_low; /**< State of the low-band (narrowband) encoder */ + int full_frame_size; /**< Length of full-band frames*/ + int frame_size; /**< Length of high-band frames*/ + int subframeSize; /**< Length of high-band sub-frames*/ + int nbSubframes; /**< Number of high-band sub-frames*/ + int windowSize; /**< Length of high-band LPC window*/ + int lpcSize; /**< Order of high-band LPC analysis */ + int bufSize; /**< Buffer size */ + int first; /**< First frame? */ + float lag_factor; /**< Lag-windowing control parameter */ + float lpc_floor; /**< Controls LPC analysis noise floor */ + float gamma1; /**< Perceptual weighting coef 1 */ + float gamma2; /**< Perceptual weighting coef 2 */ + + char *stack; /**< Temporary allocation stack */ + float *x0d, *x1d; /**< QMF filter signals*/ + float *high; /**< High-band signal (buffer) */ + float *y0, *y1; /**< QMF synthesis signals */ + float *h0_mem, *h1_mem, *g0_mem, *g1_mem; /**< QMF memories */ + + float *excBuf; /**< High-band excitation */ + float *exc; /**< High-band excitation (for QMF only)*/ + float *buf; /**< Temporary buffer */ + float *res; /**< Zero-input response (ringing) */ + float *sw; /**< Perceptually weighted signal */ + float *target; /**< Weighted target signal (analysis by synthesis) */ + float *window; /**< LPC analysis window */ + float *lagWindow; /**< Auto-correlation window */ + float *autocorr; /**< Auto-correlation (for LPC analysis) */ + float *rc; /**< Reflection coefficients (unused) */ + float *lpc; /**< LPC coefficients */ + float *lsp; /**< LSP coefficients */ + float *qlsp; /**< Quantized LSPs */ + float *old_lsp; /**< LSPs of previous frame */ + float *old_qlsp; /**< Quantized LSPs of previous frame */ + float *interp_lsp; /**< Interpolated LSPs for current sub-frame */ + float *interp_qlsp; /**< Interpolated quantized LSPs for current sub-frame */ + float *interp_lpc; /**< Interpolated LPCs for current sub-frame */ + float *interp_qlpc; /**< Interpolated quantized LPCs for current sub-frame */ + float *bw_lpc1; /**< Bandwidth-expanded version of LPCs (#1) */ + float *bw_lpc2; /**< Bandwidth-expanded version of LPCs (#2) */ + + float *mem_sp; /**< Synthesis signal memory */ + float *mem_sp2; + float *mem_sw; /**< Perceptual signal memory */ + float *pi_gain; + + float vbr_quality; /**< Quality setting for VBR encoding */ + int vbr_enabled; /**< 1 for enabling VBR, 0 otherwise */ + int abr_enabled; /**< ABR setting (in bps), 0 if off */ + float abr_drift; + float abr_drift2; + float abr_count; + int vad_enabled; /**< 1 for enabling VAD, 0 otherwise */ + float relative_quality; + + SpeexSubmode **submodes; + int submodeID; + int submodeSelect; + int complexity; + int sampling_rate; + +} SBEncState; + + +/**Structure representing the full state of the sub-band decoder*/ +typedef struct SBDecState { + SpeexMode *mode; /**< Pointer to the mode (containing for vtable info) */ + void *st_low; /**< State of the low-band (narrowband) encoder */ + int full_frame_size; + int frame_size; + int subframeSize; + int nbSubframes; + int lpcSize; + int first; + int sampling_rate; + int lpc_enh_enabled; + + char *stack; + float *x0d, *x1d; + float *high; + float *y0, *y1; + float *h0_mem, *h1_mem, *g0_mem, *g1_mem; + + float *exc; + float *qlsp; + float *old_qlsp; + float *interp_qlsp; + float *interp_qlpc; + + float *mem_sp; + float *pi_gain; + + SpeexSubmode **submodes; + int submodeID; +} SBDecState; + + +/**Initializes encoder state*/ +void *sb_encoder_init(SpeexMode *m); + +/**De-allocates encoder state resources*/ +void sb_encoder_destroy(void *state); + +/**Encodes one frame*/ +int sb_encode(void *state, float *in, SpeexBits *bits); + + +/**Initializes decoder state*/ +void *sb_decoder_init(SpeexMode *m); + +/**De-allocates decoder state resources*/ +void sb_decoder_destroy(void *state); + +/**Decodes one frame*/ +int sb_decode(void *state, SpeexBits *bits, float *out); + +int sb_encoder_ctl(void *state, int request, void *ptr); + +int sb_decoder_ctl(void *state, int request, void *ptr); + +#endif diff --git a/Code/BF2/External/speex-1.0.5/libspeex/speex_callbacks.c b/Code/BF2/External/speex-1.0.5/libspeex/speex_callbacks.c new file mode 100644 index 000000000..fb234eb64 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/speex_callbacks.c @@ -0,0 +1,135 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File speex_callbacks.c + Callback handling and in-band signalling + + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +*/ + +#include +#include "misc.h" + +int speex_inband_handler(SpeexBits *bits, SpeexCallback *callback_list, void *state) +{ + int id; + SpeexCallback *callback; + /*speex_bits_advance(bits, 5);*/ + id=speex_bits_unpack_unsigned(bits, 4); + callback = callback_list+id; + + if (callback->func) + { + return callback->func(bits, state, callback->data); + } else + /*If callback is not registered, skip the right number of bits*/ + { + int adv; + if (id<2) + adv = 1; + else if (id<8) + adv = 4; + else if (id<10) + adv = 8; + else if (id<12) + adv = 16; + else if (id<14) + adv = 32; + else + adv = 64; + speex_bits_advance(bits, adv); + } + return 0; +} + +int speex_std_mode_request_handler(SpeexBits *bits, void *state, void *data) +{ + int m; + m = speex_bits_unpack_unsigned(bits, 4); + speex_encoder_ctl(data, SPEEX_SET_MODE, &m); + return 0; +} + +int speex_std_low_mode_request_handler(SpeexBits *bits, void *state, void *data) +{ + int m; + m = speex_bits_unpack_unsigned(bits, 4); + speex_encoder_ctl(data, SPEEX_SET_LOW_MODE, &m); + return 0; +} + +int speex_std_high_mode_request_handler(SpeexBits *bits, void *state, void *data) +{ + int m; + m = speex_bits_unpack_unsigned(bits, 4); + speex_encoder_ctl(data, SPEEX_SET_HIGH_MODE, &m); + return 0; +} + +int speex_std_vbr_request_handler(SpeexBits *bits, void *state, void *data) +{ + int vbr; + vbr = speex_bits_unpack_unsigned(bits, 1); + speex_encoder_ctl(data, SPEEX_SET_VBR, &vbr); + return 0; +} + +int speex_std_enh_request_handler(SpeexBits *bits, void *state, void *data) +{ + int enh; + enh = speex_bits_unpack_unsigned(bits, 1); + speex_decoder_ctl(data, SPEEX_SET_ENH, &enh); + return 0; +} + +int speex_std_vbr_quality_request_handler(SpeexBits *bits, void *state, void *data) +{ + int qual; + qual = speex_bits_unpack_unsigned(bits, 4); + speex_encoder_ctl(data, SPEEX_SET_VBR_QUALITY, &qual); + return 0; +} + + +int speex_std_char_handler(SpeexBits *bits, void *state, void *data) +{ + unsigned char ch; + ch = speex_bits_unpack_unsigned(bits, 8); + _speex_putc(ch, data); + return 0; +} + + + +/* Default handler for user callbacks: skip it */ +int speex_default_user_handler(SpeexBits *bits, void *state, void *data) +{ + int req_size = speex_bits_unpack_unsigned(bits, 4); + speex_bits_advance(bits, 5+8*req_size); + return 0; +} diff --git a/Code/BF2/External/speex-1.0.5/libspeex/speex_header.c b/Code/BF2/External/speex-1.0.5/libspeex/speex_header.c new file mode 100644 index 000000000..6b0874e04 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/speex_header.c @@ -0,0 +1,162 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: speex_header.c + Describes the Speex header + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +*/ + +#include +#include "misc.h" +#include + +#ifndef NULL +#define NULL 0 +#endif + +#define ENDIAN_SWITCH(x) {x=le_int(x);} + + +/* +typedef struct SpeexHeader { + char speex_string[8]; + char speex_version[SPEEX_HEADER_VERSION_LENGTH]; + int speex_version_id; + int header_size; + int rate; + int mode; + int mode_bitstream_version; + int nb_channels; + int bitrate; + int frame_size; + int vbr; + int frames_per_packet; + int extra_headers; + int reserved1; + int reserved2; +} SpeexHeader; +*/ + +void speex_init_header(SpeexHeader *header, int rate, int nb_channels, SpeexMode *m) +{ + int i; + char *h="Speex "; + /* + strncpy(header->speex_string, "Speex ", 8); + strncpy(header->speex_version, SPEEX_VERSION, SPEEX_HEADER_VERSION_LENGTH-1); + header->speex_version[SPEEX_HEADER_VERSION_LENGTH-1]=0; + */ + for (i=0;i<8;i++) + header->speex_string[i]=h[i]; + for (i=0;ispeex_version[i]=SPEEX_VERSION[i]; + for (;ispeex_version[i]=0; + + header->speex_version_id = 1; + header->header_size = sizeof(SpeexHeader); + + header->rate = rate; + header->mode = m->modeID; + header->mode_bitstream_version = m->bitstream_version; + if (m->modeID<0) + speex_warning("This mode is meant to be used alone"); + header->nb_channels = nb_channels; + header->bitrate = -1; + speex_mode_query(m, SPEEX_MODE_FRAME_SIZE, &header->frame_size); + header->vbr = 0; + + header->frames_per_packet = 0; + header->extra_headers = 0; + header->reserved1 = 0; + header->reserved2 = 0; +} + +char *speex_header_to_packet(SpeexHeader *header, int *size) +{ + SpeexHeader *le_header; + le_header = (SpeexHeader*)speex_alloc(sizeof(SpeexHeader)); + + speex_move(le_header, header, sizeof(SpeexHeader)); + + /*Make sure everything is now little-endian*/ + ENDIAN_SWITCH(le_header->speex_version_id); + ENDIAN_SWITCH(le_header->header_size); + ENDIAN_SWITCH(le_header->rate); + ENDIAN_SWITCH(le_header->mode); + ENDIAN_SWITCH(le_header->mode_bitstream_version); + ENDIAN_SWITCH(le_header->nb_channels); + ENDIAN_SWITCH(le_header->bitrate); + ENDIAN_SWITCH(le_header->frame_size); + ENDIAN_SWITCH(le_header->vbr); + ENDIAN_SWITCH(le_header->frames_per_packet); + ENDIAN_SWITCH(le_header->extra_headers); + + *size = sizeof(SpeexHeader); + return (char *)le_header; +} + +SpeexHeader *speex_packet_to_header(char *packet, int size) +{ + int i; + SpeexHeader *le_header; + char *h = "Speex "; + for (i=0;i<8;i++) + if (packet[i]!=h[i]) + { + speex_warning ("This doesn't look like a Speex file"); + return NULL; + } + + /*FIXME: Do we allow larger headers?*/ + if (size < sizeof(SpeexHeader)) + { + speex_warning("Speex header too small"); + return NULL; + } + + le_header = (SpeexHeader*)speex_alloc(sizeof(SpeexHeader)); + + speex_move(le_header, packet, sizeof(SpeexHeader)); + + /*Make sure everything is converted correctly from little-endian*/ + ENDIAN_SWITCH(le_header->speex_version_id); + ENDIAN_SWITCH(le_header->header_size); + ENDIAN_SWITCH(le_header->rate); + ENDIAN_SWITCH(le_header->mode); + ENDIAN_SWITCH(le_header->mode_bitstream_version); + ENDIAN_SWITCH(le_header->nb_channels); + ENDIAN_SWITCH(le_header->bitrate); + ENDIAN_SWITCH(le_header->frame_size); + ENDIAN_SWITCH(le_header->vbr); + ENDIAN_SWITCH(le_header->frames_per_packet); + ENDIAN_SWITCH(le_header->extra_headers); + + return le_header; + +} diff --git a/Code/BF2/External/speex-1.0.5/libspeex/stack_alloc.h b/Code/BF2/External/speex-1.0.5/libspeex/stack_alloc.h new file mode 100644 index 000000000..2390b69dc --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/stack_alloc.h @@ -0,0 +1,62 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: stack_alloc.h + + Temporary memory allocation on stack + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef STACK_ALLOC_H +#define STACK_ALLOC_H + +#if 0 + +/*Aligns the stack to a 'size' boundary */ +#define ALIGN(stack, size) (stack=(void*)((((int)stack)+((size)-1)) & (-(size)))) +/*Aligns the stack to a 'size' boundary minus k */ +#define ALIGN_1(stack, size, k) (stack=(void*)(((((int)stack)+((size)-1+(k))) & (-(size)))-(k))) + +/* Allocates 'size' elements of type 'type' on the stack */ +#define PUSH(stack, size, type) (ALIGN(stack,sizeof(type)),stack=(void*)(((int)stack)+((size)*sizeof(type))),(type*)(((int)stack)-((size)*sizeof(type)))) + + +#else + +/*Aligns the stack to a 'size' boundary */ +#define ALIGN(stack, size) ((stack) += ((size) - (int)(stack)) & ((size) - 1)) + +/* Allocates 'size' elements of type 'type' on the stack */ +#define PUSH(stack, size, type) (ALIGN((stack),sizeof(type)),(stack)+=((size)*sizeof(type)),(type*)((stack)-((size)*sizeof(type)))) + +/* Allocates a struct stack */ +#define PUSHS(stack, type) (ALIGN((stack),sizeof(long)),(stack)+=(sizeof(type)),(type*)((stack)-(sizeof(type)))) + + +#endif + +#endif diff --git a/Code/BF2/External/speex-1.0.5/libspeex/stereo.c b/Code/BF2/External/speex-1.0.5/libspeex/stereo.c new file mode 100644 index 000000000..baaccd9a9 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/stereo.c @@ -0,0 +1,151 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: stereo.c + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include +#include +#include "vq.h" +#include + +#define MAX_IN_SAMPLES 640 + +/*float e_ratio_quant[4] = {1, 1.26, 1.587, 2};*/ +static float e_ratio_quant[4] = {.25, .315, .397, .5}; + +void speex_encode_stereo(float *data, int frame_size, SpeexBits *bits) +{ + int i, tmp; + float e_left=0, e_right=0, e_tot=0; + float balance, e_ratio; + for (i=0;i0) + speex_bits_pack(bits, 0, 1); + else + speex_bits_pack(bits, 1, 1); + balance=floor(.5+fabs(balance)); + if (balance>30) + balance=31; + + speex_bits_pack(bits, (int)balance, 5); + + /*Quantize energy ratio*/ + tmp=vq_index(&e_ratio, e_ratio_quant, 1, 4); + speex_bits_pack(bits, tmp, 2); +} + +void speex_encode_stereo_int(short *data, int frame_size, SpeexBits *bits) +{ + int i; + /* FIXME: Do some dynamic allocation here */ + float float_data[2*MAX_IN_SAMPLES]; + for (i=0;i<2*frame_size;i++) + float_data[i] = data[i]; + speex_encode_stereo(float_data, frame_size, bits); +} + +void speex_decode_stereo(float *data, int frame_size, SpeexStereoState *stereo) +{ + float balance, e_ratio; + int i; + float e_tot=0, e_left, e_right, e_sum; + + balance=stereo->balance; + e_ratio=stereo->e_ratio; + for (i=frame_size-1;i>=0;i--) + { + e_tot += data[i]*data[i]; + } + e_sum=e_tot/e_ratio; + e_left = e_sum*balance / (1+balance); + e_right = e_sum-e_left; + + e_left = sqrt(e_left/(e_tot+.01)); + e_right = sqrt(e_right/(e_tot+.01)); + + for (i=frame_size-1;i>=0;i--) + { + float ftmp=data[i]; + stereo->smooth_left = .98*stereo->smooth_left + .02*e_left; + stereo->smooth_right = .98*stereo->smooth_right + .02*e_right; + data[2*i] = stereo->smooth_left*ftmp; + data[2*i+1] = stereo->smooth_right*ftmp; + } +} + +void speex_decode_stereo_int(short *data, int frame_size, SpeexStereoState *stereo) +{ + int i; + /* FIXME: Do some dynamic allocation here */ + float float_data[2*MAX_IN_SAMPLES]; + speex_decode_stereo(float_data, frame_size, stereo); + for (i=0;i32767.f) + data[i] = 32767; + else if (float_data[i]<-32768.f) + data[i] = -32768; + else + data[i] = (short)floor(.5+float_data[i]); + } +} + +int speex_std_stereo_request_handler(SpeexBits *bits, void *state, void *data) +{ + SpeexStereoState *stereo; + float sign=1; + int tmp; + + stereo = (SpeexStereoState*)data; + if (speex_bits_unpack_unsigned(bits, 1)) + sign=-1; + tmp = speex_bits_unpack_unsigned(bits, 5); + stereo->balance = exp(sign*.25*tmp); + + tmp = speex_bits_unpack_unsigned(bits, 2); + stereo->e_ratio = e_ratio_quant[tmp]; + + return 0; +} diff --git a/Code/BF2/External/speex-1.0.5/libspeex/testenc.c b/Code/BF2/External/speex-1.0.5/libspeex/testenc.c new file mode 100644 index 000000000..e50192b06 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/testenc.c @@ -0,0 +1,127 @@ +#include +#include +#include +#include + +#define FRAME_SIZE 160 +#include +int main(int argc, char **argv) +{ + char *inFile, *outFile, *bitsFile; + FILE *fin, *fout, *fbits=NULL; + short in[FRAME_SIZE]; + float input[FRAME_SIZE], bak[FRAME_SIZE], bak2[FRAME_SIZE]; + char cbits[200]; + int nbBits; + int i; + void *st; + void *dec; + SpeexBits bits; + int tmp; + int bitCount=0; + SpeexCallback callback; + + for (i=0;i32000) + input[i]=32000; + else if (input[i]<-32000) + input[i]=-32000; + } + speex_bits_reset(&bits); + for (i=0;i +#include +#include + +#define FRAME_SIZE 640 +#include +int main(int argc, char **argv) +{ + char *inFile, *outFile, *bitsFile; + FILE *fin, *fout, *fbits=NULL; + short in[FRAME_SIZE]; + float input[FRAME_SIZE], bak[FRAME_SIZE], bak2[FRAME_SIZE]; + char cbits[200]; + int nbBits; + int i; + void *st; + void *dec; + SpeexBits bits; + int tmp; + int bitCount=0; + + for (i=0;i32000) + input[i]=32000; + else if (input[i]<-32000) + input[i]=-32000; + } + speex_bits_reset(&bits); + for (i=0;i +#include +#include + +#define FRAME_SIZE 320 +#include +int main(int argc, char **argv) +{ + char *inFile, *outFile, *bitsFile; + FILE *fin, *fout, *fbits=NULL; + short in[FRAME_SIZE]; + float input[FRAME_SIZE], bak[FRAME_SIZE], bak2[FRAME_SIZE]; + char cbits[200]; + int nbBits; + int i; + void *st; + void *dec; + SpeexBits bits; + int tmp; + int bitCount=0; + + for (i=0;i32000) + input[i]=32000; + else if (input[i]<-32000) + input[i]=-32000; + } + speex_bits_reset(&bits); + for (i=0;i + + +#define sqr(x) ((x)*(x)) + +#define MIN_ENERGY 6000 +#define NOISE_POW .3 + + +float vbr_nb_thresh[9][11]={ + {-1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0}, /* CNG */ + { 3.5, 2.5, 2.0, 1.2, 0.5, 0.0, -0.5, -0.7, -0.8, -0.9, -1.0}, /* 2 kbps */ + {10.0, 6.5, 5.2, 4.5, 3.9, 3.5, 3.0, 2.5, 2.3, 1.8, 1.0}, /* 6 kbps */ + {11.0, 8.8, 7.5, 6.5, 5.0, 3.9, 3.9, 3.9, 3.5, 3.0, 1.0}, /* 8 kbps */ + {11.0, 11.0, 9.9, 9.0, 8.0, 7.0, 6.5, 6.0, 5.0, 4.0, 2.0}, /* 11 kbps */ + {11.0, 11.0, 11.0, 11.0, 9.5, 9.0, 8.0, 7.0, 6.5, 5.0, 3.0}, /* 15 kbps */ + {11.0, 11.0, 11.0, 11.0, 11.0, 11.0, 9.5, 8.5, 8.0, 6.5, 4.0}, /* 18 kbps */ + {11.0, 11.0, 11.0, 11.0, 11.0, 11.0, 11.0, 11.0, 9.8, 7.5, 5.5}, /* 24 kbps */ + { 8.0, 5.0, 3.7, 3.0, 2.5, 2.0, 1.8, 1.5, 1.0, 0.0, 0.0} /* 4 kbps */ +}; + + +float vbr_hb_thresh[5][11]={ + {-1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0}, /* silence */ + {-1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0}, /* 2 kbps */ + {11.0, 11.0, 9.5, 8.5, 7.5, 6.0, 5.0, 3.9, 3.0, 2.0, 1.0}, /* 6 kbps */ + {11.0, 11.0, 11.0, 11.0, 11.0, 9.5, 8.7, 7.8, 7.0, 6.5, 4.0}, /* 10 kbps */ + {11.0, 11.0, 11.0, 11.0, 11.0, 11.0, 11.0, 11.0, 9.8, 7.5, 5.5} /* 18 kbps */ +}; + +float vbr_uhb_thresh[2][11]={ + {-1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0}, /* silence */ + { 3.9, 2.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0} /* 2 kbps */ +}; + +void vbr_init(VBRState *vbr) +{ + int i; + + vbr->average_energy=0; + vbr->last_energy=1; + vbr->accum_sum=0; + vbr->energy_alpha=.1; + vbr->soft_pitch=0; + vbr->last_pitch_coef=0; + vbr->last_quality=0; + + vbr->noise_accum = .05*pow(MIN_ENERGY, NOISE_POW); + vbr->noise_accum_count=.05; + vbr->noise_level=vbr->noise_accum/vbr->noise_accum_count; + vbr->consec_noise=0; + + + for (i=0;ilast_log_energy[i] = log(MIN_ENERGY); +} + + +/* + This function should analyse the signal and decide how critical the + coding error will be perceptually. The following factors should be + taken into account: + + -Attacks (positive energy derivative) should be coded with more bits + + -Stationary voiced segments should receive more bits + + -Segments with (very) low absolute energy should receive less bits (maybe + only shaped noise?) + + -DTX for near-zero energy? + + -Stationary fricative segments should have less bits + + -Temporal masking: when energy slope is decreasing, decrease the bit-rate + + -Decrease bit-rate for males (low pitch)? + + -(wideband only) less bits in the high-band when signal is very + non-stationary (harder to notice high-frequency noise)??? + +*/ + +float vbr_analysis(VBRState *vbr, float *sig, int len, int pitch, float pitch_coef) +{ + int i; + float ener=0, ener1=0, ener2=0; + float qual=7; + int va; + float log_energy; + float non_st=0; + float voicing; + float pow_ener; + + for (i=0;i>1;i++) + ener1 += sig[i]*sig[i]; + + for (i=len>>1;ilast_log_energy[i]); + non_st = non_st/(30*VBR_MEMORY_SIZE); + if (non_st>1) + non_st=1; + + voicing = 3*(pitch_coef-.4)*fabs(pitch_coef-.4); + vbr->average_energy = (1-vbr->energy_alpha)*vbr->average_energy + vbr->energy_alpha*ener; + vbr->noise_level=vbr->noise_accum/vbr->noise_accum_count; + pow_ener = pow(ener,NOISE_POW); + if (vbr->noise_accum_count<.06 && ener>MIN_ENERGY) + vbr->noise_accum = .05*pow_ener; + + if ((voicing<.3 && non_st < .2 && pow_ener < 1.2*vbr->noise_level) + || (voicing<.3 && non_st < .05 && pow_ener < 1.5*vbr->noise_level) + || (voicing<.4 && non_st < .05 && pow_ener < 1.2*vbr->noise_level) + || (voicing<0 && non_st < .05)) + { + float tmp; + va = 0; + vbr->consec_noise++; + if (pow_ener > 3*vbr->noise_level) + tmp = 3*vbr->noise_level; + else + tmp = pow_ener; + if (vbr->consec_noise>=4) + { + vbr->noise_accum = .95*vbr->noise_accum + .05*tmp; + vbr->noise_accum_count = .95*vbr->noise_accum_count + .05; + } + } else { + va = 1; + vbr->consec_noise=0; + } + + if (pow_ener < vbr->noise_level && ener>MIN_ENERGY) + { + vbr->noise_accum = .95*vbr->noise_accum + .05*pow_ener; + vbr->noise_accum_count = .95*vbr->noise_accum_count + .05; + } + + /* Checking for very low absolute energy */ + if (ener < 30000) + { + qual -= .7; + if (ener < 10000) + qual-=.7; + if (ener < 3000) + qual-=.7; + } else { + float short_diff, long_diff; + short_diff = log((ener+1)/(1+vbr->last_energy)); + long_diff = log((ener+1)/(1+vbr->average_energy)); + /*fprintf (stderr, "%f %f\n", short_diff, long_diff);*/ + + if (long_diff<-5) + long_diff=-5; + if (long_diff>2) + long_diff=2; + + if (long_diff>0) + qual += .6*long_diff; + if (long_diff<0) + qual += .5*long_diff; + if (short_diff>0) + { + if (short_diff>5) + short_diff=5; + qual += .5*short_diff; + } + /* Checking for energy increases */ + if (ener2 > 1.6*ener1) + qual += .5; + } + vbr->last_energy = ener; + vbr->soft_pitch = .6*vbr->soft_pitch + .4*pitch_coef; + qual += 2.2*((pitch_coef-.4) + (vbr->soft_pitch-.4)); + + if (qual < vbr->last_quality) + qual = .5*qual + .5*vbr->last_quality; + if (qual<4) + qual=4; + if (qual>10) + qual=10; + + /* + if (vbr->consec_noise>=2) + qual-=1.3; + if (vbr->consec_noise>=5) + qual-=1.3; + if (vbr->consec_noise>=12) + qual-=1.3; + */ + if (vbr->consec_noise>=3) + qual=4; + + if (vbr->consec_noise) + qual -= 1.0 * (log(3.0 + vbr->consec_noise)-log(3)); + if (qual<0) + qual=0; + + if (ener<60000) + { + if (vbr->consec_noise>2) + qual-=0.5*(log(3.0 + vbr->consec_noise)-log(3)); + if (ener<10000&&vbr->consec_noise>2) + qual-=0.5*(log(3.0 + vbr->consec_noise)-log(3)); + if (qual<0) + qual=0; + qual += .3*log(ener/60000.0); + } + if (qual<-1) + qual=-1; + + /*printf ("%f %f %f %f %d\n", qual, voicing, non_st, pow_ener/(.01+vbr->noise_level), va);*/ + + vbr->last_pitch_coef = pitch_coef; + vbr->last_quality = qual; + + for (i=VBR_MEMORY_SIZE-1;i>0;i--) + vbr->last_log_energy[i] = vbr->last_log_energy[i-1]; + vbr->last_log_energy[0] = log_energy; + + /*printf ("VBR: %f %f %f %d %f\n", (float)(log_energy-log(vbr->average_energy+MIN_ENERGY)), non_st, voicing, va, vbr->noise_level);*/ + + return qual; +} + +void vbr_destroy(VBRState *vbr) +{ +} diff --git a/Code/BF2/External/speex-1.0.5/libspeex/vbr.h b/Code/BF2/External/speex-1.0.5/libspeex/vbr.h new file mode 100644 index 000000000..405b47f64 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/vbr.h @@ -0,0 +1,66 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: vbr.h + + VBR-related routines + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +*/ + + +#ifndef VBR_H +#define VBR_H + +#define VBR_MEMORY_SIZE 5 + +extern float vbr_nb_thresh[9][11]; +extern float vbr_hb_thresh[5][11]; +extern float vbr_uhb_thresh[2][11]; + +typedef struct VBRState { + float energy_alpha; + float average_energy; + float last_energy; + float last_log_energy[VBR_MEMORY_SIZE]; + float accum_sum; + float last_pitch_coef; + float soft_pitch; + float last_quality; + float noise_level; + float noise_accum; + float noise_accum_count; + int consec_noise; +} VBRState; + +void vbr_init(VBRState *vbr); + +float vbr_analysis(VBRState *vbr, float *sig, int len, int pitch, float pitch_coef); + +void vbr_destroy(VBRState *vbr); + +#endif diff --git a/Code/BF2/External/speex-1.0.5/libspeex/vq.c b/Code/BF2/External/speex-1.0.5/libspeex/vq.c new file mode 100644 index 000000000..ed36f7d27 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/vq.c @@ -0,0 +1,116 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: vq.c + Vector quantization + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include "vq.h" + +/*Finds the index of the entry in a codebook that best matches the input*/ +int vq_index(float *in, float *codebook, int len, int entries) +{ + int i,j; + float min_dist=0; + int best_index=0; + for (i=0;i= 1) && (k > used || dist < best_dist[k-1]); k--) + { + best_dist[k]=best_dist[k-1]; + nbest[k] = nbest[k-1]; + } + best_dist[k]=dist; + nbest[k]=i; + used++; + } + } +} + +/*Finds the indices of the n-best entries in a codebook with sign*/ +void vq_nbest_sign(float *in, float *codebook, int len, int entries, float *E, int N, int *nbest, float *best_dist) +{ + int i,j,k, sign, used; + used=0; + for (i=0;i0) + { + sign=1; + dist=-dist; + } else + { + sign=0; + } + dist += .5*E[i]; + if (i= 1) && (k > used || dist < best_dist[k-1]); k--) + { + best_dist[k]=best_dist[k-1]; + nbest[k] = nbest[k-1]; + } + best_dist[k]=dist; + nbest[k]=i; + used++; + if (sign) + nbest[k]+=entries; + } + } +} diff --git a/Code/BF2/External/speex-1.0.5/libspeex/vq.h b/Code/BF2/External/speex-1.0.5/libspeex/vq.h new file mode 100644 index 000000000..e82ba6c0a --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/libspeex/vq.h @@ -0,0 +1,42 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: vq.h + Vector quantization + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef VQ_H +#define VQ_H + +int vq_index(float *in, float *codebook, int len, int entries); + +void vq_nbest(float *in, float *codebook, int len, int entries, float *E, int N, int *nbest, float *best_dist); + +void vq_nbest_sign(float *in, float *codebook, int len, int entries, float *E, int N, int *nbest, float *best_dist); + +#endif diff --git a/Code/BF2/External/speex-1.0.5/ltmain.sh b/Code/BF2/External/speex-1.0.5/ltmain.sh new file mode 100644 index 000000000..ea9adbaf7 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/ltmain.sh @@ -0,0 +1,6430 @@ +# ltmain.sh - Provide generalized library-building support services. +# NOTE: Changing this file will not affect anything until you rerun configure. +# +# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004 +# Free Software Foundation, Inc. +# Originally by Gordon Matzigkeit , 1996 +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +# +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + +basename="s,^.*/,,g" + +# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh +# is ksh but when the shell is invoked as "sh" and the current value of +# the _XPG environment variable is not equal to 1 (one), the special +# positional parameter $0, within a function call, is the name of the +# function. +progpath="$0" + +# The name of this program: +progname=`echo "$progpath" | $SED $basename` +modename="$progname" + +# Global variables: +EXIT_SUCCESS=0 +EXIT_FAILURE=1 + +PROGRAM=ltmain.sh +PACKAGE=libtool +VERSION=1.5.6 +TIMESTAMP=" (1.1220.2.95 2004/04/11 05:50:42) Debian$Rev: 215 $" + + +# Check that we have a working $echo. +if test "X$1" = X--no-reexec; then + # Discard the --no-reexec flag, and continue. + shift +elif test "X$1" = X--fallback-echo; then + # Avoid inline document here, it may be left over + : +elif test "X`($echo '\t') 2>/dev/null`" = 'X\t'; then + # Yippee, $echo works! + : +else + # Restart under the correct shell, and then maybe $echo will work. + exec $SHELL "$progpath" --no-reexec ${1+"$@"} +fi + +if test "X$1" = X--fallback-echo; then + # used as fallback echo + shift + cat <&2 + $echo "Fatal configuration error. See the $PACKAGE docs for more information." 1>&2 + exit $EXIT_FAILURE +fi + +# Global variables. +mode=$default_mode +nonopt= +prev= +prevopt= +run= +show="$echo" +show_help= +execute_dlfiles= +lo2o="s/\\.lo\$/.${objext}/" +o2lo="s/\\.${objext}\$/.lo/" + +##################################### +# Shell function definitions: +# This seems to be the best place for them + +# func_win32_libid arg +# return the library type of file 'arg' +# +# Need a lot of goo to handle *both* DLLs and import libs +# Has to be a shell function in order to 'eat' the argument +# that is supplied when $file_magic_command is called. +func_win32_libid () { + win32_libid_type="unknown" + win32_fileres=`file -L $1 2>/dev/null` + case $win32_fileres in + *ar\ archive\ import\ library*) # definitely import + win32_libid_type="x86 archive import" + ;; + *ar\ archive*) # could be an import, or static + if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null | \ + $EGREP -e 'file format pe-i386(.*architecture: i386)?' >/dev/null ; then + win32_nmres=`eval $NM -f posix -A $1 | \ + sed -n -e '1,100{/ I /{x;/import/!{s/^/import/;h;p;};x;};}'` + if test "X$win32_nmres" = "Ximport" ; then + win32_libid_type="x86 archive import" + else + win32_libid_type="x86 archive static" + fi + fi + ;; + *DLL*) + win32_libid_type="x86 DLL" + ;; + *executable*) # but shell scripts are "executable" too... + case $win32_fileres in + *MS\ Windows\ PE\ Intel*) + win32_libid_type="x86 DLL" + ;; + esac + ;; + esac + $echo $win32_libid_type +} + + +# func_infer_tag arg +# Infer tagged configuration to use if any are available and +# if one wasn't chosen via the "--tag" command line option. +# Only attempt this if the compiler in the base compile +# command doesn't match the default compiler. +# arg is usually of the form 'gcc ...' +func_infer_tag () { + if test -n "$available_tags" && test -z "$tagname"; then + CC_quoted= + for arg in $CC; do + case $arg in + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") + arg="\"$arg\"" + ;; + esac + CC_quoted="$CC_quoted $arg" + done + case $@ in + # Blanks in the command may have been stripped by the calling shell, + # but not from the CC environment variable when configure was run. + " $CC "* | "$CC "* | " `$echo $CC` "* | "`$echo $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$echo $CC_quoted` "* | "`$echo $CC_quoted` "*) ;; + # Blanks at the start of $base_compile will cause this to fail + # if we don't check for them as well. + *) + for z in $available_tags; do + if grep "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then + # Evaluate the configuration. + eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`" + CC_quoted= + for arg in $CC; do + # Double-quote args containing other shell metacharacters. + case $arg in + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") + arg="\"$arg\"" + ;; + esac + CC_quoted="$CC_quoted $arg" + done + case "$@ " in + " $CC "* | "$CC "* | " `$echo $CC` "* | "`$echo $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$echo $CC_quoted` "* | "`$echo $CC_quoted` "*) + # The compiler in the base compile command matches + # the one in the tagged configuration. + # Assume this is the tagged configuration we want. + tagname=$z + break + ;; + esac + fi + done + # If $tagname still isn't set, then no tagged configuration + # was found and let the user know that the "--tag" command + # line option must be used. + if test -z "$tagname"; then + $echo "$modename: unable to infer tagged configuration" + $echo "$modename: specify a tag with \`--tag'" 1>&2 + exit $EXIT_FAILURE +# else +# $echo "$modename: using $tagname tagged configuration" + fi + ;; + esac + fi +} +# End of Shell function definitions +##################################### + +# Darwin sucks +eval std_shrext=\"$shrext_cmds\" + +# Parse our command line options once, thoroughly. +while test "$#" -gt 0 +do + arg="$1" + shift + + case $arg in + -*=*) optarg=`$echo "X$arg" | $Xsed -e 's/[-_a-zA-Z0-9]*=//'` ;; + *) optarg= ;; + esac + + # If the previous option needs an argument, assign it. + if test -n "$prev"; then + case $prev in + execute_dlfiles) + execute_dlfiles="$execute_dlfiles $arg" + ;; + tag) + tagname="$arg" + preserve_args="${preserve_args}=$arg" + + # Check whether tagname contains only valid characters + case $tagname in + *[!-_A-Za-z0-9,/]*) + $echo "$progname: invalid tag name: $tagname" 1>&2 + exit $EXIT_FAILURE + ;; + esac + + case $tagname in + CC) + # Don't test for the "default" C tag, as we know, it's there, but + # not specially marked. + ;; + *) + if grep "^# ### BEGIN LIBTOOL TAG CONFIG: $tagname$" < "$progpath" > /dev/null; then + taglist="$taglist $tagname" + # Evaluate the configuration. + eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$tagname'$/,/^# ### END LIBTOOL TAG CONFIG: '$tagname'$/p' < $progpath`" + else + $echo "$progname: ignoring unknown tag $tagname" 1>&2 + fi + ;; + esac + ;; + *) + eval "$prev=\$arg" + ;; + esac + + prev= + prevopt= + continue + fi + + # Have we seen a non-optional argument yet? + case $arg in + --help) + show_help=yes + ;; + + --version) + $echo "$PROGRAM (GNU $PACKAGE) $VERSION$TIMESTAMP" + $echo + $echo "Copyright (C) 2003 Free Software Foundation, Inc." + $echo "This is free software; see the source for copying conditions. There is NO" + $echo "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." + exit $EXIT_SUCCESS + ;; + + --config) + ${SED} -e '1,/^# ### BEGIN LIBTOOL CONFIG/d' -e '/^# ### END LIBTOOL CONFIG/,$d' $progpath + # Now print the configurations for the tags. + for tagname in $taglist; do + ${SED} -n -e "/^# ### BEGIN LIBTOOL TAG CONFIG: $tagname$/,/^# ### END LIBTOOL TAG CONFIG: $tagname$/p" < "$progpath" + done + exit $EXIT_SUCCESS + ;; + + --debug) + $echo "$progname: enabling shell trace mode" + set -x + preserve_args="$preserve_args $arg" + ;; + + --dry-run | -n) + run=: + ;; + + --features) + $echo "host: $host" + if test "$build_libtool_libs" = yes; then + $echo "enable shared libraries" + else + $echo "disable shared libraries" + fi + if test "$build_old_libs" = yes; then + $echo "enable static libraries" + else + $echo "disable static libraries" + fi + exit $EXIT_SUCCESS + ;; + + --finish) mode="finish" ;; + + --mode) prevopt="--mode" prev=mode ;; + --mode=*) mode="$optarg" ;; + + --preserve-dup-deps) duplicate_deps="yes" ;; + + --quiet | --silent) + show=: + preserve_args="$preserve_args $arg" + ;; + + --tag) prevopt="--tag" prev=tag ;; + --tag=*) + set tag "$optarg" ${1+"$@"} + shift + prev=tag + preserve_args="$preserve_args --tag" + ;; + + -dlopen) + prevopt="-dlopen" + prev=execute_dlfiles + ;; + + -*) + $echo "$modename: unrecognized option \`$arg'" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + ;; + + *) + nonopt="$arg" + break + ;; + esac +done + +if test -n "$prevopt"; then + $echo "$modename: option \`$prevopt' requires an argument" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE +fi + +# If this variable is set in any of the actions, the command in it +# will be execed at the end. This prevents here-documents from being +# left over by shells. +exec_cmd= + +if test -z "$show_help"; then + + # Infer the operation mode. + if test -z "$mode"; then + $echo "*** Warning: inferring the mode of operation is deprecated." 1>&2 + $echo "*** Future versions of Libtool will require -mode=MODE be specified." 1>&2 + case $nonopt in + *cc | cc* | *++ | gcc* | *-gcc* | g++* | xlc*) + mode=link + for arg + do + case $arg in + -c) + mode=compile + break + ;; + esac + done + ;; + *db | *dbx | *strace | *truss) + mode=execute + ;; + *install*|cp|mv) + mode=install + ;; + *rm) + mode=uninstall + ;; + *) + # If we have no mode, but dlfiles were specified, then do execute mode. + test -n "$execute_dlfiles" && mode=execute + + # Just use the default operation mode. + if test -z "$mode"; then + if test -n "$nonopt"; then + $echo "$modename: warning: cannot infer operation mode from \`$nonopt'" 1>&2 + else + $echo "$modename: warning: cannot infer operation mode without MODE-ARGS" 1>&2 + fi + fi + ;; + esac + fi + + # Only execute mode is allowed to have -dlopen flags. + if test -n "$execute_dlfiles" && test "$mode" != execute; then + $echo "$modename: unrecognized option \`-dlopen'" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + fi + + # Change the help message to a mode-specific one. + generic_help="$help" + help="Try \`$modename --help --mode=$mode' for more information." + + # These modes are in order of execution frequency so that they run quickly. + case $mode in + # libtool compile mode + compile) + modename="$modename: compile" + # Get the compilation command and the source file. + base_compile= + srcfile="$nonopt" # always keep a non-empty value in "srcfile" + suppress_opt=yes + suppress_output= + arg_mode=normal + libobj= + later= + + for arg + do + case "$arg_mode" in + arg ) + # do not "continue". Instead, add this to base_compile + lastarg="$arg" + arg_mode=normal + ;; + + target ) + libobj="$arg" + arg_mode=normal + continue + ;; + + normal ) + # Accept any command-line options. + case $arg in + -o) + if test -n "$libobj" ; then + $echo "$modename: you cannot specify \`-o' more than once" 1>&2 + exit $EXIT_FAILURE + fi + arg_mode=target + continue + ;; + + -static | -prefer-pic | -prefer-non-pic) + later="$later $arg" + continue + ;; + + -no-suppress) + suppress_opt=no + continue + ;; + + -Xcompiler) + arg_mode=arg # the next one goes into the "base_compile" arg list + continue # The current "srcfile" will either be retained or + ;; # replaced later. I would guess that would be a bug. + + -Wc,*) + args=`$echo "X$arg" | $Xsed -e "s/^-Wc,//"` + lastarg= + save_ifs="$IFS"; IFS=',' + for arg in $args; do + IFS="$save_ifs" + + # Double-quote args containing other shell metacharacters. + # Many Bourne shells cannot handle close brackets correctly + # in scan sets, so we specify it separately. + case $arg in + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") + arg="\"$arg\"" + ;; + esac + lastarg="$lastarg $arg" + done + IFS="$save_ifs" + lastarg=`$echo "X$lastarg" | $Xsed -e "s/^ //"` + + # Add the arguments to base_compile. + base_compile="$base_compile $lastarg" + continue + ;; + + * ) + # Accept the current argument as the source file. + # The previous "srcfile" becomes the current argument. + # + lastarg="$srcfile" + srcfile="$arg" + ;; + esac # case $arg + ;; + esac # case $arg_mode + + # Aesthetically quote the previous argument. + lastarg=`$echo "X$lastarg" | $Xsed -e "$sed_quote_subst"` + + case $lastarg in + # Double-quote args containing other shell metacharacters. + # Many Bourne shells cannot handle close brackets correctly + # in scan sets, so we specify it separately. + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") + lastarg="\"$lastarg\"" + ;; + esac + + base_compile="$base_compile $lastarg" + done # for arg + + case $arg_mode in + arg) + $echo "$modename: you must specify an argument for -Xcompile" + exit $EXIT_FAILURE + ;; + target) + $echo "$modename: you must specify a target with \`-o'" 1>&2 + exit $EXIT_FAILURE + ;; + *) + # Get the name of the library object. + [ -z "$libobj" ] && libobj=`$echo "X$srcfile" | $Xsed -e 's%^.*/%%'` + ;; + esac + + # Recognize several different file suffixes. + # If the user specifies -o file.o, it is replaced with file.lo + xform='[cCFSifmso]' + case $libobj in + *.ada) xform=ada ;; + *.adb) xform=adb ;; + *.ads) xform=ads ;; + *.asm) xform=asm ;; + *.c++) xform=c++ ;; + *.cc) xform=cc ;; + *.ii) xform=ii ;; + *.class) xform=class ;; + *.cpp) xform=cpp ;; + *.cxx) xform=cxx ;; + *.f90) xform=f90 ;; + *.for) xform=for ;; + *.java) xform=java ;; + esac + + libobj=`$echo "X$libobj" | $Xsed -e "s/\.$xform$/.lo/"` + + case $libobj in + *.lo) obj=`$echo "X$libobj" | $Xsed -e "$lo2o"` ;; + *) + $echo "$modename: cannot determine name of library object from \`$libobj'" 1>&2 + exit $EXIT_FAILURE + ;; + esac + + func_infer_tag $base_compile + + for arg in $later; do + case $arg in + -static) + build_old_libs=yes + continue + ;; + + -prefer-pic) + pic_mode=yes + continue + ;; + + -prefer-non-pic) + pic_mode=no + continue + ;; + esac + done + + objname=`$echo "X$obj" | $Xsed -e 's%^.*/%%'` + xdir=`$echo "X$obj" | $Xsed -e 's%/[^/]*$%%'` + if test "X$xdir" = "X$obj"; then + xdir= + else + xdir=$xdir/ + fi + lobj=${xdir}$objdir/$objname + + if test -z "$base_compile"; then + $echo "$modename: you must specify a compilation command" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + fi + + # Delete any leftover library objects. + if test "$build_old_libs" = yes; then + removelist="$obj $lobj $libobj ${libobj}T" + else + removelist="$lobj $libobj ${libobj}T" + fi + + $run $rm $removelist + trap "$run $rm $removelist; exit $EXIT_FAILURE" 1 2 15 + + # On Cygwin there's no "real" PIC flag so we must build both object types + case $host_os in + cygwin* | mingw* | pw32* | os2*) + pic_mode=default + ;; + esac + if test "$pic_mode" = no && test "$deplibs_check_method" != pass_all; then + # non-PIC code in shared libraries is not supported + pic_mode=default + fi + + # Calculate the filename of the output object if compiler does + # not support -o with -c + if test "$compiler_c_o" = no; then + output_obj=`$echo "X$srcfile" | $Xsed -e 's%^.*/%%' -e 's%\.[^.]*$%%'`.${objext} + lockfile="$output_obj.lock" + removelist="$removelist $output_obj $lockfile" + trap "$run $rm $removelist; exit $EXIT_FAILURE" 1 2 15 + else + output_obj= + need_locks=no + lockfile= + fi + + # Lock this critical section if it is needed + # We use this script file to make the link, it avoids creating a new file + if test "$need_locks" = yes; then + until $run ln "$progpath" "$lockfile" 2>/dev/null; do + $show "Waiting for $lockfile to be removed" + sleep 2 + done + elif test "$need_locks" = warn; then + if test -f "$lockfile"; then + $echo "\ +*** ERROR, $lockfile exists and contains: +`cat $lockfile 2>/dev/null` + +This indicates that another process is trying to use the same +temporary object file, and libtool could not work around it because +your compiler does not support \`-c' and \`-o' together. If you +repeat this compilation, it may succeed, by chance, but you had better +avoid parallel builds (make -j) in this platform, or get a better +compiler." + + $run $rm $removelist + exit $EXIT_FAILURE + fi + $echo $srcfile > "$lockfile" + fi + + if test -n "$fix_srcfile_path"; then + eval srcfile=\"$fix_srcfile_path\" + fi + + $run $rm "$libobj" "${libobj}T" + + # Create a libtool object file (analogous to a ".la" file), + # but don't create it if we're doing a dry run. + test -z "$run" && cat > ${libobj}T </dev/null`" != "X$srcfile"; then + $echo "\ +*** ERROR, $lockfile contains: +`cat $lockfile 2>/dev/null` + +but it should contain: +$srcfile + +This indicates that another process is trying to use the same +temporary object file, and libtool could not work around it because +your compiler does not support \`-c' and \`-o' together. If you +repeat this compilation, it may succeed, by chance, but you had better +avoid parallel builds (make -j) in this platform, or get a better +compiler." + + $run $rm $removelist + exit $EXIT_FAILURE + fi + + # Just move the object if needed, then go on to compile the next one + if test -n "$output_obj" && test "X$output_obj" != "X$lobj"; then + $show "$mv $output_obj $lobj" + if $run $mv $output_obj $lobj; then : + else + error=$? + $run $rm $removelist + exit $error + fi + fi + + # Append the name of the PIC object to the libtool object file. + test -z "$run" && cat >> ${libobj}T <> ${libobj}T </dev/null`" != "X$srcfile"; then + $echo "\ +*** ERROR, $lockfile contains: +`cat $lockfile 2>/dev/null` + +but it should contain: +$srcfile + +This indicates that another process is trying to use the same +temporary object file, and libtool could not work around it because +your compiler does not support \`-c' and \`-o' together. If you +repeat this compilation, it may succeed, by chance, but you had better +avoid parallel builds (make -j) in this platform, or get a better +compiler." + + $run $rm $removelist + exit $EXIT_FAILURE + fi + + # Just move the object if needed + if test -n "$output_obj" && test "X$output_obj" != "X$obj"; then + $show "$mv $output_obj $obj" + if $run $mv $output_obj $obj; then : + else + error=$? + $run $rm $removelist + exit $error + fi + fi + + # Append the name of the non-PIC object the libtool object file. + # Only append if the libtool object file exists. + test -z "$run" && cat >> ${libobj}T <> ${libobj}T <&2 + fi + if test -n "$link_static_flag"; then + dlopen_self=$dlopen_self_static + fi + else + if test -z "$pic_flag" && test -n "$link_static_flag"; then + dlopen_self=$dlopen_self_static + fi + fi + build_libtool_libs=no + build_old_libs=yes + prefer_static_libs=yes + break + ;; + esac + done + + # See if our shared archives depend on static archives. + test -n "$old_archive_from_new_cmds" && build_old_libs=yes + + # Go through the arguments, transforming them on the way. + while test "$#" -gt 0; do + arg="$1" + shift + case $arg in + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") + qarg=\"`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`\" ### testsuite: skip nested quoting test + ;; + *) qarg=$arg ;; + esac + libtool_args="$libtool_args $qarg" + + # If the previous option needs an argument, assign it. + if test -n "$prev"; then + case $prev in + output) + compile_command="$compile_command @OUTPUT@" + finalize_command="$finalize_command @OUTPUT@" + ;; + esac + + case $prev in + dlfiles|dlprefiles) + if test "$preload" = no; then + # Add the symbol object into the linking commands. + compile_command="$compile_command @SYMFILE@" + finalize_command="$finalize_command @SYMFILE@" + preload=yes + fi + case $arg in + *.la | *.lo) ;; # We handle these cases below. + force) + if test "$dlself" = no; then + dlself=needless + export_dynamic=yes + fi + prev= + continue + ;; + self) + if test "$prev" = dlprefiles; then + dlself=yes + elif test "$prev" = dlfiles && test "$dlopen_self" != yes; then + dlself=yes + else + dlself=needless + export_dynamic=yes + fi + prev= + continue + ;; + *) + if test "$prev" = dlfiles; then + dlfiles="$dlfiles $arg" + else + dlprefiles="$dlprefiles $arg" + fi + prev= + continue + ;; + esac + ;; + expsyms) + export_symbols="$arg" + if test ! -f "$arg"; then + $echo "$modename: symbol file \`$arg' does not exist" + exit $EXIT_FAILURE + fi + prev= + continue + ;; + expsyms_regex) + export_symbols_regex="$arg" + prev= + continue + ;; + inst_prefix) + inst_prefix_dir="$arg" + prev= + continue + ;; + precious_regex) + precious_files_regex="$arg" + prev= + continue + ;; + release) + release="-$arg" + prev= + continue + ;; + objectlist) + if test -f "$arg"; then + save_arg=$arg + moreargs= + for fil in `cat $save_arg` + do +# moreargs="$moreargs $fil" + arg=$fil + # A libtool-controlled object. + + # Check to see that this really is a libtool object. + if (${SED} -e '2q' $arg | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then + pic_object= + non_pic_object= + + # Read the .lo file + # If there is no directory component, then add one. + case $arg in + */* | *\\*) . $arg ;; + *) . ./$arg ;; + esac + + if test -z "$pic_object" || \ + test -z "$non_pic_object" || + test "$pic_object" = none && \ + test "$non_pic_object" = none; then + $echo "$modename: cannot find name of object for \`$arg'" 1>&2 + exit $EXIT_FAILURE + fi + + # Extract subdirectory from the argument. + xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'` + if test "X$xdir" = "X$arg"; then + xdir= + else + xdir="$xdir/" + fi + + if test "$pic_object" != none; then + # Prepend the subdirectory the object is found in. + pic_object="$xdir$pic_object" + + if test "$prev" = dlfiles; then + if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then + dlfiles="$dlfiles $pic_object" + prev= + continue + else + # If libtool objects are unsupported, then we need to preload. + prev=dlprefiles + fi + fi + + # CHECK ME: I think I busted this. -Ossama + if test "$prev" = dlprefiles; then + # Preload the old-style object. + dlprefiles="$dlprefiles $pic_object" + prev= + fi + + # A PIC object. + libobjs="$libobjs $pic_object" + arg="$pic_object" + fi + + # Non-PIC object. + if test "$non_pic_object" != none; then + # Prepend the subdirectory the object is found in. + non_pic_object="$xdir$non_pic_object" + + # A standard non-PIC object + non_pic_objects="$non_pic_objects $non_pic_object" + if test -z "$pic_object" || test "$pic_object" = none ; then + arg="$non_pic_object" + fi + fi + else + # Only an error if not doing a dry-run. + if test -z "$run"; then + $echo "$modename: \`$arg' is not a valid libtool object" 1>&2 + exit $EXIT_FAILURE + else + # Dry-run case. + + # Extract subdirectory from the argument. + xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'` + if test "X$xdir" = "X$arg"; then + xdir= + else + xdir="$xdir/" + fi + + pic_object=`$echo "X${xdir}${objdir}/${arg}" | $Xsed -e "$lo2o"` + non_pic_object=`$echo "X${xdir}${arg}" | $Xsed -e "$lo2o"` + libobjs="$libobjs $pic_object" + non_pic_objects="$non_pic_objects $non_pic_object" + fi + fi + done + else + $echo "$modename: link input file \`$save_arg' does not exist" + exit $EXIT_FAILURE + fi + arg=$save_arg + prev= + continue + ;; + rpath | xrpath) + # We need an absolute path. + case $arg in + [\\/]* | [A-Za-z]:[\\/]*) ;; + *) + $echo "$modename: only absolute run-paths are allowed" 1>&2 + exit $EXIT_FAILURE + ;; + esac + if test "$prev" = rpath; then + case "$rpath " in + *" $arg "*) ;; + *) rpath="$rpath $arg" ;; + esac + else + case "$xrpath " in + *" $arg "*) ;; + *) xrpath="$xrpath $arg" ;; + esac + fi + prev= + continue + ;; + xcompiler) + compiler_flags="$compiler_flags $qarg" + prev= + compile_command="$compile_command $qarg" + finalize_command="$finalize_command $qarg" + continue + ;; + xlinker) + linker_flags="$linker_flags $qarg" + compiler_flags="$compiler_flags $wl$qarg" + prev= + compile_command="$compile_command $wl$qarg" + finalize_command="$finalize_command $wl$qarg" + continue + ;; + xcclinker) + linker_flags="$linker_flags $qarg" + compiler_flags="$compiler_flags $qarg" + prev= + compile_command="$compile_command $qarg" + finalize_command="$finalize_command $qarg" + continue + ;; + shrext) + shrext_cmds="$arg" + prev= + continue + ;; + *) + eval "$prev=\"\$arg\"" + prev= + continue + ;; + esac + fi # test -n "$prev" + + prevarg="$arg" + + case $arg in + -all-static) + if test -n "$link_static_flag"; then + compile_command="$compile_command $link_static_flag" + finalize_command="$finalize_command $link_static_flag" + fi + continue + ;; + + -allow-undefined) + # FIXME: remove this flag sometime in the future. + $echo "$modename: \`-allow-undefined' is deprecated because it is the default" 1>&2 + continue + ;; + + -avoid-version) + avoid_version=yes + continue + ;; + + -dlopen) + prev=dlfiles + continue + ;; + + -dlpreopen) + prev=dlprefiles + continue + ;; + + -export-dynamic) + export_dynamic=yes + continue + ;; + + -export-symbols | -export-symbols-regex) + if test -n "$export_symbols" || test -n "$export_symbols_regex"; then + $echo "$modename: more than one -exported-symbols argument is not allowed" + exit $EXIT_FAILURE + fi + if test "X$arg" = "X-export-symbols"; then + prev=expsyms + else + prev=expsyms_regex + fi + continue + ;; + + -inst-prefix-dir) + prev=inst_prefix + continue + ;; + + # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:* + # so, if we see these flags be careful not to treat them like -L + -L[A-Z][A-Z]*:*) + case $with_gcc/$host in + no/*-*-irix* | /*-*-irix*) + compile_command="$compile_command $arg" + finalize_command="$finalize_command $arg" + ;; + esac + continue + ;; + + -L*) + dir=`$echo "X$arg" | $Xsed -e 's/^-L//'` + # We need an absolute path. + case $dir in + [\\/]* | [A-Za-z]:[\\/]*) ;; + *) + absdir=`cd "$dir" && pwd` + if test -z "$absdir"; then + $echo "$modename: cannot determine absolute directory name of \`$dir'" 1>&2 + exit $EXIT_FAILURE + fi + dir="$absdir" + ;; + esac + case "$deplibs " in + *" -L$dir "*) ;; + *) + deplibs="$deplibs -L$dir" + lib_search_path="$lib_search_path $dir" + ;; + esac + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*) + case :$dllsearchpath: in + *":$dir:"*) ;; + *) dllsearchpath="$dllsearchpath:$dir";; + esac + ;; + esac + continue + ;; + + -l*) + if test "X$arg" = "X-lc" || test "X$arg" = "X-lm"; then + case $host in + *-*-cygwin* | *-*-pw32* | *-*-beos*) + # These systems don't actually have a C or math library (as such) + continue + ;; + *-*-mingw* | *-*-os2*) + # These systems don't actually have a C library (as such) + test "X$arg" = "X-lc" && continue + ;; + *-*-openbsd* | *-*-freebsd*) + # Do not include libc due to us having libc/libc_r. + test "X$arg" = "X-lc" && continue + ;; + *-*-rhapsody* | *-*-darwin1.[012]) + # Rhapsody C and math libraries are in the System framework + deplibs="$deplibs -framework System" + continue + esac + elif test "X$arg" = "X-lc_r"; then + case $host in + *-*-openbsd* | *-*-freebsd*) + # Do not include libc_r directly, use -pthread flag. + continue + ;; + esac + fi + deplibs="$deplibs $arg" + continue + ;; + + -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe) + deplibs="$deplibs $arg" + continue + ;; + + -module) + module=yes + continue + ;; + + # gcc -m* arguments should be passed to the linker via $compiler_flags + # in order to pass architecture information to the linker + # (e.g. 32 vs 64-bit). This may also be accomplished via -Wl,-mfoo + # but this is not reliable with gcc because gcc may use -mfoo to + # select a different linker, different libraries, etc, while + # -Wl,-mfoo simply passes -mfoo to the linker. + -m*) + # Unknown arguments in both finalize_command and compile_command need + # to be aesthetically quoted because they are evaled later. + arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"` + case $arg in + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") + arg="\"$arg\"" + ;; + esac + compile_command="$compile_command $arg" + finalize_command="$finalize_command $arg" + if test "$with_gcc" = "yes" ; then + compiler_flags="$compiler_flags $arg" + fi + continue + ;; + + -shrext) + prev=shrext + continue + ;; + + -no-fast-install) + fast_install=no + continue + ;; + + -no-install) + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*) + # The PATH hackery in wrapper scripts is required on Windows + # in order for the loader to find any dlls it needs. + $echo "$modename: warning: \`-no-install' is ignored for $host" 1>&2 + $echo "$modename: warning: assuming \`-no-fast-install' instead" 1>&2 + fast_install=no + ;; + *) no_install=yes ;; + esac + continue + ;; + + -no-undefined) + allow_undefined=no + continue + ;; + + -objectlist) + prev=objectlist + continue + ;; + + -o) prev=output ;; + + -precious-files-regex) + prev=precious_regex + continue + ;; + + -release) + prev=release + continue + ;; + + -rpath) + prev=rpath + continue + ;; + + -R) + prev=xrpath + continue + ;; + + -R*) + dir=`$echo "X$arg" | $Xsed -e 's/^-R//'` + # We need an absolute path. + case $dir in + [\\/]* | [A-Za-z]:[\\/]*) ;; + *) + $echo "$modename: only absolute run-paths are allowed" 1>&2 + exit $EXIT_FAILURE + ;; + esac + case "$xrpath " in + *" $dir "*) ;; + *) xrpath="$xrpath $dir" ;; + esac + continue + ;; + + -static) + # The effects of -static are defined in a previous loop. + # We used to do the same as -all-static on platforms that + # didn't have a PIC flag, but the assumption that the effects + # would be equivalent was wrong. It would break on at least + # Digital Unix and AIX. + continue + ;; + + -thread-safe) + thread_safe=yes + continue + ;; + + -version-info) + prev=vinfo + continue + ;; + -version-number) + prev=vinfo + vinfo_number=yes + continue + ;; + + -Wc,*) + args=`$echo "X$arg" | $Xsed -e "$sed_quote_subst" -e 's/^-Wc,//'` + arg= + save_ifs="$IFS"; IFS=',' + for flag in $args; do + IFS="$save_ifs" + case $flag in + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") + flag="\"$flag\"" + ;; + esac + arg="$arg $wl$flag" + compiler_flags="$compiler_flags $flag" + done + IFS="$save_ifs" + arg=`$echo "X$arg" | $Xsed -e "s/^ //"` + ;; + + -Wl,*) + args=`$echo "X$arg" | $Xsed -e "$sed_quote_subst" -e 's/^-Wl,//'` + arg= + save_ifs="$IFS"; IFS=',' + for flag in $args; do + IFS="$save_ifs" + case $flag in + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") + flag="\"$flag\"" + ;; + esac + arg="$arg $wl$flag" + compiler_flags="$compiler_flags $wl$flag" + linker_flags="$linker_flags $flag" + done + IFS="$save_ifs" + arg=`$echo "X$arg" | $Xsed -e "s/^ //"` + ;; + + -Xcompiler) + prev=xcompiler + continue + ;; + + -Xlinker) + prev=xlinker + continue + ;; + + -XCClinker) + prev=xcclinker + continue + ;; + + # Some other compiler flag. + -* | +*) + # Unknown arguments in both finalize_command and compile_command need + # to be aesthetically quoted because they are evaled later. + arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"` + case $arg in + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") + arg="\"$arg\"" + ;; + esac + ;; + + *.$objext) + # A standard object. + objs="$objs $arg" + ;; + + *.lo) + # A libtool-controlled object. + + # Check to see that this really is a libtool object. + if (${SED} -e '2q' $arg | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then + pic_object= + non_pic_object= + + # Read the .lo file + # If there is no directory component, then add one. + case $arg in + */* | *\\*) . $arg ;; + *) . ./$arg ;; + esac + + if test -z "$pic_object" || \ + test -z "$non_pic_object" || + test "$pic_object" = none && \ + test "$non_pic_object" = none; then + $echo "$modename: cannot find name of object for \`$arg'" 1>&2 + exit $EXIT_FAILURE + fi + + # Extract subdirectory from the argument. + xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'` + if test "X$xdir" = "X$arg"; then + xdir= + else + xdir="$xdir/" + fi + + if test "$pic_object" != none; then + # Prepend the subdirectory the object is found in. + pic_object="$xdir$pic_object" + + if test "$prev" = dlfiles; then + if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then + dlfiles="$dlfiles $pic_object" + prev= + continue + else + # If libtool objects are unsupported, then we need to preload. + prev=dlprefiles + fi + fi + + # CHECK ME: I think I busted this. -Ossama + if test "$prev" = dlprefiles; then + # Preload the old-style object. + dlprefiles="$dlprefiles $pic_object" + prev= + fi + + # A PIC object. + libobjs="$libobjs $pic_object" + arg="$pic_object" + fi + + # Non-PIC object. + if test "$non_pic_object" != none; then + # Prepend the subdirectory the object is found in. + non_pic_object="$xdir$non_pic_object" + + # A standard non-PIC object + non_pic_objects="$non_pic_objects $non_pic_object" + if test -z "$pic_object" || test "$pic_object" = none ; then + arg="$non_pic_object" + fi + fi + else + # Only an error if not doing a dry-run. + if test -z "$run"; then + $echo "$modename: \`$arg' is not a valid libtool object" 1>&2 + exit $EXIT_FAILURE + else + # Dry-run case. + + # Extract subdirectory from the argument. + xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'` + if test "X$xdir" = "X$arg"; then + xdir= + else + xdir="$xdir/" + fi + + pic_object=`$echo "X${xdir}${objdir}/${arg}" | $Xsed -e "$lo2o"` + non_pic_object=`$echo "X${xdir}${arg}" | $Xsed -e "$lo2o"` + libobjs="$libobjs $pic_object" + non_pic_objects="$non_pic_objects $non_pic_object" + fi + fi + ;; + + *.$libext) + # An archive. + deplibs="$deplibs $arg" + old_deplibs="$old_deplibs $arg" + continue + ;; + + *.la) + # A libtool-controlled library. + + if test "$prev" = dlfiles; then + # This library was specified with -dlopen. + dlfiles="$dlfiles $arg" + prev= + elif test "$prev" = dlprefiles; then + # The library was specified with -dlpreopen. + dlprefiles="$dlprefiles $arg" + prev= + else + deplibs="$deplibs $arg" + fi + continue + ;; + + # Some other compiler argument. + *) + # Unknown arguments in both finalize_command and compile_command need + # to be aesthetically quoted because they are evaled later. + arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"` + case $arg in + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") + arg="\"$arg\"" + ;; + esac + ;; + esac # arg + + # Now actually substitute the argument into the commands. + if test -n "$arg"; then + compile_command="$compile_command $arg" + finalize_command="$finalize_command $arg" + fi + done # argument parsing loop + + if test -n "$prev"; then + $echo "$modename: the \`$prevarg' option requires an argument" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + fi + + if test "$export_dynamic" = yes && test -n "$export_dynamic_flag_spec"; then + eval arg=\"$export_dynamic_flag_spec\" + compile_command="$compile_command $arg" + finalize_command="$finalize_command $arg" + fi + + oldlibs= + # calculate the name of the file, without its directory + outputname=`$echo "X$output" | $Xsed -e 's%^.*/%%'` + libobjs_save="$libobjs" + + if test -n "$shlibpath_var"; then + # get the directories listed in $shlibpath_var + eval shlib_search_path=\`\$echo \"X\${$shlibpath_var}\" \| \$Xsed -e \'s/:/ /g\'\` + else + shlib_search_path= + fi + eval sys_lib_search_path=\"$sys_lib_search_path_spec\" + eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\" + + output_objdir=`$echo "X$output" | $Xsed -e 's%/[^/]*$%%'` + if test "X$output_objdir" = "X$output"; then + output_objdir="$objdir" + else + output_objdir="$output_objdir/$objdir" + fi + # Create the object directory. + if test ! -d "$output_objdir"; then + $show "$mkdir $output_objdir" + $run $mkdir $output_objdir + status=$? + if test "$status" -ne 0 && test ! -d "$output_objdir"; then + exit $status + fi + fi + + # Determine the type of output + case $output in + "") + $echo "$modename: you must specify an output file" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + ;; + *.$libext) linkmode=oldlib ;; + *.lo | *.$objext) linkmode=obj ;; + *.la) linkmode=lib ;; + *) linkmode=prog ;; # Anything else should be a program. + esac + + case $host in + *cygwin* | *mingw* | *pw32*) + # don't eliminate duplications in $postdeps and $predeps + duplicate_compiler_generated_deps=yes + ;; + *) + duplicate_compiler_generated_deps=$duplicate_deps + ;; + esac + specialdeplibs= + + libs= + # Find all interdependent deplibs by searching for libraries + # that are linked more than once (e.g. -la -lb -la) + for deplib in $deplibs; do + if test "X$duplicate_deps" = "Xyes" ; then + case "$libs " in + *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; + esac + fi + libs="$libs $deplib" + done + + if test "$linkmode" = lib; then + libs="$predeps $libs $compiler_lib_search_path $postdeps" + + # Compute libraries that are listed more than once in $predeps + # $postdeps and mark them as special (i.e., whose duplicates are + # not to be eliminated). + pre_post_deps= + if test "X$duplicate_compiler_generated_deps" = "Xyes" ; then + for pre_post_dep in $predeps $postdeps; do + case "$pre_post_deps " in + *" $pre_post_dep "*) specialdeplibs="$specialdeplibs $pre_post_deps" ;; + esac + pre_post_deps="$pre_post_deps $pre_post_dep" + done + fi + pre_post_deps= + fi + + deplibs= + newdependency_libs= + newlib_search_path= + need_relink=no # whether we're linking any uninstalled libtool libraries + notinst_deplibs= # not-installed libtool libraries + notinst_path= # paths that contain not-installed libtool libraries + case $linkmode in + lib) + passes="conv link" + for file in $dlfiles $dlprefiles; do + case $file in + *.la) ;; + *) + $echo "$modename: libraries can \`-dlopen' only libtool libraries: $file" 1>&2 + exit $EXIT_FAILURE + ;; + esac + done + ;; + prog) + compile_deplibs= + finalize_deplibs= + alldeplibs=no + newdlfiles= + newdlprefiles= + passes="conv scan dlopen dlpreopen link" + ;; + *) passes="conv" + ;; + esac + for pass in $passes; do + if test "$linkmode,$pass" = "lib,link" || + test "$linkmode,$pass" = "prog,scan"; then + libs="$deplibs" + deplibs= + fi + if test "$linkmode" = prog; then + case $pass in + dlopen) libs="$dlfiles" ;; + dlpreopen) libs="$dlprefiles" ;; + link) + libs="$deplibs %DEPLIBS%" + test "X$link_all_deplibs" != Xno && libs="$libs $dependency_libs" + ;; + esac + fi + if test "$pass" = dlopen; then + # Collect dlpreopened libraries + save_deplibs="$deplibs" + deplibs= + fi + for deplib in $libs; do + lib= + found=no + case $deplib in + -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe) + if test "$linkmode,$pass" = "prog,link"; then + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + deplibs="$deplib $deplibs" + fi + continue + ;; + -l*) + if test "$linkmode" != lib && test "$linkmode" != prog; then + $echo "$modename: warning: \`-l' is ignored for archives/objects" 1>&2 + continue + fi + if test "$pass" = conv; then + deplibs="$deplib $deplibs" + continue + fi + name=`$echo "X$deplib" | $Xsed -e 's/^-l//'` + for searchdir in $newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path; do + for search_ext in .la $std_shrext .so .a; do + # Search the libtool library + lib="$searchdir/lib${name}${search_ext}" + if test -f "$lib"; then + if test "$search_ext" = ".la"; then + found=yes + else + found=no + fi + break 2 + fi + done + done + if test "$found" != yes; then + # deplib doesn't seem to be a libtool library + if test "$linkmode,$pass" = "prog,link"; then + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + deplibs="$deplib $deplibs" + test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" + fi + continue + else # deplib is a libtool library + # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib, + # We need to do some special things here, and not later. + if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then + case " $predeps $postdeps " in + *" $deplib "*) + if (${SED} -e '2q' $lib | + grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then + library_names= + old_library= + case $lib in + */* | *\\*) . $lib ;; + *) . ./$lib ;; + esac + for l in $old_library $library_names; do + ll="$l" + done + if test "X$ll" = "X$old_library" ; then # only static version available + found=no + ladir=`$echo "X$lib" | $Xsed -e 's%/[^/]*$%%'` + test "X$ladir" = "X$lib" && ladir="." + lib=$ladir/$old_library + if test "$linkmode,$pass" = "prog,link"; then + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + deplibs="$deplib $deplibs" + test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" + fi + continue + fi + fi + ;; + *) ;; + esac + fi + fi + ;; # -l + -L*) + case $linkmode in + lib) + deplibs="$deplib $deplibs" + test "$pass" = conv && continue + newdependency_libs="$deplib $newdependency_libs" + newlib_search_path="$newlib_search_path "`$echo "X$deplib" | $Xsed -e 's/^-L//'` + ;; + prog) + if test "$pass" = conv; then + deplibs="$deplib $deplibs" + continue + fi + if test "$pass" = scan; then + deplibs="$deplib $deplibs" + else + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + fi + newlib_search_path="$newlib_search_path "`$echo "X$deplib" | $Xsed -e 's/^-L//'` + ;; + *) + $echo "$modename: warning: \`-L' is ignored for archives/objects" 1>&2 + ;; + esac # linkmode + continue + ;; # -L + -R*) + if test "$pass" = link; then + dir=`$echo "X$deplib" | $Xsed -e 's/^-R//'` + # Make sure the xrpath contains only unique directories. + case "$xrpath " in + *" $dir "*) ;; + *) xrpath="$xrpath $dir" ;; + esac + fi + deplibs="$deplib $deplibs" + continue + ;; + *.la) lib="$deplib" ;; + *.$libext) + if test "$pass" = conv; then + deplibs="$deplib $deplibs" + continue + fi + case $linkmode in + lib) + if test "$deplibs_check_method" != pass_all; then + $echo + $echo "*** Warning: Trying to link with static lib archive $deplib." + $echo "*** I have the capability to make that library automatically link in when" + $echo "*** you link to this library. But I can only do this if you have a" + $echo "*** shared version of the library, which you do not appear to have" + $echo "*** because the file extensions .$libext of this argument makes me believe" + $echo "*** that it is just a static archive that I should not used here." + else + $echo + $echo "*** Warning: Linking the shared library $output against the" + $echo "*** static library $deplib is not portable!" + deplibs="$deplib $deplibs" + fi + continue + ;; + prog) + if test "$pass" != link; then + deplibs="$deplib $deplibs" + else + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + fi + continue + ;; + esac # linkmode + ;; # *.$libext + *.lo | *.$objext) + if test "$pass" = conv; then + deplibs="$deplib $deplibs" + elif test "$linkmode" = prog; then + if test "$pass" = dlpreopen || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then + # If there is no dlopen support or we're linking statically, + # we need to preload. + newdlprefiles="$newdlprefiles $deplib" + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + newdlfiles="$newdlfiles $deplib" + fi + fi + continue + ;; + %DEPLIBS%) + alldeplibs=yes + continue + ;; + esac # case $deplib + if test "$found" = yes || test -f "$lib"; then : + else + $echo "$modename: cannot find the library \`$lib'" 1>&2 + exit $EXIT_FAILURE + fi + + # Check to see that this really is a libtool archive. + if (${SED} -e '2q' $lib | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then : + else + $echo "$modename: \`$lib' is not a valid libtool archive" 1>&2 + exit $EXIT_FAILURE + fi + + ladir=`$echo "X$lib" | $Xsed -e 's%/[^/]*$%%'` + test "X$ladir" = "X$lib" && ladir="." + + dlname= + dlopen= + dlpreopen= + libdir= + library_names= + old_library= + # If the library was installed with an old release of libtool, + # it will not redefine variables installed, or shouldnotlink + installed=yes + shouldnotlink=no + + # Read the .la file + case $lib in + */* | *\\*) . $lib ;; + *) . ./$lib ;; + esac + + if test "$linkmode,$pass" = "lib,link" || + test "$linkmode,$pass" = "prog,scan" || + { test "$linkmode" != prog && test "$linkmode" != lib; }; then + test -n "$dlopen" && dlfiles="$dlfiles $dlopen" + test -n "$dlpreopen" && dlprefiles="$dlprefiles $dlpreopen" + fi + + if test "$pass" = conv; then + # Only check for convenience libraries + deplibs="$lib $deplibs" + if test -z "$libdir"; then + if test -z "$old_library"; then + $echo "$modename: cannot find name of link library for \`$lib'" 1>&2 + exit $EXIT_FAILURE + fi + # It is a libtool convenience library, so add in its objects. + convenience="$convenience $ladir/$objdir/$old_library" + old_convenience="$old_convenience $ladir/$objdir/$old_library" + tmp_libs= + for deplib in $dependency_libs; do + deplibs="$deplib $deplibs" + if test "X$duplicate_deps" = "Xyes" ; then + case "$tmp_libs " in + *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; + esac + fi + tmp_libs="$tmp_libs $deplib" + done + elif test "$linkmode" != prog && test "$linkmode" != lib; then + $echo "$modename: \`$lib' is not a convenience library" 1>&2 + exit $EXIT_FAILURE + fi + continue + fi # $pass = conv + + + # Get the name of the library we link against. + linklib= + for l in $old_library $library_names; do + linklib="$l" + done + if test -z "$linklib"; then + $echo "$modename: cannot find name of link library for \`$lib'" 1>&2 + exit $EXIT_FAILURE + fi + + # This library was specified with -dlopen. + if test "$pass" = dlopen; then + if test -z "$libdir"; then + $echo "$modename: cannot -dlopen a convenience library: \`$lib'" 1>&2 + exit $EXIT_FAILURE + fi + if test -z "$dlname" || + test "$dlopen_support" != yes || + test "$build_libtool_libs" = no; then + # If there is no dlname, no dlopen support or we're linking + # statically, we need to preload. We also need to preload any + # dependent libraries so libltdl's deplib preloader doesn't + # bomb out in the load deplibs phase. + dlprefiles="$dlprefiles $lib $dependency_libs" + else + newdlfiles="$newdlfiles $lib" + fi + continue + fi # $pass = dlopen + + # We need an absolute path. + case $ladir in + [\\/]* | [A-Za-z]:[\\/]*) abs_ladir="$ladir" ;; + *) + abs_ladir=`cd "$ladir" && pwd` + if test -z "$abs_ladir"; then + $echo "$modename: warning: cannot determine absolute directory name of \`$ladir'" 1>&2 + $echo "$modename: passing it literally to the linker, although it might fail" 1>&2 + abs_ladir="$ladir" + fi + ;; + esac + laname=`$echo "X$lib" | $Xsed -e 's%^.*/%%'` + + # Find the relevant object directory and library name. + if test "X$installed" = Xyes; then + if test ! -f "$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then + $echo "$modename: warning: library \`$lib' was moved." 1>&2 + dir="$ladir" + absdir="$abs_ladir" + libdir="$abs_ladir" + else + dir="$libdir" + absdir="$libdir" + fi + else + dir="$ladir/$objdir" + absdir="$abs_ladir/$objdir" + # Remove this search path later + notinst_path="$notinst_path $abs_ladir" + fi # $installed = yes + name=`$echo "X$laname" | $Xsed -e 's/\.la$//' -e 's/^lib//'` + + # This library was specified with -dlpreopen. + if test "$pass" = dlpreopen; then + if test -z "$libdir"; then + $echo "$modename: cannot -dlpreopen a convenience library: \`$lib'" 1>&2 + exit $EXIT_FAILURE + fi + # Prefer using a static library (so that no silly _DYNAMIC symbols + # are required to link). + if test -n "$old_library"; then + newdlprefiles="$newdlprefiles $dir/$old_library" + # Otherwise, use the dlname, so that lt_dlopen finds it. + elif test -n "$dlname"; then + newdlprefiles="$newdlprefiles $dir/$dlname" + else + newdlprefiles="$newdlprefiles $dir/$linklib" + fi + fi # $pass = dlpreopen + + if test -z "$libdir"; then + # Link the convenience library + if test "$linkmode" = lib; then + deplibs="$dir/$old_library $deplibs" + elif test "$linkmode,$pass" = "prog,link"; then + compile_deplibs="$dir/$old_library $compile_deplibs" + finalize_deplibs="$dir/$old_library $finalize_deplibs" + else + deplibs="$lib $deplibs" # used for prog,scan pass + fi + continue + fi + + + if test "$linkmode" = prog && test "$pass" != link; then + newlib_search_path="$newlib_search_path $ladir" + deplibs="$lib $deplibs" + + linkalldeplibs=no + if test "$link_all_deplibs" != no || test -z "$library_names" || + test "$build_libtool_libs" = no; then + linkalldeplibs=yes + fi + + tmp_libs= + for deplib in $dependency_libs; do + case $deplib in + -L*) newlib_search_path="$newlib_search_path "`$echo "X$deplib" | $Xsed -e 's/^-L//'`;; ### testsuite: skip nested quoting test + esac + # Need to link against all dependency_libs? + if test "$linkalldeplibs" = yes; then + deplibs="$deplib $deplibs" + else + # Need to hardcode shared library paths + # or/and link against static libraries + newdependency_libs="$deplib $newdependency_libs" + fi + if test "X$duplicate_deps" = "Xyes" ; then + case "$tmp_libs " in + *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; + esac + fi + tmp_libs="$tmp_libs $deplib" + done # for deplib + continue + fi # $linkmode = prog... + + if test "$linkmode,$pass" = "prog,link"; then + if test -n "$library_names" && + { test "$prefer_static_libs" = no || test -z "$old_library"; }; then + # We need to hardcode the library path + if test -n "$shlibpath_var"; then + # Make sure the rpath contains only unique directories. + case "$temp_rpath " in + *" $dir "*) ;; + *" $absdir "*) ;; + *) temp_rpath="$temp_rpath $dir" ;; + esac + fi + + # Hardcode the library path. + # Skip directories that are in the system default run-time + # search path. + case " $sys_lib_dlsearch_path " in + *" $absdir "*) ;; + *) + case "$compile_rpath " in + *" $absdir "*) ;; + *) compile_rpath="$compile_rpath $absdir" + esac + ;; + esac + case " $sys_lib_dlsearch_path " in + *" $libdir "*) ;; + *) + case "$finalize_rpath " in + *" $libdir "*) ;; + *) finalize_rpath="$finalize_rpath $libdir" + esac + ;; + esac + fi # $linkmode,$pass = prog,link... + + if test "$alldeplibs" = yes && + { test "$deplibs_check_method" = pass_all || + { test "$build_libtool_libs" = yes && + test -n "$library_names"; }; }; then + # We only need to search for static libraries + continue + fi + fi + + link_static=no # Whether the deplib will be linked statically + if test -n "$library_names" && + { test "$prefer_static_libs" = no || test -z "$old_library"; }; then + if test "$installed" = no; then + notinst_deplibs="$notinst_deplibs $lib" + need_relink=yes + fi + # This is a shared library + + # Warn about portability, can't link against -module's on + # some systems (darwin) + if test "$shouldnotlink" = yes && test "$pass" = link ; then + $echo + if test "$linkmode" = prog; then + $echo "*** Warning: Linking the executable $output against the loadable module" + else + $echo "*** Warning: Linking the shared library $output against the loadable module" + fi + $echo "*** $linklib is not portable!" + fi + if test "$linkmode" = lib && + test "$hardcode_into_libs" = yes; then + # Hardcode the library path. + # Skip directories that are in the system default run-time + # search path. + case " $sys_lib_dlsearch_path " in + *" $absdir "*) ;; + *) + case "$compile_rpath " in + *" $absdir "*) ;; + *) compile_rpath="$compile_rpath $absdir" + esac + ;; + esac + case " $sys_lib_dlsearch_path " in + *" $libdir "*) ;; + *) + case "$finalize_rpath " in + *" $libdir "*) ;; + *) finalize_rpath="$finalize_rpath $libdir" + esac + ;; + esac + fi + + if test -n "$old_archive_from_expsyms_cmds"; then + # figure out the soname + set dummy $library_names + realname="$2" + shift; shift + libname=`eval \\$echo \"$libname_spec\"` + # use dlname if we got it. it's perfectly good, no? + if test -n "$dlname"; then + soname="$dlname" + elif test -n "$soname_spec"; then + # bleh windows + case $host in + *cygwin* | mingw*) + major=`expr $current - $age` + versuffix="-$major" + ;; + esac + eval soname=\"$soname_spec\" + else + soname="$realname" + fi + + # Make a new name for the extract_expsyms_cmds to use + soroot="$soname" + soname=`$echo $soroot | ${SED} -e 's/^.*\///'` + newlib="libimp-`$echo $soname | ${SED} 's/^lib//;s/\.dll$//'`.a" + + # If the library has no export list, then create one now + if test -f "$output_objdir/$soname-def"; then : + else + $show "extracting exported symbol list from \`$soname'" + save_ifs="$IFS"; IFS='~' + cmds=$extract_expsyms_cmds + for cmd in $cmds; do + IFS="$save_ifs" + eval cmd=\"$cmd\" + $show "$cmd" + $run eval "$cmd" || exit $? + done + IFS="$save_ifs" + fi + + # Create $newlib + if test -f "$output_objdir/$newlib"; then :; else + $show "generating import library for \`$soname'" + save_ifs="$IFS"; IFS='~' + cmds=$old_archive_from_expsyms_cmds + for cmd in $cmds; do + IFS="$save_ifs" + eval cmd=\"$cmd\" + $show "$cmd" + $run eval "$cmd" || exit $? + done + IFS="$save_ifs" + fi + # make sure the library variables are pointing to the new library + dir=$output_objdir + linklib=$newlib + fi # test -n "$old_archive_from_expsyms_cmds" + + if test "$linkmode" = prog || test "$mode" != relink; then + add_shlibpath= + add_dir= + add= + lib_linked=yes + case $hardcode_action in + immediate | unsupported) + if test "$hardcode_direct" = no; then + add="$dir/$linklib" + case $host in + *-*-sco3.2v5* ) add_dir="-L$dir" ;; + *-*-darwin* ) + # if the lib is a module then we can not link against + # it, someone is ignoring the new warnings I added + if /usr/bin/file -L $add 2> /dev/null | $EGREP "bundle" >/dev/null ; then + $echo "** Warning, lib $linklib is a module, not a shared library" + if test -z "$old_library" ; then + $echo + $echo "** And there doesn't seem to be a static archive available" + $echo "** The link will probably fail, sorry" + else + add="$dir/$old_library" + fi + fi + esac + elif test "$hardcode_minus_L" = no; then + case $host in + *-*-sunos*) add_shlibpath="$dir" ;; + esac + add_dir="-L$dir" + add="-l$name" + elif test "$hardcode_shlibpath_var" = no; then + add_shlibpath="$dir" + add="-l$name" + else + lib_linked=no + fi + ;; + relink) + if test "$hardcode_direct" = yes; then + add="$dir/$linklib" + elif test "$hardcode_minus_L" = yes; then + add_dir="-L$dir" + # Try looking first in the location we're being installed to. + if test -n "$inst_prefix_dir"; then + case "$libdir" in + [\\/]*) + add_dir="$add_dir -L$inst_prefix_dir$libdir" + ;; + esac + fi + add="-l$name" + elif test "$hardcode_shlibpath_var" = yes; then + add_shlibpath="$dir" + add="-l$name" + else + lib_linked=no + fi + ;; + *) lib_linked=no ;; + esac + + if test "$lib_linked" != yes; then + $echo "$modename: configuration error: unsupported hardcode properties" + exit $EXIT_FAILURE + fi + + if test -n "$add_shlibpath"; then + case :$compile_shlibpath: in + *":$add_shlibpath:"*) ;; + *) compile_shlibpath="$compile_shlibpath$add_shlibpath:" ;; + esac + fi + if test "$linkmode" = prog; then + test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs" + test -n "$add" && compile_deplibs="$add $compile_deplibs" + else + test -n "$add_dir" && deplibs="$add_dir $deplibs" + test -n "$add" && deplibs="$add $deplibs" + if test "$hardcode_direct" != yes && \ + test "$hardcode_minus_L" != yes && \ + test "$hardcode_shlibpath_var" = yes; then + case :$finalize_shlibpath: in + *":$libdir:"*) ;; + *) finalize_shlibpath="$finalize_shlibpath$libdir:" ;; + esac + fi + fi + fi + + if test "$linkmode" = prog || test "$mode" = relink; then + add_shlibpath= + add_dir= + add= + # Finalize command for both is simple: just hardcode it. + if test "$hardcode_direct" = yes; then + add="$libdir/$linklib" + elif test "$hardcode_minus_L" = yes; then + add_dir="-L$libdir" + add="-l$name" + elif test "$hardcode_shlibpath_var" = yes; then + case :$finalize_shlibpath: in + *":$libdir:"*) ;; + *) finalize_shlibpath="$finalize_shlibpath$libdir:" ;; + esac + add="-l$name" + elif test "$hardcode_automatic" = yes; then + if test -n "$inst_prefix_dir" && + test -f "$inst_prefix_dir$libdir/$linklib" ; then + add="$inst_prefix_dir$libdir/$linklib" + else + add="$libdir/$linklib" + fi + else + # We cannot seem to hardcode it, guess we'll fake it. + add_dir="-L$libdir" + # Try looking first in the location we're being installed to. + if test -n "$inst_prefix_dir"; then + case "$libdir" in + [\\/]*) + add_dir="$add_dir -L$inst_prefix_dir$libdir" + ;; + esac + fi + add="-l$name" + fi + + if test "$linkmode" = prog; then + test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs" + test -n "$add" && finalize_deplibs="$add $finalize_deplibs" + else + test -n "$add_dir" && deplibs="$add_dir $deplibs" + test -n "$add" && deplibs="$add $deplibs" + fi + fi + elif test "$linkmode" = prog; then + # Here we assume that one of hardcode_direct or hardcode_minus_L + # is not unsupported. This is valid on all known static and + # shared platforms. + if test "$hardcode_direct" != unsupported; then + test -n "$old_library" && linklib="$old_library" + compile_deplibs="$dir/$linklib $compile_deplibs" + finalize_deplibs="$dir/$linklib $finalize_deplibs" + else + compile_deplibs="-l$name -L$dir $compile_deplibs" + finalize_deplibs="-l$name -L$dir $finalize_deplibs" + fi + elif test "$build_libtool_libs" = yes; then + # Not a shared library + if test "$deplibs_check_method" != pass_all; then + # We're trying link a shared library against a static one + # but the system doesn't support it. + + # Just print a warning and add the library to dependency_libs so + # that the program can be linked against the static library. + $echo + $echo "*** Warning: This system can not link to static lib archive $lib." + $echo "*** I have the capability to make that library automatically link in when" + $echo "*** you link to this library. But I can only do this if you have a" + $echo "*** shared version of the library, which you do not appear to have." + if test "$module" = yes; then + $echo "*** But as you try to build a module library, libtool will still create " + $echo "*** a static module, that should work as long as the dlopening application" + $echo "*** is linked with the -dlopen flag to resolve symbols at runtime." + if test -z "$global_symbol_pipe"; then + $echo + $echo "*** However, this would only work if libtool was able to extract symbol" + $echo "*** lists from a program, using \`nm' or equivalent, but libtool could" + $echo "*** not find such a program. So, this module is probably useless." + $echo "*** \`nm' from GNU binutils and a full rebuild may help." + fi + if test "$build_old_libs" = no; then + build_libtool_libs=module + build_old_libs=yes + else + build_libtool_libs=no + fi + fi + else + convenience="$convenience $dir/$old_library" + old_convenience="$old_convenience $dir/$old_library" + deplibs="$dir/$old_library $deplibs" + link_static=yes + fi + fi # link shared/static library? + + if test "$linkmode" = lib; then + if test -n "$dependency_libs" && + { test "$hardcode_into_libs" != yes || + test "$build_old_libs" = yes || + test "$link_static" = yes; }; then + # Extract -R from dependency_libs + temp_deplibs= + for libdir in $dependency_libs; do + case $libdir in + -R*) temp_xrpath=`$echo "X$libdir" | $Xsed -e 's/^-R//'` + case " $xrpath " in + *" $temp_xrpath "*) ;; + *) xrpath="$xrpath $temp_xrpath";; + esac;; + *) temp_deplibs="$temp_deplibs $libdir";; + esac + done + dependency_libs="$temp_deplibs" + fi + + newlib_search_path="$newlib_search_path $absdir" + # Link against this library + test "$link_static" = no && newdependency_libs="$abs_ladir/$laname $newdependency_libs" + # ... and its dependency_libs + tmp_libs= + for deplib in $dependency_libs; do + newdependency_libs="$deplib $newdependency_libs" + if test "X$duplicate_deps" = "Xyes" ; then + case "$tmp_libs " in + *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; + esac + fi + tmp_libs="$tmp_libs $deplib" + done + + if test "$link_all_deplibs" != no; then + # Add the search paths of all dependency libraries + for deplib in $dependency_libs; do + case $deplib in + -L*) path="$deplib" ;; + *.la) + dir=`$echo "X$deplib" | $Xsed -e 's%/[^/]*$%%'` + test "X$dir" = "X$deplib" && dir="." + # We need an absolute path. + case $dir in + [\\/]* | [A-Za-z]:[\\/]*) absdir="$dir" ;; + *) + absdir=`cd "$dir" && pwd` + if test -z "$absdir"; then + $echo "$modename: warning: cannot determine absolute directory name of \`$dir'" 1>&2 + absdir="$dir" + fi + ;; + esac + if grep "^installed=no" $deplib > /dev/null; then + path="$absdir/$objdir" + else + eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib` + if test -z "$libdir"; then + $echo "$modename: \`$deplib' is not a valid libtool archive" 1>&2 + exit $EXIT_FAILURE + fi + if test "$absdir" != "$libdir"; then + $echo "$modename: warning: \`$deplib' seems to be moved" 1>&2 + fi + path="$absdir" + fi + depdepl= + case $host in + *-*-darwin*) + # we do not want to link against static libs, + # but need to link against shared + eval deplibrary_names=`${SED} -n -e 's/^library_names=\(.*\)$/\1/p' $deplib` + if test -n "$deplibrary_names" ; then + for tmp in $deplibrary_names ; do + depdepl=$tmp + done + if test -f "$path/$depdepl" ; then + depdepl="$path/$depdepl" + fi + # do not add paths which are already there + case " $newlib_search_path " in + *" $path "*) ;; + *) newlib_search_path="$newlib_search_path $path";; + esac + fi + path="" + ;; + *) + path="-L$path" + ;; + esac + ;; + -l*) + case $host in + *-*-darwin*) + # Again, we only want to link against shared libraries + eval tmp_libs=`$echo "X$deplib" | $Xsed -e "s,^\-l,,"` + for tmp in $newlib_search_path ; do + if test -f "$tmp/lib$tmp_libs.dylib" ; then + eval depdepl="$tmp/lib$tmp_libs.dylib" + break + fi + done + path="" + ;; + *) continue ;; + esac + ;; + *) continue ;; + esac + case " $deplibs " in + *" $depdepl "*) ;; + *) deplibs="$depdepl $deplibs" ;; + esac + case " $deplibs " in + *" $path "*) ;; + *) deplibs="$deplibs $path" ;; + esac + done + fi # link_all_deplibs != no + fi # linkmode = lib + done # for deplib in $libs + dependency_libs="$newdependency_libs" + if test "$pass" = dlpreopen; then + # Link the dlpreopened libraries before other libraries + for deplib in $save_deplibs; do + deplibs="$deplib $deplibs" + done + fi + if test "$pass" != dlopen; then + if test "$pass" != conv; then + # Make sure lib_search_path contains only unique directories. + lib_search_path= + for dir in $newlib_search_path; do + case "$lib_search_path " in + *" $dir "*) ;; + *) lib_search_path="$lib_search_path $dir" ;; + esac + done + newlib_search_path= + fi + + if test "$linkmode,$pass" != "prog,link"; then + vars="deplibs" + else + vars="compile_deplibs finalize_deplibs" + fi + for var in $vars dependency_libs; do + # Add libraries to $var in reverse order + eval tmp_libs=\"\$$var\" + new_libs= + for deplib in $tmp_libs; do + # FIXME: Pedantically, this is the right thing to do, so + # that some nasty dependency loop isn't accidentally + # broken: + #new_libs="$deplib $new_libs" + # Pragmatically, this seems to cause very few problems in + # practice: + case $deplib in + -L*) new_libs="$deplib $new_libs" ;; + -R*) ;; + *) + # And here is the reason: when a library appears more + # than once as an explicit dependence of a library, or + # is implicitly linked in more than once by the + # compiler, it is considered special, and multiple + # occurrences thereof are not removed. Compare this + # with having the same library being listed as a + # dependency of multiple other libraries: in this case, + # we know (pedantically, we assume) the library does not + # need to be listed more than once, so we keep only the + # last copy. This is not always right, but it is rare + # enough that we require users that really mean to play + # such unportable linking tricks to link the library + # using -Wl,-lname, so that libtool does not consider it + # for duplicate removal. + case " $specialdeplibs " in + *" $deplib "*) new_libs="$deplib $new_libs" ;; + *) + case " $new_libs " in + *" $deplib "*) ;; + *) new_libs="$deplib $new_libs" ;; + esac + ;; + esac + ;; + esac + done + tmp_libs= + for deplib in $new_libs; do + case $deplib in + -L*) + case " $tmp_libs " in + *" $deplib "*) ;; + *) tmp_libs="$tmp_libs $deplib" ;; + esac + ;; + *) tmp_libs="$tmp_libs $deplib" ;; + esac + done + eval $var=\"$tmp_libs\" + done # for var + fi + # Last step: remove runtime libs from dependency_libs + # (they stay in deplibs) + tmp_libs= + for i in $dependency_libs ; do + case " $predeps $postdeps $compiler_lib_search_path " in + *" $i "*) + i="" + ;; + esac + if test -n "$i" ; then + tmp_libs="$tmp_libs $i" + fi + done + dependency_libs=$tmp_libs + done # for pass + if test "$linkmode" = prog; then + dlfiles="$newdlfiles" + dlprefiles="$newdlprefiles" + fi + + case $linkmode in + oldlib) + if test -n "$deplibs"; then + $echo "$modename: warning: \`-l' and \`-L' are ignored for archives" 1>&2 + fi + + if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then + $echo "$modename: warning: \`-dlopen' is ignored for archives" 1>&2 + fi + + if test -n "$rpath"; then + $echo "$modename: warning: \`-rpath' is ignored for archives" 1>&2 + fi + + if test -n "$xrpath"; then + $echo "$modename: warning: \`-R' is ignored for archives" 1>&2 + fi + + if test -n "$vinfo"; then + $echo "$modename: warning: \`-version-info/-version-number' is ignored for archives" 1>&2 + fi + + if test -n "$release"; then + $echo "$modename: warning: \`-release' is ignored for archives" 1>&2 + fi + + if test -n "$export_symbols" || test -n "$export_symbols_regex"; then + $echo "$modename: warning: \`-export-symbols' is ignored for archives" 1>&2 + fi + + # Now set the variables for building old libraries. + build_libtool_libs=no + oldlibs="$output" + objs="$objs$old_deplibs" + ;; + + lib) + # Make sure we only generate libraries of the form `libNAME.la'. + case $outputname in + lib*) + name=`$echo "X$outputname" | $Xsed -e 's/\.la$//' -e 's/^lib//'` + eval shared_ext=\"$shrext_cmds\" + eval libname=\"$libname_spec\" + ;; + *) + if test "$module" = no; then + $echo "$modename: libtool library \`$output' must begin with \`lib'" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + fi + if test "$need_lib_prefix" != no; then + # Add the "lib" prefix for modules if required + name=`$echo "X$outputname" | $Xsed -e 's/\.la$//'` + eval shared_ext=\"$shrext_cmds\" + eval libname=\"$libname_spec\" + else + libname=`$echo "X$outputname" | $Xsed -e 's/\.la$//'` + fi + ;; + esac + + if test -n "$objs"; then + if test "$deplibs_check_method" != pass_all; then + $echo "$modename: cannot build libtool library \`$output' from non-libtool objects on this host:$objs" 2>&1 + exit $EXIT_FAILURE + else + $echo + $echo "*** Warning: Linking the shared library $output against the non-libtool" + $echo "*** objects $objs is not portable!" + libobjs="$libobjs $objs" + fi + fi + + if test "$dlself" != no; then + $echo "$modename: warning: \`-dlopen self' is ignored for libtool libraries" 1>&2 + fi + + set dummy $rpath + if test "$#" -gt 2; then + $echo "$modename: warning: ignoring multiple \`-rpath's for a libtool library" 1>&2 + fi + install_libdir="$2" + + oldlibs= + if test -z "$rpath"; then + if test "$build_libtool_libs" = yes; then + # Building a libtool convenience library. + # Some compilers have problems with a `.al' extension so + # convenience libraries should have the same extension an + # archive normally would. + oldlibs="$output_objdir/$libname.$libext $oldlibs" + build_libtool_libs=convenience + build_old_libs=yes + fi + + if test -n "$vinfo"; then + $echo "$modename: warning: \`-version-info/-version-number' is ignored for convenience libraries" 1>&2 + fi + + if test -n "$release"; then + $echo "$modename: warning: \`-release' is ignored for convenience libraries" 1>&2 + fi + else + + # Parse the version information argument. + save_ifs="$IFS"; IFS=':' + set dummy $vinfo 0 0 0 + IFS="$save_ifs" + + if test -n "$8"; then + $echo "$modename: too many parameters to \`-version-info'" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + fi + + # convert absolute version numbers to libtool ages + # this retains compatibility with .la files and attempts + # to make the code below a bit more comprehensible + + case $vinfo_number in + yes) + number_major="$2" + number_minor="$3" + number_revision="$4" + # + # There are really only two kinds -- those that + # use the current revision as the major version + # and those that subtract age and use age as + # a minor version. But, then there is irix + # which has an extra 1 added just for fun + # + case $version_type in + darwin|linux|osf|windows) + current=`expr $number_major + $number_minor` + age="$number_minor" + revision="$number_revision" + ;; + freebsd-aout|freebsd-elf|sunos) + current="$number_major" + revision="$number_minor" + age="0" + ;; + irix|nonstopux) + current=`expr $number_major + $number_minor - 1` + age="$number_minor" + revision="$number_minor" + ;; + *) + $echo "$modename: unknown library version type \`$version_type'" 1>&2 + $echo "Fatal configuration error. See the $PACKAGE docs for more information." 1>&2 + exit $EXIT_FAILURE + ;; + esac + ;; + no) + current="$2" + revision="$3" + age="$4" + ;; + esac + + # Check that each of the things are valid numbers. + case $current in + 0 | [1-9] | [1-9][0-9] | [1-9][0-9][0-9]) ;; + *) + $echo "$modename: CURRENT \`$current' is not a nonnegative integer" 1>&2 + $echo "$modename: \`$vinfo' is not valid version information" 1>&2 + exit $EXIT_FAILURE + ;; + esac + + case $revision in + 0 | [1-9] | [1-9][0-9] | [1-9][0-9][0-9]) ;; + *) + $echo "$modename: REVISION \`$revision' is not a nonnegative integer" 1>&2 + $echo "$modename: \`$vinfo' is not valid version information" 1>&2 + exit $EXIT_FAILURE + ;; + esac + + case $age in + 0 | [1-9] | [1-9][0-9] | [1-9][0-9][0-9]) ;; + *) + $echo "$modename: AGE \`$age' is not a nonnegative integer" 1>&2 + $echo "$modename: \`$vinfo' is not valid version information" 1>&2 + exit $EXIT_FAILURE + ;; + esac + + if test "$age" -gt "$current"; then + $echo "$modename: AGE \`$age' is greater than the current interface number \`$current'" 1>&2 + $echo "$modename: \`$vinfo' is not valid version information" 1>&2 + exit $EXIT_FAILURE + fi + + # Calculate the version variables. + major= + versuffix= + verstring= + case $version_type in + none) ;; + + darwin) + # Like Linux, but with the current version available in + # verstring for coding it into the library header + major=.`expr $current - $age` + versuffix="$major.$age.$revision" + # Darwin ld doesn't like 0 for these options... + minor_current=`expr $current + 1` + verstring="-compatibility_version $minor_current -current_version $minor_current.$revision" + ;; + + freebsd-aout) + major=".$current" + versuffix=".$current.$revision"; + ;; + + freebsd-elf) + major=".$current" + versuffix=".$current"; + ;; + + irix | nonstopux) + major=`expr $current - $age + 1` + + case $version_type in + nonstopux) verstring_prefix=nonstopux ;; + *) verstring_prefix=sgi ;; + esac + verstring="$verstring_prefix$major.$revision" + + # Add in all the interfaces that we are compatible with. + loop=$revision + while test "$loop" -ne 0; do + iface=`expr $revision - $loop` + loop=`expr $loop - 1` + verstring="$verstring_prefix$major.$iface:$verstring" + done + + # Before this point, $major must not contain `.'. + major=.$major + versuffix="$major.$revision" + ;; + + linux) + major=.`expr $current - $age` + versuffix="$major.$age.$revision" + ;; + + osf) + major=.`expr $current - $age` + versuffix=".$current.$age.$revision" + verstring="$current.$age.$revision" + + # Add in all the interfaces that we are compatible with. + loop=$age + while test "$loop" -ne 0; do + iface=`expr $current - $loop` + loop=`expr $loop - 1` + verstring="$verstring:${iface}.0" + done + + # Make executables depend on our current version. + verstring="$verstring:${current}.0" + ;; + + sunos) + major=".$current" + versuffix=".$current.$revision" + ;; + + windows) + # Use '-' rather than '.', since we only want one + # extension on DOS 8.3 filesystems. + major=`expr $current - $age` + versuffix="-$major" + ;; + + *) + $echo "$modename: unknown library version type \`$version_type'" 1>&2 + $echo "Fatal configuration error. See the $PACKAGE docs for more information." 1>&2 + exit $EXIT_FAILURE + ;; + esac + + # Clear the version info if we defaulted, and they specified a release. + if test -z "$vinfo" && test -n "$release"; then + major= + case $version_type in + darwin) + # we can't check for "0.0" in archive_cmds due to quoting + # problems, so we reset it completely + verstring= + ;; + *) + verstring="0.0" + ;; + esac + if test "$need_version" = no; then + versuffix= + else + versuffix=".0.0" + fi + fi + + # Remove version info from name if versioning should be avoided + if test "$avoid_version" = yes && test "$need_version" = no; then + major= + versuffix= + verstring="" + fi + + # Check to see if the archive will have undefined symbols. + if test "$allow_undefined" = yes; then + if test "$allow_undefined_flag" = unsupported; then + $echo "$modename: warning: undefined symbols not allowed in $host shared libraries" 1>&2 + build_libtool_libs=no + build_old_libs=yes + fi + else + # Don't allow undefined symbols. + allow_undefined_flag="$no_undefined_flag" + fi + fi + + if test "$mode" != relink; then + # Remove our outputs, but don't remove object files since they + # may have been created when compiling PIC objects. + removelist= + tempremovelist=`$echo "$output_objdir/*"` + for p in $tempremovelist; do + case $p in + *.$objext) + ;; + $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/${libname}${release}.*) + if test "X$precious_files_regex" != "X"; then + if echo $p | $EGREP -e "$precious_files_regex" >/dev/null 2>&1 + then + continue + fi + fi + removelist="$removelist $p" + ;; + *) ;; + esac + done + if test -n "$removelist"; then + $show "${rm}r $removelist" + $run ${rm}r $removelist + fi + fi + + # Now set the variables for building old libraries. + if test "$build_old_libs" = yes && test "$build_libtool_libs" != convenience ; then + oldlibs="$oldlibs $output_objdir/$libname.$libext" + + # Transform .lo files to .o files. + oldobjs="$objs "`$echo "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}'$/d' -e "$lo2o" | $NL2SP` + fi + + # Eliminate all temporary directories. + for path in $notinst_path; do + lib_search_path=`$echo "$lib_search_path " | ${SED} -e 's% $path % %g'` + deplibs=`$echo "$deplibs " | ${SED} -e 's% -L$path % %g'` + dependency_libs=`$echo "$dependency_libs " | ${SED} -e 's% -L$path % %g'` + done + + if test -n "$xrpath"; then + # If the user specified any rpath flags, then add them. + temp_xrpath= + for libdir in $xrpath; do + temp_xrpath="$temp_xrpath -R$libdir" + case "$finalize_rpath " in + *" $libdir "*) ;; + *) finalize_rpath="$finalize_rpath $libdir" ;; + esac + done + if test "$hardcode_into_libs" != yes || test "$build_old_libs" = yes; then + dependency_libs="$temp_xrpath $dependency_libs" + fi + fi + + # Make sure dlfiles contains only unique files that won't be dlpreopened + old_dlfiles="$dlfiles" + dlfiles= + for lib in $old_dlfiles; do + case " $dlprefiles $dlfiles " in + *" $lib "*) ;; + *) dlfiles="$dlfiles $lib" ;; + esac + done + + # Make sure dlprefiles contains only unique files + old_dlprefiles="$dlprefiles" + dlprefiles= + for lib in $old_dlprefiles; do + case "$dlprefiles " in + *" $lib "*) ;; + *) dlprefiles="$dlprefiles $lib" ;; + esac + done + + if test "$build_libtool_libs" = yes; then + if test -n "$rpath"; then + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos*) + # these systems don't actually have a c library (as such)! + ;; + *-*-rhapsody* | *-*-darwin1.[012]) + # Rhapsody C library is in the System framework + deplibs="$deplibs -framework System" + ;; + *-*-netbsd*) + # Don't link with libc until the a.out ld.so is fixed. + ;; + *-*-openbsd* | *-*-freebsd*) + # Do not include libc due to us having libc/libc_r. + test "X$arg" = "X-lc" && continue + ;; + *) + # Add libc to deplibs on all other systems if necessary. + if test "$build_libtool_need_lc" = "yes"; then + deplibs="$deplibs -lc" + fi + ;; + esac + fi + + # Transform deplibs into only deplibs that can be linked in shared. + name_save=$name + libname_save=$libname + release_save=$release + versuffix_save=$versuffix + major_save=$major + # I'm not sure if I'm treating the release correctly. I think + # release should show up in the -l (ie -lgmp5) so we don't want to + # add it in twice. Is that correct? + release="" + versuffix="" + major="" + newdeplibs= + droppeddeps=no + case $deplibs_check_method in + pass_all) + # Don't check for shared/static. Everything works. + # This might be a little naive. We might want to check + # whether the library exists or not. But this is on + # osf3 & osf4 and I'm not really sure... Just + # implementing what was already the behavior. + newdeplibs=$deplibs + ;; + test_compile) + # This code stresses the "libraries are programs" paradigm to its + # limits. Maybe even breaks it. We compile a program, linking it + # against the deplibs as a proxy for the library. Then we can check + # whether they linked in statically or dynamically with ldd. + $rm conftest.c + cat > conftest.c </dev/null` + for potent_lib in $potential_libs; do + # Follow soft links. + if ls -lLd "$potent_lib" 2>/dev/null \ + | grep " -> " >/dev/null; then + continue + fi + # The statement above tries to avoid entering an + # endless loop below, in case of cyclic links. + # We might still enter an endless loop, since a link + # loop can be closed while we follow links, + # but so what? + potlib="$potent_lib" + while test -h "$potlib" 2>/dev/null; do + potliblink=`ls -ld $potlib | ${SED} 's/.* -> //'` + case $potliblink in + [\\/]* | [A-Za-z]:[\\/]*) potlib="$potliblink";; + *) potlib=`$echo "X$potlib" | $Xsed -e 's,[^/]*$,,'`"$potliblink";; + esac + done + if eval $file_magic_cmd \"\$potlib\" 2>/dev/null \ + | ${SED} 10q \ + | $EGREP "$file_magic_regex" > /dev/null; then + newdeplibs="$newdeplibs $a_deplib" + a_deplib="" + break 2 + fi + done + done + fi + if test -n "$a_deplib" ; then + droppeddeps=yes + $echo + $echo "*** Warning: linker path does not have real file for library $a_deplib." + $echo "*** I have the capability to make that library automatically link in when" + $echo "*** you link to this library. But I can only do this if you have a" + $echo "*** shared version of the library, which you do not appear to have" + $echo "*** because I did check the linker path looking for a file starting" + if test -z "$potlib" ; then + $echo "*** with $libname but no candidates were found. (...for file magic test)" + else + $echo "*** with $libname and none of the candidates passed a file format test" + $echo "*** using a file magic. Last file checked: $potlib" + fi + fi + else + # Add a -L argument. + newdeplibs="$newdeplibs $a_deplib" + fi + done # Gone through all deplibs. + ;; + match_pattern*) + set dummy $deplibs_check_method + match_pattern_regex=`expr "$deplibs_check_method" : "$2 \(.*\)"` + for a_deplib in $deplibs; do + name="`expr $a_deplib : '-l\(.*\)'`" + # If $name is empty we are operating on a -L argument. + if test -n "$name" && test "$name" != "0"; then + if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then + case " $predeps $postdeps " in + *" $a_deplib "*) + newdeplibs="$newdeplibs $a_deplib" + a_deplib="" + ;; + esac + fi + if test -n "$a_deplib" ; then + libname=`eval \\$echo \"$libname_spec\"` + for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do + potential_libs=`ls $i/$libname[.-]* 2>/dev/null` + for potent_lib in $potential_libs; do + potlib="$potent_lib" # see symlink-check above in file_magic test + if eval $echo \"$potent_lib\" 2>/dev/null \ + | ${SED} 10q \ + | $EGREP "$match_pattern_regex" > /dev/null; then + newdeplibs="$newdeplibs $a_deplib" + a_deplib="" + break 2 + fi + done + done + fi + if test -n "$a_deplib" ; then + droppeddeps=yes + $echo + $echo "*** Warning: linker path does not have real file for library $a_deplib." + $echo "*** I have the capability to make that library automatically link in when" + $echo "*** you link to this library. But I can only do this if you have a" + $echo "*** shared version of the library, which you do not appear to have" + $echo "*** because I did check the linker path looking for a file starting" + if test -z "$potlib" ; then + $echo "*** with $libname but no candidates were found. (...for regex pattern test)" + else + $echo "*** with $libname and none of the candidates passed a file format test" + $echo "*** using a regex pattern. Last file checked: $potlib" + fi + fi + else + # Add a -L argument. + newdeplibs="$newdeplibs $a_deplib" + fi + done # Gone through all deplibs. + ;; + none | unknown | *) + newdeplibs="" + tmp_deplibs=`$echo "X $deplibs" | $Xsed -e 's/ -lc$//' \ + -e 's/ -[LR][^ ]*//g'` + if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then + for i in $predeps $postdeps ; do + # can't use Xsed below, because $i might contain '/' + tmp_deplibs=`$echo "X $tmp_deplibs" | ${SED} -e "1s,^X,," -e "s,$i,,"` + done + fi + if $echo "X $tmp_deplibs" | $Xsed -e 's/[ ]//g' \ + | grep . >/dev/null; then + $echo + if test "X$deplibs_check_method" = "Xnone"; then + $echo "*** Warning: inter-library dependencies are not supported in this platform." + else + $echo "*** Warning: inter-library dependencies are not known to be supported." + fi + $echo "*** All declared inter-library dependencies are being dropped." + droppeddeps=yes + fi + ;; + esac + versuffix=$versuffix_save + major=$major_save + release=$release_save + libname=$libname_save + name=$name_save + + case $host in + *-*-rhapsody* | *-*-darwin1.[012]) + # On Rhapsody replace the C library is the System framework + newdeplibs=`$echo "X $newdeplibs" | $Xsed -e 's/ -lc / -framework System /'` + ;; + esac + + if test "$droppeddeps" = yes; then + if test "$module" = yes; then + $echo + $echo "*** Warning: libtool could not satisfy all declared inter-library" + $echo "*** dependencies of module $libname. Therefore, libtool will create" + $echo "*** a static module, that should work as long as the dlopening" + $echo "*** application is linked with the -dlopen flag." + if test -z "$global_symbol_pipe"; then + $echo + $echo "*** However, this would only work if libtool was able to extract symbol" + $echo "*** lists from a program, using \`nm' or equivalent, but libtool could" + $echo "*** not find such a program. So, this module is probably useless." + $echo "*** \`nm' from GNU binutils and a full rebuild may help." + fi + if test "$build_old_libs" = no; then + oldlibs="$output_objdir/$libname.$libext" + build_libtool_libs=module + build_old_libs=yes + else + build_libtool_libs=no + fi + else + $echo "*** The inter-library dependencies that have been dropped here will be" + $echo "*** automatically added whenever a program is linked with this library" + $echo "*** or is declared to -dlopen it." + + if test "$allow_undefined" = no; then + $echo + $echo "*** Since this library must not contain undefined symbols," + $echo "*** because either the platform does not support them or" + $echo "*** it was explicitly requested with -no-undefined," + $echo "*** libtool will only create a static version of it." + if test "$build_old_libs" = no; then + oldlibs="$output_objdir/$libname.$libext" + build_libtool_libs=module + build_old_libs=yes + else + build_libtool_libs=no + fi + fi + fi + fi + # Done checking deplibs! + deplibs=$newdeplibs + fi + + # All the library-specific variables (install_libdir is set above). + library_names= + old_library= + dlname= + + # Test again, we may have decided not to build it any more + if test "$build_libtool_libs" = yes; then + if test "$hardcode_into_libs" = yes; then + # Hardcode the library paths + hardcode_libdirs= + dep_rpath= + rpath="$finalize_rpath" + test "$mode" != relink && rpath="$compile_rpath$rpath" + for libdir in $rpath; do + if test -n "$hardcode_libdir_flag_spec"; then + if test -n "$hardcode_libdir_separator"; then + if test -z "$hardcode_libdirs"; then + hardcode_libdirs="$libdir" + else + # Just accumulate the unique libdirs. + case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in + *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) + ;; + *) + hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir" + ;; + esac + fi + else + eval flag=\"$hardcode_libdir_flag_spec\" + dep_rpath="$dep_rpath $flag" + fi + elif test -n "$runpath_var"; then + case "$perm_rpath " in + *" $libdir "*) ;; + *) perm_rpath="$perm_rpath $libdir" ;; + esac + fi + done + # Substitute the hardcoded libdirs into the rpath. + if test -n "$hardcode_libdir_separator" && + test -n "$hardcode_libdirs"; then + libdir="$hardcode_libdirs" + if test -n "$hardcode_libdir_flag_spec_ld"; then + eval dep_rpath=\"$hardcode_libdir_flag_spec_ld\" + else + eval dep_rpath=\"$hardcode_libdir_flag_spec\" + fi + fi + if test -n "$runpath_var" && test -n "$perm_rpath"; then + # We should set the runpath_var. + rpath= + for dir in $perm_rpath; do + rpath="$rpath$dir:" + done + eval "$runpath_var='$rpath\$$runpath_var'; export $runpath_var" + fi + test -n "$dep_rpath" && deplibs="$dep_rpath $deplibs" + fi + + shlibpath="$finalize_shlibpath" + test "$mode" != relink && shlibpath="$compile_shlibpath$shlibpath" + if test -n "$shlibpath"; then + eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var" + fi + + # Get the real and link names of the library. + eval shared_ext=\"$shrext_cmds\" + eval library_names=\"$library_names_spec\" + set dummy $library_names + realname="$2" + shift; shift + + if test -n "$soname_spec"; then + eval soname=\"$soname_spec\" + else + soname="$realname" + fi + if test -z "$dlname"; then + dlname=$soname + fi + + lib="$output_objdir/$realname" + for link + do + linknames="$linknames $link" + done + + # Use standard objects if they are pic + test -z "$pic_flag" && libobjs=`$echo "X$libobjs" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP` + + # Prepare the list of exported symbols + if test -z "$export_symbols"; then + if test "$always_export_symbols" = yes || test -n "$export_symbols_regex"; then + $show "generating symbol list for \`$libname.la'" + export_symbols="$output_objdir/$libname.exp" + $run $rm $export_symbols + cmds=$export_symbols_cmds + save_ifs="$IFS"; IFS='~' + for cmd in $cmds; do + IFS="$save_ifs" + eval cmd=\"$cmd\" + if len=`expr "X$cmd" : ".*"` && + test "$len" -le "$max_cmd_len" || test "$max_cmd_len" -le -1; then + $show "$cmd" + $run eval "$cmd" || exit $? + skipped_export=false + else + # The command line is too long to execute in one step. + $show "using reloadable object file for export list..." + skipped_export=: + fi + done + IFS="$save_ifs" + if test -n "$export_symbols_regex"; then + $show "$EGREP -e \"$export_symbols_regex\" \"$export_symbols\" > \"${export_symbols}T\"" + $run eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' + $show "$mv \"${export_symbols}T\" \"$export_symbols\"" + $run eval '$mv "${export_symbols}T" "$export_symbols"' + fi + fi + fi + + if test -n "$export_symbols" && test -n "$include_expsyms"; then + $run eval '$echo "X$include_expsyms" | $SP2NL >> "$export_symbols"' + fi + + tmp_deplibs= + for test_deplib in $deplibs; do + case " $convenience " in + *" $test_deplib "*) ;; + *) + tmp_deplibs="$tmp_deplibs $test_deplib" + ;; + esac + done + deplibs="$tmp_deplibs" + + if test -n "$convenience"; then + if test -n "$whole_archive_flag_spec"; then + save_libobjs=$libobjs + eval libobjs=\"\$libobjs $whole_archive_flag_spec\" + else + gentop="$output_objdir/${outputname}x" + $show "${rm}r $gentop" + $run ${rm}r "$gentop" + $show "$mkdir $gentop" + $run $mkdir "$gentop" + status=$? + if test "$status" -ne 0 && test ! -d "$gentop"; then + exit $status + fi + generated="$generated $gentop" + + for xlib in $convenience; do + # Extract the objects. + case $xlib in + [\\/]* | [A-Za-z]:[\\/]*) xabs="$xlib" ;; + *) xabs=`pwd`"/$xlib" ;; + esac + xlib=`$echo "X$xlib" | $Xsed -e 's%^.*/%%'` + xdir="$gentop/$xlib" + + $show "${rm}r $xdir" + $run ${rm}r "$xdir" + $show "$mkdir $xdir" + $run $mkdir "$xdir" + status=$? + if test "$status" -ne 0 && test ! -d "$xdir"; then + exit $status + fi + # We will extract separately just the conflicting names and we will no + # longer touch any unique names. It is faster to leave these extract + # automatically by $AR in one run. + $show "(cd $xdir && $AR x $xabs)" + $run eval "(cd \$xdir && $AR x \$xabs)" || exit $? + if ($AR t "$xabs" | sort | sort -uc >/dev/null 2>&1); then + : + else + $echo "$modename: warning: object name conflicts; renaming object files" 1>&2 + $echo "$modename: warning: to ensure that they will not overwrite" 1>&2 + $AR t "$xabs" | sort | uniq -cd | while read -r count name + do + i=1 + while test "$i" -le "$count" + do + # Put our $i before any first dot (extension) + # Never overwrite any file + name_to="$name" + while test "X$name_to" = "X$name" || test -f "$xdir/$name_to" + do + name_to=`$echo "X$name_to" | $Xsed -e "s/\([^.]*\)/\1-$i/"` + done + $show "(cd $xdir && $AR xN $i $xabs '$name' && $mv '$name' '$name_to')" + $run eval "(cd \$xdir && $AR xN $i \$xabs '$name' && $mv '$name' '$name_to')" || exit $? + i=`expr $i + 1` + done + done + fi + + libobjs="$libobjs "`find $xdir -name \*.$objext -print -o -name \*.lo -print | $NL2SP` + done + fi + fi + + if test "$thread_safe" = yes && test -n "$thread_safe_flag_spec"; then + eval flag=\"$thread_safe_flag_spec\" + linker_flags="$linker_flags $flag" + fi + + # Make a backup of the uninstalled library when relinking + if test "$mode" = relink; then + $run eval '(cd $output_objdir && $rm ${realname}U && $mv $realname ${realname}U)' || exit $? + fi + + # Do each of the archive commands. + if test "$module" = yes && test -n "$module_cmds" ; then + if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then + eval test_cmds=\"$module_expsym_cmds\" + cmds=$module_expsym_cmds + else + eval test_cmds=\"$module_cmds\" + cmds=$module_cmds + fi + else + if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then + eval test_cmds=\"$archive_expsym_cmds\" + cmds=$archive_expsym_cmds + else + eval test_cmds=\"$archive_cmds\" + cmds=$archive_cmds + fi + fi + + if test "X$skipped_export" != "X:" && len=`expr "X$test_cmds" : ".*"` && + test "$len" -le "$max_cmd_len" || test "$max_cmd_len" -le -1; then + : + else + # The command line is too long to link in one step, link piecewise. + $echo "creating reloadable object files..." + + # Save the value of $output and $libobjs because we want to + # use them later. If we have whole_archive_flag_spec, we + # want to use save_libobjs as it was before + # whole_archive_flag_spec was expanded, because we can't + # assume the linker understands whole_archive_flag_spec. + # This may have to be revisited, in case too many + # convenience libraries get linked in and end up exceeding + # the spec. + if test -z "$convenience" || test -z "$whole_archive_flag_spec"; then + save_libobjs=$libobjs + fi + save_output=$output + + # Clear the reloadable object creation command queue and + # initialize k to one. + test_cmds= + concat_cmds= + objlist= + delfiles= + last_robj= + k=1 + output=$output_objdir/$save_output-${k}.$objext + # Loop over the list of objects to be linked. + for obj in $save_libobjs + do + eval test_cmds=\"$reload_cmds $objlist $last_robj\" + if test "X$objlist" = X || + { len=`expr "X$test_cmds" : ".*"` && + test "$len" -le "$max_cmd_len"; }; then + objlist="$objlist $obj" + else + # The command $test_cmds is almost too long, add a + # command to the queue. + if test "$k" -eq 1 ; then + # The first file doesn't have a previous command to add. + eval concat_cmds=\"$reload_cmds $objlist $last_robj\" + else + # All subsequent reloadable object files will link in + # the last one created. + eval concat_cmds=\"\$concat_cmds~$reload_cmds $objlist $last_robj\" + fi + last_robj=$output_objdir/$save_output-${k}.$objext + k=`expr $k + 1` + output=$output_objdir/$save_output-${k}.$objext + objlist=$obj + len=1 + fi + done + # Handle the remaining objects by creating one last + # reloadable object file. All subsequent reloadable object + # files will link in the last one created. + test -z "$concat_cmds" || concat_cmds=$concat_cmds~ + eval concat_cmds=\"\${concat_cmds}$reload_cmds $objlist $last_robj\" + + if ${skipped_export-false}; then + $show "generating symbol list for \`$libname.la'" + export_symbols="$output_objdir/$libname.exp" + $run $rm $export_symbols + libobjs=$output + # Append the command to create the export file. + eval concat_cmds=\"\$concat_cmds~$export_symbols_cmds\" + fi + + # Set up a command to remove the reloadale object files + # after they are used. + i=0 + while test "$i" -lt "$k" + do + i=`expr $i + 1` + delfiles="$delfiles $output_objdir/$save_output-${i}.$objext" + done + + $echo "creating a temporary reloadable object file: $output" + + # Loop through the commands generated above and execute them. + save_ifs="$IFS"; IFS='~' + for cmd in $concat_cmds; do + IFS="$save_ifs" + $show "$cmd" + $run eval "$cmd" || exit $? + done + IFS="$save_ifs" + + libobjs=$output + # Restore the value of output. + output=$save_output + + if test -n "$convenience" && test -n "$whole_archive_flag_spec"; then + eval libobjs=\"\$libobjs $whole_archive_flag_spec\" + fi + # Expand the library linking commands again to reset the + # value of $libobjs for piecewise linking. + + # Do each of the archive commands. + if test "$module" = yes && test -n "$module_cmds" ; then + if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then + cmds=$module_expsym_cmds + else + cmds=$module_cmds + fi + else + if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then + cmds=$archive_expsym_cmds + else + cmds=$archive_cmds + fi + fi + + # Append the command to remove the reloadable object files + # to the just-reset $cmds. + eval cmds=\"\$cmds~\$rm $delfiles\" + fi + save_ifs="$IFS"; IFS='~' + for cmd in $cmds; do + IFS="$save_ifs" + eval cmd=\"$cmd\" + $show "$cmd" + $run eval "$cmd" || exit $? + done + IFS="$save_ifs" + + # Restore the uninstalled library and exit + if test "$mode" = relink; then + $run eval '(cd $output_objdir && $rm ${realname}T && $mv $realname ${realname}T && $mv "$realname"U $realname)' || exit $? + exit $EXIT_SUCCESS + fi + + # Create links to the real library. + for linkname in $linknames; do + if test "$realname" != "$linkname"; then + $show "(cd $output_objdir && $rm $linkname && $LN_S $realname $linkname)" + $run eval '(cd $output_objdir && $rm $linkname && $LN_S $realname $linkname)' || exit $? + fi + done + + # If -module or -export-dynamic was specified, set the dlname. + if test "$module" = yes || test "$export_dynamic" = yes; then + # On all known operating systems, these are identical. + dlname="$soname" + fi + fi + ;; + + obj) + if test -n "$deplibs"; then + $echo "$modename: warning: \`-l' and \`-L' are ignored for objects" 1>&2 + fi + + if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then + $echo "$modename: warning: \`-dlopen' is ignored for objects" 1>&2 + fi + + if test -n "$rpath"; then + $echo "$modename: warning: \`-rpath' is ignored for objects" 1>&2 + fi + + if test -n "$xrpath"; then + $echo "$modename: warning: \`-R' is ignored for objects" 1>&2 + fi + + if test -n "$vinfo"; then + $echo "$modename: warning: \`-version-info' is ignored for objects" 1>&2 + fi + + if test -n "$release"; then + $echo "$modename: warning: \`-release' is ignored for objects" 1>&2 + fi + + case $output in + *.lo) + if test -n "$objs$old_deplibs"; then + $echo "$modename: cannot build library object \`$output' from non-libtool objects" 1>&2 + exit $EXIT_FAILURE + fi + libobj="$output" + obj=`$echo "X$output" | $Xsed -e "$lo2o"` + ;; + *) + libobj= + obj="$output" + ;; + esac + + # Delete the old objects. + $run $rm $obj $libobj + + # Objects from convenience libraries. This assumes + # single-version convenience libraries. Whenever we create + # different ones for PIC/non-PIC, this we'll have to duplicate + # the extraction. + reload_conv_objs= + gentop= + # reload_cmds runs $LD directly, so let us get rid of + # -Wl from whole_archive_flag_spec + wl= + + if test -n "$convenience"; then + if test -n "$whole_archive_flag_spec"; then + eval reload_conv_objs=\"\$reload_objs $whole_archive_flag_spec\" + else + gentop="$output_objdir/${obj}x" + $show "${rm}r $gentop" + $run ${rm}r "$gentop" + $show "$mkdir $gentop" + $run $mkdir "$gentop" + status=$? + if test "$status" -ne 0 && test ! -d "$gentop"; then + exit $status + fi + generated="$generated $gentop" + + for xlib in $convenience; do + # Extract the objects. + case $xlib in + [\\/]* | [A-Za-z]:[\\/]*) xabs="$xlib" ;; + *) xabs=`pwd`"/$xlib" ;; + esac + xlib=`$echo "X$xlib" | $Xsed -e 's%^.*/%%'` + xdir="$gentop/$xlib" + + $show "${rm}r $xdir" + $run ${rm}r "$xdir" + $show "$mkdir $xdir" + $run $mkdir "$xdir" + status=$? + if test "$status" -ne 0 && test ! -d "$xdir"; then + exit $status + fi + # We will extract separately just the conflicting names and we will no + # longer touch any unique names. It is faster to leave these extract + # automatically by $AR in one run. + $show "(cd $xdir && $AR x $xabs)" + $run eval "(cd \$xdir && $AR x \$xabs)" || exit $? + if ($AR t "$xabs" | sort | sort -uc >/dev/null 2>&1); then + : + else + $echo "$modename: warning: object name conflicts; renaming object files" 1>&2 + $echo "$modename: warning: to ensure that they will not overwrite" 1>&2 + $AR t "$xabs" | sort | uniq -cd | while read -r count name + do + i=1 + while test "$i" -le "$count" + do + # Put our $i before any first dot (extension) + # Never overwrite any file + name_to="$name" + while test "X$name_to" = "X$name" || test -f "$xdir/$name_to" + do + name_to=`$echo "X$name_to" | $Xsed -e "s/\([^.]*\)/\1-$i/"` + done + $show "(cd $xdir && $AR xN $i $xabs '$name' && $mv '$name' '$name_to')" + $run eval "(cd \$xdir && $AR xN $i \$xabs '$name' && $mv '$name' '$name_to')" || exit $? + i=`expr $i + 1` + done + done + fi + + reload_conv_objs="$reload_objs "`find $xdir -name \*.$objext -print -o -name \*.lo -print | $NL2SP` + done + fi + fi + + # Create the old-style object. + reload_objs="$objs$old_deplibs "`$echo "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}$'/d' -e '/\.lib$/d' -e "$lo2o" | $NL2SP`" $reload_conv_objs" ### testsuite: skip nested quoting test + + output="$obj" + cmds=$reload_cmds + save_ifs="$IFS"; IFS='~' + for cmd in $cmds; do + IFS="$save_ifs" + eval cmd=\"$cmd\" + $show "$cmd" + $run eval "$cmd" || exit $? + done + IFS="$save_ifs" + + # Exit if we aren't doing a library object file. + if test -z "$libobj"; then + if test -n "$gentop"; then + $show "${rm}r $gentop" + $run ${rm}r $gentop + fi + + exit $EXIT_SUCCESS + fi + + if test "$build_libtool_libs" != yes; then + if test -n "$gentop"; then + $show "${rm}r $gentop" + $run ${rm}r $gentop + fi + + # Create an invalid libtool object if no PIC, so that we don't + # accidentally link it into a program. + # $show "echo timestamp > $libobj" + # $run eval "echo timestamp > $libobj" || exit $? + exit $EXIT_SUCCESS + fi + + if test -n "$pic_flag" || test "$pic_mode" != default; then + # Only do commands if we really have different PIC objects. + reload_objs="$libobjs $reload_conv_objs" + output="$libobj" + cmds=$reload_cmds + save_ifs="$IFS"; IFS='~' + for cmd in $cmds; do + IFS="$save_ifs" + eval cmd=\"$cmd\" + $show "$cmd" + $run eval "$cmd" || exit $? + done + IFS="$save_ifs" + fi + + if test -n "$gentop"; then + $show "${rm}r $gentop" + $run ${rm}r $gentop + fi + + exit $EXIT_SUCCESS + ;; + + prog) + case $host in + *cygwin*) output=`$echo $output | ${SED} -e 's,.exe$,,;s,$,.exe,'` ;; + esac + if test -n "$vinfo"; then + $echo "$modename: warning: \`-version-info' is ignored for programs" 1>&2 + fi + + if test -n "$release"; then + $echo "$modename: warning: \`-release' is ignored for programs" 1>&2 + fi + + if test "$preload" = yes; then + if test "$dlopen_support" = unknown && test "$dlopen_self" = unknown && + test "$dlopen_self_static" = unknown; then + $echo "$modename: warning: \`AC_LIBTOOL_DLOPEN' not used. Assuming no dlopen support." + fi + fi + + case $host in + *-*-rhapsody* | *-*-darwin1.[012]) + # On Rhapsody replace the C library is the System framework + compile_deplibs=`$echo "X $compile_deplibs" | $Xsed -e 's/ -lc / -framework System /'` + finalize_deplibs=`$echo "X $finalize_deplibs" | $Xsed -e 's/ -lc / -framework System /'` + ;; + esac + + case $host in + *darwin*) + # Don't allow lazy linking, it breaks C++ global constructors + if test "$tagname" = CXX ; then + compile_command="$compile_command ${wl}-bind_at_load" + finalize_command="$finalize_command ${wl}-bind_at_load" + fi + ;; + esac + + compile_command="$compile_command $compile_deplibs" + finalize_command="$finalize_command $finalize_deplibs" + + if test -n "$rpath$xrpath"; then + # If the user specified any rpath flags, then add them. + for libdir in $rpath $xrpath; do + # This is the magic to use -rpath. + case "$finalize_rpath " in + *" $libdir "*) ;; + *) finalize_rpath="$finalize_rpath $libdir" ;; + esac + done + fi + + # Now hardcode the library paths + rpath= + hardcode_libdirs= + for libdir in $compile_rpath $finalize_rpath; do + if test -n "$hardcode_libdir_flag_spec"; then + if test -n "$hardcode_libdir_separator"; then + if test -z "$hardcode_libdirs"; then + hardcode_libdirs="$libdir" + else + # Just accumulate the unique libdirs. + case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in + *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) + ;; + *) + hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir" + ;; + esac + fi + else + eval flag=\"$hardcode_libdir_flag_spec\" + rpath="$rpath $flag" + fi + elif test -n "$runpath_var"; then + case "$perm_rpath " in + *" $libdir "*) ;; + *) perm_rpath="$perm_rpath $libdir" ;; + esac + fi + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*) + case :$dllsearchpath: in + *":$libdir:"*) ;; + *) dllsearchpath="$dllsearchpath:$libdir";; + esac + ;; + esac + done + # Substitute the hardcoded libdirs into the rpath. + if test -n "$hardcode_libdir_separator" && + test -n "$hardcode_libdirs"; then + libdir="$hardcode_libdirs" + eval rpath=\" $hardcode_libdir_flag_spec\" + fi + compile_rpath="$rpath" + + rpath= + hardcode_libdirs= + for libdir in $finalize_rpath; do + if test -n "$hardcode_libdir_flag_spec"; then + if test -n "$hardcode_libdir_separator"; then + if test -z "$hardcode_libdirs"; then + hardcode_libdirs="$libdir" + else + # Just accumulate the unique libdirs. + case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in + *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) + ;; + *) + hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir" + ;; + esac + fi + else + eval flag=\"$hardcode_libdir_flag_spec\" + rpath="$rpath $flag" + fi + elif test -n "$runpath_var"; then + case "$finalize_perm_rpath " in + *" $libdir "*) ;; + *) finalize_perm_rpath="$finalize_perm_rpath $libdir" ;; + esac + fi + done + # Substitute the hardcoded libdirs into the rpath. + if test -n "$hardcode_libdir_separator" && + test -n "$hardcode_libdirs"; then + libdir="$hardcode_libdirs" + eval rpath=\" $hardcode_libdir_flag_spec\" + fi + finalize_rpath="$rpath" + + if test -n "$libobjs" && test "$build_old_libs" = yes; then + # Transform all the library objects into standard objects. + compile_command=`$echo "X$compile_command" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP` + finalize_command=`$echo "X$finalize_command" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP` + fi + + dlsyms= + if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then + if test -n "$NM" && test -n "$global_symbol_pipe"; then + dlsyms="${outputname}S.c" + else + $echo "$modename: not configured to extract global symbols from dlpreopened files" 1>&2 + fi + fi + + if test -n "$dlsyms"; then + case $dlsyms in + "") ;; + *.c) + # Discover the nlist of each of the dlfiles. + nlist="$output_objdir/${outputname}.nm" + + $show "$rm $nlist ${nlist}S ${nlist}T" + $run $rm "$nlist" "${nlist}S" "${nlist}T" + + # Parse the name list into a source file. + $show "creating $output_objdir/$dlsyms" + + test -z "$run" && $echo > "$output_objdir/$dlsyms" "\ +/* $dlsyms - symbol resolution table for \`$outputname' dlsym emulation. */ +/* Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP */ + +#ifdef __cplusplus +extern \"C\" { +#endif + +/* Prevent the only kind of declaration conflicts we can make. */ +#define lt_preloaded_symbols some_other_symbol + +/* External symbol declarations for the compiler. */\ +" + + if test "$dlself" = yes; then + $show "generating symbol list for \`$output'" + + test -z "$run" && $echo ': @PROGRAM@ ' > "$nlist" + + # Add our own program objects to the symbol list. + progfiles=`$echo "X$objs$old_deplibs" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP` + for arg in $progfiles; do + $show "extracting global C symbols from \`$arg'" + $run eval "$NM $arg | $global_symbol_pipe >> '$nlist'" + done + + if test -n "$exclude_expsyms"; then + $run eval '$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T' + $run eval '$mv "$nlist"T "$nlist"' + fi + + if test -n "$export_symbols_regex"; then + $run eval '$EGREP -e "$export_symbols_regex" "$nlist" > "$nlist"T' + $run eval '$mv "$nlist"T "$nlist"' + fi + + # Prepare the list of exported symbols + if test -z "$export_symbols"; then + export_symbols="$output_objdir/$output.exp" + $run $rm $export_symbols + $run eval "${SED} -n -e '/^: @PROGRAM@$/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"' + else + $run eval "${SED} -e 's/\([][.*^$]\)/\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$output.exp"' + $run eval 'grep -f "$output_objdir/$output.exp" < "$nlist" > "$nlist"T' + $run eval 'mv "$nlist"T "$nlist"' + fi + fi + + for arg in $dlprefiles; do + $show "extracting global C symbols from \`$arg'" + name=`$echo "$arg" | ${SED} -e 's%^.*/%%'` + $run eval '$echo ": $name " >> "$nlist"' + $run eval "$NM $arg | $global_symbol_pipe >> '$nlist'" + done + + if test -z "$run"; then + # Make sure we have at least an empty file. + test -f "$nlist" || : > "$nlist" + + if test -n "$exclude_expsyms"; then + $EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T + $mv "$nlist"T "$nlist" + fi + + # Try sorting and uniquifying the output. + if grep -v "^: " < "$nlist" | + if sort -k 3 /dev/null 2>&1; then + sort -k 3 + else + sort +2 + fi | + uniq > "$nlist"S; then + : + else + grep -v "^: " < "$nlist" > "$nlist"S + fi + + if test -f "$nlist"S; then + eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$dlsyms"' + else + $echo '/* NONE */' >> "$output_objdir/$dlsyms" + fi + + $echo >> "$output_objdir/$dlsyms" "\ + +#undef lt_preloaded_symbols + +#if defined (__STDC__) && __STDC__ +# define lt_ptr void * +#else +# define lt_ptr char * +# define const +#endif + +/* The mapping between symbol names and symbols. */ +const struct { + const char *name; + lt_ptr address; +} +lt_preloaded_symbols[] = +{\ +" + + eval "$global_symbol_to_c_name_address" < "$nlist" >> "$output_objdir/$dlsyms" + + $echo >> "$output_objdir/$dlsyms" "\ + {0, (lt_ptr) 0} +}; + +/* This works around a problem in FreeBSD linker */ +#ifdef FREEBSD_WORKAROUND +static const void *lt_preloaded_setup() { + return lt_preloaded_symbols; +} +#endif + +#ifdef __cplusplus +} +#endif\ +" + fi + + pic_flag_for_symtable= + case $host in + # compiling the symbol table file with pic_flag works around + # a FreeBSD bug that causes programs to crash when -lm is + # linked before any other PIC object. But we must not use + # pic_flag when linking with -static. The problem exists in + # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1. + *-*-freebsd2*|*-*-freebsd3.0*|*-*-freebsdelf3.0*) + case "$compile_command " in + *" -static "*) ;; + *) pic_flag_for_symtable=" $pic_flag -DFREEBSD_WORKAROUND";; + esac;; + *-*-hpux*) + case "$compile_command " in + *" -static "*) ;; + *) pic_flag_for_symtable=" $pic_flag";; + esac + esac + + # Now compile the dynamic symbol file. + $show "(cd $output_objdir && $LTCC -c$no_builtin_flag$pic_flag_for_symtable \"$dlsyms\")" + $run eval '(cd $output_objdir && $LTCC -c$no_builtin_flag$pic_flag_for_symtable "$dlsyms")' || exit $? + + # Clean up the generated files. + $show "$rm $output_objdir/$dlsyms $nlist ${nlist}S ${nlist}T" + $run $rm "$output_objdir/$dlsyms" "$nlist" "${nlist}S" "${nlist}T" + + # Transform the symbol file into the correct name. + compile_command=`$echo "X$compile_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%"` + finalize_command=`$echo "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%"` + ;; + *) + $echo "$modename: unknown suffix for \`$dlsyms'" 1>&2 + exit $EXIT_FAILURE + ;; + esac + else + # We keep going just in case the user didn't refer to + # lt_preloaded_symbols. The linker will fail if global_symbol_pipe + # really was required. + + # Nullify the symbol file. + compile_command=`$echo "X$compile_command" | $Xsed -e "s% @SYMFILE@%%"` + finalize_command=`$echo "X$finalize_command" | $Xsed -e "s% @SYMFILE@%%"` + fi + + if test "$need_relink" = no || test "$build_libtool_libs" != yes; then + # Replace the output file specification. + compile_command=`$echo "X$compile_command" | $Xsed -e 's%@OUTPUT@%'"$output"'%g'` + link_command="$compile_command$compile_rpath" + + # We have no uninstalled library dependencies, so finalize right now. + $show "$link_command" + $run eval "$link_command" + status=$? + + # Delete the generated files. + if test -n "$dlsyms"; then + $show "$rm $output_objdir/${outputname}S.${objext}" + $run $rm "$output_objdir/${outputname}S.${objext}" + fi + + exit $status + fi + + if test -n "$shlibpath_var"; then + # We should set the shlibpath_var + rpath= + for dir in $temp_rpath; do + case $dir in + [\\/]* | [A-Za-z]:[\\/]*) + # Absolute path. + rpath="$rpath$dir:" + ;; + *) + # Relative path: add a thisdir entry. + rpath="$rpath\$thisdir/$dir:" + ;; + esac + done + temp_rpath="$rpath" + fi + + if test -n "$compile_shlibpath$finalize_shlibpath"; then + compile_command="$shlibpath_var=\"$compile_shlibpath$finalize_shlibpath\$$shlibpath_var\" $compile_command" + fi + if test -n "$finalize_shlibpath"; then + finalize_command="$shlibpath_var=\"$finalize_shlibpath\$$shlibpath_var\" $finalize_command" + fi + + compile_var= + finalize_var= + if test -n "$runpath_var"; then + if test -n "$perm_rpath"; then + # We should set the runpath_var. + rpath= + for dir in $perm_rpath; do + rpath="$rpath$dir:" + done + compile_var="$runpath_var=\"$rpath\$$runpath_var\" " + fi + if test -n "$finalize_perm_rpath"; then + # We should set the runpath_var. + rpath= + for dir in $finalize_perm_rpath; do + rpath="$rpath$dir:" + done + finalize_var="$runpath_var=\"$rpath\$$runpath_var\" " + fi + fi + + if test "$no_install" = yes; then + # We don't need to create a wrapper script. + link_command="$compile_var$compile_command$compile_rpath" + # Replace the output file specification. + link_command=`$echo "X$link_command" | $Xsed -e 's%@OUTPUT@%'"$output"'%g'` + # Delete the old output file. + $run $rm $output + # Link the executable and exit + $show "$link_command" + $run eval "$link_command" || exit $? + exit $EXIT_SUCCESS + fi + + if test "$hardcode_action" = relink; then + # Fast installation is not supported + link_command="$compile_var$compile_command$compile_rpath" + relink_command="$finalize_var$finalize_command$finalize_rpath" + + $echo "$modename: warning: this platform does not like uninstalled shared libraries" 1>&2 + $echo "$modename: \`$output' will be relinked during installation" 1>&2 + else + if test "$fast_install" != no; then + link_command="$finalize_var$compile_command$finalize_rpath" + if test "$fast_install" = yes; then + relink_command=`$echo "X$compile_var$compile_command$compile_rpath" | $Xsed -e 's%@OUTPUT@%\$progdir/\$file%g'` + else + # fast_install is set to needless + relink_command= + fi + else + link_command="$compile_var$compile_command$compile_rpath" + relink_command="$finalize_var$finalize_command$finalize_rpath" + fi + fi + + # Replace the output file specification. + link_command=`$echo "X$link_command" | $Xsed -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'` + + # Delete the old output files. + $run $rm $output $output_objdir/$outputname $output_objdir/lt-$outputname + + $show "$link_command" + $run eval "$link_command" || exit $? + + # Now create the wrapper script. + $show "creating $output" + + # Quote the relink command for shipping. + if test -n "$relink_command"; then + # Preserve any variables that may affect compiler behavior + for var in $variables_saved_for_relink; do + if eval test -z \"\${$var+set}\"; then + relink_command="{ test -z \"\${$var+set}\" || unset $var || { $var=; export $var; }; }; $relink_command" + elif eval var_value=\$$var; test -z "$var_value"; then + relink_command="$var=; export $var; $relink_command" + else + var_value=`$echo "X$var_value" | $Xsed -e "$sed_quote_subst"` + relink_command="$var=\"$var_value\"; export $var; $relink_command" + fi + done + relink_command="(cd `pwd`; $relink_command)" + relink_command=`$echo "X$relink_command" | $Xsed -e "$sed_quote_subst"` + fi + + # Quote $echo for shipping. + if test "X$echo" = "X$SHELL $progpath --fallback-echo"; then + case $progpath in + [\\/]* | [A-Za-z]:[\\/]*) qecho="$SHELL $progpath --fallback-echo";; + *) qecho="$SHELL `pwd`/$progpath --fallback-echo";; + esac + qecho=`$echo "X$qecho" | $Xsed -e "$sed_quote_subst"` + else + qecho=`$echo "X$echo" | $Xsed -e "$sed_quote_subst"` + fi + + # Only actually do things if our run command is non-null. + if test -z "$run"; then + # win32 will think the script is a binary if it has + # a .exe suffix, so we strip it off here. + case $output in + *.exe) output=`$echo $output|${SED} 's,.exe$,,'` ;; + esac + # test for cygwin because mv fails w/o .exe extensions + case $host in + *cygwin*) + exeext=.exe + outputname=`$echo $outputname|${SED} 's,.exe$,,'` ;; + *) exeext= ;; + esac + case $host in + *cygwin* | *mingw* ) + cwrappersource=`$echo ${objdir}/lt-${output}.c` + cwrapper=`$echo ${output}.exe` + $rm $cwrappersource $cwrapper + trap "$rm $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15 + + cat > $cwrappersource <> $cwrappersource<<"EOF" +#include +#include +#include +#include +#include +#include + +#if defined(PATH_MAX) +# define LT_PATHMAX PATH_MAX +#elif defined(MAXPATHLEN) +# define LT_PATHMAX MAXPATHLEN +#else +# define LT_PATHMAX 1024 +#endif + +#ifndef DIR_SEPARATOR +#define DIR_SEPARATOR '/' +#endif + +#if defined (_WIN32) || defined (__MSDOS__) || defined (__DJGPP__) || \ + defined (__OS2__) +#define HAVE_DOS_BASED_FILE_SYSTEM +#ifndef DIR_SEPARATOR_2 +#define DIR_SEPARATOR_2 '\\' +#endif +#endif + +#ifndef DIR_SEPARATOR_2 +# define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR) +#else /* DIR_SEPARATOR_2 */ +# define IS_DIR_SEPARATOR(ch) \ + (((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2)) +#endif /* DIR_SEPARATOR_2 */ + +#define XMALLOC(type, num) ((type *) xmalloc ((num) * sizeof(type))) +#define XFREE(stale) do { \ + if (stale) { free ((void *) stale); stale = 0; } \ +} while (0) + +const char *program_name = NULL; + +void * xmalloc (size_t num); +char * xstrdup (const char *string); +char * basename (const char *name); +char * fnqualify(const char *path); +char * strendzap(char *str, const char *pat); +void lt_fatal (const char *message, ...); + +int +main (int argc, char *argv[]) +{ + char **newargz; + int i; + + program_name = (char *) xstrdup ((char *) basename (argv[0])); + newargz = XMALLOC(char *, argc+2); +EOF + + cat >> $cwrappersource <> $cwrappersource <<"EOF" + newargz[1] = fnqualify(argv[0]); + /* we know the script has the same name, without the .exe */ + /* so make sure newargz[1] doesn't end in .exe */ + strendzap(newargz[1],".exe"); + for (i = 1; i < argc; i++) + newargz[i+1] = xstrdup(argv[i]); + newargz[argc+1] = NULL; +EOF + + cat >> $cwrappersource <> $cwrappersource <<"EOF" +} + +void * +xmalloc (size_t num) +{ + void * p = (void *) malloc (num); + if (!p) + lt_fatal ("Memory exhausted"); + + return p; +} + +char * +xstrdup (const char *string) +{ + return string ? strcpy ((char *) xmalloc (strlen (string) + 1), string) : NULL +; +} + +char * +basename (const char *name) +{ + const char *base; + +#if defined (HAVE_DOS_BASED_FILE_SYSTEM) + /* Skip over the disk name in MSDOS pathnames. */ + if (isalpha (name[0]) && name[1] == ':') + name += 2; +#endif + + for (base = name; *name; name++) + if (IS_DIR_SEPARATOR (*name)) + base = name + 1; + return (char *) base; +} + +char * +fnqualify(const char *path) +{ + size_t size; + char *p; + char tmp[LT_PATHMAX + 1]; + + assert(path != NULL); + + /* Is it qualified already? */ +#if defined (HAVE_DOS_BASED_FILE_SYSTEM) + if (isalpha (path[0]) && path[1] == ':') + return xstrdup (path); +#endif + if (IS_DIR_SEPARATOR (path[0])) + return xstrdup (path); + + /* prepend the current directory */ + /* doesn't handle '~' */ + if (getcwd (tmp, LT_PATHMAX) == NULL) + lt_fatal ("getcwd failed"); + size = strlen(tmp) + 1 + strlen(path) + 1; /* +2 for '/' and '\0' */ + p = XMALLOC(char, size); + sprintf(p, "%s%c%s", tmp, DIR_SEPARATOR, path); + return p; +} + +char * +strendzap(char *str, const char *pat) +{ + size_t len, patlen; + + assert(str != NULL); + assert(pat != NULL); + + len = strlen(str); + patlen = strlen(pat); + + if (patlen <= len) + { + str += len - patlen; + if (strcmp(str, pat) == 0) + *str = '\0'; + } + return str; +} + +static void +lt_error_core (int exit_status, const char * mode, + const char * message, va_list ap) +{ + fprintf (stderr, "%s: %s: ", program_name, mode); + vfprintf (stderr, message, ap); + fprintf (stderr, ".\n"); + + if (exit_status >= 0) + exit (exit_status); +} + +void +lt_fatal (const char *message, ...) +{ + va_list ap; + va_start (ap, message); + lt_error_core (EXIT_FAILURE, "FATAL", message, ap); + va_end (ap); +} +EOF + # we should really use a build-platform specific compiler + # here, but OTOH, the wrappers (shell script and this C one) + # are only useful if you want to execute the "real" binary. + # Since the "real" binary is built for $host, then this + # wrapper might as well be built for $host, too. + $run $LTCC -s -o $cwrapper $cwrappersource + ;; + esac + $rm $output + trap "$rm $output; exit $EXIT_FAILURE" 1 2 15 + + $echo > $output "\ +#! $SHELL + +# $output - temporary wrapper script for $objdir/$outputname +# Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP +# +# The $output program cannot be directly executed until all the libtool +# libraries that it depends on are installed. +# +# This wrapper script should never be moved out of the build directory. +# If it is, it will not operate correctly. + +# Sed substitution that helps us do robust quoting. It backslashifies +# metacharacters that are still active within double-quoted strings. +Xsed='${SED} -e 1s/^X//' +sed_quote_subst='$sed_quote_subst' + +# The HP-UX ksh and POSIX shell print the target directory to stdout +# if CDPATH is set. +if test \"\${CDPATH+set}\" = set; then CDPATH=:; export CDPATH; fi + +relink_command=\"$relink_command\" + +# This environment variable determines our operation mode. +if test \"\$libtool_install_magic\" = \"$magic\"; then + # install mode needs the following variable: + notinst_deplibs='$notinst_deplibs' +else + # When we are sourced in execute mode, \$file and \$echo are already set. + if test \"\$libtool_execute_magic\" != \"$magic\"; then + echo=\"$qecho\" + file=\"\$0\" + # Make sure echo works. + if test \"X\$1\" = X--no-reexec; then + # Discard the --no-reexec flag, and continue. + shift + elif test \"X\`(\$echo '\t') 2>/dev/null\`\" = 'X\t'; then + # Yippee, \$echo works! + : + else + # Restart under the correct shell, and then maybe \$echo will work. + exec $SHELL \"\$0\" --no-reexec \${1+\"\$@\"} + fi + fi\ +" + $echo >> $output "\ + + # Find the directory that this script lives in. + thisdir=\`\$echo \"X\$file\" | \$Xsed -e 's%/[^/]*$%%'\` + test \"x\$thisdir\" = \"x\$file\" && thisdir=. + + # Follow symbolic links until we get to the real thisdir. + file=\`ls -ld \"\$file\" | ${SED} -n 's/.*-> //p'\` + while test -n \"\$file\"; do + destdir=\`\$echo \"X\$file\" | \$Xsed -e 's%/[^/]*\$%%'\` + + # If there was a directory component, then change thisdir. + if test \"x\$destdir\" != \"x\$file\"; then + case \"\$destdir\" in + [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;; + *) thisdir=\"\$thisdir/\$destdir\" ;; + esac + fi + + file=\`\$echo \"X\$file\" | \$Xsed -e 's%^.*/%%'\` + file=\`ls -ld \"\$thisdir/\$file\" | ${SED} -n 's/.*-> //p'\` + done + + # Try to get the absolute directory name. + absdir=\`cd \"\$thisdir\" && pwd\` + test -n \"\$absdir\" && thisdir=\"\$absdir\" +" + + if test "$fast_install" = yes; then + $echo >> $output "\ + program=lt-'$outputname'$exeext + progdir=\"\$thisdir/$objdir\" + + if test ! -f \"\$progdir/\$program\" || \\ + { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | ${SED} 1q\`; \\ + test \"X\$file\" != \"X\$progdir/\$program\"; }; then + + file=\"\$\$-\$program\" + + if test ! -d \"\$progdir\"; then + $mkdir \"\$progdir\" + else + $rm \"\$progdir/\$file\" + fi" + + $echo >> $output "\ + + # relink executable if necessary + if test -n \"\$relink_command\"; then + if relink_command_output=\`eval \$relink_command 2>&1\`; then : + else + $echo \"\$relink_command_output\" >&2 + $rm \"\$progdir/\$file\" + exit $EXIT_FAILURE + fi + fi + + $mv \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null || + { $rm \"\$progdir/\$program\"; + $mv \"\$progdir/\$file\" \"\$progdir/\$program\"; } + $rm \"\$progdir/\$file\" + fi" + else + $echo >> $output "\ + program='$outputname' + progdir=\"\$thisdir/$objdir\" +" + fi + + $echo >> $output "\ + + if test -f \"\$progdir/\$program\"; then" + + # Export our shlibpath_var if we have one. + if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then + $echo >> $output "\ + # Add our own library path to $shlibpath_var + $shlibpath_var=\"$temp_rpath\$$shlibpath_var\" + + # Some systems cannot cope with colon-terminated $shlibpath_var + # The second colon is a workaround for a bug in BeOS R4 sed + $shlibpath_var=\`\$echo \"X\$$shlibpath_var\" | \$Xsed -e 's/::*\$//'\` + + export $shlibpath_var +" + fi + + # fixup the dll searchpath if we need to. + if test -n "$dllsearchpath"; then + $echo >> $output "\ + # Add the dll search path components to the executable PATH + PATH=$dllsearchpath:\$PATH +" + fi + + $echo >> $output "\ + if test \"\$libtool_execute_magic\" != \"$magic\"; then + # Run the actual program with our arguments. +" + case $host in + # Backslashes separate directories on plain windows + *-*-mingw | *-*-os2*) + $echo >> $output "\ + exec \$progdir\\\\\$program \${1+\"\$@\"} +" + ;; + + *) + $echo >> $output "\ + exec \$progdir/\$program \${1+\"\$@\"} +" + ;; + esac + $echo >> $output "\ + \$echo \"\$0: cannot exec \$program \${1+\"\$@\"}\" + exit $EXIT_FAILURE + fi + else + # The program doesn't exist. + \$echo \"\$0: error: \$progdir/\$program does not exist\" 1>&2 + \$echo \"This script is just a wrapper for \$program.\" 1>&2 + $echo \"See the $PACKAGE documentation for more information.\" 1>&2 + exit $EXIT_FAILURE + fi +fi\ +" + chmod +x $output + fi + exit $EXIT_SUCCESS + ;; + esac + + # See if we need to build an old-fashioned archive. + for oldlib in $oldlibs; do + + if test "$build_libtool_libs" = convenience; then + oldobjs="$libobjs_save" + addlibs="$convenience" + build_libtool_libs=no + else + if test "$build_libtool_libs" = module; then + oldobjs="$libobjs_save" + build_libtool_libs=no + else + oldobjs="$old_deplibs $non_pic_objects" + fi + addlibs="$old_convenience" + fi + + if test -n "$addlibs"; then + gentop="$output_objdir/${outputname}x" + $show "${rm}r $gentop" + $run ${rm}r "$gentop" + $show "$mkdir $gentop" + $run $mkdir "$gentop" + status=$? + if test "$status" -ne 0 && test ! -d "$gentop"; then + exit $status + fi + generated="$generated $gentop" + + # Add in members from convenience archives. + for xlib in $addlibs; do + # Extract the objects. + case $xlib in + [\\/]* | [A-Za-z]:[\\/]*) xabs="$xlib" ;; + *) xabs=`pwd`"/$xlib" ;; + esac + xlib=`$echo "X$xlib" | $Xsed -e 's%^.*/%%'` + xdir="$gentop/$xlib" + + $show "${rm}r $xdir" + $run ${rm}r "$xdir" + $show "$mkdir $xdir" + $run $mkdir "$xdir" + status=$? + if test "$status" -ne 0 && test ! -d "$xdir"; then + exit $status + fi + # We will extract separately just the conflicting names and we will no + # longer touch any unique names. It is faster to leave these extract + # automatically by $AR in one run. + $show "(cd $xdir && $AR x $xabs)" + $run eval "(cd \$xdir && $AR x \$xabs)" || exit $? + if ($AR t "$xabs" | sort | sort -uc >/dev/null 2>&1); then + : + else + $echo "$modename: warning: object name conflicts; renaming object files" 1>&2 + $echo "$modename: warning: to ensure that they will not overwrite" 1>&2 + $AR t "$xabs" | sort | uniq -cd | while read -r count name + do + i=1 + while test "$i" -le "$count" + do + # Put our $i before any first dot (extension) + # Never overwrite any file + name_to="$name" + while test "X$name_to" = "X$name" || test -f "$xdir/$name_to" + do + name_to=`$echo "X$name_to" | $Xsed -e "s/\([^.]*\)/\1-$i/"` + done + $show "(cd $xdir && $AR xN $i $xabs '$name' && $mv '$name' '$name_to')" + $run eval "(cd \$xdir && $AR xN $i \$xabs '$name' && $mv '$name' '$name_to')" || exit $? + i=`expr $i + 1` + done + done + fi + + oldobjs="$oldobjs "`find $xdir -name \*.${objext} -print -o -name \*.lo -print | $NL2SP` + done + fi + + # Do each command in the archive commands. + if test -n "$old_archive_from_new_cmds" && test "$build_libtool_libs" = yes; then + cmds=$old_archive_from_new_cmds + else + eval cmds=\"$old_archive_cmds\" + + if len=`expr "X$cmds" : ".*"` && + test "$len" -le "$max_cmd_len" || test "$max_cmd_len" -le -1; then + cmds=$old_archive_cmds + else + # the command line is too long to link in one step, link in parts + $echo "using piecewise archive linking..." + save_RANLIB=$RANLIB + RANLIB=: + objlist= + concat_cmds= + save_oldobjs=$oldobjs + # GNU ar 2.10+ was changed to match POSIX; thus no paths are + # encoded into archives. This makes 'ar r' malfunction in + # this piecewise linking case whenever conflicting object + # names appear in distinct ar calls; check, warn and compensate. + if (for obj in $save_oldobjs + do + $echo "X$obj" | $Xsed -e 's%^.*/%%' + done | sort | sort -uc >/dev/null 2>&1); then + : + else + $echo "$modename: warning: object name conflicts; overriding AR_FLAGS to 'cq'" 1>&2 + $echo "$modename: warning: to ensure that POSIX-compatible ar will work" 1>&2 + AR_FLAGS=cq + fi + # Is there a better way of finding the last object in the list? + for obj in $save_oldobjs + do + last_oldobj=$obj + done + for obj in $save_oldobjs + do + oldobjs="$objlist $obj" + objlist="$objlist $obj" + eval test_cmds=\"$old_archive_cmds\" + if len=`expr "X$test_cmds" : ".*"` && + test "$len" -le "$max_cmd_len"; then + : + else + # the above command should be used before it gets too long + oldobjs=$objlist + if test "$obj" = "$last_oldobj" ; then + RANLIB=$save_RANLIB + fi + test -z "$concat_cmds" || concat_cmds=$concat_cmds~ + eval concat_cmds=\"\${concat_cmds}$old_archive_cmds\" + objlist= + fi + done + RANLIB=$save_RANLIB + oldobjs=$objlist + if test "X$oldobjs" = "X" ; then + eval cmds=\"\$concat_cmds\" + else + eval cmds=\"\$concat_cmds~\$old_archive_cmds\" + fi + fi + fi + save_ifs="$IFS"; IFS='~' + for cmd in $cmds; do + eval cmd=\"$cmd\" + IFS="$save_ifs" + $show "$cmd" + $run eval "$cmd" || exit $? + done + IFS="$save_ifs" + done + + if test -n "$generated"; then + $show "${rm}r$generated" + $run ${rm}r$generated + fi + + # Now create the libtool archive. + case $output in + *.la) + old_library= + test "$build_old_libs" = yes && old_library="$libname.$libext" + $show "creating $output" + + # Preserve any variables that may affect compiler behavior + for var in $variables_saved_for_relink; do + if eval test -z \"\${$var+set}\"; then + relink_command="{ test -z \"\${$var+set}\" || unset $var || { $var=; export $var; }; }; $relink_command" + elif eval var_value=\$$var; test -z "$var_value"; then + relink_command="$var=; export $var; $relink_command" + else + var_value=`$echo "X$var_value" | $Xsed -e "$sed_quote_subst"` + relink_command="$var=\"$var_value\"; export $var; $relink_command" + fi + done + # Quote the link command for shipping. + relink_command="(cd `pwd`; $SHELL $progpath $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)" + relink_command=`$echo "X$relink_command" | $Xsed -e "$sed_quote_subst"` + if test "$hardcode_automatic" = yes ; then + relink_command= + fi + + + # Only create the output if not a dry run. + if test -z "$run"; then + for installed in no yes; do + if test "$installed" = yes; then + if test -z "$install_libdir"; then + break + fi + output="$output_objdir/$outputname"i + # Replace all uninstalled libtool libraries with the installed ones + newdependency_libs= + for deplib in $dependency_libs; do + case $deplib in + *.la) + name=`$echo "X$deplib" | $Xsed -e 's%^.*/%%'` + eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib` + if test -z "$libdir"; then + $echo "$modename: \`$deplib' is not a valid libtool archive" 1>&2 + exit $EXIT_FAILURE + fi + newdependency_libs="$newdependency_libs $libdir/$name" + ;; + *) newdependency_libs="$newdependency_libs $deplib" ;; + esac + done + dependency_libs="$newdependency_libs" + newdlfiles= + for lib in $dlfiles; do + name=`$echo "X$lib" | $Xsed -e 's%^.*/%%'` + eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib` + if test -z "$libdir"; then + $echo "$modename: \`$lib' is not a valid libtool archive" 1>&2 + exit $EXIT_FAILURE + fi + newdlfiles="$newdlfiles $libdir/$name" + done + dlfiles="$newdlfiles" + newdlprefiles= + for lib in $dlprefiles; do + name=`$echo "X$lib" | $Xsed -e 's%^.*/%%'` + eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib` + if test -z "$libdir"; then + $echo "$modename: \`$lib' is not a valid libtool archive" 1>&2 + exit $EXIT_FAILURE + fi + newdlprefiles="$newdlprefiles $libdir/$name" + done + dlprefiles="$newdlprefiles" + else + newdlfiles= + for lib in $dlfiles; do + case $lib in + [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;; + *) abs=`pwd`"/$lib" ;; + esac + newdlfiles="$newdlfiles $abs" + done + dlfiles="$newdlfiles" + newdlprefiles= + for lib in $dlprefiles; do + case $lib in + [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;; + *) abs=`pwd`"/$lib" ;; + esac + newdlprefiles="$newdlprefiles $abs" + done + dlprefiles="$newdlprefiles" + fi + $rm $output + # place dlname in correct position for cygwin + tdlname=$dlname + case $host,$output,$installed,$module,$dlname in + *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll) tdlname=../bin/$dlname ;; + esac + $echo > $output "\ +# $outputname - a libtool library file +# Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP +# +# Please DO NOT delete this file! +# It is necessary for linking the library. + +# The name that we can dlopen(3). +dlname='$tdlname' + +# Names of this library. +library_names='$library_names' + +# The name of the static archive. +old_library='$old_library' + +# Libraries that this one depends upon. +dependency_libs='$dependency_libs' + +# Version information for $libname. +current=$current +age=$age +revision=$revision + +# Is this an already installed library? +installed=$installed + +# Should we warn about portability when linking against -modules? +shouldnotlink=$module + +# Files to dlopen/dlpreopen +dlopen='$dlfiles' +dlpreopen='$dlprefiles' + +# Directory that this library needs to be installed in: +libdir='$install_libdir'" + if test "$installed" = no && test "$need_relink" = yes; then + $echo >> $output "\ +relink_command=\"$relink_command\"" + fi + done + fi + + # Do a symbolic link so that the libtool archive can be found in + # LD_LIBRARY_PATH before the program is installed. + $show "(cd $output_objdir && $rm $outputname && $LN_S ../$outputname $outputname)" + $run eval '(cd $output_objdir && $rm $outputname && $LN_S ../$outputname $outputname)' || exit $? + ;; + esac + exit $EXIT_SUCCESS + ;; + + # libtool install mode + install) + modename="$modename: install" + + # There may be an optional sh(1) argument at the beginning of + # install_prog (especially on Windows NT). + if test "$nonopt" = "$SHELL" || test "$nonopt" = /bin/sh || + # Allow the use of GNU shtool's install command. + $echo "X$nonopt" | $Xsed | grep shtool > /dev/null; then + # Aesthetically quote it. + arg=`$echo "X$nonopt" | $Xsed -e "$sed_quote_subst"` + case $arg in + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*) + arg="\"$arg\"" + ;; + esac + install_prog="$arg " + arg="$1" + shift + else + install_prog= + arg="$nonopt" + fi + + # The real first argument should be the name of the installation program. + # Aesthetically quote it. + arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"` + case $arg in + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*) + arg="\"$arg\"" + ;; + esac + install_prog="$install_prog$arg" + + # We need to accept at least all the BSD install flags. + dest= + files= + opts= + prev= + install_type= + isdir=no + stripme= + for arg + do + if test -n "$dest"; then + files="$files $dest" + dest="$arg" + continue + fi + + case $arg in + -d) isdir=yes ;; + -f) prev="-f" ;; + -g) prev="-g" ;; + -m) prev="-m" ;; + -o) prev="-o" ;; + -s) + stripme=" -s" + continue + ;; + -*) ;; + + *) + # If the previous option needed an argument, then skip it. + if test -n "$prev"; then + prev= + else + dest="$arg" + continue + fi + ;; + esac + + # Aesthetically quote the argument. + arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"` + case $arg in + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*) + arg="\"$arg\"" + ;; + esac + install_prog="$install_prog $arg" + done + + if test -z "$install_prog"; then + $echo "$modename: you must specify an install program" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + fi + + if test -n "$prev"; then + $echo "$modename: the \`$prev' option requires an argument" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + fi + + if test -z "$files"; then + if test -z "$dest"; then + $echo "$modename: no file or destination specified" 1>&2 + else + $echo "$modename: you must specify a destination" 1>&2 + fi + $echo "$help" 1>&2 + exit $EXIT_FAILURE + fi + + # Strip any trailing slash from the destination. + dest=`$echo "X$dest" | $Xsed -e 's%/$%%'` + + # Check to see that the destination is a directory. + test -d "$dest" && isdir=yes + if test "$isdir" = yes; then + destdir="$dest" + destname= + else + destdir=`$echo "X$dest" | $Xsed -e 's%/[^/]*$%%'` + test "X$destdir" = "X$dest" && destdir=. + destname=`$echo "X$dest" | $Xsed -e 's%^.*/%%'` + + # Not a directory, so check to see that there is only one file specified. + set dummy $files + if test "$#" -gt 2; then + $echo "$modename: \`$dest' is not a directory" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + fi + fi + case $destdir in + [\\/]* | [A-Za-z]:[\\/]*) ;; + *) + for file in $files; do + case $file in + *.lo) ;; + *) + $echo "$modename: \`$destdir' must be an absolute directory name" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + ;; + esac + done + ;; + esac + + # This variable tells wrapper scripts just to set variables rather + # than running their programs. + libtool_install_magic="$magic" + + staticlibs= + future_libdirs= + current_libdirs= + for file in $files; do + + # Do each installation. + case $file in + *.$libext) + # Do the static libraries later. + staticlibs="$staticlibs $file" + ;; + + *.la) + # Check to see that this really is a libtool archive. + if (${SED} -e '2q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then : + else + $echo "$modename: \`$file' is not a valid libtool archive" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + fi + + library_names= + old_library= + relink_command= + # If there is no directory component, then add one. + case $file in + */* | *\\*) . $file ;; + *) . ./$file ;; + esac + + # Add the libdir to current_libdirs if it is the destination. + if test "X$destdir" = "X$libdir"; then + case "$current_libdirs " in + *" $libdir "*) ;; + *) current_libdirs="$current_libdirs $libdir" ;; + esac + else + # Note the libdir as a future libdir. + case "$future_libdirs " in + *" $libdir "*) ;; + *) future_libdirs="$future_libdirs $libdir" ;; + esac + fi + + dir=`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'`/ + test "X$dir" = "X$file/" && dir= + dir="$dir$objdir" + + if test -n "$relink_command"; then + # Determine the prefix the user has applied to our future dir. + inst_prefix_dir=`$echo "$destdir" | $SED "s%$libdir\$%%"` + + # Don't allow the user to place us outside of our expected + # location b/c this prevents finding dependent libraries that + # are installed to the same prefix. + # At present, this check doesn't affect windows .dll's that + # are installed into $libdir/../bin (currently, that works fine) + # but it's something to keep an eye on. + if test "$inst_prefix_dir" = "$destdir"; then + $echo "$modename: error: cannot install \`$file' to a directory not ending in $libdir" 1>&2 + exit $EXIT_FAILURE + fi + + if test -n "$inst_prefix_dir"; then + # Stick the inst_prefix_dir data into the link command. + relink_command=`$echo "$relink_command" | $SED "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"` + else + relink_command=`$echo "$relink_command" | $SED "s%@inst_prefix_dir@%%"` + fi + + $echo "$modename: warning: relinking \`$file'" 1>&2 + $show "$relink_command" + if $run eval "$relink_command"; then : + else + $echo "$modename: error: relink \`$file' with the above command before installing it" 1>&2 + exit $EXIT_FAILURE + fi + fi + + # See the names of the shared library. + set dummy $library_names + if test -n "$2"; then + realname="$2" + shift + shift + + srcname="$realname" + test -n "$relink_command" && srcname="$realname"T + + # Install the shared library and build the symlinks. + $show "$install_prog $dir/$srcname $destdir/$realname" + $run eval "$install_prog $dir/$srcname $destdir/$realname" || exit $? + if test -n "$stripme" && test -n "$striplib"; then + $show "$striplib $destdir/$realname" + $run eval "$striplib $destdir/$realname" || exit $? + fi + + if test "$#" -gt 0; then + # Delete the old symlinks, and create new ones. + for linkname + do + if test "$linkname" != "$realname"; then + $show "(cd $destdir && $rm $linkname && $LN_S $realname $linkname)" + $run eval "(cd $destdir && $rm $linkname && $LN_S $realname $linkname)" + fi + done + fi + + # Do each command in the postinstall commands. + lib="$destdir/$realname" + cmds=$postinstall_cmds + save_ifs="$IFS"; IFS='~' + for cmd in $cmds; do + IFS="$save_ifs" + eval cmd=\"$cmd\" + $show "$cmd" + $run eval "$cmd" || exit $? + done + IFS="$save_ifs" + fi + + # Install the pseudo-library for information purposes. + name=`$echo "X$file" | $Xsed -e 's%^.*/%%'` + instname="$dir/$name"i + $show "$install_prog $instname $destdir/$name" + $run eval "$install_prog $instname $destdir/$name" || exit $? + + # Maybe install the static library, too. + test -n "$old_library" && staticlibs="$staticlibs $dir/$old_library" + ;; + + *.lo) + # Install (i.e. copy) a libtool object. + + # Figure out destination file name, if it wasn't already specified. + if test -n "$destname"; then + destfile="$destdir/$destname" + else + destfile=`$echo "X$file" | $Xsed -e 's%^.*/%%'` + destfile="$destdir/$destfile" + fi + + # Deduce the name of the destination old-style object file. + case $destfile in + *.lo) + staticdest=`$echo "X$destfile" | $Xsed -e "$lo2o"` + ;; + *.$objext) + staticdest="$destfile" + destfile= + ;; + *) + $echo "$modename: cannot copy a libtool object to \`$destfile'" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + ;; + esac + + # Install the libtool object if requested. + if test -n "$destfile"; then + $show "$install_prog $file $destfile" + $run eval "$install_prog $file $destfile" || exit $? + fi + + # Install the old object if enabled. + if test "$build_old_libs" = yes; then + # Deduce the name of the old-style object file. + staticobj=`$echo "X$file" | $Xsed -e "$lo2o"` + + $show "$install_prog $staticobj $staticdest" + $run eval "$install_prog \$staticobj \$staticdest" || exit $? + fi + exit $EXIT_SUCCESS + ;; + + *) + # Figure out destination file name, if it wasn't already specified. + if test -n "$destname"; then + destfile="$destdir/$destname" + else + destfile=`$echo "X$file" | $Xsed -e 's%^.*/%%'` + destfile="$destdir/$destfile" + fi + + # If the file is missing, and there is a .exe on the end, strip it + # because it is most likely a libtool script we actually want to + # install + stripped_ext="" + case $file in + *.exe) + if test ! -f "$file"; then + file=`$echo $file|${SED} 's,.exe$,,'` + stripped_ext=".exe" + fi + ;; + esac + + # Do a test to see if this is really a libtool program. + case $host in + *cygwin*|*mingw*) + wrapper=`$echo $file | ${SED} -e 's,.exe$,,'` + ;; + *) + wrapper=$file + ;; + esac + if (${SED} -e '4q' $wrapper | grep "^# Generated by .*$PACKAGE")>/dev/null 2>&1; then + notinst_deplibs= + relink_command= + + # To insure that "foo" is sourced, and not "foo.exe", + # finese the cygwin/MSYS system by explicitly sourcing "foo." + # which disallows the automatic-append-.exe behavior. + case $build in + *cygwin* | *mingw*) wrapperdot=${wrapper}. ;; + *) wrapperdot=${wrapper} ;; + esac + # If there is no directory component, then add one. + case $file in + */* | *\\*) . ${wrapperdot} ;; + *) . ./${wrapperdot} ;; + esac + + # Check the variables that should have been set. + if test -z "$notinst_deplibs"; then + $echo "$modename: invalid libtool wrapper script \`$wrapper'" 1>&2 + exit $EXIT_FAILURE + fi + + finalize=yes + for lib in $notinst_deplibs; do + # Check to see that each library is installed. + libdir= + if test -f "$lib"; then + # If there is no directory component, then add one. + case $lib in + */* | *\\*) . $lib ;; + *) . ./$lib ;; + esac + fi + libfile="$libdir/"`$echo "X$lib" | $Xsed -e 's%^.*/%%g'` ### testsuite: skip nested quoting test + if test -n "$libdir" && test ! -f "$libfile"; then + $echo "$modename: warning: \`$lib' has not been installed in \`$libdir'" 1>&2 + finalize=no + fi + done + + relink_command= + # To insure that "foo" is sourced, and not "foo.exe", + # finese the cygwin/MSYS system by explicitly sourcing "foo." + # which disallows the automatic-append-.exe behavior. + case $build in + *cygwin* | *mingw*) wrapperdot=${wrapper}. ;; + *) wrapperdot=${wrapper} ;; + esac + # If there is no directory component, then add one. + case $file in + */* | *\\*) . ${wrapperdot} ;; + *) . ./${wrapperdot} ;; + esac + + outputname= + if test "$fast_install" = no && test -n "$relink_command"; then + if test "$finalize" = yes && test -z "$run"; then + tmpdir="/tmp" + test -n "$TMPDIR" && tmpdir="$TMPDIR" + tmpdir="$tmpdir/libtool-$$" + save_umask=`umask` + umask 0077 + if $mkdir "$tmpdir"; then + umask $save_umask + else + umask $save_umask + $echo "$modename: error: cannot create temporary directory \`$tmpdir'" 1>&2 + continue + fi + file=`$echo "X$file$stripped_ext" | $Xsed -e 's%^.*/%%'` + outputname="$tmpdir/$file" + # Replace the output file specification. + relink_command=`$echo "X$relink_command" | $Xsed -e 's%@OUTPUT@%'"$outputname"'%g'` + + $show "$relink_command" + if $run eval "$relink_command"; then : + else + $echo "$modename: error: relink \`$file' with the above command before installing it" 1>&2 + ${rm}r "$tmpdir" + continue + fi + file="$outputname" + else + $echo "$modename: warning: cannot relink \`$file'" 1>&2 + fi + else + # Install the binary that we compiled earlier. + file=`$echo "X$file$stripped_ext" | $Xsed -e "s%\([^/]*\)$%$objdir/\1%"` + fi + fi + + # remove .exe since cygwin /usr/bin/install will append another + # one anyways + case $install_prog,$host in + */usr/bin/install*,*cygwin*) + case $file:$destfile in + *.exe:*.exe) + # this is ok + ;; + *.exe:*) + destfile=$destfile.exe + ;; + *:*.exe) + destfile=`$echo $destfile | ${SED} -e 's,.exe$,,'` + ;; + esac + ;; + esac + $show "$install_prog$stripme $file $destfile" + $run eval "$install_prog\$stripme \$file \$destfile" || exit $? + test -n "$outputname" && ${rm}r "$tmpdir" + ;; + esac + done + + for file in $staticlibs; do + name=`$echo "X$file" | $Xsed -e 's%^.*/%%'` + + # Set up the ranlib parameters. + oldlib="$destdir/$name" + + $show "$install_prog $file $oldlib" + $run eval "$install_prog \$file \$oldlib" || exit $? + + if test -n "$stripme" && test -n "$old_striplib"; then + $show "$old_striplib $oldlib" + $run eval "$old_striplib $oldlib" || exit $? + fi + + # Do each command in the postinstall commands. + cmds=$old_postinstall_cmds + save_ifs="$IFS"; IFS='~' + for cmd in $cmds; do + IFS="$save_ifs" + eval cmd=\"$cmd\" + $show "$cmd" + $run eval "$cmd" || exit $? + done + IFS="$save_ifs" + done + + if test -n "$future_libdirs"; then + $echo "$modename: warning: remember to run \`$progname --finish$future_libdirs'" 1>&2 + fi + + if test -n "$current_libdirs"; then + # Maybe just do a dry run. + test -n "$run" && current_libdirs=" -n$current_libdirs" + exec_cmd='$SHELL $progpath $preserve_args --finish$current_libdirs' + else + exit $EXIT_SUCCESS + fi + ;; + + # libtool finish mode + finish) + modename="$modename: finish" + libdirs="$nonopt" + admincmds= + + if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then + for dir + do + libdirs="$libdirs $dir" + done + + for libdir in $libdirs; do + if test -n "$finish_cmds"; then + # Do each command in the finish commands. + cmds=$finish_cmds + save_ifs="$IFS"; IFS='~' + for cmd in $cmds; do + IFS="$save_ifs" + eval cmd=\"$cmd\" + $show "$cmd" + $run eval "$cmd" || admincmds="$admincmds + $cmd" + done + IFS="$save_ifs" + fi + if test -n "$finish_eval"; then + # Do the single finish_eval. + eval cmds=\"$finish_eval\" + $run eval "$cmds" || admincmds="$admincmds + $cmds" + fi + done + fi + + # Exit here if they wanted silent mode. + test "$show" = : && exit $EXIT_SUCCESS + + $echo "----------------------------------------------------------------------" + $echo "Libraries have been installed in:" + for libdir in $libdirs; do + $echo " $libdir" + done + $echo + $echo "If you ever happen to want to link against installed libraries" + $echo "in a given directory, LIBDIR, you must either use libtool, and" + $echo "specify the full pathname of the library, or use the \`-LLIBDIR'" + $echo "flag during linking and do at least one of the following:" + if test -n "$shlibpath_var"; then + $echo " - add LIBDIR to the \`$shlibpath_var' environment variable" + $echo " during execution" + fi + if test -n "$runpath_var"; then + $echo " - add LIBDIR to the \`$runpath_var' environment variable" + $echo " during linking" + fi + if test -n "$hardcode_libdir_flag_spec"; then + libdir=LIBDIR + eval flag=\"$hardcode_libdir_flag_spec\" + + $echo " - use the \`$flag' linker flag" + fi + if test -n "$admincmds"; then + $echo " - have your system administrator run these commands:$admincmds" + fi + if test -f /etc/ld.so.conf; then + $echo " - have your system administrator add LIBDIR to \`/etc/ld.so.conf'" + fi + $echo + $echo "See any operating system documentation about shared libraries for" + $echo "more information, such as the ld(1) and ld.so(8) manual pages." + $echo "----------------------------------------------------------------------" + exit $EXIT_SUCCESS + ;; + + # libtool execute mode + execute) + modename="$modename: execute" + + # The first argument is the command name. + cmd="$nonopt" + if test -z "$cmd"; then + $echo "$modename: you must specify a COMMAND" 1>&2 + $echo "$help" + exit $EXIT_FAILURE + fi + + # Handle -dlopen flags immediately. + for file in $execute_dlfiles; do + if test ! -f "$file"; then + $echo "$modename: \`$file' is not a file" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + fi + + dir= + case $file in + *.la) + # Check to see that this really is a libtool archive. + if (${SED} -e '2q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then : + else + $echo "$modename: \`$lib' is not a valid libtool archive" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + fi + + # Read the libtool library. + dlname= + library_names= + + # If there is no directory component, then add one. + case $file in + */* | *\\*) . $file ;; + *) . ./$file ;; + esac + + # Skip this library if it cannot be dlopened. + if test -z "$dlname"; then + # Warn if it was a shared library. + test -n "$library_names" && $echo "$modename: warning: \`$file' was not linked with \`-export-dynamic'" + continue + fi + + dir=`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'` + test "X$dir" = "X$file" && dir=. + + if test -f "$dir/$objdir/$dlname"; then + dir="$dir/$objdir" + else + $echo "$modename: cannot find \`$dlname' in \`$dir' or \`$dir/$objdir'" 1>&2 + exit $EXIT_FAILURE + fi + ;; + + *.lo) + # Just add the directory containing the .lo file. + dir=`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'` + test "X$dir" = "X$file" && dir=. + ;; + + *) + $echo "$modename: warning \`-dlopen' is ignored for non-libtool libraries and objects" 1>&2 + continue + ;; + esac + + # Get the absolute pathname. + absdir=`cd "$dir" && pwd` + test -n "$absdir" && dir="$absdir" + + # Now add the directory to shlibpath_var. + if eval "test -z \"\$$shlibpath_var\""; then + eval "$shlibpath_var=\"\$dir\"" + else + eval "$shlibpath_var=\"\$dir:\$$shlibpath_var\"" + fi + done + + # This variable tells wrapper scripts just to set shlibpath_var + # rather than running their programs. + libtool_execute_magic="$magic" + + # Check if any of the arguments is a wrapper script. + args= + for file + do + case $file in + -*) ;; + *) + # Do a test to see if this is really a libtool program. + if (${SED} -e '4q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then + # If there is no directory component, then add one. + case $file in + */* | *\\*) . $file ;; + *) . ./$file ;; + esac + + # Transform arg to wrapped name. + file="$progdir/$program" + fi + ;; + esac + # Quote arguments (to preserve shell metacharacters). + file=`$echo "X$file" | $Xsed -e "$sed_quote_subst"` + args="$args \"$file\"" + done + + if test -z "$run"; then + if test -n "$shlibpath_var"; then + # Export the shlibpath_var. + eval "export $shlibpath_var" + fi + + # Restore saved environment variables + if test "${save_LC_ALL+set}" = set; then + LC_ALL="$save_LC_ALL"; export LC_ALL + fi + if test "${save_LANG+set}" = set; then + LANG="$save_LANG"; export LANG + fi + + # Now prepare to actually exec the command. + exec_cmd="\$cmd$args" + else + # Display what would be done. + if test -n "$shlibpath_var"; then + eval "\$echo \"\$shlibpath_var=\$$shlibpath_var\"" + $echo "export $shlibpath_var" + fi + $echo "$cmd$args" + exit $EXIT_SUCCESS + fi + ;; + + # libtool clean and uninstall mode + clean | uninstall) + modename="$modename: $mode" + rm="$nonopt" + files= + rmforce= + exit_status=0 + + # This variable tells wrapper scripts just to set variables rather + # than running their programs. + libtool_install_magic="$magic" + + for arg + do + case $arg in + -f) rm="$rm $arg"; rmforce=yes ;; + -*) rm="$rm $arg" ;; + *) files="$files $arg" ;; + esac + done + + if test -z "$rm"; then + $echo "$modename: you must specify an RM program" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + fi + + rmdirs= + + origobjdir="$objdir" + for file in $files; do + dir=`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'` + if test "X$dir" = "X$file"; then + dir=. + objdir="$origobjdir" + else + objdir="$dir/$origobjdir" + fi + name=`$echo "X$file" | $Xsed -e 's%^.*/%%'` + test "$mode" = uninstall && objdir="$dir" + + # Remember objdir for removal later, being careful to avoid duplicates + if test "$mode" = clean; then + case " $rmdirs " in + *" $objdir "*) ;; + *) rmdirs="$rmdirs $objdir" ;; + esac + fi + + # Don't error if the file doesn't exist and rm -f was used. + if (test -L "$file") >/dev/null 2>&1 \ + || (test -h "$file") >/dev/null 2>&1 \ + || test -f "$file"; then + : + elif test -d "$file"; then + exit_status=1 + continue + elif test "$rmforce" = yes; then + continue + fi + + rmfiles="$file" + + case $name in + *.la) + # Possibly a libtool archive, so verify it. + if (${SED} -e '2q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then + . $dir/$name + + # Delete the libtool libraries and symlinks. + for n in $library_names; do + rmfiles="$rmfiles $objdir/$n" + done + test -n "$old_library" && rmfiles="$rmfiles $objdir/$old_library" + test "$mode" = clean && rmfiles="$rmfiles $objdir/$name $objdir/${name}i" + + if test "$mode" = uninstall; then + if test -n "$library_names"; then + # Do each command in the postuninstall commands. + cmds=$postuninstall_cmds + save_ifs="$IFS"; IFS='~' + for cmd in $cmds; do + IFS="$save_ifs" + eval cmd=\"$cmd\" + $show "$cmd" + $run eval "$cmd" + if test "$?" -ne 0 && test "$rmforce" != yes; then + exit_status=1 + fi + done + IFS="$save_ifs" + fi + + if test -n "$old_library"; then + # Do each command in the old_postuninstall commands. + cmds=$old_postuninstall_cmds + save_ifs="$IFS"; IFS='~' + for cmd in $cmds; do + IFS="$save_ifs" + eval cmd=\"$cmd\" + $show "$cmd" + $run eval "$cmd" + if test "$?" -ne 0 && test "$rmforce" != yes; then + exit_status=1 + fi + done + IFS="$save_ifs" + fi + # FIXME: should reinstall the best remaining shared library. + fi + fi + ;; + + *.lo) + # Possibly a libtool object, so verify it. + if (${SED} -e '2q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then + + # Read the .lo file + . $dir/$name + + # Add PIC object to the list of files to remove. + if test -n "$pic_object" \ + && test "$pic_object" != none; then + rmfiles="$rmfiles $dir/$pic_object" + fi + + # Add non-PIC object to the list of files to remove. + if test -n "$non_pic_object" \ + && test "$non_pic_object" != none; then + rmfiles="$rmfiles $dir/$non_pic_object" + fi + fi + ;; + + *) + if test "$mode" = clean ; then + noexename=$name + case $file in + *.exe) + file=`$echo $file|${SED} 's,.exe$,,'` + noexename=`$echo $name|${SED} 's,.exe$,,'` + # $file with .exe has already been added to rmfiles, + # add $file without .exe + rmfiles="$rmfiles $file" + ;; + esac + # Do a test to see if this is a libtool program. + if (${SED} -e '4q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then + relink_command= + . $dir/$noexename + + # note $name still contains .exe if it was in $file originally + # as does the version of $file that was added into $rmfiles + rmfiles="$rmfiles $objdir/$name $objdir/${name}S.${objext}" + if test "$fast_install" = yes && test -n "$relink_command"; then + rmfiles="$rmfiles $objdir/lt-$name" + fi + if test "X$noexename" != "X$name" ; then + rmfiles="$rmfiles $objdir/lt-${noexename}.c" + fi + fi + fi + ;; + esac + $show "$rm $rmfiles" + $run $rm $rmfiles || exit_status=1 + done + objdir="$origobjdir" + + # Try to remove the ${objdir}s in the directories where we deleted files + for dir in $rmdirs; do + if test -d "$dir"; then + $show "rmdir $dir" + $run rmdir $dir >/dev/null 2>&1 + fi + done + + exit $exit_status + ;; + + "") + $echo "$modename: you must specify a MODE" 1>&2 + $echo "$generic_help" 1>&2 + exit $EXIT_FAILURE + ;; + esac + + if test -z "$exec_cmd"; then + $echo "$modename: invalid operation mode \`$mode'" 1>&2 + $echo "$generic_help" 1>&2 + exit $EXIT_FAILURE + fi +fi # test -z "$show_help" + +if test -n "$exec_cmd"; then + eval exec $exec_cmd + exit $EXIT_FAILURE +fi + +# We need to display help for each of the modes. +case $mode in +"") $echo \ +"Usage: $modename [OPTION]... [MODE-ARG]... + +Provide generalized library-building support services. + + --config show all configuration variables + --debug enable verbose shell tracing +-n, --dry-run display commands without modifying any files + --features display basic configuration information and exit + --finish same as \`--mode=finish' + --help display this help message and exit + --mode=MODE use operation mode MODE [default=inferred from MODE-ARGS] + --quiet same as \`--silent' + --silent don't print informational messages + --tag=TAG use configuration variables from tag TAG + --version print version information + +MODE must be one of the following: + + clean remove files from the build directory + compile compile a source file into a libtool object + execute automatically set library path, then run a program + finish complete the installation of libtool libraries + install install libraries or executables + link create a library or an executable + uninstall remove libraries from an installed directory + +MODE-ARGS vary depending on the MODE. Try \`$modename --help --mode=MODE' for +a more detailed description of MODE. + +Report bugs to ." + exit $EXIT_SUCCESS + ;; + +clean) + $echo \ +"Usage: $modename [OPTION]... --mode=clean RM [RM-OPTION]... FILE... + +Remove files from the build directory. + +RM is the name of the program to use to delete files associated with each FILE +(typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed +to RM. + +If FILE is a libtool library, object or program, all the files associated +with it are deleted. Otherwise, only FILE itself is deleted using RM." + ;; + +compile) + $echo \ +"Usage: $modename [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE + +Compile a source file into a libtool library object. + +This mode accepts the following additional options: + + -o OUTPUT-FILE set the output file name to OUTPUT-FILE + -prefer-pic try to building PIC objects only + -prefer-non-pic try to building non-PIC objects only + -static always build a \`.o' file suitable for static linking + +COMPILE-COMMAND is a command to be used in creating a \`standard' object file +from the given SOURCEFILE. + +The output file name is determined by removing the directory component from +SOURCEFILE, then substituting the C source code suffix \`.c' with the +library object suffix, \`.lo'." + ;; + +execute) + $echo \ +"Usage: $modename [OPTION]... --mode=execute COMMAND [ARGS]... + +Automatically set library path, then run a program. + +This mode accepts the following additional options: + + -dlopen FILE add the directory containing FILE to the library path + +This mode sets the library path environment variable according to \`-dlopen' +flags. + +If any of the ARGS are libtool executable wrappers, then they are translated +into their corresponding uninstalled binary, and any of their required library +directories are added to the library path. + +Then, COMMAND is executed, with ARGS as arguments." + ;; + +finish) + $echo \ +"Usage: $modename [OPTION]... --mode=finish [LIBDIR]... + +Complete the installation of libtool libraries. + +Each LIBDIR is a directory that contains libtool libraries. + +The commands that this mode executes may require superuser privileges. Use +the \`--dry-run' option if you just want to see what would be executed." + ;; + +install) + $echo \ +"Usage: $modename [OPTION]... --mode=install INSTALL-COMMAND... + +Install executables or libraries. + +INSTALL-COMMAND is the installation command. The first component should be +either the \`install' or \`cp' program. + +The rest of the components are interpreted as arguments to that command (only +BSD-compatible install options are recognized)." + ;; + +link) + $echo \ +"Usage: $modename [OPTION]... --mode=link LINK-COMMAND... + +Link object files or libraries together to form another library, or to +create an executable program. + +LINK-COMMAND is a command using the C compiler that you would use to create +a program from several object files. + +The following components of LINK-COMMAND are treated specially: + + -all-static do not do any dynamic linking at all + -avoid-version do not add a version suffix if possible + -dlopen FILE \`-dlpreopen' FILE if it cannot be dlopened at runtime + -dlpreopen FILE link in FILE and add its symbols to lt_preloaded_symbols + -export-dynamic allow symbols from OUTPUT-FILE to be resolved with dlsym(3) + -export-symbols SYMFILE + try to export only the symbols listed in SYMFILE + -export-symbols-regex REGEX + try to export only the symbols matching REGEX + -LLIBDIR search LIBDIR for required installed libraries + -lNAME OUTPUT-FILE requires the installed library libNAME + -module build a library that can dlopened + -no-fast-install disable the fast-install mode + -no-install link a not-installable executable + -no-undefined declare that a library does not refer to external symbols + -o OUTPUT-FILE create OUTPUT-FILE from the specified objects + -objectlist FILE Use a list of object files found in FILE to specify objects + -precious-files-regex REGEX + don't remove output files matching REGEX + -release RELEASE specify package release information + -rpath LIBDIR the created library will eventually be installed in LIBDIR + -R[ ]LIBDIR add LIBDIR to the runtime path of programs and libraries + -static do not do any dynamic linking of libtool libraries + -version-info CURRENT[:REVISION[:AGE]] + specify library version info [each variable defaults to 0] + +All other options (arguments beginning with \`-') are ignored. + +Every other argument is treated as a filename. Files ending in \`.la' are +treated as uninstalled libtool libraries, other files are standard or library +object files. + +If the OUTPUT-FILE ends in \`.la', then a libtool library is created, +only library objects (\`.lo' files) may be specified, and \`-rpath' is +required, except when creating a convenience library. + +If OUTPUT-FILE ends in \`.a' or \`.lib', then a standard library is created +using \`ar' and \`ranlib', or on Windows using \`lib'. + +If OUTPUT-FILE ends in \`.lo' or \`.${objext}', then a reloadable object file +is created, otherwise an executable program is created." + ;; + +uninstall) + $echo \ +"Usage: $modename [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE... + +Remove libraries from an installation directory. + +RM is the name of the program to use to delete files associated with each FILE +(typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed +to RM. + +If FILE is a libtool library, all the files associated with it are deleted. +Otherwise, only FILE itself is deleted using RM." + ;; + +*) + $echo "$modename: invalid operation mode \`$mode'" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + ;; +esac + +$echo +$echo "Try \`$modename --help' for more information about other modes." + +exit $EXIT_SUCCESS + +# The TAGs below are defined such that we never get into a situation +# in which we disable both kinds of libraries. Given conflicting +# choices, we go for a static library, that is the most portable, +# since we can't tell whether shared libraries were disabled because +# the user asked for that or because the platform doesn't support +# them. This is particularly important on AIX, because we don't +# support having both static and shared libraries enabled at the same +# time on that platform, so we default to a shared-only configuration. +# If a disable-shared tag is given, we'll fallback to a static-only +# configuration. But we'll never go from static-only to shared-only. + +# ### BEGIN LIBTOOL TAG CONFIG: disable-shared +build_libtool_libs=no +build_old_libs=yes +# ### END LIBTOOL TAG CONFIG: disable-shared + +# ### BEGIN LIBTOOL TAG CONFIG: disable-static +build_old_libs=`case $build_libtool_libs in yes) $echo no;; *) $echo yes;; esac` +# ### END LIBTOOL TAG CONFIG: disable-static + +# Local Variables: +# mode:shell-script +# sh-indentation:2 +# End: diff --git a/Code/BF2/External/speex-1.0.5/missing b/Code/BF2/External/speex-1.0.5/missing new file mode 100755 index 000000000..e7ef83a1c --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/missing @@ -0,0 +1,360 @@ +#! /bin/sh +# Common stub for a few missing GNU programs while installing. + +scriptversion=2003-09-02.23 + +# Copyright (C) 1996, 1997, 1999, 2000, 2002, 2003 +# Free Software Foundation, Inc. +# Originally by Fran,cois Pinard , 1996. + +# 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, or (at your option) +# any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA +# 02111-1307, USA. + +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + +if test $# -eq 0; then + echo 1>&2 "Try \`$0 --help' for more information" + exit 1 +fi + +run=: + +# In the cases where this matters, `missing' is being run in the +# srcdir already. +if test -f configure.ac; then + configure_ac=configure.ac +else + configure_ac=configure.in +fi + +msg="missing on your system" + +case "$1" in +--run) + # Try to run requested program, and just exit if it succeeds. + run= + shift + "$@" && exit 0 + # Exit code 63 means version mismatch. This often happens + # when the user try to use an ancient version of a tool on + # a file that requires a minimum version. In this case we + # we should proceed has if the program had been absent, or + # if --run hadn't been passed. + if test $? = 63; then + run=: + msg="probably too old" + fi + ;; +esac + +# If it does not exist, or fails to run (possibly an outdated version), +# try to emulate it. +case "$1" in + + -h|--h|--he|--hel|--help) + echo "\ +$0 [OPTION]... PROGRAM [ARGUMENT]... + +Handle \`PROGRAM [ARGUMENT]...' for when PROGRAM is missing, or return an +error status if there is no known handling for PROGRAM. + +Options: + -h, --help display this help and exit + -v, --version output version information and exit + --run try to run the given command, and emulate it if it fails + +Supported PROGRAM values: + aclocal touch file \`aclocal.m4' + autoconf touch file \`configure' + autoheader touch file \`config.h.in' + automake touch all \`Makefile.in' files + bison create \`y.tab.[ch]', if possible, from existing .[ch] + flex create \`lex.yy.c', if possible, from existing .c + help2man touch the output file + lex create \`lex.yy.c', if possible, from existing .c + makeinfo touch the output file + tar try tar, gnutar, gtar, then tar without non-portable flags + yacc create \`y.tab.[ch]', if possible, from existing .[ch] + +Send bug reports to ." + ;; + + -v|--v|--ve|--ver|--vers|--versi|--versio|--version) + echo "missing $scriptversion (GNU Automake)" + ;; + + -*) + echo 1>&2 "$0: Unknown \`$1' option" + echo 1>&2 "Try \`$0 --help' for more information" + exit 1 + ;; + + aclocal*) + if test -z "$run" && ($1 --version) > /dev/null 2>&1; then + # We have it, but it failed. + exit 1 + fi + + echo 1>&2 "\ +WARNING: \`$1' is $msg. You should only need it if + you modified \`acinclude.m4' or \`${configure_ac}'. You might want + to install the \`Automake' and \`Perl' packages. Grab them from + any GNU archive site." + touch aclocal.m4 + ;; + + autoconf) + if test -z "$run" && ($1 --version) > /dev/null 2>&1; then + # We have it, but it failed. + exit 1 + fi + + echo 1>&2 "\ +WARNING: \`$1' is $msg. You should only need it if + you modified \`${configure_ac}'. You might want to install the + \`Autoconf' and \`GNU m4' packages. Grab them from any GNU + archive site." + touch configure + ;; + + autoheader) + if test -z "$run" && ($1 --version) > /dev/null 2>&1; then + # We have it, but it failed. + exit 1 + fi + + echo 1>&2 "\ +WARNING: \`$1' is $msg. You should only need it if + you modified \`acconfig.h' or \`${configure_ac}'. You might want + to install the \`Autoconf' and \`GNU m4' packages. Grab them + from any GNU archive site." + files=`sed -n 's/^[ ]*A[CM]_CONFIG_HEADER(\([^)]*\)).*/\1/p' ${configure_ac}` + test -z "$files" && files="config.h" + touch_files= + for f in $files; do + case "$f" in + *:*) touch_files="$touch_files "`echo "$f" | + sed -e 's/^[^:]*://' -e 's/:.*//'`;; + *) touch_files="$touch_files $f.in";; + esac + done + touch $touch_files + ;; + + automake*) + if test -z "$run" && ($1 --version) > /dev/null 2>&1; then + # We have it, but it failed. + exit 1 + fi + + echo 1>&2 "\ +WARNING: \`$1' is $msg. You should only need it if + you modified \`Makefile.am', \`acinclude.m4' or \`${configure_ac}'. + You might want to install the \`Automake' and \`Perl' packages. + Grab them from any GNU archive site." + find . -type f -name Makefile.am -print | + sed 's/\.am$/.in/' | + while read f; do touch "$f"; done + ;; + + autom4te) + if test -z "$run" && ($1 --version) > /dev/null 2>&1; then + # We have it, but it failed. + exit 1 + fi + + echo 1>&2 "\ +WARNING: \`$1' is needed, but is $msg. + You might have modified some files without having the + proper tools for further handling them. + You can get \`$1' as part of \`Autoconf' from any GNU + archive site." + + file=`echo "$*" | sed -n 's/.*--output[ =]*\([^ ]*\).*/\1/p'` + test -z "$file" && file=`echo "$*" | sed -n 's/.*-o[ ]*\([^ ]*\).*/\1/p'` + if test -f "$file"; then + touch $file + else + test -z "$file" || exec >$file + echo "#! /bin/sh" + echo "# Created by GNU Automake missing as a replacement of" + echo "# $ $@" + echo "exit 0" + chmod +x $file + exit 1 + fi + ;; + + bison|yacc) + echo 1>&2 "\ +WARNING: \`$1' $msg. You should only need it if + you modified a \`.y' file. You may need the \`Bison' package + in order for those modifications to take effect. You can get + \`Bison' from any GNU archive site." + rm -f y.tab.c y.tab.h + if [ $# -ne 1 ]; then + eval LASTARG="\${$#}" + case "$LASTARG" in + *.y) + SRCFILE=`echo "$LASTARG" | sed 's/y$/c/'` + if [ -f "$SRCFILE" ]; then + cp "$SRCFILE" y.tab.c + fi + SRCFILE=`echo "$LASTARG" | sed 's/y$/h/'` + if [ -f "$SRCFILE" ]; then + cp "$SRCFILE" y.tab.h + fi + ;; + esac + fi + if [ ! -f y.tab.h ]; then + echo >y.tab.h + fi + if [ ! -f y.tab.c ]; then + echo 'main() { return 0; }' >y.tab.c + fi + ;; + + lex|flex) + echo 1>&2 "\ +WARNING: \`$1' is $msg. You should only need it if + you modified a \`.l' file. You may need the \`Flex' package + in order for those modifications to take effect. You can get + \`Flex' from any GNU archive site." + rm -f lex.yy.c + if [ $# -ne 1 ]; then + eval LASTARG="\${$#}" + case "$LASTARG" in + *.l) + SRCFILE=`echo "$LASTARG" | sed 's/l$/c/'` + if [ -f "$SRCFILE" ]; then + cp "$SRCFILE" lex.yy.c + fi + ;; + esac + fi + if [ ! -f lex.yy.c ]; then + echo 'main() { return 0; }' >lex.yy.c + fi + ;; + + help2man) + if test -z "$run" && ($1 --version) > /dev/null 2>&1; then + # We have it, but it failed. + exit 1 + fi + + echo 1>&2 "\ +WARNING: \`$1' is $msg. You should only need it if + you modified a dependency of a manual page. You may need the + \`Help2man' package in order for those modifications to take + effect. You can get \`Help2man' from any GNU archive site." + + file=`echo "$*" | sed -n 's/.*-o \([^ ]*\).*/\1/p'` + if test -z "$file"; then + file=`echo "$*" | sed -n 's/.*--output=\([^ ]*\).*/\1/p'` + fi + if [ -f "$file" ]; then + touch $file + else + test -z "$file" || exec >$file + echo ".ab help2man is required to generate this page" + exit 1 + fi + ;; + + makeinfo) + if test -z "$run" && (makeinfo --version) > /dev/null 2>&1; then + # We have makeinfo, but it failed. + exit 1 + fi + + echo 1>&2 "\ +WARNING: \`$1' is $msg. You should only need it if + you modified a \`.texi' or \`.texinfo' file, or any other file + indirectly affecting the aspect of the manual. The spurious + call might also be the consequence of using a buggy \`make' (AIX, + DU, IRIX). You might want to install the \`Texinfo' package or + the \`GNU make' package. Grab either from any GNU archive site." + file=`echo "$*" | sed -n 's/.*-o \([^ ]*\).*/\1/p'` + if test -z "$file"; then + file=`echo "$*" | sed 's/.* \([^ ]*\) *$/\1/'` + file=`sed -n '/^@setfilename/ { s/.* \([^ ]*\) *$/\1/; p; q; }' $file` + fi + touch $file + ;; + + tar) + shift + if test -n "$run"; then + echo 1>&2 "ERROR: \`tar' requires --run" + exit 1 + fi + + # We have already tried tar in the generic part. + # Look for gnutar/gtar before invocation to avoid ugly error + # messages. + if (gnutar --version > /dev/null 2>&1); then + gnutar "$@" && exit 0 + fi + if (gtar --version > /dev/null 2>&1); then + gtar "$@" && exit 0 + fi + firstarg="$1" + if shift; then + case "$firstarg" in + *o*) + firstarg=`echo "$firstarg" | sed s/o//` + tar "$firstarg" "$@" && exit 0 + ;; + esac + case "$firstarg" in + *h*) + firstarg=`echo "$firstarg" | sed s/h//` + tar "$firstarg" "$@" && exit 0 + ;; + esac + fi + + echo 1>&2 "\ +WARNING: I can't seem to be able to run \`tar' with the given arguments. + You may want to install GNU tar or Free paxutils, or check the + command line arguments." + exit 1 + ;; + + *) + echo 1>&2 "\ +WARNING: \`$1' is needed, and is $msg. + You might have modified some files without having the + proper tools for further handling them. Check the \`README' file, + it often tells you about the needed prerequisites for installing + this package. You may also peek at any GNU archive site, in case + some other package would contain this missing \`$1' program." + exit 1 + ;; +esac + +exit 0 + +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "scriptversion=" +# time-stamp-format: "%:y-%02m-%02d.%02H" +# time-stamp-end: "$" +# End: diff --git a/Code/BF2/External/speex-1.0.5/mkinstalldirs b/Code/BF2/External/speex-1.0.5/mkinstalldirs new file mode 100755 index 000000000..d2d5f21b6 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/mkinstalldirs @@ -0,0 +1,111 @@ +#! /bin/sh +# mkinstalldirs --- make directory hierarchy +# Author: Noah Friedman +# Created: 1993-05-16 +# Public domain + +errstatus=0 +dirmode="" + +usage="\ +Usage: mkinstalldirs [-h] [--help] [-m mode] dir ..." + +# process command line arguments +while test $# -gt 0 ; do + case $1 in + -h | --help | --h*) # -h for help + echo "$usage" 1>&2 + exit 0 + ;; + -m) # -m PERM arg + shift + test $# -eq 0 && { echo "$usage" 1>&2; exit 1; } + dirmode=$1 + shift + ;; + --) # stop option processing + shift + break + ;; + -*) # unknown option + echo "$usage" 1>&2 + exit 1 + ;; + *) # first non-opt arg + break + ;; + esac +done + +for file +do + if test -d "$file"; then + shift + else + break + fi +done + +case $# in + 0) exit 0 ;; +esac + +case $dirmode in + '') + if mkdir -p -- . 2>/dev/null; then + echo "mkdir -p -- $*" + exec mkdir -p -- "$@" + fi + ;; + *) + if mkdir -m "$dirmode" -p -- . 2>/dev/null; then + echo "mkdir -m $dirmode -p -- $*" + exec mkdir -m "$dirmode" -p -- "$@" + fi + ;; +esac + +for file +do + set fnord `echo ":$file" | sed -ne 's/^:\//#/;s/^://;s/\// /g;s/^#/\//;p'` + shift + + pathcomp= + for d + do + pathcomp="$pathcomp$d" + case $pathcomp in + -*) pathcomp=./$pathcomp ;; + esac + + if test ! -d "$pathcomp"; then + echo "mkdir $pathcomp" + + mkdir "$pathcomp" || lasterr=$? + + if test ! -d "$pathcomp"; then + errstatus=$lasterr + else + if test ! -z "$dirmode"; then + echo "chmod $dirmode $pathcomp" + lasterr="" + chmod "$dirmode" "$pathcomp" || lasterr=$? + + if test ! -z "$lasterr"; then + errstatus=$lasterr + fi + fi + fi + fi + + pathcomp="$pathcomp/" + done +done + +exit $errstatus + +# Local Variables: +# mode: shell-script +# sh-indentation: 2 +# End: +# mkinstalldirs ends here diff --git a/Code/BF2/External/speex-1.0.5/speex.m4 b/Code/BF2/External/speex-1.0.5/speex.m4 new file mode 100644 index 000000000..b0ddfc3f1 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/speex.m4 @@ -0,0 +1,104 @@ +# Configure paths for libspeex +# Jean-Marc Valin +# Shamelessly stolen from: +# Jack Moffitt 10-21-2000 +# Shamelessly stolen from Owen Taylor and Manish Singh + +dnl XIPH_PATH_SPEEX([ACTION-IF-FOUND [, ACTION-IF-NOT-FOUND]]) +dnl Test for libspeex, and define SPEEX_CFLAGS and SPEEX_LIBS +dnl +AC_DEFUN(XIPH_PATH_SPEEX, +[dnl +dnl Get the cflags and libraries +dnl +AC_ARG_WITH(speex,[ --with-speex=PFX Prefix where libspeex is installed (optional)], speex_prefix="$withval", speex_prefix="") +AC_ARG_WITH(speex-libraries,[ --with-speex-libraries=DIR Directory where libspeex library is installed (optional)], speex_libraries="$withval", speex_libraries="") +AC_ARG_WITH(speex-includes,[ --with-speex-includes=DIR Directory where libspeex header files are installed (optional)], speex_includes="$withval", speex_includes="") +AC_ARG_ENABLE(speextest, [ --disable-speextest Do not try to compile and run a test Speex program],, enable_speextest=yes) + + if test "x$speex_libraries" != "x" ; then + SPEEX_LIBS="-L$speex_libraries" + elif test "x$speex_prefix" != "x" ; then + SPEEX_LIBS="-L$speex_prefix/lib" + elif test "x$prefix" != "xNONE" ; then + SPEEX_LIBS="-L$prefix/lib" + fi + + SPEEX_LIBS="$SPEEX_LIBS -lspeex" + + if test "x$speex_includes" != "x" ; then + SPEEX_CFLAGS="-I$speex_includes" + elif test "x$speex_prefix" != "x" ; then + SPEEX_CFLAGS="-I$speex_prefix/include" + elif test "x$prefix" != "xNONE"; then + SPEEX_CFLAGS="-I$prefix/include" + fi + + AC_MSG_CHECKING(for Speex) + no_speex="" + + + if test "x$enable_speextest" = "xyes" ; then + ac_save_CFLAGS="$CFLAGS" + ac_save_LIBS="$LIBS" + CFLAGS="$CFLAGS $SPEEX_CFLAGS" + LIBS="$LIBS $SPEEX_LIBS" +dnl +dnl Now check if the installed Speex is sufficiently new. +dnl + rm -f conf.speextest + AC_TRY_RUN([ +#include +#include +#include +#include + +int main () +{ + system("touch conf.speextest"); + return 0; +} + +],, no_speex=yes,[echo $ac_n "cross compiling; assumed OK... $ac_c"]) + CFLAGS="$ac_save_CFLAGS" + LIBS="$ac_save_LIBS" + fi + + if test "x$no_speex" = "x" ; then + AC_MSG_RESULT(yes) + ifelse([$1], , :, [$1]) + else + AC_MSG_RESULT(no) + if test -f conf.speextest ; then + : + else + echo "*** Could not run Speex test program, checking why..." + CFLAGS="$CFLAGS $SPEEX_CFLAGS" + LIBS="$LIBS $SPEEX_LIBS" + AC_TRY_LINK([ +#include +#include +], [ return 0; ], + [ echo "*** The test program compiled, but did not run. This usually means" + echo "*** that the run-time linker is not finding Speex or finding the wrong" + echo "*** version of Speex. If it is not finding Speex, you'll need to set your" + echo "*** LD_LIBRARY_PATH environment variable, or edit /etc/ld.so.conf to point" + echo "*** to the installed location Also, make sure you have run ldconfig if that" + echo "*** is required on your system" + echo "***" + echo "*** If you have an old version installed, it is best to remove it, although" + echo "*** you may also be able to get things to work by modifying LD_LIBRARY_PATH"], + [ echo "*** The test program failed to compile or link. See the file config.log for the" + echo "*** exact error that occured. This usually means Speex was incorrectly installed" + echo "*** or that you have moved Speex since it was installed." ]) + CFLAGS="$ac_save_CFLAGS" + LIBS="$ac_save_LIBS" + fi + SPEEX_CFLAGS="" + SPEEX_LIBS="" + ifelse([$2], , :, [$2]) + fi + AC_SUBST(SPEEX_CFLAGS) + AC_SUBST(SPEEX_LIBS) + rm -f conf.speextest +]) diff --git a/Code/BF2/External/speex-1.0.5/speex.pc.in b/Code/BF2/External/speex-1.0.5/speex.pc.in new file mode 100644 index 000000000..6cd2cbe3f --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/speex.pc.in @@ -0,0 +1,14 @@ +# libspeex pkg-config source file + +prefix=@prefix@ +exec_prefix=@exec_prefix@ +libdir=@libdir@ +includedir=@includedir@ + +Name: speex +Description: Speex is an audio codec tuned for speech +Version: @SPEEX_VERSION@ +Requires: ogg +Conflicts: +Libs: -L${libdir} -lspeex +Cflags: -I${includedir} diff --git a/Code/BF2/External/speex-1.0.5/src/Makefile.am b/Code/BF2/External/speex-1.0.5/src/Makefile.am new file mode 100644 index 000000000..5fe3fb84e --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/src/Makefile.am @@ -0,0 +1,24 @@ +## Process this file with automake to produce Makefile.in. -*-Makefile-*- + +# $Id: Makefile.am,v 1.9.2.1 2003/05/31 06:10:43 jm Exp $ + +# Disable automatic dependency tracking if using other tools than gcc and gmake +#AUTOMAKE_OPTIONS = no-dependencies + +INCLUDES = -I$(top_srcdir)/include -I$(top_srcdir)/libspeex $(OGG_INCLUDES) + +mandir = $(prefix)/share/man +man_MANS = speexenc.1 speexdec.1 + +EXTRA_DIST = $(man_MANS) getopt_win.h getopt.c getopt1.c wave_out.c wave_out.h + +include_HEADERS = +noinst_HEADERS = wav_io.h + +bin_PROGRAMS = speexenc speexdec + +speexenc_SOURCES = speexenc.c wav_io.c +speexenc_LDADD = $(top_builddir)/libspeex/libspeex.la $(OGG_LDFLAGS) $(OGG_LIBS) + +speexdec_SOURCES = speexdec.c wav_io.c +speexdec_LDADD = $(top_builddir)/libspeex/libspeex.la $(OGG_LDFLAGS) $(OGG_LIBS) diff --git a/Code/BF2/External/speex-1.0.5/src/Makefile.in b/Code/BF2/External/speex-1.0.5/src/Makefile.in new file mode 100644 index 000000000..5122b0bbc --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/src/Makefile.in @@ -0,0 +1,555 @@ +# Makefile.in generated by automake 1.8.5 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004 Free Software Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# $Id: Makefile.am,v 1.9.2.1 2003/05/31 06:10:43 jm Exp $ + +# Disable automatic dependency tracking if using other tools than gcc and gmake +#AUTOMAKE_OPTIONS = no-dependencies + + +SOURCES = $(speexdec_SOURCES) $(speexenc_SOURCES) + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +top_builddir = .. +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +INSTALL = @INSTALL@ +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +host_triplet = @host@ +bin_PROGRAMS = speexenc$(EXEEXT) speexdec$(EXEEXT) +subdir = src +DIST_COMMON = $(include_HEADERS) $(noinst_HEADERS) \ + $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ + $(top_srcdir)/configure.in +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs +CONFIG_CLEAN_FILES = +am__installdirs = "$(DESTDIR)$(bindir)" "$(DESTDIR)$(man1dir)" "$(DESTDIR)$(includedir)" +binPROGRAMS_INSTALL = $(INSTALL_PROGRAM) +PROGRAMS = $(bin_PROGRAMS) +am_speexdec_OBJECTS = speexdec.$(OBJEXT) wav_io.$(OBJEXT) +speexdec_OBJECTS = $(am_speexdec_OBJECTS) +am__DEPENDENCIES_1 = +speexdec_DEPENDENCIES = $(top_builddir)/libspeex/libspeex.la \ + $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) +am_speexenc_OBJECTS = speexenc.$(OBJEXT) wav_io.$(OBJEXT) +speexenc_OBJECTS = $(am_speexenc_OBJECTS) +speexenc_DEPENDENCIES = $(top_builddir)/libspeex/libspeex.la \ + $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) +DEFAULT_INCLUDES = -I. -I$(srcdir) +depcomp = $(SHELL) $(top_srcdir)/depcomp +am__depfiles_maybe = depfiles +@AMDEP_TRUE@DEP_FILES = ./$(DEPDIR)/speexdec.Po \ +@AMDEP_TRUE@ ./$(DEPDIR)/speexenc.Po ./$(DEPDIR)/wav_io.Po +COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ + $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +LTCOMPILE = $(LIBTOOL) --mode=compile $(CC) $(DEFS) \ + $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ + $(AM_CFLAGS) $(CFLAGS) +CCLD = $(CC) +LINK = $(LIBTOOL) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ + $(AM_LDFLAGS) $(LDFLAGS) -o $@ +SOURCES = $(speexdec_SOURCES) $(speexenc_SOURCES) +DIST_SOURCES = $(speexdec_SOURCES) $(speexenc_SOURCES) +man1dir = $(mandir)/man1 +NROFF = nroff +MANS = $(man_MANS) +includeHEADERS_INSTALL = $(INSTALL_HEADER) +HEADERS = $(include_HEADERS) $(noinst_HEADERS) +ETAGS = etags +CTAGS = ctags +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMDEP_FALSE = @AMDEP_FALSE@ +AMDEP_TRUE = @AMDEP_TRUE@ +AMTAR = @AMTAR@ +AR = @AR@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +ECHO = @ECHO@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +F77 = @F77@ +FFLAGS = @FFLAGS@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +LDFLAGS = @LDFLAGS@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +MAINT = @MAINT@ +MAINTAINER_MODE_FALSE = @MAINTAINER_MODE_FALSE@ +MAINTAINER_MODE_TRUE = @MAINTAINER_MODE_TRUE@ +MAKEINFO = @MAKEINFO@ +OBJEXT = @OBJEXT@ +OGG_INCLUDES = @OGG_INCLUDES@ +OGG_LDFLAGS = @OGG_LDFLAGS@ +OGG_LIBS = @OGG_LIBS@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +RANLIB = @RANLIB@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SPEEX_LT_AGE = @SPEEX_LT_AGE@ +SPEEX_LT_CURRENT = @SPEEX_LT_CURRENT@ +SPEEX_LT_REVISION = @SPEEX_LT_REVISION@ +SPEEX_VERSION = @SPEEX_VERSION@ +STRIP = @STRIP@ +VERSION = @VERSION@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_CXX = @ac_ct_CXX@ +ac_ct_F77 = @ac_ct_F77@ +ac_ct_RANLIB = @ac_ct_RANLIB@ +ac_ct_STRIP = @ac_ct_STRIP@ +am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ +am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ +am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ +am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +datadir = @datadir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localstatedir = @localstatedir@ +mandir = $(prefix)/share/man +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +src = @src@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +INCLUDES = -I$(top_srcdir)/include -I$(top_srcdir)/libspeex $(OGG_INCLUDES) +man_MANS = speexenc.1 speexdec.1 +EXTRA_DIST = $(man_MANS) getopt_win.h getopt.c getopt1.c wave_out.c wave_out.h +include_HEADERS = +noinst_HEADERS = wav_io.h +speexenc_SOURCES = speexenc.c wav_io.c +speexenc_LDADD = $(top_builddir)/libspeex/libspeex.la $(OGG_LDFLAGS) $(OGG_LIBS) +speexdec_SOURCES = speexdec.c wav_io.c +speexdec_LDADD = $(top_builddir)/libspeex/libspeex.la $(OGG_LDFLAGS) $(OGG_LIBS) +all: all-am + +.SUFFIXES: +.SUFFIXES: .c .lo .o .obj +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ + && exit 0; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/Makefile'; \ + cd $(top_srcdir) && \ + $(AUTOMAKE) --gnu src/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +install-binPROGRAMS: $(bin_PROGRAMS) + @$(NORMAL_INSTALL) + test -z "$(bindir)" || $(mkdir_p) "$(DESTDIR)$(bindir)" + @list='$(bin_PROGRAMS)'; for p in $$list; do \ + p1=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ + if test -f $$p \ + || test -f $$p1 \ + ; then \ + f=`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \ + echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=install $(binPROGRAMS_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \ + $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=install $(binPROGRAMS_INSTALL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \ + else :; fi; \ + done + +uninstall-binPROGRAMS: + @$(NORMAL_UNINSTALL) + @list='$(bin_PROGRAMS)'; for p in $$list; do \ + f=`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/'`; \ + echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \ + rm -f "$(DESTDIR)$(bindir)/$$f"; \ + done + +clean-binPROGRAMS: + @list='$(bin_PROGRAMS)'; for p in $$list; do \ + f=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ + echo " rm -f $$p $$f"; \ + rm -f $$p $$f ; \ + done +speexdec$(EXEEXT): $(speexdec_OBJECTS) $(speexdec_DEPENDENCIES) + @rm -f speexdec$(EXEEXT) + $(LINK) $(speexdec_LDFLAGS) $(speexdec_OBJECTS) $(speexdec_LDADD) $(LIBS) +speexenc$(EXEEXT): $(speexenc_OBJECTS) $(speexenc_DEPENDENCIES) + @rm -f speexenc$(EXEEXT) + $(LINK) $(speexenc_LDFLAGS) $(speexenc_OBJECTS) $(speexenc_LDADD) $(LIBS) + +mostlyclean-compile: + -rm -f *.$(OBJEXT) + +distclean-compile: + -rm -f *.tab.c + +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/speexdec.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/speexenc.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/wav_io.Po@am__quote@ + +.c.o: +@am__fastdepCC_TRUE@ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ +@am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ depfile='$(DEPDIR)/$*.Po' tmpdepfile='$(DEPDIR)/$*.TPo' @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(COMPILE) -c $< + +.c.obj: +@am__fastdepCC_TRUE@ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \ +@am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ depfile='$(DEPDIR)/$*.Po' tmpdepfile='$(DEPDIR)/$*.TPo' @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'` + +.c.lo: +@am__fastdepCC_TRUE@ if $(LTCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ +@am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Plo"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ depfile='$(DEPDIR)/$*.Plo' tmpdepfile='$(DEPDIR)/$*.TPlo' @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(LTCOMPILE) -c -o $@ $< + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +distclean-libtool: + -rm -f libtool +uninstall-info-am: +install-man1: $(man1_MANS) $(man_MANS) + @$(NORMAL_INSTALL) + test -z "$(man1dir)" || $(mkdir_p) "$(DESTDIR)$(man1dir)" + @list='$(man1_MANS) $(dist_man1_MANS) $(nodist_man1_MANS)'; \ + l2='$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \ + for i in $$l2; do \ + case "$$i" in \ + *.1*) list="$$list $$i" ;; \ + esac; \ + done; \ + for i in $$list; do \ + if test -f $(srcdir)/$$i; then file=$(srcdir)/$$i; \ + else file=$$i; fi; \ + ext=`echo $$i | sed -e 's/^.*\\.//'`; \ + case "$$ext" in \ + 1*) ;; \ + *) ext='1' ;; \ + esac; \ + inst=`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \ + inst=`echo $$inst | sed -e 's/^.*\///'`; \ + inst=`echo $$inst | sed '$(transform)'`.$$ext; \ + echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \ + $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst"; \ + done +uninstall-man1: + @$(NORMAL_UNINSTALL) + @list='$(man1_MANS) $(dist_man1_MANS) $(nodist_man1_MANS)'; \ + l2='$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \ + for i in $$l2; do \ + case "$$i" in \ + *.1*) list="$$list $$i" ;; \ + esac; \ + done; \ + for i in $$list; do \ + ext=`echo $$i | sed -e 's/^.*\\.//'`; \ + case "$$ext" in \ + 1*) ;; \ + *) ext='1' ;; \ + esac; \ + inst=`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \ + inst=`echo $$inst | sed -e 's/^.*\///'`; \ + inst=`echo $$inst | sed '$(transform)'`.$$ext; \ + echo " rm -f '$(DESTDIR)$(man1dir)/$$inst'"; \ + rm -f "$(DESTDIR)$(man1dir)/$$inst"; \ + done +install-includeHEADERS: $(include_HEADERS) + @$(NORMAL_INSTALL) + test -z "$(includedir)" || $(mkdir_p) "$(DESTDIR)$(includedir)" + @list='$(include_HEADERS)'; for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + f="`echo $$p | sed -e 's|^.*/||'`"; \ + echo " $(includeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(includedir)/$$f'"; \ + $(includeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(includedir)/$$f"; \ + done + +uninstall-includeHEADERS: + @$(NORMAL_UNINSTALL) + @list='$(include_HEADERS)'; for p in $$list; do \ + f="`echo $$p | sed -e 's|^.*/||'`"; \ + echo " rm -f '$(DESTDIR)$(includedir)/$$f'"; \ + rm -f "$(DESTDIR)$(includedir)/$$f"; \ + done + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + tags=; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$tags $$unique; \ + fi +ctags: CTAGS +CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + tags=; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + test -z "$(CTAGS_ARGS)$$tags$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$tags $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && cd $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) $$here + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ + list='$(DISTFILES)'; for file in $$list; do \ + case $$file in \ + $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ + $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ + esac; \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test "$$dir" != "$$file" && test "$$dir" != "."; then \ + dir="/$$dir"; \ + $(mkdir_p) "$(distdir)$$dir"; \ + else \ + dir=''; \ + fi; \ + if test -d $$d/$$file; then \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + fi; \ + cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + else \ + test -f $(distdir)/$$file \ + || cp -p $$d/$$file $(distdir)/$$file \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile $(PROGRAMS) $(MANS) $(HEADERS) +installdirs: + for dir in "$(DESTDIR)$(bindir)" "$(DESTDIR)$(man1dir)" "$(DESTDIR)$(includedir)"; do \ + test -z "$$dir" || $(mkdir_p) "$$dir"; \ + done +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + `test -z '$(STRIP)' || \ + echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -rm -f $(CONFIG_CLEAN_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am + +distclean: distclean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +distclean-am: clean-am distclean-compile distclean-generic \ + distclean-libtool distclean-tags + +dvi: dvi-am + +dvi-am: + +html: html-am + +info: info-am + +info-am: + +install-data-am: install-includeHEADERS install-man + +install-exec-am: install-binPROGRAMS + +install-info: install-info-am + +install-man: install-man1 + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-compile mostlyclean-generic \ + mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-binPROGRAMS uninstall-includeHEADERS \ + uninstall-info-am uninstall-man + +uninstall-man: uninstall-man1 + +.PHONY: CTAGS GTAGS all all-am check check-am clean clean-binPROGRAMS \ + clean-generic clean-libtool ctags distclean distclean-compile \ + distclean-generic distclean-libtool distclean-tags distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-binPROGRAMS install-data install-data-am install-exec \ + install-exec-am install-includeHEADERS install-info \ + install-info-am install-man install-man1 install-strip \ + installcheck installcheck-am installdirs maintainer-clean \ + maintainer-clean-generic mostlyclean mostlyclean-compile \ + mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ + tags uninstall uninstall-am uninstall-binPROGRAMS \ + uninstall-includeHEADERS uninstall-info-am uninstall-man \ + uninstall-man1 + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/Code/BF2/External/speex-1.0.5/src/getopt.c b/Code/BF2/External/speex-1.0.5/src/getopt.c new file mode 100644 index 000000000..33d299bd4 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/src/getopt.c @@ -0,0 +1,1047 @@ +/* Getopt for GNU. + NOTE: getopt is now part of the C library, so if you don't know what + "Keep this file name-space clean" means, talk to drepper@gnu.org + before changing it! + + Copyright (C) 1987, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 + Free Software Foundation, Inc. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public License as + published by the Free Software Foundation; either version 2 of the + License, or (at your option) any later version. + + The GNU C Library 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 + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with the GNU C Library; see the file COPYING.LIB. If not, + write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, + Boston, MA 02111-1307, USA. */ + +/* This tells Alpha OSF/1 not to define a getopt prototype in . + Ditto for AIX 3.2 and . */ +#ifndef _NO_PROTO +# define _NO_PROTO +#endif + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#if !defined __STDC__ || !__STDC__ +/* This is a separate conditional since some stdc systems + reject `defined (const)'. */ +# ifndef const +# define const +# endif +#endif + +#include + +/* Comment out all this code if we are using the GNU C Library, and are not + actually compiling the library itself. This code is part of the GNU C + Library, but also included in many other GNU distributions. Compiling + and linking in this code is a waste when using the GNU C library + (especially if it is a shared library). Rather than having every GNU + program understand `configure --with-gnu-libc' and omit the object files, + it is simpler to just do this in the source for each such file. */ + +#define GETOPT_INTERFACE_VERSION 2 +#if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2 +# include +# if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION +# define ELIDE_CODE +# endif +#endif + +#ifndef ELIDE_CODE + + +/* This needs to come after some library #include + to get __GNU_LIBRARY__ defined. */ +#ifdef __GNU_LIBRARY__ +/* Don't include stdlib.h for non-GNU C libraries because some of them + contain conflicting prototypes for getopt. */ +# include +# include +#endif /* GNU C library. */ + +#ifdef VMS +# include +# if HAVE_STRING_H - 0 +# include +# endif +#endif + +#ifndef _ +/* This is for other GNU distributions with internationalized messages. + When compiling libc, the _ macro is predefined. */ +# ifdef HAVE_LIBINTL_H +# include +# define _(msgid) gettext (msgid) +# else +# define _(msgid) (msgid) +# endif +#endif + +/* This version of `getopt' appears to the caller like standard Unix `getopt' + but it behaves differently for the user, since it allows the user + to intersperse the options with the other arguments. + + As `getopt' works, it permutes the elements of ARGV so that, + when it is done, all the options precede everything else. Thus + all application programs are extended to handle flexible argument order. + + Setting the environment variable POSIXLY_CORRECT disables permutation. + Then the behavior is completely standard. + + GNU application programs can use a third alternative mode in which + they can distinguish the relative order of options and other arguments. */ + +#include "getopt_win.h" + +/* For communication from `getopt' to the caller. + When `getopt' finds an option that takes an argument, + the argument value is returned here. + Also, when `ordering' is RETURN_IN_ORDER, + each non-option ARGV-element is returned here. */ + +char *optarg; + +/* Index in ARGV of the next element to be scanned. + This is used for communication to and from the caller + and for communication between successive calls to `getopt'. + + On entry to `getopt', zero means this is the first call; initialize. + + When `getopt' returns -1, this is the index of the first of the + non-option elements that the caller should itself scan. + + Otherwise, `optind' communicates from one call to the next + how much of ARGV has been scanned so far. */ + +/* 1003.2 says this must be 1 before any call. */ +int optind = 1; + +/* Formerly, initialization of getopt depended on optind==0, which + causes problems with re-calling getopt as programs generally don't + know that. */ + +int __getopt_initialized; + +/* The next char to be scanned in the option-element + in which the last option character we returned was found. + This allows us to pick up the scan where we left off. + + If this is zero, or a null string, it means resume the scan + by advancing to the next ARGV-element. */ + +static char *nextchar; + +/* Callers store zero here to inhibit the error message + for unrecognized options. */ + +int opterr = 1; + +/* Set to an option character which was unrecognized. + This must be initialized on some systems to avoid linking in the + system's own getopt implementation. */ + +int optopt = '?'; + +/* Describe how to deal with options that follow non-option ARGV-elements. + + If the caller did not specify anything, + the default is REQUIRE_ORDER if the environment variable + POSIXLY_CORRECT is defined, PERMUTE otherwise. + + REQUIRE_ORDER means don't recognize them as options; + stop option processing when the first non-option is seen. + This is what Unix does. + This mode of operation is selected by either setting the environment + variable POSIXLY_CORRECT, or using `+' as the first character + of the list of option characters. + + PERMUTE is the default. We permute the contents of ARGV as we scan, + so that eventually all the non-options are at the end. This allows options + to be given in any order, even with programs that were not written to + expect this. + + RETURN_IN_ORDER is an option available to programs that were written + to expect options and other ARGV-elements in any order and that care about + the ordering of the two. We describe each non-option ARGV-element + as if it were the argument of an option with character code 1. + Using `-' as the first character of the list of option characters + selects this mode of operation. + + The special argument `--' forces an end of option-scanning regardless + of the value of `ordering'. In the case of RETURN_IN_ORDER, only + `--' can cause `getopt' to return -1 with `optind' != ARGC. */ + +static enum +{ + REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER +} ordering; + +/* Value of POSIXLY_CORRECT environment variable. */ +static char *posixly_correct; + +#ifdef __GNU_LIBRARY__ +/* We want to avoid inclusion of string.h with non-GNU libraries + because there are many ways it can cause trouble. + On some systems, it contains special magic macros that don't work + in GCC. */ +# include +# define my_index strchr +#else + +#include + +/* Avoid depending on library functions or files + whose names are inconsistent. */ + +#ifndef getenv +extern char *getenv (); +#endif + +static char * +my_index (str, chr) + const char *str; + int chr; +{ + while (*str) + { + if (*str == chr) + return (char *) str; + str++; + } + return 0; +} + +/* If using GCC, we can safely declare strlen this way. + If not using GCC, it is ok not to declare it. */ +#ifdef __GNUC__ +/* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h. + That was relevant to code that was here before. */ +# if (!defined __STDC__ || !__STDC__) && !defined strlen +/* gcc with -traditional declares the built-in strlen to return int, + and has done so at least since version 2.4.5. -- rms. */ +extern int strlen (const char *); +# endif /* not __STDC__ */ +#endif /* __GNUC__ */ + +#endif /* not __GNU_LIBRARY__ */ + +/* Handle permutation of arguments. */ + +/* Describe the part of ARGV that contains non-options that have + been skipped. `first_nonopt' is the index in ARGV of the first of them; + `last_nonopt' is the index after the last of them. */ + +static int first_nonopt; +static int last_nonopt; + +#ifdef _LIBC +/* Bash 2.0 gives us an environment variable containing flags + indicating ARGV elements that should not be considered arguments. */ + +/* Defined in getopt_init.c */ +extern char *__getopt_nonoption_flags; + +static int nonoption_flags_max_len; +static int nonoption_flags_len; + +static int original_argc; +static char *const *original_argv; + +/* Make sure the environment variable bash 2.0 puts in the environment + is valid for the getopt call we must make sure that the ARGV passed + to getopt is that one passed to the process. */ +static void +__attribute__ ((unused)) +store_args_and_env (int argc, char *const *argv) +{ + /* XXX This is no good solution. We should rather copy the args so + that we can compare them later. But we must not use malloc(3). */ + original_argc = argc; + original_argv = argv; +} +# ifdef text_set_element +text_set_element (__libc_subinit, store_args_and_env); +# endif /* text_set_element */ + +# define SWAP_FLAGS(ch1, ch2) \ + if (nonoption_flags_len > 0) \ + { \ + char __tmp = __getopt_nonoption_flags[ch1]; \ + __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \ + __getopt_nonoption_flags[ch2] = __tmp; \ + } +#else /* !_LIBC */ +# define SWAP_FLAGS(ch1, ch2) +#endif /* _LIBC */ + +/* Exchange two adjacent subsequences of ARGV. + One subsequence is elements [first_nonopt,last_nonopt) + which contains all the non-options that have been skipped so far. + The other is elements [last_nonopt,optind), which contains all + the options processed since those non-options were skipped. + + `first_nonopt' and `last_nonopt' are relocated so that they describe + the new indices of the non-options in ARGV after they are moved. */ + +#if defined __STDC__ && __STDC__ +static void exchange (char **); +#endif + +static void +exchange (argv) + char **argv; +{ + int bottom = first_nonopt; + int middle = last_nonopt; + int top = optind; + char *tem; + + /* Exchange the shorter segment with the far end of the longer segment. + That puts the shorter segment into the right place. + It leaves the longer segment in the right place overall, + but it consists of two parts that need to be swapped next. */ + +#ifdef _LIBC + /* First make sure the handling of the `__getopt_nonoption_flags' + string can work normally. Our top argument must be in the range + of the string. */ + if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len) + { + /* We must extend the array. The user plays games with us and + presents new arguments. */ + char *new_str = malloc (top + 1); + if (new_str == NULL) + nonoption_flags_len = nonoption_flags_max_len = 0; + else + { + memset (__mempcpy (new_str, __getopt_nonoption_flags, + nonoption_flags_max_len), + '\0', top + 1 - nonoption_flags_max_len); + nonoption_flags_max_len = top + 1; + __getopt_nonoption_flags = new_str; + } + } +#endif + + while (top > middle && middle > bottom) + { + if (top - middle > middle - bottom) + { + /* Bottom segment is the short one. */ + int len = middle - bottom; + register int i; + + /* Swap it with the top part of the top segment. */ + for (i = 0; i < len; i++) + { + tem = argv[bottom + i]; + argv[bottom + i] = argv[top - (middle - bottom) + i]; + argv[top - (middle - bottom) + i] = tem; + SWAP_FLAGS (bottom + i, top - (middle - bottom) + i); + } + /* Exclude the moved bottom segment from further swapping. */ + top -= len; + } + else + { + /* Top segment is the short one. */ + int len = top - middle; + register int i; + + /* Swap it with the bottom part of the bottom segment. */ + for (i = 0; i < len; i++) + { + tem = argv[bottom + i]; + argv[bottom + i] = argv[middle + i]; + argv[middle + i] = tem; + SWAP_FLAGS (bottom + i, middle + i); + } + /* Exclude the moved top segment from further swapping. */ + bottom += len; + } + } + + /* Update records for the slots the non-options now occupy. */ + + first_nonopt += (optind - last_nonopt); + last_nonopt = optind; +} + +/* Initialize the internal data when the first call is made. */ + +#if defined __STDC__ && __STDC__ +static const char *_getopt_initialize (int, char *const *, const char *); +#endif +static const char * +_getopt_initialize (argc, argv, optstring) + int argc; + char *const *argv; + const char *optstring; +{ + /* Start processing options with ARGV-element 1 (since ARGV-element 0 + is the program name); the sequence of previously skipped + non-option ARGV-elements is empty. */ + + first_nonopt = last_nonopt = optind; + + nextchar = NULL; + + posixly_correct = getenv ("POSIXLY_CORRECT"); + + /* Determine how to handle the ordering of options and nonoptions. */ + + if (optstring[0] == '-') + { + ordering = RETURN_IN_ORDER; + ++optstring; + } + else if (optstring[0] == '+') + { + ordering = REQUIRE_ORDER; + ++optstring; + } + else if (posixly_correct != NULL) + ordering = REQUIRE_ORDER; + else + ordering = PERMUTE; + +#ifdef _LIBC + if (posixly_correct == NULL + && argc == original_argc && argv == original_argv) + { + if (nonoption_flags_max_len == 0) + { + if (__getopt_nonoption_flags == NULL + || __getopt_nonoption_flags[0] == '\0') + nonoption_flags_max_len = -1; + else + { + const char *orig_str = __getopt_nonoption_flags; + int len = nonoption_flags_max_len = strlen (orig_str); + if (nonoption_flags_max_len < argc) + nonoption_flags_max_len = argc; + __getopt_nonoption_flags = + (char *) malloc (nonoption_flags_max_len); + if (__getopt_nonoption_flags == NULL) + nonoption_flags_max_len = -1; + else + memset (__mempcpy (__getopt_nonoption_flags, orig_str, len), + '\0', nonoption_flags_max_len - len); + } + } + nonoption_flags_len = nonoption_flags_max_len; + } + else + nonoption_flags_len = 0; +#endif + + return optstring; +} + +/* Scan elements of ARGV (whose length is ARGC) for option characters + given in OPTSTRING. + + If an element of ARGV starts with '-', and is not exactly "-" or "--", + then it is an option element. The characters of this element + (aside from the initial '-') are option characters. If `getopt' + is called repeatedly, it returns successively each of the option characters + from each of the option elements. + + If `getopt' finds another option character, it returns that character, + updating `optind' and `nextchar' so that the next call to `getopt' can + resume the scan with the following option character or ARGV-element. + + If there are no more option characters, `getopt' returns -1. + Then `optind' is the index in ARGV of the first ARGV-element + that is not an option. (The ARGV-elements have been permuted + so that those that are not options now come last.) + + OPTSTRING is a string containing the legitimate option characters. + If an option character is seen that is not listed in OPTSTRING, + return '?' after printing an error message. If you set `opterr' to + zero, the error message is suppressed but we still return '?'. + + If a char in OPTSTRING is followed by a colon, that means it wants an arg, + so the following text in the same ARGV-element, or the text of the following + ARGV-element, is returned in `optarg'. Two colons mean an option that + wants an optional arg; if there is text in the current ARGV-element, + it is returned in `optarg', otherwise `optarg' is set to zero. + + If OPTSTRING starts with `-' or `+', it requests different methods of + handling the non-option ARGV-elements. + See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above. + + Long-named options begin with `--' instead of `-'. + Their names may be abbreviated as long as the abbreviation is unique + or is an exact match for some defined option. If they have an + argument, it follows the option name in the same ARGV-element, separated + from the option name by a `=', or else the in next ARGV-element. + When `getopt' finds a long-named option, it returns 0 if that option's + `flag' field is nonzero, the value of the option's `val' field + if the `flag' field is zero. + + The elements of ARGV aren't really const, because we permute them. + But we pretend they're const in the prototype to be compatible + with other systems. + + LONGOPTS is a vector of `struct option' terminated by an + element containing a name which is zero. + + LONGIND returns the index in LONGOPT of the long-named option found. + It is only valid when a long-named option has been found by the most + recent call. + + If LONG_ONLY is nonzero, '-' as well as '--' can introduce + long-named options. */ + +int +_getopt_internal (argc, argv, optstring, longopts, longind, long_only) + int argc; + char *const *argv; + const char *optstring; + const struct option *longopts; + int *longind; + int long_only; +{ + optarg = NULL; + + if (optind == 0 || !__getopt_initialized) + { + if (optind == 0) + optind = 1; /* Don't scan ARGV[0], the program name. */ + optstring = _getopt_initialize (argc, argv, optstring); + __getopt_initialized = 1; + } + + /* Test whether ARGV[optind] points to a non-option argument. + Either it does not have option syntax, or there is an environment flag + from the shell indicating it is not an option. The later information + is only used when the used in the GNU libc. */ +#ifdef _LIBC +# define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0' \ + || (optind < nonoption_flags_len \ + && __getopt_nonoption_flags[optind] == '1')) +#else +# define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0') +#endif + + if (nextchar == NULL || *nextchar == '\0') + { + /* Advance to the next ARGV-element. */ + + /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been + moved back by the user (who may also have changed the arguments). */ + if (last_nonopt > optind) + last_nonopt = optind; + if (first_nonopt > optind) + first_nonopt = optind; + + if (ordering == PERMUTE) + { + /* If we have just processed some options following some non-options, + exchange them so that the options come first. */ + + if (first_nonopt != last_nonopt && last_nonopt != optind) + exchange ((char **) argv); + else if (last_nonopt != optind) + first_nonopt = optind; + + /* Skip any additional non-options + and extend the range of non-options previously skipped. */ + + while (optind < argc && NONOPTION_P) + optind++; + last_nonopt = optind; + } + + /* The special ARGV-element `--' means premature end of options. + Skip it like a null option, + then exchange with previous non-options as if it were an option, + then skip everything else like a non-option. */ + + if (optind != argc && !strcmp (argv[optind], "--")) + { + optind++; + + if (first_nonopt != last_nonopt && last_nonopt != optind) + exchange ((char **) argv); + else if (first_nonopt == last_nonopt) + first_nonopt = optind; + last_nonopt = argc; + + optind = argc; + } + + /* If we have done all the ARGV-elements, stop the scan + and back over any non-options that we skipped and permuted. */ + + if (optind == argc) + { + /* Set the next-arg-index to point at the non-options + that we previously skipped, so the caller will digest them. */ + if (first_nonopt != last_nonopt) + optind = first_nonopt; + return -1; + } + + /* If we have come to a non-option and did not permute it, + either stop the scan or describe it to the caller and pass it by. */ + + if (NONOPTION_P) + { + if (ordering == REQUIRE_ORDER) + return -1; + optarg = argv[optind++]; + return 1; + } + + /* We have found another option-ARGV-element. + Skip the initial punctuation. */ + + nextchar = (argv[optind] + 1 + + (longopts != NULL && argv[optind][1] == '-')); + } + + /* Decode the current option-ARGV-element. */ + + /* Check whether the ARGV-element is a long option. + + If long_only and the ARGV-element has the form "-f", where f is + a valid short option, don't consider it an abbreviated form of + a long option that starts with f. Otherwise there would be no + way to give the -f short option. + + On the other hand, if there's a long option "fubar" and + the ARGV-element is "-fu", do consider that an abbreviation of + the long option, just like "--fu", and not "-f" with arg "u". + + This distinction seems to be the most useful approach. */ + + if (longopts != NULL + && (argv[optind][1] == '-' + || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1]))))) + { + char *nameend; + const struct option *p; + const struct option *pfound = NULL; + int exact = 0; + int ambig = 0; + int indfound = -1; + int option_index; + + for (nameend = nextchar; *nameend && *nameend != '='; nameend++) + /* Do nothing. */ ; + + /* Test all long options for either exact match + or abbreviated matches. */ + for (p = longopts, option_index = 0; p->name; p++, option_index++) + if (!strncmp (p->name, nextchar, nameend - nextchar)) + { + if ((unsigned int) (nameend - nextchar) + == (unsigned int) strlen (p->name)) + { + /* Exact match found. */ + pfound = p; + indfound = option_index; + exact = 1; + break; + } + else if (pfound == NULL) + { + /* First nonexact match found. */ + pfound = p; + indfound = option_index; + } + else + /* Second or later nonexact match found. */ + ambig = 1; + } + + if (ambig && !exact) + { + if (opterr) + fprintf (stderr, _("%s: option `%s' is ambiguous\n"), + argv[0], argv[optind]); + nextchar += strlen (nextchar); + optind++; + optopt = 0; + return '?'; + } + + if (pfound != NULL) + { + option_index = indfound; + optind++; + if (*nameend) + { + /* Don't test has_arg with >, because some C compilers don't + allow it to be used on enums. */ + if (pfound->has_arg) + optarg = nameend + 1; + else + { + if (opterr) + { + if (argv[optind - 1][1] == '-') + /* --option */ + fprintf (stderr, + _("%s: option `--%s' doesn't allow an argument\n"), + argv[0], pfound->name); + else + /* +option or -option */ + fprintf (stderr, + _("%s: option `%c%s' doesn't allow an argument\n"), + argv[0], argv[optind - 1][0], pfound->name); + } + + nextchar += strlen (nextchar); + + optopt = pfound->val; + return '?'; + } + } + else if (pfound->has_arg == 1) + { + if (optind < argc) + optarg = argv[optind++]; + else + { + if (opterr) + fprintf (stderr, + _("%s: option `%s' requires an argument\n"), + argv[0], argv[optind - 1]); + nextchar += strlen (nextchar); + optopt = pfound->val; + return optstring[0] == ':' ? ':' : '?'; + } + } + nextchar += strlen (nextchar); + if (longind != NULL) + *longind = option_index; + if (pfound->flag) + { + *(pfound->flag) = pfound->val; + return 0; + } + return pfound->val; + } + + /* Can't find it as a long option. If this is not getopt_long_only, + or the option starts with '--' or is not a valid short + option, then it's an error. + Otherwise interpret it as a short option. */ + if (!long_only || argv[optind][1] == '-' + || my_index (optstring, *nextchar) == NULL) + { + if (opterr) + { + if (argv[optind][1] == '-') + /* --option */ + fprintf (stderr, _("%s: unrecognized option `--%s'\n"), + argv[0], nextchar); + else + /* +option or -option */ + fprintf (stderr, _("%s: unrecognized option `%c%s'\n"), + argv[0], argv[optind][0], nextchar); + } + nextchar = (char *) ""; + optind++; + optopt = 0; + return '?'; + } + } + + /* Look at and handle the next short option-character. */ + + { + char c = *nextchar++; + char *temp = my_index (optstring, c); + + /* Increment `optind' when we start to process its last character. */ + if (*nextchar == '\0') + ++optind; + + if (temp == NULL || c == ':') + { + if (opterr) + { + if (posixly_correct) + /* 1003.2 specifies the format of this message. */ + fprintf (stderr, _("%s: illegal option -- %c\n"), + argv[0], c); + else + fprintf (stderr, _("%s: invalid option -- %c\n"), + argv[0], c); + } + optopt = c; + return '?'; + } + /* Convenience. Treat POSIX -W foo same as long option --foo */ + if (temp[0] == 'W' && temp[1] == ';') + { + char *nameend; + const struct option *p; + const struct option *pfound = NULL; + int exact = 0; + int ambig = 0; + int indfound = 0; + int option_index; + + /* This is an option that requires an argument. */ + if (*nextchar != '\0') + { + optarg = nextchar; + /* If we end this ARGV-element by taking the rest as an arg, + we must advance to the next element now. */ + optind++; + } + else if (optind == argc) + { + if (opterr) + { + /* 1003.2 specifies the format of this message. */ + fprintf (stderr, _("%s: option requires an argument -- %c\n"), + argv[0], c); + } + optopt = c; + if (optstring[0] == ':') + c = ':'; + else + c = '?'; + return c; + } + else + /* We already incremented `optind' once; + increment it again when taking next ARGV-elt as argument. */ + optarg = argv[optind++]; + + /* optarg is now the argument, see if it's in the + table of longopts. */ + + for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++) + /* Do nothing. */ ; + + /* Test all long options for either exact match + or abbreviated matches. */ + for (p = longopts, option_index = 0; p->name; p++, option_index++) + if (!strncmp (p->name, nextchar, nameend - nextchar)) + { + if ((unsigned int) (nameend - nextchar) == strlen (p->name)) + { + /* Exact match found. */ + pfound = p; + indfound = option_index; + exact = 1; + break; + } + else if (pfound == NULL) + { + /* First nonexact match found. */ + pfound = p; + indfound = option_index; + } + else + /* Second or later nonexact match found. */ + ambig = 1; + } + if (ambig && !exact) + { + if (opterr) + fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"), + argv[0], argv[optind]); + nextchar += strlen (nextchar); + optind++; + return '?'; + } + if (pfound != NULL) + { + option_index = indfound; + if (*nameend) + { + /* Don't test has_arg with >, because some C compilers don't + allow it to be used on enums. */ + if (pfound->has_arg) + optarg = nameend + 1; + else + { + if (opterr) + fprintf (stderr, _("\ +%s: option `-W %s' doesn't allow an argument\n"), + argv[0], pfound->name); + + nextchar += strlen (nextchar); + return '?'; + } + } + else if (pfound->has_arg == 1) + { + if (optind < argc) + optarg = argv[optind++]; + else + { + if (opterr) + fprintf (stderr, + _("%s: option `%s' requires an argument\n"), + argv[0], argv[optind - 1]); + nextchar += strlen (nextchar); + return optstring[0] == ':' ? ':' : '?'; + } + } + nextchar += strlen (nextchar); + if (longind != NULL) + *longind = option_index; + if (pfound->flag) + { + *(pfound->flag) = pfound->val; + return 0; + } + return pfound->val; + } + nextchar = NULL; + return 'W'; /* Let the application handle it. */ + } + if (temp[1] == ':') + { + if (temp[2] == ':') + { + /* This is an option that accepts an argument optionally. */ + if (*nextchar != '\0') + { + optarg = nextchar; + optind++; + } + else + optarg = NULL; + nextchar = NULL; + } + else + { + /* This is an option that requires an argument. */ + if (*nextchar != '\0') + { + optarg = nextchar; + /* If we end this ARGV-element by taking the rest as an arg, + we must advance to the next element now. */ + optind++; + } + else if (optind == argc) + { + if (opterr) + { + /* 1003.2 specifies the format of this message. */ + fprintf (stderr, + _("%s: option requires an argument -- %c\n"), + argv[0], c); + } + optopt = c; + if (optstring[0] == ':') + c = ':'; + else + c = '?'; + } + else + /* We already incremented `optind' once; + increment it again when taking next ARGV-elt as argument. */ + optarg = argv[optind++]; + nextchar = NULL; + } + } + return c; + } +} + +int +getopt (argc, argv, optstring) + int argc; + char *const *argv; + const char *optstring; +{ + return _getopt_internal (argc, argv, optstring, + (const struct option *) 0, + (int *) 0, + 0); +} + +#endif /* Not ELIDE_CODE. */ + +#ifdef TEST + +/* Compile with -DTEST to make an executable for use in testing + the above definition of `getopt'. */ + +int +main (argc, argv) + int argc; + char **argv; +{ + int c; + int digit_optind = 0; + + while (1) + { + int this_option_optind = optind ? optind : 1; + + c = getopt (argc, argv, "abc:d:0123456789"); + if (c == -1) + break; + + switch (c) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + if (digit_optind != 0 && digit_optind != this_option_optind) + printf ("digits occur in two different argv-elements.\n"); + digit_optind = this_option_optind; + printf ("option %c\n", c); + break; + + case 'a': + printf ("option a\n"); + break; + + case 'b': + printf ("option b\n"); + break; + + case 'c': + printf ("option c with value `%s'\n", optarg); + break; + + case '?': + break; + + default: + printf ("?? getopt returned character code 0%o ??\n", c); + } + } + + if (optind < argc) + { + printf ("non-option ARGV-elements: "); + while (optind < argc) + printf ("%s ", argv[optind++]); + printf ("\n"); + } + + exit (0); +} + +#endif /* TEST */ diff --git a/Code/BF2/External/speex-1.0.5/src/getopt1.c b/Code/BF2/External/speex-1.0.5/src/getopt1.c new file mode 100644 index 000000000..39f8383e9 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/src/getopt1.c @@ -0,0 +1,188 @@ +/* getopt_long and getopt_long_only entry points for GNU getopt. + Copyright (C) 1987,88,89,90,91,92,93,94,96,97,98 + Free Software Foundation, Inc. + This file is part of the GNU C Library. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public License as + published by the Free Software Foundation; either version 2 of the + License, or (at your option) any later version. + + The GNU C Library 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 + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with the GNU C Library; see the file COPYING.LIB. If not, + write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, + Boston, MA 02111-1307, USA. */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "getopt_win.h" + +#if !defined __STDC__ || !__STDC__ +/* This is a separate conditional since some stdc systems + reject `defined (const)'. */ +#ifndef const +#define const +#endif +#endif + +#include + +/* Comment out all this code if we are using the GNU C Library, and are not + actually compiling the library itself. This code is part of the GNU C + Library, but also included in many other GNU distributions. Compiling + and linking in this code is a waste when using the GNU C library + (especially if it is a shared library). Rather than having every GNU + program understand `configure --with-gnu-libc' and omit the object files, + it is simpler to just do this in the source for each such file. */ + +#define GETOPT_INTERFACE_VERSION 2 +#if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2 +#include +#if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION +#define ELIDE_CODE +#endif +#endif + +#ifndef ELIDE_CODE + + +/* This needs to come after some library #include + to get __GNU_LIBRARY__ defined. */ +#ifdef __GNU_LIBRARY__ +#include +#endif + +#ifndef NULL +#define NULL 0 +#endif + +int +getopt_long (argc, argv, options, long_options, opt_index) + int argc; + char *const *argv; + const char *options; + const struct option *long_options; + int *opt_index; +{ + return _getopt_internal (argc, argv, options, long_options, opt_index, 0); +} + +/* Like getopt_long, but '-' as well as '--' can indicate a long option. + If an option that starts with '-' (not '--') doesn't match a long option, + but does match a short option, it is parsed as a short option + instead. */ + +int +getopt_long_only (argc, argv, options, long_options, opt_index) + int argc; + char *const *argv; + const char *options; + const struct option *long_options; + int *opt_index; +{ + return _getopt_internal (argc, argv, options, long_options, opt_index, 1); +} + + +#endif /* Not ELIDE_CODE. */ + +#ifdef TEST + +#include + +int +main (argc, argv) + int argc; + char **argv; +{ + int c; + int digit_optind = 0; + + while (1) + { + int this_option_optind = optind ? optind : 1; + int option_index = 0; + static struct option long_options[] = + { + {"add", 1, 0, 0}, + {"append", 0, 0, 0}, + {"delete", 1, 0, 0}, + {"verbose", 0, 0, 0}, + {"create", 0, 0, 0}, + {"file", 1, 0, 0}, + {0, 0, 0, 0} + }; + + c = getopt_long (argc, argv, "abc:d:0123456789", + long_options, &option_index); + if (c == -1) + break; + + switch (c) + { + case 0: + printf ("option %s", long_options[option_index].name); + if (optarg) + printf (" with arg %s", optarg); + printf ("\n"); + break; + + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + if (digit_optind != 0 && digit_optind != this_option_optind) + printf ("digits occur in two different argv-elements.\n"); + digit_optind = this_option_optind; + printf ("option %c\n", c); + break; + + case 'a': + printf ("option a\n"); + break; + + case 'b': + printf ("option b\n"); + break; + + case 'c': + printf ("option c with value `%s'\n", optarg); + break; + + case 'd': + printf ("option d with value `%s'\n", optarg); + break; + + case '?': + break; + + default: + printf ("?? getopt returned character code 0%o ??\n", c); + } + } + + if (optind < argc) + { + printf ("non-option ARGV-elements: "); + while (optind < argc) + printf ("%s ", argv[optind++]); + printf ("\n"); + } + + exit (0); +} + +#endif /* TEST */ diff --git a/Code/BF2/External/speex-1.0.5/src/getopt_win.h b/Code/BF2/External/speex-1.0.5/src/getopt_win.h new file mode 100644 index 000000000..91eb54e55 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/src/getopt_win.h @@ -0,0 +1,169 @@ +/* Declarations for getopt. + Copyright (C) 1989,90,91,92,93,94,96,97,98 Free Software Foundation, Inc. + This file is part of the GNU C Library. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public License as + published by the Free Software Foundation; either version 2 of the + License, or (at your option) any later version. + + The GNU C Library 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 + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with the GNU C Library; see the file COPYING.LIB. If not, + write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, + Boston, MA 02111-1307, USA. */ + +#ifndef _GETOPT_H + +#ifndef __need_getopt +# define _GETOPT_H 1 +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* For communication from `getopt' to the caller. + When `getopt' finds an option that takes an argument, + the argument value is returned here. + Also, when `ordering' is RETURN_IN_ORDER, + each non-option ARGV-element is returned here. */ + +extern char *optarg; + +/* Index in ARGV of the next element to be scanned. + This is used for communication to and from the caller + and for communication between successive calls to `getopt'. + + On entry to `getopt', zero means this is the first call; initialize. + + When `getopt' returns -1, this is the index of the first of the + non-option elements that the caller should itself scan. + + Otherwise, `optind' communicates from one call to the next + how much of ARGV has been scanned so far. */ + +extern int optind; + +/* Callers store zero here to inhibit the error message `getopt' prints + for unrecognized options. */ + +extern int opterr; + +/* Set to an option character which was unrecognized. */ + +extern int optopt; + +#ifndef __need_getopt +/* Describe the long-named options requested by the application. + The LONG_OPTIONS argument to getopt_long or getopt_long_only is a vector + of `struct option' terminated by an element containing a name which is + zero. + + The field `has_arg' is: + no_argument (or 0) if the option does not take an argument, + required_argument (or 1) if the option requires an argument, + optional_argument (or 2) if the option takes an optional argument. + + If the field `flag' is not NULL, it points to a variable that is set + to the value given in the field `val' when the option is found, but + left unchanged if the option is not found. + + To have a long-named option do something other than set an `int' to + a compiled-in constant, such as set a value from `optarg', set the + option's `flag' field to zero and its `val' field to a nonzero + value (the equivalent single-letter option character, if there is + one). For long options that have a zero `flag' field, `getopt' + returns the contents of the `val' field. */ + +struct option +{ +# if defined __STDC__ && __STDC__ + const char *name; +# else + char *name; +# endif + /* has_arg can't be an enum because some compilers complain about + type mismatches in all the code that assumes it is an int. */ + int has_arg; + int *flag; + int val; +}; + +/* Names for the values of the `has_arg' field of `struct option'. */ + +# define no_argument 0 +# define required_argument 1 +# define optional_argument 2 +#endif /* need getopt */ + + +/* Get definitions and prototypes for functions to process the + arguments in ARGV (ARGC of them, minus the program name) for + options given in OPTS. + + Return the option character from OPTS just read. Return -1 when + there are no more options. For unrecognized options, or options + missing arguments, `optopt' is set to the option letter, and '?' is + returned. + + The OPTS string is a list of characters which are recognized option + letters, optionally followed by colons, specifying that that letter + takes an argument, to be placed in `optarg'. + + If a letter in OPTS is followed by two colons, its argument is + optional. This behavior is specific to the GNU `getopt'. + + The argument `--' causes premature termination of argument + scanning, explicitly telling `getopt' that there are no more + options. + + If OPTS begins with `--', then non-option arguments are treated as + arguments to the option '\0'. This behavior is specific to the GNU + `getopt'. */ + +#if defined __STDC__ && __STDC__ +# ifdef __GNU_LIBRARY__ +/* Many other libraries have conflicting prototypes for getopt, with + differences in the consts, in stdlib.h. To avoid compilation + errors, only prototype getopt for the GNU C library. */ +extern int getopt (int __argc, char *const *__argv, const char *__shortopts); +# else /* not __GNU_LIBRARY__ */ +extern int getopt (); +# endif /* __GNU_LIBRARY__ */ + +# ifndef __need_getopt +extern int getopt_long (int __argc, char *const *__argv, const char *__shortopts, + const struct option *__longopts, int *__longind); +extern int getopt_long_only (int __argc, char *const *__argv, + const char *__shortopts, + const struct option *__longopts, int *__longind); + +/* Internal only. Users should not call this directly. */ +extern int _getopt_internal (int __argc, char *const *__argv, + const char *__shortopts, + const struct option *__longopts, int *__longind, + int __long_only); +# endif +#else /* not __STDC__ */ +extern int getopt (); +# ifndef __need_getopt +extern int getopt_long (); +extern int getopt_long_only (); + +extern int _getopt_internal (); +# endif +#endif /* __STDC__ */ + +#ifdef __cplusplus +} +#endif + +/* Make sure we later can get all the definitions and declarations. */ +#undef __need_getopt + +#endif /* getopt.h */ diff --git a/Code/BF2/External/speex-1.0.5/src/speexdec.1 b/Code/BF2/External/speex-1.0.5/src/speexdec.1 new file mode 100644 index 000000000..8d4ef2e96 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/src/speexdec.1 @@ -0,0 +1,78 @@ +.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.29. +.TH SPEEXDEC "1" "September 2003" "speexdec version 1.0.3" "User Commands" +.SH NAME +speexdec \- manual page for speexdec version 1.0.3 +.SH SYNOPSIS +.B speexdec +[\fIoptions\fR] \fIinput_file.spx \fR[\fIoutput_file\fR] +.SH DESCRIPTION +Decodes a Speex file and produce a WAV file or raw file +.SS "input_file can be:" +.TP +filename.spx +regular Speex file +.TP +- +stdin +.SS "output_file can be:" +.TP +filename.wav +Wav file +.TP +filename.* +Raw PCM file (any extension other that .wav) +.TP +- +stdout +.TP +(nothing) +Will be played to soundcard +.SH OPTIONS +.TP +\fB\-\-enh\fR +Enable perceptual enhancement (default) +.TP +\fB\-\-no\-enh\fR +Disable perceptual enhancement +.TP +\fB\-\-force\-nb\fR +Force decoding in narrowband +.TP +\fB\-\-force\-wb\fR +Force decoding in wideband +.TP +\fB\-\-force\-uwb\fR +Force decoding in ultra-wideband +.TP +\fB\-\-mono\fR +Force decoding in mono +.TP +\fB\-\-stereo\fR +Force decoding in stereo +.TP +\fB\-\-rate\fR n +Force decoding at sampling rate n Hz +.TP +\fB\-\-packet\-loss\fR n +Simulate n % random packet loss +.TP +\fB\-V\fR +Verbose mode (show bit-rate) +.TP +\fB\-h\fR, \fB\-\-help\fR +This help +.TP +\fB\-v\fR, \fB\-\-version\fR +Version information +.TP +\fB\-\-pf\fR +Deprecated, use \fB\-\-enh\fR instead +.TP +\fB\-\-no\-pf\fR +Deprecated, use \fB\-\-no\-enh\fR instead +.PP +More information is available from the Speex site: http://www.speex.org +.PP +Please report bugs to the mailing list `speex-dev@xiph.org'. +.SH COPYRIGHT +Copyright \(co 2002 Jean-Marc Valin diff --git a/Code/BF2/External/speex-1.0.5/src/speexdec.c b/Code/BF2/External/speex-1.0.5/src/speexdec.c new file mode 100644 index 000000000..cffac997c --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/src/speexdec.c @@ -0,0 +1,767 @@ +/* Copyright (C) 2002-2003 Jean-Marc Valin + File: speexdec.c + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + + +#include +#if !defined WIN32 && !defined _WIN32 +#include +#include +#endif +#include +#include + +#include +#include + +#if defined WIN32 || defined _WIN32 +#include +#include "getopt_win.h" +#include "wave_out.h" +/* We need the following two to set stdout to binary */ +#include +#include +#endif +#include + +#ifdef __MINGW32__ +#include "wave_out.c" +#endif + +#ifdef HAVE_SYS_SOUNDCARD_H +#include +#include +#include +#include +#include + +#elif defined HAVE_SYS_AUDIOIO_H +#include +#include +#include +#include +#ifndef AUDIO_ENCODING_SLINEAR +#define AUDIO_ENCODING_SLINEAR AUDIO_ENCODING_LINEAR /* Solaris */ +#endif + +#endif + +#include +#include "wav_io.h" +#include +#include +#include +#include "misc.h" + +#define MAX_FRAME_SIZE 2000 + +#define readint(buf, base) (((buf[base+3]<<24)&0xff000000)| \ + ((buf[base+2]<<16)&0xff0000)| \ + ((buf[base+1]<<8)&0xff00)| \ + (buf[base]&0xff)) + +static void print_comments(char *comments, int length) +{ + char *c=comments; + int len, i, nb_fields; + char *end; + + if (length<8) + { + fprintf (stderr, "Invalid/corrupted comments\n"); + return; + } + end = c+length; + len=readint(c, 0); + c+=4; + if (c+len>end) + { + fprintf (stderr, "Invalid/corrupted comments\n"); + return; + } + fwrite(c, 1, len, stderr); + c+=len; + fprintf (stderr, "\n"); + if (c+4>end) + { + fprintf (stderr, "Invalid/corrupted comments\n"); + return; + } + nb_fields=readint(c, 0); + c+=4; + for (i=0;iend) + { + fprintf (stderr, "Invalid/corrupted comments\n"); + return; + } + len=readint(c, 0); + c+=4; + if (c+len>end) + { + fprintf (stderr, "Invalid/corrupted comments\n"); + return; + } + fwrite(c, 1, len, stderr); + c+=len; + fprintf (stderr, "\n"); + } +} + +FILE *out_file_open(char *outFile, int rate, int *channels) +{ + FILE *fout=NULL; + /*Open output file*/ + if (strlen(outFile)==0) + { +#if defined HAVE_SYS_SOUNDCARD_H + int audio_fd, format, stereo; + audio_fd=open("/dev/dsp", O_WRONLY); + if (audio_fd<0) + { + perror("Cannot open /dev/dsp"); + exit(1); + } + + format=AFMT_S16_NE; + if (ioctl(audio_fd, SNDCTL_DSP_SETFMT, &format)==-1) + { + perror("SNDCTL_DSP_SETFMT"); + close(audio_fd); + exit(1); + } + + stereo=0; + if (*channels==2) + stereo=1; + if (ioctl(audio_fd, SNDCTL_DSP_STEREO, &stereo)==-1) + { + perror("SNDCTL_DSP_STEREO"); + close(audio_fd); + exit(1); + } + if (stereo!=0) + { + if (*channels==1) + fprintf (stderr, "Cannot set mono mode, will decode in stereo\n"); + *channels=2; + } + + if (ioctl(audio_fd, SNDCTL_DSP_SPEED, &rate)==-1) + { + perror("SNDCTL_DSP_SPEED"); + close(audio_fd); + exit(1); + } + fout = fdopen(audio_fd, "w"); +#elif defined HAVE_SYS_AUDIOIO_H + audio_info_t info; + int audio_fd; + + audio_fd = open("/dev/audio", O_WRONLY); + if (audio_fd<0) + { + perror("Cannot open /dev/audio"); + exit(1); + } + + AUDIO_INITINFO(&info); +#ifdef AUMODE_PLAY /* NetBSD/OpenBSD */ + info.mode = AUMODE_PLAY; +#endif + info.play.encoding = AUDIO_ENCODING_SLINEAR; + info.play.precision = 16; + info.play.sample_rate = rate; + info.play.channels = *channels; + + if (ioctl(audio_fd, AUDIO_SETINFO, &info) < 0) + { + perror ("AUDIO_SETINFO"); + exit(1); + } + fout = fdopen(audio_fd, "w"); +#elif defined WIN32 || defined _WIN32 + { + unsigned int speex_channels = *channels; + if (Set_WIN_Params (INVALID_FILEDESC, rate, SAMPLE_SIZE, speex_channels)) + { + fprintf (stderr, "Can't access %s\n", "WAVE OUT"); + exit(1); + } + } +#else + fprintf (stderr, "No soundcard support\n"); + exit(1); +#endif + } else { + if (strcmp(outFile,"-")==0) + { +#if defined WIN32 || defined _WIN32 + _setmode(_fileno(stdout), _O_BINARY); +#endif + fout=stdout; + } + else + { + fout = fopen(outFile, "wb"); + if (!fout) + { + perror(outFile); + exit(1); + } + if (strcmp(outFile+strlen(outFile)-4,".wav")==0 || strcmp(outFile+strlen(outFile)-4,".WAV")==0) + write_wav_header(fout, rate, *channels, 0, 0); + } + } + return fout; +} + +void usage() +{ + printf ("Usage: speexdec [options] input_file.spx [output_file]\n"); + printf ("\n"); + printf ("Decodes a Speex file and produce a WAV file or raw file\n"); + printf ("\n"); + printf ("input_file can be:\n"); + printf (" filename.spx regular Speex file\n"); + printf (" - stdin\n"); + printf ("\n"); + printf ("output_file can be:\n"); + printf (" filename.wav Wav file\n"); + printf (" filename.* Raw PCM file (any extension other that .wav)\n"); + printf (" - stdout\n"); + printf (" (nothing) Will be played to soundcard\n"); + printf ("\n"); + printf ("Options:\n"); + printf (" --enh Enable perceptual enhancement (default)\n"); + printf (" --no-enh Disable perceptual enhancement\n"); + printf (" --force-nb Force decoding in narrowband\n"); + printf (" --force-wb Force decoding in wideband\n"); + printf (" --force-uwb Force decoding in ultra-wideband\n"); + printf (" --mono Force decoding in mono\n"); + printf (" --stereo Force decoding in stereo\n"); + printf (" --rate n Force decoding at sampling rate n Hz\n"); + printf (" --packet-loss n Simulate n %% random packet loss\n"); + printf (" -V Verbose mode (show bit-rate)\n"); + printf (" -h, --help This help\n"); + printf (" -v, --version Version information\n"); + printf (" --pf Deprecated, use --enh instead\n"); + printf (" --no-pf Deprecated, use --no-enh instead\n"); + printf ("\n"); + printf ("More information is available from the Speex site: http://www.speex.org\n"); + printf ("\n"); + printf ("Please report bugs to the mailing list `speex-dev@xiph.org'.\n"); +} + +void version() +{ + printf ("speexdec (Speex decoder) version " SPEEX_VERSION " (compiled " __DATE__ ")\n"); + printf ("Copyright (C) 2002-2003 Jean-Marc Valin\n"); +} + +void version_short() +{ + printf ("speexdec version " SPEEX_VERSION "\n"); + printf ("Copyright (C) 2002-2003 Jean-Marc Valin\n"); +} + +static void *process_header(ogg_packet *op, int enh_enabled, int *frame_size, int *rate, int *nframes, int forceMode, int *channels, SpeexStereoState *stereo, int *extra_headers, int quiet) +{ + void *st; + SpeexMode *mode; + SpeexHeader *header; + int modeID; + SpeexCallback callback; + + header = speex_packet_to_header((char*)op->packet, op->bytes); + if (!header) + { + fprintf (stderr, "Cannot read header\n"); + return NULL; + } + if (header->mode >= SPEEX_NB_MODES) + { + fprintf (stderr, "Mode number %d does not (yet/any longer) exist in this version\n", + header->mode); + return NULL; + } + + modeID = header->mode; + if (forceMode!=-1) + modeID = forceMode; + + mode = speex_lib_get_mode (modeID); + + if (header->speex_version_id > 1) + { + fprintf (stderr, "This file was encoded with Speex bit-stream version %d, which I don't know how to decode\n", header->speex_version_id); + return NULL; + } + + if (mode->bitstream_version < header->mode_bitstream_version) + { + fprintf (stderr, "The file was encoded with a newer version of Speex. You need to upgrade in order to play it.\n"); + return NULL; + } + if (mode->bitstream_version > header->mode_bitstream_version) + { + fprintf (stderr, "The file was encoded with an older version of Speex. You would need to downgrade the version in order to play it.\n"); + return NULL; + } + + st = speex_decoder_init(mode); + if (!st) + { + fprintf (stderr, "Decoder initialization failed.\n"); + return NULL; + } + speex_decoder_ctl(st, SPEEX_SET_ENH, &enh_enabled); + speex_decoder_ctl(st, SPEEX_GET_FRAME_SIZE, frame_size); + + if (!(*channels==1)) + { + callback.callback_id = SPEEX_INBAND_STEREO; + callback.func = speex_std_stereo_request_handler; + callback.data = stereo; + speex_decoder_ctl(st, SPEEX_SET_HANDLER, &callback); + } + if (!*rate) + *rate = header->rate; + /* Adjust rate if --force-* options are used */ + if (forceMode!=-1) + { + if (header->mode < forceMode) + *rate <<= (forceMode - header->mode); + if (header->mode > forceMode) + *rate >>= (header->mode - forceMode); + } + + speex_decoder_ctl(st, SPEEX_SET_SAMPLING_RATE, rate); + + *nframes = header->frames_per_packet; + + if (*channels==-1) + *channels = header->nb_channels; + + if (!quiet) + { + fprintf (stderr, "Decoding %d Hz audio using %s mode", + *rate, mode->modeName); + + if (*channels==1) + fprintf (stderr, " (mono"); + else + fprintf (stderr, " (stereo"); + + if (header->vbr) + fprintf (stderr, ", VBR)\n"); + else + fprintf(stderr, ")\n"); + /*fprintf (stderr, "Decoding %d Hz audio at %d bps using %s mode\n", + *rate, mode->bitrate, mode->modeName);*/ + } + + *extra_headers = header->extra_headers; + + free(header); + return st; +} + +int main(int argc, char **argv) +{ + int c; + int option_index = 0; + char *inFile, *outFile; + FILE *fin, *fout=NULL; + short out[MAX_FRAME_SIZE]; + short output[MAX_FRAME_SIZE]; + int frame_size=0; + void *st=NULL; + SpeexBits bits; + int packet_count=0; + int stream_init = 0; + int quiet = 0; + ogg_int64_t page_granule=0, last_granule=0; + int skip_samples=0, page_nb_packets; + struct option long_options[] = + { + {"help", no_argument, NULL, 0}, + {"quiet", no_argument, NULL, 0}, + {"version", no_argument, NULL, 0}, + {"version-short", no_argument, NULL, 0}, + {"enh", no_argument, NULL, 0}, + {"no-enh", no_argument, NULL, 0}, + {"pf", no_argument, NULL, 0}, + {"no-pf", no_argument, NULL, 0}, + {"force-nb", no_argument, NULL, 0}, + {"force-wb", no_argument, NULL, 0}, + {"force-uwb", no_argument, NULL, 0}, + {"rate", required_argument, NULL, 0}, + {"mono", no_argument, NULL, 0}, + {"stereo", no_argument, NULL, 0}, + {"packet-loss", required_argument, NULL, 0}, + {0, 0, 0, 0} + }; + ogg_sync_state oy; + ogg_page og; + ogg_packet op; + ogg_stream_state os; + int enh_enabled; + int nframes=2; + int print_bitrate=0; + int close_in=0; + int eos=0; + int forceMode=-1; + int audio_size=0; + float loss_percent=-1; + SpeexStereoState stereo = SPEEX_STEREO_STATE_INIT; + int channels=-1; + int rate=0; + int extra_headers; + int wav_format=0; + + enh_enabled = 1; + + /*Process options*/ + while(1) + { + c = getopt_long (argc, argv, "hvV", + long_options, &option_index); + if (c==-1) + break; + + switch(c) + { + case 0: + if (strcmp(long_options[option_index].name,"help")==0) + { + usage(); + exit(0); + } else if (strcmp(long_options[option_index].name,"quiet")==0) + { + quiet = 1; + } else if (strcmp(long_options[option_index].name,"version")==0) + { + version(); + exit(0); + } else if (strcmp(long_options[option_index].name,"version-short")==0) + { + version_short(); + exit(0); + } else if (strcmp(long_options[option_index].name,"enh")==0) + { + enh_enabled=1; + } else if (strcmp(long_options[option_index].name,"no-enh")==0) + { + enh_enabled=0; + } else if (strcmp(long_options[option_index].name,"pf")==0) + { + fprintf (stderr, "--pf is deprecated, use --enh instead\n"); + enh_enabled=1; + } else if (strcmp(long_options[option_index].name,"no-pf")==0) + { + fprintf (stderr, "--no-pf is deprecated, use --no-enh instead\n"); + enh_enabled=0; + } else if (strcmp(long_options[option_index].name,"force-nb")==0) + { + forceMode=0; + } else if (strcmp(long_options[option_index].name,"force-wb")==0) + { + forceMode=1; + } else if (strcmp(long_options[option_index].name,"force-uwb")==0) + { + forceMode=2; + } else if (strcmp(long_options[option_index].name,"mono")==0) + { + channels=1; + } else if (strcmp(long_options[option_index].name,"stereo")==0) + { + channels=2; + } else if (strcmp(long_options[option_index].name,"rate")==0) + { + rate=atoi (optarg); + } else if (strcmp(long_options[option_index].name,"packet-loss")==0) + { + loss_percent = atof(optarg); + } + break; + case 'h': + usage(); + exit(0); + break; + case 'v': + version(); + exit(0); + break; + case 'V': + print_bitrate=1; + break; + case '?': + usage(); + exit(1); + break; + } + } + if (argc-optind!=2 && argc-optind!=1) + { + usage(); + exit(1); + } + inFile=argv[optind]; + + if (argc-optind==2) + outFile=argv[optind+1]; + else + outFile = ""; + wav_format = strlen(outFile)>=4 && ( + strcmp(outFile+strlen(outFile)-4,".wav")==0 + || strcmp(outFile+strlen(outFile)-4,".WAV")==0); + /*Open input file*/ + if (strcmp(inFile, "-")==0) + { +#if defined WIN32 || defined _WIN32 + _setmode(_fileno(stdin), _O_BINARY); +#endif + fin=stdin; + } + else + { + fin = fopen(inFile, "rb"); + if (!fin) + { + perror(inFile); + exit(1); + } + close_in=1; + } + + + /*Init Ogg data struct*/ + ogg_sync_init(&oy); + + speex_bits_init(&bits); + /*Main decoding loop*/ + while (1) + { + char *data; + int i, j, nb_read; + /*Get the ogg buffer for writing*/ + data = ogg_sync_buffer(&oy, 200); + /*Read bitstream from input file*/ + nb_read = fread(data, sizeof(char), 200, fin); + ogg_sync_wrote(&oy, nb_read); + + /*Loop for all complete pages we got (most likely only one)*/ + while (ogg_sync_pageout(&oy, &og)==1) + { + int packet_no; + if (stream_init == 0) { + ogg_stream_init(&os, ogg_page_serialno(&og)); + stream_init = 1; + } + /*Add page to the bitstream*/ + ogg_stream_pagein(&os, &og); + page_granule = ogg_page_granulepos(&og); + page_nb_packets = ogg_page_packets(&og); + if (page_granule>0 && frame_size) + { + skip_samples = page_nb_packets*frame_size*nframes - (page_granule-last_granule); + if (ogg_page_eos(&og)) + skip_samples = -skip_samples; + /*else if (!ogg_page_bos(&og)) + skip_samples = 0;*/ + } else + { + skip_samples = 0; + } + /*printf ("page granulepos: %d %d %d\n", skip_samples, page_nb_packets, (int)page_granule);*/ + last_granule = page_granule; + /*Extract all available packets*/ + packet_no=0; + while (!eos && ogg_stream_packetout(&os, &op)==1) + { + /*If first packet, process as Speex header*/ + if (packet_count==0) + { + st = process_header(&op, enh_enabled, &frame_size, &rate, &nframes, forceMode, &channels, &stereo, &extra_headers, quiet); + if (!nframes) + nframes=1; + if (!st) + exit(1); + fout = out_file_open(outFile, rate, &channels); + + } else if (packet_count==1) + { + if (!quiet) + print_comments((char*)op.packet, op.bytes); + } else if (packet_count<=1+extra_headers) + { + /* Ignore extra headers */ + } else { + int lost=0; + packet_no++; + if (loss_percent>0 && 100*((float)rand())/RAND_MAX 0) + { + /*printf ("chopping first packet\n");*/ + new_frame_size -= skip_samples; + frame_offset = skip_samples; + } + if (packet_no == page_nb_packets && skip_samples < 0) + { + int packet_length = nframes*frame_size+skip_samples; + new_frame_size = packet_length - j*frame_size; + if (new_frame_size<0) + new_frame_size = 0; + if (new_frame_size>frame_size) + new_frame_size = frame_size; + /*printf ("chopping end: %d %d %d\n", new_frame_size, packet_length, packet_no);*/ + } + if (new_frame_size) + { +#if defined WIN32 || defined _WIN32 + if (strlen(outFile)==0) + WIN_Play_Samples (out+frame_offset*channels, sizeof(short) * new_frame_size*channels); + else +#endif + fwrite(out+frame_offset*channels, sizeof(short), new_frame_size*channels, fout); + + audio_size+=sizeof(short)*new_frame_size*channels; + } + } + } + } + packet_count++; + } + } + if (feof(fin)) + break; + + } + + if (wav_format) + { + if (fseek(fout,4,SEEK_SET)==0) + { + int tmp; + tmp = le_int(audio_size+36); + fwrite(&tmp,4,1,fout); + if (fseek(fout,32,SEEK_CUR)==0) + { + tmp = le_int(audio_size); + fwrite(&tmp,4,1,fout); + } else + { + fprintf (stderr, "First seek worked, second didn't\n"); + } + } else { + fprintf (stderr, "Cannot seek on wave file, size will be incorrect\n"); + } + } + + if (st) + speex_decoder_destroy(st); + else + { + fprintf (stderr, "This doesn't look like a Speex file\n"); + } + speex_bits_destroy(&bits); + if (stream_init) + ogg_stream_clear(&os); + ogg_sync_clear(&oy); + +#if defined WIN32 || defined _WIN32 + if (strlen(outFile)==0) + WIN_Audio_close (); +#endif + + if (close_in) + fclose(fin); + if (fout != NULL) + fclose(fout); + + return 0; +} diff --git a/Code/BF2/External/speex-1.0.5/src/speexenc.1 b/Code/BF2/External/speex-1.0.5/src/speexenc.1 new file mode 100644 index 000000000..5b3c8c0e8 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/src/speexenc.1 @@ -0,0 +1,105 @@ +.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.29. +.TH SPEEXENC "1" "September 2003" "speexenc version 1.0.3" "User Commands" +.SH NAME +speexenc \- manual page for speexenc version 1.0.3 +.SH SYNOPSIS +.B speexenc +[\fIoptions\fR] \fIinput_file output_file\fR +.SH DESCRIPTION +Encodes input_file using Speex. It can read the WAV or raw files. +.SS "input_file can be:" +.TP +filename.wav +wav file +.TP +filename.* +Raw PCM file (any extension other than .wav) +.TP +- +stdin +.SS "output_file can be:" +.TP +filename.spx +Speex file +.TP +- +stdout +.SH OPTIONS +.TP +\fB\-n\fR, \fB\-\-narrowband\fR +Narrowband (8 kHz) input file +.TP +\fB\-w\fR, \fB\-\-wideband\fR +Wideband (16 kHz) input file +.HP +\fB\-u\fR, \fB\-\-ultra\-wideband\fR "Ultra-wideband" (32 kHz) input file +.TP +\fB\-\-quality\fR n +Encoding quality (0-10), default 3 +.TP +\fB\-\-bitrate\fR n +Encoding bit-rate (use bit-rate n or lower) +.TP +\fB\-\-vbr\fR +Enable variable bit-rate (VBR) +.TP +\fB\-\-abr\fR rate +Enable average bit-rate (ABR) at rate bps +.TP +\fB\-\-vad\fR +Enable voice activity detection (VAD) +.TP +\fB\-\-dtx\fR +Enable file-based discontinuous transmission (DTX) +.TP +\fB\-\-comp\fR n +Set encoding complexity (0-10), default 3 +.TP +\fB\-\-nframes\fR n +Number of frames per Ogg packet (1-10), default 1 +.TP +\fB\-\-comment\fR +Add the given string as an extra comment. This may be +used multiple times +.TP +\fB\-\-author\fR +Author of this track +.TP +\fB\-\-title\fR +Title for this track +.TP +\fB\-h\fR, \fB\-\-help\fR +This help +.TP +\fB\-v\fR, \fB\-\-version\fR +Version information +.TP +\fB\-V\fR +Verbose mode (show bit-rate) +.SS "Raw input options:" +.TP +\fB\-\-rate\fR n +Sampling rate for raw input +.TP +\fB\-\-stereo\fR +Consider raw input as stereo +.TP +\fB\-\-le\fR +Raw input is little-endian +.TP +\fB\-\-be\fR +Raw input is big-endian +.TP +\fB\-\-8bit\fR +Raw input is 8-bit unsigned +.TP +\fB\-\-16bit\fR +Raw input is 16-bit signed +.PP +Default raw PCM input is 16-bit, little-endian, mono +.PP +More information is available from the Speex site: http://www.speex.org +.PP +Please report bugs to the mailing list `speex-dev@xiph.org'. +.SH COPYRIGHT +Copyright \(co 2002 Jean-Marc Valin diff --git a/Code/BF2/External/speex-1.0.5/src/speexenc.c b/Code/BF2/External/speex-1.0.5/src/speexenc.c new file mode 100644 index 000000000..5cfa0027d --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/src/speexenc.c @@ -0,0 +1,835 @@ +/* Copyright (C) 2002-2003 Jean-Marc Valin + File: speexenc.c + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include +#if !defined WIN32 && !defined _WIN32 +#include +#include +#endif +#include +#include +#include + +#include +#include +#include "wav_io.h" +#include +#include +#include "misc.h" + +#if defined WIN32 || defined _WIN32 +#include "getopt_win.h" +/* We need the following two to set stdout to binary */ +#include +#include +#endif + + +void comment_init(char **comments, int* length, char *vendor_string); +void comment_add(char **comments, int* length, char *tag, char *val); + + +/*Write an Ogg page to a file pointer*/ +int oe_write_page(ogg_page *page, FILE *fp) +{ + int written; + written = fwrite(page->header,1,page->header_len, fp); + written += fwrite(page->body,1,page->body_len, fp); + + return written; +} + +#define MAX_FRAME_SIZE 2000 +#define MAX_FRAME_BYTES 2000 + +/* Convert input audio bits, endians and channels */ +static int read_samples(FILE *fin,int frame_size, int bits, int channels, int lsb, short * input, char *buff, int *size) +{ + unsigned char in[MAX_FRAME_BYTES*2]; + int i; + short *s; + int nb_read; + + if (size && *size<=0) + { + return 0; + } + /*Read input audio*/ + if (size) + *size -= bits/8*channels*frame_size; + if (buff) + { + for (i=0;i<12;i++) + in[i]=buff[i]; + nb_read = fread(in+12,1,bits/8*channels*frame_size-12, fin) + 12; + if (size) + *size += 12; + } else { + nb_read = fread(in,1,bits/8*channels* frame_size, fin); + } + nb_read /= bits/8*channels; + + /*fprintf (stderr, "%d\n", nb_read);*/ + if (nb_read==0) + return 0; + + s=(short*)in; + if(bits==8) + { + /* Convert 8->16 bits */ + for(i=frame_size*channels-1;i>=0;i--) + { + s[i]=(in[i]<<8)^0x8000; + } + } else + { + /* convert to our endian format */ + for(i=0;i10) + nframes=10; + } else if (strcmp(long_options[option_index].name,"comp")==0) + { + complexity = atoi (optarg); + } else if (strcmp(long_options[option_index].name,"help")==0) + { + usage(); + exit(0); + } else if (strcmp(long_options[option_index].name,"quiet")==0) + { + quiet = 1; + } else if (strcmp(long_options[option_index].name,"version")==0) + { + version(); + exit(0); + } else if (strcmp(long_options[option_index].name,"version-short")==0) + { + version_short(); + exit(0); + } else if (strcmp(long_options[option_index].name,"le")==0) + { + lsb=1; + } else if (strcmp(long_options[option_index].name,"be")==0) + { + lsb=0; + } else if (strcmp(long_options[option_index].name,"8bit")==0) + { + fmt=8; + } else if (strcmp(long_options[option_index].name,"16bit")==0) + { + fmt=16; + } else if (strcmp(long_options[option_index].name,"stereo")==0) + { + chan=2; + } else if (strcmp(long_options[option_index].name,"rate")==0) + { + rate=atoi (optarg); + } else if (strcmp(long_options[option_index].name,"comment")==0) + { + if (!strchr(optarg, '=')) + { + fprintf (stderr, "Invalid comment: %s\n", optarg); + fprintf (stderr, "Comments must be of the form name=value\n"); + exit(1); + } + comment_add(&comments, &comments_length, NULL, optarg); + } else if (strcmp(long_options[option_index].name,"author")==0) + { + comment_add(&comments, &comments_length, "author=", optarg); + } else if (strcmp(long_options[option_index].name,"title")==0) + { + comment_add(&comments, &comments_length, "title=", optarg); + } + + break; + case 'n': + modeID = SPEEX_MODEID_NB; + break; + case 'h': + usage(); + exit(0); + break; + case 'v': + version(); + exit(0); + break; + case 'V': + print_bitrate=1; + break; + case 'w': + modeID = SPEEX_MODEID_WB; + break; + case 'u': + modeID = SPEEX_MODEID_UWB; + break; + case '?': + usage(); + exit(1); + break; + } + } + if (argc-optind!=2) + { + usage(); + exit(1); + } + inFile=argv[optind]; + outFile=argv[optind+1]; + + /*Initialize Ogg stream struct*/ + srand(time(NULL)); + if (ogg_stream_init(&os, rand())==-1) + { + fprintf(stderr,"Error: stream init failed\n"); + exit(1); + } + + if (strcmp(inFile, "-")==0) + { +#if defined WIN32 || defined _WIN32 + _setmode(_fileno(stdin), _O_BINARY); +#endif + fin=stdin; + } + else + { + fin = fopen(inFile, "rb"); + if (!fin) + { + perror(inFile); + exit(1); + } + close_in=1; + } + + { + fread(first_bytes, 1, 12, fin); + if (strncmp(first_bytes,"RIFF",4)==0 && strncmp(first_bytes,"RIFF",4)==0) + { + if (read_wav_header(fin, &rate, &chan, &fmt, &size)==-1) + exit(1); + wave_input=1; + lsb=1; /* CHECK: exists big-endian .wav ?? */ + } + } + + if (modeID==-1 && !rate) + { + /* By default, use narrowband/8 kHz */ + modeID = SPEEX_MODEID_NB; + rate=8000; + } else if (modeID!=-1 && rate) + { + if (rate>48000) + { + fprintf (stderr, "Error: sampling rate too high: %d Hz, try down-sampling\n", rate); + exit(1); + } else if (rate>25000) + { + if (modeID != SPEEX_MODEID_UWB) + { + fprintf (stderr, "Warning: Trying to encode in %s at %d Hz. I'll do it but I suggest you try ultra-wideband instead\n", mode->modeName , rate); + } + } else if (rate>12500) + { + if (modeID != SPEEX_MODEID_WB) + { + fprintf (stderr, "Warning: Trying to encode in %s at %d Hz. I'll do it but I suggest you try wideband instead\n", mode->modeName , rate); + } + } else if (rate>=6000) + { + if (modeID != SPEEX_MODEID_NB) + { + fprintf (stderr, "Warning: Trying to encode in %s at %d Hz. I'll do it but I suggest you try narrowband instead\n", mode->modeName , rate); + } + } else { + fprintf (stderr, "Error: sampling rate too low: %d Hz\n", rate); + exit(1); + } + } else if (modeID==-1) + { + if (rate>48000) + { + fprintf (stderr, "Error: sampling rate too high: %d Hz, try down-sampling\n", rate); + exit(1); + } else if (rate>25000) + { + modeID = SPEEX_MODEID_UWB; + } else if (rate>12500) + { + modeID = SPEEX_MODEID_WB; + } else if (rate>=6000) + { + modeID = SPEEX_MODEID_NB; + } else { + fprintf (stderr, "Error: Sampling rate too low: %d Hz\n", rate); + exit(1); + } + } else if (!rate) + { + if (modeID == SPEEX_MODEID_NB) + rate=8000; + else if (modeID == SPEEX_MODEID_WB) + rate=16000; + else if (modeID == SPEEX_MODEID_UWB) + rate=32000; + } + + if (!quiet) + if (rate!=8000 && rate!=16000 && rate!=32000) + fprintf (stderr, "Warning: Speex is only optimized for 8, 16 and 32 kHz. It will still work at %d Hz but your mileage may vary\n", rate); + + mode = speex_lib_get_mode (modeID); + + speex_init_header(&header, rate, 1, mode); + header.frames_per_packet=nframes; + header.vbr=vbr_enabled; + header.nb_channels = chan; + + { + char *st_string="mono"; + if (chan==2) + st_string="stereo"; + if (!quiet) + fprintf (stderr, "Encoding %d Hz audio using %s mode (%s)\n", + header.rate, mode->modeName, st_string); + } + /*fprintf (stderr, "Encoding %d Hz audio at %d bps using %s mode\n", + header.rate, mode->bitrate, mode->modeName);*/ + + /*Initialize Speex encoder*/ + st = speex_encoder_init(mode); + + if (strcmp(outFile,"-")==0) + { +#if defined WIN32 || defined _WIN32 + _setmode(_fileno(stdout), _O_BINARY); +#endif + fout=stdout; + } + else + { + fout = fopen(outFile, "wb"); + if (!fout) + { + perror(outFile); + exit(1); + } + close_out=1; + } + + speex_encoder_ctl(st, SPEEX_GET_FRAME_SIZE, &frame_size); + speex_encoder_ctl(st, SPEEX_SET_COMPLEXITY, &complexity); + speex_encoder_ctl(st, SPEEX_SET_SAMPLING_RATE, &rate); + + if (quality >= 0) + { + if (vbr_enabled) + speex_encoder_ctl(st, SPEEX_SET_VBR_QUALITY, &vbr_quality); + else + speex_encoder_ctl(st, SPEEX_SET_QUALITY, &quality); + } + if (bitrate) + { + if (quality >= 0 && vbr_enabled) + fprintf (stderr, "Warning: --bitrate option is overriding --quality\n"); + speex_encoder_ctl(st, SPEEX_SET_BITRATE, &bitrate); + } + if (vbr_enabled) + { + tmp=1; + speex_encoder_ctl(st, SPEEX_SET_VBR, &tmp); + } else if (vad_enabled) + { + tmp=1; + speex_encoder_ctl(st, SPEEX_SET_VAD, &tmp); + } + if (dtx_enabled) + speex_encoder_ctl(st, SPEEX_SET_DTX, &tmp); + if (dtx_enabled && !(vbr_enabled || abr_enabled || vad_enabled)) + { + fprintf (stderr, "Warning: --dtx is useless without --vad, --vbr or --abr\n"); + } else if ((vbr_enabled || abr_enabled) && (vad_enabled)) + { + fprintf (stderr, "Warning: --vad is already implied by --vbr or --abr\n"); + } + + if (abr_enabled) + { + speex_encoder_ctl(st, SPEEX_SET_ABR, &abr_enabled); + } + + speex_encoder_ctl(st, SPEEX_GET_LOOKAHEAD, &lookahead); + + /*Write header*/ + { + + op.packet = (unsigned char *)speex_header_to_packet(&header, (int*)&(op.bytes)); + op.b_o_s = 1; + op.e_o_s = 0; + op.granulepos = 0; + op.packetno = 0; + ogg_stream_packetin(&os, &op); + free(op.packet); + + op.packet = (unsigned char *)comments; + op.bytes = comments_length; + op.b_o_s = 0; + op.e_o_s = 0; + op.granulepos = 0; + op.packetno = 1; + ogg_stream_packetin(&os, &op); + + while((result = ogg_stream_flush(&os, &og))) + { + if(!result) break; + ret = oe_write_page(&og, fout); + if(ret != og.header_len + og.body_len) + { + fprintf (stderr,"Error: failed writing header to output stream\n"); + exit(1); + } + else + bytes_written += ret; + } + } + + free(comments); + + speex_bits_init(&bits); + + if (!wave_input) + { + nb_samples = read_samples(fin,frame_size,fmt,chan,lsb,input, first_bytes, NULL); + } else { + nb_samples = read_samples(fin,frame_size,fmt,chan,lsb,input, NULL, &size); + } + if (nb_samples==0) + eos=1; + total_samples += nb_samples; + nb_encoded = -lookahead; + /*Main encoding loop (one frame per iteration)*/ + while (!eos || total_samples>nb_encoded) + { + id++; + /*Encode current frame*/ + if (chan==2) + speex_encode_stereo_int(input, frame_size, &bits); + + speex_encode_int(st, input, &bits); + + nb_encoded += frame_size; + if (print_bitrate) { + int tmp; + char ch=13; + speex_encoder_ctl(st, SPEEX_GET_BITRATE, &tmp); + fputc (ch, stderr); + cumul_bits += tmp; + enc_frames += 1; + if (!quiet) + { + if (vad_enabled || vbr_enabled || abr_enabled) + fprintf (stderr, "Bitrate is use: %d bps (average %d bps) ", tmp, (int)(cumul_bits/enc_frames)); + else + fprintf (stderr, "Bitrate is use: %d bps ", tmp); + } + + } + + if (wave_input) + { + nb_samples = read_samples(fin,frame_size,fmt,chan,lsb,input, NULL, &size); + } else { + nb_samples = read_samples(fin,frame_size,fmt,chan,lsb,input, NULL, NULL); + } + if (nb_samples==0) + { + eos=1; + } + if (eos && total_samples<=nb_encoded) + op.e_o_s = 1; + else + op.e_o_s = 0; + total_samples += nb_samples; + + if ((id+1)%nframes!=0) + continue; + speex_bits_insert_terminator(&bits); + nbBytes = speex_bits_write(&bits, cbits, MAX_FRAME_BYTES); + speex_bits_reset(&bits); + op.packet = (unsigned char *)cbits; + op.bytes = nbBytes; + op.b_o_s = 0; + /*Is this redundent?*/ + if (eos && total_samples<=nb_encoded) + op.e_o_s = 1; + else + op.e_o_s = 0; + op.granulepos = (id+1)*frame_size-lookahead; + if (op.granulepos>total_samples) + op.granulepos = total_samples; + /*printf ("granulepos: %d %d %d %d %d %d\n", (int)op.granulepos, id, nframes, lookahead, 5, 6);*/ + op.packetno = 2+id/nframes; + ogg_stream_packetin(&os, &op); + + /*Write all new pages (most likely 0 or 1)*/ + while (ogg_stream_pageout(&os,&og)) + { + ret = oe_write_page(&og, fout); + if(ret != og.header_len + og.body_len) + { + fprintf (stderr,"Error: failed writing header to output stream\n"); + exit(1); + } + else + bytes_written += ret; + } + } + if ((id+1)%nframes!=0) + { + while ((id+1)%nframes!=0) + { + id++; + speex_bits_pack(&bits, 15, 5); + } + nbBytes = speex_bits_write(&bits, cbits, MAX_FRAME_BYTES); + op.packet = (unsigned char *)cbits; + op.bytes = nbBytes; + op.b_o_s = 0; + op.e_o_s = 1; + op.granulepos = (id+1)*frame_size-lookahead; + if (op.granulepos>total_samples) + op.granulepos = total_samples; + + op.packetno = 2+id/nframes; + ogg_stream_packetin(&os, &op); + } + /*Flush all pages left to be written*/ + while (ogg_stream_flush(&os, &og)) + { + ret = oe_write_page(&og, fout); + if(ret != og.header_len + og.body_len) + { + fprintf (stderr,"Error: failed writing header to output stream\n"); + exit(1); + } + else + bytes_written += ret; + } + + speex_encoder_destroy(st); + speex_bits_destroy(&bits); + ogg_stream_clear(&os); + + if (close_in) + fclose(fin); + if (close_out) + fclose(fout); + return 0; +} + +/* + Comments will be stored in the Vorbis style. + It is describled in the "Structure" section of + http://www.xiph.org/ogg/vorbis/doc/v-comment.html + +The comment header is decoded as follows: + 1) [vendor_length] = read an unsigned integer of 32 bits + 2) [vendor_string] = read a UTF-8 vector as [vendor_length] octets + 3) [user_comment_list_length] = read an unsigned integer of 32 bits + 4) iterate [user_comment_list_length] times { + 5) [length] = read an unsigned integer of 32 bits + 6) this iteration's user comment = read a UTF-8 vector as [length] octets + } + 7) [framing_bit] = read a single bit as boolean + 8) if ( [framing_bit] unset or end of packet ) then ERROR + 9) done. + + If you have troubles, please write to ymnk@jcraft.com. + */ + +#define readint(buf, base) (((buf[base+3]<<24)&0xff000000)| \ + ((buf[base+2]<<16)&0xff0000)| \ + ((buf[base+1]<<8)&0xff00)| \ + (buf[base]&0xff)) +#define writeint(buf, base, val) do{ buf[base+3]=((val)>>24)&0xff; \ + buf[base+2]=((val)>>16)&0xff; \ + buf[base+1]=((val)>>8)&0xff; \ + buf[base]=(val)&0xff; \ + }while(0) + +void comment_init(char **comments, int* length, char *vendor_string) +{ + int vendor_length=strlen(vendor_string); + int user_comment_list_length=0; + int len=4+vendor_length+4; + char *p=(char*)malloc(len); + if(p==NULL){ + } + writeint(p, 0, vendor_length); + memcpy(p+4, vendor_string, vendor_length); + writeint(p, 4+vendor_length, user_comment_list_length); + *length=len; + *comments=p; +} +void comment_add(char **comments, int* length, char *tag, char *val) +{ + char* p=*comments; + int vendor_length=readint(p, 0); + int user_comment_list_length=readint(p, 4+vendor_length); + int tag_len=(tag?strlen(tag):0); + int val_len=strlen(val); + int len=(*length)+4+tag_len+val_len; + + p=(char*)realloc(p, len); + if(p==NULL){ + } + + writeint(p, *length, tag_len+val_len); /* length of comment */ + if(tag) memcpy(p+*length+4, tag, tag_len); /* comment */ + memcpy(p+*length+4+tag_len, val, val_len); /* comment */ + writeint(p, 4+vendor_length, user_comment_list_length+1); + + *comments=p; + *length=len; +} +#undef readint +#undef writeint diff --git a/Code/BF2/External/speex-1.0.5/src/wav_io.c b/Code/BF2/External/speex-1.0.5/src/wav_io.c new file mode 100644 index 000000000..f5fc2b932 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/src/wav_io.c @@ -0,0 +1,226 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: wav_io.c + Routines to handle wav (RIFF) headers + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include +#include +#include "misc.h" + +int read_wav_header(FILE *file, int *rate, int *channels, int *format, int *size) +{ + char ch[5]; + int itmp; + short stmp; + int bpersec; + short balign; + int skip_bytes; + int i; + + ch[4]=0; +#if 0 + fread(ch, 1, 4, file); + if (strcmp(ch, "RIFF")!=0) + { + fseek(file, 0, SEEK_SET); + return 0; + } + + fread(&itmp, 4, 1, file); + *size = le_int(itmp-36); + + fread(ch, 1, 4, file); + if (strcmp(ch, "WAVE")!=0) + { + fprintf (stderr, "RIFF file is not a WAVE file\n"); + return -1; + } +#endif + fread(ch, 1, 4, file); + while (strcmp(ch, "fmt ")!=0) + { + fread(&itmp, 4, 1, file); + itmp = le_int(itmp); + /*fprintf (stderr, "skip=%d\n", itmp);*/ + /*strange way of seeking, but it works even for pipes*/ + for (i=0;i2) + { + fprintf (stderr, "Only mono and (intensity) stereo supported\n"); + return -1; + } + + fread(&itmp, 4, 1, file); + itmp = le_int(itmp); + *rate = itmp; + if (*rate != 8000 && *rate != 16000 && *rate != 11025 && *rate != 22050 && *rate != 32000 && *rate != 44100 && *rate != 48000) + { + fprintf (stderr, "Only 8 kHz (narrowband) and 16 kHz (wideband) supported (plus 11.025 kHz and 22.05 kHz, but your mileage may vary)\n"); + return -1; + } + + fread(&itmp, 4, 1, file); + bpersec = le_int(itmp); + + fread(&stmp, 2, 1, file); + balign = le_short(stmp); + + fread(&stmp, 2, 1, file); + stmp = le_short(stmp); + if (stmp!=16 && stmp!=8) + { + fprintf (stderr, "Only 8/16-bit linear supported\n"); + return -1; + } + *format=stmp; + + if (bpersec!=*rate**channels*stmp/8) + { + fprintf (stderr, "Corrupted header: ByteRate mismatch\n"); + return -1; + } + + if (balign!=*channels*stmp/8) + { + fprintf (stderr, "Corrupted header: BlockAlign mismatch\n"); + return -1; + } + + + /*strange way of seeking, but it works even for pipes*/ + if (skip_bytes>0) + for (i=0;i + +int read_wav_header(FILE *file, int *rate, int *channels, int *format, int *size); + +void write_wav_header(FILE *file, int rate, int channels, int format, int size); + +#endif diff --git a/Code/BF2/External/speex-1.0.5/src/wave_out.c b/Code/BF2/External/speex-1.0.5/src/wave_out.c new file mode 100644 index 000000000..6eb9dcc92 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/src/wave_out.c @@ -0,0 +1,216 @@ +/* Copyright (c) 2002, John Edwards + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/* Set TABS = 4 */ +/******************************************************************** + + function: To provide playback of 16 bit PCM wave data in Win32 + environments from decoded compressed files. + + ********************************************************************/ + +#if defined WIN32 || defined _WIN32 + +#include +#include +#include "wave_out.h" + +#define MAXWAVESIZE 4294967040LU +#define MAX_WAVEBLOCKS 32 + +// This is modified for USE_WIN_AUDIO - ONLY 2002-02-27 + + +static CRITICAL_SECTION cs; +static HWAVEOUT dev = NULL; +static int ScheduledBlocks = 0; +static int PlayedWaveHeadersCount = 0; // free index +static WAVEHDR* PlayedWaveHeaders [MAX_WAVEBLOCKS]; + +static int +Box ( const char* msg ) +{ + MessageBox ( NULL, msg, " "VERSION_STRING": Error Message . . .", MB_OK | MB_ICONEXCLAMATION ); + return -1; +} + + +/* + * This function registers already played WAVE chunks. Freeing is done by free_memory(), + */ + +static void CALLBACK +wave_callback ( HWAVE hWave, UINT uMsg, DWORD dwInstance, DWORD dwParam1, DWORD dwParam2 ) +{ + if ( uMsg == WOM_DONE ) { + EnterCriticalSection ( &cs ); + PlayedWaveHeaders [PlayedWaveHeadersCount++] = (WAVEHDR*) dwParam1; + LeaveCriticalSection ( &cs ); + } +} + + +static void +free_memory ( void ) +{ + WAVEHDR* wh; + HGLOBAL hg; + + EnterCriticalSection ( &cs ); + wh = PlayedWaveHeaders [--PlayedWaveHeadersCount]; + ScheduledBlocks--; // decrease the number of USED blocks + LeaveCriticalSection ( &cs ); + + waveOutUnprepareHeader ( dev, wh, sizeof (WAVEHDR) ); + + hg = GlobalHandle ( wh -> lpData ); // Deallocate the buffer memory + GlobalUnlock (hg); + GlobalFree (hg); + + hg = GlobalHandle ( wh ); // Deallocate the header memory + GlobalUnlock (hg); + GlobalFree (hg); +} + + +Int +Set_WIN_Params ( FILE_T dummyFile , + Ldouble SampleFreq, + Uint BitsPerSample, + Uint Channels ) +{ + WAVEFORMATEX outFormat; + UINT deviceID = WAVE_MAPPER; + + (void) dummyFile; + + if ( waveOutGetNumDevs () == 0 ) + return Box ( "No audio device present." ); + + outFormat.wFormatTag = WAVE_FORMAT_PCM; + outFormat.wBitsPerSample = BitsPerSample; + outFormat.nChannels = Channels; + outFormat.nSamplesPerSec = (unsigned long)(SampleFreq + 0.5); + outFormat.nBlockAlign = (outFormat.wBitsPerSample + 7) / 8 * outFormat.nChannels; + outFormat.nAvgBytesPerSec = outFormat.nSamplesPerSec * outFormat.nBlockAlign; + + switch ( waveOutOpen ( &dev, deviceID, &outFormat, (DWORD)wave_callback, 0, CALLBACK_FUNCTION ) ) + { + case MMSYSERR_ALLOCATED: return Box ( "Device is already open." ); + case MMSYSERR_BADDEVICEID: return Box ( "The specified device is out of range." ); + case MMSYSERR_NODRIVER: return Box ( "There is no audio driver in this system." ); + case MMSYSERR_NOMEM: return Box ( "Unable to allocate sound memory." ); + case WAVERR_BADFORMAT: return Box ( "This audio format is not supported." ); + case WAVERR_SYNC: return Box ( "The device is synchronous." ); + default: return Box ( "Unknown media error." ); + case MMSYSERR_NOERROR: break; + } + + waveOutReset ( dev ); + InitializeCriticalSection ( &cs ); + SetPriorityClass ( GetCurrentProcess (), HIGH_PRIORITY_CLASS ); + return 0; +} + + +int +WIN_Play_Samples ( const void* data, size_t len ) +{ + HGLOBAL hg; + HGLOBAL hg2; + LPWAVEHDR wh; + void* allocptr; + + do { + while ( PlayedWaveHeadersCount > 0 ) // free used blocks ... + free_memory (); + + if ( ScheduledBlocks < sizeof(PlayedWaveHeaders)/sizeof(*PlayedWaveHeaders) ) // wait for a free block ... + break; + Sleep (26); + } while (1); + + if ( (hg2 = GlobalAlloc ( GMEM_MOVEABLE, len )) == NULL ) // allocate some memory for a copy of the buffer + return Box ( "GlobalAlloc failed." ); + + allocptr = GlobalLock (hg2); + CopyMemory ( allocptr, data, len ); // Here we can call any modification output functions we want.... + + if ( (hg = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, sizeof (WAVEHDR))) == NULL ) // now make a header and WRITE IT! + return -1; + + wh = GlobalLock (hg); + wh -> dwBufferLength = len; + wh -> lpData = allocptr; + + if ( waveOutPrepareHeader ( dev, wh, sizeof (WAVEHDR)) != MMSYSERR_NOERROR ) { + GlobalUnlock (hg); + GlobalFree (hg); + return -1; + } + + if ( waveOutWrite ( dev, wh, sizeof (WAVEHDR)) != MMSYSERR_NOERROR ) { + GlobalUnlock (hg); + GlobalFree (hg); + return -1; + } + + EnterCriticalSection ( &cs ); + ScheduledBlocks++; + LeaveCriticalSection ( &cs ); + + return len; +} + + +int +WIN_Audio_close ( void ) +{ + if ( dev != NULL ) { + + while ( ScheduledBlocks > 0 ) { + Sleep (ScheduledBlocks); + while ( PlayedWaveHeadersCount > 0 ) // free used blocks ... + free_memory (); + } + + waveOutReset (dev); // reset the device + waveOutClose (dev); // close the device + dev = NULL; + } + + DeleteCriticalSection ( &cs ); + ScheduledBlocks = 0; + return 0; +} + +#endif + +/* end of wave_out.c */ diff --git a/Code/BF2/External/speex-1.0.5/src/wave_out.h b/Code/BF2/External/speex-1.0.5/src/wave_out.h new file mode 100644 index 000000000..bc97ff6bb --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/src/wave_out.h @@ -0,0 +1,65 @@ +/* Copyright (c) 2002, John Edwards + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +// WAVE_OUT.H - Necessary stuff for WIN_AUDIO + + +#include +#include + +#define VERSION_STRING "\n 0.7.0\n" + +#define Cdecl __cdecl +#define __attribute__(x) +#define sleep(__sec) Sleep ((__sec) * 1000) +#define inline __inline +#define restrict + +//// constants ///////////////////////////////////////////////////// + +#define CD_SAMPLE_FREQ 44.1e3 +#define SAMPLE_SIZE 16 +#define SAMPLE_SIZE_STRING "" +#define WINAUDIO_FD ((FILE_T)-128) +#define FILE_T FILE* +#define INVALID_FILEDESC NULL + +//// Simple types ////////////////////////////////////////////////// + +typedef signed int Int; // at least -32767...+32767, fast type +typedef unsigned int Uint; // at least 0...65535, fast type +typedef long double Ldouble; // most exact floating point format + +//// procedures/functions ////////////////////////////////////////// +// wave_out.c +Int Set_WIN_Params ( FILE_T dummyFile , Ldouble SampleFreq, Uint BitsPerSample, Uint Channels); +int WIN_Play_Samples ( const void* buff, size_t len ); +int WIN_Audio_close ( void ); + diff --git a/Code/BF2/External/speex-1.0.5/win32/Makefile.am b/Code/BF2/External/speex-1.0.5/win32/Makefile.am new file mode 100644 index 000000000..a7ee4c7b3 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/win32/Makefile.am @@ -0,0 +1,9 @@ +## Process this file with automake to produce Makefile.in. -*-Makefile-*- + +# Disable automatic dependency tracking if using other tools than gcc and gmake +#AUTOMAKE_OPTIONS = no-dependencies + +EXTRA_DIST = speex.iss + +SUBDIRS = libspeex speexenc speexdec + diff --git a/Code/BF2/External/speex-1.0.5/win32/Makefile.in b/Code/BF2/External/speex-1.0.5/win32/Makefile.in new file mode 100644 index 000000000..621cbbdf8 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/win32/Makefile.in @@ -0,0 +1,464 @@ +# Makefile.in generated by automake 1.8.5 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004 Free Software Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# Disable automatic dependency tracking if using other tools than gcc and gmake +#AUTOMAKE_OPTIONS = no-dependencies +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +top_builddir = .. +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +INSTALL = @INSTALL@ +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +host_triplet = @host@ +subdir = win32 +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ + $(top_srcdir)/configure.in +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs +CONFIG_CLEAN_FILES = +SOURCES = +DIST_SOURCES = +RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \ + html-recursive info-recursive install-data-recursive \ + install-exec-recursive install-info-recursive \ + install-recursive installcheck-recursive installdirs-recursive \ + pdf-recursive ps-recursive uninstall-info-recursive \ + uninstall-recursive +ETAGS = etags +CTAGS = ctags +DIST_SUBDIRS = $(SUBDIRS) +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMDEP_FALSE = @AMDEP_FALSE@ +AMDEP_TRUE = @AMDEP_TRUE@ +AMTAR = @AMTAR@ +AR = @AR@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +ECHO = @ECHO@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +F77 = @F77@ +FFLAGS = @FFLAGS@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +LDFLAGS = @LDFLAGS@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +MAINT = @MAINT@ +MAINTAINER_MODE_FALSE = @MAINTAINER_MODE_FALSE@ +MAINTAINER_MODE_TRUE = @MAINTAINER_MODE_TRUE@ +MAKEINFO = @MAKEINFO@ +OBJEXT = @OBJEXT@ +OGG_INCLUDES = @OGG_INCLUDES@ +OGG_LDFLAGS = @OGG_LDFLAGS@ +OGG_LIBS = @OGG_LIBS@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +RANLIB = @RANLIB@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SPEEX_LT_AGE = @SPEEX_LT_AGE@ +SPEEX_LT_CURRENT = @SPEEX_LT_CURRENT@ +SPEEX_LT_REVISION = @SPEEX_LT_REVISION@ +SPEEX_VERSION = @SPEEX_VERSION@ +STRIP = @STRIP@ +VERSION = @VERSION@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_CXX = @ac_ct_CXX@ +ac_ct_F77 = @ac_ct_F77@ +ac_ct_RANLIB = @ac_ct_RANLIB@ +ac_ct_STRIP = @ac_ct_STRIP@ +am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ +am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ +am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ +am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +datadir = @datadir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +src = @src@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +EXTRA_DIST = speex.iss +SUBDIRS = libspeex speexenc speexdec +all: all-recursive + +.SUFFIXES: +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ + && exit 0; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu win32/Makefile'; \ + cd $(top_srcdir) && \ + $(AUTOMAKE) --gnu win32/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +distclean-libtool: + -rm -f libtool +uninstall-info-am: + +# This directory's subdirectories are mostly independent; you can cd +# into them and run `make' without going through this Makefile. +# To change the values of `make' variables: instead of editing Makefiles, +# (1) if the variable is set in `config.status', edit `config.status' +# (which will cause the Makefiles to be regenerated when you run `make'); +# (2) otherwise, pass the desired values on the `make' command line. +$(RECURSIVE_TARGETS): + @set fnord $$MAKEFLAGS; amf=$$2; \ + dot_seen=no; \ + target=`echo $@ | sed s/-recursive//`; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + dot_seen=yes; \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || case "$$amf" in *=*) exit 1;; *k*) fail=yes;; *) exit 1;; esac; \ + done; \ + if test "$$dot_seen" = "no"; then \ + $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ + fi; test -z "$$fail" + +mostlyclean-recursive clean-recursive distclean-recursive \ +maintainer-clean-recursive: + @set fnord $$MAKEFLAGS; amf=$$2; \ + dot_seen=no; \ + case "$@" in \ + distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ + *) list='$(SUBDIRS)' ;; \ + esac; \ + rev=''; for subdir in $$list; do \ + if test "$$subdir" = "."; then :; else \ + rev="$$subdir $$rev"; \ + fi; \ + done; \ + rev="$$rev ."; \ + target=`echo $@ | sed s/-recursive//`; \ + for subdir in $$rev; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || case "$$amf" in *=*) exit 1;; *k*) fail=yes;; *) exit 1;; esac; \ + done && test -z "$$fail" +tags-recursive: + list='$(SUBDIRS)'; for subdir in $$list; do \ + test "$$subdir" = . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \ + done +ctags-recursive: + list='$(SUBDIRS)'; for subdir in $$list; do \ + test "$$subdir" = . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \ + done + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + tags=; \ + here=`pwd`; \ + if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ + include_option=--etags-include; \ + empty_fix=.; \ + else \ + include_option=--include; \ + empty_fix=; \ + fi; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test ! -f $$subdir/TAGS || \ + tags="$$tags $$include_option=$$here/$$subdir/TAGS"; \ + fi; \ + done; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$tags $$unique; \ + fi +ctags: CTAGS +CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + tags=; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + test -z "$(CTAGS_ARGS)$$tags$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$tags $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && cd $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) $$here + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ + list='$(DISTFILES)'; for file in $$list; do \ + case $$file in \ + $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ + $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ + esac; \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test "$$dir" != "$$file" && test "$$dir" != "."; then \ + dir="/$$dir"; \ + $(mkdir_p) "$(distdir)$$dir"; \ + else \ + dir=''; \ + fi; \ + if test -d $$d/$$file; then \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + fi; \ + cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + else \ + test -f $(distdir)/$$file \ + || cp -p $$d/$$file $(distdir)/$$file \ + || exit 1; \ + fi; \ + done + list='$(SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test -d "$(distdir)/$$subdir" \ + || mkdir "$(distdir)/$$subdir" \ + || exit 1; \ + (cd $$subdir && \ + $(MAKE) $(AM_MAKEFLAGS) \ + top_distdir="../$(top_distdir)" \ + distdir="../$(distdir)/$$subdir" \ + distdir) \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-recursive +all-am: Makefile +installdirs: installdirs-recursive +installdirs-am: +install: install-recursive +install-exec: install-exec-recursive +install-data: install-data-recursive +uninstall: uninstall-recursive + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-recursive +install-strip: + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + `test -z '$(STRIP)' || \ + echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -rm -f $(CONFIG_CLEAN_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-recursive + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-recursive + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-libtool \ + distclean-tags + +dvi: dvi-recursive + +dvi-am: + +html: html-recursive + +info: info-recursive + +info-am: + +install-data-am: + +install-exec-am: + +install-info: install-info-recursive + +install-man: + +installcheck-am: + +maintainer-clean: maintainer-clean-recursive + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-recursive + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-recursive + +pdf-am: + +ps: ps-recursive + +ps-am: + +uninstall-am: uninstall-info-am + +uninstall-info: uninstall-info-recursive + +.PHONY: $(RECURSIVE_TARGETS) CTAGS GTAGS all all-am check check-am \ + clean clean-generic clean-libtool clean-recursive ctags \ + ctags-recursive distclean distclean-generic distclean-libtool \ + distclean-recursive distclean-tags distdir dvi dvi-am html \ + html-am info info-am install install-am install-data \ + install-data-am install-exec install-exec-am install-info \ + install-info-am install-man install-strip installcheck \ + installcheck-am installdirs installdirs-am maintainer-clean \ + maintainer-clean-generic maintainer-clean-recursive \ + mostlyclean mostlyclean-generic mostlyclean-libtool \ + mostlyclean-recursive pdf pdf-am ps ps-am tags tags-recursive \ + uninstall uninstall-am uninstall-info-am + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/Code/BF2/External/speex-1.0.5/win32/libspeex/Makefile.am b/Code/BF2/External/speex-1.0.5/win32/libspeex/Makefile.am new file mode 100644 index 000000000..9430c78ce --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/win32/libspeex/Makefile.am @@ -0,0 +1,6 @@ +## Process this file with automake to produce Makefile.in. -*-Makefile-*- + +# Disable automatic dependency tracking if using other tools than gcc and gmake +#AUTOMAKE_OPTIONS = no-dependencies + +EXTRA_DIST = libspeex.dsp libspeex.dsw libspeex_dynamic.dsp speex.def diff --git a/Code/BF2/External/speex-1.0.5/win32/libspeex/Makefile.in b/Code/BF2/External/speex-1.0.5/win32/libspeex/Makefile.in new file mode 100644 index 000000000..42cfb3c85 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/win32/libspeex/Makefile.in @@ -0,0 +1,320 @@ +# Makefile.in generated by automake 1.8.5 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004 Free Software Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# Disable automatic dependency tracking if using other tools than gcc and gmake +#AUTOMAKE_OPTIONS = no-dependencies +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +top_builddir = ../.. +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +INSTALL = @INSTALL@ +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +host_triplet = @host@ +subdir = win32/libspeex +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ + $(top_srcdir)/configure.in +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs +CONFIG_CLEAN_FILES = +SOURCES = +DIST_SOURCES = +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMDEP_FALSE = @AMDEP_FALSE@ +AMDEP_TRUE = @AMDEP_TRUE@ +AMTAR = @AMTAR@ +AR = @AR@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +ECHO = @ECHO@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +F77 = @F77@ +FFLAGS = @FFLAGS@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +LDFLAGS = @LDFLAGS@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +MAINT = @MAINT@ +MAINTAINER_MODE_FALSE = @MAINTAINER_MODE_FALSE@ +MAINTAINER_MODE_TRUE = @MAINTAINER_MODE_TRUE@ +MAKEINFO = @MAKEINFO@ +OBJEXT = @OBJEXT@ +OGG_INCLUDES = @OGG_INCLUDES@ +OGG_LDFLAGS = @OGG_LDFLAGS@ +OGG_LIBS = @OGG_LIBS@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +RANLIB = @RANLIB@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SPEEX_LT_AGE = @SPEEX_LT_AGE@ +SPEEX_LT_CURRENT = @SPEEX_LT_CURRENT@ +SPEEX_LT_REVISION = @SPEEX_LT_REVISION@ +SPEEX_VERSION = @SPEEX_VERSION@ +STRIP = @STRIP@ +VERSION = @VERSION@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_CXX = @ac_ct_CXX@ +ac_ct_F77 = @ac_ct_F77@ +ac_ct_RANLIB = @ac_ct_RANLIB@ +ac_ct_STRIP = @ac_ct_STRIP@ +am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ +am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ +am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ +am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +datadir = @datadir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +src = @src@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +EXTRA_DIST = libspeex.dsp libspeex.dsw libspeex_dynamic.dsp speex.def +all: all-am + +.SUFFIXES: +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ + && exit 0; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu win32/libspeex/Makefile'; \ + cd $(top_srcdir) && \ + $(AUTOMAKE) --gnu win32/libspeex/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +distclean-libtool: + -rm -f libtool +uninstall-info-am: +tags: TAGS +TAGS: + +ctags: CTAGS +CTAGS: + + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ + list='$(DISTFILES)'; for file in $$list; do \ + case $$file in \ + $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ + $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ + esac; \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test "$$dir" != "$$file" && test "$$dir" != "."; then \ + dir="/$$dir"; \ + $(mkdir_p) "$(distdir)$$dir"; \ + else \ + dir=''; \ + fi; \ + if test -d $$d/$$file; then \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + fi; \ + cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + else \ + test -f $(distdir)/$$file \ + || cp -p $$d/$$file $(distdir)/$$file \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile +installdirs: +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + `test -z '$(STRIP)' || \ + echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -rm -f $(CONFIG_CLEAN_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-am + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-libtool + +dvi: dvi-am + +dvi-am: + +html: html-am + +info: info-am + +info-am: + +install-data-am: + +install-exec-am: + +install-info: install-info-am + +install-man: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-info-am + +.PHONY: all all-am check check-am clean clean-generic clean-libtool \ + distclean distclean-generic distclean-libtool distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-exec install-exec-am \ + install-info install-info-am install-man install-strip \ + installcheck installcheck-am installdirs maintainer-clean \ + maintainer-clean-generic mostlyclean mostlyclean-generic \ + mostlyclean-libtool pdf pdf-am ps ps-am uninstall uninstall-am \ + uninstall-info-am + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/Code/BF2/External/speex-1.0.5/win32/libspeex/libspeex.dsp b/Code/BF2/External/speex-1.0.5/win32/libspeex/libspeex.dsp new file mode 100644 index 000000000..526df1ca6 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/win32/libspeex/libspeex.dsp @@ -0,0 +1,286 @@ +# Microsoft Developer Studio Project File - Name="libspeex" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Static Library" 0x0104 + +CFG=libspeex - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "libspeex.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "libspeex.mak" CFG="libspeex - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "libspeex - Win32 Release" (based on "Win32 (x86) Static Library") +!MESSAGE "libspeex - Win32 Debug" (based on "Win32 (x86) Static Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "libspeex - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +F90=df.exe +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /FD /c +# ADD CPP /nologo /GX /Ox /Ot /Og /Oi /Ob2 /I "../../include" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /FD /c +# ADD BASE RSC /l 0x809 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo + +!ELSEIF "$(CFG)" == "libspeex - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Target_Dir "" +F90=df.exe +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /FD /GZ /c +# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /I "../../include" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /FD /GZ /c +# ADD BASE RSC /l 0x809 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo + +!ENDIF + +# Begin Target + +# Name "libspeex - Win32 Release" +# Name "libspeex - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=..\..\libspeex\bits.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\cb_search.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\exc_10_16_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\exc_10_32_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\exc_20_32_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\exc_5_256_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\exc_5_64_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\exc_8_128_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\filters.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\gain_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\gain_table_lbr.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\hexc_10_32_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\hexc_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\high_lsp_tables.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\lpc.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\lsp.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\lsp_tables_nb.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\ltp.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\math_approx.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\misc.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\modes.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\nb_celp.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\quant_lsp.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\sb_celp.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\speex_callbacks.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\speex_header.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\stereo.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\vbr.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\vq.c +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=..\..\libspeex\cb_search.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\filters.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\lpc.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\lsp.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\ltp.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\math_approx.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\misc.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\modes.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\nb_celp.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\quant_lsp.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\sb_celp.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\speex.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\speex_bits.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\speex_callbacks.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\speex_header.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\speex_stereo.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\stack_alloc.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\vbr.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\vq.h +# End Source File +# End Group +# End Target +# End Project diff --git a/Code/BF2/External/speex-1.0.5/win32/libspeex/libspeex.dsw b/Code/BF2/External/speex-1.0.5/win32/libspeex/libspeex.dsw new file mode 100644 index 000000000..9fb56fefe --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/win32/libspeex/libspeex.dsw @@ -0,0 +1,41 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "libspeex"=.\libspeex.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "libspeex_dynamic"=.\libspeex_dynamic.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git a/Code/BF2/External/speex-1.0.5/win32/libspeex/libspeex_dynamic.dsp b/Code/BF2/External/speex-1.0.5/win32/libspeex/libspeex_dynamic.dsp new file mode 100644 index 000000000..60e46d3db --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/win32/libspeex/libspeex_dynamic.dsp @@ -0,0 +1,295 @@ +# Microsoft Developer Studio Project File - Name="libspeex_dynamic" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102 + +CFG=libspeex_dynamic - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "libspeex_dynamic.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "libspeex_dynamic.mak" CFG="libspeex_dynamic - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "libspeex_dynamic - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library") +!MESSAGE "libspeex_dynamic - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +MTL=midl.exe +RSC=rc.exe + +!IF "$(CFG)" == "libspeex_dynamic - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "libspeex_dynamic___Win32_Release" +# PROP BASE Intermediate_Dir "libspeex_dynamic___Win32_Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Dynamic_Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "LIBSPEEX_DYNAMIC_EXPORTS" /YX /FD /c +# ADD CPP /nologo /MT /W3 /GX /O2 /I "../../include" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "LIBSPEEX_DYNAMIC_EXPORTS" /YX /FD /c +# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 /out:"Release/libspeex.dll" + +!ELSEIF "$(CFG)" == "libspeex_dynamic - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "libspeex_dynamic___Win32_Debug" +# PROP BASE Intermediate_Dir "libspeex_dynamic___Win32_Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Dynamic_Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "LIBSPEEX_DYNAMIC_EXPORTS" /YX /FD /GZ /c +# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "../../include" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "LIBSPEEX_DYNAMIC_EXPORTS" /YX /FD /GZ /c +# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /out:"Debug/libspeex.dll" /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "libspeex_dynamic - Win32 Release" +# Name "libspeex_dynamic - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=..\..\libspeex\bits.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\cb_search.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\cb_search.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\exc_10_16_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\exc_10_32_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\exc_20_32_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\exc_5_256_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\exc_5_64_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\exc_8_128_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\filters.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\filters.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\gain_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\gain_table_lbr.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\hexc_10_32_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\hexc_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\high_lsp_tables.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\lpc.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\lpc.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\lsp.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\lsp.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\lsp_tables_nb.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\ltp.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\ltp.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\math_approx.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\math_approx.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\misc.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\misc.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\modes.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\modes.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\nb_celp.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\nb_celp.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\quant_lsp.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\quant_lsp.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\sb_celp.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\sb_celp.h +# End Source File +# Begin Source File + +SOURCE=.\speex.def +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\speex.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\speex_bits.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\speex_callbacks.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\speex_callbacks.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\speex_header.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\speex_header.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\speex_stereo.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\stack_alloc.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\stereo.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\vbr.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\vbr.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\vq.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\vq.h +# End Source File +# End Group +# End Target +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# End Group +# End Project diff --git a/Code/BF2/External/speex-1.0.5/win32/libspeex/speex.def b/Code/BF2/External/speex-1.0.5/win32/libspeex/speex.def new file mode 100644 index 000000000..cb89364f5 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/win32/libspeex/speex.def @@ -0,0 +1,49 @@ +; +; speex.def +; +LIBRARY +EXPORTS +; +speex_encoder_init +speex_encoder_destroy +speex_encode +speex_encoder_ctl +speex_decoder_init +speex_decoder_destroy +speex_decode +speex_decoder_ctl +speex_mode_query +speex_lib_ctl +speex_bits_init +speex_bits_init_buffer +speex_bits_destroy +speex_bits_reset +speex_bits_rewind +speex_bits_read_from +speex_bits_read_whole_bytes +speex_bits_write +speex_bits_write_whole_bytes +speex_bits_pack +speex_bits_unpack_signed +speex_bits_unpack_unsigned +speex_bits_nbytes +speex_bits_peek_unsigned +speex_bits_peek +speex_bits_advance +speex_bits_remaining +speex_bits_insert_terminator +speex_inband_handler +speex_std_mode_request_handler +speex_std_high_mode_request_handler +speex_std_char_handler +speex_default_user_handler +speex_std_low_mode_request_handler +speex_std_vbr_request_handler +speex_std_enh_request_handler +speex_std_vbr_quality_request_handler +speex_init_header +speex_header_to_packet +speex_packet_to_header +speex_encode_stereo +speex_decode_stereo +speex_std_stereo_request_handler diff --git a/Code/BF2/External/speex-1.0.5/win32/speex.iss b/Code/BF2/External/speex-1.0.5/win32/speex.iss new file mode 100644 index 000000000..ca9013eac --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/win32/speex.iss @@ -0,0 +1,50 @@ +; Script generated by the Inno Setup Script Wizard. +; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES! + +[Setup] +AppName=Speex +AppVerName=Speex V1.0.4 +AppPublisherURL=http://www.speex.org +AppSupportURL=http://www.speex.org +AppUpdatesURL=http://www.speex.org +DefaultDirName={pf}\Speex +DefaultGroupName=Speex +AllowNoIcons=yes +LicenseFile=..\COPYING +InfoAfterFile=..\README +OutputDir=. +OutputBaseFilename=speex_win32_1.0.4_setup +;WizardImageFile=speexlogo.bmp +; uncomment the following line if you want your installation to run on NT 3.51 too. +; MinVersion=4,3.51 + +[Tasks] +;Name: "desktopicon"; Description: "Create a &desktop icon"; GroupDescription: "Additional icons:"; MinVersion: 4,4 + +[Dirs] +Name: "{app}" +Name: "{app}\doc" +Name: "{app}\libspeex" +Name: "{app}\libspeex\include" +Name: "{app}\libspeex\include\speex" + +[Files] +Source: "speexdec\Release\speexdec.exe"; DestDir: "{app}"; Flags: ignoreversion +Source: "speexenc\Release\speexenc.exe"; DestDir: "{app}"; Flags: ignoreversion +Source: "..\doc\manual.pdf"; DestDir: "{app}\doc"; Flags: ignoreversion +Source: "libspeex\Release\libspeex.lib"; DestDir: "{app}\libspeex"; Flags: ignoreversion +Source: "libspeex\Release\libspeex.dll"; DestDir: "{app}\libspeex"; Flags: ignoreversion +Source: "libspeex\Release\libspeex.exp"; DestDir: "{app}\libspeex"; Flags: ignoreversion +Source: "..\include\speex.h"; DestDir: "{app}\libspeex\include"; Flags: ignoreversion +Source: "..\include\speex_bits.h"; DestDir: "{app}\libspeex\include"; Flags: ignoreversion +Source: "..\include\speex_callbacks.h"; DestDir: "{app}\libspeex\include"; Flags: ignoreversion +Source: "..\include\speex_header.h"; DestDir: "{app}\libspeex\include"; Flags: ignoreversion +Source: "..\include\speex_stereo.h"; DestDir: "{app}\libspeex\include"; Flags: ignoreversion +Source: "..\include\speex\speex.h"; DestDir: "{app}\libspeex\include\speex\"; Flags: ignoreversion +Source: "..\include\speex\speex_bits.h"; DestDir: "{app}\libspeex\include\speex\"; Flags: ignoreversion +Source: "..\include\speex\speex_callbacks.h"; DestDir: "{app}\libspeex\include\speex\"; Flags: ignoreversion +Source: "..\include\speex\speex_header.h"; DestDir: "{app}\libspeex\include\speex\"; Flags: ignoreversion +Source: "..\include\speex\speex_stereo.h"; DestDir: "{app}\libspeex\include\speex\"; Flags: ignoreversion + +[Run] + diff --git a/Code/BF2/External/speex-1.0.5/win32/speexdec/Makefile.am b/Code/BF2/External/speex-1.0.5/win32/speexdec/Makefile.am new file mode 100644 index 000000000..7c4792201 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/win32/speexdec/Makefile.am @@ -0,0 +1,6 @@ +## Process this file with automake to produce Makefile.in. -*-Makefile-*- + +# Disable automatic dependency tracking if using other tools than gcc and gmake +#AUTOMAKE_OPTIONS = no-dependencies + +EXTRA_DIST = speexdec.dsp speexdec.dsw diff --git a/Code/BF2/External/speex-1.0.5/win32/speexdec/Makefile.in b/Code/BF2/External/speex-1.0.5/win32/speexdec/Makefile.in new file mode 100644 index 000000000..b409e2f93 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/win32/speexdec/Makefile.in @@ -0,0 +1,320 @@ +# Makefile.in generated by automake 1.8.5 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004 Free Software Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# Disable automatic dependency tracking if using other tools than gcc and gmake +#AUTOMAKE_OPTIONS = no-dependencies +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +top_builddir = ../.. +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +INSTALL = @INSTALL@ +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +host_triplet = @host@ +subdir = win32/speexdec +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ + $(top_srcdir)/configure.in +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs +CONFIG_CLEAN_FILES = +SOURCES = +DIST_SOURCES = +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMDEP_FALSE = @AMDEP_FALSE@ +AMDEP_TRUE = @AMDEP_TRUE@ +AMTAR = @AMTAR@ +AR = @AR@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +ECHO = @ECHO@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +F77 = @F77@ +FFLAGS = @FFLAGS@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +LDFLAGS = @LDFLAGS@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +MAINT = @MAINT@ +MAINTAINER_MODE_FALSE = @MAINTAINER_MODE_FALSE@ +MAINTAINER_MODE_TRUE = @MAINTAINER_MODE_TRUE@ +MAKEINFO = @MAKEINFO@ +OBJEXT = @OBJEXT@ +OGG_INCLUDES = @OGG_INCLUDES@ +OGG_LDFLAGS = @OGG_LDFLAGS@ +OGG_LIBS = @OGG_LIBS@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +RANLIB = @RANLIB@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SPEEX_LT_AGE = @SPEEX_LT_AGE@ +SPEEX_LT_CURRENT = @SPEEX_LT_CURRENT@ +SPEEX_LT_REVISION = @SPEEX_LT_REVISION@ +SPEEX_VERSION = @SPEEX_VERSION@ +STRIP = @STRIP@ +VERSION = @VERSION@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_CXX = @ac_ct_CXX@ +ac_ct_F77 = @ac_ct_F77@ +ac_ct_RANLIB = @ac_ct_RANLIB@ +ac_ct_STRIP = @ac_ct_STRIP@ +am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ +am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ +am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ +am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +datadir = @datadir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +src = @src@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +EXTRA_DIST = speexdec.dsp speexdec.dsw +all: all-am + +.SUFFIXES: +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ + && exit 0; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu win32/speexdec/Makefile'; \ + cd $(top_srcdir) && \ + $(AUTOMAKE) --gnu win32/speexdec/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +distclean-libtool: + -rm -f libtool +uninstall-info-am: +tags: TAGS +TAGS: + +ctags: CTAGS +CTAGS: + + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ + list='$(DISTFILES)'; for file in $$list; do \ + case $$file in \ + $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ + $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ + esac; \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test "$$dir" != "$$file" && test "$$dir" != "."; then \ + dir="/$$dir"; \ + $(mkdir_p) "$(distdir)$$dir"; \ + else \ + dir=''; \ + fi; \ + if test -d $$d/$$file; then \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + fi; \ + cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + else \ + test -f $(distdir)/$$file \ + || cp -p $$d/$$file $(distdir)/$$file \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile +installdirs: +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + `test -z '$(STRIP)' || \ + echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -rm -f $(CONFIG_CLEAN_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-am + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-libtool + +dvi: dvi-am + +dvi-am: + +html: html-am + +info: info-am + +info-am: + +install-data-am: + +install-exec-am: + +install-info: install-info-am + +install-man: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-info-am + +.PHONY: all all-am check check-am clean clean-generic clean-libtool \ + distclean distclean-generic distclean-libtool distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-exec install-exec-am \ + install-info install-info-am install-man install-strip \ + installcheck installcheck-am installdirs maintainer-clean \ + maintainer-clean-generic mostlyclean mostlyclean-generic \ + mostlyclean-libtool pdf pdf-am ps ps-am uninstall uninstall-am \ + uninstall-info-am + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/Code/BF2/External/speex-1.0.5/win32/speexdec/speexdec.dsp b/Code/BF2/External/speex-1.0.5/win32/speexdec/speexdec.dsp new file mode 100644 index 000000000..c1d9e73e1 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/win32/speexdec/speexdec.dsp @@ -0,0 +1,130 @@ +# Microsoft Developer Studio Project File - Name="speexdec" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=speexdec - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "speexdec.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "speexdec.mak" CFG="speexdec - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "speexdec - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "speexdec - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "speexdec - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /GX /O1 /I "../../include" /I "../../libspeex" /I "../../../ogg/include" /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD BASE RSC /l 0x809 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib winmm.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "speexdec - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /I "../../include" /I "../../libspeex" /I "../../../ogg/include" /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ "../../libspeex" /c +# ADD BASE RSC /l 0x809 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib winmm.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "speexdec - Win32 Release" +# Name "speexdec - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=..\..\src\getopt.c +# End Source File +# Begin Source File + +SOURCE=..\..\src\getopt1.c +# End Source File +# Begin Source File + +SOURCE=..\..\src\speexdec.c +# End Source File +# Begin Source File + +SOURCE=..\..\src\wav_io.c +# End Source File +# Begin Source File + +SOURCE=..\..\src\wave_out.c +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=..\..\src\getopt_win.h +# End Source File +# Begin Source File + +SOURCE=..\..\src\wav_io.h +# End Source File +# Begin Source File + +SOURCE=..\..\src\wave_out.h +# End Source File +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# End Target +# End Project diff --git a/Code/BF2/External/speex-1.0.5/win32/speexdec/speexdec.dsw b/Code/BF2/External/speex-1.0.5/win32/speexdec/speexdec.dsw new file mode 100644 index 000000000..37f2d1f21 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/win32/speexdec/speexdec.dsw @@ -0,0 +1,59 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "libspeex"=..\libspeex\libspeex.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "ogg_static"="..\..\..\MYOV-1.0\ogg\win32\ogg_static.dsp" - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "speexdec"=.\speexdec.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name libspeex + End Project Dependency + Begin Project Dependency + Project_Dep_Name ogg_static + End Project Dependency +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git a/Code/BF2/External/speex-1.0.5/win32/speexenc/Makefile.am b/Code/BF2/External/speex-1.0.5/win32/speexenc/Makefile.am new file mode 100644 index 000000000..c15584f6f --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/win32/speexenc/Makefile.am @@ -0,0 +1,6 @@ +## Process this file with automake to produce Makefile.in. -*-Makefile-*- + +# Disable automatic dependency tracking if using other tools than gcc and gmake +#AUTOMAKE_OPTIONS = no-dependencies + +EXTRA_DIST = speexenc.dsp speexenc.dsw diff --git a/Code/BF2/External/speex-1.0.5/win32/speexenc/Makefile.in b/Code/BF2/External/speex-1.0.5/win32/speexenc/Makefile.in new file mode 100644 index 000000000..3d4988e22 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/win32/speexenc/Makefile.in @@ -0,0 +1,320 @@ +# Makefile.in generated by automake 1.8.5 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004 Free Software Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# Disable automatic dependency tracking if using other tools than gcc and gmake +#AUTOMAKE_OPTIONS = no-dependencies +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +top_builddir = ../.. +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +INSTALL = @INSTALL@ +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +host_triplet = @host@ +subdir = win32/speexenc +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ + $(top_srcdir)/configure.in +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs +CONFIG_CLEAN_FILES = +SOURCES = +DIST_SOURCES = +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMDEP_FALSE = @AMDEP_FALSE@ +AMDEP_TRUE = @AMDEP_TRUE@ +AMTAR = @AMTAR@ +AR = @AR@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +ECHO = @ECHO@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +F77 = @F77@ +FFLAGS = @FFLAGS@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +LDFLAGS = @LDFLAGS@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +MAINT = @MAINT@ +MAINTAINER_MODE_FALSE = @MAINTAINER_MODE_FALSE@ +MAINTAINER_MODE_TRUE = @MAINTAINER_MODE_TRUE@ +MAKEINFO = @MAKEINFO@ +OBJEXT = @OBJEXT@ +OGG_INCLUDES = @OGG_INCLUDES@ +OGG_LDFLAGS = @OGG_LDFLAGS@ +OGG_LIBS = @OGG_LIBS@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +RANLIB = @RANLIB@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SPEEX_LT_AGE = @SPEEX_LT_AGE@ +SPEEX_LT_CURRENT = @SPEEX_LT_CURRENT@ +SPEEX_LT_REVISION = @SPEEX_LT_REVISION@ +SPEEX_VERSION = @SPEEX_VERSION@ +STRIP = @STRIP@ +VERSION = @VERSION@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_CXX = @ac_ct_CXX@ +ac_ct_F77 = @ac_ct_F77@ +ac_ct_RANLIB = @ac_ct_RANLIB@ +ac_ct_STRIP = @ac_ct_STRIP@ +am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ +am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ +am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ +am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +datadir = @datadir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +src = @src@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +EXTRA_DIST = speexenc.dsp speexenc.dsw +all: all-am + +.SUFFIXES: +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ + && exit 0; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu win32/speexenc/Makefile'; \ + cd $(top_srcdir) && \ + $(AUTOMAKE) --gnu win32/speexenc/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +distclean-libtool: + -rm -f libtool +uninstall-info-am: +tags: TAGS +TAGS: + +ctags: CTAGS +CTAGS: + + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ + list='$(DISTFILES)'; for file in $$list; do \ + case $$file in \ + $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ + $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ + esac; \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test "$$dir" != "$$file" && test "$$dir" != "."; then \ + dir="/$$dir"; \ + $(mkdir_p) "$(distdir)$$dir"; \ + else \ + dir=''; \ + fi; \ + if test -d $$d/$$file; then \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + fi; \ + cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + else \ + test -f $(distdir)/$$file \ + || cp -p $$d/$$file $(distdir)/$$file \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile +installdirs: +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + `test -z '$(STRIP)' || \ + echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -rm -f $(CONFIG_CLEAN_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-am + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-libtool + +dvi: dvi-am + +dvi-am: + +html: html-am + +info: info-am + +info-am: + +install-data-am: + +install-exec-am: + +install-info: install-info-am + +install-man: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-info-am + +.PHONY: all all-am check check-am clean clean-generic clean-libtool \ + distclean distclean-generic distclean-libtool distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-exec install-exec-am \ + install-info install-info-am install-man install-strip \ + installcheck installcheck-am installdirs maintainer-clean \ + maintainer-clean-generic mostlyclean mostlyclean-generic \ + mostlyclean-libtool pdf pdf-am ps ps-am uninstall uninstall-am \ + uninstall-info-am + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/Code/BF2/External/speex-1.0.5/win32/speexenc/speexenc.dsp b/Code/BF2/External/speex-1.0.5/win32/speexenc/speexenc.dsp new file mode 100644 index 000000000..279955341 --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/win32/speexenc/speexenc.dsp @@ -0,0 +1,122 @@ +# Microsoft Developer Studio Project File - Name="speexenc" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=speexenc - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "speexenc.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "speexenc.mak" CFG="speexenc - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "speexenc - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "speexenc - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "speexenc - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /GX /O1 /Ob2 /I "../../include" /I "../../libspeex" /I "../../../ogg/include" /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD BASE RSC /l 0x809 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "speexenc - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /I "../../include" /I "../../libspeex" /I "../../../ogg/include" /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD BASE RSC /l 0x809 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "speexenc - Win32 Release" +# Name "speexenc - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=..\..\src\getopt.c +# End Source File +# Begin Source File + +SOURCE=..\..\src\getopt1.c +# End Source File +# Begin Source File + +SOURCE=..\..\src\speexenc.c +# End Source File +# Begin Source File + +SOURCE=..\..\src\wav_io.c +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=..\..\src\getopt_win.h +# End Source File +# Begin Source File + +SOURCE=..\..\src\wav_io.h +# End Source File +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# End Target +# End Project diff --git a/Code/BF2/External/speex-1.0.5/win32/speexenc/speexenc.dsw b/Code/BF2/External/speex-1.0.5/win32/speexenc/speexenc.dsw new file mode 100644 index 000000000..55aa72dbd --- /dev/null +++ b/Code/BF2/External/speex-1.0.5/win32/speexenc/speexenc.dsw @@ -0,0 +1,59 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "libspeex"=..\libspeex\libspeex.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "ogg_static"="..\..\..\MYOV-1.0\ogg\win32\ogg_static.dsp" - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "speexenc"=.\speexenc.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name libspeex + End Project Dependency + Begin Project Dependency + Project_Dep_Name ogg_static + End Project Dependency +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git a/Code/BF2/Game/AudioSettings.cpp b/Code/BF2/Game/AudioSettings.cpp index c3ef6fd66..24e9fbb43 100644 --- a/Code/BF2/Game/AudioSettings.cpp +++ b/Code/BF2/Game/AudioSettings.cpp @@ -7,7 +7,14 @@ #include "../Core/Ids.h" #include "../Core/SmartItf.h" // classManager #include "../Sound/BfSound.h" +#if defined(_WIN32) #include +#else +#include // [CHOSEN, not recovered] hw.memsize for the GlobalMemoryStatus arm +#include +#endif +#include +#include #include #include #include @@ -19,9 +26,23 @@ namespace { int physicalMemoryMegabytes() { try { +#if defined(_WIN32) MEMORYSTATUS status; GlobalMemoryStatus(&status); int megabytes = static_cast((status.dwTotalPhys + 0x7FFFFu) >> 20); +#else + // [CHOSEN, not recovered] GlobalMemoryStatus for the large-address-aware 32-bit BF2.exe: + // dwTotalPhys is a 32-bit DWORD saturated at 0xFFFFFFFF above 4 GB. The same DWORD + // arithmetic follows, so a machine with 4 GB or more wraps to 0 MB and selects "Low", as + // the retail client does on such a machine. + std::uint64_t physical = 0; + std::size_t length = sizeof(physical); + if (sysctlbyname("hw.memsize", &physical, &length, 0, 0) != 0) + physical = 0; + const std::uint32_t totalPhys = physical > 0xFFFFFFFFull ? 0xFFFFFFFFu + : static_cast(physical); + int megabytes = static_cast(static_cast(totalPhys + 0x7FFFFu) >> 20); +#endif const int remainder = megabytes % 4; if (remainder) megabytes += 4 - remainder; return megabytes; @@ -314,6 +335,19 @@ bool AudioSettings::apply(bool reportErrors) applyRecord(m_current, reportErrors); g_bfSound->engine()->playMusic(); } + // [TEMP] [CHOSEN, not recovered] BF2_AUDIO_TRACE=1: what an apply left in the sound + // facade, for unattended option runs. [RETIRE-WHEN: macos-options-validated] + const char* trace = std::getenv("BF2_AUDIO_TRACE"); + if (trace && trace[0] == '1') + { + std::fprintf(stderr, "[TEMP] [AUDIO] apply result=%d status=%d provider=\"%s\" eax=%d quality=\"%s\" " + "groups effects=%.3f music=%.3f voice=%.3f effects3=%.3f\n", + result ? 1 : 0, m_status, m_current.provider.c_str(), m_current.enableEAX ? 1 : 0, + m_current.soundQuality.c_str(), g_bfSound->getVolumeForGroup(0), + g_bfSound->getVolumeForGroup(1), g_bfSound->getVolumeForGroup(2), + g_bfSound->getVolumeForGroup(3)); + std::fflush(stderr); + } } return result; } diff --git a/Code/BF2/Game/Common/ClientConnection.cpp b/Code/BF2/Game/Common/ClientConnection.cpp index b5bf1af30..3cf7d4959 100644 --- a/Code/BF2/Game/Common/ClientConnection.cpp +++ b/Code/BF2/Game/Common/ClientConnection.cpp @@ -23,6 +23,7 @@ #include "../../IO/Network/NetworkManager.h" // io::networkManager - transmitMsgs' local-latency arm #include "../../Physics/LatencyCompensation.h" // world::LatencyCompensation::getLocalLatency (local only) #include "../GameServer/ServerSettings.h" // sv.demoQuality - demoQualityFromSettings' single read +#include "../../Platform/MsvcRand.h" // [CHOSEN, not recovered] the client CRT's rand (MSVCR71) namespace dice { namespace hfe { @@ -243,7 +244,7 @@ const char* ClientConnection::initChallengeString(const char* fixed) else { for (int j = 0; j <= 9; ++j) - m_challengeString[j] = static_cast(rand() % 26 + 97); + m_challengeString[j] = static_cast(bf2crt::rand() % 26 + 97); m_challengeString[9] = 0; // the tenth byte becomes the terminator } return m_challengeString; diff --git a/Code/BF2/Game/Common/DataBlockManager.cpp b/Code/BF2/Game/Common/DataBlockManager.cpp index 74052808e..e11b92d53 100644 --- a/Code/BF2/Game/Common/DataBlockManager.cpp +++ b/Code/BF2/Game/Common/DataBlockManager.cpp @@ -1,6 +1,7 @@ // Splits and assembles network data blocks, transferring completed payloads into events. #include "DataBlockManager.h" +#include // fprintf - the oversized-announcement report #include // memcpy - addDataChunk and enqueueDataBlock #include "GameEventManager.h" // addEvent / getConnectionId @@ -118,11 +119,31 @@ void DataBlockManager::update() } // Starts assembling one incoming block. Returns false if another is in progress. +// ELF 0x808C7E0 passes the announced size to operator new[] (0x808C837) unchecked; the size +// comes straight off the wire (DataBlockEvent::deSerialize, ELF 0x806F9F0, 32 bits), so any +// peer could make the receiver attempt a 4 GB allocation. +// [CHOSEN, not recovered] Announcements above MAX_RECEIVE_SIZE are refused like a busy +// manager: nothing is allocated, m_receiving stays empty, and the block's chunks are then +// dropped by addDataChunk. The connection is kept. Logged once per process. bool DataBlockManager::newDataBlock(unsigned int blockEventId, unsigned int size) { if (m_receiving) return false; // already assembling one + if (size > MAX_RECEIVE_SIZE) + { + static bool reported = false; + if (!reported) + { + reported = true; + std::fprintf(stderr, "[CHOSEN, not recovered] DataBlockManager::newDataBlock: refused " + "block %u announcing %u bytes (limit %u); further refusals are " + "not logged\n", blockEventId, size, + static_cast(MAX_RECEIVE_SIZE)); + } + return false; + } + DataBlock* const block = new DataBlock; block->m_position = 0; block->m_data = 0; diff --git a/Code/BF2/Game/Common/DataBlockManager.h b/Code/BF2/Game/Common/DataBlockManager.h index 445b70a53..12ba0aaba 100644 --- a/Code/BF2/Game/Common/DataBlockManager.h +++ b/Code/BF2/Game/Common/DataBlockManager.h @@ -47,6 +47,13 @@ class DataBlockReadyEvent : public EventNode class DataBlockManager { public: + // [CHOSEN, not recovered] Largest incoming block newDataBlock accepts (retail has no limit). + // The largest fixed-size senders are EndOfRoundInfo (7,166 bytes), ServerInfo (895) and + // MapInfo (369); the map list and remote-console text grow with their content but stay in + // the tens of kilobytes. 1 MiB leaves a wide margin and bounds the memory a peer can + // claim to one such buffer per connection. + enum { MAX_RECEIVE_SIZE = 0x100000 }; + DataBlockManager(GameEventManager* gameEvents, bool isRecording); // Keep these four methods before the virtual destructor to preserve interface order. diff --git a/Code/BF2/Game/Common/GhostManager.cpp b/Code/BF2/Game/Common/GhostManager.cpp index 83274b203..b043f7439 100644 --- a/Code/BF2/Game/Common/GhostManager.cpp +++ b/Code/BF2/Game/Common/GhostManager.cpp @@ -37,6 +37,7 @@ #include "../../Core/ClassManager.h" // getClassName +0x28 - debugShowActiveGhosts #include "../../Core/SettingsRepostitory.h" // GSDebugGhostManager, boolGet +0x50 +#include // offsetof - the retail layout checks below #include // memset - the 4 KB ghost table #include // debugShowActiveGhosts' two locals @@ -45,6 +46,12 @@ namespace hfe { extern ClassManager* classManager; // Core/Globals.cpp - the per-TU extern convention +#if defined(_M_IX86) +// readData's remove and update arms read these two fields at their retail offsets. +static_assert(offsetof(io::INetworkableObject, m_ownerId) == 0x04, "retail owner id"); +static_assert(offsetof(io::INetworkableObject, m_object) == 0x08, "retail replicated object"); +#endif + // Initialize per-connection ghost queues and baseline storage. Ghost ids are seeded // lazily on first assignment. State masks and the control-object id are deliberately // left uninitialized until their owning paths set them. @@ -1722,13 +1729,12 @@ bool GhostManager::readData(io::BitStream& stream) io::INetworkableObject* const objEntry = networkable->m_networkableObject; bool disable = true; - if (objEntry && *reinterpret_cast( - reinterpret_cast(objEntry) + 4) >= 0) + // The retail reads are the low word of m_ownerId (+0x04 on x86), sign-extended. + if (objEntry && static_cast(objEntry->m_ownerId) >= 0) { // the object belongs to a player - only disable it if that player is gone // or local, and only if it is not parented to something else. - const short playerId = *reinterpret_cast( - reinterpret_cast(objEntry) + 4); + const short playerId = static_cast(objEntry->m_ownerId); world::IPlayer* const player = world::playerManager->getPlayerFromId(playerId); if (!player || !player->getIsRemote() || object->getParent()) disable = false; @@ -1782,10 +1788,10 @@ bool GhostManager::readData(io::BitStream& stream) io::INetworkable* const n = desc ? desc->properties[0].networkables[0] : 0; if (n && n->m_networkableObject) { - const unsigned char* const info = - *reinterpret_cast( - reinterpret_cast(n->m_networkableObject) + 8); - if (info && (info[4] & 0x20)) + // The retail reads [netobj +0x08] (m_object) and tests the low byte of that object's + // +0x04 flag word, the same bit sendData skips on. + const world::IObject* const info = n->m_networkableObject->m_object; + if (info && (static_cast(info->getFlags()) & 0x20)) desc = 0; // treat it as unknown: skip the payload } } diff --git a/Code/BF2/Game/Common/PlayerActionManager.cpp b/Code/BF2/Game/Common/PlayerActionManager.cpp index cd54f3011..c705a0c2d 100644 --- a/Code/BF2/Game/Common/PlayerActionManager.cpp +++ b/Code/BF2/Game/Common/PlayerActionManager.cpp @@ -32,6 +32,9 @@ PlayerActionManager::PlayerActionManager() std::memset(&zeroInput, 0, sizeof(zeroInput)); PlayerAction zeroAction; + // set() does not write m_inputIndex, so the index is cleared first. transmit sends slot 0's + // index as the packet's base index while add() is still sliding these placeholders out. + zeroAction.m_inputIndex = 0; zeroAction.set(zeroInput); for (int i = 0; i < 3; ++i) diff --git a/Code/BF2/Game/Common/ServerConnection.cpp b/Code/BF2/Game/Common/ServerConnection.cpp index c1095b771..62b1a2405 100644 --- a/Code/BF2/Game/Common/ServerConnection.cpp +++ b/Code/BF2/Game/Common/ServerConnection.cpp @@ -39,6 +39,7 @@ #include "../../IO/Network/NetworkableInfo.h" // getForceNetworkableId - the phase-A replication gate #include "../../Scene/Object/ObjectTypes/Game/IPlayerControlObject.h" // getDefaultTeam - the object's team #include "../Objects/ObjectLayoutAccess.h" // physicsNode (+0x44) / objectTemplate (+0x14) +#include "../Objects/RemoteControlledObjectTemplate.h" // rcType - getSpecialCommanderObjects #include "../../Physics/IPhysicsNode.h" // getPositionalSpeed (+0x60) - the priority speed factor #include "../../IO/Network/INetworkableObject.h" // m_ownerId / m_object - the scope pass reads both #include "../../Core/Debug.h" // the attested line-98 "Control object not found" @@ -75,15 +76,6 @@ int remoteControlledObjectTeam(world::IObject* object) return 0; } -// Returns the template's remote-control type, despite the helper's State name. -// [UNRESOLVED] Meanings of the selected type values. -int remoteControlledObjectState(world::IObject* object) -{ - const char* const templ = reinterpret_cast( - world::object_detail::LayoutAccess::objectTemplate(object)); // IObject +0x14 - return *reinterpret_cast(templ + 0x180); // ...Template::rcType -} - // ICameraObject's transform - both updateGhostManager call sites inline `vtable +0x10 with a 0 // argument` and copy the 64-byte result; that slot is getTransformation(float). void cameraTransform(world::ICameraObject* camera, Mat4& out) @@ -213,7 +205,11 @@ void ServerConnection::getSpecialCommanderObjects(int team) it != rcObjects.end(); ++it) { world::IObject* const object = it->second; - const int state = remoteControlledObjectState(object); // the template's rcType + // Registry objects carry a RemoteControlledObjectTemplate; the PE reads its rcType at + // retail +0x180. The named member, because this build's template layout is not retail's + // (rcType sits at +0x208 on x86 here). [UNRESOLVED] Meanings of the selected type values. + const int state = static_cast( + world::object_detail::LayoutAccess::objectTemplate(object))->rcType; // IObject +0x14 if (remoteControlledObjectTeam(object) != team) continue; if (state != 1 && state != 2 && state != 3) diff --git a/Code/BF2/Game/ControlSettings.cpp b/Code/BF2/Game/ControlSettings.cpp index 1703ef526..aaa70d91f 100644 --- a/Code/BF2/Game/ControlSettings.cpp +++ b/Code/BF2/Game/ControlSettings.cpp @@ -218,7 +218,7 @@ void ControlSettings::updateInputDevices() // it is a game input, the output name is emptied, the manager captures into it, and the frame // event manager is asked to post event (10, 12) - the engine's EnableEscapeKeyMapping handler, // which clears the flag - two seconds later (40000000h). The third argument is never read. -bool ControlSettings::mapNextInput(int input, bool alternate, int /*unused*/, bool second, bool gameInput) +int ControlSettings::mapNextInput(int input, bool alternate, int /*unused*/, bool second, bool gameInput) { m_mappingInput = true; bool isAxis = false; @@ -229,7 +229,7 @@ bool ControlSettings::mapNextInput(int input, bool alternate, int /*unused*/, bo } } m_mappedInputName = ""; - const bool result = mapManager()->mapNextInput(m_map, input, alternate, isAxis, second, !gameInput, m_mappedInputName); + const int result = mapManager()->mapNextInput(m_map, input, alternate, isAxis, second, !gameInput, m_mappedInputName); frameEventManager->postEvent(static_cast(10), 12u, nullptr, 2.0f); return result; } diff --git a/Code/BF2/Game/ControlSettings.h b/Code/BF2/Game/ControlSettings.h index 8268d6ea2..7a1880a67 100644 --- a/Code/BF2/Game/ControlSettings.h +++ b/Code/BF2/Game/ControlSettings.h @@ -21,7 +21,7 @@ class IControlSettings : public IBase { virtual bool setDefaults() = 0; //+24 4B3230: reset, re-run Settings/Controls.con, back up; true virtual void resetControlMaps() = 0; //+28 4B2BE0: reset() on every live map virtual void updateInputDevices() = 0; //+2C 4B2C70: device manager update(-1.0f) then update(0.1f) - virtual bool mapNextInput(int input, bool alternate, int unused, bool second, bool gameInput) = 0; + virtual int mapNextInput(int input, bool alternate, int unused, bool second, bool gameInput) = 0; //+30 4B2CA0: the manager's full EAX (int status) virtual bool selectControlMap(const std::string& name) = 0; //+34 4B38A0: the map the feel accessors forward to; true virtual bool getBindingDescription(io::IControlMap* map, int input, bool alternate, bool second, bool gameInput, std::string& key, std::wstring& text) = 0; @@ -72,7 +72,7 @@ class ControlSettings final : public IControlSettings { bool setDefaults() override; void resetControlMaps() override; void updateInputDevices() override; - bool mapNextInput(int input, bool alternate, int unused, bool second, bool gameInput) override; + int mapNextInput(int input, bool alternate, int unused, bool second, bool gameInput) override; bool selectControlMap(const std::string& name) override; bool getBindingDescription(io::IControlMap* map, int input, bool alternate, bool second, bool gameInput, std::string& key, std::wstring& text) override; diff --git a/Code/BF2/Game/DemoAvailableInfo.cpp b/Code/BF2/Game/DemoAvailableInfo.cpp new file mode 100644 index 000000000..be04db203 --- /dev/null +++ b/Code/BF2/Game/DemoAvailableInfo.cpp @@ -0,0 +1,114 @@ +// Demo download announcement serialization (data block 9). +// Recovered from the symbolized dedicated ELF (0x8054B10..0x8055120); the client's reader is +// BF2.exe 0x5BCB40, its constructor 0x5BCC50. +#include "DemoAvailableInfo.h" + +#include "../Core/StringUtil.h" // getEmptyString - clear() +#include "../IO/BitStream.h" + +#include + +namespace dice { +namespace hfe { + +namespace { + +// Each string is an 8-bit length, at most 256 (which the 8-bit field writes as 0, as shipped), +// then its bytes. +void writeAnnouncedString(io::BitStream& stream, const std::string& text) +{ + const unsigned int length = text.size() < 0x100 ? static_cast(text.size()) : 0x100; + stream.writeBits(&length, 8); + for (unsigned int i = 0; i < length; ++i) + { + const int character = static_cast(text[i]); + stream.writeBits(&character, 8); + } +} + +// The reader fills a zeroed 257-byte buffer and keeps strlen of it, so an embedded NUL truncates. +void readAnnouncedString(io::BitStream& stream, std::string& out) +{ + unsigned int length = 0; + stream.readBits(&length, 8); + char buffer[257]; + std::memset(buffer, 0, sizeof(buffer)); + for (unsigned int i = 0; i < length; ++i) + { + unsigned int character = 0; + stream.readBits(&character, 8); + buffer[i] = static_cast(character); + } + out.assign(buffer, std::strlen(buffer)); +} + +} // namespace + +// DemoAvailableInfo - ELF 0x8054B10 / 0x8054B60. +DemoAvailableInfo::DemoAvailableInfo() + : m_url() + , m_mapName() + , m_dirty(true) + , m_netBuffer() +{ +} + +// clear - ELF 0x8054BB0: both strings emptied (map first); the buffer is not dirtied, as shipped. +void DemoAvailableInfo::clear() +{ + m_url = (m_mapName = getEmptyString()); +} + +const std::string& DemoAvailableInfo::getUrl() const { return m_url; } // 0x8054BF0 + +void DemoAvailableInfo::setUrl(const std::string& url) // 0x8054C00 +{ + m_url = url; + m_dirty = true; +} + +const std::string& DemoAvailableInfo::getMapName() const { return m_mapName; } // 0x8054C30 + +void DemoAvailableInfo::setMapName(const std::string& mapName) // 0x8054C40 +{ + m_mapName = mapName; + m_dirty = true; +} + +// setFromDataBlock - ELF 0x8054C70, 459 B. No stream-error report. +void DemoAvailableInfo::setFromDataBlock(const void* data, unsigned int size) +{ + io::BitStream stream(static_cast(const_cast(data)), size); + stream.setReadMode(); + stream.setBitSize(8 * size); + readAnnouncedString(stream, m_url); + readAnnouncedString(stream, m_mapName); +} + +const void* DemoAvailableInfo::getNetBuffer() // 0x8054E40 +{ + if (m_dirty) + updateNetBuffer(); + return m_netBuffer.empty() ? 0 : &m_netBuffer[0]; +} + +unsigned int DemoAvailableInfo::getNetBufferSize() // 0x8054E70 +{ + if (m_dirty) + updateNetBuffer(); + return static_cast(m_netBuffer.size()); +} + +// updateNetBuffer - ELF 0x8054EA0, 640 B: a 367-byte staging buffer trimmed to the bits written. +void DemoAvailableInfo::updateNetBuffer() +{ + m_netBuffer.resize(0x16F, 0); + io::BitStream stream(&m_netBuffer[0], static_cast(m_netBuffer.size())); + writeAnnouncedString(stream, m_url); + writeAnnouncedString(stream, m_mapName); + m_netBuffer.resize((stream.getBitPosition() + 7) >> 3, 0); + m_dirty = false; +} + +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/Game/DemoAvailableInfo.h b/Code/BF2/Game/DemoAvailableInfo.h new file mode 100644 index 000000000..0e8cfaea5 --- /dev/null +++ b/Code/BF2/Game/DemoAvailableInfo.h @@ -0,0 +1,42 @@ +// A recorded demo's download announcement: url and map, sent by the server as data block 9 +// after its auto-demo hook ran. STL members make object size and offsets toolchain-dependent +// (ELF: url +0x00, mapName +0x04, dirty +0x08, net buffer +0x0C; BF2.exe: +0x00 / +0x1C / +0x38 +// / +0x3C). + +#ifndef GAME_DEMOAVAILABLEINFO_H +#define GAME_DEMOAVAILABLEINFO_H + +#include +#include + +namespace dice { +namespace hfe { + +class DemoAvailableInfo +{ +public: + DemoAvailableInfo(); + + void clear(); + const std::string& getUrl() const; + void setUrl(const std::string& url); + const std::string& getMapName() const; + void setMapName(const std::string& mapName); + + void setFromDataBlock(const void* data, unsigned int size); + const void* getNetBuffer(); + unsigned int getNetBufferSize(); + +private: + void updateNetBuffer(); + + std::string m_url; + std::string m_mapName; + bool m_dirty; + std::vector m_netBuffer; +}; + +} // namespace hfe +} // namespace dice + +#endif // GAME_DEMOAVAILABLEINFO_H diff --git a/Code/BF2/Game/DemoRecorder/DemoLibrary.cpp b/Code/BF2/Game/DemoRecorder/DemoLibrary.cpp index 2c284150f..f88d13eea 100644 --- a/Code/BF2/Game/DemoRecorder/DemoLibrary.cpp +++ b/Code/BF2/Game/DemoRecorder/DemoLibrary.cpp @@ -1,7 +1,7 @@ // [INFERRED] path. Full client PE410742/4C2510/4C25D0/4C2590/479830/4C3030/4C2A60/4C1D90/4C1FF0/ -// /4C1B90/689430/4C1BA0/4C1BB0/4C1BC0/4B3AB0/4B1C80/4C1C00/4C1DB0 read; the HTTP-side -// bodies 4C2DF0/4C1B70/4C1B80/4C1BD0 read and left as diagnostic stops at their first use of the -// withheld HTTPRequest base. +// /4C1B90/689430/4C1BA0/4C1BB0/4C1BC0/4B3AB0/4B1C80/4C1C00/4C1DB0 read. The HTTP side +// (4C1B70/4C1B80/4C1BD0 and the callbacks 4C1EC0/4C2D70/4B3A90) is recovered on the HTTPRequest +// base (Game/Persistence/HTTPRequest.cpp); 4C2DF0 (download) remains a stop. #include "DemoLibrary.h" #if !DEDICATED #include "DemoHeader.h" @@ -14,6 +14,11 @@ #include "../../IO/Stream/ZStream.h" #include #include +#include +#if !defined(_WIN32) +#include // strcasecmp - the _stricmp of 4C26E0 +#endif +#include #include #include @@ -22,7 +27,7 @@ extern ClassManager* classManager; DemoLibraryEntry::DemoLibraryEntry() : version(0) {} // constructs the five strings; the int is written by refresh -// (124 B): the withheld base's constructor (59C390) runs first in retail; then the table, +// 4C2510 (124 B): the HTTPRequest base's constructor (59C390) runs first; then the table, // refcount 1, the empty entry vector, the four strings, progress 0, the two flags clear and the // pending bookmark -1. DemoLibrary::DemoLibrary() @@ -30,8 +35,8 @@ DemoLibrary::DemoLibrary() { } -// (131 B): the four strings in reverse order, the entry rows and their storage, then the -// withheld base's destructor (59C3C0). +// 4C25D0 (131 B): the four strings in reverse order, the entry rows and their storage, then the +// HTTPRequest base's destructor (59C3C0). DemoLibrary::~DemoLibrary() {} // (66 B): the settings-factory shape - aggregation refused, 176 retail bytes, construction @@ -114,13 +119,77 @@ bool DemoLibrary::refreshEntries() return true; } -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: demo-library-http-request] -// Stops until the HTTP request base and transfer lifecycle are recovered. -bool DemoLibrary::download(const std::string&, const std::string&, const std::string&) +// nextFreeDemoName - 4C26E0, 689 B: "demo" for the smallest N no .bf2demo in the profile demo +// folder is named after (compared case-insensitively, _stricmp). No current profile: "". +std::string DemoLibrary::nextFreeDemoName() +{ + IBase* manager = classManager->getSingleton(std::string("LocalProfileManager")); + if (!manager || !static_cast(manager)->getCurrentProfile()) // +44 + return std::string(""); + const std::string directory("@HOME@/Profiles/Default/demos/"); + std::string candidate; + std::vector taken; + std::list files; + io::fileManager->findFiles(directory, false, files); // +34 + for (std::list::iterator it = files.begin(); it != files.end(); ++it) { + io::FileInfo info = *it; + if (info.isDirectory) + continue; + if (extractFileExt(info.name) == "bf2demo") + taken.push_back(extractFileNameWithoutExt(info.name)); + } + for (int index = 0;; ++index) { + candidate = formatString("demo%d", index); + std::vector::size_type i = 0; +#if defined(_WIN32) + while (i < taken.size() && ::_stricmp(taken[i].c_str(), candidate.c_str()) != 0) +#else + while (i < taken.size() && ::strcasecmp(taken[i].c_str(), candidate.c_str()) != 0) +#endif + ++i; + if (i == taken.size()) + break; + } + return candidate; +} + +// download - 4C2DF0, 571 B: a busy transfer is cancelled first; the name, url and description +// are kept for the menu, the progress reset. With a current profile, the demo folder is touched +// into existence (dummy.txt written, then deleted) and the file goes to /profiles/Default/ +// demos/.bf2demo through the base's asynchronous getFile. A refused request +// reports "Unable to download demo file". The completion callback rescans the library. +bool DemoLibrary::download(const std::string& name, const std::string& url, const std::string& description) { - std::fprintf(stderr, "[FRONTIER] dice::hfe::DemoLibrary::download: the HTTPRequest base (Game/Persistence/HTTPRequest.cpp, PE59C390) that PE4C2DF0 tests first is unrecovered\n"); - std::fflush(stderr); - std::abort(); + if (HTTPRequest::isUpdating()) // 59C400 + HTTPRequest::cancel(); // 59C440 + m_downloadFailed = false; + m_downloadName = name; + m_downloadUrl = url; + m_downloadDescription = description; + m_downloadProgress = 0.0f; + IBase* manager = classManager->getSingleton(std::string("LocalProfileManager")); + if (!manager || !static_cast(manager)->getCurrentProfile()) // +44 + return false; + // fileManager +0x54 (the base file system) +0x48: the @HOME@ substitution. + std::string folder(io::fileManager->getBaseSystem()->getHomeSubstitution()); +#if defined(_WIN32) + folder += "\\profiles\\Default\\demos\\"; +#else + // [PLATFORM] The GameSpy HTTP SDK opens the target with fopen, so the POSIX client spells the + // folder with '/' and in the lower case UnixFileSystem::fixUnixPath gives every path after the + // home prefix (the library scans the same folder through it). + folder += "/profiles/default/demos/"; +#endif + const std::string dummy(folder + "dummy.txt"); + io::fileManager->writeFile(dummy, 0, 0, true); // +30 + io::fileManager->deleteFile(dummy); // +20 + const std::string target(folder + nextFreeDemoName() + ".bf2demo"); + m_downloadPath = target; // +30 + if (!HTTPRequest::getFile(url, target, true)) { // 59C5B0 + reportError(std::string("Unable to download demo file")); + return false; + } + return true; } unsigned int DemoLibrary::getNumEntries() @@ -147,27 +216,54 @@ bool DemoLibrary::removeEntry(unsigned int index) return true; } -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: demo-library-http-request] -// / 4C1B80 / 4C1BD0 forward to the withheld base (59C420 think, 59C400 busy, 59C440 cancel -// followed by the target file's deletion). +// 4C1B70: `add ecx,4; jmp 59C420` - the base's think (no SDK call while both handles are -1). +// The tail jump leaves no defined answer in EAX; the only caller (SwiffHost::update) drops it. int DemoLibrary::update() { - std::fprintf(stderr, "[FRONTIER] dice::hfe::DemoLibrary::update: HTTPRequest 59C420 (PE4C1B70) is unrecovered\n"); - std::fflush(stderr); - std::abort(); + HTTPRequest::update(); + return 0; } +// 4C1B80: `add ecx,4; jmp 59C400` - the base's pending-transfer test. bool DemoLibrary::isDownloading() { - std::fprintf(stderr, "[FRONTIER] dice::hfe::DemoLibrary::isDownloading: HTTPRequest 59C400 (PE4C1B80) is unrecovered\n"); - std::fflush(stderr); - std::abort(); + return HTTPRequest::isUpdating(); } +// 4C1BD0: through the table's +28 (isDownloading); when busy, the base's cancel (59C440), then +// fileManager +20 deletes the target file (+30), and true. Idle answers the +28 false. bool DemoLibrary::cancelDownload() { - std::fprintf(stderr, "[FRONTIER] dice::hfe::DemoLibrary::cancelDownload: HTTPRequest 59C440 (PE4C1BD0) is unrecovered\n"); - std::fflush(stderr); - std::abort(); + if (!isDownloading()) + return false; + HTTPRequest::cancel(); + io::fileManager->deleteFile(m_downloadPath); // +20 + return true; +} +// 4C1EC0 (this = base +4): failed flag (+AC) set, the base failure (59C640), the message posted +// when it is not "" (operator!= 87F324 against 87FB54), then the partial target (+30) deleted. +void DemoLibrary::onGetFailure(const std::string& message) +{ + m_downloadFailed = true; + HTTPRequest::onGetFailure(message); + if (message != "") + reportError(message); + io::fileManager->deleteFile(m_downloadPath); // +20 +} +// 4C2D70: failed flag cleared, the base completion (59C660); a pending bookmark (+A8 != -1) goes +// to LocalProfileManager +B0 when that singleton exists, then is reset to -1; then the rescan 4C2A60. +void DemoLibrary::onGetFileComplete() +{ + m_downloadFailed = false; + HTTPRequest::onGetFileComplete(); + if (m_pendingBookmark != -1) { + IBase* manager = classManager->getSingleton(std::string("LocalProfileManager")); + if (manager) + static_cast(manager)->removeDemoBookmark(static_cast(m_pendingBookmark)); // +B0 + m_pendingBookmark = -1; + } + refreshEntries(); } +// 4B3A90 (ICF-shared): the progress float is stored at +A0. +void DemoLibrary::onProgress(float progress) { m_downloadProgress = progress; } const std::string& DemoLibrary::getDownloadName() { return m_downloadName; } const std::string& DemoLibrary::getDownloadUrl() { return m_downloadUrl; } diff --git a/Code/BF2/Game/DemoRecorder/DemoLibrary.h b/Code/BF2/Game/DemoRecorder/DemoLibrary.h index 381897ac3..38344b7a1 100644 --- a/Code/BF2/Game/DemoRecorder/DemoLibrary.h +++ b/Code/BF2/Game/DemoRecorder/DemoLibrary.h @@ -1,10 +1,11 @@ // Lists profile demos and exposes download controls. [INFERRED] Names and placement. -// [FRONTIER] [RETIRE-WHEN: demo-library-http-request] Implement the HTTPRequest base, -// callbacks, and download/update/status/cancel slots before enabling HTTP use; -// remaining calls stop with diagnostics. +// The HTTPRequest base sits at +4 (ctor 4C2510 calls 59C390 on [esi+4] and stores its table +// 8A90E8 there). update/isDownloading/cancelDownload and the three callbacks are recovered; +// download (4C2DF0) still stops: its target-name helper 4C26E0 is unrecovered. #ifndef GAME_DEMORECORDER_DEMOLIBRARY_H #define GAME_DEMORECORDER_DEMOLIBRARY_H #include "../../Core/IBase.h" +#include "../Persistence/HTTPRequest.h" #include #include #if !DEDICATED @@ -30,27 +31,27 @@ struct DemoLibraryEntry class IDemoLibrary : public IBase { public: virtual bool refresh() = 0; //+10 4C3030: 4C2A60, then true; LocalProfileManager::login 4AA4CD - virtual bool download(const std::string& name, const std::string& url, const std::string& description) = 0; //+14 4C2DF0 [FRONTIER] + virtual bool download(const std::string& name, const std::string& url, const std::string& description) = 0; //+14 4C2DF0 (name helper 4C26E0) virtual unsigned int getNumEntries() = 0; virtual DemoLibraryEntry* getEntry(unsigned int index) = 0; //+1C 4C1FF0: null past the count (through the virtual count) virtual bool removeEntry(unsigned int index) = 0; //+20 4C2660: deletes the file, erases the row - virtual int update() = 0; //+24 4C1B70 -> HTTPRequest 59C420 [FRONTIER] - virtual bool isDownloading() = 0; //+28 4C1B80 -> HTTPRequest 59C400 [FRONTIER] + virtual int update() = 0; //+24 4C1B70 -> HTTPRequest 59C420 + virtual bool isDownloading() = 0; //+28 4C1B80 -> HTTPRequest 59C400 virtual const std::string& getDownloadName() = 0; //+2C 4C1B90 +4C virtual const std::string& getDownloadUrl() = 0; virtual const std::string& getDownloadDescription() = 0; virtual float getDownloadProgress() = 0; //+38 4C1BB0 +A0 - virtual bool cancelDownload() = 0; //+3C 4C1BD0 [FRONTIER] + virtual bool cancelDownload() = 0; //+3C 4C1BD0 virtual bool getFlagA4() = 0; //+40 4C1BC0 +A4 [UNRESOLVED role] virtual void setFlagA4(bool value) = 0; //+44 4B3AB0 (ICF-shared setter) virtual void setPendingBookmark(int index) = 0; //+48 4B1C80 +A8; the download-complete callback hands it to LocalProfileManager +B0 virtual bool hasDownloadFailed() = 0; //+4C 4C1C00 +AC, raised by the failure callback }; -class DemoLibrary final : public IDemoLibrary { +class DemoLibrary final : public IDemoLibrary, public HTTPRequest { public: - DemoLibrary(); // retail 176 bytes (24 of them the withheld base) - ~DemoLibrary(); // body; the slot sits in the withheld base's table + DemoLibrary(); // 4C2510, retail 176 bytes (24 of them the base at +4) + ~DemoLibrary(); // 4C25D0; its slot is the base table's 4C25C0 thunk static IBase* create(unsigned int iid, IBase* outer); void addRef() override; // shared int getRef() override; // shared @@ -72,10 +73,15 @@ class DemoLibrary final : public IDemoLibrary { void setFlagA4(bool value) override; void setPendingBookmark(int index) override; bool hasDownloadFailed() override; + // The HTTPRequest table 8A90E8: +8 4C1EC0, +C 4C2D70, +18 4B3A90 (the rest are the base's). + void onGetFailure(const std::string& message) override; + void onGetFileComplete() override; + void onProgress(float progress) override; private: friend struct DemoLibraryFixture; - bool refreshEntries(); // [INFERRED] name + bool refreshEntries(); + std::string nextFreeDemoName(); // 4C26E0 [INFERRED] name // [INFERRED] name void reportError(const std::string& message); // [INFERRED] name: SwiffHost +1E4 record {1, message, 0} int m_refCount; // retail +1C std::vector m_entries; // retail +20 diff --git a/Code/BF2/Game/DemoRecorder/DemoRecorder.cpp b/Code/BF2/Game/DemoRecorder/DemoRecorder.cpp index 67723d096..5bcb89851 100644 --- a/Code/BF2/Game/DemoRecorder/DemoRecorder.cpp +++ b/Code/BF2/Game/DemoRecorder/DemoRecorder.cpp @@ -6,41 +6,35 @@ #include "DemoRecorder.h" #include "DemoHeader.h" +#include "DemoSpectatorCamera.h" #include "../GameServer/ServerSettings.h" // ds:0x8AAB7A0 - the header's server name #include "../IGame.h" // game->getCurrentMapName() - the header's map name #include "../../Core/Debug.h" // init()'s two fatal diagnostics, lines 123 and 133 #include "../../Core/SystemInfo.h" // systemInfo()->getDateTimeString() - vptr +0x0C +#include "../../Core/System.h" // WorldPref::resetTickCount / getTickCount - the playback clock +#include "../../IO/Console/Console.h" // io::mainConsole->run - the demo camera .con files #include "../../IO/BitStream.h" // m_highWaterBits / getBuffer - the packet payload #include "../../IO/File/FileManager.h" // io::fileManager->open - vptr +0x18 #include "../../IO/Stream/IStream.h" // write +0x14, release +0x08 #include "../../IO/Stream/ZStream.h" // the deflate wrapper every .bf2demo is written through -#include // fprintf / fflush - the [FRONTIER] stops -#include // abort namespace dice { namespace hfe { namespace { +// openCompressedDemoFile - ELF 0x814F780, 184 B. // Opens a compressed demo stream. The compression wrapper retains its own reference, -// so the initial file-stream reference is released before returning it. The playback -// branch remains a separate frontier. +// so the initial file-stream reference is released before returning it. Reading opens with +// mode 2 / access 0 whatever secondFlag says; writing picks mode 0 or 1 from it, access 2. io::IStream* openCompressedDemoFile(const std::string& path, bool forWrite, bool secondFlag) { - if (!forWrite) - { - std::fprintf(stderr, "[FRONTIER] dice::hfe::(anon)::openCompressedDemoFile playback branch " - "reached (ELF 0x814F810)\n"); - std::fflush(stderr); - std::abort(); - } - - io::IStream* const file = io::fileManager->open( - path, - static_cast(secondFlag ? 0 : 1), - static_cast(2), - 0); + io::IStream* const file = forWrite + ? io::fileManager->open(path, static_cast(secondFlag ? 0 : 1), + static_cast(2), 0) + : io::fileManager->open(path, static_cast(2), + static_cast(0), 0); if (!file) return 0; @@ -100,14 +94,14 @@ void DemoRecorder::init(const DemoConfig& config) demoHeader = new DemoHeader(); // operator new(0x14) visualUpdateB = 0.0f; - byte5C = false; - byte5D = false; - dword60 = 0; - dword64 = 0; + tickResynced = false; + frameHeaderRead = false; + frameTick = 0; + frameSize = 0; bufferCapacity = 0x40000; bufferData = 0; demoSpectatorCamera = 0; - byte74 = false; + endOfStream = false; renderType = 0; byte84 = false; @@ -133,8 +127,17 @@ void DemoRecorder::init(const DemoConfig& config) renderMode = inited; } -// Opens recording streams. Camera mode 1 also needs the spectator rig and camera -// track. [FRONTIER] That client-only rig remains unrecovered. +namespace { +// The eight empty arguments and the ignored result of io::Console::run, as every .con runner passes. +void runDemoCameraConfig(const char* file) +{ + io::mainConsole->run(file, "", "", "", "", "", "", "", "", io::Console::ignoredString_); // vptr +0x28 +} +} // namespace + +// initRecord - ELF 0x814FDF0, 847 B. +// Opens the packet stream; camera mode 1 also records the spectator camera to cameraFile and +// runs Settings/demo-recordcam.con. bool DemoRecorder::initRecord() { if (!openRecordStream(demoConfig.demoFile)) @@ -142,33 +145,72 @@ bool DemoRecorder::initRecord() if (demoConfig.cameraMode == 1) { - std::fprintf(stderr, "[FRONTIER] dice::hfe::DemoRecorder::initRecord camera arm reached " - "(DemoSpectatorCamera is unrecovered; ELF 0x814FE2C)\n"); - std::fflush(stderr); - std::abort(); + demoSpectatorCamera = new DemoSpectatorCamera(this); // operator new(0xA4) + if (!recordCameraToStream(demoConfig.cameraFile)) + return false; + runDemoCameraConfig("Settings/demo-recordcam.con"); } return true; } +// initPlayback - ELF 0x8150140, 1429 B. +// Always builds the spectator camera, then opens the packet stream. Camera mode 0 plays the +// demo with the free/follow camera; 1 records that camera to cameraFile while playing +// (demo-recordcam.con); 2 plays a recorded camera track (demo-playcam.con). Line 192 reports +// any other mode, as a DEBUGTYPE_6 abort. bool DemoRecorder::initPlayback() { - std::fprintf(stderr, "[FRONTIER] dice::hfe::DemoRecorder::initPlayback reached\n"); - std::fflush(stderr); - std::abort(); + demoSpectatorCamera = new DemoSpectatorCamera(this); // operator new(0xA4) + if (!openPlaybackStream(demoConfig.demoFile)) + return false; + + switch (demoConfig.cameraMode) + { + case 0: + return true; + case 1: + if (!recordCameraToStream(demoConfig.cameraFile)) + return false; + runDemoCameraConfig("Settings/demo-recordcam.con"); + return true; + case 2: + if (!playCameraFromStream(demoConfig.cameraFile)) + return false; + runDemoCameraConfig("Settings/demo-playcam.con"); + return true; + default: + Debug(DEBUGTYPE_6, "Game/DemoRecorder/DemoRecorder.cpp", 192, "") + << "Invalid camera mode: " << static_cast(demoConfig.cameraMode); + return false; + } } +// initRender - ELF 0x81506E0, 849 B / PE 0x54BE60. Movie render (demo mode 2): the demo plays +// through a recorded camera track; renderType 1 waits for the initial-state packet +// (handleSpecialPacket arms 2) and startRenderMovie turns it into 3, rendering to file. bool DemoRecorder::initRender() { - std::fprintf(stderr, "[FRONTIER] dice::hfe::DemoRecorder::initRender reached\n"); - std::fflush(stderr); - std::abort(); + demoSpectatorCamera = new DemoSpectatorCamera(this); // operator new(0xA4) + renderType = 1; + if (!openPlaybackStream(demoConfig.demoFile)) + return false; + if (!playCameraFromStream(demoConfig.cameraFile)) + return false; + runDemoCameraConfig("Settings/demo-playcam.con"); + return true; } +// initRenderSound - ELF 0x8150A40, 833 B / PE 0x54C000. Sound render (demo mode 3): as initRender +// without the movie state; as shipped it runs the record-camera config. bool DemoRecorder::initRenderSound() { - std::fprintf(stderr, "[FRONTIER] dice::hfe::DemoRecorder::initRenderSound reached\n"); - std::fflush(stderr); - std::abort(); + demoSpectatorCamera = new DemoSpectatorCamera(this); // operator new(0xA4) + if (!openPlaybackStream(demoConfig.demoFile)) + return false; + if (!playCameraFromStream(demoConfig.cameraFile)) + return false; + runDemoCameraConfig("Settings/demo-recordcam.con"); + return true; } // openRecordStream - ELF 0x8151160, 271 B / PE 0x4CAE10, 249 B. @@ -194,6 +236,185 @@ bool DemoRecorder::openRecordStream(const std::string& path) return true; } +// openPlaybackStream - ELF 0x8151270, 189 B. +// Refuses to reopen. The 0x40000-byte read buffer is allocated once and kept across restarts. +// A file whose header does not read closes again. The camera is told it plays a demo (not a +// camera track) with no camera stream yet. No null test on the camera: initPlayback made it. +bool DemoRecorder::openPlaybackStream(const std::string& path) +{ + if (zStreamFile) + return false; + if (!bufferData) + { + bufferData = new unsigned char[bufferCapacity]; + if (!bufferData) + return false; + } + zStreamFile = openCompressedDemoFile(path, false, false); + if (!zStreamFile) + return false; + + isOpenForRecordFlag = false; + if (!demoHeader->readFrom(zStreamFile)) + { + close(); + return false; + } + demoSpectatorCamera->setPlaybackMode(false); + demoSpectatorCamera->setPlaybackStream(0); + return true; +} + +// recordCameraToStream - ELF 0x8151330, 360 B. +// The camera track is written through the same compressed-file wrapper, refusing an existing +// file (the open's secondFlag); line 355 reports the failure. +bool DemoRecorder::recordCameraToStream(const std::string& path) +{ + cameraStreamFile = openCompressedDemoFile(path, true, false); + if (!cameraStreamFile) + { + Debug(DEBUGTYPE_6, "Game/DemoRecorder/DemoRecorder.cpp", 355, "") + << "Failed to open camera file " << path << " for writing. It probably exist already."; + return false; + } + byte56 = true; + cameraSuppressed = false; + demoSpectatorCamera->setPlaybackStream(0); + demoSpectatorCamera->setRecordStream(cameraStreamFile); + return true; +} + +// playCameraFromStream - ELF 0x81514A0, 106 B. +bool DemoRecorder::playCameraFromStream(const std::string& path) +{ + cameraStreamFile = openCompressedDemoFile(path, false, false); + if (!cameraStreamFile) + return false; + byte56 = false; + cameraSuppressed = true; + demoSpectatorCamera->setPlaybackMode(true); + demoSpectatorCamera->setPlaybackStream(cameraStreamFile); + return true; +} + +// readData - ELF 0x81515C0, 132 B / PE 0x54C3B0. +// One packet for the given tick. When the packet stream runs dry and the config ties the camera +// to it (DemoConfig +0x2C, syncCameraAndDemo), the camera track is dropped as well. +bool DemoRecorder::readData(int tick, io::BitStream* stream) +{ + const bool read = internalReadData(tick, stream); + if (!read && cameraStreamFile && demoConfig.syncCameraAndDemo) + { + cameraStreamFile->release(); // vptr +0x08 + cameraStreamFile = 0; + if (demoSpectatorCamera) + { + demoSpectatorCamera->setRecordStream(0); + demoSpectatorCamera->setPlaybackStream(0); + } + } + return read; +} + +// internalReadData - ELF 0x8151650, 301 B. +// Frames are (tick, size, payload); tick -2 frames are special packets and are handled inline. +// The first data frame, or one more than 100 ticks ahead of the caller, resets the world tick to +// the frame's; a frame still in the future hands back an empty packet. A short payload read ends +// the stream. A tick of -1 is never compared and plays at once. +bool DemoRecorder::internalReadData(int tick, io::BitStream* stream) +{ + if (!zStreamFile || endOfStream) + return false; + + if (!frameHeaderRead) + { + for (;;) + { + if (!readNextFrameHeader()) + { + endOfStream = true; + return false; + } + if (frameTick != -2) + break; + handleSpecialPacket(static_cast(frameSize)); + } + } + + if (frameTick != -1) + { + if (!tickResynced || frameTick - tick > 100) + { + WorldPref::resetTickCount(static_cast(frameTick)); + tick = WorldPref::getTickCount(); + tickResynced = true; + } + if (frameTick > tick) + { + stream->setBuffer(bufferData, 0); + stream->resetPositions(); + stream->setReadMode(); + return true; + } + } + + const unsigned int got = zStreamFile->read(bufferData, frameSize); // vptr +0x10 + if (got != frameSize) + { + endOfStream = true; + return false; + } + stream->setBuffer(bufferData, got); + stream->resetPositions(); + stream->setReadMode(); + frameHeaderRead = false; + return true; +} + +// readNextFrameHeader - ELF 0x81519A0, 140 B. +// A frame larger than the read buffer is refused (and left unread); otherwise the header counts +// as read while the stream still has bytes. +bool DemoRecorder::readNextFrameHeader() +{ + if (!zStreamFile->getAvailableBytes()) // vptr +0x1C + return false; + zStreamFile->read(&frameTick, 4); + zStreamFile->read(&frameSize, 4); + if (frameSize > bufferCapacity) + { + frameHeaderRead = false; + return false; + } + frameHeaderRead = zStreamFile->getAvailableBytes() != 0; + return frameHeaderRead; +} + +// handleSpecialPacket - ELF 0x8151A30, 335 B. +// The initial-state marker arms a pending movie render (1 -> 2); line 563 reports anything else. +void DemoRecorder::handleSpecialPacket(DemoRecorderSpecialPacket packet) +{ + if (packet == DemoRecorderSpecialPacket_InitialState) + { + if (renderType == 1) + renderType = 2; + return; + } + Debug(DEBUGTYPE_6, "Game/DemoRecorder/DemoRecorder.cpp", 563, "") + << "Invalid special packet " << static_cast(packet); +} + +// restartPlayback - ELF 0x8151D70, 64 B. +// Reopens from the start through init(). As shipped, init() allocates a fresh DemoHeader and a +// fresh camera without freeing the old ones; preserved. +void DemoRecorder::restartPlayback() +{ + if (!isOpenForPlayback()) + return; + close(); + init(demoConfig); + playbackPlaying = true; +} + // Writes nonempty packets; writeFakePacketData also permits empty packets. void DemoRecorder::writeData(int tick, io::BitStream* stream) { @@ -266,16 +487,13 @@ void DemoRecorder::close() cameraStreamFile->release(); cameraStreamFile = 0; } - byte74 = false; - byte5C = false; + endOfStream = false; + tickResynced = false; if (demoSpectatorCamera) { - // Unreachable on a dedicated server - the pointer is only ever set by initRecord's camera - // arm. setPlaybackStream(0) / setRecordStream(0) belong to the unrecovered camera class. - std::fprintf(stderr, "[FRONTIER] dice::hfe::DemoRecorder::close camera arm reached\n"); - std::fflush(stderr); - std::abort(); + demoSpectatorCamera->setPlaybackStream(0); + demoSpectatorCamera->setRecordStream(0); } } @@ -295,9 +513,12 @@ void DemoRecorder::stopCameraRecording() } +// ~DemoRecorder - ELF 0x8150EF0, 342 B: close, then the camera, the read buffer and the header. DemoRecorder::~DemoRecorder() { close(); + delete demoSpectatorCamera; + delete[] bufferData; delete demoHeader; } @@ -329,51 +550,82 @@ bool DemoRecorder::startRenderMovie() return true; } -// THE DemoSpectatorCamera forwarders - client playback. Each stops by name rather than invent a -// call into an unrecovered 0xA4-byte class. None is reachable from a recording dedicated server. +// The DemoSpectatorCamera forwarders - ELF 0x8151B90..0x8151E80, BF2.exe 0x54BBE0..0x54BD01. +// Each answers false / -1 without a camera, except demoVisualUpdate, which (as shipped) calls +// the camera unless a camera track plays. bool DemoRecorder::quit() const { - std::fprintf(stderr, "[FRONTIER] dice::hfe::DemoRecorder::quit reached\n"); - std::fflush(stderr); - std::abort(); + return demoSpectatorCamera ? demoSpectatorCamera->getEOF() : false; +} + +void DemoRecorder::updateTicks(int ticks) +{ + if (demoSpectatorCamera) + demoSpectatorCamera->updateTicks(ticks); +} + +// handlePlayerInput - ELF 0x8151C40: drains the queued inputs in order. +void DemoRecorder::handlePlayerInput(float deltaTime) +{ + while (!playerInputs.empty()) + { + internalHandlePlayerInput(playerInputs.front(), deltaTime); + playerInputs.pop_front(); + } +} + +void DemoRecorder::internalHandlePlayerInput(const io::PlayerInput& input, float deltaTime) +{ + if (demoSpectatorCamera && !byte54) + demoSpectatorCamera->handlePlayerInput(input, deltaTime); +} + +// addPlayerInput - ELF 0x8151BF0: inputs are only queued while a demo plays. +void DemoRecorder::addPlayerInput(const io::PlayerInput& input) +{ + if (isOpenForPlayback()) + playerInputs.push_back(input); +} + +// demoVisualUpdate - ELF 0x8151BB0 / PE 0x54BBE0. b is kept for getPlaybackMatrixAndFOV. +void DemoRecorder::demoVisualUpdate(float a, float b) +{ + if (!cameraSuppressed) + demoSpectatorCamera->demoVisualUpdate(a); + visualUpdateB = b; +} + +// getPlaybackMatrixAndFOV - ELF 0x8151D00 / PE 0x54BC20. +void DemoRecorder::getPlaybackMatrixAndFOV(Mat4* matrix, float* fov) +{ + if (demoSpectatorCamera) + demoSpectatorCamera->getPlaybackMatrixAndFOV(matrix, fov, visualUpdateB); } -void DemoRecorder::updateTicks(int) +bool DemoRecorder::nextCamera() // PE 0x54BC70 { - std::fprintf(stderr, "[FRONTIER] dice::hfe::DemoRecorder::updateTicks reached\n"); - std::fflush(stderr); - std::abort(); + return demoSpectatorCamera ? demoSpectatorCamera->nextCamera() : false; } -void DemoRecorder::handlePlayerInput(float) +bool DemoRecorder::nextPlayer() // PE 0x54BC90 { - std::fprintf(stderr, "[FRONTIER] dice::hfe::DemoRecorder::handlePlayerInput reached\n"); - std::fflush(stderr); - std::abort(); + return demoSpectatorCamera ? demoSpectatorCamera->nextPlayer() : false; } -void DemoRecorder::addPlayerInput(const io::PlayerInput&) +bool DemoRecorder::previousPlayer() // PE 0x54BCB0 { - std::fprintf(stderr, "[FRONTIER] dice::hfe::DemoRecorder::addPlayerInput reached\n"); - std::fflush(stderr); - std::abort(); + return demoSpectatorCamera ? demoSpectatorCamera->previousPlayer() : false; } -void DemoRecorder::demoVisualUpdate(float, float) +int DemoRecorder::getCurrentDemoPlayerId() // PE 0x54BCD0 { - std::fprintf(stderr, "[FRONTIER] dice::hfe::DemoRecorder::demoVisualUpdate reached\n"); - std::fflush(stderr); - std::abort(); + return demoSpectatorCamera ? demoSpectatorCamera->getCurrentDemoPlayerId() : -1; } -// Returns without a spectator camera. Otherwise stops at the unresolved camera -// transform call, which takes output, flag, and visual update time. -void DemoRecorder::getCameraTransformation(Mat4&, int) +bool DemoRecorder::getIsFreeFlying() // PE 0x54BCF0 { - std::fprintf(stderr, "[FRONTIER] dice::hfe::DemoRecorder::getCameraTransformation reached\n"); - std::fflush(stderr); - std::abort(); + return demoSpectatorCamera ? demoSpectatorCamera->getIsFreeFlying() : false; } } // namespace hfe diff --git a/Code/BF2/Game/DemoRecorder/DemoRecorder.h b/Code/BF2/Game/DemoRecorder/DemoRecorder.h index bbf434869..1499d7f3a 100644 --- a/Code/BF2/Game/DemoRecorder/DemoRecorder.h +++ b/Code/BF2/Game/DemoRecorder/DemoRecorder.h @@ -1,6 +1,6 @@ -// Demo recording and playback state. Playback/rendering and spectator-camera -// forwarders retain [FRONTIER] stops. This nonpolymorphic class contains STL members; -// its ELF size must not be imposed on MSVC or native-pointer builds. +// Demo recording, playback and movie/sound render state. This nonpolymorphic class contains STL +// members; its ELF size must not be imposed on MSVC or native-pointer builds. BF2.exe offsets are ELF + 0x78 from +0x4C +// (three MSVC strings in DemoConfig plus string44/48) and + 0x80 from +0x80 (MSVC list). #ifndef GAME_DEMORECORDER_DEMORECORDER_H // [INFERRED] guard style #define GAME_DEMORECORDER_DEMORECORDER_H @@ -20,9 +20,7 @@ namespace io { class BitStream; class IStream; } class DemoHeader; -// Unrecovered client spectator rig. Dedicated recording never constructs it; -// forwarders retain named [FRONTIER] stops when a live rig would be required. -class DemoSpectatorCamera; +class DemoSpectatorCamera; // DemoSpectatorCamera.h - the playback/record camera rig enum DemoRecorderSpecialPacket { @@ -44,9 +42,16 @@ class DemoRecorder // the four modes init() dispatches on void init(const DemoConfig& config); bool initRecord(); - bool initPlayback(); // / PE 0x4CB230 [FRONTIER] - bool initRender(); // [FRONTIER] - bool initRenderSound(); // [FRONTIER] + bool initPlayback(); + bool initRender(); + bool initRenderSound(); + + // the playback path + bool openPlaybackStream(const std::string& path); + bool recordCameraToStream(const std::string& path); + bool playCameraFromStream(const std::string& path); + bool readData(int tick, io::BitStream* stream); + void restartPlayback(); // the record path. ALL bool openRecordStream(const std::string& path); @@ -67,15 +72,18 @@ class DemoRecorder bool isRenderingToFile() const; bool startRenderMovie(); - // the DemoSpectatorCamera forwarders. Client playback; [FRONTIER] stops here. + // the DemoSpectatorCamera forwarders (client playback). Each is a no-op without a camera. bool quit() const; void updateTicks(int ticks); void handlePlayerInput(float deltaTime); void addPlayerInput(const io::PlayerInput& input); void demoVisualUpdate(float a, float b); - // Writes the demo camera/listener transform when a spectator rig exists. - // [INFERRED] name and parameter spellings. - void getCameraTransformation(Mat4& out, int flag); // > camera 0x62AC40 + void getPlaybackMatrixAndFOV(Mat4* matrix, float* fov); + bool nextCamera(); + bool nextPlayer(); + bool previousPlayer(); + int getCurrentDemoPlayerId(); + bool getIsFreeFlying(); // the 0x88 record. Names without a comment are [INFERRED] from their only writer. // demo.cpp reads renderMode, demoConfig and byte84 by these exact names. @@ -85,19 +93,19 @@ class DemoRecorder /* +0x48 */ std::string string48; // [UNRESOLVED] ctor leaves it empty /* +0x4C */ io::IStream* zStreamFile; // Packet stream: a ZStream over a file. /* +0x50 */ io::IStream* cameraStreamFile; // the separate .bf2cam track - /* +0x54 */ bool byte54; // [UNRESOLVED] init() zeroes it + /* +0x54 */ bool byte54; // [UNRESOLVED] init() zeroes it; set, it mutes camera input /* +0x55 */ bool isOpenForRecordFlag; // set by openRecordStream, tested by both is*() - /* +0x56 */ bool byte56; // [UNRESOLVED] init() zeroes it - /* +0x57 */ bool cameraSuppressed; // gates demoVisualUpdate + /* +0x56 */ bool byte56; // [UNRESOLVED] init() zeroes it; recordCameraToStream sets it + /* +0x57 */ bool cameraSuppressed; // gates demoVisualUpdate; set while a camera track plays /* +0x58 */ DemoHeader* demoHeader; // init() allocates one (operator new(0x14)) - /* +0x5C */ bool byte5C; // [UNRESOLVED]; close() clears it - /* +0x5D */ bool byte5D; // [UNRESOLVED] init() zeroes it - /* +0x60 */ int dword60; // [UNRESOLVED] init() zeroes it - /* +0x64 */ int dword64; // [UNRESOLVED] init() zeroes it + /* +0x5C */ bool tickResynced; // [INFERRED] the first frame reset the world tick + /* +0x5D */ bool frameHeaderRead; // [INFERRED] frameTick/frameSize hold an unread frame + /* +0x60 */ int frameTick; // [INFERRED] the pending frame's tick; -2 special + /* +0x64 */ unsigned int frameSize; // [INFERRED] its byte count (special: the packet id) /* +0x68 */ unsigned int bufferCapacity; // init() = 0x40000 /* +0x6C */ unsigned char* bufferData; // init() zeroes it; the playback read buffer /* +0x70 */ DemoSpectatorCamera* demoSpectatorCamera; // null unless cameraMode == 1 - /* +0x74 */ bool byte74; // [UNRESOLVED]; close() clears it + /* +0x74 */ bool endOfStream; // [INFERRED] a short read ended the packet stream /* +0x78 */ float visualUpdateB; // init() zeroes it /* +0x7C */ std::list playerInputs; // drained by handlePlayerInput /* +0x80 */ int renderType; // 0/1/2/3; startRenderMovie moves 2 -> 3 @@ -105,6 +113,11 @@ class DemoRecorder /* +0x85 */ bool playbackPlaying; // [IDB name] private: + bool internalReadData(int tick, io::BitStream* stream); + bool readNextFrameHeader(); + void handleSpecialPacket(DemoRecorderSpecialPacket packet); + void internalHandlePlayerInput(const io::PlayerInput& input, float deltaTime); + DemoRecorder(const DemoRecorder&); // not in the binary; not generated DemoRecorder& operator=(const DemoRecorder&); }; diff --git a/Code/BF2/Game/DemoRecorder/DemoSpectatorCamera.cpp b/Code/BF2/Game/DemoRecorder/DemoSpectatorCamera.cpp new file mode 100644 index 000000000..e36fdfc9b --- /dev/null +++ b/Code/BF2/Game/DemoRecorder/DemoSpectatorCamera.cpp @@ -0,0 +1,774 @@ +// Demo spectator camera: records the local view into a .bf2cam track and replays it. +// Path attested by the anonymous-namespace symbol +// _GLOBAL__N_Game_DemoRecorder_DemoSpectatorCamera.cpp...g_freeCamSpeed (ELF 0x8154610). +// Recovered from the symbolized dedicated ELF; every body was read there. The client BF2.exe twins +// (0x6298C0..0x62AEFF) match the ELF bodies; none of the ELF bodies is compiled down. +// The static string array dice::hfe::defaultSquadNames this TU's initializer also builds (ELF +// 0x8154163..0x8154404) comes from an included squad header, not from this file; it is not used here. + +#include "DemoSpectatorCamera.h" + +#include "DemoRecorder.h" // isOpenForPlayback, tickResynced, demoConfig, stopCameraRecording +#include "../IGame.h" // game->setSimulationRate (+0xE4), queryInterface +#include "../SingletonServer.h" // m_iNametagManager->setSpectatedPlayer (+0x60) +#include "../Utility/Vars.h" // the demo-cam-* console variables +#include "../Objects/IObject.h" +#include "../Objects/IObjectTemplate.h" // createObject (+0x54) +#include "../Objects/IPlayer.h" // getVehicle +0x48, getId +0x54, getIsAlive +0x6C +#include "../Objects/ICameraObject.h" // getTransformation (+0x10) +#include "../Objects/Base/FreeCamera.h" // the free camera's own table (+0x180 getTransformation) +#include "../../Core/Ids.h" // IID_IGameServer, CID_FreeCameraTemplate, IID_IPlayerControlObject +#include "../../Core/System.h" // WorldPref::getTickCount +#include "../../IO/Console/Console.h" // mainConsole->executeLine, Console::ignoredString_ +#include "../../IO/Stream/IStream.h" // read +0x10, write +0x14, getAvailableBytes +0x1C +#include "../../Scene/Object/PlayerManager.h" // getPlayerFromId +0x20, getLocalHumanPlayer +0x30 +#include "../../Scene/Object/ObjectTypes/Base/ObjectTemplateManager.h" // getTemplate(name, cid) +0x28 +#include "../../Scene/Object/ObjectTypes/Game/IPlayerControlObject.h" // getActiveCamera +0x44 + +#include // fmodf +#include // memset +#include + +namespace dice { +namespace hfe { + +namespace { + +// The TU's console variables, registered by the static initializer (ELF 0x815442D..0x8154532) +// in this order. Each holds the live storage address Vars hands back. +float* g_freeCamSpeed = Vars::getFloat("demo-fspeed", 100.0f); // ds:0x8AACC80 +int* g_useOffset = Vars::getInt("demo-cam-offset", 1); // ds:0x8AACC84 +float* g_offsetSpeed = Vars::getFloat("demo-cam-offset-speed", 1.0f); // ds:0x8AACC88 +float* g_offsetMinDistance = Vars::getFloat("demo-cam-offset-min", 0.2f); // ds:0x8AACC8C +float* g_offsetSlowFactor = Vars::getFloat("demo-cam-offset-slow", 0.8f); // ds:0x8AACC90 +float* g_mouseWheelFactor = Vars::getFloat("demo-cam-mouse-wheel-scale", 0.85f); // ds:0x8AACC94 +int* g_360capture = Vars::getInt("demo-cam-360-capture", 0); // ds:0x8AACC98 +float* g_360captureAngle = Vars::getFloat("demo-cam-360-capture-move", 0.0f); // ds:0x8AACC9C + +// ds:0x8893E20 (.rodata): the simulation rates PIWeaponSelect1..9 pick. +const int g_slomoRatios[9] = { 0, 100, 5, 25, 50, 75, 150, 300, 1000 }; + +// [CHOSEN, not recovered] spelling of the inline the ELF expands at every analog read: the value +// when the input's mapping bit is set, otherwise 0.0f (fldz). The retail inline is not in the tree. +inline float mappedInput(const io::PlayerInput& input, io::PlayerInputMap index) +{ + if ((input.mappingFlags >> (static_cast(index) & 0x3Fu)) & 1ULL) + return input.inputs[index]; + return 0.0f; +} + +// ELF 0x8154690 (W) float lerp and 0x8154630 (W) Vec3 lerp / PE 0x629DC0. +// Both compute (1 - t) * a + t * b. They are instances of one anonymous-namespace template in the +// ELF; the tree's Vec3 has no arithmetic operators, so the two instances are spelled as explicit +// specializations [CHOSEN, not recovered]. +template T lerp(T a, T b, float t); + +template <> float lerp(float a, float b, float t) +{ + return (1.0f - t) * a + t * b; +} + +template <> Vec3 lerp(Vec3 a, Vec3 b, float t) +{ + const float s = 1.0f - t; + Vec3 result = { s * a.x + t * b.x, s * a.y + t * b.y, s * a.z + t * b.z }; + return result; +} + +// [CHOSEN, not recovered] spelling of the identity fill the constructors and ensureCamerasCreated +// expand: sixteen zero stores, then 1.0f on the diagonal (the tree's Mat4 has no such inline). +inline void setIdentity(Mat4& m) +{ + for (int i = 0; i < 16; ++i) + m.m[i] = 0.0f; + m.m[15] = 1.0f; + m.m[10] = 1.0f; + m.m[5] = 1.0f; + m.m[0] = 1.0f; +} + +} // namespace + +// construction + +// ELF 0x8151F50 (C1) / 0x81520B0 (C2), 343 B each. +DemoSpectatorCamera::DemoSpectatorCamera(DemoRecorder* owner) +{ + m_owner = owner; + m_keyLatches = new KeyLatches; // operator new(0xC) + m_currentPlayerId = -1; + m_mode = Mode_FreeFlying; + m_playbackMode = false; + m_eof = false; + setIdentity(m_matrix); + m_yaw = 0.0f; + m_pitch = 0.0f; + m_numUpdates = 0; + m_maxUpdates = 4; + m_updates = new CameraUpdate[4]; // operator new[](0xE0), no cookie + m_playbackStream = 0; + m_recordStream = 0; + m_double74 = -1.0; + m_spareUpdate = new CameraUpdate; // operator new(0x38) + m_followDistance = 2.0f; + m_ticks = 0; + m_tickOffset = 0; + m_float84 = 0.0f; + m_float88 = 0.0f; + m_heightOffset = 0.0f; + m_inputPrimed = false; + m_tickOffsetSet = false; + m_visualTime = 0.0f; + std::memset(m_keyLatches, 0, sizeof(KeyLatches)); // rep stosd, 3 dwords +} + +// ELF 0x8152210 / 0x81522A0, 138 B. The free camera is destroyed (IObject::destroy(true), slot +// +0x34) before the member WeakPtr drops its control block. +DemoSpectatorCamera::~DemoSpectatorCamera() +{ + delete m_spareUpdate; + delete[] m_updates; + delete m_keyLatches; + if (m_freeCamera.get()) + m_freeCamera.get()->destroy(true); +} + +// trivial accessors + +// ELF 0x8152330 +void DemoSpectatorCamera::setPlaybackMode(bool playback) +{ + m_playbackMode = playback; +} + +// ELF 0x8152340. A new stream clears the end-of-track flag. +void DemoSpectatorCamera::setPlaybackStream(io::IStream* stream) +{ + m_eof = false; + m_playbackStream = stream; +} + +// ELF 0x8152360 / PE 0x6298E0 +bool DemoSpectatorCamera::getEOF() const +{ + return m_playbackMode && m_eof; +} + +// ELF 0x8152380 +void DemoSpectatorCamera::setRecordStream(io::IStream* stream) +{ + m_recordStream = stream; +} + +// ELF 0x8152390. A stale id is reset to -1 when the player is gone. +world::IPlayer* DemoSpectatorCamera::getCurrentPlayer() +{ + if (m_currentPlayerId < 0) + return 0; + world::IPlayer* player = world::playerManager->getPlayerFromId(m_currentPlayerId); + if (!player) + m_currentPlayerId = -1; + return player; +} + +// ELF 0x8152790 / PE 0x68E7B0 +int DemoSpectatorCamera::getCurrentDemoPlayerId() +{ + return m_currentPlayerId; +} + +// ELF 0x81531A0 +world::FreeCamera* DemoSpectatorCamera::getFreeCamera() +{ + return static_cast(m_freeCamera.get()); +} + +// ELF 0x8153210 / PE 0x629990 +bool DemoSpectatorCamera::getIsFreeFlying() +{ + return m_mode == Mode_FreeFlying; +} + +// ELF 0x81540F0 +DemoSpectatorCamera::Mode DemoSpectatorCamera::intToMode(int value) +{ + switch (value) + { + case 0: return Mode_FreeFlying; + case 1: return Mode_FollowPlayer; + default: return Mode_FreeFlying; + } +} + +// input + +// ELF 0x81523D0. Edge detector: true only on the frame a mapped input crosses 0.5. An id above 63 +// has no mapping bit and reads as released. +bool DemoSpectatorCamera::checkSingleKey(const io::PlayerInput& input, io::PlayerInputMap key, + bool& latch) +{ + bool pressed = false; + if (static_cast(key) <= 63 + && ((input.mappingFlags >> (static_cast(key) & 0x3Fu)) & 1ULL)) + pressed = input.inputs[key] > 0.5f; + + if (pressed) + { + if (!latch) + { + latch = true; + return true; + } + return false; + } + latch = false; + return false; +} + +// ELF 0x8152490 / PE 0x62ACF0. The first call only primes (and, while recording live, pauses the +// simulation); later calls dispatch the demo keys, then feed the active camera. +void DemoSpectatorCamera::handlePlayerInput(const io::PlayerInput& input, float deltaTime) +{ + if (!ensureCamerasCreated()) + return; + + if (!m_inputPrimed) + { + if (!m_playbackMode && m_recordStream) + game->setSimulationRate(0); + m_inputPrimed = true; + return; + } + + if (checkSingleKey(input, io::PIAltFire, m_keyLatches->latched[0])) + nextCamera(); + + if (checkSingleKey(input, io::PIAction, m_keyLatches->latched[1])) + { + if (mappedInput(input, io::PISprint) == 0.0f) + nextPlayer(); + else + previousPlayer(); + } + + if (checkSingleKey(input, io::PIReload, m_keyLatches->latched[2])) + { + if (m_recordStream) + m_owner->stopCameraRecording(); + io::mainConsole->executeLine(std::string("renderer.stopRenderMovie\n"), + io::Console::ignoredString_, false, false, false, false, false); + } + + for (int i = 0; i <= 8; ++i) + { + if (checkSingleKey(input, static_cast(io::PIWeaponSelect1 + i), + m_keyLatches->latched[3 + i])) + game->setSimulationRate(g_slomoRatios[i]); + } + + if (m_mode == Mode_FreeFlying && getFreeCamera()) + getFreeCamera()->handlePlayerInput(0, input, deltaTime, 0); // IObject slot +0x100 + else + handleFollowInput(input, deltaTime); +} + +// ELF 0x81526F0 / PE 0x62ABF0 +bool DemoSpectatorCamera::nextCamera() +{ + nextMode(); + return true; +} + +// ELF 0x8152710 / PE 0x62AC00 +bool DemoSpectatorCamera::nextPlayer() +{ + setMode(Mode_FollowPlayer); + updateSpectateTarget(1); + return true; +} + +// ELF 0x8152750 / PE 0x62AC20 +bool DemoSpectatorCamera::previousPlayer() +{ + setMode(Mode_FollowPlayer); + updateSpectateTarget(-1); + return true; +} + +// ELF 0x81527A0 / PE 0x62A730. Walks the 256 player ids from the current one in the given +// direction and follows the first live player that has a vehicle; falls back to free flight. +void DemoSpectatorCamera::updateSpectateTarget(int direction) +{ + // ELF 0x8154540 candidate_t::candidate_t(int, int). The step is clamped to -1/+1; a zero step + // becomes +1 without advancing, so direction 0 re-tests the current id first. + struct candidate_t + { + int step; // +0x00 + int id; // +0x04 + + candidate_t(int dir, int start) + : step(dir), id(start) + { + if (step < -1) + step = -1; + if (step > 1) + step = 1; + if (step != 0) + advance(); + else + step = 1; + } + + // [INFERRED] inline: the same signed (id + step + 256) % 256 the loop expands. + void advance() + { + id = (id + step + 256) % 256; + } + }; + + candidate_t candidate(direction, getCurrentPlayer() ? m_currentPlayerId : 0); + for (int i = 0; i < 256; ++i) + { + world::IPlayer* player = world::playerManager->getPlayerFromId(candidate.id); + if (player && player->getIsAlive() && player->getVehicle()) + { + m_currentPlayerId = candidate.id; + break; + } + candidate.advance(); + } + + if (!getCurrentPlayer()) + setMode(Mode_FreeFlying); +} + +// ELF 0x8153290 / PE 0x62A300. Follow-mode controls: mouse look turns, throttle zooms (sprint +// slows it), lie/crouch move the look-at height, the next/prev item keys scale the distance. +void DemoSpectatorCamera::handleFollowInput(const io::PlayerInput& input, float deltaTime) +{ + if (*g_360capture) + { + // 360 capture: one externally driven yaw step per request, then the request is consumed. + if (*g_360captureAngle != 0.0f) + { + m_yaw += *g_360captureAngle; + Vars::set(std::string("demo-cam-360-capture-move"), std::string("0")); + } + return; + } + + const float lookY = mappedInput(input, io::PIMouseLookY); + const float lookX = mappedInput(input, io::PIMouseLookX); + const float throttle = mappedInput(input, io::PIThrottle); + const float lie = mappedInput(input, io::PILie); + const float crouch = mappedInput(input, io::PICrouch); + const float sprint = mappedInput(input, io::PISprint); + + m_followDistance += -throttle * (1.0f - sprint * *g_offsetSlowFactor) * *g_offsetSpeed * deltaTime; + m_pitch += lookY * deltaTime * *g_freeCamSpeed; + m_yaw += lookX * deltaTime * *g_freeCamSpeed; + m_heightOffset += (lie - crouch) * 0.5f * *g_offsetSpeed * deltaTime; + + if (m_heightOffset < -10.0f) + m_heightOffset = -10.0f; + if (m_heightOffset > 10.0f) + m_heightOffset = 10.0f; + + if (m_pitch < -89.0f) + m_pitch = -89.0f; + else if (m_pitch > 89.0f) + m_pitch = 89.0f; + + if (mappedInput(input, io::PINextItem) != 0.0f) + m_followDistance = *g_mouseWheelFactor * m_followDistance; + else if (mappedInput(input, io::PIPrevItem) != 0.0f) + m_followDistance = m_followDistance / *g_mouseWheelFactor; + + const float minDistance = *g_offsetMinDistance; + if (m_followDistance < minDistance) + m_followDistance = minDistance; + else if (m_followDistance > 1000.0f) + m_followDistance = 1000.0f; +} + +// modes and the free camera + +// ELF 0x8152F50 / PE 0x62A830. Creates the MultiPlayerFreeCamera object on first use and parks it +// 75 m up at the origin. Returns whether a free camera exists. +bool DemoSpectatorCamera::ensureCamerasCreated() +{ + if (!getFreeCamera()) + { + world::IObjectTemplate* objectTemplate = world::objectTemplateManager->getTemplate( + std::string("MultiPlayerFreeCamera"), world::CID_FreeCameraTemplate); + if (objectTemplate) + { + m_freeCamera = objectTemplate->createObject()->getWeakPtr(); + if (getFreeCamera()) + { + getFreeCamera()->updateFlags(0, 0x3800); // slot +0x60 + Mat4 transform; + setIdentity(transform); + transform.m[13] = 75.0f; + getFreeCamera()->setAbsoluteTransformation(transform); // slot +0x8C + } + } + } + return getFreeCamera() != 0; +} + +// ELF 0x81531C0. Entering free flight hands the current view to the free camera. +void DemoSpectatorCamera::setMode(Mode mode) +{ + m_mode = mode; + if (mode == Mode_FreeFlying) + { + if (world::FreeCamera* freeCamera = getFreeCamera()) + freeCamera->setAbsoluteTransformation(m_matrix); + } +} + +// ELF 0x8153230 / PE 0x62AA10 (GameClient also calls the PE copy directly). +void DemoSpectatorCamera::nextMode() +{ + if (m_mode == Mode_FreeFlying) + { + setMode(Mode_FollowPlayer); + updateSpectateTarget(0); + if (getCurrentPlayer()) + return; + } + setMode(Mode_FreeFlying); +} + +// per-frame + +// ELF 0x8153100 / PE 0x62A950. Only the live view (not a playing track) steps the free camera. +void DemoSpectatorCamera::demoVisualUpdate(float time) +{ + m_visualTime = time; + if (m_playbackMode) + return; + if (!ensureCamerasCreated()) + return; + + if (m_mode == Mode_FreeFlying && getFreeCamera()) + { + getFreeCamera()->handleFrameUpdate(time); // slot +0xAC + getFreeCamera()->handleUpdate(time, 0); // slot +0xB0 + } + + INametagManager* nametags = SingletonServer::m_iNametagManager; + if (nametags) + nametags->setSpectatedPlayer(getCurrentPlayer()); +} + +// ELF 0x8152890 / PE 0x62AC40. The FOV out-parameter is always 1.0f. +void DemoSpectatorCamera::getPlaybackMatrixAndFOV(Mat4* matrix, float* fov, float time) +{ + if (fov) + *fov = 1.0f; + if (!matrix) + return; + + if (m_playbackMode) + calcCameraFromUpdates(time); + else if (!getFreeCamera() || m_mode != Mode_FreeFlying) + updateLookAtMatrix(); + else + m_matrix = getFreeCamera()->getTransformation(m_visualTime); // FreeCamera +0x180 + + *matrix = m_matrix; +} + +// ELF 0x81535B0 / PE 0x629B10. Orbit the followed player's root vehicle: yaw/pitch rotate an +// offset of length followDistance (or the vehicle's visual radius when demo-cam-offset is 0) +// around the vehicle position raised by heightOffset. +void DemoSpectatorCamera::updateLookAtMatrix() +{ + world::IPlayer* player = getCurrentPlayer(); + if (!player) + return; + world::IObject* vehicle = player->getVehicle(); + if (!vehicle) + return; + + world::IObject* root = world::getRootParent(vehicle); + const float radius = root->getVisualBoundingRadius(); // slot +0x94 + const float yaw = std::fmod(m_yaw, 360.0f); + const float pitch = std::fmod(m_pitch, 360.0f); + + const Vec3& rootPosition = root->getAbsolutePosition(); // slot +0x6C + const Vec3 target = { rootPosition.x, rootPosition.y + m_heightOffset, rootPosition.z }; + + Vec3 offset; + offset.x = *g_useOffset ? m_followDistance : radius; + offset.y = 0.0f; + offset.z = 0.0f; + + Mat4 rotation = Mat4::getIdentity(); + const Vec3 angles = { yaw, 0.0f, pitch }; + setRotationZXY(rotation, -angles.z, -angles.y, -angles.x); + + const float* m = rotation.m; + const Vec3 eye = { + offset.x * m[0] + offset.y * m[4] + offset.z * m[8] + m[12] + target.x, + offset.x * m[1] + offset.y * m[5] + offset.z * m[9] + m[13] + target.y, + offset.x * m[2] + offset.y * m[6] + offset.z * m[10] + m[14] + target.z + }; + const Vec3 up = { 0.0f, 1.0f, 0.0f }; + calcLookAtMatrix(m_matrix, eye, target, up); +} + +// recording + +// ELF 0x8152A10 / PE 0x62A000. While recording (or once playback has resynced the tick) samples +// the camera, smooths it over the last four samples and writes one CameraUpdate per elapsed tick. +// A listen server records the local player's vehicle camera instead of the spectator view. +void DemoSpectatorCamera::updateTicks(int ticks) +{ + if (m_owner->isOpenForPlayback() && !m_owner->tickResynced) + return; + + m_ticks = ticks; + if (ticks == 0 || !m_recordStream) + return; + + CameraUpdate update; + update.tick = static_cast(WorldPref::getTickCount()); + + world::IPlayer* localPlayer = world::playerManager->getLocalHumanPlayer(); + if (localPlayer && game->queryInterface(IID_IGameServer)) + { + update.mode = Mode_FreeFlying; + world::IObject* vehicle = localPlayer->getVehicle(); + if (!vehicle) + { + const Vec3 parked = { 0.0f, 100.0f, 0.0f }; + update.position = parked; + update.rotation.fromMat(Mat4::getIdentity()); + } + else + { + world::IPlayerControlObject* pco = static_cast( + vehicle->queryInterface(world::IID_IPlayerControlObject)); + if (pco) + { + world::ICameraObject* camera = pco->getActiveCamera(); + if (camera) + { + const Mat4 transform = camera->getTransformation(m_visualTime); + update.position.x = transform.m[12]; + update.position.y = transform.m[13]; + update.position.z = transform.m[14]; + update.rotation.fromMat(transform); + } + } + } + } + else + { + update.playerId = getCurrentPlayer() ? getCurrentPlayer()->getId() : -1; + update.yaw = m_yaw; + update.pitch = m_pitch; + update.followDistance = m_followDistance; + update.heightOffset = m_heightOffset; + update.mode = m_mode; + update.position.x = m_matrix.m[12]; + update.position.y = m_matrix.m[13]; + update.position.z = m_matrix.m[14]; + update.rotation.fromMat(m_matrix); + } + + // shift the history and append the new sample + for (int i = 1; i < m_maxUpdates; ++i) + m_updates[i - 1] = m_updates[i]; + m_updates[m_maxUpdates - 1] = update; + + // the written position is the history's mean... + Vec3 sum = { 0.0f, 0.0f, 0.0f }; + for (int i = 0; i < m_maxUpdates; ++i) + { + sum.x += m_updates[i].position.x; + sum.y += m_updates[i].position.y; + sum.z += m_updates[i].position.z; + } + const float scale = 1.0f / static_cast(m_maxUpdates); + update.position.x = sum.x * scale; + update.position.y = sum.y * scale; + update.position.z = sum.z * scale; + + // ...and its rotation a chain of half-way slerps over entries 0..3 (fixed, as shipped). + Quat first = { 0.0f, 0.0f, 0.0f, 1.0f }; + Quat second = { 0.0f, 0.0f, 0.0f, 1.0f }; + first.slerp(m_updates[0].rotation, m_updates[1].rotation, 0.5f); + second.slerp(first, m_updates[2].rotation, 0.5f); + update.rotation.slerp(second, m_updates[3].rotation, 0.5f); + + for (int i = 0; i < ticks; ++i) + { + update.writeToStream(m_recordStream); + ++update.tick; + } +} + +// playback + +// ELF 0x8153A40 / PE 0x62A570. Drops samples older than the current tick, then refills the +// four-entry window from the track. Without demoConfig.syncCameraAndDemo the first sample read +// fixes a tick offset that maps track ticks onto the current world tick. Returns whether the +// window is full; an empty or exhausted stream sets the end-of-track flag. +bool DemoSpectatorCamera::readCameraUpdates() +{ + if (!m_playbackStream || !m_playbackStream->getAvailableBytes()) + { + m_eof = true; + return false; + } + + const unsigned int now = static_cast(WorldPref::getTickCount()); + + for (int i = 0; m_numUpdates > 0 && i < m_maxUpdates; ++i) + { + if (m_updates[0].tick >= now) + break; + for (int j = 0; j < m_numUpdates - 1; ++j) + m_updates[j] = m_updates[j + 1]; + --m_numUpdates; + } + + const int toRead = m_maxUpdates - m_numUpdates; + if (toRead == 0) + return true; + + for (int k = 0; k < toRead; ++k) + { + const int index = m_maxUpdates - toRead + k; + if (!m_playbackStream->getAvailableBytes()) + break; + + m_updates[index].readFromStream(m_playbackStream); + if (!m_tickOffsetSet && !m_owner->demoConfig.syncCameraAndDemo) + m_tickOffset = static_cast(now - m_updates[index].tick); + m_tickOffsetSet = true; + + m_updates[index].tick += m_tickOffset; + if (m_updates[index].tick < now) + --k; // stale: read the next sample into this slot + else + ++m_numUpdates; + } + return m_numUpdates == m_maxUpdates; +} + +// ELF 0x8153880 / PE 0x62AAD0. Interpolates between window entries 0 and 1: free-mode samples +// carry a full transform, follow-mode samples the orbit parameters and the followed player. +void DemoSpectatorCamera::calcCameraFromUpdates(float time) +{ + if (!readCameraUpdates()) + return; + + const CameraUpdate* from = &m_updates[0]; + const CameraUpdate* to = &m_updates[1]; + + if (from->mode == Mode_FreeFlying) + { + Quat rotation = { 0.0f, 0.0f, 0.0f, 1.0f }; + rotation.slerp(from->rotation, to->rotation, time); + rotation.toMat(m_matrix); + const Vec3 position = lerp(from->position, to->position, time); + m_matrix.m[12] = position.x; + m_matrix.m[13] = position.y; + m_matrix.m[14] = position.z; + } + else + { + m_yaw = lerp(from->yaw, to->yaw, time); + m_pitch = lerp(from->pitch, to->pitch, time); + m_followDistance = lerp(from->followDistance, to->followDistance, time); + m_heightOffset = lerp(from->heightOffset, to->heightOffset, time); + m_currentPlayerId = from->playerId; + updateLookAtMatrix(); + } +} + +// CameraUpdate + +// ELF 0x8153C80 / 0x8153CC0. +0x0C..+0x18 stay uninitialized, as shipped. +CameraUpdate::CameraUpdate() +{ + mode = DemoSpectatorCamera::Mode_FreeFlying; + tick = 0; + playerId = -1; + rotation.x = 0.0f; + rotation.y = 0.0f; + rotation.z = 0.0f; + rotation.w = 1.0f; + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; +} + +// ELF 0x8153D00. Record: tick, mode, then either the free-mode quaternion (x y z w) and position, +// or the follow-mode player id and orbit parameters; every field 4 bytes. The stream's +// return values are ignored. +void CameraUpdate::writeToStream(io::IStream* stream) const +{ + stream->write(&tick, 4); + stream->write(&mode, 4); + if (mode == DemoSpectatorCamera::Mode_FreeFlying) + { + stream->write(&rotation.x, 4); + stream->write(&rotation.y, 4); + stream->write(&rotation.z, 4); + stream->write(&rotation.w, 4); + stream->write(&position.x, 4); + stream->write(&position.y, 4); + stream->write(&position.z, 4); + } + else + { + stream->write(&playerId, 4); + stream->write(&yaw, 4); + stream->write(&pitch, 4); + stream->write(&followDistance, 4); + stream->write(&heightOffset, 4); + } +} + +// ELF 0x8153F20. The inverse of writeToStream; an unknown mode reads as free mode, and a +// free-mode position with squared length above 1e10 is discarded (zeroed). +void CameraUpdate::readFromStream(io::IStream* stream) +{ + stream->read(&tick, 4); + int rawMode; + stream->read(&rawMode, 4); + mode = DemoSpectatorCamera::intToMode(rawMode); + if (mode == DemoSpectatorCamera::Mode_FreeFlying) + { + stream->read(&rotation.x, 4); + stream->read(&rotation.y, 4); + stream->read(&rotation.z, 4); + stream->read(&rotation.w, 4); + stream->read(&position.x, 4); + stream->read(&position.y, 4); + stream->read(&position.z, 4); + if (position.x * position.x + position.y * position.y + position.z * position.z > 1.0e10f) + { + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; + } + } + else + { + stream->read(&playerId, 4); + stream->read(&yaw, 4); + stream->read(&pitch, 4); + stream->read(&followDistance, 4); + stream->read(&heightOffset, 4); + } +} + +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/Game/DemoRecorder/DemoSpectatorCamera.h b/Code/BF2/Game/DemoRecorder/DemoSpectatorCamera.h new file mode 100644 index 000000000..9e0c2608c --- /dev/null +++ b/Code/BF2/Game/DemoRecorder/DemoSpectatorCamera.h @@ -0,0 +1,139 @@ +// Demo spectator camera: the free-flying / follow-player camera rig a DemoRecorder owns while it +// records or plays a .bf2cam camera track. Recovered from the symbolized dedicated ELF +// (0x8151F50..0x8154690, TU Game/DemoRecorder/DemoSpectatorCamera.cpp by its anonymous-namespace +// symbol) and cross-checked against BF2.exe 0x6298C0..0x62AEFF. +// Nonpolymorphic. ELF size 0xA4 (DemoRecorder::initPlayback allocates operator new(0xA4)); the +// PE layout differs from +0x74 on (MSVC aligns the double to 8), so the offsets below are ELF only. + +#ifndef GAME_DEMORECORDER_DEMOSPECTATORCAMERA_H // [INFERRED] guard style +#define GAME_DEMORECORDER_DEMOSPECTATORCAMERA_H + +#include "../../Core/WeakPtr.h" +#include "../../Math/Mat4.h" +#include "../../Math/Quat.h" +#include "../../Math/Vec3.h" +#include "../../IO/Input/PlayerInput.h" // io::PlayerInput / io::PlayerInputMap + +namespace dice { +namespace hfe { + +namespace io { class IStream; } +namespace world { class IObject; class IPlayer; class FreeCamera; } + +class DemoRecorder; +struct CameraUpdate; + +class DemoSpectatorCamera +{ +public: + // The type name is attested by setMode(Mode)'s mangling. Only 0 and 1 exist (intToMode maps + // everything else to 0). Enumerator spellings [CHOSEN, not recovered]; 0 is the free-flying + // mode (getIsFreeFlying tests == 0), 1 follows a player. + enum Mode + { + Mode_FreeFlying = 0, + Mode_FollowPlayer = 1 + }; + + explicit DemoSpectatorCamera(DemoRecorder* owner); // ELF 0x8151F50 (C1) / 0x81520B0 (C2) + ~DemoSpectatorCamera(); // ELF 0x8152210 / 0x81522A0 + + // what DemoRecorder drives + void setPlaybackMode(bool playback); // ELF 0x8152330 + void setPlaybackStream(io::IStream* stream); // ELF 0x8152340 + bool getEOF() const; // ELF 0x8152360 / PE 0x6298E0 + void setRecordStream(io::IStream* stream); // ELF 0x8152380 + void updateTicks(int ticks); // ELF 0x8152A10 / PE 0x62A000 + void handlePlayerInput(const io::PlayerInput& input, float deltaTime); // ELF 0x8152490 / PE 0x62ACF0 + void demoVisualUpdate(float time); // ELF 0x8153100 / PE 0x62A950 + void getPlaybackMatrixAndFOV(Mat4* matrix, float* fov, float time); // ELF 0x8152890 / PE 0x62AC40 + bool nextCamera(); // ELF 0x81526F0 / PE 0x62ABF0 + bool nextPlayer(); // ELF 0x8152710 / PE 0x62AC00 + bool previousPlayer(); // ELF 0x8152750 / PE 0x62AC20 + int getCurrentDemoPlayerId(); // ELF 0x8152790 / PE 0x68E7B0 (ICF-shared) + bool getIsFreeFlying(); // ELF 0x8153210 / PE 0x629990 + world::IPlayer* getCurrentPlayer(); // ELF 0x8152390 + // [INFERRED] return type: every call through it dispatches the FreeCamera table (ELF vtable + // +0x180 = FreeCamera::getTransformation(float)); the object is the CID_FreeCameraTemplate + // template's createObject() result. + world::FreeCamera* getFreeCamera(); // ELF 0x81531A0 + void setMode(Mode mode); // ELF 0x81531C0 + void nextMode(); // ELF 0x8153230 / PE 0x62AA10 + + static Mode intToMode(int value); // ELF 0x81540F0 (no this) + + // Helpers. Access is not visible in the Itanium manglings; private is [INFERRED]. +private: + // ELF 0x81523D0 - static (the callers pass no this). + static bool checkSingleKey(const io::PlayerInput& input, io::PlayerInputMap key, bool& latch); + void updateSpectateTarget(int direction); // ELF 0x81527A0 + bool ensureCamerasCreated(); // ELF 0x8152F50 / PE 0x62A830 + void handleFollowInput(const io::PlayerInput& input, float deltaTime); // ELF 0x8153290 / PE 0x62A300 + void updateLookAtMatrix(); // ELF 0x81535B0 / PE 0x629B10 + void calcCameraFromUpdates(float time); // ELF 0x8153880 / PE 0x62AAD0 + bool readCameraUpdates(); // ELF 0x8153A40 / PE 0x62A570 + + // [CHOSEN, not recovered] type for the +0x04 block: operator new(0xC) / operator delete + // (scalar forms, so not a new[] array), zeroed by a 3-dword rep stosd, then handed out as + // bool& at +0..+11. Index 0 = PIAltFire, 1 = PIAction, 2 = PIReload, 3..11 = PIWeaponSelect1..9. + struct KeyLatches + { + bool latched[12]; + }; + + // Member names are [INFERRED] from their readers and writers unless noted. + /* +0x00 */ DemoRecorder* m_owner; + /* +0x04 */ KeyLatches* m_keyLatches; + /* +0x08 */ int m_currentPlayerId; // ctor -1 + /* +0x0C */ WeakPtr m_freeCamera; // the MultiPlayerFreeCamera object + /* +0x10 */ Mode m_mode; + /* +0x14 */ bool m_playbackMode; // setPlaybackMode + /* +0x15 */ bool m_eof; // set when the camera track runs dry + /* +0x18 */ Mat4 m_matrix; // ctor identity; the output transform + /* +0x58 */ float m_yaw; // degrees + /* +0x5C */ float m_pitch; // degrees, clamped to +-89 + /* +0x60 */ int m_numUpdates; // valid entries in m_updates + /* +0x64 */ int m_maxUpdates; // ctor 4 + /* +0x68 */ CameraUpdate* m_updates; // new CameraUpdate[4] (0xE0, no cookie) + /* +0x6C */ io::IStream* m_playbackStream; // not owned + /* +0x70 */ io::IStream* m_recordStream; // not owned + /* +0x74 */ double m_double74; // [UNRESOLVED] ctor -1.0, never read in this TU + /* +0x7C */ CameraUpdate* m_spareUpdate; // [UNRESOLVED] ctor new CameraUpdate, dtor deletes, nothing else + /* +0x80 */ int m_ticks; // updateTicks stores its argument + /* +0x84 */ float m_float84; // [UNRESOLVED] ctor 0, never read in this TU + /* +0x88 */ float m_float88; // [UNRESOLVED] ctor 0, never read in this TU + /* +0x8C */ int m_unused8C; // [CHOSEN, not recovered] no instruction touches +0x8C + /* +0x90 */ float m_followDistance; // ctor 2.0; clamped to [demo-cam-offset-min, 1000] + /* +0x94 */ float m_heightOffset; // clamped to +-10 + /* +0x98 */ bool m_inputPrimed; // the first handlePlayerInput only primes + /* +0x99 */ bool m_tickOffsetSet; + /* +0x9C */ int m_tickOffset; // playback tick -> world tick shift + /* +0xA0 */ float m_visualTime; // demoVisualUpdate's argument + + DemoSpectatorCamera(const DemoSpectatorCamera&); // not in the binary; not generated + DemoSpectatorCamera& operator=(const DemoSpectatorCamera&); +}; + +// One sampled camera state, 0x38 bytes in the ELF; the .bf2cam track is a sequence of these. +// Field names are [INFERRED] from the camera members updateTicks copies into them. +struct CameraUpdate +{ + CameraUpdate(); // ELF 0x8153C80 / 0x8153CC0 + void writeToStream(io::IStream* stream) const; // ELF 0x8153D00 + void readFromStream(io::IStream* stream); // ELF 0x8153F20 + + /* +0x00 */ DemoSpectatorCamera::Mode mode; + /* +0x04 */ unsigned int tick; // compared unsigned (jae) against the world tick + /* +0x08 */ int playerId; // follow mode only + /* +0x0C */ float yaw; // follow mode only; the ctor leaves +0x0C..+0x18 unset + /* +0x10 */ float pitch; + /* +0x14 */ float followDistance; + /* +0x18 */ float heightOffset; + /* +0x1C */ Quat rotation; // free mode only + /* +0x2C */ Vec3 position; // free mode only +}; + +} // namespace hfe +} // namespace dice + +#endif // GAME_DEMORECORDER_DEMOSPECTATORCAMERA_H diff --git a/Code/BF2/Game/DistributedLightRenderer/DistributedLightRenderer.cpp b/Code/BF2/Game/DistributedLightRenderer/DistributedLightRenderer.cpp new file mode 100644 index 000000000..118e10028 --- /dev/null +++ b/Code/BF2/Game/DistributedLightRenderer/DistributedLightRenderer.cpp @@ -0,0 +1,296 @@ +// dice::hfe::DistributedLightRenderer, BF2.exe 0x46B5B0..0x46C690 (see the header). +// +// PE / ELF differences (the client is the reference; the ELF is the dedicated server's copy): +// performTraceObject the PE continues after "LightmapGeneration not found" (and then calls through +// the null generator) and, for a missing object, sends 0xF and still traces with +// a null active object before sending the trace's own result; the ELF returns +// after the diagnostic and after the 0xF. +// update the ELF writer table is ordered differently (queueText at +0x38, as the AI +// DebugRenderer notes); the calls are the same. +#include "DistributedLightRenderer.h" +#if !DEDICATED +#include "../../Core/ClassManager.h" +#include "../../Core/Debug.h" +#include "../../Core/Ids.h" +#include "../../Core/StringUtil.h" // formatString (4310D0) +#include "../../Geom/LightmapGeneration/ILightmapGeneration.h" +#include "../../Scene/Object/ObjectManager.h" // world::objectManager (ds:A08F58) +#include "../Common/GameEvent.h" // PostRemoteEvent (53CFA0) +#include "../GameServer/GameServer.h" // sendDataBlock (4C57B0) +#include "../IEventListener.h" // ECNetwork +#include "../IGame.h" // game (ds:99E348) +#include "../IGameServer.h" +#include "../Objects/IObject.h" +#include +#include +#include +#include +#include + +#define DLR_FILE "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Game\\DistributedLightRenderer\\DistributedLightRenderer.cpp" + +namespace dice { +namespace hfe { + +extern ClassManager* classManager; + +namespace { + +// The "DebugTextWriter" slots update uses (geom::DebugTextWriter, GeomMisc/DebugTextWriter.cpp), +// declared locally in table order as the AI DebugRenderer does. [INFERRED] interface name. +class DebugTextWriterView : public IBase +{ +public: + virtual bool setFont(const std::string&) = 0; // +10 + virtual bool isEnabled() const = 0; // +14 + virtual void setEnabled(bool) = 0; // +18 + virtual unsigned int getColour() const = 0; // +1C + virtual void setColour(unsigned int colour) = 0; // +20 + virtual void queueWorldGroupColoured(const Vec3&, unsigned int, const std::vector&, + int, int, int) = 0; // +24 + virtual void queueWorldTextColoured(const Vec3&, unsigned int, const std::string&, int) = 0; // +28 + virtual void queueGroupColoured(int, int, unsigned int, const std::vector&, + int, int, int) = 0; // +2C + virtual void queueTextColoured(int, int, unsigned int, const std::string&, int) = 0;// +30 + virtual void queueWorldGroup(const Vec3&, const std::vector&, int, int, int) = 0; // +34 + virtual void queueWorldText(const Vec3&, const std::string&, int) = 0; // +38 + virtual void queueGroup(int, int, const std::vector&, int, int, int) = 0; // +3C + virtual void queueText(int x, int y, const std::string& text, int alignment) = 0; // +40 +protected: + ~DebugTextWriterView() {} +}; + +// The "Terrain" singleton's primary table up to the patch count (geom::Terrain, Geom/Terrain.h), +// declared locally so game code does not pull in the renderer's terrain header. +class TerrainView : public IBase +{ +public: + virtual unsigned int getReflectionTypeId() = 0; // +10 + virtual void init() = 0; // +14 + virtual void load(const std::string&) = 0; // +18 + virtual void slot07() = 0; // +1C + virtual void setRenderStyle(int) = 0; // +20 + virtual int getRenderStyle() = 0; // +24 + virtual void update() = 0; // +28 + virtual void slot11() = 0; // +2C + virtual int getPatchCount() = 0; // +30, patches per side +protected: + ~TerrainView() {} +}; + +void sendLightmapResult(unsigned int code) // ECNetwork 0xE done / 0xF failed +{ + GameEvent* const event = new (std::nothrow) PostRemoteEvent(ECNetwork, code, false, 0, 0, 0.0f); // 0x54 + game->sendGameEvent(0xFFFFFFFFu, event); // +8C +} + +} // namespace + +// 40FF0E: an aggregate outer is refused; a failed interface query releases the new object. +IBase* DistributedLightRenderer::create(unsigned int iid, IBase* outer) +{ + if (outer) return nullptr; + void* allocation = ::operator new(sizeof(DistributedLightRenderer)); + DistributedLightRenderer* renderer = allocation ? new (allocation) DistributedLightRenderer : nullptr; + IBase* result = static_cast(renderer->queryInterface(iid)); + if (!result) renderer->release(); + return result; +} + +// 46C350. +08 is not written in retail (the job counter starts with whatever the heap held); +// [CHOSEN, not recovered] it starts at 0 here. +DistributedLightRenderer::DistributedLightRenderer() : m_refCount(1), m_nextJobId(0) {} + +// 46C120: the containers are cleared; the queued and assigned work items are not freed. +DistributedLightRenderer::~DistributedLightRenderer() {} + +void DistributedLightRenderer::addRef() { ++m_refCount; } +int DistributedLightRenderer::getRef() { return m_refCount; } +int DistributedLightRenderer::release() +{ + const int remaining = --m_refCount; + if (remaining == 0) delete this; // +2C(1) + return remaining; +} + +void* DistributedLightRenderer::queryInterface(unsigned int iid) const +{ + if (iid == IID_IBase || iid == IID_IDistributedLightRenderer) + return const_cast(this); + return nullptr; +} + +// 46C1E0: objects carry patch -1; the id is the running counter. +void DistributedLightRenderer::addObjectToJobQueue(world::IObject* object, int terrainPatch) +{ + DLRWorkItem* const item = new (std::nothrow) DLRWorkItem(); // 0xC, zeroed + item->object = object; + item->id = m_nextJobId++; + item->terrainPatch = object ? -1 : terrainPatch; + m_jobs.push_back(item); +} + +// 46C580: every registered object that is alive, not mobile, has geometry within 10000 of the +// origin, and whose geometry answers ILightSampleable. Walks a copy of the registry. +void DistributedLightRenderer::traceAllObjects() +{ + const std::map objects(world::objectManager->getAllRegisteredObjects()); // +B4 + for (std::map::const_iterator it = objects.begin(); it != objects.end(); ++it) { + world::IObject* const object = it->second; + const unsigned int flags = object->m_flags; + if ((flags & world::IObject::OFHasMobilePhysics) || !(flags & world::IObject::OFIsAlive) || !object->m_geometry) + continue; + const Vec3& position = object->getAbsolutePosition(); // +68 + const float distance = std::sqrt(position.x * position.x + position.y * position.y + position.z * position.z); + if (!(distance <= 10000.0f)) // 89FBB0 + continue; + IBase* const geometry = static_cast(object->m_geometry); + if (geometry && geometry->queryInterface(geom::IID_ILightSampleable)) + addObjectToJobQueue(object, 0); + } +} + +// 46C3F0: one job per terrain patch (the count is per side). The patch count is read through the +// singleton itself, not the editable interface it is checked for. +void DistributedLightRenderer::traceTerrain() +{ + IBase* const terrain = classManager->getSingleton(std::string("Terrain")); // +48 + if (!terrain) { + Debug(DEBUGTYPE_6, DLR_FILE, 0x5A, "") << "no terrain found"; + return; + } + if (!terrain->queryInterface(geom::IID_ITerrainEditable)) { + Debug(DEBUGTYPE_6, DLR_FILE, 0x60, "") << "IID_ITerrainEditable not found for terrain"; + return; + } + TerrainView* const view = static_cast(terrain); + for (unsigned int patch = 0; patch < static_cast(view->getPatchCount() * view->getPatchCount()); ++patch) + addObjectToJobQueue(nullptr, static_cast(patch)); +} + +// 46BDC0: a known client is reported, then (re)inserted idle with no job. +void DistributedLightRenderer::addRenderResource(int resource) +{ + if (m_resources.find(resource) != m_resources.end()) + Debug(DEBUGTYPE_6, DLR_FILE, 0x91, "") << "Client already registred as an resource"; + m_resources.insert(std::make_pair(resource, static_cast(nullptr))); + m_idleResources.insert(resource); +} + +// 46C250: a departing client's job goes back to the end of the queue. +void DistributedLightRenderer::removeRenderResource(int resource) +{ + std::map::iterator found = m_resources.find(resource); + if (found != m_resources.end()) { + if (found->second) + m_jobs.push_back(found->second); + m_resources.erase(found); + } + std::set::iterator idle = m_idleResources.find(resource); + if (idle != m_idleResources.end()) + m_idleResources.erase(idle); +} + +// 46BE80: the client is idle again and its job is freed. +// [CHOSEN, not recovered] Retail does not test the lookup; an unknown client reads the map head. +// Here it is ignored. +void DistributedLightRenderer::workItemFinished(int resource) +{ + std::map::iterator found = m_resources.find(resource); + if (found == m_resources.end()) return; + DLRWorkItem* const item = found->second; + found->second = nullptr; + m_idleResources.insert(found->first); + ::operator delete(item); +} + +// 46BA30: records the job and, on a server, sends it to the client as data block 4. +void DistributedLightRenderer::assignWorkItem(int resource, DLRWorkItem* item) +{ + std::map::iterator found = m_resources.find(resource); + if (found == m_resources.end()) { + Debug(DEBUGTYPE_6, DLR_FILE, 0x134, "") << "Resource " << resource << " not found"; + // [CHOSEN, not recovered] Retail goes on to write the job into the map head. + return; + } + if (found->second) + Debug(DEBUGTYPE_6, DLR_FILE, 0x139, "") << "Job already assigned to resource " << resource; + found->second = item; + IGameServer* const server = static_cast(game->queryInterface(IID_IGameServer)); // +0C + if (!server) return; + DLRWorkItemBlock block; + std::memset(&block, 0, sizeof(block)); + if (item->object) { + block.id = item->object->m_objectId; // +10 + block.isTerrain = false; + } else { + block.id = static_cast(item->terrainPatch); + block.isTerrain = true; + } + static_cast(server)->sendDataBlock(resource, 4, &block, sizeof(block), true); +} + +// 46B5B0, a lightmap-rendering client's half: trace the block's object (as the object manager's +// active object) or terrain patch, and report. +void DistributedLightRenderer::performTraceObject(void* data, unsigned int size) +{ + (void)size; + geom::ILightmapGeneration* const generation = static_cast( + classManager->getSimpleSingleton(std::string("LightmapGeneration"))); // +58 + if (!generation) + Debug(DEBUGTYPE_6, DLR_FILE, 0xD8, "") << "LightmapGeneration not found"; + const DLRWorkItemBlock* const block = static_cast(data); + bool traced; + if (!block->isTerrain) { + world::IObject* const object = world::objectManager->getRegisteredObject(static_cast(block->id)); // +B0 + if (!object) + sendLightmapResult(0xF); + world::IObject* const previous = world::objectManager->getActiveObject(); // +90 + world::objectManager->setActiveObject(object); // +94 + traced = generation->traceActiveObject(); // +14 + world::objectManager->setActiveObject(previous); + } else { + traced = generation->traceTerrain(static_cast(block->id)); // +1C + } + sendLightmapResult(traced ? 0xE : 0xF); +} + +// 46BED0: hand queued jobs to idle clients, then the progress lines (server) or the node banner. +void DistributedLightRenderer::update() +{ + while (!m_jobs.empty()) { + if (m_idleResources.empty()) + break; + const int resource = *m_idleResources.begin(); + m_idleResources.erase(m_idleResources.begin()); + DLRWorkItem* const item = m_jobs.front(); + m_jobs.pop_front(); + assignWorkItem(resource, item); + } + DebugTextWriterView* const writer = + static_cast(classManager->getSingleton(std::string("DebugTextWriter"))); // +48 + if (!writer) + return; + const unsigned int colour = writer->getColour(); + if (game->queryInterface(IID_IGameServer)) { + writer->setColour(0xFFFFFFFFu); + writer->queueText(20, 500, formatString("Distributed lightmapGeneration in progress..."), 0); + writer->queueText(20, 510, formatString("Using %d nodes", static_cast(m_resources.size())), 0); + writer->queueText(20, 520, formatString("%d items enqued.", static_cast(m_jobs.size())), 0); + writer->queueText(20, 530, formatString("%d items in progress.", + static_cast(m_resources.size() - m_idleResources.size())), 0); + } else { + writer->setColour(0xAAFFAAFFu); + writer->queueText(20, 500, formatString("Distributed lightmapGeneration in progress...connected to server"), 0); + } + writer->setColour(colour); +} + +#if defined(_M_IX86) +static_assert(sizeof(DLRWorkItem) == 0xC, "DLRWorkItem layout"); +static_assert(sizeof(DLRWorkItemBlock) == 0x248, "data block 4 layout"); +#endif + +} // namespace hfe +} // namespace dice +#endif diff --git a/Code/BF2/Game/DistributedLightRenderer/DistributedLightRenderer.h b/Code/BF2/Game/DistributedLightRenderer/DistributedLightRenderer.h new file mode 100644 index 000000000..9d610fa43 --- /dev/null +++ b/Code/BF2/Game/DistributedLightRenderer/DistributedLightRenderer.h @@ -0,0 +1,91 @@ +// dice::hfe::DistributedLightRenderer, the "DistributedLightRenderer" singleton (factory +// "dice.bf2.DistributedLightRenderer", CID 121009, IID 120009). BF2.exe 0x46B5B0..0x46C690, table +// 0x89FB40, 0x38 bytes; the bf2 ELF carries the same class with its symbols (0x80C15A0..0x80C4300). +// +// Distributed lightmap generation: a server queues work items (one per traceable object, or one +// per terrain patch) and hands one to each connected lightmap-rendering client as data block 4; +// the client traces it through the renderer's "LightmapGeneration" and answers with ECNetwork +// 0xE (done) or 0xF (failed). In the shipped client the rendering-node switch is never set (its +// command-line option 35 is not registered), so only the server half could run in retail. +#ifndef GAME_DISTRIBUTEDLIGHTRENDERER_DISTRIBUTEDLIGHTRENDERER_H +#define GAME_DISTRIBUTEDLIGHTRENDERER_DISTRIBUTEDLIGHTRENDERER_H + +#include "../../Core/IBase.h" +#include +#include +#include + +#if !DEDICATED +namespace dice { +namespace hfe { +namespace world { class IObject; } + +// One queued job, 0xC bytes (46C1E0): an object, or a terrain patch when the object is null. +struct DLRWorkItem +{ + world::IObject* object; // +00 + int terrainPatch; // +04, -1 for objects + unsigned int id; // +08, the renderer's running job counter +}; + +// Data block 4 as assignWorkItem sends it (0x248 bytes). Only the tail is written. +struct DLRWorkItemBlock +{ + unsigned char unused[0x240]; // +000, not written in retail ([CHOSEN] zeroed here) + unsigned int id; // +240, the object's id, or the terrain patch + bool isTerrain; // +244 + unsigned char pad[3]; +}; + +// [INFERRED] interface name and placement; the slot names are the ELF's. +class IDistributedLightRenderer : public IBase +{ +public: + virtual void traceAllObjects() = 0; // +10 + virtual void traceTerrain() = 0; // +14 + virtual void addRenderResource(int resource) = 0; // +18 + virtual void removeRenderResource(int resource) = 0; // +1C + virtual void workItemFinished(int resource) = 0; // +20 + virtual void performTraceObject(void* data, unsigned int size) = 0; // +24 + virtual void update() = 0; // +28 +protected: + ~IDistributedLightRenderer() {} +}; + +class DistributedLightRenderer : public IDistributedLightRenderer +{ +public: + static IBase* create(unsigned int iid, IBase* outer); // 40FF0E + + DistributedLightRenderer(); // 46C350 + virtual ~DistributedLightRenderer(); // 46C120 (+2C deleting 46C3C0) + + void addRef() override; // 6D0970 + int getRef() override; // 68AED0 + int release() override; // 46C1C0 + void* queryInterface(unsigned int iid) const override; // 46C190 + + void traceAllObjects() override; // 46C580 + void traceTerrain() override; // 46C3F0 + void addRenderResource(int resource) override; // 46BDC0 + void removeRenderResource(int resource) override; // 46C250 + void workItemFinished(int resource) override; // 46BE80 + void performTraceObject(void* data, unsigned int size) override;// 46B5B0 + void update() override; // 46BED0 + +private: + friend struct DistributedLightRendererFixture; + void addObjectToJobQueue(world::IObject* object, int terrainPatch); // 46C1E0 + void assignWorkItem(int resource, DLRWorkItem* item); // 46BA30 + + int m_refCount; // +04 + unsigned int m_nextJobId; // +08 + std::deque m_jobs; // +0C + std::map m_resources; // +20, the job each client is working on + std::set m_idleResources; // +2C +}; + +} // namespace hfe +} // namespace dice +#endif +#endif diff --git a/Code/BF2/Game/GameClient/GameClient.cpp b/Code/BF2/Game/GameClient/GameClient.cpp index 53dea96d9..faaebc68b 100644 --- a/Code/BF2/Game/GameClient/GameClient.cpp +++ b/Code/BF2/Game/GameClient/GameClient.cpp @@ -1,10 +1,9 @@ -// Client-only game loop and network session. Unimplemented calls retain named -// [FRONTIER] diagnostics and stop execution. [TEMP] [CHOSEN, not recovered] -// [RETIRE-WHEN: game-client-bodies] Replace remaining GAMECLIENT_FRONTIER sites -// with their implementations. +// Client-only game loop and network session. #include "GameClient.h" +#include "../PunkBuster/PbGlue.h" #if !DEDICATED +#include #include #include #include @@ -22,12 +21,14 @@ #include "../Main/BF2Engine.h" // bf2Engine->demo (isPlayingDemo) #include "../Main/Demo.h" #include "../Main/BF2ClientSeams.h" // hudManager, g_distributedLightRenderer +#include "../DistributedLightRenderer/DistributedLightRenderer.h" #include "../Main/StatsMonitor.h" #include "../Utility/BuildNrUtil.h" #include "../Common/ClientConnection.h" #include "../Common/GhostManager.h" // ECNetwork 17: removeGhostable #include "../Common/ClientVoteManager.h" // update's per-frame kick-vote ticker (599290) #include "../Common/GameEventManager.h" +#include "../GameEvents/ChangePlayerNameEvent.h" #include "../Common/StringManager.h" #include "../Common/GameEvent.h" #include "../GameEvents/ChallengeEvent.h" @@ -58,6 +59,10 @@ #include "../../IO/Input/Input.h" // enterVehicle: io::IInputManager +0x2C #include "../Objects/IObjectTemplate.h" #include "../DemoRecorder/DemoRecorder.h" +#include "../DemoAvailableInfo.h" +#include "../../Core/SystemInfo.h" +#include "../DemoRecorder/DemoLibrary.h" +#include "../LocalProfileManager.h" #include "../../Scene/Object/PlayerManager.h" #include "../../Scene/Object/ObjectManager.h" #include "../../Scene/Object/ObjectTypes/Base/ObjectTemplateManager.h" @@ -117,13 +122,11 @@ namespace hfe { #define GAMECLIENT_FILE "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Game\\GameClient\\GameClient.cpp" -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: game-client-bodies] -#define GAMECLIENT_FRONTIER(method, text) \ - do { \ - std::fprintf(stderr, "[FRONTIER] dice::hfe::GameClient::" method ": " text "\n"); \ - std::fflush(stderr); \ - std::abort(); \ - } while (0) +// The recorder test BF2.exe inlines at every demo site: `recorder && 54B8F0(recorder)`. +static bool demoPlaybackActive(const DemoRecorder* recorder) +{ + return recorder != 0 && recorder->isOpenForPlayback(); +} // Rejects aggregation and releases an object whose interface query fails. // The original unchecked query after failed allocation remains. @@ -322,17 +325,14 @@ int GameClient::disconnect() // Loads the current map after preparing squads and notifying listeners. Clears // readiness first and restores file resolve mode after load success or failure. -// The recorder's playback-skip flag bypasses loading and returns true. +// A restarted demo playback (the recorder's playbackPlaying, PE +0x105) keeps the loaded level +// and returns true (4D2EAD). bool GameClient::load() { DemoRecorder* const recorder = m_demoRecorder; m_isReady = false; - if (recorder) - { - // ..4D2EBD: `recorder+0xC4 && !recorder+0xCD` (54B8F0) and the byte at +0x105 - the - // DemoRecorder's PE layout is not mapped onto the tree's ELF-recovered class. - GAMECLIENT_FRONTIER("load", "DemoRecorder playback predicate (54B8F0, bytes +0xC4/+0xCD/+0x105) is unmapped"); - } + if (demoPlaybackActive(recorder) && recorder->playbackPlaying) + return true; if (squadManager) static_cast(squadManager)->reAddDynamicSpawnGroups(); // +0x14 @@ -354,9 +354,10 @@ bool GameClient::load() io::fileManager->setFileResolveMode(1); if (!gameLogic->load(levelPath)) // +0x14 { - // / 4D3072: two LoadStat calls on the singleton (45D6D0, then 45D540) - the failed - // load's report. [UNRESOLVED] which two of LoadStat's methods those PE bodies are. - GAMECLIENT_FRONTIER("load", "IGameLogic::load refused; the LoadStat pair 45D6D0/45D540 is unmapped"); + // 4D3064: the loading screen's callback ends (unregisterLoadCallback 45D6D0, which also + // resets) and the statistics are reset once more (resetLoadStats 45D540). + loadStat->unregisterLoadCallback(); + loadStat->resetLoadStats(); io::fileManager->setFileResolveMode(resolveMode); return false; } @@ -391,18 +392,21 @@ bool GameClient::update(int steps, float dt) world::IPlayer* const local = world::playerManager->getLocalHumanPlayer(); if (isLightmapRenderingNode()) { - // : g_distributedLightRenderer->+0x28(); then the quit latch on byte_9A7758 and - // mainConsole->executeLine("quit\n", ignoredString_, 0, 0, 0, 0, 0). - GAMECLIENT_FRONTIER("update", "the lightmap-rendering node's DistributedLightRenderer +0x28 is unrecovered"); + // 4D57B6: the renderer's update, then quit once a connection that was up has gone + // (the latch is byte_9A7758). Unreachable in retail: see Game.h isLightmapRenderingNode. + static_cast(g_distributedLightRenderer)->update(); // +0x28 + static bool wasConnected = false; + if (m_connection) // +0xC0 + wasConnected = true; + else if (wasConnected) + io::mainConsole->executeLine(std::string("quit\n"), io::Console::ignoredString_, 0, 0, 0, 0, 0); } else if (local && gameLogic->getGameStatus() == 1) // +0x158 { static_cast(local)->update(static_cast(delta)); } - const bool demoPlaying = m_demoRecorder != 0; // : recorder && 54B8F0(recorder) - if (demoPlaying) - GAMECLIENT_FRONTIER("update", "DemoRecorder playback predicate (54B8F0) is unmapped"); + const bool demoPlaying = demoPlaybackActive(m_demoRecorder); if (!demoPlaying) { if (steps) @@ -442,8 +446,15 @@ bool GameClient::update(int steps, float dt) world::responsePhysicsManager->startFrame(); // +0x2C if (i == steps - 1) { - if (demoPlaying) - GAMECLIENT_FRONTIER("update", "the demo listener transform (440B20 / 54BC20) is unmapped"); + // 4D5945: a playing demo listens from the spectator camera (identity Mat4 440B20, + // then 54BC20), with a zero velocity; the recorder test is repeated here. + if (demoPlaybackActive(m_demoRecorder)) + { + Mat4 listener = Mat4::getIdentity(); + m_demoRecorder->getPlaybackMatrixAndFOV(&listener, 0); + const Vec3 velocity = { 0.0f, 0.0f, 0.0f }; + g_bfSound->update(steps, listener, velocity, false); // PE +0x14 + } else g_bfSound->update(steps); // PE +0x18 } @@ -453,8 +464,12 @@ bool GameClient::update(int steps, float dt) ClientVoteManager::getInstance()->update(dt); transmit(steps, delta); m_playerInputs.clear(); - if (m_showNetGraph && m_bitStream) - GAMECLIENT_FRONTIER("update", "BitStream PE +0x04 (the net-graph reset) is unmapped"); + // 4D5A15: with the net graph shown, the stats object's update (PE +0x04, no null test). + // [CHOSEN, not recovered] retail's object is the 0x88-byte client derivative (vtable 9135C8) + // whose update (6BB110) also runs 6BAE90 and 6BB090; the tree builds the base class (see + // playDemo/connect), so the base update (client then server status) runs. + if (m_showNetGraph) + m_networkableStats->update(); return ok; } @@ -741,9 +756,35 @@ bool GameClient::stepWorld(float dt) if (player->getAltFiringState()) fireMask |= 2u; // PE +0x1A8 = ELF +0x1AC if (player->getFiringState()) fireMask |= 1u; // PE +0x1A0 = ELF +0x1A4 - // [UNRESOLVED] The original Player state-clear has no mapped member in this layout - // and is omitted to avoid writing an unrelated field. - // [RETIRE-WHEN: player-pe-layout] Map the client Player member before restoring the store. + // PE 0x5C056A `mov byte [esi+0x234], 0`, straight after the getFiringState call: the + // primary-fire press latch (PE +0x234 = ELF +0x204, the second operand of + // getFiringState, PE 0x504D00) is consumed here. Player::netUpdate sets it for a press + // seen on the wire, so a tap shorter than one update still fires exactly one message 6; + // without this clear every remote player's primary fire stays held after the first press. + static_cast(player)->m_field204 = false; + + // [TEMP] [CHOSEN, not recovered] remote-fire replay tracer, armed by + // BF2_TRACE_REMOTE_FIRE=1: one stderr line whenever the replayed fire mask of a player + // changes, so a stuck or never-raised trigger shows up. Read-only. + // [RETIRE-WHEN: remote-fire-validated] + { + static int traceArmed = -1; + if (traceArmed < 0) + traceArmed = std::getenv("BF2_TRACE_REMOTE_FIRE") ? 1 : 0; + const int id = player->getId(); + if (traceArmed && id >= 0 && id < 256) + { + static unsigned int lastMask[256]; + if (lastMask[id] != fireMask) + { + lastMask[id] = fireMask; + std::fprintf(stderr, "[REMOTEFIRE] frame=%d p%d mask=%u vehicle=%s\n", + m_frameCount, id, fireMask, + vehicle->getTemplate()->getName().c_str()); + std::fflush(stderr); + } + } + } if (fireMask) sendFireMessages(fireMask, player, vehicle, false); @@ -856,7 +897,7 @@ bool GameClient::receive(float dt) for (std::list::iterator it = packets.begin(); it != packets.end(); ++it) { if (m_punkBuster) - GAMECLIENT_FRONTIER("receive", "the PunkBuster client packet handler (4D9DE0) is unrecovered"); + PB_handlePacket(static_cast(it->data), static_cast(it->size), it->name); // 0x4D4F43 else Debug(DEBUGTYPE_6, GAMECLIENT_FILE, 672, "") << "PunkBuster packets on a disabled client"; std::free(it->data); @@ -869,9 +910,10 @@ bool GameClient::receive(float dt) code = m_netClient->receive(m_bitStream); else { - // ..4D4FF8: the demo playback read - 4C4420()'s recorder stream through 54C3B0 into - // m_bitStream; a non-empty stream is a packet (0), else 8. - GAMECLIENT_FRONTIER("receive", "the demo playback packet read (4C4420 / 54C3B0) is unmapped"); + // 4D5034: without a NetClient the packets come from the recorder at the world tick + // (4C4420); a filled stream is a packet (0), an empty or failed read is code 8. + const bool read = m_demoRecorder->readData(WorldPref::getTickCount(), m_bitStream); // 54C3B0 + code = (read && m_bitStream->m_highWaterBits != 0) ? 0 : 8; } switch (code) { @@ -1462,14 +1504,16 @@ bool GameClient::isPlayingDemo() return demo != 0 && demo->isPlayback; } -// setSimulationRate - 4D3110, 62 B: only while a demo plays - a rate other than 100 runs -// IBfSound PE +0xC4, then 5965B0(rate) (the recorder's rate). +// setSimulationRate - 4D3110, 62 B: only while a demo plays. A rate other than 100 forces the +// sound update (IBfSound PE +0xC4, setForceUpdate), then the engine rate is set (ds:99E2B8 is +// g_system; 5965B0 stores System +0x08). void GameClient::setSimulationRate(int rate) { - (void) rate; - if (!m_demoRecorder) + if (!demoPlaybackActive(m_demoRecorder)) return; - GAMECLIENT_FRONTIER("setSimulationRate", "DemoRecorder playback predicate and rate (54B8F0 / 5965B0) are unmapped"); + if (rate != 100) + g_bfSound->setForceUpdate(); + g_system->setSimulationRate(rate); } int GameClient::getSimulationRate() { return g_system->getSimulationRate(); } // (11 B, shared with GameServer) void GameClient::debugShowActiveGhosts(int) {} // : empty @@ -1603,9 +1647,8 @@ bool GameClient::handleControlObjectState(io::BitStream*, unsigned short network // networkables, and client statistics. Returns false if connection setup fails. bool GameClient::playDemo(DemoRecorder* recorder) { - // ..4D41EA: io::inputManager->+0x2C("InfantryPlayerInputControlMap") - the tree's - // InputManager carries no such slot yet. - GAMECLIENT_FRONTIER("playDemo", "io::InputManager PE +0x2C (the control-map selector) is unmapped"); + static_cast(io::inputManager) + ->setPlayerControlMap(std::string("InfantryPlayerInputControlMap")); // 4D41EA, +0x2C m_demoRecorder = recorder; world::objectManager->destroyObjects(); m_netClient = 0; @@ -2060,52 +2103,96 @@ std::string GameClient::getServerAddress() { return m_serverAddress; } / std::string GameClient::getServerAddressCopy() { return m_serverAddress; } // the folded twin, +0x78 void GameClient::slot44(int) {} // > nullsub_2 -// The demo group - 4D2650 (109 B), 4D26C0 (57 B), 4D2700 (36 B), 4D2730 (39 B), 4D2760 (38 B), -// (25 B), 4D3D60 (257 B). Every one reads DemoRecorder bytes by PE offset (+0xC4, +0xCD, -// +0xE8, +0xEC, +0x105 and the object at +0xE8) that the tree's ELF-recovered DemoRecorder does -// not map; a null recorder is the only arm transcribed. +// The demo group - BF2.exe 4D2650..4D2800 and 4D3D60. These run on the IGameClient subobject +// (+0xA8); the recorder is +0x98 there, GameClient +0x140. Each acts only while the recorder plays +// (54B8F0, DemoRecorder::isOpenForPlayback). Slot names are [INFERRED] from the recorder calls. + +// restartDemo - 4D2650, 109 B: back to the first frame with an empty world and fresh ghost and +// event state. void GameClient::restartDemo() { - if (!m_demoRecorder) return; - GAMECLIENT_FRONTIER("restartDemo", "DemoRecorder PE members (+0xC4/+0xCD/+0x105) are unmapped"); + if (!m_demoRecorder || !m_demoRecorder->isOpenForPlayback()) + return; + gameLogic->reset(); // +0x24 + destroyAllPlayers(); // Game:: 4444C0 + g_bfSound->engine()->stopAllSamples(); // IBfSound PE +0x24, ISoundEngine +0x18 + gameLogic->restartDemoPlayback(); // +0x28 + m_connection->m_gameEventManager->reset(); // PE +0x34 (one destructor slot) + m_connection->m_ghostManager->reset(); // 5BADF0 + m_demoRecorder->restartPlayback(); // 54CB60 } -void GameClient::setDemoPaused(bool) + +// demoSwitchPlayer - 4D26C0, 57 B: the spectator camera's next (true) or previous player +// (54BC90 / 54BCB0). +void GameClient::demoSwitchPlayer(bool next) { - if (!m_demoRecorder) return; - GAMECLIENT_FRONTIER("setDemoPaused", "DemoRecorder pause/resume (54BC90 / 54BCB0) are unmapped"); + if (!m_demoRecorder || !m_demoRecorder->isOpenForPlayback()) + return; + if (next) + m_demoRecorder->nextPlayer(); + else + m_demoRecorder->previousPlayer(); } -void GameClient::slot50() + +// demoNextCamera - 4D2700, 36 B (54BC70). +void GameClient::demoNextCamera() { - if (!m_demoRecorder) return; - GAMECLIENT_FRONTIER("slot50", "DemoRecorder +0xE8 and 62AA10 are unmapped"); + if (m_demoRecorder && m_demoRecorder->isOpenForPlayback()) + m_demoRecorder->nextCamera(); } -int GameClient::slot54() + +// demoGetCurrentPlayerId - 4D2730, 39 B (54BCD0); -1 when no demo plays. +int GameClient::demoGetCurrentPlayerId() { - if (!m_demoRecorder) return -1; - GAMECLIENT_FRONTIER("slot54", "DemoRecorder +0xE8 and 68E7B0 are unmapped"); + if (m_demoRecorder && m_demoRecorder->isOpenForPlayback()) + return m_demoRecorder->getCurrentDemoPlayerId(); + return -1; } -bool GameClient::slot58() + +// demoIsFreeFlying - 4D2760, 38 B (54BCF0). +bool GameClient::demoIsFreeFlying() { - if (!m_demoRecorder) return false; - GAMECLIENT_FRONTIER("slot58", "DemoRecorder +0xE8 (+0x10) is unmapped"); + if (m_demoRecorder && m_demoRecorder->isOpenForPlayback()) + return m_demoRecorder->getIsFreeFlying(); + return false; } -bool GameClient::isDemoPlaying() + +// isDemoAtEnd - 4D2800: the recorder's end-of-stream byte (PE +0xEC). BF2Engine pauses on it. +bool GameClient::isDemoAtEnd() { - if (!m_demoRecorder) return false; - GAMECLIENT_FRONTIER("isDemoPlaying", "DemoRecorder +0xEC is unmapped"); + return m_demoRecorder != 0 && m_demoRecorder->endOfStream; } -void GameClient::slot6C(int, int) + +// addDemoBookmark - 4D3D60, 257 B: a demo announced by the server (handleDataBlock block 9) is +// bookmarked in the current profile as {joined server name, map, url, now}, the profile is saved +// and the demo library is flagged. No profile manager: nothing. Argument names [INFERRED] from +// the bookmark fields the menu's "demobm" list reads (field1c is the map). +void GameClient::addDemoBookmark(const std::string& url, const std::string& mapName) { - GAMECLIENT_FRONTIER("slot6C", "LocalProfileManager +0xA4 and DemoLibrary +0x44 (the recorded-demo registration) are unmapped"); + ILocalProfileManager* const profiles = static_cast( + classManager->getSingleton(std::string("LocalProfileManager"))); // +0x48 + if (!profiles) + return; + ui::ISwiffHost* const host = static_cast( + classManager->getSingleton(std::string("SwiffHost"))); + std::string serverName; + if (host) + serverName = host->getStringE5C(); // +0x300 + const std::string now = systemInfo()->getDateTimeString(); // 434320, PE +0x08 + profiles->addDemoBookmark(serverName, mapName, url, now); // PE +0xA4 + profiles->saveCurrentProfile(); // PE +0x40 + IBase* const library = classManager->getSingleton(std::string("DemoLibrary")); + if (library) + static_cast(library)->setFlagA4(true); // +0x44 } // togglePause - 4D2790: setPause(!getPause()), both through the +0xA8 table. void GameClient::togglePause() { setPause(!getPause()); } -// setPause - 4D27B0, 71 B: pausing always sticks; unpausing only while no demo plays. The rate goes -// to 0 or 100 through IGame::setSimulationRate (primary +0xE0). +// setPause - 4D27B0, 71 B: pausing always sticks; unpausing is refused once a demo has reached its +// end (+0x68). The rate goes to 0 or 100 through IGame::setSimulationRate (primary +0xE0). void GameClient::setPause(bool paused) { - if (paused || !isDemoPlaying()) + if (paused || !isDemoAtEnd()) { m_paused = paused; setSimulationRate(paused ? 0 : 100); @@ -2115,6 +2202,18 @@ bool GameClient::getPause() { return m_paused; } / bool GameClient::getDisconnectRequested() { return m_disconnectRequested; } // : +0x120 bool GameClient::getIsReady() { return m_isReady; } // : +0x158 +namespace { +// The payload pointer a PostRemoteEvent stores in its notification node (PE node +0x2C). The named +// member keeps the retail x86 offset and follows the native layout elsewhere. +#if defined(_M_IX86) +static_assert(offsetof(NotificationEventNode, m_data) == 0x2C, "retail PE notification payload"); +#endif +inline void* remoteEventPayload(EventNode* node) +{ + return static_cast(node)->m_data; +} +} // namespace + // Dispatches client core/network events for join progress, player state, chat and object removal. // Database acknowledgements preserve network-ID regression order; mismatched IDs are fatal. // Event-specific node and data payloads must match the selected ID. @@ -2126,8 +2225,18 @@ void GameClient::handleEvent(EventCategory category, unsigned int id, EventNode* { if (node && *reinterpret_cast(node) == 1007) { + // 4D668F: the settings' player name goes to the server as a ChangePlayerNameEvent + // (0x30 bytes, 53D2E0) for the local player (IPlayer PE +0x50, getId), queued on + // the connection's event manager (PE +0x38, addEvent). A failed allocation queues 0. if (world::playerManager->getLocalHumanPlayer() && m_netClient) - GAMECLIENT_FRONTIER("handleEvent", "ECCore 1/1007: the ChangePlayerNameEvent resend (53D2E0) through the connection is unmapped"); + { + GameEvent* rename = 0; + if (void* allocation = ::operator new(sizeof(ChangePlayerNameEvent), std::nothrow)) + rename = new (allocation) ChangePlayerNameEvent( + world::playerManager->getLocalHumanPlayer()->getId(), + settings->stringGet(std::string("GSPlayerName"), std::string("player"))); + m_connection->m_gameEventManager->addEvent(rename); + } } } else if (id == 14) @@ -2177,7 +2286,7 @@ void GameClient::handleEvent(EventCategory category, unsigned int id, EventNode* // Rewind the id allocator before comparing the highest used network id with the // server's watermark. The rewind result is discarded; the separate query can return -1. io::networkManager->regressNetworkableIds(); // discarded - const int theirs = **reinterpret_cast(reinterpret_cast(node) + 0x2C); + const int theirs = *static_cast(remoteEventPayload(node)); // node +0x2C const int ours = io::networkManager->getHighestUsedNetID(); if (theirs != ours) Debug(DEBUGTYPE_7, GAMECLIENT_FILE, 1404, "") @@ -2194,7 +2303,7 @@ void GameClient::handleEvent(EventCategory category, unsigned int id, EventNode* break; case 9: { - const int playerId = **reinterpret_cast(reinterpret_cast(node) + 0x2C); + const int playerId = *static_cast(remoteEventPayload(node)); // node +0x2C if (world::IPlayer* player = world::playerManager->getPlayerFromId(playerId)) { player->setIsAlive(true); // PE +0x64 @@ -2204,7 +2313,7 @@ void GameClient::handleEvent(EventCategory category, unsigned int id, EventNode* } case 10: { - const char* const payload = *reinterpret_cast(reinterpret_cast(node) + 0x2C); + const char* const payload = static_cast(remoteEventPayload(node)); // node +0x2C const int playerId = *reinterpret_cast(payload); const bool flag = payload[4] != 0; world::IPlayer* const player = world::playerManager->getPlayerFromId(playerId); @@ -2291,8 +2400,9 @@ void GameClient::handleEvent(EventCategory category, unsigned int id, EventNode* void GameClient::handleDataBlock(EventNode* node, void* data) { (void) data; - if (m_demoRecorder) - GAMECLIENT_FRONTIER("handleDataBlock", "DemoRecorder playback predicate (54B8F0) is unmapped"); + // 4D5A4C: a restarted demo playback has already seen its blocks. + if (demoPlaybackActive(m_demoRecorder) && m_demoRecorder->playbackPlaying) + return; DataBlockReadyEvent* const block = static_cast(node); const unsigned int type = block->m_blockEventId; // PE +0x2C @@ -2317,7 +2427,8 @@ void GameClient::handleDataBlock(EventNode* node, void* data) } if (serverInfo->m_block.voipEnabled) // +0x31 gameLogic->startupVoipClient(); // +0x25C - if (serverInfo->getRequestResponse()) // the server wants our ClientInfo + // 4D5B71: a demo playback never answers with a ClientInfo. + if (serverInfo->getRequestResponse() && !demoPlaybackActive(m_demoRecorder)) { ClientInfo info; info.m_playerNameHash = AntiHacks::instance()->m_playerNameHash; // +0x00 -> info +0x38 @@ -2367,7 +2478,9 @@ void GameClient::handleDataBlock(EventNode* node, void* data) eventManager->postEvent(ECHud, 63, &m_commanderEnabled, 4.0f); // +0x10 if (load()) // PE +0x1C = ELF +0x20 { - // the demo predicate again (a null recorder here - see the top), then the proceed event + // 4D5EE0: a demo playback sends neither the loaded event nor the content checks. + if (demoPlaybackActive(m_demoRecorder)) + break; GameEvent* const loaded = new (std::nothrow) PostRemoteEvent(ECNetwork, 2, false, 0, 0, 0.0f); // 0x54 sendGameEvent(0xFFFFFFFFu, loaded); // PE +0x8C = ELF +0x90 @@ -2392,7 +2505,12 @@ void GameClient::handleDataBlock(EventNode* node, void* data) } case 4: if (isLightmapRenderingNode()) - GAMECLIENT_FRONTIER("handleDataBlock", "block 4: DistributedLightRenderer +0x24 is unrecovered"); + { + // 4D5FAE: a lightmap job for this node. Unreachable in retail (see update). + static_cast(g_distributedLightRenderer) + ->performTraceObject(const_cast(bytes), size); // +0x24 + break; + } Debug(DEBUGTYPE_6, GAMECLIENT_FILE, 1300, "") << "Server asked us to generate lightmaps, and we arent a lightmap rendering node"; break; @@ -2415,8 +2533,13 @@ void GameClient::handleDataBlock(EventNode* node, void* data) static_cast(endOfRound.getDelay())); // PE +0x170 break; } - case 9: - GAMECLIENT_FRONTIER("handleDataBlock", "block 9: the 5BCC50 block and IGameClient +0x6C are unmapped"); + case 9: // DemoAvailableInfo - 4D613E + { + DemoAvailableInfo announced; // 5BCC50 + announced.setFromDataBlock(bytes, size); // 5BCB40 + addDemoBookmark(announced.getUrl(), announced.getMapName()); // IGameClient +0x6C + break; + } default: break; } diff --git a/Code/BF2/Game/GameClient/GameClient.h b/Code/BF2/Game/GameClient/GameClient.h index b7b8cede0..f38c44c69 100644 --- a/Code/BF2/Game/GameClient/GameClient.h +++ b/Code/BF2/Game/GameClient/GameClient.h @@ -106,15 +106,15 @@ class GameClient : public Game, public IGameClient, public IEventListener virtual std::string getServerAddress(); virtual void slot44(int); virtual void restartDemo(); - virtual void setDemoPaused(bool paused); - virtual void slot50(); - virtual int slot54(); - virtual bool slot58(); + virtual void demoSwitchPlayer(bool next); + virtual void demoNextCamera(); + virtual int demoGetCurrentPlayerId(); + virtual bool demoIsFreeFlying(); virtual void togglePause(); virtual void setPause(bool paused); virtual bool getPause(); - virtual bool isDemoPlaying(); - virtual void slot6C(int a, int b); + virtual bool isDemoAtEnd(); + virtual void addDemoBookmark(const std::string& url, const std::string& mapName); virtual bool getDisconnectRequested(); virtual bool getIsReady(); virtual std::string getServerAddressCopy(); diff --git a/Code/BF2/Game/GameEvents/DropVehicleEvent.cpp b/Code/BF2/Game/GameEvents/DropVehicleEvent.cpp index 482a1d558..eab6620f7 100644 --- a/Code/BF2/Game/GameEvents/DropVehicleEvent.cpp +++ b/Code/BF2/Game/GameEvents/DropVehicleEvent.cpp @@ -43,16 +43,15 @@ DropVehicleEvent::DropVehicleEvent(float positionX, float positionZ, int team, b { } -#if !DEDICATED // PE7B2460, all16 instructions read. Do not delegate to the default ctor: -// the retail client does not initialize m_field15, even though serialize reads it. +// ELF 0x840F690 inlines the same producer in BFCommander::dropVehicle. +// shipped defect: m_field15 is not initialized, even though serialize reads it. DropVehicleEvent::DropVehicleEvent(int team, Vec2 position) : GameEvent() { m_positionX = position.x; m_positionZ = position.y; m_team = static_cast(team); } -#endif int DropVehicleEvent::getType() const { diff --git a/Code/BF2/Game/GameEvents/DropVehicleEvent.h b/Code/BF2/Game/GameEvents/DropVehicleEvent.h index 6da8a087a..6759a3594 100644 --- a/Code/BF2/Game/GameEvents/DropVehicleEvent.h +++ b/Code/BF2/Game/GameEvents/DropVehicleEvent.h @@ -16,10 +16,8 @@ class DropVehicleEvent : public GameEvent // 0x18 public: // [INFERRED] argument order - no ELF constructor exists. DropVehicleEvent(float positionX, float positionZ, int team, bool field15); -#if !DEDICATED - // Client PE7B2460 leaves the serialized byte+15 untouched. + // The commander producer leaves the trailing serialized byte untouched. DropVehicleEvent(int team, Vec2 position); -#endif DropVehicleEvent() : m_positionX(0.0f), m_positionZ(0.0f), m_team(0), m_field15(false) {} virtual ~DropVehicleEvent() {} diff --git a/Code/BF2/Game/GameLogic/CombatArea.cpp b/Code/BF2/Game/GameLogic/CombatArea.cpp index df099cccf..61563f5f3 100644 --- a/Code/BF2/Game/GameLogic/CombatArea.cpp +++ b/Code/BF2/Game/GameLogic/CombatArea.cpp @@ -85,5 +85,17 @@ bool CombatArea::checkPositionPolygon(const Vec3& position) const return inside; } +// ELF 0x81245E0. The first edge's left-hand normal offsets its midpoint. +bool CombatArea::isClockwise() const +{ + const float dx = m_points[1].x - m_points[0].x; + const float dz = m_points[1].y - m_points[0].y; + Vec3 position; + position.x = -dz + (m_points[1].x + m_points[0].x) * 0.5f; + position.y = 0.0f; + position.z = dx + (m_points[1].y + m_points[0].y) * 0.5f; + return !checkPositionPolygon(position); +} + } // namespace hfe } // namespace dice diff --git a/Code/BF2/Game/GameLogic/CombatArea.h b/Code/BF2/Game/GameLogic/CombatArea.h index 62e56d55e..4a4f4bda7 100644 --- a/Code/BF2/Game/GameLogic/CombatArea.h +++ b/Code/BF2/Game/GameLogic/CombatArea.h @@ -26,6 +26,9 @@ class CombatArea // Test the XZ position against the inclusive rectangle. bool checkPositionRect(const Vec3& position) const; + // Test the left side of the first polygon edge; requires at least two vertices. + bool isClockwise() const; + // Offsets describe the original 32-bit layout; STL-bearing layouts depend on the compiler. /* +0x00 */ int m_isPolygon; // 0 = rectangle, non-0 = polygon /* +0x04 */ float m_minX; diff --git a/Code/BF2/Game/GameLogic/CombatAreaManager.cpp b/Code/BF2/Game/GameLogic/CombatAreaManager.cpp index cac969aed..58332913d 100644 --- a/Code/BF2/Game/GameLogic/CombatAreaManager.cpp +++ b/Code/BF2/Game/GameLogic/CombatAreaManager.cpp @@ -295,5 +295,59 @@ void CombatAreaManager::addVehicleTimer(int vehicleCategory, float seconds) entry->second = seconds; } +// ELF 0x8125A00. The caller owns clearing the output vector. +bool CombatAreaManager::getAiCombatAreas(std::vector& areas) const +{ + for (unsigned int i = 0; i < m_areas.size(); ++i) + if (m_areas[i]->m_usedByPathFinding) + areas.push_back(m_areas[i]); + return areas.size() == 1; +} + +// ELF 0x8125890. The manager's player/team and enable filters do not apply here. +bool CombatAreaManager::isAiPositionInside(const Vec3& position, + const std::vector& areas) const +{ + bool anyInclusion = false; + bool inside = false; + for (unsigned int i = 0; i < areas.size(); ++i) + if (!areas[i]->m_isExclusion) + anyInclusion = true; + + if (!anyInclusion) + { + world::IHeightmap* heightmap = + static_cast(world::heightmapCluster)->getPrimaryHeightmap(); + int sizeX, sizeZ; + heightmap->getSize(sizeX, sizeZ); + // shipped defect: the dimensions are queried but never used to test the position. + inside = true; + } + + for (unsigned int i = 0; i < areas.size(); ++i) + { + CombatArea* area = areas[i]; + if (!area->m_isExclusion) + { + const bool hit = static_cast(area->m_isPolygon) + ? area->checkPositionPolygon(position) : area->checkPositionRect(position); + if (hit) + inside = true; + } + } + for (unsigned int i = 0; i < areas.size(); ++i) + { + CombatArea* area = areas[i]; + if (area->m_isExclusion) + { + const bool hit = static_cast(area->m_isPolygon) + ? area->checkPositionPolygon(position) : area->checkPositionRect(position); + if (hit) + inside = false; + } + } + return inside; +} + } // namespace hfe } // namespace dice diff --git a/Code/BF2/Game/GameLogic/CombatAreaManager.h b/Code/BF2/Game/GameLogic/CombatAreaManager.h index 665479747..99181f1cb 100644 --- a/Code/BF2/Game/GameLogic/CombatAreaManager.h +++ b/Code/BF2/Game/GameLogic/CombatAreaManager.h @@ -5,6 +5,7 @@ #include #include #include +#include "../../Math/Vec3.h" namespace dice { namespace hfe { @@ -24,6 +25,12 @@ class CombatAreaManager // Null players and players without a controllable vehicle return false. bool isPlayerInside(world::IPlayer* player); + // Append pathfinding-enabled areas; return true only when the resulting list has one area. + bool getAiCombatAreas(std::vector& areas) const; + + // Apply inclusions and then exclusions from a borrowed AI area list. + bool isAiPositionInside(const Vec3& position, const std::vector& areas) const; + // Return the category grace period in seconds. Null objects, ladders, and absent entries // use the default. A non-null object must have a valid template. float getTimeAllowedOutside(world::IObject* object); diff --git a/Code/BF2/Game/GameLogic/GameLogic.cpp b/Code/BF2/Game/GameLogic/GameLogic.cpp index d3dc96e35..cb7cc882f 100644 --- a/Code/BF2/Game/GameLogic/GameLogic.cpp +++ b/Code/BF2/Game/GameLogic/GameLogic.cpp @@ -4,6 +4,9 @@ #include "GameLogic.h" #include "../Main/Game.h" // isDedicated - loadCallback's client/server split +#if !DEDICATED +#include "../VoipClient/BF2VoipClient.h" // bf2VoipClient (ds:0x9A4DA0) +#endif #include "GameLogicCollision.h" // doImpact's exact static forwarding target #include "GameLogicExplosion.h" // common explosion presentation forwarder #include "../Objects/ObjectLayoutAccess.h" // heal / replenishAmmo walk +0x3C / +0x28 @@ -994,7 +997,7 @@ void GameLogic::removeStrategicObject(world::IObject* object) // future-state arm. PE uses the single-precision reciprocal of 30; ELF divides by 30. float GameLogic::getTimeToNextStateChange() { - if (m_nextStateChangeAtTick > WorldPref::getTickCount()) + if (m_nextStateChangeAtTick > static_cast(WorldPref::getTickCount())) { const unsigned int ticks = m_nextStateChangeAtTick - WorldPref::getTickCount(); #if defined(_WIN32) @@ -1231,9 +1234,9 @@ void GameLogic::setFogStartEndAndBase(const Vec4& value) IBase* const framework = classManager->getSingleton("PostProductionFrameWork"); if (framework) { - typedef void (__fastcall* SetStateVec4Fn)(void* self, void* edx, const Vec4* value); + typedef void (__thiscall* SetStateVec4Fn)(void* self, const Vec4* value); void** const vtbl = *reinterpret_cast(framework); - reinterpret_cast(vtbl[0x24 / sizeof(void*)])(framework, 0, &value); + reinterpret_cast(vtbl[0x24 / 4])(framework, &value); } } @@ -2229,6 +2232,11 @@ GameLogic::~GameLogic() m_voipQuality = 3; // +0x180 m_voipEnabled = false; // +0x170 m_isVoipClientRunning = false; // +0x17C +#if !DEDICATED + // BF2.exe 0x4F629E..0x4F62B3: the client also shuts its voice session down here. + if (!isDedicated() && bf2VoipClient) + bf2VoipClient->shutdown(); // +0x68 +#endif if (world::supplyDropManager) // ds:0x8AADAAC world::supplyDropManager->reset(); @@ -3035,6 +3043,14 @@ void GameLogic::handleExplosion(Vec3 position, float radius, int material, float canTK, includeSource); } +// BF2.exe 0x4ED60B..0x4ED6C2 (client): every return after the kill latch passes here. Retail's client +// zeroes the Falcon's force effects on the local human player's death; none exists without the archived +// device (Code/Archive/NovintFalcon), so, as in the dedicated image (ELF), this only returns. +static bool finishKillPlayer(world::IPlayer*) +{ + return true; +} + // Marks a player dead, publishes death events, dismounts vehicles and updates the death camera. // Returns false only for a null player. Vehicle exit repeats until the free camera is reached. // Ladder/zipline parents must expose a player-control object; required camera and vehicle @@ -3122,7 +3138,7 @@ bool GameLogic::killPlayer(world::IPlayer* player, bool a4, bool a5) const int status = m_gameStatus; if (status == 2 || status == 5) - return true; + return finishKillPlayer(player); // killer credit - the armor walk starts from the post-loop vehicle world::IArmorGLComp* armor = 0; @@ -3146,14 +3162,14 @@ bool GameLogic::killPlayer(world::IPlayer* player, bool a4, bool a5) world::IObject* const soldier = player->getDefaultVehicle(); // vt +0xA4 if (!soldier) - return true; + return finishKillPlayer(player); if (world::object_detail::LayoutAccess::objectTemplate(soldier)->getClassID() == world::CID_SoldierTemplate) { if (!armor) - return true; + return finishKillPlayer(player); if (armor->isDestroyed()) // +0x54 - return true; + return finishKillPlayer(player); Vec3 up; up.x = 0.0f; up.y = 1.0f; up.z = 0.0f; Vec3 zero; zero.x = 0.0f; zero.y = 0.0f; zero.z = 0.0f; @@ -3168,7 +3184,7 @@ bool GameLogic::killPlayer(world::IPlayer* player, bool a4, bool a5) armor->fullDestroy(); // +0x100 } } - return true; + return finishKillPlayer(player); } // Base defaults. Keep declared return types until callers or both images establish @@ -3182,7 +3198,19 @@ bool GameLogic::giveDamage(world::IObject*, float, world::IPlayer*, bool GameLogic::reSpawnPlayer(world::IPlayer*) { return false; } // xor eax,eax bool GameLogic::selectSpawnGroup(world::IPlayer*, int) { return false; } // xor eax,eax bool GameLogic::selectTeam(world::IPlayer*, int) { return false; } // xor eax,eax -void GameLogic::startupVoipClient() {} +// BF2.exe 0x4EC300 (client): starts the voice session the server announced, once. The dedicated +// image's body is empty (ELF), as is a dedicated run of the client image (isDedicated, 0x440510). +// Retail answers a bool nobody reads; the interface keeps the void slot. +void GameLogic::startupVoipClient() +{ +#if !DEDICATED + if (isDedicated() || m_isVoipClientRunning || !m_voipEnabled || !bf2VoipClient) + return; + if (bf2VoipClient->startSession(m_voipServerAddress, m_voipServerPort, m_voipBFClientPort, + m_voipQuality, true)) // +0x2C + m_isVoipClientRunning = true; +#endif +} // Forwards all impact arguments to GameLogicCollision. Dedicated images retain // its empty effect implementation. The final flag skips the underwater test. diff --git a/Code/BF2/Game/GameLogic/GameLogicCollision.cpp b/Code/BF2/Game/GameLogic/GameLogicCollision.cpp index 659a28827..b6c933448 100644 --- a/Code/BF2/Game/GameLogic/GameLogicCollision.cpp +++ b/Code/BF2/Game/GameLogic/GameLogicCollision.cpp @@ -30,6 +30,8 @@ #include "../Objects/ISoldier.h" // the man-down retraction's getOccupingPlayer #include "../Objects/Projectiles/GenericProjectile.h" // the sole IProjectileObject implementor #include "../../Core/System.h" // WorldPref::getTickCount +#include "../../AI/AIInterface/BFKnowledge/BFCollisionHandler.h" // the AI collision courier +#include "../../AI/AIDLL/AI/Main/CommonSingletonServer.h" // m_iBFCollisionHandler #if !DEDICATED // The client bodies of doImpact / playCollisionEffect (BF2.exe 0x5CADF0 / 0x5CA9C0 / 0x5CA910). #include "../Main/Game.h" // isDedicated() - BF2.exe 0x440510 @@ -46,8 +48,6 @@ namespace dice { namespace hfe { namespace world { extern IBase* materialManager; } // ds:0x8AD2820 - Core/Globals.cpp -namespace ai { extern IBase* g_bfCollisionHandler; } // ds:0x8AC35E4 - Core/Globals.cpp, and - // declared the same way in GenericProjectile.cpp namespace world { @@ -121,18 +121,6 @@ void normaliseIfNeeded(Vec3& v) } inline MaterialManager* materials() { return static_cast(materialManager); } -// [FRONTIER] [TEMP] [CHOSEN, not recovered] Stops at the opaque AI collision -// courier: object-hit and terrain-hit argument lists are unresolved. -// Reachable when g_bfCollisionHandler is populated. -// [RETIRE-WHEN: bfcollisionhandler-iface] Recover the complete typed interface, -// including projectile removal, before replacing this boundary. -[[noreturn]] void bfCollisionHandlerFrontier(const char* what) -{ - std::fprintf(stderr, - "[FRONTIER] dice::hfe::world::GameLogicCollision AI collision courier: %s\n", what); - std::fflush(stderr); - std::abort(); -} #if !DEDICATED // Builds a plane from normal and point, preserving (z + y) + x dot-product order. @@ -844,8 +832,10 @@ bool GameLogicCollision::serverHandleCollisionForProjectile(IObject* projectile, proj, projectile, hitObject, armor, damaged, faceB); } - if (ai::g_bfCollisionHandler) - bfCollisionHandlerFrontier("object hit (IBFCollisionHandler +0x0C)"); + // ELF 0x80DD04A: the AI collision handler hears the object hit (+0x0C) at the contact. + if (ai::IBFCollisionHandler* const collision = static_cast( + ai::CommonSingletonServer::m_iBFCollisionHandler)) + collision->handleCollision(projectile, hitObject, contact); } else { @@ -860,8 +850,15 @@ bool GameLogicCollision::serverHandleCollisionForProjectile(IObject* projectile, proj, projectile, 0, 0, false, faceB); } - if (ai::g_bfCollisionHandler) - bfCollisionHandlerFrontier("terrain hit (IBFCollisionHandler +0x30)"); + // ELF 0x80DD468: a terrain hit is a miss (+0x30): the owner's id (-1 without one), the + // round and its object id, the contact. + if (ai::IBFCollisionHandler* const collision = static_cast( + ai::CommonSingletonServer::m_iBFCollisionHandler)) + { + IPlayer* const owner = gp->getPlayer(); // +0x54 + collision->handleProjectileMiss(owner ? owner->getId() : -1, projectile, + projectile->getObjectId(), contact); + } } // ricochet / penetrate diff --git a/Code/BF2/Game/GameLogic/GameLogicDamage.cpp b/Code/BF2/Game/GameLogic/GameLogicDamage.cpp index 5d1095def..410950f12 100644 --- a/Code/BF2/Game/GameLogic/GameLogicDamage.cpp +++ b/Code/BF2/Game/GameLogic/GameLogicDamage.cpp @@ -401,15 +401,18 @@ void GameLogicDamage::serverGiveDamage(IObject* object, float damage, IPlayer* a victims.push_back(seatPlayer); } - // The vestigial client block - see the header. Virtual calls kept, results dropped. + // The Falcon "Damage" envelope's inputs (BF2.exe 0x5E64A3..0x5E66A2, ledger N2 17b): the + // look-at frame from the owner to the hit and the owner's three rows. As in the ELF, the calls + // stay and the haptic block itself is gone (archived device, Code/Archive/NovintFalcon). { Mat4 lookAt = Mat4::getIdentity(); - owner->getAbsoluteTransformation(); // +0x84 - owner->getAbsoluteTransformation(); - owner->getAbsoluteTransformation(); + owner->getAbsoluteTransformation(); // +0x84 (row 2) + owner->getAbsoluteTransformation(); // (row 0) + const Mat4& ownerTransform = owner->getAbsoluteTransformation(); // (row 1) Vec3 up = { 0.0f, 1.0f, 0.0f }; calcLookAtMatrix(lookAt, owner->getAbsolutePosition(), position, up); - playerManager->getLocalHumanPlayer(); // +0x30 + IPlayer* const localPlayer = playerManager->getLocalHumanPlayer(); // +0x30 + (void) localPlayer; (void) ownerTransform; if (attacker && seatPlayer && attacker != seatPlayer) { seatPlayer->getTeam(); @@ -427,8 +430,8 @@ void GameLogicDamage::serverGiveDamage(IObject* object, float damage, IPlayer* a { Vec3 pos = position; const unsigned int weaponId = weapon->getObjectId(); // +0x10 - // ..539 / PE 58763F..684: registered IBFCollisionHandler, - // not the independent chosen g_bfCollisionHandler storage. Vec3 is + // ..539 / bf2_w32ded.exe 0x58763F..684: the registered IBFCollisionHandler, the same + // variable (w32ded 0x8B7030, BF2.exe 0xA38688) every other engine report reads. Vec3 is // BY value (mangling and PE's twelve stack bytes); GCC passes its copy // indirectly. The typed call preserves the native compiler's ABI. collisionHandler->handleProjectileDamage(owner, damage, seatPlayer->getId(), weaponId, pos); diff --git a/Code/BF2/Game/GameLogic/GameLogicExplosion.cpp b/Code/BF2/Game/GameLogic/GameLogicExplosion.cpp index 9c78e9159..700f61b98 100644 --- a/Code/BF2/Game/GameLogic/GameLogicExplosion.cpp +++ b/Code/BF2/Game/GameLogic/GameLogicExplosion.cpp @@ -37,12 +37,13 @@ #include "../../Scene/Object/PlayerManager.h" #include "../../Scene/Object/ObjectTypes/Game/IPlayerControlObject.h" #include "../../Sound/BfSound.h" +#include "../../Platform/MsvcRand.h" // [CHOSEN, not recovered] the client CRT's rand (MSVCR71) +#include "../../AI/AIInterface/BFKnowledge/BFCollisionHandler.h" +#include "../../AI/AIDLL/AI/Main/CommonSingletonServer.h" // m_iBFCollisionHandler namespace dice { namespace hfe { -namespace ai { extern IBase* g_bfCollisionHandler; } - namespace world { extern IBase* materialManager; @@ -166,15 +167,6 @@ class FlagIgnoreWaterPredicator : public ObjectFlagPredicator } }; -// IBFCollisionHandler remains an AI-only interface frontier. -[[noreturn]] void bfCollisionHandlerFrontier() -{ - std::fprintf(stderr, - "[FRONTIER] dice::hfe::world::GameLogicExplosion AI explosion courier reached\n"); - std::fflush(stderr); - std::abort(); -} - GenericProjectile* projectileFromObject(IObject* object) { if (!object) @@ -443,8 +435,12 @@ bool GameLogicExplosion::serverHandleExplosionOnObject( return false; IPlayerControlObject* const pco = findPco(root); - if (player && ai::g_bfCollisionHandler && weapon) - bfCollisionHandlerFrontier(); + // ELF 0x80E375E: the AI hears the queued damage (+0x20), the explosion position by value. + ai::IBFCollisionHandler* const collision = + static_cast(ai::CommonSingletonServer::m_iBFCollisionHandler); + if (player && collision && weapon) + collision->handleExplosionDamage(object, calculatedDamage, player->getId(), + weapon->getObjectId(), explosionPosition); if (!pco) return false; @@ -559,7 +555,7 @@ bool GameLogicExplosion::handleExplosionForceOnObject( if (isSoldier) { radial.y += *g_explosionSoldierForceYMod; - strength *= static_cast(std::rand() % 100) / 200.0f + 0.8f; + strength *= static_cast(bf2crt::rand() % 100) / 200.0f + 0.8f; } const float existingForce = length(node->getPositionalAcceleration()); diff --git a/Code/BF2/Game/GameLogic/Player.cpp b/Code/BF2/Game/GameLogic/Player.cpp index d958a4b00..0b384f288 100644 --- a/Code/BF2/Game/GameLogic/Player.cpp +++ b/Code/BF2/Game/GameLogic/Player.cpp @@ -10,6 +10,9 @@ #include "../../IO/Stream/IStream.h" #include "ClientGameLogic.h" // getAutoInput's runtime !isServer() arm #include "../Main/Game.h" // isDedicated() - updateClientSettings' client arm +#if !DEDICATED +#include "../VoipClient/BF2VoipClient.h" // bf2VoipClient (ds:0x9A4DA0) - setVoipSessionId +#endif #include "../GeneralSettings.h" // IGeneralSettings::getAutoReload - updateClientSettings #include "../../Core/ClassManager.h" #include "../../Core/EventManager.h" @@ -73,10 +76,15 @@ #include "../Objects/GameLogicComp/IArmorGLComp.h" // getDefaultMaterial #include "../../Scene/Object/ObjectTypes/Game/IPlayerControlObject.h" #include "ActionBuffer.h" // sizeof 0x2C - ditto +#if !DEDICATED +// BF2.exe 0x5ED220: client tutorial owner. +#include "PlayerVOHelp.h" +#endif namespace dice { namespace hfe { +#if DEDICATED // [INFERRED] Client voice-over tutorial state owned by Player. Dedicated players leave it null. // The constructor and help/update behavior remain declaration-only; the trailing pairs store // message intervals and countdowns. @@ -97,6 +105,7 @@ struct PlayerVOHelp std::string labels[82]; // +0x200 on both ports; let the host STL determine stride. struct Timer { float interval, remaining; } timers[82]; }; +#endif // ds:0x8ACBFA4 - Core/Globals.cpp owns it, declared IBase* with no layout. Same // declaration GameLogic.cpp:1028 uses; the two must stay identical or MSVC mangles two @@ -230,9 +239,7 @@ Player::Player(int index, world::CPersistentExplosionEffectManager* explosionEff , m_profileId(0) , m_field2E0(1.0f) , m_field2E4(0.0f) - , m_field2E8(0) - , m_field2EC(0) - , m_field2F0(0) + , m_tearGasPosition() , m_field2F4(0.0f) , m_field2F8(1.0f) , m_gasDamage(0.0f) @@ -293,6 +300,15 @@ Player::Player(int index, world::CPersistentExplosionEffectManager* explosionEff // io::INetworkable's +0x18 slot, not a private helper - see Player.h. init(0); +#if !DEDICATED + // BF2.exe 0x505D20..0x505D52. + if (!isDedicated()) + { + m_voHelp = new PlayerVOHelp(); + m_voHelp->loadPlayed(); + } +#endif + // Retail also sets a networkable-base float to -1 here; that field has no exposed accessor // in this model. Notify AI of the player only when its singleton exists. if (ai::g_aiInstance) @@ -502,8 +518,9 @@ void Player::updateStateMask(unsigned int* mask) c->buff[149] = static_cast(m_field160[4]); // heal / gave-ammo "recent" flags: set for the 10 ticks after the event (unsigned compare) - if (static_cast(m_healRepairedAtTick + 10) > WorldPref::getTickCount()) *mask |= 0x80000u; - if (static_cast(m_gaveAmmoAtTick + 10) > WorldPref::getTickCount()) *mask |= 0x100000u; + const unsigned int tick = static_cast(WorldPref::getTickCount()); + if (static_cast(m_healRepairedAtTick + 10) > tick) *mask |= 0x80000u; + if (static_cast(m_gaveAmmoAtTick + 10) > tick) *mask |= 0x100000u; // team -> buff[16] - bit 0x200, with a 20-frame re-send after a team change (mask[1]&2) slotDword(c, 16) = m_team; @@ -1947,21 +1964,13 @@ void Player::handleGasClouds(float deltaTime) if (!particleSystemManager) return; - // [PLATFORM] This plugin boundary uses RendDX9's MSVC 7.1 vector carrier: allocator at +0, - // begin at +4, end at +8. Do not cast it to a native std::vector; the ELF container differs. + // The renderer's active-instance vector, shared by reference (issue #7). const geom::ParticleSystemInstanceList* const systems = particleSystemManager->getInstances(); - // The PE re-reads the vector words on every iteration and breaks on a null begin; retain - // those repeated reads rather than snapshotting a container that instance calls may mutate. - for (unsigned int i = 0; ; ++i) + // The PE re-reads the vector's size on every iteration; retain that rather than snapshotting + // a container that instance calls may mutate. + for (unsigned int i = 0; i < static_cast(systems->size()); ++i) { - geom::IParticleSystemInstance* const* const first = systems->begin(); - if (!first) - break; - geom::IParticleSystemInstance* const* const last = systems->end(); - if (i >= static_cast(last - first)) - break; - - geom::IParticleSystemInstance* const system = systems->begin()[i]; + geom::IParticleSystemInstance* const system = (*systems)[i]; if (!system->getTemplate()->getGasCloudType()) continue; @@ -2192,10 +2201,7 @@ void Player::setBlurryVision(float fadeTime, float holdTime, float damage) if (vehicle) { const Vec3& position = vehicle->getAbsolutePosition(); - // These existing three dword carriers hold float bits, not numeric integers. - std::memcpy(&m_field2E8, &position.x, sizeof(float)); - std::memcpy(&m_field2EC, &position.y, sizeof(float)); - std::memcpy(&m_field2F0, &position.z, sizeof(float)); + m_tearGasPosition = position; } } m_field2E4 = damage; @@ -2494,7 +2500,32 @@ const world::IObjectTemplate* Player::getPersonalDecalTemplate() const } // Dedicated-image VO-help hooks are inert; the played query always returns true. -// These bodies do not implement client tutorial playback. +#if !DEDICATED +// PE slots +0x210..+0x21C correspond to ELF +0x214..+0x220: ELF has two destructor slots. +// BF2.exe 0x4F9F00. +void Player::enableVOHelp(bool enabled) +{ + if (m_voHelp) + m_voHelp->enable(enabled); +} +// BF2.exe 0x4F9F20. +void Player::enableVOHelpMessage(int id) +{ + if (m_voHelp) + m_voHelp->disableMessage(id, false); +} +// BF2.exe 0x4F9F40. +void Player::disableVOHelpMessage(int id) +{ + if (m_voHelp) + m_voHelp->disableMessage(id, true); +} +// BF2.exe 0x4F9F60. +bool Player::getVOHelpMessagePlayed(int id) +{ + return m_voHelp && m_voHelp->messagePlayed(id); +} +#else void Player::enableVOHelp(bool) { } @@ -2511,6 +2542,7 @@ bool Player::getVOHelpMessagePlayed(int) { return true; } +#endif // Rename through PlayerManager before changing the local name. Duplicate names // are silently rejected. @@ -2633,6 +2665,11 @@ unsigned short Player::getVoipSessionId() void Player::setVoipSessionId(unsigned short sessionId) { m_voipSessionId = sessionId; +#if !DEDICATED + // BF2.exe 0x4FA481..0x4FA4A2: the local player's id is also the voice client's header id (+0x60). + if (bf2VoipClient && this == world::playerManager->getLocalHumanPlayer()) + bf2VoipClient->setPlayerId(sessionId); +#endif } // . IPlayer +0x98. One load - IPlayer.h already recorded "(Player +0x158)". @@ -3610,6 +3647,23 @@ bool Player::getIsSquadLeader() const return m_isSquadLeader; // byte +0xF5 } +// [INFERRED] The client tests the new value through a code-virtualised predicate pair before the +// keep-alive (0x502D50/0x502DB0 -> 0x4FD280/0x4FD380, bodies not statically readable). The same +// stubs, called as 0x502F30(x, x), produce the stored flag where the ELF stores `x != 0`, so the +// keep-alive test is read as `x != 0`. The periodic keep-alive (3 s) covers any other reading. +static void voipKeepAliveOnRoleChange(int value, bool localOnly, const world::IPlayer* self) +{ +#if !DEDICATED + if (isDedicated() || value == 0) + return; + if (localOnly && self != world::playerManager->getLocalHumanPlayer()) + return; + bf2VoipClient->sendKeepAlive(); // +0x58, no null test (the client always has one) +#else + (void)value; (void)localOnly; (void)self; +#endif +} + // Normalize the public squad id to 16 bits before applying membership side effects. void Player::setSquadId(unsigned int id) { @@ -3631,6 +3685,8 @@ void Player::setSquadId(unsigned short id) if (gameLogic->isServer() && !m_isAI) VoipServerConnection::GetInstance()->UpdatePlayerRouting(this); + + voipKeepAliveOnRoleChange(id, false, this); // PE 0x5040C0..0x5040E6 } // / PE 0x4746B0, 24 B. The bool is explicitly normalised to an int. @@ -3648,6 +3704,8 @@ void Player::setIsSquadLeader(int leader) VoipServerConnection::GetInstance()->UpdatePlayerRouting(this); static_cast(squadManager)->updateOrderMarkers(this); + + voipKeepAliveOnRoleChange(leader, false, this); // PE 0x504145..0x504169 } // / PE 0x4746D0, 24 B. The bool is explicitly normalised to an int. @@ -3675,6 +3733,8 @@ void Player::setIsCommander(int commander) if (gameLogic->isServer()) VoipServerConnection::GetInstance()->UpdatePlayerRouting(this); + + voipKeepAliveOnRoleChange(commander, true, this); // PE 0x504248..0x50427B, local player only } // . IPlayer +0x10C. The same shape one field over, and the very next call in @@ -4135,11 +4195,20 @@ void Player::update(float deltaTime) // 1 & 2: the persistent explosion effects world::explosionEffectManager->handleObject(this); - // [PLATFORM] The client additionally updates an unidentified member before local - // explosion effects. That client-only call remains unimplemented. - // [RETIRE-WHEN: player-update-client-arm] Identify the member and recover its update. +#if !DEDICATED + // BF2.exe 0x505340..0x505385. + // PE +0x58 is getIsRemote (ELF +0x5C), not getIsAIPlayer. if (this == world::playerManager->getLocalHumanPlayer() && !getIsRemote()) + { + if (m_voHelp) + m_voHelp->update(deltaTime); world::explosionEffectManager->updateExplosionEffects(deltaTime); + } +#else + // The dedicated image updates only the local explosion effects here. + if (this == world::playerManager->getLocalHumanPlayer() && !getIsRemote()) + world::explosionEffectManager->updateExplosionEffects(deltaTime); +#endif // 3: a dead player is not inside a control point if (!getIsAlive() && m_isInsideCP) @@ -4904,9 +4973,10 @@ void Player::setFlagHolder(bool holder) { m_flagHolder = holder; } bool Player::getFlagHolder() const { return m_flagHolder; } // +0x124 // the firing trio: 0x80F9390 / 0x80F93E0 / 0x80F9410 -// getFiringState IS NOT AN accessor. It ORs the live firing bool with a second field at +0x204, -// so a player counts as firing when either is set. [UNRESOLVED] what +0x204 is - the ctor zeroes it -// and nothing recovered writes it - but the OR is compiled and is reproduced. +// getFiringState IS NOT AN accessor. It ORs the live firing bool with the primary-fire press latch +// at +0x204 (PE 0x504D00: +0x184 || +0x234), so a player counts as firing when either is set. The +// client's network apply sets the latch for a remote press; GameClient::stepWorld clears it once +// it has been read (PE 0x5C056A). bool Player::getFiringState() const { return m_field160[0] != 0 || m_field204 != 0; // +0x160 || +0x204 diff --git a/Code/BF2/Game/GameLogic/Player.h b/Code/BF2/Game/GameLogic/Player.h index 75f2c3ab4..d91bf4b6f 100644 --- a/Code/BF2/Game/GameLogic/Player.h +++ b/Code/BF2/Game/GameLogic/Player.h @@ -360,6 +360,14 @@ class Player : public world::IPlayer, public io::IConsoleSaveable, public io::Ne // Applies decoded remote weapon ammunition state to the player's live weapons. void forceSetRemoteClientAmmo(unsigned int firedMask); + // The position captured when a tear-gas exposure starts (see m_tearGasPosition). + // [CHOSEN, not recovered] Neither image has this accessor: the retail AI image reads the three + // floats at raw x86 offsets +0x2E8/+0x2EC/+0x2F0 of the world::IPlayer it gets from + // IAIPlayer::getPlayer (BBPAvoidCollisionInfantery::createPlan, libaidll 0x22E304..0x22E310, + // three `flds`). The inline accessor gives the native AI image the same field without copying + // x86 offsets. + const Vec3& getTearGasPosition() const { return m_tearGasPosition; } + private: // Non-vtable Player helpers, all attested by their ELF manglings and direct callers. Keeping // these private avoids inventing a wider gameplay API for implementation details. @@ -387,6 +395,9 @@ class Player : public world::IPlayer, public io::IConsoleSaveable, public io::Ne // Zipline::detachSoldier writes the same raw world-time cooldown in both shipped ports // (ELF 0x81D0680 / PE 0x57CF30). Narrow friend, no setter. friend class world::Zipline; + // GameClient::stepWorld consumes the remote primary-fire press latch (+0x204) inline + // (PE 0x5C056A). Narrow friend, no setter. + friend class GameClient; protected: @@ -564,9 +575,11 @@ class Player : public world::IPlayer, public io::IConsoleSaveable, public io::Ne /* +0x2D8 */ int m_profileId; // 0 /* +0x2E0 */ float m_field2E0; // 1.0f NOT 0 /* +0x2E4 */ float m_field2E4; // 0; gas damage per second [UNRESOLVED name] - /* +0x2E8 */ int m_field2E8; // 0 - /* +0x2EC */ int m_field2EC; // 0 - /* +0x2F0 */ int m_field2F0; // 0 + // +0x2E8..+0x2F0: one Vec3, zeroed by the constructor; setBlurryVision (bf2 0x80F6890, + // 0x80F691D..0x80F693A) copies the three words of the default vehicle's getAbsolutePosition + // (+0x6C) through a base register at +0x2E8 when a gas exposure starts; the AI image reads + // them as floats. No other writer in the bf2 image. [INFERRED] name. + /* +0x2E8 */ Vec3 m_tearGasPosition; // (0, 0, 0) /* +0x2F4 */ float m_field2F4; // 0; blur fade countdown [UNRESOLVED name] /* +0x2F8 */ float m_field2F8; // 1.0f NOT 0 /* +0x2FC */ float m_gasDamage; // 0 diff --git a/Code/BF2/Game/GameLogic/PlayerVOHelp.cpp b/Code/BF2/Game/GameLogic/PlayerVOHelp.cpp new file mode 100644 index 000000000..a02dfb51c --- /dev/null +++ b/Code/BF2/Game/GameLogic/PlayerVOHelp.cpp @@ -0,0 +1,1010 @@ +// [INFERRED] Client tutorial implementation and placement. BF2.exe is the reference; +// the symbolized dedicated ELF has no corresponding tutorial owner. +#include +#include +#include +#include + +#include "PlayerVOHelp.h" + +#if !DEDICATED +#include "GameLogic.h" +#include "VoiceMessages.h" +#include "../Main/Game.h" +#include "../Main/BF2ClientSeams.h" +#include "../GeneralSettings.h" +#include "../LocalProfileManager.h" +#include "../Objects/IObject.h" +#include "../Objects/IPlayer.h" +#include "../Objects/ISoldier.h" +#include "../Objects/ICameraObject.h" +#include "../Objects/IWeaponObject.h" +#include "../Objects/HelpHudCompTemplate.h" +#include "../Objects/IWeaponHudComp.h" +#include "../Objects/WeaponHudCompTemplate.h" +#include "../Objects/Game/Kit.h" +#include "../Objects/IVehicleHudComp.h" +#include "../Objects/ObjectLayoutAccess.h" +#include "../Objects/Game/EntryPoint.h" +#include "../Objects/GameLogicComp/IArmorGLComp.h" +#include "../../Scene/Object/ObjectTypes/Game/IPlayerControlObject.h" +#include "../Objects/ObjectTemplate.h" +#include "../../Core/Random.h" +#include "../../Core/SettingsRepostitory.h" +#include "../../Core/Ids.h" +#include "../../Core/System.h" +#include "../../Core/StringUtil.h" +#include "../../Sound/BfSound.h" +#include "../../Sound/NullSound.h" +#include "../../Scene/Object/PlayerManager.h" +#include "../../Scene/Object/ObjectManager.h" +#include "../../Scene/Object/ObjectPredicator.h" +#include "../../AI/AIInterface/SingletonServer.h" +#include "../../AI/AIInterface/IAIPlayerCourier.h" +#include "../../Menu/BF2HudManager.h" +#include "../../Menu/HudAmmo.h" +#include "../../Menu/HudVehicleInformation.h" + +namespace dice { namespace hfe { + +namespace { +// [CHOSEN, not recovered] Owner-requested +help 0/1 outranks the profile for this session. +// Both tutorial publication paths share the override; General.con keeps the profile value. +bool showTutorialMessages() +{ + if (settings->boolExists("GSCommandLineShowTutorialMessages")) + return settings->boolGet("GSCommandLineShowTutorialMessages", true); + return static_cast(static_cast(g_generalSettings)) + ->getShowTutorialMessages(); +} + +// BF2.exe 0x43FFA0/0x440030; preserve the shared Rand draw and signed shift. +float helpRandom(float scale, float offset) +{ + const int value = (static_cast(Rand.getRaw() | 0x80u) >> 7) + 1; + return static_cast(static_cast(value) * scale + offset); +} +} + +// BF2.exe 0x5EDF21, repeated in cases 54/55/69/76/77. No component query. +world::IHelpHudComp* PlayerVOHelp::helpComponent(world::IObject* object) +{ + return static_cast(world::object_detail::LayoutAccess::helpHudComponent(object)); +} +// BF2.exe 0x5EDF2D. +bool PlayerVOHelp::hasAbilityHud(world::IObject* object) +{ + return world::object_detail::LayoutAccess::abilityHudComponent(object) != 0; +} +// BF2.exe 0x5EDF55/0x5EE308/0x5EE54F/0x5EFF4C: retain getHudInfo dispatch. +// Its borrowed result is the embedded info block; use the owning type's offset +// so the adjacent scalar reads follow this compiler's STL and pointer layout. +const world::HelpHudCompTemplate* PlayerVOHelp::helpTemplate(world::IHelpHudComp* help) +{ + return reinterpret_cast( + reinterpret_cast(help->getHudInfo()) - + offsetof(world::HelpHudCompTemplate, m_helpHudInfo)); +} +// BF2.exe 0x5EDF58/0x5EFF4F/0x5EE30B/0x5EE552: info +188/+189/+18A/+18B. +bool PlayerVOHelp::helpActive(world::IHelpHudComp* help, int kind) +{ + const world::HelpHudCompTemplate* componentTemplate = helpTemplate(help); + switch (kind) + { + case 0: return componentTemplate->m_isActive; + case 1: return componentTemplate->m_altIsActive; + case 2: return componentTemplate->m_lowArmorIsActive; + default: return componentTemplate->m_lowAmmoIsActive; + } +} +// BF2.exe 0x5EF98D/0x5EF990: getHudInfo, then signed integer at info +190. +int PlayerVOHelp::helpDistance(world::IHelpHudComp* help) +{ + return helpTemplate(help)->m_closeToDistance; +} +// BF2.exe 0x5EE7AB/0x5EE7D0: HudAmmo +B4, preserving both caller reads. +float PlayerVOHelp::helpPrimaryAmmo(hud::HudAmmo* ammo) +{ + return ammo->m_field0b4; +} + +namespace { +// BF2.exe 0x5DEC70. [INFERRED] helper name. This search ignores team and entry +// radius; prefer the nearest empty seat, retaining the nearest AI-occupied fallback. +world::IPlayerControlObject* findNearbyControl(const Vec3& origin, world::IPlayer* player, float radius) +{ + if (player && player->getIsAIPlayer()) + { + radius = 15.0f; + static_cast(ai::BFSingletonServer::m_iaiPlayerCourier) + ->getRequestedVehicle(player->getId()); + } + std::vector& scratch = world::objectManager->getObjectTempVector(); + std::vector().swap(scratch); + float nearestEmpty = 100000.0f, nearestAI = 100000.0f; + world::IPlayerControlObject* empty = 0; + world::IPlayerControlObject* aiOccupied = 0; + world::ObjectFlagPredicator predicator(0x200); + std::vector candidates; + world::objectManager->getObjectsFromGrid(origin, radius, scratch, &predicator); + for (world::IObject* object : scratch) + candidates.push_back(object); + world::objectManager->getNoCollisionObjectsFromGrid(origin, radius, scratch, &predicator); + for (world::IObject* object : scratch) + candidates.push_back(object); + for (world::IObject* object : candidates) + { + const Vec3& position = object->getAbsolutePosition(); + const float x = position.x - origin.x; + const float y = position.y - origin.y; + const float z = position.z - origin.z; + const float distance = std::sqrt(z * z + (y * y + x * x)); + if (distance > radius || distance > nearestEmpty) + continue; + world::IArmorGLComp* armor = 0; + for (world::IObject* parent = object; parent; parent = parent->getParent()) + if ((armor = static_cast(parent->getArmorComponent()))) + break; + if (armor && armor->isDestroyed()) + continue; + world::IObject* root = world::getRootParent(object ? + static_cast(object->queryInterface(world::IID_IObject)) : 0); + world::IPlayerControlObject* pco = world::findOwningPlayerControlObject(root); + if (!pco) + continue; + auto* seats = pco->getPcos(); + for (const auto& entry : *seats) + { + world::IPlayerControlObject* seat = entry.second; + if (!seat->isOccupied()) + { + nearestEmpty = distance; + empty = seat; + break; + } + if (seat->getOccupingPlayer()->getIsAIPlayer() && distance < nearestAI) + { + nearestAI = distance; + aiOccupied = seat; + } + } + } + return empty ? empty : aiOccupied; +} +} + +// BF2.exe 0x5ED220. +PlayerVOHelp::PlayerVOHelp() + : messageActive(false), messageDuration(10.0f), messageElapsed(0.0f), + enabled(false), onFoot(false) +{ + for (int i = 0; i < 82; ++i) + timers[i].interval = timers[i].remaining = 0.03333333507180214f; + for (bool& value : played) + value = false; + for (bool& value : disabled) + value = false; + for (int& value : minimumExperience) + value = 0; + nextMessageDelay = helpRandom(0.00000178813934326171875f, 10.0f); + + labels[0] = "HUD_HELP_PLAYER_CONTROLS_moveMouseToLook"; + labels[1] = "HUD_HELP_PLAYER_CONTROLS_moveForwardsBackwards"; + labels[2] = "HUD_HELP_PLAYER_CONTROLS_fireLeftMouse"; + labels[3] = "HUD_HELP_WEPAON_HANDHELD_GENERAL_reloadWeapon"; + labels[4] = "HUD_HELP_PLAYER_CONTROLS_zoomAltFire"; + labels[5] = "HUD_HELP_PLAYER_CONTROLS_jump"; + minimumExperience[5] = 7200; + labels[6] = "HUD_HELP_PLAYER_CONTROLS_crouch"; + minimumExperience[6] = 18000; + labels[7] = "HUD_HELP_PLAYER_CONTROLS_lieDown"; + disabled[7] = true; + labels[8] = "HUD_HELP_PLAYER_CONTROLS_strafeLeftRight"; + minimumExperience[8] = 7200; + labels[9] = "HUD_HELP_SQUAD_squadJoined"; + labels[10] = "HUD_HELP_SPAWNSCREEN_SQUADTAB_createSquad"; + minimumExperience[10] = 36000; + labels[11] = "HUD_HELP_SQUAD_squadCreated"; + disabled[11] = true; + labels[12] = "HUD_HELP_SPAWNSCREEN_SQUADTAB_joinSquad"; + disabled[12] = true; + labels[13] = "HUD_HELP_PLAYER_CONTROLS_parachute"; + labels[14] = "HUD_HELP_MENU_CONTROLS_callMedicWhenManDown"; + labels[15] = "HUD_HELP_MENU_CONTROLS_COMMOROSE_slcommoRoseAvailable"; + labels[16] = "HUD_HELP_COMMANDER_placeArtillery"; + disabled[16] = true; + labels[17] = "HUD_HELP_COMMANDER_placeSupplies"; + disabled[17] = true; + labels[18] = "HUD_HELP_COMMANDER_placeUAV"; + disabled[18] = true; + labels[19] = "HUD_HELP_COMMANDER_artilleryFired"; + disabled[19] = true; + labels[20] = "HUD_HELP_COMMANDER_UAVplaced"; + disabled[20] = true; + labels[21] = "HUD_HELP_SQUAD_callForTarget"; + disabled[21] = true; + labels[22] = "HUD_HELP_COMMANDER_commanderApply"; + disabled[22] = true; + labels[23] = "HUD_HELP_SPAWNSCREEN_SQUADTAB_applyCommander"; + minimumExperience[23] = 72000; + labels[24] = "HUD_HELP_COMMANDER_SQUADLIST_squadList"; + disabled[24] = true; + labels[25] = "HUD_HELP_COMMANDER_SQUADLIST_clickSquadList"; + labels[26] = "HUD_HELP_COMMANDER_MINIMAP_description"; + labels[27] = "HUD_HELP_COMMANDER_MAP_QUICKMENU"; + labels[28] = "HUD_HELP_COMMANDER_MAP_ZOOM_inOut"; + labels[29] = "HUD_HELP_COMMANDER_SATELLITESCAN_description"; + labels[30] = "HUD_HELP_COMMANDER_UAV_description"; + labels[31] = "HUD_HELP_COMMANDER_ARTILLERY_description"; + labels[32] = "HUD_HELP_COMMANDER_SUPPLIES_description"; + labels[34] = "HUD_HELP_SQUAD_LEADER_VOIP_commanderChannel"; + disabled[34] = true; + labels[35] = "HUD_HELP_COMMANDER_VOIP_allSquadLeadersChannel"; + disabled[35] = true; + labels[36] = "HUD_HELP_COMMANDER_COMMUNICATION_VOIPTOGGLE"; + disabled[36] = true; + labels[37] = "HUD_HELP_COMMANDER_MAP_REQUESTS_received"; + disabled[37] = true; + labels[38] = "HUD_HELP_COMMANDER_SQUADLIST_orderIcon"; + disabled[38] = true; + labels[39] = "HUD_HELP_COMMANDER_MAP_SATELLITEVIEW_moveKeys"; + disabled[39] = true; + labels[40] = "HUD_HELP_COMMANDER_SQUADLIST_commoMenu"; + labels[41] = "HUD_HELP_COMMANDER_MAP_FILTERS"; + labels[42] = "HUD_HELP_SQUAD_LEADER_mainMapRightMouseMenu"; + labels[43] = ""; + labels[45] = "HUD_HELP_KIT_MEDIC_NAMETAG_indicatorBar"; + disabled[45] = true; + labels[46] = "HUD_HELP_KIT_SUPPORT_NAMETAG_indicatorBar"; + disabled[46] = true; + labels[47] = "HUD_HELP_KIT_ENGINEER_NAMETAG_indicatorBar"; + disabled[47] = true; + labels[48] = "HUD_HELP_GAMEPLAY_captureFlag"; + disabled[48] = true; + labels[49] = "HUD_HELP_GAMEPLAY_exitToCapture"; + disabled[49] = true; + labels[50] = "HUD_HELP_MENU_CONTROLS_COMMOROSE_specificSpotted"; + disabled[50] = true; + labels[51] = "HUD_HELP_COMMANDER_uavDamaged"; + disabled[51] = true; + labels[52] = "HUD_HELP_COMMANDER_radarDamaged"; + disabled[52] = true; + labels[53] = "HUD_HELP_COMMANDER_artilleryDamaged"; + disabled[53] = true; + labels[54] = ""; + labels[55] = ""; + labels[56] = "HUD_HELP_SPAWNSCREEN_spawnOnSL"; + disabled[56] = true; + labels[57] = "HUD_HELP_MENU_CONTROLS_zoomMap"; + labels[58] = "HUD_HELP_SQUAD_recievedTarget"; + disabled[58] = true; + labels[59] = "HUD_HELP_SPAWNSCREEN_KITTAB_pickArmyAndKit"; + labels[60] = "HUD_HELP_SPAWNSCREEN_KITTAB_pickSpawnPoint"; + labels[61] = "HUD_HELP_SPAWNSCREEN_KITTAB_useUnlock"; + disabled[61] = true; + labels[62] = "HUD_HELP_SPAWNSCREEN_KITTAB_trySquads"; + minimumExperience[62] = 21600; + labels[63] = "HUD_HELP_GAMEPLAY_climbLadder"; + labels[64] = "HUD_HELP_PLAYER_CONTROLS_radioMessages"; + minimumExperience[64] = 7200; + labels[65] = "HUD_HELP_MENU_COMMOROSE_slCommoRoseFirstUse"; + disabled[65] = true; + minimumExperience[66] = 7200; + disabled[66] = true; + labels[67] = "HUD_HELP_VEHICLE_GENERAL_CONTROLS_enterVehicle"; + labels[68] = "HUD_HELP_VEHICLE_CONTROLS_exitVehicle"; + timers[69].interval = 1.0f; + labels[69] = ""; + labels[70] = "HUD_HELP_PLAYER_CONTROLS_sprint"; + disabled[70] = true; + labels[71] = "HUD_HELP_PLAYER_CONTROLS_lieDown"; + minimumExperience[71] = 18000; + labels[72] = "HUD_HELP_MENU_CONTROLS_changeWeapon"; + labels[73] = "HUD_HELP_MENU_CONTROLS_largeMap"; + minimumExperience[73] = 7200; + labels[74] = "HUD_HELP_MENU_CONTROLS_scoreBoard"; + minimumExperience[74] = 18000; + labels[75] = "HUD_HELP_MENU_CONTROLS_spawnScreen"; + labels[76] = ""; + labels[77] = ""; + labels[78] = "HUD_HELP_PLAYER_CONTROLS_GasMask"; + labels[79] = "HUD_HELP_PLAYER_CONTROLS_NightVision"; + labels[80] = "HUD_HELP_WEAPON_HANDHELD_ZLINE_CONTROLS_useZipLine"; + labels[81] = "HUD_HELP_WEAPON_HANDHELD_GHOOK_CONTROLS_useGrapplingHookUp"; + +} + +// BF2.exe 0x5ED0E0. +void PlayerVOHelp::enable(bool value) { enabled = value; } +// BF2.exe 0x5ED120. No index guard is present in retail. +void PlayerVOHelp::disableMessage(int id, bool value) { disabled[id] = value; } +// BF2.exe 0x5ED140. +bool PlayerVOHelp::messagePlayed(int id) const { return played[id]; } + +// BF2.exe 0x5ED0F0; the argument is a by-value string. +void PlayerVOHelp::savePlayed(std::string key) +{ + if (!isDedicated()) + static_cast(g_generalSettings)->setPlayedVOHelp(key); +} + +// BF2.exe 0x5ED1A0; the dedicated arm returns false. +bool PlayerVOHelp::wasPlayed(std::string key) +{ + if (!isDedicated()) + return static_cast(g_generalSettings)->checkPlayedVOHelp(key); + return false; +} + +// BF2.exe 0x5EDB20. Empty dynamic-message slots are never marked played. +void PlayerVOHelp::markPlayed(int id, bool save) +{ + if (id != 82 && !labels[id].empty()) + { + played[id] = true; + if (save) + savePlayed(labels[id]); + } +} + +// BF2.exe 0x5EDB80. The profile stores total played seconds; retain repeated mode checks. +void PlayerVOHelp::loadPlayed() +{ + if (!isDedicated()) + for (int id = 0; id < 82; ++id) + { + if ((!labels[id].empty() && + static_cast(g_generalSettings)->checkPlayedVOHelp(labels[id])) || + isDedicated() || !(minimumExperience[id] <= + static_cast(g_localProfileManager)->getTotalPlayedTime())) + markPlayed(id, false); + } +} + +// BF2.exe 0x5ED150. Reset on expiry; subtract dt only on the non-expired arm. +bool PlayerVOHelp::tickMessage(int id, float dt) +{ + if (timers[id].remaining <= 0.0f) + { + timers[id].remaining = timers[id].interval; + return true; + } + timers[id].remaining -= dt; + return false; +} + +// BF2.exe 0x5F1460. +void PlayerVOHelp::update(float dt) +{ + if (!enabled || (gameLogic && gameLogic->getGameStatus() != 1)) + return; + world::IPlayer* player = world::playerManager->getLocalHumanPlayer(); + if (!player) + return; + world::IObject* vehicle = player->getVehicle(); + onFoot = vehicle && vehicle->getTemplate()->getClassID() == 38035; + messageElapsed += dt; + nextMessageDelay -= dt; + if (messageActive) + { + if (!(messageElapsed > messageDuration)) + return; + messageActive = false; + messageElapsed = 0.0f; + nextMessageDelay = helpRandom(30.0f * 0.000000059604644775390625f, 10.0f); + } + for (int id = 0; id < 82; ++id) + if (!disabled[id] && !played[id] && tickMessage(id, dt) && tryMessage(id, dt)) + { + messageActive = true; + messageElapsed = 0.0f; + nextMessageDelay = 0.0f; + markPlayed(id, true); + return; + } +} + +// BF2.exe 0x4F8110. Client definition of the existing VoiceMessages entry point; +// [INFERRED] placement here keeps this recovery within the lent PlayerVOHelp boundary. +int VoiceMessages::playHelpMessage(const std::string& key) +{ + const auto message = m_helpMessages.find(getLowerCase(key)); + if (message == m_helpMessages.end()) + return -1; + const int id = message->second; + ISoundTemplate* soundTemplate = m_helpSound->getTemplate(); + if (g_bfSound->getVolumeForGroup(soundTemplate->getVolumeGroup()) > 0.05f) + { + m_helpSound->stop(); + m_helpSound->playSample(id, 1); + } + return id; +} + +// BF2.exe 0x5ED1E0, with GameLogic::getVoiceMessages at client 0x4BDBB0. +void PlayerVOHelp::playVoice(std::string key) +{ + if (world::playerManager->getLocalHumanPlayer()) + static_cast(gameLogic)->getVoiceMessages()->playHelpMessage(key); +} + +// BF2.exe 0x5EDC10. The decompiler's incorrect no-return annotation on delete +// hides the candidate scan; instructions retain both grid queries and the class test. +bool PlayerVOHelp::nearObject(const Vec3& origin, float radius, unsigned int classId) +{ + std::vector& scratch = world::objectManager->getObjectTempVector(); + std::vector().swap(scratch); + world::ObjectFlagPredicator predicator(0x200); + std::vector candidates; + world::objectManager->getObjectsFromGrid(origin, radius, scratch, &predicator); + for (world::IObject* object : scratch) + candidates.push_back(object); + world::objectManager->getNoCollisionObjectsFromGrid(origin, radius, scratch, &predicator); + for (world::IObject* object : scratch) + candidates.push_back(object); + for (world::IObject* object : candidates) + if (object->getTemplate()->getClassID() == classId) + { + const Vec3& position = object->getAbsolutePosition(); + const float x = position.x - origin.x; + const float y = position.y - origin.y; + const float z = position.z - origin.z; + if (!(std::sqrt(z * z + y * y + x * x) > radius)) + return true; + } + return false; +} + +// BF2.exe 0x5EDE00. Keep message IDs and the ordering within each branch. +bool PlayerVOHelp::tryMessage(int id, float /*dt*/) +{ + const float random = helpRandom(0.0000059604644775390625f, 0.0f); + world::IPlayer* player = world::playerManager->getLocalHumanPlayer(); + if (!player) + return false; + // Repeated calls below are intentional: retail does not cache the HUD mode. + const auto show = [this](int message) { + // [CHOSEN, not recovered] Owner's visual-only tutorial preference. + // Keep voice, timers and played-history updates on their recovered paths. + if (!showTutorialMessages()) + return; + hudManager->showWideHelp(hudManager->replaceWideInputKeys( + hudManager->getLocalizedString(labels[message])), 9.0f); + }; + const auto showAndVoice = [&show, this](int message) { + show(message); + playVoice(labels[message]); + return true; + }; + const auto showKey = [](const std::string& key) { + // [CHOSEN, not recovered] Also covers component and proximity tutorial text. + if (!showTutorialMessages()) + return; + hudManager->showWideHelp(hudManager->replaceWideInputKeys( + hudManager->getLocalizedString(key)), 9.0f); + }; + // Shared retail tails retain each virtual getHudInfo call and the C-string + // comparison: embedded NULs are not compared like std::string values. + const auto showComponent = [&showKey](world::IHelpHudComp* help, + std::string world::HelpHudInfo::*text, std::string world::HelpHudInfo::*sound) { + if (!(help->getHudInfo()->*text).empty() && !wasPlayed(help->getHudInfo()->*text)) + { + showKey(help->getHudInfo()->*text); + const char* soundKey = (help->getHudInfo()->*sound).c_str(); + const char* textKey = (help->getHudInfo()->*text).c_str(); + if (std::strcmp(textKey, soundKey) != 0) + savePlayed(help->getHudInfo()->*text); + } + if (!(help->getHudInfo()->*sound).empty() && !wasPlayed(help->getHudInfo()->*sound)) + { + playVoice(help->getHudInfo()->*sound); + savePlayed(help->getHudInfo()->*sound); + } + }; + switch (id) + { + case 0: + if (hudManager->getMode() == 0 && onFoot) + { + show(0); + return true; + } + break; + case 1: + if (!(WorldPref::getWorldTime() > 3.0)) + return false; + if (hudManager->getMode() != 0 || !onFoot) + return false; + show(1); + playVoice("move_help"); + return true; + case 2: + if (hudManager->getMode() == 0 && onFoot && player->getIsAlive()) + return showAndVoice(2); + break; + case 3: + if (hudManager->getMode() == 0 && onFoot && player->getIsAlive()) + { + if (helpPrimaryAmmo(hudManager->getAmmo()) <= 0.3f && + helpPrimaryAmmo(hudManager->getAmmo()) > 0.0f) + return showAndVoice(3); + } + break; + case 4: + if (hudManager->getMode() == 0 && onFoot && player->getIsAlive()) + { + show(4); + playVoice("weapon_zoom"); + return true; + } + break; + case 5: + case 6: + case 7: + case 8: + case 71: + case 75: + if (nextMessageDelay < 0.0f && random < ((id == 8 || id == 71) ? 20.0f : 10.0f)) + if (hudManager->getMode() == 0 && onFoot) + { + show(id); + return true; + } + break; + case 9: + if (player->getSquadId() != 0 && !player->getIsSquadLeader()) + { + show(9); + return true; + } + break; + case 10: + case 12: + if (hudManager->getMode() == 18 && player->getSquadId() == 0) + return showAndVoice(id); + break; + case 11: + if (player->getIsSquadLeader()) + { + show(11); + return true; + } + break; + case 13: + if (onFoot && hudManager) + { + world::ISoldier* soldier = hudManager->getPlayerSoldier(player); + if (soldier && soldier->getIsSkyDiving()) + { + playVoice("parachute_help"); + show(13); + return true; + } + } + break; + case 14: + { + world::IObject* vehicle = player->getVehicle(); + if (vehicle && vehicle->getTemplate()->getClassID() == 38035) + { + world::IArmorGLComp* armor = 0; + for (world::IObject* object = vehicle; object; object = object->getParent()) + if ((armor = static_cast(object->getArmorComponent()))) + break; + if (armor && armor->getStatus() == 1) + { + playVoice("man_down_help"); + show(14); + return true; + } + } + } + break; + case 15: + if (player->getIsSquadLeader() && hudManager->getMode() == 0) + return showAndVoice(15); + break; + case 16: + if (hudManager->getMode() != 22) + return false; + show(16); + playVoice("place_artillery"); + return true; + case 17: + show(17); + playVoice("place_supplies"); + return true; + case 18: + show(18); + playVoice("place_uav"); + return true; + case 19: + case 20: + if (hudManager->isCommanderShown()) + { + show(id); + playVoice(id == 19 ? "artillery_fired" : "uav_placed"); + return true; + } + break; + case 21: + show(21); + return true; + case 22: + if (!player->getIsCommander()) + return showAndVoice(22); + break; + case 23: + if (hudManager->getMode() != 18 && hudManager->getMode() != 17) + return false; + return showAndVoice(23); + case 24: + case 26: + case 27: + case 28: + case 29: + case 30: + case 31: + case 32: + case 35: + case 36: + case 37: + case 38: + case 39: + case 51: + case 52: + case 53: + if (hudManager->isCommanderShown()) + return showAndVoice(id); + break; + case 25: + case 40: + if (hudManager->isCommanderShown() && + world::playerManager->getNrOfActiveSquads(player->getTeam()) > 0) + return showAndVoice(id); + break; + case 34: + case 45: + case 46: + case 47: + case 48: + case 49: + case 50: + case 56: + return showAndVoice(id); + case 41: + if (hudManager->getMode() == 15) + return showAndVoice(41); + break; + case 42: + if (hudManager->getMode() == 17) + return showAndVoice(42); + break; + case 43: + { + if (!player->getVehicle()) + return false; + world::IObject* defaultVehicle = player->getDefaultVehicle(); + if (player->getVehicle() == defaultVehicle) + return false; + world::Kit* kit = hudManager->getPlayerKit(player); + if (!kit) + return false; + auto* pco = static_cast( + player->getVehicle()->queryInterface(world::IID_IPlayerControlObject)); + world::IHelpHudComp* help = helpComponent(kit); + if (!pco || !hasAbilityHud(kit) || !pco->getAutoUseAbility() || !help) + return false; + if (!helpActive(help, 0)) + return false; + showComponent(help, &world::HelpHudInfo::helpStringKey, + &world::HelpHudInfo::helpSoundKey); + help->setIsActive(false); + return true; + } + case 54: + if (player->getVehicle()) + { + world::IHelpHudComp* help = helpComponent(player->getVehicle()); + if (help) + { + auto* armor = static_cast(player->getVehicle()->getArmorComponent()); + if (armor) + { + const float hitPoints = armor->getHitPoints(); + const long double maximum = armor->getMaxHitPoints(); + if (hitPoints / maximum < 0.3f && helpActive(help, 2)) + { + showComponent(help, &world::HelpHudInfo::lowArmorHelpStringKey, + &world::HelpHudInfo::lowArmorHelpSoundKey); + help->setLowArmorIsActive(false); + return true; + } + } + } + } + break; + case 55: + if (player->getVehicle()) + { + world::IPlayerControlObject* pco = world::findOwningPlayerControlObject(player->getVehicle()); + if (pco) + for (int channel = 0; channel < 2; ++channel) + { + world::IObject* object = pco->getActiveWeapon(channel); + if (!object) + continue; + auto* weapon = static_cast(object->queryInterface(world::IID_IWeaponObject)); + if (!weapon) + continue; + world::IHelpHudComp* help = helpComponent(object); + if (!help) + continue; + const float firstMagazine = static_cast(weapon->getMag0Size()); + const int magazine = weapon->getMagSize(); + if (static_cast(firstMagazine) / magazine < 0.3f && helpActive(help, 3)) + { + showComponent(help, &world::HelpHudInfo::lowAmmoHelpStringKey, + &world::HelpHudInfo::lowAmmoHelpSoundKey); + help->setLowAmmoIsActive(false); + return true; + } + } + } + break; + case 69: + if (onFoot) + { + world::IObject* vehicle = player->getVehicle(); + if (vehicle && vehicle->queryInterface(world::IID_IPlayerControlObject)) + { + world::IPlayerControlObject* near = findNearbyControl( + player->getVehicle()->getAbsolutePosition(), player, 30.0f); + if (!near) + return false; + auto* object = static_cast(near->queryInterface(world::IID_IObject)); + if (!object) + return false; + world::IHelpHudComp* help = helpComponent(object); + if (!help) + return false; + int otherTeam = near->getTeam(); + int referenceTeam = player->getTeam(); + if (!help->getIsCloseToActive(referenceTeam, otherTeam)) + return false; + world::IObject* current = player->getVehicle(); + const Vec3& target = object->getAbsolutePosition(); + const Vec3& source = current->getAbsolutePosition(); + const float x = source.x - target.x; + const float y = source.y - target.y; + const float z = source.z - target.z; + const float distance = std::sqrt((z * z + y * y) + x * x); + if (!(static_cast(helpDistance(help)) > distance)) + return false; + // Retail evaluates the other team's getter before the local team's. + const auto closeText = [&]() -> const std::string& { + const int other = near->getTeam(); + const int reference = player->getTeam(); + return help->getCloseToHelpStringKey(reference, other); + }; + const auto closeSound = [&]() -> const std::string& { + const int other = near->getTeam(); + const int reference = player->getTeam(); + return help->getCloseToHelpSoundKey(reference, other); + }; + if (!closeText().empty() && !wasPlayed(closeText())) + { + showKey(closeText()); + const char* soundKey = closeSound().c_str(); + const char* textKey = closeText().c_str(); + if (std::strcmp(textKey, soundKey) != 0) + savePlayed(closeText()); + } + if (!closeSound().empty() && !wasPlayed(closeSound())) + { + playVoice(closeSound()); + savePlayed(closeSound()); + } + otherTeam = near->getTeam(); + referenceTeam = player->getTeam(); + help->setCloseToIsActive(referenceTeam, otherTeam, false); + return true; + } + } + break; + case 76: + if (!player->getVehicle() || hudManager->getMode() != 0 || !player->getIsAlive()) + return false; + { + world::IPlayerControlObject* pco = world::findOwningPlayerControlObject(player->getVehicle()); + if (!pco) + return false; + world::IObject* weapon = pco->getActiveWeapon(0); + if (!weapon) + return false; + world::IHelpHudComp* help = helpComponent(weapon); + if (!help) + return false; + if (!helpActive(help, 0) && !helpActive(help, 1)) + return false; + auto* weaponHud = static_cast(world::object_detail::LayoutAccess::weaponHudComponent(weapon)); + if (!weaponHud || !hudManager->getVehicleInformation()) + return false; + if (helpActive(help, 0)) + { + hud::HudVehicleInformation* vehicleHud = hudManager->getVehicleInformation(); + const int guiIndex = weaponHud->getHudInfo()->guiIndex; + if (vehicleHud->getGuiIndex() == guiIndex) + { + showComponent(help, &world::HelpHudInfo::helpStringKey, + &world::HelpHudInfo::helpSoundKey); + help->setIsActive(false); + return true; + } + } + if (helpActive(help, 1)) + { + hud::HudVehicleInformation* vehicleHud = hudManager->getVehicleInformation(); + const int guiIndex = weaponHud->getHudInfo()->altGuiIndex; + if (vehicleHud->getGuiIndex() == guiIndex) + { + showComponent(help, &world::HelpHudInfo::altHelpStringKey, + &world::HelpHudInfo::altHelpSoundKey); + help->setAltIsActive(false); + return true; + } + } + } + break; + case 77: + if (!player->getVehicle() || !player->getIsAlive()) + return false; + { + world::IHelpHudComp* help = helpComponent(player->getVehicle()); + if (help && helpActive(help, 0)) + { + showComponent(help, &world::HelpHudInfo::helpStringKey, + &world::HelpHudInfo::helpSoundKey); + help->setIsActive(false); + return true; + } + } + break; + case 57: + if (player->getIsAlive()) + if (hudManager->getMode() == 2 || hudManager->getMode() == 18 || + hudManager->getMode() == 17 || hudManager->getMode() == 15) + { + show(57); + return true; + } + break; + case 58: + show(58); + playVoice("place_artillery"); + return true; + case 59: + case 60: + case 61: + case 62: + if (hudManager->getMode() == 1) + return showAndVoice(id); + break; + case 63: + if (onFoot && player->getVehicle()->queryInterface(world::IID_IPlayerControlObject) && + nearObject(player->getVehicle()->getAbsolutePosition(), 3.0f, 40000)) + { + playVoice("ladder_help"); + show(63); + return true; + } + break; + case 64: + if (hudManager->getMode() == 0) + { + show(64); + playVoice("comm_rose"); + return true; + } + break; + case 65: + case 66: + if (player->getIsSquadLeader()) + return showAndVoice(id); + break; + case 67: + if (onFoot) + { + world::IObject* vehicle = player->getVehicle(); + if (vehicle && vehicle->queryInterface(world::IID_IPlayerControlObject)) + { + world::IObject* origin = player->getVehicle(); + const int team = player->getTeam(); + if (world::BFfindEntryPoint(origin->getAbsolutePosition(), + 3.0f, team, player, true, true, true)) + { + auto* vehicleHud = static_cast(vehicle->getVehicleHudComponent()); + if (vehicle->getTemplate() && vehicle->getTemplate()->getClassID() == 40000) + return false; + if (vehicleHud && !vehicleHud->getHudInfo()->standardHelpEnabled) + return false; + playVoice("enter_Vehicle_help"); + show(67); + return true; + } + } + } + break; + case 68: + { + world::IObject* defaultVehicle = player->getDefaultVehicle(); + if (player->getVehicle() != defaultVehicle && player->getIsAlive()) + { + world::IObject* vehicle = player->getVehicle(); + if (vehicle) + { + auto* vehicleHud = static_cast(vehicle->getVehicleHudComponent()); + if (vehicle->getTemplate() && vehicle->getTemplate()->getClassID() == 40006) + return false; + if (vehicleHud && !vehicleHud->getHudInfo()->standardHelpEnabled) + return false; + } + playVoice("exit_Vehicle_help"); + show(68); + return true; + } + } + break; + case 70: + if (onFoot) + { + playVoice("HUD_HELP_PLAYER_CONTROLS_sprint"); + show(70); + return true; + } + break; + case 72: + if (WorldPref::getWorldTime() > 20.0) + if (hudManager->getMode() == 0 && onFoot && player->getIsAlive()) + { + show(72); + playVoice("weapon_change"); + return true; + } + break; + case 73: + if (WorldPref::getWorldTime() > 60.0) + { + show(73); + playVoice("open_map"); + return true; + } + break; + case 74: + if (hudManager->getMode() == 0 && onFoot) + { + show(74); + return true; + } + break; + case 78: + if (hudManager->getMode() == 0 && onFoot && player->getIsNearGasCloud()) + return showAndVoice(78); + break; + case 79: + if (hudManager->getMode() == 0 && onFoot && player->isPlayerInNightMap()) + return showAndVoice(79); + break; + case 80: + case 81: + if (hudManager->getMode() == 0 && onFoot && player->getDefaultVehicle()) + if (nearObject(player->getDefaultVehicle()->getAbsolutePosition(), 3.0f, + id == 80 ? 40009 : 40013)) + return showAndVoice(id); + break; + } + return false; +} + +} } +#endif diff --git a/Code/BF2/Game/GameLogic/PlayerVOHelp.h b/Code/BF2/Game/GameLogic/PlayerVOHelp.h new file mode 100644 index 000000000..243cc7f35 --- /dev/null +++ b/Code/BF2/Game/GameLogic/PlayerVOHelp.h @@ -0,0 +1,55 @@ +// [INFERRED] Client tutorial owner and source placement beside Player. +#ifndef GAME_GAMELOGIC_PLAYERVOHELP_H +#define GAME_GAMELOGIC_PLAYERVOHELP_H + +#include "../../Core/BuildConfig.h" +#if !DEDICATED +#include +#include "../../Math/Vec3.h" + +namespace dice { namespace hfe { +namespace world { class IObject; class IHelpHudComp; class HelpHudCompTemplate; } +namespace hud { class HudAmmo; } + +// BF2.exe 0x5ED220 initializes this state; native STL determines string stride. +// Class and method names are [INFERRED]. No virtual surface is published. +struct PlayerVOHelp +{ + PlayerVOHelp(); + ~PlayerVOHelp() = default; // BF2.exe 0x504720: reverse destruction of 82 strings. + void enable(bool value); + void disableMessage(int id, bool value); + bool messagePlayed(int id) const; + void markPlayed(int id, bool save); + void loadPlayed(); + bool tickMessage(int id, float dt); + void update(float dt); + bool tryMessage(int id, float dt); + + static void savePlayed(std::string key); + static bool wasPlayed(std::string key); + static void playVoice(std::string key); + static bool nearObject(const Vec3& origin, float radius, unsigned int classId); + static world::IHelpHudComp* helpComponent(world::IObject* object); + static bool hasAbilityHud(world::IObject* object); + static bool helpActive(world::IHelpHudComp* help, int kind); + static int helpDistance(world::IHelpHudComp* help); + static const world::HelpHudCompTemplate* helpTemplate(world::IHelpHudComp* help); + static float helpPrimaryAmmo(hud::HudAmmo* ammo); + + bool played[82]; + bool disabled[82]; + int minimumExperience[82]; // Total played seconds, not score. + bool messageActive; + float messageDuration; + float messageElapsed; + float nextMessageDelay; + bool enabled; + bool onFoot; // Retail +0x1FD: the vehicle template is Soldier. + std::string labels[82]; + struct Timer { float interval, remaining; } timers[82]; +}; + +} } +#endif +#endif diff --git a/Code/BF2/Game/GameLogic/ServerGameLogic.cpp b/Code/BF2/Game/GameLogic/ServerGameLogic.cpp index 65f84edea..2e9b5f3ca 100644 --- a/Code/BF2/Game/GameLogic/ServerGameLogic.cpp +++ b/Code/BF2/Game/GameLogic/ServerGameLogic.cpp @@ -3,6 +3,9 @@ // Keep the retail event order and unchecked assumptions at each call site. #include "ServerGameLogic.h" +#if defined(__APPLE__) +#include "../../Platform/X87Compat.h" // [CHOSEN, not recovered] +#endif #include #include @@ -545,6 +548,33 @@ void ServerGameLogic::uPlaying(float deltaTime) if (getBeginRoundState() == 3 && m_shouldUpdateTicketSystem) // +0x28C uPlayingTicketSystem(deltaTime); + +#if !defined(_WIN32) + // [TEMP] [CHOSEN, not recovered] BF2_ROUND_TRACE=1: one stderr line per BeginRoundState + // change and every 30 s of play (tickets, alive humans, players), so loopback runs can + // confirm the round start from the server log. Off by default; reads only. + // [RETIRE-WHEN: the macOS loopback round checks move to a query tool] + static const bool roundTrace = std::getenv("BF2_ROUND_TRACE") != 0; + if (roundTrace) + { + static int lastState = -1; + static unsigned int lastTick = 0; + const int now = static_cast(getBeginRoundState()); + const unsigned int tick = static_cast(WorldPref::getTickCount()); + if (now != lastState || (now == 3 && tick - lastTick >= 900)) + { + std::fprintf(stderr, + "[round] state %d -> %d tick %u aliveHumans %d players %d needed %d " + "tickets %u/%u ai %d\n", + lastState, now, tick, world::playerManager->getNumberOfAliveHumanPlayers(), + world::playerManager->getNumberOfPlayers(), + serverSettings->getNumPlayersNeededToStart(), getNumberOfTickets(1), + getNumberOfTickets(2), ai::g_aiInstance != 0 ? 1 : 0); + lastState = now; + lastTick = tick; + } + } +#endif } @@ -1324,6 +1354,20 @@ void ServerGameLogic::checkSpecialForcesTriggers(world::IPlayer* player, world:: soldier->handleMessage(static_cast(26), player, false); } +#if !defined(_WIN32) +// [TEMP] BF2_ENTRY_TRACE=1: which step of the vehicle entry refuses (diagnosis only, no behaviour). +// [RETIRE-WHEN: vehicle-entry-diagnosed] +static bool entryTraceArmed() +{ + static const bool armed = std::getenv("BF2_ENTRY_TRACE") != 0; + return armed; +} +#define BF2_ENTRY_TRACE(...) do { if (entryTraceArmed()) { std::fprintf(stderr, "[ENTRY] " __VA_ARGS__); \ + std::fputc('\n', stderr); std::fflush(stderr); } } while (0) +#else +#define BF2_ENTRY_TRACE(...) do { } while (0) +#endif + // Processes a player's per-tick fire, vehicle, seat, device and camera input. // Dead players proceed only while using their free camera. The drop-key path requires a vehicle. // Entering or leaving rereads the current vehicle for later actions; repeated queries are intentional. @@ -1340,6 +1384,8 @@ void ServerGameLogic::checkPlayerTriggers(world::IPlayer* player, world::IObject // 2. PIUse - the enter / exit key if (inputPressed(input, io::PIUse)) { + BF2_ENTRY_TRACE("PIUse p%d holdsSelectable=%d", player->getId(), + playerHoldsSelectableWeapon(effectiveControlObject(player)) ? 1 : 0); if (!playerHoldsSelectableWeapon(effectiveControlObject(player))) { toggleEntryPoint(player, true); @@ -1589,9 +1635,13 @@ void ServerGameLogic::toggleEntryPoint(world::IPlayer* playerArg, bool enter) world::IPlayer* const player = getPlayer(playerArg); // the identity + BF2_ENTRY_TRACE("toggle p%d enter=%d", player->getId(), enter ? 1 : 0); // gate 1: a spectator toggles nothing if (player->getVehicle() == player->getFreeCamera()) // +0x48 / +0xA8 + { + BF2_ENTRY_TRACE("refused: free camera"); return; + } // gate 2: a dead or wrecked body // the template is read raw (+0x14) and dereferenced with NO null check, unlike the enter half. @@ -1602,18 +1652,28 @@ void ServerGameLogic::toggleEntryPoint(world::IPlayer* playerArg, bool enter) world::IArmorGLComp* const armor = static_cast( world::object_detail::LayoutAccess::armorComponent(player->getVehicle())); // +0x3C if (armor && armor->getStatus()) // +0x5C: 0 alive, 1 wreck, 2 gone + { + BF2_ENTRY_TRACE("refused: armor status %d", (int) armor->getStatus()); return; + } } // gate 3: the one-second world-time cooldown if (WorldPref::getWorldTime() - static_cast(player)->m_worldTime < 1.0f) // +0xE4 + { + BF2_ENTRY_TRACE("refused: cooldown (now %.2f last %.2f)", (double) WorldPref::getWorldTime(), + (double) static_cast(player)->m_worldTime); return; + } world::IObject* vehicle = player->getVehicle(); // +0x48 world::IPlayerControlObject* const pco = static_cast( vehicle->queryInterface(world::IID_IPlayerControlObject)); // +0x0C if (!pco) + { + BF2_ENTRY_TRACE("refused: vehicle has no PCO"); return; + } // `proceed` is decided before the exit half runs and is not recomputed afterwards: a player // whose seat forbids entering another vehicle still gets to leave it, they just do not get the @@ -1694,6 +1754,7 @@ void ServerGameLogic::toggleEntryPoint(world::IPlayer* playerArg, bool enter) } } + BF2_ENTRY_TRACE("inVehicle=%d proceed=%d", inVehicle ? 1 : 0, proceed ? 1 : 0); if (!proceed) return; @@ -1704,7 +1765,10 @@ void ServerGameLogic::toggleEntryPoint(world::IPlayer* playerArg, bool enter) world::object_detail::LayoutAccess::objectTemplate(vehicle); // +0x14 if (vt && vt->getClassID() == world::CID_SoldierTemplate && !static_cast(vehicle)->isNotFireingOrHaveRecoil()) // +0x298 + { + BF2_ENTRY_TRACE("refused: soldier firing or recoiling"); return; + } } const float radius = enter ? 3.0f : 5.0f; // cmovnz flt_888E6B8 (3.0) over 0x40A00000 (5.0) @@ -1736,6 +1800,8 @@ void ServerGameLogic::toggleEntryPoint(world::IPlayer* playerArg, bool enter) entry = world::BFfindEntryPoint(position, radius, player->getTeam(), // +0xE8 player, enter, true, true); } + BF2_ENTRY_TRACE("search at %.1f/%.1f/%.1f r=%.1f team=%d -> entry=%p", (double) position.x, + (double) position.y, (double) position.z, (double) radius, player->getTeam(), (void*) entry); if (entry) { @@ -1746,7 +1812,9 @@ void ServerGameLogic::toggleEntryPoint(world::IPlayer* playerArg, bool enter) world::IObject* const target = static_cast( entry->queryInterface(world::IID_IObject)); // +0x0C - if (game->enterVehicle(player, target, false)) // +0xA4 + const bool entered = game->enterVehicle(player, target, false); // +0xA4 + BF2_ENTRY_TRACE("enterVehicle -> %d", entered ? 1 : 0); + if (entered) static_cast(player)->m_worldTime = static_cast(WorldPref::getWorldTime()); } else @@ -1933,6 +2001,14 @@ void ServerGameLogic::spawnPlayer(world::IPlayer* playerArg, std::pairboolGet(std::string("UseAI"), false) == 1) refuseBecauseAI = (player->getIsAIPlayer() == 1); // +0x64 +#if !defined(_WIN32) + // [TEMP] [CHOSEN, not recovered] AI test aid: BF2_AI_SPAWN_WITHOUT_HUMAN=1 lets bots + // take the first spawn wave without a human, so AI runs need no client (server-only + // loopback). Off by default; the shipped rule above is unchanged. + // [RETIRE-WHEN: AI recovery reaches G6] + if (refuseBecauseAI && std::getenv("BF2_AI_SPAWN_WITHOUT_HUMAN")) + refuseBecauseAI = false; +#endif } if (refuseBecauseAI) return; @@ -2434,7 +2510,12 @@ PyObject* sgl_setParam(PyObject*, PyObject* args) // four keys to the game logic, five to the score manager - and each narrows the double // differently. See the note above. if (key.compare("tickets") == 0) +#if defined(__APPLE__) + // [CHOSEN, not recovered] Keep the x86 wrap of a negative value (arm64 saturates): docs/macos-c-arm64-client.md. + sgl->setNumberOfTickets(team, bf2x87::lowUInt32(value)); +#else sgl->setNumberOfTickets(team, static_cast(value)); +#endif else if (key.compare("ticketLimit") == 0) // GameLogic.py passes (team, limitId, threshold) here: the generic `value` is // the limit ID and the generic `id` argument is its threshold. Keep their order. diff --git a/Code/BF2/Game/GameLogic/SpawnSystem/SpawnGroup.cpp b/Code/BF2/Game/GameLogic/SpawnSystem/SpawnGroup.cpp index 9a3cc5a1f..c5bdee7c7 100644 --- a/Code/BF2/Game/GameLogic/SpawnSystem/SpawnGroup.cpp +++ b/Code/BF2/Game/GameLogic/SpawnSystem/SpawnGroup.cpp @@ -2,6 +2,9 @@ #include "SpawnGroup.h" +#include // [TEMP] BF2_SPAWNGROUP_TRACE +#include + #include "../../../Core/Ids.h" #include "../../../Core/SettingsRepostitory.h" // settings - GLSWorldSizeX/Z #include "../../../Core/System.h" // WorldPref::getTickCount @@ -15,6 +18,7 @@ #include // rand - getSpawnPoint's pick +#include "../../../Platform/MsvcRand.h" // [CHOSEN, not recovered] the client CRT's rand (MSVCR71) namespace dice { namespace hfe { @@ -147,7 +151,7 @@ ISpawnPoint* SpawnGroup::getSpawnPoint(bool isAI) const } ISpawnPoint* picked = 0; if (!candidates.empty()) - picked = candidates[static_cast(std::rand()) % candidates.size()]; + picked = candidates[static_cast(bf2crt::rand()) % candidates.size()]; return picked; } @@ -364,7 +368,7 @@ bool SpawnGroup::getNetUpdate(io::BitStream& stream, io::BaseLineData* /*baselin } // Reads changed spawn-group fields into the next baseline, carrying forward unsent values. -// Position and squad are both decoded, but a position change takes precedence when applying them. +// Position and squad are both decoded and both applied (position first). // Decoded positions have zero Y. World-size settings are reread for each update; // odd world sizes retain the writer/reader quantization difference. void SpawnGroup::setNetUpdate(io::BitStream& stream, float /*time*/, bool ghostActive, @@ -433,7 +437,7 @@ void SpawnGroup::setNetUpdate(io::BitStream& stream, float /*time*/, bool ghostA if (stateMask == 0) // nothing changed - no apply return; - // 6: the apply. A second pass, AND NOT IN THE read'S order - see the note. + // 6: the apply. A second pass, AND NOT IN THE read'S order. const int worldSizeX = settings->intGet(std::string("GLSWorldSizeX"), 0); const int worldSizeZ = settings->intGet(std::string("GLSWorldSizeZ"), 0); @@ -456,10 +460,24 @@ void SpawnGroup::setNetUpdate(io::BitStream& stream, float /*time*/, bool ghostA - static_cast(worldSizeZ / 2); setPos(position); // +0x30, BY value } - else if (stateMask & 0x20) // else, not a second if - see the note + // A second if, not an else: retail lays the setPos block out of line and returns from it to + // the squad test (0x811222D call +0x30, 0x8112230 jmp 0x811211C `and edi, 0x20`). An else + // dropped the squad of every group whose first update also carried its position, leaving the + // constructor's -1 ("no squad", offered to the whole team): squad-leader spawn points appeared + // for players outside the squad. + if (stateMask & 0x20) { setSquad(record.squad); // +0x20 } +#if defined(__APPLE__) + // [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: squad-spawn-filter-validated] + // BF2_SPAWNGROUP_TRACE=1: each applied client spawn-group update. + static const bool trace = std::getenv("BF2_SPAWNGROUP_TRACE") != 0; + if (trace) + std::fprintf(stderr, "[SPAWNGROUP] %p mask=0x%02x team=%d squad=%d active=%d points=%d aiOnly=%d\n", + (void*) this, stateMask, getTeam(), getSquad(), m_active ? 1 : 0, m_hasSpawnPoints ? 1 : 0, + m_onlyForAI ? 1 : 0); +#endif } } // namespace hfe diff --git a/Code/BF2/Game/GameLogic/SquadManager/Squad.cpp b/Code/BF2/Game/GameLogic/SquadManager/Squad.cpp index 7e7f36681..f6ac103bf 100644 --- a/Code/BF2/Game/GameLogic/SquadManager/Squad.cpp +++ b/Code/BF2/Game/GameLogic/SquadManager/Squad.cpp @@ -15,7 +15,6 @@ #include "../../../AI/AIInterface/AIInstance.h" #include "../../../AI/AIInterface/IAIEventCourier.h" #include "../../../AI/AIInterface/SingletonServer.h" -#include "../../../AI/AIInterface/BFKnowledge/AIFrontier.h" #include "../../../Core/EventManager.h" // eventManager->postEvent - removeFromSquad #include "../../Common/GameEvent.h" // PostRemoteEvent - the ECHud 20/21 sends #include "../../IGameLogic.h" // gameLogic->isServer @@ -435,12 +434,10 @@ bool Squad::removeFromSquad(int playerId, bool skipScriptEvent, bool kicked) if (ai::g_aiInstance && ai::aiInstance()->isInitialized()) { - const int teamId = player->getTeam(); // player unchecked - (void)teamId; // / PE 0x45F844 reads the team before the courier call with // (playerId, current m_squadId, teamId), ELF +0x90 / PE +0x8C. - // [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - BF2_AI_FRONTIER("dice::hfe::Squad::removeFromSquad (AIEventCourier::event_removedFromSquad)"); + const int teamId = player->getTeam(); // player unchecked + ai::BFSingletonServer::m_iaiEventCourier->event_removedFromSquad(playerId, m_squadId, teamId); } if (m_members.empty()) // +0x144 diff --git a/Code/BF2/Game/GameLogic/SquadManager/SquadManager.cpp b/Code/BF2/Game/GameLogic/SquadManager/SquadManager.cpp index 387d4859f..5623eabd1 100644 --- a/Code/BF2/Game/GameLogic/SquadManager/SquadManager.cpp +++ b/Code/BF2/Game/GameLogic/SquadManager/SquadManager.cpp @@ -11,7 +11,6 @@ #include "../../../AI/AIInterface/AIInstance.h" #include "../../../AI/AIInterface/IAIEventCourier.h" #include "../../../AI/AIInterface/SingletonServer.h" -#include "../../../AI/AIInterface/BFKnowledge/AIFrontier.h" #include "../../../Scene/Object/PlayerManager.h" // getPlayersSortedByScore (+0x4C) - client arm #include "../../../Scene/Object/PlayerScoreData.h" // join eligibility field +0x10 #include "../../Common/GameEvent.h" // PostRemoteEvent @@ -549,8 +548,10 @@ void SquadManager::issueSquadOrder(int teamId, int squadId, SquadOrder& order, } } -// Broadcasts the order before commander and member HUD notifications. Preserve -// repeated ID lookups. [UNRESOLVED] The optional AI courier branch remains omitted. +// issueCommanderOrder - ELF 0x811D800. Broadcasts the order before commander and member HUD +// notifications. Preserve repeated ID lookups. The AI singleton (ds:0x8AC37F8) is loaded once +// before the member loop; while it is non-null and initialized (IAIInstance +0x1C), every member +// first gets ecai 8 `(playerId, orderId)` (eventManager +0x14) and then its HUD 26, AI or not. void SquadManager::issueCommanderOrder(int teamId, int squadId, SquadOrder& order, bool suppressEvent) { @@ -578,6 +579,7 @@ void SquadManager::issueCommanderOrder(int teamId, int squadId, SquadOrder& orde new PostRemoteEvent(ECHud, 27, false, &squadId, 4, 0.0f)); } + IBase* const aiSingleton = ai::g_aiInstance; // 0x811D939: read once, before the loop for (std::set::iterator it = squad->m_members.begin(); it != squad->m_members.end(); ++it) { @@ -585,7 +587,12 @@ void SquadManager::issueCommanderOrder(int teamId, int squadId, SquadOrder& orde if (!player) continue; - // [UNRESOLVED] ecai 8 notification behind ds:0x8AC37F8 / PE dword_8B25B0. + // 0x811D98E..0x811DAA3: the AI courier's commander-order notification. + if (aiSingleton && reinterpret_cast(aiSingleton)->isInitialized()) + { + int aiPayload[2] = { *it, order.orderId }; + eventManager->postEvent(ECAI, 8, aiPayload, 0.0f); + } if (player->getId() == 255) { eventManager->postEvent(ECHud, 26, &squadId, 0.0f); diff --git a/Code/BF2/Game/GameLogic/VoiceMessages.cpp b/Code/BF2/Game/GameLogic/VoiceMessages.cpp index 7f7c7b927..62b420f18 100644 --- a/Code/BF2/Game/GameLogic/VoiceMessages.cpp +++ b/Code/BF2/Game/GameLogic/VoiceMessages.cpp @@ -11,6 +11,7 @@ #include // sqrt - playSoldierVO's range test #include // rand - getSpeechId #include // memset - the speech table +#include "../../Platform/MsvcRand.h" // [CHOSEN, not recovered] the client CRT's rand (MSVCR71) namespace dice { namespace hfe { @@ -386,7 +387,7 @@ int VoiceMessages::getSpeechId(int message, int voice) if (cell.first < 0 || cell.count <= 0) return -1; if (cell.count > 1) - return cell.first + std::rand() % cell.count; + return cell.first + bf2crt::rand() % cell.count; return cell.first; } diff --git a/Code/BF2/Game/GameLogic/VoiceMessages.h b/Code/BF2/Game/GameLogic/VoiceMessages.h index ebaf0163d..3b1a31bfb 100644 --- a/Code/BF2/Game/GameLogic/VoiceMessages.h +++ b/Code/BF2/Game/GameLogic/VoiceMessages.h @@ -1,6 +1,6 @@ // Per-level radio and voice registry owned by GameLogic. Console scripts populate // message names, samples and per-team voices before finalize creates the sounds. -// Speaker handles are weak. Help entry points remain named frontiers. +// Speaker handles are weak. The help-playing query remains a named frontier. // STL-containing layouts differ across platforms; use typed fields. #ifndef GAME_GAMELOGIC_VOICEMESSAGES_H // [INFERRED] guard style #define GAME_GAMELOGIC_VOICEMESSAGES_H @@ -64,7 +64,7 @@ class VoiceMessages int playRadioMessage(int, const std::string&, const std::string&, const std::string&); int playSoldierVO(int, int, int, const Vec3&, world::Soldier*); - int playHelpMessage(const std::string&); // [FRONTIER] + int playHelpMessage(const std::string&); // BF2.exe 0x4F8110; client body beside PlayerVOHelp. bool isHelpVOPlaying() const; // [FRONTIER] int getFreeVOSoundIndex(const Vec3&, world::Soldier*); diff --git a/Code/BF2/Game/GameServer/AutoRecorder.h b/Code/BF2/Game/GameServer/AutoRecorder.h index 1227e39f0..f96f0973b 100644 --- a/Code/BF2/Game/GameServer/AutoRecorder.h +++ b/Code/BF2/Game/GameServer/AutoRecorder.h @@ -6,6 +6,9 @@ #define GAME_GAMESERVER_AUTORECORDER_H #include +#if !defined(_WIN32) +#include +#endif #include "../IEventListener.h" #include "../../Core/Mutex.h" @@ -41,7 +44,12 @@ class AutoRecorderHookThread : public Thread /* +0x10 */ std::string m_hookCommand; // sv.autoDemoHook, copied by init /* +0x14 */ AutoRecorder* m_owner; // hookCompleted's receiver /* +0x18 */ Mutex* m_mutex; // the owner'S mutex, not one of its own +#if defined(_WIN32) /* +0x1C */ bool m_quit; // set by ~AutoRecorder before Thread::stop +#else + // [CHOSEN, not recovered] POSIX: run also reads this flag while the owner mutex is unlocked. + std::atomic m_quit; +#endif }; // AutoRecorder - ELF ctor 0x809FD20 (C1, 298 B), dtor 0x809FF90 (D1) / 0x80A00D0 (D0), diff --git a/Code/BF2/Game/GameServer/GameServer.cpp b/Code/BF2/Game/GameServer/GameServer.cpp index 1ff718b7e..3594c10ec 100644 --- a/Code/BF2/Game/GameServer/GameServer.cpp +++ b/Code/BF2/Game/GameServer/GameServer.cpp @@ -2,6 +2,9 @@ // GameServer owns level loading, client admission, simulation and outgoing game state. // Keep the recovered lifecycle and dispatch ordering; method-level exceptions remain at their sites. +#if defined(__APPLE__) && !DEDICATED +#include "../../Platform/macOS/Warmup.h" // [CHOSEN] +warmupLevel (port addition) +#endif #include "GameServer.h" #include "VoipServerConnection.h" #include "ClientInfo.h" // handleDataBlock parses a block-id-1 payload into one @@ -12,7 +15,11 @@ #include "../GameLogic/SquadManager/ISquadManager.h" #if !DEDICATED #include "../GeneralSettings.h" // limitCoopPlayers' two client-only bot-count pushes +#include "../../Sound/BfSound.h" +#include "../Main/BF2ClientSeams.h" // hudManager - the radio spam notice of a hosted game +#include "../../Menu/BF2HudManager.h" #endif +#include "ServerInfo.h" // radioBlockedDuration - the spam notice's seconds #include "../Common/GameEventManager.h" // onNewConnection queues the ChallengeEvent #include "../Common/GhostManager.h" // the per-connection ghost update #include "../../Core/System.h" // WorldPref::getTickCount @@ -52,6 +59,7 @@ #include "../../AI/AIDLL/AI/Main/BF2AI.h" // PE unload's AI isInitialized/clear pair #endif #include "../Main/BF2Engine.h" // loadAI / quitNextFrame / updateStatusMonitor +#include "../PunkBuster/PbGlue.h" // PbAuthClient, PB_handlePacket, PB_get_sv_punkbusterInstalled #include "../Utility/BuildNrUtil.h" // getNetVersionNumber - the protocol stamp #include "../../Core/ClassManager.h" // createInstance2 +0x34 / getSimpleSingleton +0x5C #include "../../Core/EventManager.h" // postEvent +0x14 @@ -121,6 +129,8 @@ #include // srand / rand - the challenge ordinal #include // the empty-maplist refusal writes to std::cout #include +#include "../../Scene/Object/WorldObjTemplPortal/PortalManager.h" // IPortalManager::update, +0x40 +#include "../../Platform/MsvcRand.h" // [CHOSEN, not recovered] the client CRT's rand (MSVCR71) namespace dice { namespace hfe { @@ -150,17 +160,6 @@ inline ServerConnection* asServerConnection(IClientConnection* c) // SDK Winsock headers into this translation unit. extern "C" char* gcd_getkeyhash(int gameid, int localid); -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: PB-ADMISSION-SDK] -// Stops before optional PunkBuster admission until its SDK state and loader are -// recovered; a null SDK must not be treated as successful authentication. -const char* punkBusterAuthClient(const char*, int, const char*) -{ - std::fprintf(stderr, "[FRONTIER] dice::hfe::(anon)::punkBusterAuthClient (PbAuthClient SDK state/loader) reached\n"); - std::fflush(stderr); - //std::abort(); - return nullptr; -} - void cdkey_auth_callback(int localId, AuthResult result, void* context) { GameServer* const gs = static_cast(context); @@ -175,8 +174,9 @@ void cdkey_auth_callback(int localId, AuthResult result, void* context) { std::string ipAndPort; gs->getConnectionIpAndPort(localId, ipAndPort); - const char* hash = gcd_getkeyhash(gamespy::g_gameID, localId); - const char* reason = punkBusterAuthClient(ipAndPort.c_str(), 1, hash); + char* hash = gcd_getkeyhash(gamespy::g_gameID, localId); + // ELF 0x80A4CB7: pbsv's admission check; without a hook from pbsv it admits (0). + const char* reason = PbAuthClient(const_cast(ipAndPort.c_str()), 1, hash); if (reason) gs->kickPlayer(localId, static_cast(34), std::string(reason)); else gs->authOk(localId); } @@ -209,16 +209,8 @@ bool GameServer::init() serverSettings->m_punkBuster = false; } - // PB_get_sv_punkbusterInstalled: ELF 0x84F8A10 / PE 0x453B80 is only fileExists. - // [CHOSEN, placement only] inline its read here until the PB integration TU is recovered. - // [PLATFORM] the shipped Linux path is pb/pbsv.so; Windows uses pb/pbsv.dll. -#ifdef _WIN32 - const char* const pbServerLibrary = "pb/pbsv.dll"; -#else - const char* const pbServerLibrary = "pb/pbsv.so"; -#endif - if (serverSettings->getRanked() - && !io::fileManager->fileExists(std::string(pbServerLibrary))) + // ELF 0x80A7500 / BF2.exe 0x4CF940: PB_get_sv_punkbusterInstalled (pb/pbsv.so, pb/pbsv.dll). + if (serverSettings->getRanked() && !PB_get_sv_punkbusterInstalled()) Debug(DEBUGTYPE_7, "Game/GameServer/GameServer.cpp", 617) << "Cannot run a ranked server without punkbuster installed and enabled."; m_isPunkBusterEnabled = serverSettings->getSvPunkBuster(); @@ -239,15 +231,15 @@ bool GameServer::init() { // Preserve both diagnostics and the subsequent demotion. Debug type 6 is fatal under // normal retail logging, despite the message saying "Changing server to unranked". - // Retail streams the ostringstream object (operator const void*), not its str(). + // Retail (ELF GameServer::init 0x80A67F0) streams the ostringstream object itself into both + // diagnostics, through operator void*, so the user saw an address instead of the text. + // [CHOSEN, not recovered] Both diagnostics carry message.str(). std::ostringstream message; message << "FATAL ERROR: Your server cannot communicate with the required internet backends.\n" << "Please read the documentation for the dedicated server to find out what ports you\n" << "need to open in your firewall and/or NAT products. Changing server to unranked.\n"; - Debug(DEBUGTYPE_8, "Game/GameServer/GameServer.cpp", 646) - << (message.fail() ? nullptr : static_cast(static_cast(&message))); - Debug(DEBUGTYPE_6, "Game/GameServer/GameServer.cpp", 647) - << (message.fail() ? nullptr : static_cast(static_cast(&message))); + Debug(DEBUGTYPE_8, "Game/GameServer/GameServer.cpp", 646) << message.str(); + Debug(DEBUGTYPE_6, "Game/GameServer/GameServer.cpp", 647) << message.str(); serverSettings->setRanked(false); } // The failure arm rejoins here if its fatal diagnostic was suppressed. No null guard exists. @@ -503,7 +495,13 @@ bool GameServer::startServer(const std::string& a1, int port, int /* dead - neve if (m_netServer) { // NetServer initialization returns zero on success; other results destroy the listener and fail startup. - if (m_netServer->init(a1, port, true) != 0) // +0x10 + const int netInit = m_netServer->init(a1, port, true); +#if defined(__APPLE__) + // [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: macos-singleplayer-hosting-validated] + if (std::getenv("BF2_HOST_TRACE")) + std::fprintf(stderr, "[host] NetServer::init(%s, %d) -> %d\n", a1.c_str(), port, netInit); +#endif + if (netInit != 0) // +0x10 { if (m_netServer) delete m_netServer; @@ -562,7 +560,13 @@ bool GameServer::startServer(const std::string& a1, int port, int /* dead - neve if (!levelName.empty()) { - if (!game->loadPath(levelName)) // IGame vtable +0x24 - THE handoff + const bool loaded = game->loadPath(levelName); +#if defined(__APPLE__) + // [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: macos-singleplayer-hosting-validated] + if (std::getenv("BF2_HOST_TRACE")) + std::fprintf(stderr, "[host] loadPath(%s) -> %d\n", levelName.c_str(), loaded ? 1 : 0); +#endif + if (!loaded) // IGame vtable +0x24 - THE handoff { #if !DEDICATED // [PLATFORM] A listen server's failed map load disables the required profiler and fails startup without quitting the engine. @@ -586,8 +590,16 @@ bool GameServer::startServer(const std::string& a1, int port, int /* dead - neve if (!isDedicated()) { const int localPlayer = createPlayer(settings->stringGet("GSPlayerName", "player"), false); +#if defined(__APPLE__) + // [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: macos-singleplayer-hosting-validated] + if (std::getenv("BF2_HOST_TRACE")) + std::fprintf(stderr, "[host] createPlayer -> %d\n", localPlayer); +#endif if (localPlayer == -1) return false; +#if defined(__APPLE__) + bf2warmup::localPlayerJoined(); // [CHOSEN] +warmupLevel progress (notification only) +#endif } #endif @@ -614,8 +626,8 @@ bool GameServer::loadPath(const std::string& levelName) limitCoopPlayers(); // The challenge ordinal is random 0..9, seeded from the wall clock in milliseconds. - srand((int)(g_system->getWallClockTime() * 1000.0)); // System +0x1C; flt_888B168 = 1000.0f - m_mapInfo.setChallengeOrdinal(rand() % 10); // MapInfo at +0x04, by value + bf2crt::srand((int)(g_system->getWallClockTime() * 1000.0)); // System +0x1C; flt_888B168 = 1000.0f + m_mapInfo.setChallengeOrdinal(bf2crt::rand() % 10); // MapInfo at +0x04, by value if (m_loadState) // +0xA0 nonzero = something is loaded unload(); // virtual, IGame slot +0x28 @@ -1460,38 +1472,88 @@ bool GameServer::destroyObject(world::IObject* object) return Game::destroyObject(object); } +namespace { +// The spam notice a hosted game shows its own human player when the radio filter refuses one of +// their messages: the shared "spam" game-info line, then the localized seconds-left chat line. +// The same arm as GameClient::radioMessage; in BF2.exe it is inlined into GameServer::radioMessage +// (0x4C523E..0x4C5348) and radioMessageFromPlayer (0x4C4FCC..0x4C50D6). A dedicated server has no +// HUD; the Linux dedicated image omits the arm. +void showRadioSpamNotice(Game* game, world::IPlayer* player) +{ +#if !DEDICATED + game->localGameInfoMessage(static_cast(14), std::string("spam")); // PE +0x60 + if (!hudManager) + return; + const int blockedDuration = serverInfo->m_block.radioBlockedDuration; + const int seconds = static_cast( + player->getRadioSpamFilterFlagTimer() // PE +0x320 + + blockedDuration + 1.0f + - WorldPref::getWorldTime()); + const std::wstring text = hudManager->replaceWideTokenFromInt( // +0x44 + hudManager->getLocalizedString( // +0x38 + std::string("HUD_HUD_MENU_CHAT_SPAM_MESSAGE")), + std::string("#SEC#"), seconds); + hudManager->addServerChat(text, player->getTeam()); // +0x130, team read last +#else + (void)game; + (void)player; +#endif +} +} // namespace + +// Sends a radio message from a player through the server's own radio relay. A hosted game (the +// client image running the server) also plays the message back for its local human player and +// shows them the spam notice; the client image tests isDedicated() at run time for both arms +// (BF2.exe 0x4C5180), while the Linux dedicated image has neither (ELF 0x080AD3E0 keeps only the +// discarded local-player query). localPlayback is cleared for anyone but the local human player. bool GameServer::radioMessage(TargetChannel channel, const std::string& message, world::IPlayer* player, unsigned int extra, - bool /*unused*/, bool bypassSpamCheck) + bool localPlayback, bool bypassSpamCheck) { if (!player) return true; - // Retail performs this virtual call even though it discards the result. - world::playerManager->getLocalHumanPlayer(); + if (player != world::playerManager->getLocalHumanPlayer()) // +0x30 + localPlayback = false; int messageId; const std::string empty1; const std::string empty2; - if (static_cast(gameLogic)->getVoiceMessages()->namesToIds( - &messageId, 0, 0, message, empty1, empty2) && - (bypassSpamCheck || !player->getIsThisASpam(true))) - { - EventNode* node = createRadioMessageReceivedEvent( - -1, - static_cast(messageId), - static_cast(player->getId()), - static_cast(player->getTeam()), - static_cast(extra), - static_cast(channel), 3); - eventManager->postEvent(ECNetwork, node, 0.0f); + if (!static_cast(gameLogic)->getVoiceMessages()->namesToIds( + &messageId, 0, 0, message, empty1, empty2)) + return true; + + if (!bypassSpamCheck && player->getIsThisASpam(true)) // PE +0x308 = ELF +0x30C + { + if (!isDedicated() && localPlayback && !player->getIsAIPlayer()) // 0x440510, PE +0x60 + showRadioSpamNotice(this, player); + return true; + } + + EventNode* node = createRadioMessageReceivedEvent( + -1, + static_cast(messageId), + static_cast(player->getId()), + static_cast(player->getTeam()), + static_cast(extra), + static_cast(channel), 3); + eventManager->postEvent(ECNetwork, node, 0.0f); + + if (!isDedicated() && localPlayback) // BF2.exe 0x4C53B2..0x4C53E0 + { + const int id = player->getId(); // getId first in this arm + const int team = player->getTeam(); + playbackRadioMessage(channel, static_cast(3), team, id, messageId); } return true; } +// As radioMessage, for a player named by id. AI senders keep their id as the relay connection, +// everyone else is relayed as the server (-1). The hosted-game arms are those of radioMessage +// (BF2.exe 0x4C4F10; ELF 0x080AD1F0 has neither), but localPlayback is not narrowed here. bool GameServer::radioMessageFromPlayer(TargetChannel channel, const std::string& message, unsigned int playerId, unsigned int extra, - bool /*unused*/, bool bypassSpamCheck) + bool localPlayback, bool bypassSpamCheck) { world::IPlayer* player = world::playerManager->getPlayerFromId(static_cast(playerId)); if (!player) @@ -1500,43 +1562,64 @@ bool GameServer::radioMessageFromPlayer(TargetChannel channel, const std::string int messageId; const std::string empty1; const std::string empty2; - if (static_cast(gameLogic)->getVoiceMessages()->namesToIds( - &messageId, 0, 0, message, empty1, empty2) && - (bypassSpamCheck || !player->getIsThisASpam(true))) - { - const int connectionId = player->getIsAIPlayer() - ? static_cast(playerId) - : 0xFF; - EventNode* node = createRadioMessageReceivedEvent( - connectionId, - static_cast(messageId), - static_cast(playerId), - static_cast(player->getTeam()), - static_cast(extra), - static_cast(channel), 3); - eventManager->postEvent(ECNetwork, node, 0.0f); + if (!static_cast(gameLogic)->getVoiceMessages()->namesToIds( + &messageId, 0, 0, message, empty1, empty2)) + return true; + + if (!bypassSpamCheck && player->getIsThisASpam(true)) + { + if (!isDedicated() && localPlayback && !player->getIsAIPlayer()) + showRadioSpamNotice(this, player); + return true; + } + + const int connectionId = player->getIsAIPlayer() + ? static_cast(playerId) + : 0xFF; + EventNode* node = createRadioMessageReceivedEvent( + connectionId, + static_cast(messageId), + static_cast(playerId), + static_cast(player->getTeam()), + static_cast(extra), + static_cast(channel), 3); + eventManager->postEvent(ECNetwork, node, 0.0f); + + if (!isDedicated() && localPlayback) // BF2.exe 0x4C5133..0x4C5161 + { + // The player's own getId, not the argument (GameClient's overload passes the argument). + const int id = player->getId(); + const int team = player->getTeam(); + playbackRadioMessage(channel, static_cast(3), team, id, messageId); } return true; } +// Sends a server game-info line (type 0). A hosted game plays it back locally as well +// (BF2.exe 0x4C53F0; not in the Linux dedicated image), with a in the team and b in the sender +// position, as GameClient::gameInfoMessage does. bool GameServer::gameInfoMessage(TargetChannel channel, const std::string& message, - unsigned int a, unsigned int b, bool /*unused*/) + unsigned int a, unsigned int b, bool localPlayback) { int messageId; const std::string empty1; const std::string empty2; - if (static_cast(gameLogic)->getVoiceMessages()->namesToIds( + if (!static_cast(gameLogic)->getVoiceMessages()->namesToIds( &messageId, 0, 0, message, empty1, empty2)) - { - EventNode* node = createRadioMessageReceivedEvent( - -1, - static_cast(messageId), - static_cast(a), - static_cast(b), - static_cast(b), - static_cast(channel), 0); - eventManager->postEvent(ECNetwork, node, 0.0f); - } + return true; + + EventNode* node = createRadioMessageReceivedEvent( + -1, + static_cast(messageId), + static_cast(a), + static_cast(b), + static_cast(b), + static_cast(channel), 0); + eventManager->postEvent(ECNetwork, node, 0.0f); + + if (!isDedicated() && localPlayback) // BF2.exe 0x4C54AA..0x4C54C7 + playbackRadioMessage(channel, static_cast(0), + static_cast(a), static_cast(b), messageId); return true; } @@ -2339,16 +2422,6 @@ extern IBase* portalManager; // ds:0x8B1ED80 - ditto } // namespace world namespace { -// [FRONTIER] [TEMP] [CHOSEN, not recovered] Bot portal updates diagnose and abort at this seam. -void portalManagerUpdate(IBase* manager, float dt); // world::PortalManager::update(float) - vtable +0x40 (0x88CABE0 slot 16) - -void portalManagerUpdate(IBase* /*manager*/, float /*dt*/) -{ - std::fprintf(stderr, "[FRONTIER] dice::hfe::(anon)::portalManagerUpdate" - " (world::PortalManager::update, vtable +0x40) reached (bots game)\n"); - std::fflush(stderr); - std::abort(); -} // Typed bridge from the shared connection interface to packet processing. inline bool clientConnectionProcessReceivedPacket(IClientConnection* c, io::BitStream* stream) { @@ -2403,9 +2476,13 @@ bool GameServer::update(int steps, float dt) updateConnections(elapsed); processGameStateAndSendPackets(elapsed); } - // [PLATFORM] NOT - BF2.exe 0x4D1138..0x4D1151, a listen-server arm the dedicated ELF - // folded away: `if (!isDedicated() && i == steps - 1)` the sound owner (ds:0xA23DC0) vslot - // +0x18(steps). Its identity is unread. +#if !DEDICATED + // A listen server updates the local listener and mixer once, after the last simulation step. + // BF2.exe 0x4D1138..0x4D1151: isDedicated (0x440510), then ds:0xA23DC0 (the BfSound that + // 0x7E1774 stores after its 0x148-byte construction) vslot +0x18(steps). + if (!isDedicated() && i == steps - 1) + g_bfSound->update(steps); +#endif } // [PLATFORM] NOT - BF2.exe 0x4D1162..0x4D1173: `if (isLightmapRenderingNode())` // (0x440530) ds:0x987350 vslot +0x28() - a lightmap-farm tool arm the dedicated ELF folded away. @@ -2765,8 +2842,8 @@ void GameServer::challengeResponse(int connectionId, GameEvent* ev) // Drain received packets, then execute queued disconnects. Do not tear down // connections inside the receive loop: NetServer retains a map cursor. Connection // 129 is the demo stream. Packet payload lengths arrive without a packet-size clamp. -// [FRONTIER] PunkBuster packet delivery remains omitted; its filtered payloads -// are still drained and freed. +// PunkBuster's filtered datagrams go to PB_handlePacket while the server runs PunkBuster, and are +// freed either way. void GameServer::processReceivedPackets() { if (!m_netServer) @@ -2791,9 +2868,9 @@ void GameServer::processReceivedPackets() for (std::list::iterator it = filtered.begin(); it != filtered.end(); ++it) { - // disabled BY project decision - the guard and the call, both reproduced as comments: - // if (m_isPunkbusterEnabled) - // PB_handlePacket(it->m_data, it->m_size, &it->m_address); + // ELF 0x80AA199 / 0x80AAC94: the payload, its size and the sender's "ip:port" name. + if (m_isPunkBusterEnabled) + PB_handlePacket(static_cast(it->data), static_cast(it->size), it->name); std::free(it->data); } } @@ -3513,7 +3590,7 @@ void GameServer::simulatePlayersCollisions(float dt) void GameServer::updatePortals(float dt) { if (ai::g_aiInstance && ai::aiInstance()->isBotsGame()) - portalManagerUpdate(world::portalManager, dt); // [FRONTIER] + reinterpret_cast(world::portalManager)->update(dt); // +0x40 } // Marks an acknowledged object ghostable for one connection. Missing connection @@ -3900,16 +3977,32 @@ void GameServer::handleRadioMessageReceivedEvent(RadioMessageReceivedEvent* even event->m_connectionId = connectionId; } -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: gameserver-radio-ai-courier] -// The no-bot production path above never enters this arm. Keeping a fail-loud callable boundary -// prevents a bots-enabled server from silently dropping radio commands while the 309-byte courier -// body and its AI-event payload remain unrecovered. -void GameServer::sendRadioMessageToAI(IEventWrapper&, int) +// sendRadioMessageToAI - ELF 0x080B5A80, 304 B. The sender is the wrapper's sender id (-1: the +// local human player); an alive sender's message is posted once per alive AI player that +// filterMessage lets hear it, as ECAI event 10 {messageId, sender id, receiver id} (the +// AIEventListener radio arm, which forwards it to the courier). +void GameServer::sendRadioMessageToAI(IEventWrapper& wrapper, int messageId) { - std::fprintf(stderr, - "[FRONTIER] dice::hfe::GameServer::sendRadioMessageToAI reached\n"); - std::fflush(stderr); - std::abort(); + world::IPlayer* sender = wrapper.getSenderId() == -1 // +0x08 + ? world::playerManager->getLocalHumanPlayer() // +0x30 + : world::playerManager->getPlayerFromId(wrapper.getSenderId()); // +0x20 + if (!sender || !sender->getIsAlive()) // +0x6C + return; + const std::list& players = world::playerManager->getPlayers(); // +0x3C + for (std::list::const_iterator it = players.begin(); it != players.end(); ++it) + { + world::IPlayer* const receiver = *it; + if (!receiver || !receiver->getIsAlive() || !receiver->getIsAIPlayer()) // +0x6C, +0x64 + continue; + if (!filterMessage(wrapper, sender, receiver)) // 0x080ADD00 + continue; + struct { int messageId; int senderId; int receiverId; } payload; // ebp-0x28..-0x20 + const int senderId = sender->getId(); // +0x54, called first + payload.receiverId = receiver->getId(); + payload.messageId = messageId; + payload.senderId = senderId; + eventManager->postEvent(ECAI, 10, &payload, 0.0f); // +0x14 + } } // Forwards chat to player/admin and server-console listeners, temporarily hiding diff --git a/Code/BF2/Game/GameServer/GameServer.h b/Code/BF2/Game/GameServer/GameServer.h index c8066a798..563f4b1f1 100644 --- a/Code/BF2/Game/GameServer/GameServer.h +++ b/Code/BF2/Game/GameServer/GameServer.h @@ -175,7 +175,7 @@ class GameServer : public Game, public IGameServer, public IEventListener bool filterTeamTail(IEventWrapper& wrapper, world::IPlayer* sender, world::IPlayer* receiver); bool filterLocalTail(IEventWrapper& wrapper, world::IPlayer* sender, world::IPlayer* receiver); void handleRadioMessageReceivedEvent(RadioMessageReceivedEvent*, void*); - void sendRadioMessageToAI(IEventWrapper&, int); // [FRONTIER] + void sendRadioMessageToAI(IEventWrapper&, int); // ELF 0x080B5A80 // : `if (m_isWaitingForClients) ++m_clientAckedEndOfRoundGuard` - void clientAckedEndOfRoundGuard(int connectionId); virtual bool changePlayerName(int, const std::string&); // +0x168 diff --git a/Code/BF2/Game/GameServer/ServerSettings.cpp b/Code/BF2/Game/GameServer/ServerSettings.cpp index b611b1fa3..fce88ce2c 100644 --- a/Code/BF2/Game/GameServer/ServerSettings.cpp +++ b/Code/BF2/Game/GameServer/ServerSettings.cpp @@ -330,12 +330,12 @@ float ServerSettings::getManDownTime() const return m_manDownTime; // +0x6C } -// [CHOSEN, not recovered] getNumPlayersNeededToStart currently returns 2 before -// its original ranked/configured logic. The following getters retain fixed ranked -// overrides for unlocks, coop settings, and team ratio. +// Number of players the round waits for: ranked servers use 6, or 8 from 33 slots up; every +// other server uses the configured sv.numPlayersNeededToStart, so a value of 1 starts the round +// with the first player. The following getters retain fixed ranked overrides for unlocks, coop +// settings, and team ratio. int ServerSettings::getNumPlayersNeededToStart() const { - return 2; if (m_ranked) // +0xF5 return (getMaxPlayers() >= 33 ? 1 : 0) * 2 + 6; return m_playersNeededToStart; // +0x58 diff --git a/Code/BF2/Game/GameServer/ServerSettingsConsole.cpp b/Code/BF2/Game/GameServer/ServerSettingsConsole.cpp index 5ab32fe97..9136b3948 100644 --- a/Code/BF2/Game/GameServer/ServerSettingsConsole.cpp +++ b/Code/BF2/Game/GameServer/ServerSettingsConsole.cpp @@ -68,15 +68,10 @@ std::string svNumReservedSlotsSet(int value) return svReceiver()->setNumReservedSlots(value); } -// [CHOSEN, not recovered] Release configurations floor the requested player count -// at two; development configurations retain the raw setter for single-player tests. -// The getter supplies the effective value. +// Stores the requested player count unchanged, as retail does; the getter applies the ranked +// override. void svNumPlayersNeededToStartSet(int value) { -#if defined(NDEBUG) - if (value < 2) - value = 2; -#endif svReceiver()->m_playersNeededToStart = value; } @@ -354,7 +349,7 @@ BF2_CONSOLE_GETSET_1(numReservedSlots, int, svReceiver() != 0, svReceiver()->m_n // numPlayersNeededToStart: ConsoleClass668, PE slot 0x82ACB4 -> ctor 0x4D0AF0 / exec 0x4D0C40; // ELF registration 0x87B109A / executor 0x87C22A0. Retail SET is a raw field write; GET uses -// the effective ranked getter. The pre-existing chosen release-build floor remains in its helper. +// the effective ranked getter. The helper keeps that raw write. BF2_CONSOLE_PROPERTY_FN(numPlayersNeededToStart, int, svReceiver() != 0, svReceiver()->getNumPlayersNeededToStart(), svNumPlayersNeededToStartSet, kSvConsoleTag) diff --git a/Code/BF2/Game/GameServer/VoipServerConnection.cpp b/Code/BF2/Game/GameServer/VoipServerConnection.cpp index df469599c..e4c2dc7d5 100644 --- a/Code/BF2/Game/GameServer/VoipServerConnection.cpp +++ b/Code/BF2/Game/GameServer/VoipServerConnection.cpp @@ -33,6 +33,7 @@ #include #include #include +#include "../../Platform/MsvcRand.h" // [CHOSEN, not recovered] the client CRT's rand (MSVCR71) namespace dice { namespace hfe { @@ -311,10 +312,10 @@ bool VoipServerConnection::InitEnabledVoip() // m_sharedSecret, and the in-process server must expect the same bytes. The PE stores it in the // shared-secret field (this+0x43FC) rather than a temporary, then hands that same string to the // server's Start. - const int letterCount = rand() % 10 + 8; + const int letterCount = bf2crt::rand() % 10 + 8; m_sharedSecret = static_cast(118); // leading 'v' for (int i = 0; i < letterCount; ++i) - m_sharedSecret += static_cast(rand() % 26 + 'a'); + m_sharedSecret += static_cast(bf2crt::rand() % 26 + 'a'); m_localVoipServer440C->Start(m_sharedSecret, static_cast(m_infoWord4400)); return true; } @@ -632,7 +633,7 @@ int VoipServerConnection::CreateClientSessionId(int playerId) return 0; const int range = (int)powf(256.0f, 2.0f); // 65536, computed not folded - int id = rand() % range; + int id = bf2crt::rand() % range; const std::list& players = world::playerManager->getPlayers(); @@ -645,7 +646,7 @@ int VoipServerConnection::CreateClientSessionId(int playerId) { if ((*it)->getVoipSessionId() == id) // vslot 624 = +0x270 { - id += 1 + (rand() % 500); // random bump, not +1 + id += 1 + (bf2crt::rand() % 500); // random bump, not +1 clash = true; // and rescan from the head break; } diff --git a/Code/BF2/Game/GeneralSettings.cpp b/Code/BF2/Game/GeneralSettings.cpp index fc316a1de..0e3816c5e 100644 --- a/Code/BF2/Game/GeneralSettings.cpp +++ b/Code/BF2/Game/GeneralSettings.cpp @@ -1,10 +1,18 @@ // [INFERRED] path. Client-only class: the dedicated ELF merely looks the "GeneralSettings" // singleton up and tolerates its absence, so every body below was read from BF2.exe. +#include +#include +#include +#include +#include +#include + #include "GeneralSettings.h" #include "LocalProfileManager.h" // cancel: ILocalProfileManager +0x44 / +0x54 #include "../Core/SmartItf.h" #include "../Menu/ISwiffHost.h" #include "../Menu/IServerBrowser.h" +#include "../Core/MsvcCrtCompat.h" // [CHOSEN, not recovered] __time32_t/_time32 outside MSVC #if !DEDICATED #include "Main/BF2ClientSeams.h" // hudManager (ds:0xA10890) #include "../Scene/Object/PlayerManager.h" // world::playerManager (ds:0xA08F60), +0x30 getLocalHumanPlayer @@ -17,12 +25,6 @@ #include "../Menu/BF2HudManager.h" #include "../Menu/HudInformationAdapter.h" #include "../Menu/HudMessages.h" -#include // sortServerHistory -#include -#include -#include -#include -#include namespace dice { namespace hfe { // Demo launches force auto-ready; ordinary launches use the saved setting. @@ -403,6 +405,9 @@ std::string GeneralSettings::getSettingsScript() stream << "GeneralSettings.setAutoReady " << m_autoReady << std::endl; stream << "GeneralSettings.setConnectionType " << m_connectionType << std::endl; stream << "GeneralSettings.setLCDDisplayModes " << m_lcdDisplayModes << std::endl; + // [CHOSEN, not recovered] Profile extension requested by the owner. + // Retail ignores the unknown method and continues loading the remaining rows. + stream << "GeneralSettings.setShowTutorialMessages " << m_showTutorialMessages << std::endl; return stream.str(); } @@ -486,6 +491,8 @@ void GeneralSettings::setDefaultValues() m_itemSelectionReverseItems = true; m_autoReload = true; m_toggleFilters = 63616; + // [CHOSEN, not recovered] Missing setting and Reset both keep retail behavior. + m_showTutorialMessages = true; } // Reloads General.con to discard unsaved options while retaining server-browser and @@ -517,6 +524,8 @@ void GeneralSettings::cancel() std::string path = std::string(lpm->getCurrentProfile()->name) + "/"; // +0x44 again path += getFileName(); // +0x10 + // [CHOSEN, not recovered] Cancel also handles older profiles without this row. + m_showTutorialMessages = true; (void) lpm->loadProfileFile(path); // +0x54 m_allowPunkBuster = allowPunkBuster; diff --git a/Code/BF2/Game/GeneralSettings.h b/Code/BF2/Game/GeneralSettings.h index c6607381e..a04e1432d 100644 --- a/Code/BF2/Game/GeneralSettings.h +++ b/Code/BF2/Game/GeneralSettings.h @@ -1,10 +1,11 @@ // General profile settings and server-history storage. #ifndef GAME_GENERALSETTINGS_H #define GAME_GENERALSETTINGS_H -#include "../Core/IBase.h" #include #include -#if !DEDICATED +#include "../Core/IBase.h" +// The interface is declared in every image (the dedicated AI reaches it through BFGame's menu +// arm, which no dedicated module can trigger); the implementation is client-only. namespace dice { namespace hfe { // Favourite/history entry. [INFERRED] Field names follow serialized settings. @@ -116,6 +117,7 @@ class IGeneralSettings : public IBase { // +164 is the deleting destructor (4B7B20), the one slot still withheld: see ~GeneralSettings. }; +#if !DEDICATED struct GeneralSettingsFixture; class GeneralSettings final : public IGeneralSettings { public: @@ -247,6 +249,11 @@ class GeneralSettings final : public IGeneralSettings { // LCD display mode setting, also exposed through the movie's VideoSettings namespace. bool getLCDDisplayModes() const override { return m_lcdDisplayModes; } //+15C void setLCDDisplayModes(bool value) override { m_lcdDisplayModes = value; } //+160 + + // [CHOSEN, not recovered] Owner's tutorial option. + // Native-only accessors leave the recovered virtual interface unchanged. + bool getShowTutorialMessages() const { return m_showTutorialMessages; } + void setShowTutorialMessages(bool value) { m_showTutorialMessages = value; } private: friend struct GeneralSettingsFixture; int m_refCount; // retail+04 @@ -283,8 +290,10 @@ class GeneralSettings final : public IGeneralSettings { int m_toggleFilters; //+F4, a bit mask: +10C tests, +110 sets/clears bool m_autoReady; //+F8 bool m_lcdDisplayModes; //+F9 + // [CHOSEN, not recovered] Persisted general option; true keeps retail pop-ups. + bool m_showTutorialMessages; }; +#endif // !DEDICATED } } #endif -#endif diff --git a/Code/BF2/Game/HudInformationLayer.cpp b/Code/BF2/Game/HudInformationLayer.cpp index 2908cc96f..ec559cec5 100644 --- a/Code/BF2/Game/HudInformationLayer.cpp +++ b/Code/BF2/Game/HudInformationLayer.cpp @@ -1,6 +1,7 @@ // Path: attested (assert), BF2.exe 0x89E910. // [INFERRED] member/helper names. Bodies read from the client PE; no HUD ELF body. #include "HudInformationLayer.h" +#include "IGameClient.h" #if !DEDICATED #include "../Core/Debug.h" #include "../Core/ClassManager.h" @@ -49,12 +50,6 @@ namespace dice { namespace hfe { namespace world { extern IBase* scoreManager; } namespace { -[[noreturn]] void hudInformationUpdateFrontier(const char* qualified, const char* detail) -{ - std::fprintf(stderr, "[FRONTIER] %s reached: %s\n", qualified, detail); - std::fflush(stderr); - std::abort(); -} // / 0x9A60B4. Identity matters independently of string contents. const char emptyString[] = ""; const wchar_t emptyWideString[] = L""; @@ -802,11 +797,28 @@ void HudInformationLayer::update(float dt) updateWideString(&m_state.TimeToSpawnString, L""); updateWideString(&m_state.DemoPausePlayString, hudManager->getLocalizedString(game->getSimulationRate() ? "HUD_HUD_DEMO_PAUSE" : "HUD_HUD_DEMO_PLAY").c_str()); - // [TEMP] [CHOSEN, not recovered] The complete client secondary interface - // remains undeclared. Stop before+58, not an invented vtable carrier. - // [RETIRE-WHEN: hud-information-demo-client] - hudInformationUpdateFrontier("dice::hfe::HudInformationLayer::update", - "PE467641: game queryInterface(120002) virtual +58, then +54 demo player ID"); + // PE 467641: the spectator camera's mode picks the camera button's label (it names the + // other mode) and whether the followed player's name shows; the name comes from the + // player manager (+0x20) and IPlayer PE +0x20 (getName, one destructor slot). + IGameClient* const demoClient = static_cast(client); + if (demoClient->demoIsFreeFlying()) { // +0x58 + m_state.DemoPlayerNameShow = false; + updateWideString(&m_state.DemoCameraString, + hudManager->getLocalizedString("HUD_HUD_DEMO_PLAYER_CAM").c_str()); + } else { + m_state.DemoPlayerNameShow = true; + updateWideString(&m_state.DemoCameraString, + hudManager->getLocalizedString("HUD_HUD_DEMO_FREE_CAM").c_str()); + } + const char* name = ""; + if (demoClient->demoGetCurrentPlayerId() != -1) { // +0x54, asked twice + world::IPlayer* const followed = + world::playerManager->getPlayerFromId(demoClient->demoGetCurrentPlayerId()); + if (followed) + name = followed->getName().c_str(); + } + updateString(&m_state.DemoPlayerNameString, name); + return; } else { m_state.DemoPlayerNameShow = false; m_state.DemoShow = false; @@ -817,7 +829,9 @@ void HudInformationLayer::update(float dt) HudInformationLayer::HudInformationLayer() : m_refCount(1), m_nextId(0) { +#if defined(_M_IX86) static_assert(sizeof(State) == 0x518, "Non-STL x86 suffix changed"); +#endif m_state.field88 = false; m_state.FriendlyTicketBleed = 0; m_state.field90 = false; @@ -995,9 +1009,14 @@ HudInformationLayer::HudInformationLayer() : m_refCount(1), m_nextId(0) // The last two overwrite eight bytes of adjacent HUD flags. Copy their // representation without inventing a larger source array or correcting // the shipped overrun. The destructor frees only the ten real pointers. + // [CHOSEN, not recovered] x64 (https://github.com/B2BF/OpenBF2/issues/7): the overrun stays + // the same eight flag bytes (+0x234..+0x23B), one 8-byte pointer instead of two 4-byte ones, + // so PlayerTeam and kitSelected are untouched as on x86. On x86 every write passes the test. const char* initial = emptyString; - std::memcpy(reinterpret_cast(&m_state) + offsetof(State, optionIcons) + i * sizeof(initial), - &initial, sizeof(initial)); + const size_t overrunEnd = offsetof(State, optionIcons) + sizeof(m_state.optionIcons) + 8; + const size_t at = offsetof(State, optionIcons) + i * sizeof(initial); + if (at + sizeof(initial) <= overrunEnd) + std::memcpy(reinterpret_cast(&m_state) + at, &initial, sizeof(initial)); m_state.radioNames[i] = emptyWideString; m_state.radioVehicleNames[i] = emptyWideString; m_state.squadNames[i] = emptyWideString; diff --git a/Code/BF2/Game/IGameClient.h b/Code/BF2/Game/IGameClient.h index 7d940d5b0..706e8c3ca 100644 --- a/Code/BF2/Game/IGameClient.h +++ b/Code/BF2/Game/IGameClient.h @@ -61,23 +61,24 @@ class IGameClient : public IBase virtual void slot44(int) = 0; // +0x48 demo playback restart (gameLogic reset / restartDemoPlayback, the recorder rewound). PE 4D2650. virtual void restartDemo() = 0; - // +0x4C demo playback pause/resume on the recorder. PE 4D26C0. - virtual void setDemoPaused(bool paused) = 0; - // [UNRESOLVED] Demo-playback method names and corresponding recorder members. - virtual void slot50() = 0; - virtual int slot54() = 0; - virtual bool slot58() = 0; + // +0x4C the spectator camera's next/previous player. PE 4D26C0. [INFERRED] name. + virtual void demoSwitchPlayer(bool next) = 0; + // +0x50 / +0x54 / +0x58 the spectator camera's nextCamera / getCurrentDemoPlayerId / + // getIsFreeFlying. PE 4D2700 / 4D2730 / 4D2760. [INFERRED] names. + virtual void demoNextCamera() = 0; + virtual int demoGetCurrentPlayerId() = 0; + virtual bool demoIsFreeFlying() = 0; // +0x5C setPause(!getPause()). PE 4D2790. virtual void togglePause() = 0; // +0x60 BF2Engine's pause state machine (ELF 0x4038A0 / 0x403060 callers). PE 4D27B0. virtual void setPause(bool paused) = 0; // +0x64 - the +0x144 byte (comdat-folded with Game::getAbortLoadLevel). virtual bool getPause() = 0; - // +0x68 the recorder exists and is in playback. PE 4D2800. - virtual bool isDemoPlaying() = 0; - // +0x6C a recorded demo handed to the profile (LocalProfileManager +0xA4, DemoLibrary - // refresh). PE 4D3D60. [UNRESOLVED] name and both int roles. - virtual void slot6C(int a, int b) = 0; + // +0x68 the recorder reached the end of its packet stream (PE +0xEC). PE 4D2800. [INFERRED] name. + virtual bool isDemoAtEnd() = 0; + // +0x6C a demo the server announced, bookmarked in the profile (LocalProfileManager +0xA4, + // DemoLibrary +0x44). PE 4D3D60. [INFERRED] name and argument roles. + virtual void addDemoBookmark(const std::string& url, const std::string& mapName) = 0; // +0x70 BF2Engine::mainLoop's pre-frame gate: true once requestDisconnect ran. PE 4D28B0. virtual bool getDisconnectRequested() = 0; // +0x74 EngineBase's client-only ghost hook: the +0x158 byte, set by ECNetwork event 4. diff --git a/Code/BF2/Game/LocalProfileManager.h b/Code/BF2/Game/LocalProfileManager.h index 4b2074bf4..604a61800 100644 --- a/Code/BF2/Game/LocalProfileManager.h +++ b/Code/BF2/Game/LocalProfileManager.h @@ -8,7 +8,8 @@ #include "IEventListener.h" #include #include -#if !DEDICATED +// The interface is declared in every image (the dedicated AI reaches it through BFGame's menu +// arm, which no dedicated module can trigger); the implementation is client-only. namespace dice { namespace hfe { struct LocalProfile { @@ -41,11 +42,12 @@ class ILocalProfileManager : public IBase { virtual bool deleteProfile(int profileIndex) = 0; virtual bool createOnlineAccount(const std::string& nick, const std::string& email, const std::string& password, const std::string& country) = 0; // PE+2C 4A7600 - // [CHOSEN, not recovered] [RETIRE-WHEN: local-profile-approved-opaque-slots] - // Abort-only placeholders preserve virtual positions. Their void() signature is not the retail ABI; - // original parameter types are unknown. These methods must never return. - virtual void frontierPrimary30() = 0; // PE+30 - virtual void frontierPrimary34() = 0; // PE+34 + // PE+30 4A7690: `cmp [ecx+0C],0; setne al; ret 4` - whether a profile is current; the one stack + // argument is ignored (its type is unknown, a dword). Name [INFERRED]. + virtual bool hasCurrentProfile(int ignored) = 0; + // PE+34 4553F0: the image's shared `mov al,1; ret 8` - true, both dword arguments ignored. Name + // [INFERRED]; no caller in the client image. + virtual bool slot34(int ignored, int ignored2) = 0; virtual bool hasProfile(const std::string& profileName) = 0; virtual bool loadCurrentProfile() = 0; // PE+3C 4AB1D0 virtual bool saveCurrentProfile() = 0; @@ -83,12 +85,18 @@ class ILocalProfileManager : public IBase { virtual bool quickLogin(const std::string& name, const std::string& password) = 0; // PE+C0 4AAD00 virtual bool saveGlobalSettings() = 0; // PE+C4 4A9440 virtual bool validateProfileFiles(const std::string& directory) = 0; // PE+C8 4A8580 + // PE+CC 619360 `mov eax,[ecx+34h]; ret` and PE+D0 4A7DB0 (sret copy of this+38h, RET 4): + // the profile index and password the last login stored. [INFERRED] names. The only known + // caller is BF2Engine's activateMod pair (0x403E40 / 0x404010). + virtual int getLoginProfileIndex() = 0; // PE+CC 619360 (ICF-shared one-load getter) + virtual std::string getLoginPassword() = 0; // PE+D0 4A7DB0 // [INFERRED] +A8/+AC/+B0 use unsigned indices/count and a borrowed pointer. // Full PE bodies/callers prove the x86 widths, arity and return conventions; // int-vs-unsigned and pointer-vs-reference source spelling are not attested. - // [FRONTIER] PE+CC..+D4 remain absent; no additional opaque slot is filled. + // PE+D4 4ABD10 is the scalar deleting destructor; no destructor slot is declared (see below). }; +#if !DEDICATED struct LocalProfileFixture; class LocalProfileManager final : public ILocalProfileManager, public IEventListener { public: @@ -111,8 +119,8 @@ class LocalProfileManager final : public ILocalProfileManager, public IEventList bool deleteProfile(int profileIndex) override; bool createOnlineAccount(const std::string& nick, const std::string& email, const std::string& password, const std::string& country) override; - void frontierPrimary30() override; - void frontierPrimary34() override; + bool hasCurrentProfile(int ignored) override; + bool slot34(int ignored, int ignored2) override; bool hasProfile(const std::string& profileName) override; bool loadCurrentProfile() override; bool saveCurrentProfile() override; @@ -150,7 +158,12 @@ class LocalProfileManager final : public ILocalProfileManager, public IEventList bool quickLogin(const std::string& name, const std::string& password) override; bool saveGlobalSettings() override; bool validateProfileFiles(const std::string& directory) override; + int getLoginProfileIndex() override; + std::string getLoginPassword() override; void handleEvent(EventCategory, unsigned int, EventNode*, void*) override; // actual5B74B0 RET16 + // [CHOSEN, not recovered] Non-virtual, no retail counterpart: once the renderer exists, a Default + // profile created in this run takes the renderer-aware defaults (see LocalProfileManagerInit.cpp). + void applyFirstStartVideoDefaults(); private: friend struct LocalProfileFixture; void reportProfileError(const std::string& message); // [INFERRED] name/caller-discard void; PE4B11A0 @@ -163,11 +176,11 @@ class LocalProfileManager final : public ILocalProfileManager, public IEventList bool m_profilesDirty; // retail+21 bool m_filterValidProfiles; // retail+22 std::vector m_profiles; // retail+24 - int m_field34; - std::string m_field38; + int m_field34; // retail+34 login's profile index (+CC) + std::string m_field38; // retail+38 login's password (+D0) bool m_field54; }; +#endif // !DEDICATED } } #endif -#endif diff --git a/Code/BF2/Game/LocalProfileManagerInit.cpp b/Code/BF2/Game/LocalProfileManagerInit.cpp index b854ef026..5d6e6821f 100644 --- a/Code/BF2/Game/LocalProfileManagerInit.cpp +++ b/Code/BF2/Game/LocalProfileManagerInit.cpp @@ -11,8 +11,15 @@ #include "Main/BF2ClientSeams.h" #include +#include + namespace dice { namespace hfe { +namespace { +// [CHOSEN, not recovered] Set when createDefaultProfile wrote the Default profile in this run. +bool s_defaultProfileCreatedThisRun = false; +} + bool LocalProfileManager::hasDefaultProfile() { // PE4AA339 discards the enumeration result and samples flag20 before the @@ -54,6 +61,7 @@ bool LocalProfileManager::createDefaultProfile() delete m_currentProfile; // deleting destructor4A8060 m_currentProfile = nullptr; } + s_defaultProfileCreatedThisRun = true; // [CHOSEN, not recovered] see applyFirstStartVideoDefaults return true; } @@ -73,5 +81,31 @@ bool LocalProfileManager::init() return true; } +// [CHOSEN, not recovered] Owner decision 2026-11-14. createDefaultProfile (4A80C0) runs from init +// (4A8980) before the renderer exists, so VideoSettings::setDefaults keeps the constructor record +// (Medium, 800x600) and a fresh install shows its login screen that way. BF2Engine::initEngine +// calls this once BF2Render::init succeeded (PE 0x409399): only when the Default profile was created +// in this run, setDefaults runs again with the renderer (High, desktop-fitting resolution, highest +// antialiasing), the session applies it (a display-mode change before the first menu frame) and +// Default/Video.con is rewritten. Existing Default profiles are never touched. +void LocalProfileManager::applyFirstStartVideoDefaults() +{ + if (!s_defaultProfileCreatedThisRun) + return; + s_defaultProfileCreatedThisRun = false; + if (m_currentProfile || !g_videoSettings) + return; + IVideoSettings* video = static_cast(g_videoSettings); + video->setDefaults(); + video->apply(); + std::string path("Default/"); + path += video->getFileName(); + writeProfileFile(path, video->getSettingsScript()); // the applied (current) record + std::fprintf(stderr, "[CHOSEN, not recovered] LocalProfileManager::applyFirstStartVideoDefaults: " + "first-start Default profile at scheme %d, resolution %s, antialiasing %s\n", + video->getVideoOptionScheme(), video->getResolution().c_str(), + video->getAntialiasing().c_str()); +} + } } #endif diff --git a/Code/BF2/Game/LocalProfileManagerOperations.cpp b/Code/BF2/Game/LocalProfileManagerOperations.cpp index a39383b19..70d9221c7 100644 --- a/Code/BF2/Game/LocalProfileManagerOperations.cpp +++ b/Code/BF2/Game/LocalProfileManagerOperations.cpp @@ -22,6 +22,7 @@ #include "DemoRecorder/DemoLibrary.h" // IDemoLibrary::refresh - login's demo-directory rescan #include "../Core/ClassManager.h" #include "../Core/EventManager.h" +#include "../IO/File/FileManager.h" // deleteProfile: io::fileManager +0x48 / +0x20 #include #include #include @@ -29,17 +30,6 @@ namespace dice { namespace hfe { extern ClassManager* classManager; -namespace { -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: local-profile-operation-calls] -// These stops belong to known callers; no suffix slot or payload ABI is invented. -[[noreturn]] void deleteSelectedProfileFrontier() -{ - std::fprintf(stderr, "[FRONTIER] dice::hfe::LocalProfileManager::deleteProfile: the default-user comparison at PE4AB01D and the directory removal that follows are unrecovered\n"); - std::fflush(stderr); - std::abort(); -} -} - // Loads and applies a profile; the middle argument is unused. // Online profiles must pass presence login. Requires current-profile, ProfileManager, and DemoLibrary objects. bool LocalProfileManager::login(int profileIndex, const std::string&, const std::string& password) @@ -157,7 +147,21 @@ bool LocalProfileManager::deleteProfile(int profileIndex) getLocalProfiles(profiles, true); // Unlike login, PE4AAFEC uses a signed comparison and has no negative guard. if (profileIndex >= static_cast(profiles.size())) return false; - deleteSelectedProfileFrontier(); + // PE4AB003..4AB10C. A deleted default user is forgotten first (Global.con's +0x20/+0x24, + // the empty string by value). + IGlobalSettings* global = static_cast(g_globalSettings); + if (profiles[profileIndex].name == global->getDefaultUser()) + global->setDefaultUser(std::string("")); + saveGlobalSettings(); // +C4 4AB05F; result discarded + // The profile directory under the file manager's own home substitution (+0x48 on + // io::fileManager itself, not its base system), with the shipped backslashes. + std::string path = std::string(io::fileManager->getHomeSubstitution()) + "\\Profiles\\"; + std::string directory = path + profiles[profileIndex].name; + // PE4AB0D1: erase(size(), 1) - a no-op the shipped body performs. + directory.erase(directory.size(), 1); + io::fileManager->deleteFile(directory); // +0x20; result discarded + m_profilesDirty = true; // +0x21 + return true; } // Creates an online account only for a current profile without a GameSpy nickname. diff --git a/Code/BF2/Game/LocalProfileManagerSelection.cpp b/Code/BF2/Game/LocalProfileManagerSelection.cpp index 6b9cce517..3173ad9f4 100644 --- a/Code/BF2/Game/LocalProfileManagerSelection.cpp +++ b/Code/BF2/Game/LocalProfileManagerSelection.cpp @@ -18,8 +18,6 @@ #include "../Core/SettingsRepostitory.h" #include "../IO/File/FileManager.h" #include "../IO/Input/Input.h" -#include -#include #include #include #include @@ -38,22 +36,16 @@ void resetSwiffServerLists(ui::ISwiffHost* host) } } -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: local-profile-approved-opaque-slots] -// Explicit owner exception for precisely these two abort-only table positions. -// void() is a chosen source placeholder, not a claim about the original unused -// one-word/two-word arguments. Neither body can return across the unknown ABI. -void LocalProfileManager::frontierPrimary30() +// PE+30 4A7690. +bool LocalProfileManager::hasCurrentProfile(int) { - std::fprintf(stderr, "[FRONTIER] dice::hfe::LocalProfileManager::frontierPrimary30: approved abort-only PE+0x30 placeholder; retail argument type remains unknown\n"); - std::fflush(stderr); - std::abort(); + return m_currentProfile != 0; } -void LocalProfileManager::frontierPrimary34() +// PE+34 4553F0 (folded with every other `return true` of this shape). +bool LocalProfileManager::slot34(int, int) { - std::fprintf(stderr, "[FRONTIER] dice::hfe::LocalProfileManager::frontierPrimary34: approved abort-only PE+0x34 placeholder; retail argument types remain unknown\n"); - std::fflush(stderr); - std::abort(); + return true; } bool LocalProfileManager::hasProfile(const std::string& profileName) diff --git a/Code/BF2/Game/LocalProfileManagerSuffix.cpp b/Code/BF2/Game/LocalProfileManagerSuffix.cpp index 783a494be..1c35682b8 100644 --- a/Code/BF2/Game/LocalProfileManagerSuffix.cpp +++ b/Code/BF2/Game/LocalProfileManagerSuffix.cpp @@ -255,6 +255,18 @@ bool LocalProfileManager::quickLogin(const std::string& name, const std::string& // PE4A9440 (80 B): the GlobalSettings file name, then its script, through the profile writer // (whose constant true is returned). +// PE 619360: one load of +34h (the body is shared by identical-code folding). +int LocalProfileManager::getLoginProfileIndex() +{ + return m_field34; +} + +// PE 4A7DB0: a copy of +38h into the caller's return string. +std::string LocalProfileManager::getLoginPassword() +{ + return m_field38; +} + bool LocalProfileManager::saveGlobalSettings() { IGlobalSettings* global = static_cast(g_globalSettings); diff --git a/Code/BF2/Game/Main/BF2.cpp b/Code/BF2/Game/Main/BF2.cpp index 10b8c2f75..bc921ef00 100644 --- a/Code/BF2/Game/Main/BF2.cpp +++ b/Code/BF2/Game/Main/BF2.cpp @@ -1,5 +1,8 @@ // Application entry points and engine-facade lifecycle. [INFERRED] source placement. +#if defined(__APPLE__) && !DEDICATED +#include "../../Platform/macOS/Warmup.h" // [CHOSEN] +warmupLevel (port addition) +#endif #include "BF2.h" #include "BF2Engine.h" // [INFERRED] path: Game/Main/BF2Engine.cpp is @@ -40,7 +43,20 @@ namespace memory { void memory_update_modules(const char*) { } } # include "../../Sound/NullSound.h" // ISoundEngine::setMasterVolume # include "../../Menu/IMenuLogic.h" // menuLogic - the active menu # include "BF2Console.h" // IMenuLogic::getConsole()->getConsoleActive() +# include "../../Platform/Windows/WinInputScript.h" // [TEMP] BF2_INPUT_SCRIPT host # endif +#elif defined(__APPLE__) && !DEDICATED +// [CHOSEN, not recovered] macOS client: the Cocoa host stands in for the Win32 message pump and +// entry chain (docs/macos-s2-4.md). The headers mirror the Win32 client list above. +# include // exit(0) on a posted quit +# include "../../IO/Input/Input.h" // IInputManager::setHasFocus +# include "../Utility/Vars.h" // Vars::enableProfiling around the main loop +# include "BF2Window.h" // the game window at BF2Engine+0x10 +# include "../../Sound/BfSound.h" // g_bfSound - the focus-loss mute +# include "../../Sound/NullSound.h" // ISoundEngine::setMasterVolume +# include "../../Menu/IMenuLogic.h" // menuLogic - the active menu +# include "BF2Console.h" // IMenuLogic::getConsole()->getConsoleActive() +# include "../../Platform/macOS/CocoaHost.h" #endif // Rebuilds the single command-line string the engine expects. The C runtime has already stripped the @@ -88,10 +104,24 @@ namespace io { extern IBase* inputManager; } // ds:0x8AC8CA4 - Core/Globa static void allowAccessibilityShortcutKeys(bool allow); static void restoreDesktopSettings(); # if !DEDICATED -static BOOL CALLBACK lockLoadedModule(PCSTR moduleName, ULONG moduleBase, ULONG moduleSize, PVOID userContext); +# if defined(_M_IX86) +typedef ULONG LoadedModuleBase; +# else +// [CHOSEN, not recovered] x64 (https://github.com/B2BF/OpenBF2/issues/7): dbghelp maps +// EnumerateLoadedModules to EnumerateLoadedModules64, whose callback takes a 64-bit base. +typedef DWORD64 LoadedModuleBase; +# endif +static BOOL CALLBACK lockLoadedModule(PCSTR moduleName, LoadedModuleBase moduleBase, ULONG moduleSize, PVOID userContext); static void trimOtherProcessesAndFileCache(); static int bf2MessageHandler(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam); # endif +#elif defined(__APPLE__) && !DEDICATED +class IBase; +namespace io { extern IBase* inputManager; } // Core/Globals.cpp defines it as IBase* + +// [CHOSEN, not recovered] The macOS counterparts of the Win32 pieces above (bottom of this file). +static void restoreDesktopSettings(); +static int bf2MessageHandler(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam); #endif BF2::BF2() @@ -145,14 +175,25 @@ bool BF2::init(const std::string& commandLine) startImmediately = true; if (startImmediately) - m_engine->startGame(false, true); // TWO bools: 0x8052979 xor eax,eax -> [esp+4]; + { + const bool started = m_engine->startGame(false, true); // TWO bools: 0x8052979 xor eax,eax -> [esp+4]; // mov edx,1 -> [esp+8]; call at 0x805298B +#if defined(__APPLE__) && !DEDICATED + bf2warmup::startResult(started); // [CHOSEN] +warmupLevel: a failed start exits +#else + (void)started; +#endif + } #if defined(_WIN32) && !DEDICATED // BF2.exe 0x401FE5: hand the window BF2's message handler (slot +0x30). The window exists only // when BF2Engine::init ran with isDedicated() false; `+dedicated 1` leaves it null. if (Window* window = m_engine->getWindow()) window->addMessageHandler(bf2MessageHandler); +#elif defined(__APPLE__) && !DEDICATED + // [CHOSEN, not recovered] The same registration for the macOS window. + if (Window* window = m_engine->getWindow()) + window->addMessageHandler(bf2MessageHandler); #endif return true; } @@ -190,6 +231,12 @@ void BF2::handleInGameWinMessages() restoreDesktopSettings(); // the same five calls bf2WinMain makes on exit exit(0); // no engine shutdown at all, as shipped } +# if !DEDICATED + // [TEMP] [CHOSEN, not recovered] A BF2_INPUT_SCRIPT run ignores the real keyboard and mouse + // (Platform/Windows/WinInputScript.h). [RETIRE-WHEN: client-test-automation-replaced] + if (inputscript::winInputScriptActive() && inputscript::winInputScriptIsRealInput(msg.message)) + continue; +# endif TranslateMessage(&msg); DispatchMessageA(&msg); } @@ -198,6 +245,9 @@ void BF2::handleInGameWinMessages() # if !DEDICATED if (menuLogic) deviceMask = static_cast(-2); // every device but bit 0 while a menu is up + // [TEMP] [CHOSEN, not recovered] One BF2_INPUT_SCRIPT tick per pump; nothing without the variable. + if (inputscript::winInputScriptActive() && m_engine && m_engine->getWindow()) + inputscript::winInputScriptPump(m_engine->getWindow()->getHwnd(), menuLogic != 0); # endif if (m_engine) { @@ -217,6 +267,33 @@ void BF2::handleInGameWinMessages() # endif } } +#elif defined(__APPLE__) && !DEDICATED + // [CHOSEN, not recovered] The Cocoa pump in place of PeekMessage/DispatchMessage: it drains + // every pending event and reports a posted quit as WM_QUIT does. The focus and mute logic + // below repeats the Win32 arm above unchanged. + if (macos::CocoaHost::instance().pumpEvents()) + { + restoreDesktopSettings(); + exit(0); // no engine shutdown, as on Win32 + } + + unsigned int deviceMask = static_cast(-1); + if (menuLogic) + deviceMask = static_cast(-2); + if (m_engine) + { + if (Window* window = m_engine->getWindow()) + { + const bool hasFocus = window->getHasFocus(); + if (io::inputManager) + static_cast(io::inputManager)->setHasFocus(hasFocus, deviceMask); + if (!settings->boolGet("GSDeveloper", false) && g_bfSound && g_bfSound->engine()) + { + ISoundEngine* engine = g_bfSound->engine(); + engine->setMasterVolume(hasFocus ? 1.0f : 0.0f); + } + } + } #endif } @@ -224,6 +301,193 @@ void BF2::handleInGameWinMessages() } // namespace dice +#if defined(__APPLE__) && !DEDICATED + +// [CHOSEN, not recovered] macOS client: the desktop-state and window-message pieces of the +// Win32 chain below, on the Cocoa host. There was no retail macOS image; see docs/macos-s2-4.md. + +namespace dice { +namespace hfe { + +using namespace hostmsg; + +// Win32 restores accessibility keys, mouse trails and the screensaver; macOS has no counterpart +// for the first two, and the display-sleep assertion stands for the screensaver switch. The +// cursor is released in case a relative-mode mouse still held it. +static void restoreDesktopSettings() +{ + macos::CocoaHost& host = macos::CocoaHost::instance(); + host.setRelativeMouseMode(false); + host.preventDisplaySleep(false); +} + +// The menu key ring (declared in BF2.h); the console ring is defined in BF2Console.cpp. +char menuKeyBuffer[256]; +int menuKeyCount = 0; +int menuKeyRead = 0; +int menuKeyWrite = 0; + +// The Win32 ring writers, unchanged: the write index wraps at 256 and the count wraps to 0. +static int pushConsoleChar(char c) +{ + int index = consoleCharWrite; + if (consoleCharWrite > 255) + index = 0; + consoleCharBuffer[index] = c; + consoleCharWrite = index + 1; + if (++consoleCharCount > 255) + consoleCharCount = 0; + return 0; +} + +static int pushMenuKey(char key) +{ + int index = menuKeyWrite; + if (menuKeyWrite > 255) + index = 0; + menuKeyBuffer[index] = key; + menuKeyWrite = index + 1; + if (++menuKeyCount > 255) + menuKeyCount = 0; + return 0; +} + +// GetAsyncKeyState(VK_CONTROL) / (VK_MENU). [CHOSEN] Command counts as Ctrl, so Command-C/V/X +// work as the Mac shortcuts; BF2Window_macos.cpp turns Command+letter into the control character. +static bool controlKeyDown() +{ + return (macos::CocoaHost::instance().modifierFlags() & + (macos::HostModControl | macos::HostModCommand)) != 0; +} + +static bool altKeyDown() +{ + return (macos::CocoaHost::instance().modifierFlags() & macos::HostModOption) != 0; +} + +// The Win32 bf2MessageHandler with the same arms. Omitted: the Caps Lock switch-off on +// WM_ACTIVATEAPP and on an in-game Caps Lock press (SendInput of VK_CAPITAL), which macOS offers +// no supported counterpart for; Caps Lock stays as the user set it. WM_INPUTLANGCHANGEREQUEST +// does not occur on macOS. +static int bf2MessageHandler(HWND /*hwnd*/, UINT message, WPARAM wParam, LPARAM lParam) +{ + if (message > WM_LBUTTONDOWN) + { + if (message == WM_LBUTTONUP) + { + if (settings && !settings->boolGet("GSDedicated", false) && menuLogic) + { + menuLogic->onMouseButtonUp(); + return 0; + } + } + else if (message == WM_LBUTTONDBLCLK) + { + if (settings && !settings->boolGet("GSDedicated", false) && menuLogic) + { + menuLogic->onMouseDoubleClick(); + return 0; + } + } + return 0; + } + if (message == WM_LBUTTONDOWN) + { + if (settings && !settings->boolGet("GSDedicated", false) && menuLogic) + menuLogic->onMouseButtonDown(); + return 0; + } + if (message == WM_MOUSEMOVE) + { + if (settings && !settings->boolGet("GSDedicated", false) && menuLogic) + menuLogic->onMouseMove(static_cast(lParam & 0xFFFF), + static_cast((lParam >> 16) & 0xFFFF)); + return 0; + } + + switch (message) + { + case WM_KEYDOWN: + if (!settings) + return 0; + if (settings->boolGet("GSDedicated", false)) + return 0; + if (!menuLogic || wParam != VK_DELETE) + return 0; + pushMenuKey(127); // DEL reaches the menu as 127 + return 0; + + case WM_CHAR: + if (!settings) + return 0; + if (settings->boolGet("GSDedicated", false)) + return 0; + pushConsoleChar(static_cast(wParam)); + if (!menuLogic || (menuLogic->getConsole() && menuLogic->getConsole()->getConsoleActive())) + return 0; + if (!controlKeyDown() || (controlKeyDown() && altKeyDown())) + { + if (wParam == 27) + menuLogic->onEscape(); + else + pushMenuKey(static_cast(wParam)); + return 0; + } + { + const char key = static_cast(wParam | 0x60); + if (key == 'v' || key == 'c' || key == 'x') + pushMenuKey(key); + } + return 0; + + default: + return 0; + } +} + +// The bf2Main/bf2WinMain shape of the Win32 client entry: desktop state saved, BF2 created, the +// pump-and-mainLoop loop, the handler removed, BF2 deleted, desktop state restored. +static int bf2MacMain(const std::string& commandLine) +{ + macos::CocoaHost& host = macos::CocoaHost::instance(); + host.initApplication(); // NSApplication before any window exists + host.preventDisplaySleep(true); // SPI_SETSCREENSAVEACTIVE 0 counterpart + + g_system->restoreFPUExceptions(); + BF2* bf2 = new BF2(); + if (!bf2->init(commandLine)) + { + restoreDesktopSettings(); + return 42; + } + + Vars::enableProfiling(true); + const std::string demo = settings->stringGet("GSDemo", std::string()); + if (!demo.empty() && bf2Engine) + bf2Engine->playDemo(true, demo); + + do + { + g_system->restoreFPUExceptions(); + bf2->handleInGameWinMessages(); + } + while (bf2Engine->mainLoop()); + + Vars::enableProfiling(false); + if (Window* window = bf2Engine->getWindow()) + window->removeMessageHandler(bf2MessageHandler); + + delete bf2; + g_system->storeAndTurnOffFPUExceptions(); + restoreDesktopSettings(); + return 0; +} + +} // namespace hfe +} // namespace dice + +#endif // __APPLE__ && !DEDICATED + #if defined(_WIN32) // Windows GUI entry and desktop-state handling shared by both images. The dedicated @@ -295,9 +559,9 @@ static void restoreDesktopSettings() // the memory-locking trio of BF2::init (client only) // . The IDB named it after its use: every loaded module's pages get locked. -static BOOL CALLBACK lockLoadedModule(PCSTR /*moduleName*/, ULONG moduleBase, ULONG moduleSize, PVOID /*userContext*/) +static BOOL CALLBACK lockLoadedModule(PCSTR /*moduleName*/, LoadedModuleBase moduleBase, ULONG moduleSize, PVOID /*userContext*/) { - VirtualLock(reinterpret_cast(moduleBase), moduleSize); + VirtualLock(reinterpret_cast(static_cast(moduleBase)), moduleSize); return TRUE; } @@ -692,6 +956,60 @@ int main(int argc, char** argv) #endif // dedicated - the headless console entry +#elif defined(__APPLE__) && !DEDICATED +#include +#include +#include +#include + +// [CHOSEN, not recovered] The macOS client entry point: the argv join of the POSIX main, then +// the Win32 client's entry chain (bf2MacMain above). +// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: macos-startup-stable] Coordinator diagnostic: +// with BF2_EXIT_TRACE set, print the stack of whoever calls exit(). lldb cannot attach through +// the sandbox-exec run harness. Registered first, so it runs last, still inside exit(). +static void bf2MacExitTrace() +{ + void* frames[64]; + const int count = backtrace(frames, 64); + std::fprintf(stderr, "[exit-trace] exit() reached from:\n"); + backtrace_symbols_fd(frames, count, 2); +} + +// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: macos-startup-stable] Coordinator diagnostic: +// with BF2_ABORT_TRACE set, stdout is unbuffered (the harness redirects it to client.log, and a +// fully buffered stdout loses its last lines at abort()) and SIGABRT prints the aborting stack. +static void bf2MacAbortTrace(int) +{ + void* frames[64]; + const int count = backtrace(frames, 64); + std::fprintf(stderr, "[abort-trace] SIGABRT raised from:\n"); + backtrace_symbols_fd(frames, count, 2); + std::signal(SIGABRT, SIG_DFL); +} + +int main(int argc, const char** argv) +{ + if (std::getenv("BF2_EXIT_TRACE")) + std::atexit(bf2MacExitTrace); + if (std::getenv("BF2_ABORT_TRACE")) + { + std::setvbuf(stdout, 0, _IONBF, 0); + std::signal(SIGABRT, bf2MacAbortTrace); + } + dice::hfe::g_system = new dice::hfe::System(); + + std::string commandLine; + for (int i = 1; i < argc; ++i) + appendCommandLineArg(commandLine, argv[i], i == 1); + + const int result = dice::hfe::bf2MacMain(commandLine); + if (result == 42) + std::cerr << "fatal error: argument parsing failed" << std::endl; + if (dice::hfe::g_system) + delete dice::hfe::g_system; + return result; +} + #else // [PLATFORM] The ELF entry point. ELF 0x8052ab0. diff --git a/Code/BF2/Game/Main/BF2.h b/Code/BF2/Game/Main/BF2.h index 57c8c2f86..9f7fb8efd 100644 --- a/Code/BF2/Game/Main/BF2.h +++ b/Code/BF2/Game/Main/BF2.h @@ -38,12 +38,16 @@ class BF2 BF2Engine* m_engine; // offset 0 - the only member }; -#if defined(_WIN32) && !DEDICATED +#if !DEDICATED // Keyboard rings filled by window messages and consumed by menu/console text input. -// Toggling either UI flushes its ring. [INFERRED] Global names. +// Toggling either UI flushes its ring. [INFERRED] Global names. The console ring is defined in +// BF2Console.cpp on every platform; the menu ring beside the Win32 window procedure in BF2.cpp. extern char consoleCharBuffer[256]; -extern char menuKeyBuffer[256]; extern int consoleCharCount, consoleCharRead, consoleCharWrite; +#endif +// [CHOSEN, not recovered] The macOS client fills the menu ring too (BF2.cpp, __APPLE__ arm). +#if (defined(_WIN32) || defined(__APPLE__)) && !DEDICATED +extern char menuKeyBuffer[256]; extern int menuKeyCount, menuKeyRead, menuKeyWrite; #endif diff --git a/Code/BF2/Game/Main/BF2ClientFrontiers.cpp b/Code/BF2/Game/Main/BF2ClientFrontiers.cpp deleted file mode 100644 index d2d2659ee..000000000 --- a/Code/BF2/Game/Main/BF2ClientFrontiers.cpp +++ /dev/null @@ -1,32 +0,0 @@ -// [INFERRED] diagnostic companions to BF2ClientSeams.h, not recovered bodies. -#include "BF2ClientSeams.h" -#if !DEDICATED -#include -#include - -namespace dice { namespace hfe { -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: local-profile-client-callers] -// The native manager publishes through +C8, with two approved abort-only positions. -// The remaining activateMod caller chain first stops at untyped +D0. These signatures -// describe the engine callers, not a recovered LocalProfileManager vtable. -#define BF2_LOCAL_PROFILE_FRONTIER(method) \ - std::fprintf(stderr, "[FRONTIER] dice::hfe::" #method ": LocalProfileManager suffix is unrecovered\n"); \ - std::fflush(stderr); \ - std::abort() - -void localProfileManager_vslot0x70(IBase*, const std::string&) { BF2_LOCAL_PROFILE_FRONTIER(localProfileManager_vslot0x70); } -const std::string& localProfileManager_vslot0xD0(IBase*, std::string&, int) { BF2_LOCAL_PROFILE_FRONTIER(localProfileManager_vslot0xD0); } -#undef BF2_LOCAL_PROFILE_FRONTIER - -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: swiff-host-server-browser] -// Haptic targets remain null until their implementations exist; menu initialization -// checks for null before dispatching to them. -IBase* g_hapticForceTargets[6] = { 0, 0, 0, 0, 0, 0 }; -#define BF2_MENU_SEAM_FRONTIER(name, text) \ - std::fprintf(stderr, "[FRONTIER] dice::hfe::" #name ": " text "\n"); \ - std::fflush(stderr); \ - std::abort() -void hapticTarget_vslot0x4C(IBase*, const double*) { BF2_MENU_SEAM_FRONTIER(hapticTarget_vslot0x4C, "the haptic force target's +0x4C (a NovintHFX::Vect3 setter) is unrecovered"); } -#undef BF2_MENU_SEAM_FRONTIER -} } -#endif diff --git a/Code/BF2/Game/Main/BF2ClientSeams.h b/Code/BF2/Game/Main/BF2ClientSeams.h index 0826b02e0..5080e2640 100644 --- a/Code/BF2/Game/Main/BF2ClientSeams.h +++ b/Code/BF2/Game/Main/BF2ClientSeams.h @@ -75,26 +75,9 @@ namespace hud { class BF2HudManager; // Menu/BF2HudManager.h: recovered construction, incomplete virtual surface } // namespace hud -// [FRONTIER] [CHOSEN, not recovered] Partial voice-client declaration used by HUD code. -// Construction, registration, and update are omitted (RW-94); bf2VoipClient must stay null. -// [RETIRE-WHEN: voip-client-hud-seam] Replace this declaration with the complete class -// before constructing a client. Its virtual positions and layout are not ABI-compatible. -class BF2VoipClient -{ -public: - BF2VoipClient(); - // . A folded byte getter: the leader channel is in use. - virtual bool getUsingLeaderChannel(); // retail +0xA0 - // . The HUD filter's leader-channel toggle; reads the local - // player's squad-leader/commander state and answers the new state. - virtual bool updateLeaderChannel(bool pressed); // retail +0xA4 - // . The other folded byte getter, read before push-to-talk. - virtual bool getPushToTalkEnabled(); // retail +0xA8 - // . The HUD filter's push-to-talk edge. - virtual void setPushToTalk(bool pressed); // retail +0xB4 - - virtual bool isBusy(); // retail +0xE4 -}; +// The voice client (BF2.exe vtable 0x89C1A8): Game/VoipClient/BF2VoipClient.h. Callers include that +// header; this one only names the type for the singleton slot below. +class BF2VoipClient; // Globals the client image owns. Defined in Game/Main/BF2Engine.cpp ([CHOSEN] placement: their // .data neighbours are that TU's statics - see the definitions). @@ -103,8 +86,8 @@ extern BF2VoipClient* bf2VoipClient; // ds:0x9A4DA0 - the "Bf2Vo extern BF2Render* g_bf2Render; // ds:0x9A5580 - published by BF2Render ctor extern IBase* g_geometryTemplateManager;// ds:0x9A5578 - 20 PE readers after init extern IBase* g_renderer; // BF2.exe `g_Renderer` - [UNRESOLVED] symbol name -extern IBase* unresolvedGlobalA33C08; // ds:0xA33C08; bf2_w32ded ds:0x8B25B0, written by - // ai::AIInstanceServer::updateInstance - [UNRESOLVED] identity +extern IBase*& unresolvedGlobalA33C08; // ds:0xA33C08 = ai::g_aiInstance (BF2.exe 0x801030, + // AIInstanceServer::updateInstance); bf2_w32ded ds:0x8B25B0 // The client's singleton slots (BF2.exe 0x4301A9 registers them; ds:0x987340..0x987398). The // first two rows pass IID 1 and flags 1, transcribed as-is in Core/ModuleRegistry.cpp. @@ -136,14 +119,8 @@ extern IBase* g_serverLogoManager; // ds:0x987340 "ServerLogo // Remaining client seams use role-based names where known and vslot names where // [UNRESOLVED]. Slot comments describe the PE ABI; typed interfaces own other services. -bool modInfo_vslot0x30(IBase* modInfo, const std::string& modName); // IModInfo +0x30 startGame join result 8 - [UNRESOLVED] role -void localProfileManager_vslot0x70(IBase* lpm, const std::string& value); // +0x70 activateMod* -const std::string& localProfileManager_vslot0xD0(IBase* lpm, std::string& scratch, int arg); // +0xD0 activateMod* -void bf2VoipClient_update(BF2VoipClient* voip); // +0x9C mainLoop [INFERRED] role -bool unresolvedGlobalA33C08_vslot0x18(); // +0x18 mainLoop (ragdoll viewer), 0x4038A0 -// Optional haptic force targets; the declared seam requires their actual interfaces. -extern IBase* g_hapticForceTargets[6]; // ds:0x9EBEC8, 0x9EBECC, 0x9EBF00, 0x9EBF04, 0x9EBF08, 0x9EBF0C [UNRESOLVED] identity; null in this image -void hapticTarget_vslot0x4C(IBase* target, const double* force3); // +0x4C a NovintHFX::Vect3 built from three doubles +bool modInfo_vslot0x30(IBase* modInfo, const std::string& modName); // IModInfo +0x30 startGame join result 8: getModFromPath != null +bool unresolvedGlobalA33C08_vslot0x18(); // +0x18 mainLoop (ragdoll viewer), 0x40D227: IAIInstance::isInitialized } // namespace hfe } // namespace dice diff --git a/Code/BF2/Game/Main/BF2Engine.cpp b/Code/BF2/Game/Main/BF2Engine.cpp index 6c3bc007b..bad39b591 100644 --- a/Code/BF2/Game/Main/BF2Engine.cpp +++ b/Code/BF2/Game/Main/BF2Engine.cpp @@ -3,13 +3,14 @@ // Coordinates startup, the frame loop and shutdown. Preserve the explicit retail Debug line numbers. #include "BF2Engine.h" +#include "../PunkBuster/PbGlue.h" +#include "PerformanceLogging.h" // +0x74, deleted in shutdownGame and shutdownEngine (every image) #include "BF2EngineSetup.h" #include "BF2Log.h" // [INFERRED] path; Game/Main/BF2Log.cpp is attested #include "BF2Console.h" // [INFERRED] path #include "IFSMoviePlayer.h" // [INFERRED] path; the renderer plugin's movie player (checkMovie, the mainLoop movie arm) #include "../../Menu/ISwiffHost.h" // the typed front-end host and MenuEvent #include "../../IO/Input/Input.h" // io::IKeyboardDevice - the movie arm's escape poll -#include "../../IO/Input/FalconDevice.h" // client PE978FC4, the menu's mouse-mode global #include "../../Core/System.h" // [INFERRED] path; Core/System.cpp attested (anon-ns) #include "../../Core/EventManager.h" // [INFERRED] path; Core/EventManager.cpp attested #include "../../Core/IProfilerClient.h" // [INFERRED] path @@ -25,7 +26,11 @@ #include "../IGame.h" // [INFERRED] path #include "../ControlSettings.h" // IControlSettings::setMappingInput - the (10,12) handler #include "../GlobalSettings.h" // IGlobalSettings::getNamePrefix - the clan tag applyProfileNameSettings reads -#include "../IGameServer.h" // recovered secondary interface; startServer is +0x1C +#include "../IGameServer.h" +#if defined(__APPLE__) && !DEDICATED +#include "../../Platform/macOS/Warmup.h" // [CHOSEN] +warmupLevel (port addition) +#include "../../Platform/macOS/HitchTrace.h" // [CHOSEN] BF2_HITCH_TRACE (port addition, measurement) +#endif // recovered secondary interface; startServer is +0x1C #include "../IGameClient.h" #include "../IGameLogic.h" // [INFERRED] path #include "../../Core/Thread.h" // [INFERRED] path; Thread::Priority is nested @@ -47,6 +52,7 @@ #include "../../Core/Registry.h" #include "../../IO/Localization/ExcelLexicon.h" #include "../Utility/SimpleParser.h" +#include "../MatchMaking/OnlineProvider.h" // [CHOSEN, not recovered] +gamespy #include "../Objects/Game/SupplyDropManager.h" // shutdown: Instance() / Release() // [INFERRED] path - promoted to its own header #include "../MapList.h" // mapList - region 1 owns its config-file default #include "../Utility/Vars.h" // Vars::getFloat - the frame limiter's overhead var @@ -54,7 +60,12 @@ #include "Demo.h" // [INFERRED] header path; demo.cpp itself is attested #include "../../Scene/Object/PlayerManager.h" // the real PlayerManager - replaces the local shim #include "../Objects/IPlayer.h" // per-player handleFrameUpdate loop +#include "../Objects/IObjectTemplate.h" // [TEMP] BF2_PLAY_TRACE: the vehicle template name #include "../Objects/ICameraObject.h" // mainLoop's held camera: getCamera / setInterpolatedMode +#if !DEDICATED +#include "../VoipClient/BF2VoipClient.h" // the "Bf2VoipClient" singleton (ds:0x9A4DA0) +#include "../../Menu/HudWidescreen.h" +#endif #include #include @@ -67,24 +78,33 @@ #include "../DemoRecorder/DemoConfig.h" // playDemo's config-from-name branch #include "BF2.h" // handleEvent case 16 -> BF2::handleInGameWinMessages -#include "BF2FrameInterpolator.h" // +0x1C client-only object; ctor real, three methods remain [FRONTIER] +#include "BF2FrameInterpolator.h" // +0x1C client-only object #if !DEDICATED #include "../../RendMisc/IRenderView.h" #include "../../RendMisc/IRenderer.h" #include "../HudInformationLayer.h" #include "../Objects/Fx/PersistentExplosionEffectManager.h" #endif -#include "../../Sound/BfSound.h" // IBfSound* g_bfSound - the client's menu/movie arms +#include "../../Sound/BfSound.h" +#if defined(__APPLE__) && !DEDICATED +#include "../../Sound/SoundEngine/BfSoundEngine.h" // [TEMP] SoundStats for BF2_PLAY_TRACE +#endif // IBfSound* g_bfSound - the client's menu/movie arms #include "../../IO/Input/Input.h" // io::IInputManager / IInputDeviceManager - the client's input arms #include // time / difftime - sessionStartTime +#include // [TEMP] std::tolower - the input-script query +#include #include // memcpy - updateInput's sample copy #include // std::fprintf - the [FRONTIER] stop in startGame's client branch #include // std::abort - the same stop #if !DEDICATED #include "BF2ClientSeams.h" // [FRONTIER] client collaborators without recovered classes +#include "../../AI/AIInterface/AIInstance.h" // ai::g_aiInstance, IAIInstance (ds:0xA33C08 in the client) #include "../LocalProfileManager.h" // native client startup interface #include "../ProfileManager.h" // renderMenu case 14 clears the pending transition #include "../../Menu/BF2HudManager.h" // constructor and established virtual prefix; publication gated +#if !DEDICATED +#include "../../Geom/GeometryTemplateManager.h" // shutdown: the client arm's template clear (+0x28) +#endif #include #include #include "../../Core/Ids.h" // the menu CIDs / IID_IMenuLogic / IID_IFSMoviePlayer @@ -92,7 +112,22 @@ #include "../../Menu/IMenuLogic.h" // menuLogic #include "../../Sound/BfSound/MusicPlayer.h" #include "../../IO/Input/PlayerInput.h" // updateInput's per-tick copy +#if defined(_WIN32) #include // ShellExecuteA - restartBF2 / activateMod / browseModHomepage +#elif defined(__APPLE__) +// [CHOSEN, not recovered] macOS: the cursor, minimize, URL and relaunch counterparts. +#include "../../Platform/macOS/CocoaHost.h" +#include "../../Platform/macOS/MacSystem.h" +#include "../../Platform/macOS/ClientPaths.h" +#include +#endif +#endif + +#if !DEDICATED && (defined(_WIN32) || defined(__APPLE__)) +#include "../../Platform/InputScript.h" // [TEMP] aim / walk-to query (BF2_INPUT_SCRIPT) +#include +#include +#include #endif // Middleware attribution functions have global scope. Preserve their startup call order. @@ -137,6 +172,11 @@ bool BF2Engine::getMenuActive() const // [CHOSEN] accessor with getMenuActive's shape: the movie player is a client-only member, and // mainLoop tests it in four places that must fold to nothing in a dedicated build. +#if DEDICATED +// [TEMP] the dedicated image has no BF2_HOST_TRACE (the helper below is client-only). +#define BF2_HOST_TRACE_SITE(step, value) ((void)0) +#endif + bool BF2Engine::isMoviePlaying() const { #if DEDICATED @@ -235,6 +275,10 @@ namespace memory { void nextVisualFrame(); } namespace memory { void nextVisualFrame() { } } // placeholder - see above namespace io { extern IBase* inputManager; extern IBase* inputDeviceManager; } // Core/Globals.cpp defines both as IBase* +#if !DEDICATED +extern Mat4 g_demoTraceCameraMatrix; // BF2Render.cpp, [TEMP] +extern bool g_demoTraceCameraValid; +#endif namespace { #if !DEDICATED @@ -247,6 +291,270 @@ void musicTraceSite(const char* site) if (armed < 0) armed = std::getenv("BF2_TRACE_MUSIC") ? 1 : 0; if (armed) { std::fprintf(stderr, "[MUSIC] event 0 from %s\n", site); std::fflush(stderr); } } +#if defined(__APPLE__) +// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: macos-singleplayer-hosting-validated] +// BF2_HOST_TRACE=1: one read-only stderr line per startMission/startGame exit, naming the step +// (the client-hosted instant battle that sometimes never loads). +void hostTrace(const char* step, int value) +{ + static int armed = -1; + if (armed < 0) armed = std::getenv("BF2_HOST_TRACE") ? 1 : 0; + if (armed) { std::fprintf(stderr, "[host] %s %d\n", step, value); std::fflush(stderr); } +} +#define BF2_HOST_TRACE_SITE(step, value) hostTrace(step, static_cast(value)) +#else +#define BF2_HOST_TRACE_SITE(step, value) ((void)0) +#endif +#if defined(__APPLE__) +// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: macos-ingame-play-validated] +// BF2_PLAY_TRACE=1: once a second, one read-only stderr line about the local player (alive, +// vehicle template and seat root, position, view direction), the players alive per team, and +// the sound engine (initialized, provider, playing samples, allocated/max voices). Judging +// scripted playthroughs from the log. Nothing is written. +void playTraceTick() +{ + static int armed = -1; + if (armed < 0) armed = std::getenv("BF2_PLAY_TRACE") ? 1 : 0; + if (!armed || !world::playerManager) + return; + static double last = 0.0; + const double now = static_cast(std::clock()) / CLOCKS_PER_SEC; + if (now - last < 1.0 && last != 0.0) + return; + last = now; + int alive[3] = { 0, 0, 0 }, total[3] = { 0, 0, 0 }; + const std::list& players = world::playerManager->getPlayers(); + for (std::list::const_iterator it = players.begin(); it != players.end(); ++it) + { + const int team = (*it)->getTeam(); + if (team < 0 || team > 2) continue; + ++total[team]; + if ((*it)->getIsAlive()) ++alive[team]; + } + char sound[256] = "sound=none"; + if (g_soundEngine && g_soundEngine->isInitialized()) + { + const SoundStats* st = static_cast(g_soundEngine->getStats()); + if (st) + std::snprintf(sound, sizeof sound, "sound=on provider=\"%s\" playing=%d waiting=%d sources=%d maxVoices=%d", + st->providerInfo ? st->providerInfo : "", st->playing, st->waiting, st->sources, st->maxVoices); + } + else if (g_soundEngine) + std::snprintf(sound, sizeof sound, "sound=not-initialized"); + world::IPlayer* player = world::playerManager->getLocalHumanPlayer(); + if (!player) + { + std::fprintf(stderr, "[PLAY] no local player; players t1 %d/%d t2 %d/%d; %s\n", + alive[1], total[1], alive[2], total[2], sound); + // [TEMP] demo playback (no local player): the spectator camera's mode and the followed + // player's position, for the demo gate's movement judge (tools/macos/loopback/demo_cycle.py). + if (game && game->isPlayingDemo()) + { + if (IGameClient* client = static_cast(game->queryInterface(IID_IGameClient))) + { + const int followed = client->demoGetCurrentPlayerId(); + const bool freeFlying = client->demoIsFreeFlying(); + float fpos[3] = { 0, 0, 0 }; + int followedAlive = -1; + std::string followedName = "-"; + if (world::IPlayer* target = followed >= 0 ? world::playerManager->getPlayerFromId(followed) : 0) + { + followedAlive = target->getIsAlive() ? 1 : 0; + followedName = target->getName(); + if (world::IObject* vehicle = target->getVehicle()) + { + world::IObject* root = world::getRootParent(vehicle); + const Vec3& p = (root ? root : vehicle)->getAbsolutePosition(); + fpos[0] = p.x; fpos[1] = p.y; fpos[2] = p.z; + } + } + // The matrix BF2Render last handed to the render view: its translation row and the + // position of its orthonormal inverse (whichever is the eye, the other is not). + float cam[3] = { 0, 0, 0 }, camInv[3] = { 0, 0, 0 }; +#if !DEDICATED + if (g_demoTraceCameraValid) + { + const float* m = g_demoTraceCameraMatrix.m; + cam[0] = m[12]; cam[1] = m[13]; cam[2] = m[14]; + for (int k = 0; k < 3; ++k) + camInv[k] = -(m[12] * m[k * 4 + 0] + m[13] * m[k * 4 + 1] + m[14] * m[k * 4 + 2]); + } +#endif + // The string the HUD's followed-name text node draws (HudElementsDemoPlayerName.con). + const char* hudName = "-"; +#if !DEDICATED + if (g_hudInformationLayer) + if (const char** slot = static_cast(g_hudInformationLayer) + ->getStringByName("DemoPlayerNameString")) + hudName = *slot ? *slot : "(null)"; +#endif + std::fprintf(stderr, "[PLAY] demo free=%d follow=%d followAlive=%d followPos=%.2f/%.2f/%.2f " + "cam=%.2f/%.2f/%.2f camInv=%.2f/%.2f/%.2f hudName=%s| followName=%s\n", + freeFlying ? 1 : 0, followed, followedAlive, fpos[0], fpos[1], fpos[2], + cam[0], cam[1], cam[2], camInv[0], camInv[1], camInv[2], hudName, followedName.c_str()); + } + } + std::fflush(stderr); + return; + } + const char* vehicleName = "-"; + float pos[3] = { 0, 0, 0 }; + if (world::IObject* vehicle = player->getVehicle()) + { + world::IObject* root = world::getRootParent(vehicle); + if (vehicle->getTemplate()) vehicleName = vehicle->getTemplate()->getName().c_str(); + const Vec3& p = (root ? root : vehicle)->getAbsolutePosition(); + pos[0] = p.x; pos[1] = p.y; pos[2] = p.z; + } + float fwd[3] = { 0, 0, 0 }; + if (world::ICameraObject* camera = player->getCamera()) + { + const Mat4& m = camera->getTransformation(0.0f); + fwd[0] = m.m[8]; fwd[1] = m.m[9]; fwd[2] = m.m[10]; + } + std::fprintf(stderr, "[PLAY] alive=%d manDown=%d team=%d vehicle=%s pos=%.1f/%.1f/%.1f fwd=%.2f/%.2f/%.2f " + "players t1 %d/%d t2 %d/%d; %s\n", + player->getIsAlive() ? 1 : 0, player->getIsManDown() ? 1 : 0, player->getTeam(), vehicleName, + pos[0], pos[1], pos[2], fwd[0], fwd[1], fwd[2], alive[1], total[1], alive[2], total[2], sound); + std::fflush(stderr); +} + +// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: macos-client-perf-understood] +// BF2_FRAME_TRACE=1: once a second (wall clock), one stderr line with the frame count, the mean and +// worst frame time, and the mean wall time of each mainLoop section. +// BF2_HITCH_TRACE=: every frame with its section times goes to the hitch trace (HitchTrace.h). +// Measurement only: off by default, nothing in the loop changes. +namespace frametrace { +enum Section { Pre, Update, Script, Objects, Render, Tail, Count }; +static int s_armed = -1; +static std::chrono::steady_clock::time_point s_mark, s_frameStart, s_windowStart; +static double s_sum[Count], s_frameMax, s_frameSum; +static int s_frames, s_ticks; +inline bool armed() +{ + if (s_armed < 0) s_armed = (std::getenv("BF2_FRAME_TRACE") ? 1 : 0) | (bf2hitch::enabled() ? 2 : 0); + return s_armed != 0; +} +inline void begin() +{ + if (!armed()) return; + s_frameStart = s_mark = std::chrono::steady_clock::now(); + if (s_windowStart.time_since_epoch().count() == 0) s_windowStart = s_frameStart; +} +inline void mark(Section s) +{ + if (!armed()) return; + const std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now(); + const double ms = std::chrono::duration(now - s_mark).count(); + s_sum[s] += ms; + if (s_armed & 2) bf2hitch::section(s, ms); + s_mark = now; +} +inline void end(int ticks, bool inGame) +{ + if (!armed()) return; + mark(Tail); + if (s_armed & 2) bf2hitch::frame(inGame); + if (!(s_armed & 1)) return; + const double ms = std::chrono::duration(s_mark - s_frameStart).count(); + s_frameSum += ms; + if (ms > s_frameMax) s_frameMax = ms; + ++s_frames; + s_ticks += ticks; + const double window = std::chrono::duration(s_mark - s_windowStart).count(); + if (window < 1.0) return; + const double n = s_frames ? s_frames : 1; + std::fprintf(stderr, "[FRAME] %s fps=%.1f mean=%.1fms max=%.1fms ticks=%d | pre %.1f update %.1f script %.1f " + "objects %.1f render %.1f tail %.1f\n", + inGame ? "game" : "menu", s_frames / window, s_frameSum / n, s_frameMax, s_ticks, + s_sum[Pre] / n, s_sum[Update] / n, s_sum[Script] / n, s_sum[Objects] / n, s_sum[Render] / n, + s_sum[Tail] / n); + std::fflush(stderr); + for (int i = 0; i < Count; ++i) s_sum[i] = 0.0; + s_frameMax = s_frameSum = 0.0; + s_frames = s_ticks = 0; + s_windowStart = s_mark; +} +} // namespace frametrace +#define BF2_FRAME_MARK(s) frametrace::mark(frametrace::s) +#endif +#if !DEDICATED && (defined(_WIN32) || defined(__APPLE__)) +// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: client-test-automation-replaced] +// The input script's aim / face / walk-to query (Platform/InputScript.h): read-only. +bool scriptQuery(const char* target, float viewPos[3], float viewFwd[3], float targetPos[3]) +{ + if (!world::playerManager) + return false; + world::IPlayer* self = world::playerManager->getLocalHumanPlayer(); + if (!self || !self->getIsAlive()) + return false; + world::ICameraObject* camera = self->getCamera(); + if (!camera) + return false; + const Mat4& m = camera->getTransformation(0.0f); + for (int i = 0; i < 3; ++i) { viewPos[i] = m.m[12 + i]; viewFwd[i] = m.m[8 + i]; } + float x, y, z; + if (std::sscanf(target, "%f/%f/%f", &x, &y, &z) == 3) + { + targetPos[0] = x; targetPos[1] = y; targetPos[2] = z; + return true; + } + const std::string kind(target); + if (kind.compare(0, 5, "tmpl:") == 0 && world::objectManager) + { + // Nearest root object whose template name is one of the comma-separated names. + std::string names = "," + kind.substr(5) + ","; + for (char& c : names) c = static_cast(std::tolower(static_cast(c))); + float bestT = 1e30f; + bool foundT = false; + std::map& all = world::objectManager->getAllObjectsFromGrid(); + for (std::map::iterator it = all.begin(); it != all.end(); ++it) + { + world::IObject* o = it->second; + if (!o || o->getParent() || !o->getTemplate()) + continue; + std::string n = "," + o->getTemplate()->getName() + ","; + for (char& c : n) c = static_cast(std::tolower(static_cast(c))); + if (names.find(n) == std::string::npos) + continue; + const Vec3& pos = o->getAbsolutePosition(); + const float dx = pos.x - viewPos[0], dy = pos.y - viewPos[1], dz = pos.z - viewPos[2]; + const float d = dx * dx + dy * dy + dz * dz; + if (d < bestT) + { + bestT = d; foundT = true; + targetPos[0] = pos.x; targetPos[1] = pos.y + 1.0f; targetPos[2] = pos.z; + } + } + return foundT; + } + const int team = self->getTeam(); + float best = 1e30f; + bool found = false; + const std::list& players = world::playerManager->getPlayers(); + for (std::list::const_iterator it = players.begin(); it != players.end(); ++it) + { + world::IPlayer* p = *it; + if (p == self || !p->getIsAlive() || !p->getVehicle()) + continue; + if ((kind == "enemy" && p->getTeam() == team) || (kind == "friend" && p->getTeam() != team)) + continue; + if (kind != "enemy" && kind != "friend" && kind != "player") + return false; + world::IObject* root = world::getRootParent(p->getVehicle()); + const Vec3& pos = (root ? root : p->getVehicle())->getAbsolutePosition(); + const float dx = pos.x - viewPos[0], dy = pos.y - viewPos[1], dz = pos.z - viewPos[2]; + const float d = dx * dx + dy * dy + dz * dz; + if (d < best) + { + best = d; found = true; + targetPos[0] = pos.x; targetPos[1] = pos.y + 1.2f; targetPos[2] = pos.z; // chest height + } + } + return found; +} +const bool s_scriptQueryRegistered = (inputscript::setScriptQuery(&scriptQuery), true); +#endif bool s_menuMusicHold = true; // byte_96E340: activateMenu skips the menu-music start once bool s_cursorShown = true; // byte_96E3A3: mainLoop hides the cursor once, when a movie starts bool s_activateMenuOnFrame1 = true; // byte_96E3A4: mainLoop's first-frame login + activateMenu @@ -292,7 +600,7 @@ void updateMenuPause(int& state, bool menuUp) if (menuUp && (!gameLogic || gameLogic->getGameStatus() != 2)) // +0x158 wantPause = true; else - wantPause = playingDemo && client && static_cast(client)->isDemoPlaying(); // +0x68 + wantPause = playingDemo && client && static_cast(client)->isDemoAtEnd(); // +0x68 if (wantPause == (state >= 0)) return; // nothing to change if (!wantPause) @@ -355,6 +663,10 @@ SingleInstanceGuard::SingleInstanceGuard() #elif defined(_WIN32) && !DEDICATED handle = 0; // the editor: no guard, never a second instance isFirstInstance = true; +#elif defined(__APPLE__) && !DEDICATED + // [CHOSEN, not recovered] Same first/second-instance gate, using a per-user advisory lock. + lockFd = macos::acquireClientInstanceLock(); + isFirstInstance = lockFd >= 0; #endif } @@ -362,6 +674,10 @@ SingleInstanceGuard::~SingleInstanceGuard() { #if BF2_ENGINE_INSTANCE_MUTEX ReleaseMutex(handle); // not CloseHandle - as shipped (0x4083F0) +#elif defined(__APPLE__) && !DEDICATED + // [CHOSEN, not recovered] Keep the inode so contenders always lock the same file. + if (lockFd >= 0) + close(lockFd); #endif } #undef BF2_ENGINE_INSTANCE_MUTEX @@ -443,6 +759,11 @@ BF2Engine::BF2Engine(BF2* bf2Ptr) #endif } +// [CHOSEN, not recovered] True only while init parses the process command line. Client images +// parse again later (menu event 5, SwiffHost::setCommandLineFile), and that text can come from menu +// content; the online provider must only ever be chosen by the user's own process arguments. +static bool s_parsingProcessArguments = false; + bool BF2Engine::init(const std::string& commandLine) { bf2Log = new BF2Log(); // operator new(0x20) == 32 bytes @@ -450,7 +771,10 @@ bool BF2Engine::init(const std::string& commandLine) ISettingsRepostitory::createSingleton(); initDefaultSettings(); - if (!parseParameters(commandLine)) + s_parsingProcessArguments = true; + const bool parsed = parseParameters(commandLine); + s_parsingProcessArguments = false; + if (!parsed) return false; #if !DEDICATED @@ -488,10 +812,13 @@ bool BF2Engine::init(const std::string& commandLine) SingletonRegInfo sri = { std::string("HudManager"), reinterpret_cast(&hudManager), 0, 0, 4 }; classManager->registerSingleton(sri); // vptr+0x44 } - // [CHOSEN, not recovered] VoIP construction is omitted. - // There should be BF2VoipClient construction (PE 0x4519B0) and registration - // of "Bf2VoipClient" here. Keep the singleton absent until voice is wanted. - // [RETIRE-WHEN: client-voip-optional] See debt RW-94. + // BF2.exe 0x40C351: operator new(0xC8) + ctor 0x4519B0 (a failed allocation stores null), then + // the "Bf2VoipClient" singleton row with the HudManager row's flags (0x40C376..0x40C3AD). + bf2VoipClient = new BF2VoipClient(); + { + SingletonRegInfo sri = { std::string("Bf2VoipClient"), reinterpret_cast(&bf2VoipClient), 0, 0, 4 }; + classManager->registerSingleton(sri); // vptr+0x44 + } } #endif @@ -578,8 +905,9 @@ bool BF2Engine::init(const std::string& commandLine) io::mainConsole->runFullAccess("Init.con", "", "", "", "", "", "", "", "", io::Console::ignoredString_); // +0x2C - // [CHOSEN, not recovered] PunkBuster initialization and its console-command hook - // are omitted. Commands therefore run without the SDK's pre-dispatch filter. + // 0x40C9EB..0x40C9FD: the PunkBuster server glue, then the PB_ console pre-dispatch hook. + PbServerInitialize(); + io::mainConsole->setHandleCommandHook(HandleCommandHookPB); debugDraw = new DebugDraw; // operator new(1), 0x813195D-0x8131962 @@ -603,6 +931,17 @@ bool BF2Engine::init(const std::string& commandLine) return true; } +#if !DEDICATED +namespace { +// GeometryTemplateManager +0x28 (clear) on the client's ds:0x9A5578 slot, through the typed +// interface that the renderer-linked client builds carry. +void shutdownGeometryTemplates(IBase* manager) +{ + static_cast(manager)->clear(); +} +} // namespace +#endif + // Shuts down the game and engine services. // [INFERRED] Boolean return type; current callers discard the always-true result. bool BF2Engine::shutdown() @@ -653,6 +992,14 @@ bool BF2Engine::shutdown() shutdownGame(true); // the bool argument is 1 (0x8131d2c-0x8131d31) +#if !DEDICATED + // Client arm (BF2.exe 0x408E32..0x408ECF; absent from the server ELF). The music player that + // initEngine created: its nonvirtual destructor (0x7E1900) unregisters the ECMenu handler. + // The member is cleared whether or not it was set (0x408E54). + delete musicPlayer; + musicPlayer = 0; +#endif + // 6. World teardown. None of this has a counterpart in init() or initEngine(): mainTerrain and // the object templates are created by level loading, so shutdown() is doing double duty as // an engine teardown and a world teardown. @@ -663,11 +1010,33 @@ bool BF2Engine::shutdown() world::objectTemplateManager->deleteAll(false); // vtable +0x38, argument 0 +#if !DEDICATED + // BF2.exe 0x408E91: drop every geometry template the level loaded (GeometryTemplateManager + // +0x28) before the renderer goes away. + if (g_geometryTemplateManager) + shutdownGeometryTemplates(g_geometryTemplateManager); +#endif + // Instance() is called and its result discarded, purely to force the singleton into existence // so that Release() has something to tear down. Faithful to the binary, odd as it reads. world::SupplyDropManager::Instance(); world::SupplyDropManager::Release(); +#if !DEDICATED + // BF2.exe 0x408EAA: delete the HUD manager through its deleting destructor (slot 0, flag 1) + // and clear the "HudManager" singleton slot. Its widgets, Ref2System and HUD fonts hold renderer + // resources, so this must precede shutdownEngine, which unloads the renderer. + if (hudManager) + { + delete hudManager; + hudManager = 0; + } + + // BF2.exe 0x408EC0: the voice client's shutdown (+0x68); the object itself is never deleted. + if (bf2VoipClient) + bf2VoipClient->shutdown(); +#endif + shutdownSettingsRepostitory(); // mirrors init()'s initSettingsRepostitory() shutdownEngine(); @@ -704,14 +1073,27 @@ void BF2Engine::initDefaultSettings() settings->boolSet("GSLoadObfuscated", true); // +0x54 // (`mov [ebp+var_445], 1` at 0x812F97D) - sm->registerUserVar("GSFullScreen", false, io::VariableSet(0)); // bool + // GSFullScreen defaults to true: retail starts fullscreen unless +fullscreen 0 is given (parsed + // after this, in parseParameters). Client PE 0x4079A2 `mov byte [ebp-1], 1` feeds the typed helper + // 0x4074E0 (registerUserVar, then vptr+0x58 exists / vptr+0x54 boolSet when missing, then the + // default map); server ELF 0x812F9CC `movb $0x1, -0x446(%ebp)`, boolSet at 0x81301DD when the + // value is missing, then recorded in the +0x54 default map and the +0x48 set. Registered unsaved, + // so no profile file carries it. + if (sm->registerUserVar("GSFullScreen", false, io::VariableSet(0))) // bool + { + const bool fullScreenDefault = true; + if (!settings->boolExists("GSFullScreen")) + settings->boolSet("GSFullScreen", fullScreenDefault); + sm->m_boolDefaults.insert(std::make_pair(std::string("GSFullScreen"), fullScreenDefault)); + sm->m_boolUnknown.insert("GSFullScreen"); + } sm->registerUserVar("GSExtrapolateFrame", true, io::VariableSet(0)); // bool sm->registerUserVar("GSShowNetGraph", true, io::VariableSet(0)); // bool sm->registerUserVar("GSClPunkBuster", true, io::VariableSet(0)); // bool - // [UNRESOLVED] The thirteen registered variables' conditional default assignments + // [UNRESOLVED] The other twelve registered variables' conditional default assignments // are incomplete: matching the typed Exists/Set pairs to variables is unresolved, - // including the eight Boolean default values. Registration failure must remain visible. + // including seven Boolean default values. Registration failure must remain visible. } // Parses plus-prefixed command-line options and applies their settings. Option ids @@ -721,10 +1103,9 @@ bool BF2Engine::parseParameters(const std::string& commandLine) // [PLATFORM] Dedicated PE 0x404AF5 keeps the server name; client PE 0x409CBD // constructs "aidll.dll". Only the ELF overwrites its initial Win32 spelling. #if DEDICATED && defined(_WIN64) - // [CHOSEN, not recovered] Native x64 keeps the AI library name empty until a - // compatible library exists; UseAI=false skips loading and an explicit connection - // request retains the empty-name refusal. [RETIRE-WHEN: native-dedicated-ai-library] - std::string aiDll; + // [CHOSEN, not recovered] Native x64 shares the rebuilt client's AI image. + // https://github.com/kr4uzi/OpenBF2/issues/11 + std::string aiDll("aidll.dll"); #elif DEDICATED std::string aiDll("AIDLL_w32ded.dll"); #else @@ -759,8 +1140,14 @@ bool BF2Engine::parseParameters(const std::string& commandLine) if (cmd.length() != 0) { SimpleParser parser('+'); // [INFERRED] form: the ctor is fully inlined. No call is emitted +#if !DEDICATED + // [CHOSEN, not recovered] Owner-requested session override; bare +help keeps usage. + parser.add( 57, "help", "0/1 hides/shows tutorial messages; no value displays help"); + parser.add( 58, "?", "Displays command-line help"); +#else parser.add( 57, "help", "Displays this help"); parser.add( 58, "?", "Same as +help"); +#endif parser.add( 0, "dedicated", "Start in dedicated server mode"); parser.add( 1, "multi", "Allow starting multiple BF2 instances"); parser.add( 8, "config", "Sets path to the ServerSettings.con file to use"); @@ -797,6 +1184,18 @@ bool BF2Engine::parseParameters(const std::string& commandLine) parser.add( 44, "maxPlayers", "Sets max players."); parser.add( 59, "ranked", "Allows gamespy snapshot sending"); parser.add( 73, "dropDynamicSpawns", "Don't re-add dynamic spawn groups as round (re)starts."); +#if defined(__APPLE__) && !DEDICATED + // [CHOSEN, not recovered] macOS port addition (not retail): fills the native effect cache. + // Ids up to 73 are retail; 35 stays recovered-but-unregistered. + parser.add( 74, "warmupLevel", "Host the level locally, build its shaders, then quit (setup)"); +#endif + // [CHOSEN, not recovered] Port addition, every image (OnlineProvider.h): retail has no + // such option and always uses gamespy.com. + parser.add( 75, "gamespy", "Use this domain instead of gamespy.com for all online services"); +#if !DEDICATED + // [CHOSEN, not recovered] https://github.com/kr4uzi/OpenBF2/issues/33 + parser.add( 76, "widescreenHud", "Use the optional vanilla widescreen HUD (0 or 1; default 0)"); +#endif // Only registered parser IDs reach these sparse switch cases. std::list > keyList; // var_C8 @@ -873,6 +1272,10 @@ bool BF2Engine::parseParameters(const std::string& commandLine) break; case 20: // +fullscreen +#if defined(__APPLE__) && !DEDICATED + if (bf2warmup::active()) // [CHOSEN] +warmupLevel runs windowed (case 74) + break; +#endif settings->boolSet("GSFullScreen", atoi(value.c_str()) != 0); break; @@ -881,6 +1284,19 @@ bool BF2Engine::parseParameters(const std::string& commandLine) Vars::set("opt-nosound", value); break; +#if !DEDICATED + case 35: // BF2.exe 0x40AE6B: the lightmap-rendering-node switch. Recovered but + // unreachable in retail: no option is registered with id 35 (the client + // registers 34 options, none of them 35), so the parser never yields it. + if (value == "1") + { + // Retail first calls memory::set_max_alloc_size(0x18CBA80); omitted under the + // shared CRT heap policy (https://github.com/B2BF/OpenBF2/issues/7, as BFTerrain). + setLightmapRenderingNode(true); + } + break; +#endif + case 39: // +demo - three effects, and the third is easy to miss settings->stringSet("GSDemo", value); setMenuActive(false); @@ -910,7 +1326,16 @@ bool BF2Engine::parseParameters(const std::string& commandLine) break; case 57: // +help - case 58: // +? - ONE case label, and it returns false (0x8135EA3 xor eax,eax +#if !DEDICATED + // [CHOSEN, not recovered] Owner request 2026-11-09. + // Session-only: never change GeneralSettings or serialize this override. + if (value == "0" || value == "1") + { + settings->boolSet("GSCommandLineShowTutorialMessages", value == "1"); + break; + } +#endif + case 58: // +? and usage forms of +help return false (0x8135EA3 xor eax,eax // > the single retn). Region 1 never runs, so BF2Engine::init fails and // the process exits after printing the help - the shipped behaviour, and // the answer to this function's old "[UNRESOLVED] return value" note. @@ -955,6 +1380,58 @@ bool BF2Engine::parseParameters(const std::string& commandLine) settings->boolSet("dropDynamicSpawns", true); break; +#if defined(__APPLE__) && !DEDICATED + case 74: // +warmupLevel - [CHOSEN, not recovered] port addition (Warmup.h): + // a server start of like +loadLevel, then quit once every effect + // build has finished. The menu is skipped (startGame's menu flow). + if (value.compare("") != 0) + { + loadLevel.assign(value); + isServer = true; + bf2warmup::configure(value); + // Windowed, whatever +fullscreen or the profile say: a fullscreen client that + // starts behind another app (the setup launches it while the user works + // elsewhere) gets WM_ACTIVATEAPP false, and the mainLoop gate (byte52, event + // 15) then skips renderMenu and the world frame, so the JOIN waits and the + // first world frame's effects are not built until the window is activated. + // The window mode does not change the shader set. + settings->boolSet("GSFullScreen", false); + } + break; +#endif + + case 75: // +gamespy - [CHOSEN, not recovered] port addition: the + // domain every online service name is formed with. A value that cannot + // be used ends start-up like +help does; continuing would send logins + // and heartbeats to a domain the user did not ask for. + { + if (!s_parsingProcessArguments) + { + // A later parse (menu-supplied command line) never changes the provider. + std::fprintf(stderr, "+gamespy: ignored outside the process command line\n"); + std::fflush(stderr); + break; + } + std::string error; + if (!onlineProvider::setDomain(value, error)) + { + std::fprintf(stderr, "+gamespy: %s\n", error.c_str()); + std::fflush(stderr); + return false; + } + break; + } + +#if !DEDICATED + case 76: // [CHOSEN, not recovered] Process option, never a menu-script override. + if (!s_parsingProcessArguments) break; + if (!hud::widescreen::setRequested(value)) { + std::fprintf(stderr, "+widescreenHud: expected 0 or 1\n"); + std::fflush(stderr); + return false; + } + break; +#endif // 6 (+checkForAvailablePatch), 7 (+checkForPatch) and 10 (+lowPriority) are // registered but share the default target 0x8133400 - they parse and do nothing. default: @@ -964,6 +1441,19 @@ bool BF2Engine::parseParameters(const std::string& commandLine) } } + // [CHOSEN, not recovered] Not in retail: give the GameSpy SDK the service names of the domain + // +gamespy selected (nothing to do for the retail domain), before any service starts, and + // report the names in use once. This runs before the status monitor takes the terminal. + if (s_parsingProcessArguments) + { +#if !DEDICATED + hud::widescreen::configureMod(settings->stringGet("GSModDirectory", "mods/bf2")); +#endif + onlineProvider::prepareGameSpySdk(); + std::fprintf(stderr, "%s\n", onlineProvider::describe(DEDICATED == 0).c_str()); + std::fflush(stderr); + } + // Default missing config paths under GSModDirectory. Command-line maxPlayers and // gameMode also set their GSCommandLine counterparts to preserve precedence. // [UNRESOLVED] Unregistered option 26 has no identified role. @@ -1107,7 +1597,7 @@ bool BF2Engine::startGame(bool noAutoJoin, bool startFromMenu) // 2nd bool fro // [UNRESOLVED] One-byte game-present allocation; only nullness is tested. // The destructor frees it without accessing its contents. - delete dwordB0; // test / 0x8138b43 delete + ::operator delete(dwordB0); // test / 0x8138b43 delete: a bare operator delete dwordB0 = new char; // stored at 0x813830e #if !DEDICATED @@ -1121,6 +1611,24 @@ bool BF2Engine::startGame(bool noAutoJoin, bool startFromMenu) // 2nd bool fro bool menuFlow = false; if (startFromMenu) menuFlow = !settings->boolGet("GSDeveloper", false); // vptr+0x50 +#if defined(__APPLE__) + if (bf2warmup::active()) // [CHOSEN] +warmupLevel: the + { // non-menu start, as a developer host + menuFlow = false; + // The shader set follows the profile's video settings, so log in the profile the game will + // use: +playerName, else GlobalSettings' default user (the menu's own login). Without a + // profile the engine defaults apply (a new profile starts from them). + ILocalProfileManager* lpm = static_cast(classManager->getSingleton("LocalProfileManager")); + std::string profile = settings->stringGet("GSPlayerName", std::string()); + if (profile.empty()) + if (IBase* gs = classManager->getSingleton("GlobalSettings")) + profile = static_cast(gs)->getDefaultUser(); + bool loggedIn = lpm && lpm->getCurrentProfile(); + if (!loggedIn && lpm && !profile.empty()) + loggedIn = lpm->quickLogin(profile, settings->stringGet("GSPlayerPassword", std::string())); + bf2warmup::profile(loggedIn ? profile : std::string()); + } +#endif if (!menuFlow) { swiffHost->setGameStarting(true); // +0xD8 @@ -1169,6 +1677,29 @@ bool BF2Engine::startGame(bool noAutoJoin, bool startFromMenu) // 2nd bool fro swiffHost->setPage(2); } activateMenu(0); +#if defined(__APPLE__) + // [TEMP] [CHOSEN, not recovered] c-loopback harness switch, off unless + // BF2_MAC_COMMANDLINE_JOIN=1 is set. Shipped, the menu's ActionScript reads this page + // (dice.bf2.Logic.getCommandLine) and calls dice.bf2.Logic.joinCommandlineServer on its + // own; the macOS menu does not run that script yet. This makes the same host call + // as_logic_joinCommandlineServer makes (port +0x0E4, address +0x0DC, joinServer +0x100, + // query port 0), so the join event reaches renderMenu's case 3 as it would from the + // menu. [RETIRE-WHEN: macos-menu-actionscript] the menu script issues the join itself. + if (!settings->boolGet("GSIsServer", false)) + { + const char* commandLineJoin = std::getenv("BF2_MAC_COMMANDLINE_JOIN"); + if (commandLineJoin && commandLineJoin[0] == '1') + { + const int page = swiffHost->getPage(); + const int port = swiffHost->getPortSetting(); + const std::string address = swiffHost->getJoinAddressSetting(); + const bool queued = swiffHost->joinServer(address, port, 0); + std::fprintf(stderr, "[TEMP] BF2_MAC_COMMANDLINE_JOIN: page %d, joinServer(%s, %d, 0) -> %d\n", + page, address.c_str(), port, queued ? 1 : 0); + std::fflush(stderr); + } + } +#endif return true; } } @@ -1181,7 +1712,9 @@ bool BF2Engine::startGame(bool noAutoJoin, bool startFromMenu) // 2nd bool fro SingletonRegInfo sri = { std::string("Game"), reinterpret_cast(&game), IID_IGame, CID_GameServer, 2 }; classManager->registerSingleton(sri); // ClassManager vtable +0x44, 0x81383c8 - if (!game->init()) // IGame vtable +0x18, 0x81383ff + const bool gameInit = game->init(); + BF2_HOST_TRACE_SITE("server game->init", gameInit); + if (!gameInit) // IGame vtable +0x18, 0x81383ff return false; // > edx=0, return 0 // renameAndReOpenPureLog composes "Logs/" + arg1 + arg2 + ".log" (verified from the string @@ -1197,7 +1730,9 @@ bool BF2Engine::startGame(bool noAutoJoin, bool startFromMenu) // 2nd bool fro setGameLogic(CID_ServerGameLogic); // releases the old gameLogic and // createInstance2(cid, IID_IGameLogic) - if (!gameLogic->init()) // IGameLogic vtable +0x10, 0x81384d0 + const bool logicInit = gameLogic->init(); + BF2_HOST_TRACE_SITE("server gameLogic->init", logicInit); + if (!logicInit) // IGameLogic vtable +0x10, 0x81384d0 return false; int port = serverSettings->m_serverPort; // ServerSettings +0x20 @@ -1205,6 +1740,7 @@ bool BF2Engine::startGame(bool noAutoJoin, bool startFromMenu) // 2nd bool fro port = settings->intGet("GSPort", 16567); // queried a second time; intGet // [UNRESOLVED] The third startServer argument's meaning; this caller passes zero. ok = gameServer->startServer(serverSettings->m_serverIP, port, 0); + BF2_HOST_TRACE_SITE("server startServer", ok); } else { @@ -1266,7 +1802,7 @@ bool BF2Engine::startGame(bool noAutoJoin, bool startFromMenu) // 2nd bool fro { std::string mod = host->getServerMod(); // the server's mod IBase* modInfo = classManager->getSingleton("ModInfo"); - if (!modInfo_vslot0x30(modInfo, mod)) // IModInfo +0x30 - [UNRESOLVED] role + if (!modInfo_vslot0x30(modInfo, mod)) // IModInfo +0x30, getModFromPath { if (compareIgnoreCase(mod, "mods/xpack") == 0) // both images host->setMessageId(26); @@ -1393,6 +1929,13 @@ bool BF2Engine::initEngine() { if (!isDedicated()) { +#if !DEDICATED + // [CHOSEN, not recovered] No retail call: between the renderer test (0x40939E) and the + // input init (0x4093C0), a Default profile created by init above takes the + // renderer-aware video defaults and the session switches to them. + static_cast(static_cast( + classManager->getSingleton("LocalProfileManager")))->applyFirstStartVideoDefaults(); +#endif if (!static_cast(io::inputManager)->init(1087)) // vslot +0x10, device mask 1087 return false; io::mainConsole->run("Settings/Controls.con", "", "", "", "", "", "", "", "", io::Console::ignoredString_); @@ -1438,7 +1981,7 @@ bool BF2Engine::initEngine() return false; SingletonServer::init(); // genuinely static - 0x813907E pushes nothing #if !DEDICATED - musicPlayer = new MusicPlayer(); // operator new(8), 0x7E1B40 - client only; never deleted + musicPlayer = new MusicPlayer(); // operator new(8), 0x7E1B40 - client only; shutdown deletes it #endif return true; } @@ -1490,7 +2033,7 @@ void BF2Engine::closeLog() bool BF2Engine::shutdownEngine() { if (dwordB0) // +0xB0, trivial destructor: a bare operator delete - delete dwordB0; // [UNRESOLVED] type - see startGame's note on offset 176 + ::operator delete(dwordB0); // [UNRESOLVED] type - see startGame's note on offset 176 dwordB0 = 0; delete performanceLogging; // +0x74. Inlined destructor: stores &PerformanceLogging::VMT, @@ -1508,12 +2051,19 @@ bool BF2Engine::shutdownEngine() delete demo; demo = 0; +#if !DEDICATED + // The dedicated image never creates either object (BF2Engine::init's client branch does), so + // both pointers stay null there and its two virtual deletes never run. The client-only classes + // are not declared in a dedicated build. if (window) // +0x10, virtual delete (vtable +4 in the ELF's type - see BF2Window.h) - delete window; // BF2Window: the game window, null in a dedicated image + delete window; // BF2Window: the game window +#endif window = 0; +#if !DEDICATED if (bf2Render) // +0x18, virtual delete (vtable +4), 0x81394b0. type attested delete bf2Render; // from Demo::beginMainLoop's mangled parameter list; +#endif bf2Render = 0; // [INFERRED] the field name if (bf2Console) // +0x14, ~BF2Console followed by operator delete @@ -1547,11 +2097,33 @@ static double s_prevWallClockTime = 0.0; // [INFERRED] na static float* const s_sleepOverheadTime = // [INFERRED] name Vars::getFloat("server-sleep-overhead-time", 0.005f); // default bits 0x3BA3D70A +#ifndef BF2_FRAME_MARK +#define BF2_FRAME_MARK(s) ((void)0) // [TEMP] BF2_FRAME_TRACE: client only +#endif bool BF2Engine::mainLoop() { // Runs one frame per call. A pending quit returns false before any frame work. if (quitNextFrameFlag) return false; +#if defined(__APPLE__) && !DEDICATED + frametrace::begin(); // [TEMP] BF2_FRAME_TRACE + bf2warmup::tick(); // [CHOSEN] +warmupLevel: progress / exit + // [CHOSEN, not recovered] +warmupLevel only: a listen server draws no world until the local + // player presses JOIN GAME on the map-loaded screen, and the first world frame builds effects + // too. Issue the button's own action: its ActionScript calls dice.bf2.Logic.readyToPlay + // (SwiffPlayer.dll 0x1004DE90, as_logic_readyToPlay), which pushes an empty type-15 MenuEvent + // through ISwiffHost +0x2C pushEvent (BF2.exe 0x49D210); renderMenu (0x40BD10) case 15 removes + // the loading screen and clears gameStarting. Gated on the map-loaded state: the same + // "not loading" the AS reads (getIsLoading: host +0xCC, +0x2A8). + if (bf2warmup::active()) + if (ui::ISwiffHost* host = static_cast(classManager->getSingleton("SwiffHost"))) + if (!host->getFlag7B8() && !host->getFlagEA8() && bf2warmup::wantsJoinGame()) + { + MenuEvent event; + event.type = 15; + host->pushEvent(event); + } +#endif // : the idle throttle. The binary does `if (!byte52) usleep(100000);` - a flat 100 ms // (imm 0x186A0 at 0x8137A80), NOT derived from a getter. byte52 (+0x52) is set from a handleEvent @@ -1695,7 +2267,11 @@ bool BF2Engine::mainLoop() { if (s_cursorShown) { +#if defined(__APPLE__) + macos::CocoaHost::instance().showCursor(false); // [CHOSEN, not recovered] ShowCursor(FALSE) +#else ShowCursor(FALSE); +#endif s_cursorShown = false; } byte70 = true; @@ -1723,8 +2299,14 @@ bool BF2Engine::mainLoop() { if (byte70) { +#if defined(__APPLE__) + // [CHOSEN, not recovered] the host's counter has ShowCursor's semantics. + if (macos::CocoaHost::instance().showCursor(true) == 1) + macos::CocoaHost::instance().showCursor(false); +#else if (ShowCursor(TRUE) == 1) ShowCursor(FALSE); +#endif if (musicPlayer) { musicTraceSite("mainLoop byte70"); // [TEMP] BF2_TRACE_MUSIC @@ -1736,8 +2318,11 @@ bool BF2Engine::mainLoop() } } - // [CHOSEN, not recovered] Client VoIP updates are omitted. - // [RETIRE-WHEN: client-voip-optional] Restore the voice update when game and voice client are available. +#if !DEDICATED + // BF2.exe 0x40CFF9..0x40D017: the voice client's frame (+0x9C) on a client with a game. + if (!isDedicated() && bf2VoipClient && game) + bf2VoipClient->updateClient(); +#endif if (game) updateMenuPause(*savedPauseState, menuLogic != 0); // on the heap int { @@ -1751,6 +2336,10 @@ bool BF2Engine::mainLoop() if ((!isDedicated() && ticks > 0 && !game) || g_bfSound->getForceUpdate()) g_bfSound->update(ticks); // IBfSound: the one-int update (PE slot +0x18) } +#if defined(__APPLE__) + if (game && !isDedicated()) + playTraceTick(); // [TEMP] BF2_PLAY_TRACE +#endif if (game && gameLogic && !isDedicated() && renderTicks > 0) // The HUD information-layer singleton is required on this client path. static_cast(g_hudInformationLayer)->update(static_cast(renderTicks) * renderDt); @@ -1759,6 +2348,7 @@ bool BF2Engine::mainLoop() // Step simulation only with ticks and both game owners present; use the // simulation-rate sample already taken for this frame. + BF2_FRAME_MARK(Pre); // [TEMP] BF2_FRAME_TRACE if (!isMoviePlaying() && ticks > 0 && game && gameLogic) // 0x813752E; BF2.exe adds the movie gate { #if !DEDICATED @@ -1775,6 +2365,7 @@ bool BF2Engine::mainLoop() // Python updates require render ticks and an initialized host, independent of // game presence and simulation rate. + BF2_FRAME_MARK(Update); // [TEMP] BF2_FRAME_TRACE if (renderTicks > 0) { if (python::pythonHost()->isInitialized()) @@ -1789,6 +2380,7 @@ bool BF2Engine::mainLoop() // Advance the separate frame-event manager by a duration, not a timestamp. // Its processEvents result is discarded. frameEventManager->processEvents(frameTime); + BF2_FRAME_MARK(Script); // [TEMP] BF2_FRAME_TRACE // Advance the world only outside movies, with a game and nonzero simulation rate. if (!isMoviePlaying() && game && !simRateZero) // / 0x813758A; BF2.exe adds the movie gate @@ -1807,7 +2399,7 @@ bool BF2Engine::mainLoop() // BF2.exe 0x40CA80: the viewer comes from BF2Render::getRenderView when the AI global // says so or the game logic is a client's. The view transform is fetched twice, as shipped. The // dedicated PE still makes the AI global's +0x18 call with bf2Render null (result - // unused) - [UNRESOLVED] identity of ds:0xA33C08 / ds:0x8B25B0; not called on a server here. + // unused). ds:0xA33C08 / ds:0x8B25B0 is ai::g_aiInstance; not called on a server here. const bool aiViewer = unresolvedGlobalA33C08 && unresolvedGlobalA33C08_vslot0x18(); if (bf2Render && (aiViewer || (gameLogic && !gameLogic->isServer()))) { @@ -1835,6 +2427,7 @@ bool BF2Engine::mainLoop() } } + BF2_FRAME_MARK(Objects); // [TEMP] BF2_FRAME_TRACE #if !DEDICATED // THE frame - BF2.exe 0x40CA80. Never in a dedicated image: isDedicated() gates it and every // object it touches is client-only. @@ -1878,6 +2471,7 @@ bool BF2Engine::mainLoop() bf2Render->update(frameTime); // vslot +0x14, 0x4530D0 #endif + BF2_FRAME_MARK(Render); // [TEMP] BF2_FRAME_TRACE bf2Console->updateConsole(); #if !DEDICATED if (hudManager) @@ -1942,8 +2536,19 @@ bool BF2Engine::mainLoop() // externally detectable. CheckServerAliveThread is the producer side. if (isDedicated()) // BF2.exe 0x40CA80: `if (sub_440510() && sub_440510())` - markAsStillRunning(); // the call site's test and the inlined body's own +#if defined(__APPLE__) && !DEDICATED + frametrace::end(ticks, game != 0 && menuLogic == 0); // [TEMP] BF2_FRAME_TRACE +#endif - // [CHOSEN, not recovered] The per-frame PunkBuster SDK pump is omitted. + // 0x40D5CB..0x40D5FE: the per-frame PunkBuster pump, client glue first. + if (game && game->isPunkBusterEnabled()) + { +#if !DEDICATED + PbClientProcessEvents(); +#endif + if (game->queryInterface(IID_IGameServer)) + PbServerProcessEvents(); + } // A queued quit makes this the final frame. return !quitNextFrameFlag; } @@ -2087,7 +2692,7 @@ bool BF2Engine::filterGameInput(io::GameInput& input) menuLogic->handleInput(input); // IMenuLogic +0x38 return false; } -#if defined(_WIN32) +#if defined(_WIN32) || defined(__APPLE__) // [CHOSEN, not recovered] macOS fills the ring too menuKeyCount = 0; // the WM_KEYDOWN ring (Game/Main/BF2.cpp) is dropped menuKeyRead = menuKeyWrite; // every frame the menu is down #endif @@ -2371,6 +2976,7 @@ bool BF2Engine::startMission(const std::string& map, const std::string& /*mode - #endif const bool started = startGame(false, false); + BF2_HOST_TRACE_SITE("startMission startGame", started); if (!started) { activateMenu(0); @@ -2539,9 +3145,8 @@ void BF2Engine::renderMenu(int renderTicks, float renderDt, double wallDelta, bo #if !DEDICATED if (!menuLogic) return; - // PE40BD44..40BD57 addresses global978FC4 directly, not an OldConsole field. - if (io::g_falconMouseMode != 2) - io::g_falconMouseMode = 1; + // PE40BD44..40BD57 sets the Falcon's mouse mode (ds:0x978FC4); it is archived with the device + // (Code/Archive/NovintFalcon). menuLogic->update(wallDelta); // +0x28 if (draw && menuLogic->beginFrame()) // +0x2C { @@ -2557,6 +3162,18 @@ void BF2Engine::renderMenu(int renderTicks, float renderDt, double wallDelta, bo ui::ISwiffHost* host = menuLogic->getSwiffHost(); // +0x20 if (host->pollEvent(event)) // +0x28 on that object { +#if defined(__APPLE__) + // [CHOSEN, not recovered] +warmupLevel only: without a logged-in profile the main menu that + // loads after JOIN GAME posts type 13 (save profile, log out, shutdownGame) at once, which + // ends the hosted game before the first world frames' effects are built. The warm-up keeps + // the game: the events that end it (8 disconnect, 13 logout, 14 kicked to the menu, 17) are + // dropped and logged. Retail cannot reach a hosted game without a profile through the menu. + if (bf2warmup::active() && (event.type == 8 || event.type == 13 || event.type == 14 || event.type == 17)) + { + bf2warmup::menuEventDropped(event.type); + event.type = 0; // the switch's default: nothing + } +#endif ui::ISwiffHost* swiffHost = 0; switch (event.type) { @@ -2702,9 +3319,16 @@ void BF2Engine::playSound(const std::string&) {} void BF2Engine::browseModHomepage(const std::string& url) { #if !DEDICATED +#if defined(__APPLE__) + // [CHOSEN, not recovered] ShowWindow(SW_MINIMIZE) and ShellExecuteA("open", url). + macos::CocoaHost::instance().minimize(); + if (!macos::CocoaHost::instance().openURL(url)) + return; +#else ShowWindow(window->getHwnd(), SW_MINIMIZE); // Window vslot +0x2C if (reinterpret_cast(ShellExecuteA(0, "open", url.c_str(), 0, 0, SW_SHOWNORMAL)) <= 32) return; +#endif quitNextFrameFlag = true; #else (void)url; @@ -2716,10 +3340,16 @@ void BF2Engine::browseModHomepage(const std::string& url) void BF2Engine::restartBF2() { #if !DEDICATED +#if defined(__APPLE__) + // [CHOSEN, not recovered] GetModuleFileNameA + ShellExecuteA(exe, commandLine). + if (!macos::relaunchExecutable(commandLine)) + return; +#else char fileName[MAX_PATH]; GetModuleFileNameA(0, fileName, MAX_PATH); if (reinterpret_cast(ShellExecuteA(0, "open", fileName, commandLine.c_str(), 0, SW_SHOWNORMAL)) <= 32) return; +#endif quitNextFrameFlag = true; #endif } @@ -2732,6 +3362,11 @@ void BF2Engine::buildRestartCommandLine(const std::string& modPath, const std::s commandLine = std::string("+modPath ") + modPath; commandLine += " +multi 1"; commandLine += " +restart 1"; + // [CHOSEN, not recovered] Not in retail: the restarted client logs in with the profile below, + // so it must keep the online domain this one was started with. + commandLine += onlineProvider::commandLineArguments(); + // [CHOSEN, not recovered] Keep the request across mod restarts; unsupported mods disable it. + if (hud::widescreen::requested()) commandLine += " +widescreenHud 1"; if (!settings->boolGet("GSFullScreen", false)) commandLine += " +fullscreen 0"; if (joinAddress) @@ -2741,14 +3376,16 @@ void BF2Engine::buildRestartCommandLine(const std::string& modPath, const std::s } if (IBase* lpm = classManager->getSingleton("LocalProfileManager")) { - if (static_cast(lpm)->getCurrentProfile()) + ILocalProfileManager* profiles = static_cast(lpm); + if (LocalProfile* profile = profiles->getCurrentProfile()) // +0x44 { - std::string scratch; - localProfileManager_vslot0x70(lpm, localProfileManager_vslot0xD0(lpm, scratch, 1)); - std::string password; - password = static_cast(lpm)->getPassword(); - commandLine += std::string(" +playerName ") + scratch; // [UNRESOLVED] which string each += takes: - commandLine += std::string(" +playerPassword ") + password; // the decompiler drops the operands + // 0x403F34..0x403FE8: the login password goes back into the record encoded (+0x70 with + // `true`, pushed before +0xD0's return slot), then the record's encoded password (+0x88) + // and its GameSpy nick (record +0x54) go on the command line. + profiles->setPassword(profiles->getLoginPassword(), true); // +0xD0, +0x70 + std::string password = profiles->getPassword(); // +0x88 + commandLine += std::string(" +playerName ") + profile->gamespyNick; + commandLine += std::string(" +playerPassword ") + password; } } } @@ -2790,7 +3427,24 @@ IMenuLogic* menuLogic = 0; // dword_987358 - the active menu; s hud::BF2HudManager* hudManager = 0; // dword_A10890 - zeroed again by the client ctor (0x408190) BF2VoipClient* bf2VoipClient = 0; // dword_9A4DA0 IBase* g_renderer = 0; // BF2.exe g_Renderer - [UNRESOLVED] symbol; set by the renderer bring-up, not by this TU -IBase* unresolvedGlobalA33C08 = 0; // ds:0xA33C08 / bf2_w32ded ds:0x8B25B0 +// ds:0xA33C08 is ai::g_aiInstance: its only writer, 0x801030, stores getSimpleSingleton("AI") as +// ai::AIInstanceServer::updateInstance does. The alias keeps one object for both names. +IBase*& unresolvedGlobalA33C08 = ai::g_aiInstance; + +// startGame join result 8 (0x40543F..0x40544F): ModInfo +0x30 with the server's mod path and a full +// 32-bit test of the result. The client ModInfo table 0x8A1230 holds 0x47E590 there, which matches +// each 0x154-byte Mod on its first string (path): IModInfo::getModFromPath. +bool modInfo_vslot0x30(IBase* modInfo, const std::string& modName) +{ + return static_cast(modInfo)->getModFromPath(modName) != 0; +} + +// mainLoop's ragdoll viewer (0x40D1ED..0x40D22A) calls the AI instance's +0x18 after its null test: +// IAIInstance::isInitialized. +bool unresolvedGlobalA33C08_vslot0x18() +{ + return ai::aiInstance()->isInitialized(); +} // The client singleton slots BF2.exe 0x4301A9 registers (Core/ModuleRegistry.cpp). [CHOSEN] placement: // their .data addresses 0x987340..0x987398 surround menuLogic (0x987358) and s_prevWallClockTime // (0x987330), i.e. this TU's statics. diff --git a/Code/BF2/Game/Main/BF2Engine.h b/Code/BF2/Game/Main/BF2Engine.h index 3ac24719b..7ee85fc96 100644 --- a/Code/BF2/Game/Main/BF2Engine.h +++ b/Code/BF2/Game/Main/BF2Engine.h @@ -188,7 +188,7 @@ class BF2Engine : public io::IInputFilter, /* 164 */ int dwordA4; // [UNRESOLVED] Constructor sets -1; shutdown does not reset it. /* 168 */ Demo* demo; // Owned demo controller. - /* 172 */ MusicPlayer* musicPlayer; // Client-only allocation; original shutdown does not delete it. + /* 172 */ MusicPlayer* musicPlayer; // Client-only allocation; the client shutdown arm deletes it. #if !DEDICATED struct MovieEntry // Client-only movie queue payload. { @@ -217,6 +217,9 @@ struct SingleInstanceGuard { #if defined(_WIN32) && !DEDICATED /* +0x00 */ void* handle; // Win32 handle without including windows.h. +#elif defined(__APPLE__) && !DEDICATED + // [CHOSEN, not recovered] Owned flock descriptor; closed on destruction or exec. + int lockFd; #endif /* +0x04 (client) / +0x00 */ bool isFirstInstance; SingleInstanceGuard(); diff --git a/Code/BF2/Game/Main/BF2Render.cpp b/Code/BF2/Game/Main/BF2Render.cpp index c70a10fb2..b5f56bb10 100644 --- a/Code/BF2/Game/Main/BF2Render.cpp +++ b/Code/BF2/Game/Main/BF2Render.cpp @@ -39,7 +39,11 @@ #include #include #include +#if defined(_WIN32) #include +#else +#include // [CHOSEN, not recovered] getpid for the title +#endif namespace dice { namespace hfe { @@ -47,34 +51,47 @@ namespace hfe { extern ClassManager* classManager; extern SettingsRepostitory* settings; extern BF2Engine* bf2Engine; // Shared engine owner. - // [UNRESOLVED] Profiler/thread registry published by the client runtime. - // [CHOSEN] Local placement; initialization queries it conditionally, while the - // original VTune render bracket requires a published instance. -IBase* profilerSingleton = 0; +extern IProfilerClient* profilerClient; // ds:0x9A5C6C, published by Core Module::init (PE 0x68CC5F) // Frame telemetry is owned by LatencyCompensation and written only by rendering. // Its product supplies the clamped render-ahead latency. +#if defined(_WIN32) +namespace { +// [CHOSEN, not recovered] Windows: RendDX9.dll and TextureAtlasBuilder.dll delay-load d3dx9_25.dll +// (Code/Build/renddx9.cmd, textureatlasbuilder.cmd), so a missing or wrong-bitness D3DX runtime no +// longer stops the loader with a system error before the game can say anything. This loads it the +// way the delay-load helper will (the same name and search order) and keeps it loaded, so the +// plugins bind this module. Without it the renderer cannot start: one message box, then the process +// ends with code 1. +void requireD3dxRuntime() +{ + if (::LoadLibraryA("d3dx9_25.dll")) + return; + ::MessageBoxA(0, +#if defined(_WIN64) + "The DirectX 9 runtime (d3dx9_25.dll, 64-bit) is missing; run the OpenBF2 installer " +#else + "The DirectX 9 runtime (d3dx9_25.dll, 32-bit) is missing; run the OpenBF2 installer " +#endif + "or the Microsoft DirectX End-User Runtime.", + "OpenBF2", MB_OK | MB_ICONERROR | MB_SETFOREGROUND); + ::ExitProcess(1); +} +} // namespace +#endif + BF2Render* g_bf2Render = 0; // ds:0x9A5580 IBase* g_geometryTemplateManager = 0; // ds:0x9A5578 namespace { -// Pauses or resumes VTune around repeated demo-frame rendering. -// [CHOSEN, not recovered] The null check stops at a named frontier until the -// profiler publisher is recovered. [RETIRE-WHEN: client-frame-arm] -void profilerSetSuspended(IBase* profiler, bool suspended) +// Pauses or resumes VTune around repeated demo-frame rendering: ds:0x9A5C6C (profilerClient, set +// from the "Profiler" singleton by Core Module::init, PE 0x68CC5F) +0x2C, dereferenced unguarded as +// in BF2.exe 0x45342B / 0x4534DC. +void profilerSetSuspended(bool suspended) { - if (!profiler) - { - std::fprintf(stderr, "[FRONTIER] dice::hfe::BF2Render::render: the ds:0x9A5C6C profiler " - "singleton is unpublished (its owner at PE 0x68CC60 is unrecovered), " - "so its +0x2C(%d) VTune bracket cannot be dispatched\n", - suspended ? 1 : 0); - std::fflush(stderr); - std::abort(); - } - static_cast(profiler)->pauseVTune(suspended); + profilerClient->pauseVTune(suspended); } // Releases collision debug geometry before the renderer module is unloaded. @@ -88,79 +105,52 @@ void notifyCollisionManagerRendererShutdown(IBase* manager) const char kSourcePath[] = "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Game\\Main\\BF2Render.cpp"; -// View of RendDX9's plugin-owned display modes. Both plugin flavors retain the -// VC7.1 container layout and 40-byte records; this is not a host-owned exchange -// container. The retail display-mode carrier embeds one record at offset 4. -struct RendererDisplayMode -{ - /* +0x00 */ unsigned short width; - /* +0x02 */ unsigned short height; - /* +0x04 */ unsigned short refreshHz; - /* +0x06 */ unsigned char bpp; - /* +0x07 */ unsigned char pad07; // never copied by 0x4547F0 - /* +0x08 */ vc71::vector_layout depthFormats; // D3DFORMAT dwords - /* +0x18 */ vc71::vector_layout multiSamples; // renddx9abi::DisplayModeMultiSample -}; -static_assert(sizeof(RendererDisplayMode) == 40, "Renderer +0x3C hands back 40-byte records"); - -// size() with VC7.1's own arithmetic: 0 while _First is null, else (_Last - _First) / 40 as a signed -// pointer difference - the imul / sar / shr-add sequence at 0x453849 and 0x454970 is a signed divide. -int rendererModeCount(const vc71::vector_layout& modes) +// RendDX9's plugin-owned display modes: the std::vector of display-mode records Renderer +0x3C +// returns (DisplayModeAbi.h; retail: a VC7.1 vector of 40-byte records). Both images share the STL +// (issue #7). The retail display-mode carrier embeds one record at offset 4. +typedef renddx9abi::DisplayModeRecord RendererDisplayMode; +typedef std::vector RendererDisplayModes; + +// size(). Retail open-codes it with VC7.1's arithmetic (0 while _First is null, else a signed +// pointer difference over 40 - the imul / sar / shr-add sequence at 0x453849 and 0x454970). +int rendererModeCount(const RendererDisplayModes& modes) { - if (!modes.first) - return 0; - return static_cast(modes.last - modes.first) / static_cast(sizeof(RendererDisplayMode)); + return static_cast(modes.size()); } -const RendererDisplayMode& rendererModeAt(const vc71::vector_layout& modes, unsigned int index) +const RendererDisplayMode& rendererModeAt(const RendererDisplayModes& modes, unsigned int index) { - return reinterpret_cast(modes.first)[index]; + return modes[index]; } // Requests modes with all three filter flags enabled. Renderer caching means // an earlier VideoOptions query can already have populated the list with its filter. -const vc71::vector_layout& rendererDisplayModes(dx9rend::IRenderer* renderer) +const RendererDisplayModes& rendererDisplayModes(dx9rend::IRenderer* renderer) { dx9rend::DisplayModeFilter filter; filter.aspect4by3 = true; // [ebp-4] filter.crossCheckDisplaySettings = true; // [ebp-3] filter.minimumResolution = true; // [ebp-2] - return *static_cast(renderer->slot_0x3C(&filter)); + return *static_cast(renderer->slot_0x3C(&filter)); } // Requires a nonempty depth-format list; init and setDisplayMode retain one entry. -// Returns a borrowed reference. Native and compatibility empty-list behavior differs. +// Returns a borrowed reference. const unsigned int& carrierDepthFront(const renddx9abi::HostDisplayMode& carrier) { return *renddx9abi::hostDepthFirst(carrier); } -// Copies display-mode scalars and assigns both owned lists. -// [PLATFORM] The native carrier flattens the fields; compatibility uses the ABI -// carrier's owned-range assignment. +// Copies display-mode scalars (0x4547F0 skips the pad byte) and assigns both lists. void assignDisplayMode(renddx9abi::HostDisplayMode& carrier, const RendererDisplayMode& mode) { carrier.width = mode.width; carrier.height = mode.height; - carrier.refreshHz = mode.refreshHz; + carrier.refreshHz = mode.refresh; carrier.bpp = mode.bpp; - const unsigned int* depthFirst = - reinterpret_cast(mode.depthFormats.first); - const unsigned int* depthLast = - reinterpret_cast(mode.depthFormats.last); - const renddx9abi::DisplayModeMultiSample* sampleFirst = - reinterpret_cast(mode.multiSamples.first); - const renddx9abi::DisplayModeMultiSample* sampleLast = - reinterpret_cast(mode.multiSamples.last); -#if BF2_PLUGIN_ABI_NATIVE - carrier.depthFormats.assign(depthFirst, depthLast); - carrier.multiSamples.assign(sampleFirst, sampleLast); -#else - renddx9abi::assignOwnedDisplayVector(carrier.depthFormats, depthFirst, depthLast); - renddx9abi::assignOwnedDisplayVector( - carrier.multiSamples, sampleFirst, sampleLast); -#endif + carrier.depthFormats.assign(mode.depthFormats.begin(), mode.depthFormats.end()); + carrier.multiSamples.assign(mode.multiSample.begin(), mode.multiSample.end()); } } // anonymous namespace @@ -210,6 +200,9 @@ IBase* BF2Render::getRenderView() bool BF2Render::init() { +#if defined(_WIN32) + requireD3dxRuntime(); // [CHOSEN, not recovered] before the window exists; see above +#endif m_window = m_engine->getWindow(); assert(m_window && "create a window"); // BF2Render.cpp:166 @@ -219,7 +212,11 @@ bool BF2Render::init() // A window title reaches nothing but the taskbar. std::ostringstream title; title << "BF2 (v" << BuildNrUtil::getBuildNrString() << "-LC" +#if defined(_WIN32) << ", pid: " << ::GetCurrentProcessId() << ")"; +#else + << ", pid: " << static_cast(::getpid()) << ")"; +#endif const bool fullscreen = settings->boolGet("GSFullScreen", false); const int width = settings->intGet("GSWindowSizeX", 800); @@ -241,15 +238,9 @@ bool BF2Render::init() m_displayModeCarrier->bpp = 32; m_displayModeCarrier->vsync = 0; -#if BF2_PLUGIN_ABI_NATIVE m_displayModeCarrier->depthFormats.push_back(75u); // D3DFMT_D24S8 m_displayModeCarrier->windows.push_back( reinterpret_cast(m_window->getHwnd())); -#else - vc71::vectorRef(&m_displayModeCarrier->depthFormats).push_back(75u); - void* hwnd = reinterpret_cast(m_window->getHwnd()); - vc71::vectorRef(&m_displayModeCarrier->windows).push_back(hwnd); -#endif if (fullscreen) m_window->toggleFullscreenStyle(); @@ -296,15 +287,6 @@ void BF2Render::shutdown() { if (m_displayModeCarrier) { -#if !BF2_PLUGIN_ABI_NATIVE - // The rebuilt client uses native mode. Keep the retail branch complete for isolated - // ABI compilation: its POD carrier has no automatic vector destructors. - renddx9abi::clearOwnedDisplayVector(m_displayModeCarrier->windows); - renddx9abi::clearOwnedDisplayVector( - m_displayModeCarrier->multiSamples); - renddx9abi::clearOwnedDisplayVector( - m_displayModeCarrier->depthFormats); -#endif delete m_displayModeCarrier; } @@ -315,6 +297,10 @@ void BF2Render::shutdown() // Configures the frame's camera and view distance, then drives renderer output. // A renderer module must be loaded. Active paths require player manager, render view, // video options and profiler services; those dependencies are not null-checked. +// [TEMP] [CHOSEN, not recovered] the last playback camera matrix, for BF2_PLAY_TRACE's demo arm. +Mat4 g_demoTraceCameraMatrix; +bool g_demoTraceCameraValid = false; + bool BF2Render::render(double frameTime, DemoRecorder* recorder) { // : the module handle decides, not the renderer pointer. @@ -327,11 +313,12 @@ bool BF2Render::render(double frameTime, DemoRecorder* recorder) if (recorder && recorder->isOpenForPlayback()) { - // [UNRESOLVED] This aggregate starts uninitialized, unlike the original identity - // Mat4 constructor. getCameraTransformation must fill it; partial writes expose - // that existing layout/initialization difference. - Mat4 transform; - recorder->getCameraTransformation(transform, 0); + // BF2.exe 0x4532BB: the identity Mat4 constructor (0x440B20), then + // DemoRecorder::getPlaybackMatrixAndFOV (0x54BC20) with no FOV out-parameter. + Mat4 transform = Mat4::getIdentity(); + recorder->getPlaybackMatrixAndFOV(&transform, 0); + g_demoTraceCameraMatrix = transform; // [TEMP] BF2_PLAY_TRACE's demo arm (BF2Engine.cpp) + g_demoTraceCameraValid = true; const float fov = recorder->demoConfig.getFOV(); const float aspect = recorder->demoConfig.getAspect(); m_renderer->getRenderView()->setFov(fov); // +0x1C @@ -372,7 +359,7 @@ bool BF2Render::render(double frameTime, DemoRecorder* recorder) int passes = 1; if (recorder && recorder->byte84) { - profilerSetSuspended(profilerSingleton, false); + profilerSetSuspended(false); passes = config ? config->vtuneRepeatCount : 1; } @@ -398,7 +385,7 @@ bool BF2Render::render(double frameTime, DemoRecorder* recorder) } if (recorder && recorder->byte84) - profilerSetSuspended(profilerSingleton, true); + profilerSetSuspended(true); return result; } @@ -430,13 +417,12 @@ unsigned int BF2Render::toggleFullscreen() // listing because the original print path is absent. [INFERRED] Method spelling. void BF2Render::listScreenModes() { - const vc71::vector_layout& modes = rendererDisplayModes(m_renderer); // +0x3C + const RendererDisplayModes& modes = rendererDisplayModes(m_renderer); // +0x3C for (unsigned int i = 0; i < static_cast(rendererModeCount(modes)); ++i) { const RendererDisplayMode& mode = rendererModeAt(modes, i); - const unsigned int* first = reinterpret_cast(mode.depthFormats.first); - const unsigned int* last = reinterpret_cast(mode.depthFormats.last); - (void)std::find(first, last, carrierDepthFront(*m_displayModeCarrier)); // discarded + (void)std::find(mode.depthFormats.begin(), mode.depthFormats.end(), + carrierDepthFront(*m_displayModeCarrier)); // discarded } } @@ -447,7 +433,7 @@ void BF2Render::listScreenModes() // [PLATFORM] Native vector operations retain their own allocation semantics. void BF2Render::setDisplayMode(int index) { - const vc71::vector_layout& modes = rendererDisplayModes(m_renderer); // +0x3C + const RendererDisplayModes& modes = rendererDisplayModes(m_renderer); // +0x3C if (index < 0 || index >= rendererModeCount(modes)) { Debug(DebugTypeError, kSourcePath, 460, "") << "ScreenMode out of range"; @@ -456,16 +442,9 @@ void BF2Render::setDisplayMode(int index) const unsigned int depthFormat = carrierDepthFront(*m_displayModeCarrier); assignDisplayMode(*m_displayModeCarrier, rendererModeAt(modes, index)); -#if BF2_PLUGIN_ABI_NATIVE m_displayModeCarrier->depthFormats.clear(); m_displayModeCarrier->depthFormats.push_back(depthFormat); m_displayModeCarrier->multiSamples.clear(); -#else - renddx9abi::clearOwnedDisplayVector(m_displayModeCarrier->depthFormats); - vc71::vectorRef(&m_displayModeCarrier->depthFormats).push_back(depthFormat); - renddx9abi::clearOwnedDisplayVector( - m_displayModeCarrier->multiSamples); -#endif m_window->resizeClient(m_displayModeCarrier->width, // +0x44 m_displayModeCarrier->height); diff --git a/Code/BF2/Game/Main/BF2Window.cpp b/Code/BF2/Game/Main/BF2Window.cpp index 76b981c0e..db48b060a 100644 --- a/Code/BF2/Game/Main/BF2Window.cpp +++ b/Code/BF2/Game/Main/BF2Window.cpp @@ -2,12 +2,14 @@ #include "BF2Window.h" -#if !DEDICATED +// [CHOSEN, not recovered] The macOS client uses BF2Window_macos.cpp instead. +#if !DEDICATED && defined(_WIN32) #include "BF2Engine.h" // menuLogic - the active menu (Window::wndProc) #include "../../Core/EventManager.h" // eventManager->postEvent on WM_ACTIVATEAPP #include "../IEventListener.h" // EventCategory #include "../Utility/Vars.h" // opt-window-x / opt-window-y +#include "../../Platform/Windows/WinInputScript.h" // [TEMP] BF2_INPUT_SCRIPT focus #include namespace dice { @@ -117,7 +119,9 @@ bool Window::create(const std::string& title, int width, int height, bool fullsc } bool Window::isCreated() const { return m_hwnd != 0; } -bool Window::getHasFocus() const { return m_hasFocus; } +// [TEMP] [CHOSEN, not recovered] A BF2_INPUT_SCRIPT run reports focus (WinInputScript.h). +// [RETIRE-WHEN: client-test-automation-replaced] +bool Window::getHasFocus() const { return m_hasFocus || inputscript::winInputScriptActive(); } const std::string& Window::getTitle() const { return m_title; } int Window::getWidth() const { return m_width; } int Window::getHeight() const { return m_height; } @@ -317,4 +321,4 @@ void BF2Window::toggleFullscreenStyle() } // namespace hfe } // namespace dice -#endif // !dedicated +#endif // !dedicated && _WIN32 diff --git a/Code/BF2/Game/Main/BF2Window.h b/Code/BF2/Game/Main/BF2Window.h index d9412204f..40310299c 100644 --- a/Code/BF2/Game/Main/BF2Window.h +++ b/Code/BF2/Game/Main/BF2Window.h @@ -6,7 +6,13 @@ #ifndef GAME_MAIN_BF2WINDOW_H // [INFERRED] guard style #define GAME_MAIN_BF2WINDOW_H +#if defined(_WIN32) #include +#elif defined(__APPLE__) +// [CHOSEN, not recovered] macOS port: HWND/UINT/WPARAM/LPARAM/LRESULT in dice::hfe, and the +// Win32 message ids BF2Window_macos.mm synthesizes from Cocoa events. +#include "../../Platform/macOS/HostWindowTypes.h" +#endif #include #include @@ -45,7 +51,12 @@ class Window // [INFERRED] name - base, TU [UNRE // the wndproc create() registers. Static: it reaches the window through // `mainWindow`, not through GWL_USERDATA (the `this` passed as lpParam to CreateWindowExA is // never read back). +#if defined(_WIN32) static LRESULT CALLBACK wndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam); +#else + // [CHOSEN, not recovered] macOS: called by BF2Window_macos.mm with synthesized messages. + static LRESULT wndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam); +#endif friend class SwiffHost; // clears m_hideCursor directly protected: diff --git a/Code/BF2/Game/Main/BF2Window_macos.cpp b/Code/BF2/Game/Main/BF2Window_macos.cpp new file mode 100644 index 000000000..248ad2853 --- /dev/null +++ b/Code/BF2/Game/Main/BF2Window_macos.cpp @@ -0,0 +1,380 @@ +// [CHOSEN, not recovered] macOS port: Window and BF2Window on top of the Cocoa host +// (Platform/macOS/CocoaHost.h). There was no retail macOS image. The class declarations, virtual +// order and member state are BF2Window.h's; each method does what its Win32 body in +// BF2Window.cpp does, with the Win32 call replaced by the host's counterpart. Cocoa events are +// turned into the Win32 messages the engine's handlers inspect and run through Window::wndProc, +// which keeps the Win32 wndProc's state rules and dispatches every message to the handler list. +// Choices that differ from Win32 are listed in docs/macos-s2-4.md. + +#if !DEDICATED && defined(__APPLE__) + +#include "BF2Window.h" + +#include "BF2Engine.h" // menuLogic - the active menu (wndProc) +#include "../../Core/EventManager.h" // eventManager->postEvent on WM_ACTIVATEAPP +#include "../IEventListener.h" // EventCategory +#include "../Utility/Vars.h" // opt-window-x / opt-window-y +#include "../../Platform/macOS/CocoaHost.h" +#include "../../Platform/macOS/MacKeyMap.h" + +namespace dice { +namespace hfe { + +using namespace hostmsg; + +Window* mainWindow = 0; + +namespace { + +macos::CocoaHost& host() { return macos::CocoaHost::instance(); } + +// Windows-1252 byte for a UTF-16 unit, or -1 when the code page has none (WM_CHAR delivers +// ANSI characters to this narrow-character window class). +int cp1252FromUtf16(unsigned short c) +{ + if (c < 0x80 || (c >= 0xA0 && c <= 0xFF)) + return c; + static const unsigned short high[32] = { + 0x20AC, 0, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, + 0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0, 0x017D, 0, + 0, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, + 0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0, 0x017E, 0x0178 }; + for (int i = 0; i < 32; ++i) + if (high[i] == c) + return 0x80 + i; + return -1; +} + +// Translates host events into Win32 messages for mainWindow, the way the Win32 wndProc finds its +// window through mainWindow rather than through the handle. +class WindowMessageSource : public macos::IHostEventListener +{ +public: + void send(UINT message, WPARAM wParam, LPARAM lParam) + { + if (mainWindow) + Window::wndProc(mainWindow->getHwnd(), message, wParam, lParam); + } + + void onAppActivationChanged(bool appActive) override + { + send(WM_ACTIVATEAPP, appActive ? 1 : 0, 0); + } + + void onFocusChanged(bool windowKey, bool appActive) override + { + const bool focused = windowKey && appActive; + if (focused == m_focused) + return; + m_focused = focused; + send(WM_ACTIVATE, focused ? WA_ACTIVE : WA_INACTIVE, 0); + send(focused ? WM_SETFOCUS : WM_KILLFOCUS, 0, 0); + } + + void onResize(int width, int height, bool minimized) override + { + send(WM_SIZE, minimized ? SIZE_MINIMIZED : SIZE_RESTORED, makeLParam(width, height)); + } + + // The close button and Cmd-Q: WM_CLOSE, whose default handling destroys the window + // (WM_DESTROY) and posts the quit message. + void onCloseRequested() override + { + send(WM_CLOSE, 0, 0); + send(WM_DESTROY, 0, 0); + } + + // WM_KEYDOWN/WM_KEYUP with the US-layout virtual key and the scan code in lParam bits 16-24. + // Option is Alt, so Option combinations and F10 arrive as WM_SYSKEY* as they do on Windows. + void onKey(const macos::HostKeyEvent& event) override + { + const unsigned char dik = macos::dikFromMacKeyCode(event.keyCode, event.isoLayout); + const unsigned int vk = macos::win32VirtualKeyFromDik(dik); + if (!vk) + return; + const bool alt = (event.modifiers & macos::HostModOption) != 0; + const bool sys = alt || vk == VK_F10; + std::uint32_t lParam = 1u | (static_cast(dik & 0x7F) << 16); + if (dik & 0x80) lParam |= 1u << 24; // extended key + if (alt) lParam |= 1u << 29; // context code + if (event.repeat || !event.down) lParam |= 1u << 30; + if (!event.down) lParam |= 1u << 31; + const UINT message = event.down ? (sys ? WM_SYSKEYDOWN : WM_KEYDOWN) + : (sys ? WM_SYSKEYUP : WM_KEYUP); + send(message, vk, static_cast(lParam)); + } + + // WM_CHAR. Backspace reports DEL (0x7F) on macOS and keypad Enter ETX (0x03); Windows sends + // BS and CR. [CHOSEN] Command+letter is delivered as the control character, so the Mac + // Command-C/V/X shortcuts reach the engine's Ctrl-C/V/X handling (the handler's Ctrl test + // treats Command as Ctrl, see BF2.cpp). + void onText(const macos::HostTextEvent& event) override + { + for (unsigned short c : event.characters) + { + if (event.keyCode == 0x33 && c == 0x7F) c = 0x08; + else if (c == 0x03) c = 0x0D; + else if (c == 0x7F) continue; + if ((event.modifiers & macos::HostModCommand) && ((c | 0x20) >= 'a' && (c | 0x20) <= 'z')) + c = static_cast(c & 0x1F); + const int ansi = cp1252FromUtf16(c); + if (ansi < 0) + continue; + send(WM_CHAR, static_cast(ansi), 1); + } + } + + // Windows sends WM_SETCURSOR, then WM_MOUSEMOVE, while the pointer is over the client area. + // While the mouse is captured (the exclusively acquired DirectInput mouse in-game) the system + // cursor does not move and Windows sends no mouse messages at all; the menu handlers + // (bf2MessageHandler -> MainMenuLogic::onMouse*, which queue into the SwiffPlayer) must not see + // in-game motion or clicks. + void onMouseMove(const macos::HostMouseMoveEvent& event) override + { + if (!event.insideView || event.captured) + return; + send(WM_SETCURSOR, 0, 1); // HTCLIENT + send(WM_MOUSEMOVE, 0, makeLParam(static_cast(event.x), static_cast(event.y))); + } + + // CS_DBLCLKS: the second press of a double click arrives as WM_LBUTTONDBLCLK. + void onMouseButton(const macos::HostMouseButtonEvent& event) override + { + if (event.captured) + return; + const LPARAM where = makeLParam(static_cast(event.x), static_cast(event.y)); + switch (event.button) + { + case 0: send(event.down ? (event.clickCount == 2 ? WM_LBUTTONDBLCLK : WM_LBUTTONDOWN) : WM_LBUTTONUP, 0, where); break; + case 1: send(event.down ? WM_RBUTTONDOWN : WM_RBUTTONUP, 0, where); break; + case 2: send(event.down ? WM_MBUTTONDOWN : WM_MBUTTONUP, 0, where); break; + default: break; + } + } + + void onMouseWheel(const macos::HostMouseWheelEvent& event) override + { + if (event.captured) + return; + send(WM_MOUSEWHEEL, static_cast(static_cast(event.delta & 0xFFFF) << 16), 0); + } + + void resetFocus() { m_focused = false; } + +private: + bool m_focused = false; +}; + +WindowMessageSource s_messageSource; + +} // namespace + +Window::Window() + : m_hwnd(0) + , m_width(0) + , m_height(0) + , m_fullscreen(false) + , m_hasFocus(false) + , m_visible(true) + , m_hideCursor(false) +{ + mainWindow = this; +} + +// Win32: hides and destroys the window (PostQuitMessage, DestroyWindow), then clears the global. +Window::~Window() +{ + if (m_hwnd) + { + host().show(false); + if (m_hwnd) + { + host().postQuitMessage(); + wndProc(m_hwnd, WM_DESTROY, 0, 0); + host().removeListener(&s_messageSource); + host().destroyWindow(); + m_hwnd = 0; + } + } + mainWindow = 0; +} + +// Win32 registers a class named after the title and creates a WS_POPUP (fullscreen) or +// WS_OVERLAPPEDWINDOW window at (x, y), -1 meaning 50. On macOS the host creates the NSWindow; +// m_fullscreen stays false here, as in Win32, until toggleFullscreenStyle flips it. +bool Window::create(const std::string& title, int width, int height, bool fullscreen, + bool hideCursor, int /*iconId*/, int x, int y) +{ + if (m_hwnd) + destroy(); + + m_hideCursor = hideCursor; + m_title = title; + + macos::HostWindowDesc desc; + desc.title = m_title; + desc.width = width; + desc.height = height; + desc.x = (x != -1) ? x : 50; + desc.y = (y != -1) ? y : 50; + desc.fullscreen = fullscreen; + desc.hideCursor = false; // the WM_SETCURSOR arm decides, as on Win32 + + host().addListener(&s_messageSource); + s_messageSource.resetFocus(); + const bool created = host().createWindow(desc); + m_hwnd = created ? reinterpret_cast(host().nativeView()) : 0; + if (!m_hwnd) + { + host().removeListener(&s_messageSource); + return false; + } + + // CreateWindowEx/ShowWindow deliver WM_SIZE with the client size. + s_messageSource.onResize(host().clientWidth(), host().clientHeight(), false); + s_messageSource.onFocusChanged(host().hasFocus(), host().isAppActive()); + + if (m_hideCursor) + { + host().setCursorHiddenInView(true); // SetCursor(0) + host().showCursor(false); // ShowCursor(FALSE) + } + host().show(true); // ShowWindow, SetForegroundWindow, UpdateWindow + return true; +} + +bool Window::isCreated() const { return m_hwnd != 0; } +bool Window::getHasFocus() const { return m_hasFocus; } +const std::string& Window::getTitle() const { return m_title; } +int Window::getWidth() const { return m_width; } +int Window::getHeight() const { return m_height; } +bool Window::unresolved18() const { return true; } +bool Window::getVisible() const { return m_visible; } +bool Window::getFullscreen() const { return m_fullscreen; } +HWND Window::getHwnd() const { return m_hwnd; } + +// Win32: PostQuitMessage; DestroyWindow (which sends WM_DESTROY); clear the handle. +void Window::destroy() +{ + if (m_hwnd) + { + host().postQuitMessage(); + wndProc(m_hwnd, WM_DESTROY, 0, 0); + host().removeListener(&s_messageSource); + host().destroyWindow(); + m_hwnd = 0; + } +} + +// The flag is written whether or not a window exists; showing also focuses (SetFocus). +void Window::show(bool visible) +{ + m_visible = visible; + if (m_hwnd) + host().show(visible); +} + +void Window::addMessageHandler(MessageHandler handler) { m_handlers.push_back(handler); } +void Window::removeMessageHandler(MessageHandler handler) { m_handlers.remove(handler); } + +// The Win32 wndProc's state rules for the messages macOS produces, then the handler dispatch. +// The Win32-only arms (WM_NCHITTEST, WM_SYSCOMMAND, WM_COMMAND, DefWindowProc) have no macOS +// counterpart: the host window has no resize border, no system menu and no default processing. +LRESULT Window::wndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) +{ + if (!hwnd) + return 0; + + Window* w = mainWindow; + if (!w) + return 0; + + switch (message) + { + case WM_SETCURSOR: + // Win32 calls SetCursor(0) only in-game; with a menu up the class/menu cursor shows. + host().setCursorHiddenInView(!menuLogic && w->m_hideCursor); + break; + + case WM_ACTIVATEAPP: + w->m_hasFocus = (wParam != 0); + if (w->m_fullscreen) + { + bool activated = (wParam != 0); + eventManager->postEvent(ECCore, 15, &activated, 0.0f); + } + break; + + case WM_DESTROY: + host().postQuitMessage(); + break; + + case WM_SIZE: + w->m_width = static_cast(lParam & 0xFFFF); + w->m_height = static_cast((lParam >> 16) & 0xFFFF); + if (wParam != SIZE_MINIMIZED) + w->m_hasFocus = true; // the Win32 quirk: any restore reads as focus + break; + + case WM_ACTIVATE: + w->m_hasFocus = (wParam == WA_ACTIVE); + break; + + case WM_SETFOCUS: + w->m_hasFocus = true; + break; + + case WM_KILLFOCUS: + w->m_hasFocus = false; + break; + + default: + break; + } + + for (std::list::iterator it = w->m_handlers.begin(); it != w->m_handlers.end(); ++it) + (*it)(hwnd, message, wParam, lParam); + return 0; +} + +BF2Window::BF2Window() + : Window() +{ +} + +BF2Window::~BF2Window() +{ +} + +bool BF2Window::createFromSettings(const std::string& title, int width, int height, + bool fullscreen, bool hideCursor, int iconId) +{ + const int y = *Vars::getInt("opt-window-y", -1); + const int x = *Vars::getInt("opt-window-x", -1); + return Window::create(title, width, height, fullscreen, hideCursor, iconId, x, y); +} + +void BF2Window::setHwnd(HWND hwnd) +{ + m_hwnd = hwnd; +} + +// Win32 resizes the outer frame to fit the client size; the host keeps the top-left corner and +// reports the new size back as WM_SIZE. +void BF2Window::resizeClient(int width, int height) +{ + host().resizeClient(width, height); +} + +// Swaps the windowed and full-screen styles, shows and foregrounds, then flips the flag last. +void BF2Window::toggleFullscreenStyle() +{ + host().setFullscreen(!m_fullscreen); + host().show(true); + m_fullscreen = !m_fullscreen; +} + +} // namespace hfe +} // namespace dice + +#endif // !DEDICATED && __APPLE__ diff --git a/Code/BF2/Game/Main/GameConsole.cpp b/Code/BF2/Game/Main/GameConsole.cpp index a745d08fd..16465a63d 100644 --- a/Code/BF2/Game/Main/GameConsole.cpp +++ b/Code/BF2/Game/Main/GameConsole.cpp @@ -7,6 +7,8 @@ #include "BF2Engine.h" #include "Game.h" // operator>>(istream&, TargetChannel&) - game.radioMessage's converter #include "../IGameServer.h" // IGameServer::sayAll/sayTeam - game.sayAll/sayTeam's receiver interface +#include "../IGameClient.h" // demo.* playback commands - the game's client interface +#include "../IGame.h" // IGame::queryInterface - demo.*'s IGameClient lookup #include "../Utility/Vars.h" // vars.set's receiver - Vars::set(std::string, std::string) #include "../../Scene/Object/PlayerManager.h" // game.radioMessage's sender - the local human #if !DEDICATED @@ -161,11 +163,12 @@ BF2_CONSOLE_METHOD_0_STATIC_ACTIVE(toggleFullscreen, gameToggleFullscreen, ::dice::hfe::bf2Engine->getBF2Render() != 0, kGameConsoleTag) #endif -#if 0 // [RETIRE-WHEN: demo recording feature is implemented] // demo.recordDemo / demo.stopRecording - dedicated PE defaults 0x759A2E ("demo", access 1, // category 0); ctors 0x411970 / 0x411B40 (vtable off_785498 / off_785528), both file-static and // returning "void". The shared gate 0x4113C0 is `dword_837F9C != 0` (bf2Engine); executors // 0x411A60 / 0x411BD0 call BF2Engine::recordDemo / stopRecording (PE 0x402A50 / 0x4026F0). +// BF2.exe registers the same pair (ctors 0x43525C / 0x435381, gate 0x435440 `bf2Engine != 0`, +// executors 0x4352CD / 0x4353D3) and five playback commands, below. BF2_CONSOLE_OBJECT("Demo", 1, 0) namespace { void demoRecord(const std::string& name) { ::dice::hfe::bf2Engine->recordDemo(name); } @@ -175,6 +178,37 @@ BF2_CONSOLE_METHOD_1_STATIC_ACTIVE(recordDemo, demoRecord, ::dice::hfe::bf2Engin std::string, kGameConsoleTag) BF2_CONSOLE_METHOD_0_STATIC_ACTIVE(stopRecording, demoStopRecording, ::dice::hfe::bf2Engine != 0, kGameConsoleTag) + +#if !DEDICATED +// The battlerecorder playback commands the HUD roses run (HudElementsDemoRecComm.con / +// HudElementsDemoCameraComm.con). BF2.exe ctors 0x4353EE..0x435639, all "void": +// - demo.shutdownDemo: gate 0x435440 `bf2Engine != 0`, executor 0x43544C -> BF2Engine::shutdownDemo +// (PE 0x404A70); +// - demo.restartDemo / togglePlayerDemo(bool) / toggleCameraDemo / toggleDemoPauseOrPlay: gate +// 0x4354B9 `client != 0`, executors 0x4354C5 / 0x43559F / 0x43561D / 0x43568B call IGameClient +// +0x48 / +0x4C / +0x50 / +0x5C on the game's IGameClient (0x402F70: `game ? +// game->queryInterface(IID_IGameClient) : 0`, re-queried by the executor). +namespace { +IGameClient* demoGameClient() +{ + return ::dice::hfe::game + ? static_cast(::dice::hfe::game->queryInterface(IID_IGameClient)) : 0; +} +void demoShutdown() { ::dice::hfe::bf2Engine->shutdownDemo(); } +void demoRestart() { demoGameClient()->restartDemo(); } +void demoTogglePlayer(bool next) { demoGameClient()->demoSwitchPlayer(next); } +void demoToggleCamera() { demoGameClient()->demoNextCamera(); } +void demoTogglePauseOrPlay() { demoGameClient()->togglePause(); } +} // namespace +BF2_CONSOLE_METHOD_0_STATIC_ACTIVE(shutdownDemo, demoShutdown, ::dice::hfe::bf2Engine != 0, + kGameConsoleTag) +BF2_CONSOLE_METHOD_0_STATIC_ACTIVE(restartDemo, demoRestart, demoGameClient() != 0, kGameConsoleTag) +BF2_CONSOLE_METHOD_1_STATIC_ACTIVE(togglePlayerDemo, demoTogglePlayer, demoGameClient() != 0, bool, + kGameConsoleTag) +BF2_CONSOLE_METHOD_0_STATIC_ACTIVE(toggleCameraDemo, demoToggleCamera, demoGameClient() != 0, + kGameConsoleTag) +BF2_CONSOLE_METHOD_0_STATIC_ACTIVE(toggleDemoPauseOrPlay, demoTogglePauseOrPlay, demoGameClient() != 0, + kGameConsoleTag) #endif // Handed to the console registry by ModuleBF2::init, the way the original registers 0x8AD45A8. diff --git a/Code/BF2/Game/Main/IVideoOptions.h b/Code/BF2/Game/Main/IVideoOptions.h index 97e8a2f88..75bd88e42 100644 --- a/Code/BF2/Game/Main/IVideoOptions.h +++ b/Code/BF2/Game/Main/IVideoOptions.h @@ -1,6 +1,5 @@ // Host view of renderer video options. Virtual order is fixed and has no destructor slot. -// Native plugins share host STL types; retail-compatible plugins convert VC7.1 strings/vectors -// at the boundary. Do not pass native STL objects through a retail-layout interface. +// The renderer shares the host's STL types (issue #7), so strings and vectors cross directly. // [INFERRED] Interface/member names. [UNRESOLVED] Unnamed option slots retain provisional roles. #ifndef GAME_MAIN_IVIDEOOPTIONS_H #define GAME_MAIN_IVIDEOOPTIONS_H diff --git a/Code/BF2/Game/Main/OpenBF2Console.cpp b/Code/BF2/Game/Main/OpenBF2Console.cpp index c9ef81083..2eb589d29 100644 --- a/Code/BF2/Game/Main/OpenBF2Console.cpp +++ b/Code/BF2/Game/Main/OpenBF2Console.cpp @@ -27,8 +27,8 @@ // `host` module and imports `bf2`. This is why openbf2.con runs before Python init - load it // afterward and the hooks are too late. // - This loader does not itself reroute sockets. bf2hub's GameSpy/master redirection relied on an -// install-time patch of the host's import table that a runtime load does not reproduce; OpenBF2 -// points the engine at the correct master-server address in source instead (see the issue). +// install-time patch of the host's import table that a runtime load does not reproduce; the +// online services' domain is selected with +gamespy (Game/MatchMaking/OnlineProvider.h). #include "../../Core/ConsoleObjectMacro.h" @@ -126,15 +126,26 @@ std::vector resolveModuleCandidates(const std::string& name) out.push_back(name); return out; } + // [CHOSEN, not recovered] macOS uses .dylib for the same lib convention; a typed .so or + // .dll is still stripped so one config line keeps working on every build. +#if defined(__APPLE__) + const char* const suffix = ".dylib"; +#else + const char* const suffix = ".so"; +#endif std::string base = name; if (endsWithNoCase(base, ".so")) base.erase(base.size() - 3); +#if defined(__APPLE__) + else if (endsWithNoCase(base, ".dylib")) + base.erase(base.size() - 6); +#endif else if (endsWithNoCase(base, ".dll")) base.erase(base.size() - 4); const std::string stem = (base.compare(0, 3, "lib") == 0) ? base.substr(3) : base; - out.push_back(std::string("lib") + stem + ".so"); + out.push_back(std::string("lib") + stem + suffix); if (base != std::string("lib") + stem) // skip the duplicate when the name already had lib - out.push_back(base + ".so"); + out.push_back(base + suffix); #endif return out; } diff --git a/Code/BF2/Game/Main/PerformanceLogging.h b/Code/BF2/Game/Main/PerformanceLogging.h new file mode 100644 index 000000000..402024762 --- /dev/null +++ b/Code/BF2/Game/Main/PerformanceLogging.h @@ -0,0 +1,29 @@ +// [INFERRED] path and file. No __FILE__ string names this class; the inline handleEvent is emitted +// as a weak symbol beside BF2Engine's code in the Linux ELF. +#ifndef GAME_MAIN_PERFORMANCELOGGING_H +#define GAME_MAIN_PERFORMANCELOGGING_H + +#include "../IEventListener.h" + +namespace dice { +namespace hfe { + +// The performance logger BF2Engine keeps at +0x74 (BF2Engine::performanceLogging). Retail 1.50 never +// creates one: in the Linux ELF the vtable (0x08892F60, a single handleEvent slot; typeinfo 0x08892FA8 +// with the single base IEventListener) is stored only by the two inlined destructors in +// BF2Engine::shutdownGame (0x08138259) and BF2Engine::shutdownEngine (0x081394DF), and its setting +// GSPerfLogAtPlayerCount is only registered as a default (BF2Engine::initDefaultSettings, 0x0812F44D). +// The client PE is [INFERRED] to match. The class is complete here so that BF2Engine's `delete` +// runs its inline, non-virtual destructor and then operator delete, as both inlined destructors do. +// [CHOSEN, not recovered] No data members: nothing constructs the object or reads a field. +class PerformanceLogging : public IEventListener +{ +public: + // ELF 0x0813AFF0: an empty body. + virtual void handleEvent(EventCategory, unsigned int, EventNode*, void*) {} +}; + +} // namespace hfe +} // namespace dice + +#endif // GAME_MAIN_PERFORMANCELOGGING_H diff --git a/Code/BF2/Game/Main/StatusMonitor.cpp b/Code/BF2/Game/Main/StatusMonitor.cpp index 257e9c939..a6dc3d9a7 100644 --- a/Code/BF2/Game/Main/StatusMonitor.cpp +++ b/Code/BF2/Game/Main/StatusMonitor.cpp @@ -2,6 +2,7 @@ // service checks define the display layout. [INFERRED] File placement. #include "StatusMonitor.h" +#include "../PunkBuster/PbGlue.h" #include "StatusMonitorImpl.h" #include "../../IO/Network/ProtocolLayer/NetServer.h" @@ -21,7 +22,7 @@ // These declarations have global scope; the PunkBuster query uses C linkage. std::string getTimeString(unsigned int seconds); -extern "C" bool isPbSvEnabled(); +extern "C" bool isPbSvEnabled(); // Game/PunkBuster/PbServer.cpp // formatString is declared with the rest of the free functions further down, inside dice::hfe; // getTimeString sits above that block (it is global, and the ELF puts it below the ctor), so it @@ -44,13 +45,6 @@ std::string getTimeString(unsigned int seconds) return dice::hfe::formatString("%02d:%02d:%02d", hours, minutes, secs); } -// [CHOSEN, not recovered] Reports no PunkBuster service until SDK glue is available. -// Replace this local stand-in with the SDK query when that service is recovered. -extern "C" bool isPbSvEnabled() -{ - return false; -} - namespace dice { namespace hfe { diff --git a/Code/BF2/Game/Main/demo.cpp b/Code/BF2/Game/Main/demo.cpp index ea7cd8bd0..2ea959898 100644 --- a/Code/BF2/Game/Main/demo.cpp +++ b/Code/BF2/Game/Main/demo.cpp @@ -15,6 +15,7 @@ #include "../../IO/TickCalculator.h" #include "../../Scene/Object/PlayerManager.h" // the real PlayerManager - replaces the local shim #include "../../IO/File/FileManager.h" // io::fileManager (0x8AC8C80), open(...); IFileSystem enums +#include "../../Core/IProfilerClient.h" // profilerClient (ELF 0x8ABBCA8 / PE 0x9A5C6C) +0x2C pauseVTune #include // proven: __ioinit for this TU at 0x8AACC3D #include #include @@ -182,12 +183,7 @@ void Demo::beginMainLoop(BF2Render* render, BF2Console* console) demoRecorder->byte84 = true; // [UNRESOLVED meaning - NOT quit(); // endMainLoop clears it under the same test] else - { - // [UNRESOLVED] 0x8141CF0..0x8141D00: vcall [vptr+0x2C](false) on the cached - // "Profiler"/IID_IProfilerClient singleton (0x8ABBCA8). No IProfilerClient vtable exists - // in the binary, so the slot cannot be named. Kept as a comment until it can: - // profiler->UNRESOLVED_slot0x2C(false); - } + profilerClient->pauseVTune(false); // 0x8141CF0: profilerClient +0x2C(false) } bool Demo::endMainLoop(BF2Render* render, bool quit) // return [CHOSEN bool] @@ -202,10 +198,7 @@ bool Demo::endMainLoop(BF2Render* render, bool quit) // return [CHOSEN bo if (demoRecorder->demoConfig.vtuneRendering) // config+0x38 demoRecorder->byte84 = false; // the begin/end asymmetry, literal else - { - // [UNRESOLVED] same profiler slot as beginMainLoop (0x8142EB3..C3): - // profiler->UNRESOLVED_slot0x2C(false); - } + profilerClient->pauseVTune(false); // 0x8142EB3: the same slot, false again } if (timeDemoStats->frameCount >= 0) // warm-up frames not recorded { diff --git a/Code/BF2/Game/MatchMaking/Client/CdKeyStore.cpp b/Code/BF2/Game/MatchMaking/Client/CdKeyStore.cpp index b1fca4b38..e658d4b58 100644 --- a/Code/BF2/Game/MatchMaking/Client/CdKeyStore.cpp +++ b/Code/BF2/Game/MatchMaking/Client/CdKeyStore.cpp @@ -6,8 +6,14 @@ #include "CdKeyStore.h" #if !DEDICATED +#if defined(_WIN32) #include #include +#else +// [CHOSEN, not recovered] macOS: the DPAPI counterpart (docs/macos-port.md, "Protected profile +// data (DPAPI)"). The flow below is the shipped one; only the API calls differ. +#include "../../../Platform/macOS/ProtectedData.h" +#endif #include // malloc / free - the 402CF0 / 402D10 pair #include // memcmp / strlen @@ -74,7 +80,11 @@ void ProtectedData::release() { if (m_blob) { +#if defined(_WIN32) ::LocalFree(m_blob->pbData); +#else + macos::freeProtectedData(m_blob->pbData); +#endif delete m_blob; m_blob = 0; } @@ -86,8 +96,13 @@ bool ProtectedData::protect(const std::string& plainText) { DATA_BLOB in; const char* const text = plainText.c_str(); +#if defined(_WIN32) in.pbData = reinterpret_cast(const_cast(text)); in.cbData = static_cast(std::strlen(text) + 1); +#else + in.pbData = reinterpret_cast(const_cast(text)); + in.cbData = static_cast(std::strlen(text) + 1); +#endif if (plainText.empty()) return false; @@ -95,21 +110,32 @@ bool ProtectedData::protect(const std::string& plainText) release(); m_blob = new DATA_BLOB; // : operator new(8) +#if defined(_WIN32) return ::CryptProtectData(&in, L"This is the description string.", 0, 0, 0, CRYPTPROTECT_UI_FORBIDDEN, m_blob) != FALSE; +#else + // A failed protect leaves the blob empty, as a failed CryptProtectData does. + m_blob->cbData = 0; + m_blob->pbData = 0; + return macos::protectData(in.pbData, in.cbData, m_blob); +#endif } // Decodes a dpapi-protected hexadecimal value in place. Assigns plaintext only on // success; failure preserves the original text and leaks the temporary decode buffer. bool ProtectedData::unprotect(std::string& hexText) { +#if defined(_WIN32) const DWORD count = static_cast(hexText.size() >> 1); LPWSTR description = 0; +#else + const std::uint32_t count = static_cast(hexText.size() >> 1); +#endif if (!count) return false; - BYTE* const bytes = static_cast(std::malloc(count)); // : the engine malloc + unsigned char* const bytes = static_cast(std::malloc(count)); // : the engine malloc hexToBytes(hexText, bytes); DATA_BLOB in; @@ -117,6 +143,7 @@ bool ProtectedData::unprotect(std::string& hexText) in.cbData = count; DATA_BLOB out; +#if defined(_WIN32) if (::CryptUnprotectData(&in, &description, 0, 0, 0, CRYPTPROTECT_UI_FORBIDDEN, &out)) { hexText = std::string(reinterpret_cast(out.pbData)); @@ -125,6 +152,23 @@ bool ProtectedData::unprotect(std::string& hexText) ::LocalFree(out.pbData); return true; } +#else + out.cbData = 0; + out.pbData = 0; + // The plain text carries its terminator (protect includes it), so it is read as a C string. + if (macos::unprotectData(in.pbData, in.cbData, &out) && out.cbData && out.pbData[out.cbData - 1] == 0) + { + hexText = std::string(reinterpret_cast(out.pbData)); + std::free(bytes); + macos::freeProtectedData(out.pbData); + return true; + } + if (out.pbData) + macos::freeProtectedData(out.pbData); + // As shipped, `bytes` is not freed on failure; there is no system message to format. + return false; +#endif +#if defined(_WIN32) char* message = 0; if (::FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | @@ -133,6 +177,7 @@ bool ProtectedData::unprotect(std::string& hexText) reinterpret_cast(&message), 0, 0)) ::LocalFree(message); return false; +#endif } // Writes the encrypted blob as hex. Requires a non-null blob from successful protection. diff --git a/Code/BF2/Game/MatchMaking/OnlineProvider.cpp b/Code/BF2/Game/MatchMaking/OnlineProvider.cpp new file mode 100644 index 000000000..1ab16f02f --- /dev/null +++ b/Code/BF2/Game/MatchMaking/OnlineProvider.cpp @@ -0,0 +1,192 @@ +// [CHOSEN, not recovered] The online services' domain and the host names formed from it; see +// OnlineProvider.h. This file has no link dependency on the GameSpy SDK: the persistence classes +// that ask it for a URL are also built on their own by test fixtures. The SDK's host-name +// variables are written in OnlineProviderGameSpy.cpp. +#include "OnlineProvider.h" + +#include "../../External/GameSpy/common/gsCommon.h" // GSI_DOMAIN_NAME, the SDK's compiled domain + +#include +#include + +namespace dice { +namespace hfe { +namespace onlineProvider { + +namespace { + +// The GameSpy game name the services are registered under (MatchMakingServer.cpp g_gameName, +// ProfileManager.cpp and ServerBrowser.cpp pass the same literal). +const char kGameName[] = "battlefield2"; + +// The SDK keeps host names in char[64] variables. +const std::string::size_type kMaxHostName = 63; + +std::string& domainStorage() +{ + static std::string value(GSI_DOMAIN_NAME); + return value; +} + +bool& overriddenStorage() +{ + static bool value = false; + return value; +} + +// Index of the master server that lists a game: sb_serverlist.c forms ".ms." +// from StringHash(game, NUM_MASTER_SERVERS). The SDK variable that replaces the list server +// (SBOverrideMasterServer) takes the whole name, so the index is computed here the same way. +int masterServerIndex(const char* gameName) +{ + unsigned int hash = 0; + for (const char* s = gameName; *s; ++s) + hash = hash * static_cast(-1664117991) + + static_cast(std::tolower(static_cast(*s))); + return static_cast(hash % 20); +} + +std::string decimal(int value) +{ + std::string text; + do + { + text.insert(text.begin(), static_cast('0' + value % 10)); + value /= 10; + } while (value); + return text; +} + +// Labels of letters, digits and '-' separated by single dots, as in a DNS name. +bool isDomainName(const std::string& text) +{ + bool labelStart = true; + for (std::string::size_type i = 0; i < text.size(); ++i) + { + const unsigned char c = static_cast(text[i]); + if (c == '.') + { + if (labelStart) + return false; + labelStart = true; + } + else if (std::isalnum(c) || c == '-') + labelStart = false; + else + return false; + } + return !labelStart; +} + +bool isNumericAddress(const std::string& text) +{ + for (std::string::size_type i = 0; i < text.size(); ++i) + if (text[i] != '.' && !std::isdigit(static_cast(text[i]))) + return false; + return true; +} + +std::string gameHost(const char* service) +{ + return std::string(kGameName) + "." + service + "." + domain(); +} + +} // namespace + +bool setDomain(const std::string& value, std::string& error) +{ + if (value.empty()) + { + error = "a domain name is required"; + return false; + } + if (!isDomainName(value)) + { + error = "\"" + value + "\" is not a domain name"; + return false; + } + if (isNumericAddress(value)) + { + // ".available.
" is not a host: an address cannot stand in for the domain. + error = "\"" + value + "\" is an address, not a domain name"; + return false; + } + // The longest name formed is ".available." (as long as the statistics one). + if (std::strlen(kGameName) + std::strlen(".available.") + value.size() > kMaxHostName) + { + error = "\"" + value + "\" is too long"; + return false; + } + domainStorage() = value; + overriddenStorage() = value != GSI_DOMAIN_NAME; + return true; +} + +const std::string& domain() +{ + return domainStorage(); +} + +bool isOverridden() +{ + return overriddenStorage(); +} + +std::string availableHost() { return gameHost("available"); } +std::string masterHost() { return gameHost("master"); } +std::string connectionManagerHost() { return "gpcm." + domain(); } +std::string searchManagerHost() { return "gpsp." + domain(); } +std::string cdKeyHost() { return "key." + domain(); } +std::string gameStatsServerName() { return "gamestats." + domain(); } +std::string gameStatsHost() { return gameHost("gamestats"); } +std::string statsWebHost() { return "BF2Web." + domain(); } + +std::string serverListHost() +{ + return gameHost(("ms" + decimal(masterServerIndex(kGameName))).c_str()); +} + +std::string natNegHost(int index) +{ + return gameHost(("natneg" + decimal(index)).c_str()); +} + +std::string statsWebUrl() +{ + return "http://" + statsWebHost() + "/ASP/"; +} + +std::string playerInfoUrl() +{ + return "http://stage-net." + domain() + "/bf2/getplayerinfo.aspx?pid="; +} + +std::string describe(bool clientServices) +{ + std::string line("online services: domain "); + line += domain(); + line += isOverridden() ? " (+gamespy)" : " (default)"; + line += "; available=" + availableHost(); + line += " master=" + masterHost(); + line += " cdkey=" + masterHost(); + line += " natneg=" + natNegHost(1) + "," + natNegHost(2) + "," + natNegHost(3); + line += " gamestats=" + gameStatsHost(); + if (clientServices) + { + line += " serverlist=" + serverListHost(); + line += " gpcm=" + connectionManagerHost(); + line += " gpsp=" + searchManagerHost(); + } + line += " statsweb=" + statsWebUrl(); + line += " playerinfo=" + playerInfoUrl(); + return line; +} + +std::string commandLineArguments() +{ + return isOverridden() ? " +gamespy " + domain() : std::string(); +} + +} // namespace onlineProvider +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/Game/MatchMaking/OnlineProvider.h b/Code/BF2/Game/MatchMaking/OnlineProvider.h new file mode 100644 index 000000000..fb1c0f7ab --- /dev/null +++ b/Code/BF2/Game/MatchMaking/OnlineProvider.h @@ -0,0 +1,99 @@ +// [CHOSEN, not recovered] Run-time domain of the online (GameSpy protocol) services. This is an +// OpenBF2 extension: retail compiled "gamespy.com" into every service name, and those hosts no +// longer exist. The names are still formed exactly as retail forms them; only the domain part can +// be replaced, with the command-line option +gamespy (BF2Engine::parseParameters). +// Without the option every name is retail's. +// +// Retail 1.50 evidence: the function or the string reference that forms each name (ELF: the ia-32 +// Linux server 1.5.3153.0; the amd-64 one has the same strings). +// +// service host name retail evidence +// availability check .available. GSIStartAvailableCheck: BF2.exe +// 0x5A080C, bf2_w32ded.exe, ELF +// master (heartbeats, CD keys) .master. qr2_init: BF2.exe 0x66AD0C, +// bf2_w32ded.exe, ELF +// server list .ms. SBServerListConnectAndQuery: +// BF2.exe 0x668255, ELF 0x84CF6A0 +// presence connection manager gpcm. GP data: BF2.exe, ELF +// presence search manager gpsp. GP data: BF2.exe, ELF +// game statistics .gamestats. StatsManager::connect copies +// "gamestats.", the SDK +// prefixes : all images +// NAT negotiation .natneg1..3. ResolveServer "%s.%s": ELF +// 0x84C5D30 (natneg1, natneg2) +// stats web requests http://BF2Web./ASP/ HTTPRequest::getGameSpyUrl: +// BF2.exe 0x59C8C0, bf2_w32ded.exe +// 0x561760, ELF 0x82BE800 +// player info web request http://stage-net./bf2/.. PlayerStatsManager static init: +// BF2.exe 0x846D00, ELF 0x82F53D0 +// +// is the GameSpy game name "battlefield2"; is the SDK's hash of it (14, the same +// tolower/-1664117991/mod-20 hash in retail). CD keys are validated at the master's address on UDP +// 29910 (gcd_init_qr2, ELF GameSpyBackend 0x80BE2A0); the SDK's stand-alone key server name +// key. is set as well and is not used by the game. The Windows images carry no NAT +// negotiation code; retail's SDK has two NAT negotiation servers, the linked revision adds a third +// with the same name format. The SDK's peerchat. (chat) and motd. (patch check) +// are linked in the ELF but no game code calls them, here or in retail. +// +// The domain comes from the command line only. A console or settings-file command could be reached +// by mod or map content and would redirect account logins; and the first service starts before +// any server settings file runs. + +#ifndef GAME_MATCHMAKING_ONLINEPROVIDER_H +#define GAME_MATCHMAKING_ONLINEPROVIDER_H + +#include + +namespace dice { +namespace hfe { +namespace onlineProvider { + +// Replaces the domain of every online service name. Returns false, with a message for the user +// in error, when the value is not a usable domain name; the current domain is then unchanged. +bool setDomain(const std::string& domain, std::string& error); + +// The domain in use: the SDK's compiled name unless setDomain replaced it. +const std::string& domain(); + +// True when setDomain replaced the compiled domain. +bool isOverridden(); + +// Host names looked up for each service. +std::string availableHost(); // availability check +std::string masterHost(); // heartbeats and CD-key validation +std::string serverListHost(); // server browser master list +std::string natNegHost(int index); // NAT negotiation server 1..3 +std::string connectionManagerHost(); // presence login +std::string searchManagerHost(); // presence search and account creation +std::string cdKeyHost(); // the SDK's stand-alone key server name +std::string gameStatsHost(); // name looked up for the statistics connection +std::string statsWebHost(); // host of statsWebUrl() + +// The value for the SDK's StatsServerHostname: the SDK prefixes the game name itself. +std::string gameStatsServerName(); + +// "http://BF2Web./ASP/", the base of the persistence requests. +std::string statsWebUrl(); + +// "http://stage-net./bf2/getplayerinfo.aspx?pid=", PlayerStatsManager's request. +std::string playerInfoUrl(); + +// One line naming the host of every service, for the start-up log. clientServices adds the +// services only client images link (server list, presence). +std::string describe(bool clientServices); + +// " +gamespy " when the domain is replaced, otherwise empty. A restarted client +// must keep the domain it was started with (BF2Engine::buildRestartCommandLine). +std::string commandLineArguments(); + +// Prepares the linked GameSpy SDK; call once, before the first service starts. Writes the service +// names into the SDK's host-name variables when the domain is replaced (with the compiled domain +// the SDK forms the same names itself and nothing is written), and on POSIX makes a closed +// connection an error return instead of a fatal SIGPIPE. Defined in OnlineProviderGameSpy.cpp. +void prepareGameSpySdk(); + +} // namespace onlineProvider +} // namespace hfe +} // namespace dice + +#endif diff --git a/Code/BF2/Game/MatchMaking/OnlineProviderGameSpy.cpp b/Code/BF2/Game/MatchMaking/OnlineProviderGameSpy.cpp new file mode 100644 index 000000000..4638c6873 --- /dev/null +++ b/Code/BF2/Game/MatchMaking/OnlineProviderGameSpy.cpp @@ -0,0 +1,80 @@ +// [CHOSEN, not recovered] Prepares the linked GameSpy SDK for the process: the online services' +// host names (OnlineProvider.h) go into the SDK's own run-time host-name variables. +#include "OnlineProvider.h" + +#include +#if !defined(_WIN32) +#include +#endif + +extern "C" { +#include "../../External/GameSpy/common/gsCommon.h" +#include "../../External/GameSpy/common/gsAvailable.h" // GSIACHostname +#include "../../External/GameSpy/qr2/qr2.h" // qr2_hostname +#include "../../External/GameSpy/gcdkey/gcdkeys.h" // gcd_hostname +#include "../../External/GameSpy/gstats/gstats.h" // StatsServerHostname +#include "../../External/GameSpy/natneg/natneg.h" // Matchup1Hostname, Matchup2Hostname +extern char* Matchup3Hostname; // natneg.c; not declared in natneg.h +#if !DEDICATED +#include "../../External/GameSpy/gp/gp.h" // GPConnectionManagerHostname and + // GPSearchManagerHostname +extern char* SBOverrideMasterServer; // sb_serverlist.c (sb_internal.h) +#endif +} + +namespace dice { +namespace hfe { +namespace onlineProvider { + +namespace { + +// Every SDK host-name array is char[64]; setDomain admits no domain that forms a longer name. +void copyName(char (&destination)[64], const std::string& name) +{ + std::strncpy(destination, name.c_str(), sizeof(destination) - 1); + destination[sizeof(destination) - 1] = '\0'; +} + +} // namespace + +void prepareGameSpySdk() +{ +#if !defined(_WIN32) + // The SDK's TCP services (presence, server list, statistics, web requests) expect send() to + // report a connection the peer has closed or refused. On POSIX the default SIGPIPE action + // ends the process instead. The embedded Python ignores SIGPIPE when it starts, but that is + // only when a server is initialised; a client in the menu has not got that far. + std::signal(SIGPIPE, SIG_IGN); +#endif + + if (!isOverridden()) + return; + + // The pointer variables take storage that outlives every SDK call. + static char natNeg[3][64]; +#if !DEDICATED + static char serverList[64]; +#endif + + copyName(GSIACHostname, availableHost()); + copyName(qr2_hostname, masterHost()); + copyName(gcd_hostname, cdKeyHost()); + copyName(StatsServerHostname, gameStatsServerName()); + copyName(natNeg[0], natNegHost(1)); + copyName(natNeg[1], natNegHost(2)); + copyName(natNeg[2], natNegHost(3)); + Matchup1Hostname = natNeg[0]; + Matchup2Hostname = natNeg[1]; + Matchup3Hostname = natNeg[2]; +#if !DEDICATED + // Server browsing and presence are linked into client images only. + copyName(GPConnectionManagerHostname, connectionManagerHost()); + copyName(GPSearchManagerHostname, searchManagerHost()); + copyName(serverList, serverListHost()); + SBOverrideMasterServer = serverList; +#endif +} + +} // namespace onlineProvider +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/Game/MatchMaking/Server/GameSpyBackend.cpp b/Code/BF2/Game/MatchMaking/Server/GameSpyBackend.cpp index 36462747e..3fd8c6a24 100644 --- a/Code/BF2/Game/MatchMaking/Server/GameSpyBackend.cpp +++ b/Code/BF2/Game/MatchMaking/Server/GameSpyBackend.cpp @@ -15,6 +15,16 @@ extern "C" { #include "../../../External/GameSpy/common/gsAvailable.h" // GSIStartAvailableCheckA / Think } +#if !defined(_WIN32) +#include +#include +#include +#include +#include +#include +#include +#endif + namespace dice { namespace hfe { @@ -172,6 +182,78 @@ void GameSpyBackend::registerKeys() s_keysRegistered = true; } +#if !defined(_WIN32) +// [PLATFORM] LAN listing for a server bound to one address. qr2_create_socket binds the query +// socket to sv.interfaceIP. Winsock delivers a 255.255.255.255 datagram to a socket bound to the +// receiving interface's address, so retail Windows answers the client's LAN echo; BSD/xnu and +// Linux deliver broadcasts only to sockets bound to INADDR_ANY, so such a POSIX server was +// invisible to the LAN browser. A second socket bound to INADDR_ANY on the query port receives +// those datagrams and hands them to qr2_parse_queryA, which answers through the qr2 socket: the +// reply's source stays interfaceIP:port (the address the game port is bound to and the one +// heartbeats advertise). Unicast to interfaceIP still reaches the more specific qr2 socket. +// The listener also receives unicast sent to other local addresses on the query port; those are +// answered from interfaceIP as well (a browser matches replies by source and drops them). +namespace { int s_lanListener = -1; } // one GameSpyBackend per process + +static void openLanBroadcastListener(qr2_t qr2) +{ + sockaddr_in bound; + socklen_t boundLen = sizeof(bound); + if (getsockname(qr2->hbsock, reinterpret_cast(&bound), &boundLen) != 0 + || bound.sin_addr.s_addr == htonl(INADDR_ANY)) + return; // no interfaceIP (or loopback, which the SDK maps to INADDR_ANY): already listening + + // Linux allows the wildcard bind next to the specific one only when both set SO_REUSEADDR; + // the existing socket's flag is checked at the time of the second bind. + int on = 1; + setsockopt(qr2->hbsock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); + + int s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + if (s < 0) + return; + setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); + sockaddr_in any; + std::memset(&any, 0, sizeof(any)); + any.sin_family = AF_INET; + any.sin_addr.s_addr = htonl(INADDR_ANY); + any.sin_port = bound.sin_port; + if (bind(s, reinterpret_cast(&any), sizeof(any)) != 0 + || fcntl(s, F_SETFL, fcntl(s, F_GETFL, 0) | O_NONBLOCK) != 0) + { + std::fprintf(stderr, "GameSpy: LAN broadcast listener on port %d failed (%s); " + "LAN clients will not list this server\n", ntohs(bound.sin_port), std::strerror(errno)); + close(s); + return; + } + s_lanListener = s; +} + +static void pollLanBroadcastListener(qr2_t qr2) +{ + if (s_lanListener < 0) + return; + char data[256]; // qr2.c INBUF_LEN; the SDK parses a NUL-terminated copy + for (;;) + { + sockaddr_in from; + socklen_t fromLen = sizeof(from); + ssize_t n = recvfrom(s_lanListener, data, sizeof(data) - 1, 0, + reinterpret_cast(&from), &fromLen); + if (n < 0) + break; // EAGAIN: drained + data[n] = '\0'; + qr2_parse_queryA(qr2, data, static_cast(n), reinterpret_cast(&from)); + } +} + +static void closeLanBroadcastListener() +{ + if (s_lanListener >= 0) + close(s_lanListener); + s_lanListener = -1; +} +#endif + // GameSpyBackend lifecycle GameSpyBackend::GameSpyBackend(MatchMakingServer::Server* mmServer) : m_isInitialized(0) @@ -207,6 +289,9 @@ GameSpyBackend::GameSpyBackend(MatchMakingServer::Server* mmServer) if (gcd_init_qr2(reinterpret_cast(m_qr2), gamespy::g_XPackGameID)) return; m_isInitialized = 1; +#if !defined(_WIN32) + openLanBroadcastListener(reinterpret_cast(m_qr2)); +#endif } GameSpyBackend::~GameSpyBackend() @@ -219,6 +304,9 @@ GameSpyBackend::~GameSpyBackend() void GameSpyBackend::shutdown() { gcd_shutdown(); +#if !defined(_WIN32) + closeLanBroadcastListener(); +#endif qr2_shutdown(reinterpret_cast(m_qr2)); m_isInitialized = 0; } @@ -236,7 +324,12 @@ GameSpyCDKeyAuthenticator* GameSpyBackend::getAuthenticator() void GameSpyBackend::update() // / PE 0x616450 (SDK body inlined on PE) { if (m_isInitialized && m_qr2) + { qr2_think(reinterpret_cast(m_qr2)); +#if !defined(_WIN32) + pollLanBroadcastListener(reinterpret_cast(m_qr2)); +#endif + } } } // namespace hfe diff --git a/Code/BF2/Game/MatchMaking/Server/MatchMakingServer.cpp b/Code/BF2/Game/MatchMaking/Server/MatchMakingServer.cpp index 0b5757fcb..e2d361d5f 100644 --- a/Code/BF2/Game/MatchMaking/Server/MatchMakingServer.cpp +++ b/Code/BF2/Game/MatchMaking/Server/MatchMakingServer.cpp @@ -14,6 +14,7 @@ extern "C" { #include "MMBackend.h" #include "GameSpyBackend.h" #include "ServerQueryCache.h" // serverQueryCache - MatchMakingServer::update ticks it +#include "../../../Platform/MsvcRand.h" // [CHOSEN, not recovered] the client CRT's rand (MSVCR71) namespace dice { namespace hfe { @@ -78,7 +79,7 @@ const char* GameSpyCDKeyAuthenticator::getChallengeString() if (!challenge[0]) { for (unsigned int i = 0; i < 8; ++i) - challenge[i] = alphabet[std::rand() % (sizeof(alphabet) - 1)]; + challenge[i] = alphabet[bf2crt::rand() % (sizeof(alphabet) - 1)]; challenge[8] = 0; } return challenge; diff --git a/Code/BF2/Game/MatchMaking/Server/ServerQueryCache.cpp b/Code/BF2/Game/MatchMaking/Server/ServerQueryCache.cpp index ad1783c34..0c74f874d 100644 --- a/Code/BF2/Game/MatchMaking/Server/ServerQueryCache.cpp +++ b/Code/BF2/Game/MatchMaking/Server/ServerQueryCache.cpp @@ -1,8 +1,9 @@ // Refreshes browser query fields from live server, mod, and player state. -#include "ServerQueryCache.h" - #include +#include + +#include "ServerQueryCache.h" #include "../../IGame.h" // game, getCurrentMapName / GameMode / Size #include "../../IGameLogic.h" // gameLogic @@ -19,8 +20,6 @@ #include "../../MapList.h" #include "../../Main/BF2Engine.h" -#include - namespace dice { namespace hfe { @@ -135,6 +134,11 @@ void ServerQueryCache::update() m_serverKeys[SQK_ticketRatio] = formatString("%d", sv->getTicketRatio()); m_serverKeys[SQK_teamRatioPercent] = formatString("%f", sv->getTeamRatioPercent()); m_serverKeys[SQK_numReservedSlots] = formatString("%d", sv->getNumReservedSlots()); + // [CHOSEN, not recovered] Owner-approved R-main-1 improvement: retail leaves + // these registered bot keys empty. + m_serverKeys[SQK_coopBotRatio] = formatString("%f", sv->getCoopBotRatio()); + m_serverKeys[SQK_coopBotCount] = formatString("%d", sv->getCoopBotCount()); + m_serverKeys[SQK_coopBotDifficulty] = formatString("%f", sv->getCoopBotDifficulty()); m_serverKeys[SQK_noVehicles] = (sv->getNoVehicles() == true) ? "1" : "0"; // the player rows, sorted by score, capped at 64 diff --git a/Code/BF2/Game/MatchMaking/Server/ServerQueryCache.h b/Code/BF2/Game/MatchMaking/Server/ServerQueryCache.h index 1ec3d5700..1c26666d5 100644 --- a/Code/BF2/Game/MatchMaking/Server/ServerQueryCache.h +++ b/Code/BF2/Game/MatchMaking/Server/ServerQueryCache.h @@ -22,7 +22,8 @@ enum ServerQueryKey SQK_friendlyFireEnabled, SQK_punish, SQK_startDelay, SQK_spawnTime, SQK_sponsorText, SQK_sponsorLogoURL, SQK_ticketRatio, SQK_teamRatioPercent, SQK_teamName1, SQK_teamName2, SQK_hasBots, SQK_useContentChecking, SQK_currentMapSize, SQK_serverPort, SQK_useGlobalUnlocks, SQK_avgFps, - SQK_communityLogoURL, SQK_usesPlasma, SQK_numReservedSlots, SQK_unused41, SQK_unused42, SQK_unused43, + SQK_communityLogoURL, SQK_usesPlasma, SQK_numReservedSlots, + SQK_coopBotRatio, SQK_coopBotCount, SQK_coopBotDifficulty, SQK_noVehicles, NUM_SERVER_KEYS }; diff --git a/Code/BF2/Game/Objects/Base/Bundle.cpp b/Code/BF2/Game/Objects/Base/Bundle.cpp index abeafd805..ed8f823ab 100644 --- a/Code/BF2/Game/Objects/Base/Bundle.cpp +++ b/Code/BF2/Game/Objects/Base/Bundle.cpp @@ -2,6 +2,7 @@ // Contents: recovered Bundle construction and composite child propagation. #include "Bundle.h" +#include "../GeometryPartAccess.h" // named geometry operations (non-MSVC) #include "BundleTemplate.h" #include "../../../Core/Debug.h" #include "../../../Core/Ids.h" @@ -25,11 +26,13 @@ namespace { # define BF2_BUNDLE_VCALL #endif +#if defined(_MSC_VER) template inline Fn bundleVslot(void* object, unsigned int byteOffset) { return reinterpret_cast((*reinterpret_cast(object))[byteOffset / 4]); } +#endif // The renderer geometry interface is not otherwise present in the server source tree. Both ports // pin this one operation: PE +0x4C / ELF +0x54, taking an absolute transform and a part number. @@ -38,11 +41,11 @@ void setGeometryPartTransformation(geom::IGeometry* geometry, { #if defined(_MSC_VER) const unsigned int slot = 0x4C; -#else - const unsigned int slot = 0x54; -#endif typedef void (BF2_BUNDLE_VCALL* Fn)(void*, const Mat4&, int); bundleVslot(geometry, slot)(geometry, transformation, part); +#else + geometry_part::setTransform(geometry, &transformation, part); // ELF +0x54 +#endif } // Leaves nearly unit vectors unchanged and collapses nearly zero vectors to zero. diff --git a/Code/BF2/Game/Objects/Base/Camera.cpp b/Code/BF2/Game/Objects/Base/Camera.cpp index 6c858a0fd..cedb2f019 100644 --- a/Code/BF2/Game/Objects/Base/Camera.cpp +++ b/Code/BF2/Game/Objects/Base/Camera.cpp @@ -5,6 +5,7 @@ // Keep request/force position paths and the separate general/near-vehicle shake behavior. #include "Camera.h" +#include "../GeometryPartAccess.h" // named geometry operations (non-MSVC) #include "../../../Core/System.h" #include "../../../Core/Ids.h" #include "../../../Core/Debug.h" // setViewMode's attested line 1171 @@ -16,6 +17,8 @@ #include "../../../Physics/HeightmapCluster.h" #include "../../../Physics/IPhysicsNode.h" #include "../IPlayer.h" +#include "../../../Scene/Object/ObjectManager.h" // updateCloseVehicleShake's grid query +#include "../../../Scene/Object/ObjectPredicator.h" // its two heavy-engine filters #include #include #include "../ObjectLayoutAccess.h" // geometry(IObject*) - +0x38 @@ -36,6 +39,19 @@ namespace world { // turning the value into an unrelated per-camera literal. const float& g_explosionShakeTime = 0.6f; +// The rest of the TU's reference-backed tuning, same shape (ELF symbols at 0x8AAE0A4..0x8AAE0F8, +// values from the static initializer 0x81DF518..0x81DF6D2). +const float& g_vehicleShakeFrequency = 10.0f; // 0x8AAE0A4 +const float& g_vehicleShakeDistance = 7.0f; // 0x8AAE0AC +const float& g_vehicleShakeAmplitude = 0.2f; // 0x8AAE0B4 +const float& g_recoilAmplitude = 0.6f; // 0x8AAE0BC +const float& g_recoilSpeed = 1.0f; // 0x8AAE0C4 +const float& g_explosionShakeAmplitude = 2.0f; // 0x8AAE0D8 +const float& g_explosionShakeFrequency = 7.0f; // 0x8AAE0E0 +const float& g_checkCloseVehicleFreq = 1.0f; // 0x8AAE0E8 +const float& g_speedShakeAmp = 0.5f; // 0x8AAE0F0 +const float& g_speedShakeFrequency = 40.0f; // 0x8AAE0F8 + // ds:0x8ABAF24 in the ELF, with the matching singleton slot in both PEs. Core/Globals.cpp owns // the storage; every shipped camera terrain/water query dereferences it without a null guard. extern IBase* heightmapCluster; @@ -109,11 +125,13 @@ inline IHeightmapCluster* cameraHeightmapCluster() # define BF2_VCALL #endif +#if defined(_MSC_VER) template inline Fn vslot(void* object, unsigned int byteOffset) { return reinterpret_cast((*reinterpret_cast(object))[byteOffset / 4]); } +#endif typedef int (BF2_VCALL* VFn_geomCount)(void*); typedef void (BF2_VCALL* VFn_geomSet)(void*, int); @@ -124,15 +142,16 @@ typedef void (BF2_VCALL* VFn_geomSet)(void*, int); const unsigned int kGeomSetSubGeometrySlot = 0x6C; const unsigned int kGeomSubGeometryCountSlot = 0x74; const unsigned int kGeomSetLodSlot = 0x78; -#else -const unsigned int kGeomSetSubGeometrySlot = 0x70; -const unsigned int kGeomSubGeometryCountSlot = 0x78; -const unsigned int kGeomSetLodSlot = 0x7C; -#endif inline int geomSubGeometryCount(void* g) { return vslot(g, kGeomSubGeometryCountSlot)(g); } inline void geomSetSubGeometry(void* g, int i){ vslot(g, kGeomSetSubGeometrySlot)(g, i); } inline void geomSetLod(void* g, int i) { vslot(g, kGeomSetLodSlot)(g, i); } +#else +// Non-MSVC: the named geometry_part operations (ELF +0x70 / +0x78 / +0x7C). +inline int geomSubGeometryCount(void* g) { return geometry_part::getSubgeomCount(g); } +inline void geomSetSubGeometry(void* g, int i){ geometry_part::setSubgeom(g, i); } +inline void geomSetLod(void* g, int i) { geometry_part::setLod(g, i); } +#endif #if !DEDICATED && defined(_MSC_VER) // [TEMP] [CHOSEN, not recovered] Optional BF2_TRACE_VEHICLE_GEOM diagnostics for geometry switches and local camera roots. @@ -296,7 +315,7 @@ Camera::Camera(const CameraTemplate* templ) , m_float208(-1.0f) , m_externCameraTrans(Mat4::getIdentity()) , m_previousViewMode(1) - , m_dword250(8) + , m_savedViewMode(8) , m_traceObjectId(0) , m_dword258(-1) , m_float25C(1.0f) @@ -306,14 +325,23 @@ Camera::Camera(const CameraTemplate* templ) , m_explosionShakePeak(0.0f) // m_explosionShakeStartTime is deliberately absent: both shipped ctors leave the qword // untouched, and handleExplosion writes it before the accepted-shake path can consume it. + // ELF 0x81DABC3..0x81DAC3E zero +0x2B4..+0x2EC (two more empty vectors, a byte and words among + // them); the still-unnamed bytes are value-initialised to the same zeros. + , m_cameraPresentationPrefix() + , m_speedShakeTime(0.0f) , m_speedShakeRoll(0.0f) + , m_unresolved2CC(0) + , m_closeVehicles() + , m_cameraPresentationSuffix() , m_updateCameraRecoil(false) , m_recoilImpulseSpeed(0.0f) , m_recoilImpulseSize(0.0f) , m_explosionShakeTimeRemaining(0.0f) , m_explosionShakeMagnitude(1.0f) + , m_closeVehicleShakePhaseX(0.0f) + , m_closeVehicleShakePhaseY(0.0f) , m_cameraRecoilX(0.0f) - , m_recoilState314(0.0f) + , m_closeVehicleCheckTime(0.0f) , m_soldierShakeX(0.0f) , m_soldierShakeY(0.0f) , m_cameraRecoilY(0.0f) @@ -357,6 +385,258 @@ void Camera::handleExplosion(float amount) } } +namespace { +const float kTwoPi = 6.2831855f; // ELF 0x888F9F4 + +// The close-vehicle scan's filters (ELF vtables 0x88A5828 / 0x88A5810): a mobile physics root of at +// least the given mass whose player-control object is occupied, then the flag test. +class HeavyEnginePredicator : public ObjectFlagPredicator +{ +public: + explicit HeavyEnginePredicator(unsigned int flags) : ObjectFlagPredicator(flags) {} + bool predicate(IObject* object) { return heavyEngine(object, 10000.0f); } // ELF 0x81E00E0 + bool performCulling(IObject*) { return true; } // ELF 0x81E0190 +protected: + bool heavyEngine(IObject* object, float minimumMass) + { + typedef object_detail::LayoutAccess L; + IObject* const root = getRootParent(object); + IPlayerControlObject* pco = 0; + for (IObject* node = root; node; node = L::parent(node)) + { + pco = static_cast(node->queryInterface(IID_IPlayerControlObject)); + if (pco) + break; + } + IPhysicsNode* const physics = static_cast(L::physicsNode(root)); // unguarded root + if (!physics || !physics->getIsMobile()) + return false; + if (!(physics->getMass() >= minimumMass)) // jb: smaller or unordered + return false; + if (!pco || !pco->isOccupied()) + return false; + return ObjectFlagPredicator::predicate(object); + } +}; + +class HeavyEngineForcePredicator : public HeavyEnginePredicator +{ +public: + explicit HeavyEngineForcePredicator(unsigned int flags) : HeavyEnginePredicator(flags) {} + bool predicate(IObject* object) { return heavyEngine(object, 2000.0f); } // ELF 0x81E01A0 + bool performCulling(IObject*) { return true; } // ELF 0x81E0250 +}; +} // namespace + +// ELF 0x81DBA90 / BF2.exe 0x5A3EA0. BF2.exe also drives the Falcon's "ShakeForce" effects from the +// shake values here (0x5A3F4F..0x5A41D7, ledger N2); like the ELF, this has no such block (the device +// is archived, Code/Archive/NovintFalcon). +void Camera::handleUpdate(float deltaTime, unsigned int flags) +{ + typedef object_detail::LayoutAccess L; + + if (flags & 4) + { + if (!getNetworkable()) // ELF +0xD8 / PE +0xD4 + return; + RotationalBundle::handleUpdate(deltaTime, flags); + return; + } + + IPlayer* const local = playerManager->getLocalHumanPlayer(); + IPlayerControlObject* pco = 0; + for (IObject* node = this; node; node = L::parent(node)) + { + pco = static_cast(node->queryInterface(IID_IPlayerControlObject)); + if (pco) + break; + } + + if (pco && local && pco->getOccupingPlayer() == local) + { + updateCameraRecoil(deltaTime); + updateCameraShake(deltaTime); + } + + m_frameTime += deltaTime; + + if (pco) + { + if (local && pco->getOccupingPlayer() == local) + { + if (m_closeVehicleCheckTime > 1.0f / g_checkCloseVehicleFreq) + { + updateCloseVehicleShake(); + m_closeVehicleCheckTime = 0.0f; + } + else + { + m_closeVehicleCheckTime += deltaTime; + } + } + + if (IPlayer* const occupant = pco->getOccupingPlayer()) + { + // The occupant's free camera takes view mode 5 and restores the saved mode after. + if (occupant->getFreeCameraEnabled()) + { + if (m_savedViewMode == 8) + { + m_savedViewMode = getViewMode(); + setViewMode(static_cast(5), 0, false); + } + } + else if (m_savedViewMode != 8) + { + setViewMode(static_cast(m_savedViewMode), 0, false); + m_savedViewMode = 8; + } + } + } + + RotationalBundle::handleUpdate(deltaTime, flags); +} + +// ELF 0x81DC1D0 / BF2.exe 0x5A1A10: one sine period of vertical recoil per impulse. +void Camera::updateCameraRecoil(float deltaTime) +{ + if (!m_updateCameraRecoil) + { + m_cameraRecoilX = 0.0f; + m_cameraRecoilY = 0.0f; + return; + } + m_cameraRecoilX = deltaTime * m_recoilImpulseSpeed * g_recoilSpeed + m_cameraRecoilX; + if (m_cameraRecoilX > 1.0f) + { + m_updateCameraRecoil = false; + m_cameraRecoilX = 0.0f; + } + m_cameraRecoilY = sinf(kTwoPi * m_cameraRecoilX) * (g_recoilAmplitude * m_recoilImpulseSize); +} + +// ELF 0x81DC270 / BF2.exe 0x5A1A90: the speed shake, the two close-vehicle shakes (on foot only) +// and the explosion shake. +void Camera::updateCameraShake(float deltaTime) +{ + typedef object_detail::LayoutAccess L; + IObject* const parent = L::parent(this); + const CameraTemplate* const templ = static_cast(m_template); + + IObject* const root = getRootParent(this); + IPhysicsNode* const physics = static_cast(L::physicsNode(root)); + if (physics && templ->getCameraShakeStartSpeed() > 0.0f) + { + const Vec3& velocity = physics->getPositionalSpeed(); + const float speed = sqrtf(velocity.x * velocity.x + velocity.y * velocity.y + velocity.z * velocity.z); + if (speed > templ->getCameraShakeStartSpeed()) + { + m_speedShakeTime += deltaTime; + const float range = templ->getCameraShakeMaxSpeed() - templ->getCameraShakeStartSpeed(); + float scale = 1.0f; + if (range > 0.0f) + { + scale = (speed - templ->getCameraShakeStartSpeed()) / range; + if (0.0f > scale) + scale = 0.0f; + else if (scale > 1.0f) + scale = 1.0f; + } + const float amplitude = scale * g_speedShakeAmp; + m_speedShakeRoll = sinf(fmodf(m_speedShakeTime * g_speedShakeFrequency, kTwoPi)) * amplitude; + } + else + { + m_speedShakeRoll = 0.0f; + } + } + + const bool onFoot = parent && L::objectTemplate(parent)->getClassID() == CID_SoldierTemplate; + if (onFoot && m_soldierShakeX > 0.0f) + { + m_closeVehicleShakePhaseX = deltaTime * g_vehicleShakeFrequency + m_closeVehicleShakePhaseX; + if (m_closeVehicleShakePhaseX > 1.0f) + m_closeVehicleShakePhaseX -= 1.0f; + m_soldierShakeRoll = sinf(kTwoPi * m_closeVehicleShakePhaseX) * (m_soldierShakeX * g_vehicleShakeAmplitude); + } + else + { + m_closeVehicleShakePhaseX = 0.0f; + m_soldierShakeRoll = 0.0f; + } + + const bool onFootY = parent && L::objectTemplate(parent)->getClassID() == CID_SoldierTemplate; + if (onFootY && m_soldierShakeY > 0.0f) + { + m_closeVehicleShakePhaseY = deltaTime * g_vehicleShakeFrequency + m_closeVehicleShakePhaseY; + if (m_closeVehicleShakePhaseY > 1.0f) + m_closeVehicleShakePhaseY -= 1.0f; + m_soldierShakePitch = sinf(kTwoPi * m_closeVehicleShakePhaseY) * (m_soldierShakeY * g_vehicleShakeAmplitude); + } + else + { + m_closeVehicleShakePhaseY = 0.0f; + m_soldierShakePitch = 0.0f; + } + + if (m_explosionShakeTimeRemaining > 0.0f) + { + m_explosionShakeTimeRemaining -= deltaTime; + const float progress = 1.0f - m_explosionShakeTimeRemaining / g_explosionShakeTime; + const float amplitude = (1.0f - progress) * (g_explosionShakeAmplitude * m_explosionShakeMagnitude); + m_explosionShakeRoll = sinf(progress * kTwoPi * g_explosionShakeFrequency) * amplitude; + } + else + { + m_explosionShakeTimeRemaining = 0.0f; + m_explosionShakeRoll = 0.0f; + } +} + +// ELF 0x81DC550 / BF2.exe 0x5A3830: in the two first-person modes, the strongest nearby heavy +// vehicle sets each close-vehicle shake: (distance limit - distance) / limit, the camera's own +// root excluded. +void Camera::updateCloseVehicleShake() +{ + m_soldierShakeX = 0.0f; + m_soldierShakeY = 0.0f; + if (static_cast(m_viewMode - 1) > 1u) + return; + + { + HeavyEnginePredicator heavy(0x1000008); + objectManager->getObjectsFromGrid(getAbsolutePosition(), g_vehicleShakeDistance, m_closeVehicles, &heavy); + for (std::vector::iterator it = m_closeVehicles.begin(); it != m_closeVehicles.end(); ++it) + { + IObject* const vehicle = *it; + if (getRootParent(this) == vehicle) + continue; + const Vec3& own = getAbsolutePosition(); + const Vec3& other = vehicle->getAbsolutePosition(); + const float dx = other.x - own.x, dy = other.y - own.y, dz = other.z - own.z; + const float strength = (g_vehicleShakeDistance - sqrtf(dx * dx + dy * dy + dz * dz)) / g_vehicleShakeDistance; + if (strength > m_soldierShakeX) + m_soldierShakeX = strength; + } + } + { + HeavyEngineForcePredicator force(0x1000008); + objectManager->getObjectsFromGrid(getAbsolutePosition(), g_vehicleShakeDistance, m_closeVehicles, &force); + for (std::vector::iterator it = m_closeVehicles.begin(); it != m_closeVehicles.end(); ++it) + { + IObject* const vehicle = *it; + if (getRootParent(this) == vehicle) + continue; + const Vec3& own = getAbsolutePosition(); + const Vec3& other = vehicle->getAbsolutePosition(); + const float dx = other.x - own.x, dy = other.y - own.y, dz = other.z - own.z; + const float strength = (g_vehicleShakeDistance - sqrtf(dx * dx + dy * dy + dz * dz)) / g_vehicleShakeDistance; + if (strength > m_soldierShakeY) + m_soldierShakeY = strength; + } + } +} + // THE ONE that unblocks findCameras. It is also the clearest statement of the class's shape: // two of the four answers are SUB-object addresses, not this. void* Camera::queryInterface(unsigned int iid) const @@ -669,8 +949,8 @@ const Mat4& Camera::getTransformation(float deltaTime) // / BF2.exe 0x5A2920, 306 B. The dedicated image ends after the // absolute-transform copy; the client retains a runtime isDedicated() gate around animation, // roll and surface constraints. The immediate parent is queried twice, as in 0x5A2955..0x5A2970. -// Camera constructors ELF 0x81DA960 / client 0x5A4F90 zero all four consumed roll components. -// Their update producers remain separate Camera::handleUpdate recovery work. +// Camera constructors ELF 0x81DA960 / client 0x5A4F90 zero all four consumed roll components; +// Camera::handleUpdate's updateCameraRecoil, updateCameraShake and updateCloseVehicleShake produce them. const Mat4& Camera::getTransformationCVMInside(float) { m_defaultTransformation = getAbsoluteTransformation(); // virtual +0x84 @@ -766,10 +1046,11 @@ const Mat4& Camera::getTransformationCVMChase(float deltaTime, bool frontChase) float radius = root->getPhysicBoundingRadius(); if (radius <= 2.0f) radius = 2.0f; -#if defined(_MSC_VER) && defined(_M_IX86) +#if defined(_MSC_VER) else // [PLATFORM] PE 0x5F0A36/0x5F0A56 repeats this virtual call on the >2 or unordered // arm. ELF 0x81DCAD0 caches its sole call, so the non-Win32 source path does too. + // Every Windows image (x86 and the native x64, issue #7) takes the PE arm. radius = root->getPhysicBoundingRadius(); #endif desiredDistance = radius * s_chaseDistanceScale; @@ -788,9 +1069,9 @@ const Mat4& Camera::getTransformationCVMChase(float deltaTime, bool frontChase) desiredDirection.x, desiredDirection.y, desiredDirection.z, 1.0f }; float blend = deltaTime * cameraTemplate->getFollowStiffness(); -#if defined(_MSC_VER) && defined(_M_IX86) +#if defined(_MSC_VER) // [PLATFORM] PE's clamp helper returns zero for unordered/NaN; the ELF's inlined comparisons - // leave NaN untouched. + // leave NaN untouched. Every Windows image (x86 and the native x64, issue #7) takes the PE arm. if (!(blend >= 0.0f)) blend = 0.0f; #else @@ -1376,7 +1657,7 @@ void Camera::handleMessage(TemplateMessage message, IPlayer* player, bool flag) const int m = static_cast(message); if (m == 2) { - m_dword250 = 8; // before the player test, as shipped + m_savedViewMode = 8; // before the player test, as shipped if (player) { if (!player->getIsAIPlayer()) // ELF +0x64 / BF2.exe +0x60 diff --git a/Code/BF2/Game/Objects/Base/Camera.h b/Code/BF2/Game/Objects/Base/Camera.h index 203ac7f1e..678eaeaa9 100644 --- a/Code/BF2/Game/Objects/Base/Camera.h +++ b/Code/BF2/Game/Objects/Base/Camera.h @@ -9,6 +9,7 @@ #include "../CameraTemplate.h" #include "../../../Math/Quat.h" #include +#include #include "../../../Scene/Object/ObjectTypes/Game/IPlayerControlObject.h" // getPcoId walks for one namespace dice { @@ -63,6 +64,13 @@ class Camera : public RotationalBundle, public ICameraObject // , non-virtual; BF2.exe inlines it at both handleMessage sites. void setRecordingValid(bool valid); + // ELF 0x81DBA90 (496 B) / BF2.exe 0x5A3EA0: the local occupant's recoil and shake, the frame + // clock, the periodic close-vehicle scan and the free-camera view switch, then RotationalBundle. + virtual void handleUpdate(float deltaTime, unsigned int flags); + void updateCameraRecoil(float deltaTime); // ELF 0x81DC1D0 / BF2.exe 0x5A1A10 + void updateCameraShake(float deltaTime); // ELF 0x81DC270 / BF2.exe 0x5A1A90 + void updateCloseVehicleShake(); // ELF 0x81DC550 / BF2.exe 0x5A3830 + // Camera::Frame is exactly a recorded world position followed by its camera-clock timestamp. // The 16-byte payload is proved independently by the ELF list-node allocation and by both // readFrame bodies' node+8/+12/+16/+20 reads. @@ -137,7 +145,7 @@ class Camera : public RotationalBundle, public ICameraObject // as the forward axis and its fourth as the translation. /* +0x20C */ Mat4 m_externCameraTrans; /* +0x24C */ int m_previousViewMode; // ctor 1 [CHOSEN] name - /* +0x250 */ int m_dword250; // ctor 8 [UNRESOLVED] + /* +0x250 */ int m_savedViewMode; // ctor 8 = none; handleUpdate's free-camera switch [INFERRED] name /* +0x254 */ unsigned int m_traceObjectId; // ctor 0 /* +0x258 */ int m_dword258; // ctor -1 [UNRESOLVED] /* +0x25C */ float m_float25C; // ctor 1.0f [UNRESOLVED] @@ -152,12 +160,18 @@ class Camera : public RotationalBundle, public ICameraObject // [UNRESOLVED] presentation working state between the accepted-explosion timestamp and the // recovered recoil block. Its bounds are direct: ELF +0x2B4..+0x2F3, PE +0x2D8..+0x31F. // The PE has eight extra bytes here after its differently aligned/client-side prefix. - unsigned char m_cameraPresentationPrefix[0x14]; + unsigned char m_cameraPresentationPrefix[0x10]; + /* ELF +0x2C4 / PE +0x2E8 */ float m_speedShakeTime; // updateCameraShake's clock [INFERRED] name /* ELF +0x2C8 / PE +0x2EC */ float m_speedShakeRoll; + /* ELF +0x2CC / PE +0x2F0 */ int m_unresolved2CC; // [UNRESOLVED] + // updateCloseVehicleShake's grid-query result (ELF +0x2D0..+0x2DB begin/end/capacity). + /* ELF +0x2D0 */ std::vector m_closeVehicles; // [INFERRED] name #if defined(_MSC_VER) && defined(_M_IX86) - unsigned char m_cameraPresentationSuffix[0x30]; + unsigned char m_cameraPresentationSuffix[0x30 - 4 - sizeof(std::vector)]; +#elif defined(__i386__) + unsigned char m_cameraPresentationSuffix[0x28 - 4 - sizeof(std::vector)]; #else - unsigned char m_cameraPresentationSuffix[0x28]; + unsigned char m_cameraPresentationSuffix[0x18]; #endif // The recoil/shake block. Its shipped absolute offsets differ between ELF and PE because // Camera's client-side preceding layout differs. addRecoilImpulse touches the first three and @@ -167,9 +181,10 @@ class Camera : public RotationalBundle, public ICameraObject /* ELF +0x2FC / PE +0x328 */ float m_recoilImpulseSize; /* ELF +0x300 / PE +0x32C */ float m_explosionShakeTimeRemaining; /* ELF +0x304 / PE +0x330 */ float m_explosionShakeMagnitude; - /* ELF +0x308 / PE +0x334 */ unsigned char m_cameraRecoilState[8]; // [UNRESOLVED] + /* ELF +0x308 / PE +0x334 */ float m_closeVehicleShakePhaseX; // updateCameraShake [INFERRED] name + /* ELF +0x30C / PE +0x338 */ float m_closeVehicleShakePhaseY; // [INFERRED] name /* ELF +0x310 / PE +0x33C */ float m_cameraRecoilX; - /* ELF +0x314 / PE +0x340 */ float m_recoilState314; // [UNRESOLVED] role, ctor zero + /* ELF +0x314 / PE +0x340 */ float m_closeVehicleCheckTime; // handleUpdate's scan clock [INFERRED] name /* ELF +0x318 / PE +0x344 */ float m_soldierShakeX; /* ELF +0x31C / PE +0x348 */ float m_soldierShakeY; /* ELF +0x320 / PE +0x34C */ float m_cameraRecoilY; diff --git a/Code/BF2/Game/Objects/Base/FreeCamera.cpp b/Code/BF2/Game/Objects/Base/FreeCamera.cpp index b2ad92921..16e5e1a5d 100644 --- a/Code/BF2/Game/Objects/Base/FreeCamera.cpp +++ b/Code/BF2/Game/Objects/Base/FreeCamera.cpp @@ -521,6 +521,9 @@ void FreeCamera::handlePlayerInput(IPlayer* player, const io::PlayerInput& input if (object_detail::LayoutAccess::parent(this)) // +0x28 return; + // BF2.exe 0x63EC73..0x63ED26 (ledger N2): the local player's free camera zeroes the Falcon's force + // effects; none exists without the archived device (Code/Archive/NovintFalcon). + IBase* gameServer = static_cast(game->queryInterface(IID_IGameServer)); bool toggleRequested = false; diff --git a/Code/BF2/Game/Objects/Base/ModuleWorldObjTemplBase.cpp b/Code/BF2/Game/Objects/Base/ModuleWorldObjTemplBase.cpp index f20fc9112..1931532bb 100644 --- a/Code/BF2/Game/Objects/Base/ModuleWorldObjTemplBase.cpp +++ b/Code/BF2/Game/Objects/Base/ModuleWorldObjTemplBase.cpp @@ -89,6 +89,52 @@ struct BaseTemplateConsoleAccess static const std::string& getAiTemplate() { return simpleObject()->m_aiTemplate; } // +296 static void setAiTemplate(const std::string& value) { simpleObject()->m_aiTemplate = value; } + // The animated-UV block (offsets ELF / PE). Every executor stores the parsed value straight + // into the field; the PE Vec2 setters of Size, Max and RotationScale go through a small + // non-inlined helper that copies the two floats (PE 0x553857, 0x5539CB, 0x553F95), which + // the ELF executors inline. + static bool getAnimatedUVTranslation() { return simpleObject()->m_animatedUVTranslation; } // 228 / 0x118 + static void setAnimatedUVTranslation(bool value) { simpleObject()->m_animatedUVTranslation = value; } + static const Math::Vec2& getAnimatedUVTranslationSpeed() // 232 / 0x11C + { return simpleObject()->m_animatedUVTranslationSpeed; } + static void setAnimatedUVTranslationSpeed(const Math::Vec2& value) + { simpleObject()->m_animatedUVTranslationSpeed = value; } + static const Math::Vec2& getAnimatedUVTranslationSize() // 248 / 0x12C + { return simpleObject()->m_animatedUVTranslationSize; } + static void setAnimatedUVTranslationSize(const Math::Vec2& value) + { simpleObject()->m_animatedUVTranslationSize = value; } + static const Math::Vec2& getAnimatedUVTranslationMax() // 240 / 0x124 + { return simpleObject()->m_animatedUVTranslationMax; } + static void setAnimatedUVTranslationMax(const Math::Vec2& value) + { simpleObject()->m_animatedUVTranslationMax = value; } + static int getAnimatedUVTranslationIndex() { return simpleObject()->m_animatedUVTranslationIndex; } // 256 / 0x134 + static void setAnimatedUVTranslationIndex(int value) { simpleObject()->m_animatedUVTranslationIndex = value; } + static bool getAnimatedUVTranslationReverse() // 260 / 0x138 + { return simpleObject()->m_animatedUVTranslationReverse; } + static void setAnimatedUVTranslationReverse(bool value) + { simpleObject()->m_animatedUVTranslationReverse = value; } + // The one int-typed flag: GET zero-extends the byte, SET stores `value != 0`. + static int getAnimatedUVRotation() { return simpleObject()->m_animatedUVRotation ? 1 : 0; } // 261 / 0x139 + static void setAnimatedUVRotation(int value) { simpleObject()->m_animatedUVRotation = value != 0; } + static int getAnimatedUVRotationIndex() { return simpleObject()->m_animatedUVRotationIndex; } // 272 / 0x144 + static void setAnimatedUVRotationIndex(int value) { simpleObject()->m_animatedUVRotationIndex = value; } + static const Math::Vec2& getAnimatedUVRotationScale() // 264 / 0x13C + { return simpleObject()->m_animatedUVRotationScale; } + static void setAnimatedUVRotationScale(const Math::Vec2& value) + { simpleObject()->m_animatedUVRotationScale = value; } + static float getAnimatedUVRotationRadius() { return simpleObject()->m_animatedUVRotationRadius; } // 276 / 0x148 + static void setAnimatedUVRotationRadius(float value) { simpleObject()->m_animatedUVRotationRadius = value; } + static bool getAnimatedUVRotationReverse() { return simpleObject()->m_animatedUVRotationReverse; } // 280 / 0x14C + static void setAnimatedUVRotationReverse(bool value) { simpleObject()->m_animatedUVRotationReverse = value; } + static bool getRotateAsAnimatedUV() { return simpleObject()->m_rotateAsAnimatedUV; } // 281 / 0x14D + static void setRotateAsAnimatedUV(bool value) { simpleObject()->m_rotateAsAnimatedUV = value; } + static const std::string& getRotateAsAnimatedUVObject() // 284 / 0x150 + { return simpleObject()->m_rotateAsAnimatedUVObject; } + static void setRotateAsAnimatedUVObject(const std::string& value) + { simpleObject()->m_rotateAsAnimatedUVObject = value; } + static bool getRotateAsAnimatedUVReverse() { return simpleObject()->m_rotateAsAnimatedUVReverse; } // 288 / 0x16C + static void setRotateAsAnimatedUVReverse(bool value) { simpleObject()->m_rotateAsAnimatedUVReverse = value; } + // Console setters update individual physics bits. Physics-type changes recompute the selected type; sleeping does not. static bool getIsSleeping() { return (simpleObject()->m_physicsFlags & 0x01) != 0; } static void setIsSleeping(bool value) @@ -560,6 +606,60 @@ BF2_CONSOLE_PROPERTY_FN(floaterMod, float, getActiveTemplate(CID_SimpleObjectTem BF2_CONSOLE_PROPERTY_FN(otherCollisionLod, int, getActiveTemplate(CID_SimpleObjectTemplate) != 0, BaseTemplateConsoleAccess::getOtherCollisionLod(), BaseTemplateConsoleAccess::setOtherCollisionLod, kObjTemplBaseConsoleTag) + +// The animated-UV properties, in shipped registration order, all under the physics sub-table's +// defaults ("ObjectTemplate", 2, 23 - the BF2.exe TU initializer constructs them at 0x84E96C.. +// 0x84EA8F right after that SetConsoleClassDefaults call). PE constructors 0x553485, 0x553599, +// 0x5536FA, 0x55386E, 0x5539E2, 0x553AF6, 0x553C0A, 0x553D24, 0x553E38, 0x553FAC, 0x5540C9, +// 0x5541DD, 0x5542F1, 0x55445E; executors 0x553543, 0x553684, 0x5537E5, 0x553959, 0x553AA0, +// 0x553BB4, 0x553CC8, 0x553DE2, 0x553F23, 0x55406A, 0x554187, 0x55429B, 0x55436E, 0x55451C. The +// ELF executors are ModuleWorldObjTemplBase.cpp ConsoleClass147..157, 159, 160 and 161 +// (0x8680310..0x8684030). Content authors these on vehicle parts (tank road wheels and tracks): +// without them SimpleObject never allocates its AnimatedUV, the geometry keeps identity UV +// matrices, and the BundledMesh _hasuvanimation_ shader samples the wrong texture region. +BF2_CONSOLE_PROPERTY_FN(animatedUVTranslation, bool, getActiveTemplate(CID_SimpleObjectTemplate) != 0, + BaseTemplateConsoleAccess::getAnimatedUVTranslation(), + BaseTemplateConsoleAccess::setAnimatedUVTranslation, kObjTemplBaseConsoleTag) +BF2_CONSOLE_PROPERTY_FN(animatedUVTranslationSpeed, Vec2, getActiveTemplate(CID_SimpleObjectTemplate) != 0, + BaseTemplateConsoleAccess::getAnimatedUVTranslationSpeed(), + BaseTemplateConsoleAccess::setAnimatedUVTranslationSpeed, kObjTemplBaseConsoleTag) +BF2_CONSOLE_PROPERTY_FN(animatedUVTranslationSize, Vec2, getActiveTemplate(CID_SimpleObjectTemplate) != 0, + BaseTemplateConsoleAccess::getAnimatedUVTranslationSize(), + BaseTemplateConsoleAccess::setAnimatedUVTranslationSize, kObjTemplBaseConsoleTag) +BF2_CONSOLE_PROPERTY_FN(animatedUVTranslationMax, Vec2, getActiveTemplate(CID_SimpleObjectTemplate) != 0, + BaseTemplateConsoleAccess::getAnimatedUVTranslationMax(), + BaseTemplateConsoleAccess::setAnimatedUVTranslationMax, kObjTemplBaseConsoleTag) +BF2_CONSOLE_PROPERTY_FN(animatedUVTranslationIndex, int, getActiveTemplate(CID_SimpleObjectTemplate) != 0, + BaseTemplateConsoleAccess::getAnimatedUVTranslationIndex(), + BaseTemplateConsoleAccess::setAnimatedUVTranslationIndex, kObjTemplBaseConsoleTag) +BF2_CONSOLE_PROPERTY_FN(animatedUVTranslationReverse, bool, getActiveTemplate(CID_SimpleObjectTemplate) != 0, + BaseTemplateConsoleAccess::getAnimatedUVTranslationReverse(), + BaseTemplateConsoleAccess::setAnimatedUVTranslationReverse, kObjTemplBaseConsoleTag) +BF2_CONSOLE_PROPERTY_FN(animatedUVRotation, int, getActiveTemplate(CID_SimpleObjectTemplate) != 0, + BaseTemplateConsoleAccess::getAnimatedUVRotation(), + BaseTemplateConsoleAccess::setAnimatedUVRotation, kObjTemplBaseConsoleTag) +BF2_CONSOLE_PROPERTY_FN(animatedUVRotationIndex, int, getActiveTemplate(CID_SimpleObjectTemplate) != 0, + BaseTemplateConsoleAccess::getAnimatedUVRotationIndex(), + BaseTemplateConsoleAccess::setAnimatedUVRotationIndex, kObjTemplBaseConsoleTag) +BF2_CONSOLE_PROPERTY_FN(animatedUVRotationScale, Vec2, getActiveTemplate(CID_SimpleObjectTemplate) != 0, + BaseTemplateConsoleAccess::getAnimatedUVRotationScale(), + BaseTemplateConsoleAccess::setAnimatedUVRotationScale, kObjTemplBaseConsoleTag) +BF2_CONSOLE_PROPERTY_FN(animatedUVRotationRadius, float, getActiveTemplate(CID_SimpleObjectTemplate) != 0, + BaseTemplateConsoleAccess::getAnimatedUVRotationRadius(), + BaseTemplateConsoleAccess::setAnimatedUVRotationRadius, kObjTemplBaseConsoleTag) +BF2_CONSOLE_PROPERTY_FN(animatedUVRotationReverse, bool, getActiveTemplate(CID_SimpleObjectTemplate) != 0, + BaseTemplateConsoleAccess::getAnimatedUVRotationReverse(), + BaseTemplateConsoleAccess::setAnimatedUVRotationReverse, kObjTemplBaseConsoleTag) +BF2_CONSOLE_PROPERTY_FN(rotateAsAnimatedUV, bool, getActiveTemplate(CID_SimpleObjectTemplate) != 0, + BaseTemplateConsoleAccess::getRotateAsAnimatedUV(), + BaseTemplateConsoleAccess::setRotateAsAnimatedUV, kObjTemplBaseConsoleTag) +BF2_CONSOLE_PROPERTY_FN(rotateAsAnimatedUVObject, std::string, getActiveTemplate(CID_SimpleObjectTemplate) != 0, + BaseTemplateConsoleAccess::getRotateAsAnimatedUVObject(), + BaseTemplateConsoleAccess::setRotateAsAnimatedUVObject, kObjTemplBaseConsoleTag) +BF2_CONSOLE_PROPERTY_FN(rotateAsAnimatedUVReverse, bool, getActiveTemplate(CID_SimpleObjectTemplate) != 0, + BaseTemplateConsoleAccess::getRotateAsAnimatedUVReverse(), + BaseTemplateConsoleAccess::setRotateAsAnimatedUVReverse, kObjTemplBaseConsoleTag) + BF2_CONSOLE_PROPERTY_FN(physicsFrequency, int, getActiveTemplate(CID_SimpleObjectTemplate) != 0, BaseTemplateConsoleAccess::getPhysicsFrequency(), BaseTemplateConsoleAccess::setPhysicsFrequency, kObjTemplBaseConsoleTag) @@ -748,8 +848,9 @@ BF2_CONSOLE_FIELD(regulateRoll, Vec2, activeRotBundle(), m_r // Class-gated executors re-read the active template; geometry accesses the raw string field. // Preserve scale's reversed get/set slots and getConeAngle1 returning coneAngle2. // Range/angle setters report fatal errors above their caps (100 / 180); empty arguments are gets. -// RW-261: the earlier objectManager castsDynamicShadow row remains withheld, so this -// LightSource-specific row currently receives those calls. Registration order matters. +// castsDynamicShadow: the objectManager row of the same name (Scene/Object/ObjectManagerConsole.cpp) +// registers earlier and is active for every template, so console lookup never reaches this row; it +// is kept because the shipped images register it. Registration order matters. namespace { LightSourceTemplate* activeLightSource() diff --git a/Code/BF2/Game/Objects/Base/SimpleObject.cpp b/Code/BF2/Game/Objects/Base/SimpleObject.cpp index e7c03e564..8326be70a 100644 --- a/Code/BF2/Game/Objects/Base/SimpleObject.cpp +++ b/Code/BF2/Game/Objects/Base/SimpleObject.cpp @@ -2,6 +2,7 @@ // Contents: recovered SimpleObject construction, teardown, and bounded overrides. #include "SimpleObject.h" +#include "../GeometryPartAccess.h" // named geometry operations (non-MSVC) #include "SimpleObjectTemplate.h" #include "../../../AI/AIInterface/AIInstance.h" @@ -17,7 +18,7 @@ #include "../../../Geom/DecalSystem/DecalObjectAccess.h" // ~SimpleObject's DecalObject slot 10 (release) #include "../../../Geom/DecalSystem/IDecalManager.h" // the ctor's object decal (createClient +0x14) #include "../../../Geom/IGeometryTemplate.h" -#if !DEDICATED && BF2_PLUGIN_ABI_NATIVE && defined(_M_IX86) +#if !DEDICATED && (defined(_MSC_VER) || defined(BF2_STATIC_PLUGINS)) #include "../../../Geom/GeometryTemplateManager.h" #endif #include "../../../Physics/CollisionManager.h" @@ -57,11 +58,13 @@ namespace { # define BF2_SIMPLE_VCALL #endif +#if defined(_MSC_VER) template inline Fn simpleVslot(void* object, unsigned int byteOffset) { return reinterpret_cast((*reinterpret_cast(object))[byteOffset / 4]); } +#endif // The two renderer-geometry operations the animated-UV update drives. [INFERRED] names - the server // tree has no IGeometry declaration and neither slot is otherwise reachable, so only the physical @@ -70,22 +73,22 @@ void setGeometryAnimatedUVTranslation(void* geometry, int index, float first, fl { #if defined(_MSC_VER) const unsigned int slot = 0x90; -#else - const unsigned int slot = 0x94; -#endif typedef void (BF2_SIMPLE_VCALL* Fn)(void*, int, float, float); simpleVslot(geometry, slot)(geometry, index, first, second); +#else + geometry_part::setUvTranslation(geometry, index, first, second); // ELF +0x94 +#endif } void setGeometryAnimatedUVRotation(void* geometry, int index, const Mat4& transform) { #if defined(_MSC_VER) const unsigned int slot = 0x98; -#else - const unsigned int slot = 0x9C; -#endif typedef void (BF2_SIMPLE_VCALL* Fn)(void*, int, const Mat4&); simpleVslot(geometry, slot)(geometry, index, transform); +#else + geometry_part::setUvTransformation(geometry, index, &transform); // ELF +0x9C +#endif } // Leaves nearly unit vectors unchanged and collapses nearly zero vectors to zero. @@ -144,7 +147,8 @@ bool setGeometry(IObject* object, const std::string& geometry) if (!::dice::hfe::g_geometryTemplateManager) return false; -#if BF2_PLUGIN_ABI_NATIVE && defined(_M_IX86) +#if !DEDICATED && (defined(_MSC_VER) || defined(BF2_STATIC_PLUGINS)) + // Native static builds call the audited IGeometryTemplateManager view (+0x18). geom::IGeometryTemplate* const geometryTemplate = static_cast( ::dice::hfe::g_geometryTemplateManager)->getTemplate(geometry); @@ -173,9 +177,13 @@ bool setGeometry(IObject* object, const std::string& geometry) // The geometry instance's +0x9C, handed the object it now belongs to. The geometry instance // interface is not modelled anywhere in this tree, so this stays a documented raw slot - the // same policy as ObjectDrawer's +0x18 and +0xCC. +#if defined(_MSC_VER) typedef void (__thiscall* SetGeometryOwnerFn)(void*, IObject*); reinterpret_cast( - (*reinterpret_cast(instance))[0x9C / sizeof(void*)])(instance, object); + (*reinterpret_cast(instance))[0x9C / 4])(instance, object); +#else + geometry_part::setOwnerObject(instance, object); // PE +0x9C +#endif instance->release(); return true; diff --git a/Code/BF2/Game/Objects/Base/SimpleObjectTemplate.cpp b/Code/BF2/Game/Objects/Base/SimpleObjectTemplate.cpp index 5d90a4e44..85db06618 100644 --- a/Code/BF2/Game/Objects/Base/SimpleObjectTemplate.cpp +++ b/Code/BF2/Game/Objects/Base/SimpleObjectTemplate.cpp @@ -31,7 +31,7 @@ #include "../../../Sound/BfSound.h" #include "../../../Sound/SoundObjectTemplate.h" #endif -#if !DEDICATED && defined(_M_IX86) && BF2_PLUGIN_ABI_NATIVE +#if !DEDICATED && (defined(_MSC_VER) || defined(BF2_STATIC_PLUGINS)) #include "../../../Geom/GeometryTemplateManager.h" #endif @@ -724,7 +724,7 @@ Vec3 SimpleObjectTemplate::getAnchorPos() const // [PLATFORM] Client calls getAnchorOffset before getAnchor; dedicated code uses the opposite order. Vec3 SimpleObjectTemplate::getAnchorPos() const { -#if defined(_M_IX86) && BF2_PLUGIN_ABI_NATIVE +#if !DEDICATED && (defined(_MSC_VER) || defined(BF2_STATIC_PLUGINS)) geom::IGeometryTemplateManager* const manager = static_cast(::dice::hfe::g_geometryTemplateManager); geom::IGeometryTemplate* const geometry = manager->getTemplate(m_geometry); diff --git a/Code/BF2/Game/Objects/Base/SimpleObjectTemplate.h b/Code/BF2/Game/Objects/Base/SimpleObjectTemplate.h index e3e7e3082..e788a4d6d 100644 --- a/Code/BF2/Game/Objects/Base/SimpleObjectTemplate.h +++ b/Code/BF2/Game/Objects/Base/SimpleObjectTemplate.h @@ -14,7 +14,7 @@ namespace dice { namespace hfe { -namespace ai { class AIObjectUnit; class WeaponObject; } // field readers, friended below +namespace ai { class AIObjectUnit; class WeaponObject; class BFCollisionHandler; class BFObjectEnvironment; } // field readers, friended below namespace world { class ArtilleryHandler; @@ -153,8 +153,11 @@ class SimpleObjectTemplate : public ObjectTemplate, public ISimpleObjectTemplate protected: friend struct BaseTemplateConsoleAccess; // recovered direct-field console executors friend class SimpleObject; + friend class ai::BFObjectEnvironment; // the spawner query reads m_aiTemplate directly friend class ai::AIObjectUnit; // m_aiTemplate (+296) of a soldier's KIT - the // AIObjectUnit reads the kit template directly. + friend class ai::BFCollisionHandler; // m_aiTemplate (+296) - handleProjectileDamage's + // AI weapon template lookup friend class ai::WeaponObject; // a projectile's m_drag (+64), m_mass (+92) and // WeaponObject reads gravity configuration directly. friend class GenericFireArm; // m_aiTemplate (+296) - GenericFireArm::init diff --git a/Code/BF2/Game/Objects/CameraTemplate.cpp b/Code/BF2/Game/Objects/CameraTemplate.cpp index 22b2684b5..070f47a0b 100644 --- a/Code/BF2/Game/Objects/CameraTemplate.cpp +++ b/Code/BF2/Game/Objects/CameraTemplate.cpp @@ -29,11 +29,26 @@ CameraTemplate::CameraTemplate() // ELF C1/C2 0x81DE2F0 / 0x81DE0C0 write 1.2 literally at +0x2DC/+0x2E0; PE ctor // BF2.exe 0x5A3210 writes the same values at +0x38C/+0x390 (0x5A33B7/0x5A33C1). These defaults // matter even before content overrides them; stock SoldierCamera authors both as 1.1. + // ELF 0x81DE1CF..0x81DE20D / BF2.exe 0x5A3395..0x5A33B1: shake and bounce defaults. Camera's + // updateCameraShake reads the two speeds every frame; content sets them per camera (e.g. the + // FAAV pilot camera's 20 / 30). The bounce strength and damping are left unset, as shipped. + , m_cameraShakeSensitivity(0.1f) // +704 + , m_cameraShakeStartSpeed(0.0f) // +708 + , m_cameraShakeMaxSpeed(0.0f) // +712 + , m_bounceLength(0.0f) // +716 + , m_bounceSensitivity(1.0f) // +720 , m_worldFOV(1.2f) // +732 , m_insideFOV(1.2f) // +736 // Cockpits permit dynamic lights by default, but not static sunlight. , m_allowInsideDynamicLights(true) // +740 , m_allowInsideStaticSun(false) // +741 + // ELF 0x81DE1EB..0x81DE277 / BF2.exe 0x5A33D7..0x5A343E: the inside lighting defaults. + , m_insideStaticSunDirection{-0.25f, -0.5f, 0.75f} // +744 + , m_insideStaticSunColor{1.0f, 1.0f, 1.0f} // +756 + , m_insideStaticSunDamageColor{1.0f, 0.0f, 0.0f} // +768 + , m_insideDamageFrequency(3.0f) // +780 + , m_insideDamageThreshold(0.15f) // +784 + , m_insideStaticSunAmbientColor{0.7f, 0.7f, 0.7f} // +788 // ELF C1 0x81DE4B2/0x81DE4BD stores -1 at +0x320/+0x324; BF2.exe ctor 0x5A3210 // stores -1 at +0x3D0/+0x3D4 (0x5A3444/0x5A344E). Camera::changeSubGeometry uses -1 // to select the PCO's authored cockpit values. Omitting these defaults can pass uninitialized diff --git a/Code/BF2/Game/Objects/CameraTemplate.h b/Code/BF2/Game/Objects/CameraTemplate.h index 1da7bdc5d..7fd03ac74 100644 --- a/Code/BF2/Game/Objects/CameraTemplate.h +++ b/Code/BF2/Game/Objects/CameraTemplate.h @@ -79,6 +79,9 @@ class CameraTemplate : public RotationalBundleTemplate // NOT A shipped function. Camera::handleExplosion reads template +704 directly in both // ports (ELF +0x2C0 / PE +0x370); this accessor is only the typed C++ home for that proven read. float getCameraShakeSensitivity() const { return m_cameraShakeSensitivity; } + // Likewise for Camera::updateCameraShake's direct reads of +708 / +712 (ELF 0x81DC291, 0x81DC4BF). + float getCameraShakeStartSpeed() const { return m_cameraShakeStartSpeed; } + float getCameraShakeMaxSpeed() const { return m_cameraShakeMaxSpeed; } protected: // layout, offsets 532..807. RotationalBundleTemplate occupies 0..531. diff --git a/Code/BF2/Game/Objects/Fx/EffectBundle.cpp b/Code/BF2/Game/Objects/Fx/EffectBundle.cpp index efca48c67..e3aaf3a1c 100644 --- a/Code/BF2/Game/Objects/Fx/EffectBundle.cpp +++ b/Code/BF2/Game/Objects/Fx/EffectBundle.cpp @@ -71,7 +71,7 @@ void normalize(Vec3& value) float unitRandom() { // sign draw / Random helpers: signed shift after setting bit 7. - return static_cast((static_cast(g_random.getRaw() | 0x80u) >> 7) + 1) + return static_cast((static_cast(Rand.getRaw() | 0x80u) >> 7) + 1) * 0.000000059604645f; } float sample(const RandomDistribution& distribution) @@ -86,7 +86,7 @@ float sample(const RandomDistribution& distribution) result = distribution.value + (distribution.variation - distribution.value) * unitRandom(); break; case CRD_EXPONENTIAL: result = -distribution.value * std::log(unitRandom()); break; - case CRD_NORMAL: result = distribution.value + g_random.getNormal() * distribution.variation; break; + case CRD_NORMAL: result = distribution.value + Rand.getNormal() * distribution.variation; break; default: result = 0.0f; break; } return result * sign; diff --git a/Code/BF2/Game/Objects/Fx/EffectBundleTemplate.cpp b/Code/BF2/Game/Objects/Fx/EffectBundleTemplate.cpp index ff32b8911..a7e228ffd 100644 --- a/Code/BF2/Game/Objects/Fx/EffectBundleTemplate.cpp +++ b/Code/BF2/Game/Objects/Fx/EffectBundleTemplate.cpp @@ -89,10 +89,9 @@ void EffectBundleTemplate::preCache() const ObjectTemplate::preCache(); } -#if DEDICATED -// Dedicated ELF81FC410 / PE5F9250, read in full. The local stream is genuinely empty; -// its zero-byte write still occurs after a successful base writer and its result is checked. -// The client effect-specific writer remains a declaration-only frontier. +// Dedicated ELF81FC410 / PE5F9250 and client BF2.exe 0x6416E0 (table 0x8FF850 +0xF8), read in +// full and identical. The local stream is genuinely empty; its zero-byte write still occurs after a +// successful base writer and its result is checked. bool EffectBundleTemplate::makeMemberScript(const TemplateInfo* info, io::IStream* stream) { std::ostringstream out; @@ -101,7 +100,6 @@ bool EffectBundleTemplate::makeMemberScript(const TemplateInfo* info, io::IStrea const std::string text = out.str(); return stream->write(text.c_str(), static_cast(text.length())) == text.length(); } -#endif // substitute the effect-aware child info for Bundle's plain TemplateInfo. BundleTemplate::TemplateInfo* EffectBundleTemplate::createTemplateInfo(const std::string& name) diff --git a/Code/BF2/Game/Objects/Fx/EffectBundleTemplate.h b/Code/BF2/Game/Objects/Fx/EffectBundleTemplate.h index e35067f63..3c603ebda 100644 --- a/Code/BF2/Game/Objects/Fx/EffectBundleTemplate.h +++ b/Code/BF2/Game/Objects/Fx/EffectBundleTemplate.h @@ -1,7 +1,7 @@ // Groups effect emitters and supplies EffectProperties as a secondary base. // Client creation constructs an EffectBundle; dedicated creation returns null. Initialization adds a 3D looping Start sound. // preCache explicitly calls ObjectTemplate, and child info uses the EffectInfo subclass. -// RandomDistribution members retain their embedded seed/layout even though sampling uses g_random. +// RandomDistribution members retain their embedded seed/layout even though sampling uses Rand. // Original ELF size is 0x340; unresolved own-field roles remain marked below. Placement is [INFERRED]. #ifndef GAME_OBJECTS_FX_EFFECTBUNDLETEMPLATE_H // [INFERRED] guard style @@ -43,7 +43,7 @@ class EffectBundleTemplate : public BundleTemplate, public EffectProperties virtual IObject* createObject() const; // dedicated null; client PE 0x642680 virtual void preCache() const; // flags-gated grandparent call virtual bool makeScript(io::IStream*); // ELF/PE recovered - virtual bool makeMemberScript(const TemplateInfo*, io::IStream*); // dedicated ELF81FC410 / PE5F9250; client frontier + virtual bool makeMemberScript(const TemplateInfo*, io::IStream*); // ELF81FC410 / PE5F9250; client 6416E0 virtual TemplateInfo* createTemplateInfo(const std::string&); // news an EffectInfo virtual void setEmitFrequencyScaleFactorLowerBound(float); // the +0x30C store diff --git a/Code/BF2/Game/Objects/Fx/Emitter.cpp b/Code/BF2/Game/Objects/Fx/Emitter.cpp index d027c50b6..450bc8e0d 100644 --- a/Code/BF2/Game/Objects/Fx/Emitter.cpp +++ b/Code/BF2/Game/Objects/Fx/Emitter.cpp @@ -12,7 +12,7 @@ #include "../ObjectTemplate.h" // ObjectTemplate::getIsPreCaching #include "../ObjectLayoutAccess.h" // physicsNode / geometry of other objects #include "../../../Core/Ids.h" // CID_EffectBundle/Particle/SpriteParticleTemplate -#include "../../../Core/Random.h" // RandomDistribution, g_random (ELF dice::hfe::Rand) +#include "../../../Core/Random.h" // RandomDistribution, Rand (ELF dice::hfe::Rand) #include "../../../Core/OverTimeDistribution.h" #include "../../../Core/System.h" // g_system->getExactTime (ELF +0x18 / PE +0x14) #include "../../../Physics/MaterialManager.h" // playParticleCollisionSound @@ -232,7 +232,7 @@ float Emitter::calcInvItensity(const EmitterTemplate* objectTemplate, float spee const float fraction = scaled - static_cast(index); const float curve = (1.0f - fraction) * objectTemplate->m_intensityOverTime.m_samples[index] + fraction * objectTemplate->m_intensityOverTime.m_samples[index + 1]; - const double product = static_cast(sampleDistribution(objectTemplate->m_intensity, g_random)) + const double product = static_cast(sampleDistribution(objectTemplate->m_intensity, Rand)) * curve * speedFactor; float intensity = static_cast(product); if (!std::isfinite(product)) @@ -315,8 +315,8 @@ void Emitter::handleUpdate(float deltaTime, unsigned int flags) handleMessage(static_cast(1), 0, false); return; } - m_delay = sampleDistribution(t->m_delay, g_random); - m_timeToLive = sampleDistribution(t->m_timeToLive, g_random); + m_delay = sampleDistribution(t->m_delay, Rand); + m_timeToLive = sampleDistribution(t->m_timeToLive, Rand); if (m_timeToLive < 0.01f) // ds:0x892ADC, NaN kept m_timeToLive = 0.01f; m_age = 0.0f; @@ -387,15 +387,15 @@ void Emitter::handleUpdate(float deltaTime, unsigned int flags) { // Velocity from the emitter's axes - row 2 dof, row 1 up, row 0 right - drawn in that order. // quirk 4: `transform` carries the previous particles' roll (rows 0/1). - const float speedDof = sampleDistribution(t->m_positionalSpeed[0], g_random); // +0x50C + const float speedDof = sampleDistribution(t->m_positionalSpeed[0], Rand); // +0x50C speed.x = transform.m[8] * speedDof; speed.y = transform.m[9] * speedDof; speed.z = transform.m[10] * speedDof; - const float speedUp = sampleDistribution(t->m_positionalSpeed[1], g_random); // +0x520 + const float speedUp = sampleDistribution(t->m_positionalSpeed[1], Rand); // +0x520 speed.x = transform.m[4] * speedUp + speed.x; speed.y = transform.m[5] * speedUp + speed.y; speed.z = transform.m[6] * speedUp + speed.z; - const float speedRight = sampleDistribution(t->m_positionalSpeed[2], g_random); // +0x534 + const float speedRight = sampleDistribution(t->m_positionalSpeed[2], Rand); // +0x534 speed.x = transform.m[0] * speedRight + speed.x; speed.y = transform.m[1] * speedRight + speed.y; speed.z = transform.m[2] * speedRight + speed.z; @@ -406,15 +406,15 @@ void Emitter::handleUpdate(float deltaTime, unsigned int flags) position.x = travel.x * along + m_lastPosition.x; position.y = travel.y * along + m_lastPosition.y; position.z = travel.z * along + m_lastPosition.z; - const float relativeDof = sampleDistribution(t->m_relativePosition[0], g_random); // +0x4D0 + const float relativeDof = sampleDistribution(t->m_relativePosition[0], Rand); // +0x4D0 position.x = transform.m[8] * relativeDof + position.x; position.y = transform.m[9] * relativeDof + position.y; position.z = transform.m[10] * relativeDof + position.z; - const float relativeUp = sampleDistribution(t->m_relativePosition[1], g_random); // +0x4E4 + const float relativeUp = sampleDistribution(t->m_relativePosition[1], Rand); // +0x4E4 position.x = transform.m[4] * relativeUp + position.x; position.y = transform.m[5] * relativeUp + position.y; position.z = transform.m[6] * relativeUp + position.z; - const float relativeRight = sampleDistribution(t->m_relativePosition[2], g_random); // +0x4F8 + const float relativeRight = sampleDistribution(t->m_relativePosition[2], Rand); // +0x4F8 position.x = transform.m[0] * relativeRight + position.x; position.y = transform.m[1] * relativeRight + position.y; position.z = transform.m[2] * relativeRight + position.z; @@ -424,10 +424,10 @@ void Emitter::handleUpdate(float deltaTime, unsigned int flags) // Roll: zRotation snapped down (truncated) to zRotationSnap steps, plus startRotation. // Draw order as shipped: zRotation (+0x598) before startRotation (+0x584). - const float zRotation = sampleDistribution(t->m_zRotation, g_random); + const float zRotation = sampleDistribution(t->m_zRotation, Rand); const float snapped = static_cast(static_cast(zRotation / t->m_zRotationSnap)) * t->m_zRotationSnap; - const float angle = sampleDistribution(t->m_startRotation, g_random) + snapped; + const float angle = sampleDistribution(t->m_startRotation, Rand) + snapped; if (!t->m_addChild) // +0x5B2 { if (angle != 0.0f) // `fucompp; test ah, 44h; jnp` - NaN rotates (0x5A2800 then skips it) @@ -454,7 +454,7 @@ void Emitter::handleUpdate(float deltaTime, unsigned int flags) // (0x402EC0), then truncated; an index at or past the count (signed `jge`) is the main one. if (t->m_numAlternateTemplates) // +0x5B8 { - const float draw = sampleDistribution(selector, g_random) + const float draw = sampleDistribution(selector, Rand) * static_cast(t->m_numAlternateTemplates + 1); const int choice = static_cast(std::floor(draw)); if (choice < t->m_numAlternateTemplates) @@ -526,9 +526,9 @@ void Emitter::handleUpdate(float deltaTime, unsigned int flags) { // Draw order as shipped: right (+0x570), UP (+0x55C), DOF (+0x548) - the source's // Vec3(dof, up, right) arguments evaluated right to left by MSVC. - const float spinRight = sampleDistribution(t->m_rotationalSpeed[2], g_random); - const float spinUp = sampleDistribution(t->m_rotationalSpeed[1], g_random); - const float spinDof = sampleDistribution(t->m_rotationalSpeed[0], g_random); + const float spinRight = sampleDistribution(t->m_rotationalSpeed[2], Rand); + const float spinUp = sampleDistribution(t->m_rotationalSpeed[1], Rand); + const float spinDof = sampleDistribution(t->m_rotationalSpeed[0], Rand); Vec3 spin = { spinDof, spinUp, spinRight }; if (t->m_addEmitterSpeed && rootPhysics) { @@ -577,7 +577,7 @@ void Emitter::handleMessage(TemplateMessage message, IPlayer* /*player*/, bool / roll.distribution = CRD_UNIFORM; roll.value = 0.0f; roll.variation = 1.0f; - if (sampleDistribution(roll, g_random) >= t->m_startProbability) + if (sampleDistribution(roll, Rand) >= t->m_startProbability) return; } // A fresh start (the age is exactly 0 - after a stop, or never started). @@ -605,8 +605,8 @@ void Emitter::handleMessage(TemplateMessage message, IPlayer* /*player*/, bool / if (m_particleTemplate) updateFlags(0x3800, 1); // updates + visual + frame updates on, the disabled bit off } - m_delay = sampleDistribution(t->m_delay, g_random); - m_timeToLive = sampleDistribution(t->m_timeToLive, g_random); + m_delay = sampleDistribution(t->m_delay, Rand); + m_timeToLive = sampleDistribution(t->m_timeToLive, Rand); m_startTime = static_cast(g_system->getExactTime()); m_age = 0.0f; m_nextEmitTime = 0.0f; @@ -643,7 +643,7 @@ void Emitter::handleMessage(TemplateMessage message, IPlayer* /*player*/, bool / static_cast(getParent())->decNumEmittersPlaying(); if (t->m_looping) { - m_timeToLive = sampleDistribution(t->m_timeToLive, g_random); + m_timeToLive = sampleDistribution(t->m_timeToLive, Rand); m_nextEmitTime = 0.0f; return; } diff --git a/Code/BF2/Game/Objects/Fx/ExplosionEffectFlashBang.cpp b/Code/BF2/Game/Objects/Fx/ExplosionEffectFlashBang.cpp index 6b92c8dd8..eb6acc407 100644 --- a/Code/BF2/Game/Objects/Fx/ExplosionEffectFlashBang.cpp +++ b/Code/BF2/Game/Objects/Fx/ExplosionEffectFlashBang.cpp @@ -1,6 +1,10 @@ // [INFERRED] path: see header. ELF 812C030..812CD34 / dedicated PE 620780..62113E. // All lifecycle, immediate/persistent/update instructions and both vtables read in full. #include "ExplosionEffectFlashBang.h" +#if defined(BF2_STATIC_PLUGINS) && !defined(_MSC_VER) +// [CHOSEN, not recovered] This native provider is an explicit PE-order table. +#include "../../../RendMisc/NativePostProductionSlots.h" +#endif #include "PersistentExplosionEffectManager.h" #include "../IPlayer.h" #include "../ICameraObject.h" @@ -43,6 +47,9 @@ template Function postSlot(void* object, unsigned int peOrdinal) { #if defined(_MSC_VER) const unsigned int ordinal = peOrdinal; +#elif defined(BF2_STATIC_PLUGINS) + // [CHOSEN, not recovered] No compiler-generated destructor is inserted here. + const unsigned int ordinal = dx9rend::native_post::slot(peOrdinal); #else const unsigned int ordinal = peOrdinal + 1; #endif diff --git a/Code/BF2/Game/Objects/Fx/Particle.cpp b/Code/BF2/Game/Objects/Fx/Particle.cpp index 6445f75ea..c878b81d9 100644 --- a/Code/BF2/Game/Objects/Fx/Particle.cpp +++ b/Code/BF2/Game/Objects/Fx/Particle.cpp @@ -3,6 +3,13 @@ // Geometry setup is client-only. Preserve NaN lifetime handling and fatal checks for invalid lifetime, // unsupported light-source attachment, rejected mesh attachment and invalid geometry part. +#if defined(__APPLE__) +#include "../../../Platform/X87Compat.h" // [CHOSEN, not recovered] x87 conversion results, including invalid inputs. +#if defined(BF2_STATIC_PLUGINS) && !defined(_MSC_VER) +// [CHOSEN, not recovered] One native scale-interface declaration in every image. +#include "../../../Geom/IScaleable.h" +#endif +#endif #include "Particle.h" #include "ParticleTemplate.h" #include "Emitter.h" // fx2_emitter's world::Emitter (playParticleCollisionSound) @@ -11,7 +18,7 @@ #include "../../../Core/ClassManager.h" #include "../../../Core/Debug.h" #include "../../../Core/Ids.h" -#include "../../../Core/Random.h" // g_random, RandomDistribution +#include "../../../Core/Random.h" // Rand, RandomDistribution #include "../../../Geom/GeometryInstanceData.h" // the two opacity factors + setOpacity #include "../../../Physics/CollisionManager.h" // ICollisionManager::getCollisionMeshPart #include "../../../Physics/ICollisionMesh.h" // ICollisionMesh::createMaterialMapping @@ -41,15 +48,19 @@ namespace { // geom::IScaleable - the IBase quartet plus setScale at +0x10, exactly the view GenericProjectile.cpp // declares for the same IID. ELF 0x82090A4 / PE 0x64A1B1 call +0x10 with the address of a Vec3. +#if defined(BF2_STATIC_PLUGINS) && !defined(_MSC_VER) +using IScaleable = geom::IScaleable; +#else class IScaleable : public IBase { public: virtual void setScale(const Vec3& scale) = 0; }; +#endif // the RandomDistribution sampler, client order // BF2.exe 0x5E74B0 (121 B) on the process-global Random (ds:977F88; the ELF's Rand 0x8ABBCB0, this -// tree's g_random): when `relative` is set it draws the sign first - u <= 0.5 (compared as a double +// tree's Rand): when `relative` is set it draws the sign first - u <= 0.5 (compared as a double // 0.5) gives -1 - and only then 0x5E7450 draws the value; the product is the result. [PLATFORM] The // ELF constructor inlines the same distribution five times with the draws the other way round // (value first, sign second: e.g. 0x82060BC after the arm at 0x8207000). Both use the global @@ -58,7 +69,7 @@ float unitRandom() { // / 0x5E7360 / 0x5E74B0: `(raw | 0x80) sar 7, + 1` - equal to `((raw >> 7) | 1) + 1` // for every raw the Lehmer state can produce (< 2^31) - then * 2^-24. - return static_cast(static_cast(((g_random.getRaw() >> 7) | 1u) + 1u)) + return static_cast(static_cast(((Rand.getRaw() >> 7) | 1u) + 1u)) * 0.000000059604645f; } @@ -79,7 +90,7 @@ float sampleDistribution(const RandomDistribution& distribution) * distribution.value)); break; case CRD_NORMAL: // (getNormal) * variation + value - value = g_random.getNormal() * distribution.variation + distribution.value; + value = Rand.getNormal() * distribution.variation + distribution.value; break; default: value = 0.0f; @@ -332,8 +343,13 @@ void Particle::init() // [PLATFORM] BF2.exe multiplies the x87 sample by the count (fimul), floors it as a // double (msvcr71 floor) and truncates; the ELF uses floorf on the float product. const float sample = sampleDistribution(partDistribution); +#if defined(__APPLE__) + const int part = bf2x87::toIntTruncate(std::floor(static_cast(sample) + * static_cast(partCount))); +#else const int part = static_cast(std::floor(static_cast(sample) * static_cast(partCount))); +#endif m_geometryPart = part; m_assignedGeometryPart = part; } @@ -436,7 +452,11 @@ void Particle::handleUpdate(float deltaTime, unsigned int) if (clamped > 1.0f) // PE `test ah, 41h; jne` / ELF fcmovnbe clamped = 1.0f; const float scaled = clamped * 100.0f; // 101 curve positions, 0..100 +#if defined(__APPLE__) + sample = bf2x87::toIntTruncate(scaled); // truncation (PE fistp under a chop control word) +#else sample = static_cast(scaled); // truncation (PE fistp under a chop control word) +#endif blend = scaled - static_cast(sample); } diff --git a/Code/BF2/Game/Objects/Fx/ParticleTemplate.cpp b/Code/BF2/Game/Objects/Fx/ParticleTemplate.cpp index 7a8ad9aa8..e44399ef9 100644 --- a/Code/BF2/Game/Objects/Fx/ParticleTemplate.cpp +++ b/Code/BF2/Game/Objects/Fx/ParticleTemplate.cpp @@ -30,9 +30,6 @@ namespace dice { namespace hfe { -Random g_random; // ds:0x8ABBCB0 [CHOSEN name] - THE object, seeded 0x759DC150 by - // its ctor (the ELF's static init). See the class note. - // , read in full. Two Lehmer steps x' = a*x mod (2^31 - 1), a = 24112 then 26143, // each in the classic overflow-free 16-bit-halves form, on the persistent state. namespace { @@ -155,14 +152,14 @@ ParticleTemplate::ParticleTemplate() break; // sample = the value case 1: sample = m_gravityModifier.value + (m_gravityModifier.variation - m_gravityModifier.value) - * (float(((g_random.getRaw() >> 7) | 1) + 1) * 0.000000059604645f); + * (float(((Rand.getRaw() >> 7) | 1) + 1) * 0.000000059604645f); break; case 2: sample = -m_gravityModifier.value - * std::log(float(((g_random.getRaw() >> 7) | 1) + 1) * 0.000000059604645f); + * std::log(float(((Rand.getRaw() >> 7) | 1) + 1) * 0.000000059604645f); break; case 3: - sample = m_gravityModifier.value + g_random.getNormal() * m_gravityModifier.variation; + sample = m_gravityModifier.value + Rand.getNormal() * m_gravityModifier.variation; break; default: sample = 0.0f; @@ -177,21 +174,21 @@ ParticleTemplate::ParticleTemplate() break; case 1: sample = m_gravityModifier.value + (m_gravityModifier.variation - m_gravityModifier.value) - * (float(((g_random.getRaw() >> 7) | 1) + 1) * 0.000000059604645f); + * (float(((Rand.getRaw() >> 7) | 1) + 1) * 0.000000059604645f); break; case 2: sample = -m_gravityModifier.value - * std::log(float(((g_random.getRaw() >> 7) | 1) + 1) * 0.000000059604645f); + * std::log(float(((Rand.getRaw() >> 7) | 1) + 1) * 0.000000059604645f); break; case 3: - sample = m_gravityModifier.value + g_random.getNormal() * m_gravityModifier.variation; + sample = m_gravityModifier.value + Rand.getNormal() * m_gravityModifier.variation; break; default: sample = 0.0f; break; } // The coin flip: u <= 0.5 negates. - if (float(((g_random.getRaw() >> 7) | 1) + 1) * 0.000000059604645f <= 0.5f) + if (float(((Rand.getRaw() >> 7) | 1) + 1) * 0.000000059604645f <= 0.5f) sample = -sample; } m_sampledValue = sample; diff --git a/Code/BF2/Game/Objects/Game/AmbientEffectArea.cpp b/Code/BF2/Game/Objects/Game/AmbientEffectArea.cpp index 7fdd4675a..75835bec3 100644 --- a/Code/BF2/Game/Objects/Game/AmbientEffectArea.cpp +++ b/Code/BF2/Game/Objects/Game/AmbientEffectArea.cpp @@ -168,7 +168,7 @@ unsigned int ambientRandom(int& seed) // ELF 81658B8..5BE9 samples the distribution, materializes float, then draws its sign. double ambientUnitRandom() { - return static_cast((static_cast(g_random.getRaw() | 0x80u) >> 7) + 1) + return static_cast((static_cast(Rand.getRaw() | 0x80u) >> 7) + 1) * (1.0 / 16777216.0); } double ambientLifetimeSample(const RandomDistribution& distribution) @@ -184,7 +184,7 @@ double ambientLifetimeSample(const RandomDistribution& distribution) value = distribution.value + (double(distribution.variation) - distribution.value) * ambientUnitRandom(); break; case CRD_EXPONENTIAL: value = -double(distribution.value) * std::log(ambientUnitRandom()); break; - case CRD_NORMAL: value = distribution.value + double(g_random.getNormal()) * distribution.variation; break; + case CRD_NORMAL: value = distribution.value + double(Rand.getNormal()) * distribution.variation; break; default: value = 0; break; } #if defined(_WIN32) diff --git a/Code/BF2/Game/Objects/Game/AnimatedBundle.cpp b/Code/BF2/Game/Objects/Game/AnimatedBundle.cpp index 2e7d8ac7b..589cf0cd1 100644 --- a/Code/BF2/Game/Objects/Game/AnimatedBundle.cpp +++ b/Code/BF2/Game/Objects/Game/AnimatedBundle.cpp @@ -1,6 +1,7 @@ // Animated-bundle lifecycle and skeleton/geometry synchronization. #include "AnimatedBundle.h" +#include "../GeometryPartAccess.h" // named geometry operations (non-MSVC) #include "../../../Animation/BoneAnimation/AnimationSystem.h" #include "../../../Animation/BoneAnimation/Skeleton.h" @@ -21,16 +22,13 @@ namespace { #if defined(_MSC_VER) # define BF2_AB_VCALL __thiscall const unsigned int kGeometryPoseSlot = 0x54; -#else -# define BF2_AB_VCALL -const unsigned int kGeometryPoseSlot = 0x58; -#endif // Geometry pose upload takes one matrix per bone and a count; the slot differs by platform. typedef void (BF2_AB_VCALL* GeometryPoseFn)(void*, void*, int); inline void* rawSlot(void* object, unsigned int byteOffset) { return (*reinterpret_cast(object))[byteOffset / 4]; } +#endif } // namespace AnimatedBundle::AnimatedBundle(const AnimatedBundleTemplate* objectTemplate) @@ -104,8 +102,13 @@ void AnimatedBundle::handleVisualUpdate(float deltaTime, float) } m_skeleton->transform(0, -1); // Upload one transformation matrix per bone. +#if defined(_MSC_VER) reinterpret_cast(rawSlot(geometry, kGeometryPoseSlot))( geometry, m_skeleton->m_transforms, m_skeleton->m_boneCount); +#else + geometry_part::setBoneTransforms(geometry, reinterpret_cast(m_skeleton->m_transforms), + m_skeleton->m_boneCount); // ELF +0x58 +#endif } // / 0x8167940, 74 B each: both systems, slots +0x30 / +0x38. diff --git a/Code/BF2/Game/Objects/Game/AntennaObject.cpp b/Code/BF2/Game/Objects/Game/AntennaObject.cpp index 22c937ef4..4b383ae3b 100644 --- a/Code/BF2/Game/Objects/Game/AntennaObject.cpp +++ b/Code/BF2/Game/Objects/Game/AntennaObject.cpp @@ -1,6 +1,7 @@ // Antenna-object lifecycle and visual simulation. #include "AntennaObject.h" +#include "../GeometryPartAccess.h" // named geometry operations (non-MSVC) #include #include @@ -21,15 +22,16 @@ namespace { #if defined(_MSC_VER) #define BF2_ANTENNA_GEOM_CALL __thiscall const unsigned int setBoneTransformsSlot = 0x54; -#else -#define BF2_ANTENNA_GEOM_CALL -const unsigned int setBoneTransformsSlot = 0x58; #endif void geometrySetBoneTransforms(void* geometry, const Mat4* transforms, int boneCount) { +#if defined(_MSC_VER) typedef void (BF2_ANTENNA_GEOM_CALL* F)(void*, const Mat4*, int); reinterpret_cast( (*static_cast(geometry))[setBoneTransformsSlot / 4])(geometry, transforms, boneCount); +#else + geometry_part::setBoneTransforms(geometry, transforms, boneCount); // ELF +0x58 +#endif } #undef BF2_ANTENNA_GEOM_CALL diff --git a/Code/BF2/Game/Objects/Game/AreaObject.cpp b/Code/BF2/Game/Objects/Game/AreaObject.cpp index f691ecdbd..0d31fc34c 100644 --- a/Code/BF2/Game/Objects/Game/AreaObject.cpp +++ b/Code/BF2/Game/Objects/Game/AreaObject.cpp @@ -21,9 +21,9 @@ AreaObject::AreaObject(const AreaObjectTemplate* objectTemplate) AreaObject::~AreaObject() {} void AreaObject::init() { Bundle::init(); } -#if DEDICATED -// The dedicated images leave the observer at (0,0,0). Client camera/render work remains a -// declaration-only frontier; these definitions deliberately belong to the dedicated image. +// Both images measure from the observer at (0,0,0): the client body BF2.exe 0x5FF790 (table +// 0x8F3838 +0xA8) is the dedicated one, with the bounds test as a call (0x5CD130, inclusive +// min/max) instead of inline compares. void AreaObject::handleFrameUpdate(float) { const Mat4& absolute = getAbsoluteTransformation(); @@ -75,6 +75,8 @@ void AreaObject::handleFrameUpdate(float) } } +#if DEDICATED +// Dedicated-only: no client caller. void AreaObject::addAbsolutePoint() { const Vec3& position = getAbsolutePosition(); diff --git a/Code/BF2/Game/Objects/Game/ArtilleryHandler.h b/Code/BF2/Game/Objects/Game/ArtilleryHandler.h index ed23a26f7..a0b50603f 100644 --- a/Code/BF2/Game/Objects/Game/ArtilleryHandler.h +++ b/Code/BF2/Game/Objects/Game/ArtilleryHandler.h @@ -37,6 +37,9 @@ class ArtilleryHandler void failedFire(); void doFire(); bool haveAnyArtillery(); + // [INFERRED] name: inlined into BFCommander::gameHasArtillery (bf2 0x840FCE0), which tests + // the list header at +4 against its first node. + bool hasArtilleryPieces() const { return !m_artillery.empty(); } private: void findHelperObjects(ArtilleryObjectStruct& artillery); diff --git a/Code/BF2/Game/Objects/Game/CommanderToolsManager.cpp b/Code/BF2/Game/Objects/Game/CommanderToolsManager.cpp index 0f68ca1a4..5a3eb1582 100644 --- a/Code/BF2/Game/Objects/Game/CommanderToolsManager.cpp +++ b/Code/BF2/Game/Objects/Game/CommanderToolsManager.cpp @@ -30,6 +30,7 @@ #include #include #include +#include "../../../Platform/MsvcRand.h" // [CHOSEN, not recovered] the client CRT's rand (MSVCR71) namespace dice { namespace hfe { @@ -129,8 +130,8 @@ bool CommanderToolState::startScan() // half-open modulo expression are both shipped behavior. Vec3 CommanderToolState::CalculateRandomDropVehicleDeviation(int maximum, int minimum) { - const int distance = minimum + std::rand() % (maximum - minimum); - const double angle = static_cast(std::rand() % 360) / 360.0 * 6.28; + const int distance = minimum + bf2crt::rand() % (maximum - minimum); + const double angle = static_cast(bf2crt::rand() % 360) / 360.0 * 6.28; const double cosine = std::cos(angle); const double sine = std::sin(angle); diff --git a/Code/BF2/Game/Objects/Game/DestroyableWindowsBundle.cpp b/Code/BF2/Game/Objects/Game/DestroyableWindowsBundle.cpp index 645309719..71097e418 100644 --- a/Code/BF2/Game/Objects/Game/DestroyableWindowsBundle.cpp +++ b/Code/BF2/Game/Objects/Game/DestroyableWindowsBundle.cpp @@ -1,6 +1,7 @@ // Path: [INFERRED]. Runtime/template pairing follows the ELF TU's global constructor. // Evidence: ELF 0x8175500..0x817693F / PE 0x58F610..0x58FFFF. #include "DestroyableWindowsBundle.h" +#include "../GeometryPartAccess.h" // named geometry operations (non-MSVC) #include "../TemplateLeaves.h" #include "../../IGame.h" #include "../../../Core/Ids.h" @@ -24,10 +25,6 @@ namespace { #if defined(_MSC_VER) #define BF2_WINDOWS_CALL __thiscall const unsigned int partSlot = 0x4C, getSecondarySlot = 0xCC, setSecondarySlot = 0xC8; -#else -#define BF2_WINDOWS_CALL -const unsigned int partSlot = 0x54, getSecondarySlot = 0xD0, setSecondarySlot = 0xCC; -#endif template F geometrySlot(void* geometry, unsigned int offset) { return reinterpret_cast((*static_cast(geometry))[offset / 4]); @@ -48,6 +45,13 @@ void setPartTransformation(void* geometry, const Mat4& matrix, int part) geometrySlot(geometry, partSlot)(geometry, matrix, part); } #undef BF2_WINDOWS_CALL +#else +// Non-MSVC: the named geometry_part operations (ELF +0x54 / +0xD0 / +0xCC). +void* secondaryGeometry(void* geometry) { return geometry_part::getNextGeometry(geometry); } +void setSecondaryGeometry(void* geometry, void* secondary) { geometry_part::setNextGeometry(geometry, secondary); } +void setPartTransformation(void* geometry, const Mat4& matrix, int part) +{ geometry_part::setTransform(geometry, &matrix, part); } +#endif } DestroyableWindowsBundle::DestroyableWindowsBundle(const DestroyableWindowsBundleTemplate* objectTemplate) diff --git a/Code/BF2/Game/Objects/Game/EngineBase.h b/Code/BF2/Game/Objects/Game/EngineBase.h index cbd8b1b3e..b7934fd7c 100644 --- a/Code/BF2/Game/Objects/Game/EngineBase.h +++ b/Code/BF2/Game/Objects/Game/EngineBase.h @@ -60,6 +60,7 @@ class EngineBase : public RotationalBundle friend class Rotor; friend class EffectBundle; // client PE 0x641EB0 / ELF 0x81FB0B0 reads m_engineRunning friend class ::dice::hfe::EngineSound; // sway reads m_gear directly: ELF +0x1E8 / PE +0x200 + friend class ObjectSpawner; // the hold arm reads m_input (retail +0x1C4) directly protected: /* 0x1B0 */ const EngineTemplate* m_template; diff --git a/Code/BF2/Game/Objects/Game/ForceObject.cpp b/Code/BF2/Game/Objects/Game/ForceObject.cpp index c68190b88..52dd9845e 100644 --- a/Code/BF2/Game/Objects/Game/ForceObject.cpp +++ b/Code/BF2/Game/Objects/Game/ForceObject.cpp @@ -1,5 +1,8 @@ // Force-object lifecycle and input-driven force application. +#if defined(__APPLE__) +#include "../../../Platform/X87Compat.h" // [CHOSEN, not recovered] x87 conversion results, including invalid inputs. +#endif #include "ForceObject.h" #include // FLT_EPSILON - the engine normalise rule @@ -85,8 +88,13 @@ void ForceObject::handleUpdate(float, unsigned int) { // getTickCount() is called before the multiply in the image (0x82A77F3), and the // cast is the ordinary truncating float->int (fistp under a round-to-zero control word). +#if defined(__APPLE__) + m_dword144 = WorldPref::getTickCount() + + bf2x87::toIntTruncate(30.0f * m_template->startDelay); +#else m_dword144 = WorldPref::getTickCount() + static_cast(30.0f * m_template->startDelay); +#endif return; } if (m_dword144 > WorldPref::getTickCount()) diff --git a/Code/BF2/Game/Objects/Game/Kit.cpp b/Code/BF2/Game/Objects/Game/Kit.cpp index ea7c9552f..f9e1144ee 100644 --- a/Code/BF2/Game/Objects/Game/Kit.cpp +++ b/Code/BF2/Game/Objects/Game/Kit.cpp @@ -18,6 +18,7 @@ #include "../IObjectTemplate.h" #include "../IPlayer.h" #include "../ItemContainerTemplate.h" +#include "../GeometryPartAccess.h" // named geometry operations (non-MSVC) #include "../ObjectLayoutAccess.h" // m_geometry (+0x38) - updateGeometry's gate #include // the shipped aborts #include // updateUnlockStatus' two working sets @@ -67,41 +68,46 @@ const unsigned int kGeometrySetGeomIndexSlot = 0x6C; const unsigned int kGeometryGetGeomIndexSlot = 0x70; const unsigned int kGeometryGetGeomCountSlot = 0x74; const unsigned int kGeometrySetBoneTransformsSlot = 0x54; -#else -typedef int (*GeometryGetIntFn)(void*); -typedef void (*GeometrySetIntFn)(void*, int); -typedef void (*GeometrySetBoneTransformsFn)(void*, const Mat4*, unsigned int); -const unsigned int kGeometrySetGeomIndexSlot = 0x70; -const unsigned int kGeometryGetGeomIndexSlot = 0x74; -const unsigned int kGeometryGetGeomCountSlot = 0x78; -const unsigned int kGeometrySetBoneTransformsSlot = 0x58; #endif +// Non-MSVC: the named geometry_part operations (ELF +0x70/+0x74/+0x78/+0x58). int geometryGetGeomCount(void* geometry) { if (!geometry) return 0; +#ifdef _MSC_VER void** const vtable = *reinterpret_cast(geometry); return reinterpret_cast( vtable[kGeometryGetGeomCountSlot / 4])(geometry); +#else + return geometry_part::getSubgeomCount(geometry); +#endif } int geometryGetGeomIndex(void* geometry) { if (!geometry) return 0; +#ifdef _MSC_VER void** const vtable = *reinterpret_cast(geometry); return reinterpret_cast( vtable[kGeometryGetGeomIndexSlot / 4])(geometry); +#else + return geometry_part::getSubgeom(geometry); +#endif } void geometrySetGeomIndex(void* geometry, int index) { if (!geometry) return; +#ifdef _MSC_VER void** const vtable = *reinterpret_cast(geometry); reinterpret_cast( vtable[kGeometrySetGeomIndexSlot / 4])(geometry, index); +#else + geometry_part::setSubgeom(geometry, index); +#endif } @@ -111,9 +117,13 @@ void geometrySetBoneTransforms(void* geometry, const Mat4* transforms, unsigned { if (!geometry) return; +#ifdef _MSC_VER void** const vtable = *reinterpret_cast(geometry); reinterpret_cast( vtable[kGeometrySetBoneTransformsSlot / 4])(geometry, transforms, boneCount); +#else + geometry_part::setBoneTransforms(geometry, transforms, static_cast(boneCount)); +#endif } // removeAllKitItems - 0x8183ED0, 93 B. TU-local (the ELF's own anonymous namespace, keyed to diff --git a/Code/BF2/Game/Objects/Game/MaskObject.cpp b/Code/BF2/Game/Objects/Game/MaskObject.cpp index d02787f7e..bce367aac 100644 --- a/Code/BF2/Game/Objects/Game/MaskObject.cpp +++ b/Code/BF2/Game/Objects/Game/MaskObject.cpp @@ -1,5 +1,10 @@ // Path: [INFERRED] - see MaskObject.h. Every own body read in both dedicated images. #include "MaskObject.h" +#include "../GeometryPartAccess.h" // named geometry operations (non-MSVC) +#if defined(BF2_STATIC_PLUGINS) && !defined(_MSC_VER) +// [CHOSEN, not recovered] Native static geometry tables retain PE slot order. +#include "../../../Geom/NativeGeometrySlots.h" +#endif #include "Soldier.h" #include "../IPlayer.h" #include "../../../Animation/BoneAnimation/Skeleton.h" @@ -75,12 +80,11 @@ void MaskObject::updateGeometryPosition(Soldier* soldier) #if defined(_MSC_VER) typedef void (__thiscall* GeometryPoseFn)(void*, void*, int); const unsigned int slot = 0x54 / 4; -#else - typedef void (*GeometryPoseFn)(void*, void*, int); - const unsigned int slot = 0x58 / 4; -#endif reinterpret_cast((*reinterpret_cast(m_geometry))[slot])( m_geometry, skeleton->m_transforms, skeleton->m_boneCount); +#else + geometry_part::setBoneTransforms(m_geometry, skeleton->m_transforms, skeleton->m_boneCount); // ELF +0x58 +#endif } } diff --git a/Code/BF2/Game/Objects/Game/ObjectSpawner.cpp b/Code/BF2/Game/Objects/Game/ObjectSpawner.cpp index d72943410..3b195ceca 100644 --- a/Code/BF2/Game/Objects/Game/ObjectSpawner.cpp +++ b/Code/BF2/Game/Objects/Game/ObjectSpawner.cpp @@ -29,6 +29,7 @@ #include "../IPlayer.h" // getVehicle - moveIntersectingSoldiers' occupant test #include "../GameLogicComp/ArmorGLComp.h" // armorTemplateCanBeDestroyed #include "../GameLogicComp/ArmorGLCompTemplate.h" +#include "EngineBase.h" // m_input - the hold arm's engine test #include // sqrtf / fabsf #include @@ -321,12 +322,6 @@ inline IPlayerControlObject* pcoOf(IObject* object) return 0; } -// Reads the engine's current input from its fixed layout. -inline float engineInput(IObject* engine) -{ - return *reinterpret_cast(reinterpret_cast(engine) + 0x1C4); -} - inline Vec3 V3(float x, float y, float z) { Vec3 v; v.x = x; v.y = y; v.z = z; return v; } // Vec3 is an aggregate here inline float distanceBetween(const Vec3& a, const Vec3& b) @@ -472,7 +467,10 @@ void ObjectSpawner::handleUpdate(float dt, unsigned int) { IObject* engine = 0; getEngineFromChildsAndSiblings(held, engine); - if (!engine || fabsf(engineInput(engine)) >= 0.1f) // flt_888CA90 + // The CID_EngineTemplate object is an EngineBase; the PE reads m_input at retail + // +0x1C4. The named member, because this build's layout is not retail's (m_input + // sits at +0x1D0 on x86 here). flt_888CA90 = 0.1. + if (!engine || fabsf(static_cast(engine)->m_input) >= 0.1f) release = true; } if (release) diff --git a/Code/BF2/Game/Objects/Game/PlayerControlObject.cpp b/Code/BF2/Game/Objects/Game/PlayerControlObject.cpp index 2a514bf3f..fd923aa9e 100644 --- a/Code/BF2/Game/Objects/Game/PlayerControlObject.cpp +++ b/Code/BF2/Game/Objects/Game/PlayerControlObject.cpp @@ -1389,6 +1389,8 @@ void PlayerControlObject::handleUpdate(float deltaTime, unsigned int flags) } if (m_ambientSoundFromTemplate || m_ambientDamagedSoundFromTemplate) updateAmbientSound(); + // BF2.exe 0x5FAC8C..0x5FBCDB (ledger N2 17b) feeds the Falcon's "CraftPhysics" forces here; + // they need a device (archived, Code/Archive/NovintFalcon). } if (m_groundContactSound) { @@ -2784,7 +2786,7 @@ void PlayerControlObject::getUnmannedInput(io::PlayerInput& input) + static_cast(30.0f * *pcoUnmannedInputTime); #endif const auto randomInteger = []() -> float { - return static_cast((static_cast(g_random.getRaw()) >> 7 | 1) + 1); + return static_cast((static_cast(Rand.getRaw()) >> 7 | 1) + 1); }; const float inverseRange = 0.000000059604645f; const int majorAxis = static_cast(std::ceil(randomInteger() * (2.0f * inverseRange))); diff --git a/Code/BF2/Game/Objects/Game/PlayerControlObjectHelpers.cpp b/Code/BF2/Game/Objects/Game/PlayerControlObjectHelpers.cpp index 222c4c29b..0e1259a4b 100644 --- a/Code/BF2/Game/Objects/Game/PlayerControlObjectHelpers.cpp +++ b/Code/BF2/Game/Objects/Game/PlayerControlObjectHelpers.cpp @@ -22,6 +22,8 @@ #include "../../../AI/AIInterface/SingletonServer.h" // BFSingletonServer::m_iaiPlayerCourier #include "../../../AI/AIInterface/IAIPlayerCourier.h" // ds:0x8AC35A0 +0x08 - the bot's order #include // the distance +#include // [TEMP] BF2_ENTRY_TRACE +#include // [TEMP] BF2_ENTRY_TRACE #include #if defined(_MSC_VER) @@ -311,6 +313,20 @@ void findPlayerInputObjects(IObject* root, std::list& out, bool stopAt // Returns the closest usable entry point matching the requested template, or null. // Filters by distance, armor, team and line of sight, preferring empty seats over bot occupants. // AI entry uses its own radius and vehicle rules. +#if !defined(_WIN32) +// [TEMP] BF2_ENTRY_TRACE=1: the per-candidate gate results (vehicle-entry diagnosis, no behaviour). +// [RETIRE-WHEN: vehicle-entry-diagnosed] +static bool epTraceArmed() +{ + static const bool armed = std::getenv("BF2_ENTRY_TRACE") != 0; + return armed; +} +#define BF2_EP_TRACE(...) do { if (player && !player->getIsAIPlayer() && epTraceArmed()) { \ + std::fprintf(stderr, "[ENTRY] " __VA_ARGS__); std::fputc('\n', stderr); std::fflush(stderr); } } while (0) +#else +#define BF2_EP_TRACE(...) do { } while (0) +#endif + IPlayerControlObject* BFfindEntryPoint(const Vec3& position, float radius, int team, IPlayer* player, bool useEntryPointRadius, bool acceptAiOccupied, bool requireLineOfSight) @@ -349,6 +365,7 @@ IPlayerControlObject* BFfindEntryPoint(const Vec3& position, float radius, int t for (unsigned int i = 0; i < scratch.size(); ++i) candidates.push_back(scratch[i]); + BF2_EP_TRACE("grid: %u objects within %.1f m", (unsigned int) candidates.size(), (double) radius); for (unsigned int c = 0; c < candidates.size(); ++c) { IObject* const object = candidates[c]; @@ -383,6 +400,9 @@ IPlayerControlObject* BFfindEntryPoint(const Vec3& position, float radius, int t { // the field is read RAW in both ports (0x81A35AE: `fld dword ptr [eax+164h]`); // EntryPointTemplate has no getter symbol of its own. + BF2_EP_TRACE("entry point %p at %.1f/%.1f/%.1f dist %.2f entryRadius %.2f", (void*) object, + (double) to.x, (double) to.y, (double) to.z, (double) distance, + (double) static_cast(L::objectTemplate(object))->m_entryRadius); if (distance > static_cast( L::objectTemplate(object))->m_entryRadius) // +0x164 continue; @@ -403,7 +423,10 @@ IPlayerControlObject* BFfindEntryPoint(const Vec3& position, float radius, int t break; } if (armor && armor->isDestroyed()) // +0x54 + { + BF2_EP_TRACE(" refused: destroyed"); continue; + } // gate 6: whose vehicle is it // the `vehicle ?` test is redundant - it was proved non-null above - but retail compiles @@ -421,7 +444,10 @@ IPlayerControlObject* BFfindEntryPoint(const Vec3& position, float radius, int t } // NO NULL guard ON `owner`, as shipped - see the header block. if (team != owner->getTeam() && owner->getTeam() != 0) // +0x98 twice + { + BF2_EP_TRACE(" refused: team %d != owner team %d", team, owner->getTeam()); continue; + } // gate 7: can the player actually see it if (!isAI && requireLineOfSight) @@ -432,7 +458,10 @@ IPlayerControlObject* BFfindEntryPoint(const Vec3& position, float radius, int t Vec3 rayFrom; rayFrom.x = position.x; rayFrom.y = position.y; rayFrom.z = position.z; if (checkIfRayHitAnyObject(rayFrom, rayTo, root, true)) // ; object-line LOS live + { + BF2_EP_TRACE(" refused: line of sight"); continue; + } } // the seat sweep @@ -446,6 +475,7 @@ IPlayerControlObject* BFfindEntryPoint(const Vec3& position, float radius, int t aiRequestedVehicle != candidate->queryInterface(IID_IObject)) // +0x0C continue; + BF2_EP_TRACE(" seat %d occupied=%d", seat->first, candidate->isOccupied() ? 1 : 0); if (!candidate->isOccupied()) // +0x18 { best = candidate; diff --git a/Code/BF2/Game/Objects/Game/Rotor.cpp b/Code/BF2/Game/Objects/Game/Rotor.cpp index 9b5740cb1..f322e27ad 100644 --- a/Code/BF2/Game/Objects/Game/Rotor.cpp +++ b/Code/BF2/Game/Objects/Game/Rotor.cpp @@ -1,6 +1,7 @@ // Rotor lifecycle and visual rotation. #include "Rotor.h" +#include "../GeometryPartAccess.h" // named geometry operations (non-MSVC) #include @@ -21,10 +22,6 @@ namespace { #if defined(_MSC_VER) #define BF2_ROTOR_GEOM_CALL __thiscall const unsigned int setGeomSlot = 0x6C, getGeomCountSlot = 0x74; -#else -#define BF2_ROTOR_GEOM_CALL -const unsigned int setGeomSlot = 0x70, getGeomCountSlot = 0x78; -#endif template F geometrySlot(void* geometry, unsigned int offset) { return reinterpret_cast((*static_cast(geometry))[offset / 4]); @@ -40,6 +37,11 @@ int getGeometryGeomCount(void* geometry) return geometrySlot(geometry, getGeomCountSlot)(geometry); } #undef BF2_ROTOR_GEOM_CALL +#else +// Non-MSVC: the named geometry_part operations (ELF +0x70 / +0x78). +void setGeometryGeom(void* geometry, int geom) { geometry_part::setSubgeom(geometry, geom); } +int getGeometryGeomCount(void* geometry) { return geometry_part::getSubgeomCount(geometry); } +#endif } // Bundle(template); the vptrs; the block (m_geomState -1, m_spinDownTimer 3.0, diff --git a/Code/BF2/Game/Objects/Game/Soldier.cpp b/Code/BF2/Game/Objects/Game/Soldier.cpp index 44c73e324..e06aaac4a 100644 --- a/Code/BF2/Game/Objects/Game/Soldier.cpp +++ b/Code/BF2/Game/Objects/Game/Soldier.cpp @@ -5,6 +5,7 @@ #include "Soldier.h" +#include "../GeometryPartAccess.h" // named geometry operations (non-MSVC) #include #include @@ -45,6 +46,12 @@ #include "../../../Core/EventManager.h" // eventManager - enter()'s AI event #include "../GameLogicComp/ArmorGLComp.h" // handleMessage reads the armor status #include "../../../AI/AIInterface/AIInstance.h" // the AI singleton, ds:0x8AC37F8 +#if !DEDICATED +#include "SoldierHapticProfile.h" // ledger N2: the control-box profile switch (HapticSettings) +#include "../PlayerControlObjectTemplate.h" // onEnter's unchecked +0x22C template view +#include "../../HapticSettings.h" +#include "../../Main/BF2ClientSeams.h" // g_hapticSettings, ds:0x987394 +#endif #include "../../../AI/AIInterface/BFKnowledge/IAIObject.h" // init()'s lock bracket, the revive's init() #include "../../GameServer/ServerSettings.h" // serverSettings - the man-down time #include "../../GameLogic/ServerGameLogic.h" // the kit handout on revive @@ -335,20 +342,26 @@ anim::IAnimationSystem* animationSystemCreateInstance(void* animationSystemTempl // Forwards field of view to the renderer-owned geometry. // Uses the PE calling convention and slot because the full geometry interface is not declared here. +#if defined(_MSC_VER) void geometrySlot10(void* geometry, float fov) { - typedef void(__fastcall* SetFovFn)(void*, void*, float); + typedef void(__thiscall* SetFovFn)(void*, float); reinterpret_cast( - (*reinterpret_cast(geometry))[0x10 / sizeof(void*)])(geometry, 0, fov); + (*reinterpret_cast(geometry))[0x10 / 4])(geometry, fov); } void geometrySlotD8(void* geometry, bool flag) { - typedef void(__fastcall* Fn)(void*, void*, unsigned int); + typedef void(__thiscall* Fn)(void*, unsigned int); reinterpret_cast( - (*reinterpret_cast(geometry))[0xD4 / sizeof(void*)])( - geometry, 0, flag ? 1u : 0u); + (*reinterpret_cast(geometry))[0xD4 / 4])( + geometry, flag ? 1u : 0u); } +#else +// Non-MSVC: the named geometry_part operations (PE +0x10 / +0xD4). +void geometrySlot10(void* geometry, float fov) { geometry_part::setFov(geometry, fov); } +void geometrySlotD8(void* geometry, bool flag) { geometry_part::setFirstPerson(geometry, flag ? 1u : 0u); } +#endif // Registers animation templates by name; file loading is deferred to the core event. void* animationSystemManagerGet(const std::string& name) @@ -362,20 +375,26 @@ void animationSystemManagerRelease(void* systemTemplate) } // Supplies a borrowed bone-transform palette to the kit geometry through its renderer interface. +#if defined(_MSC_VER) void geometrySetBoneTransforms(void* geometry, const Mat4* transforms, int boneCount) // PE +0x54 { - typedef void(__fastcall* SetBonesFn)(void*, void*, const Mat4*, unsigned int); + typedef void(__thiscall* SetBonesFn)(void*, const Mat4*, unsigned int); reinterpret_cast( - (*reinterpret_cast(geometry))[0x54 / sizeof(void*)])( - geometry, 0, transforms, static_cast(boneCount)); + (*reinterpret_cast(geometry))[0x54 / 4])( + geometry, transforms, static_cast(boneCount)); } void geometrySlot7C(void* geometry, int a) // PE +0x78 { - typedef void*(__fastcall* SetLodFn)(void*, void*, int); + typedef void*(__thiscall* SetLodFn)(void*, int); reinterpret_cast( - (*reinterpret_cast(geometry))[0x78 / sizeof(void*)])(geometry, 0, a); + (*reinterpret_cast(geometry))[0x78 / 4])(geometry, a); } +#else +void geometrySetBoneTransforms(void* geometry, const Mat4* transforms, int boneCount) +{ geometry_part::setBoneTransforms(geometry, transforms, boneCount); } // PE +0x54 +void geometrySlot7C(void* geometry, int a) { geometry_part::setLod(geometry, a); } // PE +0x78 +#endif // AI events are available only when a published AI instance reports a bots game. inline bool aiConnectionIsUp() @@ -383,13 +402,28 @@ inline bool aiConnectionIsUp() return ai::g_aiInstance != 0 && ai::aiInstance()->isBotsGame(); } -// Object +0x34, read raw. It is the handle the AI event carries for this body, and this tree -// has not yet named the base-class field it lives in - so it is a documented offset rather than -// an invented member. [UNRESOLVED] name. -inline int objectAiHandle(const void* object) -{ - return *reinterpret_cast(static_cast(object) + 0x34); -} +// The ECAI 1/2 (entered/exited vehicle) payload this body posts for itself: retail stores five +// dwords - this soldier's AI object (Object +0x34, IObject::m_aiObject), a null second AI object, +// team, id and a zero trailing word. PlayerControlObject's AiEnterNote/AiExitNote give the same +// events this shape; the pointer members keep it whole on native x64. The x86 layout is retail's. +struct SoldierAiSeatPayload +{ + void* aiObject; // +0x00 this soldier's AI object + void* otherAiObject; // +0x04 always null here + int team; // +0x08 + int id; // +0x0C + int trailing; // +0x10 the trailing flag byte, stored as a whole dword +}; +// The ECAI 6/7 (man down / revived) payload: this soldier's AI object, then the player id. +struct SoldierAiPlayerPayload +{ + void* aiObject; // +0x00 Object +0x34 + int playerId; // +0x04 +}; +#if defined(_M_IX86) +static_assert(sizeof(SoldierAiSeatPayload) == 20, "retail five-dword ECAI 1/2 payload"); +static_assert(sizeof(SoldierAiPlayerPayload) == 8, "retail two-dword ECAI 6/7 payload"); +#endif // Retail Object +0x3C, read directly by handleMessage and enter. LayoutAccess names the same // cached armor component without depending on the shipped pointer width. @@ -555,6 +589,14 @@ Soldier::Soldier(const SoldierTemplate* objectTemplate) m_soldierSound = new SoldierSound(this); // operator new(0x38) + its ctor initAnimation(); // [FRONTIER] +#if !DEDICATED + // BF2.exe 0x5AC764..0x5AC90B (ledger N2): the local player's Soldier puts the control box on the + // SOLDIER profile. A fresh Soldier has no occupant, so this compares null with the local player, as + // retail does. Retail also flags the Falcon's control box for a rebuild (archived device, + // Code/Archive/NovintFalcon). + if (getOccupingPlayer() == playerManager->getLocalHumanPlayer()) // +0x168 weak, +0x30 + applyHapticProfile(static_cast(g_hapticSettings), HapticProfileSoldier); +#endif resetInstance(); // [FRONTIER] } @@ -752,13 +794,13 @@ void Soldier::exit() if (aiConnectionIsUp() && getOccupingPlayer()) { - int payload[5]; - payload[0] = objectAiHandle(this); // +0x34 - payload[1] = 0; - payload[2] = getOccupingPlayer()->getTeam(); // +0xE8 - payload[3] = getOccupingPlayer()->getId(); // +0x54 - payload[4] = 0; // the trailing byte - eventManager->postEvent(ECAI, 2, payload, 0.0f); // +0x14 + SoldierAiSeatPayload payload; + payload.aiObject = object_detail::LayoutAccess::aiObject(this); // +0x34 + payload.otherAiObject = 0; + payload.team = getOccupingPlayer()->getTeam(); // +0xE8 + payload.id = getOccupingPlayer()->getId(); // +0x54 + payload.trailing = 0; // the trailing byte + eventManager->postEvent(ECAI, 2, &payload, 0.0f); // +0x14 } if (getOccupingPlayer()) @@ -853,6 +895,13 @@ void Soldier::onExit() m_lookLeftRightAngle = 0.0f; // +0x20C m_byte38D = false; // +0x38D updateWeaponIsActiveState(); +#if !DEDICATED + // BF2.exe 0x5AB5E6..0x5AB83A (ledger N2): back on foot, the local player's control box takes the + // SOLDIER profile. Retail also zeroes the Falcon's force effects and flags its control box for a + // rebuild (archived device, Code/Archive/NovintFalcon). + if (getOccupingPlayer() && getOccupingPlayer() == playerManager->getLocalHumanPlayer()) // +0x10 twice + applyHapticProfile(static_cast(g_hapticSettings), HapticProfileSoldier); +#endif } // Stops tinnitus for the local human occupant and posts the updated tinnitus setup event. @@ -3052,13 +3101,13 @@ bool Soldier::enter(IPlayer* player) // 7. tell the AI, if there is one listening. if (aiConnectionIsUp() && getOccupingPlayer()) { - int payload[5]; - payload[0] = objectAiHandle(this); - payload[1] = 0; - payload[2] = getOccupingPlayer()->getTeam(); - payload[3] = getOccupingPlayer()->getId(); - payload[4] = 0; // a trailing byte in the ELF - eventManager->postEvent(static_cast(3), 1, payload, 0.0f); + SoldierAiSeatPayload payload; + payload.aiObject = object_detail::LayoutAccess::aiObject(this); // +0x34 + payload.otherAiObject = 0; + payload.team = getOccupingPlayer()->getTeam(); + payload.id = getOccupingPlayer()->getId(); + payload.trailing = 0; // a trailing byte in the ELF + eventManager->postEvent(static_cast(3), 1, &payload, 0.0f); } // 8. reset the per-body input latches. Backwards, 1 then 0 - dice's. @@ -3129,10 +3178,10 @@ void Soldier::handleMessage(TemplateMessage message, IPlayer* player, bool remot + WorldPref::getTickCount())); if (aiConnectionIsUp()) { - int payload[2]; - payload[0] = objectAiHandle(this); - payload[1] = getOccupingPlayer()->getId(); - eventManager->postEvent(static_cast(3), 6, payload, 0.0f); + SoldierAiPlayerPayload payload; + payload.aiObject = object_detail::LayoutAccess::aiObject(this); // +0x34 + payload.playerId = getOccupingPlayer()->getId(); + eventManager->postEvent(static_cast(3), 6, &payload, 0.0f); } } @@ -3175,10 +3224,10 @@ void Soldier::handleMessage(TemplateMessage message, IPlayer* player, bool remot if (getOccupingPlayer() && aiConnectionIsUp()) { - int payload[2]; - payload[0] = objectAiHandle(this); - payload[1] = getOccupingPlayer()->getId(); - eventManager->postEvent(static_cast(3), 7, payload, 0.0f); + SoldierAiPlayerPayload payload; + payload.aiObject = object_detail::LayoutAccess::aiObject(this); // +0x34 + payload.playerId = getOccupingPlayer()->getId(); + eventManager->postEvent(static_cast(3), 7, &payload, 0.0f); } } break; @@ -3833,10 +3882,27 @@ void Soldier::handlePlayerInput(IPlayer* player, const io::PlayerInput& input, } const float yawDelta = getYawRecoil() + lookX; - const float pitchDelta = getPitchRecoil() + lookY; + const float pitchRecoil = getPitchRecoil(); + const float pitchDelta = pitchRecoil + lookY; + // BF2.exe 0x5AE335..0x5AE72B (ledger N2 17b) feeds the Falcon's "Recoil" force here; it needs a + // device (archived, Code/Archive/NovintFalcon). m_pitchDeltaThisTick = pitchDelta; // +0x298 m_yawDeltaThisTick = yawDelta; // +0x294 m_lookUpDownAngle += pitchDelta; +#if !defined(_WIN32) + { + // [TEMP] BF2_LOOK_TRACE=1: per-call pitch inputs (sustained-fire view climb diagnosis). + // [RETIRE-WHEN: view-climb-diagnosed] + static const bool lookTrace = std::getenv("BF2_LOOK_TRACE") != 0; + if (lookTrace && getOccupingPlayer() && (pitchDelta != 0.0f || yawDelta != 0.0f)) + { + std::fprintf(stderr, "[LOOK] tick=%d flags=%u lookY=%.4f recoilP=%.4f lookX=%.4f recoilY=%.4f -> upDown=%.3f camPitch=%.3f\n", + (int) WorldPref::getTickCount(), flags, (double) lookY, (double) (pitchDelta - lookY), + (double) lookX, (double) (yawDelta - lookX), (double) m_lookUpDownAngle, (double) m_cameraPitch); + std::fflush(stderr); + } + } +#endif // 11. the yaw pipeline // the vehicle's own yaw limits, if he is riding one @@ -4038,6 +4104,8 @@ void Soldier::handlePlayerInput(IPlayer* player, const io::PlayerInput& input, rotation.z = 0.0f; // SoldierPhysicsNode consumes only Y; typed dispatch preserves each platform's vtable ABI. node->setRotationalSpeed(rotation); + // BF2.exe 0x5AECE8..0x5AF3F6 (ledger N2 17b) feeds the Falcon's "CraftPhysics" forces here; they + // need a device (archived, Code/Archive/NovintFalcon). // pose input, but only once the go-prone timer has expired bool proneReady = false; @@ -4188,6 +4256,21 @@ void Soldier::onEnter(IObject* entering) if ((*mods)[i].first.compare(rootName) == 0) rootPco->addVehicleMod((*mods)[i].second); // unguarded, +0xDC } +#if !DEDICATED + // BF2.exe 0x5ACC99..0x5ADE14 (ledger N2): for the local player, the control box takes the + // profile of what was entered. Both templates are taken as player-control templates unchecked + // (+0x22C), as compiled. Retail then flags the Falcon's control box for a rebuild and zeroes + // its force effects (archived device, Code/Archive/NovintFalcon). + if (getOccupingPlayer() && getOccupingPlayer() == playerManager->getLocalHumanPlayer()) + { + IPlayerControlObjectTemplate* const entered = static_cast( + const_cast(L::objectTemplate(entering))); + IPlayerControlObjectTemplate* const rootTemplate = static_cast( + const_cast(L::objectTemplate(root))); + applyHapticProfile(static_cast(g_hapticSettings), + hapticProfileForEntered(entered, rootTemplate)); + } +#endif } // 5. diff --git a/Code/BF2/Game/Objects/Game/SoldierAnimation.cpp b/Code/BF2/Game/Objects/Game/SoldierAnimation.cpp index 674deef3f..c2081bb11 100644 --- a/Code/BF2/Game/Objects/Game/SoldierAnimation.cpp +++ b/Code/BF2/Game/Objects/Game/SoldierAnimation.cpp @@ -45,6 +45,7 @@ #include "../RotationalBundleTemplate.h" #include "RotationalBundle.h" // getCurrentRotation #include "Kit.h" // reviveAnimations' geometry gate +#include "../../../Platform/MsvcRand.h" // [CHOSEN, not recovered] the client CRT's rand (MSVCR71) namespace dice { namespace hfe { @@ -59,38 +60,37 @@ typedef object_detail::LayoutAccess L; // the raw Object offsets, as Soldier // reviveAnimations tells the carried kit's geometry that the soldier has returned to the prone // pose. geom::IGeometry is still unrecovered, but this one seam is bounded in both shipped x86 // images: handleMessage is PE/MSVC +0x60 and ELF/Itanium +0x64 (the destructor-pair shift). +// The slot follows the compiler's destructor ABI, so native MSVC x64 takes the PE arm too. void geometryHandleMessage(void* geometry, TemplateMessage message, void* payload) { -#if defined(_MSC_VER) && defined(_M_IX86) +#if defined(_MSC_VER) typedef void (__thiscall *Method)(void*, TemplateMessage, void*); - const unsigned int slot = 0x60 / sizeof(void*); -#else - typedef void (*Method)(void*, TemplateMessage, void*); - const unsigned int slot = 0x64 / sizeof(void*); -#endif + const unsigned int slot = 0x60 / 4; void** const vtable = *reinterpret_cast(geometry); reinterpret_cast(vtable[slot])(geometry, message, payload); +#else + // RendDX9 SkinnedMesh +0x60 (0x101A67E0) is (int part, byte flag): `cmp byte [ebp+0xC],0`, + // then +0x17C = part or -1. The second dword's low byte is the flag (ELF +0x64). + geometry_part::setExcludedPart(geometry, static_cast(message), + (reinterpret_cast(payload) & 0xFFu) != 0); +#endif } // Renderer dispatch for field of view, geometry selection and bone palettes. -// Explicit PE/ELF slot constants account for their differing destructor layouts. -#if defined(_MSC_VER) && defined(_M_IX86) +// Explicit PE/ELF slot constants account for their differing destructor layouts; MSVC x64 keeps +// the MSVC (PE) table order. +#if defined(_MSC_VER) #define BF2_SOLDIER_GEOM_CALL __thiscall const unsigned int kGeometrySetFovSlot = 0x10; const unsigned int kGeometrySetGeomIndexSlot = 0x6C; const unsigned int kGeometrySetBoneTransformsSlot = 0x54; const unsigned int kGeometryGatherUsedBonesSlot = 0x58; -#else -#define BF2_SOLDIER_GEOM_CALL -const unsigned int kGeometrySetFovSlot = 0x10; -const unsigned int kGeometrySetGeomIndexSlot = 0x70; -const unsigned int kGeometrySetBoneTransformsSlot = 0x58; -const unsigned int kGeometryGatherUsedBonesSlot = 0x5C; #endif +#if defined(_MSC_VER) template F geometrySlot(void* geometry, unsigned int offset) { - return reinterpret_cast((*static_cast(geometry))[offset / sizeof(void*)]); + return reinterpret_cast((*static_cast(geometry))[offset / 4]); } void geometrySetFov(void* geometry, float fov) @@ -119,6 +119,14 @@ void geometryGatherUsedBones(void* geometry, std::vector* out) geometrySlot(geometry, kGeometryGatherUsedBonesSlot)(geometry, out); } #undef BF2_SOLDIER_GEOM_CALL +#else +// Non-MSVC: the named geometry_part operations (ELF +0x10 / +0x70 / +0x58 / +0x5C). +void geometrySetFov(void* geometry, float fov) { geometry_part::setFov(geometry, fov); } +void geometrySetGeomIndex(void* geometry, int geom) { geometry_part::setSubgeom(geometry, geom); } +void geometrySetBoneTransforms(void* geometry, const Mat4* transforms, unsigned int boneCount) +{ geometry_part::setBoneTransforms(geometry, transforms, static_cast(boneCount)); } +void geometryGatherUsedBones(void* geometry, std::vector* out) { geometry_part::gatherUsedBones(geometry, out); } +#endif // Soldier animation and physics console tuning values. float* const rd_expForceMod = Vars::getFloat("rd_expForceMod", 1.0f); // applyExplosionForce @@ -900,12 +908,12 @@ void Soldier::updateThirdPersonAnimations(float dt, bool updateGeometry) } else { - const float roll = static_cast(rand() % 16) * 0.0625f; + const float roll = static_cast(bf2crt::rand() % 16) * 0.0625f; m_soldierLookIdleTime = roll * *soldier_lookIdleTime; if (roll >= 0.5f) { m_headPosition.z = *soldier_lookIdleAngle; - if ((rand() & 1) != 0) + if ((bf2crt::rand() & 1) != 0) m_headPosition.z = -m_headPosition.z; } else @@ -1304,7 +1312,8 @@ void Soldier::enableRagDoll() > sqrtf(velocity.x * velocity.x + velocity.y * velocity.y + velocity.z * velocity.z) * 1.5f) velocity = local; } - if (WorldPref::getTickCount() < m_hitByVehicleSpeedTicks) + // ELF 0x081B67CF: an unsigned comparison (cmp, jae). + if (static_cast(WorldPref::getTickCount()) < m_hitByVehicleSpeedTicks) { velocity = m_hitByVehicleSpeed; m_hitByVehicleSpeedTicks = 0; diff --git a/Code/BF2/Game/Objects/Game/SoldierHapticProfile.cpp b/Code/BF2/Game/Objects/Game/SoldierHapticProfile.cpp new file mode 100644 index 000000000..e669572da --- /dev/null +++ b/Code/BF2/Game/Objects/Game/SoldierHapticProfile.cpp @@ -0,0 +1,77 @@ +// The control-box profile switch (ledger N2, 17a). See SoldierHapticProfile.h. +#include "SoldierHapticProfile.h" +#if !DEDICATED +#include "../../HapticSettings.h" +#include "../IPlayerControlObjectTemplate.h" + +namespace dice { namespace hfe { namespace world { + +void applyHapticProfile(IHapticSettings* s, HapticProfile profile) +{ + switch (profile) { + case HapticProfileAir: // 0x5AD363 / 0x5AD87A: +0x64 +0x6C +0xD4 +0xDC +0xE4 + s->setControlBoxLength(s->getControlBoxLengthAIR().x, s->getControlBoxLengthAIR().y, s->getControlBoxLengthAIR().z); + s->setControlBoxStiffness(s->getControlBoxStiffnessAIR().x, s->getControlBoxStiffnessAIR().y, s->getControlBoxStiffnessAIR().z); + s->setAimSensitivity(s->getAimSensitivityAIR().x, s->getAimSensitivityAIR().y, s->getAimSensitivityAIR().z); + s->setAimSensitivityLength(s->getAimSensitivityLengthAIR().x, s->getAimSensitivityLengthAIR().y, s->getAimSensitivityLengthAIR().z); + s->setTurnSensitivity(s->getTurnSensitivityAIR().x, s->getTurnSensitivityAIR().y, s->getTurnSensitivityAIR().z); + break; + case HapticProfileHeli: // 0x5AD1C9 / 0x5ADA1A: +0x74 +0x7C +0xEC +0xF4 +0xFC + s->setControlBoxLength(s->getControlBoxLengthHELI().x, s->getControlBoxLengthHELI().y, s->getControlBoxLengthHELI().z); + s->setControlBoxStiffness(s->getControlBoxStiffnessHELI().x, s->getControlBoxStiffnessHELI().y, s->getControlBoxStiffnessHELI().z); + s->setAimSensitivity(s->getAimSensitivityHELI().x, s->getAimSensitivityHELI().y, s->getAimSensitivityHELI().z); + s->setAimSensitivityLength(s->getAimSensitivityLengthHELI().x, s->getAimSensitivityLengthHELI().y, s->getAimSensitivityLengthHELI().z); + s->setTurnSensitivity(s->getTurnSensitivityHELI().x, s->getTurnSensitivityHELI().y, s->getTurnSensitivityHELI().z); + break; + case HapticProfileLand: // 0x5AD51F: +0x84 +0x8C +0x104 +0x10C +0x114 + s->setControlBoxLength(s->getControlBoxLengthLAND().x, s->getControlBoxLengthLAND().y, s->getControlBoxLengthLAND().z); + s->setControlBoxStiffness(s->getControlBoxStiffnessLAND().x, s->getControlBoxStiffnessLAND().y, s->getControlBoxStiffnessLAND().z); + s->setAimSensitivity(s->getAimSensitivityLAND().x, s->getAimSensitivityLAND().y, s->getAimSensitivityLAND().z); + s->setAimSensitivityLength(s->getAimSensitivityLengthLAND().x, s->getAimSensitivityLengthLAND().y, s->getAimSensitivityLengthLAND().z); + s->setTurnSensitivity(s->getTurnSensitivityLAND().x, s->getTurnSensitivityLAND().y, s->getTurnSensitivityLAND().z); + break; + case HapticProfileSea: // 0x5AD6C8: +0x94 +0x9C +0x11C +0x124 +0x12C + s->setControlBoxLength(s->getControlBoxLengthSEA().x, s->getControlBoxLengthSEA().y, s->getControlBoxLengthSEA().z); + s->setControlBoxStiffness(s->getControlBoxStiffnessSEA().x, s->getControlBoxStiffnessSEA().y, s->getControlBoxStiffnessSEA().z); + s->setAimSensitivity(s->getAimSensitivitySEA().x, s->getAimSensitivitySEA().y, s->getAimSensitivitySEA().z); + s->setAimSensitivityLength(s->getAimSensitivityLengthSEA().x, s->getAimSensitivityLengthSEA().y, s->getAimSensitivityLengthSEA().z); + s->setTurnSensitivity(s->getTurnSensitivitySEA().x, s->getTurnSensitivitySEA().y, s->getTurnSensitivitySEA().z); + break; + case HapticProfileSoldier: // +0x54 +0x5C +0xBC +0xC4 +0xCC + default: + s->setControlBoxLength(s->getControlBoxLengthSOLDIER().x, s->getControlBoxLengthSOLDIER().y, s->getControlBoxLengthSOLDIER().z); + s->setControlBoxStiffness(s->getControlBoxStiffnessSOLDIER().x, s->getControlBoxStiffnessSOLDIER().y, s->getControlBoxStiffnessSOLDIER().z); + s->setAimSensitivity(s->getAimSensitivitySOLDIER().x, s->getAimSensitivitySOLDIER().y, s->getAimSensitivitySOLDIER().z); + s->setAimSensitivityLength(s->getAimSensitivityLengthSOLDIER().x, s->getAimSensitivityLengthSOLDIER().y, s->getAimSensitivityLengthSOLDIER().z); + s->setTurnSensitivity(s->getTurnSensitivitySOLDIER().x, s->getTurnSensitivitySOLDIER().y, s->getTurnSensitivitySOLDIER().z); + break; + } +} + +HapticProfile hapticProfileForEntered(IPlayerControlObjectTemplate* entered, IPlayerControlObjectTemplate* root) +{ + switch (entered->getVehicleType()) { // +0x34; jump tables 0x5ADE64 / 0x5ADE70 + case 8: case 9: case 15: case 19: case 20: case 24: case 25: + return HapticProfileSoldier; + case 26: + switch (entered->getVehicleCategory()) { // +0x24 + case 2: + return HapticProfileAir; + case 3: + return entered->getControlsCategory() ? HapticProfileHeli : HapticProfileSoldier; // +0x2C + default: + return HapticProfileSoldier; + } + default: + switch (root->getVehicleCategory()) { // +0x24; jump table 0x5ADE84 + case 0: return HapticProfileLand; + case 1: return HapticProfileSea; + case 2: return HapticProfileAir; + case 3: return HapticProfileHeli; + default: return HapticProfileSoldier; + } + } +} + +} } } +#endif diff --git a/Code/BF2/Game/Objects/Game/SoldierHapticProfile.h b/Code/BF2/Game/Objects/Game/SoldierHapticProfile.h new file mode 100644 index 000000000..bf4300498 --- /dev/null +++ b/Code/BF2/Game/Objects/Game/SoldierHapticProfile.h @@ -0,0 +1,40 @@ +// The control-box profile switch the Soldier makes for the local player (ledger N2, 17a): it writes +// HapticSettings' active control-box values from the profile of what the player is in. +// [CHOSEN, not recovered] file and names: retail inlines all of this in Soldier::Soldier +// (0x5AC784..0x5AC90B), Soldier::onEnter (0x5ACCC6..0x5ADE14) and Soldier::onExit +// (0x5AB611..0x5AB83A). It lives here so the fake-settings check can drive it without a Soldier. +// The Falcon force inputs that were declared here are archived (Code/Archive/NovintFalcon). +#ifndef GAME_OBJECTS_GAME_SOLDIERHAPTICPROFILE_H +#define GAME_OBJECTS_GAME_SOLDIERHAPTICPROFILE_H +#include "../../../Core/BuildConfig.h" +#if !DEDICATED +namespace dice { namespace hfe { +class IHapticSettings; +namespace world { +class IPlayerControlObjectTemplate; + +// HapticSettings' per-vehicle profiles, in their interface order. +enum HapticProfile { + HapticProfileSoldier, + HapticProfileAir, + HapticProfileHeli, + HapticProfileLand, + HapticProfileSea +}; + +// The five copies every site makes: the active control-box length and stiffness, aim sensitivity, +// aim sensitivity length and turn sensitivity, each from the profile's own value (HapticSettings +0x48, +// +0x50, +0xA8, +0xB0, +0xB8 set from the profile's getters). Each getter is called once per component, +// as retail does. +void applyHapticProfile(IHapticSettings* settings, HapticProfile profile); + +// Soldier::onEnter's choice (0x5ACCC6..0x5AD51F): by the entered object's vehicle type; type 26 by +// its own vehicle category (2 AIR, 3 HELI while its controls category is non-zero, else SOLDIER); +// types 8, 9, 15, 19, 20, 24 and 25 SOLDIER; every other type by the root object's vehicle category +// (0 LAND, 1 SEA, 2 AIR, 3 HELI, other SOLDIER). +HapticProfile hapticProfileForEntered(IPlayerControlObjectTemplate* entered, + IPlayerControlObjectTemplate* root); + +} } } +#endif +#endif diff --git a/Code/BF2/Game/Objects/Game/SupplyDepot.cpp b/Code/BF2/Game/Objects/Game/SupplyDepot.cpp index 886815483..57ec5435c 100644 --- a/Code/BF2/Game/Objects/Game/SupplyDepot.cpp +++ b/Code/BF2/Game/Objects/Game/SupplyDepot.cpp @@ -16,6 +16,7 @@ #include #include #include +#include "../../../Platform/MsvcRand.h" // [CHOSEN, not recovered] the client CRT's rand (MSVCR71) namespace dice { namespace hfe { namespace world { namespace { @@ -123,9 +124,9 @@ SupplyDepot::SupplyDepot(const SupplyDepotTemplate* objectTemplate) { #if defined(_MSC_VER) // [PLATFORM] PE 0x573A96 multiplies by float bits 0x3D088889; ELF divides by 30. - m_lastUpdate = static_cast(std::rand() % 30) * 0.033333335f; + m_lastUpdate = static_cast(bf2crt::rand() % 30) * 0.033333335f; #else - m_lastUpdate = static_cast(std::rand() % 30) / 30.0f; + m_lastUpdate = static_cast(bf2crt::rand() % 30) / 30.0f; #endif Object::updateFlags(0x800, 2); } @@ -367,9 +368,9 @@ void SupplyDepot::reset() m_hasRepair = !m_repair.empty(); #if defined(_MSC_VER) // uses the same multiply as its constructor; ELF uses division. - m_lastUpdate = static_cast(std::rand() % 30) * 0.033333335f; + m_lastUpdate = static_cast(bf2crt::rand() % 30) * 0.033333335f; #else - m_lastUpdate = static_cast(std::rand() % 30) / 30.0f; + m_lastUpdate = static_cast(bf2crt::rand() % 30) / 30.0f; #endif } bool SupplyDepot::getWorkOnVehicles() { return m_depotTemplate->m_workOnVehicles; } diff --git a/Code/BF2/Game/Objects/Game/Triggerable.h b/Code/BF2/Game/Objects/Game/Triggerable.h index c5351458a..3498c1414 100644 --- a/Code/BF2/Game/Objects/Game/Triggerable.h +++ b/Code/BF2/Game/Objects/Game/Triggerable.h @@ -13,6 +13,7 @@ namespace dice { namespace hfe { class ISound; class TriggerableTargetNetworkable; +namespace ai { class BAPConTriggerableActive; class BBPTriggerable; } namespace world { class TriggerableTemplate; class TriggerableTargetTemplate; @@ -51,6 +52,10 @@ class Triggerable : public Bundle, public ISoundNode private: friend class TriggerableManager; // Retail reads the cached template and toggles +16C directly. friend class TriggerableTarget; + // [INFERRED] friendship: the AI condition reads +16C inline (libaidll ELF 0x1EAF50). + friend class ai::BAPConTriggerableActive; + // [INFERRED] friendship: the pattern reads the cached template inline (libaidll ELF 0x2A6F56). + friend class ai::BBPTriggerable; int m_refCount; // +140 const TriggerableTemplate* m_template; // +144 int m_id; // +148 diff --git a/Code/BF2/Game/Objects/GameLogicComp/ArmorGLComp.cpp b/Code/BF2/Game/Objects/GameLogicComp/ArmorGLComp.cpp index 0e165a96a..1f9714dfd 100644 --- a/Code/BF2/Game/Objects/GameLogicComp/ArmorGLComp.cpp +++ b/Code/BF2/Game/Objects/GameLogicComp/ArmorGLComp.cpp @@ -26,7 +26,7 @@ #include "../../IGame.h" // game->destroyObject #include "../../IGameLogic.h" // gameLogic - isServer / getGameStatus / giveDamage #include "../../Common/GameEvent.h" // revive: ECGameLogic 14 replication -#include "../Fx/ParticleTemplate.h" // g_random - UpdateInWaterStatus' jitter +#include "../Fx/ParticleTemplate.h" // Rand - UpdateInWaterStatus' jitter #include "../IObject.h" #include "../IStrategicObjectComp.h" // ResetStrategicObject's component #include "../StrategicObjectComp.h" // ... and the holder it looks up @@ -85,21 +85,19 @@ typedef void (__thiscall *GeometrySetIntFn)(void*, int); const unsigned int kGeometrySetGeomIndexSlot = 0x6C; const unsigned int kGeometryGetGeomIndexSlot = 0x70; const unsigned int kGeometryGetGeomCountSlot = 0x74; -#else -typedef int (*GeometryGetIntFn)(void*); -typedef void (*GeometrySetIntFn)(void*, int); -const unsigned int kGeometrySetGeomIndexSlot = 0x70; -const unsigned int kGeometryGetGeomIndexSlot = 0x74; -const unsigned int kGeometryGetGeomCountSlot = 0x78; #endif int geometryGetGeomCount(void* geometry) { if (!geometry) return 0; +#ifdef _MSC_VER void** const vtable = *reinterpret_cast(geometry); return reinterpret_cast( vtable[kGeometryGetGeomCountSlot / 4])(geometry); +#else + return geometry_part::getSubgeomCount(geometry); // ELF +0x78 +#endif } int geometryGetPartCount(void* geometry) @@ -113,9 +111,6 @@ int geometryGetPartCount(void* geometry) #ifdef _MSC_VER const unsigned int kGeometryShowDamageSlot = 0xC0; typedef void (__thiscall *GeometryShowDamageFn)(void*, int, int); -#else -const unsigned int kGeometryShowDamageSlot = 0xC4; -typedef void (*GeometryShowDamageFn)(void*, int, int); #endif void geometryInitDamageState(void* geometry) @@ -133,9 +128,13 @@ void geometryShowDamage(void* geometry, int a, int b) if (!geometry) return; +#ifdef _MSC_VER void** const vtable = *reinterpret_cast(geometry); reinterpret_cast( vtable[kGeometryShowDamageSlot / 4])(geometry, a, b); +#else + geometry_part::updateFlags(geometry, static_cast(a), static_cast(b)); // ELF +0xC4 +#endif } void geometrySetPartTransform(void* geometry, const Mat4* transform, int part) @@ -571,7 +570,7 @@ void ArmorGLComp::UpdateInWaterStatus() if (worldTime > *g_armorWaterSafetyCheckTime + m_lastWaterCheckTime) { timerFired = true; - const unsigned int x = g_random.getRaw(); // two Lehmer steps, inlined in the ELF + const unsigned int x = Rand.getRaw(); // two Lehmer steps, inlined in the ELF const float roll = static_cast(((static_cast(x) >> 7) | 1) + 1) * 5.9604645e-08f; m_lastWaterCheckTime = worldTime - (roll * 0.30000001f + 0.0f); } diff --git a/Code/BF2/Game/Objects/GeometryPartAccess.h b/Code/BF2/Game/Objects/GeometryPartAccess.h index b886a3eff..94f0c51fb 100644 --- a/Code/BF2/Game/Objects/GeometryPartAccess.h +++ b/Code/BF2/Game/Objects/GeometryPartAccess.h @@ -8,8 +8,11 @@ #include "../../Math/Mat4.h" #include #include +#if defined(BF2_STATIC_PLUGINS) && !defined(_MSC_VER) +// [CHOSEN, not recovered] Static native geometry providers retain explicit PE tables. +#include "../../Geom/NativeGeometrySlots.h" +#endif #if defined(_MSC_VER) && defined(_M_IX86) -#include "../../../RendDX9Abi/Vc71String.h" #define BF2_GEOMETRY_PART_CALL __thiscall #else #define BF2_GEOMETRY_PART_CALL @@ -21,6 +24,9 @@ template inline Function slot(void* geometry, unsigned int pe, u { #if defined(_MSC_VER) const unsigned int offset = pe; +#elif defined(BF2_STATIC_PLUGINS) + // [CHOSEN, not recovered] This is a function table, not an ELF class vtable. + const unsigned int offset = 4 * geom::native_geometry::slot(pe, elf); #else const unsigned int offset = elf; #endif @@ -67,19 +73,81 @@ inline void* getTemplate(void* geometry) return slot(geometry, 0x38, 0x3C)(geometry); } +// Named geometry-instance operations used by game code. Native static builds select the named +// ordinal of the renderer's explicit PE-order tables (Geom/NativeGeometrySlots.h, checked by +// tools/macos/vtable_audit.py against BundledMesh/StaticMesh/SkinnedMesh/MeshParticleMesh); +// MSVC keeps the PE byte offset and other non-MSVC builds the ELF one. Callers never index a +// geometry table themselves (the gate's raw-slot scan rejects new sites). +#if defined(BF2_STATIC_PLUGINS) && !defined(_MSC_VER) +#define BF2_GEOMETRY_OP(pe, elf, name) slot(geometry, 4 * geom::native_geometry::name, 4 * geom::native_geometry::name) +#else +#define BF2_GEOMETRY_OP(pe, elf, name) slot(geometry, pe, elf) +#endif +inline float getBoundingRadius(void* geometry) +{ typedef float (BF2_GEOMETRY_PART_CALL* Function)(void*); return BF2_GEOMETRY_OP(0x44, 0x48, GetBoundingRadius)(geometry); } +inline void setFov(void* geometry, float fov) +{ typedef void (BF2_GEOMETRY_PART_CALL* Function)(void*, float); BF2_GEOMETRY_OP(0x10, 0x10, SetFov)(geometry, fov); } +inline float getFov(void* geometry) +{ typedef float (BF2_GEOMETRY_PART_CALL* Function)(void*); return BF2_GEOMETRY_OP(0x14, 0x14, GetFov)(geometry); } +inline void setGeometryTransform(void* geometry, const Mat4* transform) +{ typedef void (BF2_GEOMETRY_PART_CALL* Function)(void*, const Mat4*); BF2_GEOMETRY_OP(0x50, 0x50, SetGeometryTransform)(geometry, transform); } +inline void setBoneTransforms(void* geometry, const Mat4* transforms, int count) +{ typedef void (BF2_GEOMETRY_PART_CALL* Function)(void*, const Mat4*, int); BF2_GEOMETRY_OP(0x54, 0x58, SetBoneTransforms)(geometry, transforms, count); } +// SkinnedMesh +0x58: appends the used bone indices to the engine's int vector (opaque here). +inline void gatherUsedBones(void* geometry, void* intVector) +{ typedef void (BF2_GEOMETRY_PART_CALL* Function)(void*, void*); BF2_GEOMETRY_OP(0x58, 0x5C, GatherUsedBones)(geometry, intVector); } +inline void setExcludedPart(void* geometry, int part, bool enable) +{ typedef void (BF2_GEOMETRY_PART_CALL* Function)(void*, int, bool); BF2_GEOMETRY_OP(0x60, 0x64, SetExcludedPart)(geometry, part, enable); } +inline void setSubgeom(void* geometry, int index) +{ typedef void (BF2_GEOMETRY_PART_CALL* Function)(void*, int); BF2_GEOMETRY_OP(0x6C, 0x70, SetSubgeom)(geometry, index); } +inline int getSubgeom(void* geometry) +{ typedef int (BF2_GEOMETRY_PART_CALL* Function)(void*); return BF2_GEOMETRY_OP(0x70, 0x74, GetSubgeom)(geometry); } +inline int getSubgeomCount(void* geometry) +{ typedef int (BF2_GEOMETRY_PART_CALL* Function)(void*); return BF2_GEOMETRY_OP(0x74, 0x78, GetSubgeomCount)(geometry); } +inline void setUvTranslation(void* geometry, int index, float x, float y) +{ typedef void (BF2_GEOMETRY_PART_CALL* Function)(void*, int, float, float); BF2_GEOMETRY_OP(0x90, 0x94, SetUvTranslation)(geometry, index, x, y); } +inline void setUvTransformation(void* geometry, int index, const Mat4* transform) +{ typedef void (BF2_GEOMETRY_PART_CALL* Function)(void*, int, const Mat4*); BF2_GEOMETRY_OP(0x98, 0x9C, SetUvTransformation)(geometry, index, transform); } +inline void* setOwnerObject(void* geometry, void* object) +{ typedef void* (BF2_GEOMETRY_PART_CALL* Function)(void*, void*); return BF2_GEOMETRY_OP(0x9C, 0x9C, SetOwnerObject)(geometry, object); } +inline void updateFlags(void* geometry, unsigned int set, unsigned int clear) +{ typedef void (BF2_GEOMETRY_PART_CALL* Function)(void*, unsigned int, unsigned int); BF2_GEOMETRY_OP(0xC0, 0xC4, UpdateFlags)(geometry, set, clear); } +inline void* setNextGeometry(void* geometry, void* next) +{ typedef void* (BF2_GEOMETRY_PART_CALL* Function)(void*, void*); return BF2_GEOMETRY_OP(0xC8, 0xCC, SetNextGeometry)(geometry, next); } +inline void* getNextGeometry(void* geometry) +{ typedef void* (BF2_GEOMETRY_PART_CALL* Function)(void*); return BF2_GEOMETRY_OP(0xCC, 0xD0, GetNextGeometry)(geometry); } +inline void setFirstPerson(void* geometry, unsigned int value) +{ typedef void (BF2_GEOMETRY_PART_CALL* Function)(void*, unsigned int); BF2_GEOMETRY_OP(0xD4, 0xD8, SetFirstPerson)(geometry, value); } +inline void setLightSourceMask(void* geometry, int mask) +{ typedef void (BF2_GEOMETRY_PART_CALL* Function)(void*, int); BF2_GEOMETRY_OP(0xE0, 0xE4, SetLightSourceMask)(geometry, mask); } +inline int getLightSourceMask(void* geometry) +{ typedef int (BF2_GEOMETRY_PART_CALL* Function)(void*); return BF2_GEOMETRY_OP(0xE4, 0xE8, GetLightSourceMask)(geometry); } +#undef BF2_GEOMETRY_OP + +#if defined(_MSC_VER) || defined(BF2_STATIC_PLUGINS) +// Renderer-internal reads (DecalShadowManager::addShadow, PE 0x10127260). No ELF image calls these +// slots, so no ELF offset is attested and they exist only where the PE table order applies. +#if defined(BF2_STATIC_PLUGINS) && !defined(_MSC_VER) +#define BF2_RENDERER_GEOMETRY_OP(pe, name) slot(geometry, 4 * geom::native_geometry::name, 4 * geom::native_geometry::name) +#else +#define BF2_RENDERER_GEOMETRY_OP(pe, name) slot(geometry, pe, pe) +#endif +// +0x28: the shadow record the geometry draws into (StaticMesh +0x34C, SkinnedMesh +0x33C, +// BundledMesh +0x2B4). +inline void* getShadowRecord(void* geometry) +{ typedef void* (BF2_GEOMETRY_PART_CALL* Function)(void*); return BF2_RENDERER_GEOMETRY_OP(0x28, GetShadowRecord)(geometry); } +// +0x48: the stored world transform, or the shared identity when none was set. +inline const Mat4* getGeometryTransform(void* geometry) +{ typedef const Mat4* (BF2_GEOMETRY_PART_CALL* Function)(void*); return BF2_RENDERER_GEOMETRY_OP(0x48, GetGeometryTransform)(geometry); } +#undef BF2_RENDERER_GEOMETRY_OP +#endif + inline bool templateNameEquals(void* objectTemplate, const char* name) { -#if defined(_MSC_VER) && defined(_M_IX86) - // MeshTemplate::getName returns vc71::string even in the native renderer. Read its - // borrowed view without creating/destroying a string or importing the renderer allocator. - typedef const vc71::string& (BF2_GEOMETRY_PART_CALL* Function)(void*); - const vc71::string& actual = slot(objectTemplate, 0x18, 0x18)(objectTemplate); - const std::size_t length = std::strlen(name); - return actual.size() == length && std::memcmp(actual.c_str(), name, length) == 0; -#else - typedef const std::string& (*Function)(void*); + // MeshTemplate::getName (+0x18) returns the renderer's std::string: the client and its + // plugins share one STL (issue #7). + typedef const std::string& (BF2_GEOMETRY_PART_CALL* Function)(void*); return slot(objectTemplate, 0x18, 0x18)(objectTemplate) == name; -#endif } } } } } diff --git a/Code/BF2/Game/Objects/HelpHudCompTemplate.h b/Code/BF2/Game/Objects/HelpHudCompTemplate.h index bc17a87c3..b70704b4c 100644 --- a/Code/BF2/Game/Objects/HelpHudCompTemplate.h +++ b/Code/BF2/Game/Objects/HelpHudCompTemplate.h @@ -14,6 +14,7 @@ namespace dice { namespace hfe { +struct PlayerVOHelp; namespace world { // Exact field order. The close-to group is three strings followed by three sounds; @@ -142,6 +143,7 @@ class HelpHudCompTemplate : public IHelpHudCompTemplate, public io::IConsoleSave private: friend class HelpHudComp; + friend struct ::dice::hfe::PlayerVOHelp; int m_refCount; bool m_firstComponentPending; diff --git a/Code/BF2/Game/Objects/IObject.h b/Code/BF2/Game/Objects/IObject.h index 7f5716350..f6c0aa4f4 100644 --- a/Code/BF2/Game/Objects/IObject.h +++ b/Code/BF2/Game/Objects/IObject.h @@ -20,6 +20,7 @@ struct LocalBoundingBox; namespace io { class INetworkable; class PlayerInput; } namespace geom { class IGeometry; } namespace hud { class BF2HudManager; class HudVehicleInformation; class HudAmmo; class HudMessages; } +class DistributedLightRenderer; class BF2FrameInterpolator; // Game/Main/BF2FrameInterpolator.h - reads +0x08/+0x38 directly namespace world { @@ -264,6 +265,8 @@ class IObject : public IPersistant friend class hud::HudVehicleInformation; // PE78B940/78B4E0: kit ability component+60 friend class hud::HudAmmo; // PE7A5600/7A59D0/7A8460: HUD component fields+54/+60/+6C friend class hud::HudMessages; // PE79E1B0/79E450: cached weapon/vehicle HUD components + // traceAllObjects (46C580) tests the flags and geometry fields; assignWorkItem reads the id. + friend class hfe::DistributedLightRenderer; // Bundle::handleMessage walks the raw sibling/parent links and reads the armor field directly // rather than dispatching getSibling()/getParent(), exactly as both ports do. friend class Bundle; diff --git a/Code/BF2/Game/Objects/IStrategicObjectComp.h b/Code/BF2/Game/Objects/IStrategicObjectComp.h index 7c582eb9a..037f57709 100644 --- a/Code/BF2/Game/Objects/IStrategicObjectComp.h +++ b/Code/BF2/Game/Objects/IStrategicObjectComp.h @@ -4,7 +4,9 @@ #ifndef GAME_OBJECTS_ISTRATEGICOBJECTCOMP_H // [INFERRED] guard style #define GAME_OBJECTS_ISTRATEGICOBJECTCOMP_H +#include #include +#include #include "IObjectComponent.h" #include "../../Math/Vec3.h" @@ -13,6 +15,11 @@ namespace dice { namespace hfe { namespace world { +#if defined(_M_IX86) +static_assert(std::is_same::value, + "x86 strategic icon handles keep the retail int signatures"); +#endif + class IStrategicObjectComp : public IObjectComponent { public: @@ -21,9 +28,10 @@ class IStrategicObjectComp : public IObjectComponent virtual const std::string& getIntactIconName() = 0; // +0x3C virtual const std::string& getDestroyedIconName() = 0; // +0x40 // 77E500 signed-compares both results with zero and stores the same dword directly into - // MapIconRecord::texture. They are integer texture handles, despite the historical Ptr names. - virtual int getIntactIconPtr() = 0; // +0x44 - virtual int getDestroyedIconPtr() = 0; // +0x48 + // MapIconRecord::texture. They are integer texture handles, despite the historical Ptr names; + // std::intptr_t is int on x86 (unchanged mangling) and pointer-wide on native x64. + virtual std::intptr_t getIntactIconPtr() = 0; // +0x44 + virtual std::intptr_t getDestroyedIconPtr() = 0; // +0x48 virtual int getPart() = 0; // +0x4C // Index of the holder assigned by GameLogic. virtual int getIndex() = 0; // +0x50 diff --git a/Code/BF2/Game/Objects/IVehicleHudComp.h b/Code/BF2/Game/Objects/IVehicleHudComp.h index 14d6d41ec..e6420feaf 100644 --- a/Code/BF2/Game/Objects/IVehicleHudComp.h +++ b/Code/BF2/Game/Objects/IVehicleHudComp.h @@ -3,6 +3,7 @@ #ifndef GAME_OBJECTS_IVEHICLEHUDCOMP_H // [INFERRED] guard style #define GAME_OBJECTS_IVEHICLEHUDCOMP_H +#include #include #include "IObjectComponent.h" #include "VehicleHudCompTemplate.h" // VehicleHudInfo / VehicleHudIcons @@ -21,9 +22,10 @@ class IVehicleHudComp : public IObjectComponent // HUD78B1E0 dispatches its getInfo slot. This was incorrectly chosen bool. virtual IPostProcessComp* getEnablePostProcessing(int) = 0; // +0x3C virtual std::string getVehicleIcon(int) = 0; // +0x40 hidden sret - virtual int getVehicleIconPtr(int) = 0; // +0x44 vector + // Texture handles: std::intptr_t is int on x86 (unchanged mangling), pointer-wide on x64. + virtual std::intptr_t getVehicleIconPtr(int) = 0; // +0x44 vector virtual std::string getAbilityIcon(int) = 0; // +0x48 hidden sret - virtual int getAbilityIconPtr(int) = 0; // +0x4C vector + virtual std::intptr_t getAbilityIconPtr(int) = 0; // +0x4C vector virtual bool getShowOnCamMode(int) = 0; // +0x50 movzx eax,al virtual void playingPantingSound(bool) = 0; // +0x54 virtual bool getIsPlayingPantingSound() = 0; // +0x58 [CHOSEN ret] diff --git a/Code/BF2/Game/Objects/MaskObjectTemplate.h b/Code/BF2/Game/Objects/MaskObjectTemplate.h index 1f01a5073..92b057c12 100644 --- a/Code/BF2/Game/Objects/MaskObjectTemplate.h +++ b/Code/BF2/Game/Objects/MaskObjectTemplate.h @@ -24,7 +24,7 @@ namespace world { std::ostream& operator<<(std::ostream&, MaskObjectType); std::istream& operator>>(std::istream&, MaskObjectType&); -class GameTemplateConsoleAccess; +struct GameTemplateConsoleAccess; class MaskObjectTemplate : public AnimatedBundleTemplate { @@ -41,7 +41,7 @@ class MaskObjectTemplate : public AnimatedBundleTemplate MaskObjectType getMaskType() const; protected: - friend class GameTemplateConsoleAccess; + friend struct GameTemplateConsoleAccess; MaskObjectType m_maskType; // ELF +0x194 / PE +0x244; ctor MOTNoMask Vec3 m_maskOffset; // ELF +0x198 / PE +0x248; ctor (0, -1.55, 0.08) }; diff --git a/Code/BF2/Game/Objects/ObjectLayoutAccess.h b/Code/BF2/Game/Objects/ObjectLayoutAccess.h index 8feab7a82..0ef354435 100644 --- a/Code/BF2/Game/Objects/ObjectLayoutAccess.h +++ b/Code/BF2/Game/Objects/ObjectLayoutAccess.h @@ -49,6 +49,9 @@ struct LayoutAccess { return p->m_weaponHudComponent; } + // BF2.exe 0x5EDF21/0x5EDF2D: VO help reads the cached slots, without a query. + static IObjectComponent*& helpHudComponent(IObject* p) { return p->m_helpHudComponent; } + static IObjectComponent*& abilityHudComponent(IObject* p) { return p->m_abilityHudComponent; } static IObjectComponent*& radioGLComponent(IObject* p) { return p->m_radioGLComponent; diff --git a/Code/BF2/Game/Objects/Projectiles/GenericProjectile.cpp b/Code/BF2/Game/Objects/Projectiles/GenericProjectile.cpp index f17f1ed69..2f934aa89 100644 --- a/Code/BF2/Game/Objects/Projectiles/GenericProjectile.cpp +++ b/Code/BF2/Game/Objects/Projectiles/GenericProjectile.cpp @@ -5,11 +5,18 @@ // Specialized client/effect branches retain named [FRONTIER] boundaries. #include "GenericProjectile.h" +#include "../GeometryPartAccess.h" // named geometry operations (non-MSVC) +#if defined(BF2_STATIC_PLUGINS) && !defined(_MSC_VER) +// [CHOSEN, not recovered] One native scale-interface declaration in every image. +#include "../../../Geom/IScaleable.h" +#endif +#if defined(BF2_STATIC_PLUGINS) && !defined(_MSC_VER) +// [CHOSEN, not recovered] Native static geometry tables retain PE slot order. +#include "../../../Geom/NativeGeometrySlots.h" +#endif #include // FLT_EPSILON #include -#include -#include #include #include "GenericProjectileTemplate.h" @@ -25,9 +32,10 @@ #include "../IWeaponObject.h" #include "../Networkables/Networkables.h" #include "../../../AI/AIInterface/BFKnowledge/BFCollisionHandler.h" +#include "../../../AI/AIDLL/AI/Main/CommonSingletonServer.h" // m_iBFCollisionHandler #include "../../../Core/Ids.h" #include "../../../Core/Debug.h" // getStickTransformation's retail error arm -#include "../../../Core/Random.h" // g_random - retail distribution sampler +#include "../../../Core/Random.h" // Rand - retail distribution sampler #include "../../../Core/System.h" // launch clocks / ticks #include "../../../Core/WeakPtr.h" // the +0x174 ctrl read - PCO's idiom #include "../../../Geom/IGeometryTemplate.h" @@ -49,10 +57,6 @@ namespace dice { namespace hfe { -namespace ai { -// Stored as an erased pointer; IBFCollisionHandler does not derive from IBase. -extern IBase* g_bfCollisionHandler; -} namespace world { extern IBase* materialManager; // ds:0x8AD2820, defined in Core/Globals.cpp @@ -61,11 +65,15 @@ namespace { // IScaleable consists of the IBase quartet followed by setScale. Both activate and updateTracer // query exactly this IID before making the typed call at +0x10. +#if defined(BF2_STATIC_PLUGINS) && !defined(_MSC_VER) +using IScaleable = geom::IScaleable; +#else class IScaleable : public IBase { public: virtual void setScale(const Vec3&) = 0; }; +#endif float unitRandom(Random& random) { @@ -85,20 +93,20 @@ float sampleRandomDistribution(const RandomDistribution& distribution) break; case CRD_UNIFORM: sample = distribution.value - + (distribution.variation - distribution.value) * unitRandom(g_random); + + (distribution.variation - distribution.value) * unitRandom(Rand); break; case CRD_EXPONENTIAL: - sample = -distribution.value * static_cast(std::log(unitRandom(g_random))); + sample = -distribution.value * static_cast(std::log(unitRandom(Rand))); break; case CRD_NORMAL: - sample = distribution.value + g_random.getNormal() * distribution.variation; + sample = distribution.value + Rand.getNormal() * distribution.variation; break; default: sample = 0.0f; break; } - if (distribution.relative && unitRandom(g_random) <= 0.5f) + if (distribution.relative && unitRandom(Rand) <= 0.5f) sample = -sample; return sample; } @@ -112,13 +120,13 @@ IObjectTemplate* getGeometryTemplate(IBase* geometry) // ordinal, including its single destructor slot, with eight-byte entries. enum { GetTemplateIndex = 0x38 / 4 }; typedef IObjectTemplate* (__thiscall *GetTemplateFn)(void*); -#else - enum { GetTemplateIndex = 0x3C / 4 }; - typedef IObjectTemplate* (*GetTemplateFn)(void*); -#endif void** const vtable = *reinterpret_cast(geometry); GetTemplateFn const getTemplate = reinterpret_cast(vtable[GetTemplateIndex]); return getTemplate(geometry); +#else + // Non-MSVC: the named geometry_part operation (ELF +0x3C). + return static_cast(geometry_part::getTemplate(geometry)); +#endif } IPlayerControlObject* findPlayerControlObject(IObject* object) @@ -157,14 +165,6 @@ void normaliseVec3(Vec3& v) v.x *= inverse; v.y *= inverse; v.z *= inverse; } -// Reports and stops unresolved projectile operations. -void projectileFrontier(const char* method) -{ - std::fprintf(stderr, "[FRONTIER] dice::hfe::world::GenericProjectile::%s reached\n", method); - std::fflush(stderr); - std::abort(); -} - } // namespace // Initializes projectile bases and state, retaining the original uninitialized gaps. @@ -511,8 +511,8 @@ void GenericProjectile::resetProjectile(bool a2) gameLogic->removeProjectile(this); // . Drop this projectile from the AI's collision tracking before the trail goes. - if (ai::g_bfCollisionHandler) - reinterpret_cast(ai::g_bfCollisionHandler) + if (ai::CommonSingletonServer::m_iBFCollisionHandler) + static_cast(ai::CommonSingletonServer::m_iBFCollisionHandler) ->handleProjectileTimeout(static_cast(this), this); destroyTrailEffect(); @@ -1052,8 +1052,8 @@ void GenericProjectile::detonate(bool forced) objectManager->postMessage(this, static_cast(32), destroyDelay); // . The same removal resetProjectile does, and the last thing detonate does. - if (ai::g_bfCollisionHandler) - reinterpret_cast(ai::g_bfCollisionHandler) + if (ai::CommonSingletonServer::m_iBFCollisionHandler) + static_cast(ai::CommonSingletonServer::m_iBFCollisionHandler) ->handleProjectileTimeout(static_cast(this), this); } diff --git a/Code/BF2/Game/Objects/Projectiles/GenericProjectileTemplate.cpp b/Code/BF2/Game/Objects/Projectiles/GenericProjectileTemplate.cpp index 34d23482b..6be63b523 100644 --- a/Code/BF2/Game/Objects/Projectiles/GenericProjectileTemplate.cpp +++ b/Code/BF2/Game/Objects/Projectiles/GenericProjectileTemplate.cpp @@ -11,7 +11,7 @@ #include "../../../Core/Ids.h" #include "../../IGameLogic.h" // gameLogic->addPreStoredTemplate - the 16-deep pre-store #include "../../../Geom/IGeometryTemplate.h" -#if !DEDICATED && defined(_M_IX86) && BF2_PLUGIN_ABI_NATIVE +#if !DEDICATED && (defined(_MSC_VER) || defined(BF2_STATIC_PLUGINS)) #include "../../../Geom/GeometryTemplateManager.h" #endif @@ -46,7 +46,7 @@ void precacheTracerGeometry(IObjectTemplate* tracerTemplate) // Returns a borrowed geometry template through the legacy cache type. Requires the client manager. IObjectTemplate* lookupTracerGeometryTemplate(const std::string& name) { -#if defined(_M_IX86) && BF2_PLUGIN_ABI_NATIVE +#if !DEDICATED && (defined(_MSC_VER) || defined(BF2_STATIC_PLUGINS)) geom::IGeometryTemplateManager* const manager = static_cast(::dice::hfe::g_geometryTemplateManager); return reinterpret_cast(manager->getTemplate(name)); diff --git a/Code/BF2/Game/Objects/RemoteControlledObjectTemplate.h b/Code/BF2/Game/Objects/RemoteControlledObjectTemplate.h index 36a5ae593..f7fe99735 100644 --- a/Code/BF2/Game/Objects/RemoteControlledObjectTemplate.h +++ b/Code/BF2/Game/Objects/RemoteControlledObjectTemplate.h @@ -12,6 +12,7 @@ namespace dice { namespace hfe { class GameLogic; +class ServerConnection; namespace world { class UAVVehicleManager; @@ -41,6 +42,7 @@ class RemoteControlledObjectTemplate : public BundleTemplate { public: friend class hfe::GameLogic; // the RCO registry reads rcType + friend class hfe::ServerConnection; // getSpecialCommanderObjects reads rcType friend class UAVVehicleManager; // UAV spawn/config reads the +0x188..+0x198 block friend class UAVVehicle; // the live drone reads uavVehicleSpeed each tick friend class CommanderToolsManager; // commander-toy aggregation reads rcType diff --git a/Code/BF2/Game/Objects/StrategicObjectComp.cpp b/Code/BF2/Game/Objects/StrategicObjectComp.cpp index db5366971..fac13a966 100644 --- a/Code/BF2/Game/Objects/StrategicObjectComp.cpp +++ b/Code/BF2/Game/Objects/StrategicObjectComp.cpp @@ -47,8 +47,8 @@ void StrategicObjectComp::handleUpdate(float) {} const std::string& StrategicObjectComp::getStrategicObjectName() { return m_template->getStrategicObjectName(); } const std::string& StrategicObjectComp::getIntactIconName() { return m_template->getIntactIcon(); } const std::string& StrategicObjectComp::getDestroyedIconName() { return m_template->getDestroyedIcon(); } -int StrategicObjectComp::getIntactIconPtr() { return m_template->getIntactIconPtr(); } -int StrategicObjectComp::getDestroyedIconPtr() { return m_template->getDestroyedIconPtr(); } +std::intptr_t StrategicObjectComp::getIntactIconPtr() { return m_template->getIntactIconPtr(); } +std::intptr_t StrategicObjectComp::getDestroyedIconPtr() { return m_template->getDestroyedIconPtr(); } int StrategicObjectComp::getPart() { return m_template->getPart(); } int StrategicObjectComp::getIndex() { return m_index; } void StrategicObjectComp::setIndex(int index) { m_index = index; } diff --git a/Code/BF2/Game/Objects/StrategicObjectComp.h b/Code/BF2/Game/Objects/StrategicObjectComp.h index 1a62a2a57..4d8a18359 100644 --- a/Code/BF2/Game/Objects/StrategicObjectComp.h +++ b/Code/BF2/Game/Objects/StrategicObjectComp.h @@ -38,8 +38,8 @@ class StrategicObjectComp : public IStrategicObjectComp const std::string& getStrategicObjectName() override; const std::string& getIntactIconName() override; const std::string& getDestroyedIconName() override; - int getIntactIconPtr() override; - int getDestroyedIconPtr() override; + std::intptr_t getIntactIconPtr() override; + std::intptr_t getDestroyedIconPtr() override; int getPart() override; int getIndex() override; void setIndex(int) override; diff --git a/Code/BF2/Game/Objects/StrategicObjectCompTemplate.cpp b/Code/BF2/Game/Objects/StrategicObjectCompTemplate.cpp index 267670798..233bb561b 100644 --- a/Code/BF2/Game/Objects/StrategicObjectCompTemplate.cpp +++ b/Code/BF2/Game/Objects/StrategicObjectCompTemplate.cpp @@ -60,7 +60,8 @@ const std::string& StrategicObjectCompTemplate::getStrategicObjectName() { retur namespace { // [INFERRED] helper name. BF2.exe 65A2F0 takes the string by value, calls // getSystem twice and resolves with loadTexture(name, true). ELF inlines null. -int resolveStrategicIcon(std::string name) +// The handle is std::intptr_t: int on x86, the full texture address on native x64. +std::intptr_t resolveStrategicIcon(std::string name) { #if !DEDICATED if (hudManager && hudManager->getSystem()) @@ -81,8 +82,8 @@ void StrategicObjectCompTemplate::setIntactIcon(std::string value) } const std::string& StrategicObjectCompTemplate::getDestroyedIcon() { return m_destroyedIcon; } const std::string& StrategicObjectCompTemplate::getIntactIcon() { return m_intactIcon; } -int StrategicObjectCompTemplate::getDestroyedIconPtr() { return m_destroyedIconPtr; } -int StrategicObjectCompTemplate::getIntactIconPtr() { return m_intactIconPtr; } +std::intptr_t StrategicObjectCompTemplate::getDestroyedIconPtr() { return m_destroyedIconPtr; } +std::intptr_t StrategicObjectCompTemplate::getIntactIconPtr() { return m_intactIconPtr; } void StrategicObjectCompTemplate::setPart(int value) { m_part = value; } int StrategicObjectCompTemplate::getPart() { return m_part; } void StrategicObjectCompTemplate::set3dMapIcon(int value) { m_mapIcon3D = value; } diff --git a/Code/BF2/Game/Objects/StrategicObjectCompTemplate.h b/Code/BF2/Game/Objects/StrategicObjectCompTemplate.h index 85a25f7a4..c1e82f4f7 100644 --- a/Code/BF2/Game/Objects/StrategicObjectCompTemplate.h +++ b/Code/BF2/Game/Objects/StrategicObjectCompTemplate.h @@ -5,6 +5,7 @@ #ifndef GAME_OBJECTS_STRATEGICOBJECTCOMPTEMPLATE_H // [INFERRED] guard style #define GAME_OBJECTS_STRATEGICOBJECTCOMPTEMPLATE_H +#include #include #include "CompTemplateInterfaces.h" @@ -36,10 +37,10 @@ class StrategicObjectCompTemplate : public IStrategicObjectCompTemplate, public virtual const std::string& getStrategicObjectName(); virtual void setDestroyedIcon(std::string); // resolves virtual const std::string& getDestroyedIcon(); - virtual int getDestroyedIconPtr(); + virtual std::intptr_t getDestroyedIconPtr(); // int on x86 virtual void setIntactIcon(std::string); // resolves virtual const std::string& getIntactIcon(); - virtual int getIntactIconPtr(); + virtual std::intptr_t getIntactIconPtr(); // int on x86 virtual void setPart(int); virtual int getPart(); virtual void set3dMapIcon(int); virtual int get3dMapIcon() const; virtual bool has3dMapIcon() const; @@ -56,8 +57,9 @@ class StrategicObjectCompTemplate : public IStrategicObjectCompTemplate, public /* 20 */ std::string m_destroyedIcon; // authored path /* 24 */ std::string m_intactIcon; // authored path - /* 28 */ int m_destroyedIconPtr; // resolved texture handle - /* 32 */ int m_intactIconPtr; // resolved texture handle + // Resolved texture handles: std::intptr_t is int on x86 (offsets unchanged), pointer-wide on x64. + /* 28 */ std::intptr_t m_destroyedIconPtr; + /* 32 */ std::intptr_t m_intactIconPtr; /* 36 */ int m_mapIcon3D; // console binding: strategicObject.3dMapIcon /* 40 */ bool m_isOnePiece; diff --git a/Code/BF2/Game/Objects/TemplateLeaves.cpp b/Code/BF2/Game/Objects/TemplateLeaves.cpp index 847705eb7..a46254d82 100644 --- a/Code/BF2/Game/Objects/TemplateLeaves.cpp +++ b/Code/BF2/Game/Objects/TemplateLeaves.cpp @@ -8,7 +8,7 @@ #include #include #if defined(_MSC_VER) && defined(_M_IX86) -#include "../../../RendDX9Abi/Vc71String.h" +#include #endif #include "Game/DynamicBundle.h" #include "Game/AreaObject.h" @@ -334,8 +334,8 @@ IObject* EnvMapTemplate::createObject() const { return 0; } bool EnvMapTemplate::writeBinary(io::IStream*) const { return false; } bool EnvMapTemplate::readBinary(io::IStream*) { return false; } -// ELF8201CC0 / clientPE64E4D0, complete reads. Renderer +1C is getTemplate(name); -// the Windows renderer retains VC7.1 strings even when both images use the native ABI. +// ELF8201CC0 / clientPE64E4D0, complete reads. Renderer +1C is getTemplate(name); the renderer +// takes the key as the shared std::string (issue #7: one STL across the image boundary). void EnvMapTemplate::templateInitialize() { updateFlags(1, 0); @@ -343,38 +343,15 @@ void EnvMapTemplate::templateInitialize() if (manager) { const std::string& name=getName(); -#if defined(_MSC_VER) && defined(_M_IX86) - // [CHOSEN, not recovered] Borrowed, read-only VC7.1 argument carrier. The - // recovered getTemplate copies its key; it neither retains nor mutates this - // carrier, so no renderer heap/string destructor crosses the image boundary. - struct BorrowedName - { - unsigned int allocator; - union { char buffer[16]; const char* pointer; } storage; - unsigned int length,capacity; - } argument={}; - static_assert(sizeof(BorrowedName)==sizeof(vc71::string),"VC7.1 argument carrier"); - argument.length=static_cast(name.size()); - if(name.size()<16) - { - std::memcpy(argument.storage.buffer,name.c_str(),name.size()+1); - argument.capacity=15; - } - else - { - argument.storage.pointer=name.c_str(); - argument.capacity=argument.length; - } - typedef void* (__thiscall* GetTemplate)(void*,const vc71::string&); - m_envMap=reinterpret_cast((*reinterpret_cast(manager))[0x1C/4])( - manager,*reinterpret_cast(&argument)); +#if defined(_MSC_VER) + typedef void* (__thiscall* GetTemplate)(void*,const std::string&); #else typedef void* (*GetTemplate)(void*,const std::string&); +#endif // ELF8201D3D / clientPE64E51C: +0x1C is logical slot 7 in both 32-bit // tables. Preserve the ordinal when native pointer width changes. m_envMap=reinterpret_cast((*reinterpret_cast(manager))[7])( manager,name); -#endif } } diff --git a/Code/BF2/Game/Objects/VehicleHudCompTemplate.cpp b/Code/BF2/Game/Objects/VehicleHudCompTemplate.cpp index 5af889953..4d02a916c 100644 --- a/Code/BF2/Game/Objects/VehicleHudCompTemplate.cpp +++ b/Code/BF2/Game/Objects/VehicleHudCompTemplate.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #if !DEDICATED @@ -35,7 +36,8 @@ namespace world { namespace { -int resolveVehicleHudIcon(std::string name) +// The handle is std::intptr_t: int on x86, the full texture address on native x64. +std::intptr_t resolveVehicleHudIcon(std::string name) { #if !DEDICATED // deliberately calls getSystem twice on the success path. @@ -212,9 +214,10 @@ class VehicleHudComp : public IVehicleHudComp return result; } - virtual int getVehicleIconPtr(int index) + virtual std::intptr_t getVehicleIconPtr(int index) { - std::vector::const_iterator icon = m_template->m_vehicleHudIcons.vehicleIconPtrs.begin(); + std::vector::const_iterator icon = + m_template->m_vehicleHudIcons.vehicleIconPtrs.begin(); if (index < m_template->getVehicleIconNumber()) icon += index; if (icon != m_template->m_vehicleHudIcons.vehicleIconPtrs.end()) @@ -233,9 +236,10 @@ class VehicleHudComp : public IVehicleHudComp return result; } - virtual int getAbilityIconPtr(int index) + virtual std::intptr_t getAbilityIconPtr(int index) { - std::vector::const_iterator icon = m_template->m_vehicleHudIcons.abilityIconPtrs.begin(); + std::vector::const_iterator icon = + m_template->m_vehicleHudIcons.abilityIconPtrs.begin(); if (index < m_template->getAbilityIconNumber()) icon += index; if (icon != m_template->m_vehicleHudIcons.abilityIconPtrs.end()) diff --git a/Code/BF2/Game/Objects/VehicleHudIcons.h b/Code/BF2/Game/Objects/VehicleHudIcons.h index c9bc81f1e..37fb6b797 100644 --- a/Code/BF2/Game/Objects/VehicleHudIcons.h +++ b/Code/BF2/Game/Objects/VehicleHudIcons.h @@ -2,11 +2,18 @@ #ifndef GAME_OBJECTS_VEHICLEHUDICONS_H #define GAME_OBJECTS_VEHICLEHUDICONS_H +#include #include +#include #include namespace dice { namespace hfe { namespace world { +#if defined(_M_IX86) +static_assert(std::is_same::value, + "x86 icon handles keep the retail int layout and mangling"); +#endif + // ELF constructor 0x822CE50; BF2.exe constructor 0x65B020. The containing // template initializes the three scalar handles after this constructor returns. // Retail ELF size 0x48, VC7.1 size 0xA0. Native STL determines this build's size; @@ -21,12 +28,13 @@ struct VehicleHudIcons std::string typeIcon; // ELF +1C; PE +3C std::string spottedIcon; // ELF +20; PE +58 // Element type is attested by vector manglings in the ELF setters. - // On the client these integer handles carry Ref2System texture addresses. - std::vector vehicleIconPtrs; // ELF +24; PE +74 - std::vector abilityIconPtrs; // ELF +30; PE +84 - int miniMapIconPtr; // ELF +3C; PE +94 - int typeIconPtr; // ELF +40; PE +98 - int spottedIconPtr; // ELF +44; PE +9C + // On the client these integer handles carry Ref2System texture addresses, so they are + // std::intptr_t: int on x86 (unchanged layout and mangling), pointer-wide on native x64. + std::vector vehicleIconPtrs; // ELF +24; PE +74 + std::vector abilityIconPtrs; // ELF +30; PE +84 + std::intptr_t miniMapIconPtr; // ELF +3C; PE +94 + std::intptr_t typeIconPtr; // ELF +40; PE +98 + std::intptr_t spottedIconPtr; // ELF +44; PE +9C }; } } } diff --git a/Code/BF2/Game/Objects/Visual/LightSource.cpp b/Code/BF2/Game/Objects/Visual/LightSource.cpp index a6d093439..66e00e7b8 100644 --- a/Code/BF2/Game/Objects/Visual/LightSource.cpp +++ b/Code/BF2/Game/Objects/Visual/LightSource.cpp @@ -13,6 +13,7 @@ #include "../../../Core/Debug.h" #include "../../../Core/ClassManager.h" #include "../../../Geom/XpLightManager.h" +#include "../../../Platform/MsvcRand.h" // [CHOSEN, not recovered] the client CRT's rand (MSVCR71) namespace dice { namespace hfe { @@ -215,8 +216,8 @@ void LightSource::handleFrameUpdate(float) const float flicker = m_template->getFlicker(); // template +0x1F8 if (flicker > 0.0f) { - // [PLATFORM] Scale by this platform's RAND_MAX to preserve the full [0, 1] flicker range. - const float r = static_cast(rand()) * (1.0f / RAND_MAX); + // [PLATFORM] Scale by the CRT generator's RAND_MAX (bf2crt) to preserve the full [0, 1] flicker range. + const float r = static_cast(bf2crt::rand()) * (1.0f / bf2crt::kRandMax); m_attenuationRange1 = m_template->getAttenuationRange1() * ((r - 1.0f) * flicker + 1.0f); // +0x148 m_attenuationRange2 = m_template->getAttenuationRange2() * ((r - 1.0f) * flicker + 1.0f); // +0x14C } diff --git a/Code/BF2/Game/Objects/WeaponHudCompTemplate.cpp b/Code/BF2/Game/Objects/WeaponHudCompTemplate.cpp index 0b4921eb3..c148dd3d2 100644 --- a/Code/BF2/Game/Objects/WeaponHudCompTemplate.cpp +++ b/Code/BF2/Game/Objects/WeaponHudCompTemplate.cpp @@ -74,9 +74,10 @@ class WeaponHudComp : public IWeaponHudComp virtual bool hasUpdate() const { return false; } virtual void handleUpdate(float) {} - virtual int getGuiIndex(bool selected) + virtual int getGuiIndex(bool sprinting) { - if (selected && m_template->getDisplaySelectOnActivation()) + // ELF 0x822E620: the template's vslot +0x12C, WeaponHudCompTemplate::getDisableOnSprint. + if (sprinting && m_template->getDisableOnSprint()) return 0; if (m_template->getAltGuiIndex() == -1) return m_template->getGuiIndex(); diff --git a/Code/BF2/Game/Objects/Weapons/DeviationComponents/SoldierDeviationComp.cpp b/Code/BF2/Game/Objects/Weapons/DeviationComponents/SoldierDeviationComp.cpp index ea0c63549..35859179c 100644 --- a/Code/BF2/Game/Objects/Weapons/DeviationComponents/SoldierDeviationComp.cpp +++ b/Code/BF2/Game/Objects/Weapons/DeviationComponents/SoldierDeviationComp.cpp @@ -6,6 +6,7 @@ #include "SoldierDeviationComp.h" #include +#include #include #include @@ -18,6 +19,8 @@ #include "../../../../Core/Ids.h" #include "../../../../IO/Input/PlayerInput.h" #include "../../../../IO/Stream/IStream.h" +#include "../../../../Physics/IResponsePhysics.h" +#include "../../../../Physics/SoldierResponse.h" // m_byteFA (+0xFA), a friend #include "../../../../Scene/Object/ObjectUtil.h" namespace dice { @@ -174,10 +177,15 @@ void SoldierDeviationComp::updateDeviation(io::PlayerInput input, if (!soldierObject->getParent()) { // Retail has no null guard here. A Soldier is expected to carry response physics; - // preserve the raw +0xFA ground-contact read instead of inventing a fallback. - unsigned char* const response = static_cast( - object_detail::LayoutAccess::responsePhysics(soldierObject)); - if (!response[0xFA]) + // preserve the +0xFA ground-contact read instead of inventing a fallback. +#if defined(_M_IX86) + static_assert(offsetof(SoldierResponsePhysics, m_byteFA) == 0xFA, + "retail soldier ground-contact byte"); +#endif + const SoldierResponsePhysics* const response = + static_cast(static_cast( + object_detail::LayoutAccess::responsePhysics(soldierObject))); + if (!response->m_byteFA) pose = SoldierPose_Stand; } diff --git a/Code/BF2/Game/Objects/Weapons/FireComponents/FireComp.cpp b/Code/BF2/Game/Objects/Weapons/FireComponents/FireComp.cpp index 8f734514a..4e5937971 100644 --- a/Code/BF2/Game/Objects/Weapons/FireComponents/FireComp.cpp +++ b/Code/BF2/Game/Objects/Weapons/FireComponents/FireComp.cpp @@ -446,11 +446,15 @@ void FireComp::setFirebuttonLastHeldAtTick(io::PlayerInputMap input, unsigned in m_altFireButtonLastHeldAtTick = tick; } +// ELF 0x82630C0 fetches the player (0x82630DE) and, when the template names an ignored fire +// button, calls through it (0x82630F2/0x82630F7) without a null test. +// [CHOSEN, not recovered] A firearm without a player skips the ignored-button test instead of +// crashing; the rest is retail (the same path retail takes when no button is ignored). bool FireComp::requestFire(bool released, bool) { IPlayer* const player = firearm()->getPlayer(); const io::PlayerInputMap ignored = m_template->getIgnoreFireButton(); - if (ignored != io::PINone && ignored == player->getCurrentFiringButton()) + if (ignored != io::PINone && player && ignored == player->getCurrentFiringButton()) return false; if (m_fireRate == static_cast(2)) diff --git a/Code/BF2/Game/Objects/Weapons/FireComponents/MultiFireComp.cpp b/Code/BF2/Game/Objects/Weapons/FireComponents/MultiFireComp.cpp index 282a72e97..e948f4108 100644 --- a/Code/BF2/Game/Objects/Weapons/FireComponents/MultiFireComp.cpp +++ b/Code/BF2/Game/Objects/Weapons/FireComponents/MultiFireComp.cpp @@ -26,15 +26,10 @@ #include "../../../../IO/Stream/IStream.h" #include "../../../../Physics/IPhysicsNode.h" #include "../../../../AI/AIInterface/BFKnowledge/BFCollisionHandler.h" +#include "../../../../AI/AIDLL/AI/Main/CommonSingletonServer.h" // m_iBFCollisionHandler namespace dice { namespace hfe { -namespace ai { - -// Stored as an erased pointer; IBFCollisionHandler does not derive from IBase. -extern IBase* g_bfCollisionHandler; - -} // namespace ai namespace world { namespace { @@ -371,8 +366,8 @@ bool MultiFireComp::launchProjectile(int index) { IProjectileObject* const projectile = static_cast( object->queryInterface(IID_IProjectileObject)); - if (ai::g_bfCollisionHandler) - reinterpret_cast(ai::g_bfCollisionHandler) + if (ai::CommonSingletonServer::m_iBFCollisionHandler) + static_cast(ai::CommonSingletonServer::m_iBFCollisionHandler) ->handleProjectileFire(projectile, object); } } diff --git a/Code/BF2/Game/Objects/Weapons/FireComponents/SingleFireComp.cpp b/Code/BF2/Game/Objects/Weapons/FireComponents/SingleFireComp.cpp index 58e3ba083..fabad090b 100644 --- a/Code/BF2/Game/Objects/Weapons/FireComponents/SingleFireComp.cpp +++ b/Code/BF2/Game/Objects/Weapons/FireComponents/SingleFireComp.cpp @@ -1,6 +1,11 @@ // Single-shot firing and template properties. #include "SingleFireComp.h" +#include "../../GeometryPartAccess.h" // named geometry operations (non-MSVC) +#if defined(BF2_STATIC_PLUGINS) && !defined(_MSC_VER) +// [CHOSEN, not recovered] Native static geometry tables retain PE slot order. +#include "../../../../Geom/NativeGeometrySlots.h" +#endif #include #include @@ -37,14 +42,9 @@ typedef void (__thiscall *GeometrySetLodFn)(void*, int); const std::size_t kGeometryGetSubgeomSlot = 0x70 / 4; const std::size_t kGeometrySetLodSlot = 0x78 / 4; const std::size_t kGeometryGetLodCountSlot = 0x80 / 4; -#else -typedef int (*GeometryGetIntFn)(void*); -typedef void (*GeometrySetLodFn)(void*, int); -const std::size_t kGeometryGetSubgeomSlot = 0x74 / 4; -const std::size_t kGeometrySetLodSlot = 0x7C / 4; -const std::size_t kGeometryGetLodCountSlot = 0x84 / 4; #endif +#if defined(_MSC_VER) void** geometryVtable(void* geometry) { return *reinterpret_cast(geometry); @@ -67,6 +67,12 @@ int geometryGetLodCount(void* geometry) return reinterpret_cast( geometryVtable(geometry)[kGeometryGetLodCountSlot])(geometry); } +#else +// Non-MSVC: the named geometry_part operations (static native: Geom/NativeGeometrySlots.h). +int geometryGetSubgeom(void* geometry) { return geometry_part::getSubgeom(geometry); } +void geometrySetLod(void* geometry, int lod) { geometry_part::setLod(geometry, lod); } +int geometryGetLodCount(void* geometry) { return geometry_part::getLodCount(geometry); } +#endif } // namespace diff --git a/Code/BF2/Game/Objects/Weapons/GenericFireArm.cpp b/Code/BF2/Game/Objects/Weapons/GenericFireArm.cpp index 015ae1ad5..1b86a3ac2 100644 --- a/Code/BF2/Game/Objects/Weapons/GenericFireArm.cpp +++ b/Code/BF2/Game/Objects/Weapons/GenericFireArm.cpp @@ -4,6 +4,7 @@ // [RETIRE-WHEN: unrecovered-factories-registered] Register remaining factories only once their required bodies exist. #include "GenericFireArm.h" +#include "../GeometryPartAccess.h" // named geometry operations (non-MSVC) #include "../Game/TriggerManager.h" #include "FireComponents/FireComp.h" #include "AmmoComponents/AmmoComp.h" // IWeaponAmmoComp - the typed ammo delegates @@ -54,15 +55,12 @@ #include #include +#include "../../../AI/AIInterface/BFKnowledge/BFCollisionHandler.h" +#include "../../../AI/AIDLL/AI/Main/CommonSingletonServer.h" + namespace dice { namespace hfe { -namespace ai { -// This singleton is null in the production no-bot server. Its concrete IBFCollisionHandler -// interface is aidll-owned and intentionally not fabricated in the engine reconstruction. -extern IBase* g_bfCollisionHandler; -} - namespace world { // ds:0x8ABAF24 (ELF) / dword_899500 (PE), published by Core/Globals.cpp. @@ -70,15 +68,6 @@ extern IBase* heightmapCluster; namespace { -// [TEMP] [CHOSEN, not recovered] - the agents.md frontier stop: name the method on stderr, -// flush, and never return. It never fabricates a default and lets execution continue. -[[noreturn]] void gfaFrontier(const char* method) -{ - std::fprintf(stderr, "[FRONTIER] dice::hfe::world::GenericFireArm::%s reached\n", method); - std::fflush(stderr); - std::abort(); -} - const float kTicksPerSecond = 30.0f; // flt_888B174 - the fixed timestep const float kRedeployInterval = 2.0f; // flt_888FFE4 - enableItem's deploy retry gap, in seconds // ds:0x8AAC680. Like the two other recovered readers, no writer exists in the dedicated server. @@ -428,14 +417,18 @@ void GenericFireArm::updateGeometry() // / client PE 0x5E0610: suppress the original mesh while an // alternate display object supplies it. Both ABIs call geometry +0x50; // this is the whole-object transform, not the adjacent per-part slot. -#if defined(_MSC_VER) && defined(_M_IX86) +#if defined(_MSC_VER) +#if defined(_M_IX86) typedef void (__thiscall* SetTransformation)(void*, const Mat4&); #else typedef void (*SetTransformation)(void*, const Mat4&); #endif reinterpret_cast( - (*static_cast(m_geometry))[0x50 / sizeof(void*)])( + (*static_cast(m_geometry))[0x50 / 4])( m_geometry, Mat4::getZero()); +#else + geometry_part::setGeometryTransform(m_geometry, &Mat4::getZero()); // PE +0x50 +#endif } else { @@ -1514,12 +1507,22 @@ void GenericFireArm::postFire(FireState requestedState, { if (m_recoilComp) m_recoilComp->postFire(event); + // BF2.exe 0x5E2A98..0x5E2CDA (ledger N2 17b): without a recoil component, retail + // gives the local player's Falcon a "RecoilPunch" (kits, wrench); it needs a + // device (archived, Code/Archive/NovintFalcon). if (m_targetComp) m_targetComp->postFire(event); if (m_zoomComp) m_zoomComp->postFire(event); - if (ai::g_bfCollisionHandler && projectileObject) - gfaFrontier("postFire (AIDLL IBFCollisionHandler fire report)"); + // ELF 0x8251867: every real round is reported to the AI collision handler + // (+0x18). The IProjectileObject query is repeated, as compiled. + ai::IBFCollisionHandler* const collision = static_cast( + ai::CommonSingletonServer::m_iBFCollisionHandler); + if (collision && projectileObject) + collision->handleProjectileFire( + static_cast( + projectileObject->queryInterface(IID_IProjectileObject)), + projectileObject); } } diff --git a/Code/BF2/Game/Objects/Weapons/RecoilComponents/SoldierBasedRecoilComp.cpp b/Code/BF2/Game/Objects/Weapons/RecoilComponents/SoldierBasedRecoilComp.cpp index 61e76a0c9..b2e9d2055 100644 --- a/Code/BF2/Game/Objects/Weapons/RecoilComponents/SoldierBasedRecoilComp.cpp +++ b/Code/BF2/Game/Objects/Weapons/RecoilComponents/SoldierBasedRecoilComp.cpp @@ -195,7 +195,7 @@ float SoldierBasedRecoilComp::getRecoil(float recoil) // . The ancestor walk starts at the weapon's parent (not the weapon), // and the freshly calculated sample precedes both the ring advance and its tick write. -void SoldierBasedRecoilComp::postFire(WeaponFireEvent&) +void SoldierBasedRecoilComp::postFire(WeaponFireEvent& event) { IObject* soldierObject = 0; for (IObject* object = m_initObject->getParent(); object && !soldierObject; @@ -214,6 +214,8 @@ void SoldierBasedRecoilComp::postFire(WeaponFireEvent&) m_recoilTicks[m_currentRecoilIndex] = static_cast(WorldPref::getTickCount()); } + // BF2.exe 0x609318..0x609690 (ledger N2 17b) gives the local occupant's Falcon a "RecoilPunch" + // here; it needs a device (archived, Code/Archive/NovintFalcon). } void SoldierBasedRecoilComp::setZoom(int zoom) diff --git a/Code/BF2/Game/Objects/Weapons/RecoilComponents/WeaponBasedRecoilComp.cpp b/Code/BF2/Game/Objects/Weapons/RecoilComponents/WeaponBasedRecoilComp.cpp index 58866d1f0..26eec01af 100644 --- a/Code/BF2/Game/Objects/Weapons/RecoilComponents/WeaponBasedRecoilComp.cpp +++ b/Code/BF2/Game/Objects/Weapons/RecoilComponents/WeaponBasedRecoilComp.cpp @@ -229,7 +229,7 @@ void WeaponBasedRecoilComp::updateComponent(float, unsigned int) // , 493 B. Ordering is significant: wake/apply force and the // optional explosion precede the saved-relative-position snapshot and both timer writes; the PCO // walk and camera impulse come last. -void WeaponBasedRecoilComp::postFire(WeaponFireEvent&) +void WeaponBasedRecoilComp::postFire(WeaponFireEvent& event) { IObject* const root = getRootParent(m_initObject); const float force = m_weaponTemplate->getRecoilForce(); @@ -264,6 +264,9 @@ void WeaponBasedRecoilComp::postFire(WeaponFireEvent&) m_savedRelativePosition.z = transform.m[14]; } + // BF2.exe 0x60A077..0x60A4FE (ledger N2 17b) gives the local occupant's Falcon a "RecoilPunch" here, + // between the snapshot and the timers; it needs a device (archived, Code/Archive/NovintFalcon). + const unsigned int tick = static_cast(WorldPref::getTickCount()); const int recoilTicks = static_cast( (m_weaponTemplate->getRecoilSpeedPeriod() * kTicksPerSecond) * 0.5f); diff --git a/Code/BF2/Game/Objects/Weapons/TargetComponents/TargetComp.cpp b/Code/BF2/Game/Objects/Weapons/TargetComponents/TargetComp.cpp index cbf4abe5c..7665f5cd5 100644 --- a/Code/BF2/Game/Objects/Weapons/TargetComponents/TargetComp.cpp +++ b/Code/BF2/Game/Objects/Weapons/TargetComponents/TargetComp.cpp @@ -3,6 +3,7 @@ // cross-checked against the BF2 1.50 Win32 dedicated-server image. #include "TargetComp.h" +#include "../../GeometryPartAccess.h" // named geometry operations (non-MSVC) #include #include @@ -44,17 +45,18 @@ IPlayerControlObject* findPlayerControlObject(IObject* object) // IGeometry is not reconstructed far enough to name this slot yet. Both shipped x86 tables were // read: the same operation is ELF +0xD8 and PE +0xD4 (the Itanium destructor-pair shift). +// The slot follows the compiler's destructor ABI, so native MSVC x64 takes the PE arm too. void geometrySetConnectionEffect(void* geometry, int enabled) { -#if defined(_MSC_VER) && defined(_M_IX86) +#if defined(_MSC_VER) typedef void (__thiscall *Method)(void*, int); - const unsigned int slot = 0xD4 / sizeof(void*); -#else - typedef void (*Method)(void*, int); - const unsigned int slot = 0xD8 / sizeof(void*); -#endif + const unsigned int slot = 0xD4 / 4; void** const vtable = *reinterpret_cast(geometry); reinterpret_cast(vtable[slot])(geometry, enabled); +#else + // The same one-dword entry the renderer's MeshParticleMesh names setFirstPerson (ELF +0xD8). + geometry_part::setFirstPerson(geometry, static_cast(enabled)); +#endif } } // namespace diff --git a/Code/BF2/Game/Objects/Weapons/ZoomComponents/DefaultZoomComp.cpp b/Code/BF2/Game/Objects/Weapons/ZoomComponents/DefaultZoomComp.cpp index 8b5030e89..d28efc684 100644 --- a/Code/BF2/Game/Objects/Weapons/ZoomComponents/DefaultZoomComp.cpp +++ b/Code/BF2/Game/Objects/Weapons/ZoomComponents/DefaultZoomComp.cpp @@ -1,9 +1,13 @@ // Path: [INFERRED] from the recovered ZoomComponents family placement. // Contents: server-reachable DefaultZoomComp and complete DefaultZoomCompTemplate leaf recovered -// from ELF 0x829BED0..0x829D77A and cross-checked against PE 0x5A58xx..0x5A64xx. -// The client-only WeaponHud notification tail is the named frontier at changeZoom(). +// from ELF 0x829BED0..0x829D77A and cross-checked against PE 0x5A58xx..0x5A64xx +// (changeZoom: PE 0x606C20, ELF 0x829C2B0). #include "DefaultZoomComp.h" +#if defined(BF2_STATIC_PLUGINS) && !defined(_MSC_VER) +// [CHOSEN, not recovered] Native static geometry tables retain PE slot order. +#include "../../../../Geom/NativeGeometrySlots.h" +#endif #include #include @@ -13,6 +17,8 @@ #include "../../Game/Soldier.h" #include "../../IObject.h" #include "../../IPlayer.h" +#include "../../IWeaponHudComp.h" +#include "../../WeaponHudCompTemplate.h" // WeaponHudInfo::altGuiIndex #include "../../ObjectLayoutAccess.h" #include "../../GeometryPartAccess.h" #include "../../../../Core/EventManager.h" @@ -29,7 +35,8 @@ namespace { // geom::IGeometry is still unrecovered. This is the complete bounded surface used by DefaultZoom. // Its virtual destructor differs across the two retail ABIs, shifting every geometry slot after it. -#if defined(_MSC_VER) && defined(_M_IX86) +// The slots follow the compiler's destructor ABI, so native MSVC x64 takes the PE arm too. +#if defined(_MSC_VER) typedef int (__thiscall *GeometryGetIntFn)(void*); typedef void (__thiscall *GeometrySetLodFn)(void*, int); typedef void* (__thiscall *GeometryGetTemplateFn)(void*); @@ -38,17 +45,9 @@ const std::size_t kGeometryGetSubgeomSlot = 0x70 / 4; const std::size_t kGeometrySetLodSlot = 0x78 / 4; const std::size_t kGeometryGetLodSlot = 0x7C / 4; const std::size_t kGeometryGetLodCountSlot = 0x80 / 4; -#else -typedef int (*GeometryGetIntFn)(void*); -typedef void (*GeometrySetLodFn)(void*, int); -typedef void* (*GeometryGetTemplateFn)(void*); -const std::size_t kGeometryGetTemplateSlot = 0x3C / 4; -const std::size_t kGeometryGetSubgeomSlot = 0x74 / 4; -const std::size_t kGeometrySetLodSlot = 0x7C / 4; -const std::size_t kGeometryGetLodSlot = 0x80 / 4; -const std::size_t kGeometryGetLodCountSlot = 0x84 / 4; #endif +#if defined(_MSC_VER) void** geometryVtable(void* geometry) { return *reinterpret_cast(geometry); @@ -83,6 +82,14 @@ void* geometryGetTemplate(void* geometry) return reinterpret_cast( geometryVtable(geometry)[kGeometryGetTemplateSlot])(geometry); } +#else +// Non-MSVC: the named geometry_part operations (static native: Geom/NativeGeometrySlots.h). +int geometryGetSubgeom(void* geometry) { return geometry_part::getSubgeom(geometry); } +void geometrySetLod(void* geometry, int lod) { geometry_part::setLod(geometry, lod); } +int geometryGetLod(void* geometry) { return geometry_part::getLod(geometry); } +int geometryGetLodCount(void* geometry) { return geometry_part::getLodCount(geometry); } +void* geometryGetTemplate(void* geometry) { return geometry_part::getTemplate(geometry); } +#endif } // namespace @@ -377,12 +384,15 @@ void DefaultZoomComp::changeZoom(int camera, bool immediate) } } - // [FRONTIER] [RETIRE-WHEN: unrecovered-factories-registered] - // Retail's remaining arm reads the firearm's Object +0x5C WeaponHud component, calls its - // specialized +0x50 getter, tests the returned object's +0x18 field, and only then posts the - // zoom HUD event for a local first-person player. WeaponHud remains factory-dark under RW-6 - // and a dedicated server's is1P() is false, so the arm is unreachable in this slice. It must - // land with the typed WeaponHud interface rather than being mis-dispatched through an ELF slot. + // Tell the HUD to recompute its GUI index (ECHud 31, HudVehicleInformation::updateGuiIndex) + // when the weapon has an alternate index, so a zoomed rifle switches to its altGuiIndex HUD + // (no crosshair for the AK-101's 52). The WeaponHud component is read before is1P(), as in + // both images (PE 0x606CD1..0x606D06, ELF 0x829C350..0x829C39D); the same tail is inlined in + // the PE reload thunk at 0x606E7C. A dedicated server's is1P() is false. + IWeaponHudComp* const weaponHud = static_cast( + object_detail::LayoutAccess::weaponHudComponent(firearm())); + if (is1P() && weaponHud && weaponHud->getHudInfo()->altGuiIndex != -1) + eventManager->postEvent(ECHud, 31, this, 0.0f); } int DefaultZoomComp::getZoomLod() const diff --git a/Code/BF2/Game/Objects/Weapons/ZoomComponents/DefaultZoomComp.h b/Code/BF2/Game/Objects/Weapons/ZoomComponents/DefaultZoomComp.h index f2db9f30d..154b91f37 100644 --- a/Code/BF2/Game/Objects/Weapons/ZoomComponents/DefaultZoomComp.h +++ b/Code/BF2/Game/Objects/Weapons/ZoomComponents/DefaultZoomComp.h @@ -1,6 +1,6 @@ // Path: [INFERRED] beside the attested weapon-component families. // Contents: server-reachable DefaultZoom runtime and complete template leaf recovered from both -// shipped x86 ports; the client-only WeaponHud notification tail remains named in .cpp. +// shipped x86 ports, including the client-side WeaponHud notification in changeZoom. #ifndef GAME_OBJECTS_WEAPONS_ZOOMCOMPONENTS_DEFAULTZOOMCOMP_H #define GAME_OBJECTS_WEAPONS_ZOOMCOMPONENTS_DEFAULTZOOMCOMP_H diff --git a/Code/BF2/Game/PasswordCodec.cpp b/Code/BF2/Game/PasswordCodec.cpp index 1e754a94e..03de023f3 100644 --- a/Code/BF2/Game/PasswordCodec.cpp +++ b/Code/BF2/Game/PasswordCodec.cpp @@ -1,15 +1,23 @@ // [INFERRED] path. Full client PE66E7D0/5B0190/5B01C0/5B0400/5B0320/5B0260 read. #include "PasswordCodec.h" #if !DEDICATED +#if defined(_WIN32) #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include #include +#else +// [CHOSEN, not recovered] macOS: the DPAPI counterpart (docs/macos-port.md, "Protected profile +// data (DPAPI)"). The flow below is the shipped one; only the three API calls differ. +#include "../Platform/macOS/ProtectedData.h" +#endif #include #include #include #include +#if defined(_MSC_VER) #pragma comment(lib, "crypt32.lib") +#endif namespace dice { namespace hfe { @@ -21,7 +29,11 @@ PasswordCodec::PasswordCodec() // PE66E7D0 PasswordCodec::~PasswordCodec() // PE5B0190 { if (m_blob) { +#if defined(_WIN32) LocalFree(m_blob->pbData); +#else + macos::freeProtectedData(m_blob->pbData); +#endif delete m_blob; m_blob = 0; } @@ -31,18 +43,34 @@ bool PasswordCodec::encode(const std::string& plain) // PE5B01C0 { // The input blob is filled (terminator included) before the empty test, as shipped. DATA_BLOB input; +#if defined(_WIN32) input.pbData = (BYTE*)plain.c_str(); input.cbData = (DWORD)std::strlen(plain.c_str()) + 1; +#else + input.pbData = (unsigned char*)plain.c_str(); + input.cbData = (std::uint32_t)std::strlen(plain.c_str()) + 1; +#endif if (plain.size() == 0) return false; if (m_blob) { +#if defined(_WIN32) LocalFree(m_blob->pbData); +#else + macos::freeProtectedData(m_blob->pbData); +#endif delete m_blob; m_blob = 0; } m_blob = new DATA_BLOB; +#if defined(_WIN32) return CryptProtectData(&input, L"This is the description string.", 0, 0, 0, CRYPTPROTECT_UI_FORBIDDEN, m_blob) != 0; +#else + // A failed protect leaves the blob empty, as a failed CryptProtectData does. + m_blob->cbData = 0; + m_blob->pbData = 0; + return macos::protectData(input.pbData, input.cbData, m_blob); +#endif } void PasswordCodec::write(std::ostream& stream) // PE5B0400 @@ -54,7 +82,7 @@ void PasswordCodec::write(std::ostream& stream) // PE5B0400 void PasswordCodec::readHexPairs(const std::string& text, unsigned char* out) // PE5B0260 { - const unsigned int count = text.size() >> 1; + const unsigned int count = static_cast(text.size() >> 1); // a 32-bit count, as in the image std::stringstream unused(std::ios::in | std::ios::out); // constructed and never used (retail) std::istringstream reader(text); for (unsigned int i = 0; i < count; ++i) { @@ -68,8 +96,10 @@ void PasswordCodec::readHexPairs(const std::string& text, unsigned char* out) // bool PasswordCodec::decode(std::string& text) // PE5B0320 { - const unsigned int count = text.size() >> 1; + const unsigned int count = static_cast(text.size() >> 1); // a 32-bit count, as in the image +#if defined(_WIN32) LPWSTR description = 0; +#endif if (!count) return false; unsigned char* bytes = new unsigned char[count]; @@ -78,6 +108,11 @@ bool PasswordCodec::decode(std::string& text) // PE5B0320 input.pbData = bytes; input.cbData = count; DATA_BLOB output; +#if !defined(_WIN32) + output.cbData = 0; + output.pbData = 0; +#endif +#if defined(_WIN32) if (CryptUnprotectData(&input, &description, 0, 0, 0, CRYPTPROTECT_UI_FORBIDDEN, &output)) { text = std::string((const char*)output.pbData); LocalFree(description); @@ -85,6 +120,21 @@ bool PasswordCodec::decode(std::string& text) // PE5B0320 LocalFree(output.pbData); return true; } +#else + // The plain text carries its terminator (encode protects it), so it is read as a C string. + if (macos::unprotectData(input.pbData, input.cbData, &output) && output.cbData + && output.pbData[output.cbData - 1] == 0) { + text = std::string((const char*)output.pbData); + delete[] bytes; + macos::freeProtectedData(output.pbData); + return true; + } + if (output.pbData) + macos::freeProtectedData(output.pbData); + // As shipped, `bytes` is not freed on failure; there is no system message to format. + return false; +#endif +#if defined(_WIN32) // The system message is formatted and released without being shown; `bytes` is not freed. const DWORD error = GetLastError(); LPSTR message = 0; @@ -93,6 +143,7 @@ bool PasswordCodec::decode(std::string& text) // PE5B0320 0, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&message, 0, 0)) LocalFree(message); return false; +#endif } } } diff --git a/Code/BF2/Game/Persistence/HTTPRequest.cpp b/Code/BF2/Game/Persistence/HTTPRequest.cpp index 5d97041eb..9cac28930 100644 --- a/Code/BF2/Game/Persistence/HTTPRequest.cpp +++ b/Code/BF2/Game/Persistence/HTTPRequest.cpp @@ -1,6 +1,7 @@ // Path: attested by the Win32 __FILE__ at the URL-validation diagnostic. // Contents: ELF 0x82BDED0..0x82BE8B0 / PE 0x560F00..0x5617D0, read in both ports. #include "HTTPRequest.h" +#include "../MatchMaking/OnlineProvider.h" // [CHOSEN, not recovered] the services' domain #include "../../External/GameSpy/ghttp/ghttp.h" #include "../../Core/Debug.h" #include @@ -144,8 +145,10 @@ void HTTPRequest::onProgress(float) {} // Shipped empty: ELF 0x82BE7F0 / PE 0x56 int HTTPRequest::getRevision() { return m_revision; } bool HTTPRequest::validateUrlNotSpoofed(std::string host) const { - // [PLATFORM] ELF 0x82BE8A0 returns true. PE 0x561500 scans the hosts file, - // emits a type-7 diagnostic on a mismatch, and still returns true. + // [PLATFORM] ELF 0x82BE8A0 returns true. BF2.exe 0x59C670 and bf2_w32ded.exe 0x561500 scan + // the hosts file and emit a type-7 diagnostic (which ends the process) for a line that names + // the host without an address in 212.77.171.x; they return true. Recovered but not called: + // see getGameSpyUrl. #if defined(_WIN32) char path[260] = {}; GetSystemDirectoryA(path, 260); @@ -170,13 +173,19 @@ bool HTTPRequest::validateUrlNotSpoofed(std::string host) const } std::string HTTPRequest::getGameSpyUrl() const { - // [CHOSEN, not recovered] Cross-platform OpenSpy policy, see #21. The reference - // images used BF2Web.gamespy.com (PE) and BF2Web.game.bf2.us (ELF), not openspy.net. - std::string url("http://BF2Web.bf2hub.p.bf2.org/ASP/"); - validateUrlNotSpoofed("BF2Web.bf2hub.p.bf2.org"); + // Retail: "http://BF2Web.gamespy.com/ASP/" and validateUrlNotSpoofed("BF2Web.gamespy.com") in + // BF2.exe (0x59C8C0), bf2_w32ded.exe (0x561760) and the 1.5.3153.0 Linux ELFs (ia-32 + // 0x82BE800). + // The ELF this file was first read from had BF2Web.game.bf2.us in the same two places. + // [CHOSEN, not recovered] The domain is onlineProvider's: gamespy.com unless +gamespy + // replaced it. The validateUrlNotSpoofed call is skipped on every platform: retail's Windows + // hosts-file check (BF2.exe 0x59C670, bf2_w32ded.exe 0x561500) accepts only GameSpy's own + // address block 212.77.171.x and otherwise ends the process (Debug type 7), and the hosts file + // is a normal way to point these names at a replacement service. + std::string url(onlineProvider::statsWebUrl()); // [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: local-stats-fixture] - // BF2_STATS_URL overrides persistence URLs for local fixtures after validating the - // original URL. Inactive when unset; announces activation once on stderr. + // BF2_STATS_URL overrides persistence URLs for local fixtures. Inactive when unset; announces + // activation once on stderr. if (const char* fixture = std::getenv("BF2_STATS_URL")) { if (*fixture) diff --git a/Code/BF2/Game/Persistence/PlayerStatsManager.cpp b/Code/BF2/Game/Persistence/PlayerStatsManager.cpp index b7debb874..7375b973f 100644 --- a/Code/BF2/Game/Persistence/PlayerStatsManager.cpp +++ b/Code/BF2/Game/Persistence/PlayerStatsManager.cpp @@ -2,17 +2,17 @@ // Preserve duplicated keys and the original spelling/type quirks. #include "PlayerStatsManager.h" +#include "../MatchMaking/OnlineProvider.h" // [CHOSEN, not recovered] the services' domain #include "../../Core/Ids.h" #include "../../Core/StringUtil.h" #include "../../External/GameSpy/ghttp/ghttp.h" #include namespace dice { namespace hfe { -namespace { -// [CHOSEN, not recovered] Cross-platform OpenSpy policy, see #21. The reference images -// (ELF static init 0x82F53D0 / PE 0x76F7B0) used stage-net.game.bf2.us (ELF) and -// stage-net.gamespy.com (PE), not openspy.net. -const std::string playerInfoUrl = "http://stage-net.bf2hub.p.bf2.org/bf2/getplayerinfo.aspx?pid="; -} +// Retail keeps "http://stage-net.gamespy.com/bf2/getplayerinfo.aspx?pid=" in a namespace-scope +// string (ELF static init 0x82F53D0 / PE 0x76F7B0; BF2.exe, bf2_w32ded.exe and the 1.5.3153.0 +// Linux ELFs; the ELF this file was first read from had stage-net.game.bf2.us). +// [CHOSEN, not recovered] update() asks onlineProvider for it instead, so that the domain +// follows +gamespy; without the option the URL is retail's. GHTTPBool cbCompleted(GHTTPRequest, GHTTPResult result, char* body, GHTTPByteCount, void* data) { IPlayerStatsManager* manager = static_cast(data); @@ -249,7 +249,7 @@ bool PlayerStatsManager::isUpdating() { return m_updating; } bool PlayerStatsManager::update() { if (!isConnected() || isUpdating()) return false; - const std::string url = playerInfoUrl + m_profile + m_query; + const std::string url = onlineProvider::playerInfoUrl() + m_profile + m_query; if (ghttpGetA(url.c_str(), GHTTPFalse, cbCompleted, this) < 0) return false; m_updating = true; return true; diff --git a/Code/BF2/Game/Persistence/StatsManager.cpp b/Code/BF2/Game/Persistence/StatsManager.cpp index 90af429f9..205ec0ad2 100644 --- a/Code/BF2/Game/Persistence/StatsManager.cpp +++ b/Code/BF2/Game/Persistence/StatsManager.cpp @@ -1,5 +1,6 @@ // Path: [INFERRED]. See StatsManager.h for the paired evidence. #include "StatsManager.h" +#include "../MatchMaking/OnlineProvider.h" // [CHOSEN, not recovered] the services' domain #include "../../Core/Ids.h" #include "../../Core/StringUtil.h" #include "../IGame.h" @@ -37,7 +38,10 @@ bool StatsManager::connect() const int port = serverSettings->m_gameSpyPort; std::strcpy(gcd_gamename, gamespy::g_gameName); std::strcpy(gcd_secret_key, gamespy::getSecretKey()); - std::strcpy(StatsServerHostname, "gamestats.bf2hub.p.bf2.org"); // gamespy.com|openspy.net + // Retail copies "gamestats.gamespy.com" (ELF 0x82F8F50, bf2_w32ded.exe 0x5C7E50, BF2.exe the + // reference at 0x46C7CE). [CHOSEN, not recovered] The domain is onlineProvider's: gamespy.com + // unless +gamespy replaced it. + std::strcpy(StatsServerHostname, onlineProvider::gameStatsServerName().c_str()); return InitStatsConnection(port) == 0; } void StatsManager::disconnect() diff --git a/Code/BF2/Game/ProfileManager.cpp b/Code/BF2/Game/ProfileManager.cpp index 8d0f52337..40f1aa625 100644 --- a/Code/BF2/Game/ProfileManager.cpp +++ b/Code/BF2/Game/ProfileManager.cpp @@ -270,6 +270,17 @@ void profileManagerGPIgnore(GPConnection* /*connection*/, void* /*arg*/, void* / { } +// 0x4A5B80 - the gpSuggestUniqueNick callback requestNickSuggestions installs. `param` is the +// owner's suggestion vector; one entry is appended per suggested nick (push_back 0x450C10). The +// result field is not read: a failed request answers zero suggestions. +void profileManagerGPSuggestions(GPConnection* /*connection*/, void* arg, void* param) +{ + const GPSuggestUniqueNickResponseArg* response = static_cast(arg); + std::vector* suggestions = static_cast*>(param); + for (int i = 0; i < response->numSuggestedNicks; ++i) + suggestions->push_back(std::string(response->suggestedNicks[i])); +} + } // namespace // the connection's own error text, or "general error" when it is empty. @@ -694,22 +705,127 @@ bool ProfileManager::getProfileInformation(int profileId, ProfileInformation& ou return true; } -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: profile-manager-account-operations] -// All parameters and returns below are proved by complete PE bodies/callers. -// Their account/GP callback bodies remain visible stops under the client startup -// publication exception. No fabricated account state or successful login is returned. -#define PROFILE_MANAGER_FRONTIER(method) \ - std::fprintf(stderr, "[FRONTIER] dice::hfe::ProfileManager::" #method " reached\n"); \ - std::fflush(stderr); \ - std::abort() +// Adds a GameSpy profile (unique nick) to the logged-in account. PE 0x4A6EB0. +// Refuses without a current profile, or with a nick the host's validator rejects (posted as a +// type-3 message when the host exists). Otherwise the account's e-mail and password are copied, the +// current unique nick remembered, and the session ended (logout). A fresh connection then creates +// the new profile with gpConnectNewUser; on success it becomes the current profile exactly as +// createOnlineAccount's does. On failure the error is reported and the old unique nick logs in +// again; when that also fails the host gets the profile-transition text. +bool ProfileManager::createProfile(const std::string& uniqueNick, const std::string& country) +{ + if (!m_currentProfile) + return false; + IBase* host = classManager->getSingleton(std::string("SwiffHost")); // kept for the end, unguarded + std::string error; + if (!validateProfileName(uniqueNick, error)) // virtual +0x54 + { + IBase* validatorHost = classManager->getSingleton(std::string("SwiffHost")); + if (validatorHost) + static_cast(validatorHost)->postMessage(SwiffHostMessage(3, error, 3)); // +0x1E4 + return false; + } + std::string previousUniqueNick; + std::string password(m_currentProfile->password); // record +0x1C + std::string email(m_currentProfile->email); // record +0x00 + getUniqueNick(previousUniqueNick); // virtual +0x34 + logout(); // virtual +0x28 + bool created = false; + int profileId; // written by the callback only + if (gpInitialize(&m_connection, kGameSpyProductId, kGameSpyNamespaceId, GP_PARTNERID_GAMESPY) != GP_NO_ERROR) + reportError(std::string("serveroffline"), true); + else + { + gpSetCallback(&m_connection, GP_ERROR, &profileManagerGPError, this); + if (gpConnectNewUser(&m_connection, uniqueNick.c_str(), uniqueNick.c_str(), email.c_str(), + password.c_str(), NULL, GP_NO_FIREWALL, GP_BLOCKING, + &profileManagerGPProfileId, &profileId) != GP_NO_ERROR) + reportError(lastErrorString(), false); + else + created = true; + } + if (!created) + { + // 0x4A7016: the shared failure tail - log out again and restore the previous profile. + logout(); // virtual +0x28 + if (!login(previousUniqueNick, password)) // virtual +0x14 + static_cast(host)->handleProfileTransition( + std::string("Connection to profile server lost.")); // +0x244 + return false; + } + createStatsPlayer(profileId, country, uniqueNick); // result unread + setCurrentProfile(email, password, profileId, uniqueNick); + fetchProfileList(m_currentProfile->profiles); + static_cast(host)->setSelectedPlayerId(profileId); // +0x220, unguarded + return true; +} -bool ProfileManager::createProfile(const std::string&, const std::string&) -{ PROFILE_MANAGER_FRONTIER(createProfile); } +// Deletes the current GameSpy profile. PE 0x4A54B0. +// Refuses without a current profile, and with fewer than two profiles on the account (an +// untranslated type-1 message). The first other profile is remembered, gpDeleteProfile is issued +// with a no-op callback (0x5AB2A0), and on success the session ends and that other profile logs in +// (by its nick, entry +4, as shipped). When the login fails the host gets the transition text. bool ProfileManager::deleteProfile() -{ PROFILE_MANAGER_FRONTIER(deleteProfile); } -bool ProfileManager::requestNickSuggestions(const std::string&) -{ PROFILE_MANAGER_FRONTIER(requestNickSuggestions); } -#undef PROFILE_MANAGER_FRONTIER +{ + if (!m_currentProfile) + return false; + if (m_currentProfile->profiles.size() <= 1) + { + reportError(std::string("Unable to delete profile, you must have at least 1 profile"), false); + return false; + } + IBase* host = classManager->getSingleton(std::string("SwiffHost")); // unguarded below + const std::string email(m_currentProfile->email); // copied and never read + std::string password(m_currentProfile->password); + (void)email; + OnlineProfileEntry other; + other.profileId = 0; + // The size is re-read on each pass; the loop stops at the first entry that is not the + // current profile id (record +0x48). + for (std::size_t index = 0; index < m_currentProfile->profiles.size(); ++index) + { + if (m_currentProfile->profiles[index].profileId != m_currentProfile->profileId) + { + other.profileId = m_currentProfile->profiles[index].profileId; + other.nick = m_currentProfile->profiles[index].nick; + other.uniqueNick = m_currentProfile->profiles[index].uniqueNick; + break; + } + } + if (gpDeleteProfile(&m_connection, &profileManagerGPIgnore, &other) != GP_NO_ERROR) + { + reportError(lastErrorString(), false); + return false; + } + logout(); // virtual +0x28 + if (!login(other.nick, password)) // virtual +0x14 + { + static_cast(host)->handleProfileTransition( + std::string("Connection to profile server lost.")); // +0x244 + return false; + } + return true; +} + +// Fetches unique-nick suggestions for `nick` into the owner's list. PE 0x4A5BD0. +// The list is emptied and its buffer released first. The request runs on a private, +// short-lived connection; a failed initialisation reports the OWNER connection's error text (the +// shipped body reads this+0x0C, not the local connection) and answers false. The suggestion +// request's own result is not read, and the answer is then true. +bool ProfileManager::requestNickSuggestions(const std::string& nick) +{ + std::vector().swap(m_nickSuggestions); // 0x445E70 + GPConnection connection; + if (gpInitialize(&connection, kGameSpyProductId, kGameSpyNamespaceId, GP_PARTNERID_GAMESPY) != GP_NO_ERROR) + { + reportError(lastErrorString(), false); + return false; + } + gpSuggestUniqueNick(&connection, nick.c_str(), GP_BLOCKING, &profileManagerGPSuggestions, + &m_nickSuggestions); + gpDestroy(&connection); + return true; +} } } #endif diff --git a/Code/BF2/Game/PunkBuster/PbClient.cpp b/Code/BF2/Game/PunkBuster/PbClient.cpp new file mode 100644 index 000000000..14fefbbd3 --- /dev/null +++ b/Code/BF2/Game/PunkBuster/PbClient.cpp @@ -0,0 +1,294 @@ +// PunkBuster client glue, BF2.exe 0x435900..0x436434 (client image only). [INFERRED] path and names; +// the ELF dedicated server carries only the server half (stPbSv), whose structure this mirrors. +#include "PbClient.h" +#include "PbGlue.h" +#include +#include +#include +#include +#if defined(_WIN32) +#include +#include +#include +#else +#include +#include +#include +#endif + +namespace { +const char kNotInstalled[] = "PunkBuster Client Not Installed"; // ds:0x893BC8 +const char kLoadFailure[] = "PB Error: Client DLL Load Failure"; // ds:0x893B7C +const char kProcFailure[] = "PB Error: Client DLL Get Procedure Failure"; // ds:0x893B48 + +#if defined(_WIN32) +void* loadLibrary(const char* path) { return reinterpret_cast(LoadLibraryA(path)); } +void* librarySymbol(void* library, const char* name) +{ + return reinterpret_cast(GetProcAddress(static_cast(library), name)); +} +void releaseLibrary(void* library) { FreeLibrary(static_cast(library)); } +int changeMode(const char* path, int mode) { return _chmod(path, mode); } +char* currentDirectory(char* buffer, int size) { return _getcwd(buffer, size); } +int compareNoCase(const char* a, const char* b) { return _stricmp(a, b); } +#else +void releaseLibrary(void*) {} +int changeMode(const char* path, int mode) { return chmod(path, static_cast(mode)); } +char* currentDirectory(char* buffer, int size) { return getcwd(buffer, static_cast(size)); } +int compareNoCase(const char* a, const char* b) { return strcasecmp(a, b); } +#endif +} // namespace + +#if defined(_WIN32) +PbClientLibraryApi g_pbClientLibrary = { loadLibrary, librarySymbol, releaseLibrary }; +#else +PbClientLibraryApi g_pbClientLibrary = { 0, 0, releaseLibrary }; +#endif + +// The static image (ds:0x96E5A8..0x96E753): magic, the reload request, the prefix and state 999. +stPbCl pbcl = { 0x264B8BABu, 0, 0, 0, 1, { 0 }, "PunkBuster Client", { 0 }, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 999 }; +void* pbClientInstance = 0; // ds:0x99EF74, PbClientInitialize's argument [INFERRED] name + +namespace { +// The exit destructor (0x873420): entry points cleared, both libraries released. +struct PbClientExit { + ~PbClientExit() + { + pbcl.m_dllProcess = 0; + pbcl.m_dllEvent = 0; + pbcl.m_dllHook198 = 0; + pbcl.m_dllHook19C = 0; + pbcl.m_consoleHook = 0; + if (pbcl.m_library) { g_pbClientLibrary.release(pbcl.m_library); pbcl.m_library = 0; } + if (pbcl.m_library2) { g_pbClientLibrary.release(pbcl.m_library2); pbcl.m_library2 = 0; } + } +} s_pbClientExit; + +// 0x435900: "\pb\", or the working directory's when the game answers nothing. +void fillPath(stPbCl* pb) +{ + if (!pb->m_gameQuery) return; + std::strcpy(pb->m_path, "fs_homepath"); + pb->m_gameQuery(0x67, pb->m_path); + if (!pb->m_path[0]) currentDirectory(pb->m_path, 0xFF); + if (pb->m_path[0] && pb->m_path[std::strlen(pb->m_path) - 1] != '\\') std::strcat(pb->m_path, "\\"); + std::strcat(pb->m_path, "pb\\"); +} + +// 0x4359A0 +char* makeFileName(stPbCl* pb, char* out, const char* name) +{ + if (!pb->m_path[0]) fillPath(pb); + std::strcpy(out, pb->m_path); + std::strcat(out, name); + return out; +} + +// 0x435A00 +void unloadDll(stPbCl* pb) +{ + pb->m_dllProcess = 0; + pb->m_dllEvent = 0; + pb->m_dllHook198 = 0; + pb->m_dllHook19C = 0; + pb->m_consoleHook = 0; + if (pb->m_library) { + g_pbClientLibrary.release(pb->m_library); + pb->m_library = 0; + } +} + +// 0x435A40: install a downloaded pbclnew.dll as pbcl.dll (keeping pbclold.dll), then load it. +const char* loadDll(stPbCl* pb) +{ + if (pb->m_library) return 0; + pb->m_dllProcess = 0; + pb->m_dllEvent = 0; + pb->m_dllHook198 = 0; + pb->m_dllHook19C = 0; + pb->m_consoleHook = 0; + // [CHOSEN, not recovered] No vendor DLL outside Windows: fail as a missing pbcl.dll would, + // before any file in the pb folder is touched. + if (!g_pbClientLibrary.load) return kLoadFailure; + char a[0x200], b[0x200]; + if (FILE* fresh = std::fopen(makeFileName(pb, a, "pbclnew.dll"), "rb")) { + std::fclose(fresh); + changeMode(makeFileName(pb, a, "pbclold.dll"), 0x180); + std::remove(makeFileName(pb, a, "pbclold.dll")); + std::rename(makeFileName(pb, a, "pbcl.dll"), makeFileName(pb, b, "pbclold.dll")); + changeMode(makeFileName(pb, a, "pbcl.dll"), 0x180); + std::remove(makeFileName(pb, a, "pbcl.dll")); + std::rename(makeFileName(pb, a, "pbclnew.dll"), makeFileName(pb, b, "pbcl.dll")); + } + pb->m_library = g_pbClientLibrary.load(makeFileName(pb, a, "pbcl.dll")); + if (!pb->m_library) return kLoadFailure; + pb->m_dllProcess = reinterpret_cast(g_pbClientLibrary.symbol(pb->m_library, "ca")); + pb->m_dllEvent = reinterpret_cast(g_pbClientLibrary.symbol(pb->m_library, "cb")); + if (!pb->m_dllProcess || !pb->m_dllEvent) { + unloadDll(pb); + return kProcFailure; + } + pb->m_reload = 0; + return 0; +} + +// The first failed load shows the not-installed notice once (state 999 -> 0). +void notifyNotInstalled(stPbCl* pb) +{ + if (pb->m_state == 999) { + pb->m_state = 0; + pb->m_gameMessage(const_cast(kNotInstalled), 1); + } +} + +// 0x436320 +char* addPbEvent(stPbCl* pb, int type, int a, char* b, int c) +{ + if (!pb->m_gameCommand || !pb->m_state) return 0; + if (pb->m_reload || !pb->m_library) { + if (pb->m_library) { + unloadDll(pb); + return 0; + } + const char* error = loadDll(pb); + if (error) { + if (type == 0x71 || type == 0x72) return 0; + notifyNotInstalled(pb); + return const_cast(error); + } + } + return reinterpret_cast(static_cast(pb->m_dllEvent(pb, type, a, b, c))); +} + +// 0x4363E0 +int processPbEvents(stPbCl* pb, int argument) +{ + if (!pb->m_gameCommand || !pb->m_state) return 0; + if (!pb->m_library) { + if (pb->m_reload) addPbEvent(pb, 0x10, 0, const_cast(""), 0); + return 0; + } + if (pb->m_reload) { + unloadDll(pb); + return 0; + } + return pb->m_dllProcess(pb, argument); +} + +// Shared shape of 0x436060 and 0x436220: with the game callbacks installed and the glue enabled, +// (re)load as needed and send `type` to the DLL (initialize passes "", connect a null pointer). +void sendLifecycleEvent(stPbCl* pb, int type, char* data) +{ + if (!pb->m_gameCommand || !pb->m_state) return; + if (pb->m_reload) { + if (pb->m_library) { + unloadDll(pb); + return; + } + } else if (pb->m_library) { + pb->m_dllEvent(pb, type, 0, data, 0); + return; + } + if (loadDll(pb)) { + if (pb->m_state != 999) return; + pb->m_state = 0; + pb->m_gameMessage(const_cast(kNotInstalled), 1); + return; + } + pb->m_dllEvent(pb, type, 0, data, 0); +} + +// ---- the game callbacks handed to pbcl.dll ------------------------------------------------------ +// 0x435C50: the DLL's game commands; only set_cl_punkbuster is honoured. (Retail also walks the +// argument past its first word and discards the result.) +int gameCommand(char* command, char* args) +{ + if (!compareNoCase(command, "set_cl_punkbuster")) PB_set_cl_punkbuster(std::atoi(args)); + return 0; +} + +// 0x435CC0: the DLL's queries, answered into its 256-byte buffer. +int gameQuery(int type, char* buffer) +{ + if (!buffer) return 0; + buffer[0xFF] = 0; + const char* value; + switch (type) { + case 0x67: + if (!compareNoCase(buffer, "fs_homepath")) value = PB_homepath(); + else if (!compareNoCase(buffer, "fs_basepath")) value = PB_basepath(); + else if (!compareNoCase(buffer, "version")) value = PB_getVersion(); + else value = PB_examineSetting(buffer); + break; + case 0x68: + value = PB_examineSetting(buffer); + break; + case 0x69: + value = PB_examineSetting(const_cast("server")); + break; + default: + buffer[0] = 0; + buffer[0xFF] = 0; + return 0; + } + std::strncpy(buffer, value, 0xFF); + buffer[0xFF] = 0; + return 0; +} + +// 0x435DD0: ": \n" to the game's output (the flag is unused). +int gameMessage(char* text, int) +{ + char line[0x801]; // [CHOSEN] one byte past retail's 0x800, which the final "\n" can overrun + std::strcpy(line, pbcl.m_gameName); + std::strcat(line, ": "); + const std::size_t used = std::strlen(line); + std::strncpy(line + used, text, 0x7FF - used); + line[0x7FF] = 0; + std::strcat(line, "\n"); + PB_outputText(line); + return 0; +} + +int sendToServer(int length, char* data) { PB_cl_sendToServer(data, length); return 0; } // 0x435EA0 +int sendUdp(char* address, unsigned short port, int length, char* data) // 0x435EB0 +{ + PB_sendUDPPacket(address, port, data, length); + return 0; +} +int callback194(char* text) { return PB_GlQuery(text); } // 0x435DC0 +} // namespace + +// ---- entry points -------------------------------------------------------------------------------- +// 0x436060: record the instance, hand over the callbacks and send the initialize event (0x10); +// without a loaded DLL the profile's cl_punkbuster is switched off. +void PbClientInitialize(void* instance) +{ + pbClientInstance = instance; + pbcl.m_serverGlue = PbServerGlueObject(); + pbcl.m_gameCommand = gameCommand; + pbcl.m_gameQuery = gameQuery; + pbcl.m_gameMessage = gameMessage; + pbcl.m_sendToServer = sendToServer; + pbcl.m_sendUdp = sendUdp; + pbcl.m_callback194 = callback194; + sendLifecycleEvent(&pbcl, 0x10, const_cast("")); + if (!pbcl.m_library) PB_set_cl_punkbuster(0); +} + +// 0x436220: the connect event (0x75), sent right after initialize when the server runs PunkBuster. +void PbClientConnect() { sendLifecycleEvent(&pbcl, 0x75, 0); } + +// 0x436000 +char* PbClAddEvent(int type, int length, char* data) { return addPbEvent(&pbcl, type, length, data, 0); } + +// 0x436020: a PB_ console command for the DLL, then the DLL's own console hook if it set one. +void PbClientTrapConsole(char* command, int length) +{ + addPbEvent(&pbcl, 0x0E, length, command, 0); + if (pbcl.m_consoleHook) pbcl.m_consoleHook(&pbcl, command, length); +} + +// 0x436150: the per-frame pump. +void PbClientProcessEvents() { processPbEvents(&pbcl, 0); } diff --git a/Code/BF2/Game/PunkBuster/PbClient.h b/Code/BF2/Game/PunkBuster/PbClient.h new file mode 100644 index 000000000..712d51345 --- /dev/null +++ b/Code/BF2/Game/PunkBuster/PbClient.h @@ -0,0 +1,55 @@ +// The PunkBuster client glue object (BF2.exe ds:0x96E5A8). [INFERRED] type name after the ELF's server +// counterpart stPbSv. pbcl.dll receives a pointer to it and reads the callbacks at their x86 offsets, so +// the x86 layout is the ABI. +#ifndef GAME_PUNKBUSTER_PBCLIENT_H +#define GAME_PUNKBUSTER_PBCLIENT_H +#include + +struct stPbCl; +// The vendor DLL's two entry points and the game callbacks it is handed (all cdecl). +typedef int (*PbClEventFn)(stPbCl*, int type, int a, char* b, int c); // "cb" +typedef int (*PbClProcessFn)(stPbCl*, int); // "ca" + +struct stPbCl { + unsigned int m_magic; // +0x00 0x264B8BAB in the static image + int m_unresolved04; // +0x04 [UNRESOLVED] + void* m_library; // +0x08 pbcl.dll + void* m_library2; // +0x0C freed only at exit (0x873463) [UNRESOLVED] + int m_reload; // +0x10 1 in the static image: the next event (re)loads + char m_md5[0x21]; // +0x14 [UNRESOLVED] use (an unreferenced md5 helper writes it) + char m_gameName[0x20]; // +0x35 "PunkBuster Client", the message prefix + char m_path[0x123]; // +0x55 "\pb\" (makefn's base) + int (*m_gameCommand)(char* command, char* args); // +0x178 0x435C50 + int (*m_gameQuery)(int type, char* buffer); // +0x17C 0x435CC0 + int (*m_gameMessage)(char* text, int flag); // +0x180 0x435DD0 + int (*m_sendToServer)(int length, char* data); // +0x184 0x435EA0 + PbClEventFn m_dllEvent; // +0x188 GetProcAddress "cb" + PbClProcessFn m_dllProcess; // +0x18C GetProcAddress "ca" + int (*m_sendUdp)(char* address, unsigned short port, int length, char* data); // +0x190 0x435EB0 + int (*m_callback194)(char*); // +0x194 0x435DC0 + void* m_dllHook198; // +0x198 written by the DLL [UNRESOLVED] + void* m_dllHook19C; // +0x19C written by the DLL [UNRESOLVED] + void (*m_consoleHook)(stPbCl*, char* command, int length); // +0x1A0 written by the DLL; console trap + void* m_serverGlue; // +0x1A4 &stPbSv (ds:0x96E758) + int m_state; // +0x1A8 999 until the not-installed notice +}; +#if defined(_M_IX86) +static_assert(offsetof(stPbCl, m_gameName) == 0x35 && offsetof(stPbCl, m_path) == 0x55, "pbcl ABI"); +static_assert(offsetof(stPbCl, m_gameCommand) == 0x178 && offsetof(stPbCl, m_dllEvent) == 0x188, "pbcl ABI"); +static_assert(offsetof(stPbCl, m_consoleHook) == 0x1A0 && offsetof(stPbCl, m_state) == 0x1A8, "pbcl ABI"); +#endif + +extern stPbCl pbcl; // ds:0x96E5A8 + +// [CHOSEN, not recovered] Library seam. Windows: LoadLibraryA / GetProcAddress / FreeLibrary, as +// retail. Elsewhere load is null: no vendor DLL exists, so the glue reports the load failure without +// touching the pb folder (the macOS client never writes into the game folder). The fake-DLL test +// installs its own functions. +struct PbClientLibraryApi { + void* (*load)(const char* path); + void* (*symbol)(void* library, const char* name); + void (*release)(void* library); +}; +extern PbClientLibraryApi g_pbClientLibrary; + +#endif diff --git a/Code/BF2/Game/PunkBuster/PbCommandHook.cpp b/Code/BF2/Game/PunkBuster/PbCommandHook.cpp new file mode 100644 index 000000000..c66780539 --- /dev/null +++ b/Code/BF2/Game/PunkBuster/PbCommandHook.cpp @@ -0,0 +1,19 @@ +// The console pre-dispatch hook for PunkBuster commands, BF2.exe 0x402FD0 / ELF 0x812E690 +// (HandleCommandHookPB). Compiled into every image; the dedicated ELF has only the server arm. +// [CHOSEN, not recovered] placement: see PbGlue.h. +#include "PbGlue.h" +#include + +bool HandleCommandHookPB(const char* command, int length) +{ + if (length < 3 || std::toupper(command[0]) != 'P' || std::toupper(command[1]) != 'B' || command[2] != '_') + return false; + if (length >= 6 && std::toupper(command[3]) == 'S' && std::toupper(command[4]) == 'V' && command[5] == '_') { + PbServerTrapConsole(const_cast(command), length); + return true; + } +#if !DEDICATED + PbClientTrapConsole(const_cast(command), length); +#endif + return true; +} diff --git a/Code/BF2/Game/PunkBuster/PbGame.cpp b/Code/BF2/Game/PunkBuster/PbGame.cpp new file mode 100644 index 000000000..cd1bd1b50 --- /dev/null +++ b/Code/BF2/Game/PunkBuster/PbGame.cpp @@ -0,0 +1,350 @@ +// BF2-side PunkBuster game functions, BF2.exe 0x4D94D0..0x4DA49B and the ELF dedicated server +// 0x84F7340..0x84F8A90 (whose symbols give the names). They answer the glues' queries and carry their +// traffic. One body for both images; the dedicated image has no client glue, so it lacks +// PB_cl_sendToServer, the client forward in PB_handlePacket and the "team" setting, and its PB_homepath +// reads GSPunkBusterPath. [INFERRED] path. +#include "PbGlue.h" +#include "../IGame.h" +#include "../IGameClient.h" +#include "../IGameServer.h" +#include "../Objects/IPlayer.h" +#include "../MatchMaking/Server/MatchMakingServer.h" +#include "../GameServer/ServerSettings.h" +#include "../Utility/BuildNrUtil.h" +#include "../../Core/Ids.h" +#include "../../Core/SettingsRepostitory.h" +#include "../../IO/Console/Console.h" +#include "../../IO/File/FileManager.h" +#include "../../IO/Network/NetworkLayer/Socket/UDPSocket.h" +#include "../../Scene/Object/PlayerManager.h" +#include +#include +#include +#include +#include +#if defined(_WIN32) +#include +#else +#include +#include +#endif + +using namespace dice::hfe; + +// GameSpy CD-key hash lookup (External/GameSpy/gcdkey), declared narrowly as GameServer.cpp does. +extern "C" char* gcd_getkeyhash(int gameid, int localid); + +namespace { +#if defined(_WIN32) +char* currentDirectory(char* buffer, int size) { return _getcwd(buffer, size); } +int compareNoCaseN(const char* a, const char* b, std::size_t n) { return _strnicmp(a, b, n); } +int compareNoCase(const char* a, const char* b) { return _stricmp(a, b); } +#else +char* currentDirectory(char* buffer, int size) { return getcwd(buffer, static_cast(size)); } +int compareNoCaseN(const char* a, const char* b, std::size_t n) { return strncasecmp(a, b, n); } +int compareNoCase(const char* a, const char* b) { return strcasecmp(a, b); } +#endif + +char s_pbPath[0x200]; // ds:0x9A7E68 (ELF ds:0x898FF40), PB_basepath's (and BF2.exe's PB_homepath's) +char s_pbVersion[0x50]; // ds:0x9A8068 +char s_pbSetting[0x100]; // ds:0x9A80B8 +char s_pbEmpty[1]; // ds:0x8AA769, PB_examineSetting's answer without a game + +#if defined(_WIN32) +const char kServerLibraryPath[] = "pb/pbsv.dll"; // ds:0x8AA724 +#else +const char kServerLibraryPath[] = "pb/pbsv.so"; // ELF ds:0x88E84D7 +#endif + +IGameClient* gameClient() { return static_cast(game->queryInterface(IID_IGameClient)); } +IGameServer* gameServer() { return static_cast(game->queryInterface(IID_IGameServer)); } +} // namespace + +// 0x4D94D0 / ELF 0x84F7340: the working directory (filled once). +char* PB_basepath() +{ + if (!s_pbPath[0]) currentDirectory(s_pbPath, 0x200); + return s_pbPath; +} +#if !DEDICATED +// 0x4D9500: the working directory too, in the same buffer. +char* PB_homepath() +{ + if (!s_pbPath[0]) currentDirectory(s_pbPath, 0x200); + return s_pbPath; +} +#else +// ELF 0x84F7370: the GSPunkBusterPath setting, re-read every call into a static string; the base path +// when it is empty. +char* PB_homepath() +{ + static std::string path; // ELF ds:0x8AC8430 + path = settings->stringGet(std::string("GSPunkBusterPath"), std::string("")); + if (path.empty()) return PB_basepath(); + return const_cast(path.c_str()); +} +#endif + +// 0x4D9530: the profile's cl_punkbuster, written only while pb/pbcl.dll exists. +void PB_set_cl_punkbuster(int value) +{ + if (!io::fileManager->fileExists(std::string("pb/pbcl.dll"))) return; + const bool enabled = value != 0; + settings->boolSet(std::string("GSClPunkBuster"), enabled); +} + +// 0x4D95B0 / ELF 0x84F7560: the server's PunkBuster flag, written only while the server library exists. +void PB_set_sv_punkbuster(int value) +{ + if (!io::fileManager->fileExists(std::string(kServerLibraryPath))) return; + serverSettings->m_punkBuster = value != 0; +} + +// 0x4D9610 / ELF 0x84F75F0 +int PB_maxClients() { return serverSettings->getMaxPlayers(); } + +// The record PB_getPlayerInfo fills for pbsv (query 0x66). [INFERRED] type and field names. +struct PbPlayerInfo { + char name[0x21]; // +0x00 + char keyHash[0x21]; // +0x21 the CD-key hash, internet servers only + char address[0x21]; // +0x42 "ip:port", or "localhost" for the hosting player + char unresolved63[5]; // +0x63 [UNRESOLVED] untouched + char extra[0x98]; // +0x68 "team="; pbsv's buffer is 0x100 bytes +}; + +// 0x4D9620 / ELF 0x84F7610: player `index`'s name, key hash, address and team for pbsv; 0 when there +// is no such player or (other than the host's) no ready client. (BF2.exe also tests +// `index < 0 && index > 63`, which is never true; gcc drops it.) +int PB_getPlayerInfo(int index, char* buffer) +{ + PbPlayerInfo* info = reinterpret_cast(buffer); + info->address[0] = 0; + if (!game) return 0; + IGameServer* server = gameServer(); + if (!server || !world::playerManager) return 0; + world::IPlayer* player = world::playerManager->getPlayerFromId(index); + world::IPlayer* local = world::playerManager->getLocalHumanPlayer(); + if (!player) return 0; + if (player != local && !server->isClientReady(index)) return 0; + std::strncpy(info->name, player->getName().c_str(), 0x20); + info->name[0x20] = 0; + if (serverSettings->m_internet && player->getIsConnected()) { + std::strncpy(info->keyHash, gcd_getkeyhash(gamespy::g_gameID, index), 0x20); + info->keyHash[0x20] = 0; + } else { + info->keyHash[0] = 0; + } + if (local == player) { + std::strcpy(info->address, "localhost"); + } else { + std::string address; + if (server->getPlayerConnectionIpAndPort(player, address)) + std::strncpy(info->address, address.c_str(), 0x20); + else + info->address[0] = 0; + info->address[0x20] = 0; + } + std::sprintf(info->extra, "team=%d", player->getTeam()); + return 1; +} + +// 0x4D97E0: the DLL's text, newline appended, to the console; on a client also to the chat window +// unless it starts with "[skipnotify]". +void PB_outputText(char* text) +{ + std::string line(text); + line += '\n'; + if (!game) return; + if (game->queryInterface(IID_IGameServer)) { + io::mainConsole->output(line); + return; + } + io::mainConsole->output(line); + if (compareNoCaseN(text, "[skipnotify]", 12)) game->addTextToChatWindow(line.c_str()); +} + +// 0x4D9890 / ELF 0x84F7950: a console command from pbsv ("Cmd_Exec"), newline appended, run silently. +void PB_issueConsoleCommand(char* command) +{ + std::string line(command); + line.append(1, '\n'); + if (io::mainConsole) + io::mainConsole->executeLine(line, io::Console::ignoredString_, false, false, false, false, false); +} + +// 0x4D98F0 / ELF 0x84F7A00: pbsv's kick ("DropClient"), with PResult 0x22 and its reason text. +void PB_DropClient(int index, char* reason) +{ + if (!game) return; + if (IGameServer* server = gameServer()) + server->kickPlayer(index, static_cast(0x22), std::string(reason)); +} + +// 0x4D9950 / ELF 0x84F7AA0: a PB packet to client `index`: "\xff\xff\xff\xff" + data, sent to the host +// and port of that player's connection address. +void PB_sv_sendToClient(int index, char* data, int length) +{ + std::string address; + if (!game) return; + IGameServer* server = gameServer(); + if (!server) return; + server->getPlayerConnectionIpAndPort(world::playerManager->getPlayerFromId(index), address); + int port = 0; + const std::string::size_type colon = address.find(":", 0, 1); + if (colon != std::string::npos) { + std::string portText; + portText = address.substr(colon + 1, address.size()); + port = static_cast(std::atoi(portText.c_str())); + std::string host; + host = address.substr(0, colon); + address = host; + } + char packet[0x640] = { '\xff', '\xff', '\xff', '\xff', 0 }; + std::memcpy(packet + 4, data, static_cast(length)); // retail has no bound either + server->sendUDPPacket(address.c_str(), static_cast(port), packet, length + 4); +} + +#if !DEDICATED +// 0x4D9B30: a PB packet to the joined server: "\xff\xff\xff\xff" + data, sent to the host and port of +// the client's server address. +void PB_cl_sendToServer(char* data, int length) +{ + if (!game) return; + IGameClient* client = gameClient(); + if (!client) return; + std::string address = client->getServerAddressCopy(); + int port = 0; + const std::string::size_type colon = address.find(":", 0, 1); + if (colon != std::string::npos) { + std::string portText; + portText = address.substr(colon + 1, address.size()); + port = std::atoi(portText.c_str()); + std::string host; + host = address.substr(0, colon); + address = host; + } + char packet[0x640] = { '\xff', '\xff', '\xff', '\xff', 0 }; + std::memcpy(packet + 4, data, static_cast(length)); // retail has no bound either + client->sendUDPPacket(address.c_str(), static_cast(port), packet, length + 4); +} +#endif + +// 0x4D9CF0: a raw datagram through the client, or else through the server. +void PB_sendUDPPacket(char* address, unsigned short port, char* data, int length) +{ + if (!game) return; + IGameClient* client = gameClient(); + IGameServer* server = gameServer(); + if (client) client->sendUDPPacket(address, port, data, length); + else if (server) server->sendUDPPacket(address, port, data, length); +} + +// 0x4D9D60: the build stamp, cached. +char* PB_getVersion() +{ + if (!s_pbVersion[0]) { + const std::string stamp(BuildNrUtil::getBuildNrString()); + std::strncpy(s_pbVersion, stamp.c_str(), 0x4F); + s_pbVersion[0x4F] = 0; + } + return s_pbVersion; +} + +// 0x4D9DD0 / ELF 0x84F88A0: answers 0. [INFERRED] identity: in both images it is the one return-0 PB_ +// function and sits immediately before PB_handlePacket; the client glue hands it to pbcl.dll as its +// +0x194 callback. [UNRESOLVED] parameter. +int PB_GlQuery(char*) { return 0; } + +// 0x4D9DE0 / ELF 0x84F88B0: a "\xff\xff\xff\xff" PB datagram from `from`. Types other than S 2 G I Y B L +// go to the client glue (client image); types other than C 1 J go to the server glue with the index of +// the player whose connection address matches (the player count when none does). +void PB_handlePacket(char* data, int length, const char* from) +{ + std::string playerAddress; + IGameServer* server = gameServer(); + if (length < 8 || std::strncmp(data, "\xff\xff\xff\xff", 4)) return; + const char type = data[7]; +#if !DEDICATED + if (type != 'S' && type != '2' && type != 'G' && type != 'I' && type != 'Y' && type != 'B' && type != 'L') + PbClAddEvent(0x0D, length - 4, data + 4); +#endif + if (type == 'C' || type == '1' || type == 'J') return; + int index = -1; + if (serverSettings->getMaxPlayers() > -1) { + do { + if (server + && server->getPlayerConnectionIpAndPort(world::playerManager->getPlayerFromId(index), playerAddress) + && !std::strcmp(playerAddress.c_str(), from)) + break; + ++index; + } while (index < serverSettings->getMaxPlayers()); + } + PbSvAddEvent(0x0D, index, length - 4, data + 4); +} + +// 0x4D9F40 / ELF 0x84F8A10: whether the server library is present. +bool PB_get_sv_punkbusterInstalled() { return io::fileManager->fileExists(std::string(kServerLibraryPath)); } + +// 0x4D9F80 / ELF 0x84F7F50: the settings the DLL may read, answered from a 256-byte buffer. +char* PB_examineSetting(char* name) +{ + if (!game) return s_pbEmpty; + s_pbSetting[0] = 0; + if (!compareNoCase(name, "cl_punkbuster")) { + const bool fallback = false; + int value = settings->boolGet(std::string("GSClPunkBuster"), fallback) ? 1 : 0; + if (game->queryInterface(IID_IGameServer)) value = 0; + std::sprintf(s_pbSetting, "%d", value); + } else if (!compareNoCase(name, "sv_punkbuster")) { + int value = serverSettings->getSvPunkBuster() ? 1 : 0; + if (game->queryInterface(IID_IGameClient)) value = 0; + std::sprintf(s_pbSetting, "%d", value); + } else if (!compareNoCase(name, "mapname")) { + std::strncpy(s_pbSetting, game->getCurrentMapName().c_str(), 0xFF); + } else if (!compareNoCase(name, "server")) { + IGameClient* client = gameClient(); + IGameServer* server = gameServer(); + if (client) std::strncpy(s_pbSetting, client->getServerAddressCopy().c_str(), 0xFF); + if (server) { + std::stringstream text; + text << server->getServerAddress(); + std::strncpy(s_pbSetting, text.str().c_str(), 0xFF); + } + } else if (!compareNoCase(name, "sv_hostname")) { + gameServer(); // queried and discarded + if (IGameClient* client = gameClient()) + std::strncpy(s_pbSetting, client->getServerAddressCopy().c_str(), 0xFF); + else + std::strncpy(s_pbSetting, serverSettings->m_serverName.c_str(), 0xFF); + } else if (!compareNoCase(name, "name")) { + if (world::IPlayer* local = world::playerManager->getLocalHumanPlayer()) + std::strncpy(s_pbSetting, local->getName().c_str(), 0xFF); + else + std::strncpy(s_pbSetting, + settings->stringGet(std::string("GSPlayerName"), std::string("player")).c_str(), 0xFF); +#if !DEDICATED + } else if (!compareNoCase(name, "team")) { + if (world::IPlayer* local = world::playerManager->getLocalHumanPlayer()) + std::sprintf(s_pbSetting, "%d", local->getTeam()); + else + s_pbSetting[0] = 0; +#endif + } else if (!compareNoCase(name, "gamename")) { + if (IGameServer* server = gameServer()) + std::strncpy(s_pbSetting, server->getName().c_str(), 0x100); + else + s_pbSetting[0] = 0; + } else if (!compareNoCaseN(name, "pb_isresolved", 13)) { + io::ISocket::Address address = {}; + address.length = 0x10; + std::string text; + const bool resolved = io::UDPSocket::nameToAddress(std::string(name + 14), &address, 0) == 0 + && io::UDPSocket::UDPaddressToString(address, &text); + if (resolved) std::strncpy(s_pbSetting, text.c_str(), 0x100); + else s_pbSetting[0] = 0; + } else { + s_pbSetting[0] = 0; + } + s_pbSetting[0xFF] = 0; + return s_pbSetting; +} diff --git a/Code/BF2/Game/PunkBuster/PbGlue.h b/Code/BF2/Game/PunkBuster/PbGlue.h new file mode 100644 index 000000000..80d67be69 --- /dev/null +++ b/Code/BF2/Game/PunkBuster/PbGlue.h @@ -0,0 +1,64 @@ +// PunkBuster integration: the game side of the Even Balance SDK boundary. [INFERRED] path and file split. +// +// The client glue (BF2.exe 0x435900..0x436434, PbClient.cpp) owns the pbcl.dll instance at ds:0x96E5A8: +// it loads the vendor DLL dynamically (LoadLibraryA / GetProcAddress "ca"/"cb"), hands it the game +// callbacks, forwards events and pumps it once a frame. The BF2-side PB_* functions (BF2.exe +// 0x4D94D0..0x4DA49B, PbGame.cpp) answer the DLL's queries. Without pbcl.dll (and on every platform but +// Windows, where no vendor DLL exists) the glue takes retail's not-installed branch. +// +// The server glue (Game/PunkBuster/PbServer.cpp, both images) owns the pbsv instance (BF2.exe +// ds:0x96E758, ELF ds:0x8AC82A0) the same way, with entry points "sa"/"sb". The BF2-side PB_* functions +// serve both glues; the dedicated image carries the server half only. +#ifndef GAME_PUNKBUSTER_PBGLUE_H +#define GAME_PUNKBUSTER_PBGLUE_H + +// ---- client glue (Game/PunkBuster/PbClient.cpp; client image only) ------------------------------- +void PbClientInitialize(void* instance); // 0x436060 +void PbClientConnect(); // 0x436220 [INFERRED] name: event 0x75 on join +char* PbClAddEvent(int type, int length, char* data); // 0x436000 +void PbClientTrapConsole(char* command, int length); // 0x436020 +void PbClientProcessEvents(); // 0x436150 + +// ---- server glue (Game/PunkBuster/PbServer.cpp; both images; BF2.exe / ELF addresses) ----------- +void PbServerInitialize(); // 0x437160 / 0x84F6170 +void PbServerTrapConsole(char* command, int length); // 0x436E70 / 0x84F6140 +void PbServerProcessEvents(); // 0x436E90 / 0x84F61F0 +void PbServerForceProcess(); // 0x436EA0 / 0x84F6210 +char* PbSvAddEvent(int type, int clientIndex, int length, char* data); // 0x436D60 / 0x84F6020 +void PbSvAddStatEvent(int clientIndex, char* first, char* second); // 0x436D90 / 0x84F6060 +void PbServerCompleteCommand(char* text, int length); // 0x436EB0 / 0x84F6230 +void PbPassConnectString(char* first, char* second); // 0x436A70 / 0x84F6270 +char* PbAuthClient(char* address, int flag, char* keyHash); // 0x436A90 / 0x84F62A0 +void PbCaptureConsoleOutput(char* text); // 0x436AC0 / 0x84F63B0 +extern "C" bool isPbSvEnabled(); // 0x436ED0 / 0x84F62E0 +void EnablePbSv(); // 0x436F40 / 0x84F6330 +void DisablePbSv(); // 0x436FC0 / 0x84F6370 +void* PbServerGlueObject(); // &pbsv, which the client glue records + +// ---- BF2-side game functions (Game/PunkBuster/PbGame.cpp; both images unless marked) ------------ +// BF2.exe / ELF addresses. +char* PB_basepath(); // 0x4D94D0 / 0x84F7340 +char* PB_homepath(); // 0x4D9500 / 0x84F7370 +void PB_set_cl_punkbuster(int value); // 0x4D9530 / 0x84F7490 +void PB_set_sv_punkbuster(int value); // 0x4D95B0 / 0x84F7560 +int PB_maxClients(); // 0x4D9610 / 0x84F75F0 +int PB_getPlayerInfo(int index, char* info); // 0x4D9620 / 0x84F7610 +void PB_outputText(char* text); // 0x4D97E0 / 0x84F7830 +void PB_issueConsoleCommand(char* command); // 0x4D9890 / 0x84F7950 +void PB_DropClient(int index, char* reason); // 0x4D98F0 / 0x84F7A00 +void PB_sv_sendToClient(int index, char* data, int length); // 0x4D9950 / 0x84F7AA0 +void PB_cl_sendToServer(char* data, int length); // 0x4D9B30, client image only [INFERRED] name +void PB_sendUDPPacket(char* address, unsigned short port, char* data, int length); // 0x4D9CF0 / 0x84F7E00 +char* PB_getVersion(); // 0x4D9D60 / 0x84F7EB0 +int PB_GlQuery(char*); // 0x4D9DD0 / 0x84F88A0 [INFERRED] identity: returns 0 +void PB_handlePacket(char* data, int length, const char* from); // 0x4D9DE0 / 0x84F88B0 +char* PB_examineSetting(char* name); // 0x4D9F80 / 0x84F7F50 +bool PB_get_sv_punkbusterInstalled(); // 0x4D9F40 / 0x84F8A10 + +// The console pre-dispatch hook BF2Engine::init registers (BF2.exe 0x402FD0): PB_SV_* commands go to +// the server glue, other PB_* commands to the client glue; true for any PB_ command. +// [CHOSEN, not recovered] placement: the ELF has it in BF2Engine.cpp's anonymous namespace; it lives +// here so the routing test can link it without the engine. +bool HandleCommandHookPB(const char* command, int length); + +#endif diff --git a/Code/BF2/Game/PunkBuster/PbServer.cpp b/Code/BF2/Game/PunkBuster/PbServer.cpp new file mode 100644 index 000000000..445af845f --- /dev/null +++ b/Code/BF2/Game/PunkBuster/PbServer.cpp @@ -0,0 +1,435 @@ +// PunkBuster server glue: BF2.exe 0x436440..0x437349 and the ELF dedicated server 0x84F6020..0x84F7340 +// (whose symbols give the names; the stPbSv members, PbCopyFile and ltoa are weak there, so inline in +// the vendor SDK header the glue was built from). Both images, one body: they differ only in the vendor library's file +// names (pbsv.dll / pbsv.so, '\' / '/', chmod 0x180 / 0x1FF), which follow the platform, and in where +// the console capture buffer lives, which follows the image. [INFERRED] path. +#include "PbServer.h" +#include "PbGlue.h" +#include +#include +#include +#include +#if defined(_WIN32) +#include +#include +#include +#else +#include +#include +#include +#endif + +namespace { +const char kNotInstalled[] = "PunkBuster Server Not Installed"; // ds:0x893D14, ELF 0x88E8440 +const char kLoadFailure[] = "PB Error: Server DLL Load Failure"; // ds:0x893CD8, ELF 0x88E8460 +const char kProcFailure[] = "PB Error: Server DLL Get Procedure Failure"; // ds:0x893CA4, ELF 0x88E84A0 +const char kQueryFailed[] = "PB Error: Query Failed"; // ds:0x893C3C, ELF 0x88E83CA + +#if defined(_WIN32) +const char kSeparator[] = "\\"; +const char kPbFolder[] = "pb\\"; +const char kLibrary[] = "pbsv.dll"; +const char kLibraryOld[] = "pbsvold.dll"; +const char kLibraryNew[] = "pbsvnew.dll"; +const char kClientLibrary[] = "pbcl.dll"; +const char kAgentLibrary[] = "pbag.dll"; +const int kLibraryMode = 0x180; +void* loadLibrary(const char* path) { return reinterpret_cast(LoadLibraryA(path)); } +void* librarySymbol(void* library, const char* name) +{ + return reinterpret_cast(GetProcAddress(static_cast(library), name)); +} +void releaseLibrary(void* library) { FreeLibrary(static_cast(library)); } +int changeMode(const char* path, int mode) { return _chmod(path, mode); } +int makeDirectory(const char* path) { return _mkdir(path); } +char* currentDirectory(char* buffer, int size) { return _getcwd(buffer, size); } +int compareNoCase(const char* a, const char* b) { return _stricmp(a, b); } +int compareNoCaseN(const char* a, const char* b, std::size_t n) { return _strnicmp(a, b, n); } +void longToText(long value, char* out) { _ltoa(value, out, 10); } +#else +const char kSeparator[] = "/"; +const char kPbFolder[] = "pb/"; +const char kLibrary[] = "pbsv.so"; +const char kLibraryOld[] = "pbsvold.so"; +const char kLibraryNew[] = "pbsvnew.so"; +const char kClientLibrary[] = "pbcl.so"; +const char kAgentLibrary[] = "pbag.so"; +const int kLibraryMode = 0x1FF; +void releaseLibrary(void*) {} +int changeMode(const char* path, int mode) { return chmod(path, static_cast(mode)); } +int makeDirectory(const char* path) { return mkdir(path, 0x1FF); } +char* currentDirectory(char* buffer, int size) { return getcwd(buffer, static_cast(size)); } +int compareNoCase(const char* a, const char* b) { return strcasecmp(a, b); } +int compareNoCaseN(const char* a, const char* b, std::size_t n) { return strncasecmp(a, b, n); } +// The ELF carries its own ltoa (0x84F6940); the server asks it for base 10 only. +void longToText(long value, char* out) { std::sprintf(out, "%ld", value); } +#endif +} // namespace + +#if defined(_WIN32) +PbServerLibraryApi g_pbServerLibrary = { loadLibrary, librarySymbol, releaseLibrary }; +#else +PbServerLibraryApi g_pbServerLibrary = { 0, 0, releaseLibrary }; +#endif + +// The static image: magic, the prefix, the reload request and state 999 (BF2.exe ds:0x96E758.., +// written by the ELF's static initializer 0x84F67C0). +stPbSv pbsv = { 0x357AFE20u, 0, 0, 0, 0, "PunkBuster Server", { 0 }, 1, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 999, 0, 0 }; + +namespace { +#if !DEDICATED +// BF2.exe keeps the console capture pair outside the object (the ELF uses pbsv +0x16C / +0x170). +char* s_captureBuffer = 0; // ds:0x99EF78 +int s_captureCapacity = 0; // ds:0x99EF7C +char*& captureBuffer() { return s_captureBuffer; } +int& captureCapacity() { return s_captureCapacity; } +#else +char*& captureBuffer() { return pbsv.m_captureBuffer; } +int& captureCapacity() { return pbsv.m_captureCapacity; } +#endif + +// The exit destructor (BF2.exe 0x873470, ELF __tcf_0 0x84F68A0): entry points cleared, the three +// libraries released. +struct PbServerExit { + ~PbServerExit() + { + pbsv.m_dllProcess = 0; + pbsv.m_dllEvent = 0; + if (pbsv.m_library) g_pbServerLibrary.release(pbsv.m_library); + pbsv.m_library = 0; + if (pbsv.m_library2) g_pbServerLibrary.release(pbsv.m_library2); + pbsv.m_library2 = 0; + pbsv.m_dllHook164 = 0; + if (pbsv.m_library3) g_pbServerLibrary.release(pbsv.m_library3); + pbsv.m_library3 = 0; + } +} s_pbServerExit; + +// BF2.exe 0x436440, ELF 0x84F7200: copy src to dst when it is non-empty and below `limit` (0: any +// size); true when every byte was written. +bool PbCopyFile(char* source, char* destination, long limit) +{ + bool copied = false; + FILE* in = std::fopen(source, "rb"); + if (!in) return false; + if (FILE* out = std::fopen(destination, "wb")) { + std::fseek(in, 0, SEEK_END); + const long size = std::ftell(in); + if (size > 0 && (!limit || size < limit)) { + if (char* buffer = new char[size]) { + std::fseek(in, 0, SEEK_SET); + const std::size_t read = std::fread(buffer, 1, static_cast(size), in); + const std::size_t written = std::fwrite(buffer, 1, read, out); + delete[] buffer; + copied = written == static_cast(size); + } + } + std::fclose(out); + } + std::fclose(in); + return copied; +} + +void appendSeparator(char* path) +{ + if (path[std::strlen(path) - 1] != kSeparator[0]) std::strcat(path, kSeparator); +} + +// BF2.exe 0x436520 (inlined in the ELF): copy into the pb folder unless it is there. +void copyIfMissing(stPbSv* pb, const char* name, const char* base) +{ + char target[0x200]; + std::strcpy(target, pb->m_path); + std::strcat(target, name); + if (FILE* present = std::fopen(target, "rb")) { + std::fclose(present); + return; + } + char source[0x200]; + std::strcpy(source, base); + std::strcat(source, name); + PbCopyFile(source, target, 0); +} + +// BF2.exe 0x436630 (inlined in the ELF): "/pb/", or the working directory's when the game +// answers nothing. +void fillPath(stPbSv* pb) +{ + if (!pb->m_gameQuery) return; + std::strcpy(pb->m_path, "fs_homepath"); + pb->m_gameQuery(0x67, pb->m_path); + if (!pb->m_path[0]) currentDirectory(pb->m_path, 0xFB); + if (pb->m_path[0]) appendSeparator(pb->m_path); + std::strcat(pb->m_path, kPbFolder); +} + +// BF2.exe 0x4366D0, ELF stPbSv::makefn 0x84F6E10. The first call fixes the pb folder; when the home +// and base folders differ it is created and seeded with the base folder's three libraries. +char* makefn(stPbSv* pb, char* out, const char* name) +{ + if (!pb->m_path[0]) { + fillPath(pb); + // [CHOSEN, not recovered] starts empty: retail leaves the buffer unset when no query + // callback exists (unreachable: PbServerInitialize installs it before any event). + char base[0x100] = ""; + if (pb->m_gameQuery) { + std::strcpy(base, "fs_basepath"); + pb->m_gameQuery(0x67, base); + } + if (base[0]) appendSeparator(base); // [CHOSEN] guard: retail reads base[-1] when empty + std::strcat(base, kPbFolder); + if (compareNoCase(base, pb->m_path) && base[0] && pb->m_path[0]) { + makeDirectory(pb->m_path); + copyIfMissing(pb, kLibrary, base); + copyIfMissing(pb, kClientLibrary, base); + copyIfMissing(pb, kAgentLibrary, base); + } + } + std::strcpy(out, pb->m_path); + std::strcat(out, name); + return out; +} + +// BF2.exe 0x436830 +void unloadDll(stPbSv* pb) +{ + pb->m_dllProcess = 0; + pb->m_dllEvent = 0; + if (pb->m_library) g_pbServerLibrary.release(pb->m_library); + pb->m_library = 0; +} + +// BF2.exe 0x436860, ELF stPbSv::LoadServerDll 0x84F6BD0: install a downloaded pbsvnew as pbsv +// (keeping pbsvold), then load it. +const char* loadServerDll(stPbSv* pb) +{ + if (pb->m_library) return 0; + pb->m_dllProcess = 0; + pb->m_dllEvent = 0; + // [CHOSEN, not recovered] No vendor library on these builds: fail as a missing pbsv would, before + // any file in the pb folder is touched (see PbServerLibraryApi). + if (!g_pbServerLibrary.load) return kLoadFailure; + char a[0x200], b[0x200]; + if (FILE* fresh = std::fopen(makefn(pb, a, kLibraryNew), "rb")) { + std::fclose(fresh); + changeMode(makefn(pb, a, kLibraryOld), kLibraryMode); + std::remove(makefn(pb, a, kLibraryOld)); + std::rename(makefn(pb, a, kLibrary), makefn(pb, b, kLibraryOld)); + changeMode(makefn(pb, a, kLibrary), kLibraryMode); + std::remove(makefn(pb, a, kLibrary)); + std::rename(makefn(pb, a, kLibraryNew), makefn(pb, b, kLibrary)); + } + pb->m_library = g_pbServerLibrary.load(makefn(pb, a, kLibrary)); + if (!pb->m_library) return kLoadFailure; + pb->m_dllProcess = reinterpret_cast(g_pbServerLibrary.symbol(pb->m_library, "sa")); + pb->m_dllEvent = reinterpret_cast(g_pbServerLibrary.symbol(pb->m_library, "sb")); + if (!pb->m_dllProcess || !pb->m_dllEvent) { + unloadDll(pb); + return kProcFailure; + } + pb->m_reload = 0; + return 0; +} + +// BF2.exe 0x437230, ELF stPbSv::AddPbEvent 0x84F6A10: an event for pbsv, (re)loading it as needed. A +// failed load answers its error text; the first one also shows the not-installed notice, except for the +// two status queries 0x71 / 0x72. +char* addPbEvent(stPbSv* pb, int type, int clientIndex, int length, char* data, int flag) +{ + if (!pb->m_gameCommand || !pb->m_state) return 0; + if (pb->m_reload || !pb->m_library) { + if (pb->m_library) { + unloadDll(pb); + return 0; + } + const char* error = loadServerDll(pb); + if (error) { + if (type == 0x71 || type == 0x72) return 0; + if (pb->m_state == 999) { + pb->m_state = 0; + pb->m_gameMessage(const_cast(kNotInstalled), 1); + } + return const_cast(error); + } + } + return reinterpret_cast(static_cast( + pb->m_dllEvent(pb, type, clientIndex, length, data, flag))); +} + +// BF2.exe 0x4372F0, ELF stPbSv::ProcessPbEvents 0x84F6B20 +int processPbEvents(stPbSv* pb, int argument) +{ + if (!pb->m_gameCommand || !pb->m_state) return 0; + if (pb->m_library) { + if (pb->m_reload) { + unloadDll(pb); + return 0; + } + return pb->m_dllProcess(pb, argument); + } + if (pb->m_reload) addPbEvent(pb, 0x10, -1, 0, const_cast(""), 0); + return 0; +} + +// ---- the game callbacks handed to pbsv ------------------------------------------------------------ +// BF2.exe 0x437040, ELF PbSvGameCommand 0x84F6430. "ConCapBufLen" passes its number in the pointer. +int gameCommand(char* command, char* args) +{ + if (!compareNoCase(command, "set_sv_punkbuster")) { + PB_set_sv_punkbuster(std::atoi(args)); + } else if (!compareNoCase(command, "ConCapBufLen")) { + captureCapacity() = static_cast(reinterpret_cast(args)); + } else if (!compareNoCase(command, "ConCapBuf")) { + captureBuffer() = args; + } else if (!compareNoCase(command, "Cmd_Exec")) { + const bool pbCommand = !compareNoCaseN(args, "pb_", 3); + PB_issueConsoleCommand(args); + if (pbCommand) PbServerForceProcess(); + } else { + // " ": the reason starts after the first word and its spaces. + char* reason = args; + while (*reason == ' ') ++reason; + while (*reason && *reason != ' ') ++reason; + while (*reason == ' ') ++reason; + if (!compareNoCase(command, "DropClient")) PB_DropClient(std::atoi(args), reason); + } + return 0; +} + +// BF2.exe 0x436B30, ELF PbSvGameQuery 0x84F6580: pbsv's queries, answered into its 256-byte buffer. +// (The ELF tests the buffer for null only after writing through it.) +char* gameQuery(int type, char* buffer) +{ + buffer[0xFE] = 0; + switch (type) { + case 0x65: + longToText(PB_maxClients(), buffer); + break; + case 0x66: + if (!PB_getPlayerInfo(std::atoi(buffer), buffer)) return const_cast(kQueryFailed); + break; + case 0x67: { + const char* value; + if (!compareNoCase(buffer, "fs_homepath")) value = PB_homepath(); + else if (!compareNoCase(buffer, "fs_basepath")) value = PB_basepath(); + else if (!compareNoCase(buffer, "version")) value = PB_getVersion(); + else value = PB_examineSetting(buffer); + std::strncpy(buffer, value, 0xFF); + break; + } + default: + break; + } + buffer[0xFE] = 0; + return 0; +} + +// BF2.exe 0x436C50, ELF PbSvGameMsg 0x84F6670: ": \n" to the game's output (the flag is +// unused). +int gameMessage(char* text, int) +{ + char line[0x801]; // [CHOSEN] one byte past retail's 0x800, which the final "\n" can overrun + std::strcpy(line, pbsv.m_gameName); + std::strcat(line, ": "); + const std::size_t used = std::strlen(line); + std::strncpy(line + used, text, 0x7FF - used); + line[0x7FF] = 0; + std::strcat(line, "\n"); + PB_outputText(line); + return 0; +} + +// BF2.exe 0x436D20, ELF PbSvSendToClient 0x84F6760 +int sendToClient(int length, char* data, int clientIndex) +{ + PB_sv_sendToClient(clientIndex, data, length); + return 0; +} + +// BF2.exe 0x436D40, ELF PbSvSendToAddrPort 0x84F6790 +int sendToAddrPort(char* address, unsigned short port, int length, char* data) +{ + PB_sendUDPPacket(address, port, data, length); + return 0; +} +} // namespace + +// ---- entry points -------------------------------------------------------------------------------- +// BF2.exe 0x437160, ELF 0x84F6170: hand over the callbacks and send the initialize event (0x10); +// without a loaded pbsv the server's PunkBuster setting is switched off. +void PbServerInitialize() +{ + pbsv.m_gameCommand = gameCommand; + pbsv.m_gameQuery = gameQuery; + pbsv.m_gameMessage = gameMessage; + pbsv.m_sendToClient = sendToClient; + pbsv.m_sendToAddrPort = sendToAddrPort; + addPbEvent(&pbsv, 0x10, -1, 0, const_cast(""), 0); + if (!pbsv.m_dllEvent) PB_set_sv_punkbuster(0); +} + +// BF2.exe 0x436D60, ELF 0x84F6020 +char* PbSvAddEvent(int type, int clientIndex, int length, char* data) +{ + return addPbEvent(&pbsv, type, clientIndex, length, data, 0); +} + +// BF2.exe 0x436D90, ELF 0x84F6060: " " as event 0xF; dropped above 0x800 characters. +// Unreferenced in both images. +void PbSvAddStatEvent(int clientIndex, char* first, char* second) +{ + if (std::strlen(first) + std::strlen(second) > 0x800) return; + char text[0x802]; // [CHOSEN] holds retail's maximum; its 0x800-byte buffer can be overrun by two + std::strcpy(text, first); + std::strcat(text, " "); + std::strcat(text, second); + addPbEvent(&pbsv, 0x0F, clientIndex, static_cast(std::strlen(text)), text, 0); +} + +// BF2.exe 0x436E70, ELF 0x84F6140: a PB_SV_ console command for pbsv. +void PbServerTrapConsole(char* command, int length) { addPbEvent(&pbsv, 0x0E, -1, length, command, 0); } + +// BF2.exe 0x436E90 / 0x436EA0, ELF 0x84F61F0 / 0x84F6210: the per-frame pump, and the forced pass a +// pb_ console command triggers. +void PbServerProcessEvents() { processPbEvents(&pbsv, 0); } +void PbServerForceProcess() { processPbEvents(&pbsv, -1); } + +// BF2.exe 0x436EB0, ELF 0x84F6230. Unreferenced in both images. +void PbServerCompleteCommand(char* text, int length) { addPbEvent(&pbsv, 0x33, -1, length, text, 0); } + +// BF2.exe 0x436A70, ELF 0x84F6270: pbsv's own hook, when it set one. Unreferenced in both images. +void PbPassConnectString(char* first, char* second) +{ + if (pbsv.m_connectString) pbsv.m_connectString(&pbsv, first, second); +} + +// BF2.exe 0x436A90, ELF 0x84F62A0: pbsv's admission check for a CD-key-authorized client; 0 admits, +// a text is the kick reason. 0 when pbsv set no hook. +char* PbAuthClient(char* address, int flag, char* keyHash) +{ + if (!pbsv.m_authClient) return 0; + return pbsv.m_authClient(&pbsv, address, flag, keyHash); +} + +// BF2.exe 0x436AC0, ELF 0x84F63B0: append a console line to pbsv's capture buffer while it fits. +// Unreferenced in both images. +void PbCaptureConsoleOutput(char* text) +{ + char* buffer = captureBuffer(); + if (!buffer) return; + const std::size_t used = std::strlen(buffer); + if (used + std::strlen(text) + 1 >= static_cast(captureCapacity())) return; + std::strcpy(buffer + used, text); + std::strcat(buffer, "\n"); +} + +// BF2.exe 0x436ED0, ELF 0x84F62E0: pbsv's status query 0x71; false when it is not loaded. +extern "C" bool isPbSvEnabled() { return addPbEvent(&pbsv, 0x71, -1, 0, 0, 1) != 0; } + +// BF2.exe 0x436F40 / 0x436FC0, ELF 0x84F6330 / 0x84F6370: events 0x75 / 0x76. Unreferenced in both +// images. +void EnablePbSv() { addPbEvent(&pbsv, 0x75, -1, 0, 0, 0); } +void DisablePbSv() { addPbEvent(&pbsv, 0x76, -1, 0, 0, 0); } + +void* PbServerGlueObject() { return &pbsv; } diff --git a/Code/BF2/Game/PunkBuster/PbServer.h b/Code/BF2/Game/PunkBuster/PbServer.h new file mode 100644 index 000000000..bedee2119 --- /dev/null +++ b/Code/BF2/Game/PunkBuster/PbServer.h @@ -0,0 +1,61 @@ +// The PunkBuster server glue object: BF2.exe ds:0x96E758, ELF ds:0x8AC82A0 (the ELF names the type +// stPbSv). pbsv receives a pointer to it and reads the callbacks at their x86 offsets, so the x86 layout +// is the ABI. Both images use the same offsets. +#ifndef GAME_PUNKBUSTER_PBSERVER_H +#define GAME_PUNKBUSTER_PBSERVER_H +#include + +struct stPbSv; +// The vendor library's two entry points and the hooks it writes back (all cdecl). +typedef int (*PbSvEventFn)(stPbSv*, int type, int clientIndex, int length, char* data, int flag); // "sb" +typedef int (*PbSvProcessFn)(stPbSv*, int); // "sa" +typedef void (*PbSvConnectStringFn)(stPbSv*, char*, char*); +typedef char* (*PbSvAuthClientFn)(stPbSv*, char* address, int, char* keyHash); + +struct stPbSv { + unsigned int m_magic; // +0x00 0x357AFE20 in the static image + int m_unresolved04; // +0x04 [UNRESOLVED] + void* m_library; // +0x08 pbsv.dll / pbsv.so + void* m_library2; // +0x0C released only at exit [UNRESOLVED] + void* m_library3; // +0x10 released only at exit [UNRESOLVED] + char m_gameName[0x20]; // +0x14 "PunkBuster Server", the message prefix + char m_path[0x104]; // +0x34 "/pb/" (makefn's base) + int m_reload; // +0x138 1 in the static image: the next event (re)loads + int (*m_gameCommand)(char* command, char* args); // +0x13C + char* (*m_gameQuery)(int type, char* buffer); // +0x140 (an error text or 0) + int (*m_gameMessage)(char* text, int flag); // +0x144 + int (*m_sendToClient)(int length, char* data, int clientIndex); // +0x148 + PbSvEventFn m_dllEvent; // +0x14C symbol "sb" + PbSvProcessFn m_dllProcess; // +0x150 symbol "sa" + int (*m_sendToAddrPort)(char* address, unsigned short port, int length, char* data); // +0x154 + PbSvConnectStringFn m_connectString; // +0x158 written by pbsv + PbSvAuthClientFn m_authClient; // +0x15C written by pbsv + void* m_dllHook160; // +0x160 [UNRESOLVED] + void* m_dllHook164; // +0x164 cleared at exit [UNRESOLVED] + int m_state; // +0x168 999 until the not-installed notice + // ELF only: the console capture buffer pbsv hands over by "ConCapBuf" / "ConCapBufLen". BF2.exe keeps + // the pair in globals of its own (ds:0x99EF78 / ds:0x99EF7C, PbServer.cpp). + char* m_captureBuffer; // +0x16C + int m_captureCapacity; // +0x170 +}; +#if defined(_M_IX86) || defined(__i386__) +static_assert(offsetof(stPbSv, m_gameName) == 0x14 && offsetof(stPbSv, m_path) == 0x34, "pbsv ABI"); +static_assert(offsetof(stPbSv, m_reload) == 0x138 && offsetof(stPbSv, m_gameCommand) == 0x13C, "pbsv ABI"); +static_assert(offsetof(stPbSv, m_dllEvent) == 0x14C && offsetof(stPbSv, m_authClient) == 0x15C, "pbsv ABI"); +static_assert(offsetof(stPbSv, m_state) == 0x168 && offsetof(stPbSv, m_captureCapacity) == 0x170, "pbsv ABI"); +#endif + +extern stPbSv pbsv; // BF2.exe ds:0x96E758, ELF ds:0x8AC82A0 + +// [CHOSEN, not recovered] Library seam, the same as the client glue's. Windows: LoadLibraryA / +// GetProcAddress / FreeLibrary, as BF2.exe does. Elsewhere load is null: no pbsv exists for these +// builds (the shipped pbsv.so is 32-bit x86), so the glue reports the load failure before it touches +// the pb folder. The fake-pbsv test installs its own functions. +struct PbServerLibraryApi { + void* (*load)(const char* path); + void* (*symbol)(void* library, const char* name); + void (*release)(void* library); +}; +extern PbServerLibraryApi g_pbServerLibrary; + +#endif diff --git a/Code/BF2/Game/SettingsConsole.cpp b/Code/BF2/Game/SettingsConsole.cpp index 1aa736df7..c42858a5c 100644 --- a/Code/BF2/Game/SettingsConsole.cpp +++ b/Code/BF2/Game/SettingsConsole.cpp @@ -2,6 +2,8 @@ // [CHOSEN] Translation-unit placement; no retail __FILE__ attests this filename. // Bindings retain their receiver signatures and client-only compilation boundary. +#include + #include "../Core/BuildConfig.h" #if !DEDICATED @@ -14,8 +16,6 @@ #include "VideoSettings.h" #include "Main/BF2ClientSeams.h" // g_audioSettings ... g_gameServerSettings (ds:0x987354..0x987394) -#include - namespace dice { namespace hfe { @@ -187,6 +187,12 @@ BF2_CONSOLE_METHOD_1_STATIC_ACTIVE(setConnectionType, generalSettings()->setConn // +0x4C by 0x416943), exec 4169C4 -> +0x160, conv 416977 BF2_CONSOLE_METHOD_1_STATIC_ACTIVE(setLCDDisplayModes, generalSettings()->setLCDDisplayModes, ::dice::hfe::g_generalSettings != 0, bool, kSettingsConsoleTag) +// [CHOSEN, not recovered] Owner's tutorial option, saved with the general settings. +// Only these new commands are available at end-user access; retail bindings keep access 2. +BF2_CONSOLE_OBJECT("GeneralSettings", 1, 0) +BF2_CONSOLE_METHOD_1_STATIC_ACTIVE(setShowTutorialMessages, generalSettings()->setShowTutorialMessages, ::dice::hfe::g_generalSettings != 0, bool, kSettingsConsoleTag) +BF2_CONSOLE_METHOD_0_RET_ACTIVE(getShowTutorialMessages, generalSettings()->getShowTutorialMessages, bool, ::dice::hfe::g_generalSettings != 0, kSettingsConsoleTag) + // Haptic settings use console access level 1. The load binding reloads the current // profile file and returns its Boolean result. BF2_CONSOLE_OBJECT("HapticSettings", 1, 0) diff --git a/Code/BF2/Game/VideoSettings.cpp b/Code/BF2/Game/VideoSettings.cpp index 820cc80bf..eb51c7c36 100644 --- a/Code/BF2/Game/VideoSettings.cpp +++ b/Code/BF2/Game/VideoSettings.cpp @@ -8,6 +8,7 @@ #include "../Core/Ids.h" #include "../RendMisc/IRenderer.h" #include "../Core/SettingsRepostitory.h" // settings - "GSLoadLevel" gates the antialiasing push +#include // [CHOSEN] sscanf for the new-profile resolution pick #include #include #include @@ -152,9 +153,69 @@ bool VideoSettings::apply() return true; } +namespace { + +// [CHOSEN, not recovered] The renderer's resolution entry ("%ix%i@%iHz") a new profile starts +// with: the largest that fits the renderer's desktop mode (IRenderer +0xDC, the adapter's +// GetAdapterDisplayMode; the Metal backend answers the main display's point size), preferring the +// desktop's refresh rate, then the highest. Empty when no entry fits or no mode is reported. +std::string desktopFitResolution(dx9rend::IRenderer* renderer, const std::vector& list) +{ + unsigned int width = 0, height = 0, hz = 0; + if (!renderer->getDesktopMode(width, height, hz)) + return std::string(); + const int desktopWidth = static_cast(width), desktopHeight = static_cast(height); + const int desktopHz = static_cast(hz); + std::string best; + long long bestArea = 0; + int bestHz = 0; + bool bestHzMatches = false; + for (const std::string& entry : list) { + int width = 0, height = 0, hz = 0; + if (std::sscanf(entry.c_str(), "%dx%d@%d", &width, &height, &hz) != 3) + continue; + if (width > desktopWidth || height > desktopHeight) + continue; + const long long area = static_cast(width) * height; + const bool hzMatches = hz == desktopHz; + if (area > bestArea + || (area == bestArea && hzMatches && !bestHzMatches) + || (area == bestArea && hzMatches == bestHzMatches && hz > bestHz)) { + best = entry; + bestArea = area; + bestHz = hz; + bestHzMatches = hzMatches; + } + } + return best; +} + +// [CHOSEN, not recovered] Owner decision 2026-11-14: the High scheme also takes the highest +// antialiasing the renderer lists for the selected mode ("Off", then "%dSamples"); retail's High +// preset stages "Off". The list is rebuilt per resolution, so this runs after a resolution change. +void selectMaxAntialiasing(IVideoOptions* options) +{ + const std::vector& list = options->getDynamicOptionList(0); + std::string best; + int bestSamples = 0; + for (const std::string& entry : list) { + int samples = 0; + if (std::sscanf(entry.c_str(), "%dSamples", &samples) == 1 && samples > bestSamples) { + best = entry; + bestSamples = samples; + } + } + if (!best.empty()) + options->setDynamicOption(0, best); +} + +} // namespace + // (359 B). The pending record takes the constructor defaults field by field, then, with a // renderer, the sixteen range values are read interleaved (+08 then +0C per index), the detected // scheme replaces the default one and the scheme is pushed to the renderer with argument 1. +// Only the two new-profile paths call this (LocalProfileManager::createDefaultProfile 4A8113 and +// createProfile 4AAAA8); existing profiles keep their Video.con. void VideoSettings::setDefaults() { m_pending.terrainQuality = 2; @@ -181,6 +242,18 @@ void VideoSettings::setDefaults() } m_pending.videoOptionScheme = detectVideoOptionScheme(); applyVideoOptionScheme(1); + // [CHOSEN, not recovered] High stages "1024x768"; a new profile takes the largest listed + // resolution that fits the desktop instead, when one does. + const std::string resolution = desktopFitResolution(renderer, getResolutionList()); + if (!resolution.empty()) { + options->setDynamicOption(1, resolution); + if (m_pending.videoOptionScheme == 2) + selectMaxAntialiasing(options); + readOptions(options); + } + std::fprintf(stderr, "[CHOSEN, not recovered] VideoSettings::setDefaults: new profile at scheme %d, " + "resolution %s, antialiasing %s\n", m_pending.videoOptionScheme, + m_pending.resolution.c_str(), m_pending.antialiasing.c_str()); } // (20 B) @@ -207,7 +280,12 @@ void VideoSettings::applyToOptions(IVideoOptions* options) options->setViewDistanceScale(m_pending.viewDistanceScale); } -// (34 B) +// (34 B). Retail answers the renderer's autodetect (RendDX9 0x1000F6E0: CPU benchmark x CPU-vendor +// multiplier, RAM, pixel-shader major and the 2005 ATI/NVIDIA device whitelist), which caps every +// GPU it does not list at Medium and a CPU it cannot identify at Low, so no current machine gets +// High. [CHOSEN, not recovered] Owner decision 2026-11-14: with a renderer the answer is the High +// scheme (2) on every platform; the renderer's heuristic still runs and is logged. Its callers are +// setDefaults (new profiles) and the options page's detectVideoScheme (reset to default). int VideoSettings::detectVideoOptionScheme() { if (!g_bf2Render) @@ -215,10 +293,14 @@ int VideoSettings::detectVideoOptionScheme() dx9rend::IRenderer* renderer = g_bf2Render->getRenderer(); if (!renderer) return 1; - return renderer->getVideoOptions()->detectQualityLevel(); + const int detected = renderer->getVideoOptions()->detectQualityLevel(); + std::fprintf(stderr, "[CHOSEN, not recovered] VideoSettings::detectVideoOptionScheme: renderer " + "autodetect %d, answering High (2)\n", detected); + return 2; } // (57 B): the argument is never read; the pending scheme is what reaches the renderer. +// [CHOSEN, not recovered] For the High scheme the highest listed antialiasing follows the preset. void VideoSettings::applyVideoOptionScheme(int /*unused*/) { if (!g_bf2Render) @@ -228,6 +310,10 @@ void VideoSettings::applyVideoOptionScheme(int /*unused*/) return; IVideoOptions* options = renderer->getVideoOptions(); options->applyQualityPreset(m_pending.videoOptionScheme); + // [CHOSEN, not recovered] High (new profiles, reset to default, the High choice) adds the + // highest listed antialiasing; see selectMaxAntialiasing. + if (m_pending.videoOptionScheme == 2) + selectMaxAntialiasing(options); readOptions(options); } diff --git a/Code/BF2/Game/VideoSettings.h b/Code/BF2/Game/VideoSettings.h index a8f9fb0e6..eff3f96b3 100644 --- a/Code/BF2/Game/VideoSettings.h +++ b/Code/BF2/Game/VideoSettings.h @@ -40,7 +40,7 @@ class IVideoSettings : public IBase { virtual void setDefaults() = 0; //+20 4B2600; LocalProfileManager::createDefaultProfile 4A8113 virtual void revertChanges() = 0; //+24 4B2890: pending takes current virtual void applyToOptions(IVideoOptions* options) = 0; //+28 4B2040: pushes pending into the renderer's options unless a game is loaded - virtual int detectVideoOptionScheme() = 0; //+2C 4B1DB0: the renderer's detected level; 1 without a renderer + virtual int detectVideoOptionScheme() = 0; //+2C 4B1DB0: the renderer's detected level ([CHOSEN] High); 1 without a renderer virtual void applyVideoOptionScheme(int unused) = 0; //+30 4B1F20: presets the renderer with the pending scheme, then reads back; the argument is not read virtual void setCustomVideoOptionScheme() = 0; //+34 4B2160: pending scheme 3 virtual bool hasChangesInGame() = 0; //+38 4B1DE0: game && hasChanges diff --git a/Code/BF2/Game/VoipClient/BF2VoipClient.cpp b/Code/BF2/Game/VoipClient/BF2VoipClient.cpp new file mode 100644 index 000000000..189a27f86 --- /dev/null +++ b/Code/BF2/Game/VoipClient/BF2VoipClient.cpp @@ -0,0 +1,569 @@ +// BF2.exe 0x4510F0..0x45235C. See BF2VoipClient.h. +#if defined(_WIN32) +#include +#else +#include +#include +#include +#include +#endif + +#include "../../External/GameSpy/Voice2/gv.h" +#include "BF2VoipClient.h" +#include "VoipMixer.h" + +#include +#include +#include + +#include "../../Core/Ids.h" // IID_IGameServer / IID_IGameClient +#include "../../Core/SmartItf.h" // classManager (ds:0x9FF960) +#include "../../Core/System.h" // g_system (ds:0x99E2B8) +#include "../../IO/Network/NetworkLayer/Socket/UDPSocket.h" // nameToAddress (0x6AD8B0) +#include "../../IO/Network/ProtocolLayer/NetServer.h" // getServerAddress +#include "../../Menu/BF2HudManager.h" // getMode / getCommander +#include "../../Menu/HudCommander.h" // isSquadSelected +#include "../../Scene/Object/PlayerManager.h" // world::playerManager (ds:0xA08F60) +#include "../../Sound/BfSound.h" // g_bfSound (ds:0xA23DC0) +#include "../AudioSettings.h" // IAudioSettings +#include "../IGame.h" // game (ds:0x99E348) +#include "../IGameClient.h" +#include "../IGameLogic.h" // gameLogic (ds:0x99EF80) +#include "../IGameServer.h" +#include "../Main/BF2ClientSeams.h" // hudManager (ds:0xA10890) +#include "../Objects/IPlayer.h" + +namespace dice { +namespace hfe { + +class BF2Engine; +extern BF2Engine* bf2Engine; // Core/Globals.cpp; ds:0x986F48 + +VoipBandPassFilter* BF2VoipClient::s_captureFilter = 0; // ds:0x9A4DA4 + +namespace { + +const int kGameStatusPreGame = 3; // GameStatus_PreGame +const int kHudModeCommanderMap = 0xF; // BF2HudManager::getMode, the commander screen + +world::IPlayer* localPlayer() +{ + return world::playerManager->getLocalHumanPlayer(); // +0x30 +} + +double now() +{ + return g_system->getExactTime(); // ds:0x99E2B8 +0x14 +} + +IAudioSettings* audioSettings() +{ + return static_cast(classManager->getSingleton(std::string("AudioSettings"))); +} + +} // namespace + +BF2VoipClient::BF2VoipClient() + : m_usingLeaderChannel(false), m_pushToTalkPressed(false), m_pushToTalkEnabled(true), + m_localMuted(false), m_talkLimit(10.0), m_mutedAt(0.0), m_muteDuration(5.0), + m_noSquadsSelected(false), m_userDisabled(false), m_internetServer(true) +{ + // 0x451A11: one filter, shared by every client and created by the first. + if (!s_captureFilter) + s_captureFilter = new VoipBandPassFilter(); + s_captureFilter->setup(2.0, 2500.0, 8000.0, 1.75, true); // 0x89C180 / 0x89C188 / 0x89C190 / 0x89C198 +} + +BF2VoipClient::~BF2VoipClient() +{ + if (s_captureFilter) + { + delete s_captureFilter; + s_captureFilter = 0; + } +} + +// Each captured frame goes through the band-pass filter (its history cleared per frame), then is +// clamped to 16 bits and truncated back into the buffer. +void BF2VoipClient::captureFilter(VoipDevice, std::int16_t* audio, std::uint16_t) +{ + s_captureFilter->reset(); + int samplesPerFrame = 0; + gvGetCodecInfo(&samplesPerFrame, 0, 0); + for (int i = 0; i < samplesPerFrame; ++i) + audio[i] = static_cast(s_captureFilter->process(static_cast(audio[i]), 32767.0)); +} + +bool BF2VoipClient::setEnabled(bool enabled) +{ + if (!m_active) + return false; + if (enabled && m_userDisabled) + return false; + if (gameLogic && gameLogic->getGameStatus() != kGameStatusPreGame && !localPlayer()) + { + m_receiveEnabled = false; + m_sendEnabled = false; + return false; + } + m_receiveEnabled = enabled; + m_sendEnabled = enabled; + return true; +} + +// Disabling turns the transport off and tells the server through the local player; enabling starts +// the session again when it is not running (outside the pre-game) and re-announces the player. +bool BF2VoipClient::setUserDisabled(bool disabled) +{ + world::IPlayer* local = world::playerManager ? localPlayer() : 0; + if (disabled) + { + m_userDisabled = disabled; + setEnabled(false); + if (local) + local->setVoipEnabled(false); // +0x28C + return true; + } + if (!m_active && gameLogic && gameLogic->getGameStatus() != kGameStatusPreGame) + { + if (!startSession(m_serverAddress, m_serverPort, m_localPort, m_quality, m_useMixer)) + return false; + } + m_userDisabled = false; + if (local) + local->setVoipEnabled(true); + return true; +} + +// A squad leader talks on the commander channel and a commander on the leaders' channel; anybody +// else always uses the default channel. +bool BF2VoipClient::updateLeaderChannel(bool pressed) +{ + if (!m_active) + return false; + world::IPlayer* local = localPlayer(); // no playerManager test, as shipped + if (!local) + return false; + if (!local->getIsSquadLeader() && !local->getIsCommander()) + { + m_usingLeaderChannel = false; + setHeaderMode(1, 0); + return m_usingLeaderChannel; + } + if (local->getIsSquadLeader()) + return squadLeaderChannel(pressed); + if (local->getIsCommander()) + return commanderChannel(pressed); + m_usingLeaderChannel = false; + return false; +} + +bool BF2VoipClient::getUsingLeaderChannel() { return m_usingLeaderChannel; } +bool BF2VoipClient::getPushToTalkEnabled() { return m_pushToTalkEnabled; } +void BF2VoipClient::setPushToTalkEnabled(bool on) { m_pushToTalkEnabled = on; } +bool BF2VoipClient::getPushToTalkPressed() { return m_pushToTalkPressed; } + +// Push to talk opens the capture gate (threshold 0) on press and closes it (threshold 1) on release. +bool BF2VoipClient::setPushToTalk(bool pressed) +{ + if (!m_pushToTalkEnabled) + return false; + if (!m_pushToTalkPressed && pressed) + setCaptureThreshold(0.0f); + if (m_pushToTalkPressed && !pressed) + { + setCaptureThreshold(1.0f); + onVoiceEnded(); + } + m_pushToTalkPressed = pressed; + return true; +} + +bool BF2VoipClient::squadLeaderChannel(bool pressed) +{ + if (!m_active) + return false; + m_usingLeaderChannel = pressed; + if (pressed) + setHeaderMode(2, 1); + else + setHeaderMode(1, 0); + return m_usingLeaderChannel; +} + +// The commander's key held talks to every squad leader (default channel, mode 1); released, the +// commander screen's selected squads become the channel list (mode 3). +bool BF2VoipClient::commanderChannel(bool pressed) +{ + if (!m_active) + return false; + m_usingLeaderChannel = pressed; + const bool onMap = hudManager->getMode() == kHudModeCommanderMap; // +0x1E0 + if (pressed) + { + m_noSquadsSelected = false; + setHeaderMode(1, 0); + return m_usingLeaderChannel; + } + // The vector is released, not cleared (0x4522AB..0x4522D1). + std::vector().swap(m_channelList); + if (onMap) + { + for (int squad = 1; squad < 10; ++squad) + { + if (hudManager->getCommander()->isSquadSelected(squad)) // +0x258, +0x30 + m_channelList.push_back(static_cast(squad)); + } + } + if (m_channelList.empty()) + { + if (onMap) + m_noSquadsSelected = true; + m_usingLeaderChannel = false; + return false; + } + m_noSquadsSelected = false; + useChannelListHeader(); + return m_usingLeaderChannel; +} + +void BF2VoipClient::setLocalMuted(bool muted) +{ + if (!m_active) + return; + world::IPlayer* local = localPlayer(); + if (!local) + return; + local->setIsMuted(muted); // +0x284 + m_localMuted = muted; + m_mutedAt = muted ? now() : 0.0; +} + +// [INFERRED] name: mutes the local player and stores the duration (0x451880). +void BF2VoipClient::muteFor(double seconds) +{ + if (!m_active) + return; + setLocalMuted(true); + m_muteDuration = seconds; +} + +void BF2VoipClient::slotC0(int, int) {} + +bool BF2VoipClient::mixerOpen() { return VoipMixer::getInstance()->open(); } +bool BF2VoipClient::mixerHasBoost() { return VoipMixer::getInstance()->findBoostControl(0); } +bool BF2VoipClient::mixerSetBoost(bool enabled) { return VoipMixer::getInstance()->setBoost(enabled); } +bool BF2VoipClient::mixerSetCaptureVolume(float v) { return VoipMixer::getInstance()->setCaptureVolume(v); } +bool BF2VoipClient::mixerGetBoost(bool* enabled) { return VoipMixer::getInstance()->getBoost(enabled); } +bool BF2VoipClient::mixerGetCaptureVolume(float volume) +{ + return VoipMixer::getInstance()->getCaptureVolume(&volume); // into the argument's own slot +} +bool BF2VoipClient::mixerSelectMicrophone() { return VoipMixer::getInstance()->selectMicrophoneRecordingSource(); } +bool BF2VoipClient::mixerSetMonitorMute(bool muted) { return VoipMixer::getInstance()->setMicrophoneMonitorMute(muted); } + +// Talking loud enough for the HUD's "voice busy" cue (0x89C2B0 = 0.95). +bool BF2VoipClient::isBusy() +{ + return m_capturing && m_captureLevel > 0.95; +} + +void BF2VoipClient::onDeviceUnplugged(GVDevice device) +{ + if (m_active && world::playerManager && localPlayer()) + localPlayer()->setVoipEnabled(false); + deviceUnplugged(device); +} + +// While anybody is heard, sound group 0 is muted (0x4518D0). +void BF2VoipClient::updateTalkDucking() +{ + if (!g_bfSound || !bf2Engine) + return; + GVSource talking[2]; + const int count = gvListTalkingSources(m_playbackDevice, talking, 1); // 0x58DDA0 + g_bfSound->setMuteState(static_cast(0), count != 0); // +0xB4 +} + +// True while at most 12 frames wait in the capture buffer. Only on internet servers; captured audio +// is then sent once the backlog exceeds that (0x451610). +bool BF2VoipClient::captureBacklogLow() +{ + if (!m_internetServer) + return false; + return gvGetAvailableCaptureBytes(m_captureDevice) / m_encodedFrameSize <= 12; // 0x58DD50 +} + +bool BF2VoipClient::canTransmit() +{ + return !m_pushToTalkEnabled || m_pushToTalkPressed; +} + +void BF2VoipClient::unpluggedCallback(GVDevice device) +{ + bf2VoipClient->onDeviceUnplugged(device); + bf2VoipClient->setEnabled(false); +} + +// Address 1 is the game server's own address: the listen server's NetServer address (127.0.0.1 +// without one), or for a client the joined "host:port" resolved through UDPSocket. Address 0, a +// disabled VoIP setting or a failed start marks the user as disabled. +bool BF2VoipClient::startSession(std::uint32_t address, std::uint16_t port, std::uint16_t localPort, + int quality, bool useMixer) +{ + if (address == 0) + { + m_userDisabled = true; + return false; + } + m_serverPort = port; + m_localPort = localPort; + m_serverAddress = address; + m_quality = quality; + m_useMixer = useMixer; + IAudioSettings* settings = audioSettings(); + if (!settings || !settings->getVoipEnabled()) // +0x38 + { + m_userDisabled = true; + return false; + } + if (address == 1) + { + if (gameLogic->isServer()) // +0x13C + { + std::string local("127.0.0.1"); + IGameServer* server = game ? static_cast(game->queryInterface(IID_IGameServer)) : 0; + if (server) + { + io::NetServer* netServer = server->getNetServer(); // +0xBC + if (netServer) + local = netServer->getServerAddress(); // +0x8C + } + address = static_cast(::inet_addr(local.c_str())); + } + else + { + IGameClient* client = game ? static_cast(game->queryInterface(IID_IGameClient)) : 0; + if (client) + { + const std::string host = client->getServerAddress(); // +0x40 + io::ISocket::Address resolved; + std::memset(&resolved, 0, sizeof(resolved)); + resolved.length = 16; + io::UDPSocket::nameToAddress(host, &resolved, 0); + std::memcpy(&address, &resolved.sockaddr[4], 4); + } + } + } + if (!VoipClient::startSession(address, port, localPort, quality, useMixer)) + { + m_userDisabled = true; + return false; + } + setUnpluggedCallback(m_captureDevice, &BF2VoipClient::unpluggedCallback); + setUnpluggedCallback(m_playbackDevice, &BF2VoipClient::unpluggedCallback); + gvSetFilter(m_captureDevice, GV_CAPTURE, &BF2VoipClient::captureFilter); // 0x58DD20 + setPlaybackVolume(settings->getVoipPlaybackVolume()); // +0x40 + setCaptureVolume(settings->getVoipCaptureVolume()); // +0x48 + VoipMixer::getInstance()->setBoost(settings->getVoipBoostEnabled()); // +0x58 + m_pushToTalkEnabled = settings->getVoipUsePushToTalk(); // +0x60 + if (m_pushToTalkEnabled) + setCaptureThreshold(1.0f); + else + setCaptureThreshold(settings->getVoipCaptureThreshold()); // +0x50 + IGameServer* server = game ? static_cast(game->queryInterface(IID_IGameServer)) : 0; + if (server) + m_internetServer = server->getIsInternetServer(); // +0x8C + return true; +} + +// The local player's datagrams: frame stamp, then sender session id at the end. Muted senders are +// dropped. Malformed lengths are rejected before reading the trailer or looking up the sender. +bool BF2VoipClient::handleIncoming(std::uint8_t* packet, int length, std::uint16_t* sender) +{ + if (!m_active || !m_playbackDevice) + return false; + // [CHOSEN, not recovered] Reject truncated trailers and incomplete codec frames. + // https://github.com/kr4uzi/OpenBF2/issues/26 + if (length <= 4 || m_encodedFrameSize <= 0 || (length - 4) % m_encodedFrameSize != 0) + return false; + std::memcpy(sender, packet + length - 2, 2); + length -= 2; + world::IPlayer* player = world::playerManager->getPlayerFromId(*sender); // +0x20 + if (!player || player->getIsMuted()) // +0x274 + return false; + std::uint16_t frameStamp = 0; + std::memcpy(&frameStamp, packet + length - 2, 2); + length -= 2; + gvPlayPacket(m_playbackDevice, packet, length, static_cast(*sender), frameStamp, GVFalse); + return true; +} + +bool BF2VoipClient::think(int* receiveError, int* sendError) +{ + if (!m_active || !m_captureDevice) + return false; + if (receiveError) + *receiveError = 0; + if (sendError) + *sendError = 0; + if (!m_receiveEnabled) + return true; + std::uint8_t buffer[0x400]; + std::uint16_t sender[2] = { 0, 0 }; + int received; + do + { + sockaddr_in from; +#if defined(_WIN32) + int fromLength = 0x10; +#else + socklen_t fromLength = 0x10; +#endif + received = static_cast(::recvfrom(m_socket, reinterpret_cast(buffer), 0x400, 0, + reinterpret_cast(&from), &fromLength)); + if (received > 0) + { + if (handleIncoming(buffer, received, sender)) + onIncomingHandled(sender); + } + else if (received == -1) + { +#if defined(_WIN32) + const int error = ::WSAGetLastError(); + const bool wouldBlock = error == WSAEWOULDBLOCK; +#else + const int error = errno; + const bool wouldBlock = error == EWOULDBLOCK || error == EAGAIN; +#endif + if (!wouldBlock && receiveError) + *receiveError = error; + break; + } + } while (received > 0); + // 0x4514F4: the backlog test runs once, before the capture loop (its back edge is 0x451502). + if (captureBacklogLow()) + return !(receiveError && *receiveError) && !(sendError && *sendError); + for (;;) + { + int length = 0x3FE; + GVFrameStamp stamp = 0; + GVScalar volume = 0.0; + if (!gvCapturePacket(m_captureDevice, buffer, &length, &stamp, &volume)) + break; + onCaptureLevel(volume); + if (m_localMuted || m_noSquadsSelected || !canTransmit()) + continue; + std::memcpy(buffer + length, &stamp, 2); + length += 2; + if (sendCaptured(buffer, &length) != -1) + continue; +#if defined(_WIN32) + const int error = ::WSAGetLastError(); + const bool wouldBlock = error == WSAEWOULDBLOCK; +#else + const int error = errno; + const bool wouldBlock = error == EWOULDBLOCK || error == EAGAIN; +#endif + if (!wouldBlock && sendError) + *sendError = error; + } + if (receiveError && *receiveError) + return false; + if (sendError && *sendError) + return false; + return true; +} + +// The local player's talking flag follows the capture level; ten seconds of continuous talk mute +// the player for m_muteDuration. +void BF2VoipClient::onCaptureLevel(double level) +{ + if (!m_localLoopback && !canTransmit()) + return; + if (!m_active || !gameLogic || gameLogic->getGameStatus() == kGameStatusPreGame) + { + VoipClient::onCaptureLevel(level); + return; + } + world::IPlayer* local = localPlayer(); + if (!local) + return; + if (m_captureStart == 0.0) + { + m_captureStart = now(); + m_capturing = true; + } + m_captureLevel = level; + m_lastCapture = now(); + if (m_lastCapture - m_captureStart > m_talkLimit) + muteFor(m_muteDuration); + if (!m_localMuted) + local->setIsTalking(m_capturing); // +0x288 +} + +void BF2VoipClient::onVoiceEnded() +{ + VoipClient::onVoiceEnded(); + world::IPlayer* local = localPlayer(); + if (local) + local->setIsTalking(m_capturing); +} + +void BF2VoipClient::onIncomingHandled(std::uint16_t* sender) +{ + if (!m_active) + return; + world::IPlayer* player = world::playerManager->getPlayerFromId(*sender); + if (player) + player->setIsTalking(true); +} + +// Per frame: GameSpy's think, the channel enable from squad membership, the commander screen, the +// transport, the anti-spam unmute, the talk timeout, the keep-alive and the sound ducking. +bool BF2VoipClient::updateClient() +{ + if (!m_active) + return false; + if (!m_playbackDevice) + return false; + gvThink(); + if (!m_playbackDevice) + return false; + world::IPlayer* local = localPlayer(); + if (!local) + return false; + if (local->getSquadId() != 0 || local->getIsCommander()) // +0x108 / +0x110 + setEnabled(true); + else + setEnabled(false); + if (m_noSquadsSelected + && !(local->getIsCommander() && hudManager->getMode() == kHudModeCommanderMap)) + m_noSquadsSelected = false; + if (m_localLoopback) + { + localLoopbackThink(); + } + else + { + int receiveError = 0; + int sendError = 0; + if (!think(&receiveError, &sendError) && (receiveError || sendError)) + { + // The message is built and dropped: its sink is compiled out of the shipped image. + std::stringstream message(std::ios::in | std::ios::out); + message << "BF2VoipClient socket send/receive error. ReceiveResult = " << receiveError + << " SendResult = " << sendError; + } + } + if (local->getIsMuted() && !m_capturing) + setLocalMuted(false); + if (m_captureStart != 0.0 && local->getStopTalkingThreshold() < now() - m_lastCapture) // +0x280 + onVoiceEnded(); + keepAliveTick(); + updateTalkDucking(); + return true; +} + +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/Game/VoipClient/BF2VoipClient.h b/Code/BF2/Game/VoipClient/BF2VoipClient.h new file mode 100644 index 000000000..37e8bdb9a --- /dev/null +++ b/Code/BF2/Game/VoipClient/BF2VoipClient.h @@ -0,0 +1,91 @@ +// The game's voice client: VoipClient bound to the local player, the squad/commander channels, push +// to talk, the anti-spam mute and the menu's AudioSettings. BF2.exe 0x4510F0..0x45235C, vtable +// 0x89C1A8 (64 slots), ctor 0x4519B0, 0xC8 bytes. Created by BF2Engine::initEngine (0x40C351) and +// registered as the "Bf2VoipClient" singleton (ds:0x9A4DA0); SwiffPlayer reaches it through +// getSingleton and calls these slots across the DLL boundary, so their order is ABI. +#ifndef BF2_GAME_VOIPCLIENT_BF2VOIPCLIENT_H +#define BF2_GAME_VOIPCLIENT_BF2VOIPCLIENT_H + +#include "VoipClient.h" + +namespace dice { +namespace hfe { + +class BF2VoipClient : public VoipClient +{ +public: + BF2VoipClient(); // 0x4519B0 + virtual ~BF2VoipClient(); // +0x00 0x451DB0 + + // Overrides of the VoipClient slots. + virtual bool startSession(std::uint32_t address, std::uint16_t port, std::uint16_t localPort, + int quality, bool useMixer); // +0x2C 0x451B60 + virtual bool setEnabled(bool enabled); // +0x50 0x451160 + virtual bool handleIncoming(std::uint8_t* packet, int length, std::uint16_t* sender); // +0x70 0x451640 + virtual bool think(int* receiveError, int* sendError); // +0x74 0x451420 + virtual void onCaptureLevel(double level); // +0x7C 0x4516D0 + virtual void onVoiceEnded(); // +0x80 0x4517C0 + virtual void onIncomingHandled(std::uint16_t* sender); // +0x84 0x4517F0 + + // BF2VoipClient's own slots. + virtual bool setUserDisabled(bool disabled); // +0x98 0x4511D0 + // [INFERRED] name. A slot of its own: VoipClient::update (+0x64) stays the base body, which + // SwiffPlayer ticks for the menu's voice test. + virtual bool updateClient(); // +0x9C 0x451E00 + virtual bool getUsingLeaderChannel(); // +0xA0 0x4B72C0 (+0xA0) + virtual bool updateLeaderChannel(bool pressed); // +0xA4 0x4512A0 + virtual bool getPushToTalkEnabled(); // +0xA8 0x4B7300 (+0xA2) + virtual void setPushToTalkEnabled(bool enabled); // +0xAC 0x4B7310 + virtual bool getPushToTalkPressed(); // +0xB0 0x4B72E0 (+0xA1) + virtual bool setPushToTalk(bool pressed); // +0xB4 0x451360 + virtual void setLocalMuted(bool muted); // +0xB8 0x451820 + virtual void muteFor(double seconds); // +0xBC 0x451880 + virtual void slotC0(int, int); // +0xC0 0x5A59F0, empty + // +0xC4..+0xE0: thin forwards to the microphone mixer singleton (BF2.exe 0x451A90..0x451B4E). + virtual bool mixerOpen(); // +0xC4 -> 0x736BD0 + virtual bool mixerHasBoost(); // +0xC8 -> 0x735A40(null) + virtual bool mixerSetBoost(bool enabled); // +0xCC -> 0x735BB0 + virtual bool mixerSetCaptureVolume(float volume); // +0xD0 -> 0x735CD0 + virtual bool mixerGetBoost(bool* enabled); // +0xD4 -> 0x735D00 + // 0x451B10 takes the float by value and hands the mixer the address of its own argument slot, + // so the volume read is lost and only the success flag reaches the caller. Reproduced. + virtual bool mixerGetCaptureVolume(float volume); // +0xD8 -> 0x735DD0 + virtual bool mixerSelectMicrophone(); // +0xDC -> 0x735EA0 + virtual bool mixerSetMonitorMute(bool muted); // +0xE0 -> 0x7361E0 + virtual bool isBusy(); // +0xE4 0x451A70 + virtual void onDeviceUnplugged(VoipDevice device); // +0xE8 0x451940 + virtual bool squadLeaderChannel(bool pressed); // +0xEC 0x4513D0 + virtual bool commanderChannel(bool pressed); // +0xF0 0x452250 + virtual void updateTalkDucking(); // +0xF4 0x4518D0 + virtual bool captureBacklogLow(); // +0xF8 0x451610 + virtual bool canTransmit(); // +0xFC 0x4518B0 + + // The gvFilterCallback on the capture device (0x4510F0) and the unplugged callback (0x451920). + // The types are gv.h's GVDevice, GVSample (gsi_i16) and GVFrameStamp (gsi_u16). + static void captureFilter(VoipDevice device, std::int16_t* audio, std::uint16_t frameStamp); + static void unpluggedCallback(VoipDevice device); + + bool m_usingLeaderChannel; // +0xA0 + bool m_pushToTalkPressed; // +0xA1 + bool m_pushToTalkEnabled; // +0xA2 initial 1 + bool m_localMuted; // +0xA3 + double m_talkLimit; // +0xA8 10.0 seconds of continuous talk before the anti-spam mute + double m_mutedAt; // +0xB0 simulation time of setLocalMuted(true), 0 otherwise + double m_muteDuration; // +0xB8 5.0 + bool m_noSquadsSelected; // +0xC0 commander on the map with no squad selected + bool m_userDisabled; // +0xC1 + bool m_internetServer; // +0xC2 initial 1; gameServer->getIsInternetServer at session start + + static VoipBandPassFilter* s_captureFilter; // ds:0x9A4DA4 +}; +#if defined(_M_IX86) +static_assert(sizeof(BF2VoipClient) == 0xC8, "BF2VoipClient must keep the retail x86 allocation size"); +#endif + +// ds:0x9A4DA0, the "Bf2VoipClient" singleton slot (defined in Game/Main/BF2Engine.cpp). +extern BF2VoipClient* bf2VoipClient; + +} // namespace hfe +} // namespace dice + +#endif diff --git a/Code/BF2/Game/VoipClient/VoipClient.cpp b/Code/BF2/Game/VoipClient/VoipClient.cpp new file mode 100644 index 000000000..77e4e3c57 --- /dev/null +++ b/Code/BF2/Game/VoipClient/VoipClient.cpp @@ -0,0 +1,737 @@ +// BF2.exe 0x736C30..0x737B00 (VoipClient) and 0x737B60..0x737D4E (VoipBandPassFilter). See VoipClient.h. +#if defined(_WIN32) +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#endif + +#include "../../External/GameSpy/Voice2/gv.h" +#include "VoipClient.h" +#include "VoipFakeDevice.h" +#include "VoipMixer.h" + +#include +#include + +namespace dice { +namespace hfe { + +VoipClient* VoipClient::s_instance = 0; // ds:0xA10880 +std::uint32_t VoipClient::s_lastKeepAlive = 0; // ds:0xA10884 + +namespace { + +// 0x736E0A..0x736E28: fcomp 0.0 then fcomp 1.0; only an ordered value outside [0, 1] is refused. +bool outsideUnitRange(float value) { return value < 0.0f || value > 1.0f; } + +// [PLATFORM] Winsock on Windows; BSD sockets elsewhere, with the Winsock-1.1 call shapes kept. +#if defined(_WIN32) +const VoipSocket kInvalidSocket = static_cast(INVALID_SOCKET); // -1, as the ctor stores +int socketError() { return ::WSAGetLastError(); } // IAT 0x87F904 +bool isWouldBlock(int error) { return error == WSAEWOULDBLOCK; } // 0x2733 +void closeVoipSocket(VoipSocket s) { ::closesocket(s); } // 0x660E54 +// 0x660B30: ioctlsocket(FIONBIO), the argument being "blocking == false". +void setNonBlocking(VoipSocket s, bool blocking) +{ + u_long nonBlocking = blocking ? 0 : 1; + ::ioctlsocket(s, FIONBIO, &nonBlocking); +} +// 0x5A0350: Winsock 1.1 startup, the result unused. +void startupSockets() +{ + WSADATA data; + ::WSAStartup(0x101, &data); +} +typedef int SockLen; +#else +const VoipSocket kInvalidSocket = -1; +int socketError() { return errno; } +bool isWouldBlock(int error) { return error == EWOULDBLOCK || error == EAGAIN; } +void closeVoipSocket(VoipSocket s) { ::close(s); } +void setNonBlocking(VoipSocket s, bool blocking) +{ + int nonBlocking = blocking ? 0 : 1; + ::ioctl(s, FIONBIO, &nonBlocking); +} +void startupSockets() {} +typedef socklen_t SockLen; +#endif + +// Retail converts the unsigned tick through fild and adds 2^32 when the sign bit is set. +double tickAsDouble(std::uint32_t tick) { return static_cast(tick); } + +// The four codec qualities the session offers: BF2 quality 1..5 picks the GameSpy codec from +// low bandwidth up, anything else the low-bandwidth codec (0x736D80's jump table at 0x736DE8). +// [CHOSEN, not recovered] by name: the 2.08 SDK enum gained GVCodecRaw at 0, so retail's values +// 4,3,2,1,0 are SuperLowBandwidth..SuperHighQuality here (Speex quality 1,2,4,7,10 either way). +GVCodec codecForQuality(int quality) +{ + switch (quality) + { + case 1: return GVCodecSuperLowBandwidth; + case 2: return GVCodecLowBandwidth; + case 3: return GVCodecAverage; + case 4: return GVCodecHighQuality; + case 5: return GVCodecSuperHighQuality; + default: return GVCodecLowBandwidth; + } +} + +const int kPacketBuffer = 0x400; // the receive/capture buffer on the stack +const int kCaptureRoom = 0x3FE; // gvCapturePacket's room: two bytes are kept for the frame stamp + +} // namespace + +// ---- VoipBandPassFilter ---------------------------------------------------------------------------- + +VoipBandPassFilter::VoipBandPassFilter() + : m_b0(0.0), m_b1(0.0), m_b2(0.0), m_a1(0.0), m_a2(0.0), + m_x1(0.0), m_x2(0.0), m_y1(0.0), m_y2(0.0), + m_enabled(false), m_gain(0.0), m_frequency(0.0), m_sampleRate(0.0), m_bandwidth(0.0) +{ +} + +void VoipBandPassFilter::reset() +{ + m_x2 = 0.0; + m_x1 = 0.0; + m_y2 = 0.0; + m_y1 = 0.0; +} + +double VoipBandPassFilter::process(double sample, double limit) +{ + if (!m_enabled) + return sample; + const double y = m_b1 * m_x1 + m_b2 * m_x2 + sample * m_b0 - m_a1 * m_y1 - m_a2 * m_y2; + m_x2 = m_x1; + m_x1 = sample; + m_y2 = m_y1; + m_y1 = y; + double out = y * m_gain; + if (!(out < limit)) + out = limit; + if (out <= -limit) + out = -limit; + return out; +} + +void VoipBandPassFilter::setup(double gain, double frequency, double sampleRate, double bandwidth, + bool enabled) +{ + m_gain = gain; + m_enabled = enabled; + m_frequency = frequency; + m_sampleRate = sampleRate; + m_bandwidth = bandwidth; + const double w0 = frequency / sampleRate * 6.283185307179586; // 0x920CF0 + const double sinW0 = std::sin(w0); + const double alpha = std::sinh(w0 / sinW0 * bandwidth * 0.34657359027997264) * sinW0; // ln2/2 + const double inverseA0 = 1.0 / (1.0 + alpha); + m_b0 = inverseA0 * alpha; + m_b1 = 0.0 * inverseA0; + m_b2 = -alpha * inverseA0; + m_a1 = std::cos(w0) * -2.0 * inverseA0; // 0x920CE0 + m_a2 = (1.0 - alpha) * inverseA0; + reset(); +} + +// ---- VoipClient -------------------------------------------------------------------------------------- + +std::uint32_t VoipClient::tickCount() +{ +#if defined(_WIN32) + return ::GetTickCount(); // IAT 0x87F0AC via 0x67CC40 +#else + timespec now; + ::clock_gettime(CLOCK_MONOTONIC, &now); + return static_cast(static_cast(now.tv_sec) * 1000u + + static_cast(now.tv_nsec) / 1000000u); +#endif +} + +VoipClient::VoipClient() + : m_active(false), m_testing(false), m_playerId(0), + m_serverAddress(0), m_serverPort(0), m_localPort(0), m_useMixer(true), + m_quality(0), m_encodedFrameSize(0x14), m_socket(kInvalidSocket), + m_captureDevice(0), m_playbackDevice(0), m_deviceLost(false), m_headerMode(1), m_channel(0), + m_initialThreshold(0.1), // 0x912480 + m_sendEnabled(true), m_receiveEnabled(false), m_keepAliveEnabled(true), + m_keepAliveInterval(3.0f), m_unused60(false), m_capturing(false), + m_captureLevel(0.0), m_captureStart(0.0), m_lastCapture(0.0), m_voiceTimeout(500.0f), + m_channelListAllocator(0), m_localLoopback(false), m_loopbackSilent(false), + m_savedMonitorMute(-1), m_savedBoost(-1) +{ + std::memset(&m_serverSockAddr, 0, sizeof(m_serverSockAddr)); + std::memset(&m_localSockAddr, 0, sizeof(m_localSockAddr)); + s_instance = this; // 0x737A98 +} + +VoipClient::~VoipClient() +{ + shutdown(); // 0x737B0C +} + +void VoipClient::setServerAddress(std::uint32_t address, std::uint16_t port) +{ + m_serverAddress = address; + m_serverPort = port; +} + +bool VoipClient::openSocket() +{ + startupSockets(); + m_socket = static_cast(::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)); // 0x660E72(2, 2, 17) + if (m_socket == kInvalidSocket) + return false; + setNonBlocking(m_socket, false); + sockaddr_in local; + std::memset(&local, 0, sizeof(local)); + local.sin_family = AF_INET; + local.sin_port = htons(m_localPort); + std::memcpy(m_localSockAddr.bytes, &local, 16); + if (::bind(m_socket, reinterpret_cast(m_localSockAddr.bytes), 0x10) == -1) // 0x67BD2A + return false; + sockaddr_in server; + std::memset(&server, 0, sizeof(server)); + server.sin_family = AF_INET; + server.sin_port = htons(m_serverPort); + server.sin_addr.s_addr = m_serverAddress; + std::memcpy(m_serverSockAddr.bytes, &server, 16); + return true; +} + +// Starts GameSpy Voice, selects the codec and opens the first capture-capable and the first +// playback-capable device (one device may serve both). Success needs both. +bool VoipClient::initVoice() +{ +#if defined(_WIN32) + if (!gvStartup(0)) // 0x58DBD0, no window +#else + if (!gvStartup()) +#endif + return false; + if (!setCodec(m_quality)) + return false; + if (VoipFakeDevice::requested()) + { + // [CHOSEN, not recovered] BF2_VOIP_CAPTURE=fake: one synthetic device serves both directions, + // set up exactly as the loop below sets up a hardware device that offers both. + GVDevice device = VoipFakeDevice::create(); + if (!device) + return false; + setUnpluggedCallback(device, &VoipClient::unpluggedCallback); + m_captureDevice = device; + gvSetCaptureThreshold(device, m_initialThreshold); + gvSetDeviceVolume(device, GV_CAPTURE, 1.0); + m_playbackDevice = device; + gvSetDeviceVolume(device, GV_PLAYBACK, 1.0); + gvStartDevice(device, GV_CAPTURE_AND_PLAYBACK); + return true; + } + GVDeviceInfo devices[10]; + const int count = gvListDevices(devices, 10, GV_CAPTURE_AND_PLAYBACK); // 0x58DC60 + if (count == 0) + return false; + for (int i = 0; i < count; ++i) + { + const GVDeviceInfo& info = devices[i]; + int capture = info.m_defaultDevice & GV_CAPTURE; + int playback = info.m_defaultDevice & GV_PLAYBACK; + if (!m_captureDevice && (info.m_deviceType & GV_CAPTURE)) + capture = info.m_deviceType & GV_CAPTURE; + if (!m_playbackDevice && (info.m_deviceType & GV_PLAYBACK)) + playback = info.m_deviceType & GV_PLAYBACK; + if (!playback && !capture) + continue; + GVDeviceType types = 0; + if (playback && !m_playbackDevice) + types = GV_PLAYBACK; + if (capture && !m_captureDevice) + types |= GV_CAPTURE; + GVDevice device = gvNewDevice(info.m_id, types); // 0x58DC70 + if (!device) + continue; + setUnpluggedCallback(device, &VoipClient::unpluggedCallback); + if (types & GV_CAPTURE) + { + m_captureDevice = device; + gvSetCaptureThreshold(device, m_initialThreshold); // 0x58DD60 + gvSetDeviceVolume(device, GV_CAPTURE, 1.0); // 0x58DCB0 + } + if (types & GV_PLAYBACK) + { + m_playbackDevice = device; + gvSetDeviceVolume(device, GV_PLAYBACK, 1.0); + } + gvStartDevice(device, types); // 0x58DCA0 + } + return m_captureDevice && m_playbackDevice; +} + +bool VoipClient::setCodec(int quality) +{ + if (!gvSetCodec(codecForQuality(quality))) // 0x58DC10 + return false; + int samplesPerFrame = 0; + int bitsPerSecond = 0; + gvGetCodecInfo(&samplesPerFrame, &m_encodedFrameSize, &bitsPerSecond); // 0x58DC20 + return true; +} + +bool VoipClient::setCaptureThreshold(float threshold) +{ + if (!m_captureDevice || outsideUnitRange(threshold)) + return false; + gvSetCaptureThreshold(m_captureDevice, threshold); + return true; +} + +bool VoipClient::getCaptureThreshold(double* threshold) +{ + if (!m_captureDevice) + return false; + *threshold = gvGetCaptureThreshold(m_captureDevice); // 0x58DD80 + return true; +} + +bool VoipClient::setPlaybackVolume(float volume) +{ + if (!m_playbackDevice || outsideUnitRange(volume)) + return false; + gvSetDeviceVolume(m_playbackDevice, GV_PLAYBACK, volume); + return true; +} + +bool VoipClient::setCaptureVolume(float volume) +{ + if (!m_captureDevice || outsideUnitRange(volume)) + return false; + gvSetDeviceVolume(m_captureDevice, GV_CAPTURE, volume); + return true; +} + +double VoipClient::getCaptureVolume() { return gvGetDeviceVolume(m_captureDevice, GV_CAPTURE); } +double VoipClient::getPlaybackVolume() { return gvGetDeviceVolume(m_playbackDevice, GV_PLAYBACK); } + +bool VoipClient::startSession(std::uint32_t address, std::uint16_t port, std::uint16_t localPort, + int quality, bool useMixer) +{ + if (m_active) + return true; + m_localPort = localPort; + m_quality = quality; + m_useMixer = useMixer; + setServerAddress(address, port); + if (!openSocket()) + return false; + if (m_testing) + { + // A running test already owns the devices; only the codec follows the session. + if (!setCodec(m_quality)) + return false; + m_active = true; + return true; + } + if (m_deviceLost) + return false; + if (!initVoice()) + return false; + if (useMixer) + initMixer(); + m_active = true; + return true; +} + +bool VoipClient::startTest(int quality, bool useMixer) +{ + if (m_active || m_testing) + return true; + m_quality = quality; + if (m_deviceLost) + return false; + if (!initVoice()) + return false; + m_receiveEnabled = true; + m_sendEnabled = false; + if (useMixer) + initMixer(); + m_testing = true; + return true; +} + +bool VoipClient::isTesting() { return m_testing; } +bool VoipClient::isActive() { return m_active; } + +bool VoipClient::getCaptureLevel(double* level) +{ + *level = m_captureLevel; + return m_capturing; +} + +void VoipClient::setHeaderMode(std::uint8_t mode, std::uint8_t channel) +{ + m_headerMode = mode; + m_channel = channel; +} + +bool VoipClient::useChannelListHeader() +{ + if (m_channelList.empty()) + return false; + m_headerMode = 3; + m_channel = 0; + return true; +} + +void VoipClient::setSendEnabled(bool enabled) { m_sendEnabled = enabled; } +void VoipClient::setReceiveEnabled(bool enabled) { m_receiveEnabled = enabled; } + +bool VoipClient::setEnabled(bool enabled) +{ + m_receiveEnabled = enabled; + m_sendEnabled = enabled; + return true; +} + +void VoipClient::setKeepAliveEnabled(bool enabled) { m_keepAliveEnabled = enabled; } + +// A three-byte datagram { session id, 6 } that keeps the server's routing entry for this player. +bool VoipClient::sendKeepAlive() +{ + if (!m_active) + return false; + std::uint8_t packet[0x20]; + std::memset(packet, 0, sizeof(packet)); + std::memcpy(packet, &m_playerId, 2); + packet[2] = 6; + return ::sendto(m_socket, reinterpret_cast(packet), 3, 0, + reinterpret_cast(m_serverSockAddr.bytes), 0x10) != -1; // 0x669E70 +} + +void VoipClient::setKeepAliveInterval(float seconds) { m_keepAliveInterval = seconds; } +void VoipClient::setPlayerId(std::uint16_t id) { m_playerId = id; } + +bool VoipClient::update() +{ + if (!m_active && !m_testing) + return false; + if (m_localLoopback) + localLoopbackThink(); + else if (m_receiveEnabled) + think(0, 0); + if (!m_playbackDevice) + return false; + gvThink(); // 0x58DC00 + if (!m_playbackDevice) + return false; + const std::uint32_t now = tickCount(); + // 0x7376BA: strictly longer than the timeout. + if (m_captureStart != 0.0 && m_voiceTimeout < tickAsDouble(now) - m_lastCapture) + onVoiceEnded(); + keepAliveTick(); + return true; +} + +bool VoipClient::shutdown() +{ + if (!m_active && !m_testing) + return true; + setEnabled(false); + m_testing = false; + m_active = false; + closeSocket(); + if (m_captureDevice) + gvStopDevice(m_captureDevice, GV_CAPTURE); // 0x7385E0 + if (m_playbackDevice) + gvStopDevice(m_playbackDevice, GV_PLAYBACK); + gvCleanup(); // 0x58DBF0 + m_playbackDevice = 0; + m_captureDevice = 0; + if (m_savedMonitorMute != -1) + VoipMixer::getInstance()->setMicrophoneMonitorMute(m_savedMonitorMute != 0); // 0x7361E0 + if (m_savedBoost != -1) + VoipMixer::getInstance()->setBoost(m_savedBoost != 0); // 0x735BB0 + VoipMixer::destroy(); // 0x7356B0 + return true; +} + +int VoipClient::sendCaptured(std::uint8_t* packet, int* length) +{ + if (!m_sendEnabled) + return 0; + return sendPacket(packet, length); +} + +// Incoming datagram: voice frames, then the frame-stamp word and the sender's session-id dword. +// The base plays every sender. Malformed lengths are rejected before reading the trailer. +bool VoipClient::handleIncoming(std::uint8_t* packet, int length, std::uint16_t* sender) +{ + if (!m_playbackDevice) + return false; + // [CHOSEN, not recovered] Reject truncated trailers and incomplete codec frames. + // https://github.com/kr4uzi/OpenBF2/issues/26 + if (length <= 6 || m_encodedFrameSize <= 0 || (length - 6) % m_encodedFrameSize != 0) + return false; + std::uint32_t stamp = 0; + std::memcpy(&stamp, packet + length - 4, 4); + length -= 4; + *reinterpret_cast(sender) = stamp; // retail stores the dword + std::uint16_t source = 0; + std::memcpy(&source, packet + length - 2, 2); + length -= 2; + gvPlayPacket(m_playbackDevice, packet, length, static_cast(stamp), + static_cast(source), GVFalse); // 0x58DD90 + return true; +} + +bool VoipClient::think(int* receiveError, int* sendError) +{ + if ((!m_active && !m_testing) || !m_captureDevice) + return false; + if (receiveError) + *receiveError = 0; + if (sendError) + *sendError = 0; + if (!m_receiveEnabled) + return false; + std::uint8_t buffer[kPacketBuffer]; + std::uint16_t sender[2] = { 0, 0 }; + int received; + do + { + sockaddr_in from; + SockLen fromLength = 0x10; + received = static_cast(::recvfrom(m_socket, reinterpret_cast(buffer), kPacketBuffer, + 0, reinterpret_cast(&from), &fromLength)); + if (received > 0) + { + if (handleIncoming(buffer, received, sender)) + onIncomingHandled(sender); + } + else if (received == -1) + { + const int error = socketError(); + if (receiveError && !isWouldBlock(error)) + *receiveError = error; + break; + } + } while (received > 0); + for (;;) + { + int length = kCaptureRoom; + GVFrameStamp stamp = 0; + GVScalar volume = 0.0; + if (!gvCapturePacket(m_captureDevice, buffer, &length, &stamp, &volume)) // 0x58DD40 + break; + onCaptureLevel(volume); + std::memcpy(buffer + length, &stamp, 2); + length += 2; + if (sendCaptured(buffer, &length) == -1 && sendError) + { + const int error = socketError(); + if (!isWouldBlock(error)) + *sendError = error; + } + } + if (receiveError && *receiveError) + return false; + if (sendError && *sendError) + return false; + return true; +} + +int VoipClient::sendPacket(std::uint8_t* packet, int* length) +{ + if ((!m_active && !m_testing) || !m_sendEnabled) + return 0; + bool written; + switch (m_headerMode) + { + case 1: written = writeHeader(packet, length); break; + case 2: written = writeChannelHeader(packet, length); break; + case 3: written = writeChannelListHeader(packet, length); break; + default: written = false; break; + } + if (!written) + return 0; + return static_cast(::sendto(m_socket, reinterpret_cast(packet), *length, 0, + reinterpret_cast(m_serverSockAddr.bytes), 0x10)); +} + +void VoipClient::onCaptureLevel(double level) +{ + m_capturing = true; + if (m_captureStart == 0.0) + m_captureStart = tickAsDouble(tickCount()); + m_lastCapture = tickAsDouble(tickCount()); + m_captureLevel = level; +} + +void VoipClient::onVoiceEnded() +{ + m_capturing = false; + m_captureStart = 0.0; + m_lastCapture = 0.0; + m_captureLevel = 0.0; +} + +void VoipClient::onIncomingHandled(std::uint16_t*) {} + +float VoipClient::getVoiceTimeout() { return m_voiceTimeout; } +void VoipClient::setVoiceTimeout(float milliseconds) { m_voiceTimeout = milliseconds; } + +void VoipClient::setUnpluggedCallback(GVDevice device, gvUnpluggedCallback callback) +{ + gvSetUnpluggedCallback(device, callback); // 0x58DD10 +} + +void VoipClient::closeSocket() +{ + if (m_socket == kInvalidSocket) + return; + closeVoipSocket(m_socket); + m_socket = kInvalidSocket; +} + +// Opens the mixer, selects the microphone as the recording source at full volume, mutes the +// microphone's speaker monitor and remembers that mute and the boost for shutdown. The answer is the +// monitor-mute call's; both callers ignore it. +bool VoipClient::initMixer() +{ + if (!VoipMixer::getInstance()->open()) // 0x736BD0 + return false; + VoipMixer::getInstance()->selectMicrophoneRecordingSource(); // 0x735EA0 + VoipMixer::getInstance()->setCaptureVolume(1.0f); // 0x735CD0 + bool muted = false; + if (VoipMixer::getInstance()->getMicrophoneMonitorMute(&muted)) // 0x736120 + m_savedMonitorMute = muted; + const bool result = VoipMixer::getInstance()->setMicrophoneMonitorMute(true); // 0x7361E0(1) + bool boost = false; + if (VoipMixer::getInstance()->getBoost(&boost)) // 0x735D00 + m_savedBoost = boost; + return result; +} + +// Local test without a server: capture is drained (and played back unless silent). +void VoipClient::localLoopbackThink() +{ + if ((!m_active && !m_testing) || !m_captureDevice) + return; + std::uint8_t buffer[kPacketBuffer]; + if (m_active) + { + sockaddr_in from; + SockLen fromLength = 0x10; + ::recvfrom(m_socket, reinterpret_cast(buffer), kPacketBuffer, 0, + reinterpret_cast(&from), &fromLength); + } + for (;;) + { + int length = kCaptureRoom; + GVFrameStamp stamp = 0; + GVScalar volume = 0.0; + if (!gvCapturePacket(m_captureDevice, buffer, &length, &stamp, &volume)) + return; + onCaptureLevel(volume); + if (m_loopbackSilent) + continue; + std::memcpy(buffer + length, &stamp, 2); + length += 2; + std::memset(buffer + length, 0, 4); + length += 4; + if (!m_playbackDevice) + continue; + std::uint32_t source = 0; + std::memcpy(&source, buffer + length - 4, 4); + std::uint16_t frameStamp = 0; + std::memcpy(&frameStamp, buffer + length - 6, 2); + gvPlayPacket(m_playbackDevice, buffer, length - 6, static_cast(source), + frameStamp, GVFalse); + } +} + +bool VoipClient::writeHeader(std::uint8_t* packet, int* length) +{ + if (!m_active && !m_testing) + return false; + std::memcpy(packet + *length, &m_playerId, 2); + *length += 2; + packet[*length] = m_headerMode; + *length += 1; + return true; +} + +bool VoipClient::writeChannelHeader(std::uint8_t* packet, int* length) +{ + if (!m_active && !m_testing) + return false; + packet[*length] = m_channel; + *length += 1; + std::memcpy(packet + *length, &m_playerId, 2); + *length += 2; + packet[*length] = m_headerMode; + *length += 1; + return true; +} + +// The squad list, its count, the session id and the mode, after the voice frames. +bool VoipClient::writeChannelListHeader(std::uint8_t* packet, int* length) +{ + if ((!m_active && !m_testing) || m_channelList.empty()) + return false; + for (std::size_t i = 0; i < m_channelList.size(); ++i) + { + packet[*length] = m_channelList[i]; + *length += 1; + } + packet[*length] = static_cast(m_channelList.size()); + *length += 1; + std::memcpy(packet + *length, &m_playerId, 2); + *length += 2; + packet[*length] = m_headerMode; + *length += 1; + return true; +} + +bool VoipClient::keepAliveTick() +{ + if (!m_keepAliveEnabled) + return false; + const std::uint32_t now = tickCount(); + const std::uint32_t elapsed = now - s_lastKeepAlive; + if (m_keepAliveInterval * 1000.0f < static_cast(elapsed)) // 0x8AA3C8, strict + { + s_lastKeepAlive = now; + sendKeepAlive(); + } + return true; +} + +void VoipClient::deviceUnplugged(GVDevice device) +{ + if (device == m_captureDevice) + m_captureDevice = 0; + if (device == m_playbackDevice) + m_playbackDevice = 0; + m_deviceLost = true; + m_testing = false; + m_active = false; +} + +void VoipClient::unpluggedCallback(GVDevice device) +{ + VoipClient* client = s_instance; + if (client) + client->deviceUnplugged(device); +} + +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/Game/VoipClient/VoipClient.h b/Code/BF2/Game/VoipClient/VoipClient.h new file mode 100644 index 000000000..73b30f5d9 --- /dev/null +++ b/Code/BF2/Game/VoipClient/VoipClient.h @@ -0,0 +1,188 @@ +// The generic voice-over-IP client BF2VoipClient derives from: GameSpy Voice 2 capture and playback +// devices, the Speex codec selection, and the UDP session with the voice server +// (Code/BF2/VoipServer). BF2.exe 0x736C30..0x737B00, vtable 0x920C48 (38 slots), ctor 0x7379C0. +// [INFERRED] class and member names: the image carries no symbols for this library. +#ifndef BF2_GAME_VOIPCLIENT_VOIPCLIENT_H +#define BF2_GAME_VOIPCLIENT_VOIPCLIENT_H + +#include +#include +#include + +// GameSpy Voice 2 (External/GameSpy/Voice2/gv.h). Only the implementation files include gv.h, so +// this header pulls in neither the SDK nor Winsock: the HUD and engine files that see the client +// keep their own include order. +struct GVIDevice; + +namespace dice { +namespace hfe { + +typedef struct ::GVIDevice* VoipDevice; // gv.h GVDevice +typedef void (*VoipUnpluggedCallback)(VoipDevice device); // gv.h gvUnpluggedCallback + +// [PLATFORM] The socket handle: Winsock's SOCKET (UINT_PTR; 4 bytes on x86, as retail), a +// descriptor elsewhere. The two socket addresses are kept as their 16 sockaddr_in bytes. +#if defined(_WIN32) +typedef std::uintptr_t VoipSocket; +#else +typedef int VoipSocket; +#endif +struct VoipSockAddr { std::uint8_t bytes[16]; }; + +// The second-order band-pass filter BF2VoipClient applies to captured audio (BF2.exe 0x737B60..0x737D4E, +// 0x70 bytes). The coefficients are the audio-EQ-cookbook band-pass with constant 0 dB peak gain, +// bandwidth in octaves. +class VoipBandPassFilter +{ +public: + VoipBandPassFilter(); // 0x737B60 + // Clears the four history values (0x737BE0). + void reset(); + // One sample through the filter, times the gain, clamped to [-limit, limit]. A disabled filter + // returns the input untouched, without gain or clamp (0x737C10). + double process(double sample, double limit); + // Stores the parameters and derives the coefficients; also clears the history (0x737C90). + void setup(double gain, double frequency, double sampleRate, double bandwidth, bool enabled); + + double m_b0; // +0x00 + double m_b1; // +0x08 always 0 for this band-pass + double m_b2; // +0x10 + double m_a1; // +0x18 a1/a0, subtracted + double m_a2; // +0x20 a2/a0, subtracted + double m_x1; // +0x28 + double m_x2; // +0x30 + double m_y1; // +0x38 + double m_y2; // +0x40 + bool m_enabled; // +0x48 + double m_gain; // +0x50 + double m_frequency; // +0x58 + double m_sampleRate; // +0x60 + double m_bandwidth; // +0x68 +}; +#if defined(_M_IX86) +static_assert(sizeof(VoipBandPassFilter) == 0x70, "VoipBandPassFilter must keep the retail x86 size"); +#endif + +class VoipClient +{ +public: + VoipClient(); // 0x7379C0 + virtual ~VoipClient(); // +0x00 0x737B00 + + virtual void setServerAddress(std::uint32_t address, std::uint16_t port); // +0x04 0x736CD0 + virtual bool openSocket(); // +0x08 0x736CF0 + virtual bool initVoice(); // +0x0C 0x7376F0 + virtual bool setCodec(int quality); // +0x10 0x736D80 + virtual bool setCaptureThreshold(float threshold); // +0x14 0x736EA0 + virtual bool getCaptureThreshold(double* threshold); // +0x18 0x736EF0 + virtual bool setPlaybackVolume(float volume); // +0x1C 0x736E00 + virtual bool setCaptureVolume(float volume); // +0x20 0x736E50 + virtual double getCaptureVolume(); // +0x24 0x451060 + virtual double getPlaybackVolume(); // +0x28 0x451070 + virtual bool startSession(std::uint32_t address, std::uint16_t port, std::uint16_t localPort, + int quality, bool useMixer); // +0x2C 0x7374F0 + virtual bool startTest(int quality, bool useMixer); // +0x30 0x737590 + virtual bool isTesting(); // +0x34 0x46CA80 (+0x09) + virtual bool isActive(); // +0x38 0x46CA70 (+0x08) + virtual bool getCaptureLevel(double* level); // +0x3C 0x737040 + virtual void setHeaderMode(std::uint8_t mode, std::uint8_t channel); // +0x40 0x451080 + virtual bool useChannelListHeader(); // +0x44 0x737610 + virtual void setSendEnabled(bool enabled); // +0x48 0x4510A0 + virtual void setReceiveEnabled(bool enabled); // +0x4C 0x4510B0 + virtual bool setEnabled(bool enabled); // +0x50 0x451040 + virtual void setKeepAliveEnabled(bool enabled); // +0x54 0x4510C0 + virtual bool sendKeepAlive(); // +0x58 0x7373C0 + virtual void setKeepAliveInterval(float seconds); // +0x5C 0x5C94A0 + virtual void setPlayerId(std::uint16_t id); // +0x60 0x4510D0 + virtual bool update(); // +0x64 0x737640 + virtual bool shutdown(); // +0x68 0x737440 + virtual int sendCaptured(std::uint8_t* packet, int* length); // +0x6C 0x736FA0 + virtual bool handleIncoming(std::uint8_t* packet, int length, std::uint16_t* sender); // +0x70 0x736F60 + virtual bool think(int* receiveError, int* sendError); // +0x74 0x7370C0 + virtual int sendPacket(std::uint8_t* packet, int* length); // +0x78 0x737930 + virtual void onCaptureLevel(double level); // +0x7C 0x736FC0 + virtual void onVoiceEnded(); // +0x80 0x737020 + virtual void onIncomingHandled(std::uint16_t* sender); // +0x84 0x5AB2A0 (empty) + virtual float getVoiceTimeout(); // +0x88 0x4510E0 + virtual void setVoiceTimeout(float milliseconds); // +0x8C 0x65CF00 + virtual void setUnpluggedCallback(VoipDevice device, VoipUnpluggedCallback callback); // +0x90 0x736F10 + virtual void closeSocket(); // +0x94 0x737420 + + // Loops capture straight back to playback for the menu's voice test; turning it on first starts the + // local test (quality 3, mixer). Header-inline: SwiffPlayer.dll links its own copy (0x100BC8B0) + // and calls it on the client it got from getSingleton. + bool setLocalLoopback(bool on) + { + if (on) + startTest(3, true); // +0x30 + if (!m_active && !m_testing) + return false; + m_localLoopback = on; + if (on) + m_loopbackSilent = false; + return true; + } + + // Nonvirtual helpers. + bool initMixer(); // 0x736C30 + void localLoopbackThink(); // 0x737240 + bool writeHeader(std::uint8_t* packet, int* length); // 0x737330, mode 1 + bool writeChannelHeader(std::uint8_t* packet, int* length); // 0x737370, mode 2 + bool writeChannelListHeader(std::uint8_t* packet, int* length); // 0x737880, mode 3 + bool keepAliveTick(); // 0x737060 + void deviceUnplugged(VoipDevice device); // 0x736F30 + static void unpluggedCallback(VoipDevice device); // 0x7375E0, through ds:0xA10880 + + // [PLATFORM] GetTickCount: Win32 on Windows, a monotonic millisecond count elsewhere. + static std::uint32_t tickCount(); + + // +0x04: no member. MSVC pads the vfptr to the class's 8-byte alignment (the doubles below), which + // is why retail never writes +0x04. + bool m_active; // +0x08 session started (startSession) + bool m_testing; // +0x09 local test started (startTest) + std::uint16_t m_playerId; // +0x0A voice session id, sent in every header + std::uint32_t m_serverAddress; // +0x0C network order + std::uint16_t m_serverPort; // +0x10 + std::uint16_t m_localPort; // +0x12 + bool m_useMixer; // +0x14 initial 1 + int m_quality; // +0x18 codec quality 1..5 + int m_encodedFrameSize; // +0x1C initial 0x14; gvGetCodecInfo + VoipSocket m_socket; // +0x20 initial -1 + VoipSockAddr m_serverSockAddr; // +0x24 sockaddr_in + VoipSockAddr m_localSockAddr; // +0x34 sockaddr_in + VoipDevice m_captureDevice; // +0x44 + VoipDevice m_playbackDevice; // +0x48 + bool m_deviceLost; // +0x4C set by the unplugged callback + std::uint8_t m_headerMode; // +0x4D 1 plain, 2 channel, 3 channel list; initial 1 + std::uint8_t m_channel; // +0x4E + double m_initialThreshold; // +0x50 0.1, given to a new capture device + bool m_sendEnabled; // +0x58 initial 1 + bool m_receiveEnabled; // +0x59 + bool m_keepAliveEnabled; // +0x5A initial 1 + float m_keepAliveInterval; // +0x5C seconds, initial 3.0 + bool m_unused60; // +0x60 written 0 by the ctor only + bool m_capturing; // +0x61 voice above the threshold since m_captureStart + double m_captureLevel; // +0x68 last capture volume + double m_captureStart; // +0x70 0 while silent + double m_lastCapture; // +0x78 + float m_voiceTimeout; // +0x80 milliseconds of silence that end a burst, 500 + std::uint32_t m_channelListAllocator;// +0x84 [CHOSEN] the VC7.1 vector's allocator word + std::vector m_channelList; // +0x88 squads a commander talks to (mode 3) + bool m_localLoopback; // +0x94 capture straight back to playback + bool m_loopbackSilent; // +0x95 loopback captures without playing back + int m_savedMonitorMute; // +0x98 initial -1; the mic's speaker-monitor mute before initMixer + int m_savedBoost; // +0x9C initial -1; the mic boost before initMixer + + static VoipClient* s_instance; // ds:0xA10880 + static std::uint32_t s_lastKeepAlive; // ds:0xA10884 +}; +#if defined(_M_IX86) +static_assert(sizeof(VoipClient) == 0xA0, "VoipClient must keep the retail x86 layout"); +static_assert(offsetof(VoipClient, m_captureDevice) == 0x44, "VoipClient +0x44"); +static_assert(offsetof(VoipClient, m_channelList) == 0x88, "VoipClient +0x88"); +#endif + +} // namespace hfe +} // namespace dice + +#endif diff --git a/Code/BF2/Game/VoipClient/VoipFakeDevice.cpp b/Code/BF2/Game/VoipClient/VoipFakeDevice.cpp new file mode 100644 index 000000000..53721ae6c --- /dev/null +++ b/Code/BF2/Game/VoipClient/VoipFakeDevice.cpp @@ -0,0 +1,169 @@ +// [CHOSEN, not recovered] See VoipFakeDevice.h. +#include "../../External/GameSpy/Voice2/gv.h" +extern "C" { +#include "../../External/GameSpy/Voice2/gvDevice.h" +#include "../../External/GameSpy/Voice2/gvCodec.h" +} +#include "VoipFakeDevice.h" + +#include +#include +#include +#include + +namespace dice { +namespace hfe { +namespace VoipFakeDevice { + +namespace { + +std::uint32_t defaultClock() { return VoipClient::tickCount(); } + +Clock s_clock = &defaultClock; +int s_amplitude = 12000; +std::uint32_t s_burstMs = 1500; +std::uint32_t s_gapMs = 1500; +int s_capturedFrames = 0; +int s_playedFrames = 0; + +// Per device: the clock origin and how many capture/playback frames have been served. +struct Pacing +{ + GVIDevice* device; + std::uint32_t start; + long long capture; + long long playback; +}; +std::vector s_devices; + +Pacing* pacingFor(GVIDevice* device) +{ + for (std::size_t i = 0; i < s_devices.size(); ++i) + if (s_devices[i].device == device) + return &s_devices[i]; + return 0; +} + +long long framesDue(const Pacing& pacing) +{ + const std::uint32_t elapsed = s_clock() - pacing.start; + const long long samples = static_cast(elapsed) * gvGetSampleRate() / 1000; + return GVISamplesPerFrame > 0 ? samples / GVISamplesPerFrame : 0; +} + +void fillFrame(GVSample* frame, long long frameIndex) +{ + const double rate = static_cast(gvGetSampleRate()); + const std::uint32_t period = s_burstMs + s_gapMs; + for (int i = 0; i < GVISamplesPerFrame; ++i) + { + const long long sample = frameIndex * GVISamplesPerFrame + i; + const std::uint32_t ms = static_cast(sample * 1000 / static_cast(rate)); + const bool on = period == 0 || (ms % period) < s_burstMs; + frame[i] = on ? static_cast(s_amplitude * std::sin(6.283185307179586 * 300.0 * sample / rate)) + : static_cast(0); + } +} + +// Drains the playback frames that are due, so sources start and stop talking on time. +void drainPlayback(GVIDevice* device, Pacing& pacing) +{ + if (!(device->m_types & GV_PLAYBACK)) + return; + const long long due = framesDue(pacing); + std::vector frame(static_cast(GVISamplesPerFrame)); + while (pacing.playback < due) + { + gvGetCustomPlaybackAudio(device, frame.data(), GVISamplesPerFrame); + ++pacing.playback; + ++s_playedFrames; + } +} + +int availableCaptureBytes(GVDevice device) +{ + Pacing* pacing = pacingFor(device); + if (!pacing) + return 0; + const long long pending = framesDue(*pacing) - pacing->capture; + return pending > 0 ? static_cast(pending * GVIBytesPerFrame) : 0; +} + +// One frame per call while frames are due; silent frames below the threshold are consumed and end +// the caller's loop, exactly as a hardware device reports "no packet". +GVBool capturePacket(GVDevice device, GVByte* packet, int* len, GVFrameStamp* frameStamp, GVScalar* volume) +{ + Pacing* pacing = pacingFor(device); + const int room = *len; + *len = 0; + if (volume) + *volume = 0; + if (!pacing) + return GVFalse; + drainPlayback(device, *pacing); + if (pacing->capture >= framesDue(*pacing) || room < GVIEncodedFrameSize) + return GVFalse; + std::vector frame(static_cast(GVISamplesPerFrame)); + fillFrame(frame.data(), pacing->capture); + ++pacing->capture; + ++s_capturedFrames; + int packetLen = room; + const GVBool over = gvSetCustomCaptureAudio(device, frame.data(), GVISamplesPerFrame, packet, + &packetLen, frameStamp, volume); + *len = over ? packetLen : 0; + return over; +} + +void (*s_customFree)(GVIDevice*) = 0; + +void freeDevice(GVIDevice* device) +{ + for (std::size_t i = 0; i < s_devices.size(); ++i) + { + if (s_devices[i].device == device) + { + s_devices.erase(s_devices.begin() + static_cast(i)); + break; + } + } + if (s_customFree) + s_customFree(device); +} + +} // namespace + +void setClock(Clock clock) { s_clock = clock ? clock : &defaultClock; } + +void setSignal(int amplitude, std::uint32_t burstMs, std::uint32_t gapMs) +{ + s_amplitude = amplitude; + s_burstMs = burstMs; + s_gapMs = gapMs; +} + +bool requested() +{ + const char* value = std::getenv("BF2_VOIP_CAPTURE"); + return value && std::strcmp(value, "fake") == 0; +} + +VoipDevice create() +{ + GVDevice device = gvNewCustomDevice(GV_CAPTURE_AND_PLAYBACK); + if (!device) + return 0; + s_customFree = device->m_methods.m_freeDevice; + device->m_methods.m_freeDevice = &freeDevice; + device->m_methods.m_capturePacket = &capturePacket; + device->m_methods.m_getAvailableCaptureBytes = &availableCaptureBytes; + Pacing pacing = { device, s_clock(), 0, 0 }; + s_devices.push_back(pacing); + return device; +} + +int capturedFrames() { return s_capturedFrames; } +int playedFrames() { return s_playedFrames; } + +} // namespace VoipFakeDevice +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/Game/VoipClient/VoipFakeDevice.h b/Code/BF2/Game/VoipClient/VoipFakeDevice.h new file mode 100644 index 000000000..eca4eccf0 --- /dev/null +++ b/Code/BF2/Game/VoipClient/VoipFakeDevice.h @@ -0,0 +1,46 @@ +// [CHOSEN, not recovered] A synthetic GameSpy Voice device for tests and gates (owner, 2026-11-13: the +// gates run without a microphone and without the macOS microphone permission prompt). It is the SDK's +// custom device with the two capture methods the BF2 client uses (gvCapturePacket and +// gvGetAvailableCaptureBytes), which the custom device leaves unsupported, served from a generated +// signal through the SDK's own custom capture path (threshold, hold, capture filter, encoder). +// Playback is drained at the same frame rate into the SDK source list, so talking state updates as +// with hardware. Nothing opens an audio device. +// +// VoipClient::initVoice uses it instead of gvListDevices/gvNewDevice when BF2_VOIP_CAPTURE=fake is +// set; the voice unit test installs it directly. +#ifndef BF2_GAME_VOIPCLIENT_VOIPFAKEDEVICE_H +#define BF2_GAME_VOIPCLIENT_VOIPFAKEDEVICE_H + +#include + +#include "VoipClient.h" + +namespace dice { +namespace hfe { + +namespace VoipFakeDevice { + +// Millisecond clock the device paces itself by; VoipClient::tickCount unless a test installs one. +typedef std::uint32_t (*Clock)(); +void setClock(Clock clock); + +// The generated capture signal: a 300 Hz tone at the given 16-bit amplitude for burstMs, then +// silence for gapMs, repeating. Defaults: amplitude 12000, 1500 ms on, 1500 ms off. +void setSignal(int amplitude, std::uint32_t burstMs, std::uint32_t gapMs); + +// True when BF2_VOIP_CAPTURE=fake. +bool requested(); + +// A started capture+playback device (GV_CAPTURE_AND_PLAYBACK); null if the SDK refuses. +VoipDevice create(); + +// Counters for tests. +int capturedFrames(); // frames handed to the capture path +int playedFrames(); // frames drained from playback + +} // namespace VoipFakeDevice + +} // namespace hfe +} // namespace dice + +#endif diff --git a/Code/BF2/Game/VoipClient/VoipMixer.cpp b/Code/BF2/Game/VoipClient/VoipMixer.cpp new file mode 100644 index 000000000..21c861158 --- /dev/null +++ b/Code/BF2/Game/VoipClient/VoipMixer.cpp @@ -0,0 +1,606 @@ +// dice::hfe::VoipMixer, BF2.exe 0x7356B0..0x736BA0 (see the header). +// +// Retail allocates with the engine's operator new/new[] (0x402CD0/0x402CF0) and frees with +// 0x402D10/0x402D20; plain new/delete stand in for them. The "Mic" name tests construct a +// std::string from the name and call find("Mic", 0, 3) (MSVCP71 imports 0x87F46C, 0x87F368). +#include "VoipMixer.h" + +#include +#include + +#include +#include +#include + +namespace dice { +namespace hfe { + +namespace { + +VoipMixer* s_instance = 0; // ds:A10878 +HMIXER s_mixer = 0; // ds:A1087C + +const float kVolumeScale = 65535.0f; // ds:8FCBF8 (0x477FFF00) +const float kVolumeInverseScale = 1.0f / 65535.0f; // ds:920C3C (0x37800080) + +inline HMIXEROBJ mixerObject() { return reinterpret_cast(s_mixer); } + +// "Mic" anywhere in a mixer name (0x735753, 0x736061). [CHOSEN, not recovered] the length is bounded +// by the array; retail reads to the terminator. +bool nameHasMic(const char* name, std::size_t capacity) +{ + std::size_t length = 0; + while (length < capacity && name[length] != '\0') + ++length; + return std::string(name, length).find("Mic", 0, 3) != std::string::npos; +} + +// 0x735C76..0x735C9E: fld, fmul 65535.0f, fistp with the rounding control forced to truncate. +// An out-of-range or NaN product stores the integer indefinite. The float product is exact in +// double, so the x87 and SSE arms agree. +DWORD volumeToControlValue(float volume) +{ + const double scaled = static_cast(volume) * static_cast(kVolumeScale); + if (!(scaled > -2147483649.0 && scaled < 2147483648.0)) + return 0x80000000u; + return static_cast(static_cast(scaled)); +} + +// 0x735E68..0x735E83: the unsigned value (fild, plus 2^32 when the sign bit is set) times +// 1/65535.0f, stored as float. Precision control is 53 bits in the MSVC runtime, so double then +// float rounds the same way. +float controlValueToVolume(DWORD value) +{ + return static_cast(static_cast(value) * static_cast(kVolumeInverseScale)); +} + +// [PLATFORM] No mixer: the answers of a machine without a mixer device in retail. Used where no +// backend exists, by test builds, and with the synthetic voice device (BF2_VOIP_CAPTURE=fake), so a +// gate run never changes the machine's microphone volume, mute or boost. +MMRESULT BF2_VOIPMIXER_WINAPI noMixerOpen(HMIXER* phmx, UINT, DWORD_PTR, DWORD_PTR, DWORD) +{ + if (phmx) + *phmx = 0; + return MMSYSERR_BADDEVICEID; +} +MMRESULT BF2_VOIPMIXER_WINAPI noMixerClose(HMIXER) { return MMSYSERR_INVALHANDLE; } +MMRESULT BF2_VOIPMIXER_WINAPI noMixerGetDevCaps(UINT_PTR, MIXERCAPSA*, UINT) { return MMSYSERR_BADDEVICEID; } +MMRESULT BF2_VOIPMIXER_WINAPI noMixerGetLineInfo(HMIXEROBJ, MIXERLINEA*, DWORD) { return MMSYSERR_INVALHANDLE; } +MMRESULT BF2_VOIPMIXER_WINAPI noMixerGetLineControls(HMIXEROBJ, MIXERLINECONTROLSA*, DWORD) { return MMSYSERR_INVALHANDLE; } +MMRESULT BF2_VOIPMIXER_WINAPI noMixerGetControlDetails(HMIXEROBJ, MIXERCONTROLDETAILS*, DWORD) { return MMSYSERR_INVALHANDLE; } +MMRESULT BF2_VOIPMIXER_WINAPI noMixerSetControlDetails(HMIXEROBJ, MIXERCONTROLDETAILS*, DWORD) { return MMSYSERR_INVALHANDLE; } + +const VoipMixerApi kNoMixerApi = { + noMixerOpen, noMixerClose, noMixerGetDevCaps, noMixerGetLineInfo, + noMixerGetLineControls, noMixerGetControlDetails, noMixerSetControlDetails, +}; +#if defined(BF2_VOIPMIXER_NO_PLATFORM_BACKEND) || (!defined(_WIN32) && !defined(__APPLE__)) +const VoipMixerApi* platformApi() { return &kNoMixerApi; } +#elif defined(_WIN32) +// [PLATFORM] Windows: winmm itself, so behaviour is retail's. +const VoipMixerApi kWinmmApi = { + ::mixerOpen, ::mixerClose, ::mixerGetDevCapsA, ::mixerGetLineInfoA, + ::mixerGetLineControlsA, ::mixerGetControlDetailsA, ::mixerSetControlDetails, +}; +const VoipMixerApi* platformApi() { return &kWinmmApi; } +#else +const VoipMixerApi* platformApi() { return voipMixerCoreAudioApi(); } +#endif + +const VoipMixerApi* s_api = 0; // [PLATFORM] null: platformApi() + +} // namespace + +void VoipMixer::setApiForTesting(const VoipMixerApi* api) +{ + s_api = api; +} + +const VoipMixerApi* VoipMixer::api() +{ + if (s_api) + return s_api; + // [CHOSEN, not recovered] The synthetic voice device (VoipFakeDevice) leaves the system mixer alone. + const char* capture = std::getenv("BF2_VOIP_CAPTURE"); + if (capture && std::strcmp(capture, "fake") == 0) + return &kNoMixerApi; + return platformApi(); +} + +// --- VoipMixerLineList ------------------------------------------------------------------------- + +VoipMixerLineList::VoipMixerLineList() : m_allocator(0), m_first(0), m_last(0), m_end(0) {} + +VoipMixerLineList::~VoipMixerLineList() +{ + release(); +} + +void VoipMixerLineList::release() +{ + ::operator delete(m_first); + m_first = m_last = m_end = 0; +} + +// push_back (0x736760) and its _Insert_n growth (0x736420): the capacity grows by half, or to the +// size needed if that is more. +void VoipMixerLineList::push_back(const MIXERLINEA& line) +{ + if (m_last == m_end) { + const std::size_t count = size(); + const std::size_t capacity = m_first ? static_cast(m_end - m_first) : 0; + std::size_t grown = capacity + capacity / 2; + if (grown < count + 1) + grown = count + 1; + MIXERLINEA* storage = static_cast(::operator new(grown * sizeof(MIXERLINEA))); + if (count) + std::memcpy(storage, m_first, count * sizeof(MIXERLINEA)); + ::operator delete(m_first); + m_first = storage; + m_last = storage + count; + m_end = storage + grown; + } + std::memcpy(m_last, &line, sizeof(MIXERLINEA)); + ++m_last; +} + +// --- VoipMixer --------------------------------------------------------------------------------- + +// BF2.exe 0x7367F0. Retail leaves the boost control and line uninitialised. +VoipMixer::VoipMixer() + : m_initialized(false), m_speakersDestination(0), m_waveInDestination(0), + m_speakersMicrophone(0), m_waveInMicrophone(0) +{ + std::memset(&m_boost, 0, sizeof(m_boost)); // [CHOSEN, not recovered] zeroed for determinism + m_boost.controlType = 0; + m_boost.queried = false; + m_boost.found = false; +} + +// BF2.exe 0x736840: the four lines, then the two lists (the body releases them, and the member +// destructors find them empty). +VoipMixer::~VoipMixer() +{ + delete m_speakersDestination; + m_speakersDestination = 0; + delete m_waveInDestination; + m_waveInDestination = 0; + delete m_speakersMicrophone; + m_speakersMicrophone = 0; + delete m_waveInMicrophone; + m_waveInMicrophone = 0; + m_waveInDestinations.release(); + m_speakersDestinations.release(); +} + +// BF2.exe 0x736930. +VoipMixer* VoipMixer::getInstance() +{ + if (!s_instance) + s_instance = new (std::nothrow) VoipMixer(); + return s_instance; +} + +// BF2.exe 0x7356B0 (from the client base's shutdown, 0x7374E3). +void VoipMixer::destroy() +{ + if (!s_instance) + return; + if (s_mixer) { + api()->close(s_mixer); + s_mixer = 0; + } + delete s_instance; // slot 0, the scalar deleting destructor 0x736BA0 + s_instance = 0; +} + +// BF2.exe 0x736BD0 (VoIP client slot +0xC4, thunk 0x451A90). +bool VoipMixer::open() +{ + const HMIXER previous = s_mixer; + MIXERCAPSA caps; + if (api()->getDevCaps(0, &caps, sizeof(caps)) != MMSYSERR_NOERROR) + return false; + // CALLBACK_WINDOW with no window: no notifications. + if (api()->open(&s_mixer, 0, 0, 0, CALLBACK_WINDOW) != MMSYSERR_NOERROR) + return false; + if (previous) + api()->close(previous); + return findLines(); +} + +// BF2.exe 0x736960. Each pass appends to the lists; only their first entries are used. +bool VoipMixer::findLines() +{ + MIXERCAPSA caps; + if (api()->getDevCaps(reinterpret_cast(s_mixer), &caps, sizeof(caps)) != MMSYSERR_NOERROR) + return false; + + MIXERLINEA line; + for (DWORD destination = 0; destination < caps.cDestinations; ++destination) { + line.cbStruct = sizeof(MIXERLINEA); + line.dwDestination = destination; + if (api()->getLineInfo(mixerObject(), &line, MIXER_GETLINEINFOF_DESTINATION) != MMSYSERR_NOERROR) + continue; + if (line.dwComponentType == MIXERLINE_COMPONENTTYPE_DST_WAVEIN) + m_waveInDestinations.push_back(line); + else if (line.dwComponentType == MIXERLINE_COMPONENTTYPE_DST_SPEAKERS) + m_speakersDestinations.push_back(line); + } + + if (m_waveInDestinations.size() == 0 || m_speakersDestinations.size() == 0) + return false; + + MIXERLINEA destinationLine; + MIXERLINEA source; + if (m_waveInDestinations.begin() != m_waveInDestinations.end()) { + destinationLine = *m_waveInDestinations.begin(); + if (findMicrophoneSource(&destinationLine, &source)) { + if (!m_waveInDestination) + m_waveInDestination = new MIXERLINEA; + *m_waveInDestination = destinationLine; + if (!m_waveInMicrophone) + m_waveInMicrophone = new MIXERLINEA; + *m_waveInMicrophone = source; + } + } + if (m_speakersDestinations.begin() != m_speakersDestinations.end()) { + destinationLine = *m_speakersDestinations.begin(); + if (findMicrophoneSource(&destinationLine, &source)) { + if (!m_speakersDestination) + m_speakersDestination = new MIXERLINEA; + *m_speakersDestination = destinationLine; + if (!m_speakersMicrophone) + m_speakersMicrophone = new MIXERLINEA; + *m_speakersMicrophone = source; + } + } + + if (!m_waveInDestination || !m_speakersDestination) + return false; + if (!m_waveInMicrophone && !m_speakersMicrophone) + return false; + m_initialized = true; + findBoostControl(0); + return m_initialized; +} + +// BF2.exe 0x7356F0: the first source of `destination` that is a microphone by component type, or +// whose name holds "Mic". +bool VoipMixer::findMicrophoneSource(const MIXERLINEA* destination, MIXERLINEA* source) +{ + const DWORD connections = destination->cConnections; + for (DWORD index = 0; index < connections; ++index) { + MIXERLINEA line; + line.cbStruct = sizeof(MIXERLINEA); + line.dwDestination = destination->dwDestination; + line.dwSource = index; + if (api()->getLineInfo(mixerObject(), &line, MIXER_GETLINEINFOF_SOURCE) != MMSYSERR_NOERROR) + continue; + if (line.dwComponentType == MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE + || nameHasMic(line.szName, sizeof(line.szName))) { + *source = line; + return true; + } + } + return false; +} + +// BF2.exe 0x7357D0: all controls of `line`, then the first of `controlType`. +bool VoipMixer::getLineControl(const MIXERLINEA& line, DWORD controlType, MIXERCONTROLA* control) +{ + if (!s_mixer || !m_initialized) + return false; + const DWORD count = line.cControls; + MIXERCONTROLA* controls = new (std::nothrow) MIXERCONTROLA[count]; + if (!controls) + return false; + + MIXERLINECONTROLSA query; + query.cbStruct = sizeof(MIXERLINECONTROLSA); + query.dwLineID = line.dwLineID; + query.dwControlID = 0; // [CHOSEN, not recovered] retail leaves it unset (ALL ignores it) + query.cControls = count; + query.cbmxctrl = sizeof(MIXERCONTROLA); + query.pamxctrl = controls; + if (api()->getLineControls(mixerObject(), &query, MIXER_GETLINECONTROLSF_ALL) != MMSYSERR_NOERROR) { + delete[] controls; + return false; + } + + bool found = false; + for (DWORD index = 0; index < query.cControls; ++index) { + if (controls[index].dwControlType == controlType) { + *control = controls[index]; + found = true; + break; + } + } + delete[] controls; + return found; +} + +// BF2.exe 0x7358D0: read the value (as validation; it is discarded), then write the boolean. +// The single detail slot is retail's (its callers pass one channel). +bool VoipMixer::setControlBool(const MIXERCONTROLA& control, DWORD channels, bool value) +{ + if (!s_mixer || !m_initialized) + return false; + DWORD detail = channels; + MIXERCONTROLDETAILS details; + details.cbStruct = sizeof(MIXERCONTROLDETAILS); + details.dwControlID = control.dwControlID; + details.cChannels = channels; + details.cMultipleItems = control.cMultipleItems; + details.cbDetails = sizeof(DWORD); + details.paDetails = &detail; + if (api()->getControlDetails(mixerObject(), &details, MIXER_GETCONTROLDETAILSF_VALUE) != MMSYSERR_NOERROR) + return false; + detail = value ? 1u : 0u; + return api()->setControlDetails(mixerObject(), &details, MIXER_SETCONTROLDETAILSF_VALUE) == MMSYSERR_NOERROR; +} + +// BF2.exe 0x735960: as setControlBool, with an unsigned value. +bool VoipMixer::setControlUnsigned(const MIXERCONTROLA& control, DWORD channels, DWORD value) +{ + if (!s_mixer || !m_initialized) + return false; + DWORD detail = channels; + MIXERCONTROLDETAILS details; + details.cbStruct = sizeof(MIXERCONTROLDETAILS); + details.dwControlID = control.dwControlID; + details.cChannels = channels; + details.cMultipleItems = control.cMultipleItems; + details.cbDetails = sizeof(DWORD); + details.paDetails = &detail; + if (api()->getControlDetails(mixerObject(), &details, MIXER_GETCONTROLDETAILSF_VALUE) != MMSYSERR_NOERROR) + return false; + detail = value; + return api()->setControlDetails(mixerObject(), &details, MIXER_SETCONTROLDETAILSF_VALUE) == MMSYSERR_NOERROR; +} + +// BF2.exe 0x735A40 (VoIP client slot +0xC8, thunk 0x451AA0 with a null `out`). The search order: +// LOUDNESS, then ONOFF, on the speakers' microphone source; then the same on the wave-in's. +bool VoipMixer::findBoostControl(BoostControl* out) +{ + if (!s_mixer || !m_initialized) + return false; + if (!m_waveInMicrophone && !m_speakersMicrophone) + return false; + if (m_boost.queried) + return m_boost.found; + m_boost.queried = true; + + if (!m_waveInMicrophone || !m_speakersMicrophone) { + m_boost.found = false; + if (out) + *out = m_boost; + return false; + } + + const MIXERLINEA* line = 0; + DWORD type = 0; + if (getLineControl(*m_speakersMicrophone, MIXERCONTROL_CONTROLTYPE_LOUDNESS, &m_boost.control)) { + line = m_speakersMicrophone; + type = MIXERCONTROL_CONTROLTYPE_LOUDNESS; + } else if (getLineControl(*m_speakersMicrophone, MIXERCONTROL_CONTROLTYPE_ONOFF, &m_boost.control)) { + line = m_speakersMicrophone; + type = MIXERCONTROL_CONTROLTYPE_ONOFF; + } else if (getLineControl(*m_waveInMicrophone, MIXERCONTROL_CONTROLTYPE_LOUDNESS, &m_boost.control)) { + line = m_waveInMicrophone; + type = MIXERCONTROL_CONTROLTYPE_LOUDNESS; + } else if (getLineControl(*m_waveInMicrophone, MIXERCONTROL_CONTROLTYPE_ONOFF, &m_boost.control)) { + line = m_waveInMicrophone; + type = MIXERCONTROL_CONTROLTYPE_ONOFF; + } + if (line) { + m_boost.controlType = type; + m_boost.line = *line; + m_boost.found = true; + } + if (out) + *out = m_boost; + return m_boost.found; +} + +// BF2.exe 0x735BB0 (VoIP client slot +0xCC, thunk 0x451AB0; shutdown 0x7374DE restores the saved +// state). The control is fetched again into the cached slot before the write. +bool VoipMixer::setBoost(bool enabled) +{ + if (!s_mixer || !m_initialized) + return false; + if (!findBoostControl(0)) + return false; + if (!getLineControl(m_boost.line, m_boost.controlType, &m_boost.control)) + return false; + return setControlBool(m_boost.control, 1, enabled); +} + +// BF2.exe 0x735C30: `volume` times 65535, truncated; no clamp, the control's bounds unused. +bool VoipMixer::setLineVolume(const MIXERLINEA* line, float volume) +{ + if (!s_mixer || !m_initialized) + return false; + MIXERCONTROLA control; + if (!getLineControl(*line, MIXERCONTROL_CONTROLTYPE_VOLUME, &control)) + return false; + return setControlUnsigned(control, 1, volumeToControlValue(volume)); +} + +// BF2.exe 0x735CD0 (VoIP client slot +0xD0, thunk 0x451AD0; the setup 0x736C64 passes 1.0). +bool VoipMixer::setCaptureVolume(float volume) +{ + if (!s_mixer || !m_initialized || !m_waveInMicrophone) + return false; + return setLineVolume(m_waveInMicrophone, volume); +} + +// BF2.exe 0x735D00 (VoIP client slot +0xD4, thunk 0x451AF0; the setup 0x736CAB saves it). +bool VoipMixer::getBoost(bool* enabled) +{ + if (!s_mixer || !m_initialized) + return false; + if (!findBoostControl(0)) + return false; + MIXERCONTROLA control; + if (!getLineControl(m_boost.line, m_boost.controlType, &control)) + return false; + DWORD value = 0; + MIXERCONTROLDETAILS details; + details.cbStruct = sizeof(MIXERCONTROLDETAILS); + details.dwControlID = control.dwControlID; + details.cChannels = 1; + details.cMultipleItems = control.cMultipleItems; + details.cbDetails = sizeof(DWORD); + details.paDetails = &value; + if (api()->getControlDetails(mixerObject(), &details, MIXER_GETCONTROLDETAILSF_VALUE) != MMSYSERR_NOERROR) + return false; + *enabled = value != 0; + return true; +} + +// BF2.exe 0x735DD0 (VoIP client slot +0xD8, thunk 0x451B10). The control value over 65535; the +// control's bounds are not read. The thunk takes its float by value and passes that slot's +// address, so the client slot only reports success; the volume read is discarded. +bool VoipMixer::getCaptureVolume(float* volume) +{ + if (!s_mixer || !m_initialized || !m_waveInMicrophone) + return false; + MIXERCONTROLA control; + if (!getLineControl(*m_waveInMicrophone, MIXERCONTROL_CONTROLTYPE_VOLUME, &control)) + return false; + DWORD value = 0; + MIXERCONTROLDETAILS details; + details.cbStruct = sizeof(MIXERCONTROLDETAILS); + details.dwControlID = control.dwControlID; + details.cChannels = 1; + details.cMultipleItems = control.cMultipleItems; + details.cbDetails = sizeof(DWORD); + details.paDetails = &value; + if (api()->getControlDetails(mixerObject(), &details, MIXER_GETCONTROLDETAILSF_VALUE) != MMSYSERR_NOERROR) + return false; + *volume = controlValueToVolume(value); + return true; +} + +// BF2.exe 0x735EA0 (VoIP client slot +0xDC, thunk 0x451B30; the setup 0x736C53). Finds the MUX of +// the wave-in destination, picks the item whose line is a microphone (by component type, then by +// "Mic" in the item text) and sets that item alone. The set's result is not checked. +bool VoipMixer::selectMicrophoneRecordingSource() +{ + if (!s_mixer || !m_initialized || !m_waveInDestination) + return false; + MIXERCONTROLA control; + if (!getLineControl(*m_waveInDestination, MIXERCONTROL_CONTROLTYPE_MUX, &control)) + return false; + + const DWORD channels = (control.fdwControl & MIXERCONTROL_CONTROLF_UNIFORM) ? 1u : m_waveInDestination->cChannels; + const DWORD items = control.cMultipleItems; + // [CHOSEN, not recovered] Sized items * channels: retail allocates `items` slots, which WINMM + // overruns for a non-uniform MUX on a multi-channel line. Retail does not check this allocation. + const DWORD slots = items * (channels ? channels : 1u); + MIXERCONTROLDETAILS_BOOLEAN* selected = new (std::nothrow) MIXERCONTROLDETAILS_BOOLEAN[slots ? slots : 1u]; + if (!selected) + return false; + + MIXERCONTROLDETAILS values; + values.cbStruct = sizeof(MIXERCONTROLDETAILS); + values.dwControlID = control.dwControlID; + values.cChannels = channels; + values.cMultipleItems = items; + values.cbDetails = sizeof(MIXERCONTROLDETAILS_BOOLEAN); + values.paDetails = selected; + if (api()->getControlDetails(mixerObject(), &values, MIXER_GETCONTROLDETAILSF_VALUE) != MMSYSERR_NOERROR) { + delete[] selected; + return false; + } + + MIXERCONTROLDETAILS_LISTTEXTA* texts = new (std::nothrow) MIXERCONTROLDETAILS_LISTTEXTA[items ? items : 1u]; + if (!texts) { + delete[] selected; + return false; + } + MIXERCONTROLDETAILS listText; + listText.cbStruct = sizeof(MIXERCONTROLDETAILS); + listText.dwControlID = control.dwControlID; + listText.cChannels = channels; + listText.cMultipleItems = items; + listText.cbDetails = sizeof(MIXERCONTROLDETAILS_LISTTEXTA); + listText.paDetails = texts; + if (api()->getControlDetails(mixerObject(), &listText, MIXER_GETCONTROLDETAILSF_LISTTEXT) != MMSYSERR_NOERROR) { + delete[] texts; + delete[] selected; + return false; + } + + // dwParam1 of each item is the source's line id. + DWORD microphone = 0xFFFFFFFFu; + for (DWORD index = 0; index < items; ++index) { + MIXERLINEA line; + line.cbStruct = sizeof(MIXERLINEA); + line.dwLineID = texts[index].dwParam1; + if (api()->getLineInfo(mixerObject(), &line, MIXER_OBJECTF_HMIXER | MIXER_GETLINEINFOF_LINEID) == MMSYSERR_NOERROR + && line.dwComponentType == MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE) { + microphone = index; + break; + } + } + if (microphone == 0xFFFFFFFFu) { + for (DWORD index = 0; index < items; ++index) { + if (nameHasMic(texts[index].szName, sizeof(texts[index].szName))) { + microphone = index; + break; + } + } + } + if (microphone == 0xFFFFFFFFu) { + delete[] texts; + delete[] selected; + return false; + } + + for (DWORD index = 0; index < items; ++index) + selected[index].fValue = 0; + selected[microphone].fValue = 1; + api()->setControlDetails(mixerObject(), &values, MIXER_SETCONTROLDETAILSF_VALUE); + delete[] texts; + delete[] selected; + return true; +} + +// BF2.exe 0x736120 (the setup 0x736C78 saves it to the client's +0x98). +bool VoipMixer::getMicrophoneMonitorMute(bool* muted) +{ + if (!s_mixer || !m_initialized || !m_speakersMicrophone) + return false; + MIXERCONTROLA control; + if (!getLineControl(*m_speakersMicrophone, MIXERCONTROL_CONTROLTYPE_MUTE, &control)) + return false; + DWORD value = 0; + MIXERCONTROLDETAILS details; + details.cbStruct = sizeof(MIXERCONTROLDETAILS); + details.dwControlID = control.dwControlID; + details.cChannels = 1; + details.cMultipleItems = control.cMultipleItems; + details.cbDetails = sizeof(DWORD); + details.paDetails = &value; + if (api()->getControlDetails(mixerObject(), &details, MIXER_GETCONTROLDETAILSF_VALUE) != MMSYSERR_NOERROR) + return false; + *muted = value != 0; + return true; +} + +// BF2.exe 0x7361E0 (VoIP client slot +0xE0, thunk 0x451B40; the setup 0x736C95 mutes, and the +// shutdown 0x7374BB restores the saved state). +bool VoipMixer::setMicrophoneMonitorMute(bool muted) +{ + if (!s_mixer || !m_initialized || !m_speakersMicrophone) + return false; + MIXERCONTROLA control; + if (!getLineControl(*m_speakersMicrophone, MIXERCONTROL_CONTROLTYPE_MUTE, &control)) + return false; + return setControlBool(control, 1, muted); +} + +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/Game/VoipClient/VoipMixer.h b/Code/BF2/Game/VoipClient/VoipMixer.h new file mode 100644 index 000000000..27698f23f --- /dev/null +++ b/Code/BF2/Game/VoipClient/VoipMixer.h @@ -0,0 +1,356 @@ +// dice::hfe::VoipMixer, the VoIP client's microphone mixer helper. BF2.exe 0x7356B0..0x736BA0, +// table 0x920C40 (one slot: the scalar deleting destructor), 0x17C bytes. [INFERRED] class name; +// the shipped image carries no symbols for it. +// +// A singleton (getInstance, BF2.exe 0x736930; instance ds:A10878) around WINMM mixer device 0 +// (handle ds:A1087C). It finds the microphone source on the wave-in (recording) destination and on +// the speakers (playback) destination, then offers: select the microphone on the recording MUX, +// capture volume (the wave-in microphone's VOLUME), microphone boost (a LOUDNESS or ONOFF switch on +// a microphone source), and the playback-monitor mute (MUTE on the speakers' microphone source). +// +// Callers: the VoIP client vtable 0x89C1A8, slots +0xC4..+0xE0 (thunks 0x451A90..0x451B50), and +// the client base's mixer setup 0x736C30 and shutdown 0x737440 (which restores the saved mute and +// boost states and then calls destroy). +// +// [PLATFORM] Every WINMM call goes through a VoipMixerApi table: winmm itself on Windows, a +// CoreAudio shell on macOS (VoipMixerCoreAudio.cpp), a scripted fake in the tests. +#ifndef GAME_VOIPCLIENT_VOIPMIXER_H +#define GAME_VOIPCLIENT_VOIPMIXER_H + +#include +#include + +#if defined(_WIN32) +# include +# include +# define BF2_VOIPMIXER_WINAPI WINAPI +#else +# define BF2_VOIPMIXER_WINAPI +#endif + +namespace dice { +namespace hfe { + +#if !defined(_WIN32) +// [PLATFORM] The mmsystem.h vocabulary the mixer uses, for platforms without the Windows SDK. +// Byte-packed as mmsystem.h is. The pointer-free structs keep their x86 sizes (MIXERLINEA 0xA8, +// MIXERCONTROLA 0x94, MIXERCAPSA 0x30; retail writes those cbStruct values). DWORD_PTR fields are +// DWORDs for that reason; the two structs that hold pointers are pointer-sized here. The names +// live in dice::hfe, never at global scope (as Platform/macOS/HostWindowTypes.h does). +typedef std::uint32_t DWORD; +typedef std::uint16_t WORD; +typedef std::int32_t LONG; +typedef unsigned int UINT; +typedef std::uintptr_t UINT_PTR; +typedef std::uintptr_t DWORD_PTR; +typedef UINT MMRESULT; +typedef UINT MMVERSION; +typedef struct HMIXER__* HMIXER; +typedef struct HMIXEROBJ__* HMIXEROBJ; + +const MMRESULT MMSYSERR_NOERROR = 0; +const MMRESULT MMSYSERR_ERROR = 1; +const MMRESULT MMSYSERR_BADDEVICEID = 2; +const MMRESULT MMSYSERR_ALLOCATED = 4; +const MMRESULT MMSYSERR_INVALHANDLE = 5; +const MMRESULT MMSYSERR_NODRIVER = 6; +const MMRESULT MMSYSERR_NOMEM = 7; +const MMRESULT MMSYSERR_NOTSUPPORTED = 8; +const MMRESULT MMSYSERR_INVALFLAG = 10; +const MMRESULT MMSYSERR_INVALPARAM = 11; +const MMRESULT MIXERR_INVALLINE = 1024; +const MMRESULT MIXERR_INVALCONTROL = 1025; +const MMRESULT MIXERR_INVALVALUE = 1026; + +const DWORD CALLBACK_WINDOW = 0x00010000u; + +const DWORD MIXER_OBJECTF_HANDLE = 0x80000000u; +const DWORD MIXER_OBJECTF_MIXER = 0x00000000u; +const DWORD MIXER_OBJECTF_HMIXER = 0x80000000u; + +const DWORD MIXER_GETLINEINFOF_DESTINATION = 0x00000000u; +const DWORD MIXER_GETLINEINFOF_SOURCE = 0x00000001u; +const DWORD MIXER_GETLINEINFOF_LINEID = 0x00000002u; +const DWORD MIXER_GETLINEINFOF_COMPONENTTYPE = 0x00000003u; +const DWORD MIXER_GETLINEINFOF_TARGETTYPE = 0x00000004u; +const DWORD MIXER_GETLINEINFOF_QUERYMASK = 0x0000000Fu; + +const DWORD MIXER_GETLINECONTROLSF_ALL = 0x00000000u; +const DWORD MIXER_GETLINECONTROLSF_ONEBYID = 0x00000001u; +const DWORD MIXER_GETLINECONTROLSF_ONEBYTYPE = 0x00000002u; +const DWORD MIXER_GETLINECONTROLSF_QUERYMASK = 0x0000000Fu; + +const DWORD MIXER_GETCONTROLDETAILSF_VALUE = 0x00000000u; +const DWORD MIXER_GETCONTROLDETAILSF_LISTTEXT = 0x00000001u; +const DWORD MIXER_GETCONTROLDETAILSF_QUERYMASK = 0x0000000Fu; +const DWORD MIXER_SETCONTROLDETAILSF_VALUE = 0x00000000u; +const DWORD MIXER_SETCONTROLDETAILSF_QUERYMASK = 0x0000000Fu; + +const DWORD MIXERLINE_LINEF_ACTIVE = 0x00000001u; +const DWORD MIXERLINE_LINEF_SOURCE = 0x80000000u; + +const DWORD MIXERLINE_COMPONENTTYPE_DST_SPEAKERS = 0x00000004u; +const DWORD MIXERLINE_COMPONENTTYPE_DST_WAVEIN = 0x00000007u; +const DWORD MIXERLINE_COMPONENTTYPE_SRC_UNDEFINED = 0x00001000u; +const DWORD MIXERLINE_COMPONENTTYPE_SRC_LINE = 0x00001002u; +const DWORD MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE = 0x00001003u; +const DWORD MIXERLINE_COMPONENTTYPE_SRC_COMPACTDISC = 0x00001005u; +const DWORD MIXERLINE_COMPONENTTYPE_SRC_WAVEOUT = 0x00001008u; + +const DWORD MIXERLINE_TARGETTYPE_UNDEFINED = 0; +const DWORD MIXERLINE_TARGETTYPE_WAVEOUT = 1; +const DWORD MIXERLINE_TARGETTYPE_WAVEIN = 2; + +const DWORD MIXERCONTROL_CONTROLF_UNIFORM = 0x00000001u; +const DWORD MIXERCONTROL_CONTROLF_MULTIPLE = 0x00000002u; + +const DWORD MIXERCONTROL_CONTROLTYPE_ONOFF = 0x20010001u; +const DWORD MIXERCONTROL_CONTROLTYPE_MUTE = 0x20010002u; +const DWORD MIXERCONTROL_CONTROLTYPE_LOUDNESS = 0x20010004u; +const DWORD MIXERCONTROL_CONTROLTYPE_VOLUME = 0x50030001u; +const DWORD MIXERCONTROL_CONTROLTYPE_MUX = 0x70010001u; + +#pragma pack(push, 1) +struct MIXERCAPSA +{ + WORD wMid; + WORD wPid; + MMVERSION vDriverVersion; + char szPname[32]; + DWORD fdwSupport; + DWORD cDestinations; +}; + +struct MIXERLINEA +{ + DWORD cbStruct; + DWORD dwDestination; + DWORD dwSource; + DWORD dwLineID; + DWORD fdwLine; + DWORD dwUser; // DWORD_PTR in mmsystem.h; x86 width kept + DWORD dwComponentType; + DWORD cChannels; + DWORD cConnections; + DWORD cControls; + char szShortName[16]; + char szName[64]; + struct + { + DWORD dwType; + DWORD dwDeviceID; + WORD wMid; + WORD wPid; + MMVERSION vDriverVersion; + char szPname[32]; + } Target; +}; + +struct MIXERCONTROLA +{ + DWORD cbStruct; + DWORD dwControlID; + DWORD dwControlType; + DWORD fdwControl; + DWORD cMultipleItems; + char szShortName[16]; + char szName[64]; + union + { + struct { LONG lMinimum; LONG lMaximum; }; + struct { DWORD dwMinimum; DWORD dwMaximum; }; + DWORD dwReserved[6]; + } Bounds; + union + { + DWORD cSteps; + DWORD cbCustomData; + DWORD dwReserved[6]; + } Metrics; +}; + +struct MIXERLINECONTROLSA +{ + DWORD cbStruct; + DWORD dwLineID; + union + { + DWORD dwControlID; + DWORD dwControlType; + }; + DWORD cControls; + DWORD cbmxctrl; + MIXERCONTROLA* pamxctrl; +}; + +struct MIXERCONTROLDETAILS +{ + DWORD cbStruct; + DWORD dwControlID; + DWORD cChannels; + union + { + void* hwndOwner; // HWND in mmsystem.h + DWORD cMultipleItems; + }; + DWORD cbDetails; + void* paDetails; +}; + +struct MIXERCONTROLDETAILS_LISTTEXTA +{ + DWORD dwParam1; + DWORD dwParam2; + char szName[64]; +}; + +struct MIXERCONTROLDETAILS_BOOLEAN { LONG fValue; }; +struct MIXERCONTROLDETAILS_UNSIGNED { DWORD dwValue; }; +#pragma pack(pop) + +static_assert(sizeof(MIXERCAPSA) == 0x30, "MIXERCAPSA x86 size"); +static_assert(sizeof(MIXERLINEA) == 0xA8, "MIXERLINEA x86 size"); +static_assert(sizeof(MIXERCONTROLA) == 0x94, "MIXERCONTROLA x86 size"); +static_assert(sizeof(MIXERCONTROLDETAILS_LISTTEXTA) == 0x48, "LISTTEXTA x86 size"); +#endif // !_WIN32 + +#if defined(_M_IX86) +static_assert(sizeof(MIXERCAPSA) == 0x30 && sizeof(MIXERLINEA) == 0xA8 && sizeof(MIXERCONTROLA) == 0x94 + && sizeof(MIXERLINECONTROLSA) == 0x18 && sizeof(MIXERCONTROLDETAILS) == 0x18, + "the mixer structs retail sizes with cbStruct"); +#endif + +// [PLATFORM] The seven WINMM entry points the mixer imports (IAT 0x87F8BC..0x87F8D4), with WINMM's +// types and semantics. Windows points them at winmm; see VoipMixer::setApiForTesting. +struct VoipMixerApi +{ + MMRESULT (BF2_VOIPMIXER_WINAPI* open)(HMIXER* phmx, UINT uMxId, DWORD_PTR dwCallback, + DWORD_PTR dwInstance, DWORD fdwOpen); // mixerOpen + MMRESULT (BF2_VOIPMIXER_WINAPI* close)(HMIXER hmx); // mixerClose + MMRESULT (BF2_VOIPMIXER_WINAPI* getDevCaps)(UINT_PTR uMxId, MIXERCAPSA* pmxcaps, + UINT cbmxcaps); // mixerGetDevCapsA + MMRESULT (BF2_VOIPMIXER_WINAPI* getLineInfo)(HMIXEROBJ hmxobj, MIXERLINEA* pmxl, + DWORD fdwInfo); // mixerGetLineInfoA + MMRESULT (BF2_VOIPMIXER_WINAPI* getLineControls)(HMIXEROBJ hmxobj, MIXERLINECONTROLSA* pmxlc, + DWORD fdwControls); // mixerGetLineControlsA + MMRESULT (BF2_VOIPMIXER_WINAPI* getControlDetails)(HMIXEROBJ hmxobj, MIXERCONTROLDETAILS* pmxcd, + DWORD fdwDetails); // mixerGetControlDetailsA + MMRESULT (BF2_VOIPMIXER_WINAPI* setControlDetails)(HMIXEROBJ hmxobj, MIXERCONTROLDETAILS* pmxcd, + DWORD fdwDetails); // mixerSetControlDetails +}; + +#if defined(__APPLE__) +// [PLATFORM] The CoreAudio table (VoipMixerCoreAudio.cpp). +const VoipMixerApi* voipMixerCoreAudioApi(); +#endif + +// [CHOSEN, not recovered] A std::vector with the VC7.1 layout (allocator word, first, +// last, end: 0x10 bytes on x86), so the object keeps its 0x17C size under any STL. Only what the +// mixer uses: push_back (BF2.exe 0x736760, VC7.1 growth by half) and release. +class VoipMixerLineList +{ +public: + VoipMixerLineList(); + ~VoipMixerLineList(); + + void push_back(const MIXERLINEA& line); + void release(); // free the storage, as the destructor does + bool empty() const { return m_first == m_last; } + std::size_t size() const { return m_first ? static_cast(m_last - m_first) : 0; } + const MIXERLINEA* begin() const { return m_first; } + const MIXERLINEA* end() const { return m_last; } + +private: + VoipMixerLineList(const VoipMixerLineList&); + VoipMixerLineList& operator=(const VoipMixerLineList&); + + std::uint32_t m_allocator; // +00, the VC7.1 allocator slot (unused) + MIXERLINEA* m_first; // +04 + MIXERLINEA* m_last; // +08 + MIXERLINEA* m_end; // +0C +}; + +class VoipMixer +{ +public: + // The boost control state, +0x18..+0x15C (0x144 bytes). findBoostControl copies it out whole. + // [INFERRED] names. + struct BoostControl + { + MIXERCONTROLA control; // +000 (object +018), the switch found on `line` + MIXERLINEA line; // +094 (object +0AC), the microphone source that carries it + DWORD controlType; // +13C (object +154), LOUDNESS or ONOFF + bool queried; // +140 (object +158), set once findBoostControl has searched + bool found; // +141 (object +159) + unsigned char pad[2]; + }; + + VoipMixer(); // BF2.exe 0x7367F0 + virtual ~VoipMixer(); // BF2.exe 0x736840 (slot 0: 0x736BA0) + + static VoipMixer* getInstance(); // BF2.exe 0x736930 + // [INFERRED] name. Closes the mixer handle, deletes the instance and clears the pointer. + static void destroy(); // BF2.exe 0x7356B0 + + // Opens mixer device 0 (after checking its caps) and finds the lines. On success the previous + // handle, if any, is closed. Answers findLines. + bool open(); // BF2.exe 0x736BD0 + // [INFERRED] name. Enumerates the destinations, finds the microphone source on the first + // wave-in and the first speakers destination; true when both were found. + bool findLines(); // BF2.exe 0x736960 + + // [INFERRED] name ("boost supported"). Searches once for the boost switch and caches the + // answer; `out` (may be null) receives the state on the first search only. + bool findBoostControl(BoostControl* out); // BF2.exe 0x735A40 + bool setBoost(bool enabled); // BF2.exe 0x735BB0 + bool getBoost(bool* enabled); // BF2.exe 0x735D00 + + // Capture volume, 0..1 mapped to 0..65535 on the wave-in microphone's VOLUME control. Retail + // neither clamps nor reads the control's bounds. + bool setCaptureVolume(float volume); // BF2.exe 0x735CD0 + bool getCaptureVolume(float* volume); // BF2.exe 0x735DD0 + + // [INFERRED] name. Selects the microphone in the wave-in destination's MUX. + bool selectMicrophoneRecordingSource(); // BF2.exe 0x735EA0 + + // [INFERRED] names. MUTE on the speakers destination's microphone source (the playback + // monitor of the microphone). + bool getMicrophoneMonitorMute(bool* muted); // BF2.exe 0x736120 + bool setMicrophoneMonitorMute(bool muted); // BF2.exe 0x7361E0 + + // [PLATFORM] Installs the WINMM table; null restores the platform default. Install it before + // the first getInstance()/open(). The table is read on every call, and nothing caches it. + static void setApiForTesting(const VoipMixerApi* api); + static const VoipMixerApi* api(); + +private: + VoipMixer(const VoipMixer&); + VoipMixer& operator=(const VoipMixer&); + + // [INFERRED] names. Retail passes the line and control by value. + bool findMicrophoneSource(const MIXERLINEA* destination, MIXERLINEA* source); // 0x7356F0 + bool getLineControl(const MIXERLINEA& line, DWORD controlType, MIXERCONTROLA* control); // 0x7357D0 + bool setControlBool(const MIXERCONTROLA& control, DWORD channels, bool value); // 0x7358D0 + bool setControlUnsigned(const MIXERCONTROLA& control, DWORD channels, DWORD value); // 0x735960 + bool setLineVolume(const MIXERLINEA* line, float volume); // 0x735C30 + + bool m_initialized; // +004, set by findLines + MIXERLINEA* m_speakersDestination; // +008, DST_SPEAKERS (4) + MIXERLINEA* m_waveInDestination; // +00C, DST_WAVEIN (7) + MIXERLINEA* m_speakersMicrophone; // +010, microphone source on the speakers + MIXERLINEA* m_waveInMicrophone; // +014, microphone source on the wave-in + BoostControl m_boost; // +018 + VoipMixerLineList m_waveInDestinations; // +15C, every DST_WAVEIN destination + VoipMixerLineList m_speakersDestinations; // +16C, every DST_SPEAKERS destination +}; + +#if defined(_M_IX86) +static_assert(sizeof(VoipMixer::BoostControl) == 0x144, "BoostControl retail size"); +static_assert(sizeof(VoipMixerLineList) == 0x10, "VC7.1 vector size"); +static_assert(sizeof(VoipMixer) == 0x17C, "VoipMixer retail size (operator new 0x17C, 0x736939)"); +#endif + +} // namespace hfe +} // namespace dice + +#endif // GAME_VOIPCLIENT_VOIPMIXER_H diff --git a/Code/BF2/Game/VoipClient/VoipMixerCoreAudio.cpp b/Code/BF2/Game/VoipClient/VoipMixerCoreAudio.cpp new file mode 100644 index 000000000..a35c02664 --- /dev/null +++ b/Code/BF2/Game/VoipClient/VoipMixerCoreAudio.cpp @@ -0,0 +1,374 @@ +// [PLATFORM] macOS backend for VoipMixer: the seven WINMM mixer entry points on the CoreAudio HAL. +// +// The shell presents mixer device 0 as long as the default input device has an input-scope +// kAudioDevicePropertyVolumeScalar (master element, else channel 1). Without one it answers like a +// machine with no mixer in retail (MMSYSERR_BADDEVICEID from mixerGetDevCapsA and mixerOpen), and +// VoipMixer::open fails there. +// +// The shell's device, in the shape VoipMixer::findLines requires (it needs a microphone source on a +// speakers destination and on a wave-in destination): +// destination 0 DST_SPEAKERS, one source: the microphone, no controls (no monitor mute); +// destination 1 DST_WAVEIN, one source: the microphone, one VOLUME control (0..65535) on the +// input volume scalar. No MUX, so selectMicrophoneRecordingSource answers false, +// and no LOUDNESS/ONOFF, so the recovered code takes retail's "no boost" branch. +// Only device properties are read and written; no input stream is opened, so there is no +// microphone permission prompt. +#if defined(__APPLE__) + +#include "VoipMixer.h" + +#include +#include + +#include +#include + +namespace dice { +namespace hfe { + +namespace { + +const DWORD kSpeakersDestinationId = 0xFFFF0000u; // WINMM-style ids: destinations 0xFFFF00nn, +const DWORD kWaveInDestinationId = 0xFFFF0001u; // sources (dest << 16) | source +const DWORD kSpeakersMicrophoneId = 0x00000000u; +const DWORD kWaveInMicrophoneId = 0x00010000u; +const DWORD kVolumeControlId = 1; +const DWORD kVolumeMaximum = 65535; + +// Open handles: the address of a slot. Each mixerOpen gets a fresh one, as WINMM's do, because +// VoipMixer::open closes the previous handle after opening the next. +bool s_handleOpen[8]; + +bool isOpenHandle(const void* handle) +{ + for (std::size_t i = 0; i < sizeof(s_handleOpen) / sizeof(s_handleOpen[0]); ++i) + if (handle == &s_handleOpen[i]) + return s_handleOpen[i]; + return false; +} + +// WINMM accepts mixer id 0 or an open handle here (retail passes its handle with OBJECTF_MIXER). +bool isMixerObject(const void* object) +{ + return object == 0 || isOpenHandle(object); +} + +struct InputVolume +{ + AudioObjectID device; + AudioObjectPropertyElement element; +}; + +AudioObjectPropertyAddress volumeAddress(AudioObjectPropertyElement element) +{ + AudioObjectPropertyAddress address = { kAudioDevicePropertyVolumeScalar, + kAudioDevicePropertyScopeInput, element }; + return address; +} + +bool findInputVolume(InputVolume* out) +{ + AudioObjectPropertyAddress address = { kAudioHardwarePropertyDefaultInputDevice, + kAudioObjectPropertyScopeGlobal, + kAudioObjectPropertyElementMain }; + AudioObjectID device = kAudioObjectUnknown; + UInt32 size = sizeof(device); + if (::AudioObjectGetPropertyData(kAudioObjectSystemObject, &address, 0, 0, &size, &device) != noErr + || device == kAudioObjectUnknown) + return false; + const AudioObjectPropertyElement elements[2] = { kAudioObjectPropertyElementMain, 1 }; + for (int i = 0; i < 2; ++i) { + const AudioObjectPropertyAddress volume = volumeAddress(elements[i]); + if (::AudioObjectHasProperty(device, &volume)) { + out->device = device; + out->element = elements[i]; + return true; + } + } + return false; +} + +void copyName(char* destination, std::size_t capacity, const char* source) +{ + std::strncpy(destination, source, capacity - 1); + destination[capacity - 1] = '\0'; +} + +void deviceName(AudioObjectID device, char* destination, std::size_t capacity) +{ + destination[0] = '\0'; + AudioObjectPropertyAddress address = { kAudioObjectPropertyName, kAudioObjectPropertyScopeGlobal, + kAudioObjectPropertyElementMain }; + CFStringRef name = 0; + UInt32 size = sizeof(name); + if (::AudioObjectGetPropertyData(device, &address, 0, 0, &size, &name) == noErr && name) { + if (!::CFStringGetCString(name, destination, static_cast(capacity), kCFStringEncodingUTF8)) + destination[0] = '\0'; + ::CFRelease(name); + } +} + +bool readVolume(const InputVolume& input, DWORD* value) +{ + const AudioObjectPropertyAddress address = volumeAddress(input.element); + Float32 scalar = 0.0f; + UInt32 size = sizeof(scalar); + if (::AudioObjectGetPropertyData(input.device, &address, 0, 0, &size, &scalar) != noErr) + return false; + if (!(scalar > 0.0f)) + scalar = 0.0f; + if (scalar > 1.0f) + scalar = 1.0f; + *value = static_cast(std::floor(scalar * static_cast(kVolumeMaximum) + 0.5f)); + return true; +} + +// Values above the control's maximum are clamped, as WDM mixer drivers clamp to the range. +bool writeVolume(const InputVolume& input, DWORD value) +{ + const AudioObjectPropertyAddress address = volumeAddress(input.element); + Boolean settable = false; + if (::AudioObjectIsPropertySettable(input.device, &address, &settable) != noErr || !settable) + return false; + Float32 scalar = static_cast(value > kVolumeMaximum ? kVolumeMaximum : value) + / static_cast(kVolumeMaximum); + return ::AudioObjectSetPropertyData(input.device, &address, 0, 0, sizeof(scalar), &scalar) == noErr; +} + +bool fillLine(DWORD lineId, MIXERLINEA* line, const InputVolume& input) +{ + const DWORD cbStruct = line->cbStruct; + std::memset(line, 0, sizeof(MIXERLINEA)); + line->cbStruct = cbStruct; + line->dwLineID = lineId; + line->cChannels = 1; + switch (lineId) { + case kSpeakersDestinationId: + line->dwDestination = 0; + line->fdwLine = MIXERLINE_LINEF_ACTIVE; + line->dwComponentType = MIXERLINE_COMPONENTTYPE_DST_SPEAKERS; + line->cConnections = 1; + copyName(line->szShortName, sizeof(line->szShortName), "Playback"); + copyName(line->szName, sizeof(line->szName), "Playback"); + line->Target.dwType = MIXERLINE_TARGETTYPE_WAVEOUT; + break; + case kWaveInDestinationId: + line->dwDestination = 1; + line->fdwLine = MIXERLINE_LINEF_ACTIVE; + line->dwComponentType = MIXERLINE_COMPONENTTYPE_DST_WAVEIN; + line->cConnections = 1; + copyName(line->szShortName, sizeof(line->szShortName), "Recording"); + copyName(line->szName, sizeof(line->szName), "Recording"); + line->Target.dwType = MIXERLINE_TARGETTYPE_WAVEIN; + break; + case kSpeakersMicrophoneId: + case kWaveInMicrophoneId: + line->dwDestination = lineId >> 16; + line->dwSource = 0; + line->fdwLine = MIXERLINE_LINEF_SOURCE | MIXERLINE_LINEF_ACTIVE; + line->dwComponentType = MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE; + line->cControls = lineId == kWaveInMicrophoneId ? 1 : 0; + copyName(line->szShortName, sizeof(line->szShortName), "Microphone"); + copyName(line->szName, sizeof(line->szName), "Microphone"); + line->Target.dwType = MIXERLINE_TARGETTYPE_WAVEIN; + break; + default: + return false; + } + deviceName(input.device, line->Target.szPname, sizeof(line->Target.szPname)); + return true; +} + +void fillVolumeControl(MIXERCONTROLA* control) +{ + std::memset(control, 0, sizeof(MIXERCONTROLA)); + control->cbStruct = sizeof(MIXERCONTROLA); + control->dwControlID = kVolumeControlId; + control->dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME; + control->fdwControl = MIXERCONTROL_CONTROLF_UNIFORM; + copyName(control->szShortName, sizeof(control->szShortName), "Volume"); + copyName(control->szName, sizeof(control->szName), "Microphone Volume"); + control->Bounds.dwMinimum = 0; + control->Bounds.dwMaximum = kVolumeMaximum; + control->Metrics.cSteps = kVolumeMaximum; +} + +MMRESULT BF2_VOIPMIXER_WINAPI coreAudioOpen(HMIXER* phmx, UINT uMxId, DWORD_PTR, DWORD_PTR, DWORD) +{ + if (!phmx) + return MMSYSERR_INVALPARAM; + InputVolume input; + if (uMxId != 0 || !findInputVolume(&input)) + return MMSYSERR_BADDEVICEID; + for (std::size_t i = 0; i < sizeof(s_handleOpen) / sizeof(s_handleOpen[0]); ++i) { + if (!s_handleOpen[i]) { + s_handleOpen[i] = true; + *phmx = reinterpret_cast(&s_handleOpen[i]); + return MMSYSERR_NOERROR; + } + } + return MMSYSERR_NOMEM; +} + +MMRESULT BF2_VOIPMIXER_WINAPI coreAudioClose(HMIXER hmx) +{ + for (std::size_t i = 0; i < sizeof(s_handleOpen) / sizeof(s_handleOpen[0]); ++i) { + if (reinterpret_cast(hmx) == &s_handleOpen[i] && s_handleOpen[i]) { + s_handleOpen[i] = false; + return MMSYSERR_NOERROR; + } + } + return MMSYSERR_INVALHANDLE; +} + +MMRESULT BF2_VOIPMIXER_WINAPI coreAudioGetDevCaps(UINT_PTR uMxId, MIXERCAPSA* pmxcaps, UINT cbmxcaps) +{ + if (!pmxcaps) + return MMSYSERR_INVALPARAM; + if (uMxId != 0 && !isOpenHandle(reinterpret_cast(uMxId))) + return MMSYSERR_BADDEVICEID; + InputVolume input; + if (!findInputVolume(&input)) + return uMxId != 0 ? MMSYSERR_NODRIVER : MMSYSERR_BADDEVICEID; + MIXERCAPSA caps; + std::memset(&caps, 0, sizeof(caps)); + deviceName(input.device, caps.szPname, sizeof(caps.szPname)); + caps.cDestinations = 2; + std::memcpy(pmxcaps, &caps, cbmxcaps < sizeof(caps) ? cbmxcaps : sizeof(caps)); + return MMSYSERR_NOERROR; +} + +MMRESULT BF2_VOIPMIXER_WINAPI coreAudioGetLineInfo(HMIXEROBJ hmxobj, MIXERLINEA* pmxl, DWORD fdwInfo) +{ + if (!isMixerObject(hmxobj)) + return MMSYSERR_INVALHANDLE; + if (!pmxl || pmxl->cbStruct < sizeof(MIXERLINEA)) + return MMSYSERR_INVALPARAM; + InputVolume input; + if (!findInputVolume(&input)) + return MMSYSERR_NODRIVER; + DWORD lineId = 0; + switch (fdwInfo & MIXER_GETLINEINFOF_QUERYMASK) { + case MIXER_GETLINEINFOF_DESTINATION: + if (pmxl->dwDestination > 1) + return MMSYSERR_INVALPARAM; + lineId = pmxl->dwDestination == 0 ? kSpeakersDestinationId : kWaveInDestinationId; + break; + case MIXER_GETLINEINFOF_SOURCE: + if (pmxl->dwDestination > 1 || pmxl->dwSource != 0) + return MMSYSERR_INVALPARAM; + lineId = pmxl->dwDestination == 0 ? kSpeakersMicrophoneId : kWaveInMicrophoneId; + break; + case MIXER_GETLINEINFOF_LINEID: + lineId = pmxl->dwLineID; + break; + case MIXER_GETLINEINFOF_COMPONENTTYPE: + if (pmxl->dwComponentType == MIXERLINE_COMPONENTTYPE_DST_SPEAKERS) + lineId = kSpeakersDestinationId; + else if (pmxl->dwComponentType == MIXERLINE_COMPONENTTYPE_DST_WAVEIN) + lineId = kWaveInDestinationId; + else if (pmxl->dwComponentType == MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE) + lineId = kSpeakersMicrophoneId; + else + return MIXERR_INVALLINE; + break; + default: + return MMSYSERR_NOTSUPPORTED; + } + return fillLine(lineId, pmxl, input) ? MMSYSERR_NOERROR : MIXERR_INVALLINE; +} + +MMRESULT BF2_VOIPMIXER_WINAPI coreAudioGetLineControls(HMIXEROBJ hmxobj, MIXERLINECONTROLSA* pmxlc, DWORD fdwControls) +{ + if (!isMixerObject(hmxobj)) + return MMSYSERR_INVALHANDLE; + if (!pmxlc || pmxlc->cbStruct < sizeof(MIXERLINECONTROLSA) || pmxlc->cbmxctrl < sizeof(MIXERCONTROLA) + || !pmxlc->pamxctrl) + return MMSYSERR_INVALPARAM; + InputVolume input; + if (!findInputVolume(&input)) + return MMSYSERR_NODRIVER; + switch (fdwControls & MIXER_GETLINECONTROLSF_QUERYMASK) { + case MIXER_GETLINECONTROLSF_ALL: { + MIXERLINEA line; + line.cbStruct = sizeof(line); + if (!fillLine(pmxlc->dwLineID, &line, input)) + return MIXERR_INVALLINE; + if (line.cControls == 0 || pmxlc->cControls != line.cControls) + return MMSYSERR_INVALPARAM; + fillVolumeControl(pmxlc->pamxctrl); + return MMSYSERR_NOERROR; + } + case MIXER_GETLINECONTROLSF_ONEBYID: + if (pmxlc->dwControlID != kVolumeControlId) + return MIXERR_INVALCONTROL; + pmxlc->dwLineID = kWaveInMicrophoneId; + fillVolumeControl(pmxlc->pamxctrl); + return MMSYSERR_NOERROR; + case MIXER_GETLINECONTROLSF_ONEBYTYPE: + if (pmxlc->dwLineID != kWaveInMicrophoneId || pmxlc->dwControlType != MIXERCONTROL_CONTROLTYPE_VOLUME) + return MIXERR_INVALCONTROL; + fillVolumeControl(pmxlc->pamxctrl); + return MMSYSERR_NOERROR; + default: + return MMSYSERR_NOTSUPPORTED; + } +} + +MMRESULT BF2_VOIPMIXER_WINAPI coreAudioGetControlDetails(HMIXEROBJ hmxobj, MIXERCONTROLDETAILS* pmxcd, DWORD fdwDetails) +{ + if (!isMixerObject(hmxobj)) + return MMSYSERR_INVALHANDLE; + if (!pmxcd || pmxcd->cbStruct < sizeof(MIXERCONTROLDETAILS) || !pmxcd->paDetails) + return MMSYSERR_INVALPARAM; + if (pmxcd->dwControlID != kVolumeControlId) + return MIXERR_INVALCONTROL; + if ((fdwDetails & MIXER_GETCONTROLDETAILSF_QUERYMASK) != MIXER_GETCONTROLDETAILSF_VALUE) + return MMSYSERR_INVALPARAM; // a fader has no list text + if (pmxcd->cChannels != 1 || pmxcd->cbDetails < sizeof(MIXERCONTROLDETAILS_UNSIGNED)) + return MMSYSERR_INVALPARAM; + InputVolume input; + if (!findInputVolume(&input)) + return MMSYSERR_NODRIVER; + DWORD value = 0; + if (!readVolume(input, &value)) + return MMSYSERR_ERROR; + static_cast(pmxcd->paDetails)->dwValue = value; + return MMSYSERR_NOERROR; +} + +MMRESULT BF2_VOIPMIXER_WINAPI coreAudioSetControlDetails(HMIXEROBJ hmxobj, MIXERCONTROLDETAILS* pmxcd, DWORD fdwDetails) +{ + if (!isMixerObject(hmxobj)) + return MMSYSERR_INVALHANDLE; + if (!pmxcd || pmxcd->cbStruct < sizeof(MIXERCONTROLDETAILS) || !pmxcd->paDetails) + return MMSYSERR_INVALPARAM; + if (pmxcd->dwControlID != kVolumeControlId) + return MIXERR_INVALCONTROL; + if ((fdwDetails & MIXER_SETCONTROLDETAILSF_QUERYMASK) != MIXER_SETCONTROLDETAILSF_VALUE) + return MMSYSERR_NOTSUPPORTED; + if (pmxcd->cChannels != 1 || pmxcd->cbDetails < sizeof(MIXERCONTROLDETAILS_UNSIGNED)) + return MMSYSERR_INVALPARAM; + InputVolume input; + if (!findInputVolume(&input)) + return MMSYSERR_NODRIVER; + const DWORD value = static_cast(pmxcd->paDetails)->dwValue; + return writeVolume(input, value) ? MMSYSERR_NOERROR : MMSYSERR_ERROR; +} + +const VoipMixerApi kCoreAudioApi = { + coreAudioOpen, coreAudioClose, coreAudioGetDevCaps, coreAudioGetLineInfo, + coreAudioGetLineControls, coreAudioGetControlDetails, coreAudioSetControlDetails, +}; + +} // namespace + +const VoipMixerApi* voipMixerCoreAudioApi() +{ + return &kCoreAudioApi; +} + +} // namespace hfe +} // namespace dice + +#endif // __APPLE__ diff --git a/Code/BF2/Geom/BoxCorners.h b/Code/BF2/Geom/BoxCorners.h new file mode 100644 index 000000000..f7c93f3cf --- /dev/null +++ b/Code/BF2/Geom/BoxCorners.h @@ -0,0 +1,148 @@ +// Path: [INFERRED] shared Geom header for RendDX9.dll's 96-byte eight-corner object box. +// Contents: the box's constructors, corner layout, world transform, frustum test and component +// extremes, one body per retail function. ObjectDrawer.cpp, XpLightManager.cpp and +// Overgrowth/OverGrowthRender.cpp use this type. The type name is +// [CHOSEN, not recovered]. + +#ifndef GEOM_BOXCORNERS_H +#define GEOM_BOXCORNERS_H + +#include +#include "QuadPatch.h" // aabbCorners - the corner layout body +#include "../Math/Frustum.h" +#include "../Math/LocalBoundingBox.h" +#include "../Math/Mat4.h" +#include "../Math/Plane3.h" +#include "../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace geom { + +// The eight corners of a box, corner i taking x from the maximum when bit 2 is set, y when bit 1 +// is set and z when bit 0 is set. Plain data: 24 floats, no vtable. +struct BoxCorners +{ + Vec3 corner[8]; + + // PE 0x100AE110. Zeroes the 24 floats (retn, no arguments). Callers that zero the same floats + // inline in retail use this constructor as well. + BoxCorners() + { + for (unsigned int i = 0; i < 8; ++i) + corner[i].x = corner[i].y = corner[i].z = 0.0f; + } + + // PE 0x100CE120. Zeroes the 24 floats inline, then lays out `bounds` (setBounds) and moves the + // corners through `world` (transform); retn 8. + BoxCorners(const LocalBoundingBox& bounds, const Mat4& world) + { + for (unsigned int i = 0; i < 8; ++i) + corner[i].x = corner[i].y = corner[i].z = 0.0f; + setBounds(bounds); + transform(world); + } + + // The same retail function as QuadPatch.h's aabbCorners, not a separate one: the corners from + // the box's (min, max) pair, which the box carries contiguously at +0x00 / +0x0C. + void setBounds(const LocalBoundingBox& bounds) + { + aabbCorners(&corner[0].x, &bounds.m_min.x); + } + + // PE 0x101C67F0. Every corner through the full matrix, translation included; all three rows + // are formed from the untouched corner before any is stored. Corner 0's y and x rows associate + // differently from corners 1..7 (101C67F6..101C683D against 101C6845..101C688C). + void transform(const Mat4& world) + { + const float* const m = world.m; + for (unsigned int i = 0; i < 8; ++i) + { + const float x = corner[i].x; + const float y = corner[i].y; + const float z = corner[i].z; + const float tz = z * m[10] + x * m[2] + y * m[6] + m[14]; + const float ty = i == 0 ? x * m[1] + y * m[5] + z * m[9] + m[13] + : x * m[1] + z * m[9] + y * m[5] + m[13]; + const float tx = i == 0 ? z * m[8] + x * m[0] + y * m[4] + m[12] + : y * m[4] + z * m[8] + x * m[0] + m[12]; + corner[i].x = tx; + corner[i].y = ty; + corner[i].z = tz; + } + } + + // PE 0x101C6A90. False as soon as one of the frustum's six planes has all eight corners + // strictly in front of it (distance > 0, ordered; all eight are counted for each plane), true + // otherwise; retn 4. Corner 0's distance is (z*n.z + x*n.x) + y*n.y + d, corners 1..7's + // (y*n.y + z*n.z) + x*n.x + d (101C6AA0..101C6AB4 against 101C6ACD..101C6AE2). + bool insideFrustum(const Frustum& frustum) const + { + for (unsigned int plane = 0; plane < 6; ++plane) + { + const Plane3& p = frustum.m_planes[plane]; + int outside = 0; + { + const Vec3& c = corner[0]; + if (c.z * p.normal.z + c.x * p.normal.x + c.y * p.normal.y + p.d > 0.0f) + outside += 1; + } + for (unsigned int i = 1; i < 8; ++i) + { + const Vec3& c = corner[i]; + if (c.y * p.normal.y + c.z * p.normal.z + c.x * p.normal.x + p.d > 0.0f) + outside += 1; + } + if (outside == 8) + return false; + } + return true; + } + + // PE 0x101C6C50. The negation of insideFrustum (`neg al; sbb eax, eax; add eax, 1`); retn 4. + bool outside(const Frustum& frustum) const + { + return !insideFrustum(frustum); + } + + // PE 0x101C6C70. The component-wise maximum, starting from corner 0: a component moves only + // when it is strictly below the corner's (`test ah, 5; jp`), so a NaN corner never wins. + Vec3 maximum() const + { + Vec3 result = corner[0]; + for (unsigned int i = 1; i < 8; ++i) + { + if (result.x < corner[i].x) result.x = corner[i].x; + if (result.y < corner[i].y) result.y = corner[i].y; + if (result.z < corner[i].z) result.z = corner[i].z; + } + return result; + } + + // PE 0x101C6E10. The component-wise minimum, starting from corner 0: a component moves only + // when it is strictly above the corner's (`test ah, 41h; jne`). + Vec3 minimum() const + { + Vec3 result = corner[0]; + for (unsigned int i = 1; i < 8; ++i) + { + if (result.x > corner[i].x) result.x = corner[i].x; + if (result.y > corner[i].y) result.y = corner[i].y; + if (result.z > corner[i].z) result.z = corner[i].z; + } + return result; + } +}; + +// setBounds hands both objects to aabbCorners as flat float arrays. +static_assert(sizeof(Vec3) == 12, "a corner is three floats"); +static_assert(offsetof(LocalBoundingBox, m_max) == 0x0C, "the box's max follows its min"); +#if defined(_M_IX86) +static_assert(sizeof(BoxCorners) == 0x60, "the eight-corner box is 96 bytes"); +#endif + +} // namespace geom +} // namespace hfe +} // namespace dice + +#endif // GEOM_BOXCORNERS_H diff --git a/Code/BF2/Geom/BundledMesh.cpp b/Code/BF2/Geom/BundledMesh.cpp index 673341e81..0cab3c8e1 100644 --- a/Code/BF2/Geom/BundledMesh.cpp +++ b/Code/BF2/Geom/BundledMesh.cpp @@ -1,6 +1,7 @@ // Path attested: BF2 1.50 RendDX9.dll string1021B300 names Geom/BundledMesh.cpp. // PE-only renderer. No dedicated ELF body exists. #ifdef BF2_IMAGE_RENDDX9 +#include "../../RendDX9Abi/ThunkAbi.h" #include "BundledMesh.h" #include "BundledMeshTemplate.h" #include "BundledMeshMaterial.h" @@ -8,15 +9,20 @@ #include "StaticMesh.h" #include "StaticMeshRenderer.h" #include "XpLightManager.h" +#include "../RendDX9/RendDX9Math.h" // the RendDX9.dll Math copies #include "../../RendDX9Abi/BfMemory.h" #include "../../RendDX9Abi/Frontier.h" #include "../../RendDX9Abi/PluginEntry.h" #include "../RendDX9/RendDX9Base.h" +#include "../RendDX9/QueueProfiler.h" #include "../RendDX9/ShaderParameter.h" -#if BF2_PLUGIN_ABI_NATIVE +#include "../RendMisc/IRenderView.h" #include "../Game/Objects/IObject.h" #include "../Game/Objects/IObjectTemplate.h" #include "../Game/Objects/ObjectLayoutAccess.h" +#include "../GeomMisc/Debug.h" +#if defined(__APPLE__) +#include "../Platform/X87Compat.h" #endif #include #include @@ -32,14 +38,15 @@ void indexBufferBind(void*); void vertexDeclarationBind(void*); // Shared 10005820 wrapper. Parameter names follow its actual body, not IDA's glued calls. void rendererDrawIndexedPrimitive(unsigned int,unsigned int,int,unsigned int,unsigned int,unsigned int); +void* effectD3dxHandle(void* effect); // Effect.cpp - the wrapper's +0x08 ID3DXEffect* } namespace geom { extern LightManager* g_LightManager; namespace { template R dispatch(void* self,unsigned int offset,A... args) { - typedef R(__fastcall* Fn)(void*,void*,A...); - return reinterpret_cast((*static_cast(self))[offset/4])(self,0,args...); + typedef R(__thiscall* Fn)(void*,A...); + return reinterpret_cast((*static_cast(self))[offset/4])(self,args...); } template T& field(void* p,unsigned int offset) { return *reinterpret_cast(static_cast(p)+offset); } @@ -48,17 +55,27 @@ template T& field(void* p,unsigned int offset) // retail-ABI flavour keeps the raw offset, which IObject's retail-aligned prefix shares. void* objectGeometryField(void* object) { -#if BF2_PLUGIN_ABI_NATIVE return world::object_detail::LayoutAccess::geometry(static_cast(object)); -#else - return field(object,0x38); -#endif } // 100A6170, including its 2^-46 squared-length threshold. Unordered comparisons // take the same x87 refusal/normalization arms; the callers discard the status code. +// PE 0x100A6170 int normalizeXZ(Vec2& value) { +#if defined(__APPLE__) + // [CHOSEN, not recovered] Keep the squared-length spill and retained x87 inverse. + using namespace bf2x87; + const float lengthSquared=store(add(mul(wide(value.x),wide(value.x)),mul(wide(value.y),wide(value.y)))); + if(!less(bf2x87::abs(sub(wide(lengthSquared),wide(1.0f))),wide(FLT_EPSILON))) + { + if(less(bf2x87::abs(wide(lengthSquared)),wide(1.4210854715202004e-14f))) + { value.x=0; value.y=0; return -20001; } + const Real factor=div(wide(1.0f),squareRoot(wide(lengthSquared))); + value.x=store(mul(factor,wide(value.x))); + value.y=store(mul(factor,wide(value.y))); + } +#else const float lengthSquared=value.x*value.x+value.y*value.y; if (!(std::fabs(static_cast(lengthSquared)-1.0)(factor*value.x); value.y=static_cast(factor*value.y); } +#endif return 0; } void allocateUvMatrices(BundledMesh& self) @@ -76,44 +94,47 @@ void allocateUvMatrices(BundledMesh& self) { self.m_uvMatrices=static_cast(::renddx9abi::engineAlloc(8*sizeof(Mat4))); if (self.m_uvMatrices) - for (int i=0;i<8;++i) new(self.m_uvMatrices+i) Mat4; + for (int i=0;i<8;++i) rendmath::constructIdentity(self.m_uvMatrices[i]); // element ctor sub_10030D80 for (int i=0;i<8;++i) self.m_uvMatrices[i]=Mat4::getIdentity(); } } void uvRangeDiagnostic(int index,unsigned int line) { - ::renddx9abi::logf("Geom/BundledMesh.cpp:%u TBM: UVMatrixIndex is out of range %d",line,index); + ::renddx9abi::Debug(DebugTypeError, + "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\BundledMesh.cpp", + static_cast(line),"") << "TBM: UVMatrixIndex is out of range " << index; } } +// PE 0x10079290, RendDX9's copy of Mat4::getZero: a function-local matrix built once from four +// zero rows through the Mat4(row0..row3) copy PE 0x100795B0; distinct from the identity used by +// getTransformation. const Mat4& bundledMeshZeroMatrix() { - // four zero rows, distinct from the identity used by getTransformation. - static Mat4 result; - static const bool initialized=[](){ std::memset(result.m,0,sizeof(result.m)); return true; }(); - (void)initialized; + static const Vec4 zero = { 0.0f, 0.0f, 0.0f, 0.0f }; + static Mat4 result = rendmath::mat4FromRows(zero, zero, zero, zero); return result; } +// PE 0x10104D10 BundledMesh::BundledMesh(BundledMeshTemplate* objectTemplate) - : GeometryInstanceData(g_bundledMeshVtable) + : GeometryInstanceData(g_bundledMeshVtable), m_refCount(1) { // Explicit fields retain the constructor's untouched allocator/padding words. - m_refCount=1; - dx9rend::Ra::raObjectParametersConstruct(&m_parameters); + // m_parameters (sub_100458E0) is constructed with the object. m_template=objectTemplate; m_partTransforms=0; m_distanceToCamera=0; m_fov=-1; m_heightOverTerrain=0; m_shadowSunHeight=0; m_underRoof=0; m_heightmapCluster=0; m_horizontalForward.x=0; m_horizontalForward.y=0; m_lodRecord=0; m_lodMaterials=0; m_geomIndex=0; m_lodIndex=0; m_animationIndex=0; m_dword29C=-1; m_dword2A0=0; m_dword2A4=0; m_uvMatrices=0; m_ownerObject=0; m_shadowCasterFrame=0; m_shadowProjection=0; m_nextGeometry=0; - m_lights.first=m_lights.last=m_lights.end=0; - m_lightRecords.first=m_lightRecords.last=m_lightRecords.end=0; + // m_lights and m_lightRecords are default-constructed empty m_shadowFadeTime=0; m_castsShadow=0; m_animationExplicit=0; m_lodExplicit=0; m_lodFrame=0; m_heightFrame=0; m_shadowFade=1; m_inverseTransform=0; if (m_template->m_loaded) initializeFromTemplate(); m_heightmapCluster=classManager->getSingleton(renddx9abi::HostString("HeightmapCluster")); } +// PE 0x10104E90 BundledMesh::~BundledMesh() { // No template reference/count decrement exists in this body. @@ -121,12 +142,10 @@ BundledMesh::~BundledMesh() if (m_inverseTransform) ::renddx9abi::engineFree(m_inverseTransform); ::renddx9abi::engineFree(m_partTransforms); ::renddx9abi::engineFree(m_uvMatrices); - vc71::setEraseValue(m_template->m_instances,this); - if (m_lightRecords.first) ::renddx9abi::engineFree(m_lightRecords.first); - m_lightRecords.first=m_lightRecords.last=m_lightRecords.end=0; - if (m_lights.first) ::renddx9abi::engineFree(m_lights.first); - m_lights.first=m_lights.last=m_lights.end=0; - dx9rend::Ra::raObjectParametersDestroy(&m_parameters); + m_template->m_instances.erase(this); + std::vector().swap(m_lightRecords); + std::vector().swap(m_lights); + // m_parameters (sub_1004D900) is destroyed with the object, after this body. // The base-class vptr restore is not observable: like StaticMesh, this is a flat ABI object. } void* bundledMeshConstruct(void* storage,BundledMeshTemplate* templ) @@ -149,8 +168,10 @@ int BundledMesh::release() } void* BundledMesh::queryInterface(unsigned int iid) { return iid==1u || iid==1227874558u || iid==2915824892u ? this : 0; } +// PE 0x10178EF0 void BundledMesh::setFov(float value) { m_fov=value; } float BundledMesh::getFov() const { return m_fov; } +// PE 0x101070E0 void* BundledMesh::setShadowProjection(void* value) { return m_shadowProjection=value; } void* BundledMesh::getShadowProjection() const { return m_shadowProjection; } int BundledMesh::getGeometryType() const { return m_lodRecord->renderKind; } @@ -172,11 +193,13 @@ float BundledMesh::getBoundingRadius() const } const Mat4* BundledMesh::getGeometryTransformation() const { return m_partTransforms ? m_partTransforms[0] : &Mat4::getIdentity(); } +// PE 0x10103D10 void BundledMesh::allocatePartTransforms() { if (!m_partTransforms) { - m_partTransforms=static_cast(::renddx9abi::engineAlloc(4*m_template->m_maxPartCount)); + m_partTransforms=static_cast( + ::renddx9abi::engineAlloc(sizeof(const Mat4*)*m_template->m_maxPartCount)); for (unsigned int i=0;im_maxPartCount;++i) m_partTransforms[i]=&bundledMeshZeroMatrix(); } @@ -187,6 +210,7 @@ void BundledMesh::setPartTransformation(const Mat4* value,int part) if (m_template->m_loaded && part(m_template->m_maxPartCount)) { allocatePartTransforms(); m_partTransforms[part]=value; } } +// PE 0x10103DB0 void BundledMesh::setGeometryTransformation(const Mat4* value) { if (m_template->m_loaded) @@ -208,21 +232,21 @@ void BundledMesh::setBoneTransforms(const Mat4* value,int) unsigned int BundledMesh::getPartCount() const { return m_lodRecord ? m_lodRecord->partCount : 0; } void BundledMesh::setGeomIndex(int geom) { - if (!m_template->m_loaded || !m_template->m_geoms.first) return; - const unsigned int count=static_cast((m_template->m_geoms.last-m_template->m_geoms.first)/32); + if (!m_template->m_loaded || m_template->m_geoms.empty()) return; + const unsigned int count=static_cast(m_template->m_geoms.size()); if (static_cast(geom)>=count || geom<0) return; if (m_geomIndex!=static_cast(geom)) { m_lodIndex=0; m_lodExplicit=0; } m_geomIndex=geom; - vc71::vector_layout& materials=reinterpret_cast(m_template->m_materials.first)[geom]; - const unsigned int lods=materials.first ? static_cast((materials.last-materials.first)/16) : 0; + std::vector& materials=m_template->m_materials[geom]; + const unsigned int lods=static_cast(materials.size()); if (m_lodIndex>=lods-1) m_lodIndex=lods-1; - m_lodMaterials=reinterpret_cast(materials.first)+m_lodIndex; - m_lodRecord=reinterpret_cast( - reinterpret_cast(m_template->m_geoms.first)[geom].lods.first)+m_lodIndex; + m_lodMaterials=materials.data()+m_lodIndex; + m_lodRecord=m_template->m_geoms[geom].lods.data()+m_lodIndex; } int BundledMesh::getGeomIndex() const { return static_cast(m_geomIndex); } int BundledMesh::getGeomCount() const -{ return m_template->m_geoms.first ? static_cast((m_template->m_geoms.last-m_template->m_geoms.first)/32) : 0; } +{ return static_cast(m_template->m_geoms.size()); } +// PE 0x10103EB0 void BundledMesh::setLodIndex(int lod) { if (lod==-1) { m_lodExplicit=0; m_lodIndex=0; } @@ -232,9 +256,9 @@ void BundledMesh::setLodIndex(int lod) int BundledMesh::getLodIndex() const { return static_cast(m_lodIndex); } int BundledMesh::getLodCount() const { - const vc71::vector_layout& lods=reinterpret_cast(m_template->m_geoms.first)[m_geomIndex].lods; - return lods.first ? static_cast((lods.last-lods.first)/72) : 0; + return static_cast(m_template->m_geoms[m_geomIndex].lods.size()); } +// PE 0x10104980 int BundledMesh::setAnimationIndex(int value) { if (value==-1) { m_animationExplicit=0; return m_animationIndex=0; } @@ -242,7 +266,8 @@ int BundledMesh::setAnimationIndex(int value) } int BundledMesh::getAnimationIndex() const { return m_animationIndex; } int BundledMesh::getMaterialCount() const -{ return m_lodMaterials && m_lodMaterials->first ? static_cast((m_lodMaterials->last-m_lodMaterials->first)/4) : 0; } +{ return m_lodMaterials ? static_cast(m_lodMaterials->size()) : 0; } +// PE 0x10104490 void BundledMesh::setUvTranslation(int index,float x,float y) { // All three setters really use OR, admitting many out-of-range indices (retail defect). @@ -250,17 +275,29 @@ void BundledMesh::setUvTranslation(int index,float x,float y) { allocateUvMatrices(*this); m_uvMatrices[index].m[8]=x; m_uvMatrices[index].m[9]=y; } else uvRangeDiagnostic(index,1423); } +// PE 0x101045C0 void BundledMesh::setUvRotation(int index,float angle) { if (index>=0 || index(m_template->m_dword10C+1)) { - const float c=static_cast(std::cos(angle)),s=static_cast(std::sin(angle)); + float c,s; +#if defined(__APPLE__) && defined(__x86_64__) + // [CHOSEN, not recovered] Use the shipped fsincos and its two float stores on Intel. + __asm__ volatile("flds %2; fsincos; fstps %0; fstps %1" : "=m"(c),"=m"(s) : "m"(angle) : "st"); +#elif defined(__APPLE__) + // [CHOSEN, not recovered] Shared native transcendental policy on Apple silicon. + c=bf2x87::store(bf2x87::cosValue(bf2x87::wide(angle))); + s=bf2x87::store(bf2x87::sinValue(bf2x87::wide(angle))); +#else + c=static_cast(std::cos(angle)); s=static_cast(std::sin(angle)); +#endif allocateUvMatrices(*this); m_uvMatrices[index].m[0]=c; m_uvMatrices[index].m[1]=-s; m_uvMatrices[index].m[4]=s; m_uvMatrices[index].m[5]=c; } else uvRangeDiagnostic(index,1443); } +// PE 0x10104720 void BundledMesh::setUvTransformation(int index,const Mat4* value) { if (index>=0 || index(m_template->m_dword10C+1)) @@ -271,12 +308,8 @@ void* BundledMesh::setOwnerObject(void* value) { return m_ownerObject=value; } void* BundledMesh::refreshRootObject() { void* root=staticMeshRootParent(m_ownerObject); -#if BF2_PLUGIN_ABI_NATIVE // The native MSVC table also places getFlags at +44; prefer its typed host contract. m_castsShadow=root && (static_cast(root)->getTemplate()->getFlags()&0x800) ? 1 : 0; -#else - m_castsShadow=root && (dispatch(field(root,0x14),0x44)&0x800) ? 1 : 0; -#endif return root; } bool BundledMesh::castsDynamicShadow() @@ -294,33 +327,61 @@ int BundledMesh::setDword29C(int value) { return m_dword29C=value; } void* BundledMesh::setNextGeometry(void* value) { return m_nextGeometry=value; } void* BundledMesh::getNextGeometry() const { return m_nextGeometry; } void BundledMesh::setTransparency(float value) { m_parameters.transparency.value=value; } +// PE 0x101040F0 void BundledMesh::initializeFromTemplate() { - if (m_template->m_geoms.first && static_cast((m_template->m_geoms.last-m_template->m_geoms.first)/32)>=2) + if (m_template->m_geoms.size()>=2) m_geomIndex=1; dispatch(this,0x6C,static_cast(m_geomIndex)); if (m_template->m_maxPartCount==1 && m_ownerObject) -#if BF2_PLUGIN_ABI_NATIVE dispatch(this,0x50,&static_cast(m_ownerObject)->getAbsoluteTransformation()); -#else - dispatch(this,0x50,dispatch(m_ownerObject,0x80)); -#endif } +#if defined(__APPLE__) +namespace { +// [CHOSEN, not recovered] Carry the x87 return through the caller's multiply/FISTP. +bf2x87::Real bundledAnimationPhaseNative(BundledMesh& mesh,const Vec3& camera) +{ + using namespace bf2x87; + Vec2 direction={store(sub(wide(camera.x),wide(mesh.m_partTransforms[0]->m[12]))), + store(sub(wide(camera.z),wide(mesh.m_partTransforms[0]->m[14])))}; + const Vec2 side={mesh.m_partTransforms[0]->m[0],mesh.m_partTransforms[0]->m[2]}; + normalizeXZ(direction); + Real result=sub(wide(0.25f),mul(add(mul(wide(direction.y),wide(mesh.m_horizontalForward.y)), + mul(wide(direction.x),wide(mesh.m_horizontalForward.x))),wide(0.249975f))); + if(less(add(mul(wide(side.y),wide(direction.y)),mul(wide(side.x),wide(direction.x))),wide(0.0f))) + result=sub(wide(1.0f),result); + return result; +} +} +#endif +// PE 0x10104840 float BundledMesh::animationPhase(const Vec3& camera) { +#if defined(__APPLE__) + return bf2x87::store(bundledAnimationPhaseNative(*this,camera)); +#else Vec2 direction={camera.x-m_partTransforms[0]->m[12],camera.z-m_partTransforms[0]->m[14]}; const Vec2 side={m_partTransforms[0]->m[0],m_partTransforms[0]->m[2]}; normalizeXZ(direction); - double result=0.25-(direction.y*m_horizontalForward.y+direction.x*m_horizontalForward.x)*0.249975f; - if (side.y*direction.y+side.x*direction.x<0) result=1.0-result; + double result=0.25-(static_cast(direction.y)*m_horizontalForward.y + +static_cast(direction.x)*m_horizontalForward.x)*0.249975f; + if (static_cast(side.y)*direction.y+static_cast(side.x)*direction.x<0) result=1.0-result; return static_cast(result); +#endif } +// PE 0x101048D0 unsigned int BundledMesh::animationIndex(const Vec3& camera) { const unsigned int count=m_template->m_u2; +#if defined(__APPLE__) + const unsigned int index=static_cast(bf2x87::toIntTruncate( + bf2x87::mul(bf2x87::wide(count),bundledAnimationPhaseNative(*this,camera)))); +#else const unsigned int index=static_cast(static_cast(animationPhase(camera)*static_cast(count))); +#endif return index>=count ? m_template->m_u2-1 : index; } +// PE 0x10103F00 unsigned int BundledMesh::materialFeatures(BundledMeshMaterial* material,bool additive,unsigned int caps) { const BundledMeshState& state=*material->m_state; @@ -339,29 +400,48 @@ unsigned int BundledMesh::materialFeatures(BundledMeshMaterial* material,bool ad if(additive)bits|=0x800; return bits; } +// PE 0x10104AE0 void BundledMesh::updateLodSelection() { const unsigned int frame=dx9rend::rendererFrameOrdinal(); if(m_lodFrame==frame || m_lodExplicit)return; m_lodFrame=frame; void* view=dispatch(dx9rend::g_rendererBase,0x48); - BundledMeshGeom& geom=reinterpret_cast(m_template->m_geoms.first)[m_geomIndex]; - MeshBounds& bounds=reinterpret_cast(geom.lods.first)->bounds; + BundledMeshGeom& geom=m_template->m_geoms[m_geomIndex]; + MeshBounds& bounds=geom.lods.data()->bounds; if(bounds.dirty)meshBoundsFinalize(bounds); const float radius=bounds.radius; +#if defined(__APPLE__) + // [CHOSEN, not recovered] Spill the threshold once, retaining each scaled comparison. + using namespace bf2x87; + const float threshold=store(sub(mul(wide(dispatch(view,0x2C)),wide(m_distanceToCamera)),wide(radius))); +#else const float threshold=dispatch(view,0x2C)*m_distanceToCamera-radius; - const unsigned int count=geom.distances.first ? static_cast((geom.distances.last-geom.distances.first)/4):0; - const float* distances=reinterpret_cast(geom.distances.first); +#endif + const unsigned int count=static_cast(geom.distances.size()); + const float* distances=geom.distances.data(); unsigned int selected=0; for(unsigned int i=0;i(dx9rend::g_Renderer,0x84C)*field(dx9rend::g_Renderer,0x8B4)(this,0x6C,static_cast(m_geomIndex)); } m_shaderLod=0; - if(field(dx9rend::g_Renderer,0x708)) + if(dx9rend::rendererTailByte(0x708)) for(int i=3;i>=0;--i) - if(threshold>field(dx9rend::g_Renderer,0x72C+4*i)) { m_shaderLod=i+1; break; } + if(threshold>dx9rend::rendererTailFloat(0x72C+4*i)) { m_shaderLod=i+1; break; } } +// PE 0x10106620 void BundledMesh::drawShadowMap(void* light,void*,void*,void*,void*,void*) { // The profiling-only bracket follows the existing mesh policy; @@ -379,32 +459,37 @@ void BundledMesh::drawShadowMap(void* light,void*,void*,void*,void*,void*) const int lodCount=dispatch(this,0x80); if(currentLod!=shadowLod)dispatch(this,0x78,lodCount-1first ? static_cast((m_lodMaterials->last-m_lodMaterials->first)/4):0; + rendmath::constructIdentity(combined); // 0x10106723 + const unsigned int materialCount=static_cast(m_lodMaterials->size()); dx9rend::vertexDeclarationBind(m_template->m_vertexDeclaration); dx9rend::vertexBufferBindStream(m_template->m_vertexBuffer,0); dx9rend::indexBufferBind(m_template->m_indexBuffer); // 1001E3A0 returns a borrowed parameter, unlike the counted 1001E420 owner. - dx9rend::ShaderParameter* unpack=dx9rend::effectGetShaderParameterBorrowedTyped(g_bundledShadowEffect,vc71::string("POSUNPACK")); + dx9rend::ShaderParameter* unpack=dx9rend::effectGetShaderParameterBorrowedTyped(g_bundledShadowEffect,std::string("POSUNPACK")); const float scale[4]={m_template->m_decompressScale.x,m_template->m_decompressScale.y,m_template->m_decompressScale.z,1}; unpack->setValue(scale,0); - if(light && field(light,0x495)) + const LightShadowRecord* const record=static_cast(light); + if(light && record->tail494[1]) // +0x495 { - combined=Mat4::getIdentity(); - combined.fullMult(field(light,0x238),field(light,0x278)); - dx9rend::effectGetShaderParameterBorrowedTyped(g_bundledShadowEffect,vc71::string("vpLightMat"))->setValue(&combined,0); - dx9rend::effectGetShaderParameterBorrowedTyped(g_bundledShadowEffect,vc71::string("vpLightTrapezMat"))->setValue(&combined,0); - void* d3dx=field(g_bundledShadowEffect,8); + rendmath::constructIdentity(combined); // 0x101067DD + geometryRendererMatrixProduct(combined,record->matrices[1],record->matrices[2]); // +0x238, +0x278 (0x10077A30) + dx9rend::effectGetShaderParameterBorrowedTyped(g_bundledShadowEffect,std::string("vpLightMat"))->setValue(&combined,0); + dx9rend::effectGetShaderParameterBorrowedTyped(g_bundledShadowEffect,std::string("vpLightTrapezMat"))->setValue(&combined,0); + // The effect's +0x08 D3DX interface. g_bundledShadowEffect is non-null here: the + // POSUNPACK and vpLightMat lookups above already dereferenced it. + void* d3dx=dx9rend::effectD3dxHandle(g_bundledShadowEffect); typedef void(__stdcall* Commit)(void*); reinterpret_cast((*static_cast(d3dx))[0x104/4])(d3dx); } else { - dx9rend::effectGetShaderParameterBorrowedTyped(g_bundledShadowEffect,vc71::string("vpLightMat"))->setValue(&field(m_shadowProjection,0x238),0); - dx9rend::effectGetShaderParameterBorrowedTyped(g_bundledShadowEffect,vc71::string("vpLightTrapezMat"))->setValue(&field(m_shadowProjection,0x278),0); + const LightShadowRecord* const own=static_cast(m_shadowProjection); + dx9rend::effectGetShaderParameterBorrowedTyped(g_bundledShadowEffect,std::string("vpLightMat"))->setValue(&own->matrices[1],0); + dx9rend::effectGetShaderParameterBorrowedTyped(g_bundledShadowEffect,std::string("vpLightTrapezMat"))->setValue(&own->matrices[2],0); } for(unsigned int i=0;i(m_lodMaterials->first)[i]; + BundledMeshMaterial* material=(*m_lodMaterials)[i]; if(material->m_kind==1 || material->m_kind==2)continue; g_bundledOneBoneSkinning->setMatrixPointerArray(reinterpret_cast(m_partTransforms),m_lodRecord->partCount); // Keep the wrapper's declared argument order: primitive count, type, base, @@ -417,9 +502,52 @@ void BundledMesh::drawShadowMap(void* light,void*,void*,void*,void*,void*) if(originalLod!=shadowLod)dispatch(this,0x78,originalGeom ? -1 : originalLod); } +// PE 0x101063B0: unreachable in 1.50: no code or data references +// [INFERRED] name. Draws the current lod's materials with every part but `part` hidden behind the +// shared zero matrix, in the effect technique "subPartHighlight". The unused-by-others globals are +// StaticMeshRenderer's borrowed bundled-mesh parameters (view inverse, one-bone skinning array, +// texture layer 0). Each material draw rebuilds the view inverse from the camera's inverse view +// matrix (a copy of a copy, then the orthonormal inverse) and binds the state's second texture. +void BundledMesh::drawSubPartHighlight(unsigned int part) +{ + static dx9rend::QueueProfiler profiler(std::string("BundledMeshSingleSubGeom")); + profiler.begin(); + + Mat4 hidden(bundledMeshZeroMatrix()); + const Mat4** const transforms=static_cast( + ::renddx9abi::engineAlloc(m_template->m_maxPartCount*4)); + for(unsigned int i=0;im_maxPartCount;++i) + transforms[i]=i==part ? m_partTransforms[i] : &hidden; + + const unsigned int materialCount=static_cast(m_lodMaterials->size()); + dx9rend::IRenderView* const view=dx9rend::rendererGetRenderViewDup(); + dx9rend::vertexDeclarationBind(m_template->m_vertexDeclaration); + dx9rend::vertexBufferBindStream(m_template->m_vertexBuffer,0); + dx9rend::indexBufferBind(m_template->m_indexBuffer); + for(unsigned int i=0;im_state; + Mat4 viewInverse(*view->getInverseViewMatrixPtr()); + const Mat4 viewInverseCopy(viewInverse); + viewInverse.setInverse(viewInverseCopy); + g_bundledViewI->setValue(&viewInverse,0); + g_bundledOneBoneSkinning->setMatrixPointerArray(reinterpret_cast(transforms),m_lodRecord->partCount); + dx9rend::effectSetTechniqueByName(g_bundledShadowEffect,std::string("subPartHighlight")); + dx9rend::effectBegin(g_bundledShadowEffect); + g_bundledTexLayer0->setValue(state->m_textures[1],0); + dx9rend::effectBeginPass(g_bundledShadowEffect,0); + dx9rend::rendererDrawIndexedPrimitive(material->m_primitiveCount,m_template->m_primitiveType, + material->m_vertexStart,0,material->m_vertexCount,material->m_indexStart); + dx9rend::effectEnd(g_bundledShadowEffect); + } + ::renddx9abi::engineFree(transforms); + dx9rend::QueueProfiler::end(); +} + namespace { -#define BM0(R,name) R __fastcall bm_##name(BundledMesh* s,void*) { return s->name(); } -#define BM1(R,name,T) R __fastcall bm_##name(BundledMesh* s,void*,T v) { return s->name(v); } +#define BM0(R,name) R RD9_THUNK bm_##name(BundledMesh* s RD9_THUNK_EDX) { return s->name(); } +#define BM1(R,name,T) R RD9_THUNK bm_##name(BundledMesh* s RD9_THUNK_EDX,T v) { return s->name(v); } BM0(int,addRef) BM0(int,getRef) BM0(int,release) BM1(void*,queryInterface,unsigned int) BM1(void,setFov,float) BM0(float,getFov) BM1(void*,setShadowProjection,void*) BM0(void*,getShadowProjection) BM0(int,getGeometryType) @@ -435,24 +563,24 @@ BM1(int,setDword29C,int) BM1(void*,setNextGeometry,void*) BM0(void*,getNextGeome BM1(void,setTransparency,float) #undef BM0 #undef BM1 -void __fastcall bm_draw(BundledMesh* s,void*,void* a,void* b,void* c) { s->draw(a,b,c); } -void __fastcall bm_shadow(BundledMesh* s,void*,void* a,void* b,void* c,void* d,void* e,void* f) { s->drawShadowMap(a,b,c,d,e,f); } -void* __fastcall bm_destroy(void* s,void*,unsigned char flags) { return bundledMeshDestroyFlags(s,flags); } -void __fastcall bm_setPart(BundledMesh* s,void*,const Mat4* value,int part) { s->setPartTransformation(value,part); } -void __fastcall bm_setBones(BundledMesh* s,void*,const Mat4* value,int count) { s->setBoneTransforms(value,count); } -void __fastcall bm_setName(BundledMesh* s,void*,const vc71::string& value) { s->m_name=value; } -void __fastcall bm_uvTranslate(BundledMesh* s,void*,int i,float x,float y) { s->setUvTranslation(i,x,y); } -void __fastcall bm_uvRotate(BundledMesh* s,void*,int i,float angle) { s->setUvRotation(i,angle); } -void __fastcall bm_uvTransform(BundledMesh* s,void*,int i,const Mat4* value) { s->setUvTransformation(i,value); } +void RD9_THUNK bm_draw(BundledMesh* s RD9_THUNK_EDX,void* a,void* b,void* c) { s->draw(a,b,c); } +void RD9_THUNK bm_shadow(BundledMesh* s RD9_THUNK_EDX,void* a,void* b,void* c,void* d,void* e,void* f) { s->drawShadowMap(a,b,c,d,e,f); } +void* RD9_THUNK bm_destroy(void* s RD9_THUNK_EDX,unsigned char flags) { return bundledMeshDestroyFlags(s,flags); } +void RD9_THUNK bm_setPart(BundledMesh* s RD9_THUNK_EDX,const Mat4* value,int part) { s->setPartTransformation(value,part); } +void RD9_THUNK bm_setBones(BundledMesh* s RD9_THUNK_EDX,const Mat4* value,int count) { s->setBoneTransforms(value,count); } +void RD9_THUNK bm_setName(BundledMesh* s RD9_THUNK_EDX,const std::string& value) { s->m_name=value; } +void RD9_THUNK bm_uvTranslate(BundledMesh* s RD9_THUNK_EDX,int i,float x,float y) { s->setUvTranslation(i,x,y); } +void RD9_THUNK bm_uvRotate(BundledMesh* s RD9_THUNK_EDX,int i,float angle) { s->setUvRotation(i,angle); } +void RD9_THUNK bm_uvTransform(BundledMesh* s RD9_THUNK_EDX,int i,const Mat4* value) { s->setUvTransformation(i,value); } // Shared retail bodies: exact callee cleanup confirmed in the instruction census. -void __fastcall bm_empty1(void*,void*,unsigned int) {} -void __fastcall bm_empty2(void*,void*,unsigned int,unsigned int) {} -bool __fastcall bm_false1(void*,void*,unsigned int) { return false; } -bool __fastcall bm_false0(void*,void*) { return false; } -int __fastcall bm_zero0(void*,void*) { return 0; } -int __fastcall bm_zero1(void*,void*,unsigned int) { return 0; } -int __fastcall bm_seven(void*,void*) { return 7; } -void __fastcall bm_stamp(BundledMesh* s,void*) { s->m_visibleFrame=dx9rend::rendererFrameOrdinal(); } +void RD9_THUNK bm_empty1(void* RD9_THUNK_EDX,unsigned int) {} +void RD9_THUNK bm_empty2(void* RD9_THUNK_EDX,unsigned int,unsigned int) {} +bool RD9_THUNK bm_false1(void* RD9_THUNK_EDX,unsigned int) { return false; } +bool RD9_THUNK bm_false0(void* RD9_THUNK_EDX) { return false; } +int RD9_THUNK bm_zero0(void* RD9_THUNK_EDX) { return 0; } +int RD9_THUNK bm_zero1(void* RD9_THUNK_EDX,unsigned int) { return 0; } +int RD9_THUNK bm_seven(void* RD9_THUNK_EDX) { return 7; } +void RD9_THUNK bm_stamp(BundledMesh* s RD9_THUNK_EDX) { s->m_visibleFrame=dx9rend::rendererFrameOrdinal(); } } #define BM_ENTRY(x) reinterpret_cast(&bm_##x) void* const g_bundledMeshVtable[62]={ diff --git a/Code/BF2/Geom/BundledMesh.h b/Code/BF2/Geom/BundledMesh.h index ba6ac5048..1a67e8c5a 100644 --- a/Code/BF2/Geom/BundledMesh.h +++ b/Code/BF2/Geom/BundledMesh.h @@ -4,14 +4,16 @@ #ifndef BF2_GEOM_BUNDLEDMESH_H #define BF2_GEOM_BUNDLEDMESH_H #ifdef BF2_IMAGE_RENDDX9 -#include "../../RendDX9Abi/Vc71String.h" -#include "../../RendDX9Abi/Vc71Vector.h" +#include #include "../Math/Mat4.h" #include "GeometryInstanceData.h" #include "../RendDX9/Ra/RaShader.h" #include +#include -namespace dice { namespace hfe { namespace geom { +namespace dice { namespace hfe { +namespace world { class LightSource; } +namespace geom { class BundledMeshTemplate; class BundledMeshMaterial; struct BundledMeshLod; @@ -68,6 +70,7 @@ class BundledMesh : public GeometryInstanceData void allocatePartTransforms(); void initializeFromTemplate(); void updateHeightOverTerrain(); + void drawSubPartHighlight(unsigned int part); // 101063B0, no callers in 1.50 float animationPhase(const Vec3& camera); unsigned int animationIndex(const Vec3& camera); unsigned int materialFeatures(BundledMeshMaterial* material,bool additive,unsigned int caps); @@ -88,7 +91,7 @@ class BundledMesh : public GeometryInstanceData void* m_heightmapCluster; // +278 Vec2 m_horizontalForward; // +27C BundledMeshLod* m_lodRecord; // +284 - vc71::vector_layout* m_lodMaterials; // +288 vector + std::vector* m_lodMaterials; // +288 the template's selected lod list unsigned int m_geomIndex; // +28C unsigned int m_lodIndex; // +290 int m_animationIndex; // +294 @@ -100,8 +103,8 @@ class BundledMesh : public GeometryInstanceData unsigned int m_shadowCasterFrame; // +2B0 void* m_shadowProjection; // +2B4 void* m_nextGeometry; // +2B8 - vc71::vector_layout m_lights; // +2BC - vc71::vector_layout m_lightRecords; // +2CC dx9rend::Ra::RaLightRecord + std::vector m_lights; // +2BC + std::vector m_lightRecords; // +2CC unsigned char m_castsShadow; // +2DC unsigned char m_animationExplicit; // +2DD unsigned char m_lodExplicit; // +2DE @@ -110,27 +113,8 @@ class BundledMesh : public GeometryInstanceData unsigned int m_heightFrame; // +2E4 float m_shadowFade; // +2E8 unsigned char m_pad2EC[4]; - double m_shadowFadeTime; // +2F0 + double m_shadowFadeTime; // +2F0, retail allocation 0x2F8 (10104D10) }; -static_assert(sizeof(BundledMesh)==0x2F8,"10104D10 allocation"); -#define BF2_BM_OFFSET(member,offset) static_assert(offsetof(BundledMesh,member)==offset,#member) -BF2_BM_OFFSET(m_name,0x4); BF2_BM_OFFSET(m_refCount,0x30); -BF2_BM_OFFSET(m_parameters,0x34); BF2_BM_OFFSET(m_template,0x258); -BF2_BM_OFFSET(m_partTransforms,0x25C); BF2_BM_OFFSET(m_inverseTransform,0x260); -BF2_BM_OFFSET(m_distanceToCamera,0x264); BF2_BM_OFFSET(m_fov,0x268); -BF2_BM_OFFSET(m_heightOverTerrain,0x26C); BF2_BM_OFFSET(m_shadowSunHeight,0x270); -BF2_BM_OFFSET(m_underRoof,0x274); BF2_BM_OFFSET(m_heightmapCluster,0x278); -BF2_BM_OFFSET(m_horizontalForward,0x27C); BF2_BM_OFFSET(m_lodRecord,0x284); -BF2_BM_OFFSET(m_lodMaterials,0x288); BF2_BM_OFFSET(m_geomIndex,0x28C); -BF2_BM_OFFSET(m_lodIndex,0x290); BF2_BM_OFFSET(m_animationIndex,0x294); -BF2_BM_OFFSET(m_shaderLod,0x298); BF2_BM_OFFSET(m_dword29C,0x29C); -BF2_BM_OFFSET(m_uvMatrices,0x2A8); BF2_BM_OFFSET(m_ownerObject,0x2AC); -BF2_BM_OFFSET(m_shadowCasterFrame,0x2B0); BF2_BM_OFFSET(m_shadowProjection,0x2B4); -BF2_BM_OFFSET(m_nextGeometry,0x2B8); BF2_BM_OFFSET(m_lights,0x2BC); -BF2_BM_OFFSET(m_lightRecords,0x2CC); BF2_BM_OFFSET(m_castsShadow,0x2DC); -BF2_BM_OFFSET(m_lodFrame,0x2E0); BF2_BM_OFFSET(m_heightFrame,0x2E4); -BF2_BM_OFFSET(m_shadowFade,0x2E8); BF2_BM_OFFSET(m_shadowFadeTime,0x2F0); -#undef BF2_BM_OFFSET extern void* const g_bundledMeshVtable[62]; const Mat4& bundledMeshZeroMatrix(); // 10079290, shared zero matrix bool bundledMeshTraceAdditive(BundledMesh*,const Vec3& origin,const Vec3& direction, diff --git a/Code/BF2/Geom/BundledMeshDraw.cpp b/Code/BF2/Geom/BundledMeshDraw.cpp index d6fe137ed..37b47826c 100644 --- a/Code/BF2/Geom/BundledMeshDraw.cpp +++ b/Code/BF2/Geom/BundledMeshDraw.cpp @@ -13,9 +13,6 @@ // Match XpLightManager's engine-interface import: retail HfeAbi already supplies // ClassManager's VC7.1 registration carriers. Only the virtual interfaces below // cross this boundary; native STL fields are never read in retail mode. -#if !BF2_PLUGIN_ABI_NATIVE -#define CORE_CLASSMANAGER_H -#endif #include "../Game/Objects/IPlayer.h" #include "../Game/Objects/ICameraObject.h" #include "../Game/Objects/IObject.h" @@ -24,10 +21,9 @@ #include "../Game/Objects/Visual/LightSourceTemplate.h" #include "../Scene/Object/PlayerManager.h" #include "../Scene/Object/ObjectTypes/Game/IPlayerControlObject.h" -#if !BF2_PLUGIN_ABI_NATIVE -#undef CORE_CLASSMANAGER_H -#endif #include "../RendDX9/Texture.h" +#include "../RendDX9/RendDX9Math.h" // the RendDX9.dll Math copies +#include "BoxCorners.h" // worldHeight's eight-corner box #include #include #include @@ -52,6 +48,9 @@ using dx9rend::Ra::RaLightingParameters; template T& field(void* p,unsigned int offset) { return *reinterpret_cast(static_cast(p)+offset); } +// The material's Ra parameter block (material +0x10); the `+0xNN` comments below are the retail +// material offsets the shipped draw writes. +RaMaterialParameters& materialParams(BundledMeshMaterial* m) { return bundledMeshMaterialParameters(m); } template R slot(void* p,unsigned int offset) { typedef R(__thiscall* Fn)(void*); @@ -70,127 +69,32 @@ world::IPlayerControlObject* controlObject(void* object) { void* const found=current->queryInterface(50373u); if(found) return static_cast(found); -#if BF2_PLUGIN_ABI_NATIVE current=current->getParent(); -#else - current=field(current,0x28); -#endif } return 0; } const world::LightSourceTemplate* lightTemplate(world::LightSource* light) { -#if BF2_PLUGIN_ABI_NATIVE return static_cast(light->getTemplate()); -#else - return field(light,0x144); -#endif } float lightRange(world::LightSource* light) { -#if BF2_PLUGIN_ABI_NATIVE return light->getAttenuationRange2(); -#else - return slot(light,0x190); -#endif } const Vec3& lightColor(world::LightSource* light) { -#if BF2_PLUGIN_ABI_NATIVE return light->getColor(); -#else - return slot(light,0x198); -#endif } const Vec3& lightDirection(world::LightSource* light) { -#if BF2_PLUGIN_ABI_NATIVE return light->getDirection(); -#else - return slot(light,0x17C); -#endif } -// 100777A0, including the unit-length early return and zero-length refusal. -void normalize(Vec3& v) -{ - const float lengthSquared=v.x*v.x+v.y*v.y+v.z*v.z; - const double epsilon=1.1920928955078125e-7; - if(std::fabs(lengthSquared-1.0)>=epsilon) - { - if(std::fabs(static_cast(lengthSquared))(lengthSquared)); - v.x=static_cast(scale*v.x); - v.y=static_cast(scale*v.y); - v.z=static_cast(scale*v.z); - } - } -} Vec3 subtract(const Vec3& a,const Vec3& b) { const Vec3 result={a.x-b.x,a.y-b.y,a.z-b.z};return result; } const Vec3& position(const Mat4& m) { return *reinterpret_cast(m.m+12); } void copy3(float* out,const Vec3& value) { std::memcpy(out,&value,sizeof(value)); } -// VC7.1 resize specializations 10106DC0/10102850->10102690. These POD carriers -// retain the vector shape used by the renderer even when hosted by the native EXE. -// The grow policy is the shipped max(required, capacity+capacity/2), from -// shrinking retains the allocation. -void resizePod(vc71::vector_layout& v,unsigned int count,unsigned int stride,bool lights) -{ - const unsigned int old=vc71::vectorSizeIn(v,stride); - const unsigned int capacity=v.first?static_cast(v.end-v.first)/stride:0; - const unsigned int maximum=0xFFFFFFFFu/stride; - if(count>maximum)throw std::length_error("vector too long"); - if(count>capacity) - { - unsigned int next=capacity<=maximum-capacity/2?capacity+capacity/2:0; - if(next(::operator new(next*stride)); - if(old)std::memcpy(data,v.first,old*stride); - if(v.first)::operator delete(v.first); - v.first=data;v.end=data+next*stride; - } - if(count>old) - { - if(lights) - for(unsigned int i=old;i(v.first+i*stride); - std::memset(&record,0,0x38); - // +38 is uninitialized in the shipped default and overwritten by draw. - record.float3C=record.float40=1.0f; - } - else std::memset(v.first+old*stride,0,(count-old)*stride); - } - if(v.first)v.last=v.first+count*stride; -} - -// 10106E40/10106F90, vector assignment. The empty-source case really releases -// its destination allocation; it is not the resize(0) behavior above. -void assignPod(vc71::vector_layout& dest,const vc71::vector_layout& src,unsigned int stride) -{ - if(&dest==&src)return; - const unsigned int count=vc71::vectorSizeIn(src,stride); - if(!count) - { - if(dest.first)::operator delete(dest.first); - dest.first=dest.last=dest.end=0; - return; - } - const unsigned int capacity=dest.first?static_cast(dest.end-dest.first)/stride:0; - if(count>capacity) - { - if(dest.first)::operator delete(dest.first); - dest.first=static_cast(::operator new(count*stride)); - dest.end=dest.first+count*stride; - } - std::memcpy(dest.first,src.first,count*stride); - dest.last=dest.first+count*stride; -} - // typed parameter assignment preserves each holder's own vptr. The // two texture values are COM interfaces (the PE pushes this, then calls stdcall // +8/+4); these are not EngineTexture wrappers or IBase refcount slots. @@ -213,65 +117,44 @@ void copyLighting(RaLightingParameters& dest,const RaLightingParameters& src) dest.matBones.a=src.matBones.a;dest.matBones.b=src.matBones.b; std::memcpy(dest.overGrowthAmbient.value,src.overGrowthAmbient.value,16); std::memcpy(&dest.shadowViewProj.value,&src.shadowViewProj.value,64); - assignPod(dest.shadowViewProjArray.value,src.shadowViewProjArray.value,64); - assignPod(dest.clampViewProjArray.value,src.clampViewProjArray.value,64); - assignPod(dest.shadowPosArray.value,src.shadowPosArray.value,16); - assignPod(dest.shadowSizeArray.value,src.shadowSizeArray.value,16); + // 10106E40/10106F90, vector assignment: an empty source releases the destination's storage. + dx9rend::Ra::raAssignParamBytes(dest.shadowViewProjArray.value,src.shadowViewProjArray.value); + dx9rend::Ra::raAssignParamBytes(dest.clampViewProjArray.value,src.clampViewProjArray.value); + dx9rend::Ra::raAssignParamBytes(dest.shadowPosArray.value,src.shadowPosArray.value); + dx9rend::Ra::raAssignParamBytes(dest.shadowSizeArray.value,src.shadowSizeArray.value); dest.shadowCount.value=src.shadowCount.value; - assignPod(dest.tail0FC,src.tail0FC,16); + dx9rend::Ra::raAssignParamBytes(dest.tail0FC,src.tail0FC); dest.tail10C=src.tail10C; } -// 100CE120 -> 101C6750/101C67F0 -> 101C6C70/101C6E10. The eight corners are -// emitted in x/y/z bit order; maximum/minimum comparisons retain NaN behavior. +// The height of the bounds' world box: the eight-corner box (geom::BoxCorners, BoxCorners.h: +// constructor, maximum, minimum) over the MeshBounds, which is the LocalBoundingBox record, then +// maximum.y - minimum.y. [INFERRED] the caller's inline arithmetic, no retail function of its own. float worldHeight(const MeshBounds& bounds,const Mat4& world) { - Vec3 corners[8]={}; - for(unsigned int i=0;i<8;++i) - { - const float x=(i&4)?bounds.max.x:bounds.min.x; - const float y=(i&2)?bounds.max.y:bounds.min.y; - const float z=(i&1)?bounds.max.z:bounds.min.z; - corners[i].x=i==0?z*world.m[8]+x*world.m[0]+y*world.m[4]+world.m[12] - :world.m[4]*y+z*world.m[8]+x*world.m[0]+world.m[12]; - corners[i].y=i==0?x*world.m[1]+y*world.m[5]+z*world.m[9]+world.m[13] - :x*world.m[1]+z*world.m[9]+y*world.m[5]+world.m[13]; - corners[i].z=z*world.m[10]+x*world.m[2]+y*world.m[6]+world.m[14]; - } - Vec3 maximum=corners[0],minimum=corners[0]; - for(unsigned int i=1;i<8;++i) - { - if(maximum.xcorners[i].x)minimum.x=corners[i].x; - if(minimum.y>corners[i].y)minimum.y=corners[i].y; - if(minimum.z>corners[i].z)minimum.z=corners[i].z; - } - return maximum.y-minimum.y; + const BoxCorners corners(reinterpret_cast(bounds),world); + return corners.maximum().y-corners.minimum().y; } void configureAlpha(BundledMeshMaterial* material,unsigned int mask) { + RaMaterialParameters& p=materialParams(material); if(material->m_kind==2) { - field(material,0x2C)=1; + p.alphaTest.value=1; // +0x2C if(material->m_state->m_alphaTest) { - if(mask&0x400)field(material,0xB4)=15; - else field(material,0x2C)=0; + if(mask&0x400)p.alphaTestRef.value=15; // +0xB4 + else p.alphaTest.value=0; } - else field(material,0xB4)=127; + else p.alphaTestRef.value=127; } else if(material->m_kind==1) { - field(material,0x2C)=1; - field(material,0xB4)=0; - field(material,0x1C)=1; - field(material,0xAC)=1; - field(material,0x24)=0; + p.alphaTest.value=1; + p.alphaTestRef.value=0; + p.alphaBlendEnable.value=1; // +0x1C + p.cullMode.value=1; // +0xAC + p.depthWrite.value=0; // +0x24 } } void setEntry(RenderQueueEntry* entry,BundledMeshMaterial* material,void* object, @@ -282,6 +165,13 @@ void setEntry(RenderQueueEntry* entry,BundledMeshMaterial* material,void* object } } // anonymous namespace +// [CHOSEN, not recovered] Shared source entry for PE 0x10107250, used by the water adapters. +void geometryCopyLightingParameters(RaLightingParameters& destination, const RaLightingParameters& source) +{ + copyLighting(destination, source); +} + +// PE 0x10104F70: the draw. Its three stack arguments are unused (`retn 0xC`). void BundledMesh::draw(void*,void*,void*) { if(!g_bundledMeshStateManager->getEnabled())return; @@ -294,7 +184,7 @@ void BundledMesh::draw(void*,void*,void*) void* const view=slot(dx9rend::g_rendererBase,0x48); const Mat4* const transform=getGeometryTransformation(); const Mat4& camera=slot(view,0x64); - const Vec3 difference=subtract(position(*transform),position(camera)); + const Vec3 difference=rendmath::subtract(position(camera),position(*transform)); // PE 0x1007AFE0 m_distanceToCamera=static_cast(std::sqrt( difference.z*difference.z+difference.y*difference.y+difference.x*difference.x)); std::memcpy(&m_parameters.tail220,&m_distanceToCamera,4); @@ -324,22 +214,25 @@ void BundledMesh::draw(void*,void*,void*) { const Vec2& range=g_LightManager->getShadowSunHeightOverFade(); float u=(m_shadowSunHeight-range.x)/(range.y-range.x); - // 101051BA consumes the clamp's ST0 result at 101051BF..CA. + // PE 0x1000ED40 (called at 101051BA) tests the high bound first and lands an unordered value + // on the low bound; the result is consumed in ST0 at 101051BF..CA. if(u>=1.0f)u=1.0f; - if(u<0.0f)u=0.0f; + if(!(u>=0.0f))u=0.0f; factor=u+(1.0f-u)*sample; } hemiFactor=static_cast(std::pow(static_cast(factor), static_cast(g_LightManager->getShadowSunScalePower()))); } - void* const timer=field(dx9rend::g_Renderer,0x5DC); + void* const timer=dx9rend::rendererFrameTimer(); // +0x5DC + // The timer is a raw 48-byte block of integers and doubles (BF2Render.cpp), so its total time + // sits at +0x20 on every target. const double now=field(timer,0x20); const double elapsed=now-m_shadowFadeTime; m_shadowFadeTime=now; - double fraction=elapsed/field(g_LightManager,0x838); + double fraction=elapsed/lightManagerShadowFadeDuration(g_LightManager); // +0x838 if(fraction>1.0)fraction=1.0; m_shadowFade=static_cast(m_shadowFade+fraction*(fadeTarget-m_shadowFade)); - m_lights.last=m_lights.first; + m_lights.clear(); bool acceptLights=true,staticSun=false; world::ICameraObject* cameraGate=0; @@ -368,15 +261,22 @@ void BundledMesh::draw(void*,void*,void*) const int maximum=g_LightManager->getMaxLightsPerBundledMesh(); g_LightManager->gatherLightsForGeometry(this,m_lights,maximum,required,0,true); } - const unsigned int lightCount=vc71::vectorSizeIn(m_lights,4); - resizePod(m_lightRecords,lightCount,sizeof(RaLightRecord),true); + const unsigned int lightCount=static_cast(m_lights.size()); + { + // 10102850->10102690: new records are zero up to +38 with 1.0f at +3C and +40; +38 is + // uninitialized in the shipped default and overwritten below. + RaLightRecord fill; + std::memset(&fill,0,0x38); + fill.float3C=fill.float40=1.0f; + m_lightRecords.resize(lightCount,fill); + } for(unsigned int i=0;i(m_lights.first)[i]; + world::LightSource* const light=m_lights[i]; float range=lightRange(light); const world::LightSourceTemplate* templ=lightTemplate(light); if(templ && templ->getIsDynamic())range*=g_LightManager->getDynamicLightRangeScale(); - RaLightRecord& record=reinterpret_cast(m_lightRecords.first)[i]; + RaLightRecord& record=m_lightRecords[i]; copy3(record.position,light->getAbsolutePosition()); record.invRangeSq=1.0f/(range*range); Vec3 color=lightColor(light); @@ -429,7 +329,7 @@ void BundledMesh::draw(void*,void*,void*) } } } - const unsigned int materialCount=vc71::vectorSizeIn(*m_lodMaterials,4); + const unsigned int materialCount=static_cast(m_lodMaterials->size()); const Mat4& animationCamera=slot(slot(dx9rend::g_rendererBase,0x50),0x64); const unsigned int animation=animationIndex(position(animationCamera)); const float heightScale=2.0f/worldHeight(m_template->m_bounds,*m_partTransforms[0]); @@ -440,12 +340,12 @@ void BundledMesh::draw(void*,void*,void*) for(unsigned int index=0;index(m_lodMaterials->first)[index]; + BundledMeshMaterial* const material=(*m_lodMaterials)[index]; BundledMeshState* const state=material->m_state; unsigned int mask=materialFeatures(material,false,caps); if(inside && !(mask&0x1000))mask=(mask&~0x100u)|0x200u; - unsigned int quality=field(dx9rend::g_Renderer,0x6CC); - if(field(dx9rend::g_Renderer,0x708) && m_shaderLod>quality)quality=m_shaderLod; + unsigned int quality=dx9rend::rendererRaPath(); // +0x6CC + if(dx9rend::rendererTailByte(0x708) && m_shaderLod>quality)quality=m_shaderLod; const unsigned int qualityMask=bundledMeshQualityMask(quality); mask&=qualityMask;if(!(mask&0x5F))mask|=1; RenderQueueEntry* const entry=dx9rend::renderEntryPoolAcquire(); @@ -460,7 +360,7 @@ void BundledMesh::draw(void*,void*,void*) color.z+(damage.z-color.z)*damagePulse}; copy3(sun->color,blended); sun->scaled24=ambient.z*0.33f+ambient.y*0.33f+ambient.x*0.33f; - copy3(sun->unread28,Vec3::getZero()); + copy3(sun->unread28,rendmath::zeroVector()); // PE 0x1007B1E0 } else { @@ -475,13 +375,15 @@ void BundledMesh::draw(void*,void*,void*) } } configureAlpha(material,mask); - field(material,0x15C)=bundledMeshShaderForBits(mask); - field(material,0x94)=static_cast(m_template->getMaterialValue100( + RaMaterialParameters& params=materialParams(material); + raMaterialShaderSlot(params)=bundledMeshShaderForBits(mask); // +0x15C + params.specularPower.value=static_cast(m_template->getMaterialValue100( // +0x94 m_geomIndex,m_lodIndex,static_cast(index))); if(state->m_envMap) { dx9rend::EngineTexture* const texture=bundledMeshEnvironmentTexture(); - dx9rend::EngineTexture*& old=field(material,0x130); + dx9rend::EngineTexture*& old= // +0x130 + reinterpret_cast(params.cubeMap.value); if(old!=texture) { if(old && --old->refCount==0) @@ -491,24 +393,26 @@ void BundledMesh::draw(void*,void*,void*) } const int lod=getLodIndex(); const int geom=getGeomIndex(); - field(material,0xA4)=m_template->slot_0x44(geom,lod,index); + params.reflectivity.value=m_template->slot_0x44(geom,lod,index); // +0xA4 } if(state->m_feature39) - field(material,0x104)=m_template->getSpecularStaticGloss( + params.staticGloss.value=m_template->getSpecularStaticGloss( // +0x104 m_geomIndex,m_lodIndex,static_cast(index)); unsigned int currentFovBits;std::memcpy(¤tFovBits,&m_fov,4); void* const projectionView=slot(dx9rend::g_rendererBase, currentFovBits==0xBF800000u?0x50:0xD4); - m_parameters.geomBones.a=reinterpret_cast(m_partTransforms); + // A pointer in the holder's first word: RaParamPair must be pointer-sized on x64. + m_parameters.geomBones.a=reinterpret_cast(m_partTransforms); m_parameters.geomBones.b=m_lodRecord->partCount; std::memcpy(&m_parameters.viewProjection.value, &slot(projectionView,0x84),sizeof(Mat4)); if(state->m_animated) { const unsigned int count=m_template->m_dword10C+1; - resizePod(m_parameters.userData.value,count<<6,1,false); + // 10106DC0: resize the byte vector; new bytes are zero-filled. + m_parameters.userData.value.resize(count<<6); for(int i=0;i(count);++i) - std::memcpy(m_parameters.userData.value.first+64*i, + std::memcpy(m_parameters.userData.value.data()+64*i, m_uvMatrices?&m_uvMatrices[i]:&Mat4::getIdentity(),64); } if(castsDynamicShadow()) @@ -516,9 +420,10 @@ void BundledMesh::draw(void*,void*,void*) const unsigned int shadowFrame=frameOrdinal(); if(getShadowCasterFrame()==shadowFrame && m_shadowProjection && !(staticSun && state->m_cockpit)) { - std::memcpy(&m_parameters.shadowProjMat.value,&field(m_shadowProjection,0x2F8),64); - std::memcpy(&m_parameters.shadowTrapMat.value,&field(m_shadowProjection,0x3B8),64); - std::memcpy(&m_parameters.shadowOccProjMat.value,&field(m_shadowProjection,0x338),64); + const LightShadowRecord* const record=static_cast(m_shadowProjection); + std::memcpy(&m_parameters.shadowProjMat.value,&record->matrices[4],64); // +0x2F8 + std::memcpy(&m_parameters.shadowTrapMat.value,&record->matrices[7],64); // +0x3B8 + std::memcpy(&m_parameters.shadowOccProjMat.value,&record->matrices[5],64); // +0x338 } } if(slot(dx9rend::g_Renderer,0xAC)) @@ -529,8 +434,9 @@ void BundledMesh::draw(void*,void*,void*) } else copy3(m_parameters.hemiMapSkyColor.value,g_LightManager->getSkyColor()); configureAlpha(material,mask); // repeated in the shipped draw - field(material,0x114)=heightScale; - setEntry(entry,material,&m_parameters,field(material,0x15C)); + params.invHemiHeightScale.value=heightScale; // +0x114 + setEntry(entry,material,&m_parameters, + static_cast(raMaterialShaderSlot(params))); // +0x15C if(material->m_kind==1) { if(m_template->m_primitiveType==4)entry->lighting.tail10C=3*animation*material->m_primitiveCount; @@ -543,11 +449,11 @@ void BundledMesh::draw(void*,void*,void*) else { Vec3 direction=lightDirection(skyLight); - if(field(dx9rend::g_Renderer,0x69C)) + if(dx9rend::rendererRenderSwitch(0x69C)) { const Mat4& eye=slot(slot(dx9rend::g_Renderer,0x48),0x64); direction=subtract(position(*getGeometryTransformation()),position(eye)); - normalize(direction); + rendmath::normalize(direction); } copy3(sun->direction,direction); } @@ -563,12 +469,12 @@ void BundledMesh::draw(void*,void*,void*) const Vec3 direction=subtract(position(*getGeometryTransformation()),origin); void* hitObject=0; const bool hit=bundledMeshTraceAdditive(this,origin,direction,hitObject); - float& fade=field(this,0x2A0); + float& fade=*reinterpret_cast(&m_dword2A0); // +2A0 if(!hit || hitObject==refreshRootObject())fade=1.0f; else if(fade>epsilon) { - fade=static_cast(fade-field(dx9rend::g_Renderer,0x59C) - *field(dx9rend::g_Renderer,0x5E8)); + fade=static_cast(fade-dx9rend::rendererTailFloat(0x59C) + *dx9rend::rendererTailDouble(0x5E8)); if(fade<0.0f || m_dword2A4+1(view,0x64); Vec3& forward=*reinterpret_cast(m_inverseTransform->m+8); forward.x=-eye.m[8];forward.y=-eye.m[9];forward.z=-eye.m[10]; - normalize(forward); + rendmath::normalize(forward); Vec3 up=*reinterpret_cast(root.m+4); - normalize(up); + rendmath::normalize(up); if(up.z*forward.z+up.y*forward.y+up.x*forward.x>0.99f) - { up=*reinterpret_cast(root.m);normalize(up); } + { up=*reinterpret_cast(root.m);rendmath::normalize(up); } Vec3& right=*reinterpret_cast(m_inverseTransform->m); right.x=up.y*forward.z-up.z*forward.y; right.y=up.z*forward.x-up.x*forward.z; @@ -592,10 +498,10 @@ void BundledMesh::draw(void*,void*,void*) vertical.y=right.x*forward.z-forward.x*right.z; vertical.z=forward.x*right.y-right.x*forward.y; copy3(m_inverseTransform->m+12,position(root)); - m_parameters.geomBones.a=reinterpret_cast(&m_inverseTransform); + m_parameters.geomBones.a=reinterpret_cast(&m_inverseTransform); m_parameters.geomBones.b=1; entry->shader=dx9rend::Ra::getShader( - static_cast(dx9rend::g_renderQueues),vc71::string("BMadditive"),false); + static_cast(dx9rend::g_renderQueues),std::string("BMadditive"),false); dx9rend::renderQueueAddToSlot(10,entry); m_dword2A4=frameOrdinal(); } @@ -621,12 +527,11 @@ void BundledMesh::draw(void*,void*,void*) if(state->m_alphaTest)delta|=0x400;delta|=0x800; delta&=qualityMask;if(!(delta&0x5F))delta|=1; dx9rend::Ra::RaShader* const shader=bundledMeshShaderForBits(delta); - for(unsigned int i=0;i(lit->lightArray.lights.value)= - reinterpret_cast(m_lightRecords.first)[i]; + *static_cast(lit->lightArray.lights.value)=m_lightRecords[i]; copyLighting(lit->lighting,entry->lighting); dx9rend::renderQueueEnqueue(lit,transparent,firstPerson,true); } diff --git a/Code/BF2/Geom/BundledMeshHeight.cpp b/Code/BF2/Geom/BundledMeshHeight.cpp index ecd7cf263..381214ad7 100644 --- a/Code/BF2/Geom/BundledMeshHeight.cpp +++ b/Code/BF2/Geom/BundledMeshHeight.cpp @@ -6,20 +6,12 @@ #include "BundledMeshTemplate.h" #include "StaticMesh.h" #include "XpLightManager.h" -#if !BF2_PLUGIN_ABI_NATIVE -#define CORE_IBASE_H -#define CORE_CLASSMANAGER_H -#endif #include "../Game/Objects/IObject.h" #include "../Game/Objects/IPlayer.h" #include "../Game/Objects/ObjectLayoutAccess.h" #include "../Scene/Object/ObjectManager.h" #include "../Scene/Object/ObjectPredicator.h" #include "../Scene/Object/PlayerManager.h" -#if !BF2_PLUGIN_ABI_NATIVE -#undef CORE_CLASSMANAGER_H -#undef CORE_IBASE_H -#endif namespace dice { namespace hfe { extern IBase* objectManager; @@ -45,6 +37,7 @@ const Vec3& meshPosition(const BundledMesh* mesh) class BundledRootIgnorePredicator : public world::ObjectPredicator { public: + // PE 0x101069D0 virtual bool predicate(world::IObject* object) { return staticMeshRootParent(object) != root; } virtual unsigned int getFlags() const { return 0; } @@ -72,6 +65,7 @@ class BundledAdditivePredicator : public world::ObjectPredicator { public: // The owner rejection precedes root/player and geometry tests. + // PE 0x10106A20 virtual bool predicate(world::IObject* object) { if (owner == object) @@ -109,6 +103,7 @@ class BundledAdditivePredicator : public world::ObjectPredicator }; } // anonymous namespace +// PE 0x10104160: height over terrain, shadow-sun height and the under-roof probe. void BundledMesh::updateHeightOverTerrain() { if (!m_heightmapCluster || !m_ownerObject) diff --git a/Code/BF2/Geom/BundledMeshMaterial.cpp b/Code/BF2/Geom/BundledMeshMaterial.cpp index 5e26f8306..e56af5b20 100644 --- a/Code/BF2/Geom/BundledMeshMaterial.cpp +++ b/Code/BF2/Geom/BundledMeshMaterial.cpp @@ -1,9 +1,11 @@ // Material ctor/apply/dtor are attested to Geom/BundledMeshTemplate.cpp. // [INFERRED] split TU, kept beside its recovered owner. BF2 1.50 PE only. #ifdef BF2_IMAGE_RENDDX9 +#include "../../RendDX9Abi/ThunkAbi.h" #include "BundledMeshMaterial.h" #include "BundledMeshTemplate.h" #include "../RendDX9/Ra/RaShader.h" +#include "../../RendDX9Abi/BfMemory.h" #include "../../RendDX9Abi/EngineFile.h" #include "../../RendDX9Abi/Frontier.h" #include @@ -12,25 +14,15 @@ namespace dice { namespace hfe { namespace geom { namespace { namespace Ra = ::dice::hfe::dx9rend::Ra; -void destroyMapNodes(BundledMeshMapNode* node) +void pushDescriptor(BundledMeshMaterial::ElementList& v, const Ra::RaVertexElementDesc* value) { - while (!node->isNil) - { - destroyMapNodes(node->right); - BundledMeshMapNode* const left = node->left; - ::renddx9abi::engineFree(node); - node = left; - } -} -void pushDescriptor(vc71::vector_layout& v, const Ra::RaVertexElementDesc* value) -{ - vc71::vectorRef(&v).push_back(value); + v.push_back(value); } // off_101E2428 is the real abstract material base: one deleting destructor and // eight _purecall slots, read fresh alongside100ED400. These are retail pure slots. extern "C" int __cdecl _purecall(void); -void* __fastcall destroyedMaterialDestroy(void* self, void*, unsigned char flags); +void* RD9_THUNK destroyedMaterialDestroy(void* self RD9_THUNK_EDX, unsigned char flags); void* const kDestroyedMaterialTable[] = { reinterpret_cast(&destroyedMaterialDestroy), reinterpret_cast(&_purecall), reinterpret_cast(&_purecall), @@ -38,7 +30,7 @@ void* const kDestroyedMaterialTable[] = { reinterpret_cast(&_purecall), reinterpret_cast(&_purecall), reinterpret_cast(&_purecall), reinterpret_cast(&_purecall) }; -void* __fastcall destroyedMaterialDestroy(void* self, void*, unsigned char flags) +void* RD9_THUNK destroyedMaterialDestroy(void* self RD9_THUNK_EDX, unsigned char flags) { *static_cast(self) = kDestroyedMaterialTable; if (flags & 1) ::renddx9abi::engineFree(self); @@ -46,96 +38,22 @@ void* __fastcall destroyedMaterialDestroy(void* self, void*, unsigned char flags } } -// The container operations preserve source-level map semantics and the proven -// 24-byte ABI. Tree balancing is the existing RW-74 chosen-container policy. -void bundledMeshMapConstruct(vc71::map_layout& map) -{ - BundledMeshMapNode* n = static_cast(::renddx9abi::engineAlloc(24)); - if (n) n->left = 0; - if (reinterpret_cast(n) != 0xFFFFFFFCu) n->parent = 0; - if (reinterpret_cast(n) != 0xFFFFFFF8u) n->right = 0; - n->color = 1; - n->isNil = 0; - map.head = reinterpret_cast(n); - n->isNil = 1; - n->left = n->parent = n->right = n; - map.size = 0; -} -BundledMeshMapNode* bundledMeshMapFind(const vc71::map_layout& map, unsigned int key) -{ - BundledMeshMapNode* const head = reinterpret_cast(map.head); - BundledMeshMapNode* best = head; - for (BundledMeshMapNode* n = head->parent; !n->isNil; ) - { - if (n->key >= key) { best = n; n = n->left; } - else n = n->right; - } - return best == head || key < best->key ? head : best; -} -unsigned int& bundledMeshMapAt(vc71::map_layout& map, unsigned int key) -{ - BundledMeshMapNode* const head = reinterpret_cast(map.head); - BundledMeshMapNode* found = bundledMeshMapFind(map, key); - if (found != head) return found->value; - BundledMeshMapNode* parent = head; - BundledMeshMapNode* cursor = head->parent; - bool left = true; - while (!cursor->isNil) - { - parent = cursor; - left = key < cursor->key; - cursor = left ? cursor->left : cursor->right; - } - BundledMeshMapNode* n = static_cast(::renddx9abi::engineAlloc(24)); - n->left = n->right = head; - n->parent = parent; - n->key = key; - n->value = 0; - n->color = 0; - n->isNil = 0; - if (parent == head) head->left = head->right = head->parent = n; - else if (left) - { - parent->left = n; - if (parent == head->left) head->left = n; - } - else - { - parent->right = n; - if (parent == head->right) head->right = n; - } - ++map.size; - return n->value; -} -void bundledMeshMapDestroy(vc71::map_layout& map) +// The abstract material table restored by all three mesh-material destructors (PE 0x101E2428). +void* const* materialDestroyedVtable() { - BundledMeshMapNode* head = reinterpret_cast(map.head); - destroyMapNodes(head->parent); - ::renddx9abi::engineFree(head); - map.head = 0; - map.size = 0; + return kDestroyedMaterialTable; } -BundledMeshMapNode* bundledMeshMapNext(BundledMeshMapNode* n) + +// Run the shared base destructor without freeing its storage (PE 0x10048C40, flags=0). +void materialRestoreBaseVtable(void* material) { - if (!n->isNil) - { - if (!n->right->isNil) - { - n = n->right; - while (!n->left->isNil) n = n->left; - } - else - { - BundledMeshMapNode* parent = n->parent; - while (!parent->isNil && n == parent->right) { n = parent; parent = parent->parent; } - n = parent; - } - } - return n; + destroyedMaterialDestroy(material RD9_THUNK_ARG, 0); } //Descriptor selection is ordered, and the two template virtual queries // are unconditional. Missing tangent support logs the shipped diagnostic. +// The element list and the declaration map (head node 0x100493C0) are default-constructed empty. +// PE 0x100E9520: the descriptor addresses, their order and the line 111 diagnostic follow the listing. BundledMeshMaterial::BundledMeshMaterial(BundledMeshTemplate* templ, bool hasUv1, bool hasTangent) { m_dword04 = 0; @@ -146,8 +64,6 @@ BundledMeshMaterial::BundledMeshMaterial(BundledMeshTemplate* templ, bool hasUv1 m_vertexStart = m_indexStart = m_primitiveCount = m_vertexCount = m_primitiveType = 0; m_vertexBuffer = m_indexBuffer = 0; m_vertexStride = 0; - m_elements.first = m_elements.last = m_elements.end = 0; - bundledMeshMapConstruct(m_declarations); const bool compressed = m_template->getCompressVertexData(); const bool normal16 = m_template->slot_0x84(); pushDescriptor(m_elements, compressed ? &Ra::g_desc_1023ED9C : &Ra::g_desc_1023EF04); @@ -166,29 +82,35 @@ BundledMeshMaterial::BundledMeshMaterial(BundledMeshTemplate* templ, bool hasUv1 //100ED400, then100ED3D0's deleting flag. The state is released by the template, // before invoking this body; the material destructor itself does not release it. +// The containers are emptied at their shipped points; their storage goes with their own +// destructors after this body. +BundledMeshMaterial::~BundledMeshMaterial() +{ + destroyMembers(); +} void BundledMeshMaterial::destroyMembers() { - bundledMeshMapDestroy(m_declarations); - if (m_elements.first) ::renddx9abi::engineFree(m_elements.first); - m_elements.first = m_elements.last = m_elements.end = 0; + m_declarations.clear(); + m_elements.clear(); Ra::raMaterialParametersDestroy(m_parameters); *reinterpret_cast(this) = kDestroyedMaterialTable; } void* BundledMeshMaterial::destroy(unsigned char flags) { - destroyMembers(); + this->~BundledMeshMaterial(); if (flags & 1) ::renddx9abi::engineFree(this); return this; } //starvation refuses before inserting. Bind order is stream, declaration, // indices. Declarations belong to the process-wide cache and are not released here. +// PE 0x100E9840 (starvation diagnostic is BundledMeshTemplate.cpp line 137) bool BundledMeshMaterial::applyStreams(void* shaderState) { Ra::RaShader* const shader = static_cast(shaderState); const unsigned int key = static_cast(shader->m_buildSerial); - BundledMeshMapNode* node = bundledMeshMapFind(m_declarations, key); - if (node == reinterpret_cast(m_declarations.head)) + DeclarationMap::iterator node = m_declarations.find(key); + if (node == m_declarations.end()) { Ra::RaStreamRequirements* required = Ra::raStreamRequirementsCreate(shader->m_requiredVertexElements); Ra::RaDeclarationBuilder builder; @@ -205,14 +127,14 @@ bool BundledMeshMaterial::applyStreams(void* shaderState) Ra::raStreamRequirementsDestroy(required); return false; } - bundledMeshMapAt(m_declarations, key) = reinterpret_cast( - Ra::raVertexDeclarationCached(Ra::raDeclarationBuilderFinish(builder), Ra::raRendererDevice())); - node = bundledMeshMapFind(m_declarations, key); + m_declarations[key] = + Ra::raVertexDeclarationCached(Ra::raDeclarationBuilderFinish(builder), Ra::raRendererDevice()); + node = m_declarations.find(key); Ra::raDeclarationBuilderDestroy(builder); Ra::raStreamRequirementsDestroy(required); } dx9rend::stateManagerSetStreamSource(0, static_cast(m_vertexBuffer), 0, m_vertexStride); - dx9rend::stateManagerSetVertexDeclaration(reinterpret_cast(node->value)); + dx9rend::stateManagerSetVertexDeclaration(node->second); dx9rend::stateManagerSetIndices(static_cast(m_indexBuffer)); return true; } diff --git a/Code/BF2/Geom/BundledMeshMaterial.h b/Code/BF2/Geom/BundledMeshMaterial.h index 94a405c27..6ec8af01d 100644 --- a/Code/BF2/Geom/BundledMeshMaterial.h +++ b/Code/BF2/Geom/BundledMeshMaterial.h @@ -3,30 +3,26 @@ #ifndef BF2_GEOM_BUNDLEDMESHMATERIAL_H #define BF2_GEOM_BUNDLEDMESHMATERIAL_H #ifdef BF2_IMAGE_RENDDX9 -#include "../../RendDX9Abi/Vc71Vector.h" -#include "../../RendDX9Abi/Vc71Map.h" +#include "MeshTemplate.h" // RaMaterialParameters #include -namespace dice { namespace hfe { namespace geom { +#include +#include +struct IDirect3DVertexDeclaration9; +namespace dice { namespace hfe { +namespace dx9rend { namespace Ra { struct RaVertexElementDesc; } } // RendDX9/Ra/RaShader.h +namespace geom { class BundledMeshTemplate; class BundledMeshState; -// The 24-byte unsigned-key node shared by this material's declaration map and the -// template's value maps. Allocators100493C0/100EB100 prove the flags at+14/+15. -struct BundledMeshMapNode -{ - BundledMeshMapNode *left, *parent, *right; - unsigned int key, value; - unsigned char color, isNil, pad[2]; -}; -static_assert(sizeof(BundledMeshMapNode)==24, "Bundled map node"); -void bundledMeshMapConstruct(vc71::map_layout& map); -BundledMeshMapNode* bundledMeshMapFind(const vc71::map_layout& map, unsigned int key); -unsigned int& bundledMeshMapAt(vc71::map_layout& map, unsigned int key); -void bundledMeshMapDestroy(vc71::map_layout& map); -BundledMeshMapNode* bundledMeshMapNext(BundledMeshMapNode* node); +// Retail allocation 0x1A0; the declaration map's 24-byte nodes come from 0x100493C0. class BundledMeshMaterial { public: + typedef std::vector ElementList; + typedef std::map DeclarationMap; + BundledMeshMaterial(BundledMeshTemplate* templ, bool hasUv1, bool hasTangent); + // The destructor body runs destroyMembers; destroy(flags) runs the destructor. + ~BundledMeshMaterial(); void destroyMembers(); virtual void* destroy(unsigned char flags); virtual bool applyStreams(void* shader); @@ -40,7 +36,8 @@ class BundledMeshMaterial unsigned int m_dword04; // +004 BundledMeshTemplate* m_template; // +008 BundledMeshState* m_state; // +00C - unsigned char m_parameters[0x150]; // +010 Ra material block + // +010 Ra material block (RaMaterialParameters; 0x150 bytes on x86) + alignas(RaMaterialParameters) unsigned char m_parameters[sizeof(RaMaterialParameters)]; int m_kind; // +160 unsigned int m_vertexStart; // +164 unsigned int m_indexStart; // +168 @@ -50,13 +47,16 @@ class BundledMeshMaterial void* m_vertexBuffer; // +178 native D3D handle unsigned int m_vertexStride; // +17C void* m_indexBuffer; // +180 native D3D handle - vc71::vector_layout m_elements; // +184 RaVertexElementDesc* - vc71::map_layout m_declarations; // +194 shader build serial -> declaration + ElementList m_elements; // +184 + DeclarationMap m_declarations; // +194 shader build serial -> declaration }; -static_assert(sizeof(BundledMeshMaterial)==0x1A0, "material allocation"); +#if defined(_M_IX86) static_assert(offsetof(BundledMeshMaterial,m_parameters)==0x10, "material parameters"); static_assert(offsetof(BundledMeshMaterial,m_kind)==0x160, "material kind"); -static_assert(offsetof(BundledMeshMaterial,m_declarations)==0x194, "declaration map"); +#endif +// The material's Ra parameter block, typed. +inline RaMaterialParameters& bundledMeshMaterialParameters(BundledMeshMaterial* material) +{ return *reinterpret_cast(material->m_parameters); } } } } #endif #endif diff --git a/Code/BF2/Geom/BundledMeshOptimizer.cpp b/Code/BF2/Geom/BundledMeshOptimizer.cpp new file mode 100644 index 000000000..abe14bdf4 --- /dev/null +++ b/Code/BF2/Geom/BundledMeshOptimizer.cpp @@ -0,0 +1,339 @@ +// Path: [INFERRED] Code/BF2/Geom/BundledMeshOptimizer.cpp, by analogy with the attested +// StaticMeshOptimizer.cpp (RendDX9 0x1021D290); no __FILE__ string names this file. +// Contents: dice.hfe.geom.GeometryOptimizer.BundledMeshOptimizer, recovered from RendDX9.dll +// (PE, symbols stripped). Primary table 0x1021D208, 0x134 bytes, factory 0x100B08D4. + +#ifdef BF2_IMAGE_RENDDX9 + +#include "MeshOptimizer.h" + +#include "../RendDX9/RendDX9Base.h" +#include "../IO/Stream/IStream.h" +#include "../../RendDX9Abi/BfMemory.h" +#include + +#include +#include +#include +#include + +namespace dice { +namespace hfe { + +namespace dx9rend { +extern void* g_rendererBase; // dword_1023B970 +IDirect3DVertexDeclaration9* vertexDeclarationD3D(void* wrapper); // BufferManager.cpp +} // namespace dx9rend + +namespace geom { + +namespace { + +// Reflection class id at 0x1021AF0C (Core/Ids.h geom::CID_BundledMeshOptimizer). +const unsigned int kClassId = 0x870CAA39u; + +const unsigned long kLockNoSysLock = 0x800u; // D3DLOCK_NOSYSLOCK +const unsigned int kMeshOptVertexCache = 0x04000000u; // D3DXMESHOPT_VERTEXCACHE +const unsigned int kMeshOptStripReorder = 0x08000000u; // D3DXMESHOPT_STRIPREORDER +const unsigned int kMeshSystemMem = 0x110u; // D3DXMESH_SYSTEMMEM +const unsigned int kMeshIbManaged = 0x200u; // D3DXMESH_IB_MANAGED + +IDirect3DDevice9* rendererDevice() +{ + return static_cast(dx9rend::g_rendererBase)->device; +} + +// The 0x40000-byte stack array optimizeMeshes hands to GenerateAdjacency. +// [CHOSEN, not recovered] memory safety: it lives on the heap and grows to three entries per face +// when a LOD has more faces than the shipped array holds. +std::vector adjacencyBuffer(unsigned int faceCount) +{ + const unsigned int shipped = 0x10000u; + return std::vector(faceCount * 3 > shipped ? faceCount * 3 : shipped); +} + +class BundledMeshOptimizer : public MeshOptimizer +{ +public: + BundledMeshOptimizer(); + ~BundledMeshOptimizer() override; + + void addRef() override; // +0x00 0x10134EB0 + int getRef() override; // +0x04 0x10138220 + int release() override; // +0x08 0x10134EC0 + unsigned int getClassId() const override; // +0x10 0x10134EA0 + bool optimize() override; // +0x14 0x10132A00 + bool optimizeFile(const std::string& path) override; // +0x18 0x10133240 + bool readHeader(renddx9abi::HostStream* stream) override; // +0x24 0x10132A10 + void readGeometry(renddx9abi::HostStream* stream) override; // +0x34 0x101336C0 + bool buildMeshes() override; // +0x40 0x10132A40 + void optimizeMeshes() override; // +0x44 0x10133350 + void writeGeometry(renddx9abi::HostStream* stream) override; // +0x4C 0x10133170 + +private: + // The class's own IBase count; the base's +0x04 count stays at 1. + int m_classRefCount; // +0x114 + unsigned int m_unused118; // +0x118 [CHOSEN, not recovered] name; never accessed + unsigned int m_unused11C; // +0x11C [CHOSEN, not recovered] name; never accessed + unsigned int m_stripIndexCount; // +0x120 + std::vector > m_geometryLods; // +0x124 [geometry][lod] +}; + +// PE 0x101335D0. The folder strings are assigned again after the base constructor. +// [CHOSEN, not recovered] the two unused dwords start at zero; retail leaves them unset. +BundledMeshOptimizer::BundledMeshOptimizer() + : m_classRefCount(1), m_unused118(0), m_unused11C(0), m_stripIndexCount(0) +{ + m_shaderFolder = std::string("Shaders/"); + m_meshFolder = std::string("Meshes/"); +} + +// PE 0x10133660 (deleting form 0x10134EE0). The strip buffers held in the LOD records are not +// released. +BundledMeshOptimizer::~BundledMeshOptimizer() +{ +} + +// PE 0x10134EB0 +void BundledMeshOptimizer::addRef() +{ + ++m_classRefCount; +} + +// PE 0x10138220 +int BundledMeshOptimizer::getRef() +{ + return m_classRefCount; +} + +// PE 0x10134EC0. The last release runs the virtual deleting destructor. +int BundledMeshOptimizer::release() +{ + const int remaining = --m_classRefCount; + if (!remaining) + delete this; + return remaining; +} + +// PE 0x10134EA0 +unsigned int BundledMeshOptimizer::getClassId() const +{ + return kClassId; +} + +// PE 0x10132A00, `xor al, al`. +bool BundledMeshOptimizer::optimize() +{ + return false; +} + +// PE 0x10133240 +bool BundledMeshOptimizer::optimizeFile(const std::string& path) +{ + const bool result = MeshOptimizer::optimizeFile(path); + releaseLodMeshes(); + return result; +} + +// PE 0x10132A10. A bundled mesh needs version 5 or later. +bool BundledMeshOptimizer::readHeader(renddx9abi::HostStream* stream) +{ + const bool result = MeshOptimizer::readHeader(stream); + if (m_head == 0 && m_version <= 4) + return false; + return result; +} + +// PE 0x101336C0. Per LOD: the bounds (the 36-byte form before version 10), then the node count. +void BundledMeshOptimizer::readGeometry(renddx9abi::HostStream* stream) +{ + const unsigned int geometryCount = static_cast(m_lodCounts.size()); + m_geometryLods.resize(geometryCount, std::vector()); + for (unsigned int geometry = 0; geometry < geometryCount; ++geometry) + { + const unsigned int lodCount = m_lodCounts[geometry]; + m_geometryLods[geometry].resize(lodCount, BundledMeshOptimizerLod()); + for (unsigned int lodIndex = 0; lodIndex < lodCount; ++lodIndex) + { + BundledMeshOptimizerLod& lod = m_geometryLods[geometry][lodIndex]; + if (m_head == 0 && m_version < 10) + meshBoundsReadLegacy(lod.bounds, stream); + else + meshBoundsReadMinMax(lod.bounds, stream); + stream->read(&lod.nodeCount, 4); + } + } +} + +// PE 0x10132A40. One system-memory D3DX mesh per LOD from the LOD's vertex and index ranges, with +// one attribute per material. A LOD without materials or with alpha mode 1 refuses the file. The +// D3DX results are not checked. +bool BundledMeshOptimizer::buildMeshes() +{ + D3DVERTEXELEMENT9 elements[256]; + UINT elementCount; + dx9rend::vertexDeclarationD3D(m_vertexDeclaration)->GetDeclaration(elements, &elementCount); + + const unsigned int geometryCount = static_cast(m_lodCounts.size()); + for (unsigned int geometry = 0; geometry < geometryCount; ++geometry) + { + const unsigned int lodCount = m_lodCounts[geometry]; + for (unsigned int lodIndex = 0; lodIndex < lodCount; ++lodIndex) + { + MeshOptimizerMaterialVector& materials = m_materials[geometry][lodIndex]; + MeshOptimizerLod& lod = m_lods[geometry][lodIndex]; + if (materials.empty()) + return false; + lod.materialCount = static_cast(materials.size()); + if (lod.alphaMode == 1) + return false; + + unsigned int indexSum = 0; + unsigned int vertexSum = 0; + for (unsigned int index = 0; index < lod.materialCount; ++index) + { + indexSum += materials[index].indexCount; + vertexSum += materials[index].vertexCount; + } + const unsigned int faceCount = indexSum / 3; + D3DXCreateMesh(faceCount, vertexSum, kMeshSystemMem, elements, rendererDevice(), + &lod.mesh); + + void* vertices; + lod.mesh->LockVertexBuffer(kLockNoSysLock, &vertices); + if (m_vertexData) + std::memcpy(vertices, m_vertexData + materials[0].vertexStart * m_vertexStride, + m_vertexStride * vertexSum); + lod.mesh->UnlockVertexBuffer(); + + void* indices; + lod.mesh->LockIndexBuffer(kLockNoSysLock, &indices); + if (m_indexData) + std::memcpy(indices, m_indexData + materials[0].indexStart, faceCount * 3 * 2); + lod.mesh->UnlockIndexBuffer(); + + DWORD* attributes; + lod.mesh->LockAttributeBuffer(kLockNoSysLock, &attributes); + unsigned int face = 0; + unsigned int end = 0; + for (unsigned int index = 0; index < lod.materialCount; ++index) + { + end += materials[index].indexCount / 3; + for (; face < end; ++face) + attributes[face] = index; + } + lod.mesh->UnlockAttributeBuffer(); + } + } + return true; +} + +// PE 0x10133350. Per LOD: rebase each material's indices onto the LOD's first vertex start (only +// for triangle lists), generate adjacency, vertex-cache optimize into a second mesh and, when the +// flags ask for strip reordering, convert every material subset to one strip. Ends with the +// shared repack. A LOD with alpha mode 1 and one material returns before the repack. +void BundledMeshOptimizer::optimizeMeshes() +{ + m_optimizeFlags = kMeshOptVertexCache; + const unsigned int geometryCount = static_cast(m_lodCounts.size()); + for (unsigned int geometry = 0; geometry < geometryCount; ++geometry) + { + const unsigned int lodCount = m_lodCounts[geometry]; + for (unsigned int lodIndex = 0; lodIndex < lodCount; ++lodIndex) + { + BundledMeshOptimizerLod& record = m_geometryLods[geometry][lodIndex]; + MeshOptimizerLod& lod = m_lods[geometry][lodIndex]; + MeshOptimizerMaterialVector& materials = m_materials[geometry][lodIndex]; + if (lod.alphaMode == 1 && lod.materialCount == 1) + return; + + void* locked; + lod.mesh->LockIndexBuffer(kLockNoSysLock, &locked); + unsigned short* const indices = static_cast(locked); + const unsigned int baseVertex = materials[0].vertexStart; + unsigned int position = 0; + unsigned int end = 0; + unsigned int indexSum = 0; + for (unsigned int index = 0; index < lod.materialCount; ++index) + { + indexSum += materials[index].indexCount; + if (m_primitiveType == 4) + end += materials[index].indexCount; + for (; position < end; ++position) + indices[position] = static_cast( + indices[position] + static_cast( + materials[index].vertexStart - baseVertex)); + } + lod.mesh->UnlockIndexBuffer(); + + std::vector adjacency = adjacencyBuffer(indexSum / 3); + lod.mesh->GenerateAdjacency(0.0f, &adjacency[0]); + lod.optimizeFlags = m_optimizeFlags; + if (lod.alphaMode == 1) + lod.optimizeFlags = kMeshOptVertexCache; + lod.mesh->Optimize(lod.optimizeFlags | kMeshSystemMem, &adjacency[0], 0, 0, 0, + &lod.optimizedMesh); + + if (lod.optimizeFlags == kMeshOptStripReorder) + { + // Dead in 1.50: m_optimizeFlags only ever holds the vertex-cache flag. + void* unused; + lod.optimizedMesh->LockIndexBuffer(kLockNoSysLock, &unused); // shipped: never read or unlocked + record.strips.resize(lod.materialCount, 0); + DWORD stripIndexCount = 0; + for (unsigned int index = 0; index < lod.materialCount; ++index) + { + D3DXConvertMeshSubsetToSingleStrip(lod.optimizedMesh, index, kMeshIbManaged, + &record.strips[index], &stripIndexCount); + m_primitiveType = 5; + materials[index].indexCount = stripIndexCount; + m_stripIndexCount += stripIndexCount; + } + } + } + } + repackBuffers(m_stripIndexCount, m_geometryLods); +} + +// PE 0x10133170. The base tables, the index tail, then per LOD the bounds through the defective +// 36-byte writer and the node count. The repacked vertex and index arrays are freed afterwards and +// the pointers kept. +void BundledMeshOptimizer::writeGeometry(renddx9abi::HostStream* stream) +{ + MeshOptimizer::writeGeometry(stream); + stream->write(&m_u2, 4); + const unsigned int geometryCount = static_cast(m_lodCounts.size()); + for (unsigned int geometry = 0; geometry < geometryCount; ++geometry) + { + const unsigned int lodCount = m_lodCounts[geometry]; + for (unsigned int lodIndex = 0; lodIndex < lodCount; ++lodIndex) + { + BundledMeshOptimizerLod& lod = m_geometryLods[geometry][lodIndex]; + meshBoundsWriteLegacy(lod.bounds, stream); + stream->write(&lod.nodeCount, 4); + } + } + delete[] m_vertexData; + delete[] m_indexData; +} + +} // anonymous namespace + +// PE 0x100B08D4 +IBase* __fastcall createBundledMeshOptimizer(unsigned int iid, IBase* outer) +{ + if (outer) + return 0; + void* const storage = ::renddx9abi::engineAlloc(sizeof(BundledMeshOptimizer)); + BundledMeshOptimizer* const self = storage ? new (storage) BundledMeshOptimizer() : 0; + IBase* const result = static_cast(self->queryInterface(iid)); + if (!result) + self->release(); + return result; +} + +} // namespace geom +} // namespace hfe +} // namespace dice + +#endif // BF2_IMAGE_RENDDX9 diff --git a/Code/BF2/Geom/BundledMeshStateManager.cpp b/Code/BF2/Geom/BundledMeshStateManager.cpp index 3f8251d6d..19cf4438b 100644 --- a/Code/BF2/Geom/BundledMeshStateManager.cpp +++ b/Code/BF2/Geom/BundledMeshStateManager.cpp @@ -6,39 +6,23 @@ #include "../../RendDX9Abi/BfMemory.h" #include "../../RendDX9Abi/Frontier.h" #include "../RendDX9/Texture.h" +#include #include #include #include namespace dice { namespace hfe { namespace dx9rend { -extern IBase* g_Renderer; -void pathToLower(vc71::string& value); -void* textureManagerGetTexture(const vc71::string& name); +void pathToLower(std::string& value); +void* textureManagerGetTexture(const std::string& name); +unsigned int rendererRaPath(); // BF2Render.cpp - the Renderer's +0x6CC shader path } namespace geom { BundledMeshStateManager* g_bundledMeshStateManager = 0; namespace { -unsigned int pointerCount(const vc71::vector_layout& v) -{ - return v.first ? static_cast((v.last - v.first) / 4) : 0; -} - -// Both callers resize a newly constructed vector, with zero as the fill value -// (0x101930AB and 0x101934A6 -> 0x100EBAD0). The allocator word remains untouched. -void resizeEmptyTextureVector(vc71::vector_layout& v, unsigned int count) -{ - if (count) - { - v.first = static_cast(::operator new(count * sizeof(void*))); - std::memset(v.first, 0, count * sizeof(void*)); - v.last = v.end = v.first + count * sizeof(void*); - } -} - -bool contains(const vc71::string& value, const char* needle) +bool contains(const std::string& value, const char* needle) { return std::strstr(value.c_str(), needle) != 0; } @@ -53,23 +37,31 @@ void addTextureReference(dx9rend::EngineTexture* texture) } } +// PE 0x10192F00 BundledMeshState::BundledMeshState() : m_refCount(1) { - // Inlined in 0x10192FF0 at 0x10192FFF and 0x10193455. - m_textures.first = m_textures.last = m_textures.end = 0; - m_animated = m_normalMap = m_extraMap = m_envMap = m_colorMapGloss = 0; - m_feature39 = m_alphaTest = m_alphaOne = m_cockpit = m_noHemiLight = 0; + // Inlined in 0x10192FF0 at 0x10192FFF and 0x10193455. m_textures is default-constructed empty. + m_animated = 0; + m_normalMap = 0; + m_extraMap = 0; + m_envMap = 0; + m_colorMapGloss = 0; + m_feature39 = 0; + m_alphaTest = 0; + m_alphaOne = 0; + m_cockpit = 0; + m_noHemiLight = 0; } BundledMeshState::~BundledMeshState() { // release each texture, unlink from the global cache, free vector, - // then destroy the name. The singleton dereference deliberately has no guard. - const unsigned int count = pointerCount(m_textures); + // then destroy the name. The singleton dereference deliberately has no guard. The vector and + // then the name are freed by their member destructors, in that order. + const unsigned int count = static_cast(m_textures.size()); for (unsigned int i = 0; i < count; ++i) { - dx9rend::EngineTexture* const texture = - reinterpret_cast(m_textures.first)[i]; + dx9rend::EngineTexture* const texture = m_textures[i]; if (texture && --texture->refCount == 0) { dx9rend::textureDtor(texture); @@ -77,9 +69,6 @@ BundledMeshState::~BundledMeshState() } } g_bundledMeshStateManager->remove(this); - if (m_textures.first) - ::renddx9abi::engineFree(m_textures.first); - m_textures.first = m_textures.last = m_textures.end = 0; } void BundledMeshState::addRef() { ++m_refCount; } @@ -103,11 +92,12 @@ void* BundledMeshState::destroy(unsigned char flags) return this; } +// PE 0x10192BF0 void BundledMeshState::deriveFeatures() { // lower a copy only. Feature derivation does not canonicalize the // name used by the case-sensitive cache, and only raises bytes already zeroed. - vc71::string lowered(m_name); + std::string lowered(m_name); dx9rend::pathToLower(lowered); if (contains(lowered, "animated")) m_animated = 1; if (contains(lowered, "envmap")) m_envMap = 1; @@ -119,32 +109,28 @@ void BundledMeshState::deriveFeatures() if (contains(lowered, "nohemilight")) m_noHemiLight = 1; } +// PE 0x10192DF0 BundledMeshStateManager::BundledMeshStateManager() : m_refCount(1) { - m_cache.first = m_cache.last = m_cache.end = 0; - new (&m_texturePrefix) vc71::string(); + // m_cache is default-constructed empty; the prefix lives in a union and is built here. + new (&m_texturePrefix) std::string(); m_enabled = m_enabled9 = 1; - m_texturePrefix = "Textures/"; + const std::string prefix("Textures/"); + m_texturePrefix = prefix; } BundledMeshStateManager::~BundledMeshStateManager() { // the cache does NOT own state references. Retail repeatedly erases - // its first pointer, then destroys the string, then frees the vector allocation. - char* const first = m_cache.first; - while (first != m_cache.last) - { - std::memmove(first, first + 4, m_cache.last - (first + 4)); - m_cache.last -= 4; - } - m_texturePrefix.~string(); - if (m_cache.first) - ::renddx9abi::engineFree(m_cache.first); - m_cache.first = m_cache.last = m_cache.end = 0; + // its first pointer, then destroys the string, then frees the vector allocation - the last + // with m_cache's own destructor, after this body. + m_cache.clear(); + m_texturePrefix.~basic_string(); } void BundledMeshStateManager::addRef() { ++m_refCount; } int BundledMeshStateManager::getRef() { return m_refCount; } +// PE 0x10193830 int BundledMeshStateManager::release() { const int remaining = --m_refCount; @@ -162,24 +148,24 @@ void* BundledMeshStateManager::queryInterface(unsigned int iid) const void BundledMeshStateManager::setEnabled(bool enabled) { m_enabled = enabled; } bool BundledMeshStateManager::getEnabled() const { return m_enabled != 0; } +// PE 0x10192D10 BundledMeshState* BundledMeshStateManager::find(const BundledMeshState& state) const { // identity is name and texture pointers, not the derived flags. - const unsigned int count = pointerCount(m_cache); + const unsigned int count = static_cast(m_cache.size()); for (unsigned int i = 0; i < count; ++i) { - BundledMeshState* const candidate = reinterpret_cast(m_cache.first)[i]; + BundledMeshState* const candidate = m_cache[i]; if (candidate->m_name.size() != state.m_name.size() || std::memcmp(candidate->m_name.c_str(), state.m_name.c_str(), state.m_name.size()) != 0) continue; - const unsigned int textures = pointerCount(candidate->m_textures); - if (textures != pointerCount(state.m_textures)) + const unsigned int textures = static_cast(candidate->m_textures.size()); + if (textures != state.m_textures.size()) continue; bool same = true; for (unsigned int j = 0; j < textures; ++j) { - if (reinterpret_cast(candidate->m_textures.first)[j] != - reinterpret_cast(state.m_textures.first)[j]) + if (candidate->m_textures[j] != state.m_textures[j]) same = false; } if (same) @@ -188,28 +174,20 @@ BundledMeshState* BundledMeshStateManager::find(const BundledMeshState& state) c return 0; } +// PE 0x10192EB0 void BundledMeshStateManager::remove(const BundledMeshState* state) { - char* cursor = m_cache.first; - if (cursor == m_cache.last) - return; - char* next = cursor + 4; - do + for (std::vector::iterator it = m_cache.begin(); it != m_cache.end();) { - if (*reinterpret_cast(cursor) == state) - { - std::memmove(cursor, next, m_cache.last - next); - m_cache.last -= 4; - } + if (*it == state) + it = m_cache.erase(it); else - { - cursor += 4; - next += 4; - } - } while (cursor != m_cache.last); + ++it; + } } -BundledMeshState* BundledMeshStateManager::read(void* effect, const vc71::string& templatePath, +// PE 0x10192FF0 +BundledMeshState* BundledMeshStateManager::read(void* effect, const std::string& templatePath, ::renddx9abi::HostNonlinearStream* stream, bool arg4, bool skipTextures) { (void)effect; // The retail first argument is never read. @@ -224,7 +202,7 @@ BundledMeshState* BundledMeshStateManager::read(void* effect, const vc71::string int mapCount; stream->read(&mapCount, 4); - resizeEmptyTextureVector(temp.m_textures, static_cast(mapCount)); + temp.m_textures.resize(static_cast(mapCount), 0); // 0x101930AB -> 0x100EBAD0 for (int i = 0; i < mapCount; ++i) { stream->read(&length, 4); @@ -233,8 +211,8 @@ BundledMeshState* BundledMeshStateManager::read(void* effect, const vc71::string raw = static_cast(::renddx9abi::engineAlloc(length + 1)); stream->read(raw, length); raw[length] = 0; - vc71::string prefix; - vc71::string mapName(raw); + std::string prefix; + std::string mapName(raw); if (!contains(mapName, "/")) { prefix = templatePath; @@ -250,12 +228,13 @@ BundledMeshState* BundledMeshStateManager::read(void* effect, const vc71::string mapName = "@@ABSOLUTE@@Common/Textures/SpecularLUT_pow36.dds"; if (!skipTextures && - (*reinterpret_cast(reinterpret_cast(dx9rend::g_Renderer) + 0x6CC) == 0 || + (dx9rend::rendererRaPath() == 0 || // Renderer +0x6CC !contains(mapName, "_b.dds"))) { - vc71::string full(prefix); + std::string full(prefix); full += mapName; - reinterpret_cast(temp.m_textures.first)[i] = dx9rend::textureManagerGetTexture(full); + temp.m_textures[i] = + static_cast(dx9rend::textureManagerGetTexture(full)); const std::string original(raw); // Preserve the unsigned size()-6 comparison, including its short-name quirk. if (i == 1 && original.rfind("_b.dds") == original.size() - 6u) @@ -268,10 +247,11 @@ BundledMeshState* BundledMeshStateManager::read(void* effect, const vc71::string else { // This path deliberately ignores skipTextures and the shader-quality gate. - vc71::string full(templatePath); + std::string full(templatePath); full += m_texturePrefix; full += "default"; - reinterpret_cast(temp.m_textures.first)[i] = dx9rend::textureManagerGetTexture(full); + temp.m_textures[i] = + static_cast(dx9rend::textureManagerGetTexture(full)); } } temp.deriveFeatures(); @@ -285,12 +265,11 @@ BundledMeshState* BundledMeshStateManager::read(void* effect, const vc71::string BundledMeshState* const fresh = storage ? new (storage) BundledMeshState() : 0; // Retail dereferences null on allocation failure; no invented success/guard. fresh->m_name = temp.m_name; - resizeEmptyTextureVector(fresh->m_textures, static_cast(mapCount)); + fresh->m_textures.resize(static_cast(mapCount), 0); // 0x101934A6 -> 0x100EBAD0 for (int i = 0; i < mapCount; ++i) { - dx9rend::EngineTexture* const texture = - reinterpret_cast(temp.m_textures.first)[i]; - reinterpret_cast(fresh->m_textures.first)[i] = texture; + dx9rend::EngineTexture* const texture = temp.m_textures[i]; + fresh->m_textures[i] = texture; if (texture) addTextureReference(texture); } @@ -299,11 +278,11 @@ BundledMeshState* BundledMeshStateManager::read(void* effect, const vc71::string { // 0x1019352E..0x1019356A only increments a dead local after the vectors // have already been sized. It does NOT add an environment texture slot. - vc71::string lowered(temp.m_name); + std::string lowered(temp.m_name); dx9rend::pathToLower(lowered); if (contains(lowered, "envmap")) ++mapCount; } - vc71::vectorRef(&m_cache).push_back(fresh); + m_cache.push_back(fresh); return fresh; } diff --git a/Code/BF2/Geom/BundledMeshStateManager.h b/Code/BF2/Geom/BundledMeshStateManager.h index adf1c4ec1..a345323bf 100644 --- a/Code/BF2/Geom/BundledMeshStateManager.h +++ b/Code/BF2/Geom/BundledMeshStateManager.h @@ -6,17 +6,21 @@ #ifdef BF2_IMAGE_RENDDX9 #include "../../RendDX9Abi/HfeAbi.h" #include "../../RendDX9Abi/HostFileAbi.h" -#include "../../RendDX9Abi/Vc71String.h" -#include "../../RendDX9Abi/Vc71Vector.h" +#include #include +#include -namespace dice { namespace hfe { namespace geom { +namespace dice { namespace hfe { +namespace dx9rend { struct EngineTexture; } // RendDX9/Texture.h +namespace geom { -// off_10220C94: IBase, then scalar deleting destructor. Allocation is 0x40. +// off_10220C94: IBase, then scalar deleting destructor. Retail allocation is 0x40. // Field names are inferred from the feature tests in 0x10192BF0 and their draw consumers. class BundledMeshState : public IBase { public: + typedef std::vector TextureList; + BundledMeshState(); ~BundledMeshState(); // 0x10192F50, nonvirtual virtual void addRef(); @@ -28,8 +32,8 @@ class BundledMeshState : public IBase void deriveFeatures(); int m_refCount; // +04 - vc71::string m_name; // +08 - vc71::vector_layout m_textures; // +24, EngineTexture* + std::string m_name; // +08 + TextureList m_textures; // +24 unsigned char m_animated; // +34 unsigned char m_normalMap; // +35, texture 1 ends in _b.dds unsigned char m_extraMap; // +36, extra non-SpecularLUT texture @@ -43,7 +47,7 @@ class BundledMeshState : public IBase unsigned char m_padding3E[2]; // untouched by ctor }; -// off_10220C7C: the complete six-slot manager table, allocation 0x38. +// off_10220C7C: the complete six-slot manager table, retail allocation 0x38. class BundledMeshStateManager : public IBase { public: @@ -57,7 +61,7 @@ class BundledMeshStateManager : public IBase virtual bool getEnabled() const; // Wrapper 0x101935E0 -> body 0x10192FF0. The effect argument is never read. - BundledMeshState* read(void* effect, const vc71::string& templatePath, + BundledMeshState* read(void* effect, const std::string& templatePath, ::renddx9abi::HostNonlinearStream* stream, bool arg4, bool skipTextures); BundledMeshState* find(const BundledMeshState& state) const; @@ -67,17 +71,11 @@ class BundledMeshStateManager : public IBase unsigned char m_enabled; // +08 unsigned char m_enabled9; // +09, draw's second-pass gate unsigned char m_padding0A[2]; // untouched by ctor - vc71::vector_layout m_cache; // +0C, non-owning State* cache + std::vector m_cache; // +0C, non-owning State* cache // Explicit lifetime preserves the retail destructor's string-before-vector-buffer order. - union { vc71::string m_texturePrefix; }; // +1C + union { std::string m_texturePrefix; }; // +1C }; -static_assert(sizeof(BundledMeshState) == 0x40, "Bundled state allocation"); -static_assert(offsetof(BundledMeshState, m_textures) == 0x24, "Bundled texture vector"); -static_assert(offsetof(BundledMeshState, m_animated) == 0x34, "Bundled feature block"); -static_assert(sizeof(BundledMeshStateManager) == 0x38, "Bundled manager allocation"); -static_assert(offsetof(BundledMeshStateManager, m_texturePrefix) == 0x1C, "Bundled prefix"); - extern BundledMeshStateManager* g_bundledMeshStateManager; // dword_102597F4 // Template ctor 0x100EA631 and dtor 0x100EA828 own the singleton references. void bundledMeshStateManagerRetain(); diff --git a/Code/BF2/Geom/BundledMeshTemplate.cpp b/Code/BF2/Geom/BundledMeshTemplate.cpp index 6260619ed..70370de95 100644 --- a/Code/BF2/Geom/BundledMeshTemplate.cpp +++ b/Code/BF2/Geom/BundledMeshTemplate.cpp @@ -1,9 +1,11 @@ // attested: Geom/BundledMeshTemplate.cpp, RendDX9.dll1.50 string1021A3C8. // PE-only renderer recovery. Addresses identify the instruction-read witnesses. -// VC7.1 container ABI adapters retain the existing RW-74 balancing policy. +// The template's containers are std containers (issue #7); retail layouts are in the header comments. #ifdef BF2_IMAGE_RENDDX9 #define NOMINMAX #include "BundledMeshTemplate.h" +#include "../RendDX9/RendDX9Math.h" // rendmath::unitScale (sub_1007B220) +#include "BundledMesh.h" #include "BundledMeshMaterial.h" #include "BundledMeshStateManager.h" #include "../../RendDX9Abi/BfMemory.h" @@ -14,6 +16,7 @@ #include "../RendDX9/Texture.h" #include "../RendDX9/Ra/RaShader.h" #include "../IO/Stream/IStream.h" +#include "../GeomMisc/Debug.h" #include #include #include @@ -31,133 +34,93 @@ extern void* g_deviceCaps; extern void* g_renderQueues; extern void* g_bufferManager; extern float g_materialCapScale, g_materialCapBias, g_materialCapC, g_materialCapD; -void* createVertexBuffer(void*,unsigned int,unsigned int,const vc71::string&,unsigned int); +void* createVertexBuffer(void*,unsigned int,unsigned int,const std::string&,unsigned int); void* vertexBufferLock(void*,unsigned int,unsigned int,unsigned int); bool vertexBufferUnlock(void*); +// BufferManager.cpp - the wrapper fields (+0x08 D3D object, +0x20 desc.Size, +0x28 stride). +unsigned int vertexBufferStride(void* wrapper); +unsigned int vertexBufferByteSize(void* wrapper); +IDirect3DVertexBuffer9* vertexBufferD3D(void* wrapper); +IDirect3DIndexBuffer9* indexBufferD3D(void* wrapper); +IDirect3DVertexDeclaration9* vertexDeclarationD3D(void* wrapper); unsigned int rendererFrameOrdinal(); } namespace geom { extern unsigned char g_bundledMeshTechniquesPending; extern dx9rend::Effect* g_bundledShadowEffect; -bool meshBuildTechniqueMasks(const vc71::string&,const vc71::string&,const char* const*, - std::map&,vc71::vector_layout&); +bool meshBuildTechniqueMasks(const std::string&,const std::string&,const char* const*, + std::map&,std::vector&); namespace { -template unsigned int count(const vc71::vector_layout& v) -{ return v.first ? static_cast((v.last-v.first)/sizeof(T)) : 0; } -template T* data(vc71::vector_layout& v) { return reinterpret_cast(v.first); } -template const T* data(const vc71::vector_layout& v) { return reinterpret_cast(v.first); } -void initialize(vc71::vector_layout& v) { v.first=v.last=v.end=0; } -void dispose(vc71::vector_layout& v) -{ if(v.first) ::renddx9abi::engineFree(v.first); v.first=v.last=v.end=0; } -// Source-level vector resize. Records here are trivially relocatable; nested vector -// contents are explicitly destroyed by their owner, matching the PE's instantiations. -template void resize(vc71::vector_layout& v,unsigned int n,const T& value) -{ - const unsigned int old=count(v); - if(n<=old) { v.last=v.first+n*sizeof(T); return; } - const unsigned int maximum=0xFFFFFFFFu/sizeof(T); - if(n>maximum) throw std::length_error("vector too long"); - const unsigned int capacity=v.first?static_cast((v.end-v.first)/sizeof(T)):0; - if(n>capacity) - { - unsigned int next=maximum-(capacity>>1)>=capacity?capacity+(capacity>>1):0; - if(next(::renddx9abi::engineAlloc(next*sizeof(T))); - if(old) std::memcpy(p,v.first,old*sizeof(T)); - if(v.first) ::renddx9abi::engineFree(v.first); - v.first=p; v.end=p+next*sizeof(T); - } - for(unsigned int i=old;i(static_cast(g))<<16) | (static_cast(static_cast(l))<<8) | m; } float asFloat(unsigned int v) { float f; std::memcpy(&f,&v,4); return f; } unsigned int asBits(float v) { unsigned int i; std::memcpy(&i,&v,4); return i; } -vc71::vector_layout& materials(BundledMeshTemplate* t,int g,int l) -{ return data(data(t->m_materials)[g])[l]; } -int rendererInt(unsigned int offset) -{ return *reinterpret_cast(reinterpret_cast(dx9rend::g_Renderer)+offset); } -void constructSet(vc71::set_layout& s) //100EB000, comparator/key/padding untouched -{ - vc71::set_node* p=static_cast(::renddx9abi::engineAlloc(20)); - if(p) p->left=0; - if(reinterpret_cast(p)!=0xFFFFFFFCu) p->parent=0; - if(reinterpret_cast(p)!=0xFFFFFFF8u) p->right=0; - p->color=1; p->isNil=0; - s.head=p; s.size=0; p->isNil=1; p->parent=p; p->left=p; p->right=p; -} +BundledMeshTemplate::MaterialList& materials(BundledMeshTemplate* t,int g,int l) +{ return t->m_materials[g][l]; } + std::map g_techniques; -struct QualityMasks -{ - vc71::vector_layout values; - QualityMasks() { initialize(values); } - ~QualityMasks() { dispose(values); } //free first, clear all three pointers -} g_qualityMaskOwner; -vc71::vector_layout& g_qualityMasks=g_qualityMaskOwner.values; +std::vector g_qualityMasks; //static teardown frees it at exit const char* const kBits[]={"nothing","hasuvanimation","hasnormalmap","hasgimap", "hasenvmap","hascockpit","usehemimap","hasshadow","hascolormapgloss", "hasstaticgloss","hasdot3alphatest","pointlight","hasshadowocclusion", "hashemiocclusion",0}; -template T& materialField(BundledMeshMaterial* m,unsigned int offset) -{ return *reinterpret_cast(reinterpret_cast(m)+offset); } -void assignTexture(BundledMeshMaterial* m,unsigned int offset,dx9rend::EngineTexture* texture) +// One texture holder's value in the material's Ra parameter block (material +0x10). +void assignTexture(RaMaterialParameters::Texture& holder,dx9rend::EngineTexture* texture) { - dx9rend::EngineTexture*& slot=materialField(m,offset); + dx9rend::EngineTexture*& slot=reinterpret_cast(holder.value); if(slot!=texture) { dx9rend::textureReleaseRef(slot); slot=texture; if(texture) dx9rend::textureAddRef(texture); } } } //The constructor deliberately leaves allocator/comparator words, //padding, the file-header fields and +1F4 untouched. +// The material tree, the instance set (head node 100EB000), the three value maps (head nodes +// 0x100EB100) and the geom vector are default-constructed empty. +// PE 0x100EA460 BundledMeshTemplate::BundledMeshTemplate() : MeshTemplate(),m_refCount(1) { - initialize(m_materials); constructSet(m_instances); - bundledMeshMapConstruct(m_materialValues0E8); bundledMeshMapConstruct(m_map0F4); - bundledMeshMapConstruct(m_map100); m_dword10C=0; initialize(m_geoms); + m_dword10C=0; m_maxPartCount=0; m_hasOpaqueMaterials=0; m_byte125=0; m_hasEnvironmentMap=0; m_compressVertexData=1; m_byte192=0; m_maxTextureRepeat=16; m_byte198=0; m_byte199=0; zeroBounds(m_bounds); - m_compressScale=unitScale(); m_decompressScale=unitScale(); m_uvDecompress=1; + m_compressScale=rendmath::unitScale(); m_decompressScale=rendmath::unitScale(); m_uvDecompress=1; m_liveInstanceCount=0; bundledMeshStateManagerRetain(); m_keepData=0; for(unsigned int i=0;i<26;++i) m_partBounds[i]=0; } //states belong to the template, material destruction does not release them. +//The storage is freed afterwards without a C++ destructor, so the std members are destroyed +//explicitly, in the shipped order. +// PE 0x100EA710 void BundledMeshTemplate::destroyMembers() { - for(unsigned int g=0;g(m_lodCounts);++g) - for(int l=0;l(m_lodCounts)[g];++l) + const unsigned int geomCount=static_cast(m_lodCounts.size()); + for(unsigned int g=0;g(m_lodCounts[g]); + for(unsigned int l=0;l(v);++i) + MaterialList& v=materials(this,g,l); + const unsigned int materialCount=static_cast(v.size()); + for(unsigned int i=0;i(v)[i]; + BundledMeshMaterial* m=v[i]; if(m->m_state) m->m_state->release(); - if(m) m->destroy(1); + if(v[i]) v[i]->destroy(1); } } + } for(unsigned int i=0;i<26;++i) if(m_partBounds[i]) ::renddx9abi::engineFree(m_partBounds[i]); bundledMeshStateManagerRelease(); - for(unsigned int i=0;i(m_geoms);++i) - { dispose(data(m_geoms)[i].lods); dispose(data(m_geoms)[i].distances); } - dispose(m_geoms); bundledMeshMapDestroy(m_map100); bundledMeshMapDestroy(m_map0F4); - bundledMeshMapDestroy(m_materialValues0E8); m_instances.destroy(); - for(unsigned int g=0;g(m_materials);++g) - { - vc71::vector_layout& v=data(m_materials)[g]; - for(unsigned int l=0;l(v);++l) dispose(data(v)[l]); - dispose(v); - } - dispose(m_materials); MeshTemplate::destroyMembers(); + m_geoms.~GeomVector(); m_map100.~ValueMap(); m_map0F4.~ValueMap(); + m_materialValues0E8.~ValueMap(); m_instances.~InstanceSet(); + m_materials.~MaterialTree(); MeshTemplate::destroyMembers(); } void* BundledMeshTemplate::destroy(unsigned char flags) { destroyMembers(); if(flags&1) ::renddx9abi::engineFree(this); return this; } @@ -166,166 +129,178 @@ int BundledMeshTemplate::getRef() { return m_refCount; } int BundledMeshTemplate::release() { int n=--m_refCount; if(!n) destroy(1); return n; } unsigned int BundledMeshTemplate::getClassId() const { return 0x870CA651; } -void BundledMeshTemplate::setName(const vc71::string& n) { m_name=n; } +void BundledMeshTemplate::setName(const std::string& n) { m_name=n; } // PE 0x100E76D0 (tail-jumps to basic_string::operator=) IBase* __fastcall createBundledMeshTemplate(unsigned int iid,IBase* outer) { if(outer) return 0; - void* p=::renddx9abi::engineAlloc(0x1FC); + void* p=::renddx9abi::engineAlloc(sizeof(BundledMeshTemplate)); //retail 0x1FC BundledMeshTemplate* t=p?new(p) BundledMeshTemplate:0; IBase* result=static_cast(t->queryInterface(iid)); if(!result) t->release(); return result; } +// PE 0x100E9040 void* BundledMeshTemplate::createInstance() { - void* storage=::renddx9abi::engineAlloc(0x2F8); + void* storage=::renddx9abi::engineAlloc(sizeof(BundledMesh)); //retail 0x2F8 void* instance=storage?bundledMeshConstruct(storage,this):0; - if(m_loaded || (m_instances.insert(reinterpret_cast(instance)),m_loaded) + if(m_loaded || (m_instances.insert(static_cast(instance)),m_loaded) || dx9rend::resourceManagerIsReady() || load()) { ++m_liveInstanceCount; m_keepData=1; return instance; } - vc71::setEraseValue(m_instances,instance); + m_instances.erase(static_cast(instance)); if(instance) bundledMeshDestroyFlags(instance,1); return 0; } +// PE 0x100E8290 (the 'Cannot load BundledMesh' diagnostic is BundledMeshTemplate.cpp line 269) bool BundledMeshTemplate::load() { if(m_loaded) return false; - vc71::string a(m_path); a+="Meshes/"; a+=m_name; a+=".bundledMesh"; - vc71::string b(m_path); b+="Meshes/"; b+=m_name; b+=".bundledMesh"; + std::string a(m_path); a+="Meshes/"; a+=m_name; a+=".bundledMesh"; + std::string b(m_path); b+="Meshes/"; b+=m_name; b+=".bundledMesh"; renddx9abi::HostFileManager* files=::dice::hfe::fileManager; if(!files->fileExists(renddx9abi::makeHostString(a))) { renddx9abi::logf("BundledMeshTemplate.cpp:269: Cannot load BundledMesh %s Please make sure it exists!",a.c_str()); return false; } - const vc71::string& path=files->fileExists(renddx9abi::makeHostString(b))?b:a; + const std::string& path=files->fileExists(renddx9abi::makeHostString(b))?b:a; renddx9abi::HostStream* stream=files->open(renddx9abi::makeHostString(path), static_cast(2),static_cast(0),0); if(!stream) return false; bool ok=loadFromStream(static_cast(stream)); stream->release(); if(!ok) return false; m_loaded=1; - for(vc71::set_node* n=m_instances.head->left;n!=m_instances.head;n=vc71::set_layout::next(n)) - bundledMeshInitTemplate(reinterpret_cast(n->key)); + for(InstanceSet::const_iterator n=m_instances.begin();n!=m_instances.end();++n) + bundledMeshInitTemplate(*n); return true; } +// PE 0x100E9CF0 (diagnostic lines 312, 320, 328) void BundledMeshTemplate::setLodDistance(int g,int l,float distance) { if(g<0||l<0||distance<0) { renddx9abi::logf("BundledMeshTemplate.cpp:312: Negative subgeometry, lod or distance"); return; } - if(count(m_geoms)) + if(!m_geoms.empty()) { - if(static_cast(g)>=count(m_geoms)) + if(static_cast(g)>=m_geoms.size()) { renddx9abi::logf("BundledMeshTemplate.cpp:320: Invalid Subgeometry"); return; } - vc71::vector_layout& distances=data(m_geoms)[g].distances; - int skip=data(m_geomInts)[g]; - if(l>=skip+static_cast(count(distances))) + std::vector& distances=m_geoms[g].distances; + int skip=m_geomInts[g]; + if(l>=skip+static_cast(distances.size())) { renddx9abi::logf("BundledMeshTemplate.cpp:328: Invalid lodSwitch"); return; } - if(l>=skip) data(distances)[l-skip]=distance; + if(l>=skip) distances[l-skip]=distance; } else { - if(count(m_lodDistances)<=static_cast(g)) - resize(m_lodDistances,g+1,emptyVector()); - vc71::vector_layout& v=data(m_lodDistances)[g]; - if(count(v)<=static_cast(l)) resize(v,l+1,0.0f); - data(v)[l]=distance; + if(m_lodDistances.size()<=static_cast(g)) + m_lodDistances.resize(g+1); + std::vector& v=m_lodDistances[g]; + if(v.size()<=static_cast(l)) v.resize(l+1,0.0f); + v[l]=distance; } } +// PE 0x100E8540 float BundledMeshTemplate::getLodDistance(int g,int l) -{ return count(m_geoms)?data(data(m_geoms)[g].distances)[l]:-1.0f; } +{ return !m_geoms.empty()?m_geoms[g].distances[l]:-1.0f; } +// PE 0x100E90E0 void BundledMeshTemplate::slot_0x40(int g,int l,int m,int bits) -{ bundledMeshMapAt(m_materialValues0E8,packedKey(g,l,static_cast(m)))=bits; } +{ m_materialValues0E8[packedKey(g,l,static_cast(m))]=bits; } +// PE 0x100E9160 float BundledMeshTemplate::slot_0x44(int g,int l,int m) { - BundledMeshMapNode* n=bundledMeshMapFind(m_materialValues0E8,packedKey(g,l,static_cast(m))); - return n==reinterpret_cast(m_materialValues0E8.head)?0.25f:asFloat(n->value); + ValueMap::const_iterator n=m_materialValues0E8.find(packedKey(g,l,static_cast(m))); + return n==m_materialValues0E8.end()?0.25f:asFloat(n->second); } void BundledMeshTemplate::setSpecularStaticGloss(int g,int l,unsigned char m,float v) -{ bundledMeshMapAt(m_map0F4,packedKey(g,l,m))=asBits(v); } +{ m_map0F4[packedKey(g,l,m)]=asBits(v); } float BundledMeshTemplate::getSpecularStaticGloss(int g,int l,unsigned char m) { - BundledMeshMapNode* n=bundledMeshMapFind(m_map0F4,packedKey(g,l,m)); - return n==reinterpret_cast(m_map0F4.head)?0.15000001f:asFloat(n->value); + ValueMap::const_iterator n=m_map0F4.find(packedKey(g,l,m)); + return n==m_map0F4.end()?0.15000001f:asFloat(n->second); } void BundledMeshTemplate::setMaterialValue100(int g,int l,unsigned char m,int v) -{ bundledMeshMapAt(m_map100,packedKey(g,l,m))=v; } +{ m_map100[packedKey(g,l,m)]=v; } int BundledMeshTemplate::getMaterialValue100(int g,int l,unsigned char m) { - BundledMeshMapNode* n=bundledMeshMapFind(m_map100,packedKey(g,l,m)); - return n==reinterpret_cast(m_map100.head)?64:static_cast(n->value); + ValueMap::const_iterator n=m_map100.find(packedKey(g,l,m)); + return n==m_map100.end()?64:static_cast(n->second); } void BundledMeshTemplate::slot_0x48(int v) { m_byte125=static_cast(v); } bool BundledMeshTemplate::slot_0x4C() { return m_byte125!=0; } -void BundledMeshTemplate::setCompressVertexData(bool v) { m_compressVertexData=v; } +void BundledMeshTemplate::setCompressVertexData(bool v) { m_compressVertexData=v; } // PE 0x100EE990 (byte +0x191; getter 0x100EE9A0) bool BundledMeshTemplate::getCompressVertexData() const { return m_compressVertexData!=0; } -void BundledMeshTemplate::slot_0x80(int v) { m_byte192=static_cast(v); } +void BundledMeshTemplate::slot_0x80(int v) { m_byte192=static_cast(v); } // PE 0x100EE9B0 (byte +0x192; getter 0x100EE9C0) bool BundledMeshTemplate::slot_0x84() { return m_byte192!=0; } void BundledMeshTemplate::setMaxTextureRepeat(int v) { m_maxTextureRepeat=v; } int BundledMeshTemplate::getMaxTextureRepeat() const { return m_maxTextureRepeat; } void BundledMeshTemplate::slot_0x90(int v) { m_byte198=static_cast(v); } bool BundledMeshTemplate::slot_0x94() { return m_byte198!=0; } -void BundledMeshTemplate::slot_0x98(int v) { m_byte199=static_cast(v); } +void BundledMeshTemplate::slot_0x98(int v) { m_byte199=static_cast(v); } // PE 0x100EE9F0 (byte +0x199; getter 0x100EEA00) bool BundledMeshTemplate::slot_0x9C() { return m_byte199!=0; } +// PE 0x100E80A0 int BundledMeshTemplate::getPrimitiveCount(int g,int l,int m) { - vc71::vector_layout& v=materials(this,g,l); - if(m!=-1) return data(v)[m]->getPrimitiveCount(); - int result=0; for(unsigned int i=0;i(v);++i) result+=data(v)[i]->getPrimitiveCount(); + MaterialList& v=materials(this,g,l); + if(m!=-1) return v[m]->getPrimitiveCount(); + int result=0; for(unsigned int i=0;igetPrimitiveCount(); return result; } +// PE 0x100E89A0 (the all-geometry arm re-enters the virtual slot +0x5C) int BundledMeshTemplate::getVertexCount(int g,int l,int m) { int result=0; if(g==-1&&l==-1) { - for(unsigned int i=0;i(m_lodCounts);++i) - for(int j=0;j(m_lodCounts)[i];++j) result+=getVertexCount(i,j,-1); + for(unsigned int i=0;i(v)[m]->getVertexCount(); - for(unsigned int i=0;i(v);++i) result+=data(v)[i]->getVertexCount(); + MaterialList& v=materials(this,g,l); + if(m!=-1) return v[m]->getVertexCount(); + for(unsigned int i=0;igetVertexCount(); return result; } +// PE 0x100E8120 int BundledMeshTemplate::getMaterialCount(unsigned int l) { - int result=0; for(unsigned int g=0;g(m_geoms);++g) - if(l(data(m_geoms)[g].lods)) result+=count(materials(this,g,l)); + int result=0; for(unsigned int g=0;g(materials(this,g,l).size()); return result; } +// PE 0x100E81D0 int BundledMeshTemplate::getLodPrimitiveCount(unsigned int l) { - int result=0; for(unsigned int g=0;g(m_geoms);++g) - if(l(data(m_geoms)[g].lods)) + int result=0; for(unsigned int g=0;g(v);++i) result+=data(v)[i]->getPrimitiveCount(); + MaterialList& v=materials(this,g,l); + for(unsigned int i=0;igetPrimitiveCount(); } return result; } +// PE 0x100E9A60 (retail collects the textures in a pointer-keyed map; only the key set is read) unsigned int BundledMeshTemplate::getMemoryUsage(int mask) { if(mask==-1) { unsigned int result=getMemoryUsage(1); result+=getMemoryUsage(2); result+=getMemoryUsage(4); return result; } if((mask&8)&&m_indexBuffer) return m_indexCount/3; - if((mask&1)&&m_vertexBuffer) return *reinterpret_cast(static_cast(m_vertexBuffer)+32); + if((mask&1)&&m_vertexBuffer) return dx9rend::vertexBufferByteSize(m_vertexBuffer); // wrapper +0x20 if((mask&2)&&m_indexBuffer) return 2*m_indexCount; if(mask&4) { std::set textures; - for(unsigned int g=0;g(m_geoms);++g) - for(unsigned int l=0;l(data(m_geoms)[g].lods);++l) + for(unsigned int g=0;g(v);++m) + MaterialList& v=materials(this,g,l); + for(unsigned int m=0;m(v)[m]->m_state->m_textures; - for(unsigned int i=0;i(t);++i) - if(data(t)[i]) textures.insert(data(t)[i]); + const BundledMeshState::TextureList& t=v[m]->m_state->m_textures; + for(unsigned int i=0;itotalBytes; return result; } return 0; } +// PE 0x100E7FA0 Vec3* BundledMeshTemplate::decompressPosition(Vec3* out,const Vec3* in) { const float y=in->y*m_compressScale.y,z=in->z*m_compressScale.z; @@ -335,23 +310,24 @@ Vec3* BundledMeshTemplate::decompressPosition(Vec3* out,const Vec3* in) out->x=qx*m_decompressScale.x; out->y=qy*m_decompressScale.y; out->z=qz*m_decompressScale.z; return out; } +// PE 0x100E9380 void BundledMeshTemplate::releaseDeviceResources() //actually preloads { static std::vector textures; textures.clear(); if(m_vertexBuffer) - { IDirect3DResource9* r=*reinterpret_cast(static_cast(m_vertexBuffer)+8); if(r) r->PreLoad(); } + { IDirect3DResource9* r=dx9rend::vertexBufferD3D(m_vertexBuffer); if(r) r->PreLoad(); } // wrapper +0x08 if(m_indexBuffer) - { IDirect3DResource9* r=*reinterpret_cast(static_cast(m_indexBuffer)+8); if(r) r->PreLoad(); } - if(count(m_materials)>=2) + { IDirect3DResource9* r=dx9rend::indexBufferD3D(m_indexBuffer); if(r) r->PreLoad(); } // wrapper +0x08 + if(m_materials.size()>=2) { - vc71::vector_layout& v=materials(this,1,0); - for(unsigned int m=0;m(v);++m) + MaterialList& v=materials(this,1,0); + for(unsigned int m=0;m(v)[m]->m_state->m_textures; - for(unsigned int i=0;i(t);++i) + const BundledMeshState::TextureList& t=v[m]->m_state->m_textures; + for(unsigned int i=0;i(t)[i]; + dx9rend::EngineTexture* p=t[i]; if(p&&std::find(textures.begin(),textures.end(),p)==textures.end()) textures.push_back(p); } } @@ -361,26 +337,27 @@ void BundledMeshTemplate::releaseDeviceResources() //actually preloads } //Skipped records still contribute bounds and maximum part count. +// PE 0x100E9F50 (compared with the listing for gates, constants, call order and field offsets; the compiler-unrolled distance loop was not compared instruction by instruction) void BundledMeshTemplate::readLods(renddx9abi::HostNonlinearStream* stream) { - BundledMeshGeom emptyGeom; initialize(emptyGeom.lods); initialize(emptyGeom.distances); - const unsigned int geoms=count(m_lodCounts); resize(m_geoms,geoms,emptyGeom); + const unsigned int geoms=static_cast(m_lodCounts.size()); m_geoms.resize(geoms); for(unsigned int g=0;g(m_lodCounts)[g]-1); - data(m_geomInts)[g]=skip; - const int kept=(data(m_lodCounts)[g]-=skip); - BundledMeshGeom& geom=data(m_geoms)[g]; + int skip=std::min(maximum,static_cast(dx9rend::rendererTailInt(0x7E4))); // Renderer +0x7E4 + skip=std::min(skip,m_lodCounts[g]-1); + m_geomInts[g]=skip; + const int kept=(m_lodCounts[g]-=skip); + BundledMeshGeom& geom=m_geoms[g]; BundledMeshLod empty; empty.partCount=0; zeroBounds(empty.bounds); empty.renderKind=0; empty.hasAlphaTest=0; - resize(geom.lods,kept,empty); resize(geom.distances,kept-1,0.0f); + geom.lods.resize(static_cast(kept),empty); + geom.distances.resize(static_cast(kept-1),0.0f); int remaining=skip; for(int l=0;l(geom.lods)[l]; + BundledMeshLod& lod=geom.lods[l]; if(m_head||m_version>=10) meshBoundsReadMinMax(lod.bounds,stream); else meshBoundsReadLegacy(lod.bounds,stream); lod.bounds.dirty=1; meshBoundsExpand(m_bounds,lod.bounds.min); meshBoundsExpand(m_bounds,lod.bounds.max); @@ -390,18 +367,19 @@ void BundledMeshTemplate::readLods(renddx9abi::HostNonlinearStream* stream) float running=static_cast(skip+1)*50.0f; for(int l=0;l(m_lodDistances)>g - &&count(data(m_lodDistances)[g])>static_cast(l)) + if(m_lodDistances.size()>g + &&m_lodDistances[g].size()>static_cast(l)) { - float* pending=data(data(m_lodDistances)[g]); - data(geom.distances)[l]=pending[l+skip]; running+=pending[l]; + const float* pending=m_lodDistances[g].data(); + geom.distances[l]=pending[l+skip]; running+=pending[l]; } - else { data(geom.distances)[l]=running; running+=50.0f; } + else { geom.distances[l]=running; running+=50.0f; } } } } //Part number is the low bone-index byte; retail does not bound it. +// PE 0x100E77F0 void BundledMeshTemplate::readVertices(renddx9abi::HostNonlinearStream* stream) { m_vertexData=renddx9abi::engineAlloc(m_vertexCount*m_vertexStride); @@ -431,6 +409,7 @@ void BundledMeshTemplate::mergeMaterials() {} //shipped ret //The declaration rewrite uses packed8 normals even when +192 selects //packed16 output; this shipped inconsistency is retained. Tangents are written //unconditionally (the presence flag only controls the stride subtraction). +// PE 0x100E79A0 void BundledMeshTemplate::buildVertexBuffers() { const bool compressed=getCompressVertexData(); bool hasUv1=false,hasTangent=false; @@ -439,8 +418,8 @@ void BundledMeshTemplate::buildVertexBuffers() UINT n=16; D3DVERTEXELEMENT9* elements=static_cast(renddx9abi::engineAlloc(128)); std::memset(elements,0,128); - (*reinterpret_cast(static_cast(m_vertexDeclaration)+8))->GetDeclaration(elements,&n); - const unsigned char normalType=(*reinterpret_cast(static_cast(dx9rend::g_deviceCaps)+0xEC)&0x80)?14:4; + dx9rend::vertexDeclarationD3D(m_vertexDeclaration)->GetDeclaration(elements,&n); // wrapper +0x08 + const unsigned char normalType=dx9rend::deviceCapsSupportsDeclType(14u)?14:4; // sub_100013A0(14): DEC3N, else UBYTE4N unsigned int removed=0; for(unsigned int i=0;i=minY)) y=minY; if(!(z>=minZ)) z=minZ; + if(x=epsilon)) x=epsilon; if(!(y>=epsilon)) y=epsilon; if(!(z>=epsilon)) z=epsilon; - const Vec3& one=unitScale(); + if(x((static_cast(one.x)/x)*32766.0); m_compressScale.y=inverseY*32766.0f; m_compressScale.z=inverseZ*32766.0f; @@ -473,14 +452,14 @@ void BundledMeshTemplate::buildVertexBuffers() m_decompressScale=Vec3{x*inverseQuantization,y*inverseQuantization,z*inverseQuantization}; m_uvDecompress=1.0f/uvScale; } - else { m_compressScale=unitScale(); m_decompressScale=unitScale(); m_uvDecompress=1; } + else { m_compressScale=rendmath::unitScale(); m_decompressScale=rendmath::unitScale(); m_uvDecompress=1; } const unsigned int oldStride=m_vertexStride; if(compressed) { const unsigned int normalRemoved=4*(m_byte192==0)+4; m_vertexStride-=normalRemoved+8; if(hasUv1) m_vertexStride-=4; if(hasTangent) m_vertexStride-=normalRemoved; } - vc71::string name("BundledMeshTemplate : "); name+=m_name; + std::string name("BundledMeshTemplate : "); name+=m_name; m_vertexBuffer=dx9rend::createVertexBuffer(dx9rend::g_bufferManager,m_vertexCount,m_vertexStride,name,8); unsigned short* target=static_cast(dx9rend::vertexBufferLock(m_vertexBuffer,0,m_vertexCount,0)); if(target) @@ -526,21 +505,20 @@ bool BundledMeshTemplate::makeScript(::dice::hfe::io::IStream* stream) //100E859 { MeshTemplate::makeScript(stream); //base write result deliberately discarded std::ostringstream out; - for(unsigned int g=0;g(m_geoms);++g) + for(unsigned int g=0;g(m_geoms)[g].distances; - for(unsigned int l=0;l(v);++l) - if(data(v)[l]!=static_cast(50*(l+1))) - out<<"GeometryTemplate.setSubGeometryLodDistance "<(v)[l]<& v=m_geoms[g].distances; + for(unsigned int l=0;l(50*(l+1))) + out<<"GeometryTemplate.setSubGeometryLodDistance "<(maps[i]->head); - for(BundledMeshMapNode* n=head->left;n!=head;n=bundledMeshMapNext(n)) - out<(static_cast(n->key)>>16)<<" " - <<((n->key>>8)&255)<<" "<<(n->key&255)<<" "<value)<begin();n!=maps[i]->end();++n) + out<(static_cast(n->first)>>16)<<" " + <<((n->first>>8)&255)<<" "<<(n->first&255)<<" "<second)<(m_lodCounts); resize(m_materials,geoms,emptyVector()); + const unsigned int geoms=static_cast(m_lodCounts.size()); m_materials.resize(geoms); D3DVERTEXELEMENT9* elements=static_cast(renddx9abi::engineAlloc(128)); std::memset(elements,0,128); UINT n=16; - (*reinterpret_cast(static_cast(m_vertexDeclaration)+8))->GetDeclaration(elements,&n); + dx9rend::vertexDeclarationD3D(m_vertexDeclaration)->GetDeclaration(elements,&n); // wrapper +0x08 bool hasUv1=false,hasTangent=false; for(unsigned int i=0;i(m_lodCounts)[g]; int skip=data(m_geomInts)[g]; - resize(data(m_materials)[g],lodCount,emptyVector()); + const int lodCount=m_lodCounts[g]; int skip=m_geomInts[g]; + m_materials[g].resize(static_cast(lodCount)); for(int l=0;lread(&materialCount,4); resize(v,materialCount,static_cast(0)); - BundledMeshLod& lod=data(data(m_geoms)[g].lods)[l]; + MaterialList& v=materials(this,g,l); unsigned int materialCount; + stream->read(&materialCount,4); v.resize(materialCount,static_cast(0)); + BundledMeshLod& lod=m_geoms[g].lods[l]; lod.renderKind=3; lod.hasAlphaTest=0; for(unsigned int i=0;i(v)[i]=m; + v[i]=m; if(m_version<5) m->m_kind=i==1?1:0; else stream->read(&m->m_kind,4); if(m->m_kind==1) lod.renderKind=2; else { m_hasOpaqueMaterials=1; if(m->m_kind==2) lod.hasAlphaTest=1; } @@ -615,34 +594,38 @@ void BundledMeshTemplate::readMaterials(renddx9abi::HostNonlinearStream* stream) } //Parameters are the shared 0x150-byte Ra material block at material+10. +// PE 0x100E8C00 void BundledMeshTemplate::finalizeMaterials() { - for(unsigned int g=0;g(m_lodCounts);++g) - for(int l=0;l(m_lodCounts)[g];++l) + for(unsigned int g=0;g(v);++i) + MaterialList& v=materials(this,g,l); + for(unsigned int i=0;i(v)[i]; - m->m_vertexBuffer=*reinterpret_cast(static_cast(m_vertexBuffer)+8); - m->m_indexBuffer=*reinterpret_cast(static_cast(m_indexBuffer)+8); - m->m_vertexStride=*reinterpret_cast(static_cast(m_vertexBuffer)+40); + BundledMeshMaterial* m=v[i]; + m->m_vertexBuffer=dx9rend::vertexBufferD3D(m_vertexBuffer); // wrapper +0x08 + m->m_indexBuffer=dx9rend::indexBufferD3D(m_indexBuffer); // wrapper +0x08 + m->m_vertexStride=dx9rend::vertexBufferStride(m_vertexBuffer); // wrapper +0x28 m->m_primitiveType=m_primitiveType; - if(m->m_kind==2) { materialField(m,0x2C)=1; materialField(m,0xB4)=m->m_state->m_alphaTest?15:127; } + // The block's holders; the `+0xNN` comments are the retail material offsets. + RaMaterialParameters& p=bundledMeshMaterialParameters(m); + if(m->m_kind==2) { p.alphaTest.value=1; p.alphaTestRef.value=m->m_state->m_alphaTest?15:127; } // +0x2C, +0xB4 if(m->m_kind==1) - { materialField(m,0x2C)=1; materialField(m,0xB4)=0; materialField(m,0x1C)=1; materialField(m,0xAC)=1; materialField(m,0x24)=0; } - vc71::vector_layout& textures=m->m_state->m_textures; - assignTexture(m,0xCC,data(textures)[0]); - if(m->m_state->m_normalMap) assignTexture(m,0xEC,data(textures)[1]); - if(m->m_state->m_extraMap) assignTexture(m,0xFC,data(textures)[count(textures)-1]); - materialField(m,0x138)=m_decompressScale.x; materialField(m,0x13C)=m_decompressScale.y; - materialField(m,0x140)=m_decompressScale.z; materialField(m,0x14C)=m_uvDecompress; + { p.alphaTest.value=1; p.alphaTestRef.value=0; p.alphaBlendEnable.value=1; p.cullMode.value=1; p.depthWrite.value=0; } // +0x2C +0xB4 +0x1C +0xAC +0x24 + // Unguarded, as shipped. + const BundledMeshState::TextureList& textures=m->m_state->m_textures; + assignTexture(p.diffuseMap,textures.data()[0]); // +0xCC + if(m->m_state->m_normalMap) assignTexture(p.normalMap,textures.data()[1]); // +0xEC + if(m->m_state->m_extraMap) assignTexture(p.giMap,textures.data()[textures.size()-1]); // +0xFC + p.posUnpack.value[0]=m_decompressScale.x; p.posUnpack.value[1]=m_decompressScale.y; // +0x138, +0x13C + p.posUnpack.value[2]=m_decompressScale.z; p.texUnpack.value=m_uvDecompress; // +0x140, +0x14C if(getCompressVertexData()) { - if(slot_0x84()) { materialField(m,0x154)=dx9rend::g_materialCapC; materialField(m,0x158)=dx9rend::g_materialCapD; } - else { materialField(m,0x154)=dx9rend::g_materialCapScale; materialField(m,0x158)=dx9rend::g_materialCapBias; } + if(slot_0x84()) { p.normalUnpack.value[0]=dx9rend::g_materialCapC; p.normalUnpack.value[1]=dx9rend::g_materialCapD; } // +0x154, +0x158 + else { p.normalUnpack.value[0]=dx9rend::g_materialCapScale; p.normalUnpack.value[1]=dx9rend::g_materialCapBias; } } - else { materialField(m,0x154)=1; materialField(m,0x158)=0; } + else { p.normalUnpack.value[0]=1; p.normalUnpack.value[1]=0; } } } } @@ -650,23 +633,65 @@ void BundledMeshTemplate::finalizeMaterials() void bundledMeshInitTechniques() { if(!g_bundledMeshTechniquesPending) return; - if(!meshBuildTechniqueMasks(vc71::string("shaders/RaShaderBM.mfx"),vc71::string("BM"),kBits,g_techniques,g_qualityMasks)) return; + if(!meshBuildTechniqueMasks(std::string("shaders/RaShaderBM.mfx"),std::string("BM"),kBits,g_techniques,g_qualityMasks)) return; dx9rend::Ra::RaShaderTable* table=static_cast(dx9rend::g_renderQueues); - g_techniques.insert(std::make_pair(0xF8000000u,dx9rend::Ra::getShader(table,vc71::string("Default"),false))); - g_techniques.insert(std::make_pair(0xF6000000u,dx9rend::Ra::getShader(table,vc71::string("BMZOnly"),false))); + g_techniques.insert(std::make_pair(0xF8000000u,dx9rend::Ra::getShader(table,std::string("Default"),false))); + g_techniques.insert(std::make_pair(0xF6000000u,dx9rend::Ra::getShader(table,std::string("BMZOnly"),false))); g_bundledMeshTechniquesPending=0; } +// PE 0x100E8A90 dx9rend::Ra::RaShader* bundledMeshShaderForBits(unsigned int bits) { auto i=g_techniques.find(bits); if(i!=g_techniques.end()) return i->second; - vc71::string names; - for(unsigned int b=0;b<32;++b) if(bits&(1u<>index)&1u)==0); + names+=kBits[index]; // shipped defect: no name-table range guard + } + message << "Couldn't find shader bits: " << bits << " looked up name: " << names; + } i=g_techniques.find(0xF8000000u); if(i!=g_techniques.end()) return i->second; - renddx9abi::logf("BundledMeshTemplate.cpp:1123: Couldn't find shader default"); return 0; + ::renddx9abi::Debug(DebugTypeError, + "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\BundledMeshTemplate.cpp", + 1123, "") << "Couldn't find shader default"; + return 0; +} +unsigned int bundledMeshQualityMask(unsigned int index) { return g_qualityMasks.data()[index]; } +// PE 0x100E8EF0: unreachable in 1.50: no code or data references. Adds a technique to the table +// bundledMeshInitTechniques fills; an existing key is kept (insert, not assignment). +void bundledMeshAddTechnique(unsigned int bits,dx9rend::Ra::RaShader* shader) +{ + g_techniques.insert(std::make_pair(bits,shader)); +} +// PE 0x100E7710: unreachable in 1.50: no code or data references. The size in bytes of a vertex +// element of D3DDECLTYPE `declType` (the retail body takes it in cl): FLOAT1, D3DCOLOR and SHORT2 +// are 4, FLOAT2 8, FLOAT3 12, FLOAT4 16; UBYTE4 (5) and every type past SHORT2 report the error +// and answer 0. +unsigned int bundledMeshDeclTypeSize(unsigned char declType) +{ + switch(declType) + { + case 0: case 4: case 6: return 4; + case 1: return 8; + case 2: return 12; + case 3: return 16; + default: + ::renddx9abi::Debug(DebugTypeError2, + "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\BundledMeshTemplate.cpp", + 1103, "") << "Unknown DeclType " << static_cast(declType); + return 0; + } } -unsigned int bundledMeshQualityMask(unsigned int index) { return data(g_qualityMasks)[index]; } -unsigned int bundledMeshQualityMask() { return bundledMeshQualityMask(rendererInt(1740)); } +unsigned int bundledMeshQualityMask() { return bundledMeshQualityMask(dx9rend::rendererRaPath()); } // Renderer +0x6CC } } } #endif diff --git a/Code/BF2/Geom/BundledMeshTemplate.h b/Code/BF2/Geom/BundledMeshTemplate.h index 80e43be14..15be23c36 100644 --- a/Code/BF2/Geom/BundledMeshTemplate.h +++ b/Code/BF2/Geom/BundledMeshTemplate.h @@ -6,11 +6,15 @@ #include "MeshTemplate.h" #include +#include +#include +#include namespace dice { namespace hfe { namespace dx9rend { namespace Ra { struct RaShader; } } namespace geom { class BundledMeshMaterial; +class BundledMesh; // readLods100E9F50 / instance101049B0 prove the 72/32-byte strides. struct BundledMeshLod @@ -23,22 +27,31 @@ struct BundledMeshLod }; struct BundledMeshGeom { - vc71::vector_layout lods; // BundledMeshLod - vc71::vector_layout distances; // float + std::vector lods; + std::vector distances; }; static_assert(sizeof(BundledMeshLod)==72, "Bundled lod stride"); -static_assert(sizeof(BundledMeshGeom)==32, "Bundled geom stride"); +// m_materials holds geom -> lod -> material pointers; m_instances the live instances. The three +// value maps store each value's 32 bits as written, keyed (geom << 16) | (lod << 8) | material. class BundledMeshTemplate : public MeshTemplate { public: + typedef std::vector MaterialList; + typedef std::vector > MaterialTree; + typedef std::vector GeomVector; + typedef std::map ValueMap; + typedef std::set InstanceSet; + BundledMeshTemplate(); + // The destructor body (then the base's): the deleting slot frees the storage afterwards + // without running a C++ destructor, so this destroys every member itself. void destroyMembers(); virtual void addRef(); virtual int getRef(); virtual int release(); virtual unsigned int getClassId() const; - virtual void setName(const vc71::string& name); + virtual void setName(const std::string& name); virtual void* createInstance(); virtual bool load(); virtual void setLodDistance(int geom, int lod, float distance); @@ -78,13 +91,13 @@ class BundledMeshTemplate : public MeshTemplate virtual bool makeScript(::dice::hfe::io::IStream* stream); int m_refCount; // +0C8 - vc71::vector_layout m_materials; // +0CC geom -> lod -> BundledMeshMaterial* - vc71::set_layout m_instances; // +0DC - vc71::map_layout m_materialValues0E8; // +0E8 packed geom/lod/material -> float - vc71::map_layout m_map0F4; // +0F4 packed key -> static gloss float - vc71::map_layout m_map100; // +100 packed key -> int, draw material+94 + MaterialTree m_materials; // +0CC + InstanceSet m_instances; // +0DC + ValueMap m_materialValues0E8; // +0E8 packed key -> float bits + ValueMap m_map0F4; // +0F4 packed key -> static gloss float bits + ValueMap m_map100; // +100 packed key -> int, draw material+94 unsigned int m_dword10C; // +10C - vc71::vector_layout m_geoms; // +110 BundledMeshGeom + GeomVector m_geoms; // +110 unsigned int m_maxPartCount; // +120 unsigned char m_hasOpaqueMaterials; // +124 readMaterials kind!=1 unsigned char m_byte125; // +125 slots48/4C @@ -105,16 +118,13 @@ class BundledMeshTemplate : public MeshTemplate unsigned int m_dword1F4; // +1F4 ctor untouched unsigned int m_liveInstanceCount; // +1F8 }; -static_assert(sizeof(BundledMeshTemplate)==0x1FC, "factory allocation"); -static_assert(offsetof(BundledMeshTemplate,m_materials)==0xCC, "material tree"); -static_assert(offsetof(BundledMeshTemplate,m_geoms)==0x110, "geometry tree"); -static_assert(offsetof(BundledMeshTemplate,m_bounds)==0x19C, "template bounds"); -static_assert(offsetof(BundledMeshTemplate,m_liveInstanceCount)==0x1F8, "instance count"); void bundledMeshInitTechniques(); dx9rend::Ra::RaShader* bundledMeshShaderForBits(unsigned int bits); unsigned int bundledMeshQualityMask(); // draw's unchecked quality indexing unsigned int bundledMeshQualityMask(unsigned int index); +void bundledMeshAddTechnique(unsigned int bits, dx9rend::Ra::RaShader* shader); +unsigned int bundledMeshDeclTypeSize(unsigned char declType); IBase* __fastcall createBundledMeshTemplate(unsigned int iid, IBase* outer); // Instance-owned bodies, published by BundledMesh.cpp. diff --git a/Code/BF2/Geom/DecalSystem/DecalContainers.h b/Code/BF2/Geom/DecalSystem/DecalContainers.h index fae72efcd..8d40a0893 100644 --- a/Code/BF2/Geom/DecalSystem/DecalContainers.h +++ b/Code/BF2/Geom/DecalSystem/DecalContainers.h @@ -1,529 +1,33 @@ -// [CHOSEN, not recovered] containers with the VC7.1 layouts embedded by decal owners. -// Vectors grow by half; resize(0) keeps storage, clear() frees it, and copies allocate exact size. -// Maps preserve ordered traversal, duplicate rejection, stable nodes and head/sentinel links. -// [CHOSEN, not recovered] insertion/erasure currently use an unbalanced search tree; -// [CHOSEN] vector moves replace deep copies and therefore change allocation traffic. -// [RETIRE-WHEN: RW-74] Replace these operations after the original container behavior is -// implemented and validated for layout, ownership, traversal and allocation semantics. +// The comparator the decal owners' std containers need beyond the defaults. Retail's decal +// containers are VC7.1 std::vector / std::map instances; the rebuilt renderer uses this toolset's +// std containers instead (issue #7), so only the template map's case-insensitive order is kept here. #ifndef BF2_GEOM_DECALSYSTEM_DECALCONTAINERS_H #define BF2_GEOM_DECALSYSTEM_DECALCONTAINERS_H #ifdef BF2_IMAGE_RENDDX9 -#include "../../../RendDX9Abi/BfMemory.h" -#include "../../../RendDX9Abi/Vc71String.h" +#include -#include +#include #include +#include namespace dice { namespace hfe { namespace geom { -namespace decalvc71 { - - -// Vector - -template -class Vector -{ -public: - Vector() : m_first(0), m_last(0), m_end(0) {} // the allocator word stays unwritten - - // VC7.1 vector(const vector&): _Buy(size()) and the uninitialised copy (0x101AB2A0). - Vector(const Vector& other) : m_first(0), m_last(0), m_end(0) - { - const unsigned int n = other.size(); - if (n) - { - m_first = allocate(n); - m_end = m_first + n; - m_last = m_first; - for (const T* p = other.m_first; p != other.m_last; ++p, ++m_last) - ::new (static_cast(m_last)) T(*p); - } - } - - // [CHOSEN] - see the file header. - Vector(Vector&& other) : m_first(other.m_first), m_last(other.m_last), m_end(other.m_end) - { - other.m_first = 0; - other.m_last = 0; - other.m_end = 0; - } - - Vector& operator=(const Vector& other) - { - if (this != &other) - { - Vector copy(other); - swap(copy); - } - return *this; - } - - Vector& operator=(Vector&& other) - { - if (this != &other) - { - clear(); - swap(other); - } - return *this; - } - - ~Vector() { clear(); } - - void swap(Vector& other) - { - T* const first = m_first; m_first = other.m_first; other.m_first = first; - T* const last = m_last; m_last = other.m_last; other.m_last = last; - T* const end = m_end; m_end = other.m_end; other.m_end = end; - } - - unsigned int size() const - { - return m_first ? static_cast(m_last - m_first) : 0u; - } - unsigned int capacity() const - { - return m_first ? static_cast(m_end - m_first) : 0u; - } - - T* data() { return m_first; } // _Myfirst, unguarded - const T* data() const { return m_first; } - T* begin() { return m_first; } - T* end() { return m_last; } - T& operator[](unsigned int i) { return m_first[i]; } - const T& operator[](unsigned int i) const { return m_first[i]; } - - void push_back(const T& value) - { - if (m_first && size() < capacity()) - { - ::new (static_cast(m_last)) T(value); - ++m_last; - return; - } - insertAtEnd(1u, value); - } - - // VC7.1 resize(n) builds `T()` and calls resize(n, T()). - void resize(unsigned int n) { resize(n, T()); } - void resize(unsigned int n, const T& value) - { - const unsigned int current = size(); - if (current < n) - insertAtEnd(n - current, value); - else if (m_first && n < current) // erase(begin() + n, end()) - { - T* const newLast = m_first + n; - for (T* p = newLast; p != m_last; ++p) - p->~T(); - m_last = newLast; - } - } - - void clear() // VC7.1 clear() == _Tidy() - { - if (m_first) - { - for (T* p = m_first; p != m_last; ++p) - p->~T(); - ::renddx9abi::engineFree(m_first); - } - m_first = 0; - m_last = 0; - m_end = 0; - } - -private: - static T* allocate(unsigned int count) - { - return static_cast(::renddx9abi::engineAlloc(count * static_cast(sizeof(T)))); - } - - // _Insert_n(end(), count, value) - the only insert position a decal path uses. - void insertAtEnd(unsigned int count, const T& value) - { - if (count == 0) - return; - const T copy(value); // `_Ty _Tmp = _Val` - const unsigned int oldSize = size(); - if (capacity() < oldSize + count) - { - const unsigned int oldCap = capacity(); - unsigned int newCap = oldCap + oldCap / 2u; - if (newCap < oldSize + count) - newCap = oldSize + count; - T* const block = allocate(newCap); - T* dst = block; - for (T* p = m_first; p != m_last; ++p, ++dst) - ::new (static_cast(dst)) T(*p); - for (unsigned int i = 0; i < count; ++i, ++dst) - ::new (static_cast(dst)) T(copy); - if (m_first) - { - for (T* p = m_first; p != m_last; ++p) - p->~T(); - ::renddx9abi::engineFree(m_first); - } - m_first = block; - m_last = dst; - m_end = block + newCap; - return; - } - for (unsigned int i = 0; i < count; ++i, ++m_last) - ::new (static_cast(m_last)) T(copy); - } - - void* m_alloc; // +0x00 allocator, padded - T* m_first; // +0x04 _Myfirst - T* m_last; // +0x08 _Mylast - T* m_end; // +0x0C _Myend -}; - - -// Map - -template -struct TreeNode -{ - TreeNode* left; // +0x00 _Left - TreeNode* parent; // +0x04 _Parent - TreeNode* right; // +0x08 _Right - K key; // +0x0C _Myval.first - V value; // _Myval.second - unsigned char color; // _Color, 1 == black - unsigned char isNil; // _Isnil -}; - -// std::less - VC7.1 compares the raw pointers, i.e. unsigned (0x10126190 `cmp; setb`, -// 0x100A5850 `cmp; jnb`). -template -struct UnsignedLess -{ - static bool less(const K& a, const K& b) { return a < b; } -}; // The template map's comparator: 0x10036390 (find, comdat-shared with GeometryTemplateManager's // registry) and 0x10126CE0 (operator[]) both call MSVCR71 `_stricmp(a.c_str(), b.c_str())`. -struct NoCaseLess +// std::map keeps the first-inserted spelling of a key, as the shipped map does. +struct DecalTemplateNameLess { - static bool less(const vc71::string& a, const vc71::string& b) + bool operator()(const std::string& a, const std::string& b) const { return ::_stricmp(a.c_str(), b.c_str()) < 0; } }; -// For the two maps the image only ever constructs, clears and destroys (DecalManager +0x78 and -// +0x84 - see DecalManager.h). Their comparators are never instantiated in the shipped image, so -// they are [UNRESOLVED]; these stand in so the shape can be declared, and nothing calls them. -struct UnreadStringLess -{ - static bool less(const vc71::string& a, const vc71::string& b) - { - return ::strcmp(a.c_str(), b.c_str()) < 0; - } -}; - -template -class Map -{ -public: - typedef TreeNode Node; - - // The owner constructor's inline sequence (0x10125215..0x10125248 for +0x28, the same six - // stores for every tree): _Buynode() for the head, then _Isnil = 1, self-links, _Mysize = 0. - Map() : m_head(buyHead()), m_size(0) - { - m_head->isNil = 1; - m_head->parent = m_head; - m_head->left = m_head; - m_head->right = m_head; - } - - // The owner destructor's inline sequence (0x101250B8..0x101250E1): erase(begin(), end()), free - // the head, null _Myhead and _Mysize. - ~Map() - { - clear(); - ::renddx9abi::engineFree(m_head); - m_head = 0; - m_size = 0; - } - - Node* begin() const { return m_head->left; } - Node* end() const { return m_head; } - unsigned int size() const { return m_size; } - - // VC7.1 _Inc (inlined at 0x10124919..0x10124957 and 0x100A54F0). - static Node* next(Node* node) - { - if (node->isNil) - return node; - if (!node->right->isNil) - { - node = node->right; - while (!node->left->isNil) - node = node->left; - return node; - } - Node* p = node->parent; - while (!p->isNil && node == p->right) - { - node = p; - p = p->parent; - } - return p; - } - - // _Lbound (sub_101C0A60's descent). - Node* lowerBound(const K& key) const - { - Node* result = m_head; - Node* cur = m_head->parent; - while (!cur->isNil) - { - if (Less::less(cur->key, key)) - cur = cur->right; - else - { - result = cur; - cur = cur->left; - } - } - return result; - } - - // find (0x100A5850 / 0x10036390): lower bound, then end() unless the key really matches. - Node* find(const K& key) const - { - Node* const n = lowerBound(key); - if (n == m_head || Less::less(key, n->key)) - return m_head; - return n; - } - - // insert(value_type) - insert_unique (0x10126190), VC7.1's _Tree::insert step for step: descend - // remembering the last node and the last direction; a left landing on begin() inserts at once; - // otherwise the candidate is that node (right landing) or its in-order predecessor (left - // landing), and the key is new only when the candidate is strictly less. Answers the node and - // whether it was new. - Node* insert(const K& key, const V& value, bool* inserted) - { - Node* where = m_head; - Node* cur = m_head->parent; - bool addLeft = true; // left of the head when empty - while (!cur->isNil) - { - where = cur; - addLeft = Less::less(key, cur->key); - cur = addLeft ? cur->left : cur->right; - } - - Node* candidate = where; - if (addLeft) - { - if (where == m_head->left) // _Where == begin() - return link(where, true, key, value, inserted); - candidate = previous(where); // Where - } - if (Less::less(candidate->key, key)) - return link(where, addLeft, key, value, inserted); - if (inserted) - *inserted = false; - return candidate; - } - - // operator[] (0x10126CE0 / 0x10126D70): lower bound; insert (key, V()) when absent; answer the - // mapped value. - V& operator[](const K& key) - { - Node* n = lowerBound(key); - if (n == m_head || Less::less(key, n->key)) - n = insert(key, V(), 0); - return n->value; - } - - // erase(iterator) (0x100F63D0 / 0x101265D0). Transplants the successor on a two-child erase so - // every surviving node keeps its address, as the shipped erase does. - void erase(Node* z) - { - if (!z || z == m_head) - return; - - Node* replacement; - if (z->left == m_head) - replacement = z->right; - else if (z->right == m_head) - replacement = z->left; - else - { - Node* successor = z->right; - while (successor->left != m_head) - successor = successor->left; - if (successor->parent != z) - { - successor->parent->left = successor->right; - if (successor->right != m_head) - successor->right->parent = successor->parent; - successor->right = z->right; - successor->right->parent = successor; - } - successor->left = z->left; - successor->left->parent = successor; - replacement = successor; - } - - if (z->parent == m_head) - m_head->parent = replacement; - else if (z == z->parent->left) - z->parent->left = replacement; - else - z->parent->right = replacement; - if (replacement != m_head) - replacement->parent = z->parent; - - relinkExtremes(); - destroyNode(z); - --m_size; - } - - // clear(): _Erase(root) + relink the head (the inlined loops at 0x10124A80..0x10124B64 and - // sub_10126250 / sub_10126BD0). Walked iteratively - the chosen tree can be degenerate. - void clear() - { - Node* n = m_head->parent; - while (n != m_head) - { - if (n->left != m_head) { n = n->left; continue; } - if (n->right != m_head) { n = n->right; continue; } - Node* const parent = n->parent; - if (parent != m_head) - { - if (parent->left == n) parent->left = m_head; - else parent->right = m_head; - } - destroyNode(n); - n = parent; - } - m_head->parent = m_head; - m_size = 0; - m_head->left = m_head; - m_head->right = m_head; - } - -private: - Map(const Map&); // no recovered path copies a tree - Map& operator=(const Map&); - - // _Buynode() for the head (sub_10125880 / sub_101256B0 / sub_101257E0): the three links null, - // _Color black, _Isnil 0 - the key and value are NOT constructed. - static Node* buyHead() - { - Node* const n = static_cast(::renddx9abi::engineAlloc(static_cast(sizeof(Node)))); - n->left = 0; // unguarded, as shipped: a failed - n->parent = 0; // allocation throws in VC7.1 and - n->right = 0; // faults here - n->color = 1; - n->isNil = 0; - return n; - } - - Node* link(Node* parent, bool asLeft, const K& key, const V& value, bool* inserted) - { - Node* const n = static_cast(::renddx9abi::engineAlloc(static_cast(sizeof(Node)))); - ::new (static_cast(&n->key)) K(key); - ::new (static_cast(&n->value)) V(value); - n->left = m_head; - n->right = m_head; - n->parent = parent; - n->color = 0; // red, as a fresh node is - n->isNil = 0; - if (parent == m_head) - { - m_head->parent = n; - m_head->left = n; - m_head->right = n; - } - else if (asLeft) - { - parent->left = n; - if (parent == m_head->left) - m_head->left = n; - } - else - { - parent->right = n; - if (parent == m_head->right) - m_head->right = n; - } - ++m_size; - if (inserted) - *inserted = true; - return n; - } - - Node* previous(Node* node) const - { - if (!node->left->isNil) - { - node = node->left; - while (!node->right->isNil) - node = node->right; - return node; - } - Node* p = node->parent; - while (!p->isNil && node == p->left) - { - node = p; - p = p->parent; - } - return p; - } - - void relinkExtremes() - { - Node* const root = m_head->parent; - if (root == m_head) - { - m_head->left = m_head; - m_head->right = m_head; - return; - } - Node* l = root; - while (l->left != m_head) - l = l->left; - Node* r = root; - while (r->right != m_head) - r = r->right; - m_head->left = l; - m_head->right = r; - } - - static void destroyNode(Node* n) - { - n->value.~V(); - n->key.~K(); - ::renddx9abi::engineFree(n); - } - - void* m_comp; // +0x00 the empty comparator, padded - Node* m_head; // +0x04 _Myhead - unsigned int m_size; // +0x08 _Mysize -}; - -#if defined(_M_IX86) -static_assert(sizeof(Vector) == 16, "the VC7.1 std::vector is 16 bytes"); -static_assert(sizeof(Map >) == 12, "the VC7.1 std::map is 12 bytes"); -static_assert(sizeof(TreeNode) == 0x18, "sub_10125880 allocates 0x18"); -static_assert(sizeof(TreeNode) == 0x18, "the +0x6C map's node is 0x18"); -static_assert(sizeof(TreeNode) == 0x30, "sub_101256B0 allocates 0x30"); -#endif - -} // namespace decalvc71 } // namespace geom } // namespace hfe } // namespace dice diff --git a/Code/BF2/Geom/DecalSystem/DecalManager.cpp b/Code/BF2/Geom/DecalSystem/DecalManager.cpp index 3df60d2f9..6bd3bf376 100644 --- a/Code/BF2/Geom/DecalSystem/DecalManager.cpp +++ b/Code/BF2/Geom/DecalSystem/DecalManager.cpp @@ -47,20 +47,20 @@ namespace { // unk_1025BEBC - a file-scope std::string built by the static initialiser 0x101D37C0 (destroyed by // the atexit entry 0x101D96B0). loadAtlas and generateTexture prefix it. -const vc71::string s_atlasDirectory("Objects/Effects/Decals/Textures/Atlas/"); +const std::string s_atlasDirectory("Objects/Effects/Decals/Textures/Atlas/"); -// The shipped code inlines MSVCP71's operator+ - copy-construct, operator+=, copy out. vc71::string -// publishes no operator+, so these carry the same steps (UndergrowthSystemLoad.cpp's precedent). -vc71::string concat(const vc71::string& left, const char* right) +// The shipped code inlines MSVCP71's operator+ - copy-construct, operator+=, copy out. These carry +// the same steps (UndergrowthSystemLoad.cpp's precedent). +std::string concat(const std::string& left, const char* right) { - vc71::string result(left); + std::string result(left); result += right; return result; } -vc71::string concat(const vc71::string& left, const vc71::string& right) +std::string concat(const std::string& left, const std::string& right) { - vc71::string result(left); + std::string result(left); result += right; return result; } @@ -76,8 +76,8 @@ dx9rend::IRenderer* renderer() // `textureAtlasRelease` in TextureAtlas.h. int releaseAtlas(dx9rend::TextureAtlas* atlas) { - typedef int (__fastcall* ReleaseFn)(void*, void*); - return reinterpret_cast(static_cast(atlas->vptr)[0x08 / 4])(atlas, 0); + typedef int (__thiscall* ReleaseFn)(void*); + return reinterpret_cast(static_cast(atlas->vptr)[0x08 / 4])(atlas); } } // anonymous namespace @@ -85,7 +85,7 @@ int releaseAtlas(dx9rend::TextureAtlas* atlas) // Initializes decal resources and pool, then derives fade times from their defaults. // The listener's render-path field and padding remain untouched. - +// PE 0x101251F0 DecalManager::DecalManager() : m_refCount(1) , m_timeToLive(20.0f) @@ -117,7 +117,8 @@ DecalManager::DecalManager() , m_decalGeomClipAngle(60.0f) , m_atlas(0) { - void* const storage = ::renddx9abi::engineAlloc(0x14u); // sub_1005F320(0x14) + void* const storage = ::renddx9abi::engineAlloc( + static_cast(sizeof(dx9rend::TextureAtlas))); // sub_1005F320(0x14) m_atlas = storage ? dx9rend::textureAtlasCtor(storage) : 0; initPool(); recomputeFades(); // inline, 0x101253C3.. @@ -127,8 +128,9 @@ DecalManager::DecalManager() // the destructor: flushDeletes, clear, the atlas released through its table // (unguarded - a failed atlas allocation faults here, as shipped), then the members in reverse // declaration order: the renderer (0x101AA4F0), the maps +0x84 / +0x78 / +0x6C, the vectors +0x5C / -// +0x4C, the maps +0x40 / +0x34 / +0x28 - each map erase(begin(), end()) + its head freed. +// +0x4C, the maps +0x40 / +0x34 / +0x28 - the std containers' own destructors. +// PE 0x10125080 DecalManager::~DecalManager() { flushDeletes(); @@ -149,6 +151,7 @@ int DecalManager::getRef() return m_refCount; } +// PE 0x10126F00 // the decremented count is cached before the object is destroyed and freed // (sub_1005F360), and returned. int DecalManager::release() @@ -163,6 +166,7 @@ int DecalManager::release() } // this for iid 1 or 820018, else 0 (branch-free `setnz; sub; and`). +// PE 0x10126EB0 void* DecalManager::queryInterface(unsigned int iid) const { if (iid == RD9_IID_IBASE) @@ -178,25 +182,26 @@ void DecalManager::reserved10() } +// PE 0x10124610 // +0x14, createClient(owner): 0 while decals are disabled (+0x2A6); // else a 0x44-byte DecalObject (operator new, D1's constructor 0x101AC7B0 with the owner), inserted // into the client set as (object, object) - also when the allocation failed and the object is 0. - void* DecalManager::createClient(void* owner) { if (!m_enabled) return 0; - void* const storage = ::renddx9abi::engineAlloc(0x44u); // sub_1005F320(0x44) + void* const storage = ::renddx9abi::engineAlloc( + static_cast(sizeof(DecalObject))); // sub_1005F320(0x44) DecalObject* const object = storage ? new (storage) DecalObject(static_cast(owner)) : 0; - bool inserted = false; - m_clients.insert(object, object, &inserted); + m_clients.insert(DecalObjectMap::value_type(object, object)); return object; } // +0x18, the deferred delete (DecalObject slot +0x28 calls it with // itself): queued unless clear() is running; update's flushDeletes destroys it. +// PE 0x10124790 void DecalManager::enqueue(void* decalObject) { if (!m_clearing) // +0x2A4 @@ -211,15 +216,15 @@ void DecalManager::enqueue(void* decalObject) // name (operator[]), takes the running count as its index (+0x58, written through the new // pointer with no null test), the count is incremented, and the index map files it too. +// PE 0x10124BE0 IDecalTemplate* DecalManager::addTemplate(const DecalTemplateString& name) { - // The key is this image's own VC7.1 string: in the retail-ABI flavour the host's string IS - // one (toVc71String answers a reference); in the native flavour it is converted once here. - const vc71::string& key = ::renddx9abi::toVc71String(name); + // The key is this image's own string; fromHostString converts the host string once here. + const std::string& key = ::renddx9abi::fromHostString(name); - DecalTemplateMap::Node* const found = m_templates.find(key); + const DecalTemplateMap::iterator found = m_templates.find(key); if (found != m_templates.end()) - return found->value; // node +0x28 + return found->second; // node +0x28 if (m_templateCount >= 0x200) { @@ -246,6 +251,7 @@ void DecalManager::reserved20(void* argument) // is reported (line 274) and handled again; the flag is set; an object already in the active set is // reported (line 283); then (object, object) is inserted - a duplicate insert changes nothing. +// PE 0x10124670 void DecalManager::addInstance(void* instance) { DecalObject* const object = static_cast(instance); @@ -256,10 +262,10 @@ void DecalManager::addInstance(void* instance) if (m_activeInstances.find(object) != m_activeInstances.end()) ::renddx9abi::logf("DecalManager.cpp:283 Trying to add already activeInstances"); - bool inserted = false; - m_activeInstances.insert(object, object, &inserted); + m_activeInstances.insert(DecalObjectMap::value_type(object, object)); } +// PE 0x10124820 // +0x28, the active flag cleared and the object queued; update's // flushRemovals takes it out of the set. The DecalObject destructor (0x101AEC80) calls this too. void DecalManager::removeInstance(void* decalObject) @@ -291,9 +297,9 @@ void DecalManager::update(float deltaTime) flushRemovals(); renderer()->getRenderViewDup(); // +0x50, answer unused m_lastDeltaTime = deltaTime; // +0x20 - for (DecalObjectMap::Node* it = m_activeInstances.begin(); it != m_activeInstances.end(); - it = DecalObjectMap::next(it)) - it->value->update(deltaTime); // [value] +0x24 + for (DecalObjectMap::iterator it = m_activeInstances.begin(); it != m_activeInstances.end(); + ++it) + it->second->update(deltaTime); // [value] +0x24 flushRemovals(); } @@ -382,6 +388,7 @@ void DecalManager::onRenderPathChanged(int path) // collect over a stack copy of the renderer's view (+0x48), then render with the renderer's view // fetched again. The two halves are the unreferenced 0x10124570 and 0x10124110, inlined here. +// PE 0x101245B0 (RenderPathListener receiver) void DecalManager::onRenderPathNotification(int unused) { collectDecals(*renderer()->getRenderView()); // +0x48, 0x10124570 body @@ -395,9 +402,10 @@ int DecalManager::getCurrentRenderPath() const } // +0x14, std::string("DecalRenderer client"). -vc71::string DecalManager::getRenderPathListenerName() const +// PE 0x10126EE0 +std::string DecalManager::getRenderPathListenerName() const { - return vc71::string("DecalRenderer client"); + return std::string("DecalRenderer client"); } // non-virtual @@ -411,6 +419,7 @@ void DecalManager::renderDecals(dx9rend::IRenderView* view) // (nullsub_9, `retn 4`) - the console's `drawStats` setter (0x100BC19F). empty: the // console can read drawStats (+0x2A5) but never change it. Shipped. +// PE 0x10124130 void DecalManager::setDrawStats(bool enable) { } @@ -429,21 +438,23 @@ void DecalManager::recomputeFades() // the DecalAtlas entry for a texture name: 0 when the atlas holds no // entry at all (its map size, `cmp [eax+10h], 0; ja`), else the atlas's lookup of name + ".dds". // The atlas pointer is not tested. Caller: DecalTemplate::loadTexture (0x101AF89D). -dx9rend::TextureAtlasEntry* DecalManager::getAtlasEntry(const vc71::string& textureName) +// PE 0x10124350 +dx9rend::TextureAtlasEntry* DecalManager::getAtlasEntry(const std::string& textureName) { - if (m_atlas->entries.size == 0) + if (dx9rend::textureAtlasEntryCount(m_atlas) == 0) return 0; - const vc71::string key = concat(textureName, ".dds"); + const std::string key = concat(textureName, ".dds"); return dx9rend::textureAtlasFind(m_atlas, key); } // load "" into the atlas; false for an empty // name. Caller: initPool. -bool DecalManager::loadAtlas(const vc71::string& fileName) +// PE 0x101243C0 +bool DecalManager::loadAtlas(const std::string& fileName) { if (fileName.size() == 0) return false; - const vc71::string path = concat(s_atlasDirectory, fileName); // unk_1025BEBC + name + const std::string path = concat(s_atlasDirectory, fileName); // unk_1025BEBC + name return dx9rend::textureAtlasLoadTAI(m_atlas, path); } @@ -454,6 +465,7 @@ bool DecalManager::loadAtlas(const vc71::string& fileName) // the host's "GSUseEffectTextureAtlas" setting is true (SettingsRepostitory +0x50, default false), // loadAtlas("DecalAtlas.tai"). +// PE 0x10124450 void DecalManager::initPool() { m_poolSize = 0x800; @@ -464,18 +476,19 @@ void DecalManager::initPool() m_freeList = m_pool; if (dx9rend::readBoolSetting("GSUseEffectTextureAtlas", false)) // +0x50 - loadAtlas(vc71::string("DecalAtlas.tai")); + loadAtlas(std::string("DecalAtlas.tai")); } -// the listener's first half: a stack copy of `view` -// (Rend::RenderView's copy constructor, 0x10125960), and the renderer's collect over it and the -// active set. +// PE 0x10124570: the listener's first half, a stack copy of `view` +// (Rend::RenderView's implicit copy constructor, 0x10125960, cited at renderViewCopyConstruct in +// RendMisc/RenderView.cpp), and the renderer's collect over it and the +// active set. Unreachable in 1.50: no code or data references. void DecalManager::collectDecals(dx9rend::IRenderView& view) { union { double alignment; - unsigned char bytes[1072]; // [ebp-430h] + unsigned char bytes[dx9rend::kRenderViewObjectBytes]; // [ebp-430h], 1072 in retail } storage; dx9rend::IRenderView* const copy = Rend::renderViewCopyConstruct(storage.bytes, view); m_renderer.collect(*copy, m_activeInstances); @@ -488,14 +501,16 @@ void DecalManager::collectDecals(dx9rend::IRenderView& view) // An object the client set does not hold is NOT destroyed (it leaks) - shipped. The queue is then // resized to 0 (VC7.1 `resize(0)` - the buffer is kept). +// PE 0x101247B0 void DecalManager::flushDeletes() { - for (DecalObject** it = m_deleteQueue.begin(); it != m_deleteQueue.end(); ++it) + for (std::vector::iterator it = m_deleteQueue.begin(); it != m_deleteQueue.end(); + ++it) { DecalObject* const object = *it; if (object->activeFlag()) removeInstance(object); // [this] +0x28 - DecalObjectMap::Node* const found = m_clients.find(object); + const DecalObjectMap::iterator found = m_clients.find(object); if (found != m_clients.end()) { m_clients.erase(found); @@ -507,11 +522,13 @@ void DecalManager::flushDeletes() // the deferred removals: each queued object erased from the active set // when present, then the queue resized to 0. +// PE 0x10124880 void DecalManager::flushRemovals() { - for (DecalObject** it = m_removeQueue.begin(); it != m_removeQueue.end(); ++it) + for (std::vector::iterator it = m_removeQueue.begin(); it != m_removeQueue.end(); + ++it) { - DecalObjectMap::Node* const found = m_activeInstances.find(*it); + const DecalObjectMap::iterator found = m_activeInstances.find(*it); if (found != m_activeInstances.end()) m_activeInstances.erase(found); } @@ -525,21 +542,19 @@ void DecalManager::flushRemovals() // +0x34 and +0x78 cleared, in that order (+0x84 and the remove queue are left); templateCount = 0; // the renderer's empty reset (0x101A9AA0); the pool `delete[]`d (sub_1005F370) - the pool pointer // is NOT cleared; clearing = 0. - +// PE 0x10124970 void DecalManager::clear() { m_clearing = true; - for (DecalTemplateMap::Node* it = m_templates.begin(); it != m_templates.end(); - it = DecalTemplateMap::next(it)) + for (DecalTemplateMap::iterator it = m_templates.begin(); it != m_templates.end(); ++it) { - if (it->value) - delete it->value; // [t] +0xA0 (1) + if (it->second) + delete it->second; // [t] +0xA0 (1) } - for (DecalObjectMap::Node* it = m_clients.begin(); it != m_clients.end(); - it = DecalObjectMap::next(it)) + for (DecalObjectMap::iterator it = m_clients.begin(); it != m_clients.end(); ++it) { - if (it->value) - delete it->value; // [o] +0x00 (1) + if (it->second) + delete it->second; // [o] +0x00 (1) } m_deleteQueue.resize(0); // sub_101262A0(0, 0) m_templates.clear(); @@ -555,6 +570,7 @@ void DecalManager::clear() // (no reference) - `return templatesByIndex[index]` - operator[], so an unknown index // files a null entry. +// PE 0x10124BC0 DecalTemplate* DecalManager::getTemplateByIndex(unsigned short index) { return m_templatesByIndex[index]; @@ -564,25 +580,25 @@ DecalTemplate* DecalManager::getTemplateByIndex(unsigned short index) // Builds the decal atlas from named template textures beneath the editor save path. // Returns false only for an empty list; downstream builder failures are not propagated. -bool DecalManager::generateTexture(const vc71::string& atlasName) +// PE 0x10124CE0 +bool DecalManager::generateTexture(const std::string& atlasName) { - std::list files; - for (DecalTemplateMap::Node* it = m_templates.begin(); it != m_templates.end(); - it = DecalTemplateMap::next(it)) + std::list files; + for (DecalTemplateMap::iterator it = m_templates.begin(); it != m_templates.end(); ++it) { - IDecalTemplate* const decalTemplate = it->value; // node +0x28 + IDecalTemplate* const decalTemplate = it->second; // node +0x28 if (decalTemplate->getDecalTextureName().size() > 0) // +0x54 - files.push_back(concat(::renddx9abi::toVc71String( + files.push_back(concat(::renddx9abi::fromHostString( decalTemplate->getDecalTextureName()), ".dds")); // +0x54 again } - vc71::string modDirectory; + std::string modDirectory; dx9rend::readStringSettingDefault("GSModDirectory", "mods/bf2", modDirectory); // +0x40 - vc71::string levelSavePath; + std::string levelSavePath; dx9rend::readStringSettingDefault("Editor_LevelSavePath", modDirectory.c_str(), levelSavePath); // +0x40 - const vc71::string taiPath = + const std::string taiPath = concat(concat(concat(concat(levelSavePath, "/"), s_atlasDirectory), atlasName), ".tai"); ::renddx9abi::HostStream* const stream = ::dice::hfe::fileManager->open( ::renddx9abi::makeHostString(taiPath), static_cast(0), diff --git a/Code/BF2/Geom/DecalSystem/DecalManager.h b/Code/BF2/Geom/DecalSystem/DecalManager.h index 4b9b5c65c..08d348d70 100644 --- a/Code/BF2/Geom/DecalSystem/DecalManager.h +++ b/Code/BF2/Geom/DecalSystem/DecalManager.h @@ -1,7 +1,8 @@ // Path: [INFERRED] header beside DecalManager.cpp, attested at RendDX9 0x1021CA40. // Decal lifetime, template registry and rendering owner, recovered from RendDX9.dll 1.50. -// Retail layout: 0x2CC bytes in both plugin flavours; constructor 0x101251F0. -// VideoOptions writes enabled at +0x2A6 directly; preserve that offset. +// Retail layout: 0x2CC bytes; constructor 0x101251F0. The native object holds std containers, so +// its size and every offset from +0x34 on differ from retail; the `// +0xNN` comments are retail's. +// Callers outside this class reach the decals-enabled byte (retail +0x2A6) through setEnabledField. #ifndef BF2_GEOM_DECALSYSTEM_DECALMANAGER_H #define BF2_GEOM_DECALSYSTEM_DECALMANAGER_H @@ -14,9 +15,11 @@ #include "DecalRenderer.h" #include "../../RendDX9/RendDX9Base.h" // dx9rend::RenderPathListener #include "../../../RendDX9Abi/BfMemory.h" -#include "../../../RendDX9Abi/Vc71String.h" +#include +#include #include +#include namespace dice { namespace hfe { @@ -41,19 +44,17 @@ extern IBase* g_DecalManager; // The two maps the image only constructs / clears / destroys: +0x78 has a 0x38-byte node (a 28-byte // std::string key destroyed per node in sub_10126BD0, a 12-byte trivially destructible value); -// +0x84 a 0x18-byte node (4-byte key and value). [UNRESOLVED] types; see DecalContainers.h. +// +0x84 a 0x18-byte node (4-byte key and value). [UNRESOLVED] types; their comparators are never +// instantiated in the shipped image, so std::less stands in and nothing calls it. struct DecalUnreadValue12 { unsigned int words[3]; }; -typedef decalvc71::Map DecalTemplateMap; -typedef decalvc71::Map > DecalTemplateIndexMap; -typedef decalvc71::Map - DecalUnreadStringMap; -typedef decalvc71::Map > - DecalUnreadMap; +typedef std::map DecalTemplateMap; +typedef std::map DecalTemplateIndexMap; +typedef std::map DecalUnreadStringMap; +typedef std::map DecalUnreadMap; // Owns decal clients, templates, the pooled records and the embedded renderer. // update() drains deferred removal/deletion queues; release() on a client is not immediate. @@ -97,7 +98,7 @@ class DecalManager : public IDecalManager, public dx9rend::RenderPathListener // Draws the current frame's decals; unused is ignored. virtual void onRenderPathNotification(int unused) override; virtual int getCurrentRenderPath() const override; // +0x10 - virtual vc71::string getRenderPathListenerName() const override; // +0x14 + virtual std::string getRenderPathListenerName() const override; // +0x14 // non-virtual, in the image's order void renderDecals(dx9rend::IRenderView* view); // (unref) @@ -106,15 +107,15 @@ class DecalManager : public IDecalManager, public dx9rend::RenderPathListener bool getDrawStats() const { return m_drawStats; } void recomputeFades(); // (unref; // inlined in 5 slots) - dx9rend::TextureAtlasEntry* getAtlasEntry(const vc71::string& textureName); - bool loadAtlas(const vc71::string& fileName); + dx9rend::TextureAtlasEntry* getAtlasEntry(const std::string& textureName); + bool loadAtlas(const std::string& fileName); void initPool(); void collectDecals(dx9rend::IRenderView& view); // (unref) void flushDeletes(); void flushRemovals(); void clear(); DecalTemplate* getTemplateByIndex(unsigned short index); // (unref) - bool generateTexture(const vc71::string& atlasName); // (console) + bool generateTexture(const std::string& atlasName); // (console) // the inline surface DecalObject.cpp (D1) and DecalRenderer.cpp use // The pool pop DecalObject::add inlines (0x101AE555..0x101AE56B): the head, and the head's link @@ -125,6 +126,7 @@ class DecalManager : public IDecalManager, public dx9rend::RenderPathListener m_freeList = record ? record->next : 0; return record; } + // PE 0x101AC620 // emitted out of line in DecalObject.cpp's range, so an inline of // this header: free the record's vertex block (sub_1005F360) and null it, then push the record. void freeRecord(DecalRecord* record) @@ -139,8 +141,8 @@ class DecalManager : public IDecalManager, public dx9rend::RenderPathListener } bool isEnabled() const { return m_enabled; } // +0x2A6 // VideoOptions::apply's store (sub_1000FCB0, 0x1001032A: `setnle cl; mov [eax+2A6h], cl` - - // (videoOptions +0x3C) > 1). VideoOptions.cpp writes byte 678 raw today; this is the typed form - // the integrator can switch it to - the offset is asserted either way. + // (videoOptions +0x3C) > 1). The native m_enabled is not at +0x2A6, so the store must come + // through here. void setEnabledField(bool enabled) { m_enabled = enabled; } float decalNormalOffset() const { return m_decalNormalOffset; } // +0x2C0 float decalGeomClipAngle() const { return m_decalGeomClipAngle; } // +0x2C4 @@ -169,8 +171,8 @@ class DecalManager : public IDecalManager, public dx9rend::RenderPathListener DecalObjectMap m_clients; // +0x028 DecalObjectMap m_activeInstances; // +0x034 DecalTemplateMap m_templates; // +0x040 - decalvc71::Vector m_deleteQueue; // +0x04C - decalvc71::Vector m_removeQueue; // +0x05C + std::vector m_deleteQueue; // +0x04C + std::vector m_removeQueue; // +0x05C DecalTemplateIndexMap m_templatesByIndex; // +0x06C DecalUnreadStringMap m_map78; // +0x078 DecalUnreadMap m_map84; // +0x084 @@ -197,38 +199,16 @@ class DecalManager : public IDecalManager, public dx9rend::RenderPathListener friend struct DecalManagerLayoutCheck; }; -// Asserted in both flavours (x86): the object is the renderer's own, and VideoOptions::apply's raw -// write at +0x2A6 has to land on m_enabled whichever flavour is built. +// The prefix before the first std container keeps its retail offsets on x86 (BF2Render.cpp reaches +// the listener subobject at +0x04). Everything from m_activeInstances on is native. struct DecalManagerLayoutCheck { #if defined(_M_IX86) - static_assert(sizeof(DecalManager) == 0x2CC, "RefFactory_geom_DecalManager allocates 0x2CC"); static_assert(offsetof(DecalManager, m_renderPath) == 0x08, "listener +0x10 reads subobject+4"); static_assert(offsetof(DecalManager, m_refCount) == 0x0C, "ICF_incrementDwordAt0xC"); static_assert(offsetof(DecalManager, m_timeToLive) == 0x10, "+0x10"); static_assert(offsetof(DecalManager, m_lastDeltaTime) == 0x20, "+0x20"); static_assert(offsetof(DecalManager, m_clients) == 0x28, "+0x28"); - static_assert(offsetof(DecalManager, m_activeInstances) == 0x34, "+0x34"); - static_assert(offsetof(DecalManager, m_templates) == 0x40, "+0x40"); - static_assert(offsetof(DecalManager, m_deleteQueue) == 0x4C, "+0x4C"); - static_assert(offsetof(DecalManager, m_removeQueue) == 0x5C, "+0x5C"); - static_assert(offsetof(DecalManager, m_templatesByIndex) == 0x6C, "+0x6C"); - static_assert(offsetof(DecalManager, m_map78) == 0x78, "+0x78"); - static_assert(offsetof(DecalManager, m_map84) == 0x84, "+0x84"); - static_assert(offsetof(DecalManager, m_pool) == 0x90, "+0x90"); - static_assert(offsetof(DecalManager, m_renderer) == 0x94, "+0x94"); - static_assert(offsetof(DecalManager, m_freeList) == 0x290, "+0x290"); - static_assert(offsetof(DecalManager, m_poolSize) == 0x294, "+0x294"); - static_assert(offsetof(DecalManager, m_templateCount) == 0x298, "+0x298"); - static_assert(offsetof(DecalManager, m_dword29C) == 0x29C, "+0x29C"); - static_assert(offsetof(DecalManager, m_clearing) == 0x2A4, "+0x2A4"); - static_assert(offsetof(DecalManager, m_drawStats) == 0x2A5, "+0x2A5"); - static_assert(offsetof(DecalManager, m_enabled) == 0x2A6, "VideoOptions::apply writes +0x2A6"); - static_assert(offsetof(DecalManager, m_fadeDistance) == 0x2B0, "+0x2B0"); - static_assert(offsetof(DecalManager, m_minimumAlpha) == 0x2B8, "+0x2B8"); - static_assert(offsetof(DecalManager, m_decalNormalOffset) == 0x2C0, "+0x2C0"); - static_assert(offsetof(DecalManager, m_decalGeomClipAngle) == 0x2C4, "+0x2C4"); - static_assert(offsetof(DecalManager, m_atlas) == 0x2C8, "+0x2C8"); #endif }; diff --git a/Code/BF2/Geom/DecalSystem/DecalManagerConsole.cpp b/Code/BF2/Geom/DecalSystem/DecalManagerConsole.cpp index 0ea0fd64b..dd1feaf02 100644 --- a/Code/BF2/Geom/DecalSystem/DecalManagerConsole.cpp +++ b/Code/BF2/Geom/DecalSystem/DecalManagerConsole.cpp @@ -6,14 +6,13 @@ #include "../../../RendDX9Abi/PluginAbi.h" -#if BF2_PLUGIN_ABI_NATIVE #include "DecalManager.h" #include "../../Core/ConsoleObjectMacro.h" #include "../../Core/ConsoleObjects.h" #include "../../../RendDX9Abi/PluginEntry.h" -#include "../../../RendDX9Abi/Vc71String.h" +#include #include @@ -59,25 +58,34 @@ void setFadeOutPercentage(float value) { decalManager()->setFadeOutAtPercentage // with no argument: generateTexture(std::string("DecalAtlas")); the bool is the reply. bool generateDecalAtlas() { - return decalManager()->generateTexture(vc71::string("DecalAtlas")); + return decalManager()->generateTexture(std::string("DecalAtlas")); } BF2_CONSOLE_OBJECT("DecalManager", 2, 0) +// PE 0x100BC08D, 0x100BC10A, 0x100BC157: constructor, argument conversion, executor. BF2_CONSOLE_PROPERTY_FN(drawStats, bool, decalManager() != 0, getDrawStats(), setDrawStats, kDecalManagerConsoleTag) +// PE 0x100BC1A8, 0x100BC219: constructor, argument conversion. BF2_CONSOLE_PROPERTY_FN(decalNormalOffset, float, decalManager() != 0, getDecalNormalOffset(), setDecalNormalOffset, kDecalManagerConsoleTag) +// PE 0x100BC2AC, 0x100BC31D: constructor, argument conversion. BF2_CONSOLE_PROPERTY_FN(decalGeomClipAngle, float, decalManager() != 0, getDecalGeomClipAngle(), setDecalGeomClipAngle, kDecalManagerConsoleTag) +// PE 0x100BC3B0, 0x100BC421: constructor, argument conversion. BF2_CONSOLE_PROPERTY_FN(fadeDistance, float, decalManager() != 0, getFadeDistance(), setFadeDistance, kDecalManagerConsoleTag) +// PE 0x100BC4B7, 0x100BC528: constructor, argument conversion. BF2_CONSOLE_PROPERTY_FN(startFadePercentageOfFadeDistancel, float, decalManager() != 0, getStartFadePercentage(), setStartFadePercentage, kDecalManagerConsoleTag) +// PE 0x100BC5BE, 0x100BC62F: constructor, argument conversion. BF2_CONSOLE_PROPERTY_FN(timeToLive, float, decalManager() != 0, getTimeToLive(), setTimeToLive, kDecalManagerConsoleTag) +// PE 0x100BC6C5, 0x100BC736: constructor, argument conversion. BF2_CONSOLE_PROPERTY_FN(fadeOutAtPercentageOfTimeToLive, float, decalManager() != 0, getFadeOutPercentage(), setFadeOutPercentage, kDecalManagerConsoleTag) +// generateTexture: binding constructor PE 0x100BC7CC (Boolean result, no arguments). +// PE 0x100BC81F: executor. BF2_CONSOLE_METHOD_0_RET_ACTIVE(generateTexture, generateDecalAtlas, bool, decalManager() != 0, kDecalManagerConsoleTag) @@ -100,5 +108,4 @@ bool unregisterDecalManagerConsoleObjects() } // namespace hfe } // namespace dice -#endif // BF2_PLUGIN_ABI_NATIVE #endif // BF2_IMAGE_RENDDX9 diff --git a/Code/BF2/Geom/DecalSystem/DecalObject.cpp b/Code/BF2/Geom/DecalSystem/DecalObject.cpp index e43ed5da6..795dadc7d 100644 --- a/Code/BF2/Geom/DecalSystem/DecalObject.cpp +++ b/Code/BF2/Geom/DecalSystem/DecalObject.cpp @@ -3,27 +3,25 @@ #ifdef BF2_IMAGE_RENDDX9 +#if defined(__APPLE__) +#include "../../Platform/X87Compat.h" // [CHOSEN, not recovered] x87 conversion results, including invalid inputs. +#endif #include "DecalObject.h" #include "../../Math/Plane3.h" +#include "../../RendDX9/RendDX9Math.h" // the RendDX9.dll Math copies +#include "../../GeomMisc/Debug.h" #include "../../../RendDX9Abi/BfMemory.h" #include "../../../RendDX9Abi/Frontier.h" // The host (BF2.exe) interfaces add dispatches into, typed in both flavours (RW-266): each virtual // used below sits at its retail PE slot in this tree's MSVC table; no STL type crosses // those calls. IObject's +0x28 / +0x38 -// are its retail-aligned prefix (ObjectLayoutAccess). The retail-ABI flavour blocks Core/ClassManager.h -// exactly as SkinnedMesh.cpp does. -#if !BF2_PLUGIN_ABI_NATIVE -#define CORE_CLASSMANAGER_H -#endif +// are its retail-aligned prefix (ObjectLayoutAccess). #include "../../Game/Objects/ObjectLayoutAccess.h" // world::IObject + its retail-aligned prefix #include "../../Physics/ICollisionMesh.h" // hasLod / getVertexVector / getFaceCount / // getFaceVector #include "../../Physics/HeightmapCluster.h" // getPrimaryScale / getSquareInWorldCoords -#if !BF2_PLUGIN_ABI_NATIVE -#undef CORE_CLASSMANAGER_H -#endif #include #include @@ -37,6 +35,9 @@ namespace geom { extern IBase* g_DecalManager; // ModuleGeom.cpp, dword_1024B908 extern IBase* g_ParticleSystemManager; // ModuleGeom.cpp, dword_1024B900 +// ParticleSystemManager.cpp (published in ParticleSystemManager.h): the manager's HeightmapCluster +// pointer (retail +0x8C14), read without a null test on the manager. +IBase* particleSystemManagerHeightmapCluster(IBase* manager); // the per-face clip planes, a VC7.1 std::vector file static (constructed empty, // destroyed by the atexit thunk 0x101D9F90). File-private: nothing outside this file reads its @@ -120,12 +121,11 @@ IDecalManager* decalManager() } // ParticleSystemManager +0x8C14 - m_heightmapCluster, the "HeightmapCluster" singleton the particle -// system caches (0x100D2FD0). The struct is TU-local to ParticleSystemManager.cpp, which pins the -// offset (static_assert, line 219); this RendDX9-own field is read at that offset in both flavours. +// system caches (particleSystemManagerPostLoadLevel). The struct is TU-local to +// ParticleSystemManager.cpp, which publishes the read; retail loads the field directly. IBase* particleHeightmapCluster() { - return *reinterpret_cast( - reinterpret_cast(g_ParticleSystemManager) + 0x8C14); + return particleSystemManagerHeightmapCluster(g_ParticleSystemManager); } @@ -158,9 +158,19 @@ float clampValue(float value, float low, float high) // -20001, discarded by every caller here); otherwise each component is scaled by 1 / sqrt(|v|^2). int normalizeInPlace(Vec3& v) { +#if defined(__APPLE__) + // [CHOSEN, not recovered] PE 0x100777A0 spills the squared length, but not its reciprocal root. + using bf2x87::wide; + using bf2x87::store; + const float lengthSquared = store(wide(v.x) * wide(v.x) + wide(v.y) * wide(v.y) + + wide(v.z) * wide(v.z)); + if (bf2x87::abs(wide(lengthSquared) - wide(1.0f)) < wide(FLT_EPSILON)) + return 0; +#else const float lengthSquared = v.x * v.x + v.y * v.y + v.z * v.z; if (std::fabs(lengthSquared - 1.0f) < FLT_EPSILON) return 0; +#endif if (std::fabs(lengthSquared) < FLT_EPSILON) { v.x = 0.0f; @@ -168,33 +178,44 @@ int normalizeInPlace(Vec3& v) v.z = 0.0f; return -20001; } +#if defined(__APPLE__) + const bf2x87::Real inverse = wide(1.0f) / bf2x87::squareRoot(wide(lengthSquared)); + v.x = store(inverse * wide(v.x)); + v.y = store(inverse * wide(v.y)); + v.z = store(inverse * wide(v.z)); +#else const float inverse = 1.0f / std::sqrt(lengthSquared); v.x = inverse * v.x; v.y = inverse * v.y; v.z = inverse * v.z; +#endif return 0; } -// PE 0x1007C440 (83 B, thiscall on the matrix) - transformVector: the 3x3 part only. Every input is -// read before the first store, so `in` and `out` may alias. -void transformVector(const Mat4& m, const Vec3& in, Vec3& out) -{ - const float z = m.m[2] * in.x + m.m[10] * in.z + m.m[6] * in.y; - const float y = m.m[1] * in.x + m.m[9] * in.z + m.m[5] * in.y; - const float x = m.m[8] * in.z + m.m[4] * in.y + in.x * m.m[0]; - out.x = x; - out.y = y; - out.z = z; -} - // the plane through three points: normal = normalise((b - a) x // (c - a)), d = -(normal . a). The normal member is zeroed first (its constructor), as shipped. +// PE 0x101AEA50 Plane3 planeFromPoints(const Vec3& a, const Vec3& b, const Vec3& c) { Plane3 plane; plane.normal.x = 0.0f; plane.normal.y = 0.0f; plane.normal.z = 0.0f; +#if defined(__APPLE__) + // [CHOSEN, not recovered] Only the Z differences spill before the cross product. + using bf2x87::wide; + using bf2x87::store; + const bf2x87::Real ux = wide(c.x) - wide(a.x); + const bf2x87::Real uy = wide(c.y) - wide(a.y); + const float uz = store(wide(c.z) - wide(a.z)); + const bf2x87::Real vx = wide(b.x) - wide(a.x); + const bf2x87::Real vy = wide(b.y) - wide(a.y); + const float vz = store(wide(b.z) - wide(a.z)); + Vec3 normal; + normal.x = store(wide(uz) * vy - wide(vz) * uy); + normal.y = store(wide(vz) * ux - vx * wide(uz)); + normal.z = store(vx * uy - vy * ux); +#else const float ux = c.x - a.x; const float uy = c.y - a.y; const float uz = c.z - a.z; @@ -205,9 +226,15 @@ Plane3 planeFromPoints(const Vec3& a, const Vec3& b, const Vec3& c) normal.x = uz * vy - vz * uy; normal.y = vz * ux - vx * uz; normal.z = vx * uy - vy * ux; +#endif normalizeInPlace(normal); plane.normal = normal; +#if defined(__APPLE__) + plane.d = store(-(wide(normal.x) * wide(a.x) + wide(normal.y) * wide(a.y) + + wide(normal.z) * wide(a.z))); +#else plane.d = -(normal.x * a.x + normal.y * a.y + normal.z * a.z); +#endif return plane; } @@ -225,6 +252,18 @@ void planeAssign(Plane3& destination, const Plane3& source) Vec3 edgeNormal(const Vec3& from, const Vec3& to, const Vec3& faceNormal) { +#if defined(__APPLE__) + // [CHOSEN, not recovered] PE 0x101AD390 retains the X/Y edge differences. + using bf2x87::wide; + using bf2x87::store; + const bf2x87::Real ex = wide(to.x) - wide(from.x); + const bf2x87::Real ey = wide(to.y) - wide(from.y); + const float ez = store(wide(to.z) - wide(from.z)); + Vec3 normal; + normal.x = store(wide(faceNormal.z) * ey - wide(ez) * wide(faceNormal.y)); + normal.y = store(wide(ez) * wide(faceNormal.x) - wide(faceNormal.z) * ex); + normal.z = store(ex * wide(faceNormal.y) - ey * wide(faceNormal.x)); +#else const float ex = to.x - from.x; const float ey = to.y - from.y; const float ez = to.z - from.z; @@ -232,6 +271,7 @@ Vec3 edgeNormal(const Vec3& from, const Vec3& to, const Vec3& faceNormal) normal.x = faceNormal.z * ey - ez * faceNormal.y; normal.y = ez * faceNormal.x - faceNormal.z * ex; normal.z = ex * faceNormal.y - ey * faceNormal.x; +#endif normalizeInPlace(normal); return normal; } @@ -293,8 +333,16 @@ unsigned char computeOutcode(const Vec3& point, const std::vector& plane for (unsigned int i = 0; i < planes.size(); ++i) { const Plane3& plane = planes[i]; +#if defined(__APPLE__) + // [CHOSEN, not recovered] PE 0x101AECD0 compares the retained dot product. + const bf2x87::Real distance = + bf2x87::wide(plane.normal.z) * bf2x87::wide(point.z) + + bf2x87::wide(plane.normal.x) * bf2x87::wide(point.x) + + bf2x87::wide(point.y) * bf2x87::wide(plane.normal.y) + bf2x87::wide(plane.d); +#else const float distance = plane.normal.z * point.z + plane.normal.x * point.x + point.y * plane.normal.y + plane.d; +#endif if (distance > 0.0f) code = static_cast(code | static_cast(1u << i)); } @@ -311,12 +359,24 @@ void emitVertex(DecalRecord* record, const DecalVertex& source, const Plane3& fa target = source; if (s_projectOntoFacePlane) { +#if defined(__APPLE__) + // [CHOSEN, not recovered] PE 0x101AD751..0x101AD797 spills only the Y/Z pushes. + using bf2x87::wide; + using bf2x87::store; + const bf2x87::Real distance = wide(facePlane.normal.y) * wide(target.position.y) + + wide(facePlane.normal.z) * wide(target.position.z) + + wide(facePlane.normal.x) * wide(target.position.x) + wide(facePlane.d); + const float pushY = store(wide(facePlane.normal.y) * distance); + const float pushZ = store(wide(facePlane.normal.z) * distance); + target.position.x = store(wide(target.position.x) - wide(facePlane.normal.x) * distance); +#else const float distance = facePlane.normal.y * target.position.y + facePlane.normal.z * target.position.z + facePlane.normal.x * target.position.x + facePlane.d; const float pushY = facePlane.normal.y * distance; const float pushZ = facePlane.normal.z * distance; target.position.x = target.position.x - facePlane.normal.x * distance; +#endif target.position.y = target.position.y - pushY; target.position.z = target.position.z - pushZ; } @@ -347,9 +407,18 @@ void setupQuad(QuadSetup& setup, const DecalRecord* record, const IDecalTemplate const float rotationDraw = randomSymmetric(); const float randomRotation = decalTemplate->getRandomRotation() * rotationDraw; // +0x44 // The product stays in st(0) through fcos / fsin (never stored first). +#if defined(__APPLE__) + // [CHOSEN, not recovered] FCOS and FSIN receive the retained angle, not its float rounding. + using bf2x87::wide; + using bf2x87::store; + const bf2x87::Real angle = (wide(decalTemplate->getRotation()) + wide(randomRotation)) * wide(s_degreesToRadians); + setup.cosine = store(bf2x87::cosValue(angle)); + setup.sine = store(bf2x87::sinValue(angle)); +#else const float angle = (decalTemplate->getRotation() + randomRotation) * s_degreesToRadians; // +0x4C setup.cosine = static_cast(std::cos(static_cast(angle))); setup.sine = static_cast(std::sin(static_cast(angle))); +#endif const float sizeDraw = randomSymmetric(); setup.randomSize = decalTemplate->getRandomSize() * sizeDraw; // +0x14 @@ -362,15 +431,28 @@ void setupQuad(QuadSetup& setup, const DecalRecord* record, const IDecalTemplate { // fistp in truncation mode, then an unsigned divide by the frames across - no guard // against a zero divisor, as shipped. +#if defined(__APPLE__) + const unsigned int frame = + static_cast(bf2x87::toIntTruncate(record->startFrame)); +#else const unsigned int frame = static_cast(static_cast(record->startFrame)); +#endif const unsigned int column = frame % decal_template_state::animationFrameCountX(decalTemplate); const Vec2& extent = decal_template_state::uvExtent(decalTemplate); +#if defined(__APPLE__) + setup.originU = store(wide(column) * wide(extent.x) + + wide(decal_template_state::uvOffset(decalTemplate).x)); + setup.originV = store(wide(frame - column) + * wide(decal_template_state::frameCountXReciprocal(decalTemplate)) * wide(extent.y) + + wide(decal_template_state::uvOffset(decalTemplate).y)); +#else setup.originU = static_cast(column) * extent.x + decal_template_state::uvOffset(decalTemplate).x; setup.originV = static_cast(frame - column) * decal_template_state::frameCountXReciprocal(decalTemplate) * extent.y + decal_template_state::uvOffset(decalTemplate).y; +#endif } } @@ -392,6 +474,8 @@ void DecalObject::operator delete(void* block) noexcept // in the image's store order. The block is not null-tested: an // allocation failure faults on the first terminator store, as shipped. +// PE 0x101AC7B0 (also 0x101AC7BB). +// The analysis splits this one body at 0x101AC7BB, after the owner test; the tail's stores equal the ones below. DecalObject::DecalObject(world::IObject* owner) { m_count = 0; @@ -421,6 +505,7 @@ DecalObject::DecalObject(world::IObject* owner) // (complete, unreferenced) / 0x101AEC80 (scalar deleting, +0x00): clear by a direct call, // leave the manager's active set, free the block (operator delete[], sub_1005F370). +// PE 0x101AD010 DecalObject::~DecalObject() { DecalObject::clear(); @@ -429,6 +514,7 @@ DecalObject::~DecalObject() } +// PE 0x101AC670 void DecalObject::setShadowRecord(void* record) // +0x04, { m_shadowRecord = record; @@ -439,6 +525,7 @@ void* DecalObject::getShadowRecord() const // +0x08, return m_shadowRecord; } +// PE 0x101AC690 void DecalObject::setVisible(bool visible) // +0x0C, both bytes { m_visible = visible; @@ -466,6 +553,7 @@ void DecalObject::release() // (38 B, retn 4). No bound: the eighth static's terminator lands in m_ring[0]. +// PE 0x101AC6F0 void DecalObject::pushStatic(DecalRecord* record) { m_static[m_staticCount] = record; @@ -474,6 +562,7 @@ void DecalObject::pushStatic(DecalRecord* record) } // (76 B, retn 4). An empty ring restarts at slot 0 (oldest 0, insert 1). +// PE 0x101AC720 void DecalObject::pushRing(DecalRecord* record) { if (m_count == 0) @@ -501,9 +590,21 @@ DecalRecord* DecalObject::popRing() return record; } +// retn 8, thiscall: the static list's swap-with-last removal of slot `index`, as clear and remove +// inline it. The first argument is pushed by nobody and never read. +// unreachable in 1.50: no code or data references +// PE 0x101AC6C0 +void DecalObject::removeStaticAt(DecalRecord* /*record*/, unsigned int index) +{ + --m_staticCount; + m_static[index] = m_static[m_staticCount]; + m_static[m_staticCount] = 0; +} + // +0x14, drain the ring oldest first, then the statics (swap-with-last from // slot 0), then zero both ring cursors. The manager is NOT told: the object stays in the active // set until update finds it empty. +// PE 0x101AC840 void DecalObject::clear() { while (m_count > 0) @@ -523,6 +624,7 @@ void DecalObject::clear() // +0x1C, drop one static decal by id. The id compares zero-extended // against the whole argument, so no argument above 255 ever matches. Ring decals are never // removable this way. The manager is not told. +// PE 0x101ACEB0 void DecalObject::remove(unsigned int decalId) { if (!decalId) @@ -551,6 +653,7 @@ void DecalObject::remove(unsigned int decalId) // (asked again here, +0x38 - the record's own +0x38 is not read); // * an object left with no decal at all leaves the active set. // Always answers true (`mov al, 1`); the manager ignores it. +// PE 0x101ACF30 bool DecalObject::update(float deltaTime) { if (!m_owner) @@ -581,10 +684,15 @@ bool DecalObject::update(float deltaTime) // add - +0x18, 0x101AE4B0 (941 B, retn 14h) +// PE 0x101AE4B0 unsigned int DecalObject::add(const Mat4* transform, const IDecalTemplate* decalTemplate, float scale, world::ICollisionMesh* collisionMesh, world::CollisionFaceInfo* faceInfo) { +#if defined(__APPLE__) + using bf2x87::wide; + using bf2x87::store; +#endif if (!decal_manager_state::decalsEnabled()) // manager +0x2A6 return 0; // An object nobody drew last frame takes static decals only. @@ -609,14 +717,32 @@ unsigned int DecalObject::add(const Mat4* transform, const IDecalTemplate* decal // truncated (fistp, chop) and packed 0xFFrrggbb. Hex-Rays drops the clamp's answer; the // instruction stream uses it for all three channels. const float colorDraw = randomSymmetric(); +#if defined(__APPLE__) + // [CHOSEN, not recovered] Preserve the one argument spill before the clamp call. + const float intensity = clampValue(store(wide(decalTemplate->getRandomColorIntensity()) + * wide(colorDraw) + wide(1.0f)), 0.0f, 1.0f); +#else const float intensity = clampValue( decalTemplate->getRandomColorIntensity() * colorDraw + 1.0f, 0.0f, 1.0f); // +0x1C +#endif const Vec4& color = decal_template_state::color(decalTemplate); +#if defined(__APPLE__) + const int red = bf2x87::toIntTruncate(wide(intensity) * wide(color.x) * wide(255.0f)); +#else const int red = static_cast(intensity * color.x * 255.0f); +#endif unsigned int packed = (static_cast(red) | 0xFFFFFF00u) << 8; +#if defined(__APPLE__) + const int green = bf2x87::toIntTruncate(wide(intensity) * wide(color.y) * wide(255.0f)); +#else const int green = static_cast(intensity * color.y * 255.0f); +#endif packed = (packed | (static_cast(green) & 0xFFu)) << 8; +#if defined(__APPLE__) + const int blue = bf2x87::toIntTruncate(wide(intensity) * wide(color.z) * wide(255.0f)); +#else const int blue = static_cast(intensity * color.z * 255.0f); +#endif packed |= static_cast(blue) & 0xFFu; record->diffuse = packed; @@ -624,9 +750,15 @@ unsigned int DecalObject::add(const Mat4* transform, const IDecalTemplate* decal { const int frameDraw = randomInteger(); // (draw * (count - 1)) * 2^-24, the count unsigned: a zero count wraps to 2^32 - 1. +#if defined(__APPLE__) + record->startFrame = store(wide(frameDraw) + * wide(decal_template_state::animationFrameCount(decalTemplate) - 1u) + * wide(5.9604644775390625e-08f)); +#else record->startFrame = static_cast(frameDraw) * static_cast(decal_template_state::animationFrameCount(decalTemplate) - 1u) * 5.9604644775390625e-08f; +#endif } else { @@ -640,12 +772,12 @@ unsigned int DecalObject::add(const Mat4* transform, const IDecalTemplate* decal { const Mat4& inverse = m_owner->getInvAbsoluteTransformation(); // IObject PE +0x84 const Mat4 copy = local; - local.mult(copy, inverse); + rendmath::mult(local, copy, inverse); // PE 0x10077C50 Vec3 row1; row1.x = transform->m[4]; row1.y = transform->m[5]; row1.z = transform->m[6]; - transformVector(inverse, row1, record->normal); + rendmath::transformVector(inverse, row1, record->normal); // sub_1007C440 } else { @@ -774,11 +906,17 @@ void DecalObject::buildQuad(DecalRecord* record, const Mat4* transform, // An object decal with no collision face - PlayerControlObject's driver tags pass (0, 0) - takes // the terrain arm with its owner-space translation as world x / z. Shipped, kept. +// PE 0x101ADF80 void DecalObject::buildProjected(DecalRecord* record, const Mat4* transform, const IDecalTemplate* decalTemplate, float scale, world::ICollisionMesh* collisionMesh, world::CollisionFaceInfo* faceInfo) { +#if defined(__APPLE__) + // [CHOSEN, not recovered] Preserve the x87 expression order and explicit float stores. + using bf2x87::wide; + using bf2x87::store; +#endif QuadSetup setup; setupQuad(setup, record, decalTemplate); @@ -787,26 +925,46 @@ void DecalObject::buildProjected(DecalRecord* record, const Mat4* transform, { const DecalVertex& source = s_quadTemplate[i]; DecalVertex& corner = s_quad[i]; +#if defined(__APPLE__) + corner.position.x = store(wide(setup.cosine) * wide(source.position.x) - wide(setup.sine) * wide(source.position.z)); + corner.position.z = store(wide(setup.sine) * wide(source.position.x) + wide(setup.cosine) * wide(source.position.z)); + const bf2x87::Real size = (wide(decalTemplate->getSize()) + wide(setup.randomSize)) * wide(scale); + corner.position.x = store(size * wide(corner.position.x)); + corner.position.y = store(size * wide(corner.position.y)); + corner.position.z = store(size * wide(corner.position.z)); +#else corner.position.x = setup.cosine * source.position.x - setup.sine * source.position.z; corner.position.z = setup.sine * source.position.x + setup.cosine * source.position.z; const float size = (decalTemplate->getSize() + setup.randomSize) * scale; // +0x0C per corner corner.position.x = size * corner.position.x; corner.position.y = size * corner.position.y; corner.position.z = size * corner.position.z; +#endif corner.u = source.u; corner.v = source.v; const Vec2& extent = decal_template_state::uvExtent(decalTemplate); +#if defined(__APPLE__) + corner.u = store((wide(corner.u) + wide(1.0f)) * wide(extent.x) * wide(0.5f)); + corner.v = store((wide(corner.v) + wide(1.0f)) * wide(extent.y) * wide(0.5f)); +#else corner.u = (corner.u + 1.0f) * extent.x * 0.5f; corner.v = (corner.v + 1.0f) * extent.y * 0.5f; +#endif corner.u = setup.originU + corner.u; corner.v = setup.originV + corner.v; const float x = corner.position.x; const float y = corner.position.y; const float z = corner.position.z; +#if defined(__APPLE__) + const float tz = store(wide(m.m[10]) * wide(z) + wide(y) * wide(m.m[6]) + wide(m.m[2]) * wide(x) + wide(m.m[14])); + const float ty = store(wide(m.m[9]) * wide(z) + wide(m.m[5]) * wide(y) + wide(m.m[1]) * wide(x) + wide(m.m[13])); + const float tx = store(wide(m.m[0]) * wide(x) + wide(m.m[8]) * wide(z) + wide(y) * wide(m.m[4]) + wide(m.m[12])); +#else const float tz = m.m[10] * z + y * m.m[6] + m.m[2] * x + m.m[14]; const float ty = m.m[9] * z + m.m[5] * y + m.m[1] * x + m.m[13]; const float tx = m.m[0] * x + m.m[8] * z + y * m.m[4] + m.m[12]; +#endif corner.position.x = tx; corner.position.y = ty; corner.position.z = tz; @@ -864,7 +1022,9 @@ void DecalObject::buildProjected(DecalRecord* record, const Mat4* transform, if (!vertices) { // vertexCount keeps its value with a null block - the render pass would walk it. Shipped. - ::renddx9abi::logf("DecalObject.cpp:370 Failed to allocate geometry mem"); // 0x172 + ::renddx9abi::Debug(DebugTypeError, + "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\DecalSystem\\DecalObject.cpp", + 370, "") << "Failed to allocate geometry mem"; return; } std::memcpy(vertices, s_geometry, count * sizeof(DecalVertex)); @@ -876,6 +1036,7 @@ void DecalObject::buildProjected(DecalRecord* record, const Mat4* transform, // flipped) - or the sentinel 0x1267 when the centre square did not answer, which reports false. // Every cell is asked even after a miss; the cluster and its scale are fetched once. +// PE 0x101ACDB0 bool DecalObject::getTerrainPatch(float x, float z, Vec3* vertices, unsigned int* face) { world::IHeightmapCluster* const cluster = static_cast( @@ -910,6 +1071,7 @@ bool DecalObject::getTerrainPatch(float x, float z, Vec3* vertices, unsigned int // Reaching 128 vertices clears the whole record at that recursion level; callers continue. // Stops on depth exhaustion, complete containment, or clip rejection. +// PE 0x101AD5E0 void DecalObject::projectOntoFace(unsigned int face, const Vec3& direction, const DecalVertex* quad, DecalRecord* record, float maxAngle, int depth, const Vec3* vertices, const DecalFace* faces, int faceCount, @@ -921,7 +1083,8 @@ void DecalObject::projectOntoFace(unsigned int face, const Vec3& direction, cons if (!buildClipPlanes(face, direction, maxAngle, vertices, faces, faceCount)) return; - // [CHOSEN] initialised: retail leaves the out-pointer unwritten when the clip rejects (-1), and + // [CHOSEN, not recovered] PE 0x101AD660 reads an unwritten out-pointer when clipping rejects. + // Keep it initialized: retail leaves the out-pointer unwritten when the clip rejects (-1), and // its first test below then compares that garbage with `quad` - either way the -1 test returns. const DecalVertex* clipped = 0; const int clippedCount = clipPolygon(quad, 4, s_clipPlanes, &clipped); @@ -996,6 +1159,7 @@ void DecalObject::projectOntoFace(unsigned int face, const Vec3& direction, cons // normalise(edge x normal) - pointing out of the triangle for the face winding - are pushed. The // three d's use different association orders, kept. faceCount is not read. +// PE 0x101AD390 bool DecalObject::buildClipPlanes(unsigned int face, const Vec3& direction, float maxAngle, const Vec3* vertices, const DecalFace* faces, int faceCount) { @@ -1008,6 +1172,16 @@ bool DecalObject::buildClipPlanes(unsigned int face, const Vec3& direction, floa if (maxAngle > 0.0f) // `test ah, 41h; jnz` { +#if defined(__APPLE__) + // [CHOSEN, not recovered] Spill the clamp argument; retain the angle limit product. + const float cosine = clampValue(clampValue(bf2x87::store( + bf2x87::wide(normal.z) * bf2x87::wide(direction.z) + + bf2x87::wide(normal.y) * bf2x87::wide(direction.y) + + bf2x87::wide(normal.x) * bf2x87::wide(direction.x)), -1.0f, 1.0f), -1.0f, 1.0f); + const double angle = std::acos(static_cast(cosine)); + if (bf2x87::wide(s_degreesToRadians) * bf2x87::wide(maxAngle) < bf2x87::wide(angle)) + return false; +#else const float cosine = clampValue( clampValue(normal.z * direction.z + normal.y * direction.y + normal.x * direction.x, -1.0f, 1.0f), @@ -1015,17 +1189,35 @@ bool DecalObject::buildClipPlanes(unsigned int face, const Vec3& direction, floa const double angle = std::acos(static_cast(cosine)); // _CIacos if (static_cast(s_degreesToRadians * maxAngle) < angle) // unordered keeps it return false; +#endif } Plane3 edge0; edge0.normal = edgeNormal(p0, p1, normal); +#if defined(__APPLE__) + using bf2x87::wide; + using bf2x87::store; + edge0.d = store(-(wide(edge0.normal.x) * wide(p0.x) + wide(edge0.normal.y) * wide(p0.y) + + wide(edge0.normal.z) * wide(p0.z))); +#else edge0.d = -(edge0.normal.x * p0.x + edge0.normal.y * p0.y + edge0.normal.z * p0.z); +#endif Plane3 edge1; edge1.normal = edgeNormal(p1, p2, normal); +#if defined(__APPLE__) + edge1.d = store(-(wide(edge1.normal.x) * wide(p1.x) + wide(edge1.normal.z) * wide(p1.z) + + wide(edge1.normal.y) * wide(p1.y))); +#else edge1.d = -(edge1.normal.x * p1.x + edge1.normal.z * p1.z + edge1.normal.y * p1.y); +#endif Plane3 edge2; edge2.normal = edgeNormal(p2, p0, normal); +#if defined(__APPLE__) + edge2.d = store(-(wide(edge2.normal.x) * wide(p2.x) + wide(edge2.normal.z) * wide(p2.z) + + wide(edge2.normal.y) * wide(p2.y))); +#else edge2.d = -(edge2.normal.x * p2.x + edge2.normal.z * p2.z + edge2.normal.y * p2.y); +#endif s_clipPlanes.planes.push_back(edge0); s_clipPlanes.planes.push_back(edge1); @@ -1034,10 +1226,98 @@ bool DecalObject::buildClipPlanes(unsigned int face, const Vec3& direction, floa } +// The collision-mesh flood that collects clip planes without projecting: the face's three edge +// planes, then for each adjacent face either its shared edge plane joins the clip set (the neighbour's +// normal is more than maxAngle degrees from the projection direction) or, while depth remains and the +// neighbour is unvisited, the flood recurses into it. The edge planes are built exactly as +// buildClipPlanes builds them. The adjacency answer is ignored, as shipped; the neighbour triple is +// initialised to the 0xFFFF terminator here, where the shipped stack buffer is uninitialised when the +// mesh refuses ([CHOSEN, not recovered] memory-safety exception). Callers pass collisionMesh and +// faceInfo; the shipped body tests only collisionMesh and hasLod. +// unreachable in 1.50: no code or data references. [INFERRED] name. +// PE 0x101ADB50 +void DecalObject::collectClipPlanes(unsigned int face, const Vec3& direction, float maxAngle, + world::ICollisionMesh* collisionMesh, int depth, + world::CollisionFaceInfo* faceInfo) +{ + if (!collisionMesh) + return; + if (!collisionMesh->hasLod(faceInfoLod(faceInfo))) // +0x28, `test al, al` + return; + const Vec3* const vertices = static_cast( + collisionMesh->getVertexVector(faceInfoLod(faceInfo))); // +0x40 + const DecalFace* const faces = static_cast( + collisionMesh->getFaceVector(faceInfoLod(faceInfo))); // +0x4C + + s_visitedFaces.insert(static_cast(face)); + + const DecalFace& corners = faces[face]; + const Vec3& p0 = vertices[corners.v0]; + const Vec3& p1 = vertices[corners.v1]; + const Vec3& p2 = vertices[corners.v2]; + const Plane3 facePlane = planeFromPoints(p0, p1, p2); + const Vec3& normal = facePlane.normal; + + Plane3 edges[3]; + edges[0].normal = edgeNormal(p0, p1, normal); + edges[1].normal = edgeNormal(p1, p2, normal); + edges[2].normal = edgeNormal(p2, p0, normal); +#if defined(__APPLE__) + { + using bf2x87::wide; + using bf2x87::store; + edges[0].d = store(-(wide(edges[0].normal.x) * wide(p0.x) + wide(edges[0].normal.y) * wide(p0.y) + + wide(edges[0].normal.z) * wide(p0.z))); + edges[1].d = store(-(wide(edges[1].normal.x) * wide(p1.x) + wide(edges[1].normal.z) * wide(p1.z) + + wide(edges[1].normal.y) * wide(p1.y))); + edges[2].d = store(-(wide(edges[2].normal.x) * wide(p2.x) + wide(edges[2].normal.z) * wide(p2.z) + + wide(edges[2].normal.y) * wide(p2.y))); + } +#else + edges[0].d = -(edges[0].normal.x * p0.x + edges[0].normal.y * p0.y + edges[0].normal.z * p0.z); + edges[1].d = -(edges[1].normal.x * p1.x + edges[1].normal.z * p1.z + edges[1].normal.y * p1.y); + edges[2].d = -(edges[2].normal.x * p2.x + edges[2].normal.z * p2.z + edges[2].normal.y * p2.y); +#endif + + unsigned short neighbours[3] = { 0xFFFFu, 0xFFFFu, 0xFFFFu }; + collisionMeshAdjacentFaces(collisionMesh, faceInfoGeometry(faceInfo), faceInfoLod(faceInfo), + face, neighbours); // +0x38, result unread + + for (int k = 0; k < 3; ++k) + { + const unsigned short next = neighbours[k]; + if (next == 0xFFFFu) + continue; + const DecalFace& other = faces[next]; + const Vec3 neighbourNormal = planeFromPoints(vertices[other.v0], vertices[other.v1], + vertices[other.v2]).normal; +#if defined(__APPLE__) + const float cosine = clampValue(clampValue(bf2x87::store( + bf2x87::wide(neighbourNormal.z) * bf2x87::wide(direction.z) + + bf2x87::wide(neighbourNormal.y) * bf2x87::wide(direction.y) + + bf2x87::wide(neighbourNormal.x) * bf2x87::wide(direction.x)), -1.0f, 1.0f), -1.0f, 1.0f); + const double angle = std::acos(static_cast(cosine)); + const bool steep = bf2x87::wide(s_degreesToRadians) * bf2x87::wide(maxAngle) < bf2x87::wide(angle); +#else + const float cosine = clampValue( + clampValue(neighbourNormal.z * direction.z + neighbourNormal.y * direction.y + + neighbourNormal.x * direction.x, -1.0f, 1.0f), -1.0f, 1.0f); + const double angle = std::acos(static_cast(cosine)); // _CIacos + const bool steep = static_cast(s_degreesToRadians * maxAngle) < angle; +#endif + if (steep) + s_clipPlanes.planes.push_back(edges[k]); + else if (depth > 0 && s_visitedFaces.find(next) == s_visitedFaces.end()) + collectClipPlanes(next, direction, maxAngle, collisionMesh, depth - 1, faceInfo); + } +} + + // Clips against planes and returns the vertex count, with output pointing to input or // scratch storage. Returns -1 for a near-parallel crossing. The zero-seeded rejection // mask never rejects early; wholly outside polygons are clipped down to zero vertices. +// PE 0x101AD040 int DecalObject::clipPolygon(const DecalVertex* input, unsigned int count, const DecalClipPlanes& clip, const DecalVertex** output) { @@ -1100,6 +1380,28 @@ int DecalObject::clipPolygon(const DecalVertex* input, unsigned int count, const float dx = b.position.x - a.position.x; const float dy = b.position.y - a.position.y; const float dz = b.position.z - a.position.z; +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain denominator, ratio and UV deltas; preserve spills. + using bf2x87::wide; + using bf2x87::store; + const bf2x87::Real du = wide(b.u) - wide(a.u); + const bf2x87::Real dv = wide(b.v) - wide(a.v); + const bf2x87::Real denominator = wide(dz) * wide(plane.normal.z) + + wide(dx) * wide(plane.normal.x) + wide(dy) * wide(plane.normal.y); + if (bf2x87::abs(denominator) < wide(FLT_EPSILON)) + return -1; + const bf2x87::Real distance = wide(a.position.z) * wide(plane.normal.z) + + wide(plane.normal.y) * wide(a.position.y) + + wide(a.position.x) * wide(plane.normal.x) + wide(plane.d); + const bf2x87::Real t = distance * (wide(-1.0f) / denominator); + const float stepY = store(wide(dy) * t); + const float stepZ = store(wide(dz) * t); + out->position.x = store(wide(dx) * t + wide(a.position.x)); + out->position.y = stepY + a.position.y; + out->position.z = stepZ + a.position.z; + const float stepU = store(du * t); + const float stepV = store(dv * t); +#else const float du = b.u - a.u; const float dv = b.v - a.v; const float denominator = @@ -1116,6 +1418,7 @@ int DecalObject::clipPolygon(const DecalVertex* input, unsigned int count, out->position.z = stepZ + a.position.z; const float stepU = du * t; const float stepV = dv * t; +#endif out->u = stepU + a.u; out->v = stepV + a.v; nextCodes[produced] = computeOutcode(out->position, planes); diff --git a/Code/BF2/Geom/DecalSystem/DecalObject.h b/Code/BF2/Geom/DecalSystem/DecalObject.h index 2702cb26e..8d25b296e 100644 --- a/Code/BF2/Geom/DecalSystem/DecalObject.h +++ b/Code/BF2/Geom/DecalSystem/DecalObject.h @@ -187,6 +187,7 @@ class DecalObject : public IDecalObject void pushStatic(DecalRecord* record); void pushRing(DecalRecord* record); DecalRecord* popRing(); + void removeStaticAt(DecalRecord* record, unsigned int index); // PE 0x101AC6C0, unreferenced // add's two geometry builders and the projection they share (thiscall in the image; // `this` is passed and unused) @@ -197,6 +198,9 @@ class DecalObject : public IDecalObject world::ICollisionMesh* collisionMesh, world::CollisionFaceInfo* faceInfo); // (retn 18h) bool getTerrainPatch(float x, float z, Vec3* vertices, unsigned int* face); // (retn 10h) + void collectClipPlanes(unsigned int face, const Vec3& direction, float maxAngle, + world::ICollisionMesh* collisionMesh, int depth, + world::CollisionFaceInfo* faceInfo); // PE 0x101ADB50 (retn 18h), unreferenced void projectOntoFace(unsigned int face, const Vec3& direction, const DecalVertex* quad, DecalRecord* record, float maxAngle, int depth, const Vec3* vertices, const DecalFace* faces, int faceCount, @@ -244,11 +248,12 @@ class DecalObject : public IDecalObject // either object crosses the host boundary, so the layout is the same in both RendDX9 flavours. struct DecalObjectLayoutCheck { + // The host's collision-face array is read through this view: every architecture. + static_assert(sizeof(DecalFace) == 8, "the collision face stride is 8 ([face*8])"); #if defined(_M_IX86) static_assert(sizeof(DecalVertex) == 0x14, "the decal vertex stride is 20 (lea [n+n*4]*4)"); static_assert(offsetof(DecalVertex, u) == 0x0C, "u at +0x0C"); static_assert(offsetof(DecalVertex, v) == 0x10, "v at +0x10"); - static_assert(sizeof(DecalFace) == 8, "the collision face stride is 8 ([face*8])"); static_assert(sizeof(DecalRecord) == 0x58, "the pool stride is 0x58 (sub_10124450)"); static_assert(offsetof(DecalRecord, position) == 0x04, "+0x04"); static_assert(offsetof(DecalRecord, diffuse) == 0x14, "+0x14"); @@ -302,7 +307,7 @@ bool decalsEnabled(); // +0x2A6 byte (VideoOptions::ap // The free-list pop add inlines (0x101AE55B..0x101AE56B): `head = head ? head->next : 0` and the // OLD head is answered unchecked - an exhausted pool hands back 0 and add writes its +0x50 at once. DecalRecord* allocateRecord(); // +0x290 -// DecalManager::freeRecord [D2's name] - 0x101AC620 (53 B, retn 4, thiscall on the manager), the +// DecalManager::freeRecord [D2's name] - PE 0x101AC620 (53 B, retn 4, thiscall on the manager), the // out-of-line copy of the inline member clear, remove, update and add's eviction all inline: // if (record->vertices) { delete record->vertices; record->vertices = 0; } // record->next = m_freeRecords; m_freeRecords = record; // +0x290 @@ -329,10 +334,10 @@ float frameCountXReciprocal(const IDecalTemplate* decalTemplate); // + const Vec2& uvExtent(const IDecalTemplate* decalTemplate); // +0xA0 (D2 m_uvExtent) } -// PE 0x1009EF30 (lcgrand_step) on the renderer-local Random at the ONE stream the -// particle system and the decals draw from. The tree keeps that stream file-static in -// ParticleSystemManager.cpp's anonymous namespace (psmType0Random / psmEmissionRaw); the integrator -// exposes it under this name. Declared, not defined. +// One lcgrand_step (Geom/LcgRandom.h's lcgrandStep, the same retail function) on the renderer-local +// Random at the ONE stream the particle system and the decals draw from. The tree keeps that stream +// file-static in ParticleSystemManager.cpp's anonymous namespace (psmType0Random / psmEmissionRaw); +// the integrator exposes it under this name. Declared, not defined. unsigned int rendererRandomRaw(); } // namespace geom diff --git a/Code/BF2/Geom/DecalSystem/DecalRenderer.cpp b/Code/BF2/Geom/DecalSystem/DecalRenderer.cpp index fc62c4db0..cde7c1be8 100644 --- a/Code/BF2/Geom/DecalSystem/DecalRenderer.cpp +++ b/Code/BF2/Geom/DecalSystem/DecalRenderer.cpp @@ -18,7 +18,10 @@ #include "../../RendDX9/ShaderParameter.h" #include "../../RendMisc/IRenderView.h" #include "../../RendMisc/IRenderer.h" -#include "../../../RendDX9Abi/Vc71String.h" +#if defined(__APPLE__) +#include "../../Platform/X87Compat.h" +#endif +#include #include #include @@ -34,7 +37,7 @@ extern void* g_bufferManager; // dw extern void* g_rendererBase; // dword_1023B970 extern void* g_raShaderConstants; // dword_1023DDBC void* createVertexBuffer(void* bufferManager, unsigned int count, unsigned int stride, - const vc71::string& name, unsigned int usage); + const std::string& name, unsigned int usage); int bufferManagerSwapPool(int value); void* vertexBufferLock(void* wrapper, unsigned int offsetVerts, unsigned int countVerts, unsigned int flags); @@ -93,9 +96,10 @@ dx9rend::IRenderer* renderer() return static_cast(dx9rend::g_rendererBase); } -unsigned char* raConstants() +// The Ra constants block (g_raShaderConstants) word at a retail x86 byte offset. +unsigned char* raConstantAt(unsigned int byteOffset) { - return static_cast(dx9rend::g_raShaderConstants); + return dx9rend::raShaderConstantsAt(byteOffset); } // sub_1000ED40 (34 B, __stdcall, `retn 0Ch`): fld low; fld high; fld value; fcomi st,st1; fcmovnb; @@ -134,35 +138,31 @@ unsigned int geometryDrawnFrame(void* geometry) return reinterpret_cast((*static_cast(geometry))[0xB0 / 4])(geometry); } -// XpLightManager.cpp's XpRenderRecordLayout (0x498 bytes): matrices[4] at +0x2F8, matrices[7] at -// +0x3B8, atlasBounds at +0x438, and the first tail byte +0x494. +// XpLightManager.h's LightShadowRecord (0x498 bytes in the PE): matrices[4] at +0x2F8, matrices[7] +// at +0x3B8, atlasBounds at +0x438, and the first tail byte +0x494. const Mat4* lightRecordShadowMatrix(void* record) { - return reinterpret_cast(static_cast(record) + 0x2F8); + return &static_cast(record)->matrices[4]; } const Mat4* lightRecordTrapezoidMatrix(void* record) { - return reinterpret_cast(static_cast(record) + 0x3B8); + return &static_cast(record)->matrices[7]; } const float* lightRecordViewPort(void* record) { - return reinterpret_cast(static_cast(record) + 0x438); + return static_cast(record)->atlasBounds; } bool lightRecordUsesSecondShadowMap(void* record) { - return static_cast(record)[0x494] != 0; + return static_cast(record)->tail494[0] != 0; } -// The LightManager's two shadow-map textures (+0x21C and +0x230, EngineTexture* - XpLightManager.cpp -// creates and releases them at 0x100F0xxx through its lmField accessor). -dx9rend::EngineTexture* lightManagerShadowMap(unsigned int byteOffset) -{ - return *reinterpret_cast( - reinterpret_cast(g_LightManager) + byteOffset); -} +// The LightManager's two shadow-map textures (+0x21C the directional map, +0x230 the point/spot +// atlas) are read through XpLightManager.h's lightManagerShadowMapTexture / +// lightManagerPointShadowMapTexture. // the sort predicate _Sort receives in edx (0x101AA75C): // key = (((texture & 0xFFFFC000) | (kind << 26)) << 4) | (shadowMap >> 14) @@ -185,7 +185,7 @@ bool batchLess(const DecalBatch& a, const DecalBatch& b) // Acquires the decal effect, dynamic default-pool vertex buffer, and parameter handles. // beginPass initializes the cursor; per-batch setup initializes pointer arrays before use. - +// PE 0x101AA050 DecalRenderer::DecalRenderer() : m_batches() , m_byte14(0) @@ -224,45 +224,45 @@ DecalRenderer::DecalRenderer() const int previousPool = dx9rend::bufferManagerSwapPool(0); m_vertexBuffer = dx9rend::createVertexBuffer(dx9rend::g_bufferManager, kVertexCapacity, - kVertexStride, vc71::string("DecalRenderer"), + kVertexStride, std::string("DecalRenderer"), 0x208u); dx9rend::bufferManagerSwapPool(previousPool); // sub_1001E420 each - the counted lookup; it guards neither the effect nor the answer. m_paramFadeDistanceAndInterval = dx9rend::effectGetShaderParameterTyped( - m_effect, vc71::string("DecalFadeDistanceAndInterval")); // +0x1B8 + m_effect, std::string("DecalFadeDistanceAndInterval")); // +0x1B8 m_paramInstanceTransformations = dx9rend::effectGetShaderParameterTyped( - m_effect, vc71::string("InstanceTransformations")); // +0x1BC + m_effect, std::string("InstanceTransformations")); // +0x1BC m_paramShadowTransformations = dx9rend::effectGetShaderParameterTyped( - m_effect, vc71::string("ShadowTransformations")); // +0x1C0 + m_effect, std::string("ShadowTransformations")); // +0x1C0 m_paramShadowTrapezoidMats = dx9rend::effectGetShaderParameterTyped( - m_effect, vc71::string("ShadowTrapezoidMats")); // +0x1C4 + m_effect, std::string("ShadowTrapezoidMats")); // +0x1C4 m_paramShadowViewPortMaps = dx9rend::effectGetShaderParameterTyped( - m_effect, vc71::string("ShadowViewPortMaps")); // +0x1C8 + m_effect, std::string("ShadowViewPortMaps")); // +0x1C8 m_paramAmbientColor = dx9rend::effectGetShaderParameterTyped( - m_effect, vc71::string("AmbientColor")); // +0x1CC + m_effect, std::string("AmbientColor")); // +0x1CC m_paramSunColor = dx9rend::effectGetShaderParameterTyped( - m_effect, vc71::string("SunColor")); // +0x1D0 + m_effect, std::string("SunColor")); // +0x1D0 m_paramSunDirection = dx9rend::effectGetShaderParameterTyped( - m_effect, vc71::string("SunDirection")); // +0x1D4 + m_effect, std::string("SunDirection")); // +0x1D4 m_paramWorldViewProjection = dx9rend::effectGetShaderParameterTyped( - m_effect, vc71::string("WorldViewProjection")); // +0x1D8 + m_effect, std::string("WorldViewProjection")); // +0x1D8 m_paramTexLayer0 = dx9rend::effectGetShaderParameterTyped( - m_effect, vc71::string("TEXLAYER0")); // +0x1DC + m_effect, std::string("TEXLAYER0")); // +0x1DC m_paramShadowMapTex = dx9rend::effectGetShaderParameterTyped( - m_effect, vc71::string("ShadowMapTex")); // +0x1E0 + m_effect, std::string("ShadowMapTex")); // +0x1E0 m_paramFogRange = dx9rend::effectGetShaderParameterTyped( - m_effect, vc71::string("fogRange")); // +0x1E4 + m_effect, std::string("fogRange")); // +0x1E4 m_paramFogColor = dx9rend::effectGetShaderParameterTyped( - m_effect, vc71::string("fogColor")); // +0x1E8 + m_effect, std::string("fogColor")); // +0x1E8 m_paramWaterFogColor = dx9rend::effectGetShaderParameterTyped( - m_effect, vc71::string("WaterFogColor")); // +0x1EC + m_effect, std::string("WaterFogColor")); // +0x1EC m_paramWaterFogRange = dx9rend::effectGetShaderParameterTyped( - m_effect, vc71::string("WaterFogRange")); // +0x1F0 + m_effect, std::string("WaterFogRange")); // +0x1F0 m_paramCameraToWater = dx9rend::effectGetShaderParameterTyped( - m_effect, vc71::string("CameraToWater")); // +0x1F4 + m_effect, std::string("CameraToWater")); // +0x1F4 m_paramWorldSpaceCamPos = dx9rend::effectGetShaderParameterTyped( - m_effect, vc71::string("WorldSpaceCamPos")); // +0x1F8 + m_effect, std::string("WorldSpaceCamPos")); // +0x1F8 } @@ -271,21 +271,25 @@ DecalRenderer::DecalRenderer() // free`), and only then the seventeenth parameter (+0x1F8) - out of field order, as // shipped. Every release is null-tested. The batch vector's destructor runs last (0x101AA62B..). +// PE 0x101AA4F0 DecalRenderer::~DecalRenderer() { - dx9rend::ShaderParameter* const first16[16] = - { - m_paramFadeDistanceAndInterval, m_paramInstanceTransformations, - m_paramShadowTransformations, m_paramShadowTrapezoidMats, m_paramShadowViewPortMaps, - m_paramAmbientColor, m_paramSunColor, m_paramSunDirection, m_paramWorldViewProjection, - m_paramTexLayer0, m_paramShadowMapTex, m_paramFogRange, m_paramFogColor, - m_paramWaterFogColor, m_paramWaterFogRange, m_paramCameraToWater - }; - for (int i = 0; i < 16; ++i) - { - if (first16[i]) - first16[i]->release(); // vtable +0x08 - } + if (m_paramFadeDistanceAndInterval) m_paramFadeDistanceAndInterval->release(); + if (m_paramInstanceTransformations) m_paramInstanceTransformations->release(); + if (m_paramShadowTransformations) m_paramShadowTransformations->release(); + if (m_paramShadowTrapezoidMats) m_paramShadowTrapezoidMats->release(); + if (m_paramShadowViewPortMaps) m_paramShadowViewPortMaps->release(); + if (m_paramAmbientColor) m_paramAmbientColor->release(); + if (m_paramSunColor) m_paramSunColor->release(); + if (m_paramSunDirection) m_paramSunDirection->release(); + if (m_paramWorldViewProjection) m_paramWorldViewProjection->release(); + if (m_paramTexLayer0) m_paramTexLayer0->release(); + if (m_paramShadowMapTex) m_paramShadowMapTex->release(); + if (m_paramFogRange) m_paramFogRange->release(); + if (m_paramFogColor) m_paramFogColor->release(); + if (m_paramWaterFogColor) m_paramWaterFogColor->release(); + if (m_paramWaterFogRange) m_paramWaterFogRange->release(); + if (m_paramCameraToWater) m_paramCameraToWater->release(); if (m_effect) dx9rend::effectRelease(m_effect); // vtable +0x08 if (m_vertexBuffer) @@ -299,6 +303,7 @@ DecalRenderer::~DecalRenderer() // shadow light record; 1 when it has a geometry (+0x20) whose +0xB0 equals the renderer's frame // ordinal (+0x54) - geometry asked first; else 0. +// PE 0x101A9B10 int DecalRenderer::classify(DecalObject* object) { if (object->getShadowRecord()) // slot +0x08 @@ -322,16 +327,16 @@ int DecalRenderer::classify(DecalObject* object) // * a batch is flushed at exactly 10 objects (`== 0Ah`) with its kind kept, and at the end of // each bucket when it holds any object; boundTexture / boundShadowMap restart at 0 per bucket. +// PE 0x101AAA90 void DecalRenderer::collect(dx9rend::IRenderView& view, DecalObjectMap& instances) { if (!m_enabled || instances.size() == 0) return; - decalvc71::Vector buckets[3]; // [ebp-6Ch..-3Ch] - for (DecalObjectMap::Node* it = instances.begin(); it != instances.end(); - it = DecalObjectMap::next(it)) + std::vector buckets[3]; // [ebp-6Ch..-3Ch] + for (DecalObjectMap::iterator it = instances.begin(); it != instances.end(); ++it) { - DecalObject* const object = it->value; + DecalObject* const object = it->second; const unsigned char changed = object->renderFlag(); object->renderFlag() = false; if (changed && object->getNumDecals() != 0) // slot +0x20 @@ -351,11 +356,11 @@ void DecalRenderer::collect(dx9rend::IRenderView& view, DecalObjectMap& instance m_boundShadowMap = 0; // +0x1C batch.reset(kind); - decalvc71::Vector& bucket = buckets[kind]; - for (unsigned int i = 0; bucket.data() && i < bucket.size(); ++i) + std::vector& bucket = buckets[kind]; + for (unsigned int i = 0; i < bucket.size(); ++i) { addObject(view, bucket[i], batch); - if (batch.objects.data() && batch.objects.size() == 10) + if (batch.objects.size() == 10) { pushBatch(batch); batch.vertexCount = 0; @@ -365,7 +370,7 @@ void DecalRenderer::collect(dx9rend::IRenderView& view, DecalObjectMap& instance batch.records.clear(); } } - if (batch.objects.data() && batch.objects.size() != 0) + if (batch.objects.size() != 0) pushBatch(batch); } } @@ -375,9 +380,10 @@ void DecalRenderer::collect(dx9rend::IRenderView& view, DecalObjectMap& instance // Captures the object slot before any flush; an object can occupy a slot even when all // its own records fade out, provided earlier records remain in the batch. +// PE 0x101AA960 void DecalRenderer::addObject(dx9rend::IRenderView& view, DecalObject* object, DecalBatch& batch) { - int objectIndex = batch.objects.data() ? static_cast(batch.objects.size()) : 0; // [ebp-4] + int objectIndex = static_cast(batch.objects.size()); // [ebp-4] for (unsigned int i = 0; i < object->staticCount(); ++i) { @@ -391,13 +397,20 @@ void DecalRenderer::addObject(dx9rend::IRenderView& view, DecalObject* object, D j = (j + 1) & object->ringMask()) { DecalRecord* const record = object->ringRecords()[j]; +#if defined(__APPLE__) + // [CHOSEN, not recovered] The subtraction/division retain x87 precision until the argument spill. + const float t = bf2x87::store((bf2x87::wide(record->age) + - bf2x87::wide(decalManager()->fadeOutTime())) + / bf2x87::wide(decalManager()->fadeOutDuration())); +#else const float t = (record->age - decalManager()->fadeOutTime()) / decalManager()->fadeOutDuration(); // fsub +0x14, fdiv +0x18 +#endif record->alpha = 1.0f - clampRange(t, 0.0f, 1.0f); // sub_1000ED40, fsubr 1.0 addRecord(batch, record, object, &objectIndex); } - if (batch.records.data() && batch.records.size() != 0) + if (batch.records.size() != 0) batch.objects.push_back(object); // 0x10126F30 on growth } @@ -405,6 +418,7 @@ void DecalRenderer::addObject(dx9rend::IRenderView& view, DecalObject* object, D // Adds a visible-alpha record, flushing on texture/shadow change or the 12288-vertex limit. // NaN alpha is retained. A flush includes the current object, then restarts its slot at zero. +// PE 0x101AA830 void DecalRenderer::addRecord(DecalBatch& batch, DecalRecord* record, DecalObject* object, int* objectIndex) { @@ -420,15 +434,15 @@ void DecalRenderer::addRecord(DecalBatch& batch, DecalRecord* record, DecalObjec if (geometry && geometryLightRecord(geometry)) // geometry +0x28 { if (lightRecordUsesSecondShadowMap(geometryLightRecord(geometry))) // +0x28 again - shadowMap = lightManagerShadowMap(0x230); + shadowMap = lightManagerPointShadowMapTexture(g_LightManager); // +0x230 else - shadowMap = lightManagerShadowMap(0x21C); + shadowMap = lightManagerShadowMapTexture(g_LightManager); // +0x21C haveShadowMap = true; } } else if (batch.kind == 2) { - shadowMap = lightManagerShadowMap(0x21C); + shadowMap = lightManagerShadowMapTexture(g_LightManager); // +0x21C haveShadowMap = true; } if (haveShadowMap && shadowMap != m_boundShadowMap) @@ -444,7 +458,7 @@ void DecalRenderer::addRecord(DecalBatch& batch, DecalRecord* record, DecalObjec } if ((batch.vertexCount + record->vertexCount >= kVertexCapacity || changed) && - batch.records.data() && batch.records.size() != 0) + batch.records.size() != 0) { batch.objects.push_back(object); pushBatch(batch); @@ -469,10 +483,10 @@ void DecalRenderer::pushBatch(const DecalBatch& batch) // Sorts and draws queued batches with the live view, then releases batch storage. // Returns false when disabled or empty. Equal-key draw order depends on std::sort. - +// PE 0x101AA670 bool DecalRenderer::render(dx9rend::IRenderView* view) { - if (!m_enabled || !m_batches.data() || m_batches.size() == 0) + if (!m_enabled || m_batches.size() == 0) return false; const Mat4* const projection = view->getProjectionMatrixPtr(); // +0x6C @@ -492,7 +506,7 @@ bool DecalRenderer::render(dx9rend::IRenderView* view) std::sort(m_batches.begin(), m_batches.end(), batchLess); int pass = 3; // [ebp-8] - for (unsigned int i = 0; m_batches.data() && i < m_batches.size(); ++i) + for (unsigned int i = 0; i < m_batches.size(); ++i) { const DecalBatch& batch = m_batches[i]; if (batch.kind != pass) @@ -507,7 +521,7 @@ bool DecalRenderer::render(dx9rend::IRenderView* view) if (pass != 3) dx9rend::effectEnd(m_effect); - m_batches.clear(); // 0x101ABC60 + free + m_batches.clear(); // 0x101ABC60; retail's VC7.1 clear also freed storage dx9rend::stateManagerPop(); return true; } @@ -516,6 +530,7 @@ bool DecalRenderer::render(dx9rend::IRenderView* view) // Binds lighting, camera, fog, and transform constants and begins the requested effect pass. // Resets the vertex cursor so the next lock discards previous data. +// PE 0x101AACF0 void DecalRenderer::beginPass(int kind) { m_vertexCursor = 100000; // 0x186A0 @@ -553,11 +568,11 @@ void DecalRenderer::beginPass(int kind) const Mat4* const cameraView = renderer()->getRenderViewDup()->getViewMatrixPtr(); // +0x50, +0x64 m_paramWorldSpaceCamPos->setValue(&cameraView->m[12], 0); // +0x1F8, view + 0x30 - m_paramFogRange->setValue(raConstants() + 0xA8, 0); // +0x1E4 - m_paramFogColor->setValue(raConstants() + 0xBC, 0); // +0x1E8 - m_paramWaterFogColor->setValue(raConstants() + 0x10C, 0); // +0x1EC, sub_10037EB0 - m_paramWaterFogRange->setValue(raConstants() + 0xF8, 0); // +0x1F0, sub_10037EA0 - m_paramCameraToWater->setValue(raConstants() + 0x1D8, 0); // +0x1F4 + m_paramFogRange->setValue(raConstantAt(0xA8), 0); // +0x1E4 + m_paramFogColor->setValue(raConstantAt(0xBC), 0); // +0x1E8 + m_paramWaterFogColor->setValue(raConstantAt(0x10C), 0); // +0x1EC, sub_10037EB0 + m_paramWaterFogRange->setValue(raConstantAt(0xF8), 0); // +0x1F0, sub_10037EA0 + m_paramCameraToWater->setValue(raConstantAt(0x1D8), 0); // +0x1F4 dx9rend::vertexBufferBindStream(m_vertexBuffer, 0); dx9rend::effectBegin(m_effect); @@ -568,9 +583,10 @@ void DecalRenderer::beginPass(int kind) // Draws a batch with discard when the ring reaches capacity, otherwise nooverwrite. // Returns false on lock failure, true after drawing or for an empty batch. +// PE 0x101A9E60 bool DecalRenderer::drawBatch(dx9rend::IRenderView* view, const DecalBatch& batch) { - if (!batch.records.data() || batch.records.size() == 0) + if (batch.records.size() == 0) return true; setInstanceTransforms(batch); @@ -616,7 +632,7 @@ bool DecalRenderer::drawBatch(dx9rend::IRenderView* view, const DecalBatch& batc if (!locked) return false; - for (unsigned int r = 0; batch.records.data() && r < batch.records.size(); ++r) + for (unsigned int r = 0; r < batch.records.size(); ++r) { const DecalRecord* const record = batch.records[r]; const DecalVertex* const source = record->vertices; @@ -652,9 +668,10 @@ bool DecalRenderer::drawBatch(dx9rend::IRenderView* view, const DecalBatch& batc // object; then InstanceTransformations (+0x1BC) gets the pointer array and the object count (+0x28). // No bound check against the ten slots - collect keeps a batch to ten objects. +// PE 0x101A9B60 void DecalRenderer::setInstanceTransforms(const DecalBatch& batch) { - for (unsigned int i = 0; batch.objects.data() && i < batch.objects.size(); ++i) + for (unsigned int i = 0; i < batch.objects.size(); ++i) { world::IObject* const owner = static_cast(batch.objects[i]->ownerObject()); @@ -663,7 +680,7 @@ void DecalRenderer::setInstanceTransforms(const DecalBatch& batch) else m_instanceTransforms[i] = &Mat4::getIdentity(); } - const unsigned int count = batch.objects.data() ? batch.objects.size() : 0u; + const unsigned int count = static_cast(batch.objects.size()); m_paramInstanceTransformations->setMatrixPointerArray( reinterpret_cast(m_instanceTransforms), count); // +0x28 } @@ -674,9 +691,10 @@ void DecalRenderer::setInstanceTransforms(const DecalBatch& batch) // ShadowViewPortMaps[i] = its +0x438..+0x444; otherwise the identity and a zero viewport. Then the // two parameters, each with the object count. +// PE 0x101A9C00 void DecalRenderer::setDynamicShadowParameters(const DecalBatch& batch) { - for (unsigned int i = 0; batch.objects.data() && i < batch.objects.size(); ++i) + for (unsigned int i = 0; i < batch.objects.size(); ++i) { void* const geometry = batch.objects[i]->ownerGeometry(); if (geometry && geometryLightRecord(geometry)) @@ -697,9 +715,10 @@ void DecalRenderer::setDynamicShadowParameters(const DecalBatch& batch) m_shadowViewPorts[i].x = 0.0f; } } - const unsigned int count = batch.objects.data() ? batch.objects.size() : 0u; + unsigned int count = static_cast(batch.objects.size()); m_paramShadowTransformations->setMatrixPointerArray( reinterpret_cast(m_shadowTransforms), count); // +0x1C0, +0x28 + count = static_cast(batch.objects.size()); m_paramShadowViewPortMaps->setValue(m_shadowViewPorts, count); // +0x1C8, +0x18 } @@ -709,9 +728,10 @@ void DecalRenderer::setDynamicShadowParameters(const DecalBatch& batch) // sub_100791E0 calls) and a zero viewport. Then ShadowTransformations, ShadowTrapezoidMats and // ShadowViewPortMaps, each with the object count. +// PE 0x101A9D20 void DecalRenderer::setStaticShadowParameters(const DecalBatch& batch) { - for (unsigned int i = 0; batch.objects.data() && i < batch.objects.size(); ++i) + for (unsigned int i = 0; i < batch.objects.size(); ++i) { void* const record = batch.objects[i]->getShadowRecord(); // slot +0x08 if (record) @@ -734,13 +754,13 @@ void DecalRenderer::setStaticShadowParameters(const DecalBatch& batch) m_shadowViewPorts[i].x = 0.0f; } } - unsigned int count = batch.objects.data() ? batch.objects.size() : 0u; + unsigned int count = static_cast(batch.objects.size()); m_paramShadowTransformations->setMatrixPointerArray( reinterpret_cast(m_shadowTransforms), count); // +0x1C0 - count = batch.objects.data() ? batch.objects.size() : 0u; + count = static_cast(batch.objects.size()); m_paramShadowTrapezoidMats->setMatrixPointerArray( reinterpret_cast(m_shadowTrapezoidMats), count); // +0x1C4 - count = batch.objects.data() ? batch.objects.size() : 0u; + count = static_cast(batch.objects.size()); m_paramShadowViewPortMaps->setValue(m_shadowViewPorts, count); // +0x1C8 } diff --git a/Code/BF2/Geom/DecalSystem/DecalRenderer.h b/Code/BF2/Geom/DecalSystem/DecalRenderer.h index e10daccd4..d0f9057f4 100644 --- a/Code/BF2/Geom/DecalSystem/DecalRenderer.h +++ b/Code/BF2/Geom/DecalSystem/DecalRenderer.h @@ -9,11 +9,12 @@ #ifdef BF2_IMAGE_RENDDX9 -#include "DecalContainers.h" #include "../../Math/Mat4.h" #include "../../Math/Vec3.h" +#include #include +#include namespace dice { namespace hfe { @@ -30,8 +31,9 @@ namespace geom { class DecalObject; struct DecalRecord; -typedef decalvc71::Map > - DecalObjectMap; +// The manager's client and active sets: every entry maps an object to itself (retail's +// std::map, ordered by the raw pointer). +typedef std::map DecalObjectMap; // Batch grouped by kind, texture, and shadow map. Holds at most ten object transforms. @@ -42,7 +44,8 @@ struct DecalBatch DecalBatch() : vertexCount(0), kind(0), texture(0), shadowMap(0) {} // vertexCount = 0, kind = the argument, texture = shadowMap = 0, - // then both vectors cleared (_Tidy: freed and nulled), objects first. + // then both vectors cleared, objects first (retail's VC7.1 clear also released the storage). + // PE 0x101AB200 void reset(int newKind) { vertexCount = 0; @@ -57,22 +60,10 @@ struct DecalBatch int kind; // +0x04 dx9rend::EngineTexture* texture; // +0x08 dx9rend::EngineTexture* shadowMap; // +0x0C - decalvc71::Vector objects; // +0x10 - decalvc71::Vector records; // +0x20 + std::vector objects; // +0x10 + std::vector records; // +0x20 }; -// std::swap on a batch - VC7.1's _Sort swaps elements by value; this exchanges the same contents -// without the deep copies. [CHOSEN] (see DecalContainers.h). -inline void swap(DecalBatch& a, DecalBatch& b) -{ - const unsigned int vertexCount = a.vertexCount; a.vertexCount = b.vertexCount; b.vertexCount = vertexCount; - const int kind = a.kind; a.kind = b.kind; b.kind = kind; - dx9rend::EngineTexture* const texture = a.texture; a.texture = b.texture; b.texture = texture; - dx9rend::EngineTexture* const shadowMap = a.shadowMap; a.shadowMap = b.shadowMap; b.shadowMap = shadowMap; - a.objects.swap(b.objects); - a.records.swap(b.records); -} - class DecalRenderer { public: @@ -107,7 +98,7 @@ class DecalRenderer void setDynamicShadowParameters(const DecalBatch& batch); void setStaticShadowParameters(const DecalBatch& batch); - decalvc71::Vector m_batches; // +0x000 + std::vector m_batches; // +0x000 unsigned int m_dword10; // +0x010 [UNRESOLVED] unsigned char m_byte14; // +0x014 [UNRESOLVED] unsigned char m_pad15[3]; @@ -147,26 +138,12 @@ class DecalRenderer friend struct DecalRendererLayoutCheck; }; +// The retail offsets stay beside the members; with std::vector members neither object keeps the +// retail size (DecalBatch 0x30, DecalRenderer 0x1FC) or the offsets after its first vector. struct DecalRendererLayoutCheck { #if defined(_M_IX86) - static_assert(sizeof(DecalBatch) == 0x30, "0x101AC590 strides the batch vector by 0x30"); static_assert(offsetof(DecalBatch, objects) == 0x10, "0x101AB9B6"); - static_assert(offsetof(DecalBatch, records) == 0x20, "0x101AB9C5"); - static_assert(sizeof(DecalRenderer) == 0x1FC, "DecalManager +0x94..+0x28F"); - static_assert(offsetof(DecalRenderer, m_boundTexture) == 0x18, "+0x18"); - static_assert(offsetof(DecalRenderer, m_viewColumn) == 0x20, "+0x20"); - static_assert(offsetof(DecalRenderer, m_worldViewProjection) == 0x30, "+0x30"); - static_assert(offsetof(DecalRenderer, m_fadeDistanceAndInterval) == 0x70, "+0x70"); - static_assert(offsetof(DecalRenderer, m_enabled) == 0x90, "+0x90"); - static_assert(offsetof(DecalRenderer, m_vertexBuffer) == 0x94, "+0x94"); - static_assert(offsetof(DecalRenderer, m_vertexCursor) == 0x9C, "+0x9C"); - static_assert(offsetof(DecalRenderer, m_instanceTransforms) == 0xA0, "+0xA0"); - static_assert(offsetof(DecalRenderer, m_shadowTransforms) == 0xC8, "+0xC8"); - static_assert(offsetof(DecalRenderer, m_shadowTrapezoidMats) == 0xF0, "+0xF0"); - static_assert(offsetof(DecalRenderer, m_shadowViewPorts) == 0x118, "+0x118"); - static_assert(offsetof(DecalRenderer, m_paramFadeDistanceAndInterval) == 0x1B8, "+0x1B8"); - static_assert(offsetof(DecalRenderer, m_paramWorldSpaceCamPos) == 0x1F8, "+0x1F8"); #endif }; diff --git a/Code/BF2/Geom/DecalSystem/DecalShadowManager.cpp b/Code/BF2/Geom/DecalSystem/DecalShadowManager.cpp new file mode 100644 index 000000000..ac585f8bd --- /dev/null +++ b/Code/BF2/Geom/DecalSystem/DecalShadowManager.cpp @@ -0,0 +1,220 @@ +// DecalShadowManager, recovered from RendDX9.dll 1.50 (0x10127160..0x101274E0 and its factory +// 0x100B0793). Attested source path: RendDX9_r's __FILE__ for +// Geom/DecalSystem/DecalShadowManager.cpp (docs/tracks/rend/attribution.md). 0x10127490 is the +// std::vector::push_back instantiation (with its insert 0x10126F30). + +#ifdef BF2_IMAGE_RENDDX9 + +#include "DecalShadowManager.h" +#include "DecalObject.h" +#include "IDecalManager.h" +#include "IDecalTemplate.h" +#include "../../Game/Objects/GeometryPartAccess.h" // the geometry instance slots +0x28/+0x44/+0x48 +#include "../../Game/Objects/IObject.h" +#include "../../Game/Objects/ObjectLayoutAccess.h" +#include "../../Math/Mat4.h" +#include "../../Math/Vec3.h" +#include "../../Physics/ICollisionMesh.h" +#include "../../Scene/Object/ObjectManager.h" +#include "../../Scene/Object/ObjectPredicator.h" +#include "../../../RendDX9Abi/BfMemory.h" +#include "../../../RendDX9Abi/PluginAbi.h" + +#include + +namespace dice { +namespace hfe { + +// PluginEntry.cpp - the host ObjectManager singleton (dword_10244AD8). +extern IBase* objectManager; + +namespace geom { + +extern IBase* g_DecalManager; // ModuleGeom.cpp, dword_1024B908 + +namespace { + +const unsigned int kIID_IBase = 1u; +const unsigned int kIID_IDecalShadowManager = 820021u; // dword_1021AE50 + +// g_DecalManager is the manager's primary interface pointer, re-read at every use as shipped. +inline IDecalManager* decalManager() +{ + return static_cast(g_DecalManager); +} + +// The ray-test predicator addShadow builds on its stack: sub_101C7E90 with mask 0x102 +// (OFIsVisible | OFHasCollision) and 0x101C7EB0's rule that every bit of the mask must be present. +// The same shape as XpLightManager.cpp's LightOcclusionPredicator. +class ShadowGroundPredicator : public world::ObjectPredicator +{ +public: + ShadowGroundPredicator() : m_mask(0x102u) {} + virtual bool predicate(world::IObject* object) + { + return (m_mask & object->getFlags()) == m_mask; + } + virtual unsigned int getFlags() const { return m_mask; } + virtual bool performCulling(world::IObject*) { return true; } + virtual bool predicateSurface(int) { return true; } + +private: + unsigned int m_mask; +}; + +} // anonymous namespace + + +// PE 0x10127160. The template is fetched (created on first use) from the decal manager, which +// ModuleGeom publishes first; neither the manager nor the template is tested for null, as shipped. +DecalShadowManager::DecalShadowManager() + : m_refCount(1), m_shadows(), m_template(0) +{ + m_template = decalManager()->addTemplate(DecalTemplateString("DecalShadowTemplate")); + m_template->setSize(1.0f); // +0x08 +} + +// PE 0x101271D0. The decals are not handed back here; clearShadows does that. +DecalShadowManager::~DecalShadowManager() +{ + m_template = 0; +} + + +// The IBase quartet. + +void DecalShadowManager::addRef() +{ + ++m_refCount; +} + +int DecalShadowManager::getRef() +{ + return m_refCount; +} + +// PE 0x101274E0. The interface has no destructor slot: at zero the destructor runs directly and +// the engine heap takes the block back. +int DecalShadowManager::release() +{ + const int remaining = --m_refCount; + if (remaining == 0) + { + this->~DecalShadowManager(); + ::renddx9abi::engineFree(this); + } + return remaining; +} + +// IBase (1) and IID_IDecalShadowManager answer `this`. +// PE 0x10127460. +void* DecalShadowManager::queryInterface(unsigned int iid) const +{ + if (iid == kIID_IBase) + return const_cast(this); + return iid != kIID_IDecalShadowManager ? 0 : const_cast(this); +} + + +// PE 0x10127200. VC7.1's clear() frees the storage (the listing's free plus three zeroed +// pointers). +void DecalShadowManager::clearShadows() +{ + for (unsigned int i = 0; i < m_shadows.size(); ++i) + decalManager()->enqueue(m_shadows[i]); // +0x18 + m_shadows.clear(); +} + +// PE 0x10127260. The ray starts at the geometry's position raised by its bounding radius and +// runs 10 units down (ObjectManager +0x68 takes a delta). On an object hit, the hit object's +// collision mesh refines the point (ICollisionMesh +0x58, lod 1, front faces) and receives the +// decal with the hit face; a ground hit places it without a mesh. The refined normal is stored +// and never read, as shipped. +bool DecalShadowManager::addShadow(void* geometry) +{ + Vec3 direction; + direction.x = 0.0f; + direction.y = -10.0f; + direction.z = 0.0f; + const Mat4* const transform = world::geometry_part::getGeometryTransform(geometry); + Vec3 from; + from.x = transform->m[12]; + from.y = transform->m[13]; + from.z = transform->m[14]; + from.y = world::geometry_part::getBoundingRadius(geometry) + from.y; + + world::IObject* hitObject = 0; + Vec3 hitPoint; + hitPoint.x = hitPoint.y = hitPoint.z = 0.0f; + Vec3 hitNormal; + hitNormal.x = hitNormal.y = hitNormal.z = 0.0f; + int hitPart; + ShadowGroundPredicator predicator; // sub_101C7E90(0x102) + if (!reinterpret_cast(objectManager)->intersectLine( + hitObject, hitPoint, hitNormal, hitPart, from, direction, &predicator, + false, false, true, false, 0)) + return false; + + world::ICollisionMesh* collisionMesh = 0; + unsigned int faceInfo = 0; // CollisionFaceInfo: lod, geometry, u16 face + if (hitObject) + { + collisionMesh = static_cast( + world::object_detail::LayoutAccess::collisionMesh(hitObject)); // IObject +0x40 + if (!collisionMesh) + return false; + Vec3 normal; + normal.x = normal.y = normal.z = 0.0f; + Vec3 position; + position.x = position.y = position.z = 0.0f; + float planeDistance; + float along; + // The inverse is fetched first (PE +0x84), then the transform (PE +0x80). + const Mat4& worldToObject = hitObject->getInvAbsoluteTransformation(); + const Mat4& objectToWorld = hitObject->getAbsoluteTransformation(); + if (!collisionMesh->getDistance(1, false, objectToWorld, worldToObject, hitPoint, + direction, normal, position, planeDistance, along, 0, + reinterpret_cast(&faceInfo), + true, false)) + return false; + hitPoint = position; + hitNormal = normal; + } + + DecalObject* const decal = static_cast( + decalManager()->createClient(hitObject)); // +0x14 + if (!decal) + return false; + decalManager()->addInstance(decal); // +0x24 + m_shadows.push_back(decal); + + Mat4 placement = Mat4::getIdentity(); + placement.m[12] = placement.m[12] + hitPoint.x; + placement.m[13] = placement.m[13] + hitPoint.y; + placement.m[14] = placement.m[14] + hitPoint.z; + decal->add(&placement, m_template, world::geometry_part::getBoundingRadius(geometry), + collisionMesh, + collisionMesh ? reinterpret_cast(&faceInfo) : 0); + decal->setShadowRecord(world::geometry_part::getShadowRecord(geometry)); // decal +0x04 + return true; +} + + +// 0x100B0793: an aggregate outer is refused; a failed query releases the new object. +IBase* __fastcall createDecalShadowManager(unsigned int iid, IBase* outer) +{ + if (outer) + return 0; + void* const storage = ::renddx9abi::engineAlloc(sizeof(DecalShadowManager)); + DecalShadowManager* const self = storage ? new (storage) DecalShadowManager() : 0; + void* const itf = self->queryInterface(iid); + if (!itf) + self->release(); + return static_cast(itf); +} + +} // namespace geom +} // namespace hfe +} // namespace dice + +#endif // BF2_IMAGE_RENDDX9 diff --git a/Code/BF2/Geom/DecalSystem/DecalShadowManager.h b/Code/BF2/Geom/DecalSystem/DecalShadowManager.h new file mode 100644 index 000000000..43a2256a9 --- /dev/null +++ b/Code/BF2/Geom/DecalSystem/DecalShadowManager.h @@ -0,0 +1,77 @@ +// Blob shadows as decals: for a geometry instance, finds the surface below it and places a +// "DecalShadowTemplate" decal there, sized by the geometry's bounding radius and bound to the +// geometry's shadow record. [INFERRED] header placement beside the attested +// Geom/DecalSystem/DecalShadowManager.cpp, and every method name. No shipped image calls +// clearShadows or addShadow; in 1.50 the singleton only registers its decal template. + +#ifndef BF2_GEOM_DECALSYSTEM_DECALSHADOWMANAGER_H +#define BF2_GEOM_DECALSYSTEM_DECALSHADOWMANAGER_H + +#ifdef BF2_IMAGE_RENDDX9 + +#include "../../Core/IBase.h" + +#include + +namespace dice { +namespace hfe { +namespace geom { + +class DecalObject; +class IDecalTemplate; + +// The decal-shadow interface: six slots, no destructor (release destroys the object directly). +// IID 820021, class id 821020, singleton "DecalShadowManager" (dword_1025BED8). +class IDecalShadowManager : public IBase +{ +public: + // Hands every placed shadow decal back to the decal manager's deletion queue. + virtual void clearShadows() = 0; // +0x10 + // Casts a ray 10 units down from the top of `geometry`'s bounding sphere, places a shadow decal + // at the hit (on the hit object's collision mesh when an object was hit) and binds it to the + // geometry's shadow record. `geometry` is a geometry instance (StaticMesh, SkinnedMesh, + // BundledMesh). False when nothing was hit, the hit object has no collision mesh, the mesh + // query misses or the decal manager refuses a client. + virtual bool addShadow(void* geometry) = 0; // +0x14 + +protected: + ~IDecalShadowManager() {} +}; + +// DecalShadowManager - 0x1C bytes, vtable 0x1021CB9C, constructor 0x10127160, factory 0x100B0793. +class DecalShadowManager : public IDecalShadowManager +{ +public: + DecalShadowManager(); // 0x10127160 + ~DecalShadowManager(); // 0x101271D0 + + virtual void addRef(); // 0x1000CB20 (folded) + virtual int getRef(); // 0x101A9A10 (folded) + virtual int release(); // 0x101274E0 + virtual void* queryInterface(unsigned int iid) const; // 0x10127460 + + virtual void clearShadows(); // 0x10127200 + virtual bool addShadow(void* geometry); // 0x10127260 + +private: + DecalShadowManager(const DecalShadowManager&); + DecalShadowManager& operator=(const DecalShadowManager&); + + // data, in shipped order + int m_refCount; // +0x04 + std::vector m_shadows; // +0x08 VC7.1 vector (allocator, first, last, end) + IDecalTemplate* m_template; // +0x18 "DecalShadowTemplate", size 1 +}; + +// dword_1025BED8. ModuleGeom.cpp owns the definition. +extern IBase* g_DecalShadowManager; + +// The factory registered under "dice.hfe.geom.DecalShadowManager" (0x100B0793). +IBase* __fastcall createDecalShadowManager(unsigned int iid, IBase* outer); + +} // namespace geom +} // namespace hfe +} // namespace dice + +#endif // BF2_IMAGE_RENDDX9 +#endif // BF2_GEOM_DECALSYSTEM_DECALSHADOWMANAGER_H diff --git a/Code/BF2/Geom/DecalSystem/DecalTemplate.cpp b/Code/BF2/Geom/DecalSystem/DecalTemplate.cpp index 218887df1..cce0831cd 100644 --- a/Code/BF2/Geom/DecalSystem/DecalTemplate.cpp +++ b/Code/BF2/Geom/DecalSystem/DecalTemplate.cpp @@ -2,13 +2,18 @@ #ifdef BF2_IMAGE_RENDDX9 +#if defined(__APPLE__) +#include "../../Platform/X87Compat.h" // [CHOSEN, not recovered] x87 conversion results, including invalid inputs. +#endif #include "DecalTemplate.h" +#include "../../Core/StringUtil.h" // equalsIgnoreCase (sub_10075080) #include "DecalManager.h" #include "DecalObject.h" // decal_template_state (below) #include "../../RendDX9/RendDX9Base.h" // textureManagerGetTexture #include "../../RendDX9/Texture.h" // EngineTexture, textureDims, textureReleaseRef #include "../../RendDX9/TextureAtlas/TextureAtlas.h" // TextureAtlasEntry +#include "../../GeomMisc/Debug.h" #include "../../../RendDX9Abi/Frontier.h" // logf #include "../../../RendDX9Abi/HostFileAbi.h" #include "../../../RendDX9Abi/PluginAbi.h" @@ -29,21 +34,10 @@ const Vec3* terrainOriginScratch(const Vec3& in); namespace { -// sub_10075080 (fastcall, 63 B): two std::strings equal under MSVCR71 `_stricmp`. loadTexture hands -// it the name and a freshly built std::string(""), so the test is "the name is empty". -bool equalsNoCase(const char* a, const char* b) -{ - return ::_stricmp(a, b) == 0; -} - // std::operator!=(const string&, const string&) (0x101AF9D0, MSVCP71's): the counted compare. bool stringsDiffer(const DecalTemplateString& a, const DecalTemplateString& b) { -#if BF2_PLUGIN_ABI_NATIVE return a != b; -#else - return a.size() != b.size() || ::memcmp(a.c_str(), b.c_str(), a.size()) != 0; -#endif } // `name + ".dds"` - the shipped code inlines MSVCP71's operator+: copy-construct, operator+=, copy @@ -78,6 +72,7 @@ float unsignedToFloat(unsigned int value) // Everything else (+0x04, +0x18..+0x28, +0x80..+0x9C) is left to reset(); nothing is written // twice here that the shipped constructor writes once. +// PE 0x101AFA70 DecalTemplate::DecalTemplate(const DecalTemplateString& name) : m_decalTextureName() , m_index(0) @@ -106,6 +101,7 @@ DecalTemplate::DecalTemplate(const DecalTemplateString& name) // finds it null. Then ~name (+0x5C) and ~decalTextureName (+0x3C), reverse declaration order. // The atlas entry (+0x7C) is borrowed from the manager's atlas and not released. +// PE 0x101AF7B0 DecalTemplate::~DecalTemplate() { assignTexture(m_texture, 0); @@ -116,6 +112,7 @@ DecalTemplate::~DecalTemplate() // Restores defaults through the virtual setters while preserving the current atlas entry. +// PE 0x101AF6C0 void DecalTemplate::reset() { assignTexture(m_texture, 0); @@ -158,6 +155,7 @@ void DecalTemplate::reset() // Updates UV offset and extent from the atlas entry and optional animation-frame scale. // Uses virtual setUvExtent; absent atlas data spans the full texture. +// PE 0x101AF4F0 void DecalTemplate::updateUv() { Vec2 extent; @@ -198,15 +196,16 @@ void DecalTemplate::updateUv() // Resolves an atlas entry first, then a standalone DDS texture. Returns true when either // resolves. Empty names leave state unchanged; other misses clear prior bindings and log. +// PE 0x101AF820 bool DecalTemplate::loadTexture(const DecalTemplateString& name) { - if (equalsNoCase(name.c_str(), "")) + if (equalsIgnoreCase(std::string(name.c_str()), std::string(""))) // sub_10075080 return false; assignTexture(m_texture, 0); DecalManager* const manager = static_cast(g_DecalManager); - m_atlasEntry = manager->getAtlasEntry(::renddx9abi::toVc71String(name)); + m_atlasEntry = manager->getAtlasEntry(::renddx9abi::fromHostString(name)); if (m_atlasEntry) return true; @@ -217,14 +216,13 @@ bool DecalTemplate::loadTexture(const DecalTemplateString& name) if (exists) { assignTexture(m_texture, static_cast( - dx9rend::textureManagerGetTexture(::renddx9abi::toVc71String(name)))); + dx9rend::textureManagerGetTexture(::renddx9abi::fromHostString(name)))); return m_texture != 0; } - // sub_10074300(6, __FILE__, 107, "") << "File " << name << " not found!"; sub_10074690. Rendered - // through logf with dice's file, line and text, as everywhere in this image. [CHOSEN, not - // recovered] - the debug-stream dispatcher is not bridged. - ::renddx9abi::logf("DecalTemplate.cpp:107 File %s not found!", name.c_str()); + ::renddx9abi::Debug(DebugTypeError, + "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\DecalSystem\\DecalTemplate.cpp", + 107, "") << "File " << name << " not found!"; return m_texture != 0; } @@ -248,11 +246,21 @@ const DecalTemplateString& DecalTemplate::getName() const // +0x04, (85 B, retn) - 1 / animationFrameCountX when that count, as a float, compares // greater than 0.0 (`fcom 0.0; test ah, 41h; jnz` - less, equal or unordered take the zero arm), // else 0; then updateUv(). Every world::DecalTemplate setter in BF2.exe calls it after its set. +// PE 0x101AFA10 void DecalTemplate::refresh() { - const float count = unsignedToFloat(m_animationFrameCountX); // +0x98 +#if defined(__APPLE__) + // [CHOSEN, not recovered] The unsigned count stays live in x87 until the reciprocal store. + const bf2x87::Real count=bf2x87::wide(m_animationFrameCountX); +#else + const double count=static_cast(m_animationFrameCountX); +#endif if (count > 0.0f) - m_frameCountXReciprocal = 1.0f / count; // fld 1.0; fdiv st, st(1) +#if defined(__APPLE__) + m_frameCountXReciprocal=static_cast(bf2x87::wide(1)/count); +#else + m_frameCountXReciprocal=static_cast(1.0/count); +#endif else m_frameCountXReciprocal = 0.0f; updateUv(); @@ -268,6 +276,7 @@ float DecalTemplate::getRandomSize() const { return m_randomSize; } void DecalTemplate::setRandomColorIntensity(float intensity) { m_randomColorIntensity = intensity; } float DecalTemplate::getRandomColorIntensity() const { return m_randomColorIntensity; } +// PE 0x101AF490 // +0x20, the colour packed with w = 1.0 through sub_1008DD80's shared // static Vec4, then copied out of it: +0x08 = x, +0x0C = y, +0x10 = z, +0x14 = 1.0. void DecalTemplate::setColor(const Vec3& color) @@ -279,6 +288,7 @@ void DecalTemplate::setColor(const Vec3& color) m_color.w = packed[3]; } +// PE 0x101AF4C0 // +0x24, the colour's xyz copied through // sub_100E11B0's shared file static, then out of it into the return slot. Vec3 DecalTemplate::getColor() const @@ -290,8 +300,10 @@ Vec3 DecalTemplate::getColor() const return *terrainOriginScratch(xyz); // sub_100E11B0(this+8) } +// PE 0x101AFB10 void DecalTemplate::setIsStatic(bool isStatic) { m_isStatic = isStatic; } // +0x28 bool DecalTemplate::getIsStatic() const { return m_isStatic; } // +0x2C +// PE 0x101AFB30 void DecalTemplate::setUsedOnTransparentMaterials(bool used) // +0x30 { m_usedOnTransparentMaterials = used; @@ -302,12 +314,14 @@ bool DecalTemplate::getUsedOnTransparentMaterials() const } // +0x38 / +0x3C, the Vec2 at +0xA0 (y through the FPU, x as a dword). +// PE 0x101AF450 void DecalTemplate::setUvExtent(const Vec2& value) { m_uvExtent.y = value.y; m_uvExtent.x = value.x; } +// PE 0x101AF470 Vec2 DecalTemplate::getUvExtent() const { return m_uvExtent; @@ -315,12 +329,14 @@ Vec2 DecalTemplate::getUvExtent() const void DecalTemplate::setRandomRotation(float randomRotation) { m_randomRotation = randomRotation; } // +0x40 float DecalTemplate::getRandomRotation() const { return m_randomRotation; } // +0x44 +// PE 0x101AFB60 void DecalTemplate::setRotation(float rotation) { m_rotation = rotation; } // +0x48 float DecalTemplate::getRotation() const { return m_rotation; } // +0x4C // +0x50, only a different name (MSVCP71 operator!=) is stored and // loaded; a failed load puts "" back. The load is handed the argument, not the member (`push ebx`, // ebx = the argument, 0x101AF9E6). The refresh (+0x04, virtual) runs either way. +// PE 0x101AF9C0 void DecalTemplate::setDecalTextureName(const DecalTemplateString& name) { if (stringsDiffer(m_decalTextureName, name)) @@ -338,8 +354,10 @@ const DecalTemplateString& DecalTemplate::getDecalTextureName() const return m_decalTextureName; } +// PE 0x101AFBA0 void DecalTemplate::setAnimationEnable(bool enable) { m_animationEnable = enable; } // +0x58 bool DecalTemplate::getAnimationEnable() const { return m_animationEnable; } // +0x5C +// PE 0x101AFB80 void DecalTemplate::setAnimationRandomizedStartFrame(bool randomized) // +0x60 { m_animationRandomizedStartFrame = randomized; @@ -353,46 +371,70 @@ float DecalTemplate::getAnimationSpeed() const { return m_animationSpee // +0x70, with a texture bound: frameWidthRel = width / texture width // (both unsigned, converted exactly). Without one: nothing. +// PE 0x101AF570 void DecalTemplate::setAnimationFrameWidth(unsigned int width) { if (m_texture) { const unsigned int* const dims = dx9rend::textureDims(m_texture); - m_animationFrameWidthRelative = unsignedToFloat(width) / unsignedToFloat(dims[0]); +#if defined(__APPLE__) + // [CHOSEN, not recovered] Neither unsigned conversion spills before division. + m_animationFrameWidthRelative=static_cast(bf2x87::wide(width)/bf2x87::wide(dims[0])); +#else + m_animationFrameWidthRelative=static_cast(static_cast(width)/static_cast(dims[0])); +#endif } } // +0x74, (82 B, retn) - 0 without a texture; else (int)(texture width * frameWidthRel), // truncated (the inline control-word switch to round-toward-zero around `fistp dword`). +// PE 0x101AF5B0 unsigned int DecalTemplate::getAnimationFrameWidth() const { if (!m_texture) return 0; const unsigned int* const dims = dx9rend::textureDims(m_texture); - return static_cast(static_cast(unsignedToFloat(dims[0]) * +#if defined(__APPLE__) + return static_cast(bf2x87::toIntTruncate(bf2x87::wide(dims[0]) * + bf2x87::wide(m_animationFrameWidthRelative))); +#else + return static_cast(static_cast(static_cast(dims[0]) * m_animationFrameWidthRelative)); +#endif } // +0x78, the height twin; the argument is narrowed to a float in its own // stack slot (`fstp [ebp+arg_0]`) before the division, which is what `(float)height` is here. +// PE 0x101AF610 void DecalTemplate::setAnimationFrameHeight(unsigned int height) { if (m_texture) { const float h = unsignedToFloat(height); const unsigned int* const dims = dx9rend::textureDims(m_texture); - m_animationFrameHeightRelative = h / unsignedToFloat(dims[1]); +#if defined(__APPLE__) + // [CHOSEN, not recovered] Only the numerator spills to float in this setter. + m_animationFrameHeightRelative=static_cast(bf2x87::wide(h)/bf2x87::wide(dims[1])); +#else + m_animationFrameHeightRelative=static_cast(static_cast(h)/static_cast(dims[1])); +#endif } } // +0x7C, (83 B, retn). +// PE 0x101AF660 unsigned int DecalTemplate::getAnimationFrameHeight() const { if (!m_texture) return 0; const unsigned int* const dims = dx9rend::textureDims(m_texture); - return static_cast(static_cast(unsignedToFloat(dims[1]) * +#if defined(__APPLE__) + return static_cast(bf2x87::toIntTruncate(bf2x87::wide(dims[1]) * + bf2x87::wide(m_animationFrameHeightRelative))); +#else + return static_cast(static_cast(static_cast(dims[1]) * m_animationFrameHeightRelative)); +#endif } void DecalTemplate::setAnimationFrameWidthRelative(float width) { m_animationFrameWidthRelative = width; } // +0x80 @@ -404,15 +446,29 @@ unsigned int DecalTemplate::getAnimationFrameCount() const { return m_a // +0x98, store the count; the reciprocal is 1 / count for a non-zero // count (`test eax, eax; jbe`), else 0. No refresh here - the BF2.exe setter calls +0x04 itself. +// PE 0x101AF3E0 void DecalTemplate::setAnimationFrameCountX(unsigned int count) { m_animationFrameCountX = count; if (count != 0) +#if defined(__APPLE__) + // [CHOSEN, not recovered] FILD's unsigned correction stays in x87 until the reciprocal store. + m_frameCountXReciprocal = bf2x87::store(bf2x87::wide(1.0f) / bf2x87::wide(count)); +#else m_frameCountXReciprocal = 1.0f / unsignedToFloat(count); // fdivr 1.0 +#endif else m_frameCountXReciprocal = 0.0f; } +// Stores the argument dword at +0x9C (the 1/frameCountX cache); this setter has no caller. +// unreachable in 1.50: no code or data references +// PE 0x101AF430 +void DecalTemplate::setFrameCountXReciprocal(float value) +{ + m_frameCountXReciprocal = value; +} + // +0x9C, 0x101AF420 - `mov eax, [ecx+98h]`. unsigned int DecalTemplate::getAnimationFrameCountX() const { diff --git a/Code/BF2/Geom/DecalSystem/DecalTemplate.h b/Code/BF2/Geom/DecalSystem/DecalTemplate.h index 205a17882..ed851e09c 100644 --- a/Code/BF2/Geom/DecalSystem/DecalTemplate.h +++ b/Code/BF2/Geom/DecalSystem/DecalTemplate.h @@ -1,6 +1,6 @@ // Renderer-side decal appearance and animation settings, owned by DecalManager. // [INFERRED] header placement and class name. Texture references release on replacement/destruction. -// HostString fields cross the engine boundary, so native and compatibility member offsets differ; +// The two HostString fields are std::string, so the native offsets after +0x3C differ from retail's; // callers must use typed accessors. The Vec2 at +0x2C is [UNRESOLVED], zeroed and unread. #ifndef BF2_GEOM_DECALSYSTEM_DECALTEMPLATE_H @@ -95,6 +95,7 @@ class DecalTemplate : public IDecalTemplate unsigned int frameCountField() const { return m_animationFrameCount; } // +0x94 unsigned int frameCountXField() const { return m_animationFrameCountX; } // +0x98 float frameCountXReciprocal() const { return m_frameCountXReciprocal; } // +0x9C + void setFrameCountXReciprocal(float value); // +0x9C, PE 0x101AF430, unreferenced const Vec2& uvExtent() const { return m_uvExtent; } // +0xA0 private: @@ -133,35 +134,10 @@ class DecalTemplate : public IDecalTemplate friend struct DecalTemplateLayoutCheck; }; -// The retail-ABI flavour keeps the shipped layout byte for byte (DecalManager::addTemplate's -// `push 0A8h`, 0x10124C81). The native flavour's two host strings are this toolchain's std::string; -// see the header note. +// Retail's object is 0xA8 bytes (DecalManager::addTemplate's `push 0A8h`, 0x10124C81). The native +// object's two strings are std::string, so no retail size or offset after +0x3C is asserted. struct DecalTemplateLayoutCheck { -#if defined(_M_IX86) && !BF2_PLUGIN_ABI_NATIVE - static_assert(sizeof(DecalTemplate) == 0xA8, "0x10124C81 allocates 0xA8"); - static_assert(offsetof(DecalTemplate, m_randomColorIntensity) == 0x04, "+0x04"); - static_assert(offsetof(DecalTemplate, m_color) == 0x08, "+0x08"); - static_assert(offsetof(DecalTemplate, m_size) == 0x18, "+0x18"); - static_assert(offsetof(DecalTemplate, m_isStatic) == 0x20, "+0x20"); - static_assert(offsetof(DecalTemplate, m_usedOnTransparentMaterials) == 0x21, "+0x21"); - static_assert(offsetof(DecalTemplate, m_randomRotation) == 0x24, "+0x24"); - static_assert(offsetof(DecalTemplate, m_vec2C) == 0x2C, "+0x2C"); - static_assert(offsetof(DecalTemplate, m_uvOffset) == 0x34, "+0x34"); - static_assert(offsetof(DecalTemplate, m_decalTextureName) == 0x3C, "+0x3C"); - static_assert(offsetof(DecalTemplate, m_index) == 0x58, "+0x58"); - static_assert(offsetof(DecalTemplate, m_name) == 0x5C, "+0x5C"); - static_assert(offsetof(DecalTemplate, m_texture) == 0x78, "+0x78"); - static_assert(offsetof(DecalTemplate, m_atlasEntry) == 0x7C, "+0x7C"); - static_assert(offsetof(DecalTemplate, m_animationRandomizedStartFrame) == 0x80, "+0x80"); - static_assert(offsetof(DecalTemplate, m_animationSpeed) == 0x84, "+0x84"); - static_assert(offsetof(DecalTemplate, m_animationEnable) == 0x88, "+0x88"); - static_assert(offsetof(DecalTemplate, m_animationFrameWidthRelative) == 0x8C, "+0x8C"); - static_assert(offsetof(DecalTemplate, m_animationFrameCount) == 0x94, "+0x94"); - static_assert(offsetof(DecalTemplate, m_animationFrameCountX) == 0x98, "+0x98"); - static_assert(offsetof(DecalTemplate, m_frameCountXReciprocal) == 0x9C, "+0x9C"); - static_assert(offsetof(DecalTemplate, m_uvExtent) == 0xA0, "+0xA0"); -#endif }; } // namespace geom diff --git a/Code/BF2/Geom/DecalSystem/IDecalManager.h b/Code/BF2/Geom/DecalSystem/IDecalManager.h index e2824e91b..42641a232 100644 --- a/Code/BF2/Geom/DecalSystem/IDecalManager.h +++ b/Code/BF2/Geom/DecalSystem/IDecalManager.h @@ -1,5 +1,5 @@ // Shared manager contract for decal clients, templates and frame updates. -// The implementation must preserve the decals-enabled byte at +0x2A6 for VideoOptions. +// The decals-enabled flag (retail +0x2A6) is set by VideoOptions through DecalManager::setEnabledField. #ifndef BF2_GEOM_DECALSYSTEM_IDECALMANAGER_H #define BF2_GEOM_DECALSYSTEM_IDECALMANAGER_H diff --git a/Code/BF2/Geom/DecalSystem/IDecalTemplate.h b/Code/BF2/Geom/DecalSystem/IDecalTemplate.h index f6b9dc9c3..bedc2e063 100644 --- a/Code/BF2/Geom/DecalSystem/IDecalTemplate.h +++ b/Code/BF2/Geom/DecalSystem/IDecalTemplate.h @@ -37,7 +37,7 @@ class IDecalTemplate virtual void setRandomColorIntensity(float intensity) = 0; // +0x18 / +0x04 virtual float getRandomColorIntensity() const = 0; // +0x1C virtual void setColor(const Vec3& color) = 0; // +0x20 / +0x08 - virtual Vec3 getColor() const = 0; // +0x24 101AF4C0 (hidden ptr) + virtual Vec3 getColor() const = 0; // +0x24 (hidden ptr); body DecalTemplate::getColor virtual void setIsStatic(bool isStatic) = 0; // +0x28 / +0x20 virtual bool getIsStatic() const = 0; // +0x2C virtual void setUsedOnTransparentMaterials(bool used) = 0; // +0x30 / +0x21 diff --git a/Code/BF2/Geom/GeometryInstanceData.h b/Code/BF2/Geom/GeometryInstanceData.h index 24fd4f3f1..920b05b3c 100644 --- a/Code/BF2/Geom/GeometryInstanceData.h +++ b/Code/BF2/Geom/GeometryInstanceData.h @@ -1,13 +1,13 @@ // Shared geometry-instance data prefix; this does not define the complete interface. -// [PLATFORM] x86 rendering retains the VC7.1 string layout, including in native-host builds. -// [CHOSEN, not recovered] The 64-bit port uses native string and pointer sizes; -// future native geometry owners must use this prefix. No x64 renderer is supplied here. +// [CHOSEN, not recovered] The name is the toolset's std::string on every target (issue #7), so +// the prefix uses native string and pointer sizes; geometry owners must use this prefix. +// The retail x86 prefix was 0x30 bytes, with the two opacity factors at +0x28 and +0x2C. #ifndef BF2_GEOM_GEOMETRYINSTANCEDATA_H #define BF2_GEOM_GEOMETRYINSTANCEDATA_H #include #if defined(_MSC_VER) && !defined(_WIN64) -#include "../../RendDX9Abi/Vc71String.h" +#include #else #include #endif @@ -21,7 +21,7 @@ struct GeometryInstanceData void* const* m_vptr; #if defined(_MSC_VER) && !defined(_WIN64) - vc71::string m_name; + std::string m_name; #else std::string m_name; #endif @@ -30,9 +30,13 @@ struct GeometryInstanceData float m_float28; // base opacity (Armor's destruction fade) float m_float2C; // distance/cull opacity - // Isolated logical slots: PE +F4 = ordinal61, ELF +F8 = ordinal62. - // RendDX9 0x10103C40 stores the float in the Ra transparency parameter (ret 4). - // No x86 fastcall dummy register argument may be carried into the native x64 call. +#if defined(BF2_STATIC_PLUGINS) && !defined(_MSC_VER) + // [CHOSEN, not recovered] Native geometry owners still publish explicit PE + // function tables, not compiler-emitted ELF tables. Their opacity entry is + // ordinal 61. The audit checks every provider and this constant together. + static constexpr unsigned nativeOpacitySlot = 61; +#endif + // Sends the combined opacity to the geometry owner's transparency parameter. void setOpacity(float value) { #ifdef _MSC_VER @@ -40,19 +44,17 @@ struct GeometryInstanceData reinterpret_cast(m_vptr[61])(this, value); #else typedef void (*Function)(void*, float); +#if defined(BF2_STATIC_PLUGINS) + reinterpret_cast(m_vptr[nativeOpacitySlot])(this, value); +#else reinterpret_cast(m_vptr[62])(this, value); +#endif #endif } }; -#if defined(_MSC_VER) && !defined(_WIN64) -static_assert(offsetof(GeometryInstanceData, m_float28) == 0x28, "retail geometry opacity"); -static_assert(offsetof(GeometryInstanceData, m_float2C) == 0x2C, "retail geometry cull fade"); -static_assert(sizeof(GeometryInstanceData) == 0x30, "retail geometry data prefix"); -#else static_assert(offsetof(GeometryInstanceData, m_float28) == sizeof(void*) + sizeof(std::string) + 2 * sizeof(unsigned int), "native geometry data prefix"); -#endif } } } #endif diff --git a/Code/BF2/Geom/GeometryTemplateManager.cpp b/Code/BF2/Geom/GeometryTemplateManager.cpp index 6917ac250..85220fcd3 100644 --- a/Code/BF2/Geom/GeometryTemplateManager.cpp +++ b/Code/BF2/Geom/GeometryTemplateManager.cpp @@ -6,25 +6,28 @@ #ifdef BF2_IMAGE_RENDDX9 #include "../../RendDX9Abi/ModuleCommon.h" -#include "../../RendDX9Abi/Vc71Map.h" -#include "../../RendDX9Abi/Vc71String.h" -#include "../../RendDX9Abi/Vc71Vector.h" +#include +#include +#include #include "../../RendDX9Abi/PluginEntry.h" #include "../../RendDX9Abi/BfMemory.h" #include "../../RendDX9Abi/Frontier.h" #include "../Core/EventManager.h" #include "../RendDX9/RendDX9Base.h" -#if BF2_PLUGIN_ABI_NATIVE #include "../IO/Console/Console.h" // getConsoleWorkingPath: typed (RW-266) -#endif #include "MeshTemplate.h" +#include "BundledMeshTemplate.h" // the geometryTemplate console's Bundled-only properties +#include "StaticMeshTemplate.h" // ... and its StaticMesh-only fields +#include "SkinnedMeshTemplate.h" +#include "GeometryTemplateManager.h" +#include "../Core/StringUtil.h" +#include "../GeomMisc/Debug.h" #include +#include -#if BF2_PLUGIN_ABI_NATIVE #include "../Core/ConsoleObjectMacro.h" #include "../Core/ConsoleObjects.h" -#endif namespace dice { namespace hfe { @@ -37,6 +40,11 @@ extern const unsigned int CID_GeometryTemplateManager = 0x870CA329u; extern IBase* g_GeometryTemplateManager; +bool GeometryTemplateNameLess::operator()(const std::string& a, const std::string& b) const +{ + return ::_stricmp(a.c_str(), b.c_str()) < 0; +} + // Slot +0x10 on the interface prefix is still unknown. Do not invent a declaration merely to // reach the instruction-proven +0x14/+0x1C setters: keep the owner opaque and isolate those two // exact x86 calls below. IBase's four-slot prefix is independently established and remains typed. @@ -49,95 +57,79 @@ IBase* templateBase(IGeometryTemplate* value) return reinterpret_cast(value); } -void setTemplateName(IGeometryTemplate* value, const vc71::string& name) +void setTemplateName(IGeometryTemplate* value, const std::string& name) { - typedef void (__thiscall *Fn)(void*, const vc71::string&); - void* target = (*reinterpret_cast(value))[0x14 / sizeof(void*)]; + typedef void (__thiscall *Fn)(void*, const std::string&); + void* target = (*reinterpret_cast(value))[0x14 / 4]; reinterpret_cast(target)(value, name); } -void setTemplatePath(IGeometryTemplate* value, const vc71::string& path) +void setTemplatePath(IGeometryTemplate* value, const std::string& path) { - typedef void (__thiscall *Fn)(void*, const vc71::string&); - void* target = (*reinterpret_cast(value))[0x1C / sizeof(void*)]; + typedef void (__thiscall *Fn)(void*, const std::string&); + void* target = (*reinterpret_cast(value))[0x1C / 4]; reinterpret_cast(target)(value, path); } // The owning map's pair destructor at 0x100B1174 releases its interface value first and destroys -// its key second. mapEraseWithValueDestroy invokes this hook only after the node has been unlinked, -// matching the observable re-entrant ordering of PE 0x100C7371. -void releaseMappedInterface(vc71::map_node* node) +// its key second. +void releaseMappedInterface(IGeometryTemplate* value) { - IBase* value = static_cast(vc71::mapNodeValue(node)); - if (value) - value->release(); + IBase* const base = templateBase(value); + if (base) + base->release(); } -// recurse through the right subtree, destroy the current node, then -// continue down the left side. The tree stays linked during value release just as retail's -// std::map::_Erase does; this deliberately preserves its awkward re-entrant view while clearing. -// The traversal algorithm is recovered, but the node shape remains Vc71Map's unbalanced -// [CHOSEN, not recovered] RW-74 tree; destruction order can therefore differ after insertions. -void clearOwnedSubtree(vc71::map_node* node, vc71::map_node* head) +// Unlinks one entry, then releases its interface - the observable re-entrant ordering of +// PE 0x100C7371: a re-entrant lookup during the release no longer finds the entry. +void eraseOwnedEntry(GeometryTemplateRegistry& map, GeometryTemplateRegistry::iterator entry) { - while (node && node != head) - { - clearOwnedSubtree(node->right, head); - vc71::map_node* left = node->left; - releaseMappedInterface(node); - reinterpret_cast(node->value)->~string(); - ::renddx9abi::engineFree(node); - node = left; - } + IGeometryTemplate* const value = entry->second; + map.erase(entry); + releaseMappedInterface(value); } -void clearOwnedMap(vc71::map_layout& map) +// std::map::_Erase from the root: right subtree, node, left subtree - descending key order - +// with the tree still linked while each interface is released; then the map is relinked empty. +template +void clearOwnedMap(Registry& map) { - if (!map.head) - return; - clearOwnedSubtree(map.head->parent, map.head); - map.relinkEmpty(); + for (typename Registry::reverse_iterator it = map.rbegin(); it != map.rend(); ++it) + if (it->second) + reinterpret_cast(it->second)->release(); + map.clear(); } -void destroyOwnedMap(vc71::map_layout& map) +// clear, then the head node. The owner frees its storage afterwards without running a C++ +// destructor, so the map is destroyed here. +template +void destroyOwnedMap(Registry& map) { clearOwnedMap(map); - if (map.head) - ::renddx9abi::engineFree(map.head); - map.comp = 0; - map.head = 0; - map.size = 0; + map.~Registry(); } // A non-owning, manually-lived slot lets release() reproduce retail's exact member teardown order: // optimizer map, vector, string, active reference, template map. A normal C++ string member would // be destroyed after the destructor body and therefore move it past the active release. -union Vc71StringStorage +union ManualStringStorage { - char bytes[sizeof(vc71::string)]; + char bytes[sizeof(std::string)]; void* alignment; - Vc71StringStorage() {} - ~Vc71StringStorage() {} + ManualStringStorage() {} + ~ManualStringStorage() {} - vc71::string& get() { return *reinterpret_cast(bytes); } + std::string& get() { return *reinterpret_cast(bytes); } }; -static_assert(sizeof(Vc71StringStorage) == sizeof(vc71::string), - "manual VC7.1 string storage must remain 28 bytes"); +static_assert(sizeof(ManualStringStorage) == sizeof(std::string), + "manual string storage must match the string"); const renddx9abi::HostString& getConsoleWorkingPath() { - // HostString selects the native or VC7.1 return type across the console boundary. // The published pointer addresses the Console object even though it has no IBase base. -#if BF2_PLUGIN_ABI_NATIVE return reinterpret_cast(mainConsole)->getWorkingPath(); -#else - typedef const renddx9abi::HostString& (__thiscall *Fn)(void*); - void* console = static_cast(mainConsole); - void* target = (*reinterpret_cast(console))[0x84 / sizeof(void*)]; - return reinterpret_cast(target)(console); -#endif } } // anonymous namespace @@ -163,49 +155,48 @@ class GeometryTemplateManager : public IBase virtual IGeometryTemplate* getActive() const; // +0x20 virtual void removeTemplate(const ::renddx9abi::HostString& name); // +0x24 virtual void clear(); // +0x28 - virtual void slot_0x2C(); - virtual void slot_0x30(); + // [CHOSEN, not recovered] element and argument type, under the unobservable-type exception. + virtual const std::vector& slot_0x2C(); // +0x2C + virtual const ::renddx9abi::HostString& slot_0x30(std::uint32_t unused); // +0x30 virtual void slot_0x34(); virtual void slot_0x38(); virtual void loadUsedTemplates(); // +0x3C virtual void resetTemplateUse(); // +0x40 virtual int getUsedTemplateCount(); // +0x44 virtual void slot_0x48(); - virtual void slot_0x4C(); - virtual bool registerOptimizer(const vc71::string& className, - const vc71::string& key); // +0x50 - virtual void runOptimizers(); // +0x54 + virtual IGeometryOptimizer* createOptimizer(unsigned int classId, + const std::string& key); // +0x4C + virtual IGeometryOptimizer* registerOptimizer(const std::string& className, + const std::string& key); // +0x50 + virtual bool runOptimizers(); // +0x54 virtual void clearOptimizers(); // +0x58 - virtual void slot_0x5C(); - virtual vc71::map_layout* getTemplateRegistry(); // +0x60 + virtual void visitTemplateClassIds(); // +0x5C + virtual GeometryTemplateRegistry* getTemplateRegistry(); // +0x60 private: void destroyOwnedMembers(); - IGeometryTemplate* createQualified(const vc71::string& typeName, - const vc71::string& fullName); + IGeometryTemplate* createQualified(const std::string& typeName, + const std::string& fullName); int m_refCount; // +0x04 - vc71::map_layout m_templates; // +0x08, no-case string -> owning template pointer + GeometryTemplateRegistry m_templates; // +0x08, no-case string -> owning template pointer IGeometryTemplate* m_active; // +0x14, owning - Vc71StringStorage m_string18; // +0x18, purpose unresolved - vc71::vector_layout m_vector34; // +0x34 - vc71::map_layout m_optimizers; // +0x44, owning optimizer pointer + ManualStringStorage m_string18; // +0x18, purpose unresolved + // [UNRESOLVED] element type: nothing recovered reads or fills it. + std::vector m_vector34; // +0x34 + // PE 0x1015E4F0 uses the same _stricmp comparator as the template registry. + typedef std::map OptimizerRegistry; + OptimizerRegistry m_optimizers; // +0x44, owning }; -static_assert(sizeof(GeometryTemplateManager) == 0x50, - "RefFactory_geom_GeometryTemplateManager allocates 0x50"); - +// Retail allocation (RefFactory_geom_GeometryTemplateManager) is 0x50 bytes. Both maps are +// default-constructed; the string slot is built in place. +// PE 0x100C7E95 GeometryTemplateManager::GeometryTemplateManager() : m_refCount(1) , m_active(0) { - m_templates.construct(); - new (m_string18.bytes) vc71::string(); - m_vector34.alloc = 0; - m_vector34.first = 0; - m_vector34.last = 0; - m_vector34.end = 0; - m_optimizers.construct(); + new (m_string18.bytes) std::string(); } void GeometryTemplateManager::addRef() @@ -218,18 +209,15 @@ int GeometryTemplateManager::getRef() return m_refCount; } +// PE 0x100C8751: the members in this exact order. void GeometryTemplateManager::destroyOwnedMembers() { - // PE 0x100C8751, in this exact order. destroyOwnedMap(m_optimizers); - if (m_vector34.first) - ::renddx9abi::engineFree(m_vector34.first); - m_vector34.first = 0; - m_vector34.last = 0; - m_vector34.end = 0; + typedef std::vector UnresolvedVector; + m_vector34.~UnresolvedVector(); - m_string18.get().~string(); + m_string18.get().~basic_string(); if (m_active) templateBase(m_active)->release(); @@ -237,6 +225,7 @@ void GeometryTemplateManager::destroyOwnedMembers() destroyOwnedMap(m_templates); } +// PE 0x100C8732 int GeometryTemplateManager::release() { const int remaining = --m_refCount; @@ -248,6 +237,7 @@ int GeometryTemplateManager::release() return remaining; } +// PE 0x100C7ED0 void* GeometryTemplateManager::queryInterface(unsigned int iid) const { if (iid == RD9_IID_IBASE || iid == IID_IGeometryTemplateManager) @@ -255,6 +245,7 @@ void* GeometryTemplateManager::queryInterface(unsigned int iid) const return 0; } +// PE 0x1015D470 void GeometryTemplateManager::setActive(IGeometryTemplate* value) { if (m_active) @@ -275,45 +266,44 @@ IGeometryTemplate* GeometryTemplateManager::getActive() const return m_active; } +// PE 0x1015DC30 void GeometryTemplateManager::registerTemplate(IGeometryTemplate* value, const ::renddx9abi::HostString& hostName) { if (!value) return; - // The registry is keyed by vc71 strings; convert once here. Identity in the compat flavour. - const vc71::string& name = ::renddx9abi::toVc71String(hostName); + // The registry's own key copy of the host string. + const std::string& name = ::renddx9abi::fromHostString(hostName); - vc71::map_node* node = vc71::mapInsertInsensitive(m_templates, 0x30, name); - if (!node) - { - RD9_FRONTIER("dice::hfe::geom::GeometryTemplateManager::registerTemplate " - "(VC7.1 map allocation failed)", 0x10); - } + // operator[]: the existing entry, or a fresh one holding null. + const GeometryTemplateRegistry::iterator node = + m_templates.insert( + GeometryTemplateRegistry::value_type(name, static_cast(0))).first; - IBase* old = static_cast(vc71::mapNodeValue(node)); + IBase* old = templateBase(node->second); if (old) { old->release(); - vc71::mapNodeValueRef(node) = 0; + node->second = 0; } - vc71::mapNodeValueRef(node) = value; + node->second = value; templateBase(value)->addRef(); setTemplateName(value, name); setActive(value); } +// PE 0x1015DC80 IGeometryTemplate* GeometryTemplateManager::createTemplate(unsigned int classId, const ::renddx9abi::HostString& hostName) { - const vc71::string& name = ::renddx9abi::toVc71String(hostName); + const std::string& name = ::renddx9abi::fromHostString(hostName); - vc71::map_node* found = vc71::mapFindInsensitive(m_templates, name); - if (found) + const GeometryTemplateRegistry::iterator found = m_templates.find(name); + if (found != m_templates.end()) { - IGeometryTemplate* value = - static_cast(vc71::mapNodeValue(found)); + IGeometryTemplate* value = found->second; setActive(value); return value; } @@ -326,52 +316,52 @@ IGeometryTemplate* GeometryTemplateManager::createTemplate(unsigned int classId, return 0; } - vc71::map_node* node = vc71::mapInsertInsensitive(m_templates, 0x30, name); - if (!node) - { - RD9_FRONTIER("dice::hfe::geom::GeometryTemplateManager::createTemplate " - "(VC7.1 map allocation failed)", 0x14); - } + // operator[] again: the factory may have registered the name in the meantime. + const GeometryTemplateRegistry::iterator node = + m_templates.insert( + GeometryTemplateRegistry::value_type(name, static_cast(0))).first; - vc71::mapNodeValueRef(node) = value; - reinterpret_cast(value)[4] = 0; // GeometryTemplate's shipped load/keep byte. + node->second = value; + reinterpret_cast(value)->m_keepData = 0; // the shipped load/keep byte, +4 templateBase(value)->addRef(); // registry ownership setTemplateName(value, name); const renddx9abi::HostString& hostPath = getConsoleWorkingPath(); -#if BF2_PLUGIN_ABI_NATIVE - const vc71::string templatePath(hostPath.data(), + const std::string templatePath(hostPath.data(), static_cast(hostPath.size())); setTemplatePath(value, templatePath); -#else - setTemplatePath(value, hostPath); -#endif setActive(value); templateBase(value)->release(); // drop the factory reference return value; // borrowed from registry/active } -IGeometryTemplate* GeometryTemplateManager::createQualified(const vc71::string& typeName, - const vc71::string& fullName) +// PE 0x1015D4B0. The qualified class name is a copy of the appended temporary and is destroyed +// before the createTemplate slot (+0x14) runs. +IGeometryTemplate* GeometryTemplateManager::createQualified(const std::string& typeName, + const std::string& fullName) { - vc71::string className("dice.hfe.geom.GeometryTemplate."); - className += typeName; - unsigned int classId = 0; - if (!classManager->getClassID(renddx9abi::HostString(className.c_str()), &classId)) + bool found; + { + const std::string className = std::string("dice.hfe.geom.GeometryTemplate.") += typeName; + found = classManager->getClassID(::renddx9abi::toHostString(className), &classId); + } + if (!found) return 0; - // createTemplate is a host-typed slot, so an internal vc71 caller converts on the way in. + // createTemplate is a host-typed slot; the internal caller passes a host string. return createTemplate(classId, ::renddx9abi::toHostString(fullName)); } +// PE 0x1015D820. A registry hit answers the stored template; a miss splits at the first ':' and asks +// createQualified for the prefix class. IGeometryTemplate* GeometryTemplateManager::getTemplate(const ::renddx9abi::HostString& hostName) { - const vc71::string& name = ::renddx9abi::toVc71String(hostName); + const std::string& name = ::renddx9abi::fromHostString(hostName); - vc71::map_node* found = vc71::mapFindInsensitive(m_templates, name); - if (found) - return static_cast(vc71::mapNodeValue(found)); + const GeometryTemplateRegistry::iterator found = m_templates.find(name); + if (found != m_templates.end()) + return found->second; unsigned int colon = 0; while (colon != name.size() && name.c_str()[colon] != ':') @@ -379,23 +369,25 @@ IGeometryTemplate* GeometryTemplateManager::getTemplate(const ::renddx9abi::Host if (colon == name.size()) return 0; - const vc71::string prefix(name.c_str(), colon); - const vc71::string suffix(name.c_str() + colon + 1, name.size() - colon - 1); + const std::string prefix(name.c_str(), colon); + const std::string suffix(name.c_str() + colon + 1, name.size() - colon - 1); (void)suffix; // Constructed and destroyed by retail, but never read (shipped quirk). return createQualified(prefix, name); // The full `type:name`, not the suffix, is the map key. // (createQualified re-enters createTemplate, which is // a host-typed slot - see its toHostString below.) } +// PE 0x1015D980 void GeometryTemplateManager::removeTemplate(const ::renddx9abi::HostString& hostName) { - const vc71::string& name = ::renddx9abi::toVc71String(hostName); + const std::string& name = ::renddx9abi::fromHostString(hostName); - vc71::map_node* node = vc71::mapFindInsensitive(m_templates, name); - if (node) - vc71::mapEraseWithValueDestroy(m_templates, node, &releaseMappedInterface); + const GeometryTemplateRegistry::iterator node = m_templates.find(name); + if (node != m_templates.end()) + eraseOwnedEntry(m_templates, node); } +// PE 0x1015DB90 void GeometryTemplateManager::clear() { if (m_active) @@ -407,43 +399,53 @@ void GeometryTemplateManager::clear() clearOwnedMap(m_optimizers); } -#define RD9_GTM_FRONTIER(method, slotOffset) \ - void GeometryTemplateManager::method() \ - { \ - RD9_FRONTIER("dice::hfe::geom::GeometryTemplateManager::" #method, slotOffset); \ - } +// PE 0x1015D940: a function-local static vector (0x102605FC, guard 0x1026060C) that nothing ever +// fills, returned by address. BF2.exe saveAllUsedTemplates walks its four-byte entries +// (0x00734703) and passes each nonzero one to +0x30 (0x00734727); it is always empty. +// [CHOSEN, not recovered] std::uint32_t element (unobservable-type exception, AGENTS.md): no +// image stores an element. _r 0x102CA220, editor 0x103152F0. +const std::vector& GeometryTemplateManager::slot_0x2C() +{ + static std::vector entries; + return entries; +} -RD9_GTM_FRONTIER(slot_0x2C, 0x2C) -RD9_GTM_FRONTIER(slot_0x30, 0x30) -RD9_GTM_FRONTIER(slot_0x34, 0x34) -RD9_GTM_FRONTIER(slot_0x38, 0x38) -RD9_GTM_FRONTIER(slot_0x4C, 0x4C) -RD9_GTM_FRONTIER(slot_0x5C, 0x5C) +// PE 0x1015D430 (`retn 4`): the four-byte argument is never read; the answer is a function-local +// static empty string (0x102605DC, guard 0x102605F8). [CHOSEN, not recovered] argument type +// (unobservable-type exception). _r 0x102C9010, editor 0x10315290. +const ::renddx9abi::HostString& GeometryTemplateManager::slot_0x30(std::uint32_t) +{ + static const ::renddx9abi::HostString empty; + return empty; +} -#undef RD9_GTM_FRONTIER +// PE 0x100C7EF8: both primary-table entries point to the same bare return. +void GeometryTemplateManager::slot_0x34() {} +// PE 0x100C7EF8. +void GeometryTemplateManager::slot_0x38() {} -// clear each template's use byte without changing registry ownership. +// PE 0x1015D7C0. Clear each template's use byte without changing registry ownership. void GeometryTemplateManager::resetTemplateUse() { - for (vc71::map_node* node = vc71::mapFirst(m_templates); node; - node = vc71::mapNext(m_templates, node)) - reinterpret_cast(vc71::mapNodeValue(node))->m_keepData = 0; + for (GeometryTemplateRegistry::iterator node = m_templates.begin(); + node != m_templates.end(); ++node) + reinterpret_cast(node->second)->m_keepData = 0; } -// The ResourceManager gate precedes the walk; loaded state is not tested. +// PE 0x1015D740. The ResourceManager gate precedes the walk; loaded state is not tested. int GeometryTemplateManager::getUsedTemplateCount() { if (!dx9rend::resourceManagerIsReady()) return 0; int count = 0; - for (vc71::map_node* node = vc71::mapFirst(m_templates); node; - node = vc71::mapNext(m_templates, node)) - if (reinterpret_cast(vc71::mapNodeValue(node))->m_keepData) + for (GeometryTemplateRegistry::iterator node = m_templates.begin(); + node != m_templates.end(); ++node) + if (reinterpret_cast(node->second)->m_keepData) ++count; return count; } -// Source-level map erase preserves the PE's advance-before-release order. +// PE 0x1015D9C0. Source-level map erase preserves the PE's advance-before-release order. void GeometryTemplateManager::loadUsedTemplates() { if (!dx9rend::resourceManagerIsReady()) @@ -463,13 +465,13 @@ void GeometryTemplateManager::loadUsedTemplates() } if (!dx9rend::readLevelLoadBoolSetting("GSKeepTemplates", false)) { - vc71::map_node* node = vc71::mapFirst(m_templates); - while (node) + GeometryTemplateRegistry::iterator node = m_templates.begin(); + while (node != m_templates.end()) { - vc71::map_node* const current = node; - node = vc71::mapNext(m_templates, node); - if (!reinterpret_cast(vc71::mapNodeValue(current))->m_keepData) - vc71::mapEraseWithValueDestroy(m_templates, current, releaseMappedInterface); + const GeometryTemplateRegistry::iterator current = node; + ++node; + if (!reinterpret_cast(current->second)->m_keepData) + eraseOwnedEntry(m_templates, current); } } else @@ -478,11 +480,10 @@ void GeometryTemplateManager::loadUsedTemplates() ::renddx9abi::logf("GeometryTemplateManager.cpp:309: Do not keep geom templates"); } - for (vc71::map_node* node = vc71::mapFirst(m_templates); node; - node = vc71::mapNext(m_templates, node)) + for (GeometryTemplateRegistry::iterator node = m_templates.begin(); + node != m_templates.end(); ++node) { - GeometryTemplate* const value = - reinterpret_cast(vc71::mapNodeValue(node)); + GeometryTemplate* const value = reinterpret_cast(node->second); if (value->m_keepData && !value->isLoaded()) value->load(); value->m_keepData = 0; @@ -491,70 +492,97 @@ void GeometryTemplateManager::loadUsedTemplates() // Technique initialization gates start pending and clear after successful initialization. -// [INFERRED] Owns the skinned and bundled technique gates. -// [FRONTIER] Static-mesh re-arming needs access to its existing file-local gate; -// expose that gate or an accessor and verify shader changes across level reloads. -// Do not create a second store: current static-mesh tables otherwise retain the first shader set. +// [INFERRED] Owns the skinned and bundled technique gates; the static-mesh gate lives with its +// reader in StaticMeshTemplate.cpp. +extern unsigned char g_staticMeshTechniquesPending; // byte_1023982C, StaticMeshTemplate.cpp unsigned char g_skinnedMeshTechniquesPending = 1; // byte_102397D4, initial value 1 unsigned char g_bundledMeshTechniquesPending = 1; // byte_10239294, initial value 1 +// The three technique initializers the priming tail calls. 0x10116EA0 is file-local to +// StaticMeshTemplate.cpp and reached through its bridge; the other two are BundledMeshTemplate.h +// and SkinnedMesh.h's published bodies. +void staticMeshPrimeTechniques(); // 0x10116EA0 +void bundledMeshInitTechniques(); // 0x100E8F20 +void skinnedMeshInitTechniques(); // 0x1010F190 + // Re-arms geometry technique initialization after shader archives change. -// [INFERRED] slot name. Static-mesh re-arming still reports a missing cross-file store. -// An empty registry returns after re-arming; a nonempty registry reaches the temp_rel -// priming [FRONTIER] until template creation and all three technique initializers are callable. +// [INFERRED] slot name. +// An empty registry returns after re-arming; a nonempty registry primes each shared table +// through a temporary "temp_rel" template of the matching class. void GeometryTemplateManager::slot_0x48() { - // The three once-gates. [INFERRED] placement for the two that have no rebuilt owner yet: this - // translation unit holds their only writer, and their readers (the BundledMesh and SkinnedMesh - // initTechniques bodies) are not recovered, so they move to those files when those land. + // The three once-gates, in the shipped store order (0x1015D53B..0x1015D545). [INFERRED] + // placement for the skinned and bundled gates: this translation unit holds their only writer. + g_staticMeshTechniquesPending = 1; // byte_1023982C g_skinnedMeshTechniquesPending = 1; // byte_102397D4 g_bundledMeshTechniquesPending = 1; // byte_10239294 - // byte_1023982C - see the block above. Named and counted rather than written to a second store. - // No value is fabricated: the shipped store is a plain byte nothing in this slot reads back. - { - static unsigned int hits = 0; - ++hits; - if (hits <= 4u || (hits & (hits - 1u)) == 0u) - ::renddx9abi::logf("[FRONTIER] dice::hfe::geom - the byte_1023982C re-arm " - "(g_staticMeshTechniquesPending) reached from " - "GeometryTemplateManager::slot_0x48 (hit #%u) - SKIPPED: the store " - "is file-local to Geom/StaticMeshTemplate.cpp's anonymous " - "namespace. Retail would set it to 1 so the next material read " - "rebuilds the static-mesh technique tables", hits); - } - - if (m_templates.size == 0) // cmp [esi+10h], 0 / jbe loc_1015D652 - unsigned + if (m_templates.size() == 0) // cmp [esi+10h], 0 / jbe loc_1015D652 - unsigned return; // `result` is still the 1 loaded at 1015D536 - RD9_FRONTIER("dice::hfe::geom::GeometryTemplateManager::slot_0x48 " - "(the temp_rel priming tail: createTemplate is a frontier and the three " - "initTechniques bodies are unrecovered)", 0x48); + // 0x1015D555..0x1015D64B: per class, createTemplate (+0x14) with a temporary "temp_rel" + // string, the initializer called with ecx = the returned template, then removeTemplate (+0x24) + // with a fresh temporary. The initializers pass ecx on to meshBuildTechniqueMasks, which + // overwrites it unread (0x101921E2), so the template is not an argument here; creating and + // removing it is kept for its registry, factory and active-template side effects. + createTemplate(0x870CA653u, ::renddx9abi::HostString("temp_rel")); // dword_1021AF04 + staticMeshPrimeTechniques(); // 0x10116EA0 + removeTemplate(::renddx9abi::HostString("temp_rel")); + createTemplate(0x870CA651u, ::renddx9abi::HostString("temp_rel")); // dword_1021AEFC + bundledMeshInitTechniques(); // 0x100E8F20 + removeTemplate(::renddx9abi::HostString("temp_rel")); + createTemplate(0x870CA652u, ::renddx9abi::HostString("temp_rel")); // dword_1021AF00 + skinnedMeshInitTechniques(); // 0x1010F190 + removeTemplate(::renddx9abi::HostString("temp_rel")); } -bool GeometryTemplateManager::registerOptimizer(const vc71::string& className, - const vc71::string& key) +// PE 0x1015DD30. Duplicate keys refuse creation; the factory may re-enter the registry. +// The interface id is dword_1021AE54 = 0x138E7 (80103), the one the optimizers' queryInterface +// 0x10134E70 accepts besides 1. +IGeometryOptimizer* GeometryTemplateManager::createOptimizer(unsigned int classId, + const std::string& key) { - vc71::string full("dice.hfe.geom.GeometryOptimizer."); - full += className; + if (m_optimizers.find(key) != m_optimizers.end()) + return 0; + IGeometryOptimizer* const value = static_cast( + classManager->createInstance(classId, 80103u, 0)); + if (!value) + return 0; + m_optimizers[key] = value; + value->addRef(); + value->release(); + return value; +} +// PE 0x1015D660. Returns the optimizer pointer, not a success Boolean. +IGeometryOptimizer* GeometryTemplateManager::registerOptimizer(const std::string& className, + const std::string& key) +{ unsigned int classId = 0; - if (!classManager->getClassID(renddx9abi::HostString(full.c_str()), &classId)) - return false; + bool found; + { + const std::string full(std::string("dice.hfe.geom.GeometryOptimizer.") += className); + found = classManager->getClassID(renddx9abi::HostString(full.c_str()), &classId); + } + if (!found) + return 0; + return createOptimizer(classId, key); +} - (void)key; - RD9_FRONTIER("dice::hfe::geom::GeometryTemplateManager::slot_0x4C " - "(optimizer insertion after a resolved class)", 0x4C); +// PE 0x1015D8D0. The optimizer results are discarded; this method always returns false. +bool GeometryTemplateManager::runOptimizers() +{ + for (OptimizerRegistry::iterator it = m_optimizers.begin(); it != m_optimizers.end(); ++it) + it->second->optimize(); return false; } -void GeometryTemplateManager::runOptimizers() +// PE 0x1015D6E0. Even the discarded class-ID queries remain virtual calls in registry order. +void GeometryTemplateManager::visitTemplateClassIds() { - if (m_optimizers.empty()) - return; - RD9_FRONTIER("dice::hfe::geom::GeometryTemplateManager::runOptimizers " - "(nonempty registry; optimizer +0x14 interface prefix is unrecovered)", 0x54); + for (GeometryTemplateRegistry::iterator it = m_templates.begin(); it != m_templates.end(); ++it) + it->second->getClassId(); } void GeometryTemplateManager::clearOptimizers() @@ -562,7 +590,7 @@ void GeometryTemplateManager::clearOptimizers() clearOwnedMap(m_optimizers); } -vc71::map_layout* GeometryTemplateManager::getTemplateRegistry() +GeometryTemplateRegistry* GeometryTemplateManager::getTemplateRegistry() { return &m_templates; } @@ -579,7 +607,11 @@ IBase* __fastcall createGeometryTemplateManager(unsigned int iid, IBase* outer) return static_cast(itf); } -#if BF2_PLUGIN_ABI_NATIVE + +void geometryTemplateManagerRearmTechniques(IBase* manager) +{ + static_cast(manager)->slot_0x48(); +} namespace { @@ -590,18 +622,53 @@ GeometryTemplateManager* templateManager() return static_cast(g_GeometryTemplateManager); } +// PE 0x100B111A. The second getActive call reloads the published manager. IGeometryTemplate* activeGeometryTemplate() { - if (!templateManager()) + GeometryTemplateManager* const manager = templateManager(); + if (!manager) + return 0; + if (!manager->getActive()) return 0; - IGeometryTemplate* active = templateManager()->getActive(); - return active ? static_cast( - templateBase(active)->queryInterface(IID_IGeometryTemplate)) : 0; + IGeometryTemplate* const active = templateManager()->getActive(); + return static_cast( + templateBase(active)->queryInterface(IID_IGeometryTemplate)); +} + +// sub_100B1269 / sub_100B128C / sub_100B12AF - the active template when its class id +// (+0x10) is BundledMesh (0x870CA651, dword_1021AEFC), StaticMesh (0x870CA653, dword_1021AF04), +// or any of BundledMesh, StaticMesh, SkinnedMesh (0x870CA652, dword_1021AF00); null otherwise. +// The class id is fetched again for every comparison, as shipped. +BundledMeshTemplate* activeBundledMeshTemplate() +{ + IGeometryTemplate* const value = activeGeometryTemplate(); + if (value && value->getClassId() == 0x870CA651u) + return static_cast(value); + return 0; +} + +// PE 0x100B128C +StaticMeshTemplate* activeStaticMeshTemplate() +{ + IGeometryTemplate* const value = activeGeometryTemplate(); + if (value && value->getClassId() == 0x870CA653u) + return static_cast(value); + return 0; +} + +// PE 0x100B12AF +MeshTemplate* activeMeshTemplate() +{ + IGeometryTemplate* const value = activeGeometryTemplate(); + if (value && (value->getClassId() == 0x870CA651u || value->getClassId() == 0x870CA653u + || value->getClassId() == 0x870CA652u)) + return static_cast(value); + return 0; } void* templateVirtual(IGeometryTemplate* value, unsigned int byteOffset) { - return (*reinterpret_cast(value))[byteOffset / sizeof(void*)]; + return (*reinterpret_cast(value))[byteOffset / 4]; } bool getTemplateBool(unsigned int byteOffset) @@ -632,17 +699,32 @@ void setTemplateInt(unsigned int byteOffset, int setting) reinterpret_cast(templateVirtual(value, byteOffset))(value, setting); } +// PE 0x100B1389. The error path's __FILE__ attests ModuleGeom.cpp, line 0xB9, as the retail home of +// this helper; it stays here with the other geometryTemplate console code [INFERRED] placement. IGeometryTemplate* consoleCreateTemplate(const std::string& type, const std::string& name) { - vc71::string className("dice.hfe.geom.GeometryTemplate."); + std::string className("dice.hfe.geom.GeometryTemplate."); className += type.c_str(); unsigned int classId = 0; if (classManager->getClassID(renddx9abi::HostString(className.c_str()), &classId)) { - const vc71::string templateName(name.c_str()); + const std::string templateName(name.c_str()); templateManager()->createTemplate(classId, ::renddx9abi::toHostString(templateName)); } + else + { + // An unknown type is reported only while the console has a working path. + const renddx9abi::HostString& hostPath = getConsoleWorkingPath(); + if (hostPath.size() != 0) + { + const std::string workingPath(hostPath.data(), static_cast(hostPath.size())); + ::renddx9abi::Debug(DebugTypeError, + "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\ModuleGeom.cpp", + 0xB9, "") << "GeometryTemplate type:" << type << " not found. File that fails:" + << workingPath; + } + } // PE helper 0x100B1389 always returns null even when creation succeeds; the generated binding // nevertheless advertises IGeometryTemplate* and marks that null as a return value. @@ -651,13 +733,30 @@ IGeometryTemplate* consoleCreateTemplate(const std::string& type, const std::str BF2_CONSOLE_OBJECT("GeometryTemplate", 2, 0) +// A template result prints the template's name; a null template prints a fixed text (the same text as +// objectGeometryValueText in ObjectGeometryConsole.cpp). +// The retail create and active bindings format their result through it (PE 0x100B438E, the +// getReturnValueAsString of both), where the generic pointer insertion would print an address. +std::string geometryTemplateValueText(IGeometryTemplate* value) +{ + std::ostringstream out; + if (value) + out << value->getName(); + else + out << "No geometry template"; + return out.str(); +} + +// PE 0x100B2337 (binding constructor), 0x100B23C3 (argument parser: two independent persistent +// std::string tokens), 0x100B2498 (executor: needs exactly two arguments). class GeometryTemplateCreateBinding : public ConsoleObjectBaseImpl { public: + // PE 0x100B2337 GeometryTemplateCreateBinding() : m_returnValue(0) { - m_objectName = consoleDefaultName(); + m_objectName = consoleDefaultStaticName(); // "GeometryTemplate" as passed (dword_10247C20) m_access = consoleDefaultAccess(); m_category = consoleDefaultCategory(); m_functionName = "create"; @@ -676,6 +775,7 @@ class GeometryTemplateCreateBinding : public ConsoleObjectBaseImpl bool isObjectActive() const override { return true; } + // PE 0x100B2498 void executeObjectMethod() override { if (m_argCount == 2) @@ -686,13 +786,18 @@ class GeometryTemplateCreateBinding : public ConsoleObjectBaseImpl } } + // PE 0x100B23C3 void setArgFromString(int index, const std::string& value) override { BF2_CC_CONVERT(std::string, 1) BF2_CC_CONVERT(std::string, 2) } - BF2_CC_RETURN_AS_STRING + // PE 0x100B438E + std::string getReturnValueAsString() const override + { + return m_hasReturnValue ? geometryTemplateValueText(m_returnValue) : std::string(); + } BF2_CC_COMMON_HOOKS private: @@ -703,9 +808,22 @@ GeometryTemplateCreateBinding s_geometryTemplateCreateBinding; BF2_CONSOLE_OBJECT("geometryTemplate", 2, 0) +// PE 0x100B1348: stream extraction of an IGeometryTemplate*: construct an empty string, extract one +// token, look it up in the template manager. Returns the stream. +std::istream& readTemplateReference(std::istream& in, IGeometryTemplate*& result) +{ + std::string templateName; + in >> templateName; + result = templateManager()->getTemplate(::renddx9abi::toHostString(templateName)); + return in; +} + +// PE 0x100B25B7 (argument parser). The token is read by PE 0x100B1348 (stream extraction of an +// IGeometryTemplate*: a std::string token, then the template manager's getTemplate). class GeometryTemplateActiveBinding : public ConsoleObjectBaseImpl { public: + // Binding constructor: PE 0x100B24F4. GeometryTemplateActiveBinding() : m_returnValue(0) { @@ -740,18 +858,23 @@ class GeometryTemplateActiveBinding : public ConsoleObjectBaseImpl } } + // PE 0x100B25B7 void setArgFromString(int index, const std::string& value) override { if (index == 1) { static IGeometryTemplate* resolved = 0; - const vc71::string templateName(value.c_str()); - resolved = templateManager()->getTemplate(::renddx9abi::toHostString(templateName)); + std::istringstream in(value); + readTemplateReference(in, resolved); m_args[0] = reinterpret_cast(&resolved); } } - BF2_CC_RETURN_AS_STRING + // Same formatter as the create binding (retail shares one body between them). + std::string getReturnValueAsString() const override + { + return m_hasReturnValue ? geometryTemplateValueText(m_returnValue) : std::string(); + } BF2_CC_COMMON_HOOKS private: @@ -760,6 +883,173 @@ class GeometryTemplateActiveBinding : public ConsoleObjectBaseImpl GeometryTemplateActiveBinding s_geometryTemplateActiveBinding; +// The type spelling the shipped bindings carry for unsigned properties ("uint"). +typedef unsigned int uint; + +// dumpInstances - ctor 0x100B2604, active while the manager exists (0x100B2565), executor +// 0x100B2656: the manager's +0x5C with no argument. +void consoleDumpInstances() +{ + templateManager()->visitTemplateClassIds(); +} + +BF2_CONSOLE_METHOD_0_STATIC_ACTIVE(dumpInstances, consoleDumpInstances, templateManager() != 0, + kGeometryTemplateConsoleTag) + +// PE 0x100B2671 / 0x100B26DE: read-only, not a zero/one-argument property. +class GeometryTemplateNameBinding : public ConsoleObjectBaseImpl +{ +public: + // PE 0x100B2671 + GeometryTemplateNameBinding() + { + m_objectName = consoleDefaultName(); + m_access = consoleDefaultAccess(); + m_category = consoleDefaultCategory(); + m_functionName = "name"; + m_type = 2; + m_minNoArgs = m_maxNoArgs = 0; + m_returnType = "std::string"; + m_hasReturnValue = false; + m_isDynamic = true; + consoleBindingList(kGeometryTemplateConsoleTag).push_back(this); + } + + virtual bool isObjectActive() const { return activeGeometryTemplate() != 0; } + // PE 0x100B26DE + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = activeGeometryTemplate()->getName(); + } + } + virtual void setArgFromString(int, const std::string&) {} + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; + +GeometryTemplateNameBinding s_geometryTemplateNameBinding; + +// setSubGeometryLodDistance geom lod distance - ctor 0x100B2711, active 0x100B26D2 (an active +// template), executor 0x100B287F: the active template's +0x30 setLodDistance. +void setSubGeometryLodDistance(int geom, int lod, float distance) +{ + activeGeometryTemplate()->setLodDistance(geom, lod, distance); +} + +// setMaterialParallaxHeightScale geom lod material value - ctor 0x100B28BF, executor 0x100B2A81: +// the active template's +0x38 setMaterialValue (the material index pushed as a full dword). +void setMaterialParallaxHeightScale(int geom, int lod, int material, float value) +{ + activeGeometryTemplate()->setMaterialValue(geom, lod, static_cast(material), value); +} + +// PE 0x100B27C0 +// PE 0x100B287F +BF2_CONSOLE_METHOD_3_STATIC_ACTIVE(setSubGeometryLodDistance, setSubGeometryLodDistance, + activeGeometryTemplate() != 0, int, int, float, + kGeometryTemplateConsoleTag) +// PE 0x100B298A +// PE 0x100B2A81 +BF2_CONSOLE_METHOD_4_STATIC_ACTIVE(setMaterialParallaxHeightScale, setMaterialParallaxHeightScale, + activeGeometryTemplate() != 0, int, int, int, float, + kGeometryTemplateConsoleTag) + +// maxSkip3pLods / maxSkipWreckLods (constructors and executors cited at the bindings below; the +// active test at 0x100B2B87 asks for a mesh template): MeshTemplate +0xE4 / +0xE0 and +0xEC / +0xE8. +uint getMaxSkip3pLods() { return static_cast(activeMeshTemplate()->getMaxSkip3pLods()); } +void setMaxSkip3pLods(uint value) { activeMeshTemplate()->setMaxSkip3pLods(static_cast(value)); } +uint getMaxSkipWreckLods() { return static_cast(activeMeshTemplate()->getMaxSkipWreckLods()); } +void setMaxSkipWreckLods(uint value) { activeMeshTemplate()->setMaxSkipWreckLods(static_cast(value)); } + +// PE 0x100B2AC9, 0x100B2B3A, 0x100B2B93: maxSkip3pLods constructor ('uint'), converter, executor. +BF2_CONSOLE_PROPERTY_FN(maxSkip3pLods, uint, activeMeshTemplate() != 0, + getMaxSkip3pLods(), setMaxSkip3pLods, kGeometryTemplateConsoleTag) +// PE 0x100B2BE6, 0x100B2CFD, 0x100B2C57, 0x100B2CB0 +BF2_CONSOLE_PROPERTY_FN(maxSkipWreckLods, uint, activeMeshTemplate() != 0, + getMaxSkipWreckLods(), setMaxSkipWreckLods, kGeometryTemplateConsoleTag) + +// The StaticMesh-only fields, active 0x100B2E0E (a StaticMesh template); each executor (cited at +// its binding below) reads or stores the field directly: shadowDetailLevel +0x2B4, +// meshDetailLevel +0x2B8, glowing +0x2A5, noLighting +0x2B0, glowFadeOutDistStart / End +// +0x2A8 / +0x2AC, ignoreLeafLighting +0x2B1. StaticMesh's draw reads them (glow fade, cone +// lighting, the LOD budget). +int getShadowDetailLevel() { return activeStaticMeshTemplate()->m_dword2B4; } +void setShadowDetailLevel(int v) { activeStaticMeshTemplate()->m_dword2B4 = v; } +int getMeshDetailLevel() { return activeStaticMeshTemplate()->m_dword2B8; } +void setMeshDetailLevel(int v) { activeStaticMeshTemplate()->m_dword2B8 = v; } +bool getGlowing() { return activeStaticMeshTemplate()->m_byte2A5 != 0; } +void setGlowing(bool v) { activeStaticMeshTemplate()->m_byte2A5 = v; } +bool getNoLighting() { return activeStaticMeshTemplate()->m_byte2B0 != 0; } +void setNoLighting(bool v) { activeStaticMeshTemplate()->m_byte2B0 = v; } +float getGlowFadeOutDistStart() { return activeStaticMeshTemplate()->m_float2A8; } +void setGlowFadeOutDistStart(float v) { activeStaticMeshTemplate()->m_float2A8 = v; } +float getGlowFadeOutDistEnd() { return activeStaticMeshTemplate()->m_float2AC; } +void setGlowFadeOutDistEnd(float v) { activeStaticMeshTemplate()->m_float2AC = v; } +bool getIgnoreLeafLighting() { return activeStaticMeshTemplate()->m_keepVegetationNormals != 0; } +void setIgnoreLeafLighting(bool v) { activeStaticMeshTemplate()->m_keepVegetationNormals = v; } + +// PE 0x100B2D50, 0x100B2DC1, 0x100B2E1A: shadowDetailLevel constructor, converter, executor. +BF2_CONSOLE_PROPERTY_FN(shadowDetailLevel, int, activeStaticMeshTemplate() != 0, + getShadowDetailLevel(), setShadowDetailLevel, kGeometryTemplateConsoleTag) +// PE 0x100B2E64, 0x100B2F22, 0x100B2ED5 +BF2_CONSOLE_PROPERTY_FN(meshDetailLevel, int, activeStaticMeshTemplate() != 0, + getMeshDetailLevel(), setMeshDetailLevel, kGeometryTemplateConsoleTag) +// PE 0x100B2F6C, 0x100B302A, 0x100B2FDD +BF2_CONSOLE_PROPERTY_FN(glowing, bool, activeStaticMeshTemplate() != 0, + getGlowing(), setGlowing, kGeometryTemplateConsoleTag) +// PE 0x100B3074, 0x100B3132, 0x100B30E5 +BF2_CONSOLE_PROPERTY_FN(noLighting, bool, activeStaticMeshTemplate() != 0, + getNoLighting(), setNoLighting, kGeometryTemplateConsoleTag) +// PE 0x100B317C, 0x100B323A, 0x100B31ED +BF2_CONSOLE_PROPERTY_FN(glowFadeOutDistStart, float, activeStaticMeshTemplate() != 0, + getGlowFadeOutDistStart(), setGlowFadeOutDistStart, kGeometryTemplateConsoleTag) +// PE 0x100B328D, 0x100B334B, 0x100B32FE +BF2_CONSOLE_PROPERTY_FN(glowFadeOutDistEnd, float, activeStaticMeshTemplate() != 0, + getGlowFadeOutDistEnd(), setGlowFadeOutDistEnd, kGeometryTemplateConsoleTag) +// PE 0x100B339E, 0x100B345C, 0x100B340F +BF2_CONSOLE_PROPERTY_FN(ignoreLeafLighting, bool, activeStaticMeshTemplate() != 0, + getIgnoreLeafLighting(), setIgnoreLeafLighting, kGeometryTemplateConsoleTag) + +// The BundledMesh-only bindings, active 0x100B3564 (a BundledMesh template). +// nrOfAnimatedUVMatrix: the executor (cited at the binding) reads or stores the int +0x10C directly. +int getNrOfAnimatedUVMatrix() { return static_cast(activeBundledMeshTemplate()->m_dword10C); } +void setNrOfAnimatedUVMatrix(int v) { activeBundledMeshTemplate()->m_dword10C = static_cast(v); } + +// PE 0x100B34A6, 0x100B3517, 0x100B3570: nrOfAnimatedUVMatrix constructor, converter, executor. +BF2_CONSOLE_PROPERTY_FN(nrOfAnimatedUVMatrix, int, activeBundledMeshTemplate() != 0, + getNrOfAnimatedUVMatrix(), setNrOfAnimatedUVMatrix, kGeometryTemplateConsoleTag) + +// setMaterialReflectionScale geom lod material value - executor 0x100B377C: the Bundled +// template's +0x40 with the float pushed in the fourth dword (the slot declares it as raw bits). +void setMaterialReflectionScale(int geom, int lod, int material, float value) +{ + int bits; + ::memcpy(&bits, &value, sizeof(bits)); + activeBundledMeshTemplate()->slot_0x40(geom, lod, material, bits); +} + +// setSpecularStaticGloss geom lod material value - executor 0x100B3986: the Bundled template's +// +0xF0 setSpecularStaticGloss. +void setSpecularStaticGloss(int geom, int lod, int material, float value) +{ + activeBundledMeshTemplate()->setSpecularStaticGloss(geom, lod, + static_cast(material), value); +} + +// PE 0x100B35BA, 0x100B3685 +BF2_CONSOLE_METHOD_4_STATIC_ACTIVE(setMaterialReflectionScale, setMaterialReflectionScale, + activeBundledMeshTemplate() != 0, int, int, int, float, + kGeometryTemplateConsoleTag) +// PE 0x100B37C4, 0x100B388F +BF2_CONSOLE_METHOD_4_STATIC_ACTIVE(setSpecularStaticGloss, setSpecularStaticGloss, + activeBundledMeshTemplate() != 0, int, int, int, float, + kGeometryTemplateConsoleTag) + bool getLightmapOverride() { return getTemplateBool(0x6C); } void setLightmapOverride(bool value) { setTemplateBool(0x68, value); } bool getDoNotGenerateLightmaps() { return getTemplateBool(0x64); } @@ -777,23 +1067,146 @@ void setLightmapSizeAll(int geom, int lod, int size) activeGeometryTemplate()->setLightmapSize(geom, lod, size); } +// PE 0x100B39D1, 0x100B3A79 BF2_CONSOLE_METHOD_3_STATIC_ACTIVE(setLightmapSizeAll, setLightmapSizeAll, activeGeometryTemplate() != 0, int, int, int, kGeometryTemplateConsoleTag) +// PE 0x100B3B6C, 0x100B3C2A, 0x100B3BDD BF2_CONSOLE_PROPERTY_FN(lightmapOverride, bool, activeGeometryTemplate() != 0, getLightmapOverride(), setLightmapOverride, kGeometryTemplateConsoleTag) +// PE 0x100B3C7F, 0x100B3D3D, 0x100B3CF0 BF2_CONSOLE_PROPERTY_FN(doNotGenerateLightmaps, bool, activeGeometryTemplate() != 0, getDoNotGenerateLightmaps(), setDoNotGenerateLightmaps, kGeometryTemplateConsoleTag) +// PE 0x100B3D92, 0x100B3E50, 0x100B3E03 BF2_CONSOLE_PROPERTY_FN(compressVertexData, bool, activeGeometryTemplate() != 0, getCompressVertexData(), setCompressVertexData, kGeometryTemplateConsoleTag) +// useRadiusForShadowDepth / useRadiusForShadowSpatial - ctors 0x100B3EA5 / 0x100B3FBE, active +// 0x100B26D2, executors 0x100B3F63 / 0x100B407C: the active template's +0x94 / +0x90 and +// +0x9C / +0x98 (the bool passed as a full dword). +// PE 0x100B3F16 +// PE 0x100B3F63 +BF2_CONSOLE_PROPERTY_FN(useRadiusForShadowDepth, bool, activeGeometryTemplate() != 0, + activeGeometryTemplate()->slot_0x94(), + activeGeometryTemplate()->slot_0x90, kGeometryTemplateConsoleTag) +// PE 0x100B402F +// PE 0x100B3FBE, 0x100B407C +BF2_CONSOLE_PROPERTY_FN(useRadiusForShadowSpatial, bool, activeGeometryTemplate() != 0, + activeGeometryTemplate()->slot_0x9C(), + activeGeometryTemplate()->slot_0x98, kGeometryTemplateConsoleTag) +// PE 0x100B40D7, 0x100B4195, 0x100B4148 BF2_CONSOLE_PROPERTY_FN(maxTextureRepeat, int, activeGeometryTemplate() != 0, getMaxTextureRepeat(), setMaxTextureRepeat, kGeometryTemplateConsoleTag) +// PE 0x100B1B4D. [INFERRED] helper name; the report only includes the three mesh classes. +std::string __fastcall consoleGeometryTemplateInfo(bool header) +{ + std::string result; + if (header) + result += formatString("%-4s %-35s %5s %5s %5s %5s %5s mats polys\n", + "type", "name", "count", "tot", "texs", "verts", "inxs"); + + GeometryTemplateRegistry* const registry = templateManager()->getTemplateRegistry(); + for (GeometryTemplateRegistry::iterator it = registry->begin(); it != registry->end(); ++it) + { + IGeometryTemplate* const value = it->second; + std::string type("-"); + int count; + if (value->getClassId() == 0x870CA653u) + { + type = "Stat"; + count = static_cast(static_cast(value)->m_instances.size()); + } + else if (value->getClassId() == 0x870CA651u) + { + type = "Bund"; + count = static_cast(static_cast(value)->m_instances.size()); + } + else if (value->getClassId() == 0x870CA652u) + { + type = "Skin"; + count = static_cast(static_cast(value)->m_instances.size()); + } + else + continue; + + const char* const name = value->getName().c_str(); + const char* const label = type.c_str(); + // The four queries are ordered, and the shipped divisions interpret EAX as signed. + const int indices = static_cast(value->getMemoryUsage(2)) / 1024; + const int vertices = static_cast(value->getMemoryUsage(1)) / 1024; + const int textures = static_cast(value->getMemoryUsage(4)) / 1024; + const int total = static_cast(value->getMemoryUsage(-1)) / 1024; + result += formatString("%-4s %-35s %5d %5d %5d %5d %5d ", label, name, + count, total, textures, vertices, indices); + result += " "; + for (unsigned int lod = 0; lod != 4; ++lod) + { + const int materials = value->getMaterialCount(lod); + result += formatString(materials != 0 ? "%d " : "- ", materials); + } + result += " "; + for (unsigned int lod = 0; lod != 4; ++lod) + { + const int primitives = value->getLodPrimitiveCount(lod); + result += formatString(primitives != 0 ? "%5d " : " - ", primitives); + } + result += "\n"; + } + return result; +} + +// PE 0x100B41E8 / 0x100B42B5 / 0x100B4268 (Boolean argument parser). The original-case object name and optional header are shipped. +// The constructor reads the defaults' static name (dword_10247C20), which retail's initializer has set +// to "GeometryTemplate" at that point (0x101D084C..0x101D0A87); this file's order has switched the +// defaults to "geometryTemplate" by then, so the value is spelled out. +class GeometryTemplatePrintInfoBinding : public ConsoleObjectBaseImpl +{ +public: + // PE 0x100B41E8 + GeometryTemplatePrintInfoBinding() + { + m_objectName = "GeometryTemplate"; + m_access = consoleDefaultAccess(); + m_category = consoleDefaultCategory(); + m_functionName = "printInfo"; + m_type = 0; + m_minNoArgs = 0; + m_maxNoArgs = 1; + m_returnType = "std::string"; + m_hasReturnValue = false; + m_isDynamic = false; + m_argTypes[0] = "bool"; + m_argNeedsConversion[0] = -1; + consoleBindingList(kGeometryTemplateConsoleTag).push_back(this); + } + virtual bool isObjectActive() const { return true; } + // PE 0x100B42B5 + virtual void executeObjectMethod() + { + if (m_argCount != 0 && m_argCount != 1) + return; + const bool header = m_argCount == 0 ? true : BF2_CC_ARG(bool, 0); + m_hasReturnValue = true; + m_returnValue = consoleGeometryTemplateInfo(header); + } + // PE 0x100B4268 + virtual void setArgFromString(int index, const std::string& value) + { + BF2_CC_CONVERT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; + +GeometryTemplatePrintInfoBinding s_geometryTemplatePrintInfoBinding; + } // anonymous namespace bool registerGeometryTemplateConsoleObjects() @@ -808,7 +1221,6 @@ bool unregisterGeometryTemplateConsoleObjects() consoleBindingList(kGeometryTemplateConsoleTag)); } -#endif // BF2_PLUGIN_ABI_NATIVE } // namespace geom } // namespace hfe diff --git a/Code/BF2/Geom/GeometryTemplateManager.h b/Code/BF2/Geom/GeometryTemplateManager.h index 68faa6735..16ea03cb0 100644 --- a/Code/BF2/Geom/GeometryTemplateManager.h +++ b/Code/BF2/Geom/GeometryTemplateManager.h @@ -4,11 +4,13 @@ #ifndef BF2_GEOM_GEOMETRYTEMPLATEMANAGER_H #define BF2_GEOM_GEOMETRYTEMPLATEMANAGER_H +#include +#include #include "../../RendDX9Abi/HfeAbi.h" -#include "../../RendDX9Abi/Vc71String.h" +#include #include "../Core/IBase.h" -namespace vc71 { struct map_layout; } +#include namespace dice { namespace hfe { @@ -16,13 +18,33 @@ namespace geom { class IGeometryTemplate; +// Optimizer interface prefix, IID 80103 (0x138E7). The concrete mesh optimizers extend this prefix. +// PE tables 0x1021D208/0x1021D2E0: +0x10 returns the class ID; +0x14 returns AL=false. +class IGeometryOptimizer : public IBase +{ +public: + virtual unsigned int getClassId() const = 0; + virtual bool optimize() = 0; +}; + +// The registry's key order: `_stricmp` over the two names, the instruction-proven comparison. A +// name keeps the spelling it was first registered with. Defined in GeometryTemplateManager.cpp. +struct GeometryTemplateNameLess +{ + bool operator()(const std::string& a, const std::string& b) const; +}; + +// name -> owning template pointer, in name order. +typedef std::map + GeometryTemplateRegistry; + #define BF2_GTM_RESERVED(offset) virtual void reserved_##offset() = 0 class IGeometryTemplateManager : public IBase { public: - // Cross-image methods use HostString, then convert once to internal VC7.1 storage. - // Do not expose vc71::string directly to a native-host caller. + // Cross-image methods use HostString, then convert once to the internal string storage. + // Do not expose std::string directly to a native-host caller. virtual void registerTemplate(IGeometryTemplate* value, const ::renddx9abi::HostString& name) = 0; // +0x10 virtual IGeometryTemplate* createTemplate(unsigned int classId, @@ -33,18 +55,27 @@ class IGeometryTemplateManager : public IBase virtual void removeTemplate(const ::renddx9abi::HostString& name) = 0; // +0x24 virtual void clear() = 0; // +0x28 - BF2_GTM_RESERVED(2C); BF2_GTM_RESERVED(30); BF2_GTM_RESERVED(34); + // PE 0x1015D940 / 0x1015D430: an always-empty static vector and a static empty string. + // [CHOSEN, not recovered] element and argument type (unobservable-type exception, AGENTS.md). + virtual const std::vector& slot_0x2C() = 0; // +0x2C + virtual const ::renddx9abi::HostString& slot_0x30(std::uint32_t unused) = 0; // +0x30 + BF2_GTM_RESERVED(34); BF2_GTM_RESERVED(38); // PE 0x1015D9C0/0x1015D7C0/0x1015D740, called by ResourceManager's load lifecycle. // Names are [INFERRED]; signatures and the template-use byte at +4 are instruction-proven. virtual void loadUsedTemplates() = 0; // +0x3C virtual void resetTemplateUse() = 0; // +0x40 virtual int getUsedTemplateCount() = 0; // +0x44 - BF2_GTM_RESERVED(48); BF2_GTM_RESERVED(4C); - BF2_GTM_RESERVED(50); BF2_GTM_RESERVED(54); BF2_GTM_RESERVED(58); - BF2_GTM_RESERVED(5C); + BF2_GTM_RESERVED(48); + // Names are [INFERRED]. Returned optimizers are borrowed from the owning registry. + virtual IGeometryOptimizer* createOptimizer(unsigned int classId, const std::string& key) = 0; // +0x4C + virtual IGeometryOptimizer* registerOptimizer(const std::string& className, + const std::string& key) = 0; // +0x50 + virtual bool runOptimizers() = 0; // +0x54 + virtual void clearOptimizers() = 0; // +0x58 + virtual void visitTemplateClassIds() = 0; // +0x5C // Returns the case-insensitive name/template registry for ordered traversal. - virtual vc71::map_layout* getTemplateRegistry() = 0; // +0x60 + virtual GeometryTemplateRegistry* getTemplateRegistry() = 0; // +0x60 protected: ~IGeometryTemplateManager() {} @@ -54,6 +85,10 @@ class IGeometryTemplateManager : public IBase // g_RoadEditableRenderer). The concrete object is created by createGeometryTemplateManager. extern IBase* g_GeometryTemplateManager; +// The manager's +0x48 slot (PE 0x1015D530): re-arms the three mesh technique gates after the +// shader set changed. Typed entry for callers outside this module (VideoOptions' ECCore arm). +void geometryTemplateManagerRearmTechniques(IBase* manager); + } // namespace geom } // namespace hfe } // namespace dice diff --git a/Code/BF2/Geom/HeightmapEventNode.cpp b/Code/BF2/Geom/HeightmapEventNode.cpp index d98b1b1b2..2f971b1b7 100644 --- a/Code/BF2/Geom/HeightmapEventNode.cpp +++ b/Code/BF2/Geom/HeightmapEventNode.cpp @@ -2,6 +2,9 @@ // Contents: the whole translation unit, (ELF 0x84A8900..0x84A8A5F, PE // bf2_w32ded 0x756520 / 0x756550). Engine code: the dedicated server links it too. +// [CHOSEN, not recovered] The macOS static renderer uses the host's identical +// implementation and RTTI for this shared event type. Windows DLLs keep their own copy. +#if !(defined(__APPLE__) && defined(BF2_STATIC_PLUGINS) && defined(BF2_IMAGE_RENDDX9)) #include "HeightmapEventNode.h" #include // the TU's static initialiser (ELF 0x84A89B0) is the guard @@ -11,7 +14,7 @@ namespace hfe { namespace geom { // ELF 0x84A8930 (C1) / 0x84A8900 (C2), 47 B; PE 0x756520. EventNode's m_next = 0, the vptr, the -// type, then the four area floats zeroed. +// type, then the four area floats zeroed. RendDX9's own copy: PE 0x101C8460 (vtable 0x10223094). HeightmapEventNode::HeightmapEventNode(unsigned int type) : SimpleEventNode(type) { @@ -22,11 +25,14 @@ HeightmapEventNode::HeightmapEventNode(unsigned int type) } // ELF 0x84A8A40 (D1) / 0x84A8A50 (D0): nothing of its own - the vptr goes back to EventNode's. +// RendDX9's scalar deleting form, PE 0x101C84C0, is slot 0 of both the EventNode table +// (0x10223088) and this class's (0x10223094). HeightmapEventNode::~HeightmapEventNode() { } -// ELF 0x84A8960, 64 B; PE 0x756550. A straight four-float copy. +// ELF 0x84A8960, 64 B; PE 0x756550. A straight four-float copy. RendDX9's copy: PE 0x101C8490 +// (posted by the road tessellator, 0x1014067D). void HeightmapEventNode::setAffectedArea(const Vec4& area) { m_affectedArea = area; @@ -41,3 +47,4 @@ const Vec4& HeightmapEventNode::getAffectedArea() const } // namespace geom } // namespace hfe } // namespace dice +#endif diff --git a/Code/BF2/Geom/HemiMapManager/HemiMapManager.cpp b/Code/BF2/Geom/HemiMapManager/HemiMapManager.cpp index ec6d2f89d..f5f9313c8 100644 --- a/Code/BF2/Geom/HemiMapManager/HemiMapManager.cpp +++ b/Code/BF2/Geom/HemiMapManager/HemiMapManager.cpp @@ -15,23 +15,12 @@ #include "../../../RendDX9Abi/Frontier.h" #include "../../../RendDX9Abi/ModuleCommon.h" #include "../../../RendDX9Abi/PluginEntry.h" -#include "../../../RendDX9Abi/Vc71Vector.h" +#include "../../../RendDX9Abi/D3dx9Sdk.h" #include #include #include - -extern "C" HRESULT WINAPI D3DXLoadSurfaceFromSurface( - IDirect3DSurface9* destination, const PALETTEENTRY* destinationPalette, - const RECT* destinationRect, IDirect3DSurface9* source, - const PALETTEENTRY* sourcePalette, const RECT* sourceRect, - DWORD filter, D3DCOLOR colourKey); -extern "C" HRESULT WINAPI D3DXSaveSurfaceToFileA( - const char* destinationFile, unsigned int fileFormat, IDirect3DSurface9* source, - const PALETTEENTRY* sourcePalette, const RECT* sourceRect); - -#pragma comment(linker, "/alternatename:_D3DXLoadSurfaceFromSurface@32=_D3DXLoadSurfaceFromSurface") -#pragma comment(linker, "/alternatename:_D3DXSaveSurfaceToFileA@20=_D3DXSaveSurfaceToFileA") +#include namespace dice { namespace hfe { @@ -57,6 +46,7 @@ void releaseTexture(dx9rend::EngineTexture* texture) } } +// PE 0x1012B5A0: drops the map's own texture reference, evicts the cache's, destroys the name and frees the map. void destroyHemiMap(HemiMap* map) { if (!map) @@ -68,10 +58,12 @@ void destroyHemiMap(HemiMap* map) // cached, this removes and releases the cache's independent reference; otherwise the cache // walk simply reaches its sentinel. dx9rend::textureManagerEvictFromCache(texture); - map->name.~string(); + map->name.~basic_string(); ::renddx9abi::engineFree(map); } +// PE 0x1012B600: allocates and fills a map; a missing .dds is replaced by an 8x8 white texture +// that is saved under Editor_LevelSavePath. HemiMap* createHemiMap(const HemiMapName& name, const Vec3& position, float range, float falloff) { @@ -81,7 +73,7 @@ HemiMap* createHemiMap(const HemiMapName& name, const Vec3& position, map->position.x = 0.0f; map->position.y = 0.0f; map->position.z = 0.0f; - new (&map->name) vc71::string(); + new (&map->name) std::string(); } // Retail 0x1012B600 continues through these stores after a failed allocation. Preserve that @@ -91,7 +83,7 @@ HemiMap* createHemiMap(const HemiMapName& name, const Vec3& position, map->name = name.c_str(); map->falloff = falloff; - vc71::string probe(map->name); + std::string probe(map->name); probe += ".dds"; if (::renddx9abi::engineFileExists(probe)) { @@ -110,7 +102,7 @@ HemiMap* createHemiMap(const HemiMapName& name, const Vec3& position, *pixel++ = 0xFFFFFFFFu; dx9rend::textureUnlock(map->texture, lock); - vc71::string saveDirectory; + std::string saveDirectory; dx9rend::readStringSettingDefault("Editor_LevelSavePath", " ERROR ", saveDirectory); saveDirectory += "/"; saveDirectory += map->name; @@ -150,7 +142,7 @@ class HemiMapManager : public IHemiMapManager int m_refCount; // +0x04 HemiMap* m_baseHemiMap; // +0x08 - vc71::vector_layout m_hemiMaps; // +0x0C + std::vector m_hemiMaps; // +0x0C float m_hemiLerpBias; // +0x1C dx9rend::HemiRenderState m_savedState; // +0x20 HemiMapInfo m_info; // +0x4C @@ -159,27 +151,18 @@ class HemiMapManager : public IHemiMapManager #if defined(_M_IX86) struct HemiMapManagerLayoutAssertions { - static_assert(sizeof(HemiMapManager) == 0x5C, - "RefFactory_geom_HemiMapManager allocates exactly 0x5C bytes"); static_assert(offsetof(HemiMapManager, m_refCount) == 0x04, "Hemi manager ref offset drift"); static_assert(offsetof(HemiMapManager, m_baseHemiMap) == 0x08, "Hemi base offset drift"); static_assert(offsetof(HemiMapManager, m_hemiMaps) == 0x0C, "Hemi vector offset drift"); - static_assert(offsetof(HemiMapManager, m_hemiLerpBias) == 0x1C, "Hemi bias offset drift"); - static_assert(offsetof(HemiMapManager, m_savedState) == 0x20, "Hemi state offset drift"); - static_assert(offsetof(HemiMapManager, m_info) == 0x4C, "Hemi info offset drift"); }; #endif +// PE 0x1012BFB0 HemiMapManager::HemiMapManager() : m_refCount(1) , m_baseHemiMap(0) , m_hemiLerpBias(0.3f) { - // VC7.1's empty allocator member at +0x0C is intentionally not written by 0x1012BFB0. - m_hemiMaps.first = 0; - m_hemiMaps.last = 0; - m_hemiMaps.end = 0; - // The constructor writes only state dwords +0x38..+0x44; the other state bytes retain the // allocator's contents until rendererCaptureHemiState fills the fields it owns. *reinterpret_cast(m_savedState.bytes + 24) = 0u; @@ -193,9 +176,19 @@ HemiMapManager::HemiMapManager() m_info.lerpBias = 0.0f; } +// PE 0x1012BFF0 HemiMapManager::~HemiMapManager() { - clear(); + // The base-map slot stays unchanged throughout destruction. + if (m_baseHemiMap) + destroyHemiMap(m_baseHemiMap); + for (std::vector::iterator it = m_hemiMaps.begin(); + it != m_hemiMaps.end(); ++it) + destroyHemiMap(*it); + + typedef std::vector HemiMapVector; + m_hemiMaps.~HemiMapVector(); + new (&m_hemiMaps) HemiMapVector(); } void HemiMapManager::addRef() @@ -208,6 +201,7 @@ int HemiMapManager::getRef() return m_refCount; } +// PE 0x1012C1C0 int HemiMapManager::release() { const int remaining = --m_refCount; @@ -219,6 +213,7 @@ int HemiMapManager::release() return remaining; } +// PE 0x1012C150 void* HemiMapManager::queryInterface(unsigned int iid) const { if (iid == RD9_IID_IBASE || iid == IID_IHemiMapManager) @@ -226,6 +221,8 @@ void* HemiMapManager::queryInterface(unsigned int iid) const return 0; } +// Releases map objects and their vector storage. The vector end is read after each map dies. +// PE 0x1012C0B0 void HemiMapManager::clear() { if (m_baseHemiMap) @@ -234,18 +231,16 @@ void HemiMapManager::clear() m_baseHemiMap = 0; } - HemiMap** it = reinterpret_cast(m_hemiMaps.first); - HemiMap** const last = reinterpret_cast(m_hemiMaps.last); - while (it != last) + std::vector::iterator it = m_hemiMaps.begin(); + while (it != m_hemiMaps.end()) destroyHemiMap(*it++); - if (m_hemiMaps.first) - ::renddx9abi::engineFree(m_hemiMaps.first); - m_hemiMaps.first = 0; - m_hemiMaps.last = 0; - m_hemiMaps.end = 0; + typedef std::vector HemiMapVector; + m_hemiMaps.~HemiMapVector(); + new (&m_hemiMaps) HemiMapVector(); } +// PE 0x1012BF70: destroys the old base map, creates the replacement and stores it at +0x08. void HemiMapManager::setBaseHemiMap(const HemiMapName& name, const Vec3& position, float range, float falloff) { @@ -259,6 +254,7 @@ HemiMap* HemiMapManager::getBaseHemiMap() const return m_baseHemiMap; } +// PE 0x1012B2F0 const HemiMapInfo& HemiMapManager::getHemiMapInfo(const HemiMap* map) { if (map) @@ -287,6 +283,7 @@ HemiMap* HemiMapManager::slot28(unsigned int) return getBaseHemiMap(); } +// PE 0x1012C1A0 void HemiMapManager::setHemiLerpBias(float bias) { m_hemiLerpBias = bias; @@ -297,6 +294,9 @@ float HemiMapManager::getHemiLerpBias() const return m_hemiLerpBias; } +// PE 0x1012B800: renders the top-down source and lighting passes, composes them with the full-screen quad, +// writes lightingTex.dds and the DXT3 conversion to the output path. The conversion-texture failure is +// reported and then dereferenced, as shipped. bool HemiMapManager::makeHemiMap(unsigned long resolution, HemiMapName outputName, Vec3 position, float orthoExtent) { @@ -402,7 +402,7 @@ bool HemiMapManager::makeHemiMap(unsigned long resolution, HemiMapName outputNam IDirect3DSurface9* surface = dx9rend::textureGetLevelSurface(sourceTexture, 0u, 0x7FFFFFFFu); - D3DXSaveSurfaceToFileA("lightingTex.dds", 4u, surface, 0, 0); + D3DXSaveSurfaceToFileA("lightingTex.dds", D3DXIFF_DDS, surface, 0, 0); surface->Release(); releaseTexture(sourceTexture); newDepthStencil->Release(); @@ -434,10 +434,10 @@ bool HemiMapManager::makeHemiMap(unsigned long resolution, HemiMapName outputNam lightingSurface->Release(); dx9rend::textureManagerSwapManaged(conversionManaged); - vc71::string outputPath(outputName.c_str()); + std::string outputPath(outputName.c_str()); ::renddx9abi::engineFilePrepareWrite(outputPath); surface = dx9rend::textureGetLevelSurface(conversionTexture, 0u, 0x7FFFFFFFu); - D3DXSaveSurfaceToFileA(outputPath.c_str(), 4u, surface, 0, 0); + D3DXSaveSurfaceToFileA(outputPath.c_str(), D3DXIFF_DDS, surface, 0, 0); surface->Release(); releaseTexture(lightingTexture); releaseTexture(conversionTexture); diff --git a/Code/BF2/Geom/HemiMapManager/HemiMapManager.h b/Code/BF2/Geom/HemiMapManager/HemiMapManager.h index 5cf133e78..c55b37222 100644 --- a/Code/BF2/Geom/HemiMapManager/HemiMapManager.h +++ b/Code/BF2/Geom/HemiMapManager/HemiMapManager.h @@ -26,19 +26,18 @@ namespace geom { #if defined(BF2_IMAGE_RENDDX9) // PE 0x1012B600 allocates 0x34 bytes. This is an ordinary owned data object, not an interface; // publish the recovered layout so its clients can use the real field instead of growing an -// accessor seam or a positional dispatch facade around it. The internal name remains the retail -// VC7.1 string even when the host/plugin boundary selects native STL carriers. +// accessor seam or a positional dispatch facade around it. The internal name is the renderer's +// std::string. struct HemiMap { Vec3 position; // +0x00 float range; // +0x0C float falloff; // +0x10 dx9rend::EngineTexture* texture; // +0x14 - vc71::string name; // +0x18 + std::string name; // +0x18 }; #if defined(_M_IX86) -static_assert(sizeof(HemiMap) == 0x34, "HemiMap allocation is 0x34 bytes"); static_assert(offsetof(HemiMap, texture) == 0x14, "HemiMap texture offset drift"); static_assert(offsetof(HemiMap, name) == 0x18, "HemiMap name offset drift"); #endif diff --git a/Code/BF2/Geom/HemiMapManager/HemiMapManagerConsole.cpp b/Code/BF2/Geom/HemiMapManager/HemiMapManagerConsole.cpp index b1213054c..603d71eb0 100644 --- a/Code/BF2/Geom/HemiMapManager/HemiMapManagerConsole.cpp +++ b/Code/BF2/Geom/HemiMapManager/HemiMapManagerConsole.cpp @@ -9,7 +9,6 @@ #include "../../Core/ConsoleObjects.h" #include "../../../RendDX9Abi/PluginEntry.h" -#if BF2_PLUGIN_ABI_NATIVE namespace dice { namespace hfe { @@ -24,6 +23,7 @@ BF2_CONSOLE_OBJECT("HemiMapManager", 2, 0) class HemiMapManagerSetBaseBinding : public ConsoleObjectBaseImpl { public: + // Binding constructor: PE 0x100C42FD. HemiMapManagerSetBaseBinding() { m_objectName = consoleDefaultName(); @@ -51,6 +51,8 @@ class HemiMapManagerSetBaseBinding : public ConsoleObjectBaseImpl return g_HemiMapManager != 0; } + // PE 0x100C43E0: three arguments default the falloff to 500; the name is copy-constructed before the call + // (the c_str() conversion below is the host-string boundary of the native port). void executeObjectMethod() override { if (m_argCount != 3 && m_argCount != 4) @@ -64,6 +66,7 @@ class HemiMapManagerSetBaseBinding : public ConsoleObjectBaseImpl g_HemiMapManager->setBaseHemiMap(name, position, range, falloff); } + // PE 0x100C4491 void setArgFromString(int index, const std::string& value) override { BF2_CC_CONVERT(std::string, 1) @@ -83,6 +86,7 @@ HemiMapManagerSetBaseBinding s_hemiMapManagerSetBaseBinding; class HemiMapManagerMakeHemiMapBinding : public ConsoleObjectBaseImpl { public: + // Binding constructor: PE 0x100C45D6. HemiMapManagerMakeHemiMapBinding() { m_objectName = consoleDefaultName(); @@ -110,6 +114,7 @@ class HemiMapManagerMakeHemiMapBinding : public ConsoleObjectBaseImpl return g_HemiMapManager != 0; } + // PE 0x100C46AF void executeObjectMethod() override { if (m_argCount != 4) @@ -123,6 +128,7 @@ class HemiMapManagerMakeHemiMapBinding : public ConsoleObjectBaseImpl m_returnValue = g_HemiMapManager->makeHemiMap(resolution, name, position, orthoExtent); } + // PE 0x100C4735 void setArgFromString(int index, const std::string& value) override { BF2_CC_CONVERT(unsigned long, 1) @@ -140,6 +146,11 @@ class HemiMapManagerMakeHemiMapBinding : public ConsoleObjectBaseImpl HemiMapManagerMakeHemiMapBinding s_hemiMapManagerMakeHemiMapBinding; +// Initializer 0x101D1EC4 follows makeHemiMap. +// PE 0x100C487A, 0x100C48EB, 0x100C4938: constructor, argument conversion, executor. +BF2_CONSOLE_PROPERTY(hemiLerpBias, float, g_HemiMapManager, + setHemiLerpBias, getHemiLerpBias, kHemiMapManagerConsoleTag) + } // anonymous namespace bool registerHemiMapManagerConsoleObjects() @@ -158,5 +169,4 @@ bool unregisterHemiMapManagerConsoleObjects() } // namespace hfe } // namespace dice -#endif // BF2_PLUGIN_ABI_NATIVE #endif // BF2_IMAGE_RENDDX9 diff --git a/Code/BF2/Geom/IGeometryTemplate.h b/Code/BF2/Geom/IGeometryTemplate.h index 05f2c72c8..36f632ea0 100644 --- a/Code/BF2/Geom/IGeometryTemplate.h +++ b/Code/BF2/Geom/IGeometryTemplate.h @@ -5,7 +5,7 @@ #include "../Core/IBase.h" #include "../Math/Vec3.h" -namespace vc71 { class string; } +#include namespace dice { namespace hfe { namespace geom { @@ -16,10 +16,10 @@ class IGeometryTemplate : public ::dice::hfe::IBase { public: virtual unsigned int getClassId() const = 0; // +0x10 - virtual void setName(const vc71::string& name) = 0; // +0x14 - virtual const vc71::string& getName() const = 0; // +0x18 - virtual void setPath(const vc71::string& path) = 0; // +0x1C - virtual const vc71::string& getPath() const = 0; // +0x20 + virtual void setName(const std::string& name) = 0; // +0x14 + virtual const std::string& getName() const = 0; // +0x18 + virtual void setPath(const std::string& path) = 0; // +0x1C + virtual const std::string& getPath() const = 0; // +0x20 virtual void* createInstance() = 0; // +0x24 base: 0 virtual bool isLoaded() const = 0; // +0x28 virtual bool load() = 0; // +0x2C base: 0 diff --git a/Code/BF2/Geom/IRoadEditable.h b/Code/BF2/Geom/IRoadEditable.h index c419677f3..f8000bc60 100644 --- a/Code/BF2/Geom/IRoadEditable.h +++ b/Code/BF2/Geom/IRoadEditable.h @@ -15,9 +15,7 @@ #include #endif -#if !defined(BF2_IMAGE_RENDDX9) || BF2_PLUGIN_ABI_NATIVE #include -#endif namespace dice { namespace hfe { @@ -42,39 +40,7 @@ typedef std::string RoadEditableString; // [CHOSEN, not recovered] Compatibility renderer builds use the VC7.1 12-byte header and 44-byte // nodes. The caller supplies the copy; the callee destroys it. Native images use std::set. -#if !defined(BF2_IMAGE_RENDDX9) || BF2_PLUGIN_ABI_NATIVE typedef std::set RoadTemplateNameSet; -#else -struct RoadTemplateNameSetNode -{ - RoadTemplateNameSetNode* left; // +0x00 - RoadTemplateNameSetNode* parent; // +0x04 - RoadTemplateNameSetNode* right; // +0x08 - unsigned char value[28]; // +0x0C a VC7.1 std::string - unsigned char color; // +0x28 - unsigned char isNil; // +0x29 - unsigned char pad[2]; -}; - -class RoadTemplateNameSet -{ -public: - ~RoadTemplateNameSet(); - - void* comparator; // +0x00 never written - RoadTemplateNameSetNode* head; // +0x04 - unsigned int size; // +0x08 - -private: - RoadTemplateNameSet(const RoadTemplateNameSet&); - RoadTemplateNameSet& operator=(const RoadTemplateNameSet&); -}; - -#if defined(_M_IX86) -static_assert(sizeof(RoadTemplateNameSetNode) == 0x2C, "the VC7.1 set node is 44 bytes"); -static_assert(sizeof(RoadTemplateNameSet) == 12, "the VC7.1 set header is 12 bytes"); -#endif -#endif // IRoad (IID 820010) - the three slots after the IBase quartet both road classes share. diff --git a/Code/BF2/Geom/IScaleable.h b/Code/BF2/Geom/IScaleable.h new file mode 100644 index 000000000..2b91ba607 --- /dev/null +++ b/Code/BF2/Geom/IScaleable.h @@ -0,0 +1,15 @@ +// [CHOSEN, not recovered] Shared native declaration of the existing six-slot +// scale interface used by world objects and MeshParticleMesh's secondary table. +#ifndef BF2_GEOM_ISCALEABLE_H +#define BF2_GEOM_ISCALEABLE_H +#include "../Core/IBase.h" +#include "../Math/Vec3.h" +namespace dice { namespace hfe { namespace geom { +class IScaleable : public IBase +{ +public: + virtual void setScale(const Vec3&) = 0; + virtual const Vec3& getScale() const = 0; +}; +} } } +#endif diff --git a/Code/BF2/Geom/ITerrainEditable.h b/Code/BF2/Geom/ITerrainEditable.h index 94479e6f3..202d9aae0 100644 --- a/Code/BF2/Geom/ITerrainEditable.h +++ b/Code/BF2/Geom/ITerrainEditable.h @@ -2,8 +2,7 @@ // [CHOSEN, not recovered] shared header usable by renderer and editor images. // Method names and getter constness are [INFERRED]; const getters must remain distinct from // Terrain's primary-interface getters. Preserve the 90-slot 1.50 virtual order. -// [CHOSEN, not recovered] native base-name getters return HostString by value because the -// Terrain base retains VC7.1 strings. Compatibility builds return references to that storage. +// [CHOSEN, not recovered] base-name getters return HostString by value. #ifndef BF2_GEOM_ITERRAINEDITABLE_H #define BF2_GEOM_ITERRAINEDITABLE_H @@ -31,11 +30,7 @@ typedef std::string TerrainEditableString; #endif // The base-name getters' result (see the above). -#if defined(BF2_IMAGE_RENDDX9) && !BF2_PLUGIN_ABI_NATIVE -typedef const TerrainEditableString& TerrainEditableNameResult; // retail: const std::string& -#else typedef TerrainEditableString TerrainEditableNameResult; // [CHOSEN] native: by value -#endif // IID_ITerrainEditable (Core/Ids.h) - dword_1021AE1C, the id TerrainEditable::queryInterface answers // with this + 0x768. @@ -62,34 +57,34 @@ class ITerrainEditable : public IBase virtual void setLodSwitchDistance(float distance) = 0; // +0x24 0x1010DC70 binding `lodSwitchDistance` virtual float getLodSwitchDistance() const = 0; // +0x28 virtual void setLowDetailTexture(const TerrainEditableString& path) = 0; // +0x2C 0x101097B0 [INFERRED] name - virtual void setPrimaryWorldScale(const Vec3& scale) = 0; // +0x30 0x101A6600 binding `primaryWorldScale` + virtual void setPrimaryWorldScale(const Vec3& scale) = 0; // +0x30 (TerrainEditableGetSets.cpp) binding `primaryWorldScale` virtual const Vec3& getPrimaryWorldScale() const = 0; // +0x34 - virtual void setSecondaryWorldScale(const Vec3& scale) = 0; // +0x38 0x101A6630 binding `secondaryWorldScale` + virtual void setSecondaryWorldScale(const Vec3& scale) = 0; // +0x38 (TerrainEditableGetSets.cpp) binding `secondaryWorldScale` virtual const Vec3& getSecondaryWorldScale() const = 0; // +0x3C - virtual void setUnresolved2C(float value) = 0; // +0x40 0x101A5FE0 [UNRESOLVED] Terrain +0x2C, no binding + virtual void setUnresolved2C(float value) = 0; // +0x40 (TerrainEditableGetSets.cpp) [UNRESOLVED] Terrain +0x2C, no binding virtual float getUnresolved2C() const = 0; // +0x44 - virtual void setPatchSize(int size) = 0; // +0x48 0x101A6000 binding `patchSize` + virtual void setPatchSize(int size) = 0; // +0x48 (TerrainEditableGetSets.cpp) binding `patchSize` virtual int getPatchSize() const = 0; // +0x4C - virtual void setSubdividePatches(bool subdivide) = 0; // +0x50 0x101A6020 binding `subdividePatches` + virtual void setSubdividePatches(bool subdivide) = 0; // +0x50 (TerrainEditableGetSets.cpp) binding `subdividePatches` virtual bool getSubdividePatches() const = 0; // +0x54 - virtual void setPatchColormapSize(int size) = 0; // +0x58 0x101A6040 binding `patchColormapSize` + virtual void setPatchColormapSize(int size) = 0; // +0x58 (TerrainEditableGetSets.cpp) binding `patchColormapSize` virtual int getPatchColormapSize() const = 0; // +0x5C virtual void setLowDetailmapSize(int size) = 0; // +0x60 0x1010DC90 binding `lowDetailmapSize` virtual int getLowDetailmapSize() const = 0; // +0x64 - virtual void setColormapBaseName(const TerrainEditableString& name) = 0; // +0x68 0x101A6060 binding `colormapBaseName` + virtual void setColormapBaseName(const TerrainEditableString& name) = 0; // +0x68 (TerrainEditableGetSets.cpp) binding `colormapBaseName` virtual TerrainEditableNameResult getColormapBaseName() const = 0; // +0x6C - virtual void setLightmapBaseName(const TerrainEditableString& name) = 0; // +0x70 0x101A60D0 binding `lightmapBaseName` + virtual void setLightmapBaseName(const TerrainEditableString& name) = 0; // +0x70 (TerrainEditableGetSets.cpp) binding `lightmapBaseName` virtual TerrainEditableNameResult getLightmapBaseName() const = 0; // +0x74 - virtual void setDetailmapBaseName(const TerrainEditableString& name) = 0; // +0x78 0x101A61D0 binding `detailmapBaseName` + virtual void setDetailmapBaseName(const TerrainEditableString& name) = 0; // +0x78 (TerrainEditableGetSets.cpp) binding `detailmapBaseName` virtual TerrainEditableNameResult getDetailmapBaseName() const = 0; // +0x7C - virtual void setLowDetailmapBaseName(const TerrainEditableString& name) = 0; // +0x80 0x101A6240 binding `lowDetailmapBaseName` + virtual void setLowDetailmapBaseName(const TerrainEditableString& name) = 0; // +0x80 (TerrainEditableGetSets.cpp) binding `lowDetailmapBaseName` virtual TerrainEditableNameResult getLowDetailmapBaseName() const = 0; // +0x84 virtual void setShaderTechnique(int technique) = 0; // +0x88 0x101A6560 binding `shaderTechnique` virtual int getShaderTechnique() const = 0; // +0x8C - virtual TerrainEditableString getLevelSavePath() const = 0; // +0x90 0x101A6660 "Editor_LevelSavePath" + "/" - virtual void setDetailTextureName(int layer, const TerrainEditableString& name) = 0; // +0x94 0x101A6700 [INFERRED] - virtual unsigned char getDetailMaterial(int layer) const = 0; // +0x98 0x101A6780 [INFERRED] record byte +0x14 - virtual void setDetailMaterial(int layer, unsigned char material) = 0; // +0x9C 0x101A67A0 [INFERRED] + virtual TerrainEditableString getLevelSavePath() const = 0; // +0x90 (TerrainEditableGetSets.cpp) "Editor_LevelSavePath" + "/" + virtual void setDetailTextureName(int layer, const TerrainEditableString& name) = 0; // +0x94 (TerrainEditableGetSets.cpp) [INFERRED] + virtual unsigned char getDetailMaterial(int layer) const = 0; // +0x98 (TerrainEditableGetSets.cpp) [INFERRED] record byte +0x14 + virtual void setDetailMaterial(int layer, unsigned char material) = 0; // +0x9C (TerrainEditableGetSets.cpp) [INFERRED] virtual TerrainDetailTextureBase* getDetailTexture(unsigned int layer) = 0; // +0xA0 0x1010ACB0 accepts layer <= 6 (shipped) // Brush strength is an integer: positive paints, negative erases. diff --git a/Code/BF2/Geom/LcgRandom.h b/Code/BF2/Geom/LcgRandom.h new file mode 100644 index 000000000..fe8043386 --- /dev/null +++ b/Code/BF2/Geom/LcgRandom.h @@ -0,0 +1,41 @@ +// Path: [INFERRED] shared Geom header for RendDX9.dll's copy of the engine random step. +// Contents: lcgrand_step, one body for every RendDX9 caller (NametagManager.cpp, +// UndergrowthSystemLoad.cpp, GeomMisc/PerlinNoise.cpp). Core/Random.cpp, which holds the +// engine's own dice::hfe::Random::getRaw, is not in the RendDX9 manifest. + +#ifndef GEOM_LCGRANDOM_H +#define GEOM_LCGRANDOM_H + +namespace dice { +namespace hfe { +namespace geom { + +// One Schrage half of the Law-Kelton lcgrand: value * multiplier mod (2^31 - 1), computed in 16-bit +// halves with the image's arithmetic shifts (`sar`) and wrapping adds. Part of lcgrandStep below, +// not a retail function of its own. +inline unsigned int lcgrandHalf(unsigned int value, unsigned int multiplier) +{ + const unsigned int low = (value & 0xFFFFu) * multiplier; + const unsigned int high = static_cast(static_cast(value) >> 16) * multiplier; + const int middle = static_cast((low >> 16) + high); + const unsigned int next = (low & 0xFFFFu) + + ((static_cast(middle) & 0x7FFFu) << 16) + + static_cast(middle >> 15); + const int reduced = static_cast(next - 0x7FFFFFFFu); + return reduced < 0 ? next : static_cast(reduced); +} + +// PE 0x1009EF30 (lcgrand_step). RendDX9's copy of dice::hfe::Random::getRaw (ELF 0x8166CE0): +// __thiscall on the state word, two Schrage steps (24112 = 0x5E30, then 26143 = 0x661F), the new +// state stored back and returned in eax. +inline unsigned int lcgrandStep(unsigned int* state) +{ + *state = lcgrandHalf(lcgrandHalf(*state, 24112u), 26143u); + return *state; +} + +} // namespace geom +} // namespace hfe +} // namespace dice + +#endif // GEOM_LCGRANDOM_H diff --git a/Code/BF2/Geom/LightGeometry.cpp b/Code/BF2/Geom/LightGeometry.cpp new file mode 100644 index 000000000..4a6831d49 --- /dev/null +++ b/Code/BF2/Geom/LightGeometry.cpp @@ -0,0 +1,132 @@ +// Owns the named texture selected through ILightGeometry. +// [INFERRED] source placement from the reflection class and its factory; no __FILE__ witness. + +#ifdef BF2_IMAGE_RENDDX9 + +#include "../Core/IBase.h" +#include "../RendDX9/RendDX9Base.h" +#include "../RendDX9/Texture.h" +#include "../../RendDX9Abi/BfMemory.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace geom { + +// Reflection class id at 0x1021AF24. +extern const unsigned int CID_LightGeometry = 0x3103A73Cu; + +namespace { + +const unsigned int kIID_ILightGeometry = 0x0F3EFCFBu; + +void releaseLightTexture(dx9rend::EngineTexture* texture) +{ + if (texture && --texture->refCount == 0) + { + dx9rend::textureDtor(texture); + ::renddx9abi::engineFree(texture); + } +} + +// The five entries at 0x1021D1C8 are IBase followed by the texture-name setter. +class LightGeometry : public IBase +{ +public: + LightGeometry(); + ~LightGeometry(); + + void addRef() override; + int getRef() override; + int release() override; + void* queryInterface(unsigned int iid) const override; + + // [INFERRED] name for the sole added virtual; an empty or unchanged name keeps the texture. + virtual void setTextureName(const std::string& name); + +private: + int m_refCount; // retail +0x04 + dx9rend::EngineTexture* m_texture; // retail +0x08, owning reference + std::string m_textureName; // retail +0x0C +}; + +// PE 0x10132970 +LightGeometry::LightGeometry() + : m_refCount(1), m_texture(0) +{ +} + +// PE 0x101328C0 +LightGeometry::~LightGeometry() +{ + releaseLightTexture(m_texture); +} + +// PE 0x1000CB20, shared IBase increment body. +void LightGeometry::addRef() +{ + ++m_refCount; +} + +// PE 0x101A9A10, shared count getter. +int LightGeometry::getRef() +{ + return m_refCount; +} + +// PE 0x101329D0 +int LightGeometry::release() +{ + const int remaining = --m_refCount; + if (!remaining) + { + this->~LightGeometry(); + ::renddx9abi::engineFree(this); + } + return remaining; +} + +// PE 0x101329A0 +void* LightGeometry::queryInterface(unsigned int iid) const +{ + if (iid == 1u || iid == kIID_ILightGeometry) + return const_cast(this); + return 0; +} + +// PE 0x10132900 +void LightGeometry::setTextureName(const std::string& name) +{ + if (name.empty() || name == m_textureName) + return; + + m_textureName = name; + releaseLightTexture(m_texture); + // The old texture slot stays published until the new lookup returns. + m_texture = static_cast( + dx9rend::textureManagerGetTexture(m_textureName)); +} + +} // anonymous namespace + +// PE 0x100B0895 +IBase* __fastcall createLightGeometry(unsigned int iid, IBase* outer) +{ + if (outer) + return 0; + + void* const storage = ::renddx9abi::engineAlloc(sizeof(LightGeometry)); + LightGeometry* const self = storage ? new (storage) LightGeometry() : 0; + IBase* const result = static_cast(self->queryInterface(iid)); + if (!result) + self->release(); + return result; +} + +} // namespace geom +} // namespace hfe +} // namespace dice + +#endif // BF2_IMAGE_RENDDX9 diff --git a/Code/BF2/Geom/LightManagerConsole.cpp b/Code/BF2/Geom/LightManagerConsole.cpp index c7c775a5f..3f7d14e1a 100644 --- a/Code/BF2/Geom/LightManagerConsole.cpp +++ b/Code/BF2/Geom/LightManagerConsole.cpp @@ -10,7 +10,6 @@ #include "../../RendDX9Abi/PluginAbi.h" -#if BF2_PLUGIN_ABI_NATIVE #include "../Core/ConsoleObjectMacro.h" #include "../Core/ConsoleObjects.h" @@ -45,36 +44,103 @@ BF2_CONSOLE_OBJECT("lightManager", 2, 0) BF2_CONSOLE_METHOD_0_STATIC_ACTIVE(init, consoleInitializeLightManager, lightManager() != 0, kLightManagerConsoleTag) +// PE 0x100BC8DC, 0x100BC961, 0x100BC9D4: constructor, argument conversion, executor. BF2_CONSOLE_PROPERTY(skyColor, Vec3, lightManager(), setSkyColor, getSkyColor, kLightManagerConsoleTag) +// PE 0x100BCA44, 0x100BCAC9, 0x100BCB3C: constructor, argument conversion, executor. BF2_CONSOLE_PROPERTY(ambientColor, Vec3, lightManager(), setAmbientColor, getAmbientColor, kLightManagerConsoleTag) +// PE 0x100BCBAC, 0x100BCC31, 0x100BCCA4: constructor, argument conversion, executor. BF2_CONSOLE_PROPERTY(treeAmbientColor, Vec3, lightManager(), setTreeAmbientColor, getTreeAmbientColor, kLightManagerConsoleTag) +// PE 0x100BCD14, 0x100BCD9E, 0x100BCE11: constructor, argument conversion, executor. BF2_CONSOLE_PROPERTY(treeSunColor, Vec3, lightManager(), setTreeSunColor, getTreeSunColor, kLightManagerConsoleTag) +// PE 0x100BCE87, 0x100BCF0C, 0x100BCF7F: constructor, argument conversion, executor. BF2_CONSOLE_PROPERTY(treeSkyColor, Vec3, lightManager(), setTreeSkyColor, getTreeSkyColor, kLightManagerConsoleTag) +// PE 0x100BCFF5, 0x100BD07A, 0x100BD0ED: constructor, argument conversion, executor. BF2_CONSOLE_PROPERTY(staticSunColor, Vec3, lightManager(), setStaticSunColor, getStaticSunColor, kLightManagerConsoleTag) +// PE 0x100BD163, 0x100BD1E8, 0x100BD25B: constructor, argument conversion, executor. BF2_CONSOLE_PROPERTY(staticSkyColor, Vec3, lightManager(), setStaticSkyColor, getStaticSkyColor, kLightManagerConsoleTag) +// PE 0x100BD2D1, 0x100BD359, 0x100BD3CC: constructor, argument conversion, executor. BF2_CONSOLE_PROPERTY(staticSpecularColor, Vec3, lightManager(), setStaticSpecularColor, getStaticSpecularColor, kLightManagerConsoleTag) +// PE 0x100BD442, 0x100BD4C7, 0x100BD53A: constructor, argument conversion, executor. BF2_CONSOLE_PROPERTY(singlePointColor, Vec3, lightManager(), setSinglePointColor, getSinglePointColor, kLightManagerConsoleTag) +// PE 0x100BD5B0, 0x100BD68D, 0x100BD700: constructor, argument conversion, executor. BF2_CONSOLE_PROPERTY(dynamicPointColor, Vec3, lightManager(), setDynamicPointColor, getDynamicPointColor, kLightManagerConsoleTag) +// PE 0x100BD776, 0x100BD7FB, 0x100BD86E: constructor, argument conversion, executor. BF2_CONSOLE_PROPERTY(effectSunColor, Vec3, lightManager(), setEffectSunColor, getEffectSunColor, kLightManagerConsoleTag) +// PE 0x100BD8E4, 0x100BD969, 0x100BD9DC: constructor, argument conversion, executor. BF2_CONSOLE_PROPERTY(effectShadowColor, Vec3, lightManager(), setEffectShadowColor, getEffectShadowColor, kLightManagerConsoleTag) +// PE 0x100BDA52, 0x100BDAC3: constructor, argument conversion. BF2_CONSOLE_PROPERTY(defaultEffectLightAffectionFactor, float, lightManager(), setDefaultEffectLightAffectionFactor, getDefaultEffectLightAffectionFactor, kLightManagerConsoleTag) +// PE 0x100BDC57, +0x1FC/+0x200. +// PE 0x100BDB5F, 0x100BDBE4: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(singlePointColorHigh, Vec3, lightManager(), + setSinglePointColorHigh, getSinglePointColorHigh, kLightManagerConsoleTag) +// PE 0x100BDDC5, +0x204/+0x208. +// PE 0x100BDCCD, 0x100BDD52: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(singlePointColorLow, Vec3, lightManager(), + setSinglePointColorLow, getSinglePointColorLow, kLightManagerConsoleTag) +// PE 0x100BDF33, +0x20C/+0x210. +// PE 0x100BDE3B, 0x100BDEC0: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(dynamicPointColorHigh, Vec3, lightManager(), + setDynamicPointColorHigh, getDynamicPointColorHigh, kLightManagerConsoleTag) +// PE 0x100BE0A1, +0x214/+0x218. +// PE 0x100BDFA9, 0x100BE02E: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(dynamicPointColorLow, Vec3, lightManager(), + setDynamicPointColorLow, getDynamicPointColorLow, kLightManagerConsoleTag) +// PE 0x100BE20F, +0x21C/+0x220. +// PE 0x100BE117, 0x100BE19C: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(skyColorHigh, Vec3, lightManager(), + setSkyColorHigh, getSkyColorHigh, kLightManagerConsoleTag) +// PE 0x100BE37D, +0x224/+0x228. +// PE 0x100BE285, 0x100BE30A: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(skyColorLow, Vec3, lightManager(), + setSkyColorLow, getSkyColorLow, kLightManagerConsoleTag) +// PE 0x100BE4EB, +0x22C/+0x230. +// PE 0x100BE3F3, 0x100BE478: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(staticSkyColorHigh, Vec3, lightManager(), + setStaticSkyColorHigh, getStaticSkyColorHigh, kLightManagerConsoleTag) +// PE 0x100BE659, +0x234/+0x238. +// PE 0x100BE561, 0x100BE5E6: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(staticSkyColorLow, Vec3, lightManager(), + setStaticSkyColorLow, getStaticSkyColorLow, kLightManagerConsoleTag) +// PE 0x100BE7C7, +0x244/+0x248. Retail publishes low before high for the sun pairs. +// PE 0x100BE6CF, 0x100BE754: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(sunColorLow, Vec3, lightManager(), + setSunColorLow, getSunColorLow, kLightManagerConsoleTag) +// PE 0x100BE935, +0x23C/+0x240. +// PE 0x100BE83D, 0x100BE8C2: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(sunColorHigh, Vec3, lightManager(), + setSunColorHigh, getSunColorHigh, kLightManagerConsoleTag) + +// PE 0x100BEAA3, +0x254/+0x258. +// PE 0x100BE9AB, 0x100BEA30: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(sunSpecColorLow, Vec3, lightManager(), + setSunSpecColorLow, getSunSpecColorLow, kLightManagerConsoleTag) +// PE 0x100BEC11, +0x24C/+0x250. +// PE 0x100BEB19, 0x100BEB9E: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(sunSpecColorHigh, Vec3, lightManager(), + setSunSpecColorHigh, getSunSpecColorHigh, kLightManagerConsoleTag) +// PE 0x100BED51 calls the double accessors directly, without virtual dispatch. +// PE 0x100BEC87, 0x100BED04: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(staticLightBlendingTime, double, lightManager(), + setStaticLightBlendingTime, getStaticLightBlendingTime, + kLightManagerConsoleTag) + // Ground-hemi string property, available while the light manager exists. -// High/low color and static-blending bindings remain unavailable pending typed wrappers. void setGroundHemiName(const std::string& name) { lightManager()->setGroundHemi(name); @@ -82,61 +148,263 @@ void setGroundHemiName(const std::string& name) std::string getGroundHemiName() { - const vc71::string& name = lightManager()->getGroundHemi(); + const std::string& name = lightManager()->getGroundHemi(); return std::string(name.c_str(), name.size()); } +// PE 0x100BED9B, 0x100BEE82, 0x100BEE18: constructor, argument conversion, executor. BF2_CONSOLE_PROPERTY_FN(groundHemi, std::string, lightManager() != 0, getGroundHemiName(), setGroundHemiName, kLightManagerConsoleTag) // Binding 29 is the connected stock path: PE 0x1015BD70/0x1015BD80 forward it to the published // HemiMapManager without a null guard. +// PE 0x100BEEF7, 0x100BEF68: constructor, argument conversion. BF2_CONSOLE_PROPERTY(hemiLerpBias, float, lightManager(), setHemiLerpBias, getHemiLerpBias, kLightManagerConsoleTag) // Binding 30 follows hemiLerpBias in the shipped static-construction order. +// PE 0x100BEFFE, 0x100BF06F: constructor, argument conversion. BF2_CONSOLE_PROPERTY(lightCullDistance, float, lightManager(), setLightCullDistance, getLightCullDistance, kLightManagerConsoleTag) -// Bindings 31..34 (per-geometry maximum lights) remain unpublished. Binding 35 follows them: +// PE 0x100BF1C3, +0x5C/+0x60. +// PE 0x100BF105, 0x100BF176: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(maxLightsPerBundledMesh, int, lightManager(), + setMaxLightsPerBundledMesh, getMaxLightsPerBundledMesh, kLightManagerConsoleTag) +// PE 0x100BF2C7, +0x64/+0x68. +// PE 0x100BF209, 0x100BF27A: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(maxLightsPerStaticMesh, int, lightManager(), + setMaxLightsPerStaticMesh, getMaxLightsPerStaticMesh, kLightManagerConsoleTag) +// PE 0x100BF3CB, +0x6C/+0x70. +// PE 0x100BF30D, 0x100BF37E: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(maxLightsPerSkinnedMesh, int, lightManager(), + setMaxLightsPerSkinnedMesh, getMaxLightsPerSkinnedMesh, kLightManagerConsoleTag) +// PE 0x100BF4CF, +0x74/+0x78. +// PE 0x100BF411, 0x100BF482: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(maxLightsPerTerrainPatch, int, lightManager(), + setMaxLightsPerTerrainPatch, getMaxLightsPerTerrainPatch, kLightManagerConsoleTag) + // PE constructor 0x100BF515, executor 0x100BF5D3, .CRT entry 0x102366E4. Reads call +0x80; -// writes pass the parsed float to +0x7C. The next ambient-alpha range binding remains absent. +// writes pass the parsed float to +0x7C. +// PE 0x100BF586: argument conversion. BF2_CONSOLE_PROPERTY(skinnedMeshShaderLodDistance, float, lightManager(), setSkinnedMeshShaderLodDistance, getSkinnedMeshShaderLodDistance, kLightManagerConsoleTag) +// PE 0x100BF762; this pair has the getter first, +0x84, then the setter, +0x88. +// PE 0x100BF61F, 0x100BF6F7: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(lightMapAmbientAlphaCutoffRange, Vec2, lightManager(), + setLightMapAmbientAlphaCutoffRange, getLightMapAmbientAlphaCutoffRange, + kLightManagerConsoleTag) + +// PE 0x100BF7CB, 0x100BF850, 0x100BF8C3: constructor, argument conversion, executor. BF2_CONSOLE_PROPERTY(sunDirection, Vec3, lightManager(), setSunDirection, getSunDirection, kLightManagerConsoleTag) +// PE 0x100BF947, 0x100BF9CC, 0x100BFA3F: constructor, argument conversion, executor. BF2_CONSOLE_PROPERTY(sunColor, Vec3, lightManager(), setSunColor, getSunColor, kLightManagerConsoleTag) +// PE 0x100BFAC3, 0x100BFB48, 0x100BFBBB: constructor, argument conversion, executor. BF2_CONSOLE_PROPERTY(sunSpecColor, Vec3, lightManager(), setSunSpecColor, getSunSpecColor, kLightManagerConsoleTag) +// PE 0x100BFC3F, 0x100BFCB0, 0x100BFCFD: constructor, argument conversion, executor. BF2_CONSOLE_PROPERTY(enableSun, bool, lightManager(), setSunEnabled, getSunEnabled, kLightManagerConsoleTag) -// Bindings 40 and 41 remain unpublished. Binding 42 is the last binding before weatherManager's -// defaults. The public console spelling +// PE 0x100BFE12, +0x11C/+0x120. +// PE 0x100BFD54, 0x100BFDC5: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(enableStencilCullerReset, bool, lightManager(), + setStencilCullerResetEnabled, getStencilCullerResetEnabled, + kLightManagerConsoleTag) + +// PE 0x100BFF80, +0x2D4/+0x2D8: the same LOD limit the StaticMesh shadow draw uses. +// PE 0x100BFE69, 0x100BFF33: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(maxLodForMaterialBatching, int, lightManager(), + setShadowMergeLodLimit, getShadowMergeLodLimit, kLightManagerConsoleTag) + +// The last binding before weatherManager's defaults. The public console spelling // is instruction-proven as dynamicPointScale even though the evidence-scoped interface wrapper // describes the underlying value as a dynamic-light range scale. +// PE 0x100BFFCC, 0x100C003D: constructor, argument conversion. BF2_CONSOLE_PROPERTY(dynamicPointScale, float, lightManager(), setDynamicLightRangeScale, getDynamicLightRangeScale, kLightManagerConsoleTag) // A separate shipped console name for the same LightManager singleton. PE 101D1AEA installs // SetConsoleClassDefaults("shadowManager", 2, 0), after weatherManager and before HemiMapManager. -// Keep the recovered subset in .CRT order: 102367E4, 102367F0, 102367F4. Other shadowManager -// commands remain unpublished until their complete accessor contracts are recovered. +// The property constructors occupy .CRT entries 0x10236760..0x10236800 in retail order. BF2_CONSOLE_OBJECT("shadowManager", 2, 0) -// PE constructor 100C3A4C / parser 100C3ABD / executor int, +28C setter/+290 getter. +// PE 0x100C17FE, +0x9C/+0xA0. +// PE 0x100C1740, 0x100C17B1: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(shadowMapSize, int, lightManager(), + setShadowMapSize, getShadowMapSize, kShadowManagerConsoleTag) +// PE 0x100C1919, +0xA4/+0xA8. +// PE 0x100C185B, 0x100C18CC: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(shadowMapObjectSize, int, lightManager(), + setShadowMapObjectSize, getShadowMapObjectSize, kShadowManagerConsoleTag) +// PE 0x100C1A23, +0xAC/+0xB0. +// PE 0x100C1965, 0x100C19D6: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(shadowMapBitDepth, int, lightManager(), + setShadowMapBitDepth, getShadowMapBitDepth, kShadowManagerConsoleTag) +// PE 0x100C1B2D, +0xB4/+0xB8. +// PE 0x100C1A6F, 0x100C1AE0: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(shadowMapDepthDistance, float, lightManager(), + setShadowDistance, getShadowDistance, kShadowManagerConsoleTag) +// PE 0x100C1C3A, +0xC4/+0xC8. +// PE 0x100C1B7C, 0x100C1BED: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(shadowMapIncludeStaticMeshes, bool, lightManager(), + setShadowStaticFeature, getShadowStaticFeature, kShadowManagerConsoleTag) +// PE 0x100C1D4F, +0xCC/+0xD0. +// PE 0x100C1C91, 0x100C1D02: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(shadowShowFrustums, bool, lightManager(), + setShadowShowFrustums, getShadowShowFrustums, kShadowManagerConsoleTag) +// PE 0x100C1E64, +0xD4/+0xD8. +// PE 0x100C1DA6, 0x100C1E17: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(shadowIntensityBias, float, lightManager(), + setShadowIntensityBias, getShadowIntensityBias, kShadowManagerConsoleTag) +// PE 0x100C1F71, +0xDC/+0xE0. Keep retail's lowercase m in lightmap. +// PE 0x100C1EB3, 0x100C1F24: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(lightmapIntensityBias, float, lightManager(), + setLightMapIntensityBias, getLightMapIntensityBias, kShadowManagerConsoleTag) +// PE 0x100C207E, +0xE4/+0xE8. +// PE 0x100C1FC0, 0x100C2031: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(dropShadowClipHeightOffset, float, lightManager(), + setDropShadowClipHeightOffset, getDropShadowClipHeightOffset, kShadowManagerConsoleTag) +// PE 0x100C218B, +0xEC/+0xF0. +// PE 0x100C20CD, 0x100C213E: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(dynamicShadowsEnabled, bool, lightManager(), + setDynamicShadowsEnabled, getDynamicShadowsEnabled, kShadowManagerConsoleTag) + +// PE 0x100C22A0, +0xF4/+0xF8. +// PE 0x100C21E2, 0x100C2253: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(dynamicStaticMeshShadowsEnabled, bool, lightManager(), + setDynamicStaticMeshShadowsEnabled, getDynamicStaticMeshShadowsEnabled, + kShadowManagerConsoleTag) +// PE 0x100C23B5, +0xFC/+0x100. +// PE 0x100C22F7, 0x100C2368: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(dynamic1pShadowsEnabled, bool, lightManager(), + setDynamic1pShadowsEnabled, getDynamic1pShadowsEnabled, kShadowManagerConsoleTag) +// PE 0x100C24CA, +0x104/+0x108. +// PE 0x100C240C, 0x100C247D: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(allowAlphaShadows, bool, lightManager(), + setAllowAlphaShadows, getAllowAlphaShadows, kShadowManagerConsoleTag) +// PE 0x100C25DF, +0x10C/+0x110. +// PE 0x100C2521, 0x100C2592: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(alphaShadowThreshold, float, lightManager(), + setAlphaShadowThreshold, getAlphaShadowThreshold, kShadowManagerConsoleTag) +// PE 0x100C26EC, +0x114/+0x118. +// PE 0x100C262E, 0x100C269F: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(shadowUpdateFactor, float, lightManager(), + setShadowUpdateFactor, getShadowUpdateFactor, kShadowManagerConsoleTag) +// PE 0x100C27F9, +0x124/+0x128. +// PE 0x100C273B, 0x100C27AC: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(shadowUpdatesEnabled, bool, lightManager(), + setShadowUpdatesEnabled, getShadowUpdatesEnabled, kShadowManagerConsoleTag) +// PE 0x100C290E, +0x12C/+0x130. +// PE 0x100C2850, 0x100C28C1: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(shadowMapDepthBias, float, lightManager(), + setShadowDepthBias, getShadowDepthBias, kShadowManagerConsoleTag) +// PE 0x100C2A1B, +0x134/+0x138. +// PE 0x100C295D, 0x100C29CE: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(shadowMapSlopeBias, float, lightManager(), + setShadowSlopeScaleDepthBias, getShadowSlopeScaleDepthBias, kShadowManagerConsoleTag) +// PE 0x100C2B28; getter +0x13C precedes setter +0x140. +// PE 0x100C2A6A, 0x100C2ADB: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(shadowOccluderOversizeFactor, float, lightManager(), + setShadowOccluderOversizeFactor, getShadowOccluderOversizeFactor, + kShadowManagerConsoleTag) +// PE 0x100C2C35; getter +0x144 precedes setter +0x148. +// PE 0x100C2B77, 0x100C2BE8: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(useLSSMOptimizations, bool, lightManager(), + setUseLSSMOptimizations, getUseLSSMOptimizations, kShadowManagerConsoleTag) + +// PE 0x100C2D4A, +0x150/+0x14C. +// PE 0x100C2C8C, 0x100C2CFD: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(usePSMOptimizations, bool, lightManager(), + setUsePSMOptimizations, getUsePSMOptimizations, kShadowManagerConsoleTag) +// PE 0x100C2E5F, +0x158/+0x154. +// PE 0x100C2DA1, 0x100C2E12: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(shadowPSMUseSlideback, bool, lightManager(), + setShadowPSMUseSlideback, getShadowPSMUseSlideback, kShadowManagerConsoleTag) +// PE 0x100C2F74, +0x160/+0x15C. +// PE 0x100C2EB6, 0x100C2F27: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(shadowPSMUseUnitCubeClipping, bool, lightManager(), + setShadowPSMUseUnitCubeClipping, getShadowPSMUseUnitCubeClipping, + kShadowManagerConsoleTag) +// PE 0x100C3089, +0x168/+0x164. +// PE 0x100C2FCB, 0x100C303C: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(shadowPSMZNearOffset, float, lightManager(), + setShadowPSMZNearOffset, getShadowPSMZNearOffset, kShadowManagerConsoleTag) +// PE 0x100C3196, +0x170/+0x16C. +// PE 0x100C30D8, 0x100C3149: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(shadowPSMZFarOffset, float, lightManager(), + setShadowPSMZFarOffset, getShadowPSMZFarOffset, kShadowManagerConsoleTag) +// PE 0x100C32A3, +0x178/+0x174. +// PE 0x100C31E5, 0x100C3256: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(shadowPSMZMinInfinityZ, float, lightManager(), + setShadowPSMZMinInfinityZ, getShadowPSMZMinInfinityZ, kShadowManagerConsoleTag) +// PE 0x100C33B0, +0x180/+0x17C. +// PE 0x100C32F2, 0x100C3363: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(shadowPSMFovY, float, lightManager(), + setShadowPSMFovY, getShadowPSMFovY, kShadowManagerConsoleTag) +// PE 0x100C34BD, +0x188/+0x184. +// PE 0x100C33FF, 0x100C3470: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(shadowTSMFocus, float, lightManager(), + setShadowTSMFocus, getShadowTSMFocus, kShadowManagerConsoleTag) +// PE 0x100C35CA, +0x190/+0x18C. +// PE 0x100C350C, 0x100C357D: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(shadow80Line, float, lightManager(), + setShadow80Line, getShadow80Line, kShadowManagerConsoleTag) +// PE 0x100C36D7, +0x194/+0x198. +// PE 0x100C3619, 0x100C368A: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(shadowMergeDynamicShadowFrustums, bool, lightManager(), + setShadowMergeDynamicShadowFrustums, getShadowMergeDynamicShadowFrustums, + kShadowManagerConsoleTag) + +// PE 0x100C37EC, +0x274/+0x278. +// PE 0x100C372E, 0x100C379F: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(shadowFromTerrainLod, int, lightManager(), + setTerrainShadowLod, getTerrainShadowLod, kShadowManagerConsoleTag) +// PE 0x100C38F6, +0x27C/+0x280. +// PE 0x100C3838, 0x100C38A9: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(shadowFromStaticMeshLod, int, lightManager(), + setStaticMeshShadowLod, getStaticMeshShadowLod, kShadowManagerConsoleTag) +// PE 0x100C3A00, +0x284/+0x288. +// PE 0x100C3942, 0x100C39B3: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(shadowFromBundledMeshLod, int, lightManager(), + setBundledMeshShadowLod, getBundledMeshShadowLod, kShadowManagerConsoleTag) +// PE 0x100C3B0A, +0x28C/+0x290. +// PE 0x100C3A4C, 0x100C3ABD: constructor, argument conversion. BF2_CONSOLE_PROPERTY(shadowFromSkinnedMeshLod, int, lightManager(), setSkinnedMeshShadowLod, getSkinnedMeshShadowLod, kShadowManagerConsoleTag) -// PE constructor 100C3D6D / parser 100C3DDE / executor float, +2A4/+2A8. +// PE 0x100C3C14, +0x294/+0x298. +// PE 0x100C3B56, 0x100C3BC7: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(shadowOverrideQuality, int, lightManager(), + setShadowOverrideQuality, getShadowOverrideQuality, kShadowManagerConsoleTag) +// PE 0x100C3D1E, +0x29C/+0x2A0. Shipped defect: the public spelling is Lenght. +// PE 0x100C3C60, 0x100C3CD1: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(shadowTestBelowRayLenght, float, lightManager(), + setShadowRoofRayLength, getShadowRoofRayLength, kShadowManagerConsoleTag) +// PE 0x100C3E2B, +0x2A4/+0x2A8. +// PE 0x100C3D6D, 0x100C3DDE: constructor, argument conversion. BF2_CONSOLE_PROPERTY(shadowSunScalePower, float, lightManager(), setShadowSunScalePower, getShadowSunScalePower, kShadowManagerConsoleTag) -// PE constructor 100C3E7A / parser 100C3EFA / executor Vec2, +2BC/+2C0. +// PE 0x100C3F65, +0x2BC/+0x2C0. +// PE 0x100C3E7A, 0x100C3EFA: constructor, argument conversion. BF2_CONSOLE_PROPERTY(shadowSunHeightOverFade, Vec2, lightManager(), setShadowSunHeightOverFade, getShadowSunHeightOverFade, kShadowManagerConsoleTag) +// PE 0x100C408C, +0x2AC/+0x2B0. +// PE 0x100C3FCE, 0x100C403F: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(shadowSunExtrusionLength, float, lightManager(), + setShadowPullbackDistance, getShadowPullbackDistance, kShadowManagerConsoleTag) +// PE 0x100C4199, +0x2B4/+0x2B8. +// PE 0x100C40DB, 0x100C414C: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(shadowUseSweepTest, bool, lightManager(), + setShadowUseSweepTest, getShadowUseSweepTest, kShadowManagerConsoleTag) +// PE 0x100C42AE, +0x2E4/+0x2E8. +// PE 0x100C41F0, 0x100C4261: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(occludedSkyNightIntensity, float, lightManager(), + setOccludedSkyNightIntensity, getOccludedSkyNightIntensity, kShadowManagerConsoleTag) } // anonymous namespace @@ -168,5 +436,4 @@ bool unregisterShadowManagerConsoleObjects() } // namespace hfe } // namespace dice -#endif // BF2_PLUGIN_ABI_NATIVE #endif // BF2_IMAGE_RENDDX9 diff --git a/Code/BF2/Geom/LightMerger.cpp b/Code/BF2/Geom/LightMerger.cpp new file mode 100644 index 000000000..e9fcc6ca5 --- /dev/null +++ b/Code/BF2/Geom/LightMerger.cpp @@ -0,0 +1,178 @@ +// Expansion-light grouping helper owned by the Xp light coordinator (+0xB0). +// Placement follows the attested _r file Code/BF2/Geom/LightMerger.cpp. + +#ifdef BF2_IMAGE_RENDDX9 + +#include "LightMerger.h" +#include "XpLightManager.h" +#include "../../RendDX9Abi/BfMemory.h" +#include "../Game/Objects/Visual/LightSource.h" +#include "../RendDX9/RendDX9Base.h" + +#include + +namespace dice { +namespace hfe { +namespace geom { + +extern LightManager* g_LightManager; // ModuleGeom.cpp, dword_1024B914 + +namespace { + +// PE 0x10264104: the frame's pooled group records, released by LightMerger::releaseRecords. +std::vector s_recordPool; + +} // anonymous namespace + +// PE 0x101938A0. +LightMergerRecord::LightMergerRecord() +{ + first.x = first.y = first.z = 0.0f; + second.x = second.y = second.z = 0.0f; +} + +// PE 0x101938C0. Both colours start as the light source's colour (LightSource +0x198). +LightMergerRecord::LightMergerRecord(const XpLight* light) +{ + first.x = first.y = first.z = 0.0f; + second.x = second.y = second.z = 0.0f; + second = xpLightSource(light)->getColor(); + first = second; +} + +// PE 0x10193910. Unreachable in 1.50: no code or data references. +LightMergerRecord::LightMergerRecord(const LightMergerRecord& other) +{ + first.x = other.first.x; first.y = other.first.y; first.z = other.first.z; + second.x = other.second.x; second.y = other.second.y; second.z = other.second.z; +} + +// PE 0x10193940. The sun colour (manager slot +0x1AC) is read before the sky colour (slot +0x30). +// Unreachable in 1.50: no code or data references. +void LightMergerRecord::captureLightManagerColors() +{ + first = g_LightManager->getSunColor(); + second = g_LightManager->getSkyColor(); +} + +// PE 0x10193990. Unreachable in 1.50: no code or data references. +void LightMergerRecord::applyToLightManager() const +{ + float* const constants = reinterpret_cast(dx9rend::raShaderConstantsAt(0x1F8)); + constants[0] = second.x; + constants[1] = second.y; + constants[2] = second.z; + g_LightManager->setSunColor(first); // slot +0x1A8 + g_LightManager->setSkyColor(second); // slot +0x2C +} + +// PE 0x10193EB0. Unreachable in 1.50: no code or data references. +void LightMerger::addLight(Key key, XpLight* light) +{ + m_dirty = true; + m_input.insert(std::make_pair(key, light)); +} + +// PE 0x10194020. Unreachable in 1.50: no code or data references. +LightMergerRecord* LightMerger::findRecord(Key key) +{ + if (m_output.count(key) != 0) + return m_output[key]; + return 0; +} + +// PE 0x10194080. The group vector is heap-owned (PE 0x101947B0 zeroes its three pointers). +LightMerger::LightMerger() + : m_group(0), m_input(), m_output(), m_dirty(false) +{ + void* const storage = ::renddx9abi::engineAlloc(sizeof(std::vector)); + m_group = storage ? new (storage) std::vector() : 0; +} + +// PE 0x10193EE0. Destroys the output cache, then the input map. Shipped defect: the +0x00 group +// vector is never released; its destructor, PE 0x101947C0, has no caller. +LightMerger::~LightMerger() +{ +} + +// PE 0x10193E40. +void LightMerger::clearTransient() +{ + m_input.clear(); + m_output.clear(); +} + +// PE 0x10193F40. A key change flushes the group built so far and caches that record under the +// NEW key; the lights of the last key are left in the group without a flush. Both are shipped +// behaviour. +void LightMerger::finalize() +{ + if (m_input.size() != 0) + { + Key previous = m_input.begin()->first; + for (std::multimap::const_iterator it = m_input.begin(); + it != m_input.end(); ++it) + { + const Key key = it->first; + XpLight* const light = it->second; + if (key != previous) + { + LightMergerRecord* const record = flushLightGroup(*m_group); + previous = key; + m_output[key] = record; + } + m_group->push_back(light); + } + } + m_dirty = false; +} + +// PE 0x101948F0. The record destructor, PE 0x10193890, is empty. +void LightMerger::releaseRecords() +{ + for (std::vector::iterator it = s_recordPool.begin(); + it != s_recordPool.end(); ++it) + { + LightMergerRecord* const record = *it; + if (record) + { + record->~LightMergerRecord(); + ::renddx9abi::engineFree(record); + } + } + s_recordPool.resize(0); +} + +// PE 0x10194840. A nonempty group allocates a record from its first light and pools it; an empty +// group reuses the first pooled record (retail writes through a null record when the pool is also +// empty; finalize never flushes an empty group). The group is emptied and the record's colours +// are then overwritten with (0, 1, 0), replacing the constructor's source colour. +LightMergerRecord* flushLightGroup(std::vector& group) +{ + LightMergerRecord* record = 0; + if (group.size() != 0) + { + XpLight* const light = group[0]; + void* const storage = ::renddx9abi::engineAlloc(sizeof(LightMergerRecord)); + record = storage ? new (storage) LightMergerRecord(light) : 0; + s_recordPool.push_back(record); + } + else if (s_recordPool.size() != 0) + { + record = s_recordPool[0]; + } + group.resize(0); + record->second.y = 1.0f; + record->second.x = 0.0f; + record->second.z = 0.0f; + record->first.y = 1.0f; + record->first.x = 0.0f; + record->first.z = 0.0f; + return record; +} + +} // namespace geom +} // namespace hfe +} // namespace dice + +#endif // BF2_IMAGE_RENDDX9 diff --git a/Code/BF2/Geom/LightMerger.h b/Code/BF2/Geom/LightMerger.h new file mode 100644 index 000000000..65660cd42 --- /dev/null +++ b/Code/BF2/Geom/LightMerger.h @@ -0,0 +1,86 @@ +// Expansion-light grouping helper owned by the Xp light coordinator. +// Placement follows the attested _r file Code/BF2/Geom/LightMerger.cpp; member and method +// spellings are [INFERRED]. +#ifndef GEOM_LIGHTMERGER_H +#define GEOM_LIGHTMERGER_H + +#ifdef BF2_IMAGE_RENDDX9 + +#include "../Math/Vec3.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace geom { + +struct XpLight; + +// A merged light group's two colours, pooled for the frame. +struct LightMergerRecord +{ + LightMergerRecord(); // PE 0x101938A0: all zero + explicit LightMergerRecord(const XpLight* light); // source colour, twice + LightMergerRecord(const LightMergerRecord& other); // member-wise copy + + // PE 0x10193940: first = the light manager's sun colour, second = its sky colour. + // [INFERRED] name; unreachable in 1.50: no code or data references. + void captureLightManagerColors(); + // PE 0x10193990: publishes second to the Ra constants (+0x1F8), then the manager's sun colour + // (first) and sky colour (second). [INFERRED] name; unreachable in 1.50. + void applyToLightManager() const; + + /* +0x00 */ Vec3 first; + /* +0x0C */ Vec3 second; +}; + +// Groups the input lights by key and caches one pooled record per group. The coordinator clears +// it at the start of a light frame and finalizes it after the frame's geometry pairs are built. +// In the shipped image nothing inserts into the input map (its only inserter, PE 0x10193EB0, has no +// caller), so finalize finds it empty and the output cache and record pool stay empty. +class LightMerger +{ +public: + LightMerger(); + ~LightMerger(); + + // Empties the input map and the output cache; the record pool is released separately. + void clearTransient(); + // Walks the input map in key order, publishing each finished group, then clears the dirty + // flag. The final group is never flushed, as in retail. + void finalize(); + + // Destroys every pooled record and empties the pool. + static void releaseRecords(); + + // [UNRESOLVED] The key's identity: its producer, PE 0x10193EB0, is unreferenced. Keys compare + // as unsigned pointers. + typedef const void* Key; + + // PE 0x10193EB0: marks the merger dirty and adds a light to the input map under a key. + // [INFERRED] name; unreachable in 1.50: no code or data references. + void addLight(Key key, XpLight* light); + // PE 0x10194020: the record cached for a key, or null. [INFERRED] name; unreachable in 1.50. + LightMergerRecord* findRecord(Key key); + +private: + LightMerger(const LightMerger&); + LightMerger& operator=(const LightMerger&); + + /* +0x00 */ std::vector* m_group; + /* +0x04 */ std::multimap m_input; + /* +0x10 */ std::map m_output; + /* +0x1C */ bool m_dirty; +}; + +// Turns the accumulated group into a pooled record, then empties the group. +LightMergerRecord* flushLightGroup(std::vector& group); + +} // namespace geom +} // namespace hfe +} // namespace dice + +#endif // BF2_IMAGE_RENDDX9 + +#endif // GEOM_LIGHTMERGER_H diff --git a/Code/BF2/Geom/LightmapGeneration/ILightSampling.h b/Code/BF2/Geom/LightmapGeneration/ILightSampling.h index 1de315793..7cc27ba7e 100644 --- a/Code/BF2/Geom/LightmapGeneration/ILightSampling.h +++ b/Code/BF2/Geom/LightmapGeneration/ILightSampling.h @@ -46,9 +46,9 @@ struct LightSampleBlock { unsigned int sampleCount; // +0x00 texels in the block (terrain) / valid samples (mesh) TerrainAabb bounds; // +0x04 the block's world box (the mesh sampler leaves it empty) - // +0x40 - the mesh sampler's VC7.1 vector of 92-byte triangle records itself (the vector object - // at its +0x18; MeshLightSampling.h); 0 for the terrain sampler, which has no triangles. The - // generator reads the vector's first / last and each record's normals at +0x24 / +0x30 / +0x3C. + // +0x40 - the mesh sampler's std::vector of 92-byte triangle records itself + // (its m_triangles; MeshLightSampling.h); 0 for the terrain sampler, which has no triangles. The + // generator reads the vector's elements and each record's three normals. const void* triangles; }; @@ -72,8 +72,9 @@ class ILightSampling : public IBase // answers its index (the mesh sampler: -1 while its record vector has no storage). The terrain // sampler ignores it and answers 0. [INFERRED] name. virtual int addLight(Vec3 color, Vec3 position, float range) = 0; // +0x20 - // The mesh sampler's recorded lights: its VC7.1 vector (at +0x28) of 28-byte (position, colour, - // range) records as addLight stores them; null for the terrain sampler. No caller is known. + // The mesh sampler's recorded lights: its std::vector (m_lights) of 28-byte + // (position, colour, range) records as addLight stores them; null for the terrain sampler. No + // caller is known. // [INFERRED] name. virtual void* getLights() = 0; // +0x24 diff --git a/Code/BF2/Geom/LightmapGeneration/LightmapGeneration.cpp b/Code/BF2/Geom/LightmapGeneration/LightmapGeneration.cpp index 6cccf77b7..530b9bf5d 100644 --- a/Code/BF2/Geom/LightmapGeneration/LightmapGeneration.cpp +++ b/Code/BF2/Geom/LightmapGeneration/LightmapGeneration.cpp @@ -10,7 +10,11 @@ #ifdef BF2_IMAGE_RENDDX9 #include "LightmapGeneration.h" +#if defined(__APPLE__) +#include "../../Platform/X87Compat.h" +#endif #include "ILightSampleable.h" +#include "MeshLightSampling.h" // MeshSampleTriangle - LightSampleBlock::triangles' element #include "../IGeometryTemplate.h" #include "../ITerrainEditable.h" #include "../StaticMesh.h" // m_template, staticMeshRootParent @@ -19,6 +23,8 @@ #include "../../Core/System.h" #include "../../Math/Frustum.h" +#include "../../Math/Ray3.h" +#include "../../RendDX9/RendDX9Math.h" // the RendDX9.dll Math copies #include "../../Math/Mat4.h" #include "../../RendDX9/RendDX9Base.h" #include "../../RendDX9/ShaderParameter.h" @@ -26,19 +32,15 @@ #include "../../RendMisc/IRenderView.h" #include "../../RendMisc/IRenderer.h" #include "../../../RendDX9Abi/BfMemory.h" +#include "../../../RendDX9Abi/D3dx9Sdk.h" #include "../../../RendDX9Abi/Frontier.h" #include "../../../RendDX9Abi/PluginAbi.h" #include "../../../RendDX9Abi/PluginEntry.h" -#include "../../../RendDX9Abi/Vc71String.h" -#include "../../../RendDX9Abi/Vc71Vector.h" +#include // The engine interfaces below are imported for their virtual order; in the retail flavour the // renderer's own IBase/IClassManager (HfeAbi.h) stand in for the host headers, exactly as // XpLightManager.cpp brackets the same includes. -#if !BF2_PLUGIN_ABI_NATIVE -#define CORE_IBASE_H -#define CORE_CLASSMANAGER_H -#endif #include "../../Game/Objects/IObject.h" #include "../../Game/Objects/IObjectTemplate.h" #include "../../Game/Objects/ObjectLayoutAccess.h" @@ -47,10 +49,6 @@ #include "../../Physics/Heightmap.h" #include "../../Physics/HeightmapCluster.h" #include "../../Scene/Object/ObjectManager.h" -#if !BF2_PLUGIN_ABI_NATIVE -#undef CORE_CLASSMANAGER_H -#undef CORE_IBASE_H -#endif #include #include @@ -60,12 +58,7 @@ #include #include #include - -// The D3DX sphere factory (d3dx9_25 exports undecorated names, XpLightManager.cpp's bridge). -extern "C" HRESULT WINAPI D3DXCreateSphere( - IDirect3DDevice9* device, float radius, unsigned int slices, - unsigned int stacks, IUnknown** mesh, void** adjacency); -#pragma comment(linker, "/alternatename:_D3DXCreateSphere@24=_D3DXCreateSphere") +#include namespace dice { namespace hfe { @@ -82,7 +75,7 @@ extern void* g_bufferManager; // BufferManager.cpp, StateManager.cpp and RendDX9Draw.cpp seams, declared per TU as the other // geometry classes declare them. void* createVertexBuffer(void* bufferManager, unsigned int count, unsigned int stride, - const vc71::string& name, unsigned int usage); + const std::string& name, unsigned int usage); int bufferManagerSwapPool(int value); void* vertexBufferLock(void* wrapper, unsigned int offsetVerts, unsigned int countVerts, unsigned int flags); @@ -103,8 +96,8 @@ extern LightManager* g_LightManager; // GeomMisc/FontSystem/FontSystem.cpp - Font::Ported and its +0x10 load / +0x18 drawText slots. IBase* createFontPortedDirect(); -bool fontPortedLoad(IBase* font, const vc71::string& path); -void fontPortedDrawText(IBase* font, float x, float y, const vc71::string& text); +bool fontPortedLoad(IBase* font, const std::string& path); +void fontPortedDrawText(IBase* font, float x, float y, const std::string& text); LightmapGeneration* g_LightmapGeneration = 0; @@ -133,36 +126,12 @@ const unsigned int kUnsetBits = 0xBF800000u; // -1.0f: "use the const unsigned int kTargetSize = 0x400u; // the 1024 x 1024 target const unsigned int kFormatA8R8G8B8 = 21u; const unsigned int kFormatD24S8 = 75u; - -// The mesh sampler's triangle record as far as the back-face test reads it (the -// LightSampleBlock::triangles vector's element). -struct SampleTriangle -{ - unsigned char unread00[0x24]; - Vec3 normal[3]; // +0x24 / +0x30 / +0x3C - unsigned char unread48[0x14]; -}; - -// The ID3DXMesh slots the generator calls, in d3dx9mesh.h order (the prefix XpLightManager.cpp -// declares as RendD3dxMesh; the build carries no D3DX headers). -struct LightmapD3dxMesh : public IUnknown -{ - virtual HRESULT STDMETHODCALLTYPE DrawSubset(DWORD attributeId) = 0; // +0x0C - virtual DWORD STDMETHODCALLTYPE GetNumFaces() = 0; // +0x10 - virtual DWORD STDMETHODCALLTYPE GetNumVertices() = 0; // +0x14 - virtual DWORD STDMETHODCALLTYPE GetFVF() = 0; // +0x18 - virtual HRESULT STDMETHODCALLTYPE GetDeclaration(D3DVERTEXELEMENT9*) = 0; // +0x1C - virtual DWORD STDMETHODCALLTYPE GetNumBytesPerVertex() = 0; // +0x20 - virtual DWORD STDMETHODCALLTYPE GetOptions() = 0; // +0x24 - virtual HRESULT STDMETHODCALLTYPE GetDevice(IDirect3DDevice9**) = 0; // +0x28 - virtual HRESULT STDMETHODCALLTYPE CloneMeshFVF( - DWORD options, DWORD fvf, IDirect3DDevice9* device, IUnknown** clone) = 0; // +0x2C - virtual HRESULT STDMETHODCALLTYPE CloneMesh( - DWORD options, const D3DVERTEXELEMENT9* declaration, - IDirect3DDevice9* device, IUnknown** clone) = 0; // +0x30 - virtual HRESULT STDMETHODCALLTYPE GetVertexBuffer(IDirect3DVertexBuffer9**) = 0; // +0x34 - virtual HRESULT STDMETHODCALLTYPE GetIndexBuffer(IDirect3DIndexBuffer9**) = 0; // +0x38 -}; +// The count word an occluder node's children array carries ahead of the four nodes (4 bytes in +// retail). [CHOSEN, not recovered] x64 (https://github.com/B2BF/OpenBF2/issues/7): padded to +// pointer size so the nodes, which hold pointers, stay pointer-aligned. +const unsigned int kChildCountHeader = + sizeof(void*) > sizeof(unsigned int) ? static_cast(sizeof(void*)) + : static_cast(sizeof(unsigned int)); // The light marker clone's declaration: one FLOAT3 position. const D3DVERTEXELEMENT9 kLightMeshDeclaration[2] = @@ -171,10 +140,6 @@ const D3DVERTEXELEMENT9 kLightMeshDeclaration[2] = { 0xFF, 0, D3DDECLTYPE_UNUSED, 0, 0, 0 } }; -#if defined(_M_IX86) -static_assert(sizeof(SampleTriangle) == 92, "the trace divides the triangle vector by 92"); -#endif - inline bool isUnset(float value) { unsigned int bits; @@ -182,51 +147,26 @@ inline bool isUnset(float value) return bits == kUnsetBits; } -// Host strings: the retail flavour's references are VC7.1 strings; only the static spelling of -// the reference changes (NametagManager.cpp / XpLightManager.cpp). -#if BF2_PLUGIN_ABI_NATIVE +// Host strings are this image's std::string; these keep the call sites' host-string spelling +// (NametagManager.cpp / XpLightManager.cpp). inline const std::string& hostStdString(const ::renddx9abi::HostString& value) { return value; } inline const ::renddx9abi::HostString& fromHostStdString(const std::string& value) { return value; } -#else -inline const std::string& hostStdString(const ::renddx9abi::HostString& value) -{ - return *reinterpret_cast(&value); -} -inline const ::renddx9abi::HostString& fromHostStdString(const std::string& value) -{ - return *reinterpret_cast(&value); -} -#endif // The light and object template reads XpLightManager.cpp makes: the retail flavour reads the // retail layout's fields, the native flavour the rebuilt classes' accessors. inline const world::LightSourceTemplate* lightSourceTemplatePointer(const world::LightSource* light) { -#if BF2_PLUGIN_ABI_NATIVE return static_cast(light->getTemplate()); -#else - return *reinterpret_cast( - reinterpret_cast(light) + 0x144); -#endif } inline unsigned int lightSourceFlags(const world::LightSource* light) { -#if BF2_PLUGIN_ABI_NATIVE return light->getFlags(); -#else - return *reinterpret_cast(reinterpret_cast(light) + 0x04); -#endif } inline const world::IObjectTemplate* objectTemplatePointer(const world::IObject* object) { -#if BF2_PLUGIN_ABI_NATIVE return object->getTemplate(); -#else - return *reinterpret_cast( - reinterpret_cast(object) + 0x14); -#endif } inline world::IHeightmapCluster* heightmapClusterByName() @@ -255,7 +195,7 @@ inline IDirect3DDevice9* renderDevice() // tree; each slot is reached through the instance's table (OverGrowthLoad.cpp's precedent). inline void* geometrySlot(void* geometry, unsigned int offset) { - return (*reinterpret_cast(geometry))[offset / sizeof(void*)]; + return (*reinterpret_cast(geometry))[offset / 4]; } inline void geometryDrawSilhouette(void* geometry, void* renderView, int legacyArm) // +0x1C { @@ -296,7 +236,7 @@ inline int geometryGetLodCount(void* geometry) } // The image's printf-into-a-string helper (TerrainLightSampling.cpp carries the same body). -void formatString(vc71::string& out, const char* format, ...) +void formatString(std::string& out, const char* format, ...) { char buffer[0x1000]; va_list args; @@ -313,7 +253,7 @@ void formatString(vc71::string& out, const char* format, ...) // "%dmin %dsec", or "%dsec" under a minute; the seconds are unsigned. The trace inlines the // same body four times. -void formatTime(vc71::string& out, unsigned int seconds) +void formatTime(std::string& out, unsigned int seconds) { const unsigned int minutes = seconds / 60u; if (minutes) @@ -376,6 +316,25 @@ int normalize2(float* v) // FLT_EPSILON of unit length, zeroed below FLT_EPSILON, otherwise scaled. int normalize3(float* v) { +#if defined(__APPLE__) + // [CHOSEN, not recovered] Preserve the squared-length spill and retained inverse. + const bf2x87::Real x(v[0]), y(v[1]), z(v[2]); + const float lengthSquared = bf2x87::store(bf2x87::add(bf2x87::add( + bf2x87::mul(x, x), bf2x87::mul(y, y)), bf2x87::mul(z, z))); + if (bf2x87::less(bf2x87::abs(bf2x87::sub(bf2x87::Real(lengthSquared), bf2x87::Real(1))), bf2x87::Real(FLT_EPSILON))) + return 0; + if (bf2x87::less(bf2x87::abs(bf2x87::Real(lengthSquared)), bf2x87::Real(FLT_EPSILON))) + { + v[0] = 0.0f; + v[1] = 0.0f; + v[2] = 0.0f; + return -20001; + } + const bf2x87::Real inverse = bf2x87::div(bf2x87::Real(1), bf2x87::squareRoot(bf2x87::Real(lengthSquared))); + v[0] = bf2x87::store(bf2x87::mul(inverse, bf2x87::Real(v[0]))); + v[1] = bf2x87::store(bf2x87::mul(inverse, bf2x87::Real(v[1]))); + v[2] = bf2x87::store(bf2x87::mul(inverse, bf2x87::Real(v[2]))); +#else const float lengthSquared = v[0] * v[0] + v[1] * v[1] + v[2] * v[2]; if (std::fabs(lengthSquared - 1.0f) < FLT_EPSILON) return 0; @@ -390,10 +349,12 @@ int normalize3(float* v) v[0] = inverse * v[0]; v[1] = inverse * v[1]; v[2] = inverse * v[2]; +#endif return 0; } // The summed component distance of two Vec4s is within FLT_EPSILON (w first). +// PE 0x100A6070 inline bool vec4ApproxEqual(const float* a, const float* b) { const float distance = ((std::fabs(a[3] - b[3]) + std::fabs(a[2] - b[2])) @@ -402,6 +363,7 @@ inline bool vec4ApproxEqual(const float* a, const float* b) } // Row by row. +// PE 0x100A60C0 inline bool mat4ApproxEqual(const Mat4& a, const Mat4& b) { return vec4ApproxEqual(a.m, b.m) && vec4ApproxEqual(a.m + 4, b.m + 4) @@ -439,22 +401,6 @@ inline void transformPoint(const Mat4& matrix, const Vec3& in, Vec3& out) out.z = z; } -// a x b, in the shipped operand order. -inline void cross(float* out, const float* a, const float* b) -{ - out[0] = b[2] * a[1] - b[1] * a[2]; - out[1] = b[0] * a[2] - a[0] * b[2]; - out[2] = a[0] * b[1] - b[0] * a[1]; -} - -// out = transpose(in). -inline void mat4Transpose(Mat4& out, const Mat4& in) -{ - for (int row = 0; row < 4; ++row) - for (int column = 0; column < 4; ++column) - out.m[row * 4 + column] = in.m[column * 4 + row]; -} - // out = a * b, each element with the shipped association and store order. void mat4Mult(Mat4& out, const Mat4& left, const Mat4& right) { @@ -479,50 +425,6 @@ void mat4Mult(Mat4& out, const Mat4& left, const Mat4& right) o[15] = ((b[11] * a[14] + b[15] * a[15]) + b[7] * a[13]) + a[12] * b[3]; } -// The image's look-at: rows 0..2 are right, up and forward, the translation `eye`. -// A forward vector shorter than FLT_EPSILON leaves the identity; one within FLT_EPSILON of +-up -// keeps identity right/up rows and a zero translation. -void lookAt(Mat4& out, const Vec3& eye, const Vec3& target, const Vec3& up) -{ - float* const m = out.m; - for (int i = 0; i < 16; ++i) - m[i] = 0.0f; - m[0] = 1.0f; - m[5] = 1.0f; - m[10] = 1.0f; - m[15] = 1.0f; - const float fx = target.x - eye.x; - const float fy = target.y - eye.y; - const float fz = target.z - eye.z; - m[10] = fz; - m[8] = fx; - m[9] = fy; - const float length = std::sqrt((m[8] * m[8] + m[9] * m[9]) + m[10] * m[10]); - if (length < FLT_EPSILON) - { - m[1] = 0.0f; m[2] = 0.0f; m[3] = 0.0f; m[0] = 1.0f; - m[5] = 1.0f; m[4] = 0.0f; m[6] = 0.0f; m[7] = 0.0f; - m[10] = 1.0f; m[8] = 0.0f; m[9] = 0.0f; m[11] = 0.0f; - m[15] = 1.0f; m[13] = 0.0f; m[14] = 0.0f; m[12] = 0.0f; - return; - } - const float inverse = 1.0f / length; - m[8] = inverse * m[8]; - m[9] = inverse * m[9]; - m[10] = inverse * m[10]; - if (std::fabs(((m[10] * up.z + m[9] * up.y) + m[8] * up.x) - 1.0f) < FLT_EPSILON) - return; - if (std::fabs(((m[10] * up.z + m[9] * up.y) + m[8] * up.x) + 1.0f) < FLT_EPSILON) - return; - cross(m, &up.x, m + 8); - normalize3(m); - cross(m + 4, m + 8, m); - normalize3(m + 4); - m[12] = eye.x; - m[13] = eye.y; - m[14] = eye.z; -} - // Grows the box to hold `p` (max tested before min on each axis), then dirties it. void expandBox(TerrainAabb& box, const Vec3& p) { @@ -536,12 +438,14 @@ void expandBox(TerrainAabb& box, const Vec3& p) } // The box's radius and centre, refreshed while dirty. +// PE 0x100A61F0 inline float boxRadius(TerrainAabb& box) { if (box.dirty) box.refresh(); return box.radius; } +// PE 0x100A6210 inline const Vec3& boxCentre(TerrainAabb& box) { if (box.dirty) @@ -550,6 +454,7 @@ inline const Vec3& boxCentre(TerrainAabb& box) } // Does the sphere's bounding cube overlap the box? (min at +0, max at +0xC only). +// PE 0x100A6630 bool aabbSphereOverlap(const TerrainAabb& box, Vec3 centre, float radius) { const float low[3] = { centre.x - radius, centre.y - radius, centre.z - radius }; @@ -639,8 +544,57 @@ bool cornersInsideFrustum(const float* corners, const Frustum& frustum) } // The phong response curve: the value raised to 0.1, 0.15, 0.2, 0.25 or 0.3 (the image's double -// constants) for modes 1..5, unchanged otherwise. -float responseCurve(int mode, float value) +// constants) for modes 1..5, unchanged otherwise. Each arm of the image's body (responseCurve below) +// is fld value, fld the exponent, _CIpow, and the unrounded x87 result is returned in ST0; the +// callers clamp it with an fcom pair (1.0f, then 0.0f, a NaN passes), scale it where they scale, and +// narrow only at the store. +#if defined(__APPLE__) +// [CHOSEN, not recovered] Apple arm: the result stays bf2x87::Real until the caller's store. +// Apple silicon has no x87 _CIpow; it uses binary64 libm, the presentation-transcendental policy. +inline bf2x87::Real responsePow(float value, double exponent) +{ +#if defined(__aarch64__) + return bf2x87::Real(std::pow(static_cast(value), exponent)); +#else + return std::pow(static_cast(value), static_cast(exponent)); +#endif +} + +typedef bf2x87::Real ResponseValue; + +ResponseValue responseCurve(int mode, float value) +{ + switch (mode) + { + case 1: return responsePow(value, 0.10000000149011612); + case 2: return responsePow(value, 0.15000000596046448); + case 3: return responsePow(value, 0.20000000298023224); + case 4: return responsePow(value, 0.25); + case 5: return responsePow(value, 0.30000001192092896); + default: return bf2x87::Real(value); + } +} + +// The callers' fcom clamp on ST0: above 1 becomes 1, below 0 becomes 0, a NaN passes. +inline ResponseValue clampResponse(ResponseValue value) +{ + if (bf2x87::greater(value, bf2x87::Real(1.0f))) + return bf2x87::Real(1.0f); + if (bf2x87::less(value, bf2x87::Real(0.0f))) + return bf2x87::Real(0.0f); + return value; +} + +inline float storeResponse(ResponseValue value) { return bf2x87::store(value); } +inline float storeResponse(ResponseValue value, float scale) +{ + return bf2x87::store(bf2x87::mul(value, bf2x87::Real(scale))); +} +#else +typedef float ResponseValue; + +// PE 0x100A6230 +ResponseValue responseCurve(int mode, float value) { switch (mode) { @@ -653,7 +607,13 @@ float responseCurve(int mode, float value) } } +inline ResponseValue clampResponse(ResponseValue value) { return clampUnit(value); } +inline float storeResponse(ResponseValue value) { return value; } +inline float storeResponse(ResponseValue value, float scale) { return value * scale; } +#endif + // The device's current viewport, field by field. +// PE 0x100A6370 void getViewport(unsigned int& x, unsigned int& y, unsigned int& width, unsigned int& height, float& minZ, float& maxZ) { @@ -667,7 +627,8 @@ void getViewport(unsigned int& x, unsigned int& y, unsigned int& width, unsigned maxZ = viewport.MaxZ; } -// The trace's inline viewport stores, gathered into one helper. +// The trace's inline viewport stores, gathered into one helper (the traces inline it). +// PE 0x100A6320 (the image's out-of-line copy is unreachable in 1.50: no code or data references) inline void setViewport(unsigned int x, unsigned int y, unsigned int width, unsigned int height, float minZ, float maxZ) { @@ -682,6 +643,7 @@ inline void setViewport(unsigned int x, unsigned int y, unsigned int width, unsi } // The last light of the published generator (the global, not the caller), or null. +// PE 0x100A7150 LightInfo* lastLight() { LightmapGeneration* const generator = g_LightmapGeneration; @@ -693,6 +655,7 @@ LightInfo* lastLight() // The sky light's azimuth in radians: its direction reversed onto the xz plane, // normalised, acos of the z component, mirrored to 2*pi - angle on the negative x side. Zero // without a sky light. +// PE 0x100A6740 float sunAzimuth() { if (!g_LightManager->getSkyLight()) // +0x28 @@ -708,6 +671,7 @@ float sunAzimuth() // The first block whose box holds `position` (x and z inclusive, y within -9999..9999), else 0. // The shipped body is a member that never reads its object. +// PE 0x100A67E0 unsigned int nearestBlock(const Vec3& position, ILightSampling* sampler) { for (unsigned int i = 0; i < sampler->getBlockCount(); ++i) @@ -733,6 +697,17 @@ unsigned int nearestBlock(const Vec3& position, ILightSampling* sampler) // its geometry, the geometry box's corners in world space, the box centre in world space and its // radius (capped at 20000). False for objects farther than 10000 from the origin and objects // without geometry. The shipped body is a member that never reads its object. +// PE 0x10093B70 [INFERRED] the out-of-line Vec3 += (receiver in ECX, `retn 4`): each component +// becomes add + v, x, y, z in that order. Its only caller is fillObjectRecord (0x100A6C0F). +Vec3& addAssign(Vec3& v, const Vec3& add) +{ + v.x = add.x + v.x; + v.y = add.y + v.y; + v.z = add.z + v.z; + return v; +} + +// PE 0x100A6B30 bool fillObjectRecord(world::IObject* object, OccluderRecord* record) { if (!object) @@ -748,24 +723,82 @@ bool fillObjectRecord(world::IObject* object, OccluderRecord* record) if (!geometry) return false; const Vec3& p = record->position; +#if defined(__APPLE__) + // [CHOSEN, not recovered] The sum, FSQRT and comparison have no float spill. + const bf2x87::Real x(p.x), y(p.y), z(p.z); + if (bf2x87::greater(bf2x87::squareRoot(bf2x87::add(bf2x87::add( + bf2x87::mul(x, x), bf2x87::mul(y, y)), bf2x87::mul(z, z))), bf2x87::Real(10000))) +#else if (std::sqrt(p.x * p.x + p.y * p.y + p.z * p.z) > 10000.0f) // a NaN distance passes +#endif return false; aabbCorners(record->corners, &geometryLocalBounds(geometry)->min.x); transformCorners(record->corners, record->transform); record->centre = boxCentre(*geometryLocalBounds(geometry)); rotateInPlace(record->transform, record->centre); - record->centre.x = record->centre.x + record->position.x; - record->centre.y = record->centre.y + record->position.y; - record->centre.z = record->centre.z + record->position.z; + addAssign(record->centre, record->position); record->radius = boxRadius(*geometryLocalBounds(geometry)); +#if defined(__APPLE__) + if (bf2x87::greater(bf2x87::Real(record->radius), bf2x87::Real(20000))) +#else if (record->radius > 20000.0f) +#endif record->radius = 20000.0f; return true; } +// A box's eight corners, zeroed and then taken from its min and max (aabbCorners). [INFERRED] name. +struct LightmapBoxCorners +{ + float corners[24]; + + // Its only caller is lightmapBoxFrustumClass, itself without a caller. + // PE 0x100AE170 (unreachable in 1.50: no code or data references reach its caller) + explicit LightmapBoxCorners(const TerrainAabb& box) + { + for (int i = 0; i < 24; ++i) + corners[i] = 0.0f; + aabbCorners(corners, &box.min.x); + } +}; + } // anonymous namespace +// Does the ray meet the sphere? True when the ray starts inside or on it (the squared distance less +// the squared radius, stored as a float, is not positive; a NaN goes on); otherwise the normalised +// direction must point toward the centre (projection negative; a NaN goes on) and the squared +// projection must reach that stored value (ordered). [INFERRED] name; the receiver is +// [CHOSEN, not recovered] Ray3: the body reads an origin at +0x00 and a direction at +0x0C, which is +// Ray3's proven layout, and no image (retail, RendDX9_r) has a caller that could name the type. +// PE 0x100A6580 (unreachable in 1.50: no code or data references) +bool lightmapRayHitsSphere(const Ray3& ray, const Vec3& centre, float radius) +{ + const float dx = ray.origin.x - centre.x; + const float dy = ray.origin.y - centre.y; + const float dz = ray.origin.z - centre.z; + const float inside = (dz * dz + dx * dx + dy * dy) - radius * radius; + if (inside <= 0.0f) + return true; + Vec3 direction = ray.direction; + rendmath::normalize(direction); + const float projection = direction.z * dz + dx * direction.x + direction.y * dy; + if (projection >= 0.0f) + return false; + return projection * projection >= inside; +} + +// 1 when the frustum holds the box's corners (cornersInsideFrustum), else 2. [INFERRED] name; the +// box is [CHOSEN, not recovered] TerrainAabb: the corner builder reads only a min at +0x00 and a max +// at +0x0C, and no image (retail, RendDX9_r) has a caller that could name the type. +// PE 0x100A66C0 (unreachable in 1.50: no code or data references) +int lightmapBoxFrustumClass(const Frustum& frustum, const TerrainAabb& box) +{ + const LightmapBoxCorners corners(box); + return cornersInsideFrustum(corners.corners, frustum) ? 1 : 2; +} + + // vector::resize(count, false). [CHOSEN, not recovered] the word handling follows VC7.1's // resize semantics (insert falses at the end / trim and mask the last word); the image's insert // and erase bodies are not transcribed. Every bit below `count` is written by the trace before it @@ -795,6 +828,7 @@ void LightFacingBits::resize(unsigned int count) // The debug defaults: position (1360, 118, 700), radius 10, a directional light toward // normalise(0, 0.3, 1), intensity 1, shadow 0.8, a 8 degree view of 150 m, self-shadowing, 100 // occluders. colorRed stays unset. +// PE 0x100A77F0 LightInfo::LightInfo() { position.x = 1360.0f; @@ -846,39 +880,50 @@ LightInfo::LightInfo(const LightInfo& other) { } -// Releases the render view's reference, then the back-face bits. +// Releases the render view's reference, then the back-face bits. The destructions inline it. +// PE 0x100A7880 (the image's out-of-line copy is unreachable in 1.50: no code or data references) LightInfo::~LightInfo() { if (renderView) renderView->release(); } +// PE 0x100A6B00 (unreachable in 1.50: no code or data references) void LightInfo::setDirection(const Vec3& value) { direction = value; normalize3(&direction.x); } const Vec3& LightInfo::getDirection() const { return direction; } +// PE 0x100A6480 (unreachable in 1.50: no code or data references) void LightInfo::setShadowIntensity(float value) { shadowIntensity = value; } float LightInfo::getShadowIntensity() const { return shadowIntensity; } +// PE 0x100A64A0 (unreachable in 1.50: no code or data references) void LightInfo::setIntensity(float value) { intensity = value; } float LightInfo::getIntensity() const { return intensity; } +// PE 0x100A64C0 (unreachable in 1.50: no code or data references) void LightInfo::setFov(float value) { fov = value; } float LightInfo::getFov() const { return fov; } +// PE 0x100A64E0 (unreachable in 1.50: no code or data references) void LightInfo::setSelfShadowing(bool value) { selfShadowing = value; } bool LightInfo::getSelfShadowing() const { return selfShadowing != 0; } +// PE 0x100A6500 (unreachable in 1.50: no code or data references) void LightInfo::setObjectShadows(bool value) { objectShadows = value; } bool LightInfo::getObjectShadows() const { return objectShadows != 0; } +// PE 0x100A6520 (unreachable in 1.50: no code or data references) void LightInfo::setViewDistance(float value) { viewDistance = value; } float LightInfo::getViewDistance() const { return viewDistance; } +// PE 0x100A6540 (unreachable in 1.50: no code or data references) void LightInfo::setSoftness(float value) { softness = value; } float LightInfo::getSoftness() const { return softness; } +// PE 0x100A6560 (unreachable in 1.50: no code or data references) void LightInfo::setMaxOccluders(int value) { maxOccluders = value; } int LightInfo::getMaxOccluders() const { return maxOccluders; } // A zero position, the identity transformation, a zero box; object and geometry stay // unset (fillObjectRecord writes them). +// PE 0x100AE260 (the zeroed corners are OcclusionBoxCorners::OcclusionBoxCorners, PE 0x100AE110) OccluderRecord::OccluderRecord() { position.x = 0.0f; @@ -900,6 +945,7 @@ OccluderRecord::OccluderRecord() // An empty dirty box, zero corners and sphere, no children, no records. +// PE 0x100A7060 OccluderNode::OccluderNode() : children(0) { @@ -920,18 +966,20 @@ OccluderNode::OccluderNode() // The four children (array form: the count word ahead of them, destroyed last to // first, freed with the word), then the record list. +// PE 0x100A70D0 OccluderNode::~OccluderNode() { if (children) { - unsigned int* const cookie = reinterpret_cast(children) - 1; - for (unsigned int i = *cookie; i-- > 0; ) + unsigned char* const cookie = reinterpret_cast(children) - kChildCountHeader; + for (unsigned int i = *reinterpret_cast(cookie); i-- > 0; ) children[i].~OccluderNode(); ::renddx9abi::engineFree(cookie); } } +// PE 0x100A7F80 LightmapGeneration::LightmapGeneration() : m_refCount(1), m_occluderTree(0), @@ -988,7 +1036,7 @@ LightmapGeneration::LightmapGeneration() m_giLightsBaseDir.x = 0.0f; m_giLightsBaseDir.y = 0.5f; m_giLightsBaseDir.z = -0.5f; m_font = createFontPortedDirect(); - fontPortedLoad(m_font, vc71::string("Fonts/BF1942.font")); // Font::Ported +0x10 + fontPortedLoad(m_font, std::string("Fonts/BF1942.font")); // Font::Ported +0x10 // Two render targets in the default pool, then two system-memory read-back copies. const int savedManaged = dx9rend::textureManagerSwapManaged(0); @@ -1017,13 +1065,13 @@ LightmapGeneration::LightmapGeneration() } // The light marker: a 0.1 m sphere, cloned to a position-only declaration (D3DXMESH_MANAGED). - D3DXCreateSphere(renderDevice(), 0.1f, 20, 20, &m_lightMesh, 0); - IUnknown* clone = 0; - static_cast(m_lightMesh)->CloneMesh(0x220, kLightMeshDeclaration, - renderDevice(), &clone); + D3DXCreateSphere(renderDevice(), 0.1f, 20, 20, reinterpret_cast(&m_lightMesh), 0); + ID3DXMesh* clone = 0; + static_cast(m_lightMesh)->CloneMesh(0x220, kLightMeshDeclaration, + renderDevice(), &clone); m_lightMesh->Release(); m_lightMesh = clone; - LightmapD3dxMesh* const mesh = static_cast(m_lightMesh); + ID3DXMesh* const mesh = static_cast(m_lightMesh); mesh->GetVertexBuffer(&m_lightMeshVertices); mesh->GetIndexBuffer(&m_lightMeshIndices); m_lightMeshVertexCount = mesh->GetNumVertices(); @@ -1031,7 +1079,7 @@ LightmapGeneration::LightmapGeneration() m_lightEffect = static_cast( dx9rend::shaderManagerGetEffect(dx9rend::g_shaderManager, "shaders/LightGeom")); - dx9rend::effectSetTechniqueByName(m_lightEffect, vc71::string("Pointlight")); + dx9rend::effectSetTechniqueByName(m_lightEffect, std::string("Pointlight")); // A two-triangle screen quad of Vec2 positions (written in the default pool). m_quadVertexCount = 6; @@ -1039,12 +1087,12 @@ LightmapGeneration::LightmapGeneration() const int savedPool = dx9rend::bufferManagerSwapPool(0); m_quadBytes = m_quadVertexCount * m_quadStride; m_quadVertexBuffer = dx9rend::createVertexBuffer(dx9rend::g_bufferManager, m_quadVertexCount, - m_quadStride, vc71::string("LightmapGeneration"), + m_quadStride, std::string("LightmapGeneration"), D3DUSAGE_WRITEONLY); dx9rend::bufferManagerSwapPool(savedPool); m_quadEffect = static_cast( dx9rend::shaderManagerGetEffect(dx9rend::g_shaderManager, "shaders/QuadGeom")); - dx9rend::effectSetTechniqueByName(m_quadEffect, vc71::string("TexturedQuad")); + dx9rend::effectSetTechniqueByName(m_quadEffect, std::string("TexturedQuad")); float* const quad = static_cast(dx9rend::vertexBufferLock(m_quadVertexBuffer, 0, 6, 0)); if (!quad) ::renddx9abi::logf("LightmapGeneration.cpp:746: Failed to lock vertex buffer"); @@ -1060,6 +1108,7 @@ LightmapGeneration::LightmapGeneration() // The two effects keep the references the shader manager handed out (shipped); the // tree is destroyed but its pointer left set. +// PE 0x100A8500 LightmapGeneration::~LightmapGeneration() { if (m_occluderTree) @@ -1069,17 +1118,17 @@ LightmapGeneration::~LightmapGeneration() } if (m_font) m_font->release(); - dx9rend::EngineTexture* const textures[4] = - { m_targetTexture, m_targetTexture2, m_sysMemTargetTexture, m_sysMemTargetTexture2 }; - for (int i = 0; i < 4; ++i) - { - dx9rend::EngineTexture* const texture = textures[i]; + const auto releaseTexture = [](dx9rend::EngineTexture* texture) { if (texture && --texture->refCount == 0) { dx9rend::textureDtor(texture); ::renddx9abi::engineFree(texture); } - } + }; + releaseTexture(m_targetTexture); + releaseTexture(m_targetTexture2); + releaseTexture(m_sysMemTargetTexture); + releaseTexture(m_sysMemTargetTexture2); if (m_depthStencil) m_depthStencil->Release(); if (m_lightMeshVertices) @@ -1099,6 +1148,7 @@ void LightmapGeneration::addRef() { ++m_refCount; } int LightmapGeneration::getRef() { return m_refCount; } // Answers the count after the decrement; zero destroys and frees. +// PE 0x100B04E0 int LightmapGeneration::release() { const int count = --m_refCount; @@ -1111,6 +1161,7 @@ int LightmapGeneration::release() } // IBase (1) and IID_ILightmapGeneration answer the object. +// PE 0x100B0490 void* LightmapGeneration::queryInterface(unsigned int iid) const { LightmapGeneration* const self = const_cast(this); @@ -1119,24 +1170,37 @@ void* LightmapGeneration::queryInterface(unsigned int iid) const return iid == kIIDLightmapGeneration ? self : 0; } +// PE 0x100B04C0 void LightmapGeneration::setProgressCallback(LightmapProgressCallback callback, void* user) { m_progressCallback = callback; m_progressUser = user; } +// The 2006 console's accessors. 1.50 keeps the setters (each getter follows its setter in the image) +// without a caller. The owner is attested by RendDX9_r.dll: its onlyNearest, blockSize, sampleOffset, +// shadowsNearCamera, skyColor, ambientColor and giLightColor bindings call the same bodies on the +// published LightmapGeneration singleton (the _r global the singleton creator writes), and the +// written offsets are the generator's fields that the traces read. + +// PE 0x100A63D0 (unreachable in 1.50: no code or data references) void LightmapGeneration::setOnlyNearest(bool value) { m_onlyNearest = value; } bool LightmapGeneration::getOnlyNearest() const { return m_onlyNearest != 0; } +// PE 0x100A63F0 (unreachable in 1.50: no code or data references) void LightmapGeneration::setFirstBlock(int value) { m_firstBlock = value; } int LightmapGeneration::getFirstBlock() const { return m_firstBlock; } +// PE 0x100A6410 (unreachable in 1.50: no code or data references) void LightmapGeneration::setBlockSize(int value) { m_blockSize = value; } int LightmapGeneration::getBlockSize() const { return m_blockSize; } +// PE 0x100A6430 (unreachable in 1.50: no code or data references) void LightmapGeneration::setSampleOffset(float value) { m_sampleOffset = value; } float LightmapGeneration::getSampleOffset() const { return m_sampleOffset; } +// PE 0x100A6450 (unreachable in 1.50: no code or data references) void LightmapGeneration::setShadowsNearCamera(float value) { m_shadowsNearCamera = value; } float LightmapGeneration::getShadowsNearCamera() const { return m_shadowsNearCamera; } // Store, then clamp each component to [0, 1]. +// PE 0x100A68A0 (unreachable in 1.50: no code or data references) void LightmapGeneration::setSkyColor(const Vec3& value) { m_skyColor = value; @@ -1144,6 +1208,7 @@ void LightmapGeneration::setSkyColor(const Vec3& value) m_skyColor.y = clampUnit(m_skyColor.y); m_skyColor.z = clampUnit(m_skyColor.z); } +// PE 0x100A6960 (unreachable in 1.50: no code or data references) void LightmapGeneration::setAmbientColor(const Vec3& value) { m_ambientColor = value; @@ -1151,6 +1216,7 @@ void LightmapGeneration::setAmbientColor(const Vec3& value) m_ambientColor.y = clampUnit(m_ambientColor.y); m_ambientColor.z = clampUnit(m_ambientColor.z); } +// PE 0x100A6A20 (unreachable in 1.50: no code or data references) void LightmapGeneration::setGILightColor(const Vec3& value) { m_giLightColor = value; @@ -1159,6 +1225,8 @@ void LightmapGeneration::setGILightColor(const Vec3& value) m_giLightColor.z = clampUnit(m_giLightColor.z); } +// PE 0x100A86B0 (the temporary LightInfo's render-view reference and vector storage are released +// by its destructor). void LightmapGeneration::pushDefaultLight() { m_lights.push_back(LightInfo()); @@ -1167,6 +1235,7 @@ void LightmapGeneration::pushDefaultLight() // Nothing while a generator exists; otherwise allocate and construct one (a failed // allocation publishes null) and register it as the simple singleton "LightmapGeneration". +// PE 0x100A8700 void createLightmapGenerationSingleton() { if (g_LightmapGeneration) @@ -1177,7 +1246,7 @@ void createLightmapGenerationSingleton() ::renddx9abi::HostString("LightmapGeneration"), g_LightmapGeneration); // ClassManager +0x50 } -// The registration is left in place, as shipped. +// PE 0x100A8770. The registration is left in place, as shipped. void destroyLightmapGenerationSingleton() { if (LightmapGeneration* const generator = g_LightmapGeneration) @@ -1191,83 +1260,19 @@ void destroyLightmapGenerationSingleton() namespace { -// vector::operator=. [CHOSEN, not recovered] storage handling: -// an empty source frees the target, otherwise the target is refilled in order. -void assignRecords(Vc71Vec& to, const Vc71Vec& from) -{ - if (&to == &from) - return; - if (from.size() == 0) - { - to.clear(); - return; - } - to.resize(0); - for (unsigned int i = 0; i < from.size(); ++i) - to.push_back(from[i]); -} - // ObjectManager +0xB4, getAllRegisteredObjects - copied into a TU-local map in key order (the // shipped traceAllObjects copy-constructs it). The retail flavour walks the host's VC7.1 tree // (OverGrowthLoad.cpp's HostObjectWalk over +0x34 is the same walk). -#if !BF2_PLUGIN_ABI_NATIVE -struct HostObjectNode -{ - HostObjectNode* left; // +0x00 - HostObjectNode* parent; // +0x04 - HostObjectNode* right; // +0x08 - unsigned int key; // +0x0C - world::IObject* object; // +0x10 - unsigned char color; // +0x14 - unsigned char isNil; // +0x15 -}; -struct HostObjectMap -{ - void* comp; // +0x00 - HostObjectNode* head; // +0x04 - unsigned int size; // +0x08 -}; - -HostObjectNode* nextNode(HostObjectNode* node) -{ - if (node->isNil) - return node; - HostObjectNode* right = node->right; - if (!right->isNil) - { - while (!right->left->isNil) - right = right->left; - return right; - } - HostObjectNode* parent = node->parent; - while (!parent->isNil && node == parent->right) - { - node = parent; - parent = parent->parent; - } - return parent; -} -#endif void copyRegisteredObjects(std::map& out) { -#if BF2_PLUGIN_ABI_NATIVE out = hostObjectManager()->getAllRegisteredObjects(); -#else - typedef HostObjectMap* (__thiscall* GetAllFn)(void*); - void* const manager = ::dice::hfe::objectManager; - HostObjectMap* const map = - reinterpret_cast((*static_cast(manager))[0xB4 / 4])(manager); - for (HostObjectNode* node = map->head->left; node != map->head; node = nextNode(node)) - out.insert(out.end(), std::make_pair(node->key, node->object)); -#endif } // The registered objects one by one, in key order, without a copy (rebuildOccluders' walk). class RegisteredObjectWalk { public: -#if BF2_PLUGIN_ABI_NATIVE RegisteredObjectWalk() : m_map(hostObjectManager()->getAllRegisteredObjects()), m_it(m_map.begin()) {} bool done() const { return m_it == m_map.end(); } @@ -1276,21 +1281,6 @@ class RegisteredObjectWalk private: const std::map& m_map; std::map::const_iterator m_it; -#else - RegisteredObjectWalk() - { - typedef HostObjectMap* (__thiscall* GetAllFn)(void*); - void* const manager = ::dice::hfe::objectManager; - m_map = reinterpret_cast((*static_cast(manager))[0xB4 / 4])(manager); - m_node = m_map->head->left; - } - bool done() const { return m_node == m_map->head; } - world::IObject* object() const { return m_node->object; } - void next() { m_node = nextNode(m_node); } -private: - HostObjectMap* m_map; - HostObjectNode* m_node; -#endif RegisteredObjectWalk(const RegisteredObjectWalk&); RegisteredObjectWalk& operator=(const RegisteredObjectWalk&); }; @@ -1302,7 +1292,8 @@ class RegisteredObjectWalk // gets four children (new[4]) quartering x and z - the y half extent is multiplied by 0, and each // child then takes the node's own y range - and each child splits the records whose sphere // touches its box (aabbSphereOverlap). Otherwise the node keeps the records. -void LightmapGeneration::splitOccluderNode(const Vc71Vec& records, +// PE 0x100A71A0 +void LightmapGeneration::splitOccluderNode(const std::vector& records, OccluderNode* node, int depth) { aabbCorners(node->corners, &node->bounds.min.x); @@ -1310,7 +1301,7 @@ void LightmapGeneration::splitOccluderNode(const Vc71Vec& recor node->radius = boxRadius(node->bounds); if (!records.data() || records.size() <= 16u || depth >= 11) { - assignRecords(node->records, records); + node->records = records; // vector::operator= return; } @@ -1319,12 +1310,12 @@ void LightmapGeneration::splitOccluderNode(const Vc71Vec& recor const float halfZ = node->bounds.extent.z * 0.5f; const float halfY = node->bounds.extent.y * 0.0f; const float halfX = node->bounds.extent.x * 0.5f; - void* const block = ::renddx9abi::engineAlloc(4 + 4 * sizeof(OccluderNode)); + void* const block = ::renddx9abi::engineAlloc(kChildCountHeader + 4 * sizeof(OccluderNode)); OccluderNode* children = 0; if (block) { *static_cast(block) = 4; - children = reinterpret_cast(static_cast(block) + 1); + children = reinterpret_cast(static_cast(block) + kChildCountHeader); for (int i = 0; i < 4; ++i) new (&children[i]) OccluderNode(); // `eh vector constructor iterator` } @@ -1353,7 +1344,7 @@ void LightmapGeneration::splitOccluderNode(const Vc71Vec& recor } for (int i = 0; i < 4; ++i) { - Vc71Vec inside; + std::vector inside; for (unsigned int r = 0; r < records.size(); ++r) { OccluderRecord* const record = records[r]; @@ -1367,8 +1358,9 @@ void LightmapGeneration::splitOccluderNode(const Vc71Vec& recor // A node's own records are taken unconditionally; a child is entered when the frustum holds its // sphere (Frustum::inside) and its corners (cornersInsideFrustum). The fourth argument is passed // on as 0 and never read. +// PE 0x100A7580 void LightmapGeneration::queryOccluderNode(const Frustum& frustum, OccluderNode* node, - Vc71Vec* out, int unused) + std::vector* out, int unused) { (void)unused; for (unsigned int i = 0; i < node->records.size(); ++i) @@ -1378,7 +1370,7 @@ void LightmapGeneration::queryOccluderNode(const Frustum& frustum, OccluderNode* for (int i = 0; i < 4; ++i) { OccluderNode* const child = &node->children[i]; - if (frustum.inside(child->centre, child->radius) && cornersInsideFrustum(child->corners, frustum)) + if (rendmath::frustumInside(frustum, child->centre, child->radius) && cornersInsideFrustum(child->corners, frustum)) queryOccluderNode(frustum, child, out, 0); } } @@ -1386,9 +1378,10 @@ void LightmapGeneration::queryOccluderNode(const Frustum& frustum, OccluderNode* // The tree's candidates land in a function-local static list (freed at exit) that is emptied, // not freed, on every call; each candidate whose object `out` does not hold yet is appended when // the frustum holds its sphere and its corners. -void LightmapGeneration::occludersInFrustum(const Frustum& frustum, Vc71Vec* out) +// PE 0x100A79C0 +void LightmapGeneration::occludersInFrustum(const Frustum& frustum, std::vector* out) { - static Vc71Vec s_candidates; + static std::vector s_candidates; s_candidates.resize(0); queryOccluderNode(frustum, m_occluderTree, &s_candidates, 0); for (unsigned int i = 0; i < s_candidates.size(); ++i) @@ -1405,16 +1398,77 @@ void LightmapGeneration::occludersInFrustum(const Frustum& frustum, Vc71Veccentre, candidate->radius) + if (rendmath::frustumInside(frustum, candidate->centre, candidate->radius) && cornersInsideFrustum(candidate->corners, frustum)) out->push_back(candidate); } } +// Every record under `node` whose sphere overlaps the query sphere (the squared centre distance less +// the squared sum of the radii is negative; a NaN fails), the node's own records first; a child is +// entered by the same test on its sphere. The object is passed on and never read. +// PE 0x100A7680 (reached only from occludersInSphere, which has no caller in 1.50) +void LightmapGeneration::queryOccluderSphere(OccluderNode* node, const Vec3& position, float radius, + std::vector* out) +{ + const Vec3 centre = position; + for (std::vector::iterator it = node->records.begin(); + it != node->records.end(); ++it) + { + const OccluderRecord* const record = *it; + const float dx = record->centre.x - centre.x; + const float dy = record->centre.y - centre.y; + const float dz = record->centre.z - centre.z; + const float reach = radius + record->radius; + if (dz * dz + dy * dy + dx * dx - reach * reach < 0.0f) + out->push_back(*it); + } + if (!node->children) + return; + for (int i = 0; i < 4; ++i) + { + OccluderNode* const child = &node->children[i]; + const float dx = child->centre.x - centre.x; + const float dy = child->centre.y - centre.y; + const float dz = child->centre.z - centre.z; + const float reach = radius + child->radius; + if (dz * dz + dy * dy + dx * dx - reach * reach < 0.0f) + queryOccluderSphere(child, position, radius, out); + } +} + +// The tree's records near the sphere land in a function-local static list (freed at exit) that is +// emptied, not freed, on every call; each one whose object `out` does not hold yet is appended. +// PE 0x100A7AD0 (unreachable in 1.50: no code or data references) +void LightmapGeneration::occludersInSphere(const Vec3& position, float radius, + std::vector* out) +{ + static std::vector s_candidates; + s_candidates.resize(0); + queryOccluderSphere(m_occluderTree, position, radius, &s_candidates); + for (std::vector::iterator it = s_candidates.begin(); + it != s_candidates.end(); ++it) + { + bool listed = false; + for (std::vector::iterator known = out->begin(); known != out->end(); + ++known) + { + if ((*it)->object == (*known)->object) + { + listed = true; + break; + } + } + if (!listed) + out->push_back(*it); + } +} + // Every record goes into a TU-local ordered map keyed by its squared distance to // `position` less its squared radius (floored at 0); the map is then destroyed and nothing is // written back, so the occluder list keeps its full length (shipped). -void LightmapGeneration::sortOccluders(Vc71Vec* records, const Vec3& position, +// PE 0x100A7BC0 +void LightmapGeneration::sortOccluders(std::vector* records, const Vec3& position, int maxCount) { (void)maxCount; @@ -1435,7 +1489,8 @@ void LightmapGeneration::sortOccluders(Vc71Vec* records, const // The root is replaced (a failed allocation publishes null); with records, its box // starts at +-9999999 and grows over every record sphere's two extreme corners, then the root is // split over m_occluderList (the argument only feeds the box). -void LightmapGeneration::buildOccluderTree(Vc71Vec* records) +// PE 0x100A78C0 +void LightmapGeneration::buildOccluderTree(std::vector* records) { void* const storage = ::renddx9abi::engineAlloc(sizeof(OccluderNode)); m_occluderTree = storage ? new (storage) OccluderNode() : 0; @@ -1463,7 +1518,8 @@ void LightmapGeneration::buildOccluderTree(Vc71Vec* records) splitOccluderNode(m_occluderList, m_occluderTree, 0); } -void LightmapGeneration::addOccluder(world::IObject* object, Vc71Vec* records) +// PE 0x100A7C90 +void LightmapGeneration::addOccluder(world::IObject* object, std::vector* records) { if (!object) return; @@ -1480,6 +1536,7 @@ void LightmapGeneration::addOccluder(world::IObject* object, Vc71Vec& objects = hostObjectManager()->getObjectTempVector(); // +0xA8 + hostObjectManager()->getObjectsFromGrid(centre, radius, objects, 0); // +0x44 + for (std::vector::iterator it = objects.begin(); it != objects.end(); ++it) + { + world::IObject* const object = *it; + // shipped: the flag word is read before the null test + if ((world::object_detail::LayoutAccess::flags(object) & world::IObject::OFHasGrid) + && object != exclude->object && object) + addOccluder(object, &m_occluders); + } + for (unsigned int i = 0; i < m_occluders.size(); ++i) + m_occluderList.push_back(&m_occluders[i]); + buildOccluderTree(&m_occluderList); +} + // Scene lights from the light manager (getLightsByMask 0x1F15): enabled lights whose // root is enabled. A directional light becomes a reversed-direction view of 500 m (the template @@ -1514,15 +1598,12 @@ void LightmapGeneration::rebuildOccluders() // `bounds` (its y range widened to -9999..9999) become local lights. Then the GI lights: a top light // for one GI light or useGITopLight, and a ring of numberOfGILights around the sky light's azimuth. // The scene lights are appended through the published generator's last light (lastLight). +// PE 0x100A87A0 void LightmapGeneration::gatherLights(TerrainAabb* bounds) { - vc71::vector_layout lights; - lights.first = 0; - lights.last = 0; - lights.end = 0; + std::vector lights; g_LightManager->getLightsByMask(lights, 0x1F15u, 0u); // +0x14 - for (world::LightSource** it = reinterpret_cast(lights.first); - it != reinterpret_cast(lights.last); ++it) + for (world::LightSource** it = lights.data(); it != lights.data() + lights.size(); ++it) { world::LightSource* const light = *it; const world::LightSourceTemplate* const tmpl = lightSourceTemplatePointer(light); @@ -1582,7 +1663,7 @@ void LightmapGeneration::gatherLights(TerrainAabb* bounds) info->intensity = tmpl->getIntensity(); info->viewDistance = 500.0f; info->softness = tmpl->getSoftness(); - const vc71::string sunlight("sunlight"); + const std::string sunlight("sunlight"); const bool isSun = _stricmp(fromHostStdString(tmpl->getName()).c_str(), sunlight.c_str()) == 0; if (isSun) @@ -1645,8 +1726,6 @@ void LightmapGeneration::gatherLights(TerrainAabb* bounds) } } } - if (lights.first) - ::renddx9abi::engineFree(lights.first); } @@ -1655,13 +1734,14 @@ void LightmapGeneration::gatherLights(TerrainAabb* bounds) // an ASSERT line came since the last status line; "failed!" or a pending ASSERT reopen it for // tracing - and close the scan's file twice (shipped). Then "Rendering object " or the // record's done!/failed! line is appended; the append's fopen is not checked (shipped). +// PE 0x100A6C50 bool LightmapGeneration::updateResumeLog(OccluderRecord* record, bool succeeded, bool starting) { if (m_logPath.empty()) return true; - vc71::string name(""); + std::string name(""); if (record && record->object) - name = fromHostStdString(objectTemplatePointer(record->object)->getName()).c_str(); // +0x28 + name = fromHostStdString(objectTemplatePointer(record->object)->getName()); // +0x28 if (starting) { @@ -1729,6 +1809,7 @@ bool LightmapGeneration::updateResumeLog(OccluderRecord* record, bool succeeded, } +// PE 0x100ADBE0 bool LightmapGeneration::traceRecord(OccluderRecord* record, int objectIndex, int objectCount, int block) { @@ -1749,6 +1830,7 @@ bool LightmapGeneration::traceRecord(OccluderRecord* record, int objectIndex, in return traceColour(record, objectIndex, objectCount, block); } +// PE 0x100ADC60 bool LightmapGeneration::traceTerrain(int patch) { if (m_enableIntensityLightmaps) @@ -1759,6 +1841,7 @@ bool LightmapGeneration::traceTerrain(int patch) // Geoms (+0x74 count, +0x6C select) and their lods (+0x80 count, +0x78 select) are // walked from the last; a lightmapOverride template skips the (geom, lod) pairs whose lightmap // size is 0. +// PE 0x100ADCA0 bool LightmapGeneration::traceObjectRecord(OccluderRecord* record, int objectIndex, int objectCount, int block) { @@ -1789,6 +1872,7 @@ bool LightmapGeneration::traceObjectRecord(OccluderRecord* record, int objectInd // The registered objects are copied, the ones without a sampleable geometry removed, // and the rest traced in key order with their index and the remaining count; a callback abort // stops after the current object. Always true. +// PE 0x100ADDA0 bool LightmapGeneration::traceAllObjects() { g_traceAborted = false; @@ -1832,6 +1916,7 @@ bool LightmapGeneration::traceAllObjects() return true; } +// PE 0x100ADF60 bool LightmapGeneration::traceActiveObjectProgress(int index, int count) { OccluderRecord record; @@ -1842,6 +1927,7 @@ bool LightmapGeneration::traceActiveObjectProgress(int index, int count) } // The object the name hash finds (ObjectManager +0x24). +// PE 0x100ADFD0 (only the name lookup differs from the active-object arm) bool LightmapGeneration::traceObject(const LightmapGenerationString& name) { OccluderRecord record; @@ -1857,6 +1943,7 @@ bool LightmapGeneration::traceActiveObject() return traceActiveObjectProgress(-1, -1); } +// PE 0x100A8DD0. // The colour trace (enableIntensityLightmaps 0). `record` null traces the terrain (block -1: every // block from m_firstBlock - 1, or the camera's block with onlyNearest); otherwise the record's // geometry in its current (geom, lod). A missing terrain or ITerrainEditable fails it. Per batch, @@ -1923,7 +2010,8 @@ bool LightmapGeneration::traceColour(OccluderRecord* record, int objectIndex, in const unsigned int capacity = 0x100000u / (static_cast(m_blockSize) * static_cast(m_blockSize)) + 1; LightSample* samples = 0; - if (void* const storage = ::renddx9abi::engineAlloc(144 * capacity)) + if (void* const storage = ::renddx9abi::engineAlloc( + static_cast(3 * sizeof(LightSample)) * capacity)) // 144 * capacity { samples = static_cast(storage); for (unsigned int i = 0; i < 3 * capacity; ++i) @@ -1938,7 +2026,7 @@ bool LightmapGeneration::traceColour(OccluderRecord* record, int objectIndex, in dx9rend::IRenderView* const savedViewDup = renderer()->getRenderViewDup(); // +0x50 unsigned int firstBlock = static_cast(m_firstBlock - 1); unsigned int occluderPeak = 0; - Vc71Vec occluders; + std::vector occluders; unsigned int totalSamples = 0; const Vec3& cameraPosition = *reinterpret_cast(&savedView->getViewMatrixPtr()->m[12]); if (block != -1) @@ -1951,9 +2039,7 @@ bool LightmapGeneration::traceColour(OccluderRecord* record, int objectIndex, in Vec3 relative; if (record) { - relative.x = cameraPosition.x - record->position.x; - relative.y = cameraPosition.y - record->position.y; - relative.z = cameraPosition.z - record->position.z; + relative = rendmath::minus(cameraPosition, record->position); // PE 0x100793F0 } firstBlock = nearestBlock(record ? relative : cameraPosition, sampler); totalSamples = sampler->getBlock(firstBlock).sampleCount; @@ -2061,7 +2147,7 @@ bool LightmapGeneration::traceColour(OccluderRecord* record, int objectIndex, in else { const Vec3 up = { 0.0f, 1.0f, 0.0f }; - lookAt(view, Vec3::getZero(), light->direction, up); + rendmath::calcLookAtMatrix(view, rendmath::zeroVector(), light->direction, up); } light->renderView->setViewMatrix(view.m); // +0x60 directionalSeen = true; @@ -2114,7 +2200,7 @@ bool LightmapGeneration::traceColour(OccluderRecord* record, int objectIndex, in if (m_noPhongAngle) results[slot] = facingLight > 0.1f ? 1.0f : 0.0f; else - results[slot] = clampUnit(responseCurve(m_phongAngleMode, facingLight)); + results[slot] = storeResponse(clampResponse(responseCurve(m_phongAngleMode, facingLight))); // The sample's tile of the target. rendered = true; @@ -2136,15 +2222,15 @@ bool LightmapGeneration::traceColour(OccluderRecord* record, int objectIndex, in if (m_noPhongAngle) results[slot] = attenuation; else - results[slot] = clampUnit(responseCurve( + results[slot] = storeResponse(clampResponse(responseCurve( m_phongAngleMode, (toLightY * sample.normal.y + toLightZ * sample.normal.z) - + toLightX * sample.normal.x)) * attenuation; + + toLightX * sample.normal.x)), attenuation); const Vec3 target = { toLightX + sample.position.x, toLightY + sample.position.y, toLightZ + sample.position.z }; const Vec3 up = { 0.0f, 1.0f, 0.0f }; - lookAt(view, sample.position, target, up); + rendmath::calcLookAtMatrix(view, sample.position, target, up); } else { @@ -2197,13 +2283,13 @@ bool LightmapGeneration::traceColour(OccluderRecord* record, int objectIndex, in lightSourceTemplatePointer(light->source); if (tmpl->getLightTypeEnum() == 1) dx9rend::effectSetTechniqueByName(m_lightEffect, - vc71::string("Pointlight")); + std::string("Pointlight")); else if (tmpl->getLightTypeEnum() == 2) { float coneAngle = light->source->getConeAngleRads2(); // +0x1C0 Mat4 basis = light->source->getAbsoluteTransformation(); const Mat4 copy = basis; - mat4Transpose(basis, copy); + rendmath::setTranspose(basis, copy); const Vec3& direction = light->source->getAbsoluteDirection(); // +0x180 const float* const m = basis.m; Vec3 spotDirection; @@ -2214,13 +2300,13 @@ bool LightmapGeneration::traceColour(OccluderRecord* record, int objectIndex, in spotDirection.z = (m[2] * direction.x + m[10] * direction.z) + m[6] * direction.y; dx9rend::effectSetTechniqueByName(m_lightEffect, - vc71::string("Spotlight")); + std::string("Spotlight")); dx9rend::effectGetShaderParameterBorrowedTyped( - m_lightEffect, vc71::string("WorldView"))->setValue(&worldView, 0); + m_lightEffect, std::string("WorldView"))->setValue(&worldView, 0); dx9rend::effectGetShaderParameterBorrowedTyped( - m_lightEffect, vc71::string("SpotDir"))->setValue(&spotDirection, 0); + m_lightEffect, std::string("SpotDir"))->setValue(&spotDirection, 0); dx9rend::effectGetShaderParameterBorrowedTyped( - m_lightEffect, vc71::string("ConeAngle"))->setValue(&coneAngle, 0); + m_lightEffect, std::string("ConeAngle"))->setValue(&coneAngle, 0); } // The scale replaces the WorldView diagonal (shipped). worldView.m[0] = light->source->getScale().x; // +0x1D4 @@ -2229,12 +2315,15 @@ bool LightmapGeneration::traceColour(OccluderRecord* record, int objectIndex, in mat4Mult(worldViewProjection, worldView, *light->renderView->getProjectionMatrixPtr()); // +0x6C dx9rend::effectGetShaderParameterBorrowedTyped( - m_lightEffect, vc71::string("WorldViewProj")) + m_lightEffect, std::string("WorldViewProj")) ->setValue(&worldViewProjection, 0); const Vec3& colour = light->source->getColor(); - const float lightColour[4] = { colour.x, colour.y, colour.z, 1.0f }; + // 0x1008DD80 inlined (0x100AA12F..0x100AA1BB): the pack writes the + // shared static (dword_1024B100) and the local copy handed on. + const float* const packed = staticMeshPackVec4(&colour.x, 1.0f); + const float lightColour[4] = { packed[0], packed[1], packed[2], packed[3] }; dx9rend::effectGetShaderParameterBorrowedTyped( - m_lightEffect, vc71::string("LightColor"))->setValue(lightColour, 0); + m_lightEffect, std::string("LightColor"))->setValue(lightColour, 0); dx9rend::stateManagerSetStreamSource(0, m_lightMeshVertices, 0, 12); dx9rend::stateManagerSetIndices(m_lightMeshIndices); dx9rend::effectBegin(m_lightEffect); @@ -2254,9 +2343,9 @@ bool LightmapGeneration::traceColour(OccluderRecord* record, int objectIndex, in if (m_quadVertexBuffer) { dx9rend::stateManagerPush(); - dx9rend::effectSetTechniqueByName(m_quadEffect, vc71::string("TexturedQuad")); + dx9rend::effectSetTechniqueByName(m_quadEffect, std::string("TexturedQuad")); dx9rend::effectGetShaderParameterBorrowedTyped( - m_quadEffect, vc71::string("TEXLAYER0"))->setValue(m_targetTexture, 0); + m_quadEffect, std::string("TEXLAYER0"))->setValue(m_targetTexture, 0); dx9rend::vertexBufferBindStream(m_quadVertexBuffer, 0); dx9rend::effectBegin(m_quadEffect); dx9rend::effectBeginPass(m_quadEffect, 0); @@ -2411,12 +2500,12 @@ bool LightmapGeneration::traceColour(OccluderRecord* record, int objectIndex, in { LightmapGenerationProgress progress; progress.percentDone = percent; - vc71::string total; - vc71::string left; - vc71::string line; + std::string total; + std::string left; + std::string line; if (objectIndex != -1 && objectCount != -1) { - vc71::string head; + std::string head; formatString(head, "Object %d/%d :", objectIndex + 1, objectCount); formatTime(total, static_cast( static_cast(g_system->getWallClockTime()))); @@ -2447,7 +2536,7 @@ bool LightmapGeneration::traceColour(OccluderRecord* record, int objectIndex, in const unsigned int white[3] = { 255, 255, 255 }; renderer()->beginScene(white, 1); // +0xC8 float y = 30.0f; - vc71::string text; + std::string text; formatString(text, "%.2f%% Lights:%d", static_cast(percent), m_lights.size()); fontPortedDrawText(m_font, 50.0f, 30.0f, text); @@ -2475,8 +2564,8 @@ bool LightmapGeneration::traceColour(OccluderRecord* record, int objectIndex, in static_cast(static_cast(count) * rate)); fontPortedDrawText(m_font, 50.0f, y, text); y = y + 40.0f; - vc71::string total; - vc71::string left; + std::string total; + std::string left; formatTime(total, static_cast( static_cast(g_system->getWallClockTime()))); formatTime(left, static_cast(static_cast(remainingSeconds))); @@ -2514,6 +2603,7 @@ bool LightmapGeneration::traceColour(OccluderRecord* record, int objectIndex, in return sampleable->destroyLightSampler(sampler); } +// PE 0x100AB3C0. // The intensity trace. `record` null traces the terrain (block -1: every block from // m_firstBlock - 1, or the camera's block with onlyNearest); otherwise the record's geometry in its // current (geom, lod). Per block: the block's lights are gathered and per-triangle back-face bits @@ -2582,7 +2672,8 @@ bool LightmapGeneration::traceIntensity(OccluderRecord* record, int objectIndex, const unsigned int capacity = 0x100000u / (static_cast(m_blockSize) * static_cast(m_blockSize)) + 1; LightSample* samples = 0; - if (void* const storage = ::renddx9abi::engineAlloc(144 * capacity)) + if (void* const storage = ::renddx9abi::engineAlloc( + static_cast(3 * sizeof(LightSample)) * capacity)) // 144 * capacity { samples = static_cast(storage); for (unsigned int i = 0; i < 3 * capacity; ++i) @@ -2597,7 +2688,7 @@ bool LightmapGeneration::traceIntensity(OccluderRecord* record, int objectIndex, dx9rend::IRenderView* const savedViewDup = renderer()->getRenderViewDup(); // +0x50 unsigned int firstBlock = static_cast(m_firstBlock - 1); unsigned int occluderPeak = 0; - Vc71Vec occluders; + std::vector occluders; unsigned int totalSamples = 0; const Vec3& cameraPosition = *reinterpret_cast(&savedView->getViewMatrixPtr()->m[12]); if (block != -1) @@ -2610,9 +2701,7 @@ bool LightmapGeneration::traceIntensity(OccluderRecord* record, int objectIndex, Vec3 relative; if (record) { - relative.x = cameraPosition.x - record->position.x; - relative.y = cameraPosition.y - record->position.y; - relative.z = cameraPosition.z - record->position.z; + relative = rendmath::minus(cameraPosition, record->position); // PE 0x100793F0 } firstBlock = nearestBlock(record ? relative : cameraPosition, sampler); totalSamples = sampler->getBlock(firstBlock).sampleCount; @@ -2658,13 +2747,13 @@ bool LightmapGeneration::traceIntensity(OccluderRecord* record, int objectIndex, // Per light: a back-face bit per sampler triangle (the terrain has none - one clear bit), // and each local light's index in the sampler (the table is never freed - shipped). - const vc71::vector_layout* const triangleVector = - static_cast(blockInfo.triangles); + const std::vector* const triangleVector = + static_cast*>(blockInfo.triangles); int triangleCount = 0; - if (triangleVector && triangleVector->first) - triangleCount = static_cast((triangleVector->last - triangleVector->first) / 92); - const SampleTriangle* const triangles = triangleVector - ? reinterpret_cast(triangleVector->first) : 0; + if (triangleVector && !triangleVector->empty()) + triangleCount = static_cast(triangleVector->size()); + const MeshSampleTriangle* const triangles = triangleVector + ? triangleVector->data() : 0; int* lightIndex = static_cast(::renddx9abi::engineAlloc(4 * m_lights.size())); for (unsigned int l = 0; l < m_lights.size(); ++l, ++lightIndex) { @@ -2793,7 +2882,7 @@ bool LightmapGeneration::traceIntensity(OccluderRecord* record, int objectIndex, else { const Vec3 up = { 0.0f, 1.0f, 0.0f }; - lookAt(view, Vec3::getZero(), light->direction, up); + rendmath::calcLookAtMatrix(view, rendmath::zeroVector(), light->direction, up); } light->renderView->setViewMatrix(view.m); // +0x60 if (!light->isGI && !light->isLocal) @@ -2855,7 +2944,7 @@ bool LightmapGeneration::traceIntensity(OccluderRecord* record, int objectIndex, if (m_noPhongAngle) results[slot] = facingLight > 0.1f ? 1.0f : 0.0f; else - results[slot] = clampUnit(responseCurve(m_phongAngleMode, facingLight)); + results[slot] = storeResponse(clampResponse(responseCurve(m_phongAngleMode, facingLight))); // The sample's tile of the target. setViewport((slot % tilesPerRow) * tileSize, (slot / tilesPerRow) * tileSize, @@ -2877,15 +2966,15 @@ bool LightmapGeneration::traceIntensity(OccluderRecord* record, int objectIndex, if (m_noPhongAngle) results[slot] = attenuation; else - results[slot] = attenuation * clampUnit(responseCurve( + results[slot] = storeResponse(clampResponse(responseCurve( m_phongAngleMode, (sample.normal.x * toLightX + toLightZ * sample.normal.z) - + toLightY * sample.normal.y)); + + toLightY * sample.normal.y)), attenuation); const Vec3 target = { sample.position.x + toLightX, toLightY + sample.position.y, toLightZ + sample.position.z }; const Vec3 up = { 0.0f, 1.0f, 0.0f }; - lookAt(view, sample.position, target, up); + rendmath::calcLookAtMatrix(view, sample.position, target, up); } else { @@ -2936,13 +3025,13 @@ bool LightmapGeneration::traceIntensity(OccluderRecord* record, int objectIndex, lightSourceTemplatePointer(light->source); if (tmpl->getLightTypeEnum() == 1) dx9rend::effectSetTechniqueByName(m_lightEffect, - vc71::string("Pointlight")); + std::string("Pointlight")); else if (tmpl->getLightTypeEnum() == 2) { float coneAngle = light->source->getConeAngleRads2(); // +0x1C0 Mat4 basis = light->source->getAbsoluteTransformation(); const Mat4 copy = basis; - mat4Transpose(basis, copy); + rendmath::setTranspose(basis, copy); const Vec3& direction = light->source->getAbsoluteDirection(); // +0x180 const float* const m = basis.m; Vec3 spotDirection; @@ -2953,13 +3042,13 @@ bool LightmapGeneration::traceIntensity(OccluderRecord* record, int objectIndex, spotDirection.z = (m[2] * direction.x + m[10] * direction.z) + m[6] * direction.y; dx9rend::effectSetTechniqueByName(m_lightEffect, - vc71::string("Spotlight")); + std::string("Spotlight")); dx9rend::effectGetShaderParameterBorrowedTyped( - m_lightEffect, vc71::string("WorldView"))->setValue(&worldView, 0); + m_lightEffect, std::string("WorldView"))->setValue(&worldView, 0); dx9rend::effectGetShaderParameterBorrowedTyped( - m_lightEffect, vc71::string("SpotDir"))->setValue(&spotDirection, 0); + m_lightEffect, std::string("SpotDir"))->setValue(&spotDirection, 0); dx9rend::effectGetShaderParameterBorrowedTyped( - m_lightEffect, vc71::string("ConeAngle"))->setValue(&coneAngle, 0); + m_lightEffect, std::string("ConeAngle"))->setValue(&coneAngle, 0); } // The scale replaces the WorldView diagonal (shipped). worldView.m[0] = light->source->getScale().x; // +0x1D4 @@ -2968,12 +3057,15 @@ bool LightmapGeneration::traceIntensity(OccluderRecord* record, int objectIndex, mat4Mult(worldViewProjection, worldView, *light->renderView->getProjectionMatrixPtr()); // +0x6C dx9rend::effectGetShaderParameterBorrowedTyped( - m_lightEffect, vc71::string("WorldViewProj")) + m_lightEffect, std::string("WorldViewProj")) ->setValue(&worldViewProjection, 0); const Vec3& colour = light->source->getColor(); - const float lightColour[4] = { colour.x, colour.y, colour.z, 1.0f }; + // 0x1008DD80 (call at 0x100ACA68): the pack writes the shared static + // (dword_1024B100), copied into the local handed on. + const float* const packed = staticMeshPackVec4(&colour.x, 1.0f); + const float lightColour[4] = { packed[0], packed[1], packed[2], packed[3] }; dx9rend::effectGetShaderParameterBorrowedTyped( - m_lightEffect, vc71::string("LightColor"))->setValue(lightColour, 0); + m_lightEffect, std::string("LightColor"))->setValue(lightColour, 0); dx9rend::stateManagerSetStreamSource(0, m_lightMeshVertices, 0, 12); dx9rend::stateManagerSetIndices(m_lightMeshIndices); dx9rend::effectBegin(m_lightEffect); @@ -3160,12 +3252,12 @@ bool LightmapGeneration::traceIntensity(OccluderRecord* record, int objectIndex, { LightmapGenerationProgress progress; progress.percentDone = percent; - vc71::string total; - vc71::string left; - vc71::string line; + std::string total; + std::string left; + std::string line; if (objectIndex != -1 && objectCount != -1) { - vc71::string head; + std::string head; formatString(head, "Object %d/%d :", objectIndex + 1, objectCount); formatTime(total, static_cast( static_cast(g_system->getWallClockTime()))); @@ -3196,7 +3288,7 @@ bool LightmapGeneration::traceIntensity(OccluderRecord* record, int objectIndex, const unsigned int white[3] = { 255, 255, 255 }; renderer()->beginScene(white, 1); // +0xC8 float y = 30.0f; - vc71::string text; + std::string text; formatString(text, "%.2f%% Lights:%d", static_cast(percent), m_lights.size()); fontPortedDrawText(m_font, 50.0f, 30.0f, text); @@ -3224,8 +3316,8 @@ bool LightmapGeneration::traceIntensity(OccluderRecord* record, int objectIndex, static_cast(static_cast(count) * rate)); fontPortedDrawText(m_font, 50.0f, y, text); y = y + 40.0f; - vc71::string total; - vc71::string left; + std::string total; + std::string left; formatTime(total, static_cast( static_cast(g_system->getWallClockTime()))); formatTime(left, static_cast(static_cast(remainingSeconds))); diff --git a/Code/BF2/Geom/LightmapGeneration/LightmapGeneration.h b/Code/BF2/Geom/LightmapGeneration/LightmapGeneration.h index adf9683ac..5da42d299 100644 --- a/Code/BF2/Geom/LightmapGeneration/LightmapGeneration.h +++ b/Code/BF2/Geom/LightmapGeneration/LightmapGeneration.h @@ -17,12 +17,12 @@ #include "ILightmapGeneration.h" #include "ILightSampling.h" #include "../QuadPatch.h" // TerrainAabb -#include "../UndergrowthSystem.h" // Vc71Vec - the renderer's owning VC7.1-layout vector #include "../../Math/Mat4.h" #include "../../Math/Vec3.h" -#include "../../../RendDX9Abi/Vc71String.h" +#include #include +#include struct IUnknown; struct IDirect3DSurface9; @@ -40,13 +40,13 @@ namespace geom { class ILightSampleable; -// A light's per-triangle back-face bits: VC7.1 std::vector, the bit count ahead of the words. -// [CHOSEN, not recovered] a local copyable form (Vc71BoolVector.h disables copying, and the light -// records are copied by value). +// A light's per-triangle back-face bits: the shipped std::vector, the bit count ahead of the +// words. [CHOSEN, not recovered] a local copyable form over std::vector words (the +// light records are copied by value). struct LightFacingBits { - unsigned int size; // +0x00 _Mysize - the destructor zeroes it - Vc71Vec words; // +0x04 _Myvec + unsigned int size; // +0x00 _Mysize - the destructor zeroes it + std::vector words; // +0x04 _Myvec LightFacingBits() : size(0) {} LightFacingBits(const LightFacingBits& other) : size(other.size), words(other.words) {} @@ -143,7 +143,7 @@ struct OccluderNode Vec3 centre; // +0x9C the bounds' centre (refreshed) float radius; // +0xA8 the bounds' radius (refreshed) OccluderNode* children; // +0xAC new[4], or null for a leaf - Vc71Vec records; // +0xB0 (first at +0xB4) the leaf's records + std::vector records; // +0xB0 (first at +0xB4) the leaf's records private: OccluderNode(const OccluderNode&); @@ -214,27 +214,35 @@ class LightmapGeneration : public ILightmapGeneration void gatherLights(TerrainAabb* bounds); // Every registered object's record, the pointer list, and the quadtree over it. void rebuildOccluders(); + // rebuildOccluders over the host grid's objects within `radius` of `centre`, without + // `exclude`'s object. No caller in 1.50. + void rebuildNearbyOccluders(const OccluderRecord* exclude, const Vec3& centre, float radius); // Appends `object`'s record unless it (or its root) moves. - void addOccluder(world::IObject* object, Vc71Vec* records); + void addOccluder(world::IObject* object, std::vector* records); // A new root bounding every record's sphere, split over m_occluderList. - void buildOccluderTree(Vc71Vec* records); + void buildOccluderTree(std::vector* records); // Quarters `node` while it holds more than 16 records, 11 levels deep at most. - void splitOccluderNode(const Vc71Vec& records, OccluderNode* node, int depth); + void splitOccluderNode(const std::vector& records, OccluderNode* node, int depth); // Every record under `node` whose subtree the frustum may see. void queryOccluderNode(const Frustum& frustum, OccluderNode* node, - Vc71Vec* out, int unused); + std::vector* out, int unused); + // Every record under `node` whose sphere overlaps the sphere (position, radius). + void queryOccluderSphere(OccluderNode* node, const Vec3& position, float radius, + std::vector* out); + // The quadtree's records near the sphere, each object once. No caller in 1.50. + void occludersInSphere(const Vec3& position, float radius, std::vector* out); // The visible records of the quadtree, each object once. - void occludersInFrustum(const Frustum& frustum, Vc71Vec* out); + void occludersInFrustum(const Frustum& frustum, std::vector* out); // Builds a distance-ordered map of `records` and drops it again (shipped: the list is never // trimmed to `maxCount`). - void sortOccluders(Vc71Vec* records, const Vec3& position, int maxCount); + void sortOccluders(std::vector* records, const Vec3& position, int maxCount); // data, in shipped order (the vptr is +0x00) int m_refCount; // +0x004 1 - Vc71Vec m_occluders; // +0x008 (first at +0x00C) - Vc71Vec m_occluderList; // +0x018 (first at +0x01C) + std::vector m_occluders; // +0x008 (first at +0x00C) + std::vector m_occluderList; // +0x018 (first at +0x01C) OccluderNode* m_occluderTree; // +0x028 rebuilt by a trace when null - Vc71Vec m_lights; // +0x02C (first at +0x030) + std::vector m_lights; // +0x02C (first at +0x030) Vec3 m_skyColor; // +0x03C 0.3 Vec3 m_ambientColor; // +0x048 0.3 float m_resolutionModifier; // +0x054 1 @@ -294,7 +302,7 @@ class LightmapGeneration : public ILightmapGeneration unsigned char pad122[2]; int m_lightmapFormat; // +0x124 1 = DXT1, else DXT5 float m_skyWhite; // +0x128 0 - vc71::string m_logPath; // +0x12C the resume log ("" = none), 2006 `useLog` + std::string m_logPath; // +0x12C the resume log ("" = none), 2006 `useLog` // +0x148 - 0.8 from the constructor; each intensity trace resets it and a terrain trace raises it // to the largest sun channel of a sample whose normal is straight up (the terrain sampler gives // water exactly that normal). The 2006 editor read the same field through its @@ -307,7 +315,6 @@ class LightmapGeneration : public ILightmapGeneration }; #if defined(_M_IX86) -static_assert(sizeof(LightInfo) == 100, "a light record is 100 bytes - see the /100 at 0x100A7150"); static_assert(offsetof(LightInfo, source) == 0x14, "light source at +0x14"); static_assert(offsetof(LightInfo, direction) == 0x18, "light direction at +0x18"); static_assert(offsetof(LightInfo, maxOccluders) == 0x3C, "occluder cap at +0x3C"); @@ -316,25 +323,9 @@ static_assert(offsetof(LightInfo, facing) == 0x50, "back-face bits at +0x50"); static_assert(sizeof(OccluderRecord) == 196, "an occluder record is 196 bytes - see 0x100A7D00"); static_assert(offsetof(OccluderRecord, centre) == 0x50, "record centre at +0x50"); static_assert(offsetof(OccluderRecord, geometry) == 0xC0, "record geometry at +0xC0"); -static_assert(sizeof(OccluderNode) == 0xC0, "a quadtree node is 0xC0 bytes - see 0x100A78C3"); static_assert(offsetof(OccluderNode, centre) == 0x9C, "node centre at +0x9C"); static_assert(offsetof(OccluderNode, children) == 0xAC, "node children at +0xAC"); static_assert(offsetof(LightmapGeneration, m_occluders) == 0x008, "+0x008"); -static_assert(offsetof(LightmapGeneration, m_occluderList) == 0x018, "+0x018"); -static_assert(offsetof(LightmapGeneration, m_occluderTree) == 0x028, "+0x028"); -static_assert(offsetof(LightmapGeneration, m_lights) == 0x02C, "+0x02C"); -static_assert(offsetof(LightmapGeneration, m_resolutionModifier) == 0x054, "resolution modifier at +0x54 - see 0x100AB507"); -static_assert(offsetof(LightmapGeneration, m_blockSize) == 0x068, "+0x068"); -static_assert(offsetof(LightmapGeneration, m_generationMethod) == 0x074, "+0x074"); -static_assert(offsetof(LightmapGeneration, m_font) == 0x088, "+0x088"); -static_assert(offsetof(LightmapGeneration, m_quadVertexBuffer) == 0x0D0, "+0x0D0"); -static_assert(offsetof(LightmapGeneration, m_progressCallback) == 0x0D4, "+0x0D4 - see 0x100B04C9"); -static_assert(offsetof(LightmapGeneration, m_numberOfGILights) == 0x0E0, "+0x0E0"); -static_assert(offsetof(LightmapGeneration, m_sunLightFov) == 0x11C, "+0x11C"); -static_assert(offsetof(LightmapGeneration, m_lightmapFormat) == 0x124, "+0x124 - see 0x10199BD5"); -static_assert(offsetof(LightmapGeneration, m_logPath) == 0x12C, "+0x12C"); -static_assert(offsetof(LightmapGeneration, m_waterSunIntensity) == 0x148, "+0x148"); -static_assert(sizeof(LightmapGeneration) == 0x14C, "the creator allocates 0x14C - see 0x100A870F"); #endif // The singleton the creator makes; the terrain sampler's lightmap writer reads its format. @@ -345,9 +336,7 @@ extern LightmapGeneration* g_LightmapGeneration; // binding calls it. void createLightmapGenerationSingleton(); // Destroys the singleton (null-safe) and clears the global. The simple-singleton registration is -// left in place, as shipped. The shipped caller is the renderer's Direct3D subsystem shutdown, which -// Renderer::shutdown (BF2Render.cpp, still a [FRONTIER]) runs; until that body exists, nothing calls -// this. +// left in place, as shipped. Called by the renderer's Direct3D subsystem shutdown (PE 0x1000ADB0). void destroyLightmapGenerationSingleton(); } // namespace geom diff --git a/Code/BF2/Geom/LightmapGeneration/LightmapGenerationConsole.cpp b/Code/BF2/Geom/LightmapGeneration/LightmapGenerationConsole.cpp index d4dd766cf..fdb2ce8cd 100644 --- a/Code/BF2/Geom/LightmapGeneration/LightmapGenerationConsole.cpp +++ b/Code/BF2/Geom/LightmapGeneration/LightmapGenerationConsole.cpp @@ -15,7 +15,7 @@ #include "../../../RendDX9Abi/PluginAbi.h" -#if BF2_PLUGIN_ABI_NATIVE && defined(BF2_IMAGE_EDITOR) && BF2_IMAGE_EDITOR +#if defined(BF2_IMAGE_EDITOR) && BF2_IMAGE_EDITOR #include "LightmapGeneration.h" #include "../../Core/ConsoleObjectMacro.h" diff --git a/Code/BF2/Geom/LightmapGeneration/MeshLightSampling.cpp b/Code/BF2/Geom/LightmapGeneration/MeshLightSampling.cpp index 81a0e2fe4..38b0fea46 100644 --- a/Code/BF2/Geom/LightmapGeneration/MeshLightSampling.cpp +++ b/Code/BF2/Geom/LightmapGeneration/MeshLightSampling.cpp @@ -1,12 +1,15 @@ // The mesh light sampler (MeshLightSampling.h), recovered from RendDX9.dll 1.50. The three record -// vectors are the renderer's VC7.1-layout Vc71Vec (RW-74): the generator reads the triangle vector -// through LightSampleBlock::triangles. +// vectors are std::vectors: the generator reads the triangle vector through +// LightSampleBlock::triangles. // Shipped defects kept: storeResults addresses texels by sample index (no pitch); the destructor // reads the lightmap format before testing for a texture, leaks both level surfaces of its // conversion copy and dereferences a failed conversion texture; the grid halving strides rows by // twice the new width; a resolution modifier of zero or below never ends the loader's halving. #ifdef BF2_IMAGE_RENDDX9 +#if defined(__APPLE__) +#include "../../Platform/X87Compat.h" // [CHOSEN, not recovered] x87 conversion results, including invalid inputs. +#endif #include "MeshLightSampling.h" #include "LightmapGeneration.h" // g_LightmapGeneration - format and trace mode #include "../XpLightManager.h" // the lightmap alpha cutoff range @@ -14,6 +17,7 @@ #include "../../RendDX9/RendDX9Base.h" // the TextureManager seams #include "../../RendDX9/Texture.h" #include "../../../RendDX9Abi/BfMemory.h" +#include "../../../RendDX9Abi/D3dx9Sdk.h" #include "../../../RendDX9Abi/EngineFile.h" // EngineStream - FileManager open / read / seek #include "../../../RendDX9Abi/Frontier.h" // renddx9abi::logf - dice's debug stream @@ -22,18 +26,6 @@ #include #include // _isnan -// d3dx9_25 exports undecorated names (D3dx9_25.def's header; EnvMapManager.cpp and -// TerrainLightSampling.cpp declare the same pair). -extern "C" HRESULT WINAPI D3DXLoadSurfaceFromSurface( - IDirect3DSurface9* destination, const PALETTEENTRY* destinationPalette, - const RECT* destinationRect, IDirect3DSurface9* source, - const PALETTEENTRY* sourcePalette, const RECT* sourceRect, - DWORD filter, D3DCOLOR colourKey); -extern "C" HRESULT WINAPI D3DXFilterTexture( - IDirect3DBaseTexture9* baseTexture, const PALETTEENTRY* palette, UINT sourceLevel, DWORD filter); -#pragma comment(linker, "/alternatename:_D3DXLoadSurfaceFromSurface@32=_D3DXLoadSurfaceFromSurface") -#pragma comment(linker, "/alternatename:_D3DXFilterTexture@16=_D3DXFilterTexture") - namespace dice { namespace hfe { namespace geom { @@ -51,11 +43,18 @@ const unsigned int kFormatDXT5 = 0x35545844u; // 'DXT5' const int kPoolManaged = 1; // the TextureManager's +0x20 creation pool const int kPoolScratch = 3; -// A sample is present when any position component exceeds FLT_EPSILON in magnitude. +// A sample is present when a magnitude exceeds FLT_EPSILON or is unordered. inline bool hasPosition(const Vec3& position) { - return std::fabs(position.x) > FLT_EPSILON || std::fabs(position.y) > FLT_EPSILON - || std::fabs(position.z) > FLT_EPSILON; +#if defined(__APPLE__) + // [CHOSEN, not recovered] FCOM signals invalid for unordered components. + return !bf2x87::lessEqual(bf2x87::wide(std::fabs(position.x)), bf2x87::wide(FLT_EPSILON)) + || !bf2x87::lessEqual(bf2x87::wide(std::fabs(position.y)), bf2x87::wide(FLT_EPSILON)) + || !bf2x87::lessEqual(bf2x87::wide(std::fabs(position.z)), bf2x87::wide(FLT_EPSILON)); +#else + return !(std::fabs(position.x) <= FLT_EPSILON) || !(std::fabs(position.y) <= FLT_EPSILON) + || !(std::fabs(position.z) <= FLT_EPSILON); +#endif } // Zeroes a position with a NaN component (x, then y, then z tested as doubles). @@ -73,17 +72,41 @@ inline void zeroNanPosition(Vec3& position) // takes the low bound. inline float clampValue(float value, float low, float high) { +#if defined(__APPLE__) + // [CHOSEN, not recovered] Match the shared PE 0x1000ED40 FCOMI exception flags. + if (bf2x87::greaterEqual(bf2x87::wide(value), bf2x87::wide(high))) + value = high; + if (!bf2x87::greaterEqual(bf2x87::wide(value), bf2x87::wide(low))) + value = low; +#else if (value >= high) value = high; if (!(value >= low)) value = low; +#endif return value; } // One packed channel: __ftol2's 64-bit truncation, its low byte kept. -inline unsigned int channelByte(float value) +#if defined(__APPLE__) +// [CHOSEN, not recovered] Keep the x87 value through __ftol2, without a float store. +using SampleReal = bf2x87::Real; +inline SampleReal sampleProduct(float a, float b) +{ + return bf2x87::mul(bf2x87::wide(a), bf2x87::wide(b)); +} +#else +using SampleReal = float; +inline SampleReal sampleProduct(float a, float b) { return a * b; } +#endif + +inline unsigned int channelByte(SampleReal value) { +#if defined(__APPLE__) + return static_cast(bf2x87::toInt64Truncate(value)) & 0xFFu; +#else return static_cast(static_cast(value)) & 0xFFu; +#endif } // Drops an owner reference; the last one destroys and frees the texture. @@ -100,6 +123,7 @@ inline void releaseTexture(dx9rend::EngineTexture* texture) // non-empty 3 x 3 neighbourhood, written to `destination`; border texels are left alone. Both // buffers hold the result afterwards: `destination` starts as a copy of `source` and is copied // back. [INFERRED] name. +// PE 0x101BD160 void lightmapDilate(unsigned int* source, unsigned int* destination, unsigned int width, unsigned int height) { @@ -145,8 +169,51 @@ void lightmapDilate(unsigned int* source, unsigned int* destination, unsigned in } // anonymous namespace +// Answers the grid sample at the fractional position (x, y): column = trunc(width * x), row = +// trunc(height * y). The record is copied with cleared results and done flag. [INFERRED] name. +// PE 0x101BD7F0: unreachable in 1.50: no code or data references. +// [CHOSEN, not recovered] Memory safety: the shipped body indexes the grid unchecked and copies the +// stack byte after its truncation temporary into directlyLit (+0x2D). An index outside the grid +// answers an empty record (zero position and normal, triangle 0xFFFFFFFF, the invalid-sample marker), +// and directlyLit is zero. +LightSample MeshLightSampler::getSampleAt(float x, float y) +{ +#if defined(__APPLE__) + // [CHOSEN, not recovered] Keep the x87 products through FISTP's truncation. + const int row = bf2x87::toIntTruncate(sampleProduct(static_cast(m_textureSizeY), y)); + const int column = bf2x87::toIntTruncate(sampleProduct(static_cast(m_textureSizeX), x)); +#else + const int row = static_cast(static_cast(m_textureSizeY) * y); + const int column = static_cast(static_cast(m_textureSizeX) * x); +#endif + const unsigned int index = static_cast(row) * m_textureSizeX + + static_cast(column); + LightSample sample; + if (m_samples.data() && index < m_samples.size()) + { + const MeshSampleRecord& record = m_samples[index]; + sample.position = record.position; + sample.normal = record.normal; + sample.triangle = record.triangle; + } + else + { + sample.triangle = 0xFFFFFFFFu; + } + sample.result[0] = 0.0f; + sample.result[1] = 0.0f; + sample.result[2] = 0.0f; + sample.result[3] = 0.0f; + sample.done = 0; + sample.directlyLit = 0; + sample.pad2E[0] = 0; + sample.pad2E[1] = 0; + return sample; +} + // The vectors start empty and the string empty; the size fields, the cursor and the batch count // are written by load() and getSamples before they are read. +// PE 0x101BD8D0 MeshLightSampler::MeshLightSampler() : m_refCount(1), m_texture(0), @@ -156,6 +223,7 @@ MeshLightSampler::MeshLightSampler() { } +// PE 0x101BD920 MeshLightSampler::~MeshLightSampler() { const bool dxt1 = g_LightmapGeneration->m_lightmapFormat == 1; // +0x124 @@ -196,6 +264,7 @@ void MeshLightSampler::addRef() { ++m_refCount; } int MeshLightSampler::getRef() { return m_refCount; } // Answers the count after the decrement; zero destroys and frees. +// PE 0x101BEF70 int MeshLightSampler::release() { const int count = --m_refCount; @@ -208,6 +277,7 @@ int MeshLightSampler::release() } // The body the terrain sampler shares in the image: IBase (1) and IID_ILightSampling answer this. +// PE 0x101BECB0 void* MeshLightSampler::queryInterface(unsigned int iid) const { MeshLightSampler* const self = const_cast(this); @@ -216,12 +286,14 @@ void* MeshLightSampler::queryInterface(unsigned int iid) const return iid == kIIDLightSampling ? self : 0; } +// PE 0x101BD310 unsigned int MeshLightSampler::getBlockCount() { return 1; } // The present samples as the count, an empty dirty box and the triangle vector itself. +// PE 0x101BD320 LightSampleBlock MeshLightSampler::getBlock(unsigned int) { LightSampleBlock result; @@ -242,6 +314,7 @@ LightSampleBlock MeshLightSampler::getBlock(unsigned int) // Continues from the cursor over the grid: NaN positions are zeroed in place, samples without a // position are skipped, and each present one is copied (position, normal, triangle) into the next // record of `out` with cleared results and done flag. The block index is ignored. +// PE 0x101BD3C0 unsigned int MeshLightSampler::getSamples(unsigned int, unsigned int maxCount, LightSample* out) { m_batch = out; @@ -279,6 +352,7 @@ unsigned int MeshLightSampler::getSamples(unsigned int, unsigned int maxCount, L // A from the LightManager's lightmap alpha cutoff range - the sample's directly-lit flag when the // range starts at 0, else the luminance 0.3 R + 0.59 G + 0.1 B (clamped to [0, 1]) mapped from the // range onto [0, 1]. The range is read either way. Always true. +// PE 0x101BD580 bool MeshLightSampler::storeResults() { unsigned int index = m_batchStart; @@ -287,54 +361,88 @@ bool MeshLightSampler::storeResults() while (!hasPosition(m_samples[index].position)) ++index; unsigned int* const texels = static_cast(m_lockInfo->pBits); - const LightSample& sample = m_batch[i]; - - float alpha; + SampleReal alpha; if (g_LightManager->getLightMapAmbientAlphaCutoffRange().x == 0.0f) { - alpha = static_cast(sample.directlyLit); + alpha = static_cast(m_batch[i].directlyLit); } else { + const LightSample& sample = m_batch[i]; +#if defined(__APPLE__) + // [CHOSEN, not recovered] The luminance has one float argument store. + const float luminance = clampValue(bf2x87::store(bf2x87::add( + bf2x87::add(sampleProduct(sample.result[2], 0.1f), + sampleProduct(sample.result[1], 0.59f)), + sampleProduct(sample.result[0], 0.3f))), 0.0f, 1.0f); +#else const float luminance = clampValue( sample.result[2] * 0.1f + sample.result[1] * 0.59f + sample.result[0] * 0.3f, 0.0f, 1.0f); - if (luminance < g_LightManager->getLightMapAmbientAlphaCutoffRange().x) +#endif + const float lowCutoff = g_LightManager->getLightMapAmbientAlphaCutoffRange().x; +#if defined(__APPLE__) + const bool below = bf2x87::less(bf2x87::wide(luminance), bf2x87::wide(lowCutoff)); +#else + const bool below = luminance < lowCutoff; +#endif + if (below) { alpha = 0.0f; } - else if (luminance >= g_LightManager->getLightMapAmbientAlphaCutoffRange().y) - { - alpha = 1.0f; - } else { - const Vec2& low = g_LightManager->getLightMapAmbientAlphaCutoffRange(); - const Vec2& high = g_LightManager->getLightMapAmbientAlphaCutoffRange(); - alpha = (luminance - low.x) - / (high.y - g_LightManager->getLightMapAmbientAlphaCutoffRange().x); + const float highCutoff = g_LightManager->getLightMapAmbientAlphaCutoffRange().y; +#if defined(__APPLE__) + const bool above = bf2x87::greaterEqual(bf2x87::wide(luminance), bf2x87::wide(highCutoff)); +#else + const bool above = luminance >= highCutoff; +#endif + if (above) + alpha = 1.0f; + else + { + const Vec2& low = g_LightManager->getLightMapAmbientAlphaCutoffRange(); + const Vec2& high = g_LightManager->getLightMapAmbientAlphaCutoffRange(); + const Vec2& last = g_LightManager->getLightMapAmbientAlphaCutoffRange(); +#if defined(__APPLE__) + // [CHOSEN, not recovered] No store between the quotient and channel conversion. + alpha = bf2x87::div(bf2x87::sub(bf2x87::wide(luminance), bf2x87::wide(low.x)), + bf2x87::sub(bf2x87::wide(high.y), bf2x87::wide(last.x))); +#else + alpha = (luminance - low.x) / (high.y - last.x); +#endif + } } } + const LightSample& sample = m_batch[i]; if (g_LightmapGeneration->m_enableIntensityLightmaps) // +0x120 { - texels[index] = (channelByte(sample.result[3] * 255.0f) << 24) - | (channelByte(sample.result[0] * 255.0f) << 16) - | (channelByte(sample.result[1] * 255.0f) << 8) - | channelByte(sample.result[2] * 255.0f); + const unsigned int a = channelByte(sampleProduct(sample.result[3], 255.0f)); + const unsigned int r = channelByte(sampleProduct(sample.result[0], 255.0f)); + const unsigned int g = channelByte(sampleProduct(sample.result[1], 255.0f)); + const unsigned int b = channelByte(sampleProduct(sample.result[2], 255.0f)); + texels[index] = (a << 24) | (r << 16) | (g << 8) | b; } else { - texels[index] = (channelByte(alpha * 255.0f) << 24) - | (channelByte(sample.result[0] * 255.0f) << 16) - | (channelByte(sample.result[1] * 255.0f) << 8) - | channelByte(sample.result[2] * 255.0f); + const unsigned int r = channelByte(sampleProduct(sample.result[0], 255.0f)); +#if defined(__APPLE__) + const unsigned int a = channelByte(bf2x87::mul(alpha, bf2x87::wide(255.0f))); +#else + const unsigned int a = channelByte(alpha * 255.0f); +#endif + const unsigned int g = channelByte(sampleProduct(sample.result[1], 255.0f)); + const unsigned int b = channelByte(sampleProduct(sample.result[2], 255.0f)); + texels[index] = (a << 24) | (r << 16) | (g << 8) | b; } } return true; } // Appends (position, colour, range) and answers its index, or -1 while the vector has no storage. +// PE 0x101BDB90 int MeshLightSampler::addLight(Vec3 color, Vec3 position, float range) { MeshSampleLight light; @@ -347,11 +455,13 @@ int MeshLightSampler::addLight(Vec3 color, Vec3 position, float range) return static_cast(m_lights.size()) - 1; } +// PE 0x101BECE0 void* MeshLightSampler::getLights() { return &m_lights; } +// PE 0x101BDC10 void MeshLightSampler::halveSampleGrid() { m_textureSizeX >>= 1; @@ -367,11 +477,12 @@ void MeshLightSampler::halveSampleGrid() m_samples.resize(m_textureSizeX * m_textureSizeY); } -bool MeshLightSampler::load(const vc71::string& path, const vc71::string& outputName) +// PE 0x101BDCD0 +bool MeshLightSampler::load(const std::string& path, const std::string& outputName) { m_outputName = outputName; ::renddx9abi::EngineStream file; - if (!file.open(path)) + if (!file.open(path, 2, 0, 0)) return false; // The magic is compared as a five-byte string; a short read leaves the shipped stack bytes @@ -484,6 +595,7 @@ bool MeshLightSampler::load(const vc71::string& path, const vc71::string& output // Each texel is rebuilt as 0xFF000000 | R << 16 | G << 8 | A from its own bytes; an empty row only // advances the cursor. +// PE 0x101BD100 void lightmapMoveAlphaToBlue(unsigned int* texels, unsigned int width, unsigned int height) { if (height == 0) diff --git a/Code/BF2/Geom/LightmapGeneration/MeshLightSampling.h b/Code/BF2/Geom/LightmapGeneration/MeshLightSampling.h index 589f8d9a3..7f047597b 100644 --- a/Code/BF2/Geom/LightmapGeneration/MeshLightSampling.h +++ b/Code/BF2/Geom/LightmapGeneration/MeshLightSampling.h @@ -14,11 +14,11 @@ #define BF2_GEOM_LIGHTMAPGENERATION_MESHLIGHTSAMPLING_H #include "ILightSampling.h" -#include "../UndergrowthSystem.h" // Vc71Vec - the renderer's owning VC7.1-layout vector #include "../../Math/Vec3.h" -#include "../../../RendDX9Abi/Vc71String.h" +#include #include +#include namespace dice { namespace hfe { @@ -93,7 +93,7 @@ class MeshLightSampler : public ILightSampling // wider than the size cap and while the resolution modifier is below 1 (doubling it each time), // NaN positions are zeroed, and an A8R8G8B8 texture of the final size is created, locked and // cleared. False only when the file cannot be opened. - bool load(const vc71::string& path, const vc71::string& outputName); + bool load(const std::string& path, const std::string& outputName); // IBase virtual void addRef(); @@ -113,12 +113,15 @@ class MeshLightSampler : public ILightSampling // stride is twice the new width, which equals the old width only for even widths (shipped). void halveSampleGrid(); + // [INFERRED] name; PE 0x101BD7F0 has no caller in 1.50. The grid sample at fractional (x, y). + LightSample getSampleAt(float x, float y); + // data, in shipped order (the vptr is +0x00) int m_refCount; // +0x04 1 - Vc71Vec m_samples; // +0x08 (first at +0x0C) the sample grid + std::vector m_samples; // +0x08 (first at +0x0C) the sample grid // +0x18 - the triangle list; LightSampleBlock::triangles points at this vector itself. - Vc71Vec m_triangles; - Vc71Vec m_lights; // +0x28 (first at +0x2C) + std::vector m_triangles; + std::vector m_lights; // +0x28 (first at +0x2C) float m_resolutionModifier; // +0x38 createLightSampler's argument unsigned int m_textureSizeX; // +0x3C the grid (and lightmap) width unsigned int m_textureSizeY; // +0x40 its height @@ -129,7 +132,7 @@ class MeshLightSampler : public ILightSampling unsigned int m_batchStart; // +0x54 where the last batch started unsigned int m_batchCount; // +0x58 samples in the last batch LightSample* m_batch; // +0x5C the caller's buffer of the last batch - vc71::string m_outputName; // +0x60 the lightmap name, without ".dds" + std::string m_outputName; // +0x60 the lightmap name, without ".dds" unsigned int m_usedWidth; // +0x7C the largest column holding a valid triangle unsigned int m_usedHeight; // +0x80 the last row holding a valid triangle // +0x84 - -1 (none); the template's lightmap size for this (geom, lod) when it overrides lightmaps. @@ -140,24 +143,14 @@ class MeshLightSampler : public ILightSampling MeshLightSampler& operator=(const MeshLightSampler&); }; -#if defined(_M_IX86) +// The .samples file record load() reads as one block (28 bytes per sample): every architecture. static_assert(sizeof(MeshSampleRecord) == 28, "a sample is 28 bytes - see the /28 at 0x101BD3F0"); +#if defined(_M_IX86) static_assert(sizeof(MeshSampleTriangle) == 92, "a triangle is 92 bytes - see 0x101BDF50"); static_assert(offsetof(MeshSampleTriangle, normal) == 0x24, "triangle normals at +0x24"); static_assert(offsetof(MeshSampleTriangle, unresolved54) == 0x54, "the loader's -1 at +0x54"); static_assert(sizeof(MeshSampleLight) == 28, "a light record is 28 bytes - see 0x101BDBE7"); static_assert(offsetof(MeshLightSampler, m_samples) == 0x08, "samples at +0x08"); -static_assert(offsetof(MeshLightSampler, m_triangles) == 0x18, "triangles at +0x18 - see 0x101BD32D"); -static_assert(offsetof(MeshLightSampler, m_lights) == 0x28, "lights at +0x28 - see 0x101BECE0"); -static_assert(offsetof(MeshLightSampler, m_resolutionModifier) == 0x38, "resolution at +0x38"); -static_assert(offsetof(MeshLightSampler, m_textureSizeX) == 0x3C, "width at +0x3C"); -static_assert(offsetof(MeshLightSampler, m_realSampleCount) == 0x44, "real samples at +0x44"); -static_assert(offsetof(MeshLightSampler, m_texture) == 0x48, "texture at +0x48"); -static_assert(offsetof(MeshLightSampler, m_batch) == 0x5C, "batch at +0x5C"); -static_assert(offsetof(MeshLightSampler, m_outputName) == 0x60, "output name at +0x60"); -static_assert(offsetof(MeshLightSampler, m_usedWidth) == 0x7C, "used width at +0x7C"); -static_assert(offsetof(MeshLightSampler, m_sizeCap) == 0x84, "size cap at +0x84"); -static_assert(sizeof(MeshLightSampler) == 0x88, "createLightSampler allocates 0x88 - see 0x1019868C"); #endif } // namespace geom diff --git a/Code/BF2/Geom/LightningManager.cpp b/Code/BF2/Geom/LightningManager.cpp new file mode 100644 index 000000000..eac3c3808 --- /dev/null +++ b/Code/BF2/Geom/LightningManager.cpp @@ -0,0 +1,652 @@ +// LightningManager, recovered from RendDX9.dll 1.50 (0x10155CB0..0x101575F0 and its factory). +// [INFERRED] file placement: the image carries no __FILE__ string or symbol for the class. +// A strike is a camera-facing textured strip (Shaders/Lightning) of 101 vertex pairs whose x is +// jittered per row; the visible part is its lowest lightningSegments rows. + +#ifdef BF2_IMAGE_RENDDX9 + +#include "../Platform/X87Compat.h" // [CHOSEN, not recovered] x87 conversion results, including invalid inputs. +#include "../RendDX9/RendDX9Math.h" // rendmath::normalize (sub_100777A0) +#include "LightningManager.h" +#include "SkyDome.h" +#include "../Game/Objects/IObjectTemplate.h" +#include "../Scene/Object/ObjectTypes/Base/ObjectTemplateManager.h" +#include "../Physics/HeightmapCluster.h" +#include "../Sound/BfSound.h" +#include "../Sound/SoundObjectTemplate.h" +#include "../Math/Mat4.h" +#include "../RendDX9/RendDX9Base.h" +#include "../RendDX9/ShaderParameter.h" +#include "../RendDX9/Texture.h" +#include "../RendMisc/IRenderView.h" +#include "../../RendDX9Abi/BfMemory.h" +#include "../../RendDX9Abi/HfeAbi.h" +#include "../../RendDX9Abi/PluginAbi.h" +#include "../../RendDX9Abi/PluginEntry.h" + +#include +#include +#include +#include + +namespace dice { +namespace hfe { + +// PluginEntry.cpp - the cached host ObjectTemplateManager (0x10244ADC). +extern IBase* objectTemplateManager; + +namespace dx9rend { +extern void* g_shaderManager; // dword_1023B97C +// BufferManager.cpp / StateManager.cpp seams, declared as OverlayTexture.cpp and SkyDome.cpp do. +void* bufferManagerCreateVertexBuffer(unsigned int count, unsigned int stride, + unsigned int usage, const char* name); // sub_10011FF0 +void vertexBufferRelease(void* wrapper); // inline --ref, sub_10014510, free +void* vertexBufferLock(void* wrapper, unsigned int offsetVerts, unsigned int countVerts, + unsigned int flags); // sub_10014630 +bool vertexBufferUnlock(void* wrapper); // sub_10014690 +void vertexBufferBindStream(void* wrapper, unsigned int stream); // sub_100146C0 +void vertexDeclarationBind(void* wrapper); // sub_100147C0 +void rendererDrawPrimitive(unsigned int primCount, unsigned int type, + unsigned int startVertex); // sub_10005870 +} // namespace dx9rend + +namespace geom { + +// StaticMesh.cpp - the shared PE 0x10077A30 product (output = left * right). +void geometryRendererMatrixProduct(Mat4& output, const Mat4& left, const Mat4& right); + +namespace { + +const unsigned int kIID_IBase = 1u; +const unsigned int kIID_ILightningManager = 0xB801DD06u; // dword_1021AEA4 +const unsigned int kCID_SoundObjectTemplate = 9986001u; // 0x985FD1, the "Sound" template class + +const unsigned int kBoltVertexCount = 0xCA; // 101 rows of two vertices +const unsigned int kBoltRowCount = 100; + +// flt_10239DF8, .data, 1000. Its only reader is drawStrike. [INFERRED] name. +float g_lightningFarPlane = 1000.0f; + +// The bolt vertex, 24 bytes: the stride createVertexBuffer is asked for. +struct LightningVertex +{ + float x, y, z; // +0x00 + float u, v; // +0x0C + unsigned int color; // +0x14 the fade, replicated into all four bytes +}; + +// unk_1021E2F4: POSITION float3 at 0, TEXCOORD0 float2 at 12, COLOR D3DCOLOR at 20. +const D3DVERTEXELEMENT9 kLightningVertexElements[] = +{ + { 0, 0, D3DDECLTYPE_FLOAT3, 0, D3DDECLUSAGE_POSITION, 0 }, + { 0, 12, D3DDECLTYPE_FLOAT2, 0, D3DDECLUSAGE_TEXCOORD, 0 }, + { 0, 20, D3DDECLTYPE_D3DCOLOR, 0, D3DDECLUSAGE_COLOR, 0 }, + { 0xFF, 0, D3DDECLTYPE_UNUSED, 0, 0, 0 } +}; + +// x87 truncating conversions (fistp under a chop control word, and _ftol2). +inline int truncateToInt(float value) +{ +#if defined(__APPLE__) + return bf2x87::toIntTruncate(value); +#else + return static_cast(value); +#endif +} + +inline long long truncateToInt64(float value) +{ +#if defined(__APPLE__) + return bf2x87::toInt64Truncate(value); +#else + return static_cast(value); +#endif +} + +// Mat4 copy (0x10030DD0) followed by the product into the original: `m = m * rhs`. +void multiplyInPlace(Mat4& m, const Mat4& rhs) +{ + const Mat4 left = m; + geometryRendererMatrixProduct(m, left, rhs); +} + +world::IHeightmapCluster* heightmapCluster() +{ + IBase* const found = classManager->getSingleton(renddx9abi::HostString("HeightmapCluster")); + return static_cast(static_cast(found)); +} + +inline SkyDome* skyDome() +{ + return static_cast(g_SkyDome); +} + +} // anonymous namespace + + +// Construction - 0x10156A80. The resources are created at once; a failure leaves the rest null. +// PE 0x10156A80. +LightningManager::LightningManager() + : m_refCount(1), m_effect(0), m_vertexDeclaration(0), m_paramWorldViewProj(0), + m_paramColor(0), m_paramTexture(0), m_texture(0), m_duration(0.15f), m_sfxDelay(5.0f), + m_strikes(), m_sfxName(), m_sfxTemplate(0), m_pertubation(10.0f), m_blendOutTime(0.1f), + m_skyBlendOutTime(0.1f), m_segments(100), m_groundPenetration(0.0f), + m_inFadeSegments(0.0f), m_outFadeSegments(0.0f), m_pending(), m_time(0.0), + m_lastTime(0.0), m_nextBuffer(0) +{ + m_scale.x = 1.0f; + m_scale.y = 300.0f; + m_color.x = 1.0f; + m_color.y = 1.0f; + m_color.z = 1.0f; + m_color.w = 1.0f; + for (int i = 0; i < 3; ++i) + { + m_vertexBuffers[i] = 0; + m_sfxSounds[i] = 0; + } + // [CHOSEN, not recovered] The shipped constructor leaves +0x44 unwritten; initResources sets it + // once the buffers exist. Zeroing it keeps a failed init deterministic natively. + m_sound = 0; + initResources(); +} + +// 0x10156B80. The members (pending queue, thunder name, strikes) follow. +LightningManager::~LightningManager() +{ + releaseResources(); +} + +void LightningManager::operator delete(void* memory) +{ + ::renddx9abi::engineFree(memory); +} + + +// The IBase quartet. + +void LightningManager::addRef() +{ + ++m_refCount; +} + +int LightningManager::getRef() +{ + return m_refCount; +} + +// sub_1015A4B0 (shared): at zero, the deleting destructor (slot +0x10, flag 1). +int LightningManager::release() +{ + const int remaining = --m_refCount; + if (remaining == 0) + delete this; + return remaining; +} + +// IBase (1) and IID_ILightningManager answer `this`. +// PE 0x10157530. +void* LightningManager::queryInterface(unsigned int iid) const +{ + if (iid == kIID_IBase) + return const_cast(this); + return iid != kIID_ILightningManager ? 0 : const_cast(this); +} + + +// 0x101561F0. Stops at the first missing resource. The Sound singleton and the bolt texture are +// fetched only after all three buffers exist. +bool LightningManager::initResources() +{ + m_effect = static_cast( + dx9rend::shaderManagerGetEffect(dx9rend::g_shaderManager, "Shaders/Lightning")); + if (!m_effect) + return false; + dx9rend::effectSetTechniqueByName(m_effect, std::string("Lightning")); // sub_1001DC60 + lookupShaderParameters(); + + m_vertexDeclaration = dx9rend::vertexDeclarationCreate(kLightningVertexElements); + if (!m_vertexDeclaration) + return false; + for (int i = 0; i < 3; ++i) + { + m_vertexBuffers[i] = dx9rend::bufferManagerCreateVertexBuffer( + kBoltVertexCount, sizeof(LightningVertex), D3DUSAGE_WRITEONLY, "LightningManager"); + if (!m_vertexBuffers[i]) + return false; + } + + m_sound = static_cast(static_cast( + classManager->getSingleton(renddx9abi::HostString("Sound")))); + m_texture = static_cast( + dx9rend::textureManagerGetTexture(std::string("common/textures/lightning"))); + return true; +} + +// 0x10155CB0, in this order. +void LightningManager::lookupShaderParameters() +{ + m_paramWorldViewProj = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("WORLDVIEWPROJ")); + m_paramColor = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("LIGHTNINGCOLOR")); + m_paramTexture = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("TEXTURE")); +} + +// PE 0x10155D30: releases the three shader parameters (TEXTURE, LIGHTNINGCOLOR, WORLDVIEWPROJ, in that +// order), each only when set, nulling the slot after its release. The same sequence runs inline in +// releaseResources. Unreachable in 1.50: no code or data references. +void LightningManager::releaseShaderParameters() +{ + if (m_paramTexture) + m_paramTexture->release(); + m_paramTexture = 0; + if (m_paramColor) + m_paramColor->release(); + m_paramColor = 0; + if (m_paramWorldViewProj) + m_paramWorldViewProj->release(); + m_paramWorldViewProj = 0; +} + +// PE 0x10156310: drops the bolt texture reference (the last one destroys and frees it) and nulls the +// slot. The same sequence runs inline in releaseResources. Unreachable in 1.50: no code or data references. +void LightningManager::releaseTexture() +{ + if (m_texture) + dx9rend::textureReleaseRef(m_texture); + m_texture = 0; +} + +// 0x10156340. The thunder first, then the texture, the three parameters in reverse, the buffers, +// the declaration and the effect; every slot is nulled. +void LightningManager::releaseResources() +{ + releaseSoundEffect(); + if (m_texture) + dx9rend::textureReleaseRef(m_texture); + m_texture = 0; + if (m_paramTexture) + m_paramTexture->release(); + m_paramTexture = 0; + if (m_paramColor) + m_paramColor->release(); + m_paramColor = 0; + if (m_paramWorldViewProj) + m_paramWorldViewProj->release(); + m_paramWorldViewProj = 0; + for (int i = 0; i < 3; ++i) + { + if (m_vertexBuffers[i]) + dx9rend::vertexBufferRelease(m_vertexBuffers[i]); + m_vertexBuffers[i] = 0; + } + if (m_vertexDeclaration) + dx9rend::vertexDeclarationRelease(m_vertexDeclaration); + m_vertexDeclaration = 0; + if (m_effect) + dx9rend::effectRelease(m_effect); + m_effect = 0; +} + +// 0x10156060. The three sound instances (ISound +0x04), the template (+0x08), then the name. +void LightningManager::releaseSoundEffect() +{ + for (int i = 0; i < 3; ++i) + { + if (m_sfxSounds[i]) + { + m_sfxSounds[i]->release(); + m_sfxSounds[i] = 0; + } + } + if (m_sfxTemplate) + { + m_sfxTemplate->release(); + m_sfxTemplate = 0; + } + m_sfxName.clear(); +} + + +// 0x10156BF0. Unlike update(), this body tests the sky dome for null. +void LightningManager::reset() +{ + if (g_SkyDome) + skyDome()->setLightingBlend(0.0f); + // VC7.1's clear() frees the storage (the listing's free plus three zeroed pointers). + m_pending.clear(); + m_strikes.clear(); + m_nextBuffer = 0; +} + +// 0x10156DB0. The sky dome is used without a null test, as shipped. +void LightningManager::update(double deltaTime) +{ + m_time = deltaTime + m_time; + processPendingLightning(); + const double frameTime = m_time - m_lastTime; + m_lastTime = m_time; + + // Fade the sky flash by frameTime / skyBlendOutTime (at most 1), never below zero. + const double blend = skyDome()->getLightingBlend(); + const double step = frameTime / m_skyBlendOutTime; + const double clamped = (1.0 < step) ? 1.0 : step; + const float faded = (blend - clamped < 0.0) ? 0.0f : static_cast(blend - clamped); + skyDome()->setLightingBlend(faded); + + for (unsigned int i = 0; i < m_strikes.size(); ++i) + { + LightningStrike& strike = m_strikes[i]; + if (m_time <= strike.flashEndTime) + { + if (!strike.built) + { + buildBoltBuffer(strike.buffer); + strike.built = true; + } + skyDome()->setLightingBlend(1.0f); + } + if (strike.soundTime <= m_time) + { + // No null test on the sound, as shipped: a strike needs lightningSFXName first. + m_sfxSounds[strike.buffer]->play(1); // ISound +0x10 + m_strikes[i] = m_strikes.back(); + m_strikes.pop_back(); + --i; + } + } +} + +// 0x10156A30. +void LightningManager::render() +{ + for (unsigned int i = 0; i < m_strikes.size(); ++i) + drawStrike(m_strikes[i]); +} + +// 0x10156C50 - the queue's push_back (sub_1013AC80 on +0xA8). +void LightningManager::addLightning(const Vec2& offset) +{ + m_pending.push_back(offset); +} + +// 0x10156D40. +void LightningManager::processPendingLightning() +{ + for (unsigned int i = 0; i < m_pending.size(); ++i) + createStrike(m_pending[i]); + m_pending.clear(); +} + +// 0x10156C60. The strike stands on the terrain under (x, z) when a heightmap cluster exists, +// else at height 0; the camera position is added only when it is drawn. +void LightningManager::createStrike(const Vec2& offset) +{ + world::IHeightmapCluster* const cluster = heightmapCluster(); + float height = 0.0f; + if (cluster) + { + Vec3 probe; + probe.y = cluster->getSeaWaterLevel(); // +0x60 + probe.x = offset.x; + probe.z = offset.y; + height = cluster->getHeightInWorldCoords(probe); // +0x68 + } + + LightningStrike strike; + strike.position.x = offset.x; + strike.position.y = height - m_groundPenetration; + strike.position.z = offset.y; + strike.flashEndTime = m_duration + m_time; + strike.soundTime = m_sfxDelay + m_time; + strike.built = false; + strike.buffer = m_nextBuffer; + ++m_nextBuffer; + if (m_nextBuffer >= 3) + m_nextBuffer = 0; + m_strikes.push_back(strike); +} + +// 0x10155DA0. Rewrites one bolt buffer: rows 0..100 from y = 1 down to y = 0, the left vertex of +// each row moving the bolt's x by a random step of up to +-pertubation/2 (in units of scale.x). +// The alpha fades in over inFadeSegments rows from the first drawn row and out over +// outFadeSegments rows towards row 100. A pertubation below 0.001 * scale.x divides by zero, as +// shipped. +void LightningManager::buildBoltBuffer(int buffer) +{ + LightningVertex* vertex = static_cast( + dx9rend::vertexBufferLock(m_vertexBuffers[buffer], 0, 0, D3DLOCK_DISCARD)); + const float pertubation = m_pertubation / m_scale.x; + float offset = 0.0f; + for (unsigned int i = 0; i < kBoltVertexCount; ++i, ++vertex) + { + const unsigned int side = i % 2; + const unsigned int row = i / 2; + if (side == 0) + { + const int r = std::rand(); + const int range = truncateToInt(pertubation * 1000.0f); + offset = static_cast(r % range) * 0.001f - pertubation * 0.5f + offset; + } + vertex->z = 0.0f; + vertex->x = static_cast(static_cast(side)) * 2.0f - 1.0f + offset; + const float rowF = static_cast(static_cast(row)); + vertex->y = 1.0f - rowF * 0.01f; + vertex->u = (side == 1) ? 1.0f : 0.0f; + vertex->v = static_cast(static_cast(row) % 2); + + float fromStart = rowF - (100.0f - static_cast(m_segments)); + if (fromStart < 0.0f) + fromStart = 0.0f; + const float toEnd = 100.0f - rowF; + + float fadeIn; + if (m_inFadeSegments != 0.0f) + { + const float a = fromStart / m_inFadeSegments; + fadeIn = (1.0f < a) ? 1.0f : a; + } + else + fadeIn = 1.0f; + + float fadeOut; + if (m_outFadeSegments != 0.0f) + { + const float b = toEnd / m_outFadeSegments; + fadeOut = (1.0f < b) ? 1.0f : b; + } + else + fadeOut = 1.0f; + + const float fade = (fadeIn < fadeOut) ? fadeIn : fadeOut; + const unsigned int level = static_cast(truncateToInt64(fade * 255.0f)); + const unsigned int low = level & 0xFFu; + vertex->color = (((((level << 8) | low) << 8) | low) << 8) | low; + } + dx9rend::vertexBufferUnlock(m_vertexBuffers[buffer]); +} + +// 0x10156920. The far plane is restored only when the constants were set, as shipped. +void LightningManager::drawStrike(const LightningStrike& strike) +{ + dx9rend::stateManagerPush(); + dx9rend::IRenderView* const view = dx9rend::rendererGetRenderViewDup(); // Renderer +0x50 + const float savedFarPlane = view->getFarPlane(); + view->setFarPlane(g_lightningFarPlane); + dx9rend::vertexDeclarationBind(m_vertexDeclaration); + dx9rend::vertexBufferBindStream(m_vertexBuffers[strike.buffer], 0); + if (setStrikeShaderConstants(strike)) + { + dx9rend::effectBegin(m_effect); + dx9rend::effectBeginPass(m_effect, 0); + // D3DPT_TRIANGLESTRIP over the last lightningSegments rows of the strip. + dx9rend::rendererDrawPrimitive(static_cast(m_segments + m_segments), 5, + static_cast((100 - m_segments) * 2)); + dx9rend::effectEnd(m_effect); + view->setFarPlane(savedFarPlane); + } + dx9rend::stateManagerPop(); +} + +// 0x10156420. Faces the strip towards the camera around the vertical axis, scales it by +// lightningScale and places it at camera + strike offset. A camera looking straight up or down +// has no horizontal direction, and the strike is skipped. +bool LightningManager::setStrikeShaderConstants(const LightningStrike& strike) +{ + dx9rend::IRenderView* const view = dx9rend::rendererGetRenderViewDup(); // Renderer +0x50 + const Mat4* const camera = view->getViewMatrixPtr(); // +0x64 + Vec3 facing; + facing.x = -camera->m[8]; + facing.y = 0.0f; + facing.z = -camera->m[10]; + if (facing.z * facing.z + facing.x * facing.x == 0.0f) + return false; + rendmath::normalize(facing); + + // The basis: right = up x facing, up, facing. The zero products are the shipped ones. + Mat4 rotation; + rotation.m[0] = facing.z - facing.y * 0.0f; + rotation.m[1] = facing.x * 0.0f - facing.z * 0.0f; + rotation.m[2] = facing.y * 0.0f - facing.x; + rotation.m[3] = 0.0f; + rotation.m[4] = 0.0f; + rotation.m[5] = 1.0f; + rotation.m[6] = 0.0f; + rotation.m[7] = 0.0f; + rotation.m[8] = facing.x; + rotation.m[9] = facing.y; + rotation.m[10] = facing.z; + rotation.m[11] = 0.0f; + rotation.m[12] = 0.0f; + rotation.m[13] = 0.0f; + rotation.m[14] = 0.0f; + rotation.m[15] = 1.0f; + + Mat4 scale = Mat4::getIdentity(); + Vec3 scaleFactors; + scaleFactors.x = m_scale.x; + scaleFactors.y = m_scale.y; + scaleFactors.z = 1.0f; + rendmath::scaleColumns(scale, scaleFactors); + + const Mat4* const cameraAgain = view->getViewMatrixPtr(); // +0x64 again + Mat4 translation = Mat4::getIdentity(); + translation.m[12] = cameraAgain->m[12] + strike.position.x; + translation.m[13] = strike.position.y; + translation.m[14] = cameraAgain->m[14] + strike.position.z; + + Mat4 world = Mat4::getIdentity(); + multiplyInPlace(world, scale); + multiplyInPlace(world, rotation); + multiplyInPlace(world, translation); + Mat4 worldViewProj = Mat4::getIdentity(); + multiplyInPlace(worldViewProj, world); + multiplyInPlace(worldViewProj, *view->getViewProjectionMatrixPtr()); // +0x84 + m_paramWorldViewProj->setValue(&worldViewProj, 0); + + // Alpha: the time left in the flash over lightningBlendOutTime, clamped to [0, 1]. + double remaining = strike.flashEndTime - m_time; + if (remaining < 0.0) + remaining = 0.0; + double alpha = remaining / m_blendOutTime; + if (1.0 < alpha) + alpha = 1.0; + Vec4 color; + color.x = m_color.x; + color.y = m_color.y; + color.z = m_color.z; + color.w = static_cast(alpha); + m_paramColor->setValue(&color, 0); + m_paramTexture->setValue(m_texture, 0); + return true; +} + + +// The console properties. + +void LightningManager::setLightningDuration(float seconds) { m_duration = seconds; } +float LightningManager::getLightningDuration() const { return m_duration; } + +void LightningManager::setLightningScale(const Vec2& scale) +{ + m_scale.y = scale.y; + m_scale.x = scale.x; +} +const Vec2& LightningManager::getLightningScale() const { return m_scale; } + +void LightningManager::setLightningPertubation(float amount) { m_pertubation = amount; } +float LightningManager::getLightningPertubation() const { return m_pertubation; } + +void LightningManager::setLightningColor(const Vec4& color) +{ + m_color.y = color.y; + m_color.x = color.x; + m_color.z = color.z; + m_color.w = color.w; +} +const Vec4& LightningManager::getLightningColor() const { return m_color; } + +void LightningManager::setLightningBlendOutTime(float seconds) { m_blendOutTime = seconds; } +float LightningManager::getLightningBlendOutTime() const { return m_blendOutTime; } + +void LightningManager::setSkyBlendOutTime(float seconds) { m_skyBlendOutTime = seconds; } +float LightningManager::getSkyBlendOutTime() const { return m_skyBlendOutTime; } + +void LightningManager::setLightningSFXDelay(float seconds) { m_sfxDelay = seconds; } +float LightningManager::getLightningSFXDelay() const { return m_sfxDelay; } + +// 0x101560B0. The template is looked up by name and the Sound class (ObjectTemplateManager PE +// +0x30); a miss leaves only the name. Each instance comes from the Sound singleton (PE +0x1C), +// which is used without a null test, as shipped. +void LightningManager::setLightningSFXName(const std::string& name) +{ + releaseSoundEffect(); + m_sfxName = name; + m_sfxTemplate = reinterpret_cast(objectTemplateManager) + ->getTemplate(renddx9abi::toHostString(name), kCID_SoundObjectTemplate); + if (!m_sfxTemplate) + return; + m_sfxTemplate->addRef(); + ISoundObjectTemplate* const sound = static_cast(m_sfxTemplate); + sound->setIsUsed(); // +0x10 + sound->impl()->setFlags(1); // +0x78, +0xC4 + for (int i = 0; i < 3; ++i) + m_sfxSounds[i] = m_sound->createSound(sound->impl(), 0); +} +const std::string& LightningManager::getLightningSFXName() const { return m_sfxName; } + +void LightningManager::setLightningSegments(int segments) +{ + if (segments >= 100) + segments = 100; + m_segments = segments; +} +int LightningManager::getLightningSegments() const { return m_segments; } + +void LightningManager::setLightningGroundPenetration(float depth) { m_groundPenetration = depth; } +float LightningManager::getLightningGroundPenetration() const { return m_groundPenetration; } + +void LightningManager::setInFadeSegments(float segments) { m_inFadeSegments = segments; } +float LightningManager::getInFadeSegments() const { return m_inFadeSegments; } + +void LightningManager::setOutFadeSegments(float segments) { m_outFadeSegments = segments; } +float LightningManager::getOutFadeSegments() const { return m_outFadeSegments; } + + +// 0x100B0BA4: an aggregate outer is refused; a failed query releases the new object. +IBase* __fastcall createLightningManager(unsigned int iid, IBase* outer) +{ + if (outer) + return 0; + void* const storage = ::renddx9abi::engineAlloc(sizeof(LightningManager)); + LightningManager* const self = storage ? new (storage) LightningManager() : 0; + void* const itf = self->queryInterface(iid); + if (!itf) + self->release(); + return static_cast(itf); +} + +} // namespace geom +} // namespace hfe +} // namespace dice + +#endif // BF2_IMAGE_RENDDX9 diff --git a/Code/BF2/Geom/LightningManager.h b/Code/BF2/Geom/LightningManager.h new file mode 100644 index 000000000..96ac7e44a --- /dev/null +++ b/Code/BF2/Geom/LightningManager.h @@ -0,0 +1,197 @@ +// Lightning bolts for the weather system: strike scheduling, the bolt vertex strips, the draw and +// the thunder sounds. WeatherManager decides when and where a strike happens; this class turns the +// request into a bolt that flashes, lights the sky dome and plays its thunder after a delay. +// [INFERRED] file placement and every method name: RendDX9.dll carries no __FILE__ string or symbol +// for this class. The console names the properties (WeatherManagerConsole.cpp). + +#ifndef BF2_GEOM_LIGHTNINGMANAGER_H +#define BF2_GEOM_LIGHTNINGMANAGER_H + +#ifdef BF2_IMAGE_RENDDX9 + +#include "../Core/IBase.h" +#include "../Math/Vec3.h" // Vec2, Vec3, Vec4 + +#include +#include +#include + +namespace dice { +namespace hfe { + +class IBfSound; +class ISound; +namespace world { class IObjectTemplate; } + +namespace dx9rend { +class Effect; +class ShaderParameter; +struct EngineTexture; +} + +namespace geom { + +// The lightning interface, vtable 0x1021E328 (33 slots, all pure but the destructor 0x10156F80). +// IID 0xB801DD06, class id 822323012, singleton "LightningManager" (dword_1024B928). +class ILightningManager : public IBase +{ +public: + virtual ~ILightningManager() {} // +0x10 + + // Drops pending and live strikes and clears the sky-dome flash. + virtual void reset() = 0; // +0x14 + // Advances the lightning clock by `deltaTime` seconds, turns pending requests into strikes, + // fades the sky-dome flash, rebuilds new bolts and plays due thunder. + virtual void update(double deltaTime) = 0; // +0x18 + // Draws every live strike. + virtual void render() = 0; // +0x1C + // Queues a strike at a horizontal offset (x, z) from the camera; update() places it. + virtual void addLightning(const Vec2& offset) = 0; // +0x20 + + // Console properties (weatherManager.*). Setters store; getters return the stored value. + virtual void setLightningDuration(float seconds) = 0; // +0x24 + virtual float getLightningDuration() const = 0; // +0x28 + virtual void setLightningScale(const Vec2& scale) = 0; // +0x2C + virtual const Vec2& getLightningScale() const = 0; // +0x30 + virtual void setLightningPertubation(float amount) = 0; // +0x34 + virtual float getLightningPertubation() const = 0; // +0x38 + virtual void setLightningColor(const Vec4& color) = 0; // +0x3C + virtual const Vec4& getLightningColor() const = 0; // +0x40 + virtual void setLightningBlendOutTime(float seconds) = 0; // +0x44 + virtual float getLightningBlendOutTime() const = 0; // +0x48 + virtual void setSkyBlendOutTime(float seconds) = 0; // +0x4C + virtual float getSkyBlendOutTime() const = 0; // +0x50 + virtual void setLightningSFXDelay(float seconds) = 0; // +0x54 + virtual float getLightningSFXDelay() const = 0; // +0x58 + // Releases the previous thunder, then looks up the Sound template `name` and creates one + // sound instance per bolt buffer. + virtual void setLightningSFXName(const std::string& name) = 0; // +0x5C + virtual const std::string& getLightningSFXName() const = 0; // +0x60 + // Clamped to at most 100 (the bolt strip has 100 segments). + virtual void setLightningSegments(int segments) = 0; // +0x64 + virtual int getLightningSegments() const = 0; // +0x68 + virtual void setLightningGroundPenetration(float depth) = 0; // +0x6C + virtual float getLightningGroundPenetration() const = 0; // +0x70 + virtual void setInFadeSegments(float segments) = 0; // +0x74 + virtual float getInFadeSegments() const = 0; // +0x78 + virtual void setOutFadeSegments(float segments) = 0; // +0x7C + virtual float getOutFadeSegments() const = 0; // +0x80 +}; + +// One live strike, 0x28 bytes on x86 (copied member-wise: 0x10157070 skips the padding). +struct LightningStrike +{ + Vec3 position; // +0x00 camera-relative x/z; y is the ground height minus + // lightningGroundPenetration + double flashEndTime; // +0x10 lightning clock + lightningDuration + double soundTime; // +0x18 lightning clock + lightningSFXDelay; the strike is + // removed when its thunder plays + bool built; // +0x20 the bolt buffer was rebuilt for this strike + int buffer; // +0x24 bolt vertex buffer and thunder sound, 0..2 round robin +}; + +// LightningManager - 0xD0 bytes, vtable 0x1021E3F0, constructor 0x10156A80, factory 0x100B0BA4. +class LightningManager : public ILightningManager +{ +public: + LightningManager(); // 0x10156A80 + virtual ~LightningManager(); // 0x10156B80 + + virtual void addRef(); // 0x1000CB20 (folded) + virtual int getRef(); // 0x101A9A10 (folded) + virtual int release(); // 0x1015A4B0 (folded) + virtual void* queryInterface(unsigned int iid) const; // 0x10157530 + + virtual void reset(); // 0x10156BF0 + virtual void update(double deltaTime); // 0x10156DB0 + virtual void render(); // 0x10156A30 + virtual void addLightning(const Vec2& offset); // 0x10156C50 + + virtual void setLightningDuration(float seconds); // 0x10155FA0 + virtual float getLightningDuration() const; // 0x10155FB0 + virtual void setLightningScale(const Vec2& scale); // 0x101569E0 + virtual const Vec2& getLightningScale() const; // 0x10155FC0 + virtual void setLightningPertubation(float amount); // 0x10155FD0 + virtual float getLightningPertubation() const; // 0x10155FE0 + virtual void setLightningColor(const Vec4& color); // 0x10156A00 + virtual const Vec4& getLightningColor() const; // 0x10155FF0 + virtual void setLightningBlendOutTime(float seconds); // 0x10156000 + virtual float getLightningBlendOutTime() const; // 0x10156010 + virtual void setSkyBlendOutTime(float seconds); // 0x10156020 + virtual float getSkyBlendOutTime() const; // 0x10156030 + virtual void setLightningSFXDelay(float seconds); // 0x10156040 + virtual float getLightningSFXDelay() const; // 0x10156050 + virtual void setLightningSFXName(const std::string& name); // 0x101560B0 + virtual const std::string& getLightningSFXName() const; // 0x10156150 + virtual void setLightningSegments(int segments); // 0x10156160 + virtual int getLightningSegments() const; // 0x10156180 + virtual void setLightningGroundPenetration(float depth); // 0x10156190 + virtual float getLightningGroundPenetration() const; // 0x101561A0 + virtual void setInFadeSegments(float segments); // 0x101561B0 + virtual float getInFadeSegments() const; // 0x101561C0 + virtual void setOutFadeSegments(float segments); // 0x101561D0 + virtual float getOutFadeSegments() const; // 0x101561E0 + + // The engine heap: the factory allocates with engineAlloc and the deleting destructor frees + // with engineFree (0x101575F0 -> sub_1005F360). + static void operator delete(void* memory); + +private: + LightningManager(const LightningManager&); + LightningManager& operator=(const LightningManager&); + + bool initResources(); // 0x101561F0 + void lookupShaderParameters(); // 0x10155CB0 + void releaseResources(); // 0x10156340 + void releaseSoundEffect(); // 0x10156060 + void releaseShaderParameters(); // 0x10155D30 [INFERRED] name, unreachable in 1.50 + void releaseTexture(); // 0x10156310 [INFERRED] name, unreachable in 1.50 + void processPendingLightning(); // 0x10156D40 + void createStrike(const Vec2& offset); // 0x10156C60 + void buildBoltBuffer(int buffer); // 0x10155DA0 + void drawStrike(const LightningStrike& strike); // 0x10156920 + bool setStrikeShaderConstants(const LightningStrike& strike); // 0x10156420 + + // data, in shipped order + int m_refCount; // +0x04 + dx9rend::Effect* m_effect; // +0x08 "Shaders/Lightning" + void* m_vertexDeclaration; // +0x0C + void* m_vertexBuffers[3]; // +0x10 202 vertices of 24 bytes each + dx9rend::ShaderParameter* m_paramWorldViewProj; // +0x1C WORLDVIEWPROJ + dx9rend::ShaderParameter* m_paramColor; // +0x20 LIGHTNINGCOLOR + dx9rend::ShaderParameter* m_paramTexture; // +0x24 TEXTURE + dx9rend::EngineTexture* m_texture; // +0x28 common/textures/lightning + float m_duration; // +0x2C lightningDuration, 0.15 + float m_sfxDelay; // +0x30 lightningSFXDelay, 5 + std::vector m_strikes; // +0x34 + IBfSound* m_sound; // +0x44 the "Sound" singleton + std::string m_sfxName; // +0x48 lightningSFXName + world::IObjectTemplate* m_sfxTemplate; // +0x64 referenced Sound template + ISound* m_sfxSounds[3]; // +0x68 one thunder per bolt buffer + Vec2 m_scale; // +0x74 lightningScale, (1, 300) + float m_pertubation; // +0x7C lightningPertubation, 10 + Vec4 m_color; // +0x80 lightningColor, (1, 1, 1, 1) + float m_blendOutTime; // +0x90 lightningBlendOutTime, 0.1 + float m_skyBlendOutTime; // +0x94 skyBlendOutTime, 0.1 + int m_segments; // +0x98 lightningSegments, 100 + float m_groundPenetration; // +0x9C lightningGroundPenetration, 0 + float m_inFadeSegments; // +0xA0 inFadeSegments, 0 + float m_outFadeSegments; // +0xA4 outFadeSegments, 0 + std::vector m_pending; // +0xA8 addLightning's queue + double m_time; // +0xB8 the lightning clock + double m_lastTime; // +0xC0 m_time at the previous update + int m_nextBuffer; // +0xC8 round-robin bolt buffer index +}; + +// dword_1024B928. ModuleGeom.cpp owns the definition; the console rows and WeatherManager read it. +extern IBase* g_LightningManager; + +// The factory registered under "dice.hfe.geom.LightningManager" (0x100B0BA4). +IBase* __fastcall createLightningManager(unsigned int iid, IBase* outer); + +} // namespace geom +} // namespace hfe +} // namespace dice + +#endif // BF2_IMAGE_RENDDX9 +#endif // BF2_GEOM_LIGHTNINGMANAGER_H diff --git a/Code/BF2/Geom/MeshOptimizer.cpp b/Code/BF2/Geom/MeshOptimizer.cpp new file mode 100644 index 000000000..a3b8b2c5a --- /dev/null +++ b/Code/BF2/Geom/MeshOptimizer.cpp @@ -0,0 +1,752 @@ +// Path: attested - "C:\dice\Projects\BF2Branches\Patch_1_50\Code\BF2\Geom\MeshOptimizer.cpp" +// appears verbatim in RendDX9.dll at 0x10221E70. +// Contents: the mesh-optimizer base, recovered from RendDX9.dll (PE, symbols stripped). +// Reads and allocations are unchecked, as shipped: the file path expects well-formed mesh content. + +#ifdef BF2_IMAGE_RENDDX9 + +#include "MeshOptimizer.h" + +#include "../RendDX9/RendDX9Base.h" +#include "../Core/StringUtil.h" // extractFileName / extractFilePath (sub_10075190 / sub_100751A0) +#include "../IO/Stream/IStream.h" +#include "../IO/File/IFileSystem.h" // io::FileInfo, findFiles (+0x34) +#include "../../RendDX9Abi/BfMemory.h" +#include "../../RendDX9Abi/Frontier.h" +#include "../../RendDX9Abi/PluginEntry.h" +#include + +#include +#include +#include +#include +#include + +namespace dice { +namespace hfe { + +namespace dx9rend { +extern void* g_rendererBase; // dword_1023B970 +IDirect3DVertexDeclaration9* vertexDeclarationD3D(void* wrapper); // BufferManager.cpp +} // namespace dx9rend + +namespace geom { + +namespace { + +// dword_1021AE54, the optimizer interface id. +const unsigned int kIID_IGeometryOptimizer = 0x138E7u; + +// D3DLOCK_NOSYSLOCK, the lock flag every optimizer buffer lock passes. +const unsigned long kLockNoSysLock = 0x800u; + +// D3DXMESHOPT_STRIPREORDER. The optimize flags only ever hold D3DXMESHOPT_VERTEXCACHE, so the +// strip branches compare against a value they never see. +const unsigned int kMeshOptStripReorder = 0x08000000u; + +renddx9abi::HostFileManager* files() +{ + return ::dice::hfe::fileManager; // dword_10244AC4 +} + +// A length-prefixed name: count, then the bytes, staged through a NUL-terminated operator new[] +// copy as shipped. +void readName(renddx9abi::HostStream* stream, std::string& out) +{ + unsigned int length; + stream->read(&length, 4); + char* const raw = new char[length + 1]; + stream->read(raw, length); + raw[length] = 0; + out = std::string(raw); + delete[] raw; +} + +void writeName(renddx9abi::HostStream* stream, const std::string& name) +{ + unsigned int length = static_cast(name.size()); + stream->write(&length, 4); + stream->write(name.data(), length); +} + +// The final path component without its last extension: the shared stem helper (Core +// extractFileNameWithoutExt; RendDX9 carries its own copy), extractFileName then rfind('.'). +std::string fileStemOf(const std::string& path) +{ + const std::string name = extractFileName(path); + const std::string::size_type dot = name.rfind('.'); + if (dot == std::string::npos) + return name; + return name.substr(0, dot); +} + +} // anonymous namespace + + +MeshOptimizerMaterial::MeshOptimizerMaterial() + : alphaMode(0), vertexStart(0), indexStart(0), indexCount(0), vertexCount(0), + unused5C(0), unused60(0) +{ + std::memset(&bounds, 0, sizeof(bounds)); + bounds.dirty = 1; +} + +void MeshOptimizerMaterial::clear() +{ + shaderFile.clear(); + technique.clear(); + std::vector().swap(textures); + alphaMode = 0; + vertexStart = 0; + indexStart = 0; + indexCount = 0; + vertexCount = 0; + unused5C = 0; + unused60 = 0; + std::memset(&bounds, 0, sizeof(bounds)); +} + +BundledMeshOptimizerLod::BundledMeshOptimizerLod() + : nodeCount(0) +{ + std::memset(&bounds, 0, sizeof(bounds)); + bounds.dirty = 1; +} + +StaticMeshOptimizerLod::StaticMeshOptimizerLod() + : matrixCount(0) +{ + std::memset(&bounds, 0, sizeof(bounds)); + bounds.dirty = 1; +} + +void StaticMeshOptimizerLod::clear() +{ + matrixCount = 0; + std::vector().swap(matrices); + std::memset(&bounds, 0, sizeof(bounds)); + std::vector().swap(strips); +} + + +// PE 0x101B6CC0. The two folder strings are assigned from temporaries after construction. +// [CHOSEN, not recovered] The header, buffer and flag scalars start at zero; retail leaves +// +0x44..+0x7C and +0xC0..+0xC8 unset until a file is read. m_vertexDeclaration is zeroed by the +// shipped constructor too. +MeshOptimizer::MeshOptimizer() + : m_refCount(1), m_byte08(0), + m_head(0), m_version(0), m_deviceId(0), m_driverVersion(0), m_header54(0), m_headerFlag(0), + m_elementCount(0), m_elements(0), m_primitiveType(0), m_vertexStride(0), m_vertexCount(0), + m_indexCount(0), m_u2(0), m_vertexData(0), m_indexData(0), m_vertexDeclaration(0), + m_unusedC0(0), m_unusedC4(0), m_optimizeFlags(0) +{ + m_shaderFolder = std::string("Shaders/"); + m_meshFolder = std::string("Meshes/"); +} + +// PE 0x101B6DA0. Only the members are destroyed: the element, vertex and index arrays and the +// vertex declaration are not released here. +MeshOptimizer::~MeshOptimizer() +{ +} + +void MeshOptimizer::operator delete(void* memory) +{ + ::renddx9abi::engineFree(memory); +} + +// PE 0x1000CB20, the shared IBase increment. +void MeshOptimizer::addRef() +{ + ++m_refCount; +} + +// PE 0x101A9A10, the shared count getter. +int MeshOptimizer::getRef() +{ + return m_refCount; +} + +// PE 0x101B8E50. The last release runs the virtual deleting destructor (slot +0x20). +int MeshOptimizer::release() +{ + const int remaining = --m_refCount; + if (!remaining) + delete this; + return remaining; +} + +// PE 0x10134E70, shared by all three tables. +void* MeshOptimizer::queryInterface(unsigned int iid) const +{ + if (iid == 1u || iid == kIID_IGeometryOptimizer) + return const_cast(this); + return 0; +} + +// PE 0x100ED3B0, the shared `xor eax, eax` body. +unsigned int MeshOptimizer::getClassId() const +{ + return 0; +} + +// PE 0x101B5D10. GeometryTemplateManager::runOptimizers' only call; it does no work. +bool MeshOptimizer::optimize() +{ + return false; +} + +// PE 0x101B6940. Unreachable in 1.50: no code or data references. The file list is +// IFileManager::findFiles(directory, true) (+0x34); a zero-size entry is skipped; the extension is +// found anywhere in the name (find(ext, 0, size)), then the plain file name must equal the stem +// plus the extension. Matches are keyed by `directory + name` in a string map whose value stays 0. +bool MeshOptimizer::optimizeDirectory(const std::string& directory, const std::string& extension) +{ + std::list listed; + files()->findFiles(directory, true, listed); + std::map paths; + for (std::list::const_iterator it = listed.begin(); it != listed.end(); ++it) + { + if (it->size == 0) + continue; + if (it->name.find(extension.c_str(), 0, extension.size()) == std::string::npos) + continue; + const std::string stem = fileStemOf(it->name); + const std::string fileName = extractFileName(it->name); + bool matches = false; + if (std::strncmp(stem.c_str(), "gpu_", 4) != 0) + matches = fileName.compare(std::string(stem) += extension) == 0; + if (matches) + { + const std::string path = std::string(directory) += it->name; + paths.insert(std::pair(path, 0)); + } + } + std::map::iterator path = paths.begin(); + if (path == paths.end() || !optimizeFile(path->first)) + return false; + // Shipped: every later file is optimized but its result is discarded. + for (++path; path != paths.end(); ++path) + optimizeFile(path->first); + return true; +} + +// PE 0x101B5E30 +bool MeshOptimizer::optimizeFile(const std::string& path) +{ + const bool result = processFile(path); + if (m_vertexDeclaration) + dx9rend::vertexDeclarationRelease(m_vertexDeclaration); + m_vertexDeclaration = 0; + return result; +} + +// PE 0x101B5F90. The output is `/gpu_`. An existing, newer output is only +// re-read for its header; otherwise the source is processed. A source that cannot be opened +// counts as processed, so the output is then written from the current state. +bool MeshOptimizer::processFile(const std::string& path) +{ + m_sourcePath = path; + dx9rend::pathReplaceSeparators(m_sourcePath, '/'); + const std::string fileName = extractFileName(m_sourcePath); + const std::string directory = extractFilePath(m_sourcePath, '/'); + m_outputPath = directory + std::string("gpu_") + fileName; + + if (files()->fileExists(renddx9abi::makeHostString(m_outputPath)) + && files()->compareFileTime(renddx9abi::makeHostString(m_outputPath), + renddx9abi::makeHostString(m_sourcePath))) + { + if (!checkOutput()) + return false; + } + else if (!processSource()) + { + return false; + } + + writeOutput(); + return true; +} + +// PE 0x101B5D20. The read sequence after the header; the result is buildMeshes'. +bool MeshOptimizer::loadBody(renddx9abi::HostStream* stream) +{ + readVertexData(stream); + readIndexTail(stream); + readGeometry(stream); + readMaterials(stream); + if (!buildMeshes()) + return false; + optimizeMeshes(); + return true; +} + +// PE 0x101B5E90. Opens the source for reading (mode 2); a missing file answers true. +bool MeshOptimizer::processSource() +{ + renddx9abi::HostStream* const stream = files()->open( + renddx9abi::makeHostString(m_sourcePath), static_cast(2), + static_cast(0), 0); + bool result = true; + if (!stream) + return result; + if (!readHeader(stream)) + { + stream->release(); + return false; + } + if (!loadBody(stream)) + result = false; + stream->release(); + return result; +} + +// PE 0x101B5EF0. A missing output answers true; an output whose header no longer matches the +// adapter sends the source through processSource. +bool MeshOptimizer::checkOutput() +{ + renddx9abi::HostStream* const stream = files()->open( + renddx9abi::makeHostString(m_outputPath), static_cast(2), + static_cast(0), 0); + if (!stream) + return true; + if (!readOutputHeader(stream)) + { + stream->release(); + return false; + } + stream->release(); + return processSource(); +} + +// PE 0x101B5F40. Opens the output for writing (mode 0, access 2). +void MeshOptimizer::writeOutput() +{ + renddx9abi::HostStream* const stream = files()->open( + renddx9abi::makeHostString(m_outputPath), static_cast(0), + static_cast(2), 0); + if (!stream) + return; + writeHeader(stream); + writeGeometry(stream); + writeMaterials(stream); + stream->release(); +} + +// PE 0x101B6100. Head 0 and version 3 or later are required. The adapter is the first identifier +// the renderer enumerated; a file already stamped with its device id needs no work. +bool MeshOptimizer::readHeader(renddx9abi::HostStream* stream) +{ + const D3DADAPTER_IDENTIFIER9* const adapter = + static_cast(dx9rend::g_rendererBase)->adapterInfo.data(); + stream->read(&m_head, 4); + stream->read(&m_version, 4); + if (m_head != 0 || m_version < 3) + return false; + stream->read(&m_deviceId, 4); + stream->read(&m_driverVersion, 4); + stream->read(&m_header54, 4); + stream->read(&m_headerFlag, 1); + if (adapter->DeviceId == m_deviceId) + return false; + m_deviceId = adapter->DeviceId; + // movzx of the word at identifier +0x422: the high half of DriverVersion.LowPart. + m_driverVersion = static_cast(adapter->DriverVersion.LowPart >> 16); + return true; +} + +// PE 0x101B5D70, a tail jump to slot +0x24. +bool MeshOptimizer::readOutputHeader(renddx9abi::HostStream* stream) +{ + return readHeader(stream); +} + +// PE 0x101B6520. LOD counts, the vertex declaration, then the vertex and index arrays. Earlier +// arrays are not freed; the element array is kept for writeGeometry. +void MeshOptimizer::readVertexData(renddx9abi::HostStream* stream) +{ + unsigned int geometryCount; + stream->read(&geometryCount, 4); + m_lodCounts.resize(geometryCount, 0); + for (unsigned int i = 0; i < geometryCount; ++i) + stream->read(&m_lodCounts[i], 4); + + stream->read(&m_elementCount, 4); + m_elements = new MeshOptimizerVertexElement[m_elementCount]; + for (unsigned int i = 0; i < m_elementCount; ++i) + stream->read(&m_elements[i], 8); + m_vertexDeclaration = dx9rend::vertexDeclarationCreate(m_elements); + + stream->read(&m_primitiveType, 4); + stream->read(&m_vertexStride, 4); + stream->read(&m_vertexCount, 4); + m_vertexData = new unsigned char[m_vertexStride * m_vertexCount]; + if (m_vertexData) + stream->read(m_vertexData, m_vertexStride * m_vertexCount); + + stream->read(&m_indexCount, 4); + m_indexData = new unsigned short[m_indexCount]; + if (m_indexData) + stream->read(m_indexData, m_indexCount * 2); +} + +// PE 0x101B5D80 +void MeshOptimizer::readIndexTail(renddx9abi::HostStream* stream) +{ + stream->read(&m_u2, 4); +} + +// PE 0x101B5DA0, an empty `ret 4`: the base reads no per-LOD geometry. +void MeshOptimizer::readGeometry(renddx9abi::HostStream*) +{ +} + +// PE 0x101B6E80. Sizes the material and LOD tables from the LOD counts, then reads each LOD's +// material count and materials. Each LOD record and each material is cleared before it is read. +void MeshOptimizer::readMaterials(renddx9abi::HostStream* stream) +{ + const unsigned int geometryCount = static_cast(m_lodCounts.size()); + m_materials.resize(geometryCount, std::vector()); + m_lods.resize(geometryCount, MeshOptimizerLodVector()); + + for (unsigned int geometry = 0; geometry < geometryCount; ++geometry) + { + const unsigned int lodCount = m_lodCounts[geometry]; + m_materials[geometry].resize(lodCount, MeshOptimizerMaterialVector()); + const MeshOptimizerLod prototype = { 0, 0, 0, 0, 0 }; + m_lods[geometry].resize(lodCount, prototype); + + for (unsigned int lodIndex = 0; lodIndex < lodCount; ++lodIndex) + { + MeshOptimizerLod& lod = m_lods[geometry][lodIndex]; + lod.mesh = 0; + lod.optimizedMesh = 0; + lod.optimizeFlags = 0; + lod.alphaMode = 0; + lod.materialCount = 0; + + unsigned int materialCount; + stream->read(&materialCount, 4); + m_materials[geometry][lodIndex].resize(materialCount, MeshOptimizerMaterial()); + for (unsigned int index = 0; index < materialCount; ++index) + { + MeshOptimizerMaterial& material = m_materials[geometry][lodIndex][index]; + material.clear(); + readMaterial(stream, material, lod); + } + } + } +} + +// PE 0x101B6760. The LOD adopts the first alpha mode that differs from its own unless it already +// holds 1; any adoption sets the vertex-cache optimize flag. The two trailing dwords are skipped. +void MeshOptimizer::readMaterial(renddx9abi::HostStream* stream, MeshOptimizerMaterial& material, + MeshOptimizerLod& lod) +{ + stream->read(&material.alphaMode, 4); + if (lod.alphaMode != material.alphaMode && lod.alphaMode != 1) + { + lod.alphaMode = material.alphaMode; + m_optimizeFlags = 0x04000000u; + } + + readName(stream, material.shaderFile); + readName(stream, material.technique); + + int textureCount; + stream->read(&textureCount, 4); + material.textures.resize(textureCount); + for (int i = 0; i < textureCount; ++i) + readName(stream, material.textures[i]); + + stream->read(&material.vertexStart, 4); + stream->read(&material.indexStart, 4); + stream->read(&material.indexCount, 4); + stream->read(&material.vertexCount, 4); + stream->skip(4); + stream->skip(4); +} + +// PE 0x101B5DB0, `xor al, al`: the base builds nothing and refuses the file. +bool MeshOptimizer::buildMeshes() +{ + return false; +} + +// PE 0x101B5DC0, an empty `ret`. +void MeshOptimizer::optimizeMeshes() +{ +} + +// PE 0x101B5DD0 +void MeshOptimizer::writeHeader(renddx9abi::HostStream* stream) +{ + stream->write(&m_head, 4); + stream->write(&m_version, 4); + stream->write(&m_deviceId, 4); + stream->write(&m_driverVersion, 4); + stream->write(&m_header54, 4); + stream->write(&m_headerFlag, 1); +} + +// PE 0x101B6650. The element array is freed after it is written and the pointer kept. The LOD +// count vector is resized to its own size, as shipped. +void MeshOptimizer::writeGeometry(renddx9abi::HostStream* stream) +{ + unsigned int geometryCount = static_cast(m_lodCounts.size()); + stream->write(&geometryCount, 4); + m_lodCounts.resize(geometryCount, 0); + for (unsigned int i = 0; i < geometryCount; ++i) + stream->write(&m_lodCounts[i], 4); + + stream->write(&m_elementCount, 4); + for (unsigned int i = 0; i < m_elementCount; ++i) + stream->write(&m_elements[i], 8); + delete[] m_elements; + + stream->write(&m_primitiveType, 4); + stream->write(&m_vertexStride, 4); + stream->write(&m_vertexCount, 4); + stream->write(m_vertexData, m_vertexStride * m_vertexCount); + stream->write(&m_indexCount, 4); + stream->write(m_indexData, m_indexCount * 2); +} + +// PE 0x101B6420. Every LOD's material count, then its materials; the index base runs across all +// geometries and LODs. +void MeshOptimizer::writeMaterials(renddx9abi::HostStream* stream) +{ + unsigned int indexBase = 0; + const unsigned int geometryCount = static_cast(m_lodCounts.size()); + for (unsigned int geometry = 0; geometry < geometryCount; ++geometry) + { + const unsigned int lodCount = m_lodCounts[geometry]; + for (unsigned int lodIndex = 0; lodIndex < lodCount; ++lodIndex) + { + MeshOptimizerMaterialVector& materials = m_materials[geometry][lodIndex]; + unsigned int materialCount = static_cast(materials.size()); + stream->write(&materialCount, 4); + for (unsigned int index = 0; index < materialCount; ++index) + writeMaterial(stream, materials[index], indexBase); + } + } +} + +// PE 0x101B61B0. The obsolete specular LUT name is reported and replaced, then every +// SpecularLUT_pow36 name is redirected to the absolute common texture. The two trailing dwords +// are written as zero. +void MeshOptimizer::writeMaterial(renddx9abi::HostStream* stream, MeshOptimizerMaterial& material, + unsigned int& indexBase) +{ + stream->write(&material.alphaMode, 4); + writeName(stream, material.shaderFile); + writeName(stream, material.technique); + + int textureCount = static_cast(material.textures.size()); + stream->write(&textureCount, 4); + for (int i = 0; i < textureCount; ++i) + { + std::string name(material.textures[i]); + if (name.find("default_sdgbmfbf_color_lut", 0, 26) != std::string::npos) + { + ::renddx9abi::logf("MeshOptimizer.cpp:533: Mesh %s has specular lut " + "default_sdgbmfbf_color_lut which is obsolete, please re-export", + m_sourcePath.c_str()); + name = "_SpecularLUT_pow36_"; + } + if (name.find("SpecularLUT_pow36", 0, 17) != std::string::npos) + name = "@@ABSOLUTE@@Common/Textures/SpecularLUT_pow36.dds"; + writeName(stream, name); + } + + unsigned int zero = 0; + stream->write(&material.vertexStart, 4); + material.indexStart = indexBase; + stream->write(&material.indexStart, 4); + stream->write(&material.indexCount, 4); + stream->write(&material.vertexCount, 4); + stream->write(&zero, 4); + stream->write(&zero, 4); + indexBase += material.indexCount; +} + +// The shared tail of both derived optimizeFile overrides. VC7.1's vector::clear also frees the +// storage. +void MeshOptimizer::releaseLodMeshes() +{ + const unsigned int geometryCount = static_cast(m_lodCounts.size()); + for (unsigned int geometry = 0; geometry < geometryCount; ++geometry) + { + MeshOptimizerLodVector& lods = m_lods[geometry]; + const unsigned int lodCount = m_lodCounts[geometry]; + for (unsigned int lodIndex = 0; lodIndex < lodCount; ++lodIndex) + { + MeshOptimizerLod& lod = lods[lodIndex]; + if (lod.optimizedMesh) + { + lod.optimizedMesh->Release(); + lod.optimizedMesh = 0; + } + if (lod.mesh) + { + lod.mesh->Release(); + lod.mesh = 0; + } + } + lods.clear(); + } + m_lodCounts.clear(); +} + +// PE 0x10132CC0 / 0x10135020. The vertex pass copies each LOD's optimized vertices, plus, for an +// alpha-mode-1 LOD, the raw vertices of the material StaticMeshOptimizer::buildMeshes left out of +// the D3DX mesh (materials[materialCount]). The index pass rebases each material's indices onto +// the LOD's first vertex start, from the strip buffers when the LOD was strip-optimized and from +// the optimized mesh otherwise. +template +void MeshOptimizer::repackBuffers(unsigned int stripIndexCount, + std::vector >& geometryLods) +{ + const unsigned int vertexBytes = m_vertexCount * m_vertexStride; + unsigned int indexTotal = m_indexCount; + if (stripIndexCount != 0 && stripIndexCount != m_indexCount) + indexTotal = stripIndexCount; +#if defined(_WIN32) + SYSTEM_INFO systemInfo; + ::GetSystemInfo(&systemInfo); // shipped: the result is never read +#endif + // [PLATFORM] The native ports have no GetSystemInfo; the call has no effect on the result. + + unsigned char* const vertices = new unsigned char[vertexBytes]; + unsigned char* vertexCursor = vertices; + unsigned int vertexOffset = 0; + const unsigned int geometryCount = static_cast(m_lodCounts.size()); + + for (unsigned int geometry = 0; geometry < geometryCount; ++geometry) + { + const unsigned int lodCount = m_lodCounts[geometry]; + for (unsigned int lodIndex = 0; lodIndex < lodCount; ++lodIndex) + { + MeshOptimizerLod& lod = m_lods[geometry][lodIndex]; + MeshOptimizerMaterialVector& materials = m_materials[geometry][lodIndex]; + unsigned int bytes = 0; + for (unsigned int index = 0; index < lod.materialCount; ++index) + bytes += materials[index].vertexCount * m_vertexStride; + + void* source; + lod.optimizedMesh->LockVertexBuffer(kLockNoSysLock, &source); + std::memcpy(vertexCursor, source, bytes); + vertexOffset += bytes; + vertexCursor += bytes; + lod.optimizedMesh->UnlockVertexBuffer(); + + if (lod.alphaMode == 1) + { + const unsigned int tail = materials[lod.materialCount].vertexCount * m_vertexStride; + std::memcpy(vertexCursor, m_vertexData + vertexOffset, tail); + vertexOffset += tail; + vertexCursor += tail; + } + } + } + + delete[] m_vertexData; + m_vertexData = vertices; + + unsigned short* const indices = new unsigned short[indexTotal]; + unsigned short* indexCursor = indices; + unsigned int indexOffset = 0; // bytes + + for (unsigned int geometry = 0; geometry < geometryCount; ++geometry) + { + const unsigned int lodCount = m_lodCounts[geometry]; + for (unsigned int lodIndex = 0; lodIndex < lodCount; ++lodIndex) + { + MeshOptimizerLod& lod = m_lods[geometry][lodIndex]; + MeshOptimizerMaterialVector& materials = m_materials[geometry][lodIndex]; + LodRecord& record = geometryLods[geometry][lodIndex]; + const unsigned int baseVertex = materials[0].vertexStart; + + if (lod.optimizeFlags == kMeshOptStripReorder) + { + // Dead in 1.50 (see kMeshOptStripReorder). Each strip buffer is rebased in place, + // copied, unlocked and released; its pointer stays in the record. + for (unsigned int index = 0; index < record.strips.size(); ++index) + { + IDirect3DIndexBuffer9* const strip = record.strips[index]; + D3DINDEXBUFFER_DESC description; + strip->GetDesc(&description); // shipped: never read + void* locked; + strip->Lock(0, 0, &locked, kLockNoSysLock); + unsigned short* const source = static_cast(locked); + const unsigned int bytes = materials[index].indexCount * 2; + for (unsigned int i = 0; i < materials[index].indexCount; ++i) + source[i] = static_cast( + source[i] + static_cast(baseVertex + - materials[index].vertexStart)); + std::memcpy(indexCursor, source, bytes); + indexOffset += bytes; + indexCursor += materials[index].indexCount; + strip->Unlock(); + strip->Release(); + } + continue; + } + + void* locked; + lod.optimizedMesh->LockIndexBuffer(kLockNoSysLock, &locked); + unsigned short* const source = static_cast(locked); + unsigned int end = 0; + unsigned int position = 0; + unsigned int bytes = 0; + for (unsigned int index = 0; index < lod.materialCount; ++index) + { + end += materials[index].indexCount; + bytes += materials[index].indexCount * 2; + for (; position < end; ++position) + source[position] = static_cast( + source[position] + static_cast(baseVertex + - materials[index].vertexStart)); + } + std::memcpy(indexCursor, source, bytes); + indexOffset += bytes; + indexCursor += end; + lod.optimizedMesh->UnlockIndexBuffer(); + + if (lod.alphaMode == 1) + { + // Shipped: the left-out material's index count is multiplied by m_u2, and only the + // product is checked against indexTotal; a refusal returns with the new index array + // neither published nor freed. + const unsigned int tail = materials[lod.materialCount].indexCount * m_u2; + if (tail > indexTotal) + return; + // [CHOSEN, not recovered] memory safety: retail copies `tail` indices from + // m_indexData + indexOffset / 2 to the cursor without checking either array's end; + // a copy that would leave either array takes the same refusal instead. + const unsigned int written = static_cast(indexCursor - indices); + if (tail > indexTotal - written || indexOffset / 2 > m_indexCount + || tail > m_indexCount - indexOffset / 2) + return; + std::memcpy(indexCursor, m_indexData + indexOffset / 2, tail * 2); + indexOffset += tail * 2; + indexCursor += tail; + } + } + } + + delete[] m_indexData; + m_indexData = indices; + m_indexCount = indexTotal; +} + +template void MeshOptimizer::repackBuffers( + unsigned int, std::vector >&); +template void MeshOptimizer::repackBuffers( + unsigned int, std::vector >&); + +} // namespace geom +} // namespace hfe +} // namespace dice + +#endif // BF2_IMAGE_RENDDX9 diff --git a/Code/BF2/Geom/MeshOptimizer.h b/Code/BF2/Geom/MeshOptimizer.h new file mode 100644 index 000000000..c0e50c6a8 --- /dev/null +++ b/Code/BF2/Geom/MeshOptimizer.h @@ -0,0 +1,231 @@ +// Path: [INFERRED] header beside MeshOptimizer.cpp, whose path is attested at RendDX9 0x10221E70. +// Shared base of the two mesh optimizers (dice.hfe.geom.GeometryOptimizer.*), recovered from +// RendDX9.dll 1.50 (PE only). Retail layout: 0x114 bytes, primary table 0x10221EB8 (22 slots), +// constructor 0x101B6CC0, destructor 0x101B6DA0. +// +// An optimizer rewrites one .staticMesh/.bundledMesh into a `gpu_` copy beside it: it reads the +// source, builds one D3DX mesh per LOD, vertex-cache optimizes it for the current adapter and +// writes the result with the adapter's device id in the header. In 1.50 nothing calls the file +// path: Renderer::initialize creates both optimizers, calls optimize() (which returns false) and +// releases them. The record types below are the in-memory form of the file's tables. + +#ifndef BF2_GEOM_MESHOPTIMIZER_H +#define BF2_GEOM_MESHOPTIMIZER_H + +#include "GeometryTemplateManager.h" +#include "MeshTemplate.h" + +#include "../../RendDX9Abi/HostFileAbi.h" + +#include +#include + +struct ID3DXMesh; +struct IDirect3DIndexBuffer9; + +namespace dice { +namespace hfe { +namespace geom { + +// One material record of a LOD, 0xA0 bytes in retail. The file stores the alpha mode, the two +// names, the texture list and the four range counts; the bounds are filled by +// StaticMeshOptimizer only. +struct MeshOptimizerMaterial +{ + // The prototype every resize copies (0x101B6FB0..0x101B701B): empty names, no textures and + // zero bounds with the dirty byte set. Retail leaves the alpha-mode and range dwords unset; + // [CHOSEN, not recovered] they start at zero (readMaterials clears every record anyway). + MeshOptimizerMaterial(); + + // The `rep stosd` over the whole record that readMaterials runs after the resize + // (0x101B7052). [CHOSEN, not recovered] The names and the texture vector are reset as objects + // instead of being overwritten with zero bytes; every scalar, including the bounds' dirty + // byte, ends at zero as in retail. + void clear(); + + std::string shaderFile; // +0x00 + std::string technique; // +0x1C + std::vector textures; // +0x38 + unsigned int alphaMode; // +0x48 + unsigned int vertexStart; // +0x4C + unsigned int indexStart; // +0x50 + unsigned int indexCount; // +0x54 + unsigned int vertexCount; // +0x58 + // [CHOSEN, not recovered] names: no instruction reads or writes these two dwords; the file's + // two trailing material dwords are skipped on read and written as zero. + unsigned int unused5C; // +0x5C + unsigned int unused60; // +0x60 + MeshBounds bounds; // +0x64 +}; + +// Per-LOD optimizer state, 0x14 bytes in retail. `alphaMode` summarizes the LOD's materials while +// they are read; `materialCount` is set by buildMeshes. +struct MeshOptimizerLod +{ + ID3DXMesh* mesh; // +0x00 D3DXCreateMesh output + ID3DXMesh* optimizedMesh; // +0x04 Optimize output + unsigned int optimizeFlags; // +0x08 + unsigned int alphaMode; // +0x0C + unsigned int materialCount; // +0x10 +}; + +// One D3DVERTEXELEMENT9 as stored in the file (8 bytes). +struct MeshOptimizerVertexElement +{ + unsigned short stream; + unsigned short offset; + unsigned char type; + unsigned char method; + unsigned char usage; + unsigned char usageIndex; +}; + +// BundledMeshOptimizer's per-LOD record, 0x50 bytes in retail. +struct BundledMeshOptimizerLod +{ + // The resize prototype (0x10133738..0x10133772): zero bounds with the dirty byte set and no + // strips. The node count is left unset there; [CHOSEN, not recovered] it starts at zero. + BundledMeshOptimizerLod(); + + unsigned int nodeCount; // +0x00 + MeshBounds bounds; // +0x04 + std::vector strips; // +0x40 one per material after strip conversion +}; + +// One 4x4 matrix as stored in the file. +struct MeshOptimizerMatrix +{ + float m[16]; +}; + +// StaticMeshOptimizer's per-LOD record, 0x60 bytes in retail. +struct StaticMeshOptimizerLod +{ + // The resize prototype (0x10135E65..0x10135EA8): no matrices, zero bounds with the dirty byte + // set, no strips. The matrix count is left unset there; [CHOSEN, not recovered] it starts at + // zero. + StaticMeshOptimizerLod(); + + // The `rep stosd` over the whole record that readGeometry runs after the resize (0x10135ED9). + // [CHOSEN, not recovered] The two vectors are reset as objects instead of being overwritten + // with zero bytes; the count and the bounds, including the dirty byte, end at zero. + void clear(); + + unsigned int matrixCount; // +0x00 + std::vector matrices; // +0x04 + MeshBounds bounds; // +0x14 + std::vector strips; // +0x50 one per material after strip conversion +}; + +typedef std::vector MeshOptimizerMaterialVector; +typedef std::vector MeshOptimizerLodVector; + +class MeshOptimizer : public IGeometryOptimizer +{ +public: + MeshOptimizer(); + + void addRef() override; // +0x00 0x1000CB20 + int getRef() override; // +0x04 0x101A9A10 + int release() override; // +0x08 0x101B8E50 + void* queryInterface(unsigned int iid) const override; // +0x0C 0x10134E70 + unsigned int getClassId() const override; // +0x10 0x100ED3B0 + bool optimize() override; // +0x14 0x101B5D10 + + // Processes `path`, then releases the vertex declaration. Returns processFile's result. + virtual bool optimizeFile(const std::string& path); // +0x18 0x101B5E30 + // Rewrites `path` into its `gpu_` copy unless that copy is newer and already matches the + // adapter. Returns false when reading failed. + virtual bool processFile(const std::string& path); // +0x1C 0x101B5F90 + virtual ~MeshOptimizer(); // +0x20 0x101B8E70 + + // Optimizes every non-empty `` file below `directory` (recursive, `gpu_` + // stems skipped) through optimizeFile. Only the first file's result decides the answer; an + // empty set answers false. Non-virtual; unreachable in 1.50. [INFERRED] name. + bool optimizeDirectory(const std::string& directory, const std::string& extension); + // Reads the file header. True when the file must be (re)optimized for this adapter; the + // device id and driver version are then replaced with the adapter's. + virtual bool readHeader(renddx9abi::HostStream* stream); // +0x24 0x101B6100 + // The header check applied to an existing `gpu_` copy. + virtual bool readOutputHeader(renddx9abi::HostStream* stream); // +0x28 0x101B5D70 + virtual void readVertexData(renddx9abi::HostStream* stream); // +0x2C 0x101B6520 + virtual void readIndexTail(renddx9abi::HostStream* stream); // +0x30 0x101B5D80 + virtual void readGeometry(renddx9abi::HostStream* stream); // +0x34 0x101B5DA0 + virtual void readMaterials(renddx9abi::HostStream* stream); // +0x38 0x101B6E80 + virtual void readMaterial(renddx9abi::HostStream* stream, MeshOptimizerMaterial& material, + MeshOptimizerLod& lod); // +0x3C 0x101B6760 + // Creates one D3DX mesh per LOD. False refuses the file. + virtual bool buildMeshes(); // +0x40 0x101B5DB0 + virtual void optimizeMeshes(); // +0x44 0x101B5DC0 + virtual void writeHeader(renddx9abi::HostStream* stream); // +0x48 0x101B5DD0 + virtual void writeGeometry(renddx9abi::HostStream* stream); // +0x4C 0x101B6650 + virtual void writeMaterials(renddx9abi::HostStream* stream); // +0x50 0x101B6420 + // Writes one material; its index start becomes `indexBase`, which then advances by the + // material's index count. + virtual void writeMaterial(renddx9abi::HostStream* stream, MeshOptimizerMaterial& material, + unsigned int& indexBase); // +0x54 0x101B61B0 + + // Objects come from the engine heap: the factories use engineAlloc and the deleting + // destructors free through operator delete (sub_1005F360). + static void operator delete(void* memory); + +protected: + // The release loop shared by both derived optimizeFile overrides: + // releases every LOD's optimized and source mesh, then clears the per-geometry LOD vectors and + // the LOD counts. + void releaseLodMeshes(); + + // The repack both derived optimizeMeshes bodies end with (0x10132CC0 for BundledMeshOptimizer, + // 0x10135020 for StaticMeshOptimizer; the bodies differ only in the derived offsets). Gathers + // every LOD's optimized vertices and indices into new staging arrays, then replaces + // m_vertexData, m_indexData and m_indexCount. `stripIndexCount` is the derived strip total; + // `geometryLods` holds the derived LOD records with their strip index buffers. + template + void repackBuffers(unsigned int stripIndexCount, + std::vector >& geometryLods); + + int m_refCount; // +0x04 + unsigned char m_byte08; // +0x08 [CHOSEN, not recovered] name; only the constructor writes it + std::string m_sourcePath; // +0x0C + std::string m_outputPath; // +0x28 + unsigned int m_head; // +0x44 + unsigned int m_version; // +0x48 + unsigned int m_deviceId; // +0x4C + unsigned int m_driverVersion; // +0x50 + unsigned int m_header54; // +0x54 + unsigned char m_headerFlag; // +0x58 + unsigned int m_elementCount; // +0x5C + MeshOptimizerVertexElement* m_elements; // +0x60 operator new[] + unsigned int m_primitiveType; // +0x64 4 list, 5 after strip conversion + unsigned int m_vertexStride; // +0x68 + unsigned int m_vertexCount; // +0x6C + unsigned int m_indexCount; // +0x70 + unsigned int m_u2; // +0x74 + unsigned char* m_vertexData; // +0x78 operator new[] + unsigned short* m_indexData; // +0x7C operator new[] + void* m_vertexDeclaration; // +0x80 BufferManager declaration wrapper + std::vector m_lodCounts; // +0x84 LODs per geometry + std::vector m_lods; // +0x94 [geometry][lod] + std::string m_stringA4; // +0xA4 [CHOSEN, not recovered] name; constructed and destroyed only + unsigned int m_unusedC0; // +0xC0 [CHOSEN, not recovered] name; never accessed + unsigned int m_unusedC4; // +0xC4 [CHOSEN, not recovered] name; never accessed + unsigned int m_optimizeFlags; // +0xC8 only ever 0x04000000 (D3DXMESHOPT_VERTEXCACHE) + std::vector > m_materials; // +0xCC [geometry][lod][material] + std::string m_shaderFolder; // +0xDC "Shaders/" + std::string m_meshFolder; // +0xF8 "Meshes/" + +private: + bool loadBody(renddx9abi::HostStream* stream); // 0x101B5D20 + bool processSource(); // 0x101B5E90 + bool checkOutput(); // 0x101B5EF0 + void writeOutput(); // 0x101B5F40 + + MeshOptimizer(const MeshOptimizer&); + MeshOptimizer& operator=(const MeshOptimizer&); +}; + +} // namespace geom +} // namespace hfe +} // namespace dice + +#endif // BF2_GEOM_MESHOPTIMIZER_H diff --git a/Code/BF2/Geom/MeshTemplate.cpp b/Code/BF2/Geom/MeshTemplate.cpp index 55e91243e..1e2ce2432 100644 --- a/Code/BF2/Geom/MeshTemplate.cpp +++ b/Code/BF2/Geom/MeshTemplate.cpp @@ -7,11 +7,13 @@ #ifdef BF2_IMAGE_RENDDX9 #include "MeshTemplate.h" +#include "../RendDX9/RendDX9Math.h" // rendmath::unitScale (sub_1007B220) #include "../../RendDX9Abi/BfMemory.h" #include "../../RendDX9Abi/Frontier.h" #include "../IO/Stream/IStream.h" +#include #include #include #include @@ -31,7 +33,7 @@ namespace dx9rend { extern void* g_bufferManager; // dword_1023B978 void* createVertexBuffer(void* bufferManager, unsigned int count, unsigned int stride, - const vc71::string& name, unsigned int usage); + const std::string& name, unsigned int usage); void* vertexBufferLock(void* wrapper, unsigned int offsetVerts, unsigned int countVerts, unsigned int flags); bool vertexBufferUnlock(void* wrapper); @@ -72,162 +74,11 @@ const unsigned int kCID_MeshTemplate = 0x870CA650u; // PE this is a file-scope `const std::string` at 0x10263DD4, constructed by the static initialiser // at 0x101D5760 and shared with at least SkinnedMeshTemplate::load (0x1010E840) and three other // bodies; the concatenation there is `path + + name`. Held as a literal rather than as a -// namespace-scope vc71::string because only the bytes are observable and a dynamically initialised +// namespace-scope std::string because only the bytes are observable and a dynamically initialised // string object in a DLL would add a static-init ordering dependency this file does not need. const char kMeshesSubDirectory[] = "Meshes/"; -// Returns unit scale for the base template's uncompressed positions. - -const Vec3& unitScale() -{ - // Constant-initialised, so the current toolchain emits no guard. The retail guard exists only - // because dice wrote a constructor call; the published value is identical. - static Vec3 value = { 1.0f, 1.0f, 1.0f }; - return value; -} - - -// std::vector::resize(n, value) - sub_10192790, plus the _Insert_n it tail-calls (sub_1003A450) -// reduced to the append case, which is the only one resize reaches. This is the instantiation the -// MeshTemplate.cpp translation unit itself emits, so it lives here rather than in Vc71Vector.h -// (which models the host's vector as a NON-owning view and has no resize). - -// The layout is the VC7.1 four-pointer shape: +0 allocator, +4 _First, +8 _Last, +12 _End. - -unsigned int vectorIntSize(const vc71::vector_layout& v) -{ - return v.first ? static_cast((v.last - v.first) >> 2) : 0u; -} - -unsigned int vectorIntCapacity(const vc71::vector_layout& v) -{ - return v.first ? static_cast((v.end - v.first) >> 2) : 0u; -} - -// sub_1003A450, the `_Where == end()` arm. The two 0x3FFFFFFF tests are the shipped _Xlen guards -// (sub_100EFD60); VC7.1's _Xlen throws std::length_error, so this one does too. -void vectorIntAppendN(vc71::vector_layout& v, unsigned int count, int value) -{ - if (!count) - return; - - const unsigned int size = vectorIntSize(v); - if (0x3FFFFFFFu - size < count) - throw std::length_error("vector too long"); - - const unsigned int capacity = vectorIntCapacity(v); - if (capacity >= count + size) - { - // Room already reserved: construct in place and publish. - int* const at = reinterpret_cast(v.last); - for (unsigned int i = 0; i < count; ++i) - at[i] = value; - v.last += 4 * count; - return; - } - - // Grow: half again, clamped up to what was actually asked for. - unsigned int newCapacity = (0x3FFFFFFFu - (capacity >> 1) >= capacity) - ? capacity + (capacity >> 1) - : 0u; - if (newCapacity < count + size) - newCapacity = count + size; - - char* const buffer = static_cast(::renddx9abi::engineAlloc(4 * newCapacity)); - if (size) - ::memcpy(buffer, v.first, 4 * size); - int* const tail = reinterpret_cast(buffer) + size; - for (unsigned int i = 0; i < count; ++i) - tail[i] = value; - - if (v.first) - ::renddx9abi::engineFree(v.first); - - v.end = buffer + 4 * newCapacity; - v.last = buffer + 4 * (size + count); - v.first = buffer; -} - -// sub_10192790 itself. The shrink arm's `memmove(first + n, last, 0)` moves zero bytes - it is the -// std::copy inside erase(begin() + n, end()) for a trivial element - so all it does is retract _Last. -void vectorIntResize(vc71::vector_layout& v, unsigned int n, int value) -{ - const unsigned int size = vectorIntSize(v); - if (size >= n) - { - if (v.first && n < static_cast((v.last - v.first) >> 2)) - v.last = v.first + 4 * n; - return; - } - vectorIntAppendN(v, n - size, value); -} - - -// Material-map nodes are 24 bytes: links, unsigned/float pair, color, then nil flag. -// Construction leaves sentinel value bytes and the allocator word untouched. - -const unsigned int kMaterialNodeSize = 0x18u; - -bool materialNodeIsNil(const vc71::map_node* node) -{ - return reinterpret_cast(node)[kMaterialNodeSize - 3] != 0; -} - -// sub_100EB100 (_Buynode) followed by the five stores the constructor makes on its result. The -// `if (p)` / `if (p != -4)` / `if (p != -8)` tests in the PE are MSVC's placement-new null guards -// around _Alptr.construct(&_Left/_Parent/_Right, 0); they are unreachable in practice and the null -// link stores below are the whole of their effect. -void materialMapInit(vc71::map_layout& m) -{ - unsigned char* const raw = - static_cast(::renddx9abi::engineAlloc(kMaterialNodeSize)); - vc71::map_node* const node = reinterpret_cast(raw); - - node->left = 0; - node->parent = 0; - node->right = 0; - raw[kMaterialNodeSize - 4] = 1; // _Color = _Black - raw[kMaterialNodeSize - 3] = 0; // _Isnil = false ... which the constructor then overrides: - - m.head = node; - raw[kMaterialNodeSize - 3] = 1; // the header IS the nil node - node->parent = node; - node->left = node; - node->right = node; - m.size = 0; -} - -// sub_100EB1A0 - VC7.1 _Tree::_Erase(_Root): recurse into the right subtree, free this node, then -// continue down the left side. The node being freed is the one the loop entered with, which is why -// the retail loop carries two cursors. -void materialEraseSubtree(vc71::map_node* root) -{ - vc71::map_node* doomed = root; - for (vc71::map_node* node = root; !materialNodeIsNil(node); doomed = node) - { - materialEraseSubtree(node->right); - node = node->left; - ::renddx9abi::engineFree(doomed); - } -} - - -// sub_100ED1C0 - _Destroy(_First, _Last) for the vector> at +0x60: free each inner -// vector's buffer and blank its _First/_Last/_End. The inner allocator word is left alone, matching -// the outer object's own constructor. - -void destroyInnerVectors(vc71::vector_layout* first, vc71::vector_layout* last) -{ - for (vc71::vector_layout* v = first; v != last; ++v) - { - if (v->first) - ::renddx9abi::engineFree(v->first); - v->first = 0; - v->last = 0; - v->end = 0; - } -} // sub_100E7180 - corner `index` of the axis-aligned box, as three separate float stores into the @@ -254,19 +105,21 @@ void meshBoundsCorner(const MeshBounds& bounds, Vec3& out, int index) } // anonymous namespace -// Expands bounds to include point, testing each maximum before its minimum. -// Always marks derived bounds dirty. +// The same retail function as RendDX9Math.h's rendmath::expand (RendDX9's +// LocalBoundingBox::expand copy), not a separate one: MeshBounds is that 60-byte record under its +// RendDX9 name, with min, max and the dirty byte at the same offsets. Expands bounds to include +// point, testing each maximum before its minimum, and always marks the derived bounds dirty. void meshBoundsExpand(MeshBounds& bounds, const Vec3& point) { - if (point.x > bounds.max.x) bounds.max.x = point.x; - if (point.x < bounds.min.x) bounds.min.x = point.x; - if (point.y > bounds.max.y) bounds.max.y = point.y; - if (point.y < bounds.min.y) bounds.min.y = point.y; - if (point.z > bounds.max.z) bounds.max.z = point.z; - if (point.z < bounds.min.z) bounds.min.z = point.z; - bounds.dirty = 1; + rendmath::expand(reinterpret_cast(bounds), point); } +static_assert(sizeof(MeshBounds) == sizeof(LocalBoundingBox), "MeshBounds is LocalBoundingBox"); +static_assert(offsetof(MeshBounds, min) == offsetof(LocalBoundingBox, m_min) + && offsetof(MeshBounds, max) == offsetof(LocalBoundingBox, m_max) + && offsetof(MeshBounds, dirty) == offsetof(LocalBoundingBox, m_derivedDataDirty), + "meshBoundsExpand hands MeshBounds to rendmath::expand as a LocalBoundingBox"); + // derive originRadius, center, radius and extent from min/max, then clear dirty. // Both radii are the largest corner distance, not half a diagonal, and both loops run all eight @@ -313,6 +166,7 @@ void meshBoundsFinalize(MeshBounds& bounds) // the OLD on-disk form: one 36-byte block straight over min, max, the two radii and // the dirty dword, then dirty is forced back to 1. Nothing is finalised and the read result is // ignored; the answer is an unconditional true. +// PE 0x10191E50 bool meshBoundsReadLegacy(MeshBounds& bounds, renddx9abi::HostStream* stream) { stream->read(&bounds, 36); @@ -322,6 +176,7 @@ bool meshBoundsReadLegacy(MeshBounds& bounds, renddx9abi::HostStream* stream) // the current form: min then max as two separate 12-byte reads, dirty, then finalize. // Two reads rather than one 24-byte read, as shipped. +// PE 0x10191E90 bool meshBoundsReadMinMax(MeshBounds& bounds, renddx9abi::HostStream* stream) { stream->read(&bounds.min, 12); @@ -331,6 +186,32 @@ bool meshBoundsReadMinMax(MeshBounds& bounds, renddx9abi::HostStream* stream) return true; } +// Marks the bounds dirty, then writes a 36-byte block. Shipped defect: the block starts at the +// stack slot holding the bounds pointer (the address of the pointer was passed for the record), so +// retail writes the pointer value followed by 32 bytes of its own stack frame. Always true. +// [CHOSEN, not recovered] memory safety: the 32 bytes past the pointer slot are written as zero; +// the first four bytes are the low half of the bounds address, as on the x86 image. +// PE 0x10191E70 +bool meshBoundsWriteLegacy(MeshBounds& bounds, renddx9abi::HostStream* stream) +{ + bounds.dirty = 1; + unsigned char block[36]; + memset(block, 0, sizeof(block)); + const unsigned int address = static_cast(reinterpret_cast(&bounds)); + memcpy(block, &address, 4); + stream->write(block, 36); + return true; +} + +// Min, then max, as two 12-byte writes. Always true. +// PE 0x10191EC0 +bool meshBoundsWriteMinMax(const MeshBounds& bounds, renddx9abi::HostStream* stream) +{ + stream->write(&bounds.min, 12); + stream->write(&bounds.max, 12); + return true; +} + // field-by-field copy. It copies the dirty byte at +0x20 and skips the three padding // bytes after it; the source's +0x21..+0x23 are not carried over. Preserved. void meshBoundsCopy(MeshBounds& dst, const MeshBounds& src) @@ -354,30 +235,19 @@ void meshBoundsCopy(MeshBounds& dst, const MeshBounds& src) // Initializes ownership and container state. keepData is assigned by the factory; -// file-header fields remain unset until loading, and container allocator words are untouched. - +// file-header fields remain unset until loading, and the VC7.1 vectors' allocator words are +// untouched. +// PE 0x101924F0 MeshTemplate::MeshTemplate() { m_dword08 = 0; m_refCount = 1; - // m_name (+0x14) and m_path (+0x30) are default-constructed by the compiler here, in exactly - // the shipped order; the retail body calls std::string::string() on the two in the same places. + // m_name (+0x14), m_path (+0x30), the three per-geom vectors (+0x50, +0x60, +0x70) and the + // material-value map (+0x80) are default-constructed by the compiler here; the retail body + // calls std::string::string() on the two strings in the same places, zeroes the vectors and + // builds the map's head node (sub_100EB100) after them. m_loaded = 0; - m_lodCounts.first = 0; - m_lodCounts.last = 0; - m_lodCounts.end = 0; - - m_lodDistances.first = 0; - m_lodDistances.last = 0; - m_lodDistances.end = 0; - - m_geomInts.first = 0; - m_geomInts.last = 0; - m_geomInts.end = 0; - - materialMapInit(m_materialValues); - m_maxSkip3pLods = 1; m_maxSkipWreckLods = 1; @@ -392,8 +262,9 @@ MeshTemplate::MeshTemplate() // Releases wrappers, material map, containers, and strings in that order. -// The map head must exist and wrapper references must be valid. Staging vertex/index -// buffers are released by their build steps, not here. Called through the destroy slot. +// Wrapper references must be valid. Staging vertex/index buffers are released by their build +// steps, not here. Called through the destroy slot, which then frees the storage without running +// a C++ destructor - so the std members are destroyed explicitly here. void MeshTemplate::destroyMembers() { @@ -407,45 +278,17 @@ void MeshTemplate::destroyMembers() if (m_vertexDeclaration) dx9rend::vertexDeclarationRelease(m_vertexDeclaration); - // ~_Tree: erase [begin(), end()) - which sub_100EBD80 recognises as the whole range and - // services by destroying the root subtree and relinking the header - then free the header. - { - vc71::map_node* const head = m_materialValues.head; - materialEraseSubtree(head->parent); - head->parent = head; - m_materialValues.size = 0; - head->left = head; - head->right = head; - - ::renddx9abi::engineFree(head); - m_materialValues.head = 0; - m_materialValues.size = 0; - } - - if (m_geomInts.first) - ::renddx9abi::engineFree(m_geomInts.first); - m_geomInts.first = 0; - m_geomInts.last = 0; - m_geomInts.end = 0; - - if (m_lodDistances.first) - { - destroyInnerVectors(reinterpret_cast(m_lodDistances.first), - reinterpret_cast(m_lodDistances.last)); - ::renddx9abi::engineFree(m_lodDistances.first); - } - m_lodDistances.first = 0; - m_lodDistances.last = 0; - m_lodDistances.end = 0; + // ~_Tree: erase [begin(), end()) (sub_100EBD80), then free the header. + m_materialValues.~MaterialValueMap(); - if (m_lodCounts.first) - ::renddx9abi::engineFree(m_lodCounts.first); - m_lodCounts.first = 0; - m_lodCounts.last = 0; - m_lodCounts.end = 0; + // The three vectors, last first; the lod-distance vector's inner vectors go before its buffer + // (sub_100ED1C0). + m_geomInts.~GeomIntVector(); + m_lodDistances.~LodDistanceVector(); + m_lodCounts.~GeomIntVector(); - m_path.~string(); - m_name.~string(); + m_path.~basic_string(); + m_name.~basic_string(); } // the deleting destructor in vtable slot +0xB0: run the body, then free the object @@ -508,22 +351,24 @@ unsigned int MeshTemplate::getClassId() const } // four one-line accessors over the two strings. -void MeshTemplate::setName(const vc71::string& name) +// PE 0x10191990 +void MeshTemplate::setName(const std::string& name) { m_name = name; } -const vc71::string& MeshTemplate::getName() const +const std::string& MeshTemplate::getName() const { return m_name; } -void MeshTemplate::setPath(const vc71::string& path) +// PE 0x101919B0 +void MeshTemplate::setPath(const std::string& path) { m_path = path; } -const vc71::string& MeshTemplate::getPath() const +const std::string& MeshTemplate::getPath() const { return m_path; } @@ -593,7 +438,7 @@ int MeshTemplate::getLodPrimitiveCount(unsigned int) { return 0; } // compressed positions, so the "decompression" it publishes is a constant. Preserved as read. Vec3* MeshTemplate::decompressPosition(Vec3* out, const Vec3*) { - const Vec3& scale = unitScale(); + const Vec3& scale = rendmath::unitScale(); out->y = scale.y; out->x = scale.x; out->z = scale.z; @@ -604,6 +449,7 @@ Vec3* MeshTemplate::decompressPosition(Vec3* out, const Vec3*) // is g_rendererBase vslot +0x54 (getFrameOrdinal, 0x1000CB10); this tree's typed accessor for that // slot is dx9rend::rendererFrameOrdinal(). Nothing else in the base releases a device resource - // the vertex/index buffers survive a device reset through BufferManager's own listener. +// PE 0x101157A0 void MeshTemplate::releaseDeviceResources() { m_dword08 = static_cast(dx9rend::rendererFrameOrdinal()); @@ -613,6 +459,7 @@ void MeshTemplate::releaseDeviceResources() // Loads through virtual readers, then builds the buffers. Trailer parsing precedes LODs // and materials. Only readHeader can report failure; later results do not stop the load. +// PE 0x10191A00 bool MeshTemplate::loadFromStream(renddx9abi::HostNonlinearStream* stream) { if (!readHeader(stream)) @@ -633,6 +480,7 @@ bool MeshTemplate::loadFromStream(renddx9abi::HostNonlinearStream* stream) // Reads the header/version and consumes three reserved words and a reserved byte. // Returns false and logs the mesh path when the header is invalid. +// PE 0x10191EF0 bool MeshTemplate::readHeader(renddx9abi::HostNonlinearStream* stream) { stream->read(&m_head, 4); @@ -655,7 +503,7 @@ bool MeshTemplate::readHeader(renddx9abi::HostNonlinearStream* stream) // `std::string(m_path) += "Meshes/"` then `+= m_name` - two operator+ temporaries in the PE, // one string here; the bytes are identical. - vc71::string full(m_path); + std::string full(m_path); full += kMeshesSubDirectory; full += m_name; @@ -669,18 +517,19 @@ bool MeshTemplate::readHeader(renddx9abi::HostNonlinearStream* stream) // Reads geometry counts, declarations, vertex data and indices. // Requires valid file sizes; counts and allocation results are unchecked. +// PE 0x10192080 void MeshTemplate::readGeometry(renddx9abi::HostNonlinearStream* stream) { unsigned int geomCount = 0; stream->read(&geomCount, 4); - vectorIntResize(m_lodCounts, geomCount, 0); - vectorIntResize(m_geomInts, geomCount, 0); + m_lodCounts.resize(geomCount, 0); // sub_10192790 + m_geomInts.resize(geomCount, 0); for (unsigned int geom = 0; geom < geomCount; ++geom) { - stream->read(reinterpret_cast(m_lodCounts.first) + geom, 4); - reinterpret_cast(m_geomInts.first)[geom] = 0; + stream->read(&m_lodCounts[geom], 4); + m_geomInts[geom] = 0; } unsigned int attributeCount = 0; @@ -712,6 +561,7 @@ void MeshTemplate::readGeometry(renddx9abi::HostNonlinearStream* stream) // the base's vertex block is raw: stride * count bytes into +0x90, verbatim. The // product is computed twice, once for the allocation and once for the read length, exactly as // shipped (stride first in both). +// PE 0x10191B00 void MeshTemplate::readVertices(renddx9abi::HostNonlinearStream* stream) { m_vertexData = ::renddx9abi::engineAlloc(m_vertexStride * m_vertexCount); @@ -728,11 +578,12 @@ void MeshTemplate::mergeMaterials() // Creation is not null-checked. Lock counts are vertices, not bytes; the freed staging // pointer is deliberately left unchanged. +// PE 0x10191B50 void MeshTemplate::buildVertexBuffers() { m_vertexBuffer = dx9rend::createVertexBuffer(dx9rend::g_bufferManager, m_vertexCount, m_vertexStride, - vc71::string("MeshTemplate"), 8); + std::string("MeshTemplate"), 8); void* const locked = dx9rend::vertexBufferLock(m_vertexBuffer, 0, m_vertexCount, 0); if (locked) @@ -748,6 +599,7 @@ void MeshTemplate::buildVertexBuffers() // D3DFMT_INDEX16, which is why the byte count is 2 * indexCount everywhere. The lock is in index // units. Same three missing guards as buildVertexBuffers. +// PE 0x10191A80 void MeshTemplate::buildIndexBuffer() { m_indexBuffer = dx9rend::bufferManagerCreateIndexBuffer(m_indexCount, 8, 101); @@ -767,6 +619,7 @@ void MeshTemplate::finalizeMaterials() } // four bytes into +0xBC, immediately after the index block. Constructed as 8. +// PE 0x10191BE0 void MeshTemplate::readTrailer(renddx9abi::HostNonlinearStream* stream) { stream->read(&m_u2, 4); diff --git a/Code/BF2/Geom/MeshTemplate.h b/Code/BF2/Geom/MeshTemplate.h index d24a3ef06..55530ec57 100644 --- a/Code/BF2/Geom/MeshTemplate.h +++ b/Code/BF2/Geom/MeshTemplate.h @@ -1,7 +1,7 @@ // Path: [INFERRED] header beside MeshTemplate.cpp, attested at RendDX9 0x10220A20. // Shared mesh loading base, recovered from RendDX9.dll 1.50 (PE only). // Retail layout: 0xC8 bytes; constructor 0x101924F0, primary table 0x10220A88. -// Embedded vectors/maps retain VC7.1 layouts and untouched allocator words. +// The material-value map and the three per-geom vectors are std containers (issue #7). #ifndef BF2_GEOM_MESHTEMPLATE_H #define BF2_GEOM_MESHTEMPLATE_H @@ -10,15 +10,18 @@ #include "../../RendDX9Abi/HfeAbi.h" #include "../../RendDX9Abi/HostFileAbi.h" -#include "../../RendDX9Abi/Vc71String.h" -#include "../../RendDX9Abi/Vc71Vector.h" -#include "../../RendDX9Abi/Vc71Map.h" +#include #include "../Core/IBase.h" #include "../IO/Console/IConsoleSaveable.h" #include "../Math/Vec3.h" +#include +#include +#include + namespace dice { namespace hfe { +namespace dx9rend { struct EngineTexture; } namespace geom { @@ -43,9 +46,89 @@ void meshBoundsExpand(MeshBounds& bounds, const Vec3& point); void meshBoundsFinalize(MeshBounds& bounds); bool meshBoundsReadLegacy(MeshBounds& bounds, renddx9abi::HostStream* stream); bool meshBoundsReadMinMax(MeshBounds& bounds, renddx9abi::HostStream* stream); +// The two writers the mesh optimizers use (MeshTemplate.cpp, PE 0x10191E70 / 0x10191EC0). +bool meshBoundsWriteLegacy(MeshBounds& bounds, renddx9abi::HostStream* stream); +bool meshBoundsWriteMinMax(const MeshBounds& bounds, renddx9abi::HostStream* stream); void meshBoundsCopy(MeshBounds& dst, const MeshBounds& src); +// The Ra material parameter block every mesh material embeds (StaticMeshMaterial, BundledMeshMaterial +// and SkinnedMeshMaterial) and the Terrain allocates. raMaterialParametersConstruct (sub_10044270, +// StaticMeshMaterial.cpp) fills it; the shader binds each named holder through the registry at +// `descriptor`, whose entries are the offsetof values of the holders below. Each holder is its +// binder table followed by the value. The `+0xNN` comments are retail x86 offsets. +struct RaMaterialParameters +{ + struct Bool { void* vptr; unsigned char value; unsigned char pad[3]; }; + struct Float { void* vptr; float value; }; + struct Int { void* vptr; int value; }; + struct Texture { void* vptr; void* value; }; // a counted EngineTexture* + struct Vec3 { void* vptr; float value[3]; }; + struct Vec4 { void* vptr; float value[4]; }; + + void* vptr; // +0x000 off_101E2210 + const void* descriptor; // +0x004 &unk_1023E7B0 - this block's offset registry + Bool alphaBlendEnable; // +0x008 "AlphaBlendEnable" + Bool depthWrite; // +0x010 "DepthWrite" + Bool alphaTest; // +0x018 "AlphaTest" + Vec4 diffuseColor; // +0x020 "DiffuseColor" + Vec4 ambient; // +0x034 "Ambient" + Vec4 pointColor; // +0x048 "PointColor" + Int pointSun; // +0x05C "PointSun" + Float disableLightmapShadows; // +0x064 "DisableLightmapShadows" + Vec4 specularColor; // +0x06C "SpecularColor" + Float specularPower; // +0x080 "SpecularPower" + Float opacity; // +0x088 "Opacity" + Float reflectivity; // +0x090 "Reflectivity" + Int cullMode; // +0x098 "CullMode" + Int alphaTestRef; // +0x0A0 "AlphaTestRef" + Int srcBlend; // +0x0A8 "SrcBlend" + Int destBlend; // +0x0B0 "DestBlend" + Texture diffuseMap; // +0x0B8 "DiffuseMap" + Texture detailMap; // +0x0C0 "DetailMap" + Texture dirtMap; // +0x0C8 "DirtMap" + Texture crackMap; // +0x0D0 "CrackMap" + Texture normalMap; // +0x0D8 "NormalMap" + Texture crackNormalMap; // +0x0E0 "CrackNormalMap" + Texture giMap; // +0x0E8 "GIMap" + Float staticGloss; // +0x0F0 "StaticGloss" (a float-splat holder) + Float objRadius; // +0x0F8 "ObjRadius" + Float invHemiHeightScale; // +0x100 "InvHemiHeightScale" + Vec4 parallaxScaleBias; // +0x108 "ParallaxScaleBias" + Texture cubeMap; // +0x11C "CubeMap" + Vec4 posUnpack; // +0x124 "PosUnpack" + Float texUnpack; // +0x138 "TexUnpack" + // "NormalUnpack" binds two floats; the mesh draws park their technique in value[2] (+0x14C). + Vec3 normalUnpack; // +0x140 +#if !defined(_M_IX86) + // [CHOSEN, not recovered] (https://github.com/B2BF/OpenBF2/issues/7) A technique pointer does + // not fit the four-byte value[2] on x64, so the native block gives it its own slot. + void* shader; +#endif +}; + +#if defined(_M_IX86) +static_assert(sizeof(RaMaterialParameters) == 0x150, + "raMaterialParametersConstruct fills 0x150 bytes; its last store is +0x14C"); +static_assert(offsetof(RaMaterialParameters, normalUnpack) == 0x140, "NormalUnpack holder at +0x140"); +#endif + +// The technique a mesh draw selected for this material (retail block +0x14C). Read by the queue +// entry as its shader; copied with the block by the copy constructor and assignment. +// PE 0x10031180 (Terrain.cpp): the counted texture-holder assignment. `texture` is an +// EngineTexture*; the old value loses a reference (destroyed at zero), the new one gains one. +void holderSetTexture(RaMaterialParameters::Texture& holder, dx9rend::EngineTexture* texture); + +inline void*& raMaterialShaderSlot(RaMaterialParameters& block) +{ +#if defined(_M_IX86) + return *reinterpret_cast(&block.normalUnpack.value[2]); +#else + return block.shader; +#endif +} + + // The 12-byte GeometryTemplate prefix that sits between the primary vptr and the console-saveable // vptr. [INFERRED] as a class of its own from the layout; the PE never shows its vtable because // MeshTemplate's constructor overwrites the slot before anything observes it. @@ -57,15 +140,23 @@ class GeometryTemplate : public IGeometryTemplate int m_dword08; // +0x08 ctor 0 [UNRESOLVED] }; +#if defined(_M_IX86) static_assert(sizeof(GeometryTemplate) == 0x0C, "GeometryTemplate prefix is 12 bytes"); +#endif // Shared mesh readers and resources; IConsoleSaveable must remain the second base at +0x0C. -// The packed material map uses 24-byte nodes, not Vc71Map.h's string-keyed nodes. +// The packed material values are a map keyed (geom, lod, material). // Slot +0xAC preloads resources and stamps the frame; it does not release them. class MeshTemplate : public GeometryTemplate, public ::dice::hfe::io::IConsoleSaveable { public: + typedef std::map MaterialValueMap; + typedef std::vector GeomIntVector; + typedef std::vector > LodDistanceVector; // per geom, per lod switch + MeshTemplate(); + // The destructor body: the deleting slot frees the storage afterwards without running a C++ + // destructor, so this destroys every member itself, in the shipped order. void destroyMembers(); // sub_101925C0 (the dtor body) // IBase quartet - the base counts at +0x10. StaticMeshTemplate overrides all four. @@ -75,10 +166,10 @@ class MeshTemplate : public GeometryTemplate, public ::dice::hfe::io::IConsoleSa virtual void* queryInterface(unsigned int iid) const; virtual unsigned int getClassId() const; - virtual void setName(const vc71::string& name); - virtual const vc71::string& getName() const; - virtual void setPath(const vc71::string& path); - virtual const vc71::string& getPath() const; + virtual void setName(const std::string& name); + virtual const std::string& getName() const; + virtual void setPath(const std::string& path); + virtual const std::string& getPath() const; virtual void* createInstance(); virtual bool isLoaded() const; virtual bool load(); @@ -139,14 +230,14 @@ class MeshTemplate : public GeometryTemplate, public ::dice::hfe::io::IConsoleSa // data, in shipped order int m_refCount; // +0x10 - vc71::string m_name; // +0x14 - vc71::string m_path; // +0x30 + std::string m_name; // +0x14 + std::string m_path; // +0x30 unsigned char m_loaded; // +0x4C unsigned char m_pad4D[3]; - vc71::vector_layout m_lodCounts; // +0x50 vector - vc71::vector_layout m_lodDistances; // +0x60 vector> (inner = vector_layout) - vc71::vector_layout m_geomInts; // +0x70 vector - vc71::map_layout m_materialValues; // +0x80 map + GeomIntVector m_lodCounts; // +0x50 + LodDistanceVector m_lodDistances; // +0x60 + GeomIntVector m_geomInts; // +0x70 lods skipped per geom + MaterialValueMap m_materialValues; // +0x80 int m_dword8C; // +0x8C void* m_vertexData; // +0x90 void* m_vertexBuffer; // +0x94 @@ -164,8 +255,6 @@ class MeshTemplate : public GeometryTemplate, public ::dice::hfe::io::IConsoleSa int m_maxSkipWreckLods; // +0xC4 }; -static_assert(sizeof(MeshTemplate) == 0xC8, "MeshTemplate is 0xC8 bytes; StaticMeshTemplate's refcount follows at +0xC8"); - } // namespace geom } // namespace hfe } // namespace dice diff --git a/Code/BF2/Geom/ModuleGeom.cpp b/Code/BF2/Geom/ModuleGeom.cpp index 86a5eb6bd..fe8f36b17 100644 --- a/Code/BF2/Geom/ModuleGeom.cpp +++ b/Code/BF2/Geom/ModuleGeom.cpp @@ -8,8 +8,6 @@ #include "../../RendDX9Abi/PluginModules.h" #include "../../RendDX9Abi/ModuleCommon.h" -#include "../../RendDX9Abi/Vc71Vector.h" -#include "../../RendDX9Abi/Vc71Map.h" #include "../../RendDX9Abi/PluginEntry.h" #include "../../RendDX9Abi/BfMemory.h" #include "../../RendDX9Abi/Frontier.h" @@ -27,7 +25,6 @@ namespace geom { extern IBase* g_GeometryTemplateManager; -#if BF2_PLUGIN_ABI_NATIVE bool registerLightManagerConsoleObjects(); bool unregisterLightManagerConsoleObjects(); bool registerShadowManagerConsoleObjects(); @@ -40,6 +37,8 @@ bool registerSkyDomeConsoleObjects(); bool unregisterSkyDomeConsoleObjects(); bool registerTerrainConsoleObjects(); bool unregisterTerrainConsoleObjects(); +bool registerTerrainCullerConsoleObjects(); +bool unregisterTerrainCullerConsoleObjects(); bool registerNametagManagerConsoleObjects(); // Geom/NametagManagerConsole.cpp - `nametags` bool unregisterNametagManagerConsoleObjects(); bool registerUndergrowthConsoleObjects(); // Geom/UndergrowthSystemConsole.cpp - `undergrowth` @@ -52,8 +51,13 @@ bool registerObjectGeometryConsoleObjects(); // Geom/ObjectGeometryConsole.cpp bool unregisterObjectGeometryConsoleObjects(); bool registerStaticMeshRendererConsoleObjects(); // Geom/StaticMeshRendererConsole.cpp - the atlas rows bool unregisterStaticMeshRendererConsoleObjects(); -#endif -#if BF2_PLUGIN_ABI_NATIVE && defined(BF2_IMAGE_EDITOR) && BF2_IMAGE_EDITOR +bool registerSkinnedMeshRendererConsoleObjects(); +bool unregisterSkinnedMeshRendererConsoleObjects(); +bool registerParticleSystemManagerConsoleObjects(); +bool unregisterParticleSystemManagerConsoleObjects(); +bool registerWeatherManagerConsoleObjects(); // Geom/WeatherManagerConsole.cpp - `weatherManager` +bool unregisterWeatherManagerConsoleObjects(); +#if defined(BF2_IMAGE_EDITOR) && BF2_IMAGE_EDITOR // Geom/LightmapGeneration/LightmapGenerationConsole.cpp - the 2006 editor's `lightmapGeneration` // rows, editor flavour only ([CHOSEN, not recovered]: 1.50 publishes none). bool registerLightmapGenerationConsoleObjects(); @@ -68,6 +72,9 @@ bool unregisterLightmapGenerationConsoleObjects(); extern const unsigned int CID_RoadCompiledRenderer; IBase* __fastcall createRoadCompiledRenderer(unsigned int iid, IBase* outer); +extern const unsigned int CID_LightGeometry; +IBase* __fastcall createLightGeometry(unsigned int iid, IBase* outer); + // RoadCompiledTemplate.cpp - GeometryTemplate.RoadCompiled (821901), the template every stock road // names. see the class list below. extern const unsigned int CID_RoadCompiledTemplate; @@ -84,15 +91,22 @@ IBase* __fastcall createRoadTemplate(unsigned int iid, IBase* outer); extern const unsigned int CID_RoadEditable; IBase* __fastcall createRoadEditable(unsigned int iid, IBase* outer); +// BundledMeshOptimizer.cpp / StaticMeshOptimizer.cpp - the two GeometryOptimizer classes +// Renderer::initialize registers, runs and clears (class ids dword_1021AF0C / dword_1021AF14). +IBase* __fastcall createBundledMeshOptimizer(unsigned int iid, IBase* outer); +IBase* __fastcall createStaticMeshOptimizer(unsigned int iid, IBase* outer); + // DecalSystem/DecalManager.cpp - because joining A server crashed without it: // BF2's in-game HUD does getSingleton("DecalManager") and dereferences the result unchecked // (0x004F6FD2). The singleton entry is already in getSingletonList; this supplies its factory. extern const unsigned int CID_DecalManager; IBase* __fastcall createDecalManager(unsigned int iid, IBase* outer); -// The gameplay-rendering singleton batch. Each is a faithful minimal class - the -// reference spine + registration are real, the render path is a named frontier. See the per-class -// files. SkyDome and the weather/undergrowth group remain deferred. +// DecalSystem/DecalShadowManager.cpp. Its constructor registers "DecalShadowTemplate" with the +// decal manager, which the singleton list creates first. +IBase* __fastcall createDecalShadowManager(unsigned int iid, IBase* outer); + +// Factories for the particle, static-mesh and skinned-mesh renderer singletons. extern const unsigned int CID_ParticleSystemManager; IBase* __fastcall createParticleSystemManager(unsigned int iid, IBase* outer); extern const unsigned int CID_StaticMeshRenderer; @@ -106,6 +120,12 @@ IBase* __fastcall createSkyDome(unsigned int iid, IBase* outer); // Factory for the undergrowth singleton and its grass resources. IBase* __fastcall createUndergrowthSystem(unsigned int iid, IBase* outer); +// Factories for the storm (Geom/WeatherManager.cpp) and its lightning (Geom/LightningManager.cpp). +IBase* __fastcall createLightningManager(unsigned int iid, IBase* outer); +IBase* __fastcall createWeatherManager(unsigned int iid, IBase* outer); +// Geom/Rain/RainManager.cpp. +IBase* __fastcall createRainManager(unsigned int iid, IBase* outer); + // Factory for static-mesh templates and their material/technique state. IBase* __fastcall createStaticMeshTemplate(unsigned int iid, IBase* outer); @@ -131,6 +151,13 @@ extern const unsigned int CID_SwiffRender; extern const unsigned int IID_ISwiffRender; IBase* __fastcall createSwiffRender(unsigned int iid, IBase* outer); +// GeomMisc/MenuRend/Video.cpp - the Bink movie pair. FSMoviePlayer and SwiffRender create Video by +// name; Video::close releases its VideoTarget. +extern const unsigned int CID_VideoTarget; +IBase* __fastcall createVideoTarget(unsigned int iid, IBase* outer); +extern const unsigned int CID_Video; +IBase* __fastcall createVideo(unsigned int iid, IBase* outer); + // GeometryTemplateManager.cpp - now in its attested source home. The first create/find/active and // ownership tranche made the old in-ModuleGeom skeleton too large to keep here honestly (RW-51). extern const unsigned int IID_IGeometryTemplateManager; @@ -171,14 +198,14 @@ IBase* g_RainManager = 0; IBase* g_Terrain = 0; // Replaces Terrain with the requested registered geometry class. Unknown names publish nothing. -void registerTerrainSingleton(const vc71::string& className) +void registerTerrainSingleton(const std::string& className) { const bool exists = classManager->getSingleton(renddx9abi::HostString("Terrain")) != 0; if (exists) classManager->unregisterSingleton(renddx9abi::HostString("Terrain")); - vc71::string fullName("dice.hfe.geom."); + std::string fullName("dice.hfe.geom."); fullName += className; unsigned int classId = 0; if (classManager->getClassID(renddx9abi::HostString(fullName.c_str()), &classId)) @@ -229,6 +256,9 @@ IBase* g_SwiffRender = 0; // Event (10, 1) registers and immediately creates SwiffRender after SwiffPlayer loads. // Event (10, 2) unregisters it and clears the singleton pointer. +// PE 0x100B0EB2. Shipped defect: the retail body dereferences the class manager and the event manager +// without a null test; the guards below keep the native backends from faulting before startup order +// publishes them (memory-safety exception). void ModuleGeom::handleCoreModuleEvent(int category, int id, int a3, int a4) { if (category != 10) @@ -256,15 +286,28 @@ void ModuleGeom::handleCoreModuleEvent(int category, int id, int a3, int a4) } } -// Appends the geometry factories available to ClassManager in registration order. -// [FRONTIER] dice::hfe::geom::ModuleGeom::getClassList: publish remaining registrations only -// when their required virtual bodies are callable and their creation/use paths are verified. +// Appends the 32 geometry classes in retail order, each with its shipped name and class id. +// PE 0x100C7F43. void ModuleGeom::getClassList(RD9_HOST_VECTOR_PARAMETER(ClassRegInfo, hostVector)) { RD9_TRACE("dice::hfe::geom::ModuleGeom::getClassList", 0x10); ::renddx9abi::HostVectorWriter out(hostVector); + { + ClassRegInfo info; + info.classId = 821004u; + info.name = "dice.hfe.geom.Terrain"; + info.create = RD9_CLASS_FACTORY(&createTerrain); + out.push_back(info); + } + { + ClassRegInfo info; + info.classId = 821005u; + info.name = "dice.hfe.geom.TerrainEditable"; + info.create = RD9_CLASS_FACTORY(&createTerrainEditable); + out.push_back(info); + } { ClassRegInfo info; info.classId = CID_GeometryTemplateManager; @@ -272,8 +315,41 @@ void ModuleGeom::getClassList(RD9_HOST_VECTOR_PARAMETER(ClassRegInfo, hostVector info.create = RD9_CLASS_FACTORY(&createGeometryTemplateManager); out.push_back(info); } - - // Keep the recovered factories in the same relative order as PE 0x100C7F43's 32 entries. + { + ClassRegInfo info; + info.classId = 0x870CA651u; + info.name = "dice.hfe.geom.GeometryTemplate.BundledMesh"; + info.create = RD9_CLASS_FACTORY(&createBundledMeshTemplate); + out.push_back(info); + } + { + ClassRegInfo info; + info.classId = 0x870CA655u; + info.name = "dice.hfe.geom.GeometryTemplate.MeshParticleMesh"; + info.create = RD9_CLASS_FACTORY(&createMeshParticleMeshTemplate); + out.push_back(info); + } + { + ClassRegInfo info; + info.classId = 0x870CA652u; + info.name = "dice.hfe.geom.GeometryTemplate.SkinnedMesh"; + info.create = RD9_CLASS_FACTORY(&createSkinnedMeshTemplate); + out.push_back(info); + } + { + ClassRegInfo info; + info.classId = 0x870CA653u; + info.name = "dice.hfe.geom.GeometryTemplate.StaticMesh"; + info.create = RD9_CLASS_FACTORY(&createStaticMeshTemplate); + out.push_back(info); + } + { + ClassRegInfo info; + info.classId = CID_RoadCompiledTemplate; + info.name = "dice.hfe.geom.GeometryTemplate.RoadCompiled"; + info.create = RD9_CLASS_FACTORY(&createRoadCompiledTemplate); + out.push_back(info); + } { ClassRegInfo info; info.classId = CID_StaticMeshRenderer; @@ -295,9 +371,6 @@ void ModuleGeom::getClassList(RD9_HOST_VECTOR_PARAMETER(ClassRegInfo, hostVector info.create = RD9_CLASS_FACTORY(&createParticleSystemManager); out.push_back(info); } - - // HemiMapManager - complete 14-slot table, including the editor/offline makeHemiMap operation. - // Its connected stock path is the setBaseHemiMap console binding used by every stock Sky.con. { ClassRegInfo info; info.classId = CID_HemiMapManager; @@ -305,9 +378,6 @@ void ModuleGeom::getClassList(RD9_HOST_VECTOR_PARAMETER(ClassRegInfo, hostVector info.create = RD9_CLASS_FACTORY(&createHemiMapManager); out.push_back(info); } - - // DecalManager - for the join path (see the forward declaration above). Its - // getSingletonList entry (flags 2) now has a factory, so getSingleton("DecalManager") resolves. { ClassRegInfo info; info.classId = CID_DecalManager; @@ -315,10 +385,13 @@ void ModuleGeom::getClassList(RD9_HOST_VECTOR_PARAMETER(ClassRegInfo, hostVector info.create = RD9_CLASS_FACTORY(&createDecalManager); out.push_back(info); } - - // VideoOptions::apply dereferences this singleton on every boot inside a - // branch guarded only on g_Renderer - the shipped defect in RW-76 - so the class exists to make - // that branch survivable. Only slot +0x18 is on that path and it is written. + { + ClassRegInfo info; + info.classId = 821020u; // dword_1021AEF0 + info.name = "dice.hfe.geom.DecalShadowManager"; + info.create = RD9_CLASS_FACTORY(&createDecalShadowManager); // 0x100B0793 + out.push_back(info); + } { ClassRegInfo info; info.classId = CID_RoadCompiledRenderer; @@ -326,8 +399,6 @@ void ModuleGeom::getClassList(RD9_HOST_VECTOR_PARAMETER(ClassRegInfo, hostVector info.create = RD9_CLASS_FACTORY(&createRoadCompiledRenderer); out.push_back(info); } - - // Editable-road renderer registration. { ClassRegInfo info; info.classId = CID_RoadEditableRenderer; @@ -335,10 +406,20 @@ void ModuleGeom::getClassList(RD9_HOST_VECTOR_PARAMETER(ClassRegInfo, hostVector info.create = RD9_CLASS_FACTORY(&createRoadEditableRenderer); out.push_back(info); } - - // Roads.RoadTemplate - 821008 (dword_1021AEB4); shipped after the two GeometryOptimizers - // (0x100C83BB), which the tree does not register. created only - // through createInstance (the editor's road templates); see Geom/RoadTemplate.cpp. + { + ClassRegInfo info; + info.classId = 0x870CAA39u; + info.name = "dice.hfe.geom.GeometryOptimizer.BundledMeshOptimizer"; + info.create = RD9_CLASS_FACTORY(&createBundledMeshOptimizer); + out.push_back(info); + } + { + ClassRegInfo info; + info.classId = 0x870CAA3Bu; + info.name = "dice.hfe.geom.GeometryOptimizer.StaticMeshOptimizer"; + info.create = RD9_CLASS_FACTORY(&createStaticMeshOptimizer); + out.push_back(info); + } { ClassRegInfo info; info.classId = CID_RoadTemplate; @@ -346,8 +427,6 @@ void ModuleGeom::getClassList(RD9_HOST_VECTOR_PARAMETER(ClassRegInfo, hostVector info.create = RD9_CLASS_FACTORY(&createRoadTemplate); out.push_back(info); } - - // Editable-road factory registration. { ClassRegInfo info; info.classId = CID_RoadEditable; @@ -355,10 +434,6 @@ void ModuleGeom::getClassList(RD9_HOST_VECTOR_PARAMETER(ClassRegInfo, hostVector info.create = RD9_CLASS_FACTORY(&createRoadEditable); out.push_back(info); } - - // NametagManager - 852419. Shipped getClassList order puts it immediately before LightManager - // (0x100C8439, just after Roads.RoadEditable). The singleton list below already names it, so - // ClassManager now creates it and fills g_NametagManager (IID 0xB801DCFE). RW-239. { ClassRegInfo info; info.classId = 852419u; @@ -366,10 +441,6 @@ void ModuleGeom::getClassList(RD9_HOST_VECTOR_PARAMETER(ClassRegInfo, hostVector info.create = RD9_CLASS_FACTORY(&createNametagManager); out.push_back(info); } - - // XpLightManager.cpp: PE factory 0x100B0502, exact 0x980-byte allocation and 189-slot primary - // interface. Its boot-live settings/empty-light surface is recovered; later light-instance and - // GPU paths stop at their individual slots. { ClassRegInfo info; info.classId = CID_LightManager; @@ -377,17 +448,13 @@ void ModuleGeom::getClassList(RD9_HOST_VECTOR_PARAMETER(ClassRegInfo, hostVector info.create = RD9_CLASS_FACTORY(&createLightManager); out.push_back(info); } - - // Register the rasterizer instantiated by the (10, 1) core event. { ClassRegInfo info; - info.classId = CID_SwiffRender; - info.name = "dice.hfe.geom.SwiffRender"; - info.create = RD9_CLASS_FACTORY(&createSwiffRender); + info.classId = 0x870CAA3Eu; + info.name = "dice.hfe.geom.ObjectDrawer"; + info.create = RD9_CLASS_FACTORY(&createObjectDrawer); out.push_back(info); } - - // SkyDome - 0x870CAA3D. ; see the note beside its forward declaration above. { ClassRegInfo info; // The literal, not a named constant, to match how getSingletonList below spells the same @@ -398,107 +465,64 @@ void ModuleGeom::getClassList(RD9_HOST_VECTOR_PARAMETER(ClassRegInfo, hostVector info.create = RD9_CLASS_FACTORY(&createSkyDome); out.push_back(info); } - - // UndergrowthSystem - 822323005 (CID_UndergrowthSystem). the - // shipped list puts it after SkyDome and LightGeometry (0x100C8574). flags-2 singleton, so - // registerSingleton constructs it; its constructor allocates only the empty atlas owner. - { - ClassRegInfo info; - info.classId = 822323005u; - info.name = "dice.hfe.geom.UndergrowthSystem"; - info.create = RD9_CLASS_FACTORY(&createUndergrowthSystem); - out.push_back(info); - } - - // Register mesh factories in BundledMesh, SkinnedMesh, StaticMesh order. { ClassRegInfo info; - info.classId = 0x870CA651u; - info.name = "dice.hfe.geom.GeometryTemplate.BundledMesh"; - info.create = RD9_CLASS_FACTORY(&createBundledMeshTemplate); + info.classId = CID_LightGeometry; + info.name = "dice.hfe.geom.LightGeometry"; + info.create = RD9_CLASS_FACTORY(&createLightGeometry); out.push_back(info); } - // G1 draft: GeometryTemplate.MeshParticleMesh - 0x870CA655. Shipped between BundledMesh and - // SkinnedMesh (0x100C8049..0x100C8071). Published together with the MeshParticlesRenderer's - // retained-list draw (drawExtras, PE 0x101753E0): muzzle flashes and tracers draw through - // IGeometry +0x18, which only queues into that renderer. { ClassRegInfo info; - info.classId = 0x870CA655u; - info.name = "dice.hfe.geom.GeometryTemplate.MeshParticleMesh"; - info.create = RD9_CLASS_FACTORY(&createMeshParticleMeshTemplate); + info.classId = 822323005u; + info.name = "dice.hfe.geom.UndergrowthSystem"; + info.create = RD9_CLASS_FACTORY(&createUndergrowthSystem); out.push_back(info); } { ClassRegInfo info; - info.classId = 0x870CA652u; - info.name = "dice.hfe.geom.GeometryTemplate.SkinnedMesh"; - info.create = RD9_CLASS_FACTORY(&createSkinnedMeshTemplate); + info.classId = CID_SwiffRender; + info.name = "dice.hfe.geom.SwiffRender"; + info.create = RD9_CLASS_FACTORY(&createSwiffRender); out.push_back(info); } - - // GeometryTemplate.StaticMesh - 0x870CA653. See the note beside its forward declaration above. - // Kept in the shipped list's relative order: the three GeometryTemplate.* entries sit together, - // after GeometryTemplateManager and before StaticMeshRenderer. { ClassRegInfo info; - info.classId = 0x870CA653u; - info.name = "dice.hfe.geom.GeometryTemplate.StaticMesh"; - info.create = RD9_CLASS_FACTORY(&createStaticMeshTemplate); + info.classId = CID_VideoTarget; // dword_1021AF34 + info.name = "dice.hfe.geom.VideoTarget"; + info.create = RD9_CLASS_FACTORY(&createVideoTarget); // 0x100B0C67 out.push_back(info); } - - // Compiled-road template registration. { ClassRegInfo info; - info.classId = CID_RoadCompiledTemplate; - info.name = "dice.hfe.geom.GeometryTemplate.RoadCompiled"; - info.create = RD9_CLASS_FACTORY(&createRoadCompiledTemplate); + info.classId = CID_Video; // dword_1021AF38 + info.name = "dice.hfe.geom.Video"; + info.create = RD9_CLASS_FACTORY(&createVideo); // 0x100B0CA6 out.push_back(info); } - - // ObjectDrawer - 0x870CAA3E. ; see the note beside its forward declaration. - // Renderer::initialize step 10 asks for it by createInstance(0x870CAA3E, 0xB801DCFC), and - // queryInterface answers both that IID and the plain IBase 1. { ClassRegInfo info; - info.classId = 0x870CAA3Eu; - info.name = "dice.hfe.geom.ObjectDrawer"; - info.create = RD9_CLASS_FACTORY(&createObjectDrawer); + info.classId = 822323012u; // dword_1021AF40 + info.name = "dice.hfe.geom.LightningManager"; + info.create = RD9_CLASS_FACTORY(&createLightningManager); // 0x100B0BA4 out.push_back(info); } - - // Terrain is instantiated on demand by terrain.create. { ClassRegInfo info; - info.classId = 821004u; - info.name = "dice.hfe.geom.Terrain"; - info.create = RD9_CLASS_FACTORY(&createTerrain); + info.classId = 822323011u; // dword_1021AF3C + info.name = "dice.hfe.geom.WeatherManager"; + info.create = RD9_CLASS_FACTORY(&createWeatherManager); // 0x100B0BE6 out.push_back(info); } - - // TerrainEditable - 821005 (dword_1021AEB0), the shipped list's "dice.hfe.geom.TerrainEditable" - // entry, factory 0x100B0586. TerrainEditable R1: - // construction, init, update and draw are written; the editing and saving slots stop at named - // [FRONTIER]s. Reached only through `terrain.create TerrainEditable` (registerTerrainSingleton) - - // the editor's verb; no shipped level asks for it. Outside the editor flavour init faults exactly - // as retail 1.50 does (see Geom/TerrainEditable.cpp). { ClassRegInfo info; - info.classId = 821005u; - info.name = "dice.hfe.geom.TerrainEditable"; - info.create = RD9_CLASS_FACTORY(&createTerrainEditable); + info.classId = 822323013u; // dword_1021AF44 + info.name = "dice.hfe.geom.RainManager"; + info.create = RD9_CLASS_FACTORY(&createRainManager); // 0x100B0C25 out.push_back(info); } - // Count follows the output container; keep the diagnostic's literal name list in sync. - ::renddx9abi::logf("ModuleGeom::getClassList: %u classes registered (GeometryTemplateManager, " - "StaticMeshRenderer, SkinnedMeshRenderer, ParticleSystemManager, HemiMapManager, " - "DecalManager, RoadCompiledRenderer, LightManager, SwiffRender, SkyDome, UndergrowthSystem, " - "GeometryTemplate.BundledMesh, GeometryTemplate.MeshParticleMesh, GeometryTemplate.SkinnedMesh, GeometryTemplate.StaticMesh, ObjectDrawer, " - "GeometryTemplate.RoadCompiled, " - "RoadEditableRenderer, Roads.RoadTemplate, " - "Terrain, TerrainEditable, NametagManager); the rest of the shipped 32 are withheld - no factory bodies yet", + ::renddx9abi::logf("ModuleGeom::getClassList: %u of the 32 shipped classes registered", out.size()); } @@ -518,6 +542,7 @@ struct GeomSingleton } // anonymous namespace +// PE 0x100C7974: the sixteen-entry table above, read in full. void ModuleGeom::getSingletonList(RD9_HOST_VECTOR_PARAMETER(SingletonRegInfo, hostVector)) { RD9_TRACE("dice::hfe::geom::ModuleGeom::getSingletonList", 0x14); @@ -560,6 +585,7 @@ void ModuleGeom::getSingletonList(RD9_HOST_VECTOR_PARAMETER(SingletonRegInfo, ho } } +// PE 0x100B0DF6. The console lists are registered per translation unit natively (see below). bool ModuleGeom::init() { RD9_TRACE("dice::hfe::geom::ModuleGeom::init", 0x18); @@ -568,21 +594,23 @@ bool ModuleGeom::init() // ConsoleObjects::registerConsoleObjects at 0x1007B570, then registers the category-10 event // handler below. Native mode shares the rebuilt host's STL ABI; retail-compatible mode cannot // safely publish current-toolchain ConsoleObject/container layouts to the VC7.1 host. -#if BF2_PLUGIN_ABI_NATIVE registerLightManagerConsoleObjects(); + registerWeatherManagerConsoleObjects(); registerShadowManagerConsoleObjects(); registerHemiMapManagerConsoleObjects(); registerGeometryTemplateConsoleObjects(); registerSkyDomeConsoleObjects(); registerTerrainConsoleObjects(); + registerTerrainCullerConsoleObjects(); registerNametagManagerConsoleObjects(); registerUndergrowthConsoleObjects(); registerDecalManagerConsoleObjects(); registerOverGrowthConsoleObjects(); registerObjectGeometryConsoleObjects(); registerStaticMeshRendererConsoleObjects(); -#endif -#if BF2_PLUGIN_ABI_NATIVE && defined(BF2_IMAGE_EDITOR) && BF2_IMAGE_EDITOR + registerSkinnedMeshRendererConsoleObjects(); + registerParticleSystemManagerConsoleObjects(); +#if defined(BF2_IMAGE_EDITOR) && BF2_IMAGE_EDITOR registerLightmapGenerationConsoleObjects(); #endif @@ -622,6 +650,7 @@ bool ModuleGeom::init() return true; } +// PE 0x100B0E28. bool ModuleGeom::close() { RD9_TRACE("dice::hfe::geom::ModuleGeom::close", 0x1C); @@ -634,23 +663,25 @@ bool ModuleGeom::close() static_cast(10), reinterpret_cast(static_cast(this))); } -#if BF2_PLUGIN_ABI_NATIVE && defined(BF2_IMAGE_EDITOR) && BF2_IMAGE_EDITOR +#if defined(BF2_IMAGE_EDITOR) && BF2_IMAGE_EDITOR unregisterLightmapGenerationConsoleObjects(); #endif -#if BF2_PLUGIN_ABI_NATIVE + unregisterParticleSystemManagerConsoleObjects(); + unregisterSkinnedMeshRendererConsoleObjects(); unregisterStaticMeshRendererConsoleObjects(); unregisterObjectGeometryConsoleObjects(); unregisterOverGrowthConsoleObjects(); unregisterDecalManagerConsoleObjects(); unregisterUndergrowthConsoleObjects(); unregisterNametagManagerConsoleObjects(); + unregisterTerrainCullerConsoleObjects(); unregisterTerrainConsoleObjects(); unregisterSkyDomeConsoleObjects(); unregisterGeometryTemplateConsoleObjects(); unregisterHemiMapManagerConsoleObjects(); unregisterShadowManagerConsoleObjects(); + unregisterWeatherManagerConsoleObjects(); unregisterLightManagerConsoleObjects(); -#endif if (classManager && classManager->getSingleton(renddx9abi::HostString("Terrain"))) classManager->unregisterSingleton(renddx9abi::HostString("Terrain")); return true; diff --git a/Code/BF2/Geom/NameTagRenderer.cpp b/Code/BF2/Geom/NameTagRenderer.cpp index 9ac3642e4..723b61857 100644 --- a/Code/BF2/Geom/NameTagRenderer.cpp +++ b/Code/BF2/Geom/NameTagRenderer.cpp @@ -5,6 +5,7 @@ #ifdef BF2_IMAGE_RENDDX9 #include "NameTagRenderer.h" +#include "StaticMesh.h" // staticMeshControlObject (sub_10103CB0) #include "NametagManager.h" // the items and the draw closure's statics (s_pulse, s_maxCallDistance) #include "../RendDX9/RendDX9Base.h" @@ -13,8 +14,7 @@ #include "../RendMisc/IRenderView.h" #include "../../RendDX9Abi/BfMemory.h" #include "../../RendDX9Abi/Frontier.h" -#include "../../RendDX9Abi/Vc71Map.h" -#include "../../RendDX9Abi/Vc71String.h" +#include #include #include @@ -61,50 +61,14 @@ namespace geom { IBase* createFontPortedDirect(); // NEW seams - drafted in integration/FontSystem_additions.inl (Font::Ported is private to that TU). // Font::Ported vslot +0x10, load(const std::string&) (0x100876A0). -bool fontPortedLoad(IBase* font, const vc71::string& path); +bool fontPortedLoad(IBase* font, const std::string& path); // Font::Ported::drawToTexture, PE 0x10087320 (non-virtual): blit `text` glyph by glyph into // `target` at *position, advancing position->x; returns the advance in pixels. float fontPortedDrawToTexture(IBase* font, dx9rend::EngineTexture* target, POINT* position, - const vc71::string& text, bool fromSystemMemory); + const std::string& text, bool fromSystemMemory); namespace { - -// [CHOSEN, not recovered] Fixed-layout view of the manager's item fields used by buffering. -// [RETIRE-WHEN: nametag-item-overlay] Replace this overlay with typed NametagItem members. - -struct TouchItemRendererFields -{ - unsigned char opaque00[0x08]; - int slot; // +0x08 the row in the owning renderer (m_slots / texture row) - int rendererType; // +0x0C which of the manager's renderers owns it (0/1/2) - vc71::string name; // +0x10 the text blitted into the row - unsigned char opaque2C[0x60 - 0x2C]; - int rankIcon; // +0x60 s_icons key blitted at the row's left, -1 = none - int colorIndex1; // +0x64 ColorArray index of the name quad (blendindices.y) - unsigned char opaque68[0x70 - 0x68]; - int colorIndex2; // +0x70 cross-fade target colour, -1 = colorIndex1 - unsigned char opaque74[0xB8 - 0x74]; - unsigned int flags; // +0xB8 bit 1 (2): show the rank icon; bit 3 (8): draw the - // name even in arrow mode - unsigned char arrowMode; // +0xBC nonzero: drawn as the off-screen arrow (drawArrows - // skips items where it is 0) and the name is not blitted -}; - -static_assert(offsetof(TouchItemRendererFields, slot) == 0x08, "item +0x08"); -static_assert(offsetof(TouchItemRendererFields, rendererType) == 0x0C, "item +0x0C"); -static_assert(offsetof(TouchItemRendererFields, name) == 0x10, "item +0x10"); -static_assert(offsetof(TouchItemRendererFields, rankIcon) == 0x60, "item +0x60"); -static_assert(offsetof(TouchItemRendererFields, colorIndex1) == 0x64, "item +0x64"); -static_assert(offsetof(TouchItemRendererFields, colorIndex2) == 0x70, "item +0x70"); -static_assert(offsetof(TouchItemRendererFields, flags) == 0xB8, "item +0xB8"); -static_assert(offsetof(TouchItemRendererFields, arrowMode) == 0xBC, "item +0xBC"); - -inline TouchItemRendererFields& touchItemFields(NametagItem* item) -{ - return *reinterpret_cast(item); -} - inline IDirect3DDevice9* device() { // dword_1023B970 + 0x0C, re-read at every use exactly as the image does. @@ -170,39 +134,6 @@ void releaseIconResources(NametagIcon& icon) } } -// The VC7.1 _Tree::_Erase shape (recurse right, walk left, free) for a vc71 header whose nodes carry -// _Isnil at nodeSize - 3. Vc71Map.h's map_layout has no destroy of its own; the +0x14 member needs -// one. [CHOSEN] helper; the tree it walks is always empty (nothing ever inserts into it). -void eraseVc71Subtree(unsigned char* node, unsigned int nilOffset) -{ - while (!node[nilOffset]) - { - eraseVc71Subtree(reinterpret_cast(node)[2], nilOffset); - unsigned char* const left = reinterpret_cast(node)[0]; - ::renddx9abi::engineFree(node); - node = left; - } -} - -// The member destructor the image emits for +0x14 (0x101B3347..0x101B336B): erase(begin(), end()) -// - whose whole-range fast path is _Erase(root) plus a relink - then free the head, zero head and -// size. -void destroyVc71Map(vc71::map_layout& map, unsigned int nodeSize) -{ - unsigned char* const head = reinterpret_cast(map.head); - if (head) - { - eraseVc71Subtree(reinterpret_cast(head)[1], nodeSize - 3); - unsigned char** const links = reinterpret_cast(head); - links[0] = head; - links[1] = head; - links[2] = head; - ::renddx9abi::engineFree(head); - } - map.head = 0; - map.size = 0; -} - const float kInverseTextureWidth = 0.001953125f; // flt_101E14C4 = 1/512 const float kInverseTextureHeight = 0.0009765625f; // flt_10221E20 = 1/1024 @@ -231,15 +162,14 @@ NameTagRenderer::IconMap NameTagRenderer::s_icons; // Initializes the trees and text textures. Render-path activation must initialize the // remaining resource pointers before destruction; the constructor leaves them untouched. +// The three trees are constructed first, as members (heads sub_101315F0, sub_1008A320, +// sub_101B4870). +// PE 0x101B2F00. NameTagRenderer::NameTagRenderer() : m_stagingTexture(0) , m_nameTexture(0) { - m_freeSlots.construct(); // sub_101315F0: 0x14-byte head, _Isnil (+0x11) = 1, self-links - m_slotMap.construct(0x18); // sub_1008A320: 0x18-byte head, _Isnil (+0x15) = 1 - m_set20.construct(); // sub_101B4870: 0x14-byte head - ++s_instanceCount; // dword_10266D9C m_dirty = 0; m_byte3849 = 0; @@ -251,8 +181,10 @@ NameTagRenderer::NameTagRenderer() // Releases this renderer's resources, then unregisters its render-path listener. // The final instance releases shared icon/bar resources once per distinct texture; -// shared maps retain their entries until process teardown. - +// shared maps retain their entries until process teardown. The member trees are destroyed after +// the body, m_set20 first, then m_slotMap, then m_freeSlots (0x101B55A0, sub_1008A450, +// sub_10131B00). +// PE 0x101B2FE0 NameTagRenderer::~NameTagRenderer() { if (s_arrowTexture) @@ -313,10 +245,6 @@ NameTagRenderer::~NameTagRenderer() dx9rend::unregisterRenderPathListener(static_cast(this)); } - - m_set20.destroy(); // 0x101B55A0 + free head + zero - destroyVc71Map(m_slotMap, 0x18); // sub_1008A450 + free head + zero - m_freeSlots.destroy(); // sub_10131B00 + free head + zero } @@ -338,10 +266,10 @@ void NameTagRenderer::initialize(int type, int slotCount, int colorCount, const // 0x101B08F0, 1,221 B, `retn 4` - where every GPU resource is made. +// PE 0x101B08F0 // IT IS NOT idempotent, AND that IS shipped. Each activation creates NEW textures and buffers for // +0x2C/+0x30/+0x34/+0x38/+0x3C without releasing the previous ones, and takes one more reference on // every static. A render-path change therefore leaks one set per renderer. Preserved. - void NameTagRenderer::onRenderPathActivated(int path) { (void)path; // never read @@ -353,7 +281,7 @@ void NameTagRenderer::onRenderPathActivated(int path) // dispatches through whatever was stored, null included. This tree's // createFontPortedDirect uses `new`, so on out-of-memory it throws where retail stores 0. s_font = createFontPortedDirect(); - fontPortedLoad(s_font, vc71::string("Fonts/BF1942.font")); // result ignored + fontPortedLoad(s_font, std::string("Fonts/BF1942.font")); // result ignored } else { @@ -366,13 +294,13 @@ void NameTagRenderer::onRenderPathActivated(int path) s_effect = static_cast(dx9rend::shaderManagerGetEffect( dx9rend::g_shaderManager, "mods/xpack/shaders/Nametag")); // sub_1001E420 each: the caller-facing lookup that takes a reference. Order as shipped. - s_texLayer0 = dx9rend::effectGetShaderParameterTyped(s_effect, vc71::string("TEXLAYER0")); - s_texLayer1 = dx9rend::effectGetShaderParameterTyped(s_effect, vc71::string("TEXLAYER1")); + s_texLayer0 = dx9rend::effectGetShaderParameterTyped(s_effect, std::string("TEXLAYER0")); + s_texLayer1 = dx9rend::effectGetShaderParameterTyped(s_effect, std::string("TEXLAYER1")); s_transformationArray = - dx9rend::effectGetShaderParameterTyped(s_effect, vc71::string("TransformationArray")); - s_colorArray = dx9rend::effectGetShaderParameterTyped(s_effect, vc71::string("ColorArray")); - s_fadeOut = dx9rend::effectGetShaderParameterTyped(s_effect, vc71::string("FadeOut")); - s_alphaArray = dx9rend::effectGetShaderParameterTyped(s_effect, vc71::string("AlphaArray")); + dx9rend::effectGetShaderParameterTyped(s_effect, std::string("TransformationArray")); + s_colorArray = dx9rend::effectGetShaderParameterTyped(s_effect, std::string("ColorArray")); + s_fadeOut = dx9rend::effectGetShaderParameterTyped(s_effect, std::string("FadeOut")); + s_alphaArray = dx9rend::effectGetShaderParameterTyped(s_effect, std::string("AlphaArray")); } else { @@ -388,7 +316,7 @@ void NameTagRenderer::onRenderPathActivated(int path) // the shared arrow texture (dword_10266D98) if (!s_arrowTexture) s_arrowTexture = static_cast( - dx9rend::textureManagerGetTexture(vc71::string("Menu/Nametag/loactionArrow.dds"))); + dx9rend::textureManagerGetTexture(std::string("Menu/Nametag/loactionArrow.dds"))); else dx9rend::textureAddRef(s_arrowTexture); // shared table slot +0x08 @@ -481,19 +409,22 @@ int NameTagRenderer::getCurrentRenderPath() const // ICF_getDwordAt0x4 return m_renderPath; // never written - see the header } -vc71::string NameTagRenderer::getRenderPathListenerName() const +// PE 0x101B5CF0 +std::string NameTagRenderer::getRenderPathListenerName() const { - return vc71::string("NameTagRenderer"); // aNametagrendere_0, capital T + return std::string("NameTagRenderer"); // aNametagrendere_0, capital T } // The device forwarding NametagManager's listener subobject performs for each renderer. +// PE 0x101B06B0 void NameTagRenderer::onDeviceLost() // a tail jump { dx9rend::textureReleaseD3DResource(m_nameTexture); // sub_10014E70, no null test } +// PE 0x101B06C0 void NameTagRenderer::onDeviceReset() { // Re-created into the same wrapper; no managed / recreate-mode swap around it this time. @@ -501,6 +432,7 @@ void NameTagRenderer::onDeviceReset() TextureWidth, TextureHeight, D3DFMT_A8R8G8B8, 1, 0, m_nameTexture)); } +// PE 0x101B06F0 void NameTagRenderer::onDeviceDestroy() // (nullsub_67) { } @@ -529,21 +461,25 @@ void NameTagRenderer::clearSlotRow(int slot, int unused) void NameTagRenderer::bufferItem(NametagItem* item, bool rebuildText) { - TouchItemRendererFields& fields = touchItemFields(item); + // The item's fields used here: m_slot (the row in m_slots and the texture), m_name (the text + // blitted into the row), m_rankIcon (the s_icons key blitted at the row's left, -1 = none), + // m_colorIndex / m_flashColorIndex (the name quad's ColorArray pair, -1 = no cross-fade), + // m_flags (bit 1: show the rank icon; bit 3: draw the name even in arrow mode) and m_arrowMode. + NametagItem& fields = *item; if (rebuildText) - clearSlotRow(fields.slot, 0); + clearSlotRow(fields.m_slot, 0); POINT pen; // var_1C / var_18 pen.x = 0; - pen.y = fields.slot << 4; + pen.y = fields.m_slot << 4; int iconWidth = 0; // var_8 if (rebuildText) { - const int rankIcon = fields.rankIcon; + const int rankIcon = fields.m_rankIcon; IconMap::iterator it = s_icons.find(rankIcon); - if (((fields.flags >> 1) & 1) != 0 && rankIcon != -1) + if (((fields.m_flags >> 1) & 1) != 0 && rankIcon != -1) { if (it == s_icons.end() && s_icons.size() != 0) it = s_icons.begin(); @@ -558,7 +494,7 @@ void NameTagRenderer::bufferItem(NametagItem* item, bool rebuildText) rect.top = it->second.top; rect.right = it->second.right; rect.bottom = it->second.bottom; - if (fields.rankIcon != -1) + if (fields.m_rankIcon != -1) device()->UpdateSurface(source, &rect, target, &pen); // vslot +0x78 source->Release(); target->Release(); @@ -569,8 +505,8 @@ void NameTagRenderer::bufferItem(NametagItem* item, bool rebuildText) pen.x += iconWidth; pen.y += 3; - if (!fields.arrowMode || ((fields.flags >> 3) & 1) != 0) - fontPortedDrawToTexture(s_font, m_nameTexture, &pen, fields.name, true); // result dropped + if (!fields.m_arrowMode || ((fields.m_flags >> 3) & 1) != 0) + fontPortedDrawToTexture(s_font, m_nameTexture, &pen, fields.m_name, true); // result dropped } const float invHalfWidth = @@ -581,8 +517,8 @@ void NameTagRenderer::bufferItem(NametagItem* item, bool rebuildText) const float pixelBias = (halfPen - static_cast(std::floor(static_cast(halfPen)))) * invHalfWidth; - const short iconColor = (m_type == 0 && fields.colorIndex1 == 3) ? 3 : 0; - NametagSlotRecord& record = m_slots[fields.slot]; + const short iconColor = (m_type == 0 && fields.m_colorIndex == 3) ? 3 : 0; + NametagSlotRecord& record = m_slots[fields.m_slot]; NametagVertex* const v = record.vertices; if (rebuildText) @@ -590,19 +526,19 @@ void NameTagRenderer::bufferItem(NametagItem* item, bool rebuildText) const float halfWidth = halfPen * invHalfWidth; // var_4 const float left = -halfWidth - pixelBias; const float halfHeight = invHalfHeight * 8.0f; // flt_1020AAD4 - const float rowTop = static_cast(fields.slot << 4) * kInverseTextureHeight; + const float rowTop = static_cast(fields.m_slot << 4) * kInverseTextureHeight; const float iconWidthF = static_cast(iconWidth); const float iconRight = (iconWidthF - halfPen) * invHalfWidth - pixelBias; const float iconU = iconWidthF * kInverseTextureWidth; setVertex(v[0], left, halfHeight, 0.0f, 0.0f, rowTop); setVertex(v[1], iconRight, halfHeight, 0.0f, iconU, - static_cast(fields.slot << 4) * kInverseTextureHeight); + static_cast(fields.m_slot << 4) * kInverseTextureHeight); const float negHalfHeight = -halfHeight; // the image parks it in var_14 for v7 setVertex(v[2], left, negHalfHeight, 0.0f, 0.0f, - static_cast((fields.slot + 1) << 4) * kInverseTextureHeight); + static_cast((fields.m_slot + 1) << 4) * kInverseTextureHeight); setVertex(v[3], iconRight, negHalfHeight, 0.0f, iconU, - static_cast((fields.slot + 1) << 4) * kInverseTextureHeight); + static_cast((fields.m_slot + 1) << 4) * kInverseTextureHeight); // The name quad's left edge IS the icon quad's right edge: whole-vertex copies (indices too; // the colour indices are overwritten below). @@ -610,15 +546,16 @@ void NameTagRenderer::bufferItem(NametagItem* item, bool rebuildText) const float right = halfWidth - pixelBias; // arg_0 reused setVertex(v[5], right, halfHeight, 0.0f, static_cast(pen.x) * kInverseTextureWidth, - static_cast(fields.slot << 4) * kInverseTextureHeight); + static_cast(fields.m_slot << 4) * kInverseTextureHeight); v[6] = v[3]; setVertex(v[7], right, negHalfHeight, 0.0f, static_cast(pen.x) * kInverseTextureWidth, - static_cast((fields.slot + 1) << 4) * kInverseTextureHeight); + static_cast((fields.m_slot + 1) << 4) * kInverseTextureHeight); } // Colour indices: the icon quad takes 3 (renderer 0's colour-3 soldiers) or 0; the name quad the - // item's pair, colourIndex2 == -1 meaning "no cross-fade". The item is re-read for every vertex. + // item's pair, m_flashColorIndex == -1 meaning "no cross-fade". The item is re-read for every + // vertex. for (int i = NametagSlotRecord::IconQuad; i < NametagSlotRecord::NameQuad; ++i) { v[i].colorIndex1 = iconColor; @@ -626,9 +563,9 @@ void NameTagRenderer::bufferItem(NametagItem* item, bool rebuildText) } for (int i = NametagSlotRecord::NameQuad; i < NametagSlotRecord::VertexCount; ++i) { - v[i].colorIndex1 = static_cast(fields.colorIndex1); - v[i].colorIndex2 = static_cast(fields.colorIndex2 != -1 ? fields.colorIndex2 - : fields.colorIndex1); + v[i].colorIndex1 = static_cast(fields.m_colorIndex); + v[i].colorIndex2 = static_cast(fields.m_flashColorIndex != -1 ? fields.m_flashColorIndex + : fields.m_colorIndex); } m_dirty = 1; @@ -664,7 +601,7 @@ void NameTagRenderer::removeTexture(int key, int count) // Rank/target textures use system memory. Existing entries are overwritten without release; // buffer locks and texture dimensions must be valid. -void NameTagRenderer::setTexture(int key, int count, const vc71::string& textureName, +void NameTagRenderer::setTexture(int key, int count, const std::string& textureName, int x, int y, int width, int height) { const int bottom = y + height; // arg_10 += arg_8 @@ -751,8 +688,8 @@ void NameTagRenderer::setTexture(int key, int count, const vc71::string& texture // Loads both textures in the current pool and shares one quad between them. // Existing bar resources are not released, and the vertex-buffer lock is not checked. -void NameTagRenderer::createBar(int key, const vc71::string& fullTextureName, - const vc71::string& emptyTextureName, int left, int top, +void NameTagRenderer::createBar(int key, const std::string& fullTextureName, + const std::string& emptyTextureName, int left, int top, int right, int bottom, int fillStart, int fillEnd) { dx9rend::EngineTexture* const fullTexture = @@ -794,7 +731,8 @@ void NameTagRenderer::createBar(int key, const vc71::string& fullTextureName, } // ECX = key: equal_range (0x101B4E80) + erase(range) (0x101B54E0), nothing released. -// Unreferenced in the image. +// Unreferenced in the image (listing read: key spilled to a local, equal_range on s_bars, erase of the range). +// PE 0x101B27C0 void NameTagRenderer::removeBar(int key) { s_bars.erase(key); diff --git a/Code/BF2/Geom/NameTagRenderer.h b/Code/BF2/Geom/NameTagRenderer.h index f91805460..d5f14fc52 100644 --- a/Code/BF2/Geom/NameTagRenderer.h +++ b/Code/BF2/Geom/NameTagRenderer.h @@ -1,18 +1,18 @@ // Path: [INFERRED]; adjacent NametagManager.cpp is attested at RendDX9 0x1021CFB0. // Nametag renderer declarations, recovered from RendDX9.dll 1.50 (PE only). -// Retail member layout is 0x3860 bytes; embedded trees use VC7.1 layouts. +// The shipped member layout is 0x3860 bytes; the embedded trees are std containers here. #ifndef GEOM_NAMETAGRENDERER_H #define GEOM_NAMETAGRENDERER_H #include #include +#include #include "../Core/IBase.h" #include "../Math/Vec3.h" #include "../RendDX9/RendDX9Base.h" #include "../../RendDX9Abi/HfeAbi.h" -#include "../../RendDX9Abi/Vc71String.h" -#include "../../RendDX9Abi/Vc71Map.h" +#include namespace dice { namespace hfe { @@ -28,9 +28,8 @@ struct EngineTexture; namespace geom { // The manager's per-tag item (nt_core owns the class and its five vtables 0x1021CF70/80, 0x1021D080/ -// 90/A0). [INFERRED] name, from INametagManager's addTouchItem family. bufferItem reads it at the -// retail offsets listed in NameTagRenderer.cpp (TouchItemRendererFields); the integrator swaps that -// overlay for nt_core's typed members. +// 90/A0). [INFERRED] name, from INametagManager's addTouchItem family. bufferItem and the draws +// read its typed members (NametagManager.h). class NametagItem; @@ -135,7 +134,7 @@ class NameTagRenderer : public dx9rend::RenderPathListener virtual void onRenderPathChanged(int path); // +0x08 nullsub_53 virtual void onRenderPathNotification(int path); // +0x0C nullsub_53 virtual int getCurrentRenderPath() const; // +0x10 - virtual vc71::string getRenderPathListenerName() const; // +0x14 + virtual std::string getRenderPathListenerName() const; // +0x14 // forwarded by NametagManager's DeviceLostResetListener subobject (0x1021D0E8), which loops // over the three renderers (renderer + i * 0x3860, i < 3) @@ -190,13 +189,13 @@ class NameTagRenderer : public dx9rend::RenderPathListener // stores s_icons[key] - or, for count > 0, s_icons[key + i] = the i-th width-wide cell. // Callers: the manager's `Nametags.setTexture` path 0x1012C720 (count = the console's index // argument) and 0x1012D610 (count 0). - static void setTexture(int key, int count, const vc71::string& textureName, + static void setTexture(int key, int count, const std::string& textureName, int x, int y, int width, int height); // 0x101B2D00, 502 B. ECX = key, EDX = &fullTextureName, then (const std::string& emptyTextureName, // left, top, right, bottom, fillStart, fillEnd), `retn 1Ch`. Caller: 0x1012C7B4 (the second // `Nametags.setTexture` after `Nametags.createBar`). - static void createBar(int key, const vc71::string& fullTextureName, - const vc71::string& emptyTextureName, int left, int top, int right, + static void createBar(int key, const std::string& fullTextureName, + const std::string& emptyTextureName, int left, int top, int right, int bottom, int fillStart, int fillEnd); // ECX = key. s_bars.erase(key) with no resource release. NO caller in the image // (and IDA had not even made it a function); kept because the body is shipped. @@ -212,11 +211,15 @@ class NameTagRenderer : public dx9rend::RenderPathListener NameTagRenderer(const NameTagRenderer&); NameTagRenderer& operator=(const NameTagRenderer&); - // data, in shipped order + // data, in shipped order. The `+0xNN` comments give the shipped x86 offsets; from m_slotMap on + // the std containers make the native offsets differ. int m_renderPath; // +0x0004 never written (see the layout note) - vc71::set_layout m_freeSlots; // +0x0008 vestigial std::set - vc71::map_layout m_slotMap; // +0x0014 vestigial, 0x18-byte nodes - vc71::set_layout m_set20; // +0x0020 vestigial, 0x14-byte nodes + std::set m_freeSlots; // +0x0008 vestigial (head sub_101315F0) + std::map m_slotMap; // +0x0014 vestigial, 0x18-byte nodes (head + // sub_1008A320, the slot maps' shape) + std::set m_set20; // +0x0020 vestigial, 0x14-byte nodes (head + // sub_101B4870); a four-byte key, + // [INFERRED] int - nothing inserts one dx9rend::EngineTexture* m_stagingTexture; // +0x002C dx9rend::EngineTexture* m_nameTexture; // +0x0030 void* m_vertexBuffer; // +0x0034 not initialised by the ctor @@ -251,35 +254,21 @@ class NameTagRenderer : public dx9rend::RenderPathListener friend struct NameTagRendererLayoutCheck; }; -// Offsets are held here, in both plugin flavours: the class holds no host container and no native -// STL member, so the retail size is the rebuilt size in the native AND the compat build. +// The vertex and record PODs keep their shipped sizes on every target (the GPU vertex declaration +// and the uploaded record block depend on them); the pointer-holding icon and bar values keep +// theirs on x86. The renderer itself holds std containers, so only the members before them keep +// their shipped offsets; NametagManager allocates and indexes the renderers as a typed array +// (shipped: 3 * 0x3860 + 4 at 0x1012F9B0, stride 0x3860). struct NameTagRendererLayoutCheck { static_assert(sizeof(NametagVertex) == 0x1C, "the Nametag.fx declaration is 28 bytes"); static_assert(sizeof(NametagSlotRecord) == 0xE0, "0x101B4230 builds 224-byte records"); +#if defined(_M_IX86) static_assert(sizeof(NametagIcon) == 0x18, "s_icons' node is 0x2C = 12 + 4 + 24 + 4"); static_assert(sizeof(NametagBar) == 0x3C, "s_bars' node is 0x50 = 12 + 4 + 60 + 4; " "createBar copies 15 dwords"); -#if defined(_M_IX86) static_assert(offsetof(NameTagRenderer, m_renderPath) == 0x0004, "+0x04"); static_assert(offsetof(NameTagRenderer, m_freeSlots) == 0x0008, "+0x08"); - static_assert(offsetof(NameTagRenderer, m_slotMap) == 0x0014, "+0x14"); - static_assert(offsetof(NameTagRenderer, m_set20) == 0x0020, "+0x20"); - static_assert(offsetof(NameTagRenderer, m_stagingTexture) == 0x002C, "+0x2C"); - static_assert(offsetof(NameTagRenderer, m_nameTexture) == 0x0030, "+0x30"); - static_assert(offsetof(NameTagRenderer, m_vertexBuffer) == 0x0034, "+0x34"); - static_assert(offsetof(NameTagRenderer, m_indexBuffer) == 0x0038, "+0x38"); - static_assert(offsetof(NameTagRenderer, m_arrowVertexBuffer) == 0x003C, "+0x3C"); - static_assert(offsetof(NameTagRenderer, m_slots) == 0x0048, "+0x48"); - static_assert(offsetof(NameTagRenderer, m_dirty) == 0x3848, "+0x3848"); - static_assert(offsetof(NameTagRenderer, m_byte384A) == 0x384A, "+0x384A"); - static_assert(offsetof(NameTagRenderer, m_slotCount) == 0x384C, "+0x384C"); - static_assert(offsetof(NameTagRenderer, m_colorCount) == 0x3850, "+0x3850"); - static_assert(offsetof(NameTagRenderer, m_type) == 0x3854, "+0x3854"); - static_assert(offsetof(NameTagRenderer, m_fadeStart) == 0x3858, "+0x3858"); - static_assert(offsetof(NameTagRenderer, m_fadeEnd) == 0x385C, "+0x385C"); - static_assert(sizeof(NameTagRenderer) == 0x3860, - "NametagManager's ctor allocates 3 * 0x3860 + 4 (0x1012F9B0) and strides 0x3860"); #endif }; diff --git a/Code/BF2/Geom/NameTagRendererDraw.inl b/Code/BF2/Geom/NameTagRendererDraw.inl index b1f039cec..65ee504a3 100644 --- a/Code/BF2/Geom/NameTagRendererDraw.inl +++ b/Code/BF2/Geom/NameTagRendererDraw.inl @@ -21,15 +21,13 @@ #include "../RendDX9/Texture.h" #include "../RendMisc/IRenderer.h" #include "../RendMisc/IRenderView.h" +#include "../../RendDX9Abi/D3dx9Sdk.h" // The host interfaces, imported the way BundledMeshDraw.cpp / XpLightManager.cpp import them: under // the retail (compat) host ABI, HfeAbi.h already supplies ClassManager's VC7.1 registration carriers, // so the engine's own ClassManager header is kept out while these interfaces come in. Only virtual // dispatch and scalar/pointer fields cross the boundary below; the one host container (getPcos) is -// bridged per flavour at ntCopySeats. -#if !BF2_PLUGIN_ABI_NATIVE -#define CORE_CLASSMANAGER_H -#endif +// copied at ntCopySeats. #include "../Game/SingletonServer.h" // INametagManager - needs the integrator's +0x60..+0x68 #include "../Game/Objects/IObject.h" #include "../Game/Objects/IObjectTemplate.h" @@ -41,22 +39,14 @@ #include "../Game/Objects/Game/Kit.h" #include "../Scene/Object/PlayerManager.h" #include "../Scene/Object/ObjectTypes/Game/IPlayerControlObject.h" -#if !BF2_PLUGIN_ABI_NATIVE -#undef CORE_CLASSMANAGER_H -#endif #include #include #include #include -// D3DXMatrixRotationZ - the d3dx9_25 import behind the thunk 0x101C4ACE (called by drawArrows and -// drawIcons). Declared raw because the modern SDK ships no D3DX9 headers, exactly as RenderView.cpp -// declares D3DXMatrixOrthoLH: the D3DXMATRIX* is sixteen floats (a Mat4 here). Two 4-byte parameters -// -> @8; /alternatename bridges the decorated reference onto the undecorated import. -struct D3DXMATRIX; -extern "C" D3DXMATRIX* __stdcall D3DXMatrixRotationZ(D3DXMATRIX* out, float angle); -#pragma comment(linker, "/alternatename:_D3DXMatrixRotationZ@8=_D3DXMatrixRotationZ") +// D3DXMatrixRotationZ is the d3dx9_25 import behind the thunk 0x101C4ACE (called by drawArrows and +// drawIcons); its D3DXMATRIX is sixteen floats (a Mat4 here). namespace dice { namespace hfe { @@ -89,153 +79,58 @@ namespace geom { extern IBase* g_NametagManager; // [CHOSEN, not recovered] integration helpers for tag drawing. -// Draw paths borrow the manager's item map, pulse value and maximum call distance. -// Preserve the host interface slots and the VC7.1 map/node layout used by the views below. +// Draw paths borrow the manager's item map, pulse value and maximum call distance through the +// INametagManager slots the image calls. namespace { -// Seam 3: the item fields this closure reads (the owning instructions quoted per field). Offsets -// +0x08/+0x0C/+0x10/+0x60/+0x64/+0x70/+0xB8/+0xBC are nt_renderer's (bufferItem) and agree. - -struct TouchItemDrawFields -{ - unsigned char opaque00[0x08]; - int slot; // +0x08 every draw: `mov ecx,[esi+8]; shl ecx,4` (the Vec4 index) - int rendererType; // +0x0C `cmp [esi+0Ch], m_type` (arrows, icons) / `cmp [esi+0Ch],0` - vc71::string name; // +0x10 bufferItem's; not read here - unsigned char opaque2C[0x54 - 0x2C]; - int distance; // +0x54 [INFERRED] rounded metres to the local player's vehicle - // (update 0x1012CE93..0x1012CEB3 fistp); drawIcons - // 0x101B2059 `fild [esi+54h]` - double fadeDistance; // +0x58 [INFERRED] the item's own fade END; 0.0 = use the - // renderer's pair. `fld qword [esi+58h]` in every FadeOut - int rankIcon; // +0x60 bufferItem's; not read here - int colorIndex1; // +0x64 `mov cx, word [esi+64h]` (arrows), `movzx edx, word - // [esi+64h]` (bars), `mov ebx,[esi+64h]` (icons) - int iconKey; // +0x68 drawIcons the s_icons key of the icon - int flashIconKey; // +0x6C drawIcons 0x101B1CE0 (TEXLAYER1 icon, -1 = the icon - // itself); vehicle icons 0x101B39DB (a dead lookup) - int colorIndex2; // +0x70 `mov edx,[esi+70h]; cmp edx,-1` - -1 = colorIndex1 - unsigned char opaque74[0x78 - 0x74]; - int elevationIconKey; // +0x78 [INFERRED] update writes 48 (above) / 49 / -1 - // (0x1012CDF8, 0x1012CE13); drawIcons 0x101B1D24 draws it - // as a second quad - float iconRotation; // +0x7C radians; drawIcons 0x101B1FDD, when flags bit 9 - int team; // +0x80 `cmp [esi+80h], eax` against the viewer's getTeam() - unsigned char opaque84[0xB8 - 0x84]; - unsigned int flags; // +0xB8 bits read here: 3, 4, 5, 9, 11, 12, 14, 16 (the byte - // test `test byte [esi+0BAh],1`), 17 - see the bodies - unsigned char arrowMode; // +0xBC nonzero: drawn as the off-screen arrow - unsigned char rebuffer; // +0xBD update's re-buffer request; NOT read by this closure - unsigned char inView; // +0xBE [INFERRED] update the render view's frustum - // test of the item's +0x90 position - unsigned char pad0BF; // +0xBF - WeakPtr player; // +0xC0 the player a renderer-0 (player) item tags - what - // 0x10131540 returns. (Renderer-2 items keep an object - // here: update 0x101305A8 reads its +0x14 template.) -}; - -static_assert(offsetof(TouchItemDrawFields, slot) == 0x08, "item +0x08"); -static_assert(offsetof(TouchItemDrawFields, rendererType) == 0x0C, "item +0x0C"); -static_assert(offsetof(TouchItemDrawFields, name) == 0x10, "item +0x10"); -static_assert(offsetof(TouchItemDrawFields, distance) == 0x54, "item +0x54"); -static_assert(offsetof(TouchItemDrawFields, fadeDistance) == 0x58, "item +0x58"); -static_assert(offsetof(TouchItemDrawFields, rankIcon) == 0x60, "item +0x60"); -static_assert(offsetof(TouchItemDrawFields, colorIndex1) == 0x64, "item +0x64"); -static_assert(offsetof(TouchItemDrawFields, iconKey) == 0x68, "item +0x68"); -static_assert(offsetof(TouchItemDrawFields, flashIconKey) == 0x6C, "item +0x6C"); -static_assert(offsetof(TouchItemDrawFields, colorIndex2) == 0x70, "item +0x70"); -static_assert(offsetof(TouchItemDrawFields, elevationIconKey) == 0x78, "item +0x78"); -static_assert(offsetof(TouchItemDrawFields, iconRotation) == 0x7C, "item +0x7C"); -static_assert(offsetof(TouchItemDrawFields, team) == 0x80, "item +0x80"); -static_assert(offsetof(TouchItemDrawFields, flags) == 0xB8, "item +0xB8"); -static_assert(offsetof(TouchItemDrawFields, arrowMode) == 0xBC, "item +0xBC"); -static_assert(offsetof(TouchItemDrawFields, rebuffer) == 0xBD, "item +0xBD"); -static_assert(offsetof(TouchItemDrawFields, inView) == 0xBE, "item +0xBE"); -static_assert(offsetof(TouchItemDrawFields, player) == 0xC0, "item +0xC0"); - -inline TouchItemDrawFields& ntItem(NametagItem* item) -{ - return *reinterpret_cast(item); -} +// The item fields this closure reads are NametagItem's typed members (NametagManager.h); the +// shipped instructions per field: +// m_slot +0x08 every draw: `mov ecx,[esi+8]; shl ecx,4` (the Vec4 index) +// m_type +0x0C `cmp [esi+0Ch], m_type` (arrows, icons) / `cmp [esi+0Ch],0` +// m_distance +0x54 [INFERRED] rounded metres to the local player's vehicle (update +// 0x1012CE93..0x1012CEB3 fistp); drawIcons 0x101B2059 `fild [esi+54h]` +// m_viewDistance +0x58 [INFERRED] the item's own fade END; 0.0 = use the renderer's pair. +// `fld qword [esi+58h]` in every FadeOut +// m_colorIndex +0x64 `mov cx, word [esi+64h]` (arrows), `movzx edx, word [esi+64h]` (bars), +// `mov ebx,[esi+64h]` (icons) +// m_icon +0x68 drawIcons: the s_icons key of the icon +// m_callIcon +0x6C drawIcons 0x101B1CE0 (TEXLAYER1 icon, -1 = the icon itself); vehicle +// icons 0x101B39DB (a dead lookup) +// m_flashColorIndex +0x70 `mov edx,[esi+70h]; cmp edx,-1` - -1 = m_colorIndex +// m_elevationIcon +0x78 [INFERRED] update writes 48 (above) / 49 / -1 (0x1012CDF8, 0x1012CE13); +// drawIcons 0x101B1D24 draws it as a second quad +// m_iconRotation +0x7C radians; drawIcons 0x101B1FDD, when flags bit 9 +// m_team +0x80 `cmp [esi+80h], eax` against the viewer's getTeam() +// m_flags +0xB8 bits read here: 3, 4, 5, 9, 11, 12, 14, 16 (the byte test +// `test byte [esi+0BAh],1`), 17 - see the bodies +// m_arrowMode +0xBC nonzero: drawn as the off-screen arrow +// m_inView +0xBE [INFERRED] update's render-view frustum test of the item's +0x90 +// position +// (m_dirty, +0xBD, is not read by this closure.) // flags bit n, as the image tests it (`shr reg, n; test reg8, 1`, or a byte test for bit 16). -inline bool ntFlag(const TouchItemDrawFields& item, unsigned int bit) +inline bool ntFlag(const NametagItem& item, unsigned int bit) { - return ((item.flags >> bit) & 1u) != 0; + return ((item.m_flags >> bit) & 1u) != 0; } // Seam 5: NametagItem::getPlayer() const, 0x10131540 - `mov eax,[ecx+0C0h]; test eax,eax; je; -// mov eax,[eax+4]` = the +0xC0 WeakPtr's get(). The image calls it from the three bar draws and -// inlines it in the vehicle-icon loop; both are this one source-level call. +// mov eax,[eax+4]` = the +0xC0 WeakPtr's get(), PlayerNametagItem::m_player. The image calls it +// from the three bar draws and inlines it in the vehicle-icon loop; both are this one source-level +// call. Every caller has already tested the item's type for 0 (a player item). (Renderer-2 items +// keep an object there: update 0x101305A8 reads its +0x14 template.) inline world::IPlayer* ntItemPlayer(NametagItem* item) { - return ntItem(item).player.get(); + return static_cast(item)->m_player.get(); } -// Seam 4: a read-only view of a VC7.1 std::map with a four-byte V - 12-byte header -// {comparator pad, _Myhead, _Mysize}, 0x18-byte nodes, _Isnil at +0x15. The manager's item map is -// one (the draws walk `[node+10h]` = value and `byte [node+15h]` = _Isnil); so is a VC7.1 host's -// PlayerControlObject::getPcos() map. Member names match nt_core's vc71::int_map_layout. - -template -struct NtIntMapNode -{ - NtIntMapNode* left; // +0x00 - NtIntMapNode* parent; // +0x04 - NtIntMapNode* right; // +0x08 - int key; // +0x0C - V value; // +0x10 - unsigned char color; // +0x14 - unsigned char isNil; // +0x15 - unsigned char pad[2]; // +0x16 -}; - -template -struct NtIntMapView -{ - typedef NtIntMapNode node; - - void* comp; // +0 - node* head; // +4 - unsigned size; // +8 - - node* begin() const { return head->left; } - node* end() const { return head; } - - // The VC7.1 _Tree iterator ++ (_Inc): the inlined walk at 0x101B1174 (drawArrows) and - // (drawIcons), the out-of-line 0x100A54F0 elsewhere. end() does not move. - static node* next(node* n) - { - if (n->isNil) - return n; - if (!n->right->isNil) - { - n = n->right; - while (!n->left->isNil) - n = n->left; - return n; - } - node* p = n->parent; - while (!p->isNil && n == p->right) - { - n = p; - p = p->parent; - } - return p; - } -}; - -typedef NtIntMapView NtItemMap; - -#if defined(_M_IX86) -static_assert(sizeof(NtIntMapNode) == 0x18, "sub_10131690 allocates 0x18-byte nodes"); -static_assert(offsetof(NtIntMapNode, value) == 0x10, "the draws read [node+10h]"); -static_assert(offsetof(NtIntMapNode, isNil) == 0x15, "the draws test byte [node+15h]"); -static_assert(sizeof(NtItemMap) == 12, "the VC7.1 std::map header is 12 bytes"); -#endif +// Seam 4: the manager's item map, std::map (NametagItemMap). The draws walk it +// in key order (the shipped _Tree iterator ++: inlined at 0x101B1174 (drawArrows) and in drawIcons, +// the out-of-line 0x100A54F0 elsewhere). +typedef NametagItemMap NtItemMap; // The host singletons, re-read at every use as the image does. @@ -275,7 +170,8 @@ inline const Vec4* ntTransformations(int type) return static_cast(static_cast(ntManager()->getTransformations(type))); } -// getItems() - +0x54 - the manager's item map by reference (`call [edx+54h]` then [eax+4]/[eax+8]). +// getItems() - +0x54 - the manager's item map by reference (`call [edx+54h]` then [eax+4]/[eax+8]: +// the shipped head and size words). The interface spells the answer const void*; the cast lives here. inline const NtItemMap& ntItems() { return *static_cast(ntManager()->getItems()); @@ -293,21 +189,6 @@ float ntClamp(float value, float low, float high) return value; } -// sub_10103CB0 - itself first, then the +0x28 parent chain, asking each for -// IID_IPlayerControlObject (read from ds:10208CF0 = 50373); the first answer, not the object. -// test esi,esi; je 0 / loop: call [eax+0Ch](50373); jnz ret; mov esi,[esi+28h]; test; jnz loop -world::IPlayerControlObject* ntOwningControlObject(world::IObject* object) -{ - while (object) - { - void* const found = object->queryInterface(world::IID_IPlayerControlObject); - if (found) - return static_cast(found); - object = object->getParent(); // the raw +0x28 read - } - return 0; -} - // The kit's cached ability component: `mov ecx,[eax+64h]` straight off ISoldier::getKit()'s result // (Kit's IObject base is its primary base, so the image applies no adjustment) - IObject's // m_abilityGLComponent, IID_IAbilityGLComp. @@ -331,7 +212,7 @@ void ntSetFadeOutA(dx9rend::Effect* effect, double itemFadeDistance, float start const double scale = 1.0f / (itemFadeDistance - itemStart); fadeOut[0] = static_cast(scale); fadeOut[1] = static_cast(-(scale * itemStart)); - dx9rend::effectGetShaderParameterBorrowedTyped(effect, vc71::string("FadeOut")) + dx9rend::effectGetShaderParameterBorrowedTyped(effect, std::string("FadeOut")) ->setValue(fadeOut, 0); } else @@ -339,7 +220,7 @@ void ntSetFadeOutA(dx9rend::Effect* effect, double itemFadeDistance, float start const float scale = 1.0f / (end - start); fadeOut[0] = scale; fadeOut[1] = -(scale * start); - dx9rend::effectGetShaderParameterBorrowedTyped(effect, vc71::string("FadeOut")) + dx9rend::effectGetShaderParameterBorrowedTyped(effect, std::string("FadeOut")) ->setValue(fadeOut, 0); } } @@ -353,7 +234,7 @@ void ntSetFadeOutB(dx9rend::Effect* effect, double itemFadeDistance, float start const double range = itemFadeDistance - itemStart; fadeOut[0] = static_cast(1.0f / range); fadeOut[1] = static_cast(-1.0f / range * itemStart); - dx9rend::effectGetShaderParameterBorrowedTyped(effect, vc71::string("FadeOut")) + dx9rend::effectGetShaderParameterBorrowedTyped(effect, std::string("FadeOut")) ->setValue(fadeOut, 0); } else @@ -361,7 +242,7 @@ void ntSetFadeOutB(dx9rend::Effect* effect, double itemFadeDistance, float start const float range = end - start; fadeOut[0] = 1.0f / range; fadeOut[1] = -1.0f / range * start; - dx9rend::effectGetShaderParameterBorrowedTyped(effect, vc71::string("FadeOut")) + dx9rend::effectGetShaderParameterBorrowedTyped(effect, std::string("FadeOut")) ->setValue(fadeOut, 0); } } @@ -369,25 +250,14 @@ void ntSetFadeOutB(dx9rend::Effect* effect, double itemFadeDistance, float start // The by-value copy of `*pco->getPcos()` the vehicle-icon loop walks (0x101B3967: 0x10132860, the // map copy constructor, into a local at [ebp-9Ch]; destroyed by 0x10132580 at 0x101B3E18). -// THE MAP belongs TO THE host. Under a retail BF2.exe it is the VC7.1 std::map (0x18-byte nodes, the same shape as the item map); under the native host it -// is that host's own std::map. The copy is plugin-local and its container shape is unobservable, so -// both flavours copy into a native std::map in key order. +// THE MAP belongs TO THE host: its std::map (in the image 0x18-byte +// nodes, the same shape as the item map). The copy is plugin-local and is walked in key order. typedef std::map NtSeatMap; NtSeatMap ntCopySeats(world::IPlayerControlObject* pco) { -#if BF2_PLUGIN_ABI_NATIVE return NtSeatMap(*pco->getPcos()); // +0x60 -#else - typedef NtIntMapView HostSeatMap; - const HostSeatMap* const host = reinterpret_cast(pco->getPcos()); // +0x60 - NtSeatMap copy; - for (HostSeatMap::node* n = host->begin(); n != host->end(); n = HostSeatMap::next(n)) - copy.insert(copy.end(), NtSeatMap::value_type(n->key, n->value)); - return copy; -#endif } // The s_icons / s_bars keys this closure looks up: values of the console enum "NametagItemIDs" @@ -413,9 +283,9 @@ const float kAmmoStatusScale = 0.06666667f; // flt_10221DCC = 0x3D888889 (1/15 // 0x101B3E50, 122 B - the per-renderer draw NametagManager::draw calls for renderers 2, 1, 0. +// PE 0x101B3E50 // The StateManager bracket (sub_100261A0 / sub_100261B0, the latter a tail jump) wraps everything, // including a demo playback's names-only frame. The viewing-player gate is the inlined 0x101B0550. - void NameTagRenderer::draw() { if (!ntViewingPlayer()) @@ -453,7 +323,7 @@ float NameTagRenderer::hitPointFraction(world::IObject* object) // 0x101B05E0, 88 B - when bufferItem has dirtied the records, copy m_slotCount * 224 bytes of them // into the slot vertex buffer. The byte count is `(n * 8 - n) << 5` (rep movsd + movsb). // The unlock and the m_dirty clear run whether or not the lock succeeded. - +// PE 0x101B05E0 void NameTagRenderer::uploadSlots() { if (!m_dirty) @@ -469,19 +339,19 @@ void NameTagRenderer::uploadSlots() // Draws all name slots in one indexed pass using the manager's colors, transforms, and alpha. // Names fade between view-space w = 2000 and 3000, independently of renderer fade settings. - +// PE 0x101B0750 void NameTagRenderer::drawNames() { - dx9rend::effectSetTechniqueByName(s_effect, vc71::string("nametag")); // result dropped + dx9rend::effectSetTechniqueByName(s_effect, std::string("nametag")); // result dropped dx9rend::effectBegin(s_effect); dx9rend::effectBeginPass(s_effect, 0); float fadeOut[2]; fadeOut[0] = 0.001f; fadeOut[1] = -2.0f; - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("FadeOut")) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("FadeOut")) ->setValue(fadeOut, 0); - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("CrossFadeValue")) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("CrossFadeValue")) ->setValue(&NametagManager::s_pulse, 0); s_colorArray->setValue(ntManager()->getColors(m_type), @@ -506,8 +376,8 @@ void NameTagRenderer::drawNames() void NameTagRenderer::drawArrows() { - dx9rend::effectSetTechniqueByName(s_effect, vc71::string("nametag_arrow")); - if (ntItems().size == 0) // `cmp [eax+8],0; jbe` + dx9rend::effectSetTechniqueByName(s_effect, std::string("nametag_arrow")); + if (ntItems().size() == 0) // `cmp [eax+8],0; jbe` return; dx9rend::effectBegin(s_effect); @@ -523,34 +393,33 @@ void NameTagRenderer::drawArrows() aspectMul[0] = static_cast(dx9rend::textureDims(s_arrowTexture)[0]) / widthViewport[2]; aspectMul[2] = 1.0f; aspectMul[3] = 1.0f; - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("AspectMul")) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("AspectMul")) ->setValue(aspectMul, 0); const NtItemMap& items = ntItems(); // the second getItems call - for (NtItemMap::node* it = items.begin(); it != items.end(); it = NtItemMap::next(it)) + for (NtItemMap::const_iterator it = items.begin(); it != items.end(); ++it) { - NametagItem* const touchItem = it->value; - TouchItemDrawFields& item = ntItem(touchItem); - if (item.rendererType != m_type || !item.arrowMode) + NametagItem& item = *it->second; + if (item.m_type != m_type || !item.m_arrowMode) continue; const Vec4* const forY = ntTransformations(m_type); const Vec4* const forX = ntTransformations(m_type); Mat4 rotation; D3DXMatrixRotationZ(reinterpret_cast(&rotation), - std::atan2(forX[item.slot].x, forY[item.slot].y) + kHalfPi); + std::atan2(forX[item.m_slot].x, forY[item.m_slot].y) + kHalfPi); float arrowRotation[4]; arrowRotation[0] = rotation.m[0]; // _11 arrowRotation[1] = rotation.m[1]; // _12 arrowRotation[2] = rotation.m[4]; // _21 arrowRotation[3] = rotation.m[5]; // _22 - const Vec4 arrowTransformation = ntTransformations(m_type)[item.slot]; + const Vec4 arrowTransformation = ntTransformations(m_type)[item.m_slot]; - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("ArrowRotation")) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("ArrowRotation")) ->setValue(arrowRotation, 0); - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("ArrowTransformation")) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("ArrowTransformation")) ->setValue(&arrowTransformation, 0); - ntSetFadeOutA(s_effect, item.fadeDistance, m_fadeStart, m_fadeEnd); + ntSetFadeOutA(s_effect, item.m_viewDistance, m_fadeStart, m_fadeEnd); NametagVertex* const vertices = static_cast(dx9rend::vertexBufferLock(m_arrowVertexBuffer, 0, 0, 0)); @@ -559,11 +428,11 @@ void NameTagRenderer::drawArrows() // The item is re-read for every vertex, as the image does. for (int i = 0; i < 6; ++i) { - vertices[i].slot = static_cast(item.slot); - vertices[i].colorIndex1 = static_cast(item.colorIndex1); - vertices[i].colorIndex2 = static_cast(item.colorIndex2 != -1 - ? item.colorIndex2 - : item.colorIndex1); + vertices[i].slot = static_cast(item.m_slot); + vertices[i].colorIndex1 = static_cast(item.m_colorIndex); + vertices[i].colorIndex2 = static_cast(item.m_flashColorIndex != -1 + ? item.m_flashColorIndex + : item.m_colorIndex); } } dx9rend::vertexBufferUnlock(m_arrowVertexBuffer); @@ -602,7 +471,7 @@ void NameTagRenderer::drawHealthBars() return; const NtItemMap& items = ntItems(); - dx9rend::effectSetTechniqueByName(s_effect, vc71::string("nametag_healthbar")); + dx9rend::effectSetTechniqueByName(s_effect, std::string("nametag_healthbar")); if (s_bars.size() == 0) // dword_102670B8, `jbe` return; const BarMap::iterator bar = s_bars.find(kICHealthBar); // unchecked @@ -611,24 +480,24 @@ void NameTagRenderer::drawHealthBars() dx9rend::effectBeginPass(s_effect, 0); s_texLayer0->setValue(bar->second.full.texture, 0); s_texLayer1->setValue(bar->second.empty.texture, 0); - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("ColorIndex1")) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("ColorIndex1")) ->setInt(0); - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("ColorIndex2")) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("ColorIndex2")) ->setInt(0); - for (NtItemMap::node* it = items.begin(); it != items.end(); it = NtItemMap::next(it)) + for (NtItemMap::const_iterator it = items.begin(); it != items.end(); ++it) { if (m_type != 0) continue; - NametagItem* const touchItem = it->value; - TouchItemDrawFields& item = ntItem(touchItem); - if (item.rendererType != 0) + NametagItem* const touchItem = it->second; + NametagItem& item = *touchItem; + if (item.m_type != 0) continue; - if (item.team != viewer->getTeam()) // PE +0xE4 + if (item.m_team != viewer->getTeam()) // PE +0xE4 continue; - if (!item.inView) + if (!item.m_inView) continue; - if (item.arrowMode) + if (item.m_arrowMode) continue; world::IPlayer* const player = ntItemPlayer(touchItem); @@ -643,20 +512,20 @@ void NameTagRenderer::drawHealthBars() if (!(health < 0.5f)) // `fcomp; test ah,5; jp` - NaN skips continue; - Vec4 translation = ntTransformations(m_type)[item.slot]; + Vec4 translation = ntTransformations(m_type)[item.m_slot]; const float invHalfHeight = 1.0f / (ntRenderer()->getRenderView()->getViewport()[3] * 0.5f); // +0x48, +0x14 const int fillStart = bar->second.fillStart; const int fillRange = bar->second.fillEnd - fillStart; translation.y = translation.y - invHalfHeight * 16.0f; float healthValue = (fillRange * health + fillStart) / bar->second.width; - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("HealthValue")) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("HealthValue")) ->setValue(&healthValue, 0); - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("HealthBarTrans")) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("HealthBarTrans")) ->setValue(&translation, 0); - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("CrossFadeValue")) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("CrossFadeValue")) ->setValue(&NametagManager::s_pulse, 0); - ntSetFadeOutB(s_effect, item.fadeDistance, m_fadeStart, m_fadeEnd); + ntSetFadeOutB(s_effect, item.m_viewDistance, m_fadeStart, m_fadeEnd); NametagVertex* const vertices = static_cast( dx9rend::vertexBufferLock(bar->second.full.vertexBuffer, 0, 0, 0)); @@ -664,9 +533,9 @@ void NameTagRenderer::drawHealthBars() { for (int i = 0; i < 6; ++i) { - vertices[i].slot = static_cast(item.slot); - vertices[i].colorIndex1 = static_cast(item.colorIndex1); - vertices[i].colorIndex2 = static_cast(item.colorIndex1); + vertices[i].slot = static_cast(item.m_slot); + vertices[i].colorIndex1 = static_cast(item.m_colorIndex); + vertices[i].colorIndex2 = static_cast(item.m_colorIndex); } } dx9rend::vertexBufferUnlock(bar->second.full.vertexBuffer); @@ -705,7 +574,7 @@ void NameTagRenderer::drawAmmoBars() return; const NtItemMap& items = ntItems(); - dx9rend::effectSetTechniqueByName(s_effect, vc71::string("nametag_healthbar")); + dx9rend::effectSetTechniqueByName(s_effect, std::string("nametag_healthbar")); if (s_bars.size() == 0) return; const BarMap::iterator bar = s_bars.find(kICAmmoBar); // unchecked @@ -715,26 +584,26 @@ void NameTagRenderer::drawAmmoBars() s_texLayer0->setValue(bar->second.full.texture, 0); s_texLayer1->setValue(bar->second.empty.texture, 0); float noCrossFade = 0.0f; // [ebp-3Ch] - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("CrossFadeValue")) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("CrossFadeValue")) ->setValue(&noCrossFade, 0); - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("ColorIndex1")) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("ColorIndex1")) ->setInt(0); - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("ColorIndex2")) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("ColorIndex2")) ->setInt(0); - for (NtItemMap::node* it = items.begin(); it != items.end(); it = NtItemMap::next(it)) + for (NtItemMap::const_iterator it = items.begin(); it != items.end(); ++it) { if (m_type != 0) continue; - NametagItem* const touchItem = it->value; - TouchItemDrawFields& item = ntItem(touchItem); - if (item.rendererType != 0) + NametagItem* const touchItem = it->second; + NametagItem& item = *touchItem; + if (item.m_type != 0) continue; - if (item.team != viewer->getTeam()) + if (item.m_team != viewer->getTeam()) continue; - if (item.arrowMode) + if (item.m_arrowMode) continue; - if (!item.inView) + if (!item.m_inView) continue; if (!ntFlag(item, 16)) // `test byte [esi+0BAh],1` continue; @@ -746,7 +615,8 @@ void NameTagRenderer::drawAmmoBars() world::IObject* const soldierObject = player->getDefaultVehicle(); if (!vehicle || !soldierObject) continue; - world::IPlayerControlObject* const control = ntOwningControlObject(vehicle); + world::IPlayerControlObject* const control = + static_cast(staticMeshControlObject(vehicle)); // sub_10103CB0 if (!control) continue; @@ -754,19 +624,19 @@ void NameTagRenderer::drawAmmoBars() if (!(ammo < 0.5f)) continue; - Vec4 translation = ntTransformations(m_type)[item.slot]; + Vec4 translation = ntTransformations(m_type)[item.m_slot]; const float invHalfHeight = 1.0f / (ntRenderer()->getRenderView()->getViewport()[3] * 0.5f); translation.y = translation.y - invHalfHeight * 10.0f; // flt_101E2B00 - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("HealthBarTrans")) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("HealthBarTrans")) ->setValue(&translation, 0); const int fillStart = bar->second.fillStart; float ammoValue = (ntClamp(ammo, 0.0f, 1.0f) * (bar->second.fillEnd - fillStart) + fillStart) / bar->second.width; - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("HealthValue")) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("HealthValue")) ->setValue(&ammoValue, 0); - ntSetFadeOutB(s_effect, item.fadeDistance, m_fadeStart, m_fadeEnd); + ntSetFadeOutB(s_effect, item.m_viewDistance, m_fadeStart, m_fadeEnd); NametagVertex* const vertices = static_cast( dx9rend::vertexBufferLock(bar->second.full.vertexBuffer, 0, 0, 0)); @@ -774,11 +644,11 @@ void NameTagRenderer::drawAmmoBars() { for (int i = 0; i < 6; ++i) { - vertices[i].slot = static_cast(item.slot); - vertices[i].colorIndex1 = static_cast(item.colorIndex1); - vertices[i].colorIndex2 = static_cast(item.colorIndex2 != -1 - ? item.colorIndex2 - : item.colorIndex1); + vertices[i].slot = static_cast(item.m_slot); + vertices[i].colorIndex1 = static_cast(item.m_colorIndex); + vertices[i].colorIndex2 = static_cast(item.m_flashColorIndex != -1 + ? item.m_flashColorIndex + : item.m_colorIndex); } } dx9rend::vertexBufferUnlock(bar->second.full.vertexBuffer); @@ -796,33 +666,32 @@ void NameTagRenderer::drawAmmoBars() void NameTagRenderer::drawIcons() { const NtItemMap& items = ntItems(); - if (items.size == 0) + if (items.size() == 0) return; - dx9rend::effectSetTechniqueByName(s_effect, vc71::string("nametag_vehicleIcons")); + dx9rend::effectSetTechniqueByName(s_effect, std::string("nametag_vehicleIcons")); dx9rend::effectBegin(s_effect); dx9rend::effectBeginPass(s_effect, 0); - for (NtItemMap::node* it = items.begin(); it != items.end(); it = NtItemMap::next(it)) + for (NtItemMap::const_iterator it = items.begin(); it != items.end(); ++it) { - NametagItem* const touchItem = it->value; - TouchItemDrawFields& item = ntItem(touchItem); - if (item.rendererType != m_type) + NametagItem& item = *it->second; + if (item.m_type != m_type) continue; if (!ntFlag(item, 4)) continue; if (!ntManager()->get3dMapOn() && !ntFlag(item, 17) - && !(ntFlag(item, 14) && item.arrowMode)) + && !(ntFlag(item, 14) && item.m_arrowMode)) continue; - if (!item.inView && !(ntFlag(item, 5) && ntFlag(item, 14))) + if (!item.m_inView && !(ntFlag(item, 5) && ntFlag(item, 14))) continue; if (!ntFlag(item, 16)) continue; - const IconMap::iterator icon = s_icons.find(item.iconKey); + const IconMap::iterator icon = s_icons.find(item.m_icon); IconMap::iterator flashIcon = icon; - if (item.flashIconKey != -1) - flashIcon = s_icons.find(item.flashIconKey); + if (item.m_callIcon != -1) + flashIcon = s_icons.find(item.m_callIcon); if (icon == s_icons.end()) continue; @@ -830,9 +699,9 @@ void NameTagRenderer::drawIcons() const NametagIcon* second = 0; // [ebp-0Ch] if (flashIcon != s_icons.end()) flash = &flashIcon->second; - if (item.elevationIconKey != -1) + if (item.m_elevationIcon != -1) { - const IconMap::iterator elevation = s_icons.find(item.elevationIconKey); + const IconMap::iterator elevation = s_icons.find(item.m_elevationIcon); if (elevation != s_icons.end()) { second = &elevation->second; @@ -842,14 +711,14 @@ void NameTagRenderer::drawIcons() s_texLayer0->setValue(icon->second.texture, 0); s_texLayer1->setValue(flash ? flash->texture : 0, 0); - Vec4 translation = ntTransformations(m_type)[item.slot]; // copied inline here + Vec4 translation = ntTransformations(m_type)[item.m_slot]; // copied inline here const float invHalfHeight = 1.0f / (ntRenderer()->getRenderView()->getViewport()[3] * 0.5f); const unsigned int iconWidth = dx9rend::textureDims(icon->second.texture)[0]; const unsigned int iconHeight = dx9rend::textureDims(icon->second.texture)[1]; - if (!item.arrowMode || ntFlag(item, 3)) + if (!item.m_arrowMode || ntFlag(item, 3)) translation.y = static_cast(iconHeight) * invHalfHeight + translation.y; - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("HealthBarTrans")) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("HealthBarTrans")) ->setValue(&translation, 0); const float iconInvWidth = 1.0f / static_cast(iconWidth); @@ -859,26 +728,26 @@ void NameTagRenderer::drawIcons() iconTexOffset[3] = 0.0f; iconTexOffset[0] = icon->second.left * iconInvWidth; iconTexOffset[1] = icon->second.top * iconInvHeight; - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("IconTexOffset")) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("IconTexOffset")) ->setValue(iconTexOffset, 0); - ntSetFadeOutA(s_effect, item.fadeDistance, m_fadeStart, m_fadeEnd); + ntSetFadeOutA(s_effect, item.m_viewDistance, m_fadeStart, m_fadeEnd); static Mat4 s_iconRotation; // ds:102670C0 (guard ds:10267100) D3DXMatrixRotationZ(reinterpret_cast(&s_iconRotation), - ntFlag(item, 9) ? item.iconRotation : 0.0f); + ntFlag(item, 9) ? item.m_iconRotation : 0.0f); float iconRotation[4]; iconRotation[0] = s_iconRotation.m[0]; // _11 iconRotation[1] = s_iconRotation.m[1]; // _12 iconRotation[2] = s_iconRotation.m[4]; // _21 iconRotation[3] = s_iconRotation.m[5]; // _22 - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("IconRotation")) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("IconRotation")) ->setValue(iconRotation, 0); - float crossFade = (1.0f - ntClamp(static_cast(item.distance) / + float crossFade = (1.0f - ntClamp(static_cast(item.m_distance) / NametagManager::s_maxCallDistance, 0.0f, 1.0f) * 0.5f) * NametagManager::s_pulse; - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("CrossFadeValue")) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("CrossFadeValue")) ->setValue(&crossFade, 0); if (flash) @@ -893,21 +762,21 @@ void NameTagRenderer::drawIcons() flashScaleOffset[2] = flash->left * flashInvWidth; flashScaleOffset[3] = flash->top * flashInvHeight; dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, - vc71::string("IconFlashTexScaleOffset")) + std::string("IconFlashTexScaleOffset")) ->setValue(flashScaleOffset, 0); } - const int colorIndex1 = ntFlag(item, 12) ? 0 : item.colorIndex1; - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("ColorIndex1")) + const int colorIndex1 = ntFlag(item, 12) ? 0 : item.m_colorIndex; + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("ColorIndex1")) ->setInt(colorIndex1); - if (ntFlag(item, 11) || item.colorIndex2 == -1) - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("ColorIndex2")) + if (ntFlag(item, 11) || item.m_flashColorIndex == -1) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("ColorIndex2")) ->setInt(colorIndex1); - else if (item.flashIconKey == -1) - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("ColorIndex2")) - ->setInt(item.colorIndex2); + else if (item.m_callIcon == -1) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("ColorIndex2")) + ->setInt(item.m_flashColorIndex); else - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("ColorIndex2")) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("ColorIndex2")) ->setInt(0); dx9rend::vertexBufferBindStream(icon->second.vertexBuffer, 0); @@ -925,6 +794,8 @@ void NameTagRenderer::drawIcons() // Keep the per-seat template tests, discarded icon lookup and repair x += height * 0.0f; // the latter preserves NaN behaviour. getDefaultVehicle() is not null-tested in retail. // [UNRESOLVED] the folded function-static guard has no observable storage. +// PE 0x101B33A0 (listing read: both parts' call order, branches, constants 0.5/16/32/0.33/0.0 and the +// unsigned-to-float width/height conversions match) void NameTagRenderer::drawArmorBarsAndVehicleIcons() { world::IPlayer* const viewer = ntViewingPlayer(); @@ -932,7 +803,7 @@ void NameTagRenderer::drawArmorBarsAndVehicleIcons() return; const NtItemMap& items = ntItems(); - dx9rend::effectSetTechniqueByName(s_effect, vc71::string("nametag_healthbar")); + dx9rend::effectSetTechniqueByName(s_effect, std::string("nametag_healthbar")); // part 1: armour bars if (s_bars.size() != 0 && viewer->getKit() == kKitEngineer) // PE +0x16C @@ -943,24 +814,24 @@ void NameTagRenderer::drawArmorBarsAndVehicleIcons() s_texLayer0->setValue(bar->second.full.texture, 0); s_texLayer1->setValue(bar->second.empty.texture, 0); float noCrossFade = 0.0f; // [ebp-18h] - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("CrossFadeValue")) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("CrossFadeValue")) ->setValue(&noCrossFade, 0); - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("ColorIndex1")) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("ColorIndex1")) ->setInt(0); - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("ColorIndex2")) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("ColorIndex2")) ->setInt(0); - for (NtItemMap::node* it = items.begin(); it != items.end(); it = NtItemMap::next(it)) + for (NtItemMap::const_iterator it = items.begin(); it != items.end(); ++it) { if (m_type != 0) continue; - NametagItem* const touchItem = it->value; - TouchItemDrawFields& item = ntItem(touchItem); - if (item.rendererType != 0) + NametagItem* const touchItem = it->second; + NametagItem& item = *touchItem; + if (item.m_type != 0) continue; - if (item.team != viewer->getTeam()) + if (item.m_team != viewer->getTeam()) continue; - if (!item.inView) + if (!item.m_inView) continue; if (!ntFlag(item, 16)) continue; @@ -979,18 +850,18 @@ void NameTagRenderer::drawArmorBarsAndVehicleIcons() if (!(armour < 0.5f)) continue; - Vec4 translation = ntTransformations(m_type)[item.slot]; + Vec4 translation = ntTransformations(m_type)[item.m_slot]; const float invHalfHeight = 1.0f / (ntRenderer()->getRenderView()->getViewport()[3] * 0.5f); const int fillStart = bar->second.fillStart; const int fillRange = bar->second.fillEnd - fillStart; translation.y = translation.y - invHalfHeight * 16.0f; float armourValue = (fillRange * armour + fillStart) / bar->second.width; - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("HealthValue")) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("HealthValue")) ->setValue(&armourValue, 0); - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("HealthBarTrans")) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("HealthBarTrans")) ->setValue(&translation, 0); - ntSetFadeOutA(s_effect, item.fadeDistance, m_fadeStart, m_fadeEnd); + ntSetFadeOutA(s_effect, item.m_viewDistance, m_fadeStart, m_fadeEnd); dx9rend::vertexBufferBindStream(bar->second.full.vertexBuffer, 0); dx9rend::rendererDrawPrimitive(2, D3DPT_TRIANGLELIST, 0); } @@ -1004,22 +875,22 @@ void NameTagRenderer::drawArmorBarsAndVehicleIcons() const IconMap::iterator medicIcon = s_icons.find(kICVehicleMedic); // [ebp-50h] const IconMap::iterator repairIcon = s_icons.find(kICVehicleRepair); // [ebp-64h] const IconMap::iterator ammoIcon = s_icons.find(kICVehicleAmmo); // [ebp-60h] - dx9rend::effectSetTechniqueByName(s_effect, vc71::string("nametag_vehicleIcons")); + dx9rend::effectSetTechniqueByName(s_effect, std::string("nametag_vehicleIcons")); dx9rend::effectBegin(s_effect); dx9rend::effectBeginPass(s_effect, 0); - for (NtItemMap::node* it = items.begin(); it != items.end(); it = NtItemMap::next(it)) + for (NtItemMap::const_iterator it = items.begin(); it != items.end(); ++it) { if (m_type != 0) continue; - NametagItem* const touchItem = it->value; - TouchItemDrawFields& item = ntItem(touchItem); - if (item.rendererType != 0) + NametagItem* const touchItem = it->second; + NametagItem& item = *touchItem; + if (item.m_type != 0) continue; - if (!item.inView) + if (!item.m_inView) continue; world::IPlayer* const teamViewer = ntViewingPlayer(); // inlined per item - if (teamViewer && item.team != teamViewer->getTeam()) + if (teamViewer && item.m_team != teamViewer->getTeam()) continue; world::IPlayer* const player = ntItemPlayer(touchItem); // inlined here in the image @@ -1062,8 +933,8 @@ void NameTagRenderer::drawArmorBarsAndVehicleIcons() bool repair = false; // [ebp-9] bool ammo = false; // [ebp-1] IconMap::iterator icon; - if (item.flashIconKey != -1) - icon = s_icons.find(item.flashIconKey); // dead - overwritten below + if (item.m_callIcon != -1) + icon = s_icons.find(item.m_callIcon); // dead - overwritten below switch (occupantSoldier->getKitType()) // ISoldier +0x58 { case kKitSupport: @@ -1088,7 +959,7 @@ void NameTagRenderer::drawArmorBarsAndVehicleIcons() s_texLayer0->setValue(icon->second.texture, 0); s_texLayer1->setValue(0, 0); - Vec4 translation = ntTransformations(m_type)[item.slot]; + Vec4 translation = ntTransformations(m_type)[item.m_slot]; const float invHalfHeight = 1.0f / (ntRenderer()->getRenderView()->getViewport()[3] * 0.5f); const unsigned int iconWidth = dx9rend::textureDims(icon->second.texture)[0]; @@ -1099,7 +970,7 @@ void NameTagRenderer::drawArmorBarsAndVehicleIcons() translation.x = invHalfHeight * 0.0f + translation.x; // adds zero else if (ammo) translation.x = invHalfHeight * 16.0f + translation.x; - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("HealthBarTrans")) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("HealthBarTrans")) ->setValue(&translation, 0); float iconRotation[4]; // see the guard note above @@ -1107,16 +978,16 @@ void NameTagRenderer::drawArmorBarsAndVehicleIcons() iconRotation[1] = 0.0f; iconRotation[2] = 0.0f; iconRotation[3] = 1.0f; - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("IconRotation")) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("IconRotation")) ->setValue(iconRotation, 0); float noCrossFade = 0.0f; // [ebp-5Ch] - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("CrossFadeValue")) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("CrossFadeValue")) ->setValue(&noCrossFade, 0); - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("ColorIndex1")) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("ColorIndex1")) ->setInt(0); - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("ColorIndex2")) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("ColorIndex2")) ->setInt(0); - ntSetFadeOutA(s_effect, item.fadeDistance, m_fadeStart, m_fadeEnd); + ntSetFadeOutA(s_effect, item.m_viewDistance, m_fadeStart, m_fadeEnd); const unsigned int iconHeight = dx9rend::textureDims(icon->second.texture)[1]; float iconTexOffset[4]; @@ -1124,7 +995,7 @@ void NameTagRenderer::drawArmorBarsAndVehicleIcons() iconTexOffset[3] = 0.0f; iconTexOffset[0] = 1.0f / static_cast(iconWidth) * icon->second.left; iconTexOffset[1] = 1.0f / static_cast(iconHeight) * icon->second.top; - dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, vc71::string("IconTexOffset")) + dx9rend::effectGetShaderParameterBorrowedTyped(s_effect, std::string("IconTexOffset")) ->setValue(iconTexOffset, 0); dx9rend::vertexBufferBindStream(icon->second.vertexBuffer, 0); diff --git a/Code/BF2/Geom/NametagManager.cpp b/Code/BF2/Geom/NametagManager.cpp index 6a619088c..6dda7342f 100644 --- a/Code/BF2/Geom/NametagManager.cpp +++ b/Code/BF2/Geom/NametagManager.cpp @@ -1,13 +1,17 @@ // Floating-tag lifecycle, event handling and item updates. -// Profiling brackets are omitted. Reissued orders retain the original unchanged-item result. -// OrderNametagItem::setOrder keeps a named stop for the null-target arm; -// callers must supply a target. +// Profiling brackets are omitted except NametagManager::draw's. Reissued orders retain the original unchanged-item result. +// OrderNametagItem::setOrder retains the shipped null-target fault. #ifdef BF2_IMAGE_RENDDX9 +#if defined(__APPLE__) +#include "../Platform/X87Compat.h" // [CHOSEN, not recovered] x87 conversion results, including invalid inputs. +#endif #include "NametagManager.h" +#include "../RendDX9/QueueProfiler.h" #include "NameTagRenderer.h" // nt_renderer - the per-TagType batch renderer #include "StaticMesh.h" // staticMeshRootParent - sub_10103CE0 +#include "LcgRandom.h" // lcgrandStep - sub_1009EF30 #include "../../RendDX9Abi/BfMemory.h" #include "../../RendDX9Abi/Frontier.h" @@ -19,9 +23,6 @@ // The engine interfaces below are imported the way XpLightManager.cpp / BundledMeshDraw.cpp do it: // only their virtual interfaces cross the plugin boundary; in the retail-compatible flavour HfeAbi // already supplies ClassManager's VC7.1 carriers, so Core/ClassManager.h is kept out. -#if !BF2_PLUGIN_ABI_NATIVE -#define CORE_CLASSMANAGER_H -#endif #include "../Game/IGame.h" #include "../Game/Objects/ObjectLayoutAccess.h" #include "../Game/Objects/IPlayer.h" @@ -41,7 +42,6 @@ #include "../Game/Objects/GameLogicComp/IArmorGLComp.h" #include "../Scene/Object/ObjectManager.h" #include "../Scene/Object/ObjectTypes/Game/IPlayerControlObject.h" -#if BF2_PLUGIN_ABI_NATIVE // Native flavour only: the host is built from these very headers, so the compiler's own layout of // these classes IS the host's layout. The retail-compatible flavour reads the retail offsets // instead (see the host seams below) and must not see these classes' native-STL layouts. @@ -56,12 +56,9 @@ #include "../Game/Objects/StrategicObjectComp.h" // addTouchItem: m_holder (a friend line) #include "../Menu/BF2HudManager.h" // getPlayerKit (+0x90) / enableVOHelpMessage (+0xF8) #include "../Menu/ISwiffHost.h" // getLocalizedString (+0xA8) -#endif -#if !BF2_PLUGIN_ABI_NATIVE -#undef CORE_CLASSMANAGER_H -#endif #include "../Math/Mat4.h" // nt_update +#include "../RendDX9/RendDX9Math.h" // the RendDX9.dll Math copies #include "../RendMisc/IRenderer.h" // nt_update: Renderer +0xB0 #include "../RendMisc/IRenderView.h" // nt_update: +0x14/+0x64/+0x68/+0x6C/+0x74 @@ -189,15 +186,6 @@ inline world::IStrategicObjectComp* strategicComponent(world::IObject* object) world::object_detail::LayoutAccess::strategicObjectComponent(object)); } -#if !BF2_PLUGIN_ABI_NATIVE -inline void* strategicHolder(world::IStrategicObjectComp* component) -{ - // StrategicObjectComp::m_holder, +0x14 in both images (vptr + four scalars precede it - see - // StrategicObjectComp.h); private there, so read at its fixed offset. 0x10130CA1. The native - // flavour reads it typed in addTouchItem, through StrategicObjectComp's friend line (RW-266). - return *reinterpret_cast(reinterpret_cast(component) + 0x14); -} -#endif inline void* rootParent(void* object) { @@ -214,22 +202,9 @@ inline float geometryBoundingRadius(void* geometry) } // host strings -#if BF2_PLUGIN_ABI_NATIVE typedef std::wstring HostWString; inline const std::string& hostStdString(const renddx9abi::HostString& value) { return value; } inline const renddx9abi::HostString& fromHostStdString(const std::string& value) { return value; } -#else -typedef vc71::wstring HostWString; -// The host receives these by reference, so only the static spelling changes (XpLightManager.cpp). -inline const std::string& hostStdString(const renddx9abi::HostString& value) -{ - return *reinterpret_cast(&value); -} -inline const renddx9abi::HostString& fromHostStdString(const std::string& value) -{ - return *reinterpret_cast(&value); -} -#endif // std::operator==(const std::string&, const char*) (MSVCP71 import, 0x10130ECD) - compare() == 0. inline bool hostStringEquals(const renddx9abi::HostString& value, const char* text) @@ -246,15 +221,9 @@ inline bool hostStringEquals(const renddx9abi::HostString& value, const char* te inline bool swiffHostGetLocalizedString(IBase* swiffHost, HostWString& out, const renddx9abi::HostString& key) { -#if BF2_PLUGIN_ABI_NATIVE // RW-266: in this flavour the flavour's string types ARE the host's std types, so the typed // interface applies - ISwiffHost slot 42 is +0xA8 (/d1reportSingleClassLayout). return static_cast(swiffHost)->getLocalizedString(out, key); -#else - typedef bool (__thiscall* LocalizeFn)(void*, HostWString&, const renddx9abi::HostString&); - return reinterpret_cast((*reinterpret_cast(swiffHost))[0xA8 / 4])( - swiffHost, out, key); -#endif } // Converts wide text using the current locale. The first size-error test intentionally @@ -280,7 +249,7 @@ renddx9abi::HostString narrowString(const HostWString& wide) // internal linkage). 0xFFF limit; an overflow is replaced by the fixed warning. char g_nametagFormatBuffer[0x1000]; -vc71::string nametagFormatString(const char* format, ...) +std::string nametagFormatString(const char* format, ...) { va_list args; va_start(args, format); @@ -292,32 +261,10 @@ vc71::string nametagFormatString(const char* format, ...) else ::sprintf(g_nametagFormatBuffer, "%s", "WARNING: The original message was too long for formatString(). \n"); - return vc71::string(g_nametagFormatBuffer); -} - -// lcgrand_step (0x1009EF30) - RendDX9's copy of dice::hfe::Random::getRaw (ELF 0x8166CE0): two -// Schrage steps, 24112 then 26143. The particle code carries the same arithmetic -// (ParticleInstanceType0Emission.inl's psmEmissionRandomStep); Core/Random.cpp is not in the -// RendDX9 manifest, so it is reproduced here rather than linked. -unsigned int randomStep(unsigned int value, unsigned int multiplier) -{ - const unsigned int low = (value & 0xFFFFu) * multiplier; - const unsigned int high = static_cast(static_cast(value) >> 16) * multiplier; - const int middle = static_cast((low >> 16) + high); - const unsigned int next = (low & 0xFFFFu) + ((static_cast(middle) & 0x7FFFu) << 16) - + static_cast(middle >> 15); - const int reduced = static_cast(next - 0x7FFFFFFFu); - return reduced < 0 ? next : static_cast(reduced); -} - -unsigned int randomRaw(Random& random) -{ - random.m_seed = randomStep(randomStep(random.m_seed, 24112u), 26143u); - return random.m_seed; + return std::string(g_nametagFormatBuffer); } // Native and plugin host layouts. -#if BF2_PLUGIN_ABI_NATIVE // Protected fields reached the way C++ allows from outside: a pointer-to-member formed inside a // derived class. Nothing is instantiated. @@ -381,57 +328,6 @@ inline bool vehicleHudUsesPlayerIcon(world::IObjectComponent* hudComponent) return static_cast(hudComponent)->getHudInfo()->usePlayerIcon; } -#else // the retail-compatible flavour: the retail host's own offsets - -template -inline T& retailField(void* object, unsigned int offset) -{ - return *reinterpret_cast(static_cast(object) + offset); -} - -// ControlPoint is `Bundle, IControlPoint` with the IControlPoint subobject at PE +0x154 (ELF +0x13C -// - one VC7.1 std::string larger, 28 - 4 bytes); m_flagPoleHeight is ELF +0x174 / PE +0x18C. - -inline world::IObject* controlPointObject(world::ControlPoint* cp) -{ - return reinterpret_cast(cp); // the primary base, +0 -} -inline int controlPointTeam(world::ControlPoint* cp) -{ - return reinterpret_cast( - reinterpret_cast(cp) + 0x154)->getTeam(); // +0x154 subobject, +0x1C -} -inline float controlPointFlagPoleHeight(world::ControlPoint* cp) -{ - return retailField(cp, 0x18C); -} -// SupplyObjectTemplate visibleOn3dMap / 3dMapIcon: ELF +0x1A4 / +0x1A8, PE +0x254 / +0x258. -inline bool supplyVisibleOn3dMap(void* t) { return retailField(t, 0x254) != 0; } -inline int supplyMapIcon(void* t) { return retailField(t, 0x258); } -// GenericProjectileTemplate visibleOn3dMap / 3dMapIcon: ELF +0x1FA / +0x1FC, PE +0x2DA / +0x2DC. -inline bool projectileVisibleOn3dMap(void* t) { return retailField(t, 0x2DA) != 0; } -inline int projectileMapIcon(void* t) { return retailField(t, 0x2DC); } -// IProjectileObject subobject slots, PE = ELF - 4 (one destructor slot): +0x60 = ELF +0x64 -// getTeam (thunk 0x8287740 -> 0x8287730), +0xC4 = ELF +0xC8 getTargetObject (0x8287230 -> -// 0x8284880) - read from GenericProjectile's -316 subtable (ELF 0x88BC650). -inline int projectileTeam(world::IObject*, void* projectile) -{ - typedef int (__thiscall* TeamFn)(void*); - return reinterpret_cast((*reinterpret_cast(projectile))[0x60 / 4])(projectile); -} -inline world::IObject* projectileTarget(world::IObject*, void* projectile) -{ - typedef world::IObject* (__thiscall* TargetFn)(void*); - return reinterpret_cast((*reinterpret_cast(projectile))[0xC4 / 4])(projectile); -} -// VehicleHudInfo::usePlayerIcon - PE +0x94 (an int and five 28-byte strings precede the flags). -inline bool vehicleHudUsesPlayerIcon(world::IObjectComponent* hudComponent) -{ - return retailField( - static_cast(hudComponent)->getHudInfo(), 0x94) != 0; -} - -#endif // BF2_PLUGIN_ABI_NATIVE // [CHOSEN, not recovered] Preserve the reissue defect's unchanged item state without @@ -446,8 +342,7 @@ inline void reissueOrderDefect() double nametagFrameDelta() { // g_Renderer +0x5E8 - the delta Renderer::update stores (BF2Render.cpp: self + 1512). - return *reinterpret_cast( - static_cast(static_cast(dx9rend::g_Renderer)) + 0x5E8); + return dx9rend::rendererTailDouble(0x5E8); } @@ -492,6 +387,7 @@ NametagItem::NametagItem(int type, int slot) } // (body) / 0x1012C2D0 (scalar deleting): the two strings, +0x2C then +0x10. +// PE 0x1012C2B0 NametagItem::~NametagItem() { } @@ -520,14 +416,13 @@ int PlayerNametagItem::getKey() // Updates and returns the soldier/vehicle-relative tag position; no player returns zero. -// Repeated vehicle reads may observe different vehicles. The x component's original -// x87 extended intermediate can differ by one ULP from SSE2. - +// Repeated vehicle reads may observe different vehicles. +// PE 0x1012D880. const Vec3& PlayerNametagItem::updatePosition() { world::IPlayer* const player = m_player.get(); if (!player) - return Vec3::getZero(); + return rendmath::zeroVector(); // PE 0x1007B1E0 Vec3 offset; offset.x = 0.0f; @@ -573,8 +468,16 @@ const Vec3& PlayerNametagItem::updatePosition() } offset.x = 0.0f; offset.z = 0.0f; +#if defined(__APPLE__) + // [CHOSEN, not recovered] Preserve the x87 intermediate across the multiply/add. + offset.y = bf2x87::store(bf2x87::add( + bf2x87::mul(bf2x87::wide(radius), + bf2x87::wide(NametagManager::s_vehicleNametagOffsetFactor)), + bf2x87::wide(NametagManager::s_vehicleNametagOffset))); +#else offset.y = radius * NametagManager::s_vehicleNametagOffsetFactor + NametagManager::s_vehicleNametagOffset; +#endif } } @@ -582,11 +485,17 @@ const Vec3& PlayerNametagItem::updatePosition() if (player->getVehicle()) base = &player->getVehicle()->getAbsolutePosition(); // PE +0x68 else - base = &Vec3::getZero(); + base = &rendmath::zeroVector(); // PE 0x1007B1E0 const float partialY = offset.y + m_offset.y; const float partialZ = offset.z + m_offset.z; +#if defined(__APPLE__) + // [CHOSEN, not recovered] X stays in x87 until its final store; Y/Z spill above. + m_position.x = bf2x87::store(bf2x87::add( + bf2x87::add(bf2x87::wide(offset.x), bf2x87::wide(m_offset.x)), bf2x87::wide(base->x))); +#else m_position.x = (offset.x + m_offset.x) + base->x; +#endif m_position.y = partialY + base->y; m_position.z = partialZ + base->z; return m_position; @@ -687,6 +596,7 @@ int OrderNametagItem::getKey() } +// PE 0x1012DDE0. const Vec3& OrderNametagItem::updatePosition() { if (m_flags & NIF_FollowTarget) @@ -711,7 +621,7 @@ void OrderNametagItem::setOrder(const SquadOrder* order, const Vec3& position) m_targetPosition = position; } -// 0x1012DCE0, 252 B, retn 8. +// PE 0x1012DCE0, retn 8. void OrderNametagItem::setOrder(const SquadOrder* order, world::IObject* target) { m_order = *order; @@ -720,12 +630,16 @@ void OrderNametagItem::setOrder(const SquadOrder* order, world::IObject* target) m_target = target->getWeakPtr(); return; } - // the null-target arm retains the null temporary with `xor eax,eax; add [eax],1` - // - a guaranteed write to address 0. Unreachable from every shipped caller (addTouchItem tests - // the target first). Kept as a stop rather than written as UB or "fixed" into a clear. - RD9_FRONTIER_AT("dice::hfe::geom::OrderNametagItem::setOrder (0x1012DDB2 - the shipped null-" - "target arm writes to address 0)", this, 0); - std::abort(); + typedef WeakPtr::Ctrl TargetControl; +#if defined(_MSC_VER) && defined(_M_IX86) + TargetControl* incoming = 0; +#else + // [CHOSEN, not recovered] Keep the null address opaque to the native optimizer so the + // shipped memory access survives instead of making the entire arm unreachable. + TargetControl* volatile incoming = 0; +#endif + ++incoming->refCount; // shipped defect: retains a null control block before clearing the target. + m_target = WeakPtr(); } // 0x101C8080, 83 B, retn 4. @@ -744,46 +658,34 @@ bool NametagRayPredicator::predicate(world::IObject* object) return (flags & m_flags) == m_flags; } +namespace { -// NametagTableVector - -NametagTableVector::~NametagTableVector() -{ - if (first) - ::renddx9abi::engineFree(first); - first = 0; - last = 0; - end = 0; -} - -// sub_10132390(n, value) - vector::resize. The only use is resize(3, 0) on an empty vector, where -// VC7.1's _Insert_n allocates exactly n elements (capacity 0 + 0/2 < n, so n). -void NametagTableVector::resize(unsigned int count, float* value) -{ - const unsigned int size = first ? static_cast((last - first) / sizeof(float*)) : 0u; - if (size >= count) +// The ray predicate narrowed to control-object roots (predicate, PE 0x101C80E0): the inherited test +// (NametagRayPredicator::predicate, PE 0x101C8080, called on the same `this`), then the object must +// answer IID_IPlayerControlObject (queryInterface slot +0x0C, id ds:10208CF0) and be its own root. +// Unreachable in 1.50: no code or data references. [CHOSEN, not recovered] class name and +// placement: retail has no constructor, vtable or caller for it, so neither is observable; the +// member reads exactly the base's fields. +class NametagRayControlRootPredicator : public NametagRayPredicator +{ +public: + NametagRayControlRootPredicator(world::IObject* ignoredRoot, unsigned int flags, + bool ignoreSoldiers) + : NametagRayPredicator(ignoredRoot, flags, ignoreSoldiers) {} + + // PE 0x101C80E0 (retn 4). + virtual bool predicate(world::IObject* object) { - last = first + count * sizeof(float*); - return; - } - const unsigned int capacity = - first ? static_cast((end - first) / sizeof(float*)) : 0u; - if (capacity < count) - { - char* const block = static_cast(::renddx9abi::engineAlloc(count * sizeof(float*))); - if (first) - { - ::memcpy(block, first, size * sizeof(float*)); - ::renddx9abi::engineFree(first); - } - first = block; - last = block + size * sizeof(float*); - end = block + count * sizeof(float*); + if (!NametagRayPredicator::predicate(object)) + return false; + if (object->queryInterface(world::IID_IPlayerControlObject) && rootParent(object) == object) + return true; + return false; } - for (unsigned int i = size; i < count; ++i) - reinterpret_cast(first)[i] = value; - last = first + count * sizeof(float*); -} +}; + +} // anonymous namespace + // NametagManager - construction and destruction @@ -817,7 +719,7 @@ NametagManager::NametagManager() eventManager->registerEventHandler(ECGame, static_cast(this), 0); m_transformations.resize(3, 0); // sub_10132390(3, 0) - m_colors.resize(3, 0); + m_colors.resize(3, 0); // (vector::resize) // operator new(0xA924): a count prefix of 3 and three NameTagRenderer ctors (0x101B2F00). A // failed allocation leaves a NULL array and the next line dereferences it - shipped; the @@ -894,7 +796,7 @@ int NametagManager::getRef() return m_refCount; } -// The remaining count is cached before the destructor, as shipped. +// The remaining count is cached before the destructor, as shipped. PE 0x10132880 int NametagManager::release() { const int remaining = --m_refCount; @@ -907,6 +809,7 @@ int NametagManager::release() } // iid 1 (dword_102088DC) or 0xB801DCFE (dword_1021AE7C) answer the raw `this`. +// PE 0x101325C0 void* NametagManager::queryInterface(unsigned int iid) const { if (iid == 1u) @@ -932,7 +835,7 @@ bool NametagManager::registerControlPointIcons(const renddx9abi::HostString& tea { const unsigned int iconsBefore = NameTagRenderer::iconCount(); // dword_102670AC - vc71::string path("Menu/Nametag/Neutral/miniMap_CP"); + std::string path("Menu/Nametag/Neutral/miniMap_CP"); NameTagRenderer::removeTexture(kIconControlPoint + 0, 0); // (42, 0) NameTagRenderer::setTexture(kIconControlPoint + 0, 0, path, 0, 0, 16, 16); @@ -956,20 +859,23 @@ bool NametagManager::registerControlPointIcons(const renddx9abi::HostString& tea } +// PE 0x10131260: the "Nametags" profiler is registered on first use (guard bit 0 at PE 0x1025D110, +// object at PE 0x1025CEA8) and destroyed at exit. void NametagManager::draw() { - // the profiler bracket ("Nametags") - not reproduced, see - // the file header. + static dx9rend::QueueProfiler profiler(std::string("Nametags")); + profiler.begin(); update(); // slot +0x14 - a virtual call for (int type = TTObject; type >= TTPlayer; --type) // 0x70C0, 0x3860, 0 - renderers 2, 1, 0 m_renderers[type].draw(); + dx9rend::QueueProfiler::end(); } -// Adds a player nametag. +// Adds a player nametag. PE 0x101309D0 bool NametagManager::addTouchItem(world::IPlayer* player) { NametagItem* item; - NametagItemMap::node* const found = m_items.find(player->getId() + kNametagKeyPlayer); // inline key + const NametagItemMap::iterator found = m_items.find(player->getId() + kNametagKeyPlayer); // inline key if (found == m_items.end()) { item = createPlayerItem(player); @@ -978,7 +884,7 @@ bool NametagManager::addTouchItem(world::IPlayer* player) } else { - item = found->value; + item = found->second; item->m_dirty = true; } @@ -998,7 +904,7 @@ bool NametagManager::addTouchItem(world::ControlPoint* controlPoint) { world::IObject* const object = controlPointObject(controlPoint); NametagItem* item; - NametagItemMap::node* const found = m_items.find(static_cast(objectId(object)) + kNametagKeyObject); + const NametagItemMap::iterator found = m_items.find(static_cast(objectId(object)) + kNametagKeyObject); if (found == m_items.end()) { item = createObjectItem(object); @@ -1007,7 +913,7 @@ bool NametagManager::addTouchItem(world::ControlPoint* controlPoint) } else { - item = found->value; + item = found->second; item->m_dirty = true; } @@ -1030,16 +936,15 @@ bool NametagManager::addTouchItem(world::ControlPoint* controlPoint) } -// 0x10130B90, 951 B, retn 4 - a soldier, a strategic object, a supply object, a projectile, a +// PE 0x10130B90: 951 B, retn 4 - a soldier, a strategic object, a supply object, a projectile, a // vehicle drop, or anything else. Every exit, store and repeated call is the shipped one. - bool NametagManager::addTouchItem(world::IObject* object) { NametagItem* item; - NametagItemMap::node* const found = m_items.find(static_cast(objectId(object)) + kNametagKeyObject); + const NametagItemMap::iterator found = m_items.find(static_cast(objectId(object)) + kNametagKeyObject); if (found != m_items.end()) { - item = found->value; + item = found->second; item->m_dirty = true; } else @@ -1076,11 +981,7 @@ bool NametagManager::addTouchItem(world::IObject* object) item->m_offset.y = object->getVisualBoundingRadius(); // PE +0x90 item->m_offset.x = 0.0f; item->m_offset.z = 0.0f; -#if BF2_PLUGIN_ABI_NATIVE if (static_cast(component)->m_holder) // +0x14 (RW-266) -#else - if (strategicHolder(component)) -#endif item->m_flags |= NIF_UseHolderPosition; // byte +0xB9 |= 1 item->m_flags &= ~NIF_Visible; item->m_colorIndex = 4; @@ -1194,11 +1095,11 @@ bool NametagManager::addTouchItem(world::IObject* object) // 0x101310A0, 204 B, retn 0Ch. bool NametagManager::addTouchItem(SquadOrder* order, int orderType, const Vec3& position) { - NametagItemMap::node* const found = m_items.find(orderType + kNametagKeyOrder); + const NametagItemMap::iterator found = m_items.find(orderType + kNametagKeyOrder); NametagItem* item = 0; if (found != m_items.end()) { - item = found->value; + item = found->second; item->m_dirty = true; } if (!item) @@ -1225,11 +1126,11 @@ bool NametagManager::addTouchItem(SquadOrder* order, int orderType, world::IObje if (!target) return false; - NametagItemMap::node* const found = m_items.find(orderType + kNametagKeyOrder); + const NametagItemMap::iterator found = m_items.find(orderType + kNametagKeyOrder); NametagItem* item = 0; if (found != m_items.end()) { - item = found->value; + item = found->second; item->m_dirty = true; } if (!item) @@ -1251,10 +1152,9 @@ bool NametagManager::addTouchItem(SquadOrder* order, int orderType, world::IObje } -// 0x10130F50, 327 B, retn 8 - the UAV: rename it to the localised "KILLMESSAGE_VEHICLE_uav" text, +// PE 0x10130F50: 327 B, retn 8 - the UAV: rename it to the localised "KILLMESSAGE_VEHICLE_uav" text, // then tag it with the owning team's relation colour. // The "SwiffHost" singleton is not null-tested; the localisation result is discarded. - bool NametagManager::addTouchItem(world::IObject* object, int team) { IBase* const swiffHost = classManager->getSingleton(renddx9abi::HostString("SwiffHost")); @@ -1265,7 +1165,7 @@ bool NametagManager::addTouchItem(world::IObject* object, int team) object->setName(hostStdString(name)); // IObject PE +0x64 NametagItem* item; - NametagItemMap::node* const found = m_items.find(static_cast(objectId(object)) + kNametagKeyObject); + const NametagItemMap::iterator found = m_items.find(static_cast(objectId(object)) + kNametagKeyObject); if (found == m_items.end()) { item = createObjectItem(object); @@ -1274,7 +1174,7 @@ bool NametagManager::addTouchItem(world::IObject* object, int team) } else { - item = found->value; + item = found->second; item->m_dirty = true; } @@ -1292,16 +1192,20 @@ bool NametagManager::addTouchItem(world::IObject* object, int team) // the per-type tables +// Unchecked indexing, as shipped (operator[], not the throwing at()). +// PE 0x10132730 float* NametagManager::getColors(int type) { - return m_colors.at(type); + return m_colors[type]; } +// PE 0x1012EFB0 float* NametagManager::getTransformations(int type) { - return m_transformations.at(type); + return m_transformations[type]; } +// PE 0x1012C820 float* NametagManager::getAlphaArray(int type) // this + 0x38 + type * 0x100 { return m_alphaArrays[type]; @@ -1314,16 +1218,16 @@ float* NametagManager::getAlphaArray(int type) // this + 0x38 + type * 0x // 0x1012ED40, 117 B: every item re-buffered into its renderer (0x101B2320, full = true). void NametagManager::rebufferAll() { - for (NametagItemMap::node* it = m_items.begin(); it != m_items.end(); it = NametagItemMap::next(it)) - m_renderers[it->value->m_type].bufferItem(it->value, true); + for (NametagItemMap::iterator it = m_items.begin(); it != m_items.end(); ++it) + m_renderers[it->second->m_type].bufferItem(it->second, true); } // 0x1012EDC0, 106 B - the renderer's ECCore CEPostLoad arm calls it: mark every item dirty and // let update() run. void NametagManager::enableBuffering() { - for (NametagItemMap::node* it = m_items.begin(); it != m_items.end(); it = NametagItemMap::next(it)) - it->value->m_dirty = true; + for (NametagItemMap::iterator it = m_items.begin(); it != m_items.end(); ++it) + it->second->m_dirty = true; m_bufferingEnabled = true; } @@ -1334,7 +1238,7 @@ void NametagManager::clearAll() for (int type = TTPlayer; type <= TTObject; ++type) { for (int slot = 0; slot < maxSlotCount(type); ++slot) - m_freeSlots[type].insert(static_cast(slot)); + m_freeSlots[type].insert(slot); m_slotMaps[type].clear(); } } @@ -1344,9 +1248,9 @@ void NametagManager::clearAll() // The item's type and slot are read before the item is null-tested. void NametagManager::removeAllItems() { - for (NametagItemMap::node* it = m_items.begin(); it != m_items.end(); it = m_items.begin()) + for (NametagItemMap::iterator it = m_items.begin(); it != m_items.end(); it = m_items.begin()) { - NametagItem* const item = it->value; + NametagItem* const item = it->second; float* const transformation = getTransformations(item->m_type) + item->m_slot * 4; // virtual transformation[0] = 0.0f; transformation[1] = 0.0f; @@ -1401,9 +1305,10 @@ void NametagManager::removeItem(int type, void* item) } // Frees the key's slot and removes its item. The type argument selects the transformation table. +// PE 0x1012FB70. void NametagManager::removeKey(int type, int key) { - NametagItemMap::node* const found = m_items.find(key); + const NametagItemMap::iterator found = m_items.find(key); if (found == m_items.end()) return; @@ -1411,11 +1316,12 @@ void NametagManager::removeKey(int type, int key) if (slots.count(key) != 0) // equal_range + _Distance { slots.erase(key); - m_freeSlots[type].insert(static_cast(found->value->m_slot)); + m_freeSlots[type].insert(found->second->m_slot); } NametagItem*& entry = m_items[key]; - float* const transformation = getTransformations(type) + entry->m_slot * 4; // virtual +0x38 + float* const transformations = getTransformations(type); // virtual +0x38 + float* const transformation = transformations + entry->m_slot * 4; transformation[0] = 0.0f; transformation[1] = 0.0f; transformation[2] = -1.0f; @@ -1439,6 +1345,7 @@ bool NametagManager::get3dMapOn() const return m_3dMapOn; } +// PE 0x10132610 void NametagManager::set3dMapOn(bool on) { m_3dMapOn = on; @@ -1484,10 +1391,10 @@ void NametagManager::handleEvent(EventCategory category, unsigned int id, EventN return; } // The spawned player is dereferenced with no null test; the key is built inline. - NametagItemMap::node* const found = m_items.find(spawned->getId() + kNametagKeyPlayer); + const NametagItemMap::iterator found = m_items.find(spawned->getId() + kNametagKeyPlayer); if (found == m_items.end()) return; - resetItem(found->value); + resetItem(found->second); return; } // any other ECGame id jumps into the ECHud id tests below. Shipped. @@ -1515,10 +1422,10 @@ void NametagManager::handleEvent(EventCategory category, unsigned int id, EventN world::IPlayer* const caller = soldier->getOccupingPlayer(); // +0x34 if (!caller) return; - NametagItemMap::node* const found = m_items.find(playerKey(caller)); + const NametagItemMap::iterator found = m_items.find(playerKey(caller)); if (found == m_items.end()) return; - NametagItem* const item = found->value; + NametagItem* const item = found->second; world::IPlayer* const local = localHumanPlayer(); if (!local) return; @@ -1606,10 +1513,10 @@ void NametagManager::handleEvent(EventCategory category, unsigned int id, EventN world::IPlayer* const player = soldier->getOccupingPlayer(); if (!player) return; - NametagItemMap::node* const found = m_items.find(player->getId() + kNametagKeyPlayer); + const NametagItemMap::iterator found = m_items.find(player->getId() + kNametagKeyPlayer); if (found == m_items.end()) return; - NametagItem* const item = found->value; + NametagItem* const item = found->second; if (item->m_timer <= 0.0f) item->m_timer = s_callIconTime; item->m_flashColorIndex = (item->m_colorIndex != 4) ? 4 : 0; @@ -1623,8 +1530,8 @@ void NametagManager::resetAllCalls() s_repairCallTimer = 0.0; // dbl_1025C228 first, as shipped s_medicCallTimer = 0.0; s_ammoCallTimer = 0.0; - for (NametagItemMap::node* it = m_items.begin(); it != m_items.end(); it = NametagItemMap::next(it)) - resetItem(it->value); // 0x1012CA10, inlined in the shipped loop + for (NametagItemMap::iterator it = m_items.begin(); it != m_items.end(); ++it) + resetItem(it->second); // 0x1012CA10, inlined in the shipped loop } // 0x1012CA10, 74 B, retn 4. @@ -1727,10 +1634,9 @@ float NametagManager::hierarchyVisualRadius(world::IObject* object, bool childre } -// 0x1012DEC0, 1,060 B, retn 4. A player tag's icon (call-for-help / squad leader / commander / +// PE 0x1012DEC0: 1,060 B, retn 4. A player tag's icon (call-for-help / squad leader / commander / // soldier / vehicle kind), its relation colour and whether it is drawn. Returns whether the // colour changed. - bool NametagManager::refreshPlayerItem(PlayerNametagItem* item) { world::IPlayer* const player = item->m_player.get(); @@ -1938,7 +1844,7 @@ bool NametagManager::refreshPlayerItem(PlayerNametagItem* item) return changed; } -// no caller in the image; the constructor and clearAll inline the same switch. +// PE 0x1012C840: no caller in the image; the constructor and clearAll inline the same switch. int NametagManager::maxSlotCount(int type) { switch (type) @@ -1950,7 +1856,7 @@ int NametagManager::maxSlotCount(int type) } } -// unreferenced in the image. Counts the item's timer down by the frame delta and +// PE 0x1012CB00: unreferenced in the image. Counts the item's timer down by the frame delta and // resets its call state at zero. The comparison is on the unrounded difference (fst keeps st0). void NametagManager::tickItemTimer(NametagItem* item) { @@ -1963,7 +1869,33 @@ void NametagManager::tickItemTimer(NametagItem* item) } } -// unreferenced dispatchers (the update inlines the same type test). +// PE 0x1012C5B0: unreachable in 1.50: no code or data references. The map key of a tag by type: +// a player's id (IPlayer slot +0x50), the order type, or an object's id (IObject +0x10) plus the +// per-type base; any other type answers 0. Takes no `this` (ecx unread), retn 0xC. [INFERRED] name. +int NametagManager::genericKey(int type, void* item, int orderType) +{ + switch (type) + { + case TTPlayer: return static_cast(item)->getId() + kNametagKeyPlayer; + case TTOrder: return orderType + kNametagKeyOrder; + case TTObject: return static_cast(objectId(static_cast(item))) + kNametagKeyObject; + default: return 0; + } +} + +// PE 0x1012F3E0: unreachable in 1.50: no code or data references. Finds the item filed under +// `key` and marks it for re-buffering; answers the item, or null when the key is not in the map. +// [INFERRED] name. +NametagItem* NametagManager::markItemDirty(int key) +{ + const NametagItemMap::iterator found = m_items.find(key); + if (found == m_items.end()) + return 0; + found->second->m_dirty = true; + return found->second; +} + +// PE 0x1012E8D0: unreferenced dispatcher (the update inlines the same type test). void NametagManager::updateItemPosition(NametagItem* item) { if (item->m_type == TTPlayer) @@ -1972,6 +1904,7 @@ void NametagManager::updateItemPosition(NametagItem* item) updateObjectItem(item); } +// PE 0x1012EF90: unreferenced dispatcher, as updateItemPosition. void NametagManager::updateItemFade(NametagItem* item) { if (item->m_type == TTPlayer) @@ -1994,11 +1927,11 @@ int NametagManager::allocateSlot(int type, int key) if (slots.count(key) != 0) // sub_101319E0 + _Distance return slots[key]; - if (freeSlots.size == 0) + if (freeSlots.size() == 0) return -1; - const int slot = static_cast(freeSlots.begin()->key); - slots.insert(key, slot, 0); + const int slot = *freeSlots.begin(); + slots.insert(NametagSlotMap::value_type(key, slot)); freeSlots.erase(freeSlots.begin()); return slot; } @@ -2012,7 +1945,7 @@ NametagItem* NametagManager::insertItem(NametagItem* item) return 0; Random random; // m_seed = 0x759DC150 - const int value = (static_cast(randomRaw(random) | 0x80u) >> 7) + 1; // lcgrand_step + const int value = (static_cast(lcgrandStep(&random.m_seed) | 0x80u) >> 7) + 1; item->m_lastSightCheckTime = static_cast(value) * 2.98023223876953125e-08; // flt_1020CFD0 = 2^-25 m_items[item->getKey()] = item; // slot +0x04, sub_10132750 @@ -2079,12 +2012,14 @@ int NametagManager::orderIcon(int orderType, int orderId) // the device listener - `this` at +0x08 in the shipped bodies +// PE 0x1012CA60. void NametagManager::onDeviceLost() // renderers 0, 1, 2 { for (int type = TTPlayer; type <= TTObject; ++type) m_renderers[type].onDeviceLost(); } +// PE 0x1012CA90. void NametagManager::onDeviceReset() { for (int type = TTPlayer; type <= TTObject; ++type) @@ -2092,6 +2027,7 @@ void NametagManager::onDeviceReset() rebufferAll(); // `jmp [eax+40h]` - a virtual tail call } +// PE 0x1012CAD0. void NametagManager::onDeviceDestroy() { for (int type = TTPlayer; type <= TTObject; ++type) @@ -2119,13 +2055,12 @@ void NametagManager::createIcon(int itemId) } -// 0x1012C720, 249 B, retn 30h - `setTexture ` (the path BY value). +// PE 0x1012C720: 249 B, retn 30h - `setTexture ` (the path BY value). // An icon registers `count` frames at once. A bar needs two calls: index 0 stores the full // texture and its rect, index 1 registers both textures. // The second call's rect is ignored - the bar is registered with the first texture's rect. // Any other index in bar mode just replaces the stored texture. - -void NametagManager::setTexture(int count, vc71::string path, int x, int y, int width, int height) +void NametagManager::setTexture(int count, std::string path, int x, int y, int width, int height) { if (m_textureMode == 0) { @@ -2167,29 +2102,52 @@ void NametagManager::setCullDistance(int type, const Vec2& distance) s_cullDistances[type] = distance; } +// PE 0x1012C8A0. float NametagManager::getEnemyDotLimit() { return s_enemyDotLimit; } +// PE 0x1012C890. void NametagManager::setEnemyDotLimit(float v) { s_enemyDotLimit = v; } +// PE 0x1012C8C0. float NametagManager::getMaxCallDistance() { return s_maxCallDistance; } +// PE 0x1012C8B0. void NametagManager::setMaxCallDistance(float v) { s_maxCallDistance = v; } +// PE 0x1012C8E0. float NametagManager::getVehicleNametagOffset() { return s_vehicleNametagOffset; } +// PE 0x1012C8D0. void NametagManager::setVehicleNametagOffset(float v) { s_vehicleNametagOffset = v; } +// PE 0x1012C900. float NametagManager::getVehicleNametagOffsetFactor() { return s_vehicleNametagOffsetFactor; } +// PE 0x1012C8F0. void NametagManager::setVehicleNametagOffsetFactor(float v) { s_vehicleNametagOffsetFactor = v; } +// PE 0x1012C920. float NametagManager::getMaxFriendlyDistance() { return s_maxFriendlyDistance; } +// PE 0x1012C910. void NametagManager::setMaxFriendlyDistance(float v) { s_maxFriendlyDistance = v; } +// PE 0x1012C940. double NametagManager::getEnemyTagDelayTime() { return s_enemyTagDelayTime; } +// PE 0x1012C930. void NametagManager::setEnemyTagDelayTime(double v) { s_enemyTagDelayTime = v; } +// PE 0x1012C960. double NametagManager::getDeployableDistance() { return s_deployableDistance; } +// PE 0x1012C950. void NametagManager::setDeployableDistance(double v) { s_deployableDistance = v; } +// PE 0x1012C980. double NametagManager::getEnemyTagFadeInTime() { return s_enemyTagFadeInTime; } +// PE 0x1012C970. void NametagManager::setEnemyTagFadeInTime(double v) { s_enemyTagFadeInTime = v; } +// PE 0x1012C9A0. double NametagManager::getEnemyTagFadeOutTime() { return s_enemyTagFadeOutTime; } +// PE 0x1012C990. void NametagManager::setEnemyTagFadeOutTime(double v) { s_enemyTagFadeOutTime = v; } +// PE 0x1012C9C0. float NametagManager::getDeathFadeOutTime() { return s_deathFadeOutTime; } +// PE 0x1012C9B0. void NametagManager::setDeathFadeOutTime(float v) { s_deathFadeOutTime = v; } +// PE 0x1012C9E0. float NametagManager::getManDownFadeOutTime() { return s_manDownFadeOutTime; } +// PE 0x1012C9D0. void NametagManager::setManDownFadeOutTime(float v) { s_manDownFadeOutTime = v; } bool NametagManager::getUseVisualRadiusForVehicles() { return s_useVisualRadiusForVehicles; } +// PE 0x1012C9F0: a byte store into the static (the getter is PE 0x1012CA00). void NametagManager::setUseVisualRadiusForVehicles(bool v) { s_useVisualRadiusForVehicles = v; } diff --git a/Code/BF2/Geom/NametagManager.h b/Code/BF2/Geom/NametagManager.h index 111082ef7..6286952ca 100644 --- a/Code/BF2/Geom/NametagManager.h +++ b/Code/BF2/Geom/NametagManager.h @@ -9,13 +9,13 @@ #define BF2_GEOM_NAMETAGMANAGER_H #include +#include +#include +#include #include "../../RendDX9Abi/PluginAbi.h" #include "../../RendDX9Abi/HfeAbi.h" -#include "../../RendDX9Abi/Vc71String.h" -#include "../../RendDX9Abi/Vc71Vector.h" -#include "../../RendDX9Abi/Vc71Map.h" -#include "../../RendDX9Abi/Vc71IntMap.h" +#include #include "../Core/IBase.h" #include "../Core/WeakPtr.h" #include "../Math/Vec3.h" @@ -39,7 +39,7 @@ class IWeaponObject; // queryWeaponObject's answer (IID 38080) namespace geom { -class NameTagRenderer; // nt_renderer's class - Geom/NameTagRenderer.h, 0x3860 bytes each +class NameTagRenderer; // nt_renderer's class - Geom/NameTagRenderer.h, 0x3860 bytes each in the image // Console enum values select the first icon in each renderer icon group. @@ -118,7 +118,8 @@ struct NametagFade }; -// Base nametag record. Renderer buffering and update helpers share this fixed layout. +// Base nametag record, 0xC0 bytes in the image (0x10131360 lays it out). Renderer buffering, +// drawing and the update helpers read its typed members. class NametagItem { @@ -138,14 +139,15 @@ class NametagItem // Returns true for an object tag whose live template is a UAV vehicle. bool isUAV(); - // data - offsets are the contract + // data - the `+0xNN` comments give the shipped x86 offsets. The members up to m_name still sit + // at them; the std::string members make every later native offset differ. // +0x04 is NOT a member: it is MSVC's padding after the vfptr of a class whose alignment is 8 // (the doubles below). That is why no recovered body ever writes it - and this compiler // reproduces it, which the static_asserts below prove. int m_slot; // +0x08 renderer slot (allocateSlot), -1 = none int m_type; // +0x0C TagType - selects renderer / slot tables - vc71::string m_name; // +0x10 the text the renderer draws (0x101B2320 fonts +0x10) - vc71::string m_text2C; // +0x2C a second string [UNRESOLVED role - update closure] + std::string m_name; // +0x10 the text the renderer draws (0x101B2320 fonts +0x10) + std::string m_text2C; // +0x2C a second string [UNRESOLVED role - update closure] Vec3 m_offset; // +0x48 added to the owner position (player: 0; CP: y = pole // height + 1; objects: y = radius or 1.2) int m_distance; // +0x54 handleEvent tests `(float)m_distance < 150` @@ -159,18 +161,19 @@ class NametagItem int m_flashColorIndex; // +0x70 -1; the second (cross-fade) colour index, -1 = m_colorIndex float m_timer; // +0x74 0; call icon / flash time left (12, 30, 100 s) // Second icon indicating a control point more than two meters above/below the local vehicle. - int m_elevationIcon; // +0x78 -1 + int m_elevationIcon; // +0x78 -1; stored at 0x1012CDF8 / 0x1012CE13 float m_iconRotation; // +0x7C 0; a float: the update closure // stores it with `fstp dword [ebx+7Ch]` (0x1012E6B2 / // 0x1012E6B9) and drawIcons (0x101B1FDD) passes it to // D3DXMatrixRotationZ when flag 0x200 is set. [INFERRED name] int m_team; // +0x80 0; the owner's team // Timestamp of the last line-of-sight check; checks are spaced by at least 0.5 seconds. - double m_lastSightCheckTime; // +0x88 0; insertItem: (seeded Random step) * 2^-25 - Vec3 m_worldPosition; // +0x90 current world-space tag position + double m_lastSightCheckTime; // +0x88 0; insertItem: (seeded Random step) * 2^-25; + // stored at 0x1012E88D + Vec3 m_worldPosition; // +0x90 current world-space tag position (0x1012CD8D..9B) // Control-point height above the local vehicle, rounded by truncating delta + 0.5. // Written with the elevation icon selection; not otherwise read. - int m_heightDelta; // +0x9C 0 + int m_heightDelta; // +0x9C 0; stored at 0x1012CDF0 NametagFade m_fade; // +0xA0..+0xB7 0, 0, 0 unsigned int m_flags; // +0xB8 7 - NametagItemFlag bool m_arrowMode; // +0xBC 0; set = drawn as the off-screen arrow: the renderer's @@ -179,7 +182,7 @@ class NametagItem // [INFERRED name - nt_renderer's reading; nt_update writes it] bool m_dirty; // +0xBD 1; re-buffer requested (update/enableBuffering set it) // Current frustum-test result, required for bar rendering. - bool m_inView; // +0xBE 0 + bool m_inView; // +0xBE 0; stored at 0x101305FE // renamed from m_unknownBF: isEnemyInSight's cached answer - in the // view cone (s_enemyDotLimit) AND a clear line of sight, re-tested at most every 0.5 s // (0x1012E8B1 / 0x1012E8BC). [INFERRED] name. @@ -212,8 +215,8 @@ class PlayerNametagItem : public NametagItem class ObjectNametagItem : public NametagItem { public: - ObjectNametagItem(world::IObject* object, int slot); // 0x1012DA50, 63 B, retn 8 (unreferenced; - // 0x10130880 inlines the same) + // The constructor is 0x1012DA50, 63 B, retn 8 (unreferenced; createObjectItem inlines the same). + ObjectNametagItem(world::IObject* object, int slot); virtual const Vec3& updatePosition(); virtual int getKey(); virtual ~ObjectNametagItem(); @@ -265,55 +268,26 @@ class NametagRayPredicator : public world::ObjectPredicator }; -// Retail-layout containers of the manager. raii wrappers so that construction and destruction run -// in member order - which is exactly the order 0x1012F810 builds them and 0x1012F5A0 tears them -// down (see the destructor's note). +// The manager's containers. As members they are constructed and destroyed in member order - which +// is exactly the order 0x1012F810 builds them and 0x1012F5A0 tears them down (see the destructor's +// note). -struct NametagItemMap : vc71::int_map_layout // std::map -{ - NametagItemMap() { construct(); } // sub_10131690 head - ~NametagItemMap() { destroy(); } // sub_10131A40 + free - // The copy constructor: 0x101327D0 (head, then the structural _Copy) is the image's copy of a - // map - called by the update closure (0x1012FC70, 0x10130290) and, through - // 0x10132860, by the renderer (0x101B33A0); 0x10132580 destroys such a copy and 0x10132280 is its - // erase(first, last). which map those callers copy is theirs to establish - the node shape is the - // same for this map and NametagSlotMap. - NametagItemMap(const NametagItemMap& other) { construct(); copyFrom(other); } -private: - NametagItemMap& operator=(const NametagItemMap&); -}; +// key -> item (head sub_10131690, destroy sub_10131A40). The image's copy of a map, +// 0x101327D0, is called by the update closure (0x1012FC70, 0x10130290) and, through 0x10132860, by +// the renderer (0x101B33A0); 0x10132580 destroys such a copy and 0x10132280 is its +// erase(first, last). Which map those callers copy is theirs to establish - the node shape is the +// same for this map and NametagSlotMap. +typedef std::map NametagItemMap; -struct NametagSlotMap : vc71::int_map_layout // std::map -{ - NametagSlotMap() { construct(); } // sub_1008A320 head - ~NametagSlotMap() { destroy(); } // sub_1008A450 + free - NametagSlotMap(const NametagSlotMap& other) { construct(); copyFrom(other); } -private: - NametagSlotMap& operator=(const NametagSlotMap&); -}; +// key -> slot (head sub_1008A320, destroy sub_1008A450). +typedef std::map NametagSlotMap; -struct NametagFreeSlotSet : vc71::set_layout // std::set - 0x14-byte nodes -{ - NametagFreeSlotSet() { construct(); } // sub_101315F0 head - ~NametagFreeSlotSet() { destroy(); } // sub_10131B00 + free -private: - NametagFreeSlotSet(const NametagFreeSlotSet&); // nothing in the image copies one - NametagFreeSlotSet& operator=(const NametagFreeSlotSet&); -}; +// The slots not in use (head sub_101315F0, destroy sub_10131B00). Nothing in the image copies one. +typedef std::set NametagFreeSlotSet; -// std::vector - the per-TagType pointers to the static float tables. Only ever resized -// once, to three nulls (sub_10132390(3, 0)). -struct NametagTableVector : vc71::vector_layout -{ - NametagTableVector() { first = 0; last = 0; end = 0; } // `alloc` is never written - shipped - ~NametagTableVector(); // free first; zero first/last/end - void resize(unsigned int count, float* value); // sub_10132390 on an empty vector - float*& operator[](int index) { return reinterpret_cast(first)[index]; } - float* at(int index) const { return reinterpret_cast(first)[index]; } -private: - NametagTableVector(const NametagTableVector&); - NametagTableVector& operator=(const NametagTableVector&); -}; +// The per-TagType pointers to the static float tables. Only ever resized once, to three nulls +// (sub_10132390(3, 0)). +typedef std::vector NametagTableVector; // NametagManager - 0x5D8 bytes. @@ -331,7 +305,7 @@ class NametagManager : public IBase, public IEventListener, public dx9rend::Devi virtual void* queryInterface(unsigned int iid) const; // +0x0C // INametagManager, +0x10..+0x68 - // Returns whether all five control-point icons registered (0x1012D610's count check). + // Returns whether all five control-point icons registered (registerControlPointIcons' count check). virtual bool init(const renddx9abi::HostString& team1, const renddx9abi::HostString& team2); // +0x10 virtual void update(); // +0x14 (nt_update) @@ -378,7 +352,7 @@ class NametagManager : public IBase, public IEventListener, public dx9rend::Devi // the `nametags` console surface (non-virtual; the executors load ecx = the singleton) void createBar(int itemId, int barStart, int barEnd); void createIcon(int itemId); - void setTexture(int count, vc71::string path, int x, int y, int width, int height); + void setTexture(int count, std::string path, int x, int y, int width, int height); const Vec2& getCullDistance(int type); void setCullDistance(int type, const Vec2& distance); float getEnemyDotLimit(); void setEnemyDotLimit(float v); @@ -427,6 +401,10 @@ class NametagManager : public IBase, public IEventListener, public dx9rend::Devi // tick an item's m_timer down by the frame delta, resetItem at zero. Unreferenced // in the image (IDA left it undefined). void tickItemTimer(NametagItem* item); + // the map key by item type (PE 0x1012C5B0) and the dirty-flag setter by key (PE 0x1012F3E0); + // both unreachable in 1.50. [INFERRED] names. + static int genericKey(int type, void* item, int orderType); + NametagItem* markItemDirty(int key); // Dispatch position and fade updates according to the item type. void updateItemPosition(NametagItem* item); void updateItemFade(NametagItem* item); @@ -495,8 +473,9 @@ class NametagManager : public IBase, public IEventListener, public dx9rend::Devi // Returns the soldier's default weapon, adapting native and compatibility layouts. static IBase* soldierDefaultWeapon(world::IPlayerControlObject* control); - // the data contract - // Every field below is at its shipped offset; the static_asserts after the class hold them. + // the data, in shipped order + // The `+0xNN` comments give the shipped x86 offsets. The std containers make every native + // offset from m_colors on differ; the static_asserts after the class hold the ones that agree. int m_refCount; // +0x00C 1 double m_time; // +0x010 0.0; update: += frame delta NametagTableVector m_transformations; // +0x018 float* per TagType (first +0x1C) @@ -516,7 +495,7 @@ class NametagManager : public IBase, public IEventListener, public dx9rend::Devi // is stored, back to -1 when used int m_barStart; // +0x3A0 0; createBar's second argument int m_barEnd; // +0x3A4 0; createBar's third argument - vc71::string m_pendingBarPath; // +0x3A8 the bar's first texture path + std::string m_pendingBarPath; // +0x3A8 the bar's first texture path int m_pendingBarRect[4]; // +0x3C4 0; its x, y, width, height int m_pad3D4; // +0x3D4 never touched double m_lastTargetCheckTime; // +0x3D8 0.0; update: every 0.5 s @@ -569,74 +548,22 @@ class NametagManager : public IBase, public IEventListener, public dx9rend::Devi NametagManager& operator=(const NametagManager&); }; -// the layout contract, held where the shipped layout is reproducible -// Every member above is a retail-layout type (vc71::* containers, Frustum, WeakPtr, scalars), so -// the 0x5D8 size holds in both plugin flavours - native and retail-compatible alike. +// The shipped offsets that still hold: the predicator, the frustum, and the members before the +// first std container. The items and the manager hold std containers, so their sizes and later +// offsets are native (the `+0xNN` comments keep the shipped ones). #if defined(_M_IX86) -static_assert(sizeof(NametagItem) == 0xC0, "0x10131360 lays out 0xC0 bytes"); -static_assert(sizeof(PlayerNametagItem) == 0xD0, "0x10130820 allocates 0xD0"); -static_assert(sizeof(ObjectNametagItem) == 0xD0, "0x10130880 allocates 0xD0"); -static_assert(sizeof(OrderNametagItem) == 0x108, "0x10130910 / 0x10130970 allocate 0x108"); static_assert(sizeof(NametagRayPredicator) == 0x10, "0x1012CC27 builds 16 bytes"); static_assert(sizeof(Frustum) == 0x1E8, "the embedded frustum runs +0x3E8..+0x5CF"); -static_assert(sizeof(NametagManager) == 0x5D8, "RefFactory_geom_NametagManager allocates 0x5D8"); static_assert(offsetof(NametagItem, m_slot) == 0x08, "item slot at +0x08"); static_assert(offsetof(NametagItem, m_type) == 0x0C, "item type at +0x0C"); static_assert(offsetof(NametagItem, m_name) == 0x10, "item name at +0x10"); -static_assert(offsetof(NametagItem, m_text2C) == 0x2C, "item second string at +0x2C"); -static_assert(offsetof(NametagItem, m_offset) == 0x48, "item offset at +0x48"); -static_assert(offsetof(NametagItem, m_distance) == 0x54, "item distance at +0x54"); -static_assert(offsetof(NametagItem, m_viewDistance) == 0x58, "item view distance at +0x58"); -static_assert(offsetof(NametagItem, m_rankIcon) == 0x60, "item rank icon at +0x60"); -static_assert(offsetof(NametagItem, m_colorIndex) == 0x64, "item colour index at +0x64"); -static_assert(offsetof(NametagItem, m_icon) == 0x68, "item icon at +0x68"); -static_assert(offsetof(NametagItem, m_callIcon) == 0x6C, "item call icon at +0x6C"); -static_assert(offsetof(NametagItem, m_flashColorIndex) == 0x70, "item flash colour at +0x70"); -static_assert(offsetof(NametagItem, m_timer) == 0x74, "item timer at +0x74"); -// the update closure's fields, renamed above - each offset is a store it makes. -static_assert(offsetof(NametagItem, m_elevationIcon) == 0x78, "0x1012CDF8 / 0x1012CE13 store +0x78"); -static_assert(offsetof(NametagItem, m_iconRotation) == 0x7C, "0x1012E6B2 / 0x1012E6B9 store +0x7C"); -static_assert(offsetof(NametagItem, m_team) == 0x80, "item team at +0x80"); -static_assert(offsetof(NametagItem, m_lastSightCheckTime) == 0x88, "0x1012E88D stores +0x88"); -static_assert(offsetof(NametagItem, m_worldPosition) == 0x90, "0x1012CD8D..9B store +0x90..+0x98"); -static_assert(offsetof(NametagItem, m_heightDelta) == 0x9C, "0x1012CDF0 stores +0x9C"); -static_assert(offsetof(NametagItem, m_fade) == 0xA0, "item fade at +0xA0"); -static_assert(offsetof(NametagItem, m_flags) == 0xB8, "item flags at +0xB8"); -static_assert(offsetof(NametagItem, m_arrowMode) == 0xBC, "item arrow byte at +0xBC"); -static_assert(offsetof(NametagItem, m_dirty) == 0xBD, "item dirty byte at +0xBD"); -static_assert(offsetof(NametagItem, m_inView) == 0xBE, "0x101305FE stores +0xBE"); -static_assert(offsetof(NametagItem, m_inSight) == 0xBF, "0x1012E8B1 / 0x1012E8BC store +0xBF"); static_assert(offsetof(NametagFade, m_sightTime) == 0x00 && offsetof(NametagFade, m_value) == 0x08 && offsetof(NametagFade, m_time) == 0x10, "the fade triple at item +0xA0/+0xA8/+0xB0"); -static_assert(offsetof(PlayerNametagItem, m_player) == 0xC0, "player weak pointer at +0xC0"); -static_assert(offsetof(PlayerNametagItem, m_position) == 0xC4, "player position at +0xC4"); -static_assert(offsetof(ObjectNametagItem, m_object) == 0xC0, "object weak pointer at +0xC0"); -static_assert(offsetof(ObjectNametagItem, m_position) == 0xC4, "object position at +0xC4"); -static_assert(offsetof(OrderNametagItem, m_order) == 0xC0, "order at +0xC0"); -static_assert(offsetof(OrderNametagItem, m_orderType) == 0xF0, "order type at +0xF0"); -static_assert(offsetof(OrderNametagItem, m_targetPosition) == 0xF4, "order position at +0xF4"); -static_assert(offsetof(OrderNametagItem, m_target) == 0x100, "order target at +0x100"); static_assert(offsetof(NametagManager, m_refCount) == 0x00C, "refcount at +0x0C"); static_assert(offsetof(NametagManager, m_time) == 0x010, "time at +0x10"); static_assert(offsetof(NametagManager, m_transformations) == 0x018, "transformation vector at +0x18"); -static_assert(offsetof(NametagManager, m_colors) == 0x028, "colour vector at +0x28"); -static_assert(offsetof(NametagManager, m_alphaArrays) == 0x038, "alpha arrays at +0x38"); -static_assert(offsetof(NametagManager, m_items) == 0x338, "item map at +0x338"); -static_assert(offsetof(NametagManager, m_renderers) == 0x344, "renderers at +0x344"); -static_assert(offsetof(NametagManager, m_bufferingEnabled) == 0x348, "buffering byte at +0x348"); -static_assert(offsetof(NametagManager, m_3dMapOn) == 0x349, "3d-map byte at +0x349"); -static_assert(offsetof(NametagManager, m_freeSlots) == 0x34C, "free-slot sets at +0x34C"); -static_assert(offsetof(NametagManager, m_slotMaps) == 0x370, "slot maps at +0x370"); -static_assert(offsetof(NametagManager, m_textureMode) == 0x394, "texture mode at +0x394"); -static_assert(offsetof(NametagManager, m_pendingBarPath) == 0x3A8, "bar path at +0x3A8"); -static_assert(offsetof(NametagManager, m_pendingBarRect) == 0x3C4, "bar rect at +0x3C4"); -static_assert(offsetof(NametagManager, m_lastTargetCheckTime) == 0x3D8, "target check time at +0x3D8"); -static_assert(offsetof(NametagManager, m_spectatedPlayer) == 0x3E0, "spectated player at +0x3E0"); -static_assert(offsetof(NametagManager, m_targetRoot) == 0x3E4, "target root at +0x3E4"); -static_assert(offsetof(NametagManager, m_frustum) == 0x3E8, "frustum at +0x3E8"); -static_assert(offsetof(NametagManager, m_isDemoPlayback) == 0x5D0, "demo byte at +0x5D0"); #endif // ModuleGeom.cpp's g_NametagManager (the "NametagManager" singleton slot). NametagManager derives diff --git a/Code/BF2/Geom/NametagManagerConsole.cpp b/Code/BF2/Geom/NametagManagerConsole.cpp index 1ee6b431a..0a96dae61 100644 --- a/Code/BF2/Geom/NametagManagerConsole.cpp +++ b/Code/BF2/Geom/NametagManagerConsole.cpp @@ -6,17 +6,18 @@ #include "../../RendDX9Abi/PluginAbi.h" -#if BF2_PLUGIN_ABI_NATIVE #include "NametagManager.h" +#include "../Core/StringUtil.h" // equalsIgnoreCase (sub_10075080) #include "../../RendDX9Abi/HfeAbi.h" #include "../../RendDX9Abi/PluginEntry.h" -#include "../../RendDX9Abi/Vc71String.h" +#include #include "../Core/ConsoleObjectMacro.h" #include "../Core/ConsoleObjects.h" #include "../Math/Vec3.h" +#include #include #include #include @@ -33,6 +34,7 @@ namespace geom { // the enumerator's name; an unnamed value writes nothing. +// PE 0x100B0F83 std::ostream& operator<<(std::ostream& out, NametagItemIDs id) { switch (id) @@ -60,12 +62,6 @@ std::ostream& operator<<(std::ostream& out, NametagItemIDs id) namespace { -// sub_10075080 - std::string equality through _stricmp (case-insensitive). -inline bool equalsNoCase(const std::string& a, const char* b) -{ - return ::_stricmp(a.c_str(), b) == 0; -} - // The shared head of both readers: one whitespace-delimited token (sub_10001A40), and a ONE- // character token is first turned into the NametagItemIDs name of its atoi value (0x100B15F3.. @@ -88,32 +84,33 @@ std::string readEnumToken(std::istream& in) std::istream& operator>>(std::istream& in, NametagItemIDs& id) { const std::string token = readEnumToken(in); - if (equalsNoCase(token, "ICRank")) id = ICRank; - else if (equalsNoCase(token, "ICRevive")) id = ICRevive; - else if (equalsNoCase(token, "ICMedic")) id = ICMedic; - else if (equalsNoCase(token, "ICAmmo")) id = ICAmmo; - else if (equalsNoCase(token, "ICRepair")) id = ICRepair; - else if (equalsNoCase(token, "ICVehicleMedic")) id = ICVehicleMedic; - else if (equalsNoCase(token, "ICVehicleRepair")) id = ICVehicleRepair; - else if (equalsNoCase(token, "ICVehicleAmmo")) id = ICVehicleAmmo; - else if (equalsNoCase(token, "ICHealthBar")) id = ICHealthBar; - else if (equalsNoCase(token, "ICArmorBar")) id = ICArmorBar; - else if (equalsNoCase(token, "ICAmmoBar")) id = ICAmmoBar; - else if (equalsNoCase(token, "ICSquadOrder")) id = ICSquadOrder; - else if (equalsNoCase(token, "ICCommanderOrder")) id = ICCommanderOrder; - else if (equalsNoCase(token, "ICTarget")) id = ICTarget; - else if (equalsNoCase(token, "ICObject")) id = ICObject; - else if (equalsNoCase(token, "ICObjectVehicleDrop")) id = ICObjectVehicleDrop; + if (equalsIgnoreCase(token, "ICRank")) id = ICRank; + else if (equalsIgnoreCase(token, "ICRevive")) id = ICRevive; + else if (equalsIgnoreCase(token, "ICMedic")) id = ICMedic; + else if (equalsIgnoreCase(token, "ICAmmo")) id = ICAmmo; + else if (equalsIgnoreCase(token, "ICRepair")) id = ICRepair; + else if (equalsIgnoreCase(token, "ICVehicleMedic")) id = ICVehicleMedic; + else if (equalsIgnoreCase(token, "ICVehicleRepair")) id = ICVehicleRepair; + else if (equalsIgnoreCase(token, "ICVehicleAmmo")) id = ICVehicleAmmo; + else if (equalsIgnoreCase(token, "ICHealthBar")) id = ICHealthBar; + else if (equalsIgnoreCase(token, "ICArmorBar")) id = ICArmorBar; + else if (equalsIgnoreCase(token, "ICAmmoBar")) id = ICAmmoBar; + else if (equalsIgnoreCase(token, "ICSquadOrder")) id = ICSquadOrder; + else if (equalsIgnoreCase(token, "ICCommanderOrder")) id = ICCommanderOrder; + else if (equalsIgnoreCase(token, "ICTarget")) id = ICTarget; + else if (equalsIgnoreCase(token, "ICObject")) id = ICObject; + else if (equalsIgnoreCase(token, "ICObjectVehicleDrop")) id = ICObjectVehicleDrop; return in; } // Numeric input is formatted as NametagItemIDs, so numeric TagType input leaves type unchanged. +// PE 0x100B197B std::istream& operator>>(std::istream& in, TagType& type) { const std::string token = readEnumToken(in); - if (equalsNoCase(token, "TTPlayer")) type = TTPlayer; - else if (equalsNoCase(token, "TTOrder")) type = TTOrder; - else if (equalsNoCase(token, "TTObject")) type = TTObject; + if (equalsIgnoreCase(token, "TTPlayer")) type = TTPlayer; + else if (equalsIgnoreCase(token, "TTOrder")) type = TTOrder; + else if (equalsIgnoreCase(token, "TTObject")) type = TTObject; return in; } @@ -146,12 +143,13 @@ void consoleCreateIcon(NametagItemIDs id) nametagSingleton()->createIcon(id); } -// the path is copied into a local and then again into the by-value parameter; the -// console boundary is also where it changes representation (SkyDomeConsole.cpp's toRetail). +// PE 0x100B954B (executor body): the path is copied into a local and then again into the by-value +// parameter, both through the std::string copy constructor (IAT 0x101DB198), so embedded NULs +// survive. The console boundary is also where it changes representation (SkyDomeConsole.cpp's toRetail). void consoleSetTexture(int count, const std::string& path, int x, int y, int width, int height) { const std::string local(path); - nametagSingleton()->setTexture(count, vc71::string(local.c_str()), x, y, width, height); + nametagSingleton()->setTexture(count, std::string(local), x, y, width, height); } Vec2 consoleGetCullDistance(TagType type) @@ -181,7 +179,8 @@ void setDeployableDistance(double v) { nametagSingleton()->setDeployableD } // anonymous namespace -// Local six-argument static console binding for setTexture. +// Local six-argument static console binding for setTexture: constructor PE 0x100B9448, executor +// PE 0x100B954B (requires six arguments), parser PE 0x100B95B8 (six persistent per-argument values). // Requires exactly six arguments; only the second argument is a string. #define NT_CONSOLE_METHOD_6_STATIC_ACTIVE(fnName, target, activeExpr, A0, A1, A2, A3, A4, A5, listTag) \ @@ -225,48 +224,83 @@ static BF2_CC_NAME BF2_CC_INSTANCE; // 0x101E6320, "float" 0x101E4270, "double" 0x101E4618, "void" 0x101E345C. BF2_CONSOLE_OBJECT("nametags", 2, 0) +// PE 0x100B91B9, 0x100B92A9, 0x100B9266: constructor, argument conversion, result formatting. BF2_CONSOLE_METHOD_3_STATIC_ACTIVE(createBar, consoleCreateBar, nametagsActive(), NametagItemIDs, int, int, kNametagsConsoleTag) +// PE 0x100B9368, 0x100B93FB: constructor, argument conversion. BF2_CONSOLE_METHOD_1_STATIC_ACTIVE(createIcon, consoleCreateIcon, nametagsActive(), NametagItemIDs, kNametagsConsoleTag) +// PE 0x100B9448, 0x100B954B, 0x100B95B8: constructor, executor, argument conversion. NT_CONSOLE_METHOD_6_STATIC_ACTIVE(setTexture, consoleSetTexture, nametagsActive(), int, std::string, int, int, int, int, kNametagsConsoleTag) +// PE 0x100B9745, 0x100B9801, 0x100B97C7: constructor, argument conversion, executor. BF2_CONSOLE_METHOD_1_RET_ACTIVE(getCullDistance, consoleGetCullDistance, Vec2, nametagsActive(), TagType, kNametagsConsoleTag) +// PE 0x100B984E, 0x100B9919, 0x100B98DF: constructor, argument conversion, executor. BF2_CONSOLE_METHOD_2_STATIC_ACTIVE(setCullDistance, consoleSetCullDistance, nametagsActive(), TagType, Vec2, kNametagsConsoleTag) +// PE 0x100B99BE, 0x100B9A2F: constructor, argument conversion. BF2_CONSOLE_PROPERTY_FN(enemyDotLimit, float, nametagsActive(), nametagSingleton()->getEnemyDotLimit(), setEnemyDotLimit, kNametagsConsoleTag) +// PE 0x100B9AC7, 0x100B9B38: constructor, argument conversion. BF2_CONSOLE_PROPERTY_FN(maxCallDistance, float, nametagsActive(), nametagSingleton()->getMaxCallDistance(), setMaxCallDistance, kNametagsConsoleTag) +// PE 0x100B9BD0, 0x100B9C41: constructor, argument conversion. BF2_CONSOLE_PROPERTY_FN(vehicleNametagOffset, float, nametagsActive(), nametagSingleton()->getVehicleNametagOffset(), setVehicleNametagOffset, kNametagsConsoleTag) +// PE 0x100B9CD9, 0x100B9D4A: constructor, argument conversion. BF2_CONSOLE_PROPERTY_FN(vehicleNametagOffsetFactor, float, nametagsActive(), nametagSingleton()->getVehicleNametagOffsetFactor(), setVehicleNametagOffsetFactor, kNametagsConsoleTag) +// PE 0x100B9DE2, 0x100B9E53: constructor, argument conversion. BF2_CONSOLE_PROPERTY_FN(maxFriendlyDistance, float, nametagsActive(), nametagSingleton()->getMaxFriendlyDistance(), setMaxFriendlyDistance, kNametagsConsoleTag) +// PE 0x100B9EEB, 0x100B9FBA, 0x100B9F5C: constructor, argument conversion, result formatting. BF2_CONSOLE_PROPERTY_FN(enemyTagDelayTime, double, nametagsActive(), nametagSingleton()->getEnemyTagDelayTime(), setEnemyTagDelayTime, kNametagsConsoleTag) +// PE 0x100BA053, 0x100BA0C4: constructor, argument conversion. BF2_CONSOLE_PROPERTY_FN(enemyTagFadeInTime, double, nametagsActive(), nametagSingleton()->getEnemyTagFadeInTime(), setEnemyTagFadeInTime, kNametagsConsoleTag) +// PE 0x100BA15D, 0x100BA1CE: constructor, argument conversion. BF2_CONSOLE_PROPERTY_FN(enemyTagFadeOutTime, double, nametagsActive(), nametagSingleton()->getEnemyTagFadeOutTime(), setEnemyTagFadeOutTime, kNametagsConsoleTag) +// PE 0x100BA267, 0x100BA2D8: constructor, argument conversion. BF2_CONSOLE_PROPERTY_FN(deathFadeOutTime, float, nametagsActive(), nametagSingleton()->getDeathFadeOutTime(), setDeathFadeOutTime, kNametagsConsoleTag) +// PE 0x100BA370, 0x100BA3E1: constructor, argument conversion. BF2_CONSOLE_PROPERTY_FN(manDownFadeOutTime, float, nametagsActive(), nametagSingleton()->getManDownFadeOutTime(), setManDownFadeOutTime, kNametagsConsoleTag) +// PE 0x100BA479, 0x100BA4F6: constructor, argument conversion. BF2_CONSOLE_PROPERTY_FN(deployableDistance, double, nametagsActive(), nametagSingleton()->getDeployableDistance(), setDeployableDistance, kNametagsConsoleTag) +#if defined(_MSC_VER) && defined(_M_IX86) +#define NAMETAG_CONSOLE_STDCALL __stdcall +#else +#define NAMETAG_CONSOLE_STDCALL // [CHOSEN, not recovered] stdcall is an x86-only convention +#endif + +// PE 0x1000D920. [INFERRED] name and placement: the one-argument float square root (stdcall, +// retn 4: fld the argument, fsqrt, answered in st0). Its only caller is the dynamic initialiser of +// g_inverseSquareRootTwo below (0x101D05D6); placed with that global, which the image keeps +// directly after this TU's createIcon binding object (0x1024F550..0x1024F5F3). +float NAMETAG_CONSOLE_STDCALL squareRootStdcall(float value) +{ + return std::sqrt(value); +} + +// [INFERRED] name. 1 / sqrt(2), computed at load (PE 0x101D05CC: fld 2.0, the call, fdivr 1.0, +// fstp 0x1024F5F4); no instruction reads it. +float g_inverseSquareRootTwo = 1.0f / squareRootStdcall(2.0f); + bool registerNametagManagerConsoleObjects() { return mainConsoleObjects->registerConsoleObjects(consoleBindingList(kNametagsConsoleTag)); @@ -281,5 +315,4 @@ bool unregisterNametagManagerConsoleObjects() } // namespace hfe } // namespace dice -#endif // BF2_PLUGIN_ABI_NATIVE #endif // BF2_IMAGE_RENDDX9 diff --git a/Code/BF2/Geom/NametagManagerUpdate.inl b/Code/BF2/Geom/NametagManagerUpdate.inl index 11d7c4ec2..c2f49d213 100644 --- a/Code/BF2/Geom/NametagManagerUpdate.inl +++ b/Code/BF2/Geom/NametagManagerUpdate.inl @@ -12,73 +12,18 @@ namespace { float settingsFloat(const char* name, float defaultValue) { const renddx9abi::HostString key(name); -#if BF2_PLUGIN_ABI_NATIVE return settings->floatGet(key, defaultValue); -#else - void* const repository = settings; - typedef const float& (__thiscall* FloatGetFn)(void*, const renddx9abi::HostString&, - const float&); - return reinterpret_cast((*reinterpret_cast(repository))[0x20 / 4])( - repository, key, defaultValue); -#endif } // Returns the player's kit as its primary IObject face across the host ABI boundary. world::IObject* hudPlayerKit(IBase* hud, world::IPlayer* player) { -#if BF2_PLUGIN_ABI_NATIVE return reinterpret_cast(hud)->getPlayerKit(player); -#else - typedef world::IObject* (__thiscall* GetPlayerKitFn)(void*, world::IPlayer*); - return reinterpret_cast((*reinterpret_cast(hud))[0x90 / 4])(hud, player); -#endif } void hudEnableVOHelpMessage(IBase* hud, int message) { -#if BF2_PLUGIN_ABI_NATIVE reinterpret_cast(hud)->enableVOHelpMessage(message); -#else - typedef void (__thiscall* EnableVOHelpMessageFn)(void*, int); - reinterpret_cast((*reinterpret_cast(hud))[0xF8 / 4])(hud, message); -#endif -} - -// sub_10103CB0 - the object, then its +0x28 parents, asking each for IID_IPlayerControlObject -// (ds:10208CF0 = 50373); the first answer. (SkinnedMesh.cpp, BundledMeshDraw.cpp, XpLightManager.cpp -// and NameTagRendererDraw.inl each carry a TU-local copy of this 20-byte body; the tree has no shared -// declaration to call.) -world::IPlayerControlObject* owningControlObject(world::IObject* object) -{ - for (; object; object = world::object_detail::LayoutAccess::parent(object)) - { - void* const found = object->queryInterface(world::IID_IPlayerControlObject); - if (found) - return static_cast(found); - } - return 0; -} - -// sub_100777A0 - normalise in place unless |v|^2 is already within FLT_EPSILON (flt_10208958) of 1; -// a vector with |v|^2 below FLT_EPSILON is zeroed and -20001 answered. A NaN length fails both tests -// and normalises to NaN. (SkyDome.cpp's vec3Normalize and SkinnedMesh.cpp keep TU-local copies.) -int nametagNormalizeVec3(Vec3& v) -{ - const float lengthSquared = v.x * v.x + v.y * v.y + v.z * v.z; - if (std::fabs(lengthSquared - 1.0f) < 1.1920929e-07f) - return 0; - if (std::fabs(lengthSquared) < 1.1920929e-07f) - { - v.x = 0.0f; - v.y = 0.0f; - v.z = 0.0f; - return -20001; - } - const float scale = 1.0f / std::sqrt(lengthSquared); - v.x = scale * v.x; - v.y = scale * v.y; - v.z = scale * v.z; - return 0; } // sub_1000ED40, __stdcall, `retn 0Ch` (value, low, high): `fcomi high; fcmovnb` then @@ -136,12 +81,14 @@ void parkTransformation(float* transformations, int slot) class NametagRootIgnorePredicator : public world::ObjectPredicator { public: + // PE 0x101C7F20 NametagRootIgnorePredicator(unsigned int flags, world::IObject* object) : m_flags(flags) , m_root(static_cast(rootParent(object))) { } + // PE 0x101C7F50 virtual bool predicate(world::IObject* object) { if (rootParent(object) == m_root) @@ -157,10 +104,8 @@ public: }; -// Iterates a by-value copy of the host's seat map in key order. -// Native builds copy std::map; compatibility builds copy the VC7.1 tree on the engine heap. +// Iterates a by-value copy of the host's seat map (the std::map getPcos() answers) in key order. -#if BF2_PLUGIN_ABI_NATIVE class NametagSeatCopy { public: @@ -181,40 +126,14 @@ private: SeatMap m_seats; SeatMap::const_iterator m_it; }; -#else -class NametagSeatCopy -{ -public: - explicit NametagSeatCopy(world::IPlayerControlObject* pco) - { - m_seats.construct(); - m_seats.copyFrom(*reinterpret_cast(pco->getPcos())); // +0x60, - m_node = m_seats.begin(); - } - ~NametagSeatCopy() - { - m_seats.destroy(); // 0x10132280 + free - } - bool atEnd() const { return m_node == m_seats.end(); } - world::IPlayerControlObject* seat() const { return m_node->value; } - void next() { m_node = SeatLayout::next(m_node); } - -private: - NametagSeatCopy(const NametagSeatCopy&); - NametagSeatCopy& operator=(const NametagSeatCopy&); - - typedef vc71::int_map_layout SeatLayout; - SeatLayout m_seats; - SeatLayout::node* m_node; -}; -#endif } // anonymous namespace -// Advances tag selection, positions, fade and text while buffering is enabled. +// PE 0x10130360: advances tag selection, positions, fade and text while buffering is enabled. // Requires the Game singleton; crosshair refresh and item updates share the same due timestamp. - +// The retail phase product is a float store whose st0 stays double; [CHOSEN, not recovered] the +// float conversion below stands for the 24-bit x87 precision the Direct3D device sets. void NametagManager::update() { if (!m_bufferingEnabled) @@ -251,13 +170,13 @@ void NametagManager::update() // the manager's own frustum: the render view's, re-projected to (0, 2000] dx9rend::IRenderView* const view = dx9rend::rendererGetRenderView(); // Renderer +0x48 - m_frustum = *view->getFrustumPtr(); // +0x74 - m_frustum.setPerspective(m_frustum.getFov(), m_frustum.m_aspect, 0.0f, 2000.0f, - m_frustum.m_transformation); + rendmath::frustumAssign(m_frustum, *view->getFrustumPtr()); // +0x74 + rendmath::frustumSetPerspective(m_frustum, m_frustum.getFov(), m_frustum.m_aspect, 0.0f, + 2000.0f, m_frustum.m_transformation); // PE 0x1007A460 - for (NametagItemMap::node* it = m_items.begin(); it != m_items.end(); it = NametagItemMap::next(it)) + for (NametagItemMap::iterator it = m_items.begin(); it != m_items.end(); ++it) { - NametagItem* const item = it->value; + NametagItem* const item = it->second; tickItemTimer(item); // 0x1012CB00, inlined updateItemPosition(item); // 0x1012E8D0, inlined @@ -287,7 +206,7 @@ void NametagManager::update() { frustum = &m_frustum; } - item->m_inView = frustum->inside(item->m_worldPosition); + item->m_inView = rendmath::frustumInside(*frustum, item->m_worldPosition); // PE 0x10079970, call 0x101305F9 // out of view: only a squad member, or a specialist the local player has called for if (!(item->m_flags & NIF_SquadMember) && !item->m_inView) @@ -403,10 +322,23 @@ bool NametagManager::isPlayerSoldierDown(world::IPlayer* player) // x/y to the centre of the pixel it falls in: // x = (floor((x + 1) / (1 / (width / 2))) - 0.5) * (1 / (width / 2)) - 1 (and y by height) // getViewport (+0x14) is asked twice, once per axis. floor is MSVCR71's double floor -// (ds:101DB2D8); the half-pixel subtraction and everything after it are float. +// (ds:101DB2D8); X spills after the half-pixel subtraction, Y stays in x87 until its final store. +// PE 0x1012C510 void NametagManager::projectOntoView(Vec4& position, dx9rend::IRenderView* view) { +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain the x87 expressions and their explicit float/double spills. + using namespace bf2x87; + const float invHalfWidth = store(div(wide(1), mul(wide(view->getViewport()[2]), wide(0.5f)))); + const float invHalfHeight = store(div(wide(1), mul(wide(view->getViewport()[3]), wide(0.5f)))); + const double floorX = std::floor(storeDouble(div(add(wide(position.x), wide(1)), wide(invHalfWidth)))); + const float pixelX = store(sub(wide(floorX), wide(0.5f))); + const double floorY = std::floor(storeDouble(div(add(wide(position.y), wide(1)), wide(invHalfHeight)))); + const Real pixelY = sub(wide(floorY), wide(0.5f)); + position.x = store(sub(mul(wide(pixelX), wide(invHalfWidth)), wide(1))); + position.y = store(sub(mul(pixelY, wide(invHalfHeight)), wide(1))); +#else const float invHalfWidth = 1.0f / (view->getViewport()[2] * 0.5f); // [ebp-4] const float invHalfHeight = 1.0f / (view->getViewport()[3] * 0.5f); // [ebp-8] const float pixelX = static_cast( @@ -415,6 +347,7 @@ void NametagManager::projectOntoView(Vec4& position, dx9rend::IRenderView* view) std::floor(static_cast((position.y + 1.0f) / invHalfHeight)) - 0.5f); position.x = pixelX * invHalfWidth - 1.0f; position.y = pixelY * invHalfHeight - 1.0f; +#endif } @@ -425,6 +358,7 @@ void NametagManager::projectOntoView(Vec4& position, dx9rend::IRenderView* view) // The camera is used with no null test (0x1012CBA5), unlike findCrosshairTarget / isInViewCone. // The eye point is copied out of the camera matrix before the target is asked for its position. +// PE 0x1012CB40. bool NametagManager::isLineOfSightClear(world::IObject* target) { world::IPlayer* const local = localHumanPlayer(); @@ -542,11 +476,19 @@ void NametagManager::updateObjectItem(NametagItem* item) const float dx = vehiclePosition.x - position.x; const float dz = vehiclePosition.z - position.z; +#if defined(__APPLE__) + const int distance = bf2x87::toIntTruncate(std::sqrt(dz * dz + dx * dx)); // fistp, truncating +#else const int distance = static_cast(std::sqrt(dz * dz + dx * dx)); // fistp, truncating +#endif if (distanceChanged(distance, item->m_distance)) { item->m_dirty = true; +#if defined(__APPLE__) + item->m_distance = bf2x87::toIntTruncate(static_cast(distance) + 0.5f); +#else item->m_distance = static_cast(static_cast(distance) + 0.5f); +#endif } } @@ -653,7 +595,7 @@ bool NametagManager::isInViewCone(world::IObject* object, float dotLimit) toObject.x = position.x - eye.m[12]; toObject.y = position.y - eye.m[13]; toObject.z = position.z - eye.m[14]; - nametagNormalizeVec3(toObject); + rendmath::normalize(toObject); dot = toObject.z * forward.z + toObject.y * forward.y + toObject.x * forward.x; } return dot > dotLimit; @@ -745,7 +687,8 @@ void NametagManager::updateHudTarget(world::IPlayer* local, world::IPlayer* play world::IObject* const soldier = player->getDefaultVehicle(); // PE +0xA0 if (!vehicle || vehicle != soldier) return; - world::IPlayerControlObject* const control = owningControlObject(soldier); + world::IPlayerControlObject* const control = + static_cast(staticMeshControlObject(soldier)); // sub_10103CB0 if (!control) return; world::IWeaponObject* const weapon = queryWeaponObject(soldierDefaultWeapon(control)); @@ -789,11 +732,7 @@ void NametagManager::updateHudTarget(world::IPlayer* local, world::IPlayer* play IBase* NametagManager::soldierDefaultWeapon(world::IPlayerControlObject* control) { -#if BF2_PLUGIN_ABI_NATIVE return static_cast(control)->m_weapon2; -#else - return retailField(control, 0x74); -#endif } @@ -801,6 +740,7 @@ IBase* NametagManager::soldierDefaultWeapon(world::IPlayerControlObject* control // Every link is null-tested; update (0x101305A3) and the object fade (0x1012E703) inline the same // test on items of every type. +// PE 0x1012D7D0. bool NametagItem::isUAV() { if (m_type != TTObject) @@ -859,7 +799,7 @@ void NametagManager::updateItemSelection(NametagItem* item) double NametagManager::calcFog(double distance) { const float* const fogRange = reinterpret_cast( - static_cast(dx9rend::g_raShaderConstants) + 0xA8); + dx9rend::raShaderConstantsAt(0xA8)); // FogRange, 4 floats const float nearScaled = static_cast(fogRange[0] * distance); // [ebp+8] as a float const float nearTerm = nearScaled + fogRange[2]; // [ebp-10h] const float farTerm = static_cast(distance * fogRange[1] + fogRange[3]); // [ebp-0Ch] @@ -887,7 +827,8 @@ void NametagManager::updatePlayerItemPosition(NametagItem* item) if (player != viewer) { world::IObject* const vehicle = player->getVehicle(); // PE +0x44 - Mat4 cameraMatrix = Mat4::getIdentity(); + Mat4 cameraMatrix; + rendmath::constructIdentity(cameraMatrix); // 0x1012E55E if (viewer->getCamera()) // PE +0x17C cameraMatrix = viewer->getCamera()->getTransformation(0.0f); if (vehicle) @@ -895,7 +836,11 @@ void NametagManager::updatePlayerItemPosition(NametagItem* item) const Vec3& vehiclePosition = vehicle->getAbsolutePosition(); // PE +0x68 const float dx = cameraMatrix.m[12] - vehiclePosition.x; const float dz = cameraMatrix.m[14] - vehiclePosition.z; +#if defined(__APPLE__) + const int distance = bf2x87::toIntTruncate(std::sqrt(dz * dz + dx * dx)); // fistp +#else const int distance = static_cast(std::sqrt(dz * dz + dx * dx)); // fistp +#endif if (distanceChanged(distance, item->m_distance)) { item->m_distance = distance; @@ -903,7 +848,8 @@ void NametagManager::updatePlayerItemPosition(NametagItem* item) } } - Mat4 vehicleMatrix = Mat4::getIdentity(); + Mat4 vehicleMatrix; + rendmath::constructIdentity(vehicleMatrix); // 0x1012E630 float vehicleForwardY; if (vehicle) { @@ -1107,7 +1053,7 @@ void NametagManager::updatePlayerItemFade(NametagItem* item) // getPcos() map are occupied (+0x18 isOccupied), in key order. // Unlike isPrimaryOccupant, a null seat is NOT skipped - it is dispatched on, as shipped. // `pco` itself is not null-tested. Its only callers (0x1012FD6A, 0x1012FFBE) hand it -// owningControlObject(rootParent(vehicle)) unguarded; update reaches both only for a player tag +// staticMeshControlObject(rootParent(vehicle)) unguarded; update reaches both only for a player tag // that kept NIF_PrimaryOccupant this frame - which needs a vehicle whose root answers // IPlayerControlObject - so a null does not arrive on the shipped path. @@ -1137,7 +1083,7 @@ void NametagManager::updateLocalVehicleSeats(NametagItem* item) world::IPlayer* const local = localHumanPlayer(); if (local != player || !local) return; - const int others = countSeats(owningControlObject(static_cast( + const int others = countSeats(static_cast(staticMeshControlObject( rootParent(local->getVehicle())))) - 1; if (others != s_lastSeatCount) // dword_1025CEA0 { @@ -1157,8 +1103,8 @@ void NametagManager::rebuildItemText(NametagItem* item) case TTPlayer: { world::IPlayer* const player = static_cast(item)->m_player.get(); - vc71::string passengers; // [ebp-1Ch] - const int others = countSeats(owningControlObject(static_cast( + std::string passengers; // [ebp-1Ch] + const int others = countSeats(static_cast(staticMeshControlObject( rootParent(player->getVehicle())))) - 1; if (others != 0) passengers = nametagFormatString(" [+%d]", others); @@ -1171,14 +1117,14 @@ void NametagManager::rebuildItemText(NametagItem* item) && static_cast(item->m_distance) <= s_cullDistances[TTPlayer].y) { const renddx9abi::HostString& name = fromHostStdString(player->getName()); // PE +0x20 - vc71::string label(nametagFormatString("[%dm] %s", item->m_distance, name.c_str())); + std::string label(nametagFormatString("[%dm] %s", item->m_distance, name.c_str())); label += passengers; item->m_name = label; } else { const renddx9abi::HostString& name = fromHostStdString(player->getName()); - vc71::string label(renddx9abi::toVc71String(name)); + std::string label(renddx9abi::fromHostString(name)); label += passengers; item->m_name = label; } @@ -1203,7 +1149,7 @@ void NametagManager::rebuildItemText(NametagItem* item) world::IObject* const object = static_cast(item)->m_object.get(); if (item->isUAV()) { - item->m_name = renddx9abi::toVc71String( + item->m_name = renddx9abi::fromHostString( fromHostStdString(object->getName())); // PE +0x60 } else if (object && !item->m_arrowMode && (item->m_flags & NIF_Bit2)) diff --git a/Code/BF2/Geom/NativeGeometrySlots.h b/Code/BF2/Geom/NativeGeometrySlots.h new file mode 100644 index 000000000..03c5f81b0 --- /dev/null +++ b/Code/BF2/Geom/NativeGeometrySlots.h @@ -0,0 +1,37 @@ +// [CHOSEN, not recovered] Logical slots in the native static renderer's explicit +// geometry tables. These tables retain PE order; Clang does not lay them out. +// tools/macos/vtable_audit.py checks every named entry against its providers. +#ifndef BF2_GEOM_NATIVEGEOMETRYSLOTS_H +#define BF2_GEOM_NATIVEGEOMETRYSLOTS_H +namespace dice { namespace hfe { namespace geom { namespace native_geometry { +constexpr unsigned SetFov = 4; // PE +0x10 / ELF +0x10 +constexpr unsigned GetFov = 5; // PE +0x14 (no ELF caller read) +constexpr unsigned GetShadowRecord = 10; // PE +0x28 (renderer-internal; no ELF caller read) +constexpr unsigned GetTemplate = 14; +constexpr unsigned GetBoundingRadius = 17; // PE +0x44 / ELF +0x48 +constexpr unsigned GetGeometryTransform = 18; // PE +0x48 (renderer-internal; no ELF caller read) +constexpr unsigned SetPartTransform = 19; +constexpr unsigned SetGeometryTransform = 20; // PE +0x50 / ELF +0x50 (both ports, GenericFireArm/Object) +constexpr unsigned SetBoneTransforms = 21; +constexpr unsigned GatherUsedBones = 22; // PE +0x58 / ELF +0x5C (SkinnedMesh) +constexpr unsigned GetPartCount = 23; +constexpr unsigned SetExcludedPart = 24; // PE +0x60 / ELF +0x64 (SkinnedMesh) +constexpr unsigned SetSubgeom = 27; // PE +0x6C / ELF +0x70 +constexpr unsigned GetSubgeom = 28; +constexpr unsigned GetSubgeomCount = 29; // PE +0x74 / ELF +0x78 +constexpr unsigned SetLod = 30; +constexpr unsigned GetLod = 31; +constexpr unsigned GetLodCount = 32; +constexpr unsigned SetUvTranslation = 36; // PE +0x90 / ELF +0x94 +constexpr unsigned SetUvTransformation = 38; // PE +0x98 / ELF +0x9C +constexpr unsigned SetOwnerObject = 39; // PE +0x9C (the ELF arm kept +0x9C) +constexpr unsigned UpdateFlags = 48; // PE +0xC0 / ELF +0xC4 (StaticMesh) +constexpr unsigned SetNextGeometry = 50; // PE +0xC8 / ELF +0xCC +constexpr unsigned GetNextGeometry = 51; // PE +0xCC / ELF +0xD0 +constexpr unsigned SetFirstPerson = 53; // PE +0xD4 / ELF +0xD8 (MeshParticleMesh) +constexpr unsigned SetLightSourceMask = 56; // PE +0xE0 / ELF +0xE4 (StaticMesh +0x28C) +constexpr unsigned GetLightSourceMask = 57; // PE +0xE4 / ELF +0xE8 (7 when unsupported) +// The selector's input remains the original four-byte PE/ELF offset pair. +constexpr unsigned slot(unsigned pe, unsigned) { return pe / 4; } +} } } } +#endif diff --git a/Code/BF2/Geom/ObjectDrawer.cpp b/Code/BF2/Geom/ObjectDrawer.cpp index 7969997a0..ca2c5192a 100644 --- a/Code/BF2/Geom/ObjectDrawer.cpp +++ b/Code/BF2/Geom/ObjectDrawer.cpp @@ -4,9 +4,15 @@ // Occlusion evidence and validation: docs/recovery-notes/Geom/object-occlusion.md. #ifdef BF2_IMAGE_RENDDX9 +#include "../RendDX9/RendDX9Math.h" // rendmath::zeroVector +#include "../../RendDX9Abi/ThunkAbi.h" #include "ObjectDrawer.h" +#include "GeometryInstanceData.h" // the opacity pair and slot of a geometry instance #include "MeshTemplate.h" // meshBoundsFinalize (sub_101C5EB0) - slot +0x3C +#include "StaticMesh.h" // StaticMeshOccluderRecord - slot +0xEC's records +#include "StaticMeshTemplate.h" // StaticMeshOccluderEdge +#include "BoxCorners.h" // the eight-corner object box (0x100AE110) #include "../../RendDX9Abi/BfMemory.h" #include "../../RendDX9Abi/Frontier.h" @@ -19,12 +25,24 @@ #include "../Math/Plane3.h" #include "../Math/Vec3.h" #include "../RendMisc/IRenderView.h" +#include "../GeomMisc/Debug.h" +#include "../GeomMisc/DebugRenderer.h" +#if defined(__APPLE__) +#include "../Platform/X87Compat.h" +#endif #include "../Scene/Object/ObjectPredicator.h" +#include "../Scene/Object/ObjectManager.h" +#if !defined(_WIN32) +#include "../Math/Frustum.h" +#include "../RendDX9/RendDX9Math.h" // the RendDX9.dll Math copies +#endif #include #include +#include #include +#include #include #include @@ -44,28 +62,28 @@ namespace { // while the remaining method signatures are unknown. -#define OD_FRONTIER(fn, slotOffset, addr, what) \ - void __fastcall fn(void* self, void*) \ - { \ - RD9_FRONTIER_AT("dice::hfe::geom::ObjectDrawer::slot_" #slotOffset \ - " (" #addr " - " what ")", self, slotOffset); \ - } - -OD_FRONTIER(od_slot1C, 0x1C, 0x100F8DE0, "324 B, unread") +void RD9_THUNK od_slot1C(void* self RD9_THUNK_EDX) +{ + static_cast(self)->slot_0x1C(); +} // +0x3C, the box occlusion query; the body is ObjectDrawer::isBoundsOccluded below. // `retn 4`, the answer in AL, like +0x38. -bool __fastcall od_slot3C(void* self, void*, void* bounds); -#undef OD_FRONTIER +bool RD9_THUNK od_slot3C(void* self RD9_THUNK_EDX, void* bounds); // +0x38, the occlusion query; the body is ObjectDrawer::isGeometryOccluded below. // `retn 4`, the answer in AL: __fastcall with the dummy edx gives the same shape. -bool __fastcall od_slot38(void* self, void*, void* geometry); +bool RD9_THUNK od_slot38(void* self RD9_THUNK_EDX, void* geometry); + +#if defined(_M_IX86) +static_assert(offsetof(ObjectDrawer, m_eventVptr) == 0x04, "the ECCore handler subobject at +0x04"); +#endif // Handles the drawer's event subobject at +0x04 and updates the outer frame gate. // [UNRESOLVED] Event data at +0x2C must point to a word compared with 4; neither pointer is guarded. -char __fastcall od_event00(void* self, void*, int category, int id, void* data, void* arg4) +// PE 0x100F7C70 +char RD9_THUNK od_event00(void* self RD9_THUNK_EDX, int category, int id, void* data, void* arg4) { (void)category; (void)arg4; @@ -73,12 +91,16 @@ char __fastcall od_event00(void* self, void*, int category, int id, void* data, if (id != 1) return static_cast(id - 1); - // &m_eventVptr sits at +0x04, so the object starts four bytes back. - ObjectDrawer* const drawer = - reinterpret_cast(static_cast(self) - 4); + // &m_eventVptr sits at +0x04, so the object starts that far back. + ObjectDrawer* const drawer = reinterpret_cast( + static_cast(self) - offsetof(ObjectDrawer, m_eventVptr)); - const unsigned int* const probe = - *reinterpret_cast(static_cast(data) + 0x2C); + // `data` is the notification node; PE +0x2C is its payload pointer, m_data (asserted below). +#if defined(_M_IX86) + static_assert(offsetof(NotificationEventNode, m_data) == 0x2C, "retail PE notification payload"); +#endif + const unsigned int* const probe = static_cast( + static_cast(static_cast(data))->m_data); const char result = (*probe == 4u) ? 1 : 0; drawer->m_byte0C = static_cast(result); @@ -86,71 +108,69 @@ char __fastcall od_event00(void* self, void*, int category, int id, void* data, } // The two that take an argument, so they cannot use the macro above. -void __fastcall od_draw(void* self, void*, float time) +void RD9_THUNK od_draw(void* self RD9_THUNK_EDX, float time) { static_cast(self)->draw(time); } -void __fastcall od_updateVisible(void* self, void*, float time) +void RD9_THUNK od_updateVisible(void* self RD9_THUNK_EDX, float time) { static_cast(self)->updateVisible(time); } -void __fastcall od_slot18(void* self, void*) +void RD9_THUNK od_slot18(void* self RD9_THUNK_EDX, float time) { - static_cast(self)->slot_0x18(); + static_cast(self)->slot_0x18(time); } -void __fastcall od_slot20(void* self, void*, void* object) +void RD9_THUNK od_slot20(void* self RD9_THUNK_EDX, void* object) { - (void)object; - RD9_FRONTIER_AT("dice::hfe::geom::ObjectDrawer::slot_0x20 (0x100F8F30, 51 B - takes an object, " - "clears a flag through its +0xA4, then two helpers)", self, 0x20); + static_cast(self)->slot_0x20(object); } // the written leaf slots, as the thin __fastcall adapters the tables need -void __fastcall od_addRef(void* self, void*) +void RD9_THUNK od_addRef(void* self RD9_THUNK_EDX) { static_cast(self)->addRef(); } -int __fastcall od_getRef(void* self, void*) +int RD9_THUNK od_getRef(void* self RD9_THUNK_EDX) { return static_cast(self)->getRef(); } -int __fastcall od_release(void* self, void*) +int RD9_THUNK od_release(void* self RD9_THUNK_EDX) { return static_cast(self)->release(); } -void* __fastcall od_queryInterface(void* self, void*, unsigned int iid) +void* RD9_THUNK od_queryInterface(void* self RD9_THUNK_EDX, unsigned int iid) { return static_cast(self)->queryInterface(iid); } -void* __fastcall od_getObjectVector(void* self, void*, int which) +void* RD9_THUNK od_getObjectVector(void* self RD9_THUNK_EDX, int which) { return static_cast(self)->getObjectVector(which); } -void __fastcall od_setRenderView(void* self, void*, void* view) +void RD9_THUNK od_setRenderView(void* self RD9_THUNK_EDX, void* view) { static_cast(self)->setRenderView(view); } -void* __fastcall od_getRenderView(void* self, void*) +void* RD9_THUNK od_getRenderView(void* self RD9_THUNK_EDX) { return static_cast(self)->getRenderView(); } -void __fastcall od_setOccluder(void* self, void*, IBase* occluder) +void RD9_THUNK od_setOccluder(void* self RD9_THUNK_EDX, IBase* occluder) { static_cast(self)->setOccluder(occluder); } -IBase* __fastcall od_getOccluder(void* self, void*) +IBase* RD9_THUNK od_getOccluder(void* self RD9_THUNK_EDX) { return static_cast(self)->getOccluder(); } @@ -162,9 +182,11 @@ IBase* __fastcall od_getOccluder(void* self, void*) class ObjectDrawerFlagPredicator { public: + // PE 0x101C7E90 explicit ObjectDrawerFlagPredicator(unsigned int mask) : m_mask(mask) {} // every bit of the mask must be present, not merely one of them. + // PE 0x101C7EB0 virtual bool predicate(world::IObject* object) { return (m_mask & object->getFlags()) == m_mask; @@ -211,6 +233,7 @@ void objectDrawerCensusReport() // Updates visual transforms and decals for an object; geometry submission runs in the deferred pass. // Null objects are ignored. Typed calls preserve platform-specific virtual ordering. +// PE 0x100F7BE0 void objectDrawerDrawObject(world::IObject* object) { if (!object) @@ -227,9 +250,9 @@ void objectDrawerDrawObject(world::IObject* object) if (void* const decal = object->getDecalObject()) // PE +0xD8 { - typedef void (__fastcall* DecalFn)(void*, void*, int); + typedef void (__thiscall* DecalFn)(void*, int); void** const vtbl = *reinterpret_cast(decal); - reinterpret_cast(vtbl[0x0C / sizeof(void*)])(decal, 0, 1); + reinterpret_cast(vtbl[0x0C / 4])(decal, 1); } if (world::object_detail::LayoutAccess::geometry(object)) @@ -265,6 +288,7 @@ class ObjectDrawerFlagPredicator; world::IObject** objectDrawerSetBegin(ObjectDrawerSet& set); world::IObject** objectDrawerSetEnd(ObjectDrawerSet& set); +// PE 0x100F7E80 void objectDrawerVisualDistanceUpdate(ObjectDrawer* self, ObjectDrawerSet& set, float time) { if (self->m_byte0C && g_objectDrawerVisualTick != 1) @@ -286,9 +310,18 @@ void objectDrawerVisualDistanceUpdate(ObjectDrawer* self, ObjectDrawerSet& set, const Mat4& objectMatrix = object->getVisualAbsoluteTransformation(); // PE +0x8C const float dx = viewMatrix->m[12] - objectMatrix.m[12]; +#if defined(__APPLE__) + // [CHOSEN, not recovered] Only x is spilled before the x87 sum z*z + y*y + x*x. + using namespace bf2x87; + const Real dy = sub(wide(viewMatrix->m[13]), wide(objectMatrix.m[13])); + const Real dz = sub(wide(viewMatrix->m[14]), wide(objectMatrix.m[14])); + const float distance = store(squareRoot(add(add(mul(dz, dz), mul(dy, dy)), + mul(wide(dx), wide(dx))))); +#else const float dy = viewMatrix->m[13] - objectMatrix.m[13]; const float dz = viewMatrix->m[14] - objectMatrix.m[14]; - const float distance = static_cast(::sqrt(static_cast(dx * dx + dy * dy + dz * dz))); + const float distance = static_cast(::sqrt(static_cast(dz * dz + dy * dy + dx * dx))); +#endif object->handleVisualUpdate(time, distance); // PE +0xA4 } @@ -307,11 +340,11 @@ struct ObjectDrawerGeometrySortKey if (!lg || !rg) return false; - typedef unsigned int (__fastcall* KeyFn)(void*, void*); + typedef unsigned int (__thiscall* KeyFn)(void*); void** const lv = *reinterpret_cast(lg); void** const rv = *reinterpret_cast(rg); - return reinterpret_cast(lv[0x38 / sizeof(void*)])(lg, 0) - < reinterpret_cast(rv[0x38 / sizeof(void*)])(rg, 0); + return reinterpret_cast(lv[0x38 / 4])(lg) + < reinterpret_cast(rv[0x38 / 4])(rg); } }; @@ -322,20 +355,12 @@ struct ObjectDrawerGeometrySortKey world::IObject** objectDrawerSetBegin(ObjectDrawerSet& set) { -#if BF2_PLUGIN_ABI_NATIVE return set.empty() ? 0 : &set[0]; -#else - return reinterpret_cast(set.first); -#endif } world::IObject** objectDrawerSetEnd(ObjectDrawerSet& set) { -#if BF2_PLUGIN_ABI_NATIVE return set.empty() ? 0 : &set[0] + set.size(); -#else - return reinterpret_cast(set.last); -#endif } void objectDrawerSort(ObjectDrawerSet& set) @@ -352,45 +377,62 @@ void objectDrawerSort(ObjectDrawerSet& set) // allocation-free. void objectDrawerClear(ObjectDrawerSet& set) { -#if BF2_PLUGIN_ABI_NATIVE set.clear(); -#else - set.last = set.first; -#endif } unsigned int objectDrawerSetSize(const ObjectDrawerSet& set) { -#if BF2_PLUGIN_ABI_NATIVE return static_cast(set.size()); -#else - return set.first ? static_cast((set.last - set.first) >> 2) : 0u; -#endif } -// Queries host collision/noncollision object grids through the selected compatibility slot. -void objectDrawerQueryGrid(unsigned int slot, const void* frustum, ObjectDrawerSet& out, +// [CHOSEN, not recovered] Restrict the native bridge to its two attested caller slots: +// PE 0x100F97D6 (collision) and 0x100F9045 (noncollision). +template +void objectDrawerQueryGrid(const void* frustum, ObjectDrawerSet& out, ObjectDrawerFlagPredicator* predicator, float time) { - if (!::dice::hfe::objectManager) - return; - + static_assert(Slot == 0x40 || Slot == 0x4C, "ObjectDrawer only queries the two frustum grids"); +#if defined(_WIN32) // In the native build, out is the host's std::vector; the plugin ABI uses its own layout. - typedef void (__fastcall* QueryFn)(void*, void*, const void*, void*, + typedef void (__thiscall* QueryFn)(void*, const void*, void*, void*, int, float, float); void* const manager = ::dice::hfe::objectManager; void** const vtbl = *reinterpret_cast(manager); - reinterpret_cast(vtbl[slot / sizeof(void*)])( - manager, 0, frustum, &out, predicator, 1, 0.0f, time); + reinterpret_cast(vtbl[Slot / 4])( + manager, frustum, &out, predicator, 1, 0.0f, time); +#else + // [CHOSEN, not recovered] Non-PE builds link the native world::ObjectManager, whose grid-query + // overloads follow the ELF table order (ObjectManager.h): the PE offsets +0x40/+0x4C name + // other overloads there (+0x40 is the sphere query), so the frustum queries returned nothing + // and no static, bundled or skinned mesh was ever submitted. + // Called by name instead; ObjectDrawerFlagPredicator keeps ObjectPredicator's table. + world::ObjectManager* const manager = + reinterpret_cast(::dice::hfe::objectManager); + const Frustum& f = *static_cast(frustum); + world::ObjectPredicator* const pred = reinterpret_cast(predicator); + if (Slot == 0x40) + manager->getObjectsFromGrid(f, out, pred, true, 0.0f, time); + else + manager->getNoCollisionObjectsFromGrid(f, out, pred, true, 0.0f, time); +#endif } void objectDrawerBuildOccluders(ObjectDrawer* self, ObjectDrawerSet& set); +void objectDrawerDebugOccluders(ObjectDrawer* self, ObjectDrawerSet& set); void objectDrawerCullObjects(ObjectDrawer* self, ObjectDrawerSet& set); void objectDrawerDestroyMembers(ObjectDrawer* self); +// The geometry instance's retail-ordered table: +0x18 submits, +0xCC answers the next geometry. +inline void** objectDrawerGeometryTable(void* geometry) +{ + void** const vtbl = *reinterpret_cast(geometry); + return vtbl; +} + // Submits each geometry in the object's chain using the drawer's view and occluder. // The unmodeled interface uses +0x18 for submission and +0xCC for the next geometry. +// PE 0x100F7C90 void objectDrawerDeferredGeometryPass(ObjectDrawer* self, world::IObject* object) { if (!object) @@ -404,12 +446,12 @@ void objectDrawerDeferredGeometryPass(ObjectDrawer* self, world::IObject* object void* geometry = world::object_detail::LayoutAccess::geometry(object); while (geometry) { - typedef void (__fastcall* PassFn)(void*, void*, void*, void*, int); - typedef void* (__fastcall* NextFn)(void*, void*); - void** const vtbl = *reinterpret_cast(geometry); - reinterpret_cast(vtbl[0x18 / sizeof(void*)])( - geometry, 0, self->m_renderView, self->m_occluder, 1); - geometry = reinterpret_cast(vtbl[0xCC / sizeof(void*)])(geometry, 0); + typedef void (__thiscall* PassFn)(void*, void*, void*, int); + typedef void* (__thiscall* NextFn)(void*); + void** const vtbl = objectDrawerGeometryTable(geometry); + reinterpret_cast(vtbl[0x18 / 4])( + geometry, self->m_renderView, self->m_occluder, 1); + geometry = reinterpret_cast(vtbl[0xCC / 4])(geometry); } } @@ -438,35 +480,83 @@ void* const kObjectDrawerEventVtable[1] = reinterpret_cast(&od_event00) // +0x00 }; -// sub_100F9A80 - the sentinel allocator both containers use. The constructor then self-links all -// three of the node's pointers and sets the byte at +0x19, which is what identifies the container -// as a _Tree rather than a list; see the header. -void* objectDrawerTreeSentinel() -{ - unsigned char* const node = static_cast(::renddx9abi::engineAlloc(0x20)); - if (!node) - return 0; +} // anonymous namespace - node[0x19] = 1; - *reinterpret_cast(node + 0x00) = node; - *reinterpret_cast(node + 0x04) = node; - *reinterpret_cast(node + 0x08) = node; - return node; +// PE 0x100F7B80: unreachable in 1.50: no code or data references (its only call site is its own +// recursion). [INFERRED] name. Retail passes the receiver through the recursion without reading it, +// so it is not modelled. Stores the base opacity (+0x28) in the object's geometry instance, hands +// the instance's combined opacity (base times the distance opacity at +0x2C) to its opacity slot +// (+0xF4), then does the same for the child chain (virtual +0xEC, sibling link +0x2C). +void objectDrawerApplyFade(world::IObject* object, float fade) +{ + if (GeometryInstanceData* const geometry = + static_cast(world::object_detail::LayoutAccess::geometry(object))) + { + geometry->m_float28 = fade; + geometry->setOpacity(fade * geometry->m_float2C); + } + for (world::IObject* child = object->getChild(); child; + child = world::object_detail::LayoutAccess::sibling(child)) + objectDrawerApplyFade(child, fade); } -} // anonymous namespace +// PE 0x100F9A00: unreachable in 1.50: no code or data references (only the Plane3 vector copy kernels +// at PE 0x100F9B20 / 0x100F9D10 / 0x100FA760 carry the same step inline). [INFERRED] name and +// placement: Plane3 declares no assignment, so the shipped one is kept as a function here. +// Copies the normal, normalises it in place as PE 0x100777A0 does (a unit-length normal is left +// alone; a near-zero one is zeroed; the squared length is spilled to a float first), and copies the +// distance last and unscaled. +Plane3& plane3AssignNormalized(Plane3& destination, const Plane3& source) +{ + const float distance = source.d; + Vec3& n = destination.normal; + n = source.normal; + const double epsilon = 1.1920928955078125e-7; +#if defined(__APPLE__) + // [CHOSEN, not recovered] Keep the squared length and the scale in x87 precision. + typedef bf2x87::Real Real; + const float lengthSquared = static_cast((Real(n.x) * Real(n.x) + Real(n.y) * Real(n.y)) + + Real(n.z) * Real(n.z)); + if (!(::fabs(static_cast(Real(lengthSquared) - Real(1.0f))) < epsilon)) + { + if (::fabs(static_cast(lengthSquared)) < epsilon) + n.x = n.y = n.z = 0.0f; + else + { + const Real scale = Real(1.0f) / bf2x87::squareRoot(Real(lengthSquared)); + n.x = static_cast(scale * Real(n.x)); + n.y = static_cast(scale * Real(n.y)); + n.z = static_cast(scale * Real(n.z)); + } + } +#else + const float lengthSquared = (n.x * n.x + n.y * n.y) + n.z * n.z; + if (!(::fabs(static_cast(lengthSquared) - 1.0) < epsilon)) + { + if (::fabs(static_cast(lengthSquared)) < epsilon) + n.x = n.y = n.z = 0.0f; + else + { + const float scale = 1.0f / ::sqrtf(lengthSquared); + n.x = scale * n.x; + n.y = scale * n.y; + n.z = scale * n.z; + } + } +#endif + destination.d = distance; + return destination; +} // Initializes drawer state and registers its ECCore subobject at priority zero. +// PE 0x100F9130 ObjectDrawer::ObjectDrawer() : m_vptr(kObjectDrawerPrimaryVtable) , m_eventVptr(kObjectDrawerEventVtable) , m_refCount(1) , m_byte0C(0) - , m_updateVisibleHasRun(0) - , m_byte0E(0) - , m_renderView(0) , m_occluder(0) , m_byte60(1) , m_float64(60.0f) @@ -476,35 +566,19 @@ ObjectDrawer::ObjectDrawer() , m_culledCount(0) , m_dword78(0) , m_dword7C(0) - , m_dword80(0) - , m_dword84(0) , m_byte88(0) { - m_tree10.comp = 0; - m_tree10.head = objectDrawerTreeSentinel(); - m_tree10.size = 0; - - m_tree1C.comp = 0; - m_tree1C.head = objectDrawerTreeSentinel(); - m_tree1C.size = 0; - - // +0x30 IS NOT zeroed and that is the shipped behaviour - see the header's note on the - // sixteen-byte vector shape. The other three words of each are. -#if !BF2_PLUGIN_ABI_NATIVE - m_visibleSet.first = 0; m_visibleSet.last = 0; m_visibleSet.end = 0; - m_drawSet.first = 0; m_drawSet.last = 0; m_drawSet.end = 0; -#endif - // +0x50 is the retail shape in both flavours (see the header). - m_vector50.first = 0; m_vector50.last = 0; m_vector50.end = 0; + // The two trees (+0x10, +0x1C; sub_100F9A80 builds each sentinel), the two object sets + // (+0x30, +0x40) and the occluder list (+0x50) are default-constructed empty. // EventManager vslot +0x2C, registerEventHandler(category 0, &subobject, 0). - if (::dice::hfe::eventManager) - { - ::dice::hfe::eventManager->registerEventHandler( - static_cast(0), - reinterpret_cast(&m_eventVptr), - 0); - } + ::dice::hfe::eventManager->registerEventHandler( + static_cast(0), + reinterpret_cast(&m_eventVptr), + 0); + m_renderView = 0; + m_updateVisibleHasRun = 0; + m_byte0E = 0; } ObjectDrawer::~ObjectDrawer() @@ -525,6 +599,7 @@ int ObjectDrawer::getRef() // 0x10051870, the } // Decrement, and on zero run the destructor and free through the engine allocator. +// PE 0x100FAFF0 int ObjectDrawer::release() { const int remaining = --m_refCount; @@ -538,6 +613,7 @@ int ObjectDrawer::release() // Two ids answer, everything else is null. IT IS NOT const-correct in the image - // the slot takes the object non-const - but every recovered reader treats it as a query. +// PE 0x100FAFA0 void* ObjectDrawer::queryInterface(unsigned int iid) const { if (iid == 1u) @@ -586,9 +662,9 @@ IBase* ObjectDrawer::getOccluder() const return m_occluder; } -// Builds and sorts visible candidates, applies occlusion, then stores camera distances. +// PE 0x100F9790. Builds and sorts candidates, applies occlusion, then stores camera distances. // Requires setRenderView before the call. - +// PE 0x100F9790 void ObjectDrawer::updateVisible(float time) { objectDrawerClear(m_visibleSet); // sub_10032330(this+0x30, 0, 0) @@ -596,15 +672,13 @@ void ObjectDrawer::updateVisible(float time) ObjectDrawerFlagPredicator predicator(world::IObject::OFIsVisible); // sub_101C7E90(2) dx9rend::IRenderView* const view = static_cast(m_renderView); - objectDrawerQueryGrid(0x40, view->getFrustumPtr(), m_visibleSet, &predicator, time); + objectDrawerQueryGrid<0x40>(view->getFrustumPtr(), m_visibleSet, &predicator, time); objectDrawerSort(m_visibleSet); if (m_byte88) { - RD9_FRONTIER_AT("dice::hfe::geom::ObjectDrawer::updateVisible (sub_100F8750, the +0x88 " - "pass - unread; the constructor leaves +0x88 clear so nothing has reached " - "it yet)", this, 0x14); + objectDrawerDebugOccluders(this, m_visibleSet); // PE 0x100F8750 } m_dword7C = 0; @@ -627,15 +701,15 @@ void ObjectDrawer::updateVisible(float time) } -// Draws the visible collision set, then separately queries and draws noncollision objects. - +// PE 0x100F8F70. Draws collision objects before querying and drawing noncollision objects. void ObjectDrawer::draw(float time) { + ObjectDrawerFlagPredicator predicator(world::IObject::OFIsVisible); if (!m_updateVisibleHasRun) { - // The shipped diagnostic is sub_10074300(6, __FILE__, 598, "") streamed into - dice's own - // file and line. This image logs instead of asserting; the text is theirs. - ::renddx9abi::logf("ObjectDrawer.cpp:598 updateVisible() must be drawn before this!"); + ::renddx9abi::Debug(DebugTypeError, + "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\ObjectDrawer.cpp", 598, "") + << "updateVisible() must be drawn before this!"; return; } @@ -647,10 +721,8 @@ void ObjectDrawer::draw(float time) objectDrawerClear(m_drawSet); // sub_10032330(this+0x40, 0, 0) - ObjectDrawerFlagPredicator predicator(world::IObject::OFIsVisible); - dx9rend::IRenderView* const view = static_cast(m_renderView); - objectDrawerQueryGrid(0x4C, view->getFrustumPtr(), m_drawSet, &predicator, time); + objectDrawerQueryGrid<0x4C>(view->getFrustumPtr(), m_drawSet, &predicator, time); objectDrawerSort(m_drawSet); @@ -681,16 +753,17 @@ void ObjectDrawer::draw(float time) // Submits the deferred geometry pass once per updateVisible/draw pair. // Consumes both completion flags before callbacks, so reentrant calls see them cleared. -void ObjectDrawer::slot_0x18() +// PE 0x100F7D60. The caller pushes a float, but neither return arm reads it (`retn 4`). +void ObjectDrawer::slot_0x18(float /*time*/) { ObjectDrawerFlagPredicator predicator(world::IObject::OFIsVisible); // built, never read (void)predicator; if (!m_updateVisibleHasRun || !m_byte0E) { - // sub_10074300(6, __FILE__, 638, "") streamed into - dice's own file and line. This image - // logs where retail asserts; the text is theirs. - ::renddx9abi::logf("ObjectDrawer.cpp:638 updateVisible() must be drawn before this!"); + ::renddx9abi::Debug(DebugTypeError, + "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\ObjectDrawer.cpp", 638, "") + << "updateVisible() must be drawn before this!"; return; } @@ -710,8 +783,67 @@ void ObjectDrawer::slot_0x18() objectDrawerDeferredGeometryPass(this, *cursor); } } -void ObjectDrawer::slot_0x1C() { od_slot1C(this, 0); } -void ObjectDrawer::slot_0x20(void* o) { od_slot20(this, 0, o); } +// PE 0x100F7D20. Both leaf helpers guard a null object; the subsequent child call does not. +void ObjectDrawer::submitObjectTree(world::IObject* object) +{ + objectDrawerDrawObject(object); // PE 0x100F7BE0 + objectDrawerDeferredGeometryPass(this, object); // PE 0x100F7C90 + for (world::IObject* child = object->getChild(); child; child = child->getSibling()) + submitObjectTree(child); +} + +// PE 0x100F8C00. The first tree is walked forward, the second backward (rbegin to rend), each +// node's geometry (+0x14) submitted through its +0x18 slot with the view and occluder re-read per +// node; then the first tree is cleared, then the second. [CHOSEN, not recovered] node value type +// under the unobservable-type exception (see ObjectDrawerTreeValue): nothing inserts into these +// trees in 1.50, so both walks are empty in practice. +void ObjectDrawer::flushDeferredGeometry() +{ + typedef void (__thiscall* PassFn)(void*, void*, void*, int); + for (ObjectDrawerTree::iterator it = m_tree10.begin(); it != m_tree10.end(); ++it) + { + void* const geometry = it->second.geometry; + reinterpret_cast(objectDrawerGeometryTable(geometry)[0x18 / 4])( + geometry, m_renderView, m_occluder, 1); + } + for (ObjectDrawerTree::reverse_iterator it = m_tree1C.rbegin(); it != m_tree1C.rend(); ++it) + { + void* const geometry = it->second.geometry; + reinterpret_cast(objectDrawerGeometryTable(geometry)[0x18 / 4])( + geometry, m_renderView, m_occluder, 1); + } + m_tree10.clear(); + m_tree1C.clear(); +} + +// PE 0x100F8DE0. Iterate the manager's ID-ordered map without filtering null entries. +void ObjectDrawer::slot_0x1C() +{ + world::ObjectManager* const manager = + reinterpret_cast(::dice::hfe::objectManager); + std::map& objects = manager->getAllObjectsFromGrid(); + for (std::map::iterator it = objects.begin(); + it != objects.end(); ++it) + { + world::IObject* const object = it->second; + objectDrawerDrawObject(object); + objectDrawerDeferredGeometryPass(this, object); + // Shipped defect: a null map value reaches this unguarded virtual call. + for (world::IObject* child = object->getChild(); child; child = child->getSibling()) + submitObjectTree(child); + } + flushDeferredGeometry(); +} + +// PE 0x100F8F30. The visual-update flag test and the object dereference are unguarded. +void ObjectDrawer::slot_0x20(void* value) +{ + world::IObject* const object = static_cast(value); + if ((object->getFlags() & 0x00001000u) != 0) + object->handleVisualUpdate(0.0f, 0.0f); + submitObjectTree(object); + flushDeferredGeometry(); +} // Tests geometry against the occluder set and counts hidden objects. @@ -724,162 +856,57 @@ namespace { // deferred pass above does (StaticMesh / BundledMesh / SkinnedMesh install the same arity at each). inline void* occlusionGeometrySlot(void* geometry, unsigned int offset) { - return (*reinterpret_cast(geometry))[offset / sizeof(void*)]; + return (*reinterpret_cast(geometry))[offset / 4]; } inline const LocalBoundingBox& occlusionGeometryLocalBounds(void* geometry) // +0x40 { - typedef const void* (__fastcall* BoundsFn)(void*, void*); + typedef const void* (__thiscall* BoundsFn)(void*); return *static_cast( - reinterpret_cast(occlusionGeometrySlot(geometry, 0x40))(geometry, 0)); + reinterpret_cast(occlusionGeometrySlot(geometry, 0x40))(geometry)); } inline float occlusionGeometryBoundingRadius(void* geometry) // +0x44 { - typedef float (__fastcall* RadiusFn)(void*, void*); - return reinterpret_cast(occlusionGeometrySlot(geometry, 0x44))(geometry, 0); + typedef float (__thiscall* RadiusFn)(void*); + return reinterpret_cast(occlusionGeometrySlot(geometry, 0x44))(geometry); } inline const Mat4* occlusionGeometryTransformation(void* geometry) // +0x48 { - typedef const Mat4* (__fastcall* TransformFn)(void*, void*); - return reinterpret_cast(occlusionGeometrySlot(geometry, 0x48))(geometry, 0); + typedef const Mat4* (__thiscall* TransformFn)(void*); + return reinterpret_cast(occlusionGeometrySlot(geometry, 0x48))(geometry); } -// VC7.1 size(): a signed byte span divided by the element size, compared unsigned (`jnb`). -inline unsigned int occlusionVectorCount(const char* first, const char* last) -{ - return static_cast((last - first) / 16); -} - -// The eight-corner object box - 0x100AE110 (the 24 floats zeroed), 0x101C6750 (corner i takes x from -// max when bit 2, y when bit 1, z when bit 0) and 0x101C67F0 (all three rows formed from the untouched -// corner; corner 0's y and x rows associate differently from corners 1..7). The same bodies as -// XpLightManager.cpp's ShadowBoxCorners, re-read for this slot. -struct OcclusionBoxCorners -{ - Vec3 corner[8]; - - OcclusionBoxCorners() - { - for (unsigned int i = 0; i < 8; ++i) - corner[i].x = corner[i].y = corner[i].z = 0.0f; - } - - void setBounds(const LocalBoundingBox& bounds) - { - for (unsigned int i = 0; i < 8; ++i) - { - corner[i].x = (i & 4u) ? bounds.m_max.x : bounds.m_min.x; - corner[i].y = (i & 2u) ? bounds.m_max.y : bounds.m_min.y; - corner[i].z = (i & 1u) ? bounds.m_max.z : bounds.m_min.z; - } - } - - void transform(const Mat4& world) - { - const float* const m = world.m; - for (unsigned int i = 0; i < 8; ++i) - { - const float x = corner[i].x; - const float y = corner[i].y; - const float z = corner[i].z; - const float tz = z * m[10] + x * m[2] + y * m[6] + m[14]; - const float ty = i == 0 ? x * m[1] + y * m[5] + z * m[9] + m[13] - : x * m[1] + z * m[9] + y * m[5] + m[13]; - const float tx = i == 0 ? z * m[8] + x * m[0] + y * m[4] + m[12] - : y * m[4] + z * m[8] + x * m[0] + m[12]; - corner[i].x = tx; - corner[i].y = ty; - corner[i].z = tz; - } - } -}; +// The eight-corner object box is Geom/BoxCorners.h's BoxCorners (zeroed by 0x100AE110, then +// setBounds and transform). // Frees each owned plane list while retaining capacity in the outer occluder list. void objectDrawerClearOccluders(ObjectDrawer* self) { - vc71::vector_layout& records = self->m_vector50; - for (char* p = records.first; p != records.last; p += sizeof(vc71::vector_layout)) - { - vc71::vector_layout& planes = *reinterpret_cast(p); - if (planes.first) - ::renddx9abi::engineFree(planes.first); - planes.first = 0; - planes.last = 0; - planes.end = 0; - } - records.last = records.first; + self->m_vector50.clear(); } -// These private views describe the records produced by StaticMesh and its template. -struct ObjectDrawerOccluderFace -{ - Plane3 plane; - vc71::vector_layout* edgeReferences; -}; - -struct ObjectDrawerOccluderRecord -{ - vc71::vector_layout faces; - vc71::vector_layout points; - vc71::vector_layout* edges; -}; - -static_assert(sizeof(ObjectDrawerOccluderFace) == 20, "world-space occluder face stride"); -static_assert(sizeof(ObjectDrawerOccluderRecord) == 36, "world-space occluder record stride"); - -// Owns the local plane list while a separate copy is appended to the drawer's outer list. -struct ObjectDrawerPlaneList +void objectDrawerNormalizeOccluderNormal(Vec3& normal) { - vc71::vector_layout planes; - - ObjectDrawerPlaneList() - { - planes.alloc = 0; - planes.first = 0; - planes.last = 0; - planes.end = 0; - } - - ~ObjectDrawerPlaneList() - { - if (planes.first) - ::renddx9abi::engineFree(planes.first); - } - - void append(const Plane3& plane) - { - if (!vc71::vectorPushBackIn(planes, sizeof(Plane3), &plane)) - throw std::bad_alloc(); - } - - void appendCopyTo(vc71::vector_layout& records) const +#if defined(__APPLE__) + // [CHOSEN, not recovered] Preserve the normalization helper's retained x87 inverse. + using namespace bf2x87; + const float lengthSquared = store(add(add(mul(wide(normal.x), wide(normal.x)), + mul(wide(normal.y), wide(normal.y))), mul(wide(normal.z), wide(normal.z)))); + if (less(bf2x87::abs(sub(wide(lengthSquared), wide(1.0f))), wide(1.1920928955078125e-7f))) + return; + if (less(bf2x87::abs(wide(lengthSquared)), wide(1.1920928955078125e-7f))) { - ObjectDrawerPlaneList copy; - const unsigned int count = vc71::vectorSizeIn(planes, sizeof(Plane3)); - if (count) - { - if (!vc71::vectorReserveIn(copy.planes, sizeof(Plane3), count)) - throw std::bad_alloc(); - ::memcpy(copy.planes.first, planes.first, count * sizeof(Plane3)); - copy.planes.last = copy.planes.first + count * sizeof(Plane3); - } - if (!vc71::vectorPushBackIn(records, sizeof(vc71::vector_layout), ©.planes)) - throw std::bad_alloc(); - copy.planes.first = 0; - copy.planes.last = 0; - copy.planes.end = 0; + normal.x = normal.y = normal.z = 0.0f; + return; } - -private: - ObjectDrawerPlaneList(const ObjectDrawerPlaneList&); - ObjectDrawerPlaneList& operator=(const ObjectDrawerPlaneList&); -}; - -void objectDrawerNormalizeOccluderNormal(Vec3& normal) -{ + const Real inverse = div(wide(1.0f), squareRoot(wide(lengthSquared))); + normal.x = store(mul(inverse, wide(normal.x))); + normal.y = store(mul(inverse, wide(normal.y))); + normal.z = store(mul(inverse, wide(normal.z))); +#else const float lengthSquared = static_cast( static_cast(normal.x) * normal.x + static_cast(normal.y) * normal.y @@ -896,10 +923,125 @@ void objectDrawerNormalizeOccluderNormal(Vec3& normal) normal.x = static_cast(inverse * normal.x); normal.y = static_cast(inverse * normal.y); normal.z = static_cast(inverse * normal.z); +#endif +} + +// PE 0x100F8750. Draws one box per occluder face, using its first two edge references. +// Requires the same world-space StaticMesh records as the production occlusion builder. +void objectDrawerDebugOccluders(ObjectDrawer* self, ObjectDrawerSet& objects) +{ + const float* camera = static_cast(self->m_renderView)->getViewMatrixPtr()->m + 12; + static_cast(self->m_renderView)->getViewMatrixPtr(); // Repeated, result discarded in PE. + for (unsigned int objectIndex = 0; objectIndex < objects.size(); ++objectIndex) + { + world::IObject* object = objects[objectIndex]; + void* geometry = world::object_detail::LayoutAccess::geometry(object); + if (!geometry) continue; + typedef int (__thiscall* Count)(void*); + const int recordCount = reinterpret_cast(occlusionGeometrySlot(geometry, 0xE8))(geometry); + if (!recordCount) continue; + const Vec3& position = object->getAbsolutePosition(); +#if defined(__APPLE__) + // [CHOSEN, not recovered] The PE retains all three differences and both squares in x87. + using namespace bf2x87; + const Real dx = sub(wide(position.x),wide(camera[0])); + const Real dy = sub(wide(position.y),wide(camera[1])); + const Real dz = sub(wide(position.z),wide(camera[2])); + const Real squared = add(add(mul(dx,dx),mul(dy,dy)),mul(dz,dz)); + if (less(mul(wide(self->m_float64),wide(self->m_float64)),squared)) continue; +#else + const float dx = position.x-camera[0], dy = position.y-camera[1], dz = position.z-camera[2]; + if (self->m_float64*self->m_float64 < dx*dx+dy*dy+dz*dz) continue; +#endif + typedef const StaticMeshOccluderRecord* (__thiscall* Record)(void*, int); + for (int recordIndex = 0; recordIndex < recordCount; ++recordIndex) + { + const StaticMeshOccluderRecord* record = reinterpret_cast( + occlusionGeometrySlot(geometry,0xEC))(geometry,recordIndex); + const std::vector* edges = record->edges; + const int faceCount = static_cast(record->faces.size()); + const StaticMeshOccluderFace* face = record->faces.data(); + for (int faceIndex = 0; faceIndex < faceCount; ++faceIndex, ++face) + { + const unsigned short* references = face->edgeReferences->data(); + const Vec3 zero = rendmath::zeroVector(); // PE 0x1007B1E0 + // The high byte encodes edge ownership and is discarded here. + const StaticMeshOccluderEdge& first = (*edges)[references[0] & 0xFFu]; + const StaticMeshOccluderEdge& second = (*edges)[references[1] & 0xFFu]; + const Vec3& a = record->points[first.points[0]]; + const Vec3& b = record->points[first.points[1]]; + const Vec3& c = record->points[second.points[0]]; + const Vec3& d = record->points[second.points[1]]; + Vec3 e1, e2, size, minimum, center; +#if defined(__APPLE__) + e1 = Vec3{store(bf2x87::abs(sub(wide(a.x),wide(b.x)))), store(bf2x87::abs(sub(wide(a.y),wide(b.y)))), store(bf2x87::abs(sub(wide(a.z),wide(b.z))))}; + e2 = Vec3{store(bf2x87::abs(sub(wide(c.x),wide(d.x)))), store(bf2x87::abs(sub(wide(c.y),wide(d.y)))), store(bf2x87::abs(sub(wide(c.z),wide(d.z))))}; + size.x = store(add(wide(e1.x),wide(zero.x))); + const Real y1 = add(wide(zero.y),wide(e1.y)); + size.z = store(add(wide(e1.z),wide(zero.z))); + size.x = store(add(wide(e2.x),wide(size.x))); + const Real ySize = add(wide(e2.y),y1); + size.y = store(ySize); + size.z = store(add(wide(e2.z),wide(size.z))); + if (!greater(wide(size.x),wide(0.01f))) size.x=0.01f; + if (!greater(ySize,wide(0.01f))) size.y=0.01f; + if (!greater(wide(size.z),wide(0.01f))) size.z=0.01f; + auto lessValue = [](float left,float right) { return bf2x87::less(bf2x87::wide(left),bf2x87::wide(right)); }; +#else + e1 = Vec3{::fabsf(a.x-b.x),::fabsf(a.y-b.y),::fabsf(a.z-b.z)}; + e2 = Vec3{::fabsf(c.x-d.x),::fabsf(c.y-d.y),::fabsf(c.z-d.z)}; + size = Vec3{(e1.x+zero.x)+e2.x,e2.y+(zero.y+e1.y),(e1.z+zero.z)+e2.z}; + if (!(size.x>0.01f)) size.x=0.01f; + if (!(size.y>0.01f)) size.y=0.01f; + if (!(size.z>0.01f)) size.z=0.01f; + auto lessValue = [](float left,float right) { return left(g_DebugRenderer)->queueGeometry(81012u,transform,"occluder"); + } + } + } } // Builds camera-facing source and silhouette planes from nearby world-space occluders. // Requires a render view and the StaticMesh face/edge/point records to remain valid for the call. +// [CHOSEN, not recovered] The native port retains the x87 values until the observed float stores. +#if defined(__APPLE__) +using OcclusionScalar = bf2x87::Real; +#else +using OcclusionScalar = double; +#endif + +// PE 0x100F9300 void objectDrawerBuildOccluders(ObjectDrawer* self, ObjectDrawerSet& objects) { dx9rend::IRenderView* const view = static_cast(self->m_renderView); @@ -915,110 +1057,113 @@ void objectDrawerBuildOccluders(ObjectDrawer* self, ObjectDrawerSet& objects) if (!geometry) continue; - typedef int (__fastcall* RecordCountFn)(void*, void*); + typedef int (__thiscall* RecordCountFn)(void*); const int recordCount = reinterpret_cast( - occlusionGeometrySlot(geometry, 0xE8))(geometry, 0); + occlusionGeometrySlot(geometry, 0xE8))(geometry); if (!recordCount) continue; const Vec3& position = object->getAbsolutePosition(); - const double dx = static_cast(position.x) - camera[0]; - const double dy = static_cast(position.y) - camera[1]; - const double dz = static_cast(position.z) - camera[2]; - if (static_cast(self->m_float64) * self->m_float64 < dx * dx + dz * dz + dy * dy) + const OcclusionScalar dx = static_cast(position.x) - camera[0]; + const OcclusionScalar dy = static_cast(position.y) - camera[1]; + const OcclusionScalar dz = static_cast(position.z) - camera[2]; + if (static_cast(self->m_float64) * self->m_float64 < dx * dx + dz * dz + dy * dy) continue; - typedef const ObjectDrawerOccluderRecord* (__fastcall* RecordFn)(void*, void*, int); + // The records are StaticMesh's world-space occluders; their edges are the template's. + typedef const StaticMeshOccluderRecord* (__thiscall* RecordFn)(void*, int); for (int recordIndex = 0; recordIndex < recordCount; ++recordIndex) { - const ObjectDrawerOccluderRecord* const record = reinterpret_cast( - occlusionGeometrySlot(geometry, 0xEC))(geometry, 0, recordIndex); - vc71::vector_layout& edges = *record->edges; - const unsigned int edgeCount = vc71::vectorSizeIn(edges, 4u); - const unsigned int faceCount = vc71::vectorSizeIn(record->faces, sizeof(ObjectDrawerOccluderFace)); + const StaticMeshOccluderRecord* const record = reinterpret_cast( + occlusionGeometrySlot(geometry, 0xEC))(geometry, recordIndex); + std::vector& edges = *record->edges; + const unsigned int edgeCount = static_cast(edges.size()); + const unsigned int faceCount = static_cast(record->faces.size()); if (!faceCount) continue; - ObjectDrawerPlaneList planes; - const ObjectDrawerOccluderFace* const faces = - reinterpret_cast(record->faces.first); + // The local plane list; a separate copy is appended to the drawer's outer list. + std::vector planes; + const StaticMeshOccluderFace* const faces = record->faces.data(); for (unsigned int faceIndex = 0; faceIndex < faceCount; ++faceIndex) { - const ObjectDrawerOccluderFace& face = faces[faceIndex]; + const StaticMeshOccluderFace& face = faces[faceIndex]; const Plane3& plane = face.plane; // The shipped loop takes every iteration's reference count from the first face. - const unsigned int referenceCount = vc71::vectorSizeIn(*faces[0].edgeReferences, 2u); - const double distance = static_cast(plane.normal.y) * camera[1] - + static_cast(plane.normal.x) * camera[0] - + static_cast(plane.normal.z) * camera[2] + plane.d; + const unsigned int referenceCount = + static_cast(faces[0].edgeReferences->size()); + const OcclusionScalar distance = static_cast(plane.normal.y) * camera[1] + + static_cast(plane.normal.x) * camera[0] + + static_cast(plane.normal.z) * camera[2] + plane.d; unsigned char selected = 0; // The original first comparison admits unordered values; the angle comparison does not. if (!(distance <= 0.0)) { - const double facing = -static_cast(forward[2]) * plane.normal.z - + -static_cast(forward[1]) * plane.normal.y - + -static_cast(forward[0]) * plane.normal.x; + const OcclusionScalar facing = -static_cast(forward[2]) * plane.normal.z + + -static_cast(forward[1]) * plane.normal.y + + -static_cast(forward[0]) * plane.normal.x; float angleThreshold; ::memcpy(&angleThreshold, &self->m_dword6C, sizeof(angleThreshold)); if (facing > angleThreshold) { - planes.append(plane); + planes.push_back(plane); selected = 1; } } for (unsigned int referenceIndex = 0; referenceIndex < referenceCount; ++referenceIndex) { - const unsigned char* const reference = reinterpret_cast( - face.edgeReferences->first + 2u * referenceIndex); - unsigned char* const edge = reinterpret_cast(edges.first + 4u * reference[0]); - edge[reference[1] ? 2 : 3] = selected; + // The edge index in the low byte, the created-here flag in the high byte. + const unsigned short reference = (*face.edgeReferences)[referenceIndex]; + StaticMeshOccluderEdge& edge = edges[reference & 0xFFu]; + edge.marks[(reference >> 8) ? 0 : 1] = selected; } } - if (!vc71::vectorSizeIn(planes.planes, sizeof(Plane3))) + if (planes.empty()) continue; - const Vec3* const points = reinterpret_cast(record->points.first); + const Vec3* const points = record->points.data(); for (unsigned int edgeIndex = 0; edgeIndex < edgeCount; ++edgeIndex) { - const unsigned char* const edge = reinterpret_cast(edges.first + 4u * edgeIndex); - if (static_cast(edge[2]) + edge[3] != 1u) + const StaticMeshOccluderEdge& edge = edges[edgeIndex]; + if (static_cast(edge.marks[0]) + edge.marks[1] != 1u) continue; - const Vec3& a = points[edge[0]]; - const Vec3& b = points[edge[1]]; - const double ax = static_cast(a.x) - camera[0]; - const double ay = static_cast(a.y) - camera[1]; - const float az = static_cast(static_cast(a.z) - camera[2]); - const double ex = static_cast(b.x) - a.x; - const double ey = static_cast(b.y) - a.y; - const double ez = static_cast(b.z) - a.z; + const Vec3& a = points[edge.points[0]]; + const Vec3& b = points[edge.points[1]]; + const OcclusionScalar ax = static_cast(a.x) - camera[0]; + const OcclusionScalar ay = static_cast(a.y) - camera[1]; + const float az = static_cast(static_cast(a.z) - camera[2]); + const OcclusionScalar ex = static_cast(b.x) - a.x; + const OcclusionScalar ey = static_cast(b.y) - a.y; + const OcclusionScalar ez = static_cast(b.z) - a.z; const float storedEz = static_cast(ez); Plane3 silhouette; silhouette.normal.x = static_cast(ez * ay - ey * az); silhouette.normal.y = static_cast(az * ex - storedEz * ax); silhouette.normal.z = static_cast(ey * ax - ay * ex); objectDrawerNormalizeOccluderNormal(silhouette.normal); - if (edge[2]) + if (edge.marks[0]) { silhouette.normal.x = -silhouette.normal.x; silhouette.normal.y = -silhouette.normal.y; silhouette.normal.z = -silhouette.normal.z; } - silhouette.d = static_cast(-(static_cast(silhouette.normal.z) * b.z - + static_cast(silhouette.normal.y) * b.y - + static_cast(silhouette.normal.x) * b.x)); - planes.append(silhouette); + silhouette.d = static_cast(-(static_cast(silhouette.normal.z) * b.z + + static_cast(silhouette.normal.y) * b.y + + static_cast(silhouette.normal.x) * b.x)); + planes.push_back(silhouette); } - planes.appendCopyTo(self->m_vector50); + self->m_vector50.push_back(planes); } } } // Removes objects wholly behind any occluder's planes, retaining the order of survivors. // Precise mode tests transformed geometry bounds only when the sphere intersects a plane. +// PE 0x100F8430 void objectDrawerCullObjects(ObjectDrawer* self, ObjectDrawerSet& set) { const bool precise = self->m_byte68 != 0; - OcclusionBoxCorners box; + BoxCorners box; unsigned int index = 0; while (index < objectDrawerSetSize(set)) { @@ -1030,23 +1175,21 @@ void objectDrawerCullObjects(ObjectDrawer* self, ObjectDrawerSet& set) bool boxBuilt = false; bool hidden = false; - for (unsigned int occluder = 0; - self->m_vector50.first && occluder < occlusionVectorCount( - self->m_vector50.first, self->m_vector50.last); ++occluder) + for (unsigned int occluder = 0; occluder < self->m_vector50.size(); ++occluder) { - const vc71::vector_layout& planes = *reinterpret_cast( - self->m_vector50.first + occluder * sizeof(vc71::vector_layout)); + const std::vector& planes = self->m_vector50[occluder]; hidden = true; - for (const char* cursor = planes.first; cursor != planes.last; cursor += sizeof(Plane3)) + for (std::vector::const_iterator cursor = planes.begin(); cursor != planes.end(); + ++cursor) { - const Plane3& plane = *reinterpret_cast(cursor); - const double distance = precise - ? static_cast(plane.normal.z) * centre.z - + static_cast(plane.normal.y) * centre.y - + static_cast(plane.normal.x) * centre.x + plane.d - : static_cast(plane.normal.z) * centre.z - + static_cast(plane.normal.x) * centre.x - + static_cast(centre.y) * plane.normal.y + plane.d; + const Plane3& plane = *cursor; + const OcclusionScalar distance = precise + ? static_cast(plane.normal.z) * centre.z + + static_cast(plane.normal.y) * centre.y + + static_cast(plane.normal.x) * centre.x + plane.d + : static_cast(plane.normal.z) * centre.z + + static_cast(plane.normal.x) * centre.x + + static_cast(centre.y) * plane.normal.y + plane.d; if (precise && distance > 0.0f) { hidden = false; @@ -1068,9 +1211,9 @@ void objectDrawerCullObjects(ObjectDrawer* self, ObjectDrawerSet& set) for (unsigned int corner = 0; corner < 8; ++corner) { const Vec3& point = box.corner[corner]; - if (static_cast(point.z) * plane.normal.z - + static_cast(point.x) * plane.normal.x - + static_cast(plane.normal.y) * point.y + plane.d > 0.0) + if (static_cast(point.z) * plane.normal.z + + static_cast(point.x) * plane.normal.x + + static_cast(plane.normal.y) * point.y + plane.d > 0.0) { hidden = false; break; @@ -1097,33 +1240,9 @@ void objectDrawerCullObjects(ObjectDrawer* self, ObjectDrawerSet& set) } } -void objectDrawerDestroyTreeNodes(void* node) -{ - while (static_cast(node)[0x19] == 0) - { - void** const links = static_cast(node); - objectDrawerDestroyTreeNodes(links[2]); - void* const left = links[0]; - ::renddx9abi::engineFree(node); - node = left; - } -} - -void objectDrawerDestroyTree(ObjectDrawerTreeHeader& tree) -{ - void** const head = static_cast(tree.head); - objectDrawerDestroyTreeNodes(head[1]); - head[1] = head; - tree.size = 0; - head[0] = head; - head[2] = head; - ::renddx9abi::engineFree(tree.head); - tree.head = 0; - tree.size = 0; -} - // Detaches the event listener and releases the drawer's owned storage and occluder. // The event manager must outlive the drawer. Render view and scene objects are borrowed. +// PE 0x100F9210 void objectDrawerDestroyMembers(ObjectDrawer* self) { self->m_vptr = kObjectDrawerPrimaryVtable; @@ -1131,15 +1250,12 @@ void objectDrawerDestroyMembers(ObjectDrawer* self) ::dice::hfe::eventManager->unregisterEventHandler( static_cast(0), reinterpret_cast(&self->m_eventVptr)); objectDrawerClearOccluders(self); - if (self->m_vector50.first) - ::renddx9abi::engineFree(self->m_vector50.first); - self->m_vector50.first = self->m_vector50.last = self->m_vector50.end = 0; + std::vector >().swap(self->m_vector50); ObjectDrawerSet().swap(self->m_drawSet); ObjectDrawerSet().swap(self->m_visibleSet); if (self->m_occluder) self->m_occluder->release(); - objectDrawerDestroyTree(self->m_tree1C); - objectDrawerDestroyTree(self->m_tree10); + // The +0x1C tree, then the +0x10 tree, are destroyed with the drawer after this body. } } // anonymous namespace @@ -1148,12 +1264,12 @@ namespace { // Table thunks use __fastcall with an unused EDX to match the __thiscall slots. // Keep definitions in the anonymous namespace containing their declarations. -bool __fastcall od_slot38(void* self, void*, void* geometry) +bool RD9_THUNK od_slot38(void* self RD9_THUNK_EDX, void* geometry) { return static_cast(self)->isGeometryOccluded(geometry); } -bool __fastcall od_slot3C(void* self, void*, void* bounds) +bool RD9_THUNK od_slot3C(void* self RD9_THUNK_EDX, void* bounds) { return static_cast(self)->isBoundsOccluded(static_cast(bounds)); } @@ -1170,21 +1286,19 @@ bool ObjectDrawer::isGeometryOccluded(void* geometry) if (m_byte68) { - OcclusionBoxCorners box; + BoxCorners box; bool boxBuilt = false; // [ebp-1] for (unsigned int occluder = 0; ; ++occluder) { - if (!m_vector50.first || occluder >= occlusionVectorCount(m_vector50.first, m_vector50.last)) + if (occluder >= m_vector50.size()) break; - const char* const record = m_vector50.first + occluder * 16; + const std::vector& record = m_vector50[occluder]; bool hidden = true; // [ebp-2] for (unsigned int index = 0; ; ++index) { - const char* const planes = *reinterpret_cast(record + 4); - if (!planes || - index >= occlusionVectorCount(planes, *reinterpret_cast(record + 8))) + if (index >= record.size()) break; - const Plane3& plane = *reinterpret_cast(planes + index * 16); + const Plane3& plane = record[index]; const float distance = plane.normal.z * centre.z + plane.normal.y * centre.y + plane.normal.x * centre.x + plane.d; if (distance > 0.0f) @@ -1222,16 +1336,13 @@ bool ObjectDrawer::isGeometryOccluded(void* geometry) for (unsigned int occluder = 0; ; ++occluder) { - if (!m_vector50.first || occluder >= occlusionVectorCount(m_vector50.first, m_vector50.last)) + if (occluder >= m_vector50.size()) break; - const char* const record = m_vector50.first + occluder * 16; - const char* const planes = *reinterpret_cast(record + 4); + const std::vector& planes = m_vector50[occluder]; bool hidden = true; - for (unsigned int index = 0; - planes && index < occlusionVectorCount(planes, *reinterpret_cast(record + 8)); - ++index) + for (unsigned int index = 0; index < planes.size(); ++index) { - const Plane3& plane = *reinterpret_cast(planes + index * 16); + const Plane3& plane = planes[index]; const float distance = plane.normal.z * centre.z + plane.normal.x * centre.x + centre.y * plane.normal.y + plane.d; if (-radius < distance) // 100F8409 `jnp` @@ -1267,17 +1378,15 @@ bool ObjectDrawer::isBoundsOccluded(LocalBoundingBox* bounds) { for (unsigned int occluder = 0; ; ++occluder) { - if (!m_vector50.first || occluder >= occlusionVectorCount(m_vector50.first, m_vector50.last)) + if (occluder >= m_vector50.size()) break; - const char* const record = m_vector50.first + occluder * 16; + const std::vector& record = m_vector50[occluder]; bool hidden = true; // [ebp-1] for (unsigned int index = 0; ; ++index) { - const char* const planes = *reinterpret_cast(record + 4); - if (!planes || - index >= occlusionVectorCount(planes, *reinterpret_cast(record + 8))) + if (index >= record.size()) break; - const Plane3& plane = *reinterpret_cast(planes + index * 16); + const Plane3& plane = record[index]; const float distance = centre.y * plane.normal.y + plane.normal.x * centre.x + centre.z * plane.normal.z + plane.d; if (distance > 0.0f) @@ -1311,16 +1420,13 @@ bool ObjectDrawer::isBoundsOccluded(LocalBoundingBox* bounds) for (unsigned int occluder = 0; ; ++occluder) { - if (!m_vector50.first || occluder >= occlusionVectorCount(m_vector50.first, m_vector50.last)) + if (occluder >= m_vector50.size()) break; - const char* const record = m_vector50.first + occluder * 16; - const char* const planes = *reinterpret_cast(record + 4); + const std::vector& planes = m_vector50[occluder]; bool hidden = true; - for (unsigned int index = 0; - planes && index < occlusionVectorCount(planes, *reinterpret_cast(record + 8)); - ++index) + for (unsigned int index = 0; index < planes.size(); ++index) { - const Plane3& plane = *reinterpret_cast(planes + index * 16); + const Plane3& plane = planes[index]; const float distance = plane.normal.z * centre.z + plane.normal.x * centre.x + centre.y * plane.normal.y + plane.d; if (-radius < distance) // 100F81DA `jnp` diff --git a/Code/BF2/Geom/ObjectDrawer.h b/Code/BF2/Geom/ObjectDrawer.h index 87c6eb84e..8583f6c6e 100644 --- a/Code/BF2/Geom/ObjectDrawer.h +++ b/Code/BF2/Geom/ObjectDrawer.h @@ -7,9 +7,10 @@ #ifndef BF2_GEOM_OBJECTDRAWER_H #define BF2_GEOM_OBJECTDRAWER_H -#include "../../RendDX9Abi/Vc71Vector.h" #include "../Core/IBase.h" +#include "../Math/Plane3.h" +#include #include namespace dice { @@ -22,24 +23,24 @@ struct LocalBoundingBox; // isBoundsOccluded's argument (Math/LocalBoundingBox namespace geom { -// Compatibility tree header; opaque comparator and sentinel retain the 12-byte shape. - -struct ObjectDrawerTreeHeader +// The two trees at +0x10 / +0x1C. PE 0x100F9A80 allocates 0x1C-byte sentinels, with tree flags +// at +0x18/+0x19. Flush (0x100F8C00) reads a geometry receiver at node +0x14. +// [CHOSEN, not recovered] Unobservable-type exception (AGENTS.md): the key and the word at node +// +0x10 are read by no instruction, and nothing inserts into either tree in 1.50 (_r flush +// 0x102311F0 and its erase helpers interpret no value), so the walk only ever sees empty trees. +// The key type and the word's name are chosen; only the geometry pointer at +0x14 is proven. +struct ObjectDrawerTreeValue { - void* comp; // +0x00 never written by the constructor - void* head; // +0x04 the sentinel; all three of ITS links point at itself - unsigned int size; // +0x08 0 + unsigned int word10; // node +0x10, never read + void* geometry; // node +0x14, the IGeometry the flush dispatches (+0x18) }; +typedef std::map ObjectDrawerTree; // ObjectManager fills these vectors by reference; their layout must match the host STL. // Compatibility builds use the VC7.1 allocator-prefixed layout. -#if BF2_PLUGIN_ABI_NATIVE typedef std::vector< ::dice::hfe::world::IObject*> ObjectDrawerSet; -#else -typedef vc71::vector_layout ObjectDrawerSet; -#endif class ObjectDrawer { @@ -74,9 +75,13 @@ class ObjectDrawer void draw(float time); void updateVisible(float time); // +0x14 // Submits the deferred geometry pass under the same frame gate as visibility and drawing. - void slot_0x18(); - void slot_0x1C(); // 0x100F8DE0, 324 B [FRONTIER] - void slot_0x20(void* object); // 0x100F8F30, 51 B [FRONTIER] + void slot_0x18(float time); // +0x18; time is unused by the shipped body + void slot_0x1C(); // 0x100F8DE0 + void slot_0x20(void* object); // 0x100F8F30; object must be non-null + // Draws and submits an object and its children recursively; the root must be non-null. + void submitObjectTree(world::IObject* object); + // Submits every geometry of the first tree forward and the second backward, then clears both. + void flushDeferredGeometry(); // +0x38, 0x100F8220, 520 B. is this geometry hidden // behind one of the occluders at +0x50? The OverGrowth draw is its one recovered caller. bool isGeometryOccluded(void* geometry); @@ -95,16 +100,15 @@ class ObjectDrawer unsigned char m_updateVisibleHasRun; // +0x0D ctor 0; updateVisible sets it unsigned char m_byte0E; // +0x0E ctor 0 unsigned char m_pad0F; - ObjectDrawerTreeHeader m_tree10; // +0x10 - ObjectDrawerTreeHeader m_tree1C; // +0x1C + ObjectDrawerTree m_tree10; // +0x10 + ObjectDrawerTree m_tree1C; // +0x1C void* m_renderView; // +0x28 ctor 0; slot +0x28 writes it IBase* m_occluder; // +0x2C ctor 0; refcounted, slot +0x30 ObjectDrawerSet m_visibleSet; // +0x30 getObjectVector(0) ObjectDrawerSet m_drawSet; // +0x40 getObjectVector(non-zero) - // +0x50 - owned occlusion volumes: fixed-layout vectors of Plane3, rebuilt each enabled - // visibility update and read by object, geometry and bounds tests. Unlike the two object - // sets above it is never handed to the host, so it retains the fixed layout internally. - vc71::vector_layout m_vector50; // +0x50 + // +0x50 - owned occlusion volumes: one plane list per occluder, rebuilt each enabled + // visibility update and read by object, geometry and bounds tests. Never handed to the host. + std::vector > m_vector50; // +0x50 unsigned char m_byte60; // +0x60 ctor 1 unsigned char m_pad61[3]; float m_float64; // +0x64 ctor 60.0f (0x42700000) @@ -126,10 +130,6 @@ class ObjectDrawer // native flavour the two object sets are the host's own twelve-byte std::vector and the object is // correspondingly smaller, which is correct rather than a drift: nothing outside this DLL indexes // an ObjectDrawer by offset. Its own factory allocates sizeof(ObjectDrawer). -#if defined(_M_IX86) && !BF2_PLUGIN_ABI_NATIVE -static_assert(sizeof(ObjectDrawer) == 0x8C, - "the factory at 0x100B0ADE allocates 0x8C for dice.hfe.geom.ObjectDrawer"); -#endif // RefFactory_geom_ObjectDrawer, 0x100B0ADE. registered in ModuleGeom - see the header note. IBase* __fastcall createObjectDrawer(unsigned int iid, IBase* outer); diff --git a/Code/BF2/Geom/ObjectGeometryConsole.cpp b/Code/BF2/Geom/ObjectGeometryConsole.cpp index 0cf027862..4eebd79f8 100644 --- a/Code/BF2/Geom/ObjectGeometryConsole.cpp +++ b/Code/BF2/Geom/ObjectGeometryConsole.cpp @@ -5,18 +5,21 @@ #ifdef BF2_IMAGE_RENDDX9 #include "../../RendDX9Abi/PluginAbi.h" -#if BF2_PLUGIN_ABI_NATIVE #include "MeshTemplate.h" // IGeometryTemplate (getClassId, +0x10) #include "RoadCompiled.h" #include "RoadCompiledTemplate.h" // CID_RoadCompiledTemplate +#include "ObjectDrawer.h" // the ObjectDrawer console's fields +#include #include "../../RendDX9Abi/HfeAbi.h" #include "../../RendDX9Abi/PluginEntry.h" -#include "../../RendDX9Abi/Vc71String.h" +#include +#include #include "../Core/ConsoleObjectMacro.h" #include "../Core/ConsoleObjects.h" #include "../Game/Objects/IObject.h" +#include "../Game/Objects/GeometryPartAccess.h" #include "../Scene/Object/ObjectManager.h" #include @@ -25,6 +28,7 @@ namespace dice { namespace hfe { extern IBase* objectManager; // PluginEntry.cpp +namespace dx9rend { extern IBase* g_ObjectDrawer; } // BF2Render.cpp - dword_1025A39C namespace geom { @@ -42,6 +46,7 @@ const unsigned int kIID_IGeometry = 0x492FE0FEu; // the active object's IGeometry component, shared by all six rows: the host // ObjectManager (tested), its active object (+0x90, tested), then queryComponent(IID_IGeometry, // IID_IGeometry) (+0x58). +// PE 0x100B1149 IBase* activeObjectGeometry() { world::ObjectManager* const manager = @@ -54,25 +59,72 @@ IBase* activeObjectGeometry() return object->queryComponent(kIID_IGeometry, kIID_IGeometry); // +0x58 } +// PE 0x100B4362 / 0x100B469A: these slots return a borrowed template and an integer. +IGeometryTemplate* getObjectGeometryTemplate() +{ + IBase* const geometry = activeObjectGeometry(); + return static_cast(world::geometry_part::getTemplate(geometry)); +} + +int getObjectSubGeometryCount() +{ + IBase* const geometry = activeObjectGeometry(); + return world::geometry_part::getSubgeomCount(geometry); +} + +// PE 0x100B45F8: the geometry is reacquired separately for each execution. +int getObjectSubGeometry() +{ + IBase* const geometry = activeObjectGeometry(); + return world::geometry_part::getSubgeom(geometry); +} + +void setObjectSubGeometry(int value) +{ + IBase* const geometry = activeObjectGeometry(); + world::geometry_part::setSubgeom(geometry, value); +} + +// PE 0x100B131F: template values print their name, not their address. +std::string objectGeometryValueText(IGeometryTemplate* value) +{ + std::ostringstream out; + if (value) + out << value->getName(); + else + out << "No geometry template"; + return out.str(); +} + +std::string objectGeometryValueText(int value) +{ + std::ostringstream out; + out << value; + return out.str(); +} + // that geometry as a RoadCompiled: only when its template (IGeometry +0x38) is a // GeometryTemplate.RoadCompiled (getClassId +0x10 against the reflection id, read as data). The -// component is the IGeometry subobject, so the object is 4 bytes lower (`lea eax, [esi-4]`). +// component is the IGeometry subobject, so the object is that member's offset lower (retail 4 +// bytes, `lea eax, [esi-4]`). // IGeometry has no typed interface in this tree; +0x38 is dispatched through the component's own // table, as XpLightManager.cpp and ObjectDrawer.cpp do. +// PE 0x100B12F0 RoadCompiled* activeRoadCompiled() { IBase* const geometry = activeObjectGeometry(); if (!geometry) return 0; - typedef IGeometryTemplate* (__fastcall* GetTemplateFn)(void*, void*); + typedef IGeometryTemplate* (__thiscall* GetTemplateFn)(void*); IGeometryTemplate* const tmpl = reinterpret_cast( - (*reinterpret_cast(geometry))[0x38 / sizeof(void*)])(geometry, 0); + (*reinterpret_cast(geometry))[0x38 / 4])(geometry); if (!tmpl) return 0; if (tmpl->getClassId() != CID_RoadCompiledTemplate) return 0; - return reinterpret_cast(reinterpret_cast(geometry) - 4); + return reinterpret_cast(reinterpret_cast(geometry) + - offsetof(RoadCompiled, m_geometry)); } // geometry.GenerateLightmapForThisInstance: the active object's geometry flag behind IGeometry @@ -83,7 +135,7 @@ bool getGenerateLightmapForThisInstance() IBase* const geometry = activeObjectGeometry(); typedef bool (__thiscall* GetFn)(void*); return reinterpret_cast( - (*reinterpret_cast(geometry))[0xBC / sizeof(void*)])(geometry); + (*reinterpret_cast(geometry))[0xBC / 4])(geometry); } void setGenerateLightmapForThisInstance(bool value) @@ -91,7 +143,7 @@ void setGenerateLightmapForThisInstance(bool value) IBase* const geometry = activeObjectGeometry(); typedef void (__thiscall* SetFn)(void*, bool); reinterpret_cast( - (*reinterpret_cast(geometry))[0xB8 / sizeof(void*)])(geometry, value); + (*reinterpret_cast(geometry))[0xB8 / 4])(geometry, value); } } // anonymous namespace @@ -99,8 +151,107 @@ void setGenerateLightmapForThisInstance(bool value) // `SetConsoleClassDefaults("Object", 2, 0)` - stored as "object", which is how the .con files spell it. BF2_CONSOLE_OBJECT("Object", 2, 0) +// Read-only rows carry type 2 and accept exactly zero arguments. +#define BF2_OBJECT_GEOMETRY_READONLY_ROW(nameLiteral, T, getter) \ +namespace { \ +class BF2_CC_NAME : public ConsoleObjectBaseImpl \ +{ \ + BF2_CC_HEAD_NAMED(nameLiteral, 2, 0, 0, #T, true) \ + BF2_CC_TAIL(0, kObjectGeometryConsoleTag) \ + virtual bool isObjectActive() const { return activeObjectGeometry() != 0; } \ + virtual void executeObjectMethod() \ + { \ + if (m_argCount == 0) \ + { \ + m_hasReturnValue = true; \ + m_returnValue = getter(); \ + } \ + } \ + virtual void setArgFromString(int, const std::string&) {} \ + virtual std::string getReturnValueAsString() const \ + { \ + return m_hasReturnValue ? objectGeometryValueText(m_returnValue) \ + : std::string(); \ + } \ + BF2_CC_COMMON_HOOKS \ +private: \ + T m_returnValue; \ +}; \ +static BF2_CC_NAME BF2_CC_INSTANCE; \ +} + +// PE 0x100B4301 / 0x100B4362, first in the shipped Object.geometry group. +BF2_OBJECT_GEOMETRY_READONLY_ROW("geometry.template", IGeometryTemplate*, getObjectGeometryTemplate) + +namespace { + +// PE 0x100B43E6 / 0x100B4466: setter-only type 3, with string return metadata. +class ObjectGeometryTechniqueBinding : public ConsoleObjectBaseImpl +{ +public: + // PE 0x100B43E6 + ObjectGeometryTechniqueBinding() + { + m_objectName = consoleDefaultName(); + m_access = consoleDefaultAccess(); + m_category = consoleDefaultCategory(); + m_functionName = "geometry.technique"; + m_type = 3; + m_minNoArgs = m_maxNoArgs = 1; + m_returnType = "std::string"; + m_hasReturnValue = false; + m_isDynamic = true; + m_argTypes[0] = "std::string"; + m_argNeedsConversion[0] = 0; + consoleBindingList(kObjectGeometryConsoleTag).push_back(this); + } + virtual bool isObjectActive() const { return activeObjectGeometry() != 0; } + // PE 0x100B4466 + virtual void executeObjectMethod() + { + if (m_argCount != 1) + return; + const std::string value(BF2_CC_ARG(std::string, 0)); + m_hasReturnValue = false; + IBase* const geometry = activeObjectGeometry(); + typedef void (__thiscall* Fn)(void*, const std::string&); +#if defined(_MSC_VER) + reinterpret_cast((*reinterpret_cast(geometry))[0x68 / 4])(geometry, value); +#elif defined(BF2_STATIC_PLUGINS) + // [CHOSEN, not recovered] Native explicit tables keep the proven PE ordinal. + // The ELF selector is unused in this guarded arm; no ELF +0x68 contract is claimed. + world::geometry_part::slot(geometry, 0x68, 0)(geometry, value); +#else +#error Object.geometry.technique requires an attested geometry table provider +#endif + } + // PE 0x100B44C5 + virtual void setArgFromString(int index, const std::string& value) + { + BF2_CC_CONVERT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; + +ObjectGeometryTechniqueBinding s_objectGeometryTechniqueBinding; + +} // anonymous namespace + +// PE 0x100B453A / 0x100B45F8, then PE 0x100B4645 / 0x100B469A. +// PE 0x100B45AB +BF2_CONSOLE_PROPERTY_FN_NAMED("geometry.subGeometry", int, activeObjectGeometry() != 0, + getObjectSubGeometry(), setObjectSubGeometry, + kObjectGeometryConsoleTag) +// PE 0x100B4645 +BF2_OBJECT_GEOMETRY_READONLY_ROW("geometry.subGeometryCount", int, getObjectSubGeometryCount) +#undef BF2_OBJECT_GEOMETRY_READONLY_ROW + // Object.geometry.GenerateLightmapForThisInstance - a bool property, active while the active object // has a geometry. Registered ahead of geometry.loadMesh, its neighbour in the shipped list. +// PE 0x100B46C6, 0x100B4784, 0x100B4737 BF2_CONSOLE_PROPERTY_FN_NAMED("geometry.GenerateLightmapForThisInstance", bool, activeObjectGeometry() != 0, getGenerateLightmapForThisInstance(), setGenerateLightmapForThisInstance, kObjectGeometryConsoleTag) @@ -119,7 +270,7 @@ class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl virtual void executeObjectMethod() \ { \ if (m_argCount != 1) return; \ - const vc71::string copy(BF2_CC_ARG(std::string, 0).c_str()); \ + const std::string copy(BF2_CC_ARG(std::string, 0).c_str()); \ m_hasReturnValue = false; \ activeRoadCompiled()->loadMesh(copy); \ } \ @@ -133,9 +284,64 @@ class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl static BF2_CC_NAME BF2_CC_INSTANCE; \ } +// PE 0x100B47DF, 0x100B489C, 0x100B485C BF2_OBJECT_GEOMETRY_LOADMESH_ROW("geometry.loadMesh", kObjectGeometryConsoleTag) #undef BF2_OBJECT_GEOMETRY_LOADMESH_ROW +namespace { + +// The ObjectDrawer console object (ctors 0x100B4911 .. 0x100B4E0A), in the shipped order after +// the Object rows. Every row is active while the renderer's drawer exists (0x100B4982, +// dword_1025A39C) and its executor reads or stores one drawer field directly. +// [INFERRED] placement in this list: retail registers both objects through ModuleGeom. +ObjectDrawer* consoleObjectDrawer() +{ + return reinterpret_cast(static_cast(dx9rend::g_ObjectDrawer)); +} + +// useOcclusion +0x60 (0x100B49DB), collectPlanesDistance +0x64 (0x100B4AD6), useExactTest +0x68 +// (0x100B4BD4), faceForwardThreshold +0x6C as a float (0x100B4CCF), showCullStats +0x70 +// (0x100B4DCD), drawDebugPlanes +0x88 (0x100B4EC8). +bool getUseOcclusion() { return consoleObjectDrawer()->m_byte60 != 0; } +void setUseOcclusion(bool v) { consoleObjectDrawer()->m_byte60 = v; } +float getCollectPlanesDistance() { return consoleObjectDrawer()->m_float64; } +void setCollectPlanesDistance(float v) { consoleObjectDrawer()->m_float64 = v; } +bool getUseExactTest() { return consoleObjectDrawer()->m_byte68 != 0; } +void setUseExactTest(bool v) { consoleObjectDrawer()->m_byte68 = v; } +float getFaceForwardThreshold() +{ + float v; + ::memcpy(&v, &consoleObjectDrawer()->m_dword6C, sizeof(v)); + return v; +} +void setFaceForwardThreshold(float v) { ::memcpy(&consoleObjectDrawer()->m_dword6C, &v, sizeof(v)); } +bool getShowCullStats() { return consoleObjectDrawer()->m_byte70 != 0; } +void setShowCullStats(bool v) { consoleObjectDrawer()->m_byte70 = v; } +bool getDrawDebugPlanes() { return consoleObjectDrawer()->m_byte88 != 0; } +void setDrawDebugPlanes(bool v) { consoleObjectDrawer()->m_byte88 = v; } + +BF2_CONSOLE_OBJECT("ObjectDrawer", 2, 0) +// PE 0x100B498E +BF2_CONSOLE_PROPERTY_FN(useOcclusion, bool, dx9rend::g_ObjectDrawer != 0, + getUseOcclusion(), setUseOcclusion, kObjectGeometryConsoleTag) +// PE 0x100B4A18, 0x100B4A89 +BF2_CONSOLE_PROPERTY_FN(collectPlanesDistance, float, dx9rend::g_ObjectDrawer != 0, + getCollectPlanesDistance(), setCollectPlanesDistance, kObjectGeometryConsoleTag) +// PE 0x100B4B16, 0x100B4B87 +BF2_CONSOLE_PROPERTY_FN(useExactTest, bool, dx9rend::g_ObjectDrawer != 0, + getUseExactTest(), setUseExactTest, kObjectGeometryConsoleTag) +// PE 0x100B4C11, 0x100B4C82 +BF2_CONSOLE_PROPERTY_FN(faceForwardThreshold, float, dx9rend::g_ObjectDrawer != 0, + getFaceForwardThreshold(), setFaceForwardThreshold, kObjectGeometryConsoleTag) +// PE 0x100B4D0F, 0x100B4D80 +BF2_CONSOLE_PROPERTY_FN(showCullStats, bool, dx9rend::g_ObjectDrawer != 0, + getShowCullStats(), setShowCullStats, kObjectGeometryConsoleTag) +// PE 0x100B4E0A, 0x100B4E7B +BF2_CONSOLE_PROPERTY_FN(drawDebugPlanes, bool, dx9rend::g_ObjectDrawer != 0, + getDrawDebugPlanes(), setDrawDebugPlanes, kObjectGeometryConsoleTag) + +} // anonymous namespace + bool registerObjectGeometryConsoleObjects() { return mainConsoleObjects->registerConsoleObjects( @@ -152,5 +358,4 @@ bool unregisterObjectGeometryConsoleObjects() } // namespace hfe } // namespace dice -#endif // BF2_PLUGIN_ABI_NATIVE #endif // BF2_IMAGE_RENDDX9 diff --git a/Code/BF2/Geom/Overgrowth/OverGrowth.cpp b/Code/BF2/Geom/Overgrowth/OverGrowth.cpp index 326f550c4..0e6e80a7b 100644 --- a/Code/BF2/Geom/Overgrowth/OverGrowth.cpp +++ b/Code/BF2/Geom/Overgrowth/OverGrowth.cpp @@ -1,33 +1,29 @@ // Owns overgrowth geometry, resources, settings, and instance tables. #ifdef BF2_IMAGE_RENDDX9 +#if defined(__APPLE__) +#include "../../Platform/X87Compat.h" // [CHOSEN, not recovered] x87 conversion results, including invalid inputs. +#endif #include "OverGrowth.h" +#include "../../Core/StringUtil.h" // equalsIgnoreCase (sub_10075080) #include "OverGrowthCell.h" #include "../MeshTemplate.h" // IGeometryTemplate (load, createInstance) #include "../GeometryTemplateManager.h" // IGeometryTemplateManager, g_GeometryTemplateManager // XpLightManager.cpp's pattern: in the retail-ABI flavour HfeAbi.h already supplies IBase and the // class-registration records, so the engine headers' own copies are suppressed around their include. -#if !BF2_PLUGIN_ABI_NATIVE -#define CORE_IBASE_H -#define CORE_CLASSMANAGER_H -#endif #include "../../Game/Objects/IObjectTemplate.h" #include "../../Scene/Object/ObjectTypes/Base/ObjectTemplateManager.h" #include "../../Physics/HeightmapCluster.h" #include "../../Physics/Heightmap.h" -#if !BF2_PLUGIN_ABI_NATIVE -#undef CORE_CLASSMANAGER_H -#undef CORE_IBASE_H -#endif #include "../ITerrainEditable.h" // the painters' overlays (IID 820005) #include "../Terrain.h" // the "Terrain" singleton's patch size / count #include "../../RendDX9/Texture.h" // EngineTexture, textureReleaseRef (10014E20) +#include "../../RendDX9/RendDX9Base.h" // pathStripExtension (100753D0) #include "../../RendDX9/TextureAtlas/TextureAtlas.h" #include "../../../RendDX9Abi/BfMemory.h" #include "../../../RendDX9Abi/HfeAbi.h" #include "../../../RendDX9Abi/PluginAbi.h" #include "../../../RendDX9Abi/PluginEntry.h" // classManager -#include "../../../RendDX9Abi/Vc71String.h" -#include "../../../RendDX9Abi/Vc71Vector.h" +#include #include #include #include @@ -45,42 +41,30 @@ extern IBase* objectTemplateManager; namespace dice { namespace hfe { namespace geom { namespace { -template T& field(void* object, unsigned int offset) -{ return *reinterpret_cast(static_cast(object) + offset); } -template const T& field(const void* object, unsigned int offset) -{ return *reinterpret_cast(static_cast(object) + offset); } // The two owner tables and the two "active" cursors the console drives. -// +0x3C VC7.1 vector (first +0x40, last +0x44, end +0x48) -// +0x4C VC7.1 vector of 0xA0 geometry records (first +0x50, last +0x54, end +0x58) +// +0x3C vector +// +0x4C vector (0xA0-byte records in the PE) // +0xE8 OverGrowthMaterial* the active material (setActiveMaterial; addMaterial nulls it) // +0xEC OverGrowthType* the active type (setActiveType; OvergrowthType.* act on it) -OverGrowthVector& materialTable(void* self) -{ return field >(self, 0x3C); } -const OverGrowthVector& materialTable(const void* self) -{ return field >(self, 0x3C); } -OverGrowthMaterial*& activeMaterial(void* self) { return field(self, 0xE8); } -OverGrowthMaterial* activeMaterial(const void* self) { return field(self, 0xE8); } -OverGrowthType*& activeType(void* self) { return field(self, 0xEC); } -OverGrowthType* activeType(const void* self) { return field(self, 0xEC); } +std::vector& materialTable(OverGrowth* self) { return self->m_materials; } +const std::vector& materialTable(const OverGrowth* self) { return self->m_materials; } +OverGrowthMaterial*& activeMaterial(OverGrowth* self) { return self->m_activeMaterial; } +OverGrowthMaterial* activeMaterial(const OverGrowth* self) { return self->m_activeMaterial; } +OverGrowthType*& activeType(OverGrowth* self) { return self->m_activeType; } +OverGrowthType* activeType(const OverGrowth* self) { return self->m_activeType; } // std::operator==(const string&, const string&) from MSVCP71 - compare(): same length and the // same bytes (memcmp over the length). -bool sameString(const vc71::string& a, const vc71::string& b) +bool sameString(const std::string& a, const std::string& b) { return a.size() == b.size() && std::memcmp(a.c_str(), b.c_str(), a.size()) == 0; } -// sub_10075080 (fastcall, 63 B) - std::string equality through _stricmp on the two c_str()s. -bool equalsNoCase(const vc71::string& a, const vc71::string& b) -{ - return ::_stricmp(a.c_str(), b.c_str()) == 0; -} - // std::operator+(const string&, const char*) - VC7.1 inlines it as `copy the left, then +=`. -vc71::string concat(const vc71::string& left, const char* right) +std::string concat(const std::string& left, const char* right) { - vc71::string result(left); + std::string result(left); result += right; return result; } @@ -90,7 +74,7 @@ vc71::string concat(const vc71::string& left, const char* right) // shared 4096-byte buffer, a 0xFFF limit, and an overflow replaced by the fixed warning. char g_overGrowthFormatBuffer[0x1000]; -vc71::string overGrowthFormatString(const char* format, ...) +std::string overGrowthFormatString(const char* format, ...) { va_list args; va_start(args, format); @@ -102,7 +86,7 @@ vc71::string overGrowthFormatString(const char* format, ...) else ::sprintf(g_overGrowthFormatBuffer, "%s", "WARNING: The original message was too long for formatString(). \n"); - return vc71::string(g_overGrowthFormatBuffer); + return std::string(g_overGrowthFormatBuffer); } @@ -110,7 +94,7 @@ vc71::string overGrowthFormatString(const char* format, ...) // Geometry instances retain the same virtual order across host ABI flavors. inline void* geometrySlot(void* geometry, unsigned int offset) { - return (*reinterpret_cast(geometry))[offset / sizeof(void*)]; + return (*reinterpret_cast(geometry))[offset / 4]; } void geometryAddRef(void* geometry) // +0x00 { @@ -131,264 +115,267 @@ IGeometryTemplateManager* geometryTemplateManager() // ObjectTemplateManager PE +0x34. MSVC groups the five getTemplate overloads in reverse declaration // order at the first one's position, so +0x34 is getTemplate(const std::string&) - the one-argument // call 1015EBB8..1015EBC1 makes. A std::string crosses: typed native, raw retail slot otherwise. -world::IObjectTemplate* objectTemplateByName(const vc71::string& name) +world::IObjectTemplate* objectTemplateByName(const std::string& name) { -#if BF2_PLUGIN_ABI_NATIVE return reinterpret_cast(::dice::hfe::objectTemplateManager) ->getTemplate(renddx9abi::toHostString(name)); -#else - typedef world::IObjectTemplate* (__thiscall* GetTemplateFn)(void*, const vc71::string&); - void* const manager = ::dice::hfe::objectTemplateManager; - return reinterpret_cast((*static_cast(manager))[0x34 / 4])(manager, name); -#endif } +} // anonymous namespace + // sub_1015EB80 (123 B, read in full): members in declaration order (+0x1C, +0x30, +0x34, the vector, -// +0x4C = 1.0), the two count pairs in the body, then the two template lookups. NO null test on -// the geometry template before load()/createInstance() - shipped. -void geometryRecordConstruct(void* record, const vc71::string& name) -{ - ::new (&field(record, 0x00)) vc71::string(name); - field(record, 0x1C) = 0; - field(record, 0x30) = 0; - field(record, 0x34) = 0; - field(record, 0x40) = 0; - field(record, 0x44) = 0; - field(record, 0x48) = 0; - field(record, 0x4C) = 1.0f; - field(record, 0x20) = 0; - field(record, 0x24) = 0; - field(record, 0x28) = 0; - field(record, 0x2C) = 0; - - world::IObjectTemplate* const objectTemplate = - objectTemplateByName(field(record, 0x00)); - field(record, 0x30) = objectTemplate; - if (objectTemplate) - objectTemplate->preCache(); // IObjectTemplate +0x68 - - field(record, 0x34) = geometryTemplateManager()->getTemplate( - renddx9abi::toHostString(field(record, 0x00))); // +0x18 - field(record, 0x34)->load(); // +0x2C - field(record, 0x1C) = field(record, 0x34)->createInstance(); // +0x24 +// +0x4C = 1.0), the two count pairs in the body, then the two template lookups. +0x38 is not +// written. NO null test on the geometry template before load()/createInstance() - shipped. +OverGrowthGeometryRecord::OverGrowthGeometryRecord(const std::string& templateName) + : name(templateName), geometry(0), objectTemplate(0), geometryTemplate(0), pool(), + distanceScale(1.0f) +{ + vertexCounts[0] = 0; + vertexCounts[1] = 0; + indexCounts[0] = 0; + indexCounts[1] = 0; + + world::IObjectTemplate* const found = objectTemplateByName(name); + objectTemplate = found; + if (found) + found->preCache(); // IObjectTemplate +0x68 + + geometryTemplate = geometryTemplateManager()->getTemplate( + renddx9abi::toHostString(name)); // +0x18 + geometryTemplate->load(); // +0x2C + geometry = geometryTemplate->createInstance(); // +0x24 } // sub_1015EC70 (230 B, read in full): the copy constructor. The initializer list copies the // pointers, +0x38 and +0x4C (the vector starts empty); the body addRefs the geometry (its slot // +0x00, NO null test), copies the two count pairs, then pushes and addRefs every vector entry. -void geometryRecordCopy(void* record, const void* other) -{ - ::new (&field(record, 0x00)) vc71::string(field(other, 0x00)); - field(record, 0x1C) = field(other, 0x1C); - field(record, 0x30) = field(other, 0x30); - field(record, 0x34) = field(other, 0x34); - field(record, 0x38) = field(other, 0x38); - field(record, 0x40) = 0; - field(record, 0x44) = 0; - field(record, 0x48) = 0; - field(record, 0x4C) = field(other, 0x4C); - geometryAddRef(field(record, 0x1C)); - field(record, 0x20) = field(other, 0x20); - field(record, 0x24) = field(other, 0x24); - field(record, 0x28) = field(other, 0x28); - field(record, 0x2C) = field(other, 0x2C); - - const vc71::vector_layout& source = field(other, 0x3C); - vc71::vectorRef target(&field(record, 0x3C)); - for (unsigned int i = 0; i < vc71::vectorSizeIn(source, 4); ++i) +OverGrowthGeometryRecord::OverGrowthGeometryRecord(const OverGrowthGeometryRecord& other) + : name(other.name), geometry(other.geometry), objectTemplate(other.objectTemplate), + geometryTemplate(other.geometryTemplate), poolUsed(other.poolUsed), pool(), + distanceScale(other.distanceScale) +{ + geometryAddRef(geometry); + vertexCounts[0] = other.vertexCounts[0]; + vertexCounts[1] = other.vertexCounts[1]; + indexCounts[0] = other.indexCounts[0]; + indexCounts[1] = other.indexCounts[1]; + + for (unsigned int i = 0; i < other.pool.size(); ++i) { - void* const entry = reinterpret_cast(source.first)[i]; - target.push_back(entry); // 1009A340 when full + void* const entry = other.pool[i]; + pool.push_back(entry); // 1009A340 when full geometryAddRef(entry); // slot +0x00 } } -// sub_1015EC00 (101 B, read in full): release the geometry (slot +0x08, guarded), release every -// vector entry (slot +0x08, unguarded), free and zero the vector, destroy the name. -void geometryRecordDestroy(void* record) -{ - if (field(record, 0x1C)) - geometryRelease(field(record, 0x1C)); - vc71::vector_layout& entries = field(record, 0x3C); - for (unsigned int i = 0; i < vc71::vectorSizeIn(entries, 4); ++i) - geometryRelease(reinterpret_cast(entries.first)[i]); - if (entries.first) - ::renddx9abi::engineFree(entries.first); - entries.first = 0; - entries.last = 0; - entries.end = 0; - field(record, 0x00).~string(); -} - -// The 0xA0-byte vector element. Its copy (0x10160610: +0x00 then +0x50) and its destruction -// (0x10160640 / the range destroy 0x101607F0: +0x50 then +0x00) are the two records' own. -// [CHOSEN] carrier so vc71::vectorRef can copy/destroy raw records with their own bodies. -struct GeometryPair +// PE 0x1015ED60: the copy assignment, read in full. The name is assigned, then the geometry pointer is +// copied and addRef'd (slot +0x00, no null test), then +0x30, +0x34, +0x4C, +0x38 and the two count pairs; +// last every entry of the other pool is pushed and addRef'd. Shipped defects: the old geometry and the +// old pool entries are not released, and the pool is appended to, not replaced. The image's callers are +// the vector shift helpers 0x10160580 / 0x101605D0 (element copy_backward / copy); the native +// vector operations used here never shift elements, so nothing calls this. +OverGrowthGeometryRecord& OverGrowthGeometryRecord::operator=(const OverGrowthGeometryRecord& other) { - unsigned int words[0xA0 / 4]; - - unsigned char* bytes() { return reinterpret_cast(words); } - const unsigned char* bytes() const { return reinterpret_cast(words); } - - GeometryPair(const vc71::string& lodName, const vc71::string& name) - { - geometryRecordConstruct(bytes(), lodName); - geometryRecordConstruct(bytes() + 0x50, name); - } - GeometryPair(const GeometryPair& other) - { - geometryRecordCopy(bytes(), other.bytes()); - geometryRecordCopy(bytes() + 0x50, other.bytes() + 0x50); - } - ~GeometryPair() + name = other.name; + geometry = other.geometry; + geometryAddRef(geometry); + objectTemplate = other.objectTemplate; + geometryTemplate = other.geometryTemplate; + distanceScale = other.distanceScale; + poolUsed = other.poolUsed; + vertexCounts[0] = other.vertexCounts[0]; + vertexCounts[1] = other.vertexCounts[1]; + indexCounts[0] = other.indexCounts[0]; + indexCounts[1] = other.indexCounts[1]; + for (unsigned int i = 0; i < other.pool.size(); ++i) { - geometryRecordDestroy(bytes() + 0x50); - geometryRecordDestroy(bytes()); + void* const entry = other.pool[i]; + pool.push_back(entry); + geometryAddRef(entry); } + return *this; +} -private: - GeometryPair& operator=(const GeometryPair&); -}; -static_assert(sizeof(GeometryPair) == 0xA0, "10160BA0 divides by 0xA0"); - -// sub_101607F0 (47 B, read in full): destroy [first, last) of the geometry vector. -void destroyGeometryPairs(unsigned char* first, unsigned char* last) +// sub_1015EC00 (101 B, read in full): release the geometry (slot +0x08, guarded), release every +// vector entry (slot +0x08, unguarded); the vector and then the name are destroyed as members. +OverGrowthGeometryRecord::~OverGrowthGeometryRecord() { - for (; first != last; first += 0xA0) - reinterpret_cast(first)->~GeometryPair(); + if (geometry) + geometryRelease(geometry); + for (unsigned int i = 0; i < pool.size(); ++i) + geometryRelease(pool[i]); } -// Base cleanup (1015F9B0 / the base destructor 1015FA50): the geometry table (101607F0 + free, -// 1015F9E9..1015FA13) and then the material table (100D28B0 + free, each -// element's destructor tidies its type vector and then its name), each vector's three pointers zeroed. -void releaseTypeVectors(void* self) +namespace { + +// The table release of the base clear and the base destructor: the geometry table (101607F0, each +// pair destroyed +0x50 then +0x00) and then the material table (100D28B0, each element's destructor +// releases its type vector and then its name). +void releaseTypeVectors(OverGrowth* self) { - vc71::vector_layout& geometries = field(self, 0x4C); - if (geometries.first) - { - destroyGeometryPairs(reinterpret_cast(geometries.first), - reinterpret_cast(geometries.last)); - ::renddx9abi::engineFree(geometries.first); - } - geometries.first = 0; - geometries.last = 0; - geometries.end = 0; - overGrowthVectorTidy(materialTable(self)); + self->m_geometries.clear(); + materialTable(self).clear(); } -// the two array frees are unconditional, then each field is cleared in order. -void clearBase(void* self) +// PE 0x1015F9B0: the base clear. The two array frees are unconditional, then each field is cleared +// in order; the tables are released only outside a reload. +void clearBase(OverGrowth* self) { - ::renddx9abi::engineFree(field(self, 0x80)); - void* second = field(self, 0x84); - field(self, 0x80) = 0; + ::renddx9abi::engineFree(self->m_densityMap); + void* second = self->m_shadowMap; + self->m_densityMap = 0; ::renddx9abi::engineFree(second); - field(self, 0x84) = 0; - if (!field(self, 0xB0)) + self->m_shadowMap = 0; + if (!self->m_reloading) releaseTypeVectors(self); - field(self, 0x1E) = 0; + self->m_initialized = 0; +} + +// PE 0x1015FA50: the unpublished base class's destructor body - the base clear, then the tables' +// elements. The path and the tables' storage are released by the member destructors that follow +// ~OverGrowth, in the shipped order (path, geometries, materials). +void destroyBase(OverGrowth* self) +{ + clearBase(self); + releaseTypeVectors(self); } // sub_1015E5D0 (39 B) - the unpublished base class's setViewDistance (its own table 0x1021EBC0 holds // it at +0x0C); the derived +0x0C calls it directly. Store the distance, then the cell size: // distance / (grid / 2 - 1), the halving a signed `cdq; sub; sar 1` on the int at +0x10. -void baseSetViewDistance(void* self, float distance) +void baseSetViewDistance(OverGrowth* self, float distance) { - field(self, 0x24) = distance; - field(self, 0x14) = distance / static_cast(field(self, 0x10) / 2 - 1); + self->m_viewDistance = distance; + self->m_cellSize = distance / static_cast(self->m_gridSize / 2 - 1); } // sub_100D0550 (161 B, read in full), called with 3 by clear and setViewDistance: the vector -// deleting destructor. Elements are destroyed last TO first (the patch destructor is its vector's: -// free the buffer when set, zero first/last/end), then operator delete[] (1005F370) on the cookie. -// The scalar arm (flags without 2) is not reached by any caller. -void deletePatchArray(unsigned char* patches) +// deleting destructor. Elements are destroyed last TO first (the patch destructor is its vector's), +// then operator delete[] (1005F370) on the cookie. The scalar arm (flags without 2) is not reached +// by any caller. +void deletePatchArray(OverGrowthPatch* patches) { - const int count = *reinterpret_cast(patches - 4); - for (int i = count - 1; i >= 0; --i) - { - unsigned char* const patch = patches + i * 0x98; - if (field(patch, 0x10)) - ::renddx9abi::engineFree(field(patch, 0x10)); - field(patch, 0x10) = 0; - field(patch, 0x14) = 0; - field(patch, 0x18) = 0; - } - ::renddx9abi::engineFree(patches - 4); + delete[] patches; } } +// PE 0x1015F8F0, 0x100CB940: the unpublished base's constructor (0x1015F8F0, read in full), then the +// derived half (0x100CB940). OverGrowth::OverGrowth() { - // PE 1015F8F0, preserving untouched padding/fields rather than zeroing the whole object. - field(this, 0x04) = 0; - field(this, 0x08) = 0; - field(this, 0x0C) = 0; - field(this, 0x10) = 10; - field(this, 0x14) = 0; - field(this, 0x18) = 0x759DC150; - field(this, 0x1C) = 1; - field(this, 0x1D) = 0; - field(this, 0x1E) = 0; - field(this, 0x20) = 0.3f; - field(this, 0x24) = 0; - field(this, 0x30) = 0.4f; - field(this, 0x34) = 12.0f; - field(this, 0x38) = 0; - field(this, 0x28) = 1.0f; - field(this, 0x2C) = 1.0f; - const unsigned int zeroFields[] = { - 0x40, 0x44, 0x48, 0x50, 0x54, 0x58, 0x5C, 0x60, - 0x6C, 0x70, 0x74, 0x78, 0x7C, 0x80, 0x84 - }; - for (unsigned int offset : zeroFields) field(this, offset) = 0; - ::new (static_cast(static_cast(this)) + 0x88) vc71::string(); - field(this, 0x10) &= ~1u; - field(this, 0xA4) = 0; - field(this, 0xB0) = 0; - field(this, 0x24) = 80.0f; - - // PE 100CB940 derived half. The compiler supplies the complete 18-entry primary table. - const unsigned int derivedZeroFields[] = { - 0xB8, 0xBC, 0xC0, 0xD0, 0xE0, 0xE4, 0xE8, 0xEC - }; - for (unsigned int offset : derivedZeroFields) field(this, offset) = 0; - field(this, 0xF0) = 0; - field(this, 0xF1) = 0; - field(this, 0xF8) = 0; - field(this, 0xFC) = 0; - field(this, 0x100) = 0; - field(this, 0xC8) = 0.15f; - field(this, 0xCC) = 0.3f; - field(this, 0xD4) = 1; - field(this, 0xD5) = 1; - field(this, 0xF4) = 1.0f; - field(this, 0x10) = 10; - field(this, 0x24) = 500.0f; -} - + // Base half: preserves untouched padding/fields rather than zeroing the whole object. The + // three vectors and the path are empty-constructed as members. + m_cameraPosition.x = 0.0f; + m_cameraPosition.y = 0.0f; + m_cameraPosition.z = 0.0f; + m_gridSize = 10; + m_cellSize = 0.0f; + m_randomSeed = 0x759DC150; + m_enabled = 1; + m_unresolved1D = 0; + m_initialized = 0; + m_fadeBand = 0.3f; + m_viewDistance = 0.0f; + m_minimumHeightFade = 0.4f; + m_cellFadeDistance = 12.0f; + m_reseatCells = 0; + m_viewDistanceScale = 1.0f; + m_heightFadeDistance = 1.0f; + m_extentX = 0.0f; + m_extentZ = 0.0f; + m_patchOrigin.x = 0.0f; + m_patchOrigin.y = 0.0f; + m_patchOrigin.z = 0.0f; + m_mapWidth = 0; + m_mapHeight = 0; + m_densityMap = 0; + m_shadowMap = 0; + m_gridSize &= ~1; + m_loaded = 0; + m_reloading = 0; + m_viewDistance = 80.0f; + + // Derived half (PE 0x100CB940). The compiler supplies the complete 18-entry primary table. + m_unresolvedD0 = 0; + m_patches = 0; + m_cells = 0; + m_activeMaterial = 0; + m_activeType = 0; + m_editorEnable = 0; + m_unresolvedF1 = 0; + m_lodTimer = 0.0f; + m_atlas = 0; + m_atlasPage = 0; + m_closeDistPercentage = 0.15f; + m_closeDistFade = 0.3f; + m_drawNear = 1; + m_updateBeforeRender = 1; + m_qualityScale = 1.0f; + m_gridSize = 10; + m_viewDistance = 500.0f; +} + +// PE 0x100D2720, 0x100CB9E0: the scalar deleting destructor's body: clear (0x100CB6C0), the +0xB4 +// vector, then the base destructor (0x1015FA50), whose base clear runs a second time. 0x100CB9E0 is +// the same body without the deleting flag, reached by no code or data (unreachable in 1.50). OverGrowth::~OverGrowth() { - // PE 100D2720 -> 100CB6C0 -> 1015FA50. Base cleanup runs again before the string dtor. OverGrowth::clear(); - if (field(this, 0xB8)) ::renddx9abi::engineFree(field(this, 0xB8)); - field(this, 0xB8) = 0; - field(this, 0xBC) = 0; - field(this, 0xC0) = 0; - clearBase(this); - field(this, 0x88).~string(); - releaseTypeVectors(this); + m_unresolvedB4.clear(); + destroyBase(this); +} + +// PE 0x100CBFD7, 0x100CBFC0: unreachable in 1.50: no code or data references. True when the atlas +// exists and its names (textureAtlasCollectNames) equal the extension-stripped names of the given +// set, compared case-insensitively in both directions: every set member must be in the atlas, then +// every atlas name must be in the set. [CHOSEN, not recovered] name; the set is the retail +// std::set (nodes keyed at +0xC, head at +4 of the container). +bool OverGrowth::atlasMatchesTextureNames(const std::set& textures) +{ + if (!m_atlas) + return false; + std::vector atlasNames; + dx9rend::textureAtlasCollectNames(m_atlas, atlasNames); + + for (std::set::const_iterator it = textures.begin(); it != textures.end(); ++it) + { + unsigned int i = 0; + for (; i < atlasNames.size(); ++i) + { + std::string stripped; + dx9rend::pathStripExtension(stripped, *it); + if (equalsIgnoreCase(atlasNames[i], stripped)) + break; + } + if (i == atlasNames.size()) + return false; + } + for (unsigned int i = 0; i < atlasNames.size(); ++i) + { + std::set::const_iterator it = textures.begin(); + for (; it != textures.end(); ++it) + { + std::string stripped; + dx9rend::pathStripExtension(stripped, *it); + if (equalsIgnoreCase(atlasNames[i], stripped)) + break; + } + if (it == textures.end()) + return false; + } + return true; } void OverGrowth::operator delete(void* memory) noexcept { ::renddx9abi::engineFree(memory); } OverGrowth* createOverGrowth() { - void* memory = ::renddx9abi::engineAlloc(0x154); + void* memory = ::renddx9abi::engineAlloc(sizeof(OverGrowth)); return memory ? ::new (memory) OverGrowth() : 0; } +// PE 0x100CB6C0. // OverGrowth::clear - +0x30, PE 100CB6C0 (219 B), read in full. Every arm written: // 100CB6CC delete[] the patches (100D0550 with 3), +0xE0 = 0. // 100CB6D8 each non-null cell of the N x N grid (row z, column x) deleted through its table's @@ -396,37 +383,35 @@ OverGrowth* createOverGrowth() // 100CB741 the atlas owner: sub_10015930 then operator delete; +0xFC = 0. // 100CB75B the adopted page: `if (!--refCount) { sub_10014E20; operator delete }`, +0x100 = 0. // 100CB78A the base clear (1015F9B0), then +0xA4 = 0. - void OverGrowth::clear() { - if (field(this, 0xE0)) - deletePatchArray(field(this, 0xE0)); - field(this, 0xE0) = 0; - if (field(this, 0xE4)) + if (m_patches) + deletePatchArray(m_patches); + m_patches = 0; + if (m_cells) { - for (int z = 0; z < field(this, 0x10); ++z) + for (int z = 0; z < m_gridSize; ++z) { - for (int x = 0; x < field(this, 0x10); ++x) + for (int x = 0; x < m_gridSize; ++x) { - OverGrowthCell* const cell = - field(this, 0xE4)[field(this, 0x10) * z + x]; + OverGrowthCell* const cell = m_cells[m_gridSize * z + x]; if (cell) cell->destroy(1); } } - ::renddx9abi::engineFree(field(this, 0xE4)); - field(this, 0xE4) = 0; + ::renddx9abi::engineFree(m_cells); + m_cells = 0; } - if (dx9rend::TextureAtlas* const atlas = field(this, 0xFC)) + if (dx9rend::TextureAtlas* const atlas = m_atlas) { dx9rend::textureAtlasDtor(atlas); ::renddx9abi::engineFree(atlas); } - field(this, 0xFC) = 0; - if (field(this, 0x100)) - dx9rend::textureReleaseRef(field(this, 0x100)); + m_atlas = 0; + if (m_atlasPage) + dx9rend::textureReleaseRef(m_atlasPage); clearBase(this); - field(this, 0xA4) = 0; + m_loaded = 0; } @@ -435,31 +420,34 @@ void OverGrowth::clear() void OverGrowth::setViewDistance(float distance) { - if (field(this, 0xE0)) - deletePatchArray(field(this, 0xE0)); - field(this, 0xE0) = 0; + if (m_patches) + deletePatchArray(m_patches); + m_patches = 0; baseSetViewDistance(this, distance); - const float extentX = field(this, 0x5C); - const float extentZ = field(this, 0x60); + const float extentX = m_extentX; + const float extentZ = m_extentZ; const float extent = (extentX < extentZ) ? extentX : extentZ; if (extent == 0.0f) return; - const double cells = std::floor(static_cast(extent / field(this, 0x14))); + const double cells = std::floor(static_cast(extent / m_cellSize)); const float cellSize = extent / static_cast(cells); // 100CBAA8 fdivr - field(this, 0x14) = cellSize; // 100CBAAF fst + m_cellSize = cellSize; // 100CBAAF fst const float inverse = 1.0f / cellSize; // 100CBAB2 fdivr 1.0 - field(this, 0xD8) = - static_cast((field(this, 0x5C) * inverse + 1.0f) * 0.5f) * 2; - field(this, 0xDC) = - static_cast((field(this, 0x60) * inverse + 1.0f) * 0.5f) * 2; +#if defined(__APPLE__) + m_patchCountX = bf2x87::toIntTruncate((m_extentX * inverse + 1.0f) * 0.5f) * 2; + m_patchCountZ = bf2x87::toIntTruncate((m_extentZ * inverse + 1.0f) * 0.5f) * 2; +#else + m_patchCountX = static_cast((m_extentX * inverse + 1.0f) * 0.5f) * 2; + m_patchCountZ = static_cast((m_extentZ * inverse + 1.0f) * 0.5f) * 2; +#endif } -float OverGrowth::getViewDistance() const { return field(this, 0x24); } // +0x10 +float OverGrowth::getViewDistance() const { return m_viewDistance; } // +0x10 OverGrowthCell* OverGrowth::getCell(int x, int z) // +0x20 { - return field(this, 0xE4)[x + z * field(this, 0x10)]; + return m_cells[x + z * m_gridSize]; } @@ -471,44 +459,44 @@ OverGrowthCell* OverGrowth::getCell(int x, int z) void OverGrowth::reload() { - field(this, 0xB0) = 1; + m_reloading = 1; save(); clear(); // 100CDDD3 virtual +0x30 preLoad(); preLoadResources(); postLoadResources(); generateAtlas(); - field(this, 0xB0) = 0; + m_reloading = 0; } -// sub_1015F450 (407 B, retn 4, read in full): the index of `name` in the geometry table, matched on +// PE 0x1015F450, 0x1015F46E: the entry and its split continuation (407 B together, retn 4, read in full). +// The index of `name` in the geometry table, matched on // either record's name (+0x00 the "_lod" record, then +0x50); -1 for an empty name. A miss builds a // pair (the "_lod" record first, then the named one) and keeps it only when both got a geometry // instance (the named record tested first), answering the new last index; else -1. // Callers: initialize, preLoad, the static-object adoption, and populatePatch (+0x44, 100CC800). - -int OverGrowth::findOrAddGeometry(const vc71::string& name) +int OverGrowth::findOrAddGeometry(const std::string& name) { if (name.size() == 0) // [name+0x14] == 0 return -1; - vc71::vector_layout& geometries = field(this, 0x4C); - for (unsigned int i = 0; i < vc71::vectorSizeIn(geometries, 0xA0); ++i) + std::vector& geometries = m_geometries; + for (unsigned int i = 0; i < geometries.size(); ++i) { - const unsigned char* const pair = reinterpret_cast(geometries.first) + i * 0xA0; - if (sameString(field(pair, 0x00), name) || - sameString(field(pair, 0x50), name)) + const OverGrowthGeometryPair& pair = geometries[i]; + if (sameString(pair.lod.name, name) || + sameString(pair.full.name, name)) return static_cast(i); } - const vc71::string full(name); // var_20 - const vc71::string lod = concat(name, "_lod"); // var_3C - const GeometryPair pair(lod, full); // var_F8 / var_A8 + const std::string full(name); // var_20 + const std::string lod = concat(name, "_lod"); // var_3C + const OverGrowthGeometryPair pair(lod, full); // var_F8 / var_A8 int index = -1; - if (field(pair.bytes(), 0x50 + 0x1C) && field(pair.bytes(), 0x1C)) + if (pair.full.geometry && pair.lod.geometry) { - vc71::vectorRef(&geometries).push_back(pair); - index = static_cast(vc71::vectorSizeIn(geometries, 0xA0)) - 1; + geometries.push_back(pair); + index = static_cast(geometries.size()) - 1; } return index; } @@ -516,6 +504,7 @@ int OverGrowth::findOrAddGeometry(const vc71::string& name) // Default vegetation-type settings. Material selection is case-insensitive; type selection // is case-sensitive and may retain an active type from another material. +// PE 0x1015E9A0 OverGrowthType::OverGrowthType() : name(), geometry(), probability(1.0f), density(0.0f), rotationScale(0.0f), minRadiusToSame(0.0f), minRadiusToOthers(0.0f), normalScale(1.0f), geometryIndex(-1) @@ -524,40 +513,13 @@ OverGrowthType::OverGrowthType() randomScale.y = 1.0f; } -// addMaterial's temporary (100CDFA0..): the name default-constructed and the three type-vector -// pointers zeroed. [CHOSEN, not recovered] the id: retail leaves the temporary's +0x1C unwritten -// (it is overwritten the moment the record lands in the table), and the allocator padding - both -// are zeroed here so no copy reads an indeterminate value. +// addMaterial's temporary (100CDFA0..): the name default-constructed and the type vector empty. +// [CHOSEN, not recovered] the id: retail leaves the temporary's +0x1C unwritten (it is overwritten +// the moment the record lands in the table); it is zeroed here so no copy reads an indeterminate +// value. OverGrowthMaterial::OverGrowthMaterial() - : name(), id(0) -{ - types.allocator = 0; - types.first = 0; - types.last = 0; - types.end = 0; -} - -// Inlined at every by-value copy (100CDE20..100CDE3A, 100CDF00..): the string, +0x1C, then the -// type vector's copy constructor 100D0600. -OverGrowthMaterial::OverGrowthMaterial(const OverGrowthMaterial& other) - : name(other.name), id(other.id) + : name(), id(0), types() { - overGrowthVectorCopyConstruct(types, other.types); -} - -// 100D1A70's element body (the erase copy-down): string =, +0x1C, then 100D0AE0. -OverGrowthMaterial& OverGrowthMaterial::operator=(const OverGrowthMaterial& other) -{ - name = other.name; - id = other.id; - overGrowthVectorAssign(types, other.types); - return *this; -} - -// 100D28B0's element body: the type vector's _Tidy, then the name. -OverGrowthMaterial::~OverGrowthMaterial() -{ - overGrowthVectorTidy(types); } // Overgrowth.path @@ -565,25 +527,26 @@ OverGrowthMaterial::~OverGrowthMaterial() // 100C92C0 (12 B): `add ecx, 88h; jmp std::string::operator=` - the only writer of +0x88 in the // image (its one caller is the path executor 100C5407). A non-empty +0x88 is what opens // preLoadResources / postLoadResources / render / updateCells (their +0x9C size tests). -void OverGrowth::setPath(const vc71::string& path) +void OverGrowth::setPath(const std::string& path) { - field(this, 0x88) = path; + m_path = path; } // 100C92D0 (7 B): `lea eax, [ecx+88h]; retn`. -const vc71::string& OverGrowth::getPath() const +const std::string& OverGrowth::getPath() const { - return field(this, 0x88); + return m_path; } // the material table +// PE 0x100C9E40. // every material as " []", backslash-separated, in table order. -vc71::string OverGrowth::getMaterialList() const +std::string OverGrowth::getMaterialList() const { - vc71::string list; - const OverGrowthVector& materials = materialTable(this); - for (const OverGrowthMaterial* it = materials.first; it != materials.last; ++it) + std::string list; + const std::vector& materials = materialTable(this); + for (const OverGrowthMaterial* it = materials.data(); it != materials.data() + materials.size(); ++it) { if (list.size()) list += "\\"; @@ -595,18 +558,18 @@ vc71::string OverGrowth::getMaterialList() const // 100CDEE0 (365 B), read in full. A duplicate ID answers false (the name is not compared). A new // record is a default-constructed temporary pushed at the end (100D2D90); then ITS id is written, // then its name, and both cursors are cleared. -bool OverGrowth::addMaterial(const vc71::string& name, unsigned int id) +bool OverGrowth::addMaterial(const std::string& name, unsigned int id) { - OverGrowthVector& materials = materialTable(this); - for (OverGrowthMaterial* it = materials.first; it != materials.last; ++it) + std::vector& materials = materialTable(this); + for (OverGrowthMaterial* it = materials.data(); it != materials.data() + materials.size(); ++it) { const OverGrowthMaterial material(*it); // by value, as shipped if (id == material.id) return false; } - overGrowthVectorPushBack(materials, OverGrowthMaterial()); - OverGrowthMaterial& added = materials.last[-1]; // `[this+44h] - 30h` + materials.push_back(OverGrowthMaterial()); + OverGrowthMaterial& added = materials.back(); // `[this+44h] - 30h` added.id = id; // +0x1C first, added.name = name; // then the name activeMaterial(this) = 0; // +0xE8 @@ -615,20 +578,20 @@ bool OverGrowth::addMaterial(const vc71::string& name, unsigned int id) } // 100CDE00 (210 B), read in full. Only the active material can be removed. Its types are cleared -// (VC7.1 clear() == _Tidy, 100CFE80) before the erase copies the tail down over it (100D1A70), -// destroys the last record (100D28B0) and shortens the table; both cursors are then cleared. +// (100CFE80) before the erase moves the tail down over it (100D1A70), destroys the last record +// (100D28B0) and shortens the table; both cursors are then cleared. bool OverGrowth::removeActiveMaterial() { if (!activeMaterial(this)) return false; - OverGrowthVector& materials = materialTable(this); - for (OverGrowthMaterial* it = materials.first; it != materials.last; ++it) + std::vector& materials = materialTable(this); + for (OverGrowthMaterial* it = materials.data(); it != materials.data() + materials.size(); ++it) { const OverGrowthMaterial material(*it); // by value, as shipped if (activeMaterial(this) == it) { - overGrowthVectorTidy(activeMaterial(this)->types); - overGrowthVectorErase(materials, it); + activeMaterial(this)->types.clear(); + materials.erase(materials.begin() + (it - materials.data())); activeType(this) = 0; activeMaterial(this) = 0; return true; @@ -639,12 +602,13 @@ bool OverGrowth::removeActiveMaterial() // the first material whose name matches case-INsensitively becomes active. A miss // changes nothing, and the active type is never touched here. -void OverGrowth::setActiveMaterial(const vc71::string& name) +// PE 0x100C9EE0 +void OverGrowth::setActiveMaterial(const std::string& name) { - OverGrowthVector& materials = materialTable(this); - for (OverGrowthMaterial* it = materials.first; it != materials.last; ++it) + std::vector& materials = materialTable(this); + for (OverGrowthMaterial* it = materials.data(); it != materials.data() + materials.size(); ++it) { - if (equalsNoCase(it->name, name)) // 100C9EF5 sub_10075080 + if (equalsIgnoreCase(it->name, name)) // 100C9EF5 sub_10075080 { activeMaterial(this) = it; return; @@ -653,26 +617,28 @@ void OverGrowth::setActiveMaterial(const vc71::string& name) } // the active material's name, or "" (unk_101DC333) without one. -vc71::string OverGrowth::getActiveMaterialName() const +// PE 0x100C8A00 +std::string OverGrowth::getActiveMaterialName() const { const OverGrowthMaterial* const material = activeMaterial(this); if (material) return material->name; - return vc71::string(""); + return std::string(""); } // the active material's type table // the active material's type names ("%s"), backslash-separated; each record copied by // value first; the end re-read through +0xE8 every pass. -vc71::string OverGrowth::getTypeList() const +// PE 0x100C9F20 +std::string OverGrowth::getTypeList() const { - vc71::string list; + std::string list; const OverGrowthMaterial* const material = activeMaterial(this); if (material) { - for (const OverGrowthType* it = material->types.first; - it != activeMaterial(this)->types.last; ++it) + for (const OverGrowthType* it = material->types.data(); + it != activeMaterial(this)->types.data() + activeMaterial(this)->types.size(); ++it) { const OverGrowthType type(*it); // by value, as shipped if (list.size()) @@ -687,23 +653,23 @@ vc71::string OverGrowth::getTypeList() const // record is a default-constructed temporary pushed at the end (100D1950); its name AND geometry are // both set to the given name; then the previously active type is re-selected by its saved name // (an empty name when there was none, which setActiveType turns into "no active type"). -bool OverGrowth::addType(const vc71::string& name) +bool OverGrowth::addType(const std::string& name) { if (!activeMaterial(this)) return false; - for (OverGrowthType* it = activeMaterial(this)->types.first; - it != activeMaterial(this)->types.last; ++it) + for (OverGrowthType* it = activeMaterial(this)->types.data(); + it != activeMaterial(this)->types.data() + activeMaterial(this)->types.size(); ++it) { const OverGrowthType type(*it); // by value, as shipped if (sameString(type.name, name)) return false; } - vc71::string previous; + std::string previous; if (activeType(this)) previous = activeType(this)->name; - overGrowthVectorPushBack(activeMaterial(this)->types, OverGrowthType()); - OverGrowthType& added = activeMaterial(this)->types.last[-1]; // `[+0E8h]+28h - 5Ch` + activeMaterial(this)->types.push_back(OverGrowthType()); + OverGrowthType& added = activeMaterial(this)->types.back(); // `[+0E8h]+28h - 5Ch` added.name = name; added.geometry = name; setActiveType(previous); @@ -718,13 +684,14 @@ bool OverGrowth::removeActiveType() return false; if (!activeType(this)) return false; - for (OverGrowthType* it = activeMaterial(this)->types.first; - it != activeMaterial(this)->types.last; ++it) + for (OverGrowthType* it = activeMaterial(this)->types.data(); + it != activeMaterial(this)->types.data() + activeMaterial(this)->types.size(); ++it) { const OverGrowthType type(*it); if (activeType(this) == it) { - overGrowthVectorErase(activeMaterial(this)->types, it); + std::vector& types = activeMaterial(this)->types; + types.erase(types.begin() + (it - types.data())); activeType(this) = 0; return true; } @@ -734,13 +701,13 @@ bool OverGrowth::removeActiveType() // 100CA050 (215 B), read in full. The first type of the active material whose name matches // (case-sensitive) becomes active; no active material, or a miss, nulls the active type. -void OverGrowth::setActiveType(const vc71::string& name) +void OverGrowth::setActiveType(const std::string& name) { OverGrowthMaterial* const material = activeMaterial(this); if (material) { - for (OverGrowthType* it = material->types.first; - it != activeMaterial(this)->types.last; ++it) + for (OverGrowthType* it = material->types.data(); + it != activeMaterial(this)->types.data() + activeMaterial(this)->types.size(); ++it) { const OverGrowthType type(*it); // by value, as shipped if (sameString(type.name, name)) @@ -758,92 +725,104 @@ void OverGrowth::setActiveType(const vc71::string& name) // live regeneration, armed only once postLoadResources has set +0xA4 (100CD7AA). Every getter // without an active type answers 0.0f (flt_101DDE64), "" or (1, 1). -void OverGrowth::setTypeGeometry(const vc71::string& geometry) +// PE 0x100C8A40 +void OverGrowth::setTypeGeometry(const std::string& geometry) { OverGrowthType* const type = activeType(this); if (!type) return; type->geometry = geometry; - if (field(this, 0xA4)) + if (m_loaded) reload(); } -vc71::string OverGrowth::getTypeGeometry() const +// PE 0x100C8A70 +std::string OverGrowth::getTypeGeometry() const { const OverGrowthType* const type = activeType(this); if (type) return type->geometry; - return vc71::string(""); + return std::string(""); } +// PE 0x100C8AB0 void OverGrowth::setTypeDensity(float value) { OverGrowthType* const type = activeType(this); if (!type) return; type->density = value; - if (field(this, 0xA4)) + if (m_loaded) reload(); } +// PE 0x100C8AE0 float OverGrowth::getTypeDensity() const { const OverGrowthType* const type = activeType(this); return type ? type->density : 0.0f; } +// PE 0x100C8B00 void OverGrowth::setTypeNormalScale(float value) { OverGrowthType* const type = activeType(this); if (!type) return; type->normalScale = value; - if (field(this, 0xA4)) + if (m_loaded) reload(); } +// PE 0x100C8B30 float OverGrowth::getTypeNormalScale() const { const OverGrowthType* const type = activeType(this); return type ? type->normalScale : 0.0f; } +// PE 0x100C8B50 void OverGrowth::setTypeRotationScale(float value) { OverGrowthType* const type = activeType(this); if (!type) return; type->rotationScale = value; - if (field(this, 0xA4)) + if (m_loaded) reload(); } +// PE 0x100C8B80 float OverGrowth::getTypeRotationScale() const { const OverGrowthType* const type = activeType(this); return type ? type->rotationScale : 0.0f; } +// PE 0x100C8BA0 void OverGrowth::setTypeMinRadiusToSame(float value) { OverGrowthType* const type = activeType(this); if (!type) return; type->minRadiusToSame = value; - if (field(this, 0xA4)) + if (m_loaded) reload(); } +// PE 0x100C8BD0 float OverGrowth::getTypeMinRadiusToSame() const { const OverGrowthType* const type = activeType(this); return type ? type->minRadiusToSame : 0.0f; } +// PE 0x100C8BF0 void OverGrowth::setTypeMinRadiusToOthers(float value) { OverGrowthType* const type = activeType(this); if (!type) return; type->minRadiusToOthers = value; - if (field(this, 0xA4)) + if (m_loaded) reload(); } +// PE 0x100C8C20 float OverGrowth::getTypeMinRadiusToOthers() const { const OverGrowthType* const type = activeType(this); @@ -857,9 +836,10 @@ void OverGrowth::setTypeRandomScale(Vec2 value) // 10 return; type->randomScale.x = value.x; // +0x44 type->randomScale.y = value.y; // +0x48 - if (field(this, 0xA4)) + if (m_loaded) reload(); } +// PE 0x100C9640 Vec2 OverGrowth::getTypeRandomScale() const { const OverGrowthType* const type = activeType(this); @@ -873,46 +853,48 @@ Vec2 OverGrowth::getTypeRandomScale() const // plain fields and small accessors -float OverGrowth::getViewDistanceScale() const { return field(this, 0x28); } // exec 100C60A7 -void OverGrowth::setViewDistanceScale(float scale) { field(this, 0x28) = scale; } -float OverGrowth::getCloseDistPercentage() const { return field(this, 0xC8); } // exec 100C680A -void OverGrowth::setCloseDistPercentage(float value) { field(this, 0xC8) = value; } -float OverGrowth::getCloseDistFade() const { return field(this, 0xCC); } // exec 100C690E -void OverGrowth::setCloseDistFade(float value) { field(this, 0xCC) = value; } -float OverGrowth::getLodTimer() const { return field(this, 0xF8); } // exec 100C6A12 -void OverGrowth::setLodTimer(float value) { field(this, 0xF8) = value; } +float OverGrowth::getViewDistanceScale() const { return m_viewDistanceScale; } // exec 100C60A7 +void OverGrowth::setViewDistanceScale(float scale) { m_viewDistanceScale = scale; } +float OverGrowth::getCloseDistPercentage() const { return m_closeDistPercentage; } // exec 100C680A +void OverGrowth::setCloseDistPercentage(float value) { m_closeDistPercentage = value; } +float OverGrowth::getCloseDistFade() const { return m_closeDistFade; } // exec 100C690E +void OverGrowth::setCloseDistFade(float value) { m_closeDistFade = value; } +float OverGrowth::getLodTimer() const { return m_lodTimer; } // exec 100C6A12 +void OverGrowth::setLodTimer(float value) { m_lodTimer = value; } +float OverGrowth::getQualityScale() const { return m_qualityScale; } +void OverGrowth::setQualityScale(float scale) { m_qualityScale = scale; } // 100C8C40 (13 B) / the editor byte +0xF0. When set, preLoadResources skips the // isOvergrowth-object adoption (100CC683 -> 100CBC80), the atlas texture collection 100CC1F0 adds // those objects' "_lod" templates (100CC282), and rebuildCells branches on it (100CAF2A). -void OverGrowth::setEditorEnable(bool enable) { field(this, 0xF0) = enable; } -bool OverGrowth::getEditorEnable() const { return field(this, 0xF0) != 0; } +void OverGrowth::setEditorEnable(bool enable) { m_editorEnable = enable; } +// PE 0x100C8C50 +bool OverGrowth::getEditorEnable() const { return m_editorEnable != 0; } // 100C92E0 (16 B): +0xF4 (VideoOptions' scale) * +0xC8 (closeDistPercentage) * +0x24 (viewDistance), // multiplied left to right. float OverGrowth::getLodDistance() const { - return field(this, 0xF4) * field(this, 0xC8) * field(this, 0x24); + return m_qualityScale * m_closeDistPercentage * m_viewDistance; } // 100CDC20 (407 B), read in full: a std::set of every NON-empty type geometry name // over every material (index loops), then the set's names in order, backslash-separated. -vc71::string OverGrowth::getGeometryList() const +std::string OverGrowth::getGeometryList() const { std::set names; // 100CDC2A sub_100CE890 - const OverGrowthVector& materials = materialTable(this); - for (unsigned int m = 0; materials.first && m < overGrowthVectorSize(materials); ++m) + const std::vector& materials = materialTable(this); + for (unsigned int m = 0; m < materials.size(); ++m) { - const OverGrowthMaterial& material = materials.first[m]; - for (unsigned int t = 0; - material.types.first && t < overGrowthVectorSize(material.types); ++t) + const OverGrowthMaterial& material = materials[m]; + for (unsigned int t = 0; t < material.types.size(); ++t) { - const OverGrowthType& type = material.types.first[t]; + const OverGrowthType& type = material.types[t]; if (!type.geometry.empty()) // type +0x30, _Mysize names.insert(std::string(type.geometry.c_str(), type.geometry.size())); } } - vc71::string list; + std::string list; for (std::set::const_iterator it = names.begin(); it != names.end(); ++it) { if (list.size()) @@ -960,11 +942,16 @@ world::IHeightmapCluster* heightmapClusterByName() // UndergrowthSystemLoad.cpp seam; all three retire by typing the slot in HfeAbi.h. Terrain* terrainSingleton() { +#if defined(_MSC_VER) typedef void* (__thiscall* GetSingletonAsFn)(void*, const renddx9abi::HostString&, unsigned int); void* const manager = ::dice::hfe::classManager; return static_cast(static_cast(reinterpret_cast( (*reinterpret_cast(manager))[0x4C / 4])(manager, renddx9abi::HostString("Terrain"), kIID_ITerrain))); +#else + return static_cast(static_cast(::dice::hfe::classManager->getSingletonAs( + renddx9abi::HostString("Terrain"), kIID_ITerrain))); // typed (HfeAbi.h) +#endif } // The painters' distance terms, `fild a; fisub b` / `fild a; fsub [float b]` under RendDX9's 24-bit @@ -983,11 +970,11 @@ void OverGrowth::paintMaterial(float x, float z, float radius, unsigned char mat { if (material != 0) // `cmp byte ptr` { - const OverGrowthVector& materials = materialTable(this); + const std::vector& materials = materialTable(this); bool missing = true; - for (unsigned int i = 0; i < overGrowthVectorSize(materials); ++i) + for (unsigned int i = 0; i < materials.size(); ++i) { - if (materials.first[i].id == material) // movzx + if (materials[i].id == material) // movzx { missing = false; break; @@ -1004,9 +991,21 @@ void OverGrowth::paintMaterial(float x, float z, float radius, unsigned char mat const float gridX = x / heightmap->getScale().x + static_cast(sizeX / 2); // +0x54, three const float gridZ = z / heightmap->getScale().z + static_cast(sizeZ / 2); // calls, in const float gridRadius = radius / heightmap->getScale().x; // this order +#if defined(__APPLE__) + const int centreX = bf2x87::toIntTruncate(gridX); // fistp under a truncating control word +#else const int centreX = static_cast(gridX); // fistp under a truncating control word +#endif +#if defined(__APPLE__) + const int centreZ = bf2x87::toIntTruncate(gridZ); +#else const int centreZ = static_cast(gridZ); +#endif +#if defined(__APPLE__) + const int reach = bf2x87::toIntTruncate(gridRadius); // __ftol2 +#else const int reach = static_cast(gridRadius); // __ftol2 +#endif const int x0 = centreX - reach <= 0 ? 0 : centreX - reach; const int x1 = sizeX < centreX + reach ? sizeX : centreX + reach; const int z0 = centreZ - reach <= 0 ? 0 : centreZ - reach; @@ -1020,7 +1019,7 @@ void OverGrowth::paintMaterial(float x, float z, float radius, unsigned char mat { const float dz = differenceAsFloat(iz, centreZf); if (!(std::sqrt(dz * dz + dx2) > gridRadius)) // test ah, 41h - field(this, 0x80)[iz * sizeX + ix] = material; + m_densityMap[iz * sizeX + ix] = material; } } @@ -1042,9 +1041,21 @@ void OverGrowth::paintShadowmap(float x, float z, float radius, unsigned char va const float gridX = x / heightmap->getScale().x + static_cast(sizeX / 2); const float gridZ = z / heightmap->getScale().z + static_cast(sizeZ / 2); const float gridRadius = radius / heightmap->getScale().x; +#if defined(__APPLE__) + const int centreX = bf2x87::toIntTruncate(gridX); +#else const int centreX = static_cast(gridX); +#endif +#if defined(__APPLE__) + const int centreZ = bf2x87::toIntTruncate(gridZ); +#else const int centreZ = static_cast(gridZ); +#endif +#if defined(__APPLE__) + const int reach = bf2x87::toIntTruncate(gridRadius); +#else const int reach = static_cast(gridRadius); +#endif const int x0 = centreX - reach <= 0 ? 0 : centreX - reach; const int x1 = sizeX < centreX + reach ? sizeX : centreX + reach; const int z0 = centreZ - reach <= 0 ? 0 : centreZ - reach; @@ -1058,7 +1069,7 @@ void OverGrowth::paintShadowmap(float x, float z, float radius, unsigned char va { const float dz = differenceAsFloat(iz, centreZf); if (!(std::sqrt(dz * dz + dx2) > gridRadius)) - field(this, 0x84)[iz * sizeX + ix] = value; + m_shadowMap[iz * sizeX + ix] = value; } } @@ -1101,7 +1112,7 @@ void OverGrowth::exportMaterialRectToTerrainTexture(unsigned int x0, unsigned in static_cast(terrain->queryInterface(kIID_ITerrainEditable)); if (editable->getShaderTechnique() != 5) // E+0x8C return; - if (!field(this, 0x80)) + if (!m_densityMap) { editable->setShaderTechnique(0); // E+0x88 return; @@ -1139,7 +1150,7 @@ void OverGrowth::exportMaterialRectToTerrainTexture(unsigned int x0, unsigned in unsigned int* texel = column; for (unsigned int i = 0; i < patchSize; ++i, texel += patchSize) { - const unsigned int value = field(this, 0x80)[ + const unsigned int value = m_densityMap[ (texelZ + i) * static_cast(sizeX) + texelX + j + static_cast(g_materialOverlayIndexBias)]; *texel = value <= 15 ? kMaterialOverlayPalette[value] : value * 0x010101u; @@ -1161,7 +1172,7 @@ void OverGrowth::exportShadowmapRectToTerrainTexture(unsigned int x0, unsigned i static_cast(terrain->queryInterface(kIID_ITerrainEditable)); if (editable->getShaderTechnique() != 6) return; - if (!field(this, 0x84)) + if (!m_shadowMap) { editable->setShaderTechnique(0); return; @@ -1199,7 +1210,7 @@ void OverGrowth::exportShadowmapRectToTerrainTexture(unsigned int x0, unsigned i unsigned int* texel = column; for (unsigned int i = 0; i < patchSize; ++i, texel += patchSize) { - const unsigned int value = field(this, 0x84)[ + const unsigned int value = m_shadowMap[ (texelZ + i) * static_cast(sizeX) + texelX + j + static_cast(g_shadowOverlayIndexBias)]; *texel = value * 0x010101u; diff --git a/Code/BF2/Geom/Overgrowth/OverGrowth.h b/Code/BF2/Geom/Overgrowth/OverGrowth.h index c7ffd73a0..ce4dee596 100644 --- a/Code/BF2/Geom/Overgrowth/OverGrowth.h +++ b/Code/BF2/Geom/Overgrowth/OverGrowth.h @@ -1,198 +1,30 @@ // Vegetation resources, cell batching, near-instance rendering and shadow collection. -// Shared internal records retain compatibility offsets; console records use typed values. +// The owner, its tables and their records are native objects with std containers (issue #7); the +// `// +0xNN` comments keep the recovered retail offsets. #ifndef BF2_GEOM_OVERGROWTH_H #define BF2_GEOM_OVERGROWTH_H #ifdef BF2_IMAGE_RENDDX9 +#include "../../Math/Mat4.h" #include "../../Math/Vec3.h" -#include "../../../RendDX9Abi/Vc71String.h" // the records' 28-byte strings -#include "../../../RendDX9Abi/Vc71Vector.h" // engineAlloc/engineFree, +#include +#include +#include namespace dice { namespace hfe { -namespace dx9rend { class IRenderView; } +class Frustum; +namespace dx9rend { class IRenderView; struct EngineTexture; struct TextureAtlas; } +namespace world { class IHeightmap; class IHeightmapCluster; class IObjectTemplate; } namespace geom { using dx9rend::IRenderView; +class IGeometryTemplate; // [INFERRED] names for instruction-proven pointer carriers. These declarations do not claim -// recovered record members, STL element types beyond the observed strides, or source constness. +// recovered record members beyond the observed strides, or source constness. struct OverGrowthCell; // 0x2AC bytes, defined in OverGrowthCell.h (constructor 100D0C90) -struct OverGrowthPatch; // 0x98-byte entries at owner +0xE0 -struct OverGrowthInstance; // 0x60-byte entries -struct OverGrowthInstanceVector; // VC7.1 vector of the preceding entries -struct OverGrowthShadowVolumes; // vector of 0x498-byte records -struct OverGrowthShadowBounds; -struct OverGrowthShadowState; -struct OverGrowthGeometryVector; - - -// [CHOSEN, not recovered] Nonowning VC7.1 vector view for raw owner storage. -// Companion helpers construct/copy/destroy elements and manage buffers on the engine heap. - -template -struct OverGrowthVector -{ - void* allocator; // +0x00 std::allocator: empty, padded to 4 - never read by the image - T* first; // +0x04 _Myfirst - T* last; // +0x08 _Mylast - T* end; // +0x0C _Myend -}; - -template -inline unsigned int overGrowthVectorSize(const OverGrowthVector& v) -{ - return v.first ? static_cast(v.last - v.first) : 0u; -} - -template -inline unsigned int overGrowthVectorCapacity(const OverGrowthVector& v) -{ - return v.first ? static_cast(v.end - v.first) : 0u; -} - -// _Destroy(first, last) -template -inline void overGrowthDestroyRange(T* first, T* last) -{ - for (; first != last; ++first) - first->~T(); -} - -// _Ucopy(first, last, dest) - copy-construct into raw storage, answer the new end. -template -inline T* overGrowthUninitializedCopy(const T* first, const T* last, T* dest) -{ - for (; first != last; ++first, ++dest) - ::new (static_cast(dest)) T(*first); - return dest; -} - -// std::copy for class types - element-wise assignment, answer the new end. -template -inline T* overGrowthCopyAssign(const T* first, const T* last, T* dest) -{ - for (; first != last; ++first, ++dest) - *dest = *first; - return dest; -} - -// _Tidy - VC7.1's clear() AND the destructor's body: destroy, free, null all three pointers. -// (VC7.1 vector::clear() is `_Tidy()`, which is why removeActiveMaterial's `types.clear()` and the -// base cleanup's table release are the same 100CFE80 body.) -template -inline void overGrowthVectorTidy(OverGrowthVector& v) -{ - if (v.first) - { - overGrowthDestroyRange(v.first, v.last); - ::renddx9abi::engineFree(v.first); - } - v.first = 0; - v.last = 0; - v.end = 0; -} - -// _Buy(n): allocate exactly n, nothing for n == 0. -template -inline void overGrowthVectorBuy(OverGrowthVector& v, unsigned int capacity) -{ - v.first = 0; - v.last = 0; - v.end = 0; - if (capacity == 0) - return; - v.first = static_cast(::renddx9abi::engineAlloc(capacity * sizeof(T))); - v.last = v.first; - v.end = v.first + capacity; -} - -// vector(const vector&) - 100D0600: _Buy(right.size()) then _Ucopy. -template -inline void overGrowthVectorCopyConstruct(OverGrowthVector& v, const OverGrowthVector& right) -{ - v.allocator = 0; // [CHOSEN, not recovered] the empty allocator's padding; never read - overGrowthVectorBuy(v, overGrowthVectorSize(right)); - if (v.first) - v.last = overGrowthUninitializedCopy(right.first, right.last, v.first); -} - -// operator= - 100D0AE0, the VC7.1 four-arm assignment. -template -inline void overGrowthVectorAssign(OverGrowthVector& v, const OverGrowthVector& right) -{ - if (&v == &right) - return; - const unsigned int count = overGrowthVectorSize(right); - if (count == 0) - { - overGrowthVectorTidy(v); // clear(): free storage - } - else if (count <= overGrowthVectorSize(v)) - { - T* const newLast = overGrowthCopyAssign(right.first, right.last, v.first); - overGrowthDestroyRange(newLast, v.last); // destroy old - v.last = v.first + count; - } - else if (count <= overGrowthVectorCapacity(v)) - { - const T* const middle = right.first + overGrowthVectorSize(v); - overGrowthCopyAssign(right.first, middle, v.first); - v.last = overGrowthUninitializedCopy(middle, right.last, v.last); - } - else - { - if (v.first) - { - overGrowthDestroyRange(v.first, v.last); // discard old array - ::renddx9abi::engineFree(v.first); - } - overGrowthVectorBuy(v, count); - if (v.first) - v.last = overGrowthUninitializedCopy(right.first, right.last, v.first); - } -} - -// push_back - construct in place when there is room, otherwise _Insert_n at -// end() (100D0880 / 100D2A20): copy the value first, grow by half (at least to size + 1), copy the -// prefix, construct the new element, then destroy and free the old array. -template -inline void overGrowthVectorPushBack(OverGrowthVector& v, const T& value) -{ - const unsigned int size = overGrowthVectorSize(v); - if (v.first && size < overGrowthVectorCapacity(v)) - { - ::new (static_cast(v.last)) T(value); // _Ufill(_Mylast, 1, _Val) - ++v.last; - return; - } - - const T copy(value); // _Tmp = _Val - const unsigned int oldCapacity = overGrowthVectorCapacity(v); - unsigned int capacity = oldCapacity + oldCapacity / 2u; - if (capacity < size + 1u) - capacity = size + 1u; - T* const buffer = static_cast(::renddx9abi::engineAlloc(capacity * sizeof(T))); - T* p = overGrowthUninitializedCopy(v.first, v.last, buffer); // prefix (the suffix is empty) - ::new (static_cast(p)) T(copy); - if (v.first) - { - overGrowthDestroyRange(v.first, v.last); - ::renddx9abi::engineFree(v.first); - } - v.end = buffer + capacity; - v.last = buffer + size + 1u; - v.first = buffer; -} - -// erase(where) - std::copy(where + 1, last, where); destroy the last; --last. -template -inline T* overGrowthVectorErase(OverGrowthVector& v, T* where) -{ - overGrowthCopyAssign(where + 1, static_cast(v.last), where); - overGrowthDestroyRange(v.last - 1, v.last); - --v.last; - return where; -} +struct OverGrowthPatch; // 0x98-byte entries at owner +0xE0, defined in OverGrowthCell.h +struct LightShadowRecord; // XpLightManager.h - the LightManager's shadow records // Per-material vegetation type, including placement weight and preloaded geometry. @@ -201,8 +33,8 @@ struct OverGrowthType { OverGrowthType(); - vc71::string name; // +0x00 addType/setActiveType key (case-sensitive ==) - vc71::string geometry; // +0x1C OvergrowthType.geometry; addType seeds it with name + std::string name; // +0x00 addType/setActiveType key (case-sensitive ==) + std::string geometry; // +0x1C OvergrowthType.geometry; addType seeds it with name float probability; // +0x38 [INFERRED] 1.0f; postLoad: density / sum(density) float density; // +0x3C OvergrowthType.density float rotationScale; // +0x40 OvergrowthType.rotationScale @@ -212,31 +44,90 @@ struct OverGrowthType float normalScale; // +0x54 OvergrowthType.normalScale int geometryIndex; // +0x58 -1 until preLoad resolves `geometry` (1015F450) }; -static_assert(sizeof(OverGrowthType) == 0x5C, "OverGrowthType is 0x5C in the PE (100D0600 divides by 92)"); -// OverGrowthMaterial - one Overgrowth.addMaterial record, 0x30 bytes, in the owner's +0x3C vector -// (preLoad/save/getMaterialList divide by 48). The copy constructor is inlined at every by-value -// copy (string, +0x1C, then 100D0600 on the types); assignment is 100D1A70's element body (string =, -// +0x1C, 100D0AE0); the destructor is 100D28B0's element body (_Tidy the types, then the string). +// OverGrowthMaterial - one Overgrowth.addMaterial record, 0x30 bytes in the PE, in the owner's +0x3C +// vector (preLoad/save/getMaterialList divide by 48). Copies and assignment are member-wise (the +// string, +0x1C, then the type vector - 100D0600 / 100D1A70 / 100D0AE0); the destructor releases the +// types, then the name (100D28B0). struct OverGrowthMaterial { OverGrowthMaterial(); - OverGrowthMaterial(const OverGrowthMaterial& other); - OverGrowthMaterial& operator=(const OverGrowthMaterial& other); - ~OverGrowthMaterial(); - - vc71::string name; // +0x00 setActiveMaterial key (_stricmp) - unsigned int id; // +0x1C addMaterial's second argument (unique): the - // Overgrowth.raw value, 0..15 (the coverage slot) - OverGrowthVector types; // +0x20 first +0x24, last +0x28, end +0x2C + + std::string name; // +0x00 setActiveMaterial key (_stricmp) + unsigned int id; // +0x1C addMaterial's second argument (unique): the + // Overgrowth.raw value, 0..15 (the coverage slot) + std::vector types; // +0x20 }; -static_assert(sizeof(OverGrowthMaterial) == 0x30, "OverGrowthMaterial is 0x30 in the PE"); -// The native host and compatibility image retain this image-owned layout. In particular, -// VideoOptions writes +0xF4 and post-load/draw test the VC7.1 string length at +0x9C. + +// One half of a geometry-table entry (0x50 bytes in the PE): a template, its own instance and the +// pool of instances the frame hands out. Construction 1015EB80, copy 1015EC70, destruction 1015EC00 +// (OverGrowth.cpp). Field names are [INFERRED]. + +struct OverGrowthGeometryRecord +{ + explicit OverGrowthGeometryRecord(const std::string& templateName); + OverGrowthGeometryRecord(const OverGrowthGeometryRecord& other); + ~OverGrowthGeometryRecord(); + + std::string name; // +0x00 the template name + void* geometry; // +0x1C the template's own instance (createInstance) + // +0x20 / +0x24 - the vegetation vertices of the non-"tile_" (leaf, [0]) and "tile_" (trunk, [1]) + // materials; +0x28 / +0x2C the matching index counts (postLoadResources). + unsigned int vertexCounts[2]; + unsigned int indexCounts[2]; + world::IObjectTemplate* objectTemplate; // +0x30 ObjectTemplateManager getTemplate(name) + IGeometryTemplate* geometryTemplate; // +0x34 GeometryTemplateManager getTemplate(name) + unsigned int poolUsed; // +0x38 pool geometries handed out this frame; + // NOT constructed (render resets it) + std::vector pool; // +0x3C the instances the pool owns + float distanceScale; // +0x4C 1.0; postLoad clamp((radius * 0.2)^2, 0.3, 1) + +private: + OverGrowthGeometryRecord& operator=(const OverGrowthGeometryRecord&); +}; + +// The 0xA0-byte geometry-table element. Its copy (0x10160610: +0x00 then +0x50) and its destruction +// (0x10160640 / the range destroy 0x101607F0: +0x50 then +0x00) are the two records' own. +struct OverGrowthGeometryPair +{ + OverGrowthGeometryPair(const std::string& lodName, const std::string& fullName) + : lod(lodName), full(fullName) {} + + OverGrowthGeometryRecord lod; // +0x00 "_lod" - the batched cell geometry + OverGrowthGeometryRecord full; // +0x50 "" - the near instances + +private: + OverGrowthGeometryPair& operator=(const OverGrowthGeometryPair&); +}; + + +// One placed vegetation instance - 0x60 bytes, a patch's vector entries (100D19E0 divides by 0x60). +// Construction 1015E930 (OverGrowthCells.cpp / OverGrowthLoad.cpp). Field names are [INFERRED]. +struct OverGrowthInstance +{ + int geometryIndex; // +0x00 the geometry pair, -1 + Mat4 transform; // +0x04 identity; the translation row is +0x34..+0x3C + float scale; // +0x44 1.0 + float cullRadius; // +0x48 the full geometry's bounding radius (times scale) + float radiusToSame; // +0x4C radius * minRadiusToSame + float radiusToOthers; // +0x50 radius * minRadiusToOthers + float shadow; // +0x54 the shadow-map sample; NOT constructed + unsigned char generated; // +0x58 1 when populatePatch placed it, 0 for a level object + unsigned char pad59[3]; + float lodFadeState; // +0x5C 1.0; the lodTimer cross-fade +}; + +// The instance list carrier of the cell/patch virtuals. +typedef std::vector OverGrowthInstanceVector; + + +// The native host and compatibility image retain this image-owned object. VideoOptions writes the +// quality scale (+0xF4); post-load/draw test the path (+0x88) for emptiness. // The unpublished base's constructor/cleanup are factored as helpers; no base type name is guessed. +// Data members are public: the Overgrowth translation units' file-local helpers read them. class OverGrowth { public: @@ -255,18 +146,22 @@ class OverGrowth virtual void reload(); // +2C 100CDDC0 virtual void clear(); virtual void render(IRenderView* view, float time); - // +38 the LightManager's directional records (VC7.1 vector, 0x498-byte elements), the - // pulled-back light Frustum it culls patches with, the caster Frustum whose near plane it grows, - // and the geometry vector it fills (LightManager +0x970). The opaque carrier names stay; the - // call site casts. - virtual void collectShadowGeometry(OverGrowthShadowVolumes*, OverGrowthShadowBounds*, - OverGrowthShadowState*, OverGrowthGeometryVector*); + // +38 the LightManager's directional records (+0x79C), the pulled-back light Frustum it culls + // patches with, the caster Frustum whose near plane it grows, and the geometry vector it fills + // (LightManager +0x970). + virtual void collectShadowGeometry(const std::vector* records, + const Frustum* lightFrustum, Frustum* casterFrustum, + std::vector* geometries); virtual void updateCell(OverGrowthCell*, OverGrowthInstanceVector*, bool changed); // +3C 100CB080 virtual void placeInstance(OverGrowthType*, Vec3*, OverGrowthInstance*); virtual void populatePatch(OverGrowthPatch*); void preLoadResources(); // direct 100CC500 void postLoadResources(); // direct 100CD020 + // Direct 100CBFC0, no caller in 1.50. [CHOSEN, not recovered] name. + bool atlasMatchesTextureNames(const std::set& textures); + // Direct 100CB7A0, no caller in 1.50. [CHOSEN, not recovered] name. + void createGeneratedObjects(std::vector* objects); static void operator delete(void* memory) noexcept; @@ -275,20 +170,20 @@ class OverGrowth // from the console spelling; getter constness is [INFERRED]. Every OvergrowthType.* member acts // on the active type (+0xEC) and is a no-op / default read when there is none. - void setPath(const vc71::string& path); - const vc71::string& getPath() const; + void setPath(const std::string& path); + const std::string& getPath() const; void preLoad(); - vc71::string getMaterialList() const; - bool addMaterial(const vc71::string& name, unsigned int id); + std::string getMaterialList() const; + bool addMaterial(const std::string& name, unsigned int id); bool removeActiveMaterial(); - void setActiveMaterial(const vc71::string& name); - vc71::string getActiveMaterialName() const; - vc71::string getTypeList() const; - bool addType(const vc71::string& name); + void setActiveMaterial(const std::string& name); + std::string getActiveMaterialName() const; + std::string getTypeList() const; + bool addType(const std::string& name); bool removeActiveType(); - void setActiveType(const vc71::string& name); + void setActiveType(const std::string& name); void save(); // 100CD7E0 (editor) - vc71::string getGeometryList() const; + std::string getGeometryList() const; float getLodDistance() const; void generateAtlas(); // 100CCD20 (editor) void setEditorEnable(bool enable); @@ -300,10 +195,14 @@ class OverGrowth float getCloseDistPercentage() const; void setCloseDistPercentage(float value); // +0xC8 float getCloseDistFade() const; void setCloseDistFade(float value); // +0xCC float getLodTimer() const; void setLodTimer(float value); // +0xF8 + // +0xF4 - the vegetation quality scale VideoOptions::apply stores (0.4 / 0.7 / 1.0 per quality + // level); updateCells multiplies it into the near distance. [CHOSEN] typed accessors for the + // field VideoOptions wrote by offset. + float getQualityScale() const; void setQualityScale(float scale); // +0xF4 // The active type's properties - OvergrowthType.*. Each setter writes the field and, once the // level is loaded (+0xA4, set by postLoadResources), regenerates everything through reload(). - void setTypeGeometry(const vc71::string& geometry); vc71::string getTypeGeometry() const; + void setTypeGeometry(const std::string& geometry); std::string getTypeGeometry() const; void setTypeDensity(float value); float getTypeDensity() const; void setTypeNormalScale(float value); float getTypeNormalScale() const; void setTypeRotationScale(float value); float getTypeRotationScale() const; @@ -315,7 +214,7 @@ class OverGrowth // or full (+0x50) name is `name`; else a new record built from `name + "_lod"` and `name`, kept // only when both templates gave a geometry; -1 for an empty name or a dropped record. preLoad, // initialize, the static-object adoption and the editor's populatePatch call it. - int findOrAddGeometry(const vc71::string& name); + int findOrAddGeometry(const std::string& name); // The editor's painting (OverGrowth.cpp). x / z / radius are world metres on the primary @@ -336,14 +235,82 @@ class OverGrowth void exportShadowmapRectToTerrainTexture(unsigned int x0, unsigned int x1, unsigned int z0, unsigned int z1); + // data, in shipped order (the vptr is +0x00). Names are [INFERRED] except the console's + // (viewDistance, viewDistanceScale, closeDistPercentage, closeDistFade, lodTimer, editorEnable, + // path). The constructor writes only the fields the PE writes; the rest stay as allocated. + Vec3 m_cameraPosition; // +0x04 baseUpdateCells: the camera + int m_gridSize; // +0x10 N, the N x N camera cells (10) + float m_cellSize; // +0x14 + unsigned int m_randomSeed; // +0x18 0x759DC150, then per cell/patch + unsigned char m_enabled; // +0x1C 1 + unsigned char m_unresolved1D; // +0x1D 0 [UNRESOLVED] + unsigned char m_initialized; // +0x1E initialize sets it + unsigned char m_pad1F; + float m_fadeBand; // +0x20 0.3; postLoad 0 + float m_viewDistance; // +0x24 Overgrowth.viewDistance + float m_viewDistanceScale; // +0x28 Overgrowth.viewDistanceScale + float m_heightFadeDistance; // +0x2C 1.0 + float m_minimumHeightFade; // +0x30 0.4; postLoad 1.0 + float m_cellFadeDistance; // +0x34 12.0 + unsigned char m_reseatCells; // +0x38 rebuildCells sets it + unsigned char m_pad39[3]; + std::vector m_materials; // +0x3C + std::vector m_geometries; // +0x4C + float m_extentX; // +0x5C map width * scale.x + float m_extentZ; // +0x60 map height * scale.z + float m_originX; // +0x64 -extentX / 2; NOT constructed + float m_originZ; // +0x68 -extentZ / 2; NOT constructed + Vec3 m_patchOrigin; // +0x6C (originX, 0, originZ) + unsigned int m_mapWidth; // +0x78 the primary heightmap's size + unsigned int m_mapHeight; // +0x7C + unsigned char* m_densityMap; // +0x80 Overgrowth.raw - material ids + unsigned char* m_shadowMap; // +0x84 OvergrowthShadowmap.raw + std::string m_path; // +0x88 Overgrowth.path + unsigned char m_loaded; // +0xA4 postLoadResources sets it + unsigned char m_padA5[3]; + world::IHeightmap* m_heightmap; // +0xA8 NOT constructed + world::IHeightmapCluster* m_cluster; // +0xAC NOT constructed + unsigned char m_reloading; // +0xB0 reload() brackets with it + unsigned char m_padB1[3]; + // +0xB4 - a vector the constructor empties and the destructor frees; nothing else touches it. + // [UNRESOLVED] element type. + std::vector m_unresolvedB4; + float m_closeDistance; // +0xC4 updateCells; NOT constructed + float m_closeDistPercentage; // +0xC8 Overgrowth.closeDistPercentage + float m_closeDistFade; // +0xCC Overgrowth.closeDistFade + unsigned int m_unresolvedD0; // +0xD0 0 [UNRESOLVED] + unsigned char m_drawNear; // +0xD4 1 - render and the shadow walk + unsigned char m_updateBeforeRender; // +0xD5 1 - render calls update() + unsigned char m_padD6[2]; + int m_patchCountX; // +0xD8 setViewDistance; NOT constructed + int m_patchCountZ; // +0xDC + OverGrowthPatch* m_patches; // +0xE0 new[] of countX * countZ + OverGrowthCell** m_cells; // +0xE4 N x N + OverGrowthMaterial* m_activeMaterial; // +0xE8 + OverGrowthType* m_activeType; // +0xEC + unsigned char m_editorEnable; // +0xF0 Overgrowth.editorEnable + unsigned char m_unresolvedF1; // +0xF1 0 [UNRESOLVED] + unsigned char m_padF2[2]; + float m_qualityScale; // +0xF4 1.0; VideoOptions writes it + float m_lodTimer; // +0xF8 Overgrowth.lodTimer + dx9rend::TextureAtlas* m_atlas; // +0xFC + dx9rend::EngineTexture* m_atlasPage; // +0x100 the atlas's first page + // +0x104 / +0x108 - the largest per-patch vertex count of the leaf [0] and trunk [1] stream; + // +0x10C / +0x110 the matching index counts. NOT constructed. + unsigned int m_streamVertexCounts[2]; + unsigned int m_streamIndexCounts[2]; + float m_materialCoverageMax[16]; // +0x114 NOT constructed + private: - // [UNRESOLVED] Names for the unrecovered members; constructor writes only observed fields. - // The string at +0x88 is explicitly constructed/destroyed in its original order. - alignas(4) unsigned char m_storage[0x150]; + OverGrowth(const OverGrowth&); + OverGrowth& operator=(const OverGrowth&); }; -static_assert(sizeof(OverGrowth) == 0x154, "OverGrowth PE image-owned layout"); OverGrowth* createOverGrowth(); + +// Re-orthonormalises a basis in place keeping its y row: rows 1 and 2 are normalised, then +// row 0 = row1 x row2 and row 2 = row0 x row1. The w column is untouched (OverGrowthCells.cpp). +void orthonormalizeKeepingY(Mat4& matrix); } } } #endif #endif diff --git a/Code/BF2/Geom/Overgrowth/OverGrowthCell.h b/Code/BF2/Geom/Overgrowth/OverGrowthCell.h index 02deb8a0d..b8561a7fc 100644 --- a/Code/BF2/Geom/Overgrowth/OverGrowthCell.h +++ b/Code/BF2/Geom/Overgrowth/OverGrowthCell.h @@ -1,15 +1,34 @@ -// Internal overgrowth grid-cell and batched-stream declarations. +// Internal overgrowth grid-cell, patch and batched-stream declarations. #ifndef BF2_GEOM_OVERGROWTHCELL_H #define BF2_GEOM_OVERGROWTHCELL_H #ifdef BF2_IMAGE_RENDDX9 #include "OverGrowth.h" +#include "../BoxCorners.h" // OverGrowthBoxCorners +#include "../MeshTemplate.h" // MeshBounds #include "../../Math/Mat4.h" +#include "../../RendDX9/Ra/RaShader.h" // RaObjectParameters #include "../../RendDX9/Ra/RaStreamDataEditable.h" namespace dice { namespace hfe { namespace geom { +// One patch of the countX * countZ grid at OverGrowth +0xE0 - 0x98 bytes in the PE, allocated with +// operator new[] (the element count ahead of the first element). Construction sub_100CAFF0: position +// and the vector zeroed, the bounds zeroed with their dirty byte set; the coverage is NOT constructed. +// The destructor is its vector's. Field names are [INFERRED]. +struct OverGrowthPatch +{ + OverGrowthPatch(); + ~OverGrowthPatch(); + + Vec3 position; // +0x00 the patch corner, y the terrain height + OverGrowthInstanceVector instances; // +0x0C + float coverage[16]; // +0x1C share of the patch's texels per material id + MeshBounds bounds; // +0x5C 60 bytes, ends at +0x98 +}; + + // Cell vertex stream plus object parameters. Extra buffer-management slots extend the // current base declaration while retaining compatibility positions. @@ -17,29 +36,32 @@ class OverGrowthCellMesh : public dx9rend::Ra::RaStreamDataEditable { public: OverGrowthCellMesh(unsigned int vertexCapacity, unsigned int indexCapacity, - const vc71::vector_layout& elements); + const std::vector& elements); void* destroy(unsigned char flags) override; // +0x00 - virtual void releaseBuffers(); // +0x30 10048D60 [FRONTIER] + virtual void releaseBuffers(); // +0x30 10048D60 virtual unsigned int getFreeVertexCount() const; // +0x34 virtual unsigned int getVertexCapacity() const; // +0x38 virtual unsigned int getIndexCapacity() const; // +0x3C - virtual void createBuffers(); // +0x40 10048C70 [FRONTIER] + virtual void createBuffers(); // +0x40 10048C70 - unsigned char m_objectParameters[0x224]; // +0x1A4 sub_100458E0 -}; + // +0x1A4 in the PE: the Ra object block, constructed in place by sub_100458E0. + alignas(dx9rend::Ra::RaObjectParameters) + unsigned char m_objectParameters[sizeof(dx9rend::Ra::RaObjectParameters)]; -#if defined(_M_IX86) -static_assert(sizeof(OverGrowthCellMesh) == 0x3C8, "the cell allocates 0x3C8 per stream (0x100D0ECE)"); -#endif + dx9rend::Ra::RaObjectParameters& objectParameters() + { return *reinterpret_cast(m_objectParameters); } +}; // Visible grid cell with bounds, camera fade, instance list, and leaf/trunk streams. -// The eight-slot interface overlays its abstract base in the 0x2AC-byte compatibility layout. +// The eight-slot interface overlays its abstract base (0x2AC bytes in the PE). Field names are +// [INFERRED]. struct OverGrowthCell { OverGrowthCell(); // 100D0C90 (+ base 1015E6D0) + ~OverGrowthCell(); // 100D18B0, reached through destroy virtual void* destroy(unsigned char flags); // +0x00 virtual bool appendGeometry(void* geometryTemplate, const Mat4* transform, float scale, @@ -51,15 +73,31 @@ struct OverGrowthCell virtual unsigned int getIndexCapacity(); // +0x18 virtual void clearFarList(); // +0x1C - alignas(4) unsigned char m_storage[0x2A8]; + unsigned char visible; // +0x04 in range and built this frame + unsigned char built; // +0x05 its streams hold the current cell + unsigned char empty; // +0x06 1 - no far instance to draw + unsigned char pad07; + Vec3 corner; // +0x08 the cell's corner, y the terrain height + float size; // +0x14 the cell edge + float fadeFactor; // +0x18 the distance / height fade + float cameraDistance; // +0x1C the camera's distance to the centre + MeshBounds bounds; // +0x20 + int cellX; // +0x5C world cell, 0x2CEE9D7 when unplaced + int cellZ; // +0x60 + unsigned char hasNear; // +0x64 some instances are drawn as full meshes + unsigned char pad65[3]; + // +0x68 - the base's Ra object block (sub_100458E0 / sub_1004D900). + alignas(dx9rend::Ra::RaObjectParameters) + unsigned char objectParameters[sizeof(dx9rend::Ra::RaObjectParameters)]; + std::vector farList; // +0x28C the instances batched into the streams + unsigned int unresolved29C; // +0x29C zeroed by the constructor and rebuildCells [UNRESOLVED] + OverGrowthPatch* lastPatch; // +0x2A0 the patch updateCell last took + OverGrowthCellMesh* leaf; // +0x2A4 the non-"tile_" materials + OverGrowthCellMesh* trunk; // +0x2A8 the "tile_" materials }; -#if defined(_M_IX86) -static_assert(sizeof(OverGrowthCell) == 0x2AC, "postLoadResources allocates 0x2AC per cell (0x100CD6DE)"); -#endif - -// The allocation postLoadResources makes per grid slot (0x100CD6DE..0x100CD6FB): sub_1005F320(0x2AC), then -// the constructor when the heap answered (OverGrowthCells.cpp). +// The allocation postLoadResources makes per grid slot (0x100CD6DE..0x100CD6FB): operator new(0x2AC), +// then the constructor when the heap answered (OverGrowthCells.cpp). OverGrowthCell* createOverGrowthCell(); // sub_1015EEB0 - the abstract base's updateCells: the camera ring of N x N cells and each cell's build. @@ -67,6 +105,33 @@ OverGrowthCell* createOverGrowthCell(); // (OverGrowthCells.cpp). void overGrowthBaseUpdateCells(OverGrowth* self, IRenderView* view); + +// Placement helpers both halves share, defined once in OverGrowthCells.cpp. + +// The 96-byte eight-corner box: the local bounds' corners carried through a world matrix +// (geom::BoxCorners, BoxCorners.h). +typedef BoxCorners OverGrowthBoxCorners; + +// Zeroes the box, then fills it with the corners of `bounds` transformed by `world`. +void constructBoxCorners(OverGrowthBoxCorners& box, const MeshBounds& bounds, const Mat4& world); + +// Grows `bounds` by the box corners' component-wise minimum, then their maximum. +void boundsExpandByCorners(MeshBounds& bounds, const OverGrowthBoxCorners& box); + +// World (x, z) to density/shadow map texel (ix, iz) and the fractions (fx, fz). An index equal to +// the map width or height is not rejected (the retail clamp's off-by-one). +void shadowCoords(OverGrowth* self, float x, float z, int* ix, int* iz, float* fx, float* fz); + +// The bilinear shadow-map value at world (x, z); a tap outside the map counts as 0. +float sampleShadow(OverGrowth* self, float x, float z); + +// Fills the patch's sixteen per-material coverage shares from the density map. +void computeCoverage(OverGrowth* self, OverGrowthPatch* patch); + +// The instance's default constructor: identity transform, unit scale, no geometry. +0x54 (the +// shadow value) is left unwritten. +void constructInstance(OverGrowthInstance& instance); + } } } #endif #endif diff --git a/Code/BF2/Geom/Overgrowth/OverGrowthCellRender.cpp b/Code/BF2/Geom/Overgrowth/OverGrowthCellRender.cpp index a843918dd..aa550831f 100644 --- a/Code/BF2/Geom/Overgrowth/OverGrowthCellRender.cpp +++ b/Code/BF2/Geom/Overgrowth/OverGrowthCellRender.cpp @@ -1,6 +1,8 @@ // Packs cell LOD vertices and submits batched vegetation streams. // Rebuild cells before drawing so both leaf and trunk shader pointers are valid. #ifdef BF2_IMAGE_RENDDX9 +#include "../../Platform/X87Compat.h" // [CHOSEN, not recovered] x87 conversion results, including invalid inputs. +#include "../../RendDX9/RendDX9Math.h" // rendmath::normalize (sub_100777A0) #include "OverGrowth.h" #include "../StaticMesh.h" // staticMeshPackVec4 - sub_1008DD80 #include "../StaticMeshTemplate.h" // StaticMeshTemplate / StaticMeshMaterial / ShaderMaterial @@ -14,8 +16,8 @@ #include "../../RendDX9/Ra/RaStreamDataEditable.h" #include "../../RendDX9/Texture.h" // EngineTexture::name (+0x58) #include "../../RendDX9/TextureAtlas/TextureAtlas.h" // textureAtlasFind - sub_100156F0 -#include "../../../RendDX9Abi/Vc71String.h" -#include "../../../RendDX9Abi/Vc71Vector.h" +#include +#include "../../../RendDX9Abi/D3dx9Sdk.h" #include "OverGrowthCell.h" #include @@ -23,17 +25,8 @@ #include #include -// The two d3dx9_25 imports appendGeometry calls (IAT 0x101DB46C / 0x101DB468). Declared raw, exactly as -// RendMisc/RenderView.cpp declares D3DXMatrixInverse: the modern SDK ships no D3DX9 headers and the -// D3DXMATRIX* is just 16 floats here; /alternatename bridges the decorated reference onto the -// undecorated import. D3DXMatrixTranspose is not in RendDX9Abi\D3dx9_25.def (the no-SDK fallback -// import library); the April 2005 SDK library carries it. -struct D3DXMATRIX; -extern "C" D3DXMATRIX* __stdcall D3DXMatrixInverse(D3DXMATRIX* out, float* determinant, - const D3DXMATRIX* m); -extern "C" D3DXMATRIX* __stdcall D3DXMatrixTranspose(D3DXMATRIX* out, const D3DXMATRIX* m); -#pragma comment(linker, "/alternatename:_D3DXMatrixInverse@12=_D3DXMatrixInverse") -#pragma comment(linker, "/alternatename:_D3DXMatrixTranspose@8=_D3DXMatrixTranspose") +// appendGeometry calls two d3dx9_25 imports, D3DXMatrixInverse and D3DXMatrixTranspose (IAT +// 0x101DB46C / 0x101DB468); their D3DXMATRIX* is just 16 floats here. namespace dice { namespace hfe { @@ -47,11 +40,6 @@ extern LightManager* g_LightManager; // ModuleGeom.cpp - dword_1024B914 namespace { -template T& field(void* object, unsigned int offset) -{ return *reinterpret_cast(static_cast(object) + offset); } -template const T& field(const void* object, unsigned int offset) -{ return *reinterpret_cast(static_cast(object) + offset); } - // flt_10219554 (0x42DA7259) = 109.22334 = 32767/300 - a cell-relative position to SHORT4; its inverse, // the immediate 0x3C16012C = 0.009155553, is the draw's decode scale. flt_10219558 (0x46FFFE00) = 32767 // and flt_10219550 (0x42FF0000) = 127.5. Each literal below is the float's exact value. @@ -60,17 +48,14 @@ const float kPositionDecode = 0.009155552834272385f; const float kShortScale = 32767.0f; const float kNormalScale = 127.5f; -// StaticMeshMaterial / cell offsets the two bodies read (the typed members are used where they exist). -const unsigned int kCellCorner = 0x08; // Vec3 - the cell's corner (base constructor 1015E6D0) -const unsigned int kCellSize = 0x14; // float - the cell edge -const unsigned int kCellLeafStream = 0x2A4; // OverGrowthCellMesh* - the non-"tile_" materials -const unsigned int kCellTrunkStream = 0x2A8; // OverGrowthCellMesh* - the "tile_" materials // The material block (RaStreamDataEditable +0x0C) holders the draw writes: PosUnpack's value at -// block +0x128 (holder +0x124, StaticMeshMaterial.cpp's RaMaterialParameters), and the Ra shader -// the block keeps at +0x14C (rebuildCells stores "LeafOG" / "TrunkOG" there; the StaticMesh draw's -// staticMeshMaterialShader and TerrainDraw's water read the same word). -const unsigned int kBlockPosUnpackValue = 0x128; -const unsigned int kBlockShader = 0x14C; +// block +0x128 (holder +0x124), and the Ra shader the block keeps at +0x14C (rebuildCells stores +// "LeafOG" / "TrunkOG" there; the StaticMesh draw's staticMeshMaterialShader and TerrainDraw's +// water read the same word - raMaterialShaderSlot). +inline RaMaterialParameters& streamMaterial(OverGrowthCellMesh* stream) +{ + return *reinterpret_cast(stream->m_materialParameters); +} // One vertex of the cell streams - 16 bytes, the stride appendGeometry hands append (`push 10h`) and the // cell constructor gives both streams. Element descriptors (OverGrowthCells.cpp, 100D0C90): position SHORT4, @@ -83,12 +68,11 @@ struct OverGrowthCellVertex short texCoord[2]; // +0x0C u, v = (clamp(t, -1, 1) * atlas scale + atlas offset) * 32767 }; -#if defined(_M_IX86) +// The vertex format: every architecture (append and the stream constructor pass the 16 literally). static_assert(sizeof(OverGrowthCellVertex) == 16, "the cell streams are built with stride 16"); +#if defined(_M_IX86) static_assert(offsetof(dx9rend::Ra::RaStreamDataEditable, m_materialParameters) == 0x0C, "the material block sits at stream +0x0C"); -static_assert(offsetof(OverGrowthCellMesh, m_objectParameters) == 0x1A4, - "the object block sits at stream +0x1A4 (entry +0x118 points at it)"); static_assert(offsetof(dx9rend::Ra::RaObjectParameters, worldViewProjection) == 0x090, "stream +0x234 is the WorldViewProjection holder (its value at +0x238)"); static_assert(offsetof(dx9rend::Ra::RaObjectParameters, objectSpaceCamPos) == 0x1B4, @@ -101,7 +85,11 @@ static_assert(offsetof(dx9rend::Ra::RaLightingParameters, overGrowthAmbient) == // __ftol2 - truncation toward zero into 64 bits; each caller keeps the low word (ax) or byte (al). inline long long ftol2(float value) { +#if defined(__APPLE__) + return bf2x87::toInt64Truncate(value); +#else return static_cast(value); +#endif } // PE 0x1000ED40 (34 B), read in full: `fcomi high; fcmovnb` then `fcomi low; fcmovb` - the high bound @@ -131,51 +119,8 @@ void mat4ScaleColumns(Mat4& matrix, const Vec3& s) m[10] = m[10] * s.z; } -// PE 0x10079610 (92 B), read in full - transformPoint (SkinnedMesh.cpp keeps the same body file-local). -// z and y are formed before x is stored because out may alias in. -void transformPoint(const Mat4& m, const float in[3], float out[3]) -{ - const float z = m.m[2] * in[0] + m.m[10] * in[2] + m.m[6] * in[1] + m.m[14]; - const float y = m.m[1] * in[0] + m.m[9] * in[2] + m.m[5] * in[1] + m.m[13]; - out[0] = m.m[8] * in[2] + m.m[4] * in[1] + in[0] * m.m[0] + m.m[12]; - out[1] = y; - out[2] = z; -} - -// PE 0x1007C440 (83 B), read in full - transformVector: the same body without the translation row. -void transformVector(const Mat4& m, const float in[3], float out[3]) -{ - const float z = m.m[2] * in[0] + m.m[10] * in[2] + m.m[6] * in[1]; - const float y = m.m[1] * in[0] + m.m[9] * in[2] + m.m[5] * in[1]; - out[0] = m.m[8] * in[2] + m.m[4] * in[1] + in[0] * m.m[0]; - out[1] = y; - out[2] = z; -} - -// PE 0x100777A0 (135 B), read in full - normalise in place: |v|^2 = (x*x + y*y) + z*z kept as a float; -// within FLT_EPSILON (flt_10208958) of 1 it is left alone; below FLT_EPSILON it is zeroed (answering -// -20001, discarded by appendGeometry); otherwise each component is scaled by 1 / sqrt(|v|^2). -int normalizeInPlace(Vec3& v) -{ - const float lengthSquared = v.x * v.x + v.y * v.y + v.z * v.z; - if (std::fabs(lengthSquared - 1.0f) < FLT_EPSILON) - return 0; - if (std::fabs(lengthSquared) < FLT_EPSILON) - { - v.x = 0.0f; - v.y = 0.0f; - v.z = 0.0f; - return -20001; - } - const float inverse = 1.0f / std::sqrt(lengthSquared); - v.x = inverse * v.x; - v.y = inverse * v.y; - v.z = inverse * v.z; - return 0; -} - // std::string::find(s, 0, count) != npos, over the counted characters (MSVCP71's find, 0x100D1F6E). -bool containsCounted(const vc71::string& text, const char* needle, unsigned int count) +bool containsCounted(const std::string& text, const char* needle, unsigned int count) { const char* const data = text.c_str(); const unsigned int size = text.size(); @@ -189,29 +134,21 @@ bool containsCounted(const vc71::string& text, const char* needle, unsigned int // The cell centre both bodies derive: (corner.x + half, corner.y, corner.z + half), half = edge * 0.5 // (100D1D46..100D1D88 and 100D1057..100D1089, the same association: half + corner). -Vec3 cellCentre(const void* cell) +Vec3 cellCentre(const OverGrowthCell* cell) { - const float half = field(cell, kCellSize) * 0.5f; + const float half = cell->size * 0.5f; Vec3 centre; - centre.y = field(cell, kCellCorner + 4); - centre.x = half + field(cell, kCellCorner); - centre.z = half + field(cell, kCellCorner + 8); + centre.y = cell->corner.y; + centre.x = half + cell->corner.x; + centre.z = half + cell->corner.z; return centre; } -// The geom-0 / lod-0 material vector of a StaticMeshTemplate: +0xD0 (m_materials.first) -> [0].first -> -// [0] - the same three loads as staticMeshFirstMaterial (StaticMeshTemplate.h), read at 0x100D1BE2.. -// 0x100D1BEB and again per material (0x100D1C4D..0x100D1C59, 0x100D1D49..0x100D1D60). -const vc71::vector_layout& firstLodMaterials(const StaticMeshTemplate* t) -{ - const vc71::vector_layout* const geom = reinterpret_cast(t->m_materials.first); - return *reinterpret_cast(geom->first); -} // One of draw's two submissions (0x100D1111..0x100D126C for the leaf stream, 0x100D126F..0x100D13CB for // the trunk stream - the second a copy of the first with the two LightManager colour slots swapped). // Nothing happens unless the stream holds vertices (+0x08) AND primitives (+0x10), both signed `jle`. -void submitCellStream(OverGrowthCellMesh* stream, const Mat4& world, const Vec3& cameraLocal, +void submitCellStream(OverGrowthCellMesh*& stream, const Mat4& world, const Vec3& cameraLocal, world::LightSource* sky, bool trunk) { if (stream->getVertexCount() <= 0) // +0x08 @@ -224,30 +161,36 @@ void submitCellStream(OverGrowthCellMesh* stream, const Mat4& world, const Vec3& dx9rend::rendererGetRenderViewDup()->getViewProjectionMatrixPtr(); // renderer +0x50, view +0x84 dx9rend::Ra::RaObjectParameters& op = *reinterpret_cast(stream->m_objectParameters); - reinterpret_cast(op.worldViewProjection.value)->fullMult(world, *viewProjection); - op.objectSpaceCamPos.value[0] = cameraLocal.x; // x, y, z - op.objectSpaceCamPos.value[1] = cameraLocal.y; // (w keeps the block's 1) - op.objectSpaceCamPos.value[2] = cameraLocal.z; + geometryRendererMatrixProduct(*reinterpret_cast(op.worldViewProjection.value), + world, *viewProjection); // 0x10077A30 + dx9rend::Ra::RaObjectParameters& currentOp = + *reinterpret_cast(stream->m_objectParameters); + // x, y, z (w keeps the block's 1): 0x10031130 at 0x100D1183 / 0x100D12DF. + dx9rend::Ra::raParamVec4SetXyz(currentOp.objectSpaceCamPos, cameraLocal); { - float* const posUnpack = reinterpret_cast(stream->m_materialParameters + kBlockPosUnpackValue); - posUnpack[0] = kPositionDecode; // 0x10031150 with the - posUnpack[1] = kPositionDecode; // stack Vec4 (s, s, s, 1) - posUnpack[2] = kPositionDecode; - posUnpack[3] = 1.0f; + // 0x10031150 at 0x100D11B9 / 0x100D1315 with the stack Vec4 (s, s, s, 1). + Vec4 posUnpack; + posUnpack.x = kPositionDecode; + posUnpack.y = kPositionDecode; + posUnpack.z = kPositionDecode; + posUnpack.w = 1.0f; + dx9rend::Ra::raParamVec4Set(streamMaterial(stream).posUnpack, posUnpack); // block +0x128 } if (sky) { + const float* const direction = terrainSkyLightDirection(sky); // host +0x17C dx9rend::Ra::RaLightRecord* const record = static_cast(entry->lightArray.lights.value); // entry +0x128 - const float* const direction = terrainSkyLightDirection(sky); // host +0x17C record->direction[1] = direction[1]; record->direction[2] = direction[2]; record->direction[0] = direction[0]; const Vec3& sun = trunk ? g_LightManager->getStaticSunColor() // +0x1D8 : g_LightManager->getTreeSunColor(); // +0x1C8 - record->color[0] = sun.x; - record->color[1] = sun.y; - record->color[2] = sun.z; + dx9rend::Ra::RaLightRecord* const colorRecord = + static_cast(entry->lightArray.lights.value); + colorRecord->color[0] = sun.x; + colorRecord->color[1] = sun.y; + colorRecord->color[2] = sun.z; } { const Vec3& ambient = trunk ? g_LightManager->getStaticSkyColor() // +0x1E8 @@ -262,8 +205,8 @@ void submitCellStream(OverGrowthCellMesh* stream, const Mat4& world, const Vec3& entry->material = stream; // entry +0x000 entry->materialParameters = stream->m_materialParameters; // entry +0x004 = stream + 0x0C entry->objectParameters = stream->m_objectParameters; // entry +0x118 = stream + 0x1A4 - entry->shader = *reinterpret_cast( - stream->m_materialParameters + kBlockShader); // entry +0x138 = [stream + 0x158] + entry->shader = static_cast( + raMaterialShaderSlot(streamMaterial(stream))); // entry +0x138 = [stream + 0x158] // The PE inlines index 0 of sub_10041A70: the shader's own queue (+0x04) through its add slot (+0x04). dx9rend::renderQueueEnqueue(entry, false, false, false); } @@ -299,32 +242,28 @@ bool OverGrowthCell::appendGeometry(void* geometryTemplate, const Mat4* transfor reinterpret_cast(&inverse)); } + // The geom-0 / lod-0 materials (StaticMeshTemplate.h's first-lod accessors: m_materials.first -> + // [0].first -> [0]), read at 0x100D1BE2..0x100D1BEB and again per material (0x100D1C4D..0x100D1C59, + // 0x100D1D49..0x100D1D60). const StaticMeshTemplate* const t = static_cast(geometryTemplate); - unsigned int remaining; - { - const vc71::vector_layout& materials = firstLodMaterials(t); - remaining = materials.first - ? static_cast((materials.last - materials.first) / static_cast(sizeof(StaticMeshMaterial))) - : 0u; - } + unsigned int remaining = staticMeshFirstLodMaterialCount(t); if (!remaining) // `test ebx, ebx; jbe` return true; const short shadowWord = static_cast(ftol2(shadow * kShortScale)); OverGrowthCellVertex vertex; // [esp+0x50] - one slot - for (unsigned int offset = 0; remaining != 0; offset += sizeof(StaticMeshMaterial), --remaining) + for (unsigned int materialIndex = 0; remaining != 0; ++materialIndex, --remaining) { - const vc71::string unusedName; // var_9C - const StaticMeshMaterial* material = reinterpret_cast( - firstLodMaterials(t).first + offset); - const vc71::string& textureName = + const std::string unusedName; // var_9C + const StaticMeshMaterial* material = staticMeshFirstLodMaterial(t, materialIndex); + const std::string& textureName = static_cast(material->m_shaderMaterial->textures[1])->name; - vc71::string ddsName; // var_130 + std::string ddsName; // var_130 { - vc71::string stem; // var_D4 + std::string stem; // var_D4 dx9rend::pathStripExtension(stem, textureName); - vc71::string suffixed(stem); // var_B8 + std::string suffixed(stem); // var_B8 suffixed += ".dds"; ddsName = suffixed; } @@ -332,7 +271,7 @@ bool OverGrowthCell::appendGeometry(void* geometryTemplate, const Mat4* transfor s_indices.resize(0); // (0, 0) dx9rend::TextureAtlas* const atlas = - field(dx9rend::g_OverGrowth, 0xFC); // the global, +0xFC + static_cast(dx9rend::g_OverGrowth)->m_atlas; // the global, +0xFC const dx9rend::TextureAtlasEntry* const found = atlas ? dx9rend::textureAtlasFind(atlas, ddsName) : 0; float scaleU = 1.0f; @@ -348,7 +287,7 @@ bool OverGrowthCell::appendGeometry(void* geometryTemplate, const Mat4* transfor } const Vec3 centre = cellCentre(this); - material = reinterpret_cast(firstLodMaterials(t).first + offset); + material = staticMeshFirstLodMaterial(t, materialIndex); for (int index = 0; index < static_cast(material->m_vegetationVertexCount); ++index) { const float* const source = reinterpret_cast( @@ -358,7 +297,7 @@ bool OverGrowthCell::appendGeometry(void* geometryTemplate, const Mat4* transfor point.x = 0.0f; point.y = 0.0f; point.z = 0.0f; - transformPoint(world, source, &point.x); + rendmath::transformPoint(world, *reinterpret_cast(source), point); // sub_10079610 const float dx = point.x - centre.x; const float dy = point.y - centre.y; const float dz = point.z - centre.z; @@ -379,21 +318,20 @@ bool OverGrowthCell::appendGeometry(void* geometryTemplate, const Mat4* transfor normal.x = 0.0f; normal.y = 0.0f; normal.z = 0.0f; - transformVector(world, source + 3, &normal.x); // +0x0C - normalizeInPlace(normal); + rendmath::transformVector(world, *reinterpret_cast(source + 3), normal); // +0x0C, sub_1007C440 + rendmath::normalize(normal); vertex.normal[2] = static_cast(ftol2((normal.x + 1.0f) * kNormalScale)); vertex.normal[1] = static_cast(ftol2((normal.y + 1.0f) * kNormalScale)); vertex.normal[0] = static_cast(ftol2((normal.z + 1.0f) * kNormalScale)); s_vertices.push_back(vertex); } - vc71::string lowered(textureName); // a copy, + std::string lowered(textureName); // a copy, dx9rend::pathToLower(lowered); // lowered (0x10074D10) const bool tiled = containsCounted(lowered, "tile_", 5); const unsigned int vertexCount = static_cast(s_vertices.size()); const void* const vertices = s_vertices.data(); // &*(begin() + 0), 0x100D2020 - OverGrowthCellMesh* const stream = - field(this, tiled ? kCellTrunkStream : kCellLeafStream); + OverGrowthCellMesh* const stream = tiled ? trunk : leaf; stream->append(vertices, 16, static_cast(vertexCount), material->m_vegetationIndices, static_cast(material->m_vegetationIndexCount)); // +0x2C, answer dropped } @@ -405,13 +343,24 @@ bool OverGrowthCell::appendGeometry(void* geometryTemplate, const Mat4* transfor // Reuses a static transform and pooled lighting records, so the call is not reentrant. // Lighting fields not written here retain their previous pooled values. +// PE 0x100D1050 void OverGrowthCell::draw(IRenderView* view, const Vec3* position, float fade) { (void)position; // arg_4 never read (void)fade; // arg_8 never read +#if defined(__APPLE__) + // [CHOSEN, not recovered] X uses the retained half size; Z reloads its float spill. + const bf2x87::Real half = bf2x87::mul(bf2x87::Real(size), bf2x87::Real(0.5f)); + const float halfSpill = bf2x87::store(half); + Vec3 centre; + centre.y = corner.y; + centre.x = bf2x87::store(bf2x87::add(half, bf2x87::Real(corner.x))); + centre.z = bf2x87::store(bf2x87::add(bf2x87::Real(halfSpill), bf2x87::Real(corner.z))); +#else const Vec3 centre = cellCentre(this); +#endif - static Mat4 s_world = Mat4::getIdentity(); // dword_10258ED0 + static Mat4 s_world = rendmath::constructedIdentity(); // dword_10258ED0, 0x100D109A s_world.m[12] = centre.x; s_world.m[0] = kPositionDecode; s_world.m[5] = kPositionDecode; @@ -428,8 +377,8 @@ void OverGrowthCell::draw(IRenderView* view, const Vec3* position, float fade) } world::LightSource* const sky = g_LightManager->getSkyLight(); // +0x28 - submitCellStream(field(this, kCellLeafStream), s_world, cameraLocal, sky, false); - submitCellStream(field(this, kCellTrunkStream), s_world, cameraLocal, sky, true); + submitCellStream(leaf, s_world, cameraLocal, sky, false); + submitCellStream(trunk, s_world, cameraLocal, sky, true); } } } } diff --git a/Code/BF2/Geom/Overgrowth/OverGrowthCells.cpp b/Code/BF2/Geom/Overgrowth/OverGrowthCells.cpp index 9f8064115..0b77c447c 100644 --- a/Code/BF2/Geom/Overgrowth/OverGrowthCells.cpp +++ b/Code/BF2/Geom/Overgrowth/OverGrowthCells.cpp @@ -2,11 +2,14 @@ // [CHOSEN, not recovered] split from OverGrowth.cpp. Record/field names are [INFERRED]. // Game instances come from level objects; procedural generation requires editorEnable. // Preserve float evaluation order and 24-bit precision. -// [FRONTIER] RaStreamDataEditable device hooks remain unavailable. -// [RETIRE-WHEN: overgrowth-stream-device-reset] Implement the resource-tracker/device hooks -// and verify managed-stream lifecycle through device loss/reset before removing the stops. #ifdef BF2_IMAGE_RENDDX9 +#if defined(__APPLE__) +#include "../../Platform/X87Compat.h" // [CHOSEN, not recovered] x87 conversion results, including invalid inputs. +#endif #include "OverGrowth.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../../Math/PortableX87.h" +#endif #include "OverGrowthCell.h" #include "../MeshTemplate.h" // MeshBounds, meshBoundsCopy / meshBoundsExpand #include "../Terrain.h" // terrainFrustumIntersectsBox (sub_101C7980) @@ -15,26 +18,21 @@ #include "../../RendMisc/IRenderView.h" #include "../../RendDX9/Ra/RaShader.h" // getShader, the object block, RaVertexElementDesc #include "../../RendDX9/Ra/RaStreamDataEditable.h" // the cell's two vertex streams +#include "../../RendDX9/RendDX9Base.h" // setRotationYDegrees (sub_10077E30) +#include "../../RendDX9/RendDX9Math.h" // rendmath::normalize (sub_100777A0) +#include "../../RendDX9/ResourceTracker.h" #include "../../RendDX9/Texture.h" // EngineTexture / textureDtor (sub_10014E20) #include "../../../RendDX9Abi/BfMemory.h" -#include "../../../RendDX9Abi/Vc71String.h" -#include "../../../RendDX9Abi/Vc71Vector.h" +#include // The host interfaces, typed in both flavours (RW-266): every slot called below sits at the retail PE // offset in this tree's MSVC tables in both the native and the retail-ABI build (probe\probe_calls.cmd: // getHeightInWorldCoords(float,float) +0x6C, getNormalInWorldCoords(float,float,Vec3&) +0x7C, IHeightmap // getScale +0x54, IObjectTemplate getCullRadiusScale +0x70 and getAnchorPos +0xAC) and none passes an STL // type. The retail-ABI flavour borrows HfeAbi's IBase, exactly as XpLightManager.cpp does. -#if !BF2_PLUGIN_ABI_NATIVE -#define CORE_IBASE_H -#define CORE_CLASSMANAGER_H -#endif #include "../../Game/Objects/IObjectTemplate.h" #include "../../Physics/HeightmapCluster.h" -#if !BF2_PLUGIN_ABI_NATIVE -#undef CORE_CLASSMANAGER_H -#undef CORE_IBASE_H -#endif +#include "../LcgRandom.h" // lcgrandStep (PE 0x1009EF30) #include #include @@ -54,41 +52,24 @@ extern void* g_renderQueues; // RenderQueues.cpp - dword_1023E408, the Ra sha namespace dice { namespace hfe { namespace geom { -// Shared vegetation records retain fixed strides: instance 0x60, patch 0x98 and cell 0x2AC. -// Instance transforms, spacing and generation flags feed patch coverage and cell batching. +// The vegetation records (OverGrowth.h / OverGrowthCell.h): instance 0x60, patch 0x98 and cell 0x2AC +// bytes in the PE. Instance transforms, spacing and generation flags feed patch coverage and cell +// batching. namespace { -template T& field(void* object, unsigned int offset) -{ return *reinterpret_cast(static_cast(object) + offset); } -template const T& field(const void* object, unsigned int offset) -{ return *reinterpret_cast(static_cast(object) + offset); } - // A raw __thiscall slot on one of RendDX9's OWN objects (geometry instances, the texture's shared // table, the ObjectDrawer's hand-built table) - the house `dispatch` from BundledMesh.cpp. template R dispatch(void* self, unsigned int offset, A... args) { - typedef R(__fastcall* Fn)(void*, void*, A...); - return reinterpret_cast((*static_cast(self))[offset / 4])(self, 0, args...); -} - -// [TEMP] [CHOSEN, not recovered] Known-signature boundaries always report, flush and stop -// (OverGrowth.cpp's house style); the stream's device-reset pair below is the only user. -__declspec(noreturn) void unresolvedAt(const char* qualified) -{ - std::fprintf(stderr, "[FRONTIER] %s reached\n", qualified); - std::fflush(stderr); - std::abort(); + typedef R(__thiscall* Fn)(void*, A...); + return reinterpret_cast((*static_cast(self))[offset / 4])(self, args...); } -const unsigned int kCellBytes = 0x2AC; // sub_1005F320(0x2AC) at 0x100CD6DE -const unsigned int kCellMeshBytes = 0x3C8; // sub_1005F320(0x3C8) at 0x100D0ECE / 0x100D0F2B -const unsigned int kPatchBytes = 0x98; -const unsigned int kInstanceBytes = 0x60; // `imul 2AAAAAABh; sar edx, 4` = /0x60 -const unsigned int kGeometryTypeBytes = 0xA0; // `lea eax,[eax+eax*4]; shl eax, 5` -const unsigned int kMaterialBytes = 0x30; // `imul 2AAAAAABh; sar edx, 3` = /0x30 -const unsigned int kMaterialTypeBytes = 0x5C; // `imul 0B21642C9h; add edx, ecx; sar edx, 6` = /0x5C +// The PE's allocations and strides: the cell sub_1005F320(0x2AC) at 0x100CD6DE, the stream +// sub_1005F320(0x3C8) at 0x100D0ECE / 0x100D0F2B, instances /0x60 (`imul 2AAAAAABh; sar edx, 4`), +// geometry pairs *0xA0, materials /0x30, material types /0x5C. // flt_1020CF68 (0x33800000) = 2^-24 and flt_102193D8 (0x37B40000) = 360 / 2^24. const float kRandomUnit = 5.9604644775390625e-08f; @@ -107,128 +88,6 @@ unsigned char g_overGrowthCellFrustumCull = 1; // byte_1023A040 namespace { -// Compatibility-vector helpers for instance records and pointers, both trivially copyable. -// Inserts grow by half capacity, at least size+count; assignment grows exactly to source size. - -unsigned int vectorSize(const vc71::vector_layout& v, unsigned int bytes) -{ return v.first ? static_cast(v.last - v.first) / bytes : 0u; } -unsigned int vectorCapacity(const vc71::vector_layout& v, unsigned int bytes) -{ return v.first ? static_cast(v.end - v.first) / bytes : 0u; } -unsigned char* vectorElement(const vc71::vector_layout& v, unsigned int index, unsigned int bytes) -{ return reinterpret_cast(v.first) + index * bytes; } - -// _Insert_n(where, count, value) - 100CF0D0 / 100D0270. The value is copied before anything moves. -void vectorInsertN(vc71::vector_layout& v, unsigned int bytes, char* where, unsigned int count, - const void* value) -{ - unsigned char copy[kInstanceBytes]; - std::memcpy(copy, value, bytes); - if (count == 0) - return; - const unsigned int maxSize = 0xFFFFFFFFu / bytes; - const unsigned int size = vectorSize(v, bytes); - if (maxSize - size < count) - throw std::length_error("vector too long"); // _Xlen, sub_100E7130 - const unsigned int capacity = vectorCapacity(v, bytes); - const unsigned int head = v.first ? static_cast(where - v.first) : 0u; - const unsigned int tail = v.first ? static_cast(v.last - where) : 0u; - if (capacity >= size + count) - { - std::memmove(where + count * bytes, where, tail); - for (unsigned int i = 0; i < count; ++i) - std::memcpy(where + i * bytes, copy, bytes); - v.last += count * bytes; - return; - } - unsigned int grown = (maxSize - (capacity >> 1) >= capacity) ? capacity + (capacity >> 1) : 0u; - if (grown < size + count) - grown = size + count; - char* const buffer = static_cast(::renddx9abi::engineAlloc(grown * bytes)); - if (head) - std::memcpy(buffer, v.first, head); - for (unsigned int i = 0; i < count; ++i) - std::memcpy(buffer + head + i * bytes, copy, bytes); - if (tail) - std::memcpy(buffer + head + count * bytes, where, tail); - if (v.first) - ::renddx9abi::engineFree(v.first); - v.end = buffer + grown * bytes; - v.last = buffer + (size + count) * bytes; - v.first = buffer; -} - -// push_back - the inline fast path (0x100CB257 / 0x100D0E62) or _Insert_n(end(), 1, value). -void vectorPushBack(vc71::vector_layout& v, unsigned int bytes, const void* value) -{ - if (v.first && vectorSize(v, bytes) < vectorCapacity(v, bytes)) - { - std::memcpy(v.last, value, bytes); - v.last += bytes; - return; - } - vectorInsertN(v, bytes, v.last, 1, value); -} - -// resize(count, value) - grow through _Insert_n, shrink by erasing the tail. -void vectorResize(vc71::vector_layout& v, unsigned int bytes, unsigned int count, const void* value) -{ - const unsigned int size = vectorSize(v, bytes); - if (size < count) - vectorInsertN(v, bytes, v.last, count - size, value); - else if (v.first && count < size) - v.last = v.first + count * bytes; -} - -// _Tidy - free the buffer and zero first/last/end (the allocator word is never written). -void vectorTidy(vc71::vector_layout& v) -{ - if (v.first) - ::renddx9abi::engineFree(v.first); - v.first = 0; - v.last = 0; - v.end = 0; -} - -// operator= - 100D0700 (instances). -void vectorAssign(vc71::vector_layout& dst, const vc71::vector_layout& src, unsigned int bytes) -{ - if (&dst == &src) - return; - const unsigned int count = vectorSize(src, bytes); - if (count == 0) - { - vectorTidy(dst); - return; - } - const unsigned int size = vectorSize(dst, bytes); - if (count <= size) // copy, then drop the tail - { - std::memmove(dst.first, src.first, count * bytes); - dst.last = dst.first + count * bytes; - return; - } - if (count <= vectorCapacity(dst, bytes)) // copy the overlap, construct the rest - { - std::memmove(dst.first, src.first, size * bytes); - std::memcpy(dst.last, src.first + size * bytes, (count - size) * bytes); - dst.last = dst.first + count * bytes; - return; - } - if (dst.first) - ::renddx9abi::engineFree(dst.first); - dst.first = 0; // _Buy (100CE6D0) zeroes first - dst.last = 0; - dst.end = 0; - if (count > 0xFFFFFFFFu / bytes) - throw std::length_error("vector too long"); - char* const buffer = static_cast(::renddx9abi::engineAlloc(count * bytes)); - dst.end = buffer + count * bytes; - dst.first = buffer; - dst.last = buffer; - std::memcpy(buffer, src.first, count * bytes); // _Ucopy (100CFC90) - dst.last = buffer + count * bytes; -} - // Local placement math helpers. @@ -244,96 +103,42 @@ float clampFloat(float value, float low, float high) return value; } -// sub_100777A0 - normalise in place unless |v|^2 is within FLT_EPSILON (flt_10208958) of 1; below -// FLT_EPSILON it zeroes and answers -20001. |v|^2 is ((x*x + y*y) + z*z). -int normalizeVec3(Vec3& v) -{ - const float lengthSquared = v.x * v.x + v.y * v.y + v.z * v.z; - if (std::fabs(lengthSquared - 1.0f) < 1.1920928955078125e-07f) - return 0; - if (std::fabs(lengthSquared) < 1.1920928955078125e-07f) - { - v.x = 0.0f; - v.y = 0.0f; - v.z = 0.0f; - return -20001; - } - const float scale = 1.0f / std::sqrt(lengthSquared); - v.x = scale * v.x; - v.y = scale * v.y; - v.z = scale * v.z; - return 0; -} - -// sub_10077E30 (retn 4) - the Y rotation: identity, then m0 = cos, m2 = -sin, m8 = sin, m10 = cos of -// flt_10238738 (0x3C8EFA35, pi/180 in .data, never written) times the angle, through x87 fsincos on the -// float-rounded radians (0x10077E36..0x10077E92). -void setRotationY(Mat4& matrix, float degrees) -{ - const float radians = 0.01745329238474369f * degrees; - float sine; - float cosine; - __asm - { - fld radians - fsincos - fstp cosine - fstp sine - } - for (unsigned int i = 0; i < 16; ++i) - matrix.m[i] = 0.0f; - matrix.m[0] = 1.0f; - matrix.m[5] = 1.0f; - matrix.m[10] = 1.0f; - matrix.m[15] = 1.0f; - matrix.m[0] = cosine; - matrix.m[2] = -sine; - matrix.m[8] = sine; - matrix.m[10] = cosine; -} +} // anonymous namespace -// sub_100C8820 - re-orthonormalise a basis keeping its y row: normalise rows 1 and 2, row0 = row1 x -// row2, row2 = row0 x row1 (from the new row0). Operand order as the fmul pairs read. +// sub_100C8820 - re-orthonormalise a basis keeping its y row: normalise rows 1 and 2 (sub_100777A0), +// row0 = row1 x row2, row2 = row0 x row1 (from the new row0). Operand order as the fmul pairs read; +// each component's two products and their difference stay on the x87 stack until the store. The +// directional shadow pass (XpLightManager.cpp) uses it as well. void orthonormalizeKeepingY(Mat4& matrix) { + using rendmath::ld; + using rendmath::st; Vec3& row0 = *reinterpret_cast(&matrix.m[0]); Vec3& row1 = *reinterpret_cast(&matrix.m[4]); Vec3& row2 = *reinterpret_cast(&matrix.m[8]); - normalizeVec3(row1); - normalizeVec3(row2); - row0.x = row2.z * row1.y - row2.y * row1.z; - row0.y = row1.z * row2.x - row2.z * row1.x; - row0.z = row2.y * row1.x - row1.y * row2.x; - row2.x = row1.z * row0.y - row1.y * row0.z; - row2.y = row1.x * row0.z - row1.z * row0.x; - row2.z = row1.y * row0.x - row1.x * row0.y; + rendmath::normalize(row1); + rendmath::normalize(row2); + row0.x = st(ld(row2.z) * ld(row1.y) - ld(row2.y) * ld(row1.z)); + row0.y = st(ld(row1.z) * ld(row2.x) - ld(row2.z) * ld(row1.x)); + row0.z = st(ld(row2.y) * ld(row1.x) - ld(row1.y) * ld(row2.x)); + row2.x = st(ld(row1.z) * ld(row0.y) - ld(row1.y) * ld(row0.z)); + row2.y = st(ld(row1.x) * ld(row0.z) - ld(row1.z) * ld(row0.x)); + row2.z = st(ld(row1.y) * ld(row0.x) - ld(row1.x) * ld(row0.y)); } -// lcgrand_step, sub_1009EF30 - RendDX9's copy of dice::hfe::Random::getRaw: two Schrage steps of the -// Law-Kelton lcgrand (24112 = 0x5E30, then 26143 = 0x661F) over the owner's +0x18. Written in unsigned -// arithmetic with the shipped `sar`s (NametagManager.cpp's randomStep, repeated TU-locally). -unsigned int randomStep(unsigned int value, unsigned int multiplier) -{ - const unsigned int low = (value & 0xFFFFu) * multiplier; - const unsigned int high = static_cast(static_cast(value) >> 16) * multiplier; - const int middle = static_cast((low >> 16) + high); - const unsigned int next = (low & 0xFFFFu) + ((static_cast(middle) & 0x7FFFu) << 16) - + static_cast(middle >> 15); - const int reduced = static_cast(next - 0x7FFFFFFFu); - return reduced < 0 ? next : static_cast(reduced); -} +namespace { // Every draw in this half is `lcgrand_step(this + 0x18); or al, 80h; sar eax, 7; add eax, 1` - a count // in [1, 2^24] (0x100C9995, 0x1015E895, 0x100CCA00). int random24(OverGrowth* self) { - unsigned int& seed = field(self, 0x18); - seed = randomStep(randomStep(seed, 24112u), 26143u); + unsigned int& seed = self->m_randomSeed; + lcgrandStep(&seed); // geom/LcgRandom.h return (static_cast(seed | 0x80u) >> 7) + 1; } world::IHeightmapCluster* heightmapCluster(OverGrowth* self) -{ return field(self, 0xAC); } // initialize: "HeightmapCluster" +{ return self->m_cluster; } // initialize: "HeightmapCluster" // sub_101C5C50 (retn 8) - does the sphere (point, radius) reach the box? The squared distance from the @@ -375,93 +180,26 @@ bool boundsSphereIntersects(const MeshBounds& bounds, const Vec3& point, float r return distance <= radius * radius; } -// The 96-byte eight-corner box: sub_100CE120 (retn 8) zeroes the 24 floats and then calls -// sub_101C6750 (min/max to corners, in bit order x = 4, y = 2, z = 1) and sub_101C67F0 (every corner -// through the full matrix). sub_101C67F0 associates corner 0's x and y sums differently from corners -// 1-7; both orders are kept (BundledMeshDraw.cpp's worldHeight reads the same body the same way). -struct OverGrowthBoxCorners -{ - float corner[8][3]; -}; +} // anonymous namespace +// The 96-byte eight-corner box (OverGrowthCell.h): the BoxCorners constructor (cited in +// BoxCorners.h) over the MeshBounds, which is the LocalBoundingBox record (MeshTemplate.cpp asserts +// the layout). The load half (OverGrowthLoad.cpp) uses it too. void constructBoxCorners(OverGrowthBoxCorners& box, const MeshBounds& bounds, const Mat4& world) { - for (unsigned int i = 0; i < 8; ++i) - for (unsigned int j = 0; j < 3; ++j) - box.corner[i][j] = 0.0f; - for (unsigned int i = 0; i < 8; ++i) - { - box.corner[i][0] = (i & 4) ? bounds.max.x : bounds.min.x; - box.corner[i][1] = (i & 2) ? bounds.max.y : bounds.min.y; - box.corner[i][2] = (i & 1) ? bounds.max.z : bounds.min.z; - } - const float* const m = world.m; - for (unsigned int i = 0; i < 8; ++i) - { - float* const c = box.corner[i]; - const float x = c[0]; - const float y = c[1]; - const float z = c[2]; - float tx; - float ty; - float tz; - if (i == 0) - { - tz = m[2] * x + z * m[10] + y * m[6] + m[14]; - ty = m[1] * x + y * m[5] + z * m[9] + m[13]; - tx = m[8] * z + m[0] * x + y * m[4] + m[12]; - } - else - { - tz = z * m[10] + x * m[2] + y * m[6] + m[14]; - ty = x * m[1] + z * m[9] + y * m[5] + m[13]; - tx = m[4] * y + z * m[8] + x * m[0] + m[12]; - } - c[0] = tx; - c[1] = ty; - c[2] = tz; - } -} - -// sub_101C6E10 - the component-wise minimum: `if (current > corner) current = corner` (test ah, 41h). -Vec3 boxCornersMin(const OverGrowthBoxCorners& box) -{ - Vec3 out; - out.x = box.corner[0][0]; - out.y = box.corner[0][1]; - out.z = box.corner[0][2]; - for (unsigned int i = 1; i < 8; ++i) - { - if (out.x > box.corner[i][0]) out.x = box.corner[i][0]; - if (out.y > box.corner[i][1]) out.y = box.corner[i][1]; - if (out.z > box.corner[i][2]) out.z = box.corner[i][2]; - } - return out; -} - -// sub_101C6C70 - the component-wise maximum: `if (current < corner) current = corner` (test ah, 5). -Vec3 boxCornersMax(const OverGrowthBoxCorners& box) -{ - Vec3 out; - out.x = box.corner[0][0]; - out.y = box.corner[0][1]; - out.z = box.corner[0][2]; - for (unsigned int i = 1; i < 8; ++i) - { - if (out.x < box.corner[i][0]) out.x = box.corner[i][0]; - if (out.y < box.corner[i][1]) out.y = box.corner[i][1]; - if (out.z < box.corner[i][2]) out.z = box.corner[i][2]; - } - return out; + box = BoxCorners(reinterpret_cast(bounds), world); } -// sub_101C5450 (retn 4) - grow the MeshBounds by the corners' minimum, then their maximum. +// sub_101C5450 (retn 4) - grow the MeshBounds by the corners' minimum (BoxCorners::minimum, +// PE 0x101C6E10), then their maximum (BoxCorners::maximum, PE 0x101C6C70). void boundsExpandByCorners(MeshBounds& bounds, const OverGrowthBoxCorners& box) { - meshBoundsExpand(bounds, boxCornersMin(box)); - meshBoundsExpand(bounds, boxCornersMax(box)); + meshBoundsExpand(bounds, box.minimum()); + meshBoundsExpand(bounds, box.maximum()); } +namespace { + // The geometry instance slots this half reads (RendDX9's own StaticMesh table; StaticMesh.h names them): // +0x38 getTemplate, +0x40 getLocalBounds (min/max at +0 / +0xC), +0x44 getBoundingRadius. void* geometryTemplate(void* geometry) { return dispatch(geometry, 0x38); } @@ -473,6 +211,8 @@ float geometryBoundingRadius(void* geometry) { return dispatch(geometry, // Density and shadow maps share the stored width and height. +} // anonymous namespace + // sub_100C88F0 (retn 18h) - world (x, z) to shadow/density map coordinates through the primary // heightmap's scale (+0xA8, IHeightmap::getScale called twice, as shipped). The integer part is the // floor, re-centred by width/2 (unsigned shr); the fraction goes out separately. @@ -480,7 +220,7 @@ float geometryBoundingRadius(void* geometry) { return dispatch(geometry, // rejected here. Preserved. void shadowCoords(OverGrowth* self, float x, float z, int* ix, int* iz, float* fx, float* fz) { - world::IHeightmap* const heightmap = field(self, 0xA8); + world::IHeightmap* const heightmap = self->m_heightmap; const float scaledX = x / heightmap->getScale().x; // vslot +0x54, 0x100C88FC const float scaledZ = z / heightmap->getScale().z; // vslot +0x54 again, 0x100C8911 const float floorX = static_cast(std::floor(static_cast(scaledX))); @@ -489,17 +229,18 @@ void shadowCoords(OverGrowth* self, float x, float z, int* ix, int* iz, float* f *fz = scaledZ - floorZ; *ix = static_cast(floorX); *iz = static_cast(floorZ); - *ix = static_cast(static_cast(*ix) + (field(self, 0x78) >> 1)); - *iz = static_cast(static_cast(*iz) + (field(self, 0x7C) >> 1)); - if (static_cast(*ix) > field(self, 0x78) || *ix < 0) + *ix = static_cast(static_cast(*ix) + (self->m_mapWidth >> 1)); + *iz = static_cast(static_cast(*iz) + (self->m_mapHeight >> 1)); + if (static_cast(*ix) > self->m_mapWidth || *ix < 0) *ix = 0; - if (static_cast(*iz) > field(self, 0x7C) || *iz < 0) + if (static_cast(*iz) > self->m_mapHeight || *iz < 0) *iz = 0; } // sub_100C92F0 (retn 8) - the bilinear shadow-map value at (x, z): four taps (byte * 1/255, // flt_101E2B98 = 0x3B808081; a tap outside the map is 0), blended ((s10 - s00) * fx + s00) and -// ((s11 - s01) * fx + s01), then ((b - a) * fz + a). +// ((s11 - s01) * fx + s01), then ((b - a) * fz + a). Also reached from the load half's addStaticObjects +// (OverGrowthLoad.cpp). float sampleShadow(OverGrowth* self, float x, float z) { int ix; @@ -508,9 +249,9 @@ float sampleShadow(OverGrowth* self, float x, float z) float fz; shadowCoords(self, x, z, &ix, &iz, &fx, &fz); const float k = 0.003921568859368563f; - const unsigned char* const shadow = field(self, 0x84); - const unsigned int width = field(self, 0x78); - const unsigned int height = field(self, 0x7C); + const unsigned char* const shadow = self->m_shadowMap; + const unsigned int width = self->m_mapWidth; + const unsigned int height = self->m_mapHeight; const int ix1 = ix + 1; const int iz1 = iz + 1; float s00 = 0.0f; @@ -534,13 +275,14 @@ float sampleShadow(OverGrowth* self, float x, float z) // map cell to the far corner's (inclusive, rows then columns), then coverage[i] = count[i] / texels for // the first sixteen values. The two ends come from shadowCoords, so a patch touching the map's far edge // reads texel index == width (the next row's first byte, or one past the buffer on the last row) - the -// shipped clamp's off-by-one, preserved. -void computeCoverage(OverGrowth* self, unsigned char* patch) +// shipped clamp's off-by-one, preserved. The load half's computePatchDensities (sub_100CA450) and +// sub_100CA3A0 call it too. +void computeCoverage(OverGrowth* self, OverGrowthPatch* patch) { - const float x0 = field(patch, 0x00); - const float z0 = field(patch, 0x08); - const float x1 = field(self, 0x14) + field(patch, 0x00); - const float z1 = field(self, 0x14) + field(patch, 0x08); + const float x0 = patch->position.x; + const float z0 = patch->position.z; + const float x1 = self->m_cellSize + patch->position.x; + const float z1 = self->m_cellSize + patch->position.z; int ix0; int iz0; int ix1; @@ -552,45 +294,47 @@ void computeCoverage(OverGrowth* self, unsigned char* patch) unsigned int counts[256]; for (unsigned int i = 0; i < 256; ++i) counts[i] = 0; - const unsigned char* const density = field(self, 0x80); + const unsigned char* const density = self->m_densityMap; for (int iz = iz0; iz <= iz1; ++iz) for (int ix = ix0; ix <= ix1; ++ix) - ++counts[density[field(self, 0x78) * iz + ix]]; + ++counts[density[self->m_mapWidth * iz + ix]]; const int texels = (iz1 - iz0 + 1) * (ix1 - ix0 + 1); const float total = static_cast(static_cast(texels)); for (unsigned int i = 0; i < 16; ++i) - field(patch, 0x1C + i * 4) = static_cast(counts[i]) / total; + patch->coverage[i] = static_cast(counts[i]) / total; } +namespace { + // sub_1015EB20 (retn 4) - the material whose density value (+0x1C) is `value`, or null. -unsigned char* findMaterial(OverGrowth* self, int value) +OverGrowthMaterial* findMaterial(OverGrowth* self, int value) { - const vc71::vector_layout& materials = field(self, 0x3C); - for (unsigned int i = 0; i < vectorSize(materials, kMaterialBytes); ++i) + std::vector& materials = self->m_materials; + for (unsigned int i = 0; i < materials.size(); ++i) { - unsigned char* const material = vectorElement(materials, i, kMaterialBytes); - if (field(material, 0x1C) == value) + OverGrowthMaterial* const material = &materials[i]; + if (static_cast(material->id) == value) return material; } return 0; } // sub_100C88C0 (retn 8) - patches[z * patchCountX + x]. -unsigned char* patchAt(OverGrowth* self, int x, int z) -{ return field(self, 0xE0) + (field(self, 0xD8) * z + x) * kPatchBytes; } +OverGrowthPatch* patchAt(OverGrowth* self, int x, int z) +{ return self->m_patches + (self->m_patchCountX * z + x); } // sub_1015E880 (retn 8) - a uniformly random point of the patch's cell square, dropped onto the terrain; // answers the density value there (vslot +0x18). Two draws: x first, then z; the cell size is re-read // between them. Each offset is ((float)count * cellSize) * 2^-24. -unsigned int pickPosition(OverGrowth* self, const unsigned char* patch, Vec3* out) +unsigned int pickPosition(OverGrowth* self, const OverGrowthPatch* patch, Vec3* out) { - const float cellSizeX = field(self, 0x14); + const float cellSizeX = self->m_cellSize; const float offsetX = static_cast(random24(self)) * cellSizeX * kRandomUnit; - const float cellSizeZ = field(self, 0x14); + const float cellSizeZ = self->m_cellSize; const float offsetZ = static_cast(random24(self)) * cellSizeZ * kRandomUnit; - out->x = offsetX + field(patch, 0x00); - out->y = field(patch, 0x04); - out->z = offsetZ + field(patch, 0x08); + out->x = offsetX + patch->position.x; + out->y = patch->position.y; + out->z = offsetZ + patch->position.z; out->y = heightmapCluster(self)->getHeightInWorldCoords(out->x, out->z); // vslot +0x6C return self->sampleDensity(out->x, out->z); // vslot +0x18, 0x1015E919 } @@ -600,10 +344,10 @@ unsigned int pickPosition(OverGrowth* self, const unsigned char* patch, Vec3* ou // last x is (x0 + size) - size, not x0), then one fsqrt. `m = m < d ? m : d` (fcom; jnp keeps m). float cellDistanceToPoint(const OverGrowthCell* cell, const Vec3* point) { - float cornerX = field(cell, 0x08); - const float cornerY = field(cell, 0x0C); - float cornerZ = field(cell, 0x10); - const float size = field(cell, 0x14); + float cornerX = cell->corner.x; + const float cornerY = cell->corner.y; + float cornerZ = cell->corner.z; + const float size = cell->size; float dx = cornerX - point->x; float dy = cornerY - point->y; float dz = cornerZ - point->z; @@ -632,49 +376,61 @@ float cellDistanceToPoint(const OverGrowthCell* cell, const Vec3* point) // ecx = a, edx = b). Both compare the camera distance +0x1C. 1015E580 answers a < b (test ah, 5 / jp); // 1015E5A0 answers a > b (test ah, 41h / jnz). bool cellNearerFirst(const OverGrowthCell* a, const OverGrowthCell* b) -{ return field(a, 0x1C) < field(b, 0x1C); } +{ return a->cameraDistance < b->cameraDistance; } bool cellFartherFirst(const OverGrowthCell* a, const OverGrowthCell* b) -{ return field(a, 0x1C) > field(b, 0x1C); } +{ return a->cameraDistance > b->cameraDistance; } + +} // anonymous namespace // sub_1015E930 - the instance's default constructor. The matrix half is the retail Mat4() inlined: all // sixteen zeroed, then 1.0f on the diagonal. +0x54 (the shadow value) and the pad after +0x58 are NOT // written - every shipped user stores +0x54 before reading it. -void constructInstance(unsigned char* instance) +void constructInstance(OverGrowthInstance& instance) { - field(instance, 0x00) = -1; + instance.geometryIndex = -1; for (unsigned int i = 0; i < 16; ++i) - field(instance, 0x04 + i * 4) = 0.0f; - field(instance, 0x40) = 1.0f; - field(instance, 0x2C) = 1.0f; - field(instance, 0x18) = 1.0f; - field(instance, 0x04) = 1.0f; - field(instance, 0x44) = 1.0f; - field(instance, 0x48) = 0.0f; - field(instance, 0x4C) = 0.0f; - field(instance, 0x50) = 0.0f; - field(instance, 0x58) = 0; - field(instance, 0x5C) = 1.0f; + instance.transform.m[i] = 0.0f; + instance.transform.m[15] = 1.0f; + instance.transform.m[10] = 1.0f; + instance.transform.m[5] = 1.0f; + instance.transform.m[0] = 1.0f; + instance.scale = 1.0f; + instance.cullRadius = 0.0f; + instance.radiusToSame = 0.0f; + instance.radiusToOthers = 0.0f; + instance.generated = 0; + instance.lodFadeState = 1.0f; } +namespace { + // The occlusion query update() makes for every candidate cell: `mov ecx, dword_1025A39C; call // [eax+3Ch]` with the cell's MeshBounds (0x1015F32B), through the drawer's table like the PE and -// unguarded. The slot is ObjectDrawer::isBoundsOccluded (0x100F8000, Geom/ObjectDrawer.cpp). It -// refreshes the box's derived data IN place when its dirty byte is set, hence the non-const box. +// unguarded. The slot is ObjectDrawer::isBoundsOccluded (Geom/ObjectDrawer.cpp). It refreshes the +// box's derived data IN place when its dirty byte is set, hence the non-const box. bool objectDrawerOccludes(MeshBounds& bounds) { + // The slot's body is PE 0x100F8000. return dispatch(static_cast(dx9rend::g_ObjectDrawer), 0x3C, static_cast(&bounds)); } // The texture store rebuildCells inlines for each stream (0x100CAE5E..0x100CAEAC, 0x100CAEAC..0x100CAEFA): -// the stream's material-block texture slot (+0xC8) takes the level OverGrowth's atlas texture (+0x100 of -// dword_10258F38 - the global, not `this`). An unchanged pointer is left alone; the old one is released -// owner-side (`if (!--ref) { sub_10014E20; free }`, the slot is not cleared first) and the new one is -// addRef'd through its shared table's +0x08. -void assignAtlasTexture(unsigned char* stream) +// the stream's material-block texture slot (stream +0xC8, block +0xBC) takes the level OverGrowth's +// atlas texture (+0x100 of dword_10258F38 - the global, not `this`). An unchanged pointer is left alone; +// the old one is released owner-side (`if (!--ref) { sub_10014E20; free }`, the slot is not cleared +// first) and the new one is addRef'd through its shared table's +0x08. The block's Ra shader word +// (stream +0x158, raMaterialShaderSlot): rebuildCells stores "LeafOG" / "TrunkOG" there. +inline RaMaterialParameters& streamMaterial(OverGrowthCellMesh* stream) +{ + return *reinterpret_cast(stream->m_materialParameters); +} +void assignAtlasTexture(OverGrowthCellMesh* stream) { - dx9rend::EngineTexture* const atlas = field(dx9rend::g_OverGrowth, 0x100); - dx9rend::EngineTexture* const old = field(stream, 0xC8); + dx9rend::EngineTexture* const atlas = static_cast(dx9rend::g_OverGrowth)->m_atlasPage; + dx9rend::EngineTexture*& slot = + *reinterpret_cast(&streamMaterial(stream).diffuseMap.value); // block +0xBC + dx9rend::EngineTexture* const old = slot; if (old == atlas) return; if (old && --old->refCount == 0) @@ -682,7 +438,7 @@ void assignAtlasTexture(unsigned char* stream) dx9rend::textureDtor(old); ::renddx9abi::engineFree(old); } - field(stream, 0xC8) = atlas; + slot = atlas; if (atlas) dispatch(static_cast(atlas), 0x08); // the shared table's addRef } @@ -693,11 +449,11 @@ void assignAtlasTexture(unsigned char* stream) // OverGrowthCellMesh OverGrowthCellMesh::OverGrowthCellMesh(unsigned int vertexCapacity, unsigned int indexCapacity, - const vc71::vector_layout& elements) + const std::vector& elements) : RaStreamDataEditable(vertexCapacity, indexCapacity, 16u, elements, dx9rend::Ra::raRendererDevice()) { dx9rend::Ra::raObjectParametersConstruct(m_objectParameters); // sub_100458E0(this + 0x1A4) - field(this, 0x354) = 1.0f; + objectParameters().transparency.value = 1.0f; // this + 0x354 } // 100D0C60 (retn 4) - the block (sub_1004D900), then RaStreamDataEditable's members (sub_10048F00), then @@ -711,16 +467,39 @@ void* OverGrowthCellMesh::destroy(unsigned char flags) return this; } -// [TEMP] [CHOSEN, not recovered] RaStreamDataEditable's device-reset pair. Nothing in this tree calls -// either slot; declared only so +0x38/+0x3C land at their retail offsets. -// [RETIRE-WHEN: overgrowth-stream-device-reset] - the pair recovered into RaStreamDataEditable.cpp. +// PE 0x10048D60: unregister and release the vertex buffer, then the index buffer. void OverGrowthCellMesh::releaseBuffers() { - unresolvedAt("dice::hfe::dx9rend::Ra::RaStreamDataEditable +0x30 (10048D60, release the D3D buffers)"); + if (m_vertexBuffer) + { + dx9rend::resourceTrackerRemove(1, m_vertexBuffer); + m_vertexBuffer->Release(); + } + if (m_indexBuffer) + { + dx9rend::resourceTrackerRemove(2, m_indexBuffer); + m_indexBuffer->Release(); + } + // shipped defect: both released pointers are left unchanged. } + +// PE 0x10048C70: recreate the managed, write-only streams when a device exists. void OverGrowthCellMesh::createBuffers() { - unresolvedAt("dice::hfe::dx9rend::Ra::RaStreamDataEditable +0x40 (10048C70, create the D3D buffers)"); + if (m_device) + { + m_device->CreateVertexBuffer(m_stride * m_vertexCapacity, D3DUSAGE_WRITEONLY, 0, + D3DPOOL_MANAGED, &m_vertexBuffer, 0); + const int vertexPool = 1; + // The PE registers the result even when the unchecked create failed. + dx9rend::resourceTrackerRegister(1, m_vertexBuffer, m_stride * m_vertexCapacity, + std::string(""), &vertexPool, 0); + m_device->CreateIndexBuffer(m_indexCapacity * m_indexSize, D3DUSAGE_WRITEONLY, + D3DFMT_INDEX16, D3DPOOL_MANAGED, &m_indexBuffer, 0); + const int indexPool = 1; + dx9rend::resourceTrackerRegister(2, m_indexBuffer, m_indexCapacity * m_indexSize, + std::string(""), &indexPool, 0); + } } // 10048EF0: `mov eax, [ecx+190h]; sub eax, [ecx+18Ch]`. @@ -730,72 +509,98 @@ unsigned int OverGrowthCellMesh::getVertexCapacity() const { return m_vertexCapa unsigned int OverGrowthCellMesh::getIndexCapacity() const { return m_indexCapacity; } +namespace { + +// PE 0x1015E6D0: the abstract cell base's constructor - not visible, not built, empty, the corner, +// sizes and bounds zeroed with the bounds dirty, and both world indices unplaced. The base table it +// publishes is replaced by the derived one at once, so it is not modelled. +void constructCellBase(OverGrowthCell& cell) +{ + cell.visible = 0; + cell.built = 0; + cell.empty = 1; + cell.corner.x = 0.0f; // +0x08..+0x3C zeroed + cell.corner.y = 0.0f; + cell.corner.z = 0.0f; + cell.size = 0.0f; + cell.fadeFactor = 0.0f; + cell.cameraDistance = 0.0f; + cell.bounds.min.x = 0.0f; + cell.bounds.min.y = 0.0f; + cell.bounds.min.z = 0.0f; + cell.bounds.max.x = 0.0f; + cell.bounds.max.y = 0.0f; + cell.bounds.max.z = 0.0f; + cell.bounds.originRadius = 0.0f; + cell.bounds.radius = 0.0f; + cell.bounds.dirty = 1; // +0x40 + cell.bounds.extent.x = 0.0f; // +0x44..+0x58 zeroed + cell.bounds.extent.y = 0.0f; + cell.bounds.extent.z = 0.0f; + cell.bounds.center.x = 0.0f; + cell.bounds.center.y = 0.0f; + cell.bounds.center.z = 0.0f; + cell.cellX = 0x2CEE9D7; + cell.cellZ = 0x2CEE9D7; +} + +} // anonymous namespace + // Initializes an unplaced cell and its leaf/trunk streams using the global level budgets. // Vertices use SHORT4 position, D3DCOLOR normal, and SHORT2 texcoord (16 bytes total). // Failed engine allocations leave the corresponding stream null. OverGrowthCell::OverGrowthCell() + : farList() { - - field(this, 0x04) = 0; - field(this, 0x05) = 0; - field(this, 0x06) = 1; - for (unsigned int offset = 0x08; offset <= 0x3C; offset += 4) - field(this, offset) = 0; - field(this, 0x40) = 1; - for (unsigned int offset = 0x44; offset <= 0x58; offset += 4) - field(this, offset) = 0; - field(this, 0x5C) = 0x2CEE9D7; - field(this, 0x60) = 0x2CEE9D7; - - - field(this, 0x64) = 0; - dx9rend::Ra::raObjectParametersConstruct(&field(this, 0x68)); - field(this, 0x290) = 0; - field(this, 0x294) = 0; - field(this, 0x298) = 0; - field(this, 0x29C) = 0; - field(this, 0x2A0) = 0; + constructCellBase(*this); + hasNear = 0; + dx9rend::Ra::raObjectParametersConstruct(objectParameters); + unresolved29C = 0; + lastPatch = 0; static const dx9rend::Ra::RaVertexElementDesc s_position(0, 7, 0, "Vtx_Position"); static const dx9rend::Ra::RaVertexElementDesc s_normal(1, 4, 3, "Vtx_Normal"); static const dx9rend::Ra::RaVertexElementDesc s_texCoord(2, 6, 5, "Vtx_TBase"); - vc71::vector_layout elements = { 0, 0, 0, 0 }; - const dx9rend::Ra::RaVertexElementDesc* element = &s_position; - vectorInsertN(elements, 4u, elements.last, 1, &element); // (the empty vector) - element = &s_normal; - vectorPushBack(elements, 4u, &element); - element = &s_texCoord; - vectorPushBack(elements, 4u, &element); - - void* const owner = dx9rend::g_OverGrowth; - void* const leafMemory = ::renddx9abi::engineAlloc(kCellMeshBytes); - field(this, 0x2A4) = leafMemory - ? ::new (leafMemory) OverGrowthCellMesh(field(owner, 0x104), - field(owner, 0x10C), elements) + // The stream's element descriptors (insert into the empty vector, then two push_backs). + std::vector elements; + elements.push_back(&s_position); + elements.push_back(&s_normal); + elements.push_back(&s_texCoord); + + const OverGrowth* const owner = static_cast(dx9rend::g_OverGrowth); + void* const leafMemory = ::renddx9abi::engineAlloc(sizeof(OverGrowthCellMesh)); + leaf = leafMemory + ? ::new (leafMemory) OverGrowthCellMesh(owner->m_streamVertexCounts[0], + owner->m_streamIndexCounts[0], elements) : 0; - void* const trunkMemory = ::renddx9abi::engineAlloc(kCellMeshBytes); - field(this, 0x2A8) = trunkMemory - ? ::new (trunkMemory) OverGrowthCellMesh(field(owner, 0x108), - field(owner, 0x110), elements) + void* const trunkMemory = ::renddx9abi::engineAlloc(sizeof(OverGrowthCellMesh)); + trunk = trunkMemory + ? ::new (trunkMemory) OverGrowthCellMesh(owner->m_streamVertexCounts[1], + owner->m_streamIndexCounts[1], elements) : 0; - vectorTidy(elements); } -// +0x00: PE 0x100D1890 (the scalar deleting wrapper) over 0x100D18B0 (the body, read in full) and -// (the base destructor, which only republishes the base table - not modelled). Each stream is -// destroyed through its own +0x00 with 1 (no null store afterwards), the far list is freed and zeroed, -// then the Ra object block (sub_1004D900). +// PE 0x100D18B0: the destructor body, then the base destructor (0x1015E5C0, which only +// republishes the base table - not modelled). Each stream is destroyed through its own +0x00 with 1 +// (no null store afterwards), the far list is freed, then the Ra object block (sub_1004D900); the +// cell's members are then destroyed. +OverGrowthCell::~OverGrowthCell() +{ + OverGrowthCellMesh* const leafStream = leaf; + if (leafStream) + leafStream->destroy(1); + OverGrowthCellMesh* const trunkStream = trunk; + if (trunkStream) + trunkStream->destroy(1); + std::vector().swap(farList); + dx9rend::Ra::raObjectParametersDestroy(objectParameters); +} + +// +0x00: PE 0x100D1890, the scalar deleting wrapper over the destructor. void* OverGrowthCell::destroy(unsigned char flags) { - OverGrowthCellMesh* const leaf = field(this, 0x2A4); - if (leaf) - leaf->destroy(1); - OverGrowthCellMesh* const trunk = field(this, 0x2A8); - if (trunk) - trunk->destroy(1); - vectorTidy(field(this, 0x28C)); - dx9rend::Ra::raObjectParametersDestroy(&field(this, 0x68)); + this->~OverGrowthCell(); if (flags & 1) ::renddx9abi::engineFree(this); return this; @@ -804,17 +609,19 @@ void* OverGrowthCell::destroy(unsigned char flags) // +0x04, appendGeometry, the LOD-vertex packer: OverGrowthCellRender.cpp. // +0x08, leaf then trunk, each through its own +0x24 (lock); no null tests. +// PE 0x100D1010 void OverGrowthCell::lock() { - field(this, 0x2A4)->lock(); - field(this, 0x2A8)->lock(); + leaf->lock(); + trunk->lock(); } // +0x0C, the same pair through +0x28 (unlock). +// PE 0x100D1030 void OverGrowthCell::unlock() { - field(this, 0x2A4)->unlock(); - field(this, 0x2A8)->unlock(); + leaf->unlock(); + trunk->unlock(); } // +0x10, draw, the cell's two render-queue submissions: OverGrowthCellRender.cpp. @@ -822,30 +629,31 @@ void OverGrowthCell::unlock() // +0x14, leaf +0x38 first, then trunk +0x38, summed. unsigned int OverGrowthCell::getVertexCapacity() { - const unsigned int leaf = field(this, 0x2A4)->getVertexCapacity(); - return leaf + field(this, 0x2A8)->getVertexCapacity(); + const unsigned int leafCapacity = leaf->getVertexCapacity(); + return leafCapacity + trunk->getVertexCapacity(); } // +0x18, the same through +0x3C. unsigned int OverGrowthCell::getIndexCapacity() { - const unsigned int leaf = field(this, 0x2A4)->getIndexCapacity(); - return leaf + field(this, 0x2A8)->getIndexCapacity(); + const unsigned int leafCapacity = leaf->getIndexCapacity(); + return leafCapacity + trunk->getIndexCapacity(); } // +0x1C, PE 0x100D1880 (16 B): `push 0; push 0; add ecx, 28Ch; call sub_100CF850` - the far list's // resize(0) (erase, the buffer is kept). void OverGrowthCell::clearFarList() { - const void* const none = 0; - vectorResize(field(this, 0x28C), 4u, 0u, &none); + OverGrowthInstance* const none = 0; + farList.resize(0u, none); } -// The allocation postLoadResources makes per grid slot (0x100CD6DE..0x100CD6FB): sub_1005F320(0x2AC), then -// the constructor when the heap answered. Published for the load half. +// The allocation postLoadResources makes per grid slot (0x100CD6DE..0x100CD6FB): operator new(0x2AC), +// then the constructor when the heap answered. Published for the load half. OverGrowthCell* createOverGrowthCell() { - void* const memory = ::renddx9abi::engineAlloc(kCellBytes); + // operator new is sub_1005F320. + void* const memory = ::renddx9abi::engineAlloc(sizeof(OverGrowthCell)); return memory ? ::new (memory) OverGrowthCell() : 0; } @@ -857,97 +665,94 @@ namespace { void baseUpdateCells(OverGrowth* self, IRenderView* view) { - if (!field(self, 0x1C)) + if (!self->m_enabled) return; - if (!field(self, 0x1E)) + if (!self->m_initialized) self->initialize(); // vslot +0x04 const Mat4* const camera = view->getViewMatrixPtr(); // vslot +0x64 - field(self, 0x08) = camera->m[13]; - field(self, 0x04) = camera->m[12]; - field(self, 0x0C) = camera->m[14]; - const float inverseCellSize = 1.0f / field(self, 0x14); - const float viewDistance = field(self, 0x24); - const int cameraCellX = static_cast(inverseCellSize * field(self, 0x04)); - const int cameraCellZ = static_cast(inverseCellSize * field(self, 0x0C)); - for (int z = 0; z < field(self, 0x10); ++z) + self->m_cameraPosition.y = camera->m[13]; + self->m_cameraPosition.x = camera->m[12]; + self->m_cameraPosition.z = camera->m[14]; + const float inverseCellSize = 1.0f / self->m_cellSize; + const float viewDistance = self->m_viewDistance; + const int cameraCellX = static_cast(inverseCellSize * self->m_cameraPosition.x); + const int cameraCellZ = static_cast(inverseCellSize * self->m_cameraPosition.z); + for (int z = 0; z < self->m_gridSize; ++z) { const float inverseViewDistance = 1.0f / viewDistance; // 0x1015EF51, per row - for (int x = 0; x < field(self, 0x10); ++x) + for (int x = 0; x < self->m_gridSize; ++x) { OverGrowthCell* const cell = self->getCell(x, z); // vslot +0x20 - const int n = field(self, 0x10); + const int n = self->m_gridSize; const int cellX = n / 2 - (100 * n + x + cameraCellX) % n + cameraCellX; const int cellZ = n / 2 - (100 * n + z + cameraCellZ) % n + cameraCellZ; - const bool moved = cellX != field(cell, 0x5C) || cellZ != field(cell, 0x60) - || field(self, 0x38) != 0; - const bool built = field(cell, 0x05) != 0 && !moved; - field(cell, 0x05) = built; + const bool moved = cellX != cell->cellX || cellZ != cell->cellZ + || self->m_reseatCells != 0; + const bool built = cell->built != 0 && !moved; + cell->built = built; if (!built && moved) { - field(cell, 0x5C) = cellX; - field(cell, 0x60) = cellZ; - field(cell, 0x14) = field(self, 0x14); - field(cell, 0x08) = static_cast(cellX) * field(self, 0x14); - field(cell, 0x0C) = 0.0f; - field(cell, 0x10) = static_cast(cellZ) * field(self, 0x14); - const float half = field(self, 0x14) * 0.5f; - field(cell, 0x0C) = heightmapCluster(self)->getHeightInWorldCoords( - half + field(cell, 0x08), half + field(cell, 0x10)); // vslot +0x6C + cell->cellX = cellX; + cell->cellZ = cellZ; + cell->size = self->m_cellSize; + cell->corner.x = static_cast(cellX) * self->m_cellSize; + cell->corner.y = 0.0f; + cell->corner.z = static_cast(cellZ) * self->m_cellSize; + const float half = self->m_cellSize * 0.5f; + cell->corner.y = heightmapCluster(self)->getHeightInWorldCoords( + half + cell->corner.x, half + cell->corner.z); // vslot +0x6C cell->clearFarList(); // cell vslot +0x1C } - const float half = field(self, 0x14) * 0.5f; - const float dx = (half + field(cell, 0x08)) - field(self, 0x04); - const float dy = field(cell, 0x0C) - field(self, 0x08); - const float dz = (half + field(cell, 0x10)) - field(self, 0x0C); - field(cell, 0x1C) = std::sqrt(dz * dz + dy * dy + dx * dx); - const float reach = cellDistanceToPoint( - cell, reinterpret_cast(&field(self, 0x04))) * inverseViewDistance; + const float half = self->m_cellSize * 0.5f; + const float dx = (half + cell->corner.x) - self->m_cameraPosition.x; + const float dy = cell->corner.y - self->m_cameraPosition.y; + const float dz = (half + cell->corner.z) - self->m_cameraPosition.z; + cell->cameraDistance = std::sqrt(dz * dz + dy * dy + dx * dx); + const float reach = cellDistanceToPoint(cell, &self->m_cameraPosition) * inverseViewDistance; const bool inRange = reach < 1.0f; - const float fadeBand = field(self, 0x20); + const float fadeBand = self->m_fadeBand; if (fadeBand == 0.0f || !(1.0f - fadeBand < reach)) - field(cell, 0x18) = 1.0f; + cell->fadeFactor = 1.0f; else - field(cell, 0x18) = clampFloat((1.0f - reach) / fadeBand, 0.0f, 1.0f); + cell->fadeFactor = clampFloat((1.0f - reach) / fadeBand, 0.0f, 1.0f); bool visible = false; if (g_overGrowthBuildEveryCell || inRange) { - if (!field(cell, 0x05)) + if (!cell->built) { - field(self, 0x18) = - (static_cast(field(cell, 0x60)) * 4711u - + static_cast(field(cell, 0x5C)) * 13u + 23u) & 0x7FFFFFFFu; - vc71::vector_layout instances = { 0, 0, 0, 0 }; - self->collectCell(cell, reinterpret_cast(&instances)); - self->buildCell(cell, reinterpret_cast(&instances)); - field(cell, 0x05) = 1; - vectorTidy(instances); + self->m_randomSeed = + (static_cast(cell->cellZ) * 4711u + + static_cast(cell->cellX) * 13u + 23u) & 0x7FFFFFFFu; + OverGrowthInstanceVector instances; + self->collectCell(cell, &instances); + self->buildCell(cell, &instances); + cell->built = 1; } - visible = field(cell, 0x05) != 0; + visible = cell->built != 0; } - field(cell, 0x04) = visible; + cell->visible = visible; } } - field(self, 0x38) = 0; + self->m_reseatCells = 0; } // sub_100CA3A0, 176 B, read in full - the editor's patch pass (rebuildCells, when +0xF0). Row-major over // the patch grid; each patch gets seed = (pz * 4711 + px * 13 + 23) & 0x7FFFFFFF (patch indices, from // 0 - unlike the cells' signed world indices), its coverage (100C9AE0), then populatePatch (vslot +0x44). - +// PE 0x100CA3A0 void regeneratePatches(OverGrowth* self) { int rowSeed = 23; - for (int pz = 0; pz < field(self, 0xDC); ++pz) + for (int pz = 0; pz < self->m_patchCountZ; ++pz) { int seed = rowSeed; - for (int px = 0; px < field(self, 0xD8); ++px) + for (int px = 0; px < self->m_patchCountX; ++px) { - unsigned char* const patch = field(self, 0xE0) - + (field(self, 0xD8) * pz + px) * kPatchBytes; - field(self, 0x18) = static_cast(seed) & 0x7FFFFFFFu; + OverGrowthPatch* const patch = self->m_patches + (self->m_patchCountX * pz + px); + self->m_randomSeed = static_cast(seed) & 0x7FFFFFFFu; computeCoverage(self, patch); - self->populatePatch(reinterpret_cast(patch)); // vslot +0x44 + self->populatePatch(patch); // vslot +0x44 seed += 13; } rowSeed += 4711; @@ -963,19 +768,20 @@ void overGrowthBaseUpdateCells(OverGrowth* self, IRenderView* view) } -// Updates, culls and draws visible cells near-to-far with distance and height fade. +// PE 0x1015F1E0, read in full. Updates, culls and draws visible cells near-to-far with distance and +// height fade. // Equal-distance ordering follows the host sort and may differ from the compatibility STL. void OverGrowth::update(IRenderView* view) { updateCells(view); // vslot +0x1C - if (!field(this, 0x1C)) + if (!m_enabled) return; - if (!field(this, 0x1E)) + if (!m_initialized) initialize(); // vslot +0x04 std::vector fartherFirst; // [ebp-0x40] - fartherFirst.reserve(static_cast(field(this, 0x10) * field(this, 0x10))); + fartherFirst.reserve(static_cast(m_gridSize * m_gridSize)); std::vector nearerFirst; // [ebp-0x30] - nearerFirst.reserve(static_cast(field(this, 0x10) * field(this, 0x10))); + nearerFirst.reserve(static_cast(m_gridSize * m_gridSize)); const Mat4* const camera = view->getViewMatrixPtr(); // vslot +0x64 const float cameraX = camera->m[12]; @@ -983,15 +789,15 @@ void OverGrowth::update(IRenderView* view) const float cameraZ = camera->m[14]; const float heightFade = clampFloat( std::fabs(cameraY - heightmapCluster(this)->getHeightInWorldCoords(cameraX, cameraZ)) - / field(this, 0x2C), - field(this, 0x30), 1.0f); + / m_heightFadeDistance, + m_minimumHeightFade, 1.0f); - for (int z = 0; z < field(this, 0x10); ++z) + for (int z = 0; z < m_gridSize; ++z) { - for (int x = 0; x < field(this, 0x10); ++x) + for (int x = 0; x < m_gridSize; ++x) { OverGrowthCell* const cell = getCell(x, z); // vslot +0x20 - if (!field(cell, 0x04) || field(cell, 0x06)) + if (!cell->visible || cell->empty) continue; if (g_overGrowthCellDistanceCull) { @@ -1004,14 +810,14 @@ void OverGrowth::update(IRenderView* view) if (g_overGrowthCellFrustumCull) { if (!terrainFrustumIntersectsBox(view->getFrustumPtr(), // vslot +0x74 - &field(cell, 0x20).min.x)) + &cell->bounds.min.x)) continue; } - if (objectDrawerOccludes(field(cell, 0x20))) + if (objectDrawerOccludes(cell->bounds)) continue; - field(cell, 0x18) = - clampFloat(field(cell, 0x1C) / field(this, 0x34), heightFade, 1.0f) - * field(cell, 0x18); + cell->fadeFactor = + clampFloat(cell->cameraDistance / m_cellFadeDistance, heightFade, 1.0f) + * cell->fadeFactor; nearerFirst.push_back(cell); } } @@ -1021,8 +827,7 @@ void OverGrowth::update(IRenderView* view) for (unsigned int i = 0; i < nearerFirst.size(); ++i) { OverGrowthCell* const cell = nearerFirst[i]; - cell->draw(view, reinterpret_cast(&field(cell, 0x08)), - field(cell, 0x18)); // cell vslot +0x10 + cell->draw(view, &cell->corner, cell->fadeFactor); // cell vslot +0x10 } } @@ -1034,50 +839,51 @@ void OverGrowth::update(IRenderView* view) // nothing (0x100CAF4A..0x100CAFD3, kept). +0x38 = 1 makes the next updateCells re-seat every cell. void OverGrowth::rebuildCells() { - for (int z = 0; z < field(this, 0x10); ++z) + for (int z = 0; z < m_gridSize; ++z) { - for (int x = 0; x < field(this, 0x10); ++x) + for (int x = 0; x < m_gridSize; ++x) { - OverGrowthCell* const cell = field(this, 0xE4)[field(this, 0x10) * z + x]; - field(cell, 0x04) = 0; - field(cell, 0x05) = 0; - field(cell, 0x64) = 0; - vectorTidy(field(cell, 0x28C)); - field(cell, 0x29C) = 0; - field(cell, 0x2A0) = 0; + OverGrowthCell* const cell = m_cells[m_gridSize * z + x]; + cell->visible = 0; + cell->built = 0; + cell->hasNear = 0; + cell->farList.clear(); // freed, not just emptied + cell->farList.shrink_to_fit(); + cell->unresolved29C = 0; + cell->lastPatch = 0; { - const vc71::string name("LeafOG"); + const std::string name("LeafOG"); dx9rend::Ra::RaShader* const shader = dx9rend::Ra::getShader( static_cast(dx9rend::g_renderQueues), name, false); - field(field(cell, 0x2A4), 0x158) = shader; + raMaterialShaderSlot(streamMaterial(cell->leaf)) = shader; // stream +0x158 } { - const vc71::string name("TrunkOG"); + const std::string name("TrunkOG"); dx9rend::Ra::RaShader* const shader = dx9rend::Ra::getShader( static_cast(dx9rend::g_renderQueues), name, false); - field(field(cell, 0x2A8), 0x158) = shader; + raMaterialShaderSlot(streamMaterial(cell->trunk)) = shader; // stream +0x158 } - assignAtlasTexture(field(cell, 0x2A4)); - assignAtlasTexture(field(cell, 0x2A8)); + assignAtlasTexture(cell->leaf); + assignAtlasTexture(cell->trunk); } } - if (field(this, 0xF0)) + if (m_editorEnable) { regeneratePatches(this); - for (int pz = 0; pz < field(this, 0xDC); ++pz) + for (int pz = 0; pz < m_patchCountZ; ++pz) { - for (int px = 0; px < field(this, 0xD8); ++px) + for (int px = 0; px < m_patchCountX; ++px) { - const vc71::vector_layout& instances = field( - field(this, 0xE0) + (field(this, 0xD8) * pz + px) * kPatchBytes, 0x0C); - for (unsigned int i = 0; i < vectorSize(instances, kInstanceBytes); ++i) + const OverGrowthInstanceVector& instances = + m_patches[m_patchCountX * pz + px].instances; + for (unsigned int i = 0; i < instances.size(); ++i) { // The shipped loop's body compiled to nothing. } } } } - field(this, 0x38) = 1; + m_reseatCells = 1; } // +0x18, PE 0x1015E600, 163 B, read in full. The density map value under (x, z): each axis @@ -1085,16 +891,14 @@ void OverGrowth::rebuildCells() // outside [0, size) (signed low test, unsigned high test) answers 0, else the byte at +0x80. unsigned int OverGrowth::sampleDensity(float x, float z) { - const unsigned int width = field(this, 0x78); - const int ix = static_cast((x - field(this, 0x64)) / field(this, 0x5C) - * static_cast(width)); - const unsigned int height = field(this, 0x7C); - const int iz = static_cast((z - field(this, 0x68)) / field(this, 0x60) - * static_cast(height)); + const unsigned int width = m_mapWidth; + const int ix = static_cast((x - m_originX) / m_extentX * static_cast(width)); + const unsigned int height = m_mapHeight; + const int iz = static_cast((z - m_originZ) / m_extentZ * static_cast(height)); if (ix < 0 || static_cast(ix) >= width || iz < 0 || static_cast(iz) >= height) return 0; - return field(this, 0x80)[width * iz + ix]; + return m_densityMap[width * iz + ix]; } // +0x1C, PE 0x100C9450, 350 B, read in full. Unloaded (empty path, size +0x9C) does nothing. Otherwise the @@ -1106,35 +910,34 @@ unsigned int OverGrowth::sampleDensity(float x, float z) // The slot is read straight from the array (N * z + x), not through getCell. void OverGrowth::updateCells(IRenderView* view) { - if (field(this, 0x88).empty()) + if (m_path.empty()) return; baseUpdateCells(this, view); - if (!field(this, 0x1C)) + if (!m_enabled) return; - if (!field(this, 0xE0)) + if (!m_patches) return; - field(this, 0xC4) = view->getZoom() * field(this, 0xF4) * field(this, 0xC8) - * field(this, 0x24); // vslot +0x28 - for (int z = 0; z < field(this, 0x10); ++z) + m_closeDistance = view->getZoom() * m_qualityScale * m_closeDistPercentage + * m_viewDistance; // vslot +0x28 + for (int z = 0; z < m_gridSize; ++z) { - for (int x = 0; x < field(this, 0x10); ++x) + for (int x = 0; x < m_gridSize; ++x) { - OverGrowthCell* const cell = field(this, 0xE4)[field(this, 0x10) * z + x]; - const int patchCountX = field(this, 0xD8); - const int patchCountZ = field(this, 0xDC); - const int px = patchCountX / 2 + field(cell, 0x5C); - const int pz = patchCountZ / 2 + field(cell, 0x60); + OverGrowthCell* const cell = m_cells[m_gridSize * z + x]; + const int patchCountX = m_patchCountX; + const int patchCountZ = m_patchCountZ; + const int px = patchCountX / 2 + cell->cellX; + const int pz = patchCountZ / 2 + cell->cellZ; if (px < 0 || pz < 0 || px >= patchCountX || pz >= patchCountZ) continue; - unsigned char* const patch = field(this, 0xE0) + (patchCountX * pz + px) * kPatchBytes; - const float radius = (field(this, 0xCC) + 1.0f) * field(this, 0xC4); - if (boundsSphereIntersects(field(patch, 0x5C), - *reinterpret_cast(&field(this, 0x04)), radius) - || field(cell, 0x64)) + OverGrowthPatch* const patch = m_patches + (patchCountX * pz + px); + const float radius = (m_closeDistFade + 1.0f) * m_closeDistance; + if (boundsSphereIntersects(patch->bounds, m_cameraPosition, radius) + || cell->hasNear) { - const bool changed = field(cell, 0x2A0) != patch; - updateCell(cell, reinterpret_cast(patch + 0x0C), changed); - field(cell, 0x2A0) = patch; + const bool changed = cell->lastPatch != patch; + updateCell(cell, &patch->instances, changed); + cell->lastPatch = patch; } } } @@ -1146,50 +949,49 @@ void OverGrowth::updateCells(IRenderView* view) // whether the list was empty (+0x06, `setz`). void OverGrowth::buildCell(OverGrowthCell* cell, OverGrowthInstanceVector* instanceVector) { - const vc71::vector_layout& instances = *reinterpret_cast(instanceVector); + OverGrowthInstanceVector& instances = *instanceVector; cell->lock(); // cell vslot +0x08 - for (unsigned int i = 0; i < vectorSize(instances, kInstanceBytes); ++i) + for (unsigned int i = 0; i < instances.size(); ++i) { - unsigned char* const instance = vectorElement(instances, i, kInstanceBytes); - const unsigned char* const type = vectorElement(field(this, 0x4C), - field(instance, 0x00), kGeometryTypeBytes); - void* const lodGeometry = field(type, 0x1C); + OverGrowthInstance* const instance = &instances[i]; + const OverGrowthGeometryPair* const type = + m_geometries.data() + static_cast(instance->geometryIndex); + void* const lodGeometry = type->lod.geometry; if (lodGeometry) - cell->appendGeometry(geometryTemplate(lodGeometry), - reinterpret_cast(instance + 0x04), - field(instance, 0x44), 0, field(instance, 0x54)); + cell->appendGeometry(geometryTemplate(lodGeometry), &instance->transform, + instance->scale, 0, instance->shadow); } cell->unlock(); // cell vslot +0x0C - field(cell, 0x06) = vectorSize(instances, kInstanceBytes) == 0; + cell->empty = instances.size() == 0; } // +0x28, PE 0x100CBBC0, 192 B, read in full. Without patches: nothing. A cell off the patch grid gets an -// emptied list (resize(0) - the Instance() temporary 1015E930 is the by-value argument). Otherwise the -// cell takes its patch's instance list (operator=, 100D0700), bounds (sub_100AE1F0) and corner, then the -// list is walked by a loop whose body compiled to nothing (0x100CBC3E..0x100CBC62, kept). +// emptied list (resize(0) - the Instance() temporary is the by-value argument). Otherwise the cell +// takes its patch's instance list (operator=), bounds (meshBoundsCopy) and corner, then the list is +// walked by a loop whose body compiled to nothing (0x100CBC3E..0x100CBC62, kept). void OverGrowth::collectCell(OverGrowthCell* cell, OverGrowthInstanceVector* instanceVector) { - if (!field(this, 0xE0)) + if (!m_patches) return; - vc71::vector_layout& instances = *reinterpret_cast(instanceVector); - const int patchCountX = field(this, 0xD8); - const int patchCountZ = field(this, 0xDC); - const int px = patchCountX / 2 + field(cell, 0x5C); - const int pz = patchCountZ / 2 + field(cell, 0x60); + OverGrowthInstanceVector& instances = *instanceVector; + const int patchCountX = m_patchCountX; + const int patchCountZ = m_patchCountZ; + const int px = patchCountX / 2 + cell->cellX; + const int pz = patchCountZ / 2 + cell->cellZ; if (px < 0 || pz < 0 || px >= patchCountX || pz >= patchCountZ) { - unsigned char empty[kInstanceBytes]; - constructInstance(empty); - vectorResize(instances, kInstanceBytes, 0u, empty); + OverGrowthInstance empty; + constructInstance(empty); // 1015E930 + instances.resize(0u, empty); return; } - unsigned char* const patch = patchAt(this, px, pz); - vectorAssign(instances, field(patch, 0x0C), kInstanceBytes); - meshBoundsCopy(field(cell, 0x20), field(patch, 0x5C)); - field(cell, 0x08) = field(patch, 0x00); - field(cell, 0x0C) = field(patch, 0x04); - field(cell, 0x10) = field(patch, 0x08); - for (unsigned int i = 0; i < vectorSize(instances, kInstanceBytes); ++i) + OverGrowthPatch* const patch = patchAt(this, px, pz); + instances = patch->instances; // operator=, 100D0700 + meshBoundsCopy(cell->bounds, patch->bounds); // sub_100AE1F0 + cell->corner.x = patch->position.x; + cell->corner.y = patch->position.y; + cell->corner.z = patch->position.z; + for (unsigned int i = 0; i < instances.size(); ++i) { // The shipped loop's body compiled to nothing. } @@ -1199,32 +1001,32 @@ void OverGrowth::collectCell(OverGrowthCell* cell, OverGrowthInstanceVector* ins // Near instances use full meshes; distance thresholds combine template radius and type settings. void OverGrowth::updateCell(OverGrowthCell* cell, OverGrowthInstanceVector* instanceVector, bool changed) { - vc71::vector_layout& farList = field(cell, 0x28C); - const vc71::vector_layout& instances = *reinterpret_cast(instanceVector); + std::vector& farList = cell->farList; + OverGrowthInstanceVector& instances = *instanceVector; bool modified = false; // [esp+0x13] unsigned int kept = 0; // [esp+0x1C] - for (unsigned int i = 0; i < vectorSize(instances, kInstanceBytes); ++i) + for (unsigned int i = 0; i < instances.size(); ++i) { - unsigned char* const instance = vectorElement(instances, i, kInstanceBytes); - const float dx = field(this, 0x04) - field(instance, 0x34); - const float dy = field(this, 0x08) - field(instance, 0x38); - const float dz = field(this, 0x0C) - field(instance, 0x3C); - const unsigned char* const type = vectorElement(field(this, 0x4C), - field(instance, 0x00), kGeometryTypeBytes); - world::IObjectTemplate* const objectTemplate = field(type, 0x80); - const float reach = objectTemplate->getCullRadiusScale() * field(instance, 0x48) // +0x70 - + field(type, 0x9C) * field(this, 0xC4) * field(this, 0x28); + OverGrowthInstance* const instance = &instances[i]; + const float dx = m_cameraPosition.x - instance->transform.m[12]; + const float dy = m_cameraPosition.y - instance->transform.m[13]; + const float dz = m_cameraPosition.z - instance->transform.m[14]; + const OverGrowthGeometryPair* const type = + m_geometries.data() + static_cast(instance->geometryIndex); + world::IObjectTemplate* const objectTemplate = type->full.objectTemplate; + const float reach = objectTemplate->getCullRadiusScale() * instance->cullRadius // +0x70 + + type->full.distanceScale * m_closeDistance * m_viewDistanceScale; const bool isNear = (dx * dx + dz * dz + dy * dy) / (reach * reach) < 1.0f; - if (!modified && farList.first && kept < vectorSize(farList, 4u)) + if (!modified && !farList.empty() && kept < farList.size()) { - unsigned char* const listed = field(farList.first, kept * 4u); + OverGrowthInstance* const listed = farList[kept]; if (isNear) { if (listed == instance) { - const void* const none = 0; + OverGrowthInstance* const none = 0; modified = true; - vectorResize(farList, 4u, kept, &none); + farList.resize(kept, none); } } else if (listed == instance) @@ -1233,47 +1035,45 @@ void OverGrowth::updateCell(OverGrowthCell* cell, OverGrowthInstanceVector* inst } else { - const void* const none = 0; + OverGrowthInstance* const none = 0; modified = true; - vectorResize(farList, 4u, kept, &none); - vectorPushBack(farList, 4u, &instance); + farList.resize(kept, none); + farList.push_back(instance); } continue; } if (!isNear) { modified = true; - vectorPushBack(farList, 4u, &instance); + farList.push_back(instance); } } - const bool hasNear = vectorSize(instances, kInstanceBytes) != vectorSize(farList, 4u); + const bool hasNear = instances.size() != farList.size(); if (!modified) - modified = hasNear != (field(cell, 0x64) != 0); - field(cell, 0x64) = hasNear; - const bool wasEmpty = field(cell, 0x06) != 0; - const bool nowEmpty = vectorSize(farList, 4u) == 0 || vectorSize(instances, kInstanceBytes) == 0; - field(cell, 0x06) = nowEmpty; + modified = hasNear != (cell->hasNear != 0); + cell->hasNear = hasNear; + const bool wasEmpty = cell->empty != 0; + const bool nowEmpty = farList.size() == 0 || instances.size() == 0; + cell->empty = nowEmpty; if (!changed && (!modified || (nowEmpty && wasEmpty))) return; // the cell's patch, re-derived; its bounds copied member-wise (the inlined 100AE1F0). - const int patchCountX = field(this, 0xD8); - const unsigned char* const patch = field(this, 0xE0) - + ((field(this, 0xDC) / 2 + field(cell, 0x60)) * patchCountX - + patchCountX / 2 + field(cell, 0x5C)) * kPatchBytes; - meshBoundsCopy(field(cell, 0x20), field(patch, 0x5C)); + const int patchCountX = m_patchCountX; + const OverGrowthPatch* const patch = m_patches + + ((m_patchCountZ / 2 + cell->cellZ) * patchCountX + patchCountX / 2 + cell->cellX); + meshBoundsCopy(cell->bounds, patch->bounds); cell->lock(); // cell vslot +0x08 - for (unsigned int k = 0; k < vectorSize(farList, 4u); ++k) + for (unsigned int k = 0; k < farList.size(); ++k) { - unsigned char* const listed = field(farList.first, k * 4u); - const unsigned char* const type = vectorElement(field(this, 0x4C), - field(listed, 0x00), kGeometryTypeBytes); - void* const lodGeometry = field(type, 0x1C); + OverGrowthInstance* const listed = farList[k]; + const OverGrowthGeometryPair* const type = + m_geometries.data() + static_cast(listed->geometryIndex); + void* const lodGeometry = type->lod.geometry; if (lodGeometry) - cell->appendGeometry(geometryTemplate(lodGeometry), - reinterpret_cast(listed + 0x04), - field(listed, 0x44), 0, field(listed, 0x54)); + cell->appendGeometry(geometryTemplate(lodGeometry), &listed->transform, + listed->scale, 0, listed->shadow); } cell->unlock(); // cell vslot +0x0C } @@ -1284,40 +1084,37 @@ void OverGrowth::updateCell(OverGrowthCell* cell, OverGrowthInstanceVector* inst // +0x40) to x, then to z, each as ((count * (range - (-range))) * 2^-24 + n) + (-range) - the PE's // association. The normalised result becomes row 1, the basis is re-orthonormalised around it (100C8820) // and the translation row takes the position. -void OverGrowth::placeInstance(OverGrowthType* typeRecord, Vec3* position, OverGrowthInstance* instanceRecord) +void OverGrowth::placeInstance(OverGrowthType* type, Vec3* position, OverGrowthInstance* instance) { - const unsigned char* const type = reinterpret_cast(typeRecord); - unsigned char* const instance = reinterpret_cast(instanceRecord); - Mat4& transform = *reinterpret_cast(instance + 0x04); - setRotationY(transform, static_cast(random24(this)) * kDegreesPerCount - 180.0f); + Mat4& transform = instance->transform; + dx9rend::setRotationYDegrees(transform, static_cast(random24(this)) * kDegreesPerCount - 180.0f); Vec3 normal; normal.x = 0.0f; normal.y = 0.0f; normal.z = 0.0f; heightmapCluster(this)->getNormalInWorldCoords(position->x, position->z, normal); // vslot +0x7C - normal.x = normal.x * field(type, 0x54); - normal.z = normal.z * field(type, 0x54); - float low = -field(type, 0x40); - normal.x = static_cast(random24(this)) * (field(type, 0x40) - low) * kRandomUnit + normal.x = normal.x * type->normalScale; + normal.z = normal.z * type->normalScale; + float low = -type->rotationScale; + normal.x = static_cast(random24(this)) * (type->rotationScale - low) * kRandomUnit + normal.x + low; - low = -field(type, 0x40); - normal.z = static_cast(random24(this)) * (field(type, 0x40) - low) * kRandomUnit + low = -type->rotationScale; + normal.z = static_cast(random24(this)) * (type->rotationScale - low) * kRandomUnit + normal.z + low; - normalizeVec3(normal); - field(instance, 0x14) = normal.x; - field(instance, 0x18) = normal.y; - field(instance, 0x1C) = normal.z; + rendmath::normalize(normal); + transform.m[4] = normal.x; // +0x14, row 1 + transform.m[5] = normal.y; + transform.m[6] = normal.z; orthonormalizeKeepingY(transform); - field(instance, 0x34) = position->x; - field(instance, 0x38) = position->y; - field(instance, 0x3C) = position->z; + transform.m[12] = position->x; // +0x34 + transform.m[13] = position->y; + transform.m[14] = position->z; } // Generates patch instances within material-density targets and stream budgets. // Limits attempts to five times the target and enforces spacing against generated instances. -void OverGrowth::populatePatch(OverGrowthPatch* patchRecord) +void OverGrowth::populatePatch(OverGrowthPatch* patch) { - unsigned char* const patch = reinterpret_cast(patchRecord); int targets[16]; int nothingLeft[16]; for (unsigned int i = 0; i < 16; ++i) @@ -1326,37 +1123,40 @@ void OverGrowth::populatePatch(OverGrowthPatch* patchRecord) nothingLeft[i] = 0; // rep stosd, 0x100CC828 } int total = 0; - const vc71::vector_layout& materials = field(this, 0x3C); - for (unsigned int i = 0; i < vectorSize(materials, kMaterialBytes); ++i) + const std::vector& materials = m_materials; + for (unsigned int i = 0; i < materials.size(); ++i) { - const unsigned char* const material = vectorElement(materials, i, kMaterialBytes); - const vc71::vector_layout& types = field(material, 0x20); + const OverGrowthMaterial* const material = &materials[i]; + const std::vector& types = material->types; float expected = 0.0f; - for (unsigned int j = 0; j < vectorSize(types, kMaterialTypeBytes); ++j) - expected = expected + field(vectorElement(types, j, kMaterialTypeBytes), 0x3C) - * field(this, 0x14) * field(this, 0x14) * 0.001f; - const int value = field(material, 0x1C); - const int count = static_cast(expected * field(patch, 0x1C + value * 4)); // __ftol2 + for (unsigned int j = 0; j < types.size(); ++j) + expected = expected + types[j].density * m_cellSize * m_cellSize * 0.001f; + const int value = static_cast(material->id); +#if defined(__APPLE__) + const int count = bf2x87::toIntTruncate(expected * patch->coverage[value]); // __ftol2 +#else + const int count = static_cast(expected * patch->coverage[value]); // __ftol2 +#endif total += count; targets[value] = count; } - vc71::vector_layout& instances = field(patch, 0x0C); - unsigned int leafVertices = field(this, 0x104); - unsigned int trunkVertices = field(this, 0x108); - unsigned int leafIndices = field(this, 0x10C); - unsigned int trunkIndices = field(this, 0x110); - for (unsigned int i = 0; i < vectorSize(instances, kInstanceBytes); ++i) + OverGrowthInstanceVector& instances = patch->instances; + unsigned int leafVertices = m_streamVertexCounts[0]; + unsigned int trunkVertices = m_streamVertexCounts[1]; + unsigned int leafIndices = m_streamIndexCounts[0]; + unsigned int trunkIndices = m_streamIndexCounts[1]; + for (unsigned int i = 0; i < instances.size(); ++i) { - const unsigned char* const existing = vectorElement(instances, i, kInstanceBytes); - if (field(existing, 0x58)) + const OverGrowthInstance* const existing = &instances[i]; + if (existing->generated) continue; - const unsigned char* const cost = vectorElement(field(this, 0x4C), - field(existing, 0x00), kGeometryTypeBytes); - leafVertices -= field(cost, 0x20); - trunkVertices -= field(cost, 0x24); - leafIndices -= field(cost, 0x28); - trunkIndices -= field(cost, 0x2C); + const OverGrowthGeometryRecord& cost = + m_geometries.data()[static_cast(existing->geometryIndex)].lod; + leafVertices -= cost.vertexCounts[0]; + trunkVertices -= cost.vertexCounts[1]; + leafIndices -= cost.indexCounts[0]; + trunkIndices -= cost.indexCounts[1]; } bool keepGoing = true; @@ -1369,67 +1169,66 @@ void OverGrowth::populatePatch(OverGrowthPatch* patchRecord) position.z = 0.0f; const unsigned int value = pickPosition(this, patch, &position); float draw = static_cast(random24(this)) * kRandomUnit; - unsigned char* const material = findMaterial(this, static_cast(value)); - if (!material || targets[field(material, 0x1C)] == 0) + OverGrowthMaterial* const material = findMaterial(this, static_cast(value)); + if (!material || targets[material->id] == 0) continue; - const vc71::vector_layout& types = field(material, 0x20); - for (unsigned int j = 0; j < vectorSize(types, kMaterialTypeBytes); ++j) + std::vector& types = material->types; + for (unsigned int j = 0; j < types.size(); ++j) { - unsigned char* const type = vectorElement(types, j, kMaterialTypeBytes); - if (!(draw < field(type, 0x38))) + OverGrowthType* const type = &types[j]; + if (!(draw < type->probability)) { - draw = draw - field(type, 0x38); + draw = draw - type->probability; continue; } - if (field(type, 0x58) < 0) + if (type->geometryIndex < 0) { // sub_1015F450(&type->+0x1C): the geometry table's find-or-add (OverGrowth.cpp). A // -1 (a missing template) is stored and the next type is tried with the draw left as it // is (0x100CCAA5..0x100CCAAA -> 0x100CCC33). - field(type, 0x58) = findOrAddGeometry(field(type, 0x1C)); - if (field(type, 0x58) < 0) + type->geometryIndex = findOrAddGeometry(type->geometry); + if (type->geometryIndex < 0) continue; } - const unsigned char* const geometryType = vectorElement( - field(this, 0x4C), field(type, 0x58), kGeometryTypeBytes); - if (field(geometryType, 0x20) > leafVertices - || field(geometryType, 0x28) > leafIndices - || field(geometryType, 0x24) > trunkVertices - || field(geometryType, 0x2C) > trunkIndices) + const OverGrowthGeometryPair* const geometryType = + m_geometries.data() + static_cast(type->geometryIndex); + if (geometryType->lod.vertexCounts[0] > leafVertices + || geometryType->lod.indexCounts[0] > leafIndices + || geometryType->lod.vertexCounts[1] > trunkVertices + || geometryType->lod.indexCounts[1] > trunkIndices) { keepGoing = false; break; } - unsigned char instance[kInstanceBytes]; + OverGrowthInstance instance; constructInstance(instance); - field(instance, 0x00) = field(type, 0x58); - field(instance, 0x54) = sampleShadow(this, position.x, position.z); - field(instance, 0x44) = 1.0f; - void* const fullGeometry = field(geometryType, 0x6C); - field(instance, 0x48) = geometryBoundingRadius(fullGeometry); - field(instance, 0x4C) = geometryBoundingRadius(fullGeometry) * field(type, 0x4C); - field(instance, 0x50) = geometryBoundingRadius(fullGeometry) * field(type, 0x50); - field(instance, 0x58) = 1; - placeInstance(reinterpret_cast(type), &position, - reinterpret_cast(instance)); // vslot +0x40 + instance.geometryIndex = type->geometryIndex; + instance.shadow = sampleShadow(this, position.x, position.z); + instance.scale = 1.0f; + void* const fullGeometry = geometryType->full.geometry; + instance.cullRadius = geometryBoundingRadius(fullGeometry); + instance.radiusToSame = geometryBoundingRadius(fullGeometry) * type->minRadiusToSame; + instance.radiusToOthers = geometryBoundingRadius(fullGeometry) * type->minRadiusToOthers; + instance.generated = 1; + placeInstance(type, &position, &instance); // vslot +0x40 { - const unsigned char* const placedType = vectorElement(field(this, 0x4C), - field(instance, 0x00), kGeometryTypeBytes); - const Vec3 anchor = field(placedType, 0x80)->getAnchorPos(); // +0xAC - field(instance, 0x38) = field(instance, 0x38) - anchor.y; + const OverGrowthGeometryPair* const placedType = + m_geometries.data() + static_cast(instance.geometryIndex); + const Vec3 anchor = placedType->full.objectTemplate->getAnchorPos(); // +0xAC + instance.transform.m[13] = instance.transform.m[13] - anchor.y; } bool spaced = true; - for (unsigned int k = 0; k < vectorSize(instances, kInstanceBytes); ++k) + for (unsigned int k = 0; k < instances.size(); ++k) { - const unsigned char* const other = vectorElement(instances, k, kInstanceBytes); - if (!field(other, 0x58)) + const OverGrowthInstance* const other = &instances[k]; + if (!other->generated) continue; - const float dx = position.x - field(other, 0x34); - const float dz = position.z - field(other, 0x3C); + const float dx = position.x - other->transform.m[12]; + const float dz = position.z - other->transform.m[14]; const float distanceSq = dz * dz + dx * dx; - const float spacing = field(other, 0x00) == field(instance, 0x00) - ? field(instance, 0x4C) + field(other, 0x4C) - : field(instance, 0x50) + field(other, 0x50); + const float spacing = other->geometryIndex == instance.geometryIndex + ? instance.radiusToSame + other->radiusToSame + : instance.radiusToOthers + other->radiusToOthers; if (distanceSq < spacing * spacing) { spaced = false; @@ -1438,16 +1237,15 @@ void OverGrowth::populatePatch(OverGrowthPatch* patchRecord) } if (!spaced) break; - leafIndices -= field(geometryType, 0x28); - trunkVertices -= field(geometryType, 0x24); - leafVertices -= field(geometryType, 0x20); - trunkIndices -= field(geometryType, 0x2C); - --targets[field(material, 0x1C)]; - vectorPushBack(instances, kInstanceBytes, instance); + leafIndices -= geometryType->lod.indexCounts[0]; + trunkVertices -= geometryType->lod.vertexCounts[1]; + leafVertices -= geometryType->lod.vertexCounts[0]; + trunkIndices -= geometryType->lod.indexCounts[1]; + --targets[material->id]; + instances.push_back(instance); OverGrowthBoxCorners corners; - constructBoxCorners(corners, *geometryLocalBounds(fullGeometry), - *reinterpret_cast(instance + 0x04)); - boundsExpandByCorners(field(patch, 0x5C), corners); + constructBoxCorners(corners, *geometryLocalBounds(fullGeometry), instance.transform); + boundsExpandByCorners(patch->bounds, corners); if (std::memcmp(targets, nothingLeft, sizeof(targets)) == 0) // repe cmpsd, 0x100CCCF3 keepGoing = false; break; diff --git a/Code/BF2/Geom/Overgrowth/OverGrowthConsole.cpp b/Code/BF2/Geom/Overgrowth/OverGrowthConsole.cpp index a248c607d..7711cb18e 100644 --- a/Code/BF2/Geom/Overgrowth/OverGrowthConsole.cpp +++ b/Code/BF2/Geom/Overgrowth/OverGrowthConsole.cpp @@ -4,12 +4,11 @@ // the multimap resolves its first active entry. Compatibility builds publish no console rows. #ifdef BF2_IMAGE_RENDDX9 #include "../../../RendDX9Abi/PluginAbi.h" -#if BF2_PLUGIN_ABI_NATIVE #include "OverGrowth.h" #include "../../../RendDX9Abi/PluginEntry.h" -#include "../../../RendDX9Abi/Vc71String.h" +#include #include "../../Core/ConsoleObjectMacro.h" #include "../../Core/ConsoleObjects.h" #include "../../Math/Vec3.h" @@ -44,16 +43,15 @@ inline bool overGrowthActive() return dx9rend::g_OverGrowth != 0; } -// The console boundary is the only place a string changes representation: the host console speaks -// this toolchain's std::string, the owner keeps the 28-byte VC7.1 one. -inline std::string toConsole(const vc71::string& value) +// The console boundary copies the owner's string for the host console (both are std::string). +inline std::string toConsole(const std::string& value) { return ::renddx9abi::toHostString(value); } -inline vc71::string toRetail(const std::string& value) +inline std::string toRetail(const std::string& value) { - return ::renddx9abi::toVc71String(value); + return ::renddx9abi::fromHostString(value); } // Overgrowth @@ -201,46 +199,61 @@ void consoleSetTypeRandomScale(const Vec2& value) { overGrowth()->setTypeRandomS BF2_CONSOLE_OBJECT("Overgrowth", 2, 0) +// PE 0x100C5471: the argument conversion. +// PE 0x100C5407: executor. BF2_CONSOLE_PROPERTY_FN(path, std::string, overGrowthActive(), consoleGetPath(), consoleSetPath, kOverGrowthConsoleTag) BF2_CONSOLE_METHOD_0_STATIC_ACTIVE(preLoad, consolePreLoad, overGrowthActive(), kOverGrowthConsoleTag) BF2_CONSOLE_METHOD_0_STATIC_ACTIVE(postLoad, consolePostLoad, overGrowthActive(), kOverGrowthConsoleTag) +// PE 0x100C562A: executor. BF2_CONSOLE_METHOD_0_RET_ACTIVE(getMaterialList, consoleGetMaterialList, std::string, overGrowthActive(), kOverGrowthConsoleTag) +// PE 0x100C5751, 0x100C5700: argument conversion, executor. BF2_CONSOLE_METHOD_2_RET_ACTIVE(addMaterial, consoleAddMaterial, bool, overGrowthActive(), std::string, uint, kOverGrowthConsoleTag) BF2_CONSOLE_METHOD_0_RET_ACTIVE(removeActiveMaterial, consoleRemoveActiveMaterial, bool, overGrowthActive(), kOverGrowthConsoleTag) +// PE 0x100C5929, 0x100C58EA: argument conversion, executor. BF2_CONSOLE_METHOD_1_STATIC_ACTIVE(setActiveMaterial, consoleSetActiveMaterial, overGrowthActive(), std::string, kOverGrowthConsoleTag) +// PE 0x100C59FD: executor. BF2_CONSOLE_METHOD_0_RET_ACTIVE(getActiveMaterialName, consoleGetActiveMaterialName, std::string, overGrowthActive(), kOverGrowthConsoleTag) +// PE 0x100C5AA0: executor. BF2_CONSOLE_METHOD_0_RET_ACTIVE(getTypeList, consoleGetTypeList, std::string, overGrowthActive(), kOverGrowthConsoleTag) +// PE 0x100C5B57, 0x100C5BA2: executor, argument conversion. BF2_CONSOLE_METHOD_1_RET_ACTIVE(addType, consoleAddType, bool, overGrowthActive(), std::string, kOverGrowthConsoleTag) BF2_CONSOLE_METHOD_0_RET_ACTIVE(removeActiveType, consoleRemoveActiveType, bool, overGrowthActive(), kOverGrowthConsoleTag) +// PE 0x100C5D03, 0x100C5D42: executor, argument conversion. BF2_CONSOLE_METHOD_1_STATIC_ACTIVE(setActiveType, consoleSetActiveType, overGrowthActive(), std::string, kOverGrowthConsoleTag) BF2_CONSOLE_METHOD_0_STATIC_ACTIVE(save, consoleSave, overGrowthActive(), kOverGrowthConsoleTag) +// PE 0x100C5E24 / 0x100C5E95: the first row's constructor and argument conversion. BF2_CONSOLE_PROPERTY_FN(viewDistance, float, overGrowthActive(), consoleGetViewDistance(), consoleSetViewDistance, kOverGrowthConsoleTag) +// PE 0x100C5F2B / 0x100C5F9C: the second row's constructor and argument conversion. BF2_CONSOLE_PROPERTY_FN(viewDistance, float, overGrowthActive(), consoleGetViewDistance(), consoleSetViewDistance, kOverGrowthConsoleTag) +// PE 0x100C605A: the argument conversion. BF2_CONSOLE_PROPERTY_FN(viewDistanceScale, float, overGrowthActive(), consoleGetViewDistanceScale(), consoleSetViewDistanceScale, kOverGrowthConsoleTag) BF2_CONSOLE_METHOD_0_STATIC_ACTIVE(exportToTerrainTexture, consoleExportToTerrainTexture, overGrowthActive(), kOverGrowthConsoleTag) +// PE 0x100C621F: argument conversion and executor (one body). BF2_CONSOLE_METHOD_4_STATIC_ACTIVE(paintMaterial, consolePaintMaterial, overGrowthActive(), float, float, float, int, kOverGrowthConsoleTag) +// PE 0x100C641F: argument conversion and executor (one body). BF2_CONSOLE_METHOD_4_STATIC_ACTIVE(paintShadowmap, consolePaintShadowmap, overGrowthActive(), float, float, float, int, kOverGrowthConsoleTag) +// PE 0x100C65B3: executor. BF2_CONSOLE_METHOD_0_RET_ACTIVE(getGeometryList, consoleGetGeometryList, std::string, overGrowthActive(), kOverGrowthConsoleTag) BF2_CONSOLE_METHOD_0_STATIC_ACTIVE(generateAll, consoleGenerateAll, overGrowthActive(), @@ -249,34 +262,45 @@ BF2_CONSOLE_METHOD_0_RET_ACTIVE(getLodDistance, consoleGetLodDistance, float, overGrowthActive(), kOverGrowthConsoleTag) BF2_CONSOLE_METHOD_0_STATIC_ACTIVE(generateAtlas, consoleGenerateAtlas, overGrowthActive(), kOverGrowthConsoleTag) +// PE 0x100C67BD: argument conversion and executor (property at OverGrowth +0xC8). BF2_CONSOLE_PROPERTY_FN(closeDistPercentage, float, overGrowthActive(), consoleGetCloseDistPercentage(), consoleSetCloseDistPercentage, kOverGrowthConsoleTag) +// PE 0x100C6850, 0x100C68C1: constructor, argument conversion and executor (+0xCC). BF2_CONSOLE_PROPERTY_FN(closeDistFade, float, overGrowthActive(), consoleGetCloseDistFade(), consoleSetCloseDistFade, kOverGrowthConsoleTag) +// PE 0x100C6954, 0x100C69C5: constructor, argument conversion and executor. BF2_CONSOLE_PROPERTY_FN(lodTimer, float, overGrowthActive(), consoleGetLodTimer(), consoleSetLodTimer, kOverGrowthConsoleTag) +// PE 0x100C6AC9, 0x100C6B16: argument conversion, executor (reads the flag as float). BF2_CONSOLE_PROPERTY_FN(editorEnable, float, overGrowthActive(), consoleGetEditorEnable(), consoleSetEditorEnable, kOverGrowthConsoleTag) BF2_CONSOLE_OBJECT("OvergrowthType", 2, 0) +// PE 0x100C6C01, 0x100C6C78: executor, argument conversion. BF2_CONSOLE_PROPERTY_FN(geometry, std::string, overGrowthActive(), consoleGetTypeGeometry(), consoleSetTypeGeometry, kOverGrowthConsoleTag) +// PE 0x100C6D5E: argument conversion and executor. BF2_CONSOLE_PROPERTY_FN(density, float, overGrowthActive(), consoleGetTypeDensity(), consoleSetTypeDensity, kOverGrowthConsoleTag) +// PE 0x100C6E65: argument conversion and executor. BF2_CONSOLE_PROPERTY_FN(normalScale, float, overGrowthActive(), consoleGetTypeNormalScale(), consoleSetTypeNormalScale, kOverGrowthConsoleTag) +// PE 0x100C6F6C: argument conversion and executor. BF2_CONSOLE_PROPERTY_FN(rotationScale, float, overGrowthActive(), consoleGetTypeRotationScale(), consoleSetTypeRotationScale, kOverGrowthConsoleTag) +// PE 0x100C7073: argument conversion and executor. BF2_CONSOLE_PROPERTY_FN(minRadiusToSame, float, overGrowthActive(), consoleGetTypeMinRadiusToSame(), consoleSetTypeMinRadiusToSame, kOverGrowthConsoleTag) +// PE 0x100C717A: argument conversion and executor. BF2_CONSOLE_PROPERTY_FN(minRadiusToOthers, float, overGrowthActive(), consoleGetTypeMinRadiusToOthers(), consoleSetTypeMinRadiusToOthers, kOverGrowthConsoleTag) +// PE 0x100C729C, 0x100C7307: argument conversion, executor. BF2_CONSOLE_PROPERTY_FN(randomScale, Vec2, overGrowthActive(), consoleGetTypeRandomScale(), consoleSetTypeRandomScale, kOverGrowthConsoleTag) @@ -301,5 +325,4 @@ bool unregisterOverGrowthConsoleObjects() } // namespace hfe } // namespace dice -#endif // BF2_PLUGIN_ABI_NATIVE #endif // BF2_IMAGE_RENDDX9 diff --git a/Code/BF2/Geom/Overgrowth/OverGrowthLoad.cpp b/Code/BF2/Geom/Overgrowth/OverGrowthLoad.cpp index 1c813fb95..93b5b24a4 100644 --- a/Code/BF2/Geom/Overgrowth/OverGrowthLoad.cpp +++ b/Code/BF2/Geom/Overgrowth/OverGrowthLoad.cpp @@ -1,6 +1,9 @@ // Vegetation resource loading, atlas adoption and editor export. // preLoad loads only the atlas; resource pre/post-load performs level initialization. #ifdef BF2_IMAGE_RENDDX9 +#if defined(__APPLE__) +#include "../../Platform/X87Compat.h" +#endif #include "OverGrowth.h" #include "OverGrowthCell.h" // createOverGrowthCell (100D0C90) #include "../MeshTemplate.h" // MeshBounds, meshBoundsExpand/Finalize, IGeometryTemplate @@ -10,10 +13,6 @@ #include "../../Math/Mat4.h" // XpLightManager.cpp's pattern: in the retail-ABI flavour HfeAbi.h already supplies IBase and the // class-registration records, so the engine headers' own copies are suppressed around their include. -#if !BF2_PLUGIN_ABI_NATIVE -#define CORE_IBASE_H -#define CORE_CLASSMANAGER_H -#endif #include "../../Game/Objects/IObject.h" #include "../../Game/Objects/IObjectTemplate.h" #include "../../Game/Objects/ObjectLayoutAccess.h" @@ -21,10 +20,7 @@ #include "../../Physics/Heightmap.h" #include "../../Scene/Object/ObjectManager.h" #include "../../Scene/Object/ObjectTypes/Base/ObjectTemplateManager.h" -#if !BF2_PLUGIN_ABI_NATIVE -#undef CORE_CLASSMANAGER_H -#undef CORE_IBASE_H -#endif +#include "../../Core/StringUtil.h" // getLowerCase (sub_10074E80) #include "../../RendDX9/RendDX9Base.h" // pathToLower, pathStripExtension, readStringSettingDefault, // textureManagerSwapDefaultMipClass #include "../../RendDX9/Texture.h" // EngineTexture, textureAddRef, textureReleaseRef @@ -35,8 +31,7 @@ #include "../../../RendDX9Abi/HostFileAbi.h" #include "../../../RendDX9Abi/PluginAbi.h" #include "../../../RendDX9Abi/PluginEntry.h" // classManager, fileManager -#include "../../../RendDX9Abi/Vc71String.h" -#include "../../../RendDX9Abi/Vc71Vector.h" +#include #include #include #include @@ -60,20 +55,13 @@ namespace dice { namespace hfe { namespace geom { namespace { -// House helpers - the same two OverGrowth.cpp keeps in its anonymous namespace. -template T& field(void* object, unsigned int offset) -{ return *reinterpret_cast(static_cast(object) + offset); } -template const T& field(const void* object, unsigned int offset) -{ return *reinterpret_cast(static_cast(object) + offset); } - - -// VC7.1 std::string operations the bodies use, over the tree's 28-byte vc71::string. +// The std::string operations the bodies use, in the shipped VC7.1 expansions. // std::operator+(const string&, const char*) - VC7.1 inlines it as `copy the left, then +=`. -vc71::string concat(const vc71::string& left, const char* right) +std::string concat(const std::string& left, const char* right) { - vc71::string result(left); + std::string result(left); result += right; return result; } @@ -83,7 +71,7 @@ vc71::string concat(const vc71::string& left, const char* right) // 100CD22B, called with off 0 and count 5). The library algorithm: scan for the first character, // then compare the whole needle; npos when absent. const unsigned int kNpos = 0xFFFFFFFFu; -unsigned int find(const vc71::string& haystack, const char* needle, unsigned int count) +unsigned int find(const std::string& haystack, const char* needle, unsigned int count) { const unsigned int size = haystack.size(); if (count == 0) @@ -97,34 +85,25 @@ unsigned int find(const vc71::string& haystack, const char* needle, unsigned int return kNpos; } -// std::less - compare(): the common prefix by memcmp, then the lengths. -struct Vc71StringLess +// Texture-name ordering is case-insensitive and stops at the first NUL. +struct StringLess { - bool operator()(const vc71::string& left, const vc71::string& right) const + bool operator()(const std::string& left, const std::string& right) const { - const unsigned int n = left.size() < right.size() ? left.size() : right.size(); - const int c = std::memcmp(left.c_str(), right.c_str(), n); - return c != 0 ? c < 0 : left.size() < right.size(); + // Ordering embedded in insert at 0x100CF6D3 and 0x100CF755. + return ::_stricmp(left.c_str(), right.c_str()) < 0; } }; -typedef std::set TextureNameSet; // set, 0x2C-byte nodes +typedef std::set TextureNameSet; // set, 0x2C-byte nodes // std::operator<<(ostream&, const string&) (sub_10001C10, 509 B, the image's own instantiation). // Every caller here streams with width 0, where the inserter's padding arms are dead, so the // characters are written as they are. -std::ostream& operator<<(std::ostream& out, const vc71::string& value) +std::ostream& operator<<(std::ostream& out, const std::string& value) { return out.write(value.c_str(), static_cast(value.size())); } -// sub_10074E80 (55 B, read in full): copy, sub_10074D10 (pathToLower) the copy, return it. -vc71::string toLower(const vc71::string& value) -{ - vc71::string lowered(value); - dx9rend::pathToLower(lowered); - return lowered; -} - // sub_1000ED40 (34 B, __stdcall, read in full): fcomi/fcmovnb against the high bound first // (moves when value >= high, ordered), then fcomi/fcmovb against the LOW bound (moves when below // OR unordered). So a NaN comes back as `low`. @@ -150,12 +129,12 @@ IGeometryTemplateManager* geometryTemplateManager() } // FileManager +0x2C readFile / +0x30 writeFile - HostFileAbi.h types both flavours. -bool hostReadFile(const vc71::string& path, void* buffer, unsigned int size, unsigned int& read) +bool hostReadFile(const std::string& path, void* buffer, unsigned int size, unsigned int& read) { return ::dice::hfe::fileManager->readFile(renddx9abi::toHostString(path), buffer, size, read); } -bool hostWriteFile(const vc71::string& path, const void* data, unsigned int size, bool flag) +bool hostWriteFile(const std::string& path, const void* data, unsigned int size, bool flag) { return ::dice::hfe::fileManager->writeFile(renddx9abi::toHostString(path), data, size, flag); } @@ -167,42 +146,16 @@ bool hostWriteFile(const vc71::string& path, const void* data, unsigned int size // ObjectManager +0x34 getAllObjectsFromGrid - a std::map by reference. // Typed native; the retail flavour walks the VC7.1 map with the inlined _Tree::iterator::_Inc the // callers carry (0x100CBF4C..0x100CBF98, 0x100CC359..0x100CC397): _Isnil at node +0x15. -#if BF2_PLUGIN_ABI_NATIVE typedef std::map HostObjectMap; -#else -struct HostObjectNode -{ - HostObjectNode* left; // +0x00 - HostObjectNode* parent; // +0x04 - HostObjectNode* right; // +0x08 - unsigned int key; // +0x0C - world::IObject* object; // +0x10 it->second, the only field the walks read - unsigned char color; // +0x14 - unsigned char isNil; // +0x15 -}; -struct HostObjectMap -{ - void* comp; // +0x00 - HostObjectNode* head; // +0x04 _Myhead (re-read by every loop test) - unsigned int size; // +0x08 -}; -#endif HostObjectMap& allObjectsFromGrid() { -#if BF2_PLUGIN_ABI_NATIVE return reinterpret_cast(::dice::hfe::objectManager)->getAllObjectsFromGrid(); -#else - typedef HostObjectMap* (__thiscall* GetAllFn)(void*); - void* const manager = ::dice::hfe::objectManager; - return *reinterpret_cast((*static_cast(manager))[0x34 / 4])(manager); -#endif } class HostObjectWalk { public: -#if BF2_PLUGIN_ABI_NATIVE HostObjectWalk() : m_map(allObjectsFromGrid()), m_it(m_map.begin()) {} bool done() const { return m_it == m_map.end(); } world::IObject* object() const { return m_it->second; } @@ -210,34 +163,6 @@ class HostObjectWalk private: HostObjectMap& m_map; HostObjectMap::iterator m_it; -#else - HostObjectWalk() : m_map(allObjectsFromGrid()), m_node(m_map.head->left) {} - bool done() const { return m_node == m_map.head; } - world::IObject* object() const { return m_node->object; } - void next() - { - if (m_node->isNil) - return; - HostObjectNode* right = m_node->right; - if (!right->isNil) - { - while (!right->left->isNil) - right = right->left; - m_node = right; - return; - } - HostObjectNode* parent = m_node->parent; - while (!parent->isNil && m_node == parent->right) - { - m_node = parent; - parent = parent->parent; - } - m_node = parent; - } -private: - HostObjectMap& m_map; - HostObjectNode* m_node; -#endif HostObjectWalk(const HostObjectWalk&); HostObjectWalk& operator=(const HostObjectWalk&); }; @@ -250,7 +175,7 @@ class HostObjectWalk inline void* geometrySlot(void* geometry, unsigned int offset) { - return (*reinterpret_cast(geometry))[offset / sizeof(void*)]; + return (*reinterpret_cast(geometry))[offset / 4]; } IGeometryTemplate* geometryGetTemplate(void* geometry) // +0x38 { @@ -268,275 +193,58 @@ float geometryBoundingRadius(void* geometry) / return reinterpret_cast(geometrySlot(geometry, 0x44))(geometry); } -// The first geom's first lod's material vector: m_materials.first -> [0].first -> the lod-0 -// vector (516-byte elements) - 100CD0A4..100CD0B8 / 100CC3BE..100CC3C7. The -// retail code reads the template this way with NO type check (vegetation is StaticMesh). -const vc71::vector_layout& firstLodMaterials(IGeometryTemplate* geometryTemplate) +// The template whose first geom's first lod materials the loaders walk (StaticMeshTemplate.h's +// staticMeshFirstLodMaterialCount / staticMeshFirstLodMaterial: m_materials.first -> [0].first -> +// the lod-0 materials) - 100CD0A4..100CD0B8 / 100CC3BE..100CC3C7. The retail code reads the +// template this way with NO type check (vegetation is StaticMesh). +const StaticMeshTemplate* vegetationTemplate(IGeometryTemplate* geometryTemplate) { - StaticMeshTemplate* const t = static_cast(geometryTemplate); - const vc71::vector_layout* const geoms = reinterpret_cast(t->m_materials.first); - return *reinterpret_cast(geoms->first); + return static_cast(geometryTemplate); } // A material's first texture reference, slot 1 of the ShaderMaterial (+0x28 -> +0x2C), and its name // (+0x58) - 100CD0E3..100CD0EE / 100CC3FC..100CC405. No null tests, as shipped. -const vc71::string& materialTextureName(const StaticMeshMaterial* material) +const std::string& materialTextureName(const StaticMeshMaterial* material) { return static_cast(material->m_shaderMaterial->textures[1])->name; } -// sub_100CE120 / the 96-byte eight-corner box. -// A copy of XpLightManager.cpp's file-local ShadowBoxCorners (anonymous namespace there); 0x101C6750, -// (all eight corners, including corner 0's different y/x association) and 0x101C6E10 -// were re-read for this draft and agree with it. - -struct BoxCorners +// The patch array: operator new[] (1005F340) - the element count ahead of the first element - then +// the vector constructor iterator sub_10001000 (42 B, read: `count - 1; js` skips a count <= 0, else +// count forward constructions). A failed allocation leaves a null. +OverGrowthPatch* newPatchArray(int count) { - Vec3 corner[8]; - - BoxCorners(const MeshBounds& bounds, const Mat4& transform) // zero, set, move - { - for (unsigned int i = 0; i < 8; ++i) - corner[i].x = corner[i].y = corner[i].z = 0.0f; - for (unsigned int i = 0; i < 8; ++i) - { - corner[i].x = (i & 4u) ? bounds.max.x : bounds.min.x; - corner[i].y = (i & 2u) ? bounds.max.y : bounds.min.y; - corner[i].z = (i & 1u) ? bounds.max.z : bounds.min.z; - } - const float* const m = transform.m; - for (unsigned int i = 0; i < 8; ++i) - { - const float x = corner[i].x; - const float y = corner[i].y; - const float z = corner[i].z; - const float tz = z * m[10] + x * m[2] + y * m[6] + m[14]; - const float ty = i == 0 ? x * m[1] + y * m[5] + z * m[9] + m[13] - : x * m[1] + z * m[9] + y * m[5] + m[13]; - const float tx = i == 0 ? z * m[8] + x * m[0] + y * m[4] + m[12] - : y * m[4] + z * m[8] + x * m[0] + m[12]; - corner[i].x = tx; - corner[i].y = ty; - corner[i].z = tz; - } - } - - Vec3 maximum() const - { - Vec3 result = corner[0]; - for (unsigned int i = 1; i < 8; ++i) - { - if (result.x < corner[i].x) result.x = corner[i].x; - if (result.y < corner[i].y) result.y = corner[i].y; - if (result.z < corner[i].z) result.z = corner[i].z; - } - return result; - } - - Vec3 minimum() const - { - Vec3 result = corner[0]; - for (unsigned int i = 1; i < 8; ++i) - { - if (result.x > corner[i].x) result.x = corner[i].x; - if (result.y > corner[i].y) result.y = corner[i].y; - if (result.z > corner[i].z) result.z = corner[i].z; - } - return result; - } -}; - -// sub_101C5450 (59 B, read in full): expand the bounds by the box's minimum corner, then by its -// maximum corner - both through sub_100796A0 (meshBoundsExpand, MeshTemplate.cpp). -void meshBoundsExpandByBox(MeshBounds& bounds, const BoxCorners& box) -{ - meshBoundsExpand(bounds, box.minimum()); - meshBoundsExpand(bounds, box.maximum()); -} - - -// THE instance - 0x60 bytes, a patch's vector entries. -// +0x00 int geometryIndex (-1) +0x44 float scale (1.0) +0x54 float shadow (NOT constructed) -// +0x04 Mat4 transform (identity) +0x48 Vec3 (0,0,0) +0x58 bool (0) +0x5C float (1.0) - -struct Instance -{ - unsigned int words[0x60 / 4]; - unsigned char* bytes() { return reinterpret_cast(words); } -}; -static_assert(sizeof(Instance) == 0x60, "100D19E0 divides by 0x60"); - -// sub_1015E930 (103 B, read in full). The sixteen transform floats are zeroed and the diagonal set -// to 1.0 (+0x40, +0x2C, +0x18, +0x04 - the identity), then the tail; +0x54 is left as it was. -void instanceConstruct(void* instance) -{ - field(instance, 0x00) = -1; - for (unsigned int offset = 0x04; offset <= 0x40; offset += 4) - field(instance, offset) = 0.0f; - field(instance, 0x40) = 1.0f; - field(instance, 0x2C) = 1.0f; - field(instance, 0x18) = 1.0f; - field(instance, 0x04) = 1.0f; - field(instance, 0x44) = 1.0f; - field(instance, 0x48) = 0.0f; - field(instance, 0x4C) = 0.0f; - field(instance, 0x50) = 0.0f; - field(instance, 0x58) = 0; - field(instance, 0x5C) = 1.0f; -} - - -// THE patch - 0x98 bytes, the countX * countZ array at OverGrowth +0xE0 (operator new[] with the -// element count in the dword before the first element). -// +0x00 Vec3 position +0x1C float density[16] (fraction of texels per material index) -// +0x0C vector +0x5C MeshBounds bounds (60 bytes, ends at +0x98) - -// sub_100CAFF0 (86 B, read in full): position and the vector zeroed, the bounds zeroed with their -// dirty byte (+0x7C) set; density[] is left unconstructed. -void patchConstruct(unsigned char* patch) -{ - field(patch, 0x00) = 0.0f; - field(patch, 0x04) = 0.0f; - field(patch, 0x08) = 0.0f; - field(patch, 0x10) = 0; - field(patch, 0x14) = 0; - field(patch, 0x18) = 0; - for (unsigned int offset = 0x5C; offset <= 0x78; offset += 4) - field(patch, offset) = 0; - field(patch, 0x7C) = 1; - for (unsigned int offset = 0x80; offset <= 0x94; offset += 4) - field(patch, offset) = 0; -} - -// The allocation operator new[] (1005F340) of count * 0x98 + 4, the count -// stored first, then the non-EH vector constructor iterator sub_10001000 (42 B, read: `count - 1; -// js` skips a count <= 0, else count forward constructions). A failed allocation leaves a null. -unsigned char* newPatchArray(int count) -{ - void* const memory = ::renddx9abi::engineAlloc(static_cast(count) * 0x98u + 4u); - if (!memory) - return 0; - *static_cast(memory) = count; - unsigned char* const patches = static_cast(memory) + 4; - for (int i = 0; i < count; ++i) - patchConstruct(patches + i * 0x98); - return patches; + return new (std::nothrow) OverGrowthPatch[count]; } // Grid helpers over the two byte maps (+0x80 density = material index per texel, +0x84 shadow). -// sub_100C88F0 (226 B, retn 18h, read in full): world (x, z) -> map texel plus the fraction. Both -// scale divisions go through the primary heightmap's getScale (+0x54), called once per axis; the -// texel is floor() offset by half the map size, and a texel above the size (unsigned compare, so an -// index equal to the size passes) or below zero is replaced by 0. -void worldToGrid(OverGrowth* self, float x, float z, int* gridX, int* gridZ, - float* fracX, float* fracZ) -{ - x = x / field(self, 0xA8)->getScale().x; - z = z / field(self, 0xA8)->getScale().z; - const float floorX = static_cast(std::floor(static_cast(x))); - const float floorZ = static_cast(std::floor(static_cast(z))); - *fracX = x - floorX; - *fracZ = z - floorZ; - *gridX = static_cast(floorX); - *gridZ = static_cast(floorZ); - *gridX += static_cast(field(self, 0x78) >> 1); - *gridZ += static_cast(field(self, 0x7C) >> 1); - if (static_cast(*gridX) > field(self, 0x78) || *gridX < 0) - *gridX = 0; - if (static_cast(*gridZ) > field(self, 0x7C) || *gridZ < 0) - *gridZ = 0; -} - -// One texel of the shadow map as 0..1, or 0 outside the map - the bounds test inlined four times in -// 100C92F0 (a signed negative test and an unsigned upper test per axis). -float shadowTexel(OverGrowth* self, int x, int z) -{ - const unsigned int width = field(self, 0x78); - if (x < 0 || static_cast(x) >= width || z < 0 || - static_cast(z) >= field(self, 0x7C)) - return 0.0f; // ds:101DDE64 (0.0) - const unsigned char texel = field(self, 0x84)[width * z + x]; - return static_cast(static_cast(texel)) * 0.003921568859368563f; // ds:101E2B98 -} - -// sub_100C92F0 (345 B, retn 8, read in full): the bilinear shadow-map sample at world (x, z). The four -// texels are fetched in the order (x,z) (x+1,z) (x,z+1) (x+1,z+1); the two rows are lerped along x, -// then the rows along z. Reached by addStaticObjects and by populatePatch (+0x44, 100CC800). -float sampleShadow(OverGrowth* self, float x, float z) -{ - int gridX = 0; - int gridZ = 0; - float fracX = 0.0f; - float fracZ = 0.0f; - worldToGrid(self, x, z, &gridX, &gridZ, &fracX, &fracZ); - const float s00 = shadowTexel(self, gridX, gridZ); - const float s10 = shadowTexel(self, gridX + 1, gridZ); - const float s01 = shadowTexel(self, gridX, gridZ + 1); - const float s11 = shadowTexel(self, gridX + 1, gridZ + 1); - const float top = (s10 - s00) * fracX + s00; - const float bottom = (s11 - s01) * fracX + s01; - return (bottom - top) * fracZ + top; -} - -// sub_100C9AE0 (495 B, retn 4, read in full): a patch's material coverage. The texel range of the -// patch's [p, p + cellSize] square (both corners through worldToGrid, the fractions discarded) is -// histogrammed over all 256 byte values; density[l] = count(l) / texel count for l < 16. The texel -// count is (gz1 - gz0 + 1) * (gx1 - gx0 + 1), converted as unsigned. Also called by 100CA3A0. -void computePatchDensity(OverGrowth* self, unsigned char* patch) -{ - const float x0 = field(patch, 0x00); - const float z0 = field(patch, 0x08); - const float x1 = field(self, 0x14) + field(patch, 0x00); - const float z1 = field(self, 0x14) + field(patch, 0x08); - int gridX0 = 0, gridZ0 = 0, gridX1 = 0, gridZ1 = 0; - float fracX = 0.0f, fracZ = 0.0f; - worldToGrid(self, x0, z0, &gridX0, &gridZ0, &fracX, &fracZ); - worldToGrid(self, x1, z1, &gridX1, &gridZ1, &fracX, &fracZ); - - unsigned int histogram[256]; - std::memset(histogram, 0, sizeof(histogram)); - for (int gz = gridZ0; gz <= gridZ1; ++gz) - { - const unsigned char* const row = - field(self, 0x80) + field(self, 0x78) * gz; - for (int gx = gridX0; gx <= gridX1; ++gx) - ++histogram[row[gx]]; - } - const unsigned int texels = - static_cast((gridZ1 - gridZ0 + 1) * (gridX1 - gridX0 + 1)); - const float total = static_cast(texels); - for (unsigned int l = 0; l < 16; ++l) - field(patch, 0x1C + 4 * l) = static_cast(histogram[l]) / total; -} - // sub_100CA450 (296 B, read in full): zero the sixteen per-material maxima (+0x114..+0x150, the // object's last field), then every patch (row by row) computes its coverage and raises the maxima on // a strict, ordered greater-than. void computePatchDensities(OverGrowth* self) { for (unsigned int l = 0; l < 16; ++l) - field(self, 0x114 + 4 * l) = 0.0f; - for (int z = 0; z < field(self, 0xDC); ++z) + self->m_materialCoverageMax[l] = 0.0f; + for (int z = 0; z < self->m_patchCountZ; ++z) { - for (int x = 0; x < field(self, 0xD8); ++x) + for (int x = 0; x < self->m_patchCountX; ++x) { - unsigned char* const patch = field(self, 0xE0) + - (field(self, 0xD8) * z + x) * 0x98; - computePatchDensity(self, patch); + OverGrowthPatch* const patch = self->m_patches + (self->m_patchCountX * z + x); + computeCoverage(self, patch); for (unsigned int l = 0; l < 16; ++l) - if (field(patch, 0x1C + 4 * l) > field(self, 0x114 + 4 * l)) - field(self, 0x114 + 4 * l) = field(patch, 0x1C + 4 * l); + if (patch->coverage[l] > self->m_materialCoverageMax[l]) + self->m_materialCoverageMax[l] = patch->coverage[l]; } } } -// The patch instance vector's push_back, the inline store when there is room, else -// _Insert_n 100D09B0 -> 100D0270 (VC7.1 growth: half again, at least one more). -void pushBackInstance(unsigned char* patch, Instance& instance) +// The patch instance vector's push_back (the inline store when there is room, else _Insert_n +// 100D09B0 -> 100D0270). +void pushBackInstance(OverGrowthPatch* patch, OverGrowthInstance& instance) { - vc71::vectorRef(&field(patch, 0x0C)).push_back(instance); + patch->instances.push_back(instance); } @@ -553,18 +261,17 @@ void addStaticObjects(OverGrowth* self) continue; const int patchX = static_cast( - (object->getAbsoluteTransformation().m[12] - field(self, 0x6C)) / - field(self, 0x14)); // +0x80 + (object->getAbsoluteTransformation().m[12] - self->m_patchOrigin.x) / + self->m_cellSize); // +0x80 const int patchZ = static_cast( - (object->getAbsoluteTransformation().m[14] - field(self, 0x74)) / - field(self, 0x14)); // +0x80 - unsigned char* const patch = field(self, 0xE0) + - (patchZ * field(self, 0xD8) + patchX) * 0x98; + (object->getAbsoluteTransformation().m[14] - self->m_patchOrigin.z) / + self->m_cellSize); // +0x80 + OverGrowthPatch* const patch = self->m_patches + (patchZ * self->m_patchCountX + patchX); - const vc71::string name(geometryGetTemplate(geometry)->getName()); // +0x38, then +0x18 + const std::string name(geometryGetTemplate(geometry)->getName()); // +0x38, then +0x18 IGeometryTemplate* lodTemplate = 0; { - const vc71::string lodName = concat(name, "_lod"); + const std::string lodName = concat(name, "_lod"); lodTemplate = geometryTemplateManager()->getTemplate(renddx9abi::toHostString(lodName)); } if (!lodTemplate) @@ -576,23 +283,20 @@ void addStaticObjects(OverGrowth* self) continue; } - Instance instance; - instanceConstruct(instance.bytes()); - field(instance.bytes(), 0x00) = self->findOrAddGeometry(name); - field(instance.bytes(), 0x04) = object->getAbsoluteTransformation(); // +0x80 - field(instance.bytes(), 0x48) = - geometryBoundingRadius(geometry) * field(instance.bytes(), 0x44); - field(instance.bytes(), 0x4C) = - geometryBoundingRadius(geometry) * field(instance.bytes(), 0x44); - field(instance.bytes(), 0x50) = - geometryBoundingRadius(geometry) * field(instance.bytes(), 0x44); - field(instance.bytes(), 0x58) = 0; - field(instance.bytes(), 0x54) = sampleShadow( - self, field(instance.bytes(), 0x34), field(instance.bytes(), 0x3C)); + OverGrowthInstance instance; + constructInstance(instance); + instance.geometryIndex = self->findOrAddGeometry(name); + instance.transform = object->getAbsoluteTransformation(); // +0x80 + instance.cullRadius = geometryBoundingRadius(geometry) * instance.scale; + instance.radiusToSame = geometryBoundingRadius(geometry) * instance.scale; + instance.radiusToOthers = geometryBoundingRadius(geometry) * instance.scale; + instance.generated = 0; + instance.shadow = sampleShadow(self, instance.transform.m[12], instance.transform.m[14]); pushBackInstance(patch, instance); - const BoxCorners box(*geometryLocalBounds(geometry), field(instance.bytes(), 0x04)); - meshBoundsExpandByBox(field(patch, 0x5C), box); + OverGrowthBoxCorners box; + constructBoxCorners(box, *geometryLocalBounds(geometry), instance.transform); + boundsExpandByCorners(patch->bounds, box); object->setComponent(IID_IGeometry, 0); // +0x54 } } @@ -605,15 +309,15 @@ void addStaticObjects(OverGrowth* self) // first geom's first lod adds ".dds" to `out`. // Callers: postLoadResources (the set is discarded - the loads are the effect), save, generateAtlas. +// PE 0x100CC1F0 void collectTextureNames(OverGrowth* self, TextureNameSet& out) { std::set templates; - const vc71::vector_layout& geometries = field(self, 0x4C); - for (unsigned int i = 0; i < vc71::vectorSizeIn(geometries, 0xA0); ++i) - templates.insert(geometryGetTemplate(field( - reinterpret_cast(geometries.first) + i * 0xA0, 0x1C))); + const std::vector& geometries = self->m_geometries; + for (unsigned int i = 0; i < geometries.size(); ++i) + templates.insert(geometryGetTemplate(geometries[i].lod.geometry)); - if (field(self, 0xF0)) + if (self->m_editorEnable) { for (HostObjectWalk walk; !walk.done(); walk.next()) { @@ -623,10 +327,10 @@ void collectTextureNames(OverGrowth* self, TextureNameSet& out) void* const geometry = world::object_detail::LayoutAccess::geometry(object); // +0x38 if (!geometry) continue; - const vc71::string name(geometryGetTemplate(geometry)->getName()); + const std::string name(geometryGetTemplate(geometry)->getName()); IGeometryTemplate* lodTemplate = 0; { - const vc71::string lodName = concat(name, "_lod"); + const std::string lodName = concat(name, "_lod"); lodTemplate = geometryTemplateManager()->getTemplate(renddx9abi::toHostString(lodName)); } if (lodTemplate) @@ -638,12 +342,12 @@ void collectTextureNames(OverGrowth* self, TextureNameSet& out) { IGeometryTemplate* const geometryTemplate = *it; geometryTemplate->load(); // +0x2C - const unsigned int count = vc71::vectorSizeIn(firstLodMaterials(geometryTemplate), 0x204); + const unsigned int count = staticMeshFirstLodMaterialCount(vegetationTemplate(geometryTemplate)); for (unsigned int k = 0; k < count; ++k) { const StaticMeshMaterial* const material = - reinterpret_cast(firstLodMaterials(geometryTemplate).first) + k; - vc71::string stripped; + staticMeshFirstLodMaterial(vegetationTemplate(geometryTemplate), k); + std::string stripped; dx9rend::pathStripExtension(stripped, materialTextureName(material)); out.insert(concat(stripped, ".dds")); } @@ -663,7 +367,7 @@ void deleteAtlas(dx9rend::TextureAtlas* atlas) // operator new(0x14) + sub_10015E60, a failed allocation giving null. dx9rend::TextureAtlas* newAtlas() { - void* const memory = ::renddx9abi::engineAlloc(0x14); + void* const memory = ::renddx9abi::engineAlloc(sizeof(dx9rend::TextureAtlas)); return memory ? dx9rend::textureAtlasCtor(memory) : 0; } @@ -673,14 +377,14 @@ dx9rend::TextureAtlas* newAtlas() // that) - shipped. void adoptFirstAtlasPage(OverGrowth* self) { - if (!field(self, 0xFC)) + if (!self->m_atlas) return; std::vector pages; - dx9rend::textureAtlasCollectPages(field(self, 0xFC), pages); + dx9rend::textureAtlasCollectPages(self->m_atlas, pages); if (!pages.empty()) { dx9rend::EngineTexture* const page = pages[0]; - field(self, 0x100) = page; + self->m_atlasPage = page; dx9rend::textureAddRef(page); // vslot +0x08 } } @@ -700,42 +404,39 @@ std::ostream& writeMatrix(std::ostream& out, const Mat4& matrix) // Returns at once when there is no patch array. void saveCollision(OverGrowth* self) { - if (!field(self, 0xE0)) + if (!self->m_patches) return; std::ostringstream out; unsigned int objects = 0; - for (int z = 0; z < field(self, 0xDC); ++z) + for (int z = 0; z < self->m_patchCountZ; ++z) { - for (int x = 0; x < field(self, 0xD8); ++x) + for (int x = 0; x < self->m_patchCountX; ++x) { - unsigned char* const patch = field(self, 0xE0) + - (field(self, 0xD8) * z + x) * 0x98; + const OverGrowthPatch* const patch = self->m_patches + (self->m_patchCountX * z + x); out << "rem Patch: " << x << ", " << z << std::endl << std::endl; - const vc71::vector_layout& instances = field(patch, 0x0C); - for (unsigned int k = 0; k < vc71::vectorSizeIn(instances, 0x60); ++k) + const OverGrowthInstanceVector& instances = patch->instances; + for (unsigned int k = 0; k < instances.size(); ++k) { - const unsigned char* const instance = - reinterpret_cast(instances.first) + k * 0x60; - if (field(instance, 0x00) < 0 || !field(instance, 0x58)) + const OverGrowthInstance* const instance = &instances[k]; + if (instance->geometryIndex < 0 || !instance->generated) continue; - const unsigned char* const pair = - reinterpret_cast(field(self, 0x4C).first) + - field(instance, 0x00) * 0xA0; - out << "Object.create " << field(pair, 0x50) << std::endl; + const OverGrowthGeometryPair* const pair = + self->m_geometries.data() + instance->geometryIndex; + out << "Object.create " << pair->full.name << std::endl; writeMatrix(out << "Object.absoluteTransformation ", - field(instance, 0x04)) << std::endl; + instance->transform) << std::endl; out << "Object.isOvergrowth 1" << std::endl; ++objects; out << std::endl; } } } - out << "rem Patches: " << field(self, 0xD8) << "x" << field(self, 0xDC) << std::endl; + out << "rem Patches: " << self->m_patchCountX << "x" << self->m_patchCountZ << std::endl; out << "rem Objects: " << objects << std::endl; const std::string sizeText = out.str(); // str() #1: size const std::string dataText = out.str(); // str() #2: data - hostWriteFile(concat(field(self, 0x88), "OvergrowthCollision.con"), + hostWriteFile(concat(self->m_path, "OvergrowthCollision.con"), dataText.c_str(), static_cast(sizeText.size()), true); // FileManager +0x30 } @@ -743,88 +444,135 @@ void saveCollision(OverGrowth* self) // These names carry a leading backslash ("\\Overgrowth.raw") that initialize's reads do not. void saveDensityMap(OverGrowth* self) { - const unsigned int bytes = field(self, 0x7C) * field(self, 0x78); - hostWriteFile(concat(field(self, 0x88), "\\Overgrowth.raw"), - field(self, 0x80), bytes, true); + const unsigned int bytes = self->m_mapHeight * self->m_mapWidth; + hostWriteFile(concat(self->m_path, "\\Overgrowth.raw"), + self->m_densityMap, bytes, true); } +// PE 0x100C9910 (the shadow-map twin of saveDensityMap). void saveShadowMap(OverGrowth* self) { - const unsigned int bytes = field(self, 0x7C) * field(self, 0x78); - hostWriteFile(concat(field(self, 0x88), "\\OvergrowthShadowmap.raw"), - field(self, 0x84), bytes, true); + const unsigned int bytes = self->m_mapHeight * self->m_mapWidth; + hostWriteFile(concat(self->m_path, "\\OvergrowthShadowmap.raw"), + self->m_shadowMap, bytes, true); } } // namespace +// PE 0x100CB050: unreachable in 1.50: no code or data references. The destructor is the instance +// vector's own: its storage (+0x10) is released and the begin/end/capacity words (+0x10/+0x14/+0x18) +// are zeroed, which the member destructor does. +OverGrowthPatch::~OverGrowthPatch() +{ +} + +// sub_100CAFF0 (86 B, read in full): position and the vector zeroed, the bounds zeroed with their +// dirty byte (+0x7C) set; coverage[] is left unconstructed. +OverGrowthPatch::OverGrowthPatch() + : instances() +{ + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; + bounds.min.x = 0.0f; + bounds.min.y = 0.0f; + bounds.min.z = 0.0f; + bounds.max.x = 0.0f; + bounds.max.y = 0.0f; + bounds.max.z = 0.0f; + bounds.originRadius = 0.0f; + bounds.radius = 0.0f; + bounds.dirty = 1; + bounds.extent.x = 0.0f; + bounds.extent.y = 0.0f; + bounds.extent.z = 0.0f; + bounds.center.x = 0.0f; + bounds.center.y = 0.0f; + bounds.center.z = 0.0f; +} + + // Initializes maps and geometry indices from the primary heightmap, then applies view distance. // Requires heightmap singletons; missing raw maps retain zero density/full shadow defaults. +// PE 0x1015F5F0 void OverGrowth::initialize() { IBase* const cluster = ::dice::hfe::classManager->getSingleton( renddx9abi::HostString("HeightmapCluster")); // +0x48 - field(this, 0xAC) = - static_cast(static_cast(cluster)); + m_cluster = static_cast(static_cast(cluster)); world::IHeightmap* const heightmap = static_cast(static_cast(cluster))->getPrimaryHeightmap(); // +0x40 - field(this, 0xA8) = heightmap; - int sizeX = 0; - int sizeZ = 0; + m_heightmap = heightmap; + int sizeX; + int sizeZ; heightmap->getSize(sizeX, sizeZ); // +0x2C - field(this, 0x78) = static_cast(sizeX); - field(this, 0x7C) = static_cast(sizeZ); - - field(this, 0x5C) = static_cast(field(this, 0x78)) * - field(this, 0xA8)->getScale().x; // +0x54 - field(this, 0x60) = static_cast(field(this, 0x7C)) * - field(this, 0xA8)->getScale().z; // +0x54 - const float halfX = field(this, 0x5C) * -0.5f; // ds:102089FC - field(this, 0x64) = halfX; - const float halfZ = field(this, 0x60) * -0.5f; - field(this, 0x68) = halfZ; - field(this, 0x70) = 0.0f; - field(this, 0x6C) = halfX; - field(this, 0x74) = halfZ; + m_mapWidth = static_cast(sizeX); + m_mapHeight = static_cast(sizeZ); + + { + const Vec3& scale = m_heightmap->getScale(); // +0x54 +#if defined(__APPLE__) + // [CHOSEN, not recovered] The unsigned FILD conversion stays exact until the product store. + m_extentX = bf2x87::store(bf2x87::mul(bf2x87::Real(m_mapWidth), bf2x87::Real(scale.x))); +#else + m_extentX = static_cast(m_mapWidth) * scale.x; +#endif + } + { + const Vec3& scale = m_heightmap->getScale(); // +0x54 again +#if defined(__APPLE__) + m_extentZ = bf2x87::store(bf2x87::mul(bf2x87::Real(m_mapHeight), bf2x87::Real(scale.z))); +#else + m_extentZ = static_cast(m_mapHeight) * scale.z; +#endif + } + const float halfX = m_extentX * -0.5f; // ds:102089FC + m_originX = halfX; + const float halfZ = m_extentZ * -0.5f; + m_originZ = halfZ; + m_patchOrigin.y = 0.0f; + m_patchOrigin.x = halfX; + m_patchOrigin.z = halfZ; unsigned char* const density = static_cast(::renddx9abi::engineAlloc( - field(this, 0x7C) * field(this, 0x78))); - field(this, 0x80) = density; - std::memset(density, 0, field(this, 0x7C) * field(this, 0x78)); + m_mapHeight * m_mapWidth)); + m_densityMap = density; + std::memset(density, 0, m_mapHeight * m_mapWidth); unsigned char* const shadow = static_cast(::renddx9abi::engineAlloc( - field(this, 0x7C) * field(this, 0x78))); - field(this, 0x84) = shadow; - std::memset(shadow, 0xFF, field(this, 0x7C) * field(this, 0x78)); + m_mapHeight * m_mapWidth)); + m_shadowMap = shadow; + std::memset(shadow, 0xFF, m_mapHeight * m_mapWidth); - unsigned int bytesRead = 0; // var_10 - const vc71::string& path = field(this, 0x88); + unsigned int bytesRead; // var_10, output only + const std::string& path = m_path; if (::renddx9abi::engineFileExists(concat(path, "Overgrowth.raw"))) // +0x1C { - const unsigned int bytes = field(this, 0x7C) * field(this, 0x78); - hostReadFile(concat(path, "Overgrowth.raw"), field(this, 0x80), bytes, + const unsigned int bytes = m_mapHeight * m_mapWidth; + hostReadFile(concat(path, "Overgrowth.raw"), m_densityMap, bytes, bytesRead); // +0x2C } if (::renddx9abi::engineFileExists(concat(path, "OvergrowthShadowmap.raw"))) { - const unsigned int bytes = field(this, 0x7C) * field(this, 0x78); - hostReadFile(concat(path, "OvergrowthShadowmap.raw"), field(this, 0x84), + const unsigned int bytes = m_mapHeight * m_mapWidth; + hostReadFile(concat(path, "OvergrowthShadowmap.raw"), m_shadowMap, bytes, bytesRead); } - setViewDistance(field(this, 0x24)); // vtable +0x0C + setViewDistance(m_viewDistance); // vtable +0x0C - const vc71::vector_layout& layers = field(this, 0x3C); - for (unsigned int i = 0; i < vc71::vectorSizeIn(layers, 0x30); ++i) + std::vector& layers = m_materials; + for (unsigned int i = 0; i < layers.size(); ++i) { - unsigned char* const layer = reinterpret_cast(layers.first) + i * 0x30; - const vc71::vector_layout& types = field(layer, 0x20); - for (unsigned int j = 0; j < vc71::vectorSizeIn(types, 0x5C); ++j) + OverGrowthMaterial& layer = layers[i]; + std::vector& types = layer.types; + for (unsigned int j = 0; j < types.size(); ++j) { - unsigned char* const type = reinterpret_cast(types.first) + j * 0x5C; - field(type, 0x58) = findOrAddGeometry(field(type, 0x1C)); + OverGrowthType& type = types[j]; + type.geometryIndex = findOrAddGeometry(type.geometry); } } - field(this, 0x1E) = 1; + m_initialized = 1; } @@ -833,33 +581,31 @@ void OverGrowth::initialize() void OverGrowth::preLoadResources() { - if (field(this, 0x88).empty()) + if (m_path.empty()) return; OverGrowth::initialize(); - field(this, 0xE0) = newPatchArray(field(this, 0xD8) * field(this, 0xDC)); - for (int z = 0; z < field(this, 0xDC); ++z) + m_patches = newPatchArray(m_patchCountX * m_patchCountZ); + for (int z = 0; z < m_patchCountZ; ++z) { const float rowZ = static_cast(z); - for (int x = 0; x < field(this, 0xD8); ++x) + for (int x = 0; x < m_patchCountX; ++x) { - unsigned char* const patch = field(this, 0xE0) + - (field(this, 0xD8) * z + x) * 0x98; - const float offsetZ = rowZ * field(this, 0x14); - field(patch, 0x00) = static_cast(x) * field(this, 0x14) + - field(this, 0x6C); - field(patch, 0x04) = field(this, 0x70); - field(patch, 0x08) = offsetZ + field(this, 0x74); - - const float half = field(this, 0x14) * 0.5f; // ds:101DD4F0 - const float height = field(this, 0xAC)->getHeightInWorldCoords( - half + field(patch, 0x00), half + field(patch, 0x08)); // +0x6C - field(patch, 0x04) = height; - - const float centreHalf = field(this, 0x14) * 0.5f; - const float centreX = centreHalf + field(patch, 0x00); - const float centreZ = centreHalf + field(patch, 0x08); - MeshBounds& bounds = field(patch, 0x5C); + OverGrowthPatch* const patch = m_patches + (m_patchCountX * z + x); + const float offsetZ = rowZ * m_cellSize; + patch->position.x = static_cast(x) * m_cellSize + m_patchOrigin.x; + patch->position.y = m_patchOrigin.y; + patch->position.z = offsetZ + m_patchOrigin.z; + + const float half = m_cellSize * 0.5f; // ds:101DD4F0 + const float height = m_cluster->getHeightInWorldCoords( + half + patch->position.x, half + patch->position.z); // +0x6C + patch->position.y = height; + + const float centreHalf = m_cellSize * 0.5f; + const float centreX = centreHalf + patch->position.x; + const float centreZ = centreHalf + patch->position.z; + MeshBounds& bounds = patch->bounds; bounds.min.x = centreX; bounds.min.y = height; bounds.min.z = centreZ; @@ -871,7 +617,7 @@ void OverGrowth::preLoadResources() } } - if (!field(this, 0xF0)) + if (!m_editorEnable) addStaticObjects(this); } @@ -881,40 +627,37 @@ void OverGrowth::preLoadResources() void OverGrowth::postLoadResources() { - if (field(this, 0x88).empty()) + if (m_path.empty()) return; // per geometry: the vegetation stream sizes and the lod fade (skipped while reloading) - if (!field(this, 0xB0)) + if (!m_reloading) { - for (unsigned int i = 0; - i < vc71::vectorSizeIn(field(this, 0x4C), 0xA0); ++i) + for (unsigned int i = 0; i < m_geometries.size(); ++i) { - static const unsigned int kRecords[2] = { 0x50, 0x00 }; // the named record, then "_lod" - for (unsigned int r = 0; r < 2; ++r) + for (unsigned int r = 0; r < 2; ++r) // the named record, then "_lod" { - unsigned char* const record = - reinterpret_cast(field(this, 0x4C).first) + - i * 0xA0 + kRecords[r]; + OverGrowthGeometryRecord* const record = + r == 0 ? &m_geometries[i].full : &m_geometries[i].lod; IGeometryTemplate* const geometryTemplate = - geometryGetTemplate(field(record, 0x1C)); // +0x38 + geometryGetTemplate(record->geometry); // +0x38 for (unsigned int k = 0; - k < vc71::vectorSizeIn(firstLodMaterials(geometryTemplate), 0x204); ++k) + k < staticMeshFirstLodMaterialCount(vegetationTemplate(geometryTemplate)); ++k) { - const StaticMeshMaterial* const material = reinterpret_cast( - firstLodMaterials(geometryTemplate).first) + k; - const vc71::string lowered = toLower(materialTextureName(material)); + const StaticMeshMaterial* const material = + staticMeshFirstLodMaterial(vegetationTemplate(geometryTemplate), k); + const std::string lowered = getLowerCase(materialTextureName(material)); unsigned int tiled = 0; if (find(lowered, "tile_", 5) != kNpos) tiled = 1; - field(record, 0x20 + tiled * 4) += material->m_vegetationVertexCount; - field(record, 0x28 + tiled * 4) += material->m_vegetationIndexCount; + record->vertexCounts[tiled] += material->m_vegetationVertexCount; + record->indexCounts[tiled] += material->m_vegetationIndexCount; } // `lowered` dies here (100CD13F) - MeshBounds* const bounds = geometryLocalBounds(field(record, 0x1C)); // +0x40 + MeshBounds* const bounds = geometryLocalBounds(record->geometry); // +0x40 if (bounds->dirty) meshBoundsFinalize(*bounds); const float scaled = bounds->radius * 0.2f; // ds:101DDF30 - field(record, 0x4C) = clampFloat(scaled * scaled, 0.3f, 1.0f); + record->distanceScale = clampFloat(scaled * scaled, 0.3f, 1.0f); } } } @@ -926,51 +669,44 @@ void OverGrowth::postLoadResources() unsigned int layerIndices[32]; // var_80 std::memset(layerVertices, 0, sizeof(layerVertices)); std::memset(layerIndices, 0, sizeof(layerIndices)); - for (unsigned int i = 0; - i < vc71::vectorSizeIn(field(this, 0x3C), 0x30); ++i) + for (unsigned int i = 0; i < m_materials.size(); ++i) { - unsigned char* const layer = - reinterpret_cast(field(this, 0x3C).first) + i * 0x30; + OverGrowthMaterial& layer = m_materials[i]; for (unsigned int j = 0; j < 2; ++j) { float densitySum = 0.0f; // ds:101DDE64 - const unsigned int slot = field(layer, 0x1C) * 2 + j; + const unsigned int slot = layer.id * 2 + j; layerVertices[slot] = 0; layerIndices[slot] = 0; - const vc71::vector_layout& types = field(layer, 0x20); - for (unsigned int k = 0; k < vc71::vectorSizeIn(types, 0x5C); ++k) + std::vector& types = layer.types; + for (unsigned int k = 0; k < types.size(); ++k) { - unsigned char* const type = reinterpret_cast(types.first) + k * 0x5C; - const int perCell = static_cast(field(this, 0x14) * field(this, 0x14) * - field(type, 0x3C) * 0.001f); // ds:101DDE54 - const unsigned char* const pair = - reinterpret_cast(field(this, 0x4C).first) + - field(type, 0x58) * 0xA0; - layerVertices[field(layer, 0x1C) * 2 + j] += - field(pair, 0x20 + j * 4) * perCell; - densitySum += field(type, 0x3C); - layerIndices[field(layer, 0x1C) * 2 + j] += - field(pair, 0x28 + j * 4) * perCell; + OverGrowthType& type = types[k]; + const int perCell = static_cast(m_cellSize * m_cellSize * + type.density * 0.001f); // ds:101DDE54 + const OverGrowthGeometryPair& pair = m_geometries.data()[type.geometryIndex]; + layerVertices[layer.id * 2 + j] += pair.lod.vertexCounts[j] * perCell; + densitySum += type.density; + layerIndices[layer.id * 2 + j] += pair.lod.indexCounts[j] * perCell; } - for (unsigned int k = 0; k < vc71::vectorSizeIn(types, 0x5C); ++k) + for (unsigned int k = 0; k < types.size(); ++k) { - unsigned char* const type = reinterpret_cast(types.first) + k * 0x5C; - field(type, 0x38) = field(type, 0x3C) / densitySum; + OverGrowthType& type = types[k]; + type.probability = type.density / densitySum; } } } // the largest per-patch vertex / index counts, per stream - field(this, 0x104) = 10; - field(this, 0x108) = 10; - field(this, 0x10C) = 10; - field(this, 0x110) = 10; - for (int z = 0; z < field(this, 0xDC); ++z) + m_streamVertexCounts[0] = 10; + m_streamVertexCounts[1] = 10; + m_streamIndexCounts[0] = 10; + m_streamIndexCounts[1] = 10; + for (int z = 0; z < m_patchCountZ; ++z) { - for (int x = 0; x < field(this, 0xD8); ++x) + for (int x = 0; x < m_patchCountX; ++x) { - unsigned char* const patch = field(this, 0xE0) + - (field(this, 0xD8) * z + x) * 0x98; + const OverGrowthPatch* const patch = m_patches + (m_patchCountX * z + x); for (unsigned int j = 0; j < 2; ++j) { unsigned int vertices = 0; @@ -978,41 +714,37 @@ void OverGrowth::postLoadResources() for (unsigned int l = 0; l < 16; ++l) { vertices += static_cast(static_cast(layerVertices[l * 2 + j]) * - field(patch, 0x1C + 4 * l)); + patch->coverage[l]); indices += static_cast(static_cast(layerIndices[l * 2 + j]) * - field(patch, 0x1C + 4 * l)); + patch->coverage[l]); } - const vc71::vector_layout& instances = field(patch, 0x0C); - for (unsigned int k = 0; k < vc71::vectorSizeIn(instances, 0x60); ++k) + const OverGrowthInstanceVector& instances = patch->instances; + for (unsigned int k = 0; k < instances.size(); ++k) { - const unsigned char* const instance = - reinterpret_cast(instances.first) + k * 0x60; - if (field(instance, 0x58)) + const OverGrowthInstance& instance = instances[k]; + if (instance.generated) continue; - const unsigned char* const pair = - reinterpret_cast(field(this, 0x4C).first) + - field(instance, 0x00) * 0xA0; - vertices += field(pair, 0x20 + j * 4); - indices += field(pair, 0x28 + j * 4); + const OverGrowthGeometryPair& pair = m_geometries.data()[instance.geometryIndex]; + vertices += pair.lod.vertexCounts[j]; + indices += pair.lod.indexCounts[j]; } - if (vertices > field(this, 0x104 + j * 4)) - field(this, 0x104 + j * 4) = vertices; - if (indices > field(this, 0x10C + j * 4)) - field(this, 0x10C + j * 4) = indices; + if (vertices > m_streamVertexCounts[j]) + m_streamVertexCounts[j] = vertices; + if (indices > m_streamIndexCounts[j]) + m_streamIndexCounts[j] = indices; } } } // the N x N cells - const int gridSize = field(this, 0x10); - field(this, 0xE4) = static_cast( - ::renddx9abi::engineAlloc(static_cast(gridSize * gridSize * 4))); - for (int z = 0; z < field(this, 0x10); ++z) + const int gridSize = m_gridSize; + m_cells = static_cast( + ::renddx9abi::engineAlloc(static_cast(gridSize * gridSize) * sizeof(OverGrowthCell*))); + for (int z = 0; z < m_gridSize; ++z) { - for (int x = 0; x < field(this, 0x10); ++x) + for (int x = 0; x < m_gridSize; ++x) { - OverGrowthCell** const slot = - field(this, 0xE4) + (field(this, 0x10) * z + x); + OverGrowthCell** const slot = m_cells + (m_gridSize * z + x); *slot = createOverGrowthCell(); } } @@ -1022,9 +754,9 @@ void OverGrowth::postLoadResources() TextureNameSet names; collectTextureNames(this, names); adoptFirstAtlasPage(this); - field(this, 0x20) = 0.0f; - field(this, 0x30) = 1.0f; - field(this, 0xA4) = 1; + m_fadeBand = 0.0f; + m_minimumHeightFade = 1.0f; + m_loaded = 1; rebuildCells(); // vtable +0x14 } } @@ -1036,29 +768,34 @@ void OverGrowth::postLoadResources() // owner at +0xFC is NOT deleted here - shipped (reload clears first; the console's direct call does // not). Callers: reload and the console command at 100C5538. +// PE 0x100C9CD0 void OverGrowth::preLoad() { OverGrowth* const self = this; - const vc71::vector_layout& layers = field(self, 0x3C); - for (unsigned int i = 0; i < vc71::vectorSizeIn(layers, 0x30); ++i) + std::vector& layers = self->m_materials; + for (unsigned int i = 0; i < layers.size(); ++i) { - unsigned char* const layer = reinterpret_cast(layers.first) + i * 0x30; - const vc71::vector_layout& types = field(layer, 0x20); - for (unsigned int j = 0; j < vc71::vectorSizeIn(types, 0x5C); ++j) + OverGrowthMaterial& layer = layers[i]; + std::vector& types = layer.types; + for (unsigned int j = 0; j < types.size(); ++j) { - unsigned char* const type = reinterpret_cast(types.first) + j * 0x5C; - if (field(type, 0x58) < 0) - field(type, 0x58) = self->findOrAddGeometry(field(type, 0x1C)); + OverGrowthType& type = types[j]; + if (type.geometryIndex < 0) + type.geometryIndex = self->findOrAddGeometry(type.geometry); } } - field(self, 0xFC) = newAtlas(); + self->m_atlas = newAtlas(); const int previousMipClass = dx9rend::textureManagerSwapDefaultMipClass(9); - if (!dx9rend::textureAtlasLoadTAI(field(self, 0xFC), - concat(field(self, 0x88), "OvergrowthAtlas.tai"))) + bool loaded; { - deleteAtlas(field(self, 0xFC)); - field(self, 0xFC) = 0; + const std::string file = concat(self->m_path, "OvergrowthAtlas.tai"); + loaded = dx9rend::textureAtlasLoadTAI(self->m_atlas, file); + } + if (!loaded) + { + deleteAtlas(self->m_atlas); + self->m_atlas = 0; } dx9rend::textureManagerSwapDefaultMipClass(previousMipClass); } @@ -1072,24 +809,23 @@ void OverGrowth::generateAtlas() OverGrowth* const self = this; TextureNameSet names; collectTextureNames(self, names); - std::list files(names.begin(), names.end()); + std::list files(names.begin(), names.end()); - vc71::string saveDirectory; + std::string saveDirectory; dx9rend::readStringSettingDefault("Editor_LevelSavePath", "", saveDirectory); // +0x40 if (saveDirectory.size() == 0) dx9rend::readStringSettingDefault("GSModDirectory", "", saveDirectory); // +0x40 - deleteAtlas(field(self, 0xFC)); - field(self, 0xFC) = newAtlas(); + deleteAtlas(self->m_atlas); + self->m_atlas = newAtlas(); const int previousMipClass = dx9rend::textureManagerSwapDefaultMipClass(9); - dx9rend::textureAtlasGenerate(field(self, 0xFC), saveDirectory, - concat(field(self, 0x88), "OvergrowthAtlas"), + dx9rend::textureAtlasGenerate(self->m_atlas, saveDirectory, + concat(self->m_path, "OvergrowthAtlas"), saveDirectory, files, true); - if (!dx9rend::textureAtlasLoadTAI(field(self, 0xFC), - concat(field(self, 0x88), "OvergrowthAtlas.tai"))) + if (!dx9rend::textureAtlasLoadTAI(self->m_atlas, concat(self->m_path, "OvergrowthAtlas.tai"))) { - deleteAtlas(field(self, 0xFC)); - field(self, 0xFC) = 0; + deleteAtlas(self->m_atlas); + self->m_atlas = 0; } adoptFirstAtlasPage(self); dx9rend::textureManagerSwapDefaultMipClass(previousMipClass); @@ -1105,44 +841,43 @@ void OverGrowth::save() { OverGrowth* const self = this; std::ostringstream out; - out << "Overgrowth.viewDistance " << field(self, 0x24) << std::endl; - out << "Overgrowth.viewDistanceScale " << field(self, 0x28) << std::endl; - out << "Overgrowth.closeDistPercentage " << field(self, 0xC8) << std::endl; + out << "Overgrowth.viewDistance " << self->m_viewDistance << std::endl; + out << "Overgrowth.viewDistanceScale " << self->m_viewDistanceScale << std::endl; + out << "Overgrowth.closeDistPercentage " << self->m_closeDistPercentage << std::endl; out << std::endl; - const vc71::vector_layout& layers = field(self, 0x3C); - for (unsigned char* layer = reinterpret_cast(layers.first); - layer != reinterpret_cast(layers.last); layer += 0x30) + const std::vector& layers = self->m_materials; + for (const OverGrowthMaterial* layer = layers.data(); layer != layers.data() + layers.size(); + ++layer) { - out << "Overgrowth.addMaterial " << field(layer, 0x00) << " " - << field(layer, 0x1C) << std::endl; - out << "Overgrowth.setActiveMaterial " << field(layer, 0x00) << std::endl; - const vc71::vector_layout& types = field(layer, 0x20); - for (unsigned char* type = reinterpret_cast(types.first); - type != reinterpret_cast(types.last); type += 0x5C) + out << "Overgrowth.addMaterial " << layer->name << " " + << layer->id << std::endl; + out << "Overgrowth.setActiveMaterial " << layer->name << std::endl; + const std::vector& types = layer->types; + for (const OverGrowthType* type = types.data(); type != types.data() + types.size(); ++type) { - out << "Overgrowth.addType " << field(type, 0x00) << std::endl; - out << "Overgrowth.setActiveType " << field(type, 0x00) << std::endl; - out << "OvergrowthType.geometry " << field(type, 0x1C) << std::endl; - out << "OvergrowthType.density " << field(type, 0x3C) << std::endl; - out << "OvergrowthType.normalScale " << field(type, 0x54) << std::endl; - out << "OvergrowthType.rotationScale " << field(type, 0x40) << std::endl; - out << "OvergrowthType.minRadiusToSame " << field(type, 0x4C) << std::endl; - out << "OvergrowthType.minRadiusToOthers " << field(type, 0x50) << std::endl; + out << "Overgrowth.addType " << type->name << std::endl; + out << "Overgrowth.setActiveType " << type->name << std::endl; + out << "OvergrowthType.geometry " << type->geometry << std::endl; + out << "OvergrowthType.density " << type->density << std::endl; + out << "OvergrowthType.normalScale " << type->normalScale << std::endl; + out << "OvergrowthType.rotationScale " << type->rotationScale << std::endl; + out << "OvergrowthType.minRadiusToSame " << type->minRadiusToSame << std::endl; + out << "OvergrowthType.minRadiusToOthers " << type->minRadiusToOthers << std::endl; } out << std::endl; } - out << "Overgrowth.path " << field(self, 0x88) << std::endl; + out << "Overgrowth.path " << self->m_path << std::endl; out << "Overgrowth.preLoad" << std::endl; { const std::string sizeText = out.str(); // str() #1 const std::string dataText = out.str(); // str() #2 - hostWriteFile(concat(field(self, 0x88), "Overgrowth.con"), + hostWriteFile(concat(self->m_path, "Overgrowth.con"), dataText.c_str(), static_cast(sizeText.size()), true); } saveCollision(self); saveDensityMap(self); saveShadowMap(self); - if (!field(self, 0xB0)) + if (!self->m_reloading) { TextureNameSet names; collectTextureNames(self, names); @@ -1152,4 +887,4 @@ void OverGrowth::save() } } } } -#endif \ No newline at end of file +#endif diff --git a/Code/BF2/Geom/Overgrowth/OverGrowthRender.cpp b/Code/BF2/Geom/Overgrowth/OverGrowthRender.cpp index 6ae306bf5..18582f33f 100644 --- a/Code/BF2/Geom/Overgrowth/OverGrowthRender.cpp +++ b/Code/BF2/Geom/Overgrowth/OverGrowthRender.cpp @@ -5,31 +5,27 @@ #include "OverGrowthCell.h" // overGrowthBaseUpdateCells (1015EEB0) #include "../GeometryInstanceData.h" // 100C88A0's +0x28 / +0x2C and the +0xF4 opacity slot #include "../MeshTemplate.h" // IGeometryTemplate::createInstance (+0x24), MeshBounds +#include "../StaticMesh.h" // StaticMesh::m_float25C - the instance's shadow value #include "../StaticMeshTemplate.h" // the template bounds the shadow walk reads at +0xFC #include "../Terrain.h" // terrainFrustumIntersectsBox - sub_101C7980 #include "../XpLightManager.h" // g_LightManager's type +#include "../BoxCorners.h" // the eight-corner object box (0x100CE120) #include "../../Math/Frustum.h" +#include "../../RendDX9/RendDX9Math.h" // the RendDX9.dll Math copies #include "../../Math/LocalBoundingBox.h" +#include "../../Platform/X87Compat.h" // [CHOSEN, not recovered] the shadow pullback's x87 add #include "../../Math/Mat4.h" #include "../../Math/Plane3.h" #include "../../Math/Vec3.h" #include "../../RendMisc/IRenderView.h" #include "../../RendDX9/RendDX9Base.h" // RendDX9Base (+0x514..+0x516), rendererFrameOrdinal -#include "../../../RendDX9Abi/Vc71String.h" -#include "../../../RendDX9Abi/Vc71Vector.h" +#include // The ONE host (BF2.exe) call of the draw half: IObjectTemplate::getCullRadiusScale on the object // template a draw type keeps at +0x80. Included the way XpLightManager.cpp includes its host // interfaces: the retail-ABI flavour takes HfeAbi's IBase / ClassManager carriers. -#if !BF2_PLUGIN_ABI_NATIVE -#define CORE_IBASE_H -#define CORE_CLASSMANAGER_H -#endif #include "../../Game/Objects/IObjectTemplate.h" -#if !BF2_PLUGIN_ABI_NATIVE -#undef CORE_CLASSMANAGER_H -#undef CORE_IBASE_H -#endif +#include "../../Game/Objects/IObject.h" #include #include @@ -51,21 +47,11 @@ extern LightManager* g_LightManager; // dword_1024B914 - ModuleGeom.cpp namespace { -template T& field(void* object, unsigned int offset) -{ return *reinterpret_cast(static_cast(object) + offset); } -template const T& field(const void* object, unsigned int offset) -{ return *reinterpret_cast(static_cast(object) + offset); } - - -// [INFERRED] names for the vegetation draw records whose strides are fixed below. -// Each draw type contains LOD and main geometry pools; geometries borrow instance transforms. -// Instance draw-type indices are unchecked. Patch bounds are finalized before culling. +// The vegetation draw records (OverGrowth.h): each draw type (geometry pair) holds the LOD and main +// geometry pools; geometries borrow instance transforms. Instance draw-type indices are unchecked. +// Patch bounds are finalized before culling. -const unsigned int kDrawTypeSize = 0xA0; -const unsigned int kPatchSize = 0x98; -const int kInstanceSize = 0x60; // 100CA6E0 / 100CAA05 (magic 0x2AAAAAAB, sar 4) -const unsigned int kShadowRecordSize = 0x498; // 100CB5E8, 101617A2 (LightManager +0x79C records) // byte_102390C0 - file-backed 1 in .data with exactly ONE reference in the image, the read at // 0x100CA70E, and no writer: the +0x58 skip below can never fire in retail. Kept mutable so the load @@ -73,12 +59,6 @@ const unsigned int kShadowRecordSize = 0x498; // 100CB5E8, 101617A2 (LightManag // [INFERRED] name. unsigned char g_overGrowthDrawObjectInstances = 1; -inline unsigned int vectorCount(const unsigned char* first, const unsigned char* last, int stride) -{ - // VC7.1 size(): a signed byte span divided by the element size, then compared unsigned (`jnb`). - return static_cast((last - first) / stride); -} - inline const Vec3& translationOf(const Mat4& transform) { return *reinterpret_cast(&transform.m[12]); // +0x30 @@ -94,59 +74,61 @@ inline const Vec3& translationOf(const Mat4& transform) inline void* geometrySlot(void* geometry, unsigned int offset) { - return (*reinterpret_cast(geometry))[offset / sizeof(void*)]; + return (*reinterpret_cast(geometry))[offset / 4]; } -// +0x18 draw(renderView, occluder, flag), `retn 0Ch` (StaticMesh 0x100FF510). The OverGrowth draw +// +0x18 draw(renderView, occluder, flag), `retn 0Ch` (StaticMesh::draw). The OverGrowth draw // always passes (view, 0, 1): 100CA974..100CA981 and 100CA9EC..100CA9F9. inline void geometryDraw(void* geometry, IRenderView* view) { - typedef void (__fastcall* DrawFn)(void*, void*, void*, void*, int); - reinterpret_cast(geometrySlot(geometry, 0x18))(geometry, 0, view, 0, 1); + // StaticMesh's slot body is PE 0x100FF510. + typedef void (__thiscall* DrawFn)(void*, void*, void*, int); + reinterpret_cast(geometrySlot(geometry, 0x18))(geometry, view, 0, 1); } // +0x24 - the shadow record this geometry receives from (StaticMesh +0x34C), one argument. inline void geometryAttachShadowRecord(void* geometry, void* record) { - typedef void (__fastcall* AttachFn)(void*, void*, void*); - reinterpret_cast(geometrySlot(geometry, 0x24))(geometry, 0, record); + typedef void (__thiscall* AttachFn)(void*, void*); + reinterpret_cast(geometrySlot(geometry, 0x24))(geometry, record); } // +0x40 getLocalBounds - the selected lod's box (StaticMesh lod record + 4). inline const LocalBoundingBox& geometryLocalBounds(void* geometry) { - typedef const void* (__fastcall* BoundsFn)(void*, void*); + typedef const void* (__thiscall* BoundsFn)(void*); return *static_cast( - reinterpret_cast(geometrySlot(geometry, 0x40))(geometry, 0)); + reinterpret_cast(geometrySlot(geometry, 0x40))(geometry)); } // +0x44 getBoundingRadius, float in ST0 (StaticMesh it finalises the lod bounds first, // so the call is NOT side-effect free and every shipped repetition is kept). inline float geometryBoundingRadius(void* geometry) { - typedef float (__fastcall* RadiusFn)(void*, void*); - return reinterpret_cast(geometrySlot(geometry, 0x44))(geometry, 0); + typedef float (__thiscall* RadiusFn)(void*); + return reinterpret_cast(geometrySlot(geometry, 0x44))(geometry); } // +0x48 getGeometryTransformation (StaticMesh the stored pointer or the shared identity). inline const Mat4* geometryTransformation(void* geometry) { - typedef const Mat4* (__fastcall* TransformFn)(void*, void*); - return reinterpret_cast(geometrySlot(geometry, 0x48))(geometry, 0); + typedef const Mat4* (__thiscall* TransformFn)(void*); + return reinterpret_cast(geometrySlot(geometry, 0x48))(geometry); } -// +0x50 setGeometryTransformation - stores the pointer (StaticMesh 0x100FF2B0), one argument. +// +0x50 setGeometryTransformation - stores the pointer (StaticMesh's body), one argument. inline void geometrySetTransformation(void* geometry, const Mat4* transform) { - typedef void (__fastcall* SetTransformFn)(void*, void*, const Mat4*); - reinterpret_cast(geometrySlot(geometry, 0x50))(geometry, 0, transform); + // StaticMesh's slot body is PE 0x100FF2B0. + typedef void (__thiscall* SetTransformFn)(void*, const Mat4*); + reinterpret_cast(geometrySlot(geometry, 0x50))(geometry, transform); } // +0xAC - the shadow-caster frame stamp (StaticMesh +0x350), one argument: renderer +0x54. inline void geometryStampShadowFrame(void* geometry, unsigned int frameOrdinal) { - typedef void (__fastcall* StampFn)(void*, void*, unsigned int); - reinterpret_cast(geometrySlot(geometry, 0xAC))(geometry, 0, frameOrdinal); + typedef void (__thiscall* StampFn)(void*, unsigned int); + reinterpret_cast(geometrySlot(geometry, 0xAC))(geometry, frameOrdinal); } @@ -155,7 +137,7 @@ inline void geometryStampShadowFrame(void* geometry, unsigned int frameOrdinal) // The distance fade goes to +0x2C and the geometry's own opacity slot (+0xF4, StaticMesh's setFade: // the Ra transparency) gets it times the base opacity +0x28. The product is formed before the store, // the store precedes the call. [INFERRED] name; it sits among OverGrowth's COMDATs (0x100C8xxx). - +// PE 0x100C88A0 void geometrySetDistanceFade(void* geometry, float fade) { GeometryInstanceData* const data = static_cast(geometry); @@ -216,11 +198,7 @@ bool isMultisampleActive() return true; if (base->disableMultisample) return false; - const unsigned int* const first = base->multiSampleFirst; - const unsigned int* const last = base->multiSampleLast; - if (first && ((last - first) >> 1)) - return *reinterpret_cast(first) > 0; - return false; + return dx9rend::multiSampleListActive(base); } // The render's alpha-to-coverage doubling, 100CA929..100CA950 and the predicate is @@ -276,8 +254,8 @@ bool frustumContainsSphere(const Frustum& frustum, const Vec3& p, float radius, return true; } -// PE 0x101C5350 (254 B), read in full - Frustum::getOutcode(point), RendDX9's copy (the tree's is a -// declared [FRONTIER] in Frustum.h). Bit i is plane i with the point strictly in front of it +// PE 0x101C5350 (254 B), read in full - Frustum::getOutcode(point), RendDX9's copy (the tree's +// shared body is Math/Frustum.cpp). Bit i is plane i with the point strictly in front of it // (distance > 0, ordered: `test ah,41h; jnz`), evaluated in the order 5, 4, 1, 0, 2, 3 (plane 5 assigns // 0x20; the rest OR in), every distance (n.z*p.z + n.y*p.y) + n.x*p.x + d. unsigned char frustumOutcode(const Frustum& frustum, const Vec3& p) @@ -304,17 +282,6 @@ unsigned char frustumOutcode(const Frustum& frustum, const Vec3& p) return code; } -// PE 0x10079610 (92 B), read in full - Mat4 transformPoint (SkinnedMesh.cpp keeps the same body -// file-local as mat4TransformPoint). z and y are formed before x is stored because out may alias in. -void transformPoint(const Mat4& m, const float in[3], float out[3]) -{ - const float z = m.m[2] * in[0] + m.m[10] * in[2] + m.m[6] * in[1] + m.m[14]; - const float y = m.m[1] * in[0] + m.m[9] * in[2] + m.m[5] * in[1] + m.m[13]; - out[0] = m.m[8] * in[2] + m.m[4] * in[1] + in[0] * m.m[0] + m.m[12]; - out[1] = y; - out[2] = z; -} - // PE 0x101C54B0 (518 B), read in full - a local box against a frustum under a transform, only the // planes in `mask` (thiscall on the box, `retn 0Ch`: frustum, transform, mask). True unless all eight // transformed corners share an outside plane of the mask: the running AND of the corners' masked @@ -342,7 +309,7 @@ bool boxIntersectsFrustum(const LocalBoundingBox& box, const Frustum& frustum, c (i & 2u) ? box.m_max.y : box.m_min.y, (i & 1u) ? box.m_max.z : box.m_min.z }; - transformPoint(transform, local, &corner.x); + rendmath::transformPoint(transform, *reinterpret_cast(local), corner); // sub_10079610 shared = static_cast(shared & (frustumOutcode(frustum, corner) & mask)); if (!shared) return true; @@ -351,98 +318,16 @@ bool boxIntersectsFrustum(const LocalBoundingBox& box, const Frustum& frustum, c } -// The eight-corner object box - PE 0x100CE120 (122 B: zero the 24 floats, then 0x101C6750 setBounds -// and 0x101C67F0 transform) and 0x100AE110 (94 B: the zeroing alone). All four bodies read here in -// full; this is XpLightManager.cpp's ShadowBoxCorners (file-local there), re-checked against the PE: -// corner i takes x from max when bit 2, y when bit 1, z when bit 0; the transform forms all three rows -// from the untouched corner, and corner 0's y and x rows associate differently from corners 1..7 -// (101C67F6..101C683D against 101C6845..101C688C). - -struct BoxCorners -{ - Vec3 corner[8]; - - BoxCorners() - { - for (unsigned int i = 0; i < 8; ++i) - corner[i].x = corner[i].y = corner[i].z = 0.0f; - } - - BoxCorners(const LocalBoundingBox& bounds, const Mat4& world) - { - for (unsigned int i = 0; i < 8; ++i) - corner[i].x = corner[i].y = corner[i].z = 0.0f; - setBounds(bounds); - transform(world); - } - - void setBounds(const LocalBoundingBox& bounds) - { - for (unsigned int i = 0; i < 8; ++i) - { - corner[i].x = (i & 4u) ? bounds.m_max.x : bounds.m_min.x; - corner[i].y = (i & 2u) ? bounds.m_max.y : bounds.m_min.y; - corner[i].z = (i & 1u) ? bounds.m_max.z : bounds.m_min.z; - } - } - - void transform(const Mat4& world) - { - const float* const m = world.m; - for (unsigned int i = 0; i < 8; ++i) - { - const float x = corner[i].x; - const float y = corner[i].y; - const float z = corner[i].z; - const float tz = z * m[10] + x * m[2] + y * m[6] + m[14]; - const float ty = i == 0 ? x * m[1] + y * m[5] + z * m[9] + m[13] - : x * m[1] + z * m[9] + y * m[5] + m[13]; - const float tx = i == 0 ? z * m[8] + x * m[0] + y * m[4] + m[12] - : y * m[4] + z * m[8] + x * m[0] + m[12]; - corner[i].x = tx; - corner[i].y = ty; - corner[i].z = tz; - } - } -}; +// The eight-corner object box is Geom/BoxCorners.h's BoxCorners (PE 0x100CE120 with 0x101C6750 and +// 0x101C67F0, the frustum test 0x101C6A90). #if defined(_M_IX86) -static_assert(sizeof(BoxCorners) == 0x60, "the eight-corner box is 96 bytes (0x100CE120 / 0x100AE110)"); static_assert(sizeof(LocalBoundingBox) == 0x3C, "the patch bounds run +0x5C..+0x97"); static_assert(sizeof(Frustum) == 0x1E8, "a shadow record's frustum sits at +0x10 of 0x498 bytes"); static_assert(sizeof(Mat4) == 0x40, "an instance's transform runs +0x04..+0x43"); -static_assert(offsetof(StaticMeshTemplate, m_bounds) == 0xFC, - "the shadow walk reads the pool template's bounds at +0xFC (100CB5A7)"); -static_assert(sizeof(MeshBounds) == sizeof(LocalBoundingBox), "MeshBounds is LocalBoundingBox"); #endif - -// PE 0x101C6A90 (433 B), read in full - the box against a frustum's six planes (thiscall on the box, -// `retn 4`): false as soon as one plane has ALL eight corners strictly in front of it (distance > 0, -// ordered; the eight are always all counted). Corner 0's distance is (z*n.z + x*n.x) + y*n.y + d, -// corners 1..7's (y*n.y + z*n.z) + x*n.x + d (101C6AA0..101C6AB4 against 101C6ACD..101C6AE2). -// StaticMesh.cpp's StaticMeshBoundsCorners::outside sums x, y, z for every corner; not reused. -bool boxCornersInsideFrustum(const BoxCorners& box, const Frustum& frustum) -{ - for (unsigned int plane = 0; plane < 6; ++plane) - { - const Plane3& p = frustum.m_planes[plane]; - int outside = 0; - { - const Vec3& c = box.corner[0]; - if (c.z * p.normal.z + c.x * p.normal.x + c.y * p.normal.y + p.d > 0.0f) - outside += 1; - } - for (unsigned int i = 1; i < 8; ++i) - { - const Vec3& c = box.corner[i]; - if (c.y * p.normal.y + c.z * p.normal.z + c.x * p.normal.x + p.d > 0.0f) - outside += 1; - } - if (outside == 8) - return false; - } - return true; -} +// The patch and template bounds are read as LocalBoundingBox: every architecture. +static_assert(sizeof(MeshBounds) == sizeof(LocalBoundingBox), "MeshBounds is LocalBoundingBox"); // Corner distance used while extending the caster near plane; preserves z/y/x association. @@ -479,14 +364,14 @@ void fitShadowFrustumNearPlane(Frustum& frustum, const Vec3* corners) plane.d = -(normal.y * corner.y + normal.z * corner.z + normal.x * corner.x); } - frustum.recalcCorners(); + rendmath::frustumRecalcCorners(frustum); const Vec3* const corner = frustum.m_corners; frustum.m_farDist = shadowCornerDistance(corner[4], corner[0]) - frustum.m_nearDist; // +0x1E0 Mat4 transformation = frustum.m_transformation; transformation.m[12] = (corner[0].x + corner[3].x) * 0.5f; transformation.m[13] = (corner[3].y + corner[0].y) * 0.5f; transformation.m[14] = (corner[3].z + corner[0].z) * 0.5f; - frustum.transform(transformation); + rendmath::frustumTransform(frustum, transformation); } @@ -499,32 +384,43 @@ void shiftShadowFrustumTowardLight(Frustum& frustum, float distance) const float x = normal.x * distance; const float y = normal.y * distance; const float z = normal.z * distance; +#if defined(__APPLE__) + // [CHOSEN, not recovered] PE 0x10161642..0x10161678 (inlined twice in 0x10161610): the x + // product stays on the x87 stack for the m[12] add; only y and z are stored first. + transformation.m[12] = bf2x87::store(bf2x87::add( + bf2x87::wide(transformation.m[12]), + bf2x87::mul(bf2x87::wide(normal.x), bf2x87::wide(distance)))); + (void)x; +#else transformation.m[12] = transformation.m[12] + x; +#endif transformation.m[13] = transformation.m[13] + y; transformation.m[14] = transformation.m[14] + z; frustum.m_farDist = frustum.m_farDist + distance; - frustum.transform(transformation); + rendmath::frustumTransform(frustum, transformation); } -void lightManagerAttachShadowReceiver(void* manager, void* geometry) +// PE 0x10161610 +void lightManagerAttachShadowReceiver(LightManager* manager, void* geometry) { - Frustum shadowFrustum(field(manager, 0x278)); // [ebp-0x274] - shiftShadowFrustumTowardLight(shadowFrustum, field(manager, 0x16C)); + Frustum shadowFrustum(lightManagerShadowFrustum(manager)); // +0x278, [ebp-0x274] + shiftShadowFrustumTowardLight(shadowFrustum, lightManagerShadowPullbackDistance(manager)); // +0x16C { const Mat4* const transform = geometryTransformation(geometry); // +0x48 const float radius = geometryBoundingRadius(geometry); // +0x44 - if (!shadowFrustum.inside(translationOf(*transform), radius)) + if (!rendmath::frustumInside(shadowFrustum, translationOf(*transform), radius)) return; } - for (unsigned char* record = field(manager, 0x7A0); - record != field(manager, 0x7A4); record += kShadowRecordSize) + std::vector& records = lightManagerShadowRecords(manager); // +0x79C + for (LightShadowRecord* record = records.data(); + record != records.data() + records.size(); ++record) { - Frustum recordFrustum(*reinterpret_cast(record + 0x10)); // [ebp-0x45C] - shiftShadowFrustumTowardLight(recordFrustum, field(manager, 0x16C)); + Frustum recordFrustum(record->frustum); // [ebp-0x45C] + shiftShadowFrustumTowardLight(recordFrustum, lightManagerShadowPullbackDistance(manager)); const Mat4* const transform = geometryTransformation(geometry); // +0x48, again const float radius = geometryBoundingRadius(geometry); // +0x44, again - if (recordFrustum.inside(translationOf(*transform), radius)) + if (rendmath::frustumInside(recordFrustum, translationOf(*transform), radius)) { geometryAttachShadowRecord(geometry, record); // +0x24 geometryStampShadowFrame(geometry, dx9rend::rendererFrameOrdinal()); // +0x54, then +0xAC @@ -536,17 +432,14 @@ void lightManagerAttachShadowReceiver(void* manager, void* geometry) // PE 0x1015E9E0 (83 B), read in full - a member of the unpublished base (thiscall on the OverGrowth): // every draw type's two pools start the frame with nothing handed out - +0x38 (the "_lod" pool) and -// +0x88 (the main pool's +0x38) zeroed, type by type, the type vector's first re-read for each store. +// +0x88 (the main pool's +0x38) zeroed, type by type, the type vector re-read for each store. // Its one caller is render (0x100CA5E4). [INFERRED] name. -void resetGeometryPools(void* self) +void resetGeometryPools(OverGrowth* self) { - for (unsigned int index = 0; ; ++index) + for (unsigned int index = 0; index < self->m_geometries.size(); ++index) { - const unsigned char* const first = field(self, 0x50); - if (!first || index >= vectorCount(first, field(self, 0x54), kDrawTypeSize)) - break; - field(field(self, 0x50) + index * kDrawTypeSize, 0x38) = 0; - field(field(self, 0x50) + index * kDrawTypeSize, 0x88) = 0; + self->m_geometries[index].lod.poolUsed = 0; + self->m_geometries[index].full.poolUsed = 0; } } @@ -554,28 +447,32 @@ void resetGeometryPools(void* self) // for this instance. When every geometry the pool owns is already out (`cmp [esi+38h], eax; jnz` - an // equality test against the vector's size, `sar 2`) the pool's template creates one more (+0x24, // IGeometryTemplate::createInstance - no null test on the result) and it is pushed (0x1009ACE0, the -// VC7.1 push_back); then the geometry at +0x38 is taken, +0x38 advances, and the geometry is handed +// push_back); then the geometry at +0x38 is taken, +0x38 advances, and the geometry is handed // the address of the instance's transform (+0x50 with instance + 4). Callers: render (twice) and the // shadow walk. [INFERRED] name. -void* acquireGeometry(unsigned char* pool, unsigned char* instance) +void* acquireGeometry(OverGrowthGeometryRecord* pool, OverGrowthInstance* instance) { - vc71::vector_layout& geometries = field(pool, 0x3C); - const unsigned int owned = geometries.first - ? static_cast((geometries.last - geometries.first) >> 2) : 0u; - if (field(pool, 0x38) == owned) + std::vector& geometries = pool->pool; + const unsigned int owned = static_cast(geometries.size()); + if (pool->poolUsed == owned) { - void* created = field(pool, 0x34)->createInstance(); // +0x24 - // [CHOSEN, not recovered] growth policy: vc71::vectorPushBackIn (RW-74) stands in for the - // shipped _Insert_n (0x1009A340); first/last/end, the element and the engine heap are shipped. - vc71::vectorPushBackIn(geometries, sizeof(void*), &created); + void* created = pool->geometryTemplate->createInstance(); // +0x24 + geometries.push_back(created); } - const unsigned int used = field(pool, 0x38); - field(pool, 0x38) = used + 1; - void* const geometry = reinterpret_cast(geometries.first)[used]; - geometrySetTransformation(geometry, &field(instance, 0x04)); // +0x50 + const unsigned int used = pool->poolUsed; + pool->poolUsed = used + 1; + void* const geometry = geometries[used]; + geometrySetTransformation(geometry, &instance->transform); // +0x50 return geometry; } +// StaticMesh +0x25C - the vegetation shadow value the draw hands each geometry (the instance's +0x54, +// stored as its bits). The pools' geometries are StaticMesh instances. +inline void geometrySetShadowValue(void* geometry, const OverGrowthInstance* instance) +{ + static_cast(static_cast(geometry))->m_float25C = instance->shadow; +} + // ObjectDrawer primary slot +0x38 (PE 0x100F8220), called through the drawer's table exactly as the // PE does (`mov ecx, dword_1025A39C; mov edx, [ecx]; push edi; call [edx+38h]` at 0x100CA7E5..0x100CA7EE, @@ -584,9 +481,9 @@ void* acquireGeometry(unsigned char* pool, unsigned char* instance) inline bool objectDrawerOccludes(IBase* drawer, void* geometry) { - typedef bool (__fastcall* OccludedFn)(void*, void*, void*); + typedef bool (__thiscall* OccludedFn)(void*, void*); void** const table = *reinterpret_cast(drawer); - return reinterpret_cast(table[0x38 / sizeof(void*)])(drawer, 0, geometry); + return reinterpret_cast(table[0x38 / 4])(drawer, geometry); } // The host call. IObjectTemplate::getCullRadiusScale - MSVC slot 28 = +0x70 in this tree's table @@ -602,68 +499,63 @@ inline float objectTemplateCullRadiusScale(const void* objectTemplate) } // namespace +// PE 0x100CA580. // Updates visible vegetation cells, culls instances and draws their main/LOD cross-fade. // view and the initialized geometry/light services must be valid; time is the frame delta. // Main-pool geometry is acquired before culling. LOD geometry draws first and is not // registered as a directional-shadow receiver. void OverGrowth::render(IRenderView* view, float time) { - if (field(this, 0x88).empty()) + if (m_path.empty()) return; - if (field(this, 0xD5)) + if (m_updateBeforeRender) OverGrowth::update(view); // 100CA5A2, direct else overGrowthBaseUpdateCells(this, view); // 100CA5AE, direct - if (!field(this, 0x1C)) + if (!m_enabled) return; - if (!field(this, 0xE0)) + if (!m_patches) return; - if (!field(this, 0xD4)) + if (!m_drawNear) return; (void)view->getViewMatrixPtr(); // 100CA5DF +0x64, discarded resetGeometryPools(this); (void)view->getFrustumPtr(); // 100CA5ED +0x74, discarded - for (int row = 0; row < field(this, 0x10); ++row) + for (int row = 0; row < m_gridSize; ++row) { - for (int column = 0; column < field(this, 0x10); ++column) + for (int column = 0; column < m_gridSize; ++column) { - unsigned char* const cell = - field(this, 0xE4)[column + row * field(this, 0x10)]; - const int patchesX = field(this, 0xD8); - const int patchesZ = field(this, 0xDC); - const int x = patchesX / 2 + field(cell, 0x5C); - const int z = patchesZ / 2 + field(cell, 0x60); + const OverGrowthCell* const cell = m_cells[column + row * m_gridSize]; + const int patchesX = m_patchCountX; + const int patchesZ = m_patchCountZ; + const int x = patchesX / 2 + cell->cellX; + const int z = patchesZ / 2 + cell->cellZ; if (x < 0 || z < 0 || x >= patchesX || z >= patchesZ) continue; - unsigned char* const patch = - field(this, 0xE0) + kPatchSize * (x + z * patchesX); - const float reach = (field(this, 0xCC) + 1.0f) * field(this, 0xC4); - if (!field(patch, 0x5C).intersectSphere(field(this, 0x04), reach)) + OverGrowthPatch* const patch = m_patches + (x + z * patchesX); + const float reach = (m_closeDistFade + 1.0f) * m_closeDistance; + if (!reinterpret_cast(patch->bounds).intersectSphere( + m_cameraPosition, reach)) continue; - for (unsigned int index = 0; ; ++index) + for (unsigned int index = 0; index < patch->instances.size(); ++index) { - const unsigned char* const first = field(patch, 0x10); - if (!first || index >= vectorCount(first, field(patch, 0x14), kInstanceSize)) - break; - unsigned char* const instance = field(patch, 0x10) + index * kInstanceSize; - unsigned char* const type = - field(this, 0x50) - + field(instance, 0x00) * static_cast(kDrawTypeSize); - if (!g_overGrowthDrawObjectInstances && field(instance, 0x58)) + OverGrowthInstance* const instance = &patch->instances[index]; + OverGrowthGeometryPair* const type = m_geometries.data() + instance->geometryIndex; + if (!g_overGrowthDrawObjectInstances && instance->generated) continue; const float drawRadius = - objectTemplateCullRadiusScale(field(type, 0x80)) * field(instance, 0x48) - + field(this, 0x28) * field(this, 0xC4) * field(type, 0x9C); - const float ratio = distanceSquared(field(instance, 0x34), field(this, 0x04)) + objectTemplateCullRadiusScale(type->full.objectTemplate) * instance->cullRadius + + m_viewDistanceScale * m_closeDistance * type->full.distanceScale; + const float ratio = distanceSquared(translationOf(instance->transform), m_cameraPosition) / (drawRadius * drawRadius); if (!(ratio < 1.0f)) // `test ah,5; jp` continue; - void* const geometry = acquireGeometry(type + 0x50, instance); + void* const geometry = acquireGeometry(&type->full, instance); { const Mat4* const transform = geometryTransformation(geometry); // +0x48 const float radius = geometryBoundingRadius(geometry); // +0x44 @@ -684,16 +576,16 @@ void OverGrowth::render(IRenderView* view, float time) } if (objectDrawerOccludes(dx9rend::g_ObjectDrawer, geometry)) continue; - lightManagerAttachShadowReceiver(static_cast(g_LightManager), geometry); + lightManagerAttachShadowReceiver(g_LightManager, geometry); - float fade = clampFloat((1.0f - std::sqrt(ratio)) / field(this, 0xCC) - * std::sqrt(field(type, 0x9C)), 0.0f, 1.0f); - if (field(this, 0xF8) > 0.0f) // 100CA83B `test ah,41h` + float fade = clampFloat((1.0f - std::sqrt(ratio)) / m_closeDistFade + * std::sqrt(type->full.distanceScale), 0.0f, 1.0f); + if (m_lodTimer > 0.0f) // 100CA83B `test ah,41h` { if (fade < 1.0f) // 100CA852 `test ah,5; jp` { - const float rate = 1.0f / field(this, 0xF8); - float& state = field(instance, 0x5C); + const float rate = 1.0f / m_lodTimer; + float& state = instance->lodFadeState; if (fade > 0.5f) // 100CA876 `test ah,41h` state = maxFloat(0.0f, minFloat(state - rate * time, 2.0f - (fade + fade))); else @@ -701,18 +593,18 @@ void OverGrowth::render(IRenderView* view, float time) } else { - field(instance, 0x5C) = 0.0f; + instance->lodFadeState = 0.0f; } - fade = 1.0f - field(instance, 0x5C); + fade = 1.0f - instance->lodFadeState; } - if (field(type, 0x1C) && fade < 1.0f) + if (type->lod.geometry && fade < 1.0f) { const float alpha = alphaToCoverageAdjusted( clampFloat((1.0f - fade) + (1.0f - fade), 0.0f, 1.0f)); - void* const lodGeometry = acquireGeometry(type, instance); + void* const lodGeometry = acquireGeometry(&type->lod, instance); geometrySetDistanceFade(lodGeometry, alpha); - field(lodGeometry, 0x25C) = field(instance, 0x54); + geometrySetShadowValue(lodGeometry, instance); geometryDraw(lodGeometry, view); // +0x18 } if (fade > 0.0f) // 100CA984 `test ah,41h` @@ -720,7 +612,7 @@ void OverGrowth::render(IRenderView* view, float time) const float alpha = alphaToCoverageAdjusted( clampFloat(fade + fade, 0.0f, 1.0f)); geometrySetDistanceFade(geometry, alpha); - field(geometry, 0x25C) = field(instance, 0x54); + geometrySetShadowValue(geometry, instance); geometryDraw(geometry, view); // +0x18 } } @@ -729,66 +621,58 @@ void OverGrowth::render(IRenderView* view, float time) } +// PE 0x100CB460. // Appends vegetation intersecting the directional shadow volumes and expands caster bounds. // Uses LOD geometry when available. Pool cursors are shared with drawing and reset only by // render, so this pass must run before the frame's vegetation draw resets those cursors. - -void OverGrowth::collectShadowGeometry(OverGrowthShadowVolumes* records, OverGrowthShadowBounds* bounds, - OverGrowthShadowState* state, OverGrowthGeometryVector* geometries) +void OverGrowth::collectShadowGeometry(const std::vector* records, + const Frustum* lightFrustum, Frustum* casterFrustumPointer, + std::vector* geometries) { - if (!field(this, 0x1C)) + if (!m_enabled) return; - if (!field(this, 0xE0)) + if (!m_patches) return; - if (!field(this, 0xD4)) + if (!m_drawNear) return; - vc71::vector_layout* const shadowRecords = reinterpret_cast(records); - if (!shadowRecords->first - || (shadowRecords->last - shadowRecords->first) / static_cast(kShadowRecordSize) == 0) + const std::vector& shadowRecords = *records; + if (shadowRecords.size() == 0) return; - if (field(this, 0x10) <= 0) + if (m_gridSize <= 0) return; - const Frustum* const lightFrustum = reinterpret_cast(bounds); - Frustum& casterFrustum = *reinterpret_cast(state); - vc71::vector_layout& output = *reinterpret_cast(geometries); + Frustum& casterFrustum = *casterFrustumPointer; + std::vector& output = *geometries; - for (int row = 0; row < field(this, 0x10); ++row) + for (int row = 0; row < m_gridSize; ++row) { - for (int column = 0; column < field(this, 0x10); ++column) + for (int column = 0; column < m_gridSize; ++column) { - unsigned char* const cell = - field(this, 0xE4)[column + row * field(this, 0x10)]; - const int patchesX = field(this, 0xD8); - const int patchesZ = field(this, 0xDC); - const int x = patchesX / 2 + field(cell, 0x5C); - const int z = patchesZ / 2 + field(cell, 0x60); + const OverGrowthCell* const cell = m_cells[column + row * m_gridSize]; + const int patchesX = m_patchCountX; + const int patchesZ = m_patchCountZ; + const int x = patchesX / 2 + cell->cellX; + const int z = patchesZ / 2 + cell->cellZ; if (x < 0 || z < 0 || x >= patchesX || z >= patchesZ) continue; - unsigned char* const patch = - field(this, 0xE0) + kPatchSize * (x + z * patchesX); - if (!terrainFrustumIntersectsBox(lightFrustum, &field(patch, 0x5C))) + OverGrowthPatch* const patch = m_patches + (x + z * patchesX); + if (!terrainFrustumIntersectsBox(lightFrustum, &patch->bounds.min.x)) continue; - for (unsigned int index = 0; ; ++index) + for (unsigned int index = 0; index < patch->instances.size(); ++index) { - const unsigned char* const first = field(patch, 0x10); - if (!first || index >= vectorCount(first, field(patch, 0x14), kInstanceSize)) - break; - unsigned char* const instance = field(patch, 0x10) + index * kInstanceSize; - unsigned char* const type = - field(this, 0x50) - + field(instance, 0x00) * static_cast(kDrawTypeSize); - const void* const lodTemplate = field(type, 0x34); - const BoxCorners box(field(lodTemplate, 0xFC), - field(instance, 0x04)); + OverGrowthInstance* const instance = &patch->instances[index]; + OverGrowthGeometryPair* const type = m_geometries.data() + instance->geometryIndex; + const StaticMeshTemplate* const lodTemplate = + static_cast(type->lod.geometryTemplate); + const BoxCorners box(reinterpret_cast(lodTemplate->m_bounds), + instance->transform); bool held = false; - for (unsigned char* record = reinterpret_cast(shadowRecords->first); - record != reinterpret_cast(shadowRecords->last); - record += kShadowRecordSize) + for (const LightShadowRecord* record = shadowRecords.data(); + record != shadowRecords.data() + shadowRecords.size(); ++record) { - if (boxCornersInsideFrustum(box, *reinterpret_cast(record + 0x10))) + if (box.insideFrustum(record->frustum)) // sub_101C6A90 { held = true; break; @@ -797,15 +681,43 @@ void OverGrowth::collectShadowGeometry(OverGrowthShadowVolumes* records, OverGro if (!held) continue; - unsigned char* const pool = field(type, 0x1C) ? type : type + 0x50; + OverGrowthGeometryRecord* const pool = type->lod.geometry ? &type->lod : &type->full; void* geometry = acquireGeometry(pool, instance); - // [CHOSEN, not recovered] growth policy: see acquireGeometry (0x1009A340 stand-in). - vc71::vectorPushBackIn(output, sizeof(void*), &geometry); + output.push_back(geometry); // 0x1009A340 fitShadowFrustumNearPlane(casterFrustum, box.corner); } } } } +// PE 0x100CB7A0: unreachable in 1.50: no code or data references. Walks every patch's instances in +// grid order (x fastest) and, for each instance with a geometry index and the generated flag set, +// creates an object from the geometry pair's object template (IObjectTemplate +0x50 in the PE, +// createObject), gives it the instance's transform (IObject +0x88, setAbsoluteTransformation) and +// initialises it (IObject +0x1C, init), then appends it to the vector. [CHOSEN, not recovered] name. +void OverGrowth::createGeneratedObjects(std::vector* objects) +{ + if (!m_patches) + return; + for (int z = 0; z < m_patchCountZ; ++z) + { + for (int x = 0; x < m_patchCountX; ++x) + { + OverGrowthPatch* const patch = m_patches + (x + z * m_patchCountX); + for (unsigned int index = 0; index < patch->instances.size(); ++index) + { + OverGrowthInstance* const instance = &patch->instances[index]; + if (instance->geometryIndex < 0 || !instance->generated) + continue; + OverGrowthGeometryPair* const type = m_geometries.data() + instance->geometryIndex; + world::IObject* const object = type->full.objectTemplate->createObject(); + object->setAbsoluteTransformation(instance->transform); + object->init(); + objects->push_back(object); + } + } + } +} + } } } #endif \ No newline at end of file diff --git a/Code/BF2/Geom/ParticleSystem/MeshParticleMesh/MeshParticleMesh.cpp b/Code/BF2/Geom/ParticleSystem/MeshParticleMesh/MeshParticleMesh.cpp index 78252d4d0..4c29fd2b2 100644 --- a/Code/BF2/Geom/ParticleSystem/MeshParticleMesh/MeshParticleMesh.cpp +++ b/Code/BF2/Geom/ParticleSystem/MeshParticleMesh/MeshParticleMesh.cpp @@ -2,7 +2,13 @@ // Shared age/alpha and transform arrays provide per-instance data to the renderer. #ifdef BF2_IMAGE_RENDDX9 +#if !defined(_MSC_VER) +// [CHOSEN, not recovered] Typed native geometry table adapters. +#include "../../../../RendDX9Abi/NativeVtable.h" +#include "../../IScaleable.h" +#endif +#include "../../../../RendDX9Abi/ThunkAbi.h" #include "MeshParticleMesh.h" #include "MeshParticleMeshTemplate.h" #include "../../BundledMeshStateManager.h" @@ -12,8 +18,7 @@ #include "../../../../RendDX9Abi/HfeAbi.h" #include "../../../../RendDX9Abi/BfMemory.h" #include "../../../../RendDX9Abi/Frontier.h" // logf -#include "../../../../RendDX9Abi/Vc71Vector.h" -#include "../../../../RendDX9Abi/Vc71Map.h" +#include "../ParticleRendererCallbacks.h" // particleRendererList, the mesh renderer #include #include @@ -71,22 +76,26 @@ MeshBounds s_emptyBounds = { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f } }; -// The shared helper both the constructor and refreshSelection inline (0x101B02A3.. / 0x101B0070). +// A bundled state's first texture (state +0x28 -> [0]), unguarded. +template +void* bundledStateFirstTexture(const std::vector& textures) +{ + return textures.data()[0]; +} + +// The shared helper both the constructor and refreshSelection inline. // NO guards: an unloaded template's null tree faults here in retail too; the geom-count test is // `sar 4` then an unsigned `jb 2`. void selectFromTemplate(MeshParticleMesh* self) { MeshParticleMeshTemplate* const t = self->m_template; - if (t->m_geoms.first - && static_cast(static_cast(t->m_geoms.last - t->m_geoms.first) >> 4) >= 2u) + if (static_cast(t->m_geoms.size()) >= 2u) self->m_geomIndex = 1; const int geom = self->m_geomIndex; const int lod = self->m_lodIndex; - self->m_lodRecord = reinterpret_cast( - reinterpret_cast(t->m_geoms.first)[geom].first) + lod; - self->m_lodMaterials = reinterpret_cast( - reinterpret_cast(t->m_materials.first)[geom].first) + lod; + self->m_lodRecord = t->m_geoms.data()[geom].data() + lod; + self->m_lodMaterials = t->m_materials.data()[geom].data() + lod; } } // anonymous namespace @@ -117,7 +126,8 @@ MeshParticleMesh::MeshParticleMesh(MeshParticleMeshTemplate* objectTemplate) m_alternateView = 0; // +0x7D m_template = objectTemplate; // +0x84 - m_partTransforms = static_cast(::renddx9abi::engineAlloc(0x68)); + // 26 part-transform pointers (retail 0x68 bytes). + m_partTransforms = static_cast(::renddx9abi::engineAlloc(0x68u / 4u * kPsmPointerSize)); for (unsigned int offset = 0; offset < 0x68u; offset += 4) m_partTransforms[offset / 4] = &s_partIdentity[0]; @@ -129,6 +139,7 @@ MeshParticleMesh::MeshParticleMesh(MeshParticleMeshTemplate* objectTemplate) // Unregisters the instance if its template is still alive. // Instances created from an already-loaded template may not be in the live set. +// PE 0x101B0310 MeshParticleMesh::~MeshParticleMesh() { m_vptr = g_meshParticleMeshVtable; // not observable; kept for the reader @@ -136,7 +147,7 @@ MeshParticleMesh::~MeshParticleMesh() if (m_partTransforms) ::renddx9abi::engineFree(m_partTransforms); if (m_template) - vc71::setEraseValue(m_template->m_instances, this); // sub_10129110(&this) + m_template->m_instances.erase(this); // sub_10129110(&this) // off_1020A660 is restored and m_name destroyed by the base - not observable. } @@ -185,13 +196,14 @@ int MeshParticleMesh::release() const int remaining = --m_refCount; if (!remaining) { - typedef void* (__fastcall* DestroyFn)(void*, void*, unsigned int); - reinterpret_cast(m_vptr[0x34 / sizeof(void*)])(this, 0, 1u); // [eax+34h] (1) + typedef void* (__thiscall* DestroyFn)(void*, unsigned int); + reinterpret_cast(m_vptr[0x34 / 4])(this, 1u); // [eax+34h] (1) } return remaining; } // four ids, compared in this order. The IScaleable arm keeps MSVC's `this` null test. +// PE 0x101B03A0 void* MeshParticleMesh::queryInterface(unsigned int iid) { if (iid == 1u // dword_102088DC, IBase @@ -199,10 +211,11 @@ void* MeshParticleMesh::queryInterface(unsigned int iid) || iid == 0xADCBF4FCu) // dword_1021AE64, IID_IRenderable return this; if (iid == 0xEBC881FAu && this) // dword_1021AE68, IID_IScaleable - return reinterpret_cast(this) + 0x30; + return &m_scaleableVptr; // the IScaleable subobject (+0x30) return 0; } +// PE 0x101B0490 void MeshParticleMesh::setFov(float value) { m_fov = value; } // +0x10 float MeshParticleMesh::getFov() const { return m_fov; } // +0x14 @@ -214,18 +227,17 @@ void MeshParticleMesh::queueDraw(void*, void*, int) { if (!m_template->m_loaded) // [eax+4Ch] return; - if (!reinterpret_cast(dx9rend::g_Renderer)[0x69F]) // particles switch + if (!dx9rend::rendererRenderSwitch(0x69F)) // particles switch return; meshParticlesRendererQueueMesh( - reinterpret_cast(g_ParticleSystemManager) + 0x5F30, this); + particleSystemManagerMeshParticlesRenderer(g_ParticleSystemManager), this); } // sub_101B04C0 - `add ecx, 1D80h`, then the fast push when size < capacity, else _Insert_n -// (sub_100D7560, engine heap via sub_1005F320). vectorRef reproduces both arms and the VC7.1 -// growth; its operator new is the same engine heap in this image (BfMemory.h). +// (sub_100D7560, engine heap via sub_1005F320): std::vector::push_back. void meshParticlesRendererQueueMesh(unsigned char* renderer, MeshParticleMesh* mesh) { - vc71::vectorRef(renderer + 0x1D80).push_back(mesh); + meshParticlesRendererMeshes(renderer).push_back(mesh); } // +0x2C, 0x101AFD00 - `mov eax,[ecx+44h]; mov eax,[eax+40h]`. No lod guard. @@ -277,19 +289,18 @@ void MeshParticleMesh::setPartTransformation(const Mat4* value, int part) // +0x50, through THE table: `call [eax+4Ch]` with (value, 0). void MeshParticleMesh::setGeometryTransformation(const Mat4* value) { - typedef void (__fastcall* SetPartFn)(void*, void*, const Mat4*, int); - reinterpret_cast(m_vptr[0x4C / sizeof(void*)])(this, 0, value, 0); + typedef void (__thiscall* SetPartFn)(void*, const Mat4*, int); + reinterpret_cast(m_vptr[0x4C / 4])(this, value, 0); } // Selects geom and the current LOD without checking their range or loaded state. +// PE 0x101B00D0 void MeshParticleMesh::setGeomIndex(int geom) { m_geomIndex = geom; MeshParticleMeshTemplate* const t = m_template; - m_lodRecord = reinterpret_cast( - reinterpret_cast(t->m_geoms.first)[geom].first) + m_lodIndex; - m_lodMaterials = reinterpret_cast( - reinterpret_cast(t->m_materials.first)[geom].first) + m_lodIndex; + m_lodRecord = t->m_geoms.data()[geom].data() + m_lodIndex; + m_lodMaterials = t->m_materials.data()[geom].data() + m_lodIndex; } int MeshParticleMesh::getGeomIndex() const { return m_geomIndex; } // +0x70 @@ -298,9 +309,7 @@ int MeshParticleMesh::getGeomIndex() const { return m_geomIndex; } // +0x int MeshParticleMesh::getGeomCount() const { const MeshParticleMeshTemplate* const t = m_template; - if (!t->m_geoms.first) - return 0; - return static_cast(t->m_geoms.last - t->m_geoms.first) >> 4; + return static_cast(t->m_geoms.size()); } // +0x78, 0x101B0120. -1 = back to lod 0 and clear the explicit byte; otherwise store and raise it. @@ -312,31 +321,24 @@ void MeshParticleMesh::setLodIndex(int lod) { m_lodIndex = 0; m_lodExplicit = 0; - m_lodRecord = reinterpret_cast( - reinterpret_cast(t->m_geoms.first)[m_geomIndex].first); - m_lodMaterials = reinterpret_cast( - reinterpret_cast(t->m_materials.first)[m_geomIndex].first); + m_lodRecord = t->m_geoms.data()[m_geomIndex].data(); + m_lodMaterials = t->m_materials.data()[m_geomIndex].data(); return; } m_lodIndex = lod; m_lodExplicit = 1; - m_lodRecord = reinterpret_cast( - reinterpret_cast(t->m_geoms.first)[m_geomIndex].first) + lod; - m_lodMaterials = reinterpret_cast( - reinterpret_cast(t->m_materials.first)[m_geomIndex].first) + lod; + m_lodRecord = t->m_geoms.data()[m_geomIndex].data() + lod; + m_lodMaterials = t->m_materials.data()[m_geomIndex].data() + lod; } int MeshParticleMesh::getLodIndex() const { return m_lodIndex; } // +0x7C // +0x80, the current geom's lod count (72-byte records, signed division). The geom -// tree itself is indexed unguarded; only the geom's own `first` is tested. +// tree itself is indexed unguarded. int MeshParticleMesh::getLodCount() const { - const vc71::vector_layout& lods = - reinterpret_cast(m_template->m_geoms.first)[m_geomIndex]; - if (!lods.first) - return 0; - return static_cast(lods.last - lods.first) / 72; + const std::vector& lods = m_template->m_geoms.data()[m_geomIndex]; + return static_cast(lods.size()); } // +0xB4, 0x101B0440 - `[ecx+58h] = arg` (a body comdat-shared with the emitter descriptor's slot @@ -347,8 +349,10 @@ void MeshParticleMesh::setDword58(unsigned int value) } unsigned char MeshParticleMesh::getFirstPerson() const { return m_firstPerson; } +// PE 0x101B0460 void MeshParticleMesh::setFirstPerson(unsigned char v) { m_firstPerson = v; } unsigned char MeshParticleMesh::getAlternateView() const { return m_alternateView; } +// PE 0x101B0480 void MeshParticleMesh::setAlternateView(unsigned char v) { m_alternateView = v; } // +0xF8, 0x101AFC60 - `retn 0Ch`: three arguments, nothing done. The table's first slot past the @@ -357,6 +361,17 @@ void MeshParticleMesh::slotF8(unsigned int, unsigned int, unsigned int) { } +// Debug error (MeshParticleMesh.cpp line 0x13F, "no get angle for meshparticlemesh") and a 0.0f result +// (fld of the .rdata zero). The one stack argument and `this` are never read. [INFERRED] name and +// [CHOSEN, not recovered] argument type: no instruction exposes either, and nothing calls it. +// unreachable in 1.50: no code or data references +// PE 0x101AFC70 +float MeshParticleMesh::getAngle(int) +{ + ::renddx9abi::logf("MeshParticleMesh.cpp:319: no get angle for meshparticlemesh"); + return 0.0f; +} + // +0xFC, 0x10188350 - `[ecx+80h] = arg` (comdat-shared with the trail descriptor's slot 97). void MeshParticleMesh::setAlpha(float value) { @@ -387,6 +402,7 @@ const Vec3& MeshParticleMesh::getScale() const // 0x101AFBF0, 31 bytes, `retn 0Ch` - (age, alpha) into AgeAndAlphaArray[index]. No bounds test. +// PE 0x101AFBF0 void MeshParticleMesh::setAgeAndAlpha(float age, float alpha, int index) { s_ageAndAlpha[index].x = age; // dword_10266258[index * 16] @@ -397,15 +413,14 @@ void MeshParticleMesh::setAgeAndAlpha(float age, float alpha, int index) // Draws batched mesh particles with the selected blend technique. // Alpha-mode-1 materials are skipped in both passes. Invalid blend modes retain the prior // technique; material, state and first-texture pointers must be valid. - +// PE 0x101AFDA0 (listing read in full: material loop, alphaMode/transparent tests, technique names, +// shader parameter order, draw argument mapping onto the named rendererDrawIndexedPrimitive order) void MeshParticleMesh::draw(int blendMode, bool transparentPass) { MeshParticleMeshEffectState& shared = g_meshParticleMeshEffectState; - const vc71::vector_layout* const materials = m_lodMaterials; // [edi+48h] - const unsigned int materialCount = materials->first - ? static_cast(static_cast(materials->last - materials->first) / 24) - : 0u; + const std::vector* const materials = m_lodMaterials; // [edi+48h] + const unsigned int materialCount = static_cast(materials->size()); dx9rend::vertexDeclarationBind(m_template->m_vertexDeclaration); // +0xA0, sub_100147C0 dx9rend::vertexBufferBindStream(m_template->m_vertexBuffer, 0); // +0x94, sub_100146C0 @@ -414,8 +429,7 @@ void MeshParticleMesh::draw(int blendMode, bool transparentPass) for (unsigned int i = 0; i < materialCount; ++i) { - const MeshParticleMeshMaterial& material = - reinterpret_cast(m_lodMaterials->first)[i]; + const MeshParticleMeshMaterial& material = m_lodMaterials->data()[i]; BundledMeshState* const state = material.state; // ebx const int alphaMode = material.alphaMode; @@ -432,11 +446,11 @@ void MeshParticleMesh::draw(int blendMode, bool transparentPass) continue; if (blendMode == 1) - dx9rend::effectSetTechniqueByName(shared.effect, vc71::string("Additive")); + dx9rend::effectSetTechniqueByName(shared.effect, std::string("Additive")); else if (blendMode == 2) - dx9rend::effectSetTechniqueByName(shared.effect, vc71::string("DiffuseWithZWrite")); + dx9rend::effectSetTechniqueByName(shared.effect, std::string("DiffuseWithZWrite")); else if (blendMode == 0) - dx9rend::effectSetTechniqueByName(shared.effect, vc71::string("Diffuse")); + dx9rend::effectSetTechniqueByName(shared.effect, std::string("Diffuse")); dx9rend::effectBegin(shared.effect); @@ -445,15 +459,14 @@ void MeshParticleMesh::draw(int blendMode, bool transparentPass) m_lodRecord->partCount); // [eax+28h] dx9rend::effectGetShaderParameterBorrowedTyped( - shared.effect, vc71::string("AgeAndAlphaArray")) + shared.effect, std::string("AgeAndAlphaArray")) ->setValue(s_ageAndAlpha, m_lodRecord->partCount); // sub_1001E3A0, [edx+18h] dx9rend::effectGetShaderParameterBorrowedTyped( - shared.effect, vc71::string("GlobalScale")) + shared.effect, std::string("GlobalScale")) ->setValue(&m_scale, 0); // +0x5C - shared.texture0->setValue( - reinterpret_cast(state->m_textures.first)[0], 0); // state +0x28 -> [0] + shared.texture0->setValue(bundledStateFirstTexture(state->m_textures), 0); // state +0x28 -> [0] dx9rend::effectBeginPass(shared.effect, 0); @@ -483,76 +496,153 @@ namespace { MeshParticleMesh* self(void* p) { return static_cast(p); } MeshParticleMesh* fromScaleable(void* p) { - return reinterpret_cast(static_cast(p) - 0x30); + return reinterpret_cast( + static_cast(p) - offsetof(MeshParticleMesh, m_scaleableVptr)); // `sub ecx, 30h` } -int __fastcall mpm_addRef(void* s, void*) { return self(s)->addRef(); } -int __fastcall mpm_getRef(void* s, void*) { return self(s)->getRef(); } -int __fastcall mpm_release(void* s, void*) { return self(s)->release(); } -void* __fastcall mpm_queryInterface(void* s, void*, unsigned int iid) +int RD9_THUNK mpm_addRef(void* s RD9_THUNK_EDX) { return self(s)->addRef(); } +int RD9_THUNK mpm_getRef(void* s RD9_THUNK_EDX) { return self(s)->getRef(); } +int RD9_THUNK mpm_release(void* s RD9_THUNK_EDX) { return self(s)->release(); } +void* RD9_THUNK mpm_queryInterface(void* s RD9_THUNK_EDX, unsigned int iid) { return self(s)->queryInterface(iid); } -void __fastcall mpm_setFov(void* s, void*, float v) { self(s)->setFov(v); } -float __fastcall mpm_getFov(void* s, void*) { return self(s)->getFov(); } -void __fastcall mpm_queueDraw(void* s, void*, void* a, void* b, int c) +void RD9_THUNK mpm_setFov(void* s RD9_THUNK_EDX, float v) { self(s)->setFov(v); } +float RD9_THUNK mpm_getFov(void* s RD9_THUNK_EDX) { return self(s)->getFov(); } +void RD9_THUNK mpm_queueDraw(void* s RD9_THUNK_EDX, void* a, void* b, int c) { self(s)->queueDraw(a, b, c); } -int __fastcall mpm_getGeometryType(void* s, void*) { return self(s)->getGeometryType(); } -void* __fastcall mpm_destroy(void* s, void*, unsigned int flags) +int RD9_THUNK mpm_getGeometryType(void* s RD9_THUNK_EDX) { return self(s)->getGeometryType(); } +void* RD9_THUNK mpm_destroy(void* s RD9_THUNK_EDX, unsigned int flags) { return meshParticleMeshDestroyFlags(s, static_cast(flags)); } -void* __fastcall mpm_getTemplate(void* s, void*) { return self(s)->getTemplate(); } -const void* __fastcall mpm_getLocalBounds(void* s, void*) { return self(s)->getLocalBounds(); } -float __fastcall mpm_getBoundingRadius(void* s, void*) { return self(s)->getBoundingRadius(); } -const Mat4* __fastcall mpm_getGeometryTransformation(void* s, void*) +void* RD9_THUNK mpm_getTemplate(void* s RD9_THUNK_EDX) { return self(s)->getTemplate(); } +const void* RD9_THUNK mpm_getLocalBounds(void* s RD9_THUNK_EDX) { return self(s)->getLocalBounds(); } +float RD9_THUNK mpm_getBoundingRadius(void* s RD9_THUNK_EDX) { return self(s)->getBoundingRadius(); } +const Mat4* RD9_THUNK mpm_getGeometryTransformation(void* s RD9_THUNK_EDX) { return self(s)->getGeometryTransformation(); } -void __fastcall mpm_setPartTransformation(void* s, void*, const Mat4* v, int part) +void RD9_THUNK mpm_setPartTransformation(void* s RD9_THUNK_EDX, const Mat4* v, int part) { self(s)->setPartTransformation(v, part); } -void __fastcall mpm_setGeometryTransformation(void* s, void*, const Mat4* v) +void RD9_THUNK mpm_setGeometryTransformation(void* s RD9_THUNK_EDX, const Mat4* v) { self(s)->setGeometryTransformation(v); } -void __fastcall mpm_setName(void* s, void*, const vc71::string& name) { self(s)->m_name = name; } -void __fastcall mpm_setGeomIndex(void* s, void*, int g) { self(s)->setGeomIndex(g); } -int __fastcall mpm_getGeomIndex(void* s, void*) { return self(s)->getGeomIndex(); } -int __fastcall mpm_getGeomCount(void* s, void*) { return self(s)->getGeomCount(); } -void __fastcall mpm_setLodIndex(void* s, void*, int l) { self(s)->setLodIndex(l); } -int __fastcall mpm_getLodIndex(void* s, void*) { return self(s)->getLodIndex(); } -int __fastcall mpm_getLodCount(void* s, void*) { return self(s)->getLodCount(); } -void __fastcall mpm_setDword58(void* s, void*, unsigned int v) { self(s)->setDword58(v); } -unsigned char __fastcall mpm_getFirstPerson(void* s, void*) { return self(s)->getFirstPerson(); } -void __fastcall mpm_setFirstPerson(void* s, void*, unsigned int v) +void RD9_THUNK mpm_setName(void* s RD9_THUNK_EDX, const std::string& name) { self(s)->m_name = name; } +void RD9_THUNK mpm_setGeomIndex(void* s RD9_THUNK_EDX, int g) { self(s)->setGeomIndex(g); } +int RD9_THUNK mpm_getGeomIndex(void* s RD9_THUNK_EDX) { return self(s)->getGeomIndex(); } +int RD9_THUNK mpm_getGeomCount(void* s RD9_THUNK_EDX) { return self(s)->getGeomCount(); } +void RD9_THUNK mpm_setLodIndex(void* s RD9_THUNK_EDX, int l) { self(s)->setLodIndex(l); } +int RD9_THUNK mpm_getLodIndex(void* s RD9_THUNK_EDX) { return self(s)->getLodIndex(); } +int RD9_THUNK mpm_getLodCount(void* s RD9_THUNK_EDX) { return self(s)->getLodCount(); } +void RD9_THUNK mpm_setDword58(void* s RD9_THUNK_EDX, unsigned int v) { self(s)->setDword58(v); } +unsigned char RD9_THUNK mpm_getFirstPerson(void* s RD9_THUNK_EDX) { return self(s)->getFirstPerson(); } +void RD9_THUNK mpm_setFirstPerson(void* s RD9_THUNK_EDX, unsigned int v) { self(s)->setFirstPerson(static_cast(v)); } // `mov al, [ebp+8]` - the low byte -unsigned char __fastcall mpm_getAlternateView(void* s, void*) { return self(s)->getAlternateView(); } -void __fastcall mpm_setAlternateView(void* s, void*, unsigned int v) +unsigned char RD9_THUNK mpm_getAlternateView(void* s RD9_THUNK_EDX) { return self(s)->getAlternateView(); } +void RD9_THUNK mpm_setAlternateView(void* s RD9_THUNK_EDX, unsigned int v) { self(s)->setAlternateView(static_cast(v)); } -void __fastcall mpm_slotF8(void* s, void*, unsigned int a, unsigned int b, unsigned int c) +void RD9_THUNK mpm_slotF8(void* s RD9_THUNK_EDX, unsigned int a, unsigned int b, unsigned int c) { self(s)->slotF8(a, b, c); } -void __fastcall mpm_setAlpha(void* s, void*, float v) { self(s)->setAlpha(v); } +void RD9_THUNK mpm_setAlpha(void* s RD9_THUNK_EDX, float v) { self(s)->setAlpha(v); } // The shared bodies. -void __fastcall mpm_empty0(void*, void*) {} -void __fastcall mpm_empty1(void*, void*, unsigned int) {} -void __fastcall mpm_empty2(void*, void*, unsigned int, unsigned int) {} -void __fastcall mpm_empty3(void*, void*, unsigned int, unsigned int, unsigned int) {} -void __fastcall mpm_empty6(void*, void*, unsigned int, unsigned int, unsigned int, +void RD9_THUNK mpm_empty0(void* RD9_THUNK_EDX) {} +void RD9_THUNK mpm_empty1(void* RD9_THUNK_EDX, unsigned int) {} +void RD9_THUNK mpm_empty2(void* RD9_THUNK_EDX, unsigned int, unsigned int) {} +void RD9_THUNK mpm_empty3(void* RD9_THUNK_EDX, unsigned int, unsigned int, unsigned int) {} +void RD9_THUNK mpm_empty6(void* RD9_THUNK_EDX, unsigned int, unsigned int, unsigned int, unsigned int, unsigned int, unsigned int) {} -unsigned int __fastcall mpm_zero0(void*, void*) { return 0; } -unsigned int __fastcall mpm_zero1(void*, void*, unsigned int) { return 0; } -bool __fastcall mpm_false0(void*, void*) { return false; } -bool __fastcall mpm_false1(void*, void*, unsigned int) { return false; } -int __fastcall mpm_minusOne(void*, void*) { return -1; } -int __fastcall mpm_seven(void*, void*) { return 7; } +unsigned int RD9_THUNK mpm_zero0(void* RD9_THUNK_EDX) { return 0; } +unsigned int RD9_THUNK mpm_zero1(void* RD9_THUNK_EDX, unsigned int) { return 0; } +bool RD9_THUNK mpm_false0(void* RD9_THUNK_EDX) { return false; } +bool RD9_THUNK mpm_false1(void* RD9_THUNK_EDX, unsigned int) { return false; } +int RD9_THUNK mpm_minusOne(void* RD9_THUNK_EDX) { return -1; } +int RD9_THUNK mpm_seven(void* RD9_THUNK_EDX) { return 7; } // IScaleable - four adjustor thunks (`sub ecx, 30h; jmp`) and the two bodies. -int __fastcall mpms_addRef(void* s, void*) { return fromScaleable(s)->addRef(); } -int __fastcall mpms_getRef(void* s, void*) { return fromScaleable(s)->getRef(); } -int __fastcall mpms_release(void* s, void*) { return fromScaleable(s)->release(); } -void* __fastcall mpms_queryInterface(void* s, void*, unsigned int iid) +int RD9_THUNK mpms_addRef(void* s RD9_THUNK_EDX) { return fromScaleable(s)->addRef(); } +int RD9_THUNK mpms_getRef(void* s RD9_THUNK_EDX) { return fromScaleable(s)->getRef(); } +int RD9_THUNK mpms_release(void* s RD9_THUNK_EDX) { return fromScaleable(s)->release(); } +void* RD9_THUNK mpms_queryInterface(void* s RD9_THUNK_EDX, unsigned int iid) { return fromScaleable(s)->queryInterface(iid); } -void __fastcall mpms_setScale(void* s, void*, const Vec3& v) { fromScaleable(s)->setScale(v); } -const Vec3& __fastcall mpms_getScale(void* s, void*) { return fromScaleable(s)->getScale(); } +void RD9_THUNK mpms_setScale(void* s RD9_THUNK_EDX, const Vec3& v) { fromScaleable(s)->setScale(v); } +const Vec3& RD9_THUNK mpms_getScale(void* s RD9_THUNK_EDX) { return fromScaleable(s)->getScale(); } } // anonymous namespace #define BF2_MPM_ENTRY(fn) reinterpret_cast(&fn) // The 64-slot table includes a three-argument no-op at +0xF8 and the setter at +0xFC. +#if !defined(_MSC_VER) +// [CHOSEN, not recovered] Preserve the empty opacity body's four-byte carrier. +void mpm_nativeOpacity(void* self, float opacity) +{ + unsigned int bits; + std::memcpy(&bits, &opacity, sizeof(bits)); + mpm_empty1(self, bits); +} +void* const g_meshParticleMeshVtable[] = +{ + BF2_MPM_ENTRY(mpm_addRef), // +0x00 0x10103C00 shared (StaticMesh) + BF2_MPM_ENTRY(mpm_getRef), // +0x04 0x10103C10 shared + BF2_MPM_ENTRY(mpm_release), // +0x08 0x10103C20 shared + BF2_MPM_ENTRY(mpm_queryInterface), // +0x0C 0x101B03A0 own + BF2_MPM_ENTRY(mpm_setFov), // +0x10 0x101B0490 own + BF2_MPM_ENTRY(mpm_getFov), // +0x14 0x101B04A0 own + BF2_MPM_ENTRY(mpm_queueDraw), // +0x18 0x101B0370 own + BF2_MPM_ENTRY(mpm_empty2), // +0x1C 0x100E1480 shared (silhouette) + BF2_MPM_ENTRY(mpm_empty6), // +0x20 0x10082D20 shared (shadow map) + BF2_MPM_ENTRY(mpm_empty1), // +0x24 0x100E13B0 shared + BF2_MPM_ENTRY(mpm_zero0), // +0x28 0x100ED3B0 shared + BF2_MPM_ENTRY(mpm_getGeometryType), // +0x2C 0x101AFD00 own + BF2_MPM_ENTRY(mpm_false1), // +0x30 0x1005DA00 shared + BF2_MPM_ENTRY(mpm_destroy), // +0x34 0x101B0520 own + BF2_MPM_ENTRY(mpm_getTemplate), // +0x38 0x10145640 shared (comdat) + BF2_MPM_ENTRY(mpm_zero1), // +0x3C 0x10088060 shared + BF2_MPM_ENTRY(mpm_getLocalBounds), // +0x40 0x101B03E0 own + BF2_MPM_ENTRY(mpm_getBoundingRadius), // +0x44 0x101B0400 own + BF2_MPM_ENTRY(mpm_getGeometryTransformation), // +0x48 0x101AFC10 own + BF2_MPM_ENTRY(mpm_setPartTransformation), // +0x4C 0x101AFD80 own + BF2_MPM_ENTRY(mpm_setGeometryTransformation), // +0x50 0x101AFC20 own + BF2_MPM_ENTRY(mpm_empty2), // +0x54 0x100E1480 shared + BF2_MPM_ENTRY(mpm_empty1), // +0x58 0x100E13B0 shared + BF2_MPM_ENTRY(mpm_zero0), // +0x5C 0x100ED3B0 shared + BF2_MPM_ENTRY(mpm_empty2), // +0x60 0x100E1480 shared + BF2_MPM_ENTRY(mpm_empty1), // +0x64 0x100E13B0 shared + BF2_MPM_ENTRY(mpm_setName), // +0x68 0x10082D30 shared + BF2_MPM_ENTRY(mpm_setGeomIndex), // +0x6C 0x101B00D0 own + BF2_MPM_ENTRY(mpm_getGeomIndex), // +0x70 0x101AFC40 own + BF2_MPM_ENTRY(mpm_getGeomCount), // +0x74 0x101AFD10 own + BF2_MPM_ENTRY(mpm_setLodIndex), // +0x78 0x101B0120 own + BF2_MPM_ENTRY(mpm_getLodIndex), // +0x7C 0x101B0430 own + BF2_MPM_ENTRY(mpm_getLodCount), // +0x80 0x101B01B0 own + BF2_MPM_ENTRY(mpm_empty1), // +0x84 0x100E13B0 shared + BF2_MPM_ENTRY(mpm_minusOne), // +0x88 0x10082D40 shared + BF2_MPM_ENTRY(mpm_zero0), // +0x8C 0x100ED3B0 shared (material count 0!) + BF2_MPM_ENTRY(mpm_empty3), // +0x90 0x10083AB0 shared + BF2_MPM_ENTRY(mpm_empty2), // +0x94 0x100E1480 shared + BF2_MPM_ENTRY(mpm_empty2), // +0x98 0x100E1480 shared + BF2_MPM_ENTRY(mpm_empty1), // +0x9C 0x100E13B0 shared (owner: ignored) + BF2_MPM_ENTRY(mpm_zero0), // +0xA0 0x100ED3B0 shared + BF2_MPM_ENTRY(mpm_zero0), // +0xA4 0x100ED3B0 shared (root: none) + BF2_MPM_ENTRY(mpm_false0), // +0xA8 0x10083AF0 shared (no shadow) + BF2_MPM_ENTRY(mpm_empty1), // +0xAC 0x100E13B0 shared + BF2_MPM_ENTRY(mpm_zero0), // +0xB0 0x100ED3B0 shared + BF2_MPM_ENTRY(mpm_setDword58), // +0xB4 0x101B0440 shared (comdat) + BF2_MPM_ENTRY(mpm_empty1), // +0xB8 0x100E13B0 shared + BF2_MPM_ENTRY(mpm_false0), // +0xBC 0x10083AF0 shared + BF2_MPM_ENTRY(mpm_empty2), // +0xC0 0x100E1480 shared + BF2_MPM_ENTRY(mpm_zero0), // +0xC4 0x100ED3B0 shared + BF2_MPM_ENTRY(mpm_zero1), // +0xC8 0x10088060 shared + BF2_MPM_ENTRY(mpm_zero0), // +0xCC 0x100ED3B0 shared (no next geometry) + BF2_MPM_ENTRY(mpm_getFirstPerson), // +0xD0 0x101B0450 own + BF2_MPM_ENTRY(mpm_setFirstPerson), // +0xD4 0x101B0460 own + BF2_MPM_ENTRY(mpm_getAlternateView), // +0xD8 0x101B0470 own + BF2_MPM_ENTRY(mpm_setAlternateView), // +0xDC 0x101B0480 own + BF2_MPM_ENTRY(mpm_empty1), // +0xE0 0x100E13B0 shared + BF2_MPM_ENTRY(mpm_seven), // +0xE4 0x10082D50 shared + BF2_MPM_ENTRY(mpm_zero0), // +0xE8 0x100ED3B0 shared + BF2_MPM_ENTRY(mpm_zero1), // +0xEC 0x10088060 shared + BF2_MPM_ENTRY(mpm_empty0), // +0xF0 0x10037D40 shared (NO frame stamp) + BF2_MPM_ENTRY(mpm_nativeOpacity), // +0xF4 0x100E13B0 shared (fade ignored) + BF2_MPM_ENTRY(mpm_slotF8), // +0xF8 0x101AFC60 own, retn 0Ch + BF2_MPM_ENTRY(mpm_setAlpha) // +0xFC 0x10188350 shared (comdat) +}; +#else void* const g_meshParticleMeshVtable[64] = { BF2_MPM_ENTRY(mpm_addRef), // +0x00 0x10103C00 shared (StaticMesh) @@ -620,8 +710,21 @@ void* const g_meshParticleMeshVtable[64] = BF2_MPM_ENTRY(mpm_slotF8), // +0xF8 0x101AFC60 own, retn 0Ch BF2_MPM_ENTRY(mpm_setAlpha) // +0xFC 0x10188350 shared (comdat) }; +#endif // IScaleable, six slots, zero-terminated in the image (0x10221B8C = 0). +#if !defined(_MSC_VER) +// [CHOSEN, not recovered] Use the shared native scale-interface signatures. +void* const g_meshParticleMeshScaleableVtable[6] = +{ + BF2_NATIVE_SLOT(::dice::hfe::geom::IScaleable, addRef, mpms_addRef), + BF2_NATIVE_SLOT(::dice::hfe::geom::IScaleable, getRef, mpms_getRef), + BF2_NATIVE_SLOT(::dice::hfe::geom::IScaleable, release, mpms_release), + BF2_NATIVE_SLOT(::dice::hfe::geom::IScaleable, queryInterface, mpms_queryInterface), + BF2_NATIVE_SLOT(::dice::hfe::geom::IScaleable, setScale, mpms_setScale), + BF2_NATIVE_SLOT(::dice::hfe::geom::IScaleable, getScale, mpms_getScale), +}; +#else void* const g_meshParticleMeshScaleableVtable[6] = { BF2_MPM_ENTRY(mpms_addRef), // +0x00 0x10103C50 thunk (StaticMesh's) @@ -631,6 +734,7 @@ void* const g_meshParticleMeshScaleableVtable[6] = BF2_MPM_ENTRY(mpms_setScale), // +0x10 BF2_MPM_ENTRY(mpms_getScale) // +0x14 }; +#endif #undef BF2_MPM_ENTRY diff --git a/Code/BF2/Geom/ParticleSystem/MeshParticleMesh/MeshParticleMesh.h b/Code/BF2/Geom/ParticleSystem/MeshParticleMesh/MeshParticleMesh.h index 9d9150d65..f5dfe557d 100644 --- a/Code/BF2/Geom/ParticleSystem/MeshParticleMesh/MeshParticleMesh.h +++ b/Code/BF2/Geom/ParticleSystem/MeshParticleMesh/MeshParticleMesh.h @@ -10,8 +10,8 @@ #include "../../GeometryInstanceData.h" #include "../../../Math/Mat4.h" #include "../../../Math/Vec3.h" -#include "../../../../RendDX9Abi/Vc71Vector.h" #include +#include namespace dice { namespace hfe { @@ -19,6 +19,7 @@ namespace geom { class MeshParticleMeshTemplate; struct MeshParticleMeshLod; +struct MeshParticleMeshMaterial; // Batches type-1 particles and queues legacy Particle/Bundle geometry for drawExtras. // Retail vtables are adapter arrays in MeshParticleMesh.cpp; preserve all 64 primary slots. @@ -59,6 +60,7 @@ class MeshParticleMesh : public GeometryInstanceData void setAlternateView(unsigned char value); // +0xDC void slotF8(unsigned int a, unsigned int b, unsigned int c); // +0xF8 0x101AFC60, empty void setAlpha(float value); // +0xFC (shared body) + float getAngle(int index); // PE 0x101AFC70, unreferenced // IScaleable, the +0x30 subobject (0x10221B74) void setScale(const Vec3& scale); // sub+0x10 0x101AFD40 @@ -77,14 +79,14 @@ class MeshParticleMesh : public GeometryInstanceData // current (geom, lod). Not a vtable slot. The constructor inlines the same body. void refreshSelection(); - // layout + // layout; the `+0xNN` comments are the retail offsets void* const* m_scaleableVptr; // +0x030 int m_refCount; // +0x034 const Mat4** m_partTransforms; // +0x038 26 entries unsigned int m_dword3C; // +0x03C ctor 0 [UNRESOLVED] float m_fov; // +0x040 ctor -1.0f MeshParticleMeshLod* m_lodRecord; // +0x044 - vc71::vector_layout* m_lodMaterials; // +0x048 vector + std::vector* m_lodMaterials; // +0x048 the template's lod materials int m_geomIndex; // +0x04C int m_lodIndex; // +0x050 unsigned char m_lodExplicit; // +0x054 @@ -100,21 +102,7 @@ class MeshParticleMesh : public GeometryInstanceData }; #if defined(_M_IX86) -#define BF2_MPM_OFFSET(member, offset) \ - static_assert(offsetof(MeshParticleMesh, member) == offset, #member) -BF2_MPM_OFFSET(m_name, 0x04); BF2_MPM_OFFSET(m_float28, 0x28); -BF2_MPM_OFFSET(m_scaleableVptr, 0x30); BF2_MPM_OFFSET(m_refCount, 0x34); -BF2_MPM_OFFSET(m_partTransforms, 0x38); BF2_MPM_OFFSET(m_dword3C, 0x3C); -BF2_MPM_OFFSET(m_fov, 0x40); BF2_MPM_OFFSET(m_lodRecord, 0x44); -BF2_MPM_OFFSET(m_lodMaterials, 0x48); BF2_MPM_OFFSET(m_geomIndex, 0x4C); -BF2_MPM_OFFSET(m_lodIndex, 0x50); BF2_MPM_OFFSET(m_lodExplicit, 0x54); -BF2_MPM_OFFSET(m_dword58, 0x58); BF2_MPM_OFFSET(m_scale, 0x5C); -BF2_MPM_OFFSET(m_unknown6C, 0x6C); BF2_MPM_OFFSET(m_firstPerson, 0x7C); -BF2_MPM_OFFSET(m_alternateView, 0x7D); BF2_MPM_OFFSET(m_alpha, 0x80); -BF2_MPM_OFFSET(m_template, 0x84); -#undef BF2_MPM_OFFSET -static_assert(sizeof(MeshParticleMesh) == 0x88, - "MeshParticleMeshTemplate::createInstance (0x10127870) allocates 0x88"); +static_assert(offsetof(MeshParticleMesh, m_name) == 0x04, "m_name"); #endif // The retail primary and IScaleable tables as adapter arrays (MeshParticleMesh.cpp). @@ -129,9 +117,10 @@ void* meshParticleMeshDestroyFlags(void* instance, unsigned char flags); void meshParticleMeshRefreshSelection(MeshParticleMesh* instance); // sub_101B04C0 (84 B) - the MeshParticlesRenderer's inline push_back onto its retained pointer list -// at renderer +0x1D80 (a VC7.1 vector_layout; the renderer's constructor zeroes +0x1D84..+0x1D8C). +// at renderer +0x1D80 (a std::vector the renderer's constructor builds in place). // The body sits in this TU's address range because MSVC instantiated the renderer's inline member -// here; IGeometry +0x18 is its only caller. `renderer` is g_ParticleSystemManager + 0x5F30. +// here; IGeometry +0x18 is its only caller. `renderer` is the manager's embedded MeshParticles +// renderer (retail g_ParticleSystemManager + 0x5F30). void meshParticlesRendererQueueMesh(unsigned char* renderer, MeshParticleMesh* mesh); } // namespace geom diff --git a/Code/BF2/Geom/ParticleSystem/MeshParticleMesh/MeshParticleMeshTemplate.cpp b/Code/BF2/Geom/ParticleSystem/MeshParticleMesh/MeshParticleMeshTemplate.cpp index 32381ab51..fb710972f 100644 --- a/Code/BF2/Geom/ParticleSystem/MeshParticleMesh/MeshParticleMeshTemplate.cpp +++ b/Code/BF2/Geom/ParticleSystem/MeshParticleMesh/MeshParticleMeshTemplate.cpp @@ -47,30 +47,10 @@ const char kMeshesFolder[] = "Meshes/"; const char kShadersFolder[] = "Shaders/"; -// sub_10128790 - the std::set header node: VC7.1's _Buynode, which constructs the three links with -// placement NEW - and placement new tests the address it is handed. The first test is therefore the -// node itself (0x101287C9); the other two are node+4 / node+8 (0x101287E0 / 0x101287F6), which are -// never null. The colour and nil bytes are plain stores, so a failed allocation faults at [4], as in -// retail. -// Byte-identical in shape to SkinnedMeshTemplate.cpp's 0x101117A0, which is file-local there. - -vc71::set_node* setConstructHead() -{ - vc71::set_node* node = - static_cast(::renddx9abi::engineAlloc(sizeof(vc71::set_node))); - ::new (static_cast(&node->left)) vc71::set_node*(0); // [+0], tested on the node - ::new (static_cast(&node->parent)) vc71::set_node*(0); // [+4], tested on node+4 - ::new (static_cast(&node->right)) vc71::set_node*(0); // [+8], tested on node+8 - node->color = 1; - node->isNil = 0; - return node; -} - - -// sub_100750C0 - `n == 0 ? true : _strnicmp(a.c_str(), b.c_str(), n) == 0`. A case-insensitive +// PE 0x100750C0 (listing read) - `n == 0 ? true : _strnicmp(a.c_str(), b.c_str(), n) == 0`. A case-insensitive // prefix test with the string pair in ecx/edx and the count on the stack. [INFERRED] name. -bool stringEqualsNoCase(const vc71::string& a, const vc71::string& b, unsigned int count) +bool stringEqualsNoCase(const std::string& a, const std::string& b, unsigned int count) { if (!count) return true; @@ -78,74 +58,19 @@ bool stringEqualsNoCase(const vc71::string& a, const vc71::string& b, unsigned i } -// Engine-heap compatibility-vector helpers. Growth copies a prototype; shrink destroys -// nested buffers, while POD material shrink does not release state references. -// [CHOSEN, not recovered] [RETIRE-WHEN: RW-74] Replace allocation details after shared -// container behavior, layout and ownership are validated. - -unsigned int vectorCount(const vc71::vector_layout& v, unsigned int elemSize) +// MeshTemplate's per-geom vectors - +0x50 lod counts, +0x60 lod distances, +0x70 skipped lods. +template +unsigned int meshGeomCount(const std::vector& v) { - return v.first ? static_cast(v.last - v.first) / elemSize : 0u; -} - -void vectorFreeNestedRange(char* begin, char* end, bool twoLevels) -{ - for (char* p = begin; p != end; p += sizeof(vc71::vector_layout)) - { - vc71::vector_layout& element = *reinterpret_cast(p); - if (element.first) - { - if (twoLevels) - vectorFreeNestedRange(element.first, element.last, false); // sub_1012AC30's inner - ::renddx9abi::engineFree(element.first); - } - element.first = 0; - element.last = 0; - element.end = 0; - } + return static_cast(v.size()); } -void vectorResize(vc71::vector_layout& v, unsigned int count, unsigned int elemSize, - const void* prototype, int nestedLevels) +template +T& meshGeomInt(std::vector& v, unsigned int geom) { - const unsigned int size = vectorCount(v, elemSize); - if (count <= size) - { - if (count < size && v.first) - { - char* const newLast = v.first + elemSize * count; - if (nestedLevels) - vectorFreeNestedRange(newLast, v.last, nestedLevels > 1); - v.last = newLast; - } - return; - } - - const unsigned int capacity = - v.first ? static_cast(v.end - v.first) / elemSize : 0u; - if (count > capacity) - { - unsigned int grown = capacity + (capacity >> 1); - if (grown < count) - grown = count; - char* const buffer = static_cast(::renddx9abi::engineAlloc(elemSize * grown)); - if (size) - std::memcpy(buffer, v.first, elemSize * size); - if (v.first) - ::renddx9abi::engineFree(v.first); - v.first = buffer; - v.last = buffer + elemSize * size; - v.end = buffer + elemSize * grown; - } - - for (unsigned int i = size; i < count; ++i) - std::memcpy(v.first + elemSize * i, prototype, elemSize); - v.last = v.first + elemSize * count; + return v.data()[geom]; } -// A zeroed vector_layout whose allocator word is left alone - what every nested-resize caller pushes -// (`mov [eax+4], ebx` / `[eax+8]` / `[eax+0Ch]`, nothing at [eax]). -const vc71::vector_layout kEmptyNestedVector = { 0, 0, 0, 0 }; // The release block inside the destructor (0x10127B8D..0x10127C98), run when the last template dies. @@ -187,7 +112,7 @@ void lookupParameterOnce(dx9rend::ShaderParameter*& slot, const char* name) { if (!slot) slot = dx9rend::effectGetShaderParameterTyped(g_meshParticleMeshEffectState.effect, - vc71::string(name)); + std::string(name)); } } // anonymous namespace @@ -203,7 +128,7 @@ IBase* __fastcall createMeshParticleMeshTemplate(unsigned int iid, IBase* outer) if (outer) return 0; - void* const storage = ::renddx9abi::engineAlloc(0x164); + void* const storage = ::renddx9abi::engineAlloc(sizeof(MeshParticleMeshTemplate)); MeshParticleMeshTemplate* self = 0; if (storage) self = new (storage) MeshParticleMeshTemplate(); @@ -216,32 +141,15 @@ IBase* __fastcall createMeshParticleMeshTemplate(unsigned int iid, IBase* outer) // 0x10127A30, 133 bytes. The base runs first (0x101924F0 = MeshTemplate::MeshTemplate), then the two -// vptrs, then this class's stores in the order below. +// vptrs, then this class's stores in the order below. The material table, the instance set +// (sub_10128790's header node) and the lod table are constructed as members. -// Leaves allocator/comparator storage and the 26-part array untouched. +// Leaves the 26-part array untouched. // Increments the live-template count after clearing the load/keep flag. - +// PE 0x10127A30 MeshParticleMeshTemplate::MeshParticleMeshTemplate() - : MeshTemplate() + : MeshTemplate(), m_refCount(1) { - m_refCount = 1; // +0xC8 - - m_materials.first = 0; // +0xD0 .. +0xD8 - m_materials.last = 0; - m_materials.end = 0; - - // sub_10128790, then `[head+11h] = 1` and the three self links, then size = 0. - m_instances.head = setConstructHead(); - m_instances.head->isNil = 1; - m_instances.head->parent = m_instances.head; - m_instances.head->left = m_instances.head; - m_instances.head->right = m_instances.head; - m_instances.size = 0; - - m_geoms.first = 0; // +0xEC .. +0xF4 - m_geoms.last = 0; - m_geoms.end = 0; - m_isDecal = 0; // +0x160 m_keepData = 0; // +0x04 ++g_meshParticleMeshEffectState.templateCount; // `add dword_1025BEDC, 1` @@ -250,33 +158,29 @@ MeshParticleMeshTemplate::MeshParticleMeshTemplate() // Clears instance template pointers before destroying containers. Surviving instances must not draw. // Shared effect release occurs inside the material loop, so a last empty template leaves -// shared handles alive. Material storage must cover all declared LOD counts. - +// shared handles alive. Material storage must cover all declared LOD counts (no bounds test). +// PE 0x10127AC0 void MeshParticleMeshTemplate::destroyMembers() { --g_meshParticleMeshEffectState.templateCount; // `sub dword_1025BEDC, 1` - const unsigned int geomCount = vectorCount(m_lodCounts, 4); + const unsigned int geomCount = meshGeomCount(m_lodCounts); for (unsigned int geom = 0; geom < geomCount; ++geom) { - const unsigned int lodCount = reinterpret_cast(m_lodCounts.first)[geom]; + const unsigned int lodCount = static_cast(meshGeomInt(m_lodCounts, geom)); for (unsigned int lod = 0; lod < lodCount; ++lod) { // `mov eax,[this+0D0h]; mov esi,[eax+geom*16+4]; add esi, lod*16` - re-read every lod. - vc71::vector_layout* const lodMaterials = - reinterpret_cast( - reinterpret_cast(m_materials.first)[geom].first) + lod; - if (!lodMaterials->first) + LodMaterials& lodMaterials = m_materials.data()[geom].data()[lod]; + if (lodMaterials.empty()) continue; // Signed division by 24 (`imul 2AAAAAABh; sar edx,2` plus the sign fix-up). - const int materialCount = - static_cast(lodMaterials->last - lodMaterials->first) / 24; + const int materialCount = static_cast(lodMaterials.size()); for (int m = 0; m < materialCount; ++m) { // `mov eax,[esi+4]` - `first` is re-read on every material. - MeshParticleMeshMaterial* const record = - reinterpret_cast(lodMaterials->first) + m; + MeshParticleMeshMaterial* const record = lodMaterials.data() + m; if (record->state) record->state->release(); // [edx+8] @@ -287,40 +191,18 @@ void MeshParticleMeshTemplate::destroyMembers() } // Detach every live instance: `mov [key+84h], 0` along the in-order walk. - for (vc71::set_node* node = m_instances.head->left; - node != m_instances.head; - node = vc71::set_layout::next(node)) - { - reinterpret_cast(node->key)->m_template = 0; - } + for (InstanceSet::iterator node = m_instances.begin(); node != m_instances.end(); ++node) + (*node)->m_template = 0; // +0xE8: free each geom's lod buffer, then the outer buffer. - if (m_geoms.first) - { - vectorFreeNestedRange(m_geoms.first, m_geoms.last, false); - ::renddx9abi::engineFree(m_geoms.first); - } - m_geoms.first = 0; - m_geoms.last = 0; - m_geoms.end = 0; + m_geoms.~LodTable(); - // +0xDC: erase(begin, end) (sub_10128FA0's whole-tree arm), free the head, clear head and size. - // The comparator word is left alone, as it was at construction. - m_instances.clear(); - ::renddx9abi::engineFree(m_instances.head); - m_instances.head = 0; - m_instances.size = 0; + // +0xDC: erase(begin, end) (sub_10128FA0's whole-tree arm), then free the head. + m_instances.~InstanceSet(); // +0xCC: sub_1012AC30 over [first, last) - every geom's lod vectors' buffers, then each geom's // buffer - then the outer buffer. - if (m_materials.first) - { - vectorFreeNestedRange(m_materials.first, m_materials.last, true); - ::renddx9abi::engineFree(m_materials.first); - } - m_materials.first = 0; - m_materials.last = 0; - m_materials.end = 0; + m_materials.~MaterialTable(); MeshTemplate::destroyMembers(); } @@ -362,6 +244,7 @@ int MeshParticleMeshTemplate::release() // (0x17701FFF), zero otherwise. Unlike MeshTemplate's 0x100EE940 it does NOT hand out the // io::IConsoleSaveable subobject for 0x3709A4FF. The `setnz / sub 1 / and` idiom is a branch-free // select of `this` or zero; it has no null guard to reproduce. +// PE 0x1013B240 void* MeshParticleMeshTemplate::queryInterface(unsigned int iid) const { if (iid == kIID_IBase || iid == kIID_IGeometryTemplate) @@ -378,10 +261,11 @@ unsigned int MeshParticleMeshTemplate::getClassId() const // Names starting with "decal_" set the decal flag; renaming never clears it. -void MeshParticleMeshTemplate::setName(const vc71::string& name) +// PE 0x10127510 +void MeshParticleMeshTemplate::setName(const std::string& name) { m_name = name; // +0x14, MSVCP71 operator= - const bool decal = stringEqualsNoCase(m_name, vc71::string("decal_"), 6); + const bool decal = stringEqualsNoCase(m_name, std::string("decal_"), 6); if (decal) m_isDecal = 1; } @@ -389,10 +273,10 @@ void MeshParticleMeshTemplate::setName(const vc71::string& name) // Creates an instance and loads the template if needed, registering it before load refreshes. // Failure removes and destroys the instance; its destructor tolerates the repeated removal. - +// PE 0x10127870 void* MeshParticleMeshTemplate::createInstance() { - void* const storage = ::renddx9abi::engineAlloc(0x88); + void* const storage = ::renddx9abi::engineAlloc(sizeof(MeshParticleMesh)); MeshParticleMesh* const instance = storage ? meshParticleMeshConstruct(storage, this) : 0; @@ -402,7 +286,7 @@ void* MeshParticleMeshTemplate::createInstance() return instance; } - m_instances.insert(reinterpret_cast(instance)); + m_instances.insert(instance); if (m_loaded || dx9rend::resourceManagerIsReady() // sub_1000D950(ds:1023B988) || load()) // [edx+2Ch] @@ -411,7 +295,7 @@ void* MeshParticleMeshTemplate::createInstance() return instance; } - vc71::setEraseValue(m_instances, instance); + m_instances.erase(instance); if (instance) meshParticleMeshDestroyFlags(instance, 1); // [edx+34h] (1) return 0; @@ -421,17 +305,18 @@ void* MeshParticleMeshTemplate::createInstance() // Loads a .bundledMesh, preferring a GPU variant when available after the plain-path check. // Parse failure keeps loaded clear for retry; success marks it before updating live instances. +// PE 0x10127570 (diagnostic line 185) bool MeshParticleMeshTemplate::load() { if (m_loaded) // +0x4C return false; - vc71::string path(m_path); // var_58 + std::string path(m_path); // var_58 path += kMeshesFolder; path += m_name; path += ".bundledMesh"; - vc71::string gpuPath(m_path); // var_74 + std::string gpuPath(m_path); // var_74 gpuPath += kMeshesFolder; gpuPath += "gpu_"; gpuPath += m_name; @@ -463,12 +348,8 @@ bool MeshParticleMeshTemplate::load() m_loaded = 1; // +0x4C, before the walk // `mov ecx,[node+0Ch]; call sub_101B0070` then the iterator ++ (sub_1009F6E0). - for (vc71::set_node* node = m_instances.head->left; - node != m_instances.head; - node = vc71::set_layout::next(node)) - { - meshParticleMeshRefreshSelection(reinterpret_cast(node->key)); - } + for (InstanceSet::iterator node = m_instances.begin(); node != m_instances.end(); ++node) + meshParticleMeshRefreshSelection(*node); return true; } @@ -476,31 +357,27 @@ bool MeshParticleMeshTemplate::load() // Reads every LOD without skipping or distance filtering. // [CHOSEN, not recovered] Prototype padding and fields overwritten by parsing are zeroed. +// PE 0x10127910 void MeshParticleMeshTemplate::readLods(::renddx9abi::HostNonlinearStream* stream) { - const unsigned int geomCount = vectorCount(m_lodCounts, 4); // var_10 + const unsigned int geomCount = meshGeomCount(m_lodCounts); // var_10 - vectorResize(m_geoms, geomCount, sizeof(vc71::vector_layout), - &kEmptyNestedVector, 1); + m_geoms.resize(geomCount); for (unsigned int geom = 0; geom < geomCount; ++geom) { - const unsigned int lodCount = reinterpret_cast(m_lodCounts.first)[geom]; + const unsigned int lodCount = static_cast(meshGeomInt(m_lodCounts, geom)); MeshParticleMeshLod prototype; std::memset(&prototype, 0, sizeof(prototype)); prototype.bounds.dirty = 1; - vc71::vector_layout& lods = - reinterpret_cast(m_geoms.first)[geom]; - vectorResize(lods, lodCount, sizeof(MeshParticleMeshLod), &prototype, 0); + m_geoms[geom].resize(lodCount, prototype); for (unsigned int lod = 0; lod < lodCount; ++lod) { // `mov eax,[this+0ECh]; add eax, geom*16; mov esi,[eax+4]; add esi, lod*72` - re-read. - MeshParticleMeshLod* const record = - reinterpret_cast( - reinterpret_cast(m_geoms.first)[geom].first) + lod; + MeshParticleMeshLod* const record = m_geoms[geom].data() + lod; // The version gate every mesh template shares: head 0 and version < 10 is the old // 36-byte bounds record. (ecx = bounds, edx = stream - the tree's two readers.) @@ -518,50 +395,40 @@ void MeshParticleMeshTemplate::readLods(::renddx9abi::HostNonlinearStream* strea // Reads materials using the shared MeshParticleMesh effect, ignoring file effect names. // Requires a BundledMesh state manager and effect-name lengths of at least three. // Unlike other mesh templates, this path does not swap mip classes or build a technique table. - +// PE 0x10127E00 void MeshParticleMeshTemplate::readMaterials(::renddx9abi::HostNonlinearStream* stream) { MeshParticleMeshEffectState& shared = g_meshParticleMeshEffectState; - const unsigned int geomCount = vectorCount(m_lodCounts, 4); // var_10 + const unsigned int geomCount = meshGeomCount(m_lodCounts); // var_10 - vectorResize(m_materials, geomCount, sizeof(vc71::vector_layout), - &kEmptyNestedVector, 2); + m_materials.resize(geomCount); for (unsigned int geom = 0; geom < geomCount; ++geom) // var_C / var_4 = 16*geom { - const unsigned int lodCount = reinterpret_cast(m_lodCounts.first)[geom]; + const unsigned int lodCount = static_cast(meshGeomInt(m_lodCounts, geom)); - vc71::vector_layout& geomMaterials = - reinterpret_cast(m_materials.first)[geom]; - vectorResize(geomMaterials, lodCount, sizeof(vc71::vector_layout), - &kEmptyNestedVector, 1); + m_materials[geom].resize(lodCount); for (unsigned int lod = 0; lod < lodCount; ++lod) // var_24 counts down { // Both trees are re-read from `this` for every lod. - vc71::vector_layout* const lodMaterials = - reinterpret_cast( - reinterpret_cast(m_materials.first)[geom].first) + lod; + LodMaterials& lodMaterials = m_materials[geom][lod]; unsigned int materialCount = 0; // var_1C stream->read(&materialCount, 4); // An all-zero 24-byte prototype - `[edx] .. [edx+14h]` all written, this one complete. const MeshParticleMeshMaterial prototype = { 0, 0, 0, 0, 0, 0 }; - vectorResize(*lodMaterials, materialCount, sizeof(MeshParticleMeshMaterial), - &prototype, 0); + lodMaterials.resize(materialCount, prototype); - MeshParticleMeshLod* const lodRecord = - reinterpret_cast( - reinterpret_cast(m_geoms.first)[geom].first) + lod; + MeshParticleMeshLod* const lodRecord = m_geoms[geom].data() + lod; lodRecord->renderKind = 3; // lod +0x40 lodRecord->hasAlphaTest = 0; // lod +0x44 (byte) for (unsigned int m = 0; m < materialCount; ++m) // var_14 { // `mov edx,[ebx+4]; lea ecx,[m+m*2]; lea ebx,[edx+ecx*8]` - first re-read per material. - MeshParticleMeshMaterial* const record = - reinterpret_cast(lodMaterials->first) + m; + MeshParticleMeshMaterial* const record = lodMaterials.data() + m; std::memset(record, 0, sizeof(*record)); // the six zero stores if (m_version >= 5u) // +0xA8 @@ -596,7 +463,7 @@ void MeshParticleMeshTemplate::readMaterials(::renddx9abi::HostNonlinearStream* fxName[fxNameLength - 3] = 0; // [len - 3], see the header note ::renddx9abi::engineFree(fxName); } - vc71::string effectName(kShadersFolder); // *unk_10263DF0 + std::string effectName(kShadersFolder); // *unk_10263DF0 effectName += "MeshParticleMesh"; shared.effect = static_cast( dx9rend::shaderManagerGetEffect(dx9rend::g_shaderManager, @@ -610,7 +477,7 @@ void MeshParticleMeshTemplate::readMaterials(::renddx9abi::HostNonlinearStream* if (!shared.worldViewProjection) { shared.worldViewProjection = dx9rend::effectGetShaderParameterTyped( - shared.effect, vc71::string("WorldViewProjection")); + shared.effect, std::string("WorldViewProjection")); if (!shared.worldViewProjection) { // Debug type 6, MeshParticleMeshTemplate.cpp:318 (0x13E). Unreachable in diff --git a/Code/BF2/Geom/ParticleSystem/MeshParticleMesh/MeshParticleMeshTemplate.h b/Code/BF2/Geom/ParticleSystem/MeshParticleMesh/MeshParticleMeshTemplate.h index 4c44c3bc9..a791eb30f 100644 --- a/Code/BF2/Geom/ParticleSystem/MeshParticleMesh/MeshParticleMeshTemplate.h +++ b/Code/BF2/Geom/ParticleSystem/MeshParticleMesh/MeshParticleMeshTemplate.h @@ -10,9 +10,9 @@ #ifdef BF2_IMAGE_RENDDX9 #include "../../MeshTemplate.h" -#include "../../../../RendDX9Abi/Vc71Vector.h" -#include "../../../../RendDX9Abi/Vc71Map.h" #include +#include +#include namespace dice { namespace hfe { @@ -58,7 +58,11 @@ struct MeshParticleMeshMaterial static_assert(sizeof(MeshParticleMeshLod) == 72, "readLods / the instance stride by 72 (0x38E38E39 >> 4)"); static_assert(offsetof(MeshParticleMeshLod, renderKind) == 0x40, "readMaterials writes lod +0x40"); static_assert(offsetof(MeshParticleMeshLod, hasAlphaTest) == 0x44, "readMaterials writes lod +0x44"); +// The rebuild keeps the records in std::vectors and indexes them by type; nothing here divides by a +// literal size, so the retail size is x86 evidence only (issue #7). +#if defined(_M_IX86) static_assert(sizeof(MeshParticleMeshMaterial) == 24, "the destructor and the draw divide by 24"); +#endif // Shared mesh-particle effect state, initialized on demand by material loading. @@ -96,7 +100,14 @@ extern MeshParticleMeshEffectState g_meshParticleMeshEffectState; class MeshParticleMeshTemplate : public MeshTemplate { public: + typedef std::vector LodMaterials; // one lod's materials + typedef std::vector > MaterialTable; // geom -> lod -> material + typedef std::vector > LodTable; // geom -> lod + typedef std::set InstanceSet; + MeshParticleMeshTemplate(); + // The destructor body: the deleting slot frees the storage afterwards without running a C++ + // destructor, so this destroys this class's members itself, in the shipped order. void destroyMembers(); // (the dtor body) // The overridden IBase trio counts at +0xC8 - the same three bodies StaticMeshTemplate, @@ -107,7 +118,7 @@ class MeshParticleMeshTemplate : public MeshTemplate virtual void* queryInterface(unsigned int iid) const; // +0x0C virtual unsigned int getClassId() const; // +0x10 - virtual void setName(const vc71::string& name); // +0x14 + virtual void setName(const std::string& name); // +0x14 virtual void* createInstance(); // +0x24 virtual bool load(); // +0x2C virtual void* destroy(unsigned char flags); // +0xB0 @@ -120,26 +131,16 @@ class MeshParticleMeshTemplate : public MeshTemplate // [UNRESOLVED] name and value type: the body is an untyped dword store. No recovered caller. virtual void setDwordF8(int index, unsigned int value); // +0xF0 - // data, in shipped order + // data, in shipped order; the `+0xNN` comments are the retail offsets int m_refCount; // +0x0C8 - vc71::vector_layout m_materials; // +0x0CC geom -> lod -> MeshParticleMeshMaterial - vc71::set_layout m_instances; // +0x0DC MeshParticleMesh* - vc71::vector_layout m_geoms; // +0x0E8 geom -> MeshParticleMeshLod + MaterialTable m_materials; // +0x0CC geom -> lod -> MeshParticleMeshMaterial + InstanceSet m_instances; // +0x0DC MeshParticleMesh* + LodTable m_geoms; // +0x0E8 geom -> MeshParticleMeshLod unsigned int m_dwordF8[26]; // +0x0F8 [UNRESOLVED], constructor-untouched unsigned char m_isDecal; // +0x160 [INFERRED] name unsigned char m_pad161[3]; // +0x161 }; -#if defined(_M_IX86) -static_assert(offsetof(MeshParticleMeshTemplate, m_refCount) == 0xC8, "refcount +0xC8 (0x100EEA10)"); -static_assert(offsetof(MeshParticleMeshTemplate, m_materials) == 0xCC, "material tree +0xCC"); -static_assert(offsetof(MeshParticleMeshTemplate, m_instances) == 0xDC, "instance set +0xDC"); -static_assert(offsetof(MeshParticleMeshTemplate, m_geoms) == 0xE8, "lod tree +0xE8"); -static_assert(offsetof(MeshParticleMeshTemplate, m_dwordF8) == 0xF8, "slot +0xF0's array at +0xF8"); -static_assert(offsetof(MeshParticleMeshTemplate, m_isDecal) == 0x160, "setName's byte +0x160"); -static_assert(sizeof(MeshParticleMeshTemplate) == 0x164, "RefFactory 0x100B07D2 allocates 0x164"); -#endif - // the factory registered under "dice.hfe.geom.GeometryTemplate.MeshParticleMesh". IBase* __fastcall createMeshParticleMeshTemplate(unsigned int iid, IBase* outer); diff --git a/Code/BF2/Geom/ParticleSystem/NSAParticleSystemTemplate.cpp b/Code/BF2/Geom/ParticleSystem/NSAParticleSystemTemplate.cpp index 66951b8e2..41fbb443f 100644 --- a/Code/BF2/Geom/ParticleSystem/NSAParticleSystemTemplate.cpp +++ b/Code/BF2/Geom/ParticleSystem/NSAParticleSystemTemplate.cpp @@ -2,14 +2,22 @@ // Textures resolve through the atlas or remain owned direct references. #ifdef BF2_IMAGE_RENDDX9 - +#if !defined(_MSC_VER) +// [CHOSEN, not recovered] Compiler-typed native table entries. +#include "../../../RendDX9Abi/NativeVtable.h" +#include "ParticleSystemManager.h" +#endif + +#include "../../../RendDX9Abi/ThunkAbi.h" +#include "ParticleRawLayout.h" #include "../XpLightManager.h" #include "ParticleTemplateResources.h" +#include "../../Platform/X87Compat.h" #include "../../../RendDX9Abi/HfeAbi.h" #include "../../../RendDX9Abi/ModuleCommon.h" #include "../../../RendDX9Abi/BfMemory.h" #include "../../../RendDX9Abi/Frontier.h" -#include "../../../RendDX9Abi/Vc71String.h" +#include #include #include @@ -20,52 +28,78 @@ namespace dice { namespace hfe { namespace geom { -extern LightManager* g_LightManager; // published boot surface; slot 2 retains retail's null guard. +void psmZeroTemplateBlock(void* block); // ParticleSystemTemplate.cpp + +extern LightManager* g_LightManager; +const Vec3* terrainOriginScratch(const Vec3& value); +const float* staticMeshPackVec4(const float value[3], float w); namespace { -// [CHOSEN, not recovered] Per-descriptor host strings occupy the same reserved 28-byte spans. Native -// std::string is 24 bytes on the supported x86 toolchain; compatibility retains VC7.1 storage. +// [CHOSEN, not recovered] Per-descriptor host strings occupy the same reserved 28-byte spans (x64: +// 32-byte tail slots, ParticleRawLayout.h). +// std::string is 24 bytes on the supported x86 toolchain. // Returning the object itself preserves reference lifetime without a shared conversion buffer. using ParticleHostString = ::renddx9abi::HostString; -static_assert(sizeof(ParticleHostString) <= 28, "particle host string exceeds its reserved span"); +static_assert(sizeof(ParticleHostString) <= kPsmDescriptorStringSpan, "particle host string exceeds its reserved span"); -inline unsigned& U (void* p, unsigned off) { return *reinterpret_cast(static_cast(p) + off); } -inline float& F (void* p, unsigned off) { return *reinterpret_cast(static_cast(p) + off); } -inline unsigned char& Bt(void* p, unsigned off) { return *reinterpret_cast(static_cast(p) + off); } -inline short& S16(void* p, unsigned off){ return *reinterpret_cast(static_cast(p) + off); } +inline unsigned& U (void* p, unsigned off) { return psmDescriptor4(p, off); } +inline float& F (void* p, unsigned off) { return psmDescriptor4(p, off); } +inline unsigned char& Bt(void* p, unsigned off) { return psmDescriptor4(p, off); } +inline short& S16(void* p, unsigned off){ return psmDescriptor4(p, off); } inline unsigned fbits(float f) { unsigned u; ::memcpy(&u, &f, 4); return u; } -#define PT_SET(name, off) void __fastcall name(void* s, void*, unsigned v){ U(s,(off)) = v; } -#define PT_GETF(name, off) float __fastcall name(void* s, void*){ return F(s,(off)); } -#define PT_GETD(name, off) unsigned __fastcall name(void* s, void*){ return U(s,(off)); } -#define PT_SETB(name, off) void __fastcall name(void* s, void*, unsigned v){ Bt(s,(off)) = static_cast(v); } -#define PT_GETB(name, off) unsigned __fastcall name(void* s, void*){ return Bt(s,(off)); } -#define PT_LEA(name, off) void* __fastcall name(void* s, void*){ return static_cast(s) + (off); } -#define PT_SETVEC(name, off, n) void __fastcall name(void* s, void*, const float* v){ for (int i=0;i<(n);++i) F(s,(off)+4u*i)=v[i]; } -#define PT_GETVEC(name, off, n) void* __fastcall name(void* s, void*, float* o){ for (int i=0;i<(n);++i) o[i]=F(s,(off)+4u*i); return o; } +#define PT_SET(name, off) void RD9_THUNK name(void* s RD9_THUNK_EDX, unsigned v){ U(s,(off)) = v; } +#define PT_SETFLT(name, off) void RD9_THUNK name(void* s RD9_THUNK_EDX, PsmFloatArg v){ U(s,(off)) = psmFloatArgBits(v); } +#define PT_GETF(name, off) float RD9_THUNK name(void* s RD9_THUNK_EDX){ return F(s,(off)); } +#define PT_GETD(name, off) unsigned RD9_THUNK name(void* s RD9_THUNK_EDX){ return U(s,(off)); } +#define PT_SETB(name, off) void RD9_THUNK name(void* s RD9_THUNK_EDX, unsigned v){ Bt(s,(off)) = static_cast(v); } +#define PT_GETB(name, off) unsigned RD9_THUNK name(void* s RD9_THUNK_EDX){ return Bt(s,(off)); } +#define PT_LEA(name, off) void* RD9_THUNK name(void* s RD9_THUNK_EDX){ return &psmDescriptor4(s, (off)); } +#define PT_SETVEC(name, off, n) void RD9_THUNK name(void* s RD9_THUNK_EDX, const float* v) \ +{ \ + if ((n)==3 || (n)==4) \ + { \ + const float z=v[2],y=v[1],x=v[0],w=(n)==4 ? v[3] : 0.0f; \ + F(s,(off)+4)=y; F(s,(off))=x; F(s,(off)+8)=z; \ + if ((n)==4) F(s,(off)+12)=w; \ + } \ + else for (int i=0;i<(n);++i) F(s,(off)+4u*i)=v[i]; \ +} +#define PT_GETVEC(name, off, n) void* RD9_THUNK name(void* s RD9_THUNK_EDX, float* o) \ +{ \ + if ((n)==3) \ + { \ + const float z=F(s,(off)+8),y=F(s,(off)+4),x=F(s,(off)); \ + o[1]=y; o[0]=x; o[2]=z; \ + } \ + else for (int i=0;i<(n);++i) o[i]=F(s,(off)+4u*i); \ + return o; \ +} // cross-called - forward declared -void __fastcall n4_s2 (void* s, void*); -void __fastcall n4_s45 (void* s, void*, unsigned a); -void __fastcall n4_s146(void* s, void*, unsigned a); +void RD9_THUNK n4_s2 (void* s RD9_THUNK_EDX); +void RD9_THUNK n4_s45 (void* s RD9_THUNK_EDX, PsmFloatArg a); +void RD9_THUNK n4_s146(void* s RD9_THUNK_EDX, unsigned a); void n4_recomputeUV(void* self); // simple slots -const ParticleHostString& __fastcall n4_s1(void* self, void*) -{ return *reinterpret_cast(static_cast(self) + 0x234); } +const ParticleHostString& RD9_THUNK n4_s1(void* self RD9_THUNK_EDX) +{ return psmDescriptor4(self, 0x234); } PT_SET (n4_s4, 0x68) PT_GETD(n4_s5, 0x68) +// PE 0x10178A70 PT_SET (n4_s6, 0x6C) PT_GETD(n4_s7, 0x6C) PT_SET (n4_s8, 0x70) PT_GETD(n4_s9, 0x70) -void __fastcall n4_s10(void* s, void*, unsigned a, unsigned b, unsigned c){ U(s,0x18)=a; U(s,0x1C)=b; U(s,0x20)=c; } +void RD9_THUNK n4_s10(void* s RD9_THUNK_EDX, PSM_VEC3_PARAMS){ U(s,0x18)=PSM_VEC3_X; U(s,0x1C)=PSM_VEC3_Y; U(s,0x20)=PSM_VEC3_Z; } // Vec3 by value PT_GETVEC(n4_s11, 0x18, 3) -PT_SET (n4_s12, 0x64) +PT_SETFLT(n4_s12, 0x64) PT_GETF(n4_s13, 0x64) -PT_SET (n4_s14, 0x60) +PT_SETFLT(n4_s14, 0x60) PT_GETF(n4_s15, 0x60) +// PE 0x10178B80 PT_SET (n4_s16, 0x258) PT_SETVEC(n4_s17, 0x24, 5) PT_LEA (n4_s18, 0x24) @@ -74,266 +108,393 @@ PT_LEA (n4_s20, 0x38) PT_SETVEC(n4_s21, 0x4C, 5) PT_LEA (n4_s22, 0x4C) PT_GETF(n4_s24, 0x10) -PT_SET (n4_s25, 0x1C0) +PT_SETFLT(n4_s25, 0x1C0) PT_GETF(n4_s26, 0x1C0) -PT_SET (n4_s27, 0x0C) +PT_SETFLT(n4_s27, 0x0C) PT_GETF(n4_s28, 0x0C) PT_GETF(n4_s30, 0x1C4) +// PE 0x10178B00 PT_SETB(n4_s31, 0x74) PT_GETB(n4_s32, 0x74) -PT_SET (n4_s33, 0x1CC) +// PE 0x10178B20 +PT_SETFLT(n4_s33, 0x1CC) PT_GETF(n4_s34, 0x1CC) +// PE 0x10178FD0 PT_SETVEC(n4_s35, 0x1B4, 3) +// PE 0x10179000 PT_GETVEC(n4_s36, 0x1B4, 3) +// PE 0x101782E0 PT_GETVEC(n4_s38, 0x200, 3) +// PE 0x101781F0 PT_SETVEC(n4_s39, 0xEC, 4) PT_LEA (n4_s40, 0xEC) +// PE 0x10178E30 PT_SETB(n4_s41, 0x210) PT_GETB(n4_s42, 0x210) -PT_SET (n4_s43, 0x78) +// PE 0x101779C0 +PT_SETFLT(n4_s43, 0x78) PT_GETF(n4_s44, 0x78) PT_GETF(n4_s46, 0x7C) -PT_SET (n4_s47, 0x84) +PT_SETFLT(n4_s47, 0x84) PT_GETF(n4_s48, 0x84) -PT_SET (n4_s49, 0x88) +// PE 0x10178BE0 +PT_SETFLT(n4_s49, 0x88) PT_GETF(n4_s50, 0x88) -PT_SET (n4_s51, 0x1B0) +// PE 0x10178CD0 +PT_SETFLT(n4_s51, 0x1B0) PT_GETF(n4_s52, 0x1B0) +// PE 0x10178220 PT_SETVEC(n4_s53, 0xFC, 4) PT_LEA (n4_s54, 0xFC) +// PE 0x10178250 PT_SETVEC(n4_s55, 0x10C, 4) PT_LEA (n4_s56, 0x10C) +// PE 0x10178280 PT_SETVEC(n4_s57, 0x11C, 4) PT_LEA (n4_s58, 0x11C) +// PE 0x10178190 PT_SETVEC(n4_s59, 0x17C, 4) PT_LEA (n4_s60, 0x17C) -PT_SET (n4_s61, 0x9C) +PT_SETFLT(n4_s61, 0x9C) PT_GETF(n4_s62, 0x9C) +// PE 0x10178CF0 PT_SETB(n4_s63, 0xDC) PT_GETB(n4_s64, 0xDC) -PT_SET (n4_s65, 0xE0) +// PE 0x10178D10 +PT_SETFLT(n4_s65, 0xE0) PT_GETF(n4_s66, 0xE0) -PT_SET (n4_s67, 0xE4) +// PE 0x10178D30 +PT_SETFLT(n4_s67, 0xE4) PT_GETF(n4_s68, 0xE4) +// PE 0x10178E50 PT_SETB(n4_s69, 0x211) PT_GETB(n4_s70, 0x211) +// PE 0x10178D50 PT_SETB(n4_s71, 0xA0) PT_GETB(n4_s72, 0xA0) -PT_SET (n4_s73, 0xA4) +PT_SETFLT(n4_s73, 0xA4) PT_GETF(n4_s74, 0xA4) +// PE 0x10178EC0 PT_SET (n4_s75, 0x260) PT_GETD(n4_s76, 0x260) -PT_SET (n4_s77, 0x264) +PT_SETFLT(n4_s77, 0x264) PT_GETF(n4_s78, 0x264) -PT_SET (n4_s79, 0x268) +PT_SETFLT(n4_s79, 0x268) PT_GETF(n4_s80, 0x268) -PT_SET (n4_s81, 0x26C) +PT_SETFLT(n4_s81, 0x26C) PT_GETF(n4_s82, 0x26C) -PT_SET (n4_s83, 0x270) +PT_SETFLT(n4_s83, 0x270) PT_GETF(n4_s84, 0x270) -PT_SET (n4_s85, 0x274) +PT_SETFLT(n4_s85, 0x274) PT_GETF(n4_s86, 0x274) -PT_SET (n4_s87, 0x278) +PT_SETFLT(n4_s87, 0x278) PT_GETF(n4_s88, 0x278) -PT_SET (n4_s89, 0x138) +// PE 0x10177A00 +PT_SETFLT(n4_s89, 0x138) PT_GETF(n4_s90, 0x138) -PT_SET (n4_s91, 0x1A4) +// PE 0x10178C60 +PT_SETFLT(n4_s91, 0x1A4) PT_GETF(n4_s92, 0x1A4) -PT_SET (n4_s93, 0x1A8) +// PE 0x10178C90 +PT_SETFLT(n4_s93, 0x1A8) PT_GETF(n4_s94, 0x1A8) +// PE 0x101781C0 PT_SETVEC(n4_s95, 0x18C, 4) PT_LEA (n4_s96, 0x18C) -PT_SET (n4_s97, 0x94) +PT_SETFLT(n4_s97, 0x94) PT_GETF(n4_s98, 0x94) -PT_SET (n4_s99, 0x1D0) +// PE 0x10177A20 +PT_SETFLT(n4_s99, 0x1D0) PT_GETF(n4_s100, 0x1D0) +// PE 0x10178050 PT_GETVEC(n4_s102, 0x1D4, 3) +// PE 0x10178160 PT_SETVEC(n4_s106, 0x16C, 4) PT_LEA (n4_s107, 0x16C) -PT_SET (n4_s108, 0x134) +// PE 0x101779E0 +PT_SETFLT(n4_s108, 0x134) PT_GETF(n4_s109, 0x134) -PT_SET (n4_s110, 0x20C) +// PE 0x10178E70 +PT_SETFLT(n4_s110, 0x20C) PT_GETF(n4_s111, 0x20C) +// PE 0x10178EA0 PT_SETB(n4_s112, 0x25D) PT_GETB(n4_s113, 0x25D) +// PE 0x10177770 PT_SETVEC(n4_s114, 0x12C, 2) -PT_GETVEC(n4_s115, 0x12C, 2) -PT_SET (n4_s116, 0x8C) +// PE 0x10177E50 +void* RD9_THUNK n4_s115(void* self RD9_THUNK_EDX, float* out) +{ + static float scratch[2]; + scratch[0]=F(self,0x12C); scratch[1]=F(self,0x130); + const float y=scratch[1],x=scratch[0]; + out[0]=x; out[1]=y; return out; +} +PT_SETFLT(n4_s116, 0x8C) PT_GETF(n4_s117, 0x8C) -PT_SET (n4_s118, 0x90) +// PE 0x10178C20 +PT_SETFLT(n4_s118, 0x90) PT_GETF(n4_s119, 0x90) -PT_SET (n4_s120, 0x1AC) +// PE 0x10178CB0 +PT_SETFLT(n4_s120, 0x1AC) PT_GETF(n4_s121, 0x1AC) +// PE 0x10178C40 PT_SETVEC(n4_s122, 0x19C, 2) +// PE 0x10178FB0 PT_GETVEC(n4_s123, 0x19C, 2) -PT_SET (n4_s124, 0x98) +PT_SETFLT(n4_s124, 0x98) PT_GETF(n4_s125, 0x98) -const ParticleHostString& __fastcall n4_s127(void* self, void*) -{ return *reinterpret_cast(static_cast(self) + 0x218); } +const ParticleHostString& RD9_THUNK n4_s127(void* self RD9_THUNK_EDX) +{ return psmDescriptor4(self, 0x218); } PT_GETB(n4_s129, 0xBC) +// PE 0x10178DB0 PT_SETB(n4_s130, 0xC4) PT_GETB(n4_s131, 0xC4) +// PE 0x10178D90 PT_SETB(n4_s132, 0xBD) PT_GETB(n4_s133, 0xBD) -PT_SET (n4_s134, 0xC0) +// PE 0x10178DD0 +PT_SETFLT(n4_s134, 0xC0) PT_GETF(n4_s135, 0xC0) -PT_SET (n4_s140, 0xC8) +// PE 0x10178DF0 +PT_SETFLT(n4_s140, 0xC8) PT_GETF(n4_s141, 0xC8) -PT_SET (n4_s142, 0xCC) +PT_SETFLT(n4_s142, 0xCC) PT_GETF(n4_s143, 0xCC) PT_GETD(n4_s145, 0xD0) PT_GETD(n4_s147, 0xD4) // complex slots -unsigned __fastcall n4_s3(void*, void*) { return 4; } // emitter type id (const) +unsigned RD9_THUNK n4_s3(void* RD9_THUNK_EDX) { return 4; } // emitter type id (const) +// PE 0x101787C0 // slot 2: recompute/finalize derived fields. -void __fastcall n4_s2(void* self, void*) +void RD9_THUNK n4_s2(void* self RD9_THUNK_EDX) { - if (F(self, 0x1D0) < 0.0f) // "auto" sentinel -> ask LightManager (null -> 0) - { - if (g_LightManager) - F(self, 0x158) = - g_LightManager->getDefaultEffectLightAffectionFactor(); - else - U(self, 0x158) = 0; - } + if (!(F(self, 0x1D0) >= 0.0f)) + F(self, 0x158) = g_LightManager->getDefaultEffectLightAffectionFactor(); else U(self, 0x158) = U(self, 0x1D0); unsigned mode = U(self, 0x68); - F(self, 0x1C8) = (mode == 0) ? 0.5f : (mode == 1) ? 0.7f : 1.0f; - - n4_s45(self, 0, U(self, 0x7C)); - - F(self, 0xB0) = (F(self, 0xA8) == F(self, 0xAC)) ? 0.0f : 1.0f / (F(self, 0xA8) - F(self, 0xAC)); - F(self, 0x14) = (F(self, 0x1C4) <= 0.0f) ? 0.2f : 1.0f / F(self, 0x1C4); - if (U(self, 0xD4)) F(self, 0xD8) = 1.0f / static_cast(U(self, 0xD4)); + if (mode == 0) F(self, 0x1C8)=0.5f; + else if (mode == 1) F(self, 0x1C8)=0.7f; + else if (mode == 2) F(self, 0x1C8)=1.0f; + +#if !defined(_MSC_VER) + static_cast(self)->setTimeToLive(F(self,0x7C)); +#else + typedef void (__thiscall* SetLifetime)(void*, float); + reinterpret_cast((*static_cast(self))[45])(self,F(self,0x7C)); +#endif + +#if defined(__APPLE__) + // [CHOSEN, not recovered] Preserve live x87 subtraction and unsigned division. + using bf2x87::wide; + F(self,0xB0) = F(self,0xA8)==F(self,0xAC) ? 0.0f + : static_cast(wide(1)/(wide(F(self,0xA8))-wide(F(self,0xAC)))); + F(self,0x14) = F(self,0x1C4)>0 ? static_cast(wide(1)/wide(F(self,0x1C4))) : 0.2f; + if (U(self,0xD4)) F(self,0xD8)=static_cast(wide(1)/wide(U(self,0xD4))); +#else + F(self,0xB0) = F(self,0xA8)==F(self,0xAC) ? 0.0f + : static_cast(1.0/(static_cast(F(self,0xA8))-F(self,0xAC))); + F(self,0x14) = F(self,0x1C4)>0 ? 1.0f/F(self,0x1C4) : 0.2f; + if (U(self,0xD4)) F(self,0xD8)=static_cast(1.0/static_cast(U(self,0xD4))); +#endif else U(self, 0xD8) = 0; n4_recomputeUV(self); } -void __fastcall n4_s23(void* self, void*, unsigned v) { U(self, 0x10) = v; n4_s2(self, 0); } -void __fastcall n4_s29(void* self, void*, unsigned v) { U(self, 0x1C4) = v; n4_s2(self, 0); } +void RD9_THUNK n4_s23(void* self RD9_THUNK_EDX, PsmFloatArg v) { U(self, 0x10) = psmFloatArgBits(v); n4_s2(self RD9_THUNK_ARG); } +// PE 0x10178AD0 +void RD9_THUNK n4_s29(void* self RD9_THUNK_EDX, PsmFloatArg v) { U(self, 0x1C4) = psmFloatArgBits(v); n4_s2(self RD9_THUNK_ARG); } +// PE 0x101782B0 // slot 37: store Vec3 at +0x200, normalize in place. -void __fastcall n4_s37(void* self, void*, const float* v) +void RD9_THUNK n4_s37(void* self RD9_THUNK_EDX, const float* v) { - F(self, 0x200) = v[0]; F(self, 0x204) = v[1]; F(self, 0x208) = v[2]; - float* p = reinterpret_cast(static_cast(self) + 0x200); - float s = p[0] * p[0] + p[1] * p[1] + p[2] * p[2]; - if (fabsf(s - 1.0f) >= FLT_EPSILON) + const float z=v[2],y=v[1],x=v[0]; + F(self,0x204)=y; F(self,0x200)=x; F(self,0x208)=z; + float* p = &psmDescriptor4(self, 0x200); +#if defined(__APPLE__) + // [CHOSEN, not recovered] The squared sum spills once; the inverse remains live. + using bf2x87::wide; + const float s=static_cast(wide(p[0])*wide(p[0])+wide(p[1])*wide(p[1])+wide(p[2])*wide(p[2])); + const bf2x87::Real error=bf2x87::abs(wide(s)-wide(1)); +#else + const float s=static_cast(static_cast(p[0])*p[0]+static_cast(p[1])*p[1] + +static_cast(p[2])*p[2]); + const double error=::fabs(static_cast(s)-1.0); +#endif + if (!(error < FLT_EPSILON)) { if (fabsf(s) < FLT_EPSILON) { p[0] = p[1] = p[2] = 0.0f; } - else { float inv = 1.0f / sqrtf(s); p[0] *= inv; p[1] *= inv; p[2] *= inv; } + else + { +#if defined(__APPLE__) + const bf2x87::Real inv=wide(1)/bf2x87::squareRoot(wide(s)); + p[0]=static_cast(inv*wide(p[0])); p[1]=static_cast(inv*wide(p[1])); + p[2]=static_cast(inv*wide(p[2])); +#else + const double inv=1.0/::sqrt(static_cast(s)); + p[0]=static_cast(inv*p[0]); p[1]=static_cast(inv*p[1]); p[2]=static_cast(inv*p[2]); +#endif + } } } +// PE 0x10177950 // slot 45: set lifetime +0x7C; recompute 1/x at +0x80 and, if +0xBC set, the +0xC0 rate. -void __fastcall n4_s45(void* self, void*, unsigned a) +void RD9_THUNK n4_s45(void* self RD9_THUNK_EDX, PsmFloatArg a) { - U(self, 0x7C) = a; + U(self, 0x7C) = psmFloatArgBits(a); float fa = F(self, 0x7C); if (fa > 0.0f) F(self, 0x80) = 1.0f / fa; if (Bt(self, 0xBC) && fa > 0.0f) F(self, 0xC0) = static_cast(U(self, 0xD0)) / fa; } // slot 101: Vec3 to +0x1D4 and mirror +0x14C. -void __fastcall n4_s101(void* self, void*, const float* v) +// PE 0x10178000 +void RD9_THUNK n4_s101(void* self RD9_THUNK_EDX, const float* v) { - F(self, 0x1D4) = v[0]; F(self, 0x1D8) = v[1]; F(self, 0x1DC) = v[2]; - F(self, 0x14C) = v[0]; F(self, 0x150) = v[1]; F(self, 0x154) = v[2]; + const float z=v[2],y=v[1],x=v[0]; + F(self,0x1D8)=y; F(self,0x1D4)=x; F(self,0x1DC)=z; + F(self,0x14C)=x; F(self,0x150)=F(self,0x1D8); F(self,0x154)=F(self,0x1DC); } // slot 103: Vec3 packed to Vec4{r,g,b,1} at +0x1E0 and mirror +0x15C. -void __fastcall n4_s103(void* self, void*, const float* v) +// PE 0x10178080 +void RD9_THUNK n4_s103(void* self RD9_THUNK_EDX, const float* v) { - F(self, 0x1E0) = v[0]; F(self, 0x1E4) = v[1]; F(self, 0x1E8) = v[2]; F(self, 0x1EC) = 1.0f; - F(self, 0x15C) = v[0]; F(self, 0x160) = v[1]; F(self, 0x164) = v[2]; F(self, 0x168) = 1.0f; + const float* const packed=staticMeshPackVec4(v,1.0f); + const float w=packed[3],z=packed[2],y=packed[1],x=packed[0]; + F(self,0x1E4)=y; F(self,0x1E0)=x; F(self,0x1E8)=z; F(self,0x1EC)=w; + F(self,0x15C)=x; F(self,0x160)=F(self,0x1E4); + F(self,0x164)=F(self,0x1E8); F(self,0x168)=F(self,0x1EC); } // slot 104: get the +0x1E0 color as Vec3 (drops w). -void* __fastcall n4_s104(void* self, void*, float* out) +// PE 0x101780F0 +void* RD9_THUNK n4_s104(void* self RD9_THUNK_EDX, float* out) { - out[0] = F(self, 0x1E0); out[1] = F(self, 0x1E4); out[2] = F(self, 0x1E8); + const Vec3* const packed=terrainOriginScratch(psmDescriptor4(self,0x1E0)); + const float z=packed->z,y=packed->y,x=packed->x; + out[1]=y; out[0]=x; out[2]=z; return out; } // slot 105: Vec3 packed to Vec4{r,g,b,1} at +0x1F0 (no mirror). -void __fastcall n4_s105(void* self, void*, const float* v) +// PE 0x10178120 +void RD9_THUNK n4_s105(void* self RD9_THUNK_EDX, const float* v) { - F(self, 0x1F0) = v[0]; F(self, 0x1F4) = v[1]; F(self, 0x1F8) = v[2]; F(self, 0x1FC) = 1.0f; + const float* const packed=staticMeshPackVec4(v,1.0f); + const float w=packed[3],z=packed[2],y=packed[1],x=packed[0]; + F(self,0x1F4)=y; F(self,0x1F0)=x; F(self,0x1F8)=z; F(self,0x1FC)=w; } // slot 126 (0x10178690), loader changed-name load, retaining the empty-name // resource behavior and clearing the stored name if the load fails. -void __fastcall n4_s126(void* self, void*, const ParticleHostString& source) +void RD9_THUNK n4_s126(void* self RD9_THUNK_EDX, const ParticleHostString& source) { - ParticleHostString* dst = reinterpret_cast(static_cast(self) + 0x218); + ParticleHostString* dst = &psmDescriptor4(self, 0x218); if (dst->size() != source.size() || ::memcmp(dst->c_str(), source.c_str(), source.size()) != 0) { *dst = source; - const vc71::string& resourceName = ::renddx9abi::toVc71String(source); - dx9rend::EngineTexture*& texture = *reinterpret_cast(static_cast(self) + 0x250); - dx9rend::TextureAtlasEntry*& region = *reinterpret_cast(static_cast(self) + 0x254); + const std::string& resourceName = ::renddx9abi::fromHostString(source); + dx9rend::EngineTexture*& texture = psmDescriptor4(self, 0x250); + dx9rend::TextureAtlasEntry*& region = psmDescriptor4(self, 0x254); if (!particleTemplateLoadTexture(texture, region, resourceName, - "dice::hfe::geom::NSAParticleSystemTemplate::setTexture", 181)) + "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\ParticleSystem\\NSAParticleSystemTemplate.cpp", 181)) *dst = ""; } } +// PE 0x101777D0 // slot 128: set +0xBC bool; when set (and +0x7C > 0) recompute the +0xC0 rate. -void __fastcall n4_s128(void* self, void*, unsigned b) +void RD9_THUNK n4_s128(void* self RD9_THUNK_EDX, unsigned b) { Bt(self, 0xBC) = static_cast(b); - if (b && F(self, 0x7C) > 0.0f) F(self, 0xC0) = static_cast(U(self, 0xD0)) / F(self, 0x7C); + if (psmBoolArg(b) && F(self, 0x7C) > 0.0f) F(self, 0xC0) = static_cast(U(self, 0xD0)) / F(self, 0x7C); } // slots 136-139: direct-texture-relative UV rates; width/height at (+0x250)+0x28/+0x2C. // Atlas-backed regions leave the direct texture null, preserving the no-op/zero branches. -void __fastcall n4_s136(void* self, void*, unsigned a) +// PE 0x10177EB0 +void RD9_THUNK n4_s136(void* self RD9_THUNK_EDX, unsigned a) { - void* t = *reinterpret_cast(static_cast(self) + 0x250); - if (t) F(self, 0xC8) = static_cast(a) / static_cast(U(t, 0x28)); + void* t = psmDescriptor4(self, 0x250); +#if defined(__APPLE__) + // [CHOSEN, not recovered] Both unsigned conversions remain live in the PE. + if (t) F(self,0xC8)=static_cast(bf2x87::wide(a) + /bf2x87::wide(static_cast(t)->width)); +#else + if (t) F(self,0xC8)=static_cast(static_cast(a) + /static_cast(static_cast(t)->width)); +#endif } -unsigned __fastcall n4_s137(void* self, void*) +// PE 0x10177EF0 +unsigned RD9_THUNK n4_s137(void* self RD9_THUNK_EDX) { - void* t = *reinterpret_cast(static_cast(self) + 0x250); - if (t) return static_cast(static_cast(static_cast(U(t, 0x28)) * F(self, 0xC8))); + void* t = psmDescriptor4(self, 0x250); +#if defined(__APPLE__) + // [CHOSEN, not recovered] Keep the unsigned dimension live through truncating FISTP. + if (t) return static_cast(bf2x87::toIntTruncate( + bf2x87::wide(static_cast(t)->width)*bf2x87::wide(F(self,0xC8)))); +#else + if (t) return static_cast(static_cast(static_cast(static_cast(t)->width)*F(self,0xC8))); +#endif return 0; } -void __fastcall n4_s138(void* self, void*, unsigned a) +// PE 0x10177F50 +void RD9_THUNK n4_s138(void* self RD9_THUNK_EDX, unsigned a) { - void* t = *reinterpret_cast(static_cast(self) + 0x250); - if (t) F(self, 0xCC) = static_cast(a) / static_cast(U(t, 0x2C)); + void* t = psmDescriptor4(self, 0x250); +#if defined(__APPLE__) + // [CHOSEN, not recovered] Only this setter spills its numerator to float first. + if (t) F(self,0xCC)=static_cast(bf2x87::wide(static_cast(a)) + /bf2x87::wide(static_cast(t)->height)); +#else + if (t) F(self,0xCC)=static_cast(static_cast(static_cast(a)) + /static_cast(static_cast(t)->height)); +#endif } -unsigned __fastcall n4_s139(void* self, void*) +// PE 0x10177FA0 +unsigned RD9_THUNK n4_s139(void* self RD9_THUNK_EDX) { - void* t = *reinterpret_cast(static_cast(self) + 0x250); - if (t) return static_cast(static_cast(static_cast(U(t, 0x2C)) * F(self, 0xCC))); + void* t = psmDescriptor4(self, 0x250); +#if defined(__APPLE__) + // [CHOSEN, not recovered] Keep the unsigned dimension live through truncating FISTP. + if (t) return static_cast(bf2x87::toIntTruncate( + bf2x87::wide(static_cast(t)->height)*bf2x87::wide(F(self,0xCC)))); +#else + if (t) return static_cast(static_cast(static_cast(static_cast(t)->height)*F(self,0xCC))); +#endif return 0; } +// PE 0x10177830 // slot 144: set +0xD0; cascade to slot146 when +0xD4 set; recompute +0xC0 when +0xBC set. -void __fastcall n4_s144(void* self, void*, unsigned a) +void RD9_THUNK n4_s144(void* self RD9_THUNK_EDX, unsigned a) { U(self, 0xD0) = a; - if (U(self, 0xD4)) n4_s146(self, 0, U(self, 0xD4)); + if (U(self, 0xD4)) n4_s146(self RD9_THUNK_ARG, U(self, 0xD4)); if (Bt(self, 0xBC) && F(self, 0x7C) > 0.0f) F(self, 0xC0) = static_cast(U(self, 0xD0)) / F(self, 0x7C); } +// PE 0x101778A0 // slot 146: set +0xD4 count; cache 1/count at +0xD8; fill the UV steps +0xC8/+0xCC when still unset. -void __fastcall n4_s146(void* self, void*, unsigned a) +void RD9_THUNK n4_s146(void* self RD9_THUNK_EDX, unsigned a) { U(self, 0xD4) = a; if (a) { float inv = 1.0f / static_cast(a); F(self, 0xD8) = inv; - if (U(self, 0xC8) == 0) n4_s140(self, 0, fbits(inv)); - if (U(self, 0xCC) == 0) n4_s142(self, 0, fbits(inv)); + // listing compares the float value against 0.0 (fucompp), so -0.0f also refills + if (F(self, 0xC8) == 0.0f) n4_s140(self RD9_THUNK_ARG, psmFloatArgFromBits(fbits(inv))); + if (F(self, 0xCC) == 0.0f) n4_s142(self RD9_THUNK_ARG, psmFloatArgFromBits(fbits(inv))); } } @@ -341,14 +502,14 @@ void __fastcall n4_s146(void* self, void*, unsigned a) // then push through slot114 into +0x12C. void n4_recomputeUV(void* self) { - void* region = *reinterpret_cast(static_cast(self) + 0x254); + const dx9rend::TextureAtlasEntry* region = psmDescriptor4(self, 0x254); float u, v; if (region) { - S16(self, 0x212) = static_cast(F(region, 8) * 32767.0f); - S16(self, 0x214) = static_cast(F(region, 0xC) * 32767.0f); - if (Bt(self, 0xC4)) { u = F(region, 0) * F(self, 0xC8); v = F(region, 4) * F(self, 0xCC); } - else { u = F(region, 0); v = F(region, 4); } + S16(self, 0x212) = static_cast(region->uOffset * 32767.0f); + S16(self, 0x214) = static_cast(region->vOffset * 32767.0f); + if (Bt(self, 0xC4)) { u = region->width * F(self, 0xC8); v = region->height * F(self, 0xCC); } + else { u = region->width; v = region->height; } } else { @@ -358,22 +519,213 @@ void n4_recomputeUV(void* self) else { u = 1.0f; v = 1.0f; } } float uv[2] = { u, v }; - n4_s114(self, 0, uv); + n4_s114(self RD9_THUNK_ARG, uv); +} + +// NSA descriptor members that nothing calls or references in 1.50: unreachable in 1.50: no code or +// data references. Each body is the listing's own. The names are [CHOSEN, not recovered]: no caller +// exposes them. + +// PE 0x10177790: recompute the +0xC0 rate (+0xD0 count over the +0x7C lifetime) when the +0xBC flag is +// set and +0x7C is positive; the same arithmetic is inlined in slots 45, 128 and 144. +void n4_recomputeRate(void* self) +{ + if (Bt(self, 0xBC) && F(self, 0x7C) > 0.0f) F(self, 0xC0) = static_cast(U(self, 0xD0)) / F(self, 0x7C); +} + +// PE 0x10177930: store the +0xD8 float; the paired getter at 0x10177940 answers st0 (float is the +// [CHOSEN, not recovered] argument type). +void n4_setD8(void* self, float value) +{ + U(self, 0xD8) = fbits(value); +} + +// PE 0x10177AC0: store the +0xB8 float; the paired getter at 0x10177AD0 answers st0. +void n4_setB8(void* self, float value) +{ + U(self, 0xB8) = fbits(value); +} + +// PE 0x101787A0: load the texture named by the stored +0x218 name (the result is not tested), then +// recompute the UV base and scale (tail jump to n4_recomputeUV, PE 0x101786E0). +void n4_reloadTexture(void* self) +{ + ParticleHostString& name = psmDescriptor4(self, 0x218); + dx9rend::EngineTexture*& texture = psmDescriptor4(self, 0x250); + dx9rend::TextureAtlasEntry*& region = psmDescriptor4(self, 0x254); + particleTemplateLoadTexture(texture, region, ::renddx9abi::fromHostString(name), + "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\ParticleSystem\\NSAParticleSystemTemplate.cpp", 181); + n4_recomputeUV(self); } // slot 0 (sub_10178460): release the owned +0x250 texture, destroy the two strings, // free when the deleting flag is set. The atlas region is borrowed. -void* __fastcall n4_dtor(void* self, void*, int flags) +void* RD9_THUNK n4_dtor(void* self RD9_THUNK_EDX, int flags) { - dx9rend::EngineTexture*& texture = *reinterpret_cast(static_cast(self) + 0x250); + dx9rend::EngineTexture*& texture = psmDescriptor4(self, 0x250); dx9rend::textureReleaseRef(texture); - reinterpret_cast(static_cast(self) + 0x234)->~ParticleHostString(); - reinterpret_cast(static_cast(self) + 0x218)->~ParticleHostString(); + psmDescriptor4(self, 0x234).~ParticleHostString(); + psmDescriptor4(self, 0x218).~ParticleHostString(); if (flags & 1) ::renddx9abi::engineFree(self); return self; } +#if !defined(_MSC_VER) +// [CHOSEN, not recovered] Match the shared consumer interface under the native ABI. +const void* const kVtable[] = +{ + BF2_NATIVE_DTOR(n4_dtor, complete), + BF2_NATIVE_DTOR(n4_dtor, deleting), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getName, n4_s1), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, refreshDerivedState, n4_s2), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getSystemType, n4_s3), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setEmitPrio, n4_s4), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getEmitPrio, n4_s5), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setLodDistance, n4_s6), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getLodDistance, n4_s7), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setQualityLevel, n4_s8), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getQualityLevel, n4_s9), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setEmitRadius, n4_s10), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getEmitRadius, n4_s11), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setRadialDirection, n4_s12), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getRadialDirection, n4_s13), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setRandomRadialDirection, n4_s14), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getRandomRadialDirection, n4_s15), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setEmitterType, n4_s16), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setEmitRangeX, n4_s17), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getEmitRangeX, n4_s18), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setEmitRangeY, n4_s19), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getEmitRangeY, n4_s20), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setEmitRangeZ, n4_s21), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getEmitRangeZ, n4_s22), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setEmitFrequency, n4_s23), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getEmitFrequency, n4_s24), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setEmitSpeed, n4_s25), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getEmitSpeed, n4_s26), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setPreWarmTime, n4_s27), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getPreWarmTime, n4_s28), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setEmitTime, n4_s29), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getEmitTime, n4_s30), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setIsLooping, n4_s31), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getIsLooping, n4_s32), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setEmitDelay, n4_s33), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getEmitDelay, n4_s34), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setRandomDirectionAngle, n4_s35), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getRandomDirectionAngle, n4_s36), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setEmitDirection, n4_s37), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getEmitDirection, n4_s38), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setRotationGraph, n4_s39), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getRotationGraph, n4_s40), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setAlignRotationToSpeed, n4_s41), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getAlignRotationToSpeed, n4_s42), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setRandomTimeToLive, n4_s43), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getRandomTimeToLive, n4_s44), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setTimeToLive, n4_s45), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getTimeToLive, n4_s46), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setGravity, n4_s47), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getGravity, n4_s48), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setAirResistance, n4_s49), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getAirResistance, n4_s50), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setRandomSpeed, n4_s51), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getRandomSpeed, n4_s52), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setGravityGraph, n4_s53), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getGravityGraph, n4_s54), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setAirResistanceGraph, n4_s55), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getAirResistanceGraph, n4_s56), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setEmitSpeedGraph, n4_s57), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getEmitSpeedGraph, n4_s58), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setTransparencyGraph, n4_s59), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getTransparencyGraph, n4_s60), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setWindAffectionFactor, n4_s61), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getWindAffectionFactor, n4_s62), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setCollisionEnable, n4_s63), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getCollisionEnable, n4_s64), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setCollisionSpeedAlongNormal, n4_s65), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getCollisionSpeedAlongNormal, n4_s66), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setCollisionSpeedAlongPlane, n4_s67), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getCollisionSpeedAlongPlane, n4_s68), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setIsLocalSystem, n4_s69), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getIsLocalSystem, n4_s70), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setForceToWaterSurface, n4_s71), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getForceToWaterSurface, n4_s72), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setWaterSurfaceOffset, n4_s73), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getWaterSurfaceOffset, n4_s74), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setGasCloudType, n4_s75), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getGasCloudType, n4_s76), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setBlurryVisionTime, n4_s77), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getBlurryVisionTime, n4_s78), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setBlurryVisionHoldTime, n4_s79), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getBlurryVisionHoldTime, n4_s80), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setMinGasCloudRadius, n4_s81), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getMinGasCloudRadius, n4_s82), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setMaxGasCloudRadius, n4_s83), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getMaxGasCloudRadius, n4_s84), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setGasCloudRadiusTime, n4_s85), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getGasCloudRadiusTime, n4_s86), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setGasCloudDamage, n4_s87), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getGasCloudDamage, n4_s88), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setParticleMaxSize, n4_s89), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getParticleMaxSize, n4_s90), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setRandomSize, n4_s91), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getRandomSize, n4_s92), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setRandomIntensity, n4_s93), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getRandomIntensity, n4_s94), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setSizeGraph, n4_s95), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getSizeGraph, n4_s96), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setAlphaCull, n4_s97), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getAlphaCull, n4_s98), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setLightAffectionFactor, n4_s99), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getLightAffectionFactor, n4_s100), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setColor1, n4_s101), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getColor1, n4_s102), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setColor2, n4_s103), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getColor2, n4_s104), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, reserved105, n4_s105), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setColorBlendGraph, n4_s106), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getColorBlendGraph, n4_s107), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setLightMapIntensityOffset, n4_s108), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getLightMapIntensityOffset, n4_s109), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setDirectionalScale, n4_s110), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getDirectionalScale, n4_s111), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setIsStaticSystem, n4_s112), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getIsStaticSystem, n4_s113), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, reserved114, n4_s114), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, reserved115, n4_s115), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setRandomRotationSpeed, n4_s116), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getRandomRotationSpeed, n4_s117), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setRotationSpeed, n4_s118), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getRotationSpeed, n4_s119), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setRandomRotation, n4_s120), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getRandomRotation, n4_s121), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setPivotOffset, n4_s122), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getPivotOffset, n4_s123), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setSelfShadowIntensity, n4_s124), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getSelfShadowIntensity, n4_s125), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setTextureName, n4_s126), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getTextureName, n4_s127), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setAnimationPlayOnce, n4_s128), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getAnimationPlayOnce, n4_s129), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setAnimationEnable, n4_s130), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getAnimationEnable, n4_s131), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setAnimationRandomizedStartFrame, n4_s132), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getAnimationRandomizedStartFrame, n4_s133), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setAnimationSpeed, n4_s134), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getAnimationSpeed, n4_s135), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setAnimationFrameWidth, n4_s136), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getAnimationFrameWidth, n4_s137), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setAnimationFrameHeight, n4_s138), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getAnimationFrameHeight, n4_s139), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setAnimationFrameWidthRelative, n4_s140), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getAnimationFrameWidthRelative, n4_s141), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setAnimationFrameHeightRelative, n4_s142), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getAnimationFrameHeightRelative, n4_s143), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setAnimationFrameCount, n4_s144), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getAnimationFrameCount, n4_s145), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, setAnimationFrameCountX, n4_s146), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType4, getAnimationFrameCountX, n4_s147), +}; +#else const void* const kVtable[148] = { reinterpret_cast(&n4_dtor), reinterpret_cast(&n4_s1), reinterpret_cast(&n4_s2), reinterpret_cast(&n4_s3), @@ -414,6 +766,7 @@ const void* const kVtable[148] = reinterpret_cast(&n4_s140), reinterpret_cast(&n4_s141), reinterpret_cast(&n4_s142), reinterpret_cast(&n4_s143), reinterpret_cast(&n4_s144), reinterpret_cast(&n4_s145), reinterpret_cast(&n4_s146), reinterpret_cast(&n4_s147), }; +#endif // sub_10177AE0 - init helper: defaults + ~18 setter calls, in shipped statement order. void initNsaDefaults(void* self) @@ -454,13 +807,13 @@ void initNsaDefaults(void* self) U (self, 0x19C)=0u; U(self,0x1A0)=0u; U(self,0x1A4)=0u; U(self,0x1A8)=0u; U (self, 0x1AC)=0u; U(self,0x1B0)=0u; U(self,0x1B4)=0u; U(self,0x1B8)=0u; U(self,0x1BC)=0u; - n4_s99(self, 0, static_cast(-1082130432)); // +0x1D0 = -1.0 - { float v[3] = { 1.0f, 1.0f, 1.0f }; n4_s101(self, 0, v); } - { float v[3] = { 1.0f, 1.0f, 1.0f }; n4_s103(self, 0, v); } - { float v[3] = { 1.0f, 1.0f, 1.0f }; n4_s105(self, 0, v); } + n4_s99(self RD9_THUNK_ARG, psmFloatArgFromBits(static_cast(-1082130432))); // +0x1D0 = -1.0 + { float v[3] = { 1.0f, 1.0f, 1.0f }; n4_s101(self RD9_THUNK_ARG, v); } + { float v[3] = { 1.0f, 1.0f, 1.0f }; n4_s103(self RD9_THUNK_ARG, v); } + { float v[3] = { 1.0f, 1.0f, 1.0f }; n4_s105(self RD9_THUNK_ARG, v); } U (self, 0x148) = 0u; - { ParticleHostString empty; *reinterpret_cast(static_cast(self) + 0x218) = empty; } + { ParticleHostString empty; psmDescriptor4(self, 0x218) = empty; } Bt(self, 0xDC) = 0; F (self, 0xE0) = 0.7f; F (self, 0xE4) = 0.8f; @@ -471,18 +824,18 @@ void initNsaDefaults(void* self) Bt(self, 0xC4) = 0; U (self, 0xC8)=0u; U(self,0xCC)=0u; U(self,0xD0)=0u; U(self,0xD4)=0u; U(self,0xD8)=0u; - { float v[2] = { 1.0f, 1.0f }; n4_s114(self, 0, v); } - n4_s89 (self, 0, fbits(1.0f)); // +0x138 = 1.0 - n4_s108(self, 0, 0u); // +0x134 = 0 - n4_s45 (self, 0, fbits(4.0f)); // +0x7C = 4.0 - n4_s43 (self, 0, 0u); // +0x78 = 0 - { float v[4] = { 0.0f, 0.0f, 1.0f, 0.0f }; n4_s106(self, 0, v); } - { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n4_s59 (self, 0, v); } - { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n4_s95 (self, 0, v); } - { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n4_s39 (self, 0, v); } - { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n4_s53 (self, 0, v); } - { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n4_s55 (self, 0, v); } - { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n4_s57 (self, 0, v); } + { float v[2] = { 1.0f, 1.0f }; n4_s114(self RD9_THUNK_ARG, v); } + n4_s89 (self RD9_THUNK_ARG, psmFloatArgFromBits(fbits(1.0f))); // +0x138 = 1.0 + n4_s108(self RD9_THUNK_ARG, psmFloatArgFromBits(0u)); // +0x134 = 0 + n4_s45 (self RD9_THUNK_ARG, psmFloatArgFromBits(fbits(4.0f))); // +0x7C = 4.0 + n4_s43 (self RD9_THUNK_ARG, psmFloatArgFromBits(0u)); // +0x78 = 0 + { float v[4] = { 0.0f, 0.0f, 1.0f, 0.0f }; n4_s106(self RD9_THUNK_ARG, v); } + { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n4_s59 (self RD9_THUNK_ARG, v); } + { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n4_s95 (self RD9_THUNK_ARG, v); } + { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n4_s39 (self RD9_THUNK_ARG, v); } + { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n4_s53 (self RD9_THUNK_ARG, v); } + { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n4_s55 (self RD9_THUNK_ARG, v); } + { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n4_s57 (self RD9_THUNK_ARG, v); } F (self, 0x264) = 20.0f; F (self, 0x268) = 20.0f; @@ -496,7 +849,7 @@ void initNsaDefaults(void* self) U (self, 0x208) = 0u; Bt(self, 0x211) = 0; - n4_s2(self, 0); // final recompute + n4_s2(self RD9_THUNK_ARG); // final recompute } } // anonymous namespace @@ -509,9 +862,9 @@ void initNsaDefaults(void* self) void* constructParticleSystemType4(void* mem, const void* nameString) { - ::memset(mem, 0, 0x27Cu); + ::memset(mem, 0, PSM_DESCRIPTOR_SIZE(0x27Cu)); - U(mem, 0x00) = ::renddx9abi::addr(kVtable); + *static_cast(mem) = kVtable; U(mem, 0x28) = 1065353216u; // 1.0 U(mem, 0x34) = 1973272912u; // bounds sentinel (== type 0) @@ -519,11 +872,11 @@ void* constructParticleSystemType4(void* mem, const void* nameString) U(mem, 0x48) = 1973272912u; U(mem, 0x50) = 1065353216u; // 1.0 U(mem, 0x5C) = 1973272912u; - // sub_10188150(this+0x12C): a 112-byte zero-fill - covered by the memset above. + psmZeroTemplateBlock(&psmDescriptor4(mem, 0x12C)); // redundant after the memset - new (static_cast(mem) + 0x218) ParticleHostString(); - new (static_cast(mem) + 0x234) ParticleHostString( - ::renddx9abi::toHostString(*static_cast(nameString))); + new (&psmDescriptor4(mem, 0x218)) ParticleHostString(); + new (&psmDescriptor4(mem, 0x234)) ParticleHostString( + ::renddx9abi::toHostString(*static_cast(nameString))); initNsaDefaults(mem); return mem; diff --git a/Code/BF2/Geom/ParticleSystem/ParticleInstanceShared13.inl b/Code/BF2/Geom/ParticleSystem/ParticleInstanceShared13.inl index c7b9b9e43..0e2aa8f1a 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleInstanceShared13.inl +++ b/Code/BF2/Geom/ParticleSystem/ParticleInstanceShared13.inl @@ -7,41 +7,41 @@ template const T& psmConstField(const void* object, unsigned int offset { return *reinterpret_cast(static_cast(object) + offset); } // PE 101839D0: `mov al, [ecx+144h]; retn`. -bool psmShared13IsEmitting(const void* self) { return psmConstField(self, 0x144) != 0; } +bool psmShared13IsEmitting(const void* self) { return psmConstInstanceB(self, 0x144) != 0; } // PE 101839E0: `mov al, [ebp+8]; mov [ecx+21Dh], al; retn 4`. -void psmShared13SetPaused(void* self, bool paused) { psmRuntimeField(self, 0x21D) = paused; } +void psmShared13SetPaused(void* self, bool paused) { psmInstanceB(self, 0x21D) = paused; } // PE 10177570: `mov al, [ecx+21Dh]; retn`. -bool psmShared13IsPaused(const void* self) { return psmConstField(self, 0x21D) != 0; } +bool psmShared13IsPaused(const void* self) { return psmConstInstanceB(self, 0x21D) != 0; } // the recently-visible byte. Start, the 60-frame emission gate and clear // all write it too; nothing in the renderer refreshes it for type 3 (see the type-3 readme). -void psmShared13SetVisible(void* self, bool value) { psmRuntimeField(self, 0x21E) = value; } -bool psmShared13IsVisible(const void* self) { return psmConstField(self, 0x21E) != 0; } +void psmShared13SetVisible(void* self, bool value) { psmInstanceB(self, 0x21E) = value; } +bool psmShared13IsVisible(const void* self) { return psmConstInstanceB(self, 0x21E) != 0; } // plain dword store / x87 load. -void psmShared13SetSpeedScale(void* self, float value) { psmRuntimeField(self, 0x138) = value; } -float psmShared13SpeedScale(const void* self) { return psmConstField(self, 0x138); } +void psmShared13SetSpeedScale(void* self, float value) { psmInstanceB(self, 0x138) = value; } +float psmShared13SpeedScale(const void* self) { return psmConstInstanceB(self, 0x138); } // loads z, y, x (x as a dword, y/z through fld), then stores y, x, z. void psmShared13SetDirectionScale(void* self, const Vec3& value) { const float z = value.z, y = value.y, x = value.x; - psmRuntimeField(self, 0x14C) = y; - psmRuntimeField(self, 0x148) = x; - psmRuntimeField(self, 0x150) = z; + psmInstanceB(self, 0x14C) = y; + psmInstanceB(self, 0x148) = x; + psmInstanceB(self, 0x150) = z; } // PE 10183A20: `lea eax, [ecx+148h]; retn`. -const Vec3& psmShared13DirectionScale(const void* self) { return psmConstField(self, 0x148); } +const Vec3& psmShared13DirectionScale(const void* self) { return psmConstInstanceB(self, 0x148); } // same load/store order as 10183A30, at +0x1C. void psmShared13SetVelocityOffset(void* self, const Vec3& value) { const float z = value.z, y = value.y, x = value.x; - psmRuntimeField(self, 0x20) = y; - psmRuntimeField(self, 0x1C) = x; - psmRuntimeField(self, 0x24) = z; + psmInstanceB(self, 0x20) = y; + psmInstanceB(self, 0x1C) = x; + psmInstanceB(self, 0x24) = z; } // PE 10183A60, 223 B. Distance from the emitter position (+0xA4) to the bounds centre plus the @@ -53,9 +53,9 @@ void psmShared13SetVelocityOffset(void* self, const Vec3& value) // copies, reported for the integrator; this shared version follows the instructions. float psmShared13BoundsRadius(const void* self) { - const Vec3& low = psmConstField(self, 0xFC); - const Vec3& high = psmConstField(self, 0x108); - const Vec3& position = psmConstField(self, 0xA4); + const Vec3& low = psmConstInstanceB(self, 0xFC); + const Vec3& high = psmConstInstanceB(self, 0x108); + const Vec3& position = psmConstInstanceB(self, 0xA4); const float x = static_cast((static_cast(low.x) + high.x) * 0.5) - position.x; const float y = static_cast((static_cast(high.y) + low.y) * 0.5 - position.y); const float zsum = high.z + low.z; diff --git a/Code/BF2/Geom/ParticleSystem/ParticleInstanceType0.inl b/Code/BF2/Geom/ParticleSystem/ParticleInstanceType0.inl index d0a66c919..81a34a745 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleInstanceType0.inl +++ b/Code/BF2/Geom/ParticleSystem/ParticleInstanceType0.inl @@ -7,6 +7,22 @@ float* psmType0NewParticle(void* self); void psmType0Emit(void* self, float dt); int psmType0AdvanceParticle(void* self, float* particle, int index, float step, unsigned int steps); +static float psmCopyStoredFloat(float value) +{ +#if !defined(_MSC_VER) || !defined(_M_IX86) + // [CHOSEN, not recovered] Native scalar copies reproduce FLD/FSTP's signaling-NaN quieting. + unsigned int bits; + ::memcpy(&bits, &value, sizeof(bits)); + if ((bits & 0x7FFFFFFFu) > 0x7F800000u && !(bits & 0x00400000u)) + { + std::feraiseexcept(FE_INVALID); + bits |= 0x00400000u; + ::memcpy(&value, &bits, sizeof(value)); + } +#endif + return value; +} + void psmNormalize3(float* v) { const float length = static_cast(static_cast(v[0]) * v[0] @@ -26,25 +42,27 @@ void psmNormalize3(float* v) } // Local transform is composed with the owner's visual transform, not physics pose. +// PE 0x1017F210 void psmType0RefreshTransform(void* self) { - if (psmRuntimeField(self, 0x14)) return; - Mat4& output = psmRuntimeField(self, 0x74); - const Mat4& local = psmRuntimeField(self, 0x34); - world::IObject* const owner = psmRuntimeField(self, 0x10); - if (owner) output.mult(local, owner->getVisualAbsoluteTransformation()); - else if (psmRuntimeField(self, 0x30)) - output.mult(local, *psmRuntimeField(self, 0x30)); + if (psmInstanceA(self, 0x14)) return; + Mat4& output = psmInstanceA(self, 0x74); + const Mat4& local = psmInstanceA(self, 0x34); + world::IObject* const owner = psmInstanceA(self, 0x10); + if (owner) rendmath::mult(output, local, owner->getVisualAbsoluteTransformation()); + else if (psmInstanceA(self, 0x30)) + rendmath::mult(output, local, *psmInstanceA(self, 0x30)); else output = local; } class ParticleInstanceType0 : public IParticleSystemInstance { - unsigned char m_data[0x238]; - template T& at(unsigned int offset) { return psmRuntimeField(this, offset); } + unsigned char m_data[PSM_INSTANCE_DATA(0x23C)]; + template T& at(unsigned int offset) { return psmInstanceA(this, offset); } template const T& at(unsigned int offset) const - { return *reinterpret_cast(reinterpret_cast(this) + offset); } + { return psmInstanceA(const_cast(this), offset); } public: + // PE 0x1017F870 explicit ParticleInstanceType0(IParticleSystemTemplate* descriptor) { at(0x14)=0; @@ -62,13 +80,13 @@ public: at(0x224)=0; at(0x225)=0; at(0x22C)=0; at(0x230)=0; at(0x234)=-1; at(0x10)=0; at(0xC)=0; at(8)=0; - const double lifetime = psmRuntimeField(descriptor,0x84)+static_cast(psmRuntimeField(descriptor,0x80)); + const double lifetime = psmDescriptor0(descriptor,0x84)+static_cast(psmDescriptor0(descriptor,0x80)); double capacityTime=lifetime; - const float emitTime=psmRuntimeField(descriptor,0x1D4); - if (emitTime!=0 && !psmRuntimeField(descriptor,0x6C) && capacityTime>emitTime) + const float emitTime=psmDescriptor0(descriptor,0x1D4); + if (emitTime!=0 && !psmDescriptor0(descriptor,0x6C) && capacityTime>emitTime) capacityTime=emitTime; - at(0x220)=static_cast(capacityTime*psmRuntimeField(descriptor,0x10)+10.0); - at(0x24)=static_cast(::renddx9abi::engineAlloc(at(0x220)*4+4)); + at(0x220)=static_cast(capacityTime*psmDescriptor0(descriptor,0x10)+10.0); + at(0x24)=static_cast(::renddx9abi::engineAlloc(at(0x220)*kPsmPointerSize+kPsmPointerSize)); at(0x24)[0]=0; at(0x18)={0,0,0}; at(0xFC)={0,0,0}; at(0x108)={0,0,0}; @@ -79,20 +97,22 @@ public: at(4)=0; at(0x228)=descriptor->getMinGasCloudRadius(); } + // PE 0x1017EF30 ~ParticleInstanceType0() override { ParticleSystemManager* const manager=reinterpret_cast(g_ParticleSystemManager); float** particles=at(0x24); for (unsigned int i=0;particles[i];++i) { - psmRuntimeField(particles[i],0)=manager->m_type0FreeList; - --psmRuntimeField(manager,0x5F28); + psmRecordLink(particles[i], 0)=manager->m_type0FreeList; + --manager->m_type0LiveCount; manager->m_type0FreeList=particles[i]; } ::renddx9abi::engineFree(particles); } static void operator delete(void* self) { ::renddx9abi::engineFree(self); } int reserved01() const override { return 0; } + // PE 0x1017F100 void reserved02() const override { ParticleInstanceType0* self=const_cast(this); @@ -102,8 +122,8 @@ public: { float** array=self->at(0x24); float* particle=array[0]; array[0]=array[--self->at(0x28)]; array[self->at(0x28)]=0; - psmRuntimeField(particle,0)=manager->m_type0FreeList; - manager->m_type0FreeList=particle; --psmRuntimeField(manager,0x5F28); + psmRecordLink(particle, 0)=manager->m_type0FreeList; + manager->m_type0FreeList=particle; --manager->m_type0LiveCount; } self->at(0x21C)=0; self->at(0x218)=0; self->at(0x219)=0; self->at(0x140)=0; self->at(0x28)=0; self->at(0x120)=0; @@ -112,20 +132,21 @@ public: self->at(0xF8)=0; self->at(0x225)=0; self->at(0x128)=1; self->at(0x129)=1; } + // PE 0x1017FC90 void reserved03(bool firstPerson) override { ParticleSystemManager* const manager=reinterpret_cast(g_ParticleSystemManager); IParticleSystemTemplate* descriptor=at(0x2C); if (descriptor->getQualityLevel()>static_cast(manager->m_qualityLevel)) return; at(0x226)=0; at(0x14C)=1; at(0x224)=1; - at(0xE0)=psmRuntimeField(descriptor,0x1D4); - at(0xE4)=psmRuntimeField(descriptor,0x1D8); + at(0xE0)=psmDescriptor0(descriptor,0x1D4); + at(0xE4)=psmDescriptor0(descriptor,0x1D8); at(0xE8)=0; at(0xF0)=0; at(0xF4)=0; - at(0xF8)=psmRuntimeField(descriptor,0xC); + at(0xF8)=psmDescriptor0(descriptor,0xC); psmType0RefreshTransform(this); if (!at(4)) { - at(0x238)=at(0xA4).y(dx9rend::g_raShaderConstants,0x1BC); + at(0x238)=at(0xA4).y<*reinterpret_cast(dx9rend::raShaderConstantsAt(0x1BC)); psmAddActive(manager,this,firstPerson); } dx9rend::IRenderView* const view=dx9rend::rendererGetRenderViewDup(); @@ -136,7 +157,8 @@ public: const Vec3& center=at(0x114); const double x=static_cast(center.x)-matrix[12], y=static_cast(center.y)-matrix[13], z=static_cast(center.z)-matrix[14]; const double distance=static_cast(maximumDistance)-at(0x120); - if (distance*distance>=x*x+y*y+z*z) + // The PE sums x, z, y; AH&5 parity at 1017FE0A takes the visible arm for unordered too. + if (!(distance*distance(0x124)=dx9rend::rendererFrameOrdinal(); at(0x128)=1; at(0x129)=1; @@ -145,38 +167,75 @@ public: } void reserved04() override { at(0x14C)=0; at(0x224)=0; at(0xE0)=0; } bool reserved05() const override { return at(0x14C)!=0; } + // PE 0x1017EAC0 (also used by the type-4 instance). void setPaused(bool value) override { at(0x225)=value; } bool reserved07() const override { return at(0x225)!=0; } void reserved08() override { at(0x14)=1; at(0xC)=0; at(0x10)=0; at(0x30)=0; } + // PE 0x1017EAE0 (also used by the type-4 instance). void reserved09(bool value) override { at(0x128)=value; } bool reserved10() const override { return at(0x128)!=0; } - void reserved11(int value) override { at(0x10)=value; } - int reserved12() const override { return at(0x10); } - void reserved13(int value) override { at(0x30)=value; } + void reserved11(intptr_t value) override { at(0x10)=value; } + intptr_t reserved12() const override { return at(0x10); } + void reserved13(intptr_t value) override { at(0x30)=value; } void* reserved14(const void* value) override { at(0x34)=*static_cast(value); return &at(0x34); } const void* reserved15() const override { return &at(0x34); } - void reserved16(const Vec3& value) override { at(0xCC)=value; } + // PE 0x1017F260 + void reserved16(const Vec3& value) override + { + const float z=value.z,y=value.y,x=value.x; + at(0xD0)=y; at(0xCC)=x; at(0xD4)=z; + } const Vec3& reserved17() const override { return at(0xCC); } + // PE 0x1017FE50. Capture all inputs before the destination or normalization can overlap them. void reserved18(const void* value) override - { at(0x208)=*static_cast(value); psmNormalize3(&at(0x208)); at(0x214)=static_cast(value)[3]; } + { + const float* coordinates = static_cast(value); + const float z = psmCopyStoredFloat(coordinates[2]); + unsigned int x; + ::memcpy(&x, coordinates, sizeof(x)); + const float y = psmCopyStoredFloat(coordinates[1]); + unsigned int distance; + ::memcpy(&distance, coordinates + 3, sizeof(distance)); + at(0x20C) = y; + at(0x210) = z; + at(0x208) = x; + psmNormalize3(&at(0x208)); + at(0x214) = distance; + } + // PE 0x1017F0E0. void reserved19(float value) override { at(0xDC)=value; } float reserved20() const override { return at(0xDC); } void reserved21(int,int) override { at(0x15C)=1; } + // PE 0x1017F020. void reserved22(float value) override { at(0x160)=value; } float reserved23() const override { return at(0x160); } + // PE 0x1017F040. void reserved24(float value) override { at(0x138)=value; } float reserved25() const override { return at(0x138); } + // PE 0x10181060 (also used by the type-4 instance). void reserved26(float value) override { at(0x13C)=value; } float reserved27() const override { return at(0x13C); } - void reserved28(const Vec3& value) override { at(0x150)=value; } + // PE 0x101810A0 + void reserved28(const Vec3& value) override + { + const float z=value.z,y=value.y,x=value.x; + at(0x154)=y; at(0x150)=x; at(0x158)=z; + } const Vec3& reserved29() const override { return at(0x150); } + // PE 0x1017F060. void reserved30(float value) override { at(0x12C)=value; } float reserved31() const override { return at(0x12C); } + // PE 0x1017F0C0. void reserved32(float value) override { at(0xD8)=value; } float reserved33() const override { return at(0xD8); } int reserved34() const override { return at(0x220); } IParticleSystemTemplate* getTemplate() const override { return at(0x2C); } - void reserved36(const Vec3& value) override { at(0x18)=value; } + // PE 0x1017EB20 + void reserved36(const Vec3& value) override + { + const float z=value.z,y=value.y,x=value.x; + at(0x1C)=y; at(0x18)=x; at(0x20)=z; + } void reserved37() override { psmType0NewParticle(this); } float reserved38() const override { @@ -193,10 +252,11 @@ public: int reserved39() const override { return at(0x28); } const Vec3& getPosition() const override { return at(0xB4); } void reserved41(float value) override { psmType0Update(this,value); } + // PE 0x1017EFC0 void reserved42(bool value) override { - if (at(4) && value!=static_cast(at(6))) - { at(7)=value; psmReclassification(reinterpret_cast(g_ParticleSystemManager)).insert(reinterpret_cast(this)); } + if (at(4) && static_cast(value)!=at(6)) + { at(7)=value; psmReclassification(reinterpret_cast(g_ParticleSystemManager)).insert(this); } } float getGasCloudRadius() const override { return at(0x228); } void setPlayer(void* value) override { at(0x230)=value; } @@ -204,11 +264,15 @@ public: void setMaterial(int value) override { at(0x234)=value; } int getMaterial() const override { return at(0x234); } void setEffectController(world::IEffectController* value) override - { at(0xC)=value; reserved11(reinterpret_cast(value ? value->getObject() : 0)); } + { at(0xC)=value; reserved11(reinterpret_cast(value ? value->getObject() : 0)); } world::IEffectController* getEffectController() const override { return at(0xC); } bool getWaterSide() const override { return at(0x238)!=0; } }; +#if defined(_M_IX86) static_assert(sizeof(ParticleInstanceType0)==0x23C,"ordinary particle instance PE1017F870 layout"); +#else +static_assert(sizeof(ParticleInstanceType0)==kPsmInstanceSize,"x64 instance layout, ParticleRawLayout.h"); +#endif IParticleSystemInstance* psmCreateType0Instance(IParticleSystemTemplate* descriptor) { diff --git a/Code/BF2/Geom/ParticleSystem/ParticleInstanceType0Emission.inl b/Code/BF2/Geom/ParticleSystem/ParticleInstanceType0Emission.inl index 08e53a231..ec212e390 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleInstanceType0Emission.inl +++ b/Code/BF2/Geom/ParticleSystem/ParticleInstanceType0Emission.inl @@ -13,24 +13,14 @@ struct PsmEmissionRandom }; static PsmEmissionRandom psmType0Random = { 0x759DC150u, false, 0 }; -unsigned int psmEmissionRandomStep(unsigned int value, unsigned int multiplier) -{ - const unsigned int low = (value & 0xFFFFu) * multiplier; - const unsigned int high = static_cast(static_cast(value) >> 16) * multiplier; - const int middle = static_cast((low >> 16) + high); - const unsigned int next = (low & 0xFFFFu) + ((static_cast(middle) & 0x7FFFu) << 16) - + static_cast(middle >> 15); - const int reduced = static_cast(next - 0x7FFFFFFFu); - return reduced < 0 ? next : static_cast(reduced); -} unsigned int psmEmissionRaw() { - psmType0Random.seed = psmEmissionRandomStep(psmEmissionRandomStep(psmType0Random.seed,24112),26143); - return psmType0Random.seed; + return lcgrandStep(&psmType0Random.seed); // PE 0x1009EF30 (LcgRandom.h) } int psmEmissionRandomInteger() { return (static_cast(psmEmissionRaw() | 0x80u) >> 7) + 1; } double psmEmissionUnit() { return static_cast(psmEmissionRandomInteger()) * 0.000000059604644775390625; } double psmEmissionSymmetric() { return static_cast(psmEmissionRandomInteger()) * 0.00000011920928955078125 - 1.0; } +// PE 0x1017A360. The cached second deviate is returned on the next call. double psmEmissionNormal() { if (psmType0Random.normalReady) @@ -52,32 +42,52 @@ double psmEmissionNormal() psmType0Random.normalReady = true; return scale * first; } +// PE 0x1017A330. Exponential deviate: -ln(u) * value, u the 24-bit unit draw. +double psmEmissionExponential(float value) +{ + return -::log(psmEmissionUnit()) * value; +} +// PE 0x1009EFC0 (`retn 8`, the Random in ecx): the 24-bit draw (step, `or al, 80h`, `sar eax, 7`, +// + 1) times (high - low), times 2^-24 (0x33800000), plus low; the double stays in ST0. +// [INFERRED] name (a Random::uniform-style member of the renderer-local Random). +double psmEmissionUniform(float low, float high) +{ + return psmEmissionRandomInteger() * (static_cast(high) - low) * 0.000000059604644775390625 + + low; +} +// PE 0x1017A420. Kind selector (unsigned compare against 3): 0 the value, 1 the uniform helper +// (psmEmissionUniform, called out of line as at 0x1017A441), 2 the exponential arm, 3 the normal +// deviate scaled by variation plus value; any other kind answers 0. +double psmEmissionKind(unsigned int kind, float value, float variation) +{ + switch (kind) + { + case 0: return value; + case 1: return psmEmissionUniform(value, variation); + case 2: return psmEmissionExponential(value); + case 3: return psmEmissionNormal() * variation + value; + default: return 0; + } +} +// PE 0x1017A480 (optional random sign), calling the kind selector PE 0x1017A420. double psmEmissionDistribution(void* distribution) { const float sign = psmRuntimeField(distribution,12) ? (psmEmissionUnit() > 0.5 ? 1.0f : -1.0f) : 1.0f; const float value = psmRuntimeField(distribution,4); const float variation = psmRuntimeField(distribution,8); - double result; - switch (psmRuntimeField(distribution,0)) - { - case 0: result = value; break; - case 1: result = psmEmissionRandomInteger() * (static_cast(variation)-value) - * 0.000000059604644775390625 + value; break; - case 2: result = -::log(psmEmissionUnit()) * value; break; - case 3: result = psmEmissionNormal() * variation + value; break; - default: result = 0; break; - } + const double result = psmEmissionKind(static_cast(psmRuntimeField(distribution,0)), + value, variation); return result * sign; } void psmEmissionDirection(float* output, void* descriptor, void* self) { - output[0]=psmRuntimeField(descriptor,0x20C)*psmRuntimeField(self,0x150); - output[1]=psmRuntimeField(descriptor,0x210)*psmRuntimeField(self,0x154); - output[2]=psmRuntimeField(descriptor,0x214)*psmRuntimeField(self,0x158); + output[0]=psmDescriptor0(descriptor,0x20C)*psmInstanceA(self,0x150); + output[1]=psmDescriptor0(descriptor,0x210)*psmInstanceA(self,0x154); + output[2]=psmDescriptor0(descriptor,0x214)*psmInstanceA(self,0x158); } -// PE10181100: five draws even when all dimensions are zero. +// PE 0x10181100: five draws even when all dimensions are zero. void psmEmissionSphere(float* output, void* descriptor, void* self, float* particle) { const float phi = static_cast(psmEmissionRandomInteger() * static_cast(3.7450703871400037e-7f)); @@ -86,25 +96,25 @@ void psmEmissionSphere(float* output, void* descriptor, void* self, float* parti const float sineTheta = static_cast(::sin(theta)); const float yRandom = static_cast(psmEmissionUnit()); const float xRandom = static_cast(psmEmissionUnit()); - const double zRadius = psmEmissionRandomInteger() * static_cast(psmRuntimeField(descriptor,0x20)) + const double zRadius = psmEmissionRandomInteger() * static_cast(psmDescriptor0(descriptor,0x20)) * 0.000000059604644775390625; - const double xRadius = static_cast(xRandom) * psmRuntimeField(descriptor,0x18); - const double yRadius = static_cast(yRandom) * psmRuntimeField(descriptor,0x1C); + const double xRadius = static_cast(xRandom) * psmDescriptor0(descriptor,0x18); + const double yRadius = static_cast(yRandom) * psmDescriptor0(descriptor,0x1C); particle[18]=static_cast(::cos(phi)*xRadius*sineTheta); particle[19]=static_cast(::sin(phi)*yRadius*sineTheta); particle[20]=static_cast(::cos(savedTheta)*zRadius); psmEmissionDirection(output,descriptor,self); } -// PE10181230. Shape1 emits radially; shape2 uses the configured direction. Largest-axis ties +// PE 0x10181230. Shape1 emits radially; shape2 uses the configured direction. Largest-axis ties // select the first component. The distributions are sampled Z,Y,X, not X,Y,Z. void psmEmissionCylinder(float* output, void* descriptor, void* self, float* particle) { - const double angle=(psmEmissionSymmetric()*psmRuntimeField(descriptor,0x70) - +psmRuntimeField(descriptor,0x74))*0.01745329238474369f; + const double angle=(psmEmissionSymmetric()*psmDescriptor0(descriptor,0x70) + +psmDescriptor0(descriptor,0x74))*0.01745329238474369f; const float sine=static_cast(::sin(angle)), cosine=static_cast(::cos(angle)); unsigned int axis=0; - if(psmRuntimeField(descriptor,0x1C)>psmRuntimeField(descriptor,0x18))axis=1; - if(psmRuntimeField(descriptor,0x20)>psmRuntimeField(descriptor,0x18+4*axis))axis=2; + if(psmDescriptor0(descriptor,0x1C)>psmDescriptor0(descriptor,0x18))axis=1; + if(psmDescriptor0(descriptor,0x20)>psmDescriptor0(descriptor,0x18+4*axis))axis=2; unsigned char* const bytes=static_cast(descriptor); const float z=static_cast(psmEmissionDistribution(bytes+0x4C)); const float y=static_cast(psmEmissionDistribution(bytes+0x38)); @@ -112,7 +122,7 @@ void psmEmissionCylinder(float* output, void* descriptor, void* self, float* par if(axis==0){particle[18]=static_cast(x);particle[19]=y*sine;particle[20]=z*cosine;} else if(axis==1){particle[18]=static_cast(x*sine);particle[19]=y;particle[20]=z*cosine;} else{particle[18]=static_cast(x*sine);particle[19]=y*cosine;particle[20]=z;} - if(psmRuntimeField(descriptor,0x264)==1) + if(psmDescriptor0(descriptor,0x264)==1) { output[0]=particle[18];output[1]=particle[19];output[2]=particle[20]; output[axis]=0; @@ -120,6 +130,7 @@ void psmEmissionCylinder(float* output, void* descriptor, void* self, float* par } else psmEmissionDirection(output,descriptor,self); } +// PE 0x10181420. The distributions are sampled Z,Y,X. void psmEmissionBox(float* output, void* descriptor, void* self, float* particle) { unsigned char* const bytes=static_cast(descriptor); @@ -133,8 +144,10 @@ void psmEmissionBox(float* output, void* descriptor, void* self, float* particle // PE10077DA0/E30/EC0 use the x87 fsincos on an explicitly rounded float angle. void psmEmissionRotation(Mat4& matrix, float degrees, unsigned int axis) { +#if defined(_WIN32) const float radians=degrees*0.01745329238474369f; float sine,cosine; +#if defined(_M_IX86) __asm { fld radians @@ -142,10 +155,26 @@ void psmEmissionRotation(Mat4& matrix, float degrees, unsigned int axis) fstp cosine fstp sine } +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + cosine=static_cast(::cos(static_cast(radians))); + sine=static_cast(::sin(static_cast(radians))); +#endif + matrix=Mat4::getIdentity(); + if(axis==0){matrix.m[5]=cosine;matrix.m[6]=sine;matrix.m[9]=-sine;matrix.m[10]=cosine;} + else if(axis==1){matrix.m[0]=cosine;matrix.m[2]=-sine;matrix.m[8]=sine;matrix.m[10]=cosine;} + else{matrix.m[0]=cosine;matrix.m[1]=-sine;matrix.m[4]=sine;matrix.m[5]=cosine;} +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-port.md). + const float radians=degrees*0.01745329238474369f; + float sine,cosine; + // [CHOSEN, not recovered] Preserve x87 rounded angle and float sin/cos stores. + bf2x87::trig(radians, sine, cosine); matrix=Mat4::getIdentity(); if(axis==0){matrix.m[5]=cosine;matrix.m[6]=sine;matrix.m[9]=-sine;matrix.m[10]=cosine;} else if(axis==1){matrix.m[0]=cosine;matrix.m[2]=-sine;matrix.m[8]=sine;matrix.m[10]=cosine;} else{matrix.m[0]=cosine;matrix.m[1]=-sine;matrix.m[4]=sine;matrix.m[5]=cosine;} +#endif } // PE10078180: 3x3 product; order differs for the first row's first/last components. void psmEmissionRotateMultiply(Mat4& output,const Mat4& left,const Mat4& right) @@ -172,46 +201,47 @@ float psmEmissionClamp(float value) return value; } +// PE 0x1017FF30 float* psmType0NewParticle(void* self) { - void* const manager=g_ParticleSystemManager; - float* const particle=psmRuntimeField(manager,0x5F20); - psmRuntimeField(manager,0x5F20)=particle?psmRuntimeField(particle,0):nullptr; - psmRuntimeField(manager,0x5F28)+=particle!=nullptr; + ParticleSystemManager* const manager=reinterpret_cast(g_ParticleSystemManager); + float* const particle=static_cast(manager->m_type0FreeList); // +0x5F20 + manager->m_type0FreeList=particle?static_cast(psmRecordLink(particle, 0)):nullptr; + manager->m_type0LiveCount+=particle!=nullptr; // +0x5F28 if(!particle)return nullptr; - ++psmRuntimeField(self,0x144); - void* descriptor=psmRuntimeField(self,0x2C); - if(psmRuntimeField(descriptor,0xCD)) + ++psmInstanceA(self,0x144); + void* descriptor=psmInstanceA(self,0x2C); + if(psmDescriptor0(descriptor,0xCD)) { const int random=psmEmissionRandomInteger(); - descriptor=psmRuntimeField(self,0x2C); - const unsigned int count=psmRuntimeField(descriptor,0xE0)-1; + descriptor=psmInstanceA(self,0x2C); + const unsigned int count=psmDescriptor0(descriptor,0xE0)-1; particle[30]=static_cast(::floor(static_cast(random)*count*0.000000059604644775390625)); } else particle[30]=0; psmRuntimeField(particle,0x54)|=0xFu; particle[12]=0; - descriptor=psmRuntimeField(self,0x2C); - const double lifetime=psmEmissionRandomInteger()*static_cast(psmRuntimeField(descriptor,0x80)) - *0.000000059604644775390625+psmRuntimeField(descriptor,0x84); + descriptor=psmInstanceA(self,0x2C); + const double lifetime=psmEmissionRandomInteger()*static_cast(psmDescriptor0(descriptor,0x80)) + *0.000000059604644775390625+psmDescriptor0(descriptor,0x84); particle[28]=static_cast(lifetime);particle[29]=static_cast(1.0/lifetime); - particle[27]=psmRuntimeField(self,0xD8);particle[9]=particle[27]*particle[29]; - particle[3]=psmRuntimeField(self,0x15C); - descriptor=psmRuntimeField(self,0x2C); - particle[13]=psmRuntimeField(descriptor,0x1AC);particle[14]=psmRuntimeField(descriptor,0x1B0); - particle[11]=psmRuntimeField(self,0x160);particle[22]=psmRuntimeField(self,0x160); - particle[2]=psmRuntimeField(descriptor,0xA0); - psmRuntimeField(particle,0x40)=psmRuntimeField(descriptor,0x21E); - psmRuntimeField(particle,0x42)=psmRuntimeField(descriptor,0x220); + particle[27]=psmInstanceA(self,0xD8);particle[9]=particle[27]*particle[29]; + particle[3]=psmInstanceA(self,0x15C); + descriptor=psmInstanceA(self,0x2C); + particle[13]=psmDescriptor0(descriptor,0x1AC);particle[14]=psmDescriptor0(descriptor,0x1B0); + particle[11]=psmInstanceA(self,0x160);particle[22]=psmInstanceA(self,0x160); + particle[2]=psmDescriptor0(descriptor,0xA0); + psmRuntimeField(particle,0x40)=psmDescriptor0(descriptor,0x21E); + psmRuntimeField(particle,0x42)=psmDescriptor0(descriptor,0x220); const float firstRandom=static_cast(psmEmissionSymmetric()); - particle[10]=firstRandom*psmRuntimeField(descriptor,0x1B4); - particle[4]=static_cast(psmEmissionSymmetric()*psmRuntimeField(descriptor,0x1B8)); - particle[32]=static_cast(psmEmissionSymmetric()*psmRuntimeField(descriptor,0x1BC)); - const double spin=psmEmissionSymmetric()*psmRuntimeField(descriptor,0x94); - particle[31]=static_cast(spin>=0?spin+psmRuntimeField(descriptor,0x98) - :spin-psmRuntimeField(descriptor,0x98)); + particle[10]=firstRandom*psmDescriptor0(descriptor,0x1B4); + particle[4]=static_cast(psmEmissionSymmetric()*psmDescriptor0(descriptor,0x1B8)); + particle[32]=static_cast(psmEmissionSymmetric()*psmDescriptor0(descriptor,0x1BC)); + const double spin=psmEmissionSymmetric()*psmDescriptor0(descriptor,0x94); + particle[31]=static_cast(spin>=0?spin+psmDescriptor0(descriptor,0x98) + :spin-psmDescriptor0(descriptor,0x98)); float direction[3]={0,0,0}; - switch(psmRuntimeField(descriptor,0x264)) + switch(psmDescriptor0(descriptor,0x264)) { case 0:psmEmissionSphere(direction,descriptor,self,particle);break; case 1:case 2:psmEmissionCylinder(direction,descriptor,self,particle);break; @@ -221,25 +251,25 @@ float* psmType0NewParticle(void* self) const float randomY=static_cast(psmEmissionSymmetric()); const float randomZ=static_cast(psmEmissionSymmetric()); Mat4 rotation,axis,copy; - psmEmissionRotation(rotation,randomX*psmRuntimeField(descriptor,0x1C4),0); - psmEmissionRotation(axis,randomY*psmRuntimeField(descriptor,0x1C8),1); + psmEmissionRotation(rotation,randomX*psmDescriptor0(descriptor,0x1C4),0); + psmEmissionRotation(axis,randomY*psmDescriptor0(descriptor,0x1C8),1); copy=rotation;psmEmissionRotateMultiply(rotation,copy,axis); - psmEmissionRotation(axis,randomZ*psmRuntimeField(descriptor,0x1CC),2); + psmEmissionRotation(axis,randomZ*psmDescriptor0(descriptor,0x1CC),2); copy=rotation;psmEmissionRotateMultiply(rotation,copy,axis); const float x=direction[0],y=direction[1],z=direction[2]; direction[2]=static_cast(static_cast(rotation.m[2])*x+static_cast(rotation.m[6])*y+static_cast(rotation.m[10])*z); direction[1]=static_cast(static_cast(rotation.m[1])*x+static_cast(rotation.m[9])*z+static_cast(rotation.m[5])*y); direction[0]=static_cast(static_cast(rotation.m[0])*x+static_cast(rotation.m[8])*z+static_cast(rotation.m[4])*y); - float speed=static_cast((psmRuntimeField(descriptor,0x1D0) - -static_cast(firstRandom)*psmRuntimeField(descriptor,0x1C0))*psmRuntimeField(self,0x13C)); - const float emitTime=psmRuntimeField(descriptor,0x1D4); - const double t=emitTime>0?1.0-static_cast(psmRuntimeField(self,0xE0))/emitTime:0; - const float envelope=static_cast(t*t*psmRuntimeField(descriptor,0x130)+t*psmRuntimeField(descriptor,0x134) - +t*t*t*psmRuntimeField(descriptor,0x12C)+psmRuntimeField(descriptor,0x138)); + float speed=static_cast((psmDescriptor0(descriptor,0x1D0) + -static_cast(firstRandom)*psmDescriptor0(descriptor,0x1C0))*psmInstanceA(self,0x13C)); + const float emitTime=psmDescriptor0(descriptor,0x1D4); + const double t=emitTime>0?1.0-static_cast(psmInstanceA(self,0xE0))/emitTime:0; + const float envelope=static_cast(t*t*psmDescriptor0(descriptor,0x130)+t*psmDescriptor0(descriptor,0x134) + +t*t*t*psmDescriptor0(descriptor,0x12C)+psmDescriptor0(descriptor,0x138)); speed*=psmEmissionClamp(envelope); - if(!psmRuntimeField(descriptor,0x21D)) + if(!psmDescriptor0(descriptor,0x21D)) { - const float* const matrix=psmRuntimeField(self,0x74).m; + const float* const matrix=psmInstanceA(self,0x74).m; const float px=particle[18],py=particle[19],pz=particle[20]; particle[20]=static_cast(static_cast(matrix[2])*px+static_cast(matrix[10])*pz+static_cast(matrix[6])*py+matrix[14]); particle[19]=static_cast(static_cast(matrix[1])*px+static_cast(matrix[9])*pz+static_cast(matrix[5])*py+matrix[13]); @@ -248,100 +278,104 @@ float* psmType0NewParticle(void* self) direction[2]=static_cast(static_cast(matrix[10])*dz+static_cast(matrix[2])*dx+static_cast(matrix[6])*dy); direction[1]=static_cast(static_cast(matrix[9])*dz+static_cast(matrix[1])*dx+static_cast(matrix[5])*dy); direction[0]=static_cast(static_cast(matrix[8])*dz+static_cast(matrix[4])*dy+static_cast(matrix[0])*dx); - const double scale=psmRuntimeField(self,0xDC); - const float inheritedX=static_cast(scale*psmRuntimeField(self,0xCC)); - const float inheritedY=static_cast(scale*psmRuntimeField(self,0xD0)); + const double scale=psmInstanceA(self,0xDC); + const float inheritedX=static_cast(scale*psmInstanceA(self,0xCC)); + const float inheritedY=static_cast(scale*psmInstanceA(self,0xD0)); const float vy=direction[1]*speed,vz=direction[2]*speed; - particle[26]=static_cast(vz+scale*psmRuntimeField(self,0xD4)); + particle[26]=static_cast(vz+scale*psmInstanceA(self,0xD4)); particle[24]=static_cast(static_cast(direction[0])*speed+inheritedX); particle[25]=vy+inheritedY; } else {particle[26]=direction[2]*speed;particle[24]=direction[0]*speed;particle[25]=direction[1]*speed;} - descriptor=psmRuntimeField(self,0x2C); - void* const region=psmRuntimeField(descriptor,0x260); - psmRuntimeField(particle,0x5C)=region?psmRuntimeField(region,0x10):psmRuntimeField(descriptor,0x25C); - psmRuntimeField(particle,0x90)=psmRuntimeField(descriptor,0x78)==2; - float** const list=psmRuntimeField(self,0x24); - list[psmRuntimeField(self,0x28)++]=particle; - list[psmRuntimeField(self,0x28)]=nullptr; + descriptor=psmInstanceA(self,0x2C); + void* const region=psmDescriptor0(descriptor,0x260); + psmRecordPointer(particle, 0)=region?static_cast(static_cast(region)->page):psmDescriptor0(descriptor,0x25C); + psmRuntimeField(particle,0x90)=psmDescriptor0(descriptor,0x78)==2; + float** const list=psmInstanceA(self,0x24); + list[psmInstanceA(self,0x28)++]=particle; + list[psmInstanceA(self,0x28)]=nullptr; return particle; } +// PE 0x10180500 (the trailing jmp at 0x10180900 is the psmType0NewParticle thunk). void psmType0Emit(void* self,float /*dt*/) { - if(!psmRuntimeField(self,0x14C))return; + if(!psmInstanceA(self,0x14C))return; const unsigned int frame=static_cast(dx9rend::g_rendererBase)->getFrameOrdinal(); - if(psmRuntimeField(self,0x124)+60u(self,0x124)+60u(self,0x129)=psmRuntimeField(self,0x128); - psmRuntimeField(self,0x128)=0;return; + psmInstanceA(self,0x129)=psmInstanceA(self,0x128); + psmInstanceA(self,0x128)=0;return; } - void* const descriptor=psmRuntimeField(self,0x2C); - const float lower=psmRuntimeField(descriptor,0xC4); - if(psmRuntimeField(self,0x134)(self,0x134)=lower; - if(psmRuntimeField(self,0x138)(self,0x138)=lower; - double frequency=static_cast(psmRuntimeField(descriptor,0x10))*psmRuntimeField(self,0x134)*psmRuntimeField(self,0x138); - void* const manager=g_ParticleSystemManager; - if(psmRuntimeField(descriptor,0x6C)||psmRuntimeField(self,0xE8)>1.0f) + void* const descriptor=psmInstanceA(self,0x2C); + const float lower=psmDescriptor0(descriptor,0xC4); + if(psmInstanceA(self,0x134)(self,0x134)=lower; + if(psmInstanceA(self,0x138)(self,0x138)=lower; + double frequency=static_cast(psmDescriptor0(descriptor,0x10))*psmInstanceA(self,0x134)*psmInstanceA(self,0x138); + ParticleSystemManager* const manager=reinterpret_cast(g_ParticleSystemManager); + if(psmDescriptor0(descriptor,0x6C)||psmInstanceA(self,0xE8)>1.0f) { - if(psmRuntimeField(manager,0x1D3C) - ||psmRuntimeField(manager,0x5F28)>static_cast(static_cast( - static_cast(psmRuntimeField(manager,0x5F24))*psmRuntimeField(manager,0x8C08)))) - frequency*=psmRuntimeField(manager,0x8BFC+4*psmRuntimeField(descriptor,0x60)); + // Retail manager +0x1D3C (the sprite renderer's over-limit byte), +0x5F28, +0x5F24, +0x8C08, +0x8BFC. + if(manager->m_particleSystemRenderer[0x1C34] + ||manager->m_type0LiveCount>static_cast(static_cast( + static_cast(static_cast(manager->m_type0PoolCount))*manager->m_value8C08))) + frequency*=manager->m_tierThresholds[psmDescriptor0(descriptor,0x60)]; } - if(!(frequency>psmRuntimeField(descriptor,0x14)))frequency=psmRuntimeField(descriptor,0x14); + if(!(frequency>psmDescriptor0(descriptor,0x14)))frequency=psmDescriptor0(descriptor,0x14); const float interval=static_cast(1.0/frequency); - if(psmRuntimeField(self,0x224)) - {psmRuntimeField(self,0xC0)=psmRuntimeField(self,0xB4);psmRuntimeField(self,0x224)=0;} - if(psmRuntimeField(descriptor,0x268)) + if(psmInstanceA(self,0x224)) + {psmInstanceA(self,0xC0)=psmInstanceA(self,0xB4);psmInstanceA(self,0x224)=0;} + if(psmDescriptor0(descriptor,0x268)) { - // [TEMP][CHOSEN, not recovered][RETIRE-WHEN: particle-emission-debug-draw] - // PE10180621 draws emission statistics through the unrecovered debug owner10247C50+28. - std::fprintf(stderr,"[FRONTIER] dice::hfe::geom::SpriteParticleSystem::emit(debug statistics) reached\n"); - std::fflush(stderr);std::abort(); + // PE 0x10180662..0x101806AA: the retained frequency is published as a double. + debugTextWriterQueueWorldText(g_DebugTextWriter, psmInstanceA(self,0xC0), 0xFFFFFFFFu, + formatString("f:%f, eaf:%f, esf:%f, count:%d", frequency, + static_cast(psmInstanceA(self,0x134)), + static_cast(psmInstanceA(self,0x138)), + static_cast(psmInstanceA(self,0x28))), 0); } - while(static_cast(interval)+psmRuntimeField(self,0xF0)<=psmRuntimeField(self,0xE8)) + while(static_cast(interval)+psmInstanceA(self,0xF0)<=psmInstanceA(self,0xE8)) { - if(psmRuntimeField(self,0xE0)!=0) + if(psmInstanceA(self,0xE0)!=0) { - const double remaining=static_cast(psmRuntimeField(self,0xE0))-interval; - psmRuntimeField(self,0xE0)=static_cast(remaining); + const double remaining=static_cast(psmInstanceA(self,0xE0))-interval; + psmInstanceA(self,0xE0)=static_cast(remaining); if(remaining<=0) { static_cast(self)->reserved04(); - if(psmRuntimeField(psmRuntimeField(self,0x2C),0x6C)) - static_cast(self)->reserved03(psmRuntimeField(self,6)!=0); + if(psmDescriptor0(psmInstanceA(self,0x2C),0x6C)) + static_cast(self)->reserved03(psmInstanceA(self,6)!=0); return; } } - psmRuntimeField(self,0xF0)=interval+psmRuntimeField(self,0xF0); - if(psmRuntimeField(self,0x128)&&psmRuntimeField(self,0x28)(self,0x220)) + psmInstanceA(self,0xF0)=interval+psmInstanceA(self,0xF0); + if(psmInstanceA(self,0x128)&&psmInstanceA(self,0x28)(self,0x220)) { float fraction=0; - if(psmRuntimeField(self,0xE8)>psmRuntimeField(self,0xEC)) - fraction=static_cast((static_cast(psmRuntimeField(self,0xF0))-psmRuntimeField(self,0xEC)) - /(static_cast(psmRuntimeField(self,0xE8))-psmRuntimeField(self,0xEC))); - const Vec3& from=psmRuntimeField(self,0xC0); - const Vec3& to=psmRuntimeField(self,0xB4); + if(psmInstanceA(self,0xE8)>psmInstanceA(self,0xEC)) + fraction=static_cast((static_cast(psmInstanceA(self,0xF0))-psmInstanceA(self,0xEC)) + /(static_cast(psmInstanceA(self,0xE8))-psmInstanceA(self,0xEC))); + const Vec3& from=psmInstanceA(self,0xC0); + const Vec3& to=psmInstanceA(self,0xB4); const float zDifference=to.z-from.z; const float xScaled=static_cast((static_cast(to.x)-from.x)*fraction); const double yScaled=(static_cast(to.y)-from.y)*fraction; const float zScaled=zDifference*fraction; - psmRuntimeField(self,0xA4)={xScaled+from.x,static_cast(yScaled+from.y),zScaled+from.z}; + psmInstanceA(self,0xA4)={xScaled+from.x,static_cast(yScaled+from.y),zScaled+from.z}; float* const particle=psmType0NewParticle(self); if(particle) { - particle[24]+=psmRuntimeField(self,0x18); - particle[25]+=psmRuntimeField(self,0x1C); - particle[26]+=psmRuntimeField(self,0x20); + particle[24]+=psmInstanceA(self,0x18); + particle[25]+=psmInstanceA(self,0x1C); + particle[26]+=psmInstanceA(self,0x20); for(unsigned int axis=24;axis<=26;++axis)if(::fabs(particle[axis])<0.001f)particle[axis]=0; - const unsigned int steps=static_cast(static_cast((static_cast(psmRuntimeField(self,0xE8)) - -psmRuntimeField(self,0xF0))*100.0)); - if(psmType0AdvanceParticle(self,particle,psmRuntimeField(self,0x28)-1,0.01f,steps)) + const unsigned int steps=static_cast(static_cast((static_cast(psmInstanceA(self,0xE8)) + -psmInstanceA(self,0xF0))*100.0)); + if(psmType0AdvanceParticle(self,particle,psmInstanceA(self,0x28)-1,0.01f,steps)) { - const float remainder=static_cast((static_cast(psmRuntimeField(self,0xE8)) - -psmRuntimeField(self,0xF0))-static_cast(steps)*0.01f); - psmType0AdvanceParticle(self,particle,psmRuntimeField(self,0x28)-1,remainder,1); + const float remainder=static_cast((static_cast(psmInstanceA(self,0xE8)) + -psmInstanceA(self,0xF0))-static_cast(steps)*0.01f); + psmType0AdvanceParticle(self,particle,psmInstanceA(self,0x28)-1,remainder,1); } } } diff --git a/Code/BF2/Geom/ParticleSystem/ParticleInstanceType0Update.inl b/Code/BF2/Geom/ParticleSystem/ParticleInstanceType0Update.inl index f0598abae..8e7e785e5 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleInstanceType0Update.inl +++ b/Code/BF2/Geom/ParticleSystem/ParticleInstanceType0Update.inl @@ -4,21 +4,23 @@ float psmType0Clamp(float value) { if (value>=1) value=1; if (!(value>=0)) return 0; return value; } +// PE 0x1017FE90. Unordered timers take the update arm (AH&5 parity). void psmType0RememberPlane(void* self) { - if (psmRuntimeField(self,0x21C)>=0.33333001f) + if (!(psmInstanceA(self,0x21C)<0.33333001f)) { - const unsigned char next=psmRuntimeField(self,0x219); - psmRuntimeField(self,0x218)=next; - psmRuntimeField(self,0x21C)-=0.33333001f; - float* target=&psmRuntimeField(self,0x168+16*next); - const float* source=&psmRuntimeField(self,0x208); + const unsigned char next=psmInstanceA(self,0x219); + psmInstanceA(self,0x218)=next; + psmInstanceA(self,0x21C)-=0.33333001f; + float* target=&psmInstanceA(self,0x168+16*next); + const float* source=&psmInstanceA(self,0x208); target[0]=source[0]; target[1]=source[1]; target[2]=source[2]; const float distance=source[3]; psmNormalize3(target); target[3]=distance; - psmRuntimeField(self,0x219)=(psmRuntimeField(self,0x219)+1)%10; + psmInstanceA(self,0x219)=(psmInstanceA(self,0x219)+1)%10; } } +// PE 0x1017F290 int psmType0AdvanceParticle(void* self,float* particle,int index,float step,unsigned int steps) { ParticleSystemManager* const manager=reinterpret_cast(g_ParticleSystemManager); @@ -26,37 +28,37 @@ int psmType0AdvanceParticle(void* self,float* particle,int index,float step,unsi particle[27]=static_cast(age); if (age>=particle[28]) { - float** const array=psmRuntimeField(self,0x24); - const unsigned int last=--psmRuntimeField(self,0x28); + float** const array=psmInstanceA(self,0x24); + const unsigned int last=--psmInstanceA(self,0x28); array[index]=array[last]; array[last]=0; - psmRuntimeField(particle,0)=manager->m_type0FreeList; - --psmRuntimeField(manager,0x5F28); manager->m_type0FreeList=particle; - ++psmRuntimeField(self,0x148); + psmRecordLink(particle, 0)=manager->m_type0FreeList; + --manager->m_type0LiveCount; manager->m_type0FreeList=particle; + ++psmInstanceA(self,0x148); return 0; } - void* descriptor=psmRuntimeField(self,0x2C); + void* descriptor=psmInstanceA(self,0x2C); Vec3 wind={0,0,0}; - if (manager->m_windEnabled && !psmRuntimeField(descriptor,0x21D) - && psmRuntimeField(descriptor,0xA4)>0) + if (manager->m_windEnabled && !psmDescriptor0(descriptor,0x21D) + && psmDescriptor0(descriptor,0xA4)>0) { wind=reinterpret_cast(manager->m_windManager)->getWind( *reinterpret_cast(particle+18)); - descriptor=psmRuntimeField(self,0x2C); - const float affection=psmRuntimeField(descriptor,0xA4); + descriptor=psmInstanceA(self,0x2C); + const float affection=psmDescriptor0(descriptor,0xA4); wind.x*=affection; wind.y*=affection; wind.z*=affection; } // The PE caches t/t^2/t^3 in three process-local scratch floats before the two graphs. const float t=particle[9]; const float t2=static_cast(static_cast(t)*t); const float t3=static_cast(static_cast(t)*t*t); - const float gravityStep=step*psmRuntimeField(descriptor,0x8C); - const float dragCurve=static_cast(static_cast(t2)*psmRuntimeField(descriptor,0x120) - +static_cast(t)*psmRuntimeField(descriptor,0x124) - +static_cast(t3)*psmRuntimeField(descriptor,0x11C)+psmRuntimeField(descriptor,0x128)); - const float drag=static_cast(static_cast(psmType0Clamp(dragCurve))*psmRuntimeField(descriptor,0x90)*step); - const float gravityCurve=static_cast(static_cast(t2)*psmRuntimeField(descriptor,0x110) - +static_cast(t)*psmRuntimeField(descriptor,0x114) - +static_cast(t3)*psmRuntimeField(descriptor,0x10C)+psmRuntimeField(descriptor,0x118)); + const float gravityStep=step*psmDescriptor0(descriptor,0x8C); + const float dragCurve=static_cast(static_cast(t2)*psmDescriptor0(descriptor,0x120) + +static_cast(t)*psmDescriptor0(descriptor,0x124) + +static_cast(t3)*psmDescriptor0(descriptor,0x11C)+psmDescriptor0(descriptor,0x128)); + const float drag=static_cast(static_cast(psmType0Clamp(dragCurve))*psmDescriptor0(descriptor,0x90)*step); + const float gravityCurve=static_cast(static_cast(t2)*psmDescriptor0(descriptor,0x110) + +static_cast(t)*psmDescriptor0(descriptor,0x114) + +static_cast(t3)*psmDescriptor0(descriptor,0x10C)+psmDescriptor0(descriptor,0x118)); const float gravity=psmType0Clamp(gravityCurve)*gravityStep; particle[9]=particle[29]*particle[27]; while (steps--) @@ -85,18 +87,27 @@ int psmType0AdvanceParticle(void* self,float* particle,int index,float step,unsi particle[26]=az+particle[26]; } for (int i=24;i<=26;++i) if (::fabs(particle[i])<0.001f) particle[i]=0; - descriptor=psmRuntimeField(self,0x2C); - if (psmRuntimeField(descriptor,0xEC)) + descriptor=psmInstanceA(self,0x2C); + if (psmDescriptor0(descriptor,0xEC)) { - const double difference=static_cast(psmRuntimeField(self,0x21C))-particle[27]; - const int current=psmRuntimeField(self,0x218); + const double difference=static_cast(psmInstanceA(self,0x21C))-particle[27]; + const int current=psmInstanceA(self,0x218); int selected=current; - if (difference<0) + // FCOM's carry branch also selects the history ring for an unordered age. + if (!(difference>=0)) { - selected-=static_cast(-3.0*difference)+1; - if (selected<0) selected+=10*((-1-selected)/10)+10; +#if defined(__APPLE__) + // [CHOSEN, not recovered] Preserve FISTP integer indefinite on native builds. + const int elapsed=bf2x87::toIntTruncate(bf2x87::mul(bf2x87::wide(-3.0f),bf2x87::wide(difference))); +#else + const int elapsed=static_cast(-3.0*difference); +#endif + selected=static_cast(static_cast(current)-static_cast(elapsed)-1u); + if (selected<0) selected=9-((-1-selected)%10); } - const float* plane=&psmRuntimeField(self,selected==current?0x208:0x168+16*selected); + // shipped defect: an unordered age can wrap the offset into preceding fields. + const unsigned int planeOffset=selected==current?0x208u:0x168u+16u*static_cast(selected); + const float* plane=&psmInstanceA(self,planeOffset); double velocityDot=static_cast(particle[26])*plane[2]+static_cast(particle[25])*plane[1]+static_cast(particle[24])*plane[0]; if (velocityDot<0) { @@ -111,7 +122,7 @@ int psmType0AdvanceParticle(void* self,float* particle,int index,float step,unsi { const double nx=velocityDot*plane[0], ny=velocityDot*plane[1]; const float nz=static_cast(velocityDot*plane[2]); - const float normal=psmRuntimeField(descriptor,0xF0), along=psmRuntimeField(descriptor,0xF4); + const float normal=psmDescriptor0(descriptor,0xF0), along=psmDescriptor0(descriptor,0xF4); const float tx=static_cast(particle[24]-nx), ty=static_cast(particle[25]-ny), tz=particle[26]-nz; const float rx=static_cast(nx*normal), ry=static_cast(ny*normal); particle[24]=static_cast(tx*along)-rx; particle[25]=static_cast(ty*along)-ry; @@ -122,109 +133,141 @@ int psmType0AdvanceParticle(void* self,float* particle,int index,float step,unsi } reinterpret_cast(particle)[0x54]|=0x80; particle[6]=particle[18]; particle[7]=particle[19]; particle[8]=particle[20]; - descriptor=psmRuntimeField(self,0x2C); - if (psmRuntimeField(descriptor,0x21D)) + descriptor=psmInstanceA(self,0x2C); + if (psmDescriptor0(descriptor,0x21D)) { - const float* m=&psmRuntimeField(self,0x74); + const float* m=&psmInstanceA(self,0x74); const double z=static_cast(m[10])*particle[8]+static_cast(m[6])*particle[7]+static_cast(m[2])*particle[6]+m[14]; const double y=static_cast(m[9])*particle[8]+static_cast(m[5])*particle[7]+static_cast(m[1])*particle[6]+m[13]; particle[6]=static_cast(static_cast(m[8])*particle[8]+static_cast(m[4])*particle[7]+static_cast(m[0])*particle[6]+m[12]); particle[7]=static_cast(y); particle[8]=static_cast(z); } - if (psmRuntimeField(descriptor,0xA8) && manager->m_heightmapCluster) - particle[7]=reinterpret_cast(manager->m_heightmapCluster)->getWaterLevelInWorldCoords(*reinterpret_cast(particle+6)); - float* bounds=&psmRuntimeField(self,0xFC); + if (psmDescriptor0(descriptor,0xA8)) + { + ParticleSystemManager* const waterManager=reinterpret_cast(g_ParticleSystemManager); + if (waterManager->m_heightmapCluster) + particle[7]=reinterpret_cast(waterManager->m_heightmapCluster)->getWaterLevelInWorldCoords(*reinterpret_cast(particle+6)); + } + float* bounds=&psmInstanceA(self,0xFC); for (int i=0;i<3;++i) { if(particle[6+i]>bounds[3+i]) bounds[3+i]=particle[6+i]; if(particle[6+i](self); ParticleSystemManager* const manager=reinterpret_cast(g_ParticleSystemManager); - const float scaled=dt*psmRuntimeField(self,0x12C); - void* descriptor=psmRuntimeField(self,0x2C); - psmRuntimeField(descriptor,8)=-1; + const float scaled=dt*psmInstanceA(self,0x12C); + void* descriptor=psmInstanceA(self,0x2C); + psmDescriptor0(descriptor,8)=-1; float elapsed=scaled; - if (!psmRuntimeField(self,0x28) && !psmRuntimeField(self,0x14C)) + if (!psmInstanceA(self,0x28) && !psmInstanceA(self,0x14C)) { psmQueueInactive(manager,instance); - if (psmRuntimeField(self,0x14)) + if (psmInstanceA(self,0x14)) reinterpret_cast(manager)->removeInstance(instance); return; } - if (psmRuntimeField(self,0x225) || scaled<=0) return; - if (!psmRuntimeField(self,0x129) && psmRuntimeField(self,0x128)) + if (psmInstanceA(self,0x225) || scaled<=0) return; + if (!psmInstanceA(self,0x129) && psmInstanceA(self,0x128)) { - psmRuntimeField(self,0x129)=psmRuntimeField(self,0x128); - if (psmRuntimeField(descriptor,0x269)) - for (float time=psmRuntimeField(descriptor,0x84);time>0;time-=0.1f) + psmInstanceA(self,0x129)=psmInstanceA(self,0x128); + if (psmDescriptor0(descriptor,0x269)) + for (float time=psmDescriptor0(descriptor,0x84);time>0;time-=0.1f) instance->reserved41(time>=0.1f?0.1f:time); } - descriptor=psmRuntimeField(self,0x2C); - if (psmRuntimeField(descriptor,0xEC)) - { psmRuntimeField(self,0x21C)+=scaled; psmType0RememberPlane(self); } - psmRuntimeField(self,0x148)=0; psmRuntimeField(self,0x144)=0; - const double maximum=static_cast(psmRuntimeField(descriptor,0x84))+psmRuntimeField(descriptor,0x80); + descriptor=psmInstanceA(self,0x2C); + if (psmDescriptor0(descriptor,0xEC)) + { psmInstanceA(self,0x21C)+=scaled; psmType0RememberPlane(self); } + psmInstanceA(self,0x148)=0; psmInstanceA(self,0x144)=0; + const double maximum=static_cast(psmDescriptor0(descriptor,0x84))+psmDescriptor0(descriptor,0x80); if (scaled>maximum) elapsed=static_cast(maximum); - for (int i=0;i<3;++i) { psmRuntimeField(self,0xFC+i*4)=0x4B18967F; psmRuntimeField(self,0x108+i*4)=0xCB18967F; } - psmRuntimeField(self,0xC0)=psmRuntimeField(self,0xA4); + for (int i=0;i<3;++i) { psmInstanceA(self,0xFC+i*4)=0x4B18967F; psmInstanceA(self,0x108+i*4)=0xCB18967F; } + psmInstanceA(self,0xC0)=psmInstanceA(self,0xA4); psmType0RefreshTransform(self); - psmRuntimeField(self,0xB4)=psmRuntimeField(self,0xA4); - descriptor=psmRuntimeField(self,0x2C); - if (psmRuntimeField(descriptor,0x21D) || psmRuntimeField(descriptor,0xB0)<=0 || psmRuntimeField(descriptor,0xA4)<=0) - psmRuntimeField(self,0x130)=psmRuntimeField(self,0x12C); + psmInstanceA(self,0xB4)=psmInstanceA(self,0xA4); + descriptor=psmInstanceA(self,0x2C); + if (psmDescriptor0(descriptor,0x21D) || psmDescriptor0(descriptor,0xB0)<=0 || psmDescriptor0(descriptor,0xA4)<=0) + psmInstanceA(self,0x130)=psmInstanceA(self,0x12C); else { - const Vec3 wind=reinterpret_cast(manager->m_windManager)->getWind(psmRuntimeField(self,0xA4)); + const Vec3 wind=reinterpret_cast(manager->m_windManager)->getWind(psmInstanceA(self,0xA4)); const double speed=static_cast(wind.x)*wind.x+static_cast(wind.y)*wind.y+static_cast(wind.z)*wind.z; - descriptor=psmRuntimeField(self,0x2C); - double divisor=static_cast(psmRuntimeField(descriptor,0xB4))*psmRuntimeField(descriptor,0xB4); + descriptor=psmInstanceA(self,0x2C); + double divisor=static_cast(psmDescriptor0(descriptor,0xB4))*psmDescriptor0(descriptor,0xB4); if (1.0>divisor) divisor=1.0; - double factor=static_cast(psmType0Clamp(static_cast(speed/divisor)))*psmRuntimeField(descriptor,0xB0); + double factor=static_cast(psmType0Clamp(static_cast(speed/divisor)))*psmDescriptor0(descriptor,0xB0); if (!(factor>1)) factor=1; - psmRuntimeField(self,0x130)=static_cast(factor*psmRuntimeField(self,0x12C)); + psmInstanceA(self,0x130)=static_cast(factor*psmInstanceA(self,0x12C)); } - const double total=static_cast(elapsed)+psmRuntimeField(self,0xF4); + const double total=static_cast(elapsed)+psmInstanceA(self,0xF4); const unsigned int steps=static_cast(static_cast(100.0*total)); const double advanced=static_cast(steps)*0.01f; - psmRuntimeField(self,0xEC)=psmRuntimeField(self,0xE8); - psmRuntimeField(self,0xF4)=static_cast(total-advanced); - psmRuntimeField(self,0xE8)=static_cast(advanced+psmRuntimeField(self,0xE8)); - for (unsigned int i=0;psmRuntimeField(self,0x24)[i];) - i+=psmType0AdvanceParticle(self,psmRuntimeField(self,0x24)[i],i,0.01f,steps); - const double delay=static_cast(psmRuntimeField(self,0xE4))-elapsed; - psmRuntimeField(self,0xE4)=static_cast(delay); - if (delay>0) { psmRuntimeField(self,0xF0)=psmRuntimeField(self,0xE8); return; } - if (psmRuntimeField(self,0xF8)>0) + psmInstanceA(self,0xEC)=psmInstanceA(self,0xE8); + psmInstanceA(self,0xF4)=static_cast(total-advanced); + psmInstanceA(self,0xE8)=static_cast(advanced+psmInstanceA(self,0xE8)); + for (unsigned int i=0;psmInstanceA(self,0x24)[i];) + i+=psmType0AdvanceParticle(self,psmInstanceA(self,0x24)[i],i,0.01f,steps); + const double delay=static_cast(psmInstanceA(self,0xE4))-elapsed; + psmInstanceA(self,0xE4)=static_cast(delay); + if (delay>0) { psmInstanceA(self,0xF0)=psmInstanceA(self,0xE8); return; } + if (psmInstanceA(self,0xF8)>0) { - float remaining=psmRuntimeField(self,0xF8); psmRuntimeField(self,0xF8)=0; + float remaining=psmInstanceA(self,0xF8); psmInstanceA(self,0xF8)=0; for (;remaining>0;remaining-=0.033333335f) instance->reserved41(remaining>=0.033333335f?0.033333335f:remaining); } psmType0Emit(self,elapsed); - psmRuntimeField(self,0xA4)=psmRuntimeField(self,0xB4); - float* bounds=&psmRuntimeField(self,0xFC); - if (psmRuntimeField(self,0x28)) + psmInstanceA(self,0xA4)=psmInstanceA(self,0xB4); + float* bounds=&psmInstanceA(self,0xFC); + if (psmInstanceA(self,0x28)) { - for (int i=0;i<3;++i) bounds[i]-=psmRuntimeField(psmRuntimeField(self,0x2C),0x148); - for (int i=3;i<6;++i) bounds[i]+=psmRuntimeField(psmRuntimeField(self,0x2C),0x148); + for (int i=0;i<3;++i) bounds[i]-=psmDescriptor0(psmInstanceA(self,0x2C),0x148); + for (int i=3;i<6;++i) bounds[i]+=psmDescriptor0(psmInstanceA(self,0x2C),0x148); } - else { psmRuntimeField(self,0xFC)=psmRuntimeField(self,0xA4); psmRuntimeField(self,0x108)=psmRuntimeField(self,0xA4); } + else { psmInstanceA(self,0xFC)=psmInstanceA(self,0xA4); psmInstanceA(self,0x108)=psmInstanceA(self,0xA4); } const float dz=bounds[5]-bounds[2], dx=static_cast((static_cast(bounds[3])-bounds[0])*0.5); const double dy=(static_cast(bounds[4])-bounds[1])*0.5; - psmRuntimeField(self,0x120)=static_cast(::sqrt(dz*0.5*(dz*0.5)+static_cast(dx)*dx+dy*dy)); + psmInstanceA(self,0x120)=static_cast(::sqrt(dz*0.5*(dz*0.5)+static_cast(dx)*dx+dy*dy)); const float zsum=bounds[5]+bounds[2]; - psmRuntimeField(self,0x114)={static_cast((static_cast(bounds[3])+bounds[0])*0.5),static_cast((static_cast(bounds[4])+bounds[1])*0.5),zsum*0.5f}; - IParticleSystemTemplate* const systemTemplate=psmRuntimeField(self,0x2C); + psmInstanceA(self,0x114)={static_cast((static_cast(bounds[3])+bounds[0])*0.5),static_cast((static_cast(bounds[4])+bounds[1])*0.5),zsum*0.5f}; + IParticleSystemTemplate* const systemTemplate=psmInstanceA(self,0x2C); if (systemTemplate->getGasCloudType()) { double duration=systemTemplate->getGasCloudRadiusTime(); if (duration==0) duration=1; - const double age=static_cast(scaled)+psmRuntimeField(self,0x22C); - psmRuntimeField(self,0x22C)=static_cast(age); - if (age>duration) psmRuntimeField(self,0x22C)=static_cast(duration); - const float fraction=static_cast(psmRuntimeField(self,0x22C)/duration); + const double age=static_cast(scaled)+psmInstanceA(self,0x22C); + psmInstanceA(self,0x22C)=static_cast(age); + if (age>duration) psmInstanceA(self,0x22C)=static_cast(duration); + const float fraction=static_cast(psmInstanceA(self,0x22C)/duration); const float start=static_cast(systemTemplate->getMinGasCloudRadius()*(1.0-fraction)); - psmRuntimeField(self,0x228)=static_cast(systemTemplate->getMaxGasCloudRadius()*static_cast(fraction)+start); + psmInstanceA(self,0x228)=static_cast(systemTemplate->getMaxGasCloudRadius()*static_cast(fraction)+start); + } +} + +// PE 0x10180EA0. The emit-and-refresh tail of psmType0Update without its gas-cloud step: emit, copy the +// emitter position back, pad the particle bounds by the descriptor radius (or collapse them onto the +// position when there are no particles) and recompute the bounding radius and centre. Unreachable in +// 1.50: no code or data references. The name is [CHOSEN, not recovered]. +void psmType0EmitAndRefreshBounds(void* self,float dt) +{ + psmType0Emit(self,dt); + psmInstanceA(self,0xA4)=psmInstanceA(self,0xB4); + float* bounds=&psmInstanceA(self,0xFC); + if (psmInstanceA(self,0x28)) + { + for (int i=0;i<3;++i) bounds[i]-=psmDescriptor0(psmInstanceA(self,0x2C),0x148); + for (int i=3;i<6;++i) bounds[i]+=psmDescriptor0(psmInstanceA(self,0x2C),0x148); } + else { psmInstanceA(self,0xFC)=psmInstanceA(self,0xA4); psmInstanceA(self,0x108)=psmInstanceA(self,0xA4); } + // The listing halves the x and z differences after rounding them to float and keeps the y + // difference unrounded; the squares are added z, y, x. + const float dz=bounds[5]-bounds[2]; + const float dx=static_cast((static_cast(bounds[3])-bounds[0])*0.5); + const double dy=(static_cast(bounds[4])-bounds[1])*0.5; + const double dzHalf=dz*0.5; + psmInstanceA(self,0x120)=static_cast(::sqrt(dzHalf*dzHalf+dy*dy+static_cast(dx)*dx)); + const float ySum=static_cast(static_cast(bounds[4])+bounds[1]); + const float zSum=static_cast(static_cast(bounds[5])+bounds[2]); + psmInstanceA(self,0x114)={static_cast((static_cast(bounds[3])+bounds[0])*0.5),ySum*0.5f,zSum*0.5f}; } diff --git a/Code/BF2/Geom/ParticleSystem/ParticleInstanceType1.inl b/Code/BF2/Geom/ParticleSystem/ParticleInstanceType1.inl index 74483af4b..5523c1472 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleInstanceType1.inl +++ b/Code/BF2/Geom/ParticleSystem/ParticleInstanceType1.inl @@ -18,27 +18,29 @@ static float psmType1DegreesToRadians=0.01745329238474369f; // Refreshes the instance transform unless detached: owner's visual transform, borrowed // parent transform, or the local transform when neither is available. +// PE 0x101841F0 void psmType1RefreshTransform(void* self) { - if (psmRuntimeField(self,0x18)) return; - Mat4& output=psmRuntimeField(self,0x74); - const Mat4& local=psmRuntimeField(self,0x34); - world::IObject* const owner=psmRuntimeField(self,0x10); - if (owner) output.mult(local,owner->getVisualAbsoluteTransformation()); - else if (psmRuntimeField(self,0x30)) - output.mult(local,*psmRuntimeField(self,0x30)); + if (psmInstanceB(self,0x18)) return; + Mat4& output=psmInstanceB(self,0x74); + const Mat4& local=psmInstanceB(self,0x34); + world::IObject* const owner=psmInstanceB(self,0x10); + if (owner) rendmath::mult(output,local,owner->getVisualAbsoluteTransformation()); + else if (psmInstanceB(self,0x30)) + rendmath::mult(output,local,*psmInstanceB(self,0x30)); else output=local; } class ParticleInstanceType1 : public IParticleSystemInstance { - unsigned char m_data[0x220]; - template T& at(unsigned int offset) { return psmRuntimeField(this,offset); } + unsigned char m_data[PSM_INSTANCE_DATA(0x224)]; + template T& at(unsigned int offset) { return psmInstanceB(this,offset); } template const T& at(unsigned int offset) const - { return *reinterpret_cast(reinterpret_cast(this)+offset); } + { return psmInstanceB(const_cast(this), offset); } public: // Cells it never writes (+0x06/+0x07, +0xCC/+0xD0, +0xE8..+0xF8, +0x13C/+0x140, // +0x220, the history planes' distances before the second pass) stay untouched here too. + // PE 0x10184810 explicit ParticleInstanceType1(IParticleSystemTemplate* descriptor) { at(0x18)=0; @@ -62,14 +64,29 @@ public: // emission time, unless the emission time is zero or the system loops) + 10, truncated. // NaN routing is retail's: an unordered lifetime is kept, an unordered emit time counts as // non-zero. - const float emitTime=psmRuntimeField(descriptor,0x194); - double capacityTime=static_cast(psmRuntimeField(descriptor,0x9C)) - +psmRuntimeField(descriptor,0x98); - if (emitTime!=0 && !psmRuntimeField(descriptor,0x198) && capacityTime>emitTime) + const float emitTime=psmDescriptor1(descriptor,0x194); +#if defined(__APPLE__) + // [CHOSEN, not recovered] Preserve the live x87 result and FISTP integer indefinite. + using bf2x87::wide; + bf2x87::Real capacityTime=wide(psmDescriptor1(descriptor,0x9C)) + +wide(psmDescriptor1(descriptor,0x98)); + if (emitTime!=0 && !psmDescriptor1(descriptor,0x198) && capacityTime>wide(emitTime)) + capacityTime=wide(emitTime); + at(0x218)=bf2x87::toIntTruncate(capacityTime*wide(psmDescriptor1(descriptor,0x10))+wide(10.0f)); + // shipped defect: the allocation's x86 byte count wraps at 32 bits. + // Scale that wrapped count to native pointer width, as for the ordinary array. + const unsigned int bytes=static_cast(at(0x218))*4u+4u; + at(0x14)=static_cast(::renddx9abi::engineAlloc( + static_cast(bytes/4u)*kPsmPointerSize)); +#else + double capacityTime=static_cast(psmDescriptor1(descriptor,0x9C)) + +psmDescriptor1(descriptor,0x98); + if (emitTime!=0 && !psmDescriptor1(descriptor,0x198) && capacityTime>emitTime) capacityTime=emitTime; - at(0x218)=static_cast(capacityTime*psmRuntimeField(descriptor,0x10)+10.0); + at(0x218)=static_cast(capacityTime*psmDescriptor1(descriptor,0x10)+10.0); // no allocation-failure or capacity guard, exactly as shipped. - at(0x14)=static_cast(::renddx9abi::engineAlloc(at(0x218)*4+4)); + at(0x14)=static_cast(::renddx9abi::engineAlloc(at(0x218)*kPsmPointerSize+kPsmPointerSize)); +#endif at(0x14)[0]=0; at(0x1C)={0,0,0}; at(0xFC)={0,0,0}; at(0x108)={0,0,0}; @@ -80,7 +97,7 @@ public: { at(offset)={0,1,0}; at(offset+12)=0; } // fetch the descriptor's geometry instance on first use (thiscall on the // descriptor, PE 10179080; the lookup is retried per instance while +0x8C stays null). - if (!psmRuntimeField(descriptor,0x8C)) + if (!psmDescriptor1(descriptor,0x8C)) particleSystemType1ResolveGeometry(descriptor); at(4)=0; } @@ -96,7 +113,7 @@ public: ParticleSystemManager* const manager= reinterpret_cast(g_ParticleSystemManager); float* const particle=at(0x14)[index]; - psmRuntimeField(particle,0)=manager->m_type1FreeList; + psmRecordLink(particle, 1)=manager->m_type1FreeList; manager->m_type1FreeList=particle; ++index; } while (at(0x14)[index]); @@ -105,6 +122,7 @@ public: } static void operator delete(void* self) { ::renddx9abi::engineFree(self); } int reserved01() const override { return 1; } + // PE 0x101840D0 // Stop, flush the live particles through one full-lifetime virtual update, then // hand every survivor back to the pool. Unlike type 2 it does NOT restart afterwards. void reserved02() const override @@ -115,7 +133,7 @@ public: { void* const descriptor=self->at(0x2C); self->reserved41(static_cast(static_cast( - psmRuntimeField(descriptor,0x9C))+psmRuntimeField(descriptor,0x98))); + psmDescriptor1(descriptor,0x9C))+psmDescriptor1(descriptor,0x98))); } // No count guard: a non-null head with a zero count underflows the index, as shipped. while (self->at(0x14)[0]) @@ -127,7 +145,7 @@ public: self->at(0x14)[self->at(0x28)]=0; ParticleSystemManager* const manager= reinterpret_cast(g_ParticleSystemManager); - psmRuntimeField(particle,0)=manager->m_type1FreeList; + psmRecordLink(particle, 1)=manager->m_type1FreeList; manager->m_type1FreeList=particle; } self->at(0x214)=0; @@ -143,6 +161,7 @@ public: // Quality refusal, emission timers, frame stamp, transform, first-time // classification, then the far-plane-bracketed visibility test (same shape as type 4's // 1017D810). The prewarm time is only armed (+0xEC); the frame update consumes it. + // PE 0x10184C10 void reserved03(bool firstPerson) override { // 10184C24 reads the manager's quality word before the descriptor's virtual call. @@ -151,9 +170,9 @@ public: if (at(0x2C)->getQualityLevel()>quality) return; void* const descriptor=at(0x2C); at(0x144)=1; at(0x21C)=1; - at(0xE8)=psmRuntimeField(descriptor,0x194); - at(0xF0)=psmRuntimeField(descriptor,0x1A4); - at(0xEC)=psmRuntimeField(descriptor,0x0C); + at(0xE8)=psmDescriptor1(descriptor,0x194); + at(0xF0)=psmDescriptor1(descriptor,0x1A4); + at(0xEC)=psmDescriptor1(descriptor,0x0C); at(0xF4)=0; at(0xF8)=0; at(0xD0)=0; at(0x21E)=1; at(0x21F)=1; at(0x124)=dx9rend::rendererFrameOrdinal(); @@ -161,7 +180,7 @@ public: if (!at(4)) { // an ordered `position.y < water height`; NaN reads as dry. - at(0x220)=at(0xA8)(dx9rend::g_raShaderConstants,0x1BC); + at(0x220)=at(0xA8)<*reinterpret_cast(dx9rend::raShaderConstantsAt(0x1BC)); psmAddActive(reinterpret_cast(g_ParticleSystemManager),this,firstPerson); } dx9rend::IRenderView* const view=dx9rend::rendererGetRenderViewDup(); @@ -191,9 +210,9 @@ public: void reserved08() override { at(0x18)=1; at(0x10)=0; at(0xC)=0; at(0x30)=0; } void reserved09(bool value) override { psmShared13SetVisible(this,value); } // 101839F0 shared bool reserved10() const override { return psmShared13IsVisible(this); } // 10183A00 shared - void reserved11(int value) override { at(0x10)=value; } // 1017A500 (all five) - int reserved12() const override { return at(0x10); } // 1010DE20 (all five) - void reserved13(int value) override { at(0x30)=value; } // 1017C200 (all five) + void reserved11(intptr_t value) override { at(0x10)=value; } // 1017A500 (all five) + intptr_t reserved12() const override { return at(0x10); } // 1010DE20 (all five) + void reserved13(intptr_t value) override { at(0x30)=value; } // 1017C200 (all five) void* reserved14(const void* value) override { at(0x34)=*static_cast(value); return &at(0x34); } const void* reserved15() const override { return &at(0x34); } // 10179DD0 (all five) @@ -201,7 +220,7 @@ public: void reserved16(const Vec3& value) override { const float z=value.z,y=value.y,x=value.x; at(0xD8)=y; at(0xD4)=x; at(0xDC)=z; } const Vec3& reserved17() const override { return at(0xD4); } - // the distance word is read before the normal is normalised in place. + // PE 0x10184E20: the distance word is read before the normal is normalised in place. void reserved18(const void* value) override { const float* const plane=static_cast(value); @@ -210,19 +229,24 @@ public: psmNormalize3(&at(0x200)); at(0x20C)=distance; } + // PE 0x101840B0 void reserved19(float value) override { at(0xE4)=value; } float reserved20() const override { return at(0xE4); } void reserved21(int,int) override { at(0x154)=1; } // 10183FF0, retn 8 + // PE 0x10184000 void reserved22(float value) override { at(0x158)=value; } float reserved23() const override { return at(0x158); } + // PE 0x10184020 void reserved24(float value) override { at(0x130)=value; } float reserved25() const override { return at(0x130); } void reserved26(float value) override { psmShared13SetSpeedScale(this,value); } // 10186110 shared float reserved27() const override { return psmShared13SpeedScale(this); } // 10183A10 shared void reserved28(const Vec3& value) override { psmShared13SetDirectionScale(this,value); } // 10183A30 shared const Vec3& reserved29() const override { return psmShared13DirectionScale(this); } // 10183A20 shared + // PE 0x10184040 void reserved30(float value) override { at(0x128)=value; } float reserved31() const override { return at(0x128); } + // PE 0x10184090 void reserved32(float value) override { at(0xE0)=value; } float reserved33() const override { return at(0xE0); } int reserved34() const override { return at(0x218); } @@ -240,7 +264,7 @@ public: { at(7)=value; psmReclassification(reinterpret_cast(g_ParticleSystemManager)) - .insert(reinterpret_cast(this)); + .insert(this); } } // Proven retail shared constant/null bodies: 1017A510 / 100E13B0 / 100ED3B0 / 10082D40. @@ -251,11 +275,15 @@ public: int getMaterial() const override { return -1; } // PE 101BB440 / 101BB480, shared by all five tables. void setEffectController(world::IEffectController* value) override - { at(0xC)=value; reserved11(reinterpret_cast(value ? value->getObject() : 0)); } + { at(0xC)=value; reserved11(reinterpret_cast(value ? value->getObject() : 0)); } world::IEffectController* getEffectController() const override { return at(0xC); } bool getWaterSide() const override { return at(0x220)!=0; } }; +#if defined(_M_IX86) static_assert(sizeof(ParticleInstanceType1)==0x224,"mesh particle instance PE 10184810 layout"); +#else +static_assert(sizeof(ParticleInstanceType1)==kPsmInstanceSize,"x64 instance layout, ParticleRawLayout.h"); +#endif // engine alloc 0x224, null returns null, else construct. The shared tail // (byte +5 = 0, push into manager +0x10) stays in psm_createInstance. diff --git a/Code/BF2/Geom/ParticleSystem/ParticleInstanceType1Emission.inl b/Code/BF2/Geom/ParticleSystem/ParticleInstanceType1Emission.inl index 2f1656a09..08a306d59 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleInstanceType1Emission.inl +++ b/Code/BF2/Geom/ParticleSystem/ParticleInstanceType1Emission.inl @@ -2,28 +2,44 @@ // Scales the descriptor's normalized direction by the instance's per-axis direction scale. void psmType1EmissionDirection(float* output,void* descriptor,void* self) { - output[0]=psmRuntimeField(descriptor,0x1DC)*psmRuntimeField(self,0x148); - output[1]=psmRuntimeField(descriptor,0x1E0)*psmRuntimeField(self,0x14C); - output[2]=psmRuntimeField(descriptor,0x1E4)*psmRuntimeField(self,0x150); + const float z=psmDescriptor1(descriptor,0x1E4)*psmInstanceB(self,0x150); + const float y=psmDescriptor1(descriptor,0x1E0)*psmInstanceB(self,0x14C); + const float x=psmDescriptor1(descriptor,0x1DC)*psmInstanceB(self,0x148); + output[0]=x; output[1]=y; output[2]=z; } // Five draws even when all radii are zero; radii are emitRadius (+0x14/+0x18/+0x1C). -void psmType1EmissionSphere(float* output,void* descriptor,void* self,float* particle) +// PE 0x10186160 +float* psmType1EmissionSphere(float* output,void* descriptor,void* self,float* particle) { const float phi=static_cast(psmEmissionRandomInteger()*static_cast(3.7450703871400037e-7f)); const double theta=psmEmissionRandomInteger()*static_cast(1.8725351935700019e-7f); const float savedTheta=static_cast(theta); +#if defined(__APPLE__) + // [CHOSEN, not recovered] Preserve FSIN on the retained angle before its float spill. + const float sineTheta=bf2x87::store(bf2x87::sinValue(bf2x87::wide(theta))); +#else const float sineTheta=static_cast(::sin(theta)); // fsin on the unrounded angle +#endif const float yRandom=static_cast(psmEmissionUnit()); const float xRandom=static_cast(psmEmissionUnit()); - const double zRadius=psmEmissionRandomInteger()*static_cast(psmRuntimeField(descriptor,0x1C)) + const double zRadius=psmEmissionRandomInteger()*static_cast(psmDescriptor1(descriptor,0x1C)) *0.000000059604644775390625; - const double xRadius=static_cast(xRandom)*psmRuntimeField(descriptor,0x14); - const double yRadius=static_cast(yRandom)*psmRuntimeField(descriptor,0x18); + const double xRadius=static_cast(xRandom)*psmDescriptor1(descriptor,0x14); + const double yRadius=static_cast(yRandom)*psmDescriptor1(descriptor,0x18); +#if defined(__APPLE__) + // [CHOSEN, not recovered] Keep the trig results and products live until each float store. + using bf2x87::wide; + psmRuntimeField(particle,0x44)=bf2x87::store(bf2x87::cosValue(wide(phi))*wide(xRadius)*wide(sineTheta)); + psmRuntimeField(particle,0x48)=bf2x87::store(bf2x87::sinValue(wide(phi))*wide(yRadius)*wide(sineTheta)); + psmRuntimeField(particle,0x4C)=bf2x87::store(bf2x87::cosValue(wide(savedTheta))*wide(zRadius)); +#else psmRuntimeField(particle,0x44)=static_cast(::cos(phi)*xRadius*sineTheta); psmRuntimeField(particle,0x48)=static_cast(::sin(phi)*yRadius*sineTheta); psmRuntimeField(particle,0x4C)=static_cast(::cos(savedTheta)*zRadius); +#endif psmType1EmissionDirection(output,descriptor,self); + return output; } // PE 10186290, emitter types 1 (radial) and 2. Largest-axis ties keep the earlier axis; the @@ -33,12 +49,12 @@ void psmType1EmissionSphere(float* output,void* descriptor,void* self,float* par // `axis = 0` step of the shipped largest-component search, with no observable effect. void psmType1EmissionCylinder(float* output,void* descriptor,void* self,float* particle) { - const double angle=(psmEmissionSymmetric()*psmRuntimeField(descriptor,0x5C) - +psmRuntimeField(descriptor,0x60))*static_cast(psmType1DegreesToRadians); + const double angle=(psmEmissionSymmetric()*psmDescriptor1(descriptor,0x5C) + +psmDescriptor1(descriptor,0x60))*static_cast(psmType1DegreesToRadians); const float cosine=static_cast(::cos(angle)), sine=static_cast(::sin(angle)); unsigned int axis=0; - if(psmRuntimeField(descriptor,0x18)>psmRuntimeField(descriptor,0x14))axis=1; - if(psmRuntimeField(descriptor,0x1C)>psmRuntimeField(descriptor,0x14+4*axis))axis=2; + if(psmDescriptor1(descriptor,0x18)>psmDescriptor1(descriptor,0x14))axis=1; + if(psmDescriptor1(descriptor,0x1C)>psmDescriptor1(descriptor,0x14+4*axis))axis=2; unsigned char* const bytes=static_cast(descriptor); const float z=static_cast(psmEmissionDistribution(bytes+0x48)); const float y=static_cast(psmEmissionDistribution(bytes+0x34)); @@ -47,7 +63,7 @@ void psmType1EmissionCylinder(float* output,void* descriptor,void* self,float* p if(axis==0){position[0]=static_cast(x);position[1]=y*sine;position[2]=z*cosine;} else if(axis==1){position[0]=static_cast(x*sine);position[1]=y;position[2]=z*cosine;} else{position[0]=static_cast(x*sine);position[1]=y*cosine;position[2]=z;} - if(psmRuntimeField(descriptor,0x214)==1) + if(psmDescriptor1(descriptor,0x214)==1) { // Radial: the emitted offset with the cylinder axis zeroed, normalised in place. output[0]=position[0];output[1]=position[1];output[2]=position[2]; @@ -58,7 +74,8 @@ void psmType1EmissionCylinder(float* output,void* descriptor,void* self,float* p } // Z, Y, X distributions, then the configured direction. -void psmType1EmissionBox(float* output,void* descriptor,void* self,float* particle) +// PE 0x10186480 +float* psmType1EmissionBox(float* output,void* descriptor,void* self,float* particle) { unsigned char* const bytes=static_cast(descriptor); const float z=static_cast(psmEmissionDistribution(bytes+0x48)); @@ -66,6 +83,46 @@ void psmType1EmissionBox(float* output,void* descriptor,void* self,float* partic psmRuntimeField(particle,0x44)=static_cast(psmEmissionDistribution(bytes+0x20)); psmRuntimeField(particle,0x48)=y;psmRuntimeField(particle,0x4C)=z; psmType1EmissionDirection(output,descriptor,self); + return output; +} + +// [INFERRED] Private names/placement for the existing rotation-and-copy sequences. +// PE 0x1017C280 +void psmType1RotateY(Mat4& matrix,float degrees) +{ + Mat4 rotation=Mat4::getIdentity(); + psmEmissionRotation(rotation,degrees,1); + const Mat4 copy=matrix; + rendmath::rotMult(matrix,copy,rotation); // PE 10078180 +} + +// PE 0x10079500 +void psmType1RotateZ(Mat4& matrix,float degrees) +{ + Mat4 rotation=Mat4::getIdentity(); + rendmath::setRotateZDeg(rotation,degrees); // PE 10077EC0 + const Mat4 copy=matrix; + rendmath::rotMult(matrix,copy,rotation); // PE 10078180 +} + +// [INFERRED] Private name/placement for the existing in-place direction transform. +// PE 0x100A6120 +void psmType1TransformDirection(const Mat4& matrix,float* direction) +{ + const float x=direction[0],y=direction[1],z=direction[2]; +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain all three x87 sums before writing the input vector. + using bf2x87::wide; + const bf2x87::Real rz=wide(matrix.m[10])*wide(z)+wide(matrix.m[2])*wide(x)+wide(matrix.m[6])*wide(y); + const bf2x87::Real ry=wide(matrix.m[9])*wide(z)+wide(matrix.m[1])*wide(x)+wide(matrix.m[5])*wide(y); + const bf2x87::Real rx=wide(matrix.m[8])*wide(z)+wide(matrix.m[4])*wide(y)+wide(x)*wide(matrix.m[0]); + direction[0]=bf2x87::store(rx); direction[1]=bf2x87::store(ry); direction[2]=bf2x87::store(rz); +#else + const double rz=static_cast(matrix.m[10])*z+static_cast(matrix.m[2])*x+static_cast(matrix.m[6])*y; + const double ry=static_cast(matrix.m[9])*z+static_cast(matrix.m[1])*x+static_cast(matrix.m[5])*y; + const double rx=static_cast(matrix.m[8])*z+static_cast(matrix.m[4])*y+static_cast(x)*matrix.m[0]; + direction[0]=static_cast(rx); direction[1]=static_cast(ry); direction[2]=static_cast(rz); +#endif } // PE 101857D0 (table +0x94, void) and its inlined twin inside 10184F00. The inline copy continues @@ -77,34 +134,34 @@ float* psmType1NewParticle(void* self, bool inlinedCopy) { ParticleSystemManager* const manager=reinterpret_cast(g_ParticleSystemManager); float* const particle=static_cast(manager->m_type1FreeList); - manager->m_type1FreeList=particle ? psmRuntimeField(particle,0) : 0; + manager->m_type1FreeList=particle ? psmRecordLink(particle, 1) : 0; if(!particle)return 0; - ++psmRuntimeField(self,0x13C); - void* descriptor=psmRuntimeField(self,0x2C); + ++psmInstanceB(self,0x13C); + void* descriptor=psmInstanceB(self,0x2C); // Lifetime = TTL (+0x9C) + unit * randomTTL (+0x98); the reciprocal divides the unrounded sum. - const double lifetime=psmEmissionRandomInteger()*static_cast(psmRuntimeField(descriptor,0x98)) - *0.000000059604644775390625+psmRuntimeField(descriptor,0x9C); + const double lifetime=psmEmissionRandomInteger()*static_cast(psmDescriptor1(descriptor,0x98)) + *0.000000059604644775390625+psmDescriptor1(descriptor,0x9C); psmRuntimeField(particle,0x94)=static_cast(lifetime); psmRuntimeField(particle,0x98)=static_cast(1.0/lifetime); - psmRuntimeField(particle,0x90)=psmRuntimeField(self,0xE0); - psmRuntimeField(particle,0x5C)=psmRuntimeField(self,0xE0)*psmRuntimeField(particle,0x98); + psmRuntimeField(particle,0x90)=psmInstanceB(self,0xE0); + psmRuntimeField(particle,0x5C)=psmInstanceB(self,0xE0)*psmRuntimeField(particle,0x98); // Plain dword moves in the PE (10185864..10185882). - psmRuntimeField(particle,0x74)=psmRuntimeField(self,0x154); - psmRuntimeField(particle,0x6C)=psmRuntimeField(self,0x158); - psmRuntimeField(particle,0x70)=psmRuntimeField(self,0x158); - psmRuntimeField(particle,0xB4)=psmRuntimeField(psmRuntimeField(self,0x2C),0xC8); + psmRuntimeField(particle,0x74)=psmInstanceB(self,0x154); + psmRuntimeField(particle,0x6C)=psmInstanceB(self,0x158); + psmRuntimeField(particle,0x70)=psmInstanceB(self,0x158); + psmRuntimeField(particle,0xB4)=psmDescriptor1(psmInstanceB(self,0x2C),0xC8); // The first symmetric draw is kept as a float: it scales the size jitter now and the speed below. const float firstRandom=static_cast(psmEmissionSymmetric()); - psmRuntimeField(particle,0x68)=firstRandom*psmRuntimeField(psmRuntimeField(self,0x2C),0x16C); + psmRuntimeField(particle,0x68)=firstRandom*psmDescriptor1(psmInstanceB(self,0x2C),0x16C); psmRuntimeField(particle,0x78)=static_cast(psmEmissionSymmetric() - *psmRuntimeField(psmRuntimeField(self,0x2C),0x170)); + *psmDescriptor1(psmInstanceB(self,0x2C),0x170)); { // One draw scales all three randomRotation components (+0x174); stored z, x, y. const double shared=psmEmissionSymmetric(); - void* const d=psmRuntimeField(self,0x2C); - const double spinX=shared*psmRuntimeField(d,0x174); - const double spinY=shared*psmRuntimeField(d,0x178); - psmRuntimeField(particle,0xB0)=static_cast(shared*psmRuntimeField(d,0x17C)); + void* const d=psmInstanceB(self,0x2C); + const double spinX=shared*psmDescriptor1(d,0x174); + const double spinY=shared*psmDescriptor1(d,0x178); + psmRuntimeField(particle,0xB0)=static_cast(shared*psmDescriptor1(d,0x17C)); psmRuntimeField(particle,0xA8)=static_cast(spinX); psmRuntimeField(particle,0xAC)=static_cast(spinY); } @@ -113,30 +170,30 @@ float* psmType1NewParticle(void* self, bool inlinedCopy) // 1018596D tests the draw with `test ah,1`, so an unordered value would take the minus // arm. The X product stays unrounded; Y and Z are rounded before the base is applied. const float draw=static_cast(psmEmissionSymmetric()); - void* const d=psmRuntimeField(self,0x2C); - const double productX=static_cast(draw)*psmRuntimeField(d,0xAC); - const float productY=static_cast(static_cast(draw)*psmRuntimeField(d,0xB0)); - const float productZ=static_cast(static_cast(draw)*psmRuntimeField(d,0xB4)); + void* const d=psmInstanceB(self,0x2C); + const double productX=static_cast(draw)*psmDescriptor1(d,0xAC); + const float productY=static_cast(static_cast(draw)*psmDescriptor1(d,0xB0)); + const float productZ=static_cast(static_cast(draw)*psmDescriptor1(d,0xB4)); double rateX,rateY,rateZ; if(!(draw>=0)) { - rateX=productX+static_cast(-psmRuntimeField(d,0xB8)); - rateY=static_cast(-psmRuntimeField(d,0xBC))+productY; - rateZ=static_cast(-psmRuntimeField(d,0xC0))+productZ; + rateX=productX+static_cast(-psmDescriptor1(d,0xB8)); + rateY=static_cast(-psmDescriptor1(d,0xBC))+productY; + rateZ=static_cast(-psmDescriptor1(d,0xC0))+productZ; } else { - rateX=productX+psmRuntimeField(d,0xB8); - rateY=static_cast(productY)+psmRuntimeField(d,0xBC); - rateZ=static_cast(productZ)+psmRuntimeField(d,0xC0); + rateX=productX+psmDescriptor1(d,0xB8); + rateY=static_cast(productY)+psmDescriptor1(d,0xBC); + rateZ=static_cast(productZ)+psmDescriptor1(d,0xC0); } psmRuntimeField(particle,0xA4)=static_cast(rateZ); psmRuntimeField(particle,0x9C)=static_cast(rateX); psmRuntimeField(particle,0xA0)=static_cast(rateY); } float direction[3]={0,0,0}; - descriptor=psmRuntimeField(self,0x2C); - switch(psmRuntimeField(descriptor,0x214)) + descriptor=psmInstanceB(self,0x2C); + switch(psmDescriptor1(descriptor,0x214)) { case 0:psmType1EmissionSphere(direction,descriptor,self,particle);break; case 1:case 2:psmType1EmissionCylinder(direction,descriptor,self,particle);break; @@ -147,13 +204,11 @@ float* psmType1NewParticle(void* self, bool inlinedCopy) const float randomX=static_cast(psmEmissionSymmetric()); const float randomY=static_cast(psmEmissionSymmetric()); const float randomZ=static_cast(psmEmissionSymmetric()); - descriptor=psmRuntimeField(self,0x2C); - Mat4 rotation,axis,copy; - psmEmissionRotation(rotation,randomX*psmRuntimeField(descriptor,0x184),0); - psmEmissionRotation(axis,randomY*psmRuntimeField(psmRuntimeField(self,0x2C),0x188),1); - copy=rotation;psmEmissionRotateMultiply(rotation,copy,axis); - psmEmissionRotation(axis,randomZ*psmRuntimeField(psmRuntimeField(self,0x2C),0x18C),2); - copy=rotation;psmEmissionRotateMultiply(rotation,copy,axis); + descriptor=psmInstanceB(self,0x2C); + Mat4 rotation; + psmEmissionRotation(rotation,randomX*psmDescriptor1(descriptor,0x184),0); + psmType1RotateY(rotation,randomY*psmDescriptor1(psmInstanceB(self,0x2C),0x188)); + psmType1RotateZ(rotation,randomZ*psmDescriptor1(psmInstanceB(self,0x2C),0x18C)); const float x=direction[0],y=direction[1],z=direction[2]; const double m0x=static_cast(rotation.m[0])*x, m4y=static_cast(rotation.m[4])*y, m8z=static_cast(rotation.m[8])*z, m1x=static_cast(rotation.m[1])*x, @@ -177,35 +232,32 @@ float* psmType1NewParticle(void* self, bool inlinedCopy) // Speed = (emitSpeed +0x190 - first draw * randomSpeed +0x180) * instance speed scale +0x138, // then scaled by the clamped emitSpeedGraph (+0x15C t^3, +0x160 t^2, +0x164 t, +0x168 const) // at t = 1 - timeLeft/emitTime (0 when emitTime is not an ordered positive number). - descriptor=psmRuntimeField(self,0x2C); - float speed=static_cast((psmRuntimeField(descriptor,0x190) - -static_cast(firstRandom)*psmRuntimeField(descriptor,0x180))*psmRuntimeField(self,0x138)); - const float emitTime=psmRuntimeField(descriptor,0x194); - const double t=emitTime>0?1.0-static_cast(psmRuntimeField(self,0xE8))/emitTime:0; - const float envelope=static_cast(t*t*psmRuntimeField(descriptor,0x160) - +t*psmRuntimeField(descriptor,0x164)+t*t*t*psmRuntimeField(descriptor,0x15C) - +psmRuntimeField(descriptor,0x168)); + descriptor=psmInstanceB(self,0x2C); + float speed=static_cast((psmDescriptor1(descriptor,0x190) + -static_cast(firstRandom)*psmDescriptor1(descriptor,0x180))*psmInstanceB(self,0x138)); + const float emitTime=psmDescriptor1(descriptor,0x194); + const double t=emitTime>0?1.0-static_cast(psmInstanceB(self,0xE8))/emitTime:0; + const float envelope=static_cast(t*t*psmDescriptor1(descriptor,0x160) + +t*psmDescriptor1(descriptor,0x164)+t*t*t*psmDescriptor1(descriptor,0x15C) + +psmDescriptor1(descriptor,0x168)); speed*=psmEmissionClamp(envelope); - if(!psmRuntimeField(psmRuntimeField(self,0x2C),0x1F1)) + if(!psmDescriptor1(psmInstanceB(self,0x2C),0x1F1)) { // World system: PE 10079610 moves the emitted offset through the world matrix in place, // PE 100A6120 rotates the direction, then the owner's inherited velocity is added. - const float* const matrix=psmRuntimeField(self,0x74).m; + const float* const matrix=psmInstanceB(self,0x74).m; float* const position=&psmRuntimeField(particle,0x44); const float px=position[0],py=position[1],pz=position[2]; const double worldZ=static_cast(matrix[2])*px+static_cast(matrix[10])*pz+static_cast(matrix[6])*py+matrix[14]; const double worldY=static_cast(matrix[1])*px+static_cast(matrix[9])*pz+static_cast(matrix[5])*py+matrix[13]; const double worldX=static_cast(matrix[8])*pz+static_cast(matrix[4])*py+static_cast(px)*matrix[0]+matrix[12]; position[0]=static_cast(worldX);position[1]=static_cast(worldY);position[2]=static_cast(worldZ); - const float dx=direction[0],dy=direction[1],dz=direction[2]; - direction[2]=static_cast(static_cast(matrix[10])*dz+static_cast(matrix[2])*dx+static_cast(matrix[6])*dy); - direction[1]=static_cast(static_cast(matrix[9])*dz+static_cast(matrix[1])*dx+static_cast(matrix[5])*dy); - direction[0]=static_cast(static_cast(matrix[8])*dz+static_cast(matrix[4])*dy+static_cast(dx)*matrix[0]); - const double scale=psmRuntimeField(self,0xE4); - const float inheritedX=static_cast(scale*psmRuntimeField(self,0xD4)); - const float inheritedY=static_cast(scale*psmRuntimeField(self,0xD8)); + psmType1TransformDirection(psmInstanceB(self,0x74),direction); + const double scale=psmInstanceB(self,0xE4); + const float inheritedX=static_cast(scale*psmInstanceB(self,0xD4)); + const float inheritedY=static_cast(scale*psmInstanceB(self,0xD8)); const float velocityY=direction[1]*speed,velocityZ=direction[2]*speed; - psmRuntimeField(particle,0x8C)=static_cast(velocityZ+scale*psmRuntimeField(self,0xDC)); + psmRuntimeField(particle,0x8C)=static_cast(velocityZ+scale*psmInstanceB(self,0xDC)); psmRuntimeField(particle,0x84)=static_cast(static_cast(direction[0])*speed+inheritedX); psmRuntimeField(particle,0x88)=velocityY+inheritedY; } @@ -216,9 +268,9 @@ float* psmType1NewParticle(void* self, bool inlinedCopy) psmRuntimeField(particle,0x84)=direction[0]*speed; psmRuntimeField(particle,0x88)=direction[1]*speed; } - float** const list=psmRuntimeField(self,0x14); - list[psmRuntimeField(self,0x28)++]=particle; - psmRuntimeField(self,0x14)[psmRuntimeField(self,0x28)]=0; + float** const list=psmInstanceB(self,0x14); + list[psmInstanceB(self,0x28)++]=particle; + psmInstanceB(self,0x14)[psmInstanceB(self,0x28)]=0; return particle; } @@ -227,76 +279,76 @@ float* psmType1NewParticle(void* self, bool inlinedCopy) // previous to the current emitter position, each new particle catching up to "now". void psmType1Emit(void* self,float /*dt*/) { - if(!psmRuntimeField(self,0x144))return; + if(!psmInstanceB(self,0x144))return; const unsigned int frame=dx9rend::rendererFrameOrdinal(); - if(psmRuntimeField(self,0x124)+60u(self,0x124)+60u(self,0x21F)=psmRuntimeField(self,0x21E); - psmRuntimeField(self,0x21E)=0;return; + psmInstanceB(self,0x21F)=psmInstanceB(self,0x21E); + psmInstanceB(self,0x21E)=0;return; } - void* const descriptor=psmRuntimeField(self,0x2C); + void* const descriptor=psmInstanceB(self,0x2C); // Descriptor +0xE4 (0.05 from the type-1 defaults, no setter slot) floors both scales. - if(psmRuntimeField(self,0x12C)(descriptor,0xE4)) - psmRuntimeField(self,0x12C)=psmRuntimeField(descriptor,0xE4); - if(psmRuntimeField(self,0x130)(descriptor,0xE4)) - psmRuntimeField(self,0x130)=psmRuntimeField(descriptor,0xE4); - double frequency=static_cast(psmRuntimeField(descriptor,0x10)) - *psmRuntimeField(self,0x12C)*psmRuntimeField(self,0x130); + if(psmInstanceB(self,0x12C)(descriptor,0xE4)) + psmInstanceB(self,0x12C)=psmDescriptor1(descriptor,0xE4); + if(psmInstanceB(self,0x130)(descriptor,0xE4)) + psmInstanceB(self,0x130)=psmDescriptor1(descriptor,0xE4); + double frequency=static_cast(psmDescriptor1(descriptor,0x10)) + *psmInstanceB(self,0x12C)*psmInstanceB(self,0x130); // Manager +0x7B48 = MeshParticlesRenderer +0x1C18, the over-budget byte its prepare (10174DA0) // writes last; descriptor +0x1A0 is the emit-priority scale (0.5 / 0.7 / 1.0) that the // descriptor's refreshDerivedState derives from +0x64. There is no minimum-frequency clamp here. if(reinterpret_cast(g_ParticleSystemManager)->m_meshParticlesRenderer[0x1C18]) - frequency*=psmRuntimeField(descriptor,0x1A0); + frequency*=psmDescriptor1(descriptor,0x1A0); const float interval=static_cast(1.0/frequency); - if(psmRuntimeField(self,0x21C)) - {psmRuntimeField(self,0xC0)=psmRuntimeField(self,0xB4);psmRuntimeField(self,0x21C)=0;} + if(psmInstanceB(self,0x21C)) + {psmInstanceB(self,0xC0)=psmInstanceB(self,0xB4);psmInstanceB(self,0x21C)=0;} IParticleSystemInstance* const instance=static_cast(self); - while(static_cast(interval)+psmRuntimeField(self,0xF8)<=psmRuntimeField(self,0xF4)) + while(static_cast(interval)+psmInstanceB(self,0xF8)<=psmInstanceB(self,0xF4)) { - if(psmRuntimeField(self,0xE8)!=0) + if(psmInstanceB(self,0xE8)!=0) { - const double remaining=static_cast(psmRuntimeField(self,0xE8))-interval; - psmRuntimeField(self,0xE8)=static_cast(remaining); + const double remaining=static_cast(psmInstanceB(self,0xE8))-interval; + psmInstanceB(self,0xE8)=static_cast(remaining); if(remaining<=0) { instance->reserved04(); - if(psmRuntimeField(psmRuntimeField(self,0x2C),0x198)) - instance->reserved03(psmRuntimeField(self,6)!=0); + if(psmDescriptor1(psmInstanceB(self,0x2C),0x198)) + instance->reserved03(psmInstanceB(self,6)!=0); return; } } - const float next=static_cast(static_cast(interval)+psmRuntimeField(self,0xF8)); - psmRuntimeField(self,0xF8)=next; - if(psmRuntimeField(self,0x21E) - &&psmRuntimeField(self,0x28)(self,0x218)) + const float next=static_cast(static_cast(interval)+psmInstanceB(self,0xF8)); + psmInstanceB(self,0xF8)=next; + if(psmInstanceB(self,0x21E) + &&psmInstanceB(self,0x28)(self,0x218)) { float fraction=0; - if(psmRuntimeField(self,0xF4)>psmRuntimeField(self,0xCC)) - fraction=static_cast((static_cast(next)-psmRuntimeField(self,0xCC)) - /(static_cast(psmRuntimeField(self,0xF4))-psmRuntimeField(self,0xCC))); + if(psmInstanceB(self,0xF4)>psmInstanceB(self,0xCC)) + fraction=static_cast((static_cast(next)-psmInstanceB(self,0xCC)) + /(static_cast(psmInstanceB(self,0xF4))-psmInstanceB(self,0xCC))); // previous (+0xC0) towards current (+0xB4); Y keeps the unrounded product. - const Vec3& from=psmRuntimeField(self,0xC0); - const Vec3& to=psmRuntimeField(self,0xB4); + const Vec3& from=psmInstanceB(self,0xC0); + const Vec3& to=psmInstanceB(self,0xB4); const float zDifference=to.z-from.z; const float xScaled=static_cast((static_cast(to.x)-from.x)*fraction); const double yScaled=(static_cast(to.y)-from.y)*fraction; const float zScaled=zDifference*fraction; - psmRuntimeField(self,0xA4)={xScaled+from.x,static_cast(yScaled+from.y),zScaled+from.z}; + psmInstanceB(self,0xA4)={xScaled+from.x,static_cast(yScaled+from.y),zScaled+from.z}; float* const particle=psmType1NewParticle(self,true); // the inlined copy's sums if(particle) { // Added emission velocity (+0x1C, shared slot +0x90); no 0.001 snap on this type. - psmRuntimeField(particle,0x84)=psmRuntimeField(self,0x1C)+psmRuntimeField(particle,0x84); - psmRuntimeField(particle,0x88)=psmRuntimeField(self,0x20)+psmRuntimeField(particle,0x88); - psmRuntimeField(particle,0x8C)=psmRuntimeField(self,0x24)+psmRuntimeField(particle,0x8C); + psmRuntimeField(particle,0x84)=psmInstanceB(self,0x1C)+psmRuntimeField(particle,0x84); + psmRuntimeField(particle,0x88)=psmInstanceB(self,0x20)+psmRuntimeField(particle,0x88); + psmRuntimeField(particle,0x8C)=psmInstanceB(self,0x24)+psmRuntimeField(particle,0x8C); const unsigned int steps=static_cast(static_cast( - (static_cast(psmRuntimeField(self,0xF4))-psmRuntimeField(self,0xF8))*100.0)); - if(psmType1AdvanceParticle(self,particle,static_cast(psmRuntimeField(self,0x28)-1u), + (static_cast(psmInstanceB(self,0xF4))-psmInstanceB(self,0xF8))*100.0)); + if(psmType1AdvanceParticle(self,particle,static_cast(psmInstanceB(self,0x28)-1u), psmType1FixedStep,steps)) { - const float remainder=static_cast((static_cast(psmRuntimeField(self,0xF4)) - -psmRuntimeField(self,0xF8))-static_cast(steps)*psmType1FixedStep); - psmType1AdvanceParticle(self,particle,static_cast(psmRuntimeField(self,0x28)-1u), + const float remainder=static_cast((static_cast(psmInstanceB(self,0xF4)) + -psmInstanceB(self,0xF8))-static_cast(steps)*psmType1FixedStep); + psmType1AdvanceParticle(self,particle,static_cast(psmInstanceB(self,0x28)-1u), remainder,1); } } diff --git a/Code/BF2/Geom/ParticleSystem/ParticleInstanceType1Update.inl b/Code/BF2/Geom/ParticleSystem/ParticleInstanceType1Update.inl index 3b8e50d13..8530cb0ae 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleInstanceType1Update.inl +++ b/Code/BF2/Geom/ParticleSystem/ParticleInstanceType1Update.inl @@ -1,20 +1,32 @@ // Mesh-particle integration uses 0.01-second steps and reevaluates gravity each step. // Collision history rotates unless the clock is strictly below one third; NaN rotates it. +// PE 0x10184E60 void psmType1RememberPlane(void* self) { - if (psmRuntimeField(self,0x214)<0.33333001f) return; - const unsigned char next=psmRuntimeField(self,0x211); - psmRuntimeField(self,0x210)=next; - psmRuntimeField(self,0x214)=static_cast( - static_cast(psmRuntimeField(self,0x214))-0.33333001f); - const float* const source=&psmRuntimeField(self,0x200); + if (psmInstanceB(self,0x214)<0.33333001f) return; + const unsigned char next=psmInstanceB(self,0x211); + psmInstanceB(self,0x210)=next; + psmInstanceB(self,0x214)=static_cast( + static_cast(psmInstanceB(self,0x214))-0.33333001f); + const float* const source=&psmInstanceB(self,0x200); const float distance=source[3]; - float* const target=&psmRuntimeField(self,0x160+16u*next); + float* const target=&psmInstanceB(self,0x160+16u*next); target[0]=source[0]; target[1]=source[1]; target[2]=source[2]; psmNormalize3(target); target[3]=distance; - psmRuntimeField(self,0x211)= - static_cast((psmRuntimeField(self,0x211)+1)%10); + psmInstanceB(self,0x211)= + static_cast((psmInstanceB(self,0x211)+1)%10); +} + +// [INFERRED] Private name/placement for the bounds endpoint assignment already inlined below. +// PE 0x1017C250 +void psmType1SetBounds(float* bounds,const Vec3& low,const Vec3& high) +{ + const float lowZ=low.z,lowY=low.y,lowX=low.x; + bounds[1]=lowY; bounds[0]=lowX; bounds[2]=lowZ; + // Retail reads the second endpoint after publishing the first. + const float highX=high.x,highZ=high.z,highY=high.y; + bounds[3]=highX; bounds[4]=highY; bounds[5]=highZ; } // PE 10184270, __thiscall (particle, index, step, steps), retn 10h. Returns 0 when the particle @@ -26,42 +38,42 @@ int psmType1AdvanceParticle(void* self,float* particle,int index,float step,unsi const double tentativeAge=static_cast(steps)*step+psmRuntimeField(particle,0x90); if (tentativeAge>=psmRuntimeField(particle,0x94)) { - float** const array=psmRuntimeField(self,0x14); - const unsigned int last=--psmRuntimeField(self,0x28); + float** const array=psmInstanceB(self,0x14); + const unsigned int last=--psmInstanceB(self,0x28); array[index]=array[last]; - psmRuntimeField(self,0x14)[psmRuntimeField(self,0x28)]=0; + psmInstanceB(self,0x14)[psmInstanceB(self,0x28)]=0; ParticleSystemManager* const manager=reinterpret_cast(g_ParticleSystemManager); - psmRuntimeField(particle,0)=manager->m_type1FreeList; + psmRecordLink(particle, 1)=manager->m_type1FreeList; manager->m_type1FreeList=particle; - ++psmRuntimeField(self,0x140); + ++psmInstanceB(self,0x140); return 0; } - void* descriptor=psmRuntimeField(self,0x2C); + void* descriptor=psmInstanceB(self,0x2C); float windX=0, windY=0, windZ=0; - if (!psmRuntimeField(descriptor,0x1F1) && psmRuntimeField(descriptor,0xCC)>0) + if (!psmDescriptor1(descriptor,0x1F1) && psmDescriptor1(descriptor,0xCC)>0) { ParticleSystemManager* const manager=reinterpret_cast(g_ParticleSystemManager); const Vec3 wind=reinterpret_cast(manager->m_windManager)->getWind( psmRuntimeField(particle,0x44)); windX=wind.x; windY=wind.y; windZ=wind.z; } - descriptor=psmRuntimeField(self,0x2C); + descriptor=psmInstanceB(self,0x2C); // 10184341..1018436A scale even the zero (no-wind) vector: a NaN or infinite affection // factor still turns the wind terms into NaN here, unlike the sprite integrator. - const float affection=psmRuntimeField(descriptor,0xCC); + const float affection=psmDescriptor1(descriptor,0xCC); const float windXScaled=static_cast(static_cast(affection)*windX); const float windYScaled=static_cast(static_cast(windY)*affection); const float windZScaled=static_cast(static_cast(windZ)*affection); - const float gravityStep=static_cast(static_cast(step)*psmRuntimeField(descriptor,0xA4)); + const float gravityStep=static_cast(static_cast(step)*psmDescriptor1(descriptor,0xA4)); // Air-resistance graph (+0x11C t^3, +0x120 t^2, +0x124 t, +0x128 constant) at the particle's // current age fraction, once per call. t^2/t^3 stay unrounded on the x87 stack. const double t=psmRuntimeField(particle,0x5C); - const float dragCurve=static_cast(t*t*psmRuntimeField(descriptor,0x120) - +t*psmRuntimeField(descriptor,0x124)+t*t*t*psmRuntimeField(descriptor,0x11C) - +psmRuntimeField(descriptor,0x128)); + const float dragCurve=static_cast(t*t*psmDescriptor1(descriptor,0x120) + +t*psmDescriptor1(descriptor,0x124)+t*t*t*psmDescriptor1(descriptor,0x11C) + +psmDescriptor1(descriptor,0x128)); const float drag=static_cast(static_cast(psmEmissionClamp(dragCurve)) - *psmRuntimeField(psmRuntimeField(self,0x2C),0xA8)*step); + *psmDescriptor1(psmInstanceB(self,0x2C),0xA8)*step); for (unsigned int remaining=steps;remaining!=0;--remaining) { @@ -71,11 +83,11 @@ int psmType1AdvanceParticle(void* self,float* particle,int index,float step,unsi const double fraction=age*psmRuntimeField(particle,0x98); psmRuntimeField(particle,0x5C)=static_cast(fraction); // Gravity graph (+0x10C t^3, +0x110 t^2, +0x114 t, +0x118 constant), descriptor re-read. - void* const graphOwner=psmRuntimeField(self,0x2C); - const float gravityCurve=static_cast(fraction*fraction*psmRuntimeField(graphOwner,0x110) - +fraction*psmRuntimeField(graphOwner,0x114) - +fraction*fraction*fraction*psmRuntimeField(graphOwner,0x10C) - +psmRuntimeField(graphOwner,0x118)); + void* const graphOwner=psmInstanceB(self,0x2C); + const float gravityCurve=static_cast(fraction*fraction*psmDescriptor1(graphOwner,0x110) + +fraction*psmDescriptor1(graphOwner,0x114) + +fraction*fraction*fraction*psmDescriptor1(graphOwner,0x10C) + +psmDescriptor1(graphOwner,0x118)); const float gravity=static_cast(static_cast(psmEmissionClamp(gravityCurve))*gravityStep); float relative[3]={ static_cast(static_cast(psmRuntimeField(particle,0x84))-windXScaled), @@ -107,25 +119,29 @@ int psmType1AdvanceParticle(void* self,float* particle,int index,float step,unsi psmRuntimeField(particle,0x8C)=static_cast(accelZ+psmRuntimeField(particle,0x8C)); } - descriptor=psmRuntimeField(self,0x2C); - if (psmRuntimeField(descriptor,0xEC)) + descriptor=psmInstanceB(self,0x2C); + if (psmDescriptor1(descriptor,0xEC)) { // 10184551..101845CB. `test ah,1` routes an unordered difference into the negative arm, // where fistp yields 0x80000000; the index arithmetic is 32-bit wraparound throughout, // including the address (+0x16)<<4. Retail has no range check on the resulting plane. - const unsigned char current=psmRuntimeField(self,0x210); - const double difference=static_cast(psmRuntimeField(self,0x214)) + const unsigned char current=psmInstanceB(self,0x210); + const double difference=static_cast(psmInstanceB(self,0x214)) -psmRuntimeField(particle,0x90); unsigned int selected=current; if (!(difference>=0)) { +#if defined(__APPLE__) + selected=current-static_cast(bf2x87::toIntTruncate(-3.0*difference))-1u; +#else selected=current-static_cast(static_cast(-3.0*difference))-1u; +#endif if (static_cast(selected)<0) selected+=10u*((0xFFFFFFFFu-selected)/10u)+10u; } const float* const plane=selected==current - ? &psmRuntimeField(self,0x200) - : reinterpret_cast(reinterpret_cast(self)+((selected+0x16u)<<4)); + ? &psmInstanceB(self,0x200) + : reinterpret_cast(reinterpret_cast(self)+((selected+0x16u)<<4)); const double velocityDot=static_cast(psmRuntimeField(particle,0x8C))*plane[2] +static_cast(psmRuntimeField(particle,0x88))*plane[1] +static_cast(plane[0])*psmRuntimeField(particle,0x84); @@ -146,8 +162,8 @@ int psmType1AdvanceParticle(void* self,float* particle,int index,float step,unsi +static_cast(plane[0])*psmRuntimeField(particle,0x84); if (reflected<0) { - void* const collision=psmRuntimeField(self,0x2C); - const float normalFactor=psmRuntimeField(collision,0xF0); + void* const collision=psmInstanceB(self,0x2C); + const float normalFactor=psmDescriptor1(collision,0xF0); const double normalX=reflected*plane[0], normalY=reflected*plane[1]; const float normalZ=static_cast(reflected*plane[2]); const float tangentX=static_cast(psmRuntimeField(particle,0x84)-normalX); @@ -156,7 +172,7 @@ int psmType1AdvanceParticle(void* self,float* particle,int index,float step,unsi const float bounceX=static_cast(normalX*normalFactor); const float bounceY=static_cast(normalY*normalFactor); const double bounceZ=static_cast(normalZ)*normalFactor; - const float along=psmRuntimeField(collision,0xF4); + const float along=psmDescriptor1(collision,0xF4); const float slideX=static_cast(static_cast(tangentX)*along); const float slideY=static_cast(static_cast(tangentY)*along); const float slideZ=static_cast(static_cast(tangentZ)*along); @@ -172,9 +188,9 @@ int psmType1AdvanceParticle(void* self,float* particle,int index,float step,unsi // the world position. reinterpret_cast(particle)[0x60]|=0x80; psmRuntimeField(particle,0x50)=psmRuntimeField(particle,0x44); - if (psmRuntimeField(psmRuntimeField(self,0x2C),0x1F1)) + if (psmDescriptor1(psmInstanceB(self,0x2C),0x1F1)) { - const float* const m=&psmRuntimeField(self,0x74); + const float* const m=&psmInstanceB(self,0x74); const float x=psmRuntimeField(particle,0x50); const float y=psmRuntimeField(particle,0x54); const float z=psmRuntimeField(particle,0x58); @@ -186,13 +202,13 @@ int psmType1AdvanceParticle(void* self,float* particle,int index,float step,unsi psmRuntimeField(particle,0x58)=static_cast(worldZ); } ParticleSystemManager* const manager=reinterpret_cast(g_ParticleSystemManager); - if (psmRuntimeField(psmRuntimeField(self,0x2C),0xD0) && manager->m_heightmapCluster) + if (psmDescriptor1(psmInstanceB(self,0x2C),0xD0) && manager->m_heightmapCluster) psmRuntimeField(particle,0x54)=static_cast(static_cast( reinterpret_cast(manager->m_heightmapCluster) ->getWaterLevelInWorldCoords(psmRuntimeField(particle,0x50))) - +psmRuntimeField(psmRuntimeField(self,0x2C),0xD4)); + +psmDescriptor1(psmInstanceB(self,0x2C),0xD4)); // ordered extrema, x max/min, then y, then z; NaN updates nothing. - float* const bounds=&psmRuntimeField(self,0xFC); + float* const bounds=&psmInstanceB(self,0xFC); for (int i=0;i<3;++i) { const float value=psmRuntimeField(particle,0x50+4u*i); @@ -206,57 +222,57 @@ int psmType1AdvanceParticle(void* self,float* particle,int index,float step,unsi void psmType1Update(void* self,float dt) { IParticleSystemInstance* const instance=static_cast(self); - float elapsed=static_cast(static_cast(dt)*psmRuntimeField(self,0x128)); - psmRuntimeField(psmRuntimeField(self,0x2C),8)=-1; - if (!psmRuntimeField(self,0x28) && !psmRuntimeField(self,0x144)) + float elapsed=static_cast(static_cast(dt)*psmInstanceB(self,0x128)); + psmDescriptor1(psmInstanceB(self,0x2C),8)=-1; + if (!psmInstanceB(self,0x28) && !psmInstanceB(self,0x144)) { psmQueueInactive(reinterpret_cast(g_ParticleSystemManager),instance); - if (psmRuntimeField(self,0x18)) + if (psmInstanceB(self,0x18)) reinterpret_cast(g_ParticleSystemManager)->removeInstance(instance); return; } // The refusal tests the RAW dt (like type 2), and a NaN dt is not refused (AH&41 parity). - if (psmRuntimeField(self,0x21D) || dt<=0) return; - void* descriptor=psmRuntimeField(self,0x2C); - if (psmRuntimeField(descriptor,0xEC)) + if (psmInstanceB(self,0x21D) || dt<=0) return; + void* descriptor=psmInstanceB(self,0x2C); + if (psmDescriptor1(descriptor,0xEC)) { // The history clock advances by the unclamped scaled time. - psmRuntimeField(self,0x214)=static_cast( - static_cast(elapsed)+psmRuntimeField(self,0x214)); + psmInstanceB(self,0x214)=static_cast( + static_cast(elapsed)+psmInstanceB(self,0x214)); psmType1RememberPlane(self); } - if (!psmRuntimeField(self,0x21F) && psmRuntimeField(self,0x21E)) - psmRuntimeField(self,0x21F)=psmRuntimeField(self,0x21E); - descriptor=psmRuntimeField(self,0x2C); - psmRuntimeField(self,0x140)=0; psmRuntimeField(self,0x13C)=0; - const double maximum=static_cast(psmRuntimeField(descriptor,0x9C))+psmRuntimeField(descriptor,0x98); + if (!psmInstanceB(self,0x21F) && psmInstanceB(self,0x21E)) + psmInstanceB(self,0x21F)=psmInstanceB(self,0x21E); + descriptor=psmInstanceB(self,0x2C); + psmInstanceB(self,0x140)=0; psmInstanceB(self,0x13C)=0; + const double maximum=static_cast(psmDescriptor1(descriptor,0x9C))+psmDescriptor1(descriptor,0x98); if (elapsed>maximum) elapsed=static_cast(maximum); for (int i=0;i<3;++i) { - psmRuntimeField(self,0xFC+4*i)=0x4B18967F; // 9999999.0f - psmRuntimeField(self,0x108+4*i)=0xCB18967F; // -9999999.0f + psmInstanceB(self,0xFC+4*i)=0x4B18967F; // 9999999.0f + psmInstanceB(self,0x108+4*i)=0xCB18967F; // -9999999.0f } - psmRuntimeField(self,0xC0)=psmRuntimeField(self,0xA4); + psmInstanceB(self,0xC0)=psmInstanceB(self,0xA4); psmType1RefreshTransform(self); - psmRuntimeField(self,0xB4)=psmRuntimeField(self,0xA4); - const double total=static_cast(elapsed)+psmRuntimeField(self,0xD0); + psmInstanceB(self,0xB4)=psmInstanceB(self,0xA4); + const double total=static_cast(elapsed)+psmInstanceB(self,0xD0); const unsigned int steps=static_cast(static_cast(100.0*total)); const double advanced=static_cast(steps)*psmType1FixedStep; - psmRuntimeField(self,0xCC)=psmRuntimeField(self,0xF4); - psmRuntimeField(self,0xD0)=static_cast(total-advanced); - psmRuntimeField(self,0xF4)=static_cast(advanced+psmRuntimeField(self,0xF4)); - for (unsigned int i=0;psmRuntimeField(self,0x14)[i];) - i+=psmType1AdvanceParticle(self,psmRuntimeField(self,0x14)[i],static_cast(i), + psmInstanceB(self,0xCC)=psmInstanceB(self,0xF4); + psmInstanceB(self,0xD0)=static_cast(total-advanced); + psmInstanceB(self,0xF4)=static_cast(advanced+psmInstanceB(self,0xF4)); + for (unsigned int i=0;psmInstanceB(self,0x14)[i];) + i+=psmType1AdvanceParticle(self,psmInstanceB(self,0x14)[i],static_cast(i), psmType1FixedStep,steps); - const double delay=static_cast(psmRuntimeField(self,0xF0))-elapsed; - psmRuntimeField(self,0xF0)=static_cast(delay); // FST: the test keeps x87 precision - if (delay>0) { psmRuntimeField(self,0xF8)=psmRuntimeField(self,0xF4); return; } + const double delay=static_cast(psmInstanceB(self,0xF0))-elapsed; + psmInstanceB(self,0xF0)=static_cast(delay); // FST: the test keeps x87 precision + if (delay>0) { psmInstanceB(self,0xF8)=psmInstanceB(self,0xF4); return; } // replay the armed prewarm in 1/60 s virtual updates (the flag word is // cleared first, so the recursion cannot re-enter this arm). - if (psmRuntimeField(self,0xEC)>0) + if (psmInstanceB(self,0xEC)>0) { - float remaining=psmRuntimeField(self,0xEC); - psmRuntimeField(self,0xEC)=0; + float remaining=psmInstanceB(self,0xEC); + psmInstanceB(self,0xEC)=0; if (remaining>0) for (;;) { @@ -267,30 +283,30 @@ void psmType1Update(void* self,float dt) } } psmType1Emit(self,elapsed); - psmRuntimeField(self,0xA4)=psmRuntimeField(self,0xB4); - float* const bounds=&psmRuntimeField(self,0xFC); - if (psmRuntimeField(self,0x28)) + psmInstanceB(self,0xA4)=psmInstanceB(self,0xB4); + float* const bounds=&psmInstanceB(self,0xFC); + if (psmInstanceB(self,0x28)) { // Every term re-reads the descriptor pointer, as 10186041..101860B1 do. for (int i=0;i<3;++i) bounds[i]=static_cast(static_cast(bounds[i]) - -psmRuntimeField(psmRuntimeField(self,0x2C),0x1E8)); + -psmDescriptor1(psmInstanceB(self,0x2C),0x1E8)); for (int i=3;i<6;++i) - bounds[i]=static_cast(static_cast(psmRuntimeField( - psmRuntimeField(self,0x2C),0x1E8))+bounds[i]); + bounds[i]=static_cast(static_cast(psmDescriptor1( + psmInstanceB(self,0x2C),0x1E8))+bounds[i]); } else { - psmRuntimeField(self,0xFC)=psmRuntimeField(self,0xA4); - psmRuntimeField(self,0x108)=psmRuntimeField(self,0xA4); + const Vec3& position=psmInstanceB(self,0xA4); + psmType1SetBounds(bounds,position,position); } // PE 1016EB70 (radius) then 1016EBC0 (centre), in that order. const float deltaZ=bounds[5]-bounds[2]; const float halfX=static_cast((static_cast(bounds[3])-bounds[0])*0.5); const double halfY=(static_cast(bounds[4])-bounds[1])*0.5; - psmRuntimeField(self,0x120)=static_cast(::sqrt(deltaZ*0.5*(deltaZ*0.5) + psmInstanceB(self,0x120)=static_cast(::sqrt(deltaZ*0.5*(deltaZ*0.5) +static_cast(halfX)*halfX+halfY*halfY)); const float sumZ=bounds[5]+bounds[2]; - psmRuntimeField(self,0x114)={static_cast((static_cast(bounds[3])+bounds[0])*0.5), + psmInstanceB(self,0x114)={static_cast((static_cast(bounds[3])+bounds[0])*0.5), static_cast((static_cast(bounds[4])+bounds[1])*0.5),sumZ*0.5f}; } diff --git a/Code/BF2/Geom/ParticleSystem/ParticleInstanceType2.inl b/Code/BF2/Geom/ParticleSystem/ParticleInstanceType2.inl index 8a6d0dda1..4ca82d529 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleInstanceType2.inl +++ b/Code/BF2/Geom/ParticleSystem/ParticleInstanceType2.inl @@ -7,32 +7,37 @@ float* psmType2NewParticle(void* self); void psmType2Emit(void* self,float dt); int psmType2AdvanceParticle(void* self,float* particle,int index,float step,unsigned int steps); +// PE 0x1017A8D0 void psmType2RefreshTransform(void* self) { - if (psmRuntimeField(self,0x18)) return; - Mat4& output=psmRuntimeField(self,0x74); - const Mat4& local=psmRuntimeField(self,0x34); - world::IObject* const owner=psmRuntimeField(self,0x10); - if (owner) output.mult(local,owner->getVisualAbsoluteTransformation()); - else if (psmRuntimeField(self,0x30)) output.mult(local,*psmRuntimeField(self,0x30)); + if (psmInstanceB(self,0x18)) return; + Mat4& output=psmInstanceB(self,0x74); + const Mat4& local=psmInstanceB(self,0x34); + world::IObject* const owner=psmInstanceB(self,0x10); + if (owner) rendmath::mult(output,local,owner->getVisualAbsoluteTransformation()); + else if (psmInstanceB(self,0x30)) rendmath::mult(output,local,*psmInstanceB(self,0x30)); else output=local; ParticleSystemManager* const manager=reinterpret_cast(g_ParticleSystemManager); - void* const descriptor=psmRuntimeField(self,0x2C); - if (psmRuntimeField(descriptor,0x8C) && manager->m_heightmapCluster) + void* const descriptor=psmInstanceB(self,0x2C); + if (psmDescriptor2(descriptor,0x8C) && manager->m_heightmapCluster) { - output=psmType4WaterMatrix(psmRuntimeField(self,0xA4),Vec3{0,1,0},psmRuntimeField(self,0x94)); - psmRuntimeField(self,0xA8)=static_cast(manager->m_heightmapCluster) - ->getWaterLevelInWorldCoords(psmRuntimeField(self,0xA4))+psmRuntimeField(descriptor,0x90); + output=psmType4WaterMatrix(psmInstanceB(self,0xA4),Vec3{0,1,0},psmInstanceB(self,0x94)); + ParticleSystemManager* const waterManager=reinterpret_cast(g_ParticleSystemManager); + const float water=static_cast(waterManager->m_heightmapCluster) + ->getWaterLevelInWorldCoords(psmInstanceB(self,0xA4)); + psmInstanceB(self,0xA8)=water + +psmDescriptor2(psmInstanceB(self,0x2C),0x90); } } class ParticleInstanceType2 : public IParticleSystemInstance { - unsigned char m_data[0x198]; - template T& at(unsigned int offset) { return psmRuntimeField(this,offset); } + unsigned char m_data[PSM_INSTANCE_DATA(0x19C)]; + template T& at(unsigned int offset) { return psmInstanceB(this,offset); } template const T& at(unsigned int offset) const - { return *reinterpret_cast(reinterpret_cast(this)+offset); } + { return psmInstanceB(const_cast(this), offset); } public: + // PE 0x1017B5D0 explicit ParticleInstanceType2(IParticleSystemTemplate* descriptor) { at(0x18)=0; at(0x1C)={0,0,0}; at(0x28)=0; @@ -48,38 +53,49 @@ public: at(0x156)=1; at(0x157)=1; at(0x15C)={0,0,0}; at(0x168)={1,1,1}; at(0x10)=0; at(0xC)=0; at(8)=0; - const float emitTime=psmRuntimeField(descriptor,0x168); - const float lifeTime=psmRuntimeField(descriptor,0x70); + const float emitTime=psmDescriptor2(descriptor,0x168); + const float lifeTime=psmDescriptor2(descriptor,0x70); +#if defined(__APPLE__) + // [CHOSEN, not recovered] Preserve the live x87 result and FISTP integer indefinite. + using bf2x87::wide; + bf2x87::Real capacityTime=wide(lifeTime); + if (emitTime!=0 && !psmDescriptor2(descriptor,0x16C)) + capacityTime=emitTime(bf2x87::toIntTruncate( + capacityTime*wide(psmDescriptor2(descriptor,0x10))+wide(10.0f))); +#else double capacityTime=lifeTime; - if (emitTime!=0 && !psmRuntimeField(descriptor,0x16C)) + if (emitTime!=0 && !psmDescriptor2(descriptor,0x16C)) capacityTime=emitTime(static_cast( - capacityTime*psmRuntimeField(descriptor,0x10)+10.0)); + capacityTime*psmDescriptor2(descriptor,0x10)+10.0)); +#endif + at(0x150)=requested; static const unsigned int capacities[]={2,4,8,16,32,64,128,256,512,1024,2048,0}; unsigned int index=0; while (capacities[index] && requested>capacities[index]) ++index; if (!capacities[index]) { - // Retail reports Debug type6, TrailSystemInstance.cpp:85. That dispatcher remains - // [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: particle-trail-capacity-debug]. - std::fprintf(stderr,"[FRONTIER] dice::hfe::geom::TrailSystemInstance::TrailSystemInstance " - "(Debug type 6, particle capacity %u exceeds 2048) reached\n",requested); - std::fflush(stderr); std::abort(); + // PE 0x1017B808. Suppression leaves the zero capacity-table terminator selected. + ::renddx9abi::Debug(DebugTypeError, + "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\ParticleSystem\\TrailSystemInstance.cpp", + 85, "") << "Particle system, uses to many particles"; } at(0x150)=capacities[index]; at(0x174)=0; at(0x178)=0; at(0x17C)=capacities[index]-1; - at(0x14)=static_cast(::renddx9abi::engineAlloc(capacities[index]*4+4)); - ::memset(at(0x14),0,capacities[index]*4+4); + at(0x14)=static_cast(::renddx9abi::engineAlloc(capacities[index]*kPsmPointerSize+kPsmPointerSize)); + ::memset(at(0x14),0,capacities[index]*kPsmPointerSize+kPsmPointerSize); at(0x1C)={0,0,0}; at(0xF8)={0,0,0}; at(0x104)={0,0,0}; at(0x34)=Mat4::getIdentity(); at(4)=0; } + // PE 0x1017A520 ~ParticleInstanceType2() override { ParticleSystemManager* const manager=reinterpret_cast(g_ParticleSystemManager); while (at(0x178)!=at(0x174)) { float* const particle=at(0x14)[at(0x178)]; - psmRuntimeField(particle,0)=manager->m_type2FreeList; + psmRecordLink(particle, 2)=manager->m_type2FreeList; manager->m_type2FreeList=particle; at(0x178)=(at(0x178)+1)&at(0x17C); } @@ -87,12 +103,13 @@ public: } static void operator delete(void* self) { ::renddx9abi::engineFree(self); } int reserved01() const override { return 2; } + // PE 0x1017A780 void reserved02() const override { ParticleInstanceType2* const self=const_cast(this); const bool wasPlaying=self->at(0x140)!=0; if (wasPlaying) self->reserved04(); - if (self->at(0x28)) self->reserved41(psmRuntimeField(self->at(0x2C),0x70)); + if (self->at(0x28)) self->reserved41(psmDescriptor2(self->at(0x2C),0x70)); ParticleSystemManager* const manager=reinterpret_cast(g_ParticleSystemManager); while (self->at(0x178)!=self->at(0x174)) { @@ -101,8 +118,8 @@ public: array[self->at(0x178)]=0; --self->at(0x28); const unsigned int next=(self->at(0x178)+1)&self->at(0x17C); self->at(0x178)=next; - if (array[next]) psmRuntimeField(array[next],0x88)=0; - psmRuntimeField(particle,0)=manager->m_type2FreeList; manager->m_type2FreeList=particle; + if (array[next]) psmRuntimeField(array[next],0x88)=0; + psmRecordLink(particle, 2)=manager->m_type2FreeList; manager->m_type2FreeList=particle; } self->at(0x174)=0; self->at(0x178)=0; self->at(0x128)=1; self->at(0x130)=0; self->at(0x28)=0; @@ -111,25 +128,26 @@ public: self->at(0x156)=1; self->at(0x157)=1; self->at(0x155)=0; if (wasPlaying) self->reserved03(false); } + // PE 0x1017ADD0 void reserved03(bool firstPerson) override { ParticleSystemManager* const manager=reinterpret_cast(g_ParticleSystemManager); IParticleSystemTemplate* const descriptor=at(0x2C); if (descriptor->getQualityLevel()>static_cast(manager->m_qualityLevel)) return; at(0x140)=1; at(0x154)=1; - at(0xE8)=psmRuntimeField(descriptor,0x168); at(0xEC)=psmRuntimeField(descriptor,0x178); + at(0xE8)=psmDescriptor2(descriptor,0x168); at(0xEC)=psmDescriptor2(descriptor,0x178); at(0xF0)=0; at(0xF4)=0; at(0xD0)=0; at(0x156)=1; at(0x157)=1; at(0x120)=dx9rend::rendererFrameOrdinal(); psmType2RefreshTransform(this); if (!at(4)) { - at(0x198)=at(0xA8)(dx9rend::g_raShaderConstants,0x1BC); + at(0x198)=at(0xA8)<*reinterpret_cast(dx9rend::raShaderConstantsAt(0x1BC)); psmAddActive(manager,this,firstPerson); } at(0x15C)=at(0xA4); at(0x158)=0; const int random=psmEmissionRandomInteger(); - const unsigned int frames=psmRuntimeField(descriptor,0x1D4)-1; + const unsigned int frames=psmDescriptor2(descriptor,0x1D4)-1; at(0x18C)=0; at(0x188)=-1; at(0x190)=static_cast(static_cast(random)*frames*0.000000059604644775390625); dx9rend::IRenderView* const view=dx9rend::rendererGetRenderViewDup(); @@ -144,7 +162,7 @@ public: { at(0x120)=dx9rend::rendererFrameOrdinal(); at(0x156)=1; at(0x157)=1; } else { at(0x120)=0; at(0x156)=0; at(0x157)=0; } view->setFarPlane(oldFar); - float remaining=psmRuntimeField(descriptor,0xC); + float remaining=psmDescriptor2(descriptor,0xC); if (remaining>0) for (;;) { @@ -156,47 +174,72 @@ public: } void reserved04() override { - if (at(0x28)) psmRuntimeField(at(0x14)[at(0x194)],0x88)=0; + if (at(0x28)) psmRuntimeField(at(0x14)[at(0x194)],0x88)=0; at(0x140)=0; at(0x154)=0; at(0xE8)=0; } bool reserved05() const override { return at(0x140)!=0; } + // PE 0x1017C1C0. void setPaused(bool value) override { at(0x155)=value; } bool reserved07() const override { return at(0x155)!=0; } void reserved08() override { at(0x18)=1; at(0x10)=0; at(0xC)=0; at(0x30)=0; } + // PE 0x1017C1E0. void reserved09(bool value) override { at(0x156)=value; } bool reserved10() const override { return at(0x156)!=0; } - void reserved11(int value) override { at(0x10)=value; } - int reserved12() const override { return at(0x10); } - void reserved13(int value) override { at(0x30)=value; } + void reserved11(intptr_t value) override { at(0x10)=value; } + intptr_t reserved12() const override { return at(0x10); } + void reserved13(intptr_t value) override { at(0x30)=value; } void* reserved14(const void* value) override { at(0x34)=*static_cast(value); return &at(0x34); } const void* reserved15() const override { return &at(0x34); } - void reserved16(const Vec3& value) override { at(0xD4)=value; } + // PE 0x1017A9A0. Read the three components before writing any overlapping destination. + void reserved16(const Vec3& value) override + { + const float z = psmCopyStoredFloat(value.z); + const float y = psmCopyStoredFloat(value.y); + unsigned int x; + ::memcpy(&x, &value.x, sizeof(x)); + at(0xD8) = y; + at(0xD4) = x; + at(0xDC) = z; + } const Vec3& reserved17() const override { return at(0xD4); } void reserved18(const void*) override {} // PE1017A6A0 genuine collision-plane null body + // PE 0x1017A6E0. void reserved19(float value) override { at(0xE4)=value; } float reserved20() const override { return at(0xE4); } void reserved21(int,int) override { at(0x144)=1; } + // PE 0x1017A630. void reserved22(float value) override { at(0x148)=value; } float reserved23() const override { return at(0x148); } + // PE 0x1017A650. void reserved24(float value) override { at(0x12C)=value; } float reserved25() const override { return at(0x12C); } + // PE 0x1017C210 void reserved26(float value) override { at(0x134)=value; } float reserved27() const override { return at(0x134); } - void reserved28(const Vec3& value) override { at(0x168)=value; } + // PE 0x1017C330 + void reserved28(const Vec3& value) override + { + const float z=value.z,y=value.y,x=value.x; + at(0x16C)=y; at(0x168)=x; at(0x170)=z; + } const Vec3& reserved29() const override { return at(0x168); } + // PE 0x1017A670. void reserved30(float value) override { at(0x124)=value; } float reserved31() const override { return at(0x124); } + // PE 0x1017A6C0. void reserved32(float value) override { at(0xE0)=value; } float reserved33() const override { return at(0xE0); } int reserved34() const override { return at(0x150); } IParticleSystemTemplate* getTemplate() const override { return at(0x2C); } void reserved36(const Vec3& value) override { at(0x1C)=value; } void reserved37() override { psmType2NewParticle(this); } + // PE 0x1017C380. Only the x centre is stored before the position is subtracted; the y + // centre stays on the x87 stack (0x1017C3B8..0x1017C3DB). float reserved38() const override { const Vec3& low=at(0xF8),&high=at(0x104),&position=at(0xA4); const float x=static_cast((static_cast(low.x)+high.x)*0.5)-position.x; - const float y=static_cast((static_cast(low.y)+high.y)*0.5)-position.y; + const float y=static_cast((static_cast(low.y)+high.y)*0.5-position.y); const float sumZ=low.z+high.z; const double z=sumZ*0.5-position.z; const float dx=static_cast((static_cast(high.x)-low.x)*0.5),dz=high.z-low.z; const double dy=(static_cast(high.y)-low.y)*0.5; @@ -206,10 +249,11 @@ public: int reserved39() const override { return at(0x28); } const Vec3& getPosition() const override { return at(0xB4); } void reserved41(float value) override { psmType2Update(this,value); } + // PE 0x1017A5C0 void reserved42(bool value) override { - if (at(4) && value!=static_cast(at(6))) - { at(7)=value; psmReclassification(reinterpret_cast(g_ParticleSystemManager)).insert(reinterpret_cast(this)); } + if (at(4) && static_cast(value)!=at(6)) + { at(7)=value; psmReclassification(reinterpret_cast(g_ParticleSystemManager)).insert(this); } } float getGasCloudRadius() const override { return 1; } void setPlayer(void*) override {} // PE100E13B0 genuine null body @@ -217,11 +261,15 @@ public: void setMaterial(int) override {} // PE100E13B0 genuine null body int getMaterial() const override { return -1; } void setEffectController(world::IEffectController* value) override - { at(0xC)=value; reserved11(reinterpret_cast(value ? value->getObject() : 0)); } + { at(0xC)=value; reserved11(reinterpret_cast(value ? value->getObject() : 0)); } world::IEffectController* getEffectController() const override { return at(0xC); } bool getWaterSide() const override { return at(0x198)!=0; } }; +#if defined(_M_IX86) static_assert(sizeof(ParticleInstanceType2)==0x19C,"TrailSystemInstance PE1017B5D0 layout"); +#else +static_assert(sizeof(ParticleInstanceType2)==kPsmInstanceSize,"x64 instance layout, ParticleRawLayout.h"); +#endif IParticleSystemInstance* psmCreateType2Instance(IParticleSystemTemplate* descriptor) { diff --git a/Code/BF2/Geom/ParticleSystem/ParticleInstanceType2Emission.inl b/Code/BF2/Geom/ParticleSystem/ParticleInstanceType2Emission.inl index 00112fe28..cb67b6d05 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleInstanceType2Emission.inl +++ b/Code/BF2/Geom/ParticleSystem/ParticleInstanceType2Emission.inl @@ -5,33 +5,65 @@ int psmType2AdvanceParticle(void*,float*,int,float,unsigned int); void psmType2EmissionDirection(float* output,void* descriptor,void* self) { - output[0]=psmRuntimeField(descriptor,0x1AC)*psmRuntimeField(self,0x168); - output[1]=psmRuntimeField(descriptor,0x1B0)*psmRuntimeField(self,0x16C); - output[2]=psmRuntimeField(descriptor,0x1B4)*psmRuntimeField(self,0x170); + output[0]=psmDescriptor2(descriptor,0x1AC)*psmInstanceB(self,0x168); + output[1]=psmDescriptor2(descriptor,0x1B0)*psmInstanceB(self,0x16C); + output[2]=psmDescriptor2(descriptor,0x1B4)*psmInstanceB(self,0x170); } -void psmType2EmissionSphere(float* output,void* descriptor,void* self,float* particle) +// PE 0x1017C490 +float* psmType2EmissionSphere(float* output,void* descriptor,void* self,float* particle) { const float phi=static_cast(psmEmissionRandomInteger()*static_cast(3.7450703871400037e-7f)); const double theta=psmEmissionRandomInteger()*static_cast(1.8725351935700019e-7f); - const float savedTheta=static_cast(theta), sineTheta=static_cast(::sin(theta)); + const float savedTheta=static_cast(theta); +#if defined(__APPLE__) + const float sineTheta=bf2x87::store(bf2x87::sinValue(bf2x87::wide(theta))); +#else + const float sineTheta=static_cast(::sin(theta)); +#endif const float yRandom=static_cast(psmEmissionUnit()), xRandom=static_cast(psmEmissionUnit()); - const double zRadius=psmEmissionRandomInteger()*static_cast(psmRuntimeField(descriptor,0x1C)) + const double zRadius=psmEmissionRandomInteger()*static_cast(psmDescriptor2(descriptor,0x1C)) *0.000000059604644775390625; - const double xRadius=static_cast(xRandom)*psmRuntimeField(descriptor,0x14); - const double yRadius=static_cast(yRandom)*psmRuntimeField(descriptor,0x18); + const double xRadius=static_cast(xRandom)*psmDescriptor2(descriptor,0x14); + const double yRadius=static_cast(yRandom)*psmDescriptor2(descriptor,0x18); +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain FSIN/FCOS results through the final products. + using bf2x87::wide; + particle[1]=bf2x87::store(bf2x87::cosValue(wide(phi))*wide(xRadius)*wide(sineTheta)); + particle[2]=bf2x87::store(bf2x87::sinValue(wide(phi))*wide(yRadius)*wide(sineTheta)); + particle[3]=bf2x87::store(bf2x87::cosValue(wide(savedTheta))*wide(zRadius)); +#else particle[1]=static_cast(::cos(phi)*xRadius*sineTheta); particle[2]=static_cast(::sin(phi)*yRadius*sineTheta); particle[3]=static_cast(::cos(savedTheta)*zRadius); +#endif psmType2EmissionDirection(output,descriptor,self); + return output; } -void psmType2EmissionCylinder(float* output,void* descriptor,void* self,float* particle) +// PE 0x1017C5C0 +float* psmType2EmissionCylinder(float* output,void* descriptor,void* self,float* particle) { - const double angle=(psmEmissionSymmetric()*psmRuntimeField(descriptor,0x5C) - +psmRuntimeField(descriptor,0x60))*0.01745329238474369f; +#if defined(__APPLE__) + // [CHOSEN, not recovered] The angle has no float/double spill before FSIN/FCOS. + using bf2x87::wide; + const bf2x87::Real angle=(wide(psmEmissionSymmetric())*wide(psmDescriptor2(descriptor,0x5C)) + +wide(psmDescriptor2(descriptor,0x60)))*wide(0.01745329238474369f); + const float cosine=bf2x87::store(bf2x87::cosValue(angle)), sine=bf2x87::store(bf2x87::sinValue(angle)); +#else + const double angle=(psmEmissionSymmetric()*psmDescriptor2(descriptor,0x5C) + +psmDescriptor2(descriptor,0x60))*0.01745329238474369f; const float cosine=static_cast(::cos(angle)), sine=static_cast(::sin(angle)); +#endif unsigned int axis=0; - if(psmRuntimeField(descriptor,0x18)>psmRuntimeField(descriptor,0x14))axis=1; - if(psmRuntimeField(descriptor,0x1C)>psmRuntimeField(descriptor,0x14+4*axis))axis=2; + for(unsigned int i=0;i<3;++i) + { +#if defined(__APPLE__) + // [CHOSEN, not recovered] Keep the first self-comparison's FCOM invalid exception too. + if(bf2x87::greater(wide(psmDescriptor2(descriptor,0x14+4*i)), + wide(psmDescriptor2(descriptor,0x14+4*axis))))axis=i; +#else + if(psmDescriptor2(descriptor,0x14+4*i)>psmDescriptor2(descriptor,0x14+4*axis))axis=i; +#endif + } unsigned char* const bytes=static_cast(descriptor); const float z=static_cast(psmEmissionDistribution(bytes+0x48)); const float y=static_cast(psmEmissionDistribution(bytes+0x34)); @@ -39,48 +71,51 @@ void psmType2EmissionCylinder(float* output,void* descriptor,void* self,float* p if(axis==0){particle[1]=static_cast(x);particle[2]=y*sine;particle[3]=z*cosine;} else if(axis==1){particle[1]=static_cast(x*sine);particle[2]=y;particle[3]=z*cosine;} else{particle[1]=static_cast(x*sine);particle[2]=y*cosine;particle[3]=z;} - if(psmRuntimeField(descriptor,0x224)==1) + if(psmDescriptor2(descriptor,0x224)==1) { output[0]=particle[1];output[1]=particle[2];output[2]=particle[3];output[axis]=0; psmNormalize3(output); } else psmType2EmissionDirection(output,descriptor,self); + return output; } -void psmType2EmissionBox(float* output,void* descriptor,void* self,float* particle) +// PE 0x1017C7B0 +float* psmType2EmissionBox(float* output,void* descriptor,void* self,float* particle) { unsigned char* const bytes=static_cast(descriptor); const float z=static_cast(psmEmissionDistribution(bytes+0x48)); const float y=static_cast(psmEmissionDistribution(bytes+0x34)); particle[1]=static_cast(psmEmissionDistribution(bytes+0x20)); particle[2]=y;particle[3]=z;psmType2EmissionDirection(output,descriptor,self); + return output; } // PE1017B0A0 and its virtual thunk1017BC60. The otherwise unused third RNG draw is retained. float* psmType2NewParticle(void* self) { - void* const manager=g_ParticleSystemManager; - float* const particle=psmRuntimeField(manager,0x85E0); - psmRuntimeField(manager,0x85E0)=particle?psmRuntimeField(particle,0):nullptr; + ParticleSystemManager* const manager=reinterpret_cast(g_ParticleSystemManager); + float* const particle=static_cast(manager->m_type2FreeList); // +0x85E0 + manager->m_type2FreeList=particle?static_cast(psmRecordLink(particle, 2)):nullptr; if(!particle)return nullptr; - ++psmRuntimeField(self,0x138); - const double dx=static_cast(psmRuntimeField(self,0xA4))-psmRuntimeField(self,0x15C); - const double dy=static_cast(psmRuntimeField(self,0xA8))-psmRuntimeField(self,0x160); - const double dz=static_cast(psmRuntimeField(self,0xAC))-psmRuntimeField(self,0x164); - const double distance=::sqrt(dx*dx+dz*dz+dy*dy)+psmRuntimeField(self,0x158); - psmRuntimeField(self,0x158)=static_cast(distance);particle[32]=static_cast(distance); - psmRuntimeField(self,0x15C)=psmRuntimeField(self,0xA4); - void* descriptor=psmRuntimeField(self,0x2C); - particle[39]=psmRuntimeField(descriptor,0x70);particle[40]=static_cast(1.0/particle[39]); - particle[38]=psmRuntimeField(self,0xE0);particle[30]=particle[38]*particle[40]; - particle[28]=psmRuntimeField(self,0x144); - particle[31]=psmRuntimeField(self,0x148);particle[34]=psmRuntimeField(self,0x148); - if(!psmRuntimeField(self,0x28))particle[34]=0; + ++psmInstanceB(self,0x138); + const double dx=static_cast(psmInstanceB(self,0xA4))-psmInstanceB(self,0x15C); + const double dy=static_cast(psmInstanceB(self,0xA8))-psmInstanceB(self,0x160); + const double dz=static_cast(psmInstanceB(self,0xAC))-psmInstanceB(self,0x164); + const double distance=::sqrt(dx*dx+dz*dz+dy*dy)+psmInstanceB(self,0x158); + psmInstanceB(self,0x158)=static_cast(distance);particle[32]=static_cast(distance); + psmInstanceB(self,0x15C)=psmInstanceB(self,0xA4); + void* descriptor=psmInstanceB(self,0x2C); + particle[39]=psmDescriptor2(descriptor,0x70);particle[40]=static_cast(1.0/particle[39]); + particle[38]=psmInstanceB(self,0xE0);particle[30]=particle[38]*particle[40]; + particle[28]=psmInstanceB(self,0x144); + particle[31]=psmInstanceB(self,0x148);particle[34]=psmInstanceB(self,0x148); + if(!psmInstanceB(self,0x28))particle[34]=0; const float firstRandom=static_cast(psmEmissionSymmetric()); - particle[29]=static_cast(psmEmissionSymmetric()*psmRuntimeField(descriptor,0x150)); + particle[29]=static_cast(psmEmissionSymmetric()*psmDescriptor2(descriptor,0x150)); psmEmissionRaw(); float direction[3]={0,0,0}; - descriptor=psmRuntimeField(self,0x2C); - switch(psmRuntimeField(descriptor,0x224)) + descriptor=psmInstanceB(self,0x2C); + switch(psmDescriptor2(descriptor,0x224)) { case 0:psmType2EmissionSphere(direction,descriptor,self,particle);break; case 1:case 2:psmType2EmissionCylinder(direction,descriptor,self,particle);break; @@ -90,20 +125,20 @@ float* psmType2NewParticle(void* self) const float randomY=static_cast(psmEmissionSymmetric()); const float randomZ=static_cast(psmEmissionSymmetric()); Mat4 rotation,axis,copy; - psmEmissionRotation(rotation,randomX*psmRuntimeField(descriptor,0x158),0); - psmEmissionRotation(axis,randomY*psmRuntimeField(descriptor,0x15C),1); + psmEmissionRotation(rotation,randomX*psmDescriptor2(descriptor,0x158),0); + psmEmissionRotation(axis,randomY*psmDescriptor2(descriptor,0x15C),1); copy=rotation;psmEmissionRotateMultiply(rotation,copy,axis); - psmEmissionRotation(axis,randomZ*psmRuntimeField(descriptor,0x160),2); + psmEmissionRotation(axis,randomZ*psmDescriptor2(descriptor,0x160),2); copy=rotation;psmEmissionRotateMultiply(rotation,copy,axis); const float x=direction[0],y=direction[1],z=direction[2]; const double rotatedZ=static_cast(rotation.m[2])*x+static_cast(rotation.m[6])*y+static_cast(rotation.m[10])*z; const float rotatedY=static_cast(static_cast(rotation.m[1])*x+static_cast(rotation.m[9])*z+static_cast(rotation.m[5])*y); direction[0]=static_cast(static_cast(rotation.m[0])*x+static_cast(rotation.m[8])*z+static_cast(rotation.m[4])*y); direction[1]=rotatedY;direction[2]=static_cast(rotatedZ); - const float speed=static_cast((psmRuntimeField(descriptor,0x164) - -static_cast(firstRandom)*psmRuntimeField(descriptor,0x154))*psmRuntimeField(self,0x134)); - const float* const matrix=psmRuntimeField(self,0x74).m; - if(!psmRuntimeField(descriptor,0x1C0)) + const float speed=static_cast((psmDescriptor2(descriptor,0x164) + -static_cast(firstRandom)*psmDescriptor2(descriptor,0x154))*psmInstanceB(self,0x134)); + const float* const matrix=psmInstanceB(self,0x74).m; + if(!psmDescriptor2(descriptor,0x1C0)) { const float px=particle[1],py=particle[2],pz=particle[3]; particle[3]=static_cast(static_cast(matrix[2])*px+static_cast(matrix[10])*pz+static_cast(matrix[6])*py+matrix[14]); @@ -113,11 +148,11 @@ float* psmType2NewParticle(void* self) direction[2]=static_cast(static_cast(matrix[10])*dz+static_cast(matrix[2])*dx+static_cast(matrix[6])*dy); direction[1]=static_cast(static_cast(matrix[9])*dz+static_cast(matrix[1])*dx+static_cast(matrix[5])*dy); direction[0]=static_cast(static_cast(matrix[8])*dz+static_cast(matrix[4])*dy+static_cast(matrix[0])*dx); - const double scale=psmRuntimeField(self,0xE4); - const float inheritedX=static_cast(scale*psmRuntimeField(self,0xD4)); - const float inheritedY=static_cast(scale*psmRuntimeField(self,0xD8)); + const double scale=psmInstanceB(self,0xE4); + const float inheritedX=static_cast(scale*psmInstanceB(self,0xD4)); + const float inheritedY=static_cast(scale*psmInstanceB(self,0xD8)); const float vy=direction[1]*speed,vz=direction[2]*speed; - particle[37]=static_cast(vz+scale*psmRuntimeField(self,0xDC)); + particle[37]=static_cast(vz+scale*psmInstanceB(self,0xDC)); particle[35]=static_cast(static_cast(direction[0])*speed+inheritedX); particle[36]=vy+inheritedY; } @@ -127,9 +162,11 @@ float* psmType2NewParticle(void* self) particle[35]=direction[0]*speed;particle[36]=rotatedY*speed; } particle[25]=matrix[8];particle[26]=matrix[9];particle[27]=matrix[10]; - const unsigned int sections=psmRuntimeField(psmRuntimeField(self,0x2C),0x220); - const float* corners=psmRuntimeField(g_ParticleSystemManager,0x8594+4*sections); - for(unsigned int i=0;i<2*psmRuntimeField(psmRuntimeField(self,0x2C),0x220);++i) + const unsigned int sections=psmDescriptor2(psmInstanceB(self,0x2C),0x220); + // Retail manager +0x8594: the trail renderer's per-side vertex arrays at its +0x8C8. + const float* corners=psmTrailField( + reinterpret_cast(g_ParticleSystemManager)->m_trailRenderer,0x8C8+4*sections); + for(unsigned int i=0;i<2*psmDescriptor2(psmInstanceB(self,0x2C),0x220);++i) { const float* c=corners+3*i; const double z=static_cast(c[2])*matrix[10]+static_cast(matrix[2])*c[0]+static_cast(c[1])*matrix[6]; @@ -138,79 +175,90 @@ float* psmType2NewParticle(void* self) particle[8+3*i]=static_cast(y);particle[9+3*i]=static_cast(z); } unsigned int index=0; - if(psmRuntimeField(self,0x28)) + if(psmInstanceB(self,0x28)) { - index=psmRuntimeField(self,0x174); - psmRuntimeField(self,0x174)=(index+1)&psmRuntimeField(self,0x17C); - ++psmRuntimeField(self,0x28); + index=psmInstanceB(self,0x174); + psmInstanceB(self,0x174)=(index+1)&psmInstanceB(self,0x17C); + ++psmInstanceB(self,0x28); } else - {psmRuntimeField(self,0x174)=1;psmRuntimeField(self,0x178)=0;psmRuntimeField(self,0x28)=1;} - psmRuntimeField(self,0x14)[index]=particle; - psmRuntimeField(self,0x194)=index; + {psmInstanceB(self,0x174)=1;psmInstanceB(self,0x178)=0;psmInstanceB(self,0x28)=1;} + psmInstanceB(self,0x14)[index]=particle; + psmInstanceB(self,0x194)=index; return particle; } -// PE1017B8E0: speed threshold, recently visible gate, timed emission and moving-emitter catch-up. +// PE 0x1017B8E0: speed threshold, recently visible gate, timed emission and moving-emitter catch-up. void psmType2Emit(void* self,float dt) { - if(!psmRuntimeField(self,0x140))return; +#if defined(__APPLE__) + // [CHOSEN, not recovered] Preserve x87 live arithmetic and integer conversion. + using Real=bf2x87::Real; +#else + using Real=double; +#endif + if(!psmInstanceB(self,0x140))return; if(dt>0.001f) { - const float dz=psmRuntimeField(self,0xBC)-psmRuntimeField(self,0xC8); - const float inverse=static_cast(1.0/dt); - const float vx=static_cast((static_cast(psmRuntimeField(self,0xB4))-psmRuntimeField(self,0xC0))*inverse); - const double vy=(static_cast(psmRuntimeField(self,0xB8))-psmRuntimeField(self,0xC4))*inverse; - const double vz=static_cast(dz)*inverse; - if(vz*vz+vy*vy+static_cast(vx)*vx(psmRuntimeField(self,0x2C),0x230)) - {psmRuntimeField(self,0xF4)=psmRuntimeField(self,0xF0);return;} + const float dz=psmInstanceB(self,0xBC)-psmInstanceB(self,0xC8); + const float inverse=static_cast(static_cast(1.0)/dt); + const float vx=static_cast((static_cast(psmInstanceB(self,0xB4))-psmInstanceB(self,0xC0))*inverse); + const Real vy=(static_cast(psmInstanceB(self,0xB8))-psmInstanceB(self,0xC4))*inverse; + const Real vz=static_cast(dz)*inverse; + if(vz*vz+vy*vy+static_cast(vx)*vx(psmInstanceB(self,0x2C),0x230)) + {psmInstanceB(self,0xF4)=psmInstanceB(self,0xF0);return;} } const unsigned int frame=static_cast(dx9rend::g_rendererBase)->getFrameOrdinal(); - if(psmRuntimeField(self,0x120)+60u(self,0x157)=psmRuntimeField(self,0x156);psmRuntimeField(self,0x156)=0;return;} - void* descriptor=psmRuntimeField(self,0x2C); - if(psmRuntimeField(self,0x128)(descriptor,0x94))psmRuntimeField(self,0x128)=psmRuntimeField(descriptor,0x94); - if(psmRuntimeField(self,0x12C)(descriptor,0x94))psmRuntimeField(self,0x12C)=psmRuntimeField(descriptor,0x94); - const float interval=static_cast(1.0/(static_cast(psmRuntimeField(descriptor,0x10)) - *psmRuntimeField(self,0x128)*psmRuntimeField(self,0x12C))); - if(psmRuntimeField(self,0x154)) - {psmRuntimeField(self,0xC0)=psmRuntimeField(self,0xB4);psmRuntimeField(self,0x154)=0;} - while(interval+static_cast(psmRuntimeField(self,0xF4))(self,0xF0)) + if(psmInstanceB(self,0x120)+60u(self,0x157)=psmInstanceB(self,0x156);psmInstanceB(self,0x156)=0;return;} + void* descriptor=psmInstanceB(self,0x2C); + if(psmInstanceB(self,0x128)(descriptor,0x94))psmInstanceB(self,0x128)=psmDescriptor2(descriptor,0x94); + if(psmInstanceB(self,0x12C)(descriptor,0x94))psmInstanceB(self,0x12C)=psmDescriptor2(descriptor,0x94); + const float interval=static_cast(static_cast(1.0)/(static_cast(psmDescriptor2(descriptor,0x10)) + *psmInstanceB(self,0x128)*psmInstanceB(self,0x12C))); + if(psmInstanceB(self,0x154)) + {psmInstanceB(self,0xC0)=psmInstanceB(self,0xB4);psmInstanceB(self,0x154)=0;} + while(interval+static_cast(psmInstanceB(self,0xF4))(self,0xF0)) { - if(psmRuntimeField(self,0xE8)!=0) + if(psmInstanceB(self,0xE8)!=0) { - const double remaining=static_cast(psmRuntimeField(self,0xE8))-interval; - psmRuntimeField(self,0xE8)=static_cast(remaining); + const Real remaining=static_cast(psmInstanceB(self,0xE8))-interval; + psmInstanceB(self,0xE8)=static_cast(remaining); if(remaining<=0) { IParticleSystemInstance* instance=static_cast(self); instance->reserved04(); - if(psmRuntimeField(psmRuntimeField(self,0x2C),0x16C))instance->reserved03(false); + if(psmDescriptor2(psmInstanceB(self,0x2C),0x16C))instance->reserved03(false); return; } } - const float next=static_cast(interval+static_cast(psmRuntimeField(self,0xF4))); - psmRuntimeField(self,0xF4)=next; - double fraction=0; - if(psmRuntimeField(self,0xF0)>psmRuntimeField(self,0xCC)) - fraction=(static_cast(next)-psmRuntimeField(self,0xCC)) - /(static_cast(psmRuntimeField(self,0xF0))-psmRuntimeField(self,0xCC)); - const Vec3 previous=psmRuntimeField(self,0xC0),current=psmRuntimeField(self,0xB4); + const float next=static_cast(interval+static_cast(psmInstanceB(self,0xF4))); + psmInstanceB(self,0xF4)=next; + Real fraction=0; + if(psmInstanceB(self,0xF0)>psmInstanceB(self,0xCC)) + fraction=(static_cast(next)-psmInstanceB(self,0xCC)) + /(static_cast(psmInstanceB(self,0xF0))-psmInstanceB(self,0xCC)); + const Vec3 previous=psmInstanceB(self,0xC0),current=psmInstanceB(self,0xB4); const float dz=current.z-previous.z; - const float dx=static_cast((static_cast(current.x)-previous.x)*fraction); - const float dy=static_cast((static_cast(current.y)-previous.y)*fraction); - psmRuntimeField(self,0xA4)={dx+previous.x,dy+previous.y,static_cast(fraction*dz+previous.z)}; - if(psmRuntimeField(self,0x28)(self,0x150)) + const float dx=static_cast((static_cast(current.x)-previous.x)*fraction); + const float dy=static_cast((static_cast(current.y)-previous.y)*fraction); + psmInstanceB(self,0xA4)={dx+previous.x,dy+previous.y,static_cast(fraction*dz+previous.z)}; + if(psmInstanceB(self,0x28)(self,0x150)) { float* particle=psmType2NewParticle(self); if(particle) { - particle[35]+=psmRuntimeField(self,0x1C);particle[36]+=psmRuntimeField(self,0x20);particle[37]+=psmRuntimeField(self,0x24); - const unsigned int steps=static_cast(static_cast((static_cast(psmRuntimeField(self,0xF0))-psmRuntimeField(self,0xF4))*100.0)); - if(psmType2AdvanceParticle(self,particle,psmRuntimeField(self,0x28)-1,0.01f,steps)) + particle[35]+=psmInstanceB(self,0x1C);particle[36]+=psmInstanceB(self,0x20);particle[37]+=psmInstanceB(self,0x24); +#if defined(__APPLE__) + const unsigned int steps=static_cast(bf2x87::toIntTruncate( + (static_cast(psmInstanceB(self,0xF0))-psmInstanceB(self,0xF4))*100.0f)); +#else + const unsigned int steps=static_cast(static_cast((static_cast(psmInstanceB(self,0xF0))-psmInstanceB(self,0xF4))*100.0)); +#endif + if(psmType2AdvanceParticle(self,particle,psmInstanceB(self,0x28)-1,0.01f,steps)) { - const float remainder=static_cast(static_cast(psmRuntimeField(self,0xF0))-psmRuntimeField(self,0xF4)-static_cast(steps)*0.01f); - psmType2AdvanceParticle(self,particle,psmRuntimeField(self,0x28)-1,remainder,1); + const float remainder=static_cast(static_cast(psmInstanceB(self,0xF0))-psmInstanceB(self,0xF4)-static_cast(steps)*0.01f); + psmType2AdvanceParticle(self,particle,psmInstanceB(self,0x28)-1,remainder,1); } } } diff --git a/Code/BF2/Geom/ParticleSystem/ParticleInstanceType2Update.inl b/Code/BF2/Geom/ParticleSystem/ParticleInstanceType2Update.inl index 4f75b3557..49ec819de 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleInstanceType2Update.inl +++ b/Code/BF2/Geom/ParticleSystem/ParticleInstanceType2Update.inl @@ -3,22 +3,29 @@ void psmType2RefreshTransform(void*); void psmType2Emit(void*,float); -// PE1017A9D0: expiry always removes the oldest ring entry; the supplied index is unused. +// PE 0x1017A9D0: expiry always removes the oldest ring entry; the supplied index is unused. int psmType2AdvanceParticle(void* self,float* particle,int /*index*/,float step,unsigned int steps) { - const double age=static_cast(steps)*step+particle[38]; +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87 intermediates; explicit float locals are PE spills. + using Real=bf2x87::Real; +#else + using Real=double; +#endif + const Real age=static_cast(steps)*step+particle[38]; particle[38]=static_cast(age); if(age>=particle[39]) { - float** const ring=psmRuntimeField(self,0x14); - unsigned int& head=psmRuntimeField(self,0x178); + float** const ring=psmInstanceB(self,0x14); + unsigned int& head=psmInstanceB(self,0x178); float* const retired=ring[head];ring[head]=nullptr; - --psmRuntimeField(self,0x28); - head=(head+1)&psmRuntimeField(self,0x17C); + --psmInstanceB(self,0x28); + head=(head+1)&psmInstanceB(self,0x17C); if(ring[head])ring[head][34]=0; - psmRuntimeField(retired,0)=psmRuntimeField(g_ParticleSystemManager,0x85E0); - psmRuntimeField(g_ParticleSystemManager,0x85E0)=retired; - ++psmRuntimeField(self,0x13C); + psmRecordLink(retired, 2)= + reinterpret_cast(g_ParticleSystemManager)->m_type2FreeList; // +0x85E0 + reinterpret_cast(g_ParticleSystemManager)->m_type2FreeList=retired; + ++psmInstanceB(self,0x13C); return 0; } // Unlike ordinary/NSA particles, Trail samples the global speed and direction unconditionally. @@ -26,156 +33,159 @@ int psmType2AdvanceParticle(void* self,float* particle,int /*index*/,float step, reinterpret_cast(g_ParticleSystemManager)->m_windManager)->getGlobalWindSpeed(); const Vec3& direction=reinterpret_cast( reinterpret_cast(g_ParticleSystemManager)->m_windManager)->getGlobalWindDirection(); - void* descriptor=psmRuntimeField(self,0x2C); - const float affection=psmRuntimeField(descriptor,0x88); + void* descriptor=psmInstanceB(self,0x2C); + const float affection=psmDescriptor2(descriptor,0x88); const float windZ=windSpeed*direction.z; - const float wx=static_cast(static_cast(windSpeed)*direction.x*affection); - const float wy=static_cast(static_cast(windSpeed)*direction.y*affection); + const float wx=static_cast(static_cast(windSpeed)*direction.x*affection); + const float wy=static_cast(static_cast(windSpeed)*direction.y*affection); const float wz=windZ*affection; - const float gravityStep=step*psmRuntimeField(descriptor,0x78); - const float drag=step*psmRuntimeField(descriptor,0x7C); - const double t=particle[30]; - const float curve=static_cast(t*t*psmRuntimeField(descriptor,0x130) - +t*psmRuntimeField(descriptor,0x134)+t*t*t*psmRuntimeField(descriptor,0x12C) - +psmRuntimeField(descriptor,0x138)); + const float gravityStep=step*psmDescriptor2(descriptor,0x78); + const float drag=step*psmDescriptor2(descriptor,0x7C); + const Real t=static_cast(particle[30]); + const float curve=static_cast(t*t*psmDescriptor2(descriptor,0x130) + +t*psmDescriptor2(descriptor,0x134)+t*t*t*psmDescriptor2(descriptor,0x12C) + +psmDescriptor2(descriptor,0x138)); const float gravity=psmType0Clamp(curve)*gravityStep; particle[30]=particle[40]*particle[38]; while(steps--) { const float dx=particle[35]-wx,dz=particle[37]-wz; - const double dy=static_cast(particle[36])-wy; - const double squared=dy*dy+static_cast(dz)*dz+static_cast(dx)*dx; + const Real dy=static_cast(particle[36])-wy; + const Real squared=dy*dy+static_cast(dz)*dz+static_cast(dx)*dx; const float speedSquared=static_cast(squared); - double ax=0,ay=0;float az=0; - if(::fabs(squared)>=1.1920929e-7f) + Real ax=0,ay=0;float az=0; + if(squared>=static_cast(1.1920929e-7f)) { - const double negative=-static_cast(speedSquared); + const Real negative=-static_cast(speedSquared); const float vy=static_cast(dy*negative),vz=static_cast(dz*negative); const float fy=vy*drag,fz=vz*drag; +#if defined(__APPLE__) + const float inverse=bf2x87::store(bf2x87::wide(1.0f)/bf2x87::squareRoot(bf2x87::wide(speedSquared))); +#else const float inverse=static_cast(1.0/::sqrt(speedSquared)); - ax=dx*negative*drag*inverse;ay=static_cast(fy)*inverse;az=fz*inverse; +#endif + ax=dx*negative*drag*inverse;ay=static_cast(fy)*inverse;az=fz*inverse; } ay+=gravity; const float halfZ=static_cast(az*0.5); const float vx=static_cast(ax*0.5+particle[35]); - const double vy=ay*0.5+particle[36],vz=static_cast(halfZ)+particle[37]; + const Real vy=ay*0.5+particle[36],vz=static_cast(halfZ)+particle[37]; const float px=vx*step,py=static_cast(vy*step); particle[1]=px+particle[1];particle[2]=py+particle[2];particle[3]=static_cast(vz*step+particle[3]); particle[35]=static_cast(ax+particle[35]);particle[36]=static_cast(ay+particle[36]);particle[37]=az+particle[37]; } for(int i=35;i<=37;++i)if(::fabs(particle[i])<0.001f)particle[i]=0; particle[4]=particle[1];particle[5]=particle[2];particle[6]=particle[3]; - if(psmRuntimeField(psmRuntimeField(self,0x2C),0x1C0)) + if(psmDescriptor2(psmInstanceB(self,0x2C),0x1C0)) { - const float* m=psmRuntimeField(self,0x74).m; + const float* m=psmInstanceB(self,0x74).m; const float x=particle[4],y=particle[5],z=particle[6]; - const double rz=static_cast(m[2])*x+static_cast(m[10])*z+static_cast(m[6])*y+m[14]; - const double ry=static_cast(m[1])*x+static_cast(m[9])*z+static_cast(m[5])*y+m[13]; - particle[4]=static_cast(static_cast(m[8])*z+static_cast(m[4])*y+static_cast(m[0])*x+m[12]); + const Real rz=static_cast(m[2])*x+static_cast(m[10])*z+static_cast(m[6])*y+m[14]; + const Real ry=static_cast(m[1])*x+static_cast(m[9])*z+static_cast(m[5])*y+m[13]; + particle[4]=static_cast(static_cast(m[8])*z+static_cast(m[4])*y+static_cast(m[0])*x+m[12]); particle[5]=static_cast(ry);particle[6]=static_cast(rz); } - if(psmRuntimeField(psmRuntimeField(self,0x2C),0x8C) + if(psmDescriptor2(psmInstanceB(self,0x2C),0x8C) &&reinterpret_cast(g_ParticleSystemManager)->m_heightmapCluster) { - const double water=reinterpret_cast( + const Real water=static_cast(reinterpret_cast( reinterpret_cast(g_ParticleSystemManager)->m_heightmapCluster) - ->getWaterLevelInWorldCoords(*reinterpret_cast(particle+4)); - particle[5]=static_cast(water+psmRuntimeField(psmRuntimeField(self,0x2C),0x90)+0.1f); + ->getWaterLevelInWorldCoords(*reinterpret_cast(particle+4))); + particle[5]=static_cast(water+psmDescriptor2(psmInstanceB(self,0x2C),0x90)+0.1f); } - // PE1017A2B0 includes ordered extrema, preserving NaN's no-update behavior. - float* bounds=&psmRuntimeField(self,0xF8); - for(int i=0;i<3;++i){if(particle[4+i]>bounds[3+i])bounds[3+i]=particle[4+i];if(particle[4+i](self,0xF8),particle[4],particle[5],particle[6]); return 1; } // PE1017BC70: source dt controls refusal; the separately scaled/clamped dt drives simulation. void psmType2Update(void* self,float dt) { - float elapsed=dt*psmRuntimeField(self,0x124); - psmRuntimeField(psmRuntimeField(self,0x2C),8)=-1; + float elapsed=dt*psmInstanceB(self,0x124); + psmDescriptor2(psmInstanceB(self,0x2C),8)=-1; IParticleSystemInstance* instance=static_cast(self); - if(!psmRuntimeField(self,0x28)&&!psmRuntimeField(self,0x140)) + if(!psmInstanceB(self,0x28)&&!psmInstanceB(self,0x140)) { psmQueueInactive(reinterpret_cast(g_ParticleSystemManager),instance); - if(psmRuntimeField(self,0x18))reinterpret_cast(g_ParticleSystemManager)->removeInstance(instance); + if(psmInstanceB(self,0x18))reinterpret_cast(g_ParticleSystemManager)->removeInstance(instance); return; } - if(psmRuntimeField(self,0x155)||dt<=0)return; - if(!psmRuntimeField(self,0x157)&&psmRuntimeField(self,0x156)) - psmRuntimeField(self,0x157)=psmRuntimeField(self,0x156); - psmRuntimeField(self,0x13C)=0;psmRuntimeField(self,0x138)=0; - void* descriptor=psmRuntimeField(self,0x2C); - if(elapsed>psmRuntimeField(descriptor,0x70))elapsed=psmRuntimeField(descriptor,0x70); - for(int i=0;i<3;++i){psmRuntimeField(self,0xF8+4*i)=0x4B18967F;psmRuntimeField(self,0x104+4*i)=0xCB18967F;} - psmRuntimeField(self,0xC0)=psmRuntimeField(self,0xA4); + if(psmInstanceB(self,0x155)||dt<=0)return; + if(!psmInstanceB(self,0x157)&&psmInstanceB(self,0x156)) + psmInstanceB(self,0x157)=psmInstanceB(self,0x156); + psmInstanceB(self,0x13C)=0;psmInstanceB(self,0x138)=0; + void* descriptor=psmInstanceB(self,0x2C); + if(elapsed>psmDescriptor2(descriptor,0x70))elapsed=psmDescriptor2(descriptor,0x70); + for(int i=0;i<3;++i){psmInstanceB(self,0xF8+4*i)=0x4B18967F;psmInstanceB(self,0x104+4*i)=0xCB18967F;} + psmInstanceB(self,0xC0)=psmInstanceB(self,0xA4); psmType2RefreshTransform(self); - psmRuntimeField(self,0xB4)=psmRuntimeField(self,0xA4); - const double total=static_cast(elapsed)+psmRuntimeField(self,0xD0); + psmInstanceB(self,0xB4)=psmInstanceB(self,0xA4); + const double total=static_cast(elapsed)+psmInstanceB(self,0xD0); const unsigned int steps=static_cast(static_cast(100.0*total)); const double advanced=static_cast(steps)*0.01f; - psmRuntimeField(self,0xCC)=psmRuntimeField(self,0xF0); - psmRuntimeField(self,0xD0)=static_cast(total-advanced); - psmRuntimeField(self,0xF0)=static_cast(advanced+psmRuntimeField(self,0xF0)); - for(unsigned int i=psmRuntimeField(self,0x178)&psmRuntimeField(self,0x17C); - i!=psmRuntimeField(self,0x174);i=(i+1)&psmRuntimeField(self,0x17C)) - psmType2AdvanceParticle(self,psmRuntimeField(self,0x14)[i],i,0.01f,steps); - const double delay=static_cast(psmRuntimeField(self,0xEC))-elapsed; - psmRuntimeField(self,0xEC)=static_cast(delay); - if(delay>0){psmRuntimeField(self,0xF4)=psmRuntimeField(self,0xF0);return;} + psmInstanceB(self,0xCC)=psmInstanceB(self,0xF0); + psmInstanceB(self,0xD0)=static_cast(total-advanced); + psmInstanceB(self,0xF0)=static_cast(advanced+psmInstanceB(self,0xF0)); + for(unsigned int i=psmInstanceB(self,0x178)&psmInstanceB(self,0x17C); + i!=psmInstanceB(self,0x174);i=(i+1)&psmInstanceB(self,0x17C)) + psmType2AdvanceParticle(self,psmInstanceB(self,0x14)[i],i,0.01f,steps); + const double delay=static_cast(psmInstanceB(self,0xEC))-elapsed; + psmInstanceB(self,0xEC)=static_cast(delay); + if(delay>0){psmInstanceB(self,0xF4)=psmInstanceB(self,0xF0);return;} psmType2Emit(self,elapsed); - psmRuntimeField(self,0xA4)=psmRuntimeField(self,0xB4); - float* bounds=&psmRuntimeField(self,0xF8); - if(psmRuntimeField(self,0x28)) + psmInstanceB(self,0xA4)=psmInstanceB(self,0xB4); + float* bounds=&psmInstanceB(self,0xF8); + if(psmInstanceB(self,0x28)) { - for(int i=0;i<3;++i)bounds[i]-=psmRuntimeField(psmRuntimeField(self,0x2C),0x1B8); - for(int i=3;i<6;++i)bounds[i]+=psmRuntimeField(psmRuntimeField(self,0x2C),0x1B8); + for(int i=0;i<3;++i)bounds[i]-=psmDescriptor2(psmInstanceB(self,0x2C),0x1B8); + for(int i=3;i<6;++i)bounds[i]+=psmDescriptor2(psmInstanceB(self,0x2C),0x1B8); } - else{psmRuntimeField(self,0xF8)=psmRuntimeField(self,0xA4);psmRuntimeField(self,0x104)=psmRuntimeField(self,0xA4);} + else{psmInstanceB(self,0xF8)=psmInstanceB(self,0xA4);psmInstanceB(self,0x104)=psmInstanceB(self,0xA4);} const float dz=bounds[5]-bounds[2],dx=static_cast((static_cast(bounds[3])-bounds[0])*0.5); const double dy=(static_cast(bounds[4])-bounds[1])*0.5; - psmRuntimeField(self,0x11C)=static_cast(::sqrt(dz*0.5*(dz*0.5)+static_cast(dx)*dx+dy*dy)); + psmInstanceB(self,0x11C)=static_cast(::sqrt(dz*0.5*(dz*0.5)+static_cast(dx)*dx+dy*dy)); const float zsum=bounds[5]+bounds[2]; - psmRuntimeField(self,0x110)={static_cast((static_cast(bounds[3])+bounds[0])*0.5),static_cast((static_cast(bounds[4])+bounds[1])*0.5),zsum*0.5f}; - descriptor=psmRuntimeField(self,0x2C); - if(psmRuntimeField(descriptor,0x1C8)&&psmRuntimeField(descriptor,0x1D4)) + psmInstanceB(self,0x110)={static_cast((static_cast(bounds[3])+bounds[0])*0.5),static_cast((static_cast(bounds[4])+bounds[1])*0.5),zsum*0.5f}; + descriptor=psmInstanceB(self,0x2C); + if(psmDescriptor2(descriptor,0x1C8)&&psmDescriptor2(descriptor,0x1D4)) { - const float time=static_cast(static_cast(elapsed)*psmRuntimeField(descriptor,0x1C4)+psmRuntimeField(self,0x190)); - psmRuntimeField(self,0x190)=time; + const float time=static_cast(static_cast(elapsed)*psmDescriptor2(descriptor,0x1C4)+psmInstanceB(self,0x190)); + psmInstanceB(self,0x190)=time; const unsigned int frame=static_cast(static_cast(::floor(time))); - psmRuntimeField(self,0x18C)=static_cast(static_cast(time)-frame); - descriptor=psmRuntimeField(self,0x2C); - const unsigned int current=frame%psmRuntimeField(descriptor,0x1D4); - if(current!=psmRuntimeField(self,0x188)) + psmInstanceB(self,0x18C)=static_cast(static_cast(time)-frame); + descriptor=psmInstanceB(self,0x2C); + const unsigned int current=frame%psmDescriptor2(descriptor,0x1D4); + if(current!=psmInstanceB(self,0x188)) { - psmRuntimeField(self,0x188)=current; - const unsigned int next=(current+1)%psmRuntimeField(descriptor,0x1D4); - const unsigned int width=psmRuntimeField(descriptor,0x1D8); + psmInstanceB(self,0x188)=current; + const unsigned int next=(current+1)%psmDescriptor2(descriptor,0x1D4); + const unsigned int width=psmDescriptor2(descriptor,0x1D8); const unsigned int cx=current%width,nx=next%width; - const double cy=static_cast(current-cx)*psmRuntimeField(descriptor,0x1DC); - const float ny=static_cast(static_cast(next-nx)*psmRuntimeField(descriptor,0x1DC)); + const double cy=static_cast(current-cx)*psmDescriptor2(descriptor,0x1DC); + const float ny=static_cast(static_cast(next-nx)*psmDescriptor2(descriptor,0x1DC)); const double oneOverShort=0.000030518509447574615; - const double cu=(static_cast(cx)*psmRuntimeField(descriptor,0xAC) - +psmRuntimeField(descriptor,0x1E0)*oneOverShort)*32767.0; - psmRuntimeField(self,0x180)=static_cast(static_cast<__int64>(cu)); - descriptor=psmRuntimeField(self,0x2C); - const double cv=(psmRuntimeField(descriptor,0x1E2)*oneOverShort+cy*psmRuntimeField(descriptor,0xB0))*32767.0; - psmRuntimeField(self,0x182)=static_cast(static_cast<__int64>(cv)); - descriptor=psmRuntimeField(self,0x2C); - const double nu=(static_cast(nx)*psmRuntimeField(descriptor,0xAC) - +psmRuntimeField(descriptor,0x1E0)*oneOverShort)*32767.0; - psmRuntimeField(self,0x184)=static_cast(static_cast<__int64>(nu)); - descriptor=psmRuntimeField(self,0x2C); - const double nv=(psmRuntimeField(descriptor,0x1E2)*oneOverShort+static_cast(ny)*psmRuntimeField(descriptor,0xB0))*32767.0; - psmRuntimeField(self,0x186)=static_cast(static_cast<__int64>(nv)); + const double cu=(static_cast(cx)*psmDescriptor2(descriptor,0xAC) + +psmDescriptor2(descriptor,0x1E0)*oneOverShort)*32767.0; + psmInstanceB(self,0x180)=static_cast(static_cast<__int64>(cu)); + descriptor=psmInstanceB(self,0x2C); + const double cv=(psmDescriptor2(descriptor,0x1E2)*oneOverShort+cy*psmDescriptor2(descriptor,0xB0))*32767.0; + psmInstanceB(self,0x182)=static_cast(static_cast<__int64>(cv)); + descriptor=psmInstanceB(self,0x2C); + const double nu=(static_cast(nx)*psmDescriptor2(descriptor,0xAC) + +psmDescriptor2(descriptor,0x1E0)*oneOverShort)*32767.0; + psmInstanceB(self,0x184)=static_cast(static_cast<__int64>(nu)); + descriptor=psmInstanceB(self,0x2C); + const double nv=(psmDescriptor2(descriptor,0x1E2)*oneOverShort+static_cast(ny)*psmDescriptor2(descriptor,0xB0))*32767.0; + psmInstanceB(self,0x186)=static_cast(static_cast<__int64>(nv)); } } else { - for(int i=0;i<4;++i)psmRuntimeField(self,0x180+2*i)=psmRuntimeField(psmRuntimeField(self,0x2C),0x1E0+2*(i%2)); + for(int i=0;i<4;++i)psmInstanceB(self,0x180+2*i)=psmDescriptor2(psmInstanceB(self,0x2C),0x1E0+2*(i%2)); } - if(psmRuntimeField(self,0x28)&&psmRuntimeField(self,0x140)) + if(psmInstanceB(self,0x28)&&psmInstanceB(self,0x140)) { - float* newest=psmRuntimeField(self,0x14)[psmRuntimeField(self,0x194)]; - *reinterpret_cast(newest+4)=psmRuntimeField(self,0xA4); + float* newest=psmInstanceB(self,0x14)[psmInstanceB(self,0x194)]; + *reinterpret_cast(newest+4)=psmInstanceB(self,0xA4); } } diff --git a/Code/BF2/Geom/ParticleSystem/ParticleInstanceType3.inl b/Code/BF2/Geom/ParticleSystem/ParticleInstanceType3.inl index 41adfe761..90d2e5cfc 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleInstanceType3.inl +++ b/Code/BF2/Geom/ParticleSystem/ParticleInstanceType3.inl @@ -20,19 +20,19 @@ typedef ::renddx9abi::HostString PsmType3ChildName; // The retail test `cmp dword ptr [esi+80h], 0` is the VC7.1 _Mysize of the +0x6C string. void psmType3ResolveChildTemplate(void* descriptor) { - if (psmRuntimeField(descriptor, 0x88)) - psmRuntimeField(descriptor, 0x88) = 0; - const PsmType3ChildName& name = psmRuntimeField(descriptor, 0x6C); + if (psmDescriptor3(descriptor, 0x88)) + psmDescriptor3(descriptor, 0x88) = 0; + const PsmType3ChildName& name = psmDescriptor3(descriptor, 0x6C); if (!name.empty()) - psmRuntimeField(descriptor, 0x88) = psmFindTemplateByName(name.c_str()); + psmDescriptor3(descriptor, 0x88) = psmFindTemplateByName(name.c_str()); } class ParticleInstanceType3 : public IParticleSystemInstance { - unsigned char m_data[0x21C]; - template T& at(unsigned int offset) { return psmRuntimeField(this, offset); } + unsigned char m_data[PSM_INSTANCE_DATA(0x220)]; + template T& at(unsigned int offset) { return psmInstanceB(this, offset); } template const T& at(unsigned int offset) const - { return *reinterpret_cast(reinterpret_cast(this) + offset); } + { return psmInstanceB(const_cast(this), offset); } public: // PE 10182110, 1019 B. Every store below is in the shipped order; bytes +5/+6/+7 are not written // here (the factory tail writes +5, psmAddActive writes +6/+7) and neither are +0xCC, +0xD0, @@ -62,16 +62,16 @@ public: // fucompp against 0: an exactly-zero emit time takes the lifetime-only // arm, NaN takes the emit-time arm (and then keeps the lifetime, `fcom` being unordered). // Both arms truncate (RC=11) (capacityTime * emitFrequency + 10). - const float emitTime=psmRuntimeField(descriptor,0x144); - double capacityTime=static_cast(psmRuntimeField(descriptor,0x90)) - +psmRuntimeField(descriptor,0x8C); - if (emitTime!=0 && !psmRuntimeField(descriptor,0x148) && capacityTime>emitTime) + const float emitTime=psmDescriptor3(descriptor,0x144); + double capacityTime=static_cast(psmDescriptor3(descriptor,0x90)) + +psmDescriptor3(descriptor,0x8C); + if (emitTime!=0 && !psmDescriptor3(descriptor,0x148) && capacityTime>emitTime) capacityTime=emitTime; - at(0x218)=static_cast(capacityTime*psmRuntimeField(descriptor,0x0C)+10.0); + at(0x218)=static_cast(capacityTime*psmDescriptor3(descriptor,0x0C)+10.0); at(8)=0; // No allocation-null guard: the shipped body stores through the answer at 10182393. at(0x14)=static_cast( - ::renddx9abi::engineAlloc(at(0x218)*4u+4u)); + ::renddx9abi::engineAlloc(at(0x218)*kPsmPointerSize+kPsmPointerSize)); at(0x14)[0]=0; at(0x1C)={0,0,0}; at(0xFC)={0,0,0}; at(0x108)={0,0,0}; @@ -81,7 +81,7 @@ public: for (unsigned int offset=0x160;offset<=0x1F0;offset+=0x10) { at(offset)=0; at(offset+4)=1; at(offset+8)=0; at(offset+12)=0; } // lazy child resolution when slot 89 did not (or could not yet) resolve the name. - if (!psmRuntimeField(descriptor,0x88)) + if (!psmDescriptor3(descriptor,0x88)) psmType3ResolveChildTemplate(descriptor); at(4)=0; } @@ -89,7 +89,7 @@ public: // list (no counter: unlike types 0/4 there is none for this pool) and frees the pointer list. // The records' child instances are NOT released here. Retail destroys an emitter only through // the drained pending list, which it reaches with zero live particles, so no child is orphaned - // on that path; the unrecovered manager teardown is the only other route. + // on that path. Manager teardown uses level unload to destroy any remaining instances. ~ParticleInstanceType3() override { ParticleSystemManager* const manager=reinterpret_cast(g_ParticleSystemManager); @@ -98,7 +98,7 @@ public: for (unsigned int i=0;at(0x14)[i];++i) { unsigned char* const record=at(0x14)[i]; - psmRuntimeField(record,0)=manager->m_type3FreeList; + psmRecordLink(record, 3)=manager->m_type3FreeList; manager->m_type3FreeList=record; } ::renddx9abi::engineFree(at(0x14)); @@ -114,25 +114,25 @@ public: if (self->at(0x28)) { void* const descriptor=self->at(0x2C); - self->reserved41(static_cast(static_cast(psmRuntimeField(descriptor,0x90)) - +psmRuntimeField(descriptor,0x8C))); + self->reserved41(static_cast(static_cast(psmDescriptor3(descriptor,0x90)) + +psmDescriptor3(descriptor,0x8C))); } ParticleSystemManager* const manager=reinterpret_cast(g_ParticleSystemManager); while (self->at(0x14)[0]) { unsigned char* const record=self->at(0x14)[0]; - if (psmRuntimeField(record,0xAC)) + if (psmRecordPointer(record, 3)) { // The record's child is read twice, exactly as 101816A5/101816B8 do. - psmRuntimeField(psmRuntimeField(record,0xAC),5)=0; + psmInstance(psmRecordPointer(record, 3),5)=0; reinterpret_cast(g_ParticleSystemManager) - ->removeInstance(psmRuntimeField(record,0xAC)); + ->removeInstance(psmRecordPointer(record, 3)); } --self->at(0x28); unsigned char** const records=self->at(0x14); records[0]=records[self->at(0x28)]; self->at(0x14)[self->at(0x28)]=0; - psmRuntimeField(record,0)=manager->m_type3FreeList; + psmRecordLink(record, 3)=manager->m_type3FreeList; manager->m_type3FreeList=record; } self->at(0x214)=0; self->at(0x210)=0; self->at(0x211)=0; @@ -152,9 +152,9 @@ public: if (!at(4)) psmAddActive(manager,this,firstPerson); void* const descriptor=at(0x2C); at(0x144)=1; at(0x21C)=1; - at(0xE8)=psmRuntimeField(descriptor,0x144); // emit time - at(0xF0)=psmRuntimeField(descriptor,0x154); // emit delay - at(0xEC)=psmRuntimeField(descriptor,0x08); // prewarm time + at(0xE8)=psmDescriptor3(descriptor,0x144); // emit time + at(0xF0)=psmDescriptor3(descriptor,0x154); // emit delay + at(0xEC)=psmDescriptor3(descriptor,0x08); // prewarm time at(0xF4)=0; at(0xF8)=0; at(0xD0)=0; at(0x21E)=1; at(0x21F)=1; at(0x124)=dx9rend::rendererFrameOrdinal(); @@ -186,13 +186,14 @@ public: void reserved08() override { at(0x18)=1; at(0x10)=0; at(0x0C)=0; at(0x30)=0; } void reserved09(bool value) override { psmShared13SetVisible(this,value); } // 101839F0 (t1) bool reserved10() const override { return psmShared13IsVisible(this); } // 10183A00 (t1) - void reserved11(int value) override { at(0x10)=value; } // 1017A500 (all) - int reserved12() const override { return at(0x10); } // 1010DE20 (all) - void reserved13(int value) override { at(0x30)=value; } // 1017C200 (all) + void reserved11(intptr_t value) override { at(0x10)=value; } // 1017A500 (all) + intptr_t reserved12() const override { return at(0x10); } // 1010DE20 (all) + void reserved13(intptr_t value) override { at(0x30)=value; } // 1017C200 (all) // PE 10181790: `add ecx,34h; jmp Mat4::operator=` - the assignment's own `this` is returned. void* reserved14(const void* value) override { at(0x34)=*static_cast(value); return &at(0x34); } const void* reserved15() const override { return &at(0x34); } // 10179DD0 (all) // the inherited-velocity direction. Loads z, y, x, then stores y, x, z. + // PE 0x101817F0 void reserved16(const Vec3& value) override { const float z=value.z, y=value.y, x=value.x; @@ -201,7 +202,7 @@ public: const Vec3& reserved17() const override { return at(0xD4); } // the current collision plane. All four source words are loaded before the first // store (z, x, y, then the distance at 10182725); xyz land at +0x200 in the order y, z, x, are - // normalised in place, and only then is the saved distance written to +0x20C. + // normalised in place, and only then is the saved distance written to +0x20C. PE 0x10182710 void reserved18(const void* value) override { const float* const source=static_cast(value); @@ -210,19 +211,24 @@ public: psmNormalize3(&at(0x200)); at(0x20C)=distance; } + // PE 0x10181640 void reserved19(float value) override { at(0xE4)=value; } float reserved20() const override { return at(0xE4); } void reserved21(int,int) override { at(0x154)=1; } // 10181580, `retn 8` + // PE 0x10181590 void reserved22(float value) override { at(0x158)=value; } float reserved23() const override { return at(0x158); } + // PE 0x101815B0 void reserved24(float value) override { at(0x130)=value; } float reserved25() const override { return at(0x130); } void reserved26(float value) override { psmShared13SetSpeedScale(this,value); } // 10186110 (t1) float reserved27() const override { return psmShared13SpeedScale(this); } // 10183A10 (t1) void reserved28(const Vec3& value) override { psmShared13SetDirectionScale(this,value); } // 10183A30 (t1) const Vec3& reserved29() const override { return psmShared13DirectionScale(this); } // 10183A20 (t1) + // PE 0x101815D0 void reserved30(float value) override { at(0x128)=value; } float reserved31() const override { return at(0x128); } + // PE 0x10181620 void reserved32(float value) override { at(0xE0)=value; } float reserved33() const override { return at(0xE0); } int reserved34() const override { return at(0x218); } @@ -234,10 +240,11 @@ public: const Vec3& getPosition() const override { return at(0xB4); } // 1017C240 (all) void reserved41(float value) override { psmType3Update(this,value); } // the common reclassification body (same shape as types 0/2/4). + // PE 0x10181530 void reserved42(bool value) override { - if (at(4) && value!=static_cast(at(6))) - { at(7)=value; psmReclassification(reinterpret_cast(g_ParticleSystemManager)).insert(reinterpret_cast(this)); } + if (at(4) && static_cast(value)!=at(6)) + { at(7)=value; psmQueueReclassification(reinterpret_cast(g_ParticleSystemManager),this); } } float getGasCloudRadius() const override { return 1; } // 1017A510 (t1,t2,t4) void setPlayer(void*) override {} // 100E13B0 null body @@ -245,11 +252,15 @@ public: void setMaterial(int) override {} // 100E13B0 null body int getMaterial() const override { return -1; } void setEffectController(world::IEffectController* value) override // 101BB440 (all) - { at(0xC)=value; reserved11(reinterpret_cast(value ? value->getObject() : 0)); } + { at(0xC)=value; reserved11(reinterpret_cast(value ? value->getObject() : 0)); } world::IEffectController* getEffectController() const override { return at(0xC); } bool getWaterSide() const override { return false; } // 10083AF0 (t4) }; +#if defined(_M_IX86) static_assert(sizeof(ParticleInstanceType3)==0x220,"emitter instance PE 100D3E5D allocation / 10182110 layout"); +#else +static_assert(sizeof(ParticleInstanceType3)==kPsmInstanceSize,"x64 instance layout, ParticleRawLayout.h"); +#endif // Factory case 3 (PE 100D3E5D): allocate 0x220 and construct; the caller's common tail at 100D3E03 // writes byte +5 = 0 and appends to the master list, as for types 0/2/4. diff --git a/Code/BF2/Geom/ParticleSystem/ParticleInstanceType3Emission.inl b/Code/BF2/Geom/ParticleSystem/ParticleInstanceType3Emission.inl index e1305aecb..52cd5fa33 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleInstanceType3Emission.inl +++ b/Code/BF2/Geom/ParticleSystem/ParticleInstanceType3Emission.inl @@ -11,9 +11,9 @@ const float psmType3DegreesToRadians = 0.01745329238474369f; // first, then y, then x; each is a float product. void psmType3EmissionDirection(float* output, void* descriptor, void* self) { - const float z=psmRuntimeField(descriptor,0x160)*psmRuntimeField(self,0x150); - const float y=psmRuntimeField(descriptor,0x15C)*psmRuntimeField(self,0x14C); - const float x=psmRuntimeField(descriptor,0x158)*psmRuntimeField(self,0x148); + const float z=psmDescriptor3(descriptor,0x160)*psmInstanceB(self,0x150); + const float y=psmDescriptor3(descriptor,0x15C)*psmInstanceB(self,0x14C); + const float x=psmDescriptor3(descriptor,0x158)*psmInstanceB(self,0x148); output[0]=x; output[1]=y; output[2]=z; } @@ -25,10 +25,10 @@ void psmType3EmissionSphere(float* output, void* descriptor, void* self, unsigne const double theta=psmEmissionRandomInteger()*static_cast(1.8725351935700019e-7f); const float savedTheta=static_cast(theta), sineTheta=static_cast(::sin(theta)); const float yRandom=static_cast(psmEmissionUnit()), xRandom=static_cast(psmEmissionUnit()); - const double zRadius=psmEmissionRandomInteger()*static_cast(psmRuntimeField(descriptor,0x18)) + const double zRadius=psmEmissionRandomInteger()*static_cast(psmDescriptor3(descriptor,0x18)) *0.000000059604644775390625; - const double xRadius=static_cast(xRandom)*psmRuntimeField(descriptor,0x10); - const double yRadius=static_cast(yRandom)*psmRuntimeField(descriptor,0x14); + const double xRadius=static_cast(xRandom)*psmDescriptor3(descriptor,0x10); + const double yRadius=static_cast(yRandom)*psmDescriptor3(descriptor,0x14); psmRuntimeField(record,0x44)=static_cast(::cos(phi)*xRadius*sineTheta); psmRuntimeField(record,0x48)=static_cast(::sin(phi)*yRadius*sineTheta); psmRuntimeField(record,0x4C)=static_cast(::cos(savedTheta)*zRadius); @@ -40,12 +40,12 @@ void psmType3EmissionSphere(float* output, void* descriptor, void* self, unsigne // radius component; the distributions are sampled Z, Y, X. void psmType3EmissionCylinder(float* output, void* descriptor, void* self, unsigned char* record) { - const double angle=(psmEmissionSymmetric()*psmRuntimeField(descriptor,0x58) - +psmRuntimeField(descriptor,0x5C))*psmType3DegreesToRadians; + const double angle=(psmEmissionSymmetric()*psmDescriptor3(descriptor,0x58) + +psmDescriptor3(descriptor,0x5C))*psmType3DegreesToRadians; const float cosine=static_cast(::cos(angle)), sine=static_cast(::sin(angle)); unsigned int axis=0; // 10183CEB compares radius.x with itself: no effect - if (psmRuntimeField(descriptor,0x14)>psmRuntimeField(descriptor,0x10)) axis=1; - if (psmRuntimeField(descriptor,0x18)>psmRuntimeField(descriptor,0x10+4*axis)) axis=2; + if (psmDescriptor3(descriptor,0x14)>psmDescriptor3(descriptor,0x10)) axis=1; + if (psmDescriptor3(descriptor,0x18)>psmDescriptor3(descriptor,0x10+4*axis)) axis=2; unsigned char* const bytes=static_cast(descriptor); const float z=static_cast(psmEmissionDistribution(bytes+0x44)); const float y=static_cast(psmEmissionDistribution(bytes+0x30)); @@ -54,7 +54,7 @@ void psmType3EmissionCylinder(float* output, void* descriptor, void* self, unsig if (axis==0) { position[0]=static_cast(x); position[1]=y*sine; position[2]=z*cosine; } else if (axis==1) { position[0]=static_cast(x*sine); position[1]=y; position[2]=z*cosine; } else { position[0]=static_cast(x*sine); position[2]=z; position[1]=y*cosine; } - if (psmRuntimeField(descriptor,0x188)==1) + if (psmDescriptor3(descriptor,0x188)==1) { output[0]=position[0]; output[1]=position[1]; output[2]=position[2]; output[axis]=0; @@ -64,6 +64,7 @@ void psmType3EmissionCylinder(float* output, void* descriptor, void* self, unsig } +// PE 0x10183E90 (ecx = output, edx = descriptor, `retn 8`): the samples are drawn z, y, x. void psmType3EmissionBox(float* output, void* descriptor, void* self, unsigned char* record) { unsigned char* const bytes=static_cast(descriptor); @@ -74,55 +75,55 @@ void psmType3EmissionBox(float* output, void* descriptor, void* self, unsigned c psmType3EmissionDirection(output,descriptor,self); } -// The particle birth shared by PE 10183080 (virtual +0x94) and the copy 101827F0 inlines at +// Particle birth shared by PE 0x10183080 (virtual +0x94) and the inline copy in PE 0x101827F0. // The two compiled copies are identical instruction for instruction except for // the association of the direction rotation's three-term sums, which `emissionLoopOrder` selects. // [CHOSEN, not recovered] packaging: one body with that flag instead of two near-identical copies. void psmType3InitRecord(void* self, unsigned char* record, bool emissionLoopOrder) { - ++psmRuntimeField(self,0x13C); - void* descriptor=psmRuntimeField(self,0x2C); - const double lifetime=psmEmissionRandomInteger()*static_cast(psmRuntimeField(descriptor,0x8C)) - *0.000000059604644775390625+psmRuntimeField(descriptor,0x90); + ++psmInstanceB(self,0x13C); + void* descriptor=psmInstanceB(self,0x2C); + const double lifetime=psmEmissionRandomInteger()*static_cast(psmDescriptor3(descriptor,0x8C)) + *0.000000059604644775390625+psmDescriptor3(descriptor,0x90); psmRuntimeField(record,0x80)=static_cast(lifetime); psmRuntimeField(record,0x84)=static_cast(1.0/lifetime); // unrounded divisor - psmRuntimeField(record,0x7C)=psmRuntimeField(self,0xE0); + psmRuntimeField(record,0x7C)=psmInstanceB(self,0xE0); psmRuntimeField(record,0x5C)=psmRuntimeField(record,0x7C)*psmRuntimeField(record,0x84); - psmRuntimeField(record,0x68)=psmRuntimeField(self,0x158); - psmRuntimeField(record,0x6C)=psmRuntimeField(self,0x158); + psmRuntimeField(record,0x68)=psmInstanceB(self,0x158); + psmRuntimeField(record,0x6C)=psmInstanceB(self,0x158); const float firstRandom=static_cast(psmEmissionSymmetric()); psmEmissionRaw(); // a discarded draw (10183149), as in the siblings const double spin=psmEmissionSymmetric(); - descriptor=psmRuntimeField(self,0x2C); - const double spinX=spin*psmRuntimeField(descriptor,0x124), spinY=spin*psmRuntimeField(descriptor,0x128); - psmRuntimeField(record,0x9C)=static_cast(spin*psmRuntimeField(descriptor,0x12C)); + descriptor=psmInstanceB(self,0x2C); + const double spinX=spin*psmDescriptor3(descriptor,0x124), spinY=spin*psmDescriptor3(descriptor,0x128); + psmRuntimeField(record,0x9C)=static_cast(spin*psmDescriptor3(descriptor,0x12C)); psmRuntimeField(record,0x94)=static_cast(spinX); psmRuntimeField(record,0x98)=static_cast(spinY); // Rotation speed: base (+0xAC) plus a signed random part (+0xA0); a negative draw subtracts the // base so the magnitude grows either way. The draw is exactly representable, so its sign is // unambiguous (the compare runs on the unrounded value). const float rate=static_cast(psmEmissionSymmetric()); - descriptor=psmRuntimeField(self,0x2C); - const double rateX=static_cast(rate)*psmRuntimeField(descriptor,0xA0); - const float rateY=static_cast(static_cast(rate)*psmRuntimeField(descriptor,0xA4)); - const float rateZ=static_cast(static_cast(rate)*psmRuntimeField(descriptor,0xA8)); + descriptor=psmInstanceB(self,0x2C); + const double rateX=static_cast(rate)*psmDescriptor3(descriptor,0xA0); + const float rateY=static_cast(static_cast(rate)*psmDescriptor3(descriptor,0xA4)); + const float rateZ=static_cast(static_cast(rate)*psmDescriptor3(descriptor,0xA8)); if (!(rate<0)) { - psmRuntimeField(record,0x90)=static_cast(static_cast(rateZ)+psmRuntimeField(descriptor,0xB4)); - psmRuntimeField(record,0x88)=static_cast(rateX+psmRuntimeField(descriptor,0xAC)); - psmRuntimeField(record,0x8C)=static_cast(static_cast(rateY)+psmRuntimeField(descriptor,0xB0)); + psmRuntimeField(record,0x90)=static_cast(static_cast(rateZ)+psmDescriptor3(descriptor,0xB4)); + psmRuntimeField(record,0x88)=static_cast(rateX+psmDescriptor3(descriptor,0xAC)); + psmRuntimeField(record,0x8C)=static_cast(static_cast(rateY)+psmDescriptor3(descriptor,0xB0)); } else { - const float negativeY=-psmRuntimeField(descriptor,0xB0), negativeZ=-psmRuntimeField(descriptor,0xB4); + const float negativeY=-psmDescriptor3(descriptor,0xB0), negativeZ=-psmDescriptor3(descriptor,0xB4); psmRuntimeField(record,0x90)=static_cast(static_cast(negativeZ)+rateZ); - psmRuntimeField(record,0x88)=static_cast(rateX+(-static_cast(psmRuntimeField(descriptor,0xAC)))); + psmRuntimeField(record,0x88)=static_cast(rateX+(-static_cast(psmDescriptor3(descriptor,0xAC)))); psmRuntimeField(record,0x8C)=static_cast(static_cast(negativeY)+rateY); } // An emitter type outside 0..3 writes no position: the record keeps its previous occupant's. float direction[3]={0,0,0}; - descriptor=psmRuntimeField(self,0x2C); - switch (psmRuntimeField(descriptor,0x188)) + descriptor=psmInstanceB(self,0x2C); + switch (psmDescriptor3(descriptor,0x188)) { case 0: psmType3EmissionSphere(direction,descriptor,self,record); break; case 1: case 2: psmType3EmissionCylinder(direction,descriptor,self,record); break; @@ -131,12 +132,12 @@ void psmType3InitRecord(void* self, unsigned char* record, bool emissionLoopOrde const float randomX=static_cast(psmEmissionSymmetric()); const float randomY=static_cast(psmEmissionSymmetric()); const float randomZ=static_cast(psmEmissionSymmetric()); - descriptor=psmRuntimeField(self,0x2C); + descriptor=psmInstanceB(self,0x2C); Mat4 rotation,axis,copy; - psmEmissionRotation(rotation,randomX*psmRuntimeField(descriptor,0x134),0); - psmEmissionRotation(axis,randomY*psmRuntimeField(descriptor,0x138),1); + psmEmissionRotation(rotation,randomX*psmDescriptor3(descriptor,0x134),0); + psmEmissionRotation(axis,randomY*psmDescriptor3(descriptor,0x138),1); copy=rotation; psmEmissionRotateMultiply(rotation,copy,axis); - psmEmissionRotation(axis,randomZ*psmRuntimeField(descriptor,0x13C),2); + psmEmissionRotation(axis,randomZ*psmDescriptor3(descriptor,0x13C),2); copy=rotation; psmEmissionRotateMultiply(rotation,copy,axis); const float* const m=rotation.m; const double dx=direction[0], dy=direction[1], dz=direction[2]; @@ -154,20 +155,20 @@ void psmType3InitRecord(void* self, unsigned char* record, bool emissionLoopOrde direction[1]=static_cast(m[9]*dz+m[5]*dy+m[1]*dx); direction[0]=static_cast(m[8]*dz+m[4]*dy+m[0]*dx); } - descriptor=psmRuntimeField(self,0x2C); - float speed=static_cast((psmRuntimeField(descriptor,0x140) - -static_cast(firstRandom)*psmRuntimeField(descriptor,0x130))*psmRuntimeField(self,0x138)); - const float emitTime=psmRuntimeField(descriptor,0x144); - const double t=emitTime>0 ? 1.0-static_cast(psmRuntimeField(self,0xE8))/emitTime : 0.0; - const float envelope=static_cast(t*psmRuntimeField(descriptor,0x10C) - +t*t*psmRuntimeField(descriptor,0x108)+t*t*t*psmRuntimeField(descriptor,0x104) - +psmRuntimeField(descriptor,0x110)); + descriptor=psmInstanceB(self,0x2C); + float speed=static_cast((psmDescriptor3(descriptor,0x140) + -static_cast(firstRandom)*psmDescriptor3(descriptor,0x130))*psmInstanceB(self,0x138)); + const float emitTime=psmDescriptor3(descriptor,0x144); + const double t=emitTime>0 ? 1.0-static_cast(psmInstanceB(self,0xE8))/emitTime : 0.0; + const float envelope=static_cast(t*psmDescriptor3(descriptor,0x10C) + +t*t*psmDescriptor3(descriptor,0x108)+t*t*t*psmDescriptor3(descriptor,0x104) + +psmDescriptor3(descriptor,0x110)); speed=static_cast(static_cast(psmEmissionClamp(envelope))*speed); - descriptor=psmRuntimeField(self,0x2C); - if (!psmRuntimeField(descriptor,0x165)) + descriptor=psmInstanceB(self,0x2C); + if (!psmDescriptor3(descriptor,0x165)) { // PE 10079610 (point, in place) and 100A6120 (vector, in place) through the world matrix. - const float* const w=&psmRuntimeField(self,0x74); + const float* const w=&psmInstanceB(self,0x74); float* const position=&psmRuntimeField(record,0x44); const double px=position[0], py=position[1], pz=position[2]; const double rz=static_cast(w[2])*px+static_cast(w[10])*pz+static_cast(w[6])*py+w[14]; @@ -179,11 +180,11 @@ void psmType3InitRecord(void* self, unsigned char* record, bool emissionLoopOrde direction[1]=static_cast(static_cast(w[9])*vz+static_cast(w[1])*vx+static_cast(w[5])*vy); direction[0]=static_cast(static_cast(w[8])*vz+static_cast(w[4])*vy+static_cast(w[0])*vx); // Inherited velocity: +0xE4 (virtual +0x4C) times the direction at +0xD4 (virtual +0x40). - const double scale=psmRuntimeField(self,0xE4); - const float inheritedX=static_cast(scale*psmRuntimeField(self,0xD4)); - const float inheritedY=static_cast(scale*psmRuntimeField(self,0xD8)); + const double scale=psmInstanceB(self,0xE4); + const float inheritedX=static_cast(scale*psmInstanceB(self,0xD4)); + const float inheritedY=static_cast(scale*psmInstanceB(self,0xD8)); const float vyScaled=direction[1]*speed, vzScaled=direction[2]*speed; - psmRuntimeField(record,0x78)=static_cast(vzScaled+scale*psmRuntimeField(self,0xDC)); + psmRuntimeField(record,0x78)=static_cast(vzScaled+scale*psmInstanceB(self,0xDC)); psmRuntimeField(record,0x70)=static_cast(static_cast(direction[0])*speed+inheritedX); psmRuntimeField(record,0x74)=vyScaled+inheritedY; } @@ -196,39 +197,31 @@ void psmType3InitRecord(void* self, unsigned char* record, bool emissionLoopOrde } // No capacity check here: 10183080 appends even when count == capacity (the emission loop // checks before it pops a record, the virtual +0x94 path does not). Same in the type-0 sibling. - psmRuntimeField(self,0x14)[psmRuntimeField(self,0x28)]=record; - ++psmRuntimeField(self,0x28); - psmRuntimeField(self,0x14)[psmRuntimeField(self,0x28)]=0; + psmInstanceB(self,0x14)[psmInstanceB(self,0x28)]=record; + ++psmInstanceB(self,0x28); + psmInstanceB(self,0x14)[psmInstanceB(self,0x28)]=0; // THE child. createInstance is the manager's own virtual (+0x14): pool initialisation, the // per-type factory and the master-list append all apply. The resolved template can be of ANY type. - descriptor=psmRuntimeField(self,0x2C); - IParticleSystemTemplate* const childTemplate=psmRuntimeField(descriptor,0x88); + descriptor=psmInstanceB(self,0x2C); + IParticleSystemTemplate* const childTemplate=psmDescriptor3(descriptor,0x88); if (childTemplate) { IParticleSystemInstance* const child= reinterpret_cast(g_ParticleSystemManager)->createInstance(childTemplate); - psmRuntimeField(record,0xAC)=child; + psmRecordPointer(record, 3)=child; // No null guard in retail: 101835D4 (slot +0x94) / 10182F3A (the copy timed emission // inlines) dereference the answer at once - it is null only when the engine allocator fails. - // [CHOSEN, not recovered] A named stop at the fault point, as in advanceParticle. - if (!child) - { - RD9_FRONTIER_AT("dice::hfe::geom::ParticleSystemEmitter::newParticle (createInstance returned " - "null; retail faults at 101835D4, or 10182F3A on the timed-emission copy)", - self, 0x94); - std::abort(); - } - child->reserved13(reinterpret_cast(record+4)); // parent matrix = this particle's + child->reserved13(reinterpret_cast(record+4)); // parent matrix = this particle's // Every following use re-reads record+0xAC, as the instructions do. - psmRuntimeField(psmRuntimeField(record,0xAC),5)=1; // not bucket-updated - psmRuntimeField(psmRuntimeField(record,0xAC),8)= - psmRuntimeField(self,8); // FOV-override byte (setFovOverride) - psmRuntimeField(record,0xAC)->reserved03(psmRuntimeField(self,6)!=0); - psmRuntimeField(record,0xAC)->reserved30(psmRuntimeField(self,0x128)); - psmRuntimeField(record,0xAC)->reserved22(psmRuntimeField(self,0x158)); + psmInstance(psmRecordPointer(record, 3),5)=1; // not bucket-updated + psmInstance(psmRecordPointer(record, 3),8)= + psmInstanceB(self,8); // FOV-override byte (setFovOverride) + psmRecordPointer(record, 3)->reserved03(psmInstanceB(self,6)!=0); + psmRecordPointer(record, 3)->reserved30(psmInstanceB(self,0x128)); + psmRecordPointer(record, 3)->reserved22(psmInstanceB(self,0x158)); } - else psmRuntimeField(record,0xAC)=0; + else psmRecordPointer(record, 3)=0; } // PE 10183080, 1467 B (virtual +0x94): pop a record and initialise it at the current emitter @@ -238,7 +231,7 @@ void psmType3NewParticle(void* self) { ParticleSystemManager* const manager=reinterpret_cast(g_ParticleSystemManager); unsigned char* const record=static_cast(manager->m_type3FreeList); - manager->m_type3FreeList=record ? psmRuntimeField(record,0) : 0; + manager->m_type3FreeList=record ? psmRecordLink(record, 3) : 0; if (!record) return; psmType3InitRecord(self,record,false); } @@ -246,79 +239,79 @@ void psmType3NewParticle(void* self) // PE 101827F0, 2187 B: timed emission. `dt` is unused, as in types 0 and 4. void psmType3Emit(void* self, float /*dt*/) { - if (!psmRuntimeField(self,0x144)) return; + if (!psmInstanceB(self,0x144)) return; const unsigned int frame=static_cast(dx9rend::g_rendererBase)->getFrameOrdinal(); // Nothing refreshes +0x124 for a type-3 instance after start: the sprite renderer's prepare // walk skips reserved01() != 0, and no other type-3 path writes it. An emitter therefore emits // for at most ~60 frames after start() (stock emitters use 0.1-0.3 s emit times). - if (psmRuntimeField(self,0x124)+60u(self,0x124)+60u(self,0x21F)=psmRuntimeField(self,0x21E); - psmRuntimeField(self,0x21E)=0; + psmInstanceB(self,0x21F)=psmInstanceB(self,0x21E); + psmInstanceB(self,0x21E)=0; return; } // No pool-pressure throttle (types 0/4 scale the frequency by the tier thresholds); the second // factor (+0x12C) is only ever 1.0 for type 3 - the coverage pass that writes the sprite // equivalent skips non-zero types - but the shipped multiply is kept. - const float interval=static_cast(1.0/(static_cast(psmRuntimeField(psmRuntimeField(self,0x2C),0x0C)) - *psmRuntimeField(self,0x130)*psmRuntimeField(self,0x12C))); - if (psmRuntimeField(self,0x21C)) + const float interval=static_cast(1.0/(static_cast(psmDescriptor3(psmInstanceB(self,0x2C),0x0C)) + *psmInstanceB(self,0x130)*psmInstanceB(self,0x12C))); + if (psmInstanceB(self,0x21C)) { - psmRuntimeField(self,0xC0)=psmRuntimeField(self,0xB4); - psmRuntimeField(self,0x21C)=0; + psmInstanceB(self,0xC0)=psmInstanceB(self,0xB4); + psmInstanceB(self,0x21C)=0; } - while (static_cast(interval)+psmRuntimeField(self,0xF8)<=psmRuntimeField(self,0xF4)) + while (static_cast(interval)+psmInstanceB(self,0xF8)<=psmInstanceB(self,0xF4)) { - if (psmRuntimeField(self,0xE8)!=0) // `fucompp`: NaN counts down too + if (psmInstanceB(self,0xE8)!=0) // `fucompp`: NaN counts down too { - const double remaining=static_cast(psmRuntimeField(self,0xE8))-interval; - psmRuntimeField(self,0xE8)=static_cast(remaining); + const double remaining=static_cast(psmInstanceB(self,0xE8))-interval; + psmInstanceB(self,0xE8)=static_cast(remaining); if (remaining<=0) { IParticleSystemInstance* const instance=static_cast(self); instance->reserved04(); - if (psmRuntimeField(psmRuntimeField(self,0x2C),0x148)) - instance->reserved03(psmRuntimeField(self,6)!=0); + if (psmDescriptor3(psmInstanceB(self,0x2C),0x148)) + instance->reserved03(psmInstanceB(self,6)!=0); return; } } - const bool visible=psmRuntimeField(self,0x21E)!=0; - const float emitted=static_cast(static_cast(interval)+psmRuntimeField(self,0xF8)); - psmRuntimeField(self,0xF8)=emitted; - if (!visible || psmRuntimeField(self,0x28)>=psmRuntimeField(self,0x218)) + const bool visible=psmInstanceB(self,0x21E)!=0; + const float emitted=static_cast(static_cast(interval)+psmInstanceB(self,0xF8)); + psmInstanceB(self,0xF8)=emitted; + if (!visible || psmInstanceB(self,0x28)>=psmInstanceB(self,0x218)) continue; float fraction=0; - if (psmRuntimeField(self,0xF4)>psmRuntimeField(self,0xCC)) - fraction=static_cast((static_cast(emitted)-psmRuntimeField(self,0xCC)) - /(static_cast(psmRuntimeField(self,0xF4))-psmRuntimeField(self,0xCC))); + if (psmInstanceB(self,0xF4)>psmInstanceB(self,0xCC)) + fraction=static_cast((static_cast(emitted)-psmInstanceB(self,0xCC)) + /(static_cast(psmInstanceB(self,0xF4))-psmInstanceB(self,0xCC))); // lerp(previous +0xC0, current +0xB4, fraction) into +0xA4, before the pool pop. { - const Vec3 from=psmRuntimeField(self,0xC0), to=psmRuntimeField(self,0xB4); + const Vec3 from=psmInstanceB(self,0xC0), to=psmInstanceB(self,0xB4); const float zDifference=to.z-from.z; const float xScaled=static_cast((static_cast(to.x)-from.x)*fraction); const double yScaled=(static_cast(to.y)-from.y)*fraction; const float zScaled=zDifference*fraction; - psmRuntimeField(self,0xA4)={xScaled+from.x,static_cast(yScaled+from.y),zScaled+from.z}; + psmInstanceB(self,0xA4)={xScaled+from.x,static_cast(yScaled+from.y),zScaled+from.z}; } ParticleSystemManager* const manager=reinterpret_cast(g_ParticleSystemManager); unsigned char* const record=static_cast(manager->m_type3FreeList); - manager->m_type3FreeList=record ? psmRuntimeField(record,0) : 0; + manager->m_type3FreeList=record ? psmRecordLink(record, 3) : 0; if (!record) continue; // an empty pool skips, not stops psmType3InitRecord(self,record,true); // The velocity offset (+0x1C, virtual +0x90) is added with no near-zero snap (type 0 snaps). - psmRuntimeField(record,0x70)=psmRuntimeField(self,0x1C)+psmRuntimeField(record,0x70); - psmRuntimeField(record,0x74)=psmRuntimeField(self,0x20)+psmRuntimeField(record,0x74); - psmRuntimeField(record,0x78)=psmRuntimeField(self,0x24)+psmRuntimeField(record,0x78); + psmRuntimeField(record,0x70)=psmInstanceB(self,0x1C)+psmRuntimeField(record,0x70); + psmRuntimeField(record,0x74)=psmInstanceB(self,0x20)+psmRuntimeField(record,0x74); + psmRuntimeField(record,0x78)=psmInstanceB(self,0x24)+psmRuntimeField(record,0x78); // Catch the new particle up from its birth time to the accumulated time: whole 0.01 s steps, // then the float remainder, both at the newest index. - const unsigned int steps=static_cast(static_cast((static_cast(psmRuntimeField(self,0xF4)) - -psmRuntimeField(self,0xF8))*100.0)); - if (psmType3AdvanceParticle(self,record,static_cast(psmRuntimeField(self,0x28)-1u), + const unsigned int steps=static_cast(static_cast((static_cast(psmInstanceB(self,0xF4)) + -psmInstanceB(self,0xF8))*100.0)); + if (psmType3AdvanceParticle(self,record,static_cast(psmInstanceB(self,0x28)-1u), psmType3TimeStep,steps)) { - const float remainder=static_cast((static_cast(psmRuntimeField(self,0xF4)) - -psmRuntimeField(self,0xF8))-static_cast(steps)*psmType3TimeStep); - psmType3AdvanceParticle(self,record,static_cast(psmRuntimeField(self,0x28)-1u), + const float remainder=static_cast((static_cast(psmInstanceB(self,0xF4)) + -psmInstanceB(self,0xF8))-static_cast(steps)*psmType3TimeStep); + psmType3AdvanceParticle(self,record,static_cast(psmInstanceB(self,0x28)-1u), remainder,1); } } diff --git a/Code/BF2/Geom/ParticleSystem/ParticleInstanceType3Registry.inl b/Code/BF2/Geom/ParticleSystem/ParticleInstanceType3Registry.inl index 1565a5aed..0dc7776fa 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleInstanceType3Registry.inl +++ b/Code/BF2/Geom/ParticleSystem/ParticleInstanceType3Registry.inl @@ -1,5 +1,6 @@ // Case-insensitive template lookup over the manager's existing name registry. // Include after g_templatesByName is defined; misses return null. +// PE 0x100D3410; the internal adapter accepts the string's character data. IParticleSystemTemplate* psmFindTemplateByName(const char* name) { const ParticleSystemNameMap::const_iterator it = g_templatesByName.find(std::string(name)); diff --git a/Code/BF2/Geom/ParticleSystem/ParticleInstanceType3Update.inl b/Code/BF2/Geom/ParticleSystem/ParticleInstanceType3Update.inl index fc7b4166b..1edeea420 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleInstanceType3Update.inl +++ b/Code/BF2/Geom/ParticleSystem/ParticleInstanceType3Update.inl @@ -8,15 +8,15 @@ void psmType3Emit(void* self, float dt); const float psmType3TimeStep = 0.01f; // PE 101817A0, 74 B: byte-for-byte the ordinary 1017F210 shape with the detached byte at +0x18 -// (type 2's offset) and no water arm. Mat4::mult is the tree's recovered 10077C50. +// (type 2's offset) and no water arm. rendmath::mult is the RendDX9 copy 10077C50. void psmType3RefreshTransform(void* self) { - if (psmRuntimeField(self,0x18)) return; - Mat4& output=psmRuntimeField(self,0x74); - const Mat4& local=psmRuntimeField(self,0x34); - world::IObject* const owner=psmRuntimeField(self,0x10); - if (owner) output.mult(local,owner->getVisualAbsoluteTransformation()); - else if (psmRuntimeField(self,0x30)) output.mult(local,*psmRuntimeField(self,0x30)); + if (psmInstanceB(self,0x18)) return; + Mat4& output=psmInstanceB(self,0x74); + const Mat4& local=psmInstanceB(self,0x34); + world::IObject* const owner=psmInstanceB(self,0x10); + if (owner) rendmath::mult(output,local,owner->getVisualAbsoluteTransformation()); + else if (psmInstanceB(self,0x30)) rendmath::mult(output,local,*psmInstanceB(self,0x30)); else output=local; } @@ -25,21 +25,21 @@ void psmType3RefreshTransform(void* self) // 1018275D `test ah,5; jnp`: only an ordered less-than skips, so a NaN accumulator runs the body. void psmType3RememberPlane(void* self) { - if (!(psmRuntimeField(self,0x214)<0.33333001f)) + if (!(psmInstanceB(self,0x214)<0.33333001f)) { - const unsigned char next=psmRuntimeField(self,0x211); - psmRuntimeField(self,0x210)=next; - psmRuntimeField(self,0x214)=static_cast( - static_cast(psmRuntimeField(self,0x214))-0.33333001f); - const float distance=psmRuntimeField(self,0x20C); // loaded before the copy - float* const target=&psmRuntimeField(self,0x160+16u*next); - const float* const source=&psmRuntimeField(self,0x200); + const unsigned char next=psmInstanceB(self,0x211); + psmInstanceB(self,0x210)=next; + psmInstanceB(self,0x214)=static_cast( + static_cast(psmInstanceB(self,0x214))-0.33333001f); + const float distance=psmInstanceB(self,0x20C); // loaded before the copy + float* const target=&psmInstanceB(self,0x160+16u*next); + const float* const source=&psmInstanceB(self,0x200); target[0]=source[0]; target[1]=source[1]; target[2]=source[2]; psmNormalize3(target); target[3]=distance; // The byte is reloaded after the normalise and wrapped with a signed idiv (always positive). - psmRuntimeField(self,0x211)=static_cast( - (static_cast(psmRuntimeField(self,0x211))+1)%10); + psmInstanceB(self,0x211)=static_cast( + (static_cast(psmInstanceB(self,0x211))+1)%10); } } @@ -66,63 +66,56 @@ int psmType3AdvanceParticle(void* self, unsigned char* record, int index, float // step loop below. 10181855 `test ah,1; jnz`: less-than OR unordered keeps the particle alive. if (static_cast(span)+psmRuntimeField(record,0x7C)>=psmRuntimeField(record,0x80)) { - if (psmRuntimeField(record,0xAC)) + if (psmRecordPointer(record, 3)) { // Hand the child back to the manager: byte +5 = 0 lets the bucket walk update it again, // removeInstance detaches+stops it (live particles) or queues its destruction (none). - psmRuntimeField(psmRuntimeField(record,0xAC),5)=0; + psmInstance(psmRecordPointer(record, 3),5)=0; reinterpret_cast(g_ParticleSystemManager) - ->removeInstance(psmRuntimeField(record,0xAC)); + ->removeInstance(psmRecordPointer(record, 3)); } - --psmRuntimeField(self,0x28); - psmRuntimeField(self,0x14)[index]= - psmRuntimeField(self,0x14)[psmRuntimeField(self,0x28)]; - psmRuntimeField(self,0x14)[psmRuntimeField(self,0x28)]=0; - psmRuntimeField(record,0)=manager->m_type3FreeList; + --psmInstanceB(self,0x28); + psmInstanceB(self,0x14)[index]= + psmInstanceB(self,0x14)[psmInstanceB(self,0x28)]; + psmInstanceB(self,0x14)[psmInstanceB(self,0x28)]=0; + psmRecordLink(record, 3)=manager->m_type3FreeList; manager->m_type3FreeList=record; - ++psmRuntimeField(self,0x140); + ++psmInstanceB(self,0x140); return 0; } - void* descriptor=psmRuntimeField(self,0x2C); + void* descriptor=psmInstanceB(self,0x2C); // Wind only for a world-space system with a positive affection (ordered `>`); unlike type 0 // the manager's wind-enabled byte (+0x8C10) is not consulted. float windX=0, windY=0, windZ=0; - if (!psmRuntimeField(descriptor,0x165) && psmRuntimeField(descriptor,0xB8)>0) + if (!psmDescriptor3(descriptor,0x165) && psmDescriptor3(descriptor,0xB8)>0) { const Vec3 wind=reinterpret_cast(manager->m_windManager)->getWind( psmRuntimeField(record,0x44)); windX=wind.x; windY=wind.y; windZ=wind.z; } - descriptor=psmRuntimeField(self,0x2C); - const float affection=psmRuntimeField(descriptor,0xB8); + descriptor=psmInstanceB(self,0x2C); + const float affection=psmDescriptor3(descriptor,0xB8); const float wx=static_cast(static_cast(affection)*windX); const float wy=static_cast(static_cast(windY)*affection); const float wz=static_cast(static_cast(windZ)*affection); - const float gravityStep=static_cast(static_cast(step)*psmRuntimeField(descriptor,0x98)); + const float gravityStep=static_cast(static_cast(step)*psmDescriptor3(descriptor,0x98)); // Air-resistance graph (+0xF4..+0x100) on the stored normalised age, then the transparency graph // (+0x114..+0x120). Both polynomials evaluate ((t*c2 + t^2*c1) + t^3*c0) + c3. double t=psmRuntimeField(record,0x5C); - const float dragCurve=static_cast(t*psmRuntimeField(descriptor,0xFC) - +t*t*psmRuntimeField(descriptor,0xF8)+t*t*t*psmRuntimeField(descriptor,0xF4) - +psmRuntimeField(descriptor,0x100)); - descriptor=psmRuntimeField(self,0x2C); + const float dragCurve=static_cast(t*psmDescriptor3(descriptor,0xFC) + +t*t*psmDescriptor3(descriptor,0xF8)+t*t*t*psmDescriptor3(descriptor,0xF4) + +psmDescriptor3(descriptor,0x100)); + descriptor=psmInstanceB(self,0x2C); const float drag=static_cast(static_cast(psmEmissionClamp(dragCurve)) - *psmRuntimeField(descriptor,0x9C)*step); // sub_1000ED40(v, 0, 1) + *psmDescriptor3(descriptor,0x9C)*step); // sub_1000ED40(v, 0, 1) t=psmRuntimeField(record,0x5C); - const float alphaCurve=static_cast(t*psmRuntimeField(descriptor,0x11C) - +t*t*psmRuntimeField(descriptor,0x118)+t*t*t*psmRuntimeField(descriptor,0x114) - +psmRuntimeField(descriptor,0x120)); - // [CHOSEN, not recovered] An unresolved child would fault here. Emit the qualified - // diagnostic and stop at the same boundary instead of continuing without the child. - if (!psmRuntimeField(record,0xAC)) - { - RD9_FRONTIER_AT("dice::hfe::geom::ParticleSystemEmitter::advanceParticle (child instance is null: " - "descriptor +0x88 never resolved; retail faults at 101819E3)", self, 0xA4); - std::abort(); - } - psmRuntimeField(record,0xAC)->reserved22(psmEmissionClamp(alphaCurve)); + const float alphaCurve=static_cast(t*psmDescriptor3(descriptor,0x11C) + +t*t*psmDescriptor3(descriptor,0x118)+t*t*t*psmDescriptor3(descriptor,0x114) + +psmDescriptor3(descriptor,0x120)); + // shipped defect: no null guard when the child template did not resolve. + psmRecordPointer(record, 3)->reserved22(psmEmissionClamp(alphaCurve)); for (unsigned int remaining=steps; remaining; --remaining) { @@ -131,11 +124,11 @@ int psmType3AdvanceParticle(void* self, unsigned char* record, int index, float psmRuntimeField(record,0x7C)=static_cast(age); const double normalised=age*psmRuntimeField(record,0x84); psmRuntimeField(record,0x5C)=static_cast(normalised); - descriptor=psmRuntimeField(self,0x2C); - const float gravityCurve=static_cast(normalised*psmRuntimeField(descriptor,0xEC) - +normalised*normalised*psmRuntimeField(descriptor,0xE8) - +normalised*normalised*normalised*psmRuntimeField(descriptor,0xE4) - +psmRuntimeField(descriptor,0xF0)); + descriptor=psmInstanceB(self,0x2C); + const float gravityCurve=static_cast(normalised*psmDescriptor3(descriptor,0xEC) + +normalised*normalised*psmDescriptor3(descriptor,0xE8) + +normalised*normalised*normalised*psmDescriptor3(descriptor,0xE4) + +psmDescriptor3(descriptor,0xF0)); float accelY=static_cast(static_cast(psmEmissionClamp(gravityCurve))*gravityStep); // var_10 // Quadratic drag against the wind-relative velocity, built from a normalised direction // (sub_100777A0) times -|v|^2 - not the reciprocal-sqrt form types 0/2/4 use. @@ -170,23 +163,27 @@ int psmType3AdvanceParticle(void* self, unsigned char* record, int index, float // No near-zero velocity snap (types 0/4 have one). } - descriptor=psmRuntimeField(self,0x2C); - if (psmRuntimeField(descriptor,0xC4)) + descriptor=psmInstanceB(self,0x2C); + if (psmDescriptor3(descriptor,0xC4)) { - const double difference=static_cast(psmRuntimeField(self,0x214))-psmRuntimeField(record,0x7C); - const int current=psmRuntimeField(self,0x210); + const double difference=static_cast(psmInstanceB(self,0x214))-psmRuntimeField(record,0x7C); + const int current=psmInstanceB(self,0x210); int selected=current; // 10181B64 `test ah,1; jnz`: less-than OR unordered walks back through the history. if (!(difference>=0)) { +#if defined(__APPLE__) + const int back=bf2x87::toIntTruncate(-3.0*difference); // RC=11 fistp +#else const int back=static_cast(-3.0*difference); // RC=11 fistp +#endif selected=static_cast(static_cast(current)-static_cast(back)-1u); if (selected<0) selected=static_cast(static_cast(selected) +((0xFFFFFFFFu-static_cast(selected))/10u)*10u+10u); } // No range guard: (selected + 0x16) << 4 is added to the instance as shipped. - const float* const plane=selected==current ? &psmRuntimeField(self,0x200) + const float* const plane=selected==current ? &psmInstanceB(self,0x200) : reinterpret_cast(static_cast(self) +((static_cast(selected)+0x16u)<<4)); double velocityDot=static_cast(psmRuntimeField(record,0x78))*plane[2] @@ -208,10 +205,10 @@ int psmType3AdvanceParticle(void* self, unsigned char* record, int index, float +static_cast(psmRuntimeField(record,0x70))*plane[0]; if (velocityDot<0) { - descriptor=psmRuntimeField(self,0x2C); + descriptor=psmInstanceB(self,0x2C); const double nx=velocityDot*plane[0], ny=velocityDot*plane[1]; const float nz=static_cast(velocityDot*plane[2]); - const float normal=psmRuntimeField(descriptor,0xC8), along=psmRuntimeField(descriptor,0xCC); + const float normal=psmDescriptor3(descriptor,0xC8), along=psmDescriptor3(descriptor,0xCC); const float tx=static_cast(psmRuntimeField(record,0x70)-nx); const float ty=static_cast(psmRuntimeField(record,0x74)-ny); const float tz=psmRuntimeField(record,0x78)-nz; @@ -227,43 +224,34 @@ int psmType3AdvanceParticle(void* self, unsigned char* record, int index, float psmRuntimeField(record,0x60)|=8u; float* const worldPosition=&psmRuntimeField(record,0x50); psmRuntimeField(record,0x50)=psmRuntimeField(record,0x44); - descriptor=psmRuntimeField(self,0x2C); - if (psmRuntimeField(descriptor,0x165)) + descriptor=psmInstanceB(self,0x2C); + if (psmDescriptor3(descriptor,0x165)) { - const float* const m=&psmRuntimeField(self,0x74); + const float* const m=&psmInstanceB(self,0x74); const double x=worldPosition[0], y=worldPosition[1], z=worldPosition[2]; const double rz=static_cast(m[10])*z+static_cast(m[2])*x+static_cast(m[6])*y+m[14]; const double ry=static_cast(m[9])*z+static_cast(m[1])*x+static_cast(m[5])*y+m[13]; worldPosition[0]=static_cast(static_cast(m[8])*z+static_cast(m[4])*y+static_cast(m[0])*x+m[12]); worldPosition[1]=static_cast(ry); worldPosition[2]=static_cast(rz); } - descriptor=psmRuntimeField(self,0x2C); + descriptor=psmInstanceB(self,0x2C); // Water placement without the descriptor's waterSurfaceOffset (+0xC0): types 2/4 add theirs. - if (psmRuntimeField(descriptor,0xBC) && manager->m_heightmapCluster) + if (psmDescriptor3(descriptor,0xBC) && manager->m_heightmapCluster) worldPosition[1]=reinterpret_cast(manager->m_heightmapCluster) ->getWaterLevelInWorldCoords(*reinterpret_cast(worldPosition)); - // PE 1017A2B0 (by-value x, y, z): ordered extrema, so NaN never moves a bound. - { - const float x=worldPosition[0], y=worldPosition[1], z=worldPosition[2]; - float* const bounds=&psmRuntimeField(self,0xFC); - if (x>bounds[3]) bounds[3]=x; - if (xbounds[4]) bounds[4]=y; - if (ybounds[5]) bounds[5]=z; - if (z(self,0xFC),worldPosition[0],worldPosition[1],worldPosition[2]); // Rotation graph (+0xD4..+0xE0), evaluated ((t^2*c1 + t*c2) + t^3*c0) + c3, scaled by the whole // advance (float(steps) * step). - descriptor=psmRuntimeField(self,0x2C); + descriptor=psmInstanceB(self,0x2C); t=psmRuntimeField(record,0x5C); - const float rotationCurve=static_cast(t*t*psmRuntimeField(descriptor,0xD8) - +t*psmRuntimeField(descriptor,0xDC)+t*t*t*psmRuntimeField(descriptor,0xD4) - +psmRuntimeField(descriptor,0xE0)); + const float rotationCurve=static_cast(t*t*psmDescriptor3(descriptor,0xD8) + +t*psmDescriptor3(descriptor,0xDC)+t*t*t*psmDescriptor3(descriptor,0xD4) + +psmDescriptor3(descriptor,0xE0)); const double rotation=static_cast(psmEmissionClamp(rotationCurve))*stepsF*step; float* const matrix=&psmRuntimeField(record,0x04); - descriptor=psmRuntimeField(self,0x2C); - if (psmRuntimeField(descriptor,0x164)) + descriptor=psmInstanceB(self,0x2C); + if (psmDescriptor3(descriptor,0x164)) { // alignRotationToSpeed: the particle frame looks along its velocity. const float vx=psmRuntimeField(record,0x70), vy=psmRuntimeField(record,0x74); @@ -312,20 +300,20 @@ int psmType3AdvanceParticle(void* self, unsigned char* record, int index, float psmRuntimeField(record,0x94)=static_cast(spinX+psmRuntimeField(record,0x94)); psmRuntimeField(record,0x98)=static_cast(spinY+psmRuntimeField(record,0x98)); psmRuntimeField(record,0x9C)=static_cast(static_cast(spinZ)+psmRuntimeField(record,0x9C)); - // PE 10078730 is the RendDX9 copy of the tree's setRotationZXY (same z/x/y bit set, same - // seven-way product, nine rotation elements only). Arguments: -rot.z, -rot.y, -rot.x. - setRotationZXY(*reinterpret_cast(matrix), -psmRuntimeField(record,0x9C), + // PE 10078730 (rendmath::setRotationZXY, RendDX9's copy: z/x/y bit set, seven-way + // product, nine rotation elements only). Arguments: -rot.z, -rot.y, -rot.x. + rendmath::setRotationZXY(*reinterpret_cast(matrix), -psmRuntimeField(record,0x9C), -psmRuntimeField(record,0x98), -psmRuntimeField(record,0x94)); matrix[12]=worldPosition[0]; matrix[13]=worldPosition[1]; matrix[14]=worldPosition[2]; } // speedFromParticle (+0x168): the child inherits the particle's velocity as speed + direction. // (Its console binding is missing on the world side today - see readme - so it stays 0.) - descriptor=psmRuntimeField(self,0x2C); - if (psmRuntimeField(descriptor,0x168)>0) + descriptor=psmInstanceB(self,0x2C); + if (psmDescriptor3(descriptor,0x168)>0) { - const float factor=psmRuntimeField(descriptor,0x168); - IParticleSystemInstance* const child=psmRuntimeField(record,0xAC); + const float factor=psmDescriptor3(descriptor,0x168); + IParticleSystemInstance* const child=psmRecordPointer(record, 3); float direction[3]; direction[0]=static_cast(static_cast(factor)*psmRuntimeField(record,0x70)); direction[1]=static_cast(static_cast(factor)*psmRuntimeField(record,0x74)); @@ -344,12 +332,12 @@ int psmType3AdvanceParticle(void* self, unsigned char* record, int index, float direction[1]=static_cast(direction[1]*inverse); direction[2]=static_cast(direction[2]*inverse); child->reserved19(speed); - psmRuntimeField(record,0xAC)->reserved16(*reinterpret_cast(direction)); + psmRecordPointer(record, 3)->reserved16(*reinterpret_cast(direction)); } } // Unguarded in retail (101820F1) like the transparency call; a null child already stopped above. // The child advances by this particle's whole span (float(steps * step)), in its own time scale. - psmRuntimeField(record,0xAC)->reserved41(span); + psmRecordPointer(record, 3)->reserved41(span); return 1; } @@ -357,51 +345,55 @@ int psmType3AdvanceParticle(void* self, unsigned char* record, int index, float void psmType3Update(void* self, float dt) { IParticleSystemInstance* const instance=static_cast(self); - float elapsed=static_cast(static_cast(dt)*psmRuntimeField(self,0x128)); - if (!psmRuntimeField(self,0x28) && !psmRuntimeField(self,0x144)) + float elapsed=static_cast(static_cast(dt)*psmInstanceB(self,0x128)); + if (!psmInstanceB(self,0x28) && !psmInstanceB(self,0x144)) { psmQueueInactive(reinterpret_cast(g_ParticleSystemManager),instance); - if (psmRuntimeField(self,0x18)) + if (psmInstanceB(self,0x18)) reinterpret_cast(g_ParticleSystemManager)->removeInstance(instance); return; } // The source dt refuses (NaN passes, as `test ah,41h; jnp` only rejects an ordered <= 0). - if (psmRuntimeField(self,0x21D) || dt<=0) return; - void* descriptor=psmRuntimeField(self,0x2C); - if (psmRuntimeField(descriptor,0xC4)) + if (psmInstanceB(self,0x21D) || dt<=0) return; + void* descriptor=psmInstanceB(self,0x2C); + if (psmDescriptor3(descriptor,0xC4)) { - psmRuntimeField(self,0x214)=static_cast(static_cast(elapsed)+psmRuntimeField(self,0x214)); + psmInstanceB(self,0x214)=static_cast(static_cast(elapsed)+psmInstanceB(self,0x214)); psmType3RememberPlane(self); } - if (!psmRuntimeField(self,0x21F) && psmRuntimeField(self,0x21E)) - psmRuntimeField(self,0x21F)=psmRuntimeField(self,0x21E); - descriptor=psmRuntimeField(self,0x2C); - psmRuntimeField(self,0x140)=0; psmRuntimeField(self,0x13C)=0; - const double maximum=static_cast(psmRuntimeField(descriptor,0x90))+psmRuntimeField(descriptor,0x8C); + if (!psmInstanceB(self,0x21F) && psmInstanceB(self,0x21E)) + psmInstanceB(self,0x21F)=psmInstanceB(self,0x21E); + descriptor=psmInstanceB(self,0x2C); + psmInstanceB(self,0x140)=0; psmInstanceB(self,0x13C)=0; + const double maximum=static_cast(psmDescriptor3(descriptor,0x90))+psmDescriptor3(descriptor,0x8C); if (elapsed>maximum) elapsed=static_cast(maximum); for (int i=0;i<3;++i) - { psmRuntimeField(self,0xFC+4*i)=0x4B18967Fu; psmRuntimeField(self,0x108+4*i)=0xCB18967Fu; } - psmRuntimeField(self,0xC0)=psmRuntimeField(self,0xA4); + { psmInstanceB(self,0xFC+4*i)=0x4B18967Fu; psmInstanceB(self,0x108+4*i)=0xCB18967Fu; } + psmInstanceB(self,0xC0)=psmInstanceB(self,0xA4); psmType3RefreshTransform(self); - psmRuntimeField(self,0xB4)=psmRuntimeField(self,0xA4); - const double total=static_cast(elapsed)+psmRuntimeField(self,0xD0); + psmInstanceB(self,0xB4)=psmInstanceB(self,0xA4); + const double total=static_cast(elapsed)+psmInstanceB(self,0xD0); +#if defined(__APPLE__) + const unsigned int steps=static_cast(bf2x87::toIntTruncate(100.0*total)); +#else const unsigned int steps=static_cast(static_cast(100.0*total)); +#endif const double advanced=static_cast(steps)*psmType3TimeStep; - psmRuntimeField(self,0xCC)=psmRuntimeField(self,0xF4); - psmRuntimeField(self,0xD0)=static_cast(total-advanced); - psmRuntimeField(self,0xF4)=static_cast(advanced+psmRuntimeField(self,0xF4)); - for (unsigned int i=0;psmRuntimeField(self,0x14)[i];) - i+=psmType3AdvanceParticle(self,psmRuntimeField(self,0x14)[i],static_cast(i), + psmInstanceB(self,0xCC)=psmInstanceB(self,0xF4); + psmInstanceB(self,0xD0)=static_cast(total-advanced); + psmInstanceB(self,0xF4)=static_cast(advanced+psmInstanceB(self,0xF4)); + for (unsigned int i=0;psmInstanceB(self,0x14)[i];) + i+=psmType3AdvanceParticle(self,psmInstanceB(self,0x14)[i],static_cast(i), psmType3TimeStep,steps); - const double delay=static_cast(psmRuntimeField(self,0xF0))-elapsed; - psmRuntimeField(self,0xF0)=static_cast(delay); - if (delay>0) { psmRuntimeField(self,0xF8)=psmRuntimeField(self,0xF4); return; } + const double delay=static_cast(psmInstanceB(self,0xF0))-elapsed; + psmInstanceB(self,0xF0)=static_cast(delay); + if (delay>0) { psmInstanceB(self,0xF8)=psmInstanceB(self,0xF4); return; } // Prewarm (+0xEC, from the descriptor at start) runs here as recursive virtual updates of at most // 1/60 s. The loop test uses the unrounded remainder (`fst` then `fcomp`). - if (psmRuntimeField(self,0xEC)>0) + if (psmInstanceB(self,0xEC)>0) { - float remaining=psmRuntimeField(self,0xEC); - psmRuntimeField(self,0xEC)=0; + float remaining=psmInstanceB(self,0xEC); + psmInstanceB(self,0xEC)=0; if (remaining>0) for (;;) { @@ -412,9 +404,9 @@ void psmType3Update(void* self, float dt) } } psmType3Emit(self,elapsed); - psmRuntimeField(self,0xA4)=psmRuntimeField(self,0xB4); - float* const bounds=&psmRuntimeField(self,0xFC); - if (psmRuntimeField(self,0x28)) + psmInstanceB(self,0xA4)=psmInstanceB(self,0xB4); + float* const bounds=&psmInstanceB(self,0xFC); + if (psmInstanceB(self,0x28)) { // A constant 1.0 margin (types 0/2/4 pad by a descriptor size instead). for (int i=0;i<3;++i) bounds[i]=static_cast(static_cast(bounds[i])-1.0); @@ -422,14 +414,14 @@ void psmType3Update(void* self, float dt) } else { - psmRuntimeField(self,0xFC)=psmRuntimeField(self,0xA4); - psmRuntimeField(self,0x108)=psmRuntimeField(self,0xA4); + psmInstanceB(self,0xFC)=psmInstanceB(self,0xA4); + psmInstanceB(self,0x108)=psmInstanceB(self,0xA4); } // PE 1016EB70 / 1016EBC0 (the same aabb radius/centre helpers the type-0 update inlines). const float dz=bounds[5]-bounds[2], dx=static_cast((static_cast(bounds[3])-bounds[0])*0.5); const double dy=(static_cast(bounds[4])-bounds[1])*0.5; - psmRuntimeField(self,0x120)=static_cast(::sqrt(dz*0.5*(dz*0.5)+static_cast(dx)*dx+dy*dy)); + psmInstanceB(self,0x120)=static_cast(::sqrt(dz*0.5*(dz*0.5)+static_cast(dx)*dx+dy*dy)); const float zsum=bounds[5]+bounds[2]; - psmRuntimeField(self,0x114)={static_cast((static_cast(bounds[3])+bounds[0])*0.5), + psmInstanceB(self,0x114)={static_cast((static_cast(bounds[3])+bounds[0])*0.5), static_cast((static_cast(bounds[4])+bounds[1])*0.5),zsum*0.5f}; } diff --git a/Code/BF2/Geom/ParticleSystem/ParticleInstanceType4.inl b/Code/BF2/Geom/ParticleSystem/ParticleInstanceType4.inl index ca017857c..8502cbed9 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleInstanceType4.inl +++ b/Code/BF2/Geom/ParticleSystem/ParticleInstanceType4.inl @@ -7,7 +7,7 @@ float* psmType4NewParticle(void* self); void psmType4Emit(void* self,float dt); int psmType4AdvanceParticle(void* self,float* particle,int index,float step,unsigned int steps); -// PE100D3150 returns shared matrix scratch; the owner immediately copies it. Preserve the +// PE 0x100D3150 returns shared matrix scratch; the owner immediately copies it. Preserve the // unusual forward-cross-up order and the parallel-axis identity result, including NaN routing. const Mat4& psmType4WaterMatrix(const Vec3& position,const Vec3& up,const Vec3& forward) { @@ -31,27 +31,28 @@ const Mat4& psmType4WaterMatrix(const Vec3& position,const Vec3& up,const Vec3& return result; } -// PE1017CB20 matches the ordinary visual-owner composition, then aligns water effects. +// PE 0x1017CB20 matches the ordinary visual-owner composition, then aligns water effects. void psmType4RefreshTransform(void* self) { - if (psmRuntimeField(self,0x14)) return; - Mat4& output=psmRuntimeField(self,0x74); - const Mat4& local=psmRuntimeField(self,0x34); - world::IObject* const owner=psmRuntimeField(self,0x10); - if (owner) output.mult(local,owner->getVisualAbsoluteTransformation()); - else if (psmRuntimeField(self,0x30)) output.mult(local,*psmRuntimeField(self,0x30)); + if (psmInstanceA(self,0x14)) return; + Mat4& output=psmInstanceA(self,0x74); + const Mat4& local=psmInstanceA(self,0x34); + world::IObject* const owner=psmInstanceA(self,0x10); + if (owner) rendmath::mult(output,local,owner->getVisualAbsoluteTransformation()); + else if (psmInstanceA(self,0x30)) rendmath::mult(output,local,*psmInstanceA(self,0x30)); else output=local; - if (psmRuntimeField(psmRuntimeField(self,0x2C),0xA0)) - output=psmType4WaterMatrix(psmRuntimeField(self,0xA4),Vec3{0,1,0},psmRuntimeField(self,0x94)); + if (psmDescriptor4(psmInstanceA(self,0x2C),0xA0)) + output=psmType4WaterMatrix(psmInstanceA(self,0xA4),Vec3{0,1,0},psmInstanceA(self,0x94)); } class ParticleInstanceType4 : public IParticleSystemInstance { - unsigned char m_data[0x224]; - template T& at(unsigned int offset) { return psmRuntimeField(this, offset); } + unsigned char m_data[PSM_INSTANCE_DATA(0x228)]; + template T& at(unsigned int offset) { return psmInstanceA(this, offset); } template const T& at(unsigned int offset) const - { return *reinterpret_cast(reinterpret_cast(this) + offset); } + { return psmInstanceA(const_cast(this), offset); } public: + // PE 0x1017D430 explicit ParticleInstanceType4(IParticleSystemTemplate* descriptor) { at(0x14)=0; @@ -69,13 +70,13 @@ public: at(0x224)=0; at(0x225)=0; // PE1017D430 leaves owner+10/controller+C untouched; EffectBundle binds these next. at(8)=0; - const double lifetime = psmRuntimeField(descriptor,0x7C)+static_cast(psmRuntimeField(descriptor,0x78)); + const double lifetime = psmDescriptor4(descriptor,0x7C)+static_cast(psmDescriptor4(descriptor,0x78)); double capacityTime=lifetime; - const float emitTime=psmRuntimeField(descriptor,0x1C4); - if (emitTime!=0 && !psmRuntimeField(descriptor,0x74) && capacityTime>emitTime) + const float emitTime=psmDescriptor4(descriptor,0x1C4); + if (emitTime!=0 && !psmDescriptor4(descriptor,0x74) && capacityTime>emitTime) capacityTime=emitTime; - at(0x220)=static_cast(capacityTime*psmRuntimeField(descriptor,0x10)+10.0); - at(0x24)=static_cast(::renddx9abi::engineAlloc(at(0x220)*4+4)); + at(0x220)=static_cast(capacityTime*psmDescriptor4(descriptor,0x10)+10.0); + at(0x24)=static_cast(::renddx9abi::engineAlloc(at(0x220)*kPsmPointerSize+kPsmPointerSize)); at(0x24)[0]=0; at(0x18)={0,0,0}; at(0xFC)={0,0,0}; at(0x108)={0,0,0}; @@ -85,20 +86,22 @@ public: { at(offset)={0,1,0}; at(offset+12)=0; } at(4)=0; } + // PE 0x1017C840 ~ParticleInstanceType4() override { ParticleSystemManager* const manager=reinterpret_cast(g_ParticleSystemManager); float** particles=at(0x24); for (unsigned int i=0;particles[i];++i) { - psmRuntimeField(particles[i],0)=manager->m_type4FreeList; - --psmRuntimeField(manager,0x8BA0); + psmRecordLink(particles[i], 4)=manager->m_type4FreeList; + --manager->m_type4LiveCount; manager->m_type4FreeList=particles[i]; } ::renddx9abi::engineFree(particles); } static void operator delete(void* self) { ::renddx9abi::engineFree(self); } int reserved01() const override { return 4; } + // PE 0x1017CA10 void reserved02() const override { ParticleInstanceType4* self=const_cast(this); @@ -108,8 +111,8 @@ public: { float** array=self->at(0x24); float* particle=array[0]; array[0]=array[--self->at(0x28)]; array[self->at(0x28)]=0; - psmRuntimeField(particle,0)=manager->m_type4FreeList; - manager->m_type4FreeList=particle; --psmRuntimeField(manager,0x8BA0); + psmRecordLink(particle, 4)=manager->m_type4FreeList; + manager->m_type4FreeList=particle; --manager->m_type4LiveCount; } self->at(0x21C)=0; self->at(0x218)=0; self->at(0x219)=0; self->at(0x140)=0; self->at(0x28)=0; self->at(0x120)=0; @@ -126,10 +129,10 @@ public: if (!at(4)) psmAddActive(manager,this,firstPerson); at(0x14C)=1; at(0x224)=1; at(0x226)=0; void* const descriptor=at(0x2C); - at(0xE0)=psmRuntimeField(descriptor,0x1C4); - at(0xE4)=psmRuntimeField(descriptor,0x1CC); + at(0xE0)=psmDescriptor4(descriptor,0x1C4); + at(0xE4)=psmDescriptor4(descriptor,0x1CC); at(0xE8)=0; at(0xF0)=0; at(0xF4)=0; - at(0xF8)=psmRuntimeField(descriptor,0xC); + at(0xF8)=psmDescriptor4(descriptor,0xC); psmType4RefreshTransform(this); dx9rend::IRenderView* const view=dx9rend::rendererGetRenderViewDup(); const float oldFar=view->getFarPlane(); @@ -151,38 +154,66 @@ public: } void reserved04() override { at(0x14C)=0; at(0x224)=0; at(0xE0)=0; } bool reserved05() const override { return at(0x14C)!=0; } + // PE 0x1017EAC0 (shared with the ordinary instance). void setPaused(bool value) override { at(0x225)=value; } bool reserved07() const override { return at(0x225)!=0; } void reserved08() override { at(0x14)=1; at(0x10)=0; at(0xC)=0; at(0x30)=0; } + // PE 0x1017EAE0 (shared with the ordinary instance). void reserved09(bool value) override { at(0x128)=value; } bool reserved10() const override { return at(0x128)!=0; } - void reserved11(int value) override { at(0x10)=value; } - int reserved12() const override { return at(0x10); } - void reserved13(int value) override { at(0x30)=value; } + void reserved11(intptr_t value) override { at(0x10)=value; } + intptr_t reserved12() const override { return at(0x10); } + void reserved13(intptr_t value) override { at(0x30)=value; } void* reserved14(const void* value) override { at(0x34)=*static_cast(value); return &at(0x34); } const void* reserved15() const override { return &at(0x34); } + // PE 0x1017CBC0 void reserved16(const Vec3& value) override { at(0xCC)=value; } const Vec3& reserved17() const override { return at(0xCC); } + // PE 0x1017DA00. Capture all inputs before the destination or normalization can overlap them. void reserved18(const void* value) override - { at(0x208)=*static_cast(value); psmNormalize3(&at(0x208)); at(0x214)=static_cast(value)[3]; } + { + const float* coordinates = static_cast(value); + const float z = psmCopyStoredFloat(coordinates[2]); + unsigned int x; + ::memcpy(&x, coordinates, sizeof(x)); + const float y = psmCopyStoredFloat(coordinates[1]); + unsigned int distance; + ::memcpy(&distance, coordinates + 3, sizeof(distance)); + at(0x20C) = y; + at(0x210) = z; + at(0x208) = x; + psmNormalize3(&at(0x208)); + at(0x214) = distance; + } + // PE 0x1017C9F0 void reserved19(float value) override { at(0xDC)=value; } float reserved20() const override { return at(0xDC); } void reserved21(int,int) override { at(0x15C)=1; } + // PE 0x1017C930 void reserved22(float value) override { at(0x160)=value; } float reserved23() const override { return at(0x160); } + // PE 0x1017C950 void reserved24(float value) override { at(0x138)=value; } float reserved25() const override { return at(0x138); } + // PE 0x10181060 (shared with the ordinary instance). void reserved26(float value) override { at(0x13C)=value; } float reserved27() const override { return at(0x13C); } void reserved28(const Vec3& value) override { at(0x150)=value; } const Vec3& reserved29() const override { return at(0x150); } + // PE 0x1017C970 void reserved30(float value) override { at(0x12C)=value; } float reserved31() const override { return at(0x12C); } + // PE 0x1017C9D0 void reserved32(float value) override { at(0xD8)=value; } float reserved33() const override { return at(0xD8); } int reserved34() const override { return at(0x220); } IParticleSystemTemplate* getTemplate() const override { return at(0x2C); } - void reserved36(const Vec3& value) override { at(0x18)=value; } + // PE 0x1017EB20 (shared with the ordinary instance). + void reserved36(const Vec3& value) override + { + const float z=value.z,y=value.y,x=value.x; + at(0x1C)=y; at(0x18)=x; at(0x20)=z; + } void reserved37() override { psmType4NewParticle(this); } float reserved38() const override { @@ -199,10 +230,11 @@ public: int reserved39() const override { return at(0x28); } const Vec3& getPosition() const override { return at(0xB4); } void reserved41(float value) override { psmType4Update(this,value); } + // PE 0x1017C8D0 void reserved42(bool value) override { - if (at(4) && value!=static_cast(at(6))) - { at(7)=value; psmReclassification(reinterpret_cast(g_ParticleSystemManager)).insert(reinterpret_cast(this)); } + if (at(4) && static_cast(value)!=at(6)) + { at(7)=value; psmReclassification(reinterpret_cast(g_ParticleSystemManager)).insert(this); } } // Proven retail shared constant/null bodies: 1017A510/100E13B0/100ED3B0/10082D40. float getGasCloudRadius() const override { return 1.0f; } @@ -211,11 +243,15 @@ public: void setMaterial(int) override {} int getMaterial() const override { return -1; } void setEffectController(world::IEffectController* value) override - { at(0xC)=value; reserved11(reinterpret_cast(value ? value->getObject() : 0)); } + { at(0xC)=value; reserved11(reinterpret_cast(value ? value->getObject() : 0)); } world::IEffectController* getEffectController() const override { return at(0xC); } bool getWaterSide() const override { return false; } }; +#if defined(_M_IX86) static_assert(sizeof(ParticleInstanceType4)==0x228,"NSA particle instance PE1017D430 layout"); +#else +static_assert(sizeof(ParticleInstanceType4)==kPsmInstanceSize,"x64 instance layout, ParticleRawLayout.h"); +#endif IParticleSystemInstance* psmCreateType4Instance(IParticleSystemTemplate* descriptor) { diff --git a/Code/BF2/Geom/ParticleSystem/ParticleInstanceType4Emission.inl b/Code/BF2/Geom/ParticleSystem/ParticleInstanceType4Emission.inl index f68ff4f78..09e82b7e3 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleInstanceType4Emission.inl +++ b/Code/BF2/Geom/ParticleSystem/ParticleInstanceType4Emission.inl @@ -7,38 +7,51 @@ int psmType4AdvanceParticle(void*,float*,int,float,unsigned int); void psmType4EmissionDirection(float* output, void* descriptor, void* self) { - output[0]=psmRuntimeField(descriptor,0x200)*psmRuntimeField(self,0x150); - output[1]=psmRuntimeField(descriptor,0x204)*psmRuntimeField(self,0x154); - output[2]=psmRuntimeField(descriptor,0x208)*psmRuntimeField(self,0x158); + output[0]=psmDescriptor4(descriptor,0x200)*psmInstanceA(self,0x150); + output[1]=psmDescriptor4(descriptor,0x204)*psmInstanceA(self,0x154); + output[2]=psmDescriptor4(descriptor,0x208)*psmInstanceA(self,0x158); } -// PE1017EB70: five draws even when all dimensions are zero. -void psmType4EmissionSphere(float* output, void* descriptor, void* self, float* particle) +// PE 0x1017EB70: five draws even when all dimensions are zero. +float* psmType4EmissionSphere(float* output, void* descriptor, void* self, float* particle) { const float phi = static_cast(psmEmissionRandomInteger() * static_cast(3.7450703871400037e-7f)); const double theta = psmEmissionRandomInteger() * static_cast(1.8725351935700019e-7f); const float savedTheta = static_cast(theta); +#if defined(__APPLE__) + const float sineTheta = bf2x87::store(bf2x87::sinValue(bf2x87::wide(theta))); +#else const float sineTheta = static_cast(::sin(theta)); +#endif const float yRandom = static_cast(psmEmissionUnit()); const float xRandom = static_cast(psmEmissionUnit()); - const double zRadius = psmEmissionRandomInteger() * static_cast(psmRuntimeField(descriptor,0x20)) + const double zRadius = psmEmissionRandomInteger() * static_cast(psmDescriptor4(descriptor,0x20)) * 0.000000059604644775390625; - const double xRadius = static_cast(xRandom) * psmRuntimeField(descriptor,0x18); - const double yRadius = static_cast(yRandom) * psmRuntimeField(descriptor,0x1C); + const double xRadius = static_cast(xRandom) * psmDescriptor4(descriptor,0x18); + const double yRadius = static_cast(yRandom) * psmDescriptor4(descriptor,0x1C); +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain FSIN/FCOS products until the output stores. + using bf2x87::wide; + particle[1]=bf2x87::store(bf2x87::cosValue(wide(phi))*wide(xRadius)*wide(sineTheta)); + particle[2]=bf2x87::store(bf2x87::sinValue(wide(phi))*wide(yRadius)*wide(sineTheta)); + particle[3]=bf2x87::store(bf2x87::cosValue(wide(savedTheta))*wide(zRadius)); +#else particle[1]=static_cast(::cos(phi)*xRadius*sineTheta); particle[2]=static_cast(::sin(phi)*yRadius*sineTheta); particle[3]=static_cast(::cos(savedTheta)*zRadius); +#endif psmType4EmissionDirection(output,descriptor,self); + return output; } -// PE1017ECA0. Shape1 emits radially; shape2 uses the configured direction. Largest-axis ties +// PE 0x1017ECA0. Shape1 emits radially; shape2 uses the configured direction. Largest-axis ties // select the first component. The distributions are sampled Z,Y,X, not X,Y,Z. void psmType4EmissionCylinder(float* output, void* descriptor, void* self, float* particle) { - const double angle=(psmEmissionSymmetric()*psmRuntimeField(descriptor,0x60) - +psmRuntimeField(descriptor,0x64))*0.01745329238474369f; + const double angle=(psmEmissionSymmetric()*psmDescriptor4(descriptor,0x60) + +psmDescriptor4(descriptor,0x64))*0.01745329238474369f; const float sine=static_cast(::sin(angle)), cosine=static_cast(::cos(angle)); unsigned int axis=0; - if(psmRuntimeField(descriptor,0x1C)>psmRuntimeField(descriptor,0x18))axis=1; - if(psmRuntimeField(descriptor,0x20)>psmRuntimeField(descriptor,0x18+4*axis))axis=2; + if(psmDescriptor4(descriptor,0x1C)>psmDescriptor4(descriptor,0x18))axis=1; + if(psmDescriptor4(descriptor,0x20)>psmDescriptor4(descriptor,0x18+4*axis))axis=2; unsigned char* const bytes=static_cast(descriptor); const float z=static_cast(psmEmissionDistribution(bytes+0x4C)); const float y=static_cast(psmEmissionDistribution(bytes+0x38)); @@ -46,7 +59,7 @@ void psmType4EmissionCylinder(float* output, void* descriptor, void* self, float if(axis==0){particle[1]=static_cast(x);particle[2]=y*sine;particle[3]=z*cosine;} else if(axis==1){particle[1]=static_cast(x*sine);particle[2]=y;particle[3]=z*cosine;} else{particle[1]=static_cast(x*sine);particle[2]=y*cosine;particle[3]=z;} - if(psmRuntimeField(descriptor,0x258)==1) + if(psmDescriptor4(descriptor,0x258)==1) { output[0]=particle[1];output[1]=particle[2];output[2]=particle[3]; output[axis]=0; @@ -54,6 +67,7 @@ void psmType4EmissionCylinder(float* output, void* descriptor, void* self, float } else psmType4EmissionDirection(output,descriptor,self); } +// PE 0x1017EE90. The distributions are sampled Z,Y,X. void psmType4EmissionBox(float* output, void* descriptor, void* self, float* particle) { unsigned char* const bytes=static_cast(descriptor); @@ -65,46 +79,47 @@ void psmType4EmissionBox(float* output, void* descriptor, void* self, float* par } +// PE 0x1017DAE0 float* psmType4NewParticle(void* self) { - void* const manager=g_ParticleSystemManager; - float* const particle=psmRuntimeField(manager,0x8B98); - psmRuntimeField(manager,0x8B98)=particle?psmRuntimeField(particle,0):nullptr; - psmRuntimeField(manager,0x8BA0)+=particle!=nullptr; + ParticleSystemManager* const manager=reinterpret_cast(g_ParticleSystemManager); + float* const particle=static_cast(manager->m_type4FreeList); // +0x8B98 + manager->m_type4FreeList=particle?static_cast(psmRecordLink(particle, 4)):nullptr; + manager->m_type4LiveCount+=particle!=nullptr; // +0x8BA0 if(!particle)return nullptr; - ++psmRuntimeField(self,0x144); - void* descriptor=psmRuntimeField(self,0x2C); - if(psmRuntimeField(descriptor,0xBD)) + ++psmInstanceA(self,0x144); + void* descriptor=psmInstanceA(self,0x2C); + if(psmDescriptor4(descriptor,0xBD)) { const int random=psmEmissionRandomInteger(); - descriptor=psmRuntimeField(self,0x2C); - const unsigned int count=psmRuntimeField(descriptor,0xD0)-1; + descriptor=psmInstanceA(self,0x2C); + const unsigned int count=psmDescriptor4(descriptor,0xD0)-1; particle[32]=static_cast(::floor(static_cast(random)*count*0.000000059604644775390625)); } else particle[32]=0; psmRuntimeField(particle,0x28)|=0xFu; particle[15]=0; - descriptor=psmRuntimeField(self,0x2C); - const double lifetime=psmEmissionRandomInteger()*static_cast(psmRuntimeField(descriptor,0x78)) - *0.000000059604644775390625+psmRuntimeField(descriptor,0x7C); + descriptor=psmInstanceA(self,0x2C); + const double lifetime=psmEmissionRandomInteger()*static_cast(psmDescriptor4(descriptor,0x78)) + *0.000000059604644775390625+psmDescriptor4(descriptor,0x7C); particle[30]=static_cast(lifetime);particle[31]=static_cast(1.0/lifetime); - particle[29]=psmRuntimeField(self,0xD8);particle[9]=particle[29]*particle[31]; - particle[18]=psmRuntimeField(self,0x15C); - descriptor=psmRuntimeField(self,0x2C); - particle[20]=psmRuntimeField(descriptor,0x19C);particle[21]=psmRuntimeField(descriptor,0x1A0); - particle[13]=psmRuntimeField(self,0x160);particle[14]=psmRuntimeField(self,0x160); - particle[35]=psmRuntimeField(descriptor,0x98); - psmRuntimeField(particle,0x40)=psmRuntimeField(descriptor,0x212); - psmRuntimeField(particle,0x42)=psmRuntimeField(descriptor,0x214); + particle[29]=psmInstanceA(self,0xD8);particle[9]=particle[29]*particle[31]; + particle[18]=psmInstanceA(self,0x15C); + descriptor=psmInstanceA(self,0x2C); + particle[20]=psmDescriptor4(descriptor,0x19C);particle[21]=psmDescriptor4(descriptor,0x1A0); + particle[13]=psmInstanceA(self,0x160);particle[14]=psmInstanceA(self,0x160); + particle[35]=psmDescriptor4(descriptor,0x98); + psmRuntimeField(particle,0x40)=psmDescriptor4(descriptor,0x212); + psmRuntimeField(particle,0x42)=psmDescriptor4(descriptor,0x214); const float firstRandom=static_cast(psmEmissionSymmetric()); - particle[12]=firstRandom*psmRuntimeField(descriptor,0x1A4); - particle[19]=static_cast(psmEmissionSymmetric()*psmRuntimeField(descriptor,0x1A8)); - particle[34]=static_cast(psmEmissionSymmetric()*psmRuntimeField(descriptor,0x1AC)); - const double spin=psmEmissionSymmetric()*psmRuntimeField(descriptor,0x8C); - particle[33]=static_cast(spin>=0?spin+psmRuntimeField(descriptor,0x90) - :spin-psmRuntimeField(descriptor,0x90)); + particle[12]=firstRandom*psmDescriptor4(descriptor,0x1A4); + particle[19]=static_cast(psmEmissionSymmetric()*psmDescriptor4(descriptor,0x1A8)); + particle[34]=static_cast(psmEmissionSymmetric()*psmDescriptor4(descriptor,0x1AC)); + const double spin=psmEmissionSymmetric()*psmDescriptor4(descriptor,0x8C); + particle[33]=static_cast(spin>=0?spin+psmDescriptor4(descriptor,0x90) + :spin-psmDescriptor4(descriptor,0x90)); float direction[3]={0,0,0}; - switch(psmRuntimeField(descriptor,0x258)) + switch(psmDescriptor4(descriptor,0x258)) { case 0:psmType4EmissionSphere(direction,descriptor,self,particle);break; case 1:case 2:psmType4EmissionCylinder(direction,descriptor,self,particle);break; @@ -114,25 +129,25 @@ float* psmType4NewParticle(void* self) const float randomY=static_cast(psmEmissionSymmetric()); const float randomZ=static_cast(psmEmissionSymmetric()); Mat4 rotation,axis,copy; - psmEmissionRotation(rotation,randomX*psmRuntimeField(descriptor,0x1B4),0); - psmEmissionRotation(axis,randomY*psmRuntimeField(descriptor,0x1B8),1); + psmEmissionRotation(rotation,randomX*psmDescriptor4(descriptor,0x1B4),0); + psmEmissionRotation(axis,randomY*psmDescriptor4(descriptor,0x1B8),1); copy=rotation;psmEmissionRotateMultiply(rotation,copy,axis); - psmEmissionRotation(axis,randomZ*psmRuntimeField(descriptor,0x1BC),2); + psmEmissionRotation(axis,randomZ*psmDescriptor4(descriptor,0x1BC),2); copy=rotation;psmEmissionRotateMultiply(rotation,copy,axis); const float x=direction[0],y=direction[1],z=direction[2]; direction[2]=static_cast(static_cast(rotation.m[2])*x+static_cast(rotation.m[6])*y+static_cast(rotation.m[10])*z); direction[1]=static_cast(static_cast(rotation.m[1])*x+static_cast(rotation.m[9])*z+static_cast(rotation.m[5])*y); direction[0]=static_cast(static_cast(rotation.m[0])*x+static_cast(rotation.m[8])*z+static_cast(rotation.m[4])*y); - float speed=static_cast((psmRuntimeField(descriptor,0x1C0) - -static_cast(firstRandom)*psmRuntimeField(descriptor,0x1B0))*psmRuntimeField(self,0x13C)); - const float emitTime=psmRuntimeField(descriptor,0x1C4); - const double t=emitTime>0?1.0-static_cast(psmRuntimeField(self,0xE0))/emitTime:0; - const float envelope=static_cast(t*t*psmRuntimeField(descriptor,0x120)+t*psmRuntimeField(descriptor,0x124) - +t*t*t*psmRuntimeField(descriptor,0x11C)+psmRuntimeField(descriptor,0x128)); + float speed=static_cast((psmDescriptor4(descriptor,0x1C0) + -static_cast(firstRandom)*psmDescriptor4(descriptor,0x1B0))*psmInstanceA(self,0x13C)); + const float emitTime=psmDescriptor4(descriptor,0x1C4); + const double t=emitTime>0?1.0-static_cast(psmInstanceA(self,0xE0))/emitTime:0; + const float envelope=static_cast(t*t*psmDescriptor4(descriptor,0x120)+t*psmDescriptor4(descriptor,0x124) + +t*t*t*psmDescriptor4(descriptor,0x11C)+psmDescriptor4(descriptor,0x128)); speed*=psmEmissionClamp(envelope); - if(!psmRuntimeField(descriptor,0x211)) + if(!psmDescriptor4(descriptor,0x211)) { - const float* const matrix=psmRuntimeField(self,0x74).m; + const float* const matrix=psmInstanceA(self,0x74).m; const float px=particle[1],py=particle[2],pz=particle[3]; particle[3]=static_cast(static_cast(matrix[2])*px+static_cast(matrix[10])*pz+static_cast(matrix[6])*py+matrix[14]); particle[2]=static_cast(static_cast(matrix[1])*px+static_cast(matrix[9])*pz+static_cast(matrix[5])*py+matrix[13]); @@ -141,22 +156,22 @@ float* psmType4NewParticle(void* self) direction[2]=static_cast(static_cast(matrix[10])*dz+static_cast(matrix[2])*dx+static_cast(matrix[6])*dy); direction[1]=static_cast(static_cast(matrix[9])*dz+static_cast(matrix[1])*dx+static_cast(matrix[5])*dy); direction[0]=static_cast(static_cast(matrix[8])*dz+static_cast(matrix[4])*dy+static_cast(matrix[0])*dx); - const double scale=psmRuntimeField(self,0xDC); - const float inheritedX=static_cast(scale*psmRuntimeField(self,0xCC)); - const float inheritedY=static_cast(scale*psmRuntimeField(self,0xD0)); + const double scale=psmInstanceA(self,0xDC); + const float inheritedX=static_cast(scale*psmInstanceA(self,0xCC)); + const float inheritedY=static_cast(scale*psmInstanceA(self,0xD0)); const float vy=direction[1]*speed,vz=direction[2]*speed; - particle[25]=static_cast(vz+scale*psmRuntimeField(self,0xD4)); + particle[25]=static_cast(vz+scale*psmInstanceA(self,0xD4)); particle[23]=static_cast(static_cast(direction[0])*speed+inheritedX); particle[24]=vy+inheritedY; } else {particle[25]=direction[2]*speed;particle[23]=direction[0]*speed;particle[24]=direction[1]*speed;} - descriptor=psmRuntimeField(self,0x2C); - void* const region=psmRuntimeField(descriptor,0x254); - psmRuntimeField(particle,0x58)=region?psmRuntimeField(region,0x10):psmRuntimeField(descriptor,0x250); + descriptor=psmInstanceA(self,0x2C); + void* const region=psmDescriptor4(descriptor,0x254); + psmRecordPointer(particle, 4)=region?static_cast(static_cast(region)->page):psmDescriptor4(descriptor,0x250); // PE1023A414..440: four oriented unit corners (-1,0,1),(1,0,1),(1,0,-1),(-1,0,-1). // These are transformed even for local systems; retain the zero terms and retail sum order. static const float corners[4][3]={{-1,0,1},{1,0,1},{1,0,-1},{-1,0,-1}}; - const float* const basis=psmRuntimeField(self,0x74).m; + const float* const basis=psmInstanceA(self,0x74).m; for(unsigned int i=0;i<4;++i) { const float* const corner=corners[i]; @@ -166,81 +181,82 @@ float* psmType4NewParticle(void* self) particle[39+3*i]=static_cast(y); particle[40+3*i]=static_cast(z); } - float** const list=psmRuntimeField(self,0x24); - list[psmRuntimeField(self,0x28)++]=particle; - list[psmRuntimeField(self,0x28)]=nullptr; + float** const list=psmInstanceA(self,0x24); + list[psmInstanceA(self,0x28)++]=particle; + list[psmInstanceA(self,0x28)]=nullptr; return particle; } // PE1017E2F0; dt is intentionally unused. void psmType4Emit(void* self,float /*dt*/) { - if(!psmRuntimeField(self,0x14C))return; + if(!psmInstanceA(self,0x14C))return; const unsigned int frame=static_cast(dx9rend::g_rendererBase)->getFrameOrdinal(); - if(psmRuntimeField(self,0x124)+60u(self,0x124)+60u(self,0x129)=psmRuntimeField(self,0x128); - psmRuntimeField(self,0x128)=0;return; + psmInstanceA(self,0x129)=psmInstanceA(self,0x128); + psmInstanceA(self,0x128)=0;return; } - void* const descriptor=psmRuntimeField(self,0x2C); - const float lower=psmRuntimeField(descriptor,0xB4); - if(psmRuntimeField(self,0x134)(self,0x134)=lower; - if(psmRuntimeField(self,0x138)(self,0x138)=lower; - double frequency=static_cast(psmRuntimeField(descriptor,0x10))*psmRuntimeField(self,0x134)*psmRuntimeField(self,0x138); - void* const manager=g_ParticleSystemManager; - if(psmRuntimeField(descriptor,0x74)||psmRuntimeField(self,0xE8)>1.0f) + void* const descriptor=psmInstanceA(self,0x2C); + const float lower=psmDescriptor4(descriptor,0xB4); + if(psmInstanceA(self,0x134)(self,0x134)=lower; + if(psmInstanceA(self,0x138)(self,0x138)=lower; + double frequency=static_cast(psmDescriptor4(descriptor,0x10))*psmInstanceA(self,0x134)*psmInstanceA(self,0x138); + ParticleSystemManager* const manager=reinterpret_cast(g_ParticleSystemManager); + if(psmDescriptor4(descriptor,0x74)||psmInstanceA(self,0xE8)>1.0f) { - if(psmRuntimeField(manager,0x8A1C) - ||psmRuntimeField(manager,0x8BA0)>static_cast(static_cast( - static_cast(psmRuntimeField(manager,0x8B9C))*psmRuntimeField(manager,0x8C08)))) - frequency*=psmRuntimeField(manager,0x8BFC+4*psmRuntimeField(descriptor,0x68)); + // Retail manager +0x8A1C (the NSA renderer's over-limit byte), +0x8BA0, +0x8B9C, +0x8C08, +0x8BFC. + if(manager->m_nsaParticleSystemRenderer[0x424] + ||manager->m_type4LiveCount>static_cast(static_cast( + static_cast(static_cast(manager->m_type4PoolCount))*manager->m_value8C08))) + frequency*=manager->m_tierThresholds[psmDescriptor4(descriptor,0x68)]; } - if(!(frequency>psmRuntimeField(descriptor,0x14)))frequency=psmRuntimeField(descriptor,0x14); + if(!(frequency>psmDescriptor4(descriptor,0x14)))frequency=psmDescriptor4(descriptor,0x14); const float interval=static_cast(1.0/frequency); - if(psmRuntimeField(self,0x224)) - {psmRuntimeField(self,0xC0)=psmRuntimeField(self,0xB4);psmRuntimeField(self,0x224)=0;} - while(static_cast(interval)+psmRuntimeField(self,0xF0)<=psmRuntimeField(self,0xE8)) + if(psmInstanceA(self,0x224)) + {psmInstanceA(self,0xC0)=psmInstanceA(self,0xB4);psmInstanceA(self,0x224)=0;} + while(static_cast(interval)+psmInstanceA(self,0xF0)<=psmInstanceA(self,0xE8)) { - if(psmRuntimeField(self,0xE0)!=0) + if(psmInstanceA(self,0xE0)!=0) { - const double remaining=static_cast(psmRuntimeField(self,0xE0))-interval; - psmRuntimeField(self,0xE0)=static_cast(remaining); + const double remaining=static_cast(psmInstanceA(self,0xE0))-interval; + psmInstanceA(self,0xE0)=static_cast(remaining); if(remaining<=0) { static_cast(self)->reserved04(); - if(psmRuntimeField(psmRuntimeField(self,0x2C),0x74)) - static_cast(self)->reserved03(psmRuntimeField(self,6)!=0); + if(psmDescriptor4(psmInstanceA(self,0x2C),0x74)) + static_cast(self)->reserved03(psmInstanceA(self,6)!=0); return; } } - psmRuntimeField(self,0xF0)=interval+psmRuntimeField(self,0xF0); - if(psmRuntimeField(self,0x128)&&psmRuntimeField(self,0x28)(self,0x220)) + psmInstanceA(self,0xF0)=interval+psmInstanceA(self,0xF0); + if(psmInstanceA(self,0x128)&&psmInstanceA(self,0x28)(self,0x220)) { float fraction=0; - if(psmRuntimeField(self,0xE8)>psmRuntimeField(self,0xEC)) - fraction=static_cast((static_cast(psmRuntimeField(self,0xF0))-psmRuntimeField(self,0xEC)) - /(static_cast(psmRuntimeField(self,0xE8))-psmRuntimeField(self,0xEC))); - const Vec3& from=psmRuntimeField(self,0xC0); - const Vec3& to=psmRuntimeField(self,0xB4); + if(psmInstanceA(self,0xE8)>psmInstanceA(self,0xEC)) + fraction=static_cast((static_cast(psmInstanceA(self,0xF0))-psmInstanceA(self,0xEC)) + /(static_cast(psmInstanceA(self,0xE8))-psmInstanceA(self,0xEC))); + const Vec3& from=psmInstanceA(self,0xC0); + const Vec3& to=psmInstanceA(self,0xB4); const float zDifference=to.z-from.z; const float xScaled=static_cast((static_cast(to.x)-from.x)*fraction); const double yScaled=(static_cast(to.y)-from.y)*fraction; const float zScaled=zDifference*fraction; - psmRuntimeField(self,0xA4)={xScaled+from.x,static_cast(yScaled+from.y),zScaled+from.z}; + psmInstanceA(self,0xA4)={xScaled+from.x,static_cast(yScaled+from.y),zScaled+from.z}; float* const particle=psmType4NewParticle(self); if(particle) { - particle[23]+=psmRuntimeField(self,0x18); - particle[24]+=psmRuntimeField(self,0x1C); - particle[25]+=psmRuntimeField(self,0x20); + particle[23]+=psmInstanceA(self,0x18); + particle[24]+=psmInstanceA(self,0x1C); + particle[25]+=psmInstanceA(self,0x20); for(unsigned int axis=23;axis<=25;++axis)if(::fabs(particle[axis])<0.001f)particle[axis]=0; - const unsigned int steps=static_cast(static_cast((static_cast(psmRuntimeField(self,0xE8)) - -psmRuntimeField(self,0xF0))*100.0)); - if(psmType4AdvanceParticle(self,particle,psmRuntimeField(self,0x28)-1,0.01f,steps)) + const unsigned int steps=static_cast(static_cast((static_cast(psmInstanceA(self,0xE8)) + -psmInstanceA(self,0xF0))*100.0)); + if(psmType4AdvanceParticle(self,particle,psmInstanceA(self,0x28)-1,0.01f,steps)) { - const float remainder=static_cast((static_cast(psmRuntimeField(self,0xE8)) - -psmRuntimeField(self,0xF0))-static_cast(steps)*0.01f); - psmType4AdvanceParticle(self,particle,psmRuntimeField(self,0x28)-1,remainder,1); + const float remainder=static_cast((static_cast(psmInstanceA(self,0xE8)) + -psmInstanceA(self,0xF0))-static_cast(steps)*0.01f); + psmType4AdvanceParticle(self,particle,psmInstanceA(self,0x28)-1,remainder,1); } } } diff --git a/Code/BF2/Geom/ParticleSystem/ParticleInstanceType4Update.inl b/Code/BF2/Geom/ParticleSystem/ParticleInstanceType4Update.inl index cd565549f..645802013 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleInstanceType4Update.inl +++ b/Code/BF2/Geom/ParticleSystem/ParticleInstanceType4Update.inl @@ -1,21 +1,23 @@ // [CHOSEN, not recovered] private split; full PE1017CBF0/1017DA40/1017E6A0 read. // Type4 uses 200-byte particles, water-aligned oriented corners and a distinct descriptor layout. +// PE 0x1017DA40. Unordered timers take the update arm (AH&5 parity). void psmType4RememberPlane(void* self) { - if (psmRuntimeField(self,0x21C)>=0.33333001f) + if (!(psmInstanceA(self,0x21C)<0.33333001f)) { - const unsigned char next=psmRuntimeField(self,0x219); - psmRuntimeField(self,0x218)=next; - psmRuntimeField(self,0x21C)-=0.33333001f; - float* target=&psmRuntimeField(self,0x168+16*next); - const float* source=&psmRuntimeField(self,0x208); + const unsigned char next=psmInstanceA(self,0x219); + psmInstanceA(self,0x218)=next; + psmInstanceA(self,0x21C)-=0.33333001f; + float* target=&psmInstanceA(self,0x168+16*next); + const float* source=&psmInstanceA(self,0x208); target[0]=source[0]; target[1]=source[1]; target[2]=source[2]; const float distance=source[3]; psmNormalize3(target); target[3]=distance; - psmRuntimeField(self,0x219)=(psmRuntimeField(self,0x219)+1)%10; + psmInstanceA(self,0x219)=(psmInstanceA(self,0x219)+1)%10; } } +// PE 0x1017CBF0 int psmType4AdvanceParticle(void* self,float* particle,int index,float step,unsigned int steps) { ParticleSystemManager* const manager=reinterpret_cast(g_ParticleSystemManager); @@ -23,31 +25,31 @@ int psmType4AdvanceParticle(void* self,float* particle,int index,float step,unsi particle[29]=static_cast(age); if (age>=particle[30]) { - float** const array=psmRuntimeField(self,0x24); - const unsigned int last=--psmRuntimeField(self,0x28); + float** const array=psmInstanceA(self,0x24); + const unsigned int last=--psmInstanceA(self,0x28); array[index]=array[last]; array[last]=0; - psmRuntimeField(particle,0)=manager->m_type4FreeList; - --psmRuntimeField(manager,0x8BA0); manager->m_type4FreeList=particle; - ++psmRuntimeField(self,0x148); + psmRecordLink(particle, 4)=manager->m_type4FreeList; + --manager->m_type4LiveCount; manager->m_type4FreeList=particle; + ++psmInstanceA(self,0x148); return 0; } - void* descriptor=psmRuntimeField(self,0x2C); + void* descriptor=psmInstanceA(self,0x2C); Vec3 wind={0,0,0}; // This PE does not consult manager.m_windEnabled; the descriptor decides whether to query. - if (!psmRuntimeField(descriptor,0x211) && psmRuntimeField(descriptor,0x9C)>0) + if (!psmDescriptor4(descriptor,0x211) && psmDescriptor4(descriptor,0x9C)>0) wind=reinterpret_cast(manager->m_windManager)->getWind(*reinterpret_cast(particle+1)); - descriptor=psmRuntimeField(self,0x2C); - const float affection=psmRuntimeField(descriptor,0x9C); + descriptor=psmInstanceA(self,0x2C); + const float affection=psmDescriptor4(descriptor,0x9C); wind.x*=affection; wind.y*=affection; wind.z*=affection; - const float gravityStep=step*psmRuntimeField(descriptor,0x84); + const float gravityStep=step*psmDescriptor4(descriptor,0x84); const double t=particle[9]; - const float dragCurve=static_cast(t*psmRuntimeField(descriptor,0x114) - +t*t*psmRuntimeField(descriptor,0x110)+t*t*t*psmRuntimeField(descriptor,0x10C) - +psmRuntimeField(descriptor,0x118)); - const float drag=static_cast(static_cast(psmType0Clamp(dragCurve))*psmRuntimeField(descriptor,0x88)*step); - const float gravityCurve=static_cast(t*psmRuntimeField(descriptor,0x104) - +t*t*psmRuntimeField(descriptor,0x100)+t*t*t*psmRuntimeField(descriptor,0xFC) - +psmRuntimeField(descriptor,0x108)); + const float dragCurve=static_cast(t*psmDescriptor4(descriptor,0x114) + +t*t*psmDescriptor4(descriptor,0x110)+t*t*t*psmDescriptor4(descriptor,0x10C) + +psmDescriptor4(descriptor,0x118)); + const float drag=static_cast(static_cast(psmType0Clamp(dragCurve))*psmDescriptor4(descriptor,0x88)*step); + const float gravityCurve=static_cast(t*psmDescriptor4(descriptor,0x104) + +t*t*psmDescriptor4(descriptor,0x100)+t*t*t*psmDescriptor4(descriptor,0xFC) + +psmDescriptor4(descriptor,0x108)); const float gravity=psmType0Clamp(gravityCurve)*gravityStep; particle[9]=particle[31]*particle[29]; while (steps--) @@ -76,18 +78,27 @@ int psmType4AdvanceParticle(void* self,float* particle,int index,float step,unsi // NSA snaps after every substep, unlike the ordinary instance's post-loop snap. for (int i=23;i<=25;++i) if (::fabs(particle[i])<0.001f) particle[i]=0; } - descriptor=psmRuntimeField(self,0x2C); - if (psmRuntimeField(descriptor,0xDC)) + descriptor=psmInstanceA(self,0x2C); + if (psmDescriptor4(descriptor,0xDC)) { - const double difference=static_cast(psmRuntimeField(self,0x21C))-particle[29]; - const int current=psmRuntimeField(self,0x218); + const double difference=static_cast(psmInstanceA(self,0x21C))-particle[29]; + const int current=psmInstanceA(self,0x218); int selected=current; - if (difference<0) + // FCOM's carry branch also selects the history ring for an unordered age. + if (!(difference>=0)) { - selected-=static_cast(-3.0*difference)+1; - if (selected<0) selected+=10*((-1-selected)/10)+10; +#if defined(__APPLE__) + // [CHOSEN, not recovered] Preserve FISTP integer indefinite on native builds. + const int elapsed=bf2x87::toIntTruncate(bf2x87::mul(bf2x87::wide(-3.0f),bf2x87::wide(difference))); +#else + const int elapsed=static_cast(-3.0*difference); +#endif + selected=static_cast(static_cast(current)-static_cast(elapsed)-1u); + if (selected<0) selected=9-((-1-selected)%10); } - const float* plane=&psmRuntimeField(self,selected==current?0x208:0x168+16*selected); + // shipped defect: an unordered age can wrap the offset into preceding fields. + const unsigned int planeOffset=selected==current?0x208u:0x168u+16u*static_cast(selected); + const float* plane=&psmInstanceA(self,planeOffset); double velocityDot=static_cast(particle[25])*plane[2]+static_cast(particle[24])*plane[1]+static_cast(particle[23])*plane[0]; if (velocityDot<0) { @@ -102,7 +113,7 @@ int psmType4AdvanceParticle(void* self,float* particle,int index,float step,unsi { const double nx=velocityDot*plane[0], ny=velocityDot*plane[1]; const float nz=static_cast(velocityDot*plane[2]); - const float normal=psmRuntimeField(descriptor,0xE0), along=psmRuntimeField(descriptor,0xE4); + const float normal=psmDescriptor4(descriptor,0xE0), along=psmDescriptor4(descriptor,0xE4); const float tx=static_cast(particle[23]-nx), ty=static_cast(particle[24]-ny), tz=particle[25]-nz; const float rx=static_cast(nx*normal), ry=static_cast(ny*normal); particle[23]=static_cast(tx*along)-rx; particle[24]=static_cast(ty*along)-ry; @@ -114,9 +125,9 @@ int psmType4AdvanceParticle(void* self,float* particle,int index,float step,unsi reinterpret_cast(particle)[0x28]|=0x80; particle[4]=particle[1]; particle[5]=particle[2]; particle[6]=particle[3]; particle[26]=particle[23]; particle[27]=particle[24]; particle[28]=particle[25]; - if (psmRuntimeField(psmRuntimeField(self,0x2C),0x211)) + if (psmDescriptor4(psmInstanceA(self,0x2C),0x211)) { - const float* m=&psmRuntimeField(self,0x74); + const float* m=&psmInstanceA(self,0x74); const double z=static_cast(m[6])*particle[5]+static_cast(m[2])*particle[4]+static_cast(m[10])*particle[6]+m[14]; const double y=static_cast(m[5])*particle[5]+static_cast(m[1])*particle[4]+static_cast(m[9])*particle[6]+m[13]; particle[4]=static_cast(static_cast(m[4])*particle[5]+static_cast(m[8])*particle[6]+static_cast(m[0])*particle[4]+m[12]); @@ -135,76 +146,81 @@ int psmType4AdvanceParticle(void* self,float* particle,int index,float step,unsi particle[26]=static_cast(static_cast(m[8])*particle[28]+static_cast(m[4])*particle[27]+static_cast(m[0])*particle[26]); particle[27]=static_cast(vy); particle[28]=static_cast(vz); } - if (psmRuntimeField(psmRuntimeField(self,0x2C),0xA0) && manager->m_heightmapCluster) - particle[5]=reinterpret_cast(manager->m_heightmapCluster)->getWaterLevelInWorldCoords(*reinterpret_cast(particle+4)) - +psmRuntimeField(psmRuntimeField(self,0x2C),0xA4); - float* bounds=&psmRuntimeField(self,0xFC); + if (psmDescriptor4(psmInstanceA(self,0x2C),0xA0)) + { + ParticleSystemManager* const waterManager=reinterpret_cast(g_ParticleSystemManager); + if (waterManager->m_heightmapCluster) + particle[5]=reinterpret_cast(waterManager->m_heightmapCluster)->getWaterLevelInWorldCoords(*reinterpret_cast(particle+4)) + +psmDescriptor4(psmInstanceA(self,0x2C),0xA4); + } + float* bounds=&psmInstanceA(self,0xFC); for (int i=0;i<3;++i) { if(particle[4+i]>bounds[3+i]) bounds[3+i]=particle[4+i]; if(particle[4+i](self); ParticleSystemManager* const manager=reinterpret_cast(g_ParticleSystemManager); - const float scaled=dt*psmRuntimeField(self,0x12C); - void* descriptor=psmRuntimeField(self,0x2C); - psmRuntimeField(descriptor,8)=-1; + const float scaled=dt*psmInstanceA(self,0x12C); + void* descriptor=psmInstanceA(self,0x2C); + psmDescriptor4(descriptor,8)=-1; float elapsed=scaled; - if (!psmRuntimeField(self,0x28) && !psmRuntimeField(self,0x14C)) + if (!psmInstanceA(self,0x28) && !psmInstanceA(self,0x14C)) { psmQueueInactive(manager,instance); - if (psmRuntimeField(self,0x14)) + if (psmInstanceA(self,0x14)) reinterpret_cast(manager)->removeInstance(instance); return; } - if (psmRuntimeField(self,0x225) || scaled<=0) return; - if (!psmRuntimeField(self,0x129) && psmRuntimeField(self,0x128)) + if (psmInstanceA(self,0x225) || scaled<=0) return; + if (!psmInstanceA(self,0x129) && psmInstanceA(self,0x128)) { - psmRuntimeField(self,0x129)=psmRuntimeField(self,0x128); - if (psmRuntimeField(descriptor,0x25D)) - for (float time=psmRuntimeField(descriptor,0x7C);time>0;time-=0.1f) + psmInstanceA(self,0x129)=psmInstanceA(self,0x128); + if (psmDescriptor4(descriptor,0x25D)) + for (float time=psmDescriptor4(descriptor,0x7C);time>0;time-=0.1f) instance->reserved41(time>=0.1f?0.1f:time); } - descriptor=psmRuntimeField(self,0x2C); - if (psmRuntimeField(descriptor,0xDC)) - { psmRuntimeField(self,0x21C)+=scaled; psmType4RememberPlane(self); } - psmRuntimeField(self,0x148)=0; psmRuntimeField(self,0x144)=0; - const double maximum=static_cast(psmRuntimeField(descriptor,0x7C))+psmRuntimeField(descriptor,0x78); + descriptor=psmInstanceA(self,0x2C); + if (psmDescriptor4(descriptor,0xDC)) + { psmInstanceA(self,0x21C)+=scaled; psmType4RememberPlane(self); } + psmInstanceA(self,0x148)=0; psmInstanceA(self,0x144)=0; + const double maximum=static_cast(psmDescriptor4(descriptor,0x7C))+psmDescriptor4(descriptor,0x78); if (scaled>maximum) elapsed=static_cast(maximum); - for (int i=0;i<3;++i) { psmRuntimeField(self,0xFC+i*4)=0x4B18967F; psmRuntimeField(self,0x108+i*4)=0xCB18967F; } - psmRuntimeField(self,0xC0)=psmRuntimeField(self,0xA4); + for (int i=0;i<3;++i) { psmInstanceA(self,0xFC+i*4)=0x4B18967F; psmInstanceA(self,0x108+i*4)=0xCB18967F; } + psmInstanceA(self,0xC0)=psmInstanceA(self,0xA4); psmType4RefreshTransform(self); - psmRuntimeField(self,0xB4)=psmRuntimeField(self,0xA4); - const double total=static_cast(elapsed)+psmRuntimeField(self,0xF4); + psmInstanceA(self,0xB4)=psmInstanceA(self,0xA4); + const double total=static_cast(elapsed)+psmInstanceA(self,0xF4); const unsigned int steps=static_cast(static_cast(100.0*total)); const double advanced=static_cast(steps)*0.01f; - psmRuntimeField(self,0xEC)=psmRuntimeField(self,0xE8); - psmRuntimeField(self,0xF4)=static_cast(total-advanced); - psmRuntimeField(self,0xE8)=static_cast(advanced+psmRuntimeField(self,0xE8)); - for (unsigned int i=0;psmRuntimeField(self,0x24)[i];) - i+=psmType4AdvanceParticle(self,psmRuntimeField(self,0x24)[i],i,0.01f,steps); - const double delay=static_cast(psmRuntimeField(self,0xE4))-elapsed; - psmRuntimeField(self,0xE4)=static_cast(delay); - if (delay>0) { psmRuntimeField(self,0xF0)=psmRuntimeField(self,0xE8); return; } - if (psmRuntimeField(self,0xF8)>0) + psmInstanceA(self,0xEC)=psmInstanceA(self,0xE8); + psmInstanceA(self,0xF4)=static_cast(total-advanced); + psmInstanceA(self,0xE8)=static_cast(advanced+psmInstanceA(self,0xE8)); + for (unsigned int i=0;psmInstanceA(self,0x24)[i];) + i+=psmType4AdvanceParticle(self,psmInstanceA(self,0x24)[i],i,0.01f,steps); + const double delay=static_cast(psmInstanceA(self,0xE4))-elapsed; + psmInstanceA(self,0xE4)=static_cast(delay); + if (delay>0) { psmInstanceA(self,0xF0)=psmInstanceA(self,0xE8); return; } + if (psmInstanceA(self,0xF8)>0) { - float remaining=psmRuntimeField(self,0xF8); psmRuntimeField(self,0xF8)=0; + float remaining=psmInstanceA(self,0xF8); psmInstanceA(self,0xF8)=0; for (;remaining>0;remaining-=0.033333335f) instance->reserved41(remaining>=0.033333335f?0.033333335f:remaining); } psmType4Emit(self,elapsed); - psmRuntimeField(self,0xA4)=psmRuntimeField(self,0xB4); - float* bounds=&psmRuntimeField(self,0xFC); - if (psmRuntimeField(self,0x28)) + psmInstanceA(self,0xA4)=psmInstanceA(self,0xB4); + float* bounds=&psmInstanceA(self,0xFC); + if (psmInstanceA(self,0x28)) { - for (int i=0;i<3;++i) bounds[i]-=psmRuntimeField(psmRuntimeField(self,0x2C),0x138); - for (int i=3;i<6;++i) bounds[i]+=psmRuntimeField(psmRuntimeField(self,0x2C),0x138); + for (int i=0;i<3;++i) bounds[i]-=psmDescriptor4(psmInstanceA(self,0x2C),0x138); + for (int i=3;i<6;++i) bounds[i]+=psmDescriptor4(psmInstanceA(self,0x2C),0x138); } - else { psmRuntimeField(self,0xFC)=psmRuntimeField(self,0xA4); psmRuntimeField(self,0x108)=psmRuntimeField(self,0xA4); } + else { psmInstanceA(self,0xFC)=psmInstanceA(self,0xA4); psmInstanceA(self,0x108)=psmInstanceA(self,0xA4); } const float dz=bounds[5]-bounds[2], dx=static_cast((static_cast(bounds[3])-bounds[0])*0.5); const double dy=(static_cast(bounds[4])-bounds[1])*0.5; - psmRuntimeField(self,0x120)=static_cast(::sqrt(dz*0.5*(dz*0.5)+static_cast(dx)*dx+dy*dy)); + psmInstanceA(self,0x120)=static_cast(::sqrt(dz*0.5*(dz*0.5)+static_cast(dx)*dx+dy*dy)); const float zsum=bounds[5]+bounds[2]; - psmRuntimeField(self,0x114)={static_cast((static_cast(bounds[3])+bounds[0])*0.5),static_cast((static_cast(bounds[4])+bounds[1])*0.5),zsum*0.5f}; + psmInstanceA(self,0x114)={static_cast((static_cast(bounds[3])+bounds[0])*0.5),static_cast((static_cast(bounds[4])+bounds[1])*0.5),zsum*0.5f}; } diff --git a/Code/BF2/Geom/ParticleSystem/ParticleManagerRuntime.inl b/Code/BF2/Geom/ParticleSystem/ParticleManagerRuntime.inl index 05572d975..51e9f952b 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleManagerRuntime.inl +++ b/Code/BF2/Geom/ParticleSystem/ParticleManagerRuntime.inl @@ -5,31 +5,50 @@ template T& psmRuntimeField(void* object, unsigned int offset) { return *reinterpret_cast(static_cast(object) + offset); } -vc71::set_layout& psmReclassification(ParticleSystemManager* self) -{ return *reinterpret_cast(self->m_pendingReclassificationTree); } +// PE 0x1017A2B0. Grow the instance bounds {min x, y, z, max x, y, z} to include a point: per axis the +// maximum is tested before the minimum, with ordered compares, so NaN never moves a bound. +void psmIncludeBoundsPoint(float* bounds, float x, float y, float z) +{ + if (x > bounds[3]) bounds[3] = x; + if (x < bounds[0]) bounds[0] = x; + if (y > bounds[4]) bounds[4] = y; + if (y < bounds[1]) bounds[1] = y; + if (z > bounds[5]) bounds[5] = z; + if (z < bounds[2]) bounds[2] = z; +} + +std::set& psmReclassification(ParticleSystemManager* self) +{ return self->m_pendingReclassification; } + +// [INFERRED] Private name for the existing guarded reclassification insertion. +// PE 0x100D3650 +void psmQueueReclassification(ParticleSystemManager* self,IParticleSystemInstance* instance) +{ + if (psmInstance(instance,4)) + psmReclassification(self).insert(instance); +} -void psmPush(ParticleSystemInstanceList& list, IParticleSystemInstance* instance) -{ vc71::vectorRef(&list).push_back(instance); } +void psmPush(ParticleSystemInstanceVector& list, IParticleSystemInstance* instance) +{ list.push_back(instance); } -// The renderer Debug stream is still a named boundary on the shipped invalid-state assertions. -// Valid scheduling does not pass through these sites. [FRONTIER] -void psmRuntimeError(ParticleSystemManager* self, const char* message) +// Shared source-level spelling for the type-6 diagnostics in PE 0x100D3FB0/0x100D4500/0x100D4820. +void psmRuntimeError(unsigned int line, const char* message) { - RD9_FRONTIER_AT(message, self, 0); - std::abort(); + ::renddx9abi::Debug(DebugTypeError, + "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\ParticleSystem\\ParticleSystemManager.cpp", + static_cast(line), "") << message; } // Add first, then classify. A trail forcibly clears both first-person flags. void psmAddActive(ParticleSystemManager* self, IParticleSystemInstance* instance, bool firstPerson) { - if (psmRuntimeField(instance, 4)) - psmRuntimeError(self, "dice::hfe::geom::ParticleSystemManager::addActiveInstance " - "(Debug: Trying to add instance twice)"); + if (psmInstance(instance, 4)) + psmRuntimeError(555, "Trying to add instance twice"); if (instance->getEffectController()) instance->getEffectController()->addNumEmittersPlaying(); - psmRuntimeField(instance, 4) = 1; - psmRuntimeField(instance, 6) = firstPerson; - psmRuntimeField(instance, 7) = firstPerson; + psmInstance(instance, 4) = 1; + psmInstance(instance, 6) = firstPerson; + psmInstance(instance, 7) = firstPerson; const bool water = instance->getWaterSide(); const int type = instance->reserved01(); int bucket; @@ -40,21 +59,20 @@ void psmAddActive(ParticleSystemManager* self, IParticleSystemInstance* instance case 2: bucket = 5 + water; break; case 4: bucket = firstPerson ? 8 : 0; break; default: - psmRuntimeError(self, "dice::hfe::geom::ParticleSystemManager::addActiveInstance " - "(Debug: Invalid template type)"); + psmRuntimeError(634, "trying to push unknown instance"); return; } - ParticleSystemInstanceList& list = self->m_renderBuckets[bucket]; + ParticleSystemInstanceVector& list = self->m_renderBuckets[bucket]; if (!firstPerson || type == 2) - for (IParticleSystemInstance** cursor = list.first; cursor != list.last; ++cursor) + for (ParticleSystemInstanceVector::iterator cursor = list.begin(); cursor != list.end(); ++cursor) if (*cursor == instance) - psmRuntimeError(self, "dice::hfe::geom::ParticleSystemManager::addActiveInstance " - "(Debug: Blah already added)"); + psmRuntimeError(type == 0 || type == 3 ? 579 : type == 1 ? 596 : type == 2 ? 609 : 621, + "Blah already added"); psmPush(list, instance); if (type == 2) { - psmRuntimeField(instance, 6) = 0; - psmRuntimeField(instance, 7) = 0; + psmInstance(instance, 6) = 0; + psmInstance(instance, 7) = 0; } } @@ -63,27 +81,29 @@ void psmQueueInactive(ParticleSystemManager* self, IParticleSystemInstance* inst { psmPush(self->m_pendingClassification, instance); } // Pending-list end and selected bucket storage are reread after callbacks. +// PE 0x100D4500 void psmRemoveActive(ParticleSystemManager* self, bool preserveReclassification) { - for (IParticleSystemInstance** cursor = self->m_pendingClassification.first; - cursor != self->m_pendingClassification.last; ++cursor) + // PE keeps ESI across pending entries. A suppressed first-person-trail error reuses it. + ParticleSystemInstanceVector* selected = 0; + for (IParticleSystemInstance** cursor = self->m_pendingClassification.data(); + cursor != self->m_pendingClassification.data() + self->m_pendingClassification.size(); + ++cursor) { IParticleSystemInstance* const instance = *cursor; - int bucket; - if (psmRuntimeField(instance, 6)) + if (psmInstance(instance, 6)) { switch (instance->reserved01()) { - case 0: case 3: bucket = 7; break; - case 1: bucket = 9; break; - case 4: bucket = 8; break; + case 0: case 3: selected = &self->m_renderBuckets[7]; break; + case 1: selected = &self->m_renderBuckets[9]; break; + case 4: selected = &self->m_renderBuckets[8]; break; case 2: - psmRuntimeError(self, "dice::hfe::geom::ParticleSystemManager::removeActiveInstances " - "(Debug: Trail should not be 1p)"); - return; + // Shipped defect: a suppressed diagnostic keeps the prior (possibly null) bucket. + psmRuntimeError(735, "Trail should not be 1p"); + break; default: - psmRuntimeError(self, "dice::hfe::geom::ParticleSystemManager::removeActiveInstances " - "(Debug: Invalid template type)"); + psmRuntimeError(743, "trying to push unknown instance"); return; } } @@ -92,73 +112,74 @@ void psmRemoveActive(ParticleSystemManager* self, bool preserveReclassification) const bool water = instance->getWaterSide(); switch (instance->reserved01()) { - case 0: case 3: bucket = 1 + water; break; - case 1: bucket = 3 + water; break; - case 2: bucket = 5 + water; break; - case 4: bucket = 0; break; + case 0: case 3: selected = &self->m_renderBuckets[1 + water]; break; + case 1: selected = &self->m_renderBuckets[3 + water]; break; + case 2: selected = &self->m_renderBuckets[5 + water]; break; + case 4: selected = &self->m_renderBuckets[0]; break; default: - psmRuntimeError(self, "dice::hfe::geom::ParticleSystemManager::removeActiveInstances " - "(Debug: Invalid template type)"); + psmRuntimeError(717, "trying to push unknown instance"); return; } } if (!preserveReclassification) - vc71::setEraseValue(psmReclassification(self), instance); - ParticleSystemInstanceList& list = self->m_renderBuckets[bucket]; + psmReclassification(self).erase(instance); + ParticleSystemInstanceVector& list = *selected; for (unsigned int i = 0; i < list.size(); ++i) - if (list.first[i] == instance) + if (list.data()[i] == instance) { - psmRuntimeField(instance, 4) = 0; + psmInstance(instance, 4) = 0; if (instance->getEffectController()) instance->getEffectController()->decNumEmittersPlaying(); - list.first[i] = list.last[-1]; - if (list.size()) --list.last; + list.data()[i] = list.back(); + if (list.size()) list.pop_back(); break; } } - self->m_pendingClassification.last = self->m_pendingClassification.first; + self->m_pendingClassification.clear(); } // destroy only entries still present in the master list; duplicates are harmless. void psmDrainDestroy(ParticleSystemManager* self) { - for (IParticleSystemInstance** cursor = self->m_pendingDestroy.first; - cursor != self->m_pendingDestroy.last; ++cursor) + for (IParticleSystemInstance** cursor = self->m_pendingDestroy.data(); + cursor != self->m_pendingDestroy.data() + self->m_pendingDestroy.size(); ++cursor) { IParticleSystemInstance* const instance = *cursor; for (unsigned int i = 0; i < self->m_instances.size(); ++i) - if (self->m_instances.first[i] == instance) + if (self->m_instances[i] == instance) { - self->m_instances.first[i] = self->m_instances.last[-1]; - --self->m_instances.last; + self->m_instances[i] = self->m_instances.back(); + self->m_instances.pop_back(); if (instance) instance->destroy(); break; } } - self->m_pendingDestroy.last = self->m_pendingDestroy.first; + self->m_pendingDestroy.clear(); } +// PE 0x100D4FD0 void psmReclassify(ParticleSystemManager* self) { - vc71::set_layout& pending = psmReclassification(self); - for (vc71::set_node* n = pending.begin(); n != pending.end(); n = vc71::set_layout::next(n)) - psmPush(self->m_pendingClassification, reinterpret_cast(n->key)); + std::set& pending = psmReclassification(self); + for (std::set::iterator n = pending.begin(); n != pending.end(); ++n) + psmPush(self->m_pendingClassification, *n); psmRemoveActive(self, true); - for (vc71::set_node* n = pending.begin(); n != pending.end(); n = vc71::set_layout::next(n)) + for (std::set::iterator n = pending.begin(); n != pending.end(); ++n) { - IParticleSystemInstance* const instance = reinterpret_cast(n->key); - psmAddActive(self, instance, psmRuntimeField(instance, 7) != 0); + IParticleSystemInstance* const instance = *n; + psmAddActive(self, instance, psmInstance(instance, 7) != 0); } pending.clear(); } // reverse snapshot traversal, reread storage per element, skip only byte +5. -void psmUpdateBucket(ParticleSystemInstanceList& list, float dt) +// PE 0x100D6310 +void psmUpdateBucket(ParticleSystemInstanceVector& list, float dt) { for (int i = static_cast(list.size()) - 1; i >= 0; --i) { - IParticleSystemInstance* const instance = list.first[i]; - if (!psmRuntimeField(instance, 5)) instance->reserved41(dt); + IParticleSystemInstance* const instance = list.data()[i]; + if (!psmInstance(instance, 5)) instance->reserved41(dt); } } @@ -167,7 +188,9 @@ struct PsmViewContext dx9rend::IRenderView* view; Vec3 position; float scaleX, scaleY; - explicit PsmViewContext(dx9rend::IRenderView* value) : view(value) + // PE 0x100D5D20 + explicit PsmViewContext(dx9rend::IRenderView* value) + : view(value), position{0,0,0}, scaleX(0.0f), scaleY(0.0f) { const float* const matrix = reinterpret_cast(view->getViewMatrixPtr()); position.x = matrix[12]; position.y = matrix[13]; position.z = matrix[14]; @@ -182,52 +205,92 @@ struct PsmViewContext } }; -// PE 10176A50/10178310/101799C0, with the identical aabb test at 10175C80. These three +// PE 0x10175C80 +bool psmCoverageContainsPoint(const Vec3& low, const Vec3& high, const Vec3& point) +{ + return point.x>=low.x && point.y>=low.y && point.z>=low.z + && point.x<=high.x && point.y<=high.y && point.z<=high.z; +} + +#if defined(__APPLE__) +// [CHOSEN, not recovered] Return the live x87 expression to the caller's float store. +using PsmCoverageReal=bf2x87::Real; +#else +using PsmCoverageReal=double; +#endif + +// PE 0x10176A50 / PE 0x10178310 / PE 0x101799C0. These three // descriptor helpers differ only in their descriptor LOD-index offset (64/6C/68). -double psmCoverage(IParticleSystemInstance* instance, const PsmViewContext& context, - unsigned int lodOffset) +// boundsOffset is the retail offset of the instance's low corner: the high corner follows at +0xC, the +// centre at +0x18 and the bounding radius at +0x24 (the trail instance at 0xF8 uses the same layout). +PsmCoverageReal psmCoverage(IParticleSystemInstance* instance, const PsmViewContext& context, + unsigned int lodOffset, unsigned int boundsOffset = 0xFC) { - const float* const data = reinterpret_cast(instance); + const Vec3& low=psmInstance(instance,boundsOffset); + const Vec3& high=psmInstance(instance,boundsOffset+0xC); + const Vec3& center=psmInstance(instance,boundsOffset+0x18); const Vec3& p = context.position; - if (p.x >= data[63] && p.y >= data[64] && p.z >= data[65] - && p.x <= data[66] && p.y <= data[67] && p.z <= data[68]) + if (psmCoverageContainsPoint(low,high,p)) return 1.0; - const double height = static_cast(data[67]) - data[64]; - const float h = static_cast(height), depth = data[68] - data[65]; - const double radius = data[72] * static_cast( - height > static_cast(data[66]) - data[63] && h > depth +#if defined(__APPLE__) + using bf2x87::wide; +#else + const auto wide=[](double value) { return value; }; +#endif + const PsmCoverageReal width=wide(high.x)-wide(low.x),height=wide(high.y)-wide(low.y); + const float h=static_cast(height),depth=static_cast(wide(high.z)-wide(low.z)); + const PsmCoverageReal radius=wide(psmInstance(instance,boundsOffset+0x24))*wide( + height > width && h > depth ? context.scaleY : context.scaleX); - const float dx = p.x - data[69]; - const double dy = static_cast(p.y) - data[70], dz = static_cast(p.z) - data[71]; - const float distance = static_cast(::sqrt(dz * dz + dy * dy + static_cast(dx) * dx)); - void* const descriptor = psmRuntimeField(instance, 0x2C); - const int lod = psmRuntimeField(descriptor, lodOffset); + const float dx=static_cast(wide(p.x)-wide(center.x)); + const PsmCoverageReal dy=wide(p.y)-wide(center.y),dz=wide(p.z)-wide(center.z); + const PsmCoverageReal squared=dz*dz+dy*dy+wide(dx)*wide(dx); +#if defined(__APPLE__) + const float distance=static_cast(bf2x87::squareRoot(squared)); +#else + const float distance=static_cast(::sqrt(squared)); +#endif + void* const descriptor = psmInstance(instance, 0x2C); + const int lod = psmDescriptor(descriptor, lodOffset); ParticleSystemManager* const published = reinterpret_cast(g_ParticleSystemManager); + const PsmCoverageReal projected=radius/wide(distance); const float nearDistance = published->m_nearDistances[lod]; - double nearCoverage = 1.0; + PsmCoverageReal nearCoverage=wide(1); if (distance > nearDistance) { - double amount = (static_cast(distance) - nearDistance) * published->m_inverseNearRanges[lod]; - if (amount > 1.0) amount = 1.0; - nearCoverage = (1.0 - amount) * (1.0 - amount); + PsmCoverageReal amount=(wide(distance)-wide(nearDistance))*wide(published->m_inverseNearRanges[lod]); + if (amount > wide(1)) amount=wide(1); + const PsmCoverageReal remaining=wide(1)-amount; + nearCoverage=remaining*remaining; } - const double result = radius / distance + nearCoverage; - return result > 1.0 ? 1.0 : result; + const PsmCoverageReal result=projected+nearCoverage; + return result>wide(1) ? wide(1) : result; +} + +// PE 0x10187B00. The trail instance's copy of the coverage helper: its bounds start at +0xF8 and its +// descriptor LOD index is read at +0x68. Unreachable in 1.50: no code or data references. The name is +// [CHOSEN, not recovered]. +PsmCoverageReal psmTrailCoverage(IParticleSystemInstance* instance, const PsmViewContext& context) +{ + return psmCoverage(instance, context, 0x68, 0xF8); } -void psmPrepareBucket(ParticleSystemInstanceList& list, const PsmViewContext& context, int type) +// PE 0x100D5DE0, 0x100D5E40, 0x100D5EA0: the ordinary, NSA and mesh copies (each calls its own +// psmCoverage copy and stores +0x134 / +0x134 / +0x12C). +void psmPrepareBucket(ParticleSystemInstanceVector& list, const PsmViewContext& context, int type) { - IParticleSystemInstance** const end = list.last; - for (IParticleSystemInstance** cursor = list.first; cursor != end; ++cursor) + IParticleSystemInstance** const end = list.data() + list.size(); + for (IParticleSystemInstance** cursor = list.data(); cursor != end; ++cursor) if ((*cursor)->reserved01() == type) { IParticleSystemInstance* const instance = *cursor; if (instance->reserved10() && instance->reserved05()) - psmRuntimeField(instance, type == 1 ? 0x12C : 0x134) = static_cast( + psmInstance(instance, type == 1 ? 0x12C : 0x134) = static_cast( psmCoverage(instance, context, type == 0 ? 0x64 : type == 4 ? 0x6C : 0x68)); } } +// PE 0x100D3350 void psmPrepareClassifiedVectors(ParticleSystemManager* self, dx9rend::IRenderView* view) { const PsmViewContext context(view); diff --git a/Code/BF2/Geom/ParticleSystem/ParticleRawLayout.h b/Code/BF2/Geom/ParticleSystem/ParticleRawLayout.h new file mode 100644 index 000000000..acb2bbfd6 --- /dev/null +++ b/Code/BF2/Geom/ParticleSystem/ParticleRawLayout.h @@ -0,0 +1,358 @@ +// Native placement of the particle system's byte-offset objects: the five descriptor types, the five +// instance types, the five pool-record types and the four renderers the manager embeds. The code +// addresses their fields by retail x86 offset; the functions below turn a retail offset into the +// offset this build stores the field at. +// +// x86: every function is the identity and every size is the retail size, so the objects keep their +// exact retail layout. +// +// x64 [CHOSEN, not recovered] (https://github.com/B2BF/OpenBF2/issues/7): a pointer, a host string or a +// std::vector no longer fits its retail 4-, 28- or 16-byte span, and a hand-built or C++ vptr takes +// 8 bytes. Each such field moves into a block appended after the retail bytes (the tail); for the +// polymorphic objects the retail bytes +4..+7, which the wider vptr covers, move there as well. +// Every other retail byte keeps its retail offset, so runs of scalar fields stay contiguous and code +// that never touches a moved field addresses the same bytes on both architectures. + +#ifndef BF2_GEOM_PARTICLESYSTEM_PARTICLERAWLAYOUT_H +#define BF2_GEOM_PARTICLESYSTEM_PARTICLERAWLAYOUT_H + +#include + +namespace dice { +namespace hfe { +namespace geom { + +// A field at an offset that is already native. +template inline T& psmRawField(void* object, unsigned int nativeOffset) +{ + return *reinterpret_cast(static_cast(object) + nativeOffset); +} + +// Marks a relocation slot a layout does not use. +const unsigned int kPsmNoField = 0xFFFFFFFFu; + +// Bytes per entry of the engine-allocated pointer tables (retail 4). +const unsigned int kPsmPointerSize = sizeof(void*); + +// Instances. Pointer fields shared by all five types: effect controller +0x0C, owner +0x10, +// descriptor +0x2C, parent matrix +0x30 and (type 0 only) player +0x230. The particle list is +0x24 +// in types 0 and 4 and +0x14 in types 1, 2 and 3; at the other offset those types keep a scalar. +const unsigned int kPsmInstanceListA = 0x24; // types 0 and 4 +const unsigned int kPsmInstanceListB = 0x14; // types 1, 2 and 3 + +#if defined(_M_IX86) + +inline unsigned int psmInstanceOffset(unsigned int retail, unsigned int) { return retail; } +// Bytes an instance class declares after its vptr. +#define PSM_INSTANCE_DATA(retailSize) ((retailSize) - 4u) + +#else + +const unsigned int kPsmInstanceTail = 0x240; // past the largest retail instance (type 0, 0x23C) +const unsigned int kPsmInstanceSize = kPsmInstanceTail + 0x38; + +inline unsigned int psmInstanceOffset(unsigned int retail, unsigned int list) +{ + if (retail - 4u < 4u) + return kPsmInstanceTail + (retail - 4u); // the flag bytes +4..+7 + switch (retail) + { + case 0x0C: return kPsmInstanceTail + 0x08; + case 0x10: return kPsmInstanceTail + 0x10; + case 0x2C: return kPsmInstanceTail + 0x20; + case 0x30: return kPsmInstanceTail + 0x28; + case 0x230: return kPsmInstanceTail + 0x30; + } + return retail == list ? kPsmInstanceTail + 0x18 : retail; +} +#define PSM_INSTANCE_DATA(retailSize) (kPsmInstanceSize - 8u) + +#endif + +// Instance fields by retail offset: types 0/4, types 1/2/3, and any type (never the particle list). +template inline T& psmInstanceA(void* instance, unsigned int retail) +{ return psmRawField(instance, psmInstanceOffset(retail, kPsmInstanceListA)); } +template inline T& psmInstanceB(void* instance, unsigned int retail) +{ return psmRawField(instance, psmInstanceOffset(retail, kPsmInstanceListB)); } +template inline T& psmInstance(void* instance, unsigned int retail) +{ return psmRawField(instance, psmInstanceOffset(retail, kPsmNoField)); } +template inline const T& psmConstInstanceB(const void* instance, unsigned int retail) +{ return psmInstanceB(const_cast(instance), retail); } + +// Descriptors. Each type holds two host strings and up to three pointers: +// type 0: strings +0x224 / +0x240, texture +0x25C, atlas region +0x260, collector +0x2A0 +// type 1: strings +0x070 / +0x1F4, geometry +0x8C, texture +0x210 +// type 2: strings +0x1E4 / +0x200, texture +0x21C +// type 3: strings +0x06C / +0x16C, child template +0x88 +// type 4: strings +0x218 / +0x234, texture +0x250, atlas region +0x254 +// The 16-bit template id at +0x04 is shared by all types. + +#if defined(_M_IX86) + +inline unsigned int psmDescriptorOffset(unsigned int retail, unsigned int, unsigned int, + unsigned int, unsigned int, unsigned int) +{ + return retail; +} +// Bytes a descriptor of the given retail size occupies; a host string's reserved span. +#define PSM_DESCRIPTOR_SIZE(retailSize) (retailSize) +const unsigned int kPsmDescriptorStringSpan = 28; + +#else + +const unsigned int kPsmDescriptorTail = 0x2A8; // past the largest retail descriptor (type 0, 0x2A4) + +inline unsigned int psmDescriptorOffset(unsigned int retail, unsigned int string0, + unsigned int string1, unsigned int pointer0, + unsigned int pointer1, unsigned int pointer2) +{ + if (retail - 4u < 4u) + return kPsmDescriptorTail + (retail - 4u); // the template id word + if (retail == string0) return kPsmDescriptorTail + 0x08; + if (retail == string1) return kPsmDescriptorTail + 0x28; + if (retail == pointer0) return kPsmDescriptorTail + 0x48; + if (retail == pointer1) return kPsmDescriptorTail + 0x50; + if (retail == pointer2) return kPsmDescriptorTail + 0x58; + return retail; +} +#define PSM_DESCRIPTOR_SIZE(retailSize) (kPsmDescriptorTail + 0x60u) +const unsigned int kPsmDescriptorStringSpan = 32; + +#endif + +inline unsigned int psmDescriptor0Offset(unsigned int retail) +{ return psmDescriptorOffset(retail, 0x224, 0x240, 0x25C, 0x260, 0x2A0); } +inline unsigned int psmDescriptor1Offset(unsigned int retail) +{ return psmDescriptorOffset(retail, 0x070, 0x1F4, 0x08C, 0x210, kPsmNoField); } +inline unsigned int psmDescriptor2Offset(unsigned int retail) +{ return psmDescriptorOffset(retail, 0x1E4, 0x200, 0x21C, kPsmNoField, kPsmNoField); } +inline unsigned int psmDescriptor3Offset(unsigned int retail) +{ return psmDescriptorOffset(retail, 0x06C, 0x16C, 0x088, kPsmNoField, kPsmNoField); } +inline unsigned int psmDescriptor4Offset(unsigned int retail) +{ return psmDescriptorOffset(retail, 0x218, 0x234, 0x250, 0x254, kPsmNoField); } +// Any descriptor type: the scalar fields and the template id. +inline unsigned int psmDescriptorCommonOffset(unsigned int retail) +{ return psmDescriptorOffset(retail, kPsmNoField, kPsmNoField, kPsmNoField, kPsmNoField, kPsmNoField); } + +// Descriptor vtable thunks. A float argument: x86 thiscall passes it in a 4-byte stack slot that the +// shipped setters store bit for bit, so the thunks keep taking it as an unsigned there; x64 passes a +// float in an XMM register. A Vec3 by value: three stack dwords on x86, a pointer to the caller's +// copy on x64. A bool: only the low byte is defined on x64. +#if defined(_M_IX86) +typedef unsigned int PsmFloatArg; +inline unsigned int psmFloatArgBits(PsmFloatArg value) { return value; } +inline PsmFloatArg psmFloatArgFromBits(unsigned int bits) { return bits; } +inline unsigned int psmBoolArg(unsigned int value) { return value; } +#define PSM_VEC3_PARAMS unsigned a, unsigned b, unsigned c +#define PSM_VEC3_X a +#define PSM_VEC3_Y b +#define PSM_VEC3_Z c +#else +typedef float PsmFloatArg; +inline unsigned int psmFloatArgBits(PsmFloatArg value) +{ + unsigned int bits; + static_assert(sizeof(bits) == sizeof(value), "float is 32 bits"); + ::memcpy(&bits, &value, sizeof(bits)); + return bits; +} +inline PsmFloatArg psmFloatArgFromBits(unsigned int bits) +{ + float value; + ::memcpy(&value, &bits, sizeof(value)); + return value; +} +inline unsigned int psmBoolArg(unsigned int value) { return value & 0xFFu; } +#define PSM_VEC3_PARAMS const unsigned int* vec3 +#define PSM_VEC3_X vec3[0] +#define PSM_VEC3_Y vec3[1] +#define PSM_VEC3_Z vec3[2] +#endif + +template inline T& psmDescriptor0(void* d, unsigned int retail) { return psmRawField(d, psmDescriptor0Offset(retail)); } +template inline T& psmDescriptor1(void* d, unsigned int retail) { return psmRawField(d, psmDescriptor1Offset(retail)); } +template inline T& psmDescriptor2(void* d, unsigned int retail) { return psmRawField(d, psmDescriptor2Offset(retail)); } +template inline T& psmDescriptor3(void* d, unsigned int retail) { return psmRawField(d, psmDescriptor3Offset(retail)); } +template inline T& psmDescriptor4(void* d, unsigned int retail) { return psmRawField(d, psmDescriptor4Offset(retail)); } +template inline T& psmDescriptor(void* d, unsigned int retail) { return psmRawField(d, psmDescriptorCommonOffset(retail)); } + +// Pool records, by particle type. Retail word 0 is the free-list link (and the draw sorter's chain +// link); types 0 and 4 keep the particle's texture at +0x5C / +0x58 and type 3 its child instance at +// +0xAC. Every other word is a scalar and keeps its retail offset. +#if defined(_M_IX86) +inline unsigned int psmRecordStride(unsigned int type) +{ + static const unsigned int strides[5] = { 148, 192, 168, 176, 200 }; + return strides[type]; +} +inline unsigned int psmRecordLinkOffset(unsigned int) { return 0; } +inline unsigned int psmRecordPointerOffset(unsigned int type) +{ + static const unsigned int offsets[5] = { 0x5C, kPsmNoField, kPsmNoField, 0xAC, 0x58 }; + return offsets[type]; +} +#else +inline unsigned int psmRecordStride(unsigned int type) +{ + static const unsigned int strides[5] = { 168, 200, 176, 192, 216 }; + return strides[type]; +} +inline unsigned int psmRecordLinkOffset(unsigned int type) +{ + static const unsigned int offsets[5] = { 152, 192, 168, 176, 200 }; + return offsets[type]; +} +inline unsigned int psmRecordPointerOffset(unsigned int type) +{ + static const unsigned int offsets[5] = { 160, kPsmNoField, kPsmNoField, 184, 208 }; + return offsets[type]; +} +#endif + +inline void*& psmRecordLink(void* record, unsigned int type) +{ return psmRawField(record, psmRecordLinkOffset(type)); } +template inline T& psmRecordPointer(void* record, unsigned int type) +{ return psmRawField(record, psmRecordPointerOffset(type)); } + +// The renderers' {instance, last index, count} draw groups: 12 bytes on x86, 16 on x64. +struct PsmDrawGroup +{ + unsigned char* instance; // +0x00 + int last; // +0x04 index of the group's last table entry + unsigned int count; // +0x08 +}; +#if defined(_M_IX86) +static_assert(sizeof(PsmDrawGroup) == 12, "draw groups are 12-byte retail records"); +#endif + +#if defined(_M_IX86) + +inline unsigned int psmSpriteRendererOffset(unsigned int retail) { return retail; } +inline unsigned int psmMeshRendererOffset(unsigned int retail) { return retail; } +inline unsigned int psmTrailRendererOffset(unsigned int retail) { return retail; } +inline unsigned int psmNsaRendererOffset(unsigned int retail) { return retail; } +const unsigned int kPsmSpriteRendererSize = 0x5E18; +const unsigned int kPsmMeshRendererSize = 0x1D90; +const unsigned int kPsmTrailRendererSize = 0x0914; +const unsigned int kPsmNsaRendererSize = 0x05A0; + +#else + +// A retail offset inside a run of 12-byte draw groups, as a native offset relative to the run. +inline unsigned int psmDrawGroupOffset(unsigned int relative) +{ + const unsigned int field = relative % 12u; + return (relative / 12u) * sizeof(PsmDrawGroup) + (field < 4u ? field : field + 4u); +} + +// ParticleSystemRenderer (retail 0x5E18): the instance list +0x08, the sorted and additive tables +// +0x18/+0x1C, the 2x256 draw groups +0x20, the radix buckets +0x182C, the scratch pointers +0x1DC0 +// and +0x1DC8, the vertex buffer +0x1DCC, the effect +0x1DD0, 14 shader parameters +0x1DD4 and the +// vertex declaration +0x1E0C. +inline unsigned int psmSpriteRendererOffset(unsigned int retail) +{ + const unsigned int tail = 0x5E18; + if (retail - 0x20u < 0x1800u) return tail + 0x8C0 + psmDrawGroupOffset(retail - 0x20u); + if (retail - 0x182Cu < 0x400u) return tail + 0x0C0 + 2u * (retail - 0x182Cu); + if (retail - 0x1DD4u < 0x38u) return tail + 0x048 + 2u * (retail - 0x1DD4u); + switch (retail) + { + case 0x0008: return tail + 0x00; + case 0x0018: return tail + 0x18; + case 0x001C: return tail + 0x20; + case 0x1DC0: return tail + 0x28; + case 0x1DC8: return tail + 0x30; + case 0x1DCC: return tail + 0x38; + case 0x1DD0: return tail + 0x40; + case 0x1E0C: return tail + 0xB8; + } + return retail; +} +const unsigned int kPsmSpriteRendererSize = 0x5E18 + 0x28C0; + +// MeshParticlesRenderer (retail 0x1D90): the particle table +0x04, the 2x256 draw groups +0x08, the +// radix buckets +0x1814 and the retained mesh list +0x1D80. +inline unsigned int psmMeshRendererOffset(unsigned int retail) +{ + const unsigned int tail = 0x1D90; + if (retail - 0x08u < 0x1800u) return tail + 0x0020 + psmDrawGroupOffset(retail - 0x08u); + if (retail - 0x1814u < 0x400u) return tail + 0x2020 + 2u * (retail - 0x1814u); + switch (retail) + { + case 0x0004: return tail + 0x00; + case 0x1D80: return tail + 0x08; + } + return retail; +} +const unsigned int kPsmMeshRendererSize = 0x1D90 + 0x2820; + +// TrailRenderer (retail 0x914): the device-listener vptr at +0 widens over the index +0x04; the +// instance list +0x08, the particle table +0x18, the 64 draw groups +0x1C, the vertex buffer +0x8B4, +// the index buffers +0x8B8 and side vertex arrays +0x8C8 (indexed by side count 1..3), the effect +// +0x8D8, 13 shader parameters +0x8DC and the vertex declaration +0x910. +inline unsigned int psmTrailRendererOffset(unsigned int retail) +{ + const unsigned int tail = 0x918; + if (retail - 4u < 4u) return tail + 0x000 + (retail - 4u); + if (retail - 0x1Cu < 0x300u) return tail + 0x100 + psmDrawGroupOffset(retail - 0x1Cu); + if (retail - 0x8B8u < 0x10u) return tail + 0x030 + 2u * (retail - 0x8B8u); + if (retail - 0x8C8u < 0x10u) return tail + 0x050 + 2u * (retail - 0x8C8u); + if (retail - 0x8DCu < 0x34u) return tail + 0x078 + 2u * (retail - 0x8DCu); + switch (retail) + { + case 0x008: return tail + 0x08; + case 0x018: return tail + 0x20; + case 0x8B4: return tail + 0x28; + case 0x8D8: return tail + 0x70; + case 0x910: return tail + 0xE0; + } + return retail; +} +const unsigned int kPsmTrailRendererSize = 0x918 + 0x500; + +// NSAParticleSystemRenderer (retail 0x5A0): the instance list +0x0C, the table +0x1C, the radix +// buckets +0x20, the scratch pointers +0x55C and +0x564, the vertex buffer +0x568, the effect +0x56C, +// 11 shader parameters +0x570 and the vertex declaration +0x59C. +inline unsigned int psmNsaRendererOffset(unsigned int retail) +{ + const unsigned int tail = 0x5A0; + if (retail - 0x20u < 0x400u) return tail + 0x020 + 2u * (retail - 0x20u); + if (retail - 0x570u < 0x2Cu) return tail + 0x840 + 2u * (retail - 0x570u); + switch (retail) + { + case 0x00C: return tail + 0x000; + case 0x01C: return tail + 0x018; + case 0x55C: return tail + 0x820; + case 0x564: return tail + 0x828; + case 0x568: return tail + 0x830; + case 0x56C: return tail + 0x838; + case 0x59C: return tail + 0x898; + } + return retail; +} +const unsigned int kPsmNsaRendererSize = 0x5A0 + 0x8A0; + +#endif + +template inline T& psmSpriteField(unsigned char* renderer, unsigned int retail) +{ return psmRawField(renderer, psmSpriteRendererOffset(retail)); } +template inline T& psmMeshField(unsigned char* renderer, unsigned int retail) +{ return psmRawField(renderer, psmMeshRendererOffset(retail)); } +template inline T& psmTrailField(unsigned char* renderer, unsigned int retail) +{ return psmRawField(renderer, psmTrailRendererOffset(retail)); } +template inline T& psmNsaField(unsigned char* renderer, unsigned int retail) +{ return psmRawField(renderer, psmNsaRendererOffset(retail)); } + +// The draw-group arrays, by retail offset of their first group. +inline PsmDrawGroup* psmSpriteGroups(unsigned char* renderer, unsigned int retail) +{ return &psmSpriteField(renderer, retail); } +inline PsmDrawGroup* psmMeshGroups(unsigned char* renderer, unsigned int retail) +{ return &psmMeshField(renderer, retail); } +inline PsmDrawGroup* psmTrailGroups(unsigned char* renderer, unsigned int retail) +{ return &psmTrailField(renderer, retail); } + +} // namespace geom +} // namespace hfe +} // namespace dice + +#endif // BF2_GEOM_PARTICLESYSTEM_PARTICLERAWLAYOUT_H diff --git a/Code/BF2/Geom/ParticleSystem/ParticleRendererActive.inl b/Code/BF2/Geom/ParticleSystem/ParticleRendererActive.inl index 822bd2cc6..3fd99a0bd 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleRendererActive.inl +++ b/Code/BF2/Geom/ParticleSystem/ParticleRendererActive.inl @@ -5,6 +5,8 @@ // PE 1016F580 uses the current x87 rounding mode, not C++ truncation. static int psmParticleRound(float value) { +#if defined(_WIN32) +#if defined(_M_IX86) int rounded; __asm { fld value @@ -12,6 +14,18 @@ static int psmParticleRound(float value) fistp rounded } return rounded; +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). cvtss2si rounds in the + // current (nearest-even) mode and yields 0x80000000 for NaN or out of range, like fistp. + return _mm_cvtss_si32(_mm_set_ss(value)); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-port.md). + int rounded; + // [CHOSEN, not recovered] Preserve x87 current-mode FRNDINT and integer indefinite. + rounded = bf2x87::integer(bf2x87::wide(value), false); + return rounded; +#endif } // PE 1000ED40, also used by the clamped acos helper 100A6050. @@ -23,18 +37,24 @@ static float psmParticleClamp(float value, float low, float high) return value; } +// PE 0x100A6050 +static double psmParticleAcos(float value) +{ + return std::acos(psmParticleClamp(value, -1.0f, 1.0f)); +} + // Four stable byte-radix passes on the nonnegative squared-distance bits. // The bucket chains use the particle's first word and are emptied on each pass. static void psmSortParticles(unsigned char* renderer, unsigned char** table, unsigned int count) { - unsigned char** buckets = reinterpret_cast(renderer + 0x182C); + unsigned char** buckets = &psmSpriteField(renderer, 0x182C); for (unsigned int byte = 0; byte < 4; ++byte) { for (int i = static_cast(count) - 1; i >= 0; --i) { unsigned char* particle = table[i]; unsigned int key = particle[0x14 + byte]; - psmDrawField(particle, 0) = buckets[key]; + psmRecordLink(particle, 0) = buckets[key]; buckets[key] = particle; } unsigned int output = 0; @@ -45,7 +65,7 @@ static void psmSortParticles(unsigned char* renderer, unsigned char** table, uns while (particle) { table[output++] = particle; - particle = psmDrawField(particle, 0); + particle = static_cast(psmRecordLink(particle, 0)); } } } @@ -53,19 +73,32 @@ static void psmSortParticles(unsigned char* renderer, unsigned char** table, uns // rotation/flipbook state is advanced once per dirty particle, even when // multiple render views collect it. The instance argument is present but unused in retail. +// PE 0x101721F0 static void psmUpdateParticleDrawState(unsigned char* renderer, unsigned char* particle, unsigned char* descriptor, unsigned char*) { unsigned int& flags = psmDrawField(particle, 0x54); if (!(flags & 0x80)) return; flags &= ~0x80u; +#if defined(__APPLE__) + // [CHOSEN, not recovered] Keep x87 intermediates until the attested stores. + using bf2x87::wide; + const bf2x87::Real age = wide(psmDrawField(particle, 0x24)); + const float rate = bf2x87::store(age * age * wide(psmDescriptor0(descriptor, 0x100)) + + age * wide(psmDescriptor0(descriptor, 0x104)) + + age * age * age * wide(psmDescriptor0(descriptor, 0xFC)) + + wide(psmDescriptor0(descriptor, 0x108))); + const float dt = bf2x87::store(wide(psmParticleClamp(rate, 0.0f, 1.0f)) + * wide(psmSpriteField(renderer, 0x1C3C))); +#else const double age = psmDrawField(particle, 0x24); - const float rate = static_cast(age * age * psmDrawField(descriptor, 0x100) - + age * psmDrawField(descriptor, 0x104) - + age * age * age * psmDrawField(descriptor, 0xFC) - + psmDrawField(descriptor, 0x108)); + const float rate = static_cast(age * age * psmDescriptor0(descriptor, 0x100) + + age * psmDescriptor0(descriptor, 0x104) + + age * age * age * psmDescriptor0(descriptor, 0xFC) + + psmDescriptor0(descriptor, 0x108)); const float dt = psmParticleClamp(rate, 0.0f, 1.0f) - * psmDrawField(renderer, 0x1C3C); + * psmSpriteField(renderer, 0x1C3C); +#endif float& rotation = psmDrawField(particle, 0x80); if (!descriptor[0x21C]) rotation = static_cast(std::fmod(static_cast(dt) @@ -74,7 +107,45 @@ static void psmUpdateParticleDrawState(unsigned char* renderer, unsigned char* p { const float* position = reinterpret_cast(particle + 0x18); const float* velocity = reinterpret_cast(particle + 0x60); - const Mat4& matrix = psmDrawField(renderer, 0x1C98); + const Mat4& matrix = psmSpriteField(renderer, 0x1C98); +#if defined(__APPLE__) + // [CHOSEN, not recovered] The previous Y/Z, current reciprocal and + // projected Y remain live; previous X and its reciprocal are spilled. + const float previousX = bf2x87::store(wide(position[0]) - wide(velocity[0]) * wide(0.001f)); + const bf2x87::Real previousY = wide(position[1]) - wide(velocity[1]) * wide(0.001f); + const float deltaZ = bf2x87::store(wide(velocity[2]) * wide(0.001f)); + const bf2x87::Real previousZ = wide(position[2]) - wide(deltaZ); + float projected[2][3]; + for (int i = 0; i < 2; ++i) + for (int j = 0; j < 3; ++j) + projected[i][j] = bf2x87::store( + (i ? previousZ : wide(position[2])) * wide(matrix.m[8 + j]) + + (i ? previousY : wide(position[1])) * wide(matrix.m[4 + j]) + + wide(i ? previousX : position[0]) * wide(matrix.m[j]) + wide(matrix.m[12 + j])); + float currentX = 0.0f; + bf2x87::Real currentY = wide(0.0f), oldX = wide(0.0f), oldY = wide(0.0f); + if (std::fabs(projected[0][2]) > 0.00000023841858f) + { + const bf2x87::Real reciprocal = wide(1.0f) / wide(projected[0][2]); + currentX = bf2x87::store(wide(projected[0][0]) * reciprocal); + currentY = reciprocal * wide(projected[0][1]); + } + if (std::fabs(projected[1][2]) > 0.00000023841858f) + { + const float reciprocal = bf2x87::store(wide(1.0f) / wide(projected[1][2])); + oldX = wide(projected[1][0]) * wide(reciprocal); + oldY = wide(projected[1][1]) * wide(reciprocal); + } + const float x = bf2x87::store(wide(currentX) - oldX); + const bf2x87::Real y = currentY - oldY; + const bf2x87::Real length = bf2x87::squareRoot(wide(x) * wide(x) + y * y); + if (length > wide(0.00000023841858f)) + { + const double angle = psmParticleAcos(bf2x87::store(y / length)); + rotation = static_cast(x > 0 ? angle : 6.2831855f - angle); + } + else rotation = 0.0f; +#else float previous[3]; for (int i = 0; i < 3; ++i) previous[i] = position[i] - velocity[i] * 0.001f; float projected[2][3]; @@ -99,68 +170,91 @@ static void psmUpdateParticleDrawState(unsigned char* renderer, unsigned char* p const double length = std::sqrt(static_cast(x) * x + y * y); if (std::fabs(length) > 0.00000023841858) { - const double angle = std::acos(psmParticleClamp(static_cast(y / length), -1, 1)); + const double angle = psmParticleAcos(static_cast(y / length)); rotation = static_cast(x > 0 ? angle : 6.2831855f - angle); } else rotation = 0.0f; +#endif } const unsigned int trigIndex = static_cast(psmParticleRound(rotation * 651.89862f)) & 0xFFF; psmDrawField(particle, 0x88) = trigIndex; - psmDrawField(particle, 0x3C) = psmDrawField(renderer, 0x1E14 + trigIndex * 4); - if (descriptor[0xD4] && psmDrawField(descriptor, 0xE0)) + psmDrawField(particle, 0x3C) = psmSpriteField(renderer, 0x1E14 + trigIndex * 4); + if (descriptor[0xD4] && psmDescriptor0(descriptor, 0xE0)) { float& frame = psmDrawField(particle, 0x78); - const double nextFrame = static_cast(dt) * psmDrawField(descriptor, 0xD0) + frame; + const double nextFrame = static_cast(dt) * psmDescriptor0(descriptor, 0xD0) + frame; frame = static_cast(nextFrame); // FST stores the float but floor receives the still-live x87 result as a double. const int whole = psmParticleRound(static_cast(std::floor(nextFrame))); - psmDrawField(particle, 0x30) = frame - static_cast(whole); - const unsigned int frameCount = psmDrawField(descriptor, 0xE0); + psmDrawField(particle, 0x30) = static_cast(static_cast(frame) - whole); + const unsigned int frameCount = psmDescriptor0(descriptor, 0xE0); const unsigned int current = static_cast(whole) % frameCount; if (current != (flags & 0xF)) { flags ^= (current ^ flags) & 0xF; const unsigned int next = (current + 1) % frameCount; - const unsigned int columns = psmDrawField(descriptor, 0xE4); + const unsigned int columns = psmDescriptor0(descriptor, 0xE4); +#if defined(__APPLE__) + // [CHOSEN, not recovered] PE 10172588 spills only the second row product. + const unsigned int xs[2] = { current % columns, next % columns }; + const bf2x87::Real ys[2] = { + wide(current - xs[0]) * wide(psmDescriptor0(descriptor, 0xE8)), + wide(bf2x87::store(wide(next - xs[1]) * wide(psmDescriptor0(descriptor, 0xE8)))) }; +#else const unsigned int cells[2] = { current, next }; +#endif for (unsigned int i = 0; i < 2; ++i) { +#if defined(__APPLE__) + const bf2x87::Real u = (wide(psmDescriptor0(descriptor, 0x21E)) * wide(0.000030518509f) + + wide(xs[i]) * wide(psmDescriptor0(descriptor, 0x13C))) * wide(32767.0f); + const bf2x87::Real v = (wide(psmDescriptor0(descriptor, 0x220)) * wide(0.000030518509f) + + ys[i] * wide(psmDescriptor0(descriptor, 0x140))) * wide(32767.0f); + psmDrawField(particle, 0x40 + i * 4) = bf2x87::lowShort(bf2x87::toInt64Truncate(u)); + psmDrawField(particle, 0x42 + i * 4) = bf2x87::lowShort(bf2x87::toInt64Truncate(v)); +#else const unsigned int x = cells[i] % columns; - const double y = static_cast(cells[i] - x) * psmDrawField(descriptor, 0xE8); - psmDrawField(particle, 0x40 + i * 4) = static_cast(static_cast( - (static_cast(psmDrawField(descriptor, 0x21E)) * 0.000030518509f - + static_cast(x) * psmDrawField(descriptor, 0x13C)) * 32767.0f)); - psmDrawField(particle, 0x42 + i * 4) = static_cast(static_cast( - (static_cast(psmDrawField(descriptor, 0x220)) * 0.000030518509f - + y * psmDrawField(descriptor, 0x140)) * 32767.0f)); + const double y = i ? static_cast(static_cast(cells[i] - x) * psmDescriptor0(descriptor, 0xE8)) + : static_cast(cells[i] - x) * psmDescriptor0(descriptor, 0xE8); + psmDrawField(particle, 0x40 + i * 4) = static_cast(static_cast<__int64>( + (static_cast(psmDescriptor0(descriptor, 0x21E)) * 0.000030518509f + + static_cast(x) * psmDescriptor0(descriptor, 0x13C)) * 32767.0f)); + psmDrawField(particle, 0x42 + i * 4) = static_cast(static_cast<__int64>( + (static_cast(psmDescriptor0(descriptor, 0x220)) * 0.000030518509f + + y * psmDescriptor0(descriptor, 0x140)) * 32767.0f)); +#endif } } } } // Both leading view calls and the view call per accepted particle are retained. +// PE 0x10171A00 (the sorted renderer's collect callback, descriptor +0x2A0). static void psmCollectSortedParticles(unsigned char* renderer, dx9rend::IRenderView* view, unsigned char* instance, unsigned char* descriptor) { view->getViewMatrixPtr(); view->getViewMatrixPtr(); const float nearPlane = view->getNearPlane(); - const unsigned int count = psmDrawField(instance, 0x28); - if (psmDrawField(descriptor, 8) == -1) - psmDrawField(descriptor, 8) = psmDrawField(renderer, 0x1D70)++; + const unsigned int count = psmInstanceA(instance, 0x28); + if (psmDescriptor0(descriptor, 8) == -1) + psmDescriptor0(descriptor, 8) = psmSpriteField(renderer, 0x1D70)++; ParticleSystemManager* manager = reinterpret_cast(g_ParticleSystemManager); - const unsigned int lod = psmDrawField(descriptor, 0x64); + const unsigned int lod = psmDescriptor0(descriptor, 0x64); const float farDistance = manager->m_farDistances[lod]; const float inverseFarRange = manager->m_inverseFarRanges[lod]; for (unsigned int i = 0; i < count; ++i) { - unsigned char* p = psmDrawField(instance, 0x24)[i]; - psmDrawField(p, 4) = psmDrawField(descriptor, 4); - const float depth = static_cast(static_cast(psmDrawField(p, 0x1C)) * psmDrawField(renderer, 0x1C44) - + static_cast(psmDrawField(p, 0x20)) * psmDrawField(renderer, 0x1C48) - + static_cast(psmDrawField(p, 0x18)) * psmDrawField(renderer, 0x1C40) - + psmDrawField(renderer, 0x1C4C)); - if (depth < nearPlane) continue; + unsigned char* p = psmInstanceA(instance, 0x24)[i]; + psmDrawField(p, 4) = psmDescriptor0(descriptor, 4); + // `fst` keeps the float copy, but the near-plane test compares the unrounded sum + // (0x10171ABC..0x10171AC7); the far test and fromNear reload the float. + const double depthSum = static_cast(psmDrawField(p, 0x1C)) * psmSpriteField(renderer, 0x1C44) + + static_cast(psmDrawField(p, 0x20)) * psmSpriteField(renderer, 0x1C48) + + static_cast(psmDrawField(p, 0x18)) * psmSpriteField(renderer, 0x1C40) + + psmSpriteField(renderer, 0x1C4C); + const float depth = static_cast(depthSum); + if (depthSum < nearPlane) continue; float& alpha = psmDrawField(p, 0x2C); if (!(depth > farDistance)) alpha = psmDrawField(p, 0x58); else @@ -169,18 +263,19 @@ static void psmCollectSortedParticles(unsigned char* renderer, dx9rend::IRenderV if (fade > 1) fade = 1; alpha = static_cast((1 - fade) * (1 - fade) * psmDrawField(p, 0x58)); } - if (alpha < psmDrawField(descriptor, 0x9C)) continue; + if (alpha < psmDescriptor0(descriptor, 0x9C)) continue; const float fromNear = depth - nearPlane; - if (descriptor[0x29C] && fromNear < psmDrawField(descriptor, 0x288) - && psmDrawField(p, 0x24) > psmDrawField(descriptor, 0x290)) + if (descriptor[0x29C] && fromNear < psmDescriptor0(descriptor, 0x288) + && psmDrawField(p, 0x24) > psmDescriptor0(descriptor, 0x290)) { - double ageFade = (static_cast(psmDrawField(p, 0x24)) - psmDrawField(descriptor, 0x290)) - * psmDrawField(descriptor, 0x294); + double ageFade = (static_cast(psmDrawField(p, 0x24)) - psmDescriptor0(descriptor, 0x290)) + * psmDescriptor0(descriptor, 0x294); ageFade = ageFade > 1 ? 0 : 1 - ageFade; - const double distanceFade = (static_cast(psmDrawField(descriptor, 0x288)) - fromNear) - * psmDrawField(descriptor, 0x28C); - alpha = static_cast(distanceFade > 1 ? ageFade : distanceFade * ageFade + 1 - distanceFade); - if (alpha < psmDrawField(descriptor, 0x298)) continue; + const double distanceFade = (static_cast(psmDescriptor0(descriptor, 0x288)) - fromNear) + * psmDescriptor0(descriptor, 0x28C); + // d * a + (1 - d): the shipped association (0x10171BB1..0x10171BBD). + alpha = static_cast(distanceFade > 1 ? ageFade : distanceFade * ageFade + (1 - distanceFade)); + if (alpha < psmDescriptor0(descriptor, 0x298)) continue; } const Mat4* matrix = view->getViewMatrixPtr(); const float x = matrix->m[12] - psmDrawField(p, 0x18); @@ -188,9 +283,9 @@ static void psmCollectSortedParticles(unsigned char* renderer, dx9rend::IRenderV const double z = static_cast(matrix->m[14]) - psmDrawField(p, 0x20); psmDrawField(p, 0x14) = static_cast(z * z + y * y + static_cast(x) * x); psmUpdateParticleDrawState(renderer, p, descriptor, instance); - psmDrawField(renderer, 0x18)[psmDrawField(renderer, 0x1C38)++] = p; + psmSpriteField(renderer, 0x18)[psmSpriteField(renderer, 0x1C38)++] = p; } - vc71::vectorRef(renderer + 8).push_back(instance); + particleRendererList(renderer, psmSpriteRendererOffset(8)).push_back(instance); } // PE 10170CE0 retains the pre-fade alpha test, omits the sorted-path near fade and @@ -201,26 +296,26 @@ static void psmCollectAdditiveParticles(unsigned char* renderer, dx9rend::IRende const float* eye = view->getViewMatrixPtr()->m + 12; const float nearPlane = view->getNearPlane(); view->getViewMatrixPtr(); - const unsigned int count = psmDrawField(instance, 0x28); - if (psmDrawField(descriptor, 8) == -1) - psmDrawField(descriptor, 8) = psmDrawField(renderer, 0x1D74)++; + const unsigned int count = psmInstanceA(instance, 0x28); + if (psmDescriptor0(descriptor, 8) == -1) + psmDescriptor0(descriptor, 8) = psmSpriteField(renderer, 0x1D74)++; view->getViewport(); ParticleSystemManager* manager = reinterpret_cast(g_ParticleSystemManager); - const unsigned int lod = psmDrawField(descriptor, 0x64); + const unsigned int lod = psmDescriptor0(descriptor, 0x64); const float farDistance = manager->m_farDistances[lod]; const float inverseFarRange = manager->m_inverseFarRanges[lod]; unsigned int accepted = 0; - unsigned int& total = psmDrawField(renderer, 0x1820); - unsigned char** table = psmDrawField(renderer, 0x1C); + unsigned int& total = psmSpriteField(renderer, 0x1820); + unsigned char** table = psmSpriteField(renderer, 0x1C); for (unsigned int i = 0; i < count; ++i) { - unsigned char* p = psmDrawField(instance, 0x24)[i]; + unsigned char* p = psmInstanceA(instance, 0x24)[i]; float& alpha = psmDrawField(p, 0x2C); - if (alpha < psmDrawField(descriptor, 0x9C)) continue; - const float depth = static_cast(static_cast(psmDrawField(p, 0x20)) * psmDrawField(renderer, 0x1C48) - + static_cast(psmDrawField(p, 0x1C)) * psmDrawField(renderer, 0x1C44) - + static_cast(psmDrawField(p, 0x18)) * psmDrawField(renderer, 0x1C40) - + psmDrawField(renderer, 0x1C4C)); + if (alpha < psmDescriptor0(descriptor, 0x9C)) continue; + const float depth = static_cast(static_cast(psmDrawField(p, 0x20)) * psmSpriteField(renderer, 0x1C48) + + static_cast(psmDrawField(p, 0x1C)) * psmSpriteField(renderer, 0x1C44) + + static_cast(psmDrawField(p, 0x18)) * psmSpriteField(renderer, 0x1C40) + + psmSpriteField(renderer, 0x1C4C)); if (depth < nearPlane) continue; if (!(depth > farDistance)) alpha = psmDrawField(p, 0x58); else @@ -233,18 +328,18 @@ static void psmCollectAdditiveParticles(unsigned char* renderer, dx9rend::IRende const double y = static_cast(eye[1]) - psmDrawField(p, 0x1C); const double z = static_cast(eye[2]) - psmDrawField(p, 0x20); psmDrawField(p, 0x14) = static_cast(z * z + static_cast(x) * x + y * y); - psmDrawField(p, 4) = psmDrawField(descriptor, 4); + psmDrawField(p, 4) = psmDescriptor0(descriptor, 4); psmUpdateParticleDrawState(renderer, p, descriptor, instance); table[total + accepted++] = p; } if (!accepted) return; - const bool ordered = psmDrawField(descriptor, 0x7C) != 0; - unsigned int& groupCount = psmDrawField(renderer, ordered ? 0x1828 : 0x1824); + const bool ordered = psmDescriptor0(descriptor, 0x7C) != 0; + unsigned int& groupCount = psmSpriteField(renderer, ordered ? 0x1828 : 0x1824); if (groupCount >= 256) return; - unsigned char* group = renderer + (ordered ? 0xC20 : 0x20) + groupCount * 12; - psmDrawField(group, 0) = instance; - psmDrawField(group, 4) = total + accepted - 1; - psmDrawField(group, 8) = accepted; + PsmDrawGroup* const group = psmSpriteGroups(renderer, ordered ? 0xC20 : 0x20) + groupCount; + group->instance = instance; + group->last = static_cast(total + accepted - 1); + group->count = accepted; ++groupCount; psmSortParticles(renderer, table + total, accepted); total += accepted; diff --git a/Code/BF2/Geom/ParticleSystem/ParticleRendererCallbacks.h b/Code/BF2/Geom/ParticleSystem/ParticleRendererCallbacks.h index eafc49afe..8887edf05 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleRendererCallbacks.h +++ b/Code/BF2/Geom/ParticleSystem/ParticleRendererCallbacks.h @@ -2,13 +2,45 @@ // PE 10171A00/10170CE0 are thiscall members stored at sprite descriptor +0x2A0. // The existing plugin's explicit-this fastcall bridge preserves ECX and stack arguments. #pragma once +#include "../../../RendDX9Abi/ThunkAbi.h" +#include "ParticleRawLayout.h" +#include namespace dice { namespace hfe { +class IBase; namespace dx9rend { class IRenderView; } namespace geom { class IParticleSystemInstance; class IParticleSystemTemplate; -void __fastcall particleRendererCollectSorted(void*, void*, dx9rend::IRenderView*, +class MeshParticleMesh; +void RD9_THUNK particleRendererCollectSorted(void* RD9_THUNK_EDX, dx9rend::IRenderView*, IParticleSystemInstance*, IParticleSystemTemplate*); -void __fastcall particleRendererCollectAdditive(void*, void*, dx9rend::IRenderView*, +void RD9_THUNK particleRendererCollectAdditive(void* RD9_THUNK_EDX, dx9rend::IRenderView*, IParticleSystemInstance*, IParticleSystemTemplate*); + +// The four renderers embedded in the manager keep their recovered byte layout (ParticleRawLayout.h). +// Each pointer list one of them owns is a std::vector constructed in place in its original 16-byte +// span (the particle and trail renderers' +0x08, the NSA renderer's +0x0C, the mesh renderer's +// +0x1D80; x64 moves them to 24-byte tail slots); this names the list at native `offset`. The manager +// constructs these lists with its renderers. +template +inline std::vector& particleRendererList(unsigned char* renderer, unsigned int offset) +{ + static_assert(sizeof(std::vector) <= (sizeof(void*) == 4 ? 16 : 24), + "a renderer list must fit its span"); + return *reinterpret_cast*>(renderer + offset); +} + +// The retained mesh list of the MeshParticles renderer (retail +0x1D80). +inline std::vector& meshParticlesRendererMeshes(unsigned char* renderer) +{ + return particleRendererList(renderer, psmMeshRendererOffset(0x1D80)); +} + +// The MeshParticles renderer embedded in the published manager. MeshParticleMesh::queueDraw +// appends to its retained mesh list at +0x1D80. No null guard on `manager`. +unsigned char* particleSystemManagerMeshParticlesRenderer(IBase* manager); + +// The manager's force-sorted byte (retail +0x8BA8), read by the sprite descriptor's slot 114. +// No null guard on `manager`. +unsigned char particleSystemManagerForceSortedParticles(IBase* manager); } } } diff --git a/Code/BF2/Geom/ParticleSystem/ParticleRendererConstruction.inl b/Code/BF2/Geom/ParticleSystem/ParticleRendererConstruction.inl index 9ea1f1f99..2f08694d5 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleRendererConstruction.inl +++ b/Code/BF2/Geom/ParticleSystem/ParticleRendererConstruction.inl @@ -1,5 +1,6 @@ // Renderer construction helpers included after psmFillTrailIndices in the manager's namespace. -// Fixed-layout storage is Win32-owned in both host flavors; keep its compatibility vectors. +// The renderers keep their recovered byte layout; their pointer lists are std::vectors constructed +// in place (particleRendererList). template static T& psmCtorField(unsigned char* renderer, unsigned int offset) @@ -13,6 +14,32 @@ static void psmCtorZeroWords(unsigned char* renderer, unsigned int offset, unsig psmCtorField(renderer, offset + 4u * i) = 0; } +// A renderer's retail -> native offset map (ParticleRawLayout.h). +typedef unsigned int (*PsmRendererLayout)(unsigned int retail); + +template +static T& psmCtorAt(unsigned char* renderer, PsmRendererLayout layout, unsigned int retail) +{ + return psmRawField(renderer, layout(retail)); +} + +// Zeroes `count` retail words starting at retail `offset`, each at its native place. +static void psmCtorZeroRetailWords(unsigned char* renderer, PsmRendererLayout layout, + unsigned int offset, unsigned int count) +{ + for (unsigned int i = 0; i < count; ++i) + psmCtorAt(renderer, layout, offset + 4u * i) = 0; +} + +// [CHOSEN, not recovered] x64: zero the relocated fields (ParticleRawLayout.h) before the retail +// stores, so a pointer slot whose retail word the constructor zeroes is zero in full. The manager's +// storage is value-initialised already; x86 has no tail. +static void psmCtorClearTail(unsigned char* renderer, unsigned int retailSize, unsigned int nativeSize) +{ + for (unsigned int i = retailSize; i < nativeSize; ++i) + renderer[i] = 0; +} + static void psmCtorIdentity(unsigned char* matrix) { psmCtorZeroWords(matrix, 0, 16); @@ -21,6 +48,7 @@ static void psmCtorIdentity(unsigned char* matrix) } // three identity matrices followed by one zero Vec4. +// PE 0x10171E40 static void psmCtorParticleMatrices(unsigned char* matrices) { for (unsigned int i = 0; i < 3; ++i) @@ -29,35 +57,28 @@ static void psmCtorParticleMatrices(unsigned char* matrices) } // four identity matrices. +// PE 0x10173E40 static void psmCtorMeshMatrices(unsigned char* matrices) { for (unsigned int i = 0; i < 4; ++i) psmCtorIdentity(matrices + 64u * i); } -static void psmCtorPointerVector(unsigned char* storage) +// Constructs an empty pointer list in its 16-byte span. +template +static void psmCtorPointerVector(unsigned char* renderer, unsigned int offset) { - // allocator<> is empty. As in the PE, its padding word is not written. - vc71::vector_layout& vector = *reinterpret_cast(storage); - vector.first = 0; - vector.last = 0; - vector.end = 0; + ::new (static_cast(renderer + offset)) std::vector(); } // The source operations are resize(30, nullptr), then resize(0), retaining capacity 30. -// 10172890 / 1016F4F0 / 10174410, with the first-growth branch of 10172660. This private -// construction adapter handles that initial reserve only, rather than pretending to implement -// a general-purpose STL container. The 120-byte allocation is unconditionally populated in PE. -static void psmCtorPrimePointerVector(unsigned char* storage) +// 10172890 / 1016F4F0 / 10174410, with the first-growth branch of 10172660. +template +static void psmCtorPrimePointerVector(unsigned char* renderer, unsigned int offset) { - vc71::vector_layout& vector = *reinterpret_cast(storage); - void** const entries = static_cast(::renddx9abi::engineAlloc(30u * sizeof(void*))); - for (unsigned int i = 0; i < 30; ++i) - entries[i] = 0; - vector.end = reinterpret_cast(entries + 30); - vector.last = reinterpret_cast(entries + 30); - vector.first = reinterpret_cast(entries); - vector.last = vector.first; + std::vector& list = particleRendererList(renderer, offset); + list.resize(30, 0); + list.resize(0); } struct PsmCtorParameter @@ -67,29 +88,29 @@ struct PsmCtorParameter }; template -static void psmCtorParameters(unsigned char* renderer, unsigned int effectOffset, - const PsmCtorParameter (¶meters)[N]) +static void psmCtorParameters(unsigned char* renderer, PsmRendererLayout layout, + unsigned int effectOffset, const PsmCtorParameter (¶meters)[N]) { for (unsigned int i = 0; i < N; ++i) { // Each temporary string and repeated effect read follows the corresponding PE call. - const vc71::string name(parameters[i].name); - psmCtorField(renderer, parameters[i].offset) = + const std::string name(parameters[i].name); + psmCtorAt(renderer, layout, parameters[i].offset) = dx9rend::effectGetShaderParameterTyped( - psmCtorField(renderer, effectOffset), name); + psmCtorAt(renderer, layout, effectOffset), name); } } // Each of the ten 0x70-byte records is value-constructed. The second allocation is left // uninitialized in both constructors. Both are operator-new[]'s Memory.dll allocation seam. -static void psmCtorParticleScratch(unsigned char* renderer, unsigned int recordsOffset, - unsigned int scratchOffset) +static void psmCtorParticleScratch(unsigned char* renderer, PsmRendererLayout layout, + unsigned int recordsOffset, unsigned int scratchOffset) { void* records = ::renddx9abi::engineAlloc(0x460); if (records) psmCtorZeroWords(static_cast(records), 0, 0x460 / 4); - psmCtorField(renderer, recordsOffset) = records; - psmCtorField(renderer, scratchOffset) = ::renddx9abi::engineAlloc(0x800); + psmCtorAt(renderer, layout, recordsOffset) = records; + psmCtorAt(renderer, layout, scratchOffset) = ::renddx9abi::engineAlloc(0x800); } // PE 10171740..10171779 uses x87 fsin/fcos and __ftol2's truncation, keeping the angle on @@ -97,13 +118,14 @@ static void psmCtorParticleScratch(unsigned char* renderer, unsigned int records // modern compiler's double/SSE temporary at the signed-short quantization boundary. static void psmCtorTrigPair(unsigned int index, short& sine, short& cosine) { +#if defined(_WIN32) const float step = 0.0015339808305725455284f; // 1021EF18, float(2*pi/4096) const float amplitude = 32767.0f; - unsigned short originalControl; - unsigned short truncateControl; short sineValue; short cosineValue; #if defined(_M_IX86) + unsigned short originalControl; + unsigned short truncateControl; __asm { fild index fmul step @@ -124,44 +146,63 @@ static void psmCtorTrigPair(unsigned int index, short& sine, short& cosine) fldcw originalControl } #else -#error Particle renderer reconstruction requires the supported MSVC x86 target. + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). The angle stays a double + // between both calls; the C++ conversions truncate toward zero like the chop-mode fistp. + const double angle = static_cast(static_cast(index)) * step; + sineValue = static_cast(static_cast(std::sin(angle) * amplitude)); + cosineValue = static_cast(static_cast(std::cos(angle) * amplitude)); #endif sine = sineValue; cosine = cosineValue; +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-port.md). + const float step = 0.0015339808305725455284f; // 1021EF18, float(2*pi/4096) + const float amplitude = 32767.0f; + unsigned short originalControl; + unsigned short truncateControl; + short sineValue; + short cosineValue; + // [CHOSEN, not recovered] Preserve x87 signed FILD, live angle and truncating short stores. + bf2x87::tableRotation(index, sineValue, cosineValue); + sine = sineValue; + cosine = cosineValue; +#endif } +// PE 0x10171110 static void psmConstructParticleRenderer(unsigned char* renderer) { + psmCtorClearTail(renderer, 0x5E18, kPsmSpriteRendererSize); renderer[0] = 0; - psmCtorField(renderer, 4) = -1; - psmCtorPointerVector(renderer + 8); - psmCtorField(renderer, 0x18) = 0; - psmCtorZeroWords(renderer, 0x20, 256u * 3u); - psmCtorZeroWords(renderer, 0xC20, 256u * 3u); - psmCtorField(renderer, 0x1824) = 0; - psmCtorField(renderer, 0x1828) = 0; - psmCtorField(renderer, 0x1C2C) = 0; - psmCtorField(renderer, 0x1C30) = 0; + psmSpriteField(renderer, 4) = -1; + psmCtorPointerVector(renderer, psmSpriteRendererOffset(8)); + psmSpriteField(renderer, 0x18) = 0; + psmCtorZeroRetailWords(renderer, psmSpriteRendererOffset, 0x20, 256u * 3u); + psmCtorZeroRetailWords(renderer, psmSpriteRendererOffset, 0xC20, 256u * 3u); + psmSpriteField(renderer, 0x1824) = 0; + psmSpriteField(renderer, 0x1828) = 0; + psmSpriteField(renderer, 0x1C2C) = 0; + psmSpriteField(renderer, 0x1C30) = 0; renderer[0x1C34] = 0; - psmCtorZeroWords(renderer, 0x1C38, 6); + psmCtorZeroRetailWords(renderer, psmSpriteRendererOffset, 0x1C38, 6); psmCtorParticleMatrices(renderer + 0x1C58); psmCtorIdentity(renderer + 0x1D28); renderer[0x1D6C] = 0; - psmCtorField(renderer, 0x1D70) = 0; + psmSpriteField(renderer, 0x1D70) = 0; renderer[0x1D78] = 0; renderer[0x1D79] = 0; - psmCtorField(renderer, 0x1D80) = 0; - psmCtorField(renderer, 0x1D84) = 0; + psmSpriteField(renderer, 0x1D80) = 0; + psmSpriteField(renderer, 0x1D84) = 0; for (unsigned int i = 0; i < 4; ++i) - psmCtorField(renderer, 0x1D8C + 4u * i) = 0.5f; + psmSpriteField(renderer, 0x1D8C + 4u * i) = 0.5f; renderer[0x1D9C] = 1; renderer[0x1D9D] = 0; renderer[0x1D9E] = 0; - psmCtorField(renderer, 0x1DC0) = 0; - psmCtorField(renderer, 0x1DC8) = 0; - psmCtorField(renderer, 0x1DCC) = 0; - psmCtorPrimePointerVector(renderer + 8); - psmCtorZeroWords(renderer, 0x182C, 256); + psmSpriteField(renderer, 0x1DC0) = 0; + psmSpriteField(renderer, 0x1DC8) = 0; + psmSpriteField(renderer, 0x1DCC) = 0; + psmCtorPrimePointerVector(renderer, psmSpriteRendererOffset(8)); + psmCtorZeroRetailWords(renderer, psmSpriteRendererOffset, 0x182C, 256); const D3DVERTEXELEMENT9 declaration[] = { {0, 0x00, 2, 0, 0, 0}, {0, 0x0C, 1, 0, 5, 0}, @@ -169,20 +210,15 @@ static void psmConstructParticleRenderer(unsigned char* renderer) {0, 0x28, 1, 0, 5, 3}, {0, 0x30, 6, 0, 5, 4}, {0, 0x34, 7, 0, 5, 5}, {0, 0x3C, 6, 0, 5, 6}, D3DDECL_END() }; - psmCtorField(renderer, 0x1E0C) = dx9rend::vertexDeclarationCreate(declaration); - if (!psmCtorField(renderer, 0x1E0C)) + psmSpriteField(renderer, 0x1E0C) = dx9rend::vertexDeclarationCreate(declaration); + if (!psmSpriteField(renderer, 0x1E0C)) { - // PE 101713A2..10171407 emits Debug type 6. Its destructor 10074690 traps after - // emission, but the renderer's per-type/module suppression configuration can skip it. - // [TEMP] [CHOSEN, not recovered] The renderer Debug dispatcher is not bridged here. - // [RETIRE-WHEN: particle-constructor-debug-dispatch] Preserve an explicit stop at that - // error-only dependency rather than replacing the retail diagnostic with log-and-return. - RD9_FRONTIER_AT("dice::hfe::geom::ParticleSystemRenderer::ParticleSystemRenderer " - "(Debug type 6, ParticleSystemRenderer.cpp:113: Failed to create declspec)", - renderer, 0); - std::abort(); + // PE 0x101713D6. The shader initialization below still runs when this is suppressed. + ::renddx9abi::Debug(DebugTypeError, + "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\ParticleSystem\\ParticleSystemRenderer.cpp", + 113, "") << "Failed to create declspec"; } - psmCtorField(renderer, 0x1DD0) = + psmSpriteField(renderer, 0x1DD0) = dx9rend::shaderManagerGetEffect(dx9rend::g_shaderManager, "mods/xpack/shaders/Particles"); const PsmCtorParameter parameters[] = { {0x1DD4, "ViewMat"}, {0x1DD8, "ProjMat"}, {0x1DDC, "HemiMapInfo"}, @@ -191,39 +227,41 @@ static void psmConstructParticleRenderer(unsigned char* renderer) {0x1E04, "WaterFogRange"}, {0x1E00, "WaterFogColor"}, {0x1E08, "CameraToWater"}, {0x1DF8, "EffectSunColor"}, {0x1DFC, "EffectShadowColor"} }; - psmCtorParameters(renderer, 0x1DD0, parameters); - psmCtorParticleScratch(renderer, 0x1DC8, 0x1DC0); + psmCtorParameters(renderer, psmSpriteRendererOffset, 0x1DD0, parameters); + psmCtorParticleScratch(renderer, psmSpriteRendererOffset, 0x1DC8, 0x1DC0); for (unsigned int i = 0; i < 4096; ++i) - psmCtorTrigPair(i, psmCtorField(renderer, 0x1E14 + i * 4u), - psmCtorField(renderer, 0x1E16 + i * 4u)); + psmCtorTrigPair(i, psmSpriteField(renderer, 0x1E14 + i * 4u), + psmSpriteField(renderer, 0x1E16 + i * 4u)); } +// PE 0x101750E0 static void psmConstructMeshParticleRenderer(unsigned char* renderer) { - psmCtorField(renderer, 0) = -1; - psmCtorField(renderer, 4) = 0; - psmCtorZeroWords(renderer, 8, 256u * 3u); - psmCtorZeroWords(renderer, 0xC08, 256u * 3u); - psmCtorField(renderer, 0x180C) = 0; - psmCtorField(renderer, 0x1810) = 0; - psmCtorField(renderer, 0x1C14) = 0; + psmCtorClearTail(renderer, 0x1D90, kPsmMeshRendererSize); + psmMeshField(renderer, 0) = -1; + psmMeshField(renderer, 4) = 0; + psmCtorZeroRetailWords(renderer, psmMeshRendererOffset, 8, 256u * 3u); + psmCtorZeroRetailWords(renderer, psmMeshRendererOffset, 0xC08, 256u * 3u); + psmMeshField(renderer, 0x180C) = 0; + psmMeshField(renderer, 0x1810) = 0; + psmMeshField(renderer, 0x1C14) = 0; renderer[0x1C18] = 0; - psmCtorZeroWords(renderer, 0x1C1C, 6); + psmCtorZeroRetailWords(renderer, psmMeshRendererOffset, 0x1C1C, 6); psmCtorMeshMatrices(renderer + 0x1C3C); renderer[0x1D3C] = 0; - psmCtorField(renderer, 0x1D40) = 0; + psmMeshField(renderer, 0x1D40) = 0; renderer[0x1D48] = 0; renderer[0x1D49] = 0; - psmCtorField(renderer, 0x1D50) = 0; - psmCtorField(renderer, 0x1D54) = 0; + psmMeshField(renderer, 0x1D50) = 0; + psmMeshField(renderer, 0x1D54) = 0; for (unsigned int i = 0; i < 4; ++i) - psmCtorField(renderer, 0x1D5C + 4u * i) = 0.5f; + psmMeshField(renderer, 0x1D5C + 4u * i) = 0.5f; renderer[0x1D6E] = 0; renderer[0x1D6F] = 0; renderer[0x1D6C] = 1; renderer[0x1D6D] = 1; - psmCtorZeroWords(renderer, 0x1D84, 3); - psmCtorZeroWords(renderer, 0x1814, 256); + psmCtorPointerVector(renderer, psmMeshRendererOffset(0x1D80)); // the retained mesh list + psmCtorZeroRetailWords(renderer, psmMeshRendererOffset, 0x1814, 256); } // The complete three-slot table at 1021F058. There is no virtual destructor. Lost and @@ -232,6 +270,7 @@ class PsmTrailDeviceListener : public dx9rend::DeviceLostResetListener { public: void onDeviceLost() override {} + // PE 0x10172B00 void onDeviceReset() override { for (unsigned int sides = 1; sides <= 3; ++sides) @@ -239,48 +278,50 @@ public: } void onDeviceDestroy() override {} }; -static_assert(sizeof(PsmTrailDeviceListener) == 4, "TrailRenderer's listener is one vptr"); +static_assert(sizeof(PsmTrailDeviceListener) == sizeof(void*), "TrailRenderer's listener is one vptr"); +// PE 0x10173530 static void psmConstructTrailRenderer(unsigned char* renderer) { + psmCtorClearTail(renderer, 0x914, kPsmTrailRendererSize); PsmTrailDeviceListener* const listener = new (renderer) PsmTrailDeviceListener; - psmCtorField(renderer, 4) = -1; - psmCtorPointerVector(renderer + 8); - psmCtorField(renderer, 0x18) = 0; - psmCtorZeroWords(renderer, 0x1C, 64u * 3u); - psmCtorField(renderer, 0x320) = 0; - psmCtorField(renderer, 0x724) = 0; + psmTrailField(renderer, 4) = -1; + psmCtorPointerVector(renderer, psmTrailRendererOffset(8)); + psmTrailField(renderer, 0x18) = 0; + psmCtorZeroRetailWords(renderer, psmTrailRendererOffset, 0x1C, 64u * 3u); + psmTrailField(renderer, 0x320) = 0; + psmTrailField(renderer, 0x724) = 0; renderer[0x728] = 0; - psmCtorZeroWords(renderer, 0x72C, 6); + psmCtorZeroRetailWords(renderer, psmTrailRendererOffset, 0x72C, 6); psmCtorMeshMatrices(renderer + 0x74C); - psmCtorField(renderer, 0x868) = 300.0f; + psmTrailField(renderer, 0x868) = 300.0f; renderer[0x84C] = 0; - psmCtorField(renderer, 0x850) = 0; + psmTrailField(renderer, 0x850) = 0; renderer[0x858] = 0; - psmCtorField(renderer, 0x860) = 0; - psmCtorField(renderer, 0x864) = 0; + psmTrailField(renderer, 0x860) = 0; + psmTrailField(renderer, 0x864) = 0; for (unsigned int i = 0; i < 4; ++i) - psmCtorField(renderer, 0x874 + 4u * i) = 0.5f; + psmTrailField(renderer, 0x874 + 4u * i) = 0.5f; renderer[0x884] = 1; - psmCtorField(renderer, 0x86C) = - psmCtorField(renderer, 0x868) * psmCtorField(renderer, 0x868); + psmTrailField(renderer, 0x86C) = + psmTrailField(renderer, 0x868) * psmTrailField(renderer, 0x868); renderer[0x885] = 1; renderer[0x886] = 0; renderer[0x887] = 0; - psmCtorField(renderer, 0x8AC) = 0; - psmCtorField(renderer, 0x8B4) = 0; - psmCtorZeroWords(renderer, 0x8D8, 15); - psmCtorPrimePointerVector(renderer + 8); - psmCtorZeroWords(renderer, 0x324, 256); - psmCtorZeroWords(renderer, 0x8B8, 4); - psmCtorField(renderer, 0x8D8) = + psmTrailField(renderer, 0x8AC) = 0; + psmTrailField(renderer, 0x8B4) = 0; + psmCtorZeroRetailWords(renderer, psmTrailRendererOffset, 0x8D8, 15); + psmCtorPrimePointerVector(renderer, psmTrailRendererOffset(8)); + psmCtorZeroRetailWords(renderer, psmTrailRendererOffset, 0x324, 256); + psmCtorZeroRetailWords(renderer, psmTrailRendererOffset, 0x8B8, 4); + psmTrailField(renderer, 0x8D8) = dx9rend::shaderManagerGetEffect(dx9rend::g_shaderManager, "mods/xpack/shaders/Trail"); const D3DVERTEXELEMENT9 declaration[] = { {0, 0x00, 2, 0, 0, 0}, {0, 0x0C, 2, 0, 3, 0}, {0, 0x18, 2, 0, 3, 1}, {0, 0x24, 3, 0, 5, 0}, {0, 0x34, 7, 0, 5, 1}, {0, 0x3C, 1, 0, 5, 2}, D3DDECL_END() }; - psmCtorField(renderer, 0x910) = dx9rend::vertexDeclarationCreate(declaration); + psmTrailField(renderer, 0x910) = dx9rend::vertexDeclarationCreate(declaration); const PsmCtorParameter parameters[] = { {0x8E4, "ViewMat"}, {0x8E8, "ProjMat"}, {0x8EC, "HemiMapInfo"}, {0x8F0, "HemiShadowAltitude"}, {0x8F8, "Texture0"}, {0x8FC, "Texture1"}, @@ -288,37 +329,39 @@ static void psmConstructTrailRenderer(unsigned char* renderer) {0x8DC, "fogRange"}, {0x8E0, "fogColor"}, {0x908, "EffectSunColor"}, {0x90C, "EffectShadowColor"} }; - psmCtorParameters(renderer, 0x8D8, parameters); + psmCtorParameters(renderer, psmTrailRendererOffset, 0x8D8, parameters); dx9rend::registerDeviceLostResetListener(listener, 4); } +// PE 0x1016E0C0 static void psmConstructNsaParticleRenderer(unsigned char* renderer) { + psmCtorClearTail(renderer, 0x5A0, kPsmNsaRendererSize); renderer[0] = 0; - psmCtorField(renderer, 4) = 0; - psmCtorField(renderer, 8) = -1; - psmCtorPointerVector(renderer + 0xC); - psmCtorField(renderer, 0x1C) = 0; - psmCtorField(renderer, 0x420) = 0; + psmNsaField(renderer, 4) = 0; + psmNsaField(renderer, 8) = -1; + psmCtorPointerVector(renderer, psmNsaRendererOffset(0xC)); + psmNsaField(renderer, 0x1C) = 0; + psmNsaField(renderer, 0x420) = 0; renderer[0x424] = 0; - psmCtorZeroWords(renderer, 0x428, 6); - psmCtorField(renderer, 0x444) = 0; + psmCtorZeroRetailWords(renderer, psmNsaRendererOffset, 0x428, 6); + psmNsaField(renderer, 0x444) = 0; psmCtorParticleMatrices(renderer + 0x448); renderer[0x518] = 0; - psmCtorField(renderer, 0x51C) = 0; + psmNsaField(renderer, 0x51C) = 0; renderer[0x520] = 0; - psmCtorField(renderer, 0x528) = 0; - psmCtorField(renderer, 0x52C) = 0; + psmNsaField(renderer, 0x528) = 0; + psmNsaField(renderer, 0x52C) = 0; for (unsigned int i = 0; i < 4; ++i) - psmCtorField(renderer, 0x534 + 4u * i) = 0.5f; + psmNsaField(renderer, 0x534 + 4u * i) = 0.5f; renderer[0x544] = 1; renderer[0x545] = 0; renderer[0x546] = 0; - psmCtorField(renderer, 0x55C) = 0; - psmCtorField(renderer, 0x564) = 0; - psmCtorField(renderer, 0x568) = 0; - psmCtorPrimePointerVector(renderer + 0xC); - psmCtorZeroWords(renderer, 0x20, 256); + psmNsaField(renderer, 0x55C) = 0; + psmNsaField(renderer, 0x564) = 0; + psmNsaField(renderer, 0x568) = 0; + psmCtorPrimePointerVector(renderer, psmNsaRendererOffset(0xC)); + psmCtorZeroRetailWords(renderer, psmNsaRendererOffset, 0x20, 256); const D3DVERTEXELEMENT9 declaration[] = { {0, 0x00, 2, 0, 0, 0}, {0, 0x0C, 1, 0, 5, 0}, @@ -326,8 +369,8 @@ static void psmConstructNsaParticleRenderer(unsigned char* renderer) {0, 0x2C, 1, 0, 5, 3}, {0, 0x34, 7, 0, 5, 4}, {0, 0x3C, 7, 0, 5, 5}, {0, 0x44, 6, 0, 5, 6}, D3DDECL_END() }; - psmCtorField(renderer, 0x59C) = dx9rend::vertexDeclarationCreate(declaration); - psmCtorField(renderer, 0x56C) = dx9rend::shaderManagerGetEffect( + psmNsaField(renderer, 0x59C) = dx9rend::vertexDeclarationCreate(declaration); + psmNsaField(renderer, 0x56C) = dx9rend::shaderManagerGetEffect( dx9rend::g_shaderManager, "mods/xpack/shaders/NonScreenAlignedParticles"); const PsmCtorParameter parameters[] = { {0x570, "ViewMat"}, {0x574, "ProjMat"}, {0x578, "HemiMapInfo"}, @@ -335,6 +378,6 @@ static void psmConstructNsaParticleRenderer(unsigned char* renderer) {0x584, "TemplateParameters"}, {0x58C, "fogRange"}, {0x590, "fogColor"}, {0x594, "EffectSunColor"}, {0x598, "EffectShadowColor"} }; - psmCtorParameters(renderer, 0x56C, parameters); - psmCtorParticleScratch(renderer, 0x564, 0x55C); + psmCtorParameters(renderer, psmNsaRendererOffset, 0x56C, parameters); + psmCtorParticleScratch(renderer, psmNsaRendererOffset, 0x564, 0x55C); } diff --git a/Code/BF2/Geom/ParticleSystem/ParticleRendererDraw.inl b/Code/BF2/Geom/ParticleSystem/ParticleRendererDraw.inl index 763706570..e7063aa39 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleRendererDraw.inl +++ b/Code/BF2/Geom/ParticleSystem/ParticleRendererDraw.inl @@ -1,6 +1,5 @@ // Particle collection, shader binding and GPU submission; included inside the manager namespace. -// [RETIRE-WHEN: particle-mesh-debug-bounds] Replace the optional bounds boundary after -// the mesh overlay is implemented and validated. Include standard headers before this file. +// Include standard headers before this file. template static T& psmDrawField(unsigned char* renderer, unsigned int offset) @@ -8,20 +7,55 @@ static T& psmDrawField(unsigned char* renderer, unsigned int offset) return *reinterpret_cast(renderer + offset); } -// VC7.1 vector::resize(0), used by 10172890, 1016F4F0 and 10174410. These -// pointer elements own nothing: erase retains the allocation, allocator word and capacity. -static void psmDrawClearPointerVector(unsigned char* vector) +// vector::resize(0), used by 10172890, 1016F4F0 and 10174410, on the renderer pointer list at +// native `offset`. These pointer elements own nothing: erase retains the allocation and capacity. +template +static void psmDrawClearPointerVector(unsigned char* renderer, unsigned int offset) { - unsigned char** const first = psmDrawField(vector, 4); - if (first && psmDrawField(vector, 8) != first) - psmDrawField(vector, 8) = first; + particleRendererList(renderer, offset).clear(); } -static unsigned int psmDrawPointerVectorSize(unsigned char* vector) +template +static unsigned int psmDrawPointerVectorSize(unsigned char* renderer, unsigned int offset) { - unsigned char** const first = psmDrawField(vector, 4); - return first ? static_cast( - psmDrawField(vector, 8) - first) : 0; + return static_cast(particleRendererList(renderer, offset).size()); +} + +// PE 0x1016EB70. [INFERRED] private helper name and placement beside its renderer callers. +static float psmParticleBoundsRadius(const float* bounds) +{ + const float deltaZ = bounds[5] - bounds[2]; +#if defined(__APPLE__) + // [CHOSEN, not recovered] Preserve the two float spills and retained half-Y value. + using bf2x87::wide; + const float halfX = bf2x87::store((wide(bounds[3]) - wide(bounds[0])) * wide(0.5f)); + const bf2x87::Real halfY = (wide(bounds[4]) - wide(bounds[1])) * wide(0.5f); + const bf2x87::Real halfZ = wide(deltaZ) * wide(0.5f); + return bf2x87::store(bf2x87::squareRoot(halfZ * halfZ + wide(halfX) * wide(halfX) + halfY * halfY)); +#else + const float halfX = static_cast((static_cast(bounds[3]) - bounds[0]) * 0.5); + const double halfY = (static_cast(bounds[4]) - bounds[1]) * 0.5; + const double halfZ = static_cast(deltaZ) * 0.5; + return static_cast(std::sqrt(halfZ * halfZ + static_cast(halfX) * halfX + halfY * halfY)); +#endif +} + +// PE 0x1016EBC0. [INFERRED] private helper name and placement beside its renderer callers. +static Vec3 psmParticleBoundsCenter(const float* bounds) +{ + const float sumZ = bounds[5] + bounds[2]; + Vec3 center; +#if defined(__APPLE__) + // [CHOSEN, not recovered] X/Y retain their sums through scaling; Z reloads its float spill. + using bf2x87::wide; + center.x = bf2x87::store((wide(bounds[3]) + wide(bounds[0])) * wide(0.5f)); + center.y = bf2x87::store((wide(bounds[4]) + wide(bounds[1])) * wide(0.5f)); +#else + center.x = static_cast((static_cast(bounds[3]) + bounds[0]) * 0.5); + center.y = static_cast((static_cast(bounds[4]) + bounds[1]) * 0.5); +#endif + center.z = sumZ * 0.5f; + return center; } #include "ParticleRendererActive.inl" @@ -32,22 +66,23 @@ static unsigned int psmDrawPointerVectorSize(unsigned char* vector) // The resets precede both the empty-input and disabled exits; // the current index at +4 is deliberately retained. The vector is at renderer +8. +// PE 0x10171790 static void psmPrepareParticleRenderer(unsigned char* renderer, dx9rend::IRenderView* view, - ParticleSystemInstanceList* instances, float deltaTime, bool firstPerson) + ParticleSystemInstanceVector* instances, float deltaTime, bool firstPerson) { - const unsigned int count = instances->size(); - psmDrawField(renderer, 0x1D7C) = 0; - psmDrawField(renderer, 0x1D6C) = 0; - psmDrawClearPointerVector(renderer + 8); - psmDrawField(renderer, 0x1820) = 0; - psmDrawField(renderer, 0x1824) = 0; - psmDrawField(renderer, 0x1828) = 0; - if (!count || !psmDrawField(renderer, 0x1D9C)) + const unsigned int count = static_cast(instances->size()); + psmSpriteField(renderer, 0x1D7C) = 0; + psmSpriteField(renderer, 0x1D6C) = 0; + psmDrawClearPointerVector(renderer, psmSpriteRendererOffset(8)); + psmSpriteField(renderer, 0x1820) = 0; + psmSpriteField(renderer, 0x1824) = 0; + psmSpriteField(renderer, 0x1828) = 0; + if (!count || !psmSpriteField(renderer, 0x1D9C)) return; - psmDrawField(renderer, 0x1C3C) = deltaTime; - psmDrawField(renderer, 0x1C58) = *view->getInverseViewMatrixPtr(); - Mat4& viewProjection = psmDrawField(renderer, 0x1C98); + psmSpriteField(renderer, 0x1C3C) = deltaTime; + psmSpriteField(renderer, 0x1C58) = *view->getInverseViewMatrixPtr(); + Mat4& viewProjection = psmSpriteField(renderer, 0x1C98); viewProjection = *view->getViewMatrixPtr(); const Mat4 originalView = viewProjection; fullInvert(originalView, viewProjection); @@ -55,155 +90,135 @@ static void psmPrepareParticleRenderer(unsigned char* renderer, dx9rend::IRender const Mat4 inverseView = viewProjection; viewProjection.fullMult(inverseView, *projection); // CRT initializer 101D5060: 1 / sqrt(double(2)), stored once as a float. - psmDrawField(renderer, 0x1D18) = static_cast(1.0 / std::sqrt(2.0)); - psmDrawField(renderer, 0x1D1C) = 255.0f; - psmDrawField(renderer, 0x1D20) = 0; - psmDrawField(renderer, 0x1D24) = 0; + psmSpriteField(renderer, 0x1D18) = static_cast(1.0 / std::sqrt(2.0)); + psmSpriteField(renderer, 0x1D1C) = 255.0f; + psmSpriteField(renderer, 0x1D20) = 0; + psmSpriteField(renderer, 0x1D24) = 0; const Mat4* inverse = view->getInverseViewMatrixPtr(); for (unsigned int i = 0; i < 4; ++i) - psmDrawField(renderer, 0x1C40 + i * 4) = inverse->m[2 + i * 4]; + psmSpriteField(renderer, 0x1C40 + i * 4) = inverse->m[2 + i * 4]; for (unsigned int i = 0; i < count; ++i) { - if (instances->first[i]->reserved01() != 0) continue; - unsigned char* instance = reinterpret_cast(instances->first[i]); + if ((*instances)[i]->reserved01() != 0) continue; + unsigned char* instance = reinterpret_cast((*instances)[i]); if ((instance[8] != 0) != firstPerson) continue; - if (!instance[0x14C] && !psmDrawField(instance, 0x28)) continue; + if (!instance[0x14C] && !psmInstanceA(instance, 0x28)) continue; const float* bounds = reinterpret_cast(instance + 0xFC); - Vec3 center; - center.x = static_cast((static_cast(bounds[0]) + bounds[3]) * 0.5); - center.y = static_cast((static_cast(bounds[4]) + bounds[1]) * 0.5); - const float sumZ = bounds[5] + bounds[2]; - center.z = sumZ * 0.5f; - const float halfX = (bounds[3] - bounds[0]) * 0.5f; - const double halfY = (static_cast(bounds[4]) - bounds[1]) * 0.5; - const float deltaZ = bounds[5] - bounds[2]; - const double halfZ = static_cast(deltaZ) * 0.5; - const float radius = static_cast(std::sqrt(halfZ * halfZ + static_cast(halfX) * halfX + halfY * halfY)); - if (!view->getFrustumPtr()->inside(center, radius)) continue; - void* owner = psmDrawField(instance, 0x10); + const Vec3 center = psmParticleBoundsCenter(bounds); + const float radius = psmParticleBoundsRadius(bounds); + if (!rendmath::frustumInside(*view->getFrustumPtr(), center, radius)) continue; + void* owner = psmInstanceA(instance, 0x10); if (owner && psmOwnerRootDisabled(owner)) continue; // IObject m_flags bit 0 (RW-266) - psmDrawField(instance, 0x124) = + psmInstanceA(instance, 0x124) = static_cast(dx9rend::g_rendererBase)->getFrameOrdinal(); instance[0x128] = 1; - if (psmDrawField(instance, 0x28)) + if (psmInstanceA(instance, 0x28)) { - unsigned char* descriptor = psmDrawField(instance, 0x2C); - typedef void (__fastcall *Collector)(void*, void*, dx9rend::IRenderView*, + unsigned char* descriptor = psmInstanceA(instance, 0x2C); + typedef void (__thiscall *Collector)(void*, dx9rend::IRenderView*, IParticleSystemInstance*, IParticleSystemTemplate*); - psmDrawField(descriptor, 0x2A0)(renderer, 0, view, + psmDescriptor0(descriptor, 0x2A0)(renderer, view, reinterpret_cast(instance), reinterpret_cast(descriptor)); } } - if (psmDrawField(renderer, 0x1C38)) + if (psmSpriteField(renderer, 0x1C38)) { - psmSortParticles(renderer, psmDrawField(renderer, 0x18), - psmDrawField(renderer, 0x1C38)); - psmDrawField(renderer, 4) = psmDrawField(renderer, 0x1C38) - 1; + psmSortParticles(renderer, psmSpriteField(renderer, 0x18), + psmSpriteField(renderer, 0x1C38)); + psmSpriteField(renderer, 4) = psmSpriteField(renderer, 0x1C38) - 1; } } // Empty or disabled input returns before any renderer write. // In particular it does not reset the index +8 or retained eligibility byte +520. +// PE 0x1016E750 static void psmPrepareNsaParticleRenderer(unsigned char* renderer, dx9rend::IRenderView* view, - ParticleSystemInstanceList* instances, + ParticleSystemInstanceVector* instances, float deltaTime, bool firstPerson) { - const unsigned int count = instances->size(); - if (!count || !psmDrawField(renderer, 0x544)) + const unsigned int count = static_cast(instances->size()); + if (!count || !psmNsaField(renderer, 0x544)) return; - psmDrawField(renderer, 0x524) = 0; - psmDrawField(renderer, 0x518) = 0; - psmDrawClearPointerVector(renderer + 0xC); - psmDrawField(renderer, 0x42C) = deltaTime; - psmDrawField(renderer, 0x448) = *view->getInverseViewMatrixPtr(); - Mat4& viewProjection = psmDrawField(renderer, 0x488); + psmNsaField(renderer, 0x524) = 0; + psmNsaField(renderer, 0x518) = 0; + psmDrawClearPointerVector(renderer, psmNsaRendererOffset(0xC)); + psmNsaField(renderer, 0x42C) = deltaTime; + psmNsaField(renderer, 0x448) = *view->getInverseViewMatrixPtr(); + Mat4& viewProjection = psmNsaField(renderer, 0x488); viewProjection = *view->getViewMatrixPtr(); const Mat4 originalView = viewProjection; fullInvert(originalView, viewProjection); const Mat4* projection = view->getProjectionMatrixPtr(); const Mat4 inverseView = viewProjection; viewProjection.fullMult(inverseView, *projection); - psmDrawField(renderer, 0x508) = static_cast(1.0 / std::sqrt(2.0)); - psmDrawField(renderer, 0x50C) = 255.0f; - psmDrawField(renderer, 0x510) = 0; - psmDrawField(renderer, 0x514) = 0; + psmNsaField(renderer, 0x508) = static_cast(1.0 / std::sqrt(2.0)); + psmNsaField(renderer, 0x50C) = 255.0f; + psmNsaField(renderer, 0x510) = 0; + psmNsaField(renderer, 0x514) = 0; const Mat4* inverse = view->getInverseViewMatrixPtr(); for (unsigned int i = 0; i < 4; ++i) - psmDrawField(renderer, 0x430 + 4 * i) = inverse->m[2 + 4 * i]; + psmNsaField(renderer, 0x430 + 4 * i) = inverse->m[2 + 4 * i]; for (unsigned int i = 0; i < count; ++i) { - if (instances->first[i]->reserved01() != 4) continue; - unsigned char* instance = reinterpret_cast(instances->first[i]); - if (!instance[0x14C] && !psmDrawField(instance, 0x28)) continue; + if ((*instances)[i]->reserved01() != 4) continue; + unsigned char* instance = reinterpret_cast((*instances)[i]); + if (!instance[0x14C] && !psmInstanceA(instance, 0x28)) continue; if ((instance[8] != 0) != firstPerson) continue; const float* bounds = reinterpret_cast(instance + 0xFC); - Vec3 center; - center.x = static_cast((static_cast(bounds[0]) + bounds[3]) * 0.5); - center.y = static_cast((static_cast(bounds[4]) + bounds[1]) * 0.5); - const float sumZ = bounds[5] + bounds[2]; - center.z = sumZ * 0.5f; - const float halfX = (bounds[3] - bounds[0]) * 0.5f; - const double halfY = (static_cast(bounds[4]) - bounds[1]) * 0.5; - const float deltaZ = bounds[5] - bounds[2]; - const double halfZ = static_cast(deltaZ) * 0.5; - const float radius = static_cast(std::sqrt(halfZ * halfZ - + static_cast(halfX) * halfX + halfY * halfY)); - if (!view->getFrustumPtr()->inside(center, radius)) continue; - void* owner = psmDrawField(instance, 0x10); + const Vec3 center = psmParticleBoundsCenter(bounds); + const float radius = psmParticleBoundsRadius(bounds); + if (!rendmath::frustumInside(*view->getFrustumPtr(), center, radius)) continue; + void* owner = psmInstanceA(instance, 0x10); if (owner && psmOwnerRootDisabled(owner)) continue; // IObject m_flags bit 0 (RW-266) - psmDrawField(instance, 0x124) = + psmInstanceA(instance, 0x124) = static_cast(dx9rend::g_rendererBase)->getFrameOrdinal(); instance[0x128] = 1; - if (psmDrawField(instance, 0x28)) + if (psmInstanceA(instance, 0x28)) { - psmCollectNsaParticles(renderer, view, instance, psmDrawField(instance, 0x2C)); + psmCollectNsaParticles(renderer, view, instance, psmInstanceA(instance, 0x2C)); if (renderer[0x545]) { - // [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: particle-nsa-debug-bounds] - // PE 1016E986 requests/publishes a DebugBoxMesh through owner10247C3C. - std::fprintf(stderr, "[FRONTIER] dice::hfe::geom::NSAParticleSystemRenderer::prepare " - "(debug bounding mesh, PE 1016E986) reached\n"); - std::fflush(stderr); - std::abort(); + // PE 0x1016E986. + debugRendererQueueBounds(bounds); } } } - if (psmDrawField(renderer, 0x428)) + if (psmNsaField(renderer, 0x428)) { - psmSortNsaParticles(renderer, psmDrawField(renderer, 0x1C), - psmDrawField(renderer, 0x428)); - psmDrawField(renderer, 8) = psmDrawField(renderer, 0x428) - 1; + psmSortNsaParticles(renderer, psmNsaField(renderer, 0x1C), + psmNsaField(renderer, 0x428)); + psmNsaField(renderer, 8) = psmNsaField(renderer, 0x428) - 1; } } // The five counters and the matrix-cache byte are reset even // for empty or disabled input. The retained pointer vector at +1D80 is not cleared. static void psmPrepareMeshParticleRenderer(unsigned char* renderer, dx9rend::IRenderView* view, - ParticleSystemInstanceList* instances, float deltaTime) + ParticleSystemInstanceVector* instances, float deltaTime) { - psmDrawField(renderer, 0x1D3C) = 0; - const unsigned int count = instances->size(); - psmDrawField(renderer, 0x1C14) = 0; - psmDrawField(renderer, 0x1808) = 0; - psmDrawField(renderer, 0x180C) = 0; - psmDrawField(renderer, 0x1810) = 0; - psmDrawField(renderer, 0x1D4C) = 0; - if (!count || !psmDrawField(renderer, 0x1D6C)) + psmMeshField(renderer, 0x1D3C) = 0; + const unsigned int count = static_cast(instances->size()); + psmMeshField(renderer, 0x1C14) = 0; + psmMeshField(renderer, 0x1808) = 0; + psmMeshField(renderer, 0x180C) = 0; + psmMeshField(renderer, 0x1810) = 0; + psmMeshField(renderer, 0x1D4C) = 0; + if (!count || !psmMeshField(renderer, 0x1D6C)) return; - psmDrawField(renderer, 0x1C20) = deltaTime; + psmMeshField(renderer, 0x1C20) = deltaTime; // the inverse-view (camera) matrix's third column is the depth row the collector // dots every particle with. Primary slot +0x68. const Mat4* inverse = view->getInverseViewMatrixPtr(); for (unsigned int i = 0; i < 4; ++i) - psmDrawField(renderer, 0x1C24 + 4 * i) = inverse->m[2 + 4 * i]; + psmMeshField(renderer, 0x1C24 + 4 * i) = inverse->m[2 + 4 * i]; for (unsigned int i = 0; i < count; ++i) { - if (instances->first[i]->reserved01() != 1) continue; - unsigned char* instance = reinterpret_cast(instances->first[i]); - if (!instance[0x144] && !psmDrawField(instance, 0x28)) continue; + if ((*instances)[i]->reserved01() != 1) continue; + unsigned char* instance = reinterpret_cast((*instances)[i]); + if (!instance[0x144] && !psmInstanceB(instance, 0x28)) continue; // Center inline, radius through 1016EB70, exactly as the sibling renderers. const float* bounds = reinterpret_cast(instance + 0xFC); Vec3 center; @@ -217,213 +232,275 @@ static void psmPrepareMeshParticleRenderer(unsigned char* renderer, dx9rend::IRe const double halfZ = static_cast(deltaZ) * 0.5; const float radius = static_cast(std::sqrt(halfZ * halfZ + static_cast(halfX) * halfX + halfY * halfY)); - if (!view->getFrustumPtr()->inside(center, radius)) continue; - void* owner = psmDrawField(instance, 0x10); + if (!rendmath::frustumInside(*view->getFrustumPtr(), center, radius)) continue; + void* owner = psmInstanceB(instance, 0x10); if (owner && psmOwnerRootDisabled(owner)) continue; // IObject m_flags bit 0 (RW-266) - psmDrawField(instance, 0x124) = + psmInstanceB(instance, 0x124) = static_cast(dx9rend::g_rendererBase)->getFrameOrdinal(); instance[0x21E] = 1; - if (!psmDrawField(instance, 0x28)) continue; + if (!psmInstanceB(instance, 0x28)) continue; // 10174F2F: 255 admitted groups (both draw orders together) end the whole walk; the // remaining instances are neither marked nor collected. The note is one-shot per process. - if (psmDrawField(renderer, 0x180C) + psmDrawField(renderer, 0x1810) >= 0xFF) + if (psmMeshField(renderer, 0x180C) + psmMeshField(renderer, 0x1810) >= 0xFF) { psmNoteMeshGroupOverflow(renderer); break; } - psmCollectMeshParticles(renderer, view, instance, psmDrawField(instance, 0x2C)); + psmCollectMeshParticles(renderer, view, instance, psmInstanceB(instance, 0x2C)); if (renderer[0x1D6E]) { - // [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: particle-mesh-debug-bounds] - // PE 10174F58..1017500E requests a DebugBoxMesh through owner 10247C3C (+0x18 by - // reflection type, named "bounding" via +0x68), scales the shared identity (100791E0) - // by the aabb extents, translates it to the aabb center (1016EBC0) and publishes it - // (+0x14). Renderer byte +0x1D6E, constructor default false. - std::fprintf(stderr, "[FRONTIER] dice::hfe::geom::MeshParticlesRenderer::prepare " - "(debug bounding mesh, PE 10174F58) reached\n"); - std::fflush(stderr); - std::abort(); + // PE 0x10174F58. + debugRendererQueueBounds(bounds); } } // the over-budget byte compares +0x1C14, which this function zeroed above and only // the draw increments, so it is always false here. Kept, like Trail's +0x728. const unsigned int threshold = static_cast(static_cast( - static_cast(psmDrawField(renderer, 0x1D78)) * 0.85000002f)); - renderer[0x1C18] = psmDrawField(renderer, 0x1C14) > threshold; + static_cast(psmMeshField(renderer, 0x1D78)) * 0.85000002f)); + renderer[0x1C18] = psmMeshField(renderer, 0x1C14) > threshold; } +// PE 0x1016F5D0. // The table loads precede the index == -1 tests in the PE, // including the loops. There is no table-null or index-range guard. The unsigned comparison // is entry +14 >= target. Both sorted groups contribute to the same +1D79 byte. static bool psmSelectParticleRenderer(unsigned char* renderer, unsigned int target) { - unsigned char** const table = psmDrawField(renderer, 0x18); - psmDrawField(renderer, 0x1D7C) = target; - const int index = psmDrawField(renderer, 4); - psmDrawField(renderer, 0x1D78) = 0; - psmDrawField(renderer, 0x1D79) = 0; - unsigned char* const entry = table[index]; + unsigned char** const table = psmSpriteField(renderer, 0x18); + psmSpriteField(renderer, 0x1D7C) = target; + const int index = psmSpriteField(renderer, 4); + psmSpriteField(renderer, 0x1D78) = 0; + psmSpriteField(renderer, 0x1D79) = 0; + // PE 0x1016F5D0: same out-of-bounds table[-1] read before the -1 test in retail; omitted + // [CHOSEN, not recovered] by loading only when the index is not -1 (here and in the loops below). + unsigned char* const entry = (index != -1) ? table[index] : 0; if (index != -1 && entry && psmDrawField(entry, 0x14) >= target) - psmDrawField(renderer, 0x1D78) = 1; + psmSpriteField(renderer, 0x1D78) = 1; for (unsigned int group = 0; group < 2; ++group) { const unsigned int countOffset = group ? 0x1828 : 0x1824; - if (psmDrawField(renderer, countOffset)) + if (psmSpriteField(renderer, countOffset)) { - unsigned char** const sortedTable = psmDrawField(renderer, 0x1C); + unsigned char** const sortedTable = psmSpriteField(renderer, 0x1C); const unsigned int firstIndexOffset = group ? 0xC24 : 0x24; - for (unsigned int i = 0; i < psmDrawField(renderer, countOffset); ++i) + for (unsigned int i = 0; i < psmSpriteField(renderer, countOffset); ++i) { - const int sortedIndex = psmDrawField(renderer, firstIndexOffset + 12 * i); - unsigned char* const sortedEntry = sortedTable[sortedIndex]; + const int sortedIndex = psmSpriteField(renderer, firstIndexOffset + 12 * i); + unsigned char* const sortedEntry = (sortedIndex != -1) ? sortedTable[sortedIndex] : 0; if (sortedIndex != -1 && sortedEntry && psmDrawField(sortedEntry, 0x14) >= target) { - psmDrawField(renderer, 0x1D79) = 1; + psmSpriteField(renderer, 0x1D79) = 1; break; } } } } - return psmDrawField(renderer, 0x1D79) != 0 - || psmDrawField(renderer, 0x1D78) != 0; + return psmSpriteField(renderer, 0x1D79) != 0 + || psmSpriteField(renderer, 0x1D78) != 0; } +// PE 0x1016D540. // Unlike the ordinary renderer this never clears +520. // The entry's threshold at +94 is unsigned, and the indexed load precedes the -1 test. static bool psmSelectNsaParticleRenderer(unsigned char* renderer, unsigned int target) { - unsigned char** const table = psmDrawField(renderer, 0x1C); - psmDrawField(renderer, 0x524) = target; - const int index = psmDrawField(renderer, 8); - unsigned char* const entry = table[index]; + unsigned char** const table = psmNsaField(renderer, 0x1C); + psmNsaField(renderer, 0x524) = target; + const int index = psmNsaField(renderer, 8); + // PE 0x1016D540: retail loads table[index] before the -1 test; that read of table[-1] is out of + // bounds. [CHOSEN, not recovered] the load is made only when index != -1 (the loaded value is + // never used otherwise), so no out-of-bounds read happens. + unsigned char* const entry = (index != -1) ? table[index] : 0; if (index != -1 && entry && psmDrawField(entry, 0x94) >= target) - psmDrawField(renderer, 0x520) = 1; - return psmDrawField(renderer, 0x520) != 0; + psmNsaField(renderer, 0x520) = 1; + return psmNsaField(renderer, 0x520) != 0; } +// PE 0x10174570. // The two sorted groups have independent flags. Every invocation // clears both flags, stores target, then scans each group until its first qualifying record. static bool psmSelectMeshParticleRenderer(unsigned char* renderer, unsigned int target) { - psmDrawField(renderer, 0x1D4C) = target; - psmDrawField(renderer, 0x1D48) = 0; - psmDrawField(renderer, 0x1D49) = 0; + psmMeshField(renderer, 0x1D4C) = target; + psmMeshField(renderer, 0x1D48) = 0; + psmMeshField(renderer, 0x1D49) = 0; for (unsigned int group = 0; group < 2; ++group) { const unsigned int countOffset = group ? 0x1810 : 0x180C; - if (psmDrawField(renderer, countOffset)) + if (psmMeshField(renderer, countOffset)) { - unsigned char** const table = psmDrawField(renderer, 4); + unsigned char** const table = psmMeshField(renderer, 4); const unsigned int firstIndexOffset = group ? 0xC0C : 0xC; - for (unsigned int i = 0; i < psmDrawField(renderer, countOffset); ++i) + for (unsigned int i = 0; i < psmMeshField(renderer, countOffset); ++i) { - const int index = psmDrawField(renderer, firstIndexOffset + 12 * i); - unsigned char* const entry = table[index]; + const int index = psmMeshField(renderer, firstIndexOffset + 12 * i); + unsigned char* const entry = (index != -1) ? table[index] : 0; // PE 0x10174570, as above if (index != -1 && entry && psmDrawField(entry, 0xBC) >= target) { - psmDrawField(renderer, group ? 0x1D49 : 0x1D48) = 1; + psmMeshField(renderer, group ? 0x1D49 : 0x1D48) = 1; break; } } } } - return psmDrawField(renderer, 0x1D49) != 0 - || psmDrawField(renderer, 0x1D48) != 0; + return psmMeshField(renderer, 0x1D49) != 0 + || psmMeshField(renderer, 0x1D48) != 0; } -// An empty count does not clear previously-set eligibility. +// PE 0x10172A60. An empty count does not clear previously-set eligibility. static bool psmSelectTrailRenderer(unsigned char* renderer, unsigned int target) { - psmDrawField(renderer, 0x85C) = target; - if (psmDrawField(renderer, 0x320)) - psmDrawField(renderer, 0x858) = 1; - return psmDrawField(renderer, 0x858) != 0; + psmTrailField(renderer, 0x85C) = target; + if (psmTrailField(renderer, 0x320)) + psmTrailField(renderer, 0x858) = 1; + return psmTrailField(renderer, 0x858) != 0; +} + +// Renderer leaf stores that nothing calls or references in 1.50: unreachable in 1.50: no code or data +// references. Each body is the listing's plain field store. The names and the (first, second) pair +// element type are [CHOSEN, not recovered]: no instruction reads the fields through these setters, and +// the two dword stores (eax, edx from the two stack arguments, ret 8) are all the listing proves. + +// PE 0x1016D600 (NSA renderer): byte store at +0x545. +static void psmNsaSetFlag545(unsigned char* renderer, unsigned char value) +{ + psmNsaField(renderer, 0x545) = value; +} + +// PE 0x1016D620 (NSA renderer): byte store at +0x546. +static void psmNsaSetFlag546(unsigned char* renderer, unsigned char value) +{ + psmNsaField(renderer, 0x546) = value; +} + +// PE 0x1016F5B0 (sprite renderer): two dword stores at +0x1C50 and +0x1C54. +static void psmSpriteSetPair1C50(unsigned char* renderer, unsigned int first, unsigned int second) +{ + psmSpriteField(renderer, 0x1C50) = first; + psmSpriteField(renderer, 0x1C54) = second; +} + +// PE 0x1016F7D0 (sprite renderer): byte store at +0x1D9E. +static void psmSpriteSetFlag1D9E(unsigned char* renderer, unsigned char value) +{ + psmSpriteField(renderer, 0x1D9E) = value; +} + +// PE 0x10172A40 (trail renderer): two dword stores at +0x744 and +0x748. +static void psmTrailSetPair744(unsigned char* renderer, unsigned int first, unsigned int second) +{ + psmTrailField(renderer, 0x744) = first; + psmTrailField(renderer, 0x748) = second; +} + +// PE 0x10172AA0 (trail renderer): byte store at +0x885. +static void psmTrailSetFlag885(unsigned char* renderer, unsigned char value) +{ + psmTrailField(renderer, 0x885) = value; +} + +// PE 0x10172AC0 (trail renderer): byte store at +0x886. +static void psmTrailSetFlag886(unsigned char* renderer, unsigned char value) +{ + psmTrailField(renderer, 0x886) = value; +} + +// PE 0x10172AE0 (trail renderer): byte store at +0x887. +static void psmTrailSetFlag887(unsigned char* renderer, unsigned char value) +{ + psmTrailField(renderer, 0x887) = value; } // both exits explicitly return false in AL. The active branch // first constructs/enters the ParticleSystem profiling scope, then touches StateManager. +// PE 0x10171CB0 static bool psmDrawParticleRenderer(unsigned char* renderer, dx9rend::IRenderView* view) { - if (!psmDrawField(renderer, 0x1D9C)) + if (!psmSpriteField(renderer, 0x1D9C)) return false; - if (!psmDrawField(renderer, 0x1D79) - && !psmDrawField(renderer, 0x1D78)) + if (!psmSpriteField(renderer, 0x1D79) + && !psmSpriteField(renderer, 0x1D78)) return false; - // [CHOSEN, not recovered] Like the existing mesh/sky draw paths, renderer profiler - // registration/timing is omitted; all render state and submission ordering is retained. + static dx9rend::QueueProfiler profiler(std::string("ParticleSystem")); // PE 0x10260FC8, guard 0x10261230 + profiler.begin(); dx9rend::stateManagerPush(); if (!renderer[0x1D6C]) { - psmDrawField(renderer, 0x1CD8) = *view->getProjectionMatrixPtr(); + psmSpriteField(renderer, 0x1CD8) = *view->getProjectionMatrixPtr(); const Mat4* projection = view->getProjectionMatrixPtr(); const Mat4* inverse = view->getInverseViewMatrixPtr(); - psmDrawField(renderer, 0x1D28).fullMult(*inverse, *projection); - psmDrawField(renderer, 0x1D68) = view->getViewport()[2]; + psmSpriteField(renderer, 0x1D28).fullMult(*inverse, *projection); + psmSpriteField(renderer, 0x1D68) = view->getViewport()[2]; renderer[0x1D6C] = 1; } bool drawn = false; psmBindParticleParameters(renderer); - if (renderer[0x1D79] && psmDrawField(renderer, 0x1828)) - drawn = psmDrawAdditiveParticles(renderer, psmDrawField(renderer, 0x1D7C), - psmDrawField(renderer, 0x1828), renderer + 0xC20); + if (renderer[0x1D79] && psmSpriteField(renderer, 0x1828)) + drawn = psmDrawAdditiveParticles(renderer, psmSpriteField(renderer, 0x1D7C), + psmSpriteField(renderer, 0x1828), psmSpriteGroups(renderer, 0xC20)); if (renderer[0x1D78]) { - const bool sortedDrawn = psmDrawSortedParticles(renderer, psmDrawField(renderer, 0x1D7C)); + const bool sortedDrawn = psmDrawSortedParticles(renderer, psmSpriteField(renderer, 0x1D7C)); drawn = sortedDrawn || drawn; renderer[0x1D78] = 0; } - if (renderer[0x1D79] && psmDrawField(renderer, 0x1824)) - drawn = psmDrawAdditiveParticles(renderer, psmDrawField(renderer, 0x1D7C), - psmDrawField(renderer, 0x1824), renderer + 0x20); // retail overwrites result + if (renderer[0x1D79] && psmSpriteField(renderer, 0x1824)) + drawn = psmDrawAdditiveParticles(renderer, psmSpriteField(renderer, 0x1D7C), + psmSpriteField(renderer, 0x1824), psmSpriteGroups(renderer, 0x20)); // retail overwrites result renderer[0x1D79] = 0; dx9rend::stateManagerPop(); + dx9rend::QueueProfiler::end(); return drawn; } // Do not clear +520 on the disabled exit: retail clears it // only after the active 1016D9B0 draw returns. +// PE 0x1016EA80 static bool psmDrawNsaParticleRenderer(unsigned char* renderer, dx9rend::IRenderView* view) { - if (!psmDrawField(renderer, 0x544) - || !psmDrawField(renderer, 0x520)) + if (!psmNsaField(renderer, 0x544) + || !psmNsaField(renderer, 0x520)) return false; - // [CHOSEN, not recovered] Profiler registration/timing is omitted, as in the ordinary draw. + static dx9rend::QueueProfiler profiler(std::string("NSAParticleSystem")); // PE 0x10260D58, guard 0x10260FC0 + profiler.begin(); dx9rend::stateManagerPush(); if (!renderer[0x518]) { - psmDrawField(renderer, 0x4C8) = *view->getProjectionMatrixPtr(); + psmNsaField(renderer, 0x4C8) = *view->getProjectionMatrixPtr(); renderer[0x518] = 1; } bool drawn = false; if (renderer[0x520]) { - drawn = psmDrawNsaParticles(renderer, psmDrawField(renderer, 0x524)); + drawn = psmDrawNsaParticles(renderer, psmNsaField(renderer, 0x524)); renderer[0x520] = 0; } dx9rend::stateManagerPop(); + dx9rend::QueueProfiler::end(); return drawn; } // Either the selected group flag OR a retained +1D80 list // requires the active branch. The renderer-enabled check comes after that decision. +// PE 0x101754A0 static bool psmDrawMeshParticleRenderer(unsigned char* renderer, dx9rend::IRenderView* view, bool pass) { - if (!psmDrawField(renderer, pass ? 0x1D48 : 0x1D49) - && !psmDrawPointerVectorSize(renderer + 0x1D80)) + if (!psmMeshField(renderer, pass ? 0x1D48 : 0x1D49) + && !psmDrawPointerVectorSize(renderer, psmMeshRendererOffset(0x1D80))) return false; - if (!psmDrawField(renderer, 0x1D6C)) + if (!psmMeshField(renderer, 0x1D6C)) return false; - // [CHOSEN, not recovered] The "MeshParticles" profiler scope (static 10261718) is omitted, - // exactly as in the other recovered draw wrappers. + static dx9rend::QueueProfiler profiler(std::string("MeshParticles")); // PE 0x10261718, guard 0x10261980 + profiler.begin(); dx9rend::stateManagerPush(); if (!renderer[0x1D3C]) { - psmDrawField(renderer, 0x1CFC) = *view->getProjectionMatrixPtr(); + psmMeshField(renderer, 0x1CFC) = *view->getProjectionMatrixPtr(); const Mat4* projection = view->getProjectionMatrixPtr(); const Mat4* inverse = view->getInverseViewMatrixPtr(); - psmDrawField(renderer, 0x1CBC).fullMult(*inverse, *projection); + psmMeshField(renderer, 0x1CBC).fullMult(*inverse, *projection); renderer[0x1D3C] = 1; } // `mov bl, 1` precedes the group loops and each result is OR-ed in: the active branch @@ -434,9 +511,9 @@ static bool psmDrawMeshParticleRenderer(unsigned char* renderer, dx9rend::IRende { if (renderer[0x1D49]) { - for (unsigned int i = 0; i < psmDrawField(renderer, 0x1810); ++i) + for (unsigned int i = 0; i < psmMeshField(renderer, 0x1810); ++i) drawn = psmDrawMeshParticleGroup(renderer, view, - psmDrawField(renderer, 0x1D4C), i, renderer + 0xC08) || drawn; + psmMeshField(renderer, 0x1D4C), i, psmMeshGroups(renderer, 0xC08)) || drawn; renderer[0x1D49] = 0; } } @@ -444,27 +521,31 @@ static bool psmDrawMeshParticleRenderer(unsigned char* renderer, dx9rend::IRende { // The pass=true arm does NOT retest +0x1D48 here (the prologue may have been satisfied // by the retained list alone); it walks every group-0 record and then clears the flag. - for (unsigned int i = 0; i < psmDrawField(renderer, 0x180C); ++i) + for (unsigned int i = 0; i < psmMeshField(renderer, 0x180C); ++i) drawn = psmDrawMeshParticleGroup(renderer, view, - psmDrawField(renderer, 0x1D4C), i, renderer + 8) || drawn; + psmMeshField(renderer, 0x1D4C), i, psmMeshGroups(renderer, 8)) || drawn; renderer[0x1D48] = 0; } dx9rend::stateManagerPop(); + dx9rend::QueueProfiler::end(); return drawn; } // The extra draw uses the retained list independently of // either sorted-group count/flag. Empty and disabled exits materialize false in AL. +// PE 0x101753E0 static bool psmDrawMeshParticleExtras(unsigned char* renderer, bool pass) { - if (!psmDrawPointerVectorSize(renderer + 0x1D80) - || !psmDrawField(renderer, 0x1D6C)) + if (!psmDrawPointerVectorSize(renderer, psmMeshRendererOffset(0x1D80)) + || !psmMeshField(renderer, 0x1D6C)) return false; - // [CHOSEN, not recovered] The second "MeshParticles" profiler scope (static 102614A8) is - // omitted like the others. + // A second "MeshParticles" profiler of its own, distinct from the mesh renderer's. + static dx9rend::QueueProfiler profiler(std::string("MeshParticles")); // PE 0x102614A8, guard 0x10261710 + profiler.begin(); dx9rend::stateManagerPush(); psmBindMeshParticleParameters(renderer); psmDrawMeshParticleExtraList(renderer, pass); dx9rend::stateManagerPop(); + dx9rend::QueueProfiler::end(); return true; } diff --git a/Code/BF2/Geom/ParticleSystem/ParticleRendererGpu.inl b/Code/BF2/Geom/ParticleSystem/ParticleRendererGpu.inl index 60db05411..42c965d62 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleRendererGpu.inl +++ b/Code/BF2/Geom/ParticleSystem/ParticleRendererGpu.inl @@ -2,27 +2,32 @@ // Complete BF2 1.50 RendDX9 instruction streams: 10171F60, 1016F740, 1016FAE0, // Dedicated ELF has no rendering counterpart. +// The shader parameters each renderer keeps, by retail offset. static dx9rend::ParameterOwner* psmParticleParameter(unsigned char* renderer, unsigned int offset) { - return psmDrawField(renderer, offset); + return psmSpriteField(renderer, offset); +} +static dx9rend::ParameterOwner* psmNsaParameter(unsigned char* renderer, unsigned int offset) +{ + return psmNsaField(renderer, offset); +} +static dx9rend::ParameterOwner* psmTrailParameter(unsigned char* renderer, unsigned int offset) +{ + return psmTrailField(renderer, offset); } -// Error-only dependency, matching the existing constructor diagnostic boundary. -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: particle-draw-debug-dispatch] -// The retail renderer Debug type-6 dispatcher is not yet available here. Never silently -// continue a failed GPU lock or the retail inconsistent-sort-count assertion. +// The caller retains the return or continuation following the diagnostic in the PE. static void psmParticleDrawDebug(unsigned int line, const char* message) { - std::fprintf(stderr, "[FRONTIER] dice::hfe::geom::ParticleSystemRenderer::draw " - "(Debug type 6, ParticleSystemRenderer.cpp:%u: %s) reached\n", line, message); - std::fflush(stderr); - std::abort(); + ::renddx9abi::Debug(DebugTypeError, + "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\ParticleSystem\\ParticleSystemRenderer.cpp", + line, "") << message; } static void* psmParticleDescriptorTexture(unsigned char* descriptor) { - unsigned char* region = psmDrawField(descriptor, 0x260); - return region ? psmDrawField(region, 0x10) : psmDrawField(descriptor, 0x25C); + unsigned char* region = psmDescriptor0(descriptor, 0x260); + return region ? static_cast(reinterpret_cast(region)->page) : psmDescriptor0(descriptor, 0x25C); } // PE 10172130 copies seven Vec4 values; these are plain descriptor shader parameters. @@ -32,6 +37,7 @@ static void psmParticleCopyParameters(unsigned char* destination, unsigned char* psmDrawField(destination, i * 4) = psmDrawField(source, i * 4); } +// PE 0x1016F740 static void psmParticleBlend(bool additive) { ParticleSystemManager* manager = reinterpret_cast(g_ParticleSystemManager); @@ -49,6 +55,21 @@ static void psmParticleBlend(bool additive) } } +// [INFERRED] Private names/placement for the shared lookup and fallback operations. +// PE 0x100D4CE0 +static IParticleSystemTemplate* psmLookupParticleTemplate(unsigned short id) +{ + return g_templatesById[id]; +} + +// PE 0x100F1490 +static dx9rend::EngineTexture* psmBaseHemiTexture() +{ + HemiMap* const map=g_HemiMapManager->getBaseHemiMap(); + return map ? map->texture : 0; +} + +// PE 0x10171F60 static void psmBindParticleParameters(unsigned char* renderer) { psmParticleParameter(renderer, 0x1DD4)->setValue(renderer + 0x1C58, 0); @@ -63,15 +84,14 @@ static void psmBindParticleParameters(unsigned char* renderer) else { // PE 100F1490 asks HemiMapManager again, despite the preceding null result. - HemiMap* fallback = g_HemiMapManager->getBaseHemiMap(); - psmParticleParameter(renderer, 0x1DE4)->setValue(fallback ? fallback->texture : 0, 0); + dx9rend::EngineTexture* const fallback=psmBaseHemiTexture(); + psmParticleParameter(renderer, 0x1DE4)->setValue(fallback, 0); } - unsigned char* constants = static_cast(dx9rend::g_raShaderConstants); - psmParticleParameter(renderer, 0x1DF0)->setValue(constants + 0xA8, 0); - psmParticleParameter(renderer, 0x1DF4)->setValue(constants + 0xBC, 0); - psmParticleParameter(renderer, 0x1E00)->setValue(constants + 0x10C, 0); - psmParticleParameter(renderer, 0x1E04)->setValue(constants + 0xF8, 0); - psmParticleParameter(renderer, 0x1E08)->setValue(constants + 0x1D8, 0); + psmParticleParameter(renderer, 0x1DF0)->setValue(dx9rend::raShaderConstantsAt(0xA8), 0); + psmParticleParameter(renderer, 0x1DF4)->setValue(dx9rend::raShaderConstantsAt(0xBC), 0); + psmParticleParameter(renderer, 0x1E00)->setValue(dx9rend::raShaderConstantsAt(0x10C), 0); + psmParticleParameter(renderer, 0x1E04)->setValue(dx9rend::raShaderConstantsAt(0xF8), 0); + psmParticleParameter(renderer, 0x1E08)->setValue(dx9rend::raShaderConstantsAt(0x1D8), 0); psmParticleParameter(renderer, 0x1DF8)->setValue(&g_LightManager->getEffectSunColor(), 0); psmParticleParameter(renderer, 0x1DFC)->setValue(&g_LightManager->getEffectShadowColor(), 0); ParticleSystemManager* manager = reinterpret_cast(g_ParticleSystemManager); @@ -81,53 +101,54 @@ static void psmBindParticleParameters(unsigned char* renderer) const Vec3 color = { scale, scale, scale }; psmParticleParameter(renderer, 0x1DF8)->setValue(&color, 0); } - dx9rend::vertexDeclarationBind(psmDrawField(renderer, 0x1E0C)); - dx9rend::vertexBufferBindStream(psmDrawField(renderer, 0x1DCC), 0); + dx9rend::vertexDeclarationBind(psmSpriteField(renderer, 0x1E0C)); + dx9rend::vertexBufferBindStream(psmSpriteField(renderer, 0x1DCC), 0); } // PE 1016FAE0 batches at most ten descriptor IDs. The sorted variant deliberately // passes count=0 to setValue; the additive variant below passes the actual count. static unsigned int psmBatchSortedParticles(unsigned char* renderer, unsigned int begin, unsigned int end) { - unsigned char* mapping = psmDrawField(renderer, 0x1DC0); + unsigned char* mapping = psmSpriteField(renderer, 0x1DC0); ::memset(mapping, 0xFF, 0x800); - unsigned int& count = psmDrawField(renderer, 0x1DC4); + unsigned int& count = psmSpriteField(renderer, 0x1DC4); count = 0; unsigned int i = begin; for (; i < end; ++i) { - unsigned char* particle = psmDrawField(renderer, 0x18)[psmDrawField(renderer, 4) - i]; + unsigned char* particle = psmSpriteField(renderer, 0x18)[psmSpriteField(renderer, 4) - i]; unsigned short id = psmDrawField(particle, 4); if (mapping[id] != 0xFF) continue; if (count >= 10) break; mapping[id] = static_cast(count); // PE 100D4CE0 is map::operator[], including insertion on a missing ID. - unsigned char* descriptor = reinterpret_cast(g_templatesById[id]); - psmParticleCopyParameters(psmDrawField(renderer, 0x1DC8) + count * 112, descriptor + 0x13C); + unsigned char* descriptor = reinterpret_cast(psmLookupParticleTemplate(id)); + psmParticleCopyParameters(psmSpriteField(renderer, 0x1DC8) + count * 112, descriptor + 0x13C); ++count; } - psmParticleParameter(renderer, 0x1DE8)->setValue(psmDrawField(renderer, 0x1DC8), 0); + psmParticleParameter(renderer, 0x1DE8)->setValue(psmSpriteField(renderer, 0x1DC8), 0); return i; } +// PE 0x1016FBA0 static unsigned int psmBatchAdditiveParticles(unsigned char* renderer, unsigned int begin, - unsigned int end, unsigned char* groups, unsigned int& particles) + unsigned int end, PsmDrawGroup* groups, unsigned int& particles) { particles = 0; - unsigned char* mapping = psmDrawField(renderer, 0x1DC0); + unsigned char* mapping = psmSpriteField(renderer, 0x1DC0); ::memset(mapping, 0xFF, 0x800); - unsigned int& count = psmDrawField(renderer, 0x1DC4); + unsigned int& count = psmSpriteField(renderer, 0x1DC4); count = 0; - unsigned char* initial = psmDrawField(groups + begin * 12, 0); - void* texture = psmParticleDescriptorTexture(psmDrawField(initial, 0x2C)); + unsigned char* initial = groups[begin].instance; + void* texture = psmParticleDescriptorTexture(psmInstanceA(initial, 0x2C)); unsigned int i = begin; for (; i < end; ++i) { - unsigned char* group = groups + i * 12; - if (!psmDrawField(group, 8)) continue; - unsigned char* instance = psmDrawField(group, 0); - unsigned char* descriptor = psmDrawField(instance, 0x2C); - const unsigned short id = psmDrawField(descriptor, 4); + PsmDrawGroup* const group = groups + i; + if (!group->count) continue; + unsigned char* instance = group->instance; + unsigned char* descriptor = psmInstanceA(instance, 0x2C); + const unsigned short id = psmDescriptor0(descriptor, 4); if (id >= 0x800) psmParticleDrawDebug(404, "Too Many templates"); if (psmParticleDescriptorTexture(descriptor) != texture) break; texture = psmParticleDescriptorTexture(descriptor); @@ -135,13 +156,13 @@ static unsigned int psmBatchAdditiveParticles(unsigned char* renderer, unsigned { if (count >= 10) break; mapping[id] = static_cast(count); - psmParticleCopyParameters(psmDrawField(renderer, 0x1DC8) + count * 112, descriptor + 0x13C); + psmParticleCopyParameters(psmSpriteField(renderer, 0x1DC8) + count * 112, descriptor + 0x13C); ++count; } - particles += psmDrawField(group, 8); + particles += group->count; } if (count) - psmParticleParameter(renderer, 0x1DE8)->setValue(psmDrawField(renderer, 0x1DC8), count); + psmParticleParameter(renderer, 0x1DE8)->setValue(psmSpriteField(renderer, 0x1DC8), count); return i; } @@ -152,7 +173,7 @@ static void psmWriteParticleVertices(unsigned char* renderer, unsigned char* par float minimumSize = psmDrawField(particle, 8); if (psmDrawField(particle, 0xC) < minimumSize) minimumSize = psmDrawField(particle, 0xC); const unsigned short id = psmDrawField(particle, 4); - const float descriptorIndex = static_cast(static_cast(psmDrawField(renderer, 0x1DC0)[id])); + const float descriptorIndex = static_cast(static_cast(psmSpriteField(renderer, 0x1DC0)[id])); const int corners[6][2] = { {-1,1}, {1,1}, {-1,-1}, {-1,-1}, {1,1}, {1,-1} }; for (unsigned int i = 0; i < 6; ++i) { @@ -177,61 +198,62 @@ static void psmParticleTechnique(unsigned char* renderer, bool additive) static const char* const additiveNames[] = { "ParticleShowFill", "AdditiveLow", "AdditiveHigh", "AdditiveHigh" }; if (manager->m_shaderQuality <= 3) { - const vc71::string technique((additive ? additiveNames : sortedNames)[manager->m_shaderQuality]); - dx9rend::effectSetTechniqueByName(psmDrawField(renderer, 0x1DD0), technique); + const std::string technique((additive ? additiveNames : sortedNames)[manager->m_shaderQuality]); + dx9rend::effectSetTechniqueByName(psmSpriteField(renderer, 0x1DD0), technique); } } static unsigned char* psmLockParticleVertices(unsigned char* renderer, unsigned int count, bool first) { - unsigned int& offset = psmDrawField(renderer, 0x5E14); + unsigned int& offset = psmSpriteField(renderer, 0x5E14); unsigned int flags = first && !offset ? 10240 : 6144; - if (count + offset >= psmDrawField(renderer, 0x1DB8)) + if (count + offset >= psmSpriteField(renderer, 0x1DB8)) { offset = 0; flags = 10240; } - return static_cast(dx9rend::vertexBufferLock(psmDrawField(renderer, 0x1DCC), offset, count, flags)); + return static_cast(dx9rend::vertexBufferLock(psmSpriteField(renderer, 0x1DCC), offset, count, flags)); } static void psmSubmitParticleVertices(unsigned char* renderer, unsigned int vertices) { - dx9rend::rendererDrawPrimitive(vertices / 3, 4, psmDrawField(renderer, 0x5E14)); - psmDrawField(renderer, 0x5E14) += vertices; + dx9rend::rendererDrawPrimitive(vertices / 3, 4, psmSpriteField(renderer, 0x5E14)); + psmSpriteField(renderer, 0x5E14) += vertices; } -static void psmCountParticleDraw(unsigned int offset) +// `counter` indexes the manager's draw counters (retail +0x8C44 + 4 * counter). +static void psmCountParticleDraw(unsigned int counter) { // PE reloads the published manager after external buffer/shader calls. - ++psmDrawField(reinterpret_cast(g_ParticleSystemManager), offset); + ++reinterpret_cast(g_ParticleSystemManager)->m_drawCounters[counter]; } // Texture/state switches flush the current vertices. A batch-boundary // blend mismatch writes the OLD blend into the particle; this shipped quirk is intentional. static bool psmDrawSortedParticles(unsigned char* renderer, float target) { - unsigned int& remaining = psmDrawField(renderer, 0x1C38); + unsigned int& remaining = psmSpriteField(renderer, 0x1C38); if (!remaining) return false; - const int startIndex = psmDrawField(renderer, 4); - unsigned char** table = psmDrawField(renderer, 0x18); + const int startIndex = psmSpriteField(renderer, 4); + unsigned char** table = psmSpriteField(renderer, 0x18); unsigned char* firstParticle = table[startIndex]; unsigned short blend = psmDrawField(firstParticle, 0x90); bool additive = blend != 0; psmParticleBlend(additive); - void* texture = psmDrawField(firstParticle, 0x5C); + void* texture = psmRecordPointer(firstParticle, 0); psmParticleParameter(renderer, 0x1DEC)->setValue(texture, 0); const unsigned int count = remaining; unsigned int batchEnd = psmBatchSortedParticles(renderer, 0, count); psmParticleTechnique(renderer, false); - void* effect = psmDrawField(renderer, 0x1DD0); - void* buffer = psmDrawField(renderer, 0x1DCC); + void* effect = psmSpriteField(renderer, 0x1DD0); + void* buffer = psmSpriteField(renderer, 0x1DCC); dx9rend::effectBegin(effect); dx9rend::effectBeginPass(effect, 0); unsigned int vertices = 0; unsigned char* output = psmLockParticleVertices(renderer, batchEnd * 6, true); - if (!output) psmParticleDrawDebug(668, "Failed to lock"); - unsigned char* manager = reinterpret_cast(g_ParticleSystemManager); - const bool forceSorted = manager[0x8BA8] != 0; + if (!output) { psmParticleDrawDebug(668, "Failed to lock"); return false; } + ParticleSystemManager* manager = reinterpret_cast(g_ParticleSystemManager); + const bool forceSorted = manager->m_forceSortedParticleType != 0; // +0x8BA8 unsigned int done = 0; for (; done < count; ++done) { @@ -243,10 +265,10 @@ static bool psmDrawSortedParticles(unsigned char* renderer, float target) psmSubmitParticleVertices(renderer, vertices); vertices = 0; batchEnd = psmBatchSortedParticles(renderer, done, count); - if (psmDrawField(particle, 0x5C) != texture) + if (psmRecordPointer(particle, 0) != texture) { - psmParticleParameter(renderer, 0x1DEC)->setValue(psmDrawField(particle, 0x5C), 0); - texture = psmDrawField(particle, 0x5C); + psmParticleParameter(renderer, 0x1DEC)->setValue(psmRecordPointer(particle, 0), 0); + texture = psmRecordPointer(particle, 0); } if (psmDrawField(particle, 0x90) != blend) { @@ -254,10 +276,10 @@ static bool psmDrawSortedParticles(unsigned char* renderer, float target) psmParticleBlend(additive); } output = psmLockParticleVertices(renderer, (batchEnd - done) * 6, false); - if (!output) psmParticleDrawDebug(724, "Failed to lock vbuffer"); - psmCountParticleDraw(0x8C44); + if (!output) { psmParticleDrawDebug(724, "Failed to lock vbuffer"); return false; } + psmCountParticleDraw(0); // +0x8C44 } - const bool textureChanged = psmDrawField(particle, 0x5C) != texture; + const bool textureChanged = psmRecordPointer(particle, 0) != texture; const bool blendChanged = forceSorted && psmDrawField(particle, 0x90) != blend; if (textureChanged || blendChanged) { @@ -265,11 +287,11 @@ static bool psmDrawSortedParticles(unsigned char* renderer, float target) psmSubmitParticleVertices(renderer, vertices); vertices = 0; output = psmLockParticleVertices(renderer, (batchEnd - done) * 6, false); - if (!output) psmParticleDrawDebug(759, "Failed to lock vbuffer"); + if (!output) { psmParticleDrawDebug(759, "Failed to lock vbuffer"); return false; } if (textureChanged) { - psmParticleParameter(renderer, 0x1DEC)->setValue(psmDrawField(particle, 0x5C), 0); - texture = psmDrawField(particle, 0x5C); + psmParticleParameter(renderer, 0x1DEC)->setValue(psmRecordPointer(particle, 0), 0); + texture = psmRecordPointer(particle, 0); } if (blendChanged) { @@ -277,52 +299,60 @@ static bool psmDrawSortedParticles(unsigned char* renderer, float target) additive = blend != 0; psmParticleBlend(additive); } - psmCountParticleDraw(0x8C44); + psmCountParticleDraw(0); // +0x8C44 } psmWriteParticleVertices(renderer, particle, output + vertices * 64); vertices += 6; - ++psmDrawField(renderer, 0x1C2C); + ++psmSpriteField(renderer, 0x1C2C); --remaining; } dx9rend::vertexBufferUnlock(buffer); - psmCountParticleDraw(0x8C44); + psmCountParticleDraw(0); // +0x8C44 psmSubmitParticleVertices(renderer, vertices); - psmDrawField(renderer, 4) = startIndex - done; + psmSpriteField(renderer, 4) = startIndex - done; dx9rend::effectEnd(effect); - if (remaining) psmParticleDrawDebug(909, "m_particleSortCount != 0"); + // PE 0x101704ED. Suppressing this diagnostic still clears the inconsistent count. + if (remaining) + { + ::renddx9abi::Debug(DebugTypeError, + "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\ParticleSystem\\ParticleSystemRenderer.cpp", + 909, "") << "m_particleSortCount != 0 " << remaining; + remaining = 0; + } return true; } +// PE 0x101705F0 static bool psmDrawAdditiveParticles(unsigned char* renderer, unsigned int target, - unsigned int count, unsigned char* groups) + unsigned int count, PsmDrawGroup* groups) { unsigned int particles; unsigned int batchEnd = psmBatchAdditiveParticles(renderer, 0, count, groups, particles); if (!particles) return false; - unsigned char* instance = psmDrawField(groups, 0); - void* texture = psmParticleDescriptorTexture(psmDrawField(instance, 0x2C)); + unsigned char* instance = groups[0].instance; + void* texture = psmParticleDescriptorTexture(psmInstanceA(instance, 0x2C)); psmParticleParameter(renderer, 0x1DEC)->setValue(texture, 0); psmParticleBlend(true); psmParticleTechnique(renderer, true); - void* effect = psmDrawField(renderer, 0x1DD0); - void* buffer = psmDrawField(renderer, 0x1DCC); + void* effect = psmSpriteField(renderer, 0x1DD0); + void* buffer = psmSpriteField(renderer, 0x1DCC); dx9rend::effectBegin(effect); dx9rend::effectBeginPass(effect, 0); unsigned int vertices = 0; unsigned char* output = psmLockParticleVertices(renderer, particles * 6, true); - if (!output) psmParticleDrawDebug(973, "Failed to lock surface"); + if (!output) { psmParticleDrawDebug(973, "Failed to lock surface"); return false; } for (unsigned int i = 0; i < count; ++i) { - unsigned char* group = groups + i * 12; + PsmDrawGroup* const group = groups + i; if (i == batchEnd) { dx9rend::vertexBufferUnlock(buffer); - psmCountParticleDraw(0x8C4C); + psmCountParticleDraw(2); // +0x8C4C psmSubmitParticleVertices(renderer, vertices); vertices = 0; batchEnd = psmBatchAdditiveParticles(renderer, i, count, groups, particles); - instance = psmDrawField(group, 0); - unsigned char* descriptor = psmDrawField(instance, 0x2C); + instance = group->instance; + unsigned char* descriptor = psmInstanceA(instance, 0x2C); if (texture != psmParticleDescriptorTexture(descriptor)) { texture = psmParticleDescriptorTexture(descriptor); @@ -331,24 +361,24 @@ static bool psmDrawAdditiveParticles(unsigned char* renderer, unsigned int targe output = psmLockParticleVertices(renderer, particles * 6, false); if (!output) return false; // Retail has no Debug/effectEnd on this later failure. } - const int index = psmDrawField(group, 4); - const unsigned int available = psmDrawField(group, 8); + const int index = group->last; + const unsigned int available = group->count; unsigned int done = 0; for (; done < available; ++done) { - unsigned char* particle = psmDrawField(renderer, 0x1C)[index - done]; + unsigned char* particle = psmSpriteField(renderer, 0x1C)[index - done]; if (psmDrawField(particle, 0x14) < target) break; psmWriteParticleVertices(renderer, particle, output + vertices * 64); vertices += 6; - --psmDrawField(group, 8); - ++psmDrawField(renderer, 0x1C30); + --group->count; + ++psmSpriteField(renderer, 0x1C30); } - psmDrawField(group, 4) = index - done; + group->last = index - static_cast(done); } dx9rend::vertexBufferUnlock(buffer); if (vertices) { - psmCountParticleDraw(0x8C4C); + psmCountParticleDraw(2); // +0x8C4C psmSubmitParticleVertices(renderer, vertices); } dx9rend::effectEnd(effect); diff --git a/Code/BF2/Geom/ParticleSystem/ParticleRendererMesh.inl b/Code/BF2/Geom/ParticleSystem/ParticleRendererMesh.inl index cbbafc9e9..3fdfca430 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleRendererMesh.inl +++ b/Code/BF2/Geom/ParticleSystem/ParticleRendererMesh.inl @@ -1,6 +1,35 @@ // Draws mesh particles through retained MeshParticleMesh instances. // Included inside the manager's anonymous namespace after the shared draw helpers; // MeshParticleMesh headers must be included outside that namespace. +// PE 0x101748C0 +static void psmMeshSetDrawBoundingBox(unsigned char* renderer, unsigned char value) +{ + psmMeshField(renderer,0x1D6E)=value; +} + +// Mesh renderer leaf stores, unreachable in 1.50: no code or data references. The names are +// [CHOSEN, not recovered]: no instruction reads the fields through these setters. + +// PE 0x101748A0: byte store at +0x1D6D. +static void psmMeshSetFlag1D6D(unsigned char* renderer, unsigned char value) +{ + psmMeshField(renderer, 0x1D6D) = value; +} + +// PE 0x101748E0: byte store at +0x1D6F. +static void psmMeshSetFlag1D6F(unsigned char* renderer, unsigned char value) +{ + psmMeshField(renderer, 0x1D6F) = value; +} + +// PE 0x10174540: two dword stores at +0x1C34 and +0x1C38. The element type of the pair is +// [CHOSEN, not recovered]: the two stack arguments are stored unchanged and never read back. +static void psmMeshSetPair1C34(unsigned char* renderer, unsigned int first, unsigned int second) +{ + psmMeshField(renderer, 0x1C34) = first; + psmMeshField(renderer, 0x1C38) = second; +} + inline void meshParticleMeshSetAgeAndAlpha(unsigned char* mesh, float age, float alpha, unsigned int slot) { @@ -10,6 +39,11 @@ inline void meshParticleMeshDrawBatch(unsigned char* mesh, int technique, bool t { reinterpret_cast(mesh)->draw(technique, transparentPass); } +// Mesh +0x44 is the selected (lod, geom) record; its first word is the number of bone slots. +inline unsigned int meshParticleMeshLodPartCount(unsigned char* mesh) +{ + return reinterpret_cast(mesh)->m_lodRecord->partCount; +} template static Fn psmMeshGeometrySlot(void* mesh, unsigned int offset) @@ -18,26 +52,28 @@ static Fn psmMeshGeometrySlot(void* mesh, unsigned int offset) } // +0x38, PE 10145640 `mov eax,[ecx+84h]; retn` - the geometry template (IGeometry::getTemplate, -// the same slot StaticMesh names). Only 10175230 calls it, and discards the result. +// the same slot StaticMesh names). Only psmDrawMeshParticleExtraList calls it, and discards the result. static void* psmMeshGeometryGetTemplate(void* mesh) { - typedef void* (__fastcall *Fn)(void*, void*); - return psmMeshGeometrySlot(mesh, 0x38)(mesh, 0); + typedef void* (__thiscall *Fn)(void*); + return psmMeshGeometrySlot(mesh, 0x38)(mesh); } -// +0x4C, PE 101AFD80 `this[+38h][part] = transform`, `retn 8` - BundledMesh's -// setPartTransformation(const Mat4*, int) shape. The pointer is stored, not copied. +// +0x4C, MeshParticleMesh::setPartTransformation: `this[+38h][part] = transform`, `retn 8` - +// BundledMesh's setPartTransformation(const Mat4*, int) shape. The pointer is stored, not copied. static void psmMeshGeometrySetPartTransformation(void* mesh, const Mat4* transform, int part) { - typedef void (__fastcall *Fn)(void*, void*, const Mat4*, int); - psmMeshGeometrySlot(mesh, 0x4C)(mesh, 0, transform, part); + // The slot body is PE 101AFD80. + typedef void (__thiscall *Fn)(void*, const Mat4*, int); + psmMeshGeometrySlot(mesh, 0x4C)(mesh, transform, part); } -// +0x50, PE 101AFC20 `this->vslot4C(transform, 0)`, `retn 4` - setGeometryTransformation. +// +0x50, MeshParticleMesh::setGeometryTransformation: `this->vslot4C(transform, 0)`, `retn 4`. static void psmMeshGeometrySetTransformation(void* mesh, const Mat4* transform) { - typedef void (__fastcall *Fn)(void*, void*, const Mat4*); - psmMeshGeometrySlot(mesh, 0x50)(mesh, 0, transform); + // The slot body is PE 101AFC20. + typedef void (__thiscall *Fn)(void*, const Mat4*); + psmMeshGeometrySlot(mesh, 0x50)(mesh, transform); } // The renderer calls ShaderParameter through its vtable (`call [reg+18h]`, +24h, +28h). Upcast so @@ -48,17 +84,26 @@ static dx9rend::ParameterOwner* psmMeshParameter(dx9rend::ShaderParameter* param } -// Math helpers private to the mesh particle transform. None of these PE bodies exists in the tree. +// Math helpers private to the mesh particle transform. // cross(a, b). Register-passed (ecx = result, edx = a, [esp] = b; ltcg). Each // component is x87: two exact products, one double subtraction, one float rounding. +// PE 0x1007B030 static Vec3 psmMeshCross(const Vec3& a, const Vec3& b) { Vec3 result; +#if defined(__APPLE__) + // [CHOSEN, not recovered] Preserve live x87 products and subtraction until each float store. + using bf2x87::wide; + result.x=static_cast(wide(b.z)*wide(a.y)-wide(b.y)*wide(a.z)); + result.y=static_cast(wide(b.x)*wide(a.z)-wide(b.z)*wide(a.x)); + result.z=static_cast(wide(b.y)*wide(a.x)-wide(b.x)*wide(a.y)); +#else result.x = static_cast(static_cast(b.z) * a.y - static_cast(b.y) * a.z); result.y = static_cast(static_cast(b.x) * a.z - static_cast(b.z) * a.x); result.z = static_cast(static_cast(b.y) * a.x - static_cast(b.x) * a.y); +#endif return result; } @@ -72,6 +117,7 @@ static void psmMeshSetRows(Mat4& matrix, const Vec3& row0, const Vec3& row1, con matrix.m[12] = row3.x; matrix.m[13] = row3.y; matrix.m[14] = row3.z; matrix.m[15] = 1.0f; } +// PE 0x10175800 // the four-row constructor - all sixteen floats zeroed, then 101744A0. static void psmMeshConstructFromRows(Mat4& matrix, const Vec3& row0, const Vec3& row1, const Vec3& row2, const Vec3& row3) @@ -95,26 +141,27 @@ static void psmMeshScaleColumns(Mat4& matrix, const Vec3& scale) matrix.m[10] = matrix.m[10] * scale.z; } -// PE 100794D0: `*this *= rhs` - copy-construct (10030DD0) then the affine product 10077C50, which -// this tree already recovers as Mat4::mult (the particle instances use it for 10077C50 too). +// PE 100794D0: `*this *= rhs` - copy-construct (10030DD0) then the affine product 10077C50 +// (the RendDX9 copy, rendmath::mult; the particle instances use it for 10077C50 too). static void psmMeshMultiplyInPlace(Mat4& matrix, const Mat4& rhs) { const Mat4 copy = matrix; - matrix.mult(copy, rhs); + rendmath::mult(matrix, copy, rhs); } // Four stable byte-radix passes over the +0xBC squared-distance bits, buckets at // renderer +0x1814, chains through the particle's first word; identical in shape to 1016F7F0. +// PE 0x10174900 static void psmSortMeshParticles(unsigned char* renderer, unsigned char** table, unsigned int count) { - unsigned char** buckets = reinterpret_cast(renderer + 0x1814); + unsigned char** buckets = &psmMeshField(renderer, 0x1814); for (unsigned int byte = 0; byte < 4; ++byte) { - for (int i = static_cast(count) - 1; i >= 0; --i) + for (int i = static_cast(count - 1u); i >= 0; --i) { unsigned char* particle = table[i]; const unsigned int key = particle[0xBC + byte]; - psmDrawField(particle, 0) = buckets[key]; + psmRecordLink(particle, 1) = buckets[key]; buckets[key] = particle; } unsigned int output = 0; @@ -125,7 +172,7 @@ static void psmSortMeshParticles(unsigned char* renderer, unsigned char** table, while (particle) { table[output++] = particle; - particle = psmDrawField(particle, 0); + particle = static_cast(psmRecordLink(particle, 1)); } } } @@ -143,16 +190,16 @@ static void psmUpdateMeshParticleDrawState(unsigned char* renderer, unsigned cha if (!(flags & 0x80)) return; // `test al,al; jns`: bit 7 of the low byte is the dirty flag flags &= ~0x80u; const double age = psmDrawField(particle, 0x5C); - const float rate = static_cast(age * age * psmDrawField(descriptor, 0x100) - + age * psmDrawField(descriptor, 0x104) - + age * age * age * psmDrawField(descriptor, 0xFC) - + psmDrawField(descriptor, 0x108)); - const float step = psmParticleClamp(rate, 0.0f, 1.0f) * psmDrawField(renderer, 0x1C20); + const float rate = static_cast(age * age * psmDescriptor1(descriptor, 0x100) + + age * psmDescriptor1(descriptor, 0x104) + + age * age * age * psmDescriptor1(descriptor, 0xFC) + + psmDescriptor1(descriptor, 0x108)); + const float step = psmParticleClamp(rate, 0.0f, 1.0f) * psmMeshField(renderer, 0x1C20); Mat4& matrix = psmDrawField(particle, 4); const Vec3& position = psmDrawField(particle, 0x50); // 101758C5/101758E1: `fucompp; test ah,44h; jp` - a NaN directional scale takes the velocity arm. - if (!descriptor[0x1F0] && psmDrawField(descriptor, 0x1EC) == 0.0f) + if (!descriptor[0x1F0] && psmDescriptor1(descriptor, 0x1EC) == 0.0f) { Vec3& rotation = psmDrawField(particle, 0xA8); const Vec3& rotationSpeed = psmDrawField(particle, 0x9C); @@ -162,10 +209,10 @@ static void psmUpdateMeshParticleDrawState(unsigned char* renderer, unsigned cha rotation.x = static_cast(static_cast(step) * rotationSpeed.x + rotation.x); rotation.y = static_cast(static_cast(step) * rotationSpeed.y + rotation.y); rotation.z = static_cast(static_cast(stepZ) + rotation.z); - // PE 10078730 is RendDX9's copy of dice::hfe::setRotationZXY (Math/Mat4.cpp): three - // fsincos rotations, Z/X/Y by the non-zero-angle mask, only the nine 3x3 terms written. + // PE 10078730 (rendmath::setRotationZXY, RendDX9's copy): three fsincos rotations, + // Z/X/Y by the non-zero-angle mask, only the nine 3x3 terms written. // So m[3]/m[7]/m[11]/m[15] keep whatever the pool record last held. Kept. - setRotationZXY(matrix, -rotation.z, -rotation.y, -rotation.x); + rendmath::setRotationZXY(matrix, -rotation.z, -rotation.y, -rotation.x); matrix.m[12] = position.x; matrix.m[13] = position.y; matrix.m[14] = position.z; @@ -216,10 +263,10 @@ static void psmUpdateMeshParticleDrawState(unsigned char* renderer, unsigned cha up = psmMeshCross(direction, right); } // `test ah,41h; jnz`: only a strictly positive directional scale stretches (NaN no). - if (psmDrawField(descriptor, 0x1EC) > 0.0f) + if (psmDescriptor1(descriptor, 0x1EC) > 0.0f) { - matrix = Mat4::getIdentity(); - const Vec3 stretch = { 1.0f, 1.0f, lengthRounded * psmDrawField(descriptor, 0x1EC) }; + rendmath::makeIdentity(matrix); // PE 0x10027810, call 0x10175B3E + const Vec3 stretch = { 1.0f, 1.0f, lengthRounded * psmDescriptor1(descriptor, 0x1EC) }; psmMeshScaleColumns(matrix, stretch); Mat4 basis; psmMeshConstructFromRows(basis, right, up, direction, position); @@ -233,19 +280,19 @@ static void psmUpdateMeshParticleDrawState(unsigned char* renderer, unsigned cha // the size graph scales the whole 3x3 part uniformly, then the transparency graph // multiplies the alpha the collector faded. const double tailAge = psmDrawField(particle, 0x5C); - const float sizeRate = static_cast(tailAge * tailAge * psmDrawField(descriptor, 0x150) - + tailAge * psmDrawField(descriptor, 0x154) - + tailAge * tailAge * tailAge * psmDrawField(descriptor, 0x14C) - + psmDrawField(descriptor, 0x158)); + const float sizeRate = static_cast(tailAge * tailAge * psmDescriptor1(descriptor, 0x150) + + tailAge * psmDescriptor1(descriptor, 0x154) + + tailAge * tailAge * tailAge * psmDescriptor1(descriptor, 0x14C) + + psmDescriptor1(descriptor, 0x158)); const float size = static_cast( - static_cast(psmParticleClamp(sizeRate, 0.0f, 1.0f)) * psmDrawField(descriptor, 0x1E8) + static_cast(psmParticleClamp(sizeRate, 0.0f, 1.0f)) * psmDescriptor1(descriptor, 0x1E8) + psmDrawField(particle, 0x68)); const Vec3 uniform = { size, size, size }; psmMeshScaleColumns(matrix, uniform); - const float alphaRate = static_cast(tailAge * tailAge * psmDrawField(descriptor, 0x140) - + tailAge * psmDrawField(descriptor, 0x144) - + tailAge * tailAge * tailAge * psmDrawField(descriptor, 0x13C) - + psmDrawField(descriptor, 0x148)); + const float alphaRate = static_cast(tailAge * tailAge * psmDescriptor1(descriptor, 0x140) + + tailAge * psmDescriptor1(descriptor, 0x144) + + tailAge * tailAge * tailAge * psmDescriptor1(descriptor, 0x13C) + + psmDescriptor1(descriptor, 0x148)); psmDrawField(particle, 0x6C) = psmParticleClamp(alphaRate, 0.0f, 1.0f) * psmDrawField(particle, 0x6C); } @@ -258,31 +305,31 @@ static void psmCollectMeshParticles(unsigned char* renderer, dx9rend::IRenderVie view->getViewMatrixPtr(); // discarded const float nearPlane = view->getNearPlane(); view->getViewMatrixPtr(); // discarded (getViewport below likewise) - const unsigned int count = psmDrawField(instance, 0x28); - if (psmDrawField(descriptor, 8) == -1) + const unsigned int count = psmInstanceB(instance, 0x28); + if (psmDescriptor1(descriptor, 8) == -1) { // renderer +0x1C38 is tested and both arms store the same counter. The retail // constructor initialises neither +0x1C38 nor the counter +0x1D44 (the rebuild's // zero-filled manager makes both 0). Kept as the dead test it is. - if (psmDrawField(renderer, 0x1C38)) - psmDrawField(descriptor, 8) = psmDrawField(renderer, 0x1D44); + if (psmMeshField(renderer, 0x1C38)) + psmDescriptor1(descriptor, 8) = psmMeshField(renderer, 0x1D44); else - psmDrawField(descriptor, 8) = psmDrawField(renderer, 0x1D44); - ++psmDrawField(renderer, 0x1D44); + psmDescriptor1(descriptor, 8) = psmMeshField(renderer, 0x1D44); + ++psmMeshField(renderer, 0x1D44); } view->getViewport(); // discarded ParticleSystemManager* manager = reinterpret_cast(g_ParticleSystemManager); - const unsigned int lod = psmDrawField(descriptor, 0x68); + const unsigned int lod = psmDescriptor1(descriptor, 0x68); const float farDistance = manager->m_farDistances[lod]; const float inverseFarRange = manager->m_inverseFarRanges[lod]; unsigned int accepted = 0; for (unsigned int i = 0; i < count; ++i) { - unsigned char* particle = psmDrawField(instance, 0x14)[i]; - const double depth = static_cast(psmDrawField(particle, 0x54)) * psmDrawField(renderer, 0x1C28) - + static_cast(psmDrawField(particle, 0x58)) * psmDrawField(renderer, 0x1C2C) - + static_cast(psmDrawField(particle, 0x50)) * psmDrawField(renderer, 0x1C24) - + psmDrawField(renderer, 0x1C30); + unsigned char* particle = psmInstanceB(instance, 0x14)[i]; + const double depth = static_cast(psmDrawField(particle, 0x54)) * psmMeshField(renderer, 0x1C28) + + static_cast(psmDrawField(particle, 0x58)) * psmMeshField(renderer, 0x1C2C) + + static_cast(psmDrawField(particle, 0x50)) * psmMeshField(renderer, 0x1C24) + + psmMeshField(renderer, 0x1C30); const float roundedDepth = static_cast(depth); // The near test compares the unrounded depth (`fst` keeps st0), the far fade below uses // the rounded copy. `test ah,5; jnp` lets NaN through. @@ -295,7 +342,7 @@ static void psmCollectMeshParticles(unsigned char* renderer, dx9rend::IRenderVie if (fade > 1) fade = 1; alpha = static_cast((1 - fade) * (1 - fade) * psmDrawField(particle, 0x70)); } - if (alpha < psmDrawField(descriptor, 0xC4)) continue; // alpha cull + if (alpha < psmDescriptor1(descriptor, 0xC4)) continue; // alpha cull const Mat4* camera = view->getViewMatrixPtr(); const float x = static_cast(static_cast(camera->m[12]) - psmDrawField(particle, 0x50)); const double y = static_cast(camera->m[13]) - psmDrawField(particle, 0x54); @@ -303,25 +350,25 @@ static void psmCollectMeshParticles(unsigned char* renderer, dx9rend::IRenderVie psmDrawField(particle, 0xBC) = static_cast(z * z + y * y + static_cast(x) * x); psmUpdateMeshParticleDrawState(renderer, particle, descriptor, instance, view); // The template id is written after the draw-state update, unlike the sprite collectors. - psmDrawField(particle, 0x64) = psmDrawField(descriptor, 4); - psmDrawField(renderer, 4)[psmDrawField(renderer, 0x1808) + accepted] = particle; + psmDrawField(particle, 0x64) = psmDescriptor1(descriptor, 4); + psmMeshField(renderer, 4)[psmMeshField(renderer, 0x1808) + accepted] = particle; ++accepted; } if (!accepted) return; // Draw order 0 -> group 0 at +8 (drawn by the pass=true draw); anything else -> group 1 at // +0xC08 (drawn by the pass=false draw). A full group (256) returns without claiming the // table slots it just wrote; those particles' dirty bits are already consumed. Kept. - const bool second = psmDrawField(descriptor, 0x94) != 0; - unsigned int& groupCount = psmDrawField(renderer, second ? 0x1810 : 0x180C); + const bool second = psmDescriptor1(descriptor, 0x94) != 0; + unsigned int& groupCount = psmMeshField(renderer, second ? 0x1810 : 0x180C); if (groupCount >= 256) return; - unsigned char* group = renderer + (second ? 0xC08 : 8) + 12 * groupCount; - psmDrawField(group, 0) = instance; - psmDrawField(group, 4) = psmDrawField(renderer, 0x1808) + accepted - 1; - psmDrawField(group, 8) = accepted; + PsmDrawGroup* const group = psmMeshGroups(renderer, second ? 0xC08 : 8) + groupCount; + group->instance = instance; + group->last = static_cast(psmMeshField(renderer, 0x1808) + accepted - 1); + group->count = accepted; ++groupCount; psmSortMeshParticles(renderer, - psmDrawField(renderer, 4) + psmDrawField(renderer, 0x1808), accepted); - psmDrawField(renderer, 0x1808) += accepted; + psmMeshField(renderer, 4) + psmMeshField(renderer, 0x1808), accepted); + psmMeshField(renderer, 0x1808) += accepted; } // PE 10175025..10175086, the group-overflow arm of 10174DA0. byte_1023A29C is a process-wide @@ -333,10 +380,10 @@ static void psmNoteMeshGroupOverflow(unsigned char* renderer) static bool s_reportGroupOverflow = true; // [INFERRED] name, PE .data 1023A29C = 1 if (!s_reportGroupOverflow) return; s_reportGroupOverflow = false; - for (unsigned int i = 0; i < psmDrawField(renderer, 0x180C); ++i) - psmDrawField(renderer, 8 + 12 * i)->getTemplate(); - for (unsigned int i = 0; i < psmDrawField(renderer, 0x1810); ++i) - psmDrawField(renderer, 0xC08 + 12 * i)->getTemplate(); + for (unsigned int i = 0; i < psmMeshField(renderer, 0x180C); ++i) + psmMeshField(renderer, 8 + 12 * i)->getTemplate(); + for (unsigned int i = 0; i < psmMeshField(renderer, 0x1810); ++i) + psmMeshField(renderer, 0xC08 + 12 * i)->getTemplate(); } // PE 10175660 (402 B). Per-frame MeshParticleMesh effect state. Unlike the sprite renderers there @@ -351,38 +398,35 @@ static void psmBindMeshParticleParameters(unsigned char* renderer) if (map) { { - const vc71::string name("HemiMapInfo"); + const std::string name("HemiMapInfo"); dx9rend::ParameterOwner* parameter = psmMeshParameter( dx9rend::effectGetShaderParameterBorrowedTyped(g_meshParticleMeshEffectState.effect, name)); const HemiMapInfo& info = g_HemiMapManager->getHemiMapInfo(map); parameter->setValue(&info, 0); } { - const vc71::string name("HemiShadowAltitude"); + const std::string name("HemiShadowAltitude"); psmMeshParameter(dx9rend::effectGetShaderParameterBorrowedTyped(g_meshParticleMeshEffectState.effect, name)) ->setFloat(map->falloff); } { - const vc71::string name("Texture1"); + const std::string name("Texture1"); psmMeshParameter(dx9rend::effectGetShaderParameterBorrowedTyped(g_meshParticleMeshEffectState.effect, name)) ->setValue(map->texture, 0); } } else { - const vc71::string name("Texture1"); + const std::string name("Texture1"); dx9rend::ParameterOwner* parameter = psmMeshParameter( dx9rend::effectGetShaderParameterBorrowedTyped(g_meshParticleMeshEffectState.effect, name)); // PE 100F1490 rereads the owner despite the null result above (as in the siblings). - HemiMap* fallback = g_HemiMapManager->getBaseHemiMap(); - parameter->setValue(fallback ? fallback->texture : 0, 0); + parameter->setValue(psmBaseHemiTexture(), 0); } // These four statics are dereferenced without a null test (only WorldViewProjection above // and the three colour words in the draws are tested). Shipped. - unsigned char* constants = static_cast(dx9rend::g_raShaderConstants); - psmMeshParameter(g_meshParticleMeshEffectState.fogRange)->setValue(constants + 0xA8, 0); - constants = static_cast(dx9rend::g_raShaderConstants); - psmMeshParameter(g_meshParticleMeshEffectState.fogColor)->setValue(constants + 0xBC, 0); + psmMeshParameter(g_meshParticleMeshEffectState.fogRange)->setValue(dx9rend::raShaderConstantsAt(0xA8), 0); + psmMeshParameter(g_meshParticleMeshEffectState.fogColor)->setValue(dx9rend::raShaderConstantsAt(0xBC), 0); { const Vec3& sun = g_LightManager->getEffectSunColor(); psmMeshParameter(g_meshParticleMeshEffectState.effectSunColor)->setValue(&sun, 0); @@ -397,21 +441,21 @@ static void psmBindMeshParticleParameters(unsigned char* renderer) // MeshParticleMesh instance, filling its bone slots from the top down and flushing a batch // (drawBatch) every time slot 0 is reached. Returns false only for an empty group. static bool psmDrawMeshParticleGroup(unsigned char* renderer, dx9rend::IRenderView* view, - unsigned int target, unsigned int groupIndex, unsigned char* groups) + unsigned int target, unsigned int groupIndex, PsmDrawGroup* groups) { - unsigned char* const group = groups + 12 * groupIndex; - if (!psmDrawField(group, 8)) return false; - const int lastIndex = psmDrawField(group, 4); + PsmDrawGroup* const group = groups + groupIndex; + if (!group->count) return false; + const int lastIndex = group->last; view->getViewport(); // discarded - IParticleSystemInstance* const instance = psmDrawField(group, 0); - const unsigned int count = psmDrawField(group, 8); + IParticleSystemInstance* const instance = reinterpret_cast(group->instance); + const unsigned int count = group->count; unsigned int consumed = 0; IParticleSystemTemplate* const systemTemplate = instance->getTemplate(); unsigned char* const descriptor = reinterpret_cast(systemTemplate); // Technique for drawBatch: blend mode 1 -> "Additive"; else write-Z -> "DiffuseWithZWrite"; // else "Diffuse". int technique = 0; - if (psmDrawField(descriptor, 0x90) == 1) technique = 1; + if (psmDescriptor1(descriptor, 0x90) == 1) technique = 1; else if (descriptor[0x1F2]) technique = 2; // COLOR1 reads descriptor +0x1AC..+0x1B8 as a Vec4 whose w is the derived light-affection // factor at +0x1B8; COLOR2 is the {rgb,1} Vec4 at +0x1BC; colorblendgraph the graph at +0x12C. @@ -426,58 +470,58 @@ static bool psmDrawMeshParticleGroup(unsigned char* renderer, dx9rend::IRenderVi static_cast(systemTemplate)->getLightMapIntensityOffset(); { // No null test on the looked-up parameter (the colour words above are tested). - const vc71::string name("LightmapIntensityOffset"); + const std::string name("LightmapIntensityOffset"); psmMeshParameter(dx9rend::effectGetShaderParameterBorrowedTyped(g_meshParticleMeshEffectState.effect, name)) ->setValue(&lightmapIntensityOffset, 0); } // Descriptor +0x8C is the MeshParticleMesh instance the type-1 template's setGeometry // (slot 114, PE 101796D0) created. Every use below re-reads it, as the PE does. A null // geometry leaves the group untouched and still reports true (shipped). - if (psmDrawField(descriptor, 0x8C)) + if (psmDescriptor1(descriptor, 0x8C)) { // Mesh +0x44 points at the selected (lod, geom) record whose first word is the number of // bone slots (the instance's matrix array at +0x38 has 26). - unsigned int slot = *psmDrawField(psmDrawField(descriptor, 0x8C), 0x44); + unsigned int slot = meshParticleMeshLodPartCount(psmDescriptor1(descriptor, 0x8C)); if (count) { for (;;) { - unsigned char* particle = psmDrawField(renderer, 4)[lastIndex - static_cast(consumed)]; + unsigned char* particle = psmMeshField(renderer, 4)[lastIndex - static_cast(consumed)]; if (psmDrawField(particle, 0xBC) < target) break; // unsigned `jb` --slot; - psmMeshGeometrySetPartTransformation(psmDrawField(descriptor, 0x8C), + psmMeshGeometrySetPartTransformation(psmDescriptor1(descriptor, 0x8C), &psmDrawField(particle, 4), static_cast(slot)); - meshParticleMeshSetAgeAndAlpha(psmDrawField(descriptor, 0x8C), + meshParticleMeshSetAgeAndAlpha(psmDescriptor1(descriptor, 0x8C), psmDrawField(particle, 0x5C), psmDrawField(particle, 0x6C), slot); if (!slot) { // A full batch writes slot 0 twice: +0x4C above, then +0x50 (-> +0x4C(m, 0)). - psmMeshGeometrySetTransformation(psmDrawField(descriptor, 0x8C), + psmMeshGeometrySetTransformation(psmDescriptor1(descriptor, 0x8C), &psmDrawField(particle, 4)); - meshParticleMeshDrawBatch(psmDrawField(descriptor, 0x8C), technique, false); - slot = *psmDrawField(psmDrawField(descriptor, 0x8C), 0x44); + meshParticleMeshDrawBatch(psmDescriptor1(descriptor, 0x8C), technique, false); + slot = meshParticleMeshLodPartCount(psmDescriptor1(descriptor, 0x8C)); } - --psmDrawField(group, 8); - ++psmDrawField(renderer, 0x1C14); + --group->count; + ++psmMeshField(renderer, 0x1C14); if (++consumed >= count) break; } } - if (slot < *psmDrawField(psmDrawField(descriptor, 0x8C), 0x44)) + if (slot < meshParticleMeshLodPartCount(psmDescriptor1(descriptor, 0x8C))) { // A partial batch parks every unfilled slot on the shared zero matrix (PE 10079290), // collapsing those copies of the mesh to a point, and draws the whole batch anyway. while (slot > 1) { --slot; - psmMeshGeometrySetPartTransformation(psmDrawField(descriptor, 0x8C), + psmMeshGeometrySetPartTransformation(psmDescriptor1(descriptor, 0x8C), &Mat4::getZero(), static_cast(slot)); } if (slot == 1) - psmMeshGeometrySetTransformation(psmDrawField(descriptor, 0x8C), &Mat4::getZero()); - meshParticleMeshDrawBatch(psmDrawField(descriptor, 0x8C), technique, false); + psmMeshGeometrySetTransformation(psmDescriptor1(descriptor, 0x8C), &Mat4::getZero()); + meshParticleMeshDrawBatch(psmDescriptor1(descriptor, 0x8C), technique, false); } } - psmDrawField(group, 4) = lastIndex - static_cast(consumed); + group->last = lastIndex - static_cast(consumed); return true; } @@ -486,18 +530,20 @@ static bool psmDrawMeshParticleGroup(unsigned char* renderer, dx9rend::IRenderVi // +0x7C first-person flag, +0x7D use the second first-person view, +0x80 alpha. static void psmDrawMeshParticleExtraList(unsigned char* renderer, bool pass) { - unsigned char** entry = psmDrawField(renderer, 0x1D84); - if (entry != psmDrawField(renderer, 0x1D88)) + std::vector& list = meshParticlesRendererMeshes(renderer); + MeshParticleMesh** entry = list.data(); + if (entry != list.data() + list.size()) { do { - unsigned char* const mesh = *entry; + MeshParticleMesh* const meshObject = *entry; + unsigned char* const mesh = reinterpret_cast(meshObject); psmMeshGeometryGetTemplate(mesh); // slot +0x38, result discarded // The view is fetched for every element, including the ones skipped below. - dx9rend::IRenderView* const view = pass && mesh[0x7D] + dx9rend::IRenderView* const view = pass && meshObject->m_alternateView // +0x7D ? static_cast(dx9rend::g_rendererBase)->getRenderView2() : static_cast(dx9rend::g_rendererBase)->getRenderViewDup(); - if (pass ? mesh[0x7C] != 0 : mesh[0x7C] == 0) + if (pass ? meshObject->m_firstPerson != 0 : meshObject->m_firstPerson == 0) // +0x7C { if (g_meshParticleMeshEffectState.worldViewProjection) { @@ -515,19 +561,19 @@ static void psmDrawMeshParticleExtraList(unsigned char* renderer, bool pass) psmMeshParameter(g_meshParticleMeshEffectState.colorBlendGraph)->setValue(&blend, 0); const float one = 1.0f; { - const vc71::string name("LightmapIntensityOffset"); + const std::string name("LightmapIntensityOffset"); psmMeshParameter(dx9rend::effectGetShaderParameterBorrowedTyped(g_meshParticleMeshEffectState.effect, name)) ->setValue(&one, 0); } - meshParticleMeshSetAgeAndAlpha(mesh, 1.0f, psmDrawField(mesh, 0x80), 0); - meshParticleMeshSetAgeAndAlpha(mesh, 1.0f, psmDrawField(mesh, 0x80), 1); + meshParticleMeshSetAgeAndAlpha(mesh, 1.0f, meshObject->m_alpha, 0); // +0x80 + meshParticleMeshSetAgeAndAlpha(mesh, 1.0f, meshObject->m_alpha, 1); meshParticleMeshDrawBatch(mesh, 1, false); // always "Additive" } ++entry; - } while (entry != psmDrawField(renderer, 0x1D88)); + } while (entry != list.data() + list.size()); } // Only the first-person call (pass == true) empties the list: PE 100D74B0 resize(0, 0), // which keeps the allocation (same effect as psmDrawClearPointerVector). if (pass) - psmDrawClearPointerVector(renderer + 0x1D80); + psmDrawClearPointerVector(renderer, psmMeshRendererOffset(0x1D80)); } diff --git a/Code/BF2/Geom/ParticleSystem/ParticleRendererNsa.inl b/Code/BF2/Geom/ParticleSystem/ParticleRendererNsa.inl index 21602452f..7253e8232 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleRendererNsa.inl +++ b/Code/BF2/Geom/ParticleSystem/ParticleRendererNsa.inl @@ -5,9 +5,11 @@ // 1016F07C..1016F0A6 uses fsin/fcos and __ftol2 truncation on the live x87 result. static void psmNsaPackRotation(float angle, short& sine, short& cosine) { +#if defined(_WIN32) const float scale = 32767.0f; - unsigned short savedControl, truncateControl; __int64 sinValue, cosValue; +#if defined(_M_IX86) + unsigned short savedControl, truncateControl; __asm { fnstcw savedControl mov ax, savedControl @@ -26,12 +28,30 @@ static void psmNsaPackRotation(float angle, short& sine, short& cosine) fistp cosValue fldcw savedControl } +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). The C++ conversions + // truncate toward zero, the rounding control the PE loads around each fistp. + sinValue = static_cast<__int64>(std::sin(static_cast(angle)) * scale); + cosValue = static_cast<__int64>(std::cos(static_cast(angle)) * scale); +#endif + sine = static_cast(sinValue); + cosine = static_cast(cosValue); +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-port.md). + const float scale = 32767.0f; + unsigned short savedControl, truncateControl; + __int64 sinValue, cosValue; + // [CHOSEN, not recovered] Preserve x87 trig truncation to int64 before low-short store. + bf2x87::packedRotation(angle, sine, cosine); + return; sine = static_cast(sinValue); cosine = static_cast(cosValue); +#endif } // The instance parameter is unused. Packed state advances once per dirty // particle; the oriented corners are supplied by the NSA simulation, not screen axes. +// PE 0x1016EE70 static void psmUpdateNsaDrawState(unsigned char* renderer, unsigned char* particle, unsigned char* descriptor, unsigned char*, dx9rend::IRenderView* view) { @@ -39,11 +59,11 @@ static void psmUpdateNsaDrawState(unsigned char* renderer, unsigned char* partic if (!(flags & 0x80)) return; flags &= ~0x80u; const double age = psmDrawField(particle, 0x24); - const float rate = static_cast(age * age * psmDrawField(descriptor, 0xF0) - + age * psmDrawField(descriptor, 0xF4) - + age * age * age * psmDrawField(descriptor, 0xEC) - + psmDrawField(descriptor, 0xF8)); - const float dt = psmParticleClamp(rate, 0, 1) * psmDrawField(renderer, 0x42C); + const float rate = static_cast(age * age * psmDescriptor4(descriptor, 0xF0) + + age * psmDescriptor4(descriptor, 0xF4) + + age * age * age * psmDescriptor4(descriptor, 0xEC) + + psmDescriptor4(descriptor, 0xF8)); + const float dt = psmParticleClamp(rate, 0, 1) * psmNsaField(renderer, 0x42C); float& rotation = psmDrawField(particle, 0x88); if (descriptor[0x210]) { @@ -92,32 +112,54 @@ static void psmUpdateNsaDrawState(unsigned char* renderer, unsigned char* partic static_cast(psmParticleClamp(height, 0, 1)) * 32767.0f)); } else psmDrawField(particle, 0x22) = 0; - const unsigned int frameCount = psmDrawField(descriptor, 0xD0); + const unsigned int frameCount = psmDescriptor4(descriptor, 0xD0); if (descriptor[0xC4] && frameCount) { float& frame = psmDrawField(particle, 0x80); - const double nextFrame = static_cast(dt) * psmDrawField(descriptor, 0xC0) + frame; + const double nextFrame = static_cast(dt) * psmDescriptor4(descriptor, 0xC0) + frame; frame = static_cast(nextFrame); +#if defined(__APPLE__) + // [CHOSEN, not recovered] Preserve FISTP integer indefinite after floor. + const unsigned int whole = static_cast(bf2x87::toIntTruncate(bf2x87::wide(std::floor(nextFrame)))); +#else const unsigned int whole = static_cast(static_cast(std::floor(nextFrame))); +#endif psmDrawField(particle, 0x3C) = static_cast(static_cast(frame) - whole); const unsigned int current = whole % frameCount; if (current != (flags & 0xF)) { flags ^= (current ^ flags) & 0xF; const unsigned int next = (current + 1) % frameCount; - const unsigned int columns = psmDrawField(descriptor, 0xD4); + const unsigned int columns = psmDescriptor4(descriptor, 0xD4); const unsigned int xs[2] = { current % columns, next % columns }; +#if defined(__APPLE__) + // [CHOSEN, not recovered] Only the second row product has a float spill in the PE. + using bf2x87::wide; + const bf2x87::Real ys[2] = { + wide(current - xs[0]) * wide(psmDescriptor4(descriptor, 0xD8)), + wide(bf2x87::store(wide(next - xs[1]) * wide(psmDescriptor4(descriptor, 0xD8)))) }; +#else const double ys[2] = { - static_cast(current - xs[0]) * psmDrawField(descriptor, 0xD8), - static_cast(static_cast(next - xs[1]) * psmDrawField(descriptor, 0xD8)) }; + static_cast(current - xs[0]) * psmDescriptor4(descriptor, 0xD8), + static_cast(static_cast(next - xs[1]) * psmDescriptor4(descriptor, 0xD8)) }; +#endif for (unsigned int i = 0; i < 2; ++i) { +#if defined(__APPLE__) + const bf2x87::Real u = (wide(xs[i]) * wide(psmDescriptor4(descriptor, 0x12C)) + + wide(psmDescriptor4(descriptor, 0x212)) * wide(0.000030518509f)) * wide(32767.0f); + const bf2x87::Real v = (wide(psmDescriptor4(descriptor, 0x214)) * wide(0.000030518509f) + + ys[i] * wide(psmDescriptor4(descriptor, 0x130))) * wide(32767.0f); + psmDrawField(particle, 0x40 + 4 * i) = bf2x87::lowShort(bf2x87::toInt64Truncate(u)); + psmDrawField(particle, 0x42 + 4 * i) = bf2x87::lowShort(bf2x87::toInt64Truncate(v)); +#else psmDrawField(particle, 0x40 + 4 * i) = static_cast(static_cast<__int64>( - (static_cast(xs[i]) * psmDrawField(descriptor, 0x12C) - + static_cast(psmDrawField(descriptor, 0x212)) * 0.000030518509f) * 32767.0f)); + (static_cast(xs[i]) * psmDescriptor4(descriptor, 0x12C) + + static_cast(psmDescriptor4(descriptor, 0x212)) * 0.000030518509f) * 32767.0f)); psmDrawField(particle, 0x42 + 4 * i) = static_cast(static_cast<__int64>( - (static_cast(psmDrawField(descriptor, 0x214)) * 0.000030518509f - + ys[i] * psmDrawField(descriptor, 0x130)) * 32767.0f)); + (static_cast(psmDescriptor4(descriptor, 0x214)) * 0.000030518509f + + ys[i] * psmDescriptor4(descriptor, 0x130)) * 32767.0f)); +#endif } } } @@ -130,21 +172,21 @@ static void psmCollectNsaParticles(unsigned char* renderer, dx9rend::IRenderView view->getViewMatrixPtr(); view->getViewMatrixPtr(); const float nearPlane = view->getNearPlane(); - const unsigned int count = psmDrawField(instance, 0x28); - if (psmDrawField(descriptor, 8) == -1) - psmDrawField(descriptor, 8) = psmDrawField(renderer, 0x51C)++; + const unsigned int count = psmInstanceA(instance, 0x28); + if (psmDescriptor4(descriptor, 8) == -1) + psmDescriptor4(descriptor, 8) = psmNsaField(renderer, 0x51C)++; ParticleSystemManager* manager = reinterpret_cast(g_ParticleSystemManager); - const unsigned int lod = psmDrawField(descriptor, 0x6C); + const unsigned int lod = psmDescriptor4(descriptor, 0x6C); const float farDistance = manager->m_farDistances[lod]; const float inverseFarRange = manager->m_inverseFarRanges[lod]; for (unsigned int i = 0; i < count; ++i) { - unsigned char* particle = psmDrawField(instance, 0x24)[i]; - psmDrawField(particle, 0x2C) = psmDrawField(descriptor, 4); - const double depth = static_cast(psmDrawField(particle, 0x14)) * psmDrawField(renderer, 0x434) - + static_cast(psmDrawField(particle, 0x18)) * psmDrawField(renderer, 0x438) - + static_cast(psmDrawField(particle, 0x10)) * psmDrawField(renderer, 0x430) - + psmDrawField(renderer, 0x43C); + unsigned char* particle = psmInstanceA(instance, 0x24)[i]; + psmDrawField(particle, 0x2C) = psmDescriptor4(descriptor, 4); + const double depth = static_cast(psmDrawField(particle, 0x14)) * psmNsaField(renderer, 0x434) + + static_cast(psmDrawField(particle, 0x18)) * psmNsaField(renderer, 0x438) + + static_cast(psmDrawField(particle, 0x10)) * psmNsaField(renderer, 0x430) + + psmNsaField(renderer, 0x43C); const float roundedDepth = static_cast(depth); if (depth < nearPlane) continue; // PE test ah,5 / jnp retains unordered input. float& alpha = psmDrawField(particle, 0x34); @@ -155,29 +197,30 @@ static void psmCollectNsaParticles(unsigned char* renderer, dx9rend::IRenderView alpha = static_cast((1 - fade) * (1 - fade) * psmDrawField(particle, 0x38)); } else alpha = psmDrawField(particle, 0x38); - if (alpha < psmDrawField(descriptor, 0x94)) continue; + if (alpha < psmDescriptor4(descriptor, 0x94)) continue; const Mat4* camera = view->getViewMatrixPtr(); const float x = camera->m[12] - psmDrawField(particle, 0x10); const double y = static_cast(camera->m[13]) - psmDrawField(particle, 0x14); const double z = static_cast(camera->m[14]) - psmDrawField(particle, 0x18); psmDrawField(particle, 0x94) = static_cast(z * z + y * y + static_cast(x) * x); psmUpdateNsaDrawState(renderer, particle, descriptor, instance, view); - psmDrawField(renderer, 0x1C)[psmDrawField(renderer, 0x428)++] = particle; + psmNsaField(renderer, 0x1C)[psmNsaField(renderer, 0x428)++] = particle; } - vc71::vectorRef(renderer + 0xC).push_back(instance); + particleRendererList(renderer, psmNsaRendererOffset(0xC)).push_back(instance); } // stable radix order, using the particle +94 distance and renderer +20 buckets. +// PE 0x1016D640 static void psmSortNsaParticles(unsigned char* renderer, unsigned char** table, unsigned int count) { - unsigned char** buckets = reinterpret_cast(renderer + 0x20); + unsigned char** buckets = &psmNsaField(renderer, 0x20); for (unsigned int byte = 0; byte < 4; ++byte) { for (int i = static_cast(count) - 1; i >= 0; --i) { unsigned char* particle = table[i]; const unsigned int key = particle[0x94 + byte]; - psmDrawField(particle, 0) = buckets[key]; + psmRecordLink(particle, 4) = buckets[key]; buckets[key] = particle; } unsigned int output = 0; @@ -188,70 +231,73 @@ static void psmSortNsaParticles(unsigned char* renderer, unsigned char** table, while (particle) { table[output++] = particle; - particle = psmDrawField(particle, 0); + particle = static_cast(psmRecordLink(particle, 4)); } } } } +// PE 0x1016D8F0 static unsigned int psmBatchNsaParticles(unsigned char* renderer, unsigned int begin, unsigned int end) { - unsigned char* mapping = psmDrawField(renderer, 0x55C); + unsigned char* mapping = psmNsaField(renderer, 0x55C); ::memset(mapping, 0xFF, 0x800); - unsigned int& count = psmDrawField(renderer, 0x560); + unsigned int& count = psmNsaField(renderer, 0x560); count = 0; unsigned int i = begin; for (; i < end; ++i) { - unsigned char* particle = psmDrawField(renderer, 0x1C)[psmDrawField(renderer, 8) - i]; + unsigned char* particle = psmNsaField(renderer, 0x1C)[psmNsaField(renderer, 8) - i]; const unsigned short id = psmDrawField(particle, 0x2C); if (mapping[id] != 0xFF) continue; if (count >= 10) break; mapping[id] = static_cast(count); - unsigned char* descriptor = reinterpret_cast(g_templatesById[id]); - psmParticleCopyParameters(psmDrawField(renderer, 0x564) + count * 112, descriptor + 0x12C); + unsigned char* descriptor = reinterpret_cast(psmLookupParticleTemplate(id)); + psmParticleCopyParameters(psmNsaField(renderer, 0x564) + count * 112, descriptor + 0x12C); ++count; } - psmParticleParameter(renderer, 0x584)->setValue(psmDrawField(renderer, 0x564), 0); + psmNsaParameter(renderer, 0x584)->setValue(psmNsaField(renderer, 0x564), 0); return i; } +// PE 0x1016EC10 static void psmBindNsaParticleParameters(unsigned char* renderer) { - if (!psmDrawPointerVectorSize(renderer + 0xC)) return; - psmParticleParameter(renderer, 0x570)->setValue(renderer + 0x448, 0); - psmParticleParameter(renderer, 0x574)->setValue(renderer + 0x4C8, 0); + if (!psmDrawPointerVectorSize(renderer, psmNsaRendererOffset(0xC))) return; + psmNsaParameter(renderer, 0x570)->setValue(renderer + 0x448, 0); + psmNsaParameter(renderer, 0x574)->setValue(renderer + 0x4C8, 0); HemiMap* map = g_HemiMapManager->getBaseHemiMap(); if (map) { - psmParticleParameter(renderer, 0x578)->setValue(&g_HemiMapManager->getHemiMapInfo(map), 0); - psmParticleParameter(renderer, 0x57C)->setFloat(map->falloff); - psmParticleParameter(renderer, 0x580)->setValue(map->texture, 0); + psmNsaParameter(renderer, 0x578)->setValue(&g_HemiMapManager->getHemiMapInfo(map), 0); + psmNsaParameter(renderer, 0x57C)->setFloat(map->falloff); + psmNsaParameter(renderer, 0x580)->setValue(map->texture, 0); } else { - HemiMap* fallback = g_HemiMapManager->getBaseHemiMap(); // PE 100F1490 rereads the owner. - psmParticleParameter(renderer, 0x580)->setValue(fallback ? fallback->texture : 0, 0); + // The helper asks the manager again after the preceding null result. + dx9rend::EngineTexture* const fallback=psmBaseHemiTexture(); + psmNsaParameter(renderer, 0x580)->setValue(fallback, 0); } - psmParticleParameter(renderer, 0x594)->setValue(&g_LightManager->getEffectSunColor(), 0); - psmParticleParameter(renderer, 0x598)->setValue(&g_LightManager->getEffectShadowColor(), 0); + psmNsaParameter(renderer, 0x594)->setValue(&g_LightManager->getEffectSunColor(), 0); + psmNsaParameter(renderer, 0x598)->setValue(&g_LightManager->getEffectShadowColor(), 0); ParticleSystemManager* manager = reinterpret_cast(g_ParticleSystemManager); if (!manager->m_shaderQuality) { const float scale = 1.0f / manager->m_value8CA4; const Vec3 color = { scale, scale, scale }; - psmParticleParameter(renderer, 0x594)->setValue(&color, 0); + psmNsaParameter(renderer, 0x594)->setValue(&color, 0); } - psmParticleParameter(renderer, 0x58C)->setValue(static_cast(dx9rend::g_raShaderConstants) + 0xA8, 0); - psmParticleParameter(renderer, 0x590)->setValue(static_cast(dx9rend::g_raShaderConstants) + 0xBC, 0); + psmNsaParameter(renderer, 0x58C)->setValue(dx9rend::raShaderConstantsAt(0xA8), 0); + psmNsaParameter(renderer, 0x590)->setValue(dx9rend::raShaderConstantsAt(0xBC), 0); manager = reinterpret_cast(g_ParticleSystemManager); static const char* const techniques[] = {"NSAParticleShowFill", "NSAParticleLow", "NSAParticleMedium", "NSAParticleHigh"}; if (manager->m_shaderQuality <= 3) - dx9rend::effectSetTechniqueByName(psmDrawField(renderer, 0x56C), vc71::string(techniques[manager->m_shaderQuality])); - dx9rend::vertexDeclarationBind(psmDrawField(renderer, 0x59C)); - dx9rend::vertexBufferBindStream(psmDrawField(renderer, 0x568), 0); - dx9rend::effectBegin(psmDrawField(renderer, 0x56C)); - dx9rend::effectBeginPass(psmDrawField(renderer, 0x56C), 0); + dx9rend::effectSetTechniqueByName(psmNsaField(renderer, 0x56C), std::string(techniques[manager->m_shaderQuality])); + dx9rend::vertexDeclarationBind(psmNsaField(renderer, 0x59C)); + dx9rend::vertexBufferBindStream(psmNsaField(renderer, 0x568), 0); + dx9rend::effectBegin(psmNsaField(renderer, 0x56C)); + dx9rend::effectBeginPass(psmNsaField(renderer, 0x56C), 0); } static void psmWriteNsaParticleVertices(unsigned char* renderer, unsigned char* particle, unsigned char* output) @@ -259,7 +305,7 @@ static void psmWriteNsaParticleVertices(unsigned char* renderer, unsigned char* float minimumSize = psmDrawField(particle, 0x8C); if (psmDrawField(particle, 0x48) < minimumSize) minimumSize = psmDrawField(particle, 0x48); const unsigned short id = psmDrawField(particle, 0x2C); - const float descriptorIndex = static_cast(static_cast(psmDrawField(renderer, 0x55C)[id])); + const float descriptorIndex = static_cast(static_cast(psmNsaField(renderer, 0x55C)[id])); const unsigned int corners[6] = {0, 1, 3, 3, 1, 2}; const short uvs[6][2] = {{-32768,32767},{32767,32767},{-32768,-32768}, {-32768,-32768},{32767,32767},{32767,-32768}}; @@ -283,66 +329,66 @@ static void psmWriteNsaParticleVertices(unsigned char* renderer, unsigned char* static bool psmDrawNsaParticles(unsigned char* renderer, unsigned int target) { - if (!psmDrawField(renderer, 0x428)) return false; - const int initialIndex = psmDrawField(renderer, 8); + if (!psmNsaField(renderer, 0x428)) return false; + const int initialIndex = psmNsaField(renderer, 8); unsigned int tableIndex = initialIndex; - unsigned char* first = psmDrawField(renderer, 0x1C)[tableIndex]; - void* texture = psmDrawField(first, 0x58); - psmParticleParameter(renderer, 0x588)->setValue(texture, 0); - const unsigned int count = psmDrawField(renderer, 0x428); + unsigned char* first = psmNsaField(renderer, 0x1C)[tableIndex]; + void* texture = psmRecordPointer(first, 4); + psmNsaParameter(renderer, 0x588)->setValue(texture, 0); + const unsigned int count = psmNsaField(renderer, 0x428); unsigned int batchEnd = psmBatchNsaParticles(renderer, 0, count); psmBindNsaParticleParameters(renderer); unsigned int vertices = 0; unsigned char* buffer = static_cast(dx9rend::vertexBufferLock( - psmDrawField(renderer, 0x568), psmDrawField(renderer, 0x444), - 6 * count, psmDrawField(renderer, 0x444) ? 6144 : 10240)); + psmNsaField(renderer, 0x568), psmNsaField(renderer, 0x444), + 6 * count, psmNsaField(renderer, 0x444) ? 6144 : 10240)); if (!buffer) return false; unsigned int consumed = 0; for (; consumed < count; ++consumed) { - unsigned char* particle = psmDrawField(renderer, 0x1C)[tableIndex]; + unsigned char* particle = psmNsaField(renderer, 0x1C)[tableIndex]; if (psmDrawField(particle, 0x94) < target) break; if (consumed == batchEnd) { - dx9rend::vertexBufferUnlock(psmDrawField(renderer, 0x568)); - dx9rend::rendererDrawPrimitive(vertices / 3, 4, psmDrawField(renderer, 0x444)); - psmDrawField(renderer, 0x444) += vertices; + dx9rend::vertexBufferUnlock(psmNsaField(renderer, 0x568)); + dx9rend::rendererDrawPrimitive(vertices / 3, 4, psmNsaField(renderer, 0x444)); + psmNsaField(renderer, 0x444) += vertices; vertices = 0; batchEnd = psmBatchNsaParticles(renderer, consumed, count); - if (psmDrawField(particle, 0x58) != texture) + if (psmRecordPointer(particle, 4) != texture) { - psmParticleParameter(renderer, 0x588)->setValue(psmDrawField(particle, 0x58), 0); - texture = psmDrawField(particle, 0x58); + psmNsaParameter(renderer, 0x588)->setValue(psmRecordPointer(particle, 4), 0); + texture = psmRecordPointer(particle, 4); } - buffer = static_cast(dx9rend::vertexBufferLock(psmDrawField(renderer, 0x568), - psmDrawField(renderer, 0x444), 6 * (batchEnd - consumed), 4096)); + buffer = static_cast(dx9rend::vertexBufferLock(psmNsaField(renderer, 0x568), + psmNsaField(renderer, 0x444), 6 * (batchEnd - consumed), 4096)); if (!buffer) return false; // Retail leaves the effect active on these lock failures. - psmCountParticleDraw(0x8C48); + psmCountParticleDraw(1); // +0x8C48 } - if (psmDrawField(particle, 0x58) != texture) + if (psmRecordPointer(particle, 4) != texture) { - dx9rend::vertexBufferUnlock(psmDrawField(renderer, 0x568)); - dx9rend::rendererDrawPrimitive(vertices / 3, 4, psmDrawField(renderer, 0x444)); - psmDrawField(renderer, 0x444) += vertices; + dx9rend::vertexBufferUnlock(psmNsaField(renderer, 0x568)); + dx9rend::rendererDrawPrimitive(vertices / 3, 4, psmNsaField(renderer, 0x444)); + psmNsaField(renderer, 0x444) += vertices; vertices = 0; - psmParticleParameter(renderer, 0x588)->setValue(psmDrawField(particle, 0x58), 0); - buffer = static_cast(dx9rend::vertexBufferLock(psmDrawField(renderer, 0x568), - psmDrawField(renderer, 0x444), 6 * (batchEnd - consumed), 4096)); + psmNsaParameter(renderer, 0x588)->setValue(psmRecordPointer(particle, 4), 0); + buffer = static_cast(dx9rend::vertexBufferLock(psmNsaField(renderer, 0x568), + psmNsaField(renderer, 0x444), 6 * (batchEnd - consumed), 4096)); if (!buffer) return false; - texture = psmDrawField(particle, 0x58); - psmCountParticleDraw(0x8C48); + texture = psmRecordPointer(particle, 4); + psmCountParticleDraw(1); // +0x8C48 } psmWriteNsaParticleVertices(renderer, particle, buffer + vertices * 72); vertices += 6; --tableIndex; - ++psmDrawField(renderer, 0x420); - --psmDrawField(renderer, 0x428); + ++psmNsaField(renderer, 0x420); + --psmNsaField(renderer, 0x428); } - dx9rend::vertexBufferUnlock(psmDrawField(renderer, 0x568)); - psmCountParticleDraw(0x8C48); - dx9rend::rendererDrawPrimitive(vertices / 3, 4, psmDrawField(renderer, 0x444)); - psmDrawField(renderer, 0x444) += vertices; - psmDrawField(renderer, 8) = initialIndex - consumed; - dx9rend::effectEnd(psmDrawField(renderer, 0x56C)); + dx9rend::vertexBufferUnlock(psmNsaField(renderer, 0x568)); + psmCountParticleDraw(1); // +0x8C48 + dx9rend::rendererDrawPrimitive(vertices / 3, 4, psmNsaField(renderer, 0x444)); + psmNsaField(renderer, 0x444) += vertices; + psmNsaField(renderer, 8) = initialIndex - consumed; + dx9rend::effectEnd(psmNsaField(renderer, 0x56C)); return true; } diff --git a/Code/BF2/Geom/ParticleSystem/ParticleRendererTrail.inl b/Code/BF2/Geom/ParticleSystem/ParticleRendererTrail.inl index f8d2070ef..9a537ba26 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleRendererTrail.inl +++ b/Code/BF2/Geom/ParticleSystem/ParticleRendererTrail.inl @@ -4,28 +4,29 @@ // Walk the circular particle array in emission order. Even a rejected // two-point trail or 65th group writes the temporary table before the admission check. +// PE 0x10172FF0 static void psmCollectTrailParticles(unsigned char* renderer, dx9rend::IRenderView* view, unsigned char* instance, unsigned char* descriptor) { view->getViewMatrixPtr(); view->getNearPlane(); view->getViewMatrixPtr(); - if (psmDrawField(descriptor, 8) == -1) - psmDrawField(descriptor, 8) = psmDrawField(renderer, 0x854)++; + if (psmDescriptor2(descriptor, 8) == -1) + psmDescriptor2(descriptor, 8) = psmTrailField(renderer, 0x854)++; ParticleSystemManager* manager = reinterpret_cast(g_ParticleSystemManager); - const unsigned int lod = psmDrawField(descriptor, 0x68); + const unsigned int lod = psmDescriptor2(descriptor, 0x68); const float farDistance = manager->m_farDistances[lod]; const float inverseFarRange = manager->m_inverseFarRanges[lod]; unsigned int count = 0; - unsigned int index = psmDrawField(instance, 0x178) - & psmDrawField(instance, 0x17C); - while (index != psmDrawField(instance, 0x174)) + unsigned int index = psmInstanceB(instance, 0x178) + & psmInstanceB(instance, 0x17C); + while (index != psmInstanceB(instance, 0x174)) { - unsigned char* particle = psmDrawField(instance, 0x14)[index]; - const double depth = static_cast(psmDrawField(particle, 0x14)) * psmDrawField(renderer, 0x738) - + static_cast(psmDrawField(particle, 0x18)) * psmDrawField(renderer, 0x73C) - + static_cast(psmDrawField(renderer, 0x734)) * psmDrawField(particle, 0x10) - + psmDrawField(renderer, 0x740); + unsigned char* particle = psmInstanceB(instance, 0x14)[index]; + const double depth = static_cast(psmDrawField(particle, 0x14)) * psmTrailField(renderer, 0x738) + + static_cast(psmDrawField(particle, 0x18)) * psmTrailField(renderer, 0x73C) + + static_cast(psmTrailField(renderer, 0x734)) * psmDrawField(particle, 0x10) + + psmTrailField(renderer, 0x740); if (!(depth > farDistance)) // PE test ah,41h includes unordered input in the unfaded arm. psmDrawField(particle, 0x7C) = psmDrawField(particle, 0x88); else @@ -35,95 +36,95 @@ static void psmCollectTrailParticles(unsigned char* renderer, dx9rend::IRenderVi psmDrawField(particle, 0x7C) = static_cast((1 - fade) * (1 - fade) * psmDrawField(particle, 0x88)); } - psmDrawField(particle, 0x86) = psmDrawField(descriptor, 4); - psmDrawField(renderer, 0x18)[psmDrawField(renderer, 0x31C) + count] = particle; - index = (index + 1) & psmDrawField(instance, 0x17C); + psmDrawField(particle, 0x86) = psmDescriptor2(descriptor, 4); + psmTrailField(renderer, 0x18)[psmTrailField(renderer, 0x31C) + count] = particle; + index = (index + 1) & psmInstanceB(instance, 0x17C); ++count; } - if (count > 2 && psmDrawField(renderer, 0x320) < 64) + if (count > 2 && psmTrailField(renderer, 0x320) < 64) { - const unsigned int group = psmDrawField(renderer, 0x320); - psmDrawField(renderer, 0x1C + 12 * group) = instance; - psmDrawField(renderer, 0x20 + 12 * group) = psmDrawField(renderer, 0x31C) + count - 1; - psmDrawField(renderer, 0x24 + 12 * group) = count; - ++psmDrawField(renderer, 0x320); - psmDrawField(renderer, 0x31C) += count; + const unsigned int group = psmTrailField(renderer, 0x320); + psmTrailField(renderer, 0x1C + 12 * group) = instance; + psmTrailField(renderer, 0x20 + 12 * group) = psmTrailField(renderer, 0x31C) + count - 1; + psmTrailField(renderer, 0x24 + 12 * group) = count; + ++psmTrailField(renderer, 0x320); + psmTrailField(renderer, 0x31C) += count; } } +// PE 0x10173FA0 static void psmBindTrailParameters(unsigned char* renderer) { - psmParticleParameter(renderer, 0x8E4)->setValue(renderer + 0x74C, 0); - psmParticleParameter(renderer, 0x8E8)->setValue(renderer + 0x80C, 0); + psmTrailParameter(renderer, 0x8E4)->setValue(renderer + 0x74C, 0); + psmTrailParameter(renderer, 0x8E8)->setValue(renderer + 0x80C, 0); HemiMap* map = g_HemiMapManager->getBaseHemiMap(); if (map) { - psmParticleParameter(renderer, 0x8EC)->setValue(&g_HemiMapManager->getHemiMapInfo(map), 0); - psmParticleParameter(renderer, 0x8F0)->setFloat(map->falloff); - psmParticleParameter(renderer, 0x8FC)->setValue(map->texture, 0); + psmTrailParameter(renderer, 0x8EC)->setValue(&g_HemiMapManager->getHemiMapInfo(map), 0); + psmTrailParameter(renderer, 0x8F0)->setFloat(map->falloff); + psmTrailParameter(renderer, 0x8FC)->setValue(map->texture, 0); } else { HemiMap* fallback = g_HemiMapManager->getBaseHemiMap(); // PE 100F1490 rereads the owner. - psmParticleParameter(renderer, 0x8FC)->setValue(fallback ? fallback->texture : 0, 0); + psmTrailParameter(renderer, 0x8FC)->setValue(fallback ? fallback->texture : 0, 0); } - psmParticleParameter(renderer, 0x908)->setValue(&g_LightManager->getEffectSunColor(), 0); - psmParticleParameter(renderer, 0x90C)->setValue(&g_LightManager->getEffectShadowColor(), 0); + psmTrailParameter(renderer, 0x908)->setValue(&g_LightManager->getEffectSunColor(), 0); + psmTrailParameter(renderer, 0x90C)->setValue(&g_LightManager->getEffectShadowColor(), 0); ParticleSystemManager* manager = reinterpret_cast(g_ParticleSystemManager); if (!manager->m_shaderQuality) { const float scale = 1.0f / manager->m_value8CA4; const Vec3 color = { scale, scale, scale }; - psmParticleParameter(renderer, 0x908)->setValue(&color, 0); + psmTrailParameter(renderer, 0x908)->setValue(&color, 0); } - psmParticleParameter(renderer, 0x8DC)->setValue(static_cast(dx9rend::g_raShaderConstants) + 0xA8, 0); - psmParticleParameter(renderer, 0x8E0)->setValue(static_cast(dx9rend::g_raShaderConstants) + 0xBC, 0); + psmTrailParameter(renderer, 0x8DC)->setValue(dx9rend::raShaderConstantsAt(0xA8), 0); + psmTrailParameter(renderer, 0x8E0)->setValue(dx9rend::raShaderConstantsAt(0xBC), 0); manager = reinterpret_cast(g_ParticleSystemManager); static const char* const techniques[] = { "TrailShowFill", "TrailLow", "TrailMedium", "TrailHigh" }; if (manager->m_shaderQuality <= 3) - dx9rend::effectSetTechniqueByName(psmDrawField(renderer, 0x8D8), vc71::string(techniques[manager->m_shaderQuality])); - dx9rend::vertexDeclarationBind(psmDrawField(renderer, 0x910)); - dx9rend::vertexBufferBindStream(psmDrawField(renderer, 0x8B4), 0); - dx9rend::effectBegin(psmDrawField(renderer, 0x8D8)); - dx9rend::effectBeginPass(psmDrawField(renderer, 0x8D8), 0); + dx9rend::effectSetTechniqueByName(psmTrailField(renderer, 0x8D8), std::string(techniques[manager->m_shaderQuality])); + dx9rend::vertexDeclarationBind(psmTrailField(renderer, 0x910)); + dx9rend::vertexBufferBindStream(psmTrailField(renderer, 0x8B4), 0); + dx9rend::effectBegin(psmTrailField(renderer, 0x8D8)); + dx9rend::effectBeginPass(psmTrailField(renderer, 0x8D8), 0); } -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: particle-trail-draw-debug-dispatch] -// Error-only dependency on the retail Debug type-6 dispatcher, TrailRenderer.cpp:647. +// PE 0x10173297. static void psmTrailDrawDebug() { - std::fprintf(stderr, "[FRONTIER] dice::hfe::geom::TrailRenderer::draw " - "(Debug type 6, TrailRenderer.cpp:647: LockFailed) reached\n"); - std::fflush(stderr); - std::abort(); + ::renddx9abi::Debug(DebugTypeError, + "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\ParticleSystem\\TrailRenderer.cpp", + 647, "") << "LockFailed"; } // The view/target parameters are unused. The selected group is consumed // in reverse order, with a separate prebuilt index buffer for each number of ribbon planes. +// PE 0x10173170 static bool psmDrawTrailGroup(unsigned char* renderer, dx9rend::IRenderView*, unsigned int, unsigned int group) { - unsigned int& remaining = psmDrawField(renderer, 0x24 + 12 * group); + unsigned int& remaining = psmTrailField(renderer, 0x24 + 12 * group); const unsigned int count = remaining; if (!count) return false; - unsigned char* instance = psmDrawField(renderer, 0x1C + 12 * group); - const unsigned int end = psmDrawField(renderer, 0x20 + 12 * group); + unsigned char* instance = psmTrailField(renderer, 0x1C + 12 * group); + const unsigned int end = psmTrailField(renderer, 0x20 + 12 * group); unsigned char* descriptor = reinterpret_cast( reinterpret_cast(instance)->getTemplate()); - const unsigned int verticesPerParticle = 2 * psmDrawField(descriptor, 0x220); - dx9rend::indexBufferBind(psmDrawField(renderer, 0x8B8 + 4 * psmDrawField(descriptor, 0x220))); - psmParticleParameter(renderer, 0x904)->setValue(descriptor + 0xAC, 0); - psmParticleParameter(renderer, 0x8F8)->setValue(psmDrawField(descriptor, 0x21C), 0); - const float fresnel = psmDrawField(descriptor, 0x220) == 1 ? 1.0f : 0.0f; - psmParticleParameter(renderer, 0x8F4)->setValue(&fresnel, 0); - const unsigned int offset = psmDrawField(renderer, 0x8B0); + const unsigned int verticesPerParticle = 2 * psmDescriptor2(descriptor, 0x220); + dx9rend::indexBufferBind(psmTrailField(renderer, 0x8B8 + 4 * psmDescriptor2(descriptor, 0x220))); + psmTrailParameter(renderer, 0x904)->setValue(descriptor + 0xAC, 0); + psmTrailParameter(renderer, 0x8F8)->setValue(psmDescriptor2(descriptor, 0x21C), 0); + const float fresnel = psmDescriptor2(descriptor, 0x220) == 1 ? 1.0f : 0.0f; + psmTrailParameter(renderer, 0x8F4)->setValue(&fresnel, 0); + const unsigned int offset = psmTrailField(renderer, 0x8B0); unsigned char* output = static_cast(dx9rend::vertexBufferLock( - psmDrawField(renderer, 0x8B4), offset, count * verticesPerParticle, offset ? 6144 : 10240)); - if (!output) psmTrailDrawDebug(); + psmTrailField(renderer, 0x8B4), offset, count * verticesPerParticle, offset ? 6144 : 10240)); + if (!output) { psmTrailDrawDebug(); return false; } unsigned int vertices = 0; for (unsigned int i = 0; i < count; ++i) { - unsigned char* particle = psmDrawField(renderer, 0x18)[end - i]; - for (unsigned int plane = 0; plane < psmDrawField(descriptor, 0x220); ++plane) + unsigned char* particle = psmTrailField(renderer, 0x18)[end - i]; + for (unsigned int plane = 0; plane < psmDescriptor2(descriptor, 0x220); ++plane) { for (unsigned int side = 0; side < 2; ++side) { @@ -134,85 +135,74 @@ static bool psmDrawTrailGroup(unsigned char* renderer, dx9rend::IRenderView*, un psmDrawField(vertex, 0x24) = static_cast(static_cast( psmDrawField(particle, 0x70)) + psmDrawField(particle, 0x74)); psmDrawField(vertex, 0x28) = psmDrawField(particle, 0x78); - psmDrawField(vertex, 0x2C) = psmDrawField(instance, 0x18C); + psmDrawField(vertex, 0x2C) = psmInstanceB(instance, 0x18C); psmDrawField(vertex, 0x30) = psmDrawField(particle, 0x7C); - psmDrawField(vertex, 0x34) = psmDrawField(instance, 0x180); - psmDrawField(vertex, 0x38) = psmDrawField(instance, 0x184); + psmDrawField(vertex, 0x34) = psmInstanceB(instance, 0x180); + psmDrawField(vertex, 0x38) = psmInstanceB(instance, 0x184); psmDrawField(vertex, 0x3C) = psmDrawField(particle, 0x80); psmDrawField(vertex, 0x40) = side ? -1.0f : 1.0f; } } --remaining; - ++psmDrawField(renderer, 0x724); + ++psmTrailField(renderer, 0x724); } - dx9rend::vertexBufferUnlock(psmDrawField(renderer, 0x8B4)); - psmCountParticleDraw(0x8C50); - dx9rend::rendererDrawIndexedPrimitive(2 * psmDrawField(descriptor, 0x220) * (count - 1), - 4, psmDrawField(renderer, 0x8B0), 0, vertices, 0); - psmDrawField(renderer, 0x8B0) += vertices; - psmDrawField(renderer, 0x20 + 12 * group) = end - count; + dx9rend::vertexBufferUnlock(psmTrailField(renderer, 0x8B4)); + psmCountParticleDraw(3); // +0x8C50 + dx9rend::rendererDrawIndexedPrimitive(2 * psmDescriptor2(descriptor, 0x220) * (count - 1), + 4, psmTrailField(renderer, 0x8B0), 0, vertices, 0); + psmTrailField(renderer, 0x8B0) += vertices; + psmTrailField(renderer, 0x20 + 12 * group) = end - count; return true; } // Empty/disabled input leaves all retained state untouched. +// PE 0x10173A00 static void psmPrepareTrailRenderer(unsigned char* renderer, dx9rend::IRenderView* view, - ParticleSystemInstanceList* instances, float deltaTime) + ParticleSystemInstanceVector* instances, float deltaTime) { - const unsigned int count = instances->size(); + const unsigned int count = static_cast(instances->size()); if (!count || !renderer[0x884]) return; - psmDrawField(renderer, 0x85C) = 0; + psmTrailField(renderer, 0x85C) = 0; renderer[0x84C] = 0; - psmDrawClearPointerVector(renderer + 8); - psmDrawField(renderer, 0x724) = 0; - psmDrawField(renderer, 0x31C) = 0; - psmDrawField(renderer, 0x320) = 0; - psmDrawField(renderer, 0x730) = deltaTime; + psmDrawClearPointerVector(renderer, psmTrailRendererOffset(8)); + psmTrailField(renderer, 0x724) = 0; + psmTrailField(renderer, 0x31C) = 0; + psmTrailField(renderer, 0x320) = 0; + psmTrailField(renderer, 0x730) = deltaTime; const Mat4* matrix = view->getInverseViewMatrixPtr(); // primary slot +68 for (unsigned int i = 0; i < 4; ++i) - psmDrawField(renderer, 0x734 + 4 * i) = matrix->m[2 + 4 * i]; + psmTrailField(renderer, 0x734 + 4 * i) = matrix->m[2 + 4 * i]; for (unsigned int i = 0; i < count; ++i) { - if (instances->first[i]->reserved01() != 2) continue; - unsigned char* instance = reinterpret_cast(instances->first[i]); - if (!instance[0x140] && !psmDrawField(instance, 0x28)) continue; + if ((*instances)[i]->reserved01() != 2) continue; + unsigned char* instance = reinterpret_cast((*instances)[i]); + if (!instance[0x140] && !psmInstanceB(instance, 0x28)) continue; const float* bounds = reinterpret_cast(instance + 0xF8); - Vec3 center; - center.x = static_cast((static_cast(bounds[0]) + bounds[3]) * 0.5); - center.y = static_cast((static_cast(bounds[4]) + bounds[1]) * 0.5); - const float sumZ = bounds[5] + bounds[2]; - center.z = sumZ * 0.5f; - const float halfX = (bounds[3] - bounds[0]) * 0.5f; - const double halfY = (static_cast(bounds[4]) - bounds[1]) * 0.5; - const float deltaZ = bounds[5] - bounds[2]; - const double halfZ = static_cast(deltaZ) * 0.5; - const float radius = static_cast(std::sqrt(halfZ * halfZ - + static_cast(halfX) * halfX + halfY * halfY)); - if (!view->getFrustumPtr()->inside(center, radius)) continue; - void* owner = psmDrawField(instance, 0x10); + const Vec3 center = psmParticleBoundsCenter(bounds); + const float radius = psmParticleBoundsRadius(bounds); + if (!rendmath::frustumInside(*view->getFrustumPtr(), center, radius)) continue; + void* owner = psmInstanceB(instance, 0x10); if (owner && psmOwnerRootDisabled(owner)) continue; // IObject m_flags bit 0 (RW-266) - psmDrawField(instance, 0x120) = + psmInstanceB(instance, 0x120) = static_cast(dx9rend::g_rendererBase)->getFrameOrdinal(); instance[0x156] = 1; - if (psmDrawField(instance, 0x28) >= 2) + if (psmInstanceB(instance, 0x28) >= 2) { - psmCollectTrailParticles(renderer, view, instance, psmDrawField(instance, 0x2C)); + psmCollectTrailParticles(renderer, view, instance, psmInstanceB(instance, 0x2C)); if (renderer[0x886]) { - // [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: particle-trail-debug-bounds] - std::fprintf(stderr, "[FRONTIER] dice::hfe::geom::TrailRenderer::prepare " - "(debug bounding mesh, PE 10173BA0) reached\n"); - std::fflush(stderr); - std::abort(); + // PE 0x10173BA0. + debugRendererQueueBounds(bounds); } } } - const unsigned int threshold = static_cast(static_cast( - static_cast(psmDrawField(renderer, 0x8AC)) * 0.85000002f)); - renderer[0x728] = psmDrawField(renderer, 0x724) > threshold; + const unsigned int threshold = psmScaledLimit(psmTrailField(renderer, 0x8AC), 0.85000002f); + renderer[0x728] = psmTrailField(renderer, 0x724) > threshold; } // The active wrapper starts with true and ORs group results into it, // including empty groups. The eligibility flag is retained on both early exits. +// PE 0x10173CC0 static bool psmDrawTrailRenderer(unsigned char* renderer, dx9rend::IRenderView* view) { if (!renderer[0x884] || !renderer[0x858]) return false; @@ -221,22 +211,22 @@ static bool psmDrawTrailRenderer(unsigned char* renderer, dx9rend::IRenderView* dx9rend::stateManagerPush(); if (!renderer[0x84C]) { - psmDrawField(renderer, 0x80C) = *view->getProjectionMatrixPtr(); + psmTrailField(renderer, 0x80C) = *view->getProjectionMatrixPtr(); const Mat4* projection = view->getProjectionMatrixPtr(); const Mat4* inverse = view->getInverseViewMatrixPtr(); - psmDrawField(renderer, 0x7CC).fullMult(*inverse, *projection); + psmTrailField(renderer, 0x7CC).fullMult(*inverse, *projection); renderer[0x84C] = 1; } - psmDrawField(renderer, 0x74C) = *view->getInverseViewMatrixPtr(); - psmParticleParameter(renderer, 0x900)->setValue(view->getViewMatrixPtr()->m + 12, 0); + psmTrailField(renderer, 0x74C) = *view->getInverseViewMatrixPtr(); + psmTrailParameter(renderer, 0x900)->setValue(view->getViewMatrixPtr()->m + 12, 0); bool drawn = true; if (renderer[0x858]) { - psmDrawField(renderer, 0x8B0) = 0; + psmTrailField(renderer, 0x8B0) = 0; psmBindTrailParameters(renderer); - for (unsigned int i = 0; i < psmDrawField(renderer, 0x320); ++i) - drawn = psmDrawTrailGroup(renderer, view, psmDrawField(renderer, 0x85C), i) || drawn; - dx9rend::effectEnd(psmDrawField(renderer, 0x8D8)); + for (unsigned int i = 0; i < psmTrailField(renderer, 0x320); ++i) + drawn = psmDrawTrailGroup(renderer, view, psmTrailField(renderer, 0x85C), i) || drawn; + dx9rend::effectEnd(psmTrailField(renderer, 0x8D8)); renderer[0x858] = 0; } dx9rend::stateManagerPop(); diff --git a/Code/BF2/Geom/ParticleSystem/ParticleSystemManager.cpp b/Code/BF2/Geom/ParticleSystem/ParticleSystemManager.cpp index 548c9f642..ce99c0147 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleSystemManager.cpp +++ b/Code/BF2/Geom/ParticleSystem/ParticleSystemManager.cpp @@ -2,40 +2,55 @@ // Coordinates wind, pause and resource lifecycle events. #ifdef BF2_IMAGE_RENDDX9 +#if !defined(_MSC_VER) +// [CHOSEN, not recovered] Compiler-typed native table entries. +#include "../../../RendDX9Abi/NativeVtable.h" +#include "ParticleSystemManager.h" +#endif +#include "../../../RendDX9Abi/ThunkAbi.h" +#if defined(__APPLE__) +#include "../../Platform/X87Compat.h" // [CHOSEN, not recovered] x87 conversion results, including invalid inputs. +#endif #include "ParticleSystemManager.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../../Math/PortableX87.h" +#endif #include "../XpLightManager.h" #include "../StaticMesh.h" #include "../HemiMapManager/HemiMapManager.h" #include "../../Math/Mat4.h" +#include "../../GeomMisc/Debug.h" +#include "../../GeomMisc/DebugTextWriter.h" +#include "../../GeomMisc/DebugRenderer.h" +#include "../../Core/StringUtil.h" +#include "../../Core/ConsoleObjectMacro.h" +#include "../../Core/ConsoleObjects.h" +#include "../../Core/SettingsRepostitory.h" #include "../../Math/Frustum.h" +#include "../../RendDX9/RendDX9Math.h" // the RendDX9.dll Math copies #include "../../RendDX9/ShaderParameter.h" +#include "../../RendDX9/QueueProfiler.h" // the draw wrappers' profiler scopes #include "ParticleTemplateResources.h" #include "ParticleRendererCallbacks.h" #include "MeshParticleMesh/MeshParticleMesh.h" // G1: the mesh renderer draws through it #include "MeshParticleMesh/MeshParticleMeshTemplate.h" // G1: g_meshParticleMeshEffectState #include "../../Game/Objects/Fx/IEffectController.h" -#if !BF2_PLUGIN_ABI_NATIVE -#define CORE_CLASSMANAGER_H -#endif #include "../../Game/Objects/IObject.h" #include "../../Game/Objects/ObjectLayoutAccess.h" // psmOwnerRootDisabled - typed (RW-266) #include "../../Scene/Object/WindManager.h" #include "../../Physics/HeightmapCluster.h" -#if !BF2_PLUGIN_ABI_NATIVE -#undef CORE_CLASSMANAGER_H -#endif #include "../../Game/Main/IVideoOptions.h" #include "../../RendDX9/RendDX9Base.h" +#include "../LcgRandom.h" // lcgrandStep (PE 0x1009EF30) #include "../../RendDX9/TextureAtlas/TextureAtlas.h" #include "../../../RendDX9Abi/HfeAbi.h" #include "../../../RendDX9Abi/ModuleCommon.h" #include "../../../RendDX9Abi/BfMemory.h" #include "../../../RendDX9Abi/Frontier.h" #include "../../../RendDX9Abi/PluginEntry.h" -#include "../../../RendDX9Abi/Vc71String.h" -#include "../../../RendDX9Abi/Vc71Vector.h" +#include #include "../../RendMisc/IRenderView.h" #include "../../RendMisc/IRenderer.h" @@ -45,8 +60,15 @@ #include #include #include +#include #include +#include #include +#include +// [CHOSEN, not recovered] Only the Windows x64 arm of psmParticleRound uses SSE; arm64 has no xmmintrin.h. +#if defined(_WIN32) && !defined(_M_IX86) +#include +#endif namespace dice { namespace hfe { @@ -87,17 +109,32 @@ extern IBase* g_ParticleSystemManager; // ModuleGeom.cpp, dword_10 extern const unsigned int CID_ParticleSystemManager = 821017u; extern const unsigned int IID_IParticleSystemManager = 820016u; -// The shipped object size, from the factory's engine-alloc (push 8CB8h; 0x100B070F). -static const unsigned int kParticleSystemManagerSize = 0x8CB8u; +// The retail object is 0x8CB8 bytes (the factory's engine-alloc, push 8CB8h; 0x100B070F). The +// native object holds std containers, so it is allocated at sizeof and placement-constructed. + +// The manager's internal instance lists: the render buckets and the two pending queues. +typedef std::vector ParticleSystemInstanceVector; -// Faithfully-sized layout. The thirteen VC7.1 vectors, three 12-byte tree headers, four embedded -// particle renderers and every scalar are placed from the constructor/destructor and public-body -// accesses. Renderer/tree internals stay opaque: their concrete element classes remain separate -// recovery work, but no member after them is allowed to float to a guessed offset. +// Members in shipped order, placed from the constructor/destructor and public-body accesses; the +// `+0xNN` comments are the retail offsets. The active-instance list is the std::vector that +// getInstances (+0x38) hands to BF2.exe. The two template registries the retail +// object embeds at +0xC0 and +0xF8 are the file-scope maps below. The four embedded renderers stay +// opaque byte spans in their recovered layout (x64 placement: ParticleRawLayout.h); their pointer +// lists are std::vectors constructed in place (particleRendererList). struct ParticleSystemManager { int release(); void* deletingDestructor(int flags); + void setDrawStats(bool value); + bool getDrawStats() const; + void setDrawBoundingBoxEnable(bool value); + bool getDrawBoundingBoxEnable(); + void setStartFadePercentageOfViewDistance(float value); + float getStartFadePercentageOfViewDistance() const; + void setViewDistance(float value); + float getViewDistance() const; + void setStartLodPercentageOfLodDistance(float value); + float getStartLodPercentageOfLodDistance() const; /* +0x00 */ const void** m_vptr; /* +0x04 */ int m_refCount; @@ -105,33 +142,32 @@ struct ParticleSystemManager /* +0x0C */ unsigned char m_paused; /* +0x0D */ unsigned char m_pad0D[3]; /* +0x10 */ ParticleSystemInstanceList m_instances; - /* +0x20 */ ParticleSystemInstanceList m_renderBuckets[10]; - /* +0xC0 */ unsigned char m_templatesByNameTree[12]; - /* +0xCC */ ParticleSystemInstanceList m_pendingDestroy; - /* +0xDC */ ParticleSystemInstanceList m_pendingClassification; - /* +0xEC */ unsigned char m_pendingReclassificationTree[12]; - /* +0xF8 */ unsigned char m_templatesByIdTree[12]; + /* +0x20 */ ParticleSystemInstanceVector m_renderBuckets[10]; + /* +0xCC */ ParticleSystemInstanceVector m_pendingDestroy; + /* +0xDC */ ParticleSystemInstanceVector m_pendingClassification; + /* +0xEC */ std::set m_pendingReclassification; /* +0x104 */ void* m_type0PoolBacking; - /* +0x108 */ unsigned char m_particleSystemRenderer[0x5E18]; + /* +0x108 */ alignas(void*) unsigned char m_particleSystemRenderer[kPsmSpriteRendererSize]; /* +0x5F20 */ void* m_type0FreeList; /* +0x5F24 */ int m_type0PoolCount; - /* +0x5F28 */ unsigned char m_pad5F28[4]; + /* +0x5F28 */ unsigned int m_type0LiveCount; // [INFERRED] name: pool items in use /* +0x5F2C */ void* m_type1PoolBacking; - /* +0x5F30 */ unsigned char m_meshParticlesRenderer[0x1D90]; + /* +0x5F30 */ alignas(void*) unsigned char m_meshParticlesRenderer[kPsmMeshRendererSize]; /* +0x7CC0 */ void* m_type1FreeList; /* +0x7CC4 */ int m_type1PoolCount; /* +0x7CC8 */ void* m_type2PoolBacking; - /* +0x7CCC */ unsigned char m_trailRenderer[0x0914]; + /* +0x7CCC */ alignas(void*) unsigned char m_trailRenderer[kPsmTrailRendererSize]; /* +0x85E0 */ void* m_type2FreeList; /* +0x85E4 */ int m_type2PoolCount; /* +0x85E8 */ void* m_type3PoolBacking; /* +0x85EC */ void* m_type3FreeList; /* +0x85F0 */ int m_type3PoolCount; /* +0x85F4 */ void* m_type4PoolBacking; - /* +0x85F8 */ unsigned char m_nsaParticleSystemRenderer[0x05A0]; + /* +0x85F8 */ alignas(void*) unsigned char m_nsaParticleSystemRenderer[kPsmNsaRendererSize]; /* +0x8B98 */ void* m_type4FreeList; /* +0x8B9C */ int m_type4PoolCount; - /* +0x8BA0 */ unsigned char m_opaque8BA0[8]; + /* +0x8BA0 */ unsigned int m_type4LiveCount; // [INFERRED] name: pool items in use + /* +0x8BA4 */ int m_poolCount8BA4; // applySettings: profile poolCount30 /* +0x8BA8 */ unsigned char m_forceSortedParticleType; /* +0x8BA9 */ unsigned char m_pad8BA9; /* +0x8BAA */ unsigned short m_nextTemplateId; @@ -149,7 +185,11 @@ struct ParticleSystemManager /* +0x8C10 */ unsigned char m_windEnabled; /* +0x8C11 */ unsigned char m_pad8C11[3]; /* +0x8C14 */ IBase* m_heightmapCluster; - /* +0x8C18 */ unsigned char m_opaque8C18[0x70]; + /* +0x8C18 */ unsigned char m_opaque8C18[0x2C]; + // [INFERRED] names: per-renderer draw-call counters (+0x8C44 sorted sprites, +0x8C48 NSA, + // +0x8C4C additive sprites, +0x8C50 trails), each incremented by psmCountParticleDraw. + /* +0x8C44 */ unsigned int m_drawCounters[4]; + /* +0x8C54 */ unsigned char m_opaque8C54[0x34]; /* +0x8C88 */ unsigned int m_value8C88; /* +0x8C8C */ unsigned int m_value8C8C; /* +0x8C90 */ unsigned char m_tearingDown; @@ -166,114 +206,102 @@ struct ParticleSystemManager /* +0x8CB4 */ void* m_textureAtlasHelper; }; -static_assert(offsetof(ParticleSystemManager, m_deltaTime) == 0x08, - "ParticleSystemManager delta time moved"); -static_assert(offsetof(ParticleSystemManager, m_paused) == 0x0C, - "ParticleSystemManager pause byte moved"); -static_assert(offsetof(ParticleSystemManager, m_instances) == 0x10, - "ParticleSystemManager active-instance vector moved"); -static_assert(offsetof(ParticleSystemManager, m_templatesByNameTree) == 0xC0, - "ParticleSystemManager name registry moved"); -static_assert(offsetof(ParticleSystemManager, m_particleSystemRenderer) == 0x108, - "ParticleSystemManager ParticleSystemRenderer moved"); -static_assert(offsetof(ParticleSystemManager, m_meshParticlesRenderer) == 0x5F30, - "ParticleSystemManager MeshParticles renderer moved"); -static_assert(offsetof(ParticleSystemManager, m_trailRenderer) == 0x7CCC, - "ParticleSystemManager TrailRenderer moved"); -static_assert(offsetof(ParticleSystemManager, m_nsaParticleSystemRenderer) == 0x85F8, - "ParticleSystemManager NSA renderer moved"); -static_assert(offsetof(ParticleSystemManager, m_type0FreeList) == 0x5F20, - "ParticleSystemManager type-0 free list moved"); -static_assert(offsetof(ParticleSystemManager, m_type1FreeList) == 0x7CC0, - "ParticleSystemManager type-1 free list moved"); -static_assert(offsetof(ParticleSystemManager, m_type2FreeList) == 0x85E0, - "ParticleSystemManager type-2 free list moved"); -static_assert(offsetof(ParticleSystemManager, m_type3PoolBacking) == 0x85E8, - "ParticleSystemManager type-3 pool backing moved"); -static_assert(offsetof(ParticleSystemManager, m_type4FreeList) == 0x8B98, - "ParticleSystemManager type-4 free list moved"); -static_assert(offsetof(ParticleSystemManager, m_nextTemplateId) == 0x8BAA, - "ParticleSystemManager template id counter moved"); -static_assert(offsetof(ParticleSystemManager, m_windManager) == 0x8C0C, - "ParticleSystemManager WindManager pointer moved"); -static_assert(offsetof(ParticleSystemManager, m_heightmapCluster) == 0x8C14, - "ParticleSystemManager HeightmapCluster pointer moved"); -static_assert(offsetof(ParticleSystemManager, m_poolsInitialized) == 0x8C92, - "ParticleSystemManager initialized flag moved"); -static_assert(offsetof(ParticleSystemManager, m_cachedLightValue) == 0x8C9C, - "ParticleSystemManager cached light value moved"); -static_assert(offsetof(ParticleSystemManager, m_textureAtlasHelper) == 0x8CB4, - "ParticleSystemManager atlas helper moved"); -static_assert(sizeof(ParticleSystemManager) == kParticleSystemManagerSize, - "ParticleSystemManager must retain its shipped 0x8CB8-byte size"); - namespace { // PE .CRT initializer 0x101D23D0 / destructor 0x101D8FC0, global 0x10258F3C. Every // observed use copies this string; its source-level name remains [INFERRED]. -const vc71::string g_particleAtlasPrefix("Objects/Effects/Textures/Atlas/"); +const std::string g_particleAtlasPrefix("Objects/Effects/Textures/Atlas/"); +// Native-offset renderer helpers (the x86 source fixtures address fields through them); this TU +// reaches renderer fields through the per-renderer layouts of ParticleRawLayout.h. inline unsigned int& psmRendererDword(unsigned char* renderer, unsigned int offset) { return *reinterpret_cast(renderer + offset); } -// Both retail end helpers temporarily set x87 rounding to truncate before fistp. Renderer counts -// are non-negative and remain in signed range in every practical path; this spelling preserves the -// observable truncation and the subsequent unsigned setnbe comparison without importing CRT x87 -// helpers across the plugin boundary. +// Ends the lifetime of a renderer pointer list the renderer constructor built in place. +template +void psmDestroyRendererList(unsigned char* renderer, unsigned int offset) +{ + typedef std::vector List; + particleRendererList(renderer, offset).~List(); +} + +// Both retail end helpers truncate to int32 before comparing the result as unsigned. +// Invalid inputs retain FISTP integer indefinite. inline unsigned int psmScaledLimit(unsigned int capacity, float factor) { +#if defined(__APPLE__) + return static_cast( + bf2x87::toIntTruncate(bf2x87::wide(capacity) * bf2x87::wide(factor))); +#else return static_cast( static_cast(static_cast(capacity) * static_cast(factor))); +#endif } -} // anonymous namespace - -void particleSystemManagerBeginFrame(IParticleSystemManager* managerInterface) +// [INFERRED] private names for the embedded renderer frame helpers. +// PE 0x1016F6C0 +void psmBeginSpriteFrame(unsigned char* particles) { - ParticleSystemManager* const manager = - reinterpret_cast(managerInterface); - unsigned char* const particles = manager->m_particleSystemRenderer; - unsigned char* const nsa = manager->m_nsaParticleSystemRenderer; + psmSpriteField(particles, 0) = 1; + psmSpriteField(particles, 0x1C2C) = 0; + psmSpriteField(particles, 0x1C30) = 0; + psmSpriteField(particles, 0x5E14) = 0; +} - // 0x100D2E80 -> 0x1016F6C0, then tail-call 0x1016D580. All seven writes are - // unconditional in retail, including before the manager's pool initializer has run. - particles[0x0000] = 1; - psmRendererDword(particles, 0x1C2C) = 0; - psmRendererDword(particles, 0x1C30) = 0; - psmRendererDword(particles, 0x5E14) = 0; - nsa[0x0000] = 1; - psmRendererDword(nsa, 0x0420) = 0; - psmRendererDword(nsa, 0x0444) = 0; +// PE 0x1016D580 +void psmBeginNsaFrame(unsigned char* nsa) +{ + psmNsaField(nsa, 0) = 1; + psmNsaField(nsa, 0x0420) = 0; + psmNsaField(nsa, 0x0444) = 0; } -void particleSystemManagerEndFrame(IParticleSystemManager* managerInterface) +// PE 0x1016F6E0 +void psmEndSpriteFrame(unsigned char* particles) { - ParticleSystemManager* const manager = - reinterpret_cast(managerInterface); - // PE helpers 0x1016F6E0 / 0x1016D5A0 intentionally read the scale through the published - // singleton, rather than through their embedded-renderer owner. Preserve that quirk. + psmSpriteField(particles, 0) = 0; ParticleSystemManager* const published = reinterpret_cast(g_ParticleSystemManager); const float factor = published->m_value8C08; - - unsigned char* const particles = manager->m_particleSystemRenderer; - particles[0x0000] = 0; const unsigned int particleLimit = - psmScaledLimit(psmRendererDword(particles, 0x1E10), factor); + psmScaledLimit(psmSpriteField(particles, 0x1E10), factor); const unsigned int particleCount = - psmRendererDword(particles, 0x1C2C) + psmRendererDword(particles, 0x1C30); - particles[0x1C34] = particleCount > particleLimit; + psmSpriteField(particles, 0x1C2C) + psmSpriteField(particles, 0x1C30); + psmSpriteField(particles, 0x1C34) = particleCount > particleLimit; +} + +// PE 0x1016D5A0 +void psmEndNsaFrame(unsigned char* nsa) +{ + psmNsaField(nsa, 0) = 0; + ParticleSystemManager* const published = + reinterpret_cast(g_ParticleSystemManager); + const float factor = published->m_value8C08; + const unsigned int nsaLimit = psmScaledLimit(psmNsaField(nsa, 0x0004), factor); + psmNsaField(nsa, 0x0424) = psmNsaField(nsa, 0x0420) > nsaLimit; +} + +} // anonymous namespace - unsigned char* const nsa = manager->m_nsaParticleSystemRenderer; - nsa[0x0000] = 0; - const unsigned int nsaLimit = psmScaledLimit(psmRendererDword(nsa, 0x0004), factor); - nsa[0x0424] = psmRendererDword(nsa, 0x0420) > nsaLimit; +void particleSystemManagerBeginFrame(IParticleSystemManager* managerInterface) +{ + ParticleSystemManager* const manager = reinterpret_cast(managerInterface); + psmBeginSpriteFrame(manager->m_particleSystemRenderer); + psmBeginNsaFrame(manager->m_nsaParticleSystemRenderer); +} + +// PE 0x100D2EA0 +void particleSystemManagerEndFrame(IParticleSystemManager* managerInterface) +{ + ParticleSystemManager* const manager = reinterpret_cast(managerInterface); + psmEndSpriteFrame(manager->m_particleSystemRenderer); + psmEndNsaFrame(manager->m_nsaParticleSystemRenderer); } // Defined in the emitter-type .cpp files: the recovered per-type constructors. Each takes the -// pre-allocated block (type-specific size) and the template-name std::string (vc71::string*), +// pre-allocated block (type-specific size) and the template-name std::string (std::string*), // installs the vtable + defaults, and returns the object. void* constructParticleSystemTemplateType0(void* mem, const void* nameString); // 0x2A4, sub_10177010 void* constructParticleSystemType1(void* mem, const void* nameString); // 0x238, sub_10179B70 @@ -286,28 +314,22 @@ void* constructParticleSystemType4(void* mem, const void* nameString); namespace { -template -T& psmField(ParticleSystemManager* self, unsigned int offset) -{ - return *reinterpret_cast(reinterpret_cast(self) + offset); -} - // The complete 18-slot primary vtable (0x10219978). Slots 0-3 are the reference spine and slot 17 // is the deleting destructor. Known-signature frontiers below retain their real argument lists so // even the diagnostic continue mode cannot corrupt ESP. // +0x00 addRef, +0x04 getRefCount - the shared reference-count thunks (0x1000CB20 / 0x101A9A10). -int __fastcall psm_addRef(void* self, void*) { return ++static_cast(self)->m_refCount; } -int __fastcall psm_getRc (void* self, void*) { return static_cast(self)->m_refCount; } +int RD9_THUNK psm_addRef(void* self RD9_THUNK_EDX) { return ++static_cast(self)->m_refCount; } +int RD9_THUNK psm_getRc (void* self RD9_THUNK_EDX) { return static_cast(self)->m_refCount; } // +0x08 release (0x100D7480): decrement, and at zero invoke the deleting destructor (slot 17). -int __fastcall psm_release(void* self, void*) +int RD9_THUNK psm_release(void* self RD9_THUNK_EDX) { return static_cast(self)->release(); } // +0x0C queryInterface (0x100D7440): accepts iid 1 (IBase) and 820016. -void* __fastcall psm_qi(void* self, void*, unsigned int iid) +void* RD9_THUNK psm_qi(void* self RD9_THUNK_EDX, unsigned int iid) { if (iid == RD9_IID_IBASE || iid == IID_IParticleSystemManager) return self; @@ -316,22 +338,24 @@ void* __fastcall psm_qi(void* self, void*, unsigned int iid) // +0x20, the BF2 build deliberately does nothing, but it does consume the template // pointer (`retn 4`). The old stand-in used a no-argument ret and was ABI-wrong. -void __fastcall psm_removeParticleSystem(void*, void*, IParticleSystemTemplate*) { } +void RD9_THUNK psm_removeParticleSystem(void* RD9_THUNK_EDX, IParticleSystemTemplate*) { } // +0x30 resetStats(), the BF2 build's genuine no-argument nullsub. The Editor body // clears counters and its console registration supplies the exact name. -void __fastcall psm_resetStats(void*, void*) { } +// PE 0x100D2E20 +void RD9_THUNK psm_resetStats(void* RD9_THUNK_EDX) { } +// PE 0x100D2E30. // +0x10, virtual-call resetStats(), then reacquire WindManager. `postLoadLevel` is NOT // this slot: Editor ResourceManager::postLoadLevel names and directly calls the 0x101C3470 twin of // BF2 0x100D2FD0, which only reacquires HeightmapCluster at +0x8C14. The ctor invokes this +0x10 // behavior inline, so `init` is the supported interpretation; the exact source spelling remains // unresolved. BF2 0x100D38D0 is instead the unnamed lazy pool/atlas initializer. -void __fastcall psm_reserved10(void* self, void*) +void RD9_THUNK psm_reserved10(void* self RD9_THUNK_EDX) { reinterpret_cast(self)->resetStats(); renddx9abi::HostString name("WindManager"); - *reinterpret_cast(static_cast(self) + 0x8C0C) = + static_cast(self)->m_windManager = // +0x8C0C classManager->getSingleton(name); } @@ -342,8 +366,9 @@ IParticleSystemInstance* psmCreateType2Instance(IParticleSystemTemplate* descrip IParticleSystemInstance* psmCreateType3Instance(IParticleSystemTemplate* descriptor); IParticleSystemInstance* psmCreateType4Instance(IParticleSystemTemplate* descriptor); const char* psmRegisteredTemplateName(IParticleSystemTemplate* descriptor); -IParticleSystemInstance* __fastcall psm_createInstance( - void* self, void*, IParticleSystemTemplate* systemTemplate) +void psmRuntimeError(unsigned int line, const char* message); +// PE 0x100D3DA0 +IParticleSystemInstance* RD9_THUNK psm_createInstance(void* self RD9_THUNK_EDX, IParticleSystemTemplate* systemTemplate) { ParticleSystemManager* const manager = static_cast(self); if (!manager->m_poolsInitialized) @@ -364,14 +389,14 @@ IParticleSystemInstance* __fastcall psm_createInstance( ? psmCreateType3Instance(systemTemplate) : psmCreateType4Instance(systemTemplate); if (instance) { - reinterpret_cast(instance)[5] = 0; - vc71::vectorRef(&manager->m_instances).push_back(instance); + psmInstance(instance, 5) = 0; + manager->m_instances.push_back(instance); } return instance; } - // Invalid template types log and return null. - ::renddx9abi::logf("ParticleSystemManager.cpp:470 Invalid template type"); + // Suppressed error diagnostics return null, as shipped. + psmRuntimeError(470, "Invalid template type"); return 0; } @@ -406,7 +431,7 @@ inline bool psmOwnerRootDisabled(void* owner) // +0x18, 0x100D4F40. Instances with live particles stop emitting and detach from their owner. // Otherwise detach the controller before queuing inactive removal and destruction. -void __fastcall psm_removeInstance(void* self, void*, IParticleSystemInstance* instance) +void RD9_THUNK psm_removeInstance(void* self RD9_THUNK_EDX, IParticleSystemInstance* instance) { ParticleSystemManager* const manager = static_cast(self); if (!manager->m_poolsInitialized || manager->m_tearingDown) @@ -422,48 +447,48 @@ void __fastcall psm_removeInstance(void* self, void*, IParticleSystemInstance* i else { instance->setEffectController(0); - if (psmRuntimeField(instance, 4)) psmQueueInactive(manager, instance); + if (psmInstance(instance, 4)) psmQueueInactive(manager, instance); psmPush(manager->m_pendingDestroy, instance); } } // +0x24, stop/release every instance, advance each by 0.1, drain twice, then assert // that the active list is empty. Both loops retain the same initial instance-count snapshot. -void __fastcall psm_reserved24(void* self, void*) +// PE 0x100D4820 +void RD9_THUNK psm_reserved24(void* self RD9_THUNK_EDX) { ParticleSystemManager* const manager = static_cast(self); psmRemoveActive(manager, false); psmDrainDestroy(manager); - const unsigned int count = manager->m_instances.size(); - for (unsigned int i = 0; i < count; ++i) manager->m_instances.first[i]->reserved02(); - for (unsigned int i = 0; i < count; ++i) manager->m_instances.first[i]->reserved41(0.1f); + const unsigned int count = static_cast(manager->m_instances.size()); + for (unsigned int i = 0; i < count; ++i) manager->m_instances[i]->reserved02(); + for (unsigned int i = 0; i < count; ++i) manager->m_instances[i]->reserved41(0.1f); psmRemoveActive(manager, false); psmDrainDestroy(manager); if (manager->m_instances.size()) - psmRuntimeError(manager, "dice::hfe::geom::ParticleSystemManager::releaseAllInstances " - "(Debug: All particle systems have not been released!)"); + psmRuntimeError(835, "All particle systems have not been released!"); // PE 0x100D48E3 } -void __fastcall psm_onPathDraw(void* self, void*, bool firstPerson, bool secondPass); +void RD9_THUNK psm_onPathDraw(void* self RD9_THUNK_EDX, bool firstPerson, bool secondPass); // +0x34, flip byte +0x0C, then broadcast it to active instances in vector order. -void __fastcall psm_togglePause(void* self, void*) +// PE 0x100D3300 +void RD9_THUNK psm_togglePause(void* self RD9_THUNK_EDX) { ParticleSystemManager* manager = static_cast(self); manager->m_paused = manager->m_paused ? 0 : 1; - const unsigned int count = manager->m_instances.size(); + const unsigned int count = static_cast(manager->m_instances.size()); for (unsigned int i = 0; i < count; ++i) - manager->m_instances.first[i]->setPaused(manager->m_paused != 0); + manager->m_instances[i]->setPaused(manager->m_paused != 0); } -// +0x40, 0x100D74A0: `vector@this+0x7CB0.resize(0, 0)`. Its elements are pointer-sized and have -// trivial destruction, so the exact observable effect is to retain storage and set last=first. -void __fastcall psm_reserved40(void* self, void*) +// +0x40, 0x100D74A0: `vector@this+0x7CB0.resize(0, 0)` - the MeshParticles renderer's retained +// mesh list (renderer +0x1D80). Its elements are pointer-sized and have trivial destruction, so the +// exact observable effect is to retain storage and empty the list. +void RD9_THUNK psm_reserved40(void* self RD9_THUNK_EDX) { - ParticleSystemInstanceList* const values = reinterpret_cast( - static_cast(self) + 0x7CB0); - values->last = values->first; + meshParticlesRendererMeshes(static_cast(self)->m_meshParticlesRenderer).clear(); } // The two template registries. The retail object embeds a std::map @@ -484,8 +509,8 @@ typedef std::map ParticleSystemNameMap g_templatesByName; -// [CHOSEN, not recovered] diagnostic identity only. Unsupported descriptor types still expose -// VC7.1 name storage in native builds, so do not interpret their getName result as HostString. +// [CHOSEN, not recovered] diagnostic identity only, read from the registry key rather than through +// a descriptor's getName. const char* psmRegisteredTemplateName(IParticleSystemTemplate* descriptor) { for (ParticleSystemNameMap::const_iterator it = g_templatesByName.begin(); @@ -497,60 +522,16 @@ const char* psmRegisteredTemplateName(IParticleSystemTemplate* descriptor) std::map g_templatesById; #include "ParticleInstanceType3Registry.inl" // G1: the emitter's child lookup (PE 100D3410) -// +0x44, scalar deleting destructor 0x100D7880. Its scalar wrapper is simple, but the complete -// destructor it calls (0x100D5610) owns the three trees, thirteen vectors, four embedded renderers, -// five pool buffers and TextureAtlas. Running that body over this replacement's intentionally -// zero-filled, unconstructed subobjects would itself be fabricated behavior. Free the inert object -// only while no deferred owner exists; otherwise stop exactly at the first missing teardown use. -bool psmHasUnrecoveredOwnedState(const ParticleSystemManager* self) -{ - if (!g_templatesByName.empty() || !g_templatesById.empty() - || self->m_instances.first || self->m_pendingDestroy.first - || self->m_pendingClassification.first || self->m_poolsInitialized - || self->m_type0PoolBacking || self->m_type1PoolBacking - || self->m_type2PoolBacking || self->m_type3PoolBacking - || self->m_type4PoolBacking || self->m_type0FreeList - || self->m_type1FreeList || self->m_type2FreeList - || self->m_type3FreeList || self->m_type4FreeList - || self->m_textureAtlasHelper) - return true; - - // Constructed renderers own allocations, declaration/effect handles and Trail's registered - // listener even before pool allocation. They must reach the existing teardown frontier too. - if (*reinterpret_cast(self->m_trailRenderer) - || *reinterpret_cast(self->m_particleSystemRenderer + 0x0C) - || *reinterpret_cast(self->m_particleSystemRenderer + 0x1DC0) - || *reinterpret_cast(self->m_particleSystemRenderer + 0x1DC8) - || *reinterpret_cast(self->m_particleSystemRenderer + 0x1E0C) - || *reinterpret_cast(self->m_particleSystemRenderer + 0x1DD0) - || *reinterpret_cast(self->m_nsaParticleSystemRenderer + 0x10) - || *reinterpret_cast(self->m_nsaParticleSystemRenderer + 0x55C) - || *reinterpret_cast(self->m_nsaParticleSystemRenderer + 0x564) - || *reinterpret_cast(self->m_nsaParticleSystemRenderer + 0x59C) - || *reinterpret_cast(self->m_nsaParticleSystemRenderer + 0x56C)) - return true; - - for (unsigned int i = 0; i < 10; ++i) - if (self->m_renderBuckets[i].first) - return true; - - // A non-null VC7.1 tree head means one of the omitted tree constructors ran and therefore its - // sentinel must be destroyed, even when the logical tree is empty. - return *reinterpret_cast(self->m_templatesByNameTree + 4) - || *reinterpret_cast(self->m_pendingReclassificationTree + 4) - || *reinterpret_cast(self->m_templatesByIdTree + 4); -} - -void* __fastcall psm_deletingDtor(void* rawSelf, void*, int flags) +void* RD9_THUNK psm_deletingDtor(void* rawSelf RD9_THUNK_EDX, int flags) { return static_cast(rawSelf)->deletingDestructor(flags); } -// 0x100D3460, called by +0x3C after copying the quality profile. The distance math and repeated -// LightManager read are exact. Retail dereferences that singleton unconditionally. Keep an explicit -// publication-failure stop for diagnostics, then use the typed evidence-scoped interface view. +// PE 0x100D3460, called by +0x3C after copying the quality profile. The LightManager +// singleton is required and is read again for the second callback. void psmRecomputeDerivedSettings(ParticleSystemManager* self) { +#if defined(_WIN32) for (unsigned int i = 0; i < 3; ++i) { const float lodScale = self->m_lodScales[i]; @@ -566,6 +547,7 @@ void psmRecomputeDerivedSettings(ParticleSystemManager* self) // PE 100D3468..100D357A uses FST, not fstp: the products remain at the // caller's x87 precision even though rounded copies are published to the fields. // The inverse denominators reload the rounded base and subtract the retained product. +#if defined(_M_IX86) __asm { fld lodScale fmul view @@ -591,13 +573,51 @@ void psmRecomputeDerivedSettings(ParticleSystemManager* self) fstp dword ptr [edx] fstp st(0) } +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). The products stay + // unrounded doubles; only the published copies are rounded to float, as with FST. + const double product = static_cast(lodScale) * view; + *base = static_cast(product); + const double nearProduct = product * nearRatio; + *nearDistance = static_cast(nearProduct); + *inverseNear = static_cast(one / (static_cast(*base) - nearProduct)); + const double farProduct = static_cast(farRatio) * *base; + *farDistance = static_cast(farProduct); + *inverseFar = static_cast(one / (static_cast(*base) - farProduct)); +#endif } - if (!g_LightManager) + // PE snapshots the old cache before the first callback and reloads the published + // LightManager for the second callback (100D357A..100D35B3). + const float previousLight = self->m_cachedLightValue; + const bool changed = previousLight != g_LightManager->getDefaultEffectLightAffectionFactor(); + self->m_cachedLightValue = g_LightManager->getDefaultEffectLightAffectionFactor(); + + if (changed) { - RD9_FRONTIER_AT("dice::hfe::geom::ParticleSystemManager::applySettings " - "(LightManager singleton publication failed)", self, 0x3C); - std::abort(); + for (ParticleSystemNameMap::iterator it = + g_templatesByName.begin(); it != g_templatesByName.end(); ++it) + it->second->refreshDerivedState(); + } +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-port.md). + for (unsigned int i = 0; i < 3; ++i) + { + const float lodScale = self->m_lodScales[i]; + const float view = self->m_effectiveViewDistance; + const float nearRatio = self->m_nearRatio; + const float farRatio = self->m_farRatio; + const float one = 1.0f; + float* const base = &self->m_baseDistances[i]; + float* const nearDistance = &self->m_nearDistances[i]; + float* const inverseNear = &self->m_inverseNearRanges[i]; + float* const farDistance = &self->m_farDistances[i]; + float* const inverseFar = &self->m_inverseFarRanges[i]; + // PE 100D3468..100D357A uses FST, not fstp: the products remain at the + // caller's x87 precision even though rounded copies are published to the fields. + // The inverse denominators reload the rounded base and subtract the retained product. + // [CHOSEN, not recovered] Preserve x87 retained near/far products with rounded base reload. + bf2x87::lod(lodScale, view, nearRatio, farRatio, *base, *nearDistance, *inverseNear, *farDistance, *inverseFar); } // PE snapshots the old cache before the first callback and reloads the published @@ -612,16 +632,16 @@ void psmRecomputeDerivedSettings(ParticleSystemManager* self) g_templatesByName.begin(); it != g_templatesByName.end(); ++it) it->second->refreshDerivedState(); } +#endif } // +0x3C applySettings, 0x100D37A0. Copies all fifteen profile words, computes the effective view // through Renderer +0x74 / VideoOptions +0x28, conditionally updates the five pool capacities, then -// runs 0x100D3460 above and sets +0x8C93. A missing LightManager stops at the named dependency; -// retail has no null guard there either. -void __fastcall psm_applySettings(void* rawSelf, void*, const ParticleSystemSettings* config) +// runs 0x100D3460 above and sets +0x8C93. Requires the LightManager singleton. +void RD9_THUNK psm_applySettings(void* rawSelf RD9_THUNK_EDX, const ParticleSystemSettings* config) { ParticleSystemManager* const self = static_cast(rawSelf); - psmField(self, 0x8CA8) = config->distanceFactor; + self->m_distanceFactor = config->distanceFactor; // +0x8CA8 const int gsViewDistance = dx9rend::readIntSetting("GSViewDistance", 500); IVideoOptions* const videoOptions = dx9rend::rendererGetVideoOptions(); @@ -630,35 +650,37 @@ void __fastcall psm_applySettings(void* rawSelf, void*, const ParticleSystemSett config->distanceFactor; if (effectiveView <= 200.0) effectiveView = 200.0; - psmField(self, 0x8CA0) = static_cast(effectiveView); + self->m_effectiveViewDistance = static_cast(effectiveView); // +0x8CA0 for (unsigned int i = 0; i < 3; ++i) { - psmField(self, 0x8BFC + i * 4) = config->tierThresholds[i]; - psmField(self, 0x8BAC + i * 4) = config->lodScales[i]; + self->m_tierThresholds[i] = config->tierThresholds[i]; // +0x8BFC + self->m_lodScales[i] = config->lodScales[i]; // +0x8BAC } - psmField(self, 0x8BDC) = config->nearRatio; - psmField(self, 0x8BF8) = config->farRatio; + self->m_nearRatio = config->nearRatio; // +0x8BDC + self->m_farRatio = config->farRatio; // +0x8BF8 - if (!psmField(self, 0x8C92)) + if (!self->m_poolsInitialized) // +0x8C92 { - psmField(self, 0x5F24) = config->poolCount04; - psmField(self, 0x85E4) = config->poolCount0C; - psmField(self, 0x8B9C) = config->poolCount04; - psmField(self, 0x7CC4) = config->poolCount08; - psmField(self, 0x8BA4) = config->poolCount30; + self->m_type0PoolCount = config->poolCount04; // +0x5F24 + self->m_type2PoolCount = config->poolCount0C; // +0x85E4 + self->m_type4PoolCount = config->poolCount04; // +0x8B9C + self->m_type1PoolCount = config->poolCount08; // +0x7CC4 + self->m_poolCount8BA4 = config->poolCount30; // +0x8BA4 } - psmField(self, 0x8CAC) = config->shaderQuality; - psmField(self, 0x8CB0) = config->qualityLevel; + self->m_shaderQuality = config->shaderQuality; // +0x8CAC + self->m_qualityLevel = config->qualityLevel; // +0x8CB0 psmRecomputeDerivedSettings(self); - psmField(self, 0x8C93) = 1; + self->m_settingsApplied = 1; // +0x8C93 } // These are the five non-polymorphic particle record constructors, not the runtime-instance // constructors behind createInstance. Only the words written by their instructions are touched; // in particular, the free-chain word is assigned by the manager after all items are constructed. +// PE 0x100D5BE0, 0x100D5C90, 0x101804D0, 0x1017A700, 0x1017E280 +// (types 1, 3, 0, 2 and 4 in that order). void psmConstructPoolRecord(unsigned int* item, unsigned int type) { static const unsigned char zero0[] = { 3,4,6,7,8,13,14,18,19,20,24,25,26,27 }; @@ -685,21 +707,26 @@ void psmConstructPoolRecord(unsigned int* item, unsigned int type) case 4: words = zero4; count = sizeof(zero4); break; } for (unsigned int i = 0; i < count; ++i) - item[words[i]] = 0; - if (type == 1 || type == 3) { - item[16] = 0x3F800000u; - item[11] = 0x3F800000u; - item[6] = 0x3F800000u; - item[1] = 0x3F800000u; + if (i == 16 && (type == 1 || type == 3)) + { + item[16] = 0x3F800000u; + item[11] = 0x3F800000u; + item[6] = 0x3F800000u; + item[1] = 0x3F800000u; + } + item[words[i]] = 0; } } // new Record[count], followed by the shipped unsigned count-1 free-chain loop. There is no -// allocation-failure or zero-count guard in PE 0x100D38D0; neither is manufactured here. +// allocation-failure or zero-count guard in preLoadLevel; neither is manufactured here. +// `retailStride` is the type's retail record size (148/192/168/176/200); x64 uses the native stride +// and free-chain link slot of ParticleRawLayout.h instead. void psmAllocatePool(void*& backing, void*& freeList, int& count, - unsigned int stride, unsigned int type) + unsigned int retailStride, unsigned int type) { + const unsigned int stride = sizeof(void*) == 4 ? retailStride : psmRecordStride(type); unsigned char* const items = static_cast( ::renddx9abi::engineAlloc(stride * static_cast(count))); if (items) @@ -707,8 +734,8 @@ void psmAllocatePool(void*& backing, void*& freeList, int& count, psmConstructPoolRecord(reinterpret_cast(items + stride * i), type); backing = items; for (unsigned int i = 0; i < static_cast(count) - 1u; ++i) - *reinterpret_cast(items + stride * i) = items + stride * (i + 1u); - *reinterpret_cast(items + stride * static_cast(count) - stride) = 0; + psmRecordLink(items + stride * i, type) = items + stride * (i + 1u); + psmRecordLink(items + stride * static_cast(count) - stride, type) = 0; freeList = backing; } @@ -718,12 +745,12 @@ T& psmRendererField(unsigned char* renderer, unsigned int offset) return *reinterpret_cast(renderer + offset); } -// Direct TrailRenderer helper the index count is in 16-bit index units. Its buffer +// PE 0x10172920. Direct TrailRenderer helper the index count is in 16-bit index units. Its buffer // null gate, failed-lock behavior and unconditional unlock after a lock attempt are shipped. void psmFillTrailIndices(unsigned char* renderer, unsigned int sides) { - const unsigned int count = psmRendererDword(renderer, 0x8AC); - void* const buffer = psmRendererField(renderer, 0x8B8 + 4u * sides); + const unsigned int count = psmTrailField(renderer, 0x8AC); + void* const buffer = psmTrailField(renderer, 0x8B8 + 4u * sides); if (!count || !buffer) return; unsigned short* const indices = static_cast( @@ -755,120 +782,202 @@ void psmFillTrailIndices(unsigned char* renderer, unsigned int sides) // The paired radial vertices intentionally coincide, and the angle step is // 360/(2*sides), so this is a half-circle fan rather than a conventional full-circle ring. -void psmCreateTrailSide(unsigned char* renderer, unsigned int sides) +// PE 0x10172B20 +bool psmCreateTrailSide(unsigned char* renderer, unsigned int sides) { const int oldPool = dx9rend::bufferManagerSwapPool(0); - psmRendererField(renderer, 0x8B8 + 4u * sides) = + psmTrailField(renderer, 0x8B8 + 4u * sides) = dx9rend::bufferManagerCreateIndexBuffer( - 6u * sides * (psmRendererDword(renderer, 0x8AC) - 1u), 8u, 101u); + 6u * sides * (psmTrailField(renderer, 0x8AC) - 1u), 8u, 101u); dx9rend::bufferManagerSwapPool(oldPool); psmFillTrailIndices(renderer, sides); Vec3* const vertices = static_cast(::renddx9abi::engineAlloc(24u * sides)); - if (vertices) + if (vertices && static_cast(2u * sides - 1u) >= 0) for (unsigned int i = 0; i < 2u * sides; ++i) new (vertices + i) Vec3{ 0.0f, 0.0f, 0.0f }; - psmRendererField(renderer, 0x8C8 + 4u * sides) = vertices; + psmTrailField(renderer, 0x8C8 + 4u * sides) = vertices; if (!vertices) { - // TrailRenderer.cpp:233, DebugTypeWarning; the caller discards the false result. - ::renddx9abi::logf("TrailRenderer.cpp:233: Failed to craete originalVertices"); - return; + ::renddx9abi::Debug(DebugTypeError, + "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\ParticleSystem\\TrailRenderer.cpp", + 233, "") << "Failed to craete originalVertices"; + return false; } +#if defined(__APPLE__) + // [CHOSEN, not recovered] Preserve the x87 division and live cosine argument. + const float step = bf2x87::store(bf2x87::wide(360.0f) / bf2x87::wide(2u * sides)); +#else const float step = static_cast(360.0 / static_cast(2u * sides)); +#endif for (unsigned int side = 0; side < sides; ++side) { +#if defined(__APPLE__) + const bf2x87::Real angle = (bf2x87::wide(side) * bf2x87::wide(step) + bf2x87::wide(step)) * + bf2x87::wide(0.01745329238474369049f); + const float sine = bf2x87::store(bf2x87::sinValue(bf2x87::wide(bf2x87::store(angle)))); + const float cosine = bf2x87::store(bf2x87::cosValue(angle)); +#else const double angle = (static_cast(side) * step + step) * static_cast(0.01745329238474369049f); // The PE rounds the sin argument through a float local, while cos consumes the // retained x87 intermediate. Keep that otherwise surprising asymmetry. const float sine = static_cast(std::sin(static_cast(angle))); const float cosine = static_cast(std::cos(angle)); +#endif vertices[side * 2u] = Vec3{ cosine, sine, 0.0f }; vertices[side * 2u + 1u] = Vec3{ cosine, sine, 0.0f }; } + return true; } // one 68-byte-stride VB followed by the 1-, 2-, and 3-sided trail IBs. -void psmCreateTrailBuffers(unsigned char* renderer) +// PE 0x10172CD0. The sole retail caller passes three maximum sides. +void psmCreateTrailBuffers(unsigned char* renderer, unsigned int maximumSides) { const int oldPool = dx9rend::bufferManagerSwapPool(0); - psmRendererDword(renderer, 0x898) = 6u * psmRendererDword(renderer, 0x8AC); - psmRendererDword(renderer, 0x894) = 68; - psmRendererDword(renderer, 0x89C) = 68u * psmRendererDword(renderer, 0x898); - psmRendererField(renderer, 0x8B4) = dx9rend::bufferManagerCreateVertexBuffer( - psmRendererDword(renderer, 0x898), 68, 0x208, "TrailRenderer"); + psmTrailField(renderer, 0x898) = 2u * maximumSides * psmTrailField(renderer, 0x8AC); + psmTrailField(renderer, 0x894) = 68; + psmTrailField(renderer, 0x89C) = 68u * psmTrailField(renderer, 0x898); + psmTrailField(renderer, 0x8B4) = dx9rend::bufferManagerCreateVertexBuffer( + psmTrailField(renderer, 0x898), 68, 0x208, "TrailRenderer"); for (unsigned int sides = 1; sides <= 3; ++sides) psmCreateTrailSide(renderer, sides); dx9rend::bufferManagerSwapPool(oldPool); } -// Allocation/reset helpers 0x1016F990, 0x1016D7C0, 0x10174AA0 and 0x10172ED0. -// They do not construct the embedded renderers or use their still-unrecovered shader state. +// A field of the sprite renderer, or of the NSA renderer when `nsa`, by retail offset. +template +T& psmParticleOrNsaField(unsigned char* renderer, bool nsa, unsigned int offset) +{ + return psmRawField(renderer, nsa ? psmNsaRendererOffset(offset) : psmSpriteRendererOffset(offset)); +} + +// PE 0x1016F990, 0x1016D7C0 +// Allocation/reset helpers (0x1016F990 sprite arm, 0x1016D7C0 NSA arm; the mesh and trail renderers have +// their own 0x10174AA0 and 0x10172ED0). Embedded renderer construction is separate from these buffer +// allocations and counter resets. void psmInitializeParticleRenderer(unsigned char* renderer, int count, bool nsa) { - psmRendererDword(renderer, nsa ? 0x004 : 0x1E10) = count; - psmRendererField(renderer, nsa ? 0x01C : 0x018) = - ::renddx9abi::engineAlloc(4u * static_cast(count)); + psmParticleOrNsaField(renderer, nsa, nsa ? 0x004 : 0x1E10) = count; + psmParticleOrNsaField(renderer, nsa, nsa ? 0x01C : 0x018) = + ::renddx9abi::engineAlloc(kPsmPointerSize * static_cast(count)); if (!nsa) - psmRendererField(renderer, 0x01C) = - ::renddx9abi::engineAlloc(4u * static_cast(count)); + psmParticleOrNsaField(renderer, nsa, 0x01C) = + ::renddx9abi::engineAlloc(kPsmPointerSize * static_cast(count)); const int oldPool = dx9rend::bufferManagerSwapPool(0); const unsigned int stride = nsa ? 72u : 64u; const unsigned int descriptor = nsa ? 0x550u : 0x1DB4u; - psmRendererDword(renderer, descriptor + 4) = 6u * static_cast(count); - psmRendererDword(renderer, descriptor) = stride; - psmRendererDword(renderer, descriptor + 8) = stride * 6u * static_cast(count); - psmRendererField(renderer, nsa ? 0x568 : 0x1DCC) = + psmParticleOrNsaField(renderer, nsa, descriptor + 4) = 6u * static_cast(count); + psmParticleOrNsaField(renderer, nsa, descriptor) = stride; + psmParticleOrNsaField(renderer, nsa, descriptor + 8) = stride * 6u * static_cast(count); + psmParticleOrNsaField(renderer, nsa, nsa ? 0x568 : 0x1DCC) = dx9rend::bufferManagerCreateVertexBuffer(6u * static_cast(count), stride, 0x208, nsa ? "NSAParticleSystemRenderer" : "ParticleSystemRenderer"); dx9rend::bufferManagerSwapPool(oldPool); const unsigned int counters = nsa ? 0x528u : 0x1D80u; - psmRendererDword(renderer, counters) = 0; - psmRendererDword(renderer, counters + 4) = 0; + psmParticleOrNsaField(renderer, nsa, counters) = 0; + psmParticleOrNsaField(renderer, nsa, counters + 4) = 0; for (unsigned int i = 0; i < 4; ++i) - psmRendererField(renderer, counters + 12 + i * 4) = 0.5f; - psmRendererDword(renderer, nsa ? 0x54C : 0x1DA4) = 0; + psmParticleOrNsaField(renderer, nsa, counters + 12 + i * 4) = 0.5f; + psmParticleOrNsaField(renderer, nsa, nsa ? 0x54C : 0x1DA4) = 0; } +// PE 0x10174AA0 void psmInitializeMeshRenderer(unsigned char* renderer, int count) { - psmRendererDword(renderer, 0x1D78) = count; - psmRendererField(renderer, 4) = - ::renddx9abi::engineAlloc(4u * static_cast(count)); - psmRendererDword(renderer, 0x1D50) = 0; - psmRendererDword(renderer, 0x1D54) = 0; + psmMeshField(renderer, 0x1D78) = count; + psmMeshField(renderer, 4) = + ::renddx9abi::engineAlloc(kPsmPointerSize * static_cast(count)); + psmMeshField(renderer, 0x1D50) = 0; + psmMeshField(renderer, 0x1D54) = 0; for (unsigned int i = 0; i < 4; ++i) - psmRendererField(renderer, 0x1D5C + i * 4) = 0.5f; - psmRendererDword(renderer, 0x1D7C) = 0; + psmMeshField(renderer, 0x1D5C + i * 4) = 0.5f; + psmMeshField(renderer, 0x1D7C) = 0; } +// PE 0x10172ED0 void psmInitializeTrailRenderer(unsigned char* renderer, int count) { - psmRendererDword(renderer, 0x8AC) = count; - psmRendererField(renderer, 24) = - ::renddx9abi::engineAlloc(4u * static_cast(count)); - psmCreateTrailBuffers(renderer); - psmRendererField(renderer, 0x868) = 300.0f; - psmRendererDword(renderer, 0x860) = 0; - psmRendererDword(renderer, 0x864) = 0; + psmTrailField(renderer, 0x8AC) = count; + psmTrailField(renderer, 24) = + ::renddx9abi::engineAlloc(kPsmPointerSize * static_cast(count)); + psmCreateTrailBuffers(renderer, 3); + psmTrailField(renderer, 0x868) = 300.0f; + psmTrailField(renderer, 0x860) = 0; + psmTrailField(renderer, 0x864) = 0; for (unsigned int i = 0; i < 4; ++i) - psmRendererField(renderer, 0x874 + i * 4) = 0.5f; - psmRendererDword(renderer, 0x890) = 0; - psmRendererField(renderer, 0x86C) = - psmRendererField(renderer, 0x868) * psmRendererField(renderer, 0x868); + psmTrailField(renderer, 0x874 + i * 4) = 0.5f; + psmTrailField(renderer, 0x890) = 0; + psmTrailField(renderer, 0x86C) = + psmTrailField(renderer, 0x868) * psmTrailField(renderer, 0x868); +} + +// PE 0x100D5200 +bool psmGenerateTexture(ParticleSystemManager* self, const std::string& atlasName) +{ + std::list textures; + for (ParticleSystemNameMap::const_iterator it = g_templatesByName.begin(); + it != g_templatesByName.end(); ++it) + { + IParticleSystemTemplate* const descriptor = it->second; + if (descriptor->getSystemType() == 0) + { + IParticleSystemTemplateType0* const sprite = + static_cast(descriptor); + if (sprite->getTextureName().size() != 0) + textures.push_back(sprite->getTextureName() + ".dds"); + } + if (descriptor->getSystemType() == 4) + { + IParticleSystemTemplateType4* const sprite = + static_cast(descriptor); + if (sprite->getTextureName().size() != 0) + textures.push_back(sprite->getTextureName() + ".dds"); + } + } + // shipped defect: if the first lookup returns its default, that temporary is + // already destroyed when its result is passed to the second lookup. + const std::string& modDirectory = settings->stringGet( + std::string("GSModDirectory"), std::string("mods/bf2")); + const std::string outputDirectory = settings->stringGet( + std::string("Editor_LevelSavePath"), modDirectory); + renddx9abi::HostStream* const stream = fileManager->open( + outputDirectory + "/" + g_particleAtlasPrefix + atlasName + ".tai", + static_cast(0), + static_cast(2), 0); + if (stream) + stream->release(); + return dx9rend::textureAtlasGenerate( + static_cast(self->m_textureAtlasHelper), + outputDirectory, g_particleAtlasPrefix + atlasName, outputDirectory, textures, false); } -// Direct PE 0x100D38D0. The image allocates fresh backing without deleting the old backing; -// preserve that ordering and leak on repeated calls. Names here are [INFERRED] from the caller. -vc71::string psmAtlasPath(const vc71::string& filename) +// The atlas path preLoadLevel builds inline: the atlas prefix plus the file name. Names here are +// [INFERRED] from the caller. +std::string psmAtlasPath(const std::string& filename) { - // vc71::string has no operator+; preserve its copy/append/result-copy sequence from + // The shipped operator+ expansion: preserve its copy/append/result-copy sequence from // 0x100D3D03..0x100D3D26, with the intermediate destroyed before loadTAI. - vc71::string prefix(g_particleAtlasPrefix); - return vc71::string(prefix += filename); + std::string prefix(g_particleAtlasPrefix); + return std::string(prefix += filename); +} + +// PE 0x100D3040: unreachable in 1.50: no code or data references. A standalone copy of the atlas +// load that psmPreLoadLevel runs inline: a non-empty filename is appended to the atlas prefix and +// loaded into the manager's atlas helper (+0x8CB4); the result is the loader's answer. The name is +// [CHOSEN, not recovered]; no instruction shows how the retail source spelled it. +bool psmLoadAtlasFile(ParticleSystemManager* self, const std::string& filename) +{ + if (!(filename.size() > 0)) + return false; + const std::string path = psmAtlasPath(filename); + return dx9rend::textureAtlasLoadTAI( + static_cast(self->m_textureAtlasHelper), path); } +// PE 0x100D38D0, the direct ResourceManager preLoadLevel call. The image allocates fresh backing +// without deleting the old backing; preserve that ordering and leak on repeated calls. void psmPreLoadLevel(ParticleSystemManager* self) { const int savedPriority = dx9rend::resourceManagerSwapDefaultPriority(5); @@ -894,10 +1003,10 @@ void psmPreLoadLevel(ParticleSystemManager* self) if (dx9rend::readBoolSetting("GSUseEffectTextureAtlas", false)) { - const vc71::string filename("ParticleAtlas.tai"); + const std::string filename("ParticleAtlas.tai"); if (!filename.empty()) { - const vc71::string path = psmAtlasPath(filename); + const std::string path = psmAtlasPath(filename); dx9rend::textureAtlasLoadTAI( static_cast(self->m_textureAtlasHelper), path); } @@ -906,13 +1015,12 @@ void psmPreLoadLevel(ParticleSystemManager* self) dx9rend::resourceManagerSwapDefaultPriority(savedPriority); } -// +0x1C createParticleSystem(type, templateName) (0x100D4D00). Look the template up by name (dedup; +// PE 0x100D4D00. +0x1C createParticleSystem(type, templateName). Look the template up by name (dedup; // one descriptor per named effect); if absent, allocate the type's object, construct it, assign a // 16-bit id, and register it in both maps. Type 0 is dice::hfe::geom::ParticleSystemTemplate // (0x2A4 bytes); the other four emitter types are reconstructed as they are first reached. // Returns the template pointer. -IParticleSystemTemplate* __fastcall psm_createParticleSystem( - void* self, void*, int type, const ParticleSystemName* name) +IParticleSystemTemplate* RD9_THUNK psm_createParticleSystem(void* self RD9_THUNK_EDX, int type, const ParticleSystemName* name) { ParticleSystemManager* const manager = static_cast(self); const char* const rawName = name->c_str(); @@ -924,48 +1032,43 @@ IParticleSystemTemplate* __fastcall psm_createParticleSystem( if (manager->m_nextTemplateId >= 0x800u) { - // Manager.cpp:371, DebugTypeError: "Too many ParticleSystemManager templates". - RD9_FRONTIER_AT("dice::hfe::geom::ParticleSystemManager::createParticleSystem " - "(template id limit 0x800)", self, 0x1C); - std::abort(); + // PE 0x100D4D70; suppressed diagnostics continue through template construction. + psmRuntimeError(371, "Too many ParticleSystemManager templates"); } - // The host-facing name follows PluginAbi (VC7.1 for retail, native std::string for the rebuilt - // client), while every render descriptor below is an internal recovered VC7.1-layout object. - // Compatibility passes the original retail object; native converts at that boundary. -#if BF2_PLUGIN_ABI_NATIVE - const vc71::string internalName(rawName); + // Every descriptor constructor below takes the name as the renderer's own string, converted + // once here from the host-facing name. + const std::string internalName(rawName); const void* const renderName = &internalName; -#else - const void* const renderName = name; -#endif void* mem = 0; switch (type) { case 0: - mem = ::renddx9abi::engineAlloc(0x2A4u); + mem = ::renddx9abi::engineAlloc(PSM_DESCRIPTOR_SIZE(0x2A4u)); if (mem) constructParticleSystemTemplateType0(mem, renderName); break; case 1: - mem = ::renddx9abi::engineAlloc(0x238u); + mem = ::renddx9abi::engineAlloc(PSM_DESCRIPTOR_SIZE(0x238u)); if (mem) constructParticleSystemType1(mem, renderName); break; case 2: - mem = ::renddx9abi::engineAlloc(0x250u); + mem = ::renddx9abi::engineAlloc(PSM_DESCRIPTOR_SIZE(0x250u)); if (mem) constructParticleSystemType2(mem, renderName); break; case 3: - mem = ::renddx9abi::engineAlloc(0x1A8u); + mem = ::renddx9abi::engineAlloc(PSM_DESCRIPTOR_SIZE(0x1A8u)); if (mem) constructParticleSystemType3(mem, renderName); break; case 4: - mem = ::renddx9abi::engineAlloc(0x27Cu); + mem = ::renddx9abi::engineAlloc(PSM_DESCRIPTOR_SIZE(0x27Cu)); if (mem) constructParticleSystemType4(mem, renderName); break; default: - ::renddx9abi::logf("createParticleSystem: unknown particle type %d name='%s'", type, rawName); - RD9_FRONTIER_AT("dice::hfe::geom::ParticleSystem unknown emitter type", self, 0x1C); - } + ::renddx9abi::Debug(DebugTypeError, + "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\ParticleSystem\\ParticleSystemManager.cpp", + 405, "") << "Invalid particleSystemType" << type; + break; + } // No allocation-null or invalid-type guard follows the retail switch: both paths run into this // store through a null descriptor. Preserve that shipped defect rather than returning nullptr. @@ -973,7 +1076,7 @@ IParticleSystemTemplate* __fastcall psm_createParticleSystem( g_templatesByName[key] = system; const unsigned short id = manager->m_nextTemplateId; - *reinterpret_cast(static_cast(mem) + 4) = id; + psmDescriptor(mem, 4) = id; ++manager->m_nextTemplateId; g_templatesById[id] = system; @@ -983,15 +1086,16 @@ IParticleSystemTemplate* __fastcall psm_createParticleSystem( } // +0x38 getter (0x100D7470). The shipped body is literally `return this + 16`: a reference/pointer -// ABI return to the active VC7.1 instance vector at byte +0x10. -ParticleSystemInstanceList* __fastcall psm_getInstances(void* self, void*) +// ABI return to the active-instance list (retail byte +0x10), the std::vector ParticleSystemManager.h +// declares. +ParticleSystemInstanceList* RD9_THUNK psm_getInstances(void* self RD9_THUNK_EDX) { return &static_cast(self)->m_instances; } // +0x28 update(dt), PE 100D5150. No pool-initialized or paused manager guard exists here. // Queue draining, preparation and all ten bucket walks retain their shipped order. -void __fastcall psm_update(void* rawSelf, void*, float dt) +void RD9_THUNK psm_update(void* rawSelf RD9_THUNK_EDX, float dt) { ParticleSystemManager* const self = static_cast(rawSelf); psmRemoveActive(self, false); @@ -1014,12 +1118,19 @@ bool psmCameraIsUnderWater() dx9rend::IRenderView* const view = static_cast(dx9rend::g_rendererBase)->getRenderView(); const float* const matrix = reinterpret_cast(view->getViewMatrixPtr()); - return matrix[13] < *reinterpret_cast( - static_cast(dx9rend::g_raShaderConstants) + 0x1BC); + return matrix[13] < *reinterpret_cast(dx9rend::raShaderConstantsAt(0x1BC)); +} + +// PE 0x100F7B50: publishes the shared particle-pass sign (Ra shader constant +0x1E0) as -1 for the +// water side and +1 otherwise; the argument is the bool the caller passes in CL. +void psmSetParticlePassSign(bool waterSide) +{ + *reinterpret_cast(dx9rend::raShaderConstantsAt(0x1E0)) = waterSide ? -1.0f : 1.0f; } // Each preparation updates the derived settings and temporarily expands the // supplied view's far plane. Empty input still executes every renderer's preparation prologue. +// PE 0x100D3680 void psmPreparePath(ParticleSystemManager* self, dx9rend::IRenderView* view, bool firstPerson, bool alternateView, bool secondPass, bool underwater) { @@ -1034,9 +1145,8 @@ void psmPreparePath(ParticleSystemManager* self, dx9rend::IRenderView* view, &self->m_renderBuckets[0], self->m_deltaTime, false); const unsigned int waterSide = secondPass != underwater ? 1u : 0u; - // PE 100F7B50 writes the shared particle-pass sign even when every bucket is empty. - *reinterpret_cast(static_cast(dx9rend::g_raShaderConstants) - + 0x1E0) = waterSide ? -1.0f : 1.0f; + // The shared particle-pass sign is written even when every bucket is empty. + psmSetParticlePassSign(waterSide != 0); psmPrepareParticleRenderer(self->m_particleSystemRenderer, view, &self->m_renderBuckets[1 + waterSide], self->m_deltaTime, false); psmPrepareMeshParticleRenderer(self->m_meshParticlesRenderer, view, @@ -1059,6 +1169,7 @@ void psmPreparePath(ParticleSystemManager* self, dx9rend::IRenderView* view, // The selector/draw order is observable even with empty classified buckets; // their genuine empty returns depend on the embedded renderer constructors and retained state. +// PE 0x100D2EC0 void psmDrawPath(ParticleSystemManager* self, dx9rend::IRenderView* view, bool firstPerson) { psmSelectParticleRenderer(self->m_particleSystemRenderer, 0); @@ -1080,19 +1191,21 @@ void psmDrawPath(ParticleSystemManager* self, dx9rend::IRenderView* view, bool f // +0x2C, PE 100D4920. Both bool arguments follow the three BF2Render call sites. Only the // uninitialized-pools return is shipped; initialized empty state takes the complete CPU path. -void __fastcall psm_onPathDraw(void* rawSelf, void*, bool firstPerson, bool secondPass) +void RD9_THUNK psm_onPathDraw(void* rawSelf RD9_THUNK_EDX, bool firstPerson, bool secondPass) { ParticleSystemManager* const self = static_cast(rawSelf); if (!self->m_poolsInitialized) return; - psmField(self, 0x1E78) = 0; - psmField(self, 0x1E7C) = 0; - psmField(self, 0x8B14) = 0; - psmField(self, 0x7C70) = 0; - psmField(self, 0x7C74) = 0; - psmField(self, 0x851C) = 0; - psmField(self, 0x8520) = 0; + // Retail manager +0x1E78/+0x1E7C, +0x8B14, +0x7C70/+0x7C74 and +0x851C/+0x8520: counters + // inside the four embedded renderers. + psmSpriteField(self->m_particleSystemRenderer, 0x1D70) = 0; + psmSpriteField(self->m_particleSystemRenderer, 0x1D74) = 0; + psmNsaField(self->m_nsaParticleSystemRenderer, 0x51C) = 0; + psmMeshField(self->m_meshParticlesRenderer, 0x1D40) = 0; + psmMeshField(self->m_meshParticlesRenderer, 0x1D44) = 0; + psmTrailField(self->m_trailRenderer, 0x850) = 0; + psmTrailField(self->m_trailRenderer, 0x854) = 0; dx9rend::IRenderView* view = static_cast(dx9rend::g_rendererBase)->getRenderViewDup(); @@ -1106,6 +1219,7 @@ void __fastcall psm_onPathDraw(void* rawSelf, void*, bool firstPerson, bool seco float effective; // PE 100D49B9..100D49DA keeps both products at the current x87 precision and // selects 200 for unordered as well as <=200. Do not spill an intermediate to double. +#if defined(_MSC_VER) && defined(_M_IX86) __asm { fld rendererDistance fmul globalViewDistance @@ -1120,6 +1234,18 @@ void __fastcall psm_onPathDraw(void* rawSelf, void*, bool firstPerson, bool seco psm_distance_selected: fstp effective } +#else +#if defined(_WIN32) + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). Only an ordered + // 200 < product keeps the product; NaN selects 200, as the C0/C2 parity test does. + const double product = static_cast(rendererDistance) * globalViewDistance * distanceFactor; + effective = static_cast(minimumDistance) < product ? static_cast(product) + : minimumDistance; +#else + // [CHOSEN, not recovered] Preserve x87 retained product and unordered minimum selection. + effective = bf2x87::effectiveDistance(rendererDistance, globalViewDistance, distanceFactor); +#endif +#endif self->m_effectiveViewDistance = effective; bool underwater = psmCameraIsUnderWater(); @@ -1134,6 +1260,31 @@ void __fastcall psm_onPathDraw(void* rawSelf, void*, bool firstPerson, bool seco } } +#if !defined(_MSC_VER) +// [CHOSEN, not recovered] Match the shared consumer interface under the native ABI. +const void* const kVtable[] = +{ + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemManager, addRef, psm_addRef), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemManager, getRef, psm_getRc), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemManager, release, psm_release), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemManager, queryInterface, psm_qi), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemManager, reserved_reacquireWindManager, psm_reserved10), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemManager, createInstance, psm_createInstance), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemManager, removeInstance, psm_removeInstance), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemManager, createParticleSystem, psm_createParticleSystem), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemManager, removeParticleSystem, psm_removeParticleSystem), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemManager, reserved_releaseAllInstances, psm_reserved24), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemManager, update, psm_update), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemManager, onPathDraw, psm_onPathDraw), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemManager, resetStats, psm_resetStats), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemManager, togglePause, psm_togglePause), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemManager, getInstances, psm_getInstances), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemManager, applySettings, psm_applySettings), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemManager, reserved_clearInternalVector, psm_reserved40), + BF2_NATIVE_DTOR(psm_deletingDtor, complete), + BF2_NATIVE_DTOR(psm_deletingDtor, deleting), +}; +#else const void* const kVtable[18] = { reinterpret_cast(&psm_addRef), // +0x00 @@ -1153,14 +1304,24 @@ const void* const kVtable[18] = reinterpret_cast(&psm_getInstances), // +0x38 active-vector getter reinterpret_cast(&psm_applySettings), // +0x3C applySettings recovered boot surface reinterpret_cast(&psm_reserved40), // +0x40 resize aux vector to zero - reinterpret_cast(&psm_deletingDtor), // +0x44 deleting destructor [FRONTIER if owned] + reinterpret_cast(&psm_deletingDtor), // +0x44 deleting destructor }; +#endif } // anonymous namespace -// G1: the type-3 descriptor's slot 89 (ParticleSystemTemplateType3.cpp, PE 101868F0) -// resolves its child through this manager's name registry at once - PE 100D3410, a manager member it -// calls on ds:1024B900. The registry is g_templatesByName (ParticleInstanceType3Registry.inl). +// PE 0x100F7AB0: the out-of-line copy of the underwater test that the particle instances' reserved03 +// bodies call. `position` is `this` in ECX; true only when position.y is ordered below the Ra shader +// constant +0x1BC (an unordered comparison answers false). The instance sources inline the same +// comparison. +bool particlePositionIsUnderwater(const Vec3& position) +{ + return position.y < *reinterpret_cast(dx9rend::raShaderConstantsAt(0x1BC)); +} + +// G1: the type-3 descriptor's slot 89 (ParticleSystemTemplateType3.cpp's n3_s89) resolves its child +// through this manager's name registry at once - psmFindTemplateByName, a manager member it calls +// on ds:1024B900. The registry is g_templatesByName (ParticleInstanceType3Registry.inl). IParticleSystemTemplate* particleSystemManagerFindTemplateByName(const char* name) { return psmFindTemplateByName(name); @@ -1180,6 +1341,21 @@ void particleSystemManagerPostLoadLevel(IParticleSystemManager* manager) self->m_heightmapCluster = classManager->getSingleton(name); } +IBase* particleSystemManagerHeightmapCluster(IBase* manager) +{ + return reinterpret_cast(manager)->m_heightmapCluster; // +0x8C14 +} + +unsigned char* particleSystemManagerMeshParticlesRenderer(IBase* manager) +{ + return reinterpret_cast(manager)->m_meshParticlesRenderer; // +0x5F30 +} + +unsigned char particleSystemManagerForceSortedParticles(IBase* manager) +{ + return reinterpret_cast(manager)->m_forceSortedParticleType; // +0x8BA8 +} + // Releases level resources allocated by psmPreLoadLevel. // Both level unload and the manager destructor must run this sweep. namespace { @@ -1192,8 +1368,8 @@ namespace { // last reference (the store sits after the refcount branch's join). void psmReleaseParticleRenderer(unsigned char* renderer) { - void*& first = psmRendererField(renderer, 0x018); - void*& second = psmRendererField(renderer, 0x01C); + void*& first = psmSpriteField(renderer, 0x018); + void*& second = psmSpriteField(renderer, 0x01C); if (first) { ::renddx9abi::engineFree(first); @@ -1201,7 +1377,7 @@ void psmReleaseParticleRenderer(unsigned char* renderer) first = 0; second = 0; } - void*& vertexBuffer = psmRendererField(renderer, 0x1DCC); + void*& vertexBuffer = psmSpriteField(renderer, 0x1DCC); if (vertexBuffer) { dx9rend::vertexBufferRelease(vertexBuffer); // --[+4]; 10014510; free @@ -1213,7 +1389,7 @@ void psmReleaseParticleRenderer(unsigned char* renderer) // psmInitializeMeshRenderer: the one pointer array at +0x04. void psmReleaseMeshRenderer(unsigned char* renderer) { - void*& items = psmRendererField(renderer, 0x04); + void*& items = psmMeshField(renderer, 0x04); if (items) { ::renddx9abi::engineFree(items); @@ -1221,17 +1397,17 @@ void psmReleaseMeshRenderer(unsigned char* renderer) } } -// Releases the trail buffers and clears the segment count last. +// PE 0x10172F50. Releases the trail buffers and clears the segment count last. // Vertex arrays are freed only when the corresponding index buffer exists; their slots stay dangling. void psmReleaseTrailRenderer(unsigned char* renderer) { - void*& items = psmRendererField(renderer, 0x018); + void*& items = psmTrailField(renderer, 0x018); if (items) { ::renddx9abi::engineFree(items); items = 0; } - void*& vertexBuffer = psmRendererField(renderer, 0x8B4); + void*& vertexBuffer = psmTrailField(renderer, 0x8B4); if (vertexBuffer) { dx9rend::vertexBufferRelease(vertexBuffer); // --[+4]; 10014510; free @@ -1239,29 +1415,29 @@ void psmReleaseTrailRenderer(unsigned char* renderer) } for (unsigned int side = 0; side < 3u; ++side) // [ebp-4] = 3, counted down { - void*& indexBuffer = psmRendererField(renderer, 0x8BC + 4u * side); + void*& indexBuffer = psmTrailField(renderer, 0x8BC + 4u * side); if (indexBuffer) { dx9rend::indexBufferRelease(indexBuffer); // --[+4]; 10014300; free - void* const vertices = psmRendererField(renderer, 0x8CC + 4u * side); + void* const vertices = psmTrailField(renderer, 0x8CC + 4u * side); indexBuffer = 0; // 10172FC8, before the free ::renddx9abi::engineFree(vertices); // sub_1005F370 - NOT nulled } } - psmRendererDword(renderer, 0x8AC) = 0; + psmTrailField(renderer, 0x8AC) = 0; } // sub_1016D8A0 (76 B), on the NSAParticleSystemRenderer at manager+0x85F8. The inverse of // psmInitializeParticleRenderer(nsa = true): the +0x1C array and the +0x568 vertex buffer. void psmReleaseNsaParticleRenderer(unsigned char* renderer) { - void*& items = psmRendererField(renderer, 0x01C); + void*& items = psmNsaField(renderer, 0x01C); if (items) { ::renddx9abi::engineFree(items); items = 0; } - void*& vertexBuffer = psmRendererField(renderer, 0x568); + void*& vertexBuffer = psmNsaField(renderer, 0x568); if (vertexBuffer) { dx9rend::vertexBufferRelease(vertexBuffer); // --[+4]; 10014510; free @@ -1269,6 +1445,103 @@ void psmReleaseNsaParticleRenderer(unsigned char* renderer) } } +// [CHOSEN, not recovered] Keep the embedded renderers' destructor bodies beside their +// construction and unload helpers in this TU; their member release order is recovered below. +inline void psmReleaseRendererParameter(dx9rend::ParameterOwner* parameter) +{ + if (parameter) parameter->release(); +} + +// PE 0x1016DF60. Unlike the sprite destructor, this also releases the pool-sized array/VB. +void psmDestroyNsaParticleRenderer(unsigned char* renderer) +{ + psmReleaseNsaParticleRenderer(renderer); + psmReleaseRendererParameter(psmNsaField(renderer, 0x570)); + psmReleaseRendererParameter(psmNsaField(renderer, 0x574)); + psmReleaseRendererParameter(psmNsaField(renderer, 0x578)); + psmReleaseRendererParameter(psmNsaField(renderer, 0x57C)); + psmReleaseRendererParameter(psmNsaField(renderer, 0x588)); + psmReleaseRendererParameter(psmNsaField(renderer, 0x580)); + psmReleaseRendererParameter(psmNsaField(renderer, 0x584)); + psmReleaseRendererParameter(psmNsaField(renderer, 0x590)); + psmReleaseRendererParameter(psmNsaField(renderer, 0x58C)); + dx9rend::Effect* const effect = psmNsaField(renderer, 0x56C); + if (effect) dx9rend::effectRelease(effect); + psmReleaseRendererParameter(psmNsaField(renderer, 0x594)); + psmReleaseRendererParameter(psmNsaField(renderer, 0x598)); + if (psmNsaField(renderer, 0x59C)) + dx9rend::vertexDeclarationRelease(psmNsaField(renderer, 0x59C)); + if (psmNsaField(renderer, 0x564)) + ::renddx9abi::engineFree(psmNsaField(renderer, 0x564)); + if (psmNsaField(renderer, 0x55C)) + ::renddx9abi::engineFree(psmNsaField(renderer, 0x55C)); + psmDestroyRendererList(renderer, psmNsaRendererOffset(0x0C)); +} + +// PE 0x10172D80. Pool buffers belong to level unload, not this parameter sweep. +void psmReleaseTrailParameters(unsigned char* renderer) +{ + psmReleaseRendererParameter(psmTrailField(renderer, 0x8E4)); + psmReleaseRendererParameter(psmTrailField(renderer, 0x8E8)); + psmReleaseRendererParameter(psmTrailField(renderer, 0x8EC)); + psmReleaseRendererParameter(psmTrailField(renderer, 0x8F0)); + psmReleaseRendererParameter(psmTrailField(renderer, 0x8F8)); + psmReleaseRendererParameter(psmTrailField(renderer, 0x8FC)); + psmReleaseRendererParameter(psmTrailField(renderer, 0x900)); + psmReleaseRendererParameter(psmTrailField(renderer, 0x904)); + psmReleaseRendererParameter(psmTrailField(renderer, 0x8F4)); + psmReleaseRendererParameter(psmTrailField(renderer, 0x8DC)); + psmReleaseRendererParameter(psmTrailField(renderer, 0x8E0)); + psmReleaseRendererParameter(psmTrailField(renderer, 0x908)); + psmReleaseRendererParameter(psmTrailField(renderer, 0x90C)); + dx9rend::Effect* const effect = psmTrailField(renderer, 0x8D8); + if (effect) dx9rend::effectRelease(effect); + if (psmTrailField(renderer, 0x910)) + dx9rend::vertexDeclarationRelease(psmTrailField(renderer, 0x910)); +} + +// PE 0x101734E0 +void psmDestroyTrailRenderer(unsigned char* renderer) +{ + psmReleaseTrailParameters(renderer); + dx9rend::unregisterDeviceLostResetListener(reinterpret_cast(renderer)); + psmDestroyRendererList(renderer, psmTrailRendererOffset(8)); +} + +// PE 0x101751F0. +void psmDestroyMeshParticleRenderer(unsigned char* renderer) +{ + psmDestroyRendererList(renderer, psmMeshRendererOffset(0x1D80)); +} + +// PE 0x10170F60. The effect is released between the two parameter groups as shipped. +void psmDestroyParticleRenderer(unsigned char* renderer) +{ + psmReleaseRendererParameter(psmSpriteField(renderer, 0x1DD4)); + psmReleaseRendererParameter(psmSpriteField(renderer, 0x1DD8)); + psmReleaseRendererParameter(psmSpriteField(renderer, 0x1DDC)); + psmReleaseRendererParameter(psmSpriteField(renderer, 0x1DE0)); + psmReleaseRendererParameter(psmSpriteField(renderer, 0x1DEC)); + psmReleaseRendererParameter(psmSpriteField(renderer, 0x1DE4)); + psmReleaseRendererParameter(psmSpriteField(renderer, 0x1DE8)); + dx9rend::Effect* const effect = psmSpriteField(renderer, 0x1DD0); + if (effect) dx9rend::effectRelease(effect); + psmReleaseRendererParameter(psmSpriteField(renderer, 0x1DF0)); + psmReleaseRendererParameter(psmSpriteField(renderer, 0x1DF4)); + psmReleaseRendererParameter(psmSpriteField(renderer, 0x1E04)); + psmReleaseRendererParameter(psmSpriteField(renderer, 0x1E00)); + psmReleaseRendererParameter(psmSpriteField(renderer, 0x1E08)); + psmReleaseRendererParameter(psmSpriteField(renderer, 0x1DF8)); + psmReleaseRendererParameter(psmSpriteField(renderer, 0x1DFC)); + if (psmSpriteField(renderer, 0x1E0C)) + dx9rend::vertexDeclarationRelease(psmSpriteField(renderer, 0x1E0C)); + if (psmSpriteField(renderer, 0x1DC8)) + ::renddx9abi::engineFree(psmSpriteField(renderer, 0x1DC8)); + if (psmSpriteField(renderer, 0x1DC0)) + ::renddx9abi::engineFree(psmSpriteField(renderer, 0x1DC0)); + psmDestroyRendererList(renderer, psmSpriteRendererOffset(8)); +} + } // anonymous namespace // Releases level particle instances, descriptors, registries, pools and atlas contents. @@ -1276,6 +1549,7 @@ void psmReleaseNsaParticleRenderer(unsigned char* renderer) // instance destructors must not read them. Teardown suppresses removeInstance callbacks. // Pending classification and stale pool pointers remain until preLoadLevel reinitializes them. // [CHOSEN, not recovered] registry storage uses the file-scope maps with case-insensitive names. +// PE 0x100D4A70 void particleSystemManagerUnloadLevel(IParticleSystemManager* manager) { ParticleSystemManager* const self = reinterpret_cast(manager); @@ -1294,30 +1568,28 @@ void particleSystemManagerUnloadLevel(IParticleSystemManager* manager) it->second->destroy(); // +0x00 (1) } - for (IParticleSystemInstance** cursor = self->m_instances.first; - cursor != self->m_instances.last; ++cursor) + const ParticleSystemInstanceList::iterator instancesEnd = self->m_instances.end(); + for (ParticleSystemInstanceList::iterator cursor = self->m_instances.begin(); + cursor != instancesEnd; ++cursor) { if (*cursor) (*cursor)->destroy(); // +0x00 (1) } - // sub_100D6B90(0, 0) = resize(0) on a vector of raw pointers: last = first, storage kept. - self->m_pendingDestroy.last = self->m_pendingDestroy.first; // +0xCC + // sub_100D6B90(0, 0) = resize(0) on a vector of raw pointers: emptied, storage kept. + self->m_pendingDestroy.clear(); // +0xCC static const unsigned int kBucketOrder[10] = { 0, 1, 3, 5, 2, 4, 6, 7, 9, 8 }; for (unsigned int i = 0; i < 10u; ++i) { - ParticleSystemInstanceList& bucket = self->m_renderBuckets[kBucketOrder[i]]; - bucket.last = bucket.first; // +0x20 + 0x10 * bucket + ParticleSystemInstanceVector& bucket = self->m_renderBuckets[kBucketOrder[i]]; + bucket.clear(); // +0x20 + 0x10 * bucket } g_templatesByName.clear(); // sub_100D6C20 + relink g_templatesById.clear(); // sub_100D5F40 walk + relink - if (self->m_instances.first) - ::renddx9abi::engineFree(self->m_instances.first); - self->m_instances.first = 0; - self->m_instances.last = 0; - self->m_instances.endStorage = 0; + // The shipped body frees the active list's storage and zeroes its three words. + ParticleSystemInstanceList().swap(self->m_instances); self->m_nextTemplateId = 0; // +0x8BAA psmReleaseParticleRenderer(self->m_particleSystemRenderer); @@ -1338,25 +1610,26 @@ void particleSystemManagerUnloadLevel(IParticleSystemManager* manager) // the atlas is borrowed and deliberately not null-checked. Its empty entry map // returns no region; otherwise the descriptor's extensionless resource name gains ".dds". -dx9rend::TextureAtlasEntry* particleSystemFindTextureRegion(const vc71::string& name) +// PE 0x100D30B0 +dx9rend::TextureAtlasEntry* particleSystemFindTextureRegion(const std::string& name) { ParticleSystemManager* const self = reinterpret_cast(g_ParticleSystemManager); dx9rend::TextureAtlas* const atlas = static_cast(self->m_textureAtlasHelper); - if (atlas->entries.size == 0) + if (dx9rend::textureAtlasEntryCount(atlas) == 0) return 0; - vc71::string path(name); + std::string path(name); path += ".dds"; return dx9rend::textureAtlasFind(atlas, path); } -void __fastcall particleRendererCollectSorted(void* self, void*, dx9rend::IRenderView* view, +void RD9_THUNK particleRendererCollectSorted(void* self RD9_THUNK_EDX, dx9rend::IRenderView* view, IParticleSystemInstance* instance, IParticleSystemTemplate* descriptor) { psmCollectSortedParticles(static_cast(self), view, reinterpret_cast(instance), reinterpret_cast(descriptor)); } -void __fastcall particleRendererCollectAdditive(void* self, void*, dx9rend::IRenderView* view, +void RD9_THUNK particleRendererCollectAdditive(void* self RD9_THUNK_EDX, dx9rend::IRenderView* view, IParticleSystemInstance* instance, IParticleSystemTemplate* descriptor) { psmCollectAdditiveParticles(static_cast(self), view, @@ -1371,15 +1644,37 @@ int ParticleSystemManager::release() return remaining; } -void* ParticleSystemManager::deletingDestructor(int flags) +namespace { + +// PE 0x100D5610 +void psmDestroyManager(ParticleSystemManager* self) { - if (psmHasUnrecoveredOwnedState(this)) - { - RD9_FRONTIER_AT("dice::hfe::geom::ParticleSystemManager::~ParticleSystemManager " - "(renderer/tree/pool teardown)", this, 0x44); - std::abort(); - } + // End the native container lifetimes explicitly to preserve + // the retail member order around the two registries currently held at file scope. + self->m_vptr = const_cast(kVtable); + particleSystemManagerUnloadLevel(reinterpret_cast(self)); + reinterpret_cast(self->m_textureAtlasHelper)->release(); + psmDestroyNsaParticleRenderer(self->m_nsaParticleSystemRenderer); + psmDestroyTrailRenderer(self->m_trailRenderer); + psmDestroyMeshParticleRenderer(self->m_meshParticlesRenderer); + psmDestroyParticleRenderer(self->m_particleSystemRenderer); + g_templatesById.clear(); + typedef std::set ReclassificationSet; + self->m_pendingReclassification.~ReclassificationSet(); + self->m_pendingClassification.~ParticleSystemInstanceVector(); + self->m_pendingDestroy.~ParticleSystemInstanceVector(); + g_templatesByName.clear(); + for (unsigned int i = 10; i; --i) + self->m_renderBuckets[i - 1].~ParticleSystemInstanceVector(); + self->m_instances.~ParticleSystemInstanceList(); +} + +} // anonymous namespace +// PE 0x100D7880 +void* ParticleSystemManager::deletingDestructor(int flags) +{ + psmDestroyManager(this); if (flags & 1) ::renddx9abi::engineFree(this); return this; @@ -1388,18 +1683,17 @@ void* ParticleSystemManager::deletingDestructor(int flags) // geom_ParticleSystemManager_ctor, 0x100D5870. The vtable/refcount, frame/pause fields, scalar // defaults, four embedded renderer constructors, no-op hook and WindManager lookup are recovered. -// Thirteen vector headers start empty; three trees retain the chosen representation below. +// The vectors and the pending-reclassification set (PE 100D594B..100D598D) are constructed with +// the object; the two template registries are the file-scope maps above. namespace { +// PE 0x100D5870 void constructParticleSystemManager(ParticleSystemManager* self) { self->m_vptr = const_cast(kVtable); self->m_refCount = 1; self->m_deltaTime = 0.0f; self->m_paused = 0; - // PE 100D594B..100D598D constructs the embedded ordered pointer set. Container balancing - // retains the existing VC7.1 adapter policy (RW-74); key ordering and set semantics are exact. - psmReclassification(self).construct(); // Construction includes shader/declaration requests and Trail's // device listener; allocating the pools later is a separate operation. @@ -1407,7 +1701,7 @@ void constructParticleSystemManager(ParticleSystemManager* self) psmConstructParticleRenderer(self->m_particleSystemRenderer); self->m_type0FreeList = 0; self->m_type0PoolCount = 0; - psmField(self, 0x5F28) = 0; + self->m_type0LiveCount = 0; // +0x5F28 self->m_type1PoolBacking = 0; psmConstructMeshParticleRenderer(self->m_meshParticlesRenderer); self->m_type1FreeList = 0; @@ -1423,35 +1717,41 @@ void constructParticleSystemManager(ParticleSystemManager* self) psmConstructNsaParticleRenderer(self->m_nsaParticleSystemRenderer); self->m_type4FreeList = 0; self->m_type4PoolCount = 0; - psmField(self, 0x8BA0) = 0; - psmField(self, 0x8BA4) = 0; - - // Scalar defaults from 0x100D5870. The factory still zero-fills the unrecovered tree headers - // and padding; that representation is [CHOSEN, not recovered], not a retail memset. - psmField(self, 0x8BA8) = 0; - psmField(self, 0x8BAA) = 0; - psmField(self, 0x8BAC) = 0.3f; - psmField(self, 0x8BB0) = 0.6f; - psmField(self, 0x8BB4) = 1.0f; - psmField(self, 0x8BDC) = 0.7f; - psmField(self, 0x8BF8) = 0.85f; - psmField(self, 0x8BFC) = 0.4f; - psmField(self, 0x8C00) = 0.55f; - psmField(self, 0x8C04) = 0.7f; - psmField(self, 0x8C08) = 0.75f; - psmField(self, 0x8C0C) = 0; - psmField(self, 0x8C10) = 1; - psmField(self, 0x8C88) = 1024u; - psmField(self, 0x8C8C) = 1024u; - psmField(self, 0x8C90) = 0; - psmField(self, 0x8C91) = 0; - psmField(self, 0x8C92) = 0; - psmField(self, 0x8C93) = 0; - psmField(self, 0x8C9C) = -1.0f; - psmField(self, 0x8CA4) = 10.0f; - psmField(self, 0x8CA8) = 1.0f; - psmField(self, 0x8CAC) = 3u; - psmField(self, 0x8CB0) = 2u; + self->m_type4LiveCount = 0; // +0x8BA0 + self->m_poolCount8BA4 = 0; // +0x8BA4 + + // Scalar defaults from 0x100D5870. The factory value-initialises the unrecovered opaque spans + // and padding; that zero fill is [CHOSEN, not recovered], not a retail memset. + self->m_forceSortedParticleType = 0; // +0x8BA8 + self->m_nextTemplateId = 0; // +0x8BAA + self->m_lodScales[0] = 0.3f; // +0x8BAC + self->m_lodScales[1] = 0.6f; // +0x8BB0 + self->m_lodScales[2] = 1.0f; // +0x8BB4 + for (unsigned int i = 0; i < 3; ++i) self->m_baseDistances[i] = 0.0f; + for (unsigned int i = 0; i < 3; ++i) self->m_inverseNearRanges[i] = 0.0f; + for (unsigned int i = 0; i < 3; ++i) self->m_nearDistances[i] = 0.0f; + self->m_nearRatio = 0.7f; // +0x8BDC + for (unsigned int i = 0; i < 3; ++i) self->m_inverseFarRanges[i] = 0.0f; + for (unsigned int i = 0; i < 3; ++i) self->m_farDistances[i] = 0.0f; + self->m_farRatio = 0.85f; // +0x8BF8 + self->m_tierThresholds[0] = 0.4f; // +0x8BFC + self->m_tierThresholds[1] = 0.55f; // +0x8C00 + self->m_tierThresholds[2] = 0.7f; // +0x8C04 + self->m_value8C08 = 0.75f; // +0x8C08 + self->m_windManager = 0; // +0x8C0C + self->m_windEnabled = 1; // +0x8C10 + self->m_heightmapCluster = 0; // +0x8C14 + self->m_value8C88 = 1024u; // +0x8C88 + self->m_value8C8C = 1024u; // +0x8C8C + self->m_tearingDown = 0; // +0x8C90 + self->m_state8C91 = 0; // +0x8C91 + self->m_poolsInitialized = 0; // +0x8C92 + self->m_settingsApplied = 0; // +0x8C93 + self->m_cachedLightValue = -1.0f; // +0x8C9C + self->m_value8CA4 = 10.0f; // +0x8CA4 + self->m_distanceFactor = 1.0f; // +0x8CA8 + self->m_shaderQuality = 3u; // +0x8CAC + self->m_qualityLevel = 2u; // +0x8CB0 // PE 0x100D5B7F..0x100D5B9C constructs the real 20-byte TextureAtlas before +0x30 and // the WindManager lookup. The preLoadLevel atlas arm consumes this object. @@ -1464,25 +1764,25 @@ void constructParticleSystemManager(ParticleSystemManager* self) // +0x10. reinterpret_cast(self)->resetStats(); renddx9abi::HostString windName("WindManager"); - psmField(self, 0x8C0C) = classManager->getSingleton(windName); + self->m_windManager = classManager->getSingleton(windName); // +0x8C0C } } // anonymous namespace -// RefFactory_geom_ParticleSystemManager, 0x100B070F. Retail allocates the shipped size and then its -// complete ctor constructs every byte-owning subobject. Until those pool/tree constructors land, -// this rebuild explicitly zeroes the opaque spans before running the recovered ctor subset. -// [CHOSEN, not recovered] zero-fill; queryInterface/release ordering is recovered. +// RefFactory_geom_ParticleSystemManager, 0x100B070F. Retail allocates the shipped 0x8CB8 bytes and +// then its complete ctor constructs every byte-owning subobject. This rebuild allocates the native +// object, value-initialises it (zero-filling the opaque spans and constructing the std members) and +// runs the recovered ctor subset. [CHOSEN, not recovered] zero-fill; queryInterface/release +// ordering is recovered. IBase* __fastcall createParticleSystemManager(unsigned int iid, IBase* outer) { if (outer) return 0; - void* storage = ::renddx9abi::engineAlloc(kParticleSystemManagerSize); - ::memset(storage, 0, kParticleSystemManagerSize); - ParticleSystemManager* self = static_cast(storage); + void* storage = ::renddx9abi::engineAlloc(sizeof(ParticleSystemManager)); + ParticleSystemManager* self = ::new (storage) ParticleSystemManager(); constructParticleSystemManager(self); - void* itf = psm_qi(self, 0, iid); + void* itf = psm_qi(self RD9_THUNK_ARG, iid); if (!itf) self->release(); return static_cast(itf); @@ -1494,6 +1794,133 @@ unsigned int rendererRandomRaw() return psmEmissionRaw(); } +// PE 0x100D2F70. Shipped defect: setting drawStats does not write the state byte. +void ParticleSystemManager::setDrawStats(bool) { } +// PE 0x100D2F80. +bool ParticleSystemManager::getDrawStats() const { return m_state8C91 != 0; } + +// PE 0x100D2F90, 0x1016F7B0 +// The renderer leaf 0x1016F7B0 (byte store at +0x1D9D) is inlined below; 0x101748C0 is the mesh +// leaf, called through psmMeshSetDrawBoundingBox. +void ParticleSystemManager::setDrawBoundingBoxEnable(bool value) +{ + psmSpriteField(m_particleSystemRenderer, 0x1D9D) = value; + psmMeshSetDrawBoundingBox(m_meshParticlesRenderer,value); +} +// PE 0x100D2FC0, 0x1016F7C0 +// The renderer leaf 0x1016F7C0 (byte load at +0x1D9D) is inlined below: only the sprite renderer is read. +bool ParticleSystemManager::getDrawBoundingBoxEnable() +{ + return psmSpriteField(m_particleSystemRenderer, 0x1D9D) != 0; +} + +// PE 0x100D3D80 / 0x100D3010. +void ParticleSystemManager::setStartFadePercentageOfViewDistance(float value) +{ + m_farRatio = value; + psmRecomputeDerivedSettings(this); +} +// PE 0x100D3010 +float ParticleSystemManager::getStartFadePercentageOfViewDistance() const { return m_farRatio; } + +// PE 0x100D3120 / 0x100D3030: 200 is a minimum, including unordered comparisons. +void ParticleSystemManager::setViewDistance(float value) +{ +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain the x87 FCOM invalid/unordered behavior. + m_effectiveViewDistance = bf2x87::less(bf2x87::wide(200.0f), bf2x87::wide(value)) ? value : 200.0f; +#else + m_effectiveViewDistance = value > 200.0f ? value : 200.0f; +#endif +} +// PE 0x100D3030 +float ParticleSystemManager::getViewDistance() const { return m_effectiveViewDistance; } + +// PE 0x100D3630 / 0x100D3020. +void ParticleSystemManager::setStartLodPercentageOfLodDistance(float value) +{ + m_nearRatio = value; + psmRecomputeDerivedSettings(this); +} +// PE 0x100D3020 +float ParticleSystemManager::getStartLodPercentageOfLodDistance() const { return m_nearRatio; } + +namespace { + +// [INFERRED] console placement; ModuleGeom's PE initializer owns the original list. +const char kParticleSystemManagerConsoleTag[] = "geom.particleSystemManager"; +typedef unsigned int uint; + +// PE 0x100BBC2D: the particle bindings use the published global directly. +ParticleSystemManager* consoleParticleSystemManager() +{ + return static_cast(static_cast(g_ParticleSystemManager)); +} + +void consoleParticleResetStats() +{ + reinterpret_cast(g_ParticleSystemManager)->resetStats(); +} + +int consoleParticleQualityLevel() { return static_cast(consoleParticleSystemManager()->m_qualityLevel); } +void setConsoleParticleQualityLevel(int value) +{ + consoleParticleSystemManager()->m_qualityLevel = static_cast(value); +} + +BF2_CONSOLE_OBJECT("ParticleSystemManager", 2, 0) + +// Shipped duplicate: both bindings remain in the ordered list and share one executor. +// PE 0x100BB522, 0x100BB5ED, 0x100BB6F8: constructor, argument conversion, shared executor. +BF2_CONSOLE_PROPERTY(drawStats, bool, consoleParticleSystemManager(), setDrawStats, getDrawStats, kParticleSystemManagerConsoleTag) +// PE 0x100BB63A, 0x100BB6AB, 0x100BB6F8: constructor, argument conversion, shared executor. +BF2_CONSOLE_PROPERTY(drawStats, bool, consoleParticleSystemManager(), setDrawStats, getDrawStats, kParticleSystemManagerConsoleTag) +// PE 0x100BB79B: resetStats is not dynamically gated. +// PE 0x100BB749: constructor. +BF2_CONSOLE_METHOD_0_STATIC_ACTIVE(resetStats, consoleParticleResetStats, true, kParticleSystemManagerConsoleTag) +// PE 0x100BB874 / 0x100BB983 / 0x100BBA8A / 0x100BBB91. +// PE 0x100BB7B6, 0x100BB827: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(drawBoundingBoxEnable, bool, consoleParticleSystemManager(), setDrawBoundingBoxEnable, getDrawBoundingBoxEnable, kParticleSystemManagerConsoleTag) +// PE 0x100BB8C5, 0x100BB936: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(startFadePercentageOfViewDistance, float, consoleParticleSystemManager(), setStartFadePercentageOfViewDistance, getStartFadePercentageOfViewDistance, kParticleSystemManagerConsoleTag) +// PE 0x100BB9CC, 0x100BBA3D: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(viewDistance, float, consoleParticleSystemManager(), setViewDistance, getViewDistance, kParticleSystemManagerConsoleTag) +// PE 0x100BBAD3, 0x100BBB44: constructor, argument conversion. +BF2_CONSOLE_PROPERTY(startLodPercentageOfLodDistance, float, consoleParticleSystemManager(), setStartLodPercentageOfLodDistance, getStartLodPercentageOfLodDistance, kParticleSystemManagerConsoleTag) +// PE 0x100BBC39 +bool consoleParticleGenerateTexture() +{ + const std::string atlasName("ParticleAtlas"); + return psmGenerateTexture(consoleParticleSystemManager(), atlasName); +} + +// PE 0x100BBBDA (constructor), 0x100BBC39 (executor). +BF2_CONSOLE_METHOD_0_RET_ACTIVE(generateTexture, consoleParticleGenerateTexture, bool, + consoleParticleSystemManager() != 0, kParticleSystemManagerConsoleTag) +// PE 0x100BBD44 / 0x100BBE45 / 0x100BBF46 / 0x100BC04A. +// PE 0x100BBC86, 0x100BBCF7: constructor, argument conversion. +BF2_CONSOLE_FIELD(affectedByWind, bool, consoleParticleSystemManager(), m_windEnabled, kParticleSystemManagerConsoleTag) +// PE 0x100BBD87, 0x100BBDF8: constructor, argument conversion. +BF2_CONSOLE_FIELD(particleSystemShaderQuality, uint, consoleParticleSystemManager(), m_shaderQuality, kParticleSystemManagerConsoleTag) +// PE 0x100BBE88, 0x100BBEF9: constructor, argument conversion. +BF2_CONSOLE_FIELD(overdrawScale, float, consoleParticleSystemManager(), m_value8CA4, kParticleSystemManagerConsoleTag) +// PE 0x100BBF8C, 0x100BBFFD: constructor, argument conversion. +BF2_CONSOLE_PROPERTY_FN(qualityLevel, int, consoleParticleSystemManager() != 0, + consoleParticleQualityLevel(), setConsoleParticleQualityLevel, + kParticleSystemManagerConsoleTag) + +} // anonymous namespace + +bool registerParticleSystemManagerConsoleObjects() +{ + return mainConsoleObjects->registerConsoleObjects(consoleBindingList(kParticleSystemManagerConsoleTag)); +} + +bool unregisterParticleSystemManagerConsoleObjects() +{ + return mainConsoleObjects->unregisterConsoleObjects(consoleBindingList(kParticleSystemManagerConsoleTag)); +} + } // namespace geom } // namespace hfe } // namespace dice diff --git a/Code/BF2/Geom/ParticleSystem/ParticleSystemManager.h b/Code/BF2/Geom/ParticleSystem/ParticleSystemManager.h index 3299a46a7..2af48fed5 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleSystemManager.h +++ b/Code/BF2/Geom/ParticleSystem/ParticleSystemManager.h @@ -15,6 +15,8 @@ #include "../../Math/Vec3.h" #include +#include +#include namespace dice { namespace hfe { @@ -52,9 +54,11 @@ class IParticleSystemInstance virtual void reserved08() = 0; // +0x20 detach virtual void reserved09(bool value) = 0; // +0x24 virtual bool reserved10() const = 0; // +0x28 - virtual void reserved11(int value) = 0; // +0x2C - virtual int reserved12() const = 0; // +0x30 - virtual void reserved13(int value) = 0; // +0x34 + // +0x2C..+0x34 carry the owner object and the parent matrix as integers; intptr_t is `int` on + // x86 (same signature) and pointer-sized on x64. + virtual void reserved11(intptr_t value) = 0; // +0x2C + virtual intptr_t reserved12() const = 0; // +0x30 + virtual void reserved13(intptr_t value) = 0; // +0x34 virtual void* reserved14(const void* value) = 0; // +0x38 virtual const void* reserved15() const = 0; // +0x3C virtual void reserved16(const Vec3& value) = 0; // +0x40 @@ -400,35 +404,10 @@ class IParticleSystemEmitterTemplate : public IParticleSystemTemplate virtual float getSpeedFromParticle() const = 0; // +0x188 }; -// The Win32 manager returns its internal VC7.1 vector by reference at +0x38. This is renderer-owned -// storage even in the rebuilt native-host flavour, so it must keep the four-word VC7.1 layout; -// exposing std::vector here would move first from +4 to +0 on modern MSVC. This carrier is for the -// Win32 RendDX9/plugin boundary. The symbolized Linux port was used to cross-check semantics, but -// its libstdc++ vector begins at +0 and would need its own executable carrier. -struct ParticleSystemInstanceList -{ - /* +0x00 */ void* allocator; - /* +0x04 */ IParticleSystemInstance** first; - /* +0x08 */ IParticleSystemInstance** last; - /* +0x0C */ IParticleSystemInstance** endStorage; - - IParticleSystemInstance* const* begin() const { return first; } - IParticleSystemInstance* const* end() const { return last; } - - unsigned int size() const - { - return first ? static_cast(last - first) : 0u; - } -}; - -#if defined(_M_IX86) || defined(__i386__) -static_assert(sizeof(ParticleSystemInstanceList) == 16, - "ParticleSystemManager's VC7.1 instance vector must remain 16 bytes"); -static_assert(offsetof(ParticleSystemInstanceList, first) == 4, - "ParticleSystemManager's instance-vector begin pointer must remain at +4"); -static_assert(offsetof(ParticleSystemInstanceList, last) == 8, - "ParticleSystemManager's instance-vector end pointer must remain at +8"); -#endif +// The manager's active-instance vector, returned by reference at +0x38. BF2.exe +// (Game/GameLogic/Player.cpp) reads it directly: the client and its renderer share one STL +// (issue #7). +typedef std::vector ParticleSystemInstanceList; // +0x3C consumes exactly 60 bytes. Names for the four pool counts and final two renderer knobs are // unresolved; their widths, offsets, and the float fields are recovered from 0x100D37A0. @@ -472,9 +451,10 @@ class IParticleSystemManager : public IBase public: // +0x00..+0x0C: IBase quartet. - // +0x10, PE 0x100D2E30. Calls +0x30, then reacquires the WindManager singleton. The exact - // source name remains [UNRESOLVED]. postLoadLevel is the separate direct BF2 0x100D2FD0 body, - // named by the Editor caller, which reacquires HeightmapCluster at manager +0x8C14. + // +0x10 (body: psm_reserved10). Calls +0x30, then reacquires the WindManager singleton. The exact + // source name remains [UNRESOLVED]. postLoadLevel is the separate direct body + // (particleSystemManagerPostLoadLevel), named by the Editor caller, which reacquires + // HeightmapCluster at manager +0x8C14. virtual void reserved_reacquireWindManager() = 0; virtual IParticleSystemInstance* createInstance( @@ -520,13 +500,17 @@ inline IParticleSystemManager* asParticleSystemManager(IBase* base) void particleSystemManagerBeginFrame(IParticleSystemManager* manager); void particleSystemManagerEndFrame(IParticleSystemManager* manager); -// Direct ResourceManager lifecycle calls, PE 0x100D38D0 / 0x100D2FD0. The preLoadLevel +// Direct ResourceManager lifecycle calls (preLoadLevel PE 0x100D38D0, postLoadLevel 0x100D2FD0). The preLoadLevel // spelling is [INFERRED] from the Editor ResourceManager caller; no virtual slots are added. void particleSystemManagerPreLoadLevel(IParticleSystemManager* manager); void particleSystemManagerPostLoadLevel(IParticleSystemManager* manager); // Releases level instances/descriptors, queues, registries, renderer buffers, pools, and atlas. void particleSystemManagerUnloadLevel(IParticleSystemManager* manager); +// The HeightmapCluster singleton postLoadLevel stored in the manager (retail +0x8C14); borrowed, +// possibly null. No null guard on `manager`. +IBase* particleSystemManagerHeightmapCluster(IBase* manager); + } // namespace geom } // namespace hfe } // namespace dice diff --git a/Code/BF2/Geom/ParticleSystem/ParticleSystemTemplate.cpp b/Code/BF2/Geom/ParticleSystem/ParticleSystemTemplate.cpp index db2cd7969..66fc7a544 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleSystemTemplate.cpp +++ b/Code/BF2/Geom/ParticleSystem/ParticleSystemTemplate.cpp @@ -2,15 +2,22 @@ // Owns direct textures when the requested region is not in the particle atlas. #ifdef BF2_IMAGE_RENDDX9 +#if !defined(_MSC_VER) +// [CHOSEN, not recovered] Compiler-typed native table entries. +#include "../../../RendDX9Abi/NativeVtable.h" +#include "ParticleSystemManager.h" +#endif +#include "../../../RendDX9Abi/ThunkAbi.h" #include "../XpLightManager.h" #include "ParticleTemplateResources.h" #include "ParticleRendererCallbacks.h" +#include "../../Platform/X87Compat.h" #include "../../../RendDX9Abi/HfeAbi.h" #include "../../../RendDX9Abi/ModuleCommon.h" #include "../../../RendDX9Abi/BfMemory.h" #include "../../../RendDX9Abi/Frontier.h" -#include "../../../RendDX9Abi/Vc71String.h" +#include #include #include @@ -29,191 +36,273 @@ extern IBase* g_ParticleSystemManager; namespace { -// [CHOSEN, not recovered] Native BF2 passes std::string through the descriptor interface; retail passes -// VC7.1 string. Each object owns its host strings in the original 28-byte reserved spans. -// Current x86 native strings occupy 24 bytes, so every subsequent descriptor offset is retained. +// [CHOSEN, not recovered] BF2 passes std::string through the descriptor interface. Each object owns +// its host strings in the original 28-byte reserved spans. Current x86 strings occupy 24 bytes, so +// every subsequent descriptor offset is retained; x64 places them in 32-byte tail slots +// (ParticleRawLayout.h). using ParticleHostString = ::renddx9abi::HostString; -static_assert(sizeof(ParticleHostString) <= 28, "particle host string exceeds its reserved span"); +static_assert(sizeof(ParticleHostString) <= kPsmDescriptorStringSpan, "particle host string exceeds its reserved span"); // Byte-offset field accessors over the raw 0x2A4 object; offsets copied verbatim from the shipped -// bodies. `self` is the object base. -inline unsigned& U (void* p, unsigned off) { return *reinterpret_cast(static_cast(p) + off); } -inline float& F (void* p, unsigned off) { return *reinterpret_cast(static_cast(p) + off); } -inline unsigned char& Bt(void* p, unsigned off) { return *reinterpret_cast(static_cast(p) + off); } -inline short& S16(void* p, unsigned off){ return *reinterpret_cast(static_cast(p) + off); } +// bodies and placed through ParticleRawLayout.h. `self` is the object base. +inline unsigned& U (void* p, unsigned off) { return psmDescriptor0(p, off); } +inline float& F (void* p, unsigned off) { return psmDescriptor0(p, off); } +inline unsigned char& Bt(void* p, unsigned off) { return psmDescriptor0(p, off); } +inline short& S16(void* p, unsigned off){ return psmDescriptor0(p, off); } inline unsigned fbits(float f) { unsigned u; ::memcpy(&u, &f, 4); return u; } // Cross-called methods (recompute / cascade) - forward declared. -void __fastcall pt_s2 (void* s, void*); -void __fastcall pt_s45 (void* s, void*, unsigned v); -void __fastcall pt_s114(void* s, void*, int type); -void __fastcall pt_s150(void* s, void*, unsigned a); +void RD9_THUNK pt_s2 (void* s RD9_THUNK_EDX); +void RD9_THUNK pt_s45 (void* s RD9_THUNK_EDX, PsmFloatArg v); +void RD9_THUNK pt_s114(void* s RD9_THUNK_EDX, int type); +void RD9_THUNK pt_s150(void* s RD9_THUNK_EDX, unsigned a); void pt_particleUpdateDeferred(); void templateRecomputeUV(void* self); // The repetitive property accessors. Every scalar arg arrives as a 4-byte stack slot (float bits read // as unsigned store identically); byte setters store the low byte. All match __thiscall callee-cleans // (the unused 2nd param is the EDX shadow). -#define PT_SETF(name, off) void __fastcall name(void* s, void*, unsigned v){ U(s,(off)) = v; } -#define PT_GETF(name, off) float __fastcall name(void* s, void*){ return F(s,(off)); } -#define PT_SETD(name, off) void __fastcall name(void* s, void*, unsigned v){ U(s,(off)) = v; } -#define PT_GETD(name, off) unsigned __fastcall name(void* s, void*){ return U(s,(off)); } -#define PT_SETB(name, off) void __fastcall name(void* s, void*, unsigned v){ Bt(s,(off)) = static_cast(v); } -#define PT_GETB(name, off) unsigned __fastcall name(void* s, void*){ return Bt(s,(off)); } -#define PT_LEA(name, off) void* __fastcall name(void* s, void*){ return static_cast(s) + (off); } -#define PT_SETVEC(name, off, n) void __fastcall name(void* s, void*, const float* v){ for (int i=0;i<(n);++i) F(s,(off)+4u*i)=v[i]; } -#define PT_GETVEC(name, off, n) void* __fastcall name(void* s, void*, float* o){ for (int i=0;i<(n);++i) o[i]=F(s,(off)+4u*i); return o; } +#define PT_SETF(name, off) void RD9_THUNK name(void* s RD9_THUNK_EDX, unsigned v){ U(s,(off)) = v; } +#define PT_SETFLT(name, off) void RD9_THUNK name(void* s RD9_THUNK_EDX, PsmFloatArg v){ U(s,(off)) = psmFloatArgBits(v); } +#define PT_GETF(name, off) float RD9_THUNK name(void* s RD9_THUNK_EDX){ return F(s,(off)); } +#define PT_SETD(name, off) void RD9_THUNK name(void* s RD9_THUNK_EDX, unsigned v){ U(s,(off)) = v; } +#define PT_GETD(name, off) unsigned RD9_THUNK name(void* s RD9_THUNK_EDX){ return U(s,(off)); } +#define PT_SETB(name, off) void RD9_THUNK name(void* s RD9_THUNK_EDX, unsigned v){ Bt(s,(off)) = static_cast(v); } +#define PT_GETB(name, off) unsigned RD9_THUNK name(void* s RD9_THUNK_EDX){ return Bt(s,(off)); } +#define PT_LEA(name, off) void* RD9_THUNK name(void* s RD9_THUNK_EDX){ return &psmDescriptor0(s, (off)); } +#define PT_SETVEC(name, off, n) void RD9_THUNK name(void* s RD9_THUNK_EDX, const float* v) \ +{ \ + if ((n)==3 || (n)==4) \ + { \ + const float z=v[2],y=v[1],x=v[0]; \ + const float w=(n)==4 ? v[3] : 0.0f; \ + F(s,(off)+4)=y; F(s,(off))=x; F(s,(off)+8)=z; \ + if ((n)==4) F(s,(off)+12)=w; \ + } \ + else for (int i=0;i<(n);++i) F(s,(off)+4u*i)=v[i]; \ +} +#define PT_GETVEC(name, off, n) void* RD9_THUNK name(void* s RD9_THUNK_EDX, float* o) \ +{ \ + const float y=F(s,(off)+4),x=F(s,(off)); \ + const float z=(n)==3 ? F(s,(off)+8) : 0.0f; \ + o[1]=y; o[0]=x; if ((n)==3) o[2]=z; return o; \ +} // simple slots (index; byte offset in the comment) -const ParticleHostString& __fastcall pt_s1(void* self, void*) -{ return *reinterpret_cast(static_cast(self) + 0x240); } +const ParticleHostString& RD9_THUNK pt_s1(void* self RD9_THUNK_EDX) +{ return psmDescriptor0(self, 0x240); } +// PE 0x10178B60 PT_SETD(pt_s4, 0x60) PT_GETD(pt_s5, 0x60) PT_SETD(pt_s6, 0x64) PT_GETD(pt_s7, 0x64) PT_SETD(pt_s8, 0x68) PT_GETD(pt_s9, 0x68) -void __fastcall pt_s10(void* s, void*, unsigned a, unsigned b, unsigned c){ U(s,0x18)=a; U(s,0x1C)=b; U(s,0x20)=c; } // 3 scalar args +// PE 0x10178F70 +void RD9_THUNK pt_s10(void* s RD9_THUNK_EDX, PSM_VEC3_PARAMS){ U(s,0x18)=PSM_VEC3_X; U(s,0x1C)=PSM_VEC3_Y; U(s,0x20)=PSM_VEC3_Z; } // Vec3 by value +// PE 0x10178F90 PT_GETVEC(pt_s11, 0x18, 3) -PT_SETF(pt_s12, 0x74) +PT_SETFLT(pt_s12, 0x74) PT_GETF(pt_s13, 0x74) -PT_SETF(pt_s14, 0x70) +// PE 0x10178A90 +PT_SETFLT(pt_s14, 0x70) PT_GETF(pt_s15, 0x70) +// PE 0x10177270 PT_SETD(pt_s16, 0x264) +// PE 0x10178B90 PT_SETVEC(pt_s17, 0x24, 5) PT_LEA (pt_s18, 0x24) +// PE 0x10177290 PT_SETVEC(pt_s19, 0x38, 5) PT_LEA (pt_s20, 0x38) +// PE 0x101772D0 PT_SETVEC(pt_s21, 0x4C, 5) PT_LEA (pt_s22, 0x4C) PT_GETF(pt_s24, 0x10) -PT_SETF(pt_s25, 0x1D0) +// PE 0x10177490 +PT_SETFLT(pt_s25, 0x1D0) PT_GETF(pt_s26, 0x1D0) -PT_SETF(pt_s27, 0x0C) +// PE 0x10178AC0 +PT_SETFLT(pt_s27, 0x0C) PT_GETF(pt_s28, 0x0C) PT_GETF(pt_s30, 0x1D4) +// PE 0x10177210 PT_SETB(pt_s31, 0x6C) PT_GETB(pt_s32, 0x6C) -PT_SETF(pt_s33, 0x1D8) +// PE 0x10177230 +PT_SETFLT(pt_s33, 0x1D8) PT_GETF(pt_s34, 0x1D8) +// PE 0x101776D0 PT_SETVEC(pt_s35, 0x1C4, 3) +// PE 0x10177700 PT_GETVEC(pt_s36, 0x1C4, 3) +// PE 0x10176A20 PT_GETVEC(pt_s38, 0x20C, 3) +// PE 0x10176930 PT_SETVEC(pt_s39, 0xFC, 4) PT_LEA (pt_s40, 0xFC) +// PE 0x10177550 PT_SETB(pt_s41, 0x21C) PT_GETB(pt_s42, 0x21C) -PT_SETF(pt_s43, 0x80) +// PE 0x10176060 +PT_SETFLT(pt_s43, 0x80) PT_GETF(pt_s44, 0x80) PT_GETF(pt_s46, 0x84) -PT_SETF(pt_s47, 0x8C) +// PE 0x10178C00 +PT_SETFLT(pt_s47, 0x8C) PT_GETF(pt_s48, 0x8C) -PT_SETF(pt_s49, 0x90) // shipped has a NaN assert; a plain store is the release behavior +// PE 0x10177300 (shipped NaN assert dropped in release builds; both arms store the argument) +PT_SETFLT(pt_s49, 0x90) // shipped has a NaN assert; a plain store is the release behavior PT_GETF(pt_s50, 0x90) -PT_SETF(pt_s51, 0x1C0) +// PE 0x101773E0 +PT_SETFLT(pt_s51, 0x1C0) PT_GETF(pt_s52, 0x1C0) +// PE 0x10176960 PT_SETVEC(pt_s53, 0x10C, 4) PT_LEA (pt_s54, 0x10C) +// PE 0x10176990 PT_SETVEC(pt_s55, 0x11C, 4) PT_LEA (pt_s56, 0x11C) +// PE 0x101769C0 PT_SETVEC(pt_s57, 0x12C, 4) PT_LEA (pt_s58, 0x12C) +// PE 0x101768D0 PT_SETVEC(pt_s59, 0x18C, 4) PT_LEA (pt_s60, 0x18C) -PT_SETF(pt_s61, 0xA4) +// PE 0x10188300 +PT_SETFLT(pt_s61, 0xA4) PT_GETF(pt_s62, 0xA4) +// PE 0x101773F0 PT_SETB(pt_s63, 0xEC) PT_GETB(pt_s64, 0xEC) -PT_SETF(pt_s65, 0xF0) +// PE 0x10177400 +PT_SETFLT(pt_s65, 0xF0) PT_GETF(pt_s66, 0xF0) -PT_SETF(pt_s67, 0xF4) +// PE 0x10177410 +PT_SETFLT(pt_s67, 0xF4) PT_GETF(pt_s68, 0xF4) PT_SETB(pt_s69, 0x21D) PT_GETB(pt_s70, 0x21D) +// PE 0x10177420 PT_SETB(pt_s71, 0xA8) PT_GETB(pt_s72, 0xA8) -PT_SETF(pt_s73, 0xAC) +// PE 0x10177440 +PT_SETFLT(pt_s73, 0xAC) PT_GETF(pt_s74, 0xAC) +// PE 0x10178F10 PT_SETD(pt_s75, 0x26C) PT_GETD(pt_s76, 0x26C) -PT_SETF(pt_s77, 0x270) +// PE 0x10177630 +PT_SETFLT(pt_s77, 0x270) PT_GETF(pt_s78, 0x270) -PT_SETF(pt_s79, 0x274) +// PE 0x10178F40 +PT_SETFLT(pt_s79, 0x274) PT_GETF(pt_s80, 0x274) -PT_SETF(pt_s81, 0x278) +// PE 0x10177640 +PT_SETFLT(pt_s81, 0x278) PT_GETF(pt_s82, 0x278) -PT_SETF(pt_s83, 0x27C) +// PE 0x10177650 +PT_SETFLT(pt_s83, 0x27C) PT_GETF(pt_s84, 0x27C) -PT_SETF(pt_s85, 0x280) +// PE 0x10177670 +PT_SETFLT(pt_s85, 0x280) PT_GETF(pt_s86, 0x280) -PT_SETF(pt_s87, 0x284) +// PE 0x10177690 +PT_SETFLT(pt_s87, 0x284) PT_GETF(pt_s88, 0x284) -PT_SETF(pt_s89, 0x148) +// PE 0x101760A0 +PT_SETFLT(pt_s89, 0x148) PT_GETF(pt_s90, 0x148) -PT_SETF(pt_s91, 0x1B4) +// PE 0x10177360 +PT_SETFLT(pt_s91, 0x1B4) PT_GETF(pt_s92, 0x1B4) -PT_SETF(pt_s93, 0x1B8) +// PE 0x101773A0 +PT_SETFLT(pt_s93, 0x1B8) PT_GETF(pt_s94, 0x1B8) +// PE 0x10176900 PT_SETVEC(pt_s95, 0x19C, 4) PT_LEA (pt_s96, 0x19C) -PT_SETF(pt_s97, 0x9C) +// PE 0x10186D80 +PT_SETFLT(pt_s97, 0x9C) PT_GETF(pt_s98, 0x9C) -PT_SETF(pt_s99, 0x1F8) +// PE 0x101760C0 +PT_SETFLT(pt_s99, 0x1F8) PT_GETF(pt_s100, 0x1F8) +// PE 0x10176790 PT_GETVEC(pt_s102, 0x1DC, 3) +// PE 0x101768A0 PT_SETVEC(pt_s106, 0x17C, 4) PT_LEA (pt_s107, 0x17C) -PT_SETF(pt_s108, 0x144) +// PE 0x10176080 +PT_SETFLT(pt_s108, 0x144) PT_GETF(pt_s109, 0x144) -PT_SETF(pt_s110, 0x218) +// PE 0x10177580 +PT_SETFLT(pt_s110, 0x218) PT_GETF(pt_s111, 0x218) +// PE 0x101775E0 PT_SETB(pt_s112, 0x269) PT_GETB(pt_s113, 0x269) PT_LEA (pt_s115, 0x78) +// PE 0x10188280 PT_SETD(pt_s116, 0x7C) PT_GETD(pt_s117, 0x7C) +// PE 0x10175D20 PT_SETVEC(pt_s118, 0x13C, 2) -PT_SETF(pt_s120, 0x94) +// PE 0x10177330 +PT_SETFLT(pt_s120, 0x94) PT_GETF(pt_s121, 0x94) -PT_SETF(pt_s122, 0x98) +// PE 0x10178C80 +PT_SETFLT(pt_s122, 0x98) PT_GETF(pt_s123, 0x98) +// PE 0x10177340 PT_SETVEC(pt_s124, 0x1AC, 2) +// PE 0x101776B0 PT_GETVEC(pt_s125, 0x1AC, 2) -PT_SETF(pt_s126, 0xA0) +// PE 0x10177380 +PT_SETFLT(pt_s126, 0xA0) PT_GETF(pt_s127, 0xA0) -PT_SETF(pt_s128, 0x1BC) +// PE 0x101773C0 +PT_SETFLT(pt_s128, 0x1BC) PT_GETF(pt_s129, 0x1BC) -const ParticleHostString& __fastcall pt_s131(void* self, void*) -{ return *reinterpret_cast(static_cast(self) + 0x224); } +const ParticleHostString& RD9_THUNK pt_s131(void* self RD9_THUNK_EDX) +{ return psmDescriptor0(self, 0x224); } PT_GETB(pt_s133, 0xCC) +// PE 0x101774D0 PT_SETB(pt_s134, 0xD4) PT_GETB(pt_s135, 0xD4) +// PE 0x101774B0 PT_SETB(pt_s136, 0xCD) PT_GETB(pt_s137, 0xCD) -PT_SETF(pt_s138, 0xD0) +// PE 0x101774F0 +PT_SETFLT(pt_s138, 0xD0) PT_GETF(pt_s139, 0xD0) -PT_SETF(pt_s144, 0xD8) +// PE 0x10177510 +PT_SETFLT(pt_s144, 0xD8) PT_GETF(pt_s145, 0xD8) -PT_SETF(pt_s146, 0xDC) +// PE 0x10177530 +PT_SETFLT(pt_s146, 0xDC) PT_GETF(pt_s147, 0xDC) PT_GETD(pt_s149, 0xE0) PT_GETD(pt_s151, 0xE4) +// PE 0x101775A0 PT_SETF(pt_s152, 0xB4) PT_GETF(pt_s153, 0xB4) +// PE 0x101775C0 PT_SETF(pt_s154, 0xB0) PT_GETF(pt_s155, 0xB0) +// PE 0x10177600 PT_SETB(pt_s156, 0x29C) PT_GETB(pt_s157, 0x29C) // complex slots (recovered bodies) // slot 3 (0x100ED3B0): shared const-0 stub. -unsigned __fastcall pt_s3(void*, void*) { return 0; } +unsigned RD9_THUNK pt_s3(void* RD9_THUNK_EDX) { return 0; } // slot 2 (0x10176F00): recompute cached/derived scalars, then re-drive slot45/slot114 and the UV // recompute. The +0x168 term consults g_LightManager when f+0x1F8 < 0. The published boot surface // provides the typed +0x270 getter; the null fallback remains the shipped guarded arm. -void __fastcall pt_s2(void* self, void*) +void RD9_THUNK pt_s2(void* self RD9_THUNK_EDX) { if (F(self, 0x1F8) < 0.0f) { @@ -231,20 +320,30 @@ void __fastcall pt_s2(void* self, void*) if (U(self, 0xE4)) F(self, 0xE8) = 1.0f / static_cast(U(self, 0xE4)); else U(self, 0xE8) = 0; - pt_s45 (self, 0, U(self, 0x84)); - pt_s114(self, 0, static_cast(U(self, 0x78))); + pt_s45 (self RD9_THUNK_ARG, psmFloatArgFromBits(U(self, 0x84))); + pt_s114(self RD9_THUNK_ARG, static_cast(U(self, 0x78))); templateRecomputeUV(self); } // slots 23/29 (0x10177460/0x101771E0): set a scalar then recompute. -void __fastcall pt_s23(void* self, void*, unsigned v) { U(self, 0x10) = v; pt_s2(self, 0); } -void __fastcall pt_s29(void* self, void*, unsigned v) { U(self, 0x1D4) = v; pt_s2(self, 0); } +void RD9_THUNK pt_s23(void* self RD9_THUNK_EDX, PsmFloatArg v) { U(self, 0x10) = psmFloatArgBits(v); pt_s2(self RD9_THUNK_ARG); } +// PE 0x101771E0 +void RD9_THUNK pt_s29(void* self RD9_THUNK_EDX, PsmFloatArg v) +{ + U(self, 0x1D4) = psmFloatArgBits(v); +#if !defined(_MSC_VER) + static_cast(self)->refreshDerivedState(); +#else + typedef void (__thiscall* Refresh)(void*); + reinterpret_cast((*static_cast(self))[2])(self); +#endif +} // slot 37 (0x101769F0): store a Vec3 at +0x20C then normalize it in place (sub_100777A0). -void __fastcall pt_s37(void* self, void*, const float* v) +void RD9_THUNK pt_s37(void* self RD9_THUNK_EDX, const float* v) { F(self, 0x20C) = v[0]; F(self, 0x210) = v[1]; F(self, 0x214) = v[2]; - float* p = reinterpret_cast(static_cast(self) + 0x20C); + float* p = &psmDescriptor0(self, 0x20C); float s = p[0] * p[0] + p[1] * p[1] + p[2] * p[2]; if (fabsf(s - 1.0f) >= FLT_EPSILON) { @@ -255,16 +354,16 @@ void __fastcall pt_s37(void* self, void*, const float* v) // slot 45 (0x10175FF0): set +0x84 float; recompute its reciprocal at +0x88 and, when the +0xCC flag // is set, the +0xD0 rate. -void __fastcall pt_s45(void* self, void*, unsigned a) +void RD9_THUNK pt_s45(void* self RD9_THUNK_EDX, PsmFloatArg a) { - U(self, 0x84) = a; + U(self, 0x84) = psmFloatArgBits(a); float fa = F(self, 0x84); if (fa > 0.0f) F(self, 0x88) = 1.0f / fa; if (Bt(self, 0xCC) && fa > 0.0f) F(self, 0xD0) = static_cast(U(self, 0xE0)) / fa; } // slot 101 (0x10176740): Vec3 written to both +0x1DC and the mirror +0x15C. -void __fastcall pt_s101(void* self, void*, const float* v) +void RD9_THUNK pt_s101(void* self RD9_THUNK_EDX, const float* v) { F(self, 0x1DC) = v[0]; F(self, 0x1E0) = v[1]; F(self, 0x1E4) = v[2]; F(self, 0x15C) = v[0]; F(self, 0x160) = v[1]; F(self, 0x164) = v[2]; @@ -272,48 +371,48 @@ void __fastcall pt_s101(void* self, void*, const float* v) // slot 103 (0x101767C0): Vec3(rgb) packed to a Vec4 {r,g,b,1} at +0x1E8 and mirror +0x16C // (sub_1008DD80 is a Vec3+scalar -> Vec4 pack with w = 1.0). -void __fastcall pt_s103(void* self, void*, const float* v) +void RD9_THUNK pt_s103(void* self RD9_THUNK_EDX, const float* v) { F(self, 0x1E8) = v[0]; F(self, 0x1EC) = v[1]; F(self, 0x1F0) = v[2]; F(self, 0x1F4) = 1.0f; F(self, 0x16C) = v[0]; F(self, 0x170) = v[1]; F(self, 0x174) = v[2]; F(self, 0x178) = 1.0f; } // slot 104 (0x10176830): get the +0x1E8 color as a Vec3 into out (sub_100E11B0 is an identity copy). -void* __fastcall pt_s104(void* self, void*, float* out) +void* RD9_THUNK pt_s104(void* self RD9_THUNK_EDX, float* out) { out[0] = F(self, 0x1E8); out[1] = F(self, 0x1EC); out[2] = F(self, 0x1F0); return out; } // slot 105 (0x10176860): Vec3 packed to a Vec4 {r,g,b,1} at +0x1FC (no mirror). -void __fastcall pt_s105(void* self, void*, const float* v) +void RD9_THUNK pt_s105(void* self RD9_THUNK_EDX, const float* v) { F(self, 0x1FC) = v[0]; F(self, 0x200) = v[1]; F(self, 0x204) = v[2]; F(self, 0x208) = 1.0f; } // slot 114 (PE 10175EF0, full instruction stream read): +2A0 is a renderer collector, // not a simulation callback. The manager's +8BA8 flag forces sorted collection. -void __fastcall pt_s114(void* self, void*, int type) +void RD9_THUNK pt_s114(void* self RD9_THUNK_EDX, int type) { U(self, 0x78) = static_cast(type); - const bool mgrFlag = reinterpret_cast(g_ParticleSystemManager)[0x8BA8] != 0; + const bool mgrFlag = particleSystemManagerForceSortedParticles(g_ParticleSystemManager) != 0; if (mgrFlag || type == 0) - *reinterpret_cast(static_cast(self) + 0x2A0) = reinterpret_cast(&particleRendererCollectSorted); + psmDescriptor0(self, 0x2A0) = reinterpret_cast(&particleRendererCollectSorted); else if (type == 1 || type == 2) - *reinterpret_cast(static_cast(self) + 0x2A0) = reinterpret_cast(&particleRendererCollectAdditive); + psmDescriptor0(self, 0x2A0) = reinterpret_cast(&particleRendererCollectAdditive); else { - *reinterpret_cast(static_cast(self) + 0x2A0) = 0; + psmDescriptor0(self, 0x2A0) = 0; static bool noted = false; if (!noted) { noted = true; ::renddx9abi::logf("ParticleSystemTemplate::setParticleType: unknown particle type %d", type); } } - pt_s89(self, 0, U(self, 0x148)); // slot 89, arg = current +0x148 + pt_s89(self RD9_THUNK_ARG, psmFloatArgFromBits(U(self, 0x148))); // slot 89, arg = current +0x148 } // slot 119 (0x10176590): get the +0x13C Vec2 into out (the retail scratch-static bounce is a compiler // temp, not shared state - modelled as a plain copy). -void* __fastcall pt_s119(void* self, void*, float* out) +void* RD9_THUNK pt_s119(void* self RD9_THUNK_EDX, float* out) { out[0] = F(self, 0x13C); out[1] = F(self, 0x140); return out; @@ -321,75 +420,97 @@ void* __fastcall pt_s119(void* self, void*, float* out) // slot 130 (0x10176DD0), loader a changed name is assigned before loading. // A failed load clears the stored name. Passing empty preserves the old texture/region pair. -void __fastcall pt_s130(void* self, void*, const ParticleHostString& source) +void RD9_THUNK pt_s130(void* self RD9_THUNK_EDX, const ParticleHostString& source) { - ParticleHostString* dst = reinterpret_cast(static_cast(self) + 0x224); + ParticleHostString* dst = &psmDescriptor0(self, 0x224); if (dst->size() != source.size() || ::memcmp(dst->c_str(), source.c_str(), source.size()) != 0) { *dst = source; - // Resource managers keep their recovered VC7.1 carriers in both renderer flavours. - const vc71::string& resourceName = ::renddx9abi::toVc71String(source); - dx9rend::EngineTexture*& texture = *reinterpret_cast(static_cast(self) + 0x25C); - dx9rend::TextureAtlasEntry*& region = *reinterpret_cast(static_cast(self) + 0x260); + // The resource managers take the renderer's own string type. + const std::string& resourceName = ::renddx9abi::fromHostString(source); + dx9rend::EngineTexture*& texture = psmDescriptor0(self, 0x25C); + dx9rend::TextureAtlasEntry*& region = psmDescriptor0(self, 0x260); if (!particleTemplateLoadTexture(texture, region, resourceName, - "dice::hfe::geom::ParticleSystemTemplate::setTexture", 300)) + "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\ParticleSystem\\ParticleSystemTemplate.cpp", 300)) *dst = ""; } } // slot 132 (0x10175D90): set the +0xCC bool; when set (and +0x84 > 0) recompute the +0xD0 rate. -void __fastcall pt_s132(void* self, void*, unsigned b) +void RD9_THUNK pt_s132(void* self RD9_THUNK_EDX, unsigned b) { Bt(self, 0xCC) = static_cast(b); - if (b && F(self, 0x84) > 0.0f) F(self, 0xD0) = static_cast(U(self, 0xE0)) / F(self, 0x84); + if (psmBoolArg(b) && F(self, 0x84) > 0.0f) F(self, 0xD0) = static_cast(U(self, 0xE0)) / F(self, 0x84); } // slots 140/141/142/143 (0x101765F0/0x10176630/0x10176690/0x101766E0): set/get the +0xD8/+0xDC rates // scaled by direct-texture dimensions at (+0x25C)+0x28/+0x2C. The atlas-region path leaves this // pointer null, retaining the shipped no-op/zero branches. -void __fastcall pt_s140(void* self, void*, unsigned a) +void RD9_THUNK pt_s140(void* self RD9_THUNK_EDX, unsigned a) { - void* atlas = *reinterpret_cast(static_cast(self) + 0x25C); - if (atlas) F(self, 0xD8) = static_cast(a) / static_cast(U(atlas, 0x28)); + void* atlas = psmDescriptor0(self, 0x25C); + if (atlas) F(self, 0xD8) = static_cast(a) / static_cast(static_cast(atlas)->width); } -unsigned __fastcall pt_s141(void* self, void*) +// PE 0x10176630 +unsigned RD9_THUNK pt_s141(void* self RD9_THUNK_EDX) { - void* atlas = *reinterpret_cast(static_cast(self) + 0x25C); - if (atlas) return static_cast(static_cast(static_cast(U(atlas, 0x28)) * F(self, 0xD8))); + void* atlas = psmDescriptor0(self, 0x25C); +#if defined(__APPLE__) + // [CHOSEN, not recovered] Keep unsigned FILD and FMUL live through FISTP. + if (atlas) return static_cast(bf2x87::toIntTruncate( + bf2x87::wide(static_cast(atlas)->width)*bf2x87::wide(F(self, 0xD8)))); +#else + if (atlas) return static_cast(static_cast(static_cast(static_cast(atlas)->width) * F(self, 0xD8))); +#endif return 0; } -void __fastcall pt_s142(void* self, void*, unsigned a) +// PE 0x10176690 +void RD9_THUNK pt_s142(void* self RD9_THUNK_EDX, unsigned a) { - void* atlas = *reinterpret_cast(static_cast(self) + 0x25C); - if (atlas) F(self, 0xDC) = static_cast(a) / static_cast(U(atlas, 0x2C)); + void* atlas = psmDescriptor0(self, 0x25C); +#if defined(__APPLE__) + // [CHOSEN, not recovered] The numerator spills to float; the unsigned divisor stays live. + if (atlas) F(self, 0xDC) = static_cast(bf2x87::wide(static_cast(a)) + /bf2x87::wide(static_cast(atlas)->height)); +#else + if (atlas) F(self, 0xDC) = static_cast(static_cast(static_cast(a)) + /static_cast(static_cast(atlas)->height)); +#endif } -unsigned __fastcall pt_s143(void* self, void*) +// PE 0x101766E0 +unsigned RD9_THUNK pt_s143(void* self RD9_THUNK_EDX) { - void* atlas = *reinterpret_cast(static_cast(self) + 0x25C); - if (atlas) return static_cast(static_cast(static_cast(U(atlas, 0x2C)) * F(self, 0xDC))); + void* atlas = psmDescriptor0(self, 0x25C); +#if defined(__APPLE__) + // [CHOSEN, not recovered] Keep unsigned FILD and FMUL live through FISTP. + if (atlas) return static_cast(bf2x87::toIntTruncate( + bf2x87::wide(static_cast(atlas)->height)*bf2x87::wide(F(self, 0xDC)))); +#else + if (atlas) return static_cast(static_cast(static_cast(static_cast(atlas)->height) * F(self, 0xDC))); +#endif return 0; } // slot 150 (0x10175E70): set the +0xE4 count; when nonzero cache 1/count at +0xE8 and push it to both // rate fields via slot144/slot146. -void __fastcall pt_s150(void* self, void*, unsigned a) +void RD9_THUNK pt_s150(void* self RD9_THUNK_EDX, unsigned a) { U(self, 0xE4) = a; if (a) { float inv = 1.0f / static_cast(a); F(self, 0xE8) = inv; - pt_s144(self, 0, fbits(inv)); - pt_s146(self, 0, fbits(inv)); + pt_s144(self RD9_THUNK_ARG, psmFloatArgFromBits(fbits(inv))); + pt_s146(self RD9_THUNK_ARG, psmFloatArgFromBits(fbits(inv))); } } // slot 148 (0x10175DF0): set the +0xE0 count; cascade to slot150 when +0xE4 is set, then recompute // the +0xD0 rate when the +0xCC flag is set. -void __fastcall pt_s148(void* self, void*, int a) +void RD9_THUNK pt_s148(void* self RD9_THUNK_EDX, int a) { U(self, 0xE0) = static_cast(a); - if (U(self, 0xE4)) pt_s150(self, 0, U(self, 0xE4)); + if (U(self, 0xE4)) pt_s150(self RD9_THUNK_ARG, U(self, 0xE4)); if (Bt(self, 0xCC) && F(self, 0x84) > 0.0f) F(self, 0xD0) = static_cast(U(self, 0xE0)) / F(self, 0x84); } @@ -397,14 +518,14 @@ void __fastcall pt_s148(void* self, void*, int a) // The direct-texture/no-texture branch clears the shorts and uses rates or {1,1}. void templateRecomputeUV(void* self) { - void* region = *reinterpret_cast(static_cast(self) + 0x260); + const dx9rend::TextureAtlasEntry* region = psmDescriptor0(self, 0x260); float u, v; if (region) { - S16(self, 0x21E) = static_cast(F(region, 8) * 32767.0f); - S16(self, 0x220) = static_cast(F(region, 0xC) * 32767.0f); - if (Bt(self, 0xD4)) { u = F(self, 0xD8) * F(region, 0); v = F(self, 0xDC) * F(region, 4); } - else { u = F(region, 0); v = F(region, 4); } + S16(self, 0x21E) = static_cast(region->uOffset * 32767.0f); + S16(self, 0x220) = static_cast(region->vOffset * 32767.0f); + if (Bt(self, 0xD4)) { u = F(self, 0xD8) * region->width; v = F(self, 0xDC) * region->height; } + else { u = region->width; v = region->height; } } else { @@ -414,23 +535,247 @@ void templateRecomputeUV(void* self) else { u = 1.0f; v = 1.0f; } } float uv[2] = { u, v }; - pt_s118(self, 0, uv); + pt_s118(self RD9_THUNK_ARG, uv); +} + +// Type 0 descriptor members that nothing calls or references in 1.50: unreachable in 1.50: no code or +// data references. Each body is the listing's own. The names are [CHOSEN, not recovered]: no caller +// exposes them. + +// PE 0x10175D40: recompute the +0xD0 rate (+0xE0 count over the +0x84 value) when the +0xCC flag is set +// and +0x84 is positive; the same arithmetic is inlined in slots 45, 132 and 148. +void templateRecomputeRate(void* self) +{ + if (Bt(self, 0xCC) && F(self, 0x84) > 0.0f) F(self, 0xD0) = static_cast(U(self, 0xE0)) / F(self, 0x84); +} + +// PE 0x10175ED0: store the +0xE8 float (the reciprocal cache that slot 150 writes). The float argument +// type is [CHOSEN, not recovered]: the paired getter at 0x10175EE0 answers st0. +void templateSetReciprocalCache(void* self, float value) +{ + U(self, 0xE8) = fbits(value); +} + +// PE 0x10176160: store the +0xC8 float; the paired getter at 0x10176170 answers st0. +void templateSetC8(void* self, float value) +{ + U(self, 0xC8) = fbits(value); } -// slot 0 (0x10177730 -> sub_10176BA0): release the direct texture, destroy the two embedded +// PE 0x10176EE0: load the texture named by the stored +0x224 name (the result is not tested), then +// recompute the UV base and scale (tail jump to templateRecomputeUV, PE 0x10176E20). +void templateReloadTexture(void* self) +{ + ParticleHostString& name = psmDescriptor0(self, 0x224); + dx9rend::EngineTexture*& texture = psmDescriptor0(self, 0x25C); + dx9rend::TextureAtlasEntry*& region = psmDescriptor0(self, 0x260); + particleTemplateLoadTexture(texture, region, ::renddx9abi::fromHostString(name), + "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\ParticleSystem\\ParticleSystemTemplate.cpp", 300); + templateRecomputeUV(self); +} + +// [CHOSEN, not recovered] Reader that PE 0x10175CE0 calls through its slot 4 (+0x10) with a destination +// and a byte count. No caller exists in any image, so the real type of the argument is unobservable; +// the first four slots are placeholders that keep the slot position. +struct TemplateByteSource +{ + virtual void unusedSlot0() = 0; + virtual void unusedSlot1() = 0; + virtual void unusedSlot2() = 0; + virtual void unusedSlot3() = 0; + virtual void read(void* destination, unsigned int size) = 0; +}; + +// PE 0x10175CE0: read the 0x214-byte block at +0x10 from the supplied source, then re-drive slot 114 +// (particle type, argument +0x78). +void templateLoadFromSource(void* self, TemplateByteSource* source) +{ + source->read(&Bt(self, 0x10), 0x214); + pt_s114(self RD9_THUNK_ARG, static_cast(U(self, 0x78))); +} + +// PE 0x10177730, 0x10176BA0 +// slot 0 (the deleting wrapper 0x10177730 and the destructor body 0x10176BA0; the shipped body releases +// the texture, nulls the field and +// repeats the guarded release, which is a no-op): release the direct texture, destroy the two embedded // strings, then free the block when the deleting flag is set. The atlas region is borrowed. -void* __fastcall pt_dtor(void* self, void*, int flags) +void* RD9_THUNK pt_dtor(void* self RD9_THUNK_EDX, int flags) { - dx9rend::EngineTexture*& texture = *reinterpret_cast(static_cast(self) + 0x25C); + dx9rend::EngineTexture*& texture = psmDescriptor0(self, 0x25C); dx9rend::textureReleaseRef(texture); - reinterpret_cast(static_cast(self) + 0x240)->~ParticleHostString(); - reinterpret_cast(static_cast(self) + 0x224)->~ParticleHostString(); + psmDescriptor0(self, 0x240).~ParticleHostString(); + psmDescriptor0(self, 0x224).~ParticleHostString(); if (flags & 1) ::renddx9abi::engineFree(self); return self; } // The 158-slot primary vtable (off_1021F300). +#if !defined(_MSC_VER) +// [CHOSEN, not recovered] Match the shared consumer interface under the native ABI. +const void* const kVtable[] = +{ + BF2_NATIVE_DTOR(pt_dtor, complete), + BF2_NATIVE_DTOR(pt_dtor, deleting), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getName, pt_s1), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, refreshDerivedState, pt_s2), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getSystemType, pt_s3), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setEmitPrio, pt_s4), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getEmitPrio, pt_s5), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setLodDistance, pt_s6), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getLodDistance, pt_s7), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setQualityLevel, pt_s8), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getQualityLevel, pt_s9), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setEmitRadius, pt_s10), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getEmitRadius, pt_s11), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setRadialDirection, pt_s12), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getRadialDirection, pt_s13), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setRandomRadialDirection, pt_s14), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getRandomRadialDirection, pt_s15), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setEmitterType, pt_s16), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setEmitRangeX, pt_s17), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getEmitRangeX, pt_s18), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setEmitRangeY, pt_s19), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getEmitRangeY, pt_s20), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setEmitRangeZ, pt_s21), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getEmitRangeZ, pt_s22), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setEmitFrequency, pt_s23), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getEmitFrequency, pt_s24), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setEmitSpeed, pt_s25), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getEmitSpeed, pt_s26), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setPreWarmTime, pt_s27), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getPreWarmTime, pt_s28), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setEmitTime, pt_s29), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getEmitTime, pt_s30), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setIsLooping, pt_s31), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getIsLooping, pt_s32), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setEmitDelay, pt_s33), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getEmitDelay, pt_s34), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setRandomDirectionAngle, pt_s35), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getRandomDirectionAngle, pt_s36), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setEmitDirection, pt_s37), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getEmitDirection, pt_s38), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setRotationGraph, pt_s39), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getRotationGraph, pt_s40), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setAlignRotationToSpeed, pt_s41), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getAlignRotationToSpeed, pt_s42), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setRandomTimeToLive, pt_s43), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getRandomTimeToLive, pt_s44), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setTimeToLive, pt_s45), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getTimeToLive, pt_s46), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setGravity, pt_s47), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getGravity, pt_s48), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setAirResistance, pt_s49), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getAirResistance, pt_s50), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setRandomSpeed, pt_s51), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getRandomSpeed, pt_s52), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setGravityGraph, pt_s53), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getGravityGraph, pt_s54), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setAirResistanceGraph, pt_s55), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getAirResistanceGraph, pt_s56), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setEmitSpeedGraph, pt_s57), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getEmitSpeedGraph, pt_s58), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setTransparencyGraph, pt_s59), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getTransparencyGraph, pt_s60), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setWindAffectionFactor, pt_s61), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getWindAffectionFactor, pt_s62), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setCollisionEnable, pt_s63), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getCollisionEnable, pt_s64), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setCollisionSpeedAlongNormal, pt_s65), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getCollisionSpeedAlongNormal, pt_s66), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setCollisionSpeedAlongPlane, pt_s67), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getCollisionSpeedAlongPlane, pt_s68), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setIsLocalSystem, pt_s69), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getIsLocalSystem, pt_s70), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setForceToWaterSurface, pt_s71), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getForceToWaterSurface, pt_s72), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setWaterSurfaceOffset, pt_s73), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getWaterSurfaceOffset, pt_s74), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setGasCloudType, pt_s75), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getGasCloudType, pt_s76), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setBlurryVisionTime, pt_s77), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getBlurryVisionTime, pt_s78), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setBlurryVisionHoldTime, pt_s79), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getBlurryVisionHoldTime, pt_s80), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setMinGasCloudRadius, pt_s81), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getMinGasCloudRadius, pt_s82), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setMaxGasCloudRadius, pt_s83), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getMaxGasCloudRadius, pt_s84), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setGasCloudRadiusTime, pt_s85), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getGasCloudRadiusTime, pt_s86), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setGasCloudDamage, pt_s87), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getGasCloudDamage, pt_s88), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setParticleMaxSize, pt_s89), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getParticleMaxSize, pt_s90), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setRandomSize, pt_s91), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getRandomSize, pt_s92), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setRandomIntensity, pt_s93), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getRandomIntensity, pt_s94), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setSizeGraph, pt_s95), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getSizeGraph, pt_s96), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setAlphaCull, pt_s97), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getAlphaCull, pt_s98), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setLightAffectionFactor, pt_s99), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getLightAffectionFactor, pt_s100), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setColor1, pt_s101), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getColor1, pt_s102), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setColor2, pt_s103), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getColor2, pt_s104), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, reserved105, pt_s105), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setColorBlendGraph, pt_s106), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getColorBlendGraph, pt_s107), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setLightMapIntensityOffset, pt_s108), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getLightMapIntensityOffset, pt_s109), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setDirectionalScale, pt_s110), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getDirectionalScale, pt_s111), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setIsStaticSystem, pt_s112), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getIsStaticSystem, pt_s113), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setParticleType, pt_s114), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getParticleTypeRef, pt_s115), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setDrawOrder, pt_s116), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getDrawOrder, pt_s117), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, reserved118, pt_s118), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, reserved119, pt_s119), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setRandomRotationSpeed, pt_s120), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getRandomRotationSpeed, pt_s121), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setRotationSpeed, pt_s122), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getRotationSpeed, pt_s123), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setPivotOffset, pt_s124), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getPivotOffset, pt_s125), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setSelfShadowIntensity, pt_s126), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getSelfShadowIntensity, pt_s127), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setRandomRotation, pt_s128), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getRandomRotation, pt_s129), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setTextureName, pt_s130), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getTextureName, pt_s131), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setAnimationPlayOnce, pt_s132), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getAnimationPlayOnce, pt_s133), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setAnimationEnable, pt_s134), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getAnimationEnable, pt_s135), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setAnimationRandomizedStartFrame, pt_s136), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getAnimationRandomizedStartFrame, pt_s137), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setAnimationSpeed, pt_s138), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getAnimationSpeed, pt_s139), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setAnimationFrameWidth, pt_s140), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getAnimationFrameWidth, pt_s141), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setAnimationFrameHeight, pt_s142), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getAnimationFrameHeight, pt_s143), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setAnimationFrameWidthRelative, pt_s144), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getAnimationFrameWidthRelative, pt_s145), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setAnimationFrameHeightRelative, pt_s146), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getAnimationFrameHeightRelative, pt_s147), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setAnimationFrameCount, pt_s148), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getAnimationFrameCount, pt_s149), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, setAnimationFrameCountX, pt_s150), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType0, getAnimationFrameCountX, pt_s151), + reinterpret_cast(&pt_s152), + reinterpret_cast(&pt_s153), + reinterpret_cast(&pt_s154), + reinterpret_cast(&pt_s155), + reinterpret_cast(&pt_s156), + reinterpret_cast(&pt_s157), +}; +#else const void* const kVtable[158] = { reinterpret_cast(&pt_dtor), reinterpret_cast(&pt_s1), reinterpret_cast(&pt_s2), reinterpret_cast(&pt_s3), @@ -474,6 +819,7 @@ const void* const kVtable[158] = reinterpret_cast(&pt_s152), reinterpret_cast(&pt_s153), reinterpret_cast(&pt_s154), reinterpret_cast(&pt_s155), reinterpret_cast(&pt_s156), reinterpret_cast(&pt_s157), }; +#endif // sub_10176180 - the init helper: field defaults + ~18 setter calls establishing the descriptor's // at-rest state, transcribed in shipped statement order. Runs at the tail of the constructor. @@ -542,13 +888,13 @@ void initTemplateDefaults(void* self) U (self, 0x1C8) = 0u; U (self, 0x1CC) = 0u; - pt_s99(self, 0, static_cast(-1082130432)); // +0x1F8 = -1.0 - { float v[3] = { 1.0f, 1.0f, 1.0f }; pt_s101(self, 0, v); } - { float v[3] = { 1.0f, 1.0f, 1.0f }; pt_s103(self, 0, v); } - { float v[3] = { 1.0f, 1.0f, 1.0f }; pt_s105(self, 0, v); } + pt_s99(self RD9_THUNK_ARG, psmFloatArgFromBits(static_cast(-1082130432))); // +0x1F8 = -1.0 + { float v[3] = { 1.0f, 1.0f, 1.0f }; pt_s101(self RD9_THUNK_ARG, v); } + { float v[3] = { 1.0f, 1.0f, 1.0f }; pt_s103(self RD9_THUNK_ARG, v); } + { float v[3] = { 1.0f, 1.0f, 1.0f }; pt_s105(self RD9_THUNK_ARG, v); } U (self, 0x158) = 0u; - { ParticleHostString empty; *reinterpret_cast(static_cast(self) + 0x224) = empty; } + { ParticleHostString empty; psmDescriptor0(self, 0x224) = empty; } Bt(self, 0xEC) = 0; U (self, 0xF0) = 1060320051u; U (self, 0xF4) = 1061997773u; @@ -563,19 +909,19 @@ void initTemplateDefaults(void* self) U (self, 0xE4) = 0u; U (self, 0xE8) = 0u; - { float v[2] = { 1.0f, 1.0f }; pt_s118(self, 0, v); } - pt_s89 (self, 0, 1065353216u); // +0x148 = 1.0 - pt_s108(self, 0, 0u); // +0x144 = 0 - pt_s114(self, 0, 0); // particle type 0 - pt_s45 (self, 0, 1082130432u); // +0x84 = 4.0 - pt_s43 (self, 0, 0u); // +0x80 = 0 - { float v[4] = { 0.0f, 0.0f, 1.0f, 0.0f }; pt_s106(self, 0, v); } - { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; pt_s59 (self, 0, v); } - { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; pt_s95 (self, 0, v); } - { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; pt_s39 (self, 0, v); } - { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; pt_s53 (self, 0, v); } - { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; pt_s55 (self, 0, v); } - { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; pt_s57 (self, 0, v); } + { float v[2] = { 1.0f, 1.0f }; pt_s118(self RD9_THUNK_ARG, v); } + pt_s89 (self RD9_THUNK_ARG, psmFloatArgFromBits(1065353216u)); // +0x148 = 1.0 + pt_s108(self RD9_THUNK_ARG, psmFloatArgFromBits(0u)); // +0x144 = 0 + pt_s114(self RD9_THUNK_ARG, 0); // particle type 0 + pt_s45 (self RD9_THUNK_ARG, psmFloatArgFromBits(1082130432u)); // +0x84 = 4.0 + pt_s43 (self RD9_THUNK_ARG, psmFloatArgFromBits(0u)); // +0x80 = 0 + { float v[4] = { 0.0f, 0.0f, 1.0f, 0.0f }; pt_s106(self RD9_THUNK_ARG, v); } + { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; pt_s59 (self RD9_THUNK_ARG, v); } + { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; pt_s95 (self RD9_THUNK_ARG, v); } + { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; pt_s39 (self RD9_THUNK_ARG, v); } + { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; pt_s53 (self RD9_THUNK_ARG, v); } + { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; pt_s55 (self RD9_THUNK_ARG, v); } + { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; pt_s57 (self RD9_THUNK_ARG, v); } U (self, 0x20C) = 0u; U (self, 0x210) = 1065353216u; @@ -589,12 +935,22 @@ void initTemplateDefaults(void* self) U (self, 0x280) = 1077936128u; U (self, 0x284) = 1073741824u; - pt_s2(self, 0); // final recompute + pt_s2(self RD9_THUNK_ARG); // final recompute } } // anonymous namespace +// PE 0x10188150 (thiscall on the block): the 112-byte sub-block the type-0, type-2 and type-4 +// template constructors embed, every dword stored zero. The block holds no string or pointer +// field, so its retail offsets are the native ones on every target. [INFERRED] name. +void psmZeroTemplateBlock(void* block) +{ + unsigned int* const words = static_cast(block); + for (unsigned int i = 0; i < 28; ++i) + words[i] = 0; +} + // geom_ParticleSystem_type0_ctor, 0x10177010. Installs the vtable, the ctor's own scalar defaults, // the two embedded name strings (string2 = the template name), the zeroed sub-block at +0x13C // (sub_10188150), and runs the init helper. A leading memset zeroes the fields retail hand-writes to @@ -603,9 +959,9 @@ void initTemplateDefaults(void* self) void* constructParticleSystemTemplateType0(void* mem, const void* nameString) { - ::memset(mem, 0, 0x2A4u); + ::memset(mem, 0, PSM_DESCRIPTOR_SIZE(0x2A4u)); - U(mem, 0x00) = ::renddx9abi::addr(kVtable); + *static_cast(mem) = kVtable; // sub_10177010 non-zero scalar defaults. U(mem, 0x28) = 1065353216u; // 1.0 @@ -614,12 +970,12 @@ void* constructParticleSystemTemplateType0(void* mem, const void* nameString) U(mem, 0x48) = 1973272912u; U(mem, 0x50) = 1065353216u; // 1.0 U(mem, 0x5C) = 1973272912u; - // sub_10188150(this+0x13C): a 112-byte zero-fill - covered by the memset above. + psmZeroTemplateBlock(&psmDescriptor0(mem, 0x13C)); // 0x101770C5, redundant after the memset - // The manager supplies an internal VC7.1 name; native getters expose an owned HostString. - new (static_cast(mem) + 0x224) ParticleHostString(); - new (static_cast(mem) + 0x240) ParticleHostString( - ::renddx9abi::toHostString(*static_cast(nameString))); + // The manager supplies the renderer's own string; the getters expose an owned HostString. + new (&psmDescriptor0(mem, 0x224)) ParticleHostString(); + new (&psmDescriptor0(mem, 0x240)) ParticleHostString( + ::renddx9abi::toHostString(*static_cast(nameString))); initTemplateDefaults(mem); return mem; diff --git a/Code/BF2/Geom/ParticleSystem/ParticleSystemTemplateType1.cpp b/Code/BF2/Geom/ParticleSystem/ParticleSystemTemplateType1.cpp index 7dda8ef66..cf6c8adb6 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleSystemTemplateType1.cpp +++ b/Code/BF2/Geom/ParticleSystem/ParticleSystemTemplateType1.cpp @@ -5,7 +5,14 @@ // The optional texture at +0x210 starts null and has no known assignment path. #ifdef BF2_IMAGE_RENDDX9 - +#if !defined(_MSC_VER) +// [CHOSEN, not recovered] Compiler-typed native table entries. +#include "../../../RendDX9Abi/NativeVtable.h" +#include "ParticleSystemManager.h" +#endif + +#include "../../../RendDX9Abi/ThunkAbi.h" +#include "ParticleRawLayout.h" #include "../XpLightManager.h" #include "../MeshTemplate.h" // G1: IGeometryTemplate #include "../GeometryTemplateManager.h" // G1: IGeometryTemplateManager @@ -14,7 +21,7 @@ #include "../../../RendDX9Abi/ModuleCommon.h" #include "../../../RendDX9Abi/BfMemory.h" #include "../../../RendDX9Abi/Frontier.h" -#include "../../../RendDX9Abi/Vc71String.h" +#include #include #include @@ -27,171 +34,269 @@ namespace geom { extern LightManager* g_LightManager; // published boot surface; slot 2 retains retail's null guard. extern IBase* g_GeometryTemplateManager; // G1: ModuleGeom.cpp, dword_1024B8F4 +const Vec3* terrainOriginScratch(const Vec3& value); +const float* staticMeshPackVec4(const float value[3], float w); namespace { // G1-e: the siblings' carrier (ParticleSystemTemplate.cpp, TrailSystemTemplate.cpp, -// NSAParticleSystemTemplate.cpp). [CHOSEN, not recovered] Native BF2 passes std::string through the -// descriptor interface; retail passes the VC7.1 string. Each object owns its host strings in the -// original 28-byte reserved spans; every later offset is retained. +// NSAParticleSystemTemplate.cpp). [CHOSEN, not recovered] BF2 passes std::string through the +// descriptor interface. Each object owns its host strings in the original 28-byte reserved spans +// (x64: 32-byte tail slots, ParticleRawLayout.h); +// every later offset is retained. using ParticleHostString = ::renddx9abi::HostString; -static_assert(sizeof(ParticleHostString) <= 28, "particle host string exceeds its reserved span"); +static_assert(sizeof(ParticleHostString) <= kPsmDescriptorStringSpan, "particle host string exceeds its reserved span"); -inline unsigned& U (void* p, unsigned off) { return *reinterpret_cast(static_cast(p) + off); } -inline float& F (void* p, unsigned off) { return *reinterpret_cast(static_cast(p) + off); } -inline unsigned char& Bt(void* p, unsigned off) { return *reinterpret_cast(static_cast(p) + off); } +inline unsigned& U (void* p, unsigned off) { return psmDescriptor1(p, off); } +inline float& F (void* p, unsigned off) { return psmDescriptor1(p, off); } +inline unsigned char& Bt(void* p, unsigned off) { return psmDescriptor1(p, off); } inline unsigned fbits(float f) { unsigned u; ::memcpy(&u, &f, 4); return u; } // G1: the two typed views the geometry hookup uses. inline ParticleHostString& geometryName(void* self) -{ return *reinterpret_cast(static_cast(self) + 0x70); } +{ return psmDescriptor1(self, 0x70); } inline IBase*& geometryInstance(void* self) -{ return *reinterpret_cast(static_cast(self) + 0x8C); } - -#define PT_SET(name, off) void __fastcall name(void* s, void*, unsigned v){ U(s,(off)) = v; } -#define PT_GETF(name, off) float __fastcall name(void* s, void*){ return F(s,(off)); } -#define PT_GETD(name, off) unsigned __fastcall name(void* s, void*){ return U(s,(off)); } -#define PT_SETB(name, off) void __fastcall name(void* s, void*, unsigned v){ Bt(s,(off)) = static_cast(v); } -#define PT_GETB(name, off) unsigned __fastcall name(void* s, void*){ return Bt(s,(off)); } -#define PT_LEA(name, off) void* __fastcall name(void* s, void*){ return static_cast(s) + (off); } -#define PT_SETVEC(name, off, n) void __fastcall name(void* s, void*, const float* v){ for (int i=0;i<(n);++i) F(s,(off)+4u*i)=v[i]; } -#define PT_GETVEC(name, off, n) void* __fastcall name(void* s, void*, float* o){ for (int i=0;i<(n);++i) o[i]=F(s,(off)+4u*i); return o; } -#define PT_VEC3A(name, off) void __fastcall name(void* s, void*, unsigned a, unsigned b, unsigned c){ U(s,(off))=a; U(s,(off)+4)=b; U(s,(off)+8)=c; } +{ return psmDescriptor1(self, 0x8C); } + +#define PT_SET(name, off) void RD9_THUNK name(void* s RD9_THUNK_EDX, unsigned v){ U(s,(off)) = v; } +#define PT_SETFLT(name, off) void RD9_THUNK name(void* s RD9_THUNK_EDX, PsmFloatArg v){ U(s,(off)) = psmFloatArgBits(v); } +#define PT_GETF(name, off) float RD9_THUNK name(void* s RD9_THUNK_EDX){ return F(s,(off)); } +#define PT_GETD(name, off) unsigned RD9_THUNK name(void* s RD9_THUNK_EDX){ return U(s,(off)); } +#define PT_SETB(name, off) void RD9_THUNK name(void* s RD9_THUNK_EDX, unsigned v){ Bt(s,(off)) = static_cast(v); } +#define PT_GETB(name, off) unsigned RD9_THUNK name(void* s RD9_THUNK_EDX){ return Bt(s,(off)); } +#define PT_LEA(name, off) void* RD9_THUNK name(void* s RD9_THUNK_EDX){ return &psmDescriptor1(s, (off)); } +#define PT_SETVEC(name, off, n) void RD9_THUNK name(void* s RD9_THUNK_EDX, const float* v) \ +{ \ + if ((n)==4) \ + { \ + const float w=v[3],z=v[2],y=v[1],x=v[0]; \ + F(s,(off)+4)=y; F(s,(off))=x; F(s,(off)+8)=z; F(s,(off)+12)=w; \ + } \ + else for (int i=0;i<(n);++i) F(s,(off)+4u*i)=v[i]; \ +} +#define PT_GETVEC(name, off, n) void* RD9_THUNK name(void* s RD9_THUNK_EDX, float* o) \ +{ \ + if ((n)==3) \ + { \ + const float z=F(s,(off)+8),y=F(s,(off)+4),x=F(s,(off)); \ + o[1]=y; o[0]=x; o[2]=z; \ + } \ + else for (int i=0;i<(n);++i) o[i]=F(s,(off)+4u*i); \ + return o; \ +} +#define PT_VEC3A(name, off) void RD9_THUNK name(void* s RD9_THUNK_EDX, PSM_VEC3_PARAMS){ U(s,(off))=PSM_VEC3_X; U(s,(off)+4)=PSM_VEC3_Y; U(s,(off)+8)=PSM_VEC3_Z; } -void __fastcall n1_s2 (void* s, void*); -void __fastcall n1_s45(void* s, void*, unsigned a); +void RD9_THUNK n1_s2 (void* s RD9_THUNK_EDX); +void RD9_THUNK n1_s45(void* s RD9_THUNK_EDX, PsmFloatArg a); // simple slots // G1-e: slot 1 (0x101790D0, `lea eax,[ecx+1F4h]`) - the name, as the host's string type. -const ParticleHostString& __fastcall n1_s1(void* self, void*) -{ return *reinterpret_cast(static_cast(self) + 0x1F4); } +const ParticleHostString& RD9_THUNK n1_s1(void* self RD9_THUNK_EDX) +{ return psmDescriptor1(self, 0x1F4); } PT_SET (n1_s4, 0x64) PT_GETD(n1_s5, 0x64) PT_SET (n1_s6, 0x68) PT_GETD(n1_s7, 0x68) +// PE 0x10178A70 PT_SET (n1_s8, 0x6C) PT_GETD(n1_s9, 0x6C) +// PE 0x1017A0C0 PT_VEC3A(n1_s10, 0x14) +// PE 0x1017A0E0 PT_GETVEC(n1_s11, 0x14, 3) -PT_SET (n1_s12, 0x60) +PT_SETFLT(n1_s12, 0x60) PT_GETF(n1_s13, 0x60) -PT_SET (n1_s14, 0x5C) +PT_SETFLT(n1_s14, 0x5C) PT_GETF(n1_s15, 0x5C) +// PE 0x10179D80 PT_SET (n1_s16, 0x214) +// PE 0x10179D90 PT_SETVEC(n1_s17, 0x20, 5) PT_LEA (n1_s18, 0x20) +// PE 0x10188220 PT_SETVEC(n1_s19, 0x34, 5) PT_LEA (n1_s20, 0x34) +// PE 0x10188250 PT_SETVEC(n1_s21, 0x48, 5) PT_LEA (n1_s22, 0x48) PT_GETF(n1_s24, 0x10) -PT_SET (n1_s25, 0x190) +PT_SETFLT(n1_s25, 0x190) PT_GETF(n1_s26, 0x190) -PT_SET (n1_s27, 0x0C) +PT_SETFLT(n1_s27, 0x0C) PT_GETF(n1_s28, 0x0C) -PT_SET (n1_s29, 0x194) +// PE 0x10186EB0 +PT_SETFLT(n1_s29, 0x194) PT_GETF(n1_s30, 0x194) +// PE 0x10179D60 PT_SETB(n1_s31, 0x198) PT_GETB(n1_s32, 0x198) -PT_SET (n1_s33, 0x1A4) +// PE 0x10178C60 +PT_SETFLT(n1_s33, 0x1A4) PT_GETF(n1_s34, 0x1A4) -PT_SETVEC(n1_s35, 0x184, 3) +// PE 0x1017A220 +void RD9_THUNK n1_s35(void* s RD9_THUNK_EDX, const float* v) +{ + const float z=v[2],y=v[1],x=v[0]; + F(s,0x188)=y; F(s,0x184)=x; F(s,0x18C)=z; +} +// PE 0x1017A250 PT_GETVEC(n1_s36, 0x184, 3) +// PE 0x10179990 PT_GETVEC(n1_s38, 0x1DC, 3) +// PE 0x101798A0 PT_SETVEC(n1_s39, 0xFC, 4) PT_LEA (n1_s40, 0xFC) +// PE 0x10179EE0 PT_SETB(n1_s41, 0x1F0) PT_GETB(n1_s42, 0x1F0) -PT_SET (n1_s43, 0x98) +// PE 0x10179110 +PT_SETFLT(n1_s43, 0x98) PT_GETF(n1_s44, 0x98) PT_GETF(n1_s46, 0x9C) -PT_SET (n1_s47, 0xA4) +PT_SETFLT(n1_s47, 0xA4) PT_GETF(n1_s48, 0xA4) -PT_SET (n1_s49, 0xA8) +PT_SETFLT(n1_s49, 0xA8) PT_GETF(n1_s50, 0xA8) -PT_SET (n1_s51, 0x180) +// PE 0x10179E40 +PT_SETFLT(n1_s51, 0x180) PT_GETF(n1_s52, 0x180) +// PE 0x101798D0 PT_SETVEC(n1_s53, 0x10C, 4) PT_LEA (n1_s54, 0x10C) +// PE 0x10179900 PT_SETVEC(n1_s55, 0x11C, 4) PT_LEA (n1_s56, 0x11C) +// PE 0x10179930 PT_SETVEC(n1_s57, 0x15C, 4) PT_LEA (n1_s58, 0x15C) +// PE 0x10179840 PT_SETVEC(n1_s59, 0x13C, 4) PT_LEA (n1_s60, 0x13C) -PT_SET (n1_s61, 0xCC) +// PE 0x10179FC0 +PT_SETFLT(n1_s61, 0xCC) PT_GETF(n1_s62, 0xCC) PT_SETB(n1_s63, 0xEC) PT_GETB(n1_s64, 0xEC) -PT_SET (n1_s65, 0xF0) +PT_SETFLT(n1_s65, 0xF0) PT_GETF(n1_s66, 0xF0) -PT_SET (n1_s67, 0xF4) +// PE 0x10177410 +PT_SETFLT(n1_s67, 0xF4) PT_GETF(n1_s68, 0xF4) +// PE 0x10179F20 PT_SETB(n1_s69, 0x1F1) PT_GETB(n1_s70, 0x1F1) +// PE 0x10179F80 PT_SETB(n1_s71, 0xD0) PT_GETB(n1_s72, 0xD0) -PT_SET (n1_s73, 0xD4) +// PE 0x10179FA0 +PT_SETFLT(n1_s73, 0xD4) PT_GETF(n1_s74, 0xD4) +// PE 0x10179FF0 PT_SET (n1_s75, 0x21C) PT_GETD(n1_s76, 0x21C) -PT_SET (n1_s77, 0x220) +// PE 0x1017A010 +PT_SETFLT(n1_s77, 0x220) PT_GETF(n1_s78, 0x220) -PT_SET (n1_s79, 0x224) +// PE 0x10188210 +PT_SETFLT(n1_s79, 0x224) PT_GETF(n1_s80, 0x224) -PT_SET (n1_s81, 0x228) +// PE 0x1017A040 +PT_SETFLT(n1_s81, 0x228) PT_GETF(n1_s82, 0x228) -PT_SET (n1_s83, 0x22C) +// PE 0x1017A060 +PT_SETFLT(n1_s83, 0x22C) PT_GETF(n1_s84, 0x22C) -PT_SET (n1_s85, 0x230) +// PE 0x1017A080 +PT_SETFLT(n1_s85, 0x230) PT_GETF(n1_s86, 0x230) -PT_SET (n1_s87, 0x234) +// PE 0x1017A0A0 +PT_SETFLT(n1_s87, 0x234) PT_GETF(n1_s88, 0x234) -PT_SET (n1_s89, 0x1E8) +// PE 0x10179160 +PT_SETFLT(n1_s89, 0x1E8) PT_GETF(n1_s90, 0x1E8) -PT_SET (n1_s91, 0x16C) +// PE 0x10179E00 +PT_SETFLT(n1_s91, 0x16C) PT_GETF(n1_s92, 0x16C) -PT_SET (n1_s93, 0x170) +// PE 0x10179E20 +PT_SETFLT(n1_s93, 0x170) PT_GETF(n1_s94, 0x170) +// PE 0x10179870 PT_SETVEC(n1_s95, 0x14C, 4) PT_LEA (n1_s96, 0x14C) -PT_SET (n1_s97, 0xC4) +// PE 0x10179EC0 +PT_SETFLT(n1_s97, 0xC4) PT_GETF(n1_s98, 0xC4) -PT_SET (n1_s99, 0x1A8) +// PE 0x101791B0 +PT_SETFLT(n1_s99, 0x1A8) PT_GETF(n1_s100, 0x1A8) +// PE 0x10179180 PT_SETVEC(n1_s101, 0x1AC, 3) -PT_GETVEC(n1_s102, 0x1AC, 3) -PT_GETVEC(n1_s104, 0x1BC, 3) +// PE 0x10179730 +void* RD9_THUNK n1_s102(void* s RD9_THUNK_EDX, float* out) +{ + const Vec3* const packed=terrainOriginScratch(psmDescriptor1(s,0x1AC)); + const float z=packed->z,y=packed->y,x=packed->x; + out[1]=y; out[0]=x; out[2]=z; + return out; +} +// PE 0x101797A0 +void* RD9_THUNK n1_s104(void* s RD9_THUNK_EDX, float* out) +{ + const Vec3* const packed=terrainOriginScratch(psmDescriptor1(s,0x1BC)); + const float z=packed->z,y=packed->y,x=packed->x; + out[1]=y; out[0]=x; out[2]=z; + return out; +} +// PE 0x10179810 PT_SETVEC(n1_s106, 0x12C, 4) PT_LEA (n1_s107, 0x12C) -PT_SET (n1_s110, 0x1EC) +// PE 0x10179F00 +PT_SETFLT(n1_s110, 0x1EC) PT_GETF(n1_s111, 0x1EC) +// PE 0x10179FD0 PT_SETB(n1_s112, 0x218) PT_GETB(n1_s113, 0x218) // G1-e: slot 115 (0x10179F40, `lea eax,[ecx+70h]`) - the geometry name, as the host's string type. -const ParticleHostString& __fastcall n1_s115(void* self, void*) +const ParticleHostString& RD9_THUNK n1_s115(void* self RD9_THUNK_EDX) { return geometryName(self); } PT_SET (n1_s116, 0x94) PT_GETD(n1_s117, 0x94) +// PE 0x10179F50 PT_SETB(n1_s118, 0x1F2) PT_GETB(n1_s119, 0x1F2) +// PE 0x10179060 PT_SET (n1_s120, 0x90) PT_GETD(n1_s121, 0x90) +// PE 0x1017A1C0 PT_VEC3A(n1_s122, 0x174) +// PE 0x1017A1F0 PT_GETVEC(n1_s123, 0x174, 3) +// PE 0x1017A100 PT_VEC3A(n1_s124, 0xAC) +// PE 0x1017A130 PT_GETVEC(n1_s125, 0xAC, 3) +// PE 0x1017A160 PT_VEC3A(n1_s126, 0xB8) +// PE 0x1017A190 PT_GETVEC(n1_s127, 0xB8, 3) // complex slots -unsigned __fastcall n1_s3(void*, void*) { return 1; } // emitter type id -void __fastcall n1_s108(void*, void*, unsigned) { } // nullsub (1-arg dispatch, ignored) -float __fastcall n1_s109(void*, void*) { return -1.0f; } // shipped returns -1.0 +unsigned RD9_THUNK n1_s3(void* RD9_THUNK_EDX) { return 1; } // emitter type id +void RD9_THUNK n1_s108(void* RD9_THUNK_EDX, PsmFloatArg) { } // nullsub (1-arg dispatch, ignored) +float RD9_THUNK n1_s109(void* RD9_THUNK_EDX) { return -1.0f; } // shipped returns -1.0 + +// PE 0x10179330: store the +0xE8 float (the constructor initialises it to -1.0); the paired getter at +// 0x10179340 answers st0. Unreachable in 1.50: no code or data references. The name and the float +// argument type are [CHOSEN, not recovered]: no caller exposes them. +void n1_setE8(void* self, float value) +{ + U(self, 0xE8) = fbits(value); +} // slot 2 (0x10179240): LightManager auto-value + mode scale + recomputes. -void __fastcall n1_s2(void* self, void*) +void RD9_THUNK n1_s2(void* self RD9_THUNK_EDX) { if (F(self, 0x1A8) < 0.0f) { @@ -207,7 +312,7 @@ void __fastcall n1_s2(void* self, void*) unsigned mode = U(self, 0x64); F(self, 0x1A0) = (mode == 0) ? 0.5f : (mode == 1) ? 0.7f : 1.0f; - n1_s45(self, 0, U(self, 0x9C)); + n1_s45(self RD9_THUNK_ARG, psmFloatArgFromBits(U(self, 0x9C))); F(self, 0xE0) = (F(self, 0xD8) == F(self, 0xDC)) ? 0.0f : 1.0f / (F(self, 0xD8) - F(self, 0xDC)); if (F(self, 0x10) >= 1.1920929e-7f) F(self, 0x19C) = 1.0f / F(self, 0x10); @@ -215,17 +320,17 @@ void __fastcall n1_s2(void* self, void*) } // slot 23 (0x10179E90): store +0x10, cache 1/x at +0x19C (unconditional). -void __fastcall n1_s23(void* self, void*, unsigned a) +void RD9_THUNK n1_s23(void* self RD9_THUNK_EDX, PsmFloatArg a) { - U(self, 0x10) = a; + U(self, 0x10) = psmFloatArgBits(a); F(self, 0x19C) = 1.0f / F(self, 0x10); } // slot 37 (0x10179960): store Vec3 at +0x1DC, normalize in place. -void __fastcall n1_s37(void* self, void*, const float* v) +void RD9_THUNK n1_s37(void* self RD9_THUNK_EDX, const float* v) { F(self, 0x1DC) = v[0]; F(self, 0x1E0) = v[1]; F(self, 0x1E4) = v[2]; - float* p = reinterpret_cast(static_cast(self) + 0x1DC); + float* p = &psmDescriptor1(self, 0x1DC); float s = p[0] * p[0] + p[1] * p[1] + p[2] * p[2]; if (fabsf(s - 1.0f) >= FLT_EPSILON) { @@ -235,20 +340,23 @@ void __fastcall n1_s37(void* self, void*, const float* v) } // slot 45 (0x101790E0): store +0x9C, cache 1/x at +0xA0 when positive. -void __fastcall n1_s45(void* self, void*, unsigned a) +void RD9_THUNK n1_s45(void* self RD9_THUNK_EDX, PsmFloatArg a) { - U(self, 0x9C) = a; + U(self, 0x9C) = psmFloatArgBits(a); if (F(self, 0x9C) > 0.0f) F(self, 0xA0) = 1.0f / F(self, 0x9C); } // slots 103/105 (0x10179760/0x101797D0): Vec3 arg promoted to Vec4 {x,y,z,1} at +0x1BC / +0x1CC. -void __fastcall n1_s103(void* self, void*, const float* v) +void RD9_THUNK n1_s103(void* self RD9_THUNK_EDX, const float* v) { F(self, 0x1BC) = v[0]; F(self, 0x1C0) = v[1]; F(self, 0x1C4) = v[2]; F(self, 0x1C8) = 1.0f; } -void __fastcall n1_s105(void* self, void*, const float* v) +// PE 0x101797D0 +void RD9_THUNK n1_s105(void* self RD9_THUNK_EDX, const float* v) { - F(self, 0x1CC) = v[0]; F(self, 0x1D0) = v[1]; F(self, 0x1D4) = v[2]; F(self, 0x1D8) = 1.0f; + const float* const packed=staticMeshPackVec4(v,1.0f); + const float w=packed[3],z=packed[2],y=packed[1],x=packed[0]; + F(self,0x1D0)=y; F(self,0x1CC)=x; F(self,0x1D4)=z; F(self,0x1D8)=w; } @@ -273,7 +381,7 @@ void resolveGeometry(void* self) } // slot 114 (0x101796D0, 95 B, retn 4): setGeometryName. -void __fastcall n1_s114(void* self, void*, const ParticleHostString& name) +void RD9_THUNK n1_s114(void* self RD9_THUNK_EDX, const ParticleHostString& name) { geometryName(self) = name; // MSVCP71 operator= if (IBase* const old = geometryInstance(self)) @@ -284,11 +392,13 @@ void __fastcall n1_s114(void* self, void*, const ParticleHostString& name) resolveGeometry(self); } -// slot 0 (0x1017A280 -> sub_10179B10): release the geometry instance @+0x8C (IBase +0x08; the slot +// PE 0x1017A280, 0x10179B10 +// slot 0 (wrapper 0x1017A280 -> destructor body 0x10179B10): release the geometry instance @+0x8C (IBase +0x08; the slot // is NOT nulled - the object is going away), release the refcounted texture @+0x210 (G1-d: always -// null in 1.50), destroy the two strings, restore the base vtable (off_1021F120, not observable), -// free-if-flag. -void* __fastcall n1_dtor(void* self, void*, int flags) +// null in 1.50), destroy the two strings, free-if-flag. +// [UNRESOLVED] The complete destructor's initial derived-table and terminal base-table stores +// (0x1021F898 / 0x1021F120) need the shared base owner; this wrapper omits those transitions. +void* RD9_THUNK n1_dtor(void* self RD9_THUNK_EDX, int flags) { if (IBase* const geometry = geometryInstance(self)) geometry->release(); // [eax+8] @@ -297,16 +407,151 @@ void* __fastcall n1_dtor(void* self, void*, int flags) // 1005F360` - exactly textureReleaseRef's body. The slot is dead in the destructor either way; // the local copy keeps the shipped "not nulled" shape. dx9rend::EngineTexture* texture = - *reinterpret_cast(static_cast(self) + 0x210); + psmDescriptor1(self, 0x210); dx9rend::textureReleaseRef(texture); - reinterpret_cast(static_cast(self) + 0x1F4)->~ParticleHostString(); + psmDescriptor1(self, 0x1F4).~ParticleHostString(); geometryName(self).~ParticleHostString(); if (flags & 1) ::renddx9abi::engineFree(self); return self; } +#if !defined(_MSC_VER) +// [CHOSEN, not recovered] Match the shared consumer interface under the native ABI. +const void* const kVtable[] = +{ + BF2_NATIVE_DTOR(n1_dtor, complete), + BF2_NATIVE_DTOR(n1_dtor, deleting), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getName, n1_s1), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, refreshDerivedState, n1_s2), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getSystemType, n1_s3), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setEmitPrio, n1_s4), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getEmitPrio, n1_s5), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setLodDistance, n1_s6), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getLodDistance, n1_s7), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setQualityLevel, n1_s8), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getQualityLevel, n1_s9), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setEmitRadius, n1_s10), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getEmitRadius, n1_s11), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setRadialDirection, n1_s12), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getRadialDirection, n1_s13), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setRandomRadialDirection, n1_s14), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getRandomRadialDirection, n1_s15), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setEmitterType, n1_s16), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setEmitRangeX, n1_s17), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getEmitRangeX, n1_s18), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setEmitRangeY, n1_s19), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getEmitRangeY, n1_s20), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setEmitRangeZ, n1_s21), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getEmitRangeZ, n1_s22), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setEmitFrequency, n1_s23), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getEmitFrequency, n1_s24), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setEmitSpeed, n1_s25), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getEmitSpeed, n1_s26), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setPreWarmTime, n1_s27), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getPreWarmTime, n1_s28), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setEmitTime, n1_s29), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getEmitTime, n1_s30), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setIsLooping, n1_s31), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getIsLooping, n1_s32), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setEmitDelay, n1_s33), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getEmitDelay, n1_s34), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setRandomDirectionAngle, n1_s35), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getRandomDirectionAngle, n1_s36), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setEmitDirection, n1_s37), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getEmitDirection, n1_s38), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setRotationGraph, n1_s39), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getRotationGraph, n1_s40), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setAlignRotationToSpeed, n1_s41), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getAlignRotationToSpeed, n1_s42), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setRandomTimeToLive, n1_s43), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getRandomTimeToLive, n1_s44), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setTimeToLive, n1_s45), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getTimeToLive, n1_s46), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setGravity, n1_s47), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getGravity, n1_s48), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setAirResistance, n1_s49), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getAirResistance, n1_s50), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setRandomSpeed, n1_s51), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getRandomSpeed, n1_s52), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setGravityGraph, n1_s53), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getGravityGraph, n1_s54), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setAirResistanceGraph, n1_s55), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getAirResistanceGraph, n1_s56), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setEmitSpeedGraph, n1_s57), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getEmitSpeedGraph, n1_s58), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setTransparencyGraph, n1_s59), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getTransparencyGraph, n1_s60), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setWindAffectionFactor, n1_s61), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getWindAffectionFactor, n1_s62), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setCollisionEnable, n1_s63), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getCollisionEnable, n1_s64), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setCollisionSpeedAlongNormal, n1_s65), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getCollisionSpeedAlongNormal, n1_s66), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setCollisionSpeedAlongPlane, n1_s67), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getCollisionSpeedAlongPlane, n1_s68), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setIsLocalSystem, n1_s69), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getIsLocalSystem, n1_s70), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setForceToWaterSurface, n1_s71), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getForceToWaterSurface, n1_s72), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setWaterSurfaceOffset, n1_s73), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getWaterSurfaceOffset, n1_s74), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setGasCloudType, n1_s75), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getGasCloudType, n1_s76), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setBlurryVisionTime, n1_s77), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getBlurryVisionTime, n1_s78), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setBlurryVisionHoldTime, n1_s79), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getBlurryVisionHoldTime, n1_s80), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setMinGasCloudRadius, n1_s81), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getMinGasCloudRadius, n1_s82), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setMaxGasCloudRadius, n1_s83), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getMaxGasCloudRadius, n1_s84), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setGasCloudRadiusTime, n1_s85), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getGasCloudRadiusTime, n1_s86), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setGasCloudDamage, n1_s87), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getGasCloudDamage, n1_s88), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setParticleMaxSize, n1_s89), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getParticleMaxSize, n1_s90), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setRandomSize, n1_s91), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getRandomSize, n1_s92), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setRandomIntensity, n1_s93), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getRandomIntensity, n1_s94), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setSizeGraph, n1_s95), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getSizeGraph, n1_s96), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setAlphaCull, n1_s97), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getAlphaCull, n1_s98), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setLightAffectionFactor, n1_s99), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getLightAffectionFactor, n1_s100), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setColor1, n1_s101), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getColor1, n1_s102), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setColor2, n1_s103), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getColor2, n1_s104), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, reserved105, n1_s105), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setColorBlendGraph, n1_s106), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getColorBlendGraph, n1_s107), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setLightMapIntensityOffset, n1_s108), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getLightMapIntensityOffset, n1_s109), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setDirectionalScale, n1_s110), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getDirectionalScale, n1_s111), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setIsStaticSystem, n1_s112), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getIsStaticSystem, n1_s113), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setGeometry, n1_s114), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getGeometry, n1_s115), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setDrawOrder, n1_s116), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getDrawOrder, n1_s117), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setWriteZ, n1_s118), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getWriteZ, n1_s119), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setBlendMode, n1_s120), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getBlendMode, n1_s121), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setRandomRotation, n1_s122), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getRandomRotation, n1_s123), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setRandomRotationSpeed, n1_s124), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getRandomRotationSpeed, n1_s125), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, setRotationSpeed, n1_s126), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType1, getRotationSpeed, n1_s127), +}; +#else const void* const kVtable[128] = { reinterpret_cast(&n1_dtor), reinterpret_cast(&n1_s1), reinterpret_cast(&n1_s2), reinterpret_cast(&n1_s3), @@ -342,6 +587,7 @@ const void* const kVtable[128] = reinterpret_cast(&n1_s120), reinterpret_cast(&n1_s121),reinterpret_cast(&n1_s122),reinterpret_cast(&n1_s123), reinterpret_cast(&n1_s124), reinterpret_cast(&n1_s125),reinterpret_cast(&n1_s126),reinterpret_cast(&n1_s127), }; +#endif // sub_10179350 - init helper. void initType1Defaults(void* self) @@ -349,8 +595,8 @@ void initType1Defaults(void* self) F (self, 0xE8) = -1.0f; U (self, 0x0C) = 0u; U (self, 0x214) = 0u; - n1_s120(self, 0, 0u); // +0x90 = 0 - n1_s116(self, 0, 1u); // +0x94 = 1 + n1_s120(self RD9_THUNK_ARG, 0u); // +0x90 = 0 + n1_s116(self RD9_THUNK_ARG, 1u); // +0x94 = 1 Bt(self, 0x1F2)=0; U(self,0x20)=0u; U(self,0x24)=0u; U(self,0x28)=0u; Bt(self,0x2C)=0; U (self, 0x34)=0u; U(self,0x38)=0u; U(self,0x3C)=0u; Bt(self,0x40)=0; U (self, 0x48)=0u; U(self,0x4C)=0u; U(self,0x50)=0u; Bt(self,0x54)=0; @@ -373,23 +619,23 @@ void initType1Defaults(void* self) F (self, 0xC8) = 1.0f; U (self, 0x16C)=0u; U(self,0x170)=0u; U(self,0x174)=0u; U(self,0x178)=0u; U(self,0x17C)=0u; U(self,0x180)=0u; U(self,0x184)=0u; U(self,0x188)=0u; U(self,0x18C)=0u; - n1_s99 (self, 0, static_cast(-1082130432)); // +0x1A8 = -1.0 - { float v[3] = { 1.0f, 1.0f, 1.0f }; n1_s101(self, 0, v); } - { float v[3] = { 1.0f, 1.0f, 1.0f }; n1_s103(self, 0, v); } - { float v[3] = { 1.0f, 1.0f, 1.0f }; n1_s105(self, 0, v); } + n1_s99 (self RD9_THUNK_ARG, psmFloatArgFromBits(static_cast(-1082130432))); // +0x1A8 = -1.0 + { float v[3] = { 1.0f, 1.0f, 1.0f }; n1_s101(self RD9_THUNK_ARG, v); } + { float v[3] = { 1.0f, 1.0f, 1.0f }; n1_s103(self RD9_THUNK_ARG, v); } + { float v[3] = { 1.0f, 1.0f, 1.0f }; n1_s105(self RD9_THUNK_ARG, v); } Bt(self, 0xEC)=0; F(self,0xF0)=0.7f; F(self,0xF4)=0.8f; U(self,0xF8)=2u; - n1_s89 (self, 0, fbits(1.0f)); // +0x1E8 = 1.0 - n1_s108(self, 0, 0u); // nullsub - n1_s45 (self, 0, fbits(4.0f)); // +0x9C = 4.0 - n1_s43 (self, 0, 0u); // +0x98 = 0 - { float v[4] = { 0.0f, 0.0f, 1.0f, 0.0f }; n1_s106(self, 0, v); } - { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n1_s59 (self, 0, v); } - { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n1_s95 (self, 0, v); } - { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n1_s39 (self, 0, v); } - { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n1_s53 (self, 0, v); } - { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n1_s55 (self, 0, v); } - { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n1_s57 (self, 0, v); } + n1_s89 (self RD9_THUNK_ARG, psmFloatArgFromBits(fbits(1.0f))); // +0x1E8 = 1.0 + n1_s108(self RD9_THUNK_ARG, psmFloatArgFromBits(0u)); // nullsub + n1_s45 (self RD9_THUNK_ARG, psmFloatArgFromBits(fbits(4.0f))); // +0x9C = 4.0 + n1_s43 (self RD9_THUNK_ARG, psmFloatArgFromBits(0u)); // +0x98 = 0 + { float v[4] = { 0.0f, 0.0f, 1.0f, 0.0f }; n1_s106(self RD9_THUNK_ARG, v); } + { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n1_s59 (self RD9_THUNK_ARG, v); } + { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n1_s95 (self RD9_THUNK_ARG, v); } + { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n1_s39 (self RD9_THUNK_ARG, v); } + { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n1_s53 (self RD9_THUNK_ARG, v); } + { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n1_s55 (self RD9_THUNK_ARG, v); } + { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n1_s57 (self RD9_THUNK_ARG, v); } Bt(self, 0xD0)=0; F(self,0xD4)=0.03f; U (self, 0x1DC)=0u; U(self,0x1E4)=0u; F(self,0x1E0)=1.0f; // default dir {0,1,0} @@ -421,8 +667,8 @@ void* particleSystemType1Geometry(void* descriptor) // geom_ParticleSystem_type1_ctor, 0x10179B70. void* constructParticleSystemType1(void* mem, const void* nameString) { - ::memset(mem, 0, 0x238u); - U(mem, 0x00) = ::renddx9abi::addr(kVtable); + ::memset(mem, 0, PSM_DESCRIPTOR_SIZE(0x238u)); + *static_cast(mem) = kVtable; U(mem, 0x24) = 1065353216u; // 1.0 U(mem, 0x30) = 1973272912u; // range sentinel @@ -431,11 +677,11 @@ void* constructParticleSystemType1(void* mem, const void* nameString) U(mem, 0x4C) = 1065353216u; U(mem, 0x58) = 1973272912u; - // G1-e: both strings are host strings. The manager supplies its internal VC7.1 name, exactly as - // for the type-0/2/4 descriptors. - new (static_cast(mem) + 0x70) ParticleHostString(); // geomName - new (static_cast(mem) + 0x1F4) ParticleHostString( - ::renddx9abi::toHostString(*static_cast(nameString))); // name + // G1-e: both strings are host strings. The manager supplies the renderer's own string, exactly + // as for the type-0/2/4 descriptors. + new (&psmDescriptor1(mem, 0x70)) ParticleHostString(); // geomName + new (&psmDescriptor1(mem, 0x1F4)) ParticleHostString( + ::renddx9abi::toHostString(*static_cast(nameString))); // name // +0x8C (geometry) and +0x210 (texture) are the retail constructor's explicit zero stores // (0x10179BC8 / 0x10179D2A); the memset above already holds them. diff --git a/Code/BF2/Geom/ParticleSystem/ParticleSystemTemplateType3.cpp b/Code/BF2/Geom/ParticleSystem/ParticleSystemTemplateType3.cpp index 1c99cd16e..0fe1ed8e3 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleSystemTemplateType3.cpp +++ b/Code/BF2/Geom/ParticleSystem/ParticleSystemTemplateType3.cpp @@ -2,12 +2,19 @@ // Every emitted particle creates an instance of that child template. #ifdef BF2_IMAGE_RENDDX9 +#if !defined(_MSC_VER) +// [CHOSEN, not recovered] Compiler-typed native table entries. +#include "../../../RendDX9Abi/NativeVtable.h" +#include "ParticleSystemManager.h" +#endif +#include "../../../RendDX9Abi/ThunkAbi.h" +#include "ParticleRawLayout.h" #include "../../../RendDX9Abi/HfeAbi.h" #include "../../../RendDX9Abi/ModuleCommon.h" #include "../../../RendDX9Abi/BfMemory.h" #include "../../../RendDX9Abi/Frontier.h" -#include "../../../RendDX9Abi/Vc71String.h" +#include #include #include @@ -24,26 +31,45 @@ IParticleSystemTemplate* particleSystemManagerFindTemplateByName(const char* nam namespace { -// [CHOSEN, not recovered] Native BF2 passes std::string through the descriptor interface; retail passes -// VC7.1 string. The two strings are host strings in their original 28-byte spans (+0x6C..+0x87 and +// [CHOSEN, not recovered] BF2 passes std::string through the descriptor interface. The two strings +// are host strings in their original 28-byte spans (x64: ParticleRawLayout.h tail slots) (+0x6C..+0x87 and // +0x16C..+0x187), exactly as the type-0/1/2/4 descriptors carry theirs, so every later offset is kept. using ParticleHostString = ::renddx9abi::HostString; -static_assert(sizeof(ParticleHostString) <= 28, "particle host string exceeds its reserved span"); +static_assert(sizeof(ParticleHostString) <= kPsmDescriptorStringSpan, "particle host string exceeds its reserved span"); -inline unsigned& U (void* p, unsigned off) { return *reinterpret_cast(static_cast(p) + off); } -inline float& F (void* p, unsigned off) { return *reinterpret_cast(static_cast(p) + off); } -inline unsigned char& Bt(void* p, unsigned off) { return *reinterpret_cast(static_cast(p) + off); } +inline unsigned& U (void* p, unsigned off) { return psmDescriptor3(p, off); } +inline float& F (void* p, unsigned off) { return psmDescriptor3(p, off); } +inline unsigned char& Bt(void* p, unsigned off) { return psmDescriptor3(p, off); } inline unsigned fbits(float f) { unsigned u; ::memcpy(&u, &f, 4); return u; } -#define PT_SET(name, off) void __fastcall name(void* s, void*, unsigned v){ U(s,(off)) = v; } -#define PT_GETF(name, off) float __fastcall name(void* s, void*){ return F(s,(off)); } -#define PT_GETD(name, off) unsigned __fastcall name(void* s, void*){ return U(s,(off)); } -#define PT_SETB(name, off) void __fastcall name(void* s, void*, unsigned v){ Bt(s,(off)) = static_cast(v); } -#define PT_GETB(name, off) unsigned __fastcall name(void* s, void*){ return Bt(s,(off)); } -#define PT_LEA(name, off) void* __fastcall name(void* s, void*){ return static_cast(s) + (off); } -#define PT_SETVEC(name, off, n) void __fastcall name(void* s, void*, const float* v){ for (int i=0;i<(n);++i) F(s,(off)+4u*i)=v[i]; } -#define PT_GETVEC(name, off, n) void* __fastcall name(void* s, void*, float* o){ for (int i=0;i<(n);++i) o[i]=F(s,(off)+4u*i); return o; } -#define PT_VEC3A(name, off) void __fastcall name(void* s, void*, unsigned a, unsigned b, unsigned c){ U(s,(off))=a; U(s,(off)+4)=b; U(s,(off)+8)=c; } +#define PT_SET(name, off) void RD9_THUNK name(void* s RD9_THUNK_EDX, unsigned v){ U(s,(off)) = v; } +#define PT_SETFLT(name, off) void RD9_THUNK name(void* s RD9_THUNK_EDX, PsmFloatArg v){ U(s,(off)) = psmFloatArgBits(v); } +#define PT_GETF(name, off) float RD9_THUNK name(void* s RD9_THUNK_EDX){ return F(s,(off)); } +#define PT_GETD(name, off) unsigned RD9_THUNK name(void* s RD9_THUNK_EDX){ return U(s,(off)); } +#define PT_SETB(name, off) void RD9_THUNK name(void* s RD9_THUNK_EDX, unsigned v){ Bt(s,(off)) = static_cast(v); } +#define PT_GETB(name, off) unsigned RD9_THUNK name(void* s RD9_THUNK_EDX){ return Bt(s,(off)); } +#define PT_LEA(name, off) void* RD9_THUNK name(void* s RD9_THUNK_EDX){ return &psmDescriptor3(s, (off)); } +#define PT_SETVEC(name, off, n) void RD9_THUNK name(void* s RD9_THUNK_EDX, const float* v) \ +{ \ + if ((n)==3 || (n)==4) \ + { \ + const float z=v[2],y=v[1],x=v[0],w=(n)==4 ? v[3] : 0.0f; \ + F(s,(off)+4)=y; F(s,(off))=x; F(s,(off)+8)=z; \ + if ((n)==4) F(s,(off)+12)=w; \ + } \ + else for (int i=0;i<(n);++i) F(s,(off)+4u*i)=v[i]; \ +} +#define PT_GETVEC(name, off, n) void* RD9_THUNK name(void* s RD9_THUNK_EDX, float* o) \ +{ \ + if ((n)==3) \ + { \ + const float z=F(s,(off)+8),y=F(s,(off)+4),x=F(s,(off)); \ + o[1]=y; o[0]=x; o[2]=z; \ + } \ + else for (int i=0;i<(n);++i) o[i]=F(s,(off)+4u*i); \ + return o; \ +} +#define PT_VEC3A(name, off) void RD9_THUNK name(void* s RD9_THUNK_EDX, PSM_VEC3_PARAMS){ U(s,(off))=PSM_VEC3_X; U(s,(off)+4)=PSM_VEC3_Y; U(s,(off)+8)=PSM_VEC3_Z; } // simple slots PT_LEA (n3_s1, 0x16C) @@ -53,99 +79,140 @@ PT_SET (n3_s6, 0x64) PT_GETD(n3_s7, 0x64) PT_SET (n3_s8, 0x68) PT_GETD(n3_s9, 0x68) +// PE 0x10186F20 PT_VEC3A(n3_s10, 0x10) +// PE 0x10186F40 PT_GETVEC(n3_s11, 0x10, 3) -PT_SET (n3_s12, 0x5C) +// PE 0x10186C90 +PT_SETFLT(n3_s12, 0x5C) PT_GETF(n3_s13, 0x5C) -PT_SET (n3_s14, 0x58) +PT_SETFLT(n3_s14, 0x58) PT_GETF(n3_s15, 0x58) +// PE 0x10186CB0 PT_SET (n3_s16, 0x188) +// PE 0x10186CC0 PT_SETVEC(n3_s17, 0x1C, 5) PT_LEA (n3_s18, 0x1C) +// PE 0x10186D00 PT_SETVEC(n3_s19, 0x30, 5) PT_LEA (n3_s20, 0x30) +// PE 0x10186D40 PT_SETVEC(n3_s21, 0x44, 5) PT_LEA (n3_s22, 0x44) PT_GETF(n3_s24, 0x0C) -PT_SET (n3_s25, 0x140) +// PE 0x10186DD0 +PT_SETFLT(n3_s25, 0x140) PT_GETF(n3_s26, 0x140) -PT_SET (n3_s27, 0x08) +// PE 0x10186C10 +PT_SETFLT(n3_s27, 0x08) PT_GETF(n3_s28, 0x08) -PT_SET (n3_s29, 0x144) +// PE 0x10186C30 +PT_SETFLT(n3_s29, 0x144) PT_GETF(n3_s30, 0x144) +// PE 0x10186C50 PT_SETB(n3_s31, 0x148) PT_GETB(n3_s32, 0x148) -PT_SET (n3_s33, 0x154) +// PE 0x10186C70 +PT_SETFLT(n3_s33, 0x154) PT_GETF(n3_s34, 0x154) +// PE 0x10187020 PT_SETVEC(n3_s35, 0x134, 3) +// PE 0x10187050 PT_GETVEC(n3_s36, 0x134, 3) +// PE 0x10186A40 PT_GETVEC(n3_s38, 0x158, 3) +// PE 0x10186950 PT_SETVEC(n3_s39, 0xD4, 4) PT_LEA (n3_s40, 0xD4) +// PE 0x10186DF0 PT_SETB(n3_s41, 0x164) PT_GETB(n3_s42, 0x164) -PT_SET (n3_s43, 0x8C) +// PE 0x10186690 +PT_SETFLT(n3_s43, 0x8C) PT_GETF(n3_s44, 0x8C) PT_GETF(n3_s46, 0x90) -PT_SET (n3_s47, 0x98) +PT_SETFLT(n3_s47, 0x98) PT_GETF(n3_s48, 0x98) -PT_SET (n3_s49, 0x9C) +PT_SETFLT(n3_s49, 0x9C) PT_GETF(n3_s50, 0x9C) -PT_SET (n3_s51, 0x130) +// PE 0x10186D90 +PT_SETFLT(n3_s51, 0x130) PT_GETF(n3_s52, 0x130) +// PE 0x10186980 PT_SETVEC(n3_s53, 0xE4, 4) PT_LEA (n3_s54, 0xE4) +// PE 0x101869B0 PT_SETVEC(n3_s55, 0xF4, 4) PT_LEA (n3_s56, 0xF4) +// PE 0x101869E0 PT_SETVEC(n3_s57, 0x104, 4) PT_LEA (n3_s58, 0x104) +// PE 0x10186A70 PT_SETVEC(n3_s59, 0x114, 4) PT_LEA (n3_s60, 0x114) -PT_SET (n3_s61, 0xB8) +// PE 0x10186E50 +PT_SETFLT(n3_s61, 0xB8) PT_GETF(n3_s62, 0xB8) +// PE 0x10178DB0 PT_SETB(n3_s63, 0xC4) PT_GETB(n3_s64, 0xC4) -PT_SET (n3_s65, 0xC8) +// PE 0x10178DF0 +PT_SETFLT(n3_s65, 0xC8) PT_GETF(n3_s66, 0xC8) -PT_SET (n3_s67, 0xCC) +PT_SETFLT(n3_s67, 0xCC) PT_GETF(n3_s68, 0xCC) +// PE 0x10186E10 PT_SETB(n3_s69, 0x165) PT_GETB(n3_s70, 0x165) +// PE 0x10186E30 PT_SETB(n3_s71, 0xBC) PT_GETB(n3_s72, 0xBC) -PT_SET (n3_s73, 0xC0) +// PE 0x10178DD0 +PT_SETFLT(n3_s73, 0xC0) PT_GETF(n3_s74, 0xC0) +// PE 0x10186E90 PT_SET (n3_s75, 0x18C) PT_GETD(n3_s76, 0x18C) -PT_SET (n3_s77, 0x190) +// PE 0x10186EA0 +PT_SETFLT(n3_s77, 0x190) PT_GETF(n3_s78, 0x190) -PT_SET (n3_s79, 0x194) +// PE 0x10186EB0 +PT_SETFLT(n3_s79, 0x194) PT_GETF(n3_s80, 0x194) -PT_SET (n3_s81, 0x198) +// PE 0x10186EC0 +PT_SETFLT(n3_s81, 0x198) PT_GETF(n3_s82, 0x198) -PT_SET (n3_s83, 0x19C) +// PE 0x10186EE0 +PT_SETFLT(n3_s83, 0x19C) PT_GETF(n3_s84, 0x19C) -PT_SET (n3_s85, 0x1A0) +// PE 0x10186F00 +PT_SETFLT(n3_s85, 0x1A0) PT_GETF(n3_s86, 0x1A0) -PT_SET (n3_s87, 0x1A4) +// PE 0x10178C60 +PT_SETFLT(n3_s87, 0x1A4) PT_GETF(n3_s88, 0x1A4) PT_LEA (n3_s90, 0x6C) +// PE 0x10186FC0 PT_VEC3A(n3_s91, 0x124) +// PE 0x10186FF0 PT_GETVEC(n3_s92, 0x124, 3) +// PE 0x10186F60 PT_VEC3A(n3_s93, 0xA0) +// PE 0x10186F90 PT_GETVEC(n3_s94, 0xA0, 3) PT_VEC3A(n3_s95, 0xAC) PT_GETVEC(n3_s96, 0xAC, 3) -PT_SET (n3_s97, 0x168) +// PE 0x10186E70 +PT_SETFLT(n3_s97, 0x168) PT_GETF(n3_s98, 0x168) // complex slots -unsigned __fastcall n3_s3(void*, void*) { return 3; } // emitter type id +unsigned RD9_THUNK n3_s3(void* RD9_THUNK_EDX) { return 3; } // emitter type id // slot 2 (0x101865F0): mode@+0x60 -> scale @+0x150 {0.5,0.7,1.0}; inverse lifetime @+0x14C. No // external calls (type 3 has no LightManager dependency). -void __fastcall n3_s2(void* self, void*) +void RD9_THUNK n3_s2(void* self RD9_THUNK_EDX) { unsigned mode = U(self, 0x60); F(self, 0x150) = (mode == 0) ? 0.5f : (mode == 1) ? 0.7f : 1.0f; @@ -154,17 +221,17 @@ void __fastcall n3_s2(void* self, void*) } // slot 23 (0x10186DB0): setLifetime - store +0x0C, cache 1/lifetime at +0x14C (unconditional divide). -void __fastcall n3_s23(void* self, void*, unsigned a) +void RD9_THUNK n3_s23(void* self RD9_THUNK_EDX, PsmFloatArg a) { - U(self, 0x0C) = a; + U(self, 0x0C) = psmFloatArgBits(a); F(self, 0x14C) = 1.0f / F(self, 0x0C); } // slot 37 (0x10186A10): store Vec3 at +0x158, normalize in place. -void __fastcall n3_s37(void* self, void*, const float* v) +void RD9_THUNK n3_s37(void* self RD9_THUNK_EDX, const float* v) { F(self, 0x158) = v[0]; F(self, 0x15C) = v[1]; F(self, 0x160) = v[2]; - float* p = reinterpret_cast(static_cast(self) + 0x158); + float* p = &psmDescriptor3(self, 0x158); float s = p[0] * p[0] + p[1] * p[1] + p[2] * p[2]; if (fabsf(s - 1.0f) >= FLT_EPSILON) { @@ -174,9 +241,9 @@ void __fastcall n3_s37(void* self, void*, const float* v) } // slot 45 (0x10186650): store +0x90; cache 1/x at +0x94 when positive. -void __fastcall n3_s45(void* self, void*, unsigned a) +void RD9_THUNK n3_s45(void* self RD9_THUNK_EDX, PsmFloatArg a) { - U(self, 0x90) = a; + U(self, 0x90) = psmFloatArgBits(a); if (F(self, 0x90) > 0.0f) F(self, 0x94) = 1.0f / F(self, 0x90); } @@ -185,26 +252,135 @@ void __fastcall n3_s45(void* self, void*, unsigned a) // non-empty name (`cmp [esi+80h], 0`, the VC7.1 size word) - look the child up at once: a BY-value // copy of the name to 100D3410 on the manager (ds:1024B900), whose answer lands in +0x88. A child // defined later answers null here, and the instance constructor's re-resolve (10186540) picks it up. -void __fastcall n3_s89(void* self, void*, const ParticleHostString& name) +void RD9_THUNK n3_s89(void* self RD9_THUNK_EDX, const ParticleHostString& name) { - ParticleHostString& dst = *reinterpret_cast(static_cast(self) + 0x6C); + ParticleHostString& dst = psmDescriptor3(self, 0x6C); dst = name; - if (U(self, 0x88)) - U(self, 0x88) = 0; + IParticleSystemTemplate*& child = psmDescriptor3(self, 0x88); + if (child) + child = 0; if (!dst.empty()) - U(self, 0x88) = ::renddx9abi::addr(particleSystemManagerFindTemplateByName(dst.c_str())); + child = particleSystemManagerFindTemplateByName(dst.c_str()); } -// slot 0 (0x10187080): destroy the two strings, restore base vtable, free-if-flag. -void* __fastcall n3_dtor(void* self, void*, int flags) +// PE 0x10187080, 0x10186510 +// slot 0 (0x10187080; 0x10186510 is the same string-destroying body as a standalone copy with no +// references): destroy the two strings, restore base vtable, free-if-flag. +void* RD9_THUNK n3_dtor(void* self RD9_THUNK_EDX, int flags) { - reinterpret_cast(static_cast(self) + 0x16C)->~ParticleHostString(); - reinterpret_cast(static_cast(self) + 0x6C)->~ParticleHostString(); + psmDescriptor3(self, 0x16C).~ParticleHostString(); + psmDescriptor3(self, 0x6C).~ParticleHostString(); if (flags & 1) ::renddx9abi::engineFree(self); return self; } +#if !defined(_MSC_VER) +// [CHOSEN, not recovered] Match the shared consumer interface under the native ABI. +const void* const kVtable[] = +{ + BF2_NATIVE_DTOR(n3_dtor, complete), + BF2_NATIVE_DTOR(n3_dtor, deleting), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getName, n3_s1), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, refreshDerivedState, n3_s2), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getSystemType, n3_s3), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setEmitPrio, n3_s4), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getEmitPrio, n3_s5), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setLodDistance, n3_s6), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getLodDistance, n3_s7), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setQualityLevel, n3_s8), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getQualityLevel, n3_s9), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setEmitRadius, n3_s10), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getEmitRadius, n3_s11), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setRadialDirection, n3_s12), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getRadialDirection, n3_s13), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setRandomRadialDirection, n3_s14), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getRandomRadialDirection, n3_s15), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setEmitterType, n3_s16), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setEmitRangeX, n3_s17), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getEmitRangeX, n3_s18), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setEmitRangeY, n3_s19), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getEmitRangeY, n3_s20), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setEmitRangeZ, n3_s21), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getEmitRangeZ, n3_s22), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setEmitFrequency, n3_s23), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getEmitFrequency, n3_s24), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setEmitSpeed, n3_s25), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getEmitSpeed, n3_s26), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setPreWarmTime, n3_s27), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getPreWarmTime, n3_s28), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setEmitTime, n3_s29), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getEmitTime, n3_s30), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setIsLooping, n3_s31), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getIsLooping, n3_s32), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setEmitDelay, n3_s33), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getEmitDelay, n3_s34), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setRandomDirectionAngle, n3_s35), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getRandomDirectionAngle, n3_s36), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setEmitDirection, n3_s37), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getEmitDirection, n3_s38), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setRotationGraph, n3_s39), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getRotationGraph, n3_s40), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setAlignRotationToSpeed, n3_s41), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getAlignRotationToSpeed, n3_s42), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setRandomTimeToLive, n3_s43), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getRandomTimeToLive, n3_s44), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setTimeToLive, n3_s45), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getTimeToLive, n3_s46), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setGravity, n3_s47), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getGravity, n3_s48), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setAirResistance, n3_s49), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getAirResistance, n3_s50), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setRandomSpeed, n3_s51), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getRandomSpeed, n3_s52), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setGravityGraph, n3_s53), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getGravityGraph, n3_s54), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setAirResistanceGraph, n3_s55), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getAirResistanceGraph, n3_s56), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setEmitSpeedGraph, n3_s57), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getEmitSpeedGraph, n3_s58), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setTransparencyGraph, n3_s59), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getTransparencyGraph, n3_s60), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setWindAffectionFactor, n3_s61), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getWindAffectionFactor, n3_s62), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setCollisionEnable, n3_s63), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getCollisionEnable, n3_s64), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setCollisionSpeedAlongNormal, n3_s65), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getCollisionSpeedAlongNormal, n3_s66), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setCollisionSpeedAlongPlane, n3_s67), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getCollisionSpeedAlongPlane, n3_s68), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setIsLocalSystem, n3_s69), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getIsLocalSystem, n3_s70), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setForceToWaterSurface, n3_s71), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getForceToWaterSurface, n3_s72), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setWaterSurfaceOffset, n3_s73), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getWaterSurfaceOffset, n3_s74), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setGasCloudType, n3_s75), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getGasCloudType, n3_s76), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setBlurryVisionTime, n3_s77), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getBlurryVisionTime, n3_s78), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setBlurryVisionHoldTime, n3_s79), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getBlurryVisionHoldTime, n3_s80), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setMinGasCloudRadius, n3_s81), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getMinGasCloudRadius, n3_s82), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setMaxGasCloudRadius, n3_s83), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getMaxGasCloudRadius, n3_s84), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setGasCloudRadiusTime, n3_s85), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getGasCloudRadiusTime, n3_s86), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setGasCloudDamage, n3_s87), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getGasCloudDamage, n3_s88), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setParticleSystemTemplate, n3_s89), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getParticleSystemTemplate, n3_s90), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setRandomRotation, n3_s91), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getRandomRotation, n3_s92), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setRandomRotationSpeed, n3_s93), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getRandomRotationSpeed, n3_s94), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setRotationSpeed, n3_s95), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getRotationSpeed, n3_s96), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, setSpeedFromParticle, n3_s97), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemEmitterTemplate, getSpeedFromParticle, n3_s98), +}; +#else const void* const kVtable[99] = { reinterpret_cast(&n3_dtor), reinterpret_cast(&n3_s1), reinterpret_cast(&n3_s2), reinterpret_cast(&n3_s3), @@ -233,6 +409,7 @@ const void* const kVtable[99] = reinterpret_cast(&n3_s92), reinterpret_cast(&n3_s93), reinterpret_cast(&n3_s94), reinterpret_cast(&n3_s95), reinterpret_cast(&n3_s96), reinterpret_cast(&n3_s97), reinterpret_cast(&n3_s98), }; +#endif // sub_101866B0 - init helper: defaults + setter calls, in shipped order. void initType3Defaults(void* self) @@ -247,8 +424,8 @@ void initType3Defaults(void* self) F (self, 0x58) = 360.0f; U (self, 0x5C) = 0u; - n3_s45(self, 0, fbits(4.0f)); // +0x90 = 4.0, +0x94 = 0.25 - n3_s43(self, 0, 0u); // +0x8C = 0 + n3_s45(self RD9_THUNK_ARG, psmFloatArgFromBits(fbits(4.0f))); // +0x90 = 4.0, +0x94 = 0.25 + n3_s43(self RD9_THUNK_ARG, psmFloatArgFromBits(0u)); // +0x8C = 0 F (self, 0x0C) = 32.0f; F (self, 0x14C) = 0.03125f; // 1/32 @@ -271,11 +448,11 @@ void initType3Defaults(void* self) F (self, 0xC8) = 0.7f; F (self, 0xCC) = 0.8f; - { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n3_s39(self, 0, v); } - { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n3_s53(self, 0, v); } - { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n3_s55(self, 0, v); } - { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n3_s57(self, 0, v); } - { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n3_s59(self, 0, v); } + { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n3_s39(self RD9_THUNK_ARG, v); } + { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n3_s53(self RD9_THUNK_ARG, v); } + { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n3_s55(self RD9_THUNK_ARG, v); } + { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n3_s57(self RD9_THUNK_ARG, v); } + { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n3_s59(self RD9_THUNK_ARG, v); } U (self, 0x168)=0u; U(self,0x158)=0u; U(self,0x160)=0u; F (self, 0x15C) = 1.0f; @@ -294,8 +471,8 @@ void initType3Defaults(void* self) // geom_ParticleSystem_type3_ctor, 0x10186AA0. void* constructParticleSystemType3(void* mem, const void* nameString) { - ::memset(mem, 0, 0x1A8u); - U(mem, 0x00) = ::renddx9abi::addr(kVtable); + ::memset(mem, 0, PSM_DESCRIPTOR_SIZE(0x1A8u)); + *static_cast(mem) = kVtable; U(mem, 0x20) = 1065353216u; // 1.0 U(mem, 0x2C) = 1973272912u; // range sentinel @@ -304,10 +481,10 @@ void* constructParticleSystemType3(void* mem, const void* nameString) U(mem, 0x48) = 1065353216u; U(mem, 0x54) = 1973272912u; - // The manager supplies an internal VC7.1 name; native getters expose an owned HostString. - new (static_cast(mem) + 0x6C) ParticleHostString(); - new (static_cast(mem) + 0x16C) ParticleHostString( - ::renddx9abi::toHostString(*static_cast(nameString))); + // The manager supplies the renderer's own string; the getters expose an owned HostString. + new (&psmDescriptor3(mem, 0x6C)) ParticleHostString(); + new (&psmDescriptor3(mem, 0x16C)) ParticleHostString( + ::renddx9abi::toHostString(*static_cast(nameString))); initType3Defaults(mem); return mem; diff --git a/Code/BF2/Geom/ParticleSystem/ParticleTemplateResources.h b/Code/BF2/Geom/ParticleSystem/ParticleTemplateResources.h index 50468c79d..08b0a13d4 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleTemplateResources.h +++ b/Code/BF2/Geom/ParticleSystem/ParticleTemplateResources.h @@ -7,23 +7,27 @@ #include "../../RendDX9/TextureAtlas/TextureAtlas.h" #include "../../RendDX9/RendDX9Base.h" #include "../../../RendDX9Abi/EngineFile.h" +#include "../../GeomMisc/Debug.h" #include #include namespace dice { namespace hfe { namespace geom { // Manager an atlas-owned region, with no added reference for the caller. -dx9rend::TextureAtlasEntry* particleSystemFindTextureRegion(const vc71::string& name); +dx9rend::TextureAtlasEntry* particleSystemFindTextureRegion(const std::string& name); -// [CHOSEN helper factoring, recovered body] Both retail loaders reject an empty name before +// [CHOSEN helper factoring, recovered body] Both retail loaders reject an empty C string before // releasing the old direct texture or replacing the region. The atlas success arm leaves the // direct texture null: the region's page owns the texture used by rendering. +// PE 0x10176C20 +// PE 0x101784E0 inline bool particleTemplateLoadTexture(dx9rend::EngineTexture*& texture, dx9rend::TextureAtlasEntry*& region, - const vc71::string& name, - const char* qualifiedName, unsigned int diagnosticLine) + const std::string& name, + const char* diagnosticFile, unsigned int diagnosticLine) { - if (name.empty()) + // The retail comparison uses _stricmp against "", so a leading NUL also refuses. + if (name.c_str()[0] == '\0') return false; dx9rend::textureReleaseRef(texture); @@ -31,7 +35,7 @@ inline bool particleTemplateLoadTexture(dx9rend::EngineTexture*& texture, if (region) return true; - vc71::string path(name); + std::string path(name); path += ".dds"; if (::renddx9abi::engineFileExists(path)) { @@ -44,13 +48,9 @@ inline bool particleTemplateLoadTexture(dx9rend::EngineTexture*& texture, } else { - // [TEMP] [CHOSEN, not recovered] The only remaining loader boundary is the configurable - // Debug type-6 dispatch, not the normal texture/atlas path. - // [RETIRE-WHEN: particle-template-texture-debug-dispatch] - std::fprintf(stderr, "[FRONTIER] %s (Debug type 6, line %u): File %s not found!\n", - qualifiedName, diagnosticLine, name.c_str()); - std::fflush(stderr); - std::abort(); + // PE 0x10176D68 / 0x10178628. + ::renddx9abi::Debug(DebugTypeError, diagnosticFile, diagnosticLine, "") + << "File " << name << " not found!"; } return texture != 0; } diff --git a/Code/BF2/Geom/ParticleSystem/TrailSystemTemplate.cpp b/Code/BF2/Geom/ParticleSystem/TrailSystemTemplate.cpp index 1f01af9d2..38392d690 100644 --- a/Code/BF2/Geom/ParticleSystem/TrailSystemTemplate.cpp +++ b/Code/BF2/Geom/ParticleSystem/TrailSystemTemplate.cpp @@ -2,17 +2,26 @@ // Contains no simulation or per-particle update function. #ifdef BF2_IMAGE_RENDDX9 +#if !defined(_MSC_VER) +// [CHOSEN, not recovered] Compiler-typed native table entries. +#include "../../../RendDX9Abi/NativeVtable.h" +#include "ParticleSystemManager.h" +#endif +#include "../../../RendDX9Abi/ThunkAbi.h" +#include "ParticleRawLayout.h" +#include "../../Platform/X87Compat.h" #include "../XpLightManager.h" #include "../../../RendDX9Abi/HfeAbi.h" #include "../../../RendDX9Abi/ModuleCommon.h" #include "../../../RendDX9Abi/BfMemory.h" #include "../../../RendDX9Abi/Frontier.h" -#include "../../../RendDX9Abi/Vc71String.h" +#include #include "../../../RendDX9Abi/PluginAbi.h" // exact case: a Linux checkout is case-sensitive #include "../../../RendDX9Abi/EngineFile.h" #include "../../RendDX9/Texture.h" #include "../../RendDX9/RendDX9Base.h" +#include "../../GeomMisc/Debug.h" #include "ParticleSystemManager.h" #include #include @@ -26,165 +35,246 @@ namespace dice { namespace hfe { namespace geom { +void psmZeroTemplateBlock(void* block); // ParticleSystemTemplate.cpp + extern LightManager* g_LightManager; // Retail refresh dereferences this when affection is negative/NaN. +const Vec3* terrainOriginScratch(const Vec3& value); +const float* staticMeshPackVec4(const float value[3], float w); namespace { using ParticleHostString = ::renddx9abi::HostString; -static_assert(sizeof(ParticleHostString) <= 28, "trail host string exceeds its reserved span"); +static_assert(sizeof(ParticleHostString) <= kPsmDescriptorStringSpan, "trail host string exceeds its reserved span"); -inline unsigned& U (void* p, unsigned off) { return *reinterpret_cast(static_cast(p) + off); } -inline float& F (void* p, unsigned off) { return *reinterpret_cast(static_cast(p) + off); } -inline unsigned char& Bt(void* p, unsigned off) { return *reinterpret_cast(static_cast(p) + off); } -inline short& S16(void* p, unsigned off){ return *reinterpret_cast(static_cast(p) + off); } +inline unsigned& U (void* p, unsigned off) { return psmDescriptor2(p, off); } +inline float& F (void* p, unsigned off) { return psmDescriptor2(p, off); } +inline unsigned char& Bt(void* p, unsigned off) { return psmDescriptor2(p, off); } +inline short& S16(void* p, unsigned off){ return psmDescriptor2(p, off); } inline unsigned fbits(float f) { unsigned u; ::memcpy(&u, &f, 4); return u; } -#define PT_SET(name, off) void __fastcall name(void* s, void*, unsigned v){ U(s,(off)) = v; } -#define PT_GETF(name, off) float __fastcall name(void* s, void*){ return F(s,(off)); } -#define PT_GETD(name, off) unsigned __fastcall name(void* s, void*){ return U(s,(off)); } -#define PT_SETB(name, off) void __fastcall name(void* s, void*, unsigned v){ Bt(s,(off)) = static_cast(v); } -#define PT_GETB(name, off) unsigned __fastcall name(void* s, void*){ return Bt(s,(off)); } -#define PT_LEA(name, off) void* __fastcall name(void* s, void*){ return static_cast(s) + (off); } -#define PT_SETVEC(name, off, n) void __fastcall name(void* s, void*, const float* v){ for (int i=0;i<(n);++i) F(s,(off)+4u*i)=v[i]; } -#define PT_GETVEC(name, off, n) void* __fastcall name(void* s, void*, float* o){ for (int i=0;i<(n);++i) o[i]=F(s,(off)+4u*i); return o; } -#define PT_VEC3A(name, off) void __fastcall name(void* s, void*, unsigned a, unsigned b, unsigned c){ U(s,(off))=a; U(s,(off)+4)=b; U(s,(off)+8)=c; } - -void __fastcall n2_s2 (void* s, void*); -void __fastcall n2_s45(void* s, void*, unsigned a); +#define PT_SET(name, off) void RD9_THUNK name(void* s RD9_THUNK_EDX, unsigned v){ U(s,(off)) = v; } +#define PT_SETFLT(name, off) void RD9_THUNK name(void* s RD9_THUNK_EDX, PsmFloatArg v){ U(s,(off)) = psmFloatArgBits(v); } +#define PT_GETF(name, off) float RD9_THUNK name(void* s RD9_THUNK_EDX){ return F(s,(off)); } +#define PT_GETD(name, off) unsigned RD9_THUNK name(void* s RD9_THUNK_EDX){ return U(s,(off)); } +#define PT_SETB(name, off) void RD9_THUNK name(void* s RD9_THUNK_EDX, unsigned v){ Bt(s,(off)) = static_cast(v); } +#define PT_GETB(name, off) unsigned RD9_THUNK name(void* s RD9_THUNK_EDX){ return Bt(s,(off)); } +#define PT_LEA(name, off) void* RD9_THUNK name(void* s RD9_THUNK_EDX){ return &psmDescriptor2(s, (off)); } +#define PT_SETVEC(name, off, n) void RD9_THUNK name(void* s RD9_THUNK_EDX, const float* v) \ +{ \ + if ((n)==3 || (n)==4) \ + { \ + const float z=v[2],y=v[1],x=v[0],w=(n)==4 ? v[3] : 0.0f; \ + F(s,(off)+4)=y; F(s,(off))=x; F(s,(off)+8)=z; \ + if ((n)==4) F(s,(off)+12)=w; \ + } \ + else for (int i=0;i<(n);++i) F(s,(off)+4u*i)=v[i]; \ +} +#define PT_GETVEC(name, off, n) void* RD9_THUNK name(void* s RD9_THUNK_EDX, float* o) \ +{ \ + if ((n)==3) \ + { \ + const float z=F(s,(off)+8),y=F(s,(off)+4),x=F(s,(off)); \ + o[1]=y; o[0]=x; o[2]=z; \ + } \ + else for (int i=0;i<(n);++i) o[i]=F(s,(off)+4u*i); \ + return o; \ +} +#define PT_VEC3A(name, off) void RD9_THUNK name(void* s RD9_THUNK_EDX, PSM_VEC3_PARAMS){ U(s,(off))=PSM_VEC3_X; U(s,(off)+4)=PSM_VEC3_Y; U(s,(off)+8)=PSM_VEC3_Z; } + +void RD9_THUNK n2_s2 (void* s RD9_THUNK_EDX); +void RD9_THUNK n2_s45(void* s RD9_THUNK_EDX, PsmFloatArg a); void n2_recomputeUV(void* self); // shared trivial slots // PE 100E13B0 is RET 4, shared by one-argument setters 41/43/51/57/110. -void __fastcall n2_null(void*, void*, unsigned) { } -float __fastcall n2_ret0(void*, void*) { return 0.0f; } -unsigned __fastcall n2_ret1(void*, void*) { return 1; } +void RD9_THUNK n2_null(void* RD9_THUNK_EDX, unsigned) { } +#if !defined(_MSC_VER) +// [CHOSEN, not recovered] This shipped RET 4 body discards its argument. Give +// each native register category a typed entry instead of converting float bits +// or a graph address into the PE's unused integer stack carrier. +void n2_nullFloat(void* self, float) { n2_null(self, 0); } +void n2_nullGraph(void* self, const Vec4&) { n2_null(self, 0); } +#endif +float RD9_THUNK n2_ret0(void* RD9_THUNK_EDX) { return 0.0f; } +unsigned RD9_THUNK n2_ret1(void* RD9_THUNK_EDX) { return 1; } // simple slots -const ParticleHostString& __fastcall n2_s1(void* self, void*) -{ return *reinterpret_cast(static_cast(self) + 0x200); } +const ParticleHostString& RD9_THUNK n2_s1(void* self RD9_THUNK_EDX) +{ return psmDescriptor2(self, 0x200); } PT_SET (n2_s4, 0x64) PT_GETD(n2_s5, 0x64) PT_SET (n2_s6, 0x68) PT_GETD(n2_s7, 0x68) +// PE 0x10178A70 PT_SET (n2_s8, 0x6C) PT_GETD(n2_s9, 0x6C) PT_VEC3A(n2_s10, 0x14) PT_GETVEC(n2_s11, 0x14, 3) -PT_SET (n2_s12, 0x60) +PT_SETFLT(n2_s12, 0x60) PT_GETF(n2_s13, 0x60) -PT_SET (n2_s14, 0x5C) +PT_SETFLT(n2_s14, 0x5C) PT_GETF(n2_s15, 0x5C) +// PE 0x10188210 PT_SET (n2_s16, 0x224) PT_SETVEC(n2_s17, 0x20, 5) PT_LEA (n2_s18, 0x20) +// PE 0x10188220 PT_SETVEC(n2_s19, 0x34, 5) PT_LEA (n2_s20, 0x34) +// PE 0x10188250 PT_SETVEC(n2_s21, 0x48, 5) PT_LEA (n2_s22, 0x48) PT_GETF(n2_s24, 0x10) -PT_SET (n2_s25, 0x164) +// PE 0x10188330 +PT_SETFLT(n2_s25, 0x164) PT_GETF(n2_s26, 0x164) -PT_SET (n2_s27, 0x0C) +PT_SETFLT(n2_s27, 0x0C) PT_GETF(n2_s28, 0x0C) -PT_SET (n2_s29, 0x168) +PT_SETFLT(n2_s29, 0x168) PT_GETF(n2_s30, 0x168) +// PE 0x101881E0 PT_SETB(n2_s31, 0x16C) PT_GETB(n2_s32, 0x16C) -PT_SET (n2_s33, 0x178) +// PE 0x101881C0 +PT_SETFLT(n2_s33, 0x178) PT_GETF(n2_s34, 0x178) +// PE 0x101884E0 PT_SETVEC(n2_s35, 0x158, 3) +// PE 0x10188510 PT_GETVEC(n2_s36, 0x158, 3) +// PE 0x10187920 PT_GETVEC(n2_s38, 0x1AC, 3) +// PE 0x10187800 PT_SETVEC(n2_s39, 0x11C, 4) PT_LEA (n2_s40, 0x11C) PT_GETF(n2_s46, 0x70) -PT_SET (n2_s47, 0x78) +PT_SETFLT(n2_s47, 0x78) PT_GETF(n2_s48, 0x78) -PT_SET (n2_s49, 0x7C) +PT_SETFLT(n2_s49, 0x7C) PT_GETF(n2_s50, 0x7C) +// PE 0x10187890 PT_SETVEC(n2_s53, 0x12C, 4) PT_LEA (n2_s54, 0x12C) +// PE 0x101878C0 PT_SETVEC(n2_s55, 0x13C, 4) PT_LEA (n2_s56, 0x13C) +// PE 0x10187830 PT_SETVEC(n2_s59, 0xFC, 4) PT_LEA (n2_s60, 0xFC) -PT_SET (n2_s61, 0x88) +// PE 0x10178BE0 +PT_SETFLT(n2_s61, 0x88) PT_GETF(n2_s62, 0x88) +// PE 0x101882E0 PT_SETB(n2_s63, 0x9C) PT_GETB(n2_s64, 0x9C) -PT_SET (n2_s65, 0xA0) +PT_SETFLT(n2_s65, 0xA0) PT_GETF(n2_s66, 0xA0) -PT_SET (n2_s67, 0xA4) +PT_SETFLT(n2_s67, 0xA4) PT_GETF(n2_s68, 0xA4) +// PE 0x10188370 PT_SETB(n2_s69, 0x1C0) PT_GETB(n2_s70, 0x1C0) +// PE 0x10188390 PT_SETB(n2_s71, 0x8C) PT_GETB(n2_s72, 0x8C) -PT_SET (n2_s73, 0x90) +// PE 0x10178C20 +PT_SETFLT(n2_s73, 0x90) PT_GETF(n2_s74, 0x90) +// PE 0x1017A0A0 PT_SET (n2_s75, 0x234) PT_GETD(n2_s76, 0x234) -PT_SET (n2_s77, 0x238) +// PE 0x10188420 +PT_SETFLT(n2_s77, 0x238) PT_GETF(n2_s78, 0x238) -PT_SET (n2_s79, 0x23C) +// PE 0x10188440 +PT_SETFLT(n2_s79, 0x23C) PT_GETF(n2_s80, 0x23C) -PT_SET (n2_s81, 0x240) +// PE 0x10188460 +PT_SETFLT(n2_s81, 0x240) PT_GETF(n2_s82, 0x240) -PT_SET (n2_s83, 0x244) +// PE 0x10188480 +PT_SETFLT(n2_s83, 0x244) PT_GETF(n2_s84, 0x244) -PT_SET (n2_s85, 0x248) +// PE 0x101884A0 +PT_SETFLT(n2_s85, 0x248) PT_GETF(n2_s86, 0x248) -PT_SET (n2_s87, 0x24C) +// PE 0x101884C0 +PT_SETFLT(n2_s87, 0x24C) PT_GETF(n2_s88, 0x24C) PT_GETF(n2_s90, 0x1B8) -PT_SET (n2_s91, 0x14C) +// PE 0x101882A0 +PT_SETFLT(n2_s91, 0x14C) PT_GETF(n2_s92, 0x14C) -PT_SET (n2_s93, 0x150) +// PE 0x101882C0 +PT_SETFLT(n2_s93, 0x150) PT_GETF(n2_s94, 0x150) +// PE 0x10187860 PT_SETVEC(n2_s95, 0x10C, 4) PT_LEA (n2_s96, 0x10C) -PT_SET (n2_s97, 0x80) +PT_SETFLT(n2_s97, 0x80) PT_GETF(n2_s98, 0x80) -PT_SET (n2_s99, 0x17C) +// PE 0x10187210 +PT_SETFLT(n2_s99, 0x17C) PT_GETF(n2_s100, 0x17C) +// PE 0x101876C0 PT_GETVEC(n2_s102, 0x180, 3) +// PE 0x101877D0 PT_SETVEC(n2_s106, 0xEC, 4) PT_LEA (n2_s107, 0xEC) -PT_SET (n2_s108, 0xB4) +// PE 0x10187110 +PT_SETFLT(n2_s108, 0xB4) PT_GETF(n2_s109, 0xB4) +// PE 0x10188400 PT_SETB(n2_s112, 0x228) PT_GETB(n2_s113, 0x228) +// PE 0x10187290 PT_SETVEC(n2_s114, 0xAC, 2) -PT_GETVEC(n2_s115, 0xAC, 2) -const ParticleHostString& __fastcall n2_s117(void* self, void*) -{ return *reinterpret_cast(static_cast(self) + 0x1E4); } +// PE 0x10187950 +void* RD9_THUNK n2_s115(void* self RD9_THUNK_EDX, float* out) +{ + static float scratch[2]; + scratch[0]=F(self,0xAC); scratch[1]=F(self,0xB0); + const float y=scratch[1],x=scratch[0]; + out[0]=x; out[1]=y; return out; +} +const ParticleHostString& RD9_THUNK n2_s117(void* self RD9_THUNK_EDX) +{ return psmDescriptor2(self, 0x1E4); } +// PE 0x101883B0 PT_SETB(n2_s118, 0x1C8) PT_GETB(n2_s119, 0x1C8) -PT_SET (n2_s120, 0x1C4) +// PE 0x101883D0 +PT_SETFLT(n2_s120, 0x1C4) PT_GETF(n2_s121, 0x1C4) -PT_SET (n2_s126, 0x1CC) +// PE 0x10178B20 +PT_SETFLT(n2_s126, 0x1CC) PT_GETF(n2_s127, 0x1CC) -PT_SET (n2_s128, 0x1D0) +PT_SETFLT(n2_s128, 0x1D0) PT_GETF(n2_s129, 0x1D0) +// PE 0x101883E0 PT_SET (n2_s130, 0x1D4) PT_GETD(n2_s131, 0x1D4) PT_GETD(n2_s133, 0x1D8) -PT_SET (n2_s134, 0xBC) +// PE 0x10187190 +PT_SETFLT(n2_s134, 0xBC) PT_GETF(n2_s135, 0xBC) -PT_SET (n2_s136, 0xC0) +// PE 0x101871B0 +PT_SETFLT(n2_s136, 0xC0) PT_GETF(n2_s137, 0xC0) -PT_SET (n2_s138, 0xC4) +// PE 0x101871D0 +PT_SETFLT(n2_s138, 0xC4) PT_GETF(n2_s139, 0xC4) -PT_SET (n2_s140, 0xC8) +// PE 0x101871F0 +PT_SETFLT(n2_s140, 0xC8) PT_GETF(n2_s141, 0xC8) PT_GETD(n2_s143, 0x220) PT_GETF(n2_s145, 0x22C) // complex slots -unsigned __fastcall n2_s3(void*, void*) { return 2; } // emitter type id +unsigned RD9_THUNK n2_s3(void* RD9_THUNK_EDX) { return 2; } // emitter type id -void __fastcall n2_s2(void* self, void*) +// PE 0x10188060 +void RD9_THUNK n2_s2(void* self RD9_THUNK_EDX) { if (!(F(self, 0x17C) >= 0.0f)) { @@ -208,64 +298,101 @@ void __fastcall n2_s2(void* self, void*) n2_recomputeUV(self); } -void __fastcall n2_s23(void* self, void*, unsigned a) { U(self, 0x10) = a; F(self, 0x170) = 1.0f / F(self, 0x10); } +// PE 0x10188310 +void RD9_THUNK n2_s23(void* self RD9_THUNK_EDX, PsmFloatArg a) { U(self, 0x10) = psmFloatArgBits(a); F(self, 0x170) = 1.0f / F(self, 0x10); } -void __fastcall n2_s37(void* self, void*, const float* v) +// PE 0x101878F0 +void RD9_THUNK n2_s37(void* self RD9_THUNK_EDX, const float* v) { - F(self, 0x1AC) = v[0]; F(self, 0x1B0) = v[1]; F(self, 0x1B4) = v[2]; - float* p = reinterpret_cast(static_cast(self) + 0x1AC); - float s = p[0] * p[0] + p[1] * p[1] + p[2] * p[2]; - if (fabsf(s - 1.0f) >= FLT_EPSILON) + const float z=v[2],y=v[1],x=v[0]; + F(self,0x1B0)=y; F(self,0x1AC)=x; F(self,0x1B4)=z; + float* p = &psmDescriptor2(self, 0x1AC); +#if defined(__APPLE__) + // [CHOSEN, not recovered] The squared sum spills once; the inverse remains live. + using bf2x87::wide; + const float s=static_cast(wide(p[0])*wide(p[0])+wide(p[1])*wide(p[1])+wide(p[2])*wide(p[2])); + const bf2x87::Real error=bf2x87::abs(wide(s)-wide(1)); +#else + const float s=static_cast(static_cast(p[0])*p[0]+static_cast(p[1])*p[1] + +static_cast(p[2])*p[2]); + const double error=::fabs(static_cast(s)-1.0); +#endif + if (!(error < FLT_EPSILON)) { if (fabsf(s) < FLT_EPSILON) { p[0] = p[1] = p[2] = 0.0f; } - else { float inv = 1.0f / sqrtf(s); p[0] *= inv; p[1] *= inv; p[2] *= inv; } + else + { +#if defined(__APPLE__) + const bf2x87::Real inv=wide(1)/bf2x87::squareRoot(wide(s)); + p[0]=static_cast(inv*wide(p[0])); p[1]=static_cast(inv*wide(p[1])); + p[2]=static_cast(inv*wide(p[2])); +#else + const double inv=1.0/::sqrt(static_cast(s)); + p[0]=static_cast(inv*p[0]); p[1]=static_cast(inv*p[1]); p[2]=static_cast(inv*p[2]); +#endif + } } } -void __fastcall n2_s45(void* self, void*, unsigned a) { U(self, 0x70) = a; F(self, 0x74) = 1.0f / F(self, 0x70); } +// PE 0x101870D0 +void RD9_THUNK n2_s45(void* self RD9_THUNK_EDX, PsmFloatArg a) { U(self, 0x70) = psmFloatArgBits(a); F(self, 0x74) = 1.0f / F(self, 0x70); } // a virtual tail call to slot 56, retaining possible overrides. -const Vec4& __fastcall n2_s58(void* self, void*) +const Vec4& RD9_THUNK n2_s58(void* self RD9_THUNK_EDX) { return static_cast(self)->getAirResistanceGraph(); } +// PE 0x10187130 // slot 89: dual write. -void __fastcall n2_s89(void* self, void*, unsigned a) { U(self, 0xB8) = a; U(self, 0x1B8) = a; } +void RD9_THUNK n2_s89(void* self RD9_THUNK_EDX, PsmFloatArg a) { U(self, 0xB8) = psmFloatArgBits(a); U(self, 0x1B8) = psmFloatArgBits(a); } // slot 101: Vec3 at +0x180 + mirror +0xCC. -void __fastcall n2_s101(void* self, void*, const float* v) +// PE 0x10187670 +void RD9_THUNK n2_s101(void* self RD9_THUNK_EDX, const float* v) { - F(self, 0x180) = v[0]; F(self, 0x184) = v[1]; F(self, 0x188) = v[2]; - F(self, 0xCC) = v[0]; F(self, 0xD0) = v[1]; F(self, 0xD4) = v[2]; + const float z=v[2],y=v[1],x=v[0]; + F(self,0x184)=y; F(self,0x180)=x; F(self,0x188)=z; + F(self,0xCC)=x; F(self,0xD0)=F(self,0x184); F(self,0xD4)=F(self,0x188); } // slot 103: Vec3 -> Vec4 {x,y,z,1} at +0x18C + mirror +0xDC. -void __fastcall n2_s103(void* self, void*, const float* v) +// PE 0x101876F0 +void RD9_THUNK n2_s103(void* self RD9_THUNK_EDX, const float* v) { - F(self, 0x18C) = v[0]; F(self, 0x190) = v[1]; F(self, 0x194) = v[2]; F(self, 0x198) = 1.0f; - F(self, 0xDC) = v[0]; F(self, 0xE0) = v[1]; F(self, 0xE4) = v[2]; F(self, 0xE8) = 1.0f; + const float* const packed=staticMeshPackVec4(v,1.0f); + const float w=packed[3],z=packed[2],y=packed[1],x=packed[0]; + F(self,0x190)=y; F(self,0x18C)=x; F(self,0x194)=z; F(self,0x198)=w; + F(self,0xDC)=x; F(self,0xE0)=F(self,0x190); + F(self,0xE4)=F(self,0x194); F(self,0xE8)=F(self,0x198); } // slot 104: get the +0x18C color as Vec3. -void* __fastcall n2_s104(void* self, void*, float* out) +// PE 0x10187760 +void* RD9_THUNK n2_s104(void* self RD9_THUNK_EDX, float* out) { - out[0] = F(self, 0x18C); out[1] = F(self, 0x190); out[2] = F(self, 0x194); + const Vec3* const packed=terrainOriginScratch(psmDescriptor2(self,0x18C)); + const float z=packed->z,y=packed->y,x=packed->x; + out[1]=y; out[0]=x; out[2]=z; return out; } // slot 105: Vec3 -> Vec4 {x,y,z,1} at +0x19C (no mirror). -void __fastcall n2_s105(void* self, void*, const float* v) +// PE 0x10187790 +void RD9_THUNK n2_s105(void* self RD9_THUNK_EDX, const float* v) { - F(self, 0x19C) = v[0]; F(self, 0x1A0) = v[1]; F(self, 0x1A4) = v[2]; F(self, 0x1A8) = 1.0f; + const float* const packed=staticMeshPackVec4(v,1.0f); + const float w=packed[3],z=packed[2],y=packed[1],x=packed[0]; + F(self,0x1A0)=y; F(self,0x19C)=x; F(self,0x1A4)=z; F(self,0x1A8)=w; } // unlike the sprite/NSA loader, trails use a direct texture without an atlas lookup. -bool n2_loadTexture(void* self, const vc71::string& name) +// PE 0x10187CD0 +bool n2_loadTexture(void* self, const std::string& name) { if (name.empty()) return false; - dx9rend::EngineTexture*& texture = *reinterpret_cast(static_cast(self) + 0x21C); + dx9rend::EngineTexture*& texture = psmDescriptor2(self, 0x21C); dx9rend::textureReleaseRef(texture); - vc71::string path(name); + std::string path(name); path += ".dds"; if (::renddx9abi::engineFileExists(path)) { @@ -276,23 +403,23 @@ bool n2_loadTexture(void* self, const vc71::string& name) } else { - // [TEMP] [CHOSEN, not recovered] Only the configurable diagnostic dispatch remains. - // [RETIRE-WHEN: particle-template-texture-debug-dispatch] - std::fprintf(stderr, "[FRONTIER] dice::hfe::geom::TrailSystemTemplate::setTextureName (Debug type 6, line 169): File %s not found!\n", name.c_str()); - std::fflush(stderr); - std::abort(); + // PE 0x10187DE9. + ::renddx9abi::Debug(DebugTypeError, + "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\ParticleSystem\\TrailSystemTemplate.cpp", + 169, "") << "File " << name << " not found!"; } return texture != 0; } // Keep the authored name copy before loading and the empty-name refusal behavior. -void __fastcall n2_s116(void* self, void*, const ParticleHostString& source) +// PE 0x10187E50 +void RD9_THUNK n2_s116(void* self RD9_THUNK_EDX, const ParticleHostString& source) { - ParticleHostString* dst = reinterpret_cast(static_cast(self) + 0x1E4); + ParticleHostString* dst = &psmDescriptor2(self, 0x1E4); if (dst->size() != source.size() || ::memcmp(dst->c_str(), source.c_str(), source.size()) != 0) { *dst = source; - const vc71::string& resourceName = ::renddx9abi::toVc71String(source); + const std::string& resourceName = ::renddx9abi::fromHostString(source); if (!n2_loadTexture(self, resourceName)) *dst = ParticleHostString(); } @@ -300,47 +427,80 @@ void __fastcall n2_s116(void* self, void*, const ParticleHostString& source) // slots 122-125: texture-relative UV; null texture -> setters no-op, getters 0, // width/height at (+0x21C)+0x28/+0x2C. -void __fastcall n2_s122(void* self, void*, unsigned a) +// PE 0x101879B0 +void RD9_THUNK n2_s122(void* self RD9_THUNK_EDX, unsigned a) { - void* t = *reinterpret_cast(static_cast(self) + 0x21C); - if (t) F(self, 0x1CC) = static_cast(a) / static_cast(U(t, 0x28)); + void* t = psmDescriptor2(self, 0x21C); +#if defined(__APPLE__) + // [CHOSEN, not recovered] Both unsigned conversions remain live in the PE. + if (t) F(self,0x1CC)=static_cast(bf2x87::wide(a) + /bf2x87::wide(static_cast(t)->width)); +#else + if (t) F(self,0x1CC)=static_cast(static_cast(a) + /static_cast(static_cast(t)->width)); +#endif } -unsigned __fastcall n2_s123(void* self, void*) +// PE 0x101879F0 +unsigned RD9_THUNK n2_s123(void* self RD9_THUNK_EDX) { - void* t = *reinterpret_cast(static_cast(self) + 0x21C); - if (t) return static_cast(static_cast(static_cast(U(t, 0x28)) * F(self, 0x1CC))); + void* t = psmDescriptor2(self, 0x21C); +#if defined(__APPLE__) + // [CHOSEN, not recovered] Keep the unsigned dimension live through truncating FISTP. + if (t) return static_cast(bf2x87::toIntTruncate( + bf2x87::wide(static_cast(t)->width)*bf2x87::wide(F(self,0x1CC)))); +#else + if (t) return static_cast(static_cast(static_cast(static_cast(t)->width)*F(self,0x1CC))); +#endif return 0; } -void __fastcall n2_s124(void* self, void*, unsigned a) +// PE 0x10187A50 +void RD9_THUNK n2_s124(void* self RD9_THUNK_EDX, unsigned a) { - void* t = *reinterpret_cast(static_cast(self) + 0x21C); - if (t) F(self, 0x1D0) = static_cast(a) / static_cast(U(t, 0x2C)); + void* t = psmDescriptor2(self, 0x21C); +#if defined(__APPLE__) + // [CHOSEN, not recovered] Only this setter spills its numerator to float first. + if (t) F(self,0x1D0)=static_cast(bf2x87::wide(static_cast(a)) + /bf2x87::wide(static_cast(t)->height)); +#else + if (t) F(self,0x1D0)=static_cast(static_cast(static_cast(a)) + /static_cast(static_cast(t)->height)); +#endif } -unsigned __fastcall n2_s125(void* self, void*) +// PE 0x10187AA0 +unsigned RD9_THUNK n2_s125(void* self RD9_THUNK_EDX) { - void* t = *reinterpret_cast(static_cast(self) + 0x21C); - if (t) return static_cast(static_cast(static_cast(U(t, 0x2C)) * F(self, 0x1D0))); + void* t = psmDescriptor2(self, 0x21C); +#if defined(__APPLE__) + // [CHOSEN, not recovered] Keep the unsigned dimension live through truncating FISTP. + if (t) return static_cast(bf2x87::toIntTruncate( + bf2x87::wide(static_cast(t)->height)*bf2x87::wide(F(self,0x1D0)))); +#else + if (t) return static_cast(static_cast(static_cast(static_cast(t)->height)*F(self,0x1D0))); +#endif return 0; } +// PE 0x101872B0 // slot 132: set +0x1D8 count; cache 1/count at +0x1DC. -void __fastcall n2_s132(void* self, void*, unsigned a) +void RD9_THUNK n2_s132(void* self RD9_THUNK_EDX, unsigned a) { U(self, 0x1D8) = a; if (a) F(self, 0x1DC) = 1.0f / static_cast(a); else U(self, 0x1DC) = 0; } +// PE 0x10187160 // slot 142: clamped 1..3. -void __fastcall n2_s142(void* self, void*, unsigned a) { if (a && a <= 3) U(self, 0x220) = a; } +void RD9_THUNK n2_s142(void* self RD9_THUNK_EDX, unsigned a) { if (a && a <= 3) U(self, 0x220) = a; } +// PE 0x10188540 // slot 144: radius + radius^2. -void __fastcall n2_s144(void* self, void*, unsigned a) { U(self, 0x22C) = a; F(self, 0x230) = F(self, 0x22C) * F(self, 0x22C); } +void RD9_THUNK n2_s144(void* self RD9_THUNK_EDX, PsmFloatArg a) { U(self, 0x22C) = psmFloatArgBits(a); F(self, 0x230) = F(self, 0x22C) * F(self, 0x22C); } // PE 10187EA0 (slot 2 tail): animation enable, not the independent static-system flag, selects UV. void n2_recomputeUV(void* self) { - void* res = *reinterpret_cast(static_cast(self) + 0x21C); + void* res = psmDescriptor2(self, 0x21C); if (res) { S16(self, 0x1E0) = 0; @@ -353,20 +513,199 @@ void n2_recomputeUV(void* self) } } -// slot 0 (PE 10188560 -> 10187C50): release the texture and destroy both host strings. -void* __fastcall n2_dtor(void* self, void*, int flags) +// Trail descriptor members that nothing calls or references in 1.50: unreachable in 1.50: no code or +// data references. Each body is the listing's own. The names are [CHOSEN, not recovered]: no caller +// exposes them. + +// PE 0x10187300: store the +0x1DC float (the reciprocal cache of the +0x1D8 count, slot 132); the paired +// getter at 0x10187310 answers st0, so float is the [CHOSEN, not recovered] argument type. +void n2_setCountReciprocal(void* self, float value) +{ + U(self, 0x1DC) = fbits(value); +} + +// PE 0x10187330: store the +0x98 float; the paired getter at 0x10187340 answers st0. +void n2_set98(void* self, float value) +{ + U(self, 0x98) = fbits(value); +} + +// PE 0x10188040: load the texture named by the stored +0x1E4 name (the result is not tested), then +// recompute the UV state (tail jump to n2_recomputeUV, PE 0x10187EA0). +void n2_reloadTexture(void* self) +{ + n2_loadTexture(self, ::renddx9abi::fromHostString(psmDescriptor2(self, 0x1E4))); + n2_recomputeUV(self); +} + +// PE 0x10188560, 0x10187C50 +// slot 0 (PE 0x10188560 -> PE 0x10187C50): release the texture and destroy both host strings. +void* RD9_THUNK n2_dtor(void* self RD9_THUNK_EDX, int flags) { - dx9rend::EngineTexture*& texture = *reinterpret_cast(static_cast(self) + 0x21C); + dx9rend::EngineTexture*& texture = psmDescriptor2(self, 0x21C); dx9rend::textureReleaseRef(texture); // Retail rereads the slot after the first release before destroying the embedded members. dx9rend::textureReleaseRef(texture); - reinterpret_cast(static_cast(self) + 0x200)->~ParticleHostString(); - reinterpret_cast(static_cast(self) + 0x1E4)->~ParticleHostString(); + psmDescriptor2(self, 0x200).~ParticleHostString(); + psmDescriptor2(self, 0x1E4).~ParticleHostString(); if (flags & 1) ::renddx9abi::engineFree(self); return self; } +#if !defined(_MSC_VER) +// [CHOSEN, not recovered] Match the shared consumer interface under the native ABI. +const void* const kVtable[] = +{ + BF2_NATIVE_DTOR(n2_dtor, complete), + BF2_NATIVE_DTOR(n2_dtor, deleting), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getName, n2_s1), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, refreshDerivedState, n2_s2), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getSystemType, n2_s3), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setEmitPrio, n2_s4), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getEmitPrio, n2_s5), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setLodDistance, n2_s6), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getLodDistance, n2_s7), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setQualityLevel, n2_s8), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getQualityLevel, n2_s9), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setEmitRadius, n2_s10), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getEmitRadius, n2_s11), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setRadialDirection, n2_s12), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getRadialDirection, n2_s13), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setRandomRadialDirection, n2_s14), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getRandomRadialDirection, n2_s15), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setEmitterType, n2_s16), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setEmitRangeX, n2_s17), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getEmitRangeX, n2_s18), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setEmitRangeY, n2_s19), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getEmitRangeY, n2_s20), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setEmitRangeZ, n2_s21), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getEmitRangeZ, n2_s22), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setEmitFrequency, n2_s23), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getEmitFrequency, n2_s24), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setEmitSpeed, n2_s25), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getEmitSpeed, n2_s26), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setPreWarmTime, n2_s27), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getPreWarmTime, n2_s28), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setEmitTime, n2_s29), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getEmitTime, n2_s30), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setIsLooping, n2_s31), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getIsLooping, n2_s32), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setEmitDelay, n2_s33), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getEmitDelay, n2_s34), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setRandomDirectionAngle, n2_s35), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getRandomDirectionAngle, n2_s36), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setEmitDirection, n2_s37), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getEmitDirection, n2_s38), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setRotationGraph, n2_s39), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getRotationGraph, n2_s40), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setAlignRotationToSpeed, n2_null), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getAlignRotationToSpeed, n2_ret1), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setRandomTimeToLive, n2_nullFloat), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getRandomTimeToLive, n2_ret0), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setTimeToLive, n2_s45), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getTimeToLive, n2_s46), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setGravity, n2_s47), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getGravity, n2_s48), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setAirResistance, n2_s49), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getAirResistance, n2_s50), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setRandomSpeed, n2_nullFloat), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getRandomSpeed, n2_ret0), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setGravityGraph, n2_s53), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getGravityGraph, n2_s54), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setAirResistanceGraph, n2_s55), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getAirResistanceGraph, n2_s56), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setEmitSpeedGraph, n2_nullGraph), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getEmitSpeedGraph, n2_s58), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setTransparencyGraph, n2_s59), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getTransparencyGraph, n2_s60), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setWindAffectionFactor, n2_s61), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getWindAffectionFactor, n2_s62), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setCollisionEnable, n2_s63), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getCollisionEnable, n2_s64), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setCollisionSpeedAlongNormal, n2_s65), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getCollisionSpeedAlongNormal, n2_s66), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setCollisionSpeedAlongPlane, n2_s67), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getCollisionSpeedAlongPlane, n2_s68), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setIsLocalSystem, n2_s69), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getIsLocalSystem, n2_s70), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setForceToWaterSurface, n2_s71), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getForceToWaterSurface, n2_s72), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setWaterSurfaceOffset, n2_s73), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getWaterSurfaceOffset, n2_s74), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setGasCloudType, n2_s75), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getGasCloudType, n2_s76), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setBlurryVisionTime, n2_s77), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getBlurryVisionTime, n2_s78), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setBlurryVisionHoldTime, n2_s79), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getBlurryVisionHoldTime, n2_s80), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setMinGasCloudRadius, n2_s81), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getMinGasCloudRadius, n2_s82), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setMaxGasCloudRadius, n2_s83), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getMaxGasCloudRadius, n2_s84), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setGasCloudRadiusTime, n2_s85), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getGasCloudRadiusTime, n2_s86), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setGasCloudDamage, n2_s87), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getGasCloudDamage, n2_s88), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setParticleMaxSize, n2_s89), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getParticleMaxSize, n2_s90), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setRandomSize, n2_s91), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getRandomSize, n2_s92), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setRandomIntensity, n2_s93), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getRandomIntensity, n2_s94), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setSizeGraph, n2_s95), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getSizeGraph, n2_s96), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setAlphaCull, n2_s97), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getAlphaCull, n2_s98), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setLightAffectionFactor, n2_s99), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getLightAffectionFactor, n2_s100), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setColor1, n2_s101), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getColor1, n2_s102), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setColor2, n2_s103), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getColor2, n2_s104), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, reserved105, n2_s105), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setColorBlendGraph, n2_s106), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getColorBlendGraph, n2_s107), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setLightMapIntensityOffset, n2_s108), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getLightMapIntensityOffset, n2_s109), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setDirectionalScale, n2_nullFloat), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getDirectionalScale, n2_ret0), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setIsStaticSystem, n2_s112), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getIsStaticSystem, n2_s113), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, reserved114, n2_s114), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, reserved115, n2_s115), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setTextureName, n2_s116), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getTextureName, n2_s117), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setAnimationEnable, n2_s118), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getAnimationEnable, n2_s119), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setAnimationSpeed, n2_s120), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getAnimationSpeed, n2_s121), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setAnimationFrameWidth, n2_s122), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getAnimationFrameWidth, n2_s123), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setAnimationFrameHeight, n2_s124), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getAnimationFrameHeight, n2_s125), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setAnimationFrameWidthRelative, n2_s126), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getAnimationFrameWidthRelative, n2_s127), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setAnimationFrameHeightRelative, n2_s128), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getAnimationFrameHeightRelative, n2_s129), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setAnimationFrameCount, n2_s130), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getAnimationFrameCount, n2_s131), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setAnimationFrameCountX, n2_s132), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getAnimationFrameCountX, n2_s133), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setFadeInFactor, n2_s134), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getFadeInFactor, n2_s135), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setFadeOutFactor, n2_s136), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getFadeOutFactor, n2_s137), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setTextureTileFactor, n2_s138), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getTextureTileFactor, n2_s139), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setTextureOffsetVelocity, n2_s140), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getTextureOffsetVelocity, n2_s141), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setNumPlanes, n2_s142), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getNumPlanes, n2_s143), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, setMinTrailVelocity, n2_s144), + BF2_NATIVE_SLOT(::dice::hfe::geom::IParticleSystemTemplateType2, getMinTrailVelocity, n2_s145), +}; +#else const void* const kVtable[146] = { reinterpret_cast(&n2_dtor), reinterpret_cast(&n2_s1), reinterpret_cast(&n2_s2), reinterpret_cast(&n2_s3), @@ -407,6 +746,7 @@ const void* const kVtable[146] = reinterpret_cast(&n2_s140), reinterpret_cast(&n2_s141), reinterpret_cast(&n2_s142), reinterpret_cast(&n2_s143), reinterpret_cast(&n2_s144), reinterpret_cast(&n2_s145), }; +#endif // sub_10187350 - init helper. void initType2Defaults(void* self) @@ -440,30 +780,30 @@ void initType2Defaults(void* self) F (self, 0x84) = 1.0f; U (self, 0x14C)=0u; U(self,0x150)=0u; U(self,0x154)=0u; U(self,0x158)=0u; U(self,0x15C)=0u; U(self,0x160)=0u; - n2_s99 (self, 0, static_cast(-1082130432)); // +0x17C = -1.0 - { float v[3] = { 1.0f, 1.0f, 1.0f }; n2_s101(self, 0, v); } - { float v[3] = { 1.0f, 1.0f, 1.0f }; n2_s103(self, 0, v); } - { float v[3] = { 1.0f, 1.0f, 1.0f }; n2_s105(self, 0, v); } + n2_s99 (self RD9_THUNK_ARG, psmFloatArgFromBits(static_cast(-1082130432))); // +0x17C = -1.0 + { float v[3] = { 1.0f, 1.0f, 1.0f }; n2_s101(self RD9_THUNK_ARG, v); } + { float v[3] = { 1.0f, 1.0f, 1.0f }; n2_s103(self RD9_THUNK_ARG, v); } + { float v[3] = { 1.0f, 1.0f, 1.0f }; n2_s105(self RD9_THUNK_ARG, v); } Bt(self, 0x9C)=0; F(self,0xA0)=0.7f; F(self,0xA4)=0.8f; U(self,0xA8)=2u; - n2_s89 (self, 0, fbits(1.0f)); // +0xB8 & +0x1B8 = 1.0 - n2_s108(self, 0, 0u); // +0xB4 = 0 - n2_s45 (self, 0, fbits(4.0f)); // +0x70 = 4.0, +0x74 = 0.25 - n2_null(self, 0, 0u); // slot 43 nullsub (one float argument) - { float v[4] = { 0.0f, 0.0f, 1.0f, 0.0f }; n2_s106(self, 0, v); } - { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n2_s59 (self, 0, v); } - { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n2_s95 (self, 0, v); } - { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n2_s53 (self, 0, v); } - { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n2_s55 (self, 0, v); } + n2_s89 (self RD9_THUNK_ARG, psmFloatArgFromBits(fbits(1.0f))); // +0xB8 & +0x1B8 = 1.0 + n2_s108(self RD9_THUNK_ARG, psmFloatArgFromBits(0u)); // +0xB4 = 0 + n2_s45 (self RD9_THUNK_ARG, psmFloatArgFromBits(fbits(4.0f))); // +0x70 = 4.0, +0x74 = 0.25 + n2_null(self RD9_THUNK_ARG, 0u); // slot 43 nullsub (one float argument) + { float v[4] = { 0.0f, 0.0f, 1.0f, 0.0f }; n2_s106(self RD9_THUNK_ARG, v); } + { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n2_s59 (self RD9_THUNK_ARG, v); } + { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n2_s95 (self RD9_THUNK_ARG, v); } + { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n2_s53 (self RD9_THUNK_ARG, v); } + { float v[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; n2_s55 (self RD9_THUNK_ARG, v); } U (self, 0x1AC)=0u; F(self,0x1B0)=1.0f; U(self,0x1B4)=0u; Bt(self,0x1C0)=0; Bt(self,0x228)=0; - { ParticleHostString empty; *reinterpret_cast(static_cast(self) + 0x1E4) = empty; } + { ParticleHostString empty; psmDescriptor2(self, 0x1E4) = empty; } F (self, 0x1C4)=1.0f; Bt(self,0x1C8)=0; U(self,0x1CC)=0u; U(self,0x1D0)=0u; U(self,0x1D4)=0u; U(self,0x1D8)=0u; U(self,0x1DC)=0u; - { float v[2] = { 1.0f, 1.0f }; n2_s114(self, 0, v); } // +0xAC/+0xB0 = 1.0 - n2_s134(self, 0, 0u); // +0xBC = 0 - n2_s136(self, 0, 0u); // +0xC0 = 0 - n2_s138(self, 0, fbits(1.0f)); // +0xC4 = 1.0 + { float v[2] = { 1.0f, 1.0f }; n2_s114(self RD9_THUNK_ARG, v); } // +0xAC/+0xB0 = 1.0 + n2_s134(self RD9_THUNK_ARG, psmFloatArgFromBits(0u)); // +0xBC = 0 + n2_s136(self RD9_THUNK_ARG, psmFloatArgFromBits(0u)); // +0xC0 = 0 + n2_s138(self RD9_THUNK_ARG, psmFloatArgFromBits(fbits(1.0f))); // +0xC4 = 1.0 F (self, 0x238)=20.0f; F(self,0x23C)=20.0f; U(self,0x22C)=0u; U(self,0x230)=0u; U(self,0x234)=0u; F (self, 0x240)=3.0f; F(self,0x244)=10.0f; F(self,0x248)=3.0f; F(self,0x24C)=2.0f; @@ -474,8 +814,8 @@ void initType2Defaults(void* self) // geom_TrailSystemTemplate_ctor, 0x10187F00. void* constructParticleSystemType2(void* mem, const void* nameString) { - ::memset(mem, 0, 0x250u); - U(mem, 0x00) = ::renddx9abi::addr(kVtable); + ::memset(mem, 0, PSM_DESCRIPTOR_SIZE(0x250u)); + *static_cast(mem) = kVtable; U(mem, 0x24) = 1065353216u; // 1.0 U(mem, 0x30) = 1973272912u; // range sentinel @@ -483,11 +823,11 @@ void* constructParticleSystemType2(void* mem, const void* nameString) U(mem, 0x44) = 1973272912u; U(mem, 0x4C) = 1065353216u; U(mem, 0x58) = 1973272912u; - // sub_10188150(this+0xAC): 112-byte zero-fill - covered by the memset. + psmZeroTemplateBlock(&psmDescriptor2(mem, 0xAC)); // redundant after the memset - new (static_cast(mem) + 0x1E4) ParticleHostString(); - new (static_cast(mem) + 0x200) ParticleHostString( - ::renddx9abi::toHostString(*static_cast(nameString))); + new (&psmDescriptor2(mem, 0x1E4)) ParticleHostString(); + new (&psmDescriptor2(mem, 0x200)) ParticleHostString( + ::renddx9abi::toHostString(*static_cast(nameString))); initType2Defaults(mem); return mem; diff --git a/Code/BF2/Geom/QuadPatch.cpp b/Code/BF2/Geom/QuadPatch.cpp index 9e0259d20..2890d9f71 100644 --- a/Code/BF2/Geom/QuadPatch.cpp +++ b/Code/BF2/Geom/QuadPatch.cpp @@ -3,35 +3,54 @@ #ifdef BF2_IMAGE_RENDDX9 +#if defined(__APPLE__) +#include "../Platform/X87Compat.h" // [CHOSEN, not recovered] Retain x87 intermediates on native macOS. +#endif + #include "../../RendDX9Abi/PluginAbi.h" +#include "../Core/StringUtil.h" // formatString (sub_10074AB0) #include "../../RendDX9Abi/PluginEntry.h" #include "../../RendDX9Abi/HostFileAbi.h" #include "../../RendDX9Abi/BfMemory.h" #include "../../RendDX9Abi/Frontier.h" -#include "../../RendDX9Abi/Vc71String.h" -#include "../../RendDX9Abi/Vc71Vector.h" +#include +#include "../../RendDX9Abi/D3dx9Sdk.h" #include "QuadPatch.h" +#include "RaQuadPatchAdapter.h" +#include "MeshTemplate.h" #include "Terrain.h" #include "XpLightManager.h" +#include "UndergrowthSystem.h" +#include "SkyDome.h" +#include "../Core/Debug.h" #include "../Math/Frustum.h" +#include "../RendDX9/RendDX9Math.h" // the RendDX9.dll Math copies #include "../Math/Mat4.h" #include "../Physics/HeightmapCluster.h" #include "../Physics/Heightmap.h" #include "../RendDX9/RendDX9Base.h" +#include "../RendDX9/QueueProfiler.h" #include "../RendDX9/ShaderParameter.h" +#include "../RendDX9/Ra/RaShader.h" #include "../RendDX9/Texture.h" #include "../RendMisc/IRenderView.h" +#include "../RendMisc/IRenderer.h" +#include "../RendMisc/EnvMapSystem/EnvMapManager.h" // the borrowed environment texture #include #include #include #include +#include #include +#include namespace dice { namespace hfe { namespace dx9rend { +extern void* g_rendererBase; +extern void* g_renderQueues; void* bufferManagerCreateVertexBuffer(unsigned int count, unsigned int stride, unsigned int usage, const char* name); void* vertexBufferLock(void* wrapper, unsigned int offsetVerts, unsigned int countVerts, @@ -48,7 +67,9 @@ void vertexBufferRelease(void* wrapper); void bufferManagerRemoveIndexBuffer(void* wrapper); // QueryManager.cpp - the Query holders' inline `if (!--q->refCount) { sub_10003FA0(q); free(q); }`. void queryReleaseRef(void* query); +void* queryManagerCreateQuery(int type); void vertexBufferBindStream(void* wrapper, unsigned int stream); +IDirect3DVertexBuffer9* vertexBufferD3D(void* wrapper); void indexBufferBind(void* wrapper); void rendererDrawIndexedPrimitive(unsigned int primCount, unsigned int type, int baseVertex, unsigned int minIndex, unsigned int numVertices, @@ -58,15 +79,24 @@ void rendererDrawIndexedPrimitive(unsigned int primCount, unsigned int type, in namespace geom { extern LightManager* g_LightManager; // ModuleGeom.cpp +// StaticMeshMaterial.cpp's fixed D3DCOLOR encoder, PE 0x10049E80. +unsigned int packVertexNormalColor(const float* normal); namespace { +// The count word the culler's node array carries ahead of its first node (4 bytes in retail). +// [CHOSEN, not recovered] x64 (https://github.com/B2BF/OpenBF2/issues/7): padded to pointer size so +// the nodes, which hold pointers, stay pointer-aligned. +const unsigned int kNodeCountHeader = + sizeof(void*) > sizeof(unsigned int) ? static_cast(sizeof(void*)) + : static_cast(sizeof(unsigned int)); + inline dx9rend::ShaderParameter* param(void* handle) { return static_cast(handle); } -// The eight-corner plane test both walks run: how many corners of the box lie in front of `plane` +// The mode-3 child walk's plane test: how many corners of the box lie in front of `plane` // (normal xyz, d), corners in the shipped order. inline int cornersInFront(const TerrainAabb& b, const float* p) { @@ -110,30 +140,28 @@ inline bool lod1(const TerrainCullerNode* n) { return n->visible && n->lod == 1; inline bool lod0n(const TerrainCullerNode* n) { return n && n->visible && n->lod == 0; } inline bool lod1n(const TerrainCullerNode* n) { return n && n->visible && n->lod == 1; } -// sub_10074AB0 - the image's printf-into-a-std::string helper: vsnprintf into a 0xFFF-byte -// buffer, or the "WARNING: ..." text when it does not fit (StaticMesh.cpp carries the same body). -void formatString(vc71::string& out, const char* format, int a, int b, int c) -{ - char buffer[0x1000]; - const int written = std::snprintf(buffer, 0xFFF, format, a, b, c); - if (written < 0) - std::snprintf(buffer, sizeof(buffer), "%s", - "WARNING: The original message was too long for formatString(). \n"); - else - buffer[written] = 0; - out = buffer; -} +// [CHOSEN, not recovered] Native arithmetic support for the retained x87 walk expressions. +#if defined(__APPLE__) +using CullerWalkReal = bf2x87::Real; +inline bool cullerWalkLess(CullerWalkReal a, CullerWalkReal b) { return bf2x87::less(a, b); } +inline bool cullerWalkGreater(CullerWalkReal a, CullerWalkReal b) { return bf2x87::greater(a, b); } +inline bool cullerWalkLessEqual(CullerWalkReal a, CullerWalkReal b) { return bf2x87::lessEqual(a, b); } +inline CullerWalkReal cullerWalkSqrt(CullerWalkReal value) { return bf2x87::squareRoot(value); } +#else +using CullerWalkReal = double; +inline bool cullerWalkLess(CullerWalkReal a, CullerWalkReal b) { return a < b; } +inline bool cullerWalkGreater(CullerWalkReal a, CullerWalkReal b) { return a > b; } +inline bool cullerWalkLessEqual(CullerWalkReal a, CullerWalkReal b) { return a <= b; } +inline CullerWalkReal cullerWalkSqrt(CullerWalkReal value) { return std::sqrt(value); } +#endif -inline unsigned int layerCount(const vc71::vector_layout& v) -{ - return vc71::vectorSizeIn(v, 4u); -} } // anonymous namespace // QuadPatchDetailLayer +// PE 0x101BB710 QuadPatchDetailLayer::QuadPatchDetailLayer(Terrain* owner) { indexBuffer = 0; @@ -153,6 +181,7 @@ QuadPatchDetailLayer::QuadPatchDetailLayer(Terrain* owner) // returns the layer's detail texture index. The low-quality-B arm parses the fields // and seeks past the tables and indices without keeping any of them. +// PE 0x101BB7C0. int QuadPatchDetailLayer::load(TerrainRawReader& reader) { Terrain* const t = terrain; @@ -184,18 +213,18 @@ int QuadPatchDetailLayer::load(TerrainRawReader& reader) if (t->m_rawHasVersion && t->m_rawVersion >= 0x18u) { - // N records of 400 bytes; record i links to children 1+4i..4+4i while they exist, and - // reads its three 64-byte rows as (row, row+192) u32 pairs. + // N TerrainLodRecords (400 bytes each in retail); record i links to children 1+4i..4+4i + // while they exist, and reads its three 64-byte rows as (row, row+192) u32 pairs. int tableCount = 0; reader.readU32(&tableCount); - lodTables = static_cast(::renddx9abi::engineAlloc(static_cast(400 * tableCount))); + lodTables = static_cast(::renddx9abi::engineAlloc(static_cast(kTerrainLodRecordSize * tableCount))); int offset = 0; - int childOffset = 400; + int childOffset = kTerrainLodRecordSize; int firstChild = 1; for (int record = 0; record < tableCount; ++record) { unsigned char* const table = lodTables + offset; - unsigned char** const children = reinterpret_cast(table + 384); + unsigned char** const children = reinterpret_cast(table)->children; // +384 if (firstChild >= tableCount) { children[3] = 0; children[2] = 0; children[1] = 0; children[0] = 0; @@ -203,9 +232,9 @@ int QuadPatchDetailLayer::load(TerrainRawReader& reader) else { children[0] = lodTables + childOffset; - children[1] = lodTables + childOffset + 400; - children[2] = lodTables + childOffset + 800; - children[3] = lodTables + childOffset + 1200; + children[1] = lodTables + childOffset + kTerrainLodRecordSize; + children[2] = lodTables + childOffset + 2 * kTerrainLodRecordSize; + children[3] = lodTables + childOffset + 3 * kTerrainLodRecordSize; } unsigned char* row = table; for (int r = 0; r < 3; ++r) @@ -214,8 +243,8 @@ int QuadPatchDetailLayer::load(TerrainRawReader& reader) reader.readU32(row + 192); row += 64; } - offset += 400; - childOffset += 1600; + offset += kTerrainLodRecordSize; + childOffset += 4 * kTerrainLodRecordSize; firstChild += 4; } indexBuffer = dx9rend::bufferManagerCreateIndexBuffer(indexCount, 8u, 101u); @@ -230,14 +259,13 @@ int QuadPatchDetailLayer::load(TerrainRawReader& reader) // count, the legacy table builder, then the upload. 1.50 content never comes here. legacyIndices = ::renddx9abi::engineAlloc(2u * indexCount); reader.read(legacyIndices, 2u * indexCount); - void* const storage = ::renddx9abi::engineAlloc(0x190); + void* const storage = ::renddx9abi::engineAlloc(sizeof(TerrainLodRecord)); // 0x190 if (storage) - ::memset(storage, 0, 0x190u); + ::memset(storage, 0, sizeof(TerrainLodRecord)); lodTables = static_cast(storage); - ::memset(lodTables, 0, 0x190u); // a second, unguarded clear, as shipped + ::memset(lodTables, 0, sizeof(TerrainLodRecord)); // a second, unguarded clear, as shipped *reinterpret_cast(lodTables + 192) = indexCount; - RD9_FRONTIER_AT("dice::hfe::geom::QuadPatchDetailLayer::load (sub_101BB490 - the pre-0x18 LOD " - "table builder)", this, 0x00); + buildLodTableTree(lodTables, 0, t->m_patchSize, 0, 0); indexBuffer = dx9rend::bufferManagerCreateIndexBuffer(indexCount, 8u, 101u); void* const bits = dx9rend::indexBufferLock(indexBuffer, 0, 0, 0); if (bits) @@ -247,6 +275,66 @@ int QuadPatchDetailLayer::load(TerrainRawReader& reader) return detailIndex; } +// PE 0x101BB490. The quadrant argument is passed on recursively but never read. +void QuadPatchDetailLayer::buildLodTableTree(unsigned char* tableBytes, int quadrant, + int size, int x, int z) +{ + (void)quadrant; + size >>= 1; + const int stride = terrain->m_patchSize + 1; +#if defined(__APPLE__) + // [CHOSEN, not recovered] Preserve the retained FILD/FMUL value before the native comparison. + if (bf2x87::greater(bf2x87::wide(terrain->m_culler->param10), + bf2x87::mul(bf2x87::wide(size), bf2x87::wide(terrain->m_primaryWorldScale.x)))) +#else + if (static_cast(terrain->m_culler->param10) > + static_cast(size) * terrain->m_primaryWorldScale.x) +#endif + return; + + TerrainLodRecord* const table = reinterpret_cast(tableBytes); + unsigned short* next = static_cast(legacyIndices) + table->starts[0][0]; + unsigned int precedingCount = 0; + for (int childIndex = 0; childIndex < 4; ++childIndex) + { + void* const storage = ::renddx9abi::engineAlloc(sizeof(TerrainLodRecord)); + if (storage) + ::memset(storage, 0, sizeof(TerrainLodRecord)); + TerrainLodRecord* const child = static_cast(storage); + // The second clear is unguarded in the shipped body. + ::memset(child, 0, sizeof(TerrainLodRecord)); + table->children[childIndex] = static_cast(storage); + const int childX = (childIndex % 2) * size + x; + const int childZ = (childIndex / 2) * size + z; + unsigned int count = 0; + for (unsigned short* triangle = next; + triangle < static_cast(legacyIndices) + + table->starts[0][0] + table->counts[0][0]; + triangle += 3) + { + const int x0 = triangle[0] % stride, z0 = triangle[0] / stride; + if (x0 < childX || x0 > childX + size || z0 < childZ || z0 > childZ + size) + continue; + const int x1 = triangle[1] % stride, z1 = triangle[1] / stride; + if (x1 < childX || x1 > childX + size || z1 < childZ || z1 > childZ + size) + continue; + const int x2 = triangle[2] % stride, z2 = triangle[2] / stride; + if (x2 < childX || x2 > childX + size || z2 < childZ || z2 > childZ + size) + continue; + + const unsigned short a = triangle[0], b = triangle[1], c = triangle[2]; + triangle[0] = next[0]; triangle[1] = next[1]; triangle[2] = next[2]; + next[0] = a; next[1] = b; next[2] = c; + next += 3; + count += 3; + } + child->starts[0][0] = table->starts[0][0] + precedingCount; + precedingCount += count; + child->counts[0][0] = count; + buildLodTableTree(table->children[childIndex], childIndex, size, childX, childZ); + } +} + // 0x101BB750, read in full. The layer's index buffer loses the layer's // reference and then its BufferManager tracking-set entry - sub_10011A50 on dword_1023B978, which // releases the set's own reference - so, unlike the Terrain's shared buffers, it is gone when this @@ -268,14 +356,14 @@ QuadPatchDetailLayer::~QuadPatchDetailLayer() freeLodTableTree(lodTables); } -// sub_101BB6B0 - the pre-0x18 layer records are separate 400-byte blocks (built by sub_101BB490, a -// [FRONTIER] of load()) linked through +0x180..+0x18C: the four children's subtrees when the first +// sub_101BB6B0 - the pre-0x18 layer records are separate blocks built by buildLodTableTree, +// linked through +0x180..+0x18C: the four children's subtrees when the first // link is set (only it is tested; each recursion tests its own argument), then the record. void QuadPatchDetailLayer::freeLodTableTree(unsigned char* table) { if (!table) return; - unsigned char* const* const children = reinterpret_cast(table + 0x180); + unsigned char* const* const children = reinterpret_cast(table)->children; // +0x180 if (children[0]) { freeLodTableTree(children[0]); @@ -289,15 +377,15 @@ void QuadPatchDetailLayer::freeLodTableTree(unsigned char* table) // QuadPatch +// PE 0x1018A0E0 QuadPatch::QuadPatch(Terrain* owner) { terrain = owner; - detailLayers.first = 0; detailLayers.last = 0; detailLayers.end = 0; center.x = 0.0f; center.y = 0.0f; center.z = 0.0f; vertexBuffer24 = 0; unresolved28 = 0; legacyVertexTable = 0; - lastDrawnFrame = 0; unresolved3C = 0; + lastDrawnFrame = 0; lastPreloadedFrame = 0; lowDetailmap = 0; colormap = 0; lightmap = 0; @@ -319,40 +407,13 @@ QuadPatch::QuadPatch(Terrain* owner) detailMap[0] = 0; detailMap[1] = 0; } -namespace { - -// dword_1026743C - the RaQuadPatchAdapter server (0x3CC bytes, Geom\RaQuadPatchAdapter.cpp). Its -// only creators (sub_101BBE20 / sub_101BBEB0, and the uncalled sub_101BBDD0) are reached from -// QuadPatch::drawWater's Ra submit, which stops before building it (see drawWater below) - so on the -// rebuilt client nothing ever sets this, and it is kept only so the teardown below has the -// shipped shape (the server is on RW-150's open list with the rest of the Ra water submit). -void* g_raQuadPatchAdapterServer = 0; - -// sub_101BBD70, called by every QuadPatch destructor (0x1018A36D): destroy the server if there is -// one - the first patch destroyed finds it, the others find null - and clear the global either way. -// The non-null arm is read, not written: the server object is not modelled (its embedded adapter's -// lighting block at +0x278 goes through sub_10044120 (raLightingParametersDestroy), its object -// block at +0x3C through sub_1004D900, the pool through sub_101BC8B0, then the +0x04 block and the -// server are freed). -void raQuadPatchAdapterServerDestroy() -{ - if (g_raQuadPatchAdapterServer) - { - RD9_FRONTIER_AT("dice::hfe::geom::RaQuadPatchAdapter server teardown (sub_101BBD70's non-null " - "arm: sub_10044120 on +0x278, sub_1004D900 on +0x3C, sub_101BC8B0, the frees) - " - "the server is never built on this client", g_raQuadPatchAdapterServer, 0x00); - } - g_raQuadPatchAdapterServer = 0; -} - -} // anonymous namespace - // Releases detail layers, textures, vertex buffers, adapter state, then the layer vector. // The legacy vertex table was freed during load and must not be freed again. +// PE 0x1018A220 QuadPatch::~QuadPatch() { - for (QuadPatchDetailLayer** it = reinterpret_cast(detailLayers.first); - it != reinterpret_cast(detailLayers.last); ++it) + for (std::vector::iterator it = detailLayers.begin(); + it != detailLayers.end(); ++it) { QuadPatchDetailLayer* const layer = *it; if (layer) @@ -374,16 +435,12 @@ QuadPatch::~QuadPatch() if (vertexBuffer) dx9rend::vertexBufferRelease(vertexBuffer); // +0x60 raQuadPatchAdapterServerDestroy(); - - if (detailLayers.first) // ~vector: _Tidy - ::renddx9abi::engineFree(detailLayers.first); - detailLayers.first = 0; - detailLayers.last = 0; - detailLayers.end = 0; + // detailLayers' own destructor frees the vector after this body. } // the patch's file record: six header fields, the placement, the vertex buffer, the // detail layers, the per-patch textures. +// PE 0x1018A5B0. void QuadPatch::load(TerrainRawReader& reader) { reader.readU32(&gridX); @@ -452,7 +509,7 @@ void QuadPatch::load(TerrainRawReader& reader) } else { - // The pre-0x18 arm: the packed xz table pairs with the terrain's legacy base grid, two + // The pre-0x18 arm: the height samples pair with the terrain's legacy base grid, two // discarded vec4s, then per-vertex 16-byte records and a normal table packed by // sub_10049E80. 1.50 content never comes here. vertexBuffer = dx9rend::bufferManagerCreateVertexBuffer( @@ -502,8 +559,14 @@ void QuadPatch::load(TerrainRawReader& reader) reader.read(normals, static_cast(12 * side * side)); if (bits) { - RD9_FRONTIER("dice::hfe::geom::QuadPatch::load (sub_10049E80 - the pre-0x18 normal packer " - "into vertex +20)", 0x00); + unsigned int* out = reinterpret_cast(bits + 20); + const float* normal = normals; + for (int i = 0; i < (t->m_patchSize + 1) * (t->m_patchSize + 1); ++i) + { + *out = packVertexNormalColor(normal); + normal += 3; + out += 6; + } } ::renddx9abi::engineFree(normals); } @@ -515,25 +578,25 @@ void QuadPatch::load(TerrainRawReader& reader) const int half = t->m_patchCount / 2; const int nameX = half + gridX; const int nameZ = half + gridZ; - vc71::string name; - formatString(name, "%02ix%02i", nameX, nameZ, 0); + std::string name; + name = formatString("%02ix%02i", nameX, nameZ); patchIndex = nameX + nameZ * t->m_patchCount; if (!hasNoDetailLayers) { const int savedClass = dx9rend::textureManagerSwapDefaultMipClass(2); { - vc71::string colormapName(t->m_colormapBaseName.c_str()); + std::string colormapName(t->m_colormapBaseName.c_str()); colormapName += name; colormap = dx9rend::textureManagerGetTexture(colormapName); } if (!t->m_lowQuality) loadDetailMaps(); dx9rend::textureManagerSwapDefaultMipClass(4); // the answer is discarded - vc71::string lowName(t->m_lowDetailmapBaseName.c_str()); + std::string lowName(t->m_lowDetailmapBaseName.c_str()); lowName += name; { - vc71::string dds(lowName.c_str()); + std::string dds(lowName.c_str()); dds += ".dds"; if (::dice::hfe::fileManager->fileExists(::renddx9abi::makeHostString(dds))) lowDetailmap = dx9rend::textureManagerGetTexture(lowName); @@ -542,13 +605,46 @@ void QuadPatch::load(TerrainRawReader& reader) } const int savedClass7 = dx9rend::textureManagerSwapDefaultMipClass(7); { - vc71::string lightmapName(t->m_lightmapBaseName.c_str()); + std::string lightmapName(t->m_lightmapBaseName.c_str()); lightmapName += name; lightmap = dx9rend::textureManagerGetTexture(lightmapName); } dx9rend::textureManagerSwapDefaultMipClass(savedClass7); } +// PE 0x1018A4F0. +void QuadPatch::reloadDetailLayers(TerrainRawReader& reader) +{ + if (!terrain->m_lowQuality) + { + reader.seek(0, fileEndOffset); + // Shipped defect: loadDetailLayers appends slots and replaces old pointers without + // destroying the previous layers. Preserve the same reload operation. + loadDetailLayers(reader); + loadDetailMaps(); + return; + } + + for (std::vector::iterator it = detailLayers.begin(); + it != detailLayers.end(); ++it) + { + QuadPatchDetailLayer* const layer = *it; + if (layer) + { + layer->~QuadPatchDetailLayer(); + ::renddx9abi::engineFree(layer); + } + } + detailLayers.clear(); + for (int i = 0; i < 2; ++i) + { + terrainReleaseTexture(detailMap[i]); + dx9rend::textureManagerEvictFromCache(detailMap[i]); + detailMap[i] = 0; + } +} + +// PE 0x1018A3A0 // the detail layers: detailTextureCount + 1 null slots, then layer records until a // -1 marker. The record's own detail index says which slot it fills; the low-quality arm parses // each record on the stack and keeps nothing. @@ -558,7 +654,7 @@ void QuadPatch::loadDetailLayers(TerrainRawReader& reader) for (int i = 0; i < t->m_detailTextureCount + 1; ++i) { QuadPatchDetailLayer* const null = 0; - vc71::vectorPushBackIn(detailLayers, 4u, &null); + detailLayers.push_back(null); } maxDetailLayerIndex = -1; int marker = 0; @@ -573,10 +669,10 @@ void QuadPatch::loadDetailLayers(TerrainRawReader& reader) } else { - void* const storage = ::renddx9abi::engineAlloc(0x3C); + void* const storage = ::renddx9abi::engineAlloc(sizeof(QuadPatchDetailLayer)); QuadPatchDetailLayer* const layer = storage ? new (storage) QuadPatchDetailLayer(t) : 0; detailIndex = layer->load(reader); // unguarded, as shipped - reinterpret_cast(detailLayers.first)[detailIndex] = layer; + detailLayers.data()[detailIndex] = layer; // unchecked index, as shipped } if (detailIndex < t->m_detailTextureCount) { @@ -590,6 +686,7 @@ void QuadPatch::loadDetailLayers(TerrainRawReader& reader) hasNoDetailLayers = 1; } +// PE 0x10188CA0 // the two packed detail maps "%02ix%02i_1" / "_2", under mip class 6, // each only when a layer index reaches its three-channel block. void QuadPatch::loadDetailMaps() @@ -600,11 +697,11 @@ void QuadPatch::loadDetailMaps() { Terrain* const t = terrain; const int half = t->m_patchCount / 2; - vc71::string name; - formatString(name, "%02ix%02i_%i", half + gridX, half + gridZ, k + 1); + std::string name; + name = formatString("%02ix%02i_%i", half + gridX, half + gridZ, k + 1); if (!detailMap[k] && threshold <= maxDetailLayerIndex) { - vc71::string full(t->m_detailmapBaseName.c_str()); + std::string full(t->m_detailmapBaseName.c_str()); full += name; detailMap[k] = dx9rend::textureManagerGetTexture(full); } @@ -630,38 +727,47 @@ inline ::dice::hfe::world::IHeightmapCluster* heightmapCluster() return static_cast< ::dice::hfe::world::IHeightmapCluster*>(static_cast(found)); } -// PE 0x100777A0 (135 B), read in full - the engine's in-place normalise: |v|^2 = (x*x + y*y) + z*z -// kept as a float; within FLT_EPSILON (flt_10208958) of 1 the vector is left alone; below -// FLT_EPSILON it is zeroed and -20001 (0xFFFFB1DF) answered; otherwise each component is scaled by -// 1 / sqrt(|v|^2) (flt_101DDDE4 = 1.0f). An unordered |v|^2 fails both tests and takes the scale. -// Every caller here drops the answer. (The same body is transcribed beside its other users: -// Overgrowth/OverGrowthCellRender.cpp, StaticMeshMaterial.cpp, the particle and nametag TUs.) -int normalizeInPlace(Vec3& v) +} // anonymous namespace + +// PE 0x10188590 (also 0x10014920, 0x10014610). The texture and vertex-buffer helpers at 0x10014920 / 0x10014610 are the +// same guarded PreLoad call (vtable slot +0x24 of the held D3D object), inlined below. +void QuadPatch::preloadResources() { - const float lengthSquared = v.x * v.x + v.y * v.y + v.z * v.z; - if (std::fabs(lengthSquared - 1.0f) < FLT_EPSILON) - return 0; - if (std::fabs(lengthSquared) < FLT_EPSILON) + if (lowDetailmap) { - v.x = 0.0f; - v.y = 0.0f; - v.z = 0.0f; - return -20001; + IDirect3DBaseTexture9* const texture = + static_cast(lowDetailmap)->baseTexture; + if (texture) + texture->PreLoad(); } - const float inverse = 1.0f / std::sqrt(lengthSquared); - v.x = inverse * v.x; - v.y = inverse * v.y; - v.z = inverse * v.z; - return 0; + if (colormap) + { + IDirect3DBaseTexture9* const texture = + static_cast(colormap)->baseTexture; + if (texture) + texture->PreLoad(); + } + if (lightmap) + { + IDirect3DBaseTexture9* const texture = + static_cast(lightmap)->baseTexture; + if (texture) + texture->PreLoad(); + } + if (vertexBuffer) + { + IDirect3DVertexBuffer9* const buffer = dx9rend::vertexBufferD3D(vertexBuffer); + if (buffer) + buffer->PreLoad(); + } + lastPreloadedFrame = dx9rend::rendererFrameOrdinal(); } -} // anonymous namespace - // 0x10188660, 29 B (`retn 4`) - Frustum::inside(centre, radius) (0x10079A60) on the patch's bounding // sphere: `push [ecx+0ACh]; add ecx, 0A0h; push ecx; mov ecx, [ebp+8]`. The answer is the byte in al. bool QuadPatch::isVisible(const Frustum* frustum) { - return frustum->inside(sphereCentre, sphereRadius); + return rendmath::frustumInside(*frustum, sphereCentre, sphereRadius); } // 0x10188BE0, 47 B (`retn 4`) - the squared distance from `position` to the patch centre (+0x18): @@ -676,6 +782,26 @@ float QuadPatch::getSquaredDistance(const Vec3& position) return dx * dx + dz * dz + dy * dy; } +// PE 0x10188C10: the distance from the render view's camera position (view matrix translation +// m[12..14]) to the patch centre, recomputed once per frame ordinal and cached at +0x30/+0x34; the +// squares are added z, x, y. [INFERRED] name and owner (the QuadPatch layout and its twin +// SurroundingPatch::getCameraDistance); unreachable in 1.50: no code or data references. The +// constructor leaves both cache words untouched, as shipped. +float QuadPatch::getCameraDistance() +{ + if (cachedDistanceFrame != dx9rend::rendererFrameOrdinal()) // base +0x54 + { + dx9rend::IRenderView* const view = dx9rend::rendererGetRenderView(); // base +0x48 + const float* const m = view->getViewMatrixPtr()->m; // view +0x64 + const float dx = center.x - m[12]; + const float dy = center.y - m[13]; + const float dz = center.z - m[14]; + cachedCameraDistance = std::sqrt(dz * dz + dx * dx + dy * dy); + cachedDistanceFrame = dx9rend::rendererFrameOrdinal(); + } + return cachedCameraDistance; +} + // Builds per-vertex normals from the primary heightmap into the normal buffer. // Preserves repeated heightmap queries and the double-weighted centre sample. @@ -737,12 +863,12 @@ void QuadPatch::buildNormalVertexBuffer() alongZ.x = fx - fx; alongZ.y = h2 - h0Again; alongZ.z = fz1 - fz; - normalizeInPlace(alongX); - normalizeInPlace(alongZ); + rendmath::normalize(alongX); + rendmath::normalize(alongZ); sample->x = alongZ.y * alongX.z - alongZ.z * alongX.y; sample->y = alongZ.z * alongX.x - alongX.z * alongZ.x; sample->z = alongX.y * alongZ.x - alongZ.y * alongX.x; - normalizeInPlace(*sample); + rendmath::normalize(*sample); ++sample; } } @@ -771,19 +897,19 @@ void QuadPatch::buildNormalVertexBuffer() average.x = average.x * 0.25f; average.y = average.y * 0.25f; average.z = average.z * 0.25f; - normalizeInPlace(average); + rendmath::normalize(average); unsigned short half = 0; float value = average.x; - D3DXFloat32To16Array(&half, &value, 1); + D3DXFloat32To16Array(reinterpret_cast(&half), &value, 1); *out++ = half; value = average.y; - D3DXFloat32To16Array(&half, &value, 1); + D3DXFloat32To16Array(reinterpret_cast(&half), &value, 1); *out++ = half; value = average.z; - D3DXFloat32To16Array(&half, &value, 1); + D3DXFloat32To16Array(reinterpret_cast(&half), &value, 1); *out++ = half; value = 0.0f; - D3DXFloat32To16Array(&half, &value, 1); + D3DXFloat32To16Array(reinterpret_cast(&half), &value, 1); *out++ = half; } } @@ -811,7 +937,7 @@ void QuadPatch::buildNormalVertexBuffer() average.x = average.x * 0.25f; average.y = average.y * 0.25f; average.z = average.z * 0.25f; - normalizeInPlace(average); + rendmath::normalize(average); out[0] = average.x; out[1] = average.y; out[2] = average.z; @@ -827,11 +953,11 @@ void QuadPatch::buildNormalVertexBuffer() // TerrainCullerNode / TerrainCuller +// PE 0x100E3C00 TerrainCullerNode::TerrainCullerNode() { patch = 0; lodTable = 0; - layerLodTables.first = 0; layerLodTables.last = 0; layerLodTables.end = 0; occlusionQuery = 0; bounds.min.x = 0.0f; bounds.min.y = 0.0f; bounds.min.z = 0.0f; bounds.max.x = 0.0f; bounds.max.y = 0.0f; bounds.max.z = 0.0f; @@ -847,12 +973,13 @@ TerrainCullerNode::TerrainCullerNode() visible = 0; cameraInside = 0; crackMask = 0; - unresolved10C = 0; + legacyParent = 0; lod = 2; - unresolved104 = -1; + legacyGridIndex = -1; child[0] = 0; child[1] = 0; child[2] = 0; child[3] = 0; } +// PE 0x100E3AE0 TerrainCuller::TerrainCuller() { terrain = 0; @@ -869,8 +996,6 @@ TerrainCuller::TerrainCuller() lodFactor28 = 2.0f; lodFactor2C = 2.7f; lodFactor30 = 3.0f; - visible.first = 0; visible.last = 0; visible.end = 0; - gathered.first = 0; gathered.last = 0; gathered.end = 0; frustum = 0; cameraPosition = 0; gatherCentre = 0; @@ -883,6 +1008,7 @@ TerrainCuller::TerrainCuller() versionFlag78 = 0; } +// PE 0x100E2D60 void TerrainCuller::init(Terrain* owner, int a, int b) { terrain = owner; @@ -896,15 +1022,12 @@ TerrainCullerNode::~TerrainCullerNode() { if (occlusionQuery) dx9rend::queryReleaseRef(occlusionQuery); // --ref; sub_10003FA0 + free at zero - if (layerLodTables.first) // ~vector: _Tidy - ::renddx9abi::engineFree(layerLodTables.first); - layerLodTables.first = 0; - layerLodTables.last = 0; - layerLodTables.end = 0; + // layerLodTables' own destructor frees the vector after this body. } // Destroys array nodes for modern terrain files or recursively frees legacy nodes. // Requires terrain ownership and completed node initialization; then frees gather/visible lists. +// PE 0x100E6800 TerrainCuller::~TerrainCuller() { Terrain* const t = terrain; @@ -912,10 +1035,12 @@ TerrainCuller::~TerrainCuller() { if (nodes) { - unsigned int* const block = reinterpret_cast(nodes) - 1; - const int count = static_cast(*block); - for (int i = count - 1; i >= 0; --i) // `sub ecx,1 / js` - signed - nodes[i].~TerrainCullerNode(); + TerrainCullerNode* const array = nodes; + unsigned char* const block = reinterpret_cast(array) - kNodeCountHeader; + const int count = static_cast(*reinterpret_cast(block)); + for (int i = static_cast(static_cast(count) - 1u); + i >= 0; --i) // `sub ecx,1 / js` - signed + array[i].~TerrainCullerNode(); ::renddx9abi::engineFree(block); } } @@ -932,17 +1057,7 @@ TerrainCuller::~TerrainCuller() root->~TerrainCullerNode(); ::renddx9abi::engineFree(root); } - - if (gathered.first) // ~vector (+0x44): _Tidy - ::renddx9abi::engineFree(gathered.first); - gathered.first = 0; - gathered.last = 0; - gathered.end = 0; - if (visible.first) // ~vector (+0x34): _Tidy - ::renddx9abi::engineFree(visible.first); - visible.first = 0; - visible.last = 0; - visible.end = 0; + // gathered (+0x44) and visible (+0x34) are destroyed after this body, in that order. } // sub_100E3D10 - the pre-0x18 tree, one node at a time: the four subtrees when the first child is @@ -962,6 +1077,7 @@ void TerrainCuller::deleteNodeTree(TerrainCullerNode* node) // one node's file record: eight u16 neighbour indices, the bounds, three bytes and // the patch index. Written in the shipped read order. +// PE 0x100E2FF0 void TerrainCuller::loadNode(TerrainRawReader& reader, TerrainCullerNode* node) { float minMax[6] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; @@ -973,7 +1089,7 @@ void TerrainCuller::loadNode(TerrainRawReader& reader, TerrainCullerNode* node) reader.readByte(&node->fileByteEC); reader.readByte(&node->hasPatchList); reader.readByte(&node->fileByteEE); - unsigned char patchIndex = 0; + unsigned char patchIndex; reader.readByte(&patchIndex); node->allNeighbours = 1; @@ -1000,6 +1116,7 @@ void TerrainCuller::loadNode(TerrainRawReader& reader, TerrainCullerNode* node) // the node array (a count word ahead of it), then per node: the four children by // position, the record, and the LOD tables - the terrain's own for a leaf (plus each detail // layer's table), the parent's child tables for an inner node that asks for them. +// PE 0x100E3FF0 void TerrainCuller::load(TerrainRawReader& reader) { Terrain* const t = terrain; @@ -1007,25 +1124,27 @@ void TerrainCuller::load(TerrainRawReader& reader) versionFlag78 = 1; reader.readU32(&nodeCount); const int count = nodeCount; - unsigned int* const storage = static_cast( - ::renddx9abi::engineAlloc(static_cast(272 * count + 4))); + unsigned char* const storage = static_cast(::renddx9abi::engineAlloc( + static_cast(sizeof(TerrainCullerNode) * count + kNodeCountHeader))); TerrainCullerNode* first = 0; if (storage) { - *storage = static_cast(count); - first = reinterpret_cast(storage + 1); - for (int i = 0; i < count; ++i) - new (first + i) TerrainCullerNode(); + *reinterpret_cast(storage) = static_cast(count); + first = reinterpret_cast(storage + kNodeCountHeader); + if (static_cast(static_cast(count) - 1u) >= 0) + { + TerrainCullerNode* next = first; + for (unsigned int remaining = static_cast(count); remaining; --remaining) + new (next++) TerrainCullerNode(); + } } nodes = first; - if (count <= 0) - return; - for (int k = 0; k < count; ++k) + for (int k = 0; k < nodeCount; ++k) { TerrainCullerNode* const node = nodes + k; - const int firstChild = 1 + 4 * k; - if (firstChild >= count) + const int firstChild = static_cast(1u + 4u * static_cast(k)); + if (firstChild >= nodeCount) { node->child[3] = 0; node->child[2] = 0; node->child[1] = 0; node->child[0] = 0; } @@ -1041,15 +1160,18 @@ void TerrainCuller::load(TerrainRawReader& reader) node->lod = 0; if (node->hasPatchList) { - node->lodTable = t->m_lodTables; - QuadPatch* const patch = node->patch; // unguarded, as shipped - const unsigned int layers = layerCount(patch->detailLayers); - for (unsigned int i = 0; i < layers; ++i) + node->lodTable = terrain->m_lodTables; + for (unsigned int i = 0; + i < static_cast(node->patch->detailLayers.size()); ++i) { - QuadPatchDetailLayer* const layer = - reinterpret_cast(patch->detailLayers.first)[i]; - unsigned char* const table = layer ? layer->lodTables : 0; - vc71::vectorPushBackIn(node->layerLodTables, 4u, &table); + QuadPatchDetailLayer* const layer = node->patch->detailLayers[i]; + if (layer) + node->layerLodTables.push_back(layer->lodTables); + else + { + unsigned char* const table = 0; + node->layerLodTables.push_back(table); + } } } else if (!node->fileByteEC) @@ -1060,21 +1182,58 @@ void TerrainCuller::load(TerrainRawReader& reader) { TerrainCullerNode* const parent = nodes + (k - 1) / 4; const int which = (k - 1) % 4; - node->lodTable = *reinterpret_cast(parent->lodTable + 384 + 4 * which); - const unsigned int layers = layerCount(node->patch->detailLayers); // unguarded, as shipped - for (unsigned int i = 0; i < layers; ++i) + node->lodTable = reinterpret_cast(parent->lodTable)->children[which]; // +384 + 4 * which + for (unsigned int i = 0; + i < static_cast(node->patch->detailLayers.size()); ++i) { - unsigned char* const parentTable = - reinterpret_cast(parent->layerLodTables.first)[i]; - unsigned char* const table = - parentTable ? *reinterpret_cast(parentTable + 384 + 4 * which) : 0; - vc71::vectorPushBackIn(node->layerLodTables, 4u, &table); + unsigned char* const parentTable = parent->layerLodTables.data()[i]; // unchecked, as shipped + if (parentTable) + node->layerLodTables.push_back( + reinterpret_cast(parentTable)->children[which]); + else + { + unsigned char* const table = 0; + node->layerLodTables.push_back(table); + } } } } } +// PE 0x100E3D60. [INFERRED] Placement with the existing TerrainCuller implementation. +void TerrainCuller::reloadDetailLayers() +{ + for (int index = 0; index < nodeCount; ++index) + { + TerrainCullerNode& node = nodes[index]; + node.layerLodTables.clear(); + if (node.hasPatchList) + { + for (unsigned int layerIndex = 0; + layerIndex < static_cast(node.patch->detailLayers.size()); + ++layerIndex) + { + QuadPatchDetailLayer* const layer = node.patch->detailLayers[layerIndex]; + node.layerLodTables.push_back(layer ? layer->lodTables : 0); + } + } + else if (node.fileByteEC) + { + TerrainCullerNode& parent = nodes[(index - 1) / 4]; + const int childIndex = (index - 1) % 4; + for (unsigned int layerIndex = 0; + layerIndex < static_cast(node.patch->detailLayers.size()); + ++layerIndex) + { + unsigned char* const table = parent.layerLodTables[layerIndex]; + node.layerLodTables.push_back(table + ? reinterpret_cast(table)->children[childIndex] : 0); + } + } + } +} + // TerrainAabb - sub_100E7180 / sub_101C5EB0. const float* TerrainAabb::corner(float out[3], int index) const @@ -1143,8 +1302,7 @@ void TerrainAabb::refresh() // the zoom (floored at param14), the root walk, the crack fixup. void TerrainCuller::update() { - if (visible.first) // sub_100E7520(0, 0) - visible.last = visible.first; + visible.clear(); // sub_100E7520(0, 0) dx9rend::IRenderView* const view = dx9rend::rendererGetRenderView(); // base +0x48 frustum = view->getFrustumPtr(); // +0x74 cameraPosition = view->getViewMatrixPtr()->m + 12; // +0x64, row 3 @@ -1165,7 +1323,8 @@ void TerrainCuller::update() // the root: the bounding sphere against the frustum, the camera's xz against the box // (flag71), else the eight corners against every plane; then the mode dispatch. -void TerrainCuller::walkRoot(TerrainCullerNode* node) +// PE 0x100E6D50. Every return explicitly materializes EAX = 1, including rejection paths. +int TerrainCuller::walkRoot(TerrainCullerNode* node) { const unsigned char cameraTest = flag71; TerrainAabb& box = node->bounds; @@ -1174,14 +1333,17 @@ void TerrainCuller::walkRoot(TerrainCullerNode* node) const float radius = box.radius; if (box.dirty) box.refresh(); - node->visible = frustum->inside(box.centre, radius) ? 1 : 0; + node->visible = rendmath::frustumInside(*frustum, box.centre, radius) ? 1 : 0; if (!node->visible) - return; + return 1; bool dispatch = false; if (cameraTest) { const float* const cam = cameraPosition; - if (cam[0] >= box.min.x && cam[0] <= box.max.x && cam[2] >= box.min.z && cam[2] <= box.max.z) + if (cullerWalkLessEqual(CullerWalkReal(box.min.x), CullerWalkReal(cam[0])) && + cullerWalkLessEqual(CullerWalkReal(cam[0]), CullerWalkReal(box.max.x)) && + cullerWalkLessEqual(CullerWalkReal(box.min.z), CullerWalkReal(cam[2])) && + cullerWalkLessEqual(CullerWalkReal(cam[2]), CullerWalkReal(box.max.z))) { node->visible = 1; node->cameraInside = 1; @@ -1191,15 +1353,24 @@ void TerrainCuller::walkRoot(TerrainCullerNode* node) if (!dispatch) { node->cameraInside = 0; - const float* plane = reinterpret_cast(frustum); int inside = 0; - for (int i = 0; i < 6; ++i, plane += 4) + for (int i = 0; i < 6; ++i) { - const int n = cornersInFront(box, plane); + const Plane3& plane = frustum->m_planes[i]; + int n = 0; + for (int corner = 0; corner < 8; ++corner) + { + const CullerWalkReal x = (corner & 4) ? box.max.x : box.min.x; + const CullerWalkReal y = (corner & 2) ? box.max.y : box.min.y; + const CullerWalkReal z = (corner & 1) ? box.max.z : box.min.z; + const CullerWalkReal nx = plane.normal.x, ny = plane.normal.y, nz = plane.normal.z; + const CullerWalkReal dot = (y * ny + x * nx) + z * nz + CullerWalkReal(plane.d); + n += cullerWalkGreater(dot, CullerWalkReal(0)); + } if (n == 8) { node->visible = 0; - return; + return 1; } if (n) { @@ -1213,22 +1384,33 @@ void TerrainCuller::walkRoot(TerrainCullerNode* node) { node->visible = (inside == 6) ? 1 : 0; if (inside != 6) - return; + return 1; } } switch (param6C) { + case 1: + walkMode1(node); + break; + case 2: + walkMode2(node); + break; case 3: walkMode3(node); break; - case 1: case 2: case 4: case 5: case 6: - RD9_FRONTIER("dice::hfe::geom::TerrainCuller::walkRoot (modes 1/2/4/5/6 - sub_100E4F10 / " - "sub_100E53A0 / sub_100E5DD0 / sub_100E6270 / sub_100E6640, unread; the shipped " - "mode is 3)", 0x28); + case 4: + walkMode4(node); + break; + case 5: + walkMode5(node); + break; + case 6: + walkMode6(node); break; default: break; } + return 1; } // mode 3, per child: the sphere, the camera's xz when the parent held it, else the @@ -1247,7 +1429,7 @@ void TerrainCuller::walkMode3(TerrainCullerNode* parent) const float radius = box.radius; if (box.dirty) box.refresh(); - const bool inSphere = frustum->inside(box.centre, radius); + const bool inSphere = rendmath::frustumInside(*frustum, box.centre, radius); child->visible = inSphere ? 1 : 0; if (!inSphere) continue; @@ -1329,139 +1511,658 @@ void TerrainCuller::walkMode3(TerrainCullerNode* parent) child->lod = 0; } if (child->fileByteEE) - vc71::vectorPushBackIn(visible, 4u, &child); + visible.push_back(child); else walkMode3(child); ++parent->childrenWalked; } } -// the node's visible children first, then the node; 3 and above clamp to 2. -void TerrainCuller::setLod(TerrainCullerNode* node, int lod) +// PE 0x100E4F10. [INFERRED] Placement with the existing TerrainCuller bodies. +void TerrainCuller::walkMode1(TerrainCullerNode* parent) { - if (node->child[0]) + parent->childrenWalked = 0; + TerrainCullerNode* candidates[4]; + float distances[4]; + for (int childIndex = 0; childIndex < 4; ++childIndex) { - for (int c = 0; c < 4; ++c) - if (node->child[c]->visible) - setLod(node->child[c], lod); + TerrainCullerNode* const child = parent->child[childIndex]; + TerrainAabb& bounds = child->bounds; + if (bounds.dirty) + bounds.refresh(); + const float radius = bounds.radius; + if (bounds.dirty) + bounds.refresh(); + child->visible = rendmath::frustumInside(*frustum, bounds.centre, radius) ? 1 : 0; + if (!child->visible) + { + candidates[childIndex] = 0; + continue; + } + child->cameraInside = 0; + int inside = 0; + for (int planeIndex = 0; planeIndex < 6; ++planeIndex) + { + const Plane3& plane = frustum->m_planes[planeIndex]; + int inFront = 0; + for (int corner = 0; corner < 8; ++corner) + { + const CullerWalkReal x = (corner & 4) ? bounds.max.x : bounds.min.x; + const CullerWalkReal y = (corner & 2) ? bounds.max.y : bounds.min.y; + const CullerWalkReal z = (corner & 1) ? bounds.max.z : bounds.min.z; + const CullerWalkReal nx = plane.normal.x, ny = plane.normal.y, nz = plane.normal.z; + CullerWalkReal dot; + if (corner == 0) + dot = (x * nx + y * ny) + z * nz + CullerWalkReal(plane.d); + else if (corner < 4) + dot = (y * ny + z * nz) + x * nx + CullerWalkReal(plane.d); + else + dot = (y * ny + x * nx) + z * nz + CullerWalkReal(plane.d); + inFront += cullerWalkGreater(dot, CullerWalkReal(0)); + } + if (inFront == 8) + { + child->visible = 0; + break; + } + if (inFront) + { + child->visible = 1; + break; + } + ++inside; + } + if (inside == 6) + child->visible = 1; + if (!child->visible) + { + candidates[childIndex] = 0; + continue; + } + candidates[childIndex] = parent->child[childIndex]; + TerrainCullerNode* const lodNode = parent->child[childIndex]; + const TerrainAabb& lodBounds = lodNode->bounds; + const float* const camera = cameraPosition; + CullerWalkReal dx = CullerWalkReal(0), dz = CullerWalkReal(0); + if (cullerWalkLess(CullerWalkReal(camera[0]), CullerWalkReal(lodBounds.min.x))) + dx = CullerWalkReal(camera[0]) - CullerWalkReal(lodBounds.min.x); + else if (cullerWalkGreater(CullerWalkReal(camera[0]), CullerWalkReal(lodBounds.max.x))) + dx = CullerWalkReal(lodBounds.max.x) - CullerWalkReal(camera[0]); + if (cullerWalkLess(CullerWalkReal(camera[2]), CullerWalkReal(lodBounds.min.z))) + dz = CullerWalkReal(camera[2]) - CullerWalkReal(lodBounds.min.z); + else if (cullerWalkGreater(CullerWalkReal(camera[2]), CullerWalkReal(lodBounds.max.z))) + dz = CullerWalkReal(lodBounds.max.z) - CullerWalkReal(camera[2]); + const CullerWalkReal distance = cullerWalkSqrt(dz * dz + dx * dx) + + CullerWalkReal(terrain->m_cameraHeightAboveTerrain); + const CullerWalkReal limit = CullerWalkReal(lodDistance); + if (!cullerWalkLessEqual(distance, limit)) + { + setLod(lodNode, !cullerWalkLessEqual(distance, limit * CullerWalkReal(lodFactor30)) ? 2 : 1); + distances[childIndex] = static_cast(distance); + } + else + { + if (lodNode->child[0]) + for (int grandchild = 0; grandchild < 4; ++grandchild) + if (lodNode->child[grandchild]->visible) + setLod(lodNode->child[grandchild], 0); + distances[childIndex] = static_cast(distance); + lodNode->lod = 0; + } + ++parent->childrenWalked; + } + if (!parent->childrenWalked) + return; + for (;;) + { + int selected = -1; + for (int index = 0; index < 4; ++index) + if (candidates[index]) + { + selected = index; + break; + } + if (selected < 0) + break; + for (int index = selected + 1; index < 4; ++index) + if (candidates[index] && + cullerWalkLess(CullerWalkReal(distances[index]), CullerWalkReal(distances[selected]))) + selected = index; + if (candidates[selected]->fileByteEE) + visible.push_back(candidates[selected]); + else + walkMode1(candidates[selected]); + candidates[selected] = 0; } - node->lod = lod; - if (lod >= 3) - node->lod = 2; } -// the crack mask. Version 0x1A content: per visible node, the neighbours 1 (bit 1), -// 6 (bit 2), 3 (bit 4) and 4 (bit 8) that sit one LOD finer decide the mask; a LOD-2 node with any -// LOD-0 neighbour drops to LOD 1 first. Older content: a LOD-2 node with a null or LOD-0 neighbour -// drops to LOD 1 and the mask stays 0. -void TerrainCuller::fixCracks() +// PE 0x100E53A0. [INFERRED] Placement with the existing TerrainCuller bodies. +void TerrainCuller::walkMode2(TerrainCullerNode* parent) { - TerrainCullerNode** const first = reinterpret_cast(visible.first); - TerrainCullerNode** const last = reinterpret_cast(visible.last); - if (versionFlag78) + for (;;) { - for (TerrainCullerNode** it = first; it != last; ++it) + parent->childrenWalked = 0; + TerrainCullerNode* candidates[4]; + for (int childIndex = 0; childIndex < 4; ++childIndex) { - TerrainCullerNode* const n = *it; - const int lod = n->lod; - n->crackMask = 0; - TerrainCullerNode* const nb1 = n->neighbour[1]; - TerrainCullerNode* const nb3 = n->neighbour[3]; - TerrainCullerNode* const nb4 = n->neighbour[4]; - TerrainCullerNode* const nb6 = n->neighbour[6]; - if (n->allNeighbours) + TerrainCullerNode* const child = parent->child[childIndex]; + TerrainAabb& bounds = child->bounds; + if (bounds.dirty) + bounds.refresh(); + const float radius = bounds.radius; + if (bounds.dirty) + bounds.refresh(); + child->visible = rendmath::frustumInside(*frustum, bounds.centre, radius) ? 1 : 0; + if (!child->visible) { - if (lod == 1) + candidates[childIndex] = 0; + continue; + } + child->cameraInside = 0; + int inside = 0; + for (int planeIndex = 0; planeIndex < 6; ++planeIndex) + { + const Plane3& plane = frustum->m_planes[planeIndex]; + int inFront = 0; + for (int corner = 0; corner < 8; ++corner) { - if (lod0(nb1)) - { - n->crackMask = 1; - if (lod0(nb3)) n->crackMask = 5; - else if (lod0(nb4)) n->crackMask = 9; - } - else if (lod0(nb6)) - { - n->crackMask = 2; - if (lod0(nb3)) n->crackMask = 6; - else if (lod0(nb4)) n->crackMask = 10; - } - else if (lod0(nb3)) n->crackMask = 4; - else if (lod0(nb4)) n->crackMask = 8; + const CullerWalkReal x = (corner & 4) ? bounds.max.x : bounds.min.x; + const CullerWalkReal y = (corner & 2) ? bounds.max.y : bounds.min.y; + const CullerWalkReal z = (corner & 1) ? bounds.max.z : bounds.min.z; + const CullerWalkReal nx = plane.normal.x, ny = plane.normal.y, nz = plane.normal.z; + CullerWalkReal dot; + if (corner < 4) + dot = (y * ny + z * nz) + x * nx + CullerWalkReal(plane.d); + else if (corner < 7) + dot = (y * ny + x * nx) + z * nz + CullerWalkReal(plane.d); + else + dot = (z * nz + x * nx) + y * ny + CullerWalkReal(plane.d); + inFront += cullerWalkGreater(dot, CullerWalkReal(0)); } - else if (lod == 2) + if (inFront == 8) { - bool anyLod0 = false; - for (int i = 0; i < 8; ++i) - if (n->neighbour[i]->lod == 0) { anyLod0 = true; break; } - if (anyLod0) - { - n->lod = 1; - if (lod0(nb1)) - { - n->crackMask = 1; - if (lod0(nb3)) n->crackMask = 1 | 4; - else if (lod0(nb4)) n->crackMask = 1 | 8; - } - else if (lod0(nb6)) - { - n->crackMask = 2; - if (lod0(nb3)) n->crackMask = 2 | 4; - else if (lod0(nb4)) n->crackMask = 2 | 8; - } - else if (lod0(nb3)) n->crackMask = 4; - else if (lod0(nb4)) n->crackMask = 8; - } - if (lod1(nb1)) - { - n->crackMask |= 1; - if (lod1(nb3)) n->crackMask |= 4; - else if (lod1(nb4)) n->crackMask |= 8; - } - else if (lod1(nb6)) - { - n->crackMask |= 2; - if (lod1(nb3)) n->crackMask |= 4; - else if (lod1(nb4)) n->crackMask |= 8; - } - else if (lod1(nb3)) n->crackMask |= 4; - else if (lod1(nb4)) n->crackMask |= 8; + child->visible = 0; + break; + } + if (inFront) + { + child->visible = 1; + break; } + ++inside; + } + if (inside == 6) + child->visible = 1; + if (!child->visible) + { + candidates[childIndex] = 0; + continue; + } + candidates[childIndex] = parent->child[childIndex]; + TerrainCullerNode* const lodNode = parent->child[childIndex]; + const TerrainAabb& lodBounds = lodNode->bounds; + const float* const camera = cameraPosition; + CullerWalkReal dx = CullerWalkReal(0), dz = CullerWalkReal(0); + if (cullerWalkLess(CullerWalkReal(camera[0]), CullerWalkReal(lodBounds.min.x))) + dx = CullerWalkReal(camera[0]) - CullerWalkReal(lodBounds.min.x); + else if (cullerWalkGreater(CullerWalkReal(camera[0]), CullerWalkReal(lodBounds.max.x))) + dx = CullerWalkReal(lodBounds.max.x) - CullerWalkReal(camera[0]); + if (cullerWalkLess(CullerWalkReal(camera[2]), CullerWalkReal(lodBounds.min.z))) + dz = CullerWalkReal(camera[2]) - CullerWalkReal(lodBounds.min.z); + else if (cullerWalkGreater(CullerWalkReal(camera[2]), CullerWalkReal(lodBounds.max.z))) + dz = CullerWalkReal(lodBounds.max.z) - CullerWalkReal(camera[2]); + const CullerWalkReal distance = cullerWalkSqrt(dx * dx + dz * dz) + + CullerWalkReal(terrain->m_cameraHeightAboveTerrain); + const CullerWalkReal limit = CullerWalkReal(lodDistance); + if (!cullerWalkLessEqual(distance, limit)) + { + setLod(lodNode, !cullerWalkLessEqual(distance, limit * CullerWalkReal(lodFactor30)) ? 2 : 1); } else { - if (lod == 1) - { - if (lod0n(nb1)) - { - n->crackMask = 1; - if (lod0n(nb3)) n->crackMask = 5; - else if (nb4 && nb4->visible && nb4->lod == 0) n->crackMask = 9; - } - else if (lod0n(nb6)) - { - n->crackMask = 2; - if (lod0n(nb3)) n->crackMask = 6; - else if (lod0n(nb4)) n->crackMask = 10; - } - else if (lod0n(nb3)) n->crackMask = 4; - else if (lod0n(nb4)) n->crackMask = 8; - } - else if (lod == 2) - { - bool anyLod0 = false; - for (int i = 0; i < 8; ++i) - { - TerrainCullerNode* const nb = n->neighbour[i]; - if (nb && nb->lod == 0) { anyLod0 = true; break; } - } - if (anyLod0) - { - n->lod = 1; - if (lod0n(nb1)) - { - n->crackMask = 1; - if (lod0n(nb3)) n->crackMask = 1 | 4; - else if (lod0n(nb4)) n->crackMask = 1 | 8; + if (lodNode->child[0]) + for (int grandchild = 0; grandchild < 4; ++grandchild) + if (lodNode->child[grandchild]->visible) + setLod(lodNode->child[grandchild], 0); + lodNode->lod = 0; + } + ++parent->childrenWalked; + } + // Shipped defect: three accepted children select all four original child slots. + const bool useAllChildren = parent->childrenWalked > 2; + if (!useAllChildren && !parent->childrenWalked) + return; + for (int index = 0; index < 3; ++index) + { + TerrainCullerNode* const selected = useAllChildren ? parent->child[index] : candidates[index]; + if (!useAllChildren && !selected) + continue; + if (selected->fileByteEE) + visible.push_back(selected); + else + walkMode2(selected); + } + TerrainCullerNode* const last = useAllChildren ? parent->child[3] : candidates[3]; + if (!useAllChildren && !last) + return; + if (last->fileByteEE) + { + visible.push_back(last); + return; + } + parent = last; // The fourth-child descent is a tail loop in the image. + } +} + +// PE 0x100E5DD0. [INFERRED] Placement with the existing TerrainCuller bodies. +int TerrainCuller::walkMode4(TerrainCullerNode* parent) +{ + parent->childrenWalked = 0; + TerrainCullerNode* candidates[4]; + bool childComplete[4]; + bool allComplete = true; + for (int childIndex = 0; childIndex < 4; ++childIndex) + { + TerrainCullerNode* const child = parent->child[childIndex]; + TerrainAabb& bounds = child->bounds; + if (bounds.dirty) + bounds.refresh(); + const float radius = bounds.radius; + if (bounds.dirty) + bounds.refresh(); + child->visible = rendmath::frustumInside(*frustum, bounds.centre, radius) ? 1 : 0; + if (!child->visible) + { + allComplete = false; + candidates[childIndex] = 0; + continue; + } + child->cameraInside = 0; + int inside = 0; + for (int planeIndex = 0; planeIndex < 6; ++planeIndex) + { + const Plane3& plane = frustum->m_planes[planeIndex]; + int inFront = 0; + for (int corner = 0; corner < 8; ++corner) + { + const CullerWalkReal x = (corner & 4) ? bounds.max.x : bounds.min.x; + const CullerWalkReal y = (corner & 2) ? bounds.max.y : bounds.min.y; + const CullerWalkReal z = (corner & 1) ? bounds.max.z : bounds.min.z; + const CullerWalkReal nx = plane.normal.x, ny = plane.normal.y, nz = plane.normal.z; + CullerWalkReal dot; + if (corner < 3) + dot = (z * nz + x * nx) + y * ny + CullerWalkReal(plane.d); + else if (corner < 5) + dot = (x * nx + z * nz) + y * ny + CullerWalkReal(plane.d); + else + dot = (z * nz + y * ny) + x * nx + CullerWalkReal(plane.d); + inFront += cullerWalkGreater(dot, CullerWalkReal(0)); + } + if (inFront == 8) + { + child->visible = 0; + break; + } + if (inFront) + { + child->visible = 1; + break; + } + ++inside; + } + if (inside == 6) + child->visible = 1; + if (!child->visible) + { + allComplete = false; + candidates[childIndex] = 0; + continue; + } + TerrainCullerNode* const lodNode = parent->child[childIndex]; + const TerrainAabb& lodBounds = lodNode->bounds; + const float* const camera = cameraPosition; + CullerWalkReal dx = CullerWalkReal(0), dz = CullerWalkReal(0); + if (cullerWalkLess(CullerWalkReal(camera[0]), CullerWalkReal(lodBounds.min.x))) + dx = CullerWalkReal(camera[0]) - CullerWalkReal(lodBounds.min.x); + else if (cullerWalkGreater(CullerWalkReal(camera[0]), CullerWalkReal(lodBounds.max.x))) + dx = CullerWalkReal(lodBounds.max.x) - CullerWalkReal(camera[0]); + if (cullerWalkLess(CullerWalkReal(camera[2]), CullerWalkReal(lodBounds.min.z))) + dz = CullerWalkReal(camera[2]) - CullerWalkReal(lodBounds.min.z); + else if (cullerWalkGreater(CullerWalkReal(camera[2]), CullerWalkReal(lodBounds.max.z))) + dz = CullerWalkReal(lodBounds.max.z) - CullerWalkReal(camera[2]); + const CullerWalkReal distance = cullerWalkSqrt(dz * dz + dx * dx) + + CullerWalkReal(terrain->m_cameraHeightAboveTerrain); + const CullerWalkReal limit = CullerWalkReal(lodDistance); + if (!cullerWalkLessEqual(distance, limit)) + { + setLod(lodNode, !cullerWalkLessEqual(distance, limit * CullerWalkReal(lodFactor30)) ? 2 : 1); + } + else + { + if (lodNode->child[0]) + for (int grandchild = 0; grandchild < 4; ++grandchild) + if (lodNode->child[grandchild]->visible) + setLod(lodNode->child[grandchild], 0); + lodNode->lod = 0; + } + TerrainCullerNode* const selected = parent->child[childIndex]; + if (!selected->fileByteEE) + { + const bool complete = walkMode4(selected) != 0; + allComplete = allComplete & complete; + childComplete[childIndex] = complete; + } + else + childComplete[childIndex] = true; + ++parent->childrenWalked; + candidates[childIndex] = parent->child[childIndex]; + } + if (!parent->patch) + return 0; + if (!allComplete) + { + for (int index = 0; index < 4; ++index) + if (candidates[index] && childComplete[index]) + visible.push_back(candidates[index]); + return 0; + } + if (!parent->hasPatchList) + return 1; + visible.push_back(parent); + return 0; +} + + +// PE 0x100E6270. [INFERRED] Placement with the existing TerrainCuller bodies. +void TerrainCuller::walkMode5(TerrainCullerNode* parent) +{ + parent->childrenWalked = 0; + for (int childIndex = 0; childIndex < 4; ++childIndex) + { + TerrainCullerNode* const child = parent->child[childIndex]; + TerrainAabb& bounds = child->bounds; + if (bounds.dirty) + bounds.refresh(); + const float radius = bounds.radius; + if (bounds.dirty) + bounds.refresh(); + child->visible = rendmath::frustumInside(*frustum, bounds.centre, radius) ? 1 : 0; + if (!child->visible) + continue; + + child->cameraInside = 0; + int inside = 0; + for (int planeIndex = 0; planeIndex < 6; ++planeIndex) + { + const Plane3& plane = frustum->m_planes[planeIndex]; + int inFront = 0; + for (int corner = 0; corner < 8; ++corner) + { + const CullerWalkReal x = (corner & 4) ? bounds.max.x : bounds.min.x; + const CullerWalkReal y = (corner & 2) ? bounds.max.y : bounds.min.y; + const CullerWalkReal z = (corner & 1) ? bounds.max.z : bounds.min.z; + const CullerWalkReal nx = plane.normal.x, ny = plane.normal.y, nz = plane.normal.z; + // The first three corners sum y/z/x; the remaining five sum y/x/z. + const CullerWalkReal dot = corner < 3 + ? (y * ny + z * nz) + x * nx + CullerWalkReal(plane.d) + : (y * ny + x * nx) + z * nz + CullerWalkReal(plane.d); + inFront += cullerWalkGreater(dot, CullerWalkReal(0)); + } + if (inFront == 8) + { + child->visible = 0; + break; + } + if (inFront) + { + child->visible = 1; + break; + } + ++inside; + } + if (inside == 6) + child->visible = 1; + if (!child->visible) + continue; + + TerrainCullerNode* const lodNode = parent->child[childIndex]; + const TerrainAabb& lodBounds = lodNode->bounds; + const float* const camera = cameraPosition; + CullerWalkReal dx = CullerWalkReal(0), dz = CullerWalkReal(0); + if (cullerWalkLess(CullerWalkReal(camera[0]), CullerWalkReal(lodBounds.min.x))) + dx = CullerWalkReal(camera[0]) - CullerWalkReal(lodBounds.min.x); + else if (cullerWalkGreater(CullerWalkReal(camera[0]), CullerWalkReal(lodBounds.max.x))) + dx = CullerWalkReal(lodBounds.max.x) - CullerWalkReal(camera[0]); + if (cullerWalkLess(CullerWalkReal(camera[2]), CullerWalkReal(lodBounds.min.z))) + dz = CullerWalkReal(camera[2]) - CullerWalkReal(lodBounds.min.z); + else if (cullerWalkGreater(CullerWalkReal(camera[2]), CullerWalkReal(lodBounds.max.z))) + dz = CullerWalkReal(lodBounds.max.z) - CullerWalkReal(camera[2]); + + const CullerWalkReal distance = cullerWalkSqrt(dz * dz + dx * dx) + + CullerWalkReal(terrain->m_cameraHeightAboveTerrain); + const CullerWalkReal limit = CullerWalkReal(lodDistance); + if (!cullerWalkLessEqual(distance, limit)) + setLod(lodNode, !cullerWalkLessEqual(distance, limit * CullerWalkReal(lodFactor30)) ? 2 : 1); + else + { + if (lodNode->child[0]) + for (int grandchild = 0; grandchild < 4; ++grandchild) + if (lodNode->child[grandchild]->visible) + setLod(lodNode->child[grandchild], 0); + lodNode->lod = 0; + } + TerrainCullerNode* const selected = parent->child[childIndex]; + if (selected->fileByteEE) + visible.push_back(selected); + else + walkMode5(selected); + ++parent->childrenWalked; + } +} + +// PE 0x100E6640. [INFERRED] Placement with the existing TerrainCuller bodies. +int TerrainCuller::walkMode6(TerrainCullerNode* node) +{ + node->childrenWalked = 0; + TerrainAabb& bounds = node->bounds; + if (bounds.dirty) + bounds.refresh(); + const float radius = bounds.radius; + if (bounds.dirty) + bounds.refresh(); + node->visible = rendmath::frustumInside(*frustum, bounds.centre, radius) ? 1 : 0; + bool accepted = node->visible != 0; + if (accepted && node->lod == 0) + { + // PE 0x101C6A90, the pure eight-corner test at 0x100E66AC. + for (int planeIndex = 0; planeIndex < 6; ++planeIndex) + { + const Plane3& plane = frustum->m_planes[planeIndex]; + int inFront = 0; + for (int corner = 0; corner < 8; ++corner) + { + const CullerWalkReal x = node->corners[3 * corner]; + const CullerWalkReal y = node->corners[3 * corner + 1]; + const CullerWalkReal z = node->corners[3 * corner + 2]; + const CullerWalkReal nx = plane.normal.x, ny = plane.normal.y, nz = plane.normal.z; + const CullerWalkReal dot = corner == 0 + ? (z * nz + x * nx) + y * ny + CullerWalkReal(plane.d) + : (y * ny + z * nz) + x * nx + CullerWalkReal(plane.d); + inFront += cullerWalkGreater(dot, CullerWalkReal(0)); + } + if (inFront == 8) + { + accepted = false; + break; + } + } + } + node->visible = accepted ? 1 : 0; + if (!node->visible) + return static_cast(node->visible); + + if (node->child[0]) + for (int child = 0; child < 4; ++child) + if (walkMode6(node->child[child])) + ++node->childrenWalked; + if (!node->patch && !node->childrenWalked) + { + node->visible = 0; + return 0; + } + if (node->fileByteEE) + { + const float* const camera = cameraPosition; + CullerWalkReal dx = CullerWalkReal(0), dz = CullerWalkReal(0); + if (cullerWalkLess(CullerWalkReal(camera[0]), CullerWalkReal(bounds.min.x))) + dx = CullerWalkReal(camera[0]) - CullerWalkReal(bounds.min.x); + else if (cullerWalkGreater(CullerWalkReal(camera[0]), CullerWalkReal(bounds.max.x))) + dx = CullerWalkReal(bounds.max.x) - CullerWalkReal(camera[0]); + if (cullerWalkLess(CullerWalkReal(camera[2]), CullerWalkReal(bounds.min.z))) + dz = CullerWalkReal(camera[2]) - CullerWalkReal(bounds.min.z); + else if (cullerWalkGreater(CullerWalkReal(camera[2]), CullerWalkReal(bounds.max.z))) + dz = CullerWalkReal(bounds.max.z) - CullerWalkReal(camera[2]); + const CullerWalkReal distance = cullerWalkSqrt(dz * dz + dx * dx) + + CullerWalkReal(terrain->m_cameraHeightAboveTerrain); + if (cullerWalkLessEqual(distance, CullerWalkReal(lodDistance))) + setLod(node, 0); + else + { + // The image's LEA triples the signed integer threshold with 32-bit wrap. + const int farLimit = static_cast(3u * static_cast(lodDistance)); + setLod(node, cullerWalkLessEqual(distance, CullerWalkReal(farLimit)) ? 1 : 2); + } + visible.push_back(node); + } + return static_cast(node->visible); +} + +// the node's visible children first, then the node; 3 and above clamp to 2. +void TerrainCuller::setLod(TerrainCullerNode* node, int lod) +{ + if (node->child[0]) + { + for (int c = 0; c < 4; ++c) + if (node->child[c]->visible) + setLod(node->child[c], lod); + } + node->lod = lod; + if (lod >= 3) + node->lod = 2; +} + +// the crack mask. Version 0x1A content: per visible node, the neighbours 1 (bit 1), +// 6 (bit 2), 3 (bit 4) and 4 (bit 8) that sit one LOD finer decide the mask; a LOD-2 node with any +// LOD-0 neighbour drops to LOD 1 first. Older content: a LOD-2 node with a null or LOD-0 neighbour +// drops to LOD 1 and the mask stays 0. +void TerrainCuller::fixCracks() +{ + TerrainCullerNode** const first = visible.data(); + TerrainCullerNode** const last = first + visible.size(); + if (versionFlag78) + { + for (TerrainCullerNode** it = first; it != last; ++it) + { + TerrainCullerNode* const n = *it; + const int lod = n->lod; + n->crackMask = 0; + TerrainCullerNode* const nb1 = n->neighbour[1]; + TerrainCullerNode* const nb3 = n->neighbour[3]; + TerrainCullerNode* const nb4 = n->neighbour[4]; + TerrainCullerNode* const nb6 = n->neighbour[6]; + if (n->allNeighbours) + { + if (lod == 1) + { + if (lod0(nb1)) + { + n->crackMask = 1; + if (lod0(nb3)) n->crackMask = 5; + else if (lod0(nb4)) n->crackMask = 9; + } + else if (lod0(nb6)) + { + n->crackMask = 2; + if (lod0(nb3)) n->crackMask = 6; + else if (lod0(nb4)) n->crackMask = 10; + } + else if (lod0(nb3)) n->crackMask = 4; + else if (lod0(nb4)) n->crackMask = 8; + } + else if (lod == 2) + { + bool anyLod0 = false; + for (int i = 0; i < 8; ++i) + if (n->neighbour[i]->lod == 0) { anyLod0 = true; break; } + if (anyLod0) + { + n->lod = 1; + if (lod0(nb1)) + { + n->crackMask = 1; + if (lod0(nb3)) n->crackMask = 1 | 4; + else if (lod0(nb4)) n->crackMask = 1 | 8; + } + else if (lod0(nb6)) + { + n->crackMask = 2; + if (lod0(nb3)) n->crackMask = 2 | 4; + else if (lod0(nb4)) n->crackMask = 2 | 8; + } + else if (lod0(nb3)) n->crackMask = 4; + else if (lod0(nb4)) n->crackMask = 8; + } + if (lod1(nb1)) + { + n->crackMask |= 1; + if (lod1(nb3)) n->crackMask |= 4; + else if (lod1(nb4)) n->crackMask |= 8; + } + else if (lod1(nb6)) + { + n->crackMask |= 2; + if (lod1(nb3)) n->crackMask |= 4; + else if (lod1(nb4)) n->crackMask |= 8; + } + else if (lod1(nb3)) n->crackMask |= 4; + else if (lod1(nb4)) n->crackMask |= 8; + } + } + else + { + if (lod == 1) + { + if (lod0n(nb1)) + { + n->crackMask = 1; + if (lod0n(nb3)) n->crackMask = 5; + else if (nb4 && nb4->visible && nb4->lod == 0) n->crackMask = 9; + } + else if (lod0n(nb6)) + { + n->crackMask = 2; + if (lod0n(nb3)) n->crackMask = 6; + else if (lod0n(nb4)) n->crackMask = 10; + } + else if (lod0n(nb3)) n->crackMask = 4; + else if (lod0n(nb4)) n->crackMask = 8; + } + else if (lod == 2) + { + bool anyLod0 = false; + for (int i = 0; i < 8; ++i) + { + TerrainCullerNode* const nb = n->neighbour[i]; + if (nb && nb->lod == 0) { anyLod0 = true; break; } + } + if (anyLod0) + { + n->lod = 1; + if (lod0n(nb1)) + { + n->crackMask = 1; + if (lod0n(nb3)) n->crackMask = 1 | 4; + else if (lod0n(nb4)) n->crackMask = 1 | 8; } else if (lod0n(nb6)) { @@ -1516,8 +2217,7 @@ void TerrainCuller::fixCracks() // clear the gathered list, take the centre and radius, walk from the root. void TerrainCuller::gatherSphere(const float* centre, float radius) { - if (gathered.first) // sub_100E7520(0, 0) - gathered.last = gathered.first; + gathered.clear(); // sub_100E7520(0, 0) gatherRadius = radius; gatherRadiusSq = radius * radius; gatherCentre = centre; @@ -1544,52 +2244,480 @@ void TerrainCuller::gatherNode(TerrainCullerNode* node) if (static_cast(radius) + gatherRadius > std::sqrt(dz * dz + dx * dx + dy * dy)) { if (node->patch) - vc71::vectorPushBackIn(gathered, 4u, &node); + gathered.push_back(node); + } +} + +// Gathers sphere-overlapping patches from this frame's visible terrain tree. +void TerrainCuller::gatherVisibleSphere(const float* centre, float radius) +{ + gathered.clear(); // sub_100E7520(0, 0) + gatherCentre = centre; + gatherRadiusSq = radius * radius; + gatherRadius = radius; + if (nodes->visible) + gatherVisibleNode(nodes); +} + +// Gathers visible leaf patches whose spheres strictly overlap the gather sphere. +// Traversed internal nodes require four valid children. Arithmetic stays in float precision +// to preserve the renderer's 24-bit x87 behavior (RW-240). +void TerrainCuller::gatherVisibleNode(TerrainCullerNode* node) +{ + if (node->childrenWalked != 0) + { + for (int c = 0; c < 4; ++c) + { + if (node->child[c]->visible) + gatherVisibleNode(node->child[c]); + } + return; + } + if (node->bounds.dirty) + node->bounds.refresh(); + const float radius = node->bounds.radius; + if (node->bounds.dirty) + node->bounds.refresh(); + const float* const centre = gatherCentre; + const float dx = centre[0] - node->bounds.centre.x; + const float dy = centre[1] - node->bounds.centre.y; + const float dz = centre[2] - node->bounds.centre.z; + const float distance = std::sqrt(dz * dz + dx * dx + dy * dy); // the float overload + const float reach = radius + gatherRadius; + if (reach > distance && node->patch) + gathered.push_back(node); +} + + +// PE 0x100E2D80. [INFERRED] Name and placement with the existing TerrainCuller bodies. +void TerrainCuller::assignLegacyGridIndices(TerrainCullerNode* node, int x, int z) +{ + for (;;) + { + if (node != nodes) + { + const int exponent = static_cast(static_cast(node->legacyLevel) - 1u); + unsigned int offset = 1; + for (int level = 1; level < exponent; ++level) + { + const unsigned int width = 1u << (static_cast(level) & 31u); + offset += width * width; + } + const unsigned int width = 1u << (static_cast(exponent) & 31u); + node->legacyGridIndex = static_cast(width * static_cast(z) + offset + + static_cast(x)); + } + if (!node->child[0]) + return; + const int x0 = static_cast(2u * static_cast(x)); + const int z0 = static_cast(2u * static_cast(z)); + const int x1 = static_cast(static_cast(x0) + 1u); + const int z1 = static_cast(static_cast(z0) + 1u); + assignLegacyGridIndices(node->child[0], x0, z0); + assignLegacyGridIndices(node->child[1], x1, z0); + assignLegacyGridIndices(node->child[2], x0, z1); + node = node->child[3]; + x = x1; + z = z1; + } +} + +namespace { + + // [CHOSEN, not recovered] Native extended expressions preserve the PE's explicit stores. +#if defined(__APPLE__) +typedef bf2x87::Real LegacyTerrainReal; +inline LegacyTerrainReal legacyWide(float value) { return bf2x87::wide(value); } +inline LegacyTerrainReal legacyInteger(int value) { return bf2x87::wide(value); } +inline float legacyStore(LegacyTerrainReal value) { return bf2x87::store(value); } +inline int legacyTruncate(LegacyTerrainReal value) { return bf2x87::toIntTruncate(value); } + +LegacyTerrainReal legacyRemainder(LegacyTerrainReal value, float divisor) +{ +#if defined(__aarch64__) || defined(BF2_TEST_SOFT_EXTENDED) + // The denominator is the stored integer patch size. Binary long division keeps the + // remainder exact without reducing an extended numerator to binary64 for libm. + const LegacyTerrainReal zero = bf2x87::wide(0); + const LegacyTerrainReal two = bf2x87::wide(2); + if (!bf2x87::isFinite(value) || divisor == 0.0f || !std::isfinite(divisor)) + return bf2x87::wide(std::fmod(bf2x87::storeDouble(value), static_cast(divisor))); + if (value == zero) + return value; + const bool negative = value < zero; + LegacyTerrainReal remainder = negative ? -value : value; + const LegacyTerrainReal unit = bf2x87::wide(std::fabs(divisor)); + LegacyTerrainReal scaled = unit; + while (scaled <= remainder / two) + scaled = scaled * two; + while (scaled >= unit) + { + if (remainder >= scaled) + remainder = remainder - scaled; + scaled = scaled / two; + } + if (remainder == zero) + remainder = zero; // fmod keeps the dividend's sign + return negative ? -remainder : remainder; +#else + return std::fmod(value, static_cast(divisor)); +#endif +} +#else +typedef double LegacyTerrainReal; +inline LegacyTerrainReal legacyWide(float value) { return value; } +inline LegacyTerrainReal legacyInteger(int value) { return value; } +inline float legacyStore(LegacyTerrainReal value) { return static_cast(value); } +inline int legacyTruncate(LegacyTerrainReal value) { return static_cast(value); } +inline LegacyTerrainReal legacyRemainder(LegacyTerrainReal value, float divisor) +{ + return std::fmod(value, static_cast(divisor)); +} +#endif + +// Shared patch-level sequence in PE 0x100E68B0 / 0x100E4690. +void bindLegacyPatch(Terrain* terrain, TerrainCullerNode* node, bool storedSize) +{ + const LegacyTerrainReal inverseScale = legacyWide(1.0f) / legacyWide(terrain->m_primaryWorldScale.x); + float x = legacyStore(legacyWide(node->bounds.min.x) * inverseScale); + const LegacyTerrainReal z = inverseScale * legacyWide(node->bounds.min.z); + const LegacyTerrainReal denominator = storedSize + ? legacyWide(legacyStore(legacyInteger(terrain->m_patchSize))) + : legacyInteger(terrain->m_patchSize); + const LegacyTerrainReal inverseSize = legacyWide(1.0f) / denominator; + x = legacyStore(legacyWide(x) * inverseSize); + const int half = terrain->m_patchCount / 2; + const unsigned int row = static_cast(legacyTruncate(z * inverseSize)) + + static_cast(half); + const unsigned int index = static_cast(legacyTruncate(legacyWide(x))) + + row * static_cast(terrain->m_patchCount) + static_cast(half); + node->patch = terrain->m_patches[index]; + node->lodTable = terrain->m_lodTables; + node->bounds.min.y = node->patch->minHeight; + node->bounds.max.y = node->patch->maxHeight; + for (unsigned int i = 0; i < node->patch->detailLayers.size(); ++i) + { + QuadPatchDetailLayer* const layer = node->patch->detailLayers[i]; + node->layerLodTables.push_back(layer ? layer->lodTables : 0); + } +} + +} // namespace + +// PE 0x100E68B0. [INFERRED] Name and placement with the existing TerrainCuller bodies. +void TerrainCuller::buildLegacyTree() +{ + world::IHeightmap* const heightmap = heightmapCluster()->getPrimaryHeightmap(); + void* const storage = ::renddx9abi::engineAlloc(sizeof(TerrainCullerNode)); + nodes = storage ? new (storage) TerrainCullerNode() : 0; + int size; + heightmap->getSize(size, size); // shipped aliasing + const int scale = legacyTruncate(legacyWide(heightmap->getScale().x)); + const unsigned int spanBits = (static_cast(size) - 1u) + * static_cast(scale); + const int span = static_cast(spanBits); + nodes->legacyGridIndex = 0; + nodes->legacyLevel = 1; + const float lower = legacyStore(legacyInteger(static_cast(0u - spanBits)) * legacyWide(0.5f)); + const float upper = legacyStore(legacyInteger(span) * legacyWide(0.5f)); + nodes->bounds.min = { lower, terrain->m_minHeight, lower }; + nodes->bounds.max = { upper, terrain->m_maxHeight, upper }; + nodes->bounds.dirty = 1; + aabbCorners(nodes->corners, &nodes->bounds.min.x); + nodes->fileByteEC = 0; + nodes->lodTable = 0; + nodes->patch = 0; + nodes->childrenWalked = 0; + nodes->legacyParent = 0; + for (int i = 0; i < 4; ++i) nodes->child[i] = 0; + for (int i = 0; i < 8; ++i) nodes->neighbour[i] = 0; + if (nodes->bounds.dirty) + nodes->bounds.refresh(); + if (legacyWide(nodes->bounds.extent.x) + == legacyInteger(terrain->m_patchSize) * legacyWide(terrain->m_primaryWorldScale.x)) + { + nodes->hasPatchList = 1; + bindLegacyPatch(terrain, nodes, true); + } + for (int quadrant = 0; quadrant < 4; ++quadrant) + buildLegacyChild(nodes, quadrant, 0); + assignLegacyGridIndices(nodes, 0, 0); + if (nodes->child[0]) + for (int quadrant = 0; quadrant < 4; ++quadrant) + if (nodes->child[quadrant]->visible) + setLod(nodes->child[quadrant], 0); + nodes->lod = 0; + linkLegacyNeighbours(nodes); +} + +// PE 0x100E4690, retn 0x0C; its third stack word is unused at every recursive call. +// [INFERRED] Name and placement with the existing TerrainCuller bodies. +void TerrainCuller::buildLegacyChild(TerrainCullerNode* parent, int quadrant, int /*unused*/) +{ + for (;;) + { + void* const storage = ::renddx9abi::engineAlloc(sizeof(TerrainCullerNode)); + TerrainCullerNode* const node = storage ? new (storage) TerrainCullerNode() : 0; + node->legacyLevel = static_cast(static_cast(parent->legacyLevel) + 1u); + TerrainAabb& source = parent->bounds; + Vec3 lower = source.min; + if (source.dirty) source.refresh(); + const float xPart = legacyStore(legacyInteger(quadrant % 2)); + lower.x = legacyStore(legacyWide(xPart) * legacyWide(source.extent.x) + * legacyWide(0.5f) + legacyWide(lower.x)); + if (source.dirty) source.refresh(); + const float zPart = legacyStore(legacyInteger(quadrant / 2)); + lower.z = legacyStore(legacyWide(zPart) * legacyWide(source.extent.z) + * legacyWide(0.5f) + legacyWide(lower.z)); + if (source.dirty) source.refresh(); + Vec3 upper = { source.centre.x, source.max.y, source.centre.z }; + if (source.dirty) source.refresh(); + upper.x = legacyStore(legacyWide(xPart) * legacyWide(source.extent.x) + * legacyWide(0.5f) + legacyWide(upper.x)); + if (source.dirty) source.refresh(); + upper.z = legacyStore(legacyWide(zPart) * legacyWide(source.extent.z) + * legacyWide(0.5f) + legacyWide(upper.z)); + node->bounds.min = lower; + node->bounds.max = upper; + node->bounds.dirty = 1; + node->legacyParent = parent; + for (int i = 0; i < 4; ++i) node->child[i] = 0; + parent->child[quadrant] = node; + for (int i = 0; i < 8; ++i) node->neighbour[i] = 0; + node->childrenWalked = 0; + TerrainAabb& bounds = node->bounds; + if (bounds.dirty) bounds.refresh(); + node->fileByteEC = legacyInteger(terrain->m_patchSize) * legacyWide(terrain->m_primaryWorldScale.x) + > legacyWide(bounds.extent.x); + if (bounds.dirty) bounds.refresh(); + node->fileByteEE = legacyWide(bounds.extent.x) == legacyInteger(param14); + if (bounds.dirty) bounds.refresh(); + if (legacyWide(bounds.extent.x) + == legacyInteger(terrain->m_patchSize) * legacyWide(terrain->m_primaryWorldScale.x)) + { + node->hasPatchList = 1; + bindLegacyPatch(terrain, node, false); + } + if (node->fileByteEC) + { + node->patch = parent->patch; + node->lodTable = reinterpret_cast(parent->lodTable)->children[quadrant]; + const LegacyTerrainReal inverse = legacyWide(1.0f) / legacyWide(terrain->m_primaryWorldScale.x); + const float maxX = legacyStore(legacyWide(bounds.max.x) * inverse); + const float maxZ = legacyStore(legacyWide(bounds.max.z) * inverse); + const float storedInverse = legacyStore(inverse); + const float minX = legacyStore(legacyWide(bounds.min.x) * legacyWide(storedInverse)); + const float minZ = legacyStore(legacyWide(bounds.min.z) * legacyWide(storedInverse)); + const float size = legacyStore(legacyInteger(terrain->m_patchSize)); + const int startX = legacyTruncate(legacyRemainder( + legacyInteger(terrain->m_patchSize) * legacyWide(20.0f) + legacyWide(minX), size)); + const int startZ = legacyTruncate(legacyRemainder( + legacyInteger(terrain->m_patchSize) * legacyWide(20.0f) + legacyWide(minZ), size)); + bounds.min.y = FLT_MAX; + bounds.max.y = FLT_MIN; // shipped positive seed + const int endZ = static_cast(static_cast(startZ) + + static_cast(legacyTruncate(legacyWide(maxZ) - legacyWide(minZ)))); + const int endX = static_cast(static_cast(startX) + + static_cast(legacyTruncate(legacyWide(maxX) - legacyWide(minX)))); + for (int z = startZ; z < endZ; ++z) + for (int x = startX; x < endX; ++x) + { + const unsigned int index = (static_cast(terrain->m_patchSize) + 1u) + * static_cast(z) + static_cast(x); + const float height = legacyStore( + legacyWide(static_cast(node->patch->legacyVertexTable)[index]) + * legacyWide(terrain->m_primaryWorldScale.y)); + bounds.min.y = bounds.min.y < height ? bounds.min.y : height; + bounds.max.y = bounds.max.y < height ? height : bounds.max.y; + } + for (unsigned int i = 0; i < node->patch->detailLayers.size(); ++i) + { + unsigned char* const table = parent->layerLodTables[i]; + node->layerLodTables.push_back(table + ? reinterpret_cast(table)->children[quadrant] : 0); + } + // shipped defect: the cached bounds remain clean after changing min/max Y. + } + if (bounds.dirty) bounds.refresh(); + if (legacyWide(bounds.extent.x) + == legacyInteger(terrain->m_patchSize) * legacyWide(terrain->m_primaryWorldScale.x) + || node->fileByteEC) + node->occlusionQuery = dx9rend::queryManagerCreateQuery(9); + aabbCorners(node->corners, &bounds.min.x); + if (bounds.dirty) bounds.refresh(); + if (!(legacyInteger(param10) < legacyWide(bounds.extent.x))) + return; + buildLegacyChild(node, 0, 0); + buildLegacyChild(node, 1, 0); + buildLegacyChild(node, 2, 0); + parent = node; + quadrant = 3; + } +} + +// PE 0x100E2E50. [INFERRED] Name and placement with the existing TerrainCuller bodies. +TerrainCullerNode* TerrainCuller::findLegacyNode(int index, TerrainCullerNode* node) +{ + if (!node) + return 0; + if (node->legacyGridIndex == index) + return node; + if (node->child[0]) + for (int child = 0; child < 4; ++child) + { + TerrainCullerNode* const found = findLegacyNode(index, node->child[child]); + if (found) + return found; + } + return 0; +} + +// PE 0x100E3250. [INFERRED] Name and placement with the existing TerrainCuller bodies. +void TerrainCuller::linkLegacyNeighbours(TerrainCullerNode* node) +{ + for (;;) + { + const int index = node->legacyGridIndex; + if (index != 0) + { + const int exponent = static_cast(static_cast(node->legacyLevel) - 1u); + const unsigned int widthBits = 1u << (static_cast(exponent) & 31u); + const int width = static_cast(widthBits); + unsigned int offset = 0; + for (int level = 1; level < exponent; ++level) + { + const unsigned int side = 1u << (static_cast(level) & 31u); + offset += side * side; + } + const unsigned int bits = static_cast(index); + const int relative = static_cast(bits - offset); + const int firstBelow = static_cast(offset + widthBits + 1u); + const int lastAbove = static_cast((widthBits - 1u) * widthBits + offset); + const int rightRemainder = relative % width; + const int leftRemainder = static_cast(bits - offset - 1u) % width; + if (leftRemainder != 0) + { + if (index >= firstBelow) + node->neighbour[0] = findLegacyNode(static_cast(bits - widthBits - 1u), nodes); + node->neighbour[3] = findLegacyNode(static_cast(bits - 1u), nodes); + if (index <= lastAbove) + node->neighbour[5] = findLegacyNode(static_cast(bits + widthBits - 1u), nodes); + } + if (index >= firstBelow) + node->neighbour[1] = findLegacyNode(static_cast(bits - widthBits), nodes); + if (index <= lastAbove) + node->neighbour[6] = findLegacyNode(static_cast(bits + widthBits), nodes); + if (rightRemainder != 0) + { + if (index >= firstBelow) + node->neighbour[2] = findLegacyNode(static_cast(bits - widthBits + 1u), nodes); + node->neighbour[4] = findLegacyNode(static_cast(bits + 1u), nodes); + if (index <= lastAbove) + node->neighbour[7] = findLegacyNode(static_cast(bits + widthBits + 1u), nodes); + } + } + if (!node->child[0]) + return; + linkLegacyNeighbours(node->child[0]); + linkLegacyNeighbours(node->child[1]); + linkLegacyNeighbours(node->child[2]); + node = node->child[3]; + } +} + +// PE 0x100E3B60. [INFERRED] Placement with the existing TerrainCuller bodies. +void TerrainCuller::filterOccluded() +{ + std::vector::iterator it = visible.begin(); + while (it != visible.end()) + { + TerrainCullerNode* const node = *it; + void* const query = node->occlusionQuery; + const int samples = readRendererOcclusionQuery(query); + const unsigned int current = + static_cast(dx9rend::g_rendererBase)->getFrameOrdinal(); + const unsigned int resultFrame = rendererOcclusionQueryFrame(query); + const int age = static_cast(current - resultFrame); +#if defined(_MSC_VER) && defined(_M_IX86) + const int maxFrames = *reinterpret_cast( + static_cast(dx9rend::g_rendererBase) + 0x3EC); +#else + // [CHOSEN, not recovered] Named access for the native renderer layout: +0x3EC is + // RendDX9Base::occlusionTerrainMaxFrames (Renderer::tailField), initialized to 1 + // (PE 0x1000BA72), set by renderer.occlusionTerrainMaxFrames with the upper-only clamp + // to 10 (0x10053523). + const int maxFrames = dx9rend::rendererTailInt(0x3EC); +#endif + if (age > maxFrames || samples != 0) + ++it; + else + { + node->visible = 0; + it = visible.erase(it); + } + } +} + +// PE 0x100E6CB0. [INFERRED] Placement with the existing TerrainCuller bodies. +void TerrainCuller::gatherVisibleFrustum(Frustum* source) +{ + gathered.clear(); + frustum = source; + if (nodes->visible) + gatherVisibleFrustumNode(nodes); +} + +// PE 0x100E4460. [INFERRED] Placement with the existing TerrainCuller bodies. +void TerrainCuller::gatherVisibleFrustumNode(TerrainCullerNode* node) +{ + if (node->childrenWalked) + { + for (int child = 0; child < 4; ++child) + if (node->child[child]->visible) + gatherVisibleFrustumNode(node->child[child]); + return; } + TerrainAabb& bounds = node->bounds; + if (bounds.dirty) + bounds.refresh(); + const float radius = bounds.radius; + if (bounds.dirty) + bounds.refresh(); + if (rendmath::frustumInside(*frustum, bounds.centre, radius) && node->patch) + gathered.push_back(node); } -// Gathers sphere-overlapping patches from this frame's visible terrain tree. -void TerrainCuller::gatherVisibleSphere(const float* centre, float radius) +// PE 0x100E6CE0. Unreachable in 1.50: no code or data references. [INFERRED] Placement with the +// existing TerrainCuller bodies. +void TerrainCuller::gatherShadowFrustum(Frustum* source, Frustum* fitNearPlane, int unused) { - if (gathered.first) // sub_100E7520(0, 0) - gathered.last = gathered.first; - gatherCentre = centre; - gatherRadiusSq = radius * radius; - gatherRadius = radius; - if (nodes->visible) - gatherVisibleNode(nodes); + gathered.clear(); // sub_100E7520(0, 0) + frustum = source; + gatherShadowFrustumNode(nodes, fitNearPlane, unused); } -// Gathers visible leaf patches whose spheres strictly overlap the gather sphere. -// Traversed internal nodes require four valid children. Arithmetic stays in float precision -// to preserve the renderer's 24-bit x87 behavior (RW-240). -void TerrainCuller::gatherVisibleNode(TerrainCullerNode* node) +// PE 0x100E4500. Unreachable in 1.50: no code or data references. Children first; leaves (no +// children) return before any test, as in gatherNode. An inner node whose box meets the frustum +// and that has the file's push flag (+0xEE) is gathered, and its box is fitted into `fitNearPlane`. +void TerrainCuller::gatherShadowFrustumNode(TerrainCullerNode* node, Frustum* fitNearPlane, int unused) { - if (node->childrenWalked != 0) - { - for (int c = 0; c < 4; ++c) - { - if (node->child[c]->visible) - gatherVisibleNode(node->child[c]); - } + if (!node->child[0]) return; + for (int c = 0; c < 4; ++c) + gatherShadowFrustumNode(node->child[c], fitNearPlane, unused); + TerrainAabb& bounds = node->bounds; + if (bounds.dirty) + bounds.refresh(); + const float radius = bounds.radius; + if (bounds.dirty) + bounds.refresh(); + if (rendmath::frustumInside(*frustum, bounds.centre, radius) && node->fileByteEE) + { + gathered.push_back(node); + if (fitNearPlane) + fitShadowFrustumNearPlaneToBounds(*fitNearPlane, bounds.min, bounds.max); } - if (node->bounds.dirty) - node->bounds.refresh(); - const float radius = node->bounds.radius; - if (node->bounds.dirty) - node->bounds.refresh(); - const float* const centre = gatherCentre; - const float dx = centre[0] - node->bounds.centre.x; - const float dy = centre[1] - node->bounds.centre.y; - const float dz = centre[2] - node->bounds.centre.z; - const float distance = std::sqrt(dz * dz + dx * dx + dy * dy); // the float overload - const float reach = radius + gatherRadius; - if (reach > distance && node->patch) - vc71::vectorPushBackIn(gathered, 4u, &node); } - // QuadPatch - the draws. namespace { @@ -1618,8 +2746,179 @@ inline void drawPatchRange(Terrain* t, unsigned int primCount, unsigned int vert 0, 0u, vertexCount, start); } +// Morph constants in PE 0x1018991B..0x10189C39. The batched draw uses a distinct component +// arrangement from drawTechniquePass; each adder row fetches the height scale again. +void setShadowBatchMorph(Terrain* t, int lod) +{ + t->m_currentLod = lod; + float selector[4] = { static_cast(lod == 0), static_cast(lod == 1), + static_cast(lod == 2), static_cast(lod == 3) }; + const float height = t->m_primaryWorldScale.y; + for (int i = 0; i != 4; ++i) + selector[i] *= height; + param(t->m_hMorphDeltaSelector)->setValue(selector, 0); + param(t->m_hNearFarMorphLimits)->setValue(&t->m_morphLimits[2 * lod], 0); + float adder[12] = {}; + if (t->m_rawHasVersion >= 1u && t->m_rawVersion >= 0x1Au) + { + const int component[3][3] = { { 2, 2, 2 }, { 1, 0, 2 }, { 1, 2, 1 } }; + for (int row = 0; row != 3; ++row) + { + const float scale = t->m_primaryWorldScale.y; + for (int i = 0; i != 4; ++i) + adder[4 * row + i] = static_cast(i == component[lod][row]) * scale; + } + } + param(t->m_hMorphDeltaAdder)->setValue(adder, 0); +} + } // anonymous namespace +// PE 0x10188B80. Tangency and unordered distances both refuse the sphere. +bool QuadPatch::intersectsLightSphere(const Vec3& position, float radius) const +{ +#if defined(__APPLE__) + const bf2x87::Real x = bf2x87::sub(bf2x87::wide(sphereCentre.x), bf2x87::wide(position.x)); + const bf2x87::Real y = bf2x87::sub(bf2x87::wide(sphereCentre.y), bf2x87::wide(position.y)); + const bf2x87::Real z = bf2x87::sub(bf2x87::wide(sphereCentre.z), bf2x87::wide(position.z)); + const bf2x87::Real r = bf2x87::add(bf2x87::wide(radius), bf2x87::wide(sphereRadius)); + const bf2x87::Real distance = bf2x87::add(bf2x87::add(bf2x87::mul(x, x), bf2x87::mul(z, z)), + bf2x87::mul(y, y)); + return bf2x87::greater(bf2x87::mul(r, r), distance); +#else + const float x = sphereCentre.x - position.x; + const float y = sphereCentre.y - position.y; + const float z = sphereCentre.z - position.z; + const float r = radius + sphereRadius; + return r * r > (x * x + z * z) + y * y; +#endif +} + +// PE 0x101885E0. [INFERRED] Method name. +void QuadPatch::drawDepthComplexity(TerrainCullerNode**& it, int pass) +{ + (void)it; + (void)pass; + Debug(DebugTypeError, + "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\QuadPatch.cpp", 1671, "") + << "TBM: not used any more!"; +} + +// PE 0x10188D80. [INFERRED] Method name. +void QuadPatch::drawTechniquePass(TerrainCullerNode**& it, std::vector* list) +{ + static unsigned int once = 0; // dword_10261A04 + static unsigned int vertexCount = 0; // dword_10261A00 + Terrain* const t = terrain; + if ((once & 1u) == 0) + { + once |= 1u; + const int side = t->m_patchSize + 1; + vertexCount = static_cast(side * side); + } + beginPatchDraw(this); + while (it != list->data() + list->size()) + { + TerrainCullerNode* const node = *it; + if (node->patch != this) + return; + const int lod = node->lod; + if (t->m_currentLod != lod) + { + t->m_currentLod = lod; + float selector[4] = { static_cast(lod == 0), static_cast(lod == 1), + static_cast(lod == 2), static_cast(lod == 3) }; + const float scaleY = t->m_primaryWorldScale.y; + for (int i = 0; i < 4; ++i) + selector[i] *= scaleY; + param(t->m_hMorphDeltaSelector)->setValue(selector, 0); + param(t->m_hNearFarMorphLimits)->setValue(&t->m_morphLimits[2 * lod], 0); + float adder[12] = {}; + if (t->m_rawHasVersion >= 1u && t->m_rawVersion >= 0x1Au) + { + const float y0 = t->m_primaryWorldScale.y; + const float zero0 = 0.0f * y0; + adder[0] = zero0; adder[1] = zero0; adder[2] = y0; adder[3] = zero0; + const float y1 = t->m_primaryWorldScale.y; + const float zero1 = (lod == 1) ? y1 * 0.0f : 0.0f * y1; + if (lod == 1) + { + adder[4] = y1; adder[5] = zero1; adder[6] = zero1; adder[7] = zero1; + } + else + { + adder[4] = zero1; adder[5] = zero1; adder[6] = y1; adder[7] = zero1; + } + const float y2 = t->m_primaryWorldScale.y; + const float zero2 = 0.0f * y2; + if (lod == 0 || lod == 1) + { + adder[8] = zero2; adder[9] = zero2; adder[10] = y2; adder[11] = zero2; + } + else + { + adder[8] = zero2; adder[9] = y2; adder[10] = zero2; adder[11] = zero2; + } + } + param(t->m_hMorphDeltaAdder)->setValue(adder, 0); + } + param(t->m_hTexLayer[0])->setValue(lightmap, 0); + const TerrainLodRecord* const table = reinterpret_cast(node->lodTable); + const int primitives = static_cast(table->counts[node->lod][0]) / 3; + drawPatchRange(t, static_cast(primitives), vertexCount, table->starts[node->lod][0]); + terrainRendererStat(624) += static_cast(primitives); + ++it; + } +} + +// PE 0x10189720. The image's mode word 0x10261A10 is zero and has no writer or pointer-table +// reference; its per-range arm is unreachable. The default arm issues one draw per LOD, even +// when no range of that LOD contributes an index. +void QuadPatch::drawShadowBatch(TerrainCullerNode**& it, std::vector* visible, + const std::vector& ranges) +{ + static unsigned int once = 0; // PE 0x10261A18 + static unsigned int vertexCount = 0; // PE 0x10261A14 + if ((once & 1u) == 0) + { + once |= 1u; + const int side = terrain->m_patchSize + 1; + vertexCount = static_cast(side * side); + } + beginPatchDraw(this); + if (ranges.empty()) + return; + if (ranges.front().patchIndex == -1 && ranges.front().count == 0) + { + drawTechniquePass(it, visible); + return; + } + for (int lod = 0; lod != 3; ++lod) + { + unsigned int first = ranges.front().start; + unsigned int count = 0; + for (std::size_t i = 0; i < ranges.size(); ++i) + { + const TerrainShadowRange& range = ranges[i]; + if (range.node->lod == lod && range.patchIndex == patchIndex) + { + count += range.count; + if (first >= range.start) + first = range.start; + } + } + if (terrain->m_indexBufferCount >= first + count) + { + param(terrain->m_hTexLayer[0])->setValue(lightmap, 0); + if (terrain->m_currentLod != lod) + setShadowBatchMorph(terrain, lod); + const unsigned int triangles = count / 3u; + drawPatchRange(terrain, triangles, vertexCount, first); + terrainRendererStat(0x270) += triangles; + } + } +} + // pass 0: every visible node of this patch, by its LOD range; the "TerrainLightmap" // arm merges contiguous ranges of one LOD, the "TerrainMorphing" arm draws them one by one. void QuadPatch::draw(TerrainCullerNode**& it) @@ -1634,8 +2933,8 @@ void QuadPatch::draw(TerrainCullerNode**& it) s_vertexCount = static_cast((n + 1) * (n + 1)); } beginPatchDraw(this); - vc71::vector_layout* const list = t->m_culler->visiblePatches(); - TerrainCullerNode** const end = reinterpret_cast(list->last); + std::vector* const list = t->m_culler->visiblePatches(); + TerrainCullerNode** const end = list->data() + list->size(); if (t->m_mergeDrawRanges == 0) { while (it != end) @@ -1695,7 +2994,7 @@ void QuadPatch::draw(TerrainCullerNode**& it) // Draws gathered nodes while advancing it, switching passes and morph constants as needed. // The default mode uses uncracked index ranges. Counts primitives, without merging ranges. -void QuadPatch::drawGatheredNodes(TerrainCullerNode**& it, vc71::vector_layout* list, +void QuadPatch::drawGatheredNodes(TerrainCullerNode**& it, std::vector* list, int passLod0, int passOther) { static unsigned int s_once = 0; // dword_10261A0C @@ -1709,7 +3008,7 @@ void QuadPatch::drawGatheredNodes(TerrainCullerNode**& it, vc71::vector_layout* s_vertexCount = static_cast((n + 1) * (n + 1)); } beginPatchDraw(this); - if (it == reinterpret_cast(list->last)) + if (it == list->data() + list->size()) return; do { @@ -1729,6 +3028,8 @@ void QuadPatch::drawGatheredNodes(TerrainCullerNode**& it, vc71::vector_layout* unsigned int count = lodCount(node); // loaded first if (kRangeMode == 1) { + // 0x10189697: MaxPrimitiveCount is read here and its result discarded, as shipped. + (void)dx9rend::deviceCapsMaxPrimitiveCount(); const unsigned int* const table = reinterpret_cast(node->lodTable); start = table[16 * lod]; count = table[16 * (lod + 3)]; @@ -1737,7 +3038,7 @@ void QuadPatch::drawGatheredNodes(TerrainCullerNode**& it, vc71::vector_layout* drawPatchRange(t, static_cast(prims), s_vertexCount, start); terrainRendererStat(0x270) += static_cast(prims); // Renderer +0x6C, then +0x270 ++it; - } while (it != reinterpret_cast(list->last)); + } while (it != list->data() + list->size()); } // (132 B) - "TerrainPointLight": this patch's run of the culler's gathered list (the @@ -1745,13 +3046,162 @@ void QuadPatch::drawGatheredNodes(TerrainCullerNode**& it, vc71::vector_layout* // and pass 1 above it. Terrain::drawMaskLights is the live caller (the ShaderVersion-1 detail pass, // dead on stock shaders, is the other). The once-registered profiler timer (0x10262168, // "TerrainPointLight") and its begin/end (sub_10046EE0 / sub_10046EF0) are stat-only scaffolding -// this tree does not reproduce. Its sibling 0x1018C880 ("TerrainSpotLight", passes 12 / 1) has only -// the dead detail pass as a caller and is not written. +// this tree does not reproduce. void QuadPatch::drawPointLight(TerrainCullerNode**& it) { drawGatheredNodes(it, terrain->m_culler->gatheredPatches(), 13, 1); } +// PE 0x1018C880. The profiler is registered on first use and destroyed at exit. +void QuadPatch::drawSpotLight(TerrainCullerNode**& it) +{ + static dx9rend::QueueProfiler profiler(std::string("TerrainSpotLight")); // PE 0x102623D8 + profiler.begin(); + drawGatheredNodes(it, terrain->m_culler->gatheredPatches(), 12, 1); + dx9rend::QueueProfiler::end(); +} + +// PE 0x1018BB70, "TerrainOccluderShadows": this patch's run of the culler's gathered list drawn from +// the index ranges of one fixed LOD row, the light manager's terrain shadow LOD (slot +0x278), not +// the node's own LOD. With the terrain's merge flag set, the first node binds the scale/translate +// constant and the vertex stream, and contiguous ranges (the next range starting where the run +// ends, or ending where it starts) are merged into one draw; a run that cannot be merged is drawn +// without the empty-count test. Without the flag every node is drawn on its own and nothing is +// bound. [INFERRED] name (the profiler string and the sibling drawPointLight / drawSpotLight); +// unreachable in 1.50: no code or data references. +void QuadPatch::drawOccluderShadows(TerrainCullerNode**& it) +{ + static unsigned int s_once = 0; // dword_10261C8C bit 0 + static unsigned int s_vertexCount = 0; // dword_10261C88 + Terrain* const t = terrain; + if ((s_once & 1u) == 0) + { + const int n = t->m_patchSize; + s_once |= 1u; + s_vertexCount = static_cast((n + 1) * (n + 1)); + } + static dx9rend::QueueProfiler profiler(std::string("TerrainOccluderShadows")); // PE 0x10261A20 + profiler.begin(); + const int lod = g_LightManager->getTerrainShadowLod(); + std::vector* const list = t->m_culler->gatheredPatches(); + TerrainCullerNode** const end = list->data() + list->size(); + if (t->m_mergeDrawRanges) + { + bool bound = false; + while (it != end) + { + TerrainCullerNode* const node = *it; + if (node->patch != this) + break; + const unsigned int* const table = reinterpret_cast(node->lodTable); + int start = static_cast(table[16 * lod]); + int count = static_cast(table[16 * (lod + 3)]); + if (!bound) + { + float scaleTrans[4]; + scaleTrans[0] = static_cast(t->m_primaryWorldScale.x * 255.0); + scaleTrans[1] = static_cast(t->m_primaryWorldScale.z * 255.0); + scaleTrans[2] = worldXf; + scaleTrans[3] = worldZf; + bound = true; + param(t->m_hScaleTransXZ)->setValue(scaleTrans, 0); + dx9rend::vertexBufferBindStream(vertexBuffer, t->m_compactVertices ? 1u : 0u); + } + ++it; + bool drawnUnmerged = false; + while (it != end) + { + TerrainCullerNode* const next = *it; + if (next->patch != this) + break; + const unsigned int* const nextTable = reinterpret_cast(next->lodTable); + const int nextStart = static_cast(nextTable[16 * lod]); + const int nextCount = static_cast(nextTable[16 * (lod + 3)]); + if (nextStart != start + count) + { + if (nextStart + nextCount != start) + { + drawPatchRange(t, static_cast(count / 3), s_vertexCount, + static_cast(start)); + drawnUnmerged = true; + break; + } + start -= nextCount; + } + count += nextCount; + ++it; + } + if (!drawnUnmerged && count > 0) + drawPatchRange(t, static_cast(count / 3), s_vertexCount, + static_cast(start)); + } + } + else + { + while (it != end) + { + TerrainCullerNode* const node = *it; + if (node->patch != this) + break; + const unsigned int* const table = reinterpret_cast(node->lodTable); + const int count = static_cast(table[16 * (lod + 3)]); + drawPatchRange(t, static_cast(count / 3), s_vertexCount, table[16 * lod]); + ++it; + } + } + dx9rend::QueueProfiler::end(); +} + +// PE 0x1018D5D0, "TerrainMakeDynamicLightMap": when the light manager's shadow updates are enabled and +// the patch has a lightmap, binds the scale/translate and base-UV constants and the vertex stream, +// then for each of the three LODs draws the gathered shadow ranges of this patch whose node has that +// LOD and whose camera distance does not exceed the undergrowth system's view distance, with the +// light view-projection of the range's shadow record (+0x3B8). Returns without ending the profiler +// when the guard fails, as shipped. [INFERRED] name (the profiler string); unreachable in 1.50: no code +// or data references. +void QuadPatch::drawDynamicLightMap() +{ + static unsigned int s_once = 0; // dword_10262D90 bit 1 + static unsigned int s_vertexCount = 0; // dword_10262B20 + static dx9rend::QueueProfiler profiler(std::string("TerrainMakeDynamicLightMap")); // PE 0x10262B28 + profiler.begin(); + if (!g_LightManager->getShadowUpdatesEnabled()) // slot +0x128 + return; + if (!lightmap) + return; + Terrain* const t = terrain; + float scaleTrans[4]; + scaleTrans[0] = static_cast(t->m_primaryWorldScale.x * 255.0); + scaleTrans[1] = static_cast(t->m_primaryWorldScale.z * 255.0); + scaleTrans[2] = worldXf; + scaleTrans[3] = worldZf; + param(t->m_hScaleTransXZ)->setValue(scaleTrans, 0); + param(t->m_hScaleBaseUV)->setFloat(static_cast(255.0 / static_cast(t->m_patchSize))); + dx9rend::vertexBufferBindStream(vertexBuffer, t->m_compactVertices ? 1u : 0u); + if ((s_once & 2u) == 0) + { + s_once |= 2u; + const int n = t->m_patchSize; + s_vertexCount = static_cast((n + 1) * (n + 1)); + } + const float viewDistance = static_cast(g_UndergrowthSystem)->getViewDistance(); + for (int lod = 0; lod < 3; ++lod) + { + for (unsigned int k = 0; k < t->m_shadowRanges.size(); ++k) + { + const TerrainShadowRange& record = t->m_shadowRanges[k]; + if (record.node->lod != lod || !(record.cameraDistance <= viewDistance) + || record.patchIndex != patchIndex) + continue; + param(t->m_hLightViewProj)->setValue(record.shadowRecord + 952, 0); + const unsigned int prims = record.count / 3; + drawPatchRange(t, prims, s_vertexCount, record.start); + terrainRendererStat(0x270) += prims; + } + } + dx9rend::QueueProfiler::end(); +} + // the diffuse passes. "TerrainDiffusePassLod0": per detail layer (the cached layer // first, then the rest, one hidden by +0x3C0), this patch's LOD-0 nodes through the layer's index // buffer and pass 4 / 5 (side) / 11 (envmap) / 14 (layer 6). "TerrainDiffusePassLodLower": the @@ -1771,8 +3221,8 @@ void QuadPatch::drawFinal(TerrainCullerNode**& it) } beginPatchDraw(this); TerrainCullerNode** const begin = it; - vc71::vector_layout* const list = t->m_culler->visiblePatches(); - TerrainCullerNode** const end = reinterpret_cast(list->last); + std::vector* const list = t->m_culler->visiblePatches(); + TerrainCullerNode** const end = list->data() + list->size(); currentDetailMap = -1; int previous = -2; if (!t->m_lowQualityB) @@ -1792,8 +3242,7 @@ void QuadPatch::drawFinal(TerrainCullerNode**& it) } if (t->m_hiddenDetailLayer != -1 && t->m_hiddenDetailLayer == layer) continue; - QuadPatchDetailLayer* const detailLayer = - reinterpret_cast(detailLayers.first)[layer]; + QuadPatchDetailLayer* const detailLayer = detailLayers.data()[layer]; // unchecked, as shipped if (!detailLayer) continue; it = begin; @@ -1811,7 +3260,7 @@ void QuadPatch::drawFinal(TerrainCullerNode**& it) if (!bound) { TerrainDetailTexture* const record = - reinterpret_cast(t->m_detailTextures.first)[detailLayer->detailIndex]; + t->m_detailTextures.data()[detailLayer->detailIndex]; if (t->m_currentLod != 0) t->setMorphConstants(0); dx9rend::indexBufferBind(detailLayer->indexBuffer); @@ -1826,9 +3275,10 @@ void QuadPatch::drawFinal(TerrainCullerNode**& it) currentDetailMap = map; param(t->m_hTexLayer[2])->setValue(detailMap[map], 0); } - // The real EnvMapManager now owns the borrowed texture at +64. + // The real EnvMapManager now owns the borrowed texture (retail +0x64). void* envTexture = record->planeMap ? 0 : - *reinterpret_cast(reinterpret_cast(terrainEnvMapManager()) + 0x64); + static_cast(static_cast( + terrainEnvMapManager())->m_currentTexture); if (layer == t->m_currentDetailLayer) { if (record->planeMap) @@ -1871,7 +3321,7 @@ void QuadPatch::drawFinal(TerrainCullerNode**& it) bound = true; } const unsigned int* const table = - reinterpret_cast(node->layerLodTables.first)[layer]; + reinterpret_cast(node->layerLodTables.data()[layer]); const unsigned int count = table[48]; if (!count) { @@ -2006,75 +3456,405 @@ void QuadPatch::drawShadow() { for (unsigned int k = 0; ; ++k) { - const vc71::vector_layout& ranges = t->m_shadowRanges; - if (!ranges.first || k >= static_cast((ranges.last - ranges.first) / 24)) + const std::vector& ranges = t->m_shadowRanges; + if (k >= ranges.size()) break; - const unsigned int* const record = reinterpret_cast(ranges.first + 24 * k); - const TerrainCullerNode* const node = reinterpret_cast(record[3]); - const unsigned char* const shadow = reinterpret_cast(record[2]); - if (node->lod == lod && static_cast(record[5]) == patchIndex) + const TerrainShadowRange& record = ranges[k]; + const TerrainCullerNode* const node = record.node; + const unsigned char* const shadow = record.shadowRecord; + if (node->lod == lod && record.patchIndex == patchIndex) { param(t->m_hLightViewProj)->setValue(shadow + 952, 0); param(t->m_hLightViewProjOrtho)->setValue(shadow + 760, 0); param(t->m_hTexLayer[0])->setValue(lightmap, 0); if (t->m_currentLod != lod) t->setMorphConstants(lod); - const unsigned int prims = record[1] / 3; - drawPatchRange(t, prims, s_vertexCount, record[0]); + const unsigned int prims = record.count / 3; + drawPatchRange(t, prims, s_vertexCount, record.start); terrainRendererStat(624) += prims; } } } } -// one call of sub_1018AC00 per dynamic-shadow record of the LightManager; answers -// whether any range was written. The record vector stays empty while no template carries flag -// 0x800 (the directional casters' test, XpLightManager.cpp ~1159), so the loop body - unread - is -// not entered today. objectManager's `castsDynamicShadow` row sets that flag on about 100 stock -// templates and is held for this reason (RW-261): with it and dynamic shadows on, this stops. +namespace { + +template bool shadowRangeLess(A a, B b) +{ +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain FILD precision and FCOM's invalid exception. + return bf2x87::less(bf2x87::wide(a), bf2x87::wide(b)); +#else + return a < b; +#endif +} + +template int shadowRangeInt(T value) +{ +#if defined(__APPLE__) + // [CHOSEN, not recovered] Masked invalid FISTP produces the integer indefinite. + return bf2x87::toIntTruncate(bf2x87::wide(value)); +#else + return static_cast(value); +#endif +} + +int shadowRangeScaleInt(float value) +{ +#if defined(__APPLE__) + // [CHOSEN, not recovered] _ftol2 leaves its low word in EAX, including overflow. + return bf2x87::lowWord(bf2x87::toInt64Truncate(bf2x87::wide(value))); +#else + return static_cast(static_cast(value)); +#endif +} + +// PE 0x10030C60/0x10030C80. Equal and unordered arguments select different sides. +float shadowRangeMin(float a, float b) { return shadowRangeLess(a, b) ? a : b; } +float shadowRangeMax(float a, float b) { return shadowRangeLess(a, b) ? b : a; } + +} // anonymous namespace + +// PE 0x1018AC00. +void QuadPatch::gatherShadowRecord(unsigned short* indices, int* cursor, LightShadowRecord* shadow, + std::vector& ranges, float extrusionScale, + unsigned char* any) +{ + const unsigned int capacity = terrain->m_indexBufferCount; + const float scaleX = terrain->m_primaryWorldScale.x; + const float scaleZ = terrain->m_primaryWorldScale.z; + if (shadow->flags448[0]) + return; + + Frustum frustum(shadow->frustum); +#if defined(__APPLE__) + // [CHOSEN, not recovered] The argument is explicitly stored before setFarDist. + rendmath::frustumSetFarDist(frustum, bf2x87::store(bf2x87::mul( + bf2x87::wide(frustum.getFarDist()), bf2x87::wide(extrusionScale)))); +#else + rendmath::frustumSetFarDist(frustum, frustum.getFarDist() * extrusionScale); +#endif + float minX = FLT_MAX, maxX = -FLT_MAX, minZ = FLT_MAX, maxZ = -FLT_MAX; + for (int i = 0; i < 8; ++i) + { + const Vec3& corner = frustum.m_corners[i]; + if (shadowRangeLess(corner.x, minX)) minX = corner.x; + if (!shadowRangeLess(corner.x, maxX)) maxX = corner.x; + if (shadowRangeLess(corner.z, minZ)) minZ = corner.z; + if (!shadowRangeLess(corner.z, maxZ)) maxZ = corner.z; + } + if (!shadowRangeLess(minX, scaledXEnd) || !shadowRangeLess(scaledX, maxX) || + !shadowRangeLess(minZ, scaledZEnd) || !shadowRangeLess(scaledZ, maxZ)) + return; + + for (int lod = 0; lod < 3; ++lod) + { + std::vector& nodes = *terrain->m_culler->visiblePatches(); + for (std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it) + { + TerrainCullerNode* const node = *it; + if (node->patch != this || node->lod != lod || + !shadowRangeLess(minX, node->bounds.max.x) || + !shadowRangeLess(node->bounds.min.x, maxX) || + !shadowRangeLess(minZ, node->bounds.max.z) || + !shadowRangeLess(node->bounds.min.z, maxZ)) + continue; + + int x0 = shadowRangeInt(std::floor(static_cast( + shadowRangeMax(minX, node->bounds.min.x)))) - scaledX; + int x1 = shadowRangeInt(std::ceil(static_cast( + shadowRangeMin(maxX, node->bounds.max.x)))) - scaledX; + int z0 = shadowRangeInt(std::floor(static_cast( + shadowRangeMax(minZ, node->bounds.min.z)))) - scaledZ; + int z1 = shadowRangeInt(std::ceil(static_cast( + shadowRangeMin(maxZ, node->bounds.max.z)))) - scaledZ; + const int alignment = 2 << lod; + x0 -= std::abs(x0 % alignment); + const int xRemainder = std::abs(x1 % alignment); + if (xRemainder) x1 += alignment - xRemainder; + z0 -= std::abs(z0 % alignment); + const int zRemainder = std::abs(z1 % alignment); + if (zRemainder) z1 += alignment - zRemainder; + const int divisorX = shadowRangeScaleInt(scaleX); + x0 /= divisorX; + x1 /= divisorX; + const int divisorZ = shadowRangeScaleInt(scaleZ); + z0 /= divisorZ; + z1 /= divisorZ; + const int stride = terrain->m_patchSize + 1; + if (!indices) + terrain->lockDynamicIndexBuffer(); + // Shipped defect: locking updates Terrain's pointer, but never refreshes indices. + if (any) + *any = 1; + const int start = *cursor; + const int step = 1 << lod; + int edgeX0 = 0, edgeZ0 = 0, edgeX1 = 0, edgeZ1 = 0; + const bool cracked = node->crackMask != 0; + if (cracked) + { + edgeX0 = (shadowRangeInt(node->bounds.min.x) - scaledX) / divisorX; + edgeZ0 = (shadowRangeInt(node->bounds.min.z) - scaledZ) / divisorZ; + edgeX1 = (shadowRangeInt(node->bounds.max.x) - scaledX) / divisorX - step; + edgeZ1 = (shadowRangeInt(node->bounds.max.z) - scaledZ) / divisorZ - step; + } + + const auto vertex = [stride](int x, int z) -> unsigned short { + return static_cast(static_cast(stride) * + static_cast(z) + static_cast(x)); + }; + const auto triangle = [indices, cursor](unsigned short a, unsigned short b, + unsigned short c) { + indices[*cursor] = a; ++*cursor; + indices[*cursor] = b; ++*cursor; + indices[*cursor] = c; ++*cursor; + }; + for (int z = z0; z < z1; z += step) + { + for (int x = x0; x < x1; x += step) + { + if (capacity < static_cast(*cursor) + (cracked ? 12u : 6u)) + goto rangeComplete; + const int crackMask = node->crackMask; + const unsigned short a = vertex(x, z); + const unsigned short b = vertex(x + step, z); + const unsigned short c = vertex(x, z + step); + const unsigned short d = vertex(x + step, z + step); + const unsigned short e = vertex(x + step / 2, z); + const unsigned short f = vertex(x, z + step / 2); + const unsigned short g = vertex(x + step, z + step / 2); + const unsigned short h = vertex(x + step / 2, z + step); + if (!cracked) + { + triangle(a, b, c); triangle(c, b, d); + } + else if (z == edgeZ0 && x == edgeX0 && (crackMask & 5) == 5) + { + triangle(a, e, f); triangle(e, b, c); + triangle(f, e, c); triangle(c, b, d); + } + else if (z == edgeZ0 && x == edgeX1 && (crackMask & 9) == 9) + { + triangle(a, e, c); triangle(e, b, c); + triangle(c, b, g); triangle(c, g, d); + } + else if (z == edgeZ1 && x == edgeX0 && (crackMask & 6) == 6) + { + triangle(a, b, f); triangle(f, b, c); + triangle(c, b, h); triangle(h, b, d); + } + else if (z == edgeZ1 && x == edgeX1 && (crackMask & 10) == 10) + { + triangle(a, b, c); triangle(h, g, d); + triangle(c, b, h); triangle(h, b, g); + } + else if (z == edgeZ0 && (crackMask & 1)) + { + triangle(a, e, c); triangle(e, b, c); triangle(c, b, d); + } + else if (z == edgeZ1 && (crackMask & 2)) + { + triangle(a, b, c); triangle(c, b, h); triangle(h, b, d); + } + else if (x == edgeX0 && (crackMask & 4)) + { + triangle(a, b, f); triangle(f, b, c); triangle(c, b, d); + } + else if (x == edgeX1 && (crackMask & 8)) + { + triangle(a, b, c); triangle(c, b, g); triangle(c, g, d); + } + else + { + triangle(a, b, c); triangle(c, b, d); + } + } + } +rangeComplete: + TerrainShadowRange range; + range.start = static_cast(start); + range.count = static_cast(*cursor - start); + range.shadowRecord = reinterpret_cast(shadow); + range.node = node; + const Mat4* const camera = dx9rend::rendererGetRenderViewDup()->getViewMatrixPtr(); +#if defined(__APPLE__) + // [CHOSEN, not recovered] Keep both distances through FSQRT until the record store. + bf2x87::Real dx = bf2x87::wide(0.0f), dz = bf2x87::wide(0.0f); + if (shadowRangeLess(camera->m[12], minX)) + dx = bf2x87::sub(bf2x87::wide(minX), bf2x87::wide(camera->m[12])); + else if (shadowRangeLess(maxX, camera->m[12])) + dx = bf2x87::sub(bf2x87::wide(camera->m[12]), bf2x87::wide(maxX)); + if (shadowRangeLess(camera->m[14], minZ)) + dz = bf2x87::sub(bf2x87::wide(minZ), bf2x87::wide(camera->m[14])); + else if (shadowRangeLess(maxZ, camera->m[14])) + dz = bf2x87::sub(bf2x87::wide(camera->m[14]), bf2x87::wide(maxZ)); + range.cameraDistance = bf2x87::store(bf2x87::squareRoot(bf2x87::add( + bf2x87::mul(dx, dx), bf2x87::mul(dz, dz)))); +#else + float dx = 0.0f, dz = 0.0f; + if (camera->m[12] < minX) dx = minX - camera->m[12]; + else if (camera->m[12] > maxX) dx = camera->m[12] - maxX; + if (camera->m[14] < minZ) dz = minZ - camera->m[14]; + else if (camera->m[14] > maxZ) dz = camera->m[14] - maxZ; + range.cameraDistance = std::sqrt(dx * dx + dz * dz); +#endif + range.patchIndex = patchIndex; + ranges.push_back(range); + } + } +} + +// PE 0x1018BAE0. Refresh the vector's current begin/end for every record. bool QuadPatch::gatherShadowRanges(void** lockedIndices, int* cursor) { unsigned char any = 0; - const vc71::vector_layout& records = terrainShadowRecords(); + std::vector& records = terrainShadowRecords(); for (unsigned int i = 0; ; ++i) { - if (!records.first || i >= static_cast((records.last - records.first) / 1176)) + if (i >= records.size()) break; - (void)lockedIndices; - (void)cursor; - RD9_FRONTIER("dice::hfe::geom::QuadPatch::gatherShadowRanges (sub_1018AC00 - the shadow " - "record vs patch range gather into Terrain +0x36C; unread, 3.8 KB)", 0x00); + gatherShadowRecord(static_cast(*lockedIndices), cursor, &records[i], + terrain->m_shadowRanges, terrain->m_shadowExtrusionScale, &any); } return any != 0; } -// the Ra water submit: an RaQuadPatchAdapter over this patch's streams, a lighting -// block with this patch's lightmap, the sky light into the light record, the cell's transform, -// then one pooled submit per merged LOD range into RSMTWater through the adapter server -// (dword_1026743C: sub_101BBE20 binds the settings, sub_101BBEB0 takes a pooled adapter and -// queues the entry). All of it is read; none of it is written, because no shipped shader defines -// the "ShaderVersion" that selects this arm (see TerrainDraw.cpp) - it stops at the adapter. -void QuadPatch::drawWater(TerrainCullerNode**& it, vc71::vector_layout* list, +// PE 0x1018D800. Builds the patch's water streams, lightmap, lighting record and transform. +void QuadPatch::drawWater(TerrainCullerNode**& it, std::vector* list, void* materialParameters, void* objectParameters) { static unsigned int s_once = 0; // dword_1026326C static unsigned int s_vertexCount = 0; // dword_10263268 - (void)materialParameters; - (void)objectParameters; if ((s_once & 1u) == 0) { const int n = terrain->m_patchSize; s_once |= 1u; s_vertexCount = static_cast((n + 1) * (n + 1)); } - RD9_FRONTIER("dice::hfe::geom::QuadPatch::drawWater (sub_1018D800 - the RaQuadPatchAdapter " - "(sub_101BBCB0) and its pooled server dword_1026743C (sub_101BBE20 / sub_101BBEB0 / " - "sub_101BC7C0), read but unwritten; reachable only when a water RaShader defines " - "ShaderVersion == 1)", 0x00); - // Continue mode only: skip this patch's entries so the caller's loop can end. Not recovered. - TerrainCullerNode** const end = reinterpret_cast(list->last); - while (it != end && (*it)->patch == this) - ++it; + RaQuadPatchAdapter adapter(terrain->m_compactVertices ? terrain->m_baseGridVertexBuffer : 0, + vertexBuffer, terrain->m_lodIndexBuffer, terrain->m_vertexDeclaration); + dx9rend::Ra::RaLightingParameters lighting; + lighting.lightMapOffset.value[0] = 1.0f; + lighting.lightMapOffset.value[1] = 1.0f; + lighting.lightMapOffset.value[2] = 0.0f; + lighting.lightMapOffset.value[3] = 0.0f; + IUnknown* const lightTexture = static_cast(lightmap)->baseTexture; + IUnknown*& storedTexture = *reinterpret_cast(&lighting.lightMap.value); + if (storedTexture != lightTexture) + { + if (storedTexture) + storedTexture->Release(); + storedTexture = lightTexture; + if (lightTexture) + lightTexture->AddRef(); + } + if (world::LightSource* const sky = g_LightManager->getSkyLight()) + { + const float* direction = terrainSkyLightDirection(sky); + lightRecord[4] = direction[1]; + lightRecord[3] = direction[0]; + lightRecord[5] = direction[2]; + const float* color = terrainSkyLightColor(sky); + lightRecord[6] = color[0]; + lightRecord[7] = color[1]; + lightRecord[8] = color[2]; + } + RaMaterialParameters& material = *static_cast(materialParameters); +#if defined(__APPLE__) + const bf2x87::Real unpackX = bf2x87::mul( + bf2x87::wide(terrain->m_primaryWorldScale.x), bf2x87::wide(255.0f)); + const bf2x87::Real unpackZ = bf2x87::mul( + bf2x87::wide(terrain->m_primaryWorldScale.z), bf2x87::wide(255.0f)); + material.posUnpack.value[2] = 0.0f; + material.posUnpack.value[0] = bf2x87::store(unpackX); + material.posUnpack.value[3] = 0.0f; + material.posUnpack.value[1] = bf2x87::store(unpackZ); +#else + material.posUnpack.value[2] = 0.0f; + material.posUnpack.value[0] = terrain->m_primaryWorldScale.x * 255.0f; + material.posUnpack.value[3] = 0.0f; + material.posUnpack.value[1] = terrain->m_primaryWorldScale.z * 255.0f; +#endif + material.normalUnpack.value[0] = terrain->m_primaryWorldScale.y; + material.normalUnpack.value[1] = 1.0f; +#if defined(__APPLE__) + material.texUnpack.value = bf2x87::store(bf2x87::div( + bf2x87::wide(255.0f), bf2x87::wide(terrain->m_patchSize))); +#else + material.texUnpack.value = 255.0f / terrain->m_patchSize; +#endif + dx9rend::Ra::RaObjectParameters& object = *static_cast(objectParameters); + for (int i = 0; i != 16; ++i) + object.world.value[i] = i % 5 == 0 ? 1.0f : 0.0f; + object.world.value[12] += worldXf; + object.world.value[14] += worldZf; + RaQuadPatchQueue* target = static_cast( + static_cast(dx9rend::g_renderQueues)->slots[9]); + raQuadPatchAdapterCheckWaterQueue(target); + // The queue is read again after the assertion, as in PE 0x1018DA09. + target = static_cast( + static_cast(dx9rend::g_renderQueues)->slots[9]); + raQuadPatchAdapterSetSettings(target, adapter, &material, &object, lighting, + *reinterpret_cast(lightRecord)); + if (terrain->m_mergeDrawRanges) + { + static dx9rend::QueueProfiler profiler(std::string("Water2")); // PE 0x10263000, guard bit 2 + profiler.begin(); + while (it != list->data() + list->size()) + { + TerrainCullerNode* const node = *it; + if (node->patch != this) + break; + unsigned int start = lodStart(node); + unsigned int count = lodCount(node); + ++it; + bool flushed = false; + while (it != list->data() + list->size()) + { + TerrainCullerNode* const next = *it; + if (next->patch != this) + break; + const unsigned int nextStart = lodStart(next); + const unsigned int nextCount = lodCount(next); + if (node->lod != next->lod || start + count != nextStart) + { + if (node->lod != next->lod || nextStart + nextCount != start) + { + // Shipped behavior: a discontinuity submits even a nonpositive count. + raQuadPatchAdapterSubmit(static_cast(count) / 3, s_vertexCount, + terrain->m_primitiveType, 0, 0, start); + flushed = true; + break; + } + start -= nextCount; + } + count += nextCount; + ++it; + } + if (!flushed && static_cast(count) > 0) + raQuadPatchAdapterSubmit(static_cast(count) / 3, s_vertexCount, + terrain->m_primitiveType, 0, 0, start); + } + dx9rend::QueueProfiler::end(); + } + else + { + static dx9rend::QueueProfiler profiler(std::string("Water2")); // PE 0x10262D98, guard bit 4 + profiler.begin(); + while (it != list->data() + list->size()) + { + TerrainCullerNode* const node = *it; + if (node->patch != this) + break; + const int primitives = static_cast(lodCount(node)) / 3; + const unsigned int start = lodStart(node); + raQuadPatchAdapterSubmit(primitives, s_vertexCount, terrain->m_primitiveType, 0, 0, start); + ++terrainRendererStat(0x268); + terrainRendererStat(0x26C) += primitives; + ++it; + } + dx9rend::QueueProfiler::end(); + } } } // namespace geom diff --git a/Code/BF2/Geom/QuadPatch.h b/Code/BF2/Geom/QuadPatch.h index 422c680b6..84a21f34a 100644 --- a/Code/BF2/Geom/QuadPatch.h +++ b/Code/BF2/Geom/QuadPatch.h @@ -6,8 +6,8 @@ #define GEOM_QUADPATCH_H #include +#include #include "../Math/Vec3.h" -#include "../../RendDX9Abi/Vc71Vector.h" namespace dice { namespace hfe { @@ -20,6 +20,8 @@ namespace geom { class Terrain; class TerrainRawReader; struct TerrainCullerNode; +struct TerrainShadowRange; +struct LightShadowRecord; // sub_101C6750 - the eight corners of an axis-aligned box from its (min, max) pair, in the shipped // order: x fixed at min for the first four (z, y, z), then at max. @@ -68,6 +70,8 @@ struct QuadPatchDetailLayer explicit QuadPatchDetailLayer(Terrain* owner); int load(TerrainRawReader& reader); ~QuadPatchDetailLayer(); + // Partitions legacy triangle indices into recursively allocated child LOD records. + void buildLodTableTree(unsigned char* table, int quadrant, int size, int x, int z); // sub_101BB6B0 (thiscall, recursive; `this` is only passed on) - the destructor's pre-0x18 arm: // the four children's subtrees when the first link (+0x180) is set, then the record. void freeLodTableTree(unsigned char* table); @@ -96,42 +100,62 @@ class QuadPatch explicit QuadPatch(Terrain* owner); virtual ~QuadPatch(); // slot 0: 0x1018E520 -> body sub_1018A220 void load(TerrainRawReader& reader); + // Drops detail resources in low quality; otherwise reloads them from the saved file offset. + void reloadDetailLayers(TerrainRawReader& reader); void loadDetailLayers(TerrainRawReader& reader); void loadDetailMaps(); + // Preloads the three base textures and primary vertex buffer, then stamps this frame. + void preloadResources(); // the per-frame bodies. Each takes the visible-list iterator by reference and // consumes every entry that belongs to this patch. void draw(TerrainCullerNode**& it); // 0x1018BE20 the Hi_/Low_Terrain pass-0 draw (accumulation target) void drawFinal(TerrainCullerNode**& it); // 0x1018C910 the diffuse detail passes (LOD 0 per layer, then the lower LODs) void drawShadow(); // 0x1018DD00 pass 7: this patch's gathered shadow ranges - bool gatherShadowRanges(void** lockedIndices, int* cursor); // 0x1018BAE0 per shadow record -> sub_1018AC00 [UNREAD, stops] - void drawWater(TerrainCullerNode**& it, vc71::vector_layout* list, + bool gatherShadowRanges(void** lockedIndices, int* cursor); // 0x1018BAE0 + // Appends this record's visible patch ranges and their cracked-grid indices. [INFERRED] name. + void gatherShadowRecord(unsigned short* indices, int* cursor, LightShadowRecord* shadow, + std::vector& ranges, float extrusionScale, + unsigned char* any); + void drawWater(TerrainCullerNode**& it, std::vector* list, void* materialParameters, void* objectParameters); // 0x1018D800 the Ra water submit - see the body // the light passes' draws over the culler's gathered list - void drawGatheredNodes(TerrainCullerNode**& it, vc71::vector_layout* list, + void drawGatheredNodes(TerrainCullerNode**& it, std::vector* list, int passLod0, int passOther); // 0x10189210 per node: its pass, the morph constants, one uncracked range void drawPointLight(TerrainCullerNode**& it); // 0x1018C7F0 "TerrainPointLight": drawGatheredNodes, pass 13 / 1 + void drawOccluderShadows(TerrainCullerNode**& it); // 0x1018BB70 [INFERRED] name; "TerrainOccluderShadows", unreachable in 1.50 + void drawDynamicLightMap(); // 0x1018D5D0 [INFERRED] name; "TerrainMakeDynamicLightMap", unreachable in 1.50 + void drawSpotLight(TerrainCullerNode**& it); // 0x1018C880 + void drawShadowBatch(TerrainCullerNode**& it, std::vector* visible, + const std::vector& ranges); // 0x10189720 + bool intersectsLightSphere(const Vec3& position, float radius) const; // 0x10188B80 + // Draws this patch's uncracked LOD ranges for the selected terrain technique pass. + void drawTechniquePass(TerrainCullerNode**& it, std::vector* list); + // Emits the shipped obsolete-depth-draw error; the iterator and pass are unused. + void drawDepthComplexity(TerrainCullerNode**& it, int pass); // three QuadPatch.cpp bodies only the dormant editable terrain calls - // TerrainEditable::update (0x1010C630) culls and sorts its patches with the first two + // TerrainEditable::update culls and sorts its patches with the first two // (0x1010C733 / 0x1010C740); QuadPatchEditable's VB rebuild (0x1019DF30) runs the third // (0x1019E150). The loaded game path never reaches them. [INFERRED] names. bool isVisible(const Frustum* frustum); // 0x10188660 29 B the sphere (+0xA0, +0xAC) against the frustum float getSquaredDistance(const Vec3& position); // 0x10188BE0 47 B |position - center|^2 + float getCameraDistance(); // 0x10188C10 [INFERRED] name; camera distance to the centre, cached per frame void buildNormalVertexBuffer(); // 0x10188680 1271 B per-vertex normals from the heightmap into +0x5C Terrain* terrain; // +0x004 - vc71::vector_layout detailLayers; // +0x008 QuadPatchDetailLayer* per detail texture (+1 slots, null-filled; first at +0x0C) + std::vector detailLayers; // +0x008 one per detail texture (+1 slots, null-filled) Vec3 center; // +0x018 patch origin + half a patch (load) // Owned vertex buffers; editable patches populate height and normal streams. // Loaded game patches leave these three optional buffers null. void* vertexBuffer24; // +0x024 0 int unresolved28; // +0x028 0 - void* legacyVertexTable; // +0x02C the pre-0x18 packed xz table - int unresolved30[2]; // +0x030 not touched + void* legacyVertexTable; // +0x02C pre-0x18 float heights; released after culler construction + float cachedCameraDistance; // +0x030 getCameraDistance's cache; the constructor does not touch it; [INFERRED] name + unsigned int cachedDistanceFrame; // +0x034 the frame ordinal that cache was computed in; not touched by the constructor; [INFERRED] name unsigned int lastDrawnFrame; // +0x038 0; drawFinal stamps the renderer's frame ordinal - int unresolved3C; // +0x03C 0 + unsigned int lastPreloadedFrame; // +0x03C 0; preloadResources stamps the renderer frame void* detailMap[2]; // +0x040 "%02ix%02i_1" / "_2" void* lowDetailmap; // +0x048 "%02ix%02i" (when the .dds exists; mip class 4) void* colormap; // +0x04C "%02ix%02i" (mip class 2) @@ -189,12 +213,16 @@ class SurroundingPatch virtual ~SurroundingPatch(); // slot 0: 0x1018F870 -> body sub_1018E910 void load(int slot, TerrainRawReader& reader); void setupPlacement(); + float getCameraDistance(); // 0x1018F390 [INFERRED] name; camera distance to the centre, cached per frame + float getSquaredDistance(const Vec3& position); // 0x1018F360 [INFERRED] name; |position - center|^2 (+0x4C) + bool isVisibleInFrustum(const Frustum* frustum); // 0x1018E550 [INFERRED] name; the bounds sphere (+0x70, +0x7C) against the frustum bool isVisible(int unused); // 0x1018F420 camera inside, far-plane reject, then the slot's edge tests void draw(int unused); // 0x1018F7B0 textures, sttransxz, the two streams, pass 0, one draw Terrain* terrain; // +0x004 void* xzBytes; // +0x008 file: 4 x vertexCount bytes (packed xz per vertex) - int unresolved0C[2]; // +0x00C not touched + float cachedCameraDistance; // +0x00C getCameraDistance's cache; [INFERRED] name + unsigned int cachedDistanceFrame; // +0x010 the frame ordinal that cache was computed in; [INFERRED] name void* lowDetailmap; // +0x014 "_s%i" void* colormap; // +0x018 "_s%i" void* xzVertexBuffer; // +0x01C "SurroundingPatch", vertexCount x 4 B @@ -239,7 +267,7 @@ struct TerrainCullerNode QuadPatch* patch; // +0x000 patches[fileByte] or null (0xFF) unsigned char* lodTable; // +0x004 the terrain's LOD table (leaf) or the parent's child table (load) - vc71::vector_layout layerLodTables; // +0x008 per detail layer of `patch`: the layer's LOD table (leaf) or the parent's child table (first at +0x0C) + std::vector layerLodTables; // +0x008 per detail layer of `patch`: the layer's LOD table (leaf) or the parent's child table // +0x018: a dx9rend Query (QueryManager.cpp) - proven by the pre-0x18 node builder // sub_100E4690, which stores QueryManager::createQuery's answer here (0x100E4E9E..0x100E4EA3), // and by the destructor, which releases it through the Query's inline --ref dance around its @@ -263,9 +291,10 @@ struct TerrainCullerNode unsigned char cameraInside; // +0x0FC 0; the camera's xz lies inside the bounds unsigned char padFD[3]; int crackMask; // +0x100 0; the crack fixup's neighbour bits (1, 2, 4, 8) that pick the LOD table column - int unresolved104; // +0x104 -1 - int unresolved108; // +0x108 not touched - int unresolved10C; // +0x10C 0 + // Legacy grid metadata; names are [INFERRED]. + int legacyGridIndex; // +0x104 constructor -1; the legacy root is 0 + int legacyLevel; // +0x108 legacy root 1; constructor leaves uninitialized + TerrainCullerNode* legacyParent; // +0x10C borrowed parent; constructor 0 }; class TerrainCuller @@ -281,19 +310,50 @@ class TerrainCuller void deleteNodeTree(TerrainCullerNode* node); void load(TerrainRawReader& reader); void loadNode(TerrainRawReader& reader, TerrainCullerNode* node); - vc71::vector_layout* visiblePatches() { return &visible; } - vc71::vector_layout* gatheredPatches() { return &gathered; } + // Builds the per-node quadtree used by terrain files predating version 0x18. + void buildLegacyTree(); + void buildLegacyChild(TerrainCullerNode* parent, int quadrant, int unused); + // Requires legacy node-level metadata; assigns the flattened grid indices in place. + void assignLegacyGridIndices(TerrainCullerNode* node, int x, int z); + TerrainCullerNode* findLegacyNode(int index, TerrainCullerNode* node); + // Populates the eight neighbour links after the legacy indices have been assigned. + void linkLegacyNeighbours(TerrainCullerNode* node); + // Rebuilds per-layer LOD references after patch detail layers have been reloaded. + void reloadDetailLayers(); + std::vector* visiblePatches() { return &visible; } // PE 0x100E2ED0 + std::vector* gatheredPatches() { return &gathered; } // the per-frame bodies void update(); // 0x100E7080 slot +0x28 of Terrain calls it: LOD distance, the walk, the crack fixup - void walkRoot(TerrainCullerNode* node); // 0x100E6D50 the root's sphere/corner tests, then the mode dispatch + // Tests the root and dispatches the selected walk. Returns the shipped constant one. + int walkRoot(TerrainCullerNode* node); + // Visits accepted children by increasing stored camera distance. + void walkMode1(TerrainCullerNode* parent); + // Visits candidates in array order, retaining the three-child fallback quirk. + void walkMode2(TerrainCullerNode* parent); void walkMode3(TerrainCullerNode* parent); // 0x100E59A0 mode 3 (the shipped default): per child - tests, LOD, push or descend + // Defers complete child groups so a patch-level parent can replace them in the visible list. + int walkMode4(TerrainCullerNode* parent); + // Traverses children in array order without the camera-inside shortcut. + void walkMode5(TerrainCullerNode* parent); + // Returns the node's final visibility after visiting its children and selecting leaf LODs. + int walkMode6(TerrainCullerNode* node); static void setLod(TerrainCullerNode* node, int lod); // 0x100E2D00 the node and its visible children; 3+ clamps to 2 void fixCracks(); // 0x100E34E0 the neighbour-LOD mask per visible node + // Removes recently occluded nodes; the native renderer age-limit read remains a frontier. + void filterOccluded(); void gatherSphere(const float* centre, float radius); // 0x100E6D10 every node with a patch within `radius` into `gathered` void gatherNode(TerrainCullerNode* node); // 0x100E45B0 its recursive walk void gatherVisibleSphere(const float* centre, float radius); // 0x100E6C70 the light passes' variant: the visible leaves within `radius` into `gathered` void gatherVisibleNode(TerrainCullerNode* node); // 0x100E4370 its recursive walk + // Replaces the gather list using visible leaves and retains the supplied frustum as the culler's current one. + void gatherVisibleFrustum(Frustum* source); + void gatherVisibleFrustumNode(TerrainCullerNode* node); + // Unreachable in 1.50 ([INFERRED] names, see QuadPatch.cpp): the shadow-caster variant of + // gatherVisibleFrustum. `fitNearPlane`, when set, is pulled back over each gathered node's box; + // `unused` is only passed down the recursion. + void gatherShadowFrustum(Frustum* source, Frustum* fitNearPlane, int unused); + void gatherShadowFrustumNode(TerrainCullerNode* node, Frustum* fitNearPlane, int unused); int lodDistance; // +0x000 not touched by the constructor; update: the current LOD distance Terrain* terrain; // +0x004 @@ -308,15 +368,15 @@ class TerrainCuller float lodFactor28; // +0x028 2.0f float lodFactor2C; // +0x02C 2.7f float lodFactor30; // +0x030 3.0f - LOD 2 beyond lodDistance * this - vc71::vector_layout visible; // +0x034 the visible node list the draws walk (first at +0x38) - vc71::vector_layout gathered; // +0x044 the sphere gathers' node list (first at +0x48) + std::vector visible; // +0x034 the visible node list the draws walk + std::vector gathered; // +0x044 the sphere gathers' node list Frustum* frustum; // +0x054 update: the render view's frustum const float* cameraPosition; // +0x058 update: row 3 of the render view's +0x64 matrix const float* gatherCentre; // +0x05C gatherSphere's centre float gatherRadius; // +0x060 float gatherRadiusSq; // +0x064 int param68; // +0x068 2 - int param6C; // +0x06C 3 - the walk mode (1..6); only 3 is written + int param6C; // +0x06C 3 - the walk mode (1..6) unsigned char flag70; // +0x070 1 - run the crack fixup unsigned char flag71; // +0x071 1 - test the camera against the root's box unsigned char pad72[2]; @@ -331,22 +391,8 @@ static_assert(offsetof(TerrainAabb, dirty) == 0x20, "box dirty byte at +0x20"); static_assert(offsetof(TerrainAabb, centre) == 0x30, "box centre at +0x30"); static_assert(sizeof(QuadPatchDetailLayer) == 0x3C, "detail layer is 0x3C bytes - see 0x1018A3A0"); static_assert(offsetof(QuadPatchDetailLayer, terrain) == 0x34, "detail layer terrain at +0x34"); -static_assert(sizeof(QuadPatch) == 0x120, "QuadPatch is 0x120 bytes - see 0x100D8B20"); static_assert(offsetof(QuadPatch, terrain) == 0x04, "QuadPatch terrain at +0x04 - one vptr ahead of it"); static_assert(offsetof(QuadPatch, detailLayers) == 0x08, "QuadPatch detail layer vector at +0x08"); -static_assert(offsetof(QuadPatch, lastDrawnFrame) == 0x38, "QuadPatch frame stamp at +0x38"); -static_assert(offsetof(QuadPatch, vertexBuffer) == 0x60, "QuadPatch vertex buffer at +0x60"); -static_assert(offsetof(QuadPatch, worldXf) == 0x88, "QuadPatch world position at +0x88"); -static_assert(offsetof(QuadPatch, heightVertexBuffer) == 0x54, "QuadPatch height VB at +0x54 - see 0x1019DFDC"); -static_assert(offsetof(QuadPatch, normalVertexBuffer) == 0x5C, "QuadPatch normal VB at +0x5C - see 0x1018868E"); -static_assert(offsetof(QuadPatch, maxHeight) == 0x98, "QuadPatch max height at +0x98 - see 0x100D894F"); -static_assert(offsetof(QuadPatch, minHeight) == 0x9C, "QuadPatch min height at +0x9C - see 0x100D892F"); -static_assert(offsetof(QuadPatch, sphereCentre) == 0xA0, "QuadPatch sphere centre at +0xA0 - see 0x10188669"); -static_assert(offsetof(QuadPatch, sphereRadius) == 0xAC, "QuadPatch sphere radius at +0xAC - see 0x10188663"); -static_assert(offsetof(QuadPatch, currentDetailMap) == 0xC4, "QuadPatch detail-map cache at +0xC4"); -static_assert(offsetof(QuadPatch, lightRecord) == 0xC8, "QuadPatch light record at +0xC8"); -static_assert(offsetof(QuadPatch, hasNoDetailLayers) == 0x10C, "QuadPatch no-detail flag at +0x10C"); -static_assert(offsetof(QuadPatch, maxDetailLayerIndex) == 0x11C, "QuadPatch max layer at +0x11C"); static_assert(sizeof(SurroundingPatch) == 0x168, "SurroundingPatch is 0x168 bytes - see 0x100D8BA0"); static_assert(offsetof(SurroundingPatch, terrain) == 0x04, "SurroundingPatch terrain at +0x04"); static_assert(offsetof(SurroundingPatch, originXf) == 0x58, "SurroundingPatch origin vector at +0x58"); @@ -354,20 +400,15 @@ static_assert(offsetof(SurroundingPatch, slot) == 0x84, "SurroundingPatch slot a static_assert(offsetof(SurroundingPatch, placement) == 0x8C, "SurroundingPatch transform at +0x8C"); static_assert(offsetof(SurroundingPatch, bounds) == 0xCC, "SurroundingPatch bounds at +0xCC"); static_assert(offsetof(SurroundingPatch, corners) == 0x108, "SurroundingPatch corners at +0x108"); -static_assert(sizeof(TerrainCullerNode) == 272, "culler node is 272 bytes - see 0x100E3FF0"); static_assert(offsetof(TerrainCullerNode, layerLodTables) == 0x08, "node layer tables at +0x08"); -static_assert(offsetof(TerrainCullerNode, child) == 0x1C, "node children at +0x1C"); -static_assert(offsetof(TerrainCullerNode, bounds) == 0x50, "node bounds at +0x50"); -static_assert(offsetof(TerrainCullerNode, corners) == 0x8C, "node corners at +0x8C"); -static_assert(offsetof(TerrainCullerNode, fileByteEC) == 0xEC, "node file bytes at +0xEC"); -static_assert(offsetof(TerrainCullerNode, childrenWalked) == 0xF0, "node walked count at +0xF0"); -static_assert(offsetof(TerrainCullerNode, lod) == 0xF8, "node lod at +0xF8"); -static_assert(offsetof(TerrainCullerNode, crackMask) == 0x100, "node crack mask at +0x100"); -static_assert(sizeof(TerrainCuller) == 0x7C, "culler is 0x7C bytes - see 0x100D7920"); +// The node's +0x08 vector is 0x10 bytes only in the image's VC7.1 STL; a current MSVC x86 build +// checks the STL-free span from +0x18 instead. +#if defined(_MSC_VER) && _MSC_VER == 1310 +static_assert(offsetof(TerrainCullerNode, legacyParent) == 0x10C, "legacy parent at +0x10C"); +#endif +static_assert(offsetof(TerrainCullerNode, legacyParent) - offsetof(TerrainCullerNode, occlusionQuery) == 0x10C - 0x18, + "legacy parent 0xF4 past +0x18 - see 0x100E47E5"); static_assert(offsetof(TerrainCuller, visible) == 0x34, "visible list at +0x34"); -static_assert(offsetof(TerrainCuller, gathered) == 0x44, "gathered list at +0x44"); -static_assert(offsetof(TerrainCuller, frustum) == 0x54, "frustum at +0x54"); -static_assert(offsetof(TerrainCuller, nodeCount) == 0x74, "node count at +0x74"); #endif } // namespace geom diff --git a/Code/BF2/Geom/QuadPatchEditable.cpp b/Code/BF2/Geom/QuadPatchEditable.cpp index ea85787ed..a9422b589 100644 --- a/Code/BF2/Geom/QuadPatchEditable.cpp +++ b/Code/BF2/Geom/QuadPatchEditable.cpp @@ -3,7 +3,10 @@ #ifdef BF2_IMAGE_RENDDX9 +#include "../Platform/X87Compat.h" // [CHOSEN, not recovered] x87 conversion results, including invalid inputs. #include "QuadPatchEditable.h" +#include "../Core/StringUtil.h" // formatString (sub_10074AB0) +#include "../GeomMisc/Debug.h" #include "TerrainEditable.h" #include "Terrain.h" #include "QuadPatch.h" @@ -19,11 +22,12 @@ #include "../RendDX9/Texture.h" #include "../RendMisc/EnvMapSystem/EnvMapManager.h" #include "../../RendDX9Abi/BfMemory.h" +#include "../../RendDX9Abi/D3dx9Sdk.h" #include "../../RendDX9Abi/Frontier.h" // renddx9abi::logf - dice's debug stream #include "../../RendDX9Abi/HostFileAbi.h" #include "../../RendDX9Abi/PluginAbi.h" #include "../../RendDX9Abi/PluginEntry.h" // classManager, fileManager -#include "../../RendDX9Abi/Vc71String.h" +#include #include #include @@ -32,27 +36,6 @@ #include #include -// The D3DX entry points this TU calls - real static imports of the shipped image (d3dx9_25.dll, listed -// in Code/RendDX9Abi/D3dx9_25.def since TerrainEditable R0). The fill callback is LPD3DXFILL2D: -// (D3DXVECTOR4* out, const D3DXVECTOR2* texCoord, const D3DXVECTOR2* texelSize, void* data). -typedef void (WINAPI* TerrainEditableFill2D)(float* out, const float* texCoord, - const float* texelSize, void* data); -extern "C" HRESULT WINAPI D3DXFillTexture(IDirect3DTexture9* texture, TerrainEditableFill2D function, - void* data); -extern "C" HRESULT WINAPI D3DXComputeBoundingSphere( - const ::dice::hfe::Vec3* firstPosition, DWORD vertexCount, DWORD stride, - ::dice::hfe::Vec3* centre, float* radius); -// R2: the surface copy the edit copy, its commit and the road-mask downsample use (the declaration -// and bridge XpLightManager.cpp already carries - eight arguments, @32). -extern "C" HRESULT WINAPI D3DXLoadSurfaceFromSurface( - IDirect3DSurface9* destination, const PALETTEENTRY* destinationPalette, - const RECT* destinationRect, IDirect3DSurface9* source, - const PALETTEENTRY* sourcePalette, const RECT* sourceRect, - DWORD filter, D3DCOLOR colourKey); -#pragma comment(linker, "/alternatename:_D3DXFillTexture@12=_D3DXFillTexture") -#pragma comment(linker, "/alternatename:_D3DXComputeBoundingSphere@20=_D3DXComputeBoundingSphere") -#pragma comment(linker, "/alternatename:_D3DXLoadSurfaceFromSurface@32=_D3DXLoadSurfaceFromSurface") - namespace dice { namespace hfe { @@ -143,22 +126,6 @@ inline dx9rend::EngineTexture* engineTexture(void* texture) return static_cast(texture); } -// sub_10074AB0 - the image's printf-into-a-std::string helper: _vsnprintf into a 0xFFF-byte window, -// the shipped warning text when it does not fit (QuadPatch.cpp and StaticMesh.cpp carry the same body). -void formatString(vc71::string& out, const char* format, ...) -{ - char buffer[0x1000]; - va_list args; - va_start(args, format); - const int written = _vsnprintf(buffer, 0xFFF, format, args); - va_end(args); - if (written < 0) - std::snprintf(buffer, sizeof(buffer), "%s", - "WARNING: The original message was too long for formatString(). \n"); - else - buffer[written] = 0; - out = buffer; -} // The "lock, fill every texel of mip 0, unlock" every texture-creating body here open-codes: // textureLock(t, 0, 0x7FFFFFFF) (sub_10014BA0), width * height dwords from the record's bits, then @@ -177,7 +144,9 @@ void fillTexture(dx9rend::EngineTexture* texture, unsigned int value) // (`retn 10h`; the texel size is not read). State: QuadPatchEditable +0x128 (last u, last v, the // current cell's u / v start, the cell counters). The compares are the listing's: a coordinate below // the last one resets that axis; a step of more than 0.125 (flt_1021DD38) opens the next cell. -void WINAPI checkerboardFill(float* out, const float* texCoord, const float*, void* data) +// PE 0x1019AF10 +void WINAPI checkerboardFill(D3DXVECTOR4* out, const D3DXVECTOR2* texCoord, const D3DXVECTOR2*, + void* data) { float* const state = static_cast(data); float& lastU = state[0]; @@ -186,41 +155,41 @@ void WINAPI checkerboardFill(float* out, const float* texCoord, const float*, vo float& cellV = state[3]; int& countU = reinterpret_cast(state)[4]; int& countV = reinterpret_cast(state)[5]; - if (texCoord[0] < lastU) + if (texCoord->x < lastU) { countU = 0; cellU = 0.0f; } - if (texCoord[1] < lastV) + if (texCoord->y < lastV) { countV = 0; cellV = 0.0f; } - if (texCoord[0] - cellU > 0.125f) + if (texCoord->x - cellU > 0.125f) { countU += 1; - cellU = texCoord[0]; + cellU = texCoord->x; } - if (texCoord[1] - cellV > 0.125f) + if (texCoord->y - cellV > 0.125f) { countV += 1; - cellV = texCoord[1]; + cellV = texCoord->y; } if ((countV + countU) % 2 == 0) { - out[0] = 0.81f; - out[1] = 0.81f; - out[2] = 0.75f; + out->x = 0.81f; + out->y = 0.81f; + out->z = 0.75f; } else { - out[0] = 0.94f; - out[1] = 0.94f; - out[2] = 0.91f; + out->x = 0.94f; + out->y = 0.94f; + out->z = 0.91f; } - out[3] = 1.0f; - lastU = texCoord[0]; - lastV = texCoord[1]; + out->w = 1.0f; + lastU = texCoord->x; + lastV = texCoord->y; } } // anonymous namespace @@ -228,12 +197,14 @@ void WINAPI checkerboardFill(float* out, const float* texCoord, const float*, vo // PatchDetailLayer +// PE 0x1019AFF0 PatchDetailLayer::PatchDetailLayer() { created = 0; data = 0; } +// PE 0x1019B000 PatchDetailLayer::~PatchDetailLayer() { if (data) @@ -243,43 +214,86 @@ PatchDetailLayer::~PatchDetailLayer() } } +// PE 0x1019B020 (the standalone copy of the body PatchDetailLayers::init inlines) void PatchDetailLayer::init(QuadPatchEditable* newOwner, int newWidth) { owner = newOwner; +#if defined(__APPLE__) + // [CHOSEN, not recovered] IMUL retains the low 32 bits. + byteSize = static_cast(static_cast(newWidth) * static_cast(newWidth)); +#else byteSize = newWidth * newWidth; +#endif width = newWidth; } -// a second create only logs. +// PE 0x1019B140. Unreachable in 1.50: no code or data references. +void PatchDetailLayer::freeData() +{ + if (created && data) + { + ::renddx9abi::engineFree(data); // operator delete[] (sub_1005F370) + data = 0; + } + created = 0; +} + +// PE 0x1019B170. Unreachable in 1.50: no code or data references. +void PatchDetailLayer::copyFrom(const PatchDetailLayer* other) +{ + ::memcpy(data, other->data, static_cast(byteSize)); +} + +// PE 0x1019BD20. Unreachable in 1.50: no code or data references. +void PatchDetailLayer::fill(unsigned char value) +{ + assertCreated(); + ::memset(data, value, static_cast(byteSize)); +} + +// PE 0x1019BAF0 (a tail jump to PatchDetailLayer::at). Unreachable in 1.50: no code or data references. +unsigned char* PatchDetailLayer::byteAt(int position) +{ + return at(position); +} + +// Reports the retail Error and refuses a second creation. +// PE 0x1019B0A0 void PatchDetailLayer::create() { if (created) { - ::renddx9abi::logf("[QuadPatchEditable.cpp:207] TBM: PatchDetailLayer already created"); + ::renddx9abi::Debug(DebugTypeError, std::string("C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\QuadPatchEditable.cpp"), 207, std::string()) + << "TBM: PatchDetailLayer already created"; return; } created = 1; data = static_cast(::renddx9abi::engineAlloc(static_cast(byteSize))); // operator new[] (sub_1005F340) } -// a log line, never a stop: every caller carries on with the null map. +// Reports the retail Error for an uncreated map; Error filtering belongs to Debug. +// PE 0x101A1CD0 void PatchDetailLayer::assertCreated() { if (!created) - ::renddx9abi::logf("[QuadPatchEditable.cpp:234] TBM: PatchDetailLayer is not created"); + ::renddx9abi::Debug(DebugTypeError, std::string("C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\QuadPatchEditable.cpp"), 234, std::string()) + << "TBM: PatchDetailLayer is not created"; } // The bound is `position > byteSize` (signed), so byteSize itself passes, and the -// refusal only logs - the address is answered regardless. +// refusal reports an Error; when filtered, the address is answered regardless. +// PE 0x1019BA60 unsigned char* PatchDetailLayer::at(int position) { assertCreated(); if (position < 0 || position > byteSize) - ::renddx9abi::logf("[QuadPatchEditable.cpp:128] TBM: pos out of range!"); + ::renddx9abi::Debug(DebugTypeError, std::string("C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\QuadPatchEditable.cpp"), 128, std::string()) + << "TBM: pos out of range!"; return data + position; } // the texels of heightmap quad (x, z): `width / patchSize` per side. No created test. +// PE 0x1019B040 void PatchDetailLayer::clearQuad(int x, int z) { const int block = width / owner->editableTerrain->m_patchSize; @@ -289,24 +303,43 @@ void PatchDetailLayer::clearQuad(int x, int z) } // the mean weight over quad (x, z): column by column, each column's rows summed in order. +// PE 0x1019BB00 float PatchDetailLayer::averageWeight(int x, int z) { assertCreated(); +#if defined(__APPLE__) + // [CHOSEN, not recovered] FIADD accumulates and divides without a float spill. + bf2x87::Real sum(0); +#else float sum = 0.0f; +#endif const int w = width; const int block = w / owner->editableTerrain->m_patchSize; int count = 0; for (int col = 0; col < block; ++col) { for (int row = 0; row < block; ++row) +#if defined(__APPLE__) + sum = bf2x87::add(sum, bf2x87::Real(data[x * block + col + w * (z * block + row)])); +#else sum = sum + static_cast(data[x * block + col + w * (z * block + row)]); +#endif +#if defined(__APPLE__) + count = static_cast(static_cast(count) + static_cast(block)); +#else count += block; +#endif } +#if defined(__APPLE__) + return bf2x87::store(bf2x87::div(sum, bf2x87::Real(count))); +#else return sum / static_cast(count); +#endif } // any non-zero weight in quad (x, z) or the one-texel border around it; each sample is // clamped to [0, width - 1] (the upper clamp first). +// PE 0x1019BC60 bool PatchDetailLayer::anyWeight(int x, int z) { assertCreated(); @@ -338,18 +371,21 @@ bool PatchDetailLayer::anyWeight(int x, int z) // PatchDetailLayers +// PE 0x1019B1A0 void PatchDetailLayers::init(QuadPatchEditable* owner, int width) { for (int i = 0; i < 6; ++i) records[i].init(owner, width); } +// PE 0x1019B370 bool PatchDetailLayers::isLayerSet(int layer, int x, int z) { return (layerMask3(x, z) & static_cast(1 << layer)) != 0; } // at most three layers: 5, 4, 3 first, then 0, 1, 2, stopping at the third found. +// PE 0x1019BE00 unsigned char PatchDetailLayers::layerMask3(int x, int z) { unsigned char mask = 0; @@ -378,6 +414,7 @@ unsigned char PatchDetailLayers::layerMask3(int x, int z) } // the layer with the largest mean weight (strictly larger wins; 0 when none exceeds 0). +// PE 0x1019BEA0 unsigned char PatchDetailLayers::dominantLayer(int x, int z) { float best = 0.0f; @@ -385,7 +422,11 @@ unsigned char PatchDetailLayers::dominantLayer(int x, int z) for (int i = 0; i < 6; ++i) { const float weight = records[i].averageWeight(x, z); +#if defined(__APPLE__) + if (bf2x87::greater(bf2x87::Real(weight), bf2x87::Real(best))) +#else if (weight > best) +#endif { best = weight; layer = static_cast(i); @@ -394,6 +435,7 @@ unsigned char PatchDetailLayers::dominantLayer(int x, int z) return layer; } +// PE 0x1019B290 unsigned char PatchDetailLayers::layerMask(int x, int z) { unsigned char mask = 0; @@ -403,19 +445,23 @@ unsigned char PatchDetailLayers::layerMask(int x, int z) return mask; } -// The guard only logs (`layer < 0 || layer > 6`, so 6 passes silently). +// Reports an Error outside [0, 6]; the shipped guard lets index 6 pass. +// PE 0x1019BD60 bool PatchDetailLayers::hasLayer(int layer, int x, int z) { if (layer < 0 || layer > 6) - ::renddx9abi::logf("[QuadPatchEditable.cpp:282] TBM: layer out of range"); + ::renddx9abi::Debug(DebugTypeError, std::string("C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\QuadPatchEditable.cpp"), 282, std::string()) + << "TBM: layer out of range"; return records[layer].anyWeight(x, z); } // the same guard, then the record's quad cleared. +// PE 0x1019B2D0 void PatchDetailLayers::clearLayerQuad(int layer, int x, int z) { if (layer < 0 || layer > 6) - ::renddx9abi::logf("[QuadPatchEditable.cpp:292] TBM: layer out of range"); + ::renddx9abi::Debug(DebugTypeError, std::string("C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\QuadPatchEditable.cpp"), 292, std::string()) + << "TBM: layer out of range"; records[layer].clearQuad(x, z); } @@ -439,6 +485,7 @@ void PatchDetailLayers::createAll() } // each map's created test (it only logs), then the map zeroed. +// PE 0x1019BF00 void PatchDetailLayers::clearAll() { for (int i = 0; i < 6; ++i) @@ -449,6 +496,7 @@ void PatchDetailLayers::clearAll() } // each map copied from the other set's, by this set's sizes. +// PE 0x1019B420 void PatchDetailLayers::copyFrom(const PatchDetailLayers* other) { for (int i = 0; i < 6; ++i) @@ -466,21 +514,43 @@ bool PatchDetailLayers::areAllCreated() } +// PE 0x1019B280 (a tail jump to getLayer). Unreachable in 1.50: no code or data references. +PatchDetailLayer* PatchDetailLayers::layerRecord(int layer) +{ + return getLayer(layer); +} + +// PE 0x1019B1F0 PatchDetailLayer* PatchDetailLayers::getLayer(int layer) { if (layer < 0 || layer > 6) - ::renddx9abi::logf("[QuadPatchEditable.cpp:256] TBM: layer out of range"); + ::renddx9abi::Debug(DebugTypeError, std::string("C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\QuadPatchEditable.cpp"), 256, std::string()) + << "TBM: layer out of range"; return records + layer; } // MergedPatchDetailLayers - every query goes to `source` until this set's own maps are all created. +// Slot +0x00 of the merged set's table (0x1022115C): refuses with the retail Error, reading neither +// argument (`retn 8`). +// PE 0x101A1D50 void MergedPatchDetailLayers::init(QuadPatchEditable*, int) { - ::renddx9abi::logf("[QuadPatchEditable.h:107] TBM: dont use this on MergedPatchDetailLayers"); + ::renddx9abi::Debug(DebugTypeError, std::string("c:\\dice\\projects\\bf2branches\\patch_1_50\\code\\bf2\\geom\\QuadPatchEditable.h"), 107, std::string()) + << "TBM: dont use this on MergedPatchDetailLayers"; } +// PE 0x1019B460. Unreachable in 1.50: no code or data references. Sets `source` first, then the +// six records' owner, byte size and width (the inlined PatchDetailLayer::init). +void MergedPatchDetailLayers::initWithSource(QuadPatchEditable* owner, int width, PatchDetailLayers* sourceSet) +{ + source = sourceSet; + for (int i = 0; i < 6; ++i) + records[i].init(owner, width); +} + +// PE 0x1019B580 bool MergedPatchDetailLayers::isLayerSet(int layer, int x, int z) { if (areAllCreated()) @@ -488,6 +558,7 @@ bool MergedPatchDetailLayers::isLayerSet(int layer, int x, int z) return source->isLayerSet(layer, x, z); } +// PE 0x1019BF80 unsigned char MergedPatchDetailLayers::layerMask3(int x, int z) { if (areAllCreated()) @@ -495,6 +566,7 @@ unsigned char MergedPatchDetailLayers::layerMask3(int x, int z) return source->layerMask3(x, z); } +// PE 0x1019BFB0 unsigned char MergedPatchDetailLayers::dominantLayer(int x, int z) { if (areAllCreated()) @@ -502,6 +574,7 @@ unsigned char MergedPatchDetailLayers::dominantLayer(int x, int z) return source->dominantLayer(x, z); } +// PE 0x1019B510 unsigned char MergedPatchDetailLayers::layerMask(int x, int z) { if (areAllCreated()) @@ -509,6 +582,7 @@ unsigned char MergedPatchDetailLayers::layerMask(int x, int z) return source->layerMask(x, z); } +// PE 0x1019BF40 bool MergedPatchDetailLayers::hasLayer(int layer, int x, int z) { if (areAllCreated()) @@ -516,6 +590,7 @@ bool MergedPatchDetailLayers::hasLayer(int layer, int x, int z) return source->hasLayer(layer, x, z); } +// PE 0x1019B540 void MergedPatchDetailLayers::clearLayerQuad(int layer, int x, int z) { if (areAllCreated()) @@ -526,6 +601,7 @@ void MergedPatchDetailLayers::clearLayerQuad(int layer, int x, int z) source->clearLayerQuad(layer, x, z); } +// PE 0x1019B4E0 (also 0x1019B4B0, an instruction-identical standalone copy) PatchDetailLayer* MergedPatchDetailLayers::getLayer(int layer) { if (areAllCreated()) @@ -540,6 +616,7 @@ PatchDetailLayer* MergedPatchDetailLayers::getLayer(int layer) // checker state, the name, the three layer sets (records created = 0, data = 0; the merged set's // source is left to init), then the flags and the texture / buffer slots. +0x328 and the file // indices are not initialised. +// PE 0x1019BFE0 QuadPatchEditable::QuadPatchEditable(TerrainEditable* owner) : QuadPatch(owner), m_colormapEdit(0), @@ -572,6 +649,7 @@ QuadPatchEditable::QuadPatchEditable(TerrainEditable* owner) // the road mask (owner references only, not nulled), the six layer index buffers; then the members - the // merged set, the edit set and the imported set, each freeing its six maps last to first - the name // and ~QuadPatch. The +0x2DC compressed detail maps are never released. +// PE 0x1019C190 QuadPatchEditable::~QuadPatchEditable() { terrainReleaseTexture(m_undergrowthOverlay); // +0x2E4 @@ -586,15 +664,23 @@ QuadPatchEditable::~QuadPatchEditable() } // The patch size is asked once (E+0x4C); both halvings are signed, as shipped. +// PE 0x1019B7A0 void QuadPatchEditable::getFileIndices(int* x, int* z) { - TerrainEditable* const te = editableTerrain; - const int patchSize = te->getPatchSize(); // E+0x4C - *x = te->m_heightmapSizeX / patchSize / 2 + gridX; // +0x350, +0x68 - *z = te->m_heightmapSizeZ / patchSize / 2 + gridZ; // +0x354, +0x6C + const int patchSize = editableTerrain->getPatchSize(); // E+0x4C +#if defined(__APPLE__) + // [CHOSEN, not recovered] ADD wraps after the two signed divisions. + *x = static_cast(static_cast(editableTerrain->m_heightmapSizeX / patchSize / 2) + + static_cast(gridX)); + *z = static_cast(static_cast(editableTerrain->m_heightmapSizeZ / patchSize / 2) + + static_cast(gridZ)); +#else + *x = editableTerrain->m_heightmapSizeX / patchSize / 2 + gridX; // +0x350, +0x68 + *z = editableTerrain->m_heightmapSizeZ / patchSize / 2 + gridZ; // +0x354, +0x6C +#endif } -// Places the patch at grid (x, z), loads its maps, and builds buffers and layer sets. +// PE 0x1019F530: places the patch at grid (x, z), loads its maps, and builds buffers and layer sets. // Colormaps prefer the editor copy, then the game copy, then a checkerboard; lightmaps // default to white. Missing detail maps are created and saved immediately. // Temporarily enables managed textures. Loaded detail maps defer import until update(). @@ -605,31 +691,39 @@ void QuadPatchEditable::init(int x, int z) gridZ = z; worldX = x * te->m_patchSize; worldZ = z * te->m_patchSize; +#if defined(__APPLE__) + scaledX = bf2x87::toIntTruncate(te->m_primaryWorldScale.x) * worldX; +#else scaledX = static_cast(te->m_primaryWorldScale.x) * worldX; +#endif +#if defined(__APPLE__) + scaledZ = bf2x87::toIntTruncate(te->m_primaryWorldScale.z) * worldZ; +#else scaledZ = static_cast(te->m_primaryWorldScale.z) * worldZ; +#endif m_fileIndexX = x + te->m_patchCount / 2; m_fileIndexZ = z + te->m_patchCount / 2; - formatString(m_fileName, "%02ix%02i", m_fileIndexX, m_fileIndexZ); + m_fileName = formatString("%02ix%02i", m_fileIndexX, m_fileIndexZ); // "" - the editor base name (P+0xFC) is asked first. - vc71::string editPath; + std::string editPath; { - const vc71::string editorBase = te->getEditorColormapBaseName(); - editPath = ::renddx9abi::toVc71String(te->getLevelSavePath()); // E+0x90 + const std::string editorBase = te->getEditorColormapBaseName(); + editPath = ::renddx9abi::fromHostString(te->getLevelSavePath()); // E+0x90 editPath += editorBase; editPath += m_fileName; } // "" - the base name (E+0x6C) is asked first. - vc71::string gamePath; + std::string gamePath; { TerrainEditableNameResult colormapBase = te->getColormapBaseName(); - gamePath = ::renddx9abi::toVc71String(te->getLevelSavePath()); - gamePath += ::renddx9abi::toVc71String(colormapBase); + gamePath = ::renddx9abi::fromHostString(te->getLevelSavePath()); + gamePath += ::renddx9abi::fromHostString(colormapBase); gamePath += m_fileName; } const int savedManaged = dx9rend::textureManagerSwapManaged(1); - vc71::string editDds(editPath); + std::string editDds(editPath); editDds += ".dds"; if (::dice::hfe::fileManager->fileExists(::renddx9abi::makeHostString(editDds))) { @@ -638,7 +732,7 @@ void QuadPatchEditable::init(int x, int z) } else { - vc71::string gameDds(gamePath); + std::string gameDds(gamePath); gameDds += ".dds"; if (::dice::hfe::fileManager->fileExists(::renddx9abi::makeHostString(gameDds))) { @@ -666,14 +760,14 @@ void QuadPatchEditable::init(int x, int z) m_materialOverlay = 0; // "" - the base name (E+0x74) is asked first. - vc71::string lightPath; + std::string lightPath; { TerrainEditableNameResult lightmapBase = te->getLightmapBaseName(); - lightPath = ::renddx9abi::toVc71String(te->getLevelSavePath()); - lightPath += ::renddx9abi::toVc71String(lightmapBase); + lightPath = ::renddx9abi::fromHostString(te->getLevelSavePath()); + lightPath += ::renddx9abi::fromHostString(lightmapBase); lightPath += m_fileName; } - vc71::string lightDds(lightPath); + std::string lightDds(lightPath); lightDds += ".dds"; if (::dice::hfe::fileManager->fileExists(::renddx9abi::makeHostString(lightDds))) { @@ -689,18 +783,18 @@ void QuadPatchEditable::init(int x, int z) // "_1" / "_2" - the editor base name (P+0xF4) first. m_detailMapsFromFile = 0; - vc71::string detailBase; + std::string detailBase; { - const vc71::string editorBase = te->getEditorDetailmapBaseName(); - detailBase = ::renddx9abi::toVc71String(te->getLevelSavePath()); + const std::string editorBase = te->getEditorDetailmapBaseName(); + detailBase = ::renddx9abi::fromHostString(te->getLevelSavePath()); detailBase += editorBase; detailBase += m_fileName; } for (int i = 0; i < 2; ++i) { - vc71::string path; - formatString(path, "%s_%i", detailBase.c_str(), i + 1); - vc71::string dds(path); + std::string path; + path = formatString("%s_%i", detailBase.c_str(), i + 1); + std::string dds(path); dds += ".dds"; if (::dice::hfe::fileManager->fileExists(::renddx9abi::makeHostString(dds))) { @@ -747,6 +841,7 @@ void QuadPatchEditable::init(int x, int z) m_importPending = 1; } +// PE 0x1019E160 // the height range (+0x98 / +0x9C, seeded FLT_MIN / FLT_MAX) and the bounding sphere // (+0xA0 / +0xAC) of the patch's (patchSize + 1)^2 heightmap samples. The compares are the listing's: // `max < h` raises, `!(min < h)` lowers. Scale and size are asked through ITerrainEditable. @@ -785,11 +880,12 @@ void QuadPatchEditable::computeBounds() ++point; } } - D3DXComputeBoundingSphere(points, static_cast(side * side), 12, &sphereCentre, &sphereRadius); + D3DXComputeBoundingSphere(reinterpret_cast(points), static_cast(side * side), + 12, reinterpret_cast(&sphereCentre), &sphereRadius); ::renddx9abi::engineFree(points); } -// the per-patch streams: +0x54 the heights (4 bytes per sample, divided by the vertical +// PE 0x1019DF30: the per-patch streams: +0x54 the heights (4 bytes per sample, divided by the vertical // scale) and a fresh +0x5C that buildNormalVertexBuffer fills. The old wrappers are released, not // nulled. The x == -1024 re-sample (when the scaled height is below one unit) asks the cluster for // the same coordinate again - -1024.0f (0xC4800000) is the column's own x. @@ -812,7 +908,11 @@ void QuadPatchEditable::rebuildVertexBuffers() static_cast(side * side), 4u, 8u, "QuadPatchEditable"); float* const heights = static_cast(dx9rend::vertexBufferLock(heightVertexBuffer, 0, 0, 0)); ::dice::hfe::world::IHeightmapCluster* const cluster = heightmapClusterByName(); +#if defined(__APPLE__) + const int step = bf2x87::toIntTruncate(editableTerrain->getPrimaryWorldScale().x); // E+0x34 +#else const int step = static_cast(editableTerrain->getPrimaryWorldScale().x); // E+0x34 +#endif const float scaleY = editableTerrain->getPrimaryWorldScale().y; // E+0x34 again const int zEnd = scaledZ + step * side; const int xEnd = scaledX + step * side; @@ -841,7 +941,8 @@ void QuadPatchEditable::rebuildVertexBuffers() // Techniques 0..2 and 7 draw the whole base grid; 4 / 5 / 6 / 8 the grid with their overlay as // TEXLAYER0 (no overlay set for another technique draws nothing); 3 draws every detail layer with // triangles, one pass each (1 side-projected, 2 environment-mapped, else 0). The technique is -// compared unsigned (a negative one draws nothing). +// compared unsigned (a negative one draws nothing). Reached only through the table (0x10221228). +// PE 0x101A15B0 void QuadPatchEditable::draw(int) { TerrainEditable* const te = editableTerrain; @@ -891,7 +992,7 @@ void QuadPatchEditable::draw(int) if (!m_layerTriangleCount[layer]) continue; const TerrainDetailTexture* const record = - reinterpret_cast(editableTerrain->m_detailTextures.first)[layer]; + editableTerrain->m_detailTextures.data()[layer]; param(editableTerrain->m_hTexLayer[1])->setValue(record->texture, 0); void* detail; if (editableTerrain->m_useCompDetailMaps && m_compDetailMap[layer / 3]) @@ -903,12 +1004,12 @@ void QuadPatchEditable::draw(int) float selector[3] = { 0.0f, 0.0f, 0.0f }; selector[2 - layer % 3] = 1.0f; dx9rend::effectGetShaderParameterBorrowedTyped(static_cast(editableTerrain->m_effect), - vc71::string("COMPONENTSELECTOR"))->setValue(selector, 0); + std::string("COMPONENTSELECTOR"))->setValue(selector, 0); } { float tiling[4] = { record->sideTiling.x, record->sideTiling.y, record->topTiling, record->yOffset }; dx9rend::effectGetShaderParameterBorrowedTyped(static_cast(editableTerrain->m_effect), - vc71::string("NEARTEXTILING"))->setValue(tiling, 0); + std::string("NEARTEXTILING"))->setValue(tiling, 0); } dx9rend::indexBufferBind(m_layerIndexBuffer[layer]); unsigned int pass; @@ -922,7 +1023,7 @@ void QuadPatchEditable::draw(int) pass = 2; // The live EnvMapManager's borrowed texture (dword_10267A34 +0x64), unguarded. dx9rend::effectGetShaderParameterBorrowedTyped(static_cast(editableTerrain->m_effect), - vc71::string("TEXLAYER7"))->setValue( + std::string("TEXLAYER7"))->setValue( static_cast(terrainEnvMapManager())->m_currentTexture, 0); } else @@ -947,6 +1048,7 @@ void QuadPatchEditable::draw(int) } // all six layers, then the pending flag cleared. +// PE 0x1019FF20 void QuadPatchEditable::importAllLayers() { for (int layer = 0; layer < 6; ++layer) @@ -992,8 +1094,18 @@ void QuadPatchEditable::importLayer(int layer) rebuildLayerIndexBuffer(layer); } +// PE 0x1019B760. Unreachable in 1.50: no code or data references. The shipped body stores through +// the index unchecked; [CHOSEN, not recovered] the index is range-tested here (memory-safety +// exception: out-of-bounds write omitted), which cannot be observed as nothing calls it. +void QuadPatchEditable::clearLayerTriangleCount(int layer) +{ + if (layer >= 0 && layer < 6) + m_layerTriangleCount[layer] = 0; +} + // two triangles per heightmap quad the merged set reports for `layer`, as u16 indices // into the (patchSize + 1)^2 grid; the lock is not tested. The count is triangles (indices / 3). +// PE 0x1019B650 void QuadPatchEditable::rebuildLayerIndexBuffer(int layer) { const int n = editableTerrain->getPatchSize(); // E+0x4C @@ -1029,10 +1141,18 @@ void QuadPatchEditable::rebuildLayerIndexBuffer(int layer) // the low-detail map rebuilt from the detail maps: cleared, then every layer whose record // says low-detail type 1 (into red, bits 16..23) or 2 (into blue, bits 0..7) adds its channel's // weights, saturating at 255. Three surfaces locked (flags 0), unlocked and released in lock order. +// PE 0x101A0D60 void QuadPatchEditable::rebuildLowDetailMap() { const int width = editableTerrain->m_patchDetailmapSize; - fillTexture(engineTexture(lowDetailmap), 0u); + { + dx9rend::TextureLockRecord* const record = dx9rend::textureLock(engineTexture(lowDetailmap), 0, 0x7FFFFFFF); + unsigned int* texel = static_cast(record->pBits); + unsigned int* const end = texel + record->width * record->height; + for (; texel != end; ++texel) + *texel = 0; + dx9rend::textureUnlock(engineTexture(lowDetailmap), record); + } IDirect3DSurface9* const lowSurface = dx9rend::textureGetLevelSurface(engineTexture(lowDetailmap), 0, 0x7FFFFFFF); D3DLOCKED_RECT lowRect; @@ -1052,7 +1172,7 @@ void QuadPatchEditable::rebuildLowDetailMap() for (int layer = 0; layer < 6; ++layer) { TerrainDetailTexture* const record = - reinterpret_cast(editableTerrain->m_detailTextures.first)[layer]; + editableTerrain->m_detailTextures.data()[layer]; const int type = record->getLowDetailType(); // record slot +0x50 if (type != 1 && type != 2) continue; @@ -1080,11 +1200,13 @@ void QuadPatchEditable::rebuildLowDetailMap() } // (nullsub_12, `retn 4`) - empty in 1.50. +// PE 0x1019B9B0 void QuadPatchEditable::debugTest(int) { } // the technique overlays: patchSize^2, D3DFMT_A8R8G8B8 (21), one mip, cleared to 0 +// PE 0x1019C3A0 void QuadPatchEditable::createUndergrowthOverlay() { if (m_undergrowthOverlay) @@ -1092,7 +1214,12 @@ void QuadPatchEditable::createUndergrowthOverlay() const int size = editableTerrain->m_patchSize; m_undergrowthOverlay = engineTexture(dx9rend::textureManagerCreateEmpty( static_cast(size), static_cast(size), 21, 1, 0, 0)); - fillTexture(m_undergrowthOverlay, 0u); + dx9rend::TextureLockRecord* const record = dx9rend::textureLock(m_undergrowthOverlay, 0, 0x7FFFFFFF); + unsigned int* texel = static_cast(record->pBits); + unsigned int* const end = texel + record->width * record->height; + for (; texel != end; ++texel) + *texel = 0; + dx9rend::textureUnlock(m_undergrowthOverlay, record); } // The releases (0x1019C410 / 0x1019C4D0 / 0x1019C590 / 0x1019C5E0): the owner reference, then the same @@ -1106,6 +1233,7 @@ void QuadPatchEditable::releaseUndergrowthOverlay() m_undergrowthOverlay = 0; } +// PE 0x1019C460 void QuadPatchEditable::createOvergrowthOverlay() { if (m_overgrowthOverlay) @@ -1116,6 +1244,7 @@ void QuadPatchEditable::createOvergrowthOverlay() fillTexture(m_overgrowthOverlay, 0u); } +// PE 0x1019C4D0 void QuadPatchEditable::releaseOvergrowthOverlay() { if (!m_overgrowthOverlay) @@ -1125,6 +1254,7 @@ void QuadPatchEditable::releaseOvergrowthOverlay() m_overgrowthOverlay = 0; } +// PE 0x1019C520 void QuadPatchEditable::createOvergrowthShadowOverlay() { if (m_overgrowthShadowOverlay) @@ -1135,6 +1265,7 @@ void QuadPatchEditable::createOvergrowthShadowOverlay() fillTexture(m_overgrowthShadowOverlay, 0u); } +// PE 0x1019C590 void QuadPatchEditable::releaseOvergrowthShadowOverlay() { if (!m_overgrowthShadowOverlay) @@ -1144,6 +1275,7 @@ void QuadPatchEditable::releaseOvergrowthShadowOverlay() m_overgrowthShadowOverlay = 0; } +// PE 0x1019C5E0 void QuadPatchEditable::releaseMaterialOverlay() { if (!m_materialOverlay) @@ -1174,31 +1306,54 @@ inline int texelPitch(const D3DLOCKED_RECT& locked) return static_cast(static_cast(locked.Pitch) >> 2); } +} // anonymous namespace + // sub_100A2FE0 - ceil of a float through the CRT's double ceil (`fld; fstp qword; call ceil`), the -// result left in st0 for the caller's chop. -inline int ceilChop(float value) +// result left in st0 for the caller's chop (folded in here; every caller chops it at once). +int ceilChop(float value) { +#if defined(__APPLE__) + // [CHOSEN, not recovered] The caller's FISTP returns integer indefinite on invalid input. + return bf2x87::toIntTruncate(std::ceil(static_cast(value))); +#else return static_cast(std::ceil(static_cast(value))); +#endif } -} // anonymous namespace - // the colour helpers (QuadPatchEditable.h) // (`retn 10h`, four floats BY value). Each * 255.0f (flt_101E14C0), chopped (fistp under a // truncating control word), the low byte kept - the third first, then the fourth unmasked (only its // low byte survives the two shifts that follow), the second, the first. +// PE 0x1019AE50 unsigned int terrainEditPackColor(float c0, float c1, float c2, float c3) { +#if defined(__APPLE__) + unsigned int packed = static_cast(bf2x87::toIntTruncate(bf2x87::mul(bf2x87::Real(c2), bf2x87::Real(255)))) & 0xFFu; +#else unsigned int packed = static_cast(static_cast(c2 * 255.0f)) & 0xFFu; +#endif +#if defined(__APPLE__) + packed |= static_cast(bf2x87::toIntTruncate(bf2x87::mul(bf2x87::Real(c3), bf2x87::Real(255)))) << 8; +#else packed |= static_cast(static_cast(c3 * 255.0f)) << 8; +#endif packed <<= 8; +#if defined(__APPLE__) + packed |= static_cast(bf2x87::toIntTruncate(bf2x87::mul(bf2x87::Real(c1), bf2x87::Real(255)))) & 0xFFu; +#else packed |= static_cast(static_cast(c1 * 255.0f)) & 0xFFu; +#endif packed <<= 8; +#if defined(__APPLE__) + packed |= static_cast(bf2x87::toIntTruncate(bf2x87::mul(bf2x87::Real(c0), bf2x87::Real(255)))) & 0xFFu; +#else packed |= static_cast(static_cast(c0 * 255.0f)) & 0xFFu; +#endif return packed; } // (ecx = out, edx = colour) - each byte, the lowest first, * 0.0039215689f (flt_101E2B98). +// PE 0x1019B9C0 void terrainEditUnpackColor(float out[4], unsigned int color) { out[0] = static_cast(color & 0xFFu) * 0.0039215689f; @@ -1209,8 +1364,29 @@ void terrainEditUnpackColor(float out[4], unsigned int color) // (thiscall on dst, `retn 8`) - dst scaled by (1 - t) and stored, all four first; then // t * src computed for all four and added. +// PE 0x101A1DD0 void terrainEditLerpColor(float dst[4], const float src[4], float t) { +#if defined(__APPLE__) + // [CHOSEN, not recovered] Keep and component zero retain x87 width; other components spill. + const bf2x87::Real keep = bf2x87::sub(bf2x87::Real(1), bf2x87::Real(t)); + const bf2x87::Real first = bf2x87::mul(keep, bf2x87::Real(dst[0])); + dst[0] = bf2x87::store(first); + const float kept1 = bf2x87::store(bf2x87::mul(keep, bf2x87::Real(dst[1]))); + dst[1] = kept1; + const float kept2 = bf2x87::store(bf2x87::mul(keep, bf2x87::Real(dst[2]))); + dst[2] = kept2; + const float kept3 = bf2x87::store(bf2x87::mul(keep, bf2x87::Real(dst[3]))); + dst[3] = kept3; + const bf2x87::Real add0 = bf2x87::mul(bf2x87::Real(t), bf2x87::Real(src[0])); + const float add1 = bf2x87::store(bf2x87::mul(bf2x87::Real(t), bf2x87::Real(src[1]))); + const float add2 = bf2x87::store(bf2x87::mul(bf2x87::Real(t), bf2x87::Real(src[2]))); + const float add3 = bf2x87::store(bf2x87::mul(bf2x87::Real(t), bf2x87::Real(src[3]))); + dst[0] = bf2x87::store(bf2x87::add(first, add0)); + dst[1] = bf2x87::store(bf2x87::add(bf2x87::Real(kept1), bf2x87::Real(add1))); + dst[2] = bf2x87::store(bf2x87::add(bf2x87::Real(kept2), bf2x87::Real(add2))); + dst[3] = bf2x87::store(bf2x87::add(bf2x87::Real(kept3), bf2x87::Real(add3))); +#else const float keep = 1.0f - t; dst[0] = keep * dst[0]; dst[1] = keep * dst[1]; @@ -1224,12 +1400,14 @@ void terrainEditLerpColor(float dst[4], const float src[4], float t) dst[1] = dst[1] + add1; dst[2] = dst[2] + add2; dst[3] = dst[3] + add3; +#endif } // the colormap's edit copy // only when there is none: a patchColormapSize^2 A8R8G8B8 texture (one mip), stored // first, then the colormap copied into it by D3DX (no rectangles, D3DX_DEFAULT filter, no colour key; // the answer not tested) and both surfaces released, the copy's first. +// PE 0x1019B5C0 void QuadPatchEditable::makeColormapEditCopy() { if (m_colormapEdit) @@ -1244,7 +1422,8 @@ void QuadPatchEditable::makeColormapEditCopy() source->Release(); } -// the copy's owner reference, then the member's value out of the cache, then nulled. +// PE 0x1019C350. The copy's owner reference (+0x04 decremented; release and free at zero), then the +// member's value out of the cache, then nulled. void QuadPatchEditable::releaseColormapEdit() { if (!m_colormapEdit) @@ -1254,8 +1433,9 @@ void QuadPatchEditable::releaseColormapEdit() m_colormapEdit = 0; } -// with a copy: the copy loaded back over the colormap (D3DX, as above), the copy's surface -// released before the colormap's, then the copy dropped (a tail jump into 0x1019C350). +// PE 0x1019EF80. With a copy (+0x120): the copy loaded back over the colormap (+0x4C; D3DX, as +// above), the copy's surface released before the colormap's, then the copy dropped (a tail jump +// into releaseColormapEdit). void QuadPatchEditable::commitColormapEdit() { if (!m_colormapEdit) @@ -1270,6 +1450,7 @@ void QuadPatchEditable::commitColormapEdit() // with a copy: every texel of it (patchColormapSize^2, x outer, z inner, the pitch // honoured) set to 0, under a (0, 0, size, size) lock with flags 0. +// PE 0x1019B910 void QuadPatchEditable::clearColormapEdits() { if (!m_colormapEdit) @@ -1292,6 +1473,7 @@ void QuadPatchEditable::clearColormapEdits() // zeroed (+0x164 clearAll), the edit and merged sets freed, and the layer's triangle count reset // (its index buffer is not rebuilt). Lock (0, 0, w, w), flags 0; the rows advance by `w` texels - // the surface pitch is ignored. +// PE 0x1019B800 void QuadPatchEditable::clearDetailLayer(int layer) { const int width = editableTerrain->m_patchDetailmapSize; @@ -1320,6 +1502,7 @@ void QuadPatchEditable::clearDetailLayer(int layer) m_layerTriangleCount[layer] = 0; } +// PE 0x1019B8F0 void QuadPatchEditable::clearAllDetailLayers() { for (int layer = 0; layer < 6; ++layer) @@ -1329,6 +1512,7 @@ void QuadPatchEditable::clearAllDetailLayers() // the edit and merged sets freed, then the layer's channel of its detail map rewritten // from the imported weights (texel = (weight << shift) | (texel & ~(255 << shift)); lock (0, 0, w, w), // flags 0, rows advance by `w` texels), and the layer's index buffer rebuilt. +// PE 0x1019EFE0 void QuadPatchEditable::revertLayer(int layer) { const int width = editableTerrain->m_patchDetailmapSize; @@ -1361,6 +1545,7 @@ void QuadPatchEditable::revertLayer(int layer) rebuildLayerIndexBuffer(layer); } +// PE 0x1019F100 void QuadPatchEditable::revertAllLayers() { for (int layer = 0; layer < 6; ++layer) @@ -1371,6 +1556,7 @@ void QuadPatchEditable::revertAllLayers() // weights copied into the imported set (+0x164 slot +0x28 with the merged set - its own maps, not the // forwarders), each set freed when it still exists (asked again), then the low-detail map rebuilt. // The argument is not read. +// PE 0x101A1A30 void QuadPatchEditable::commitLayer(int) { if (!m_colormapEdited) @@ -1387,6 +1573,7 @@ void QuadPatchEditable::commitLayer(int) rebuildLowDetailMap(); } +// PE 0x101A1AB0 void QuadPatchEditable::commitAllLayers() { for (int layer = 0; layer < 6; ++layer) @@ -1397,6 +1584,7 @@ void QuadPatchEditable::commitAllLayers() // (w(3i + 2) << 16) + (w(3i + 1) << 8) + w(3i) - alpha 0 - at texel (x, z), the pitch honoured; the // weight index is x + z * w (x outer, z inner). Both maps locked over (0, 0, w, w) with flags 0 first, // unlocked and released in map order last. The layer argument is not read. +// PE 0x1019D400 void QuadPatchEditable::writeLayersBack(int x0, int x1, int z0, int z1, int) { const int width = editableTerrain->m_patchDetailmapSize; @@ -1536,6 +1724,7 @@ void QuadPatchEditable::addLayerWeight(int layer, int position, int amount) // the brushes // (nullsub_11, `retn 10h`) - empty in 1.50: TerrainEditable::brushHeightmapPatches reaches // every patch under the brush and nothing happens here. +// PE 0x1019B780 void QuadPatchEditable::brushHeightmap(float, float, float, float) { } @@ -1550,8 +1739,13 @@ void QuadPatchEditable::paintDetail(float x, float z, float radius, int strength const float zr = z - static_cast(scaledZ); // +0x7C if (!(xr + radius > 0.0f)) return; +#if defined(__APPLE__) + const float extent = static_cast(bf2x87::toIntTruncate( + static_cast(te->m_patchSize) * te->m_primaryWorldScale.x)); +#else const float extent = static_cast(static_cast( static_cast(te->m_patchSize) * te->m_primaryWorldScale.x)); +#endif if (!(xr - radius < extent) || !(zr + radius > 0.0f) || !(zr - radius < extent) || !m_colormapEdited) return; @@ -1563,7 +1757,11 @@ void QuadPatchEditable::paintDetail(float x, float z, float radius, int strength const float xs = xr * scale; const float zs = zr * scale; const float rs = scale * radius; +#if defined(__APPLE__) + int x0 = bf2x87::toIntTruncate(xs - rs); +#else int x0 = static_cast(xs - rs); +#endif if (x0 <= 0) x0 = 0; int xEnd = size; @@ -1572,7 +1770,11 @@ void QuadPatchEditable::paintDetail(float x, float z, float radius, int strength if (size >= top) xEnd = top; } +#if defined(__APPLE__) + int z0 = bf2x87::toIntTruncate(zs - rs); +#else int z0 = static_cast(zs - rs); +#endif if (z0 <= 0) z0 = 0; int zEnd = size; @@ -1608,7 +1810,11 @@ void QuadPatchEditable::paintDetail(float x, float z, float radius, int strength double falloff = std::cos(static_cast(distance * inverse * 1.5707964f)); // flt_1022106C if (!(0.0 < falloff)) falloff = 0.0; +#if defined(__APPLE__) + const int amount = bf2x87::toIntTruncate(static_cast(static_cast(strength) * falloff)); +#else const int amount = static_cast(static_cast(static_cast(strength) * falloff)); +#endif if (!amount) continue; addLayerWeight(layer, position, amount); @@ -1626,42 +1832,87 @@ void QuadPatchEditable::paintDetail(float x, float z, float radius, int strength // colormap's texel by |t|, a zero strength stores 0. The colour is R/B-swapped before use // ({c2, c1, c0, c3} of its bytes, low first): an argument 0x00BBGGRR paints red RR. Both surfaces are // unlocked and released, the colormap's first. +// PE 0x1019FF40 void QuadPatchEditable::paintColor(float x, float z, float radius, int strength, unsigned int color) { - TerrainEditable* const te = editableTerrain; +#if defined(__APPLE__) + // [CHOSEN, not recovered] Match FILD inputs, retained arithmetic and attested spills. + const float xr = bf2x87::store(bf2x87::sub(bf2x87::Real(x), bf2x87::Real(scaledX))); + const float zr = bf2x87::store(bf2x87::sub(bf2x87::Real(z), bf2x87::Real(scaledZ))); +#else const float xr = x - static_cast(scaledX); const float zr = z - static_cast(scaledZ); - const int extentInt = static_cast(static_cast(te->m_patchSize) * te->m_primaryWorldScale.x); +#endif +#if defined(__APPLE__) + const int extentInt = bf2x87::toIntTruncate(bf2x87::mul(bf2x87::Real(editableTerrain->m_patchSize), bf2x87::Real(editableTerrain->m_primaryWorldScale.x))); +#else + const int extentInt = static_cast(static_cast(editableTerrain->m_patchSize) * editableTerrain->m_primaryWorldScale.x); +#endif +#if defined(__APPLE__) + if (!bf2x87::greater(bf2x87::add(bf2x87::Real(xr), bf2x87::Real(radius)), bf2x87::Real(0))) +#else if (!(xr + radius > 0.0f)) +#endif return; const float extent = static_cast(extentInt); +#if defined(__APPLE__) + if (!bf2x87::less(bf2x87::sub(bf2x87::Real(xr), bf2x87::Real(radius)), bf2x87::Real(extent)) + || !bf2x87::greater(bf2x87::add(bf2x87::Real(zr), bf2x87::Real(radius)), bf2x87::Real(0)) + || !bf2x87::less(bf2x87::sub(bf2x87::Real(zr), bf2x87::Real(radius)), bf2x87::Real(extent)) + || !m_colormapEdited) +#else if (!(xr - radius < extent) || !(zr + radius > 0.0f) || !(zr - radius < extent) || !m_colormapEdited) +#endif return; if (!m_colormapEdit) makeColormapEditCopy(); - const int size = te->m_patchColormapSize; + const int size = editableTerrain->m_patchColormapSize; +#if defined(__APPLE__) + const bf2x87::Real scale = bf2x87::div(bf2x87::Real(size), bf2x87::Real(extent)); + const float xs = bf2x87::store(bf2x87::mul(bf2x87::Real(xr), scale)); + const float zs = bf2x87::store(bf2x87::mul(bf2x87::Real(zr), scale)); + const float rs = bf2x87::store(bf2x87::mul(scale, bf2x87::Real(radius))); + const float inverse = bf2x87::store(bf2x87::div(bf2x87::Real(1), bf2x87::Real(rs))); +#else const float scale = static_cast(size) / extent; const float xs = xr * scale; const float zs = zr * scale; const float rs = scale * radius; const float inverse = 1.0f / rs; +#endif +#if defined(__APPLE__) + int x0 = bf2x87::toIntTruncate(bf2x87::sub(bf2x87::Real(xs), bf2x87::Real(rs))); +#else int x0 = static_cast(xs - rs); +#endif if (x0 <= 0) x0 = 0; int xEnd = size; { +#if defined(__APPLE__) + const int top = ceilChop(bf2x87::store(bf2x87::add(bf2x87::Real(xs), bf2x87::Real(rs)))); +#else const int top = ceilChop(xs + rs); +#endif if (size >= top) xEnd = top; } +#if defined(__APPLE__) + int z0 = bf2x87::toIntTruncate(bf2x87::sub(bf2x87::Real(zs), bf2x87::Real(rs))); +#else int z0 = static_cast(zs - rs); +#endif if (z0 <= 0) z0 = 0; int zEnd = size; { +#if defined(__APPLE__) + const int top = ceilChop(bf2x87::store(bf2x87::add(bf2x87::Real(zs), bf2x87::Real(rs)))); +#else const int top = ceilChop(zs + rs); +#endif if (size >= top) zEnd = top; } @@ -1678,23 +1929,49 @@ void QuadPatchEditable::paintColor(float x, float z, float radius, int strength, for (int px = x0; px < xEnd; ++px) { +#if defined(__APPLE__) + if (z0 >= zEnd) + continue; + const bf2x87::Real dx = bf2x87::sub(bf2x87::Real(px), bf2x87::Real(xs)); + const float dxSquared = bf2x87::store(bf2x87::mul(dx, dx)); +#else const float dx = static_cast(px) - xs; const float dxSquared = dx * dx; +#endif for (int pz = z0; pz < zEnd; ++pz) { +#if defined(__APPLE__) + const bf2x87::Real dz = bf2x87::sub(bf2x87::Real(pz), bf2x87::Real(zs)); + const bf2x87::Real distance = bf2x87::squareRoot(bf2x87::add(bf2x87::mul(dz, dz), bf2x87::Real(dxSquared))); + const float sampledDistance = bf2x87::store(distance); + if (bf2x87::greater(distance, bf2x87::Real(rs))) +#else const float dz = static_cast(pz) - zs; const float distance = std::sqrt(dz * dz + dxSquared); if (distance > rs) +#endif continue; unsigned int* const edit = editBits + px + pz * texelPitch(editLocked); const unsigned int* const original = colormapBits + px + pz * texelPitch(colormapLocked); float colour[4]; terrainEditUnpackColor(colour, color); +#if defined(__APPLE__) + bf2x87::Real falloff = bf2x87::cosValue(bf2x87::mul(bf2x87::mul( + bf2x87::Real(sampledDistance), bf2x87::Real(inverse)), bf2x87::Real(1.5707964f))); + if (!bf2x87::less(bf2x87::Real(0), falloff)) + falloff = bf2x87::Real(0); +#else double falloff = std::cos(static_cast(distance * inverse * 1.5707964f)); if (!(0.0 < falloff)) falloff = 0.0; +#endif const float target[4] = { colour[2], colour[1], colour[0], colour[3] }; +#if defined(__APPLE__) + const float t = bf2x87::store(bf2x87::abs(bf2x87::mul(bf2x87::mul(falloff, + bf2x87::Real(strength)), bf2x87::Real(0.0039215689f)))); +#else const float t = std::fabs(static_cast(falloff * static_cast(strength)) * 0.0039215689f); +#endif float result[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; float current[4]; terrainEditUnpackColor(current, *edit); @@ -1719,15 +1996,133 @@ void QuadPatchEditable::paintColor(float x, float z, float radius, int strength, editSurface->Release(); } +// PE 0x1019DC80 (`retn 14h`). Unreachable in 1.50: no code or data references. The colour brush on the +// low-detail map: the centre is x and z times the texels per patch unit (detail size / patch size, +// integer division, chopped), the radius in texels is detailSize / (patchSize * primary scale x) * +// radius, and the window is clamped to the map. The map's level 0 is locked with the whole-map rect and +// flags 0. Per texel inside the radius: t = |cos(distance / radius * pi/2) * strength / 255|; a texel +// with t > 0 is lerped by t toward the colour (R/B-swapped as in paintColor) for a positive strength, +// toward zero for a negative one, and re-packed unchanged for a zero strength. The distance is not +// rounded to float before the cosine (paintColor stores it first). +void QuadPatchEditable::paintLowDetailColor(float x, float z, float radius, int strength, unsigned int color) +{ + TerrainEditable* const terrain = editableTerrain; + const int size = terrain->m_patchDetailmapSize; + const int patchSize = terrain->m_patchSize; + const int texelsPerPatch = size / patchSize; +#if defined(__APPLE__) + // [CHOSEN, not recovered] Match the FILD inputs, the retained x87 arithmetic and the attested spills. + const int cx = bf2x87::toIntTruncate(bf2x87::mul(bf2x87::Real(x), bf2x87::Real(texelsPerPatch))); + const int cz = bf2x87::toIntTruncate(bf2x87::mul(bf2x87::Real(z), bf2x87::Real(texelsPerPatch))); + const float rad = bf2x87::store(bf2x87::mul( + bf2x87::div(bf2x87::Real(size), bf2x87::mul(bf2x87::Real(patchSize), + bf2x87::Real(terrain->m_primaryWorldScale.x))), + bf2x87::Real(radius))); + const float inverse = bf2x87::store(bf2x87::div(bf2x87::Real(1), bf2x87::Real(rad))); + const int whole = bf2x87::toIntTruncate(bf2x87::Real(rad)); +#else + const int cx = static_cast(x * static_cast(texelsPerPatch)); + const int cz = static_cast(z * static_cast(texelsPerPatch)); + const float rad = static_cast(size) + / (static_cast(patchSize) * terrain->m_primaryWorldScale.x) * radius; + const float inverse = 1.0f / rad; + const int whole = static_cast(rad); +#endif + int xStart = cx - whole; + if (xStart <= 0) + xStart = 0; + int xEnd = size; + if (!(size < cx + whole)) + xEnd = cx + whole; + int zStart = cz - whole; + if (zStart <= 0) + zStart = 0; + int zEnd = size; + if (!(size < cz + whole)) + zEnd = cz + whole; + + const float centreZ = static_cast(cz); + RECT rect = { 0, 0, size, size }; + IDirect3DSurface9* const surface = dx9rend::textureGetLevelSurface(engineTexture(lowDetailmap), 0, 0x7FFFFFFF); + D3DLOCKED_RECT locked; + surface->LockRect(&locked, &rect, 0); + unsigned int* const bits = static_cast(locked.pBits); + for (int px = xStart; px < xEnd; ++px) + { +#if defined(__APPLE__) + const bf2x87::Real dx = bf2x87::sub(bf2x87::Real(px), bf2x87::Real(cx)); + const float dxSquared = bf2x87::store(bf2x87::mul(dx, dx)); +#else + const float dx = static_cast(px - cx); + const float dxSquared = dx * dx; +#endif + for (int pz = zStart; pz < zEnd; ++pz) + { +#if defined(__APPLE__) + const bf2x87::Real dz = bf2x87::sub(bf2x87::Real(pz), bf2x87::Real(centreZ)); + const bf2x87::Real distance = bf2x87::squareRoot( + bf2x87::add(bf2x87::mul(dz, dz), bf2x87::Real(dxSquared))); + if (bf2x87::greater(distance, bf2x87::Real(rad))) + continue; + bf2x87::Real falloff = bf2x87::cosValue(bf2x87::mul(bf2x87::mul( + distance, bf2x87::Real(inverse)), bf2x87::Real(1.5707964f))); + if (!bf2x87::less(bf2x87::Real(0), falloff)) + falloff = bf2x87::Real(0); + const bf2x87::Real weight = bf2x87::abs(bf2x87::mul(bf2x87::mul(falloff, + bf2x87::Real(strength)), bf2x87::Real(0.0039215689f))); + const float t = bf2x87::store(weight); + if (!bf2x87::greater(weight, bf2x87::Real(0))) + continue; +#else + const float dz = static_cast(pz) - centreZ; + const float distance = std::sqrt(dz * dz + dxSquared); + if (distance > rad) + continue; + double falloff = std::cos(static_cast(distance * inverse * 1.5707964f)); + if (!(0.0 < falloff)) + falloff = 0.0; + const double weight = std::fabs(falloff * static_cast(strength) * 0.0039215689f); + const float t = static_cast(weight); + if (!(weight > 0.0)) + continue; +#endif + unsigned int* const texel = bits + px + pz * texelPitch(locked); + float result[4]; + terrainEditUnpackColor(result, *texel); + if (strength > 0) + { + float painted[4]; + terrainEditUnpackColor(painted, color); + const float target[4] = { painted[2], painted[1], painted[0], painted[3] }; + terrainEditLerpColor(result, target, t); + } + else if (strength < 0) + { + const float zero[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; + terrainEditLerpColor(result, zero, t); + } + *texel = terrainEditPackColor(result[0], result[1], result[2], result[3]); + } + } + surface->UnlockRect(); + surface->Release(); +} + // Blends the editable colormap toward a layer's tiled color texture for positive strength, // or back toward the original colormap for negative strength. The layer texture must exist. // Negative v wrapping intentionally uses texture width rather than height. +// PE 0x101A10D0 void QuadPatchEditable::paintColorFromTexture(float x, float z, float radius, int strength, int layer) { TerrainEditable* const te = editableTerrain; const float xr = x - static_cast(scaledX); const float zr = z - static_cast(scaledZ); +#if defined(__APPLE__) + // [CHOSEN, not recovered] the FILD * FMUL product is chopped unrounded (0x101A10FC..0x101A110F). + const int extentInt = bf2x87::toIntTruncate(bf2x87::mul(bf2x87::Real(te->m_patchSize), bf2x87::Real(te->m_primaryWorldScale.x))); +#else const int extentInt = static_cast(static_cast(te->m_patchSize) * te->m_primaryWorldScale.x); +#endif if (!(xr + radius > 0.0f)) return; const float extent = static_cast(extentInt); @@ -1743,7 +2138,11 @@ void QuadPatchEditable::paintColorFromTexture(float x, float z, float radius, in const float zs = zr * scale; const float rs = scale * radius; const float inverse = 1.0f / rs; +#if defined(__APPLE__) + int x0 = bf2x87::toIntTruncate(xs - rs); +#else int x0 = static_cast(xs - rs); +#endif if (x0 <= 0) x0 = 0; int xEnd = size; @@ -1752,7 +2151,11 @@ void QuadPatchEditable::paintColorFromTexture(float x, float z, float radius, in if (size >= top) xEnd = top; } +#if defined(__APPLE__) + int z0 = bf2x87::toIntTruncate(zs - rs); +#else int z0 = static_cast(zs - rs); +#endif if (z0 <= 0) z0 = 0; int zEnd = size; @@ -1770,7 +2173,7 @@ void QuadPatchEditable::paintColorFromTexture(float x, float z, float radius, in D3DLOCKED_RECT editLocked; editSurface->LockRect(&editLocked, 0, 0); const TerrainDetailTextureEditable* const record = static_cast( - reinterpret_cast(te->m_detailTextures.first)[layer]); + te->m_detailTextures.data()[layer]); const int textureHeight = static_cast(dx9rend::textureDims(record->colorTexture)[1]); const int textureWidth = static_cast(dx9rend::textureDims(record->colorTexture)[0]); IDirect3DSurface9* const textureSurface = dx9rend::textureGetLevelSurface(record->colorTexture, 0, 0x7FFFFFFF); @@ -1793,13 +2196,23 @@ void QuadPatchEditable::paintColorFromTexture(float x, float z, float radius, in if (distance > rs) continue; const float inverseScale = 1.0f / scale; +#if defined(__APPLE__) + int u = bf2x87::toIntTruncate(std::floor(static_cast( + (inverseScale * pxF + static_cast(scaledX)) * record->colorTextureTiling.x + 0.5f))); +#else int u = static_cast(std::floor(static_cast( (inverseScale * pxF + static_cast(scaledX)) * record->colorTextureTiling.x + 0.5f))); +#endif u = u % textureWidth; if (u < 0) u += textureWidth; +#if defined(__APPLE__) + int v = bf2x87::toIntTruncate(std::floor(static_cast( + (inverseScale * pzF + static_cast(scaledZ)) * record->colorTextureTiling.y + 0.5f))); +#else int v = static_cast(std::floor(static_cast( (inverseScale * pzF + static_cast(scaledZ)) * record->colorTextureTiling.y + 0.5f))); +#endif v = v % textureHeight; if (v < 0) v += textureWidth; // the width (shipped) @@ -1809,7 +2222,8 @@ void QuadPatchEditable::paintColorFromTexture(float x, float z, float radius, in unsigned int* const edit = editBits + px + pz * texelPitch(editLocked); if (!(0.0 < falloff)) falloff = 0.0; - const float t = std::fabs(static_cast(falloff * static_cast(strength)) * 0.0039215689f); + // FIMUL, FMUL 1/255, FABS, one FSTP: no rounding before the store (0x101A148F..0x101A14A2). + const float t = static_cast(std::fabs(falloff * static_cast(strength) * 0.0039215689f)); float paint[4]; terrainEditUnpackColor(paint, *source); float result[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; @@ -1843,19 +2257,23 @@ void QuadPatchEditable::paintColorFromTexture(float x, float z, float radius, in // makeUncompDDS (E+0xFC) into `directory`; when ".dds" then exists, detail map 0 is dropped // (owner release + evict) and reloaded from it, and layers 0..2 re-imported (0x1019D2D0). The .tga is // deleted either way (FileManager +0x20). -void QuadPatchEditable::importBaseLayers(const vc71::string& directory) +// PE 0x1019E480 +void QuadPatchEditable::importBaseLayers(const std::string& directory) { - vc71::string tile(directory); + std::string tile(directory); tile += "/tx"; tile += m_fileName; { - vc71::string tga(tile); + std::string tga(tile); tga += ".tga"; editableTerrain->makeUncompDDS(::renddx9abi::toHostString(tga), ::renddx9abi::toHostString(directory)); } - vc71::string dds(tile); - dds += ".dds"; - if (::dice::hfe::fileManager->fileExists(::renddx9abi::makeHostString(dds))) + bool exists; + { + const std::string dds(std::string(tile) += ".dds"); + exists = ::dice::hfe::fileManager->fileExists(::renddx9abi::makeHostString(dds)); + } + if (exists) { terrainReleaseTexture(detailMap[0]); dx9rend::textureManagerEvictFromCache(detailMap[0]); @@ -1864,7 +2282,7 @@ void QuadPatchEditable::importBaseLayers(const vc71::string& directory) importLayer(1); importLayer(2); } - vc71::string tga(tile); + std::string tga(tile); tga += ".tga"; ::dice::hfe::fileManager->deleteFile(::renddx9abi::makeHostString(tga)); } @@ -1875,23 +2293,26 @@ void QuadPatchEditable::importBaseLayers(const vc71::string& directory) // and every texel whose byte (layer % 3) is not zero is added to the layer as a weight (the brush's // arithmetic, rows advance by `w` texels); the texture is dropped (owner release + evict) before its // surface is unlocked and released, then the whole patch is written back and all six index buffers -// rebuilt. The .tga is deleted either way. -void QuadPatchEditable::importLayerTile(int layer, const vc71::string& directory) +// rebuilt. The .tga is deleted either way. The texel loop inlines the detail brush's weight arithmetic +// (addLayerWeight; its never-taken negative-amount arm is present in the listing too). +// PE 0x1019E650 +void QuadPatchEditable::importLayerTile(int layer, const std::string& directory) { - const int width = editableTerrain->m_patchDetailmapSize; - vc71::string tile(directory); - tile += "/tx"; - tile += m_fileName; - vc71::string outputDirectory; - formatString(outputDirectory, "%s/", directory.c_str()); + const int width = editableTerrain->m_patchDetailmapSize; // E+0x44, read first + const std::string tile = directory + "/tx" + m_fileName; + std::string outputDirectory; + outputDirectory = formatString("%s/", directory.c_str()); { - vc71::string tga(tile); + std::string tga(tile); tga += ".tga"; editableTerrain->makeUncompDDS(::renddx9abi::toHostString(tga), ::renddx9abi::toHostString(outputDirectory)); } - vc71::string dds(tile); - dds += ".dds"; - if (::dice::hfe::fileManager->fileExists(::renddx9abi::makeHostString(dds))) + bool exists; + { + const std::string dds(tile + ".dds"); // destroyed before the test + exists = ::dice::hfe::fileManager->fileExists(::renddx9abi::makeHostString(dds)); + } + if (exists) { if (!m_detailLayersEdit.areAllCreated()) { @@ -1934,25 +2355,36 @@ void QuadPatchEditable::importLayerTile(int layer, const vc71::string& directory for (int i = 0; i < 6; ++i) rebuildLayerIndexBuffer(i); } - vc71::string tga(tile); + std::string tga(tile); tga += ".tga"; ::dice::hfe::fileManager->deleteFile(::renddx9abi::makeHostString(tga)); } +// PE 0x1019ED40: only logs the retail Error "TBM: dont use this functions!" (QuadPatchEditable.cpp:2147) and +// returns; the one stack argument is never read. [INFERRED] name; [CHOSEN, not recovered] argument type +// (a directory string reference, as its sibling tile imports take: no instruction reads it). +// unreachable in 1.50: no code or data references. +void QuadPatchEditable::importAllLayerTiles(const std::string&) +{ + ::renddx9abi::Debug(DebugTypeError, std::string("C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\QuadPatchEditable.cpp"), 2147, std::string()) + << "TBM: dont use this functions!"; +} + +// PE 0x1019EDC0 // the colormap from "/tx.tga" (converted into `directory`): when the // .dds exists the colormap is dropped (owner release + evict) and reloaded from it, the patch marked // edited (+0x32A) and its edit copy cleared. The .tga is deleted either way. -void QuadPatchEditable::importColormapTile(const vc71::string& directory) +void QuadPatchEditable::importColormapTile(const std::string& directory) { - vc71::string tile(directory); + std::string tile(directory); tile += "/tx"; tile += m_fileName; { - vc71::string tga(tile); + std::string tga(tile); tga += ".tga"; editableTerrain->makeUncompDDS(::renddx9abi::toHostString(tga), ::renddx9abi::toHostString(directory)); } - vc71::string dds(tile); + std::string dds(tile); dds += ".dds"; if (::dice::hfe::fileManager->fileExists(::renddx9abi::makeHostString(dds))) { @@ -1962,13 +2394,13 @@ void QuadPatchEditable::importColormapTile(const vc71::string& directory) m_colormapEdited = 1; clearColormapEdits(); } - vc71::string tga(tile); + std::string tga(tile); tga += ".tga"; ::dice::hfe::fileManager->deleteFile(::renddx9abi::makeHostString(tga)); } // lightmaps -// the lightmap dropped (owner release + evict, nulled) and reloaded under a managed-flag +// PE 0x1019F350: the lightmap dropped (owner release + evict, nulled) and reloaded under a managed-flag // swap to 1 (sub_10017E20): "" - the base name (E+0x74) asked before // the save path (E+0x90) - else a patchColormapSize^2 A8R8G8B8 texture filled white. void QuadPatchEditable::reloadLightmap() @@ -1981,14 +2413,14 @@ void QuadPatchEditable::reloadLightmap() lightmap = 0; } const int savedManaged = dx9rend::textureManagerSwapManaged(1); - vc71::string path; + std::string path; { TerrainEditableNameResult lightmapBase = te->getLightmapBaseName(); // E+0x74 - path = ::renddx9abi::toVc71String(te->getLevelSavePath()); // E+0x90 - path += ::renddx9abi::toVc71String(lightmapBase); + path = ::renddx9abi::fromHostString(te->getLevelSavePath()); // E+0x90 + path += ::renddx9abi::fromHostString(lightmapBase); path += m_fileName; } - vc71::string dds(path); + std::string dds(path); dds += ".dds"; if (::dice::hfe::fileManager->fileExists(::renddx9abi::makeHostString(dds))) { @@ -2009,6 +2441,7 @@ void QuadPatchEditable::reloadLightmap() // the height stream on 1, the terrain's LOD index buffer, and one draw of the LOD-0 range: its // triangle count (+0x11C) as primitives and, for a triangle list (+0x1A8 == 4), three vertices per // primitive - else primitives + 2. +// PE 0x1019E340 void QuadPatchEditable::drawForLightmapGeneration() { TerrainEditable* const te = editableTerrain; @@ -2028,22 +2461,37 @@ void QuadPatchEditable::drawForLightmapGeneration() // (scaledX, 0, scaledZ) .. + patchSize * the primary scale (E+0x4C, then E+0x34). The box's // derived fields are left as the caller built them. +// PE 0x1019E410 void QuadPatchEditable::getWorldBounds(TerrainAabb& bounds) { - TerrainEditable* const te = editableTerrain; - const int patchSize = te->getPatchSize(); // E+0x4C - const Vec3& scale = te->getPrimaryWorldScale(); // E+0x34 + const int patchSize = editableTerrain->getPatchSize(); // E+0x4C + const Vec3& scale = editableTerrain->getPrimaryWorldScale(); // E+0x34 + const float scaleX = scale.x; + const float scaleZ = scale.z; + const int originX = scaledX; + const int originZ = scaledZ; bounds.min.y = 0.0f; - bounds.min.x = static_cast(scaledX); - bounds.min.z = static_cast(scaledZ); + bounds.min.x = static_cast(originX); + bounds.min.z = static_cast(originZ); +#if defined(__APPLE__) + // [CHOSEN, not recovered] Z retains the FILD size; X reloads its float spill. + const float size = bf2x87::store(bf2x87::Real(patchSize)); + const bf2x87::Real maxZ = bf2x87::add(bf2x87::mul(bf2x87::Real(patchSize), bf2x87::Real(scaleZ)), bf2x87::Real(scaledZ)); + const bf2x87::Real maxX = bf2x87::add(bf2x87::mul(bf2x87::Real(size), bf2x87::Real(scaleX)), bf2x87::Real(scaledX)); + bounds.max.y = 0.0f; + bounds.max.x = bf2x87::store(maxX); + bounds.max.z = bf2x87::store(maxZ); +#else const float size = static_cast(patchSize); bounds.max.y = 0.0f; - bounds.max.x = size * scale.x + static_cast(scaledX); - bounds.max.z = size * scale.z + static_cast(scaledZ); + bounds.max.x = size * scaleX + static_cast(scaledX); + bounds.max.z = size * scaleZ + static_cast(scaledZ); +#endif } // the road mask and its consumers // owner release, evict, nulled. +// PE 0x1019F300 void QuadPatchEditable::releaseRoadMask() { if (!m_roadMask) @@ -2065,36 +2513,35 @@ void QuadPatchEditable::renderRoadMask(int size) const int patchSize = te->m_patchSize; // +0x38 dx9rend::stateManagerPush(); - unsigned char* const toggles = static_cast(static_cast(dx9rend::g_Renderer)); - const unsigned char saved1701 = toggles[1701]; - const unsigned char saved1693 = toggles[1693]; - const unsigned char saved1713 = toggles[1713]; - const unsigned char saved1705 = toggles[1705]; - const unsigned char saved1697 = toggles[1697]; - const unsigned char saved1717 = toggles[1717]; - const unsigned char saved1702 = toggles[1702]; - const unsigned char saved1703 = toggles[1703]; - const unsigned char saved1698 = toggles[1698]; - const unsigned char saved1714 = toggles[1714]; - const unsigned char saved1700 = toggles[1700]; + const unsigned char saved1701 = dx9rend::rendererRenderSwitch(1701); + const unsigned char saved1693 = dx9rend::rendererRenderSwitch(1693); + const unsigned char saved1713 = dx9rend::rendererRenderSwitch(1713); + const unsigned char saved1705 = dx9rend::rendererRenderSwitch(1705); + const unsigned char saved1697 = dx9rend::rendererRenderSwitch(1697); + const unsigned char saved1717 = dx9rend::rendererRenderSwitch(1717); + const unsigned char saved1702 = dx9rend::rendererRenderSwitch(1702); + const unsigned char saved1703 = dx9rend::rendererRenderSwitch(1703); + const unsigned char saved1698 = dx9rend::rendererRenderSwitch(1698); + const unsigned char saved1714 = dx9rend::rendererRenderSwitch(1714); + const unsigned char saved1700 = dx9rend::rendererRenderSwitch(1700); te->m_primaryHeightmap->getSeaWaterLevel(); // +0x64, dropped dx9rend::rendererGetHemiRenderMode(); // sub_10009F00, dropped g_LightManager->getDynamicShadowsEnabled(); // +0xF0, dropped te->getShaderTechnique(); // E+0x8C, dropped - toggles[1693] = 0; - toggles[1701] = 0; - toggles[1713] = 0; - toggles[1705] = 0; - toggles[1697] = 0; + dx9rend::rendererRenderSwitch(1693) = 0; + dx9rend::rendererRenderSwitch(1701) = 0; + dx9rend::rendererRenderSwitch(1713) = 0; + dx9rend::rendererRenderSwitch(1705) = 0; + dx9rend::rendererRenderSwitch(1697) = 0; bundledMeshSetHemiEnabled(0); // dword_102597F4 +0x10 - toggles[1717] = 0; - toggles[1702] = 0; - toggles[1703] = 0; - toggles[1698] = 0; + dx9rend::rendererRenderSwitch(1717) = 0; + dx9rend::rendererRenderSwitch(1702) = 0; + dx9rend::rendererRenderSwitch(1703) = 0; + dx9rend::rendererRenderSwitch(1698) = 0; staticMeshRendererSetHemiEnabled(0); // +0x18 - toggles[1714] = 0; - toggles[1700] = 1; + dx9rend::rendererRenderSwitch(1714) = 0; + dx9rend::rendererRenderSwitch(1700) = 1; roadCompiledRendererSetHemiEnabled(1); // +0x18 static_cast(g_RoadEditableRenderer)->m_mode = 1; // +0x18 @@ -2121,19 +2568,19 @@ void QuadPatchEditable::renderRoadMask(int size) position.z = patchSizeF * te->m_primaryWorldScale.z * (static_cast(gridZ) + 0.5f); dx9rend::rendererRenderOrthoTopDown(renderTarget, depthStencil, position, extent, flags); - toggles[1693] = saved1693; - toggles[1701] = saved1701; - toggles[1713] = saved1713; - toggles[1705] = saved1705; - toggles[1697] = saved1697; + dx9rend::rendererRenderSwitch(1693) = saved1693; + dx9rend::rendererRenderSwitch(1701) = saved1701; + dx9rend::rendererRenderSwitch(1713) = saved1713; + dx9rend::rendererRenderSwitch(1705) = saved1705; + dx9rend::rendererRenderSwitch(1697) = saved1697; bundledMeshSetHemiEnabled(saved1697); - toggles[1717] = saved1717; - toggles[1702] = saved1702; - toggles[1703] = saved1703; - toggles[1698] = saved1698; + dx9rend::rendererRenderSwitch(1717) = saved1717; + dx9rend::rendererRenderSwitch(1702) = saved1702; + dx9rend::rendererRenderSwitch(1703) = saved1703; + dx9rend::rendererRenderSwitch(1698) = saved1698; staticMeshRendererSetHemiEnabled(saved1698); - toggles[1714] = saved1714; - toggles[1700] = saved1700; + dx9rend::rendererRenderSwitch(1714) = saved1714; + dx9rend::rendererRenderSwitch(1700) = saved1700; roadCompiledRendererSetHemiEnabled(saved1700); static_cast(g_RoadEditableRenderer)->m_mode = 0; @@ -2230,6 +2677,7 @@ void QuadPatchEditable::burnRoadsInUndergrowth() releaseRoadMask(); // 0x1019F300's body, inlined } +// PE 0x101A0F30 // the patch's materials into the primary heightmap: per heightmap quad (z outer, x inner, // n = the patch size asked through E+0x4C) the merged set's dominant layer (+0x0C) and that record's // material byte (+0x14), then the road mask at the patch size and every non-zero mask texel's low byte @@ -2246,7 +2694,7 @@ void QuadPatchEditable::buildMaterialMap() { const unsigned char layer = m_mergedLayers.dominantLayer(x, z); const TerrainDetailTexture* const record = - reinterpret_cast(te->m_detailTextures.first)[layer]; + te->m_detailTextures.data()[layer]; te->m_primaryHeightmap->setMaterialInGrid(x + n * gridX, z + n * gridZ, record->materialId); ++x; } @@ -2273,6 +2721,7 @@ void QuadPatchEditable::buildMaterialMap() // Rebuilds the material/height overlay only for technique 8, replacing any previous overlay. // Writes contiguous patch-sized rows without using lock pitch. Height display retains the // low-byte conversion and subsequent color scaling, including overflow wrapping. +// PE 0x101A1AD0 void QuadPatchEditable::createMaterialOverlay() { if (m_materialOverlay) @@ -2338,37 +2787,38 @@ void QuadPatchEditable::createMaterialOverlay() // (`retn 4`) - both detail maps saved as "_<1|2>" // (the editor base name, P+0xF4, asked before the save path, E+0x90). -void QuadPatchEditable::saveDetailMaps(const vc71::string& suffix) +void QuadPatchEditable::saveDetailMaps(const std::string& suffix) { TerrainEditable* const te = editableTerrain; - vc71::string base; + std::string base; { - const vc71::string editorBase = te->getEditorDetailmapBaseName(); // P+0xF4 - base = ::renddx9abi::toVc71String(te->getLevelSavePath()); // E+0x90 + const std::string editorBase = te->getEditorDetailmapBaseName(); // P+0xF4 + base = ::renddx9abi::fromHostString(te->getLevelSavePath()); // E+0x90 base += editorBase; base += m_fileName; } for (int i = 0; i < 2; ++i) { - vc71::string number; - formatString(number, "_%i", i + 1); - vc71::string name(base); + std::string number; + number = formatString("_%i", i + 1); + std::string name(base); name += number; name += suffix; dx9rend::textureManagerSaveTexture(engineTexture(detailMap[i]), name); // sub_10017F90, answer dropped } } -// (`retn 4`) - the lightmap saved as "". -void QuadPatchEditable::saveLightmap(const vc71::string& base) +// PE 0x1019D210 (`retn 4`) - the lightmap saved as "". +void QuadPatchEditable::saveLightmap(const std::string& base) { - vc71::string name(::renddx9abi::toVc71String(editableTerrain->getLevelSavePath())); // E+0x90 + std::string name(::renddx9abi::fromHostString(editableTerrain->getLevelSavePath())); // E+0x90 name += base; name += m_fileName; dx9rend::textureManagerSaveTexture(engineTexture(lightmap), name); } -// only for an edited colormap (+0x32A): the edit copy committed (0x1019EF80), then the +// PE 0x1019FE30 +// only for an edited colormap (+0x32A): the edit copy committed (commitColormapEdit), then the // colormap saved as "" (P+0xFC asked first). void QuadPatchEditable::saveEditedColormap() { @@ -2376,10 +2826,10 @@ void QuadPatchEditable::saveEditedColormap() return; commitColormapEdit(); TerrainEditable* const te = editableTerrain; - vc71::string name; + std::string name; { - const vc71::string editorBase = te->getEditorColormapBaseName(); // P+0xFC - name = ::renddx9abi::toVc71String(te->getLevelSavePath()); + const std::string editorBase = te->getEditorColormapBaseName(); // P+0xFC + name = ::renddx9abi::fromHostString(te->getLevelSavePath()); name += editorBase; name += m_fileName; } @@ -2399,14 +2849,14 @@ void QuadPatchEditable::removeCompDetailMaps() terrainReleaseTexture(m_compDetailMap[i]); dx9rend::textureManagerEvictFromCache(m_compDetailMap[i]); m_compDetailMap[i] = 0; - vc71::string name; + std::string name; { - const vc71::string editorBase = te->getEditorDetailmapBaseName(); // P+0xF4 - name = ::renddx9abi::toVc71String(te->getLevelSavePath()); + const std::string editorBase = te->getEditorDetailmapBaseName(); // P+0xF4 + name = ::renddx9abi::fromHostString(te->getLevelSavePath()); name += editorBase; name += m_fileName; - vc71::string suffix; - formatString(suffix, "_%i_tmp", i + 1); + std::string suffix; + suffix = formatString("_%i_tmp", i + 1); name += suffix; } name += ".dds"; @@ -2421,49 +2871,46 @@ void QuadPatchEditable::removeCompDetailMaps() // "_tmp_.dds" output moved onto "_tmp.dds" (no leftover delete), and "<...>__tmp" loaded by name // (sub_10019260) into +0x2DC / +0x2E0. // The name goes through the texture manager, which cuts at the last dot - a dotted save path breaks it. +// PE 0x101A0310 void QuadPatchEditable::makeCompDetailMaps() { removeCompDetailMaps(); { - const vc71::string suffix("_tmp"); + const std::string suffix("_tmp"); saveDetailMaps(suffix); } - TerrainEditable* const te = editableTerrain; for (int i = 0; i < 2; ++i) { - vc71::string temp; + std::string temp; { - const vc71::string editorBase = te->getEditorDetailmapBaseName(); // P+0xF4 - vc71::string base(::renddx9abi::toVc71String(te->getLevelSavePath())); - base += editorBase; - base += m_fileName; - vc71::string suffix; - formatString(suffix, "_%i_tmp", i + 1); + const std::string editorBase = editableTerrain->getEditorDetailmapBaseName(); // P+0xF4 + const std::string base((std::string(::renddx9abi::fromHostString(editableTerrain->getLevelSavePath())) += editorBase) += m_fileName); + std::string suffix; + suffix = formatString("_%i_tmp", i + 1); temp = base; temp += suffix; } { // The argument blocks are built right to left: the options, the directory, the file. - const TerrainEditableString options(te->m_detailmapSettings); // +0x800 - vc71::string outputDirectory; + const TerrainEditableString options(editableTerrain->m_detailmapSettings); // +0x800 + std::string outputDirectory; { - const vc71::string directory = te->getEditorDetailmapDirectory(); // P+0xF8 - outputDirectory = ::renddx9abi::toVc71String(te->getLevelSavePath()); - outputDirectory += directory; + const std::string directory = editableTerrain->getEditorDetailmapDirectory(); // P+0xF8 + outputDirectory = std::string(::renddx9abi::fromHostString(editableTerrain->getLevelSavePath())) += directory; } - vc71::string file(temp); + std::string file(temp); file += ".dds"; - te->runNvdxt(::renddx9abi::toHostString(file), ::renddx9abi::toHostString(outputDirectory), options); + editableTerrain->runNvdxt(::renddx9abi::toHostString(file), ::renddx9abi::toHostString(outputDirectory), options); } { - vc71::string input(temp); + std::string input(temp); input += ".dds"; ::dice::hfe::fileManager->deleteFile(::renddx9abi::makeHostString(input)); } { - vc71::string target(temp); + std::string target(temp); target += ".dds"; - vc71::string source(temp); + std::string source(temp); source += "_.dds"; ::dice::hfe::fileManager->moveFile(::renddx9abi::makeHostString(source), ::renddx9abi::makeHostString(target)); @@ -2472,22 +2919,22 @@ void QuadPatchEditable::makeCompDetailMaps() } } +// PE 0x1019C630 // Burns the patch colormap, optionally rendering edited layers before DDS compilation. // Deletes the destination first and preserves the compatibility target-release sequence. -// [CHOSEN, not recovered] Unused render-flag storage is zero-initialized. -void QuadPatchEditable::burnColormap(const vc71::string& base) +void QuadPatchEditable::burnColormap(const std::string& base) { TerrainEditable* const te = editableTerrain; const int size = te->m_patchColormapSize; // +0x48 - vc71::string path; + std::string path; { TerrainEditableNameResult colormapBase = te->getColormapBaseName(); // E+0x6C - path = ::renddx9abi::toVc71String(te->getLevelSavePath()); // E+0x90 - path += ::renddx9abi::toVc71String(colormapBase); + path = ::renddx9abi::fromHostString(te->getLevelSavePath()); // E+0x90 + path += ::renddx9abi::fromHostString(colormapBase); path += m_fileName; } { - vc71::string dds(path); + std::string dds(path); dds += ".dds"; ::dice::hfe::fileManager->deleteFile(::renddx9abi::makeHostString(dds)); // +0x20 } @@ -2495,10 +2942,10 @@ void QuadPatchEditable::burnColormap(const vc71::string& base) return; if (!m_colormapEdited) // +0x32A { - vc71::string target(::renddx9abi::toVc71String(te->getLevelSavePath())); + std::string target(::renddx9abi::fromHostString(te->getLevelSavePath())); target += base; target += m_fileName; - vc71::string dds(target); + std::string dds(target); dds += ".dds"; const bool missing = !::dice::hfe::fileManager->fileExists(::renddx9abi::makeHostString(dds)); // +0x1C if (missing) @@ -2507,38 +2954,41 @@ void QuadPatchEditable::burnColormap(const vc71::string& base) } dx9rend::stateManagerPush(); - unsigned char* const toggles = static_cast(static_cast(dx9rend::g_Renderer)); - const unsigned char saved1693 = toggles[1693]; - const unsigned char saved1713 = toggles[1713]; - const unsigned char saved1705 = toggles[1705]; - const unsigned char saved1697 = toggles[1697]; - const unsigned char saved1717 = toggles[1717]; - const unsigned char saved1702 = toggles[1702]; - const unsigned char saved1703 = toggles[1703]; - const unsigned char saved1698 = toggles[1698]; - const unsigned char saved1714 = toggles[1714]; - const unsigned char saved1700 = toggles[1700]; + const unsigned char saved1693 = dx9rend::rendererRenderSwitch(1693); + const unsigned char saved1713 = dx9rend::rendererRenderSwitch(1713); + const unsigned char saved1705 = dx9rend::rendererRenderSwitch(1705); + const unsigned char saved1697 = dx9rend::rendererRenderSwitch(1697); + const unsigned char saved1717 = dx9rend::rendererRenderSwitch(1717); + const unsigned char saved1702 = dx9rend::rendererRenderSwitch(1702); + const unsigned char saved1703 = dx9rend::rendererRenderSwitch(1703); + const unsigned char saved1698 = dx9rend::rendererRenderSwitch(1698); + const unsigned char saved1714 = dx9rend::rendererRenderSwitch(1714); + const unsigned char saved1700 = dx9rend::rendererRenderSwitch(1700); const float savedSeaLevel = te->m_primaryHeightmap->getSeaWaterLevel(); // +0x64 const int savedRenderMode = dx9rend::rendererGetHemiRenderMode(); const bool savedShadows = g_LightManager->getDynamicShadowsEnabled(); // +0xF0 const int savedTechnique = te->getShaderTechnique(); // E+0x8C - toggles[1693] = 1; - toggles[1713] = 0; - toggles[1705] = 0; - toggles[1697] = 0; + dx9rend::rendererRenderSwitch(1693) = 1; + dx9rend::rendererRenderSwitch(1713) = 0; + dx9rend::rendererRenderSwitch(1705) = 0; + dx9rend::rendererRenderSwitch(1697) = 0; bundledMeshSetHemiEnabled(0); // dword_102597F4 +0x10 - toggles[1717] = 0; - toggles[1702] = 0; - toggles[1703] = 0; - toggles[1698] = 0; + dx9rend::rendererRenderSwitch(1717) = 0; + dx9rend::rendererRenderSwitch(1702) = 0; + dx9rend::rendererRenderSwitch(1703) = 0; + dx9rend::rendererRenderSwitch(1698) = 0; staticMeshRendererSetHemiEnabled(0); // +0x18 - toggles[1714] = 0; - toggles[1700] = 1; + dx9rend::rendererRenderSwitch(1714) = 0; + dx9rend::rendererRenderSwitch(1700) = 1; roadCompiledRendererSetHemiEnabled(1); // +0x18 te->m_primaryHeightmap->setSeaWaterLevel(-110.0f); // +0x60, dx9rend::rendererSetHemiRenderMode(4); g_LightManager->setDynamicShadowsEnabled(false); // +0xEC + // The shipped block stores +0x00..+0x12 only (0x1019C8EF..0x1019C926) and passes +0x13 and the + // view word (+0x14) as stack garbage. [CHOSEN, not recovered] all 24 bytes zeroed (an + // uninitialised read, see the memory-safety exception): the render reads +0x14 only when +0x00 + // is set, and it is 0. dx9rend::RenderFlags flags; std::memset(&flags, 0, sizeof(flags)); flags.field01 = 1; // the terrain arm @@ -2553,26 +3003,30 @@ void QuadPatchEditable::burnColormap(const vc71::string& base) D3DMULTISAMPLE_NONE, 0, FALSE, &renderTarget, 0); // +0x70 device->CreateDepthStencilSurface(static_cast(size), static_cast(size), D3DFMT_D24S8, D3DMULTISAMPLE_NONE, 0, FALSE, &depthStencil, 0); // +0x74 - const float patchSizeF = static_cast(te->m_patchSize); - const float extent = patchSizeF * te->m_primaryWorldScale.x; + // [CHOSEN, not recovered] the x87 sequence 0x1019C97D..0x1019C9DC: only the extent is spilled to + // float; patchSize * scale.z stays wide into the z product, which is narrowed at the store. + const bf2x87::Real patchSizeWide = bf2x87::Real(te->m_patchSize); + const float extent = bf2x87::store(bf2x87::mul(patchSizeWide, bf2x87::Real(te->m_primaryWorldScale.x))); + const bf2x87::Real depth = bf2x87::mul(patchSizeWide, bf2x87::Real(te->m_primaryWorldScale.z)); Vec3 position; - position.x = (static_cast(gridX) + 0.5f) * extent; + position.x = bf2x87::store(bf2x87::mul(bf2x87::add(bf2x87::Real(gridX), bf2x87::Real(0.5f)), + bf2x87::Real(extent))); position.y = 500.0f; - position.z = patchSizeF * te->m_primaryWorldScale.z * (static_cast(gridZ) + 0.5f); + position.z = bf2x87::store(bf2x87::mul(depth, bf2x87::add(bf2x87::Real(gridZ), bf2x87::Real(0.5f)))); dx9rend::rendererRenderOrthoTopDown(renderTarget, depthStencil, position, extent, flags); - toggles[1693] = saved1693; - toggles[1713] = saved1713; - toggles[1705] = saved1705; - toggles[1697] = saved1697; + dx9rend::rendererRenderSwitch(1693) = saved1693; + dx9rend::rendererRenderSwitch(1713) = saved1713; + dx9rend::rendererRenderSwitch(1705) = saved1705; + dx9rend::rendererRenderSwitch(1697) = saved1697; bundledMeshSetHemiEnabled(saved1697); - toggles[1717] = saved1717; - toggles[1702] = saved1702; - toggles[1703] = saved1703; - toggles[1698] = saved1698; + dx9rend::rendererRenderSwitch(1717) = saved1717; + dx9rend::rendererRenderSwitch(1702) = saved1702; + dx9rend::rendererRenderSwitch(1703) = saved1703; + dx9rend::rendererRenderSwitch(1698) = saved1698; staticMeshRendererSetHemiEnabled(saved1698); - toggles[1714] = saved1714; - toggles[1700] = saved1700; + dx9rend::rendererRenderSwitch(1714) = saved1714; + dx9rend::rendererRenderSwitch(1700) = saved1700; roadCompiledRendererSetHemiEnabled(saved1700); te->m_primaryHeightmap->setSeaWaterLevel(savedSeaLevel); dx9rend::rendererSetHemiRenderMode(savedRenderMode); @@ -2601,43 +3055,43 @@ void QuadPatchEditable::burnColormap(const vc71::string& base) flippedSurface->UnlockRect(); bigSurface->UnlockRect(); { - vc71::string name(path); + std::string name(path); name += "_u8888"; dx9rend::textureManagerSaveTexture(flipped, name); } { // The argument blocks are built right to left: the options, the directory, the file. const TerrainEditableString options(te->m_colormapSettings); // +0x7C8 - vc71::string outputDirectory; + std::string outputDirectory; { - const vc71::string directory = te->getColormapDirectory(); // P+0xEC - outputDirectory = ::renddx9abi::toVc71String(te->getLevelSavePath()); + const std::string directory = te->getColormapDirectory(); // P+0xEC + outputDirectory = ::renddx9abi::fromHostString(te->getLevelSavePath()); outputDirectory += directory; } - vc71::string file(path); + std::string file(path); file += "_u8888.dds"; te->runNvdxt(::renddx9abi::toHostString(file), ::renddx9abi::toHostString(outputDirectory), options); // E+0xF4 } { - vc71::string target(path); + std::string target(path); target += ".dds"; ::dice::hfe::fileManager->deleteFile(::renddx9abi::makeHostString(target)); } { - vc71::string target(path); + std::string target(path); target += ".dds"; - vc71::string source(path); + std::string source(path); source += "_u8888_.dds"; ::dice::hfe::fileManager->moveFile(::renddx9abi::makeHostString(source), ::renddx9abi::makeHostString(target)); // +0x24 } { - vc71::string input(path); + std::string input(path); input += "_u8888.dds"; ::dice::hfe::fileManager->deleteFile(::renddx9abi::makeHostString(input)); } { - vc71::string leftover(path); + std::string leftover(path); leftover += "_u8888_.dds"; ::dice::hfe::fileManager->deleteFile(::renddx9abi::makeHostString(leftover)); } diff --git a/Code/BF2/Geom/QuadPatchEditable.h b/Code/BF2/Geom/QuadPatchEditable.h index 6e7ade054..c053dc82c 100644 --- a/Code/BF2/Geom/QuadPatchEditable.h +++ b/Code/BF2/Geom/QuadPatchEditable.h @@ -8,7 +8,7 @@ #define BF2_GEOM_QUADPATCHEDITABLE_H #include "QuadPatch.h" -#include "../../RendDX9Abi/Vc71String.h" +#include #include @@ -46,6 +46,11 @@ struct PatchDetailLayer void init(QuadPatchEditable* owner, int width); // (inlined by PatchDetailLayers::init) void create(); void assertCreated(); // a logged "TBM", never a stop + // The next four are unreachable in 1.50 (no code or data references); names [INFERRED]. + void freeData(); // PE 0x1019B140: delete[] data when created + void copyFrom(const PatchDetailLayer* other); // PE 0x1019B170: byteSize bytes from other's data + void fill(unsigned char value); // PE 0x1019BD20: assertCreated, then every byte + unsigned char* byteAt(int position); // PE 0x1019BAF0: a tail jump to at() unsigned char* at(int position); void clearQuad(int x, int z); // one heightmap quad's texels to 0 float averageWeight(int x, int z); @@ -90,6 +95,9 @@ class PatchDetailLayers // clearLayerQuad) accepts layer 6, one past the six records, and only logs: the address is // answered for any layer. PatchDetailLayer* getLayer(int layer); + // PE 0x1019B280: a tail jump to getLayer. Unreachable in 1.50 (no code or data references); + // name [INFERRED]. + PatchDetailLayer* layerRecord(int layer); PatchDetailLayer records[6]; // +0x04 }; @@ -115,6 +123,10 @@ class MergedPatchDetailLayers : public PatchDetailLayers // not all created, else this set's own. (Its one caller, 0x1010B575, is an R2 brush.) PatchDetailLayer* getLayer(int layer); + // PE 0x1019B460: initializes the six records (the inlined PatchDetailLayer::init) and sets + // `source`. Unreachable in 1.50 (no code or data references); name [INFERRED]. + void initWithSource(QuadPatchEditable* owner, int width, PatchDetailLayers* sourceSet); + PatchDetailLayers* source; // +0x7C }; @@ -136,6 +148,9 @@ class QuadPatchEditable : public QuadPatch void importAllLayers(); void importLayer(int layer); // detail map channel -> weight map void rebuildLayerIndexBuffer(int layer); + // PE 0x1019B760: zeroes one layer's triangle count. Unreachable in 1.50 (no code or data + // references); name [INFERRED]. + void clearLayerTriangleCount(int layer); void rebuildLowDetailMap(); void debugTest(int value); // (nullsub_12, `retn 4`) // The technique overlays TerrainEditable::setShaderTechnique creates and releases (techniques 4 / 5 / @@ -159,15 +174,19 @@ class QuadPatchEditable : public QuadPatch void writeLayersBack(int x0, int x1, int z0, int z1, int layer); // (the layer is not read) void paintDetail(float x, float z, float radius, int strength, int layer); void drawForLightmapGeneration(); - void importBaseLayers(const vc71::string& directory); - void importLayerTile(int layer, const vc71::string& directory); - void importColormapTile(const vc71::string& directory); + void importBaseLayers(const std::string& directory); + void importLayerTile(int layer, const std::string& directory); + void importAllLayerTiles(const std::string& directory); // logs only; unreachable in 1.50 + void importColormapTile(const std::string& directory); void commitColormapEdit(); void revertLayer(int layer); void revertAllLayers(); void releaseRoadMask(); void reloadLightmap(); void paintColor(float x, float z, float radius, int strength, unsigned int color); + // PE 0x1019DC80 (`retn 14h`): a colour brush on the low-detail map (+0x48) with no overlap or + // edit-copy gates. Unreachable in 1.50 (no code or data references); name [INFERRED]. + void paintLowDetailColor(float x, float z, float radius, int strength, unsigned int color); // The two TerrainLightSampling reads. [INFERRED] names. // getFileIndices: (heightmapSize / patchSize) / 2 + grid position per axis, the "%02ix%02i" pair. // getWorldBounds: the patch's world box at height 0; only min and max are written. @@ -181,9 +200,9 @@ class QuadPatchEditable : public QuadPatch void commitAllLayers(); // R3: saving. Strings by reference (`retn 4`). [INFERRED] names. - void burnColormap(const vc71::string& base); // (`base` read only when not edited) - void saveDetailMaps(const vc71::string& suffix); - void saveLightmap(const vc71::string& base); + void burnColormap(const std::string& base); // (`base` read only when not edited) + void saveDetailMaps(const std::string& suffix); + void saveLightmap(const std::string& base); void removeCompDetailMaps(); void saveEditedColormap(); void makeCompDetailMaps(); @@ -202,7 +221,7 @@ class QuadPatchEditable : public QuadPatch int m_checkerCountV; // +0x13C int m_fileIndexX; // +0x140 gridX + patchCount / 2 - the "%02ix%02i" file name int m_fileIndexZ; // +0x144 - vc71::string m_fileName; // +0x148 "%02ix%02i" + std::string m_fileName; // +0x148 "%02ix%02i" PatchDetailLayers m_detailLayers; // +0x164 the imported weight maps PatchDetailLayers m_detailLayersEdit; // +0x1E0 the edited working copy (R2) [INFERRED] MergedPatchDetailLayers m_mergedLayers; // +0x25C source = +0x164 until its own maps exist @@ -232,6 +251,10 @@ class QuadPatchEditable : public QuadPatch QuadPatchEditable& operator=(const QuadPatchEditable&); }; +// The brushes' upper texel bound: ceil of `value` through the CRT's double ceil, chopped to int +// (QuadPatchEditable.cpp; SurroundingPatchEditable's brushes use it as well). +int ceilChop(float value); + #if defined(_M_IX86) static_assert(sizeof(PatchDetailLayer) == 0x14, "a weight map record is 20 bytes - see 0x1019B1A0"); static_assert(offsetof(PatchDetailLayer, data) == 0x08, "record data at +0x08"); @@ -240,23 +263,6 @@ static_assert(sizeof(PatchDetailLayers) == 0x7C, "six records behind a vptr"); static_assert(offsetof(PatchDetailLayers, records) == 0x04, "records at +0x04"); static_assert(sizeof(MergedPatchDetailLayers) == 0x80, "the merged set's source at +0x7C"); static_assert(offsetof(MergedPatchDetailLayers, source) == 0x7C, "source at +0x7C - QuadPatchEditable::init (0x1019F530) stores +0x2D8"); -static_assert(sizeof(QuadPatchEditable) == 0x32C, "TerrainEditable::init (0x1010ADA0) allocates 0x32C per patch"); -static_assert(offsetof(QuadPatchEditable, m_colormapEdit) == 0x120, "+0x120"); -static_assert(offsetof(QuadPatchEditable, editableTerrain) == 0x124, "+0x124"); -static_assert(offsetof(QuadPatchEditable, m_checkerLastU) == 0x128, "checker state at +0x128"); -static_assert(offsetof(QuadPatchEditable, m_fileIndexX) == 0x140, "+0x140"); -static_assert(offsetof(QuadPatchEditable, m_fileName) == 0x148, "+0x148"); -static_assert(offsetof(QuadPatchEditable, m_detailLayers) == 0x164, "+0x164"); -static_assert(offsetof(QuadPatchEditable, m_detailLayersEdit) == 0x1E0, "+0x1E0"); -static_assert(offsetof(QuadPatchEditable, m_mergedLayers) == 0x25C, "+0x25C"); -static_assert(offsetof(QuadPatchEditable, m_compDetailMap) == 0x2DC, "+0x2DC"); -static_assert(offsetof(QuadPatchEditable, m_undergrowthOverlay) == 0x2E4, "+0x2E4"); -static_assert(offsetof(QuadPatchEditable, m_roadMask) == 0x2F4, "+0x2F4 - see 0x1019F300"); -static_assert(offsetof(QuadPatchEditable, m_layerIndexBuffer) == 0x2F8, "+0x2F8"); -static_assert(offsetof(QuadPatchEditable, m_layerTriangleCount) == 0x310, "+0x310"); -static_assert(offsetof(QuadPatchEditable, m_detailMapsFromFile) == 0x328, "+0x328"); -static_assert(offsetof(QuadPatchEditable, m_importPending) == 0x329, "+0x329"); -static_assert(offsetof(QuadPatchEditable, m_colormapEdited) == 0x32A, "+0x32A"); #endif } // namespace geom diff --git a/Code/BF2/Geom/RaQuadPatchAdapter.cpp b/Code/BF2/Geom/RaQuadPatchAdapter.cpp new file mode 100644 index 000000000..73f1b0185 --- /dev/null +++ b/Code/BF2/Geom/RaQuadPatchAdapter.cpp @@ -0,0 +1,422 @@ +// Attested Geom/RaQuadPatchAdapter.cpp (retail path at PE 0x102220E0). +#ifdef BF2_IMAGE_RENDDX9 +#include "RaQuadPatchAdapter.h" +#include "MeshTemplate.h" +#include "../RendDX9/Ra/RaShader.h" +#include "../../RendDX9Abi/BfMemory.h" +#include "../../RendDX9Abi/ThunkAbi.h" +#include +#include +#include +#include +#include +#include + +#if defined(_MSC_VER) +// The UCRT exports the CRT assertion handler the shipped image calls but no longer declares it in +// . +extern "C" void __cdecl _assert(const char* expression, const char* file, unsigned line); +#endif + +namespace dice { namespace hfe { +namespace dx9rend { +void vertexBufferBindStream(void*, unsigned int); +void indexBufferBind(void*); +void vertexDeclarationBind(void*); +} +namespace geom { +namespace Ra = dx9rend::Ra; +void materialRestoreBaseVtable(void*); +void geometryCopyLightingParameters(Ra::RaLightingParameters&, const Ra::RaLightingParameters&); + +namespace { +const char kPath[] = "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\RaQuadPatchAdapter.cpp"; +const char kHeader[] = "c:\\dice\\projects\\bf2branches\\patch_1_50\\code\\bf2\\geom\\RaQuadPatchAdapter.h"; + +void check(bool value, const char* expression, const char* file, int line) +{ + if (value) + return; +#if defined(_MSC_VER) + _assert(expression, file, static_cast(line)); +#else + // [CHOSEN, not recovered] The native port has no MSVCR71 assertion dialog. + std::fprintf(stderr, "Assertion failed: %s, file %s, line %d\n", expression, file, line); + std::fflush(stderr); + std::abort(); +#endif +} + +// PE 0x101BC290. Assignment preserves each holder's binder table. +Ra::RaObjectParameters* assignObject(Ra::RaObjectParameters& d, const Ra::RaObjectParameters& s) +{ + d.registry = s.registry; + std::memcpy(d.world.value, s.world.value, 64); + std::memcpy(d.viewProjection.value, s.viewProjection.value, 64); + std::memcpy(d.worldViewProjection.value, s.worldViewProjection.value, 64); + std::memcpy(d.shadowProjMat.value, s.shadowProjMat.value, 64); + std::memcpy(d.shadowOccProjMat.value, s.shadowOccProjMat.value, 64); + std::memcpy(d.shadowTrapMat.value, s.shadowTrapMat.value, 64); + d.geomBones.a = s.geomBones.a; + d.geomBones.b = s.geomBones.b; + d.transparency.value = s.transparency.value; + std::memcpy(d.objectSpaceCamPos.value, s.objectSpaceCamPos.value, 16); + d.windSpeed.value = s.windSpeed.value; + std::memcpy(d.windDir.value, s.windDir.value, 12); + Ra::raAssignParamBytes(d.userData.value, s.userData.value); + d.heightOverTerrain.value = s.heightOverTerrain.value; + std::memcpy(d.hemiMapSkyColor.value, s.hemiMapSkyColor.value, 16); + std::memcpy(d.objectSpaceWorldUp.value, s.objectSpaceWorldUp.value, 12); + d.tail220 = s.tail220; + return &d; +} + +// PE 0x101BC5B0. The source is a constructed adapter's object block. +Ra::RaObjectParameters* copyConstructObject(Ra::RaObjectParameters& d, const Ra::RaObjectParameters& s) +{ + d.vptr = s.vptr; + d.registry = s.registry; + d.world = s.world; + d.viewProjection = s.viewProjection; + d.worldViewProjection = s.worldViewProjection; + d.shadowProjMat = s.shadowProjMat; + d.shadowOccProjMat = s.shadowOccProjMat; + d.shadowTrapMat = s.shadowTrapMat; + d.geomBones = s.geomBones; + d.transparency = s.transparency; + d.objectSpaceCamPos = s.objectSpaceCamPos; + d.windSpeed = s.windSpeed; + d.windDir = s.windDir; + d.userData.vptr = s.userData.vptr; + new (&d.userData.value) std::vector(s.userData.value); + d.heightOverTerrain = s.heightOverTerrain; + d.hemiMapSkyColor = s.hemiMapSkyColor; + d.objectSpaceWorldUp = s.objectSpaceWorldUp; + d.tail220 = s.tail220; + return &d; +} + +extern "C" int __cdecl _purecall(void); +void* RD9_THUNK adapterDestroy(void* self RD9_THUNK_EDX, unsigned char flags); + +// PE 0x101BBB50; the shader argument is consumed but never read. +bool RD9_THUNK adapterBind(void* self RD9_THUNK_EDX, void*) +{ + RaQuadPatchAdapter& a = *static_cast(self); + check(a.compactVertices != 0, "m_pCompactVertexData", kPath, 79); + check(a.indices != 0, "m_pLODIndices", kPath, 80); + check(a.declaration != 0, "m_pNewDecl", kPath, 81); + unsigned int stream = 0; + if (a.vertices) + { + dx9rend::vertexBufferBindStream(a.vertices, stream); + stream = 1; + } + dx9rend::vertexBufferBindStream(a.compactVertices, stream); + dx9rend::indexBufferBind(a.indices); + dx9rend::vertexDeclarationBind(a.declaration); + a.bound = 1; + return true; +} + +// PE 0x10051870. +int RD9_THUNK adapterVertexCount(void* s RD9_THUNK_EDX) { return static_cast(s)->vertexCount; } +// PE 0x101BC210. +int RD9_THUNK adapterIndexCount(void* s RD9_THUNK_EDX) +{ return static_cast(static_cast(static_cast(s)->primitiveCount) * 3u); } +// PE 0x101A9A10. +int RD9_THUNK adapterPrimitiveCount(void* s RD9_THUNK_EDX) { return static_cast(s)->primitiveCount; } +// PE 0x10051710. +int RD9_THUNK adapterPrimitiveType(void* s RD9_THUNK_EDX) { return static_cast(s)->primitiveType; } +// PE 0x1010DE20. +int RD9_THUNK adapterVertexStart(void* s RD9_THUNK_EDX) { return static_cast(s)->vertexStart; } +// PE 0x101C42F0. +int RD9_THUNK adapterIndexOffset(void* s RD9_THUNK_EDX) { return static_cast(s)->indexOffset; } +// PE 0x10051D70. +int RD9_THUNK adapterIndexStart(void* s RD9_THUNK_EDX) { return static_cast(s)->indexStart; } + +// PE 0x10222130 and 0x10222154: only the stream-binding slot differs. +void* const kBaseTable[9] = { + reinterpret_cast(&adapterDestroy), reinterpret_cast(&_purecall), + reinterpret_cast(&adapterVertexCount), reinterpret_cast(&adapterIndexCount), + reinterpret_cast(&adapterPrimitiveCount), reinterpret_cast(&adapterPrimitiveType), + reinterpret_cast(&adapterVertexStart), reinterpret_cast(&adapterIndexOffset), + reinterpret_cast(&adapterIndexStart) +}; +void* const kAdapterTable[9] = { + reinterpret_cast(&adapterDestroy), reinterpret_cast(&adapterBind), + reinterpret_cast(&adapterVertexCount), reinterpret_cast(&adapterIndexCount), + reinterpret_cast(&adapterPrimitiveCount), reinterpret_cast(&adapterPrimitiveType), + reinterpret_cast(&adapterVertexStart), reinterpret_cast(&adapterIndexOffset), + reinterpret_cast(&adapterIndexStart) +}; + +// PE 0x101BC260. +void* RD9_THUNK adapterDestroy(void* self RD9_THUNK_EDX, unsigned char flags) +{ + static_cast(self)->~RaQuadPatchAdapter(); + if (flags & 1) + ::renddx9abi::engineFree(self); + return self; +} + +struct Chunk +{ + RaQuadPatchAdapter adapters[64]; + int used; + // PE 0x101BC4A0, 0x101BC220, 0x101BC9C0: the default constructor (64 adapters built forward, then + // used = 0 at +0x9500) and the compiler-generated destructor (adapters destroyed in reverse) and + // copy constructor (the 64 adapters copied through PE 0x101BC930, then used). + Chunk() : used(0) {} +}; + +class Pool +{ +public: + // PE 0x101BCB50. The shipped reservation uses remainder, not division. + explicit Pool(int reservation) + { + int count = reservation % 64; + if (count < 1) + count = 1; + for (int i = 0; i != count; ++i) + appendChunk(); + reset(); + } + + // PE 0x101BCAD0. Copies a fully constructed 64-adapter chunk before destroying the temporary. + void appendChunk() + { + chunks.push_back(Chunk()); + vacant = chunks.begin(); + for (std::size_t i = 1; i < chunks.size(); ++i) + ++vacant; + } + + // PE 0x101BC1D0. + void reset() + { + for (std::list::iterator i = chunks.begin(); i != chunks.end(); ++i) + i->used = 0; + vacant = chunks.begin(); + acquired = 0; + } + + // PE 0x101BCBD0 and 0x101BCC30: the vacant-chunk walk and the slot step (used < 64 hands out + // chunk + 0x254 * used). + RaQuadPatchAdapter* acquire() + { + if (chunks.empty()) + appendChunk(); + check(vacant != chunks.end(), "m_VacantChunk != m_Chunks.end()", kHeader, 80); + if (vacant->used >= 64) + { + ++vacant; + if (vacant == chunks.end()) + appendChunk(); + } + RaQuadPatchAdapter* result = 0; + if (vacant->used < 64) + result = &vacant->adapters[vacant->used++]; + ++acquired; + check(result != 0, "t", kHeader, 59); + return result; + } + + // PE 0x101BC8B0. std::list destruction releases each chunk's array in reverse order. + std::list chunks; + std::list::iterator vacant; + unsigned int acquired; +}; + +struct Settings +{ + RaQuadPatchQueue* target; // +0x000 + RaQuadPatchAdapter adapter; // +0x004 + RaMaterialParameters* material; // +0x258 + Ra::RaObjectParameters* object; // +0x25C + Ra::RaLightingParameters lighting; // +0x260 + Ra::RaLightRecord light; // +0x370 + + // PE 0x101BC410. The light record's +0x38 word stays untouched. + Settings() + { + std::memset(&light, 0, 14 * sizeof(float)); + light.float3C = 1.0f; + light.float40 = 1.0f; + } +}; + +struct Server +{ + Pool pool; + RaQuadPatchAdapter* last; + Settings settings; + Server() : pool(64), last(0) {} +}; +Server* g_server = 0; // PE 0x1026743C + +// PE 0x101BBDD0 and the identical lazy creation arms of raQuadPatchAdapterSetSettings and +// raQuadPatchAdapterSubmit. +Server* server() +{ + if (!g_server) + { + void* storage = ::renddx9abi::engineAlloc(sizeof(Server)); + g_server = storage ? new (storage) Server : 0; + } + return g_server; +} + +// PE 0x101BC7C0. +void submit(Settings& settings, RaQuadPatchAdapter* adapter, int count, int vertices, + int type, int firstVertex, int offset, int firstIndex) +{ + *adapter = settings.adapter; + adapter->primitiveCount = count; + adapter->vertexCount = vertices; + adapter->primitiveType = type; + adapter->vertexStart = firstVertex; + adapter->indexOffset = offset; + adapter->indexStart = firstIndex; + adapter->bound = 0; + check(settings.object != 0, "geometrySettings", kPath, 123); + assignObject(adapter->object.get(), *settings.object); + dx9rend::RenderQueueEntry* entry = dx9rend::renderEntryPoolAcquire(); + entry->material = adapter; + entry->objectParameters = &adapter->object.get(); + entry->materialParameters = settings.material; + geometryCopyLightingParameters(entry->lighting, settings.lighting); + entry->shader = static_cast(raMaterialShaderSlot(*settings.material)); + *static_cast(entry->lightArray.lights.value) = settings.light; // PE 0x100FF680 + check(settings.target != 0, "targetManager", kPath, 135); + settings.target->add(entry); +} +} // anonymous namespace + +// PE 0x101BBC60. +RaQuadPatchAdapter::RaQuadPatchAdapter() + : vptr(kBaseTable), primitiveCount(0), vertexCount(0), primitiveType(4), + vertexStart(0), indexOffset(0), indexStart(0), bound(0) +{ + Ra::raObjectParametersConstruct(object.bytes); + vertices = compactVertices = indices = declaration = 0; + vptr = kAdapterTable; +} + +// PE 0x101BBCB0. +RaQuadPatchAdapter::RaQuadPatchAdapter(void* v, void* c, void* i, void* d) + : vptr(kBaseTable), primitiveCount(0), vertexCount(0), primitiveType(4), + vertexStart(0), indexOffset(0), indexStart(0), bound(0) +{ + Ra::raObjectParametersConstruct(object.bytes); + vertices = v; + vptr = kAdapterTable; + compactVertices = c; + indices = i; + declaration = d; + check(compactVertices != 0, "m_pCompactVertexData", kPath, 68); + check(indices != 0, "m_pLODIndices", kPath, 69); + check(declaration != 0, "m_pNewDecl", kPath, 70); +} + +// PE 0x101BC930. +RaQuadPatchAdapter::RaQuadPatchAdapter(const RaQuadPatchAdapter& s) + : vptr(kBaseTable), primitiveCount(s.primitiveCount), vertexCount(s.vertexCount), + primitiveType(s.primitiveType), vertexStart(s.vertexStart), indexOffset(s.indexOffset), + indexStart(s.indexStart), bound(s.bound) +{ + copyConstructObject(object.get(), s.object.get()); + vptr = kAdapterTable; + vertices = s.vertices; + compactVertices = s.compactVertices; + indices = s.indices; + declaration = s.declaration; +} + +// PE 0x101BBC10 (also 0x101BBBF0, a second copy of the same body). +RaQuadPatchAdapter::~RaQuadPatchAdapter() +{ + vptr = kBaseTable; + Ra::raObjectParametersDestroy(object.bytes); + materialRestoreBaseVtable(this); +} + +// PE 0x101BBB20: unreachable in 1.50: no code or data references. Stores the six draw-range words +// in field order (+0x04..+0x18) and clears the bound flag (+0x1C). +void RaQuadPatchAdapter::setDrawRange(int count, int vertices, int type, int firstVertex, + int offset, int firstIndex) +{ + primitiveCount = count; + vertexCount = vertices; + primitiveType = type; + vertexStart = firstVertex; + indexOffset = offset; + indexStart = firstIndex; + bound = 0; +} + +// PE 0x101BC530. +RaQuadPatchAdapter& RaQuadPatchAdapter::operator=(const RaQuadPatchAdapter& s) +{ + primitiveCount = s.primitiveCount; + vertexCount = s.vertexCount; + primitiveType = s.primitiveType; + vertexStart = s.vertexStart; + indexOffset = s.indexOffset; + indexStart = s.indexStart; + bound = s.bound; + assignObject(object.get(), s.object.get()); + vertices = s.vertices; + compactVertices = s.compactVertices; + indices = s.indices; + declaration = s.declaration; + return *this; +} + +// PE 0x101BBE20. +void raQuadPatchAdapterSetSettings(RaQuadPatchQueue* target, const RaQuadPatchAdapter& adapter, + void* material, Ra::RaObjectParameters* object, + const Ra::RaLightingParameters& lighting, const Ra::RaLightRecord& light) +{ + Settings& settings = server()->settings; + settings.target = target; + settings.adapter = adapter; + settings.object = object; + settings.material = static_cast(material); + geometryCopyLightingParameters(settings.lighting, lighting); + settings.light = light; // PE 0x100FF680 +} + +// PE 0x101BBEB0. A bound last adapter signals that the previous queued group was consumed. +void raQuadPatchAdapterSubmit(int count, int vertices, int type, int firstVertex, int offset, int firstIndex) +{ + Server* owner = server(); + if (owner->last && owner->last->bound) + owner->pool.reset(); + RaQuadPatchAdapter* adapter = owner->pool.acquire(); + owner->last = adapter; + Settings& settings = server()->settings; + submit(settings, adapter, count, vertices, type, firstVertex, offset, firstIndex); +} + +// [CHOSEN, not recovered] Source bridge for the assertion at PE 0x1018D9EA. +void raQuadPatchAdapterCheckWaterQueue(RaQuadPatchQueue* target) +{ + check(target != 0, "raShaderServer->m_specialManagers[RSMTWater]", + "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\QuadPatch.cpp", 1761); +} + +// PE 0x101BBD70. Settings lighting, prototype, pooled chunks, list storage, then the server. +void raQuadPatchAdapterServerDestroy() +{ + Server* const owner = g_server; + if (owner) + { + owner->~Server(); + ::renddx9abi::engineFree(owner); + } + g_server = 0; +} +} } } +#endif diff --git a/Code/BF2/Geom/RaQuadPatchAdapter.h b/Code/BF2/Geom/RaQuadPatchAdapter.h new file mode 100644 index 000000000..d0f03d0f6 --- /dev/null +++ b/Code/BF2/Geom/RaQuadPatchAdapter.h @@ -0,0 +1,87 @@ +// Terrain-water geometry and the pooled adapters retained by queued draws. +#ifndef BF2_GEOM_RAQUADPATCHADAPTER_H +#define BF2_GEOM_RAQUADPATCHADAPTER_H + +#include "../RendDX9/Ra/RaParameterBlocks.h" +#include + +namespace dice { namespace hfe { +namespace dx9rend { struct RenderQueueEntry; namespace Ra { struct RaLightRecord; } } +namespace geom { + +// Prefix of the hand-built render queue table (PE 0x101E1848). No C++ destructor slots. +class RaQuadPatchQueue +{ +public: + virtual void* destroy(unsigned int flags) = 0; + virtual void add(dx9rend::RenderQueueEntry* entry) = 0; +}; + +struct RaQuadPatchAdapter +{ + RaQuadPatchAdapter(); + RaQuadPatchAdapter(void* vertices, void* compactVertices, void* indices, void* declaration); + RaQuadPatchAdapter(const RaQuadPatchAdapter& source); + ~RaQuadPatchAdapter(); + RaQuadPatchAdapter& operator=(const RaQuadPatchAdapter& source); + // [INFERRED] name; PE 0x101BBB20 has no caller in 1.50 (raQuadPatchAdapterSubmit inlines the stores). + void setDrawRange(int primitiveCount, int vertexCount, int primitiveType, int vertexStart, + int indexOffset, int indexStart); + + // Manual lifetime permits the shipped object-block copy constructor, without invoking + // RaObjectParameters' unrelated default constructor on that path. + union ObjectStorage + { + alignas(dx9rend::Ra::RaObjectParameters) unsigned char bytes[sizeof(dx9rend::Ra::RaObjectParameters)]; + ObjectStorage() {} + ~ObjectStorage() {} + dx9rend::Ra::RaObjectParameters& get() + { return *reinterpret_cast(bytes); } + const dx9rend::Ra::RaObjectParameters& get() const + { return *reinterpret_cast(bytes); } + }; + + void* const* vptr; // +0x000 + int primitiveCount; // +0x004 + int vertexCount; // +0x008 + int primitiveType; // +0x00C + int vertexStart; // +0x010 + int indexOffset; // +0x014 + int indexStart; // +0x018 + unsigned char bound; // +0x01C + ObjectStorage object; // +0x020 + void* vertices; // +0x244, optional first stream + void* compactVertices; // +0x248 + void* indices; // +0x24C + void* declaration; // +0x250 +}; + +#if defined(_M_IX86) +static_assert(offsetof(RaQuadPatchAdapter, object) == 0x20, "adapter object parameters"); +// The 0x224-byte object block holds one std::vector (UserData, +0x1E4) and has that size only with +// the image's VC7.1 STL; a current MSVC x86 build checks the block without it and the tail instead. +#if defined(_MSC_VER) && _MSC_VER == 1310 +static_assert(sizeof(RaQuadPatchAdapter) == 0x254, "retail water adapter stride"); +static_assert(offsetof(RaQuadPatchAdapter, compactVertices) == 0x248, "adapter compact stream"); +#endif +static_assert(sizeof(dx9rend::Ra::RaObjectParameters) - sizeof(std::vector) == 0x224 - 0x10, + "object block without its UserData vector"); +static_assert(offsetof(RaQuadPatchAdapter, vertices) - offsetof(RaQuadPatchAdapter, object) + == sizeof(dx9rend::Ra::RaObjectParameters) + && offsetof(RaQuadPatchAdapter, compactVertices) - offsetof(RaQuadPatchAdapter, vertices) == 0x248 - 0x244 + && sizeof(RaQuadPatchAdapter) - offsetof(RaQuadPatchAdapter, vertices) == 0x254 - 0x244, + "adapter streams follow the object block - stride 0x254, see 0x101BC506"); +#endif + +// Borrowed settings are copied into the server; queued draws own their object/lighting copies. +void raQuadPatchAdapterSetSettings(RaQuadPatchQueue* target, const RaQuadPatchAdapter& adapter, + void* material, dx9rend::Ra::RaObjectParameters* object, + const dx9rend::Ra::RaLightingParameters& lighting, + const dx9rend::Ra::RaLightRecord& light); +void raQuadPatchAdapterSubmit(int primitiveCount, int vertexCount, int primitiveType, + int vertexStart, int indexOffset, int indexStart); +void raQuadPatchAdapterCheckWaterQueue(RaQuadPatchQueue* target); +void raQuadPatchAdapterServerDestroy(); + +} } } +#endif diff --git a/Code/BF2/Geom/Rain/RainManager.cpp b/Code/BF2/Geom/Rain/RainManager.cpp new file mode 100644 index 000000000..b315d6401 --- /dev/null +++ b/Code/BF2/Geom/Rain/RainManager.cpp @@ -0,0 +1,920 @@ +// RainManager, recovered from RendDX9.dll 1.50 (0x10157B30..0x1015A580 and its factory 0x100B0C25). +// Attested source path: RendDX9_r's __FILE__ for Geom/Rain/RainManager.cpp (docs/tracks/rend/ +// rdebug-findings.md). The vector operations 0x10159F90..0x1015A389 and 0x1015A4D0 are the +// std::vector instantiation behind m_particles.resize(). + +#ifdef BF2_IMAGE_RENDDX9 + +#include "../../Platform/X87Compat.h" // [CHOSEN, not recovered] x87 conversion results, including invalid inputs. +#include "../../RendDX9/RendDX9Math.h" // rendmath::normalize (sub_100777A0) +#include "RainManager.h" +#include "../../Math/Mat4.h" +#include "../../RendDX9/RendDX9Base.h" +#include "../../RendDX9/ShaderParameter.h" +#include "../../RendDX9/Texture.h" +#include "../../RendMisc/IRenderView.h" +#include "../../../RendDX9Abi/BfMemory.h" +#include "../../../RendDX9Abi/HfeAbi.h" +#include "../../../RendDX9Abi/PluginAbi.h" +#include "../../../RendDX9Abi/PluginEntry.h" + +#include +#include +#include +#include +#include + +namespace dice { +namespace hfe { + +namespace dx9rend { +extern void* g_shaderManager; // dword_1023B97C +// BufferManager.cpp / Renderer seams, declared as LightningManager.cpp declares them. +void* bufferManagerCreateVertexBuffer(unsigned int count, unsigned int stride, + unsigned int usage, const char* name); // sub_10011FF0 +void vertexBufferRelease(void* wrapper); // inline --ref, sub_10014510, free +void* vertexBufferLock(void* wrapper, unsigned int offsetVerts, unsigned int countVerts, + unsigned int flags); // sub_10014630 +bool vertexBufferUnlock(void* wrapper); // sub_10014690 +void vertexBufferBindStream(void* wrapper, unsigned int stream); // sub_100146C0 +void vertexDeclarationBind(void* wrapper); // sub_100147C0 +void rendererDrawPrimitive(unsigned int primCount, unsigned int type, + unsigned int startVertex); // sub_10005870 +} // namespace dx9rend + +namespace geom { + +// StaticMesh.cpp - the shared PE 0x10077A30 product (output = left * right). +void geometryRendererMatrixProduct(Mat4& output, const Mat4& left, const Mat4& right); + +namespace { + +const unsigned int kIID_IBase = 1u; +const unsigned int kIID_IRainManager = 0xB801DD07u; // dword_1021AEA8 + +// The box drawn per cell in render mode 2: twelve edges of two vertices. +const unsigned int kCellBoxVertexCount = 24; + +// dword_1021E6D8: the primitive type per render mode, which is also the vertex count of one +// primitive (render() advances the start vertex by type * primitives). +const unsigned int kRenderModePrimitiveType[3] = { 1u /* D3DPT_POINTLIST */, + 2u /* D3DPT_LINELIST */, + 2u /* D3DPT_LINELIST */ }; + +// The point-sprite render states setShaderConstants sets through the state manager (its +// ID3DXEffectStateManager::SetRenderState slot +0x1C). The D3D9 subset header carries no +// point-sprite enumerators, so the values are spelled here. +const unsigned int kRenderStatePointSpriteEnable = 156; // D3DRS_POINTSPRITEENABLE +const unsigned int kRenderStatePointScaleEnable = 157; // D3DRS_POINTSCALEENABLE +const unsigned int kRenderStatePointSizeMin = 155; // D3DRS_POINTSIZE_MIN +const unsigned int kRenderStatePointSizeMax = 166; // D3DRS_POINTSIZE_MAX + +// flt_10239E60, .data, pi / 180. Its only reader is updateDeviations. [INFERRED] name. +float g_rainDegreesToRadians = 0.0174532924f; + +// The rain vertex, 16 bytes: the stride createVertexBuffer asks for. The last two bytes are +// never written by any shipped builder. +struct RainVertex +{ + float x, y, z; // +0x00 cell-local position + unsigned char cell; // +0x0C cell % 32, the CELLPOSITIONS index of its draw batch + unsigned char group; // +0x0D the deviation group + unsigned char unused[2]; // +0x0E +}; + +// unk_1021E57C: POSITION float3 at 0, COLOR ubyte4 at 12. +const D3DVERTEXELEMENT9 kRainVertexElements[] = +{ + { 0, 0, D3DDECLTYPE_FLOAT3, 0, D3DDECLUSAGE_POSITION, 0 }, + { 0, 12, D3DDECLTYPE_UBYTE4, 0, D3DDECLUSAGE_COLOR, 0 }, + { 0xFF, 0, D3DDECLTYPE_UNUSED, 0, 0, 0 } +}; + +// fistp under a chop control word. +inline int truncateToInt(float value) +{ +#if defined(__APPLE__) + return bf2x87::toIntTruncate(value); +#else + return static_cast(value); +#endif +} + +// The bit pattern of a float render-state value. +inline unsigned int floatBits(float value) +{ + unsigned int bits; + std::memcpy(&bits, &value, sizeof(bits)); + return bits; +} + +// Mat4 copy (0x10030DD0) followed by the product into the original: `m = m * rhs`. +void multiplyInPlace(Mat4& m, const Mat4& rhs) +{ + const Mat4 left = m; + geometryRendererMatrixProduct(m, left, rhs); +} + +inline void writeVertex(RainVertex* vertex, float x, float y, float z, unsigned char cell, + unsigned char group) +{ + vertex->x = x; + vertex->y = y; + vertex->z = z; + vertex->cell = cell; + vertex->group = group; +} + +} // anonymous namespace + + +// Construction - 0x10159D30. The effect and the declaration are created at once; the particle +// buffer only when a particle count is set. +RainManager::RainManager() + : m_refCount(1), m_effect(0), m_vertexDeclaration(0), m_vertexBuffer(0), + m_vertexBufferCount(0), m_texture(0), m_paramWorldViewProj(0), m_paramParticleColor(0), + m_paramTexture(0), m_paramCameraPos(0), m_paramFadeOutRange(0), m_paramFadeOutDelta(0), + m_paramCellPositions(0), m_paramDeviationGroups(0), m_paramParticleSize(0), + m_paramParticleMaxSize(0), m_paramPointScale(0), m_time(0.0), m_enabled(false), + m_cellCenterFrozen(false), m_renderMode(0), m_particleSize(8.0f), + m_particleMaxSize(12.0f), m_fallSpeed(3.5f), m_fadeOutFactor(0.875f), m_lineLength(3.0f), + m_particles() +{ + m_cellCenter.x = m_cellCenter.y = m_cellCenter.z = m_cellCenter.w = 0.0f; + m_cameraOffset.x = m_cameraOffset.y = m_cameraOffset.z = 0.0f; + m_cellExtents.x = 40.0f; + m_cellExtents.y = 20.0f; + m_cellExtents.z = 40.0f; + m_pointScale.x = 1.0f; + m_pointScale.y = 0.0f; + m_pointScale.z = 0.0f; + m_particleColor.x = 1.0f; + m_particleColor.y = 1.0f; + m_particleColor.z = 1.0f; + m_particleColor.w = 0.5f; + m_fallDirection.x = 0.0f; + m_fallDirection.y = -1.0f; + m_fallDirection.z = 0.0f; + for (int i = 0; i < kCellCount; ++i) + m_cells[i].x = m_cells[i].y = m_cells[i].z = m_cells[i].w = 0.0f; + m_deviationSpeed.x = m_deviationSpeed.y = 0.0f; + m_deviationAmplitude.x = m_deviationAmplitude.y = m_deviationAmplitude.z = 0.0f; + for (int i = 0; i < kDeviationCount; ++i) + { + m_deviationOffsets[i].x = m_deviationOffsets[i].y = 0.0f; + m_deviationOffsets[i].z = m_deviationOffsets[i].w = 0.0f; + } + // m_frameTime, m_cellPrimitiveCounts and m_deviations stay unwritten, as shipped: update() + // stores the frame time before anything reads it, and setEnabled() fills the counts (through + // setRenderMode) and the deviation groups before render() can use them. + initResources(); +} + +// 0x10159EB0 (0x1015A580 deleting). The texture reference is not released: releaseResources +// leaves m_texture alone, and only setTexture drops it - shipped leak. +RainManager::~RainManager() +{ + releaseResources(); +} + +void RainManager::operator delete(void* memory) +{ + ::renddx9abi::engineFree(memory); +} + + +// The IBase quartet. + +void RainManager::addRef() +{ + ++m_refCount; +} + +int RainManager::getRef() +{ + return m_refCount; +} + +// sub_1015A4B0 (shared): at zero, the deleting destructor (slot +0x10, flag 1). +int RainManager::release() +{ + const int remaining = --m_refCount; + if (remaining == 0) + delete this; + return remaining; +} + +// IBase (1) and IID_IRainManager answer `this`. +// PE 0x1015A480. +void* RainManager::queryInterface(unsigned int iid) const +{ + if (iid == kIID_IBase) + return const_cast(this); + return iid != kIID_IRainManager ? 0 : const_cast(this); +} + + +// PE 0x101580D0. No technique is selected here; setRenderMode selects one. +bool RainManager::initResources() +{ + m_effect = static_cast( + dx9rend::shaderManagerGetEffect(dx9rend::g_shaderManager, "Shaders/Rain")); + if (!m_effect) + return false; + lookupShaderParameters(); + m_vertexDeclaration = dx9rend::vertexDeclarationCreate(kRainVertexElements); + return m_vertexDeclaration != 0; +} + +// PE 0x10157B40, in this order. +void RainManager::lookupShaderParameters() +{ + m_paramWorldViewProj = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("WORLDVIEWPROJ")); + m_paramParticleColor = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("PARTICLECOLOR")); + m_paramTexture = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("TEXTURE")); + m_paramCameraPos = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("CAMERAPOS")); + m_paramFadeOutRange = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("FADEOUTRANGE")); + m_paramFadeOutDelta = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("FADEOUTDELTA")); + m_paramCellPositions = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("CELLPOSITIONS")); + m_paramDeviationGroups = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("DEVIATIONGROUPS")); + m_paramParticleSize = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("PARTICLESIZE")); + m_paramParticleMaxSize = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("PARTICLEMAXSIZE")); + m_paramPointScale = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("POINTSCALE")); +} + +// PE 0x10157CF0, in the shipped order; every slot is nulled. +void RainManager::releaseShaderParameters() +{ + if (m_paramPointScale) + m_paramPointScale->release(); + m_paramPointScale = 0; + if (m_paramParticleSize) + m_paramParticleSize->release(); + m_paramParticleSize = 0; + if (m_paramParticleMaxSize) + m_paramParticleMaxSize->release(); + m_paramParticleMaxSize = 0; + if (m_paramDeviationGroups) + m_paramDeviationGroups->release(); + m_paramDeviationGroups = 0; + if (m_paramCellPositions) + m_paramCellPositions->release(); + m_paramCellPositions = 0; + if (m_paramFadeOutRange) + m_paramFadeOutRange->release(); + m_paramFadeOutRange = 0; + if (m_paramFadeOutDelta) + m_paramFadeOutDelta->release(); + m_paramFadeOutDelta = 0; + if (m_paramCameraPos) + m_paramCameraPos->release(); + m_paramCameraPos = 0; + if (m_paramTexture) + m_paramTexture->release(); + m_paramTexture = 0; + if (m_paramParticleColor) + m_paramParticleColor->release(); + m_paramParticleColor = 0; + if (m_paramWorldViewProj) + m_paramWorldViewProj->release(); + m_paramWorldViewProj = 0; +} + +// PE 0x10158140. The parameters, the buffer, the declaration, then the effect. +void RainManager::releaseResources() +{ + releaseShaderParameters(); + if (m_vertexBuffer) + dx9rend::vertexBufferRelease(m_vertexBuffer); + m_vertexBuffer = 0; + if (m_vertexDeclaration) + dx9rend::vertexDeclarationRelease(m_vertexDeclaration); + m_vertexDeclaration = 0; + if (m_effect) + dx9rend::effectRelease(m_effect); + m_effect = 0; +} + +// PE 0x10158220. A zero count leaves no buffer and still succeeds; a failed creation also +// clears the stored count. +bool RainManager::createVertexBuffer(unsigned int count) +{ + if (m_vertexBuffer) + { + dx9rend::vertexBufferRelease(m_vertexBuffer); + m_vertexBuffer = 0; + } + m_vertexBufferCount = count; + if (count) + { + m_vertexBuffer = dx9rend::bufferManagerCreateVertexBuffer( + count, sizeof(RainVertex), D3DUSAGE_WRITEONLY, "RainManager"); + if (!m_vertexBuffer) + { + m_vertexBufferCount = 0; + return false; + } + } + return true; +} + +// PE 0x101582D0: the low corner of one cell around its centre. +Vec3 RainManager::getCellMin() const +{ + const float sizeX = m_cellExtents.x + m_cellExtents.x; + const float sizeY = m_cellExtents.y + m_cellExtents.y; + const float sizeZ = m_cellExtents.z + m_cellExtents.z; + Vec3 corner; + corner.x = sizeX * 0.2f * -0.5f; + corner.y = sizeY * 0.2f * -0.5f; + corner.z = sizeZ * 0.2f * -0.5f; + return corner; +} + +// PE 0x10158330: the high corner of one cell around its centre. +Vec3 RainManager::getCellMax() const +{ + const float sizeX = m_cellExtents.x + m_cellExtents.x; + const float sizeY = m_cellExtents.y + m_cellExtents.y; + const float sizeZ = m_cellExtents.z + m_cellExtents.z; + Vec3 corner; + corner.x = sizeX * 0.2f * 0.5f; + corner.y = sizeY * 0.2f * 0.5f; + corner.z = sizeZ * 0.2f * 0.5f; + return corner; +} + +// PE 0x10158390. Each axis in steps of 0.001, drawing x, y, z in that order. An axis spanning +// less than 0.001 divides by zero, as shipped. +Vec3 RainManager::randomPointInBox(const Vec3& min, const Vec3& max) const +{ + const float spanX = max.x - min.x; + const float spanY = max.y - min.y; + const float spanZ = max.z - min.z; + Vec3 point; + { + const int r = std::rand(); + point.x = static_cast(r % truncateToInt(spanX * 1000.0f)) * 0.001f + min.x; + } + { + const int r = std::rand(); + point.y = static_cast(r % truncateToInt(spanY * 1000.0f)) * 0.001f + min.y; + } + { + const int r = std::rand(); + point.z = static_cast(r % truncateToInt(spanZ * 1000.0f)) * 0.001f + min.z; + } + return point; +} + +// PE 0x10158490. The box is the cell (both corners inlined); the group is drawn last. +void RainManager::initParticle(RainParticle& particle, int cell) +{ + particle.position = randomPointInBox(getCellMin(), getCellMax()); + particle.cell = cell; + particle.group = std::rand() % 16; +} + +// PE 0x10159270. Particles are spread evenly over the cells; the cells form a 6 x 6 x 6 grid +// around the cell centre, x varying fastest, then z, then y. Each cell keeps the centre's w. +void RainManager::initParticles() +{ + for (unsigned int i = 0; i < m_particles.size(); ++i) + initParticle(m_particles[i], + static_cast(i * static_cast(kCellCount) + / m_particles.size())); + + const float spanX = (m_cellExtents.x + m_cellExtents.x) * 0.2f; + const float spanY = (m_cellExtents.y + m_cellExtents.y) * 0.2f; + const float spanZ = (m_cellExtents.z + m_cellExtents.z) * 0.2f; + for (unsigned int j = 0; j < static_cast(kCellCount); ++j) + { + const float x = (static_cast(j % 6) - 2.5f) * spanX; + const float y = (static_cast(j / 36 % 6) - 2.5f) * spanY; + const float z = (static_cast(j / 6 % 6) - 2.5f) * spanZ; + Vec4& cell = m_cells[j]; + cell.w = m_cellCenter.w; + cell.z = z + m_cellCenter.z; + cell.x = x + m_cellCenter.x; + cell.y = y + m_cellCenter.y; + } +} + +// PE 0x10157DB0. Two random angles in tenths of a degree, then a random fraction of each +// non-zero amplitude axis (a zero axis draws no number). +void RainManager::initDeviations() +{ + const float* const amplitude = &m_deviationAmplitude.x; + for (int i = 0; i < kDeviationCount; ++i) + { + RainDeviation& deviation = m_deviations[i]; + deviation.angle[0] = static_cast(std::rand() % 3600) * 0.1f; + deviation.angle[1] = static_cast(std::rand() % 3600) * 0.1f; + float* const out = &deviation.amplitude.x; + for (int k = 0; k < 3; ++k) + { + if (amplitude[k] != 0.0f) + out[k] = static_cast(std::rand() % 1000) / (1000.0f / amplitude[k]); + else + out[k] = 0.0f; + } + } +} + +// PE 0x10157E70. Publishes each group's offset from its current angles, then advances the angles +// by deviationSpeed degrees per second, wrapping only above 360. +void RainManager::updateDeviations() +{ + for (int i = 0; i < kDeviationCount; ++i) + { + RainDeviation& deviation = m_deviations[i]; + Vec4& offset = m_deviationOffsets[i]; + const float angle0 = g_rainDegreesToRadians * deviation.angle[0]; + const float angle1 = g_rainDegreesToRadians * deviation.angle[1]; + offset.w = 0.0f; + offset.x = std::cos(angle0) * deviation.amplitude.x; + offset.y = std::sin(angle1) * deviation.amplitude.y; + offset.z = std::sin(angle0) * deviation.amplitude.z; + + const float next0 = static_cast(m_frameTime * m_deviationSpeed.x + deviation.angle[0]); + deviation.angle[0] = next0; + if (next0 > 360.0f) + deviation.angle[0] = next0 - 360.0f; + const float next1 = static_cast(m_frameTime * m_deviationSpeed.y + deviation.angle[1]); + deviation.angle[1] = next1; + if (next1 > 360.0f) + deviation.angle[1] = next1 - 360.0f; + } +} + +// PE 0x10158580 (unrolled nine times): every cell falls by direction * speed * frame time. The +// fourth component is advanced by speed * 0, as shipped. +void RainManager::moveCells() +{ + for (int i = 0; i < kCellCount; ++i) + { + const float frameTime = static_cast(m_frameTime); + Vec4& cell = m_cells[i]; + cell.x += m_fallDirection.x * m_fallSpeed * frameTime; + cell.y += m_fallDirection.y * m_fallSpeed * frameTime; + cell.z += m_fallDirection.z * m_fallSpeed * frameTime; + cell.w += m_fallSpeed * 0.0f * frameTime; + } +} + +// PE 0x10158A00. A cell that left the volume around the centre (extent plus half a cell on each +// side) moves by whole volume-plus-cell spans until it is back inside. A zero span with a cell +// outside never terminates, as shipped. +void RainManager::wrapCells() +{ + const float* const extents = &m_cellExtents.x; + float size[3]; + size[0] = extents[0] + extents[0]; + size[1] = extents[1] + extents[1]; + size[2] = extents[2] + extents[2]; + float span[3]; + span[0] = size[0] * 0.2f; + span[1] = size[1] * 0.2f; + span[2] = size[2] * 0.2f; + + for (int i = 0; i < kCellCount; ++i) + { + Vec4& cell = m_cells[i]; + float relative[4]; + relative[0] = cell.x - m_cellCenter.x; + relative[1] = cell.y - m_cellCenter.y; + relative[2] = cell.z - m_cellCenter.z; + relative[3] = cell.w - m_cellCenter.w; + for (int k = 0; k < 3; ++k) + { + const float half = span[k] * 0.5f; + const float upper = half + extents[k]; + if (relative[k] > upper) + { + const float step = size[k] + span[k]; + float value = relative[k]; + do + value -= step; + while (value > upper); + relative[k] = value; + } + const float lower = -extents[k] - half; + if (relative[k] < lower) + { + const float step = size[k] + span[k]; + float value = relative[k]; + do + value += step; + while (value < lower); + relative[k] = value; + } + } + cell.x = relative[0] + m_cellCenter.x; + cell.y = relative[1] + m_cellCenter.y; + cell.z = relative[2] + m_cellCenter.z; + cell.w = relative[3] + m_cellCenter.w; + } +} + +// PE 0x10157F40. Nothing in the image calls it; render() sets the same parameter inline. +void RainManager::setCellPositions(int first, int count) +{ + m_paramCellPositions->setValue(&m_cells[first], static_cast(count)); +} + +// PE 0x10158E30. Without a texture nothing is set and the draw is skipped. The world is the +// identity, so WORLDVIEWPROJ is the view-projection. +bool RainManager::setShaderConstants() +{ + if (!m_texture) + return false; + + dx9rend::stateManagerSetRenderState(kRenderStatePointSizeMin, floatBits(0.0f)); + dx9rend::stateManagerSetRenderState(kRenderStatePointSizeMax, floatBits(64.0f)); + dx9rend::stateManagerSetRenderState(kRenderStatePointScaleEnable, 1); + dx9rend::stateManagerSetRenderState(kRenderStatePointSpriteEnable, 1); + + dx9rend::IRenderView* const view = dx9rend::rendererGetRenderViewDup(); // Renderer +0x50 + Mat4 worldViewProj = Mat4::getIdentity(); + multiplyInPlace(worldViewProj, *view->getViewProjectionMatrixPtr()); // +0x84 + m_paramWorldViewProj->setValue(&worldViewProj, 0); + m_paramParticleColor->setValue(&m_particleColor, 0); + m_paramParticleSize->setFloat(m_particleSize); + m_paramParticleMaxSize->setFloat(m_particleMaxSize); + m_paramPointScale->setValue(&m_pointScale, 0); + m_paramTexture->setValue(m_texture, 0); + m_paramCameraPos->setValue(&m_cellCenter, 0); + + Vec3 fadeOutRange; + fadeOutRange.x = m_fadeOutFactor * m_cellExtents.x; + fadeOutRange.y = m_fadeOutFactor * m_cellExtents.y; + fadeOutRange.z = m_fadeOutFactor * m_cellExtents.z; + Vec3 fadeOutDelta; + fadeOutDelta.x = m_cellExtents.x - fadeOutRange.x; + fadeOutDelta.y = m_cellExtents.y - fadeOutRange.y; + fadeOutDelta.z = m_cellExtents.z - fadeOutRange.z; + m_paramFadeOutRange->setValue(&fadeOutRange, 0); + m_paramFadeOutDelta->setValue(&fadeOutDelta, 0); + m_paramDeviationGroups->setValue(m_deviationOffsets, kDeviationCount); + return true; +} + +// PE 0x10159BC0. Rebuilds the vertex buffer for the mode and selects its technique; the mode is +// stored even when it is none of the three. The line arm creates its buffer twice, as shipped. +void RainManager::setRenderMode(int mode) +{ + switch (mode) + { + case 0: + buildPointBuffer(); + dx9rend::effectSetTechniqueByName(m_effect, std::string("Point")); + break; + case 1: + createVertexBuffer(static_cast(m_particles.size() + m_particles.size())); + buildLineBuffer(); + dx9rend::effectSetTechniqueByName(m_effect, std::string("Line")); + break; + case 2: + buildCellBuffer(); + dx9rend::effectSetTechniqueByName(m_effect, std::string("Cells")); + break; + default: + break; + } + m_renderMode = mode; +} + +// PE 0x10159960. One point per particle; each cell counts its particles. +void RainManager::buildPointBuffer() +{ + std::memset(m_cellPrimitiveCounts, 0, sizeof(m_cellPrimitiveCounts)); + createVertexBuffer(static_cast(m_particles.size())); + if (!m_vertexBuffer) + return; + RainVertex* vertex = static_cast( + dx9rend::vertexBufferLock(m_vertexBuffer, 0, 0, D3DLOCK_DISCARD)); + for (unsigned int i = 0; i < m_particles.size(); ++i) + { + const RainParticle& particle = m_particles[i]; + writeVertex(vertex, particle.position.x, particle.position.y, particle.position.z, + static_cast(particle.cell % kCellsPerDraw), + static_cast(particle.group)); + ++m_cellPrimitiveCounts[particle.cell]; + ++vertex; + } + dx9rend::vertexBufferUnlock(m_vertexBuffer); +} + +// PE 0x10159A50. One streak per particle, from the particle back along the fall direction. +void RainManager::buildLineBuffer() +{ + std::memset(m_cellPrimitiveCounts, 0, sizeof(m_cellPrimitiveCounts)); + createVertexBuffer(static_cast(m_particles.size() + m_particles.size())); + if (!m_vertexBuffer) + return; + RainVertex* vertex = static_cast( + dx9rend::vertexBufferLock(m_vertexBuffer, 0, 0, D3DLOCK_DISCARD)); + for (unsigned int i = 0; i < m_particles.size(); ++i) + { + const RainParticle& particle = m_particles[i]; + writeVertex(vertex, particle.position.x, particle.position.y, particle.position.z, + static_cast(particle.cell % kCellsPerDraw), + static_cast(particle.group)); + ++vertex; + const float streakX = m_lineLength * m_fallDirection.x; + const float streakY = m_lineLength * m_fallDirection.y; + const float streakZ = m_lineLength * m_fallDirection.z; + writeVertex(vertex, particle.position.x - streakX, particle.position.y - streakY, + particle.position.z - streakZ, + static_cast(particle.cell % kCellsPerDraw), + static_cast(particle.group)); + ++m_cellPrimitiveCounts[particle.cell]; + ++vertex; + } + dx9rend::vertexBufferUnlock(m_vertexBuffer); +} + +// PE 0x10158B80. The twelve edges of one cell box for each of the 216 cells, every cell +// counting twelve lines: per y, the two z edges then the two x edges at each x / z; then the +// four y edges. +void RainManager::buildCellBuffer() +{ + if (!createVertexBuffer(kCellCount * kCellBoxVertexCount)) + return; + RainVertex* vertex = static_cast( + dx9rend::vertexBufferLock(m_vertexBuffer, 0, 0, D3DLOCK_DISCARD)); + const Vec3 cellMin = getCellMin(); + const Vec3 cellMax = getCellMax(); + Vec3 corners[2]; + corners[0] = cellMin; + corners[1] = cellMax; + + for (int i = 0; i < kCellCount; ++i) + { + m_cellPrimitiveCounts[i] = 12; + const unsigned char index = static_cast(i % kCellsPerDraw); + for (int j = 0; j < 2; ++j) + { + const float y = corners[j].y; + for (int k = 0; k < 2; ++k) + { + writeVertex(vertex++, corners[k].x, y, cellMin.z, index, 0); + writeVertex(vertex++, corners[k].x, y, cellMax.z, index, 0); + } + for (int k = 0; k < 2; ++k) + { + writeVertex(vertex++, cellMin.x, y, corners[k].z, index, 0); + writeVertex(vertex++, cellMax.x, y, corners[k].z, index, 0); + } + } + for (int j = 0; j < 2; ++j) + { + for (int k = 0; k < 2; ++k) + { + writeVertex(vertex++, corners[k].x, cellMin.y, corners[j].z, index, 0); + writeVertex(vertex++, corners[k].x, cellMax.y, corners[j].z, index, 0); + } + } + } + dx9rend::vertexBufferUnlock(m_vertexBuffer); +} + + +// PE 0x10157B30. The particle count goes through the virtual setter. +void RainManager::reset() +{ + setParticleCount(0); + m_enabled = false; +} + +// PE 0x10158DA0. Unless frozen, the cell centre follows the camera (plus the offset) even while +// disabled; the w component is kept. +void RainManager::update(double deltaTime) +{ + if (!m_cellCenterFrozen) + { + dx9rend::IRenderView* const view = dx9rend::rendererGetRenderViewDup(); // Renderer +0x50 + const Mat4* const camera = view->getViewMatrixPtr(); // +0x64 + m_cellCenter.x = camera->m[12]; + m_cellCenter.y = camera->m[13]; + m_cellCenter.z = camera->m[14]; + m_cellCenter.x = m_cameraOffset.x + m_cellCenter.x; + m_cellCenter.y = m_cameraOffset.y + m_cellCenter.y; + m_cellCenter.z = m_cameraOffset.z + m_cellCenter.z; + } + if (m_enabled) + { + m_frameTime = deltaTime; + m_time = deltaTime + m_time; + moveCells(); + updateDeviations(); + wrapCells(); + } +} + +// PE 0x10159030. The cells go to the shader 32 at a time (CELLPOSITIONS); each batch draws the +// primitives its cells counted, in buffer order. +void RainManager::render() +{ + if (!m_enabled) + return; + dx9rend::stateManagerPush(); + dx9rend::vertexDeclarationBind(m_vertexDeclaration); + dx9rend::vertexBufferBindStream(m_vertexBuffer, 0); + if (setShaderConstants()) + { + dx9rend::effectBegin(m_effect); + dx9rend::effectBeginPass(m_effect, 0); + unsigned int startVertex = 0; + int remaining = kCellCount; + const int* counts = m_cellPrimitiveCounts; + const Vec4* cells = m_cells; + do + { + const int batch = remaining < kCellsPerDraw ? remaining : kCellsPerDraw; + m_paramCellPositions->setValue(cells, static_cast(batch)); + unsigned int primitives = 0; + for (int i = 0; i < batch; ++i) + primitives += static_cast(counts[i]); + dx9rend::rendererDrawPrimitive(primitives, kRenderModePrimitiveType[m_renderMode], + startVertex); + startVertex += kRenderModePrimitiveType[m_renderMode] * primitives; + cells += kCellsPerDraw; + counts += kCellsPerDraw; + remaining -= kCellsPerDraw; + } + while (remaining > 0); + dx9rend::effectEnd(m_effect); + } + dx9rend::stateManagerPop(); +} + + +// The properties. + +// PE 0x10159D00. Enabling re-scatters the particles, rolls the deviations and rebuilds the +// buffer for the current mode; disabling keeps everything. +void RainManager::setEnabled(bool enabled) +{ + m_enabled = enabled; + if (enabled) + { + initParticles(); + initDeviations(); + setRenderMode(m_renderMode); + } +} +bool RainManager::getEnabled() const { return m_enabled; } + +// PE 0x101581B0. +void RainManager::setTexture(const std::string& name) +{ + if (m_texture) + dx9rend::textureReleaseRef(m_texture); + m_texture = 0; + if (!name.empty()) + m_texture = static_cast( + dx9rend::textureManagerGetTexture(std::string(name.c_str()))); +} + +// PE 0x10159F00. VC7.1's clear() frees the storage (the listing's free plus three zeroed +// pointers). +void RainManager::setParticleCount(unsigned int count) +{ + if (createVertexBuffer(count)) + m_particles.resize(count); + else + m_particles.clear(); +} +unsigned int RainManager::getParticleCount() const +{ + return static_cast(m_particles.size()); +} + +// PE 0x10159240. Freezes the centre first. +void RainManager::setCellCenter(const Vec4& center) +{ + m_cellCenterFrozen = true; + m_cellCenter.x = center.x; + m_cellCenter.y = center.y; + m_cellCenter.z = center.z; + m_cellCenter.w = center.w; +} +const Vec4& RainManager::getCellCenter() const { return m_cellCenter; } + +// PE 0x10159220. +void RainManager::setCameraOffset(const Vec3& offset) +{ + m_cameraOffset.x = offset.x; + m_cameraOffset.y = offset.y; + m_cameraOffset.z = offset.z; +} +const Vec3& RainManager::getCameraOffset() const { return m_cameraOffset; } + +// PE 0x10159140. +void RainManager::setCellExtents(const Vec3& extents) +{ + m_cellExtents.x = extents.x; + m_cellExtents.y = extents.y; + m_cellExtents.z = extents.z; +} +const Vec3& RainManager::getCellExtents() const { return m_cellExtents; } + +// PE 0x101591C0. +void RainManager::setPointScale(const Vec3& scale) +{ + m_pointScale.x = scale.x; + m_pointScale.y = scale.y; + m_pointScale.z = scale.z; +} +const Vec3& RainManager::getPointScale() const { return m_pointScale; } + +// PE 0x10159170. +void RainManager::setParticleColor(const Vec4& color) +{ + m_particleColor.x = color.x; + m_particleColor.y = color.y; + m_particleColor.z = color.z; + m_particleColor.w = color.w; +} +const Vec4& RainManager::getParticleColor() const { return m_particleColor; } + +// PE 0x10157FA0. +void RainManager::setParticleSize(float size) { m_particleSize = size; } +float RainManager::getParticleSize() const { return m_particleSize; } + +// PE 0x101580B0. +void RainManager::setParticleMaxSize(float size) { m_particleMaxSize = size; } +float RainManager::getParticleMaxSize() const { return m_particleMaxSize; } + +// PE 0x101591F0. +void RainManager::setFallDirection(const Vec3& direction) +{ + m_fallDirection.x = direction.x; + m_fallDirection.y = direction.y; + m_fallDirection.z = direction.z; + rendmath::normalize(m_fallDirection); +} +const Vec3& RainManager::getFallDirection() const { return m_fallDirection; } + +// PE 0x10157FC0. +void RainManager::setFallSpeed(float speed) { m_fallSpeed = speed; } +float RainManager::getFallSpeed() const { return m_fallSpeed; } + +// PE 0x10157FE0. +void RainManager::setFadeOutFactor(float factor) { m_fadeOutFactor = factor; } +float RainManager::getFadeOutFactor() const { return m_fadeOutFactor; } + +// PE 0x10158B50. +void RainManager::setDeviationAmplitude(const Vec3& amplitude) +{ + m_deviationAmplitude.x = amplitude.x; + m_deviationAmplitude.y = amplitude.y; + m_deviationAmplitude.z = amplitude.z; + initDeviations(); +} +const Vec3& RainManager::getDeviationAmplitude() const { return m_deviationAmplitude; } + +// PE 0x101591A0. +void RainManager::setDeviationSpeed(const Vec2& speed) +{ + m_deviationSpeed.x = speed.x; + m_deviationSpeed.y = speed.y; +} +const Vec2& RainManager::getDeviationSpeed() const { return m_deviationSpeed; } + +// PE 0x10158010. +void RainManager::setCellCenterFrozen(bool frozen) { m_cellCenterFrozen = frozen; } +bool RainManager::getCellCenterFrozen() const { return m_cellCenterFrozen; } + +// PE 0x10159CC0. +void RainManager::setDrawCells(bool draw) { setRenderMode(draw ? 2 : 0); } +bool RainManager::getDrawCells() const { return m_renderMode == 2; } + +// PE 0x10159CE0. +void RainManager::setDrawLines(bool draw) { setRenderMode(draw ? 1 : 0); } +bool RainManager::getDrawLines() const { return m_renderMode == 1; } + +// PE 0x10158090. +void RainManager::setLineLength(float length) { m_lineLength = length; } +float RainManager::getLineLength() const { return m_lineLength; } + + +// 0x100B0C25: an aggregate outer is refused; a failed query releases the new object. +IBase* __fastcall createRainManager(unsigned int iid, IBase* outer) +{ + if (outer) + return 0; + void* const storage = ::renddx9abi::engineAlloc(sizeof(RainManager)); + RainManager* const self = storage ? new (storage) RainManager() : 0; + void* const itf = self->queryInterface(iid); + if (!itf) + self->release(); + return static_cast(itf); +} + +} // namespace geom +} // namespace hfe +} // namespace dice + +#endif // BF2_IMAGE_RENDDX9 diff --git a/Code/BF2/Geom/Rain/RainManager.h b/Code/BF2/Geom/Rain/RainManager.h new file mode 100644 index 000000000..ab36b75ec --- /dev/null +++ b/Code/BF2/Geom/Rain/RainManager.h @@ -0,0 +1,268 @@ +// Camera-following rain: 216 particle cells (a 6 x 6 x 6 grid) centred on the camera, drawn with +// Shaders/Rain as point sprites, streak lines or debug cell boxes. Each particle belongs to one +// cell and one of 16 wind deviation groups; the shader adds the cell position and the group's +// deviation to the particle's cell-local position. The renderer resets it before each level load, +// updates it every frame and draws it after the weather in the transparent pass. +// [INFERRED] header placement beside the attested Geom/Rain/RainManager.cpp, and every method +// name: RendDX9.dll has no symbol or console string for the class, and no shipped image calls +// any slot past +0x1C, so rain stays disabled in a 1.50 session. + +#ifndef BF2_GEOM_RAIN_RAINMANAGER_H +#define BF2_GEOM_RAIN_RAINMANAGER_H + +#ifdef BF2_IMAGE_RENDDX9 + +#include "../../Core/IBase.h" +#include "../../Math/Vec3.h" // Vec2, Vec3, Vec4 + +#include +#include + +namespace dice { +namespace hfe { + +namespace dx9rend { +class Effect; +class ShaderParameter; +struct EngineTexture; +} + +namespace geom { + +// The rain interface, vtable 0x1021E5A8 (45 slots, all pure but the destructor 0x10157B00). +// IID 0xB801DD07, class id 822323013, singleton "RainManager" (dword_1024B92C). +class IRainManager : public IBase +{ +public: + virtual ~IRainManager() {} // +0x10 + + // Drops every particle and disables the rain (Renderer::handleLevelPreLoad). + virtual void reset() = 0; // +0x14 + // Moves the cell grid to the camera and, while enabled, advances the rain by `deltaTime` + // seconds (Renderer::update). + virtual void update(double deltaTime) = 0; // +0x18 + // Draws the rain while enabled (the renderer's transparent pass). + virtual void render() = 0; // +0x1C + + // Enabling scatters the particles over the cells, rolls new deviation groups and rebuilds + // the vertex buffer for the current render mode. + virtual void setEnabled(bool enabled) = 0; // +0x20 + virtual bool getEnabled() const = 0; // +0x24 + // Releases the current texture; a non-empty name loads the new one. + virtual void setTexture(const std::string& name) = 0; // +0x28 + // Recreates the vertex buffer for `count` particles and resizes the particle list; a failed + // buffer creation frees the list instead. + virtual void setParticleCount(unsigned int count) = 0; // +0x2C + virtual unsigned int getParticleCount() const = 0; // +0x30 + // Places the grid explicitly and stops update() from following the camera. + virtual void setCellCenter(const Vec4& center) = 0; // +0x34 + virtual const Vec4& getCellCenter() const = 0; // +0x38 + // Added to the camera position when the grid follows the camera. + virtual void setCameraOffset(const Vec3& offset) = 0; // +0x3C + virtual const Vec3& getCameraOffset() const = 0; // +0x40 + // Half the size of the rain volume; one cell spans 0.4 times it on each axis. + virtual void setCellExtents(const Vec3& extents) = 0; // +0x44 + virtual const Vec3& getCellExtents() const = 0; // +0x48 + virtual void setPointScale(const Vec3& scale) = 0; // +0x4C (POINTSCALE) + virtual const Vec3& getPointScale() const = 0; // +0x50 + virtual void setParticleColor(const Vec4& color) = 0; // +0x54 (PARTICLECOLOR) + virtual const Vec4& getParticleColor() const = 0; // +0x58 + virtual void setParticleSize(float size) = 0; // +0x5C (PARTICLESIZE) + virtual float getParticleSize() const = 0; // +0x60 + virtual void setParticleMaxSize(float size) = 0; // +0x64 (PARTICLEMAXSIZE) + virtual float getParticleMaxSize() const = 0; // +0x68 + // Stored normalized. + virtual void setFallDirection(const Vec3& direction) = 0; // +0x6C + virtual const Vec3& getFallDirection() const = 0; // +0x70 + virtual void setFallSpeed(float speed) = 0; // +0x74 + virtual float getFallSpeed() const = 0; // +0x78 + // The fraction of the extents where the fade-out starts (FADEOUTRANGE / FADEOUTDELTA). + virtual void setFadeOutFactor(float factor) = 0; // +0x7C + virtual float getFadeOutFactor() const = 0; // +0x80 + // Rolls new deviation groups with the new amplitude. + virtual void setDeviationAmplitude(const Vec3& amplitude) = 0; // +0x84 + virtual const Vec3& getDeviationAmplitude() const = 0; // +0x88 + // Degrees per second of the two deviation angles. + virtual void setDeviationSpeed(const Vec2& speed) = 0; // +0x8C + virtual const Vec2& getDeviationSpeed() const = 0; // +0x90 + virtual void setCellCenterFrozen(bool frozen) = 0; // +0x94 + virtual bool getCellCenterFrozen() const = 0; // +0x98 + // true selects the cell boxes (mode 2), false the points (mode 0). + virtual void setDrawCells(bool draw) = 0; // +0x9C + virtual bool getDrawCells() const = 0; // +0xA0 + // true selects the streak lines (mode 1), false the points (mode 0). + virtual void setDrawLines(bool draw) = 0; // +0xA4 + virtual bool getDrawLines() const = 0; // +0xA8 + // The length of a streak line along the fall direction. + virtual void setLineLength(float length) = 0; // +0xAC + virtual float getLineLength() const = 0; // +0xB0 +}; + +// One particle, 20 bytes on x86: its position inside its cell, the cell and the deviation group. +struct RainParticle +{ + // [CHOSEN, not recovered] The shipped resize value (split tail 0x10159F43) zeroes only the + // position and leaves cell and group as stack garbage, which buildPointBuffer would use as an + // index into m_cellPrimitiveCounts. They are zeroed here. + RainParticle() : cell(0), group(0) { position.x = position.y = position.z = 0.0f; } + + Vec3 position; // +0x00 + int cell; // +0x0C 0..215 + int group; // +0x10 0..15, the deviation group +}; + +// One deviation group, 20 bytes: two angles in degrees and the per-axis amplitude. +struct RainDeviation +{ + float angle[2]; // +0x00 + Vec3 amplitude; // +0x08 per axis: a random fraction of the deviation amplitude +}; + +// RainManager - 0x1408 bytes, vtable 0x1021E6F0, constructor 0x10159D30, factory 0x100B0C25. +class RainManager : public IRainManager +{ +public: + enum { kCellCount = 216, kDeviationCount = 16, kCellsPerDraw = 32 }; + + RainManager(); // 0x10159D30 + virtual ~RainManager(); // 0x10159EB0 / 0x1015A580 + + virtual void addRef(); // 0x1000CB20 (folded) + virtual int getRef(); // 0x101A9A10 (folded) + virtual int release(); // 0x1015A4B0 (folded) + virtual void* queryInterface(unsigned int iid) const; // 0x1015A480 + + virtual void reset(); // 0x10157B30 + virtual void update(double deltaTime); // 0x10158DA0 + virtual void render(); // 0x10159030 + + virtual void setEnabled(bool enabled); // 0x10159D00 + virtual bool getEnabled() const; // 0x10157F70 + virtual void setTexture(const std::string& name); // 0x101581B0 + virtual void setParticleCount(unsigned int count); // 0x10159F00 + virtual unsigned int getParticleCount() const; // 0x101582A0 + virtual void setCellCenter(const Vec4& center); // 0x10159240 + virtual const Vec4& getCellCenter() const; // 0x10158080 + virtual void setCameraOffset(const Vec3& offset); // 0x10159220 + virtual const Vec3& getCameraOffset() const; // 0x10158070 + virtual void setCellExtents(const Vec3& extents); // 0x10159140 + virtual const Vec3& getCellExtents() const; // 0x10157F80 + virtual void setPointScale(const Vec3& scale); // 0x101591C0 + virtual const Vec3& getPointScale() const; // 0x10158050 + virtual void setParticleColor(const Vec4& color); // 0x10159170 + virtual const Vec4& getParticleColor() const; // 0x10157F90 + virtual void setParticleSize(float size); // 0x10157FA0 + virtual float getParticleSize() const; // 0x10157FB0 + virtual void setParticleMaxSize(float size); // 0x101580B0 + virtual float getParticleMaxSize() const; // 0x101580C0 + virtual void setFallDirection(const Vec3& direction); // 0x101591F0 + virtual const Vec3& getFallDirection() const; // 0x10158060 + virtual void setFallSpeed(float speed); // 0x10157FC0 + virtual float getFallSpeed() const; // 0x10157FD0 + virtual void setFadeOutFactor(float factor); // 0x10157FE0 + virtual float getFadeOutFactor() const; // 0x10157FF0 + virtual void setDeviationAmplitude(const Vec3& amplitude); // 0x10158B50 + virtual const Vec3& getDeviationAmplitude() const; // 0x10157DA0 + virtual void setDeviationSpeed(const Vec2& speed); // 0x101591A0 + virtual const Vec2& getDeviationSpeed() const; // 0x10158000 + virtual void setCellCenterFrozen(bool frozen); // 0x10158010 + virtual bool getCellCenterFrozen() const; // 0x10158020 + virtual void setDrawCells(bool draw); // 0x10159CC0 + virtual bool getDrawCells() const; // 0x10158030 + virtual void setDrawLines(bool draw); // 0x10159CE0 + virtual bool getDrawLines() const; // 0x10158040 + virtual void setLineLength(float length); // 0x10158090 + virtual float getLineLength() const; // 0x101580A0 + + // The engine heap: the factory allocates with engineAlloc and the deleting destructor frees + // with engineFree (0x1015A580 -> sub_1005F360). + static void operator delete(void* memory); + +private: + RainManager(const RainManager&); + RainManager& operator=(const RainManager&); + + bool initResources(); // 0x101580D0 + void lookupShaderParameters(); // 0x10157B40 + void releaseShaderParameters(); // 0x10157CF0 + void releaseResources(); // 0x10158140 + bool createVertexBuffer(unsigned int count); // 0x10158220 + Vec3 getCellMin() const; // 0x101582D0 + Vec3 getCellMax() const; // 0x10158330 + Vec3 randomPointInBox(const Vec3& min, const Vec3& max) const; // 0x10158390 + void initParticle(RainParticle& particle, int cell); // 0x10158490 + void initParticles(); // 0x10159270 + void initDeviations(); // 0x10157DB0 + void updateDeviations(); // 0x10157E70 + void moveCells(); // 0x10158580 + void wrapCells(); // 0x10158A00 + void setCellPositions(int first, int count); // 0x10157F40 + bool setShaderConstants(); // 0x10158E30 + void setRenderMode(int mode); // 0x10159BC0 + void buildPointBuffer(); // 0x10159960 + void buildLineBuffer(); // 0x10159A50 + void buildCellBuffer(); // 0x10158B80 + + // data, in shipped order + int m_refCount; // +0x04 + dx9rend::Effect* m_effect; // +0x08 "Shaders/Rain" + void* m_vertexDeclaration; // +0x0C + void* m_vertexBuffer; // +0x10 16-byte vertices + unsigned int m_vertexBufferCount; // +0x14 + dx9rend::EngineTexture* m_texture; // +0x18 + dx9rend::ShaderParameter* m_paramWorldViewProj; // +0x1C WORLDVIEWPROJ + dx9rend::ShaderParameter* m_paramParticleColor; // +0x20 PARTICLECOLOR + dx9rend::ShaderParameter* m_paramTexture; // +0x24 TEXTURE + dx9rend::ShaderParameter* m_paramCameraPos; // +0x28 CAMERAPOS + dx9rend::ShaderParameter* m_paramFadeOutRange; // +0x2C FADEOUTRANGE + dx9rend::ShaderParameter* m_paramFadeOutDelta; // +0x30 FADEOUTDELTA + dx9rend::ShaderParameter* m_paramCellPositions; // +0x34 CELLPOSITIONS + dx9rend::ShaderParameter* m_paramDeviationGroups; // +0x38 DEVIATIONGROUPS + dx9rend::ShaderParameter* m_paramParticleSize; // +0x3C PARTICLESIZE + dx9rend::ShaderParameter* m_paramParticleMaxSize; // +0x40 PARTICLEMAXSIZE + dx9rend::ShaderParameter* m_paramPointScale; // +0x44 POINTSCALE + double m_time; // +0x48 the rain clock + double m_frameTime; // +0x50 the last update's deltaTime; + // written before every read + bool m_enabled; // +0x58 + bool m_cellCenterFrozen; // +0x59 + int m_renderMode; // +0x5C 0 points, 1 lines, 2 cells + Vec4 m_cellCenter; // +0x60 CAMERAPOS + Vec3 m_cameraOffset; // +0x70 + Vec3 m_cellExtents; // +0x7C (40, 20, 40) + Vec3 m_pointScale; // +0x88 (1, 0, 0) + Vec4 m_particleColor; // +0x94 (1, 1, 1, 0.5) + float m_particleSize; // +0xA4 8 + float m_particleMaxSize; // +0xA8 12 + Vec3 m_fallDirection; // +0xAC (0, -1, 0) + float m_fallSpeed; // +0xB8 3.5 + float m_fadeOutFactor; // +0xBC 0.875 + Vec4 m_cells[kCellCount]; // +0xC0 CELLPOSITIONS + int m_cellPrimitiveCounts[kCellCount]; // +0xE40 + float m_lineLength; // +0x11A0 3 + Vec2 m_deviationSpeed; // +0x11A4 (0, 0) + Vec3 m_deviationAmplitude; // +0x11AC (0, 0, 0) + RainDeviation m_deviations[kDeviationCount]; // +0x11B8 + Vec4 m_deviationOffsets[kDeviationCount]; // +0x12F8 DEVIATIONGROUPS + std::vector m_particles; // +0x13F8 +}; + +// dword_1024B92C. ModuleGeom.cpp owns the definition. +extern IBase* g_RainManager; + +// The factory registered under "dice.hfe.geom.RainManager" (0x100B0C25). +IBase* __fastcall createRainManager(unsigned int iid, IBase* outer); + +// The renderer caches the "RainManager" singleton as an untyped pointer (Renderer +0x5D8). +// The interface derives from IBase first, so the conversion adjusts nothing. +inline IRainManager* asRainManager(void* singleton) +{ + return static_cast(static_cast(singleton)); +} + +} // namespace geom +} // namespace hfe +} // namespace dice + +#endif // BF2_IMAGE_RENDDX9 +#endif // BF2_GEOM_RAIN_RAINMANAGER_H diff --git a/Code/BF2/Geom/RoadCompiled.cpp b/Code/BF2/Geom/RoadCompiled.cpp index 8834e69ea..2b19bd56f 100644 --- a/Code/BF2/Geom/RoadCompiled.cpp +++ b/Code/BF2/Geom/RoadCompiled.cpp @@ -3,13 +3,23 @@ #ifdef BF2_IMAGE_RENDDX9 +#if !defined(_MSC_VER) +// [CHOSEN, not recovered] Compiler-typed native table entries. +#include "../../RendDX9Abi/NativeVtable.h" +#include "IRoadEditable.h" +#include +#endif +#include "../../RendDX9Abi/ThunkAbi.h" #include "RoadCompiled.h" #include "RoadCompiledTemplate.h" #include "QuadPatch.h" // TerrainCuller (Terrain::m_culler's type) #include "Terrain.h" // terrain() - the "Terrain" singleton (dword_1024B930) +#include "../GeomMisc/Debug.h" #include "../Math/Frustum.h" +#include "../RendDX9/RendDX9Math.h" // the RendDX9.dll Math copies +#include "../Platform/X87Compat.h" // [CHOSEN, not recovered] the x87 chunk distance (updateChunkVisibility) #include "../RendMisc/IRenderView.h" #include "../RendDX9/RendDX9Base.h" // rendererGetRenderView, the ABI host stream typedefs #include "../../RendDX9Abi/BfMemory.h" @@ -18,9 +28,10 @@ #include "../../RendDX9Abi/ModuleCommon.h" // RD9_IID_IBASE #include "../../RendDX9Abi/PluginAbi.h" #include "../../RendDX9Abi/PluginEntry.h" -#include "../../RendDX9Abi/Vc71String.h" +#include #include +#include #include namespace dice { @@ -34,7 +45,7 @@ extern IBase* g_Renderer; // dword_1023D098 - BF2Render.cpp (the Renderer // BufferManager.cpp / StateManager.cpp, declared per TU as every other client does. void* createVertexBuffer(void* bufferManager, unsigned int count, unsigned int stride, - const vc71::string& name, unsigned int usage); + const std::string& name, unsigned int usage); void* bufferManagerCreateIndexBuffer(unsigned int count, unsigned int usage, unsigned int format); void* vertexBufferLock(void* wrapper, unsigned int offsetVerts, unsigned int countVerts, @@ -77,57 +88,71 @@ static_assert(sizeof(RoadCompiledVertex) == 32, "loadMesh creates the buffer wit // Renderer +0x6A4, `drawRoads` - VideoOptions::apply's terrain-quality arm writes it (0 at quality 1, // 1 at 2 and 3) and renderFrame's road block tests it. addToRenderQueue reads it through g_Renderer -// (`mov eax, g_Renderer; cmp byte ptr [eax+6A4h], 0`), unguarded. A RendDX9-internal field of the -// same image, read at its shipped offset (the XpLightManager.cpp precedent for renderer fields). +// (`mov eax, g_Renderer; cmp byte ptr [eax+6A4h], 0`), unguarded. Read through BF2Render.cpp's +// render-switch accessor, keyed by that retail offset. bool rendererDrawRoads() { - return static_cast(static_cast(dx9rend::g_Renderer))[0x6A4] != 0; + return dx9rend::rendererRenderSwitch(0x6A4) != 0; } RoadCompiled* fromGeometry(void* subobject) { - return reinterpret_cast(static_cast(subobject) - 4); + return reinterpret_cast(static_cast(subobject) + - offsetof(RoadCompiled, m_geometry)); // retail +4 } // THE IRoad table, seven slots. MSVC will not make a free function __thiscall; a // __fastcall with an unused EDX is the same convention for these slots. -int __fastcall rc_addRef(void* self, void*) +int RD9_THUNK rc_addRef(void* self RD9_THUNK_EDX) { return static_cast(self)->addRef(); } -int __fastcall rc_getRef(void* self, void*) +int RD9_THUNK rc_getRef(void* self RD9_THUNK_EDX) { return static_cast(self)->getRef(); } -int __fastcall rc_release(void* self, void*) +int RD9_THUNK rc_release(void* self RD9_THUNK_EDX) { return static_cast(self)->release(); } -void* __fastcall rc_queryInterface(void* self, void*, unsigned int iid) +void* RD9_THUNK rc_queryInterface(void* self RD9_THUNK_EDX, unsigned int iid) { return static_cast(self)->queryInterface(iid); } // +0x10, 0x1015AD30 - `ret`. [UNRESOLVED] role; nothing recovered calls it. -void __fastcall rc_slot10(void*, void*) +void RD9_THUNK rc_slot10(void* RD9_THUNK_EDX) { } -void __fastcall rc_updateChunkVisibility(void* self, void*, const Frustum* frustum) +void RD9_THUNK rc_updateChunkVisibility(void* self RD9_THUNK_EDX, const Frustum* frustum) { static_cast(self)->updateChunkVisibility(frustum); } -bool __fastcall rc_anyChunkVisible(void* self, void*) +bool RD9_THUNK rc_anyChunkVisible(void* self RD9_THUNK_EDX) { return static_cast(self)->anyChunkVisible(); } +#if !defined(_MSC_VER) +// [CHOSEN, not recovered] Match the shared consumer interface under the native ABI. +void* const kRoadVtable[] = +{ + BF2_NATIVE_SLOT(::dice::hfe::geom::IRoad, addRef, rc_addRef), + BF2_NATIVE_SLOT(::dice::hfe::geom::IRoad, getRef, rc_getRef), + BF2_NATIVE_SLOT(::dice::hfe::geom::IRoad, release, rc_release), + BF2_NATIVE_SLOT(::dice::hfe::geom::IRoad, queryInterface, rc_queryInterface), + BF2_NATIVE_SLOT(::dice::hfe::geom::IRoad, draw, rc_slot10), + BF2_NATIVE_SLOT(::dice::hfe::geom::IRoad, updateChunkVisibility, rc_updateChunkVisibility), + BF2_NATIVE_SLOT(::dice::hfe::geom::IRoad, anyChunkVisible, rc_anyChunkVisible), +}; +#else void* const kRoadVtable[7] = { reinterpret_cast(&rc_addRef), // +0x00 (shared with StaticMesh) @@ -138,99 +163,177 @@ void* const kRoadVtable[7] = reinterpret_cast(&rc_updateChunkVisibility), // +0x14 reinterpret_cast(&rc_anyChunkVisible) // +0x18 }; +#endif // THE IGeometry table, 0x1021E8E8 - 62 slots, `this` = the subobject at +4. The four IBase entries // are MSVC adjustor thunks (`sub ecx, 4; jmp `); every other entry that is not this // class's own body is one of the image-wide default bodies, each read: its `retn N` fixes the arity. -int __fastcall rg_addRef(void* self, void*) +int RD9_THUNK rg_addRef(void* self RD9_THUNK_EDX) { return fromGeometry(self)->addRef(); } -int __fastcall rg_getRef(void* self, void*) +int RD9_THUNK rg_getRef(void* self RD9_THUNK_EDX) { return fromGeometry(self)->getRef(); } -int __fastcall rg_release(void* self, void*) +int RD9_THUNK rg_release(void* self RD9_THUNK_EDX) { return fromGeometry(self)->release(); } -void* __fastcall rg_queryInterface(void* self, void*, unsigned int iid) +void* RD9_THUNK rg_queryInterface(void* self RD9_THUNK_EDX, unsigned int iid) { return fromGeometry(self)->queryInterface(iid); } -void __fastcall rg_emptyNoArgs(void*, void*) { } // 0x10037D40 `ret` -void __fastcall rg_emptyOneArg(void*, void*, int) { } // 0x100E13B0 `retn 4` -void __fastcall rg_emptyTwoArgs(void*, void*, int, int) { } // 0x100E1480 `retn 8` -void __fastcall rg_emptyThreeArgs(void*, void*, int, int, int) { } // 0x10083AB0 `retn 0Ch` -void __fastcall rg_emptySixArgs(void*, void*, int, int, int, int, int, int) { } // 0x10082D20 `retn 18h` -int __fastcall rg_returnsZero(void*, void*) { return 0; } -int __fastcall rg_returnsZeroOneArg(void*, void*, int) { return 0; } // 0x10088060 `retn 4` -bool __fastcall rg_returnsFalse(void*, void*) { return false; } -bool __fastcall rg_returnsFalseOneArg(void*, void*, int) { return false; } // 0x1005DA00 `retn 4` -int __fastcall rg_returnsOne(void*, void*) { return 1; } -int __fastcall rg_returnsMinusOne(void*, void*) { return -1; } -int __fastcall rg_returnsSeven(void*, void*) { return 7; } -float __fastcall rg_returnsMinusOneF(void*, void*) { return -1.0f; } // 0x10082D10 `fld -1.0` +void RD9_THUNK rg_emptyNoArgs(void* RD9_THUNK_EDX) { } // 0x10037D40 `ret` +void RD9_THUNK rg_emptyOneArg(void* RD9_THUNK_EDX, int) { } // 0x100E13B0 `retn 4` +void RD9_THUNK rg_emptyTwoArgs(void* RD9_THUNK_EDX, int, int) { } // 0x100E1480 `retn 8` +void RD9_THUNK rg_emptyThreeArgs(void* RD9_THUNK_EDX, int, int, int) { } // 0x10083AB0 `retn 0Ch` +void RD9_THUNK rg_emptySixArgs(void* RD9_THUNK_EDX, int, int, int, int, int, int) { } // 0x10082D20 `retn 18h` +// The two zero bodies also fill pointer slots (+0x28 the light record, +0xA4 the root object, +0xCC the +// next geometry), so the zero is pointer-sized: the same `xor eax, eax` on x86, all of RAX on x64. +std::uintptr_t RD9_THUNK rg_returnsZero(void* RD9_THUNK_EDX) { return 0; } +std::uintptr_t RD9_THUNK rg_returnsZeroOneArg(void* RD9_THUNK_EDX, int) { return 0; } // 0x10088060 `retn 4` +bool RD9_THUNK rg_returnsFalse(void* RD9_THUNK_EDX) { return false; } +bool RD9_THUNK rg_returnsFalseOneArg(void* RD9_THUNK_EDX, int) { return false; } // 0x1005DA00 `retn 4` +int RD9_THUNK rg_returnsOne(void* RD9_THUNK_EDX) { return 1; } +int RD9_THUNK rg_returnsMinusOne(void* RD9_THUNK_EDX) { return -1; } +int RD9_THUNK rg_returnsSeven(void* RD9_THUNK_EDX) { return 7; } +float RD9_THUNK rg_returnsMinusOneF(void* RD9_THUNK_EDX) { return -1.0f; } // 0x10082D10 `fld -1.0` // +0x18, (`retn 0Ch`) - the ObjectDrawer's deferred pass passes (renderView, occluder, 1); // the body reads none of the three. -void __fastcall rg_addToRenderQueue(void* self, void*, void*, void*, int) +void RD9_THUNK rg_addToRenderQueue(void* self RD9_THUNK_EDX, void*, void*, int) { fromGeometry(self)->addToRenderQueue(); } // +0x34, 0x1015BB00 - `sub ecx, 4; jmp 0x1015BB60`, the scalar deleting destructor. -void* __fastcall rg_destroy(void* self, void*, unsigned int flags) +void* RD9_THUNK rg_destroy(void* self RD9_THUNK_EDX, unsigned int flags) { return fromGeometry(self)->destroy(flags); } // +0x38, the same body as IRoad +0x04 (`mov eax, [ecx+34h]`), which on the subobject // reads object +0x38: the template. ICF folded "getRef" and "getTemplate" into one function. -void* __fastcall rg_getTemplate(void* self, void*) +void* RD9_THUNK rg_getTemplate(void* self RD9_THUNK_EDX) { return fromGeometry(self)->m_template; } // +0x40, 0x1015AD50 - `lea eax, [ecx+94h]`: the local bounds (object +0x98). -const void* __fastcall rg_getLocalBounds(void* self, void*) +const void* RD9_THUNK rg_getLocalBounds(void* self RD9_THUNK_EDX) { return &fromGeometry(self)->m_localBounds; } // +0x44, 0x1015AD60 - `fld dword ptr [ecx+54h]`: the file's radius (object +0x58). -float __fastcall rg_getRadius(void* self, void*) +float RD9_THUNK rg_getRadius(void* self RD9_THUNK_EDX) { return fromGeometry(self)->m_radius; } // +0x48, 0x1015AD70 - `lea eax, [ecx+0D0h]`: the transform (object +0xD4). -const Mat4* __fastcall rg_getTransform(void* self, void*) +const Mat4* RD9_THUNK rg_getTransform(void* self RD9_THUNK_EDX) { return &fromGeometry(self)->m_transform; } // +0x50, (`retn 4`). -void __fastcall rg_setTransform(void* self, void*, const Mat4* transform) +void RD9_THUNK rg_setTransform(void* self RD9_THUNK_EDX, const Mat4* transform) { fromGeometry(self)->setTransform(transform); } // +0x68, 0x10082D30 - `add ecx, 4; jmp std::string::operator=`: the subobject's own name string // (object +0x08). The shared body StaticMesh's +0x68 is; it answers the string. -vc71::string* __fastcall rg_setName(void* self, void*, const vc71::string& value) +std::string* RD9_THUNK rg_setName(void* self RD9_THUNK_EDX, const std::string& value) { - vc71::string& name = static_cast(self)->m_name; + std::string& name = static_cast(self)->m_name; name = value; return &name; } +#if !defined(_MSC_VER) +// [CHOSEN, not recovered] The opacity entry consumes a float on native targets; +// the shipped empty body discards the same four-byte carrier. +void rg_nativeOpacity(void* self, float opacity) +{ + unsigned int bits; + std::memcpy(&bits, &opacity, sizeof(bits)); + rg_emptyOneArg(self, bits); +} +void* const kRoadGeometryVtable[] = +{ + reinterpret_cast(&rg_addRef), // +0x00 0x1015BB30 thunk -> 0x10103C00 + reinterpret_cast(&rg_getRef), // +0x04 0x1015BB40 thunk -> 0x10103C10 + reinterpret_cast(&rg_release), // +0x08 0x1015BB50 thunk -> 0x1015BB10 + reinterpret_cast(&rg_queryInterface), // +0x0C 0x1015BAF0 thunk -> 0x1015BAB0 + reinterpret_cast(&rg_emptyOneArg), // +0x10 + reinterpret_cast(&rg_returnsMinusOneF), // +0x14 0x10082D10 -1.0f + reinterpret_cast(&rg_addToRenderQueue), // +0x18 + reinterpret_cast(&rg_emptyTwoArgs), // +0x1C + reinterpret_cast(&rg_emptySixArgs), // +0x20 + reinterpret_cast(&rg_emptyOneArg), // +0x24 + reinterpret_cast(&rg_returnsZero), // +0x28 + reinterpret_cast(&rg_returnsZero), // +0x2C + reinterpret_cast(&rg_returnsFalseOneArg), // +0x30 + reinterpret_cast(&rg_destroy), // +0x34 0x1015BB00 thunk -> 0x1015BB60 + reinterpret_cast(&rg_getTemplate), // +0x38 (object +0x38) + reinterpret_cast(&rg_returnsZeroOneArg), // +0x3C + reinterpret_cast(&rg_getLocalBounds), // +0x40 + reinterpret_cast(&rg_getRadius), // +0x44 + reinterpret_cast(&rg_getTransform), // +0x48 + reinterpret_cast(&rg_emptyTwoArgs), // +0x4C + reinterpret_cast(&rg_setTransform), // +0x50 + reinterpret_cast(&rg_emptyTwoArgs), // +0x54 + reinterpret_cast(&rg_emptyOneArg), // +0x58 + reinterpret_cast(&rg_returnsZero), // +0x5C + reinterpret_cast(&rg_emptyTwoArgs), // +0x60 + reinterpret_cast(&rg_emptyOneArg), // +0x64 + reinterpret_cast(&rg_setName), // +0x68 + reinterpret_cast(&rg_emptyOneArg), // +0x6C + reinterpret_cast(&rg_returnsZero), // +0x70 + reinterpret_cast(&rg_returnsOne), // +0x74 + reinterpret_cast(&rg_emptyOneArg), // +0x78 + reinterpret_cast(&rg_returnsZero), // +0x7C + reinterpret_cast(&rg_returnsOne), // +0x80 + reinterpret_cast(&rg_emptyOneArg), // +0x84 + reinterpret_cast(&rg_returnsMinusOne), // +0x88 + reinterpret_cast(&rg_returnsZero), // +0x8C + reinterpret_cast(&rg_emptyThreeArgs), // +0x90 + reinterpret_cast(&rg_emptyTwoArgs), // +0x94 + reinterpret_cast(&rg_emptyTwoArgs), // +0x98 + reinterpret_cast(&rg_emptyOneArg), // +0x9C (setOwner: nothing kept) + reinterpret_cast(&rg_returnsZero), // +0xA0 + reinterpret_cast(&rg_returnsZero), // +0xA4 (root object: null) + reinterpret_cast(&rg_returnsFalse), // +0xA8 + reinterpret_cast(&rg_emptyOneArg), // +0xAC + reinterpret_cast(&rg_returnsZero), // +0xB0 + reinterpret_cast(&rg_emptyOneArg), // +0xB4 + reinterpret_cast(&rg_emptyOneArg), // +0xB8 + reinterpret_cast(&rg_returnsFalse), // +0xBC + reinterpret_cast(&rg_emptyTwoArgs), // +0xC0 + reinterpret_cast(&rg_returnsZero), // +0xC4 + reinterpret_cast(&rg_returnsZeroOneArg), // +0xC8 + reinterpret_cast(&rg_returnsZero), // +0xCC (next geometry: none) + reinterpret_cast(&rg_returnsFalse), // +0xD0 + reinterpret_cast(&rg_emptyOneArg), // +0xD4 + reinterpret_cast(&rg_returnsFalse), // +0xD8 + reinterpret_cast(&rg_emptyOneArg), // +0xDC + reinterpret_cast(&rg_emptyOneArg), // +0xE0 + reinterpret_cast(&rg_returnsSeven), // +0xE4 + reinterpret_cast(&rg_returnsZero), // +0xE8 + reinterpret_cast(&rg_returnsZeroOneArg), // +0xEC + reinterpret_cast(&rg_emptyNoArgs), // +0xF0 + reinterpret_cast(&rg_nativeOpacity) // +0xF4 (setOpacity: nothing kept) +}; +#else void* const kRoadGeometryVtable[62] = { reinterpret_cast(&rg_addRef), // +0x00 0x1015BB30 thunk -> 0x10103C00 @@ -296,6 +399,7 @@ void* const kRoadGeometryVtable[62] = reinterpret_cast(&rg_emptyNoArgs), // +0xF0 reinterpret_cast(&rg_emptyOneArg) // +0xF4 (setOpacity: nothing kept) }; +#endif // The two helpers setTransform and loadMesh share: the local bounds are the world bounds minus the // transform's translation row (+0x104..+0x10C), with the dirty byte raised. Both shipped copies @@ -345,7 +449,8 @@ void setIdentity(Mat4& matrix) // Initializes geometry state and owned containers. loadMesh must run before drawing: // index/chunk counts, visibility, version words, and allocator words remain uninitialized. - +// PE 0x1015B1D0 (the shipped body writes the identity transform twice: the Mat4 member's +// construction, then the constructor body; one write is observable). RoadCompiled::RoadCompiled(RoadCompiledTemplate* owner) : m_roadVptr(kRoadVtable) , m_geometry(kRoadGeometryVtable) @@ -365,10 +470,9 @@ RoadCompiled::RoadCompiled(RoadCompiledTemplate* owner) setIdentity(m_transform); } -// the vertex buffer and the index buffer released owner-side (each only when present), -// then the members in reverse order: the +0x170 string, the visible bits (_Mysize zeroed, then the -// words freed), the centres, radii, index counts and starts (each freed and nulled), and finally the -// IGeometry prefix's name string. +// PE 0x1015B410. The vertex buffer (+0x44) and the index buffer (+0x48) released owner-side (each only when present), +// then the members in reverse order: the +0x170 string, the visible bits, the centres, radii, index +// counts and starts, and finally the IGeometry prefix's name string. RoadCompiled::~RoadCompiled() { if (m_vertexBuffer) @@ -399,13 +503,13 @@ int RoadCompiled::release() const int remaining = --m_refCount; if (!remaining) { - typedef void* (__fastcall* DestroyFn)(void*, void*, unsigned int); - reinterpret_cast(m_geometry.m_vptr[0x34 / sizeof(void*)])(&m_geometry, 0, 1); + typedef void* (__thiscall* DestroyFn)(void*, unsigned int); + reinterpret_cast(m_geometry.m_vptr[0x34 / 4])(&m_geometry, 1); } return remaining; } -// IBase and IRoad (820010) answer with the object; IGeometry (0x492FE0FE) with the +4 +// PE 0x1015BAB0. IBase and IRoad (820010) answer with the object; IGeometry (0x492FE0FE) with the +4 // subobject. The shipped body tests `this` before adjusting - the static_cast's null guard, which a // member function cannot observe. void* RoadCompiled::queryInterface(unsigned int iid) @@ -429,7 +533,7 @@ void* RoadCompiled::destroy(unsigned int flags) // Updates 1.4+ chunk visibility by distance then frustum; older meshes are always visible. // Requires terrain and compiled-road renderer singletons. Unordered distances are rejected. - +// PE 0x1015AE70 void RoadCompiled::updateChunkVisibility(const Frustum* frustum) { #if defined(BF2_IMAGE_EDITOR) && BF2_IMAGE_EDITOR @@ -455,15 +559,27 @@ void RoadCompiled::updateChunkVisibility(const Frustum* frustum) const float dy = frustum->m_transformation.m[13] - centre.y; const float dz = frustum->m_transformation.m[14] - centre.z; const float* const radius = &m_chunkRadii[i]; +#if defined(__APPLE__) + // [CHOSEN, not recovered] the shipped body keeps the differences, squares, root and the + // radius subtraction on the x87 stack and compares that against the stored float. + using namespace bf2x87; + const Real ex = sub(wide(frustum->m_transformation.m[12]), wide(centre.x)); + const Real ey = sub(wide(frustum->m_transformation.m[13]), wide(centre.y)); + const Real ez = sub(wide(frustum->m_transformation.m[14]), wide(centre.z)); + const Real root = squareRoot(add(add(mul(ez, ez), mul(ey, ey)), mul(ex, ex))); + (void)dx; (void)dy; (void)dz; + if (less(sub(root, wide(*radius)), wide(maxDistance))) +#else const float distance = std::sqrt((dz * dz + dy * dy) + dx * dx) - *radius; if (distance < maxDistance) +#endif { - m_chunkVisible.set(i, frustum->inside(centre, *radius)); - m_anyChunkVisible |= m_chunkVisible.test(i) ? 1 : 0; + m_chunkVisible[i] = rendmath::frustumInside(*frustum, centre, *radius); + m_anyChunkVisible |= m_chunkVisible[i] ? 1 : 0; } else { - m_chunkVisible.set(i, false); + m_chunkVisible[i] = false; } } } @@ -485,8 +601,8 @@ void RoadCompiled::addToRenderQueue() return; const Frustum* const frustum = dx9rend::rendererGetRenderView()->getFrustumPtr(); - typedef void (__fastcall* VisibilityFn)(void*, void*, const Frustum*); - reinterpret_cast(m_roadVptr[0x14 / sizeof(void*)])(this, 0, frustum); + typedef void (__thiscall* VisibilityFn)(void*, const Frustum*); + reinterpret_cast(m_roadVptr[0x14 / 4])(this, frustum); if (m_anyChunkVisible) roadCompiledRendererAdd(this); @@ -494,6 +610,7 @@ void RoadCompiled::addToRenderQueue() // IGeometry +0x50, the transform copied in (sub_10030E80), then the local bounds // re-derived from it. +// PE 0x1015ADD0 void RoadCompiled::setTransform(const Mat4* transform) { m_transform = *transform; @@ -505,7 +622,8 @@ void RoadCompiled::setTransform(const Mat4* transform) // Missing files trap. Failed buffer locks skip reads and desynchronize the stream. // Version 1.4 requires a chunk table even though the editable-road writer omits it. -void RoadCompiled::loadMesh(const vc71::string& file) +// PE 0x1015B550 +void RoadCompiled::loadMesh(const std::string& file) { renddx9abi::HostStream* const stream = ::dice::hfe::fileManager->open( renddx9abi::makeHostString(file), static_cast(2), @@ -519,10 +637,9 @@ void RoadCompiled::loadMesh(const vc71::string& file) stream->read(&m_versionMinor, 4); // +0x18C and +0x18E if (m_versionMajor <= 1 && m_versionMinor <= 2) { - // sub_10074300(6, __FILE__, 140, "") << ... ; sub_10074690 - dice's debug stream, rendered - // as one log line with dice's file, line and text, as every recovered diagnostic here is. - ::renddx9abi::logf("RoadCompiled.cpp:140: TBM: Old compiled road version on %s. " - "Needs to be recompiled", file.c_str()); + ::renddx9abi::Debug(DebugTypeError, + "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\RoadCompiled.cpp", + 140, std::string()) << "TBM: Old compiled road version on " << file << ". Needs to be recompiled"; } stream->read(&m_origin, 12); // +0x4C @@ -534,20 +651,22 @@ void RoadCompiled::loadMesh(const vc71::string& file) stream->read(&m_vertexCount, 4); // +0x3C m_vertexBuffer = dx9rend::createVertexBuffer(dx9rend::g_bufferManager, m_vertexCount, 32, - vc71::string("RoadCompiled"), 8); // writeonly + std::string("RoadCompiled"), 8); // writeonly RoadCompiledVertex* const vertices = static_cast( dx9rend::vertexBufferLock(m_vertexBuffer, 0, 0, 0)); + // The shipped reader reuses the completed vertex counter as its chunk-start slot. + unsigned int start = 0; + float alpha; if (vertices) { RoadCompiledVertex* out = vertices; - for (int i = 0; i < static_cast(m_vertexCount); ++i, ++out) // `jge` - signed + for (; static_cast(start) < static_cast(m_vertexCount); ++start, ++out) // `jge` - signed { float position[3] = { 0.0f, 0.0f, 0.0f }; float uv0[2] = { 0.0f, 0.0f }; float uv1[2] = { 0.0f, 0.0f }; float skipped12[3] = { 0.0f, 0.0f, 0.0f }; float skipped16[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; - float alpha; stream->read(position, 12); if (m_versionMajor == 1 && m_versionMinor == 2) @@ -587,11 +706,11 @@ void RoadCompiled::loadMesh(const vc71::string& file) if (m_versionMajor >= 1 && m_versionMinor >= 4) { stream->read(&m_chunkCount, 4); // +0x114 + // Unwritten on a first failed read; later short reads retain the preceding value. + unsigned int indexCount; + float radius; for (unsigned int i = 0; i < m_chunkCount; ++i) { - unsigned int start = 0; // the reader reuses its argument slot for this - unsigned int indexCount = 0; - float radius = 0.0f; Vec3 centre = { 0.0f, 0.0f, 0.0f }; stream->read(&start, 4); stream->read(&indexCount, 4); @@ -614,6 +733,7 @@ void RoadCompiled::loadMesh(const vc71::string& file) // Binds vertices before checking indices. Chunk primitive counts use unsigned division; // the pre-1.4 whole-buffer count uses signed division. +// PE 0x1015AFD0 void RoadCompiled::draw() { if (!m_vertexCount) @@ -622,7 +742,9 @@ void RoadCompiled::draw() dx9rend::vertexBufferBindStream(m_vertexBuffer, 0); if (!m_indexBuffer) { - ::renddx9abi::logf("RoadCompiled.cpp:291: TBM: the new roads need a idx Buffer!"); + ::renddx9abi::Debug(DebugTypeError, + "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\RoadCompiled.cpp", + 291, std::string()) << "TBM: the new roads need a idx Buffer!"; return; } dx9rend::indexBufferBind(m_indexBuffer); @@ -636,14 +758,14 @@ void RoadCompiled::draw() { do { - if (m_chunkVisible.test(i)) + if (m_chunkVisible[i]) { start = m_chunkStarts[i]; count = m_chunkIndexCounts[i]; ++i; while (i < m_chunkCount) { - if (!m_chunkVisible.test(i)) + if (!m_chunkVisible[i]) { dx9rend::rendererDrawIndexedPrimitive(count / 3u, 4u, 0, 0u, m_vertexCount, start); diff --git a/Code/BF2/Geom/RoadCompiled.h b/Code/BF2/Geom/RoadCompiled.h index b44ff921b..2bd70221e 100644 --- a/Code/BF2/Geom/RoadCompiled.h +++ b/Code/BF2/Geom/RoadCompiled.h @@ -11,12 +11,11 @@ #include "RoadCompiledTemplate.h" #include "GeometryInstanceData.h" #include "MeshTemplate.h" // MeshBounds -#include "UndergrowthSystem.h" // Vc71Vec - the tree's owning 16-byte VC7.1 vector -#include "Vc71BoolVector.h" // RoadChunkBits - the VC7.1 std::vector #include "../Math/Mat4.h" #include "../Math/Vec3.h" #include +#include namespace dice { namespace hfe { @@ -26,9 +25,9 @@ class Frustum; namespace geom { -// Per-chunk visibility bits using the shared VC7.1 vector layout. +// Per-chunk visibility bits (the shipped std::vector). -typedef Vc71BoolVector RoadChunkBits; +typedef std::vector RoadChunkBits; class RoadCompiled { @@ -51,7 +50,7 @@ class RoadCompiled void* destroy(unsigned int flags); // +0x34 // reached directly - void loadMesh(const vc71::string& file); // Object.geometry.loadMesh + void loadMesh(const std::string& file); // Object.geometry.loadMesh void draw(); // RoadCompiledRenderer's walk // data, every offset asserted below @@ -69,14 +68,14 @@ class RoadCompiled MeshBounds m_localBounds; // +0x098 Mat4 m_transform; // +0x0D4 unsigned int m_chunkCount; // +0x114 not written by the constructor - Vc71Vec m_chunkStarts; // +0x118 - Vc71Vec m_chunkIndexCounts; // +0x128 - Vc71Vec m_chunkRadii; // +0x138 - Vc71Vec m_chunkCentres; // +0x148 + std::vector m_chunkStarts; // +0x118 + std::vector m_chunkIndexCounts; // +0x128 + std::vector m_chunkRadii; // +0x138 + std::vector m_chunkCentres; // +0x148 RoadChunkBits m_chunkVisible; // +0x158 unsigned char m_anyChunkVisible; // +0x16C not written by the constructor unsigned char m_pad16D[3]; - vc71::string m_string170; // +0x170 [UNRESOLVED] no reader or writer + std::string m_string170; // +0x170 [UNRESOLVED] no reader or writer unsigned short m_versionMinor; // +0x18C unsigned short m_versionMajor; // +0x18E int m_order; // +0x190 @@ -88,29 +87,6 @@ class RoadCompiled #if defined(_M_IX86) static_assert(offsetof(RoadCompiled, m_geometry) == 0x004, "IGeometry subobject at +0x04"); -static_assert(offsetof(RoadCompiled, m_refCount) == 0x034, "refCount at +0x34"); -static_assert(offsetof(RoadCompiled, m_template) == 0x038, "template at +0x38"); -static_assert(offsetof(RoadCompiled, m_vertexCount) == 0x03C, "vertex count at +0x3C"); -static_assert(offsetof(RoadCompiled, m_indexCount) == 0x040, "index count at +0x40"); -static_assert(offsetof(RoadCompiled, m_vertexBuffer) == 0x044, "vertex buffer at +0x44"); -static_assert(offsetof(RoadCompiled, m_indexBuffer) == 0x048, "index buffer at +0x48"); -static_assert(offsetof(RoadCompiled, m_origin) == 0x04C, "origin at +0x4C"); -static_assert(offsetof(RoadCompiled, m_radius) == 0x058, "radius at +0x58"); -static_assert(offsetof(RoadCompiled, m_worldBounds) == 0x05C, "world bounds at +0x5C"); -static_assert(offsetof(RoadCompiled, m_localBounds) == 0x098, "local bounds at +0x98"); -static_assert(offsetof(RoadCompiled, m_transform) == 0x0D4, "transform at +0xD4"); -static_assert(offsetof(RoadCompiled, m_chunkCount) == 0x114, "chunk count at +0x114"); -static_assert(offsetof(RoadCompiled, m_chunkStarts) == 0x118, "chunk starts at +0x118"); -static_assert(offsetof(RoadCompiled, m_chunkIndexCounts) == 0x128, "chunk index counts at +0x128"); -static_assert(offsetof(RoadCompiled, m_chunkRadii) == 0x138, "chunk radii at +0x138"); -static_assert(offsetof(RoadCompiled, m_chunkCentres) == 0x148, "chunk centres at +0x148"); -static_assert(offsetof(RoadCompiled, m_chunkVisible) == 0x158, "visible bits at +0x158"); -static_assert(offsetof(RoadCompiled, m_anyChunkVisible) == 0x16C, "any-visible byte at +0x16C"); -static_assert(offsetof(RoadCompiled, m_string170) == 0x170, "string at +0x170"); -static_assert(offsetof(RoadCompiled, m_versionMinor) == 0x18C, "version minor at +0x18C"); -static_assert(offsetof(RoadCompiled, m_versionMajor) == 0x18E, "version major at +0x18E"); -static_assert(offsetof(RoadCompiled, m_order) == 0x190, "order at +0x190"); -static_assert(sizeof(RoadCompiled) == 0x194, "createInstance (0x1013B050) allocates 0x194"); #endif // IGeometry's address for an instance - the pointer createInstance answers and the component the @@ -125,6 +101,9 @@ void roadCompiledRendererAdd(RoadCompiled* road); // RoadCompiledRenderer.cpp - the singleton's +0x8C view-distance scale (1.3f), which the per-chunk // visibility reads straight off g_RoadCompiledRenderer (0x1015AEA3). float roadCompiledRendererViewDistanceScale(); +// RoadCompiledRenderer.cpp - the singleton's RenderPathListener subobject (retail +0x24), whose +0x0C +// renderFrame calls directly each frame. Unguarded: the caller tests the singleton. +void* roadCompiledRendererListener(); } // namespace geom } // namespace hfe diff --git a/Code/BF2/Geom/RoadCompiledRenderer.cpp b/Code/BF2/Geom/RoadCompiledRenderer.cpp index 73fd63e40..b4bff7236 100644 --- a/Code/BF2/Geom/RoadCompiledRenderer.cpp +++ b/Code/BF2/Geom/RoadCompiledRenderer.cpp @@ -3,7 +3,13 @@ #ifdef BF2_IMAGE_RENDDX9 +#if !defined(_MSC_VER) +// [CHOSEN, not recovered] Compiler-typed native table entries. +#include "../../RendDX9Abi/NativeVtable.h" +#include "../RendDX9/RendDX9Base.h" +#endif +#include "../../RendDX9Abi/ThunkAbi.h" #include "RoadCompiled.h" #include "RoadCompiledTemplate.h" #include "QuadPatch.h" // TerrainCuller @@ -15,6 +21,7 @@ #include "../Math/Vec3.h" #include "../RendMisc/IRenderView.h" #include "../RendDX9/RendDX9Base.h" +#include "../RendDX9/QueueProfiler.h" #include "../RendDX9/ShaderParameter.h" #include "../RendDX9/Texture.h" #include "../../RendDX9Abi/BfMemory.h" @@ -22,11 +29,12 @@ #include "../../RendDX9Abi/ModuleCommon.h" #include "../../RendDX9Abi/PluginAbi.h" #include "../../RendDX9Abi/PluginEntry.h" -#include "../../RendDX9Abi/Vc71String.h" +#include #include #include #include +#include "../GeomMisc/FSQuadDrawer.h" // textureHalfTexelSize, PE 0x100846A0 namespace dice { namespace hfe { @@ -59,9 +67,10 @@ const unsigned int kRaFogColor = 0xBC; // FogColor const unsigned int kRaAmbientIlluminationRange = 0xD0; // AmbientIlluminationRange (sub_100380E0) const unsigned int kRaSinglePointColor = 0x230; // SinglePointColor -unsigned char* raConstants() +// The Ra constants block (g_raShaderConstants) word at a retail x86 byte offset. +unsigned char* raConstantAt(unsigned int byteOffset) { - return static_cast(dx9rend::g_raShaderConstants); + return dx9rend::raShaderConstantsAt(byteOffset); } unsigned int floatBits(float value) @@ -72,15 +81,14 @@ unsigned int floatBits(float value) } // Renderer +0x780 - one of the renderer's path targets (+0x778..+0x7C8, released by the render-path -// deactivation), read through g_Renderer at 0x10145356 for the render-path-2 arm. RendDX9-internal -// field of the same image, read at its shipped offset (the XpLightManager.cpp precedent). +// deactivation), read through g_Renderer at 0x10145356 for the render-path-2 arm. Read through +// BF2Render.cpp's path-target accessor, keyed by that retail offset. dx9rend::EngineTexture* rendererPathTarget780() { - return *reinterpret_cast( - static_cast(static_cast(dx9rend::g_Renderer)) + 0x780); + return dx9rend::rendererPathTarget(0x780); } -// (retn 8) - a row vector through a Mat4: out = in * m. Every product is formed before the +// PE 0x10144790 (retn 8) - a row vector through a Mat4: out = in * m. Every product is formed before the // first store, so `in` and `out` may alias (the draw walk passes the same Vec4 for both). The sums // keep the shipped association, w first: // w = ((m3*x + m15*w) + m7*y) + m11*z z = ((m2*x + m14*w) + m6*y) + m10*z @@ -122,8 +130,8 @@ class RoadCompiledRenderer int getSlot84() const { return m_int84; } // +0x14 void setEnabled(unsigned char value) { m_enabled = value; } // +0x18 unsigned char getEnabled() const { return m_enabled; } // +0x1C - vc71::string& setName(const vc71::string& value) { return m_name = value; } // +0x20 - vc71::string* getName() { return &m_name; } // +0x24 + std::string& setName(const std::string& value) { return m_name = value; } // +0x20 + std::string* getName() { return &m_name; } // +0x24 // the work void add(RoadCompiled* road); @@ -141,7 +149,7 @@ class RoadCompiledRenderer void* const* m_vptr; // +0x00 unsigned char m_enabled; // +0x04 unsigned char m_pad05[3]; - vc71::string m_name; // +0x08 + std::string m_name; // +0x08 void* const* m_listenerVptr; // +0x24 int m_renderPath; // +0x28 int m_refCount; // +0x2C @@ -183,90 +191,71 @@ class RoadCompiledRenderer #if defined(_M_IX86) static_assert(offsetof(RoadCompiledRenderer, m_enabled) == 0x04, "enabled byte at +0x04"); static_assert(offsetof(RoadCompiledRenderer, m_name) == 0x08, "name at +0x08"); -static_assert(offsetof(RoadCompiledRenderer, m_listenerVptr) == 0x24, - "renderFrame calls the listener at renderer+36 (BF2Render.cpp)"); -static_assert(offsetof(RoadCompiledRenderer, m_renderPath) == 0x28, "render path at +0x28"); -static_assert(offsetof(RoadCompiledRenderer, m_refCount) == 0x2C, "refCount at +0x2C"); -static_assert(offsetof(RoadCompiledRenderer, m_effect) == 0x30, "effect at +0x30"); -static_assert(offsetof(RoadCompiledRenderer, m_paramWorldSpaceCamPos) == 0x50, "WorldSpaceCamPos at +0x50"); -static_assert(offsetof(RoadCompiledRenderer, m_paramAmbientIlluminationRange) == 0x74, - "AmbientIlluminationRange at +0x74"); -static_assert(offsetof(RoadCompiledRenderer, m_roads) == 0x78, "road list at +0x78"); -static_assert(offsetof(RoadCompiledRenderer, m_int84) == 0x84, "+0x84"); -static_assert(offsetof(RoadCompiledRenderer, m_hemiDirectFlag) == 0x88, "hemi direct flag at +0x88"); -static_assert(offsetof(RoadCompiledRenderer, m_viewDistanceScale) == 0x8C, "view-distance scale at +0x8C"); -static_assert(offsetof(RoadCompiledRenderer, m_depthBias) == 0x90, "depth bias at +0x90"); -static_assert(offsetof(RoadCompiledRenderer, m_slopeScaleDepthBias) == 0x94, "slope bias at +0x94"); -static_assert(offsetof(RoadCompiledRenderer, m_heightmapCluster) == 0x98, "HeightmapCluster at +0x98"); -static_assert(offsetof(RoadCompiledRenderer, m_terrain) == 0x9C, "terrain at +0x9C"); -static_assert(offsetof(RoadCompiledRenderer, m_worldSpaceCamPos) == 0xA0, "WorldSpaceCamPos value at +0xA0"); -static_assert(offsetof(RoadCompiledRenderer, m_fadeOut) == 0xB0, - "renderFrame and roadQueuePass read the fade pair at +0xB0/+0xB4"); -static_assert(sizeof(RoadCompiledRenderer) == 0xB8, - "RefFactory_geom_RoadCompiledRenderer allocates 0xB8 (0x100B0AA8)"); #endif namespace { +// The owner of the listener subobject (retail: listener - 0x24). RoadCompiledRenderer* fromListener(void* listener) { - return reinterpret_cast(static_cast(listener) - 0x24); + return reinterpret_cast(static_cast(listener) + - offsetof(RoadCompiledRenderer, m_listenerVptr)); } // Primary-table thunks use __fastcall with unused EDX to match the __thiscall slots. -int __fastcall rcr_addRef(void* self, void*) +int RD9_THUNK rcr_addRef(void* self RD9_THUNK_EDX) { return static_cast(self)->addRef(); } -int __fastcall rcr_getRef(void* self, void*) +int RD9_THUNK rcr_getRef(void* self RD9_THUNK_EDX) { return static_cast(self)->getRef(); } -int __fastcall rcr_release(void* self, void*) +int RD9_THUNK rcr_release(void* self RD9_THUNK_EDX) { return static_cast(self)->release(); } -void* __fastcall rcr_queryInterface(void* self, void*, unsigned int iid) +void* RD9_THUNK rcr_queryInterface(void* self RD9_THUNK_EDX, unsigned int iid) { return static_cast(self)->queryInterface(iid); } // +0x10 / +0x14 - the int at +0x84. [UNRESOLVED] role: StaticMeshRenderer's +0x10 is an empty body and // its +0x14 answers 0; nothing recovered calls either on this singleton. -void __fastcall rcr_setSlot84(void* self, void*, int value) +void RD9_THUNK rcr_setSlot84(void* self RD9_THUNK_EDX, int value) { static_cast(self)->setSlot84(value); } -int __fastcall rcr_getSlot84(void* self, void*) +int RD9_THUNK rcr_getSlot84(void* self RD9_THUNK_EDX) { return static_cast(self)->getSlot84(); } // +0x18, the one VideoOptions::apply calls. A single byte store. -void __fastcall rcr_setEnabled(void* self, void*, int value) +void RD9_THUNK rcr_setEnabled(void* self RD9_THUNK_EDX, int value) { static_cast(self)->setEnabled(static_cast(value)); } -unsigned char __fastcall rcr_getEnabled(void* self, void*) +unsigned char RD9_THUNK rcr_getEnabled(void* self RD9_THUNK_EDX) { return static_cast(self)->getEnabled(); } // +0x20, 0x10121A10 - `add ecx, 8; jmp std::string::operator=(const std::string&)`: the import's // mangled name pins the argument, and the assignment's result (the name) is what it answers. -vc71::string* __fastcall rcr_setName(void* self, void*, const vc71::string& value) +std::string* RD9_THUNK rcr_setName(void* self RD9_THUNK_EDX, const std::string& value) { return &static_cast(self)->setName(value); } -vc71::string* __fastcall rcr_getName(void* self, void*) +std::string* RD9_THUNK rcr_getName(void* self RD9_THUNK_EDX) { return static_cast(self)->getName(); } @@ -291,33 +280,45 @@ void* const kPrimaryVtable[10] = // +0x00, 0x101C43C0 - `mov [ecx+4], arg`: the activated path into +0x28. -void __fastcall rcr_onRenderPathActivated(void* self, void*, int path) +void RD9_THUNK rcr_onRenderPathActivated(void* self RD9_THUNK_EDX, int path) { fromListener(self)->m_renderPath = path; } -void __fastcall rcr_onRenderPathDeactivated(void*, void*) { } // +0x04 0x10037D40 `ret` -void __fastcall rcr_onRenderPathChanged(void*, void*, int) { } // +0x08 0x100E13B0 `retn 4` +void RD9_THUNK rcr_onRenderPathDeactivated(void* RD9_THUNK_EDX) { } // +0x04 0x10037D40 `ret` +void RD9_THUNK rcr_onRenderPathChanged(void* RD9_THUNK_EDX, int) { } // +0x08 0x100E13B0 `retn 4` // +0x0C, (`retn 4`) - the per-frame call. The argument (renderFrame passes 0) is not read. -void __fastcall rcr_onRenderPathNotification(void* self, void*, int) +void RD9_THUNK rcr_onRenderPathNotification(void* self RD9_THUNK_EDX, int) { fromListener(self)->onRenderPathNotification(); } // +0x10, 0x101A9A10 - `mov eax, [ecx+4]`. -int __fastcall rcr_getCurrentRenderPath(void* self, void*) +int RD9_THUNK rcr_getCurrentRenderPath(void* self RD9_THUNK_EDX) { return fromListener(self)->m_renderPath; } -// +0x14, (`retn 4`) - the name, constructed into the caller's hidden return slot. -vc71::string* __fastcall rcr_getRenderPathListenerName(void*, void*, vc71::string* out) +// PE 0x10145650. +0x14, (`retn 4`) - the name, constructed into the caller's hidden return slot. +std::string* RD9_THUNK rcr_getRenderPathListenerName(void* RD9_THUNK_EDX, std::string* out) { - new (out) vc71::string("RoadCompiledRenderer"); + new (out) std::string("RoadCompiledRenderer"); return out; } +#if !defined(_MSC_VER) +// [CHOSEN, not recovered] Match the shared consumer interface under the native ABI. +void* const kListenerVtable[] = +{ + BF2_NATIVE_SLOT(::dice::hfe::dx9rend::RenderPathListener, onRenderPathActivated, rcr_onRenderPathActivated), + BF2_NATIVE_SLOT(::dice::hfe::dx9rend::RenderPathListener, onRenderPathDeactivated, rcr_onRenderPathDeactivated), + BF2_NATIVE_SLOT(::dice::hfe::dx9rend::RenderPathListener, onRenderPathChanged, rcr_onRenderPathChanged), + BF2_NATIVE_SLOT(::dice::hfe::dx9rend::RenderPathListener, onRenderPathNotification, rcr_onRenderPathNotification), + BF2_NATIVE_SLOT(::dice::hfe::dx9rend::RenderPathListener, getCurrentRenderPath, rcr_getCurrentRenderPath), + BF2_NATIVE_SLOT(::dice::hfe::dx9rend::RenderPathListener, getRenderPathListenerName, rcr_getRenderPathListenerName), +}; +#else void* const kListenerVtable[6] = { reinterpret_cast(&rcr_onRenderPathActivated), // +0x00 @@ -327,6 +328,7 @@ void* const kListenerVtable[6] = reinterpret_cast(&rcr_getCurrentRenderPath), // +0x10 reinterpret_cast(&rcr_getRenderPathListenerName) // +0x14 }; +#endif } // anonymous namespace @@ -334,6 +336,7 @@ void* const kListenerVtable[6] = // Initializes resources, binds the shader, then registers the render-path listener. // The enabled flag and render path remain uninitialized; bindEffect fills the deferred handles. +// PE 0x10145120 RoadCompiledRenderer::RoadCompiledRenderer() : m_vptr(kPrimaryVtable) , m_listenerVptr(kListenerVtable) @@ -372,47 +375,45 @@ RoadCompiledRenderer::RoadCompiledRenderer() } -// the shader binding. The effect through the ShaderManager (sub_10022EF0), its technique, +// PE 0x10144820, the shader binding. The effect through the ShaderManager (sub_10022EF0), its technique, // then seventeen handles through Effect::getShaderParameter (sub_1001E420, each with the caller-facing // extra reference the destructor releases), in this exact order - WorldSpaceCamPos is fetched after // fogColor although its slot is +0x50. // No null test anywhere: a failed effect load faults in the technique selection, as shipped. - void RoadCompiledRenderer::bindEffect() { m_effect = static_cast(dx9rend::shaderManagerGetEffect( dx9rend::g_shaderManager, "mods/xpack/shaders/RoadCompiled")); - dx9rend::effectSetTechniqueByName(m_effect, vc71::string("roadcompiledFull")); + dx9rend::effectSetTechniqueByName(m_effect, std::string("roadcompiledFull")); m_paramWorldViewProjection = - dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("WorldViewProjection")); - m_paramLocalEye = dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("LocalEye")); - m_paramTexBlendFactor = dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("TexBlendFactor")); - m_paramFadeOut = dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("FadeOut")); - m_paramTexLayer3 = dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("TEXLAYER3")); - m_paramTexLayer4 = dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("TEXLAYER4")); - m_paramTexLayer2 = dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("TEXLAYER2")); - m_paramScaleY = dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("SCALEY")); - m_paramSunColor = dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("SUNCOLOR")); - m_paramGIColor = dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("GICOLOR")); - m_paramFogRange = dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("fogRange")); - m_paramFogColor = dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("fogColor")); + dx9rend::effectGetShaderParameterTyped(m_effect, std::string("WorldViewProjection")); + m_paramLocalEye = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("LocalEye")); + m_paramTexBlendFactor = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("TexBlendFactor")); + m_paramFadeOut = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("FadeOut")); + m_paramTexLayer3 = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("TEXLAYER3")); + m_paramTexLayer4 = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("TEXLAYER4")); + m_paramTexLayer2 = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("TEXLAYER2")); + m_paramScaleY = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("SCALEY")); + m_paramSunColor = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("SUNCOLOR")); + m_paramGIColor = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("GICOLOR")); + m_paramFogRange = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("fogRange")); + m_paramFogColor = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("fogColor")); m_paramWorldSpaceCamPos = - dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("WorldSpaceCamPos")); - m_paramTexProjOffset = dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("TEXPROJOFFSET")); - m_paramTexProjScale = dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("TEXPROJSCALE")); + dx9rend::effectGetShaderParameterTyped(m_effect, std::string("WorldSpaceCamPos")); + m_paramTexProjOffset = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("TEXPROJOFFSET")); + m_paramTexProjScale = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("TEXPROJSCALE")); m_paramSinglePointColor = - dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("SINGLEPOINTCOLOR")); + dx9rend::effectGetShaderParameterTyped(m_effect, std::string("SINGLEPOINTCOLOR")); m_paramAmbientIlluminationRange = - dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("AmbientIlluminationRange")); + dx9rend::effectGetShaderParameterTyped(m_effect, std::string("AmbientIlluminationRange")); } -// the destructor body. Each handle released through its +0x08 when present, in the +// PE 0x10145010, the destructor body. Each handle released through its +0x08 when present, in the // shipped (non-declaration) order, with the effect released between fogColor and texprojoffset; then // the listener unregistered (RendDX9_unregisterRenderPathListener, this + 0x24), and the members: the // road list (0x1000EAD0), then the name. - RoadCompiledRenderer::~RoadCompiledRenderer() { if (m_paramTexLayer2) m_paramTexLayer2->release(); // +0x4C @@ -437,7 +438,7 @@ RoadCompiledRenderer::~RoadCompiledRenderer() dx9rend::unregisterRenderPathListener(static_cast(&m_listenerVptr)); } -// at zero the destructor body runs and the block goes back to the engine heap. +// PE 0x10145690. At zero the destructor body runs and the block goes back to the engine heap. int RoadCompiledRenderer::release() { const int remaining = --m_refCount; @@ -464,36 +465,37 @@ void* RoadCompiledRenderer::queryInterface(unsigned int iid) const // template of equal priority does not stop the walk, so equal-priority templates interleave in // arrival order. +// PE 0x10145210 void RoadCompiledRenderer::add(RoadCompiled* road) { RoadCompiledTemplate* const tmpl = road->m_template; - RoadListNode* const head = m_roads.head; - RoadListNode* where = head->next; - if (where != head) + RoadList::iterator where = m_roads.begin(); + if (where != m_roads.end()) { const int priority = tmpl->m_priority; do { - RoadCompiled* const queued = where->value; + RoadCompiled* const queued = *where; RoadCompiledTemplate* const queuedTemplate = queued->m_template; if (priority < queuedTemplate->m_priority) break; if (tmpl == queuedTemplate && road->m_order < queued->m_order) break; - where = where->next; + ++where; } - while (where != head); + while (where != m_roads.end()); } m_roads.insert(where, road); // 0x1013B1C0 + _Incsize + the link } +// PE 0x10145290 (listener +0x0C, this + 0x24). // Draws queued roads to the current render-path targets, then drains the queue. -// A disabled renderer drops the queue without drawing. - +// A disabled renderer drops the queue without drawing. The draw runs inside the "RoadCompiled" +// QueueProfiler scope (static, guard bit 0 at 0x1025E1D8, object 0x1025DF70). void RoadCompiledRenderer::onRenderPathNotification() { - if (!m_roads.size) + if (m_roads.empty()) return; if (!m_enabled) { @@ -501,6 +503,9 @@ void RoadCompiledRenderer::onRenderPathNotification() return; } + static dx9rend::QueueProfiler profiler(std::string("RoadCompiled")); + profiler.begin(); + if (m_renderPath == 3) { m_paramTexLayer2->setValue(dx9rend::rendererGetHemiScratchTexture(), 0); @@ -514,13 +519,14 @@ void RoadCompiledRenderer::onRenderPathNotification() } drawAll(); + dx9rend::QueueProfiler::end(); } // Draws queued roads with the duplicate render view, then clears the queue. // Without terrain, returns before clearing. Distance culling uses the file-space origin; // template changes update blending even when both templates use the same textures. - +// PE 0x10144B00 void RoadCompiledRenderer::drawAll() { dx9rend::IRenderView* const view = dx9rend::rendererGetRenderViewDup(); // +0x50 @@ -562,10 +568,9 @@ void RoadCompiledRenderer::drawAll() updateFrameConstants(); RoadCompiledTemplate* last = 0; - RoadListNode* const head = m_roads.head; - for (RoadListNode* node = head->next; node != head; node = node->next) + for (RoadList::iterator node = m_roads.begin(); node != m_roads.end(); ++node) { - RoadCompiled* const road = node->value; + RoadCompiled* const road = *node; RoadCompiledTemplate* const tmpl = road->m_template; terrainOriginScratch(camera); // inlined sub_100E11B0 @@ -621,10 +626,10 @@ void RoadCompiledRenderer::drawAll() } -// Updates road fade, lighting, fog, projection and depth-bias constants. +// PE 0x10145390. Updates road fade, lighting, fog, projection and depth-bias constants. The +// half-texel pair is the inlined wrapper PE 0x100846A0 (0.5 / width, 0.5 / height of the hemi texture). // Requires terrain, its culler, renderer targets and Ra constants. Projection offset is // cached from the first target size, even if later frame dimensions change. - void RoadCompiledRenderer::updateFrameConstants() { if (!m_heightmapCluster) @@ -654,14 +659,17 @@ void RoadCompiledRenderer::updateFrameConstants() m_paramGIColor->setValue(gi, 0); } - m_paramFogRange->setValue(raConstants() + kRaFogRange, 0); - m_paramFogColor->setValue(raConstants() + kRaFogColor, 0); + m_paramFogRange->setValue(raConstantAt(kRaFogRange), 0); + m_paramFogColor->setValue(raConstantAt(kRaFogColor), 0); m_paramWorldSpaceCamPos->setValue(m_worldSpaceCamPos, 0); dx9rend::EngineTexture* const hemi = dx9rend::rendererGetHemiScratchTexture(); // g_Renderer +0x774 float halfTexel[2]; - halfTexel[0] = 0.5f / static_cast(static_cast(hemi->width)); - halfTexel[1] = 0.5f / static_cast(static_cast(hemi->height)); + { + const Math::Vec2 half = textureHalfTexelSize(hemi); // PE 0x100846A0, call 0x101454F9 + halfTexel[0] = half.x; + halfTexel[1] = half.y; + } static unsigned int s_texProjOnce = 0; // dword_1025DF6C static float s_texProjScale[4]; // dword_1025DF5C @@ -685,12 +693,12 @@ void RoadCompiledRenderer::updateFrameConstants() m_paramTexProjScale->setValue(s_texProjScale, 0); m_paramTexProjOffset->setValue(s_texProjOffset, 0); - m_paramSinglePointColor->setValue(raConstants() + kRaSinglePointColor, 0); + m_paramSinglePointColor->setValue(raConstantAt(kRaSinglePointColor), 0); m_paramTexLayer2->setValue(dx9rend::rendererGetHemiScratchTexture(), 0); { const float* const holder = reinterpret_cast( - raConstants() + kRaAmbientIlluminationRange); + raConstantAt(kRaAmbientIlluminationRange)); const float range[4] = { holder[0], holder[1], holder[2], holder[3] }; m_paramAmbientIlluminationRange->setValue(range, 0); } @@ -716,6 +724,54 @@ float roadCompiledRendererViewDistanceScale() ->m_viewDistanceScale; } +// PE 0x100285AF, inlined by Renderer +0x80. Caller guards the singleton. +// [CHOSEN, not recovered] Typed source bridge to the native field. +void roadCompiledRendererSetViewDistanceScale(float value) +{ + static_cast(static_cast(g_RoadCompiledRenderer)) + ->m_viewDistanceScale = value; +} + +// PE 0x100285EF, inlined by Renderer +0x88. Caller guards the singleton. +// [CHOSEN, not recovered] Typed source bridge to the native field. +void roadCompiledRendererSetDepthBias(float value) +{ + static_cast(static_cast(g_RoadCompiledRenderer)) + ->m_depthBias = value; +} + +// [CHOSEN, not recovered] Native owner bridges for the console's direct field accesses. +// PE 0x100B1FDB +unsigned char& roadCompiledRendererConsoleDisableFade(void* receiver) +{ + return static_cast(receiver)->m_hemiDirectFlag; +} + +// PE 0x100B20E3 +float& roadCompiledRendererConsoleDepthBias(void* receiver) +{ + return static_cast(receiver)->m_depthBias; +} + +// PE 0x100B21E9 +float& roadCompiledRendererConsoleSlopeScaleDepthBias(void* receiver) +{ + return static_cast(receiver)->m_slopeScaleDepthBias; +} + +// PE 0x100B22EF +float& roadCompiledRendererConsoleLodDistanceModifier(void* receiver) +{ + return static_cast(receiver)->m_viewDistanceScale; +} + +// renderFrame's `g_RoadCompiledRenderer + 36`: the listener subobject whose +0x0C it calls with 0. +void* roadCompiledRendererListener() +{ + return &static_cast(static_cast(g_RoadCompiledRenderer)) + ->m_listenerVptr; +} + // Renderer::roadQueuePass (BF2Render.cpp, 0x1002A560) - the three things it reads off the singleton: // the fade pair (+0xB0/+0xB4, sub_10038810) and the two bias words (+0x90/+0x94) it hands the // StateManager as their bit patterns. Unguarded; roadQueuePass tests the singleton first. @@ -759,7 +815,8 @@ void roadCompiledRendererSetHemiDirectFlag(unsigned char value) ->setHemiDirectFlag(value); } -// RefFactory_geom_RoadCompiledRenderer, 0x100B0A9C: `if (outer) return 0`, allocate 0xB8, construct, +// RefFactory_geom_RoadCompiledRenderer, 0x100B0A9C: `if (outer) return 0`, allocate the object +// (retail 0xB8 bytes), construct, // then queryInterface through the new object without testing the allocation (a failed allocation // faults at the QI, as shipped), and release it when the interface is refused. IBase* __fastcall createRoadCompiledRenderer(unsigned int iid, IBase* outer) diff --git a/Code/BF2/Geom/RoadCompiledTemplate.cpp b/Code/BF2/Geom/RoadCompiledTemplate.cpp index 32bf18367..3138a8500 100644 --- a/Code/BF2/Geom/RoadCompiledTemplate.cpp +++ b/Code/BF2/Geom/RoadCompiledTemplate.cpp @@ -4,6 +4,7 @@ #ifdef BF2_IMAGE_RENDDX9 #include "RoadCompiledTemplate.h" +#include "../RendDX9/RendDX9Math.h" // rendmath::unitScale (sub_1007B220) #include "RoadCompiled.h" #include "Terrain.h" // TerrainRawReader - the raw reader family 0x10075DE0..0x100763A0 @@ -11,7 +12,7 @@ #include "../RendDX9/Texture.h" // EngineTexture, textureDtor #include "../../RendDX9Abi/BfMemory.h" #include "../../RendDX9Abi/ModuleCommon.h" -#include "../../RendDX9Abi/Vc71String.h" +#include #include #include @@ -42,31 +43,23 @@ void releaseOwnedTexture(dx9rend::EngineTexture* texture) } } -// sub_1007B220's shared `static const Vec3(1, 1, 1)` - decompressPosition's only source. MeshTemplate.cpp -// transcribes the same function-local static for its own table; the value is a constant. -const Vec3& unitScale() -{ - static Vec3 value = { 1.0f, 1.0f, 1.0f }; - return value; -} - } // anonymous namespace // Initializes template resources and strings. Priority and the byte at +0x04 remain untouched. +// PE 0x1013AF80 RoadCompiledTemplate::RoadCompiledTemplate() - : m_refCount(1) + : m_refCount((m_dword08 = 0, 1)) // Clear the inherited word before the instance list allocates. , m_loaded(0) , m_texture0(0) , m_texture1(0) , m_blendFactor(0.0f) + , m_fadeOff{0.0f, 0.0f} { - m_dword08 = 0; - m_fadeOff[0] = 0.0f; - m_fadeOff[1] = 0.0f; } // the two textures released owner-side (texture0 first), then the members in reverse // order: the path string, the name string and the instance list (0x1000EAD0). +// PE 0x1013AFE0 RoadCompiledTemplate::~RoadCompiledTemplate() { releaseOwnedTexture(m_texture0); @@ -92,6 +85,7 @@ int RoadCompiledTemplate::getRef() // the destructor body is called directly (the table has no deleting-destructor slot), // then the block goes back to the engine heap. +// PE 0x1013B2B0 int RoadCompiledTemplate::release() { const int remaining = --m_refCount; @@ -116,24 +110,27 @@ void* RoadCompiledTemplate::queryInterface(unsigned int iid) const unsigned int RoadCompiledTemplate::getClassId() const { return CID_RoadCompiledTemplate; } -void RoadCompiledTemplate::setName(const vc71::string& name) { m_name = name; } -const vc71::string& RoadCompiledTemplate::getName() const { return m_name; } -void RoadCompiledTemplate::setPath(const vc71::string& path) { m_path = path; } -const vc71::string& RoadCompiledTemplate::getPath() const { return m_path; } +// PE 0x1013B280 +void RoadCompiledTemplate::setName(const std::string& name) { m_name = name; } +const std::string& RoadCompiledTemplate::getName() const { return m_name; } +// PE 0x1013B290 +void RoadCompiledTemplate::setPath(const std::string& path) { m_path = path; } +const std::string& RoadCompiledTemplate::getPath() const { return m_path; } bool RoadCompiledTemplate::isLoaded() const { return m_loaded != 0; } -// createGeometry. A new 0x194-byte RoadCompiled joins the END of the instance list (the +// createGeometry. A new RoadCompiled (retail 0x194 bytes) joins the END of the instance list (the // list holds the null too if the allocation failed); a template no one has asked for yet loads its // `_compiled.dat` right here unless the ResourceManager is deferring loads (its +0x04 byte, sub_1000D950) // - then GeometryTemplateManager::loadUsedTemplates loads it with the others. Either way the keep byte // goes up, and the caller gets the IGeometry subobject (instance + 4), or null. // The load is a virtual call (`call [eax+2Ch]`), and it is made on the keep byte, NOT on +0x10: a // template the manager already marked is never loaded here, loaded or not. +// PE 0x1013B050 void* RoadCompiledTemplate::createInstance() { - void* const storage = ::renddx9abi::engineAlloc(0x194); + void* const storage = ::renddx9abi::engineAlloc(sizeof(RoadCompiled)); RoadCompiled* const instance = storage ? new (storage) RoadCompiled(this) : 0; - m_instances.insert(m_instances.head, instance); // push_back + m_instances.push_back(instance); if (!m_keepData && !dx9rend::resourceManagerIsReady()) load(); // +0x2C @@ -147,19 +144,20 @@ void* RoadCompiledTemplate::createInstance() // priority. The shipped body tests neither the open nor a single read. // The file name is built as `(path + name) + "_compiled.dat"` - VC7.1's operator+ inlined twice // (0x1013AE49..0x1013AEAB); only the finished string is observable. +// PE 0x1013AE30 bool RoadCompiledTemplate::load() { if (m_loaded) return false; - vc71::string file(m_path); + std::string file(m_path); file += m_name; file += "_compiled.dat"; TerrainRawReader reader; reader.open(file, 2, 0, 0); - vc71::string line; + std::string line; reader.readLine(line, '\n'); m_texture0 = static_cast( dx9rend::textureManagerGetTexture(line)); @@ -213,7 +211,7 @@ int RoadCompiledTemplate::getLodPrimitiveCount(unsigned int) { return 0; } // the input is never read. Vec3* RoadCompiledTemplate::decompressPosition(Vec3* out, const Vec3*) { - const Vec3& scale = unitScale(); + const Vec3& scale = rendmath::unitScale(); out->y = scale.y; out->x = scale.x; out->z = scale.z; @@ -224,16 +222,16 @@ Vec3* RoadCompiledTemplate::decompressPosition(Vec3* out, const Vec3*) void RoadCompiledTemplate::releaseDeviceResources() { } -// RefFactory 0x100B09DC - `if (outer) return 0`, allocate 0x70, construct, queryInterface(iid) through -// the NEW object without testing the allocation (a failed allocation faults on the QI, as shipped), -// and release it when the interface is refused. +// RefFactory 0x100B09DC - `if (outer) return 0`, allocate the object (retail 0x70 bytes), construct, +// queryInterface(iid) through the NEW object without testing the allocation (a failed allocation +// faults on the QI, as shipped), and release it when the interface is refused. IBase* __fastcall createRoadCompiledTemplate(unsigned int iid, IBase* outer) { if (outer) return 0; - void* const storage = ::renddx9abi::engineAlloc(0x70); + void* const storage = ::renddx9abi::engineAlloc(sizeof(RoadCompiledTemplate)); RoadCompiledTemplate* self = 0; if (storage) self = new (storage) RoadCompiledTemplate(); diff --git a/Code/BF2/Geom/RoadCompiledTemplate.h b/Code/BF2/Geom/RoadCompiledTemplate.h index cc326381c..95e844e07 100644 --- a/Code/BF2/Geom/RoadCompiledTemplate.h +++ b/Code/BF2/Geom/RoadCompiledTemplate.h @@ -9,9 +9,9 @@ #define BF2_GEOM_ROADCOMPILEDTEMPLATE_H #include "MeshTemplate.h" // IGeometryTemplate (44 slots) and the 12-byte GeometryTemplate prefix -#include "Vc71PtrList.h" // RoadList - the VC7.1 std::list #include // offsetof - the layout assertions below +#include namespace dice { namespace hfe { @@ -23,10 +23,9 @@ namespace geom { class RoadCompiled; -// Shared compatibility list for template instances and per-frame compiled-road queues. +// The shipped std::list: template instances and the per-frame compiled-road queue. -typedef Vc71PtrListNode RoadListNode; -typedef Vc71PtrList RoadList; +typedef std::list RoadList; // RoadCompiledTemplate - GeometryTemplate.RoadCompiled. The 44 slots in table order; the ones this @@ -47,10 +46,10 @@ class RoadCompiledTemplate : public GeometryTemplate // IGeometryTemplate virtual unsigned int getClassId() const; // +0x10 - virtual void setName(const vc71::string& name); // +0x14 - virtual const vc71::string& getName() const; // +0x18 - virtual void setPath(const vc71::string& path); // +0x1C - virtual const vc71::string& getPath() const; // +0x20 + virtual void setName(const std::string& name); // +0x14 + virtual const std::string& getName() const; // +0x18 + virtual void setPath(const std::string& path); // +0x1C + virtual const std::string& getPath() const; // +0x20 virtual void* createInstance(); // +0x24 virtual bool isLoaded() const; // +0x28 virtual bool load(); // +0x2C @@ -93,8 +92,8 @@ class RoadCompiledTemplate : public GeometryTemplate unsigned char m_loaded; // +0x10 ctor 0 unsigned char m_pad11[3]; // +0x11 not written RoadList m_instances; // +0x14 - vc71::string m_name; // +0x20 - vc71::string m_path; // +0x3C + std::string m_name; // +0x20 + std::string m_path; // +0x3C dx9rend::EngineTexture* m_texture0; // +0x58 ctor 0 dx9rend::EngineTexture* m_texture1; // +0x5C ctor 0 float m_blendFactor; // +0x60 ctor 0 @@ -110,14 +109,6 @@ class RoadCompiledTemplate : public GeometryTemplate static_assert(offsetof(RoadCompiledTemplate, m_refCount) == 0x0C, "refCount at +0x0C"); static_assert(offsetof(RoadCompiledTemplate, m_loaded) == 0x10, "loaded at +0x10"); static_assert(offsetof(RoadCompiledTemplate, m_instances) == 0x14, "instance list at +0x14"); -static_assert(offsetof(RoadCompiledTemplate, m_name) == 0x20, "name at +0x20"); -static_assert(offsetof(RoadCompiledTemplate, m_path) == 0x3C, "path at +0x3C"); -static_assert(offsetof(RoadCompiledTemplate, m_texture0) == 0x58, "texture0 at +0x58"); -static_assert(offsetof(RoadCompiledTemplate, m_texture1) == 0x5C, "texture1 at +0x5C"); -static_assert(offsetof(RoadCompiledTemplate, m_blendFactor) == 0x60, "blend factor at +0x60"); -static_assert(offsetof(RoadCompiledTemplate, m_fadeOff) == 0x64, "fade-off at +0x64"); -static_assert(offsetof(RoadCompiledTemplate, m_priority) == 0x6C, "priority at +0x6C"); -static_assert(sizeof(RoadCompiledTemplate) == 0x70, "the factory 0x100B09DC allocates 0x70"); #endif // The reflection id getClassId answers and the Object.geometry.* rows test (0x100B12F0). diff --git a/Code/BF2/Geom/RoadEditable.cpp b/Code/BF2/Geom/RoadEditable.cpp index 397ec68d9..ced42b959 100644 --- a/Code/BF2/Geom/RoadEditable.cpp +++ b/Code/BF2/Geom/RoadEditable.cpp @@ -11,7 +11,12 @@ #include "../Core/EventManager.h" // eventManager's methods, ECEditor #include "../GeomMisc/EditorSpline.h" // IEditorSpline #include "../GeomMisc/PerlinNoise.h" // IPerlinNoise +#include "../GeomMisc/Debug.h" #include "../Math/Mat4.h" +#include "../RendDX9/RendDX9Math.h" // rendmath::constructIdentity, the PE 0x10077A30 product +#if defined(__APPLE__) +#include "../Platform/X87Compat.h" +#endif #include "../Physics/HeightmapCluster.h" // world::IHeightmapCluster (+0x68) #include "../Physics/HeightmapClusterEditable.h" // world::IHeightmapClusterEditable (+0x34) #include "../RendMisc/IRenderView.h" @@ -19,18 +24,18 @@ #include "../RendDX9/ShaderParameter.h" #include "../RendDX9/Texture.h" #include "../../RendDX9Abi/BfMemory.h" +#include "../../RendDX9Abi/D3dx9Sdk.h" #include "../../RendDX9Abi/Frontier.h" // renddx9abi::logf - dice's debug stream #include "../../RendDX9Abi/HostFileAbi.h" #include "../../RendDX9Abi/ModuleCommon.h" #include "../../RendDX9Abi/PluginAbi.h" #include "../../RendDX9Abi/PluginEntry.h" // classManager, fileManager, eventManager -#include "../../RendDX9Abi/Vc71String.h" +#include -#if BF2_PLUGIN_ABI_NATIVE #include "HeightmapEventNode.h" // the native host's EventNode shape -#endif #include +#include #include #include #include @@ -39,33 +44,6 @@ #include #include -// The D3DX entry points this TU calls - real static imports of the shipped image (d3dx9_25.dll). -// D3DX exports undecorated names; /alternatename maps this compiler's decorated references onto them -// (see Code/RendDX9Abi/D3dx9_25.def). The Vec3 parameters are D3DXVECTOR3* (three floats). -extern "C" HRESULT WINAPI D3DXComputeBoundingBox( - const ::dice::hfe::Vec3* firstPosition, DWORD vertexCount, DWORD stride, - ::dice::hfe::Vec3* minimum, ::dice::hfe::Vec3* maximum); -extern "C" HRESULT WINAPI D3DXComputeBoundingSphere( - const ::dice::hfe::Vec3* firstPosition, DWORD vertexCount, DWORD stride, - ::dice::hfe::Vec3* centre, float* radius); -extern "C" HRESULT WINAPI D3DXCreateRenderToSurface( - IDirect3DDevice9* device, UINT width, UINT height, D3DFORMAT format, BOOL depthStencil, - D3DFORMAT depthStencilFormat, void** renderToSurface); -extern "C" HRESULT WINAPI D3DXLoadSurfaceFromSurface( - IDirect3DSurface9* destination, const PALETTEENTRY* destinationPalette, - const RECT* destinationRect, IDirect3DSurface9* source, - const PALETTEENTRY* sourcePalette, const RECT* sourceRect, - DWORD filter, D3DCOLOR colourKey); -extern "C" HRESULT WINAPI D3DXSaveSurfaceToFileA( - const char* destinationFile, unsigned int fileFormat, IDirect3DSurface9* source, - const PALETTEENTRY* sourcePalette, const RECT* sourceRect); - -#pragma comment(linker, "/alternatename:_D3DXComputeBoundingBox@20=_D3DXComputeBoundingBox") -#pragma comment(linker, "/alternatename:_D3DXComputeBoundingSphere@20=_D3DXComputeBoundingSphere") -#pragma comment(linker, "/alternatename:_D3DXCreateRenderToSurface@28=_D3DXCreateRenderToSurface") -#pragma comment(linker, "/alternatename:_D3DXLoadSurfaceFromSurface@32=_D3DXLoadSurfaceFromSurface") -#pragma comment(linker, "/alternatename:_D3DXSaveSurfaceToFileA@20=_D3DXSaveSurfaceToFileA") - namespace dice { namespace hfe { @@ -78,7 +56,7 @@ extern void* g_raShaderConstants; // dword_1023DDBC - RenderQueues.cpp // BufferManager.cpp / StateManager.cpp, declared per TU as every other client does. void* createVertexBuffer(void* bufferManager, unsigned int count, unsigned int stride, - const vc71::string& name, unsigned int usage); + const std::string& name, unsigned int usage); void* vertexBufferLock(void* wrapper, unsigned int offsetVerts, unsigned int countVerts, unsigned int flags); bool vertexBufferUnlock(void* wrapper); @@ -140,9 +118,10 @@ const unsigned int kEventBuildFinalRoad = 304; const unsigned int kEventBuildGhostRoad = 305; const unsigned int kEventHeightmapModified = 100; -unsigned char* raConstants() +// The Ra constants block (g_raShaderConstants) word at a retail x86 byte offset. +unsigned char* raConstantAt(unsigned int byteOffset) { - return static_cast(dx9rend::g_raShaderConstants); + return dx9rend::raShaderConstantsAt(byteOffset); } dx9rend::RendDX9Base* rendererBase() @@ -181,97 +160,24 @@ world::IHeightmapCluster* heightmapCluster() // [CHOSEN, not recovered] seam (RW-268 / RW-275) - retire both copies by typing the slot in HfeAbi.h. void* classManagerGetSingletonAs(const ::renddx9abi::HostString& name, unsigned int iid) { +#if defined(_MSC_VER) typedef void* (__thiscall* GetSingletonAsFn)(void*, const ::renddx9abi::HostString&, unsigned int); void* const manager = ::dice::hfe::classManager; return reinterpret_cast((*reinterpret_cast(manager))[0x4C / 4])( manager, name, iid); -} - -// ID3DXRenderToSurface, in d3dx9core.h's slot order (the SDK header is not part of this build). -struct RenderToSurface : public IUnknown -{ - virtual HRESULT __stdcall GetDevice(IDirect3DDevice9** device) = 0; // +0x0C - virtual HRESULT __stdcall GetDesc(void* description) = 0; // +0x10 - virtual HRESULT __stdcall BeginScene(IDirect3DSurface9* surface, - const D3DVIEWPORT9* viewport) = 0; // +0x14 - virtual HRESULT __stdcall EndScene(DWORD mipFilter) = 0; // +0x18 - virtual HRESULT __stdcall OnLostDevice() = 0; // +0x1C - virtual HRESULT __stdcall OnResetDevice() = 0; // +0x20 -}; - -#if !BF2_PLUGIN_ABI_NATIVE - -// Compatibility event node with the retail host's 0x40-byte layout and affected-area payload. -// [CHOSEN] Host-owned fields remain opaque; native builds use geom::HeightmapEventNode. -// RW-275: remove this copy when EventNode matches the retail host layout. - -class RetailHeightmapEventNode -{ -public: - explicit RetailHeightmapEventNode(unsigned int eventType) - : next(0) - , pad24(0) - , type(eventType) - , pad2C(0) - { - std::memset(hostOwned, 0, sizeof(hostOwned)); - area.x = 0.0f; - area.y = 0.0f; - area.z = 0.0f; - area.w = 0.0f; - } - virtual ~RetailHeightmapEventNode() {} - virtual void release() { delete this; } - virtual int getType() const { return static_cast(type); } - - void setAffectedArea(const Vec4& value) { area = value; } - - unsigned char hostOwned[0x1C]; // +0x04 - void* next; // +0x20 - unsigned int pad24; // +0x24 - unsigned int type; // +0x28 - unsigned int pad2C; // +0x2C - Vec4 area; // +0x30 -}; - -static_assert(sizeof(RetailHeightmapEventNode) == 0x40, "0x10140633 allocates 0x40"); +#else + return ::dice::hfe::classManager->getSingletonAs(name, iid); // typed (HfeAbi.h) #endif +} -} // anonymous namespace - -#if !BF2_PLUGIN_ABI_NATIVE - -// RoadTemplateNameSet's destructor - the callee-side destruction of +0x84's by-value set -// (0x1013D0D0): erase(begin(), end()) (the whole range, so _Erase from the root, -// right subtree first, then the node's string, the node, and on to the left), then the -// head freed (`push [ebp+arg_8]; call sub_1005F360`). -namespace { -void eraseNameSubtree(RoadTemplateNameSetNode* node) -{ - while (!node->isNil) - { - eraseNameSubtree(node->right); - RoadTemplateNameSetNode* const left = node->left; - reinterpret_cast(static_cast(node->value))->~string(); - ::renddx9abi::engineFree(node); - node = left; - } -} } // anonymous namespace -RoadTemplateNameSet::~RoadTemplateNameSet() -{ - if (!head) - return; - eraseNameSubtree(head->parent); - ::renddx9abi::engineFree(head); -} -#endif // Initializes a ghost road, registers its terrain-event handler, and acquires effect handles. // The triangle count and vector allocator word remain uninitialized until geometry is built. +// PE 0x1013D100 RoadEditable::RoadEditable() : m_refCount(1) , m_template(0) @@ -310,14 +216,14 @@ RoadEditable::RoadEditable() m_effect = static_cast( dx9rend::shaderManagerGetEffect(dx9rend::g_shaderManager, "Shaders/Road")); m_paramWorldViewProjection = - dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("WorldViewProjection")); - m_paramViewPos = dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("ViewPos")); - m_paramTexLayer0 = dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("TEXLAYER0")); - m_paramTexLayer1 = dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("TEXLAYER1")); - m_paramBlendFactor = dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("BlendFactor")); - m_paramMaterial = dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("Material")); - m_paramFogRange = dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("fogRange")); - m_paramFogColor = dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("fogColor")); + dx9rend::effectGetShaderParameterTyped(m_effect, std::string("WorldViewProjection")); + m_paramViewPos = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("ViewPos")); + m_paramTexLayer0 = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("TEXLAYER0")); + m_paramTexLayer1 = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("TEXLAYER1")); + m_paramBlendFactor = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("BlendFactor")); + m_paramMaterial = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("Material")); + m_paramFogRange = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("fogRange")); + m_paramFogColor = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("fogColor")); Vec2 zero; zero.x = 0.0f; @@ -335,6 +241,7 @@ RoadEditable::RoadEditable() // owner decrement (the buffers are NOT removed from the BufferManager's tracking sets); fogRange and // fogColor released only when set. Then the members: the two polygon lists, the name, the scale // offsets. +// PE 0x1013D3E0 RoadEditable::~RoadEditable() { static_cast(static_cast(g_RoadEditableRenderer))->remove(this); // +0x14 @@ -406,7 +313,7 @@ void* RoadEditable::queryInterface(unsigned int iid) const } -// Draws the road and paired edge objects, restoring depth bias afterward. +// PE 0x1013B810. Draws the road and paired edge objects, restoring depth bias afterward. // In road-mask mode, only material IDs 1..255 draw. The queue, compiled renderer, // and template must exist whenever vertices are present; no null guards are applied. void RoadEditable::draw() @@ -429,10 +336,11 @@ void RoadEditable::draw() dx9rend::stateManagerSetRenderState(175u, roadCompiledRendererSlopeScaleDepthBiasBits()); dx9rend::IRenderView* const view = dx9rend::rendererGetRenderView(); // renderer +0x48 - Mat4 worldViewProjection = Mat4::getIdentity(); + Mat4 worldViewProjection; + rendmath::constructIdentity(worldViewProjection); // 0x1013B8AD const Mat4* const projection = view->getProjectionMatrixPtr(); // +0x6C const Mat4* const inverseView = view->getInverseViewMatrixPtr(); // +0x68 - worldViewProjection.fullMult(*inverseView, *projection); + geometryRendererMatrixProduct(worldViewProjection, *inverseView, *projection); // 0x10077A30 m_paramWorldViewProjection->setValue(&worldViewProjection, 0); // +0x18 m_paramViewPos->setValue(&view->getInverseViewMatrixPtr()->m[12], 0); m_paramTexLayer0->setValue(m_texture0, 0); @@ -440,10 +348,10 @@ void RoadEditable::draw() m_paramBlendFactor->setFloat(m_template->getBlendFactor()); // +0x24 / +0x3C m_paramMaterial->setFloat(static_cast(m_template->getMaterial()) * 0.0039215689f); // flt_101E2B98 (1/255) - m_paramFogRange->setValue(raConstants() + kRaFogRange, 0); - m_paramFogColor->setValue(raConstants() + kRaFogColor, 0); + m_paramFogRange->setValue(raConstantAt(kRaFogRange), 0); + m_paramFogColor->setValue(raConstantAt(kRaFogColor), 0); - dx9rend::effectSetTechniqueByName(m_effect, vc71::string("roadeditable")); + dx9rend::effectSetTechniqueByName(m_effect, std::string("roadeditable")); dx9rend::effectBegin(m_effect); dx9rend::effectBeginPass(m_effect, static_cast(queue->m_mode)); dx9rend::vertexBufferBindStream(m_vertexBuffer, 0); @@ -476,7 +384,7 @@ bool RoadEditable::anyChunkVisible() { return true; } // 0 // IRoadEditable - the accessors. -// the template is stored first, unconditionally; with one, both textures are released +// PE 0x1013BA60. The template is stored first, unconditionally; with one, both textures are released // (the inline owner decrement) and reloaded from its two texture files (TextureManager by name, // sub_10019260, each file copied into the by-value string argument). Then invalidate (+0x78). void RoadEditable::setTemplate(IRoadTemplate* roadTemplate) @@ -487,9 +395,9 @@ void RoadEditable::setTemplate(IRoadTemplate* roadTemplate) dx9rend::textureReleaseRef(m_texture0); dx9rend::textureReleaseRef(m_texture1); m_texture0 = static_cast(dx9rend::textureManagerGetTexture( - ::renddx9abi::toVc71String(roadTemplate->getTextureFile(0)))); // +0x14 + ::renddx9abi::fromHostString(roadTemplate->getTextureFile(0)))); // +0x14 m_texture1 = static_cast(dx9rend::textureManagerGetTexture( - ::renddx9abi::toVc71String(roadTemplate->getTextureFile(1)))); + ::renddx9abi::fromHostString(roadTemplate->getTextureFile(1)))); } invalidate(); } @@ -497,6 +405,7 @@ void RoadEditable::setTemplate(IRoadTemplate* roadTemplate) IRoadTemplate* RoadEditable::getTemplate() { return m_template; } // stored with no reference taken, then invalidate (+0x78). +// PE 0x1013B310 void RoadEditable::setSpline(IEditorSpline* spline) { m_spline = spline; @@ -505,6 +414,7 @@ void RoadEditable::setSpline(IEditorSpline* spline) IEditorSpline* RoadEditable::getSpline() { return m_spline; } +// PE 0x1013B340 void RoadEditable::setNoise(IPerlinNoise* noise) { m_noise = noise; @@ -513,7 +423,7 @@ void RoadEditable::setNoise(IPerlinNoise* noise) IPerlinNoise* RoadEditable::getNoise() { return m_noise; } -// y through the FPU, x as a dword, into element `layer` (unchecked; no invalidate). +// PE 0x1013C3F0. y through the FPU, x as a dword, into element `layer` (unchecked; no invalidate). void RoadEditable::setTextureScaleOffset(int layer, const Vec2& offset) { Vec2& element = m_textureScaleOffsets[static_cast(layer)]; @@ -521,7 +431,7 @@ void RoadEditable::setTextureScaleOffset(int layer, const Vec2& offset) element.x = offset.x; } -// the element's address (unchecked). +// PE 0x1013C410. The element's address (unchecked). const Vec2& RoadEditable::getTextureScaleOffset(int layer) { return m_textureScaleOffsets[static_cast(layer)]; @@ -532,6 +442,7 @@ int RoadEditable::getPriority() { return m_priority; } // the pair's two dwords stored, then invalidate; // the getters 0x101432C0 / D0 / E0 / F0 answer the pair's address. +// PE 0x10143350 void RoadEditable::setFadeDistAtStartLeft(Vec2 distance) { m_fadeDistAtStartLeft = distance; @@ -540,6 +451,7 @@ void RoadEditable::setFadeDistAtStartLeft(Vec2 distance) const Vec2& RoadEditable::getFadeDistAtStartLeft() { return m_fadeDistAtStartLeft; } +// PE 0x10143370 void RoadEditable::setFadeDistAtStartRight(Vec2 distance) { m_fadeDistAtStartRight = distance; @@ -548,6 +460,7 @@ void RoadEditable::setFadeDistAtStartRight(Vec2 distance) const Vec2& RoadEditable::getFadeDistAtStartRight() { return m_fadeDistAtStartRight; } +// PE 0x10143390 void RoadEditable::setFadeDistAtEndLeft(Vec2 distance) { m_fadeDistAtEndLeft = distance; @@ -556,6 +469,7 @@ void RoadEditable::setFadeDistAtEndLeft(Vec2 distance) const Vec2& RoadEditable::getFadeDistAtEndLeft() { return m_fadeDistAtEndLeft; } +// PE 0x101433B0 void RoadEditable::setFadeDistAtEndRight(Vec2 distance) { m_fadeDistAtEndRight = distance; @@ -576,7 +490,7 @@ ::renddx9abi::HostString RoadEditable::getName() return m_name; } -// only a change does anything: the byte stored, then buildGeometry (+0x88) with the +// PE 0x1013B620. Only a change does anything: the byte stored, then buildGeometry (+0x88) with the // template's width and max error(0) - the error asked for first - and the new state. void RoadEditable::setGhost(bool ghost) { @@ -602,7 +516,7 @@ ::renddx9abi::HostString RoadEditable::getCompiledMeshPath() return path; } -// Releases buffers and rebuilds when a spline and template exist. +// PE 0x1013BC80. Releases buffers and rebuilds when a spline and template exist. // The vertex pointer is left stale and buildGeometry releases it again; preserve this legacy // behavior. Missing inputs also leave the old vertex count and pointer available to draw. void RoadEditable::invalidate() @@ -661,6 +575,7 @@ void RoadEditable::releaseBuffersForEditor() // Rebuilds road buffers and bounds from at least four control points. // Uses template width/error rather than the arguments. Empty triangle output leaves buffers alone. +// PE 0x1013FC00 void RoadEditable::buildGeometry(float /*width - not read*/, float /*maxError - not read*/, bool ghost) { if (m_spline->getControlPointCount() < 4) // +0x54 @@ -685,7 +600,7 @@ void RoadEditable::buildGeometry(float /*width - not read*/, float /*maxError - } m_vertexBuffer = dx9rend::createVertexBuffer(dx9rend::g_bufferManager, static_cast(m_vertexCount), 32u, - vc71::string("RoadEditable"), 0u); + std::string("RoadEditable"), 0u); float* destination = static_cast(dx9rend::vertexBufferLock(m_vertexBuffer, 0u, 0u, 0u)); for (int i = 0; i < m_vertexCount; ++i) { @@ -723,13 +638,15 @@ void RoadEditable::buildGeometry(float /*width - not read*/, float /*maxError - Vec3 maximum; minimum.x = minimum.y = minimum.z = 0.0f; maximum.x = maximum.y = maximum.z = 0.0f; - D3DXComputeBoundingBox(&vertices[0].position, static_cast(vertices.size()), 64u, - &minimum, &maximum); + D3DXComputeBoundingBox(reinterpret_cast(&vertices[0].position), + static_cast(vertices.size()), static_cast(sizeof(vertices[0])), // 64 + reinterpret_cast(&minimum), reinterpret_cast(&maximum)); m_bounds.min = minimum; m_bounds.max = maximum; m_bounds.dirty = 1; - D3DXComputeBoundingSphere(&vertices[0].position, static_cast(vertices.size()), 64u, - &m_centre, &m_radius); + D3DXComputeBoundingSphere(reinterpret_cast(&vertices[0].position), + static_cast(vertices.size()), static_cast(sizeof(vertices[0])), // 64 + reinterpret_cast(&m_centre), &m_radius); dx9rend::bufferManagerSwapPool(savedPool); } @@ -738,7 +655,7 @@ void RoadEditable::buildGeometry(float /*width - not read*/, float /*maxError - // The caller must truncate the .con first and provide terrain and writable output paths. // The version-1.4 mesh omits the chunk table expected by the reader. Ghost state is restored. // [CHOSEN] Host float formatting may use two-digit rather than three-digit exponents. - +// PE 0x1013BDE0 bool RoadEditable::compile(const ::renddx9abi::HostString& levelPath) { if (!m_vertexCount) @@ -751,7 +668,7 @@ bool RoadEditable::compile(const ::renddx9abi::HostString& levelPath) buildGeometry(width, maxError, false); } - vc71::string savePath; + std::string savePath; dx9rend::readStringSettingDefault("Editor_LevelSavePath", " ERROR ", savePath); // settings +0x40 ::renddx9abi::HostString conPath = ::renddx9abi::makeHostString(savePath); conPath += "\\"; @@ -848,6 +765,7 @@ bool RoadEditable::compile(const ::renddx9abi::HostString& levelPath) // (`retn 10h`) - a stub: the by-value set is destroyed (the callee's job) and the answer // is true. The path is not read. +// PE 0x1013D0D0 bool RoadEditable::compileTemplates(const ::renddx9abi::HostString&, RoadTemplateNameSet) { return true; @@ -860,6 +778,7 @@ bool RoadEditable::compileTemplates(const ::renddx9abi::HostString&, RoadTemplat // preserves the existing held buffers/open state bracket, and pixel traversal ignores pitch. // The editor flavour takes the 8-bit target, sizes it to the footprint, retries a smaller one when // the copy back fails, cleans up when none works, and reads at the pitch (see the body). +// PE 0x1013FED0 void RoadEditable::projectToTerrain() { if (m_spline->getControlPointCount() < 4 || !m_spline || !m_template) @@ -894,7 +813,7 @@ void RoadEditable::projectToTerrain() dx9rend::stateManagerPush(); void* const positions = dx9rend::createVertexBuffer(dx9rend::g_bufferManager, static_cast(vertexCount), 12u, - vc71::string("RoadEditable"), 8u); + std::string("RoadEditable"), 8u); float* out = static_cast(dx9rend::vertexBufferLock(positions, 0u, 0u, 0u)); for (int i = 0; i < vertexCount; ++i) { @@ -968,9 +887,9 @@ void RoadEditable::projectToTerrain() if (device->CreateOffscreenPlainSurface(static_cast(size), static_cast(size), format, D3DPOOL_SYSTEMMEM, &rendering, 0) != 0) continue; - RenderToSurface* target = 0; + ID3DXRenderToSurface* target = 0; if (D3DXCreateRenderToSurface(device, static_cast(size), static_cast(size), format, - FALSE, D3DFMT_UNKNOWN, reinterpret_cast(&target)) != 0) + FALSE, D3DFMT_UNKNOWN, &target) != 0) { rendering->Release(); continue; @@ -1002,7 +921,7 @@ void RoadEditable::projectToTerrain() const float spanY = maximum.y - minimum.y; constant2[1] = 1.0f / spanY; - dx9rend::effectSetTechniqueByName(m_effect, vc71::string("projectroad")); + dx9rend::effectSetTechniqueByName(m_effect, std::string("projectroad")); dx9rend::effectBegin(m_effect); dx9rend::effectBeginPass(m_effect, 0); device->SetVertexShaderConstantF(0, constant0, 1); // +0x178 @@ -1043,7 +962,7 @@ void RoadEditable::projectToTerrain() dx9rend::bufferManagerRemoveIndexBuffer(footprintIndices); } if (floatTarget) - D3DXSaveSurfaceToFileA("c:\\tbmTest.dds", 4u, rendering, 0, 0); // D3DXIFF_DDS + D3DXSaveSurfaceToFileA("c:\\tbmTest.dds", D3DXIFF_DDS, rendering, 0, 0); const int x0 = static_cast(std::floor(static_cast(minimum.x))); const int z0 = static_cast(std::floor(static_cast(minimum.z))); @@ -1101,15 +1020,9 @@ void RoadEditable::projectToTerrain() area.y = static_cast(z0); area.z = static_cast(x1); area.w = static_cast(z1); -#if BF2_PLUGIN_ABI_NATIVE HeightmapEventNode* const node = new HeightmapEventNode(kEventHeightmapModified); node->setAffectedArea(area); ::dice::hfe::eventManager->postEvent(ECEditor, node, 0.0f); // +0x14 -#else - RetailHeightmapEventNode* const node = new RetailHeightmapEventNode(kEventHeightmapModified); - node->setAffectedArea(area); - ::dice::hfe::eventManager->postEvent(ECEditor, reinterpret_cast(node), 0.0f); -#endif #if defined(BF2_IMAGE_EDITOR) && BF2_IMAGE_EDITOR projected = true; #endif @@ -1148,6 +1061,7 @@ bool RoadEditable::makeScript(::dice::hfe::io::IStream*) // projectToTerrain, then invalidate; 300 the template -> invalidate; 301 the template -> // setTemplate(0); 302 / 303 this road -> invalidate; 304 / 305 this road -> setGhost(false / true). // Every reaction is a virtual call through the primary table. +// PE 0x1013B4C0 void RoadEditable::handleEvent(EventCategory, unsigned int id, EventNode*, void* data) { switch (id) @@ -1190,17 +1104,15 @@ void RoadEditable::handleEvent(EventCategory, unsigned int id, EventNode*, void* } -// RefFactory refuse aggregation, 0x118 bytes, construct, QI with NO null test on the -// object (shipped), release on refusal. (The native flavour's object is smaller - its HostString is -// the host's std::string - and still fits the shipped block.) +// RefFactory refuse aggregation, the object (retail 0x118 bytes), construct, QI with NO null test +// on the object (shipped), release on refusal. IBase* __fastcall createRoadEditable(unsigned int iid, IBase* outer) { if (outer) return 0; - static_assert(sizeof(RoadEditable) <= 0x118, "the shipped 0x118-byte block must hold the object"); - void* const storage = ::renddx9abi::engineAlloc(0x118); + void* const storage = ::renddx9abi::engineAlloc(sizeof(RoadEditable)); RoadEditable* self = 0; if (storage) self = new (storage) RoadEditable(); diff --git a/Code/BF2/Geom/RoadEditable.h b/Code/BF2/Geom/RoadEditable.h index 1c299306d..fea4ea7cc 100644 --- a/Code/BF2/Geom/RoadEditable.h +++ b/Code/BF2/Geom/RoadEditable.h @@ -12,8 +12,6 @@ #include "IRoadEditable.h" #include "MeshTemplate.h" // MeshBounds -#include "UndergrowthSystem.h" // Vc71Vec -#include "Vc71ValueList.h" #include "../Game/IEventListener.h" #include "../IO/Console/IConsoleSaveable.h" #include "../Math/Vec3.h" @@ -21,6 +19,7 @@ #include "../../RendDX9Abi/PluginAbi.h" // renddx9abi::HostString #include +#include #include namespace dice { @@ -53,7 +52,7 @@ struct RoadEditableVertex RoadEditableVertex(const Vec3& samplePosition, const Vec3& sampleNormal); // (`retn 0Ch`, this = the result): position and normal through the Vec3 lerp - // (0x10106AE0), both uv sets as a * (1 - t) + b * t, alpha as (b - a) * t + a. The flag and the + // (lerpVec3), both uv sets as a * (1 - t) + b * t, alpha as (b - a) * t + a. The flag and the // four floats are left as they were. void interpolate(const RoadEditableVertex& a, const RoadEditableVertex& b, float t); // the same without position and normal. @@ -61,7 +60,7 @@ struct RoadEditableVertex }; typedef std::vector RoadPolygon; -typedef Vc71ValueList RoadPolygonList; +typedef std::list RoadPolygonList; class RoadEditable : public IRoadEditable, public ::dice::hfe::io::IConsoleSaveable, @@ -138,7 +137,7 @@ class RoadEditable : public IRoadEditable, IEditorSpline* m_edge0; // +0x18 [INFERRED] type, never set IEditorSpline* m_edge1; // +0x1C IPerlinNoise* m_noise; // +0x20 - Vc71Vec m_textureScaleOffsets; // +0x24 + std::vector m_textureScaleOffsets; // +0x24 int m_vertexCount; // +0x34 int m_triangleCount; // +0x38 not written by the ctor void* m_vertexBuffer; // +0x3C @@ -180,31 +179,7 @@ static_assert(offsetof(RoadEditableVertex, needsUv) == 0x28, "flag byte at +0x28 static_assert(offsetof(RoadEditableVertex, alpha) == 0x3C, "alpha at +0x3C"); #endif -// The retail flavour's layout is the shipped one. In the native flavour HostString is the host's -// std::string, so the name takes that type's size instead - the object never crosses the boundary by -// layout, only through its slots. -#if defined(_M_IX86) && !BF2_PLUGIN_ABI_NATIVE -static_assert(offsetof(RoadEditable, m_refCount) == 0x0C, "refCount at +0x0C"); -static_assert(offsetof(RoadEditable, m_template) == 0x10, "template at +0x10"); -static_assert(offsetof(RoadEditable, m_noise) == 0x20, "noise at +0x20"); -static_assert(offsetof(RoadEditable, m_textureScaleOffsets) == 0x24, "scale offsets at +0x24"); -static_assert(offsetof(RoadEditable, m_vertexCount) == 0x34, "vertex count at +0x34"); -static_assert(offsetof(RoadEditable, m_vertexBuffer) == 0x3C, "vertex buffer at +0x3C"); -static_assert(offsetof(RoadEditable, m_texture0) == 0x44, "texture 0 at +0x44"); -static_assert(offsetof(RoadEditable, m_effect) == 0x4C, "effect at +0x4C"); -static_assert(offsetof(RoadEditable, m_paramFogColor) == 0x6C, "fogColor handle at +0x6C"); -static_assert(offsetof(RoadEditable, m_centre) == 0x70, "sphere centre at +0x70"); -static_assert(offsetof(RoadEditable, m_radius) == 0x7C, "sphere radius at +0x7C"); -static_assert(offsetof(RoadEditable, m_bounds) == 0x80, "bounds at +0x80"); -static_assert(offsetof(RoadEditable, m_name) == 0xBC, "name at +0xBC"); -static_assert(offsetof(RoadEditable, m_pendingPolygons) == 0xD8, "pending polygons at +0xD8"); -static_assert(offsetof(RoadEditable, m_readyPolygons) == 0xE4, "ready polygons at +0xE4"); -static_assert(offsetof(RoadEditable, m_ghost) == 0xF0, "ghost byte at +0xF0"); -static_assert(offsetof(RoadEditable, m_priority) == 0xF4, "priority at +0xF4"); -static_assert(offsetof(RoadEditable, m_fadeDistAtStartLeft) == 0xF8, "fade start-left at +0xF8"); -static_assert(offsetof(RoadEditable, m_fadeDistAtEndRight) == 0x110, "fade end-right at +0x110"); -static_assert(sizeof(RoadEditable) == 0x118, "the factory 0x100B0A1B allocates 0x118"); -#endif +// The object never crosses the boundary by layout, only through its slots. // RefFactory published by ModuleGeom::getClassList. IBase* __fastcall createRoadEditable(unsigned int iid, IBase* outer); diff --git a/Code/BF2/Geom/RoadEditableRenderer.cpp b/Code/BF2/Geom/RoadEditableRenderer.cpp index 27ea1ad88..06234bd0d 100644 --- a/Code/BF2/Geom/RoadEditableRenderer.cpp +++ b/Code/BF2/Geom/RoadEditableRenderer.cpp @@ -30,8 +30,8 @@ const int kNoPriority = 999999999; } // anonymous namespace -// vptr, refCount 1, the flag byte 0, the list (a fresh head, size 0 - the allocator word -// is not written), +0x18 = 0. +// vptr, refCount 1, the flag byte 0, the empty list, +0x18 = 0. +// PE 0x10144440 RoadEditableRenderer::RoadEditableRenderer() : m_refCount(1) , m_flag08(0) @@ -75,47 +75,50 @@ void* RoadEditableRenderer::queryInterface(unsigned int iid) const // the _Incsize test). void RoadEditableRenderer::add(IRoadEditable* road) { - RoadEditableListNode* const head = m_roads.head; - for (RoadEditableListNode* node = head->next; node != head; node = node->next) + for (RoadEditableList::iterator node = m_roads.begin(); node != m_roads.end(); ++node) { - if (node->value == road) + if (*node == road) return; } - m_roads.insert(m_roads.head, road); + m_roads.push_back(road); } -// erase(find(begin, end, road)): the first match only; erase's own `node != head` guard -// makes an absent road a no-op. +// erase(find(begin, end, road)): the first match only; the shipped erase's own `node != head` +// guard makes an absent road a no-op. +// PE 0x101443F0 void RoadEditableRenderer::remove(IRoadEditable* road) { - RoadEditableListNode* const head = m_roads.head; - RoadEditableListNode* node = head->next; - while (node != head && node->value != road) - node = node->next; - m_roads.erase(node); + RoadEditableList::iterator node = m_roads.begin(); + while (node != m_roads.end() && *node != road) + ++node; + if (node != m_roads.end()) + m_roads.erase(node); } // Draws a copy of the road queue by template priority, then road priority within a template. // Changes to the original queue during draw do not affect this pass. Clears the coverage // mask before drawing. At least one remaining template priority must be below 999999999; // otherwise winner selection leaves a null pointer. Priority calls remain repeated. +// PE 0x10144520 void RoadEditableRenderer::drawAll() { RoadEditableList queue(m_roads); - if (queue.size > 0) + if (!queue.empty()) { lightManagerSetRenderTargetTexture(0, dx9rend::rendererGetHemiScratchTexture()); dx9rend::stateManagerClear(1u, 0x00FFFFFFu, 0.0f, 0u); lightManagerSetRenderTargetTexture(0, 0); do { - RoadEditableListNode* best = 0; + // No winner leaves `best` singular and the draw below dereferences it, as shipped + // (retail: a null node). + RoadEditableList::iterator best = RoadEditableList::iterator(); IRoadTemplate* bestTemplate = 0; int lowestTemplatePriority = kNoPriority; int lowestRoadPriority = kNoPriority; - for (RoadEditableListNode* node = queue.head->next; node != queue.head; node = node->next) + for (RoadEditableList::iterator node = queue.begin(); node != queue.end(); ++node) { - IRoadEditable* const road = node->value; + IRoadEditable* const road = *node; IRoadTemplate* const roadTemplate = road->getTemplate(); // +0x20 if (roadTemplate->getPriority() < lowestTemplatePriority) // +0x4C { @@ -131,10 +134,10 @@ void RoadEditableRenderer::drawAll() best = node; } } - best->value->draw(); // +0x10 + (*best)->draw(); // +0x10 queue.erase(best); } - while (queue.size > 0); + while (!queue.empty()); } } @@ -142,15 +145,15 @@ void RoadEditableRenderer::setFlag08(bool value) { m_flag08 = value ? 1 : 0; bool RoadEditableRenderer::getFlag08() { return m_flag08 != 0; } -// RefFactory refuse aggregation, 0x1C bytes, construct, QI with NO null test on the -// object (shipped), release on refusal. +// RefFactory refuse aggregation, the object (retail 0x1C bytes), construct, QI with NO null +// test on the object (shipped), release on refusal. IBase* __fastcall createRoadEditableRenderer(unsigned int iid, IBase* outer) { if (outer) return 0; - void* const storage = ::renddx9abi::engineAlloc(0x1C); + void* const storage = ::renddx9abi::engineAlloc(sizeof(RoadEditableRenderer)); RoadEditableRenderer* self = 0; if (storage) self = new (storage) RoadEditableRenderer(); diff --git a/Code/BF2/Geom/RoadEditableRenderer.h b/Code/BF2/Geom/RoadEditableRenderer.h index e3ba39b09..1ca401a9e 100644 --- a/Code/BF2/Geom/RoadEditableRenderer.h +++ b/Code/BF2/Geom/RoadEditableRenderer.h @@ -9,17 +9,16 @@ #include "IRoadEditable.h" #include "IRoadEditableRenderer.h" // IRoadEditableRenderer (table 0x1021DA00), shared with the editor -#include "Vc71PtrList.h" #include "../../RendDX9Abi/HfeAbi.h" #include +#include namespace dice { namespace hfe { namespace geom { -typedef Vc71PtrList RoadEditableList; -typedef Vc71PtrListNode RoadEditableListNode; +typedef std::list RoadEditableList; class RoadEditableRenderer : public IRoadEditableRenderer @@ -56,8 +55,6 @@ class RoadEditableRenderer : public IRoadEditableRenderer static_assert(offsetof(RoadEditableRenderer, m_refCount) == 0x04, "refCount at +0x04"); static_assert(offsetof(RoadEditableRenderer, m_flag08) == 0x08, "flag byte at +0x08"); static_assert(offsetof(RoadEditableRenderer, m_roads) == 0x0C, "road list at +0x0C"); -static_assert(offsetof(RoadEditableRenderer, m_mode) == 0x18, "mode word at +0x18"); -static_assert(sizeof(RoadEditableRenderer) == 0x1C, "the factory 0x100B0A5D allocates 0x1C"); #endif // RefFactory published by ModuleGeom::getClassList. diff --git a/Code/BF2/Geom/RoadEditableTessellate.inl b/Code/BF2/Geom/RoadEditableTessellate.inl index fd53a0704..891add1e8 100644 --- a/Code/BF2/Geom/RoadEditableTessellate.inl +++ b/Code/BF2/Geom/RoadEditableTessellate.inl @@ -1,6 +1,6 @@ // Road spline sampling, terrain-grid clipping, triangulation and texture interpolation. // [CHOSEN, not recovered] included split of RoadEditable.cpp; never compile it separately. -// Preserve float association/24-bit precision and the explicit double-precision sort keys. +// Preserve operand association and the observed float/double stores. namespace dice { namespace hfe { @@ -8,6 +8,46 @@ namespace geom { namespace { +#if defined(__APPLE__) +// [CHOSEN, not recovered] Keep the x87 register values until the observed stores on native hosts. +typedef bf2x87::Real RoadScalar; +typedef bf2x87::Real RoadDouble; +#else +typedef float RoadScalar; +typedef double RoadDouble; +#endif + +template +bool roadLess(T a, U b) +{ +#if defined(__APPLE__) + // [CHOSEN, not recovered] These sites use FCOM, including its invalid flag for quiet NaNs. + return bf2x87::less(RoadScalar(a), RoadScalar(b)); +#else + return a < b; +#endif +} + +template +bool roadLessEqual(T a, U b) +{ +#if defined(__APPLE__) + // [CHOSEN, not recovered] FCOM equality/range tests through the native arithmetic backend. + return bf2x87::lessEqual(RoadScalar(a), RoadScalar(b)); +#else + return a <= b; +#endif +} + +RoadScalar roadSquareRoot(RoadScalar value) +{ +#if defined(__APPLE__) + // [CHOSEN, not recovered] The shared native FSQRT policy. + return bf2x87::squareRoot(value); +#else + return std::sqrt(value); +#endif +} // Small vector arithmetic, in the shipped operand order. @@ -32,13 +72,27 @@ float lengthSumYXZ(float x, float y, float z) { return std::sqrt((y * y + x * x) float lengthXZ(float x, float z) { return std::sqrt(x * x + z * z); } // (thiscall on `out`, `retn 0Ch`) - out = a, then each component (b - a) * t + a. +// PE 0x10106AE0 void lerpVec3(Vec3& out, const Vec3& a, const Vec3& b, float t) { const Vec3 start = a; out = start; +#if defined(__APPLE__) + // [CHOSEN, not recovered] Preserve the asymmetric FSTP spills before the three additions. + const RoadScalar dx = RoadScalar(b.x) - out.x; + const RoadScalar dy = RoadScalar(b.y) - start.y; + const float dz = bf2x87::store(RoadScalar(b.z) - start.z); + const float scaledX = bf2x87::store(dx * t); + const RoadScalar scaledY = dy * t; + const float scaledZ = bf2x87::store(RoadScalar(dz) * t); + out.x = bf2x87::store(RoadScalar(scaledX) + out.x); + out.y = bf2x87::store(scaledY + start.y); + out.z = bf2x87::store(RoadScalar(scaledZ) + start.z); +#else out.x = (b.x - start.x) * t + start.x; out.y = (b.y - start.y) * t + start.y; out.z = (b.z - start.z) * t + start.z; +#endif } } // anonymous namespace @@ -76,7 +130,8 @@ RoadEditableVertex::RoadEditableVertex(const Vec3& samplePosition, const Vec3& s unknown2C[0] = unknown2C[1] = unknown2C[2] = unknown2C[3] = 0.0f; } -// w = 1 - t once; each uv component is w*a + t*b (the product of a and w is formed first). +// Interpolates position and normal, then the two texture layers and alpha. +// PE 0x1013B670 void RoadEditableVertex::interpolate(const RoadEditableVertex& a, const RoadEditableVertex& b, float t) { lerpVec3(position, a.position, b.position, t); @@ -84,16 +139,32 @@ void RoadEditableVertex::interpolate(const RoadEditableVertex& a, const RoadEdit interpolateTexCoords(a, b, t); } - +// Blends the two texture layers and alpha, preserving the layer-specific float stores. +// PE 0x1013B760 void RoadEditableVertex::interpolateTexCoords(const RoadEditableVertex& a, const RoadEditableVertex& b, float t) { - const float w = 1.0f - t; // flt_101DDDE4 - t - uv0.x = w * a.uv0.x + t * b.uv0.x; - uv0.y = w * a.uv0.y + t * b.uv0.y; - uv1.x = w * a.uv1.x + t * b.uv1.x; - uv1.y = w * a.uv1.y + t * b.uv1.y; - alpha = (b.alpha - a.alpha) * t + a.alpha; + uv0 = a.uv0; + const RoadScalar w = RoadScalar(1.0f) - t; + const RoadScalar leftU0 = w * uv0.x; + uv0.x = static_cast(leftU0); + const float leftV0 = static_cast(w * uv0.y); + uv0.y = leftV0; + const RoadScalar rightU0 = RoadScalar(t) * b.uv0.x; + const float rightV0 = static_cast(RoadScalar(t) * b.uv0.y); + uv0.x = static_cast(leftU0 + rightU0); + uv0.y = static_cast(RoadScalar(leftV0) + rightV0); + + uv1 = a.uv1; + const float leftU1 = static_cast(w * uv1.x); + uv1.x = leftU1; + const RoadScalar leftV1 = w * uv1.y; + uv1.y = static_cast(leftV1); + const RoadScalar rightU1 = RoadScalar(t) * b.uv1.x; + const float rightV1 = static_cast(RoadScalar(t) * b.uv1.y); + uv1.x = static_cast(RoadScalar(leftU1) + rightU1); + uv1.y = static_cast(leftV1 + rightV1); + alpha = static_cast((RoadScalar(b.alpha) - a.alpha) * t + a.alpha); } namespace { @@ -104,12 +175,14 @@ namespace { // v = (c.z - a.z)(b.x - a.x) - (b.z - a.z)(c.x - a.x); 1 above 0.5, -1 below -0.5 (both // double constants), else 0 - a NaN answers 0. +// PE 0x1013B370 int areaSign(const Vec3& a, const Vec3& b, const Vec3& c) { - const float v = (c.z - a.z) * (b.x - a.x) - (b.z - a.z) * (c.x - a.x); - if (v > 0.5) // dbl_1020D7D0 + const RoadScalar v = (RoadScalar(c.z) - a.z) * (RoadScalar(b.x) - a.x) + - (RoadScalar(b.z) - a.z) * (RoadScalar(c.x) - a.x); + if (roadLess(0.5, v)) // dbl_1020D7D0 return 1; - if (v < -0.5) // dbl_1021D798 + if (roadLess(v, -0.5)) // dbl_1021D798 return -1; return 0; } @@ -117,23 +190,33 @@ int areaSign(const Vec3& a, const Vec3& b, const Vec3& c) // (`retn 18h`) - segment a-b against c-d. |denominator| below FLT_EPSILON answers false // without writing s or t; otherwise both are written, and the answer is whether both lie strictly // inside (0, 1) - a NaN passes every range test. +// PE 0x1013B3D0 bool segmentsIntersect(const Vec3& a, const Vec3& b, const Vec3& c, const Vec3& d, float* s, float* t) { - const float denominator = (d.z - c.z) * (b.x - a.x) - (d.x - c.x) * (b.z - a.z); - if (std::fabs(denominator) < FLT_EPSILON) // flt_101E05A0 + const RoadScalar denominator = (RoadScalar(d.z) - c.z) * (RoadScalar(b.x) - a.x) + - (RoadScalar(d.x) - c.x) * (RoadScalar(b.z) - a.z); +#if defined(__APPLE__) + const RoadScalar magnitude = bf2x87::abs(denominator); +#else + const RoadScalar magnitude = std::fabs(denominator); +#endif + if (roadLess(magnitude, FLT_EPSILON)) // flt_101E05A0 return false; - const float inverse = 1.0f / denominator; - *s = ((a.z - c.z) * (d.x - c.x) - (d.z - c.z) * (a.x - c.x)) * inverse; - const float tValue = inverse * ((a.z - c.z) * (b.x - a.x) - (b.z - a.z) * (a.x - c.x)); - *t = tValue; - if (tValue <= 0.0f || tValue >= 1.0f) + const RoadScalar inverse = RoadScalar(1.0f) / denominator; + *s = static_cast(((RoadScalar(a.z) - c.z) * (RoadScalar(d.x) - c.x) + - (RoadScalar(d.z) - c.z) * (RoadScalar(a.x) - c.x)) * inverse); + const RoadScalar tValue = ((RoadScalar(a.z) - c.z) * (RoadScalar(b.x) - a.x) + - (RoadScalar(b.z) - a.z) * (RoadScalar(a.x) - c.x)) * inverse; + *t = static_cast(tValue); + if (roadLessEqual(tValue, 0.0f) || roadLessEqual(1.0f, tValue)) return false; - if (*s <= 0.0f || *s >= 1.0f) + if (roadLessEqual(*s, 0.0f) || roadLessEqual(1.0f, *s)) return false; return true; } // is c on segment a-b? Along x unless a.x == b.x (then along z); inclusive both ways. +// PE 0x1013BBD0 int between(const Vec3& a, const Vec3& b, const Vec3& c) { if (a.x != b.x) @@ -144,6 +227,7 @@ int between(const Vec3& a, const Vec3& b, const Vec3& c) // (`retn 14h`) - the collinear case of segmentIntersection: '0' unless c is on the line // a-b; then the first of c, d (on a-b) or a, b (on c-d) that lies on the other segment, copied to p, // with 'e'. +// PE 0x1013BD10 char parallelIntersection(const Vec3& a, const Vec3& b, const Vec3& c, const Vec3& d, Vec3& p) { if (areaSign(a, b, c) != 0) @@ -173,33 +257,39 @@ char parallelIntersection(const Vec3& a, const Vec3& b, const Vec3& c, const Vec // (`retn 1Ch`) - O'Rourke's SegSegInt on x/z: '1' proper crossing, 'v' a vertex of one // segment on the other, '0' none, 'e' collinear overlap, '?' none of those decided. s (along a-b) -// and t (along c-d) are stored as doubles but carry float precision - the inverse is formed at 24 -// bits (`fld 1.0; fdiv`) and kept as a float (`fst` to a dword). The point is lerp(a, b, s). +// and t (along c-d) are stored as doubles; the denominator and inverse also have qword spills. +// The first product uses the retained inverse, and the second reloads its double spill. +// The point is lerp(a, b, float(s)). // The collinear arm returns from parallelIntersection without writing s or t (shipped). +// PE 0x1013C420 char segmentIntersection(const Vec3& a, const Vec3& b, const Vec3& c, const Vec3& d, Vec3& p, double& s, double& t) { char code = '?'; - const float denominator = (((a.z - b.z) * c.x + (c.z - d.z) * b.x) + (b.z - a.z) * d.x) - + (d.z - c.z) * a.x; + const RoadDouble denominator = (((RoadDouble(a.z) - b.z) * c.x + (RoadDouble(c.z) - d.z) * b.x) + + (RoadDouble(b.z) - a.z) * d.x) + (RoadDouble(d.z) - c.z) * a.x; + const double storedDenominator = static_cast(denominator); if (denominator == 0.0) return parallelIntersection(a, b, c, d, p); - const float numerator = ((c.z - a.z) * d.x + (a.z - d.z) * c.x) + (d.z - c.z) * a.x; + const RoadDouble numerator = ((RoadDouble(c.z) - a.z) * d.x + (RoadDouble(a.z) - d.z) * c.x) + + (RoadDouble(d.z) - c.z) * a.x; if (numerator == 0.0 || numerator == denominator) code = 'v'; - const float inverse = 1.0f / denominator; // dbl_101E0260 / denominator + const RoadDouble inverse = RoadDouble(1.0) / denominator; + const double storedInverse = static_cast(inverse); s = static_cast(inverse * numerator); - const float numerator2 = -(((b.z - a.z) * c.x + (a.z - c.z) * b.x) + (c.z - b.z) * a.x); - if (numerator2 == 0.0 || numerator2 == denominator) + const RoadDouble numerator2 = -(((RoadDouble(b.z) - a.z) * c.x + (RoadDouble(a.z) - c.z) * b.x) + + (RoadDouble(c.z) - b.z) * a.x); + if (numerator2 == 0.0 || numerator2 == storedDenominator) code = 'v'; - const float tValue = numerator2 * inverse; + const RoadDouble tValue = numerator2 * storedInverse; t = static_cast(tValue); - if (0.0 < s && s < 1.0 && 0.0 < tValue && tValue < 1.0) + if (roadLess(0.0, s) && roadLess(s, 1.0) && roadLess(0.0, tValue) && roadLess(tValue, 1.0)) code = '1'; - else if (s < 0.0 || s > 1.0 || tValue < 0.0 || tValue > 1.0) + else if (roadLess(s, 0.0) || roadLess(1.0, s) || roadLess(tValue, 0.0) || roadLess(1.0, tValue)) code = '0'; lerpVec3(p, a, b, static_cast(s)); @@ -208,29 +298,36 @@ char segmentIntersection(const Vec3& a, const Vec3& b, const Vec3& c, const Vec3 // v = (c.x - a.x)(b.z - a.z) - (c.z - a.z)(b.x - a.x); false only when v < 0 (a NaN is // "left"). +// PE 0x101406E0 bool leftOn(const Vec3& a, const Vec3& b, const Vec3& c) { - const float v = (c.x - a.x) * (b.z - a.z) - (c.z - a.z) * (b.x - a.x); - return !(v < 0.0f); + const RoadScalar v = (RoadScalar(c.x) - a.x) * (RoadScalar(b.z) - a.z) + - (RoadScalar(c.z) - a.z) * (RoadScalar(b.x) - a.x); + return !roadLess(v, 0.0f); } // the two edge tests a-b and b-c, then leftOn(c, a, p). +// PE 0x10140730 bool pointInTriangle(const Vec3& a, const Vec3& b, const Vec3& c, const Vec3& p) { - if ((b.z - a.z) * (p.x - a.x) - (p.z - a.z) * (b.x - a.x) < 0.0f) + if (roadLess((RoadScalar(b.z) - a.z) * (RoadScalar(p.x) - a.x) + - (RoadScalar(p.z) - a.z) * (RoadScalar(b.x) - a.x), 0.0f)) return false; - if ((c.z - b.z) * (p.x - b.x) - (p.z - b.z) * (c.x - b.x) < 0.0f) + if (roadLess((RoadScalar(c.z) - b.z) * (RoadScalar(p.x) - b.x) + - (RoadScalar(p.z) - b.z) * (RoadScalar(c.x) - b.x), 0.0f)) return false; return leftOn(c, a, p); } // the leftOn value's sign into `side`: -1 below 0, 1 above, 0 otherwise (NaN too). +// PE 0x101407D0 void orient(const Vec3& a, const Vec3& b, const Vec3& c, int& side) { - const float v = (c.x - a.x) * (b.z - a.z) - (c.z - a.z) * (b.x - a.x); - if (v < 0.0f) + const RoadScalar v = (RoadScalar(c.x) - a.x) * (RoadScalar(b.z) - a.z) + - (RoadScalar(c.z) - a.z) * (RoadScalar(b.x) - a.x); + if (roadLess(v, 0.0f)) side = -1; - else if (v > 0.0f) + else if (roadLess(0.0f, v)) side = 1; else side = 0; @@ -239,19 +336,19 @@ void orient(const Vec3& a, const Vec3& b, const Vec3& c, int& side) // Interpolates target texture coordinates in the x/z triangle; returns false outside it. // Out-of-range ratios repeat the edge calculation but still use the original result. -// [CHOSEN] A degenerate parallel intersection uses zero for the unwritten edge parameter. - +// Shipped defect: a parallel edge leaves the interpolation parameter unwritten. +// PE 0x10140BD0 bool interpolateInTriangle(const RoadEditableVertex& a, const RoadEditableVertex& b, const RoadEditableVertex& c, RoadEditableVertex& target) { - const float winding = ((a.position.z * c.position.x - a.position.x * c.position.z) - + (a.position.x * b.position.z - a.position.z * b.position.x)) - + (b.position.x * c.position.z - c.position.x * b.position.z); + const RoadScalar winding = ((RoadScalar(a.position.z) * c.position.x - RoadScalar(a.position.x) * c.position.z) + + (RoadScalar(a.position.x) * b.position.z - RoadScalar(a.position.z) * b.position.x)) + + (RoadScalar(b.position.x) * c.position.z - RoadScalar(c.position.x) * b.position.z); RoadEditableVertex p0; RoadEditableVertex p1; RoadEditableVertex p2; p0 = a; - if (winding > 0.0f) // `test ah, 41h; jnz` - zero and NaN take b, c + if (roadLess(0.0f, winding)) // `test ah, 41h; jnz` - zero and NaN take b, c { p1 = c; p2 = b; @@ -265,14 +362,19 @@ bool interpolateInTriangle(const RoadEditableVertex& a, const RoadEditableVertex return false; Vec3 point = makeVec3(0.0f, 0.0f, 0.0f); - double s = 0.0; - double t = 0.0; + double s; + double t; segmentIntersection(p2.position, p1.position, p0.position, target.position, point, s, t); RoadEditableVertex edge; edge.interpolate(p2, p1, static_cast(s)); - const float ratio = lengthXZ(target.position.x - p0.position.x, target.position.z - p0.position.z) - / lengthXZ(edge.position.x - p0.position.x, edge.position.z - p0.position.z); - if (ratio < 0.0 || ratio > 1.0) + const RoadScalar targetX = RoadScalar(target.position.x) - p0.position.x; + const RoadScalar targetZ = RoadScalar(target.position.z) - p0.position.z; + const float edgeX = edge.position.x - p0.position.x; + const float edgeZ = edge.position.z - p0.position.z; + const RoadScalar quotient = roadSquareRoot(targetZ * targetZ + targetX * targetX) + / roadSquareRoot(RoadScalar(edgeZ) * edgeZ + RoadScalar(edgeX) * edgeX); + const float ratio = static_cast(quotient); + if (roadLess(quotient, 0.0) || roadLess(1.0, ratio)) { point = makeVec3(0.0f, 0.0f, 0.0f); segmentIntersection(p2.position, p1.position, p0.position, target.position, point, s, t); @@ -289,16 +391,17 @@ bool interpolateInTriangle(const RoadEditableVertex& a, const RoadEditableVertex // the shoelace sum over the polygon's x/z, (z_i * x_prev - z_prev * x_i) added in order // (the shipped loop is unrolled by four; the additions stay sequential), times 0.5f. -float polygonArea(const RoadPolygon& polygon, const std::vector& vertices) +// PE 0x10141560 +RoadScalar polygonArea(const RoadPolygon& polygon, const std::vector& vertices) { const unsigned int count = static_cast(polygon.size()); - float area = 0.0f; + RoadScalar area = RoadScalar(0.0f); unsigned int previous = count - 1; for (unsigned int i = 0; i < count; ++i) { const Vec3& current = vertices[polygon[i]].position; const Vec3& before = vertices[polygon[previous]].position; - area = area + (current.z * before.x - before.z * current.x); + area = area + (RoadScalar(current.z) * before.x - RoadScalar(before.z) * current.x); previous = i; } return area * 0.5f; // flt_101DD4F0 @@ -306,9 +409,10 @@ float polygonArea(const RoadPolygon& polygon, const std::vector& vertices) { - if (!(polygonArea(polygon, vertices) > 0.0f)) + if (!roadLess(0.0f, polygonArea(polygon, vertices))) return; const RoadPolygon copy(polygon); polygon.clear(); @@ -319,12 +423,14 @@ void ensureClockwise(RoadPolygon& polygon, const std::vector // (`retn 14h`) - a, b, c are vertex indices. Not an ear when the corner turns the wrong // way ((b.z - a.z)(c.x - a.x) - (c.z - a.z)(b.x - a.x) < 0) or when any other live polygon vertex // (not -1, not a, b or c) lies in the triangle. +// PE 0x1013C630 bool isEar(const RoadPolygon& polygon, int a, int b, int c, const std::vector& vertices) { const Vec3& pa = vertices[a].position; const Vec3& pb = vertices[b].position; const Vec3& pc = vertices[c].position; - if ((pb.z - pa.z) * (pc.x - pa.x) - (pc.z - pa.z) * (pb.x - pa.x) < 0.0f) + if (roadLess((RoadScalar(pb.z) - pa.z) * (RoadScalar(pc.x) - pa.x) + - (RoadScalar(pc.z) - pa.z) * (RoadScalar(pb.x) - pa.x), 0.0f)) return false; for (unsigned int i = 0; i < polygon.size(); ++i) { @@ -339,14 +445,16 @@ bool isEar(const RoadPolygon& polygon, int a, int b, int c, const std::vector& vertices, std::vector& indices) { const Vec3& pa = vertices[a].position; const Vec3& pb = vertices[b].position; const Vec3& pc = vertices[c].position; - const float r = (pb.x - pc.x) * (pa.z - pc.z) - (pb.z - pc.z) * (pa.x - pc.x); - if (r > 0.0f) + const RoadScalar r = (RoadScalar(pb.x) - pc.x) * (RoadScalar(pa.z) - pc.z) + - (RoadScalar(pb.z) - pc.z) * (RoadScalar(pa.x) - pc.x); + if (roadLess(0.0f, r)) { indices.push_back(c); indices.push_back(a); @@ -366,11 +474,15 @@ void emitTriangle(int a, int b, int c, const std::vector& ve // turn, i and the next two live entries (circularly, unsigned %); the first ear is emitted and its // middle entry removed; a pass that finds no ear emits the last triple it tried and removes its // middle anyway. One entry goes per pass until two remain. +// PE 0x1013C7C0 void earClip(RoadPolygon& polygon, const std::vector& vertices, std::vector& indices) { if (polygon.size() < 3) { - ::renddx9abi::logf("RoadEditable.cpp:501: TBM: npoly with less then 3 vertex!"); + const std::string expression(""); + const std::string file("C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\RoadEditable.cpp"); + ::renddx9abi::Debug(DebugTypeError, file, 501, expression) + << "TBM: npoly with less then 3 vertex!"; return; } if (polygon.size() == 3) @@ -429,65 +541,117 @@ void earClip(RoadPolygon& polygon, const std::vector& vertic // Returns a tolerance-adjusted polygon extremum on the even grid. // Requires a nonempty polygon. Minima round down; maxima round up. Ties and NaN replace // minima, while maxima change only on a strict increase. +#if defined(__APPLE__) +// [CHOSEN, not recovered] Native equivalent of the qword libm argument, FISTP and 32-bit wrap. +int roadGridRound(float value, float tolerance, bool maximum) +{ + const RoadScalar adjusted = maximum ? RoadScalar(value) - tolerance : RoadScalar(value) + tolerance; + const double input = bf2x87::storeDouble(adjusted); + const int n = bf2x87::toIntTruncate(RoadScalar(maximum ? std::ceil(input) : std::floor(input))); + const int odd = static_cast(n) & 1u; + return bf2x87::lowWord(static_cast(n) - odd + (maximum && odd ? 2 : 0)); +} +#endif + +int roadGridStep(int value, int step) +{ +#if defined(__APPLE__) + // [CHOSEN, not recovered] Preserve the ADD/SUB wrap on the native compiler. + return bf2x87::lowWord(static_cast(value) + step); +#else + return value + step; +#endif +} + +float roadGridOffset(int value, float offset) +{ +#if defined(__APPLE__) + // [CHOSEN, not recovered] FILD, add/subtract, then the first float store. + return bf2x87::store(RoadScalar(value) + offset); +#else + return static_cast(value) + offset; +#endif +} + +// PE 0x10141370 int extremeMinZ(RoadPolygon polygon, const std::vector& vertices, float tolerance) { float minimum = vertices[polygon[0]].position.z; for (unsigned int i = 1; i < polygon.size(); ++i) { const float z = vertices[polygon[i]].position.z; - if (!(minimum < z)) + if (!roadLess(minimum, z)) minimum = z; } +#if defined(__APPLE__) + return roadGridRound(minimum, tolerance, false); +#else const int n = static_cast(std::floor(static_cast(minimum + tolerance))); return n - std::abs(n) % 2; +#endif } // the maximum x, even upward. +// PE 0x10141410 int extremeMaxX(RoadPolygon polygon, const std::vector& vertices, float tolerance) { float maximum = vertices[polygon[0]].position.x; for (unsigned int i = 1; i < polygon.size(); ++i) { const float x = vertices[polygon[i]].position.x; - if (maximum < x) + if (roadLess(maximum, x)) maximum = x; } +#if defined(__APPLE__) + return roadGridRound(maximum, tolerance, true); +#else int n = static_cast(std::ceil(static_cast(maximum - tolerance))); const int odd = std::abs(n) % 2; if (odd) n = n - odd + 2; return n; +#endif } // the maximum z, even upward. +// PE 0x101414B0 int extremeMaxZ(RoadPolygon polygon, const std::vector& vertices, float tolerance) { float maximum = vertices[polygon[0]].position.z; for (unsigned int i = 1; i < polygon.size(); ++i) { const float z = vertices[polygon[i]].position.z; - if (maximum < z) + if (roadLess(maximum, z)) maximum = z; } +#if defined(__APPLE__) + return roadGridRound(maximum, tolerance, true); +#else int n = static_cast(std::ceil(static_cast(maximum - tolerance))); const int odd = std::abs(n) % 2; if (odd) n = n - odd + 2; return n; +#endif } // the minimum x, even downward. +// PE 0x101428D0 int extremeMinX(RoadPolygon polygon, const std::vector& vertices, float tolerance) { float minimum = vertices[polygon[0]].position.x; for (unsigned int i = 1; i < polygon.size(); ++i) { const float x = vertices[polygon[i]].position.x; - if (!(minimum < x)) + if (!roadLess(minimum, x)) minimum = x; } +#if defined(__APPLE__) + return roadGridRound(minimum, tolerance, false); +#else const int n = static_cast(std::floor(static_cast(minimum + tolerance))); return n - std::abs(n) % 2; +#endif } // The cut classifyPolygon proposes (splitAndTriangulate's 12-byte local): a line x = cut.x (axis 0) @@ -502,24 +666,25 @@ struct PolygonCut // (`retn 0Ch`) - with 1 cm of tolerance: more than one 2 m cell across in x cuts at the // first grid line inside (minX + 2, axis 0); else more than one in z (minZ + 2, axis 1); else a // single cell - false. +// PE 0x1013C9A0 bool classifyPolygon(const RoadPolygon& polygon, PolygonCut& cut, const std::vector& vertices) { const int minX = extremeMinX(polygon, vertices, 0.01f); - const int maxXLessTwo = extremeMaxX(polygon, vertices, 0.01f) - 2; + const int maxXLessTwo = roadGridStep(extremeMaxX(polygon, vertices, 0.01f), -2); const int minZ = extremeMinZ(polygon, vertices, 0.01f); const int maxZ = extremeMaxZ(polygon, vertices, 0.01f); if (minX != maxXLessTwo) { - cut.x = static_cast(minX + 2); + cut.x = static_cast(roadGridStep(minX, 2)); cut.z = 0.0f; cut.axis = 0; return true; } - if (minZ != maxZ - 2) + if (minZ != roadGridStep(maxZ, -2)) { cut.x = 0.0f; cut.axis = 1; - cut.z = static_cast(minZ + 2); + cut.z = static_cast(roadGridStep(minZ, 2)); return true; } return false; @@ -535,11 +700,87 @@ bool containsIndex(const std::vector& values, int value) return false; } +RoadScalar roadDistanceXZ(const Vec3& a, const Vec3& b) +{ + const RoadScalar x = RoadScalar(a.x) - b.x; + const RoadScalar z = RoadScalar(a.z) - b.z; + return roadSquareRoot(z * z + x * x); +} + +RoadScalar roadDistance3(const Vec3& a, const Vec3& b, unsigned int order, bool spillDifferences) +{ + RoadScalar x = RoadScalar(a.x) - b.x; + RoadScalar y = RoadScalar(a.y) - b.y; + RoadScalar z = RoadScalar(a.z) - b.z; + if (spillDifferences) + { + x = RoadScalar(static_cast(x)); + y = RoadScalar(static_cast(y)); + z = RoadScalar(static_cast(z)); + } + if (order == 2) + return roadSquareRoot((y * y + x * x) + z * z); + return roadSquareRoot(order == 1 ? (x * x + z * z) + y * y : (z * z + y * y) + x * x); +} + +float roadProjectionRatio(const Vec3& origin, const Vec3& point, const Vec3& edge) +{ + const RoadScalar numerator = roadDistanceXZ(point, origin); + const float x = edge.x - origin.x; + const float z = edge.z - origin.z; + return static_cast(numerator / roadSquareRoot(RoadScalar(z) * z + RoadScalar(x) * x)); +} + +#if defined(__APPLE__) +// [CHOSEN, not recovered] Native storage for the tessellator's register values and float spills. +struct RoadDeviation +{ + float x, y, z; + RoadScalar denominatorX, denominatorY, denominatorZ; +}; + +RoadScalar roadLength(RoadScalar x, RoadScalar y, RoadScalar z, unsigned int order) +{ + if (order == 1) + return roadSquareRoot((x * x + z * z) + y * y); + if (order == 2) + return roadSquareRoot((y * y + x * x) + z * z); + return roadSquareRoot((z * z + y * y) + x * x); +} + +RoadDeviation roadDeviation(const Vec3& anchor, const Vec3& sample, const Vec3& ahead, bool right) +{ + const RoadScalar rawDx = RoadScalar(anchor.x) - sample.x; + const RoadScalar dx = right ? rawDx : RoadScalar(static_cast(rawDx)); + const float dy = anchor.y - sample.y; + const float dz = anchor.z - sample.z; + const RoadScalar ex = RoadScalar(ahead.x) - anchor.x; + const float ey = ahead.y - anchor.y; + const RoadScalar ez = RoadScalar(ahead.z) - anchor.z; + const float storedEx = static_cast(ex); + RoadDeviation result; + result.x = static_cast(RoadScalar(ey) * dz - ez * dy); + result.y = static_cast(ez * dx - RoadScalar(dz) * storedEx); + result.z = static_cast(RoadScalar(dy) * storedEx - RoadScalar(ey) * dx); + result.denominatorX = RoadScalar(storedEx); + result.denominatorY = ey; + result.denominatorZ = right ? RoadScalar(static_cast(ez)) : ez; + return result; +} + +float roadDeviationError(const RoadDeviation& value, unsigned int order) +{ + return static_cast(roadLength(value.x, value.y, value.z, order) + / roadLength(value.denominatorX, value.denominatorY, value.denominatorZ, order)); +} +#endif + // Splits polygon across line a-b, appending intersection vertices and output pieces. // Returns false for no crossings or an odd crossing count. Requires at least three // vertices and finite coordinates; endpoint hits use a one-centimetre tolerance. +// PE 0x10143490 bool clipPolygon(const Vec3& a, const Vec3& b, std::vector& pieces, const RoadPolygon& polygon, std::vector& vertices, bool verbose) { @@ -557,7 +798,7 @@ bool clipPolygon(const Vec3& a, const Vec3& b, std::vector& pieces, std::vector crossingNew; // index into newVertices, or -1 std::vector newVertices; - double s = 0.0; + double s; int sideAfter = 0; for (unsigned int i = 0; i < polygon.size(); ++i) { @@ -572,12 +813,11 @@ bool clipPolygon(const Vec3& a, const Vec3& b, std::vector& pieces, { RoadEditableVertex crossing; crossing.interpolate(from, to, static_cast(t)); - if (lengthXZ(crossing.position.x - to.position.x, crossing.position.z - to.position.z) < 0.01) + if (roadLess(roadDistanceXZ(crossing.position, to.position), 0.01)) { t = 1.0; // the end vertex is hit - tested below } - else if (lengthXZ(crossing.position.x - from.position.x, - crossing.position.z - from.position.z) < 0.01) + else if (roadLess(roadDistanceXZ(crossing.position, from.position), 0.01)) { crossingVertex.push_back(polygon[i]); crossingNew.push_back(-1); @@ -596,21 +836,28 @@ bool clipPolygon(const Vec3& a, const Vec3& b, std::vector& pieces, } } - // |t - 1| at 24 bits (`fsubr` against the double 1.0); a NaN skips. - if (!(std::fabs(static_cast(t - 1.0)) < 0.01)) + // The qword parameter stays in the register through subtraction, FABS and comparison. +#if defined(__APPLE__) + if (!roadLess(bf2x87::abs(RoadDouble(t) - 1.0), 0.01)) +#else + if (!(std::fabs(t - 1.0) < 0.01)) +#endif continue; - const float abX = b.x - a.x; - const float abZ = b.z - a.z; - const float sideOfStart = (from.position.x - a.x) * abZ - abX * (from.position.z - a.z); + const RoadScalar wideAbX = RoadScalar(b.x) - a.x; + const RoadScalar wideAbZ = RoadScalar(b.z) - a.z; + const RoadScalar sideOfStart = (RoadScalar(from.position.x) - a.x) * wideAbZ + - wideAbX * (RoadScalar(from.position.z) - a.z); int sideBefore; - if (sideOfStart < 0.0f) + if (roadLess(sideOfStart, 0.0f)) sideBefore = -1; - else if (sideOfStart > 0.0f) + else if (roadLess(0.0f, sideOfStart)) sideBefore = 1; else continue; // the start vertex is on the line (or NaN) + const float abX = static_cast(wideAbX); + const float abZ = static_cast(wideAbZ); Vec3 after = makeVec3(0.0f, 0.0f, 0.0f); unsigned int k = (i + 2) % count; if (k != i) @@ -618,13 +865,14 @@ bool clipPolygon(const Vec3& a, const Vec3& b, std::vector& pieces, for (;;) { after = vertices[polygon[k]].position; - const float side = (after.x - a.x) * abZ - abX * (after.z - a.z); - if (side < 0.0f) + const RoadScalar side = (RoadScalar(after.x) - a.x) * abZ + - RoadScalar(abX) * (RoadScalar(after.z) - a.z); + if (roadLess(side, 0.0f)) { sideAfter = -1; break; } - if (side > 0.0f) + if (roadLess(0.0f, side)) { sideAfter = 1; break; @@ -673,7 +921,7 @@ bool clipPolygon(const Vec3& a, const Vec3& b, std::vector& pieces, double best = 1000.0; // dbl_101E01D8 for (unsigned int m = 0; m < crossingParameter.size(); ++m) { - if (crossingParameter[m] != -1.0 && crossingParameter[m] < best) + if (crossingParameter[m] != -1.0 && roadLess(crossingParameter[m], best)) { smallest = m; best = crossingParameter[m]; @@ -753,8 +1001,8 @@ bool clipPolygon(const Vec3& a, const Vec3& b, std::vector& pieces, // Assigns coordinates to vertices from start onward using the road columns and mode. // Mode 0 clears resolved flags; modes 1 and 2 retain them. Requires nonempty columns // and finite coordinates. Mode 2 intentionally reuses the centre-column distance. -// [CHOSEN] Uninitialized compatibility fallback indices and intersection values start at zero. - +// Shipped defect: failed parallel intersections leave the interpolation parameter unwritten. +// PE 0x10141690 void assignTexCoords(const std::vector& first, const std::vector& second, const std::vector& third, std::vector& vertices, unsigned int start, int mode) @@ -782,8 +1030,7 @@ void assignTexCoords(const std::vector& first, const std::ve if (side == 0) { v.interpolateTexCoords(l0, l1, - lengthXZ(v.position.x - l0.position.x, v.position.z - l0.position.z) - / lengthXZ(l1.position.x - l0.position.x, l1.position.z - l0.position.z)); + roadProjectionRatio(l0.position, v.position, l1.position)); v.needsUv = 0; break; } @@ -791,8 +1038,7 @@ void assignTexCoords(const std::vector& first, const std::ve if (side == 0) { v.interpolateTexCoords(l1, r1, - lengthXZ(v.position.x - l1.position.x, v.position.z - l1.position.z) - / lengthXZ(r1.position.x - l1.position.x, r1.position.z - l1.position.z)); + roadProjectionRatio(l1.position, v.position, r1.position)); v.needsUv = 0; break; } @@ -800,8 +1046,7 @@ void assignTexCoords(const std::vector& first, const std::ve if (side == 0) { v.interpolateTexCoords(r1, r0, - lengthXZ(v.position.x - r1.position.x, v.position.z - r1.position.z) - / lengthXZ(r0.position.x - r1.position.x, r0.position.z - r1.position.z)); + roadProjectionRatio(r1.position, v.position, r0.position)); v.needsUv = 0; break; } @@ -809,8 +1054,7 @@ void assignTexCoords(const std::vector& first, const std::ve if (side == 0) { v.interpolateTexCoords(r0, l0, - lengthXZ(v.position.x - r0.position.x, v.position.z - r0.position.z) - / lengthXZ(l0.position.x - r0.position.x, l0.position.z - r0.position.z)); + roadProjectionRatio(r0.position, v.position, l0.position)); v.needsUv = 0; break; } @@ -818,8 +1062,7 @@ void assignTexCoords(const std::vector& first, const std::ve if (side == 0) { v.interpolateTexCoords(l0, r1, - lengthXZ(v.position.x - l0.position.x, v.position.z - l0.position.z) - / lengthXZ(r1.position.x - l0.position.x, r1.position.z - l0.position.z)); + roadProjectionRatio(l0.position, v.position, r1.position)); v.needsUv = 0; break; } @@ -842,10 +1085,11 @@ void assignTexCoords(const std::vector& first, const std::ve if (mode == 1) { - unsigned int nearest = 0; // shipped: the third column's address (unset) + // Shipped defect: until a nearer sample is found, this argument slot holds the third column pointer. + unsigned int nearest = static_cast(reinterpret_cast(&third)); int side = static_cast(start); // shipped: the `start` argument slot - float s = 0.0f; // shipped: an unwritten stack word - float t = 0.0f; + float s; + float t; for (unsigned int k = start; k < vertices.size(); ++k) { RoadEditableVertex& v = vertices[k]; @@ -856,17 +1100,16 @@ void assignTexCoords(const std::vector& first, const std::ve { const Vec3& p1 = first[i].position; const Vec3& p2 = second[i].position; - const float toFirst = lengthSumXZY(p1.x - v.position.x, p1.y - v.position.y, - p1.z - v.position.z); - const float toSecond = lengthSumXZY(p2.x - v.position.x, p2.y - v.position.y, - p2.z - v.position.z); - if (toFirst < best) + const RoadScalar firstDistance = roadDistance3(p1, v.position, true, false); + const float toFirst = static_cast(firstDistance); + const float toSecond = static_cast(roadDistance3(p2, v.position, true, false)); + if (roadLess(firstDistance, best)) { nearest = i; best = toFirst; side = 1; } - if (toSecond < best) + if (roadLess(toSecond, best)) { nearest = i; best = toSecond; @@ -897,13 +1140,9 @@ void assignTexCoords(const std::vector& first, const std::ve previous = second[nearest - 1]; following = second[nearest + 1]; } - const float toPrevious = lengthSumZYX(previous.position.x - v.position.x, - previous.position.y - v.position.y, - previous.position.z - v.position.z); - const float toFollowing = lengthSumZYX(following.position.x - v.position.x, - following.position.y - v.position.y, - following.position.z - v.position.z); - neighbour = (toFollowing > toPrevious) ? nearest - 1 : nearest + 1; + const RoadScalar toPrevious = roadDistance3(previous.position, v.position, false, false); + const RoadScalar toFollowing = roadDistance3(following.position, v.position, false, true); + neighbour = roadLess(toPrevious, toFollowing) ? nearest - 1 : nearest + 1; } RoadEditableVertex closest; @@ -926,8 +1165,7 @@ void assignTexCoords(const std::vector& first, const std::ve segmentsIntersect(along.position, across.position, closest.position, v.position, &s, &t); RoadEditableVertex hit; hit.interpolate(along, across, s); - const float ratio = lengthXZ(v.position.x - closest.position.x, v.position.z - closest.position.z) - / lengthXZ(hit.position.x - closest.position.x, hit.position.z - closest.position.z); + const float ratio = roadProjectionRatio(closest.position, v.position, hit.position); v.interpolateTexCoords(closest, hit, ratio); } return; @@ -937,8 +1175,8 @@ void assignTexCoords(const std::vector& first, const std::ve { unsigned int nearest = start; // shipped: the `start` argument slot int side = mode; // shipped: the `mode` argument slot - float s = 0.0f; // shipped: an unwritten stack word - float t = 0.0f; + float s; + float t; for (unsigned int k = start; k < vertices.size(); ++k) { RoadEditableVertex& v = vertices[k]; @@ -949,27 +1187,25 @@ void assignTexCoords(const std::vector& first, const std::ve { const Vec3& p1 = first[i].position; const Vec3& p2 = second[i].position; - const float toFirst = lengthSumXZY(p1.x - v.position.x, p1.y - v.position.y, - p1.z - v.position.z); - const float toSecond = lengthSumXZY(p2.x - v.position.x, p2.y - v.position.y, - p2.z - v.position.z); - const float toThird = lengthSumXZY(p2.x - v.position.x, p2.y - v.position.y, - p2.z - v.position.z); // [shipped] the centre again - if (toFirst < best) + const RoadScalar firstDistance = roadDistance3(p1, v.position, true, false); + const float toFirst = static_cast(firstDistance); + const float toSecond = static_cast(roadDistance3(p2, v.position, true, false)); + const float toThird = static_cast(roadDistance3(p2, v.position, true, false)); // shipped defect: centre again + if (roadLess(firstDistance, best)) { nearest = i; best = toFirst; side = 1; } - if (toSecond < best) + if (roadLess(toSecond, best)) { nearest = i; best = toSecond; side = 21; - if (!(toFirst < toThird)) + if (!roadLess(toFirst, toThird)) side = 23; } - if (toThird < best) + if (roadLess(toThird, best)) { nearest = i; best = toThird; @@ -1002,13 +1238,9 @@ void assignTexCoords(const std::vector& first, const std::ve previous = column[nearest - 1]; following = column[nearest + 1]; } - const float toPrevious = lengthSumXZY(previous.position.x - v.position.x, - previous.position.y - v.position.y, - previous.position.z - v.position.z); - const float toFollowing = lengthSumXZY(following.position.x - v.position.x, - following.position.y - v.position.y, - following.position.z - v.position.z); - neighbour = (toFollowing > toPrevious) ? nearest - 1 : nearest + 1; + const RoadScalar toPrevious = roadDistance3(previous.position, v.position, true, false); + const RoadScalar toFollowing = roadDistance3(following.position, v.position, true, true); + neighbour = roadLess(toPrevious, toFollowing) ? nearest - 1 : nearest + 1; } RoadEditableVertex closest; @@ -1043,8 +1275,7 @@ void assignTexCoords(const std::vector& first, const std::ve segmentsIntersect(along.position, across.position, closest.position, v.position, &s, &t); RoadEditableVertex hit; hit.interpolate(along, across, s); - const float ratio = lengthXZ(v.position.x - closest.position.x, v.position.z - closest.position.z) - / lengthXZ(hit.position.x - closest.position.x, hit.position.z - closest.position.z); + const float ratio = roadProjectionRatio(closest.position, v.position, hit.position); v.interpolateTexCoords(closest, hit, ratio); } } @@ -1052,26 +1283,213 @@ void assignTexCoords(const std::vector& first, const std::ve // The fade ramps' clamps, each exactly as its arm compares (NaN results noted per form). // First pass: t < 1 ? (0 < t ? t : 0) : 1 - a NaN becomes 1. -float fadeRamp(float t) +float fadeRamp(RoadScalar t) { - if (!(t < 1.0f)) + if (!roadLess(t, 1.0f)) return 1.0f; - return (0.0f < t) ? t : 0.0f; + const float stored = static_cast(t); + return roadLess(0.0f, stored) ? stored : 0.0f; } // Second pass: min(min(t, 1), current) against 0 - a NaN t becomes 1, a NaN current is replaced. -float fadeRampEnd(float t, float current) +float fadeRampEnd(RoadScalar t, float current) { - if (!(t < 1.0f)) - t = 1.0f; - if (current < t) - t = current; - return (0.0f < t) ? t : 0.0f; + if (!roadLess(t, 1.0f)) + t = RoadScalar(1.0f); + if (roadLess(current, t)) + t = RoadScalar(current); + return roadLess(0.0f, t) ? static_cast(t) : 0.0f; } } // anonymous namespace +// Dead tessellator helpers: unreachable in 1.50, no code or data references (no export, no table, no +// caller beyond the pair noted below). They keep their external linkage so the unused-function warning +// stays quiet; nothing calls them. The thiscall-on-the-road bodies take the road's pending list +// (+0xD8; the only road field they read) by reference [CHOSEN, not recovered]. + +// (thiscall on `out`, `retn 0Ch` through the target) - `push ebp; mov ebp, esp; pop ebp; jmp` to the +// Vec3 lerp, the same three arguments untouched. +// PE 0x1013B750 +void roadLerpVec3Forward(Vec3& out, const Vec3& a, const Vec3& b, float t) +{ + lerpVec3(out, a, b, t); +} + +// (stdcall, `retn 0Ch`) - areaSign(a, b, c) == 0. +// PE 0x1013BC60 +bool roadAreaSignIsZero(const Vec3& a, const Vec3& b, const Vec3& c) +{ + return areaSign(a, b, c) == 0; +} + +// (thiscall, `retn 8`) - every element equal to oldIndex in every pending polygon becomes newIndex. +// Only the snapping helper below calls it. +// PE 0x1013C5D0 +void roadReplacePendingIndex(RoadPolygonList& pending, int oldIndex, int newIndex) +{ + for (RoadPolygonList::iterator node = pending.begin(); node != pending.end(); ++node) + { + RoadPolygon& polygon = *node; + for (unsigned int i = 0; !polygon.empty() && i < polygon.size(); ++i) + { + if (polygon[i] == oldIndex) + polygon[i] = newIndex; + } + } +} + +// (`retn 20h`) - the edge polygon[k] -> polygon[(k + 1) % n] against the segment a-b. Writes +// index = -1 and the first ratio `s` (double) before it decides anything. A second ratio within +// 1e-4 of 1 means the lines meet at the far end: answers whether the other end points of the edge lie +// on opposite sides of a-b (nothing is appended). Otherwise, when the second ratio lies in +// [0.0001, 1), appends the point lerp(edge start, edge end, ratio) as a fresh vertex to `out`, +// writes its index to `index` and answers true. polygon.size() == 0 divides by zero (shipped). +// PE 0x1013CA80 +bool roadEdgeCrossing(const Vec3& a, const Vec3& b, const RoadPolygon& polygon, int k, + const std::vector& vertices, double& s, int& index, + std::vector& out) +{ + const unsigned int count = static_cast(polygon.size()); + const unsigned int next = static_cast(k + 1) % count; + const float ax = a.x; + const float az = a.z; + const float bx = b.x; + const RoadScalar dzAB = RoadScalar(b.z) - az; + const float dzABStored = static_cast(dzAB); + const Vec3& c = vertices[polygon[k]].position; + const Vec3& d = vertices[polygon[next]].position; + const float cx = c.x; + const float cz = c.z; + const float dx = d.x; + const float dz = d.z; + + index = -1; + const RoadScalar t1Register = (RoadScalar(dz) - cz) * ax; + const double t1 = static_cast(t1Register); + const RoadScalar t2 = (RoadScalar(cz) - dz) * bx; + const RoadScalar t3 = t2 + (RoadScalar(az) - b.z) * cx; + const RoadScalar t4 = t3 + RoadScalar(dx) * dzAB; + const RoadScalar denominator = t1Register + t4; + const float u = static_cast(RoadScalar(cz) - az); + const RoadScalar inverse = RoadScalar(1.0) / denominator; + const RoadScalar sValue = (((RoadScalar(az) - dz) * cx + RoadScalar(u) * dx) + t1) * inverse; + s = static_cast(sValue); + const RoadScalar x1 = RoadScalar(cz) - b.z; + const RoadScalar y1 = x1 * ax + (RoadScalar(az) - cz) * bx; + const RoadScalar y2 = y1 + RoadScalar(cx) * dzAB; + const RoadScalar ratio = (-y2) * inverse; + + if (roadLess(0.9999, ratio) && roadLess(ratio, 1.0001)) + { + const float q = static_cast(RoadScalar(bx) - ax); + const float r = static_cast(RoadScalar(dzABStored) * (RoadScalar(cx) - ax) + - RoadScalar(u) * q); + if (roadLess(RoadScalar(std::fabs(r)), 0.0001)) + return false; + // The shipped source compares two constants here (a dword 0 and |qword 0| < 1e-4), so the + // scan below always runs. + RoadScalar side = 0.0f; + const double zeroConstant = 0.0; + if (roadLess(RoadScalar(std::fabs(zeroConstant)), 0.0001)) + { + unsigned int j = static_cast(k) + 2; + do + { + const unsigned int size = static_cast(polygon.size()); + const Vec3& e = vertices[polygon[j % size]].position; + ++j; + side = (RoadScalar(e.x) - ax) * dzABStored - (RoadScalar(e.z) - az) * q; + } while (roadLess(RoadScalar(std::fabs(static_cast(side))), 0.0001)); + } + if (roadLess(0.0f, r) && roadLess(0.0f, side)) + return false; + if (roadLess(r, 0.0f) && roadLess(side, 0.0f)) + return false; + return true; + } + + if (roadLess(ratio, 0.0001) || roadLessEqual(1.0, ratio)) + return false; + + RoadEditableVertex crossing; + lerpVec3(crossing.position, c, d, static_cast(ratio)); + crossing.uv0.x = 0.0f; // the inline vertex constructor's stores after the call + crossing.uv0.y = 0.0f; + crossing.uv1.x = 0.0f; + crossing.uv1.y = 0.0f; + index = static_cast(out.size()); + out.push_back(crossing); + return true; +} + +// (thiscall, `retn 8`) - snaps the point to millimetres in x and z (y is kept), drops every vertex +// within 1 mm of it (their indices become -1 in the pending polygons, the survivors are renumbered +// into a compacted copy), appends the point itself under index -1's replacement, then removes +// consecutive duplicate indices from each pending polygon. The compacted vertex vector is a local +// that is destroyed at the end (`vertices` is never written; shipped). +// Shipped defect, restored as a bounds check [CHOSEN, not recovered; memory-safety exception]: the +// duplicate-removal pass compares the next index with element (m - 1) of the half-built copy, which +// lies past its end once an index has been skipped; here such an out-of-range comparison counts as +// "different". +// PE 0x1013CDE0 +void roadSnapPoint(RoadPolygonList& pending, RoadEditableVertex& point, + const std::vector& vertices) +{ + const float y = point.position.y; + point.position.x = static_cast(RoadScalar(point.position.x) * 1000.0f); + point.position.y = static_cast(RoadScalar(point.position.y) * 1000.0f); + point.position.z = static_cast(RoadScalar(point.position.z) * 1000.0f); + point.position.x = static_cast(RoadScalar(static_cast(point.position.x)) * 0.001f); + point.position.z = static_cast(RoadScalar(static_cast(point.position.z)) * 0.001f); + point.position.y = y; + + std::vector snapped; + for (unsigned int i = 0; !vertices.empty() && i < vertices.size(); ++i) + { + const RoadEditableVertex& v = vertices[i]; + const RoadScalar deltaX = RoadScalar(v.position.x) - point.position.x; + const RoadScalar deltaZ = RoadScalar(v.position.z) - point.position.z; + const RoadScalar distance = roadSquareRoot(deltaX * deltaX + deltaZ * deltaZ); + if (roadLess(0.001, distance)) + { + const int newIndex = static_cast(snapped.size()); + snapped.push_back(v); + if (newIndex != static_cast(i)) + roadReplacePendingIndex(pending, static_cast(i), newIndex); + } + else + { + roadReplacePendingIndex(pending, static_cast(i), -1); + } + } + const int pointIndex = static_cast(snapped.size()); + snapped.push_back(point); + roadReplacePendingIndex(pending, -1, pointIndex); + + for (RoadPolygonList::iterator node = pending.begin(); node != pending.end(); ++node) + { + RoadPolygon& polygon = *node; + for (unsigned int j = 1; !polygon.empty() && j < polygon.size(); ++j) + { + if (polygon[j - 1] != polygon[j]) + continue; + RoadPolygon compact; + compact.push_back(polygon[0]); + for (unsigned int m = 1; !polygon.empty() && m < polygon.size(); ++m) + { + const bool same = (m - 1 < compact.size()) && compact[m - 1] == polygon[m]; + if (!same) + compact.push_back(polygon[m]); + } + polygon = compact; + break; + } + } +} + + // (`retn 8`) - drain the pending list: a polygon of three or more vertices that spans more // than one 2 m cell is cut at the first grid line inside (classifyPolygon; the cut line runs 1 m past // the polygon's even-rounded extent) and its pieces go back on the pending list; a single cell is cut @@ -1080,12 +1498,13 @@ float fadeRampEnd(float t, float current) // whole. Then every ready polygon of three or more vertices is ear-clipped into `indices`. Polygons // with fewer vertices are dropped from both lists unprocessed. +// PE 0x1013D560 void RoadEditable::splitAndTriangulate(std::vector& vertices, std::vector& indices) { PolygonCut cut; cut.x = 0.0f; cut.z = 0.0f; // the axis word is not initialised (shipped) - while (m_pendingPolygons.size != 0) + while (!m_pendingPolygons.empty()) { RoadPolygon& polygon = m_pendingPolygons.front(); if (polygon.size() >= 3) @@ -1097,16 +1516,16 @@ void RoadEditable::splitAndTriangulate(std::vector& vertices if (cut.axis == 0) { const int maxZ = extremeMaxZ(polygon, vertices, 0.0f); - lineStart = makeVec3(cut.x, 0.0f, static_cast(maxZ) + 1.0f); + lineStart = makeVec3(cut.x, 0.0f, roadGridOffset(maxZ, 1.0f)); const int minZ = extremeMinZ(polygon, vertices, 0.0f); - lineEnd = makeVec3(cut.x, 0.0f, static_cast(minZ) - 1.0f); + lineEnd = makeVec3(cut.x, 0.0f, roadGridOffset(minZ, -1.0f)); } else { const int maxX = extremeMaxX(polygon, vertices, 0.0f); - lineStart = makeVec3(static_cast(maxX) + 1.0f, 0.0f, cut.z); + lineStart = makeVec3(roadGridOffset(maxX, 1.0f), 0.0f, cut.z); const int minX = extremeMinX(polygon, vertices, 0.0f); - lineEnd = makeVec3(static_cast(minX) - 1.0f, 0.0f, cut.z); + lineEnd = makeVec3(roadGridOffset(minX, -1.0f), 0.0f, cut.z); } std::vector pieces; if (clipPolygon(lineStart, lineEnd, pieces, polygon, vertices, false)) @@ -1123,12 +1542,12 @@ void RoadEditable::splitAndTriangulate(std::vector& vertices { const int maxZ = extremeMaxZ(polygon, vertices, 0.01f); const int minX = extremeMinX(polygon, vertices, 0.01f); - const Vec3 lineStart = makeVec3(static_cast(minX) - 1.0f, 0.0f, - static_cast(maxZ) + 1.0f); + const Vec3 lineStart = makeVec3(roadGridOffset(minX, -1.0f), 0.0f, + roadGridOffset(maxZ, 1.0f)); const int minZ = extremeMinZ(polygon, vertices, 0.01f); const int maxX = extremeMaxX(polygon, vertices, 0.01f); - const Vec3 lineEnd = makeVec3(static_cast(maxX) + 1.0f, 0.0f, - static_cast(minZ) - 1.0f); + const Vec3 lineEnd = makeVec3(roadGridOffset(maxX, 1.0f), 0.0f, + roadGridOffset(minZ, -1.0f)); std::vector pieces; if (clipPolygon(lineStart, lineEnd, pieces, polygon, vertices, false)) { @@ -1144,7 +1563,7 @@ void RoadEditable::splitAndTriangulate(std::vector& vertices m_pendingPolygons.pop_front(); } - while (m_readyPolygons.size != 0) + while (!m_readyPolygons.empty()) { RoadPolygon& polygon = m_readyPolygons.front(); if (polygon.size() >= 3) @@ -1158,6 +1577,7 @@ void RoadEditable::splitAndTriangulate(std::vector& vertices // the template supplies the error limit. Ghost mode emits a strip or mirrored-column mesh. // Requires sampled edges to be nonempty; the final error test retains an unchecked end read. // Noise changes only x. Final geometry is split on the terrain grid and projected to its heightmap. +// PE 0x1013DAC0 int RoadEditable::tessellate(std::vector& vertices, std::vector& indices, float width, float /*maxError - not read*/, bool ghost) { @@ -1196,10 +1616,10 @@ int RoadEditable::tessellate(std::vector& vertices, std::vec const Vec2& offset1 = m_textureScaleOffsets[1]; const Vec2& scale1 = m_template->getTextureScale(1); const float scaleU1 = scale1.x + offset1.x; - const float scaleV1 = offset1.y + scale1.y; - const float inverseWidth = 1.0f / width; - const float alongScale0 = scaleU0 * inverseWidth / scaleV0; - const float alongScale1 = inverseWidth * scaleU1 / scaleV1; + const RoadScalar scaleV1 = RoadScalar(offset1.y) + scale1.y; + const RoadScalar inverseWidth = RoadScalar(1.0f) / width; + const float alongScale0 = static_cast(RoadScalar(scaleU0) * inverseWidth / scaleV0); + const float alongScale1 = static_cast(inverseWidth * scaleU1 / scaleV1); const bool mirror0 = m_template->getMirror(0); // +0x24 const bool mirror1 = m_template->getMirror(1); @@ -1235,6 +1655,13 @@ int RoadEditable::tessellate(std::vector& vertices, std::vec bool keep = false; for (unsigned int j = nextRow; j <= i; ++j) { +#if defined(__APPLE__) + const RoadDeviation leftDeviation = roadDeviation(firstAnchor.position, left[j].position, + left[i + 1].position, false); + const RoadDeviation rightDeviation = roadDeviation(secondAnchor.position, right[j].position, + right[i + 1].position, true); + const float leftError = roadDeviationError(leftDeviation, 0); +#else const Vec3& a = firstAnchor.position; const float d1x = a.x - left[j].position.x; const float d1y = a.y - left[j].position.y; @@ -1260,13 +1687,18 @@ int RoadEditable::tessellate(std::vector& vertices, std::vec const float c2z = d2y * fx - fy * d2x; const float leftError = lengthSumZYX(c1x, c1y, c1z) / lengthSumZYX(ex, ey, ez); - if (m_template->getMaxTesselatedError(0) < leftError) // +0x34 +#endif + if (roadLess(m_template->getMaxTesselatedError(0), leftError)) // +0x34 { keep = true; break; } +#if defined(__APPLE__) + const float rightError = roadDeviationError(rightDeviation, 0); +#else const float rightError = lengthSumZYX(c2x, c2y, c2z) / lengthSumZYX(fx, fy, fz); - if (m_template->getMaxTesselatedError(0) < rightError || i == leftSamples.size() - 1) +#endif + if (roadLess(m_template->getMaxTesselatedError(0), rightError) || i == leftSamples.size() - 1) { keep = true; break; @@ -1279,22 +1711,19 @@ int RoadEditable::tessellate(std::vector& vertices, std::vec RoadEditableVertex rightVertex = rightSamples[i]; if (m_noise) { - const float noiseX = static_cast(i) * 0.1f; // flt_101DD25C + const float noiseX = static_cast(RoadScalar(i) * 0.1f); // flt_101DD25C leftVertex.position.x = m_noise->sample(noiseX, 0.0f, 0.0f, 0.0f) + leftVertex.position.x; rightVertex.position.x = m_noise->sample(noiseX + 1000.0f, 0.0f, 0.0f, 0.0f) + rightVertex.position.x; } - const float dx = rightVertex.position.x - secondAnchor.position.x; - const float dy = rightVertex.position.y - secondAnchor.position.y; - const float dz = rightVertex.position.z - secondAnchor.position.z; rightVertex.uv0.x = inverseScaleU0; rightVertex.uv1.x = inverseScaleU1; leftVertex.uv0.x = 0.0f; leftVertex.uv1.x = 0.0f; - const float rowLength = lengthSumZYX(dx, dy, dz); - const float v0 = alongScale0 * rowLength + secondAnchor.uv0.y; + const RoadScalar rowLength = roadDistance3(rightVertex.position, secondAnchor.position, 0, false); + const float v0 = static_cast(RoadScalar(alongScale0) * rowLength + secondAnchor.uv0.y); rightVertex.uv0.y = v0; - const float v1 = alongScale1 * rowLength + secondAnchor.uv1.y; + const float v1 = static_cast(RoadScalar(alongScale1) * rowLength + secondAnchor.uv1.y); rightVertex.uv1.y = v1; leftVertex.uv1.y = v1; leftVertex.uv0.y = v0; @@ -1311,48 +1740,48 @@ int RoadEditable::tessellate(std::vector& vertices, std::vec if (m_fadeDistAtStartRight.y != 0.0f) secondColumn[0].alpha = 0.0f; - float firstDistance = 0.0f; - float secondDistance = 0.0f; + RoadScalar firstDistance = RoadScalar(0.0f); + RoadScalar secondDistance = RoadScalar(0.0f); for (unsigned int k = 1; k < firstColumn.size(); ++k) { const Vec3& p = firstColumn[k].position; const Vec3& q = firstColumn[k - 1].position; - firstDistance = firstDistance + lengthSumZYX(p.x - q.x, p.y - q.y, p.z - q.z); + firstDistance = firstDistance + roadDistance3(p, q, 0, false); const Vec3& r = secondColumn[k].position; const Vec3& u = secondColumn[k - 1].position; - secondDistance = secondDistance + lengthSumZYX(r.x - u.x, r.y - u.y, r.z - u.z); - if (0.0f != m_fadeDistAtStartLeft.y - m_fadeDistAtStartLeft.x) + secondDistance = secondDistance + roadDistance3(r, u, 0, false); + if (0.0f != RoadScalar(m_fadeDistAtStartLeft.y) - m_fadeDistAtStartLeft.x) { firstColumn[k].alpha = fadeRamp((firstDistance - m_fadeDistAtStartLeft.x) - / (m_fadeDistAtStartLeft.y - m_fadeDistAtStartLeft.x)); + / (RoadScalar(m_fadeDistAtStartLeft.y) - m_fadeDistAtStartLeft.x)); } - if (0.0f != m_fadeDistAtStartRight.y - m_fadeDistAtStartRight.x) + if (0.0f != RoadScalar(m_fadeDistAtStartRight.y) - m_fadeDistAtStartRight.x) { secondColumn[k].alpha = fadeRamp((secondDistance - m_fadeDistAtStartRight.x) - / (m_fadeDistAtStartRight.y - m_fadeDistAtStartRight.x)); + / (RoadScalar(m_fadeDistAtStartRight.y) - m_fadeDistAtStartRight.x)); } } - const float firstTotal = firstDistance; - const float secondTotal = secondDistance; - float firstRun = 0.0f; - float secondRun = 0.0f; + const RoadScalar firstTotal = firstDistance; + const float secondTotal = static_cast(secondDistance); + RoadScalar firstRun = RoadScalar(0.0f); + RoadScalar secondRun = RoadScalar(0.0f); for (unsigned int k = 1; k < firstColumn.size(); ++k) { const Vec3& p = firstColumn[k].position; const Vec3& q = firstColumn[k - 1].position; - firstRun = firstRun + lengthSumXZY(p.x - q.x, p.y - q.y, p.z - q.z); + firstRun = firstRun + roadDistance3(p, q, 1, false); const Vec3& r = secondColumn[k].position; const Vec3& u = secondColumn[k - 1].position; - secondRun = secondRun + lengthSumXZY(r.x - u.x, r.y - u.y, r.z - u.z); - if (0.0f != m_fadeDistAtEndLeft.y - m_fadeDistAtEndLeft.x) + secondRun = secondRun + roadDistance3(r, u, 1, false); + if (0.0f != RoadScalar(m_fadeDistAtEndLeft.y) - m_fadeDistAtEndLeft.x) { firstColumn[k].alpha = fadeRampEnd(((firstTotal - firstRun) - m_fadeDistAtEndLeft.x) - / (m_fadeDistAtEndLeft.y - m_fadeDistAtEndLeft.x), firstColumn[k].alpha); + / (RoadScalar(m_fadeDistAtEndLeft.y) - m_fadeDistAtEndLeft.x), firstColumn[k].alpha); } - if (0.0f != m_fadeDistAtEndRight.y - m_fadeDistAtEndRight.x) + if (0.0f != RoadScalar(m_fadeDistAtEndRight.y) - m_fadeDistAtEndRight.x) { secondColumn[k].alpha = fadeRampEnd(((secondTotal - secondRun) - m_fadeDistAtEndRight.x) - / (m_fadeDistAtEndRight.y - m_fadeDistAtEndRight.x), secondColumn[k].alpha); + / (RoadScalar(m_fadeDistAtEndRight.y) - m_fadeDistAtEndRight.x), secondColumn[k].alpha); } } @@ -1388,7 +1817,7 @@ int RoadEditable::tessellate(std::vector& vertices, std::vec firstAnchor = leftSamples[0]; thirdAnchor = rightSamples[0]; secondAnchor = firstAnchor; - secondAnchor.position = makeVec3((thirdAnchor.position.x + firstAnchor.position.x) * 0.5f, + secondAnchor.position = makeVec3(static_cast((RoadScalar(thirdAnchor.position.x) + firstAnchor.position.x) * 0.5f), (thirdAnchor.position.y + firstAnchor.position.y) * 0.5f, (thirdAnchor.position.z + firstAnchor.position.z) * 0.5f); firstAnchor.uv1.x = 0.0f; @@ -1397,7 +1826,8 @@ int RoadEditable::tessellate(std::vector& vertices, std::vec firstAnchor.uv0.y = 0.0f; thirdAnchor.uv0.y = 0.0f; secondAnchor.uv0.y = 0.0f; - const float inverseScaleU0 = 1.0f / scaleU0; + const RoadScalar rawInverseScaleU0 = RoadScalar(1.0f) / scaleU0; + const float inverseScaleU0 = static_cast(rawInverseScaleU0); if (mirror0) { secondAnchor.uv0.x = inverseScaleU0; @@ -1405,10 +1835,11 @@ int RoadEditable::tessellate(std::vector& vertices, std::vec } else { - secondAnchor.uv0.x = 0.5f * inverseScaleU0; + secondAnchor.uv0.x = static_cast(RoadScalar(0.5f) * rawInverseScaleU0); thirdAnchor.uv0.x = inverseScaleU0; } - const float inverseScaleU1 = 1.0f / scaleU1; + const RoadScalar rawInverseScaleU1 = RoadScalar(1.0f) / scaleU1; + const float inverseScaleU1 = static_cast(rawInverseScaleU1); thirdAnchor.uv1.y = 0.0f; secondAnchor.uv1.y = 0.0f; if (mirror1) @@ -1418,7 +1849,7 @@ int RoadEditable::tessellate(std::vector& vertices, std::vec } else { - secondAnchor.uv1.x = 0.5f * inverseScaleU1; + secondAnchor.uv1.x = static_cast(RoadScalar(0.5f) * rawInverseScaleU1); thirdAnchor.uv1.x = inverseScaleU1; } firstColumn.push_back(firstAnchor); @@ -1434,6 +1865,13 @@ int RoadEditable::tessellate(std::vector& vertices, std::vec bool keep = false; for (unsigned int j = nextRow; j <= i; ++j) { +#if defined(__APPLE__) + const RoadDeviation leftDeviation = roadDeviation(firstAnchor.position, left[j].position, + left[i + 1].position, false); + const RoadDeviation rightDeviation = roadDeviation(thirdAnchor.position, right[j].position, + right[i + 1].position, true); + const float leftError = roadDeviationError(leftDeviation, 0); +#else const Vec3& a = firstAnchor.position; const float d1x = a.x - left[j].position.x; const float d1y = a.y - left[j].position.y; @@ -1459,13 +1897,18 @@ int RoadEditable::tessellate(std::vector& vertices, std::vec const float c2z = d2y * fx - fy * d2x; const float leftError = lengthSumZYX(c1x, c1y, c1z) / lengthSumZYX(ex, ey, ez); - if (m_template->getMaxTesselatedError(0) < leftError) +#endif + if (roadLess(m_template->getMaxTesselatedError(0), leftError)) { keep = true; break; } +#if defined(__APPLE__) + const float rightError = roadDeviationError(rightDeviation, 1); +#else const float rightError = lengthSumXZY(c2x, c2y, c2z) / lengthSumXZY(fx, fy, fz); - if (m_template->getMaxTesselatedError(0) < rightError || i == sampleCount - 1) +#endif + if (roadLess(m_template->getMaxTesselatedError(0), rightError) || i == sampleCount - 1) { keep = true; break; @@ -1478,23 +1921,19 @@ int RoadEditable::tessellate(std::vector& vertices, std::vec RoadEditableVertex rightVertex = rightSamples[i]; if (m_noise) { - const float noiseX = static_cast(i) * 0.1f; + const float noiseX = static_cast(RoadScalar(i) * 0.1f); leftVertex.position.x = m_noise->sample(noiseX, 0.0f, 0.0f, 0.0f) + leftVertex.position.x; rightVertex.position.x = m_noise->sample(noiseX + 1000.0f, 0.0f, 0.0f, 0.0f) + rightVertex.position.x; } RoadEditableVertex centreVertex = leftVertex; - centreVertex.position = makeVec3((rightVertex.position.x + leftVertex.position.x) * 0.5f, + centreVertex.position = makeVec3(static_cast((RoadScalar(rightVertex.position.x) + leftVertex.position.x) * 0.5f), (rightVertex.position.y + leftVertex.position.y) * 0.5f, (rightVertex.position.z + leftVertex.position.z) * 0.5f); - const float rightLength = lengthSumZYX(rightVertex.position.x - thirdAnchor.position.x, - rightVertex.position.y - thirdAnchor.position.y, - rightVertex.position.z - thirdAnchor.position.z); - const float leftLength = lengthSumZYX(leftVertex.position.x - firstAnchor.position.x, - leftVertex.position.y - firstAnchor.position.y, - leftVertex.position.z - firstAnchor.position.z); + const float rightLength = static_cast(roadDistance3(rightVertex.position, thirdAnchor.position, 0, false)); + const RoadScalar leftLength = roadDistance3(leftVertex.position, firstAnchor.position, 0, false); leftVertex.uv0.x = 0.0f; - const float rowLength = (leftLength + rightLength) * 0.5f; + const RoadScalar rowLength = (leftLength + rightLength) * 0.5f; if (mirror0) { centreVertex.uv0.x = inverseScaleU0; @@ -1505,7 +1944,7 @@ int RoadEditable::tessellate(std::vector& vertices, std::vec rightVertex.uv0.x = inverseScaleU0; centreVertex.uv0.x = inverseScaleU0 * 0.5f; } - const float v0 = alongScale0 * rowLength + secondAnchor.uv0.y; + const float v0 = static_cast(RoadScalar(alongScale0) * rowLength + secondAnchor.uv0.y); centreVertex.uv0.y = v0; leftVertex.uv1.x = 0.0f; if (mirror1) @@ -1518,7 +1957,7 @@ int RoadEditable::tessellate(std::vector& vertices, std::vec rightVertex.uv1.x = inverseScaleU1; centreVertex.uv1.x = inverseScaleU1 * 0.5f; } - const float v1 = rowLength * alongScale1 + secondAnchor.uv1.y; + const float v1 = static_cast(rowLength * alongScale1 + secondAnchor.uv1.y); rightVertex.uv0.y = v0; leftVertex.uv0.y = v0; centreVertex.uv1.y = v1; @@ -1541,50 +1980,50 @@ int RoadEditable::tessellate(std::vector& vertices, std::vec if (m_fadeDistAtStartRight.y != 0.0f) thirdColumn[0].alpha = 0.0f; - float firstDistance = 0.0f; - float centreDistance = 0.0f; + RoadScalar firstDistance = RoadScalar(0.0f); + RoadScalar centreDistance = RoadScalar(0.0f); for (unsigned int k = 1; k < firstColumn.size(); ++k) { const Vec3& p = firstColumn[k].position; const Vec3& q = firstColumn[k - 1].position; - firstDistance = firstDistance + lengthSumZYX(p.x - q.x, p.y - q.y, p.z - q.z); + firstDistance = firstDistance + roadDistance3(p, q, 0, false); const Vec3& r = secondColumn[k].position; const Vec3& u = secondColumn[k - 1].position; - centreDistance = centreDistance + lengthSumZYX(r.x - u.x, r.y - u.y, r.z - u.z); - if (0.0f != m_fadeDistAtStartLeft.y - m_fadeDistAtStartLeft.x) + centreDistance = centreDistance + roadDistance3(r, u, 0, false); + if (0.0f != RoadScalar(m_fadeDistAtStartLeft.y) - m_fadeDistAtStartLeft.x) { firstColumn[k].alpha = fadeRamp((firstDistance - m_fadeDistAtStartLeft.x) - / (m_fadeDistAtStartLeft.y - m_fadeDistAtStartLeft.x)); + / (RoadScalar(m_fadeDistAtStartLeft.y) - m_fadeDistAtStartLeft.x)); } - if (0.0f != m_fadeDistAtStartRight.y - m_fadeDistAtStartRight.x) + if (0.0f != RoadScalar(m_fadeDistAtStartRight.y) - m_fadeDistAtStartRight.x) { thirdColumn[k].alpha = fadeRamp((centreDistance - m_fadeDistAtStartRight.x) - / (m_fadeDistAtStartRight.y - m_fadeDistAtStartRight.x)); // [shipped] the centre's run + / (RoadScalar(m_fadeDistAtStartRight.y) - m_fadeDistAtStartRight.x)); // [shipped] the centre's run } } - const float firstTotal = firstDistance; - const float centreTotal = centreDistance; - float firstRun = 0.0f; - float centreRun = 0.0f; + const RoadScalar firstTotal = firstDistance; + const float centreTotal = static_cast(centreDistance); + RoadScalar firstRun = RoadScalar(0.0f); + RoadScalar centreRun = RoadScalar(0.0f); for (unsigned int k = 1; k < firstColumn.size(); ++k) { const Vec3& p = firstColumn[k].position; const Vec3& q = firstColumn[k - 1].position; - firstRun = firstRun + lengthSumZYX(p.x - q.x, p.y - q.y, p.z - q.z); + firstRun = firstRun + roadDistance3(p, q, 0, false); const Vec3& r = secondColumn[k].position; const Vec3& u = secondColumn[k - 1].position; - centreRun = centreRun + lengthSumYXZ(r.x - u.x, r.y - u.y, r.z - u.z); - if (0.0f != m_fadeDistAtEndLeft.y - m_fadeDistAtEndLeft.x) + centreRun = centreRun + roadDistance3(r, u, 2, false); + if (0.0f != RoadScalar(m_fadeDistAtEndLeft.y) - m_fadeDistAtEndLeft.x) { firstColumn[k].alpha = fadeRampEnd(((firstTotal - firstRun) - m_fadeDistAtEndLeft.x) - / (m_fadeDistAtEndLeft.y - m_fadeDistAtEndLeft.x), firstColumn[k].alpha); + / (RoadScalar(m_fadeDistAtEndLeft.y) - m_fadeDistAtEndLeft.x), firstColumn[k].alpha); } - if (0.0f != m_fadeDistAtEndRight.y - m_fadeDistAtEndRight.x) + if (0.0f != RoadScalar(m_fadeDistAtEndRight.y) - m_fadeDistAtEndRight.x) { thirdColumn[k].alpha = fadeRampEnd(((centreTotal - centreRun) - m_fadeDistAtEndRight.x) - / (m_fadeDistAtEndRight.y - m_fadeDistAtEndRight.x), thirdColumn[k].alpha); + / (RoadScalar(m_fadeDistAtEndRight.y) - m_fadeDistAtEndRight.x), thirdColumn[k].alpha); } - secondColumn[k].alpha = (firstColumn[k].alpha + thirdColumn[k].alpha) * 0.5f; + secondColumn[k].alpha = static_cast((RoadScalar(firstColumn[k].alpha) + thirdColumn[k].alpha) * 0.5f); } if (ghost) diff --git a/Code/BF2/Geom/RoadTemplate.cpp b/Code/BF2/Geom/RoadTemplate.cpp index 6d24772c4..9b595be6a 100644 --- a/Code/BF2/Geom/RoadTemplate.cpp +++ b/Code/BF2/Geom/RoadTemplate.cpp @@ -11,7 +11,8 @@ #include "../../RendDX9Abi/ModuleCommon.h" #include "../../RendDX9Abi/PluginAbi.h" #include "../../RendDX9Abi/PluginEntry.h" // dice::hfe::fileManager -#include "../../RendDX9Abi/Vc71String.h" +#include +#include #include @@ -38,18 +39,17 @@ const unsigned int kIID_IRoadTemplate = 820008u; // (200, 300), width 1.0f, the +0x5C / +0x60 / +0x64 zeros, the name, priority 0. Then the default // contents: two empty texture files (each through a temporary std::string("")), two (1, 1) scales, // two false mirror flags, and one 0.25f max tesselated error (the inline push_back). +// PE 0x1013A700 RoadTemplate::RoadTemplate() : m_refCount(1) , m_blendFactor(1.0f) + , m_fadeOffDistance{200.0f, 300.0f} , m_width(1.0f) , m_unknown5C(0) , m_unknown60(0.0f) , m_material(0) , m_priority(0) { - m_fadeOffDistance.x = 200.0f; - m_fadeOffDistance.y = 300.0f; - m_textureFiles.push_back(::renddx9abi::HostString("")); m_textureFiles.push_back(::renddx9abi::HostString("")); @@ -67,8 +67,9 @@ RoadTemplate::RoadTemplate() m_maxTesselatedErrors.push_back(0.25f); // inline; _Insert_n 0x1004E420 } -// the members in reverse: the name, the error vector, the mirror flags (size zeroed, then -// the words), the scales, the texture files (sub_100111E0). The C++ member order is the shipped one. +// the members in reverse: the name, the error vector, the mirror flags, the scales, the texture +// files (sub_100111E0). The C++ member order is the shipped one. +// PE 0x1013A690 RoadTemplate::~RoadTemplate() { } @@ -112,19 +113,19 @@ void* RoadTemplate::queryInterface(unsigned int iid) const // The accessors. None checks its index (shipped). -// std::string::operator= on the element (index * 28 bytes from _Myfirst). +// PE 0x1013A1A0: std::string::operator= on the element. void RoadTemplate::setTextureFile(int index, const ::renddx9abi::HostString& file) { m_textureFiles[static_cast(index)] = file; } -// the element's address. +// PE 0x1013A1D0: the element's address. const ::renddx9abi::HostString& RoadTemplate::getTextureFile(int index) { return m_textureFiles[static_cast(index)]; } -// y through the FPU, x as a dword: a Vec2 copy into the element. +// PE 0x1013A1F0: y through the FPU, x as a dword: a Vec2 copy into the element. void RoadTemplate::setTextureScale(int index, const Vec2& scale) { Vec2& element = m_textureScales[static_cast(index)]; @@ -132,42 +133,45 @@ void RoadTemplate::setTextureScale(int index, const Vec2& scale) element.x = scale.x; } -// the element's address. +// PE 0x1013A210: the element's address. const Vec2& RoadTemplate::getTextureScale(int index) { return m_textureScales[static_cast(index)]; } -// the inline bit or / and-not on the word `index >> 5` (unsigned `shr`). +// PE 0x1013A650: the inline bit or / and-not on the word `index >> 5` (unsigned `shr`). void RoadTemplate::setMirror(unsigned int index, bool mirror) { - m_mirrors.set(index, mirror); + m_mirrors[index] = mirror; } -// the inline bit test, answered as 0 / 1 (`neg / sbb / neg`). +// PE 0x1013A620: the inline bit test, answered as 0 / 1 (`neg / sbb / neg`). bool RoadTemplate::getMirror(unsigned int index) { - return m_mirrors.test(index); + return m_mirrors[index]; } +// PE 0x1013A0F0 void RoadTemplate::setWidth(float width) { m_width = width; } float RoadTemplate::getWidth() { return m_width; } -// element `lod` of the float vector (+0x3C), unchecked. +// PE 0x1013A220: element `lod` of the float vector (+0x3C), unchecked. void RoadTemplate::setMaxTesselatedError(int lod, float error) { m_maxTesselatedErrors[static_cast(lod)] = error; } +// PE 0x1013A240 float RoadTemplate::getMaxTesselatedError(int lod) { return m_maxTesselatedErrors[static_cast(lod)]; } +// PE 0x1013A110 void RoadTemplate::setBlendFactor(float factor) { m_blendFactor = factor; } float RoadTemplate::getBlendFactor() { return m_blendFactor; } -// y through the FPU, x as a dword. +// PE 0x1013A180: y through the FPU, x as a dword. void RoadTemplate::setFadeOffDistance(const Vec2& distance) { m_fadeOffDistance.y = distance.y; @@ -176,8 +180,10 @@ void RoadTemplate::setFadeOffDistance(const Vec2& distance) const Vec2& RoadTemplate::getFadeOffDistance() { return m_fadeOffDistance; } +// PE 0x10178BC0 (ICF with the ParticleSystemTemplate +0x84 dword setter: one dword store at +0x84) void RoadTemplate::setPriority(int priority) { m_priority = priority; } int RoadTemplate::getPriority() { return m_priority; } +// PE 0x10178B40 (ICF with the ParticleSystemTemplate +0x64 dword setter: one dword store at +0x64) void RoadTemplate::setMaterial(int material) { m_material = material; } int RoadTemplate::getMaterial() { return m_material; } @@ -187,21 +193,23 @@ void RoadTemplate::setName(const ::renddx9abi::HostString& name) m_name = name; } -// a copy of the name into the caller's return slot. +// PE 0x1013AD30: a copy of the name into the caller's return slot. ::renddx9abi::HostString RoadTemplate::getName() { return m_name; } +// PE 0x1013A140 void RoadTemplate::setUnknown5C(int value) { m_unknown5C = value; } int RoadTemplate::getUnknown5C() { return m_unknown5C; } +// PE 0x1013A160 void RoadTemplate::setUnknown60(float value) { m_unknown60 = value; } float RoadTemplate::getUnknown60() { return m_unknown60; } +// PE 0x1013A260 (slot +0x60 of IRoadTemplate's table 0x1021D610) // Writes the template's _compiled.con and _compiled.dat beside each other. // Requires writable output streams; failures are unchecked and the result is always true. - bool RoadTemplate::compile(const ::renddx9abi::HostString& path) { ::renddx9abi::HostString conFile(path); @@ -219,50 +227,44 @@ bool RoadTemplate::compile(const ::renddx9abi::HostString& path) static_cast< ::renddx9abi::HostFileMode>(0), static_cast< ::renddx9abi::HostFileAccess>(2), 0); // FileManager +0x18 - // The ostringstream's three lines; `endl` puts '\n' (and flushes a string buffer - nothing). - ::renddx9abi::HostString text("GeometryTemplate.create RoadCompiled "); - text += getName(); // #3 - text += "\n"; - text += "ObjectTemplate.create SimpleObject "; - text += getName(); // #4 - text += "\n"; - text += "ObjectTemplate.geometry "; - text += getName(); // #5 - text += "\n"; - - stream->write(text.c_str(), static_cast(text.size())); // +0x14, unguarded + // Three lines through an ostringstream; `endl` puts '\n' and flushes the string buffer (no effect). + std::ostringstream text; + text << "GeometryTemplate.create RoadCompiled " << getName() << std::endl; // #3 + text << "ObjectTemplate.create SimpleObject " << getName() << std::endl; // #4 + text << "ObjectTemplate.geometry " << getName() << std::endl; // #5 + + // str() is taken twice: once for the size, once for the data (0x1013A4CD / 0x1013A4E0). + stream->write(text.str().c_str(), static_cast(text.str().size())); // +0x14, unguarded stream->release(); // +0x08 TerrainRawReader raw; - raw.open(::renddx9abi::toVc71String(datFile), 0, 2, 0); + raw.open(::renddx9abi::fromHostString(datFile), 0, 2, 0); - vc71::string line0(::renddx9abi::toVc71String(m_textureFiles[0u])); - line0 += "\n"; // operator+=(char) 0x0A + std::string line0(::renddx9abi::fromHostString(m_textureFiles[0u])); + line0 += '\n'; // operator+=(char) 0x0A raw.writeString(line0); - vc71::string line1(::renddx9abi::toVc71String(m_textureFiles[1u])); - line1 += "\n"; + std::string line1(::renddx9abi::fromHostString(m_textureFiles[1u])); + line1 += '\n'; raw.writeString(line1); raw.writeF32(m_blendFactor); raw.writeVec2(&m_fadeOffDistance); - raw.writeU32(static_cast(m_priority)); + raw.writeI32(m_priority); // sub_10076160, the int writer raw.close(); return true; } -// RefFactory refuse aggregation, 0x88 bytes, construct, QI with NO null test on the -// object (shipped), release on refusal. (The native flavour's object is smaller - its HostString is -// the host's std::string - and still fits the shipped block.) +// RefFactory refuse aggregation, the object (retail 0x88 bytes), construct, QI with NO null +// test on the object (shipped), release on refusal. IBase* __fastcall createRoadTemplate(unsigned int iid, IBase* outer) { if (outer) return 0; - static_assert(sizeof(RoadTemplate) <= 0x88, "the shipped 0x88-byte block must hold the object"); - void* const storage = ::renddx9abi::engineAlloc(0x88); + void* const storage = ::renddx9abi::engineAlloc(sizeof(RoadTemplate)); RoadTemplate* self = 0; if (storage) self = new (storage) RoadTemplate(); diff --git a/Code/BF2/Geom/RoadTemplate.h b/Code/BF2/Geom/RoadTemplate.h index b764b00a0..43405134f 100644 --- a/Code/BF2/Geom/RoadTemplate.h +++ b/Code/BF2/Geom/RoadTemplate.h @@ -8,13 +8,12 @@ #define BF2_GEOM_ROADTEMPLATE_H #include "IRoadTemplate.h" // IRoadTemplate (table 0x1021D610), shared with the editor -#include "UndergrowthSystem.h" // Vc71Vec -#include "Vc71BoolVector.h" #include "../Math/Vec3.h" // Vec2 #include "../../RendDX9Abi/HfeAbi.h" #include "../../RendDX9Abi/PluginAbi.h" // renddx9abi::HostString #include +#include namespace dice { namespace hfe { @@ -62,10 +61,10 @@ class RoadTemplate : public IRoadTemplate // data, in shipped order int m_refCount; // +0x04 - Vc71Vec< ::renddx9abi::HostString> m_textureFiles; // +0x08 - Vc71Vec m_textureScales; // +0x18 - Vc71BoolVector m_mirrors; // +0x28 - Vc71Vec m_maxTesselatedErrors; // +0x3C + std::vector< ::renddx9abi::HostString> m_textureFiles; // +0x08 + std::vector m_textureScales; // +0x18 + std::vector m_mirrors; // +0x28 + std::vector m_maxTesselatedErrors; // +0x3C float m_blendFactor; // +0x4C Vec2 m_fadeOffDistance; // +0x50 float m_width; // +0x58 @@ -80,23 +79,7 @@ class RoadTemplate : public IRoadTemplate RoadTemplate& operator=(const RoadTemplate&); }; -// The retail flavour's layout is the shipped one. In the native flavour HostString is the host's -// std::string, so the name (and the texture-file elements) take that type's size instead - the -// object never crosses the boundary by layout, only through its slots. -#if defined(_M_IX86) && !BF2_PLUGIN_ABI_NATIVE -static_assert(offsetof(RoadTemplate, m_refCount) == 0x04, "refCount at +0x04"); -static_assert(offsetof(RoadTemplate, m_textureFiles) == 0x08, "texture files at +0x08"); -static_assert(offsetof(RoadTemplate, m_textureScales) == 0x18, "texture scales at +0x18"); -static_assert(offsetof(RoadTemplate, m_mirrors) == 0x28, "mirror flags at +0x28"); -static_assert(offsetof(RoadTemplate, m_maxTesselatedErrors) == 0x3C, "max errors at +0x3C"); -static_assert(offsetof(RoadTemplate, m_blendFactor) == 0x4C, "blend factor at +0x4C"); -static_assert(offsetof(RoadTemplate, m_fadeOffDistance) == 0x50, "fade-off at +0x50"); -static_assert(offsetof(RoadTemplate, m_width) == 0x58, "width at +0x58"); -static_assert(offsetof(RoadTemplate, m_material) == 0x64, "material at +0x64"); -static_assert(offsetof(RoadTemplate, m_name) == 0x68, "name at +0x68"); -static_assert(offsetof(RoadTemplate, m_priority) == 0x84, "priority at +0x84"); -static_assert(sizeof(RoadTemplate) == 0x88, "the factory 0x100B099A allocates 0x88"); -#endif +// The object never crosses the boundary by layout, only through its slots. // RefFactory published by ModuleGeom::getClassList. IBase* __fastcall createRoadTemplate(unsigned int iid, IBase* outer); diff --git a/Code/BF2/Geom/SkinnedMesh.cpp b/Code/BF2/Geom/SkinnedMesh.cpp index 3e2b1b81c..cb66a6ee9 100644 --- a/Code/BF2/Geom/SkinnedMesh.cpp +++ b/Code/BF2/Geom/SkinnedMesh.cpp @@ -5,40 +5,45 @@ #ifdef BF2_IMAGE_RENDDX9 +#include "../../RendDX9Abi/ThunkAbi.h" +#include "../RendDX9/RendDX9Math.h" // rendmath::normalize (sub_100777A0) #include "SkinnedMesh.h" #include "../../RendDX9Abi/BfMemory.h" // engineAlloc - the 104 bone matrices #include "../../RendDX9Abi/Frontier.h" -#include "../../RendDX9Abi/Vc71Vector.h" -#include "../../RendDX9Abi/Vc71Map.h" // the renderer queues' multimap insert +#include "../../RendDX9Abi/PluginEntry.h" #include "../Core/Ids.h" // IID_IBase / IID_IGeometry / IID_IRenderable #include "../Game/Objects/Visual/LightSource.h" // the gathered lights #include "../Math/Vec3.h" #include "../RendDX9/Ra/RaShader.h" // raObjectParametersConstruct #include "../RendDX9/RendDX9Base.h" // rendererFrameOrdinal, the render view +#include "../RendDX9/ShaderParameter.h" // the shadow-state parameters' release +#include "../RendDX9/QueueProfiler.h" +#if defined(__APPLE__) +#include "../Platform/X87Compat.h" +#endif +#include "../../RendDX9Abi/D3dx9Sdk.h" // ID3DXEffect - the shadow draw's commit #include "XpLightManager.h" // g_LightManager - the shadow lod +#include "HemiMapManager/HemiMapManager.h" // g_HemiMapManager - the base hemi map #include "MeshTemplate.h" // MeshBounds / meshBoundsFinalize #include "SkinnedMeshTemplate.h" #include "StaticMesh.h" // staticMeshRootParent - sub_10103CE0, shared // Host interfaces preserve virtual order. Field and container access selects the host ABI; // only the common IObject layout prefix is shared directly. -#if !BF2_PLUGIN_ABI_NATIVE -#define CORE_CLASSMANAGER_H -#endif #include "../Game/Objects/Visual/LightSourceTemplate.h" // getIsDynamic - the lit path's +0xF0 #include "../Game/Objects/IPlayer.h" // getVehicle / getCamera / hasFirstPersonView #include "../Game/Objects/ICameraObject.h" // getAllowDynamicLights #include "../Game/Objects/IObjectTemplate.h" // getClassID / getFlags #include "../Game/Objects/ObjectLayoutAccess.h" // IObject's retail-aligned prefix #include "../Scene/Object/PlayerManager.h" // getLocalHumanPlayer +#include "../Scene/Object/ObjectManager.h" +#include "../Scene/Object/ObjectPredicator.h" #include "../Scene/Object/ObjectTypes/Game/IPlayerControlObject.h" // the first-person pair -#if !BF2_PLUGIN_ABI_NATIVE -#undef CORE_CLASSMANAGER_H -#endif #include #include #include +#include namespace dice { namespace hfe { @@ -56,7 +61,8 @@ extern void* g_renderQueues; // RenderQueues.cpp - dword_1023E408, the Ra sha extern void* g_shaderManager; // ShaderManager.cpp - dword_1023B97C // declared per-TU, as QuadDrawer.cpp does; Effect.cpp publishes no header for it. -bool effectSetTechniqueByName(void* effect, const vc71::string& name); +bool effectSetTechniqueByName(void* effect, const std::string& name); +void* effectD3dxHandle(void* effect); // Effect.cpp - the wrapper's +0x08 ID3DXEffect* // The Renderer console object - a different global from g_rendererBase, and declared in this same // namespace by StaticMesh.cpp, StaticMeshStateManager.cpp and StaticMeshTemplate.cpp. @@ -76,33 +82,23 @@ namespace geom { extern LightManager* g_LightManager; // XpLightManager.cpp, dword_1024B914 extern IBase* g_SkinnedMeshRenderer; // ModuleGeom.cpp, dword_1024B8F8 +void xpGatherDebugLights(void* geometry, std::vector* out); namespace { // Per-geometry records contain paired vectors of 132-byte LODs and distance floats. -// The parallel companion table contains vectors of 16-byte records. -const vc71::vector_layout* geomRecord(const SkinnedMeshTemplate* t, unsigned int geom) +// The parallel material table holds one vector of 456-byte material records per lod. +// Both are indexed unguarded, as shipped. +SkinnedMeshGeomRecord* geomRecord(SkinnedMeshTemplate* t, unsigned int geom) { - return reinterpret_cast(t->m_vector0DC.first + 32 * geom); + return t->m_geoms.data() + geom; } -const vc71::vector_layout* companionRecord(const SkinnedMeshTemplate* t, unsigned int geom) +SkinnedMeshTemplate::GeomMaterials* companionRecord(SkinnedMeshTemplate* t, unsigned int geom) { - return reinterpret_cast(t->m_vector0CC.first + 16 * geom); + return t->m_materials.data() + geom; } -enum -{ - kLodRecordStride = 132, // the records inside a geom's nested vector - kCompanionStride = 16, // the records inside the companion's nested vector - kMaterialStride = 456, // what +0x58 counts out of m_lodMaterials - kPartRecordStride = 68, // the records +0x58 gathers ids from - kLodBoundsOffset = 28, // MeshBounds inside the 132-byte lod record: the radius - kLodBoundsDirtyOffset = 32, // and its "needs finalising" byte - kLodPartVectorOffset = 68, // first/last of the part vector, at +68 / +72 - kLightRecordStride = 68 // the records the draw builds at +0x584 -}; - // Shared selection and matrix helpers. @@ -136,49 +132,19 @@ const Mat4& skinnedMeshZeroMatrix() template R viewSlot(void* view, unsigned int slot) { - typedef R(__fastcall * Fn)(void*, void*); + typedef R(__thiscall * Fn)(void*); return reinterpret_cast( - (*reinterpret_cast(view))[slot / sizeof(void*)])(view, 0); + (*reinterpret_cast(view))[slot / 4])(view); } // The Renderer's two gate bytes, read at +0x6A3 and +0x6AB off the console object. bool rendererFlagAt(unsigned int byteOffset) { - return *(reinterpret_cast(dx9rend::g_Renderer) + byteOffset) != 0; -} - -// SkinnedMeshRenderer +0x40 - a mode word the draw compares against 2 in three places. -// sub_10123A40, `mov eax, [ecx+40h]; retn`. [INFERRED] name. -int skinnedMeshRendererMode() -{ - return *reinterpret_cast( - reinterpret_cast(g_SkinnedMeshRenderer) + 0x40); + return dx9rend::rendererTailByte(byteOffset) != 0; } - -// Submits by camera distance to the selected renderer map; the two draw paths use -// different maps. Compatibility nodes are 24 bytes. - -const unsigned int kSkinnedMeshRendererNodeSize = 0x18u; // SkinnedMeshRenderer.cpp's construct() - -void skinnedMeshRendererSubmit(SkinnedMesh* mesh, unsigned int mapOffset) -{ - if (!g_SkinnedMeshRenderer || !mesh) - return; - vc71::map_layout* const queue = reinterpret_cast( - reinterpret_cast(g_SkinnedMeshRenderer) + mapOffset); - queue->insertMultiFloat(mesh->m_distanceToCamera, mesh, kSkinnedMeshRendererNodeSize); -} - -void skinnedMeshRendererSubmitA(SkinnedMesh* mesh) // sub_10123A50, the renderer's +0x10 map -{ - skinnedMeshRendererSubmit(mesh, 0x10); -} - -void skinnedMeshRendererSubmitB(SkinnedMesh* mesh) // sub_10123A90, the renderer's +0x28 map -{ - skinnedMeshRendererSubmit(mesh, 0x28); -} +// SkinnedMeshRenderer's mode word (sub_10123A40) and its two distance-ordered submission queues +// (sub_10123A50 / sub_10123A90) are defined beside the renderer, in SkinnedMeshRenderer.cpp. // the lit path's LightSource seams // The light's own virtuals are typed (RW-266): getAbsolutePosition +0x68, getDirection +0x17C, @@ -193,13 +159,8 @@ world::LightSource* lightSourceOf(void* light) // Native LightSource has a different layout; never apply that offset to it. const world::LightSourceTemplate* lightSourceTemplate(void* light) { -#if BF2_PLUGIN_ABI_NATIVE return static_cast( static_cast(light)->getTemplate()); -#else - return *reinterpret_cast( - static_cast(light) + 0x144); -#endif } // A virtual, so typed in both flavours: the tree's slot 60 (+0xF0) is retail's getIsDynamic. @@ -225,13 +186,10 @@ int skinnedMeshLightDebugMode() return static_cast(g_skinnedMeshLightDebugMode); } -// Unreachable while the switch above stays zero, which in the shipped image is always. -void skinnedMeshDebugLightList(SkinnedMesh* mesh, vc71::vector_layout* out) +// PE 0x101A7EA7 calls the static Xp coordinator, not the LightManager singleton. +void skinnedMeshDebugLightList(SkinnedMesh* mesh, std::vector* out) { - (void)out; - RD9_FRONTIER_AT("dice::hfe::geom::skinnedMeshDebugLightList (PE sub_100EEED0, a multimap " - "equal_range walk keyed by the instance pointer; reachable only if something " - "sets ds:10264C48, which nothing in the shipped image does)", mesh, 0); + xpGatherDebugLights(mesh, out); } @@ -259,79 +217,47 @@ const unsigned int kTemplateCastsDynamicShadow = 0x0800u; // Empties the light pointer vector while retaining capacity. -void lightVectorResizeToEmpty(vc71::vector_layout& v) +void lightVectorResizeToEmpty(std::vector& v) { - if (v.first && v.first != v.last) - v.last = v.first; + v.clear(); } // Resizes the light-record vector without freeing capacity on shrink. -// New records leave attenuation at +0x38 untouched; the draw loop fills it before use. +// New records zero their first fourteen dwords and set +0x3C/+0x40 to 1.0f. The shipped record +// constructor leaves the attenuation at +0x38 unwritten; here it is value-initialised, which is +// not observable because the draw loop fills it before use. void skinnedMeshReserveLightRecords(SkinnedMesh* mesh, unsigned int count) { - vc71::vector_layout& v = mesh->m_lightRecords; + std::vector& v = mesh->m_lightRecords; - const unsigned int size = - v.first ? static_cast((v.last - v.first) / kLightRecordStride) : 0u; + const unsigned int size = static_cast(v.size()); if (count <= size) { // Shrink (or no change): the shipped path walks a destroy range and republishes `last`. - v.last = v.first + kLightRecordStride * count; + v.resize(count); return; } - const unsigned int capacity = - v.first ? static_cast((v.end - v.first) / kLightRecordStride) : 0u; - if (count > capacity) - { - char* const grown = - static_cast(::renddx9abi::engineAlloc(kLightRecordStride * count)); - if (!grown) - return; - if (v.first) - { - std::memcpy(grown, v.first, kLightRecordStride * size); - ::renddx9abi::engineFree(v.first); - } - v.first = grown; - v.end = grown + kLightRecordStride * count; - } - v.last = v.first + kLightRecordStride * count; - + v.resize(count); for (unsigned int i = size; i < count; ++i) { - unsigned char* const record = - reinterpret_cast(v.first) + kLightRecordStride * i; - std::memset(record, 0, 0x38); // the fourteen zeroed dwords - // +0x38 is deliberately NOT written - see the header note. - *reinterpret_cast(record + 0x3C) = 1.0f; - *reinterpret_cast(record + 0x40) = 1.0f; + dx9rend::Ra::RaLightRecord& record = v[i]; + std::memset(&record, 0, 0x38); // the fourteen zeroed dwords + record.float3C = 1.0f; + record.float40 = 1.0f; } } -// sub_100286E0 - the Renderer's time, off its +0x5DC. sub_1015C5E0 - the LightManager's fade -// duration, a double at its +0x838. Both return doubles and both are kept as doubles. -// sub_100286E0 -> sub_100776A0 - The Renderer holds a timer pointer at -// its +0x5DC, and the time is that object's +0x20 read as a double. Two indirections, not one: -// reading +0x5DC itself as a double would give a pointer bit pattern. -double rendererTimeSeconds() -{ - void* const timer = *reinterpret_cast( - reinterpret_cast(dx9rend::g_Renderer) + 0x5DC); - return *reinterpret_cast(static_cast(timer) + 0x20); -} - } // anonymous namespace // Shader-quality masks populated by technique initialization before any mesh draw. // [CHOSEN, not recovered] Storage lives with its accessor. -// [RETIRE-WHEN: the SkinnedMesh technique init fills it] -vc71::vector_layout g_skinnedMeshQualityMasks = { 0, 0, 0, 0 }; +std::vector g_skinnedMeshQualityMasks; // The SkinnedMesh technique map behind sub_1010EFF0's two lookups - header at 0x1025B574. Mirrors // `g_staticMeshTechniques` in StaticMeshTemplate.cpp, and like it this is a file-scope static that @@ -344,11 +270,11 @@ extern unsigned char g_skinnedMeshTechniquesPending; // StaticMeshTemplate.cpp publishes this: it is sub_101921D0, which the shipped image calls from // both classes' technique inits. See the note beside the forwarder there. -bool meshBuildTechniqueMasks(const vc71::string& mfxPath, - const vc71::string& techniquePrefix, +bool meshBuildTechniqueMasks(const std::string& mfxPath, + const std::string& techniquePrefix, const char* const* bitNames, std::map& techniqueMap, - vc71::vector_layout& maskVector); + std::vector& maskVector); // Shader feature names in bit order: each entry encodes 1 << index. @@ -370,6 +296,17 @@ const char* const kSkinnedMeshShaderBitNames[] = }; +// PE 0x1010F160 (`retn 8`, this unread). Inserts (bits, shader) into the skinned technique map +// (0x1025B574, insert 0x100EBA10); an existing key is kept. Unreachable in 1.50: no code or data +// references. The shipped body leaves the address of its own dead stack pair in eax; no result is +// modelled, as for staticMeshInsertTechnique (0x10116E70). [INFERRED] name and signature. +void skinnedMeshInsertTechnique(unsigned int bits, ::dice::hfe::dx9rend::Ra::RaShader* shader); +void skinnedMeshInsertTechnique(unsigned int bits, ::dice::hfe::dx9rend::Ra::RaShader* shader) +{ + g_skinnedMeshTechniques.insert(std::make_pair(bits, shader)); +} + + // Initializes skinned technique masks and the Default fallback at key 0xF8000000. // Failed loads leave the gate armed for retry and do not emit a diagnostic. @@ -378,8 +315,8 @@ void skinnedMeshInitTechniques() bool built = false; if (g_skinnedMeshTechniquesPending) // byte_102397D4, 0x1010F19C { - vc71::string prefix("SM"); - vc71::string mfx("shaders/RaShaderSM.mfx"); + std::string prefix("SM"); + std::string mfx("shaders/RaShaderSM.mfx"); built = meshBuildTechniqueMasks(mfx, prefix, kSkinnedMeshShaderBitNames, g_skinnedMeshTechniques, g_skinnedMeshQualityMasks); @@ -388,7 +325,7 @@ void skinnedMeshInitTechniques() if (!built) return; // 0x1010F217, and nothing is logged - vc71::string name("Default"); + std::string name("Default"); ::dice::hfe::dx9rend::Ra::RaShader* const shader = ::dice::hfe::dx9rend::Ra::getShader( static_cast< ::dice::hfe::dx9rend::Ra::RaShaderTable*>( @@ -405,26 +342,13 @@ namespace { unsigned int shaderMaskTableSize() { - return g_skinnedMeshQualityMasks.first - ? static_cast(g_skinnedMeshQualityMasks.last - - g_skinnedMeshQualityMasks.first) >> 2 - : 0u; + return static_cast(g_skinnedMeshQualityMasks.size()); } const unsigned int* shaderMaskTable() { - // [CHOSEN, not recovered] Report an unloaded technique table before indexed access. - // Normal material loading fills it before drawing. - if (!g_skinnedMeshQualityMasks.first) - { - RD9_FRONTIER_AT("dice::hfe::geom::shaderMaskTable - the per-quality mask vector " - "(ds:1025B584) is EMPTY. Its filler is the technique init inside " - "SkinnedMeshTemplate::readMaterials (slot +0xDC, sub_1010FD00), which IS " - "written - so reaching this means a draw ran before that template loaded", - 0, 0); - return 0; - } - return reinterpret_cast(g_skinnedMeshQualityMasks.first); + // PE 0x101A7AF0 reads the data pointer without an empty-table guard. + return g_skinnedMeshQualityMasks.data(); } @@ -447,30 +371,9 @@ void* findShaderForBits(unsigned int bits) return 0; } -// sub_10103CB0 - Walk UP the parent chain (+0x28, the same link -// staticMeshRootParent follows) asking each ancestor for IID_IPlayerControlObject (50373), and -// return the first that answers. So it means "the nearest ancestor the local player CONTROLS" - -// which is exactly what the draw's first-person test needs, and it is why the test compares this -// against the light owner's own +0x44 rather than comparing raw roots. -// queryInterface is IBase slot 3 (+0x0C) and the parent is IObject's -// retail-aligned +0x28 prefix field (ObjectLayoutAccess), identical in both flavours. -void* skinnedMeshObjectOf(void* object) -{ - world::IObject* current = static_cast(object); - while (current) - { - void* const found = current->queryInterface(::dice::hfe::world::IID_IPlayerControlObject); - if (found) - return found; - current = world::object_detail::LayoutAccess::parent(current); // +0x28 - } - return 0; -} - double lightManagerFadeSeconds() { - return *reinterpret_cast( - reinterpret_cast(g_LightManager) + 0x838); + return lightManagerShadowFadeDuration(g_LightManager); // +0x838 } // The draw tail's remaining seams. [UNRESOLVED] owners; offsets are read. @@ -481,8 +384,6 @@ unsigned int shaderMaskTableSize(); // sub_1010EFF0 - define-bits -> shader, falling back to the 0xF8000000 default entry. Its // diagnostics carry the SkinnedMeshTemplate.cpp __FILE__ at lines 918 and 926. void* findShaderForBits(unsigned int bits); -// sub_10103CB0 - the companion of staticMeshRootParent used by the first-person test. -void* skinnedMeshObjectOf(void* object); // Clamps high before low; NaN passes through unchanged. float clampFloat(float value, float low, float high) @@ -495,169 +396,86 @@ float clampFloat(float value, float low, float high) return static_cast(v); } -// and recorded rather than named: sub_10079610 is `transformPoint` -// (row 3 added), sub_1007C440 is `transformVector` (row 3 NOT added) and sub_100FB020 is -// transformPoint packed into a Vec4 with an explicit w. Three near-identical bodies whose only -// difference is the translation row and the trailing store; do not substitute one for another. -// sub_10079610, transcribed. The shipped body computes z and y into x87 registers before -// storing x, because out[] may alias in[]; the ordering is load-bearing and is preserved. -void mat4TransformPoint(const Mat4& m, const float in[3], float out[3]) -{ - const float z = m.m[2] * in[0] + m.m[10] * in[2] + m.m[6] * in[1] + m.m[14]; - const float y = m.m[1] * in[0] + m.m[9] * in[2] + m.m[5] * in[1] + m.m[13]; - out[0] = m.m[8] * in[2] + m.m[4] * in[1] + in[0] * m.m[0] + m.m[12]; - out[1] = y; - out[2] = z; -} - -// sub_1007C440 - the same body without the translation row: a direction, not a point. -void mat4TransformVector(const Mat4& m, const float in[3], float out[3]) -{ - const float z = m.m[2] * in[0] + m.m[10] * in[2] + m.m[6] * in[1]; - const float y = m.m[1] * in[0] + m.m[9] * in[2] + m.m[5] * in[1]; - out[0] = m.m[8] * in[2] + m.m[4] * in[1] + in[0] * m.m[0]; - out[1] = y; - out[2] = z; -} - // Transforms a point and writes w before x/y/z; preserve the store order when out aliases input. +// PE 0x100FB020 void mat4TransformPointVec4(const Mat4& m, const float in[3], void* out, unsigned int w) { +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain all three x87 results until the w-first stores. + using namespace bf2x87; + const Real z = add(add(add(mul(wide(m.m[6]), wide(in[1])), + mul(wide(m.m[10]), wide(in[2]))), mul(wide(m.m[2]), wide(in[0]))), wide(m.m[14])); + const Real y = add(add(add(mul(wide(m.m[5]), wide(in[1])), + mul(wide(m.m[9]), wide(in[2]))), mul(wide(m.m[1]), wide(in[0]))), wide(m.m[13])); + const Real x = add(add(add(mul(wide(m.m[4]), wide(in[1])), + mul(wide(m.m[8]), wide(in[2]))), mul(wide(in[0]), wide(m.m[0]))), wide(m.m[12])); +#else const float z = m.m[6] * in[1] + m.m[10] * in[2] + m.m[2] * in[0] + m.m[14]; const float y = m.m[5] * in[1] + m.m[9] * in[2] + m.m[1] * in[0] + m.m[13]; const float x = m.m[4] * in[1] + m.m[8] * in[2] + in[0] * m.m[0] + m.m[12]; +#endif unsigned char* const d = static_cast(out); *reinterpret_cast(d + 12) = w; - *reinterpret_cast(d + 0) = x; - *reinterpret_cast(d + 4) = y; - *reinterpret_cast(d + 8) = z; -} - -// sub_100777A0 - normalise in place, but only when the squared length is not already 1 within -// FLT_EPSILON; a degenerate vector is zeroed and -20001 returned. SkyDome.cpp carries this same -// body in its anonymous namespace, so it has internal linkage and cannot be shared - this is that -// transcription repeated, not a second independent reading. The draw discards the return, as every -// caller in the image does. -void mat4Normalize(float v[3]) -{ - const float lengthSq = v[0] * v[0] + v[1] * v[1] + v[2] * v[2]; - if (std::fabs(static_cast(lengthSq) - 1.0) >= 1.1920929e-7) - { - if (std::fabs(static_cast(lengthSq)) < 1.1920929e-7) - { - v[0] = 0.0f; - v[1] = 0.0f; - v[2] = 0.0f; - return; - } - const double scale = 1.0 / std::sqrt(static_cast(lengthSq)); - v[0] = static_cast(v[0] * scale); - v[1] = static_cast(v[1] * scale); - v[2] = static_cast(v[2] * scale); - } -} - - -// Assigns POD elements, reusing capacity when possible and clearing an empty source. -// [CHOSEN, not recovered] Allocation helpers reproduce contents and ownership without -// the original allocator internals. [RETIRE-WHEN: RW-74] - -void vectorAssignRaw(vc71::vector_layout& dst, const vc71::vector_layout& src, unsigned elemSize) -{ - if (&dst == &src) - return; - - const unsigned int srcCount = - src.first ? static_cast((src.last - src.first) / elemSize) : 0u; - if (!srcCount) - { - if (dst.first) - ::renddx9abi::engineFree(dst.first); - dst.first = 0; - dst.last = 0; - dst.end = 0; - return; - } - - const unsigned int capacity = - dst.first ? static_cast((dst.end - dst.first) / elemSize) : 0u; - if (srcCount > capacity) - { - if (dst.first) - ::renddx9abi::engineFree(dst.first); - char* const grown = static_cast(::renddx9abi::engineAlloc(elemSize * srcCount)); - dst.first = grown; - dst.end = grown ? grown + elemSize * srcCount : 0; - if (!grown) - { - dst.last = 0; - return; - } - } - std::memcpy(dst.first, src.first, elemSize * srcCount); - dst.last = dst.first + elemSize * srcCount; + *reinterpret_cast(d + 0) = static_cast(x); + *reinterpret_cast(d + 4) = static_cast(y); + *reinterpret_cast(d + 8) = static_cast(z); } -// Copies the base queue payload, including nested 64-byte and 16-byte record vectors. +// Copies the base queue payload - the entry's lighting block (entry +0x08) - including its nested +// 64-byte and 16-byte record vectors. The `+0xNN` comments are retail offsets in that block. // Ref-counted pointers release before addRef; keep the old != new guards for self-assignment. // The two references are COM interfaces: Release (+0x08) and AddRef (+0x04) are __stdcall with the // interface pushed, as the shipped copy calls them - not __fastcall with it in ECX, which hands the // callee a stack word as its `this` (a skinned mesh lit by a muzzle flash crashed in d3d9.dll so). -void renderQueueEntryCopyPayload(void* destEntry, void* sourceEntry) +void renderQueueEntryCopyPayload(dx9rend::Ra::RaLightingParameters& d, + const dx9rend::Ra::RaLightingParameters& a) { - unsigned char* const d = static_cast(destEntry); - const unsigned char* const a = static_cast(sourceEntry); - if (d == a) + if (&d == &a) return; typedef unsigned long(__stdcall * RefFn)(void*); struct Local { - static void swapRef(unsigned char* dst, const unsigned char* src, unsigned int at) + static void swapRef(void*& dst, void* const& src) { - void* const oldRef = *reinterpret_cast(dst + at); - void* const newRef = *reinterpret_cast(src + at); + void* const oldRef = dst; + void* const newRef = src; if (oldRef == newRef) return; if (oldRef) // release first - shipped, and safe only behind the test above reinterpret_cast((*reinterpret_cast(oldRef))[0x08 / 4])(oldRef); - *reinterpret_cast(dst + at) = newRef; + dst = newRef; if (newRef) reinterpret_cast((*reinterpret_cast(newRef))[0x04 / 4])(newRef); } }; - *reinterpret_cast(d + 0x04) = *reinterpret_cast(a + 0x04); - - std::memcpy(d + 0x0C, a + 0x0C, 0x1C - 0x0C); // +0x0C .. +0x18 - Local::swapRef(d, a, 0x20); - Local::swapRef(d, a, 0x28); - std::memcpy(d + 0x30, a + 0x30, 0x40 - 0x30); // +0x30 .. +0x3C - *reinterpret_cast(d + 0x44) = *reinterpret_cast(a + 0x44); - *reinterpret_cast(d + 0x48) = *reinterpret_cast(a + 0x48); - std::memcpy(d + 0x50, a + 0x50, 0x60 - 0x50); // +0x50 .. +0x5C - std::memcpy(d + 0x64, a + 0x64, sizeof(Mat4)); - - vectorAssignRaw(*reinterpret_cast(d + 168), - *reinterpret_cast(a + 168), 64); - vectorAssignRaw(*reinterpret_cast(d + 188), - *reinterpret_cast(a + 188), 64); - vectorAssignRaw(*reinterpret_cast(d + 208), - *reinterpret_cast(a + 208), 16); - vectorAssignRaw(*reinterpret_cast(d + 228), - *reinterpret_cast(a + 228), 16); - *reinterpret_cast(d + 248) = *reinterpret_cast(a + 248); - vectorAssignRaw(*reinterpret_cast(d + 252), - *reinterpret_cast(a + 252), 16); - *reinterpret_cast(d + 268) = *reinterpret_cast(a + 268); -} - -// The SkinnedMeshRenderer's cached shadow Effect (ds:1025B230) and its four cached ShaderParameters -// (ds:1025B234/238/23C/240). All five are filled by SkinnedMeshRenderer, which is NOT recovered -// (sub_10123Axx); the shadow draw below is written in full against them, which is the same position -// StaticMesh.cpp's shadow pass is in - transcribed, compiled, and not yet drivable. + d.registry = a.registry; // +0x04 + + std::memcpy(d.unnamed008.value, a.unnamed008.value, sizeof(d.unnamed008.value)); // +0x0C + Local::swapRef(d.terrainLightMap.value, a.terrainLightMap.value); // +0x20 + Local::swapRef(d.lightMap.value, a.lightMap.value); // +0x28 + std::memcpy(d.lightMapOffset.value, a.lightMapOffset.value, + sizeof(d.lightMapOffset.value)); // +0x30 + d.matBones.a = a.matBones.a; // +0x44 + d.matBones.b = a.matBones.b; // +0x48 + std::memcpy(d.overGrowthAmbient.value, a.overGrowthAmbient.value, + sizeof(d.overGrowthAmbient.value)); // +0x50 + std::memcpy(d.shadowViewProj.value, a.shadowViewProj.value, sizeof(Mat4)); // +0x64 + + using ::dice::hfe::dx9rend::Ra::raAssignParamBytes; + raAssignParamBytes(d.shadowViewProjArray.value, a.shadowViewProjArray.value); // +0xA8 + raAssignParamBytes(d.clampViewProjArray.value, a.clampViewProjArray.value); // +0xBC + raAssignParamBytes(d.shadowPosArray.value, a.shadowPosArray.value); // +0xD0 + raAssignParamBytes(d.shadowSizeArray.value, a.shadowSizeArray.value); // +0xE4 + d.shadowCount.value = a.shadowCount.value; // +0xF8 + raAssignParamBytes(d.tail0FC, a.tail0FC); // +0xFC + d.tail10C = a.tail10C; // +0x10C +} + +// Shadow effect and parameters retained by SkinnedMeshTemplate::readMaterials. struct SkinnedMeshShadowState { void* effect; // ds:1025B230; its +0x08 is the D3DX interface, CommitChanges at 0x104 @@ -669,14 +487,19 @@ struct SkinnedMeshShadowState // Shared shadow effect and parameters initialized by SkinnedMeshTemplate::readMaterials. -// Later templates retain the existing references. The [CHOSEN] guard reports missing -// initialization before a draw can dereference this state. +// Later templates retain the existing references. SkinnedMeshShadowState g_skinnedMeshShadowState = { 0, 0, 0, 0, 0 }; } // anonymous namespace +// [CHOSEN, not recovered] Named access to the shared effect read at PE 0x1015C2A6. +dx9rend::Effect* skinnedMeshShadowEffect() +{ + return static_cast(g_skinnedMeshShadowState.effect); +} + // Creates shared shadow parameters once, otherwise retains each existing reference. // Effect loading must succeed before the unguarded parameter lookups. @@ -686,37 +509,37 @@ void skinnedMeshInitShadowState() if (state.effect) { - typedef void(__fastcall * RefFn)(void*, void*); + typedef void(__thiscall * RefFn)(void*); reinterpret_cast( - (*reinterpret_cast(state.effect))[0x00 / sizeof(void*)])(state.effect, 0); + (*reinterpret_cast(state.effect))[0x00 / 4])(state.effect); void* const params[4] = { state.lightMat, state.lightTrapezMat, state.texLayer0, state.geomBones }; for (int i = 0; i < 4; ++i) reinterpret_cast( - (*reinterpret_cast(params[i]))[0x04 / sizeof(void*)])(params[i], 0); + (*reinterpret_cast(params[i]))[0x04 / 4])(params[i]); return; } // dice.hfe.geom.GeometryTemplate.SkinnedMesh, from ModuleGeom.cpp's class-id census. const unsigned int kSkinnedMeshTemplateClassId = 0x870CA652u; - vc71::string effectName("Shaders/"); // *unk_10263DF0, static init at 0x101D5740 + std::string effectName("Shaders/"); // *unk_10263DF0, static init at 0x101D5740 effectName += "SkinnedMesh"; state.effect = ::dice::hfe::dx9rend::shaderManagerGetEffect( ::dice::hfe::dx9rend::g_shaderManager, effectName.c_str()); { void* const lm = g_LightManager; - typedef void(__fastcall * RegisterFn)(void*, void*, unsigned int, void*); + typedef void(__thiscall * RegisterFn)(void*, unsigned int, void*); reinterpret_cast( - (*reinterpret_cast(lm))[0x2F0 / sizeof(void*)])( - lm, 0, kSkinnedMeshTemplateClassId, state.effect); + (*reinterpret_cast(lm))[0x2F0 / 4])( + lm, kSkinnedMeshTemplateClassId, state.effect); - typedef unsigned char(__fastcall * PredFn)(void*, void*); + typedef unsigned char(__thiscall * PredFn)(void*); if (reinterpret_cast( - (*reinterpret_cast(lm))[0xF0 / sizeof(void*)])(lm, 0)) + (*reinterpret_cast(lm))[0xF0 / 4])(lm)) { - const vc71::string technique( + const std::string technique( ::dice::hfe::dx9rend::deviceCapsIsNvidia() ? "DrawShadowMapNV" : "DrawShadowMap"); ::dice::hfe::dx9rend::effectSetTechniqueByName(state.effect, technique); } @@ -725,30 +548,36 @@ void skinnedMeshInitShadowState() ::dice::hfe::dx9rend::Effect* const effect = static_cast< ::dice::hfe::dx9rend::Effect*>(state.effect); state.lightMat = - ::dice::hfe::dx9rend::effectGetShaderParameterTyped(effect, vc71::string("vpLightMat")); + ::dice::hfe::dx9rend::effectGetShaderParameterTyped(effect, std::string("vpLightMat")); state.lightTrapezMat = - ::dice::hfe::dx9rend::effectGetShaderParameterTyped(effect, vc71::string("vpLightTrapezMat")); + ::dice::hfe::dx9rend::effectGetShaderParameterTyped(effect, std::string("vpLightTrapezMat")); state.texLayer0 = - ::dice::hfe::dx9rend::effectGetShaderParameterTyped(effect, vc71::string("TEXLAYER0")); + ::dice::hfe::dx9rend::effectGetShaderParameterTyped(effect, std::string("TEXLAYER0")); state.geomBones = - ::dice::hfe::dx9rend::effectGetShaderParameterTyped(effect, vc71::string("BoneArray")); + ::dice::hfe::dx9rend::effectGetShaderParameterTyped(effect, std::string("BoneArray")); +} + +// PE 0x10110875..0x101108C4 (SkinnedMeshTemplate's destructor). Each pointer is tested before +// its release (slot +0x08); only the effect's result is read. +void skinnedMeshReleaseShadowState() +{ + SkinnedMeshShadowState& state = g_skinnedMeshShadowState; + void* const params[4] = + { state.lightMat, state.lightTrapezMat, state.texLayer0, state.geomBones }; + for (int i = 0; i < 4; ++i) + if (params[i]) + static_cast< ::dice::hfe::dx9rend::ShaderParameter*>(params[i])->release(); + if (state.effect + && !::dice::hfe::dx9rend::effectRelease( + static_cast< ::dice::hfe::dx9rend::Effect*>(state.effect))) + state.effect = 0; } namespace { SkinnedMeshShadowState* skinnedMeshShadowState() { - // Require shadow-technique initialization before this draw. - if (!g_skinnedMeshShadowState.effect) - { - RD9_FRONTIER_AT("dice::hfe::geom::skinnedMeshShadowState - the five globals at " - "ds:1025B230..1025B240 are NULL. Their one-shot initialiser IS written - " - "SkinnedMeshTemplate::readMaterials (slot +0xDC, sub_1010FD00) - so " - "reaching this means a shadow draw ran before that template loaded; the " - "parameters are vpLightMat / vpLightTrapezMat / TEXLAYER0 / BoneArray", - 0, 0); - return 0; - } + // PE 0x101A86B0 uses these globals without an initialization guard. return &g_skinnedMeshShadowState; } @@ -760,27 +589,27 @@ SkinnedMeshShadowState* skinnedMeshShadowState() // reaches through its typed dx9rend::ShaderParameter::setValue. void shaderParameterSetValue(void* parameter, const void* value, int index) { - typedef void(__fastcall * Fn)(void*, void*, const void*, int); + typedef void(__thiscall * Fn)(void*, const void*, int); reinterpret_cast( - (*reinterpret_cast(parameter))[0x18 / sizeof(void*)])(parameter, 0, value, index); + (*reinterpret_cast(parameter))[0x18 / 4])(parameter, value, index); } // ShaderParameter vslot +0x28 - the matrix-array upload, `(Mat4 palette, unsigned count)`. This // is the GeomBones set: the skinning palette reaching the shader. void shaderParameterSetMatrixArray(void* parameter, Mat4* const* palette, unsigned int count) { - typedef void(__fastcall * Fn)(void*, void*, Mat4* const*, unsigned int); + typedef void(__thiscall * Fn)(void*, Mat4* const*, unsigned int); reinterpret_cast( - (*reinterpret_cast(parameter))[0x28 / sizeof(void*)])(parameter, 0, palette, count); + (*reinterpret_cast(parameter))[0x28 / 4])(parameter, palette, count); } // `mov eax, [effect+8]; call [[eax]+104h]` - ID3DXEffect::CommitChanges on the wrapper's D3DX // effect. Byte-for-byte the shape StaticMesh.cpp's staticMeshEffectCommitChanges records. +// The only caller passes skinnedMeshShadowState()->effect, which that accessor has proven non-null. void skinnedMeshEffectCommitChanges(void* effect) { - void* const d3dx = *reinterpret_cast(static_cast(effect) + 8); - typedef void(__stdcall * Fn)(void*); - reinterpret_cast((*reinterpret_cast(d3dx))[0x104 / sizeof(void*)])(d3dx); + ID3DXEffect* const d3dx = static_cast(dx9rend::effectD3dxHandle(effect)); + d3dx->CommitChanges(); } // The renderer's statistics block, its +0x23C word. Every shadow draw adds the material's primitive @@ -789,9 +618,9 @@ void skinnedMeshEffectCommitChanges(void* effect) void skinnedMeshCountShadowPrimitives(unsigned int primitives) { void* const base = dx9rend::g_rendererBase; - typedef void*(__fastcall * Fn)(void*, void*); + typedef void*(__thiscall * Fn)(void*); void* const stats = reinterpret_cast( - (*reinterpret_cast(base))[0x6C / sizeof(void*)])(base, 0); + (*reinterpret_cast(base))[0x6C / 4])(base); *reinterpret_cast(static_cast(stats) + 0x23C) += primitives; } @@ -801,8 +630,7 @@ void skinnedMeshCountShadowPrimitives(unsigned int primitives) // views through the base. Two different globals, kept apart. [UNRESOLVED] names; offsets are read. float rendererLodScaleAt(unsigned int byteOffset) { - return *reinterpret_cast( - reinterpret_cast(dx9rend::g_Renderer) + byteOffset); + return dx9rend::rendererTailFloat(byteOffset); } @@ -810,7 +638,7 @@ float rendererLodScaleAt(unsigned int byteOffset) // Initializes mesh state, selects loaded template data, then allocates the palette. -// Vector allocator words and fields +0x160, +0x348, and +0x594 remain untouched. +// Fields +0x160, +0x348, and +0x594 remain untouched. SkinnedMesh::SkinnedMesh(void* objectTemplate) : GeometryInstanceData(g_skinnedMeshVtable) @@ -838,10 +666,7 @@ SkinnedMesh::SkinnedMesh(void* objectTemplate) m_matrixE0 = Mat4::getIdentity(); m_matrix120 = Mat4::getIdentity(); - // +0x164: first/last/end only. The allocator word is NOT written - shipped. - m_lights.first = 0; - m_lights.last = 0; - m_lights.end = 0; + // +0x164: the light vector is constructed empty with the object. m_boneTransforms = 0; // +0x174 / +0x178, the caller's skeleton palette m_boneTransformCount = 0; @@ -857,13 +682,9 @@ SkinnedMesh::SkinnedMesh(void* objectTemplate) m_float354 = 1.0f; m_double358 = 0.0; - // +0x360 .. +0x583, the 0x224-byte block Terrain.cpp already drives. - ::dice::hfe::dx9rend::Ra::raObjectParametersConstruct(m_objectParameters); + // +0x360: m_objectParameters (sub_100458E0) is constructed with the object. - // +0x584: first/last/end only, allocator word untouched - the same shape again. - m_lightRecords.first = 0; - m_lightRecords.last = 0; - m_lightRecords.end = 0; + // +0x584: the light-record vector is constructed empty with the object. // the same arithmetic as refreshSelection, inlined here in retail. // No template/null/vector guards are shipped beyond this loaded-byte test. Instances made @@ -890,10 +711,8 @@ SkinnedMesh::SkinnedMesh(void* objectTemplate) } m_fov = -1.0f; // PE 0x101A79CF, after the palette loop - // [UNRESOLVED] Separate existing constructor gap: retail 0x101A79EB..0x101A79F1 looks up - // ClassManager.getSingleton("HeightmapCluster") here. The current zero keeps the named - // updateHeightOverTerrain frontier unreachable; this radius repair does not recover it. - m_heightmapCluster = 0; + // PE 0x101A7650: the borrowed singleton lookup is the constructor's final operation. + m_heightmapCluster = classManager->getSingleton(renddx9abi::HostString("HeightmapCluster")); } SkinnedMesh* skinnedMeshConstruct(void* storage, void* objectTemplate) @@ -934,8 +753,8 @@ int SkinnedMesh::release() // Dispatched through the vtable (`mov eax,[ecx]; push 1; call [eax+34h]`), not called // directly. Slot +0x34 is the scalar deleting destructor, and flag bit 0 tells it to free // the block after running ~SkinnedMesh. - typedef void*(__fastcall * DeleteFn)(void*, void*, unsigned int); - reinterpret_cast(m_vptr[0x34 / sizeof(void*)])(this, 0, 1u); + typedef void*(__thiscall * DeleteFn)(void*, unsigned int); + reinterpret_cast(m_vptr[0x34 / 4])(this, 1u); } return remaining; } @@ -1026,12 +845,11 @@ float SkinnedMesh::getBoundingRadius() const return 1.0f; // ds:101DDDE4 == 1.0f } - MeshBounds* const bounds = - reinterpret_cast(m_lodRecord + kLodBoundsOffset - 28); - if (m_lodRecord[kLodBoundsDirtyOffset]) - meshBoundsFinalize(*bounds); + MeshBounds& bounds = m_lodRecord->bounds; + if (bounds.dirty) // lod +0x20 + meshBoundsFinalize(bounds); - return *reinterpret_cast(m_lodRecord + kLodBoundsOffset); + return bounds.radius; // lod +0x1C } @@ -1078,33 +896,23 @@ void SkinnedMesh::gatherVisibleParts(HostIntVector* out) updateLodSelection(); // sub_101A7180, the same refresh both draws run first const unsigned int geomCount = - m_lodMaterials && m_lodMaterials->first - ? static_cast((m_lodMaterials->last - m_lodMaterials->first) - / kMaterialStride) - : 0u; + m_lodMaterials ? static_cast(m_lodMaterials->size()) : 0u; // The ONE place this class touches a container the host owns. See the HostIntVector note in - // the header for why the type differs by flavour; the push below is the only line that cares. -#if BF2_PLUGIN_ABI_NATIVE + // the header; the push below is the only line that cares. HostIntVector& ids = *out; // our own BF2.exe: same STL, same /MD heap, same container -#else - vc71::vectorRef ids(out); // the retail host's VC7.1 vector, driven through the shim -#endif for (unsigned int i = 0; i < geomCount; ++i) { - const unsigned int byteOffset = 16 * i; - const int* part = *reinterpret_cast( - m_lodRecord + byteOffset + kLodPartVectorOffset); + // The lod's part vector i (lod +0x40 + 16 * i); its end is re-read per element. + const SkinnedMeshPart* part = m_lodRecord->parts[i].data(); - while (part != *reinterpret_cast( - m_lodRecord + byteOffset + kLodPartVectorOffset + 4)) + while (part != m_lodRecord->parts[i].data() + m_lodRecord->parts[i].size()) { - if (m_excludedPart != *part) - ids.push_back(*part); + if (m_excludedPart != part->partId) + ids.push_back(part->partId); - part = reinterpret_cast( - reinterpret_cast(part) + kPartRecordStride); + ++part; } } } @@ -1132,9 +940,8 @@ void SkinnedMesh::setGeomIndex(int geom) m_geomIndex = geom; m_lodIndex = 0; - m_lodRecord = reinterpret_cast(geomRecord(m_template, m_geomIndex)->first); - m_lodMaterials = reinterpret_cast( - companionRecord(m_template, m_geomIndex)->first); + m_lodRecord = geomRecord(m_template, m_geomIndex)->lods.data(); + m_lodMaterials = companionRecord(m_template, m_geomIndex)->data(); } // +0x70, 0x101A6810 - `mov eax, [ecx+3Ch]; retn`. @@ -1146,8 +953,8 @@ int SkinnedMesh::getGeomIndex() const // +0x74, how many geoms the template has, out of its 32-byte-strided vector. int SkinnedMesh::getGeomCount() const { - if (m_template->m_loaded && m_template->m_vector0DC.first) - return static_cast((m_template->m_vector0DC.last - m_template->m_vector0DC.first) / 32); + if (m_template->m_loaded && !m_template->m_geoms.empty()) + return static_cast(m_template->m_geoms.size()); return 0; } @@ -1165,30 +972,26 @@ void* SkinnedMesh::setLodIndex(int lod) { m_lodIndex = 0; m_lodExplicit = 0; - m_lodRecord = reinterpret_cast(geomRecord(m_template, m_geomIndex)->first); - m_lodMaterials = reinterpret_cast( - companionRecord(m_template, m_geomIndex)->first); + m_lodRecord = geomRecord(m_template, m_geomIndex)->lods.data(); + m_lodMaterials = companionRecord(m_template, m_geomIndex)->data(); return m_lodMaterials; } - const vc71::vector_layout* const geom = geomRecord(m_template, m_geomIndex); - const unsigned int lodCount = - geom->first ? static_cast((geom->last - geom->first) / kLodRecordStride) : 0u; + std::vector& lods = geomRecord(m_template, m_geomIndex)->lods; + const unsigned int lodCount = static_cast(lods.size()); - if (!geom->first || lod < 0 || static_cast(lod) >= lodCount) + if (lods.empty() || lod < 0 || static_cast(lod) >= lodCount) { // The shipped retry really is a virtual self-dispatch, and now that the table exists it // is written as one. A subclass overriding +0x78 sees the retry, exactly as in retail. - typedef void*(__fastcall * SetLodFn)(void*, void*, int); - return reinterpret_cast(m_vptr[0x78 / sizeof(void*)])(this, 0, -1); + typedef void*(__thiscall * SetLodFn)(void*, int); + return reinterpret_cast(m_vptr[0x78 / 4])(this, -1); } m_lodIndex = lod; m_lodExplicit = 1; - m_lodRecord = reinterpret_cast(geom->first) + kLodRecordStride * lod; - m_lodMaterials = reinterpret_cast( - reinterpret_cast(companionRecord(m_template, m_geomIndex)->first) - + kCompanionStride * lod); + m_lodRecord = lods.data() + lod; + m_lodMaterials = companionRecord(m_template, m_geomIndex)->data() + lod; return m_lodRecord; } @@ -1204,10 +1007,8 @@ int SkinnedMesh::getLodCount() const if (!m_template->m_loaded) return 0; - const vc71::vector_layout* const geom = geomRecord(m_template, m_geomIndex); - if (!geom->first) - return 0; - return static_cast((geom->last - geom->first) / kLodRecordStride); + const std::vector& lods = geomRecord(m_template, m_geomIndex)->lods; + return static_cast(lods.size()); } @@ -1286,13 +1087,14 @@ void* SkinnedMesh::getShadowCasterFrame() // flags "is translucent" below 1.0f. void SkinnedMesh::setTransparency(float alpha) { - *reinterpret_cast(m_objectParameters + (0x510 - 0x360)) = alpha; + m_objectParameters.transparency.value = alpha; // +0x510 } // Refreshes automatic LOD once per frame, selecting the last qualifying distance. // Explicit LODs remain selected until setLodIndex(-1); their frame stamp still advances. +// PE 0x101A7180 void SkinnedMesh::updateLodSelection() { const unsigned int frame = dx9rend::rendererFrameOrdinal(); // base vslot +0x54 @@ -1314,45 +1116,53 @@ void SkinnedMesh::updateLodSelection() else { void* const base = dx9rend::g_rendererBase; - typedef void*(__fastcall * ViewFn)(void*, void*); + typedef void*(__thiscall * ViewFn)(void*); view = reinterpret_cast( - (*reinterpret_cast(base))[0xD4 / sizeof(void*)])(base, 0); + (*reinterpret_cast(base))[0xD4 / 4])(base); } // The current geom's first lod record supplies the radius the distance is biased by. - const vc71::vector_layout* const geom = geomRecord(m_template, m_geomIndex); - unsigned char* const firstLod = reinterpret_cast(geom->first); - if (firstLod[kLodBoundsDirtyOffset]) - meshBoundsFinalize(*reinterpret_cast(firstLod)); - const float radius = *reinterpret_cast(firstLod + kLodBoundsOffset); + SkinnedMeshGeomRecord* const geom = geomRecord(m_template, m_geomIndex); + SkinnedMeshLod* const firstLod = geom->lods.data(); + if (firstLod->bounds.dirty) + meshBoundsFinalize(firstLod->bounds); + const float radius = firstLod->bounds.radius; - typedef float(__fastcall * LodScaleFn)(void*, void*); + typedef float(__thiscall * LodScaleFn)(void*); const float viewLodScale = reinterpret_cast( - (*reinterpret_cast(view))[0x2C / sizeof(void*)])(view, 0); + (*reinterpret_cast(view))[0x2C / 4])(view); +#if defined(__APPLE__) + // [CHOSEN, not recovered] The threshold is spilled; the two scaled distances are not. + const float threshold = bf2x87::store(bf2x87::sub(bf2x87::mul( + bf2x87::wide(viewLodScale), bf2x87::wide(m_distanceToCamera)), bf2x87::wide(radius))); +#else const float threshold = viewLodScale * m_distanceToCamera - radius; - const float rendererScale = rendererLodScaleAt(0x84C) * rendererLodScaleAt(0x8B8); +#endif // The per-lod distances live in the geom record's second vector. - const vc71::vector_layout& distances = geom[1]; - const unsigned int count = - distances.first - ? static_cast((distances.last - distances.first) / sizeof(float)) - : 0u; - const float* const values = reinterpret_cast(distances.first); + const std::vector& distances = geom->distances; + const unsigned int count = static_cast(distances.size()); + const float* const values = distances.data(); unsigned int chosen = 0; for (unsigned int i = 0; i < count; ++i) - if (values[i] * rendererScale < threshold) + { +#if defined(__APPLE__) + if (bf2x87::less(bf2x87::mul(bf2x87::mul(bf2x87::wide(values[i]), + bf2x87::wide(rendererLodScaleAt(0x84C))), bf2x87::wide(rendererLodScaleAt(0x8B8))), + bf2x87::wide(threshold))) +#else + if (values[i] * rendererLodScaleAt(0x84C) * rendererLodScaleAt(0x8B8) < threshold) +#endif chosen = i + 1; + } if (chosen != m_lodIndex) { m_lodIndex = chosen; - m_lodRecord = reinterpret_cast(geom->first) + kLodRecordStride * chosen; - m_lodMaterials = reinterpret_cast( - reinterpret_cast(companionRecord(m_template, m_geomIndex)->first) - + kCompanionStride * chosen); + m_lodRecord = geom->lods.data() + chosen; + m_lodMaterials = companionRecord(m_template, m_geomIndex)->data() + chosen; } } @@ -1361,6 +1171,7 @@ void SkinnedMesh::updateLodSelection() // Missing skeletons use identity; excluded parts use a separate shared transform. // Only geometry zero receives an identity fallback when its palette is empty. +// PE 0x101A7370 void SkinnedMesh::updateBonePalettes() { const unsigned int frame = dx9rend::rendererFrameOrdinal(); @@ -1368,11 +1179,7 @@ void SkinnedMesh::updateBonePalettes() return; m_paletteFrameStamp = frame; - const unsigned int count = - m_lodMaterials && m_lodMaterials->first - ? static_cast((m_lodMaterials->last - m_lodMaterials->first) - / kMaterialStride) - : 0u; + const unsigned int count = static_cast(m_lodMaterials->size()); if (!count) return; @@ -1380,20 +1187,20 @@ void SkinnedMesh::updateBonePalettes() { m_boneCounts[geom] = 0; - const unsigned int vectorOffset = 16 * geom + kLodPartVectorOffset; - unsigned char* part = *reinterpret_cast(m_lodRecord + vectorOffset); + // The lod's part vector `geom` (lod +0x40 + 16 * geom). + const SkinnedMeshPart* part = m_lodRecord->parts[geom].data(); Mat4** palette = &m_bonePalettes[geom][0]; - if (part != *reinterpret_cast(m_lodRecord + vectorOffset + 4)) + if (part != m_lodRecord->parts[geom].data() + m_lodRecord->parts[geom].size()) { do { - const int partId = *reinterpret_cast(part); + const int partId = part->partId; if (m_boneTransforms) { if (m_excludedPart != partId) { - (*palette)->fullMult(*reinterpret_cast(part + 4), + (*palette)->fullMult(part->transform, m_boneTransforms[partId]); // partId << 6 } else @@ -1408,10 +1215,10 @@ void SkinnedMesh::updateBonePalettes() ++m_boneCounts[geom]; ++palette; - part += kPartRecordStride; + ++part; } // The end pointer is RE-read from the object each iteration, not cached. Preserved. - while (part != *reinterpret_cast(m_lodRecord + vectorOffset + 4)); + while (part != m_lodRecord->parts[geom].data() + m_lodRecord->parts[geom].size()); if (m_boneCounts[geom]) continue; @@ -1433,13 +1240,12 @@ void SkinnedMesh::updateBonePalettes() // this on every live instance once the file is in. It recomputes both from the current geom and lod // rather than resetting them, so a selection made earlier survives the load. +// PE 0x101A6FD0 void* SkinnedMesh::refreshSelection() { - const vc71::vector_layout* const geom = geomRecord(m_template, m_geomIndex); - m_lodRecord = reinterpret_cast(geom->first) + kLodRecordStride * m_lodIndex; - m_lodMaterials = reinterpret_cast( - reinterpret_cast(companionRecord(m_template, m_geomIndex)->first) - + kCompanionStride * m_lodIndex); + SkinnedMeshGeomRecord* const geom = geomRecord(m_template, m_geomIndex); + m_lodRecord = geom->lods.data() + m_lodIndex; + m_lodMaterials = companionRecord(m_template, m_geomIndex)->data() + m_lodIndex; return m_lodMaterials; } @@ -1448,6 +1254,7 @@ void* SkinnedMesh::refreshSelection() // Temporarily applies the shadow LOD, then restores it and invalidates the palette stamp. // Both shadow parameters receive the same matrix; only the caster-specific arm commits it. +// PE 0x101A86B0 void SkinnedMesh::drawShadowMap(void* caster, unsigned int, unsigned int, unsigned int, bool alphaPass, unsigned int) { @@ -1456,14 +1263,15 @@ void SkinnedMesh::drawShadowMap(void* caster, unsigned int, unsigned int, unsign return; if (!m_transform) return; - if (alphaPass && !m_lodRecord[129]) + if (alphaPass && !m_lodRecord->hasAlphaTest) // lod +0x81 return; updateLodSelection(); const int shadowLod = skinnedMeshShadowLod(); // LightManager +0x290 - const int currentLod = getLodIndex(); - const int lodCount = getLodCount(); + const int currentLod = viewSlot(this, 0x7C); + const int lodCount = viewSlot(this, 0x80); + typedef void*(__thiscall* SetLodFn)(void*, int); int selected = shadowLod; if (currentLod > shadowLod) { @@ -1474,78 +1282,84 @@ void SkinnedMesh::drawShadowMap(void* caster, unsigned int, unsigned int, unsign int lod = lodCount - 1; if (lod >= shadowLod) lod = shadowLod; - setLodIndex(lod); + reinterpret_cast(m_vptr[0x78 / 4])(this, lod); } updateBonePalettes(); + static dx9rend::QueueProfiler profiler(std::string("SkinnedMeshDrawShadowMap")); + profiler.begin(); + SkinnedMeshShadowState* const state = skinnedMeshShadowState(); dx9rend::vertexDeclarationBind(t->m_vertexDeclaration); // +0xA0 dx9rend::vertexBufferBindStream(t->m_vertexBuffer, 0); // +0x94 dx9rend::indexBufferBind(t->m_indexBuffer); // +0x9C - const unsigned char* const casterBytes = static_cast(caster); - if (casterBytes && casterBytes[0x495]) + // The caster is a LightManager shadow record (XpLightManager.h); the `+0xNN` comments are its + // retail offsets. + const LightShadowRecord* const casterRecord = static_cast(caster); + if (casterRecord && casterRecord->tail494[1]) // +0x495 { - Mat4 light = Mat4::getIdentity(); - light.fullMult(*m_transform, *reinterpret_cast(casterBytes + 0x238)); - Mat4 scratch = Mat4::getIdentity(); - scratch.fullMult(*m_transform, *reinterpret_cast(casterBytes + 0x238)); + Mat4 light; + rendmath::constructIdentity(light); // 0x101A87D6 + geometryRendererMatrixProduct(light, *m_transform, casterRecord->matrices[1]); // +0x238 + Mat4 scratch; + rendmath::constructIdentity(scratch); // 0x101A87F4 + geometryRendererMatrixProduct(scratch, *m_transform, casterRecord->matrices[1]); // +0x238 // `light` is recomputed here; the value above is discarded. Shipped. - light.fullMult(scratch, *reinterpret_cast(casterBytes + 0x278)); + geometryRendererMatrixProduct(light, scratch, casterRecord->matrices[2]); // +0x278 shaderParameterSetValue(state->lightMat, &light, 0); shaderParameterSetValue(state->lightTrapezMat, &light, 0); // the same matrix skinnedMeshEffectCommitChanges(state->effect); } else { - const unsigned char* const own = static_cast(m_dword33C); - Mat4 light = Mat4::getIdentity(); - light.fullMult(*m_transform, *reinterpret_cast(own + 0x238)); - Mat4 trapez = Mat4::getIdentity(); - trapez.fullMult(*m_transform, *reinterpret_cast(own + 0x278)); + const LightShadowRecord* const own = static_cast(m_dword33C); + Mat4 light; + rendmath::constructIdentity(light); // 0x101A885E + geometryRendererMatrixProduct(light, *m_transform, own->matrices[1]); // +0x238 + Mat4 trapez; + rendmath::constructIdentity(trapez); // 0x101A8881 + geometryRendererMatrixProduct(trapez, *m_transform, own->matrices[2]); // +0x278 shaderParameterSetValue(state->lightMat, &light, 0); shaderParameterSetValue(state->lightTrapezMat, &trapez, 0); // No CommitChanges on this arm. } - const unsigned int materials = - m_lodMaterials && m_lodMaterials->first - ? static_cast((m_lodMaterials->last - m_lodMaterials->first) - / kMaterialStride) - : 0u; + const unsigned int materials = static_cast(m_lodMaterials->size()); for (unsigned int i = 0; i < materials; ++i) { - const unsigned char* const material = - reinterpret_cast(m_lodMaterials->first) + kMaterialStride * i; - const bool materialIsAlpha = material[0x18A] != 0; + const SkinnedMeshMaterial& material = m_lodMaterials->data()[i]; + const bool materialIsAlpha = material.isAlpha != 0; // +0x18A if (materialIsAlpha != alphaPass) continue; shaderParameterSetMatrixArray(state->geomBones, m_bonePalettes[i], m_boneCounts[i]); if (materialIsAlpha) { - shaderParameterSetValue(state->texLayer0, - **reinterpret_cast(material + 8), 0); + // The first texture, through the record's texture vector (+0x04, unguarded). + shaderParameterSetValue(state->texLayer0, material.textures.data()[0], 0); } - const unsigned int primitives = *reinterpret_cast(material + 0x20); + const unsigned int primitives = material.primitiveCount; // +0x20 dx9rend::rendererDrawIndexedPrimitive( primitives, t->m_primitiveType, // template +0xAC - *reinterpret_cast(material + 0x18), + static_cast(material.vertexStart), // +0x18 0, - *reinterpret_cast(material + 0x24), - *reinterpret_cast(material + 0x1C)); + material.vertexCount, // +0x24 + material.indexStart); // +0x1C skinnedMeshCountShadowPrimitives(primitives); // renderer stats +0x23C } + dx9rend::QueueProfiler::end(); + if (currentLod != selected) { - setLodIndex(-1); + reinterpret_cast(m_vptr[0x78 / 4])(this, -1); --m_paletteFrameStamp; // forces the next updateBonePalettes to rebuild. Shipped. } } @@ -1553,35 +1367,40 @@ void SkinnedMesh::drawShadowMap(void* caster, unsigned int, unsigned int, unsign // Builds material shader-permutation flags, including this frame's shadow-caster state. -unsigned int SkinnedMesh::buildShaderDefineMask(const unsigned char* material, bool alphaPass, +// PE 0x101A6820 +unsigned int SkinnedMesh::buildShaderDefineMask(const SkinnedMeshMaterial* material, bool alphaPass, unsigned int quality) { unsigned int mask = 0; - if (material[0x188]) + if (material->hasNormalMap) // +0x188 mask = 2; - if (material[0x189]) + if (material->objSpaceNormalMap) // +0x189 mask |= 4u; - if (material[0x18B]) + if (material->hasEnvMap) // +0x18B mask |= 8u; mask |= 0x10u; + std::string name(""); + if (!alphaPass) { - if (refreshAndGetByte334()) // +0xA8 + if (viewSlot(this, 0xA8)) { - if (reinterpret_cast(getShadowCasterFrame()) // +0xB0 - == dx9rend::rendererFrameOrdinal()) + const unsigned int frame = dx9rend::rendererFrameOrdinal(); + // The pointer-typed slot carries a 32-bit frame ordinal. + if (static_cast(reinterpret_cast(viewSlot(this, 0xB0))) + == frame) mask |= 0x40u; } } // The quality refinement is gated on the 0x40 bit just set, so it can only ever apply to a // caster; and on the Renderer's +0xAC predicate being false. - typedef unsigned char(__fastcall * PredFn)(void*, void*); + typedef unsigned char(__thiscall * PredFn)(void*); void* const renderer = dx9rend::g_Renderer; if (quality >= 3 && !reinterpret_cast( - (*reinterpret_cast(renderer))[0xAC / sizeof(void*)])(renderer, 0) + (*reinterpret_cast(renderer))[0xAC / 4])(renderer) && (mask & 0x40u) != 0) mask |= 0x100u; @@ -1592,14 +1411,118 @@ unsigned int SkinnedMesh::buildShaderDefineMask(const unsigned char* material, b } -// [FRONTIER] Terrain-height probes require the shared scratch bank, probe interface, -// and LightManager inputs. This entry stops until those dependencies are implemented. +namespace { + +// PE 0x101069D0, table 0x1021B2B8: this filter excludes the cached root object. +// The remaining slots are getFlags=0 and the two one-argument true predicates. +class SkinnedHeightRootPredicator : public world::ObjectPredicator +{ +public: + bool predicate(world::IObject* object) override + { return staticMeshRootParent(object) != root; } + unsigned int getFlags() const override { return 0; } + bool performCulling(world::IObject*) override { return true; } + bool predicateSurface(int) override { return true; } + void* root; +}; + +// PE 0x101C7E90 / 0x101C7EB0, table 0x10222BD8. CRT 0x101D5EB0 constructs +// the height probe's instance with mask zero; no instruction writes that mask later. +class SkinnedHeightFlagPredicator : public world::ObjectPredicator +{ +public: + SkinnedHeightFlagPredicator() : flags(0) {} + bool predicate(world::IObject* object) override + { return (world::object_detail::LayoutAccess::flags(object) & flags) == flags; } + unsigned int getFlags() const override { return flags; } + bool performCulling(world::IObject*) override { return true; } + bool predicateSurface(int) override { return true; } + unsigned int flags; +}; +SkinnedHeightFlagPredicator skinnedHeightFlags; + +} // anonymous namespace + +// PE 0x101A6A10: the distance the draw stored at +0x344 (`fld dword ptr [ecx+0x344]`). +// unreachable in 1.50: no code or data references. [INFERRED] name. +float SkinnedMesh::getDistanceToCamera() const +{ + return m_distanceToCamera; +} + +// PE 0x101A6D10: shadow-effect light parameters. The base hemi map's texture is kept at +0x160 (0 without +// a map) and its info goes to HemiMapInfo; the sun direction is multiplied by the transposed rotation of +// m_matrix60 (x = m[0]*dx + m[4]*dy + m[8]*dz and so on, w = 1) into SunLightDirection; NormalOffsetScale +// is 2; SkyColor and AmbientColor are the manager's colours packed with w = 1; SunColor is the sky +// light's colour packed with w = 1, or four zeros without a sky light. +// unreachable in 1.50: no code or data references. [INFERRED] name. +void SkinnedMesh::applyShadowLightParameters() +{ + dx9rend::Effect* const effect = skinnedMeshShadowEffect(); + HemiMap* const map = g_HemiMapManager->getBaseHemiMap(); // +0x18 + m_dword160 = 0; + if (map) + { + m_dword160 = static_cast(reinterpret_cast(map->texture)); // HemiMap +0x14 + const std::string name("HemiMapInfo"); + dx9rend::ShaderParameter* const parameter = + dx9rend::effectGetShaderParameterBorrowedTyped(effect, name); + parameter->setValue(&g_HemiMapManager->getHemiMapInfo(map), 0); // +0x1C + } + + float direction4[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; + { + const Vec3 sun = g_LightManager->getSunDirection(); // +0x1A4 + const float* const m = m_matrix60.m; + direction4[0] = (m[8] * sun.z + m[4] * sun.y) + sun.x * m[0]; + direction4[1] = (m[1] * sun.x + m[9] * sun.z) + m[5] * sun.y; + direction4[2] = (m[2] * sun.x + m[10] * sun.z) + m[6] * sun.y; + direction4[3] = 1.0f; + } + { + const std::string name("SunLightDirection"); + dx9rend::effectGetShaderParameterBorrowedTyped(effect, name)->setValue(direction4, 0); + } + { + const std::string name("NormalOffsetScale"); + dx9rend::effectGetShaderParameterBorrowedTyped(effect, name)->setFloat(2.0f); + } + + float sky4[4]; + { + const float* const packed = staticMeshPackVec4(&g_LightManager->getSkyColor().x, 1.0f); // +0x30 + sky4[0] = packed[0]; sky4[1] = packed[1]; sky4[2] = packed[2]; sky4[3] = packed[3]; + } + { + const std::string name("SkyColor"); + dx9rend::effectGetShaderParameterBorrowedTyped(effect, name)->setValue(sky4, 0); + } + float ambient4[4]; + { + const float* const packed = staticMeshPackVec4(&g_LightManager->getAmbientColor().x, 1.0f); // +0x38 + ambient4[0] = packed[0]; ambient4[1] = packed[1]; ambient4[2] = packed[2]; ambient4[3] = packed[3]; + } + { + const std::string name("AmbientColor"); + dx9rend::effectGetShaderParameterBorrowedTyped(effect, name)->setValue(ambient4, 0); + } + + float sunColor4[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; + if (world::LightSource* const sky = g_LightManager->getSkyLight()) // +0x28 + { + const float* const packed = staticMeshPackVec4(&sky->getColor().x, 1.0f); // +0x198 + sunColor4[0] = packed[0]; sunColor4[1] = packed[1]; sunColor4[2] = packed[2]; sunColor4[3] = packed[3]; + } + { + const std::string name("SunColor"); + dx9rend::effectGetShaderParameterBorrowedTyped(effect, name)->setValue(sunColor4, 0); + } +} + +// PE 0x101A6A20. Shared hit buffers persist between probes and between meshes. void SkinnedMesh::updateHeightOverTerrain() { - // These three guards are shipped. The first currently cannot pass because the constructor's - // HeightmapCluster singleton lookup remains omitted, not because retail always stores zero. - // Recovering that separate lookup may expose the named probe frontier below (RW-204). if (!m_heightmapCluster) // +0x54 return; if (!m_ownerObject) // +0x330 @@ -1607,14 +1530,57 @@ void SkinnedMesh::updateHeightOverTerrain() if (!m_template->m_loaded) // the template's +0x4C return; - RD9_FRONTIER("dice::hfe::geom::SkinnedMesh::updateHeightOverTerrain body (PE 0x101A6A20, READ - " - "three ray probes through objectManager (ds:10244AD8) vslot +0x68 " - "against a lazily-zeroed scratch bank behind five bits of ds:10264C44)", 0); + typedef world::IObject* (__thiscall* RootFunction)(void*); + const auto root = [this]() { + return reinterpret_cast(m_vptr[0xA4 / 4])(this); + }; + const auto position = [this]() -> const Vec3& { + return *reinterpret_cast(&m_transform->m[12]); + }; + static Vec3 down = {0.0f, 0.0f, 0.0f}; + static Vec3 up = {0.0f, 0.0f, 0.0f}; + down.y = root()->getVisualBoundingRadius() * -4.0f; + up.y = g_LightManager->getShadowRoofRayLength(); + static Vec3 hitPoint = {0.0f, 0.0f, 0.0f}; + static Vec3 hitNormal = {0.0f, 0.0f, 0.0f}; + static world::IObject* hitObject; + hitObject = 0; + static int hitPart; + static SkinnedHeightRootPredicator rootFilter; + rootFilter.root = root(); + float& height = *reinterpret_cast(&m_dword48); + float& sunHeight = *reinterpret_cast(&m_dword4C); + if (reinterpret_cast(objectManager)->intersectLine( + hitObject, hitPoint, hitNormal, hitPart, position(), down, + &rootFilter, true, false, true, true, 0)) + height = position().y - hitPoint.y; + else + height = root()->getVisualBoundingRadius() * 4.0f; + + const Vec2& fadeRange = g_LightManager->getShadowSunHeightOverFade(); + down.y = -fadeRange.y; + if (reinterpret_cast(objectManager)->intersectLine( + hitObject, hitPoint, hitNormal, hitPart, position(), down, + &skinnedHeightFlags, false, false, true, true, 0)) + sunHeight = position().y - hitPoint.y; + else + sunHeight = fadeRange.y; + + const double difference = static_cast(height) - root()->getVisualBoundingRadius(); + height = static_cast(difference); + if (difference < 0.0) + height = 0.0f; + float radius = root()->getVisualBoundingRadius(); + if (radius < 2.0f) + radius = 2.0f; + height /= radius; + m_byte50 = reinterpret_cast(objectManager)->intersectLine( + hitObject, hitPoint, hitNormal, hitPart, position(), up, + &rootFilter, false, false, false, false, 0); } -// Instance rendering; remaining dependency boundaries retain named stops. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: skinnedmesh-instance] +// PE 0x101A7AF0: instance rendering, including the optional Xp light-association diagnostic. void SkinnedMesh::draw(void*, void*, void*) { // -- 1. the entry gate @@ -1623,7 +1589,7 @@ void SkinnedMesh::draw(void*, void*, void*) // nothing; below 1.0f he is merely flagged translucent and takes a different queue later. if (!rendererFlagAt(0x6A3)) return; - const float transparency = *reinterpret_cast(m_objectParameters + (0x510 - 0x360)); + const float transparency = m_objectParameters.transparency.value; // +0x510 if (transparency < 0.0000099999997f) return; @@ -1649,7 +1615,7 @@ void SkinnedMesh::draw(void*, void*, void*) const float distance = static_cast(std::sqrt(dx * dx + dy * dy + dz * dz)); m_distanceToCamera = distance; // +0x344 // The same value is also written into the Ra block at +0x580, where the shader reads it. - *reinterpret_cast(m_objectParameters + (0x580 - 0x360)) = distance; + *reinterpret_cast(&m_objectParameters.tail220) = distance; updateLodSelection(); @@ -1681,13 +1647,11 @@ void SkinnedMesh::draw(void*, void*, void*) g_LightManager->gatherLightsForGeometry(this, m_lights, static_cast(maxLights), 0x1B09u, 0u, true); // +0x20 - const unsigned int gathered = - m_lights.first - ? static_cast((m_lights.last - m_lights.first) >> 2) : 0u; + const unsigned int gathered = static_cast(m_lights.size()); if (gathered || skinnedMeshRendererMode() == 2) { - if (m_lodRecord[128] && skinnedMeshRendererMode() != 2) + if (m_lodRecord->humanSkin && skinnedMeshRendererMode() != 2) // lod +0x80 skinnedMeshRendererSubmitA(this); skinnedMeshRendererSubmitB(this); } @@ -1721,7 +1685,9 @@ void SkinnedMesh::draw(void*, void*, void*) const float hemiA = g_LightManager->sampleSimpleShadowMap(x, z); const bool below = g_LightManager->sampleSimpleShadowMapIO(x, z) < 0.5f; - float factor; + // The factor stays on the x87 stack as an extended value and is spilled as a double + // (PE 0x101A7D5C), so it is carried as a double here. + double factor; if (m_byte50) { factor = below ? hemiA : 1.0f; @@ -1730,31 +1696,31 @@ void SkinnedMesh::draw(void*, void*, void*) { const Vec2& range = g_LightManager->getShadowSunHeightOverFade(); const float height = *reinterpret_cast(&m_dword4C); - float u = (height - range.x) / (range.y - range.x); - // THE clamp'S result IS discarded. clampFloat returns the clamped value and the - // shipped body ignores it, using the unclamped `u` on the next line. Reproduced: this - // is a real defect in retail, and agents.md says preserve it rather than fix it. - (void)clampFloat(u, 0.0f, 1.0f); - factor = u + (1.0f - u) * hemiA; + const float u = (height - range.x) / (range.y - range.x); + // clampFloat (PE 0x1000ED40) answers in st0 and the next three instructions + // (0x101A7D44..0x101A7D4F) use that clamped value: factor = c + (1 - c) * hemiA. + const double c = clampFloat(u, 0.0f, 1.0f); + factor = c + (1.0 - c) * static_cast(hemiA); } else { - factor = 1.0f; + factor = 1.0; } - hemiFactor = static_cast(std::pow(static_cast(factor), + hemiFactor = static_cast(std::pow(factor, static_cast(g_LightManager->getShadowSunScalePower()))); } // -- 7. ease +0x354 toward the target, over real time // The elapsed time is kept as a double at +0x358 and the divisor is a double at the light // manager's +0x838. Narrowing either to float changes the easing on long sessions. - const double now = rendererTimeSeconds(); + const double now = dx9rend::rendererPostTime(); // the Renderer time const double elapsed = now - m_double358; m_double358 = now; - float t = static_cast(elapsed / lightManagerFadeSeconds()); - if (t > 1.0f) - t = 1.0f; - m_float354 += t * (easeTarget - m_float354); + // t stays a double through the min against 1.0 (the listing compares and multiplies it unrounded). + double t = elapsed / lightManagerFadeSeconds(); + if (t > 1.0) + t = 1.0; + m_float354 = static_cast(m_float354 + t * (static_cast(easeTarget) - m_float354)); // Clear gathered lights while retaining capacity for the next frame. lightVectorResizeToEmpty(m_lights); // sub_100E1C20(0, 0) @@ -1800,15 +1766,13 @@ void SkinnedMesh::draw(void*, void*, void*) } // -- 10. build one 68-byte record per gathered light - const unsigned int lightCount = - m_lights.first ? static_cast((m_lights.last - m_lights.first) >> 2) : 0u; + const unsigned int lightCount = static_cast(m_lights.size()); skinnedMeshReserveLightRecords(this, lightCount); for (unsigned int i = 0; i < lightCount; ++i) { - void* const light = reinterpret_cast(m_lights.first)[i]; - unsigned char* const record = reinterpret_cast(m_lightRecords.first) - + kLightRecordStride * i; + void* const light = m_lights[i]; + dx9rend::Ra::RaLightRecord& record = m_lightRecords[i]; float range = lightSourceOf(light)->getAttenuationRange2(); // +0x190 const world::LightSourceTemplate* const lightTemplate = lightSourceTemplate(light); // +0x144 @@ -1819,9 +1783,9 @@ void SkinnedMesh::draw(void*, void*, void*) // THE receiver IS m_matrix60, which IS fullInvert(*m_transform) - so the light's world // position lands in object space. Settled from the instruction stream (`lea ecx, [esi+60h]` // at 0x101A7F3D), not from the decompiler, which dropped the receiver entirely. - mat4TransformPoint(m_matrix60, &lightSourceOf(light)->getAbsolutePosition().x, // +0x68 - reinterpret_cast(record)); - *reinterpret_cast(record + 0x38) = 1.0f / (range * range); + rendmath::transformPoint(m_matrix60, lightSourceOf(light)->getAbsolutePosition(), // +0x68 + *reinterpret_cast(record.position)); // sub_10079610 + record.invRangeSq = 1.0f / (range * range); // +0x38 const float* const color = &lightSourceOf(light)->getColor().x; // +0x198 float r = color[0], g = color[1], b = color[2]; @@ -1834,35 +1798,33 @@ void SkinnedMesh::draw(void*, void*, void*) g *= m_float354; b *= m_float354; } - *reinterpret_cast(record + 0x18) = r; - *reinterpret_cast(record + 0x1C) = g; - *reinterpret_cast(record + 0x20) = b; + record.color[0] = r; // +0x18 + record.color[1] = g; + record.color[2] = b; } - // Fill the per-object shader parameters. - unsigned char* const ra = m_objectParameters; + // Fill the per-object shader parameters (the instance's +0x360 block; the `+0xNN` comments + // below are retail instance offsets). + dx9rend::Ra::RaObjectParameters& ra = m_objectParameters; // +0x3F4 = world x viewProjection -> WorldViewProjection. - reinterpret_cast(ra + (0x3F4 - 0x360)) + reinterpret_cast(ra.worldViewProjection.value) ->fullMult(*m_transform, *viewSlot(view, 0x84)); // +0x36C = the transform verbatim -> World. The same store StaticMesh.cpp makes. - std::memcpy(ra + (0x36C - 0x360), m_transform->m, sizeof(Mat4)); + std::memcpy(ra.world.value, m_transform->m, sizeof(Mat4)); // +0x518 = the camera's translation through m_matrix60 (= fullInvert(*m_transform)), w = 1 // -> ObjectSpaceCamPos. Settled from `lea ecx, [esi+60h]` at 0x101A801B, not from the // decompiler, which rendered the receiver as an operand. mat4TransformPointVec4(m_matrix60, &viewSlot(view, 0x64)->m[12], - ra + (0x518 - 0x360), 0x3F800000u); - // ObjectSpaceWorldUp retains multiplication by zero to preserve NaN/infinity behavior. + ra.objectSpaceCamPos.value, 0x3F800000u); + // ObjectSpaceWorldUp (+0x574) retains multiplication by zero to preserve NaN/infinity behavior. const float* const inv = m_matrix60.m; - *reinterpret_cast(ra + (0x574 - 0x360)) = (inv[8] + inv[0]) * 0.0f + inv[4]; - *reinterpret_cast(ra + (0x578 - 0x360)) = (inv[9] + inv[1]) * 0.0f + inv[5]; - *reinterpret_cast(ra + (0x57C - 0x360)) = (inv[10] + inv[2]) * 0.0f + inv[6]; + ra.objectSpaceWorldUp.value[0] = (inv[8] + inv[0]) * 0.0f + inv[4]; + ra.objectSpaceWorldUp.value[1] = (inv[9] + inv[1]) * 0.0f + inv[5]; + ra.objectSpaceWorldUp.value[2] = (inv[10] + inv[2]) * 0.0f + inv[6]; const unsigned int materials = - m_lodMaterials && m_lodMaterials->first - ? static_cast((m_lodMaterials->last - m_lodMaterials->first) - / kMaterialStride) - : 0u; + m_lodMaterials ? static_cast(m_lodMaterials->size()) : 0u; // A FOV override marks first-person geometry; otherwise compare roots with the local player. bool firstPerson = true; @@ -1875,12 +1837,12 @@ void SkinnedMesh::draw(void*, void*, void*) if (owner && owner->hasFirstPersonView()) // PE +0x184 { world::IPlayerControlObject* const local = static_cast( - skinnedMeshObjectOf(owner->getVehicle())); // PE +0x44 + staticMeshControlObject(owner->getVehicle())); // PE +0x44 if (local && !local->getNeverDrawAs1p() // +0x144 && !local->isChildSoldierActive()) // +0x140 { world::IPlayerControlObject* const mine = - static_cast(skinnedMeshObjectOf(m_ownerObject)); + static_cast(staticMeshControlObject(m_ownerObject)); if (m_ownerObject && mine && !mine->getNeverDrawAs1p()) { firstPerson = staticMeshRootParent(owner->getVehicle()) @@ -1891,13 +1853,13 @@ void SkinnedMesh::draw(void*, void*, void*) } // +0x558 = the height probe's first output -> HeightOverTerrain. - *reinterpret_cast(ra + (0x558 - 0x360)) = m_dword48; + *reinterpret_cast(&ra.heightOverTerrain.value) = m_dword48; // The shader quality, from IRenderer::getVideoOptions()'s +0x04 with 4. void* const videoOptions = viewSlot(base, 0x74); - typedef unsigned int(__fastcall * OptionFn)(void*, void*, int); + typedef unsigned int(__thiscall * OptionFn)(void*, int); const unsigned int quality = reinterpret_cast( - (*reinterpret_cast(videoOptions))[0x04 / sizeof(void*)])(videoOptions, 0, 4); + (*reinterpret_cast(videoOptions))[0x04 / 4])(videoOptions, 4); // The sky light's direction, carried into object space. float skyDirection[3] = { 0.0f, 0.0f, 0.0f }; @@ -1915,22 +1877,21 @@ void SkinnedMesh::draw(void*, void*, void*) v[0] = here->m[12] - cam->m[12]; v[1] = here->m[13] - cam->m[13]; v[2] = here->m[14] - cam->m[14]; - mat4Normalize(v); + rendmath::normalize(*reinterpret_cast(v)); } - mat4TransformVector(m_matrix60, v, skyDirection); + rendmath::transformVector(m_matrix60, *reinterpret_cast(v), + *reinterpret_cast(skyDirection)); // sub_1007C440 } // -- 13. one queue entry per material, plus one more per gathered light for (unsigned int i = 0; i < materials; ++i) { - unsigned char* const material = - reinterpret_cast(m_lodMaterials->first) + kMaterialStride * i; + SkinnedMeshMaterial& material = m_lodMaterials->data()[i]; - const unsigned int mask = buildShaderDefineMask(material, false, quality); + const unsigned int mask = buildShaderDefineMask(&material, false, quality); // Only the alternate path clamps this index, and it clamps to the LOD index. - unsigned int index = *reinterpret_cast( - reinterpret_cast(dx9rend::g_Renderer) + 0x6CC); + unsigned int index = dx9rend::rendererRaPath(); // Renderer +0x6CC if (rendererFlagAt(0x6D0)) { const unsigned int available = shaderMaskTableSize(); @@ -1941,20 +1902,25 @@ void SkinnedMesh::draw(void*, void*, void*) unsigned int bits = shaderMaskTable()[index] & mask; if ((bits & 0x1Bu) == 0) bits |= 1u; - *reinterpret_cast(material + 0x184) = findShaderForBits(bits); + // Record +0x184, the parameter block's last word. + void*& shaderSlot = raMaterialShaderSlot(skinnedMeshMaterialParameters(material)); + shaderSlot = findShaderForBits(bits); // The shadow matrices, copied out of the +0x33C object - but only while this instance is a // shadow caster on this frame, the same +0xA8/+0xB0 pair buildShaderDefineMask consults. if (refreshAndGetByte334() - && reinterpret_cast(getShadowCasterFrame()) + && static_cast(reinterpret_cast(getShadowCasterFrame())) == dx9rend::rendererFrameOrdinal()) { if (m_dword33C) { - const unsigned char* const caster = static_cast(m_dword33C); - std::memcpy(ra + (0x438 - 0x360), caster + 0x2F8, sizeof(Mat4)); - std::memcpy(ra + (0x4C0 - 0x360), caster + 0x3B8, sizeof(Mat4)); - std::memcpy(ra + (0x47C - 0x360), caster + 0x338, sizeof(Mat4)); + // The +0x33C object is a LightManager shadow record (XpLightManager.h): its + // matrices [4] (+0x2F8), [7] (+0x3B8) and [5] (+0x338). + const LightShadowRecord* const caster = + static_cast(m_dword33C); + std::memcpy(ra.shadowProjMat.value, &caster->matrices[4], sizeof(Mat4)); // +0x438 + std::memcpy(ra.shadowTrapMat.value, &caster->matrices[7], sizeof(Mat4)); // +0x4C0 + std::memcpy(ra.shadowOccProjMat.value, &caster->matrices[5], sizeof(Mat4)); // +0x47C } } @@ -1963,32 +1929,31 @@ void SkinnedMesh::draw(void*, void*, void*) const Vec3& skyColor = g_LightManager->getSkyColor(); // +0x30 if (viewSlot(base, 0xAC)) { - *reinterpret_cast(ra + (0x560 - 0x360)) = ambientScale * skyColor.x; - *reinterpret_cast(ra + (0x564 - 0x360)) = ambientScale * skyColor.y; - *reinterpret_cast(ra + (0x568 - 0x360)) = ambientScale * skyColor.z; + ra.hemiMapSkyColor.value[0] = ambientScale * skyColor.x; // +0x560 + ra.hemiMapSkyColor.value[1] = ambientScale * skyColor.y; + ra.hemiMapSkyColor.value[2] = ambientScale * skyColor.z; } else { - *reinterpret_cast(ra + (0x560 - 0x360)) = skyColor.x; - *reinterpret_cast(ra + (0x564 - 0x360)) = skyColor.y; - *reinterpret_cast(ra + (0x568 - 0x360)) = skyColor.z; + ra.hemiMapSkyColor.value[0] = skyColor.x; + ra.hemiMapSkyColor.value[1] = skyColor.y; + ra.hemiMapSkyColor.value[2] = skyColor.z; } dx9rend::RenderQueueEntry* const entry = dx9rend::renderEntryPoolAcquire(); - entry->material = material; - entry->materialParameters = material + 0x38; - entry->objectParameters = ra; - *reinterpret_cast(reinterpret_cast(entry) + 0x138) = - *reinterpret_cast(material + 0x184); - // +0x4C / +0x50 - this material's bone palette and its count. This is where the skinning - // reaches the shader, and it is why the palettes are per-material rather than per-instance. - *reinterpret_cast(reinterpret_cast(entry) + 0x4C) = - &m_bonePalettes[i][0]; - *reinterpret_cast(reinterpret_cast(entry) + 0x50) = - m_boneCounts[i]; - - unsigned char* const params = - *reinterpret_cast(reinterpret_cast(entry) + 0x128); + entry->material = &material; + entry->materialParameters = material.parameters; // record +0x38 + entry->objectParameters = &ra; + entry->shader = static_cast(shaderSlot); // entry +0x138 + // entry +0x4C / +0x50 (the lighting block's MatBones pair) - this material's bone palette + // and its count. This is where the skinning reaches the shader, and it is why the palettes + // are per-material rather than per-instance. + // A pointer in the holder's first word: RaParamPair must be pointer-sized on x64. + entry->lighting.matBones.a = reinterpret_cast(&m_bonePalettes[i][0]); + entry->lighting.matBones.b = m_boneCounts[i]; + + // entry +0x128, the light-array block's Lights holder: one RaLightRecord. + unsigned char* const params = static_cast(entry->lightArray.lights.value); { const Vec3& sun = g_LightManager->getSunColor(); // +0x1AC float* const dst = reinterpret_cast(params + 24); @@ -2014,35 +1979,27 @@ void SkinnedMesh::draw(void*, void*, void*) // One extra entry per light record, sharing the material but carrying that light's data // and a re-based define mask. - const unsigned int records = - m_lightRecords.first - ? static_cast((m_lightRecords.last - m_lightRecords.first) - / kLightRecordStride) - : 0u; + const unsigned int records = static_cast(m_lightRecords.size()); for (unsigned int l = 0; l < records; ++l) { dx9rend::RenderQueueEntry* const lit = dx9rend::renderEntryPoolAcquire(); - lit->material = material; - lit->materialParameters = material + 0x38; - lit->objectParameters = ra; + lit->material = &material; + lit->materialParameters = material.parameters; + lit->objectParameters = &ra; // THE RE-base IS TWO steps AND THE first ONE IS dead: `bits & 0xFFFFFCBF` is computed // and then its low byte is overwritten by `(bits & 0x3F) | 0x80`. Reproduced as the // shipped pair rather than folded to the value it actually yields. unsigned int rebased = bits & 0xFFFFFCBFu; rebased = (rebased & 0xFFFFFF00u) | ((bits & 0x3Fu) | 0x80u); - *reinterpret_cast(reinterpret_cast(lit) + 0x138) = - findShaderForBits(rebased); + lit->shader = static_cast(findShaderForBits(rebased)); - unsigned char* const litParams = - *reinterpret_cast(reinterpret_cast(lit) + 0x128); - std::memcpy(litParams, reinterpret_cast(m_lightRecords.first) - + kLightRecordStride * l, kLightRecordStride); + std::memcpy(lit->lightArray.lights.value, &m_lightRecords[l], + sizeof(dx9rend::Ra::RaLightRecord)); // both operands are the entry + 8: `lea ecx,[edi+8]` / `lea ecx,[ebx+8]` at - // The payload starts one dword past the entry's own head. - renderQueueEntryCopyPayload(reinterpret_cast(lit) + 8, - reinterpret_cast(entry) + 8); + // The payload starts one dword past the entry's own head: the lighting block. + renderQueueEntryCopyPayload(lit->lighting, entry->lighting); dx9rend::renderQueueEnqueue(lit, translucent, m_fov != -1.0f, true); } } @@ -2064,19 +2021,12 @@ SkinnedMesh::~SkinnedMesh() for (int bone = 0; bone < kSkinnedMeshBonesPerPalette; ++bone) ::renddx9abi::engineFree(m_bonePalettes[palette][bone]); // sub_1005F360, unguarded - if (m_lightRecords.first) - ::renddx9abi::engineFree(m_lightRecords.first); - m_lightRecords.first = 0; - m_lightRecords.last = 0; - m_lightRecords.end = 0; - - ::dice::hfe::dx9rend::Ra::raObjectParametersDestroy(m_objectParameters); + // The light records' storage is released here, in the shipped order. + std::vector().swap(m_lightRecords); - if (m_lights.first) - ::renddx9abi::engineFree(m_lights.first); - m_lights.first = 0; - m_lights.last = 0; - m_lights.end = 0; + // The gathered lights' storage is released here. m_objectParameters (sub_1004D900), which the + // shipped body tears down just before it, is destroyed with the object after this body. + std::vector().swap(m_lights); } @@ -2085,30 +2035,30 @@ SkinnedMesh::~SkinnedMesh() namespace { -int __fastcall skm_addRef(void* self, void*) { return static_cast(self)->addRef(); } -int __fastcall skm_getRef(void* self, void*) { return static_cast(self)->getRef(); } -int __fastcall skm_release(void* self, void*) { return static_cast(self)->release(); } -void* __fastcall skm_queryInterface(void* self, void*, unsigned int iid) +int RD9_THUNK skm_addRef(void* self RD9_THUNK_EDX) { return static_cast(self)->addRef(); } +int RD9_THUNK skm_getRef(void* self RD9_THUNK_EDX) { return static_cast(self)->getRef(); } +int RD9_THUNK skm_release(void* self RD9_THUNK_EDX) { return static_cast(self)->release(); } +void* RD9_THUNK skm_queryInterface(void* self RD9_THUNK_EDX, unsigned int iid) { return static_cast(self)->queryInterface(iid); } -void __fastcall skm_setFov(void* self, void*, float fov) +void RD9_THUNK skm_setFov(void* self RD9_THUNK_EDX, float fov) { return static_cast(self)->setFov(fov); } -float __fastcall skm_getFov(void* self, void*) +float RD9_THUNK skm_getFov(void* self RD9_THUNK_EDX) { return static_cast(self)->getFov(); } -void __fastcall skm_draw(void* self, void*, void* a, void* b, void* c) +void RD9_THUNK skm_draw(void* self RD9_THUNK_EDX, void* a, void* b, void* c) { static_cast(self)->draw(a, b, c); } -void __fastcall skm_drawShadowMap(void* self, void*, void* caster, unsigned int a, +void RD9_THUNK skm_drawShadowMap(void* self RD9_THUNK_EDX, void* caster, unsigned int a, unsigned int b, unsigned int c, bool alphaPass, unsigned int d) { static_cast(self)->drawShadowMap(caster, a, b, c, alphaPass, d); } -void* __fastcall skm_setDword33C(void* self, void*, void* v) +void* RD9_THUNK skm_setDword33C(void* self RD9_THUNK_EDX, void* v) { return static_cast(self)->setDword33C(v); } -void* __fastcall skm_getDword33C(void* self, void*) +void* RD9_THUNK skm_getDword33C(void* self RD9_THUNK_EDX) { return static_cast(self)->getDword33C(); } // +0x34 - the MSVC scalar deleting destructor: run the real one, then free when bit 0 is set. -void* __fastcall skm_scalarDeletingDtor(void* self, void*, unsigned int flags) +void* RD9_THUNK skm_scalarDeletingDtor(void* self RD9_THUNK_EDX, unsigned int flags) { SkinnedMesh* const mesh = static_cast(self); mesh->~SkinnedMesh(); @@ -2117,71 +2067,71 @@ void* __fastcall skm_scalarDeletingDtor(void* self, void*, unsigned int flags) return self; } -void* __fastcall skm_getTemplate(void* self, void*) +void* RD9_THUNK skm_getTemplate(void* self RD9_THUNK_EDX) { return static_cast(self)->getTemplate(); } -const void* __fastcall skm_getLocalBounds(void* self, void*) +const void* RD9_THUNK skm_getLocalBounds(void* self RD9_THUNK_EDX) { return static_cast(self)->getLocalBounds(); } -float __fastcall skm_getBoundingRadius(void* self, void*) +float RD9_THUNK skm_getBoundingRadius(void* self RD9_THUNK_EDX) { return static_cast(self)->getBoundingRadius(); } -const Mat4* __fastcall skm_getGeometryTransformation(void* self, void*) +const Mat4* RD9_THUNK skm_getGeometryTransformation(void* self RD9_THUNK_EDX) { return static_cast(self)->getGeometryTransformation(); } -void __fastcall skm_setGeometryTransformation(void* self, void*, const Mat4* m) +void RD9_THUNK skm_setGeometryTransformation(void* self RD9_THUNK_EDX, const Mat4* m) { static_cast(self)->setGeometryTransformation(m); } -void __fastcall skm_setBoneTransforms(void* self, void*, const Mat4* bones, unsigned int count) +void RD9_THUNK skm_setBoneTransforms(void* self RD9_THUNK_EDX, const Mat4* bones, unsigned int count) { static_cast(self)->setBoneTransforms(bones, count); } -void __fastcall skm_gatherVisibleParts(void* self, void*, HostIntVector* out) +void RD9_THUNK skm_gatherVisibleParts(void* self RD9_THUNK_EDX, HostIntVector* out) { static_cast(self)->gatherVisibleParts(out); } -void __fastcall skm_setExcludedPart(void* self, void*, int part, bool enable) +void RD9_THUNK skm_setExcludedPart(void* self RD9_THUNK_EDX, int part, bool enable) { static_cast(self)->setExcludedPart(part, enable); } -void __fastcall skm_setGeomIndex(void* self, void*, int g) +void RD9_THUNK skm_setGeomIndex(void* self RD9_THUNK_EDX, int g) { static_cast(self)->setGeomIndex(g); } -int __fastcall skm_getGeomIndex(void* self, void*) +int RD9_THUNK skm_getGeomIndex(void* self RD9_THUNK_EDX) { return static_cast(self)->getGeomIndex(); } -int __fastcall skm_getGeomCount(void* self, void*) +int RD9_THUNK skm_getGeomCount(void* self RD9_THUNK_EDX) { return static_cast(self)->getGeomCount(); } -void* __fastcall skm_setLodIndex(void* self, void*, int lod) +void* RD9_THUNK skm_setLodIndex(void* self RD9_THUNK_EDX, int lod) { return static_cast(self)->setLodIndex(lod); } -int __fastcall skm_getLodIndex(void* self, void*) +int RD9_THUNK skm_getLodIndex(void* self RD9_THUNK_EDX) { return static_cast(self)->getLodIndex(); } -int __fastcall skm_getLodCount(void* self, void*) +int RD9_THUNK skm_getLodCount(void* self RD9_THUNK_EDX) { return static_cast(self)->getLodCount(); } -void __fastcall skm_setOwnerObject(void* self, void*, void* o) +void RD9_THUNK skm_setOwnerObject(void* self RD9_THUNK_EDX, void* o) { static_cast(self)->setOwnerObject(o); } -void* __fastcall skm_getOwnerObject(void* self, void*) +void* RD9_THUNK skm_getOwnerObject(void* self RD9_THUNK_EDX) { return static_cast(self)->getOwnerObject(); } -void* __fastcall skm_refreshRootObject(void* self, void*) +void* RD9_THUNK skm_refreshRootObject(void* self RD9_THUNK_EDX) { return static_cast(self)->refreshRootObject(); } -unsigned char __fastcall skm_refreshAndGetByte334(void* self, void*) +unsigned char RD9_THUNK skm_refreshAndGetByte334(void* self RD9_THUNK_EDX) { return static_cast(self)->refreshAndGetByte334(); } -void __fastcall skm_setShadowCasterFrame(void* self, void*, void* f) +void RD9_THUNK skm_setShadowCasterFrame(void* self RD9_THUNK_EDX, void* f) { static_cast(self)->setShadowCasterFrame(f); } -void* __fastcall skm_getShadowCasterFrame(void* self, void*) +void* RD9_THUNK skm_getShadowCasterFrame(void* self RD9_THUNK_EDX) { return static_cast(self)->getShadowCasterFrame(); } -void __fastcall skm_setTransparency(void* self, void*, float a) +void RD9_THUNK skm_setTransparency(void* self RD9_THUNK_EDX, float a) { static_cast(self)->setTransparency(a); } // the shared bodies, each read -void __fastcall skm_empty1(void*, void*, unsigned int) {} -void __fastcall skm_empty2(void*, void*, unsigned int, unsigned int) {} -void __fastcall skm_empty3(void*, void*, unsigned int, unsigned int, +void RD9_THUNK skm_empty1(void* RD9_THUNK_EDX, unsigned int) {} +void RD9_THUNK skm_empty2(void* RD9_THUNK_EDX, unsigned int, unsigned int) {} +void RD9_THUNK skm_empty3(void* RD9_THUNK_EDX, unsigned int, unsigned int, unsigned int) {} -unsigned int __fastcall skm_zero0(void*, void*) { return 0; } -unsigned int __fastcall skm_zero1(void*, void*, unsigned int) { return 0; } -bool __fastcall skm_false0(void*, void*) { return false; } -bool __fastcall skm_false1(void*, void*, unsigned int) { return false; } -int __fastcall skm_minusOne(void*, void*) { return -1; } -int __fastcall skm_seven(void*, void*) { return 7; } -int __fastcall skm_three(void*, void*) { return 3; } +unsigned int RD9_THUNK skm_zero0(void* RD9_THUNK_EDX) { return 0; } +unsigned int RD9_THUNK skm_zero1(void* RD9_THUNK_EDX, unsigned int) { return 0; } +bool RD9_THUNK skm_false0(void* RD9_THUNK_EDX) { return false; } +bool RD9_THUNK skm_false1(void* RD9_THUNK_EDX, unsigned int) { return false; } +int RD9_THUNK skm_minusOne(void* RD9_THUNK_EDX) { return -1; } +int RD9_THUNK skm_seven(void* RD9_THUNK_EDX) { return 7; } +int RD9_THUNK skm_three(void* RD9_THUNK_EDX) { return 3; } // 0x10082D30 - `m_name = value` through MSVCP71's string operator=. Writes +0x04. -void __fastcall skm_setName(void* self, void*, const vc71::string& name) +void RD9_THUNK skm_setName(void* self RD9_THUNK_EDX, const std::string& name) { static_cast(self)->m_name = name; } // 0x10103AD0 - `[ecx+24h] = rendererFrameOrdinal()`. Writes +0x24, valid in both classes. -void __fastcall skm_stampFrameOrdinal(void* self, void*) +void RD9_THUNK skm_stampFrameOrdinal(void* self RD9_THUNK_EDX) { static_cast(self)->m_dword24 = dx9rend::rendererFrameOrdinal(); } } // anonymous namespace diff --git a/Code/BF2/Geom/SkinnedMesh.h b/Code/BF2/Geom/SkinnedMesh.h index 534967401..6c54433fc 100644 --- a/Code/BF2/Geom/SkinnedMesh.h +++ b/Code/BF2/Geom/SkinnedMesh.h @@ -8,29 +8,27 @@ #define BF2_GEOM_SKINNEDMESH_H #include // offsetof - the layout assertions below -#include "../../RendDX9Abi/Vc71String.h" -#include "../../RendDX9Abi/Vc71Vector.h" +#include #include "../Math/Mat4.h" +#include "../RendDX9/Ra/RaShader.h" // RaObjectParameters, RaLightRecord #include "GeometryInstanceData.h" -#if BF2_PLUGIN_ABI_NATIVE #include -#endif namespace dice { namespace hfe { +namespace world { class LightSource; } +namespace dx9rend { class Effect; } namespace geom { -// The host owns the used-bone output vector. Match its STL in native builds and -// the 16-byte VC7.1 vector layout in compatibility builds; the interface stays a pointer. -#if BF2_PLUGIN_ABI_NATIVE +// The host owns the used-bone output vector: the toolset's std::vector; the interface stays a +// pointer. typedef std::vector HostIntVector; -#else -typedef vc71::vector_layout HostIntVector; -#endif class SkinnedMeshTemplate; +struct SkinnedMeshLod; +struct SkinnedMeshMaterial; // The palette geometry is shipped, not chosen: the constructor allocates four runs of twenty-SIX // Mat4 pointers, one 0x40 block each, and sets every matrix to identity twice over - once inside @@ -45,8 +43,8 @@ class SkinnedMesh : public GeometryInstanceData explicit SkinnedMesh(void* objectTemplate); // the IBase quartet, +0x00..+0x0C - // The first three are NOT StaticMesh's. StaticMesh counts at +0x34 and uses 0x10103C00/10/20; - // this class counts at +0x30 and uses 0x101071D0/E0/F0. Different offsets, different bodies - + // The first three are NOT StaticMesh's. This class counts at +0x30 and uses 0x101071D0/E0/F0; + // StaticMesh counts at +0x34 and uses its own three. Different offsets, different bodies - // which is exactly the sanity check that says the two layouts really do diverge here. int addRef(); // +0x00 (shared) int getRef() const; // +0x04 (shared) @@ -124,12 +122,17 @@ class SkinnedMesh : public GeometryInstanceData // and load() only calls it after the read, which is the whole of the shipped protection. void* refreshSelection(); // Three ray probes whose results land in +0x48 / +0x4C / +0x50. - // The body is a named stop. - void updateHeightOverTerrain(); // 0x101A6A20 frontier + // Requires an owner, loaded template and HeightmapCluster singleton. + void updateHeightOverTerrain(); // 0x101A6A20 + // Non-virtual; unreachable in 1.50 (PE 0x101A6A10). [INFERRED] name. + float getDistanceToCamera() const; + // Binds the sun direction (rotated by m_matrix60), sky, ambient and sky-light colours on the shared + // shadow effect; non-virtual, unreachable in 1.50 (PE 0x101A6D10). [INFERRED] name. + void applyShadowLightParameters(); // The per-material shader-permutation mask the main draw stamps into every queue // entry. A __thiscall with three stack arguments - the draw's decompilation drops the // receiver, and the standalone view restores it (it dispatches +0xA8 and +0xB0). - unsigned int buildShaderDefineMask(const unsigned char* material, bool alphaPass, + unsigned int buildShaderDefineMask(const SkinnedMeshMaterial* material, bool alphaPass, unsigned int quality); // the draws @@ -145,16 +148,14 @@ class SkinnedMesh : public GeometryInstanceData // NOT read. It has 104 Mat4 allocations and four vectors to undo, so it is not guessable. ~SkinnedMesh(); // 0x101A7A10 frontier - // data, in shipped order - // +0x000..+0x02F: inherited GeometryInstanceData; all retail offsets remain asserted. + // data, in shipped order; the `+0xNN` comments are the retail offsets + // +0x000..+0x02F: inherited GeometryInstanceData. int m_refCount; // +0x030 ctor 1 StaticMesh keeps its at +0x34 - // +0x034 / +0x038: the current selection, rewritten together by +0x6C and +0x78. The lod - // record is 132 bytes (its +0x1C is the bounding radius, its +0x20 the "bounds dirty" byte, - // its +0x80 a flag the draw reads, and a vector of 68-byte material records starts at its - // +0x44). The companion is itself a vc71 vector, of 456-byte records. - unsigned char* m_lodRecord; // +0x034 ctor 0, then the template gate - vc71::vector_layout* m_lodMaterials; // +0x038 ctor 0, then the template gate + // +0x034 / +0x038: the current selection, rewritten together by +0x6C and +0x78: the + // template's 132-byte lod record and that lod's vector of 456-byte material records. + SkinnedMeshLod* m_lodRecord; // +0x034 ctor 0, then the template gate + std::vector* m_lodMaterials; // +0x038 ctor 0, then the template gate unsigned int m_geomIndex; // +0x03C ctor 0; slots +0x6C / +0x70 unsigned int m_lodIndex; // +0x040 ctor 0; slots +0x78 / +0x7C unsigned char m_lodExplicit; // +0x044 ctor 0; +0x78 sets it, -1 clears it @@ -165,7 +166,7 @@ class SkinnedMesh : public GeometryInstanceData unsigned int m_dword4C; // +0x04C ctor 0 unsigned char m_byte50; // +0x050 ctor 0 unsigned char m_pad051[3]; // +0x051 - void* m_heightmapCluster; // +0x054 ctor 0, and the constructor's last store + void* m_heightmapCluster; // +0x054 borrowed singleton, looked up last SkinnedMeshTemplate* m_template; // +0x058 the constructor's argument const Mat4* m_transform; // +0x05C ctor 0; slots +0x48 / +0x50 @@ -176,10 +177,9 @@ class SkinnedMesh : public GeometryInstanceData unsigned int m_dword160; // +0x160 NOT written by the constructor // +0x164 is a vector, and that is why the constructor "skips" +0x164 and zeroes exactly - // +0x168/+0x16C/+0x170: the allocator word is left alone, the shipped shape this whole tree - // shows. The draw passes `this + 0x164` to XpLightManager's gather and then walks - // (last - first) >> 2 pointers out of it, so the element type is world::LightSource*. - vc71::vector_layout m_lights; // +0x164 alloc UNwritten; first/last/end zeroed + // +0x168/+0x16C/+0x170 in retail. The draw passes `this + 0x164` to XpLightManager's gather and + // then walks (last - first) >> 2 pointers out of it, so the element type is world::LightSource*. + std::vector m_lights; // +0x164 // The skeleton palette the caller hands in. updateBonePalettes indexes it with // `partRecord[0] << 6`, a stride of sizeof(Mat4) - which is what proves the type. const Mat4* m_boneTransforms; // +0x174 ctor 0; slot +0x54 @@ -210,11 +210,10 @@ class SkinnedMesh : public GeometryInstanceData // +0x360 .. +0x583 - raObjectParametersConstruct (0x100458E0), the same 0x224-byte block // StaticMesh embeds at its +0x38 and Terrain.cpp already drives. Its `Transparency` holder is // the +0x510 that slot +0xF4 writes. - unsigned char m_objectParameters[0x224]; // +0x360 + ::dice::hfe::dx9rend::Ra::RaObjectParameters m_objectParameters; // +0x360 - // +0x584: the same unwritten-allocator vector shape again. The draw appends one 68-byte record - // per gathered light here and walks it with (last - first) / 68. - vc71::vector_layout m_lightRecords; // +0x584 alloc UNwritten; first/last/end zeroed + // +0x584: the draw sizes this to one 68-byte record per gathered light. + std::vector< ::dice::hfe::dx9rend::Ra::RaLightRecord> m_lightRecords; // +0x584 unsigned int m_dword594; // +0x594 NOT written by the constructor }; @@ -224,50 +223,7 @@ class SkinnedMesh : public GeometryInstanceData static_assert(offsetof(SkinnedMesh, m_vptr) == 0x000, "m_vptr"); static_assert(offsetof(SkinnedMesh, m_name) == 0x004, "m_name"); -static_assert(offsetof(SkinnedMesh, m_dword20) == 0x020, "m_dword20"); -static_assert(offsetof(SkinnedMesh, m_float28) == 0x028, "m_float28"); -static_assert(offsetof(SkinnedMesh, m_refCount) == 0x030, "m_refCount"); -static_assert(offsetof(SkinnedMesh, m_lodRecord) == 0x034, "m_lodRecord"); -static_assert(offsetof(SkinnedMesh, m_lodMaterials) == 0x038, "m_lodMaterials"); -static_assert(offsetof(SkinnedMesh, m_geomIndex) == 0x03C, "m_geomIndex"); -static_assert(offsetof(SkinnedMesh, m_lodIndex) == 0x040, "m_lodIndex"); -static_assert(offsetof(SkinnedMesh, m_lodExplicit) == 0x044, "m_lodExplicit"); -static_assert(offsetof(SkinnedMesh, m_dword48) == 0x048, "m_dword48"); -static_assert(offsetof(SkinnedMesh, m_dword4C) == 0x04C, "m_dword4C"); -static_assert(offsetof(SkinnedMesh, m_byte50) == 0x050, "m_byte50"); -static_assert(offsetof(SkinnedMesh, m_heightmapCluster) == 0x054, "m_heightmapCluster"); -static_assert(offsetof(SkinnedMesh, m_template) == 0x058, "m_template"); -static_assert(offsetof(SkinnedMesh, m_transform) == 0x05C, "m_transform"); -static_assert(offsetof(SkinnedMesh, m_matrix60) == 0x060, "m_matrix60"); -static_assert(offsetof(SkinnedMesh, m_matrixA0) == 0x0A0, "m_matrixA0"); -static_assert(offsetof(SkinnedMesh, m_matrixE0) == 0x0E0, "m_matrixE0"); -static_assert(offsetof(SkinnedMesh, m_matrix120) == 0x120, "m_matrix120"); -static_assert(offsetof(SkinnedMesh, m_dword160) == 0x160, "m_dword160"); -static_assert(offsetof(SkinnedMesh, m_lights) == 0x164, "m_lights"); -static_assert(offsetof(SkinnedMesh, m_boneTransforms) == 0x174, "m_boneTransforms"); -static_assert(offsetof(SkinnedMesh, m_boneTransformCount) == 0x178, "m_boneTransformCount"); -static_assert(offsetof(SkinnedMesh, m_excludedPart) == 0x17C, "m_excludedPart"); -static_assert(offsetof(SkinnedMesh, m_bonePalettes) == 0x180, "m_bonePalettes"); static_assert(sizeof(((SkinnedMesh*)0)->m_bonePalettes) == 0x1A0, "104 Mat4* = 0x180..0x31F"); -static_assert(offsetof(SkinnedMesh, m_boneCounts) == 0x320, "m_boneCounts"); -static_assert(offsetof(SkinnedMesh, m_ownerObject) == 0x330, "m_ownerObject"); -static_assert(offsetof(SkinnedMesh, m_byte334) == 0x334, "m_byte334"); -static_assert(offsetof(SkinnedMesh, m_shadowCasterFrame) == 0x338, "m_shadowCasterFrame"); -static_assert(offsetof(SkinnedMesh, m_dword33C) == 0x33C, "m_dword33C"); -static_assert(offsetof(SkinnedMesh, m_fov) == 0x340, "m_fov"); -static_assert(offsetof(SkinnedMesh, m_distanceToCamera) == 0x344, "m_distanceToCamera"); -static_assert(offsetof(SkinnedMesh, m_dword348) == 0x348, "m_dword348"); -static_assert(offsetof(SkinnedMesh, m_paletteFrameStamp) == 0x34C, "m_paletteFrameStamp"); -static_assert(offsetof(SkinnedMesh, m_lodFrameStamp) == 0x350, "m_lodFrameStamp"); -static_assert(offsetof(SkinnedMesh, m_float354) == 0x354, "m_float354"); -static_assert(offsetof(SkinnedMesh, m_double358) == 0x358, "m_double358"); -static_assert(offsetof(SkinnedMesh, m_objectParameters) == 0x360, "m_objectParameters"); -static_assert(offsetof(SkinnedMesh, m_lightRecords) == 0x584, "m_lightRecords"); -static_assert(offsetof(SkinnedMesh, m_dword594) == 0x594, "m_dword594"); - -// 0x594 + 4 = 0x598, and SkinnedMeshTemplate::createInstance (0x1010F270) allocates exactly that. -static_assert(sizeof(SkinnedMesh) == 0x598, - "SkinnedMeshTemplate::createInstance (0x1010F270) allocates 0x598"); #endif // the SkinnedMesh technique initialisation. It is what fills the per-quality @@ -281,9 +237,28 @@ void skinnedMeshInitTechniques(); // storage lives beside the draw that reads it. void skinnedMeshInitShadowState(); +// The release half, inlined into the template destructor at PE 0x10110875..0x101108C4: drops one +// reference on each of the four parameters, then on the effect, and forgets the effect (so the +// next skinnedMeshInitShadowState creates it again) only when that was its last reference. The +// parameter globals are not cleared. Called once per destroyed template that had loaded. +void skinnedMeshReleaseShadowState(); + +// Borrows the current shadow effect; initialization and lifetime remain with the templates. +dx9rend::Effect* skinnedMeshShadowEffect(); + // 0x101A7650, called on storage the template already allocated. SkinnedMesh* skinnedMeshConstruct(void* storage, void* objectTemplate); +// SkinnedMeshRenderer (SkinnedMeshRenderer.cpp), as the draw reaches it through the published +// singleton. sub_10123A40 answers the renderer's mode word, which the draw compares against 2. +// sub_10123A50 / sub_10123A90 queue a mesh by its camera distance into the renderer's first and +// third distance-ordered queues; both return at once when the renderer or the mesh is null. +int skinnedMeshRendererMode(); +// Store the render pass's enable byte; the published singleton must exist. +void skinnedMeshRendererSetEnabled(unsigned char enabled); +void skinnedMeshRendererSubmitA(SkinnedMesh* mesh); +void skinnedMeshRendererSubmitB(SkinnedMesh* mesh); + // Primary compatibility table. Keep each thunk's declared stack-argument count. extern void* const g_skinnedMeshVtable[62]; diff --git a/Code/BF2/Geom/SkinnedMeshRenderer.cpp b/Code/BF2/Geom/SkinnedMeshRenderer.cpp index a3ea2131f..be99f0c00 100644 --- a/Code/BF2/Geom/SkinnedMeshRenderer.cpp +++ b/Code/BF2/Geom/SkinnedMeshRenderer.cpp @@ -3,13 +3,24 @@ #ifdef BF2_IMAGE_RENDDX9 +#if !defined(_MSC_VER) +#include "../../RendDX9Abi/NativeVtable.h" +#endif +#include "../../RendDX9Abi/ThunkAbi.h" #include "../../RendDX9Abi/HfeAbi.h" #include "../../RendDX9Abi/ModuleCommon.h" #include "../../RendDX9Abi/BfMemory.h" #include "../../RendDX9Abi/Frontier.h" -#include "../../RendDX9Abi/Vc71String.h" -#include "../../RendDX9Abi/Vc71Map.h" +#include "../../RendDX9Abi/PluginEntry.h" +#include "../Core/ConsoleObjectMacro.h" +#include "../Core/ConsoleObjects.h" +#include "../Core/StringUtil.h" +#include +#include "SkinnedMesh.h" // the submission seams this file defines +#include "../GeomMisc/Debug.h" +#include "../RendDX9/RendDX9Base.h" +#include #include #include @@ -17,62 +28,93 @@ namespace dice { namespace hfe { namespace geom { +extern IBase* g_SkinnedMeshRenderer; // ModuleGeom.cpp, dword_1024B8F8 + // getClassList: sub_100518A0(821015, "dice.hfe.geom.SkinnedMeshRenderer", factory). getSingletonList // { "SkinnedMeshRenderer", &g_SkinnedMeshRenderer, iid 1, classId 821015, flags 2 }. extern const unsigned int CID_SkinnedMeshRenderer = 821015u; extern const unsigned int IID_ISkinnedMeshRenderer = 1u; // IID_IBase - the record really uses 1 -static const unsigned int kSkinnedMeshRendererSize = 0x44u; // factory alloc, 0x100B06D0 +// The retail object is 0x44 bytes (factory alloc, 0x100B06D0); the native one holds std +// containers and is allocated at sizeof. + +// A distance-ordered submission queue: camera distance -> mesh, equal distances after the +// existing ones (multimap insert at the upper bound). The shipped nodes are 0x18 bytes. +typedef std::multimap SkinnedMeshQueue; + +// [INFERRED] enumerator spellings from the printed strings; metadata and moves prove 32 bits. +enum ShaderQuality : int { SQHigh = 0, SQMedium = 1, SQLow = 2 }; -// [CHOSEN] header over the 68-byte object; every offset is named because the class is fully recovered. +// Native containers replace the retail STL layout; offsets below describe the x86 image. struct SkinnedMeshRenderer { + SkinnedMeshRenderer(); + ~SkinnedMeshRenderer(); + void setShaderQuality(ShaderQuality value); + ShaderQuality getShaderQuality() const; + const void** m_vptr; // +0x00 primary vtable (ABI) const void** m_listenerVptr; // +0x04 RenderPathListener subobject vtable (ABI) - void* m_renderPath; // +0x08 set/read by the listener slots + int m_renderPath; // +0x08 listener state; constructor leaves it unwritten int m_refCount; // +0x0C - vc71::map_layout m_map1; // +0x10 - vc71::map_layout m_map2; // +0x1C - vc71::map_layout m_map3; // +0x28 + SkinnedMeshQueue m_map1; // +0x10 the draw's sub_10123A50 queue + SkinnedMeshQueue m_map2; // +0x1C [UNRESOLVED] use; the same 0x18-byte node + SkinnedMeshQueue m_map3; // +0x28 the draw's sub_10123A90 queue unsigned char m_bool; // +0x34 primary slots 4/5 unsigned char m_pad35[3]; int m_dword38; // +0x38 int m_dword3C; // +0x3C [UNRESOLVED] - ctor does not write it - int m_dword40; // +0x40 + int m_dword40; // +0x40 shaderQuality }; +// PE 0x10123A30 (the getter, 0x10123A40, is skinnedMeshRendererMode's read). [INFERRED] member +// names; the console supplies the type. +void SkinnedMeshRenderer::setShaderQuality(ShaderQuality value) +{ + m_dword40 = static_cast(value); +} + +ShaderQuality SkinnedMeshRenderer::getShaderQuality() const +{ + return static_cast(m_dword40); +} + namespace { // primary vtable (0x1021C928, 6 slots) - refcount at +0x0C -int __fastcall skm_addRef(void* self, void*) { return ++static_cast(self)->m_refCount; } -int __fastcall skm_getRc (void* self, void*) { return static_cast(self)->m_refCount; } -int __fastcall skm_release(void* self, void*); +int RD9_THUNK skm_addRef(void* self RD9_THUNK_EDX) { return ++static_cast(self)->m_refCount; } +int RD9_THUNK skm_getRc (void* self RD9_THUNK_EDX) { return static_cast(self)->m_refCount; } +int RD9_THUNK skm_release(void* self RD9_THUNK_EDX); // queryInterface (0x10025930): iid 1 only. -void* __fastcall skm_qi(void* self, void*, unsigned int iid) { return (iid == RD9_IID_IBASE) ? self : 0; } -// +0x10 setBool([+0x34]), +0x14 getBool. -void __fastcall skm_setBool(void* self, void*, int v) { static_cast(self)->m_bool = static_cast(v); } -int __fastcall skm_getBool(void* self, void*) { return static_cast(self)->m_bool; } +void* RD9_THUNK skm_qi(void* self RD9_THUNK_EDX, unsigned int iid) { return (iid == RD9_IID_IBASE) ? self : 0; } +// PE 0x101240A0: +0x10 copies the argument's low byte to +0x34 (retn 4). +void RD9_THUNK skm_setBool(void* self RD9_THUNK_EDX, unsigned char v) { static_cast(self)->m_bool = v; } +// PE 0x101240B0: +0x14 returns the stored byte in al. +unsigned char RD9_THUNK skm_getBool(void* self RD9_THUNK_EDX) { return static_cast(self)->m_bool; } // secondary vtable (0x1021C910, RenderPathListener, 6 slots). `self` is the subobject pointer at -// object+0x04, so the object is `self - 4` and the render-path back-pointer is object+0x08. +// object+0x04, so the object is `self - 4` and the integer render path is object+0x08. inline SkinnedMeshRenderer* objOfListener(void* self) { - return reinterpret_cast(reinterpret_cast(self) - 4); + return reinterpret_cast( + reinterpret_cast(self) - offsetof(SkinnedMeshRenderer, m_listenerVptr)); } -void __fastcall skm_setRenderPath(void* self, void*, void* path) { objOfListener(self)->m_renderPath = path; } -void* __fastcall skm_getRenderPath(void* self, void*) { return objOfListener(self)->m_renderPath; } -void __fastcall skm_lisNull1(void*, void*) { } // +0x04 nullsub_15 -void __fastcall skm_lisNull2(void*, void*, int) { } // +0x08 nullsub_53 -// +0x0C: the shipped "This path is invalid" error emitter (SkinnedMeshRenderer.cpp:29). Reproduced as -// a one-line diagnostic rather than the full dice error machinery. -void __fastcall skm_lisPathInvalid(void*, void*, void*) +// PE 0x101C43C0 / 0x101A9A10: store/read the listener's +4 dword. +void RD9_THUNK skm_setRenderPath(void* self RD9_THUNK_EDX, int path) { objOfListener(self)->m_renderPath = path; } +int RD9_THUNK skm_getRenderPath(void* self RD9_THUNK_EDX) { return objOfListener(self)->m_renderPath; } +void RD9_THUNK skm_lisNull1(void* RD9_THUNK_EDX) { } // +0x04 nullsub_15 +void RD9_THUNK skm_lisNull2(void* RD9_THUNK_EDX, int) { } // +0x08 nullsub_53 +// PE 0x101239B0. The path word is unused; type 7 retains the error-alias policy. +void RD9_THUNK skm_lisPathInvalid(void* RD9_THUNK_EDX, int) { - ::renddx9abi::logf("SkinnedMeshRenderer.cpp:29: This path is invalid"); + ::renddx9abi::Debug(DebugTypeError2, + "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\SkinnedMeshRenderer.cpp", 29, "") + << "This path is invalid"; } -// +0x14 getRenderPathListenerName -> returns "SkinnedMeshRenderer" by value (hidden out-pointer). -void* __fastcall skm_lisGetName(void*, void*, void* out) +// PE 0x10124080. Returns the listener name by value through the compatibility output pointer. +void* RD9_THUNK skm_lisGetName(void* RD9_THUNK_EDX, void* out) { - new (out) vc71::string("SkinnedMeshRenderer"); + new (out) std::string("SkinnedMeshRenderer"); return out; } @@ -88,25 +130,32 @@ const void* const kPrimaryVtable[6] = const void* const kListenerVtable[6] = { +#if !defined(_MSC_VER) + // [CHOSEN, not recovered] Let the compiler supply native integer and string returns. + BF2_NATIVE_SLOT(dx9rend::RenderPathListener, onRenderPathActivated, skm_setRenderPath), + BF2_NATIVE_SLOT(dx9rend::RenderPathListener, onRenderPathDeactivated, skm_lisNull1), + BF2_NATIVE_SLOT(dx9rend::RenderPathListener, onRenderPathChanged, skm_lisNull2), + BF2_NATIVE_SLOT(dx9rend::RenderPathListener, onRenderPathNotification, skm_lisPathInvalid), + BF2_NATIVE_SLOT(dx9rend::RenderPathListener, getCurrentRenderPath, skm_getRenderPath), + BF2_NATIVE_SLOT(dx9rend::RenderPathListener, getRenderPathListenerName, skm_lisGetName), +#else reinterpret_cast(&skm_setRenderPath), // +0x00 reinterpret_cast(&skm_lisNull1), // +0x04 nullsub reinterpret_cast(&skm_lisNull2), // +0x08 nullsub reinterpret_cast(&skm_lisPathInvalid), // +0x0C "This path is invalid" reinterpret_cast(&skm_getRenderPath), // +0x10 getRenderPath (inherited shape) reinterpret_cast(&skm_lisGetName), // +0x14 getName +#endif }; -int __fastcall skm_release(void* self, void*) +// PE 0x101240C0. Preserve the decremented result across destruction and freeing. +int RD9_THUNK skm_release(void* self RD9_THUNK_EDX) { SkinnedMeshRenderer* p = static_cast(self); const int remaining = --p->m_refCount; if (remaining == 0) { - // Match the shipped dtor's observable teardown: free the three map head-nodes, then the object. - vc71::map_node* h; - h = p->m_map3.head; if (h) ::renddx9abi::engineFree(h); - h = p->m_map2.head; if (h) ::renddx9abi::engineFree(h); - h = p->m_map1.head; if (h) ::renddx9abi::engineFree(h); + p->~SkinnedMeshRenderer(); ::renddx9abi::engineFree(self); } return remaining; @@ -114,46 +163,190 @@ int __fastcall skm_release(void* self, void*) } // anonymous namespace -// geom_SkinnedMeshRenderer_ctor, 0x10123B80. Faithful except the render-path registration. -// [FRONTIER] dice::hfe::dx9rend::RendDX9_registerRenderPathListener - the listener-list layout is -// unread (same frontier RoadCompiledRenderer defers). The object is fully built; it is simply not -// yet spliced into the render-path list, so its listener slots are not driven by that list. -namespace { -void constructSkinnedMeshRenderer(SkinnedMeshRenderer* self) -{ - self->m_vptr = const_cast(kPrimaryVtable); - self->m_listenerVptr = const_cast(kListenerVtable); - self->m_renderPath = 0; - self->m_refCount = 1; - self->m_map1.construct(0x18); // sub_10123C60 - 0x18-byte RB head nodes - self->m_map2.construct(0x18); - self->m_map3.construct(0x18); - self->m_bool = 1; - self->m_pad35[0] = 0; self->m_pad35[1] = 0; self->m_pad35[2] = 0; - self->m_dword38 = 0; - self->m_dword3C = 0; - self->m_dword40 = 0; +// PE 0x10123B80. Tables/refcount precede the three queues; registration follows the tail stores. +SkinnedMeshRenderer::SkinnedMeshRenderer() + : m_vptr(const_cast(kPrimaryVtable)), + m_listenerVptr(const_cast(kListenerVtable)), + m_refCount(1), m_bool(1), m_dword38(0), m_dword40(0) +{ + dx9rend::registerRenderPathListener(static_cast(&m_listenerVptr)); +} + +// PE 0x10123AD0. Restore both tables, unregister, then destroy queues 3, 2 and 1. +SkinnedMeshRenderer::~SkinnedMeshRenderer() +{ + m_vptr = const_cast(kPrimaryVtable); + m_listenerVptr = const_cast(kListenerVtable); + dx9rend::unregisterRenderPathListener(static_cast(&m_listenerVptr)); } -} // anonymous namespace // RefFactory_geom_SkinnedMeshRenderer, 0x100B06D0. IBase* __fastcall createSkinnedMeshRenderer(unsigned int iid, IBase* outer) { if (outer) return 0; - void* storage = ::renddx9abi::engineAlloc(kSkinnedMeshRendererSize); - if (!storage) - return 0; - ::memset(storage, 0, kSkinnedMeshRendererSize); - SkinnedMeshRenderer* self = static_cast(storage); - constructSkinnedMeshRenderer(self); + void* storage = ::renddx9abi::engineAlloc(sizeof(SkinnedMeshRenderer)); + SkinnedMeshRenderer* const self = storage ? ::new (storage) SkinnedMeshRenderer : 0; - void* itf = skm_qi(self, 0, iid); + // Shipped defect: allocation failure still enters virtual queryInterface through null. + IBase* const instance = reinterpret_cast(self); + void* itf = instance->queryInterface(iid); if (!itf) - skm_release(self, 0); + instance->release(); return static_cast(itf); } +// Native draw facade for the published renderer's shader-quality getter. +int skinnedMeshRendererMode() +{ + return static_cast(reinterpret_cast( + g_SkinnedMeshRenderer)->getShaderQuality()); +} + +// PE 0x101240A0, primary +0x10. Renderer checks the singleton before this call. +void skinnedMeshRendererSetEnabled(unsigned char enabled) +{ + skm_setBool(g_SkinnedMeshRenderer RD9_THUNK_ARG, enabled); +} + +// sub_10123A50 / sub_10123A90 - insert the mesh by its camera distance into the renderer's +0x10 / +// +0x28 queue. +void skinnedMeshRendererSubmitA(SkinnedMesh* mesh) +{ + if (!g_SkinnedMeshRenderer || !mesh) + return; + reinterpret_cast(g_SkinnedMeshRenderer)->m_map1.insert( + SkinnedMeshQueue::value_type(mesh->m_distanceToCamera, mesh)); +} + +// PE 0x10123A90 +void skinnedMeshRendererSubmitB(SkinnedMesh* mesh) +{ + // PE 0x101A6A10, camera-distance accessor expanded here. + const float distance = mesh->m_distanceToCamera; + reinterpret_cast(g_SkinnedMeshRenderer)->m_map3.insert( + SkinnedMeshQueue::value_type(distance, mesh)); +} + +namespace { + +const char kSkinnedMeshRendererConsoleTag[] = "geom.skinnedMeshRenderer"; + +// PE 0x100B0D77: do not substitute the published global for the named singleton lookup. +SkinnedMeshRenderer* consoleSkinnedMeshRenderer() +{ + IBase* const found = classManager->getSingleton(::renddx9abi::HostString("SkinnedMeshRenderer")); + return static_cast(static_cast(found)); +} + +// PE 0x100B0F53. Unrecognised stored values write no text. +std::ostream& __fastcall operator<<(std::ostream& out, ShaderQuality value) +{ + switch (value) + { + case SQHigh: out << "SQHigh"; break; + case SQMedium: out << "SQMedium"; break; + case SQLow: out << "SQLow"; break; + } + return out; +} + +// PE 0x100B1494. Substring matches precede numeric aliases; unknown tokens select High. +std::istream& __fastcall operator>>(std::istream& in, ShaderQuality& value) +{ + std::string token; + in >> token; + if (lowerCaseFind(token, "High") != std::string::npos || token == "0") + value = SQHigh; + else if (lowerCaseFind(token, "Medium") != std::string::npos || token == "1") + value = SQMedium; + else if (lowerCaseFind(token, "Low") != std::string::npos || token == "2") + value = SQLow; + else + value = SQHigh; + return in; +} + +BF2_CONSOLE_OBJECT("SkinnedMeshRenderer", 2, 0) + +// getReturnValueAsString is empty unless a result is present, otherwise the enum streamed through +// the ShaderQuality inserter 0x100B0F53. +class SkinnedMeshShaderQualityBinding : public ConsoleObjectBaseImpl +{ +public: + // PE 0x100BB3B8: binding constructor. + SkinnedMeshShaderQualityBinding() + { + m_objectName = consoleDefaultName(); + m_access = consoleDefaultAccess(); + m_category = consoleDefaultCategory(); + m_functionName = "shaderQuality"; + m_type = 1; + m_minNoArgs = 0; + m_maxNoArgs = 1; + m_returnType = "ShaderQuality"; + m_hasReturnValue = false; + m_isDynamic = true; + m_argTypes[0] = "ShaderQuality"; + m_argNeedsConversion[0] = -1; + consoleBindingList(kSkinnedMeshRendererConsoleTag).push_back(this); + } + virtual bool isObjectActive() const { return consoleSkinnedMeshRenderer() != 0; } + // PE 0x100BB435 + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = consoleSkinnedMeshRenderer()->getShaderQuality(); + } + else if (m_argCount == 1) + { + const ShaderQuality value = BF2_CC_ARG(ShaderQuality, 0); + m_hasReturnValue = false; + consoleSkinnedMeshRenderer()->setShaderQuality(value); + } + } + // PE 0x100BB4D5 + virtual void setArgFromString(int index, const std::string& value) + { + if (index == 1) + { + static ShaderQuality parsed = SQHigh; + std::istringstream in(value); + // The retail operator assigns High even when token extraction fails. + in >> parsed; + m_args[0] = reinterpret_cast(&parsed); + } + } + // PE 0x100BB47D + virtual std::string getReturnValueAsString() const + { + if (!m_hasReturnValue) + return std::string(); + std::ostringstream out; + out << m_returnValue; + return out.str(); + } + BF2_CC_COMMON_HOOKS +private: + ShaderQuality m_returnValue; +}; + +SkinnedMeshShaderQualityBinding s_skinnedMeshShaderQualityBinding; + +} // anonymous namespace + +bool registerSkinnedMeshRendererConsoleObjects() +{ + return mainConsoleObjects->registerConsoleObjects(consoleBindingList(kSkinnedMeshRendererConsoleTag)); +} + +bool unregisterSkinnedMeshRendererConsoleObjects() +{ + return mainConsoleObjects->unregisterConsoleObjects(consoleBindingList(kSkinnedMeshRendererConsoleTag)); +} + } // namespace geom } // namespace hfe } // namespace dice diff --git a/Code/BF2/Geom/SkinnedMeshTemplate.cpp b/Code/BF2/Geom/SkinnedMeshTemplate.cpp index 933daf80d..c1b447733 100644 --- a/Code/BF2/Geom/SkinnedMeshTemplate.cpp +++ b/Code/BF2/Geom/SkinnedMeshTemplate.cpp @@ -3,11 +3,10 @@ #ifdef BF2_IMAGE_RENDDX9 +#include "../../RendDX9Abi/ThunkAbi.h" #include "../../RendDX9Abi/HfeAbi.h" #include "../../RendDX9Abi/BfMemory.h" #include "../../RendDX9Abi/Frontier.h" -#include "../../RendDX9Abi/Vc71Vector.h" -#include "../../RendDX9Abi/Vc71Map.h" #include "../../RendDX9Abi/EngineFile.h" // the file manager seams and logf #include "../../RendDX9Abi/PluginEntry.h" // dice::hfe::fileManager #include "../../RendDX9Abi/HostFileAbi.h" // HostFileManager / HostStream / makeHostString @@ -16,55 +15,46 @@ #include "../RendDX9/RendDX9Base.h" // resourceManagerIsReady #include "SkinnedMesh.h" // the 0x598 instance this factory builds #include "SkinnedMeshTemplate.h" +#include "../GeomMisc/Debug.h" #include +#include +#include #include +#include +#include +#include namespace dice { namespace hfe { namespace dx9rend { +namespace Ra { +void raMaterialParametersCopyConstruct(void* storage, const void* source); +} // sub_10017E00 on dword_1023B974 - declared per-TU, as StaticMeshStateManager.cpp and // StaticMesh.cpp both do; the texture manager publishes no header for it. int textureManagerSwapDefaultMipClass(int value); -// The Renderer console object - its +0x6CC is the shader-quality index the texture gate reads. -extern IBase* g_Renderer; +// BufferManager.cpp - the wrapper fields (+0x08 D3D object, +0x28 stride). +unsigned int vertexBufferStride(void* wrapper); +unsigned int vertexBufferByteSize(void* wrapper); +IDirect3DVertexBuffer9* vertexBufferD3D(void* wrapper); +IDirect3DIndexBuffer9* indexBufferD3D(void* wrapper); } // namespace dx9rend namespace geom { -namespace { - -// the std::set header node. byte-identical to StaticMeshTemplate.cpp's 0x1011B6F0: -// MSVC instantiated the same allocator once per translation unit, which is why the two addresses -// differ and the two bodies do not. +void* const* materialDestroyedVtable(); // BundledMeshMaterial.cpp, shared abstract material table -// The shipped guards are lopsided and are preserved: the three link stores are each guarded on -// the allocation succeeding, the two flag bytes are NOT. A failed allocation therefore faults here -// in retail too - and the caller's own `head->isNil = 1` faults as well. -vc71::set_node* setConstructHead() -{ - vc71::set_node* node = - static_cast(::renddx9abi::engineAlloc(sizeof(vc71::set_node))); - if (node) - node->left = 0; - if (node) - node->parent = 0; - if (node) - node->right = 0; - node->color = 1; - node->isNil = 0; - return node; -} +namespace { -// Tracks live instances in a compatibility set that preserves surviving node addresses. -// Pointer keys rely on the 32-bit target; this representation is not portable to 64 bits. -void instanceSetInsert(vc71::set_layout& set, void* instance) +// Tracks live instances in the set RendDX9/BF2Render.cpp's setLods also walks. +void instanceSetInsert(std::set& set, SkinnedMesh* instance) { // The shipped insert returns pair through a hidden slot; every caller in the // image discards it, and so does this one. - static_cast(set.insert(reinterpret_cast(instance))); + static_cast(set.insert(instance)); } } // namespace @@ -72,10 +62,9 @@ void instanceSetInsert(vc71::set_layout& set, void* instance) // Removes the instance from the unique-key set; does nothing when absent. -void instanceSetErase(vc71::set_layout& set, void* instance) +void instanceSetErase(std::set& set, SkinnedMesh* instance) { - if (vc71::set_node* const node = set.find(reinterpret_cast(instance))) - set.erase(node); + set.erase(instance); } @@ -87,7 +76,7 @@ IBase* __fastcall createSkinnedMeshTemplate(unsigned int iid, IBase* outer) if (outer) return 0; - void* storage = ::renddx9abi::engineAlloc(0x10C); + void* storage = ::renddx9abi::engineAlloc(sizeof(SkinnedMeshTemplate)); SkinnedMeshTemplate* self = 0; if (storage) self = new (storage) SkinnedMeshTemplate(); @@ -99,35 +88,70 @@ IBase* __fastcall createSkinnedMeshTemplate(unsigned int iid, IBase* outer) } -// Initializes derived state after MeshTemplate and clears the keep byte last. -// Vector allocator words and padding at +0xED..+0xFB remain untouched. - +// Initializes derived state after MeshTemplate and clears the keep byte last. The material table +// (+0xCC) and the geom table (+0xDC) are constructed as members. +// Padding at +0xED..+0xFB remains untouched. +// PE 0x101106B0 SkinnedMeshTemplate::SkinnedMeshTemplate() : MeshTemplate() + , m_refCount(1) + , m_byte0EC(0) + , m_byte0FC(0) { - m_refCount = 1; // +0xC8 + // The instance set (0x101117A0's header node, retail +0x100) is constructed as a member. - m_vector0CC.first = 0; // +0xD0 .. +0xD8; the allocator word is NOT written - m_vector0CC.last = 0; - m_vector0CC.end = 0; + m_keepData = 0; // +0x04, and the constructor's last store +} - m_vector0DC.first = 0; // +0xE0 .. +0xE8; ditto - m_vector0DC.last = 0; - m_vector0DC.end = 0; - m_byte0EC = 0; // +0xEC - m_byte0FC = 0; // +0xFC +// PE 0x10110740. Only a loaded template (+0x4C) holds texture and shadow-state references: +// per geom, the lod count comes from the +0x50 vector and each lod's materials are walked, every +// non-null texture losing one reference (dtor and free at zero). Then the shadow state, then the +// members: the instance set, the geom table, the material table, the MeshTemplate members. +void SkinnedMeshTemplate::destroyMembers() +{ + if (m_loaded) + { + const unsigned int geomCount = static_cast(m_lodCounts.size()); + for (unsigned int geom = 0; geom < geomCount; ++geom) + { + const unsigned int lodCount = static_cast(m_lodCounts[geom]); + for (unsigned int lod = 0; lod < lodCount; ++lod) + { + LodMaterials& materials = m_materials[geom][lod]; + for (std::size_t m = 0; m < materials.size(); ++m) + { + std::vector< ::dice::hfe::dx9rend::EngineTexture*>& textures = + materials[m].textures; + for (std::size_t t = 0; t < textures.size(); ++t) + { + ::dice::hfe::dx9rend::EngineTexture* const texture = textures[t]; + if (texture && --texture->refCount == 0) + { + ::dice::hfe::dx9rend::textureDtor(texture); // sub_10014E20 + ::renddx9abi::engineFree(texture); + } + } + } + } + } + skinnedMeshReleaseShadowState(); // 0x10110875..0x101108C4 + } - // 0x101117A0 on the set, then the header node becomes the nil sentinel and self-links three - // ways. The comparator word at +0x100 is never written, exactly as shipped. - m_instances.head = setConstructHead(); - m_instances.head->isNil = 1; - m_instances.head->parent = m_instances.head; - m_instances.head->left = m_instances.head; - m_instances.head->right = m_instances.head; - m_instances.size = 0; + typedef std::set InstanceSet; + m_instances.~InstanceSet(); // 0x101108CA, +0x100 + m_geoms.~GeomTable(); // sub_10114FD0, +0xDC + m_materials.~MaterialTable(); // sub_10114DE0, +0xCC + MeshTemplate::destroyMembers(); // sub_101925C0 +} - m_keepData = 0; // +0x04, and the constructor's last store +// PE 0x101157F0, slot +0xB0. +void* SkinnedMeshTemplate::destroy(unsigned char flags) +{ + destroyMembers(); + if ((flags & 1) != 0) + ::renddx9abi::engineFree(this); + return this; } @@ -166,333 +190,89 @@ void* SkinnedMeshTemplate::queryInterface(unsigned int iid) const } -// The five helpers readMaterials drives that this tree does not carry. Each is one named seam so the -// body above reads as the shipped sequence. [FRONTIER] [RETIRE-WHEN: skinnedmesh-instance] +// Local material-table storage, LOD metadata and renderer-setting helpers. namespace { -// Destroys a material-map subtree; the 20-byte POD values own no resources. -// The companion material vectors are nested by geometry, LOD and material. -// [CHOSEN, not recovered] VC7.1 tree traversal preserves keys, values and sentinel links. -// [RETIRE-WHEN: RW-74] Replace the traversal when the original allocation/erase helpers are -// implemented and their node ownership and observable tree behavior are verified. -void materialMapDestroySubtree(vc71::map_node_u32* node) +// MeshTemplate's per-geom vectors - +0x50 lod counts, +0x60 lod distances, +0x70 skipped lods. +template +unsigned int meshGeomCount(const std::vector& v) { - while (node && !node->isNil) - { - materialMapDestroySubtree(node->right); - vc71::map_node_u32* const left = node->left; - ::renddx9abi::engineFree(node); - node = left; - } + return static_cast(v.size()); } -void materialMapClear(vc71::map_layout& map) // sub_10049900, fast arm +template +T& meshGeomInt(std::vector& v, unsigned int geom) { - if (!map.head) - return; - vc71::map_node_u32* const head = reinterpret_cast(map.head); - materialMapDestroySubtree(head->parent); - head->parent = head; - head->left = head; - head->right = head; - map.size = 0; + return v.data()[geom]; } -vc71::map_node_u32* materialMapCopySubtree(vc71::map_node_u32* head, - const vc71::map_node_u32* source, - vc71::map_node_u32* parent) +// The source lod distances of `geom` and their count; null and 0 when the table has no such geom. +template +const float* meshLodDistances(const std::vector& v, unsigned int geom, int& count) { - if (!source || source->isNil) - return head; // a nil child points at the sentinel, as shipped - - vc71::map_node_u32* const node = static_cast( - ::renddx9abi::engineAlloc(sizeof(vc71::map_node_u32))); - if (!node) - return head; - - std::memcpy(node, source, sizeof(vc71::map_node_u32)); // key, value and colour - node->parent = parent; - node->left = materialMapCopySubtree(head, source->left, node); - node->right = materialMapCopySubtree(head, source->right, node); - return node; -} - -void materialMapCopy(vc71::map_layout& destination, const vc71::map_layout& source) -{ - if (!destination.head || !source.head) - return; - vc71::map_node_u32* const head = - reinterpret_cast(destination.head); - const vc71::map_node_u32* const sourceHead = - reinterpret_cast(source.head); - - head->parent = materialMapCopySubtree(head, sourceHead->parent, head); - destination.size = source.size; - - // The leftmost/rightmost links are RE-derived by walking the new tree, not copied. - if (head->parent->isNil) - { - head->left = head; - head->right = head; - return; - } - vc71::map_node_u32* node = head->parent; - while (!node->left->isNil) - node = node->left; - head->left = node; - - node = head->parent; - while (!node->right->isNil) - node = node->right; - head->right = node; + count = 0; + if (v.size() <= geom) + return 0; + count = static_cast(v[geom].size()); + return v[geom].data(); } // g_Renderer + 0x7E4 - the renderer-level lod-skip setting readLods clamps against. // StaticMeshTemplate.cpp carries the same read as `rendererLodSkipBase`, file-local. int skinnedMeshLodSkipBase() { - return *reinterpret_cast( - reinterpret_cast(dx9rend::g_Renderer) + 2020); + return dx9rend::rendererTailInt(0x7E4); } -// Forward declaration: vectorResizeRaw is defined further down this file. -void vectorResizeRaw(vc71::vector_layout& v, unsigned int count, unsigned int elemSize, - const void* prototype); - // sub_10112CF0 - resize a vector of 68-byte bone-matrix records. \u2605 THE prototype IS AN identity // matrix AT offset +0x04, not +0x00: the shipped builder stores 1.0f to +0x04, +0x18, +0x2C and // +0x40 of a zeroed 68-byte block, which is a Mat4 diagonal shifted up by one dword. So each record // is {dword, Mat4}. -void skinnedMeshMatrixVectorResize(vc71::vector_layout& v, unsigned int count) -{ - unsigned char prototype[68]; - std::memset(prototype, 0, sizeof(prototype)); - *reinterpret_cast(prototype + 0x04) = 1.0f; - *reinterpret_cast(prototype + 0x18) = 1.0f; - *reinterpret_cast(prototype + 0x2C) = 1.0f; - *reinterpret_cast(prototype + 0x40) = 1.0f; - vectorResizeRaw(v, count, 68, prototype); -} - -enum { kSkinnedMeshMaterialStride = 456 }; // the record skinnedMeshMaterialConstruct builds - - -// The shrink/grow body all three share, and the one `skinnedMeshReserveLightRecords` already uses. -// [CHOSEN, not recovered] in its allocation detail, under the standing [RETIRE-WHEN: RW-74] policy. -void vectorResizeRaw(vc71::vector_layout& v, unsigned int count, unsigned int elemSize, - const void* prototype) -{ - const unsigned int size = - v.first ? static_cast((v.last - v.first) / elemSize) : 0u; - if (count <= size) - { - v.last = v.first + elemSize * count; // shrink: republish _Last - return; - } - - const unsigned int capacity = - v.first ? static_cast((v.end - v.first) / elemSize) : 0u; - if (count > capacity) - { - char* const grown = static_cast(::renddx9abi::engineAlloc(elemSize * count)); - if (!grown) - return; - if (v.first) - { - std::memcpy(grown, v.first, elemSize * size); - ::renddx9abi::engineFree(v.first); - } - v.first = grown; - v.end = grown + elemSize * count; - } - v.last = v.first + elemSize * count; - - for (unsigned int i = size; i < count; ++i) - std::memcpy(v.first + elemSize * i, prototype, elemSize); -} - -// sub_10111DF0 / sub_100EC310 - `vector::operator=` over 4-byte elements: an empty source frees -// and clears, otherwise the destination is grown if needed and the elements copied. -// SkinnedMesh.cpp carries this same body in ITS anonymous namespace, so it cannot be shared; -// this is that transcription repeated, not a second reading. [RETIRE-WHEN: RW-74] -void vectorAssignRaw(vc71::vector_layout& dst, const vc71::vector_layout& src, unsigned elemSize) +void skinnedMeshMatrixVectorResize(std::vector& v, unsigned int count) { - if (&dst == &src) - return; - - const unsigned int srcCount = - src.first ? static_cast((src.last - src.first) / elemSize) : 0u; - if (!srcCount) - { - if (dst.first) - ::renddx9abi::engineFree(dst.first); - dst.first = 0; - dst.last = 0; - dst.end = 0; - return; - } - - const unsigned int capacity = - dst.first ? static_cast((dst.end - dst.first) / elemSize) : 0u; - if (srcCount > capacity) - { - if (dst.first) - ::renddx9abi::engineFree(dst.first); - char* const grown = static_cast(::renddx9abi::engineAlloc(elemSize * srcCount)); - dst.first = grown; - dst.end = grown ? grown + elemSize * srcCount : 0; - if (!grown) - { - dst.last = 0; - return; - } - } - std::memcpy(dst.first, src.first, elemSize * srcCount); - dst.last = dst.first + elemSize * srcCount; + SkinnedMeshPart prototype; + std::memset(&prototype, 0, sizeof(prototype)); + prototype.transform.m[0] = 1.0f; // +0x04 + prototype.transform.m[5] = 1.0f; // +0x18 + prototype.transform.m[10] = 1.0f; // +0x2C + prototype.transform.m[15] = 1.0f; // +0x40 + v.resize(count, prototype); } // Resizes a texture-pointer vector, filling new elements with null. -void textureVectorResize(vc71::vector_layout& v, unsigned int count) +void textureVectorResize(std::vector& v, unsigned int count) { - static void* const kNullTexture = 0; - vectorResizeRaw(v, count, sizeof(void*), &kNullTexture); + v.resize(count, static_cast(0)); } - -// Copies a material into its live record. Map assignment guards self-assignment and -// clears the destination before copying. - -void skinnedMeshMaterialCommit(void* record, const void* scratch) -{ - unsigned char* const d = static_cast(record); - const unsigned char* const a = static_cast(scratch); - - // +0x04 - the texture vector. 4-byte elements. - vectorAssignRaw(*reinterpret_cast(d + 0x04), - *reinterpret_cast(a + 0x04), 4); - - // +0x14 .. +0x24 - five dwords, four of which the draws read back as baseVertex, startIndex, - // primitive count and vertex count. - std::memcpy(d + 0x14, a + 0x14, 0x28 - 0x14); - - // +0x28 - the vertex-element vector. Also 4-byte elements (pointers to RaVertexElementDesc). - vectorAssignRaw(*reinterpret_cast(d + 0x28), - *reinterpret_cast(a + 0x28), 4); - - ::dice::hfe::dx9rend::Ra::raMaterialParametersAssign(d + 0x38, a + 0x38); - - std::memcpy(d + 0x188, a + 0x188, 5); // the five flag bytes - std::memcpy(d + 0x190, a + 0x190, 0x1A0 - 0x190); - - *reinterpret_cast(d + 0x1A0) = - *reinterpret_cast(a + 0x1A0); - - // The self-assignment guard compares the two map addresses, not the objects. - if (d + 0x1BC != a + 0x1BC) - { - materialMapClear(*reinterpret_cast(d + 0x1BC)); - materialMapCopy(*reinterpret_cast(d + 0x1BC), - *reinterpret_cast(a + 0x1BC)); - } -} - -void skinnedMeshMaterialDestroy(void* scratch) +void skinnedMeshReserveGeoms(SkinnedMeshTemplate::MaterialTable& companions, unsigned int count) { - unsigned char* const m = static_cast(scratch); - - vc71::map_layout& map = *reinterpret_cast(m + 0x1BC); - materialMapClear(map); - if (map.head) - ::renddx9abi::engineFree(map.head); - map.head = 0; - map.size = 0; - - reinterpret_cast(m + 0x1A0)->~string(); - - ::dice::hfe::dx9rend::Ra::raMaterialParametersDestroy(m + 0x38); - - vc71::vector_layout& elements = *reinterpret_cast(m + 0x28); - if (elements.first) - ::renddx9abi::engineFree(elements.first); - elements.first = 0; - elements.last = 0; - elements.end = 0; - - vc71::vector_layout& textures = *reinterpret_cast(m + 0x04); - if (textures.first) - ::renddx9abi::engineFree(textures.first); - textures.first = 0; - textures.last = 0; - textures.end = 0; - - // [FRONTIER] The shared material base table is unavailable. Leave the destroyed - // record's vptr null; records must be reconstructed before any further dispatch. - *reinterpret_cast(m) = 0; + companions.resize(count); } -// Empty nested-vector value. -const vc71::vector_layout kEmptyNestedVector = { 0, 0, 0, 0 }; - -// StaticMeshMaterial.cpp already carries this body, but in ITS anonymous namespace, so it has -// internal linkage and cannot be shared. This is that transcription repeated, not a second reading. -// The growth policy is the shipped one: capacity + capacity/2, floored at size + 1. -void pointerVectorPush(vc71::vector_layout& v, const void* value) -{ - const unsigned int size = - v.first ? static_cast((v.last - v.first) >> 2) : 0u; - const unsigned int capacity = - v.first ? static_cast((v.end - v.first) >> 2) : 0u; - - if (size == capacity) - { - unsigned int grown = capacity + (capacity >> 1); - if (grown < size + 1u) - grown = size + 1u; - char* const buffer = static_cast(::renddx9abi::engineAlloc(grown * 4u)); - if (!buffer) - return; - if (size) - std::memcpy(buffer, v.first, size * 4u); - if (v.first) - ::renddx9abi::engineFree(v.first); - v.first = buffer; - v.last = buffer + size * 4u; - v.end = buffer + grown * 4u; - } - - *reinterpret_cast(v.last) = value; - v.last += 4; -} - -void skinnedMeshReserveGeoms(vc71::vector_layout& companions, unsigned int count) -{ - vectorResizeRaw(companions, count, sizeof(vc71::vector_layout), &kEmptyNestedVector); -} - -void skinnedMeshReserveLods(vc71::vector_layout* geomCompanion, int count) +void skinnedMeshReserveLods(SkinnedMeshTemplate::GeomMaterials* geomCompanion, int count) { if (!geomCompanion || count < 0) return; - vectorResizeRaw(*geomCompanion, static_cast(count), - sizeof(vc71::vector_layout), &kEmptyNestedVector); + geomCompanion->resize(static_cast(count)); } -// Expands materials with shallow byte copies of the prototype. -// Each record must be overwritten by material parsing before its shared storage is used. -void skinnedMeshReserveMaterials(vc71::vector_layout* lodCompanion, unsigned int count, - const void* prototype) +// Expands a lod's materials with copies of the prototype. +// Each record is overwritten by material parsing before its storage is used. +void skinnedMeshReserveMaterials(SkinnedMeshTemplate::LodMaterials* lodCompanion, + unsigned int count, const SkinnedMeshMaterial* prototype) { if (!lodCompanion || !prototype) return; - vectorResizeRaw(*lodCompanion, count, kSkinnedMeshMaterialStride, prototype); + lodCompanion->resize(count, *prototype); } // Destroys a material and frees its engine allocation when flags bit 0 is set. // Returns the original pointer. The material keeps the nine-slot interface used by render queues. void* skinnedMeshMaterialDestroyFlags(void* material, unsigned char flags) { - skinnedMeshMaterialDestroy(material); + static_cast(material)->~SkinnedMeshMaterial(); if (flags & 1) ::renddx9abi::engineFree(material); return material; @@ -500,24 +280,24 @@ void* skinnedMeshMaterialDestroyFlags(void* material, unsigned char flags) // Binds vertex streams and a declaration cached by shader build serial. // Missing elements report failure on every call and are not cached. +// PE 0x1010F5F0 bool skinnedMeshMaterialApplyStreams(void* material, void* shaderState) { namespace Ra = ::dice::hfe::dx9rend::Ra; - unsigned char* const m = static_cast(material); + SkinnedMeshMaterial* const m = static_cast(material); Ra::RaShader* const shader = static_cast(shaderState); - vc71::map_layout& declarations = *reinterpret_cast(m + 0x1BC); + SkinnedMeshMaterial::DeclarationMap& declarations = m->declarations; // +0x1BC const unsigned int key = static_cast(shader->m_buildSerial); // +0x174 - vc71::map_node_u32* node = vc71::mapFindU32(declarations, key); - if (!node) + SkinnedMeshMaterial::DeclarationMap::iterator node = declarations.find(key); + if (node == declarations.end()) { Ra::RaStreamRequirements* const required = Ra::raStreamRequirementsCreate(shader->m_requiredVertexElements); // sub_10049330 + sub_1004A0F0 Ra::RaDeclarationBuilder builder; Ra::raDeclarationBuilderConstruct(builder); - const vc71::vector_layout& elements = - *reinterpret_cast(m + 0x28); + const std::vector& elements = m->elements; // +0x28 if (Ra::raStreamRequirementsConsume(required, elements)) Ra::raDeclarationBuilderAddStream(builder, elements); @@ -525,19 +305,20 @@ bool skinnedMeshMaterialApplyStreams(void* material, void* shaderState) { char missing[1024]; Ra::raStreamRequirementsDescribe(required, missing, sizeof(missing)); - ::renddx9abi::logf("SkinnedMeshTemplate.cpp:126 Starving streams in the shader %s, %s", - shader->m_name.c_str(), missing); + ::renddx9abi::Debug(DebugTypeError, + "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\SkinnedMeshTemplate.cpp", + 126, "") << "Starving streams in the shader " << shader->m_name << missing; Ra::raDeclarationBuilderDestroy(builder); Ra::raStreamRequirementsDestroy(required); return false; } IDirect3DDevice9* const device = Ra::raRendererDevice(); // renderer +0x0C - vc71::map_node_u32* const inserted = vc71::mapInsertU32(declarations, key); - *reinterpret_cast(inserted->value) = - Ra::raVertexDeclarationCached(Ra::raDeclarationBuilderFinish(builder), - device); - node = vc71::mapFindU32(declarations, key); + // Insert first (the new value is zero-filled), then build and store the declaration. + SkinnedMeshDeclarationEntry& inserted = declarations[key]; + inserted.declaration = + Ra::raVertexDeclarationCached(Ra::raDeclarationBuilderFinish(builder), device); + node = declarations.find(key); Ra::raDeclarationBuilderDestroy(builder); Ra::raStreamRequirementsDestroy(required); } @@ -545,37 +326,39 @@ bool skinnedMeshMaterialApplyStreams(void* material, void* shaderState) // The bind, in the shipped order: stream 0 from +0x194 at the +0x198 stride, the declaration, // then the index buffer at +0x19C. ::dice::hfe::dx9rend::stateManagerSetStreamSource( - 0, *reinterpret_cast(m + 0x194), 0, - *reinterpret_cast(m + 0x198)); // +0x58 + 0, m->vertexBuffer, 0, m->vertexStride); // +0x58 ::dice::hfe::dx9rend::stateManagerSetVertexDeclaration( - *reinterpret_cast(node->value)); // +0x5C - ::dice::hfe::dx9rend::stateManagerSetIndices( - *reinterpret_cast(m + 0x19C)); // +0x54 + node->second.declaration); // +0x5C + ::dice::hfe::dx9rend::stateManagerSetIndices(m->indexBuffer); // +0x54 return true; } -// The five accessors and the two constants, each one instruction of body. -inline int materialDword(const void* material, unsigned int offset) +SkinnedMeshMaterial* materialOf(void* self) { - return *reinterpret_cast(static_cast(material) + offset); + return static_cast(self); } // The nine __fastcall entries the table holds. The shipped records are __thiscall, which is this // receiver-in-ecx shape with the unused edx slot - the same idiom RenderQueues.cpp's own vtables // use, and the same one `materialApplyStreams` calls back through. -void* __fastcall smm_destroy(void* self, void*, unsigned char flags) +void* RD9_THUNK smm_destroy(void* self RD9_THUNK_EDX, unsigned char flags) { return skinnedMeshMaterialDestroyFlags(self, flags); } -unsigned char __fastcall smm_applyStreams(void* self, void*, void* shaderState) +unsigned char RD9_THUNK smm_applyStreams(void* self RD9_THUNK_EDX, void* shaderState) { return skinnedMeshMaterialApplyStreams(self, shaderState) ? 1u : 0u; } -int __fastcall smm_getVertexCount(void* self, void*) { return materialDword(self, 0x24); } -int __fastcall smm_slot0C(void*, void*) { return -1; } -int __fastcall smm_getPrimitiveCount(void* self, void*) { return materialDword(self, 0x20); } -int __fastcall smm_getDword190(void* self, void*) { return materialDword(self, 0x190); } -int __fastcall smm_getVertexStart(void* self, void*) { return materialDword(self, 0x18); } -int __fastcall smm_slot1C(void*, void*) { return 0; } -int __fastcall smm_getIndexStart(void* self, void*) { return materialDword(self, 0x1C); } +int RD9_THUNK smm_getVertexCount(void* self RD9_THUNK_EDX) +{ return static_cast(materialOf(self)->vertexCount); } // +0x24 +int RD9_THUNK smm_slot0C(void* RD9_THUNK_EDX) { return -1; } +int RD9_THUNK smm_getPrimitiveCount(void* self RD9_THUNK_EDX) +{ return static_cast(materialOf(self)->primitiveCount); } // +0x20 +int RD9_THUNK smm_getDword190(void* self RD9_THUNK_EDX) +{ return static_cast(materialOf(self)->primitiveType); } // +0x190 +int RD9_THUNK smm_getVertexStart(void* self RD9_THUNK_EDX) +{ return static_cast(materialOf(self)->vertexStart); } // +0x18 +int RD9_THUNK smm_slot1C(void* RD9_THUNK_EDX) { return 0; } +int RD9_THUNK smm_getIndexStart(void* self RD9_THUNK_EDX) +{ return static_cast(materialOf(self)->indexStart); } // +0x1C void* const kSkinnedMeshMaterialVtable[9] = { @@ -590,60 +373,129 @@ void* const kSkinnedMeshMaterialVtable[9] = reinterpret_cast(&smm_getIndexStart) // +0x20 }; +} // anonymous namespace -// Constructs a material in storage large enough for the 456-byte record. -// Installs the nine-slot render interface and skinning vertex elements; hasTangent controls -// tangent-space support. Missing support reports the existing diagnostic. -void skinnedMeshMaterialConstruct(void* storage, bool hasTangent) +// Constructs a material record. +// Installs the nine-slot render interface and skinning vertex elements; hasTangent controls +// tangent-space support. Missing support reports the existing diagnostic. The texture vector, the +// element vector, the +0x1A0 string and the declaration map are constructed as members. + +// PE 0x1010F310 +SkinnedMeshMaterial::SkinnedMeshMaterial(bool hasTangent) + : vtable(kSkinnedMeshMaterialVtable), textures(), + dword14(0), vertexStart(0), indexStart(0), primitiveCount(0), vertexCount(0), // +0x14..+0x24 + elements() { - unsigned char* const m = static_cast(storage); - - *reinterpret_cast(m) = kSkinnedMeshMaterialVtable; - std::memset(m + 0x08, 0, 0x28 - 0x08); // +0x08 .. +0x24 + ::dice::hfe::dx9rend::Ra::raMaterialParametersConstruct(parameters); // +0x38 - // +0x28: the vertex-element vector. Allocator word untouched; first/last/end zeroed. - vc71::vector_layout& elements = *reinterpret_cast(m + 0x28); - elements.first = 0; - elements.last = 0; - elements.end = 0; + hasNormalMap = 0; // +0x188 + objSpaceNormalMap = 0; // +0x189 + isAlpha = 0; // +0x18A + hasEnvMap = 0; // +0x18B + flag18C = 0; // +0x18C - ::dice::hfe::dx9rend::Ra::raMaterialParametersConstruct(m + 0x38); + primitiveType = 4; // +0x190, four, not zero + vertexBuffer = 0; // +0x194 + vertexStride = 0; // +0x198 + indexBuffer = 0; // +0x19C - m[0x188] = 0; - m[0x189] = 0; - m[0x18A] = 0; - m[0x18B] = 0; - m[0x18C] = 0; + new (&string1A0) std::string(); + new (&declarations) DeclarationMap(); - *reinterpret_cast(m + 0x190) = 4; // four, not zero - *reinterpret_cast(m + 0x194) = 0; - *reinterpret_cast(m + 0x198) = 0; - *reinterpret_cast(m + 0x19C) = 0; - - new (m + 0x1A0) vc71::string(); // +0x1A0 - reinterpret_cast(m + 0x1BC)->construct(sizeof(vc71::map_node_u32)); - - pointerVectorPush(elements, &::dice::hfe::dx9rend::Ra::g_desc_1023EF04); // Vtx_Position - pointerVectorPush(elements, &::dice::hfe::dx9rend::Ra::g_desc_1023EF7C); // Vtx_Normal - pointerVectorPush(elements, &::dice::hfe::dx9rend::Ra::g_desc_1023ED74); // Vtx_BoneWeights - pointerVectorPush(elements, &::dice::hfe::dx9rend::Ra::g_desc_1023EEDC); // Vtx_BoneIdcs - pointerVectorPush(elements, &::dice::hfe::dx9rend::Ra::g_desc_1023ED4C); // Vtx_TBase + elements.push_back(&::dice::hfe::dx9rend::Ra::g_desc_1023EF04); // Vtx_Position + elements.push_back(&::dice::hfe::dx9rend::Ra::g_desc_1023EF7C); // Vtx_Normal + elements.push_back(&::dice::hfe::dx9rend::Ra::g_desc_1023ED74); // Vtx_BoneWeights + elements.push_back(&::dice::hfe::dx9rend::Ra::g_desc_1023EEDC); // Vtx_BoneIdcs + elements.push_back(&::dice::hfe::dx9rend::Ra::g_desc_1023ED4C); // Vtx_TBase if (hasTangent) { - pointerVectorPush(elements, &::dice::hfe::dx9rend::Ra::g_desc_1023EFF4); + elements.push_back(&::dice::hfe::dx9rend::Ra::g_desc_1023EFF4); } else { - ::renddx9abi::logf("SkinnedMeshTemplate.cpp:101: tl: Material created _without_ tangent " - "support. Something must be wrong! (because we haven't implemented " - "this yet!!)"); + ::renddx9abi::Debug(DebugTypeError, + "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\SkinnedMeshTemplate.cpp", + 101, "") << "tl: Material created _without_ tangent support. Something must be wrong!" + << " (because we haven't implemented this yet!!)"; } } +// Copies a material without retaining the parameter block's texture references. +// Preserve the shipped difference between copy construction and counted assignment. +// PE 0x10112860, 0x10112300, 0x10112150: copy constructor, with the texture-vector copy constructor +// (+0x04) and the declaration-map copy constructor (+0x1BC) instantiations it calls. +SkinnedMeshMaterial::SkinnedMeshMaterial(const SkinnedMeshMaterial& other) + : vtable(kSkinnedMeshMaterialVtable), textures(other.textures), + dword14(other.dword14), vertexStart(other.vertexStart), indexStart(other.indexStart), + primitiveCount(other.primitiveCount), vertexCount(other.vertexCount), + elements(other.elements) +{ + ::dice::hfe::dx9rend::Ra::raMaterialParametersCopyConstruct(parameters, other.parameters); + hasNormalMap=other.hasNormalMap; + objSpaceNormalMap=other.objSpaceNormalMap; + isAlpha=other.isAlpha; + hasEnvMap=other.hasEnvMap; + flag18C=other.flag18C; + primitiveType=other.primitiveType; + vertexBuffer=other.vertexBuffer; + vertexStride=other.vertexStride; + indexBuffer=other.indexBuffer; + new (&string1A0) std::string(other.string1A0); + new (&declarations) DeclarationMap(other.declarations); +} -} // anonymous namespace +// Copies a material into its live record. Map assignment guards self-assignment and +// clears the destination before copying. +// PE 0x10112BA0 +SkinnedMeshMaterial& SkinnedMeshMaterial::operator=(const SkinnedMeshMaterial& other) +{ + // +0x04 - the texture vector. 4-byte elements. + textures = other.textures; + + // +0x14 .. +0x24 - five dwords, four of which the draws read back as baseVertex, startIndex, + // primitive count and vertex count. + dword14 = other.dword14; + vertexStart = other.vertexStart; + indexStart = other.indexStart; + primitiveCount = other.primitiveCount; + vertexCount = other.vertexCount; + + // +0x28 - the vertex-element vector. Also 4-byte elements (pointers to RaVertexElementDesc). + elements = other.elements; + + ::dice::hfe::dx9rend::Ra::raMaterialParametersAssign(parameters, other.parameters); + + hasNormalMap = other.hasNormalMap; // the five flag bytes + objSpaceNormalMap = other.objSpaceNormalMap; + isAlpha = other.isAlpha; + hasEnvMap = other.hasEnvMap; + flag18C = other.flag18C; + primitiveType = other.primitiveType; // +0x190 .. +0x19C + vertexBuffer = other.vertexBuffer; + vertexStride = other.vertexStride; + indexBuffer = other.indexBuffer; + + string1A0 = other.string1A0; + + // The self-assignment guard compares the two map addresses, not the objects. + declarations = other.declarations; + return *this; +} + +// PE 0x10112520. Restore the abstract base table only after the last member is destroyed. +SkinnedMeshMaterial::~SkinnedMeshMaterial() +{ + declarations.~DeclarationMap(); + string1A0.~basic_string(); + ::dice::hfe::dx9rend::Ra::raMaterialParametersDestroy(parameters); + typedef decltype(elements) ElementVector; + typedef decltype(textures) TextureVector; + elements.~ElementVector(); + textures.~TextureVector(); + vtable = materialDestroyedVtable(); +} // Reads materials for each geometry/LOD, resolving textures and shader flags. // The stream and LOD records must already be initialized. Uses mip class 12 for these loads @@ -656,12 +508,9 @@ void SkinnedMeshTemplate::readMaterials(::renddx9abi::HostNonlinearStream* strea skinnedMeshInitTechniques(); // sub_1010F190 - fills the mask vector - const unsigned int geomCount = - m_lodCounts.first - ? static_cast((m_lodCounts.last - m_lodCounts.first) >> 2) - : 0u; + const unsigned int geomCount = meshGeomCount(m_lodCounts); - skinnedMeshReserveGeoms(m_vector0CC, geomCount); // sub_10115380 - one entry per geom + skinnedMeshReserveGeoms(m_materials, geomCount); // sub_10115380 - one entry per geom // Initialize shared shadow parameters before reading material records. skinnedMeshInitShadowState(); @@ -671,52 +520,44 @@ void SkinnedMeshTemplate::readMaterials(::renddx9abi::HostNonlinearStream* strea for (unsigned int geom = 0; geom < geomCount; ++geom) { - const int lodCount = - reinterpret_cast(m_lodCounts.first)[geom]; + const int lodCount = meshGeomInt(m_lodCounts, geom); // readLods records the number of LODs to skip for each geometry. - int lodsToSkip = reinterpret_cast(m_geomInts.first)[geom]; + int lodsToSkip = meshGeomInt(m_geomInts, geom); // The geom's own companion entry - the receiver measured at 0x1010FF49. - vc71::vector_layout* const geomCompanion = - reinterpret_cast(m_vector0CC.first + 16 * geom); + GeomMaterials* const geomCompanion = m_materials.data() + geom; skinnedMeshReserveLods(geomCompanion, lodCount); // sub_10114D00 - one entry per lod - int lodByteOffset = 0; // 132 * destination lod - int companionByteOffset = 0; // 16 * destination lod + int destinationLod = 0; // the lod record / material vector index for (int lod = 0; lod < lodCount; ) { // The 32-byte geom record's first vector holds 132-byte lod records; its companion in - // the other vector holds 16-byte ones. Both are indexed by the destination lod, which - // is what the skip dance below keeps still. - unsigned char* const lodRecord = - reinterpret_cast( - reinterpret_cast( - m_vector0DC.first + 32 * geom)->first) + lodByteOffset; - vc71::vector_layout* const companion = - reinterpret_cast( - reinterpret_cast(geomCompanion->first) + companionByteOffset); + // the other table holds one material vector per lod. Both are indexed by the + // destination lod, which is what the skip dance below keeps still. + SkinnedMeshLod* const lodRecord = m_geoms.data()[geom].lods.data() + destinationLod; + LodMaterials* const companion = geomCompanion->data() + destinationLod; // Reset per-LOD humanskin and alpha-test flags before scanning materials. - lodRecord[0x80] = 0; - lodRecord[0x81] = 0; + lodRecord->humanSkin = 0; // lod +0x80 + lodRecord->hasAlphaTest = 0; // lod +0x81 unsigned int materialCount = 0; stream->read(&materialCount, 4); - // The prototype the resize copies, built on this frame exactly as the shipped - // body builds it at `mov ecx, esp` immediately before the call. - unsigned char materialPrototype[kSkinnedMeshMaterialStride]; - skinnedMeshMaterialConstruct(materialPrototype, true); - skinnedMeshReserveMaterials(companion, materialCount, - materialPrototype); + { + // The prototype the resize copies, built on this frame exactly as the shipped + // body builds it at `mov ecx, esp` immediately before the call. + const SkinnedMeshMaterial materialPrototype(true); + skinnedMeshReserveMaterials(companion, materialCount, &materialPrototype); + } for (unsigned int material = 0; material < materialCount; ++material) { + char* shaderName = 0; + { // Build textures in the temporary material before committing it. - unsigned char scratchMaterial[kSkinnedMeshMaterialStride]; - skinnedMeshMaterialConstruct(scratchMaterial, true); - vc71::vector_layout& textures = - *reinterpret_cast(scratchMaterial + 0x04); + SkinnedMeshMaterial scratchMaterial(true); + std::vector& textures = scratchMaterial.textures; // +0x04 unsigned int skipBytes = 0; stream->read(&skipBytes, 4); @@ -726,8 +567,7 @@ void SkinnedMeshTemplate::readMaterials(::renddx9abi::HostNonlinearStream* strea // allocated length + 1 and NUL-terminated by hand - the stream stores no terminator. unsigned int nameLength = 0; stream->read(&nameLength, 4); - char* const shaderName = - static_cast(::renddx9abi::engineAlloc(nameLength + 1)); + shaderName = static_cast(::renddx9abi::engineAlloc(nameLength + 1)); stream->read(shaderName, nameLength); shaderName[nameLength] = 0; ::strlwr(shaderName); @@ -736,7 +576,7 @@ void SkinnedMeshTemplate::readMaterials(::renddx9abi::HostNonlinearStream* strea if (std::strstr(shaderName, "tangent")) m_byte0FC = 1; // +0xFC, the template-wide tangent flag if (std::strstr(shaderName, "humanskin")) - lodRecord[0x80] = 1; + lodRecord->humanSkin = 1; // Gather textures in the temporary material's vector. unsigned int textureCount = 0; @@ -757,8 +597,8 @@ void SkinnedMeshTemplate::readMaterials(::renddx9abi::HostNonlinearStream* strea stream->read(rawName, textureNameLength); rawName[textureNameLength] = 0; - vc71::string prefix(""); - vc71::string name(rawName); + std::string prefix(""); + std::string name(rawName); // A name with no '/' is relative: it gets the template's path plus // *unk_1025B53C, which is the literal "Textures/" (static init 0x101D31C0). @@ -780,19 +620,18 @@ void SkinnedMeshTemplate::readMaterials(::renddx9abi::HostNonlinearStream* strea name = "@@ABSOLUTE@@Common/Textures/SpecularLUT_pow36.dds"; // Skip bump maps at nonzero shader quality, and skip all textures for omitted LODs. - const unsigned int shaderQuality = *reinterpret_cast( - reinterpret_cast(::dice::hfe::dx9rend::g_Renderer) - + 0x6CC); + const unsigned int shaderQuality = + ::dice::hfe::dx9rend::rendererRaPath(); // Renderer +0x6CC const bool isBumpName = std::strstr(name.c_str(), "_b.dds") != 0 || std::strstr(name.c_str(), "_b_os.dds") != 0; if (lodsToSkip <= 0 && (!shaderQuality || !isBumpName)) { - vc71::string full(prefix); + std::string full(prefix); full += name; void* const texture = ::dice::hfe::dx9rend::textureManagerGetTexture(full); - if (textures.first) - reinterpret_cast(textures.first)[t] = texture; + if (!textures.empty()) + textures[t] = static_cast(texture); // Slot 1 counts as a real texture only when it is not a SpecularLUT. if (t == 1 && !std::strstr(name.c_str(), "SpecularLUT")) @@ -804,28 +643,26 @@ void SkinnedMeshTemplate::readMaterials(::renddx9abi::HostNonlinearStream* strea (void)hasRealSecondTexture; // Read draw-range values directly into the material record. - stream->read(scratchMaterial + 0x18, 4); // baseVertex - stream->read(scratchMaterial + 0x1C, 4); // startIndex + stream->read(&scratchMaterial.vertexStart, 4); // +0x18 baseVertex + stream->read(&scratchMaterial.indexStart, 4); // +0x1C startIndex unsigned int indexCount = 0; stream->read(&indexCount, 4); // Derive triangle-list/strip counts; other primitive types keep the initialized zero. if (m_primitiveType == 4) // D3DPT_TRIANGLELIST - *reinterpret_cast(scratchMaterial + 0x20) = indexCount / 3u; + scratchMaterial.primitiveCount = indexCount / 3u; // +0x20 else if (m_primitiveType == 5) // D3DPT_TRIANGLESTRIP - *reinterpret_cast(scratchMaterial + 0x20) = indexCount - 2u; + scratchMaterial.primitiveCount = indexCount - 2u; - stream->read(scratchMaterial + 0x24, 4); // vertex count + stream->read(&scratchMaterial.vertexCount, 4); // +0x24 vertex count stream->skip(4); stream->skip(4); // The destination, measured at the record inside the companion. - unsigned char* const record = - reinterpret_cast(companion->first) - + kSkinnedMeshMaterialStride * material; + SkinnedMeshMaterial& record = companion->data()[material]; - skinnedMeshMaterialCommit(record, scratchMaterial); + record = scratchMaterial; if (lodsToSkip <= 0) { @@ -834,8 +671,7 @@ void SkinnedMeshTemplate::readMaterials(::renddx9abi::HostNonlinearStream* strea // running total being non-zero, so the first kept lod moves nothing. if (skippedIndices) { - unsigned int& startIndex = - *reinterpret_cast(record + 0x1C); + unsigned int& startIndex = record.indexStart; // +0x1C const unsigned int previous = startIndex; startIndex = previous - skippedIndices; std::memmove(m_indexData + startIndex, m_indexData + previous, @@ -843,12 +679,10 @@ void SkinnedMeshTemplate::readMaterials(::renddx9abi::HostNonlinearStream* strea } if (skippedVertices) { - unsigned int& baseVertex = - *reinterpret_cast(record + 0x18); + unsigned int& baseVertex = record.vertexStart; // +0x18 const unsigned int previous = baseVertex; baseVertex = previous - skippedVertices; - const unsigned int vertexCount = - *reinterpret_cast(record + 0x24); + const unsigned int vertexCount = record.vertexCount; // +0x24 std::memmove( static_cast(m_vertexData) + baseVertex * m_vertexStride, static_cast(m_vertexData) + previous * m_vertexStride, @@ -861,13 +695,12 @@ void SkinnedMeshTemplate::readMaterials(::renddx9abi::HostNonlinearStream* strea // Reload the vector's first pointer on each iteration. for (unsigned int j = 0;; ++j) { - void** const slots = reinterpret_cast(textures.first); - if (!slots) + const unsigned int held = static_cast(textures.size()); + if (!held) break; - const unsigned int held = - static_cast((textures.last - textures.first) >> 2); if (j >= held) break; + dx9rend::EngineTexture* const* const slots = textures.data(); if (slots[j]) { // The release-if-present pattern this tree already carries: @@ -879,11 +712,11 @@ void SkinnedMeshTemplate::readMaterials(::renddx9abi::HostNonlinearStream* strea ::dice::hfe::dx9rend::textureReleaseRef(doomed); } } - skippedVertices += *reinterpret_cast(record + 0x24); + skippedVertices += record.vertexCount; // +0x24 skippedIndices += indexCount; } - skinnedMeshMaterialDestroy(scratchMaterial); + } // the scratch material is destroyed here ::renddx9abi::engineFree(shaderName); } @@ -891,13 +724,11 @@ void SkinnedMeshTemplate::readMaterials(::renddx9abi::HostNonlinearStream* strea // Reuse the destination slot after consuming a skipped LOD from the stream. if (lodsToSkip > 0) { - lodByteOffset -= 132; - companionByteOffset -= 16; + --destinationLod; --lodsToSkip; --lod; } - lodByteOffset += 132; - companionByteOffset += 16; + ++destinationLod; if (++lod >= lodCount) break; } @@ -911,14 +742,13 @@ void SkinnedMeshTemplate::readMaterials(::renddx9abi::HostNonlinearStream* strea } -// Registers the new instance before loading so load callbacks can update it. -// Failure unregisters and destroys it through its engine-heap deleting slot. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: skinnedmesh-template] -// Retire remaining template boundaries after their declared behavior is implemented and validated. +// Constructs an instance, registering it while this template is unloaded. +// Failed loading removes and deletes the instance; ready resources skip the load. +// PE 0x1010F270 void* SkinnedMeshTemplate::createInstance() { - void* const storage = ::renddx9abi::engineAlloc(0x598); + void* const storage = ::renddx9abi::engineAlloc(sizeof(SkinnedMesh)); SkinnedMesh* const instance = storage ? skinnedMeshConstruct(storage, this) : 0; @@ -942,8 +772,8 @@ void* SkinnedMeshTemplate::createInstance() instanceSetErase(m_instances, instance); if (instance) { - typedef void*(__fastcall * DtorFn)(void*, void*, unsigned int); - reinterpret_cast(instance->m_vptr[0x34 / sizeof(void*)])(instance, 0, 1); + typedef void*(__thiscall * DtorFn)(void*, unsigned int); + reinterpret_cast(instance->m_vptr[0x34 / 4])(instance, 1); } return 0; } @@ -951,7 +781,7 @@ void* SkinnedMeshTemplate::createInstance() // Loads the named .skinnedMesh and updates live instances before marking it loaded. // Returns false when already loaded; parser failure is not propagated. - +// PE 0x1010E840. bool SkinnedMeshTemplate::load() { if (m_loaded) // +0x4C @@ -959,13 +789,13 @@ bool SkinnedMeshTemplate::load() static const char* const kMeshesFolder = "Meshes/"; // unk_10263DD4 - vc71::string path(m_path.c_str()); + std::string path(m_path.c_str()); path += kMeshesFolder; path += m_name; path += ".skinnedMesh"; // Built, never read. See the header note. - vc71::string gpuPath(m_path.c_str()); + std::string gpuPath(m_path.c_str()); gpuPath += kMeshesFolder; gpuPath += "gpu_"; gpuPath += m_name; @@ -995,11 +825,10 @@ bool SkinnedMeshTemplate::load() // Re-point every live instance at the data that just arrived. The set is empty until // createInstance has run. - for (vc71::set_node* node = m_instances.head ? m_instances.head->left : 0; - node && node != m_instances.head; - node = vc71::set_layout::next(node)) + for (std::set::iterator node = m_instances.begin(); node != m_instances.end(); + ++node) { - if (SkinnedMesh* const instance = reinterpret_cast(node->key)) + if (SkinnedMesh* const instance = *node) { instance->refreshSelection(); } @@ -1016,17 +845,19 @@ void SkinnedMeshTemplate::readTrailer(::renddx9abi::HostNonlinearStream* stream) (void)stream; // the shared empty body. Deliberately reads nothing. } +// PE 0x10110970 (compared with the listing instruction by instruction, including the +// compiler-unrolled distance loop). The vector::resize (0x10114510) and +// vector::resize (0x10115700) instantiations take a by-value prototype: retail's lod +// prototype has zeroed bounds with dirty (+0x20) = 1 and leaves +0x3C / +0x80 / +0x81 unwritten, +// where lods.resize value-initialises; unobservable, both bounds readers set dirty and every kept +// lod is read at once. void SkinnedMeshTemplate::readLods(::renddx9abi::HostNonlinearStream* stream) { - const unsigned int geomCount = - m_lodCounts.first - ? static_cast(m_lodCounts.last - m_lodCounts.first) >> 2 - : 0u; + const unsigned int geomCount = meshGeomCount(m_lodCounts); // sub_10115700 - resize the 32-byte geom-record vector. Its prototype is a default record: - // two empty vectors and the pad. - static const unsigned char kEmptyGeomRecord[32] = { 0 }; - vectorResizeRaw(m_vector0DC, geomCount, 32, kEmptyGeomRecord); + // two empty vectors. + m_geoms.resize(geomCount); if (!geomCount) return; @@ -1039,61 +870,54 @@ void SkinnedMeshTemplate::readLods(::renddx9abi::HostNonlinearStream* stream) if (geomCount == 1) { if (geom == 0) skip = m_maxSkip3pLods; } else if (geomCount == 2) { if (geom == 1) skip = m_maxSkip3pLods; } - const int lodCount = reinterpret_cast(m_lodCounts.first)[geom]; + const int lodCount = meshGeomInt(m_lodCounts, geom); if (skip >= rendererSkip) skip = rendererSkip; if (lodCount - 1 < skip) skip = lodCount - 1; - reinterpret_cast(m_geomInts.first)[geom] = skip; // +0x70 remembers it + meshGeomInt(m_geomInts, geom) = skip; // +0x70 remembers it const int kept = lodCount - skip; - reinterpret_cast(m_lodCounts.first)[geom] = kept; + meshGeomInt(m_lodCounts, geom) = kept; - unsigned char* const geomRecord = - reinterpret_cast(m_vector0DC.first) + 32 * geom; - vc71::vector_layout& lods = - *reinterpret_cast(geomRecord); // +0x00, 132-byte lods - vc71::vector_layout& distances = - *reinterpret_cast(geomRecord + 0x10); // +0x10, floats + SkinnedMeshGeomRecord& geomRecord = m_geoms[geom]; + std::vector& lods = geomRecord.lods; // +0x00, 132-byte lods + std::vector& distances = geomRecord.distances; // +0x10, floats - static const unsigned char kEmptyLodRecord[132] = { 0 }; - vectorResizeRaw(lods, static_cast(kept), 132, kEmptyLodRecord); + // New lod records have empty part vectors (retail prototype: see the comment above). + lods.resize(static_cast(kept)); const float kZeroDistance = 0.0f; - vectorResizeRaw(distances, static_cast(kept - 1), 4, - &kZeroDistance); + distances.resize(static_cast(kept - 1), kZeroDistance); // read each kept lod // The skip is implemented by rewinding the destination, so a skipped lod is read and // then overwritten by the next one. Same net-zero dance as readMaterials'. int remainingSkips = skip; - int lodIndex = 0; - int byteOffset = 0; + int lodIndex = 0; // also the destination record if (kept > 0) { do { - unsigned char* const lod = - reinterpret_cast(lods.first) + byteOffset; + SkinnedMeshLod* const lod = lods.data() + lodIndex; // The same version gate the StaticMesh sibling documents. if (m_head == 0 && m_version < 10u) - meshBoundsReadLegacy(*reinterpret_cast(lod), stream); + meshBoundsReadLegacy(lod->bounds, stream); else - meshBoundsReadMinMax(*reinterpret_cast(lod), stream); + meshBoundsReadMinMax(lod->bounds, stream); // +0x3C counts the bone-matrix vectors beginning at +0x40, with 16-byte stride. - stream->read(lod + 60, 4); // +0x3C - const unsigned int arrays = *reinterpret_cast(lod + 60); + stream->read(&lod->paletteCount, 4); // +0x3C + const unsigned int arrays = lod->paletteCount; if (arrays) { - vc71::vector_layout* palette = - reinterpret_cast(lod + 64); // +0x40 + std::vector* palette = lod->parts; // +0x40 for (unsigned int a = 0; a < arrays; ++a) { unsigned int count = 0; stream->read(&count, 4); skinnedMeshMatrixVectorResize(*palette, count); - stream->read(palette->first, 68 * count); + stream->read(palette->data(), 68 * count); ++palette; } } @@ -1102,9 +926,7 @@ void SkinnedMeshTemplate::readLods(::renddx9abi::HostNonlinearStream* stream) { --remainingSkips; --lodIndex; - byteOffset -= 132; } - byteOffset += 132; ++lodIndex; } while (lodIndex < kept); @@ -1112,32 +934,22 @@ void SkinnedMeshTemplate::readLods(::renddx9abi::HostNonlinearStream* stream) // Copy distance source[skip + lod], but advance the accumulator by source[lod]. // Preserve this asymmetric indexing and the 50-unit default step. - const int skipped = reinterpret_cast(m_geomInts.first)[geom]; + const int skipped = meshGeomInt(m_geomInts, geom); const int distanceCount = kept - 1; float accumulator = static_cast(skipped + 1) * 50.0f; for (int lod = 0; lod < distanceCount; ++lod) { - float* const destination = reinterpret_cast(distances.first); + float* const destination = distances.data(); bool stored = false; - if (m_lodDistances.first - && static_cast( - (m_lodDistances.last - m_lodDistances.first) >> 4) > geom) + int innerSize = 0; + const float* const source = meshLodDistances(m_lodDistances, geom, innerSize); + if (innerSize > lod) { - const vc71::vector_layout* const inner = - reinterpret_cast(m_lodDistances.first) + geom; - const int innerSize = - inner->first - ? static_cast((inner->last - inner->first) >> 2) : 0; - if (innerSize > lod) - { - const float* const source = - reinterpret_cast(inner->first); - destination[lod] = source[skipped + lod]; // skip-adjusted - accumulator += source[lod]; // NOT skip-adjusted - stored = true; - } + destination[lod] = source[skipped + lod]; // skip-adjusted + accumulator += source[lod]; // NOT skip-adjusted + stored = true; } if (!stored) @@ -1150,6 +962,31 @@ void SkinnedMeshTemplate::readLods(::renddx9abi::HostNonlinearStream* stream) } +// [INFERRED] Placement beside the template's other overrides; rdebug neighbours support this TU. +// PE 0x1010EB60, the IConsoleSaveable secondary-this entry at table 0x1021C14C +0x10. +bool SkinnedMeshTemplate::makeScript(::dice::hfe::io::IStream* stream) +{ + MeshTemplate::makeScript(stream); + std::ostringstream out; + const unsigned int geomCount=static_cast(m_geoms.size()); + for(unsigned int geom=0;geom(m_geoms[geom].distances.size()); + float defaultDistance=50.0f; + for(unsigned int lod=0;lod(script.size()); + return stream->write(script.c_str(),length)==length; +} + // The five slots the RW-193 audit turned up. except finalizeMaterials. @@ -1160,101 +997,75 @@ int SkinnedMeshTemplate::getVertexCount(int geom, int lod, int material) { if (geom == -1 && lod == -1) { - const unsigned int geomCount = - m_lodCounts.first - ? static_cast(m_lodCounts.last - m_lodCounts.first) >> 2 - : 0u; + const unsigned int geomCount = meshGeomCount(m_lodCounts); int total = 0; for (unsigned int g = 0; g < geomCount; ++g) { - const unsigned int lodCount = - static_cast(reinterpret_cast(m_lodCounts.first)[g]); + const unsigned int lodCount = static_cast(meshGeomInt(m_lodCounts, g)); for (unsigned int l = 0; l < lodCount; ++l) total += getVertexCount(static_cast(g), static_cast(l), -1); } return total; } - const vc71::vector_layout* const lodCompanion = - reinterpret_cast( - reinterpret_cast(m_vector0CC.first)[geom].first) + lod; + // The table is indexed unguarded, as shipped. + const LodMaterials& lodMaterials = m_materials.data()[geom].data()[lod]; if (material == -1) { int count = 0; - const unsigned char* record = - reinterpret_cast(lodCompanion->first); - const int materials = - record ? static_cast((lodCompanion->last - lodCompanion->first) / 456) : 0; - for (int m = 0; m < materials; ++m, record += 456) - count += *reinterpret_cast(record + 36); + const SkinnedMeshMaterial* record = lodMaterials.data(); + const int materials = static_cast(lodMaterials.size()); + for (int m = 0; m < materials; ++m, ++record) + count += static_cast(record->vertexCount); // +0x24 return count; } - return *reinterpret_cast( - reinterpret_cast(lodCompanion->first) + 456 * material + 36); + return static_cast(lodMaterials.data()[material].vertexCount); } // +0xA0, how many 456-byte material records this lod has, summed over every geom. +// PE 0x1010E680 int SkinnedMeshTemplate::getMaterialCount(unsigned int lod) { int total = 0; - const unsigned int geomCount = - m_vector0DC.first - ? static_cast(m_vector0DC.last - m_vector0DC.first) >> 5 - : 0u; + const unsigned int geomCount = static_cast(m_geoms.size()); for (unsigned int geom = 0; geom < geomCount; ++geom) { - const vc71::vector_layout* const lods = - reinterpret_cast( - reinterpret_cast(m_vector0DC.first) + 32 * geom); - if (!lods->first - || lod >= static_cast((lods->last - lods->first) / 132)) + const std::vector& lods = m_geoms[geom].lods; + if (lods.empty() || lod >= static_cast(lods.size())) continue; - const vc71::vector_layout* const lodCompanion = - reinterpret_cast( - reinterpret_cast(m_vector0CC.first)[geom].first) + lod; - if (lodCompanion->first) - total += static_cast((lodCompanion->last - lodCompanion->first) / 456); + const LodMaterials& lodMaterials = m_materials.data()[geom].data()[lod]; + total += static_cast(lodMaterials.size()); } return total; } -// +0xA4, the same walk, but asking each material record's OWN vtable +0x10 and summing +// PE 0x1010E750 (+0xA4), the same walk, but asking each material record's OWN vtable +0x10 and summing // the answers. [UNRESOLVED] what that slot returns; MeshTemplate.h names this getLodPrimitiveCount. int SkinnedMeshTemplate::getLodPrimitiveCount(unsigned int lod) { int total = 0; - const unsigned int geomCount = - m_vector0DC.first - ? static_cast(m_vector0DC.last - m_vector0DC.first) >> 5 - : 0u; + const unsigned int geomCount = static_cast(m_geoms.size()); for (unsigned int geom = 0; geom < geomCount; ++geom) { - const vc71::vector_layout* const lods = - reinterpret_cast( - reinterpret_cast(m_vector0DC.first) + 32 * geom); - if (!lods->first - || lod >= static_cast((lods->last - lods->first) / 132)) + const std::vector& lods = m_geoms[geom].lods; + if (lods.empty() || lod >= static_cast(lods.size())) continue; - const vc71::vector_layout* const lodCompanion = - reinterpret_cast( - reinterpret_cast(m_vector0CC.first)[geom].first) + lod; - if (!lodCompanion->first) + LodMaterials& lodMaterials = m_materials.data()[geom].data()[lod]; + if (lodMaterials.empty()) continue; - const int materials = - static_cast((lodCompanion->last - lodCompanion->first) / 456); - unsigned char* record = reinterpret_cast(lodCompanion->first); - for (int m = 0; m < materials; ++m, record += 456) + const int materials = static_cast(lodMaterials.size()); + SkinnedMeshMaterial* record = lodMaterials.data(); + for (int m = 0; m < materials; ++m, ++record) { - typedef int(__fastcall * Fn)(void*, void*); - total += reinterpret_cast( - (*reinterpret_cast(record))[0x10 / sizeof(void*)])(record, 0); + typedef int(__thiscall * Fn)(void*); + total += reinterpret_cast(record->vtable[0x10 / 4])(record); } } return total; @@ -1273,10 +1084,10 @@ void SkinnedMeshTemplate::mergeMaterials() namespace { -// Releases the previous texture through a temporary, then replaces the slot. -void skinnedMeshAssignTextureSlot(unsigned char* record, unsigned int slot, void* texture) +// Releases the previous texture through a temporary, then replaces the holder's value. +void skinnedMeshAssignTextureSlot(RaMaterialParameters::Texture& holder, void* texture) { - void** const held = reinterpret_cast(record + slot); + void** const held = &holder.value; if (*held == texture) return; // identity guard, as shipped ::dice::hfe::dx9rend::EngineTexture* doomed = @@ -1285,76 +1096,79 @@ void skinnedMeshAssignTextureSlot(unsigned char* record, unsigned int slot, void *held = texture; if (texture) { - typedef void(__fastcall * AddRefFn)(void*, void*); + typedef void(__thiscall * AddRefFn)(void*); reinterpret_cast( - (*reinterpret_cast(texture))[0x08 / sizeof(void*)])(texture, 0); + (*reinterpret_cast(texture))[0x08 / 4])(texture); } } -unsigned int bufferHandleAt(void* wrapper, unsigned int byteOffset) +// The vertex-buffer wrapper's stride (+0x28), or 0 for no wrapper. +unsigned int bufferStride(void* wrapper) +{ + return wrapper ? ::dice::hfe::dx9rend::vertexBufferStride(wrapper) : 0u; +} + +// The wrappers' D3D interface pointers (+0x08), or null for no wrapper. +IDirect3DVertexBuffer9* vertexBufferObject(void* wrapper) +{ + return wrapper ? ::dice::hfe::dx9rend::vertexBufferD3D(wrapper) : 0; +} + +IDirect3DIndexBuffer9* indexBufferObject(void* wrapper) { - return wrapper - ? *reinterpret_cast( - static_cast(wrapper) + byteOffset) - : 0u; + return wrapper ? ::dice::hfe::dx9rend::indexBufferD3D(wrapper) : 0; } } // namespace +// PE 0x1010ED00 void SkinnedMeshTemplate::finalizeMaterials() { - const unsigned int geomCount = - m_vector0CC.first - ? static_cast(m_vector0CC.last - m_vector0CC.first) >> 4 - : 0u; + const unsigned int geomCount = static_cast(m_materials.size()); for (unsigned int geom = 0; geom < geomCount; ++geom) { - const vc71::vector_layout* const geomCompanion = - reinterpret_cast(m_vector0CC.first) + geom; - if (!geomCompanion->first) + GeomMaterials& geomCompanion = m_materials[geom]; + if (geomCompanion.empty()) continue; - const unsigned int lodCount = - static_cast(geomCompanion->last - geomCompanion->first) >> 4; + const unsigned int lodCount = static_cast(geomCompanion.size()); for (unsigned int lod = 0; lod < lodCount; ++lod) { - const vc71::vector_layout* const lodCompanion = - reinterpret_cast(geomCompanion->first) + lod; - if (!lodCompanion->first) + LodMaterials& lodCompanion = geomCompanion[lod]; + if (lodCompanion.empty()) continue; - const int materials = - static_cast((lodCompanion->last - lodCompanion->first) / 456); - unsigned char* record = reinterpret_cast(lodCompanion->first); + const int materials = static_cast(lodCompanion.size()); + SkinnedMeshMaterial* record = lodCompanion.data(); - for (int m = 0; m < materials; ++m, record += 456) + // The `+0xNN` / decimal comments are retail record offsets; the ones below +0x188 + // are inside the parameter block. + for (int m = 0; m < materials; ++m, ++record) { - *reinterpret_cast(record + 400) = m_primitiveType; // +0xAC - *reinterpret_cast(record + 404) = - bufferHandleAt(m_vertexBuffer, 8); - *reinterpret_cast(record + 408) = - bufferHandleAt(m_vertexBuffer, 40); - *reinterpret_cast(record + 412) = - bufferHandleAt(m_indexBuffer, 8); - *reinterpret_cast(record + 188) = 64.0f; - - if (record[394]) + record->primitiveType = m_primitiveType; // 400, from +0xAC + record->vertexBuffer = vertexBufferObject(m_vertexBuffer); // 404 + record->vertexStride = bufferStride(m_vertexBuffer); // 408 + record->indexBuffer = indexBufferObject(m_indexBuffer); // 412 + RaMaterialParameters& block = skinnedMeshMaterialParameters(*record); + block.specularPower.value = 64.0f; // 188 + + if (record->isAlpha) // 394 { - record[84] = 1; - *reinterpret_cast(record + 220) = 127; - *reinterpret_cast(record + 212) = 1; + block.alphaTest.value = 1; // 84 + block.alphaTestRef.value = 127; // 220 + block.cullMode.value = 1; // 212 } - // The textures come from the record's OWN texture vector: +0x08 is its `first`, - // so `(record + 8)` is texture 0 and `*(*(record + 8) + 4)` is texture 1. - void** const textures = *reinterpret_cast(record + 8); - if (textures) + // The textures come from the record's OWN texture vector (+0x04, whose storage + // pointer is at +0x08): texture 0 and texture 1, unguarded once storage exists. + if (record->textures.capacity()) { - skinnedMeshAssignTextureSlot(record, 244, textures[0]); - if (record[392]) - skinnedMeshAssignTextureSlot(record, 276, textures[1]); + dx9rend::EngineTexture* const* const textures = record->textures.data(); + skinnedMeshAssignTextureSlot(block.diffuseMap, textures[0]); // 244 + if (record->hasNormalMap) // 392 + skinnedMeshAssignTextureSlot(block.normalMap, textures[1]); // 276 } } } @@ -1368,27 +1182,117 @@ unsigned int SkinnedMeshTemplate::getClassId() const return 0x870CA652u; } -void SkinnedMeshTemplate::setLodDistance(int, int, float) +namespace { + +// SkinnedMeshTemplate::setLodDistance's diagnostic arms. +void skinnedLodDistanceDebug(unsigned int line, const char* text, const std::string& name) { - RD9_FRONTIER("dice::hfe::geom::SkinnedMeshTemplate::setLodDistance (PE 0x1010FAA0)", 0x30); + ::renddx9abi::Debug(DebugTypeError, + "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Geom\\SkinnedMeshTemplate.cpp", + line, "") << text << name; +} + +} // anonymous namespace + +// PE 0x1010FAA0. Before loading, missing entries grow with zero-valued distances. +// Loaded distances are addressed after the skipped LODs; the getter does not make that adjustment. +void SkinnedMeshTemplate::setLodDistance(int geom, int lod, float distance) +{ + if (geom < 0 || lod < 0 || distance < 0.0f) + { + skinnedLodDistanceDebug(255, "Negative subgeometry lodswitch or distance ", m_name); + return; + } + if (!m_geoms.empty()) + { + if (geom >= static_cast(m_geoms.size())) + { + skinnedLodDistanceDebug(263, " Invalid Subgeometry ", m_name); + return; + } + const int skipped = m_geomInts.data()[geom]; + std::vector& distances = m_geoms.data()[geom].distances; + if (lod >= skipped + static_cast(distances.size())) + { + skinnedLodDistanceDebug(271, " Invalid lodSwitch ", m_name); + return; + } + if (lod >= skipped) + distances.data()[lod - skipped] = distance; + return; + } + if (m_lodDistances.size() < static_cast(geom + 1)) + m_lodDistances.resize(static_cast(geom + 1)); + std::vector& distances = m_lodDistances.data()[geom]; + if (distances.size() < static_cast(lod + 1)) + distances.resize(static_cast(lod + 1), 0.0f); + distances.data()[lod] = distance; } -float SkinnedMeshTemplate::getLodDistance(int, int) +// PE 0x1010EB10. Nonempty geometry is the only guard; both indices remain unchecked. +float SkinnedMeshTemplate::getLodDistance(int geom, int lod) { - RD9_FRONTIER("dice::hfe::geom::SkinnedMeshTemplate::getLodDistance (PE 0x1010EB10)", 0x34); - return 0.0f; + if (!m_geoms.empty()) + return m_geoms.data()[geom].distances.data()[lod]; + return -1.0f; } -unsigned int SkinnedMeshTemplate::getMemoryUsage(int) +// PE 0x1010F810. Bit 8 returns the triangle count immediately, discarding any byte subtotal. +unsigned int SkinnedMeshTemplate::getMemoryUsage(int mask) { - RD9_FRONTIER("dice::hfe::geom::SkinnedMeshTemplate::getMemoryUsage (PE 0x1010F810)", 0x54); - return 0; + if (mask == -1) + { + unsigned int result = getMemoryUsage(1); + result += getMemoryUsage(2); + result += getMemoryUsage(4); + return result; + } + unsigned int result = 0; + if ((mask & 1) && m_vertexBuffer) + result = dx9rend::vertexBufferByteSize(m_vertexBuffer); + if ((mask & 2) && m_indexBuffer) + result += 2u * m_indexCount; + if ((mask & 8) && m_indexBuffer) + return m_indexCount / 3u; + if (mask & 4) + { + std::map textures; + for (unsigned int geom = 0; geom < m_geoms.size(); ++geom) + { + const unsigned int lodCount = static_cast(m_geoms.data()[geom].lods.size()); + for (unsigned int lod = 0; lod < lodCount; ++lod) + { + LodMaterials& materials = m_materials.data()[geom].data()[lod]; + const unsigned int count = static_cast(materials.size()); + for (unsigned int material = 0; material < count; ++material) + { + const std::vector& source = materials.data()[material].textures; + const unsigned int textureCount = static_cast(source.size()); + for (unsigned int texture = 0; texture < textureCount; ++texture) + if (source.data()[texture]) + textures[source.data()[texture]] = source.data()[texture]; + } + } + } + for (std::map::const_iterator it = textures.begin(); + it != textures.end(); ++it) + if (it->second) + result += it->second->totalBytes; + } + return result; } -int SkinnedMeshTemplate::getPrimitiveCount(int, int, int) +// PE 0x1010E5F0. Only material=-1 requests aggregation; geometry and LOD are always indexed directly. +int SkinnedMeshTemplate::getPrimitiveCount(int geom, int lod, int material) { - RD9_FRONTIER("dice::hfe::geom::SkinnedMeshTemplate::getPrimitiveCount (PE 0x1010E5F0)", 0x58); - return 0; + const LodMaterials& materials = m_materials.data()[geom].data()[lod]; + if (material != -1) + return static_cast(materials.data()[material].primitiveCount); + unsigned int result = 0; + const unsigned int count = static_cast(materials.size()); + for (unsigned int i = 0; i < count; ++i) + result += materials.data()[i].primitiveCount; + return static_cast(result); } } // namespace geom diff --git a/Code/BF2/Geom/SkinnedMeshTemplate.h b/Code/BF2/Geom/SkinnedMeshTemplate.h index 6d475211a..f7f56b928 100644 --- a/Code/BF2/Geom/SkinnedMeshTemplate.h +++ b/Code/BF2/Geom/SkinnedMeshTemplate.h @@ -9,24 +9,128 @@ #ifdef BF2_IMAGE_RENDDX9 #include "MeshTemplate.h" -#include "../../RendDX9Abi/Vc71Vector.h" -#include "../../RendDX9Abi/Vc71Map.h" +#include "../Math/Mat4.h" +#include + +#include +#include +#include + +struct IDirect3DVertexBuffer9; +struct IDirect3DIndexBuffer9; +struct IDirect3DVertexDeclaration9; namespace dice { namespace hfe { +namespace dx9rend { +struct EngineTexture; +namespace Ra { struct RaVertexElementDesc; } +} namespace geom { +class SkinnedMesh; + // sub_10112090 through the template's +0x100 set - erase one live instance. Published because // `SkinnedMesh::~SkinnedMesh` is what calls it; see the definition's note for why the shipped -// inlined `equal_range` + range-erase and this `find` + `erase(node)` are the same operation. -void instanceSetErase(vc71::set_layout& set, void* instance); +// inlined `equal_range` + range-erase and this erase-by-key are the same operation. +void instanceSetErase(std::set& set, SkinnedMesh* instance); + + +// One bone part of a lod's palette (68 bytes): the skeleton bone it follows and the part's own +// transform. readLods resizes these with an identity transform and a zero part id. +struct SkinnedMeshPart +{ + int partId; // +0x00 index into the instance's skeleton matrices + Mat4 transform; // +0x04 +}; + +static_assert(sizeof(SkinnedMeshPart) == 68, "readLods reads parts as one 68-byte-stride block"); + +// One 132-byte lod record. readLods fills the bounds, the palette count and the part vectors; +// readMaterials clears and sets the two flags. +struct SkinnedMeshLod +{ + MeshBounds bounds; // +0x00 the draws read radius +0x1C, dirty +0x20 + unsigned int paletteCount; // +0x3C how many part vectors follow + std::vector parts[4]; // +0x40 one per material palette, 16-byte stride + unsigned char humanSkin; // +0x80 a material shader name holds "humanskin" + unsigned char hasAlphaTest; // +0x81 [INFERRED] the shadow draw's alpha gate + unsigned char pad82[2]; // +0x82 +}; + +// One geom's 32-byte record: its lods and the lod switch distances (one fewer than the lods). +struct SkinnedMeshGeomRecord +{ + std::vector lods; // +0x00 + std::vector distances; // +0x10 +}; + +// The vertex-declaration cache's mapped value. The shipped node carries 20 value bytes; only the +// first word, the cached declaration, is read or written. [UNRESOLVED] the remaining sixteen. +struct SkinnedMeshDeclarationEntry +{ + IDirect3DVertexDeclaration9* declaration; // +0x00 + unsigned char unresolved04[16]; +}; + +// One 456-byte skinned-mesh material record (retail +0x00..+0x1C7). The render queues dispatch +// through the nine-slot table at +0x00; SkinnedMeshTemplate.cpp defines the special members: +// construction installs the table and the skinning vertex elements, copy builds a fresh +// parameter block without retaining its textures, and assignment is the shipped commit. +// [CHOSEN, not recovered] Anonymous union storage permits explicit container lifetimes around +// the raw parameter block without changing field types, order or offsets. +struct SkinnedMeshMaterial +{ + typedef std::map DeclarationMap; + + explicit SkinnedMeshMaterial(bool hasTangent); + SkinnedMeshMaterial(const SkinnedMeshMaterial& other); + SkinnedMeshMaterial& operator=(const SkinnedMeshMaterial& other); + ~SkinnedMeshMaterial(); + + void* const* vtable; // +0x000 nine slots + union { std::vector textures; }; // +0x004 + unsigned int dword14; // +0x014 [UNRESOLVED] + unsigned int vertexStart; // +0x018 baseVertex + unsigned int indexStart; // +0x01C + unsigned int primitiveCount; // +0x020 + unsigned int vertexCount; // +0x024 + union { std::vector elements; }; // +0x028 + // The Ra material block (raMaterialParametersConstruct, RaMaterialParameters); retail + // +0x038..+0x187. + alignas(RaMaterialParameters) unsigned char parameters[sizeof(RaMaterialParameters)]; + unsigned char hasNormalMap; // +0x188 define bit 1 + unsigned char objSpaceNormalMap;// +0x189 define bit 2 + unsigned char isAlpha; // +0x18A the alpha pass + unsigned char hasEnvMap; // +0x18B define bit 3 + unsigned char flag18C; // +0x18C [UNRESOLVED] + unsigned char pad18D[3]; // +0x18D + unsigned int primitiveType; // +0x190 constructed 4 + IDirect3DVertexBuffer9* vertexBuffer; // +0x194 + unsigned int vertexStride; // +0x198 + IDirect3DIndexBuffer9* indexBuffer; // +0x19C + union { std::string string1A0; }; // +0x1A0 [UNRESOLVED] role + union { DeclarationMap declarations; }; // +0x1BC by shader build serial +}; + +// The material's Ra parameter block (retail record +0x38), typed. +inline RaMaterialParameters& skinnedMeshMaterialParameters(SkinnedMeshMaterial& material) +{ + return *reinterpret_cast(material.parameters); +} + // Soldier mesh loader with derived reference counting at +0xC8. // readTrailer is intentionally empty: reading the base trailer would shift the stream. -// Preserve untouched vector allocator words and the unresolved +0xED..+0xFB bytes. +// Preserve the unresolved +0xED..+0xFB bytes. class SkinnedMeshTemplate : public MeshTemplate { public: + typedef std::vector LodMaterials; // one lod's materials + typedef std::vector GeomMaterials; // one geom's lods + typedef std::vector MaterialTable; // geom -> lod -> material + typedef std::vector GeomTable; + SkinnedMeshTemplate(); // The overridden quartet counts at +0xC8 - the same three bodies StaticMeshTemplate uses, @@ -60,15 +164,25 @@ class SkinnedMeshTemplate : public MeshTemplate virtual void readMaterials(::renddx9abi::HostNonlinearStream* stream); - // data, in shipped order + // Writes nondefault LOD distances after the base script; the base result is discarded. + virtual bool makeScript(::dice::hfe::io::IStream* stream); + + // The destructor body (PE 0x10110740) and the deleting destructor in slot +0xB0 + // (0x101157F0). The storage is freed without a C++ destructor, so destroyMembers destroys + // every member itself: a loaded template first drops its material texture references and its + // share of the skinned shadow state. + void destroyMembers(); + virtual void* destroy(unsigned char flags); + + // data, in shipped order; the `+0xNN` comments are the retail offsets int m_refCount; // +0xC8 - vc71::vector_layout m_vector0CC; // +0xCC [UNRESOLVED] element type - vc71::vector_layout m_vector0DC; // +0xDC [UNRESOLVED] element type + MaterialTable m_materials; // +0xCC geom -> lod -> SkinnedMeshMaterial + GeomTable m_geoms; // +0xDC geom -> lods and lod distances unsigned char m_byte0EC; // +0xEC unsigned char m_unknown0ED[15]; // +0xED..+0xFB [UNRESOLVED], ctor-untouched unsigned char m_byte0FC; // +0xFC unsigned char m_pad0FD[3]; // +0xFD..+0xFF - vc71::set_layout m_instances; // +0x100 SkinnedMesh* + std::set m_instances; // +0x100 live instances, in pointer order }; } // namespace geom diff --git a/Code/BF2/Geom/SkyDome.cpp b/Code/BF2/Geom/SkyDome.cpp index 743aa59e8..06786b424 100644 --- a/Code/BF2/Geom/SkyDome.cpp +++ b/Code/BF2/Geom/SkyDome.cpp @@ -1,7 +1,6 @@ // Path: [INFERRED] from the registered class; no __FILE__ or Linux witness. // SkyDome implementation, recovered from RendDX9.dll 1.50. // Dome drawing uses the listener subobject at +4; flare drawing uses the primary. -// [CHOSEN, not recovered] profiler-only brackets remain omitted at the marked sites. #ifdef BF2_IMAGE_RENDDX9 @@ -14,14 +13,17 @@ #include "../Game/Objects/Visual/LightSource.h" // skyLightGetDirection - typed (RW-266) #include "../Math/Mat4.h" #include "../Math/Vec3.h" +#include "../RendDX9/RendDX9Math.h" // the RendDX9.dll Math copies #include "../Physics/HeightmapCluster.h" #include "../RendDX9/RendDX9Base.h" +#include "../RendDX9/QueryManager.h" +#include "../RendDX9/QueueProfiler.h" #include "../RendDX9/ShaderParameter.h" #include "../RendDX9/Texture.h" #include "../RendMisc/IRenderView.h" #include "../../RendDX9Abi/BfMemory.h" #include "../../RendDX9Abi/PluginEntry.h" -#include "../../RendDX9Abi/Vc71String.h" +#include #include #include @@ -68,8 +70,8 @@ namespace { // no external reader, so they are file-scope here with the same guards and the same zero fill. -// dword_1025D3D0 - the dome draw's guard word. Bit 1 guards the profiler-stat registration that is -// deliberately not reproduced (see the file header), so nothing below claims it. +// dword_1025D3D0 - the dome draw's guard word. Bit 1 guards the profiler registration, which is a +// function-local static in onRenderPathNotification here, so nothing below claims it. unsigned int g_domeOnceFlags = 0; // [UNRESOLVED] Zeroed once by dome drawing; no consumer is known. @@ -83,7 +85,8 @@ Vec4 g_cloudLerpConstant = { 0.0f, 0.0f, 0.0f, 0.0f }; Vec4 g_cloudsFadeOutConstant = { 0.0f, 0.0f, 0.0f, 0.0f }; // dword_1025D644 - the flare draw's guard word, a different word from the dome's. Bit 2 guards its -// own copy of the profiler registration (not reproduced), bit 1 guards the constant below. +// own copy of the profiler registration (a function-local static in drawFlare here), bit 1 +// guards the constant below. unsigned int g_flareOnceFlags = 0; // dword_1025D640, guard bit 1 = 0x3FC90FDB = pi/2. [UNRESOLVED]: written once at 0x10139917 and @@ -110,32 +113,8 @@ const float kTexOffsetWrap = 16.0f; // update()'s wrap threshold // Local vector math helpers. -// sub_10077830 - scale a matrix IN place by multiplying each column by the matching component. -// It scales the translation ROW too (m[12] *= s.x and so on); the dome's world matrix relies on -// that, so do not "fix" it into a 3x3 scale. -void mat4ScaleColumns(Mat4& m, const Vec3& s) -{ - m.m[0] = s.x * m.m[0]; - m.m[4] = m.m[4] * s.x; - m.m[8] = s.x * m.m[8]; - m.m[12] = m.m[12] * s.x; - m.m[1] = s.y * m.m[1]; - m.m[5] = s.y * m.m[5]; - m.m[9] = s.y * m.m[9]; - m.m[13] = s.y * m.m[13]; - m.m[2] = s.z * m.m[2]; - m.m[6] = m.m[6] * s.z; - m.m[10] = m.m[10] * s.z; - m.m[14] = m.m[14] * s.z; -} - -// Multiplies in place using the full 4x4 product, preserving perspective terms. -void mat4MultiplyInPlace(Mat4& m, const Mat4& rhs) -{ - const Mat4 lhs = m; - m.fullMult(lhs, rhs); -} - +// PE 0x1007C4A0 (RendDX9.dll COMDAT copy of Vec3::operator-() const, hidden result, `retn 4`): +// -z, -y, -x formed before the x, y, z stores; drawFlare's four negations. void vec3Negate(Vec3& out, const Vec3& in) { const float z = -in.z; @@ -163,44 +142,15 @@ void vec3Add(Vec3& out, const Vec3& a, const Vec3& b) out.z = z; } -// sub_10077760 - `out = cross(a, b)`. `out` is the __thiscall `this`; the body never reads it. -void vec3Cross(Vec3& out, const Vec3& a, const Vec3& b) -{ - out.x = b.z * a.y - b.y * a.z; - out.y = b.x * a.z - a.x * b.z; - out.z = a.x * b.y - b.x * a.y; -} - -// sub_100777A0 - normalise in place, but only when the squared length is not already 1 (within -// FLT_EPSILON); a degenerate vector is zeroed and -20001 returned. The callers here discard it. -int vec3Normalize(Vec3& v) -{ - const float lengthSq = v.x * v.x + v.y * v.y + v.z * v.z; - if (std::fabs(static_cast(lengthSq) - 1.0) >= 1.1920929e-7) - { - if (std::fabs(static_cast(lengthSq)) < 1.1920929e-7) - { - v.x = 0.0f; - v.y = 0.0f; - v.z = 0.0f; - return -20001; - } - const double scale = 1.0 / std::sqrt(static_cast(lengthSq)); - v.x = static_cast(scale * v.x); - v.y = static_cast(scale * v.y); - v.z = static_cast(scale * v.z); - } - return 0; -} - -// sub_1000ED40, __stdcall. The high clamp is applied first and the compare is `>=`, so a NaN -// passes through both tests and comes back unchanged. Transcribed, not tidied. +// sub_1000ED40, __stdcall: `fcomi high; fcmovnb` then `fcomi low; fcmovb`. The high clamp is +// applied first; an unordered compare sets CF, so a NaN skips the high move and takes the low one +// and comes back as `low`. float clampFloat(float value, float low, float high) { double v = value; if (value >= static_cast(high)) v = high; - if (v < low) + if (!(v >= low)) return low; return static_cast(v); } @@ -211,13 +161,18 @@ float clampFloat(float value, float low, float high) // the xyz of its `fogColor` parameter. const Vec3* raShaderConstantsFogColor() { - return reinterpret_cast( - static_cast(dx9rend::g_raShaderConstants) + 268); + return reinterpret_cast(dx9rend::raShaderConstantsAt(268)); } // dx9rend::Query is private to QueryManager.cpp; these three bodies have no declaration there. -// Layout facts used below are that file's own: +0x08 IDirect3DQuery9*, +0x0C type, +0x10 the frame -// ordinal of the last accepted result, +0x14 the result itself, +0x18/+0x19 the two state bytes. +// Fields by retail offset (QueryManager.cpp's own layout): +0x04 refcount, +0x08 IDirect3DQuery9*, +// +0x0C type, +0x10 the frame ordinal of the last accepted result, +0x14 the result itself, +// +0x18/+0x19 the two state bytes. queryFieldAt maps each onto the native field. +template +T& queryField(void* query, unsigned int retailOffset) +{ + return *reinterpret_cast(dx9rend::queryFieldAt(query, retailOffset)); +} // sub_10004050 - read the occlusion result. Only a type-9 query with a live D3D object and the // "issued" byte set actually calls GetData; on S_OK it stamps the renderer's frame ordinal at +0x10, @@ -225,19 +180,19 @@ const Vec3* raShaderConstantsFogColor() // returned and, on a failed GetData, restored. int queryReadOcclusionResult(void* query) { - unsigned char* const self = static_cast(query); - IDirect3DQuery9* const d3d = *reinterpret_cast(self + 0x08); - int* const samples = reinterpret_cast(self + 0x14); - if (!d3d || *reinterpret_cast(self + 0x0C) != 9) + IDirect3DQuery9* const d3d = queryField(query, 0x08); + int* const samples = &queryField(query, 0x14); + if (!d3d || queryField(query, 0x0C) != 9) return -1; - if (self[0x19]) + unsigned char& issued = queryField(query, 0x19); + if (issued) { const int previous = *samples; if (d3d->GetData(samples, 4, 0) == D3D_OK) { - *reinterpret_cast(self + 0x10) = dx9rend::rendererFrameOrdinal(); + queryField(query, 0x10) = dx9rend::rendererFrameOrdinal(); const int result = *samples; - self[0x19] = 0; + issued = 0; return result; } *samples = previous; @@ -248,7 +203,7 @@ int queryReadOcclusionResult(void* query) // sub_10004120 - the frame ordinal stamped by the read above. unsigned int queryResultFrame(void* query) { - return *reinterpret_cast(static_cast(query) + 0x10); + return queryField(query, 0x10); } // sub_100041A0 - the begin/end toggle. It reads the pending result first, then, if nothing is @@ -256,18 +211,19 @@ unsigned int queryResultFrame(void* query) // is set, flips the toggle, and marks "issued" on the END half. Two calls bracket a draw. void queryToggleBeginEnd(void* query) { - unsigned char* const self = static_cast(query); queryReadOcclusionResult(query); - if (self[0x19]) + unsigned char& issued = queryField(query, 0x19); + if (issued) return; - IDirect3DQuery9* const d3d = *reinterpret_cast(self + 0x08); + IDirect3DQuery9* const d3d = queryField(query, 0x08); if (!d3d) return; - const bool wasEnd = (self[0x18] != 0); + unsigned char& toggle = queryField(query, 0x18); + const bool wasEnd = (toggle != 0); d3d->Issue(static_cast((wasEnd ? 0 : 1) + 1)); - self[0x18] = static_cast(wasEnd ? 0 : 1); + toggle = static_cast(wasEnd ? 0 : 1); if (wasEnd) - self[0x19] = 1; + issued = 1; } // Returns the sky light's stored direction. @@ -311,9 +267,49 @@ void submitIndexedGeometry(StaticMeshTemplate* template_, StaticMeshMaterial* ma } // anonymous namespace +// [CHOSEN, not recovered] Shared source entry points for the existing PE query bodies. +// PE 0x10004050. +int readRendererOcclusionQuery(void* query) +{ + return queryReadOcclusionResult(query); +} -// Initializes sky resources in member order. Flare material and +0x180 remain untouched. +// PE 0x10004120; the source bridge is [CHOSEN, not recovered]. +unsigned int rendererOcclusionQueryFrame(void* query) +{ + return queryResultFrame(query); +} + +// PE 0x10004130. Unreachable in 1.50: no code or data references. The number of frames since the +// stamped read: the renderer's frame ordinal minus the stamp at +0x10. +unsigned int rendererOcclusionQueryAge(void* query) +{ + return dx9rend::rendererFrameOrdinal() - queryField(query, 0x10); +} +// PE 0x10004150. Unreachable in 1.50: no code or data references. Whether the stamped read happened +// in the current frame. +bool rendererOcclusionQueryReadThisFrame(void* query) +{ + return queryField(query, 0x10) == dx9rend::rendererFrameOrdinal(); +} + +// PE 0x100040B0. Unreachable in 1.50: no code or data references. The event-query counterpart of the +// occlusion read: a type-8 query with a live D3D object and the "issued" byte set is polled with the +// flush flag and the sample dword returned (the HRESULT is ignored); any other query answers 1. +unsigned int rendererEventQueryResult(void* query) +{ + IDirect3DQuery9* const d3d = queryField(query, 0x08); + if (!d3d || queryField(query, 0x0C) != 8 || !queryField(query, 0x19)) + return 1; + unsigned int signalled = 0; + d3d->GetData(&signalled, 4, 1); + return signalled; +} + + +// PE 0x10138CB0 +// Initializes sky resources in member order. Flare material and +0x180 remain untouched. SkyDome::SkyDome() : m_renderPath(0) , m_refCount(1) @@ -349,26 +345,14 @@ SkyDome::SkyDome() , m_flareOcclusionInterval(32) , m_lightingBlend(0.0f) { - // The layout the whole file depends on, checked here because the members are private and the - // class is complete only inside its own bodies. + // The retail x86 layout, checked here because the members are private and the class is + // complete only inside its own bodies. Every access is by member name, so x64 keeps its own + // offsets. +#if defined(_M_IX86) static_assert(offsetof(SkyDome, m_renderPath) == 0x008, "listener path word at +0x08"); static_assert(offsetof(SkyDome, m_refCount) == 0x00C, "refcount at +0x0C"); static_assert(offsetof(SkyDome, m_skyTemplate) == 0x024, "skyTemplate string at +0x24"); - static_assert(offsetof(SkyDome, m_hasCloudLayer) == 0x078, "cloud flags at +0x78/+0x79"); - static_assert(offsetof(SkyDome, m_cloudLayerCount) == 0x07C, "cloud layer count at +0x7C"); - static_assert(offsetof(SkyDome, m_scrollDirection) == 0x0D4, "scroll direction at +0xD4"); - static_assert(offsetof(SkyDome, m_skyTemplatePtr) == 0x0E4, "sky template at +0xE4"); - static_assert(offsetof(SkyDome, m_effect) == 0x0FC, "effect at +0xFC"); - static_assert(offsetof(SkyDome, m_paramTexLayer0) == 0x100, "TEXLAYER0 at +0x100"); - static_assert(offsetof(SkyDome, m_paramLightingColor) == 0x12C, "LIGHTINGCOLOR at +0x12C"); - static_assert(offsetof(SkyDome, m_vertexDeclClouds) == 0x130, "cloud declaration at +0x130"); - static_assert(offsetof(SkyDome, m_texOffset) == 0x13C, "texture offset at +0x13C"); - static_assert(offsetof(SkyDome, m_skyMaterial) == 0x15C, "sky material at +0x15C"); - static_assert(offsetof(SkyDome, m_flareQuery) == 0x168, "occlusion query at +0x168"); - static_assert(offsetof(SkyDome, m_flareTextureName) == 0x184, "flare texture name at +0x184"); - static_assert(offsetof(SkyDome, m_flareDirection) == 0x1A0, "flare direction at +0x1A0"); - static_assert(offsetof(SkyDome, m_flareOcclusionInterval) == 0x1C0, "recheck interval at +0x1C0"); - static_assert(offsetof(SkyDome, m_lightingColor) == 0x1C8, "lighting colour at +0x1C8"); +#endif m_position.x = 0.0f; m_position.y = 0.0f; @@ -397,24 +381,24 @@ SkyDome::SkyDome() // releases. No null guard on the effect: the parameter lookups dereference it directly. m_effect = static_cast( dx9rend::shaderManagerGetEffect(dx9rend::g_shaderManager, "mods/xpack/shaders/SkyDome")); - m_paramTexLayer0 = dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("TEXLAYER0")); - m_paramTexLayer1 = dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("TEXLAYER1")); - m_paramTexLayer2 = dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("TEXLAYER2")); - m_paramTexOffset = dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("TEXOFFSET")); - m_paramTexOffset2 = dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("TEXOFFSET2")); + m_paramTexLayer0 = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("TEXLAYER0")); + m_paramTexLayer1 = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("TEXLAYER1")); + m_paramTexLayer2 = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("TEXLAYER2")); + m_paramTexOffset = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("TEXOFFSET")); + m_paramTexOffset2 = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("TEXOFFSET2")); m_paramCloudsFadeOutDist = - dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("CLOUDSFADEOUTDIST")); + dx9rend::effectGetShaderParameterTyped(m_effect, std::string("CLOUDSFADEOUTDIST")); m_paramCloudLerpFactors = - dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("CLOUDLERPFACTORS")); + dx9rend::effectGetShaderParameterTyped(m_effect, std::string("CLOUDLERPFACTORS")); m_paramWorldViewProjection = - dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("WorldViewProjection")); + dx9rend::effectGetShaderParameterTyped(m_effect, std::string("WorldViewProjection")); m_paramFlareParams = - dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("FLAREPARAMS")); - m_paramFogColor = dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("fogColor")); + dx9rend::effectGetShaderParameterTyped(m_effect, std::string("FLAREPARAMS")); + m_paramFogColor = dx9rend::effectGetShaderParameterTyped(m_effect, std::string("fogColor")); m_paramLightingBlend = - dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("LIGHTINGBLEND")); + dx9rend::effectGetShaderParameterTyped(m_effect, std::string("LIGHTINGBLEND")); m_paramLightingColor = - dx9rend::effectGetShaderParameterTyped(m_effect, vc71::string("LIGHTINGCOLOR")); + dx9rend::effectGetShaderParameterTyped(m_effect, std::string("LIGHTINGCOLOR")); // register before the first technique selection. dx9rend::registerRenderPathListener( @@ -494,12 +478,11 @@ SkyDome::SkyDome() } -// destruction - 0x10138530. The release order is the shipped one and it is NOT the reverse of +// PE 0x10138530: destruction. The release order is the shipped one and it is NOT the reverse of // construction: the two lighting parameters go first, then the occlusion query, then four textures // in the order sky, flare, cloud2, cloud, then the remaining ten parameters in a scrambled order, // then the effect, then the three templates (flare, sky, cloud), then the two vertex declarations, // then the listener unregister, then the strings. Transcribed exactly. - SkyDome::~SkyDome() { if (m_paramLightingColor) @@ -512,12 +495,10 @@ SkyDome::~SkyDome() // The Query has no release slot - QueryManager.cpp's three-slot table is {getRef, nullsub, // addRef}. Retail open-codes `if (!--refcount) { dtor; engineFree; }` here (sub_10003FA0 is // that destructor: it releases the IDirect3DQuery9 and drops the manager's counter). - int* const refCount = reinterpret_cast( - static_cast(m_flareQuery) + 4); + int* const refCount = &queryField(m_flareQuery, 0x04); if (--*refCount == 0) { - IDirect3DQuery9** const d3d = reinterpret_cast( - static_cast(m_flareQuery) + 8); + IDirect3DQuery9** const d3d = &queryField(m_flareQuery, 0x08); if (*d3d) { (*d3d)->Release(); @@ -592,6 +573,7 @@ int SkyDome::getRef() // ICF_getDwordAt0xC, 0x10051710 return m_refCount; } +// PE 0x1013A0C0 int SkyDome::release() { const int remaining = --m_refCount; @@ -603,6 +585,7 @@ int SkyDome::release() return remaining; } +// PE 0x1013A060 void* SkyDome::queryInterface(unsigned int iid) const { if (iid != 1) @@ -611,12 +594,10 @@ void* SkyDome::queryInterface(unsigned int iid) const } -// update - 0x10138790, primary +0x10. Renderer::renderFrame's frame-update call. - +// PE 0x10138790: update, primary +0x10. Renderer::renderFrame's frame-update call. // m_time is accumulated and never read by anything in the image; the two texture offsets scroll and // wrap. THE wrap IS NOT PER-component: either component reaching 16 subtracts 16 from both, so a // pair with very different speeds drifts. Shipped, reproduced. - void SkyDome::update(float deltaTime) { m_time = deltaTime + m_time; @@ -641,26 +622,31 @@ void SkyDome::update(float deltaTime) } +// PE 0x101388A0 void SkyDome::setPosition(const Vec3& position) { m_position = position; } +// PE 0x10138260 const Vec3& SkyDome::getPosition() const { return m_position; } +// PE 0x10138290 void SkyDome::setDomeScale(float scale) { m_domeScale = scale; } +// PE 0x101382A0 float SkyDome::getDomeScale() const { return m_domeScale; } +// PE 0x10138270 void SkyDome::setDomeRotation(float degrees) { m_domeRotation = degrees; @@ -671,6 +657,7 @@ float SkyDome::getDomeRotation() const return m_domeRotation; } +// PE 0x10138500 void SkyDome::setLightingBlend(float value) { m_lightingBlend = value; @@ -681,6 +668,7 @@ float SkyDome::getLightingBlend() const return m_lightingBlend; } +// PE 0x10138B20 void SkyDome::setLightingColor(const Vec3& color) { m_lightingColor = color; @@ -691,6 +679,7 @@ const Vec3& SkyDome::getLightingColor() const return m_lightingColor; } +// PE 0x10138AA0 void SkyDome::setScrollDirection(const Vec2& direction) { m_scrollDirection = direction; @@ -701,6 +690,7 @@ const Vec2& SkyDome::getScrollDirection() const return m_scrollDirection; } +// PE 0x10138AC0 void SkyDome::setScrollDirection2(const Vec2& direction) { m_scrollDirection2 = direction; @@ -711,6 +701,7 @@ const Vec2& SkyDome::getScrollDirection2() const return m_scrollDirection2; } +// PE 0x10138AE0 void SkyDome::setFadeCloudsDistances(const Vec2& distances) { m_fadeCloudsDistances = distances; @@ -721,6 +712,7 @@ const Vec2& SkyDome::getFadeCloudsDistances() const return m_fadeCloudsDistances; } +// PE 0x10138B00 void SkyDome::setCloudLerpFactors(const Vec2& factors) { m_cloudLerpFactors = factors; @@ -734,7 +726,8 @@ const Vec2& SkyDome::getCloudLerpFactors() const // Selects the first geometry/LOD/material of a loaded sky template. // Those containers and the material shader must exist; no guards are applied. -void SkyDome::setSkyTemplate(const vc71::string& name) +// PE 0x10138BD0 +void SkyDome::setSkyTemplate(const std::string& name) { m_skyTemplate = name; if (m_skyTemplatePtr) @@ -771,9 +764,9 @@ void SkyDome::setSkyTemplate(const vc71::string& name) setHasCloudLayer(true); } -// setFlareTemplate - 0x10138B50, primary +0x84. Same shape as setSkyTemplate minus the texture +// setFlareTemplate - PE 0x10138B50, primary +0x84. Same shape as setSkyTemplate minus the texture // harvesting, plus the flare-dirty reset before the lookup. -void SkyDome::setFlareTemplate(const vc71::string& name) +void SkyDome::setFlareTemplate(const std::string& name) { m_flareTemplate = name; if (m_flareTemplatePtr) @@ -789,22 +782,22 @@ void SkyDome::setFlareTemplate(const vc71::string& name) } } -const vc71::string& SkyDome::getSkyTemplate() const +const std::string& SkyDome::getSkyTemplate() const { return m_skyTemplate; } -const vc71::string& SkyDome::getFlareTemplate() const +const std::string& SkyDome::getFlareTemplate() const { return m_flareTemplate; } -// setCloudTemplate - 0x10138420, primary +0x4C. +// setCloudTemplate - PE 0x10138420, primary +0x4C. // The shipped body ignores its argument and assigns the // current skyTemplate string instead. `Skydome.cloudTemplate whatever` therefore resolves the SKY // template again. Reproduced; `name` is deliberately unused. -void SkyDome::setCloudTemplate(const vc71::string& name) +void SkyDome::setCloudTemplate(const std::string& name) { (void)name; m_cloudTemplate = m_skyTemplate; @@ -819,7 +812,7 @@ void SkyDome::setCloudTemplate(const vc71::string& name) } } -const vc71::string& SkyDome::getCloudTemplate() const +const std::string& SkyDome::getCloudTemplate() const { return m_cloudTemplate; } @@ -828,7 +821,8 @@ const vc71::string& SkyDome::getCloudTemplate() const // Texture setters release the previous texture, save the name, then load a replacement. // The loader modifies its own string copy. -void SkyDome::setSkyTexture(const vc71::string& name) +// PE 0x101388C0 +void SkyDome::setSkyTexture(const std::string& name) { if (m_skyTextureTex) dx9rend::textureReleaseRef(m_skyTextureTex); @@ -837,12 +831,13 @@ void SkyDome::setSkyTexture(const vc71::string& name) static_cast(dx9rend::textureManagerGetTexture(m_skyTexture)); } -const vc71::string& SkyDome::getSkyTexture() const +const std::string& SkyDome::getSkyTexture() const { return m_skyTexture; } -void SkyDome::setCloudTexture(const vc71::string& name) +// PE 0x101389E0 +void SkyDome::setCloudTexture(const std::string& name) { if (m_cloudTextureTex) dx9rend::textureReleaseRef(m_cloudTextureTex); @@ -851,12 +846,13 @@ void SkyDome::setCloudTexture(const vc71::string& name) static_cast(dx9rend::textureManagerGetTexture(m_cloudTexture)); } -const vc71::string& SkyDome::getCloudTexture() const +const std::string& SkyDome::getCloudTexture() const { return m_cloudTexture; } -void SkyDome::setCloudTexture2(const vc71::string& name) +// PE 0x10138A40 +void SkyDome::setCloudTexture2(const std::string& name) { if (m_cloudTexture2Tex) dx9rend::textureReleaseRef(m_cloudTexture2Tex); @@ -865,16 +861,16 @@ void SkyDome::setCloudTexture2(const vc71::string& name) static_cast(dx9rend::textureManagerGetTexture(m_cloudTexture2)); } -const vc71::string& SkyDome::getCloudTexture2() const +const std::string& SkyDome::getCloudTexture2() const { return m_cloudTexture2; } -// setFlareTexture - 0x10138920, primary +0x8C. The only texture setter with a shape of its own: +// setFlareTexture - PE 0x10138920, primary +0x8C. The only texture setter with a shape of its own: // an empty name simply clears m_hasFlare and does nothing else (the old wrapper is still released // first), and a non-empty name adopts the stock "flaresprite" geometry when no flare template has // been chosen yet - through the virtual +0x84 slot, not the member function. -void SkyDome::setFlareTexture(const vc71::string& name) +void SkyDome::setFlareTexture(const std::string& name) { if (m_flareTextureTex) dx9rend::textureReleaseRef(m_flareTextureTex); @@ -882,7 +878,7 @@ void SkyDome::setFlareTexture(const vc71::string& name) if (name.size() != 0) { if (!m_flareTemplatePtr) - setFlareTemplate(vc71::string("flaresprite")); + setFlareTemplate(std::string("flaresprite")); m_flareOcclusionReference = 1; m_flareTextureName = name; m_flareTextureTex = static_cast( @@ -897,14 +893,14 @@ void SkyDome::setFlareTexture(const vc71::string& name) } // getFlareTexture - 0x101382D0, primary +0x90. See the header: the read has a side effect. -const vc71::string& SkyDome::getFlareTexture() +const std::string& SkyDome::getFlareTexture() { m_flareOcclusionReference = 1; return m_flareTextureName; } -// setHasCloudLayer - 0x10138380, primary +0x3C. Clearing layer 1 also clears layer 2, and both +// setHasCloudLayer - PE 0x10138380, primary +0x3C. Clearing layer 1 also clears layer 2, and both // arms re-apply the current layer count so the technique follows. Both inner calls go through the // vtable in the shipped body. void SkyDome::setHasCloudLayer(bool value) @@ -920,7 +916,7 @@ bool SkyDome::getHasCloudLayer() const return m_hasCloudLayer != 0; } -// setHasCloudLayer2 - 0x101383C0, primary +0x44. Layer 2 cannot be enabled without layer 1. +// setHasCloudLayer2 - PE 0x101383C0, primary +0x44. Layer 2 cannot be enabled without layer 1. void SkyDome::setHasCloudLayer2(bool value) { if (value && getHasCloudLayer()) @@ -935,7 +931,7 @@ bool SkyDome::getHasCloudLayer2() const return m_hasCloudLayer2 != 0; } -// setCloudLayerCount - 0x101382F0, primary +0x94. Stores the count and picks the technique. Note +// setCloudLayerCount - PE 0x101382F0, primary +0x94. Stores the count and picks the technique. Note // there is NO getter slot for this field; the count is only observable through the technique. // The repeated getHasCloudLayer() dispatch in the second test is the shipped shape. void SkyDome::setCloudLayerCount(int count) @@ -943,20 +939,21 @@ void SkyDome::setCloudLayerCount(int count) m_cloudLayerCount = count; if (getHasCloudLayer() && getHasCloudLayer2() && m_cloudLayerCount > 1) { - dx9rend::effectSetTechniqueByName(m_effect, vc71::string("SkyDomeNV3xDualClouds")); + dx9rend::effectSetTechniqueByName(m_effect, std::string("SkyDomeNV3xDualClouds")); return; } if (!getHasCloudLayer() || !m_cloudLayerCount) { - dx9rend::effectSetTechniqueByName(m_effect, vc71::string("SkyDomeNV3xNoClouds")); + dx9rend::effectSetTechniqueByName(m_effect, std::string("SkyDomeNV3xNoClouds")); return; } - dx9rend::effectSetTechniqueByName(m_effect, vc71::string("SkyDomeNV3x")); + dx9rend::effectSetTechniqueByName(m_effect, std::string("SkyDomeNV3x")); } // dx9rend::RenderPathListener - secondary table 0x1021D390 +// PE 0x101384F0 void SkyDome::onRenderPathActivated(int path) { m_renderPath = path; @@ -976,20 +973,20 @@ int SkyDome::getCurrentRenderPath() const // 0x101A9A10 on the su return m_renderPath; } -vc71::string SkyDome::getRenderPathListenerName() const +// PE 0x1013A0A0 +std::string SkyDome::getRenderPathListenerName() const { - return vc71::string("SkyDome"); + return std::string("SkyDome"); } -// Draws the dome and clouds using the camera rotation and a temporary far plane of 2500. -// Dome scaling also scales its translation before projection. - #pragma warning(push) // C4700/C4701 are correct here and are silenced only because the defect they report is the shipped // behaviour this body exists to reproduce. See the waterLevel note inside. #pragma warning(disable : 4700 4701) +// PE 0x101392A0: draws the dome and clouds using the camera rotation and a temporary far plane of +// 2500. Dome scaling also scales its translation before projection. void SkyDome::onRenderPathNotification(int unused) { (void)unused; @@ -997,9 +994,10 @@ void SkyDome::onRenderPathNotification(int unused) if (!m_skyTemplatePtr) return; - // the once-only sub_10047F20("SkyDome") stat - // registration (guard bit 1 of g_domeOnceFlags) and the sub_10046EE0/sub_10046EF0 bracket on - // unk_1025D168. Stat-only scaffolding; not reproduced. See the file header. + // The "SkyDome" profiler (object at PE 0x1025D168, guard bit 0 of PE 0x1025D3D0) registers on + // first use after the null test above and is closed on the single exit below. + static dx9rend::QueueProfiler profiler(std::string("SkyDome")); + profiler.begin(); m_paramLightingBlend->setFloat(m_lightingBlend); m_paramLightingColor->setValue(&m_lightingColor, 0); @@ -1027,25 +1025,25 @@ void SkyDome::onRenderPathNotification(int unused) if (cameraPosition->y < waterLevel) { - dx9rend::effectSetTechniqueByName(m_effect, vc71::string("SkyDomeUnderWater")); + dx9rend::effectSetTechniqueByName(m_effect, std::string("SkyDomeUnderWater")); } else if (getHasCloudLayer() && getHasCloudLayer2() && m_cloudLayerCount > 1) { - dx9rend::effectSetTechniqueByName(m_effect, vc71::string("SkyDomeNV3xDualClouds")); + dx9rend::effectSetTechniqueByName(m_effect, std::string("SkyDomeNV3xDualClouds")); } else if (getHasCloudLayer() && m_cloudLayerCount) { if (m_lightingBlend > 0.0f) - dx9rend::effectSetTechniqueByName(m_effect, vc71::string("SkyDomeNV3xLit")); + dx9rend::effectSetTechniqueByName(m_effect, std::string("SkyDomeNV3xLit")); else - dx9rend::effectSetTechniqueByName(m_effect, vc71::string("SkyDomeNV3x")); + dx9rend::effectSetTechniqueByName(m_effect, std::string("SkyDomeNV3x")); } else { if (m_lightingBlend > 0.0f) - dx9rend::effectSetTechniqueByName(m_effect, vc71::string("SkyDomeNV3xNoCloudsLit")); + dx9rend::effectSetTechniqueByName(m_effect, std::string("SkyDomeNV3xNoCloudsLit")); else - dx9rend::effectSetTechniqueByName(m_effect, vc71::string("SkyDomeNV3xNoClouds")); + dx9rend::effectSetTechniqueByName(m_effect, std::string("SkyDomeNV3xNoClouds")); } // guard bit 2 zeroes the scratch block that is never read. See the declaration. @@ -1071,11 +1069,11 @@ void SkyDome::onRenderPathNotification(int unused) scale.x = m_domeScale; scale.y = m_domeScale; scale.z = m_domeScale; - mat4ScaleColumns(world, scale); + rendmath::scaleColumns(world, scale); const Mat4 inverseView = *drawView->getInverseViewMatrixPtr(); const Mat4 worldBeforeRotate = world; - world.rotMult(worldBeforeRotate, inverseView); + rendmath::rotMult(world, worldBeforeRotate, inverseView); // PE 0x10078180 const float savedFarPlane = drawView->getFarPlane(); drawView->setFarPlane(kSkyFarPlane); @@ -1164,7 +1162,7 @@ void SkyDome::onRenderPathNotification(int unused) dx9rend::effectEnd(m_effect); dx9rend::stateManagerPop(); - // the profiler scope close; see above. + dx9rend::QueueProfiler::end(); } #pragma warning(pop) @@ -1189,9 +1187,9 @@ void SkyDome::submitFlarePass() } +// PE 0x10139900: primary table 0x1021D3A8 +0xA8. // Mode 1 draws flare occlusion, mode 2 draws the visible flare; nonpositive modes do nothing. // The underwater early return leaves the temporary far plane in place. - void SkyDome::drawFlare(int mode) { // guard bit 1 of g_flareOnceFlags initialises the constant that is never read. @@ -1209,8 +1207,11 @@ void SkyDome::drawFlare(int mode) flareDirection.y = 0.0f; flareDirection.z = 0.0f; - // guard bit 2 plus the sub_10046EE0 bracket on unk_1025D3D8. The - // same stat-only scaffolding as the dome draw; not reproduced. + // The second "SkyDome" profiler (object at PE 0x1025D3D8, guard bit 1 of PE 0x1025D644) begins + // here. Shipped defect: only the mode 1 occlusion path closes it; the underwater return and the + // mode 2 return leave it current. + static dx9rend::QueueProfiler profiler(std::string("SkyDome")); + profiler.begin(); if (!m_flareQuery) m_flareQuery = dx9rend::queryManagerCreateQuery(9); // D3DQUERYTYPE_OCCLUSION @@ -1233,7 +1234,8 @@ void SkyDome::drawFlare(int mode) // an explicitly configured flare direction wins; otherwise the sky light supplies // one. The test is the SUM of the three components against 0.01, evaluated z + y + x, and a // missing sky light leaves the direction at (0,0,0). - if (m_flareDirection.z + m_flareDirection.y + m_flareDirection.x >= kFlareDirectionEpsilon) + // (the retail branch is taken for an unordered sum too, hence the negated less-than) + if (!(m_flareDirection.z + m_flareDirection.y + m_flareDirection.x < kFlareDirectionEpsilon)) { Vec3 negated; vec3Negate(negated, m_flareDirection); @@ -1247,7 +1249,8 @@ void SkyDome::drawFlare(int mode) } // the billboard basis. Rows 0/1/2 of flareWorld are the quad's axes. - Mat4 flareWorld = Mat4::getIdentity(); + Mat4 flareWorld; + rendmath::constructIdentity(flareWorld); // 0x10139A97 Vec3* const basisX = reinterpret_cast(&flareWorld.m[0]); Vec3* const basisY = reinterpret_cast(&flareWorld.m[4]); Vec3* const basisZ = reinterpret_cast(&flareWorld.m[8]); @@ -1259,8 +1262,8 @@ void SkyDome::drawFlare(int mode) basisY->y = 1.0f; basisY->z = 0.0f; vec3Negate(*basisZ, *reinterpret_cast(&view->getViewMatrixPtr()->m[8])); - vec3Cross(*basisX, *basisY, *basisZ); - vec3Cross(*basisY, *basisZ, *basisX); + rendmath::cross(*basisX, *basisY, *basisZ); + rendmath::cross(*basisY, *basisZ, *basisX); } else { @@ -1311,14 +1314,14 @@ void SkyDome::drawFlare(int mode) // The far plane is forced after the view-projection multiply here, unlike the dome draw, // which forces it before fetching its projection matrix. Shipped order, kept. const Mat4 viewProjection = *view->getViewProjectionMatrixPtr(); - mat4MultiplyInPlace(flareWorld, viewProjection); + rendmath::multiplyAssign(flareWorld, viewProjection); // PE 0x100A2F00 const float savedFarPlane = view->getFarPlane(); view->setFarPlane(kSkyFarPlane); m_paramWorldViewProjection->setValue(&flareWorld, 0); if (mode == 2) { - dx9rend::effectSetTechniqueByName(m_effect, vc71::string("SkyDomeSunFlare")); + dx9rend::effectSetTechniqueByName(m_effect, std::string("SkyDomeSunFlare")); Vec4 flareParams = { 0.0f, 0.0f, 0.0f, 0.0f }; @@ -1326,7 +1329,7 @@ void SkyDome::drawFlare(int mode) toFlare.x = flarePosition.x - cameraPosition.x; toFlare.y = flarePosition.y - cameraPosition.y; toFlare.z = flarePosition.z - cameraPosition.z; - vec3Normalize(toFlare); + rendmath::normalize(toFlare); const Mat4* const facingMatrix = view->getViewMatrixPtr(); const float facing = toFlare.z * facingMatrix->m[10] + @@ -1380,16 +1383,16 @@ void SkyDome::drawFlare(int mode) if (mode == 1 && m_flareOcclusionPending) { if (m_flareOcclusionFrame % m_flareOcclusionInterval) - dx9rend::effectSetTechniqueByName(m_effect, vc71::string("SkyDomeFlareOcclude")); + dx9rend::effectSetTechniqueByName(m_effect, std::string("SkyDomeFlareOcclude")); else - dx9rend::effectSetTechniqueByName(m_effect, vc71::string("SkyDomeFlareOccludeCheck")); + dx9rend::effectSetTechniqueByName(m_effect, std::string("SkyDomeFlareOccludeCheck")); queryToggleBeginEnd(m_flareQuery); submitFlarePass(); queryToggleBeginEnd(m_flareQuery); m_flareOcclusionPending = 0; - // the profiler scope close, on this path only. Not reproduced. + dx9rend::QueueProfiler::end(); } view->setFarPlane(savedFarPlane); @@ -1402,7 +1405,7 @@ IBase* __fastcall createSkyDome(unsigned int iid, IBase* outer) { if (outer) return 0; - void* const storage = ::renddx9abi::engineAlloc(0x1D4); + void* const storage = ::renddx9abi::engineAlloc(sizeof(SkyDome)); SkyDome* const self = storage ? new (storage) SkyDome() : 0; void* const itf = self->queryInterface(iid); if (!itf) diff --git a/Code/BF2/Geom/SkyDome.h b/Code/BF2/Geom/SkyDome.h index 7fdf7b2ba..8c33e4658 100644 --- a/Code/BF2/Geom/SkyDome.h +++ b/Code/BF2/Geom/SkyDome.h @@ -7,7 +7,7 @@ #define BF2_GEOM_SKYDOME_H #include "../../RendDX9Abi/HfeAbi.h" -#include "../../RendDX9Abi/Vc71String.h" +#include #include "../Core/IBase.h" #include "../Math/Vec3.h" #include "../RendDX9/RendDX9Base.h" @@ -51,20 +51,20 @@ class SkyDome : public IBase, public dx9rend::RenderPathListener virtual float getDomeScale() const; // +0x20 virtual void setDomeRotation(float degrees); // +0x24 virtual float getDomeRotation() const; // +0x28 - virtual void setSkyTemplate(const vc71::string& name); // +0x2C - virtual const vc71::string& getSkyTemplate() const; // +0x30 - virtual void setSkyTexture(const vc71::string& name); // +0x34 - virtual const vc71::string& getSkyTexture() const; // +0x38 + virtual void setSkyTemplate(const std::string& name); // +0x2C + virtual const std::string& getSkyTemplate() const; // +0x30 + virtual void setSkyTexture(const std::string& name); // +0x34 + virtual const std::string& getSkyTexture() const; // +0x38 virtual void setHasCloudLayer(bool value); // +0x3C virtual bool getHasCloudLayer() const; // +0x40 virtual void setHasCloudLayer2(bool value); // +0x44 virtual bool getHasCloudLayer2() const; // +0x48 - virtual void setCloudTemplate(const vc71::string& name); // +0x4C - virtual const vc71::string& getCloudTemplate() const; // +0x50 - virtual void setCloudTexture(const vc71::string& name); // +0x54 - virtual const vc71::string& getCloudTexture() const; // +0x58 - virtual void setCloudTexture2(const vc71::string& name); // +0x5C - virtual const vc71::string& getCloudTexture2() const; // +0x60 + virtual void setCloudTemplate(const std::string& name); // +0x4C + virtual const std::string& getCloudTemplate() const; // +0x50 + virtual void setCloudTexture(const std::string& name); // +0x54 + virtual const std::string& getCloudTexture() const; // +0x58 + virtual void setCloudTexture2(const std::string& name); // +0x5C + virtual const std::string& getCloudTexture2() const; // +0x60 virtual void setScrollDirection(const Vec2& direction); // +0x64 virtual const Vec2& getScrollDirection() const; // +0x68 virtual void setScrollDirection2(const Vec2& direction); // +0x6C @@ -73,20 +73,20 @@ class SkyDome : public IBase, public dx9rend::RenderPathListener virtual const Vec2& getFadeCloudsDistances() const; // +0x78 virtual void setCloudLerpFactors(const Vec2& factors); // +0x7C virtual const Vec2& getCloudLerpFactors() const; // +0x80 - virtual void setFlareTemplate(const vc71::string& name); // +0x84 - virtual const vc71::string& getFlareTemplate() const; // +0x88 - virtual void setFlareTexture(const vc71::string& name); // +0x8C + virtual void setFlareTemplate(const std::string& name); // +0x84 + virtual const std::string& getFlareTemplate() const; // +0x88 + virtual void setFlareTexture(const std::string& name); // +0x8C // NOT const: 0x101382D0 stores 1 // into m_flareOcclusionReference (+0x1AC) before returning the string, which resets the flare's // occlusion ratio to "fully visible" - i.e. it marks the flare state dirty. A getter with a // side effect; the console's flareTexture read therefore has an observable effect on rendering. - virtual const vc71::string& getFlareTexture(); // +0x90 + virtual const std::string& getFlareTexture(); // +0x90 virtual void setCloudLayerCount(int count); // +0x94 virtual void setLightingBlend(float value); // +0x98 virtual float getLightingBlend() const; // +0x9C virtual void setLightingColor(const Vec3& color); // +0xA0 virtual const Vec3& getLightingColor() const; // +0xA4 - // Renderer::renderFrame (0x1002F7E0) calls this three times a frame with 0, 1 and 2. + // PE 0x10139900. Renderer::renderFrame calls this three times a frame with 0, 1 and 2. virtual void drawFlare(int mode); // +0xA8 // dx9rend::RenderPathListener, secondary table 0x1021D390 @@ -99,7 +99,7 @@ class SkyDome : public IBase, public dx9rend::RenderPathListener // argument (`retn 4`) and never reads it; the parameter is kept so the arity matches. virtual void onRenderPathNotification(int unused); // +0x0C virtual int getCurrentRenderPath() const; // +0x10 - virtual vc71::string getRenderPathListenerName() const; // +0x14 + virtual std::string getRenderPathListenerName() const; // +0x14 private: // Retail inlines this bind-and-submit sequence at both of drawFlare's two draw sites @@ -115,16 +115,16 @@ class SkyDome : public IBase, public dx9rend::RenderPathListener Vec3 m_position; // +0x010 float m_domeScale; // +0x01C float m_domeRotation; // +0x020 - vc71::string m_skyTemplate; // +0x024 - vc71::string m_flareTemplate; // +0x040 - vc71::string m_skyTexture; // +0x05C + std::string m_skyTemplate; // +0x024 + std::string m_flareTemplate; // +0x040 + std::string m_skyTexture; // +0x05C unsigned char m_hasCloudLayer; // +0x078 unsigned char m_hasCloudLayer2; // +0x079 unsigned char m_pad07A[2]; int m_cloudLayerCount; // +0x07C - vc71::string m_cloudTemplate; // +0x080 - vc71::string m_cloudTexture; // +0x09C - vc71::string m_cloudTexture2; // +0x0B8 + std::string m_cloudTemplate; // +0x080 + std::string m_cloudTexture; // +0x09C + std::string m_cloudTexture2; // +0x0B8 Vec2 m_scrollDirection; // +0x0D4 Vec2 m_scrollDirection2; // +0x0DC IGeometryTemplate* m_skyTemplatePtr; // +0x0E4 @@ -163,7 +163,7 @@ class SkyDome : public IBase, public dx9rend::RenderPathListener float m_flareAngleFadeMul; // +0x178 dx9rend::EngineTexture* m_flareTextureTex; // +0x17C int m_dword180; // +0x180 uninitialised, [UNRESOLVED] - vc71::string m_flareTextureName; // +0x184 + std::string m_flareTextureName; // +0x184 Vec3 m_flareDirection; // +0x1A0 int m_flareOcclusionReference; // +0x1AC int m_flareOcclusionVisible; // +0x1B0 @@ -186,9 +186,9 @@ class SkyDome : public IBase, public dx9rend::RenderPathListener void setFlareFadeMulField(float value) { m_flareFadeMul = value; } }; -#if defined(_M_IX86) -static_assert(sizeof(SkyDome) == 0x1D4, "RefFactory_geom_SkyDome allocates 0x1D4 - see 0x100B0960"); -#endif +// Shared borrowed-query reads; neither operation changes ownership. +int readRendererOcclusionQuery(void* query); +unsigned int rendererOcclusionQueryFrame(void* query); // dword_1024B918 in RendDX9.dll. ModuleGeom.cpp owns the definition; SkyDomeConsole.cpp and the // renderer's three guarded calls read it. diff --git a/Code/BF2/Geom/SkyDomeConsole.cpp b/Code/BF2/Geom/SkyDomeConsole.cpp index 39f052f7e..068d4c01a 100644 --- a/Code/BF2/Geom/SkyDomeConsole.cpp +++ b/Code/BF2/Geom/SkyDomeConsole.cpp @@ -1,16 +1,14 @@ // Sky-dome console properties, available while the singleton exists. -// [RETIRE-WHEN: skydome-typed-owner] Retired: bindings use typed methods and field accessors. #ifdef BF2_IMAGE_RENDDX9 #include "../../RendDX9Abi/PluginAbi.h" -#if BF2_PLUGIN_ABI_NATIVE #include "SkyDome.h" #include "../../RendDX9Abi/HfeAbi.h" -#include "../../RendDX9Abi/Vc71String.h" +#include #include "../Core/ConsoleObjectMacro.h" #include "../Core/ConsoleObjects.h" #include "../Math/Vec3.h" @@ -33,20 +31,27 @@ inline SkyDome* skyDome() return static_cast(g_SkyDome); } -// The console boundary is the only place a string changes representation: the host console speaks -// this toolchain's std::string, the object keeps the 28-byte VC7.1 one. -inline std::string toConsole(const vc71::string& value) +// The console boundary copies the object's string for the host console (both are std::string). +inline std::string toConsole(const std::string& value) { return std::string(value.c_str()); } -inline vc71::string toRetail(const std::string& value) +inline std::string toRetail(const std::string& value) { - return vc71::string(value.c_str()); + return std::string(value.c_str()); } // Small named adapters keep the generated bindings readable. The retail slot each one used to // reach by offset is noted beside it. +// PE 0x100B7767: primary +0x18 reads, +0x14 writes. +Vec3 getDomePosition() { return skyDome()->getPosition(); } +void setDomePosition(const Vec3& value) { skyDome()->setPosition(value); } + +// PE 0x100B7895: primary +0x20 reads, +0x1C writes. +float getDomeSize() { return skyDome()->getDomeScale(); } +void setDomeSize(float value) { skyDome()->setDomeScale(value); } + float getDomeRotation() { return skyDome()->getDomeRotation(); } // +0x28 void setDomeRotation(float value) { skyDome()->setDomeRotation(value); } // +0x24 @@ -73,7 +78,9 @@ void setFlareTexture(const std::string& value) // The three direct-field properties. Retail has no vtable slot for any of them; the class exposes // typed accessors so this file does not have to know the layout. +// PE 0x100B7F99 Vec3 getFlareDirection() { return skyDome()->flareDirection(); } // field +0x1A0 +// PE 0x100B7F7B void setFlareDirection(const Vec3& value) { skyDome()->setFlareDirectionField(value); } float getFlareFadeAdd() { return skyDome()->flareFadeAdd(); } // field +0x16C @@ -135,45 +142,70 @@ void setLightingColor(const Vec3& value) { skyDome()->setLightingColor(value); } BF2_CONSOLE_OBJECT("skyDome", 2, 0) +// PE 0x100B766F, 0x100B76F4 +BF2_CONSOLE_PROPERTY_FN(domePosition, Vec3, skyDome() != 0, + getDomePosition(), setDomePosition, kSkyDomeConsoleTag) +// PE 0x100B77D7, 0x100B7848 +BF2_CONSOLE_PROPERTY_FN(domeSize, float, skyDome() != 0, + getDomeSize(), setDomeSize, kSkyDomeConsoleTag) +// PE 0x100B78DE, 0x100B794F BF2_CONSOLE_PROPERTY_FN(domeRotation, float, skyDome() != 0, getDomeRotation(), setDomeRotation, kSkyDomeConsoleTag) +// PE 0x100B79E5, 0x100B7ACC, 0x100B7A62, 0x100B877E, 0x100C184A, 0x100B8B79: constructor, argument conversion, executor, result formatting, range pair (shared base body), range strings (shared base body). BF2_CONSOLE_PROPERTY_FN(skyTemplate, std::string, skyDome() != 0, getSkyTemplate(), setSkyTemplate, kSkyDomeConsoleTag) +// PE 0x100B7B41, 0x100B7C2E, 0x100B7BBE: constructor, argument conversion, executor. BF2_CONSOLE_PROPERTY_FN(flareTemplate, std::string, skyDome() != 0, getFlareTemplate(), setFlareTemplate, kSkyDomeConsoleTag) +// PE 0x100B7CA3, 0x100B7D90, 0x100B7D20: constructor, argument conversion, executor. BF2_CONSOLE_PROPERTY_FN(flareTexture, std::string, skyDome() != 0, getFlareTexture(), setFlareTexture, kSkyDomeConsoleTag) +// PE 0x100B7E05, 0x100B7E8A, 0x100B7EFD, 0x100BD635: constructor, argument conversion, executor, result formatting. BF2_CONSOLE_PROPERTY_FN(flareDirection, Vec3, skyDome() != 0, getFlareDirection(), setFlareDirection, kSkyDomeConsoleTag) +// PE 0x100B7FB9, 0x100B802A: constructor, argument conversion. BF2_CONSOLE_PROPERTY_FN(flareFadeAdd, float, skyDome() != 0, getFlareFadeAdd(), setFlareFadeAdd, kSkyDomeConsoleTag) +// PE 0x100B80BD, 0x100B812E: constructor, argument conversion. BF2_CONSOLE_PROPERTY_FN(flareFadeMul, float, skyDome() != 0, getFlareFadeMul(), setFlareFadeMul, kSkyDomeConsoleTag) +// PE 0x100B81C1, 0x100B82A8, 0x100B823E: constructor, argument conversion, executor. BF2_CONSOLE_PROPERTY_FN(skyTexture, std::string, skyDome() != 0, getSkyTexture(), setSkyTexture, kSkyDomeConsoleTag) +// PE 0x100B831D, 0x100B838E, 0x100B83DB, 0x100BB593: constructor, argument conversion, executor, result formatting. BF2_CONSOLE_PROPERTY_FN(hasCloudLayer, bool, skyDome() != 0, getHasCloudLayer(), setHasCloudLayer, kSkyDomeConsoleTag) +// PE 0x100B842C, 0x100B849D, 0x100B84EA: constructor, argument conversion, executor. BF2_CONSOLE_PROPERTY_FN(hasCloudLayer2, bool, skyDome() != 0, getHasCloudLayer2(), setHasCloudLayer2, kSkyDomeConsoleTag) // Retail 0x10138420 ignores this setter's argument and copies the current skyTemplate string. // Calling SkyDome::setCloudTemplate, rather than assigning the field here, preserves that shipped // defect - the class reproduces it, so the binding does not have to know about it. +// PE 0x100B853B, 0x100B8622, 0x100B85B8: constructor, argument conversion, executor. BF2_CONSOLE_PROPERTY_FN(cloudTemplate, std::string, skyDome() != 0, getCloudTemplate(), setCloudTemplate, kSkyDomeConsoleTag) +// PE 0x100B8697, 0x100B87DA, 0x100B8714: constructor, argument conversion, executor. BF2_CONSOLE_PROPERTY_FN(cloudTexture, std::string, skyDome() != 0, getCloudTexture(), setCloudTexture, kSkyDomeConsoleTag) +// PE 0x100B884F, 0x100B8936, 0x100B88CC: constructor, argument conversion, executor. BF2_CONSOLE_PROPERTY_FN(cloudTexture2, std::string, skyDome() != 0, getCloudTexture2(), setCloudTexture2, kSkyDomeConsoleTag) +// PE 0x100B89AB, 0x100B8A2B, 0x100B8A96, 0x100BF69F: constructor, argument conversion, executor, result formatting. BF2_CONSOLE_PROPERTY_FN(scrollDirection, Vec2, skyDome() != 0, getScrollDirection(), setScrollDirection, kSkyDomeConsoleTag) +// PE 0x100B8AF9, 0x100B8BC5, 0x100B8C30: constructor, argument conversion, executor. BF2_CONSOLE_PROPERTY_FN(scrollDirection2, Vec2, skyDome() != 0, getScrollDirection2(), setScrollDirection2, kSkyDomeConsoleTag) +// PE 0x100B8C93, 0x100B8D13, 0x100B8D7E: constructor, argument conversion, executor. BF2_CONSOLE_PROPERTY_FN(fadeCloudsDistances, Vec2, skyDome() != 0, getFadeCloudsDistances(), setFadeCloudsDistances, kSkyDomeConsoleTag) +// PE 0x100B8DE1, 0x100B8E61, 0x100B8ECC: constructor, argument conversion, executor. BF2_CONSOLE_PROPERTY_FN(cloudLerpFactors, Vec2, skyDome() != 0, getCloudLerpFactors(), setCloudLerpFactors, kSkyDomeConsoleTag) +// PE 0x100B8F32, 0x100B8FA3: constructor, argument conversion. BF2_CONSOLE_PROPERTY_FN(lightingBlend, float, skyDome() != 0, getLightingBlend(), setLightingBlend, kSkyDomeConsoleTag) +// PE 0x100B903F, 0x100B90D0, 0x100B9143: constructor, argument conversion, executor. BF2_CONSOLE_PROPERTY_FN(lightingColor, Vec3, skyDome() != 0, getLightingColor(), setLightingColor, kSkyDomeConsoleTag) @@ -195,5 +227,4 @@ bool unregisterSkyDomeConsoleObjects() } // namespace hfe } // namespace dice -#endif // BF2_PLUGIN_ABI_NATIVE #endif // BF2_IMAGE_RENDDX9 diff --git a/Code/BF2/Geom/StaticMesh.cpp b/Code/BF2/Geom/StaticMesh.cpp index f7cbd0fde..8c9d8c52b 100644 --- a/Code/BF2/Geom/StaticMesh.cpp +++ b/Code/BF2/Geom/StaticMesh.cpp @@ -1,24 +1,32 @@ // Static-mesh instance rendering, visibility and shadow state. +#include "../../RendDX9Abi/ThunkAbi.h" #include "StaticMesh.h" +#include "../Core/StringUtil.h" // formatString (sub_10074AB0) #ifdef BF2_IMAGE_RENDDX9 +#if !defined(_MSC_VER) +// [CHOSEN, not recovered] Compiler-typed native table entries. +#include "../../RendDX9Abi/NativeVtable.h" +#include "LightmapGeneration/ILightSampleable.h" +#endif #include "../../RendDX9Abi/BfMemory.h" // engineAlloc - the map sentinel -#include "../../RendDX9Abi/D3dxEffect.h" // D3dxCommitChangesFn - the shadow draw's commit +#include "../../RendDX9Abi/D3dx9Sdk.h" // ID3DXEffect - the shadow draw's commit #include "../../RendDX9Abi/EngineFile.h" // engineFileExists / readEngineFile #include "../../RendDX9Abi/Frontier.h" #include "../../RendDX9Abi/PluginEntry.h" // classManager - the WindManager lookup -#include "../../RendDX9Abi/Vc71Map.h" // the int-keyed lightmap-cache node #include "../Core/Ids.h" // IID_IGeometry / IRenderable / ILightSampleable #include "../Game/Main/IVideoOptions.h" #include "../Game/Objects/IObject.h" // the owner's getIsOvergrowth #include "../Game/Objects/ObjectLayoutAccess.h" // staticMeshRootParent's IObject prefix fields #include "../Game/Objects/Visual/LightSource.h" #include "../Math/Frustum.h" +#include "../RendDX9/RendDX9Math.h" // the RendDX9.dll Math copies #include "../Math/Plane3.h" #include "../Math/Vec3.h" +#include "../Platform/X87Compat.h" #include "../RendDX9/Ra/RaShader.h" // raObjectParametersConstruct, RenderQueueEntry #include "../RendDX9/RendDX9Base.h" #include "../RendDX9/Texture.h" // textureReleaseRef - the lightmap cache @@ -27,9 +35,11 @@ #include "../Scene/Object/WindManager.h" // the vegetation arm's wind speed #include "LightmapGeneration/ILightSampleable.h" // the +0x30 table's interface (ILightSampling) #include "LightmapGeneration/MeshLightSampling.h" // the sampler createLightSampler makes +#include "BoxCorners.h" // the eight-corner material box test #include "MeshTemplate.h" // MeshBounds / meshBoundsFinalize #include "StaticMeshRenderer.h" // the singleton's flags, counters and atlases #include "StaticMeshTemplate.h" // the tail gate reads MeshTemplate::m_loaded +#include "Terrain.h" // the water arm's techniques and envmap #include "XpLightManager.h" // the light gather and the five colour getters #include @@ -42,6 +52,11 @@ namespace dice { namespace hfe { namespace dx9rend { +namespace Ra { unsigned char effectManagerFlag40(); } +// BufferManager.cpp. +void* indexBufferLock(void* wrapper, unsigned int offsetIndices, unsigned int countIndices, + unsigned int flags); +bool indexBufferUnlock(void* wrapper); // RendDX9Init.cpp, dword_1023B970. Declared per-TU here exactly as DecalManager.cpp and // HemiMapManager.cpp declare it; +0x54 is getFrameOrdinal, which MeshTemplate.cpp also documents. extern void* g_rendererBase; @@ -62,7 +77,7 @@ bool rendererIsExpansionPack(); // BufferManager.cpp - declared here the way StaticMeshMaterial.cpp declares the same entry points. extern void* g_bufferManager; // dword_1023B978 void* createVertexBuffer(void* bufferManager, unsigned int count, unsigned int stride, - const vc71::string& name, unsigned int usage); + const std::string& name, unsigned int usage); void* vertexBufferLock(void* wrapper, unsigned int offsetVerts, unsigned int countVerts, unsigned int flags); bool vertexBufferUnlock(void* wrapper); @@ -77,45 +92,40 @@ void rendererDrawIndexedPrimitive(unsigned int primCount, unsigned int type, int unsigned int startIndex); void stateManagerPush(); void stateManagerPop(); +void* effectD3dxHandle(void* effect); // Effect.cpp - the wrapper's +0x08 ID3DXEffect* } namespace geom { extern LightManager* g_LightManager; // XpLightManager.cpp, dword_1024B914 extern IBase* g_StaticMeshRenderer; // StaticMeshRenderer.cpp, dword_1024B8F8 +extern IBase* g_Terrain; // ModuleGeom.cpp, dword_1024B930 namespace { // The primary table has 63 slots; ILightSampleable has seven. // Explicit tables preserve the ABI while remaining interface signatures are unknown. -void __fastcall sm_drawSilhouette(void* self, void*, void* unused, int legacyArm) +void RD9_THUNK sm_drawSilhouette(void* self RD9_THUNK_EDX, void* unused, int legacyArm) { static_cast(self)->drawSilhouette(unused, legacyArm); } // +0x20, the shadow-map draw. `retn 18h`. -void __fastcall sm_drawShadowMap(void* self, void*, void* caster, unsigned int a2, +void RD9_THUNK sm_drawShadowMap(void* self RD9_THUNK_EDX, void* caster, unsigned int a2, unsigned int a3, unsigned int a4, unsigned int a5, unsigned int a6) { static_cast(self)->drawShadowMap(caster, a2, a3, a4, a5, a6); } -// The draw's expansion-pack arm, sub_100FE130 (0x117F B). Only reached when -// Renderer::isExpansionPack(), which vanilla BF2 1.50 never answers true; the vanilla arm is -// written in full below. [RETIRE-WHEN: RW-staticmesh-xpack-draw] -void staticMeshDrawExpansionStop(void* self) -{ - RD9_FRONTIER_AT("dice::hfe::geom::StaticMesh::drawExpansion (sub_100FE130, the expansion-pack " - "arm of slot +0x18; unreachable on vanilla 1.50)", self, 0x18); -} +void staticMeshDrawExpansion(void* self); // the written slots, as the thin adapters the tables need // +0x34, the scalar deleting destructor. Bit 0 of the flag means "and // free the storage", which is the MSVC convention release() relies on. -void* __fastcall sm_deletingDestructor(void* self, void*, int flags) +void* RD9_THUNK sm_deletingDestructor(void* self RD9_THUNK_EDX, int flags) { static_cast(self)->~StaticMesh(); if ((flags & 1) != 0) @@ -123,89 +133,89 @@ void* __fastcall sm_deletingDestructor(void* self, void*, int flags) return self; } -int __fastcall sm_addRef(void* self, void*) +int RD9_THUNK sm_addRef(void* self RD9_THUNK_EDX) { return static_cast(self)->addRef(); } -int __fastcall sm_getRef(void* self, void*) +int RD9_THUNK sm_getRef(void* self RD9_THUNK_EDX) { return static_cast(self)->getRef(); } -int __fastcall sm_release(void* self, void*) +int RD9_THUNK sm_release(void* self RD9_THUNK_EDX) { return static_cast(self)->release(); } -void* __fastcall sm_queryInterface(void* self, void*, unsigned int iid) +void* RD9_THUNK sm_queryInterface(void* self RD9_THUNK_EDX, unsigned int iid) { return static_cast(self)->queryInterface(iid); } // +0x18, the draw. `retn 0Ch`: renderView, occluder, flag. -void __fastcall sm_draw(void* self, void*, void* renderView, void* occluder, int flag) +void RD9_THUNK sm_draw(void* self RD9_THUNK_EDX, void* renderView, void* occluder, int flag) { static_cast(self)->draw(renderView, occluder, flag); } // +0x14, 0x10082D10 - `fld -1.0; retn`. Shared with the base family (fifteen constructors // install the base table this slot comes from). -float __fastcall sm_slot14(void* self, void*) +float RD9_THUNK sm_slot14(void* self RD9_THUNK_EDX) { return static_cast(self)->slot14ReturnsMinusOne(); } // +0x30, 0x1005DA00 - `xor al,al; retn 4`. -bool __fastcall sm_slot30(void* self, void*, int argument) +bool RD9_THUNK sm_slot30(void* self RD9_THUNK_EDX, int argument) { return static_cast(self)->slot30ReturnsFalse(argument); } // +0x3C and +0xC8, 0x10088060 - `xor eax,eax; retn 4`. One body, two slots, one arity. -int __fastcall sm_slot3C(void* self, void*, int argument) +int RD9_THUNK sm_slot3C(void* self RD9_THUNK_EDX, int argument) { return static_cast(self)->slot3CReturnsZero(argument); } // +0x44, the bounding radius. -float __fastcall sm_getBoundingRadius(void* self, void*) +float RD9_THUNK sm_getBoundingRadius(void* self RD9_THUNK_EDX) { return static_cast(self)->getBoundingRadius(); } // +0x48, the transform, or the shared identity. -const Mat4* __fastcall sm_getGeometryTransformation(void* self, void*) +const Mat4* RD9_THUNK sm_getGeometryTransformation(void* self RD9_THUNK_EDX) { return static_cast(self)->getGeometryTransformation(); } // +0x4C, 0x100FB320 - `retn 8`. -void __fastcall sm_setDynamicPartTransformation(void* self, void*, unsigned int part, +void RD9_THUNK sm_setDynamicPartTransformation(void* self RD9_THUNK_EDX, unsigned int part, const Mat4* transform) { static_cast(self)->setDynamicPartTransformation(part, transform); } -void __fastcall sm_setGeometryTransformation(void* self, void*, const Mat4* transform) +void RD9_THUNK sm_setGeometryTransformation(void* self RD9_THUNK_EDX, const Mat4* transform) { static_cast(self)->setGeometryTransformation(transform); } // +0x54, +0x60, +0x94, +0x98 - 0x100E1480, `retn 8`: an empty virtual taking two dwords. The // one body sits in four slots; its arity is its own, so the four adapters are one function. -void __fastcall sm_emptyTwoArgs(void*, void*, unsigned int, unsigned int) +void RD9_THUNK sm_emptyTwoArgs(void* RD9_THUNK_EDX, unsigned int, unsigned int) { } // +0x58, +0x64, +0xB4, +0xD4, +0xDC - 0x100E13B0, `retn 4`: an empty virtual taking one dword. -void __fastcall sm_emptyOneArg(void*, void*, unsigned int) +void RD9_THUNK sm_emptyOneArg(void* RD9_THUNK_EDX, unsigned int) { } // +0x5C, +0xA0, +0xCC - 0x100ED3B0, `xor eax,eax; retn`: zero, no arguments. +0xCC is the // "next geometry in the chain" slot the object walkers follow; see getNextGeometry. -int __fastcall sm_returnsZero(void*, void*) +int RD9_THUNK sm_returnsZero(void* RD9_THUNK_EDX) { return 0; } @@ -214,168 +224,169 @@ int __fastcall sm_returnsZero(void*, void*) // name at +0x04 assigned from the argument. The argument is a VC7.1 std::string in the // shipped image; whether the host ever calls this slot (with its own string layout) is not known - // no recovered host body does - so it is typed as the image types it. -void __fastcall sm_setName(void* self, void*, const vc71::string* value) +void RD9_THUNK sm_setName(void* self RD9_THUNK_EDX, const std::string* value) { static_cast(self)->setName(*value); } // +0x84, 0x100FC010 - `retn 4`. -void __fastcall sm_setMaterialOverride(void* self, void*, int index) +void RD9_THUNK sm_setMaterialOverride(void* self RD9_THUNK_EDX, int index) { static_cast(self)->setMaterialOverride(index); } // +0x8C -int __fastcall sm_getMaterialCount(void* self, void*) +int RD9_THUNK sm_getMaterialCount(void* self RD9_THUNK_EDX) { return static_cast(self)->getMaterialCount(); } // +0x90, 0x10083AB0 - `retn 0Ch`: an empty virtual taking three dwords. -void __fastcall sm_emptyThreeArgs(void*, void*, unsigned int, unsigned int, unsigned int) +void RD9_THUNK sm_emptyThreeArgs(void* RD9_THUNK_EDX, unsigned int, unsigned int, unsigned int) { } // +0xA8, +0xD0, +0xD8 - 0x10083AF0, `xor al,al; retn`: false, no arguments. -bool __fastcall sm_returnsFalse(void*, void*) +bool RD9_THUNK sm_returnsFalse(void* RD9_THUNK_EDX) { return false; } // +0xE8 -int __fastcall sm_getOccluderRecordCount(void* self, void*) +int RD9_THUNK sm_getOccluderRecordCount(void* self RD9_THUNK_EDX) { return static_cast(self)->getOccluderRecordCount(); } // +0xEC, 0x100FC120 - `retn 4`. -const void* __fastcall sm_getOccluderRecord(void* self, void*, unsigned int index) +const void* RD9_THUNK sm_getOccluderRecord(void* self RD9_THUNK_EDX, unsigned int index) { return static_cast(self)->getOccluderRecord(index); } -int __fastcall sm_getNextGeometry(void* self, void*) +int RD9_THUNK sm_getNextGeometry(void* self RD9_THUNK_EDX) { return static_cast(self)->getNextGeometry(); } -void __fastcall sm_setDword28C(void* self, void*, void* value) +void RD9_THUNK sm_setDword28C(void* self RD9_THUNK_EDX, void* value) { static_cast(self)->setDword28C(value); } -void* __fastcall sm_getDword28C(void* self, void*) +void* RD9_THUNK sm_getDword28C(void* self RD9_THUNK_EDX) { return static_cast(self)->getDword28C(); } -void __fastcall sm_setGeom(void* self, void*, int geom) +void RD9_THUNK sm_setGeom(void* self RD9_THUNK_EDX, int geom) { static_cast(self)->setGeom(geom); } -void __fastcall sm_setLod(void* self, void*, int lod) +void RD9_THUNK sm_setLod(void* self RD9_THUNK_EDX, int lod) { static_cast(self)->setLod(lod); } -int __fastcall sm_getGeomCount(void* self, void*) +int RD9_THUNK sm_getGeomCount(void* self RD9_THUNK_EDX) { return static_cast(self)->getGeomCount(); } -int __fastcall sm_getLodCount(void* self, void*) +int RD9_THUNK sm_getLodCount(void* self RD9_THUNK_EDX) { return static_cast(self)->getLodCount(); } -int __fastcall sm_getGeomIndex(void* self, void*) +int RD9_THUNK sm_getGeomIndex(void* self RD9_THUNK_EDX) { return static_cast(self)->getGeomIndex(); } -int __fastcall sm_getLodIndex(void* self, void*) +int RD9_THUNK sm_getLodIndex(void* self RD9_THUNK_EDX) { return static_cast(self)->getLodIndex(); } -int __fastcall sm_getDword31C(void* self, void*) +int RD9_THUNK sm_getDword31C(void* self RD9_THUNK_EDX) { return static_cast(self)->getDword31C(); } -void __fastcall sm_updateFlags(void* self, void*, unsigned int set, unsigned int clear) +void RD9_THUNK sm_updateFlags(void* self RD9_THUNK_EDX, unsigned int set, unsigned int clear) { static_cast(self)->updateFlags(set, clear); } -unsigned int __fastcall sm_getFlags(void* self, void*) +unsigned int RD9_THUNK sm_getFlags(void* self RD9_THUNK_EDX) { return static_cast(self)->getFlags(); } -void __fastcall sm_stampFrameOrdinal(void* self, void*) +void RD9_THUNK sm_stampFrameOrdinal(void* self RD9_THUNK_EDX) { static_cast(self)->stampFrameOrdinal(); } -void __fastcall sm_setDword350(void* self, void*, void* value) +void RD9_THUNK sm_setDword350(void* self RD9_THUNK_EDX, void* value) { static_cast(self)->setDword350(value); } -void* __fastcall sm_getDword350(void* self, void*) +void* RD9_THUNK sm_getDword350(void* self RD9_THUNK_EDX) { return static_cast(self)->getDword350(); } -void __fastcall sm_setOwnerObject(void* self, void*, void* object) +void RD9_THUNK sm_setOwnerObject(void* self RD9_THUNK_EDX, void* object) { static_cast(self)->setOwnerObject(object); } -void* __fastcall sm_refreshRootObject(void* self, void*) +void* RD9_THUNK sm_refreshRootObject(void* self RD9_THUNK_EDX) { return static_cast(self)->refreshRootObject(); } -void __fastcall sm_setFade(void* self, void*, float value) +void RD9_THUNK sm_setFade(void* self RD9_THUNK_EDX, float value) { static_cast(self)->setFade(value); } // the nine accessors -void* __fastcall sm_getTemplate(void* self, void*) +void* RD9_THUNK sm_getTemplate(void* self RD9_THUNK_EDX) { return static_cast(self)->getTemplate(); } -const void* __fastcall sm_getLocalBounds(void* self, void*) +const void* RD9_THUNK sm_getLocalBounds(void* self RD9_THUNK_EDX) { return static_cast(self)->getLocalBounds(); } -void* __fastcall sm_getRootObject(void* self, void*) +void* RD9_THUNK sm_getRootObject(void* self RD9_THUNK_EDX) { return static_cast(self)->getRootObject(); } -void __fastcall sm_setFloat308(void* self, void*, float value) +void RD9_THUNK sm_setFloat308(void* self RD9_THUNK_EDX, float value) { static_cast(self)->setFloat308(value); } -void __fastcall sm_setDword34C(void* self, void*, unsigned int value) +// The +0x24 caller (XpLightManager) passes a LightShadowRecord pointer; pointer-sized on x64. +void RD9_THUNK sm_setDword34C(void* self RD9_THUNK_EDX, uintptr_t value) { static_cast(self)->setDword34C(value); } -unsigned int __fastcall sm_getDword34C(void* self, void*) +uintptr_t RD9_THUNK sm_getDword34C(void* self RD9_THUNK_EDX) { return static_cast(self)->getDword34C(); } -int __fastcall sm_getGeometryType(void* self, void*) +int RD9_THUNK sm_getGeometryType(void* self RD9_THUNK_EDX) { return static_cast(self)->getGeometryType(); } @@ -383,12 +394,12 @@ int __fastcall sm_getGeometryType(void* self, void*) // THE truncation IS THE point. The shipped body compares the low byte of the argument // slot, so 0x100 is false to it and would be true to an `int != 0` test. Taking the raw dword // here and narrowing it is what keeps that. -void __fastcall sm_setFlagBit1(void* self, void*, int raw) +void RD9_THUNK sm_setFlagBit1(void* self RD9_THUNK_EDX, int raw) { static_cast(self)->setFlagBit1(static_cast(raw)); } -bool __fastcall sm_getFlagBit1(void* self, void*) +bool RD9_THUNK sm_getFlagBit1(void* self RD9_THUNK_EDX) { return static_cast(self)->getFlagBit1(); } @@ -461,40 +472,41 @@ void* const kStaticMeshVtable[63] = }; -// Converts the ILightSampleable face at +0x30 to its owning StaticMesh. +// Converts the ILightSampleable face (retail +0x30) to its owning StaticMesh. inline StaticMesh* fromLightSampleable(void* subobject) { - return reinterpret_cast(static_cast(subobject) - 0x30); + return reinterpret_cast(static_cast(subobject) + - offsetof(StaticMesh, m_lightSampleableVptr)); } -int __fastcall sm_ls_addRef(void* self, void*) +int RD9_THUNK sm_ls_addRef(void* self RD9_THUNK_EDX) { return fromLightSampleable(self)->addRef(); } -int __fastcall sm_ls_getRef(void* self, void*) +int RD9_THUNK sm_ls_getRef(void* self RD9_THUNK_EDX) { return fromLightSampleable(self)->getRef(); } -int __fastcall sm_ls_release(void* self, void*) +int RD9_THUNK sm_ls_release(void* self RD9_THUNK_EDX) { return fromLightSampleable(self)->release(); } -void* __fastcall sm_ls_queryInterface(void* self, void*, unsigned int iid) +void* RD9_THUNK sm_ls_queryInterface(void* self RD9_THUNK_EDX, unsigned int iid) { return fromLightSampleable(self)->queryInterface(iid); } -bool __fastcall sm_ls_slot10(void* self, void*) +bool RD9_THUNK sm_ls_slot10(void* self RD9_THUNK_EDX) { return fromLightSampleable(self)->lightSampleableSlot10ReturnsTrue(); } // Defined below with the other name builders. -void staticMeshLightmapName(const StaticMesh* self, vc71::string& out); +void staticMeshLightmapName(const StaticMesh* self, std::string& out); // ILightSampleable +0x14: a MeshLightSampler for the current (geom, lod), loaded from // "